floating-ui.dom.esm.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. import { rectToClientRect, arrow as arrow$1, autoPlacement as autoPlacement$1, detectOverflow as detectOverflow$1, flip as flip$1, hide as hide$1, inline as inline$1, limitShift as limitShift$1, offset as offset$1, shift as shift$1, size as size$1, computePosition as computePosition$1 } from '@floating-ui/core';
  2. import { round, createCoords, max, min, floor } from '@floating-ui/utils';
  3. import { getComputedStyle as getComputedStyle$1, isHTMLElement, isElement, getWindow, isWebKit, getFrameElement, getNodeScroll, getDocumentElement, isTopLayer, getNodeName, isOverflowElement, getOverflowAncestors, getParentNode, isLastTraversableNode, isContainingBlock, isTableElement, getContainingBlock } from '@floating-ui/utils/dom';
  4. export { getOverflowAncestors } from '@floating-ui/utils/dom';
  5. function getCssDimensions(element) {
  6. const css = getComputedStyle$1(element);
  7. // In testing environments, the `width` and `height` properties are empty
  8. // strings for SVG elements, returning NaN. Fallback to `0` in this case.
  9. let width = parseFloat(css.width) || 0;
  10. let height = parseFloat(css.height) || 0;
  11. const hasOffset = isHTMLElement(element);
  12. const offsetWidth = hasOffset ? element.offsetWidth : width;
  13. const offsetHeight = hasOffset ? element.offsetHeight : height;
  14. const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;
  15. if (shouldFallback) {
  16. width = offsetWidth;
  17. height = offsetHeight;
  18. }
  19. return {
  20. width,
  21. height,
  22. $: shouldFallback
  23. };
  24. }
  25. function unwrapElement(element) {
  26. return !isElement(element) ? element.contextElement : element;
  27. }
  28. function getScale(element) {
  29. const domElement = unwrapElement(element);
  30. if (!isHTMLElement(domElement)) {
  31. return createCoords(1);
  32. }
  33. const rect = domElement.getBoundingClientRect();
  34. const {
  35. width,
  36. height,
  37. $
  38. } = getCssDimensions(domElement);
  39. let x = ($ ? round(rect.width) : rect.width) / width;
  40. let y = ($ ? round(rect.height) : rect.height) / height;
  41. // 0, NaN, or Infinity should always fallback to 1.
  42. if (!x || !Number.isFinite(x)) {
  43. x = 1;
  44. }
  45. if (!y || !Number.isFinite(y)) {
  46. y = 1;
  47. }
  48. return {
  49. x,
  50. y
  51. };
  52. }
  53. const noOffsets = /*#__PURE__*/createCoords(0);
  54. function getVisualOffsets(element) {
  55. const win = getWindow(element);
  56. if (!isWebKit() || !win.visualViewport) {
  57. return noOffsets;
  58. }
  59. return {
  60. x: win.visualViewport.offsetLeft,
  61. y: win.visualViewport.offsetTop
  62. };
  63. }
  64. function shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {
  65. if (isFixed === void 0) {
  66. isFixed = false;
  67. }
  68. if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) {
  69. return false;
  70. }
  71. return isFixed;
  72. }
  73. function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {
  74. if (includeScale === void 0) {
  75. includeScale = false;
  76. }
  77. if (isFixedStrategy === void 0) {
  78. isFixedStrategy = false;
  79. }
  80. const clientRect = element.getBoundingClientRect();
  81. const domElement = unwrapElement(element);
  82. let scale = createCoords(1);
  83. if (includeScale) {
  84. if (offsetParent) {
  85. if (isElement(offsetParent)) {
  86. scale = getScale(offsetParent);
  87. }
  88. } else {
  89. scale = getScale(element);
  90. }
  91. }
  92. const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);
  93. let x = (clientRect.left + visualOffsets.x) / scale.x;
  94. let y = (clientRect.top + visualOffsets.y) / scale.y;
  95. let width = clientRect.width / scale.x;
  96. let height = clientRect.height / scale.y;
  97. if (domElement) {
  98. const win = getWindow(domElement);
  99. const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;
  100. let currentWin = win;
  101. let currentIFrame = getFrameElement(currentWin);
  102. while (currentIFrame && offsetParent && offsetWin !== currentWin) {
  103. const iframeScale = getScale(currentIFrame);
  104. const iframeRect = currentIFrame.getBoundingClientRect();
  105. const css = getComputedStyle$1(currentIFrame);
  106. const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;
  107. const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;
  108. x *= iframeScale.x;
  109. y *= iframeScale.y;
  110. width *= iframeScale.x;
  111. height *= iframeScale.y;
  112. x += left;
  113. y += top;
  114. currentWin = getWindow(currentIFrame);
  115. currentIFrame = getFrameElement(currentWin);
  116. }
  117. }
  118. return rectToClientRect({
  119. width,
  120. height,
  121. x,
  122. y
  123. });
  124. }
  125. // If <html> has a CSS width greater than the viewport, then this will be
  126. // incorrect for RTL.
  127. function getWindowScrollBarX(element, rect) {
  128. const leftScroll = getNodeScroll(element).scrollLeft;
  129. if (!rect) {
  130. return getBoundingClientRect(getDocumentElement(element)).left + leftScroll;
  131. }
  132. return rect.left + leftScroll;
  133. }
  134. function getHTMLOffset(documentElement, scroll) {
  135. const htmlRect = documentElement.getBoundingClientRect();
  136. const x = htmlRect.left + scroll.scrollLeft - getWindowScrollBarX(documentElement, htmlRect);
  137. const y = htmlRect.top + scroll.scrollTop;
  138. return {
  139. x,
  140. y
  141. };
  142. }
  143. function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {
  144. let {
  145. elements,
  146. rect,
  147. offsetParent,
  148. strategy
  149. } = _ref;
  150. const isFixed = strategy === 'fixed';
  151. const documentElement = getDocumentElement(offsetParent);
  152. const topLayer = elements ? isTopLayer(elements.floating) : false;
  153. if (offsetParent === documentElement || topLayer && isFixed) {
  154. return rect;
  155. }
  156. let scroll = {
  157. scrollLeft: 0,
  158. scrollTop: 0
  159. };
  160. let scale = createCoords(1);
  161. const offsets = createCoords(0);
  162. const isOffsetParentAnElement = isHTMLElement(offsetParent);
  163. if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
  164. if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {
  165. scroll = getNodeScroll(offsetParent);
  166. }
  167. if (isOffsetParentAnElement) {
  168. const offsetRect = getBoundingClientRect(offsetParent);
  169. scale = getScale(offsetParent);
  170. offsets.x = offsetRect.x + offsetParent.clientLeft;
  171. offsets.y = offsetRect.y + offsetParent.clientTop;
  172. }
  173. }
  174. const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);
  175. return {
  176. width: rect.width * scale.x,
  177. height: rect.height * scale.y,
  178. x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x + htmlOffset.x,
  179. y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + htmlOffset.y
  180. };
  181. }
  182. function getClientRects(element) {
  183. return Array.from(element.getClientRects());
  184. }
  185. // Gets the entire size of the scrollable document area, even extending outside
  186. // of the `<html>` and `<body>` rect bounds if horizontally scrollable.
  187. function getDocumentRect(element) {
  188. const html = getDocumentElement(element);
  189. const scroll = getNodeScroll(element);
  190. const body = element.ownerDocument.body;
  191. const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);
  192. const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);
  193. let x = -scroll.scrollLeft + getWindowScrollBarX(element);
  194. const y = -scroll.scrollTop;
  195. if (getComputedStyle$1(body).direction === 'rtl') {
  196. x += max(html.clientWidth, body.clientWidth) - width;
  197. }
  198. return {
  199. width,
  200. height,
  201. x,
  202. y
  203. };
  204. }
  205. // Safety check: ensure the scrollbar space is reasonable in case this
  206. // calculation is affected by unusual styles.
  207. // Most scrollbars leave 15-18px of space.
  208. const SCROLLBAR_MAX = 25;
  209. function getViewportRect(element, strategy) {
  210. const win = getWindow(element);
  211. const html = getDocumentElement(element);
  212. const visualViewport = win.visualViewport;
  213. let width = html.clientWidth;
  214. let height = html.clientHeight;
  215. let x = 0;
  216. let y = 0;
  217. if (visualViewport) {
  218. width = visualViewport.width;
  219. height = visualViewport.height;
  220. const visualViewportBased = isWebKit();
  221. if (!visualViewportBased || visualViewportBased && strategy === 'fixed') {
  222. x = visualViewport.offsetLeft;
  223. y = visualViewport.offsetTop;
  224. }
  225. }
  226. const windowScrollbarX = getWindowScrollBarX(html);
  227. // <html> `overflow: hidden` + `scrollbar-gutter: stable` reduces the
  228. // visual width of the <html> but this is not considered in the size
  229. // of `html.clientWidth`.
  230. if (windowScrollbarX <= 0) {
  231. const doc = html.ownerDocument;
  232. const body = doc.body;
  233. const bodyStyles = getComputedStyle(body);
  234. const bodyMarginInline = doc.compatMode === 'CSS1Compat' ? parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight) || 0 : 0;
  235. const clippingStableScrollbarWidth = Math.abs(html.clientWidth - body.clientWidth - bodyMarginInline);
  236. if (clippingStableScrollbarWidth <= SCROLLBAR_MAX) {
  237. width -= clippingStableScrollbarWidth;
  238. }
  239. } else if (windowScrollbarX <= SCROLLBAR_MAX) {
  240. // If the <body> scrollbar is on the left, the width needs to be extended
  241. // by the scrollbar amount so there isn't extra space on the right.
  242. width += windowScrollbarX;
  243. }
  244. return {
  245. width,
  246. height,
  247. x,
  248. y
  249. };
  250. }
  251. // Returns the inner client rect, subtracting scrollbars if present.
  252. function getInnerBoundingClientRect(element, strategy) {
  253. const clientRect = getBoundingClientRect(element, true, strategy === 'fixed');
  254. const top = clientRect.top + element.clientTop;
  255. const left = clientRect.left + element.clientLeft;
  256. const scale = isHTMLElement(element) ? getScale(element) : createCoords(1);
  257. const width = element.clientWidth * scale.x;
  258. const height = element.clientHeight * scale.y;
  259. const x = left * scale.x;
  260. const y = top * scale.y;
  261. return {
  262. width,
  263. height,
  264. x,
  265. y
  266. };
  267. }
  268. function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {
  269. let rect;
  270. if (clippingAncestor === 'viewport') {
  271. rect = getViewportRect(element, strategy);
  272. } else if (clippingAncestor === 'document') {
  273. rect = getDocumentRect(getDocumentElement(element));
  274. } else if (isElement(clippingAncestor)) {
  275. rect = getInnerBoundingClientRect(clippingAncestor, strategy);
  276. } else {
  277. const visualOffsets = getVisualOffsets(element);
  278. rect = {
  279. x: clippingAncestor.x - visualOffsets.x,
  280. y: clippingAncestor.y - visualOffsets.y,
  281. width: clippingAncestor.width,
  282. height: clippingAncestor.height
  283. };
  284. }
  285. return rectToClientRect(rect);
  286. }
  287. function hasFixedPositionAncestor(element, stopNode) {
  288. const parentNode = getParentNode(element);
  289. if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {
  290. return false;
  291. }
  292. return getComputedStyle$1(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode);
  293. }
  294. // A "clipping ancestor" is an `overflow` element with the characteristic of
  295. // clipping (or hiding) child elements. This returns all clipping ancestors
  296. // of the given element up the tree.
  297. function getClippingElementAncestors(element, cache) {
  298. const cachedResult = cache.get(element);
  299. if (cachedResult) {
  300. return cachedResult;
  301. }
  302. let result = getOverflowAncestors(element, [], false).filter(el => isElement(el) && getNodeName(el) !== 'body');
  303. let currentContainingBlockComputedStyle = null;
  304. const elementIsFixed = getComputedStyle$1(element).position === 'fixed';
  305. let currentNode = elementIsFixed ? getParentNode(element) : element;
  306. // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
  307. while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {
  308. const computedStyle = getComputedStyle$1(currentNode);
  309. const currentNodeIsContaining = isContainingBlock(currentNode);
  310. if (!currentNodeIsContaining && computedStyle.position === 'fixed') {
  311. currentContainingBlockComputedStyle = null;
  312. }
  313. const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === 'static' && !!currentContainingBlockComputedStyle && (currentContainingBlockComputedStyle.position === 'absolute' || currentContainingBlockComputedStyle.position === 'fixed') || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode);
  314. if (shouldDropCurrentNode) {
  315. // Drop non-containing blocks.
  316. result = result.filter(ancestor => ancestor !== currentNode);
  317. } else {
  318. // Record last containing block for next iteration.
  319. currentContainingBlockComputedStyle = computedStyle;
  320. }
  321. currentNode = getParentNode(currentNode);
  322. }
  323. cache.set(element, result);
  324. return result;
  325. }
  326. // Gets the maximum area that the element is visible in due to any number of
  327. // clipping ancestors.
  328. function getClippingRect(_ref) {
  329. let {
  330. element,
  331. boundary,
  332. rootBoundary,
  333. strategy
  334. } = _ref;
  335. const elementClippingAncestors = boundary === 'clippingAncestors' ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary);
  336. const clippingAncestors = [...elementClippingAncestors, rootBoundary];
  337. const firstRect = getClientRectFromClippingAncestor(element, clippingAncestors[0], strategy);
  338. let top = firstRect.top;
  339. let right = firstRect.right;
  340. let bottom = firstRect.bottom;
  341. let left = firstRect.left;
  342. for (let i = 1; i < clippingAncestors.length; i++) {
  343. const rect = getClientRectFromClippingAncestor(element, clippingAncestors[i], strategy);
  344. top = max(rect.top, top);
  345. right = min(rect.right, right);
  346. bottom = min(rect.bottom, bottom);
  347. left = max(rect.left, left);
  348. }
  349. return {
  350. width: right - left,
  351. height: bottom - top,
  352. x: left,
  353. y: top
  354. };
  355. }
  356. function getDimensions(element) {
  357. const {
  358. width,
  359. height
  360. } = getCssDimensions(element);
  361. return {
  362. width,
  363. height
  364. };
  365. }
  366. function getRectRelativeToOffsetParent(element, offsetParent, strategy) {
  367. const isOffsetParentAnElement = isHTMLElement(offsetParent);
  368. const documentElement = getDocumentElement(offsetParent);
  369. const isFixed = strategy === 'fixed';
  370. const rect = getBoundingClientRect(element, true, isFixed, offsetParent);
  371. let scroll = {
  372. scrollLeft: 0,
  373. scrollTop: 0
  374. };
  375. const offsets = createCoords(0);
  376. // If the <body> scrollbar appears on the left (e.g. RTL systems). Use
  377. // Firefox with layout.scrollbar.side = 3 in about:config to test this.
  378. function setLeftRTLScrollbarOffset() {
  379. offsets.x = getWindowScrollBarX(documentElement);
  380. }
  381. if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
  382. if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {
  383. scroll = getNodeScroll(offsetParent);
  384. }
  385. if (isOffsetParentAnElement) {
  386. const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);
  387. offsets.x = offsetRect.x + offsetParent.clientLeft;
  388. offsets.y = offsetRect.y + offsetParent.clientTop;
  389. } else if (documentElement) {
  390. setLeftRTLScrollbarOffset();
  391. }
  392. }
  393. if (isFixed && !isOffsetParentAnElement && documentElement) {
  394. setLeftRTLScrollbarOffset();
  395. }
  396. const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);
  397. const x = rect.left + scroll.scrollLeft - offsets.x - htmlOffset.x;
  398. const y = rect.top + scroll.scrollTop - offsets.y - htmlOffset.y;
  399. return {
  400. x,
  401. y,
  402. width: rect.width,
  403. height: rect.height
  404. };
  405. }
  406. function isStaticPositioned(element) {
  407. return getComputedStyle$1(element).position === 'static';
  408. }
  409. function getTrueOffsetParent(element, polyfill) {
  410. if (!isHTMLElement(element) || getComputedStyle$1(element).position === 'fixed') {
  411. return null;
  412. }
  413. if (polyfill) {
  414. return polyfill(element);
  415. }
  416. let rawOffsetParent = element.offsetParent;
  417. // Firefox returns the <html> element as the offsetParent if it's non-static,
  418. // while Chrome and Safari return the <body> element. The <body> element must
  419. // be used to perform the correct calculations even if the <html> element is
  420. // non-static.
  421. if (getDocumentElement(element) === rawOffsetParent) {
  422. rawOffsetParent = rawOffsetParent.ownerDocument.body;
  423. }
  424. return rawOffsetParent;
  425. }
  426. // Gets the closest ancestor positioned element. Handles some edge cases,
  427. // such as table ancestors and cross browser bugs.
  428. function getOffsetParent(element, polyfill) {
  429. const win = getWindow(element);
  430. if (isTopLayer(element)) {
  431. return win;
  432. }
  433. if (!isHTMLElement(element)) {
  434. let svgOffsetParent = getParentNode(element);
  435. while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) {
  436. if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) {
  437. return svgOffsetParent;
  438. }
  439. svgOffsetParent = getParentNode(svgOffsetParent);
  440. }
  441. return win;
  442. }
  443. let offsetParent = getTrueOffsetParent(element, polyfill);
  444. while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) {
  445. offsetParent = getTrueOffsetParent(offsetParent, polyfill);
  446. }
  447. if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) {
  448. return win;
  449. }
  450. return offsetParent || getContainingBlock(element) || win;
  451. }
  452. const getElementRects = async function (data) {
  453. const getOffsetParentFn = this.getOffsetParent || getOffsetParent;
  454. const getDimensionsFn = this.getDimensions;
  455. const floatingDimensions = await getDimensionsFn(data.floating);
  456. return {
  457. reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy),
  458. floating: {
  459. x: 0,
  460. y: 0,
  461. width: floatingDimensions.width,
  462. height: floatingDimensions.height
  463. }
  464. };
  465. };
  466. function isRTL(element) {
  467. return getComputedStyle$1(element).direction === 'rtl';
  468. }
  469. const platform = {
  470. convertOffsetParentRelativeRectToViewportRelativeRect,
  471. getDocumentElement,
  472. getClippingRect,
  473. getOffsetParent,
  474. getElementRects,
  475. getClientRects,
  476. getDimensions,
  477. getScale,
  478. isElement,
  479. isRTL
  480. };
  481. function rectsAreEqual(a, b) {
  482. return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
  483. }
  484. // https://samthor.au/2021/observing-dom/
  485. function observeMove(element, onMove) {
  486. let io = null;
  487. let timeoutId;
  488. const root = getDocumentElement(element);
  489. function cleanup() {
  490. var _io;
  491. clearTimeout(timeoutId);
  492. (_io = io) == null || _io.disconnect();
  493. io = null;
  494. }
  495. function refresh(skip, threshold) {
  496. if (skip === void 0) {
  497. skip = false;
  498. }
  499. if (threshold === void 0) {
  500. threshold = 1;
  501. }
  502. cleanup();
  503. const elementRectForRootMargin = element.getBoundingClientRect();
  504. const {
  505. left,
  506. top,
  507. width,
  508. height
  509. } = elementRectForRootMargin;
  510. if (!skip) {
  511. onMove();
  512. }
  513. if (!width || !height) {
  514. return;
  515. }
  516. const insetTop = floor(top);
  517. const insetRight = floor(root.clientWidth - (left + width));
  518. const insetBottom = floor(root.clientHeight - (top + height));
  519. const insetLeft = floor(left);
  520. const rootMargin = -insetTop + "px " + -insetRight + "px " + -insetBottom + "px " + -insetLeft + "px";
  521. const options = {
  522. rootMargin,
  523. threshold: max(0, min(1, threshold)) || 1
  524. };
  525. let isFirstUpdate = true;
  526. function handleObserve(entries) {
  527. const ratio = entries[0].intersectionRatio;
  528. if (ratio !== threshold) {
  529. if (!isFirstUpdate) {
  530. return refresh();
  531. }
  532. if (!ratio) {
  533. // If the reference is clipped, the ratio is 0. Throttle the refresh
  534. // to prevent an infinite loop of updates.
  535. timeoutId = setTimeout(() => {
  536. refresh(false, 1e-7);
  537. }, 1000);
  538. } else {
  539. refresh(false, ratio);
  540. }
  541. }
  542. if (ratio === 1 && !rectsAreEqual(elementRectForRootMargin, element.getBoundingClientRect())) {
  543. // It's possible that even though the ratio is reported as 1, the
  544. // element is not actually fully within the IntersectionObserver's root
  545. // area anymore. This can happen under performance constraints. This may
  546. // be a bug in the browser's IntersectionObserver implementation. To
  547. // work around this, we compare the element's bounding rect now with
  548. // what it was at the time we created the IntersectionObserver. If they
  549. // are not equal then the element moved, so we refresh.
  550. refresh();
  551. }
  552. isFirstUpdate = false;
  553. }
  554. // Older browsers don't support a `document` as the root and will throw an
  555. // error.
  556. try {
  557. io = new IntersectionObserver(handleObserve, {
  558. ...options,
  559. // Handle <iframe>s
  560. root: root.ownerDocument
  561. });
  562. } catch (_e) {
  563. io = new IntersectionObserver(handleObserve, options);
  564. }
  565. io.observe(element);
  566. }
  567. refresh(true);
  568. return cleanup;
  569. }
  570. /**
  571. * Automatically updates the position of the floating element when necessary.
  572. * Should only be called when the floating element is mounted on the DOM or
  573. * visible on the screen.
  574. * @returns cleanup function that should be invoked when the floating element is
  575. * removed from the DOM or hidden from the screen.
  576. * @see https://floating-ui.com/docs/autoUpdate
  577. */
  578. function autoUpdate(reference, floating, update, options) {
  579. if (options === void 0) {
  580. options = {};
  581. }
  582. const {
  583. ancestorScroll = true,
  584. ancestorResize = true,
  585. elementResize = typeof ResizeObserver === 'function',
  586. layoutShift = typeof IntersectionObserver === 'function',
  587. animationFrame = false
  588. } = options;
  589. const referenceEl = unwrapElement(reference);
  590. const ancestors = ancestorScroll || ancestorResize ? [...(referenceEl ? getOverflowAncestors(referenceEl) : []), ...(floating ? getOverflowAncestors(floating) : [])] : [];
  591. ancestors.forEach(ancestor => {
  592. ancestorScroll && ancestor.addEventListener('scroll', update, {
  593. passive: true
  594. });
  595. ancestorResize && ancestor.addEventListener('resize', update);
  596. });
  597. const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update) : null;
  598. let reobserveFrame = -1;
  599. let resizeObserver = null;
  600. if (elementResize) {
  601. resizeObserver = new ResizeObserver(_ref => {
  602. let [firstEntry] = _ref;
  603. if (firstEntry && firstEntry.target === referenceEl && resizeObserver && floating) {
  604. // Prevent update loops when using the `size` middleware.
  605. // https://github.com/floating-ui/floating-ui/issues/1740
  606. resizeObserver.unobserve(floating);
  607. cancelAnimationFrame(reobserveFrame);
  608. reobserveFrame = requestAnimationFrame(() => {
  609. var _resizeObserver;
  610. (_resizeObserver = resizeObserver) == null || _resizeObserver.observe(floating);
  611. });
  612. }
  613. update();
  614. });
  615. if (referenceEl && !animationFrame) {
  616. resizeObserver.observe(referenceEl);
  617. }
  618. if (floating) {
  619. resizeObserver.observe(floating);
  620. }
  621. }
  622. let frameId;
  623. let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;
  624. if (animationFrame) {
  625. frameLoop();
  626. }
  627. function frameLoop() {
  628. const nextRefRect = getBoundingClientRect(reference);
  629. if (prevRefRect && !rectsAreEqual(prevRefRect, nextRefRect)) {
  630. update();
  631. }
  632. prevRefRect = nextRefRect;
  633. frameId = requestAnimationFrame(frameLoop);
  634. }
  635. update();
  636. return () => {
  637. var _resizeObserver2;
  638. ancestors.forEach(ancestor => {
  639. ancestorScroll && ancestor.removeEventListener('scroll', update);
  640. ancestorResize && ancestor.removeEventListener('resize', update);
  641. });
  642. cleanupIo == null || cleanupIo();
  643. (_resizeObserver2 = resizeObserver) == null || _resizeObserver2.disconnect();
  644. resizeObserver = null;
  645. if (animationFrame) {
  646. cancelAnimationFrame(frameId);
  647. }
  648. };
  649. }
  650. /**
  651. * Resolves with an object of overflow side offsets that determine how much the
  652. * element is overflowing a given clipping boundary on each side.
  653. * - positive = overflowing the boundary by that number of pixels
  654. * - negative = how many pixels left before it will overflow
  655. * - 0 = lies flush with the boundary
  656. * @see https://floating-ui.com/docs/detectOverflow
  657. */
  658. const detectOverflow = detectOverflow$1;
  659. /**
  660. * Modifies the placement by translating the floating element along the
  661. * specified axes.
  662. * A number (shorthand for `mainAxis` or distance), or an axes configuration
  663. * object may be passed.
  664. * @see https://floating-ui.com/docs/offset
  665. */
  666. const offset = offset$1;
  667. /**
  668. * Optimizes the visibility of the floating element by choosing the placement
  669. * that has the most space available automatically, without needing to specify a
  670. * preferred placement. Alternative to `flip`.
  671. * @see https://floating-ui.com/docs/autoPlacement
  672. */
  673. const autoPlacement = autoPlacement$1;
  674. /**
  675. * Optimizes the visibility of the floating element by shifting it in order to
  676. * keep it in view when it will overflow the clipping boundary.
  677. * @see https://floating-ui.com/docs/shift
  678. */
  679. const shift = shift$1;
  680. /**
  681. * Optimizes the visibility of the floating element by flipping the `placement`
  682. * in order to keep it in view when the preferred placement(s) will overflow the
  683. * clipping boundary. Alternative to `autoPlacement`.
  684. * @see https://floating-ui.com/docs/flip
  685. */
  686. const flip = flip$1;
  687. /**
  688. * Provides data that allows you to change the size of the floating element —
  689. * for instance, prevent it from overflowing the clipping boundary or match the
  690. * width of the reference element.
  691. * @see https://floating-ui.com/docs/size
  692. */
  693. const size = size$1;
  694. /**
  695. * Provides data to hide the floating element in applicable situations, such as
  696. * when it is not in the same clipping context as the reference element.
  697. * @see https://floating-ui.com/docs/hide
  698. */
  699. const hide = hide$1;
  700. /**
  701. * Provides data to position an inner element of the floating element so that it
  702. * appears centered to the reference element.
  703. * @see https://floating-ui.com/docs/arrow
  704. */
  705. const arrow = arrow$1;
  706. /**
  707. * Provides improved positioning for inline reference elements that can span
  708. * over multiple lines, such as hyperlinks or range selections.
  709. * @see https://floating-ui.com/docs/inline
  710. */
  711. const inline = inline$1;
  712. /**
  713. * Built-in `limiter` that will stop `shift()` at a certain point.
  714. */
  715. const limitShift = limitShift$1;
  716. /**
  717. * Computes the `x` and `y` coordinates that will place the floating element
  718. * next to a given reference element.
  719. */
  720. const computePosition = (reference, floating, options) => {
  721. // This caches the expensive `getClippingElementAncestors` function so that
  722. // multiple lifecycle resets re-use the same result. It only lives for a
  723. // single call. If other functions become expensive, we can add them as well.
  724. const cache = new Map();
  725. const mergedOptions = {
  726. platform,
  727. ...options
  728. };
  729. const platformWithCache = {
  730. ...mergedOptions.platform,
  731. _c: cache
  732. };
  733. return computePosition$1(reference, floating, {
  734. ...mergedOptions,
  735. platform: platformWithCache
  736. });
  737. };
  738. export { arrow, autoPlacement, autoUpdate, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, platform, shift, size };