popper-utils.js 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. /**!
  2. * @fileOverview Kickass library to create and place poppers near their reference elements.
  3. * @version 1.12.5
  4. * @license
  5. * Copyright (c) 2016 Federico Zivolo and contributors
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in all
  15. * copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. * SOFTWARE.
  24. */
  25. /**
  26. * Get CSS computed property of the given element
  27. * @method
  28. * @memberof Popper.Utils
  29. * @argument {Eement} element
  30. * @argument {String} property
  31. */
  32. function getStyleComputedProperty(element, property) {
  33. if (element.nodeType !== 1) {
  34. return [];
  35. }
  36. // NOTE: 1 DOM access here
  37. const css = window.getComputedStyle(element, null);
  38. return property ? css[property] : css;
  39. }
  40. /**
  41. * Returns the parentNode or the host of the element
  42. * @method
  43. * @memberof Popper.Utils
  44. * @argument {Element} element
  45. * @returns {Element} parent
  46. */
  47. function getParentNode(element) {
  48. if (element.nodeName === 'HTML') {
  49. return element;
  50. }
  51. return element.parentNode || element.host;
  52. }
  53. /**
  54. * Returns the scrolling parent of the given element
  55. * @method
  56. * @memberof Popper.Utils
  57. * @argument {Element} element
  58. * @returns {Element} scroll parent
  59. */
  60. function getScrollParent(element) {
  61. // Return body, `getScroll` will take care to get the correct `scrollTop` from it
  62. if (!element || ['HTML', 'BODY', '#document'].indexOf(element.nodeName) !== -1) {
  63. return window.document.body;
  64. }
  65. // Firefox want us to check `-x` and `-y` variations as well
  66. const { overflow, overflowX, overflowY } = getStyleComputedProperty(element);
  67. if (/(auto|scroll)/.test(overflow + overflowY + overflowX)) {
  68. return element;
  69. }
  70. return getScrollParent(getParentNode(element));
  71. }
  72. /**
  73. * Returns the offset parent of the given element
  74. * @method
  75. * @memberof Popper.Utils
  76. * @argument {Element} element
  77. * @returns {Element} offset parent
  78. */
  79. function getOffsetParent(element) {
  80. // NOTE: 1 DOM access here
  81. const offsetParent = element && element.offsetParent;
  82. const nodeName = offsetParent && offsetParent.nodeName;
  83. if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') {
  84. return window.document.documentElement;
  85. }
  86. // .offsetParent will return the closest TD or TABLE in case
  87. // no offsetParent is present, I hate this job...
  88. if (['TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') {
  89. return getOffsetParent(offsetParent);
  90. }
  91. return offsetParent;
  92. }
  93. function isOffsetContainer(element) {
  94. const { nodeName } = element;
  95. if (nodeName === 'BODY') {
  96. return false;
  97. }
  98. return nodeName === 'HTML' || getOffsetParent(element.firstElementChild) === element;
  99. }
  100. /**
  101. * Finds the root node (document, shadowDOM root) of the given element
  102. * @method
  103. * @memberof Popper.Utils
  104. * @argument {Element} node
  105. * @returns {Element} root node
  106. */
  107. function getRoot(node) {
  108. if (node.parentNode !== null) {
  109. return getRoot(node.parentNode);
  110. }
  111. return node;
  112. }
  113. /**
  114. * Finds the offset parent common to the two provided nodes
  115. * @method
  116. * @memberof Popper.Utils
  117. * @argument {Element} element1
  118. * @argument {Element} element2
  119. * @returns {Element} common offset parent
  120. */
  121. function findCommonOffsetParent(element1, element2) {
  122. // This check is needed to avoid errors in case one of the elements isn't defined for any reason
  123. if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) {
  124. return window.document.documentElement;
  125. }
  126. // Here we make sure to give as "start" the element that comes first in the DOM
  127. const order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING;
  128. const start = order ? element1 : element2;
  129. const end = order ? element2 : element1;
  130. // Get common ancestor container
  131. const range = document.createRange();
  132. range.setStart(start, 0);
  133. range.setEnd(end, 0);
  134. const { commonAncestorContainer } = range;
  135. // Both nodes are inside #document
  136. if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) {
  137. if (isOffsetContainer(commonAncestorContainer)) {
  138. return commonAncestorContainer;
  139. }
  140. return getOffsetParent(commonAncestorContainer);
  141. }
  142. // one of the nodes is inside shadowDOM, find which one
  143. const element1root = getRoot(element1);
  144. if (element1root.host) {
  145. return findCommonOffsetParent(element1root.host, element2);
  146. } else {
  147. return findCommonOffsetParent(element1, getRoot(element2).host);
  148. }
  149. }
  150. /**
  151. * Gets the scroll value of the given element in the given side (top and left)
  152. * @method
  153. * @memberof Popper.Utils
  154. * @argument {Element} element
  155. * @argument {String} side `top` or `left`
  156. * @returns {number} amount of scrolled pixels
  157. */
  158. function getScroll(element, side = 'top') {
  159. const upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft';
  160. const nodeName = element.nodeName;
  161. if (nodeName === 'BODY' || nodeName === 'HTML') {
  162. const html = window.document.documentElement;
  163. const scrollingElement = window.document.scrollingElement || html;
  164. return scrollingElement[upperSide];
  165. }
  166. return element[upperSide];
  167. }
  168. /*
  169. * Sum or subtract the element scroll values (left and top) from a given rect object
  170. * @method
  171. * @memberof Popper.Utils
  172. * @param {Object} rect - Rect object you want to change
  173. * @param {HTMLElement} element - The element from the function reads the scroll values
  174. * @param {Boolean} subtract - set to true if you want to subtract the scroll values
  175. * @return {Object} rect - The modifier rect object
  176. */
  177. function includeScroll(rect, element, subtract = false) {
  178. const scrollTop = getScroll(element, 'top');
  179. const scrollLeft = getScroll(element, 'left');
  180. const modifier = subtract ? -1 : 1;
  181. rect.top += scrollTop * modifier;
  182. rect.bottom += scrollTop * modifier;
  183. rect.left += scrollLeft * modifier;
  184. rect.right += scrollLeft * modifier;
  185. return rect;
  186. }
  187. /*
  188. * Helper to detect borders of a given element
  189. * @method
  190. * @memberof Popper.Utils
  191. * @param {CSSStyleDeclaration} styles
  192. * Result of `getStyleComputedProperty` on the given element
  193. * @param {String} axis - `x` or `y`
  194. * @return {number} borders - The borders size of the given axis
  195. */
  196. function getBordersSize(styles, axis) {
  197. const sideA = axis === 'x' ? 'Left' : 'Top';
  198. const sideB = sideA === 'Left' ? 'Right' : 'Bottom';
  199. return +styles[`border${sideA}Width`].split('px')[0] + +styles[`border${sideB}Width`].split('px')[0];
  200. }
  201. /**
  202. * Tells if you are running Internet Explorer 10
  203. * @method
  204. * @memberof Popper.Utils
  205. * @returns {Boolean} isIE10
  206. */
  207. let isIE10 = undefined;
  208. var isIE10$1 = function () {
  209. if (isIE10 === undefined) {
  210. isIE10 = navigator.appVersion.indexOf('MSIE 10') !== -1;
  211. }
  212. return isIE10;
  213. };
  214. function getSize(axis, body, html, computedStyle) {
  215. return Math.max(body[`offset${axis}`], body[`scroll${axis}`], html[`client${axis}`], html[`offset${axis}`], html[`scroll${axis}`], isIE10$1() ? html[`offset${axis}`] + computedStyle[`margin${axis === 'Height' ? 'Top' : 'Left'}`] + computedStyle[`margin${axis === 'Height' ? 'Bottom' : 'Right'}`] : 0);
  216. }
  217. function getWindowSizes() {
  218. const body = window.document.body;
  219. const html = window.document.documentElement;
  220. const computedStyle = isIE10$1() && window.getComputedStyle(html);
  221. return {
  222. height: getSize('Height', body, html, computedStyle),
  223. width: getSize('Width', body, html, computedStyle)
  224. };
  225. }
  226. var _extends = Object.assign || function (target) {
  227. for (var i = 1; i < arguments.length; i++) {
  228. var source = arguments[i];
  229. for (var key in source) {
  230. if (Object.prototype.hasOwnProperty.call(source, key)) {
  231. target[key] = source[key];
  232. }
  233. }
  234. }
  235. return target;
  236. };
  237. /**
  238. * Given element offsets, generate an output similar to getBoundingClientRect
  239. * @method
  240. * @memberof Popper.Utils
  241. * @argument {Object} offsets
  242. * @returns {Object} ClientRect like output
  243. */
  244. function getClientRect(offsets) {
  245. return _extends({}, offsets, {
  246. right: offsets.left + offsets.width,
  247. bottom: offsets.top + offsets.height
  248. });
  249. }
  250. /**
  251. * Get bounding client rect of given element
  252. * @method
  253. * @memberof Popper.Utils
  254. * @param {HTMLElement} element
  255. * @return {Object} client rect
  256. */
  257. function getBoundingClientRect(element) {
  258. let rect = {};
  259. // IE10 10 FIX: Please, don't ask, the element isn't
  260. // considered in DOM in some circumstances...
  261. // This isn't reproducible in IE10 compatibility mode of IE11
  262. if (isIE10$1()) {
  263. try {
  264. rect = element.getBoundingClientRect();
  265. const scrollTop = getScroll(element, 'top');
  266. const scrollLeft = getScroll(element, 'left');
  267. rect.top += scrollTop;
  268. rect.left += scrollLeft;
  269. rect.bottom += scrollTop;
  270. rect.right += scrollLeft;
  271. } catch (err) {}
  272. } else {
  273. rect = element.getBoundingClientRect();
  274. }
  275. const result = {
  276. left: rect.left,
  277. top: rect.top,
  278. width: rect.right - rect.left,
  279. height: rect.bottom - rect.top
  280. };
  281. // subtract scrollbar size from sizes
  282. const sizes = element.nodeName === 'HTML' ? getWindowSizes() : {};
  283. const width = sizes.width || element.clientWidth || result.right - result.left;
  284. const height = sizes.height || element.clientHeight || result.bottom - result.top;
  285. let horizScrollbar = element.offsetWidth - width;
  286. let vertScrollbar = element.offsetHeight - height;
  287. // if an hypothetical scrollbar is detected, we must be sure it's not a `border`
  288. // we make this check conditional for performance reasons
  289. if (horizScrollbar || vertScrollbar) {
  290. const styles = getStyleComputedProperty(element);
  291. horizScrollbar -= getBordersSize(styles, 'x');
  292. vertScrollbar -= getBordersSize(styles, 'y');
  293. result.width -= horizScrollbar;
  294. result.height -= vertScrollbar;
  295. }
  296. return getClientRect(result);
  297. }
  298. function getOffsetRectRelativeToArbitraryNode(children, parent) {
  299. const isIE10 = isIE10$1();
  300. const isHTML = parent.nodeName === 'HTML';
  301. const childrenRect = getBoundingClientRect(children);
  302. const parentRect = getBoundingClientRect(parent);
  303. const scrollParent = getScrollParent(children);
  304. const styles = getStyleComputedProperty(parent);
  305. const borderTopWidth = +styles.borderTopWidth.split('px')[0];
  306. const borderLeftWidth = +styles.borderLeftWidth.split('px')[0];
  307. let offsets = getClientRect({
  308. top: childrenRect.top - parentRect.top - borderTopWidth,
  309. left: childrenRect.left - parentRect.left - borderLeftWidth,
  310. width: childrenRect.width,
  311. height: childrenRect.height
  312. });
  313. offsets.marginTop = 0;
  314. offsets.marginLeft = 0;
  315. // Subtract margins of documentElement in case it's being used as parent
  316. // we do this only on HTML because it's the only element that behaves
  317. // differently when margins are applied to it. The margins are included in
  318. // the box of the documentElement, in the other cases not.
  319. if (!isIE10 && isHTML) {
  320. const marginTop = +styles.marginTop.split('px')[0];
  321. const marginLeft = +styles.marginLeft.split('px')[0];
  322. offsets.top -= borderTopWidth - marginTop;
  323. offsets.bottom -= borderTopWidth - marginTop;
  324. offsets.left -= borderLeftWidth - marginLeft;
  325. offsets.right -= borderLeftWidth - marginLeft;
  326. // Attach marginTop and marginLeft because in some circumstances we may need them
  327. offsets.marginTop = marginTop;
  328. offsets.marginLeft = marginLeft;
  329. }
  330. if (isIE10 ? parent.contains(scrollParent) : parent === scrollParent && scrollParent.nodeName !== 'BODY') {
  331. offsets = includeScroll(offsets, parent);
  332. }
  333. return offsets;
  334. }
  335. function getViewportOffsetRectRelativeToArtbitraryNode(element) {
  336. const html = window.document.documentElement;
  337. const relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html);
  338. const width = Math.max(html.clientWidth, window.innerWidth || 0);
  339. const height = Math.max(html.clientHeight, window.innerHeight || 0);
  340. const scrollTop = getScroll(html);
  341. const scrollLeft = getScroll(html, 'left');
  342. const offset = {
  343. top: scrollTop - relativeOffset.top + relativeOffset.marginTop,
  344. left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft,
  345. width,
  346. height
  347. };
  348. return getClientRect(offset);
  349. }
  350. /**
  351. * Check if the given element is fixed or is inside a fixed parent
  352. * @method
  353. * @memberof Popper.Utils
  354. * @argument {Element} element
  355. * @argument {Element} customContainer
  356. * @returns {Boolean} answer to "isFixed?"
  357. */
  358. function isFixed(element) {
  359. const nodeName = element.nodeName;
  360. if (nodeName === 'BODY' || nodeName === 'HTML') {
  361. return false;
  362. }
  363. if (getStyleComputedProperty(element, 'position') === 'fixed') {
  364. return true;
  365. }
  366. return isFixed(getParentNode(element));
  367. }
  368. /**
  369. * Computed the boundaries limits and return them
  370. * @method
  371. * @memberof Popper.Utils
  372. * @param {HTMLElement} popper
  373. * @param {HTMLElement} reference
  374. * @param {number} padding
  375. * @param {HTMLElement} boundariesElement - Element used to define the boundaries
  376. * @returns {Object} Coordinates of the boundaries
  377. */
  378. function getBoundaries(popper, reference, padding, boundariesElement) {
  379. // NOTE: 1 DOM access here
  380. let boundaries = { top: 0, left: 0 };
  381. const offsetParent = findCommonOffsetParent(popper, reference);
  382. // Handle viewport case
  383. if (boundariesElement === 'viewport') {
  384. boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent);
  385. } else {
  386. // Handle other cases based on DOM element used as boundaries
  387. let boundariesNode;
  388. if (boundariesElement === 'scrollParent') {
  389. boundariesNode = getScrollParent(getParentNode(popper));
  390. if (boundariesNode.nodeName === 'BODY') {
  391. boundariesNode = window.document.documentElement;
  392. }
  393. } else if (boundariesElement === 'window') {
  394. boundariesNode = window.document.documentElement;
  395. } else {
  396. boundariesNode = boundariesElement;
  397. }
  398. const offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent);
  399. // In case of HTML, we need a different computation
  400. if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) {
  401. const { height, width } = getWindowSizes();
  402. boundaries.top += offsets.top - offsets.marginTop;
  403. boundaries.bottom = height + offsets.top;
  404. boundaries.left += offsets.left - offsets.marginLeft;
  405. boundaries.right = width + offsets.left;
  406. } else {
  407. // for all the other DOM elements, this one is good
  408. boundaries = offsets;
  409. }
  410. }
  411. // Add paddings
  412. boundaries.left += padding;
  413. boundaries.top += padding;
  414. boundaries.right -= padding;
  415. boundaries.bottom -= padding;
  416. return boundaries;
  417. }
  418. function getArea({ width, height }) {
  419. return width * height;
  420. }
  421. /**
  422. * Utility used to transform the `auto` placement to the placement with more
  423. * available space.
  424. * @method
  425. * @memberof Popper.Utils
  426. * @argument {Object} data - The data object generated by update method
  427. * @argument {Object} options - Modifiers configuration and options
  428. * @returns {Object} The data object, properly modified
  429. */
  430. function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement, padding = 0) {
  431. if (placement.indexOf('auto') === -1) {
  432. return placement;
  433. }
  434. const boundaries = getBoundaries(popper, reference, padding, boundariesElement);
  435. const rects = {
  436. top: {
  437. width: boundaries.width,
  438. height: refRect.top - boundaries.top
  439. },
  440. right: {
  441. width: boundaries.right - refRect.right,
  442. height: boundaries.height
  443. },
  444. bottom: {
  445. width: boundaries.width,
  446. height: boundaries.bottom - refRect.bottom
  447. },
  448. left: {
  449. width: refRect.left - boundaries.left,
  450. height: boundaries.height
  451. }
  452. };
  453. const sortedAreas = Object.keys(rects).map(key => _extends({
  454. key
  455. }, rects[key], {
  456. area: getArea(rects[key])
  457. })).sort((a, b) => b.area - a.area);
  458. const filteredAreas = sortedAreas.filter(({ width, height }) => width >= popper.clientWidth && height >= popper.clientHeight);
  459. const computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key;
  460. const variation = placement.split('-')[1];
  461. return computedPlacement + (variation ? `-${variation}` : '');
  462. }
  463. const nativeHints = ['native code', '[object MutationObserverConstructor]'];
  464. /**
  465. * Determine if a function is implemented natively (as opposed to a polyfill).
  466. * @method
  467. * @memberof Popper.Utils
  468. * @argument {Function | undefined} fn the function to check
  469. * @returns {Boolean}
  470. */
  471. var isNative = (fn => nativeHints.some(hint => (fn || '').toString().indexOf(hint) > -1));
  472. const isBrowser = typeof window !== 'undefined';
  473. const longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox'];
  474. let timeoutDuration = 0;
  475. for (let i = 0; i < longerTimeoutBrowsers.length; i += 1) {
  476. if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) {
  477. timeoutDuration = 1;
  478. break;
  479. }
  480. }
  481. function microtaskDebounce(fn) {
  482. let scheduled = false;
  483. let i = 0;
  484. const elem = document.createElement('span');
  485. // MutationObserver provides a mechanism for scheduling microtasks, which
  486. // are scheduled *before* the next task. This gives us a way to debounce
  487. // a function but ensure it's called *before* the next paint.
  488. const observer = new MutationObserver(() => {
  489. fn();
  490. scheduled = false;
  491. });
  492. observer.observe(elem, { attributes: true });
  493. return () => {
  494. if (!scheduled) {
  495. scheduled = true;
  496. elem.setAttribute('x-index', i);
  497. i = i + 1; // don't use compund (+=) because it doesn't get optimized in V8
  498. }
  499. };
  500. }
  501. function taskDebounce(fn) {
  502. let scheduled = false;
  503. return () => {
  504. if (!scheduled) {
  505. scheduled = true;
  506. setTimeout(() => {
  507. scheduled = false;
  508. fn();
  509. }, timeoutDuration);
  510. }
  511. };
  512. }
  513. // It's common for MutationObserver polyfills to be seen in the wild, however
  514. // these rely on Mutation Events which only occur when an element is connected
  515. // to the DOM. The algorithm used in this module does not use a connected element,
  516. // and so we must ensure that a *native* MutationObserver is available.
  517. const supportsNativeMutationObserver = isBrowser && isNative(window.MutationObserver);
  518. /**
  519. * Create a debounced version of a method, that's asynchronously deferred
  520. * but called in the minimum time possible.
  521. *
  522. * @method
  523. * @memberof Popper.Utils
  524. * @argument {Function} fn
  525. * @returns {Function}
  526. */
  527. var debounce = supportsNativeMutationObserver ? microtaskDebounce : taskDebounce;
  528. /**
  529. * Mimics the `find` method of Array
  530. * @method
  531. * @memberof Popper.Utils
  532. * @argument {Array} arr
  533. * @argument prop
  534. * @argument value
  535. * @returns index or -1
  536. */
  537. function find(arr, check) {
  538. // use native find if supported
  539. if (Array.prototype.find) {
  540. return arr.find(check);
  541. }
  542. // use `filter` to obtain the same behavior of `find`
  543. return arr.filter(check)[0];
  544. }
  545. /**
  546. * Return the index of the matching object
  547. * @method
  548. * @memberof Popper.Utils
  549. * @argument {Array} arr
  550. * @argument prop
  551. * @argument value
  552. * @returns index or -1
  553. */
  554. function findIndex(arr, prop, value) {
  555. // use native findIndex if supported
  556. if (Array.prototype.findIndex) {
  557. return arr.findIndex(cur => cur[prop] === value);
  558. }
  559. // use `find` + `indexOf` if `findIndex` isn't supported
  560. const match = find(arr, obj => obj[prop] === value);
  561. return arr.indexOf(match);
  562. }
  563. /**
  564. * Get the position of the given element, relative to its offset parent
  565. * @method
  566. * @memberof Popper.Utils
  567. * @param {Element} element
  568. * @return {Object} position - Coordinates of the element and its `scrollTop`
  569. */
  570. function getOffsetRect(element) {
  571. let elementRect;
  572. if (element.nodeName === 'HTML') {
  573. const { width, height } = getWindowSizes();
  574. elementRect = {
  575. width,
  576. height,
  577. left: 0,
  578. top: 0
  579. };
  580. } else {
  581. elementRect = {
  582. width: element.offsetWidth,
  583. height: element.offsetHeight,
  584. left: element.offsetLeft,
  585. top: element.offsetTop
  586. };
  587. }
  588. // position
  589. return getClientRect(elementRect);
  590. }
  591. /**
  592. * Get the outer sizes of the given element (offset size + margins)
  593. * @method
  594. * @memberof Popper.Utils
  595. * @argument {Element} element
  596. * @returns {Object} object containing width and height properties
  597. */
  598. function getOuterSizes(element) {
  599. const styles = window.getComputedStyle(element);
  600. const x = parseFloat(styles.marginTop) + parseFloat(styles.marginBottom);
  601. const y = parseFloat(styles.marginLeft) + parseFloat(styles.marginRight);
  602. const result = {
  603. width: element.offsetWidth + y,
  604. height: element.offsetHeight + x
  605. };
  606. return result;
  607. }
  608. /**
  609. * Get the opposite placement of the given one
  610. * @method
  611. * @memberof Popper.Utils
  612. * @argument {String} placement
  613. * @returns {String} flipped placement
  614. */
  615. function getOppositePlacement(placement) {
  616. const hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' };
  617. return placement.replace(/left|right|bottom|top/g, matched => hash[matched]);
  618. }
  619. /**
  620. * Get offsets to the popper
  621. * @method
  622. * @memberof Popper.Utils
  623. * @param {Object} position - CSS position the Popper will get applied
  624. * @param {HTMLElement} popper - the popper element
  625. * @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this)
  626. * @param {String} placement - one of the valid placement options
  627. * @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper
  628. */
  629. function getPopperOffsets(popper, referenceOffsets, placement) {
  630. placement = placement.split('-')[0];
  631. // Get popper node sizes
  632. const popperRect = getOuterSizes(popper);
  633. // Add position, width and height to our offsets object
  634. const popperOffsets = {
  635. width: popperRect.width,
  636. height: popperRect.height
  637. };
  638. // depending by the popper placement we have to compute its offsets slightly differently
  639. const isHoriz = ['right', 'left'].indexOf(placement) !== -1;
  640. const mainSide = isHoriz ? 'top' : 'left';
  641. const secondarySide = isHoriz ? 'left' : 'top';
  642. const measurement = isHoriz ? 'height' : 'width';
  643. const secondaryMeasurement = !isHoriz ? 'height' : 'width';
  644. popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2;
  645. if (placement === secondarySide) {
  646. popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement];
  647. } else {
  648. popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)];
  649. }
  650. return popperOffsets;
  651. }
  652. /**
  653. * Get offsets to the reference element
  654. * @method
  655. * @memberof Popper.Utils
  656. * @param {Object} state
  657. * @param {Element} popper - the popper element
  658. * @param {Element} reference - the reference element (the popper will be relative to this)
  659. * @returns {Object} An object containing the offsets which will be applied to the popper
  660. */
  661. function getReferenceOffsets(state, popper, reference) {
  662. const commonOffsetParent = findCommonOffsetParent(popper, reference);
  663. return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent);
  664. }
  665. /**
  666. * Get the prefixed supported property name
  667. * @method
  668. * @memberof Popper.Utils
  669. * @argument {String} property (camelCase)
  670. * @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix)
  671. */
  672. function getSupportedPropertyName(property) {
  673. const prefixes = [false, 'ms', 'Webkit', 'Moz', 'O'];
  674. const upperProp = property.charAt(0).toUpperCase() + property.slice(1);
  675. for (let i = 0; i < prefixes.length - 1; i++) {
  676. const prefix = prefixes[i];
  677. const toCheck = prefix ? `${prefix}${upperProp}` : property;
  678. if (typeof window.document.body.style[toCheck] !== 'undefined') {
  679. return toCheck;
  680. }
  681. }
  682. return null;
  683. }
  684. /**
  685. * Check if the given variable is a function
  686. * @method
  687. * @memberof Popper.Utils
  688. * @argument {Any} functionToCheck - variable to check
  689. * @returns {Boolean} answer to: is a function?
  690. */
  691. function isFunction(functionToCheck) {
  692. const getType = {};
  693. return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
  694. }
  695. /**
  696. * Helper used to know if the given modifier is enabled.
  697. * @method
  698. * @memberof Popper.Utils
  699. * @returns {Boolean}
  700. */
  701. function isModifierEnabled(modifiers, modifierName) {
  702. return modifiers.some(({ name, enabled }) => enabled && name === modifierName);
  703. }
  704. /**
  705. * Helper used to know if the given modifier depends from another one.<br />
  706. * It checks if the needed modifier is listed and enabled.
  707. * @method
  708. * @memberof Popper.Utils
  709. * @param {Array} modifiers - list of modifiers
  710. * @param {String} requestingName - name of requesting modifier
  711. * @param {String} requestedName - name of requested modifier
  712. * @returns {Boolean}
  713. */
  714. function isModifierRequired(modifiers, requestingName, requestedName) {
  715. const requesting = find(modifiers, ({ name }) => name === requestingName);
  716. const isRequired = !!requesting && modifiers.some(modifier => {
  717. return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order;
  718. });
  719. if (!isRequired) {
  720. const requesting = `\`${requestingName}\``;
  721. const requested = `\`${requestedName}\``;
  722. console.warn(`${requested} modifier is required by ${requesting} modifier in order to work, be sure to include it before ${requesting}!`);
  723. }
  724. return isRequired;
  725. }
  726. /**
  727. * Tells if a given input is a number
  728. * @method
  729. * @memberof Popper.Utils
  730. * @param {*} input to check
  731. * @return {Boolean}
  732. */
  733. function isNumeric(n) {
  734. return n !== '' && !isNaN(parseFloat(n)) && isFinite(n);
  735. }
  736. /**
  737. * Remove event listeners used to update the popper position
  738. * @method
  739. * @memberof Popper.Utils
  740. * @private
  741. */
  742. function removeEventListeners(reference, state) {
  743. // Remove resize event listener on window
  744. window.removeEventListener('resize', state.updateBound);
  745. // Remove scroll event listener on scroll parents
  746. state.scrollParents.forEach(target => {
  747. target.removeEventListener('scroll', state.updateBound);
  748. });
  749. // Reset state
  750. state.updateBound = null;
  751. state.scrollParents = [];
  752. state.scrollElement = null;
  753. state.eventsEnabled = false;
  754. return state;
  755. }
  756. /**
  757. * Loop trough the list of modifiers and run them in order,
  758. * each of them will then edit the data object.
  759. * @method
  760. * @memberof Popper.Utils
  761. * @param {dataObject} data
  762. * @param {Array} modifiers
  763. * @param {String} ends - Optional modifier name used as stopper
  764. * @returns {dataObject}
  765. */
  766. function runModifiers(modifiers, data, ends) {
  767. const modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends));
  768. modifiersToRun.forEach(modifier => {
  769. if (modifier.function) {
  770. console.warn('`modifier.function` is deprecated, use `modifier.fn`!');
  771. }
  772. const fn = modifier.function || modifier.fn;
  773. if (modifier.enabled && isFunction(fn)) {
  774. // Add properties to offsets to make them a complete clientRect object
  775. // we do this before each modifier to make sure the previous one doesn't
  776. // mess with these values
  777. data.offsets.popper = getClientRect(data.offsets.popper);
  778. data.offsets.reference = getClientRect(data.offsets.reference);
  779. data = fn(data, modifier);
  780. }
  781. });
  782. return data;
  783. }
  784. /**
  785. * Set the attributes to the given popper
  786. * @method
  787. * @memberof Popper.Utils
  788. * @argument {Element} element - Element to apply the attributes to
  789. * @argument {Object} styles
  790. * Object with a list of properties and values which will be applied to the element
  791. */
  792. function setAttributes(element, attributes) {
  793. Object.keys(attributes).forEach(function (prop) {
  794. const value = attributes[prop];
  795. if (value !== false) {
  796. element.setAttribute(prop, attributes[prop]);
  797. } else {
  798. element.removeAttribute(prop);
  799. }
  800. });
  801. }
  802. /**
  803. * Set the style to the given popper
  804. * @method
  805. * @memberof Popper.Utils
  806. * @argument {Element} element - Element to apply the style to
  807. * @argument {Object} styles
  808. * Object with a list of properties and values which will be applied to the element
  809. */
  810. function setStyles(element, styles) {
  811. Object.keys(styles).forEach(prop => {
  812. let unit = '';
  813. // add unit if the value is numeric and is one of the following
  814. if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) {
  815. unit = 'px';
  816. }
  817. element.style[prop] = styles[prop] + unit;
  818. });
  819. }
  820. function attachToScrollParents(scrollParent, event, callback, scrollParents) {
  821. const isBody = scrollParent.nodeName === 'BODY';
  822. const target = isBody ? window : scrollParent;
  823. target.addEventListener(event, callback, { passive: true });
  824. if (!isBody) {
  825. attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents);
  826. }
  827. scrollParents.push(target);
  828. }
  829. /**
  830. * Setup needed event listeners used to update the popper position
  831. * @method
  832. * @memberof Popper.Utils
  833. * @private
  834. */
  835. function setupEventListeners(reference, options, state, updateBound) {
  836. // Resize event listener on window
  837. state.updateBound = updateBound;
  838. window.addEventListener('resize', state.updateBound, { passive: true });
  839. // Scroll event listener on scroll parents
  840. const scrollElement = getScrollParent(reference);
  841. attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents);
  842. state.scrollElement = scrollElement;
  843. state.eventsEnabled = true;
  844. return state;
  845. }
  846. // This is here just for backward compatibility with versions lower than v1.10.3
  847. // you should import the utilities using named exports, if you want them all use:
  848. // ```
  849. // import * as PopperUtils from 'popper-utils';
  850. // ```
  851. // The default export will be removed in the next major version.
  852. var index = {
  853. computeAutoPlacement,
  854. debounce,
  855. findIndex,
  856. getBordersSize,
  857. getBoundaries,
  858. getBoundingClientRect,
  859. getClientRect,
  860. getOffsetParent,
  861. getOffsetRect,
  862. getOffsetRectRelativeToArbitraryNode,
  863. getOuterSizes,
  864. getParentNode,
  865. getPopperOffsets,
  866. getReferenceOffsets,
  867. getScroll,
  868. getScrollParent,
  869. getStyleComputedProperty,
  870. getSupportedPropertyName,
  871. getWindowSizes,
  872. isFixed,
  873. isFunction,
  874. isModifierEnabled,
  875. isModifierRequired,
  876. isNative,
  877. isNumeric,
  878. removeEventListeners,
  879. runModifiers,
  880. setAttributes,
  881. setStyles,
  882. setupEventListeners
  883. };
  884. export { computeAutoPlacement, debounce, findIndex, getBordersSize, getBoundaries, getBoundingClientRect, getClientRect, getOffsetParent, getOffsetRect, getOffsetRectRelativeToArbitraryNode, getOuterSizes, getParentNode, getPopperOffsets, getReferenceOffsets, getScroll, getScrollParent, getStyleComputedProperty, getSupportedPropertyName, getWindowSizes, isFixed, isFunction, isModifierEnabled, isModifierRequired, isNative, isNumeric, removeEventListeners, runModifiers, setAttributes, setStyles, setupEventListeners };export default index;
  885. //# sourceMappingURL=popper-utils.js.map