floating-ui-5c49748f.js 52 KB

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