popper-utils.js 32 KB

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