popper-utils.js 34 KB

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