popper-utils.js 32 KB

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