Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

2463 lines
83KB

  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. var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && typeof navigator !== 'undefined';
  26. const timeoutDuration = function () {
  27. const longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox'];
  28. for (let i = 0; i < longerTimeoutBrowsers.length; i += 1) {
  29. if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) {
  30. return 1;
  31. }
  32. }
  33. return 0;
  34. }();
  35. function microtaskDebounce(fn) {
  36. let called = false;
  37. return () => {
  38. if (called) {
  39. return;
  40. }
  41. called = true;
  42. window.Promise.resolve().then(() => {
  43. called = false;
  44. fn();
  45. });
  46. };
  47. }
  48. function taskDebounce(fn) {
  49. let scheduled = false;
  50. return () => {
  51. if (!scheduled) {
  52. scheduled = true;
  53. setTimeout(() => {
  54. scheduled = false;
  55. fn();
  56. }, timeoutDuration);
  57. }
  58. };
  59. }
  60. const supportsMicroTasks = isBrowser && window.Promise;
  61. /**
  62. * Create a debounced version of a method, that's asynchronously deferred
  63. * but called in the minimum time possible.
  64. *
  65. * @method
  66. * @memberof Popper.Utils
  67. * @argument {Function} fn
  68. * @returns {Function}
  69. */
  70. var debounce = supportsMicroTasks ? microtaskDebounce : taskDebounce;
  71. /**
  72. * Check if the given variable is a function
  73. * @method
  74. * @memberof Popper.Utils
  75. * @argument {Any} functionToCheck - variable to check
  76. * @returns {Boolean} answer to: is a function?
  77. */
  78. function isFunction(functionToCheck) {
  79. const getType = {};
  80. return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
  81. }
  82. /**
  83. * Get CSS computed property of the given element
  84. * @method
  85. * @memberof Popper.Utils
  86. * @argument {Eement} element
  87. * @argument {String} property
  88. */
  89. function getStyleComputedProperty(element, property) {
  90. if (element.nodeType !== 1) {
  91. return [];
  92. }
  93. // NOTE: 1 DOM access here
  94. const window = element.ownerDocument.defaultView;
  95. const css = window.getComputedStyle(element, null);
  96. return property ? css[property] : css;
  97. }
  98. /**
  99. * Returns the parentNode or the host of the element
  100. * @method
  101. * @memberof Popper.Utils
  102. * @argument {Element} element
  103. * @returns {Element} parent
  104. */
  105. function getParentNode(element) {
  106. if (element.nodeName === 'HTML') {
  107. return element;
  108. }
  109. return element.parentNode || element.host;
  110. }
  111. /**
  112. * Returns the scrolling parent of the given element
  113. * @method
  114. * @memberof Popper.Utils
  115. * @argument {Element} element
  116. * @returns {Element} scroll parent
  117. */
  118. function getScrollParent(element) {
  119. // Return body, `getScroll` will take care to get the correct `scrollTop` from it
  120. if (!element) {
  121. return document.body;
  122. }
  123. switch (element.nodeName) {
  124. case 'HTML':
  125. case 'BODY':
  126. return element.ownerDocument.body;
  127. case '#document':
  128. return element.body;
  129. }
  130. // Firefox want us to check `-x` and `-y` variations as well
  131. const { overflow, overflowX, overflowY } = getStyleComputedProperty(element);
  132. if (/(auto|scroll|overlay)/.test(overflow + overflowY + overflowX)) {
  133. return element;
  134. }
  135. return getScrollParent(getParentNode(element));
  136. }
  137. /**
  138. * Returns the reference node of the reference object, or the reference object itself.
  139. * @method
  140. * @memberof Popper.Utils
  141. * @param {Element|Object} reference - the reference element (the popper will be relative to this)
  142. * @returns {Element} parent
  143. */
  144. function getReferenceNode(reference) {
  145. return reference && reference.referenceNode ? reference.referenceNode : reference;
  146. }
  147. const isIE11 = isBrowser && !!(window.MSInputMethodContext && document.documentMode);
  148. const isIE10 = isBrowser && /MSIE 10/.test(navigator.userAgent);
  149. /**
  150. * Determines if the browser is Internet Explorer
  151. * @method
  152. * @memberof Popper.Utils
  153. * @param {Number} version to check
  154. * @returns {Boolean} isIE
  155. */
  156. function isIE(version) {
  157. if (version === 11) {
  158. return isIE11;
  159. }
  160. if (version === 10) {
  161. return isIE10;
  162. }
  163. return isIE11 || isIE10;
  164. }
  165. /**
  166. * Returns the offset parent of the given element
  167. * @method
  168. * @memberof Popper.Utils
  169. * @argument {Element} element
  170. * @returns {Element} offset parent
  171. */
  172. function getOffsetParent(element) {
  173. if (!element) {
  174. return document.documentElement;
  175. }
  176. const noOffsetParent = isIE(10) ? document.body : null;
  177. // NOTE: 1 DOM access here
  178. let offsetParent = element.offsetParent || null;
  179. // Skip hidden elements which don't have an offsetParent
  180. while (offsetParent === noOffsetParent && element.nextElementSibling) {
  181. offsetParent = (element = element.nextElementSibling).offsetParent;
  182. }
  183. const nodeName = offsetParent && offsetParent.nodeName;
  184. if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') {
  185. return element ? element.ownerDocument.documentElement : document.documentElement;
  186. }
  187. // .offsetParent will return the closest TH, TD or TABLE in case
  188. // no offsetParent is present, I hate this job...
  189. if (['TH', 'TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') {
  190. return getOffsetParent(offsetParent);
  191. }
  192. return offsetParent;
  193. }
  194. function isOffsetContainer(element) {
  195. const { nodeName } = element;
  196. if (nodeName === 'BODY') {
  197. return false;
  198. }
  199. return nodeName === 'HTML' || getOffsetParent(element.firstElementChild) === element;
  200. }
  201. /**
  202. * Finds the root node (document, shadowDOM root) of the given element
  203. * @method
  204. * @memberof Popper.Utils
  205. * @argument {Element} node
  206. * @returns {Element} root node
  207. */
  208. function getRoot(node) {
  209. if (node.parentNode !== null) {
  210. return getRoot(node.parentNode);
  211. }
  212. return node;
  213. }
  214. /**
  215. * Finds the offset parent common to the two provided nodes
  216. * @method
  217. * @memberof Popper.Utils
  218. * @argument {Element} element1
  219. * @argument {Element} element2
  220. * @returns {Element} common offset parent
  221. */
  222. function findCommonOffsetParent(element1, element2) {
  223. // This check is needed to avoid errors in case one of the elements isn't defined for any reason
  224. if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) {
  225. return document.documentElement;
  226. }
  227. // Here we make sure to give as "start" the element that comes first in the DOM
  228. const order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING;
  229. const start = order ? element1 : element2;
  230. const end = order ? element2 : element1;
  231. // Get common ancestor container
  232. const range = document.createRange();
  233. range.setStart(start, 0);
  234. range.setEnd(end, 0);
  235. const { commonAncestorContainer } = range;
  236. // Both nodes are inside #document
  237. if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) {
  238. if (isOffsetContainer(commonAncestorContainer)) {
  239. return commonAncestorContainer;
  240. }
  241. return getOffsetParent(commonAncestorContainer);
  242. }
  243. // one of the nodes is inside shadowDOM, find which one
  244. const element1root = getRoot(element1);
  245. if (element1root.host) {
  246. return findCommonOffsetParent(element1root.host, element2);
  247. } else {
  248. return findCommonOffsetParent(element1, getRoot(element2).host);
  249. }
  250. }
  251. /**
  252. * Gets the scroll value of the given element in the given side (top and left)
  253. * @method
  254. * @memberof Popper.Utils
  255. * @argument {Element} element
  256. * @argument {String} side `top` or `left`
  257. * @returns {number} amount of scrolled pixels
  258. */
  259. function getScroll(element, side = 'top') {
  260. const upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft';
  261. const nodeName = element.nodeName;
  262. if (nodeName === 'BODY' || nodeName === 'HTML') {
  263. const html = element.ownerDocument.documentElement;
  264. const scrollingElement = element.ownerDocument.scrollingElement || html;
  265. return scrollingElement[upperSide];
  266. }
  267. return element[upperSide];
  268. }
  269. /*
  270. * Sum or subtract the element scroll values (left and top) from a given rect object
  271. * @method
  272. * @memberof Popper.Utils
  273. * @param {Object} rect - Rect object you want to change
  274. * @param {HTMLElement} element - The element from the function reads the scroll values
  275. * @param {Boolean} subtract - set to true if you want to subtract the scroll values
  276. * @return {Object} rect - The modifier rect object
  277. */
  278. function includeScroll(rect, element, subtract = false) {
  279. const scrollTop = getScroll(element, 'top');
  280. const scrollLeft = getScroll(element, 'left');
  281. const modifier = subtract ? -1 : 1;
  282. rect.top += scrollTop * modifier;
  283. rect.bottom += scrollTop * modifier;
  284. rect.left += scrollLeft * modifier;
  285. rect.right += scrollLeft * modifier;
  286. return rect;
  287. }
  288. /*
  289. * Helper to detect borders of a given element
  290. * @method
  291. * @memberof Popper.Utils
  292. * @param {CSSStyleDeclaration} styles
  293. * Result of `getStyleComputedProperty` on the given element
  294. * @param {String} axis - `x` or `y`
  295. * @return {number} borders - The borders size of the given axis
  296. */
  297. function getBordersSize(styles, axis) {
  298. const sideA = axis === 'x' ? 'Left' : 'Top';
  299. const sideB = sideA === 'Left' ? 'Right' : 'Bottom';
  300. return parseFloat(styles[`border${sideA}Width`]) + parseFloat(styles[`border${sideB}Width`]);
  301. }
  302. function getSize(axis, body, html, computedStyle) {
  303. 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);
  304. }
  305. function getWindowSizes(document) {
  306. const body = document.body;
  307. const html = document.documentElement;
  308. const computedStyle = isIE(10) && getComputedStyle(html);
  309. return {
  310. height: getSize('Height', body, html, computedStyle),
  311. width: getSize('Width', body, html, computedStyle)
  312. };
  313. }
  314. var _extends = Object.assign || function (target) {
  315. for (var i = 1; i < arguments.length; i++) {
  316. var source = arguments[i];
  317. for (var key in source) {
  318. if (Object.prototype.hasOwnProperty.call(source, key)) {
  319. target[key] = source[key];
  320. }
  321. }
  322. }
  323. return target;
  324. };
  325. /**
  326. * Given element offsets, generate an output similar to getBoundingClientRect
  327. * @method
  328. * @memberof Popper.Utils
  329. * @argument {Object} offsets
  330. * @returns {Object} ClientRect like output
  331. */
  332. function getClientRect(offsets) {
  333. return _extends({}, offsets, {
  334. right: offsets.left + offsets.width,
  335. bottom: offsets.top + offsets.height
  336. });
  337. }
  338. /**
  339. * Get bounding client rect of given element
  340. * @method
  341. * @memberof Popper.Utils
  342. * @param {HTMLElement} element
  343. * @return {Object} client rect
  344. */
  345. function getBoundingClientRect(element) {
  346. let rect = {};
  347. // IE10 10 FIX: Please, don't ask, the element isn't
  348. // considered in DOM in some circumstances...
  349. // This isn't reproducible in IE10 compatibility mode of IE11
  350. try {
  351. if (isIE(10)) {
  352. rect = element.getBoundingClientRect();
  353. const scrollTop = getScroll(element, 'top');
  354. const scrollLeft = getScroll(element, 'left');
  355. rect.top += scrollTop;
  356. rect.left += scrollLeft;
  357. rect.bottom += scrollTop;
  358. rect.right += scrollLeft;
  359. } else {
  360. rect = element.getBoundingClientRect();
  361. }
  362. } catch (e) {}
  363. const result = {
  364. left: rect.left,
  365. top: rect.top,
  366. width: rect.right - rect.left,
  367. height: rect.bottom - rect.top
  368. };
  369. // subtract scrollbar size from sizes
  370. const sizes = element.nodeName === 'HTML' ? getWindowSizes(element.ownerDocument) : {};
  371. const width = sizes.width || element.clientWidth || result.width;
  372. const height = sizes.height || element.clientHeight || result.height;
  373. let horizScrollbar = element.offsetWidth - width;
  374. let vertScrollbar = element.offsetHeight - height;
  375. // if an hypothetical scrollbar is detected, we must be sure it's not a `border`
  376. // we make this check conditional for performance reasons
  377. if (horizScrollbar || vertScrollbar) {
  378. const styles = getStyleComputedProperty(element);
  379. horizScrollbar -= getBordersSize(styles, 'x');
  380. vertScrollbar -= getBordersSize(styles, 'y');
  381. result.width -= horizScrollbar;
  382. result.height -= vertScrollbar;
  383. }
  384. return getClientRect(result);
  385. }
  386. function getOffsetRectRelativeToArbitraryNode(children, parent, fixedPosition = false) {
  387. const isIE10 = isIE(10);
  388. const isHTML = parent.nodeName === 'HTML';
  389. const childrenRect = getBoundingClientRect(children);
  390. const parentRect = getBoundingClientRect(parent);
  391. const scrollParent = getScrollParent(children);
  392. const styles = getStyleComputedProperty(parent);
  393. const borderTopWidth = parseFloat(styles.borderTopWidth);
  394. const borderLeftWidth = parseFloat(styles.borderLeftWidth);
  395. // In cases where the parent is fixed, we must ignore negative scroll in offset calc
  396. if (fixedPosition && isHTML) {
  397. parentRect.top = Math.max(parentRect.top, 0);
  398. parentRect.left = Math.max(parentRect.left, 0);
  399. }
  400. let offsets = getClientRect({
  401. top: childrenRect.top - parentRect.top - borderTopWidth,
  402. left: childrenRect.left - parentRect.left - borderLeftWidth,
  403. width: childrenRect.width,
  404. height: childrenRect.height
  405. });
  406. offsets.marginTop = 0;
  407. offsets.marginLeft = 0;
  408. // Subtract margins of documentElement in case it's being used as parent
  409. // we do this only on HTML because it's the only element that behaves
  410. // differently when margins are applied to it. The margins are included in
  411. // the box of the documentElement, in the other cases not.
  412. if (!isIE10 && isHTML) {
  413. const marginTop = parseFloat(styles.marginTop);
  414. const marginLeft = parseFloat(styles.marginLeft);
  415. offsets.top -= borderTopWidth - marginTop;
  416. offsets.bottom -= borderTopWidth - marginTop;
  417. offsets.left -= borderLeftWidth - marginLeft;
  418. offsets.right -= borderLeftWidth - marginLeft;
  419. // Attach marginTop and marginLeft because in some circumstances we may need them
  420. offsets.marginTop = marginTop;
  421. offsets.marginLeft = marginLeft;
  422. }
  423. if (isIE10 && !fixedPosition ? parent.contains(scrollParent) : parent === scrollParent && scrollParent.nodeName !== 'BODY') {
  424. offsets = includeScroll(offsets, parent);
  425. }
  426. return offsets;
  427. }
  428. function getViewportOffsetRectRelativeToArtbitraryNode(element, excludeScroll = false) {
  429. const html = element.ownerDocument.documentElement;
  430. const relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html);
  431. const width = Math.max(html.clientWidth, window.innerWidth || 0);
  432. const height = Math.max(html.clientHeight, window.innerHeight || 0);
  433. const scrollTop = !excludeScroll ? getScroll(html) : 0;
  434. const scrollLeft = !excludeScroll ? getScroll(html, 'left') : 0;
  435. const offset = {
  436. top: scrollTop - relativeOffset.top + relativeOffset.marginTop,
  437. left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft,
  438. width,
  439. height
  440. };
  441. return getClientRect(offset);
  442. }
  443. /**
  444. * Check if the given element is fixed or is inside a fixed parent
  445. * @method
  446. * @memberof Popper.Utils
  447. * @argument {Element} element
  448. * @argument {Element} customContainer
  449. * @returns {Boolean} answer to "isFixed?"
  450. */
  451. function isFixed(element) {
  452. const nodeName = element.nodeName;
  453. if (nodeName === 'BODY' || nodeName === 'HTML') {
  454. return false;
  455. }
  456. if (getStyleComputedProperty(element, 'position') === 'fixed') {
  457. return true;
  458. }
  459. const parentNode = getParentNode(element);
  460. if (!parentNode) {
  461. return false;
  462. }
  463. return isFixed(parentNode);
  464. }
  465. /**
  466. * Finds the first parent of an element that has a transformed property defined
  467. * @method
  468. * @memberof Popper.Utils
  469. * @argument {Element} element
  470. * @returns {Element} first transformed parent or documentElement
  471. */
  472. function getFixedPositionOffsetParent(element) {
  473. // This check is needed to avoid errors in case one of the elements isn't defined for any reason
  474. if (!element || !element.parentElement || isIE()) {
  475. return document.documentElement;
  476. }
  477. let el = element.parentElement;
  478. while (el && getStyleComputedProperty(el, 'transform') === 'none') {
  479. el = el.parentElement;
  480. }
  481. return el || document.documentElement;
  482. }
  483. /**
  484. * Computed the boundaries limits and return them
  485. * @method
  486. * @memberof Popper.Utils
  487. * @param {HTMLElement} popper
  488. * @param {HTMLElement} reference
  489. * @param {number} padding
  490. * @param {HTMLElement} boundariesElement - Element used to define the boundaries
  491. * @param {Boolean} fixedPosition - Is in fixed position mode
  492. * @returns {Object} Coordinates of the boundaries
  493. */
  494. function getBoundaries(popper, reference, padding, boundariesElement, fixedPosition = false) {
  495. // NOTE: 1 DOM access here
  496. let boundaries = { top: 0, left: 0 };
  497. const offsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, getReferenceNode(reference));
  498. // Handle viewport case
  499. if (boundariesElement === 'viewport') {
  500. boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent, fixedPosition);
  501. } else {
  502. // Handle other cases based on DOM element used as boundaries
  503. let boundariesNode;
  504. if (boundariesElement === 'scrollParent') {
  505. boundariesNode = getScrollParent(getParentNode(reference));
  506. if (boundariesNode.nodeName === 'BODY') {
  507. boundariesNode = popper.ownerDocument.documentElement;
  508. }
  509. } else if (boundariesElement === 'window') {
  510. boundariesNode = popper.ownerDocument.documentElement;
  511. } else {
  512. boundariesNode = boundariesElement;
  513. }
  514. const offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent, fixedPosition);
  515. // In case of HTML, we need a different computation
  516. if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) {
  517. const { height, width } = getWindowSizes(popper.ownerDocument);
  518. boundaries.top += offsets.top - offsets.marginTop;
  519. boundaries.bottom = height + offsets.top;
  520. boundaries.left += offsets.left - offsets.marginLeft;
  521. boundaries.right = width + offsets.left;
  522. } else {
  523. // for all the other DOM elements, this one is good
  524. boundaries = offsets;
  525. }
  526. }
  527. // Add paddings
  528. padding = padding || 0;
  529. const isPaddingNumber = typeof padding === 'number';
  530. boundaries.left += isPaddingNumber ? padding : padding.left || 0;
  531. boundaries.top += isPaddingNumber ? padding : padding.top || 0;
  532. boundaries.right -= isPaddingNumber ? padding : padding.right || 0;
  533. boundaries.bottom -= isPaddingNumber ? padding : padding.bottom || 0;
  534. return boundaries;
  535. }
  536. function getArea({ width, height }) {
  537. return width * height;
  538. }
  539. /**
  540. * Utility used to transform the `auto` placement to the placement with more
  541. * available space.
  542. * @method
  543. * @memberof Popper.Utils
  544. * @argument {Object} data - The data object generated by update method
  545. * @argument {Object} options - Modifiers configuration and options
  546. * @returns {Object} The data object, properly modified
  547. */
  548. function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement, padding = 0) {
  549. if (placement.indexOf('auto') === -1) {
  550. return placement;
  551. }
  552. const boundaries = getBoundaries(popper, reference, padding, boundariesElement);
  553. const rects = {
  554. top: {
  555. width: boundaries.width,
  556. height: refRect.top - boundaries.top
  557. },
  558. right: {
  559. width: boundaries.right - refRect.right,
  560. height: boundaries.height
  561. },
  562. bottom: {
  563. width: boundaries.width,
  564. height: boundaries.bottom - refRect.bottom
  565. },
  566. left: {
  567. width: refRect.left - boundaries.left,
  568. height: boundaries.height
  569. }
  570. };
  571. const sortedAreas = Object.keys(rects).map(key => _extends({
  572. key
  573. }, rects[key], {
  574. area: getArea(rects[key])
  575. })).sort((a, b) => b.area - a.area);
  576. const filteredAreas = sortedAreas.filter(({ width, height }) => width >= popper.clientWidth && height >= popper.clientHeight);
  577. const computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key;
  578. const variation = placement.split('-')[1];
  579. return computedPlacement + (variation ? `-${variation}` : '');
  580. }
  581. /**
  582. * Get offsets to the reference element
  583. * @method
  584. * @memberof Popper.Utils
  585. * @param {Object} state
  586. * @param {Element} popper - the popper element
  587. * @param {Element} reference - the reference element (the popper will be relative to this)
  588. * @param {Element} fixedPosition - is in fixed position mode
  589. * @returns {Object} An object containing the offsets which will be applied to the popper
  590. */
  591. function getReferenceOffsets(state, popper, reference, fixedPosition = null) {
  592. const commonOffsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, getReferenceNode(reference));
  593. return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent, fixedPosition);
  594. }
  595. /**
  596. * Get the outer sizes of the given element (offset size + margins)
  597. * @method
  598. * @memberof Popper.Utils
  599. * @argument {Element} element
  600. * @returns {Object} object containing width and height properties
  601. */
  602. function getOuterSizes(element) {
  603. const window = element.ownerDocument.defaultView;
  604. const styles = window.getComputedStyle(element);
  605. const x = parseFloat(styles.marginTop || 0) + parseFloat(styles.marginBottom || 0);
  606. const y = parseFloat(styles.marginLeft || 0) + parseFloat(styles.marginRight || 0);
  607. const result = {
  608. width: element.offsetWidth + y,
  609. height: element.offsetHeight + x
  610. };
  611. return result;
  612. }
  613. /**
  614. * Get the opposite placement of the given one
  615. * @method
  616. * @memberof Popper.Utils
  617. * @argument {String} placement
  618. * @returns {String} flipped placement
  619. */
  620. function getOppositePlacement(placement) {
  621. const hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' };
  622. return placement.replace(/left|right|bottom|top/g, matched => hash[matched]);
  623. }
  624. /**
  625. * Get offsets to the popper
  626. * @method
  627. * @memberof Popper.Utils
  628. * @param {Object} position - CSS position the Popper will get applied
  629. * @param {HTMLElement} popper - the popper element
  630. * @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this)
  631. * @param {String} placement - one of the valid placement options
  632. * @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper
  633. */
  634. function getPopperOffsets(popper, referenceOffsets, placement) {
  635. placement = placement.split('-')[0];
  636. // Get popper node sizes
  637. const popperRect = getOuterSizes(popper);
  638. // Add position, width and height to our offsets object
  639. const popperOffsets = {
  640. width: popperRect.width,
  641. height: popperRect.height
  642. };
  643. // depending by the popper placement we have to compute its offsets slightly differently
  644. const isHoriz = ['right', 'left'].indexOf(placement) !== -1;
  645. const mainSide = isHoriz ? 'top' : 'left';
  646. const secondarySide = isHoriz ? 'left' : 'top';
  647. const measurement = isHoriz ? 'height' : 'width';
  648. const secondaryMeasurement = !isHoriz ? 'height' : 'width';
  649. popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2;
  650. if (placement === secondarySide) {
  651. popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement];
  652. } else {
  653. popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)];
  654. }
  655. return popperOffsets;
  656. }
  657. /**
  658. * Mimics the `find` method of Array
  659. * @method
  660. * @memberof Popper.Utils
  661. * @argument {Array} arr
  662. * @argument prop
  663. * @argument value
  664. * @returns index or -1
  665. */
  666. function find(arr, check) {
  667. // use native find if supported
  668. if (Array.prototype.find) {
  669. return arr.find(check);
  670. }
  671. // use `filter` to obtain the same behavior of `find`
  672. return arr.filter(check)[0];
  673. }
  674. /**
  675. * Return the index of the matching object
  676. * @method
  677. * @memberof Popper.Utils
  678. * @argument {Array} arr
  679. * @argument prop
  680. * @argument value
  681. * @returns index or -1
  682. */
  683. function findIndex(arr, prop, value) {
  684. // use native findIndex if supported
  685. if (Array.prototype.findIndex) {
  686. return arr.findIndex(cur => cur[prop] === value);
  687. }
  688. // use `find` + `indexOf` if `findIndex` isn't supported
  689. const match = find(arr, obj => obj[prop] === value);
  690. return arr.indexOf(match);
  691. }
  692. /**
  693. * Loop trough the list of modifiers and run them in order,
  694. * each of them will then edit the data object.
  695. * @method
  696. * @memberof Popper.Utils
  697. * @param {dataObject} data
  698. * @param {Array} modifiers
  699. * @param {String} ends - Optional modifier name used as stopper
  700. * @returns {dataObject}
  701. */
  702. function runModifiers(modifiers, data, ends) {
  703. const modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends));
  704. modifiersToRun.forEach(modifier => {
  705. if (modifier['function']) {
  706. // eslint-disable-line dot-notation
  707. console.warn('`modifier.function` is deprecated, use `modifier.fn`!');
  708. }
  709. const fn = modifier['function'] || modifier.fn; // eslint-disable-line dot-notation
  710. if (modifier.enabled && isFunction(fn)) {
  711. // Add properties to offsets to make them a complete clientRect object
  712. // we do this before each modifier to make sure the previous one doesn't
  713. // mess with these values
  714. data.offsets.popper = getClientRect(data.offsets.popper);
  715. data.offsets.reference = getClientRect(data.offsets.reference);
  716. data = fn(data, modifier);
  717. }
  718. });
  719. return data;
  720. }
  721. /**
  722. * Updates the position of the popper, computing the new offsets and applying
  723. * the new style.<br />
  724. * Prefer `scheduleUpdate` over `update` because of performance reasons.
  725. * @method
  726. * @memberof Popper
  727. */
  728. function update() {
  729. // if popper is destroyed, don't perform any further update
  730. if (this.state.isDestroyed) {
  731. return;
  732. }
  733. let data = {
  734. instance: this,
  735. styles: {},
  736. arrowStyles: {},
  737. attributes: {},
  738. flipped: false,
  739. offsets: {}
  740. };
  741. // compute reference element offsets
  742. data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference, this.options.positionFixed);
  743. // compute auto placement, store placement inside the data object,
  744. // modifiers will be able to edit `placement` if needed
  745. // and refer to originalPlacement to know the original value
  746. data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding);
  747. // store the computed placement inside `originalPlacement`
  748. data.originalPlacement = data.placement;
  749. data.positionFixed = this.options.positionFixed;
  750. // compute the popper offsets
  751. data.offsets.popper = getPopperOffsets(this.popper, data.offsets.reference, data.placement);
  752. data.offsets.popper.position = this.options.positionFixed ? 'fixed' : 'absolute';
  753. // run the modifiers
  754. data = runModifiers(this.modifiers, data);
  755. // the first `update` will call `onCreate` callback
  756. // the other ones will call `onUpdate` callback
  757. if (!this.state.isCreated) {
  758. this.state.isCreated = true;
  759. this.options.onCreate(data);
  760. } else {
  761. this.options.onUpdate(data);
  762. }
  763. }
  764. /**
  765. * Helper used to know if the given modifier is enabled.
  766. * @method
  767. * @memberof Popper.Utils
  768. * @returns {Boolean}
  769. */
  770. function isModifierEnabled(modifiers, modifierName) {
  771. return modifiers.some(({ name, enabled }) => enabled && name === modifierName);
  772. }
  773. /**
  774. * Get the prefixed supported property name
  775. * @method
  776. * @memberof Popper.Utils
  777. * @argument {String} property (camelCase)
  778. * @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix)
  779. */
  780. function getSupportedPropertyName(property) {
  781. const prefixes = [false, 'ms', 'Webkit', 'Moz', 'O'];
  782. const upperProp = property.charAt(0).toUpperCase() + property.slice(1);
  783. for (let i = 0; i < prefixes.length; i++) {
  784. const prefix = prefixes[i];
  785. const toCheck = prefix ? `${prefix}${upperProp}` : property;
  786. if (typeof document.body.style[toCheck] !== 'undefined') {
  787. return toCheck;
  788. }
  789. }
  790. return null;
  791. }
  792. /**
  793. * Destroys the popper.
  794. * @method
  795. * @memberof Popper
  796. */
  797. function destroy() {
  798. this.state.isDestroyed = true;
  799. // touch DOM only if `applyStyle` modifier is enabled
  800. if (isModifierEnabled(this.modifiers, 'applyStyle')) {
  801. this.popper.removeAttribute('x-placement');
  802. this.popper.style.position = '';
  803. this.popper.style.top = '';
  804. this.popper.style.left = '';
  805. this.popper.style.right = '';
  806. this.popper.style.bottom = '';
  807. this.popper.style.willChange = '';
  808. this.popper.style[getSupportedPropertyName('transform')] = '';
  809. }
  810. this.disableEventListeners();
  811. // remove the popper if user explicitly asked for the deletion on destroy
  812. // do not use `remove` because IE11 doesn't support it
  813. if (this.options.removeOnDestroy) {
  814. this.popper.parentNode.removeChild(this.popper);
  815. }
  816. return this;
  817. }
  818. /**
  819. * Get the window associated with the element
  820. * @argument {Element} element
  821. * @returns {Window}
  822. */
  823. function getWindow(element) {
  824. const ownerDocument = element.ownerDocument;
  825. return ownerDocument ? ownerDocument.defaultView : window;
  826. }
  827. function attachToScrollParents(scrollParent, event, callback, scrollParents) {
  828. const isBody = scrollParent.nodeName === 'BODY';
  829. const target = isBody ? scrollParent.ownerDocument.defaultView : scrollParent;
  830. target.addEventListener(event, callback, { passive: true });
  831. if (!isBody) {
  832. attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents);
  833. }
  834. scrollParents.push(target);
  835. }
  836. /**
  837. * Setup needed event listeners used to update the popper position
  838. * @method
  839. * @memberof Popper.Utils
  840. * @private
  841. */
  842. function setupEventListeners(reference, options, state, updateBound) {
  843. // Resize event listener on window
  844. state.updateBound = updateBound;
  845. getWindow(reference).addEventListener('resize', state.updateBound, { passive: true });
  846. // Scroll event listener on scroll parents
  847. const scrollElement = getScrollParent(reference);
  848. attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents);
  849. state.scrollElement = scrollElement;
  850. state.eventsEnabled = true;
  851. return state;
  852. }
  853. /**
  854. * It will add resize/scroll events and start recalculating
  855. * position of the popper element when they are triggered.
  856. * @method
  857. * @memberof Popper
  858. */
  859. function enableEventListeners() {
  860. if (!this.state.eventsEnabled) {
  861. this.state = setupEventListeners(this.reference, this.options, this.state, this.scheduleUpdate);
  862. }
  863. }
  864. /**
  865. * Remove event listeners used to update the popper position
  866. * @method
  867. * @memberof Popper.Utils
  868. * @private
  869. */
  870. function removeEventListeners(reference, state) {
  871. // Remove resize event listener on window
  872. getWindow(reference).removeEventListener('resize', state.updateBound);
  873. // Remove scroll event listener on scroll parents
  874. state.scrollParents.forEach(target => {
  875. target.removeEventListener('scroll', state.updateBound);
  876. });
  877. // Reset state
  878. state.updateBound = null;
  879. state.scrollParents = [];
  880. state.scrollElement = null;
  881. state.eventsEnabled = false;
  882. return state;
  883. }
  884. /**
  885. * It will remove resize/scroll events and won't recalculate popper position
  886. * when they are triggered. It also won't trigger `onUpdate` callback anymore,
  887. * unless you call `update` method manually.
  888. * @method
  889. * @memberof Popper
  890. */
  891. function disableEventListeners() {
  892. if (this.state.eventsEnabled) {
  893. cancelAnimationFrame(this.scheduleUpdate);
  894. this.state = removeEventListeners(this.reference, this.state);
  895. }
  896. }
  897. /**
  898. * Tells if a given input is a number
  899. * @method
  900. * @memberof Popper.Utils
  901. * @param {*} input to check
  902. * @return {Boolean}
  903. */
  904. function isNumeric(n) {
  905. return n !== '' && !isNaN(parseFloat(n)) && isFinite(n);
  906. }
  907. /**
  908. * Set the style to the given popper
  909. * @method
  910. * @memberof Popper.Utils
  911. * @argument {Element} element - Element to apply the style to
  912. * @argument {Object} styles
  913. * Object with a list of properties and values which will be applied to the element
  914. */
  915. function setStyles(element, styles) {
  916. Object.keys(styles).forEach(prop => {
  917. let unit = '';
  918. // add unit if the value is numeric and is one of the following
  919. if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) {
  920. unit = 'px';
  921. }
  922. element.style[prop] = styles[prop] + unit;
  923. });
  924. }
  925. /**
  926. * Set the attributes to the given popper
  927. * @method
  928. * @memberof Popper.Utils
  929. * @argument {Element} element - Element to apply the attributes to
  930. * @argument {Object} styles
  931. * Object with a list of properties and values which will be applied to the element
  932. */
  933. function setAttributes(element, attributes) {
  934. Object.keys(attributes).forEach(function (prop) {
  935. const value = attributes[prop];
  936. if (value !== false) {
  937. element.setAttribute(prop, attributes[prop]);
  938. } else {
  939. element.removeAttribute(prop);
  940. }
  941. });
  942. }
  943. /**
  944. * @function
  945. * @memberof Modifiers
  946. * @argument {Object} data - The data object generated by `update` method
  947. * @argument {Object} data.styles - List of style properties - values to apply to popper element
  948. * @argument {Object} data.attributes - List of attribute properties - values to apply to popper element
  949. * @argument {Object} options - Modifiers configuration and options
  950. * @returns {Object} The same data object
  951. */
  952. function applyStyle(data) {
  953. // any property present in `data.styles` will be applied to the popper,
  954. // in this way we can make the 3rd party modifiers add custom styles to it
  955. // Be aware, modifiers could override the properties defined in the previous
  956. // lines of this modifier!
  957. setStyles(data.instance.popper, data.styles);
  958. // any property present in `data.attributes` will be applied to the popper,
  959. // they will be set as HTML attributes of the element
  960. setAttributes(data.instance.popper, data.attributes);
  961. // if arrowElement is defined and arrowStyles has some properties
  962. if (data.arrowElement && Object.keys(data.arrowStyles).length) {
  963. setStyles(data.arrowElement, data.arrowStyles);
  964. }
  965. return data;
  966. }
  967. /**
  968. * Set the x-placement attribute before everything else because it could be used
  969. * to add margins to the popper margins needs to be calculated to get the
  970. * correct popper offsets.
  971. * @method
  972. * @memberof Popper.modifiers
  973. * @param {HTMLElement} reference - The reference element used to position the popper
  974. * @param {HTMLElement} popper - The HTML element used as popper
  975. * @param {Object} options - Popper.js options
  976. */
  977. function applyStyleOnLoad(reference, popper, options, modifierOptions, state) {
  978. // compute reference element offsets
  979. const referenceOffsets = getReferenceOffsets(state, popper, reference, options.positionFixed);
  980. // compute auto placement, store placement inside the data object,
  981. // modifiers will be able to edit `placement` if needed
  982. // and refer to originalPlacement to know the original value
  983. const placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding);
  984. popper.setAttribute('x-placement', placement);
  985. // Apply `position` to popper before anything else because
  986. // without the position applied we can't guarantee correct computations
  987. setStyles(popper, { position: options.positionFixed ? 'fixed' : 'absolute' });
  988. return options;
  989. }
  990. /**
  991. * @function
  992. * @memberof Popper.Utils
  993. * @argument {Object} data - The data object generated by `update` method
  994. * @argument {Boolean} shouldRound - If the offsets should be rounded at all
  995. * @returns {Object} The popper's position offsets rounded
  996. *
  997. * The tale of pixel-perfect positioning. It's still not 100% perfect, but as
  998. * good as it can be within reason.
  999. * Discussion here: https://github.com/FezVrasta/popper.js/pull/715
  1000. *
  1001. * Low DPI screens cause a popper to be blurry if not using full pixels (Safari
  1002. * as well on High DPI screens).
  1003. *
  1004. * Firefox prefers no rounding for positioning and does not have blurriness on
  1005. * high DPI screens.
  1006. *
  1007. * Only horizontal placement and left/right values need to be considered.
  1008. */
  1009. function getRoundedOffsets(data, shouldRound) {
  1010. const { popper, reference } = data.offsets;
  1011. const { round, floor } = Math;
  1012. const noRound = v => v;
  1013. const referenceWidth = round(reference.width);
  1014. const popperWidth = round(popper.width);
  1015. const isVertical = ['left', 'right'].indexOf(data.placement) !== -1;
  1016. const isVariation = data.placement.indexOf('-') !== -1;
  1017. const sameWidthParity = referenceWidth % 2 === popperWidth % 2;
  1018. const bothOddWidth = referenceWidth % 2 === 1 && popperWidth % 2 === 1;
  1019. const horizontalToInteger = !shouldRound ? noRound : isVertical || isVariation || sameWidthParity ? round : floor;
  1020. const verticalToInteger = !shouldRound ? noRound : round;
  1021. return {
  1022. left: horizontalToInteger(bothOddWidth && !isVariation && shouldRound ? popper.left - 1 : popper.left),
  1023. top: verticalToInteger(popper.top),
  1024. bottom: verticalToInteger(popper.bottom),
  1025. right: horizontalToInteger(popper.right)
  1026. };
  1027. }
  1028. const isFirefox = isBrowser && /Firefox/i.test(navigator.userAgent);
  1029. /**
  1030. * @function
  1031. * @memberof Modifiers
  1032. * @argument {Object} data - The data object generated by `update` method
  1033. * @argument {Object} options - Modifiers configuration and options
  1034. * @returns {Object} The data object, properly modified
  1035. */
  1036. function computeStyle(data, options) {
  1037. const { x, y } = options;
  1038. const { popper } = data.offsets;
  1039. // Remove this legacy support in Popper.js v2
  1040. const legacyGpuAccelerationOption = find(data.instance.modifiers, modifier => modifier.name === 'applyStyle').gpuAcceleration;
  1041. if (legacyGpuAccelerationOption !== undefined) {
  1042. console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!');
  1043. }
  1044. const gpuAcceleration = legacyGpuAccelerationOption !== undefined ? legacyGpuAccelerationOption : options.gpuAcceleration;
  1045. const offsetParent = getOffsetParent(data.instance.popper);
  1046. const offsetParentRect = getBoundingClientRect(offsetParent);
  1047. // Styles
  1048. const styles = {
  1049. position: popper.position
  1050. };
  1051. const offsets = getRoundedOffsets(data, window.devicePixelRatio < 2 || !isFirefox);
  1052. const sideA = x === 'bottom' ? 'top' : 'bottom';
  1053. const sideB = y === 'right' ? 'left' : 'right';
  1054. // if gpuAcceleration is set to `true` and transform is supported,
  1055. // we use `translate3d` to apply the position to the popper we
  1056. // automatically use the supported prefixed version if needed
  1057. const prefixedProperty = getSupportedPropertyName('transform');
  1058. // now, let's make a step back and look at this code closely (wtf?)
  1059. // If the content of the popper grows once it's been positioned, it
  1060. // may happen that the popper gets misplaced because of the new content
  1061. // overflowing its reference element
  1062. // To avoid this problem, we provide two options (x and y), which allow
  1063. // the consumer to define the offset origin.
  1064. // If we position a popper on top of a reference element, we can set
  1065. // `x` to `top` to make the popper grow towards its top instead of
  1066. // its bottom.
  1067. let left, top;
  1068. if (sideA === 'bottom') {
  1069. // when offsetParent is <html> the positioning is relative to the bottom of the screen (excluding the scrollbar)
  1070. // and not the bottom of the html element
  1071. if (offsetParent.nodeName === 'HTML') {
  1072. top = -offsetParent.clientHeight + offsets.bottom;
  1073. } else {
  1074. top = -offsetParentRect.height + offsets.bottom;
  1075. }
  1076. } else {
  1077. top = offsets.top;
  1078. }
  1079. if (sideB === 'right') {
  1080. if (offsetParent.nodeName === 'HTML') {
  1081. left = -offsetParent.clientWidth + offsets.right;
  1082. } else {
  1083. left = -offsetParentRect.width + offsets.right;
  1084. }
  1085. } else {
  1086. left = offsets.left;
  1087. }
  1088. if (gpuAcceleration && prefixedProperty) {
  1089. styles[prefixedProperty] = `translate3d(${left}px, ${top}px, 0)`;
  1090. styles[sideA] = 0;
  1091. styles[sideB] = 0;
  1092. styles.willChange = 'transform';
  1093. } else {
  1094. // othwerise, we use the standard `top`, `left`, `bottom` and `right` properties
  1095. const invertTop = sideA === 'bottom' ? -1 : 1;
  1096. const invertLeft = sideB === 'right' ? -1 : 1;
  1097. styles[sideA] = top * invertTop;
  1098. styles[sideB] = left * invertLeft;
  1099. styles.willChange = `${sideA}, ${sideB}`;
  1100. }
  1101. // Attributes
  1102. const attributes = {
  1103. 'x-placement': data.placement
  1104. };
  1105. // Update `data` attributes, styles and arrowStyles
  1106. data.attributes = _extends({}, attributes, data.attributes);
  1107. data.styles = _extends({}, styles, data.styles);
  1108. data.arrowStyles = _extends({}, data.offsets.arrow, data.arrowStyles);
  1109. return data;
  1110. }
  1111. /**
  1112. * Helper used to know if the given modifier depends from another one.<br />
  1113. * It checks if the needed modifier is listed and enabled.
  1114. * @method
  1115. * @memberof Popper.Utils
  1116. * @param {Array} modifiers - list of modifiers
  1117. * @param {String} requestingName - name of requesting modifier
  1118. * @param {String} requestedName - name of requested modifier
  1119. * @returns {Boolean}
  1120. */
  1121. function isModifierRequired(modifiers, requestingName, requestedName) {
  1122. const requesting = find(modifiers, ({ name }) => name === requestingName);
  1123. const isRequired = !!requesting && modifiers.some(modifier => {
  1124. return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order;
  1125. });
  1126. if (!isRequired) {
  1127. const requesting = `\`${requestingName}\``;
  1128. const requested = `\`${requestedName}\``;
  1129. console.warn(`${requested} modifier is required by ${requesting} modifier in order to work, be sure to include it before ${requesting}!`);
  1130. }
  1131. return isRequired;
  1132. }
  1133. /**
  1134. * @function
  1135. * @memberof Modifiers
  1136. * @argument {Object} data - The data object generated by update method
  1137. * @argument {Object} options - Modifiers configuration and options
  1138. * @returns {Object} The data object, properly modified
  1139. */
  1140. function arrow(data, options) {
  1141. // arrow depends on keepTogether in order to work
  1142. if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) {
  1143. return data;
  1144. }
  1145. let arrowElement = options.element;
  1146. // if arrowElement is a string, suppose it's a CSS selector
  1147. if (typeof arrowElement === 'string') {
  1148. arrowElement = data.instance.popper.querySelector(arrowElement);
  1149. // if arrowElement is not found, don't run the modifier
  1150. if (!arrowElement) {
  1151. return data;
  1152. }
  1153. } else {
  1154. // if the arrowElement isn't a query selector we must check that the
  1155. // provided DOM node is child of its popper node
  1156. if (!data.instance.popper.contains(arrowElement)) {
  1157. console.warn('WARNING: `arrow.element` must be child of its popper element!');
  1158. return data;
  1159. }
  1160. }
  1161. const placement = data.placement.split('-')[0];
  1162. const { popper, reference } = data.offsets;
  1163. const isVertical = ['left', 'right'].indexOf(placement) !== -1;
  1164. const len = isVertical ? 'height' : 'width';
  1165. const sideCapitalized = isVertical ? 'Top' : 'Left';
  1166. const side = sideCapitalized.toLowerCase();
  1167. const altSide = isVertical ? 'left' : 'top';
  1168. const opSide = isVertical ? 'bottom' : 'right';
  1169. const arrowElementSize = getOuterSizes(arrowElement)[len];
  1170. //
  1171. // extends keepTogether behavior making sure the popper and its
  1172. // reference have enough pixels in conjunction
  1173. //
  1174. // top/left side
  1175. if (reference[opSide] - arrowElementSize < popper[side]) {
  1176. data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowElementSize);
  1177. }
  1178. // bottom/right side
  1179. if (reference[side] + arrowElementSize > popper[opSide]) {
  1180. data.offsets.popper[side] += reference[side] + arrowElementSize - popper[opSide];
  1181. }
  1182. data.offsets.popper = getClientRect(data.offsets.popper);
  1183. // compute center of the popper
  1184. const center = reference[side] + reference[len] / 2 - arrowElementSize / 2;
  1185. // Compute the sideValue using the updated popper offsets
  1186. // take popper margin in account because we don't have this info available
  1187. const css = getStyleComputedProperty(data.instance.popper);
  1188. const popperMarginSide = parseFloat(css[`margin${sideCapitalized}`]);
  1189. const popperBorderSide = parseFloat(css[`border${sideCapitalized}Width`]);
  1190. let sideValue = center - data.offsets.popper[side] - popperMarginSide - popperBorderSide;
  1191. // prevent arrowElement from being placed not contiguously to its popper
  1192. sideValue = Math.max(Math.min(popper[len] - arrowElementSize, sideValue), 0);
  1193. data.arrowElement = arrowElement;
  1194. data.offsets.arrow = {
  1195. [side]: Math.round(sideValue),
  1196. [altSide]: '' // make sure to unset any eventual altSide value from the DOM node
  1197. };
  1198. return data;
  1199. }
  1200. /**
  1201. * Get the opposite placement variation of the given one
  1202. * @method
  1203. * @memberof Popper.Utils
  1204. * @argument {String} placement variation
  1205. * @returns {String} flipped placement variation
  1206. */
  1207. function getOppositeVariation(variation) {
  1208. if (variation === 'end') {
  1209. return 'start';
  1210. } else if (variation === 'start') {
  1211. return 'end';
  1212. }
  1213. return variation;
  1214. }
  1215. /**
  1216. * List of accepted placements to use as values of the `placement` option.<br />
  1217. * Valid placements are:
  1218. * - `auto`
  1219. * - `top`
  1220. * - `right`
  1221. * - `bottom`
  1222. * - `left`
  1223. *
  1224. * Each placement can have a variation from this list:
  1225. * - `-start`
  1226. * - `-end`
  1227. *
  1228. * Variations are interpreted easily if you think of them as the left to right
  1229. * written languages. Horizontally (`top` and `bottom`), `start` is left and `end`
  1230. * is right.<br />
  1231. * Vertically (`left` and `right`), `start` is top and `end` is bottom.
  1232. *
  1233. * Some valid examples are:
  1234. * - `top-end` (on top of reference, right aligned)
  1235. * - `right-start` (on right of reference, top aligned)
  1236. * - `bottom` (on bottom, centered)
  1237. * - `auto-end` (on the side with more space available, alignment depends by placement)
  1238. *
  1239. * @static
  1240. * @type {Array}
  1241. * @enum {String}
  1242. * @readonly
  1243. * @method placements
  1244. * @memberof Popper
  1245. */
  1246. var placements = ['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start'];
  1247. // Get rid of `auto` `auto-start` and `auto-end`
  1248. const validPlacements = placements.slice(3);
  1249. /**
  1250. * Given an initial placement, returns all the subsequent placements
  1251. * clockwise (or counter-clockwise).
  1252. *
  1253. * @method
  1254. * @memberof Popper.Utils
  1255. * @argument {String} placement - A valid placement (it accepts variations)
  1256. * @argument {Boolean} counter - Set to true to walk the placements counterclockwise
  1257. * @returns {Array} placements including their variations
  1258. */
  1259. function clockwise(placement, counter = false) {
  1260. const index = validPlacements.indexOf(placement);
  1261. const arr = validPlacements.slice(index + 1).concat(validPlacements.slice(0, index));
  1262. return counter ? arr.reverse() : arr;
  1263. }
  1264. const BEHAVIORS = {
  1265. FLIP: 'flip',
  1266. CLOCKWISE: 'clockwise',
  1267. COUNTERCLOCKWISE: 'counterclockwise'
  1268. };
  1269. /**
  1270. * @function
  1271. * @memberof Modifiers
  1272. * @argument {Object} data - The data object generated by update method
  1273. * @argument {Object} options - Modifiers configuration and options
  1274. * @returns {Object} The data object, properly modified
  1275. */
  1276. function flip(data, options) {
  1277. // if `inner` modifier is enabled, we can't use the `flip` modifier
  1278. if (isModifierEnabled(data.instance.modifiers, 'inner')) {
  1279. return data;
  1280. }
  1281. if (data.flipped && data.placement === data.originalPlacement) {
  1282. // seems like flip is trying to loop, probably there's not enough space on any of the flippable sides
  1283. return data;
  1284. }
  1285. const boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, options.boundariesElement, data.positionFixed);
  1286. let placement = data.placement.split('-')[0];
  1287. let placementOpposite = getOppositePlacement(placement);
  1288. let variation = data.placement.split('-')[1] || '';
  1289. let flipOrder = [];
  1290. switch (options.behavior) {
  1291. case BEHAVIORS.FLIP:
  1292. flipOrder = [placement, placementOpposite];
  1293. break;
  1294. case BEHAVIORS.CLOCKWISE:
  1295. flipOrder = clockwise(placement);
  1296. break;
  1297. case BEHAVIORS.COUNTERCLOCKWISE:
  1298. flipOrder = clockwise(placement, true);
  1299. break;
  1300. default:
  1301. flipOrder = options.behavior;
  1302. }
  1303. flipOrder.forEach((step, index) => {
  1304. if (placement !== step || flipOrder.length === index + 1) {
  1305. return data;
  1306. }
  1307. placement = data.placement.split('-')[0];
  1308. placementOpposite = getOppositePlacement(placement);
  1309. const popperOffsets = data.offsets.popper;
  1310. const refOffsets = data.offsets.reference;
  1311. // using floor because the reference offsets may contain decimals we are not going to consider here
  1312. const floor = Math.floor;
  1313. const overlapsRef = placement === 'left' && floor(popperOffsets.right) > floor(refOffsets.left) || placement === 'right' && floor(popperOffsets.left) < floor(refOffsets.right) || placement === 'top' && floor(popperOffsets.bottom) > floor(refOffsets.top) || placement === 'bottom' && floor(popperOffsets.top) < floor(refOffsets.bottom);
  1314. const overflowsLeft = floor(popperOffsets.left) < floor(boundaries.left);
  1315. const overflowsRight = floor(popperOffsets.right) > floor(boundaries.right);
  1316. const overflowsTop = floor(popperOffsets.top) < floor(boundaries.top);
  1317. const overflowsBottom = floor(popperOffsets.bottom) > floor(boundaries.bottom);
  1318. const overflowsBoundaries = placement === 'left' && overflowsLeft || placement === 'right' && overflowsRight || placement === 'top' && overflowsTop || placement === 'bottom' && overflowsBottom;
  1319. // flip the variation if required
  1320. const isVertical = ['top', 'bottom'].indexOf(placement) !== -1;
  1321. // flips variation if reference element overflows boundaries
  1322. const flippedVariationByRef = !!options.flipVariations && (isVertical && variation === 'start' && overflowsLeft || isVertical && variation === 'end' && overflowsRight || !isVertical && variation === 'start' && overflowsTop || !isVertical && variation === 'end' && overflowsBottom);
  1323. // flips variation if popper content overflows boundaries
  1324. const flippedVariationByContent = !!options.flipVariationsByContent && (isVertical && variation === 'start' && overflowsRight || isVertical && variation === 'end' && overflowsLeft || !isVertical && variation === 'start' && overflowsBottom || !isVertical && variation === 'end' && overflowsTop);
  1325. const flippedVariation = flippedVariationByRef || flippedVariationByContent;
  1326. if (overlapsRef || overflowsBoundaries || flippedVariation) {
  1327. // this boolean to detect any flip loop
  1328. data.flipped = true;
  1329. if (overlapsRef || overflowsBoundaries) {
  1330. placement = flipOrder[index + 1];
  1331. }
  1332. if (flippedVariation) {
  1333. variation = getOppositeVariation(variation);
  1334. }
  1335. data.placement = placement + (variation ? '-' + variation : '');
  1336. // this object contains `position`, we want to preserve it along with
  1337. // any additional property we may add in the future
  1338. data.offsets.popper = _extends({}, data.offsets.popper, getPopperOffsets(data.instance.popper, data.offsets.reference, data.placement));
  1339. data = runModifiers(data.instance.modifiers, data, 'flip');
  1340. }
  1341. });
  1342. return data;
  1343. }
  1344. /**
  1345. * @function
  1346. * @memberof Modifiers
  1347. * @argument {Object} data - The data object generated by update method
  1348. * @argument {Object} options - Modifiers configuration and options
  1349. * @returns {Object} The data object, properly modified
  1350. */
  1351. function keepTogether(data) {
  1352. const { popper, reference } = data.offsets;
  1353. const placement = data.placement.split('-')[0];
  1354. const floor = Math.floor;
  1355. const isVertical = ['top', 'bottom'].indexOf(placement) !== -1;
  1356. const side = isVertical ? 'right' : 'bottom';
  1357. const opSide = isVertical ? 'left' : 'top';
  1358. const measurement = isVertical ? 'width' : 'height';
  1359. if (popper[side] < floor(reference[opSide])) {
  1360. data.offsets.popper[opSide] = floor(reference[opSide]) - popper[measurement];
  1361. }
  1362. if (popper[opSide] > floor(reference[side])) {
  1363. data.offsets.popper[opSide] = floor(reference[side]);
  1364. }
  1365. return data;
  1366. }
  1367. /**
  1368. * Converts a string containing value + unit into a px value number
  1369. * @function
  1370. * @memberof {modifiers~offset}
  1371. * @private
  1372. * @argument {String} str - Value + unit string
  1373. * @argument {String} measurement - `height` or `width`
  1374. * @argument {Object} popperOffsets
  1375. * @argument {Object} referenceOffsets
  1376. * @returns {Number|String}
  1377. * Value in pixels, or original string if no values were extracted
  1378. */
  1379. function toValue(str, measurement, popperOffsets, referenceOffsets) {
  1380. // separate value from unit
  1381. const split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/);
  1382. const value = +split[1];
  1383. const unit = split[2];
  1384. // If it's not a number it's an operator, I guess
  1385. if (!value) {
  1386. return str;
  1387. }
  1388. if (unit.indexOf('%') === 0) {
  1389. let element;
  1390. switch (unit) {
  1391. case '%p':
  1392. element = popperOffsets;
  1393. break;
  1394. case '%':
  1395. case '%r':
  1396. default:
  1397. element = referenceOffsets;
  1398. }
  1399. const rect = getClientRect(element);
  1400. return rect[measurement] / 100 * value;
  1401. } else if (unit === 'vh' || unit === 'vw') {
  1402. // if is a vh or vw, we calculate the size based on the viewport
  1403. let size;
  1404. if (unit === 'vh') {
  1405. size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
  1406. } else {
  1407. size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
  1408. }
  1409. return size / 100 * value;
  1410. } else {
  1411. // if is an explicit pixel unit, we get rid of the unit and keep the value
  1412. // if is an implicit unit, it's px, and we return just the value
  1413. return value;
  1414. }
  1415. }
  1416. /**
  1417. * Parse an `offset` string to extrapolate `x` and `y` numeric offsets.
  1418. * @function
  1419. * @memberof {modifiers~offset}
  1420. * @private
  1421. * @argument {String} offset
  1422. * @argument {Object} popperOffsets
  1423. * @argument {Object} referenceOffsets
  1424. * @argument {String} basePlacement
  1425. * @returns {Array} a two cells array with x and y offsets in numbers
  1426. */
  1427. function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) {
  1428. const offsets = [0, 0];
  1429. // Use height if placement is left or right and index is 0 otherwise use width
  1430. // in this way the first offset will use an axis and the second one
  1431. // will use the other one
  1432. const useHeight = ['right', 'left'].indexOf(basePlacement) !== -1;
  1433. // Split the offset string to obtain a list of values and operands
  1434. // The regex addresses values with the plus or minus sign in front (+10, -20, etc)
  1435. const fragments = offset.split(/(\+|\-)/).map(frag => frag.trim());
  1436. // Detect if the offset string contains a pair of values or a single one
  1437. // they could be separated by comma or space
  1438. const divider = fragments.indexOf(find(fragments, frag => frag.search(/,|\s/) !== -1));
  1439. if (fragments[divider] && fragments[divider].indexOf(',') === -1) {
  1440. console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.');
  1441. }
  1442. // If divider is found, we divide the list of values and operands to divide
  1443. // them by ofset X and Y.
  1444. const splitRegex = /\s*,\s*|\s+/;
  1445. let ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments];
  1446. // Convert the values with units to absolute pixels to allow our computations
  1447. ops = ops.map((op, index) => {
  1448. // Most of the units rely on the orientation of the popper
  1449. const measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width';
  1450. let mergeWithPrevious = false;
  1451. return op
  1452. // This aggregates any `+` or `-` sign that aren't considered operators
  1453. // e.g.: 10 + +5 => [10, +, +5]
  1454. .reduce((a, b) => {
  1455. if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) {
  1456. a[a.length - 1] = b;
  1457. mergeWithPrevious = true;
  1458. return a;
  1459. } else if (mergeWithPrevious) {
  1460. a[a.length - 1] += b;
  1461. mergeWithPrevious = false;
  1462. return a;
  1463. } else {
  1464. return a.concat(b);
  1465. }
  1466. }, [])
  1467. // Here we convert the string values into number values (in px)
  1468. .map(str => toValue(str, measurement, popperOffsets, referenceOffsets));
  1469. });
  1470. // Loop trough the offsets arrays and execute the operations
  1471. ops.forEach((op, index) => {
  1472. op.forEach((frag, index2) => {
  1473. if (isNumeric(frag)) {
  1474. offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1);
  1475. }
  1476. });
  1477. });
  1478. return offsets;
  1479. }
  1480. /**
  1481. * @function
  1482. * @memberof Modifiers
  1483. * @argument {Object} data - The data object generated by update method
  1484. * @argument {Object} options - Modifiers configuration and options
  1485. * @argument {Number|String} options.offset=0
  1486. * The offset value as described in the modifier description
  1487. * @returns {Object} The data object, properly modified
  1488. */
  1489. function offset(data, { offset }) {
  1490. const { placement, offsets: { popper, reference } } = data;
  1491. const basePlacement = placement.split('-')[0];
  1492. let offsets;
  1493. if (isNumeric(+offset)) {
  1494. offsets = [+offset, 0];
  1495. } else {
  1496. offsets = parseOffset(offset, popper, reference, basePlacement);
  1497. }
  1498. if (basePlacement === 'left') {
  1499. popper.top += offsets[0];
  1500. popper.left -= offsets[1];
  1501. } else if (basePlacement === 'right') {
  1502. popper.top += offsets[0];
  1503. popper.left += offsets[1];
  1504. } else if (basePlacement === 'top') {
  1505. popper.left += offsets[0];
  1506. popper.top -= offsets[1];
  1507. } else if (basePlacement === 'bottom') {
  1508. popper.left += offsets[0];
  1509. popper.top += offsets[1];
  1510. }
  1511. data.popper = popper;
  1512. return data;
  1513. }
  1514. /**
  1515. * @function
  1516. * @memberof Modifiers
  1517. * @argument {Object} data - The data object generated by `update` method
  1518. * @argument {Object} options - Modifiers configuration and options
  1519. * @returns {Object} The data object, properly modified
  1520. */
  1521. function preventOverflow(data, options) {
  1522. let boundariesElement = options.boundariesElement || getOffsetParent(data.instance.popper);
  1523. // If offsetParent is the reference element, we really want to
  1524. // go one step up and use the next offsetParent as reference to
  1525. // avoid to make this modifier completely useless and look like broken
  1526. if (data.instance.reference === boundariesElement) {
  1527. boundariesElement = getOffsetParent(boundariesElement);
  1528. }
  1529. // NOTE: DOM access here
  1530. // resets the popper's position so that the document size can be calculated excluding
  1531. // the size of the popper element itself
  1532. const transformProp = getSupportedPropertyName('transform');
  1533. const popperStyles = data.instance.popper.style; // assignment to help minification
  1534. const { top, left, [transformProp]: transform } = popperStyles;
  1535. popperStyles.top = '';
  1536. popperStyles.left = '';
  1537. popperStyles[transformProp] = '';
  1538. const boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, boundariesElement, data.positionFixed);
  1539. // NOTE: DOM access here
  1540. // restores the original style properties after the offsets have been computed
  1541. popperStyles.top = top;
  1542. popperStyles.left = left;
  1543. popperStyles[transformProp] = transform;
  1544. options.boundaries = boundaries;
  1545. const order = options.priority;
  1546. let popper = data.offsets.popper;
  1547. const check = {
  1548. primary(placement) {
  1549. let value = popper[placement];
  1550. if (popper[placement] < boundaries[placement] && !options.escapeWithReference) {
  1551. value = Math.max(popper[placement], boundaries[placement]);
  1552. }
  1553. return { [placement]: value };
  1554. },
  1555. secondary(placement) {
  1556. const mainSide = placement === 'right' ? 'left' : 'top';
  1557. let value = popper[mainSide];
  1558. if (popper[placement] > boundaries[placement] && !options.escapeWithReference) {
  1559. value = Math.min(popper[mainSide], boundaries[placement] - (placement === 'right' ? popper.width : popper.height));
  1560. }
  1561. return { [mainSide]: value };
  1562. }
  1563. };
  1564. order.forEach(placement => {
  1565. const side = ['left', 'top'].indexOf(placement) !== -1 ? 'primary' : 'secondary';
  1566. popper = _extends({}, popper, check[side](placement));
  1567. });
  1568. data.offsets.popper = popper;
  1569. return data;
  1570. }
  1571. /**
  1572. * @function
  1573. * @memberof Modifiers
  1574. * @argument {Object} data - The data object generated by `update` method
  1575. * @argument {Object} options - Modifiers configuration and options
  1576. * @returns {Object} The data object, properly modified
  1577. */
  1578. function shift(data) {
  1579. const placement = data.placement;
  1580. const basePlacement = placement.split('-')[0];
  1581. const shiftvariation = placement.split('-')[1];
  1582. // if shift shiftvariation is specified, run the modifier
  1583. if (shiftvariation) {
  1584. const { reference, popper } = data.offsets;
  1585. const isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1;
  1586. const side = isVertical ? 'left' : 'top';
  1587. const measurement = isVertical ? 'width' : 'height';
  1588. const shiftOffsets = {
  1589. start: { [side]: reference[side] },
  1590. end: {
  1591. [side]: reference[side] + reference[measurement] - popper[measurement]
  1592. }
  1593. };
  1594. data.offsets.popper = _extends({}, popper, shiftOffsets[shiftvariation]);
  1595. }
  1596. return data;
  1597. }
  1598. /**
  1599. * @function
  1600. * @memberof Modifiers
  1601. * @argument {Object} data - The data object generated by update method
  1602. * @argument {Object} options - Modifiers configuration and options
  1603. * @returns {Object} The data object, properly modified
  1604. */
  1605. function hide(data) {
  1606. if (!isModifierRequired(data.instance.modifiers, 'hide', 'preventOverflow')) {
  1607. return data;
  1608. }
  1609. const refRect = data.offsets.reference;
  1610. const bound = find(data.instance.modifiers, modifier => modifier.name === 'preventOverflow').boundaries;
  1611. if (refRect.bottom < bound.top || refRect.left > bound.right || refRect.top > bound.bottom || refRect.right < bound.left) {
  1612. // Avoid unnecessary DOM access if visibility hasn't changed
  1613. if (data.hide === true) {
  1614. return data;
  1615. }
  1616. data.hide = true;
  1617. data.attributes['x-out-of-boundaries'] = '';
  1618. } else {
  1619. // Avoid unnecessary DOM access if visibility hasn't changed
  1620. if (data.hide === false) {
  1621. return data;
  1622. }
  1623. data.hide = false;
  1624. data.attributes['x-out-of-boundaries'] = false;
  1625. }
  1626. return data;
  1627. }
  1628. /**
  1629. * @function
  1630. * @memberof Modifiers
  1631. * @argument {Object} data - The data object generated by `update` method
  1632. * @argument {Object} options - Modifiers configuration and options
  1633. * @returns {Object} The data object, properly modified
  1634. */
  1635. function inner(data) {
  1636. const placement = data.placement;
  1637. const basePlacement = placement.split('-')[0];
  1638. const { popper, reference } = data.offsets;
  1639. const isHoriz = ['left', 'right'].indexOf(basePlacement) !== -1;
  1640. const subtractLength = ['top', 'left'].indexOf(basePlacement) === -1;
  1641. popper[isHoriz ? 'left' : 'top'] = reference[basePlacement] - (subtractLength ? popper[isHoriz ? 'width' : 'height'] : 0);
  1642. data.placement = getOppositePlacement(placement);
  1643. data.offsets.popper = getClientRect(popper);
  1644. return data;
  1645. }
  1646. /**
  1647. * Modifier function, each modifier can have a function of this type assigned
  1648. * to its `fn` property.<br />
  1649. * These functions will be called on each update, this means that you must
  1650. * make sure they are performant enough to avoid performance bottlenecks.
  1651. *
  1652. * @function ModifierFn
  1653. * @argument {dataObject} data - The data object generated by `update` method
  1654. * @argument {Object} options - Modifiers configuration and options
  1655. * @returns {dataObject} The data object, properly modified
  1656. */
  1657. /**
  1658. * Modifiers are plugins used to alter the behavior of your poppers.<br />
  1659. * Popper.js uses a set of 9 modifiers to provide all the basic functionalities
  1660. * needed by the library.
  1661. *
  1662. * Usually you don't want to override the `order`, `fn` and `onLoad` props.
  1663. * All the other properties are configurations that could be tweaked.
  1664. * @namespace modifiers
  1665. */
  1666. var modifiers = {
  1667. /**
  1668. * Modifier used to shift the popper on the start or end of its reference
  1669. * element.<br />
  1670. * It will read the variation of the `placement` property.<br />
  1671. * It can be one either `-end` or `-start`.
  1672. * @memberof modifiers
  1673. * @inner
  1674. */
  1675. shift: {
  1676. /** @prop {number} order=100 - Index used to define the order of execution */
  1677. order: 100,
  1678. /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
  1679. enabled: true,
  1680. /** @prop {ModifierFn} */
  1681. fn: shift
  1682. },
  1683. /**
  1684. * The `offset` modifier can shift your popper on both its axis.
  1685. *
  1686. * It accepts the following units:
  1687. * - `px` or unit-less, interpreted as pixels
  1688. * - `%` or `%r`, percentage relative to the length of the reference element
  1689. * - `%p`, percentage relative to the length of the popper element
  1690. * - `vw`, CSS viewport width unit
  1691. * - `vh`, CSS viewport height unit
  1692. *
  1693. * For length is intended the main axis relative to the placement of the popper.<br />
  1694. * This means that if the placement is `top` or `bottom`, the length will be the
  1695. * `width`. In case of `left` or `right`, it will be the `height`.
  1696. *
  1697. * You can provide a single value (as `Number` or `String`), or a pair of values
  1698. * as `String` divided by a comma or one (or more) white spaces.<br />
  1699. * The latter is a deprecated method because it leads to confusion and will be
  1700. * removed in v2.<br />
  1701. * Additionally, it accepts additions and subtractions between different units.
  1702. * Note that multiplications and divisions aren't supported.
  1703. *
  1704. * Valid examples are:
  1705. * ```
  1706. * 10
  1707. * '10%'
  1708. * '10, 10'
  1709. * '10%, 10'
  1710. * '10 + 10%'
  1711. * '10 - 5vh + 3%'
  1712. * '-10px + 5vh, 5px - 6%'
  1713. * ```
  1714. * > **NB**: If you desire to apply offsets to your poppers in a way that may make them overlap
  1715. * > with their reference element, unfortunately, you will have to disable the `flip` modifier.
  1716. * > You can read more on this at this [issue](https://github.com/FezVrasta/popper.js/issues/373).
  1717. *
  1718. * @memberof modifiers
  1719. * @inner
  1720. */
  1721. offset: {
  1722. /** @prop {number} order=200 - Index used to define the order of execution */
  1723. order: 200,
  1724. /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
  1725. enabled: true,
  1726. /** @prop {ModifierFn} */
  1727. fn: offset,
  1728. /** @prop {Number|String} offset=0
  1729. * The offset value as described in the modifier description
  1730. */
  1731. offset: 0
  1732. },
  1733. /**
  1734. * Modifier used to prevent the popper from being positioned outside the boundary.
  1735. *
  1736. * A scenario exists where the reference itself is not within the boundaries.<br />
  1737. * We can say it has "escaped the boundaries" — or just "escaped".<br />
  1738. * In this case we need to decide whether the popper should either:
  1739. *
  1740. * - detach from the reference and remain "trapped" in the boundaries, or
  1741. * - if it should ignore the boundary and "escape with its reference"
  1742. *
  1743. * When `escapeWithReference` is set to`true` and reference is completely
  1744. * outside its boundaries, the popper will overflow (or completely leave)
  1745. * the boundaries in order to remain attached to the edge of the reference.
  1746. *
  1747. * @memberof modifiers
  1748. * @inner
  1749. */
  1750. preventOverflow: {
  1751. /** @prop {number} order=300 - Index used to define the order of execution */
  1752. order: 300,
  1753. /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
  1754. enabled: true,
  1755. /** @prop {ModifierFn} */
  1756. fn: preventOverflow,
  1757. /**
  1758. * @prop {Array} [priority=['left','right','top','bottom']]
  1759. * Popper will try to prevent overflow following these priorities by default,
  1760. * then, it could overflow on the left and on top of the `boundariesElement`
  1761. */
  1762. priority: ['left', 'right', 'top', 'bottom'],
  1763. /**
  1764. * @prop {number} padding=5
  1765. * Amount of pixel used to define a minimum distance between the boundaries
  1766. * and the popper. This makes sure the popper always has a little padding
  1767. * between the edges of its container
  1768. */
  1769. padding: 5,
  1770. /**
  1771. * @prop {String|HTMLElement} boundariesElement='scrollParent'
  1772. * Boundaries used by the modifier. Can be `scrollParent`, `window`,
  1773. * `viewport` or any DOM element.
  1774. */
  1775. boundariesElement: 'scrollParent'
  1776. },
  1777. /**
  1778. * Modifier used to make sure the reference and its popper stay near each other
  1779. * without leaving any gap between the two. Especially useful when the arrow is
  1780. * enabled and you want to ensure that it points to its reference element.
  1781. * It cares only about the first axis. You can still have poppers with margin
  1782. * between the popper and its reference element.
  1783. * @memberof modifiers
  1784. * @inner
  1785. */
  1786. keepTogether: {
  1787. /** @prop {number} order=400 - Index used to define the order of execution */
  1788. order: 400,
  1789. /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
  1790. enabled: true,
  1791. /** @prop {ModifierFn} */
  1792. fn: keepTogether
  1793. },
  1794. /**
  1795. * This modifier is used to move the `arrowElement` of the popper to make
  1796. * sure it is positioned between the reference element and its popper element.
  1797. * It will read the outer size of the `arrowElement` node to detect how many
  1798. * pixels of conjunction are needed.
  1799. *
  1800. * It has no effect if no `arrowElement` is provided.
  1801. * @memberof modifiers
  1802. * @inner
  1803. */
  1804. arrow: {
  1805. /** @prop {number} order=500 - Index used to define the order of execution */
  1806. order: 500,
  1807. /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
  1808. enabled: true,
  1809. /** @prop {ModifierFn} */
  1810. fn: arrow,
  1811. /** @prop {String|HTMLElement} element='[x-arrow]' - Selector or node used as arrow */
  1812. element: '[x-arrow]'
  1813. },
  1814. /**
  1815. * Modifier used to flip the popper's placement when it starts to overlap its
  1816. * reference element.
  1817. *
  1818. * Requires the `preventOverflow` modifier before it in order to work.
  1819. *
  1820. * **NOTE:** this modifier will interrupt the current update cycle and will
  1821. * restart it if it detects the need to flip the placement.
  1822. * @memberof modifiers
  1823. * @inner
  1824. */
  1825. flip: {
  1826. /** @prop {number} order=600 - Index used to define the order of execution */
  1827. order: 600,
  1828. /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
  1829. enabled: true,
  1830. /** @prop {ModifierFn} */
  1831. fn: flip,
  1832. /**
  1833. * @prop {String|Array} behavior='flip'
  1834. * The behavior used to change the popper's placement. It can be one of
  1835. * `flip`, `clockwise`, `counterclockwise` or an array with a list of valid
  1836. * placements (with optional variations)
  1837. */
  1838. behavior: 'flip',
  1839. /**
  1840. * @prop {number} padding=5
  1841. * The popper will flip if it hits the edges of the `boundariesElement`
  1842. */
  1843. padding: 5,
  1844. /**
  1845. * @prop {String|HTMLElement} boundariesElement='viewport'
  1846. * The element which will define the boundaries of the popper position.
  1847. * The popper will never be placed outside of the defined boundaries
  1848. * (except if `keepTogether` is enabled)
  1849. */
  1850. boundariesElement: 'viewport',
  1851. /**
  1852. * @prop {Boolean} flipVariations=false
  1853. * The popper will switch placement variation between `-start` and `-end` when
  1854. * the reference element overlaps its boundaries.
  1855. *
  1856. * The original placement should have a set variation.
  1857. */
  1858. flipVariations: false,
  1859. /**
  1860. * @prop {Boolean} flipVariationsByContent=false
  1861. * The popper will switch placement variation between `-start` and `-end` when
  1862. * the popper element overlaps its reference boundaries.
  1863. *
  1864. * The original placement should have a set variation.
  1865. */
  1866. flipVariationsByContent: false
  1867. },
  1868. /**
  1869. * Modifier used to make the popper flow toward the inner of the reference element.
  1870. * By default, when this modifier is disabled, the popper will be placed outside
  1871. * the reference element.
  1872. * @memberof modifiers
  1873. * @inner
  1874. */
  1875. inner: {
  1876. /** @prop {number} order=700 - Index used to define the order of execution */
  1877. order: 700,
  1878. /** @prop {Boolean} enabled=false - Whether the modifier is enabled or not */
  1879. enabled: false,
  1880. /** @prop {ModifierFn} */
  1881. fn: inner
  1882. },
  1883. /**
  1884. * Modifier used to hide the popper when its reference element is outside of the
  1885. * popper boundaries. It will set a `x-out-of-boundaries` attribute which can
  1886. * be used to hide with a CSS selector the popper when its reference is
  1887. * out of boundaries.
  1888. *
  1889. * Requires the `preventOverflow` modifier before it in order to work.
  1890. * @memberof modifiers
  1891. * @inner
  1892. */
  1893. hide: {
  1894. /** @prop {number} order=800 - Index used to define the order of execution */
  1895. order: 800,
  1896. /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
  1897. enabled: true,
  1898. /** @prop {ModifierFn} */
  1899. fn: hide
  1900. },
  1901. /**
  1902. * Computes the style that will be applied to the popper element to gets
  1903. * properly positioned.
  1904. *
  1905. * Note that this modifier will not touch the DOM, it just prepares the styles
  1906. * so that `applyStyle` modifier can apply it. This separation is useful
  1907. * in case you need to replace `applyStyle` with a custom implementation.
  1908. *
  1909. * This modifier has `850` as `order` value to maintain backward compatibility
  1910. * with previous versions of Popper.js. Expect the modifiers ordering method
  1911. * to change in future major versions of the library.
  1912. *
  1913. * @memberof modifiers
  1914. * @inner
  1915. */
  1916. computeStyle: {
  1917. /** @prop {number} order=850 - Index used to define the order of execution */
  1918. order: 850,
  1919. /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
  1920. enabled: true,
  1921. /** @prop {ModifierFn} */
  1922. fn: computeStyle,
  1923. /**
  1924. * @prop {Boolean} gpuAcceleration=true
  1925. * If true, it uses the CSS 3D transformation to position the popper.
  1926. * Otherwise, it will use the `top` and `left` properties
  1927. */
  1928. gpuAcceleration: true,
  1929. /**
  1930. * @prop {string} [x='bottom']
  1931. * Where to anchor the X axis (`bottom` or `top`). AKA X offset origin.
  1932. * Change this if your popper should grow in a direction different from `bottom`
  1933. */
  1934. x: 'bottom',
  1935. /**
  1936. * @prop {string} [x='left']
  1937. * Where to anchor the Y axis (`left` or `right`). AKA Y offset origin.
  1938. * Change this if your popper should grow in a direction different from `right`
  1939. */
  1940. y: 'right'
  1941. },
  1942. /**
  1943. * Applies the computed styles to the popper element.
  1944. *
  1945. * All the DOM manipulations are limited to this modifier. This is useful in case
  1946. * you want to integrate Popper.js inside a framework or view library and you
  1947. * want to delegate all the DOM manipulations to it.
  1948. *
  1949. * Note that if you disable this modifier, you must make sure the popper element
  1950. * has its position set to `absolute` before Popper.js can do its work!
  1951. *
  1952. * Just disable this modifier and define your own to achieve the desired effect.
  1953. *
  1954. * @memberof modifiers
  1955. * @inner
  1956. */
  1957. applyStyle: {
  1958. /** @prop {number} order=900 - Index used to define the order of execution */
  1959. order: 900,
  1960. /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
  1961. enabled: true,
  1962. /** @prop {ModifierFn} */
  1963. fn: applyStyle,
  1964. /** @prop {Function} */
  1965. onLoad: applyStyleOnLoad,
  1966. /**
  1967. * @deprecated since version 1.10.0, the property moved to `computeStyle` modifier
  1968. * @prop {Boolean} gpuAcceleration=true
  1969. * If true, it uses the CSS 3D transformation to position the popper.
  1970. * Otherwise, it will use the `top` and `left` properties
  1971. */
  1972. gpuAcceleration: undefined
  1973. }
  1974. };
  1975. /**
  1976. * The `dataObject` is an object containing all the information used by Popper.js.
  1977. * This object is passed to modifiers and to the `onCreate` and `onUpdate` callbacks.
  1978. * @name dataObject
  1979. * @property {Object} data.instance The Popper.js instance
  1980. * @property {String} data.placement Placement applied to popper
  1981. * @property {String} data.originalPlacement Placement originally defined on init
  1982. * @property {Boolean} data.flipped True if popper has been flipped by flip modifier
  1983. * @property {Boolean} data.hide True if the reference element is out of boundaries, useful to know when to hide the popper
  1984. * @property {HTMLElement} data.arrowElement Node used as arrow by arrow modifier
  1985. * @property {Object} data.styles Any CSS property defined here will be applied to the popper. It expects the JavaScript nomenclature (eg. `marginBottom`)
  1986. * @property {Object} data.arrowStyles Any CSS property defined here will be applied to the popper arrow. It expects the JavaScript nomenclature (eg. `marginBottom`)
  1987. * @property {Object} data.boundaries Offsets of the popper boundaries
  1988. * @property {Object} data.offsets The measurements of popper, reference and arrow elements
  1989. * @property {Object} data.offsets.popper `top`, `left`, `width`, `height` values
  1990. * @property {Object} data.offsets.reference `top`, `left`, `width`, `height` values
  1991. * @property {Object} data.offsets.arrow] `top` and `left` offsets, only one of them will be different from 0
  1992. */
  1993. /**
  1994. * Default options provided to Popper.js constructor.<br />
  1995. * These can be overridden using the `options` argument of Popper.js.<br />
  1996. * To override an option, simply pass an object with the same
  1997. * structure of the `options` object, as the 3rd argument. For example:
  1998. * ```
  1999. * new Popper(ref, pop, {
  2000. * modifiers: {
  2001. * preventOverflow: { enabled: false }
  2002. * }
  2003. * })
  2004. * ```
  2005. * @type {Object}
  2006. * @static
  2007. * @memberof Popper
  2008. */
  2009. var Defaults = {
  2010. /**
  2011. * Popper's placement.
  2012. * @prop {Popper.placements} placement='bottom'
  2013. */
  2014. placement: 'bottom',
  2015. /**
  2016. * Set this to true if you want popper to position it self in 'fixed' mode
  2017. * @prop {Boolean} positionFixed=false
  2018. */
  2019. positionFixed: false,
  2020. /**
  2021. * Whether events (resize, scroll) are initially enabled.
  2022. * @prop {Boolean} eventsEnabled=true
  2023. */
  2024. eventsEnabled: true,
  2025. /**
  2026. * Set to true if you want to automatically remove the popper when
  2027. * you call the `destroy` method.
  2028. * @prop {Boolean} removeOnDestroy=false
  2029. */
  2030. removeOnDestroy: false,
  2031. /**
  2032. * Callback called when the popper is created.<br />
  2033. * By default, it is set to no-op.<br />
  2034. * Access Popper.js instance with `data.instance`.
  2035. * @prop {onCreate}
  2036. */
  2037. onCreate: () => {},
  2038. /**
  2039. * Callback called when the popper is updated. This callback is not called
  2040. * on the initialization/creation of the popper, but only on subsequent
  2041. * updates.<br />
  2042. * By default, it is set to no-op.<br />
  2043. * Access Popper.js instance with `data.instance`.
  2044. * @prop {onUpdate}
  2045. */
  2046. onUpdate: () => {},
  2047. /**
  2048. * List of modifiers used to modify the offsets before they are applied to the popper.
  2049. * They provide most of the functionalities of Popper.js.
  2050. * @prop {modifiers}
  2051. */
  2052. modifiers
  2053. };
  2054. /**
  2055. * @callback onCreate
  2056. * @param {dataObject} data
  2057. */
  2058. /**
  2059. * @callback onUpdate
  2060. * @param {dataObject} data
  2061. */
  2062. // Utils
  2063. // Methods
  2064. class Popper {
  2065. /**
  2066. * Creates a new Popper.js instance.
  2067. * @class Popper
  2068. * @param {Element|referenceObject} reference - The reference element used to position the popper
  2069. * @param {Element} popper - The HTML / XML element used as the popper
  2070. * @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults)
  2071. * @return {Object} instance - The generated Popper.js instance
  2072. */
  2073. constructor(reference, popper, options = {}) {
  2074. this.scheduleUpdate = () => requestAnimationFrame(this.update);
  2075. // make update() debounced, so that it only runs at most once-per-tick
  2076. this.update = debounce(this.update.bind(this));
  2077. // with {} we create a new object with the options inside it
  2078. this.options = _extends({}, Popper.Defaults, options);
  2079. // init state
  2080. this.state = {
  2081. isDestroyed: false,
  2082. isCreated: false,
  2083. scrollParents: []
  2084. };
  2085. // get reference and popper elements (allow jQuery wrappers)
  2086. this.reference = reference && reference.jquery ? reference[0] : reference;
  2087. this.popper = popper && popper.jquery ? popper[0] : popper;
  2088. // Deep merge modifiers options
  2089. this.options.modifiers = {};
  2090. Object.keys(_extends({}, Popper.Defaults.modifiers, options.modifiers)).forEach(name => {
  2091. this.options.modifiers[name] = _extends({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {});
  2092. });
  2093. // Refactoring modifiers' list (Object => Array)
  2094. this.modifiers = Object.keys(this.options.modifiers).map(name => _extends({
  2095. name
  2096. }, this.options.modifiers[name]))
  2097. // sort the modifiers by order
  2098. .sort((a, b) => a.order - b.order);
  2099. // modifiers have the ability to execute arbitrary code when Popper.js get inited
  2100. // such code is executed in the same order of its modifier
  2101. // they could add new properties to their options configuration
  2102. // BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`!
  2103. this.modifiers.forEach(modifierOptions => {
  2104. if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) {
  2105. modifierOptions.onLoad(this.reference, this.popper, this.options, modifierOptions, this.state);
  2106. }
  2107. });
  2108. // fire the first update to position the popper in the right place
  2109. this.update();
  2110. const eventsEnabled = this.options.eventsEnabled;
  2111. if (eventsEnabled) {
  2112. // setup event listeners, they will take care of update the position in specific situations
  2113. this.enableEventListeners();
  2114. }
  2115. this.state.eventsEnabled = eventsEnabled;
  2116. }
  2117. // We can't use class properties because they don't get listed in the
  2118. // class prototype and break stuff like Sinon stubs
  2119. update() {
  2120. return update.call(this);
  2121. }
  2122. destroy() {
  2123. return destroy.call(this);
  2124. }
  2125. enableEventListeners() {
  2126. return enableEventListeners.call(this);
  2127. }
  2128. disableEventListeners() {
  2129. return disableEventListeners.call(this);
  2130. }
  2131. /**
  2132. * Schedules an update. It will run on the next UI update available.
  2133. * @method scheduleUpdate
  2134. * @memberof Popper
  2135. */
  2136. /**
  2137. * Collection of utilities useful when writing custom modifiers.
  2138. * Starting from version 1.7, this method is available only if you
  2139. * include `popper-utils.js` before `popper.js`.
  2140. *
  2141. * **DEPRECATION**: This way to access PopperUtils is deprecated
  2142. * and will be removed in v2! Use the PopperUtils module directly instead.
  2143. * Due to the high instability of the methods contained in Utils, we can't
  2144. * guarantee them to follow semver. Use them at your own risk!
  2145. * @static
  2146. * @private
  2147. * @type {Object}
  2148. * @deprecated since version 1.8
  2149. * @member Utils
  2150. * @memberof Popper
  2151. */
  2152. }
  2153. /**
  2154. * The `referenceObject` is an object that provides an interface compatible with Popper.js
  2155. * and lets you use it as replacement of a real DOM node.<br />
  2156. * You can use this method to position a popper relatively to a set of coordinates
  2157. * in case you don't have a DOM node to use as reference.
  2158. *
  2159. * ```
  2160. * new Popper(referenceObject, popperNode);
  2161. * ```
  2162. *
  2163. * NB: This feature isn't supported in Internet Explorer 10.
  2164. * @name referenceObject
  2165. * @property {Function} data.getBoundingClientRect
  2166. * A function that returns a set of coordinates compatible with the native `getBoundingClientRect` method.
  2167. * @property {number} data.clientWidth
  2168. * An ES6 getter that will return the width of the virtual reference element.
  2169. * @property {number} data.clientHeight
  2170. * An ES6 getter that will return the height of the virtual reference element.
  2171. */
  2172. Popper.Utils = (typeof window !== 'undefined' ? window : global).PopperUtils;
  2173. Popper.placements = placements;
  2174. Popper.Defaults = Defaults;
  2175. export default Popper;
  2176. //# sourceMappingURL=popper.js.map