popper-utils.js 34 KB

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