floating-ui-b48c8256.js 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777
  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. 'use strict';
  7. const dom = require('./dom-2ec8c9ed.js');
  8. const debounce = require('./debounce-2c8b61fb.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 (config.floatingUINonChromiumPositioningFix &&
  1284. // ⚠️ browser-sniffing is not a best practice and should be avoided ⚠️
  1285. /firefox|safari/i.test(getUAString())) {
  1286. const { getClippingRect, getElementRects, getOffsetParent } = await Promise.resolve().then(function () { return require('./nonChromiumPlatformUtils-95812e02.js'); });
  1287. platform.getClippingRect = getClippingRect;
  1288. platform.getOffsetParent = getOffsetParent;
  1289. platform.getElementRects = getElementRects;
  1290. }
  1291. }
  1292. const placementDataAttribute = "data-placement";
  1293. /**
  1294. * Exported for testing purposes only
  1295. */
  1296. const repositionDebounceTimeout = 100;
  1297. const effectivePlacements = [
  1298. "top",
  1299. "bottom",
  1300. "right",
  1301. "left",
  1302. "top-start",
  1303. "top-end",
  1304. "bottom-start",
  1305. "bottom-end",
  1306. "right-start",
  1307. "right-end",
  1308. "left-start",
  1309. "left-end"
  1310. ];
  1311. const defaultMenuPlacement = "bottom-start";
  1312. const FloatingCSS = {
  1313. animation: "calcite-floating-ui-anim",
  1314. animationActive: "calcite-floating-ui-anim--active"
  1315. };
  1316. function getMiddleware({ placement, disableFlip, flipPlacements, offsetDistance, offsetSkidding, arrowEl, type }) {
  1317. const defaultMiddleware = [shift(), hide()];
  1318. if (type === "menu") {
  1319. return [
  1320. ...defaultMiddleware,
  1321. flip({
  1322. fallbackPlacements: flipPlacements || ["top-start", "top", "top-end", "bottom-start", "bottom", "bottom-end"]
  1323. })
  1324. ];
  1325. }
  1326. if (type === "popover" || type === "tooltip") {
  1327. const middleware = [
  1328. ...defaultMiddleware,
  1329. offset({
  1330. mainAxis: typeof offsetDistance === "number" ? offsetDistance : 0,
  1331. crossAxis: typeof offsetSkidding === "number" ? offsetSkidding : 0
  1332. })
  1333. ];
  1334. if (placement === "auto" || placement === "auto-start" || placement === "auto-end") {
  1335. middleware.push(autoPlacement({ alignment: placement === "auto-start" ? "start" : placement === "auto-end" ? "end" : null }));
  1336. }
  1337. else if (!disableFlip) {
  1338. middleware.push(flip(flipPlacements ? { fallbackPlacements: flipPlacements } : {}));
  1339. }
  1340. if (arrowEl) {
  1341. middleware.push(arrow({
  1342. element: arrowEl
  1343. }));
  1344. }
  1345. return middleware;
  1346. }
  1347. return [];
  1348. }
  1349. function filterComputedPlacements(placements, el) {
  1350. const filteredPlacements = placements.filter((placement) => effectivePlacements.includes(placement));
  1351. if (filteredPlacements.length !== placements.length) {
  1352. console.warn(`${el.tagName}: Invalid value found in: flipPlacements. Try any of these: ${effectivePlacements
  1353. .map((placement) => `"${placement}"`)
  1354. .join(", ")
  1355. .trim()}`, { el });
  1356. }
  1357. return filteredPlacements;
  1358. }
  1359. /*
  1360. In floating-ui, "*-start" and "*-end" are already flipped in RTL.
  1361. There is no need for our "*-leading" and "*-trailing" values anymore.
  1362. https://github.com/floating-ui/floating-ui/issues/1530
  1363. https://github.com/floating-ui/floating-ui/issues/1563
  1364. */
  1365. function getEffectivePlacement(floatingEl, placement) {
  1366. const placements = ["left", "right"];
  1367. if (dom.getElementDir(floatingEl) === "rtl") {
  1368. placements.reverse();
  1369. }
  1370. return placement
  1371. .replace(/-leading/gi, "-start")
  1372. .replace(/-trailing/gi, "-end")
  1373. .replace(/leading/gi, placements[0])
  1374. .replace(/trailing/gi, placements[1]);
  1375. }
  1376. /**
  1377. * Convenience function to manage `reposition` calls for FloatingUIComponents that use `positionFloatingUI.
  1378. *
  1379. * Note: this is not needed for components that use `calcite-popover`.
  1380. *
  1381. * @param component
  1382. * @param options
  1383. * @param options.referenceEl
  1384. * @param options.floatingEl
  1385. * @param options.overlayPositioning
  1386. * @param options.placement
  1387. * @param options.disableFlip
  1388. * @param options.flipPlacements
  1389. * @param options.offsetDistance
  1390. * @param options.offsetSkidding
  1391. * @param options.arrowEl
  1392. * @param options.type
  1393. * @param delayed
  1394. */
  1395. async function reposition(component, options, delayed = false) {
  1396. if (!component.open) {
  1397. return;
  1398. }
  1399. return delayed ? debouncedReposition(options) : positionFloatingUI(options);
  1400. }
  1401. const debouncedReposition = debounce.debounce(positionFloatingUI, repositionDebounceTimeout, {
  1402. leading: true,
  1403. maxWait: repositionDebounceTimeout
  1404. });
  1405. /**
  1406. * Positions the floating element relative to the reference element.
  1407. *
  1408. * **Note:** exported for testing purposes only
  1409. *
  1410. * @param root0
  1411. * @param root0.referenceEl
  1412. * @param root0.floatingEl
  1413. * @param root0.overlayPositioning
  1414. * @param root0.placement
  1415. * @param root0.disableFlip
  1416. * @param root0.flipPlacements
  1417. * @param root0.offsetDistance
  1418. * @param root0.offsetSkidding
  1419. * @param root0.arrowEl
  1420. * @param root0.type
  1421. * @param root0.includeArrow
  1422. */
  1423. async function positionFloatingUI({ referenceEl, floatingEl, overlayPositioning = "absolute", placement, disableFlip, flipPlacements, offsetDistance, offsetSkidding, includeArrow = false, arrowEl, type }) {
  1424. var _a;
  1425. if (!referenceEl || !floatingEl || (includeArrow && !arrowEl)) {
  1426. return null;
  1427. }
  1428. await floatingUIBrowserCheck;
  1429. const { x, y, placement: effectivePlacement, strategy: position, middlewareData } = await computePosition(referenceEl, floatingEl, {
  1430. strategy: overlayPositioning,
  1431. placement: placement === "auto" || placement === "auto-start" || placement === "auto-end"
  1432. ? undefined
  1433. : getEffectivePlacement(floatingEl, placement),
  1434. middleware: getMiddleware({
  1435. placement,
  1436. disableFlip,
  1437. flipPlacements,
  1438. offsetDistance,
  1439. offsetSkidding,
  1440. arrowEl,
  1441. type
  1442. })
  1443. });
  1444. if (middlewareData === null || middlewareData === void 0 ? void 0 : middlewareData.arrow) {
  1445. const { x: arrowX, y: arrowY } = middlewareData.arrow;
  1446. Object.assign(arrowEl.style, {
  1447. left: arrowX != null ? `${arrowX}px` : "",
  1448. top: arrowY != null ? `${arrowY}px` : ""
  1449. });
  1450. }
  1451. const referenceHidden = (_a = middlewareData === null || middlewareData === void 0 ? void 0 : middlewareData.hide) === null || _a === void 0 ? void 0 : _a.referenceHidden;
  1452. const visibility = referenceHidden ? "hidden" : null;
  1453. const pointerEvents = visibility ? "none" : null;
  1454. floatingEl.setAttribute(placementDataAttribute, effectivePlacement);
  1455. const transform = `translate(${Math.round(x)}px,${Math.round(y)}px)`;
  1456. Object.assign(floatingEl.style, {
  1457. visibility,
  1458. pointerEvents,
  1459. position,
  1460. top: "0",
  1461. left: "0",
  1462. transform
  1463. });
  1464. }
  1465. /**
  1466. * Exported for testing purposes only
  1467. *
  1468. * @internal
  1469. */
  1470. const cleanupMap = new WeakMap();
  1471. /**
  1472. * Helper to set up floating element interactions on connectedCallback.
  1473. *
  1474. * @param component
  1475. * @param referenceEl
  1476. * @param floatingEl
  1477. */
  1478. function connectFloatingUI(component, referenceEl, floatingEl) {
  1479. if (!floatingEl || !referenceEl) {
  1480. return;
  1481. }
  1482. disconnectFloatingUI(component, referenceEl, floatingEl);
  1483. const position = component.overlayPositioning;
  1484. // ensure position matches for initial positioning
  1485. floatingEl.style.position = position;
  1486. if (position === "absolute") {
  1487. moveOffScreen(floatingEl);
  1488. }
  1489. const runAutoUpdate = autoUpdate
  1490. ;
  1491. cleanupMap.set(component, runAutoUpdate(referenceEl, floatingEl, () => component.reposition()));
  1492. }
  1493. /**
  1494. * Helper to tear down floating element interactions on disconnectedCallback.
  1495. *
  1496. * @param component
  1497. * @param referenceEl
  1498. * @param floatingEl
  1499. */
  1500. function disconnectFloatingUI(component, referenceEl, floatingEl) {
  1501. if (!floatingEl || !referenceEl) {
  1502. return;
  1503. }
  1504. getTransitionTarget(floatingEl).removeEventListener("transitionend", handleTransitionElTransitionEnd);
  1505. const cleanup = cleanupMap.get(component);
  1506. if (cleanup) {
  1507. cleanup();
  1508. }
  1509. cleanupMap.delete(component);
  1510. }
  1511. const visiblePointerSize = 4;
  1512. /**
  1513. * Default offset the position of the floating element away from the reference element.
  1514. *
  1515. * @default 6
  1516. */
  1517. const defaultOffsetDistance = Math.ceil(Math.hypot(visiblePointerSize, visiblePointerSize));
  1518. /**
  1519. * This utils applies floating element styles to avoid affecting layout when closed.
  1520. *
  1521. * This should be called when the closing transition will start.
  1522. *
  1523. * @param floatingEl
  1524. */
  1525. function updateAfterClose(floatingEl) {
  1526. if (!floatingEl || floatingEl.style.position !== "absolute") {
  1527. return;
  1528. }
  1529. getTransitionTarget(floatingEl).addEventListener("transitionend", handleTransitionElTransitionEnd);
  1530. }
  1531. function getTransitionTarget(floatingEl) {
  1532. // assumes floatingEl w/ shadowRoot is a FloatingUIComponent
  1533. return floatingEl.shadowRoot || floatingEl;
  1534. }
  1535. function handleTransitionElTransitionEnd(event) {
  1536. const floatingTransitionEl = event.target;
  1537. if (
  1538. // using any prop from floating-ui transition
  1539. event.propertyName === "opacity" &&
  1540. floatingTransitionEl.classList.contains(FloatingCSS.animation)) {
  1541. const floatingEl = getFloatingElFromTransitionTarget(floatingTransitionEl);
  1542. moveOffScreen(floatingEl);
  1543. getTransitionTarget(floatingEl).removeEventListener("transitionend", handleTransitionElTransitionEnd);
  1544. }
  1545. }
  1546. function moveOffScreen(floatingEl) {
  1547. floatingEl.style.transform = "";
  1548. floatingEl.style.top = "-99999px";
  1549. floatingEl.style.left = "-99999px";
  1550. }
  1551. function getFloatingElFromTransitionTarget(floatingTransitionEl) {
  1552. return dom.closestElementCrossShadowBoundary(floatingTransitionEl, `[${placementDataAttribute}]`);
  1553. }
  1554. exports.FloatingCSS = FloatingCSS;
  1555. exports.connectFloatingUI = connectFloatingUI;
  1556. exports.defaultMenuPlacement = defaultMenuPlacement;
  1557. exports.defaultOffsetDistance = defaultOffsetDistance;
  1558. exports.disconnectFloatingUI = disconnectFloatingUI;
  1559. exports.filterComputedPlacements = filterComputedPlacements;
  1560. exports.rectToClientRect = rectToClientRect;
  1561. exports.reposition = reposition;
  1562. exports.updateAfterClose = updateAfterClose;