popper-utils.js 34 KB

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