popper-utils.js 34 KB

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