floating-ui.js 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775
  1. /*!
  2. * All material copyright ESRI, All Rights Reserved, unless otherwise specified.
  3. * See https://github.com/Esri/calcite-components/blob/master/LICENSE.md for details.
  4. * v1.0.0-beta.97
  5. */
  6. import { c as getElementDir, o as closestElementCrossShadowBoundary } from './dom.js';
  7. import { Build } from '@stencil/core/internal/client/index.js';
  8. import { d as debounce } from './debounce.js';
  9. function getSide(placement) {
  10. return placement.split('-')[0];
  11. }
  12. function getAlignment(placement) {
  13. return placement.split('-')[1];
  14. }
  15. function getMainAxisFromPlacement(placement) {
  16. return ['top', 'bottom'].includes(getSide(placement)) ? 'x' : 'y';
  17. }
  18. function getLengthFromAxis(axis) {
  19. return axis === 'y' ? 'height' : 'width';
  20. }
  21. function computeCoordsFromPlacement(_ref, placement, rtl) {
  22. let {
  23. reference,
  24. floating
  25. } = _ref;
  26. const commonX = reference.x + reference.width / 2 - floating.width / 2;
  27. const commonY = reference.y + reference.height / 2 - floating.height / 2;
  28. const mainAxis = getMainAxisFromPlacement(placement);
  29. const length = getLengthFromAxis(mainAxis);
  30. const commonAlign = reference[length] / 2 - floating[length] / 2;
  31. const side = getSide(placement);
  32. const isVertical = mainAxis === 'x';
  33. let coords;
  34. switch (side) {
  35. case 'top':
  36. coords = {
  37. x: commonX,
  38. y: reference.y - floating.height
  39. };
  40. break;
  41. case 'bottom':
  42. coords = {
  43. x: commonX,
  44. y: reference.y + reference.height
  45. };
  46. break;
  47. case 'right':
  48. coords = {
  49. x: reference.x + reference.width,
  50. y: commonY
  51. };
  52. break;
  53. case 'left':
  54. coords = {
  55. x: reference.x - floating.width,
  56. y: commonY
  57. };
  58. break;
  59. default:
  60. coords = {
  61. x: reference.x,
  62. y: reference.y
  63. };
  64. }
  65. switch (getAlignment(placement)) {
  66. case 'start':
  67. coords[mainAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);
  68. break;
  69. case 'end':
  70. coords[mainAxis] += commonAlign * (rtl && isVertical ? -1 : 1);
  71. break;
  72. }
  73. return coords;
  74. }
  75. /**
  76. * Computes the `x` and `y` coordinates that will place the floating element
  77. * next to a reference element when it is given a certain positioning strategy.
  78. *
  79. * This export does not have any `platform` interface logic. You will need to
  80. * write one for the platform you are using Floating UI with.
  81. */
  82. const computePosition$1 = async (reference, floating, config) => {
  83. const {
  84. placement = 'bottom',
  85. strategy = 'absolute',
  86. middleware = [],
  87. platform
  88. } = config;
  89. const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating));
  90. let rects = await platform.getElementRects({
  91. reference,
  92. floating,
  93. strategy
  94. });
  95. let {
  96. x,
  97. y
  98. } = computeCoordsFromPlacement(rects, placement, rtl);
  99. let statefulPlacement = placement;
  100. let middlewareData = {};
  101. let resetCount = 0;
  102. for (let i = 0; i < middleware.length; i++) {
  103. const {
  104. name,
  105. fn
  106. } = middleware[i];
  107. const {
  108. x: nextX,
  109. y: nextY,
  110. data,
  111. reset
  112. } = await fn({
  113. x,
  114. y,
  115. initialPlacement: placement,
  116. placement: statefulPlacement,
  117. strategy,
  118. middlewareData,
  119. rects,
  120. platform,
  121. elements: {
  122. reference,
  123. floating
  124. }
  125. });
  126. x = nextX != null ? nextX : x;
  127. y = nextY != null ? nextY : y;
  128. middlewareData = { ...middlewareData,
  129. [name]: { ...middlewareData[name],
  130. ...data
  131. }
  132. };
  133. if (reset && resetCount <= 50) {
  134. resetCount++;
  135. if (typeof reset === 'object') {
  136. if (reset.placement) {
  137. statefulPlacement = reset.placement;
  138. }
  139. if (reset.rects) {
  140. rects = reset.rects === true ? await platform.getElementRects({
  141. reference,
  142. floating,
  143. strategy
  144. }) : reset.rects;
  145. }
  146. ({
  147. x,
  148. y
  149. } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));
  150. }
  151. i = -1;
  152. continue;
  153. }
  154. }
  155. return {
  156. x,
  157. y,
  158. placement: statefulPlacement,
  159. strategy,
  160. middlewareData
  161. };
  162. };
  163. function expandPaddingObject(padding) {
  164. return {
  165. top: 0,
  166. right: 0,
  167. bottom: 0,
  168. left: 0,
  169. ...padding
  170. };
  171. }
  172. function getSideObjectFromPadding(padding) {
  173. return typeof padding !== 'number' ? expandPaddingObject(padding) : {
  174. top: padding,
  175. right: padding,
  176. bottom: padding,
  177. left: padding
  178. };
  179. }
  180. function rectToClientRect(rect) {
  181. return { ...rect,
  182. top: rect.y,
  183. left: rect.x,
  184. right: rect.x + rect.width,
  185. bottom: rect.y + rect.height
  186. };
  187. }
  188. /**
  189. * Resolves with an object of overflow side offsets that determine how much the
  190. * element is overflowing a given clipping boundary.
  191. * - positive = overflowing the boundary by that number of pixels
  192. * - negative = how many pixels left before it will overflow
  193. * - 0 = lies flush with the boundary
  194. * @see https://floating-ui.com/docs/detectOverflow
  195. */
  196. async function detectOverflow(middlewareArguments, options) {
  197. var _await$platform$isEle;
  198. if (options === void 0) {
  199. options = {};
  200. }
  201. const {
  202. x,
  203. y,
  204. platform,
  205. rects,
  206. elements,
  207. strategy
  208. } = middlewareArguments;
  209. const {
  210. boundary = 'clippingAncestors',
  211. rootBoundary = 'viewport',
  212. elementContext = 'floating',
  213. altBoundary = false,
  214. padding = 0
  215. } = options;
  216. const paddingObject = getSideObjectFromPadding(padding);
  217. const altContext = elementContext === 'floating' ? 'reference' : 'floating';
  218. const element = elements[altBoundary ? altContext : elementContext];
  219. const clippingClientRect = rectToClientRect(await platform.getClippingRect({
  220. element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))),
  221. boundary,
  222. rootBoundary,
  223. strategy
  224. }));
  225. const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({
  226. rect: elementContext === 'floating' ? { ...rects.floating,
  227. x,
  228. y
  229. } : rects.reference,
  230. offsetParent: await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating)),
  231. strategy
  232. }) : rects[elementContext]);
  233. return {
  234. top: clippingClientRect.top - elementClientRect.top + paddingObject.top,
  235. bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,
  236. left: clippingClientRect.left - elementClientRect.left + paddingObject.left,
  237. right: elementClientRect.right - clippingClientRect.right + paddingObject.right
  238. };
  239. }
  240. const min$1 = Math.min;
  241. const max$1 = Math.max;
  242. function within(min$1$1, value, max$1$1) {
  243. return max$1(min$1$1, min$1(value, max$1$1));
  244. }
  245. /**
  246. * Positions an inner element of the floating element such that it is centered
  247. * to the reference element.
  248. * @see https://floating-ui.com/docs/arrow
  249. */
  250. const arrow = options => ({
  251. name: 'arrow',
  252. options,
  253. async fn(middlewareArguments) {
  254. // Since `element` is required, we don't Partial<> the type
  255. const {
  256. element,
  257. padding = 0
  258. } = options != null ? options : {};
  259. const {
  260. x,
  261. y,
  262. placement,
  263. rects,
  264. platform
  265. } = middlewareArguments;
  266. if (element == null) {
  267. return {};
  268. }
  269. const paddingObject = getSideObjectFromPadding(padding);
  270. const coords = {
  271. x,
  272. y
  273. };
  274. const axis = getMainAxisFromPlacement(placement);
  275. const alignment = getAlignment(placement);
  276. const length = getLengthFromAxis(axis);
  277. const arrowDimensions = await platform.getDimensions(element);
  278. const minProp = axis === 'y' ? 'top' : 'left';
  279. const maxProp = axis === 'y' ? 'bottom' : 'right';
  280. const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length];
  281. const startDiff = coords[axis] - rects.reference[axis];
  282. const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element));
  283. let clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
  284. if (clientSize === 0) {
  285. clientSize = rects.floating[length];
  286. }
  287. const centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the floating element if the center
  288. // point is outside the floating element's bounds
  289. const min = paddingObject[minProp];
  290. const max = clientSize - arrowDimensions[length] - paddingObject[maxProp];
  291. const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference;
  292. const offset = within(min, center, max); // Make sure that arrow points at the reference
  293. const alignmentPadding = alignment === 'start' ? paddingObject[minProp] : paddingObject[maxProp];
  294. const shouldAddOffset = alignmentPadding > 0 && center !== offset && rects.reference[length] <= rects.floating[length];
  295. const alignmentOffset = shouldAddOffset ? center < min ? min - center : max - center : 0;
  296. return {
  297. [axis]: coords[axis] - alignmentOffset,
  298. data: {
  299. [axis]: offset,
  300. centerOffset: center - offset
  301. }
  302. };
  303. }
  304. });
  305. const hash$1 = {
  306. left: 'right',
  307. right: 'left',
  308. bottom: 'top',
  309. top: 'bottom'
  310. };
  311. function getOppositePlacement(placement) {
  312. return placement.replace(/left|right|bottom|top/g, matched => hash$1[matched]);
  313. }
  314. function getAlignmentSides(placement, rects, rtl) {
  315. if (rtl === void 0) {
  316. rtl = false;
  317. }
  318. const alignment = getAlignment(placement);
  319. const mainAxis = getMainAxisFromPlacement(placement);
  320. const length = getLengthFromAxis(mainAxis);
  321. let mainAlignmentSide = mainAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top';
  322. if (rects.reference[length] > rects.floating[length]) {
  323. mainAlignmentSide = getOppositePlacement(mainAlignmentSide);
  324. }
  325. return {
  326. main: mainAlignmentSide,
  327. cross: getOppositePlacement(mainAlignmentSide)
  328. };
  329. }
  330. const hash = {
  331. start: 'end',
  332. end: 'start'
  333. };
  334. function getOppositeAlignmentPlacement(placement) {
  335. return placement.replace(/start|end/g, matched => hash[matched]);
  336. }
  337. const sides = ['top', 'right', 'bottom', 'left'];
  338. const allPlacements = /*#__PURE__*/sides.reduce((acc, side) => acc.concat(side, side + "-start", side + "-end"), []);
  339. function getPlacementList(alignment, autoAlignment, allowedPlacements) {
  340. const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement);
  341. return allowedPlacementsSortedByAlignment.filter(placement => {
  342. if (alignment) {
  343. return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false);
  344. }
  345. return true;
  346. });
  347. }
  348. /**
  349. * Automatically chooses the `placement` which has the most space available.
  350. * @see https://floating-ui.com/docs/autoPlacement
  351. */
  352. const autoPlacement = function (options) {
  353. if (options === void 0) {
  354. options = {};
  355. }
  356. return {
  357. name: 'autoPlacement',
  358. options,
  359. async fn(middlewareArguments) {
  360. var _middlewareData$autoP, _middlewareData$autoP2, _middlewareData$autoP3, _middlewareData$autoP4, _placementsSortedByLe;
  361. const {
  362. x,
  363. y,
  364. rects,
  365. middlewareData,
  366. placement,
  367. platform,
  368. elements
  369. } = middlewareArguments;
  370. const {
  371. alignment = null,
  372. allowedPlacements = allPlacements,
  373. autoAlignment = true,
  374. ...detectOverflowOptions
  375. } = options;
  376. const placements = getPlacementList(alignment, autoAlignment, allowedPlacements);
  377. const overflow = await detectOverflow(middlewareArguments, detectOverflowOptions);
  378. const currentIndex = (_middlewareData$autoP = (_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.index) != null ? _middlewareData$autoP : 0;
  379. const currentPlacement = placements[currentIndex];
  380. if (currentPlacement == null) {
  381. return {};
  382. }
  383. const {
  384. main,
  385. cross
  386. } = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))); // Make `computeCoords` start from the right place
  387. if (placement !== currentPlacement) {
  388. return {
  389. x,
  390. y,
  391. reset: {
  392. placement: placements[0]
  393. }
  394. };
  395. }
  396. const currentOverflows = [overflow[getSide(currentPlacement)], overflow[main], overflow[cross]];
  397. const allOverflows = [...((_middlewareData$autoP3 = (_middlewareData$autoP4 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP4.overflows) != null ? _middlewareData$autoP3 : []), {
  398. placement: currentPlacement,
  399. overflows: currentOverflows
  400. }];
  401. const nextPlacement = placements[currentIndex + 1]; // There are more placements to check
  402. if (nextPlacement) {
  403. return {
  404. data: {
  405. index: currentIndex + 1,
  406. overflows: allOverflows
  407. },
  408. reset: {
  409. placement: nextPlacement
  410. }
  411. };
  412. }
  413. const placementsSortedByLeastOverflow = allOverflows.slice().sort((a, b) => a.overflows[0] - b.overflows[0]);
  414. const placementThatFitsOnAllSides = (_placementsSortedByLe = placementsSortedByLeastOverflow.find(_ref => {
  415. let {
  416. overflows
  417. } = _ref;
  418. return overflows.every(overflow => overflow <= 0);
  419. })) == null ? void 0 : _placementsSortedByLe.placement;
  420. const resetPlacement = placementThatFitsOnAllSides != null ? placementThatFitsOnAllSides : placementsSortedByLeastOverflow[0].placement;
  421. if (resetPlacement !== placement) {
  422. return {
  423. data: {
  424. index: currentIndex + 1,
  425. overflows: allOverflows
  426. },
  427. reset: {
  428. placement: resetPlacement
  429. }
  430. };
  431. }
  432. return {};
  433. }
  434. };
  435. };
  436. function getExpandedPlacements(placement) {
  437. const oppositePlacement = getOppositePlacement(placement);
  438. return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];
  439. }
  440. /**
  441. * Changes the placement of the floating element to one that will fit if the
  442. * initially specified `placement` does not.
  443. * @see https://floating-ui.com/docs/flip
  444. */
  445. const flip = function (options) {
  446. if (options === void 0) {
  447. options = {};
  448. }
  449. return {
  450. name: 'flip',
  451. options,
  452. async fn(middlewareArguments) {
  453. var _middlewareData$flip;
  454. const {
  455. placement,
  456. middlewareData,
  457. rects,
  458. initialPlacement,
  459. platform,
  460. elements
  461. } = middlewareArguments;
  462. const {
  463. mainAxis: checkMainAxis = true,
  464. crossAxis: checkCrossAxis = true,
  465. fallbackPlacements: specifiedFallbackPlacements,
  466. fallbackStrategy = 'bestFit',
  467. flipAlignment = true,
  468. ...detectOverflowOptions
  469. } = options;
  470. const side = getSide(placement);
  471. const isBasePlacement = side === initialPlacement;
  472. const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));
  473. const placements = [initialPlacement, ...fallbackPlacements];
  474. const overflow = await detectOverflow(middlewareArguments, detectOverflowOptions);
  475. const overflows = [];
  476. let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];
  477. if (checkMainAxis) {
  478. overflows.push(overflow[side]);
  479. }
  480. if (checkCrossAxis) {
  481. const {
  482. main,
  483. cross
  484. } = getAlignmentSides(placement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)));
  485. overflows.push(overflow[main], overflow[cross]);
  486. }
  487. overflowsData = [...overflowsData, {
  488. placement,
  489. overflows
  490. }]; // One or more sides is overflowing
  491. if (!overflows.every(side => side <= 0)) {
  492. var _middlewareData$flip$, _middlewareData$flip2;
  493. const nextIndex = ((_middlewareData$flip$ = (_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) != null ? _middlewareData$flip$ : 0) + 1;
  494. const nextPlacement = placements[nextIndex];
  495. if (nextPlacement) {
  496. // Try next placement and re-run the lifecycle
  497. return {
  498. data: {
  499. index: nextIndex,
  500. overflows: overflowsData
  501. },
  502. reset: {
  503. placement: nextPlacement
  504. }
  505. };
  506. }
  507. let resetPlacement = 'bottom';
  508. switch (fallbackStrategy) {
  509. case 'bestFit':
  510. {
  511. var _overflowsData$map$so;
  512. const placement = (_overflowsData$map$so = overflowsData.map(d => [d, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$map$so[0].placement;
  513. if (placement) {
  514. resetPlacement = placement;
  515. }
  516. break;
  517. }
  518. case 'initialPlacement':
  519. resetPlacement = initialPlacement;
  520. break;
  521. }
  522. if (placement !== resetPlacement) {
  523. return {
  524. reset: {
  525. placement: resetPlacement
  526. }
  527. };
  528. }
  529. }
  530. return {};
  531. }
  532. };
  533. };
  534. function getSideOffsets(overflow, rect) {
  535. return {
  536. top: overflow.top - rect.height,
  537. right: overflow.right - rect.width,
  538. bottom: overflow.bottom - rect.height,
  539. left: overflow.left - rect.width
  540. };
  541. }
  542. function isAnySideFullyClipped(overflow) {
  543. return sides.some(side => overflow[side] >= 0);
  544. }
  545. /**
  546. * Provides data to hide the floating element in applicable situations, such as
  547. * when it is not in the same clipping context as the reference element.
  548. * @see https://floating-ui.com/docs/hide
  549. */
  550. const hide = function (_temp) {
  551. let {
  552. strategy = 'referenceHidden',
  553. ...detectOverflowOptions
  554. } = _temp === void 0 ? {} : _temp;
  555. return {
  556. name: 'hide',
  557. async fn(middlewareArguments) {
  558. const {
  559. rects
  560. } = middlewareArguments;
  561. switch (strategy) {
  562. case 'referenceHidden':
  563. {
  564. const overflow = await detectOverflow(middlewareArguments, { ...detectOverflowOptions,
  565. elementContext: 'reference'
  566. });
  567. const offsets = getSideOffsets(overflow, rects.reference);
  568. return {
  569. data: {
  570. referenceHiddenOffsets: offsets,
  571. referenceHidden: isAnySideFullyClipped(offsets)
  572. }
  573. };
  574. }
  575. case 'escaped':
  576. {
  577. const overflow = await detectOverflow(middlewareArguments, { ...detectOverflowOptions,
  578. altBoundary: true
  579. });
  580. const offsets = getSideOffsets(overflow, rects.floating);
  581. return {
  582. data: {
  583. escapedOffsets: offsets,
  584. escaped: isAnySideFullyClipped(offsets)
  585. }
  586. };
  587. }
  588. default:
  589. {
  590. return {};
  591. }
  592. }
  593. }
  594. };
  595. };
  596. async function convertValueToCoords(middlewareArguments, value) {
  597. const {
  598. placement,
  599. platform,
  600. elements
  601. } = middlewareArguments;
  602. const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));
  603. const side = getSide(placement);
  604. const alignment = getAlignment(placement);
  605. const isVertical = getMainAxisFromPlacement(placement) === 'x';
  606. const mainAxisMulti = ['left', 'top'].includes(side) ? -1 : 1;
  607. const crossAxisMulti = rtl && isVertical ? -1 : 1;
  608. const rawValue = typeof value === 'function' ? value(middlewareArguments) : value; // eslint-disable-next-line prefer-const
  609. let {
  610. mainAxis,
  611. crossAxis,
  612. alignmentAxis
  613. } = typeof rawValue === 'number' ? {
  614. mainAxis: rawValue,
  615. crossAxis: 0,
  616. alignmentAxis: null
  617. } : {
  618. mainAxis: 0,
  619. crossAxis: 0,
  620. alignmentAxis: null,
  621. ...rawValue
  622. };
  623. if (alignment && typeof alignmentAxis === 'number') {
  624. crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis;
  625. }
  626. return isVertical ? {
  627. x: crossAxis * crossAxisMulti,
  628. y: mainAxis * mainAxisMulti
  629. } : {
  630. x: mainAxis * mainAxisMulti,
  631. y: crossAxis * crossAxisMulti
  632. };
  633. }
  634. /**
  635. * Displaces the floating element from its reference element.
  636. * @see https://floating-ui.com/docs/offset
  637. */
  638. const offset = function (value) {
  639. if (value === void 0) {
  640. value = 0;
  641. }
  642. return {
  643. name: 'offset',
  644. options: value,
  645. async fn(middlewareArguments) {
  646. const {
  647. x,
  648. y
  649. } = middlewareArguments;
  650. const diffCoords = await convertValueToCoords(middlewareArguments, value);
  651. return {
  652. x: x + diffCoords.x,
  653. y: y + diffCoords.y,
  654. data: diffCoords
  655. };
  656. }
  657. };
  658. };
  659. function getCrossAxis(axis) {
  660. return axis === 'x' ? 'y' : 'x';
  661. }
  662. /**
  663. * Shifts the floating element in order to keep it in view when it will overflow
  664. * a clipping boundary.
  665. * @see https://floating-ui.com/docs/shift
  666. */
  667. const shift = function (options) {
  668. if (options === void 0) {
  669. options = {};
  670. }
  671. return {
  672. name: 'shift',
  673. options,
  674. async fn(middlewareArguments) {
  675. const {
  676. x,
  677. y,
  678. placement
  679. } = middlewareArguments;
  680. const {
  681. mainAxis: checkMainAxis = true,
  682. crossAxis: checkCrossAxis = false,
  683. limiter = {
  684. fn: _ref => {
  685. let {
  686. x,
  687. y
  688. } = _ref;
  689. return {
  690. x,
  691. y
  692. };
  693. }
  694. },
  695. ...detectOverflowOptions
  696. } = options;
  697. const coords = {
  698. x,
  699. y
  700. };
  701. const overflow = await detectOverflow(middlewareArguments, detectOverflowOptions);
  702. const mainAxis = getMainAxisFromPlacement(getSide(placement));
  703. const crossAxis = getCrossAxis(mainAxis);
  704. let mainAxisCoord = coords[mainAxis];
  705. let crossAxisCoord = coords[crossAxis];
  706. if (checkMainAxis) {
  707. const minSide = mainAxis === 'y' ? 'top' : 'left';
  708. const maxSide = mainAxis === 'y' ? 'bottom' : 'right';
  709. const min = mainAxisCoord + overflow[minSide];
  710. const max = mainAxisCoord - overflow[maxSide];
  711. mainAxisCoord = within(min, mainAxisCoord, max);
  712. }
  713. if (checkCrossAxis) {
  714. const minSide = crossAxis === 'y' ? 'top' : 'left';
  715. const maxSide = crossAxis === 'y' ? 'bottom' : 'right';
  716. const min = crossAxisCoord + overflow[minSide];
  717. const max = crossAxisCoord - overflow[maxSide];
  718. crossAxisCoord = within(min, crossAxisCoord, max);
  719. }
  720. const limitedCoords = limiter.fn({ ...middlewareArguments,
  721. [mainAxis]: mainAxisCoord,
  722. [crossAxis]: crossAxisCoord
  723. });
  724. return { ...limitedCoords,
  725. data: {
  726. x: limitedCoords.x - x,
  727. y: limitedCoords.y - y
  728. }
  729. };
  730. }
  731. };
  732. };
  733. function isWindow(value) {
  734. return value && value.document && value.location && value.alert && value.setInterval;
  735. }
  736. function getWindow(node) {
  737. if (node == null) {
  738. return window;
  739. }
  740. if (!isWindow(node)) {
  741. const ownerDocument = node.ownerDocument;
  742. return ownerDocument ? ownerDocument.defaultView || window : window;
  743. }
  744. return node;
  745. }
  746. function getComputedStyle(element) {
  747. return getWindow(element).getComputedStyle(element);
  748. }
  749. function getNodeName(node) {
  750. return isWindow(node) ? '' : node ? (node.nodeName || '').toLowerCase() : '';
  751. }
  752. function getUAString() {
  753. const uaData = navigator.userAgentData;
  754. if (uaData != null && uaData.brands) {
  755. return uaData.brands.map(item => item.brand + "/" + item.version).join(' ');
  756. }
  757. return navigator.userAgent;
  758. }
  759. function isHTMLElement(value) {
  760. return value instanceof getWindow(value).HTMLElement;
  761. }
  762. function isElement(value) {
  763. return value instanceof getWindow(value).Element;
  764. }
  765. function isNode(value) {
  766. return value instanceof getWindow(value).Node;
  767. }
  768. function isShadowRoot(node) {
  769. // Browsers without `ShadowRoot` support
  770. if (typeof ShadowRoot === 'undefined') {
  771. return false;
  772. }
  773. const OwnElement = getWindow(node).ShadowRoot;
  774. return node instanceof OwnElement || node instanceof ShadowRoot;
  775. }
  776. function isOverflowElement(element) {
  777. // Firefox wants us to check `-x` and `-y` variations as well
  778. const {
  779. overflow,
  780. overflowX,
  781. overflowY,
  782. display
  783. } = getComputedStyle(element);
  784. return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX) && !['inline', 'contents'].includes(display);
  785. }
  786. function isTableElement(element) {
  787. return ['table', 'td', 'th'].includes(getNodeName(element));
  788. }
  789. function isContainingBlock(element) {
  790. // TODO: Try and use feature detection here instead
  791. const isFirefox = /firefox/i.test(getUAString());
  792. const css = getComputedStyle(element); // This is non-exhaustive but covers the most common CSS properties that
  793. // create a containing block.
  794. // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
  795. return css.transform !== 'none' || css.perspective !== 'none' || isFirefox && css.willChange === 'filter' || isFirefox && (css.filter ? css.filter !== 'none' : false) || ['transform', 'perspective'].some(value => css.willChange.includes(value)) || ['paint', 'layout', 'strict', 'content'].some( // TS 4.1 compat
  796. value => {
  797. const contain = css.contain;
  798. return contain != null ? contain.includes(value) : false;
  799. });
  800. }
  801. function isLayoutViewport() {
  802. // Not Safari
  803. return !/^((?!chrome|android).)*safari/i.test(getUAString()); // Feature detection for this fails in various ways
  804. // • Always-visible scrollbar or not
  805. // • Width of <html>, etc.
  806. // const vV = win.visualViewport;
  807. // return vV ? Math.abs(win.innerWidth / vV.scale - vV.width) < 0.5 : true;
  808. }
  809. function isLastTraversableNode(node) {
  810. return ['html', 'body', '#document'].includes(getNodeName(node));
  811. }
  812. const min = Math.min;
  813. const max = Math.max;
  814. const round = Math.round;
  815. function getBoundingClientRect(element, includeScale, isFixedStrategy) {
  816. var _win$visualViewport$o, _win$visualViewport, _win$visualViewport$o2, _win$visualViewport2;
  817. if (includeScale === void 0) {
  818. includeScale = false;
  819. }
  820. if (isFixedStrategy === void 0) {
  821. isFixedStrategy = false;
  822. }
  823. const clientRect = element.getBoundingClientRect();
  824. let scaleX = 1;
  825. let scaleY = 1;
  826. if (includeScale && isHTMLElement(element)) {
  827. scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1;
  828. scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1;
  829. }
  830. const win = isElement(element) ? getWindow(element) : window;
  831. const addVisualOffsets = !isLayoutViewport() && isFixedStrategy;
  832. const x = (clientRect.left + (addVisualOffsets ? (_win$visualViewport$o = (_win$visualViewport = win.visualViewport) == null ? void 0 : _win$visualViewport.offsetLeft) != null ? _win$visualViewport$o : 0 : 0)) / scaleX;
  833. const y = (clientRect.top + (addVisualOffsets ? (_win$visualViewport$o2 = (_win$visualViewport2 = win.visualViewport) == null ? void 0 : _win$visualViewport2.offsetTop) != null ? _win$visualViewport$o2 : 0 : 0)) / scaleY;
  834. const width = clientRect.width / scaleX;
  835. const height = clientRect.height / scaleY;
  836. return {
  837. width,
  838. height,
  839. top: y,
  840. right: x + width,
  841. bottom: y + height,
  842. left: x,
  843. x,
  844. y
  845. };
  846. }
  847. function getDocumentElement(node) {
  848. return ((isNode(node) ? node.ownerDocument : node.document) || window.document).documentElement;
  849. }
  850. function getNodeScroll(element) {
  851. if (isElement(element)) {
  852. return {
  853. scrollLeft: element.scrollLeft,
  854. scrollTop: element.scrollTop
  855. };
  856. }
  857. return {
  858. scrollLeft: element.pageXOffset,
  859. scrollTop: element.pageYOffset
  860. };
  861. }
  862. function getWindowScrollBarX(element) {
  863. // If <html> has a CSS width greater than the viewport, then this will be
  864. // incorrect for RTL.
  865. return getBoundingClientRect(getDocumentElement(element)).left + getNodeScroll(element).scrollLeft;
  866. }
  867. function isScaled(element) {
  868. const rect = getBoundingClientRect(element);
  869. return round(rect.width) !== element.offsetWidth || round(rect.height) !== element.offsetHeight;
  870. }
  871. function getRectRelativeToOffsetParent(element, offsetParent, strategy) {
  872. const isOffsetParentAnElement = isHTMLElement(offsetParent);
  873. const documentElement = getDocumentElement(offsetParent);
  874. const rect = getBoundingClientRect(element, // @ts-ignore - checked above (TS 4.1 compat)
  875. isOffsetParentAnElement && isScaled(offsetParent), strategy === 'fixed');
  876. let scroll = {
  877. scrollLeft: 0,
  878. scrollTop: 0
  879. };
  880. const offsets = {
  881. x: 0,
  882. y: 0
  883. };
  884. if (isOffsetParentAnElement || !isOffsetParentAnElement && strategy !== 'fixed') {
  885. if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {
  886. scroll = getNodeScroll(offsetParent);
  887. }
  888. if (isHTMLElement(offsetParent)) {
  889. const offsetRect = getBoundingClientRect(offsetParent, true);
  890. offsets.x = offsetRect.x + offsetParent.clientLeft;
  891. offsets.y = offsetRect.y + offsetParent.clientTop;
  892. } else if (documentElement) {
  893. offsets.x = getWindowScrollBarX(documentElement);
  894. }
  895. }
  896. return {
  897. x: rect.left + scroll.scrollLeft - offsets.x,
  898. y: rect.top + scroll.scrollTop - offsets.y,
  899. width: rect.width,
  900. height: rect.height
  901. };
  902. }
  903. function getParentNode(node) {
  904. if (getNodeName(node) === 'html') {
  905. return node;
  906. }
  907. return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle
  908. // @ts-ignore
  909. node.assignedSlot || // step into the shadow DOM of the parent of a slotted node
  910. node.parentNode || ( // DOM Element detected
  911. isShadowRoot(node) ? node.host : null) || // ShadowRoot detected
  912. getDocumentElement(node) // fallback
  913. );
  914. }
  915. function getTrueOffsetParent(element) {
  916. if (!isHTMLElement(element) || getComputedStyle(element).position === 'fixed') {
  917. return null;
  918. }
  919. return element.offsetParent;
  920. }
  921. function getContainingBlock(element) {
  922. let currentNode = getParentNode(element);
  923. if (isShadowRoot(currentNode)) {
  924. currentNode = currentNode.host;
  925. }
  926. while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {
  927. if (isContainingBlock(currentNode)) {
  928. return currentNode;
  929. } else {
  930. const parent = currentNode.parentNode;
  931. currentNode = isShadowRoot(parent) ? parent.host : parent;
  932. }
  933. }
  934. return null;
  935. } // Gets the closest ancestor positioned element. Handles some edge cases,
  936. // such as table ancestors and cross browser bugs.
  937. function getOffsetParent(element) {
  938. const window = getWindow(element);
  939. let offsetParent = getTrueOffsetParent(element);
  940. while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === 'static') {
  941. offsetParent = getTrueOffsetParent(offsetParent);
  942. }
  943. if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle(offsetParent).position === 'static' && !isContainingBlock(offsetParent))) {
  944. return window;
  945. }
  946. return offsetParent || getContainingBlock(element) || window;
  947. }
  948. function getDimensions(element) {
  949. if (isHTMLElement(element)) {
  950. return {
  951. width: element.offsetWidth,
  952. height: element.offsetHeight
  953. };
  954. }
  955. const rect = getBoundingClientRect(element);
  956. return {
  957. width: rect.width,
  958. height: rect.height
  959. };
  960. }
  961. function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {
  962. let {
  963. rect,
  964. offsetParent,
  965. strategy
  966. } = _ref;
  967. const isOffsetParentAnElement = isHTMLElement(offsetParent);
  968. const documentElement = getDocumentElement(offsetParent);
  969. if (offsetParent === documentElement) {
  970. return rect;
  971. }
  972. let scroll = {
  973. scrollLeft: 0,
  974. scrollTop: 0
  975. };
  976. const offsets = {
  977. x: 0,
  978. y: 0
  979. };
  980. if (isOffsetParentAnElement || !isOffsetParentAnElement && strategy !== 'fixed') {
  981. if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {
  982. scroll = getNodeScroll(offsetParent);
  983. }
  984. if (isHTMLElement(offsetParent)) {
  985. const offsetRect = getBoundingClientRect(offsetParent, true);
  986. offsets.x = offsetRect.x + offsetParent.clientLeft;
  987. offsets.y = offsetRect.y + offsetParent.clientTop;
  988. } // This doesn't appear to be need to be negated.
  989. // else if (documentElement) {
  990. // offsets.x = getWindowScrollBarX(documentElement);
  991. // }
  992. }
  993. return { ...rect,
  994. x: rect.x - scroll.scrollLeft + offsets.x,
  995. y: rect.y - scroll.scrollTop + offsets.y
  996. };
  997. }
  998. function getViewportRect(element, strategy) {
  999. const win = getWindow(element);
  1000. const html = getDocumentElement(element);
  1001. const visualViewport = win.visualViewport;
  1002. let width = html.clientWidth;
  1003. let height = html.clientHeight;
  1004. let x = 0;
  1005. let y = 0;
  1006. if (visualViewport) {
  1007. width = visualViewport.width;
  1008. height = visualViewport.height;
  1009. const layoutViewport = isLayoutViewport();
  1010. if (layoutViewport || !layoutViewport && strategy === 'fixed') {
  1011. x = visualViewport.offsetLeft;
  1012. y = visualViewport.offsetTop;
  1013. }
  1014. }
  1015. return {
  1016. width,
  1017. height,
  1018. x,
  1019. y
  1020. };
  1021. }
  1022. // of the `<html>` and `<body>` rect bounds if horizontally scrollable
  1023. function getDocumentRect(element) {
  1024. var _element$ownerDocumen;
  1025. const html = getDocumentElement(element);
  1026. const scroll = getNodeScroll(element);
  1027. const body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;
  1028. const width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
  1029. const height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
  1030. let x = -scroll.scrollLeft + getWindowScrollBarX(element);
  1031. const y = -scroll.scrollTop;
  1032. if (getComputedStyle(body || html).direction === 'rtl') {
  1033. x += max(html.clientWidth, body ? body.clientWidth : 0) - width;
  1034. }
  1035. return {
  1036. width,
  1037. height,
  1038. x,
  1039. y
  1040. };
  1041. }
  1042. function getNearestOverflowAncestor(node) {
  1043. const parentNode = getParentNode(node);
  1044. if (isLastTraversableNode(parentNode)) {
  1045. // @ts-ignore assume body is always available
  1046. return node.ownerDocument.body;
  1047. }
  1048. if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {
  1049. return parentNode;
  1050. }
  1051. return getNearestOverflowAncestor(parentNode);
  1052. }
  1053. function getOverflowAncestors(node, list) {
  1054. var _node$ownerDocument;
  1055. if (list === void 0) {
  1056. list = [];
  1057. }
  1058. const scrollableAncestor = getNearestOverflowAncestor(node);
  1059. const isBody = scrollableAncestor === ((_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.body);
  1060. const win = getWindow(scrollableAncestor);
  1061. const target = isBody ? [win].concat(win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : []) : scrollableAncestor;
  1062. const updatedList = list.concat(target);
  1063. return isBody ? updatedList : // @ts-ignore: isBody tells us target will be an HTMLElement here
  1064. updatedList.concat(getOverflowAncestors(target));
  1065. }
  1066. function contains(parent, child) {
  1067. const rootNode = child.getRootNode == null ? void 0 : child.getRootNode(); // First, attempt with faster native method
  1068. if (parent.contains(child)) {
  1069. return true;
  1070. } // then fallback to custom implementation with Shadow DOM support
  1071. else if (rootNode && isShadowRoot(rootNode)) {
  1072. let next = child;
  1073. do {
  1074. // use `===` replace node.isSameNode()
  1075. if (next && parent === next) {
  1076. return true;
  1077. } // @ts-ignore: need a better way to handle this...
  1078. next = next.parentNode || next.host;
  1079. } while (next);
  1080. }
  1081. return false;
  1082. }
  1083. function getNearestParentCapableOfEscapingClipping(element, clippingAncestors) {
  1084. let currentNode = element;
  1085. while (currentNode && !isLastTraversableNode(currentNode) && // @ts-expect-error
  1086. !clippingAncestors.includes(currentNode)) {
  1087. if (isElement(currentNode) && ['absolute', 'fixed'].includes(getComputedStyle(currentNode).position)) {
  1088. break;
  1089. }
  1090. const parentNode = getParentNode(currentNode);
  1091. currentNode = isShadowRoot(parentNode) ? parentNode.host : parentNode;
  1092. }
  1093. return currentNode;
  1094. }
  1095. function getInnerBoundingClientRect(element, strategy) {
  1096. const clientRect = getBoundingClientRect(element, false, strategy === 'fixed');
  1097. const top = clientRect.top + element.clientTop;
  1098. const left = clientRect.left + element.clientLeft;
  1099. return {
  1100. top,
  1101. left,
  1102. x: left,
  1103. y: top,
  1104. right: left + element.clientWidth,
  1105. bottom: top + element.clientHeight,
  1106. width: element.clientWidth,
  1107. height: element.clientHeight
  1108. };
  1109. }
  1110. function getClientRectFromClippingAncestor(element, clippingParent, strategy) {
  1111. if (clippingParent === 'viewport') {
  1112. return rectToClientRect(getViewportRect(element, strategy));
  1113. }
  1114. if (isElement(clippingParent)) {
  1115. return getInnerBoundingClientRect(clippingParent, strategy);
  1116. }
  1117. return rectToClientRect(getDocumentRect(getDocumentElement(element)));
  1118. } // A "clipping ancestor" is an overflowable container with the characteristic of
  1119. // clipping (or hiding) overflowing elements with a position different from
  1120. // `initial`
  1121. function getClippingAncestors(element) {
  1122. const clippingAncestors = getOverflowAncestors(element);
  1123. const nearestEscapableParent = getNearestParentCapableOfEscapingClipping(element, clippingAncestors);
  1124. let clipperElement = null;
  1125. if (nearestEscapableParent && isHTMLElement(nearestEscapableParent)) {
  1126. const offsetParent = getOffsetParent(nearestEscapableParent);
  1127. if (isOverflowElement(nearestEscapableParent)) {
  1128. clipperElement = nearestEscapableParent;
  1129. } else if (isHTMLElement(offsetParent)) {
  1130. clipperElement = offsetParent;
  1131. }
  1132. }
  1133. if (!isElement(clipperElement)) {
  1134. return [];
  1135. } // @ts-ignore isElement check ensures we return Array<Element>
  1136. return clippingAncestors.filter(clippingAncestors => clipperElement && isElement(clippingAncestors) && contains(clippingAncestors, clipperElement) && getNodeName(clippingAncestors) !== 'body');
  1137. } // Gets the maximum area that the element is visible in due to any number of
  1138. // clipping ancestors
  1139. function getClippingRect(_ref) {
  1140. let {
  1141. element,
  1142. boundary,
  1143. rootBoundary,
  1144. strategy
  1145. } = _ref;
  1146. const mainClippingAncestors = boundary === 'clippingAncestors' ? getClippingAncestors(element) : [].concat(boundary);
  1147. const clippingAncestors = [...mainClippingAncestors, rootBoundary];
  1148. const firstClippingAncestor = clippingAncestors[0];
  1149. const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => {
  1150. const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy);
  1151. accRect.top = max(rect.top, accRect.top);
  1152. accRect.right = min(rect.right, accRect.right);
  1153. accRect.bottom = min(rect.bottom, accRect.bottom);
  1154. accRect.left = max(rect.left, accRect.left);
  1155. return accRect;
  1156. }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy));
  1157. return {
  1158. width: clippingRect.right - clippingRect.left,
  1159. height: clippingRect.bottom - clippingRect.top,
  1160. x: clippingRect.left,
  1161. y: clippingRect.top
  1162. };
  1163. }
  1164. const platform = {
  1165. getClippingRect,
  1166. convertOffsetParentRelativeRectToViewportRelativeRect,
  1167. isElement,
  1168. getDimensions,
  1169. getOffsetParent,
  1170. getDocumentElement,
  1171. getElementRects: _ref => {
  1172. let {
  1173. reference,
  1174. floating,
  1175. strategy
  1176. } = _ref;
  1177. return {
  1178. reference: getRectRelativeToOffsetParent(reference, getOffsetParent(floating), strategy),
  1179. floating: { ...getDimensions(floating),
  1180. x: 0,
  1181. y: 0
  1182. }
  1183. };
  1184. },
  1185. getClientRects: element => Array.from(element.getClientRects()),
  1186. isRTL: element => getComputedStyle(element).direction === 'rtl'
  1187. };
  1188. /**
  1189. * Automatically updates the position of the floating element when necessary.
  1190. * @see https://floating-ui.com/docs/autoUpdate
  1191. */
  1192. function autoUpdate(reference, floating, update, options) {
  1193. if (options === void 0) {
  1194. options = {};
  1195. }
  1196. const {
  1197. ancestorScroll: _ancestorScroll = true,
  1198. ancestorResize = true,
  1199. elementResize = true,
  1200. animationFrame = false
  1201. } = options;
  1202. const ancestorScroll = _ancestorScroll && !animationFrame;
  1203. const ancestors = ancestorScroll || ancestorResize ? [...(isElement(reference) ? getOverflowAncestors(reference) : []), ...getOverflowAncestors(floating)] : [];
  1204. ancestors.forEach(ancestor => {
  1205. ancestorScroll && ancestor.addEventListener('scroll', update, {
  1206. passive: true
  1207. });
  1208. ancestorResize && ancestor.addEventListener('resize', update);
  1209. });
  1210. let observer = null;
  1211. if (elementResize) {
  1212. let initialUpdate = true;
  1213. observer = new ResizeObserver(() => {
  1214. if (!initialUpdate) {
  1215. update();
  1216. }
  1217. initialUpdate = false;
  1218. });
  1219. isElement(reference) && !animationFrame && observer.observe(reference);
  1220. observer.observe(floating);
  1221. }
  1222. let frameId;
  1223. let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;
  1224. if (animationFrame) {
  1225. frameLoop();
  1226. }
  1227. function frameLoop() {
  1228. const nextRefRect = getBoundingClientRect(reference);
  1229. if (prevRefRect && (nextRefRect.x !== prevRefRect.x || nextRefRect.y !== prevRefRect.y || nextRefRect.width !== prevRefRect.width || nextRefRect.height !== prevRefRect.height)) {
  1230. update();
  1231. }
  1232. prevRefRect = nextRefRect;
  1233. frameId = requestAnimationFrame(frameLoop);
  1234. }
  1235. update();
  1236. return () => {
  1237. var _observer;
  1238. ancestors.forEach(ancestor => {
  1239. ancestorScroll && ancestor.removeEventListener('scroll', update);
  1240. ancestorResize && ancestor.removeEventListener('resize', update);
  1241. });
  1242. (_observer = observer) == null ? void 0 : _observer.disconnect();
  1243. observer = null;
  1244. if (animationFrame) {
  1245. cancelAnimationFrame(frameId);
  1246. }
  1247. };
  1248. }
  1249. /**
  1250. * Computes the `x` and `y` coordinates that will place the floating element
  1251. * next to a reference element when it is given a certain CSS positioning
  1252. * strategy.
  1253. */
  1254. const computePosition = (reference, floating, options) => computePosition$1(reference, floating, {
  1255. platform,
  1256. ...options
  1257. });
  1258. /**
  1259. * This module helps users provide custom configuration for component internals.
  1260. *
  1261. * @internal
  1262. */
  1263. const configOverrides = globalThis["calciteComponentsConfig"];
  1264. const config = {
  1265. /**
  1266. * We apply a custom fix to improve positioning for non-Chromium browsers.
  1267. * The fix comes at a performance cost, so provides users a way to opt-out if necessary.
  1268. *
  1269. * @internal
  1270. */
  1271. floatingUINonChromiumPositioningFix: true,
  1272. ...configOverrides
  1273. };
  1274. const floatingUIBrowserCheck = patchFloatingUiForNonChromiumBrowsers();
  1275. async function patchFloatingUiForNonChromiumBrowsers() {
  1276. function getUAString() {
  1277. const uaData = navigator.userAgentData;
  1278. if (uaData === null || uaData === void 0 ? void 0 : uaData.brands) {
  1279. return uaData.brands.map((item) => `${item.brand}/${item.version}`).join(" ");
  1280. }
  1281. return navigator.userAgent;
  1282. }
  1283. if (Build.isBrowser &&
  1284. config.floatingUINonChromiumPositioningFix &&
  1285. // ⚠️ browser-sniffing is not a best practice and should be avoided ⚠️
  1286. /firefox|safari/i.test(getUAString())) {
  1287. const { getClippingRect, getElementRects, getOffsetParent } = await import('./nonChromiumPlatformUtils.js');
  1288. platform.getClippingRect = getClippingRect;
  1289. platform.getOffsetParent = getOffsetParent;
  1290. platform.getElementRects = getElementRects;
  1291. }
  1292. }
  1293. const placementDataAttribute = "data-placement";
  1294. /**
  1295. * Exported for testing purposes only
  1296. */
  1297. const repositionDebounceTimeout = 100;
  1298. const effectivePlacements = [
  1299. "top",
  1300. "bottom",
  1301. "right",
  1302. "left",
  1303. "top-start",
  1304. "top-end",
  1305. "bottom-start",
  1306. "bottom-end",
  1307. "right-start",
  1308. "right-end",
  1309. "left-start",
  1310. "left-end"
  1311. ];
  1312. const defaultMenuPlacement = "bottom-start";
  1313. const FloatingCSS = {
  1314. animation: "calcite-floating-ui-anim",
  1315. animationActive: "calcite-floating-ui-anim--active"
  1316. };
  1317. function getMiddleware({ placement, disableFlip, flipPlacements, offsetDistance, offsetSkidding, arrowEl, type }) {
  1318. const defaultMiddleware = [shift(), hide()];
  1319. if (type === "menu") {
  1320. return [
  1321. ...defaultMiddleware,
  1322. flip({
  1323. fallbackPlacements: flipPlacements || ["top-start", "top", "top-end", "bottom-start", "bottom", "bottom-end"]
  1324. })
  1325. ];
  1326. }
  1327. if (type === "popover" || type === "tooltip") {
  1328. const middleware = [
  1329. ...defaultMiddleware,
  1330. offset({
  1331. mainAxis: typeof offsetDistance === "number" ? offsetDistance : 0,
  1332. crossAxis: typeof offsetSkidding === "number" ? offsetSkidding : 0
  1333. })
  1334. ];
  1335. if (placement === "auto" || placement === "auto-start" || placement === "auto-end") {
  1336. middleware.push(autoPlacement({ alignment: placement === "auto-start" ? "start" : placement === "auto-end" ? "end" : null }));
  1337. }
  1338. else if (!disableFlip) {
  1339. middleware.push(flip(flipPlacements ? { fallbackPlacements: flipPlacements } : {}));
  1340. }
  1341. if (arrowEl) {
  1342. middleware.push(arrow({
  1343. element: arrowEl
  1344. }));
  1345. }
  1346. return middleware;
  1347. }
  1348. return [];
  1349. }
  1350. function filterComputedPlacements(placements, el) {
  1351. const filteredPlacements = placements.filter((placement) => effectivePlacements.includes(placement));
  1352. if (filteredPlacements.length !== placements.length) {
  1353. console.warn(`${el.tagName}: Invalid value found in: flipPlacements. Try any of these: ${effectivePlacements
  1354. .map((placement) => `"${placement}"`)
  1355. .join(", ")
  1356. .trim()}`, { el });
  1357. }
  1358. return filteredPlacements;
  1359. }
  1360. /*
  1361. In floating-ui, "*-start" and "*-end" are already flipped in RTL.
  1362. There is no need for our "*-leading" and "*-trailing" values anymore.
  1363. https://github.com/floating-ui/floating-ui/issues/1530
  1364. https://github.com/floating-ui/floating-ui/issues/1563
  1365. */
  1366. function getEffectivePlacement(floatingEl, placement) {
  1367. const placements = ["left", "right"];
  1368. if (getElementDir(floatingEl) === "rtl") {
  1369. placements.reverse();
  1370. }
  1371. return placement
  1372. .replace(/-leading/gi, "-start")
  1373. .replace(/-trailing/gi, "-end")
  1374. .replace(/leading/gi, placements[0])
  1375. .replace(/trailing/gi, placements[1]);
  1376. }
  1377. /**
  1378. * Convenience function to manage `reposition` calls for FloatingUIComponents that use `positionFloatingUI.
  1379. *
  1380. * Note: this is not needed for components that use `calcite-popover`.
  1381. *
  1382. * @param component
  1383. * @param options
  1384. * @param options.referenceEl
  1385. * @param options.floatingEl
  1386. * @param options.overlayPositioning
  1387. * @param options.placement
  1388. * @param options.disableFlip
  1389. * @param options.flipPlacements
  1390. * @param options.offsetDistance
  1391. * @param options.offsetSkidding
  1392. * @param options.arrowEl
  1393. * @param options.type
  1394. * @param delayed
  1395. */
  1396. async function reposition(component, options, delayed = false) {
  1397. if (!component.open) {
  1398. return;
  1399. }
  1400. return delayed ? debouncedReposition(options) : positionFloatingUI(options);
  1401. }
  1402. const debouncedReposition = debounce(positionFloatingUI, repositionDebounceTimeout, {
  1403. leading: true,
  1404. maxWait: repositionDebounceTimeout
  1405. });
  1406. /**
  1407. * Positions the floating element relative to the reference element.
  1408. *
  1409. * **Note:** exported for testing purposes only
  1410. *
  1411. * @param root0
  1412. * @param root0.referenceEl
  1413. * @param root0.floatingEl
  1414. * @param root0.overlayPositioning
  1415. * @param root0.placement
  1416. * @param root0.disableFlip
  1417. * @param root0.flipPlacements
  1418. * @param root0.offsetDistance
  1419. * @param root0.offsetSkidding
  1420. * @param root0.arrowEl
  1421. * @param root0.type
  1422. * @param root0.includeArrow
  1423. */
  1424. async function positionFloatingUI({ referenceEl, floatingEl, overlayPositioning = "absolute", placement, disableFlip, flipPlacements, offsetDistance, offsetSkidding, includeArrow = false, arrowEl, type }) {
  1425. var _a;
  1426. if (!referenceEl || !floatingEl || (includeArrow && !arrowEl)) {
  1427. return null;
  1428. }
  1429. await floatingUIBrowserCheck;
  1430. const { x, y, placement: effectivePlacement, strategy: position, middlewareData } = await computePosition(referenceEl, floatingEl, {
  1431. strategy: overlayPositioning,
  1432. placement: placement === "auto" || placement === "auto-start" || placement === "auto-end"
  1433. ? undefined
  1434. : getEffectivePlacement(floatingEl, placement),
  1435. middleware: getMiddleware({
  1436. placement,
  1437. disableFlip,
  1438. flipPlacements,
  1439. offsetDistance,
  1440. offsetSkidding,
  1441. arrowEl,
  1442. type
  1443. })
  1444. });
  1445. if (middlewareData === null || middlewareData === void 0 ? void 0 : middlewareData.arrow) {
  1446. const { x: arrowX, y: arrowY } = middlewareData.arrow;
  1447. Object.assign(arrowEl.style, {
  1448. left: arrowX != null ? `${arrowX}px` : "",
  1449. top: arrowY != null ? `${arrowY}px` : ""
  1450. });
  1451. }
  1452. const referenceHidden = (_a = middlewareData === null || middlewareData === void 0 ? void 0 : middlewareData.hide) === null || _a === void 0 ? void 0 : _a.referenceHidden;
  1453. const visibility = referenceHidden ? "hidden" : null;
  1454. const pointerEvents = visibility ? "none" : null;
  1455. floatingEl.setAttribute(placementDataAttribute, effectivePlacement);
  1456. const transform = `translate(${Math.round(x)}px,${Math.round(y)}px)`;
  1457. Object.assign(floatingEl.style, {
  1458. visibility,
  1459. pointerEvents,
  1460. position,
  1461. top: "0",
  1462. left: "0",
  1463. transform
  1464. });
  1465. }
  1466. /**
  1467. * Exported for testing purposes only
  1468. *
  1469. * @internal
  1470. */
  1471. const cleanupMap = new WeakMap();
  1472. /**
  1473. * Helper to set up floating element interactions on connectedCallback.
  1474. *
  1475. * @param component
  1476. * @param referenceEl
  1477. * @param floatingEl
  1478. */
  1479. function connectFloatingUI(component, referenceEl, floatingEl) {
  1480. if (!floatingEl || !referenceEl) {
  1481. return;
  1482. }
  1483. disconnectFloatingUI(component, referenceEl, floatingEl);
  1484. const position = component.overlayPositioning;
  1485. // ensure position matches for initial positioning
  1486. floatingEl.style.position = position;
  1487. if (position === "absolute") {
  1488. moveOffScreen(floatingEl);
  1489. }
  1490. const runAutoUpdate = Build.isBrowser
  1491. ? autoUpdate
  1492. : (_refEl, _floatingEl, updateCallback) => {
  1493. updateCallback();
  1494. return () => {
  1495. /* noop */
  1496. };
  1497. };
  1498. cleanupMap.set(component, runAutoUpdate(referenceEl, floatingEl, () => component.reposition()));
  1499. }
  1500. /**
  1501. * Helper to tear down floating element interactions on disconnectedCallback.
  1502. *
  1503. * @param component
  1504. * @param referenceEl
  1505. * @param floatingEl
  1506. */
  1507. function disconnectFloatingUI(component, referenceEl, floatingEl) {
  1508. if (!floatingEl || !referenceEl) {
  1509. return;
  1510. }
  1511. getTransitionTarget(floatingEl).removeEventListener("transitionend", handleTransitionElTransitionEnd);
  1512. const cleanup = cleanupMap.get(component);
  1513. if (cleanup) {
  1514. cleanup();
  1515. }
  1516. cleanupMap.delete(component);
  1517. }
  1518. const visiblePointerSize = 4;
  1519. /**
  1520. * Default offset the position of the floating element away from the reference element.
  1521. *
  1522. * @default 6
  1523. */
  1524. const defaultOffsetDistance = Math.ceil(Math.hypot(visiblePointerSize, visiblePointerSize));
  1525. /**
  1526. * This utils applies floating element styles to avoid affecting layout when closed.
  1527. *
  1528. * This should be called when the closing transition will start.
  1529. *
  1530. * @param floatingEl
  1531. */
  1532. function updateAfterClose(floatingEl) {
  1533. if (!floatingEl || floatingEl.style.position !== "absolute") {
  1534. return;
  1535. }
  1536. getTransitionTarget(floatingEl).addEventListener("transitionend", handleTransitionElTransitionEnd);
  1537. }
  1538. function getTransitionTarget(floatingEl) {
  1539. // assumes floatingEl w/ shadowRoot is a FloatingUIComponent
  1540. return floatingEl.shadowRoot || floatingEl;
  1541. }
  1542. function handleTransitionElTransitionEnd(event) {
  1543. const floatingTransitionEl = event.target;
  1544. if (
  1545. // using any prop from floating-ui transition
  1546. event.propertyName === "opacity" &&
  1547. floatingTransitionEl.classList.contains(FloatingCSS.animation)) {
  1548. const floatingEl = getFloatingElFromTransitionTarget(floatingTransitionEl);
  1549. moveOffScreen(floatingEl);
  1550. getTransitionTarget(floatingEl).removeEventListener("transitionend", handleTransitionElTransitionEnd);
  1551. }
  1552. }
  1553. function moveOffScreen(floatingEl) {
  1554. floatingEl.style.transform = "";
  1555. floatingEl.style.top = "-99999px";
  1556. floatingEl.style.left = "-99999px";
  1557. }
  1558. function getFloatingElFromTransitionTarget(floatingTransitionEl) {
  1559. return closestElementCrossShadowBoundary(floatingTransitionEl, `[${placementDataAttribute}]`);
  1560. }
  1561. export { FloatingCSS as F, disconnectFloatingUI as a, defaultOffsetDistance as b, connectFloatingUI as c, defaultMenuPlacement as d, rectToClientRect as e, filterComputedPlacements as f, reposition as r, updateAfterClose as u };