popper-utils.js 32 KB

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