popper-utils.js 33 KB

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