popper.js 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298
  1. /**!
  2. * @fileOverview Kickass library to create and place poppers near their reference elements.
  3. * @version 1.12.5
  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. const nativeHints = ['native code', '[object MutationObserverConstructor]'];
  26. /**
  27. * Determine if a function is implemented natively (as opposed to a polyfill).
  28. * @method
  29. * @memberof Popper.Utils
  30. * @argument {Function | undefined} fn the function to check
  31. * @returns {Boolean}
  32. */
  33. var isNative = (fn => nativeHints.some(hint => (fn || '').toString().indexOf(hint) > -1));
  34. const isBrowser = typeof window !== 'undefined';
  35. const longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox'];
  36. let timeoutDuration = 0;
  37. for (let i = 0; i < longerTimeoutBrowsers.length; i += 1) {
  38. if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) {
  39. timeoutDuration = 1;
  40. break;
  41. }
  42. }
  43. function microtaskDebounce(fn) {
  44. let scheduled = false;
  45. let i = 0;
  46. const elem = document.createElement('span');
  47. // MutationObserver provides a mechanism for scheduling microtasks, which
  48. // are scheduled *before* the next task. This gives us a way to debounce
  49. // a function but ensure it's called *before* the next paint.
  50. const observer = new MutationObserver(() => {
  51. fn();
  52. scheduled = false;
  53. });
  54. observer.observe(elem, { attributes: true });
  55. return () => {
  56. if (!scheduled) {
  57. scheduled = true;
  58. elem.setAttribute('x-index', i);
  59. i = i + 1; // don't use compund (+=) because it doesn't get optimized in V8
  60. }
  61. };
  62. }
  63. function taskDebounce(fn) {
  64. let scheduled = false;
  65. return () => {
  66. if (!scheduled) {
  67. scheduled = true;
  68. setTimeout(() => {
  69. scheduled = false;
  70. fn();
  71. }, timeoutDuration);
  72. }
  73. };
  74. }
  75. // It's common for MutationObserver polyfills to be seen in the wild, however
  76. // these rely on Mutation Events which only occur when an element is connected
  77. // to the DOM. The algorithm used in this module does not use a connected element,
  78. // and so we must ensure that a *native* MutationObserver is available.
  79. const supportsNativeMutationObserver = isBrowser && isNative(window.MutationObserver);
  80. /**
  81. * Create a debounced version of a method, that's asynchronously deferred
  82. * but called in the minimum time possible.
  83. *
  84. * @method
  85. * @memberof Popper.Utils
  86. * @argument {Function} fn
  87. * @returns {Function}
  88. */
  89. var debounce = supportsNativeMutationObserver ? microtaskDebounce : taskDebounce;
  90. /**
  91. * Check if the given variable is a function
  92. * @method
  93. * @memberof Popper.Utils
  94. * @argument {Any} functionToCheck - variable to check
  95. * @returns {Boolean} answer to: is a function?
  96. */
  97. function isFunction(functionToCheck) {
  98. const getType = {};
  99. return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
  100. }
  101. /**
  102. * Get CSS computed property of the given element
  103. * @method
  104. * @memberof Popper.Utils
  105. * @argument {Eement} element
  106. * @argument {String} property
  107. */
  108. function getStyleComputedProperty(element, property) {
  109. if (element.nodeType !== 1) {
  110. return [];
  111. }
  112. // NOTE: 1 DOM access here
  113. const css = window.getComputedStyle(element, null);
  114. return property ? css[property] : css;
  115. }
  116. /**
  117. * Returns the parentNode or the host of the element
  118. * @method
  119. * @memberof Popper.Utils
  120. * @argument {Element} element
  121. * @returns {Element} parent
  122. */
  123. function getParentNode(element) {
  124. if (element.nodeName === 'HTML') {
  125. return element;
  126. }
  127. return element.parentNode || element.host;
  128. }
  129. /**
  130. * Returns the scrolling parent of the given element
  131. * @method
  132. * @memberof Popper.Utils
  133. * @argument {Element} element
  134. * @returns {Element} scroll parent
  135. */
  136. function getScrollParent(element) {
  137. // Return body, `getScroll` will take care to get the correct `scrollTop` from it
  138. if (!element || ['HTML', 'BODY', '#document'].indexOf(element.nodeName) !== -1) {
  139. return window.document.body;
  140. }
  141. // Firefox want us to check `-x` and `-y` variations as well
  142. const { overflow, overflowX, overflowY } = getStyleComputedProperty(element);
  143. if (/(auto|scroll)/.test(overflow + overflowY + overflowX)) {
  144. return element;
  145. }
  146. return getScrollParent(getParentNode(element));
  147. }
  148. /**
  149. * Returns the offset parent of the given element
  150. * @method
  151. * @memberof Popper.Utils
  152. * @argument {Element} element
  153. * @returns {Element} offset parent
  154. */
  155. function getOffsetParent(element) {
  156. // NOTE: 1 DOM access here
  157. const offsetParent = element && element.offsetParent;
  158. const nodeName = offsetParent && offsetParent.nodeName;
  159. if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') {
  160. return window.document.documentElement;
  161. }
  162. // .offsetParent will return the closest TD or TABLE in case
  163. // no offsetParent is present, I hate this job...
  164. if (['TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') {
  165. return getOffsetParent(offsetParent);
  166. }
  167. return offsetParent;
  168. }
  169. function isOffsetContainer(element) {
  170. const { nodeName } = element;
  171. if (nodeName === 'BODY') {
  172. return false;
  173. }
  174. return nodeName === 'HTML' || getOffsetParent(element.firstElementChild) === element;
  175. }
  176. /**
  177. * Finds the root node (document, shadowDOM root) of the given element
  178. * @method
  179. * @memberof Popper.Utils
  180. * @argument {Element} node
  181. * @returns {Element} root node
  182. */
  183. function getRoot(node) {
  184. if (node.parentNode !== null) {
  185. return getRoot(node.parentNode);
  186. }
  187. return node;
  188. }
  189. /**
  190. * Finds the offset parent common to the two provided nodes
  191. * @method
  192. * @memberof Popper.Utils
  193. * @argument {Element} element1
  194. * @argument {Element} element2
  195. * @returns {Element} common offset parent
  196. */
  197. function findCommonOffsetParent(element1, element2) {
  198. // This check is needed to avoid errors in case one of the elements isn't defined for any reason
  199. if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) {
  200. return window.document.documentElement;
  201. }
  202. // Here we make sure to give as "start" the element that comes first in the DOM
  203. const order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING;
  204. const start = order ? element1 : element2;
  205. const end = order ? element2 : element1;
  206. // Get common ancestor container
  207. const range = document.createRange();
  208. range.setStart(start, 0);
  209. range.setEnd(end, 0);
  210. const { commonAncestorContainer } = range;
  211. // Both nodes are inside #document
  212. if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) {
  213. if (isOffsetContainer(commonAncestorContainer)) {
  214. return commonAncestorContainer;
  215. }
  216. return getOffsetParent(commonAncestorContainer);
  217. }
  218. // one of the nodes is inside shadowDOM, find which one
  219. const element1root = getRoot(element1);
  220. if (element1root.host) {
  221. return findCommonOffsetParent(element1root.host, element2);
  222. } else {
  223. return findCommonOffsetParent(element1, getRoot(element2).host);
  224. }
  225. }
  226. /**
  227. * Gets the scroll value of the given element in the given side (top and left)
  228. * @method
  229. * @memberof Popper.Utils
  230. * @argument {Element} element
  231. * @argument {String} side `top` or `left`
  232. * @returns {number} amount of scrolled pixels
  233. */
  234. function getScroll(element, side = 'top') {
  235. const upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft';
  236. const nodeName = element.nodeName;
  237. if (nodeName === 'BODY' || nodeName === 'HTML') {
  238. const html = window.document.documentElement;
  239. const scrollingElement = window.document.scrollingElement || html;
  240. return scrollingElement[upperSide];
  241. }
  242. return element[upperSide];
  243. }
  244. /*
  245. * Sum or subtract the element scroll values (left and top) from a given rect object
  246. * @method
  247. * @memberof Popper.Utils
  248. * @param {Object} rect - Rect object you want to change
  249. * @param {HTMLElement} element - The element from the function reads the scroll values
  250. * @param {Boolean} subtract - set to true if you want to subtract the scroll values
  251. * @return {Object} rect - The modifier rect object
  252. */
  253. function includeScroll(rect, element, subtract = false) {
  254. const scrollTop = getScroll(element, 'top');
  255. const scrollLeft = getScroll(element, 'left');
  256. const modifier = subtract ? -1 : 1;
  257. rect.top += scrollTop * modifier;
  258. rect.bottom += scrollTop * modifier;
  259. rect.left += scrollLeft * modifier;
  260. rect.right += scrollLeft * modifier;
  261. return rect;
  262. }
  263. /*
  264. * Helper to detect borders of a given element
  265. * @method
  266. * @memberof Popper.Utils
  267. * @param {CSSStyleDeclaration} styles
  268. * Result of `getStyleComputedProperty` on the given element
  269. * @param {String} axis - `x` or `y`
  270. * @return {number} borders - The borders size of the given axis
  271. */
  272. function getBordersSize(styles, axis) {
  273. const sideA = axis === 'x' ? 'Left' : 'Top';
  274. const sideB = sideA === 'Left' ? 'Right' : 'Bottom';
  275. return +styles[`border${sideA}Width`].split('px')[0] + +styles[`border${sideB}Width`].split('px')[0];
  276. }
  277. /**
  278. * Tells if you are running Internet Explorer 10
  279. * @method
  280. * @memberof Popper.Utils
  281. * @returns {Boolean} isIE10
  282. */
  283. let isIE10 = undefined;
  284. var isIE10$1 = function () {
  285. if (isIE10 === undefined) {
  286. isIE10 = navigator.appVersion.indexOf('MSIE 10') !== -1;
  287. }
  288. return isIE10;
  289. };
  290. function getSize(axis, body, html, computedStyle) {
  291. 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);
  292. }
  293. function getWindowSizes() {
  294. const body = window.document.body;
  295. const html = window.document.documentElement;
  296. const computedStyle = isIE10$1() && window.getComputedStyle(html);
  297. return {
  298. height: getSize('Height', body, html, computedStyle),
  299. width: getSize('Width', body, html, computedStyle)
  300. };
  301. }
  302. var _extends = Object.assign || function (target) {
  303. for (var i = 1; i < arguments.length; i++) {
  304. var source = arguments[i];
  305. for (var key in source) {
  306. if (Object.prototype.hasOwnProperty.call(source, key)) {
  307. target[key] = source[key];
  308. }
  309. }
  310. }
  311. return target;
  312. };
  313. /**
  314. * Given element offsets, generate an output similar to getBoundingClientRect
  315. * @method
  316. * @memberof Popper.Utils
  317. * @argument {Object} offsets
  318. * @returns {Object} ClientRect like output
  319. */
  320. function getClientRect(offsets) {
  321. return _extends({}, offsets, {
  322. right: offsets.left + offsets.width,
  323. bottom: offsets.top + offsets.height
  324. });
  325. }
  326. /**
  327. * Get bounding client rect of given element
  328. * @method
  329. * @memberof Popper.Utils
  330. * @param {HTMLElement} element
  331. * @return {Object} client rect
  332. */
  333. function getBoundingClientRect(element) {
  334. let rect = {};
  335. // IE10 10 FIX: Please, don't ask, the element isn't
  336. // considered in DOM in some circumstances...
  337. // This isn't reproducible in IE10 compatibility mode of IE11
  338. if (isIE10$1()) {
  339. try {
  340. rect = element.getBoundingClientRect();
  341. const scrollTop = getScroll(element, 'top');
  342. const scrollLeft = getScroll(element, 'left');
  343. rect.top += scrollTop;
  344. rect.left += scrollLeft;
  345. rect.bottom += scrollTop;
  346. rect.right += scrollLeft;
  347. } catch (err) {}
  348. } else {
  349. rect = element.getBoundingClientRect();
  350. }
  351. const result = {
  352. left: rect.left,
  353. top: rect.top,
  354. width: rect.right - rect.left,
  355. height: rect.bottom - rect.top
  356. };
  357. // subtract scrollbar size from sizes
  358. const sizes = element.nodeName === 'HTML' ? getWindowSizes() : {};
  359. const width = sizes.width || element.clientWidth || result.right - result.left;
  360. const height = sizes.height || element.clientHeight || result.bottom - result.top;
  361. let horizScrollbar = element.offsetWidth - width;
  362. let vertScrollbar = element.offsetHeight - height;
  363. // if an hypothetical scrollbar is detected, we must be sure it's not a `border`
  364. // we make this check conditional for performance reasons
  365. if (horizScrollbar || vertScrollbar) {
  366. const styles = getStyleComputedProperty(element);
  367. horizScrollbar -= getBordersSize(styles, 'x');
  368. vertScrollbar -= getBordersSize(styles, 'y');
  369. result.width -= horizScrollbar;
  370. result.height -= vertScrollbar;
  371. }
  372. return getClientRect(result);
  373. }
  374. function getOffsetRectRelativeToArbitraryNode(children, parent) {
  375. const isIE10 = isIE10$1();
  376. const isHTML = parent.nodeName === 'HTML';
  377. const childrenRect = getBoundingClientRect(children);
  378. const parentRect = getBoundingClientRect(parent);
  379. const scrollParent = getScrollParent(children);
  380. const styles = getStyleComputedProperty(parent);
  381. const borderTopWidth = +styles.borderTopWidth.split('px')[0];
  382. const borderLeftWidth = +styles.borderLeftWidth.split('px')[0];
  383. let offsets = getClientRect({
  384. top: childrenRect.top - parentRect.top - borderTopWidth,
  385. left: childrenRect.left - parentRect.left - borderLeftWidth,
  386. width: childrenRect.width,
  387. height: childrenRect.height
  388. });
  389. offsets.marginTop = 0;
  390. offsets.marginLeft = 0;
  391. // Subtract margins of documentElement in case it's being used as parent
  392. // we do this only on HTML because it's the only element that behaves
  393. // differently when margins are applied to it. The margins are included in
  394. // the box of the documentElement, in the other cases not.
  395. if (!isIE10 && isHTML) {
  396. const marginTop = +styles.marginTop.split('px')[0];
  397. const marginLeft = +styles.marginLeft.split('px')[0];
  398. offsets.top -= borderTopWidth - marginTop;
  399. offsets.bottom -= borderTopWidth - marginTop;
  400. offsets.left -= borderLeftWidth - marginLeft;
  401. offsets.right -= borderLeftWidth - marginLeft;
  402. // Attach marginTop and marginLeft because in some circumstances we may need them
  403. offsets.marginTop = marginTop;
  404. offsets.marginLeft = marginLeft;
  405. }
  406. if (isIE10 ? parent.contains(scrollParent) : parent === scrollParent && scrollParent.nodeName !== 'BODY') {
  407. offsets = includeScroll(offsets, parent);
  408. }
  409. return offsets;
  410. }
  411. function getViewportOffsetRectRelativeToArtbitraryNode(element) {
  412. const html = window.document.documentElement;
  413. const relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html);
  414. const width = Math.max(html.clientWidth, window.innerWidth || 0);
  415. const height = Math.max(html.clientHeight, window.innerHeight || 0);
  416. const scrollTop = getScroll(html);
  417. const scrollLeft = getScroll(html, 'left');
  418. const offset = {
  419. top: scrollTop - relativeOffset.top + relativeOffset.marginTop,
  420. left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft,
  421. width,
  422. height
  423. };
  424. return getClientRect(offset);
  425. }
  426. /**
  427. * Check if the given element is fixed or is inside a fixed parent
  428. * @method
  429. * @memberof Popper.Utils
  430. * @argument {Element} element
  431. * @argument {Element} customContainer
  432. * @returns {Boolean} answer to "isFixed?"
  433. */
  434. function isFixed(element) {
  435. const nodeName = element.nodeName;
  436. if (nodeName === 'BODY' || nodeName === 'HTML') {
  437. return false;
  438. }
  439. if (getStyleComputedProperty(element, 'position') === 'fixed') {
  440. return true;
  441. }
  442. return isFixed(getParentNode(element));
  443. }
  444. /**
  445. * Computed the boundaries limits and return them
  446. * @method
  447. * @memberof Popper.Utils
  448. * @param {HTMLElement} popper
  449. * @param {HTMLElement} reference
  450. * @param {number} padding
  451. * @param {HTMLElement} boundariesElement - Element used to define the boundaries
  452. * @returns {Object} Coordinates of the boundaries
  453. */
  454. function getBoundaries(popper, reference, padding, boundariesElement) {
  455. // NOTE: 1 DOM access here
  456. let boundaries = { top: 0, left: 0 };
  457. const offsetParent = findCommonOffsetParent(popper, reference);
  458. // Handle viewport case
  459. if (boundariesElement === 'viewport') {
  460. boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent);
  461. } else {
  462. // Handle other cases based on DOM element used as boundaries
  463. let boundariesNode;
  464. if (boundariesElement === 'scrollParent') {
  465. boundariesNode = getScrollParent(getParentNode(popper));
  466. if (boundariesNode.nodeName === 'BODY') {
  467. boundariesNode = window.document.documentElement;
  468. }
  469. } else if (boundariesElement === 'window') {
  470. boundariesNode = window.document.documentElement;
  471. } else {
  472. boundariesNode = boundariesElement;
  473. }
  474. const offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent);
  475. // In case of HTML, we need a different computation
  476. if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) {
  477. const { height, width } = getWindowSizes();
  478. boundaries.top += offsets.top - offsets.marginTop;
  479. boundaries.bottom = height + offsets.top;
  480. boundaries.left += offsets.left - offsets.marginLeft;
  481. boundaries.right = width + offsets.left;
  482. } else {
  483. // for all the other DOM elements, this one is good
  484. boundaries = offsets;
  485. }
  486. }
  487. // Add paddings
  488. boundaries.left += padding;
  489. boundaries.top += padding;
  490. boundaries.right -= padding;
  491. boundaries.bottom -= padding;
  492. return boundaries;
  493. }
  494. function getArea({ width, height }) {
  495. return width * height;
  496. }
  497. /**
  498. * Utility used to transform the `auto` placement to the placement with more
  499. * available space.
  500. * @method
  501. * @memberof Popper.Utils
  502. * @argument {Object} data - The data object generated by update method
  503. * @argument {Object} options - Modifiers configuration and options
  504. * @returns {Object} The data object, properly modified
  505. */
  506. function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement, padding = 0) {
  507. if (placement.indexOf('auto') === -1) {
  508. return placement;
  509. }
  510. const boundaries = getBoundaries(popper, reference, padding, boundariesElement);
  511. const rects = {
  512. top: {
  513. width: boundaries.width,
  514. height: refRect.top - boundaries.top
  515. },
  516. right: {
  517. width: boundaries.right - refRect.right,
  518. height: boundaries.height
  519. },
  520. bottom: {
  521. width: boundaries.width,
  522. height: boundaries.bottom - refRect.bottom
  523. },
  524. left: {
  525. width: refRect.left - boundaries.left,
  526. height: boundaries.height
  527. }
  528. };
  529. const sortedAreas = Object.keys(rects).map(key => _extends({
  530. key
  531. }, rects[key], {
  532. area: getArea(rects[key])
  533. })).sort((a, b) => b.area - a.area);
  534. const filteredAreas = sortedAreas.filter(({ width, height }) => width >= popper.clientWidth && height >= popper.clientHeight);
  535. const computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key;
  536. const variation = placement.split('-')[1];
  537. return computedPlacement + (variation ? `-${variation}` : '');
  538. }
  539. /**
  540. * Get offsets to the reference element
  541. * @method
  542. * @memberof Popper.Utils
  543. * @param {Object} state
  544. * @param {Element} popper - the popper element
  545. * @param {Element} reference - the reference element (the popper will be relative to this)
  546. * @returns {Object} An object containing the offsets which will be applied to the popper
  547. */
  548. function getReferenceOffsets(state, popper, reference) {
  549. const commonOffsetParent = findCommonOffsetParent(popper, reference);
  550. return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent);
  551. }
  552. /**
  553. * Get the outer sizes of the given element (offset size + margins)
  554. * @method
  555. * @memberof Popper.Utils
  556. * @argument {Element} element
  557. * @returns {Object} object containing width and height properties
  558. */
  559. function getOuterSizes(element) {
  560. const styles = window.getComputedStyle(element);
  561. const x = parseFloat(styles.marginTop) + parseFloat(styles.marginBottom);
  562. const y = parseFloat(styles.marginLeft) + parseFloat(styles.marginRight);
  563. const result = {
  564. width: element.offsetWidth + y,
  565. height: element.offsetHeight + x
  566. };
  567. return result;
  568. }
  569. /**
  570. * Get the opposite placement of the given one
  571. * @method
  572. * @memberof Popper.Utils
  573. * @argument {String} placement
  574. * @returns {String} flipped placement
  575. */
  576. function getOppositePlacement(placement) {
  577. const hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' };
  578. return placement.replace(/left|right|bottom|top/g, matched => hash[matched]);
  579. }
  580. /**
  581. * Get offsets to the popper
  582. * @method
  583. * @memberof Popper.Utils
  584. * @param {Object} position - CSS position the Popper will get applied
  585. * @param {HTMLElement} popper - the popper element
  586. * @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this)
  587. * @param {String} placement - one of the valid placement options
  588. * @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper
  589. */
  590. function getPopperOffsets(popper, referenceOffsets, placement) {
  591. placement = placement.split('-')[0];
  592. // Get popper node sizes
  593. const popperRect = getOuterSizes(popper);
  594. // Add position, width and height to our offsets object
  595. const popperOffsets = {
  596. width: popperRect.width,
  597. height: popperRect.height
  598. };
  599. // depending by the popper placement we have to compute its offsets slightly differently
  600. const isHoriz = ['right', 'left'].indexOf(placement) !== -1;
  601. const mainSide = isHoriz ? 'top' : 'left';
  602. const secondarySide = isHoriz ? 'left' : 'top';
  603. const measurement = isHoriz ? 'height' : 'width';
  604. const secondaryMeasurement = !isHoriz ? 'height' : 'width';
  605. popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2;
  606. if (placement === secondarySide) {
  607. popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement];
  608. } else {
  609. popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)];
  610. }
  611. return popperOffsets;
  612. }
  613. /**
  614. * Mimics the `find` method of Array
  615. * @method
  616. * @memberof Popper.Utils
  617. * @argument {Array} arr
  618. * @argument prop
  619. * @argument value
  620. * @returns index or -1
  621. */
  622. function find(arr, check) {
  623. // use native find if supported
  624. if (Array.prototype.find) {
  625. return arr.find(check);
  626. }
  627. // use `filter` to obtain the same behavior of `find`
  628. return arr.filter(check)[0];
  629. }
  630. /**
  631. * Return the index of the matching object
  632. * @method
  633. * @memberof Popper.Utils
  634. * @argument {Array} arr
  635. * @argument prop
  636. * @argument value
  637. * @returns index or -1
  638. */
  639. function findIndex(arr, prop, value) {
  640. // use native findIndex if supported
  641. if (Array.prototype.findIndex) {
  642. return arr.findIndex(cur => cur[prop] === value);
  643. }
  644. // use `find` + `indexOf` if `findIndex` isn't supported
  645. const match = find(arr, obj => obj[prop] === value);
  646. return arr.indexOf(match);
  647. }
  648. /**
  649. * Loop trough the list of modifiers and run them in order,
  650. * each of them will then edit the data object.
  651. * @method
  652. * @memberof Popper.Utils
  653. * @param {dataObject} data
  654. * @param {Array} modifiers
  655. * @param {String} ends - Optional modifier name used as stopper
  656. * @returns {dataObject}
  657. */
  658. function runModifiers(modifiers, data, ends) {
  659. const modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends));
  660. modifiersToRun.forEach(modifier => {
  661. if (modifier.function) {
  662. console.warn('`modifier.function` is deprecated, use `modifier.fn`!');
  663. }
  664. const fn = modifier.function || modifier.fn;
  665. if (modifier.enabled && isFunction(fn)) {
  666. // Add properties to offsets to make them a complete clientRect object
  667. // we do this before each modifier to make sure the previous one doesn't
  668. // mess with these values
  669. data.offsets.popper = getClientRect(data.offsets.popper);
  670. data.offsets.reference = getClientRect(data.offsets.reference);
  671. data = fn(data, modifier);
  672. }
  673. });
  674. return data;
  675. }
  676. /**
  677. * Updates the position of the popper, computing the new offsets and applying
  678. * the new style.<br />
  679. * Prefer `scheduleUpdate` over `update` because of performance reasons.
  680. * @method
  681. * @memberof Popper
  682. */
  683. function update() {
  684. // if popper is destroyed, don't perform any further update
  685. if (this.state.isDestroyed) {
  686. return;
  687. }
  688. let data = {
  689. instance: this,
  690. styles: {},
  691. arrowStyles: {},
  692. attributes: {},
  693. flipped: false,
  694. offsets: {}
  695. };
  696. // compute reference element offsets
  697. data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference);
  698. // compute auto placement, store placement inside the data object,
  699. // modifiers will be able to edit `placement` if needed
  700. // and refer to originalPlacement to know the original value
  701. data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding);
  702. // store the computed placement inside `originalPlacement`
  703. data.originalPlacement = data.placement;
  704. // compute the popper offsets
  705. data.offsets.popper = getPopperOffsets(this.popper, data.offsets.reference, data.placement);
  706. data.offsets.popper.position = 'absolute';
  707. // run the modifiers
  708. data = runModifiers(this.modifiers, data);
  709. // the first `update` will call `onCreate` callback
  710. // the other ones will call `onUpdate` callback
  711. if (!this.state.isCreated) {
  712. this.state.isCreated = true;
  713. this.options.onCreate(data);
  714. } else {
  715. this.options.onUpdate(data);
  716. }
  717. }
  718. /**
  719. * Helper used to know if the given modifier is enabled.
  720. * @method
  721. * @memberof Popper.Utils
  722. * @returns {Boolean}
  723. */
  724. function isModifierEnabled(modifiers, modifierName) {
  725. return modifiers.some(({ name, enabled }) => enabled && name === modifierName);
  726. }
  727. /**
  728. * Get the prefixed supported property name
  729. * @method
  730. * @memberof Popper.Utils
  731. * @argument {String} property (camelCase)
  732. * @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix)
  733. */
  734. function getSupportedPropertyName(property) {
  735. const prefixes = [false, 'ms', 'Webkit', 'Moz', 'O'];
  736. const upperProp = property.charAt(0).toUpperCase() + property.slice(1);
  737. for (let i = 0; i < prefixes.length - 1; i++) {
  738. const prefix = prefixes[i];
  739. const toCheck = prefix ? `${prefix}${upperProp}` : property;
  740. if (typeof window.document.body.style[toCheck] !== 'undefined') {
  741. return toCheck;
  742. }
  743. }
  744. return null;
  745. }
  746. /**
  747. * Destroy the popper
  748. * @method
  749. * @memberof Popper
  750. */
  751. function destroy() {
  752. this.state.isDestroyed = true;
  753. // touch DOM only if `applyStyle` modifier is enabled
  754. if (isModifierEnabled(this.modifiers, 'applyStyle')) {
  755. this.popper.removeAttribute('x-placement');
  756. this.popper.style.left = '';
  757. this.popper.style.position = '';
  758. this.popper.style.top = '';
  759. this.popper.style[getSupportedPropertyName('transform')] = '';
  760. }
  761. this.disableEventListeners();
  762. // remove the popper if user explicity asked for the deletion on destroy
  763. // do not use `remove` because IE11 doesn't support it
  764. if (this.options.removeOnDestroy) {
  765. this.popper.parentNode.removeChild(this.popper);
  766. }
  767. return this;
  768. }
  769. function attachToScrollParents(scrollParent, event, callback, scrollParents) {
  770. const isBody = scrollParent.nodeName === 'BODY';
  771. const target = isBody ? window : scrollParent;
  772. target.addEventListener(event, callback, { passive: true });
  773. if (!isBody) {
  774. attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents);
  775. }
  776. scrollParents.push(target);
  777. }
  778. /**
  779. * Setup needed event listeners used to update the popper position
  780. * @method
  781. * @memberof Popper.Utils
  782. * @private
  783. */
  784. function setupEventListeners(reference, options, state, updateBound) {
  785. // Resize event listener on window
  786. state.updateBound = updateBound;
  787. window.addEventListener('resize', state.updateBound, { passive: true });
  788. // Scroll event listener on scroll parents
  789. const scrollElement = getScrollParent(reference);
  790. attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents);
  791. state.scrollElement = scrollElement;
  792. state.eventsEnabled = true;
  793. return state;
  794. }
  795. /**
  796. * It will add resize/scroll events and start recalculating
  797. * position of the popper element when they are triggered.
  798. * @method
  799. * @memberof Popper
  800. */
  801. function enableEventListeners() {
  802. if (!this.state.eventsEnabled) {
  803. this.state = setupEventListeners(this.reference, this.options, this.state, this.scheduleUpdate);
  804. }
  805. }
  806. /**
  807. * Remove event listeners used to update the popper position
  808. * @method
  809. * @memberof Popper.Utils
  810. * @private
  811. */
  812. function removeEventListeners(reference, state) {
  813. // Remove resize event listener on window
  814. window.removeEventListener('resize', state.updateBound);
  815. // Remove scroll event listener on scroll parents
  816. state.scrollParents.forEach(target => {
  817. target.removeEventListener('scroll', state.updateBound);
  818. });
  819. // Reset state
  820. state.updateBound = null;
  821. state.scrollParents = [];
  822. state.scrollElement = null;
  823. state.eventsEnabled = false;
  824. return state;
  825. }
  826. /**
  827. * It will remove resize/scroll events and won't recalculate popper position
  828. * when they are triggered. It also won't trigger onUpdate callback anymore,
  829. * unless you call `update` method manually.
  830. * @method
  831. * @memberof Popper
  832. */
  833. function disableEventListeners() {
  834. if (this.state.eventsEnabled) {
  835. window.cancelAnimationFrame(this.scheduleUpdate);
  836. this.state = removeEventListeners(this.reference, this.state);
  837. }
  838. }
  839. /**
  840. * Tells if a given input is a number
  841. * @method
  842. * @memberof Popper.Utils
  843. * @param {*} input to check
  844. * @return {Boolean}
  845. */
  846. function isNumeric(n) {
  847. return n !== '' && !isNaN(parseFloat(n)) && isFinite(n);
  848. }
  849. /**
  850. * Set the style to the given popper
  851. * @method
  852. * @memberof Popper.Utils
  853. * @argument {Element} element - Element to apply the style to
  854. * @argument {Object} styles
  855. * Object with a list of properties and values which will be applied to the element
  856. */
  857. function setStyles(element, styles) {
  858. Object.keys(styles).forEach(prop => {
  859. let unit = '';
  860. // add unit if the value is numeric and is one of the following
  861. if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) {
  862. unit = 'px';
  863. }
  864. element.style[prop] = styles[prop] + unit;
  865. });
  866. }
  867. /**
  868. * Set the attributes to the given popper
  869. * @method
  870. * @memberof Popper.Utils
  871. * @argument {Element} element - Element to apply the attributes to
  872. * @argument {Object} styles
  873. * Object with a list of properties and values which will be applied to the element
  874. */
  875. function setAttributes(element, attributes) {
  876. Object.keys(attributes).forEach(function (prop) {
  877. const value = attributes[prop];
  878. if (value !== false) {
  879. element.setAttribute(prop, attributes[prop]);
  880. } else {
  881. element.removeAttribute(prop);
  882. }
  883. });
  884. }
  885. /**
  886. * @function
  887. * @memberof Modifiers
  888. * @argument {Object} data - The data object generated by `update` method
  889. * @argument {Object} data.styles - List of style properties - values to apply to popper element
  890. * @argument {Object} data.attributes - List of attribute properties - values to apply to popper element
  891. * @argument {Object} options - Modifiers configuration and options
  892. * @returns {Object} The same data object
  893. */
  894. function applyStyle(data) {
  895. // any property present in `data.styles` will be applied to the popper,
  896. // in this way we can make the 3rd party modifiers add custom styles to it
  897. // Be aware, modifiers could override the properties defined in the previous
  898. // lines of this modifier!
  899. setStyles(data.instance.popper, data.styles);
  900. // any property present in `data.attributes` will be applied to the popper,
  901. // they will be set as HTML attributes of the element
  902. setAttributes(data.instance.popper, data.attributes);
  903. // if arrowElement is defined and arrowStyles has some properties
  904. if (data.arrowElement && Object.keys(data.arrowStyles).length) {
  905. setStyles(data.arrowElement, data.arrowStyles);
  906. }
  907. return data;
  908. }
  909. /**
  910. * Set the x-placement attribute before everything else because it could be used
  911. * to add margins to the popper margins needs to be calculated to get the
  912. * correct popper offsets.
  913. * @method
  914. * @memberof Popper.modifiers
  915. * @param {HTMLElement} reference - The reference element used to position the popper
  916. * @param {HTMLElement} popper - The HTML element used as popper.
  917. * @param {Object} options - Popper.js options
  918. */
  919. function applyStyleOnLoad(reference, popper, options, modifierOptions, state) {
  920. // compute reference element offsets
  921. const referenceOffsets = getReferenceOffsets(state, popper, reference);
  922. // compute auto placement, store placement inside the data object,
  923. // modifiers will be able to edit `placement` if needed
  924. // and refer to originalPlacement to know the original value
  925. const placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding);
  926. popper.setAttribute('x-placement', placement);
  927. // Apply `position` to popper before anything else because
  928. // without the position applied we can't guarantee correct computations
  929. setStyles(popper, { position: 'absolute' });
  930. return options;
  931. }
  932. /**
  933. * @function
  934. * @memberof Modifiers
  935. * @argument {Object} data - The data object generated by `update` method
  936. * @argument {Object} options - Modifiers configuration and options
  937. * @returns {Object} The data object, properly modified
  938. */
  939. function computeStyle(data, options) {
  940. const { x, y } = options;
  941. const { popper } = data.offsets;
  942. // Remove this legacy support in Popper.js v2
  943. const legacyGpuAccelerationOption = find(data.instance.modifiers, modifier => modifier.name === 'applyStyle').gpuAcceleration;
  944. if (legacyGpuAccelerationOption !== undefined) {
  945. console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!');
  946. }
  947. const gpuAcceleration = legacyGpuAccelerationOption !== undefined ? legacyGpuAccelerationOption : options.gpuAcceleration;
  948. const offsetParent = getOffsetParent(data.instance.popper);
  949. const offsetParentRect = getBoundingClientRect(offsetParent);
  950. // Styles
  951. const styles = {
  952. position: popper.position
  953. };
  954. // floor sides to avoid blurry text
  955. const offsets = {
  956. left: Math.floor(popper.left),
  957. top: Math.floor(popper.top),
  958. bottom: Math.floor(popper.bottom),
  959. right: Math.floor(popper.right)
  960. };
  961. const sideA = x === 'bottom' ? 'top' : 'bottom';
  962. const sideB = y === 'right' ? 'left' : 'right';
  963. // if gpuAcceleration is set to `true` and transform is supported,
  964. // we use `translate3d` to apply the position to the popper we
  965. // automatically use the supported prefixed version if needed
  966. const prefixedProperty = getSupportedPropertyName('transform');
  967. // now, let's make a step back and look at this code closely (wtf?)
  968. // If the content of the popper grows once it's been positioned, it
  969. // may happen that the popper gets misplaced because of the new content
  970. // overflowing its reference element
  971. // To avoid this problem, we provide two options (x and y), which allow
  972. // the consumer to define the offset origin.
  973. // If we position a popper on top of a reference element, we can set
  974. // `x` to `top` to make the popper grow towards its top instead of
  975. // its bottom.
  976. let left, top;
  977. if (sideA === 'bottom') {
  978. top = -offsetParentRect.height + offsets.bottom;
  979. } else {
  980. top = offsets.top;
  981. }
  982. if (sideB === 'right') {
  983. left = -offsetParentRect.width + offsets.right;
  984. } else {
  985. left = offsets.left;
  986. }
  987. if (gpuAcceleration && prefixedProperty) {
  988. styles[prefixedProperty] = `translate3d(${left}px, ${top}px, 0)`;
  989. styles[sideA] = 0;
  990. styles[sideB] = 0;
  991. styles.willChange = 'transform';
  992. } else {
  993. // othwerise, we use the standard `top`, `left`, `bottom` and `right` properties
  994. const invertTop = sideA === 'bottom' ? -1 : 1;
  995. const invertLeft = sideB === 'right' ? -1 : 1;
  996. styles[sideA] = top * invertTop;
  997. styles[sideB] = left * invertLeft;
  998. styles.willChange = `${sideA}, ${sideB}`;
  999. }
  1000. // Attributes
  1001. const attributes = {
  1002. 'x-placement': data.placement
  1003. };
  1004. // Update `data` attributes, styles and arrowStyles
  1005. data.attributes = _extends({}, attributes, data.attributes);
  1006. data.styles = _extends({}, styles, data.styles);
  1007. data.arrowStyles = _extends({}, data.offsets.arrow, data.arrowStyles);
  1008. return data;
  1009. }
  1010. /**
  1011. * Helper used to know if the given modifier depends from another one.<br />
  1012. * It checks if the needed modifier is listed and enabled.
  1013. * @method
  1014. * @memberof Popper.Utils
  1015. * @param {Array} modifiers - list of modifiers
  1016. * @param {String} requestingName - name of requesting modifier
  1017. * @param {String} requestedName - name of requested modifier
  1018. * @returns {Boolean}
  1019. */
  1020. function isModifierRequired(modifiers, requestingName, requestedName) {
  1021. const requesting = find(modifiers, ({ name }) => name === requestingName);
  1022. const isRequired = !!requesting && modifiers.some(modifier => {
  1023. return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order;
  1024. });
  1025. if (!isRequired) {
  1026. const requesting = `\`${requestingName}\``;
  1027. const requested = `\`${requestedName}\``;
  1028. console.warn(`${requested} modifier is required by ${requesting} modifier in order to work, be sure to include it before ${requesting}!`);
  1029. }
  1030. return isRequired;
  1031. }
  1032. /**
  1033. * @function
  1034. * @memberof Modifiers
  1035. * @argument {Object} data - The data object generated by update method
  1036. * @argument {Object} options - Modifiers configuration and options
  1037. * @returns {Object} The data object, properly modified
  1038. */
  1039. function arrow(data, options) {
  1040. // arrow depends on keepTogether in order to work
  1041. if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) {
  1042. return data;
  1043. }
  1044. let arrowElement = options.element;
  1045. // if arrowElement is a string, suppose it's a CSS selector
  1046. if (typeof arrowElement === 'string') {
  1047. arrowElement = data.instance.popper.querySelector(arrowElement);
  1048. // if arrowElement is not found, don't run the modifier
  1049. if (!arrowElement) {
  1050. return data;
  1051. }
  1052. } else {
  1053. // if the arrowElement isn't a query selector we must check that the
  1054. // provided DOM node is child of its popper node
  1055. if (!data.instance.popper.contains(arrowElement)) {
  1056. console.warn('WARNING: `arrow.element` must be child of its popper element!');
  1057. return data;
  1058. }
  1059. }
  1060. const placement = data.placement.split('-')[0];
  1061. const { popper, reference } = data.offsets;
  1062. const isVertical = ['left', 'right'].indexOf(placement) !== -1;
  1063. const len = isVertical ? 'height' : 'width';
  1064. const sideCapitalized = isVertical ? 'Top' : 'Left';
  1065. const side = sideCapitalized.toLowerCase();
  1066. const altSide = isVertical ? 'left' : 'top';
  1067. const opSide = isVertical ? 'bottom' : 'right';
  1068. const arrowElementSize = getOuterSizes(arrowElement)[len];
  1069. //
  1070. // extends keepTogether behavior making sure the popper and its
  1071. // reference have enough pixels in conjuction
  1072. //
  1073. // top/left side
  1074. if (reference[opSide] - arrowElementSize < popper[side]) {
  1075. data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowElementSize);
  1076. }
  1077. // bottom/right side
  1078. if (reference[side] + arrowElementSize > popper[opSide]) {
  1079. data.offsets.popper[side] += reference[side] + arrowElementSize - popper[opSide];
  1080. }
  1081. // compute center of the popper
  1082. const center = reference[side] + reference[len] / 2 - arrowElementSize / 2;
  1083. // Compute the sideValue using the updated popper offsets
  1084. // take popper margin in account because we don't have this info available
  1085. const popperMarginSide = getStyleComputedProperty(data.instance.popper, `margin${sideCapitalized}`).replace('px', '');
  1086. let sideValue = center - getClientRect(data.offsets.popper)[side] - popperMarginSide;
  1087. // prevent arrowElement from being placed not contiguously to its popper
  1088. sideValue = Math.max(Math.min(popper[len] - arrowElementSize, sideValue), 0);
  1089. data.arrowElement = arrowElement;
  1090. data.offsets.arrow = {};
  1091. data.offsets.arrow[side] = Math.round(sideValue);
  1092. data.offsets.arrow[altSide] = ''; // make sure to unset any eventual altSide value from the DOM node
  1093. return data;
  1094. }
  1095. /**
  1096. * Get the opposite placement variation of the given one
  1097. * @method
  1098. * @memberof Popper.Utils
  1099. * @argument {String} placement variation
  1100. * @returns {String} flipped placement variation
  1101. */
  1102. function getOppositeVariation(variation) {
  1103. if (variation === 'end') {
  1104. return 'start';
  1105. } else if (variation === 'start') {
  1106. return 'end';
  1107. }
  1108. return variation;
  1109. }
  1110. /**
  1111. * List of accepted placements to use as values of the `placement` option.<br />
  1112. * Valid placements are:
  1113. * - `auto`
  1114. * - `top`
  1115. * - `right`
  1116. * - `bottom`
  1117. * - `left`
  1118. *
  1119. * Each placement can have a variation from this list:
  1120. * - `-start`
  1121. * - `-end`
  1122. *
  1123. * Variations are interpreted easily if you think of them as the left to right
  1124. * written languages. Horizontally (`top` and `bottom`), `start` is left and `end`
  1125. * is right.<br />
  1126. * Vertically (`left` and `right`), `start` is top and `end` is bottom.
  1127. *
  1128. * Some valid examples are:
  1129. * - `top-end` (on top of reference, right aligned)
  1130. * - `right-start` (on right of reference, top aligned)
  1131. * - `bottom` (on bottom, centered)
  1132. * - `auto-right` (on the side with more space available, alignment depends by placement)
  1133. *
  1134. * @static
  1135. * @type {Array}
  1136. * @enum {String}
  1137. * @readonly
  1138. * @method placements
  1139. * @memberof Popper
  1140. */
  1141. var placements = ['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start'];
  1142. // Get rid of `auto` `auto-start` and `auto-end`
  1143. const validPlacements = placements.slice(3);
  1144. /**
  1145. * Given an initial placement, returns all the subsequent placements
  1146. * clockwise (or counter-clockwise).
  1147. *
  1148. * @method
  1149. * @memberof Popper.Utils
  1150. * @argument {String} placement - A valid placement (it accepts variations)
  1151. * @argument {Boolean} counter - Set to true to walk the placements counterclockwise
  1152. * @returns {Array} placements including their variations
  1153. */
  1154. function clockwise(placement, counter = false) {
  1155. const index = validPlacements.indexOf(placement);
  1156. const arr = validPlacements.slice(index + 1).concat(validPlacements.slice(0, index));
  1157. return counter ? arr.reverse() : arr;
  1158. }
  1159. const BEHAVIORS = {
  1160. FLIP: 'flip',
  1161. CLOCKWISE: 'clockwise',
  1162. COUNTERCLOCKWISE: 'counterclockwise'
  1163. };
  1164. /**
  1165. * @function
  1166. * @memberof Modifiers
  1167. * @argument {Object} data - The data object generated by update method
  1168. * @argument {Object} options - Modifiers configuration and options
  1169. * @returns {Object} The data object, properly modified
  1170. */
  1171. function flip(data, options) {
  1172. // if `inner` modifier is enabled, we can't use the `flip` modifier
  1173. if (isModifierEnabled(data.instance.modifiers, 'inner')) {
  1174. return data;
  1175. }
  1176. if (data.flipped && data.placement === data.originalPlacement) {
  1177. // seems like flip is trying to loop, probably there's not enough space on any of the flippable sides
  1178. return data;
  1179. }
  1180. const boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, options.boundariesElement);
  1181. let placement = data.placement.split('-')[0];
  1182. let placementOpposite = getOppositePlacement(placement);
  1183. let variation = data.placement.split('-')[1] || '';
  1184. let flipOrder = [];
  1185. switch (options.behavior) {
  1186. case BEHAVIORS.FLIP:
  1187. flipOrder = [placement, placementOpposite];
  1188. break;
  1189. case BEHAVIORS.CLOCKWISE:
  1190. flipOrder = clockwise(placement);
  1191. break;
  1192. case BEHAVIORS.COUNTERCLOCKWISE:
  1193. flipOrder = clockwise(placement, true);
  1194. break;
  1195. default:
  1196. flipOrder = options.behavior;
  1197. }
  1198. flipOrder.forEach((step, index) => {
  1199. if (placement !== step || flipOrder.length === index + 1) {
  1200. return data;
  1201. }
  1202. placement = data.placement.split('-')[0];
  1203. placementOpposite = getOppositePlacement(placement);
  1204. const popperOffsets = data.offsets.popper;
  1205. const refOffsets = data.offsets.reference;
  1206. // using floor because the reference offsets may contain decimals we are not going to consider here
  1207. const floor = Math.floor;
  1208. const overlapsRef = placement === 'left' && floor(popperOffsets.right) > floor(refOffsets.left) || placement === 'right' && floor(popperOffsets.left) < floor(refOffsets.right) || placement === 'top' && floor(popperOffsets.bottom) > floor(refOffsets.top) || placement === 'bottom' && floor(popperOffsets.top) < floor(refOffsets.bottom);
  1209. const overflowsLeft = floor(popperOffsets.left) < floor(boundaries.left);
  1210. const overflowsRight = floor(popperOffsets.right) > floor(boundaries.right);
  1211. const overflowsTop = floor(popperOffsets.top) < floor(boundaries.top);
  1212. const overflowsBottom = floor(popperOffsets.bottom) > floor(boundaries.bottom);
  1213. const overflowsBoundaries = placement === 'left' && overflowsLeft || placement === 'right' && overflowsRight || placement === 'top' && overflowsTop || placement === 'bottom' && overflowsBottom;
  1214. // flip the variation if required
  1215. const isVertical = ['top', 'bottom'].indexOf(placement) !== -1;
  1216. const flippedVariation = !!options.flipVariations && (isVertical && variation === 'start' && overflowsLeft || isVertical && variation === 'end' && overflowsRight || !isVertical && variation === 'start' && overflowsTop || !isVertical && variation === 'end' && overflowsBottom);
  1217. if (overlapsRef || overflowsBoundaries || flippedVariation) {
  1218. // this boolean to detect any flip loop
  1219. data.flipped = true;
  1220. if (overlapsRef || overflowsBoundaries) {
  1221. placement = flipOrder[index + 1];
  1222. }
  1223. if (flippedVariation) {
  1224. variation = getOppositeVariation(variation);
  1225. }
  1226. data.placement = placement + (variation ? '-' + variation : '');
  1227. // this object contains `position`, we want to preserve it along with
  1228. // any additional property we may add in the future
  1229. data.offsets.popper = _extends({}, data.offsets.popper, getPopperOffsets(data.instance.popper, data.offsets.reference, data.placement));
  1230. data = runModifiers(data.instance.modifiers, data, 'flip');
  1231. }
  1232. });
  1233. return data;
  1234. }
  1235. /**
  1236. * @function
  1237. * @memberof Modifiers
  1238. * @argument {Object} data - The data object generated by update method
  1239. * @argument {Object} options - Modifiers configuration and options
  1240. * @returns {Object} The data object, properly modified
  1241. */
  1242. function keepTogether(data) {
  1243. const { popper, reference } = data.offsets;
  1244. const placement = data.placement.split('-')[0];
  1245. const floor = Math.floor;
  1246. const isVertical = ['top', 'bottom'].indexOf(placement) !== -1;
  1247. const side = isVertical ? 'right' : 'bottom';
  1248. const opSide = isVertical ? 'left' : 'top';
  1249. const measurement = isVertical ? 'width' : 'height';
  1250. if (popper[side] < floor(reference[opSide])) {
  1251. data.offsets.popper[opSide] = floor(reference[opSide]) - popper[measurement];
  1252. }
  1253. if (popper[opSide] > floor(reference[side])) {
  1254. data.offsets.popper[opSide] = floor(reference[side]);
  1255. }
  1256. return data;
  1257. }
  1258. /**
  1259. * Converts a string containing value + unit into a px value number
  1260. * @function
  1261. * @memberof {modifiers~offset}
  1262. * @private
  1263. * @argument {String} str - Value + unit string
  1264. * @argument {String} measurement - `height` or `width`
  1265. * @argument {Object} popperOffsets
  1266. * @argument {Object} referenceOffsets
  1267. * @returns {Number|String}
  1268. * Value in pixels, or original string if no values were extracted
  1269. */
  1270. function toValue(str, measurement, popperOffsets, referenceOffsets) {
  1271. // separate value from unit
  1272. const split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/);
  1273. const value = +split[1];
  1274. const unit = split[2];
  1275. // If it's not a number it's an operator, I guess
  1276. if (!value) {
  1277. return str;
  1278. }
  1279. if (unit.indexOf('%') === 0) {
  1280. let element;
  1281. switch (unit) {
  1282. case '%p':
  1283. element = popperOffsets;
  1284. break;
  1285. case '%':
  1286. case '%r':
  1287. default:
  1288. element = referenceOffsets;
  1289. }
  1290. const rect = getClientRect(element);
  1291. return rect[measurement] / 100 * value;
  1292. } else if (unit === 'vh' || unit === 'vw') {
  1293. // if is a vh or vw, we calculate the size based on the viewport
  1294. let size;
  1295. if (unit === 'vh') {
  1296. size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
  1297. } else {
  1298. size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
  1299. }
  1300. return size / 100 * value;
  1301. } else {
  1302. // if is an explicit pixel unit, we get rid of the unit and keep the value
  1303. // if is an implicit unit, it's px, and we return just the value
  1304. return value;
  1305. }
  1306. }
  1307. /**
  1308. * Parse an `offset` string to extrapolate `x` and `y` numeric offsets.
  1309. * @function
  1310. * @memberof {modifiers~offset}
  1311. * @private
  1312. * @argument {String} offset
  1313. * @argument {Object} popperOffsets
  1314. * @argument {Object} referenceOffsets
  1315. * @argument {String} basePlacement
  1316. * @returns {Array} a two cells array with x and y offsets in numbers
  1317. */
  1318. function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) {
  1319. const offsets = [0, 0];
  1320. // Use height if placement is left or right and index is 0 otherwise use width
  1321. // in this way the first offset will use an axis and the second one
  1322. // will use the other one
  1323. const useHeight = ['right', 'left'].indexOf(basePlacement) !== -1;
  1324. // Split the offset string to obtain a list of values and operands
  1325. // The regex addresses values with the plus or minus sign in front (+10, -20, etc)
  1326. const fragments = offset.split(/(\+|\-)/).map(frag => frag.trim());
  1327. // Detect if the offset string contains a pair of values or a single one
  1328. // they could be separated by comma or space
  1329. const divider = fragments.indexOf(find(fragments, frag => frag.search(/,|\s/) !== -1));
  1330. if (fragments[divider] && fragments[divider].indexOf(',') === -1) {
  1331. console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.');
  1332. }
  1333. // If divider is found, we divide the list of values and operands to divide
  1334. // them by ofset X and Y.
  1335. const splitRegex = /\s*,\s*|\s+/;
  1336. let ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments];
  1337. // Convert the values with units to absolute pixels to allow our computations
  1338. ops = ops.map((op, index) => {
  1339. // Most of the units rely on the orientation of the popper
  1340. const measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width';
  1341. let mergeWithPrevious = false;
  1342. return op
  1343. // This aggregates any `+` or `-` sign that aren't considered operators
  1344. // e.g.: 10 + +5 => [10, +, +5]
  1345. .reduce((a, b) => {
  1346. if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) {
  1347. a[a.length - 1] = b;
  1348. mergeWithPrevious = true;
  1349. return a;
  1350. } else if (mergeWithPrevious) {
  1351. a[a.length - 1] += b;
  1352. mergeWithPrevious = false;
  1353. return a;
  1354. } else {
  1355. return a.concat(b);
  1356. }
  1357. }, [])
  1358. // Here we convert the string values into number values (in px)
  1359. .map(str => toValue(str, measurement, popperOffsets, referenceOffsets));
  1360. });
  1361. // Loop trough the offsets arrays and execute the operations
  1362. ops.forEach((op, index) => {
  1363. op.forEach((frag, index2) => {
  1364. if (isNumeric(frag)) {
  1365. offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1);
  1366. }
  1367. });
  1368. });
  1369. return offsets;
  1370. }
  1371. /**
  1372. * @function
  1373. * @memberof Modifiers
  1374. * @argument {Object} data - The data object generated by update method
  1375. * @argument {Object} options - Modifiers configuration and options
  1376. * @argument {Number|String} options.offset=0
  1377. * The offset value as described in the modifier description
  1378. * @returns {Object} The data object, properly modified
  1379. */
  1380. function offset(data, { offset }) {
  1381. const { placement, offsets: { popper, reference } } = data;
  1382. const basePlacement = placement.split('-')[0];
  1383. let offsets;
  1384. if (isNumeric(+offset)) {
  1385. offsets = [+offset, 0];
  1386. } else {
  1387. offsets = parseOffset(offset, popper, reference, basePlacement);
  1388. }
  1389. if (basePlacement === 'left') {
  1390. popper.top += offsets[0];
  1391. popper.left -= offsets[1];
  1392. } else if (basePlacement === 'right') {
  1393. popper.top += offsets[0];
  1394. popper.left += offsets[1];
  1395. } else if (basePlacement === 'top') {
  1396. popper.left += offsets[0];
  1397. popper.top -= offsets[1];
  1398. } else if (basePlacement === 'bottom') {
  1399. popper.left += offsets[0];
  1400. popper.top += offsets[1];
  1401. }
  1402. data.popper = popper;
  1403. return data;
  1404. }
  1405. /**
  1406. * @function
  1407. * @memberof Modifiers
  1408. * @argument {Object} data - The data object generated by `update` method
  1409. * @argument {Object} options - Modifiers configuration and options
  1410. * @returns {Object} The data object, properly modified
  1411. */
  1412. function preventOverflow(data, options) {
  1413. let boundariesElement = options.boundariesElement || getOffsetParent(data.instance.popper);
  1414. // If offsetParent is the reference element, we really want to
  1415. // go one step up and use the next offsetParent as reference to
  1416. // avoid to make this modifier completely useless and look like broken
  1417. if (data.instance.reference === boundariesElement) {
  1418. boundariesElement = getOffsetParent(boundariesElement);
  1419. }
  1420. const boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, boundariesElement);
  1421. options.boundaries = boundaries;
  1422. const order = options.priority;
  1423. let popper = data.offsets.popper;
  1424. const check = {
  1425. primary(placement) {
  1426. let value = popper[placement];
  1427. if (popper[placement] < boundaries[placement] && !options.escapeWithReference) {
  1428. value = Math.max(popper[placement], boundaries[placement]);
  1429. }
  1430. return { [placement]: value };
  1431. },
  1432. secondary(placement) {
  1433. const mainSide = placement === 'right' ? 'left' : 'top';
  1434. let value = popper[mainSide];
  1435. if (popper[placement] > boundaries[placement] && !options.escapeWithReference) {
  1436. value = Math.min(popper[mainSide], boundaries[placement] - (placement === 'right' ? popper.width : popper.height));
  1437. }
  1438. return { [mainSide]: value };
  1439. }
  1440. };
  1441. order.forEach(placement => {
  1442. const side = ['left', 'top'].indexOf(placement) !== -1 ? 'primary' : 'secondary';
  1443. popper = _extends({}, popper, check[side](placement));
  1444. });
  1445. data.offsets.popper = popper;
  1446. return data;
  1447. }
  1448. /**
  1449. * @function
  1450. * @memberof Modifiers
  1451. * @argument {Object} data - The data object generated by `update` method
  1452. * @argument {Object} options - Modifiers configuration and options
  1453. * @returns {Object} The data object, properly modified
  1454. */
  1455. function shift(data) {
  1456. const placement = data.placement;
  1457. const basePlacement = placement.split('-')[0];
  1458. const shiftvariation = placement.split('-')[1];
  1459. // if shift shiftvariation is specified, run the modifier
  1460. if (shiftvariation) {
  1461. const { reference, popper } = data.offsets;
  1462. const isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1;
  1463. const side = isVertical ? 'left' : 'top';
  1464. const measurement = isVertical ? 'width' : 'height';
  1465. const shiftOffsets = {
  1466. start: { [side]: reference[side] },
  1467. end: {
  1468. [side]: reference[side] + reference[measurement] - popper[measurement]
  1469. }
  1470. };
  1471. data.offsets.popper = _extends({}, popper, shiftOffsets[shiftvariation]);
  1472. }
  1473. return data;
  1474. }
  1475. /**
  1476. * @function
  1477. * @memberof Modifiers
  1478. * @argument {Object} data - The data object generated by update method
  1479. * @argument {Object} options - Modifiers configuration and options
  1480. * @returns {Object} The data object, properly modified
  1481. */
  1482. function hide(data) {
  1483. if (!isModifierRequired(data.instance.modifiers, 'hide', 'preventOverflow')) {
  1484. return data;
  1485. }
  1486. const refRect = data.offsets.reference;
  1487. const bound = find(data.instance.modifiers, modifier => modifier.name === 'preventOverflow').boundaries;
  1488. if (refRect.bottom < bound.top || refRect.left > bound.right || refRect.top > bound.bottom || refRect.right < bound.left) {
  1489. // Avoid unnecessary DOM access if visibility hasn't changed
  1490. if (data.hide === true) {
  1491. return data;
  1492. }
  1493. data.hide = true;
  1494. data.attributes['x-out-of-boundaries'] = '';
  1495. } else {
  1496. // Avoid unnecessary DOM access if visibility hasn't changed
  1497. if (data.hide === false) {
  1498. return data;
  1499. }
  1500. data.hide = false;
  1501. data.attributes['x-out-of-boundaries'] = false;
  1502. }
  1503. return data;
  1504. }
  1505. /**
  1506. * @function
  1507. * @memberof Modifiers
  1508. * @argument {Object} data - The data object generated by `update` method
  1509. * @argument {Object} options - Modifiers configuration and options
  1510. * @returns {Object} The data object, properly modified
  1511. */
  1512. function inner(data) {
  1513. const placement = data.placement;
  1514. const basePlacement = placement.split('-')[0];
  1515. const { popper, reference } = data.offsets;
  1516. const isHoriz = ['left', 'right'].indexOf(basePlacement) !== -1;
  1517. const subtractLength = ['top', 'left'].indexOf(basePlacement) === -1;
  1518. popper[isHoriz ? 'left' : 'top'] = reference[basePlacement] - (subtractLength ? popper[isHoriz ? 'width' : 'height'] : 0);
  1519. data.placement = getOppositePlacement(placement);
  1520. data.offsets.popper = getClientRect(popper);
  1521. return data;
  1522. }
  1523. /**
  1524. * Modifier function, each modifier can have a function of this type assigned
  1525. * to its `fn` property.<br />
  1526. * These functions will be called on each update, this means that you must
  1527. * make sure they are performant enough to avoid performance bottlenecks.
  1528. *
  1529. * @function ModifierFn
  1530. * @argument {dataObject} data - The data object generated by `update` method
  1531. * @argument {Object} options - Modifiers configuration and options
  1532. * @returns {dataObject} The data object, properly modified
  1533. */
  1534. /**
  1535. * Modifiers are plugins used to alter the behavior of your poppers.<br />
  1536. * Popper.js uses a set of 9 modifiers to provide all the basic functionalities
  1537. * needed by the library.
  1538. *
  1539. * Usually you don't want to override the `order`, `fn` and `onLoad` props.
  1540. * All the other properties are configurations that could be tweaked.
  1541. * @namespace modifiers
  1542. */
  1543. var modifiers = {
  1544. /**
  1545. * Modifier used to shift the popper on the start or end of its reference
  1546. * element.<br />
  1547. * It will read the variation of the `placement` property.<br />
  1548. * It can be one either `-end` or `-start`.
  1549. * @memberof modifiers
  1550. * @inner
  1551. */
  1552. shift: {
  1553. /** @prop {number} order=100 - Index used to define the order of execution */
  1554. order: 100,
  1555. /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
  1556. enabled: true,
  1557. /** @prop {ModifierFn} */
  1558. fn: shift
  1559. },
  1560. /**
  1561. * The `offset` modifier can shift your popper on both its axis.
  1562. *
  1563. * It accepts the following units:
  1564. * - `px` or unitless, interpreted as pixels
  1565. * - `%` or `%r`, percentage relative to the length of the reference element
  1566. * - `%p`, percentage relative to the length of the popper element
  1567. * - `vw`, CSS viewport width unit
  1568. * - `vh`, CSS viewport height unit
  1569. *
  1570. * For length is intended the main axis relative to the placement of the popper.<br />
  1571. * This means that if the placement is `top` or `bottom`, the length will be the
  1572. * `width`. In case of `left` or `right`, it will be the height.
  1573. *
  1574. * You can provide a single value (as `Number` or `String`), or a pair of values
  1575. * as `String` divided by a comma or one (or more) white spaces.<br />
  1576. * The latter is a deprecated method because it leads to confusion and will be
  1577. * removed in v2.<br />
  1578. * Additionally, it accepts additions and subtractions between different units.
  1579. * Note that multiplications and divisions aren't supported.
  1580. *
  1581. * Valid examples are:
  1582. * ```
  1583. * 10
  1584. * '10%'
  1585. * '10, 10'
  1586. * '10%, 10'
  1587. * '10 + 10%'
  1588. * '10 - 5vh + 3%'
  1589. * '-10px + 5vh, 5px - 6%'
  1590. * ```
  1591. * > **NB**: If you desire to apply offsets to your poppers in a way that may make them overlap
  1592. * > with their reference element, unfortunately, you will have to disable the `flip` modifier.
  1593. * > More on this [reading this issue](https://github.com/FezVrasta/popper.js/issues/373)
  1594. *
  1595. * @memberof modifiers
  1596. * @inner
  1597. */
  1598. offset: {
  1599. /** @prop {number} order=200 - Index used to define the order of execution */
  1600. order: 200,
  1601. /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
  1602. enabled: true,
  1603. /** @prop {ModifierFn} */
  1604. fn: offset,
  1605. /** @prop {Number|String} offset=0
  1606. * The offset value as described in the modifier description
  1607. */
  1608. offset: 0
  1609. },
  1610. /**
  1611. * Modifier used to prevent the popper from being positioned outside the boundary.
  1612. *
  1613. * An scenario exists where the reference itself is not within the boundaries.<br />
  1614. * We can say it has "escaped the boundaries" — or just "escaped".<br />
  1615. * In this case we need to decide whether the popper should either:
  1616. *
  1617. * - detach from the reference and remain "trapped" in the boundaries, or
  1618. * - if it should ignore the boundary and "escape with its reference"
  1619. *
  1620. * When `escapeWithReference` is set to`true` and reference is completely
  1621. * outside its boundaries, the popper will overflow (or completely leave)
  1622. * the boundaries in order to remain attached to the edge of the reference.
  1623. *
  1624. * @memberof modifiers
  1625. * @inner
  1626. */
  1627. preventOverflow: {
  1628. /** @prop {number} order=300 - Index used to define the order of execution */
  1629. order: 300,
  1630. /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
  1631. enabled: true,
  1632. /** @prop {ModifierFn} */
  1633. fn: preventOverflow,
  1634. /**
  1635. * @prop {Array} [priority=['left','right','top','bottom']]
  1636. * Popper will try to prevent overflow following these priorities by default,
  1637. * then, it could overflow on the left and on top of the `boundariesElement`
  1638. */
  1639. priority: ['left', 'right', 'top', 'bottom'],
  1640. /**
  1641. * @prop {number} padding=5
  1642. * Amount of pixel used to define a minimum distance between the boundaries
  1643. * and the popper this makes sure the popper has always a little padding
  1644. * between the edges of its container
  1645. */
  1646. padding: 5,
  1647. /**
  1648. * @prop {String|HTMLElement} boundariesElement='scrollParent'
  1649. * Boundaries used by the modifier, can be `scrollParent`, `window`,
  1650. * `viewport` or any DOM element.
  1651. */
  1652. boundariesElement: 'scrollParent'
  1653. },
  1654. /**
  1655. * Modifier used to make sure the reference and its popper stay near eachothers
  1656. * without leaving any gap between the two. Expecially useful when the arrow is
  1657. * enabled and you want to assure it to point to its reference element.
  1658. * It cares only about the first axis, you can still have poppers with margin
  1659. * between the popper and its reference element.
  1660. * @memberof modifiers
  1661. * @inner
  1662. */
  1663. keepTogether: {
  1664. /** @prop {number} order=400 - Index used to define the order of execution */
  1665. order: 400,
  1666. /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
  1667. enabled: true,
  1668. /** @prop {ModifierFn} */
  1669. fn: keepTogether
  1670. },
  1671. /**
  1672. * This modifier is used to move the `arrowElement` of the popper to make
  1673. * sure it is positioned between the reference element and its popper element.
  1674. * It will read the outer size of the `arrowElement` node to detect how many
  1675. * pixels of conjuction are needed.
  1676. *
  1677. * It has no effect if no `arrowElement` is provided.
  1678. * @memberof modifiers
  1679. * @inner
  1680. */
  1681. arrow: {
  1682. /** @prop {number} order=500 - Index used to define the order of execution */
  1683. order: 500,
  1684. /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
  1685. enabled: true,
  1686. /** @prop {ModifierFn} */
  1687. fn: arrow,
  1688. /** @prop {String|HTMLElement} element='[x-arrow]' - Selector or node used as arrow */
  1689. element: '[x-arrow]'
  1690. },
  1691. /**
  1692. * Modifier used to flip the popper's placement when it starts to overlap its
  1693. * reference element.
  1694. *
  1695. * Requires the `preventOverflow` modifier before it in order to work.
  1696. *
  1697. * **NOTE:** this modifier will interrupt the current update cycle and will
  1698. * restart it if it detects the need to flip the placement.
  1699. * @memberof modifiers
  1700. * @inner
  1701. */
  1702. flip: {
  1703. /** @prop {number} order=600 - Index used to define the order of execution */
  1704. order: 600,
  1705. /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
  1706. enabled: true,
  1707. /** @prop {ModifierFn} */
  1708. fn: flip,
  1709. /**
  1710. * @prop {String|Array} behavior='flip'
  1711. * The behavior used to change the popper's placement. It can be one of
  1712. * `flip`, `clockwise`, `counterclockwise` or an array with a list of valid
  1713. * placements (with optional variations).
  1714. */
  1715. behavior: 'flip',
  1716. /**
  1717. * @prop {number} padding=5
  1718. * The popper will flip if it hits the edges of the `boundariesElement`
  1719. */
  1720. padding: 5,
  1721. /**
  1722. * @prop {String|HTMLElement} boundariesElement='viewport'
  1723. * The element which will define the boundaries of the popper position,
  1724. * the popper will never be placed outside of the defined boundaries
  1725. * (except if keepTogether is enabled)
  1726. */
  1727. boundariesElement: 'viewport'
  1728. },
  1729. /**
  1730. * Modifier used to make the popper flow toward the inner of the reference element.
  1731. * By default, when this modifier is disabled, the popper will be placed outside
  1732. * the reference element.
  1733. * @memberof modifiers
  1734. * @inner
  1735. */
  1736. inner: {
  1737. /** @prop {number} order=700 - Index used to define the order of execution */
  1738. order: 700,
  1739. /** @prop {Boolean} enabled=false - Whether the modifier is enabled or not */
  1740. enabled: false,
  1741. /** @prop {ModifierFn} */
  1742. fn: inner
  1743. },
  1744. /**
  1745. * Modifier used to hide the popper when its reference element is outside of the
  1746. * popper boundaries. It will set a `x-out-of-boundaries` attribute which can
  1747. * be used to hide with a CSS selector the popper when its reference is
  1748. * out of boundaries.
  1749. *
  1750. * Requires the `preventOverflow` modifier before it in order to work.
  1751. * @memberof modifiers
  1752. * @inner
  1753. */
  1754. hide: {
  1755. /** @prop {number} order=800 - Index used to define the order of execution */
  1756. order: 800,
  1757. /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
  1758. enabled: true,
  1759. /** @prop {ModifierFn} */
  1760. fn: hide
  1761. },
  1762. /**
  1763. * Computes the style that will be applied to the popper element to gets
  1764. * properly positioned.
  1765. *
  1766. * Note that this modifier will not touch the DOM, it just prepares the styles
  1767. * so that `applyStyle` modifier can apply it. This separation is useful
  1768. * in case you need to replace `applyStyle` with a custom implementation.
  1769. *
  1770. * This modifier has `850` as `order` value to maintain backward compatibility
  1771. * with previous versions of Popper.js. Expect the modifiers ordering method
  1772. * to change in future major versions of the library.
  1773. *
  1774. * @memberof modifiers
  1775. * @inner
  1776. */
  1777. computeStyle: {
  1778. /** @prop {number} order=850 - Index used to define the order of execution */
  1779. order: 850,
  1780. /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
  1781. enabled: true,
  1782. /** @prop {ModifierFn} */
  1783. fn: computeStyle,
  1784. /**
  1785. * @prop {Boolean} gpuAcceleration=true
  1786. * If true, it uses the CSS 3d transformation to position the popper.
  1787. * Otherwise, it will use the `top` and `left` properties.
  1788. */
  1789. gpuAcceleration: true,
  1790. /**
  1791. * @prop {string} [x='bottom']
  1792. * Where to anchor the X axis (`bottom` or `top`). AKA X offset origin.
  1793. * Change this if your popper should grow in a direction different from `bottom`
  1794. */
  1795. x: 'bottom',
  1796. /**
  1797. * @prop {string} [x='left']
  1798. * Where to anchor the Y axis (`left` or `right`). AKA Y offset origin.
  1799. * Change this if your popper should grow in a direction different from `right`
  1800. */
  1801. y: 'right'
  1802. },
  1803. /**
  1804. * Applies the computed styles to the popper element.
  1805. *
  1806. * All the DOM manipulations are limited to this modifier. This is useful in case
  1807. * you want to integrate Popper.js inside a framework or view library and you
  1808. * want to delegate all the DOM manipulations to it.
  1809. *
  1810. * Note that if you disable this modifier, you must make sure the popper element
  1811. * has its position set to `absolute` before Popper.js can do its work!
  1812. *
  1813. * Just disable this modifier and define you own to achieve the desired effect.
  1814. *
  1815. * @memberof modifiers
  1816. * @inner
  1817. */
  1818. applyStyle: {
  1819. /** @prop {number} order=900 - Index used to define the order of execution */
  1820. order: 900,
  1821. /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
  1822. enabled: true,
  1823. /** @prop {ModifierFn} */
  1824. fn: applyStyle,
  1825. /** @prop {Function} */
  1826. onLoad: applyStyleOnLoad,
  1827. /**
  1828. * @deprecated since version 1.10.0, the property moved to `computeStyle` modifier
  1829. * @prop {Boolean} gpuAcceleration=true
  1830. * If true, it uses the CSS 3d transformation to position the popper.
  1831. * Otherwise, it will use the `top` and `left` properties.
  1832. */
  1833. gpuAcceleration: undefined
  1834. }
  1835. };
  1836. /**
  1837. * The `dataObject` is an object containing all the informations used by Popper.js
  1838. * this object get passed to modifiers and to the `onCreate` and `onUpdate` callbacks.
  1839. * @name dataObject
  1840. * @property {Object} data.instance The Popper.js instance
  1841. * @property {String} data.placement Placement applied to popper
  1842. * @property {String} data.originalPlacement Placement originally defined on init
  1843. * @property {Boolean} data.flipped True if popper has been flipped by flip modifier
  1844. * @property {Boolean} data.hide True if the reference element is out of boundaries, useful to know when to hide the popper.
  1845. * @property {HTMLElement} data.arrowElement Node used as arrow by arrow modifier
  1846. * @property {Object} data.styles Any CSS property defined here will be applied to the popper, it expects the JavaScript nomenclature (eg. `marginBottom`)
  1847. * @property {Object} data.arrowStyles Any CSS property defined here will be applied to the popper arrow, it expects the JavaScript nomenclature (eg. `marginBottom`)
  1848. * @property {Object} data.boundaries Offsets of the popper boundaries
  1849. * @property {Object} data.offsets The measurements of popper, reference and arrow elements.
  1850. * @property {Object} data.offsets.popper `top`, `left`, `width`, `height` values
  1851. * @property {Object} data.offsets.reference `top`, `left`, `width`, `height` values
  1852. * @property {Object} data.offsets.arrow] `top` and `left` offsets, only one of them will be different from 0
  1853. */
  1854. /**
  1855. * Default options provided to Popper.js constructor.<br />
  1856. * These can be overriden using the `options` argument of Popper.js.<br />
  1857. * To override an option, simply pass as 3rd argument an object with the same
  1858. * structure of this object, example:
  1859. * ```
  1860. * new Popper(ref, pop, {
  1861. * modifiers: {
  1862. * preventOverflow: { enabled: false }
  1863. * }
  1864. * })
  1865. * ```
  1866. * @type {Object}
  1867. * @static
  1868. * @memberof Popper
  1869. */
  1870. var Defaults = {
  1871. /**
  1872. * Popper's placement
  1873. * @prop {Popper.placements} placement='bottom'
  1874. */
  1875. placement: 'bottom',
  1876. /**
  1877. * Whether events (resize, scroll) are initially enabled
  1878. * @prop {Boolean} eventsEnabled=true
  1879. */
  1880. eventsEnabled: true,
  1881. /**
  1882. * Set to true if you want to automatically remove the popper when
  1883. * you call the `destroy` method.
  1884. * @prop {Boolean} removeOnDestroy=false
  1885. */
  1886. removeOnDestroy: false,
  1887. /**
  1888. * Callback called when the popper is created.<br />
  1889. * By default, is set to no-op.<br />
  1890. * Access Popper.js instance with `data.instance`.
  1891. * @prop {onCreate}
  1892. */
  1893. onCreate: () => {},
  1894. /**
  1895. * Callback called when the popper is updated, this callback is not called
  1896. * on the initialization/creation of the popper, but only on subsequent
  1897. * updates.<br />
  1898. * By default, is set to no-op.<br />
  1899. * Access Popper.js instance with `data.instance`.
  1900. * @prop {onUpdate}
  1901. */
  1902. onUpdate: () => {},
  1903. /**
  1904. * List of modifiers used to modify the offsets before they are applied to the popper.
  1905. * They provide most of the functionalities of Popper.js
  1906. * @prop {modifiers}
  1907. */
  1908. modifiers
  1909. };
  1910. /**
  1911. * @callback onCreate
  1912. * @param {dataObject} data
  1913. */
  1914. /**
  1915. * @callback onUpdate
  1916. * @param {dataObject} data
  1917. */
  1918. // Utils
  1919. // Methods
  1920. class Popper {
  1921. /**
  1922. * Create a new Popper.js instance
  1923. * @class Popper
  1924. * @param {HTMLElement|referenceObject} reference - The reference element used to position the popper
  1925. * @param {HTMLElement} popper - The HTML element used as popper.
  1926. * @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults)
  1927. * @return {Object} instance - The generated Popper.js instance
  1928. */
  1929. constructor(reference, popper, options = {}) {
  1930. this.scheduleUpdate = () => requestAnimationFrame(this.update);
  1931. // make update() debounced, so that it only runs at most once-per-tick
  1932. this.update = debounce(this.update.bind(this));
  1933. // with {} we create a new object with the options inside it
  1934. this.options = _extends({}, Popper.Defaults, options);
  1935. // init state
  1936. this.state = {
  1937. isDestroyed: false,
  1938. isCreated: false,
  1939. scrollParents: []
  1940. };
  1941. // get reference and popper elements (allow jQuery wrappers)
  1942. this.reference = reference.jquery ? reference[0] : reference;
  1943. this.popper = popper.jquery ? popper[0] : popper;
  1944. // Deep merge modifiers options
  1945. this.options.modifiers = {};
  1946. Object.keys(_extends({}, Popper.Defaults.modifiers, options.modifiers)).forEach(name => {
  1947. this.options.modifiers[name] = _extends({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {});
  1948. });
  1949. // Refactoring modifiers' list (Object => Array)
  1950. this.modifiers = Object.keys(this.options.modifiers).map(name => _extends({
  1951. name
  1952. }, this.options.modifiers[name]))
  1953. // sort the modifiers by order
  1954. .sort((a, b) => a.order - b.order);
  1955. // modifiers have the ability to execute arbitrary code when Popper.js get inited
  1956. // such code is executed in the same order of its modifier
  1957. // they could add new properties to their options configuration
  1958. // BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`!
  1959. this.modifiers.forEach(modifierOptions => {
  1960. if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) {
  1961. modifierOptions.onLoad(this.reference, this.popper, this.options, modifierOptions, this.state);
  1962. }
  1963. });
  1964. // fire the first update to position the popper in the right place
  1965. this.update();
  1966. const eventsEnabled = this.options.eventsEnabled;
  1967. if (eventsEnabled) {
  1968. // setup event listeners, they will take care of update the position in specific situations
  1969. this.enableEventListeners();
  1970. }
  1971. this.state.eventsEnabled = eventsEnabled;
  1972. }
  1973. // We can't use class properties because they don't get listed in the
  1974. // class prototype and break stuff like Sinon stubs
  1975. update() {
  1976. return update.call(this);
  1977. }
  1978. destroy() {
  1979. return destroy.call(this);
  1980. }
  1981. enableEventListeners() {
  1982. return enableEventListeners.call(this);
  1983. }
  1984. disableEventListeners() {
  1985. return disableEventListeners.call(this);
  1986. }
  1987. /**
  1988. * Schedule an update, it will run on the next UI update available
  1989. * @method scheduleUpdate
  1990. * @memberof Popper
  1991. */
  1992. /**
  1993. * Collection of utilities useful when writing custom modifiers.
  1994. * Starting from version 1.7, this method is available only if you
  1995. * include `popper-utils.js` before `popper.js`.
  1996. *
  1997. * **DEPRECATION**: This way to access PopperUtils is deprecated
  1998. * and will be removed in v2! Use the PopperUtils module directly instead.
  1999. * Due to the high instability of the methods contained in Utils, we can't
  2000. * guarantee them to follow semver. Use them at your own risk!
  2001. * @static
  2002. * @private
  2003. * @type {Object}
  2004. * @deprecated since version 1.8
  2005. * @member Utils
  2006. * @memberof Popper
  2007. */
  2008. }
  2009. /**
  2010. * The `referenceObject` is an object that provides an interface compatible with Popper.js
  2011. * and lets you use it as replacement of a real DOM node.<br />
  2012. * You can use this method to position a popper relatively to a set of coordinates
  2013. * in case you don't have a DOM node to use as reference.
  2014. *
  2015. * ```
  2016. * new Popper(referenceObject, popperNode);
  2017. * ```
  2018. *
  2019. * NB: This feature isn't supported in Internet Explorer 10
  2020. * @name referenceObject
  2021. * @property {Function} data.getBoundingClientRect
  2022. * A function that returns a set of coordinates compatible with the native `getBoundingClientRect` method.
  2023. * @property {number} data.clientWidth
  2024. * An ES6 getter that will return the width of the virtual reference element.
  2025. * @property {number} data.clientHeight
  2026. * An ES6 getter that will return the height of the virtual reference element.
  2027. */
  2028. Popper.Utils = (typeof window !== 'undefined' ? window : global).PopperUtils;
  2029. Popper.placements = placements;
  2030. Popper.Defaults = Defaults;
  2031. export default Popper;
  2032. //# sourceMappingURL=popper.js.map