popper.js 79 KB

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