popper.js 78 KB

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