popper-utils.js 35 KB

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