popper.js 80 KB

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