popper-utils.js 30 KB

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