floating-ui.core.esm.js 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  1. import { getSideAxis, getAlignmentAxis, getAxisLength, getSide, getAlignment, evaluate, getPaddingObject, rectToClientRect, min, clamp, placements, getAlignmentSides, getOppositeAlignmentPlacement, getOppositePlacement, getExpandedPlacements, getOppositeAxisPlacements, sides, max, getOppositeAxis } from '@floating-ui/utils';
  2. export { rectToClientRect } from '@floating-ui/utils';
  3. function computeCoordsFromPlacement(_ref, placement, rtl) {
  4. let {
  5. reference,
  6. floating
  7. } = _ref;
  8. const sideAxis = getSideAxis(placement);
  9. const alignmentAxis = getAlignmentAxis(placement);
  10. const alignLength = getAxisLength(alignmentAxis);
  11. const side = getSide(placement);
  12. const isVertical = sideAxis === 'y';
  13. const commonX = reference.x + reference.width / 2 - floating.width / 2;
  14. const commonY = reference.y + reference.height / 2 - floating.height / 2;
  15. const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;
  16. let coords;
  17. switch (side) {
  18. case 'top':
  19. coords = {
  20. x: commonX,
  21. y: reference.y - floating.height
  22. };
  23. break;
  24. case 'bottom':
  25. coords = {
  26. x: commonX,
  27. y: reference.y + reference.height
  28. };
  29. break;
  30. case 'right':
  31. coords = {
  32. x: reference.x + reference.width,
  33. y: commonY
  34. };
  35. break;
  36. case 'left':
  37. coords = {
  38. x: reference.x - floating.width,
  39. y: commonY
  40. };
  41. break;
  42. default:
  43. coords = {
  44. x: reference.x,
  45. y: reference.y
  46. };
  47. }
  48. switch (getAlignment(placement)) {
  49. case 'start':
  50. coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);
  51. break;
  52. case 'end':
  53. coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);
  54. break;
  55. }
  56. return coords;
  57. }
  58. /**
  59. * Resolves with an object of overflow side offsets that determine how much the
  60. * element is overflowing a given clipping boundary on each side.
  61. * - positive = overflowing the boundary by that number of pixels
  62. * - negative = how many pixels left before it will overflow
  63. * - 0 = lies flush with the boundary
  64. * @see https://floating-ui.com/docs/detectOverflow
  65. */
  66. async function detectOverflow(state, options) {
  67. var _await$platform$isEle;
  68. if (options === void 0) {
  69. options = {};
  70. }
  71. const {
  72. x,
  73. y,
  74. platform,
  75. rects,
  76. elements,
  77. strategy
  78. } = state;
  79. const {
  80. boundary = 'clippingAncestors',
  81. rootBoundary = 'viewport',
  82. elementContext = 'floating',
  83. altBoundary = false,
  84. padding = 0
  85. } = evaluate(options, state);
  86. const paddingObject = getPaddingObject(padding);
  87. const altContext = elementContext === 'floating' ? 'reference' : 'floating';
  88. const element = elements[altBoundary ? altContext : elementContext];
  89. const clippingClientRect = rectToClientRect(await platform.getClippingRect({
  90. 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))),
  91. boundary,
  92. rootBoundary,
  93. strategy
  94. }));
  95. const rect = elementContext === 'floating' ? {
  96. x,
  97. y,
  98. width: rects.floating.width,
  99. height: rects.floating.height
  100. } : rects.reference;
  101. const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating));
  102. const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || {
  103. x: 1,
  104. y: 1
  105. } : {
  106. x: 1,
  107. y: 1
  108. };
  109. const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({
  110. elements,
  111. rect,
  112. offsetParent,
  113. strategy
  114. }) : rect);
  115. return {
  116. top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,
  117. bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,
  118. left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,
  119. right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x
  120. };
  121. }
  122. // Maximum number of resets that can occur before bailing to avoid infinite reset loops.
  123. const MAX_RESET_COUNT = 50;
  124. /**
  125. * Computes the `x` and `y` coordinates that will place the floating element
  126. * next to a given reference element.
  127. *
  128. * This export does not have any `platform` interface logic. You will need to
  129. * write one for the platform you are using Floating UI with.
  130. */
  131. const computePosition = async (reference, floating, config) => {
  132. const {
  133. placement = 'bottom',
  134. strategy = 'absolute',
  135. middleware = [],
  136. platform
  137. } = config;
  138. const platformWithDetectOverflow = platform.detectOverflow ? platform : {
  139. ...platform,
  140. detectOverflow
  141. };
  142. const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating));
  143. let rects = await platform.getElementRects({
  144. reference,
  145. floating,
  146. strategy
  147. });
  148. let {
  149. x,
  150. y
  151. } = computeCoordsFromPlacement(rects, placement, rtl);
  152. let statefulPlacement = placement;
  153. let resetCount = 0;
  154. const middlewareData = {};
  155. for (let i = 0; i < middleware.length; i++) {
  156. const currentMiddleware = middleware[i];
  157. if (!currentMiddleware) {
  158. continue;
  159. }
  160. const {
  161. name,
  162. fn
  163. } = currentMiddleware;
  164. const {
  165. x: nextX,
  166. y: nextY,
  167. data,
  168. reset
  169. } = await fn({
  170. x,
  171. y,
  172. initialPlacement: placement,
  173. placement: statefulPlacement,
  174. strategy,
  175. middlewareData,
  176. rects,
  177. platform: platformWithDetectOverflow,
  178. elements: {
  179. reference,
  180. floating
  181. }
  182. });
  183. x = nextX != null ? nextX : x;
  184. y = nextY != null ? nextY : y;
  185. middlewareData[name] = {
  186. ...middlewareData[name],
  187. ...data
  188. };
  189. if (reset && resetCount < MAX_RESET_COUNT) {
  190. resetCount++;
  191. if (typeof reset === 'object') {
  192. if (reset.placement) {
  193. statefulPlacement = reset.placement;
  194. }
  195. if (reset.rects) {
  196. rects = reset.rects === true ? await platform.getElementRects({
  197. reference,
  198. floating,
  199. strategy
  200. }) : reset.rects;
  201. }
  202. ({
  203. x,
  204. y
  205. } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));
  206. }
  207. i = -1;
  208. }
  209. }
  210. return {
  211. x,
  212. y,
  213. placement: statefulPlacement,
  214. strategy,
  215. middlewareData
  216. };
  217. };
  218. /**
  219. * Provides data to position an inner element of the floating element so that it
  220. * appears centered to the reference element.
  221. * @see https://floating-ui.com/docs/arrow
  222. */
  223. const arrow = options => ({
  224. name: 'arrow',
  225. options,
  226. async fn(state) {
  227. const {
  228. x,
  229. y,
  230. placement,
  231. rects,
  232. platform,
  233. elements,
  234. middlewareData
  235. } = state;
  236. // Since `element` is required, we don't Partial<> the type.
  237. const {
  238. element,
  239. padding = 0
  240. } = evaluate(options, state) || {};
  241. if (element == null) {
  242. return {};
  243. }
  244. const paddingObject = getPaddingObject(padding);
  245. const coords = {
  246. x,
  247. y
  248. };
  249. const axis = getAlignmentAxis(placement);
  250. const length = getAxisLength(axis);
  251. const arrowDimensions = await platform.getDimensions(element);
  252. const isYAxis = axis === 'y';
  253. const minProp = isYAxis ? 'top' : 'left';
  254. const maxProp = isYAxis ? 'bottom' : 'right';
  255. const clientProp = isYAxis ? 'clientHeight' : 'clientWidth';
  256. const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length];
  257. const startDiff = coords[axis] - rects.reference[axis];
  258. const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element));
  259. let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0;
  260. // DOM platform can return `window` as the `offsetParent`.
  261. if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) {
  262. clientSize = elements.floating[clientProp] || rects.floating[length];
  263. }
  264. const centerToReference = endDiff / 2 - startDiff / 2;
  265. // If the padding is large enough that it causes the arrow to no longer be
  266. // centered, modify the padding so that it is centered.
  267. const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1;
  268. const minPadding = min(paddingObject[minProp], largestPossiblePadding);
  269. const maxPadding = min(paddingObject[maxProp], largestPossiblePadding);
  270. // Make sure the arrow doesn't overflow the floating element if the center
  271. // point is outside the floating element's bounds.
  272. const min$1 = minPadding;
  273. const max = clientSize - arrowDimensions[length] - maxPadding;
  274. const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference;
  275. const offset = clamp(min$1, center, max);
  276. // If the reference is small enough that the arrow's padding causes it to
  277. // to point to nothing for an aligned placement, adjust the offset of the
  278. // floating element itself. To ensure `shift()` continues to take action,
  279. // a single reset is performed when this is true.
  280. const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0;
  281. const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0;
  282. return {
  283. [axis]: coords[axis] + alignmentOffset,
  284. data: {
  285. [axis]: offset,
  286. centerOffset: center - offset - alignmentOffset,
  287. ...(shouldAddOffset && {
  288. alignmentOffset
  289. })
  290. },
  291. reset: shouldAddOffset
  292. };
  293. }
  294. });
  295. function getPlacementList(alignment, autoAlignment, allowedPlacements) {
  296. const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement);
  297. return allowedPlacementsSortedByAlignment.filter(placement => {
  298. if (alignment) {
  299. return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false);
  300. }
  301. return true;
  302. });
  303. }
  304. /**
  305. * Optimizes the visibility of the floating element by choosing the placement
  306. * that has the most space available automatically, without needing to specify a
  307. * preferred placement. Alternative to `flip`.
  308. * @see https://floating-ui.com/docs/autoPlacement
  309. */
  310. const autoPlacement = function (options) {
  311. if (options === void 0) {
  312. options = {};
  313. }
  314. return {
  315. name: 'autoPlacement',
  316. options,
  317. async fn(state) {
  318. var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE;
  319. const {
  320. rects,
  321. middlewareData,
  322. placement,
  323. platform,
  324. elements
  325. } = state;
  326. const {
  327. crossAxis = false,
  328. alignment,
  329. allowedPlacements = placements,
  330. autoAlignment = true,
  331. ...detectOverflowOptions
  332. } = evaluate(options, state);
  333. const placements$1 = alignment !== undefined || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements;
  334. const overflow = await platform.detectOverflow(state, detectOverflowOptions);
  335. const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0;
  336. const currentPlacement = placements$1[currentIndex];
  337. if (currentPlacement == null) {
  338. return {};
  339. }
  340. const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)));
  341. // Make `computeCoords` start from the right place.
  342. if (placement !== currentPlacement) {
  343. return {
  344. reset: {
  345. placement: placements$1[0]
  346. }
  347. };
  348. }
  349. const currentOverflows = [overflow[getSide(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]]];
  350. const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), {
  351. placement: currentPlacement,
  352. overflows: currentOverflows
  353. }];
  354. const nextPlacement = placements$1[currentIndex + 1];
  355. // There are more placements to check.
  356. if (nextPlacement) {
  357. return {
  358. data: {
  359. index: currentIndex + 1,
  360. overflows: allOverflows
  361. },
  362. reset: {
  363. placement: nextPlacement
  364. }
  365. };
  366. }
  367. const placementsSortedByMostSpace = allOverflows.map(d => {
  368. const alignment = getAlignment(d.placement);
  369. return [d.placement, alignment && crossAxis ?
  370. // Check along the mainAxis and main crossAxis side.
  371. d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) :
  372. // Check only the mainAxis.
  373. d.overflows[0], d.overflows];
  374. }).sort((a, b) => a[1] - b[1]);
  375. const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0,
  376. // Aligned placements should not check their opposite crossAxis
  377. // side.
  378. getAlignment(d[0]) ? 2 : 3).every(v => v <= 0));
  379. const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0];
  380. if (resetPlacement !== placement) {
  381. return {
  382. data: {
  383. index: currentIndex + 1,
  384. overflows: allOverflows
  385. },
  386. reset: {
  387. placement: resetPlacement
  388. }
  389. };
  390. }
  391. return {};
  392. }
  393. };
  394. };
  395. /**
  396. * Optimizes the visibility of the floating element by flipping the `placement`
  397. * in order to keep it in view when the preferred placement(s) will overflow the
  398. * clipping boundary. Alternative to `autoPlacement`.
  399. * @see https://floating-ui.com/docs/flip
  400. */
  401. const flip = function (options) {
  402. if (options === void 0) {
  403. options = {};
  404. }
  405. return {
  406. name: 'flip',
  407. options,
  408. async fn(state) {
  409. var _middlewareData$arrow, _middlewareData$flip;
  410. const {
  411. placement,
  412. middlewareData,
  413. rects,
  414. initialPlacement,
  415. platform,
  416. elements
  417. } = state;
  418. const {
  419. mainAxis: checkMainAxis = true,
  420. crossAxis: checkCrossAxis = true,
  421. fallbackPlacements: specifiedFallbackPlacements,
  422. fallbackStrategy = 'bestFit',
  423. fallbackAxisSideDirection = 'none',
  424. flipAlignment = true,
  425. ...detectOverflowOptions
  426. } = evaluate(options, state);
  427. // If a reset by the arrow was caused due to an alignment offset being
  428. // added, we should skip any logic now since `flip()` has already done its
  429. // work.
  430. // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643
  431. if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
  432. return {};
  433. }
  434. const side = getSide(placement);
  435. const initialSideAxis = getSideAxis(initialPlacement);
  436. const isBasePlacement = getSide(initialPlacement) === initialPlacement;
  437. const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));
  438. const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));
  439. const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== 'none';
  440. if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) {
  441. fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));
  442. }
  443. const placements = [initialPlacement, ...fallbackPlacements];
  444. const overflow = await platform.detectOverflow(state, detectOverflowOptions);
  445. const overflows = [];
  446. let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];
  447. if (checkMainAxis) {
  448. overflows.push(overflow[side]);
  449. }
  450. if (checkCrossAxis) {
  451. const sides = getAlignmentSides(placement, rects, rtl);
  452. overflows.push(overflow[sides[0]], overflow[sides[1]]);
  453. }
  454. overflowsData = [...overflowsData, {
  455. placement,
  456. overflows
  457. }];
  458. // One or more sides is overflowing.
  459. if (!overflows.every(side => side <= 0)) {
  460. var _middlewareData$flip2, _overflowsData$filter;
  461. const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;
  462. const nextPlacement = placements[nextIndex];
  463. if (nextPlacement) {
  464. const ignoreCrossAxisOverflow = checkCrossAxis === 'alignment' ? initialSideAxis !== getSideAxis(nextPlacement) : false;
  465. if (!ignoreCrossAxisOverflow ||
  466. // We leave the current main axis only if every placement on that axis
  467. // overflows the main axis.
  468. overflowsData.every(d => getSideAxis(d.placement) === initialSideAxis ? d.overflows[0] > 0 : true)) {
  469. // Try next placement and re-run the lifecycle.
  470. return {
  471. data: {
  472. index: nextIndex,
  473. overflows: overflowsData
  474. },
  475. reset: {
  476. placement: nextPlacement
  477. }
  478. };
  479. }
  480. }
  481. // First, find the candidates that fit on the mainAxis side of overflow,
  482. // then find the placement that fits the best on the main crossAxis side.
  483. let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement;
  484. // Otherwise fallback.
  485. if (!resetPlacement) {
  486. switch (fallbackStrategy) {
  487. case 'bestFit':
  488. {
  489. var _overflowsData$filter2;
  490. const placement = (_overflowsData$filter2 = overflowsData.filter(d => {
  491. if (hasFallbackAxisSideDirection) {
  492. const currentSideAxis = getSideAxis(d.placement);
  493. return currentSideAxis === initialSideAxis ||
  494. // Create a bias to the `y` side axis due to horizontal
  495. // reading directions favoring greater width.
  496. currentSideAxis === 'y';
  497. }
  498. return true;
  499. }).map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0];
  500. if (placement) {
  501. resetPlacement = placement;
  502. }
  503. break;
  504. }
  505. case 'initialPlacement':
  506. resetPlacement = initialPlacement;
  507. break;
  508. }
  509. }
  510. if (placement !== resetPlacement) {
  511. return {
  512. reset: {
  513. placement: resetPlacement
  514. }
  515. };
  516. }
  517. }
  518. return {};
  519. }
  520. };
  521. };
  522. function getSideOffsets(overflow, rect) {
  523. return {
  524. top: overflow.top - rect.height,
  525. right: overflow.right - rect.width,
  526. bottom: overflow.bottom - rect.height,
  527. left: overflow.left - rect.width
  528. };
  529. }
  530. function isAnySideFullyClipped(overflow) {
  531. return sides.some(side => overflow[side] >= 0);
  532. }
  533. /**
  534. * Provides data to hide the floating element in applicable situations, such as
  535. * when it is not in the same clipping context as the reference element.
  536. * @see https://floating-ui.com/docs/hide
  537. */
  538. const hide = function (options) {
  539. if (options === void 0) {
  540. options = {};
  541. }
  542. return {
  543. name: 'hide',
  544. options,
  545. async fn(state) {
  546. const {
  547. rects,
  548. platform
  549. } = state;
  550. const {
  551. strategy = 'referenceHidden',
  552. ...detectOverflowOptions
  553. } = evaluate(options, state);
  554. switch (strategy) {
  555. case 'referenceHidden':
  556. {
  557. const overflow = await platform.detectOverflow(state, {
  558. ...detectOverflowOptions,
  559. elementContext: 'reference'
  560. });
  561. const offsets = getSideOffsets(overflow, rects.reference);
  562. return {
  563. data: {
  564. referenceHiddenOffsets: offsets,
  565. referenceHidden: isAnySideFullyClipped(offsets)
  566. }
  567. };
  568. }
  569. case 'escaped':
  570. {
  571. const overflow = await platform.detectOverflow(state, {
  572. ...detectOverflowOptions,
  573. altBoundary: true
  574. });
  575. const offsets = getSideOffsets(overflow, rects.floating);
  576. return {
  577. data: {
  578. escapedOffsets: offsets,
  579. escaped: isAnySideFullyClipped(offsets)
  580. }
  581. };
  582. }
  583. default:
  584. {
  585. return {};
  586. }
  587. }
  588. }
  589. };
  590. };
  591. function getBoundingRect(rects) {
  592. const minX = min(...rects.map(rect => rect.left));
  593. const minY = min(...rects.map(rect => rect.top));
  594. const maxX = max(...rects.map(rect => rect.right));
  595. const maxY = max(...rects.map(rect => rect.bottom));
  596. return {
  597. x: minX,
  598. y: minY,
  599. width: maxX - minX,
  600. height: maxY - minY
  601. };
  602. }
  603. function getRectsByLine(rects) {
  604. const sortedRects = rects.slice().sort((a, b) => a.y - b.y);
  605. const groups = [];
  606. let prevRect = null;
  607. for (let i = 0; i < sortedRects.length; i++) {
  608. const rect = sortedRects[i];
  609. if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) {
  610. groups.push([rect]);
  611. } else {
  612. groups[groups.length - 1].push(rect);
  613. }
  614. prevRect = rect;
  615. }
  616. return groups.map(rect => rectToClientRect(getBoundingRect(rect)));
  617. }
  618. /**
  619. * Provides improved positioning for inline reference elements that can span
  620. * over multiple lines, such as hyperlinks or range selections.
  621. * @see https://floating-ui.com/docs/inline
  622. */
  623. const inline = function (options) {
  624. if (options === void 0) {
  625. options = {};
  626. }
  627. return {
  628. name: 'inline',
  629. options,
  630. async fn(state) {
  631. const {
  632. placement,
  633. elements,
  634. rects,
  635. platform,
  636. strategy
  637. } = state;
  638. // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a
  639. // ClientRect's bounds, despite the event listener being triggered. A
  640. // padding of 2 seems to handle this issue.
  641. const {
  642. padding = 2,
  643. x,
  644. y
  645. } = evaluate(options, state);
  646. const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []);
  647. const clientRects = getRectsByLine(nativeClientRects);
  648. const fallback = rectToClientRect(getBoundingRect(nativeClientRects));
  649. const paddingObject = getPaddingObject(padding);
  650. function getBoundingClientRect() {
  651. // There are two rects and they are disjoined.
  652. if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) {
  653. // Find the first rect in which the point is fully inside.
  654. return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback;
  655. }
  656. // There are 2 or more connected rects.
  657. if (clientRects.length >= 2) {
  658. if (getSideAxis(placement) === 'y') {
  659. const firstRect = clientRects[0];
  660. const lastRect = clientRects[clientRects.length - 1];
  661. const isTop = getSide(placement) === 'top';
  662. const top = firstRect.top;
  663. const bottom = lastRect.bottom;
  664. const left = isTop ? firstRect.left : lastRect.left;
  665. const right = isTop ? firstRect.right : lastRect.right;
  666. const width = right - left;
  667. const height = bottom - top;
  668. return {
  669. top,
  670. bottom,
  671. left,
  672. right,
  673. width,
  674. height,
  675. x: left,
  676. y: top
  677. };
  678. }
  679. const isLeftSide = getSide(placement) === 'left';
  680. const maxRight = max(...clientRects.map(rect => rect.right));
  681. const minLeft = min(...clientRects.map(rect => rect.left));
  682. const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight);
  683. const top = measureRects[0].top;
  684. const bottom = measureRects[measureRects.length - 1].bottom;
  685. const left = minLeft;
  686. const right = maxRight;
  687. const width = right - left;
  688. const height = bottom - top;
  689. return {
  690. top,
  691. bottom,
  692. left,
  693. right,
  694. width,
  695. height,
  696. x: left,
  697. y: top
  698. };
  699. }
  700. return fallback;
  701. }
  702. const resetRects = await platform.getElementRects({
  703. reference: {
  704. getBoundingClientRect
  705. },
  706. floating: elements.floating,
  707. strategy
  708. });
  709. if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) {
  710. return {
  711. reset: {
  712. rects: resetRects
  713. }
  714. };
  715. }
  716. return {};
  717. }
  718. };
  719. };
  720. const originSides = /*#__PURE__*/new Set(['left', 'top']);
  721. // For type backwards-compatibility, the `OffsetOptions` type was also
  722. // Derivable.
  723. async function convertValueToCoords(state, options) {
  724. const {
  725. placement,
  726. platform,
  727. elements
  728. } = state;
  729. const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));
  730. const side = getSide(placement);
  731. const alignment = getAlignment(placement);
  732. const isVertical = getSideAxis(placement) === 'y';
  733. const mainAxisMulti = originSides.has(side) ? -1 : 1;
  734. const crossAxisMulti = rtl && isVertical ? -1 : 1;
  735. const rawValue = evaluate(options, state);
  736. // eslint-disable-next-line prefer-const
  737. let {
  738. mainAxis,
  739. crossAxis,
  740. alignmentAxis
  741. } = typeof rawValue === 'number' ? {
  742. mainAxis: rawValue,
  743. crossAxis: 0,
  744. alignmentAxis: null
  745. } : {
  746. mainAxis: rawValue.mainAxis || 0,
  747. crossAxis: rawValue.crossAxis || 0,
  748. alignmentAxis: rawValue.alignmentAxis
  749. };
  750. if (alignment && typeof alignmentAxis === 'number') {
  751. crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis;
  752. }
  753. return isVertical ? {
  754. x: crossAxis * crossAxisMulti,
  755. y: mainAxis * mainAxisMulti
  756. } : {
  757. x: mainAxis * mainAxisMulti,
  758. y: crossAxis * crossAxisMulti
  759. };
  760. }
  761. /**
  762. * Modifies the placement by translating the floating element along the
  763. * specified axes.
  764. * A number (shorthand for `mainAxis` or distance), or an axes configuration
  765. * object may be passed.
  766. * @see https://floating-ui.com/docs/offset
  767. */
  768. const offset = function (options) {
  769. if (options === void 0) {
  770. options = 0;
  771. }
  772. return {
  773. name: 'offset',
  774. options,
  775. async fn(state) {
  776. var _middlewareData$offse, _middlewareData$arrow;
  777. const {
  778. x,
  779. y,
  780. placement,
  781. middlewareData
  782. } = state;
  783. const diffCoords = await convertValueToCoords(state, options);
  784. // If the placement is the same and the arrow caused an alignment offset
  785. // then we don't need to change the positioning coordinates.
  786. if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
  787. return {};
  788. }
  789. return {
  790. x: x + diffCoords.x,
  791. y: y + diffCoords.y,
  792. data: {
  793. ...diffCoords,
  794. placement
  795. }
  796. };
  797. }
  798. };
  799. };
  800. /**
  801. * Optimizes the visibility of the floating element by shifting it in order to
  802. * keep it in view when it will overflow the clipping boundary.
  803. * @see https://floating-ui.com/docs/shift
  804. */
  805. const shift = function (options) {
  806. if (options === void 0) {
  807. options = {};
  808. }
  809. return {
  810. name: 'shift',
  811. options,
  812. async fn(state) {
  813. const {
  814. x,
  815. y,
  816. placement,
  817. platform
  818. } = state;
  819. const {
  820. mainAxis: checkMainAxis = true,
  821. crossAxis: checkCrossAxis = false,
  822. limiter = {
  823. fn: _ref => {
  824. let {
  825. x,
  826. y
  827. } = _ref;
  828. return {
  829. x,
  830. y
  831. };
  832. }
  833. },
  834. ...detectOverflowOptions
  835. } = evaluate(options, state);
  836. const coords = {
  837. x,
  838. y
  839. };
  840. const overflow = await platform.detectOverflow(state, detectOverflowOptions);
  841. const crossAxis = getSideAxis(getSide(placement));
  842. const mainAxis = getOppositeAxis(crossAxis);
  843. let mainAxisCoord = coords[mainAxis];
  844. let crossAxisCoord = coords[crossAxis];
  845. if (checkMainAxis) {
  846. const minSide = mainAxis === 'y' ? 'top' : 'left';
  847. const maxSide = mainAxis === 'y' ? 'bottom' : 'right';
  848. const min = mainAxisCoord + overflow[minSide];
  849. const max = mainAxisCoord - overflow[maxSide];
  850. mainAxisCoord = clamp(min, mainAxisCoord, max);
  851. }
  852. if (checkCrossAxis) {
  853. const minSide = crossAxis === 'y' ? 'top' : 'left';
  854. const maxSide = crossAxis === 'y' ? 'bottom' : 'right';
  855. const min = crossAxisCoord + overflow[minSide];
  856. const max = crossAxisCoord - overflow[maxSide];
  857. crossAxisCoord = clamp(min, crossAxisCoord, max);
  858. }
  859. const limitedCoords = limiter.fn({
  860. ...state,
  861. [mainAxis]: mainAxisCoord,
  862. [crossAxis]: crossAxisCoord
  863. });
  864. return {
  865. ...limitedCoords,
  866. data: {
  867. x: limitedCoords.x - x,
  868. y: limitedCoords.y - y,
  869. enabled: {
  870. [mainAxis]: checkMainAxis,
  871. [crossAxis]: checkCrossAxis
  872. }
  873. }
  874. };
  875. }
  876. };
  877. };
  878. /**
  879. * Built-in `limiter` that will stop `shift()` at a certain point.
  880. */
  881. const limitShift = function (options) {
  882. if (options === void 0) {
  883. options = {};
  884. }
  885. return {
  886. options,
  887. fn(state) {
  888. const {
  889. x,
  890. y,
  891. placement,
  892. rects,
  893. middlewareData
  894. } = state;
  895. const {
  896. offset = 0,
  897. mainAxis: checkMainAxis = true,
  898. crossAxis: checkCrossAxis = true
  899. } = evaluate(options, state);
  900. const coords = {
  901. x,
  902. y
  903. };
  904. const crossAxis = getSideAxis(placement);
  905. const mainAxis = getOppositeAxis(crossAxis);
  906. let mainAxisCoord = coords[mainAxis];
  907. let crossAxisCoord = coords[crossAxis];
  908. const rawOffset = evaluate(offset, state);
  909. const computedOffset = typeof rawOffset === 'number' ? {
  910. mainAxis: rawOffset,
  911. crossAxis: 0
  912. } : {
  913. mainAxis: 0,
  914. crossAxis: 0,
  915. ...rawOffset
  916. };
  917. if (checkMainAxis) {
  918. const len = mainAxis === 'y' ? 'height' : 'width';
  919. const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis;
  920. const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis;
  921. if (mainAxisCoord < limitMin) {
  922. mainAxisCoord = limitMin;
  923. } else if (mainAxisCoord > limitMax) {
  924. mainAxisCoord = limitMax;
  925. }
  926. }
  927. if (checkCrossAxis) {
  928. var _middlewareData$offse, _middlewareData$offse2;
  929. const len = mainAxis === 'y' ? 'width' : 'height';
  930. const isOriginSide = originSides.has(getSide(placement));
  931. const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis);
  932. const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0);
  933. if (crossAxisCoord < limitMin) {
  934. crossAxisCoord = limitMin;
  935. } else if (crossAxisCoord > limitMax) {
  936. crossAxisCoord = limitMax;
  937. }
  938. }
  939. return {
  940. [mainAxis]: mainAxisCoord,
  941. [crossAxis]: crossAxisCoord
  942. };
  943. }
  944. };
  945. };
  946. /**
  947. * Provides data that allows you to change the size of the floating element —
  948. * for instance, prevent it from overflowing the clipping boundary or match the
  949. * width of the reference element.
  950. * @see https://floating-ui.com/docs/size
  951. */
  952. const size = function (options) {
  953. if (options === void 0) {
  954. options = {};
  955. }
  956. return {
  957. name: 'size',
  958. options,
  959. async fn(state) {
  960. var _state$middlewareData, _state$middlewareData2;
  961. const {
  962. placement,
  963. rects,
  964. platform,
  965. elements
  966. } = state;
  967. const {
  968. apply = () => {},
  969. ...detectOverflowOptions
  970. } = evaluate(options, state);
  971. const overflow = await platform.detectOverflow(state, detectOverflowOptions);
  972. const side = getSide(placement);
  973. const alignment = getAlignment(placement);
  974. const isYAxis = getSideAxis(placement) === 'y';
  975. const {
  976. width,
  977. height
  978. } = rects.floating;
  979. let heightSide;
  980. let widthSide;
  981. if (side === 'top' || side === 'bottom') {
  982. heightSide = side;
  983. widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right';
  984. } else {
  985. widthSide = side;
  986. heightSide = alignment === 'end' ? 'top' : 'bottom';
  987. }
  988. const maximumClippingHeight = height - overflow.top - overflow.bottom;
  989. const maximumClippingWidth = width - overflow.left - overflow.right;
  990. const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight);
  991. const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth);
  992. const noShift = !state.middlewareData.shift;
  993. let availableHeight = overflowAvailableHeight;
  994. let availableWidth = overflowAvailableWidth;
  995. if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) {
  996. availableWidth = maximumClippingWidth;
  997. }
  998. if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) {
  999. availableHeight = maximumClippingHeight;
  1000. }
  1001. if (noShift && !alignment) {
  1002. const xMin = max(overflow.left, 0);
  1003. const xMax = max(overflow.right, 0);
  1004. const yMin = max(overflow.top, 0);
  1005. const yMax = max(overflow.bottom, 0);
  1006. if (isYAxis) {
  1007. availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right));
  1008. } else {
  1009. availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom));
  1010. }
  1011. }
  1012. await apply({
  1013. ...state,
  1014. availableWidth,
  1015. availableHeight
  1016. });
  1017. const nextDimensions = await platform.getDimensions(elements.floating);
  1018. if (width !== nextDimensions.width || height !== nextDimensions.height) {
  1019. return {
  1020. reset: {
  1021. rects: true
  1022. }
  1023. };
  1024. }
  1025. return {};
  1026. }
  1027. };
  1028. };
  1029. export { arrow, autoPlacement, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, shift, size };