You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1063 lines
33KB

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