popper-utils.js 32 KB

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