floating-ui.core.browser.mjs 39 KB

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