You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@myfaces.apache.org by lo...@apache.org on 2021/06/24 08:33:46 UTC
[myfaces-tobago] branch master updated: refactor: rename file
This is an automated email from the ASF dual-hosted git repository.
lofwyr pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/myfaces-tobago.git
The following commit(s) were added to refs/heads/master by this push:
new 880eb58 refactor: rename file
880eb58 is described below
commit 880eb58a7e4eacdb676f06bbbd9a8d9b2a95b2d0
Author: Udo Schnurpfeil <ud...@irian.eu>
AuthorDate: Thu Jun 24 10:33:09 2021 +0200
refactor: rename file
---
.../tobago-theme-standard/src/main/js/tobago.js | 16060 +++++++++----------
.../src/main/js/tobago.js.map | 2 +-
.../src/main/js/tobago.min.js | 4 +-
.../src/main/js/tobago.min.js.map | 2 +-
.../src/main/ts/tobago-all.ts | 2 +-
.../ts/{tobago-command.ts => tobago-behavior.ts} | 0
6 files changed, 8035 insertions(+), 8035 deletions(-)
diff --git a/tobago-theme/tobago-theme-standard/src/main/js/tobago.js b/tobago-theme/tobago-theme-standard/src/main/js/tobago.js
index 10a39c0..5724dc4 100644
--- a/tobago-theme/tobago-theme-standard/src/main/js/tobago.js
+++ b/tobago-theme/tobago-theme-standard/src/main/js/tobago.js
@@ -125,5134 +125,3702 @@
}
});
- /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var BehaviorMode;
- (function (BehaviorMode) {
- BehaviorMode[BehaviorMode["none"] = 0] = "none";
- BehaviorMode[BehaviorMode["client"] = 1] = "client";
- BehaviorMode[BehaviorMode["ajax"] = 2] = "ajax";
- BehaviorMode[BehaviorMode["full"] = 3] = "full";
- })(BehaviorMode || (BehaviorMode = {}));
+ var top = 'top';
+ var bottom = 'bottom';
+ var right = 'right';
+ var left = 'left';
+ var auto = 'auto';
+ var basePlacements = [top, bottom, right, left];
+ var start = 'start';
+ var end = 'end';
+ var clippingParents = 'clippingParents';
+ var viewport = 'viewport';
+ var popper = 'popper';
+ var reference = 'reference';
+ var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {
+ return acc.concat([placement + "-" + start, placement + "-" + end]);
+ }, []);
+ var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) {
+ return acc.concat([placement, placement + "-" + start, placement + "-" + end]);
+ }, []); // modifiers that need to read the DOM
- /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- var CollapseOperation;
- (function (CollapseOperation) {
- CollapseOperation[CollapseOperation["none"] = 0] = "none";
- CollapseOperation[CollapseOperation["show"] = 1] = "show";
- CollapseOperation[CollapseOperation["hide"] = 2] = "hide";
- CollapseOperation[CollapseOperation["toggle"] = 3] = "toggle";
- })(CollapseOperation || (CollapseOperation = {}));
+ var beforeRead = 'beforeRead';
+ var read = 'read';
+ var afterRead = 'afterRead'; // pure-logic modifiers
- /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- const TobagoDropdownEvent = {
- HIDE: "tobago.dropdown.hide",
- HIDDEN: "tobago.dropdown.hidden",
- SHOW: "tobago.dropdown.show",
- SHOWN: "tobago.dropdown.shown"
- };
- /**
- * The dropdown implementation of Bootstrap does not move the menu to the tobago-page-menuStore. This behavior is
- * implemented in this class.
- */
- class Dropdown$1 extends HTMLElement {
- constructor() {
- super();
- if (!this.classList.contains("tobago-dropdown-submenu")) { // ignore submenus
- this.addEventListener("shown.bs.dropdown", this.openDropdown.bind(this));
- this.addEventListener("hidden.bs.dropdown", this.closeDropdown.bind(this));
- }
- }
- openDropdown() {
- this.dispatchEvent(new CustomEvent(TobagoDropdownEvent.SHOW));
- if (!this.inStickyHeader()) {
- this.menuStore.appendChild(this.dropdownMenu);
- }
- this.dispatchEvent(new CustomEvent(TobagoDropdownEvent.SHOWN));
- }
- closeDropdown() {
- this.dispatchEvent(new CustomEvent(TobagoDropdownEvent.HIDE));
- if (!this.inStickyHeader()) {
- this.appendChild(this.dropdownMenu);
- }
- this.dispatchEvent(new CustomEvent(TobagoDropdownEvent.HIDDEN));
- }
- inStickyHeader() {
- return Boolean(this.closest("tobago-header.sticky-top"));
- }
- get dropdownMenu() {
- const root = this.getRootNode();
- return root.querySelector(`.dropdown-menu[name='${this.id}']`);
- }
- get menuStore() {
- const root = this.getRootNode();
- return root.querySelector(".tobago-page-menuStore");
- }
- }
- document.addEventListener("tobago.init", function (event) {
- if (window.customElements.get("tobago-dropdown") == null) {
- window.customElements.define("tobago-dropdown", Dropdown$1);
- }
- });
+ var beforeMain = 'beforeMain';
+ var main = 'main';
+ var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)
- function hasProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
- }
+ var beforeWrite = 'beforeWrite';
+ var write = 'write';
+ var afterWrite = 'afterWrite';
+ var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];
- function lastItemOf(arr) {
- return arr[arr.length - 1];
+ function getNodeName(element) {
+ return element ? (element.nodeName || '').toLowerCase() : null;
}
- // push only the items not included in the array
- function pushUnique(arr, ...items) {
- items.forEach((item) => {
- if (arr.includes(item)) {
- return;
- }
- arr.push(item);
- });
- return arr;
- }
+ function getWindow(node) {
+ if (node == null) {
+ return window;
+ }
- function stringToArray(str, separator) {
- // convert empty string to an empty array
- return str ? str.split(separator) : [];
+ if (node.toString() !== '[object Window]') {
+ var ownerDocument = node.ownerDocument;
+ return ownerDocument ? ownerDocument.defaultView || window : window;
+ }
+
+ return node;
}
- function isInRange(testVal, min, max) {
- const minOK = min === undefined || testVal >= min;
- const maxOK = max === undefined || testVal <= max;
- return minOK && maxOK;
+ function isElement$1(node) {
+ var OwnElement = getWindow(node).Element;
+ return node instanceof OwnElement || node instanceof Element;
}
- function limitToRange(val, min, max) {
- if (val < min) {
- return min;
- }
- if (val > max) {
- return max;
- }
- return val;
+ function isHTMLElement(node) {
+ var OwnElement = getWindow(node).HTMLElement;
+ return node instanceof OwnElement || node instanceof HTMLElement;
}
- function createTagRepeat(tagName, repeat, attributes = {}, index = 0, html = '') {
- const openTagSrc = Object.keys(attributes).reduce((src, attr) => {
- let val = attributes[attr];
- if (typeof val === 'function') {
- val = val(index);
- }
- return `${src} ${attr}="${val}"`;
- }, tagName);
- html += `<${openTagSrc}></${tagName}>`;
+ function isShadowRoot(node) {
+ // IE 11 has no ShadowRoot
+ if (typeof ShadowRoot === 'undefined') {
+ return false;
+ }
- const next = index + 1;
- return next < repeat
- ? createTagRepeat(tagName, repeat, attributes, next, html)
- : html;
+ var OwnElement = getWindow(node).ShadowRoot;
+ return node instanceof OwnElement || node instanceof ShadowRoot;
}
- // Remove the spacing surrounding tags for HTML parser not to create text nodes
- // before/after elements
- function optimizeTemplateHTML(html) {
- return html.replace(/>\s+/g, '>').replace(/\s+</, '<');
- }
+ // and applies them to the HTMLElements such as popper and arrow
- function stripTime(timeValue) {
- return new Date(timeValue).setHours(0, 0, 0, 0);
- }
+ function applyStyles(_ref) {
+ var state = _ref.state;
+ Object.keys(state.elements).forEach(function (name) {
+ var style = state.styles[name] || {};
+ var attributes = state.attributes[name] || {};
+ var element = state.elements[name]; // arrow is optional + virtual elements
- function today() {
- return new Date().setHours(0, 0, 0, 0);
- }
+ if (!isHTMLElement(element) || !getNodeName(element)) {
+ return;
+ } // Flow doesn't support to extend this property, but it's the most
+ // effective way to apply styles to an HTMLElement
+ // $FlowFixMe[cannot-write]
- // Get the time value of the start of given date or year, month and day
- function dateValue(...args) {
- switch (args.length) {
- case 0:
- return today();
- case 1:
- return stripTime(args[0]);
- }
- // use setFullYear() to keep 2-digit year from being mapped to 1900-1999
- const newDate = new Date(0);
- newDate.setFullYear(...args);
- return newDate.setHours(0, 0, 0, 0);
- }
+ Object.assign(element.style, style);
+ Object.keys(attributes).forEach(function (name) {
+ var value = attributes[name];
- function addDays(date, amount) {
- const newDate = new Date(date);
- return newDate.setDate(newDate.getDate() + amount);
+ if (value === false) {
+ element.removeAttribute(name);
+ } else {
+ element.setAttribute(name, value === true ? '' : value);
+ }
+ });
+ });
}
- function addWeeks(date, amount) {
- return addDays(date, amount * 7);
- }
+ function effect$2(_ref2) {
+ var state = _ref2.state;
+ var initialStyles = {
+ popper: {
+ position: state.options.strategy,
+ left: '0',
+ top: '0',
+ margin: '0'
+ },
+ arrow: {
+ position: 'absolute'
+ },
+ reference: {}
+ };
+ Object.assign(state.elements.popper.style, initialStyles.popper);
+ state.styles = initialStyles;
- function addMonths(date, amount) {
- // If the day of the date is not in the new month, the last day of the new
- // month will be returned. e.g. Jan 31 + 1 month → Feb 28 (not Mar 03)
- const newDate = new Date(date);
- const monthsToSet = newDate.getMonth() + amount;
- let expectedMonth = monthsToSet % 12;
- if (expectedMonth < 0) {
- expectedMonth += 12;
+ if (state.elements.arrow) {
+ Object.assign(state.elements.arrow.style, initialStyles.arrow);
}
- const time = newDate.setMonth(monthsToSet);
- return newDate.getMonth() !== expectedMonth ? newDate.setDate(0) : time;
- }
+ return function () {
+ Object.keys(state.elements).forEach(function (name) {
+ var element = state.elements[name];
+ var attributes = state.attributes[name] || {};
+ var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them
- function addYears(date, amount) {
- // If the date is Feb 29 and the new year is not a leap year, Feb 28 of the
- // new year will be returned.
- const newDate = new Date(date);
- const expectedMonth = newDate.getMonth();
- const time = newDate.setFullYear(newDate.getFullYear() + amount);
- return expectedMonth === 1 && newDate.getMonth() === 2 ? newDate.setDate(0) : time;
- }
+ var style = styleProperties.reduce(function (style, property) {
+ style[property] = '';
+ return style;
+ }, {}); // arrow is optional + virtual elements
- // Calculate the distance bettwen 2 days of the week
- function dayDiff(day, from) {
- return (day - from + 7) % 7;
- }
+ if (!isHTMLElement(element) || !getNodeName(element)) {
+ return;
+ }
- // Get the date of the specified day of the week of given base date
- function dayOfTheWeekOf(baseDate, dayOfWeek, weekStart = 0) {
- const baseDay = new Date(baseDate).getDay();
- return addDays(baseDate, dayDiff(dayOfWeek, weekStart) - dayDiff(baseDay, weekStart));
- }
+ Object.assign(element.style, style);
+ Object.keys(attributes).forEach(function (attribute) {
+ element.removeAttribute(attribute);
+ });
+ });
+ };
+ } // eslint-disable-next-line import/no-unused-modules
- // Get the ISO week of a date
- function getWeek(date) {
- // start of ISO week is Monday
- const thuOfTheWeek = dayOfTheWeekOf(date, 4, 1);
- // 1st week == the week where the 4th of January is in
- const firstThu = dayOfTheWeekOf(new Date(thuOfTheWeek).setMonth(0, 4), 4, 1);
- return Math.round((thuOfTheWeek - firstThu) / 604800000) + 1;
+
+ var applyStyles$1 = {
+ name: 'applyStyles',
+ enabled: true,
+ phase: 'write',
+ fn: applyStyles,
+ effect: effect$2,
+ requires: ['computeStyles']
+ };
+
+ function getBasePlacement(placement) {
+ return placement.split('-')[0];
}
- // Get the start year of the period of years that includes given date
- // years: length of the year period
- function startOfYearPeriod(date, years) {
- /* @see https://en.wikipedia.org/wiki/Year_zero#ISO_8601 */
- const year = new Date(date).getFullYear();
- return Math.floor(year / years) * years;
+ function getBoundingClientRect(element) {
+ var rect = element.getBoundingClientRect();
+ return {
+ width: rect.width,
+ height: rect.height,
+ top: rect.top,
+ right: rect.right,
+ bottom: rect.bottom,
+ left: rect.left,
+ x: rect.left,
+ y: rect.top
+ };
}
- // pattern for format parts
- const reFormatTokens = /dd?|DD?|mm?|MM?|yy?(?:yy)?/;
- // pattern for non date parts
- const reNonDateParts = /[\s!-/:-@[-`{-~年月日]+/;
- // cache for persed formats
- let knownFormats = {};
- // parse funtions for date parts
- const parseFns = {
- y(date, year) {
- return new Date(date).setFullYear(parseInt(year, 10));
- },
- m(date, month, locale) {
- const newDate = new Date(date);
- let monthIndex = parseInt(month, 10) - 1;
+ // means it doesn't take into account transforms.
- if (isNaN(monthIndex)) {
- if (!month) {
- return NaN;
- }
+ function getLayoutRect(element) {
+ var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed.
+ // Fixes https://github.com/popperjs/popper-core/issues/1223
- const monthName = month.toLowerCase();
- const compareNames = name => name.toLowerCase().startsWith(monthName);
- // compare with both short and full names because some locales have periods
- // in the short names (not equal to the first X letters of the full names)
- monthIndex = locale.monthsShort.findIndex(compareNames);
- if (monthIndex < 0) {
- monthIndex = locale.months.findIndex(compareNames);
- }
- if (monthIndex < 0) {
- return NaN;
- }
- }
+ var width = element.offsetWidth;
+ var height = element.offsetHeight;
- newDate.setMonth(monthIndex);
- return newDate.getMonth() !== normalizeMonth(monthIndex)
- ? newDate.setDate(0)
- : newDate.getTime();
- },
- d(date, day) {
- return new Date(date).setDate(parseInt(day, 10));
- },
- };
- // format functions for date parts
- const formatFns = {
- d(date) {
- return date.getDate();
- },
- dd(date) {
- return padZero(date.getDate(), 2);
- },
- D(date, locale) {
- return locale.daysShort[date.getDay()];
- },
- DD(date, locale) {
- return locale.days[date.getDay()];
- },
- m(date) {
- return date.getMonth() + 1;
- },
- mm(date) {
- return padZero(date.getMonth() + 1, 2);
- },
- M(date, locale) {
- return locale.monthsShort[date.getMonth()];
- },
- MM(date, locale) {
- return locale.months[date.getMonth()];
- },
- y(date) {
- return date.getFullYear();
- },
- yy(date) {
- return padZero(date.getFullYear(), 2).slice(-2);
- },
- yyyy(date) {
- return padZero(date.getFullYear(), 4);
- },
- };
+ if (Math.abs(clientRect.width - width) <= 1) {
+ width = clientRect.width;
+ }
- // get month index in normal range (0 - 11) from any number
- function normalizeMonth(monthIndex) {
- return monthIndex > -1 ? monthIndex % 12 : normalizeMonth(monthIndex + 12);
- }
+ if (Math.abs(clientRect.height - height) <= 1) {
+ height = clientRect.height;
+ }
- function padZero(num, length) {
- return num.toString().padStart(length, '0');
+ return {
+ x: element.offsetLeft,
+ y: element.offsetTop,
+ width: width,
+ height: height
+ };
}
- function parseFormatString(format) {
- if (typeof format !== 'string') {
- throw new Error("Invalid date format.");
- }
- if (format in knownFormats) {
- return knownFormats[format];
- }
+ function contains(parent, child) {
+ var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method
- // sprit the format string into parts and seprators
- const separators = format.split(reFormatTokens);
- const parts = format.match(new RegExp(reFormatTokens, 'g'));
- if (separators.length === 0 || !parts) {
- throw new Error("Invalid date format.");
- }
+ if (parent.contains(child)) {
+ return true;
+ } // then fallback to custom implementation with Shadow DOM support
+ else if (rootNode && isShadowRoot(rootNode)) {
+ var next = child;
- // collect format functions used in the format
- const partFormatters = parts.map(token => formatFns[token]);
+ do {
+ if (next && parent.isSameNode(next)) {
+ return true;
+ } // $FlowFixMe[prop-missing]: need a better way to handle this...
- // collect parse function keys used in the format
- // iterate over parseFns' keys in order to keep the order of the keys.
- const partParserKeys = Object.keys(parseFns).reduce((keys, key) => {
- const token = parts.find(part => part[0] !== 'D' && part[0].toLowerCase() === key);
- if (token) {
- keys.push(key);
- }
- return keys;
- }, []);
- return knownFormats[format] = {
- parser(dateStr, locale) {
- const dateParts = dateStr.split(reNonDateParts).reduce((dtParts, part, index) => {
- if (part.length > 0 && parts[index]) {
- const token = parts[index][0];
- if (token === 'M') {
- dtParts.m = part;
- } else if (token !== 'D') {
- dtParts[token] = part;
- }
- }
- return dtParts;
- }, {});
+ next = next.parentNode || next.host;
+ } while (next);
+ } // Give up, the result is false
- // iterate over partParserkeys so that the parsing is made in the oder
- // of year, month and day to prevent the day parser from correcting last
- // day of month wrongly
- return partParserKeys.reduce((origDate, key) => {
- const newDate = parseFns[key](origDate, dateParts[key], locale);
- // ingnore the part failed to parse
- return isNaN(newDate) ? origDate : newDate;
- }, today());
- },
- formatter(date, locale) {
- let dateStr = partFormatters.reduce((str, fn, index) => {
- return str += `${separators[index]}${fn(date, locale)}`;
- }, '');
- // separators' length is always parts' length + 1,
- return dateStr += lastItemOf(separators);
- },
- };
+
+ return false;
}
- function parseDate(dateStr, format, locale) {
- if (dateStr instanceof Date || typeof dateStr === 'number') {
- const date = stripTime(dateStr);
- return isNaN(date) ? undefined : date;
- }
- if (!dateStr) {
- return undefined;
- }
- if (dateStr === 'today') {
- return today();
- }
+ function getComputedStyle$1(element) {
+ return getWindow(element).getComputedStyle(element);
+ }
- if (format && format.toValue) {
- const date = format.toValue(dateStr, format, locale);
- return isNaN(date) ? undefined : stripTime(date);
- }
+ function isTableElement(element) {
+ return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;
+ }
- return parseFormatString(format).parser(dateStr, locale);
+ function getDocumentElement(element) {
+ // $FlowFixMe[incompatible-return]: assume body is always available
+ return ((isElement$1(element) ? element.ownerDocument : // $FlowFixMe[prop-missing]
+ element.document) || window.document).documentElement;
}
- function formatDate(date, format, locale) {
- if (isNaN(date) || (!date && date !== 0)) {
- return '';
+ function getParentNode(element) {
+ if (getNodeName(element) === 'html') {
+ return element;
}
- const dateObj = typeof date === 'number' ? new Date(date) : date;
-
- if (format.toDisplay) {
- return format.toDisplay(dateObj, format, locale);
- }
+ return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle
+ // $FlowFixMe[incompatible-return]
+ // $FlowFixMe[prop-missing]
+ element.assignedSlot || // step into the shadow DOM of the parent of a slotted node
+ element.parentNode || ( // DOM Element detected
+ isShadowRoot(element) ? element.host : null) || // ShadowRoot detected
+ // $FlowFixMe[incompatible-call]: HTMLElement is a Node
+ getDocumentElement(element) // fallback
- return parseFormatString(format).formatter(dateObj, locale);
+ );
}
- const listenerRegistry = new WeakMap();
- const {addEventListener, removeEventListener} = EventTarget.prototype;
-
- // Register event listeners to a key object
- // listeners: array of listener definitions;
- // - each definition must be a flat array of event target and the arguments
- // used to call addEventListener() on the target
- function registerListeners(keyObj, listeners) {
- let registered = listenerRegistry.get(keyObj);
- if (!registered) {
- registered = [];
- listenerRegistry.set(keyObj, registered);
+ function getTrueOffsetParent(element) {
+ if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837
+ getComputedStyle$1(element).position === 'fixed') {
+ return null;
}
- listeners.forEach((listener) => {
- addEventListener.call(...listener);
- registered.push(listener);
- });
- }
- function unregisterListeners(keyObj) {
- let listeners = listenerRegistry.get(keyObj);
- if (!listeners) {
- return;
- }
- listeners.forEach((listener) => {
- removeEventListener.call(...listener);
- });
- listenerRegistry.delete(keyObj);
- }
+ return element.offsetParent;
+ } // `.offsetParent` reports `null` for fixed elements, while absolute elements
+ // return the containing block
- // Event.composedPath() polyfill for Edge
- // based on https://gist.github.com/kleinfreund/e9787d73776c0e3750dcfcdc89f100ec
- if (!Event.prototype.composedPath) {
- const getComposedPath = (node, path = []) => {
- path.push(node);
- let parent;
- if (node.parentNode) {
- parent = node.parentNode;
- } else if (node.host) { // ShadowRoot
- parent = node.host;
- } else if (node.defaultView) { // Document
- parent = node.defaultView;
- }
- return parent ? getComposedPath(parent, path) : path;
- };
+ function getContainingBlock(element) {
+ var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') !== -1;
+ var isIE = navigator.userAgent.indexOf('Trident') !== -1;
- Event.prototype.composedPath = function () {
- return getComposedPath(this.target);
- };
- }
+ if (isIE && isHTMLElement(element)) {
+ // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport
+ var elementCss = getComputedStyle$1(element);
- function findFromPath(path, criteria, currentTarget, index = 0) {
- const el = path[index];
- if (criteria(el)) {
- return el;
- } else if (el === currentTarget || !el.parentElement) {
- // stop when reaching currentTarget or <html>
- return;
+ if (elementCss.position === 'fixed') {
+ return null;
+ }
}
- return findFromPath(path, criteria, currentTarget, index + 1);
- }
- // Search for the actual target of a delegated event
- function findElementInEventPath(ev, selector) {
- const criteria = typeof selector === 'function' ? selector : el => el.matches(selector);
- return findFromPath(ev.composedPath(), criteria, ev.currentTarget);
- }
+ var currentNode = getParentNode(element);
- // default locales
- const locales = {
- en: {
- days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
- daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
- daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
- months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
- monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
- today: "Today",
- clear: "Clear",
- titleFormat: "MM y"
+ while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) {
+ var css = getComputedStyle$1(currentNode); // This is non-exhaustive but covers the most common CSS properties that
+ // create a containing block.
+ // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
+
+ if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') {
+ return currentNode;
+ } else {
+ currentNode = currentNode.parentNode;
+ }
}
- };
- // config options updatable by setOptions() and their default values
- const defaultOptions = {
- autohide: false,
- beforeShowDay: null,
- beforeShowDecade: null,
- beforeShowMonth: null,
- beforeShowYear: null,
- calendarWeeks: false,
- clearBtn: false,
- dateDelimiter: ',',
- datesDisabled: [],
- daysOfWeekDisabled: [],
- daysOfWeekHighlighted: [],
- defaultViewDate: undefined, // placeholder, defaults to today() by the program
- disableTouchKeyboard: false,
- format: 'mm/dd/yyyy',
- language: 'en',
- maxDate: null,
- maxNumberOfDates: 1,
- maxView: 3,
- minDate: null,
- nextArrow: '»',
- orientation: 'auto',
- pickLevel: 0,
- prevArrow: '«',
- showDaysOfWeek: true,
- showOnClick: true,
- showOnFocus: true,
- startView: 0,
- title: '',
- todayBtn: false,
- todayBtnMode: 0,
- todayHighlight: false,
- updateOnBlur: true,
- weekStart: 0,
- };
+ return null;
+ } // Gets the closest ancestor positioned element. Handles some edge cases,
+ // such as table ancestors and cross browser bugs.
- const range = document.createRange();
- function parseHTML(html) {
- return range.createContextualFragment(html);
- }
+ function getOffsetParent(element) {
+ var window = getWindow(element);
+ var offsetParent = getTrueOffsetParent(element);
- function hideElement(el) {
- if (el.style.display === 'none') {
- return;
- }
- // back up the existing display setting in data-style-display
- if (el.style.display) {
- el.dataset.styleDisplay = el.style.display;
+ while (offsetParent && isTableElement(offsetParent) && getComputedStyle$1(offsetParent).position === 'static') {
+ offsetParent = getTrueOffsetParent(offsetParent);
}
- el.style.display = 'none';
- }
- function showElement(el) {
- if (el.style.display !== 'none') {
- return;
- }
- if (el.dataset.styleDisplay) {
- // restore backed-up dispay property
- el.style.display = el.dataset.styleDisplay;
- delete el.dataset.styleDisplay;
- } else {
- el.style.display = '';
+ if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle$1(offsetParent).position === 'static')) {
+ return window;
}
- }
- function emptyChildNodes(el) {
- if (el.firstChild) {
- el.removeChild(el.firstChild);
- emptyChildNodes(el);
- }
+ return offsetParent || getContainingBlock(element) || window;
}
- function replaceChildNodes(el, newChildNodes) {
- emptyChildNodes(el);
- if (newChildNodes instanceof DocumentFragment) {
- el.appendChild(newChildNodes);
- } else if (typeof newChildNodes === 'string') {
- el.appendChild(parseHTML(newChildNodes));
- } else if (typeof newChildNodes.forEach === 'function') {
- newChildNodes.forEach((node) => {
- el.appendChild(node);
- });
- }
+ function getMainAxisFromPlacement(placement) {
+ return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y';
}
- const {
- language: defaultLang,
- format: defaultFormat,
- weekStart: defaultWeekStart,
- } = defaultOptions;
+ var max = Math.max;
+ var min = Math.min;
+ var round = Math.round;
- // Reducer function to filter out invalid day-of-week from the input
- function sanitizeDOW(dow, day) {
- return dow.length < 6 && day >= 0 && day < 7
- ? pushUnique(dow, day)
- : dow;
+ function within(min$1, value, max$1) {
+ return max(min$1, min(value, max$1));
}
- function calcEndOfWeek(startOfWeek) {
- return (startOfWeek + 6) % 7;
+ function getFreshSideObject() {
+ return {
+ top: 0,
+ right: 0,
+ bottom: 0,
+ left: 0
+ };
}
- // validate input date. if invalid, fallback to the original value
- function validateDate(value, format, locale, origValue) {
- const date = parseDate(value, format, locale);
- return date !== undefined ? date : origValue;
+ function mergePaddingObject(paddingObject) {
+ return Object.assign({}, getFreshSideObject(), paddingObject);
}
- // Validate viewId. if invalid, fallback to the original value
- function validateViewId(value, origValue, max = 3) {
- const viewId = parseInt(value, 10);
- return viewId >= 0 && viewId <= max ? viewId : origValue;
+ function expandToHashMap(value, keys) {
+ return keys.reduce(function (hashMap, key) {
+ hashMap[key] = value;
+ return hashMap;
+ }, {});
}
- // Create Datepicker configuration to set
- function processOptions(options, datepicker) {
- const inOpts = Object.assign({}, options);
- const config = {};
- const locales = datepicker.constructor.locales;
- let {
- format,
- language,
- locale,
- maxDate,
- maxView,
- minDate,
- pickLevel,
- startView,
- weekStart,
- } = datepicker.config || {};
+ var toPaddingObject = function toPaddingObject(padding, state) {
+ padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, {
+ placement: state.placement
+ })) : padding;
+ return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
+ };
- if (inOpts.language) {
- let lang;
- if (inOpts.language !== language) {
- if (locales[inOpts.language]) {
- lang = inOpts.language;
- } else {
- // Check if langauge + region tag can fallback to the one without
- // region (e.g. fr-CA → fr)
- lang = inOpts.language.split('-')[0];
- if (locales[lang] === undefined) {
- lang = false;
- }
- }
- }
- delete inOpts.language;
- if (lang) {
- language = config.language = lang;
+ function arrow(_ref) {
+ var _state$modifiersData$;
- // update locale as well when updating language
- const origLocale = locale || locales[defaultLang];
- // use default language's properties for the fallback
- locale = Object.assign({
- format: defaultFormat,
- weekStart: defaultWeekStart
- }, locales[defaultLang]);
- if (language !== defaultLang) {
- Object.assign(locale, locales[language]);
- }
- config.locale = locale;
- // if format and/or weekStart are the same as old locale's defaults,
- // update them to new locale's defaults
- if (format === origLocale.format) {
- format = config.format = locale.format;
- }
- if (weekStart === origLocale.weekStart) {
- weekStart = config.weekStart = locale.weekStart;
- config.weekEnd = calcEndOfWeek(locale.weekStart);
- }
- }
- }
+ var state = _ref.state,
+ name = _ref.name,
+ options = _ref.options;
+ var arrowElement = state.elements.arrow;
+ var popperOffsets = state.modifiersData.popperOffsets;
+ var basePlacement = getBasePlacement(state.placement);
+ var axis = getMainAxisFromPlacement(basePlacement);
+ var isVertical = [left, right].indexOf(basePlacement) >= 0;
+ var len = isVertical ? 'height' : 'width';
- if (inOpts.format) {
- const hasToDisplay = typeof inOpts.format.toDisplay === 'function';
- const hasToValue = typeof inOpts.format.toValue === 'function';
- const validFormatString = reFormatTokens.test(inOpts.format);
- if ((hasToDisplay && hasToValue) || validFormatString) {
- format = config.format = inOpts.format;
- }
- delete inOpts.format;
+ if (!arrowElement || !popperOffsets) {
+ return;
}
- //*** dates ***//
- // while min and maxDate for "no limit" in the options are better to be null
- // (especially when updating), the ones in the config have to be undefined
- // because null is treated as 0 (= unix epoch) when comparing with time value
- let minDt = minDate;
- let maxDt = maxDate;
- if (inOpts.minDate !== undefined) {
- minDt = inOpts.minDate === null
- ? dateValue(0, 0, 1) // set 0000-01-01 to prevent negative values for year
- : validateDate(inOpts.minDate, format, locale, minDt);
- delete inOpts.minDate;
- }
- if (inOpts.maxDate !== undefined) {
- maxDt = inOpts.maxDate === null
- ? undefined
- : validateDate(inOpts.maxDate, format, locale, maxDt);
- delete inOpts.maxDate;
- }
- if (maxDt < minDt) {
- minDate = config.minDate = maxDt;
- maxDate = config.maxDate = minDt;
- } else {
- if (minDate !== minDt) {
- minDate = config.minDate = minDt;
- }
- if (maxDate !== maxDt) {
- maxDate = config.maxDate = maxDt;
- }
- }
+ var paddingObject = toPaddingObject(options.padding, state);
+ var arrowRect = getLayoutRect(arrowElement);
+ var minProp = axis === 'y' ? top : left;
+ var maxProp = axis === 'y' ? bottom : right;
+ var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];
+ var startDiff = popperOffsets[axis] - state.rects.reference[axis];
+ var arrowOffsetParent = getOffsetParent(arrowElement);
+ var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
+ var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is
+ // outside of the popper bounds
- if (inOpts.datesDisabled) {
- config.datesDisabled = inOpts.datesDisabled.reduce((dates, dt) => {
- const date = parseDate(dt, format, locale);
- return date !== undefined ? pushUnique(dates, date) : dates;
- }, []);
- delete inOpts.datesDisabled;
- }
- if (inOpts.defaultViewDate !== undefined) {
- const viewDate = parseDate(inOpts.defaultViewDate, format, locale);
- if (viewDate !== undefined) {
- config.defaultViewDate = viewDate;
- }
- delete inOpts.defaultViewDate;
- }
+ var min = paddingObject[minProp];
+ var max = clientSize - arrowRect[len] - paddingObject[maxProp];
+ var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;
+ var offset = within(min, center, max); // Prevents breaking syntax highlighting...
- //*** days of week ***//
- if (inOpts.weekStart !== undefined) {
- const wkStart = Number(inOpts.weekStart) % 7;
- if (!isNaN(wkStart)) {
- weekStart = config.weekStart = wkStart;
- config.weekEnd = calcEndOfWeek(wkStart);
- }
- delete inOpts.weekStart;
- }
- if (inOpts.daysOfWeekDisabled) {
- config.daysOfWeekDisabled = inOpts.daysOfWeekDisabled.reduce(sanitizeDOW, []);
- delete inOpts.daysOfWeekDisabled;
- }
- if (inOpts.daysOfWeekHighlighted) {
- config.daysOfWeekHighlighted = inOpts.daysOfWeekHighlighted.reduce(sanitizeDOW, []);
- delete inOpts.daysOfWeekHighlighted;
- }
+ var axisProp = axis;
+ state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);
+ }
- //*** multi date ***//
- if (inOpts.maxNumberOfDates !== undefined) {
- const maxNumberOfDates = parseInt(inOpts.maxNumberOfDates, 10);
- if (maxNumberOfDates >= 0) {
- config.maxNumberOfDates = maxNumberOfDates;
- config.multidate = maxNumberOfDates !== 1;
+ function effect$1(_ref2) {
+ var state = _ref2.state,
+ options = _ref2.options;
+ var _options$element = options.element,
+ arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element;
+
+ if (arrowElement == null) {
+ return;
+ } // CSS selector
+
+
+ if (typeof arrowElement === 'string') {
+ arrowElement = state.elements.popper.querySelector(arrowElement);
+
+ if (!arrowElement) {
+ return;
}
- delete inOpts.maxNumberOfDates;
- }
- if (inOpts.dateDelimiter) {
- config.dateDelimiter = String(inOpts.dateDelimiter);
- delete inOpts.dateDelimiter;
}
- //*** pick level & view ***//
- let newPickLevel = pickLevel;
- if (inOpts.pickLevel !== undefined) {
- newPickLevel = validateViewId(inOpts.pickLevel, 2);
- delete inOpts.pickLevel;
- }
- if (newPickLevel !== pickLevel) {
- pickLevel = config.pickLevel = newPickLevel;
- }
+ if (!contains(state.elements.popper, arrowElement)) {
- let newMaxView = maxView;
- if (inOpts.maxView !== undefined) {
- newMaxView = validateViewId(inOpts.maxView, maxView);
- delete inOpts.maxView;
- }
- // ensure max view >= pick level
- newMaxView = pickLevel > newMaxView ? pickLevel : newMaxView;
- if (newMaxView !== maxView) {
- maxView = config.maxView = newMaxView;
+ return;
}
- let newStartView = startView;
- if (inOpts.startView !== undefined) {
- newStartView = validateViewId(inOpts.startView, newStartView);
- delete inOpts.startView;
- }
- // ensure pick level <= start view <= max view
- if (newStartView < pickLevel) {
- newStartView = pickLevel;
- } else if (newStartView > maxView) {
- newStartView = maxView;
- }
- if (newStartView !== startView) {
- config.startView = newStartView;
- }
+ state.elements.arrow = arrowElement;
+ } // eslint-disable-next-line import/no-unused-modules
- //*** template ***//
- if (inOpts.prevArrow) {
- const prevArrow = parseHTML(inOpts.prevArrow);
- if (prevArrow.childNodes.length > 0) {
- config.prevArrow = prevArrow.childNodes;
- }
- delete inOpts.prevArrow;
- }
- if (inOpts.nextArrow) {
- const nextArrow = parseHTML(inOpts.nextArrow);
- if (nextArrow.childNodes.length > 0) {
- config.nextArrow = nextArrow.childNodes;
- }
- delete inOpts.nextArrow;
- }
- //*** misc ***//
- if (inOpts.disableTouchKeyboard !== undefined) {
- config.disableTouchKeyboard = 'ontouchstart' in document && !!inOpts.disableTouchKeyboard;
- delete inOpts.disableTouchKeyboard;
- }
- if (inOpts.orientation) {
- const orientation = inOpts.orientation.toLowerCase().split(/\s+/g);
- config.orientation = {
- x: orientation.find(x => (x === 'left' || x === 'right')) || 'auto',
- y: orientation.find(y => (y === 'top' || y === 'bottom')) || 'auto',
- };
- delete inOpts.orientation;
- }
- if (inOpts.todayBtnMode !== undefined) {
- switch(inOpts.todayBtnMode) {
- case 0:
- case 1:
- config.todayBtnMode = inOpts.todayBtnMode;
- }
- delete inOpts.todayBtnMode;
- }
+ var arrow$1 = {
+ name: 'arrow',
+ enabled: true,
+ phase: 'main',
+ fn: arrow,
+ effect: effect$1,
+ requires: ['popperOffsets'],
+ requiresIfExists: ['preventOverflow']
+ };
- //*** copy the rest ***//
- Object.keys(inOpts).forEach((key) => {
- if (inOpts[key] !== undefined && hasProperty(defaultOptions, key)) {
- config[key] = inOpts[key];
- }
- });
+ var unsetSides = {
+ top: 'auto',
+ right: 'auto',
+ bottom: 'auto',
+ left: 'auto'
+ }; // Round the offsets to the nearest suitable subpixel based on the DPR.
+ // Zooming can change the DPR, but it seems to report a value that will
+ // cleanly divide the values into the appropriate subpixels.
- return config;
+ function roundOffsetsByDPR(_ref) {
+ var x = _ref.x,
+ y = _ref.y;
+ var win = window;
+ var dpr = win.devicePixelRatio || 1;
+ return {
+ x: round(round(x * dpr) / dpr) || 0,
+ y: round(round(y * dpr) / dpr) || 0
+ };
}
- const pickerTemplate = optimizeTemplateHTML(`<div class="datepicker">
- <div class="datepicker-picker">
- <div class="datepicker-header">
- <div class="datepicker-title"></div>
- <div class="datepicker-controls">
- <button type="button" class="%buttonClass% prev-btn"></button>
- <button type="button" class="%buttonClass% view-switch"></button>
- <button type="button" class="%buttonClass% next-btn"></button>
- </div>
- </div>
- <div class="datepicker-main"></div>
- <div class="datepicker-footer">
- <div class="datepicker-controls">
- <button type="button" class="%buttonClass% today-btn"></button>
- <button type="button" class="%buttonClass% clear-btn"></button>
- </div>
- </div>
- </div>
-</div>`);
+ function mapToStyles(_ref2) {
+ var _Object$assign2;
- const daysTemplate = optimizeTemplateHTML(`<div class="days">
- <div class="days-of-week">${createTagRepeat('span', 7, {class: 'dow'})}</div>
- <div class="datepicker-grid">${createTagRepeat('span', 42)}</div>
-</div>`);
+ var popper = _ref2.popper,
+ popperRect = _ref2.popperRect,
+ placement = _ref2.placement,
+ offsets = _ref2.offsets,
+ position = _ref2.position,
+ gpuAcceleration = _ref2.gpuAcceleration,
+ adaptive = _ref2.adaptive,
+ roundOffsets = _ref2.roundOffsets;
- const calendarWeeksTemplate = optimizeTemplateHTML(`<div class="calendar-weeks">
- <div class="days-of-week"><span class="dow"></span></div>
- <div class="weeks">${createTagRepeat('span', 6, {class: 'week'})}</div>
-</div>`);
+ var _ref3 = roundOffsets === true ? roundOffsetsByDPR(offsets) : typeof roundOffsets === 'function' ? roundOffsets(offsets) : offsets,
+ _ref3$x = _ref3.x,
+ x = _ref3$x === void 0 ? 0 : _ref3$x,
+ _ref3$y = _ref3.y,
+ y = _ref3$y === void 0 ? 0 : _ref3$y;
- // Base class of the view classes
- class View {
- constructor(picker, config) {
- Object.assign(this, config, {
- picker,
- element: parseHTML(`<div class="datepicker-view"></div>`).firstChild,
- selected: [],
- });
- this.init(this.picker.datepicker.config);
- }
+ var hasX = offsets.hasOwnProperty('x');
+ var hasY = offsets.hasOwnProperty('y');
+ var sideX = left;
+ var sideY = top;
+ var win = window;
- init(options) {
- if (options.pickLevel !== undefined) {
- this.isMinView = this.id === options.pickLevel;
- }
- this.setOptions(options);
- this.updateFocus();
- this.updateSelection();
- }
+ if (adaptive) {
+ var offsetParent = getOffsetParent(popper);
+ var heightProp = 'clientHeight';
+ var widthProp = 'clientWidth';
- // Execute beforeShow() callback and apply the result to the element
- // args:
- // - current - current value on the iteration on view rendering
- // - timeValue - time value of the date to pass to beforeShow()
- performBeforeHook(el, current, timeValue) {
- let result = this.beforeShow(new Date(timeValue));
- switch (typeof result) {
- case 'boolean':
- result = {enabled: result};
- break;
- case 'string':
- result = {classes: result};
- }
+ if (offsetParent === getWindow(popper)) {
+ offsetParent = getDocumentElement(popper);
- if (result) {
- if (result.enabled === false) {
- el.classList.add('disabled');
- pushUnique(this.disabled, current);
- }
- if (result.classes) {
- const extraClasses = result.classes.split(/\s+/);
- el.classList.add(...extraClasses);
- if (extraClasses.includes('disabled')) {
- pushUnique(this.disabled, current);
- }
- }
- if (result.content) {
- replaceChildNodes(el, result.content);
+ if (getComputedStyle$1(offsetParent).position !== 'static') {
+ heightProp = 'scrollHeight';
+ widthProp = 'scrollWidth';
}
+ } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it
+
+
+ offsetParent = offsetParent;
+
+ if (placement === top) {
+ sideY = bottom; // $FlowFixMe[prop-missing]
+
+ y -= offsetParent[heightProp] - popperRect.height;
+ y *= gpuAcceleration ? 1 : -1;
+ }
+
+ if (placement === left) {
+ sideX = right; // $FlowFixMe[prop-missing]
+
+ x -= offsetParent[widthProp] - popperRect.width;
+ x *= gpuAcceleration ? 1 : -1;
}
}
+
+ var commonStyles = Object.assign({
+ position: position
+ }, adaptive && unsetSides);
+
+ if (gpuAcceleration) {
+ var _Object$assign;
+
+ return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) < 2 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign));
+ }
+
+ return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : '', _Object$assign2[sideX] = hasX ? x + "px" : '', _Object$assign2.transform = '', _Object$assign2));
}
- class DaysView extends View {
- constructor(picker) {
- super(picker, {
- id: 0,
- name: 'days',
- cellClass: 'day',
- });
+ function computeStyles(_ref4) {
+ var state = _ref4.state,
+ options = _ref4.options;
+ var _options$gpuAccelerat = options.gpuAcceleration,
+ gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,
+ _options$adaptive = options.adaptive,
+ adaptive = _options$adaptive === void 0 ? true : _options$adaptive,
+ _options$roundOffsets = options.roundOffsets,
+ roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;
+
+ var commonStyles = {
+ placement: getBasePlacement(state.placement),
+ popper: state.elements.popper,
+ popperRect: state.rects.popper,
+ gpuAcceleration: gpuAcceleration
+ };
+
+ if (state.modifiersData.popperOffsets != null) {
+ state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {
+ offsets: state.modifiersData.popperOffsets,
+ position: state.options.strategy,
+ adaptive: adaptive,
+ roundOffsets: roundOffsets
+ })));
}
- init(options, onConstruction = true) {
- if (onConstruction) {
- const inner = parseHTML(daysTemplate).firstChild;
- this.dow = inner.firstChild;
- this.grid = inner.lastChild;
- this.element.appendChild(inner);
- }
- super.init(options);
+ if (state.modifiersData.arrow != null) {
+ state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {
+ offsets: state.modifiersData.arrow,
+ position: 'absolute',
+ adaptive: false,
+ roundOffsets: roundOffsets
+ })));
}
- setOptions(options) {
- let updateDOW;
+ state.attributes.popper = Object.assign({}, state.attributes.popper, {
+ 'data-popper-placement': state.placement
+ });
+ } // eslint-disable-next-line import/no-unused-modules
- if (hasProperty(options, 'minDate')) {
- this.minDate = options.minDate;
- }
- if (hasProperty(options, 'maxDate')) {
- this.maxDate = options.maxDate;
- }
- if (options.datesDisabled) {
- this.datesDisabled = options.datesDisabled;
- }
- if (options.daysOfWeekDisabled) {
- this.daysOfWeekDisabled = options.daysOfWeekDisabled;
- updateDOW = true;
- }
- if (options.daysOfWeekHighlighted) {
- this.daysOfWeekHighlighted = options.daysOfWeekHighlighted;
- }
- if (options.todayHighlight !== undefined) {
- this.todayHighlight = options.todayHighlight;
- }
- if (options.weekStart !== undefined) {
- this.weekStart = options.weekStart;
- this.weekEnd = options.weekEnd;
- updateDOW = true;
- }
- if (options.locale) {
- const locale = this.locale = options.locale;
- this.dayNames = locale.daysMin;
- this.switchLabelFormat = locale.titleFormat;
- updateDOW = true;
- }
- if (options.beforeShowDay !== undefined) {
- this.beforeShow = typeof options.beforeShowDay === 'function'
- ? options.beforeShowDay
- : undefined;
- }
- if (options.calendarWeeks !== undefined) {
- if (options.calendarWeeks && !this.calendarWeeks) {
- const weeksElem = parseHTML(calendarWeeksTemplate).firstChild;
- this.calendarWeeks = {
- element: weeksElem,
- dow: weeksElem.firstChild,
- weeks: weeksElem.lastChild,
- };
- this.element.insertBefore(weeksElem, this.element.firstChild);
- } else if (this.calendarWeeks && !options.calendarWeeks) {
- this.element.removeChild(this.calendarWeeks.element);
- this.calendarWeeks = null;
- }
- }
- if (options.showDaysOfWeek !== undefined) {
- if (options.showDaysOfWeek) {
- showElement(this.dow);
- if (this.calendarWeeks) {
- showElement(this.calendarWeeks.dow);
- }
- } else {
- hideElement(this.dow);
- if (this.calendarWeeks) {
- hideElement(this.calendarWeeks.dow);
- }
- }
- }
+ var computeStyles$1 = {
+ name: 'computeStyles',
+ enabled: true,
+ phase: 'beforeWrite',
+ fn: computeStyles,
+ data: {}
+ };
- // update days-of-week when locale, daysOfweekDisabled or weekStart is changed
- if (updateDOW) {
- Array.from(this.dow.children).forEach((el, index) => {
- const dow = (this.weekStart + index) % 7;
- el.textContent = this.dayNames[dow];
- el.className = this.daysOfWeekDisabled.includes(dow) ? 'dow disabled' : 'dow';
- });
- }
- }
+ var passive = {
+ passive: true
+ };
- // Apply update on the focused date to view's settings
- updateFocus() {
- const viewDate = new Date(this.picker.viewDate);
- const viewYear = viewDate.getFullYear();
- const viewMonth = viewDate.getMonth();
- const firstOfMonth = dateValue(viewYear, viewMonth, 1);
- const start = dayOfTheWeekOf(firstOfMonth, this.weekStart, this.weekStart);
+ function effect(_ref) {
+ var state = _ref.state,
+ instance = _ref.instance,
+ options = _ref.options;
+ var _options$scroll = options.scroll,
+ scroll = _options$scroll === void 0 ? true : _options$scroll,
+ _options$resize = options.resize,
+ resize = _options$resize === void 0 ? true : _options$resize;
+ var window = getWindow(state.elements.popper);
+ var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);
- this.first = firstOfMonth;
- this.last = dateValue(viewYear, viewMonth + 1, 0);
- this.start = start;
- this.focused = this.picker.viewDate;
+ if (scroll) {
+ scrollParents.forEach(function (scrollParent) {
+ scrollParent.addEventListener('scroll', instance.update, passive);
+ });
}
- // Apply update on the selected dates to view's settings
- updateSelection() {
- const {dates, rangepicker} = this.picker.datepicker;
- this.selected = dates;
- if (rangepicker) {
- this.range = rangepicker.dates;
- }
+ if (resize) {
+ window.addEventListener('resize', instance.update, passive);
}
- // Update the entire view UI
- render() {
- // update today marker on ever render
- this.today = this.todayHighlight ? today() : undefined;
- // refresh disabled dates on every render in order to clear the ones added
- // by beforeShow hook at previous render
- this.disabled = [...this.datesDisabled];
-
- const switchLabel = formatDate(this.focused, this.switchLabelFormat, this.locale);
- this.picker.setViewSwitchLabel(switchLabel);
- this.picker.setPrevBtnDisabled(this.first <= this.minDate);
- this.picker.setNextBtnDisabled(this.last >= this.maxDate);
-
- if (this.calendarWeeks) {
- // start of the UTC week (Monday) of the 1st of the month
- const startOfWeek = dayOfTheWeekOf(this.first, 1, 1);
- Array.from(this.calendarWeeks.weeks.children).forEach((el, index) => {
- el.textContent = getWeek(addWeeks(startOfWeek, index));
+ return function () {
+ if (scroll) {
+ scrollParents.forEach(function (scrollParent) {
+ scrollParent.removeEventListener('scroll', instance.update, passive);
});
}
- Array.from(this.grid.children).forEach((el, index) => {
- const classList = el.classList;
- const current = addDays(this.start, index);
- const date = new Date(current);
- const day = date.getDay();
-
- el.className = `datepicker-cell ${this.cellClass}`;
- el.dataset.date = current;
- el.textContent = date.getDate();
- if (current < this.first) {
- classList.add('prev');
- } else if (current > this.last) {
- classList.add('next');
- }
- if (this.today === current) {
- classList.add('today');
- }
- if (current < this.minDate || current > this.maxDate || this.disabled.includes(current)) {
- classList.add('disabled');
- }
- if (this.daysOfWeekDisabled.includes(day)) {
- classList.add('disabled');
- pushUnique(this.disabled, current);
- }
- if (this.daysOfWeekHighlighted.includes(day)) {
- classList.add('highlighted');
- }
- if (this.range) {
- const [rangeStart, rangeEnd] = this.range;
- if (current > rangeStart && current < rangeEnd) {
- classList.add('range');
- }
- if (current === rangeStart) {
- classList.add('range-start');
- }
- if (current === rangeEnd) {
- classList.add('range-end');
- }
- }
- if (this.selected.includes(current)) {
- classList.add('selected');
- }
- if (current === this.focused) {
- classList.add('focused');
- }
+ if (resize) {
+ window.removeEventListener('resize', instance.update, passive);
+ }
+ };
+ } // eslint-disable-next-line import/no-unused-modules
- if (this.beforeShow) {
- this.performBeforeHook(el, current, current);
- }
- });
- }
- // Update the view UI by applying the changes of selected and focused items
- refresh() {
- const [rangeStart, rangeEnd] = this.range || [];
- this.grid
- .querySelectorAll('.range, .range-start, .range-end, .selected, .focused')
- .forEach((el) => {
- el.classList.remove('range', 'range-start', 'range-end', 'selected', 'focused');
- });
- Array.from(this.grid.children).forEach((el) => {
- const current = Number(el.dataset.date);
- const classList = el.classList;
- if (current > rangeStart && current < rangeEnd) {
- classList.add('range');
- }
- if (current === rangeStart) {
- classList.add('range-start');
- }
- if (current === rangeEnd) {
- classList.add('range-end');
- }
- if (this.selected.includes(current)) {
- classList.add('selected');
- }
- if (current === this.focused) {
- classList.add('focused');
- }
- });
- }
+ var eventListeners = {
+ name: 'eventListeners',
+ enabled: true,
+ phase: 'write',
+ fn: function fn() {},
+ effect: effect,
+ data: {}
+ };
- // Update the view UI by applying the change of focused item
- refreshFocus() {
- const index = Math.round((this.focused - this.start) / 86400000);
- this.grid.querySelectorAll('.focused').forEach((el) => {
- el.classList.remove('focused');
- });
- this.grid.children[index].classList.add('focused');
- }
+ var hash$1 = {
+ left: 'right',
+ right: 'left',
+ bottom: 'top',
+ top: 'bottom'
+ };
+ function getOppositePlacement(placement) {
+ return placement.replace(/left|right|bottom|top/g, function (matched) {
+ return hash$1[matched];
+ });
}
- function computeMonthRange(range, thisYear) {
- if (!range || !range[0] || !range[1]) {
- return;
- }
+ var hash = {
+ start: 'end',
+ end: 'start'
+ };
+ function getOppositeVariationPlacement(placement) {
+ return placement.replace(/start|end/g, function (matched) {
+ return hash[matched];
+ });
+ }
- const [[startY, startM], [endY, endM]] = range;
- if (startY > thisYear || endY < thisYear) {
- return;
- }
- return [
- startY === thisYear ? startM : -1,
- endY === thisYear ? endM : 12,
- ];
+ function getWindowScroll(node) {
+ var win = getWindow(node);
+ var scrollLeft = win.pageXOffset;
+ var scrollTop = win.pageYOffset;
+ return {
+ scrollLeft: scrollLeft,
+ scrollTop: scrollTop
+ };
}
- class MonthsView extends View {
- constructor(picker) {
- super(picker, {
- id: 1,
- name: 'months',
- cellClass: 'month',
- });
- }
-
- init(options, onConstruction = true) {
- if (onConstruction) {
- this.grid = this.element;
- this.element.classList.add('months', 'datepicker-grid');
- this.grid.appendChild(parseHTML(createTagRepeat('span', 12, {'data-month': ix => ix})));
- }
- super.init(options);
- }
+ function getWindowScrollBarX(element) {
+ // If <html> has a CSS width greater than the viewport, then this will be
+ // incorrect for RTL.
+ // Popper 1 is broken in this case and never had a bug report so let's assume
+ // it's not an issue. I don't think anyone ever specifies width on <html>
+ // anyway.
+ // Browsers where the left scrollbar doesn't cause an issue report `0` for
+ // this (e.g. Edge 2019, IE11, Safari)
+ return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
+ }
- setOptions(options) {
- if (options.locale) {
- this.monthNames = options.locale.monthsShort;
- }
- if (hasProperty(options, 'minDate')) {
- if (options.minDate === undefined) {
- this.minYear = this.minMonth = this.minDate = undefined;
- } else {
- const minDateObj = new Date(options.minDate);
- this.minYear = minDateObj.getFullYear();
- this.minMonth = minDateObj.getMonth();
- this.minDate = minDateObj.setDate(1);
- }
- }
- if (hasProperty(options, 'maxDate')) {
- if (options.maxDate === undefined) {
- this.maxYear = this.maxMonth = this.maxDate = undefined;
- } else {
- const maxDateObj = new Date(options.maxDate);
- this.maxYear = maxDateObj.getFullYear();
- this.maxMonth = maxDateObj.getMonth();
- this.maxDate = dateValue(this.maxYear, this.maxMonth + 1, 0);
- }
- }
- if (options.beforeShowMonth !== undefined) {
- this.beforeShow = typeof options.beforeShowMonth === 'function'
- ? options.beforeShowMonth
- : undefined;
- }
- }
+ function getViewportRect(element) {
+ var win = getWindow(element);
+ var html = getDocumentElement(element);
+ var visualViewport = win.visualViewport;
+ var width = html.clientWidth;
+ var height = html.clientHeight;
+ var x = 0;
+ var y = 0; // NB: This isn't supported on iOS <= 12. If the keyboard is open, the popper
+ // can be obscured underneath it.
+ // Also, `html.clientHeight` adds the bottom bar height in Safari iOS, even
+ // if it isn't open, so if this isn't available, the popper will be detected
+ // to overflow the bottom of the screen too early.
- // Update view's settings to reflect the viewDate set on the picker
- updateFocus() {
- const viewDate = new Date(this.picker.viewDate);
- this.year = viewDate.getFullYear();
- this.focused = viewDate.getMonth();
- }
+ if (visualViewport) {
+ width = visualViewport.width;
+ height = visualViewport.height; // Uses Layout Viewport (like Chrome; Safari does not currently)
+ // In Chrome, it returns a value very close to 0 (+/-) but contains rounding
+ // errors due to floating point numbers, so we need to check precision.
+ // Safari returns a number <= 0, usually < -1 when pinch-zoomed
+ // Feature detection fails in mobile emulation mode in Chrome.
+ // Math.abs(win.innerWidth / visualViewport.scale - visualViewport.width) <
+ // 0.001
+ // Fallback here: "Not Safari" userAgent
- // Update view's settings to reflect the selected dates
- updateSelection() {
- const {dates, rangepicker} = this.picker.datepicker;
- this.selected = dates.reduce((selected, timeValue) => {
- const date = new Date(timeValue);
- const year = date.getFullYear();
- const month = date.getMonth();
- if (selected[year] === undefined) {
- selected[year] = [month];
- } else {
- pushUnique(selected[year], month);
- }
- return selected;
- }, {});
- if (rangepicker && rangepicker.dates) {
- this.range = rangepicker.dates.map(timeValue => {
- const date = new Date(timeValue);
- return isNaN(date) ? undefined : [date.getFullYear(), date.getMonth()];
- });
+ if (!/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
+ x = visualViewport.offsetLeft;
+ y = visualViewport.offsetTop;
}
}
- // Update the entire view UI
- render() {
- // refresh disabled months on every render in order to clear the ones added
- // by beforeShow hook at previous render
- this.disabled = [];
+ return {
+ width: width,
+ height: height,
+ x: x + getWindowScrollBarX(element),
+ y: y
+ };
+ }
- this.picker.setViewSwitchLabel(this.year);
- this.picker.setPrevBtnDisabled(this.year <= this.minYear);
- this.picker.setNextBtnDisabled(this.year >= this.maxYear);
+ // of the `<html>` and `<body>` rect bounds if horizontally scrollable
- const selected = this.selected[this.year] || [];
- const yrOutOfRange = this.year < this.minYear || this.year > this.maxYear;
- const isMinYear = this.year === this.minYear;
- const isMaxYear = this.year === this.maxYear;
- const range = computeMonthRange(this.range, this.year);
+ function getDocumentRect(element) {
+ var _element$ownerDocumen;
- Array.from(this.grid.children).forEach((el, index) => {
- const classList = el.classList;
- const date = dateValue(this.year, index, 1);
+ var html = getDocumentElement(element);
+ var winScroll = getWindowScroll(element);
+ var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;
+ var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
+ var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
+ var x = -winScroll.scrollLeft + getWindowScrollBarX(element);
+ var y = -winScroll.scrollTop;
- el.className = `datepicker-cell ${this.cellClass}`;
- if (this.isMinView) {
- el.dataset.date = date;
- }
- // reset text on every render to clear the custom content set
- // by beforeShow hook at previous render
- el.textContent = this.monthNames[index];
+ if (getComputedStyle$1(body || html).direction === 'rtl') {
+ x += max(html.clientWidth, body ? body.clientWidth : 0) - width;
+ }
- if (
- yrOutOfRange
- || isMinYear && index < this.minMonth
- || isMaxYear && index > this.maxMonth
- ) {
- classList.add('disabled');
- }
- if (range) {
- const [rangeStart, rangeEnd] = range;
- if (index > rangeStart && index < rangeEnd) {
- classList.add('range');
- }
- if (index === rangeStart) {
- classList.add('range-start');
- }
- if (index === rangeEnd) {
- classList.add('range-end');
- }
- }
- if (selected.includes(index)) {
- classList.add('selected');
- }
- if (index === this.focused) {
- classList.add('focused');
- }
+ return {
+ width: width,
+ height: height,
+ x: x,
+ y: y
+ };
+ }
- if (this.beforeShow) {
- this.performBeforeHook(el, index, date);
- }
- });
- }
+ function isScrollParent(element) {
+ // Firefox wants us to check `-x` and `-y` variations as well
+ var _getComputedStyle = getComputedStyle$1(element),
+ overflow = _getComputedStyle.overflow,
+ overflowX = _getComputedStyle.overflowX,
+ overflowY = _getComputedStyle.overflowY;
- // Update the view UI by applying the changes of selected and focused items
- refresh() {
- const selected = this.selected[this.year] || [];
- const [rangeStart, rangeEnd] = computeMonthRange(this.range, this.year) || [];
- this.grid
- .querySelectorAll('.range, .range-start, .range-end, .selected, .focused')
- .forEach((el) => {
- el.classList.remove('range', 'range-start', 'range-end', 'selected', 'focused');
- });
- Array.from(this.grid.children).forEach((el, index) => {
- const classList = el.classList;
- if (index > rangeStart && index < rangeEnd) {
- classList.add('range');
- }
- if (index === rangeStart) {
- classList.add('range-start');
- }
- if (index === rangeEnd) {
- classList.add('range-end');
- }
- if (selected.includes(index)) {
- classList.add('selected');
- }
- if (index === this.focused) {
- classList.add('focused');
- }
- });
+ return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
+ }
+
+ function getScrollParent(node) {
+ if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {
+ // $FlowFixMe[incompatible-return]: assume body is always available
+ return node.ownerDocument.body;
}
- // Update the view UI by applying the change of focused item
- refreshFocus() {
- this.grid.querySelectorAll('.focused').forEach((el) => {
- el.classList.remove('focused');
- });
- this.grid.children[this.focused].classList.add('focused');
+ if (isHTMLElement(node) && isScrollParent(node)) {
+ return node;
}
- }
- function toTitleCase(word) {
- return [...word].reduce((str, ch, ix) => str += ix ? ch : ch.toUpperCase(), '');
+ return getScrollParent(getParentNode(node));
}
- // Class representing the years and decades view elements
- class YearsView extends View {
- constructor(picker, config) {
- super(picker, config);
- }
+ /*
+ given a DOM element, return the list of all scroll parents, up the list of ancesors
+ until we get to the top window object. This list is what we attach scroll listeners
+ to, because if any of these parent elements scroll, we'll need to re-calculate the
+ reference element's position.
+ */
- init(options, onConstruction = true) {
- if (onConstruction) {
- this.navStep = this.step * 10;
- this.beforeShowOption = `beforeShow${toTitleCase(this.cellClass)}`;
- this.grid = this.element;
- this.element.classList.add(this.name, 'datepicker-grid');
- this.grid.appendChild(parseHTML(createTagRepeat('span', 12)));
- }
- super.init(options);
- }
+ function listScrollParents(element, list) {
+ var _element$ownerDocumen;
- setOptions(options) {
- if (hasProperty(options, 'minDate')) {
- if (options.minDate === undefined) {
- this.minYear = this.minDate = undefined;
- } else {
- this.minYear = startOfYearPeriod(options.minDate, this.step);
- this.minDate = dateValue(this.minYear, 0, 1);
- }
- }
- if (hasProperty(options, 'maxDate')) {
- if (options.maxDate === undefined) {
- this.maxYear = this.maxDate = undefined;
- } else {
- this.maxYear = startOfYearPeriod(options.maxDate, this.step);
- this.maxDate = dateValue(this.maxYear, 11, 31);
- }
- }
- if (options[this.beforeShowOption] !== undefined) {
- const beforeShow = options[this.beforeShowOption];
- this.beforeShow = typeof beforeShow === 'function' ? beforeShow : undefined;
- }
+ if (list === void 0) {
+ list = [];
}
- // Update view's settings to reflect the viewDate set on the picker
- updateFocus() {
- const viewDate = new Date(this.picker.viewDate);
- const first = startOfYearPeriod(viewDate, this.navStep);
- const last = first + 9 * this.step;
+ var scrollParent = getScrollParent(element);
+ var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);
+ var win = getWindow(scrollParent);
+ var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;
+ var updatedList = list.concat(target);
+ return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here
+ updatedList.concat(listScrollParents(getParentNode(target)));
+ }
- this.first = first;
- this.last = last;
- this.start = first - this.step;
- this.focused = startOfYearPeriod(viewDate, this.step);
- }
+ function rectToClientRect(rect) {
+ return Object.assign({}, rect, {
+ left: rect.x,
+ top: rect.y,
+ right: rect.x + rect.width,
+ bottom: rect.y + rect.height
+ });
+ }
- // Update view's settings to reflect the selected dates
- updateSelection() {
- const {dates, rangepicker} = this.picker.datepicker;
- this.selected = dates.reduce((years, timeValue) => {
- return pushUnique(years, startOfYearPeriod(timeValue, this.step));
- }, []);
- if (rangepicker && rangepicker.dates) {
- this.range = rangepicker.dates.map(timeValue => {
- if (timeValue !== undefined) {
- return startOfYearPeriod(timeValue, this.step);
- }
- });
- }
- }
+ function getInnerBoundingClientRect(element) {
+ var rect = getBoundingClientRect(element);
+ rect.top = rect.top + element.clientTop;
+ rect.left = rect.left + element.clientLeft;
+ rect.bottom = rect.top + element.clientHeight;
+ rect.right = rect.left + element.clientWidth;
+ rect.width = element.clientWidth;
+ rect.height = element.clientHeight;
+ rect.x = rect.left;
+ rect.y = rect.top;
+ return rect;
+ }
- // Update the entire view UI
- render() {
- // refresh disabled years on every render in order to clear the ones added
- // by beforeShow hook at previous render
- this.disabled = [];
+ function getClientRectFromMixedType(element, clippingParent) {
+ return clippingParent === viewport ? rectToClientRect(getViewportRect(element)) : isHTMLElement(clippingParent) ? getInnerBoundingClientRect(clippingParent) : rectToClientRect(getDocumentRect(getDocumentElement(element)));
+ } // A "clipping parent" is an overflowable container with the characteristic of
+ // clipping (or hiding) overflowing elements with a position different from
+ // `initial`
- this.picker.setViewSwitchLabel(`${this.first}-${this.last}`);
- this.picker.setPrevBtnDisabled(this.first <= this.minYear);
- this.picker.setNextBtnDisabled(this.last >= this.maxYear);
- Array.from(this.grid.children).forEach((el, index) => {
- const classList = el.classList;
- const current = this.start + (index * this.step);
- const date = dateValue(current, 0, 1);
+ function getClippingParents(element) {
+ var clippingParents = listScrollParents(getParentNode(element));
+ var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle$1(element).position) >= 0;
+ var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;
- el.className = `datepicker-cell ${this.cellClass}`;
- if (this.isMinView) {
- el.dataset.date = date;
- }
- el.textContent = el.dataset.year = current;
+ if (!isElement$1(clipperElement)) {
+ return [];
+ } // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414
- if (index === 0) {
- classList.add('prev');
- } else if (index === 11) {
- classList.add('next');
- }
- if (current < this.minYear || current > this.maxYear) {
- classList.add('disabled');
- }
- if (this.range) {
- const [rangeStart, rangeEnd] = this.range;
- if (current > rangeStart && current < rangeEnd) {
- classList.add('range');
- }
- if (current === rangeStart) {
- classList.add('range-start');
- }
- if (current === rangeEnd) {
- classList.add('range-end');
- }
- }
- if (this.selected.includes(current)) {
- classList.add('selected');
- }
- if (current === this.focused) {
- classList.add('focused');
- }
- if (this.beforeShow) {
- this.performBeforeHook(el, current, date);
- }
- });
- }
+ return clippingParents.filter(function (clippingParent) {
+ return isElement$1(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body';
+ });
+ } // Gets the maximum area that the element is visible in due to any number of
+ // clipping parents
- // Update the view UI by applying the changes of selected and focused items
- refresh() {
- const [rangeStart, rangeEnd] = this.range || [];
- this.grid
- .querySelectorAll('.range, .range-start, .range-end, .selected, .focused')
- .forEach((el) => {
- el.classList.remove('range', 'range-start', 'range-end', 'selected', 'focused');
- });
- Array.from(this.grid.children).forEach((el) => {
- const current = Number(el.textContent);
- const classList = el.classList;
- if (current > rangeStart && current < rangeEnd) {
- classList.add('range');
- }
- if (current === rangeStart) {
- classList.add('range-start');
- }
- if (current === rangeEnd) {
- classList.add('range-end');
- }
- if (this.selected.includes(current)) {
- classList.add('selected');
- }
- if (current === this.focused) {
- classList.add('focused');
- }
- });
- }
- // Update the view UI by applying the change of focused item
- refreshFocus() {
- const index = Math.round((this.focused - this.start) / this.step);
- this.grid.querySelectorAll('.focused').forEach((el) => {
- el.classList.remove('focused');
- });
- this.grid.children[index].classList.add('focused');
- }
+ function getClippingRect(element, boundary, rootBoundary) {
+ var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);
+ var clippingParents = [].concat(mainClippingParents, [rootBoundary]);
+ var firstClippingParent = clippingParents[0];
+ var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {
+ var rect = getClientRectFromMixedType(element, clippingParent);
+ accRect.top = max(rect.top, accRect.top);
+ accRect.right = min(rect.right, accRect.right);
+ accRect.bottom = min(rect.bottom, accRect.bottom);
+ accRect.left = max(rect.left, accRect.left);
+ return accRect;
+ }, getClientRectFromMixedType(element, firstClippingParent));
+ clippingRect.width = clippingRect.right - clippingRect.left;
+ clippingRect.height = clippingRect.bottom - clippingRect.top;
+ clippingRect.x = clippingRect.left;
+ clippingRect.y = clippingRect.top;
+ return clippingRect;
}
- function triggerDatepickerEvent(datepicker, type) {
- const detail = {
- date: datepicker.getDate(),
- viewDate: new Date(datepicker.picker.viewDate),
- viewId: datepicker.picker.currentView.id,
- datepicker,
- };
- datepicker.element.dispatchEvent(new CustomEvent(type, {detail}));
+ function getVariation(placement) {
+ return placement.split('-')[1];
}
- // direction: -1 (to previous), 1 (to next)
- function goToPrevOrNext(datepicker, direction) {
- const {minDate, maxDate} = datepicker.config;
- const {currentView, viewDate} = datepicker.picker;
- let newViewDate;
- switch (currentView.id) {
- case 0:
- newViewDate = addMonths(viewDate, direction);
- break;
- case 1:
- newViewDate = addYears(viewDate, direction);
+ function computeOffsets(_ref) {
+ var reference = _ref.reference,
+ element = _ref.element,
+ placement = _ref.placement;
+ var basePlacement = placement ? getBasePlacement(placement) : null;
+ var variation = placement ? getVariation(placement) : null;
+ var commonX = reference.x + reference.width / 2 - element.width / 2;
+ var commonY = reference.y + reference.height / 2 - element.height / 2;
+ var offsets;
+
+ switch (basePlacement) {
+ case top:
+ offsets = {
+ x: commonX,
+ y: reference.y - element.height
+ };
break;
- default:
- newViewDate = addYears(viewDate, direction * currentView.navStep);
- }
- newViewDate = limitToRange(newViewDate, minDate, maxDate);
- datepicker.picker.changeFocus(newViewDate).render();
- }
- function switchView(datepicker) {
- const viewId = datepicker.picker.currentView.id;
- if (viewId === datepicker.config.maxView) {
- return;
- }
- datepicker.picker.changeView(viewId + 1).render();
- }
+ case bottom:
+ offsets = {
+ x: commonX,
+ y: reference.y + reference.height
+ };
+ break;
- function unfocus(datepicker) {
- if (datepicker.config.updateOnBlur) {
- datepicker.update({autohide: true});
- } else {
- datepicker.refresh('input');
- datepicker.hide();
+ case right:
+ offsets = {
+ x: reference.x + reference.width,
+ y: commonY
+ };
+ break;
+
+ case left:
+ offsets = {
+ x: reference.x - element.width,
+ y: commonY
+ };
+ break;
+
+ default:
+ offsets = {
+ x: reference.x,
+ y: reference.y
+ };
}
- }
- function goToSelectedMonthOrYear(datepicker, selection) {
- const picker = datepicker.picker;
- const viewDate = new Date(picker.viewDate);
- const viewId = picker.currentView.id;
- const newDate = viewId === 1
- ? addMonths(viewDate, selection - viewDate.getMonth())
- : addYears(viewDate, selection - viewDate.getFullYear());
+ var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;
- picker.changeFocus(newDate).changeView(viewId - 1).render();
- }
+ if (mainAxis != null) {
+ var len = mainAxis === 'y' ? 'height' : 'width';
- function onClickTodayBtn(datepicker) {
- const picker = datepicker.picker;
- const currentDate = today();
- if (datepicker.config.todayBtnMode === 1) {
- if (datepicker.config.autohide) {
- datepicker.setDate(currentDate);
- return;
+ switch (variation) {
+ case start:
+ offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);
+ break;
+
+ case end:
+ offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);
+ break;
}
- datepicker.setDate(currentDate, {render: false});
- picker.update();
}
- if (picker.viewDate !== currentDate) {
- picker.changeFocus(currentDate);
- }
- picker.changeView(0).render();
- }
- function onClickClearBtn(datepicker) {
- datepicker.setDate({clear: true});
+ return offsets;
}
- function onClickViewSwitch(datepicker) {
- switchView(datepicker);
- }
+ function detectOverflow(state, options) {
+ if (options === void 0) {
+ options = {};
+ }
- function onClickPrevBtn(datepicker) {
- goToPrevOrNext(datepicker, -1);
- }
+ var _options = options,
+ _options$placement = _options.placement,
+ placement = _options$placement === void 0 ? state.placement : _options$placement,
+ _options$boundary = _options.boundary,
+ boundary = _options$boundary === void 0 ? clippingParents : _options$boundary,
+ _options$rootBoundary = _options.rootBoundary,
+ rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary,
+ _options$elementConte = _options.elementContext,
+ elementContext = _options$elementConte === void 0 ? popper : _options$elementConte,
+ _options$altBoundary = _options.altBoundary,
+ altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary,
+ _options$padding = _options.padding,
+ padding = _options$padding === void 0 ? 0 : _options$padding;
+ var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
+ var altContext = elementContext === popper ? reference : popper;
+ var referenceElement = state.elements.reference;
+ var popperRect = state.rects.popper;
+ var element = state.elements[altBoundary ? altContext : elementContext];
+ var clippingClientRect = getClippingRect(isElement$1(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary);
+ var referenceClientRect = getBoundingClientRect(referenceElement);
+ var popperOffsets = computeOffsets({
+ reference: referenceClientRect,
+ element: popperRect,
+ strategy: 'absolute',
+ placement: placement
+ });
+ var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets));
+ var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect
+ // 0 or negative = within the clipping rect
- function onClickNextBtn(datepicker) {
- goToPrevOrNext(datepicker, 1);
- }
+ var overflowOffsets = {
+ top: clippingClientRect.top - elementClientRect.top + paddingObject.top,
+ bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,
+ left: clippingClientRect.left - elementClientRect.left + paddingObject.left,
+ right: elementClientRect.right - clippingClientRect.right + paddingObject.right
+ };
+ var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element
- // For the picker's main block to delegete the events from `datepicker-cell`s
- function onClickView(datepicker, ev) {
- const target = findElementInEventPath(ev, '.datepicker-cell');
- if (!target || target.classList.contains('disabled')) {
- return;
+ if (elementContext === popper && offsetData) {
+ var offset = offsetData[placement];
+ Object.keys(overflowOffsets).forEach(function (key) {
+ var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;
+ var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x';
+ overflowOffsets[key] += offset[axis] * multiply;
+ });
}
- const {id, isMinView} = datepicker.picker.currentView;
- if (isMinView) {
- datepicker.setDate(Number(target.dataset.date));
- } else if (id === 1) {
- goToSelectedMonthOrYear(datepicker, Number(target.dataset.month));
- } else {
- goToSelectedMonthOrYear(datepicker, Number(target.dataset.year));
- }
+ return overflowOffsets;
}
- function onClickPicker(datepicker) {
- if (!datepicker.inline && !datepicker.config.disableTouchKeyboard) {
- datepicker.inputField.focus();
+ function computeAutoPlacement(state, options) {
+ if (options === void 0) {
+ options = {};
}
+
+ var _options = options,
+ placement = _options.placement,
+ boundary = _options.boundary,
+ rootBoundary = _options.rootBoundary,
+ padding = _options.padding,
+ flipVariations = _options.flipVariations,
+ _options$allowedAutoP = _options.allowedAutoPlacements,
+ allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP;
+ var variation = getVariation(placement);
+ var placements$1 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) {
+ return getVariation(placement) === variation;
+ }) : basePlacements;
+ var allowedPlacements = placements$1.filter(function (placement) {
+ return allowedAutoPlacements.indexOf(placement) >= 0;
+ });
+
+ if (allowedPlacements.length === 0) {
+ allowedPlacements = placements$1;
+ } // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...
+
+
+ var overflows = allowedPlacements.reduce(function (acc, placement) {
+ acc[placement] = detectOverflow(state, {
+ placement: placement,
+ boundary: boundary,
+ rootBoundary: rootBoundary,
+ padding: padding
+ })[getBasePlacement(placement)];
+ return acc;
+ }, {});
+ return Object.keys(overflows).sort(function (a, b) {
+ return overflows[a] - overflows[b];
+ });
}
- function processPickerOptions(picker, options) {
- if (options.title !== undefined) {
- if (options.title) {
- picker.controls.title.textContent = options.title;
- showElement(picker.controls.title);
- } else {
- picker.controls.title.textContent = '';
- hideElement(picker.controls.title);
- }
- }
- if (options.prevArrow) {
- const prevBtn = picker.controls.prevBtn;
- emptyChildNodes(prevBtn);
- options.prevArrow.forEach((node) => {
- prevBtn.appendChild(node.cloneNode(true));
- });
- }
- if (options.nextArrow) {
- const nextBtn = picker.controls.nextBtn;
- emptyChildNodes(nextBtn);
- options.nextArrow.forEach((node) => {
- nextBtn.appendChild(node.cloneNode(true));
- });
- }
- if (options.locale) {
- picker.controls.todayBtn.textContent = options.locale.today;
- picker.controls.clearBtn.textContent = options.locale.clear;
- }
- if (options.todayBtn !== undefined) {
- if (options.todayBtn) {
- showElement(picker.controls.todayBtn);
- } else {
- hideElement(picker.controls.todayBtn);
- }
- }
- if (hasProperty(options, 'minDate') || hasProperty(options, 'maxDate')) {
- const {minDate, maxDate} = picker.datepicker.config;
- picker.controls.todayBtn.disabled = !isInRange(today(), minDate, maxDate);
- }
- if (options.clearBtn !== undefined) {
- if (options.clearBtn) {
- showElement(picker.controls.clearBtn);
- } else {
- hideElement(picker.controls.clearBtn);
- }
+ function getExpandedFallbackPlacements(placement) {
+ if (getBasePlacement(placement) === auto) {
+ return [];
}
- }
- // Compute view date to reset, which will be...
- // - the last item of the selected dates or defaultViewDate if no selection
- // - limitted to minDate or maxDate if it exceeds the range
- function computeResetViewDate(datepicker) {
- const {dates, config} = datepicker;
- const viewDate = dates.length > 0 ? lastItemOf(dates) : config.defaultViewDate;
- return limitToRange(viewDate, config.minDate, config.maxDate);
+ var oppositePlacement = getOppositePlacement(placement);
+ return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];
}
- // Change current view's view date
- function setViewDate(picker, newDate) {
- const oldViewDate = new Date(picker.viewDate);
- const newViewDate = new Date(newDate);
- const {id, year, first, last} = picker.currentView;
- const viewYear = newViewDate.getFullYear();
+ function flip(_ref) {
+ var state = _ref.state,
+ options = _ref.options,
+ name = _ref.name;
- picker.viewDate = newDate;
- if (viewYear !== oldViewDate.getFullYear()) {
- triggerDatepickerEvent(picker.datepicker, 'changeYear');
- }
- if (newViewDate.getMonth() !== oldViewDate.getMonth()) {
- triggerDatepickerEvent(picker.datepicker, 'changeMonth');
+ if (state.modifiersData[name]._skip) {
+ return;
}
- // return whether the new date is in different period on time from the one
- // displayed in the current view
- // when true, the view needs to be re-rendered on the next UI refresh.
- switch (id) {
- case 0:
- return newDate < first || newDate > last;
- case 1:
- return viewYear !== year;
- default:
- return viewYear < first || viewYear > last;
- }
- }
+ var _options$mainAxis = options.mainAxis,
+ checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
+ _options$altAxis = options.altAxis,
+ checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,
+ specifiedFallbackPlacements = options.fallbackPlacements,
+ padding = options.padding,
+ boundary = options.boundary,
+ rootBoundary = options.rootBoundary,
+ altBoundary = options.altBoundary,
+ _options$flipVariatio = options.flipVariations,
+ flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,
+ allowedAutoPlacements = options.allowedAutoPlacements;
+ var preferredPlacement = state.options.placement;
+ var basePlacement = getBasePlacement(preferredPlacement);
+ var isBasePlacement = basePlacement === preferredPlacement;
+ var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));
+ var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {
+ return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, {
+ placement: placement,
+ boundary: boundary,
+ rootBoundary: rootBoundary,
+ padding: padding,
+ flipVariations: flipVariations,
+ allowedAutoPlacements: allowedAutoPlacements
+ }) : placement);
+ }, []);
+ var referenceRect = state.rects.reference;
+ var popperRect = state.rects.popper;
+ var checksMap = new Map();
+ var makeFallbackChecks = true;
+ var firstFittingPlacement = placements[0];
- function getTextDirection(el) {
- return window.getComputedStyle(el).direction;
- }
+ for (var i = 0; i < placements.length; i++) {
+ var placement = placements[i];
- // Class representing the picker UI
- class Picker {
- constructor(datepicker) {
- this.datepicker = datepicker;
+ var _basePlacement = getBasePlacement(placement);
- const template = pickerTemplate.replace(/%buttonClass%/g, datepicker.config.buttonClass);
- const element = this.element = parseHTML(template).firstChild;
- const [header, main, footer] = element.firstChild.children;
- const title = header.firstElementChild;
- const [prevBtn, viewSwitch, nextBtn] = header.lastElementChild.children;
- const [todayBtn, clearBtn] = footer.firstChild.children;
- const controls = {
- title,
- prevBtn,
- viewSwitch,
- nextBtn,
- todayBtn,
- clearBtn,
- };
- this.main = main;
- this.controls = controls;
+ var isStartVariation = getVariation(placement) === start;
+ var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;
+ var len = isVertical ? 'width' : 'height';
+ var overflow = detectOverflow(state, {
+ placement: placement,
+ boundary: boundary,
+ rootBoundary: rootBoundary,
+ altBoundary: altBoundary,
+ padding: padding
+ });
+ var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;
- const elementClass = datepicker.inline ? 'inline' : 'dropdown';
- element.classList.add(`datepicker-${elementClass}`);
+ if (referenceRect[len] > popperRect[len]) {
+ mainVariationSide = getOppositePlacement(mainVariationSide);
+ }
- processPickerOptions(this, datepicker.config);
- this.viewDate = computeResetViewDate(datepicker);
+ var altVariationSide = getOppositePlacement(mainVariationSide);
+ var checks = [];
- // set up event listeners
- registerListeners(datepicker, [
- [element, 'click', onClickPicker.bind(null, datepicker), {capture: true}],
- [main, 'click', onClickView.bind(null, datepicker)],
- [controls.viewSwitch, 'click', onClickViewSwitch.bind(null, datepicker)],
- [controls.prevBtn, 'click', onClickPrevBtn.bind(null, datepicker)],
- [controls.nextBtn, 'click', onClickNextBtn.bind(null, datepicker)],
- [controls.todayBtn, 'click', onClickTodayBtn.bind(null, datepicker)],
- [controls.clearBtn, 'click', onClickClearBtn.bind(null, datepicker)],
- ]);
+ if (checkMainAxis) {
+ checks.push(overflow[_basePlacement] <= 0);
+ }
- // set up views
- this.views = [
- new DaysView(this),
- new MonthsView(this),
- new YearsView(this, {id: 2, name: 'years', cellClass: 'year', step: 1}),
- new YearsView(this, {id: 3, name: 'decades', cellClass: 'decade', step: 10}),
- ];
- this.currentView = this.views[datepicker.config.startView];
+ if (checkAltAxis) {
+ checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);
+ }
- this.currentView.render();
- this.main.appendChild(this.currentView.element);
- datepicker.config.container.appendChild(this.element);
- }
+ if (checks.every(function (check) {
+ return check;
+ })) {
+ firstFittingPlacement = placement;
+ makeFallbackChecks = false;
+ break;
+ }
- setOptions(options) {
- processPickerOptions(this, options);
- this.views.forEach((view) => {
- view.init(options, false);
- });
- this.currentView.render();
+ checksMap.set(placement, checks);
}
- detach() {
- this.datepicker.config.container.removeChild(this.element);
- }
+ if (makeFallbackChecks) {
+ // `2` may be desired in some cases – research later
+ var numberOfChecks = flipVariations ? 3 : 1;
- show() {
- if (this.active) {
- return;
- }
- this.element.classList.add('active');
- this.active = true;
+ var _loop = function _loop(_i) {
+ var fittingPlacement = placements.find(function (placement) {
+ var checks = checksMap.get(placement);
- const datepicker = this.datepicker;
- if (!datepicker.inline) {
- // ensure picker's direction matches input's
- const inputDirection = getTextDirection(datepicker.inputField);
- if (inputDirection !== getTextDirection(datepicker.config.container)) {
- this.element.dir = inputDirection;
- } else if (this.element.dir) {
- this.element.removeAttribute('dir');
- }
+ if (checks) {
+ return checks.slice(0, _i).every(function (check) {
+ return check;
+ });
+ }
+ });
- this.place();
- if (datepicker.config.disableTouchKeyboard) {
- datepicker.inputField.blur();
+ if (fittingPlacement) {
+ firstFittingPlacement = fittingPlacement;
+ return "break";
}
- }
- triggerDatepickerEvent(datepicker, 'show');
- }
+ };
- hide() {
- if (!this.active) {
- return;
+ for (var _i = numberOfChecks; _i > 0; _i--) {
+ var _ret = _loop(_i);
+
+ if (_ret === "break") break;
}
- this.datepicker.exitEditMode();
- this.element.classList.remove('active');
- this.active = false;
- triggerDatepickerEvent(this.datepicker, 'hide');
}
- place() {
- const {classList, style} = this.element;
- const {config, inputField} = this.datepicker;
- const container = config.container;
- const {
- width: calendarWidth,
- height: calendarHeight,
- } = this.element.getBoundingClientRect();
- const {
- left: containerLeft,
- top: containerTop,
- width: containerWidth,
- } = container.getBoundingClientRect();
- const {
- left: inputLeft,
- top: inputTop,
- width: inputWidth,
- height: inputHeight
- } = inputField.getBoundingClientRect();
- let {x: orientX, y: orientY} = config.orientation;
- let scrollTop;
- let left;
- let top;
+ if (state.placement !== firstFittingPlacement) {
+ state.modifiersData[name]._skip = true;
+ state.placement = firstFittingPlacement;
+ state.reset = true;
+ }
+ } // eslint-disable-next-line import/no-unused-modules
- if (container === document.body) {
- scrollTop = window.scrollY;
- left = inputLeft + window.scrollX;
- top = inputTop + scrollTop;
- } else {
- scrollTop = container.scrollTop;
- left = inputLeft - containerLeft;
- top = inputTop - containerTop + scrollTop;
- }
- if (orientX === 'auto') {
- if (left < 0) {
- // align to the left and move into visible area if input's left edge < window's
- orientX = 'left';
- left = 10;
- } else if (left + calendarWidth > containerWidth) {
- // align to the right if canlendar's right edge > container's
- orientX = 'right';
- } else {
- orientX = getTextDirection(inputField) === 'rtl' ? 'right' : 'left';
- }
- }
- if (orientX === 'right') {
- left -= calendarWidth - inputWidth;
- }
+ var flip$1 = {
+ name: 'flip',
+ enabled: true,
+ phase: 'main',
+ fn: flip,
+ requiresIfExists: ['offset'],
+ data: {
+ _skip: false
+ }
+ };
- if (orientY === 'auto') {
- orientY = top - calendarHeight < scrollTop ? 'bottom' : 'top';
- }
- if (orientY === 'top') {
- top -= calendarHeight;
- } else {
- top += inputHeight;
- }
+ function getSideOffsets(overflow, rect, preventedOffsets) {
+ if (preventedOffsets === void 0) {
+ preventedOffsets = {
+ x: 0,
+ y: 0
+ };
+ }
- classList.remove(
- 'datepicker-orient-top',
- 'datepicker-orient-bottom',
- 'datepicker-orient-right',
- 'datepicker-orient-left'
- );
- classList.add(`datepicker-orient-${orientY}`, `datepicker-orient-${orientX}`);
+ return {
+ top: overflow.top - rect.height - preventedOffsets.y,
+ right: overflow.right - rect.width + preventedOffsets.x,
+ bottom: overflow.bottom - rect.height + preventedOffsets.y,
+ left: overflow.left - rect.width - preventedOffsets.x
+ };
+ }
- style.top = top ? `${top}px` : top;
- style.left = left ? `${left}px` : left;
- }
+ function isAnySideFullyClipped(overflow) {
+ return [top, right, bottom, left].some(function (side) {
+ return overflow[side] >= 0;
+ });
+ }
- setViewSwitchLabel(labelText) {
- this.controls.viewSwitch.textContent = labelText;
- }
+ function hide(_ref) {
+ var state = _ref.state,
+ name = _ref.name;
+ var referenceRect = state.rects.reference;
+ var popperRect = state.rects.popper;
+ var preventedOffsets = state.modifiersData.preventOverflow;
+ var referenceOverflow = detectOverflow(state, {
+ elementContext: 'reference'
+ });
+ var popperAltOverflow = detectOverflow(state, {
+ altBoundary: true
+ });
+ var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);
+ var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);
+ var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);
+ var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);
+ state.modifiersData[name] = {
+ referenceClippingOffsets: referenceClippingOffsets,
+ popperEscapeOffsets: popperEscapeOffsets,
+ isReferenceHidden: isReferenceHidden,
+ hasPopperEscaped: hasPopperEscaped
+ };
+ state.attributes.popper = Object.assign({}, state.attributes.popper, {
+ 'data-popper-reference-hidden': isReferenceHidden,
+ 'data-popper-escaped': hasPopperEscaped
+ });
+ } // eslint-disable-next-line import/no-unused-modules
- setPrevBtnDisabled(disabled) {
- this.controls.prevBtn.disabled = disabled;
- }
- setNextBtnDisabled(disabled) {
- this.controls.nextBtn.disabled = disabled;
- }
+ var hide$1 = {
+ name: 'hide',
+ enabled: true,
+ phase: 'main',
+ requiresIfExists: ['preventOverflow'],
+ fn: hide
+ };
- changeView(viewId) {
- const oldView = this.currentView;
- const newView = this.views[viewId];
- if (newView.id !== oldView.id) {
- this.currentView = newView;
- this._renderMethod = 'render';
- triggerDatepickerEvent(this.datepicker, 'changeView');
- this.main.replaceChild(newView.element, oldView.element);
- }
- return this;
- }
+ function distanceAndSkiddingToXY(placement, rects, offset) {
+ var basePlacement = getBasePlacement(placement);
+ var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;
- // Change the focused date (view date)
- changeFocus(newViewDate) {
- this._renderMethod = setViewDate(this, newViewDate) ? 'render' : 'refreshFocus';
- this.views.forEach((view) => {
- view.updateFocus();
- });
- return this;
- }
+ var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, {
+ placement: placement
+ })) : offset,
+ skidding = _ref[0],
+ distance = _ref[1];
- // Apply the change of the selected dates
- update() {
- const newViewDate = computeResetViewDate(this.datepicker);
- this._renderMethod = setViewDate(this, newViewDate) ? 'render' : 'refresh';
- this.views.forEach((view) => {
- view.updateFocus();
- view.updateSelection();
- });
- return this;
- }
+ skidding = skidding || 0;
+ distance = (distance || 0) * invertDistance;
+ return [left, right].indexOf(basePlacement) >= 0 ? {
+ x: distance,
+ y: skidding
+ } : {
+ x: skidding,
+ y: distance
+ };
+ }
- // Refresh the picker UI
- render(quickRender = true) {
- const renderMethod = (quickRender && this._renderMethod) || 'render';
- delete this._renderMethod;
+ function offset(_ref2) {
+ var state = _ref2.state,
+ options = _ref2.options,
+ name = _ref2.name;
+ var _options$offset = options.offset,
+ offset = _options$offset === void 0 ? [0, 0] : _options$offset;
+ var data = placements.reduce(function (acc, placement) {
+ acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset);
+ return acc;
+ }, {});
+ var _data$state$placement = data[state.placement],
+ x = _data$state$placement.x,
+ y = _data$state$placement.y;
- this.currentView[renderMethod]();
+ if (state.modifiersData.popperOffsets != null) {
+ state.modifiersData.popperOffsets.x += x;
+ state.modifiersData.popperOffsets.y += y;
}
+
+ state.modifiersData[name] = data;
+ } // eslint-disable-next-line import/no-unused-modules
+
+
+ var offset$1 = {
+ name: 'offset',
+ enabled: true,
+ phase: 'main',
+ requires: ['popperOffsets'],
+ fn: offset
+ };
+
+ function popperOffsets(_ref) {
+ var state = _ref.state,
+ name = _ref.name;
+ // Offsets are the actual position the popper needs to have to be
+ // properly positioned near its reference element
+ // This is the most basic placement, and will be adjusted by
+ // the modifiers in the next step
+ state.modifiersData[name] = computeOffsets({
+ reference: state.rects.reference,
+ element: state.rects.popper,
+ strategy: 'absolute',
+ placement: state.placement
+ });
+ } // eslint-disable-next-line import/no-unused-modules
+
+
+ var popperOffsets$1 = {
+ name: 'popperOffsets',
+ enabled: true,
+ phase: 'read',
+ fn: popperOffsets,
+ data: {}
+ };
+
+ function getAltAxis(axis) {
+ return axis === 'x' ? 'y' : 'x';
}
- // Find the closest date that doesn't meet the condition for unavailable date
- // Returns undefined if no available date is found
- // addFn: function to calculate the next date
- // - args: time value, amount
- // increase: amount to pass to addFn
- // testFn: function to test the unavailablity of the date
- // - args: time value; retun: true if unavailable
- function findNextAvailableOne(date, addFn, increase, testFn, min, max) {
- if (!isInRange(date, min, max)) {
+ function preventOverflow(_ref) {
+ var state = _ref.state,
+ options = _ref.options,
+ name = _ref.name;
+ var _options$mainAxis = options.mainAxis,
+ checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
+ _options$altAxis = options.altAxis,
+ checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis,
+ boundary = options.boundary,
+ rootBoundary = options.rootBoundary,
+ altBoundary = options.altBoundary,
+ padding = options.padding,
+ _options$tether = options.tether,
+ tether = _options$tether === void 0 ? true : _options$tether,
+ _options$tetherOffset = options.tetherOffset,
+ tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;
+ var overflow = detectOverflow(state, {
+ boundary: boundary,
+ rootBoundary: rootBoundary,
+ padding: padding,
+ altBoundary: altBoundary
+ });
+ var basePlacement = getBasePlacement(state.placement);
+ var variation = getVariation(state.placement);
+ var isBasePlacement = !variation;
+ var mainAxis = getMainAxisFromPlacement(basePlacement);
+ var altAxis = getAltAxis(mainAxis);
+ var popperOffsets = state.modifiersData.popperOffsets;
+ var referenceRect = state.rects.reference;
+ var popperRect = state.rects.popper;
+ var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, {
+ placement: state.placement
+ })) : tetherOffset;
+ var data = {
+ x: 0,
+ y: 0
+ };
+
+ if (!popperOffsets) {
return;
}
- if (testFn(date)) {
- const newDate = addFn(date, increase);
- return findNextAvailableOne(newDate, addFn, increase, testFn, min, max);
- }
- return date;
- }
- // direction: -1 (left/up), 1 (right/down)
- // vertical: true for up/down, false for left/right
- function moveByArrowKey(datepicker, ev, direction, vertical) {
- const picker = datepicker.picker;
- const currentView = picker.currentView;
- const step = currentView.step || 1;
- let viewDate = picker.viewDate;
- let addFn;
- let testFn;
- switch (currentView.id) {
- case 0:
- if (vertical) {
- viewDate = addDays(viewDate, direction * 7);
- } else if (ev.ctrlKey || ev.metaKey) {
- viewDate = addYears(viewDate, direction);
- } else {
- viewDate = addDays(viewDate, direction);
- }
- addFn = addDays;
- testFn = (date) => currentView.disabled.includes(date);
- break;
- case 1:
- viewDate = addMonths(viewDate, vertical ? direction * 4 : direction);
- addFn = addMonths;
- testFn = (date) => {
- const dt = new Date(date);
- const {year, disabled} = currentView;
- return dt.getFullYear() === year && disabled.includes(dt.getMonth());
- };
- break;
- default:
- viewDate = addYears(viewDate, direction * (vertical ? 4 : 1) * step);
- addFn = addYears;
- testFn = date => currentView.disabled.includes(startOfYearPeriod(date, step));
- }
- viewDate = findNextAvailableOne(
- viewDate,
- addFn,
- direction < 0 ? -step : step,
- testFn,
- currentView.minDate,
- currentView.maxDate
- );
- if (viewDate !== undefined) {
- picker.changeFocus(viewDate).render();
- }
- }
+ if (checkMainAxis || checkAltAxis) {
+ var mainSide = mainAxis === 'y' ? top : left;
+ var altSide = mainAxis === 'y' ? bottom : right;
+ var len = mainAxis === 'y' ? 'height' : 'width';
+ var offset = popperOffsets[mainAxis];
+ var min$1 = popperOffsets[mainAxis] + overflow[mainSide];
+ var max$1 = popperOffsets[mainAxis] - overflow[altSide];
+ var additive = tether ? -popperRect[len] / 2 : 0;
+ var minLen = variation === start ? referenceRect[len] : popperRect[len];
+ var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go
+ // outside the reference bounds
- function onKeydown(datepicker, ev) {
- if (ev.key === 'Tab') {
- unfocus(datepicker);
- return;
- }
+ var arrowElement = state.elements.arrow;
+ var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {
+ width: 0,
+ height: 0
+ };
+ var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject();
+ var arrowPaddingMin = arrowPaddingObject[mainSide];
+ var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want
+ // to include its full size in the calculation. If the reference is small
+ // and near the edge of a boundary, the popper can overflow even if the
+ // reference is not overflowing as well (e.g. virtual elements with no
+ // width or height)
- const picker = datepicker.picker;
- const {id, isMinView} = picker.currentView;
- if (!picker.active) {
- switch (ev.key) {
- case 'ArrowDown':
- case 'Escape':
- picker.show();
- break;
- case 'Enter':
- datepicker.update();
- break;
- default:
- return;
- }
- } else if (datepicker.editMode) {
- switch (ev.key) {
- case 'Escape':
- picker.hide();
- break;
- case 'Enter':
- datepicker.exitEditMode({update: true, autohide: datepicker.config.autohide});
- break;
- default:
- return;
- }
- } else {
- switch (ev.key) {
- case 'Escape':
- picker.hide();
- break;
- case 'ArrowLeft':
- if (ev.ctrlKey || ev.metaKey) {
- goToPrevOrNext(datepicker, -1);
- } else if (ev.shiftKey) {
- datepicker.enterEditMode();
- return;
- } else {
- moveByArrowKey(datepicker, ev, -1, false);
- }
- break;
- case 'ArrowRight':
- if (ev.ctrlKey || ev.metaKey) {
- goToPrevOrNext(datepicker, 1);
- } else if (ev.shiftKey) {
- datepicker.enterEditMode();
- return;
- } else {
- moveByArrowKey(datepicker, ev, 1, false);
- }
- break;
- case 'ArrowUp':
- if (ev.ctrlKey || ev.metaKey) {
- switchView(datepicker);
- } else if (ev.shiftKey) {
- datepicker.enterEditMode();
- return;
- } else {
- moveByArrowKey(datepicker, ev, -1, true);
- }
- break;
- case 'ArrowDown':
- if (ev.shiftKey && !ev.ctrlKey && !ev.metaKey) {
- datepicker.enterEditMode();
- return;
- }
- moveByArrowKey(datepicker, ev, 1, true);
- break;
- case 'Enter':
- if (isMinView) {
- datepicker.setDate(picker.viewDate);
- } else {
- picker.changeView(id - 1).render();
- }
- break;
- case 'Backspace':
- case 'Delete':
- datepicker.enterEditMode();
- return;
- default:
- if (ev.key.length === 1 && !ev.ctrlKey && !ev.metaKey) {
- datepicker.enterEditMode();
- }
- return;
+ var arrowLen = within(0, referenceRect[len], arrowRect[len]);
+ var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - tetherOffsetValue : minLen - arrowLen - arrowPaddingMin - tetherOffsetValue;
+ var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + tetherOffsetValue : maxLen + arrowLen + arrowPaddingMax + tetherOffsetValue;
+ var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);
+ var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;
+ var offsetModifierValue = state.modifiersData.offset ? state.modifiersData.offset[state.placement][mainAxis] : 0;
+ var tetherMin = popperOffsets[mainAxis] + minOffset - offsetModifierValue - clientOffset;
+ var tetherMax = popperOffsets[mainAxis] + maxOffset - offsetModifierValue;
+
+ if (checkMainAxis) {
+ var preventedOffset = within(tether ? min(min$1, tetherMin) : min$1, offset, tether ? max(max$1, tetherMax) : max$1);
+ popperOffsets[mainAxis] = preventedOffset;
+ data[mainAxis] = preventedOffset - offset;
}
- }
- ev.preventDefault();
- ev.stopPropagation();
- }
- function onFocus(datepicker) {
- if (datepicker.config.showOnFocus && !datepicker._showing) {
- datepicker.show();
- }
- }
+ if (checkAltAxis) {
+ var _mainSide = mainAxis === 'x' ? top : left;
- // for the prevention for entering edit mode while getting focus on click
- function onMousedown(datepicker, ev) {
- const el = ev.target;
- if (datepicker.picker.active || datepicker.config.showOnClick) {
- el._active = el === document.activeElement;
- el._clicking = setTimeout(() => {
- delete el._active;
- delete el._clicking;
- }, 2000);
- }
- }
+ var _altSide = mainAxis === 'x' ? bottom : right;
- function onClickInput(datepicker, ev) {
- const el = ev.target;
- if (!el._clicking) {
- return;
- }
- clearTimeout(el._clicking);
- delete el._clicking;
+ var _offset = popperOffsets[altAxis];
- if (el._active) {
- datepicker.enterEditMode();
- }
- delete el._active;
+ var _min = _offset + overflow[_mainSide];
- if (datepicker.config.showOnClick) {
- datepicker.show();
- }
- }
+ var _max = _offset - overflow[_altSide];
- function onPaste(datepicker, ev) {
- if (ev.clipboardData.types.includes('text/plain')) {
- datepicker.enterEditMode();
+ var _preventedOffset = within(tether ? min(_min, tetherMin) : _min, _offset, tether ? max(_max, tetherMax) : _max);
+
+ popperOffsets[altAxis] = _preventedOffset;
+ data[altAxis] = _preventedOffset - _offset;
+ }
}
+
+ state.modifiersData[name] = data;
+ } // eslint-disable-next-line import/no-unused-modules
+
+
+ var preventOverflow$1 = {
+ name: 'preventOverflow',
+ enabled: true,
+ phase: 'main',
+ fn: preventOverflow,
+ requiresIfExists: ['offset']
+ };
+
+ function getHTMLElementScroll(element) {
+ return {
+ scrollLeft: element.scrollLeft,
+ scrollTop: element.scrollTop
+ };
}
- // for the `document` to delegate the events from outside the picker/input field
- function onClickOutside(datepicker, ev) {
- const element = datepicker.element;
- if (element !== document.activeElement) {
- return;
- }
- const pickerElem = datepicker.picker.element;
- if (findElementInEventPath(ev, el => el === element || el === pickerElem)) {
- return;
+ function getNodeScroll(node) {
+ if (node === getWindow(node) || !isHTMLElement(node)) {
+ return getWindowScroll(node);
+ } else {
+ return getHTMLElementScroll(node);
}
- unfocus(datepicker);
}
- function stringifyDates(dates, config) {
- return dates
- .map(dt => formatDate(dt, config.format, config.locale))
- .join(config.dateDelimiter);
- }
+ // Composite means it takes into account transforms as well as layout.
- // parse input dates and create an array of time values for selection
- // returns undefined if there are no valid dates in inputDates
- // when origDates (current selection) is passed, the function works to mix
- // the input dates into the current selection
- function processInputDates(datepicker, inputDates, clear = false) {
- const {config, dates: origDates, rangepicker} = datepicker;
- if (inputDates.length === 0) {
- // empty input is considered valid unless origiDates is passed
- return clear ? [] : undefined;
+ function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {
+ if (isFixed === void 0) {
+ isFixed = false;
}
- const rangeEnd = rangepicker && datepicker === rangepicker.datepickers[1];
- let newDates = inputDates.reduce((dates, dt) => {
- let date = parseDate(dt, config.format, config.locale);
- if (date === undefined) {
- return dates;
- }
- if (config.pickLevel > 0) {
- // adjust to 1st of the month/Jan 1st of the year
- // or to the last day of the monh/Dec 31st of the year if the datepicker
- // is the range-end picker of a rangepicker
- const dt = new Date(date);
- if (config.pickLevel === 1) {
- date = rangeEnd
- ? dt.setMonth(dt.getMonth() + 1, 0)
- : dt.setDate(1);
- } else {
- date = rangeEnd
- ? dt.setFullYear(dt.getFullYear() + 1, 0, 0)
- : dt.setMonth(0, 1);
- }
+ var documentElement = getDocumentElement(offsetParent);
+ var rect = getBoundingClientRect(elementOrVirtualElement);
+ var isOffsetParentAnElement = isHTMLElement(offsetParent);
+ var scroll = {
+ scrollLeft: 0,
+ scrollTop: 0
+ };
+ var offsets = {
+ x: 0,
+ y: 0
+ };
+
+ if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
+ if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078
+ isScrollParent(documentElement)) {
+ scroll = getNodeScroll(offsetParent);
}
- if (
- isInRange(date, config.minDate, config.maxDate)
- && !dates.includes(date)
- && !config.datesDisabled.includes(date)
- && !config.daysOfWeekDisabled.includes(new Date(date).getDay())
- ) {
- dates.push(date);
+
+ if (isHTMLElement(offsetParent)) {
+ offsets = getBoundingClientRect(offsetParent);
+ offsets.x += offsetParent.clientLeft;
+ offsets.y += offsetParent.clientTop;
+ } else if (documentElement) {
+ offsets.x = getWindowScrollBarX(documentElement);
}
- return dates;
- }, []);
- if (newDates.length === 0) {
- return;
- }
- if (config.multidate && !clear) {
- // get the synmetric difference between origDates and newDates
- newDates = newDates.reduce((dates, date) => {
- if (!origDates.includes(date)) {
- dates.push(date);
- }
- return dates;
- }, origDates.filter(date => !newDates.includes(date)));
}
- // do length check always because user can input multiple dates regardless of the mode
- return config.maxNumberOfDates && newDates.length > config.maxNumberOfDates
- ? newDates.slice(config.maxNumberOfDates * -1)
- : newDates;
- }
- // refresh the UI elements
- // modes: 1: input only, 2, picker only, 3 both
- function refreshUI(datepicker, mode = 3, quickRender = true) {
- const {config, picker, inputField} = datepicker;
- if (mode & 2) {
- const newView = picker.active ? config.pickLevel : config.startView;
- picker.update().changeView(newView).render(quickRender);
- }
- if (mode & 1 && inputField) {
- inputField.value = stringifyDates(datepicker.dates, config);
- }
+ return {
+ x: rect.left + scroll.scrollLeft - offsets.x,
+ y: rect.top + scroll.scrollTop - offsets.y,
+ width: rect.width,
+ height: rect.height
+ };
}
- function setDate(datepicker, inputDates, options) {
- let {clear, render, autohide} = options;
- if (render === undefined) {
- render = true;
- }
- if (!render) {
- autohide = false;
- } else if (autohide === undefined) {
- autohide = datepicker.config.autohide;
- }
+ function order(modifiers) {
+ var map = new Map();
+ var visited = new Set();
+ var result = [];
+ modifiers.forEach(function (modifier) {
+ map.set(modifier.name, modifier);
+ }); // On visiting object, check for its dependencies and visit them recursively
- const newDates = processInputDates(datepicker, inputDates, clear);
- if (!newDates) {
- return;
- }
- if (newDates.toString() !== datepicker.dates.toString()) {
- datepicker.dates = newDates;
- refreshUI(datepicker, render ? 3 : 1);
- triggerDatepickerEvent(datepicker, 'changeDate');
- } else {
- refreshUI(datepicker, 1);
- }
- if (autohide) {
- datepicker.hide();
+ function sort(modifier) {
+ visited.add(modifier.name);
+ var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);
+ requires.forEach(function (dep) {
+ if (!visited.has(dep)) {
+ var depModifier = map.get(dep);
+
+ if (depModifier) {
+ sort(depModifier);
+ }
+ }
+ });
+ result.push(modifier);
}
- }
- /**
- * Class representing a date picker
- */
- class Datepicker {
- /**
- * Create a date picker
- * @param {Element} element - element to bind a date picker
- * @param {Object} [options] - config options
- * @param {DateRangePicker} [rangepicker] - DateRangePicker instance the
- * date picker belongs to. Use this only when creating date picker as a part
- * of date range picker
- */
- constructor(element, options = {}, rangepicker = undefined) {
- element.datepicker = this;
- this.element = element;
+ modifiers.forEach(function (modifier) {
+ if (!visited.has(modifier.name)) {
+ // check for visited object
+ sort(modifier);
+ }
+ });
+ return result;
+ }
- // set up config
- const config = this.config = Object.assign({
- buttonClass: (options.buttonClass && String(options.buttonClass)) || 'button',
- container: document.body,
- defaultViewDate: today(),
- maxDate: undefined,
- minDate: undefined,
- }, processOptions(defaultOptions, this));
- this._options = options;
- Object.assign(config, processOptions(options, this));
+ function orderModifiers(modifiers) {
+ // order based on dependencies
+ var orderedModifiers = order(modifiers); // order based on phase
- // configure by type
- const inline = this.inline = element.tagName !== 'INPUT';
- let inputField;
- let initialDates;
+ return modifierPhases.reduce(function (acc, phase) {
+ return acc.concat(orderedModifiers.filter(function (modifier) {
+ return modifier.phase === phase;
+ }));
+ }, []);
+ }
- if (inline) {
- config.container = element;
- initialDates = stringToArray(element.dataset.date, config.dateDelimiter);
- delete element.dataset.date;
- } else {
- const container = options.container ? document.querySelector(options.container) : null;
- if (container) {
- config.container = container;
- }
- inputField = this.inputField = element;
- inputField.classList.add('datepicker-input');
- initialDates = stringToArray(inputField.value, config.dateDelimiter);
- }
- if (rangepicker) {
- // check validiry
- const index = rangepicker.inputs.indexOf(inputField);
- const datepickers = rangepicker.datepickers;
- if (index < 0 || index > 1 || !Array.isArray(datepickers)) {
- throw Error('Invalid rangepicker object.');
- }
- // attach itaelf to the rangepicker here so that processInputDates() can
- // determine if this is the range-end picker of the rangepicker while
- // setting inital values when pickLevel > 0
- datepickers[index] = this;
- // add getter for rangepicker
- Object.defineProperty(this, 'rangepicker', {
- get() {
- return rangepicker;
- },
+ function debounce$1(fn) {
+ var pending;
+ return function () {
+ if (!pending) {
+ pending = new Promise(function (resolve) {
+ Promise.resolve().then(function () {
+ pending = undefined;
+ resolve(fn());
+ });
});
}
- // set initial dates
- this.dates = [];
- // process initial value
- const inputDateValues = processInputDates(this, initialDates);
- if (inputDateValues && inputDateValues.length > 0) {
- this.dates = inputDateValues;
- }
- if (inputField) {
- inputField.value = stringifyDates(this.dates, config);
- }
+ return pending;
+ };
+ }
- const picker = this.picker = new Picker(this);
+ function mergeByName(modifiers) {
+ var merged = modifiers.reduce(function (merged, current) {
+ var existing = merged[current.name];
+ merged[current.name] = existing ? Object.assign({}, existing, current, {
+ options: Object.assign({}, existing.options, current.options),
+ data: Object.assign({}, existing.data, current.data)
+ }) : current;
+ return merged;
+ }, {}); // IE11 does not support Object.values
- if (inline) {
- this.show();
- } else {
- // set up event listeners in other modes
- const onMousedownDocument = onClickOutside.bind(null, this);
- const listeners = [
- [inputField, 'keydown', onKeydown.bind(null, this)],
- [inputField, 'focus', onFocus.bind(null, this)],
- [inputField, 'mousedown', onMousedown.bind(null, this)],
- [inputField, 'click', onClickInput.bind(null, this)],
- [inputField, 'paste', onPaste.bind(null, this)],
- [document, 'mousedown', onMousedownDocument],
- [document, 'touchstart', onMousedownDocument],
- [window, 'resize', picker.place.bind(picker)]
- ];
- registerListeners(this, listeners);
- }
- }
+ return Object.keys(merged).map(function (key) {
+ return merged[key];
+ });
+ }
- /**
- * Format Date object or time value in given format and language
- * @param {Date|Number} date - date or time value to format
- * @param {String|Object} format - format string or object that contains
- * toDisplay() custom formatter, whose signature is
- * - args:
- * - date: {Date} - Date instance of the date passed to the method
- * - format: {Object} - the format object passed to the method
- * - locale: {Object} - locale for the language specified by `lang`
- * - return:
- * {String} formatted date
- * @param {String} [lang=en] - language code for the locale to use
- * @return {String} formatted date
- */
- static formatDate(date, format, lang) {
- return formatDate(date, format, lang && locales[lang] || locales.en);
- }
-
- /**
- * Parse date string
- * @param {String|Date|Number} dateStr - date string, Date object or time
- * value to parse
- * @param {String|Object} format - format string or object that contains
- * toValue() custom parser, whose signature is
- * - args:
- * - dateStr: {String|Date|Number} - the dateStr passed to the method
- * - format: {Object} - the format object passed to the method
- * - locale: {Object} - locale for the language specified by `lang`
- * - return:
- * {Date|Number} parsed date or its time value
- * @param {String} [lang=en] - language code for the locale to use
- * @return {Number} time value of parsed date
- */
- static parseDate(dateStr, format, lang) {
- return parseDate(dateStr, format, lang && locales[lang] || locales.en);
- }
+ var DEFAULT_OPTIONS = {
+ placement: 'bottom',
+ modifiers: [],
+ strategy: 'absolute'
+ };
- /**
- * @type {Object} - Installed locales in `[languageCode]: localeObject` format
- * en`:_English (US)_ is pre-installed.
- */
- static get locales() {
- return locales;
+ function areValidElements() {
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
}
- /**
- * @type {Boolean} - Whether the picker element is shown. `true` whne shown
- */
- get active() {
- return !!(this.picker && this.picker.active);
- }
+ return !args.some(function (element) {
+ return !(element && typeof element.getBoundingClientRect === 'function');
+ });
+ }
- /**
- * @type {HTMLDivElement} - DOM object of picker element
- */
- get pickerElement() {
- return this.picker ? this.picker.element : undefined;
+ function popperGenerator(generatorOptions) {
+ if (generatorOptions === void 0) {
+ generatorOptions = {};
}
- /**
- * Set new values to the config options
- * @param {Object} options - config options to update
- */
- setOptions(options) {
- const picker = this.picker;
- const newOptions = processOptions(options, this);
- Object.assign(this._options, options);
- Object.assign(this.config, newOptions);
- picker.setOptions(newOptions);
+ var _generatorOptions = generatorOptions,
+ _generatorOptions$def = _generatorOptions.defaultModifiers,
+ defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,
+ _generatorOptions$def2 = _generatorOptions.defaultOptions,
+ defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;
+ return function createPopper(reference, popper, options) {
+ if (options === void 0) {
+ options = defaultOptions;
+ }
- refreshUI(this, 3);
- }
+ var state = {
+ placement: 'bottom',
+ orderedModifiers: [],
+ options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),
+ modifiersData: {},
+ elements: {
+ reference: reference,
+ popper: popper
+ },
+ attributes: {},
+ styles: {}
+ };
+ var effectCleanupFns = [];
+ var isDestroyed = false;
+ var instance = {
+ state: state,
+ setOptions: function setOptions(options) {
+ cleanupModifierEffects();
+ state.options = Object.assign({}, defaultOptions, state.options, options);
+ state.scrollParents = {
+ reference: isElement$1(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],
+ popper: listScrollParents(popper)
+ }; // Orders the modifiers based on their dependencies and `phase`
+ // properties
- /**
- * Show the picker element
- */
- show() {
- if (this.inputField) {
- if (this.inputField.disabled) {
- return;
- }
- if (this.inputField !== document.activeElement) {
- this._showing = true;
- this.inputField.focus();
- delete this._showing;
- }
- }
- this.picker.show();
- }
+ var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers
- /**
- * Hide the picker element
- * Not available on inline picker
- */
- hide() {
- if (this.inline) {
- return;
- }
- this.picker.hide();
- this.picker.update().changeView(this.config.startView).render();
- }
+ state.orderedModifiers = orderedModifiers.filter(function (m) {
+ return m.enabled;
+ }); // Validate the provided modifiers so that the consumer will get warned
- /**
- * Destroy the Datepicker instance
- * @return {Detepicker} - the instance destroyed
- */
- destroy() {
- this.hide();
- unregisterListeners(this);
- this.picker.detach();
- if (!this.inline) {
- this.inputField.classList.remove('datepicker-input');
- }
- delete this.element.datepicker;
- return this;
- }
+ runModifierEffects();
+ return instance.update();
+ },
+ // Sync update – it will always be executed, even if not necessary. This
+ // is useful for low frequency updates where sync behavior simplifies the
+ // logic.
+ // For high frequency updates (e.g. `resize` and `scroll` events), always
+ // prefer the async Popper#update method
+ forceUpdate: function forceUpdate() {
+ if (isDestroyed) {
+ return;
+ }
- /**
- * Get the selected date(s)
- *
- * The method returns a Date object of selected date by default, and returns
- * an array of selected dates in multidate mode. If format string is passed,
- * it returns date string(s) formatted in given format.
- *
- * @param {String} [format] - Format string to stringify the date(s)
- * @return {Date|String|Date[]|String[]} - selected date(s), or if none is
- * selected, empty array in multidate mode and untitled in sigledate mode
- */
- getDate(format = undefined) {
- const callback = format
- ? date => formatDate(date, format, this.config.locale)
- : date => new Date(date);
+ var _state$elements = state.elements,
+ reference = _state$elements.reference,
+ popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements
+ // anymore
- if (this.config.multidate) {
- return this.dates.map(callback);
- }
- if (this.dates.length > 0) {
- return callback(this.dates[0]);
- }
- }
+ if (!areValidElements(reference, popper)) {
- /**
- * Set selected date(s)
- *
- * In multidate mode, you can pass multiple dates as a series of arguments
- * or an array. (Since each date is parsed individually, the type of the
- * dates doesn't have to be the same.)
- * The given dates are used to toggle the select status of each date. The
- * number of selected dates is kept from exceeding the length set to
- * maxNumberOfDates.
- *
- * With clear: true option, the method can be used to clear the selection
- * and to replace the selection instead of toggling in multidate mode.
- * If the option is passed with no date arguments or an empty dates array,
- * it works as "clear" (clear the selection then set nothing), and if the
- * option is passed with new dates to select, it works as "replace" (clear
- * the selection then set the given dates)
- *
- * When render: false option is used, the method omits re-rendering the
- * picker element. In this case, you need to call refresh() method later in
- * order for the picker element to reflect the changes. The input field is
- * refreshed always regardless of this option.
- *
- * When invalid (unparsable, repeated, disabled or out-of-range) dates are
- * passed, the method ignores them and applies only valid ones. In the case
- * that all the given dates are invalid, which is distinguished from passing
- * no dates, the method considers it as an error and leaves the selection
- * untouched.
- *
- * @param {...(Date|Number|String)|Array} [dates] - Date strings, Date
- * objects, time values or mix of those for new selection
- * @param {Object} [options] - function options
- * - clear: {boolean} - Whether to clear the existing selection
- * defualt: false
- * - render: {boolean} - Whether to re-render the picker element
- * default: true
- * - autohide: {boolean} - Whether to hide the picker element after re-render
- * Ignored when used with render: false
- * default: config.autohide
- */
- setDate(...args) {
- const dates = [...args];
- const opts = {};
- const lastArg = lastItemOf(args);
- if (
- typeof lastArg === 'object'
- && !Array.isArray(lastArg)
- && !(lastArg instanceof Date)
- && lastArg
- ) {
- Object.assign(opts, dates.pop());
- }
+ return;
+ } // Store the reference and popper rects to be read by modifiers
- const inputDates = Array.isArray(dates[0]) ? dates[0] : dates;
- setDate(this, inputDates, opts);
- }
- /**
- * Update the selected date(s) with input field's value
- * Not available on inline picker
- *
- * The input field will be refreshed with properly formatted date string.
- *
- * @param {Object} [options] - function options
- * - autohide: {boolean} - whether to hide the picker element after refresh
- * default: false
- */
- update(options = undefined) {
- if (this.inline) {
- return;
- }
+ state.rects = {
+ reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'),
+ popper: getLayoutRect(popper)
+ }; // Modifiers have the ability to reset the current update cycle. The
+ // most common use case for this is the `flip` modifier changing the
+ // placement, which then needs to re-run all the modifiers, because the
+ // logic was previously ran for the previous placement and is therefore
+ // stale/incorrect
- const opts = {clear: true, autohide: !!(options && options.autohide)};
- const inputDates = stringToArray(this.inputField.value, this.config.dateDelimiter);
- setDate(this, inputDates, opts);
- }
+ state.reset = false;
+ state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier
+ // is filled with the initial data specified by the modifier. This means
+ // it doesn't persist and is fresh on each update.
+ // To ensure persistent data, use `${name}#persistent`
- /**
- * Refresh the picker element and the associated input field
- * @param {String} [target] - target item when refreshing one item only
- * 'picker' or 'input'
- * @param {Boolean} [forceRender] - whether to re-render the picker element
- * regardless of its state instead of optimized refresh
- */
- refresh(target = undefined, forceRender = false) {
- if (target && typeof target !== 'string') {
- forceRender = target;
- target = undefined;
- }
+ state.orderedModifiers.forEach(function (modifier) {
+ return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);
+ });
- let mode;
- if (target === 'picker') {
- mode = 2;
- } else if (target === 'input') {
- mode = 1;
- } else {
- mode = 3;
- }
- refreshUI(this, mode, !forceRender);
- }
+ for (var index = 0; index < state.orderedModifiers.length; index++) {
- /**
- * Enter edit mode
- * Not available on inline picker or when the picker element is hidden
- */
- enterEditMode() {
- if (this.inline || !this.picker.active || this.editMode) {
- return;
- }
- this.editMode = true;
- this.inputField.classList.add('in-edit');
- }
+ if (state.reset === true) {
+ state.reset = false;
+ index = -1;
+ continue;
+ }
- /**
- * Exit from edit mode
- * Not available on inline picker
- * @param {Object} [options] - function options
- * - update: {boolean} - whether to call update() after exiting
- * If false, input field is revert to the existing selection
- * default: false
- */
- exitEditMode(options = undefined) {
- if (this.inline || !this.editMode) {
- return;
- }
- const opts = Object.assign({update: false}, options);
- delete this.editMode;
- this.inputField.classList.remove('in-edit');
- if (opts.update) {
- this.update(opts);
- }
- }
- }
+ var _state$orderedModifie = state.orderedModifiers[index],
+ fn = _state$orderedModifie.fn,
+ _state$orderedModifie2 = _state$orderedModifie.options,
+ _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,
+ name = _state$orderedModifie.name;
- /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- class Page extends HTMLElement {
- constructor() {
- super();
- this.submitActive = false;
- }
- /**
- * The Tobago root element
- */
- static page(element) {
- const rootNode = element.getRootNode();
- const pages = rootNode.querySelectorAll("tobago-page");
- if (pages.length > 0) {
- if (pages.length >= 2) {
- console.warn("Found more than one tobago-page element!");
- }
- return pages.item(0);
- }
- console.warn("Found no tobago page!");
- return null;
- }
- /**
- * "a:b" -> "a"
- * "a:b:c" -> "a:b"
- * "a" -> null
- * null -> null
- * "a:b::sub-component" -> "a"
- * "a::sub-component:b" -> "a::sub-component" // should currently not happen in Tobago
- *
- * @param clientId The clientId of a component.
- * @return The clientId of the naming container.
- */
- static getNamingContainerId(clientId) {
- if (clientId == null || clientId.lastIndexOf(":") === -1) {
- return null;
- }
- let id = clientId;
- while (true) {
- const sub = id.lastIndexOf("::");
- if (sub == -1) {
- break;
- }
- if (sub + 1 == id.lastIndexOf(":")) {
- id = id.substring(0, sub);
- }
- else {
- break;
- }
+ if (typeof fn === 'function') {
+ state = fn({
+ state: state,
+ options: _options,
+ name: name,
+ instance: instance
+ }) || state;
+ }
}
- return id.substring(0, id.lastIndexOf(":"));
- }
- connectedCallback() {
- this.registerAjaxListener();
- this.form.addEventListener("submit", this.beforeSubmit.bind(this));
- window.addEventListener("unload", this.beforeUnload.bind(this));
- this.addEventListener("keypress", (event) => {
- let code = event.which; // XXX deprecated
- if (code === 0) {
- code = event.keyCode;
- }
- if (code === 13) {
- const target = event.target;
- if (target.tagName === "A" || target.tagName === "BUTTON") {
- return;
- }
- if (target.tagName === "TEXTAREA") {
- if (!event.metaKey && !event.ctrlKey) {
- return;
- }
- }
- const name = target.getAttribute("name");
- let id = name ? name : target.id;
- while (id != null) {
- const command = document.querySelector(`[data-tobago-default='${id}']`);
- if (command) {
- command.dispatchEvent(new MouseEvent("click"));
- break;
- }
- id = Page.getNamingContainerId(id);
- }
- return false;
- }
+ },
+ // Async and optimistically optimized update – it will not be executed if
+ // not necessary (debounced to run at most once-per-tick)
+ update: debounce$1(function () {
+ return new Promise(function (resolve) {
+ instance.forceUpdate();
+ resolve(state);
});
+ }),
+ destroy: function destroy() {
+ cleanupModifierEffects();
+ isDestroyed = true;
+ }
+ };
+
+ if (!areValidElements(reference, popper)) {
+
+ return instance;
}
- beforeSubmit(event, decoupled = false) {
- this.submitActive = true;
- if (!decoupled) {
- this.body.insertAdjacentHTML("beforeend", `<tobago-overlay for='${this.id}'></tobago-overlay>`);
+
+ instance.setOptions(options).then(function (state) {
+ if (!isDestroyed && options.onFirstUpdate) {
+ options.onFirstUpdate(state);
+ }
+ }); // Modifiers have the ability to execute arbitrary code before the first
+ // update cycle runs. They will be executed in the same order as the update
+ // cycle. This is useful when a modifier adds some persistent data that
+ // other modifiers need to use, but the modifier is run after the dependent
+ // one.
+
+ function runModifierEffects() {
+ state.orderedModifiers.forEach(function (_ref3) {
+ var name = _ref3.name,
+ _ref3$options = _ref3.options,
+ options = _ref3$options === void 0 ? {} : _ref3$options,
+ effect = _ref3.effect;
+
+ if (typeof effect === 'function') {
+ var cleanupFn = effect({
+ state: state,
+ name: name,
+ instance: instance,
+ options: options
+ });
+
+ var noopFn = function noopFn() {};
+
+ effectCleanupFns.push(cleanupFn || noopFn);
}
- console.debug(this.body.querySelector("tobago-overlay"));
- }
- /**
- * Wrapper function to call application generated onunload function
- */
- beforeUnload() {
- console.debug("unload");
- // todo: here me may check, if user will loose its edit state on the page
+ });
}
- registerAjaxListener() {
- jsf.ajax.addOnEvent(this.jsfResponse.bind(this));
- }
- jsfResponse(event) {
- console.timeEnd("[tobago-jsf] jsf-ajax");
- console.time("[tobago-jsf] jsf-ajax");
- console.debug("[tobago-jsf] JSF event status: '%s'", event.status);
- if (event.status === "success") {
- event.responseXML.querySelectorAll("update").forEach(this.jsfResponseSuccess.bind(this));
- }
- else if (event.status === "complete") {
- event.responseXML.querySelectorAll("update").forEach(this.jsfResponseComplete.bind(this));
- }
- }
- jsfResponseSuccess(update) {
- const id = update.id;
- let rootNode = this.getRootNode();
- // XXX in case of "this" is tobago-page (e.g. ajax exception handling) rootNode is not set correctly???
- if (!rootNode.getElementById) {
- rootNode = document;
- }
- console.debug("[tobago-jsf] Update after jsf.ajax success: %s", id);
- }
- jsfResponseComplete(update) {
- const id = update.id;
- if (JsfParameter.isJsfId(id)) {
- console.debug("[tobago-jsf] Update after jsf.ajax complete: #", id);
- const overlay = this.querySelector(`tobago-overlay[for='${id}']`);
- if (overlay) {
- overlay.remove();
- }
- else {
- console.warn("Didn't found overlay for id", id);
- }
- }
- }
- get form() {
- return this.querySelector("form");
- }
- get body() {
- return this.closest("body");
- }
- get locale() {
- let locale = this.getAttribute("locale");
- if (!locale) {
- locale = document.documentElement.lang;
- }
- return locale;
+
+ function cleanupModifierEffects() {
+ effectCleanupFns.forEach(function (fn) {
+ return fn();
+ });
+ effectCleanupFns = [];
}
+
+ return instance;
+ };
}
- document.addEventListener("tobago.init", (event) => {
- if (window.customElements.get("tobago-page") == null) {
- window.customElements.define("tobago-page", Page);
- }
+ var createPopper$2 = /*#__PURE__*/popperGenerator(); // eslint-disable-next-line import/no-unused-modules
+
+ var defaultModifiers$1 = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1];
+ var createPopper$1 = /*#__PURE__*/popperGenerator({
+ defaultModifiers: defaultModifiers$1
+ }); // eslint-disable-next-line import/no-unused-modules
+
+ var defaultModifiers = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1, offset$1, flip$1, preventOverflow$1, arrow$1, hide$1];
+ var createPopper = /*#__PURE__*/popperGenerator({
+ defaultModifiers: defaultModifiers
+ }); // eslint-disable-next-line import/no-unused-modules
+
+ var Popper = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ popperGenerator: popperGenerator,
+ detectOverflow: detectOverflow,
+ createPopperBase: createPopper$2,
+ createPopper: createPopper,
+ createPopperLite: createPopper$1,
+ top: top,
+ bottom: bottom,
+ right: right,
+ left: left,
+ auto: auto,
+ basePlacements: basePlacements,
+ start: start,
+ end: end,
+ clippingParents: clippingParents,
+ viewport: viewport,
+ popper: popper,
+ reference: reference,
+ variationPlacements: variationPlacements,
+ placements: placements,
+ beforeRead: beforeRead,
+ read: read,
+ afterRead: afterRead,
+ beforeMain: beforeMain,
+ main: main,
+ afterMain: afterMain,
+ beforeWrite: beforeWrite,
+ write: write,
+ afterWrite: afterWrite,
+ modifierPhases: modifierPhases,
+ applyStyles: applyStyles$1,
+ arrow: arrow$1,
+ computeStyles: computeStyles$1,
+ eventListeners: eventListeners,
+ flip: flip$1,
+ hide: hide$1,
+ offset: offset$1,
+ popperOffsets: popperOffsets$1,
+ preventOverflow: preventOverflow$1
});
- class JsfParameter {
- static isJsfId(id) {
- switch (id) {
- case JsfParameter.VIEW_STATE:
- case JsfParameter.CLIENT_WINDOW:
- case JsfParameter.VIEW_ROOT:
- case JsfParameter.VIEW_HEAD:
- case JsfParameter.VIEW_BODY:
- case JsfParameter.RESOURCE:
- return false;
- default:
- return true;
- }
- }
- static isJsfBody(id) {
- switch (id) {
- case JsfParameter.VIEW_ROOT:
- case JsfParameter.VIEW_BODY:
- return true;
- default:
- return false;
- }
- }
- }
- JsfParameter.VIEW_STATE = "javax.faces.ViewState";
- JsfParameter.CLIENT_WINDOW = "javax.faces.ClientWindow";
- JsfParameter.VIEW_ROOT = "javax.faces.ViewRoot";
- JsfParameter.VIEW_HEAD = "javax.faces.ViewHead";
- JsfParameter.VIEW_BODY = "javax.faces.ViewBody";
- JsfParameter.RESOURCE = "javax.faces.Resource";
- /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ /*!
+ * Bootstrap v5.0.2 (https://getbootstrap.com/)
+ * Copyright 2011-2021 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
+ */
+
+ /**
+ * --------------------------------------------------------------------------
+ * Bootstrap (v5.0.2): dom/selector-engine.js
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
+ * --------------------------------------------------------------------------
*/
- class DatePicker extends HTMLElement {
- constructor() {
- super();
+
+ /**
+ * ------------------------------------------------------------------------
+ * Constants
+ * ------------------------------------------------------------------------
+ */
+ const NODE_TEXT = 3;
+ const SelectorEngine = {
+ find(selector, element = document.documentElement) {
+ return [].concat(...Element.prototype.querySelectorAll.call(element, selector));
+ },
+
+ findOne(selector, element = document.documentElement) {
+ return Element.prototype.querySelector.call(element, selector);
+ },
+
+ children(element, selector) {
+ return [].concat(...element.children).filter(child => child.matches(selector));
+ },
+
+ parents(element, selector) {
+ const parents = [];
+ let ancestor = element.parentNode;
+
+ while (ancestor && ancestor.nodeType === Node.ELEMENT_NODE && ancestor.nodeType !== NODE_TEXT) {
+ if (ancestor.matches(selector)) {
+ parents.push(ancestor);
+ }
+
+ ancestor = ancestor.parentNode;
}
- connectedCallback() {
- if (this.type == "date") {
- console.debug("check input type=date support", DatePicker.SUPPORTS_INPUT_TYPE_DATE);
- if (!DatePicker.SUPPORTS_INPUT_TYPE_DATE) {
- this.setAttribute("type", "text");
- this.initVanillaDatePicker();
- }
- }
+
+ return parents;
+ },
+
+ prev(element, selector) {
+ let previous = element.previousElementSibling;
+
+ while (previous) {
+ if (previous.matches(selector)) {
+ return [previous];
+ }
+
+ previous = previous.previousElementSibling;
}
- initVanillaDatePicker() {
- var _a;
- const field = this.field;
- const locale = Page.page(this).locale;
- const i18n = this.i18n;
- i18n.titleFormat = "MM y"; // todo i18n
- i18n.format = this.pattern;
- Datepicker.locales[locale] = i18n;
- const options = {
- buttonClass: "btn",
- orientation: "auto",
- autohide: true,
- language: locale,
- todayBtn: this.todayButton,
- todayBtnMode: 1,
- minDate: this.min,
- maxDate: this.max,
- // todo readonly
- // todo show week numbers
- };
- const datepicker = new Datepicker(field, options);
- // XXX these listeners are needed as long as we have a solution for:
- // XXX https://github.com/mymth/vanillajs-datepicker/issues/13
- // XXX the 2nd point is missing the "normal" change event on the input element
- field.addEventListener("keyup", (event) => {
- // console.info("event -----> ", event.type);
- if (event.metaKey || event.key.length > 1 && event.key !== "Backspace" && event.key !== "Delete") {
- return;
- }
- // back up user's input when user types printable character or backspace/delete
- const target = event.target;
- target._oldValue = target.value;
- });
- field.addEventListener("focus", (event) => {
- // console.info("event -----> ", event.type);
- this.lastValue = field.value;
- });
- field.addEventListener("blur", (event) => {
- // console.info("event -----> ", event.type);
- const target = event.target;
- // no-op when user goes to another window or the input field has no backed-up value
- if (document.hasFocus() && target._oldValue !== undefined) {
- if (target._oldValue !== target.value) {
- target.datepicker.setDate(target._oldValue || { clear: true });
- }
- delete target._oldValue;
- }
- if (this.lastValue !== field.value) {
- field.dispatchEvent(new Event("change"));
- }
- });
- datepicker.element.addEventListener("changeDate", (event) => {
- // console.info("event -----> ", event.type);
- field.dispatchEvent(new Event("change"));
- });
- // simple solution for the picker: currently only open, not close is implemented
- (_a = this.querySelector(".tobago-date-picker")) === null || _a === void 0 ? void 0 : _a.addEventListener("click", (event) => {
- this.field.focus();
- });
- }
- get todayButton() {
- return this.hasAttribute("today-button");
- }
- set todayButton(todayButton) {
- if (todayButton) {
- this.setAttribute("today-button", "");
- }
- else {
- this.removeAttribute("today-button");
- }
- }
- get type() {
- var _a;
- return (_a = this.field) === null || _a === void 0 ? void 0 : _a.getAttribute("type");
- }
- get min() {
- var _a;
- return (_a = this.field) === null || _a === void 0 ? void 0 : _a.getAttribute("min");
- }
- get max() {
- var _a;
- return (_a = this.field) === null || _a === void 0 ? void 0 : _a.getAttribute("max");
- }
- get pattern() {
- let pattern = this.getAttribute("pattern");
- return pattern ? pattern : "yyyy-mm-dd";
- }
- get i18n() {
- const i18n = this.getAttribute("i18n");
- return i18n ? JSON.parse(i18n) : undefined;
- }
- get field() {
- const rootNode = this.getRootNode();
- return rootNode.getElementById(this.id + "::field");
- }
- }
- DatePicker.SUPPORTS_INPUT_TYPE_DATE = (() => {
- const input = document.createElement("input");
- input.setAttribute("type", "date");
- const thisIsNoDate = "this is not a date";
- input.setAttribute("value", thisIsNoDate);
- return input.value !== thisIsNoDate;
- })();
- document.addEventListener("tobago.init", function (event) {
- if (window.customElements.get("tobago-date") == null) {
- window.customElements.define("tobago-date", DatePicker);
- }
- });
-
- var top = 'top';
- var bottom = 'bottom';
- var right = 'right';
- var left = 'left';
- var auto = 'auto';
- var basePlacements = [top, bottom, right, left];
- var start = 'start';
- var end = 'end';
- var clippingParents = 'clippingParents';
- var viewport = 'viewport';
- var popper = 'popper';
- var reference = 'reference';
- var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {
- return acc.concat([placement + "-" + start, placement + "-" + end]);
- }, []);
- var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) {
- return acc.concat([placement, placement + "-" + start, placement + "-" + end]);
- }, []); // modifiers that need to read the DOM
-
- var beforeRead = 'beforeRead';
- var read = 'read';
- var afterRead = 'afterRead'; // pure-logic modifiers
- var beforeMain = 'beforeMain';
- var main = 'main';
- var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)
+ return [];
+ },
- var beforeWrite = 'beforeWrite';
- var write = 'write';
- var afterWrite = 'afterWrite';
- var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];
+ next(element, selector) {
+ let next = element.nextElementSibling;
- function getNodeName(element) {
- return element ? (element.nodeName || '').toLowerCase() : null;
- }
+ while (next) {
+ if (next.matches(selector)) {
+ return [next];
+ }
- function getWindow(node) {
- if (node == null) {
- return window;
- }
+ next = next.nextElementSibling;
+ }
- if (node.toString() !== '[object Window]') {
- var ownerDocument = node.ownerDocument;
- return ownerDocument ? ownerDocument.defaultView || window : window;
+ return [];
}
- return node;
- }
+ };
- function isElement$1(node) {
- var OwnElement = getWindow(node).Element;
- return node instanceof OwnElement || node instanceof Element;
- }
+ /**
+ * --------------------------------------------------------------------------
+ * Bootstrap (v5.0.2): util/index.js
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
+ * --------------------------------------------------------------------------
+ */
- function isHTMLElement(node) {
- var OwnElement = getWindow(node).HTMLElement;
- return node instanceof OwnElement || node instanceof HTMLElement;
- }
+ const MAX_UID = 1000000;
+ const MILLISECONDS_MULTIPLIER = 1000;
+ const TRANSITION_END = 'transitionend'; // Shoutout AngusCroll (https://goo.gl/pxwQGp)
- function isShadowRoot(node) {
- // IE 11 has no ShadowRoot
- if (typeof ShadowRoot === 'undefined') {
- return false;
+ const toType = obj => {
+ if (obj === null || obj === undefined) {
+ return `${obj}`;
}
- var OwnElement = getWindow(node).ShadowRoot;
- return node instanceof OwnElement || node instanceof ShadowRoot;
- }
+ return {}.toString.call(obj).match(/\s([a-z]+)/i)[1].toLowerCase();
+ };
+ /**
+ * --------------------------------------------------------------------------
+ * Public Util Api
+ * --------------------------------------------------------------------------
+ */
- // and applies them to the HTMLElements such as popper and arrow
- function applyStyles(_ref) {
- var state = _ref.state;
- Object.keys(state.elements).forEach(function (name) {
- var style = state.styles[name] || {};
- var attributes = state.attributes[name] || {};
- var element = state.elements[name]; // arrow is optional + virtual elements
+ const getUID = prefix => {
+ do {
+ prefix += Math.floor(Math.random() * MAX_UID);
+ } while (document.getElementById(prefix));
- if (!isHTMLElement(element) || !getNodeName(element)) {
- return;
- } // Flow doesn't support to extend this property, but it's the most
- // effective way to apply styles to an HTMLElement
- // $FlowFixMe[cannot-write]
+ return prefix;
+ };
+ const getSelector = element => {
+ let selector = element.getAttribute('data-bs-target');
- Object.assign(element.style, style);
- Object.keys(attributes).forEach(function (name) {
- var value = attributes[name];
+ if (!selector || selector === '#') {
+ let hrefAttr = element.getAttribute('href'); // The only valid content that could double as a selector are IDs or classes,
+ // so everything starting with `#` or `.`. If a "real" URL is used as the selector,
+ // `document.querySelector` will rightfully complain it is invalid.
+ // See https://github.com/twbs/bootstrap/issues/32273
- if (value === false) {
- element.removeAttribute(name);
- } else {
- element.setAttribute(name, value === true ? '' : value);
- }
- });
- });
- }
+ if (!hrefAttr || !hrefAttr.includes('#') && !hrefAttr.startsWith('.')) {
+ return null;
+ } // Just in case some CMS puts out a full URL with the anchor appended
- function effect$2(_ref2) {
- var state = _ref2.state;
- var initialStyles = {
- popper: {
- position: state.options.strategy,
- left: '0',
- top: '0',
- margin: '0'
- },
- arrow: {
- position: 'absolute'
- },
- reference: {}
- };
- Object.assign(state.elements.popper.style, initialStyles.popper);
- state.styles = initialStyles;
- if (state.elements.arrow) {
- Object.assign(state.elements.arrow.style, initialStyles.arrow);
+ if (hrefAttr.includes('#') && !hrefAttr.startsWith('#')) {
+ hrefAttr = `#${hrefAttr.split('#')[1]}`;
+ }
+
+ selector = hrefAttr && hrefAttr !== '#' ? hrefAttr.trim() : null;
}
- return function () {
- Object.keys(state.elements).forEach(function (name) {
- var element = state.elements[name];
- var attributes = state.attributes[name] || {};
- var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them
+ return selector;
+ };
- var style = styleProperties.reduce(function (style, property) {
- style[property] = '';
- return style;
- }, {}); // arrow is optional + virtual elements
+ const getSelectorFromElement = element => {
+ const selector = getSelector(element);
- if (!isHTMLElement(element) || !getNodeName(element)) {
- return;
- }
+ if (selector) {
+ return document.querySelector(selector) ? selector : null;
+ }
- Object.assign(element.style, style);
- Object.keys(attributes).forEach(function (attribute) {
- element.removeAttribute(attribute);
- });
- });
- };
- } // eslint-disable-next-line import/no-unused-modules
+ return null;
+ };
+ const getElementFromSelector = element => {
+ const selector = getSelector(element);
+ return selector ? document.querySelector(selector) : null;
+ };
- var applyStyles$1 = {
- name: 'applyStyles',
- enabled: true,
- phase: 'write',
- fn: applyStyles,
- effect: effect$2,
- requires: ['computeStyles']
- };
+ const getTransitionDurationFromElement = element => {
+ if (!element) {
+ return 0;
+ } // Get transition-duration of the element
- function getBasePlacement(placement) {
- return placement.split('-')[0];
- }
- function getBoundingClientRect(element) {
- var rect = element.getBoundingClientRect();
- return {
- width: rect.width,
- height: rect.height,
- top: rect.top,
- right: rect.right,
- bottom: rect.bottom,
- left: rect.left,
- x: rect.left,
- y: rect.top
- };
- }
+ let {
+ transitionDuration,
+ transitionDelay
+ } = window.getComputedStyle(element);
+ const floatTransitionDuration = Number.parseFloat(transitionDuration);
+ const floatTransitionDelay = Number.parseFloat(transitionDelay); // Return 0 if element or transition duration is not found
- // means it doesn't take into account transforms.
+ if (!floatTransitionDuration && !floatTransitionDelay) {
+ return 0;
+ } // If multiple durations are defined, take the first
- function getLayoutRect(element) {
- var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed.
- // Fixes https://github.com/popperjs/popper-core/issues/1223
- var width = element.offsetWidth;
- var height = element.offsetHeight;
+ transitionDuration = transitionDuration.split(',')[0];
+ transitionDelay = transitionDelay.split(',')[0];
+ return (Number.parseFloat(transitionDuration) + Number.parseFloat(transitionDelay)) * MILLISECONDS_MULTIPLIER;
+ };
- if (Math.abs(clientRect.width - width) <= 1) {
- width = clientRect.width;
+ const triggerTransitionEnd = element => {
+ element.dispatchEvent(new Event(TRANSITION_END));
+ };
+
+ const isElement = obj => {
+ if (!obj || typeof obj !== 'object') {
+ return false;
}
- if (Math.abs(clientRect.height - height) <= 1) {
- height = clientRect.height;
+ if (typeof obj.jquery !== 'undefined') {
+ obj = obj[0];
}
- return {
- x: element.offsetLeft,
- y: element.offsetTop,
- width: width,
- height: height
- };
- }
+ return typeof obj.nodeType !== 'undefined';
+ };
- function contains(parent, child) {
- var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method
+ const getElement = obj => {
+ if (isElement(obj)) {
+ // it's a jQuery object or a node element
+ return obj.jquery ? obj[0] : obj;
+ }
- if (parent.contains(child)) {
- return true;
- } // then fallback to custom implementation with Shadow DOM support
- else if (rootNode && isShadowRoot(rootNode)) {
- var next = child;
+ if (typeof obj === 'string' && obj.length > 0) {
+ return SelectorEngine.findOne(obj);
+ }
- do {
- if (next && parent.isSameNode(next)) {
- return true;
- } // $FlowFixMe[prop-missing]: need a better way to handle this...
+ return null;
+ };
+ const typeCheckConfig = (componentName, config, configTypes) => {
+ Object.keys(configTypes).forEach(property => {
+ const expectedTypes = configTypes[property];
+ const value = config[property];
+ const valueType = value && isElement(value) ? 'element' : toType(value);
- next = next.parentNode || next.host;
- } while (next);
- } // Give up, the result is false
+ if (!new RegExp(expectedTypes).test(valueType)) {
+ throw new TypeError(`${componentName.toUpperCase()}: Option "${property}" provided type "${valueType}" but expected type "${expectedTypes}".`);
+ }
+ });
+ };
+ const isVisible = element => {
+ if (!isElement(element) || element.getClientRects().length === 0) {
+ return false;
+ }
- return false;
- }
+ return getComputedStyle(element).getPropertyValue('visibility') === 'visible';
+ };
- function getComputedStyle$1(element) {
- return getWindow(element).getComputedStyle(element);
- }
+ const isDisabled = element => {
+ if (!element || element.nodeType !== Node.ELEMENT_NODE) {
+ return true;
+ }
- function isTableElement(element) {
- return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;
- }
+ if (element.classList.contains('disabled')) {
+ return true;
+ }
- function getDocumentElement(element) {
- // $FlowFixMe[incompatible-return]: assume body is always available
- return ((isElement$1(element) ? element.ownerDocument : // $FlowFixMe[prop-missing]
- element.document) || window.document).documentElement;
- }
+ if (typeof element.disabled !== 'undefined') {
+ return element.disabled;
+ }
- function getParentNode(element) {
- if (getNodeName(element) === 'html') {
- return element;
+ return element.hasAttribute('disabled') && element.getAttribute('disabled') !== 'false';
+ };
+
+ const findShadowRoot = element => {
+ if (!document.documentElement.attachShadow) {
+ return null;
+ } // Can find the shadow root otherwise it'll return the document
+
+
+ if (typeof element.getRootNode === 'function') {
+ const root = element.getRootNode();
+ return root instanceof ShadowRoot ? root : null;
}
- return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle
- // $FlowFixMe[incompatible-return]
- // $FlowFixMe[prop-missing]
- element.assignedSlot || // step into the shadow DOM of the parent of a slotted node
- element.parentNode || ( // DOM Element detected
- isShadowRoot(element) ? element.host : null) || // ShadowRoot detected
- // $FlowFixMe[incompatible-call]: HTMLElement is a Node
- getDocumentElement(element) // fallback
+ if (element instanceof ShadowRoot) {
+ return element;
+ } // when we don't find a shadow root
- );
- }
- function getTrueOffsetParent(element) {
- if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837
- getComputedStyle$1(element).position === 'fixed') {
+ if (!element.parentNode) {
return null;
}
- return element.offsetParent;
- } // `.offsetParent` reports `null` for fixed elements, while absolute elements
- // return the containing block
+ return findShadowRoot(element.parentNode);
+ };
+ const noop = () => {};
- function getContainingBlock(element) {
- var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') !== -1;
- var isIE = navigator.userAgent.indexOf('Trident') !== -1;
+ const reflow = element => element.offsetHeight;
- if (isIE && isHTMLElement(element)) {
- // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport
- var elementCss = getComputedStyle$1(element);
+ const getjQuery = () => {
+ const {
+ jQuery
+ } = window;
- if (elementCss.position === 'fixed') {
- return null;
- }
+ if (jQuery && !document.body.hasAttribute('data-bs-no-jquery')) {
+ return jQuery;
}
- var currentNode = getParentNode(element);
+ return null;
+ };
- while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) {
- var css = getComputedStyle$1(currentNode); // This is non-exhaustive but covers the most common CSS properties that
- // create a containing block.
- // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
+ const DOMContentLoadedCallbacks = [];
- if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') {
- return currentNode;
- } else {
- currentNode = currentNode.parentNode;
+ const onDOMContentLoaded = callback => {
+ if (document.readyState === 'loading') {
+ // add listener on the first call when the document is in loading state
+ if (!DOMContentLoadedCallbacks.length) {
+ document.addEventListener('DOMContentLoaded', () => {
+ DOMContentLoadedCallbacks.forEach(callback => callback());
+ });
}
+
+ DOMContentLoadedCallbacks.push(callback);
+ } else {
+ callback();
}
+ };
- return null;
- } // Gets the closest ancestor positioned element. Handles some edge cases,
- // such as table ancestors and cross browser bugs.
+ const isRTL = () => document.documentElement.dir === 'rtl';
+ const defineJQueryPlugin = plugin => {
+ onDOMContentLoaded(() => {
+ const $ = getjQuery();
+ /* istanbul ignore if */
- function getOffsetParent(element) {
- var window = getWindow(element);
- var offsetParent = getTrueOffsetParent(element);
+ if ($) {
+ const name = plugin.NAME;
+ const JQUERY_NO_CONFLICT = $.fn[name];
+ $.fn[name] = plugin.jQueryInterface;
+ $.fn[name].Constructor = plugin;
- while (offsetParent && isTableElement(offsetParent) && getComputedStyle$1(offsetParent).position === 'static') {
- offsetParent = getTrueOffsetParent(offsetParent);
- }
+ $.fn[name].noConflict = () => {
+ $.fn[name] = JQUERY_NO_CONFLICT;
+ return plugin.jQueryInterface;
+ };
+ }
+ });
+ };
- if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle$1(offsetParent).position === 'static')) {
- return window;
+ const execute = callback => {
+ if (typeof callback === 'function') {
+ callback();
}
+ };
- return offsetParent || getContainingBlock(element) || window;
- }
+ const executeAfterTransition = (callback, transitionElement, waitForTransition = true) => {
+ if (!waitForTransition) {
+ execute(callback);
+ return;
+ }
- function getMainAxisFromPlacement(placement) {
- return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y';
- }
+ const durationPadding = 5;
+ const emulatedDuration = getTransitionDurationFromElement(transitionElement) + durationPadding;
+ let called = false;
- var max = Math.max;
- var min = Math.min;
- var round = Math.round;
-
- function within(min$1, value, max$1) {
- return max(min$1, min(value, max$1));
- }
+ const handler = ({
+ target
+ }) => {
+ if (target !== transitionElement) {
+ return;
+ }
- function getFreshSideObject() {
- return {
- top: 0,
- right: 0,
- bottom: 0,
- left: 0
+ called = true;
+ transitionElement.removeEventListener(TRANSITION_END, handler);
+ execute(callback);
};
- }
- function mergePaddingObject(paddingObject) {
- return Object.assign({}, getFreshSideObject(), paddingObject);
- }
+ transitionElement.addEventListener(TRANSITION_END, handler);
+ setTimeout(() => {
+ if (!called) {
+ triggerTransitionEnd(transitionElement);
+ }
+ }, emulatedDuration);
+ };
+ /**
+ * Return the previous/next element of a list.
+ *
+ * @param {array} list The list of elements
+ * @param activeElement The active element
+ * @param shouldGetNext Choose to get next or previous element
+ * @param isCycleAllowed
+ * @return {Element|elem} The proper element
+ */
- function expandToHashMap(value, keys) {
- return keys.reduce(function (hashMap, key) {
- hashMap[key] = value;
- return hashMap;
- }, {});
- }
- var toPaddingObject = function toPaddingObject(padding, state) {
- padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, {
- placement: state.placement
- })) : padding;
- return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
- };
+ const getNextActiveElement = (list, activeElement, shouldGetNext, isCycleAllowed) => {
+ let index = list.indexOf(activeElement); // if the element does not exist in the list return an element depending on the direction and if cycle is allowed
- function arrow(_ref) {
- var _state$modifiersData$;
+ if (index === -1) {
+ return list[!shouldGetNext && isCycleAllowed ? list.length - 1 : 0];
+ }
- var state = _ref.state,
- name = _ref.name,
- options = _ref.options;
- var arrowElement = state.elements.arrow;
- var popperOffsets = state.modifiersData.popperOffsets;
- var basePlacement = getBasePlacement(state.placement);
- var axis = getMainAxisFromPlacement(basePlacement);
- var isVertical = [left, right].indexOf(basePlacement) >= 0;
- var len = isVertical ? 'height' : 'width';
+ const listLength = list.length;
+ index += shouldGetNext ? 1 : -1;
- if (!arrowElement || !popperOffsets) {
- return;
+ if (isCycleAllowed) {
+ index = (index + listLength) % listLength;
}
- var paddingObject = toPaddingObject(options.padding, state);
- var arrowRect = getLayoutRect(arrowElement);
- var minProp = axis === 'y' ? top : left;
- var maxProp = axis === 'y' ? bottom : right;
- var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];
- var startDiff = popperOffsets[axis] - state.rects.reference[axis];
- var arrowOffsetParent = getOffsetParent(arrowElement);
- var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
- var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is
- // outside of the popper bounds
+ return list[Math.max(0, Math.min(index, listLength - 1))];
+ };
- var min = paddingObject[minProp];
- var max = clientSize - arrowRect[len] - paddingObject[maxProp];
- var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;
- var offset = within(min, center, max); // Prevents breaking syntax highlighting...
+ /**
+ * --------------------------------------------------------------------------
+ * Bootstrap (v5.0.2): dom/event-handler.js
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
+ * --------------------------------------------------------------------------
+ */
+ /**
+ * ------------------------------------------------------------------------
+ * Constants
+ * ------------------------------------------------------------------------
+ */
- var axisProp = axis;
- state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);
- }
+ const namespaceRegex = /[^.]*(?=\..*)\.|.*/;
+ const stripNameRegex = /\..*/;
+ const stripUidRegex = /::\d+$/;
+ const eventRegistry = {}; // Events storage
- function effect$1(_ref2) {
- var state = _ref2.state,
- options = _ref2.options;
- var _options$element = options.element,
- arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element;
+ let uidEvent = 1;
+ const customEvents = {
+ mouseenter: 'mouseover',
+ mouseleave: 'mouseout'
+ };
+ const customEventsRegex = /^(mouseenter|mouseleave)/i;
+ const nativeEvents = new Set(['click', 'dblclick', 'mouseup', 'mousedown', 'contextmenu', 'mousewheel', 'DOMMouseScroll', 'mouseover', 'mouseout', 'mousemove', 'selectstart', 'selectend', 'keydown', 'keypress', 'keyup', 'orientationchange', 'touchstart', 'touchmove', 'touchend', 'touchcancel', 'pointerdown', 'pointermove', 'pointerup', 'pointerleave', 'pointercancel', 'gesturestart', 'gesturechange', 'gestureend', 'focus', 'blur', 'change', 'reset', 'select', 'submit', 'focusin', 'focu [...]
+ /**
+ * ------------------------------------------------------------------------
+ * Private methods
+ * ------------------------------------------------------------------------
+ */
- if (arrowElement == null) {
- return;
- } // CSS selector
+ function getUidEvent(element, uid) {
+ return uid && `${uid}::${uidEvent++}` || element.uidEvent || uidEvent++;
+ }
+ function getEvent(element) {
+ const uid = getUidEvent(element);
+ element.uidEvent = uid;
+ eventRegistry[uid] = eventRegistry[uid] || {};
+ return eventRegistry[uid];
+ }
- if (typeof arrowElement === 'string') {
- arrowElement = state.elements.popper.querySelector(arrowElement);
+ function bootstrapHandler(element, fn) {
+ return function handler(event) {
+ event.delegateTarget = element;
- if (!arrowElement) {
- return;
+ if (handler.oneOff) {
+ EventHandler.off(element, event.type, fn);
}
- }
- if (!contains(state.elements.popper, arrowElement)) {
+ return fn.apply(element, [event]);
+ };
+ }
- return;
- }
+ function bootstrapDelegationHandler(element, selector, fn) {
+ return function handler(event) {
+ const domElements = element.querySelectorAll(selector);
- state.elements.arrow = arrowElement;
- } // eslint-disable-next-line import/no-unused-modules
+ for (let {
+ target
+ } = event; target && target !== this; target = target.parentNode) {
+ for (let i = domElements.length; i--;) {
+ if (domElements[i] === target) {
+ event.delegateTarget = target;
+ if (handler.oneOff) {
+ // eslint-disable-next-line unicorn/consistent-destructuring
+ EventHandler.off(element, event.type, selector, fn);
+ }
- var arrow$1 = {
- name: 'arrow',
- enabled: true,
- phase: 'main',
- fn: arrow,
- effect: effect$1,
- requires: ['popperOffsets'],
- requiresIfExists: ['preventOverflow']
- };
+ return fn.apply(target, [event]);
+ }
+ }
+ } // To please ESLint
- var unsetSides = {
- top: 'auto',
- right: 'auto',
- bottom: 'auto',
- left: 'auto'
- }; // Round the offsets to the nearest suitable subpixel based on the DPR.
- // Zooming can change the DPR, but it seems to report a value that will
- // cleanly divide the values into the appropriate subpixels.
- function roundOffsetsByDPR(_ref) {
- var x = _ref.x,
- y = _ref.y;
- var win = window;
- var dpr = win.devicePixelRatio || 1;
- return {
- x: round(round(x * dpr) / dpr) || 0,
- y: round(round(y * dpr) / dpr) || 0
+ return null;
};
}
- function mapToStyles(_ref2) {
- var _Object$assign2;
-
- var popper = _ref2.popper,
- popperRect = _ref2.popperRect,
- placement = _ref2.placement,
- offsets = _ref2.offsets,
- position = _ref2.position,
- gpuAcceleration = _ref2.gpuAcceleration,
- adaptive = _ref2.adaptive,
- roundOffsets = _ref2.roundOffsets;
+ function findHandler(events, handler, delegationSelector = null) {
+ const uidEventList = Object.keys(events);
- var _ref3 = roundOffsets === true ? roundOffsetsByDPR(offsets) : typeof roundOffsets === 'function' ? roundOffsets(offsets) : offsets,
- _ref3$x = _ref3.x,
- x = _ref3$x === void 0 ? 0 : _ref3$x,
- _ref3$y = _ref3.y,
- y = _ref3$y === void 0 ? 0 : _ref3$y;
+ for (let i = 0, len = uidEventList.length; i < len; i++) {
+ const event = events[uidEventList[i]];
- var hasX = offsets.hasOwnProperty('x');
- var hasY = offsets.hasOwnProperty('y');
- var sideX = left;
- var sideY = top;
- var win = window;
+ if (event.originalHandler === handler && event.delegationSelector === delegationSelector) {
+ return event;
+ }
+ }
- if (adaptive) {
- var offsetParent = getOffsetParent(popper);
- var heightProp = 'clientHeight';
- var widthProp = 'clientWidth';
+ return null;
+ }
- if (offsetParent === getWindow(popper)) {
- offsetParent = getDocumentElement(popper);
+ function normalizeParams(originalTypeEvent, handler, delegationFn) {
+ const delegation = typeof handler === 'string';
+ const originalHandler = delegation ? delegationFn : handler;
+ let typeEvent = getTypeEvent(originalTypeEvent);
+ const isNative = nativeEvents.has(typeEvent);
- if (getComputedStyle$1(offsetParent).position !== 'static') {
- heightProp = 'scrollHeight';
- widthProp = 'scrollWidth';
- }
- } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it
+ if (!isNative) {
+ typeEvent = originalTypeEvent;
+ }
+ return [delegation, originalHandler, typeEvent];
+ }
- offsetParent = offsetParent;
+ function addHandler(element, originalTypeEvent, handler, delegationFn, oneOff) {
+ if (typeof originalTypeEvent !== 'string' || !element) {
+ return;
+ }
- if (placement === top) {
- sideY = bottom; // $FlowFixMe[prop-missing]
+ if (!handler) {
+ handler = delegationFn;
+ delegationFn = null;
+ } // in case of mouseenter or mouseleave wrap the handler within a function that checks for its DOM position
+ // this prevents the handler from being dispatched the same way as mouseover or mouseout does
- y -= offsetParent[heightProp] - popperRect.height;
- y *= gpuAcceleration ? 1 : -1;
- }
- if (placement === left) {
- sideX = right; // $FlowFixMe[prop-missing]
+ if (customEventsRegex.test(originalTypeEvent)) {
+ const wrapFn = fn => {
+ return function (event) {
+ if (!event.relatedTarget || event.relatedTarget !== event.delegateTarget && !event.delegateTarget.contains(event.relatedTarget)) {
+ return fn.call(this, event);
+ }
+ };
+ };
- x -= offsetParent[widthProp] - popperRect.width;
- x *= gpuAcceleration ? 1 : -1;
+ if (delegationFn) {
+ delegationFn = wrapFn(delegationFn);
+ } else {
+ handler = wrapFn(handler);
}
}
- var commonStyles = Object.assign({
- position: position
- }, adaptive && unsetSides);
-
- if (gpuAcceleration) {
- var _Object$assign;
+ const [delegation, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn);
+ const events = getEvent(element);
+ const handlers = events[typeEvent] || (events[typeEvent] = {});
+ const previousFn = findHandler(handlers, originalHandler, delegation ? handler : null);
- return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) < 2 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign));
+ if (previousFn) {
+ previousFn.oneOff = previousFn.oneOff && oneOff;
+ return;
}
- return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : '', _Object$assign2[sideX] = hasX ? x + "px" : '', _Object$assign2.transform = '', _Object$assign2));
+ const uid = getUidEvent(originalHandler, originalTypeEvent.replace(namespaceRegex, ''));
+ const fn = delegation ? bootstrapDelegationHandler(element, handler, delegationFn) : bootstrapHandler(element, handler);
+ fn.delegationSelector = delegation ? handler : null;
+ fn.originalHandler = originalHandler;
+ fn.oneOff = oneOff;
+ fn.uidEvent = uid;
+ handlers[uid] = fn;
+ element.addEventListener(typeEvent, fn, delegation);
}
- function computeStyles(_ref4) {
- var state = _ref4.state,
- options = _ref4.options;
- var _options$gpuAccelerat = options.gpuAcceleration,
- gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,
- _options$adaptive = options.adaptive,
- adaptive = _options$adaptive === void 0 ? true : _options$adaptive,
- _options$roundOffsets = options.roundOffsets,
- roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;
-
- var commonStyles = {
- placement: getBasePlacement(state.placement),
- popper: state.elements.popper,
- popperRect: state.rects.popper,
- gpuAcceleration: gpuAcceleration
- };
+ function removeHandler(element, events, typeEvent, handler, delegationSelector) {
+ const fn = findHandler(events[typeEvent], handler, delegationSelector);
- if (state.modifiersData.popperOffsets != null) {
- state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {
- offsets: state.modifiersData.popperOffsets,
- position: state.options.strategy,
- adaptive: adaptive,
- roundOffsets: roundOffsets
- })));
+ if (!fn) {
+ return;
}
- if (state.modifiersData.arrow != null) {
- state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {
- offsets: state.modifiersData.arrow,
- position: 'absolute',
- adaptive: false,
- roundOffsets: roundOffsets
- })));
- }
+ element.removeEventListener(typeEvent, fn, Boolean(delegationSelector));
+ delete events[typeEvent][fn.uidEvent];
+ }
- state.attributes.popper = Object.assign({}, state.attributes.popper, {
- 'data-popper-placement': state.placement
+ function removeNamespacedHandlers(element, events, typeEvent, namespace) {
+ const storeElementEvent = events[typeEvent] || {};
+ Object.keys(storeElementEvent).forEach(handlerKey => {
+ if (handlerKey.includes(namespace)) {
+ const event = storeElementEvent[handlerKey];
+ removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector);
+ }
});
- } // eslint-disable-next-line import/no-unused-modules
+ }
+ function getTypeEvent(event) {
+ // allow to get the native events from namespaced events ('click.bs.button' --> 'click')
+ event = event.replace(stripNameRegex, '');
+ return customEvents[event] || event;
+ }
- var computeStyles$1 = {
- name: 'computeStyles',
- enabled: true,
- phase: 'beforeWrite',
- fn: computeStyles,
- data: {}
- };
+ const EventHandler = {
+ on(element, event, handler, delegationFn) {
+ addHandler(element, event, handler, delegationFn, false);
+ },
- var passive = {
- passive: true
- };
+ one(element, event, handler, delegationFn) {
+ addHandler(element, event, handler, delegationFn, true);
+ },
- function effect(_ref) {
- var state = _ref.state,
- instance = _ref.instance,
- options = _ref.options;
- var _options$scroll = options.scroll,
- scroll = _options$scroll === void 0 ? true : _options$scroll,
- _options$resize = options.resize,
- resize = _options$resize === void 0 ? true : _options$resize;
- var window = getWindow(state.elements.popper);
- var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);
+ off(element, originalTypeEvent, handler, delegationFn) {
+ if (typeof originalTypeEvent !== 'string' || !element) {
+ return;
+ }
- if (scroll) {
- scrollParents.forEach(function (scrollParent) {
- scrollParent.addEventListener('scroll', instance.update, passive);
- });
- }
+ const [delegation, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn);
+ const inNamespace = typeEvent !== originalTypeEvent;
+ const events = getEvent(element);
+ const isNamespace = originalTypeEvent.startsWith('.');
- if (resize) {
- window.addEventListener('resize', instance.update, passive);
- }
+ if (typeof originalHandler !== 'undefined') {
+ // Simplest case: handler is passed, remove that listener ONLY.
+ if (!events || !events[typeEvent]) {
+ return;
+ }
- return function () {
- if (scroll) {
- scrollParents.forEach(function (scrollParent) {
- scrollParent.removeEventListener('scroll', instance.update, passive);
- });
+ removeHandler(element, events, typeEvent, originalHandler, delegation ? handler : null);
+ return;
}
- if (resize) {
- window.removeEventListener('resize', instance.update, passive);
+ if (isNamespace) {
+ Object.keys(events).forEach(elementEvent => {
+ removeNamespacedHandlers(element, events, elementEvent, originalTypeEvent.slice(1));
+ });
}
- };
- } // eslint-disable-next-line import/no-unused-modules
+ const storeElementEvent = events[typeEvent] || {};
+ Object.keys(storeElementEvent).forEach(keyHandlers => {
+ const handlerKey = keyHandlers.replace(stripUidRegex, '');
- var eventListeners = {
- name: 'eventListeners',
- enabled: true,
- phase: 'write',
- fn: function fn() {},
- effect: effect,
- data: {}
- };
+ if (!inNamespace || originalTypeEvent.includes(handlerKey)) {
+ const event = storeElementEvent[keyHandlers];
+ removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector);
+ }
+ });
+ },
- var hash$1 = {
- left: 'right',
- right: 'left',
- bottom: 'top',
- top: 'bottom'
- };
- function getOppositePlacement(placement) {
- return placement.replace(/left|right|bottom|top/g, function (matched) {
- return hash$1[matched];
- });
- }
+ trigger(element, event, args) {
+ if (typeof event !== 'string' || !element) {
+ return null;
+ }
- var hash = {
- start: 'end',
- end: 'start'
- };
- function getOppositeVariationPlacement(placement) {
- return placement.replace(/start|end/g, function (matched) {
- return hash[matched];
- });
- }
+ const $ = getjQuery();
+ const typeEvent = getTypeEvent(event);
+ const inNamespace = event !== typeEvent;
+ const isNative = nativeEvents.has(typeEvent);
+ let jQueryEvent;
+ let bubbles = true;
+ let nativeDispatch = true;
+ let defaultPrevented = false;
+ let evt = null;
- function getWindowScroll(node) {
- var win = getWindow(node);
- var scrollLeft = win.pageXOffset;
- var scrollTop = win.pageYOffset;
- return {
- scrollLeft: scrollLeft,
- scrollTop: scrollTop
- };
- }
+ if (inNamespace && $) {
+ jQueryEvent = $.Event(event, args);
+ $(element).trigger(jQueryEvent);
+ bubbles = !jQueryEvent.isPropagationStopped();
+ nativeDispatch = !jQueryEvent.isImmediatePropagationStopped();
+ defaultPrevented = jQueryEvent.isDefaultPrevented();
+ }
- function getWindowScrollBarX(element) {
- // If <html> has a CSS width greater than the viewport, then this will be
- // incorrect for RTL.
- // Popper 1 is broken in this case and never had a bug report so let's assume
- // it's not an issue. I don't think anyone ever specifies width on <html>
- // anyway.
- // Browsers where the left scrollbar doesn't cause an issue report `0` for
- // this (e.g. Edge 2019, IE11, Safari)
- return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
- }
+ if (isNative) {
+ evt = document.createEvent('HTMLEvents');
+ evt.initEvent(typeEvent, bubbles, true);
+ } else {
+ evt = new CustomEvent(event, {
+ bubbles,
+ cancelable: true
+ });
+ } // merge custom information in our event
- function getViewportRect(element) {
- var win = getWindow(element);
- var html = getDocumentElement(element);
- var visualViewport = win.visualViewport;
- var width = html.clientWidth;
- var height = html.clientHeight;
- var x = 0;
- var y = 0; // NB: This isn't supported on iOS <= 12. If the keyboard is open, the popper
- // can be obscured underneath it.
- // Also, `html.clientHeight` adds the bottom bar height in Safari iOS, even
- // if it isn't open, so if this isn't available, the popper will be detected
- // to overflow the bottom of the screen too early.
- if (visualViewport) {
- width = visualViewport.width;
- height = visualViewport.height; // Uses Layout Viewport (like Chrome; Safari does not currently)
- // In Chrome, it returns a value very close to 0 (+/-) but contains rounding
- // errors due to floating point numbers, so we need to check precision.
- // Safari returns a number <= 0, usually < -1 when pinch-zoomed
- // Feature detection fails in mobile emulation mode in Chrome.
- // Math.abs(win.innerWidth / visualViewport.scale - visualViewport.width) <
- // 0.001
- // Fallback here: "Not Safari" userAgent
+ if (typeof args !== 'undefined') {
+ Object.keys(args).forEach(key => {
+ Object.defineProperty(evt, key, {
+ get() {
+ return args[key];
+ }
- if (!/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
- x = visualViewport.offsetLeft;
- y = visualViewport.offsetTop;
+ });
+ });
+ }
+
+ if (defaultPrevented) {
+ evt.preventDefault();
}
+
+ if (nativeDispatch) {
+ element.dispatchEvent(evt);
+ }
+
+ if (evt.defaultPrevented && typeof jQueryEvent !== 'undefined') {
+ jQueryEvent.preventDefault();
+ }
+
+ return evt;
}
- return {
- width: width,
- height: height,
- x: x + getWindowScrollBarX(element),
- y: y
- };
- }
+ };
- // of the `<html>` and `<body>` rect bounds if horizontally scrollable
+ /**
+ * --------------------------------------------------------------------------
+ * Bootstrap (v5.0.2): dom/data.js
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
+ * --------------------------------------------------------------------------
+ */
- function getDocumentRect(element) {
- var _element$ownerDocumen;
+ /**
+ * ------------------------------------------------------------------------
+ * Constants
+ * ------------------------------------------------------------------------
+ */
+ const elementMap = new Map();
+ var Data = {
+ set(element, key, instance) {
+ if (!elementMap.has(element)) {
+ elementMap.set(element, new Map());
+ }
- var html = getDocumentElement(element);
- var winScroll = getWindowScroll(element);
- var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;
- var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
- var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
- var x = -winScroll.scrollLeft + getWindowScrollBarX(element);
- var y = -winScroll.scrollTop;
+ const instanceMap = elementMap.get(element); // make it clear we only want one instance per element
+ // can be removed later when multiple key/instances are fine to be used
- if (getComputedStyle$1(body || html).direction === 'rtl') {
- x += max(html.clientWidth, body ? body.clientWidth : 0) - width;
- }
+ if (!instanceMap.has(key) && instanceMap.size !== 0) {
+ // eslint-disable-next-line no-console
+ console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(instanceMap.keys())[0]}.`);
+ return;
+ }
- return {
- width: width,
- height: height,
- x: x,
- y: y
- };
- }
+ instanceMap.set(key, instance);
+ },
- function isScrollParent(element) {
- // Firefox wants us to check `-x` and `-y` variations as well
- var _getComputedStyle = getComputedStyle$1(element),
- overflow = _getComputedStyle.overflow,
- overflowX = _getComputedStyle.overflowX,
- overflowY = _getComputedStyle.overflowY;
+ get(element, key) {
+ if (elementMap.has(element)) {
+ return elementMap.get(element).get(key) || null;
+ }
- return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
- }
+ return null;
+ },
- function getScrollParent(node) {
- if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {
- // $FlowFixMe[incompatible-return]: assume body is always available
- return node.ownerDocument.body;
- }
+ remove(element, key) {
+ if (!elementMap.has(element)) {
+ return;
+ }
- if (isHTMLElement(node) && isScrollParent(node)) {
- return node;
+ const instanceMap = elementMap.get(element);
+ instanceMap.delete(key); // free up element references if there are no instances left for an element
+
+ if (instanceMap.size === 0) {
+ elementMap.delete(element);
+ }
}
- return getScrollParent(getParentNode(node));
- }
+ };
- /*
- given a DOM element, return the list of all scroll parents, up the list of ancesors
- until we get to the top window object. This list is what we attach scroll listeners
- to, because if any of these parent elements scroll, we'll need to re-calculate the
- reference element's position.
- */
+ /**
+ * --------------------------------------------------------------------------
+ * Bootstrap (v5.0.2): base-component.js
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
+ * --------------------------------------------------------------------------
+ */
+ /**
+ * ------------------------------------------------------------------------
+ * Constants
+ * ------------------------------------------------------------------------
+ */
- function listScrollParents(element, list) {
- var _element$ownerDocumen;
+ const VERSION = '5.0.2';
- if (list === void 0) {
- list = [];
- }
+ class BaseComponent {
+ constructor(element) {
+ element = getElement(element);
- var scrollParent = getScrollParent(element);
- var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);
- var win = getWindow(scrollParent);
- var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;
- var updatedList = list.concat(target);
- return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here
- updatedList.concat(listScrollParents(getParentNode(target)));
- }
+ if (!element) {
+ return;
+ }
- function rectToClientRect(rect) {
- return Object.assign({}, rect, {
- left: rect.x,
- top: rect.y,
- right: rect.x + rect.width,
- bottom: rect.y + rect.height
- });
- }
+ this._element = element;
+ Data.set(this._element, this.constructor.DATA_KEY, this);
+ }
- function getInnerBoundingClientRect(element) {
- var rect = getBoundingClientRect(element);
- rect.top = rect.top + element.clientTop;
- rect.left = rect.left + element.clientLeft;
- rect.bottom = rect.top + element.clientHeight;
- rect.right = rect.left + element.clientWidth;
- rect.width = element.clientWidth;
- rect.height = element.clientHeight;
- rect.x = rect.left;
- rect.y = rect.top;
- return rect;
- }
+ dispose() {
+ Data.remove(this._element, this.constructor.DATA_KEY);
+ EventHandler.off(this._element, this.constructor.EVENT_KEY);
+ Object.getOwnPropertyNames(this).forEach(propertyName => {
+ this[propertyName] = null;
+ });
+ }
- function getClientRectFromMixedType(element, clippingParent) {
- return clippingParent === viewport ? rectToClientRect(getViewportRect(element)) : isHTMLElement(clippingParent) ? getInnerBoundingClientRect(clippingParent) : rectToClientRect(getDocumentRect(getDocumentElement(element)));
- } // A "clipping parent" is an overflowable container with the characteristic of
- // clipping (or hiding) overflowing elements with a position different from
- // `initial`
+ _queueCallback(callback, element, isAnimated = true) {
+ executeAfterTransition(callback, element, isAnimated);
+ }
+ /** Static */
- function getClippingParents(element) {
- var clippingParents = listScrollParents(getParentNode(element));
- var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle$1(element).position) >= 0;
- var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;
+ static getInstance(element) {
+ return Data.get(element, this.DATA_KEY);
+ }
- if (!isElement$1(clipperElement)) {
- return [];
- } // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414
+ static getOrCreateInstance(element, config = {}) {
+ return this.getInstance(element) || new this(element, typeof config === 'object' ? config : null);
+ }
+ static get VERSION() {
+ return VERSION;
+ }
- return clippingParents.filter(function (clippingParent) {
- return isElement$1(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body';
- });
- } // Gets the maximum area that the element is visible in due to any number of
- // clipping parents
+ static get NAME() {
+ throw new Error('You have to implement the static method "NAME", for each component!');
+ }
+ static get DATA_KEY() {
+ return `bs.${this.NAME}`;
+ }
- function getClippingRect(element, boundary, rootBoundary) {
- var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);
- var clippingParents = [].concat(mainClippingParents, [rootBoundary]);
- var firstClippingParent = clippingParents[0];
- var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {
- var rect = getClientRectFromMixedType(element, clippingParent);
- accRect.top = max(rect.top, accRect.top);
- accRect.right = min(rect.right, accRect.right);
- accRect.bottom = min(rect.bottom, accRect.bottom);
- accRect.left = max(rect.left, accRect.left);
- return accRect;
- }, getClientRectFromMixedType(element, firstClippingParent));
- clippingRect.width = clippingRect.right - clippingRect.left;
- clippingRect.height = clippingRect.bottom - clippingRect.top;
- clippingRect.x = clippingRect.left;
- clippingRect.y = clippingRect.top;
- return clippingRect;
- }
+ static get EVENT_KEY() {
+ return `.${this.DATA_KEY}`;
+ }
- function getVariation(placement) {
- return placement.split('-')[1];
}
- function computeOffsets(_ref) {
- var reference = _ref.reference,
- element = _ref.element,
- placement = _ref.placement;
- var basePlacement = placement ? getBasePlacement(placement) : null;
- var variation = placement ? getVariation(placement) : null;
- var commonX = reference.x + reference.width / 2 - element.width / 2;
- var commonY = reference.y + reference.height / 2 - element.height / 2;
- var offsets;
+ /**
+ * --------------------------------------------------------------------------
+ * Bootstrap (v5.0.2): alert.js
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
+ * --------------------------------------------------------------------------
+ */
+ /**
+ * ------------------------------------------------------------------------
+ * Constants
+ * ------------------------------------------------------------------------
+ */
- switch (basePlacement) {
- case top:
- offsets = {
- x: commonX,
- y: reference.y - element.height
- };
- break;
+ const NAME$c = 'alert';
+ const DATA_KEY$b = 'bs.alert';
+ const EVENT_KEY$b = `.${DATA_KEY$b}`;
+ const DATA_API_KEY$8 = '.data-api';
+ const SELECTOR_DISMISS = '[data-bs-dismiss="alert"]';
+ const EVENT_CLOSE = `close${EVENT_KEY$b}`;
+ const EVENT_CLOSED = `closed${EVENT_KEY$b}`;
+ const EVENT_CLICK_DATA_API$7 = `click${EVENT_KEY$b}${DATA_API_KEY$8}`;
+ const CLASS_NAME_ALERT = 'alert';
+ const CLASS_NAME_FADE$6 = 'fade';
+ const CLASS_NAME_SHOW$9 = 'show';
+ /**
+ * ------------------------------------------------------------------------
+ * Class Definition
+ * ------------------------------------------------------------------------
+ */
- case bottom:
- offsets = {
- x: commonX,
- y: reference.y + reference.height
- };
- break;
+ class Alert extends BaseComponent {
+ // Getters
+ static get NAME() {
+ return NAME$c;
+ } // Public
- case right:
- offsets = {
- x: reference.x + reference.width,
- y: commonY
- };
- break;
- case left:
- offsets = {
- x: reference.x - element.width,
- y: commonY
- };
- break;
+ close(element) {
+ const rootElement = element ? this._getRootElement(element) : this._element;
- default:
- offsets = {
- x: reference.x,
- y: reference.y
- };
- }
+ const customEvent = this._triggerCloseEvent(rootElement);
- var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;
+ if (customEvent === null || customEvent.defaultPrevented) {
+ return;
+ }
- if (mainAxis != null) {
- var len = mainAxis === 'y' ? 'height' : 'width';
+ this._removeElement(rootElement);
+ } // Private
- switch (variation) {
- case start:
- offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);
- break;
- case end:
- offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);
- break;
- }
+ _getRootElement(element) {
+ return getElementFromSelector(element) || element.closest(`.${CLASS_NAME_ALERT}`);
}
- return offsets;
- }
+ _triggerCloseEvent(element) {
+ return EventHandler.trigger(element, EVENT_CLOSE);
+ }
- function detectOverflow(state, options) {
- if (options === void 0) {
- options = {};
+ _removeElement(element) {
+ element.classList.remove(CLASS_NAME_SHOW$9);
+ const isAnimated = element.classList.contains(CLASS_NAME_FADE$6);
+
+ this._queueCallback(() => this._destroyElement(element), element, isAnimated);
}
- var _options = options,
- _options$placement = _options.placement,
- placement = _options$placement === void 0 ? state.placement : _options$placement,
- _options$boundary = _options.boundary,
- boundary = _options$boundary === void 0 ? clippingParents : _options$boundary,
- _options$rootBoundary = _options.rootBoundary,
- rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary,
- _options$elementConte = _options.elementContext,
- elementContext = _options$elementConte === void 0 ? popper : _options$elementConte,
- _options$altBoundary = _options.altBoundary,
- altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary,
- _options$padding = _options.padding,
- padding = _options$padding === void 0 ? 0 : _options$padding;
- var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
- var altContext = elementContext === popper ? reference : popper;
- var referenceElement = state.elements.reference;
- var popperRect = state.rects.popper;
- var element = state.elements[altBoundary ? altContext : elementContext];
- var clippingClientRect = getClippingRect(isElement$1(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary);
- var referenceClientRect = getBoundingClientRect(referenceElement);
- var popperOffsets = computeOffsets({
- reference: referenceClientRect,
- element: popperRect,
- strategy: 'absolute',
- placement: placement
- });
- var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets));
- var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect
- // 0 or negative = within the clipping rect
+ _destroyElement(element) {
+ element.remove();
+ EventHandler.trigger(element, EVENT_CLOSED);
+ } // Static
- var overflowOffsets = {
- top: clippingClientRect.top - elementClientRect.top + paddingObject.top,
- bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,
- left: clippingClientRect.left - elementClientRect.left + paddingObject.left,
- right: elementClientRect.right - clippingClientRect.right + paddingObject.right
- };
- var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element
- if (elementContext === popper && offsetData) {
- var offset = offsetData[placement];
- Object.keys(overflowOffsets).forEach(function (key) {
- var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;
- var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x';
- overflowOffsets[key] += offset[axis] * multiply;
+ static jQueryInterface(config) {
+ return this.each(function () {
+ const data = Alert.getOrCreateInstance(this);
+
+ if (config === 'close') {
+ data[config](this);
+ }
});
}
- return overflowOffsets;
- }
+ static handleDismiss(alertInstance) {
+ return function (event) {
+ if (event) {
+ event.preventDefault();
+ }
- function computeAutoPlacement(state, options) {
- if (options === void 0) {
- options = {};
+ alertInstance.close(this);
+ };
}
- var _options = options,
- placement = _options.placement,
- boundary = _options.boundary,
- rootBoundary = _options.rootBoundary,
- padding = _options.padding,
- flipVariations = _options.flipVariations,
- _options$allowedAutoP = _options.allowedAutoPlacements,
- allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP;
- var variation = getVariation(placement);
- var placements$1 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) {
- return getVariation(placement) === variation;
- }) : basePlacements;
- var allowedPlacements = placements$1.filter(function (placement) {
- return allowedAutoPlacements.indexOf(placement) >= 0;
- });
+ }
+ /**
+ * ------------------------------------------------------------------------
+ * Data Api implementation
+ * ------------------------------------------------------------------------
+ */
- if (allowedPlacements.length === 0) {
- allowedPlacements = placements$1;
- } // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...
+ EventHandler.on(document, EVENT_CLICK_DATA_API$7, SELECTOR_DISMISS, Alert.handleDismiss(new Alert()));
+ /**
+ * ------------------------------------------------------------------------
+ * jQuery
+ * ------------------------------------------------------------------------
+ * add .Alert to jQuery only if jQuery is present
+ */
- var overflows = allowedPlacements.reduce(function (acc, placement) {
- acc[placement] = detectOverflow(state, {
- placement: placement,
- boundary: boundary,
- rootBoundary: rootBoundary,
- padding: padding
- })[getBasePlacement(placement)];
- return acc;
- }, {});
- return Object.keys(overflows).sort(function (a, b) {
- return overflows[a] - overflows[b];
- });
- }
+ defineJQueryPlugin(Alert);
- function getExpandedFallbackPlacements(placement) {
- if (getBasePlacement(placement) === auto) {
- return [];
- }
+ /**
+ * --------------------------------------------------------------------------
+ * Bootstrap (v5.0.2): button.js
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
+ * --------------------------------------------------------------------------
+ */
+ /**
+ * ------------------------------------------------------------------------
+ * Constants
+ * ------------------------------------------------------------------------
+ */
- var oppositePlacement = getOppositePlacement(placement);
- return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];
- }
+ const NAME$b = 'button';
+ const DATA_KEY$a = 'bs.button';
+ const EVENT_KEY$a = `.${DATA_KEY$a}`;
+ const DATA_API_KEY$7 = '.data-api';
+ const CLASS_NAME_ACTIVE$3 = 'active';
+ const SELECTOR_DATA_TOGGLE$5 = '[data-bs-toggle="button"]';
+ const EVENT_CLICK_DATA_API$6 = `click${EVENT_KEY$a}${DATA_API_KEY$7}`;
+ /**
+ * ------------------------------------------------------------------------
+ * Class Definition
+ * ------------------------------------------------------------------------
+ */
- function flip(_ref) {
- var state = _ref.state,
- options = _ref.options,
- name = _ref.name;
+ class Button extends BaseComponent {
+ // Getters
+ static get NAME() {
+ return NAME$b;
+ } // Public
- if (state.modifiersData[name]._skip) {
- return;
- }
- var _options$mainAxis = options.mainAxis,
- checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
- _options$altAxis = options.altAxis,
- checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,
- specifiedFallbackPlacements = options.fallbackPlacements,
- padding = options.padding,
- boundary = options.boundary,
- rootBoundary = options.rootBoundary,
- altBoundary = options.altBoundary,
- _options$flipVariatio = options.flipVariations,
- flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,
- allowedAutoPlacements = options.allowedAutoPlacements;
- var preferredPlacement = state.options.placement;
- var basePlacement = getBasePlacement(preferredPlacement);
- var isBasePlacement = basePlacement === preferredPlacement;
- var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));
- var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {
- return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, {
- placement: placement,
- boundary: boundary,
- rootBoundary: rootBoundary,
- padding: padding,
- flipVariations: flipVariations,
- allowedAutoPlacements: allowedAutoPlacements
- }) : placement);
- }, []);
- var referenceRect = state.rects.reference;
- var popperRect = state.rects.popper;
- var checksMap = new Map();
- var makeFallbackChecks = true;
- var firstFittingPlacement = placements[0];
+ toggle() {
+ // Toggle class and sync the `aria-pressed` attribute with the return value of the `.toggle()` method
+ this._element.setAttribute('aria-pressed', this._element.classList.toggle(CLASS_NAME_ACTIVE$3));
+ } // Static
- for (var i = 0; i < placements.length; i++) {
- var placement = placements[i];
- var _basePlacement = getBasePlacement(placement);
+ static jQueryInterface(config) {
+ return this.each(function () {
+ const data = Button.getOrCreateInstance(this);
- var isStartVariation = getVariation(placement) === start;
- var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;
- var len = isVertical ? 'width' : 'height';
- var overflow = detectOverflow(state, {
- placement: placement,
- boundary: boundary,
- rootBoundary: rootBoundary,
- altBoundary: altBoundary,
- padding: padding
+ if (config === 'toggle') {
+ data[config]();
+ }
});
- var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;
-
- if (referenceRect[len] > popperRect[len]) {
- mainVariationSide = getOppositePlacement(mainVariationSide);
- }
-
- var altVariationSide = getOppositePlacement(mainVariationSide);
- var checks = [];
-
- if (checkMainAxis) {
- checks.push(overflow[_basePlacement] <= 0);
- }
-
- if (checkAltAxis) {
- checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);
- }
-
- if (checks.every(function (check) {
- return check;
- })) {
- firstFittingPlacement = placement;
- makeFallbackChecks = false;
- break;
- }
-
- checksMap.set(placement, checks);
}
- if (makeFallbackChecks) {
- // `2` may be desired in some cases – research later
- var numberOfChecks = flipVariations ? 3 : 1;
-
- var _loop = function _loop(_i) {
- var fittingPlacement = placements.find(function (placement) {
- var checks = checksMap.get(placement);
+ }
+ /**
+ * ------------------------------------------------------------------------
+ * Data Api implementation
+ * ------------------------------------------------------------------------
+ */
- if (checks) {
- return checks.slice(0, _i).every(function (check) {
- return check;
- });
- }
- });
- if (fittingPlacement) {
- firstFittingPlacement = fittingPlacement;
- return "break";
- }
- };
+ EventHandler.on(document, EVENT_CLICK_DATA_API$6, SELECTOR_DATA_TOGGLE$5, event => {
+ event.preventDefault();
+ const button = event.target.closest(SELECTOR_DATA_TOGGLE$5);
+ const data = Button.getOrCreateInstance(button);
+ data.toggle();
+ });
+ /**
+ * ------------------------------------------------------------------------
+ * jQuery
+ * ------------------------------------------------------------------------
+ * add .Button to jQuery only if jQuery is present
+ */
- for (var _i = numberOfChecks; _i > 0; _i--) {
- var _ret = _loop(_i);
+ defineJQueryPlugin(Button);
- if (_ret === "break") break;
- }
+ /**
+ * --------------------------------------------------------------------------
+ * Bootstrap (v5.0.2): dom/manipulator.js
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
+ * --------------------------------------------------------------------------
+ */
+ function normalizeData(val) {
+ if (val === 'true') {
+ return true;
}
- if (state.placement !== firstFittingPlacement) {
- state.modifiersData[name]._skip = true;
- state.placement = firstFittingPlacement;
- state.reset = true;
+ if (val === 'false') {
+ return false;
}
- } // eslint-disable-next-line import/no-unused-modules
-
- var flip$1 = {
- name: 'flip',
- enabled: true,
- phase: 'main',
- fn: flip,
- requiresIfExists: ['offset'],
- data: {
- _skip: false
+ if (val === Number(val).toString()) {
+ return Number(val);
}
- };
- function getSideOffsets(overflow, rect, preventedOffsets) {
- if (preventedOffsets === void 0) {
- preventedOffsets = {
- x: 0,
- y: 0
- };
+ if (val === '' || val === 'null') {
+ return null;
}
- return {
- top: overflow.top - rect.height - preventedOffsets.y,
- right: overflow.right - rect.width + preventedOffsets.x,
- bottom: overflow.bottom - rect.height + preventedOffsets.y,
- left: overflow.left - rect.width - preventedOffsets.x
- };
+ return val;
}
- function isAnySideFullyClipped(overflow) {
- return [top, right, bottom, left].some(function (side) {
- return overflow[side] >= 0;
- });
+ function normalizeDataKey(key) {
+ return key.replace(/[A-Z]/g, chr => `-${chr.toLowerCase()}`);
}
- function hide(_ref) {
- var state = _ref.state,
- name = _ref.name;
- var referenceRect = state.rects.reference;
- var popperRect = state.rects.popper;
- var preventedOffsets = state.modifiersData.preventOverflow;
- var referenceOverflow = detectOverflow(state, {
- elementContext: 'reference'
- });
- var popperAltOverflow = detectOverflow(state, {
- altBoundary: true
- });
- var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);
- var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);
- var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);
- var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);
- state.modifiersData[name] = {
- referenceClippingOffsets: referenceClippingOffsets,
- popperEscapeOffsets: popperEscapeOffsets,
- isReferenceHidden: isReferenceHidden,
- hasPopperEscaped: hasPopperEscaped
- };
- state.attributes.popper = Object.assign({}, state.attributes.popper, {
- 'data-popper-reference-hidden': isReferenceHidden,
- 'data-popper-escaped': hasPopperEscaped
- });
- } // eslint-disable-next-line import/no-unused-modules
+ const Manipulator = {
+ setDataAttribute(element, key, value) {
+ element.setAttribute(`data-bs-${normalizeDataKey(key)}`, value);
+ },
+ removeDataAttribute(element, key) {
+ element.removeAttribute(`data-bs-${normalizeDataKey(key)}`);
+ },
- var hide$1 = {
- name: 'hide',
- enabled: true,
- phase: 'main',
- requiresIfExists: ['preventOverflow'],
- fn: hide
- };
+ getDataAttributes(element) {
+ if (!element) {
+ return {};
+ }
- function distanceAndSkiddingToXY(placement, rects, offset) {
- var basePlacement = getBasePlacement(placement);
- var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;
+ const attributes = {};
+ Object.keys(element.dataset).filter(key => key.startsWith('bs')).forEach(key => {
+ let pureKey = key.replace(/^bs/, '');
+ pureKey = pureKey.charAt(0).toLowerCase() + pureKey.slice(1, pureKey.length);
+ attributes[pureKey] = normalizeData(element.dataset[key]);
+ });
+ return attributes;
+ },
- var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, {
- placement: placement
- })) : offset,
- skidding = _ref[0],
- distance = _ref[1];
+ getDataAttribute(element, key) {
+ return normalizeData(element.getAttribute(`data-bs-${normalizeDataKey(key)}`));
+ },
- skidding = skidding || 0;
- distance = (distance || 0) * invertDistance;
- return [left, right].indexOf(basePlacement) >= 0 ? {
- x: distance,
- y: skidding
- } : {
- x: skidding,
- y: distance
- };
- }
+ offset(element) {
+ const rect = element.getBoundingClientRect();
+ return {
+ top: rect.top + document.body.scrollTop,
+ left: rect.left + document.body.scrollLeft
+ };
+ },
- function offset(_ref2) {
- var state = _ref2.state,
- options = _ref2.options,
- name = _ref2.name;
- var _options$offset = options.offset,
- offset = _options$offset === void 0 ? [0, 0] : _options$offset;
- var data = placements.reduce(function (acc, placement) {
- acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset);
- return acc;
- }, {});
- var _data$state$placement = data[state.placement],
- x = _data$state$placement.x,
- y = _data$state$placement.y;
-
- if (state.modifiersData.popperOffsets != null) {
- state.modifiersData.popperOffsets.x += x;
- state.modifiersData.popperOffsets.y += y;
+ position(element) {
+ return {
+ top: element.offsetTop,
+ left: element.offsetLeft
+ };
}
- state.modifiersData[name] = data;
- } // eslint-disable-next-line import/no-unused-modules
-
-
- var offset$1 = {
- name: 'offset',
- enabled: true,
- phase: 'main',
- requires: ['popperOffsets'],
- fn: offset
};
- function popperOffsets(_ref) {
- var state = _ref.state,
- name = _ref.name;
- // Offsets are the actual position the popper needs to have to be
- // properly positioned near its reference element
- // This is the most basic placement, and will be adjusted by
- // the modifiers in the next step
- state.modifiersData[name] = computeOffsets({
- reference: state.rects.reference,
- element: state.rects.popper,
- strategy: 'absolute',
- placement: state.placement
- });
- } // eslint-disable-next-line import/no-unused-modules
+ /**
+ * --------------------------------------------------------------------------
+ * Bootstrap (v5.0.2): carousel.js
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
+ * --------------------------------------------------------------------------
+ */
+ /**
+ * ------------------------------------------------------------------------
+ * Constants
+ * ------------------------------------------------------------------------
+ */
+ const NAME$a = 'carousel';
+ const DATA_KEY$9 = 'bs.carousel';
+ const EVENT_KEY$9 = `.${DATA_KEY$9}`;
+ const DATA_API_KEY$6 = '.data-api';
+ const ARROW_LEFT_KEY = 'ArrowLeft';
+ const ARROW_RIGHT_KEY = 'ArrowRight';
+ const TOUCHEVENT_COMPAT_WAIT = 500; // Time for mouse compat events to fire after touch
- var popperOffsets$1 = {
- name: 'popperOffsets',
- enabled: true,
- phase: 'read',
- fn: popperOffsets,
- data: {}
+ const SWIPE_THRESHOLD = 40;
+ const Default$9 = {
+ interval: 5000,
+ keyboard: true,
+ slide: false,
+ pause: 'hover',
+ wrap: true,
+ touch: true
+ };
+ const DefaultType$9 = {
+ interval: '(number|boolean)',
+ keyboard: 'boolean',
+ slide: '(boolean|string)',
+ pause: '(string|boolean)',
+ wrap: 'boolean',
+ touch: 'boolean'
+ };
+ const ORDER_NEXT = 'next';
+ const ORDER_PREV = 'prev';
+ const DIRECTION_LEFT = 'left';
+ const DIRECTION_RIGHT = 'right';
+ const KEY_TO_DIRECTION = {
+ [ARROW_LEFT_KEY]: DIRECTION_RIGHT,
+ [ARROW_RIGHT_KEY]: DIRECTION_LEFT
};
+ const EVENT_SLIDE = `slide${EVENT_KEY$9}`;
+ const EVENT_SLID = `slid${EVENT_KEY$9}`;
+ const EVENT_KEYDOWN = `keydown${EVENT_KEY$9}`;
+ const EVENT_MOUSEENTER = `mouseenter${EVENT_KEY$9}`;
+ const EVENT_MOUSELEAVE = `mouseleave${EVENT_KEY$9}`;
+ const EVENT_TOUCHSTART = `touchstart${EVENT_KEY$9}`;
+ const EVENT_TOUCHMOVE = `touchmove${EVENT_KEY$9}`;
+ const EVENT_TOUCHEND = `touchend${EVENT_KEY$9}`;
+ const EVENT_POINTERDOWN = `pointerdown${EVENT_KEY$9}`;
+ const EVENT_POINTERUP = `pointerup${EVENT_KEY$9}`;
+ const EVENT_DRAG_START = `dragstart${EVENT_KEY$9}`;
+ const EVENT_LOAD_DATA_API$2 = `load${EVENT_KEY$9}${DATA_API_KEY$6}`;
+ const EVENT_CLICK_DATA_API$5 = `click${EVENT_KEY$9}${DATA_API_KEY$6}`;
+ const CLASS_NAME_CAROUSEL = 'carousel';
+ const CLASS_NAME_ACTIVE$2 = 'active';
+ const CLASS_NAME_SLIDE = 'slide';
+ const CLASS_NAME_END = 'carousel-item-end';
+ const CLASS_NAME_START = 'carousel-item-start';
+ const CLASS_NAME_NEXT = 'carousel-item-next';
+ const CLASS_NAME_PREV = 'carousel-item-prev';
+ const CLASS_NAME_POINTER_EVENT = 'pointer-event';
+ const SELECTOR_ACTIVE$1 = '.active';
+ const SELECTOR_ACTIVE_ITEM = '.active.carousel-item';
+ const SELECTOR_ITEM = '.carousel-item';
+ const SELECTOR_ITEM_IMG = '.carousel-item img';
+ const SELECTOR_NEXT_PREV = '.carousel-item-next, .carousel-item-prev';
+ const SELECTOR_INDICATORS = '.carousel-indicators';
+ const SELECTOR_INDICATOR = '[data-bs-target]';
+ const SELECTOR_DATA_SLIDE = '[data-bs-slide], [data-bs-slide-to]';
+ const SELECTOR_DATA_RIDE = '[data-bs-ride="carousel"]';
+ const POINTER_TYPE_TOUCH = 'touch';
+ const POINTER_TYPE_PEN = 'pen';
+ /**
+ * ------------------------------------------------------------------------
+ * Class Definition
+ * ------------------------------------------------------------------------
+ */
- function getAltAxis(axis) {
- return axis === 'x' ? 'y' : 'x';
- }
+ class Carousel extends BaseComponent {
+ constructor(element, config) {
+ super(element);
+ this._items = null;
+ this._interval = null;
+ this._activeElement = null;
+ this._isPaused = false;
+ this._isSliding = false;
+ this.touchTimeout = null;
+ this.touchStartX = 0;
+ this.touchDeltaX = 0;
+ this._config = this._getConfig(config);
+ this._indicatorsElement = SelectorEngine.findOne(SELECTOR_INDICATORS, this._element);
+ this._touchSupported = 'ontouchstart' in document.documentElement || navigator.maxTouchPoints > 0;
+ this._pointerEvent = Boolean(window.PointerEvent);
- function preventOverflow(_ref) {
- var state = _ref.state,
- options = _ref.options,
- name = _ref.name;
- var _options$mainAxis = options.mainAxis,
- checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
- _options$altAxis = options.altAxis,
- checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis,
- boundary = options.boundary,
- rootBoundary = options.rootBoundary,
- altBoundary = options.altBoundary,
- padding = options.padding,
- _options$tether = options.tether,
- tether = _options$tether === void 0 ? true : _options$tether,
- _options$tetherOffset = options.tetherOffset,
- tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;
- var overflow = detectOverflow(state, {
- boundary: boundary,
- rootBoundary: rootBoundary,
- padding: padding,
- altBoundary: altBoundary
- });
- var basePlacement = getBasePlacement(state.placement);
- var variation = getVariation(state.placement);
- var isBasePlacement = !variation;
- var mainAxis = getMainAxisFromPlacement(basePlacement);
- var altAxis = getAltAxis(mainAxis);
- var popperOffsets = state.modifiersData.popperOffsets;
- var referenceRect = state.rects.reference;
- var popperRect = state.rects.popper;
- var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, {
- placement: state.placement
- })) : tetherOffset;
- var data = {
- x: 0,
- y: 0
- };
+ this._addEventListeners();
+ } // Getters
- if (!popperOffsets) {
- return;
+
+ static get Default() {
+ return Default$9;
}
- if (checkMainAxis || checkAltAxis) {
- var mainSide = mainAxis === 'y' ? top : left;
- var altSide = mainAxis === 'y' ? bottom : right;
- var len = mainAxis === 'y' ? 'height' : 'width';
- var offset = popperOffsets[mainAxis];
- var min$1 = popperOffsets[mainAxis] + overflow[mainSide];
- var max$1 = popperOffsets[mainAxis] - overflow[altSide];
- var additive = tether ? -popperRect[len] / 2 : 0;
- var minLen = variation === start ? referenceRect[len] : popperRect[len];
- var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go
- // outside the reference bounds
+ static get NAME() {
+ return NAME$a;
+ } // Public
- var arrowElement = state.elements.arrow;
- var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {
- width: 0,
- height: 0
- };
- var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject();
- var arrowPaddingMin = arrowPaddingObject[mainSide];
- var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want
- // to include its full size in the calculation. If the reference is small
- // and near the edge of a boundary, the popper can overflow even if the
- // reference is not overflowing as well (e.g. virtual elements with no
- // width or height)
- var arrowLen = within(0, referenceRect[len], arrowRect[len]);
- var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - tetherOffsetValue : minLen - arrowLen - arrowPaddingMin - tetherOffsetValue;
- var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + tetherOffsetValue : maxLen + arrowLen + arrowPaddingMax + tetherOffsetValue;
- var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);
- var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;
- var offsetModifierValue = state.modifiersData.offset ? state.modifiersData.offset[state.placement][mainAxis] : 0;
- var tetherMin = popperOffsets[mainAxis] + minOffset - offsetModifierValue - clientOffset;
- var tetherMax = popperOffsets[mainAxis] + maxOffset - offsetModifierValue;
+ next() {
+ this._slide(ORDER_NEXT);
+ }
- if (checkMainAxis) {
- var preventedOffset = within(tether ? min(min$1, tetherMin) : min$1, offset, tether ? max(max$1, tetherMax) : max$1);
- popperOffsets[mainAxis] = preventedOffset;
- data[mainAxis] = preventedOffset - offset;
+ nextWhenVisible() {
+ // Don't call next when the page isn't visible
+ // or the carousel or its parent isn't visible
+ if (!document.hidden && isVisible(this._element)) {
+ this.next();
}
+ }
- if (checkAltAxis) {
- var _mainSide = mainAxis === 'x' ? top : left;
+ prev() {
+ this._slide(ORDER_PREV);
+ }
- var _altSide = mainAxis === 'x' ? bottom : right;
+ pause(event) {
+ if (!event) {
+ this._isPaused = true;
+ }
- var _offset = popperOffsets[altAxis];
+ if (SelectorEngine.findOne(SELECTOR_NEXT_PREV, this._element)) {
+ triggerTransitionEnd(this._element);
+ this.cycle(true);
+ }
- var _min = _offset + overflow[_mainSide];
+ clearInterval(this._interval);
+ this._interval = null;
+ }
- var _max = _offset - overflow[_altSide];
+ cycle(event) {
+ if (!event) {
+ this._isPaused = false;
+ }
- var _preventedOffset = within(tether ? min(_min, tetherMin) : _min, _offset, tether ? max(_max, tetherMax) : _max);
+ if (this._interval) {
+ clearInterval(this._interval);
+ this._interval = null;
+ }
- popperOffsets[altAxis] = _preventedOffset;
- data[altAxis] = _preventedOffset - _offset;
+ if (this._config && this._config.interval && !this._isPaused) {
+ this._updateInterval();
+
+ this._interval = setInterval((document.visibilityState ? this.nextWhenVisible : this.next).bind(this), this._config.interval);
}
}
- state.modifiersData[name] = data;
- } // eslint-disable-next-line import/no-unused-modules
+ to(index) {
+ this._activeElement = SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element);
+ const activeIndex = this._getItemIndex(this._activeElement);
- var preventOverflow$1 = {
- name: 'preventOverflow',
- enabled: true,
- phase: 'main',
- fn: preventOverflow,
- requiresIfExists: ['offset']
- };
+ if (index > this._items.length - 1 || index < 0) {
+ return;
+ }
- function getHTMLElementScroll(element) {
- return {
- scrollLeft: element.scrollLeft,
- scrollTop: element.scrollTop
- };
- }
+ if (this._isSliding) {
+ EventHandler.one(this._element, EVENT_SLID, () => this.to(index));
+ return;
+ }
- function getNodeScroll(node) {
- if (node === getWindow(node) || !isHTMLElement(node)) {
- return getWindowScroll(node);
- } else {
- return getHTMLElementScroll(node);
+ if (activeIndex === index) {
+ this.pause();
+ this.cycle();
+ return;
+ }
+
+ const order = index > activeIndex ? ORDER_NEXT : ORDER_PREV;
+
+ this._slide(order, this._items[index]);
+ } // Private
+
+
+ _getConfig(config) {
+ config = { ...Default$9,
+ ...Manipulator.getDataAttributes(this._element),
+ ...(typeof config === 'object' ? config : {})
+ };
+ typeCheckConfig(NAME$a, config, DefaultType$9);
+ return config;
}
- }
- // Composite means it takes into account transforms as well as layout.
+ _handleSwipe() {
+ const absDeltax = Math.abs(this.touchDeltaX);
- function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {
- if (isFixed === void 0) {
- isFixed = false;
+ if (absDeltax <= SWIPE_THRESHOLD) {
+ return;
+ }
+
+ const direction = absDeltax / this.touchDeltaX;
+ this.touchDeltaX = 0;
+
+ if (!direction) {
+ return;
+ }
+
+ this._slide(direction > 0 ? DIRECTION_RIGHT : DIRECTION_LEFT);
}
- var documentElement = getDocumentElement(offsetParent);
- var rect = getBoundingClientRect(elementOrVirtualElement);
- var isOffsetParentAnElement = isHTMLElement(offsetParent);
- var scroll = {
- scrollLeft: 0,
- scrollTop: 0
- };
- var offsets = {
- x: 0,
- y: 0
- };
+ _addEventListeners() {
+ if (this._config.keyboard) {
+ EventHandler.on(this._element, EVENT_KEYDOWN, event => this._keydown(event));
+ }
- if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
- if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078
- isScrollParent(documentElement)) {
- scroll = getNodeScroll(offsetParent);
+ if (this._config.pause === 'hover') {
+ EventHandler.on(this._element, EVENT_MOUSEENTER, event => this.pause(event));
+ EventHandler.on(this._element, EVENT_MOUSELEAVE, event => this.cycle(event));
}
- if (isHTMLElement(offsetParent)) {
- offsets = getBoundingClientRect(offsetParent);
- offsets.x += offsetParent.clientLeft;
- offsets.y += offsetParent.clientTop;
- } else if (documentElement) {
- offsets.x = getWindowScrollBarX(documentElement);
+ if (this._config.touch && this._touchSupported) {
+ this._addTouchEventListeners();
}
}
- return {
- x: rect.left + scroll.scrollLeft - offsets.x,
- y: rect.top + scroll.scrollTop - offsets.y,
- width: rect.width,
- height: rect.height
- };
- }
+ _addTouchEventListeners() {
+ const start = event => {
+ if (this._pointerEvent && (event.pointerType === POINTER_TYPE_PEN || event.pointerType === POINTER_TYPE_TOUCH)) {
+ this.touchStartX = event.clientX;
+ } else if (!this._pointerEvent) {
+ this.touchStartX = event.touches[0].clientX;
+ }
+ };
- function order(modifiers) {
- var map = new Map();
- var visited = new Set();
- var result = [];
- modifiers.forEach(function (modifier) {
- map.set(modifier.name, modifier);
- }); // On visiting object, check for its dependencies and visit them recursively
+ const move = event => {
+ // ensure swiping with one touch and not pinching
+ this.touchDeltaX = event.touches && event.touches.length > 1 ? 0 : event.touches[0].clientX - this.touchStartX;
+ };
- function sort(modifier) {
- visited.add(modifier.name);
- var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);
- requires.forEach(function (dep) {
- if (!visited.has(dep)) {
- var depModifier = map.get(dep);
+ const end = event => {
+ if (this._pointerEvent && (event.pointerType === POINTER_TYPE_PEN || event.pointerType === POINTER_TYPE_TOUCH)) {
+ this.touchDeltaX = event.clientX - this.touchStartX;
+ }
- if (depModifier) {
- sort(depModifier);
+ this._handleSwipe();
+
+ if (this._config.pause === 'hover') {
+ // If it's a touch-enabled device, mouseenter/leave are fired as
+ // part of the mouse compatibility events on first tap - the carousel
+ // would stop cycling until user tapped out of it;
+ // here, we listen for touchend, explicitly pause the carousel
+ // (as if it's the second time we tap on it, mouseenter compat event
+ // is NOT fired) and after a timeout (to allow for mouse compatibility
+ // events to fire) we explicitly restart cycling
+ this.pause();
+
+ if (this.touchTimeout) {
+ clearTimeout(this.touchTimeout);
}
+
+ this.touchTimeout = setTimeout(event => this.cycle(event), TOUCHEVENT_COMPAT_WAIT + this._config.interval);
}
+ };
+
+ SelectorEngine.find(SELECTOR_ITEM_IMG, this._element).forEach(itemImg => {
+ EventHandler.on(itemImg, EVENT_DRAG_START, e => e.preventDefault());
});
- result.push(modifier);
+
+ if (this._pointerEvent) {
+ EventHandler.on(this._element, EVENT_POINTERDOWN, event => start(event));
+ EventHandler.on(this._element, EVENT_POINTERUP, event => end(event));
+
+ this._element.classList.add(CLASS_NAME_POINTER_EVENT);
+ } else {
+ EventHandler.on(this._element, EVENT_TOUCHSTART, event => start(event));
+ EventHandler.on(this._element, EVENT_TOUCHMOVE, event => move(event));
+ EventHandler.on(this._element, EVENT_TOUCHEND, event => end(event));
+ }
}
- modifiers.forEach(function (modifier) {
- if (!visited.has(modifier.name)) {
- // check for visited object
- sort(modifier);
+ _keydown(event) {
+ if (/input|textarea/i.test(event.target.tagName)) {
+ return;
}
- });
- return result;
- }
- function orderModifiers(modifiers) {
- // order based on dependencies
- var orderedModifiers = order(modifiers); // order based on phase
+ const direction = KEY_TO_DIRECTION[event.key];
- return modifierPhases.reduce(function (acc, phase) {
- return acc.concat(orderedModifiers.filter(function (modifier) {
- return modifier.phase === phase;
- }));
- }, []);
- }
+ if (direction) {
+ event.preventDefault();
- function debounce$1(fn) {
- var pending;
- return function () {
- if (!pending) {
- pending = new Promise(function (resolve) {
- Promise.resolve().then(function () {
- pending = undefined;
- resolve(fn());
- });
- });
+ this._slide(direction);
}
+ }
- return pending;
- };
- }
-
- function mergeByName(modifiers) {
- var merged = modifiers.reduce(function (merged, current) {
- var existing = merged[current.name];
- merged[current.name] = existing ? Object.assign({}, existing, current, {
- options: Object.assign({}, existing.options, current.options),
- data: Object.assign({}, existing.data, current.data)
- }) : current;
- return merged;
- }, {}); // IE11 does not support Object.values
+ _getItemIndex(element) {
+ this._items = element && element.parentNode ? SelectorEngine.find(SELECTOR_ITEM, element.parentNode) : [];
+ return this._items.indexOf(element);
+ }
- return Object.keys(merged).map(function (key) {
- return merged[key];
- });
- }
+ _getItemByOrder(order, activeElement) {
+ const isNext = order === ORDER_NEXT;
+ return getNextActiveElement(this._items, activeElement, isNext, this._config.wrap);
+ }
- var DEFAULT_OPTIONS = {
- placement: 'bottom',
- modifiers: [],
- strategy: 'absolute'
- };
+ _triggerSlideEvent(relatedTarget, eventDirectionName) {
+ const targetIndex = this._getItemIndex(relatedTarget);
- function areValidElements() {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
+ const fromIndex = this._getItemIndex(SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element));
- return !args.some(function (element) {
- return !(element && typeof element.getBoundingClientRect === 'function');
- });
- }
-
- function popperGenerator(generatorOptions) {
- if (generatorOptions === void 0) {
- generatorOptions = {};
+ return EventHandler.trigger(this._element, EVENT_SLIDE, {
+ relatedTarget,
+ direction: eventDirectionName,
+ from: fromIndex,
+ to: targetIndex
+ });
}
- var _generatorOptions = generatorOptions,
- _generatorOptions$def = _generatorOptions.defaultModifiers,
- defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,
- _generatorOptions$def2 = _generatorOptions.defaultOptions,
- defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;
- return function createPopper(reference, popper, options) {
- if (options === void 0) {
- options = defaultOptions;
- }
+ _setActiveIndicatorElement(element) {
+ if (this._indicatorsElement) {
+ const activeIndicator = SelectorEngine.findOne(SELECTOR_ACTIVE$1, this._indicatorsElement);
+ activeIndicator.classList.remove(CLASS_NAME_ACTIVE$2);
+ activeIndicator.removeAttribute('aria-current');
+ const indicators = SelectorEngine.find(SELECTOR_INDICATOR, this._indicatorsElement);
- var state = {
- placement: 'bottom',
- orderedModifiers: [],
- options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),
- modifiersData: {},
- elements: {
- reference: reference,
- popper: popper
- },
- attributes: {},
- styles: {}
- };
- var effectCleanupFns = [];
- var isDestroyed = false;
- var instance = {
- state: state,
- setOptions: function setOptions(options) {
- cleanupModifierEffects();
- state.options = Object.assign({}, defaultOptions, state.options, options);
- state.scrollParents = {
- reference: isElement$1(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],
- popper: listScrollParents(popper)
- }; // Orders the modifiers based on their dependencies and `phase`
- // properties
+ for (let i = 0; i < indicators.length; i++) {
+ if (Number.parseInt(indicators[i].getAttribute('data-bs-slide-to'), 10) === this._getItemIndex(element)) {
+ indicators[i].classList.add(CLASS_NAME_ACTIVE$2);
+ indicators[i].setAttribute('aria-current', 'true');
+ break;
+ }
+ }
+ }
+ }
- var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers
+ _updateInterval() {
+ const element = this._activeElement || SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element);
- state.orderedModifiers = orderedModifiers.filter(function (m) {
- return m.enabled;
- }); // Validate the provided modifiers so that the consumer will get warned
+ if (!element) {
+ return;
+ }
- runModifierEffects();
- return instance.update();
- },
- // Sync update – it will always be executed, even if not necessary. This
- // is useful for low frequency updates where sync behavior simplifies the
- // logic.
- // For high frequency updates (e.g. `resize` and `scroll` events), always
- // prefer the async Popper#update method
- forceUpdate: function forceUpdate() {
- if (isDestroyed) {
- return;
- }
+ const elementInterval = Number.parseInt(element.getAttribute('data-bs-interval'), 10);
- var _state$elements = state.elements,
- reference = _state$elements.reference,
- popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements
- // anymore
+ if (elementInterval) {
+ this._config.defaultInterval = this._config.defaultInterval || this._config.interval;
+ this._config.interval = elementInterval;
+ } else {
+ this._config.interval = this._config.defaultInterval || this._config.interval;
+ }
+ }
- if (!areValidElements(reference, popper)) {
+ _slide(directionOrOrder, element) {
+ const order = this._directionToOrder(directionOrOrder);
- return;
- } // Store the reference and popper rects to be read by modifiers
+ const activeElement = SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element);
+ const activeElementIndex = this._getItemIndex(activeElement);
- state.rects = {
- reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'),
- popper: getLayoutRect(popper)
- }; // Modifiers have the ability to reset the current update cycle. The
- // most common use case for this is the `flip` modifier changing the
- // placement, which then needs to re-run all the modifiers, because the
- // logic was previously ran for the previous placement and is therefore
- // stale/incorrect
+ const nextElement = element || this._getItemByOrder(order, activeElement);
- state.reset = false;
- state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier
- // is filled with the initial data specified by the modifier. This means
- // it doesn't persist and is fresh on each update.
- // To ensure persistent data, use `${name}#persistent`
+ const nextElementIndex = this._getItemIndex(nextElement);
- state.orderedModifiers.forEach(function (modifier) {
- return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);
- });
+ const isCycling = Boolean(this._interval);
+ const isNext = order === ORDER_NEXT;
+ const directionalClassName = isNext ? CLASS_NAME_START : CLASS_NAME_END;
+ const orderClassName = isNext ? CLASS_NAME_NEXT : CLASS_NAME_PREV;
- for (var index = 0; index < state.orderedModifiers.length; index++) {
+ const eventDirectionName = this._orderToDirection(order);
- if (state.reset === true) {
- state.reset = false;
- index = -1;
- continue;
- }
+ if (nextElement && nextElement.classList.contains(CLASS_NAME_ACTIVE$2)) {
+ this._isSliding = false;
+ return;
+ }
- var _state$orderedModifie = state.orderedModifiers[index],
- fn = _state$orderedModifie.fn,
- _state$orderedModifie2 = _state$orderedModifie.options,
- _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,
- name = _state$orderedModifie.name;
+ if (this._isSliding) {
+ return;
+ }
- if (typeof fn === 'function') {
- state = fn({
- state: state,
- options: _options,
- name: name,
- instance: instance
- }) || state;
- }
- }
- },
- // Async and optimistically optimized update – it will not be executed if
- // not necessary (debounced to run at most once-per-tick)
- update: debounce$1(function () {
- return new Promise(function (resolve) {
- instance.forceUpdate();
- resolve(state);
- });
- }),
- destroy: function destroy() {
- cleanupModifierEffects();
- isDestroyed = true;
- }
- };
+ const slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName);
- if (!areValidElements(reference, popper)) {
+ if (slideEvent.defaultPrevented) {
+ return;
+ }
- return instance;
+ if (!activeElement || !nextElement) {
+ // Some weirdness is happening, so we bail
+ return;
}
- instance.setOptions(options).then(function (state) {
- if (!isDestroyed && options.onFirstUpdate) {
- options.onFirstUpdate(state);
- }
- }); // Modifiers have the ability to execute arbitrary code before the first
- // update cycle runs. They will be executed in the same order as the update
- // cycle. This is useful when a modifier adds some persistent data that
- // other modifiers need to use, but the modifier is run after the dependent
- // one.
+ this._isSliding = true;
- function runModifierEffects() {
- state.orderedModifiers.forEach(function (_ref3) {
- var name = _ref3.name,
- _ref3$options = _ref3.options,
- options = _ref3$options === void 0 ? {} : _ref3$options,
- effect = _ref3.effect;
+ if (isCycling) {
+ this.pause();
+ }
- if (typeof effect === 'function') {
- var cleanupFn = effect({
- state: state,
- name: name,
- instance: instance,
- options: options
- });
+ this._setActiveIndicatorElement(nextElement);
- var noopFn = function noopFn() {};
+ this._activeElement = nextElement;
- effectCleanupFns.push(cleanupFn || noopFn);
- }
+ const triggerSlidEvent = () => {
+ EventHandler.trigger(this._element, EVENT_SLID, {
+ relatedTarget: nextElement,
+ direction: eventDirectionName,
+ from: activeElementIndex,
+ to: nextElementIndex
});
+ };
+
+ if (this._element.classList.contains(CLASS_NAME_SLIDE)) {
+ nextElement.classList.add(orderClassName);
+ reflow(nextElement);
+ activeElement.classList.add(directionalClassName);
+ nextElement.classList.add(directionalClassName);
+
+ const completeCallBack = () => {
+ nextElement.classList.remove(directionalClassName, orderClassName);
+ nextElement.classList.add(CLASS_NAME_ACTIVE$2);
+ activeElement.classList.remove(CLASS_NAME_ACTIVE$2, orderClassName, directionalClassName);
+ this._isSliding = false;
+ setTimeout(triggerSlidEvent, 0);
+ };
+
+ this._queueCallback(completeCallBack, activeElement, true);
+ } else {
+ activeElement.classList.remove(CLASS_NAME_ACTIVE$2);
+ nextElement.classList.add(CLASS_NAME_ACTIVE$2);
+ this._isSliding = false;
+ triggerSlidEvent();
}
- function cleanupModifierEffects() {
- effectCleanupFns.forEach(function (fn) {
- return fn();
- });
- effectCleanupFns = [];
+ if (isCycling) {
+ this.cycle();
}
+ }
- return instance;
- };
- }
- var createPopper$2 = /*#__PURE__*/popperGenerator(); // eslint-disable-next-line import/no-unused-modules
+ _directionToOrder(direction) {
+ if (![DIRECTION_RIGHT, DIRECTION_LEFT].includes(direction)) {
+ return direction;
+ }
- var defaultModifiers$1 = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1];
- var createPopper$1 = /*#__PURE__*/popperGenerator({
- defaultModifiers: defaultModifiers$1
- }); // eslint-disable-next-line import/no-unused-modules
+ if (isRTL()) {
+ return direction === DIRECTION_LEFT ? ORDER_PREV : ORDER_NEXT;
+ }
- var defaultModifiers = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1, offset$1, flip$1, preventOverflow$1, arrow$1, hide$1];
- var createPopper = /*#__PURE__*/popperGenerator({
- defaultModifiers: defaultModifiers
- }); // eslint-disable-next-line import/no-unused-modules
+ return direction === DIRECTION_LEFT ? ORDER_NEXT : ORDER_PREV;
+ }
- var Popper = /*#__PURE__*/Object.freeze({
- __proto__: null,
- popperGenerator: popperGenerator,
- detectOverflow: detectOverflow,
- createPopperBase: createPopper$2,
- createPopper: createPopper,
- createPopperLite: createPopper$1,
- top: top,
- bottom: bottom,
- right: right,
- left: left,
- auto: auto,
- basePlacements: basePlacements,
- start: start,
- end: end,
- clippingParents: clippingParents,
- viewport: viewport,
- popper: popper,
- reference: reference,
- variationPlacements: variationPlacements,
- placements: placements,
- beforeRead: beforeRead,
- read: read,
- afterRead: afterRead,
- beforeMain: beforeMain,
- main: main,
- afterMain: afterMain,
- beforeWrite: beforeWrite,
- write: write,
- afterWrite: afterWrite,
- modifierPhases: modifierPhases,
- applyStyles: applyStyles$1,
- arrow: arrow$1,
- computeStyles: computeStyles$1,
- eventListeners: eventListeners,
- flip: flip$1,
- hide: hide$1,
- offset: offset$1,
- popperOffsets: popperOffsets$1,
- preventOverflow: preventOverflow$1
- });
+ _orderToDirection(order) {
+ if (![ORDER_NEXT, ORDER_PREV].includes(order)) {
+ return order;
+ }
- /*!
- * Bootstrap v5.0.2 (https://getbootstrap.com/)
- * Copyright 2011-2021 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
- */
+ if (isRTL()) {
+ return order === ORDER_PREV ? DIRECTION_LEFT : DIRECTION_RIGHT;
+ }
- /**
- * --------------------------------------------------------------------------
- * Bootstrap (v5.0.2): dom/selector-engine.js
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
- * --------------------------------------------------------------------------
- */
+ return order === ORDER_PREV ? DIRECTION_RIGHT : DIRECTION_LEFT;
+ } // Static
- /**
- * ------------------------------------------------------------------------
- * Constants
- * ------------------------------------------------------------------------
- */
- const NODE_TEXT = 3;
- const SelectorEngine = {
- find(selector, element = document.documentElement) {
- return [].concat(...Element.prototype.querySelectorAll.call(element, selector));
- },
- findOne(selector, element = document.documentElement) {
- return Element.prototype.querySelector.call(element, selector);
- },
+ static carouselInterface(element, config) {
+ const data = Carousel.getOrCreateInstance(element, config);
+ let {
+ _config
+ } = data;
- children(element, selector) {
- return [].concat(...element.children).filter(child => child.matches(selector));
- },
+ if (typeof config === 'object') {
+ _config = { ..._config,
+ ...config
+ };
+ }
- parents(element, selector) {
- const parents = [];
- let ancestor = element.parentNode;
+ const action = typeof config === 'string' ? config : _config.slide;
- while (ancestor && ancestor.nodeType === Node.ELEMENT_NODE && ancestor.nodeType !== NODE_TEXT) {
- if (ancestor.matches(selector)) {
- parents.push(ancestor);
+ if (typeof config === 'number') {
+ data.to(config);
+ } else if (typeof action === 'string') {
+ if (typeof data[action] === 'undefined') {
+ throw new TypeError(`No method named "${action}"`);
}
- ancestor = ancestor.parentNode;
+ data[action]();
+ } else if (_config.interval && _config.ride) {
+ data.pause();
+ data.cycle();
}
+ }
- return parents;
- },
-
- prev(element, selector) {
- let previous = element.previousElementSibling;
+ static jQueryInterface(config) {
+ return this.each(function () {
+ Carousel.carouselInterface(this, config);
+ });
+ }
- while (previous) {
- if (previous.matches(selector)) {
- return [previous];
- }
+ static dataApiClickHandler(event) {
+ const target = getElementFromSelector(this);
- previous = previous.previousElementSibling;
+ if (!target || !target.classList.contains(CLASS_NAME_CAROUSEL)) {
+ return;
}
- return [];
- },
+ const config = { ...Manipulator.getDataAttributes(target),
+ ...Manipulator.getDataAttributes(this)
+ };
+ const slideIndex = this.getAttribute('data-bs-slide-to');
- next(element, selector) {
- let next = element.nextElementSibling;
+ if (slideIndex) {
+ config.interval = false;
+ }
- while (next) {
- if (next.matches(selector)) {
- return [next];
- }
+ Carousel.carouselInterface(target, config);
- next = next.nextElementSibling;
+ if (slideIndex) {
+ Carousel.getInstance(target).to(slideIndex);
}
- return [];
+ event.preventDefault();
}
- };
-
+ }
/**
- * --------------------------------------------------------------------------
- * Bootstrap (v5.0.2): util/index.js
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
- * --------------------------------------------------------------------------
+ * ------------------------------------------------------------------------
+ * Data Api implementation
+ * ------------------------------------------------------------------------
*/
- const MAX_UID = 1000000;
- const MILLISECONDS_MULTIPLIER = 1000;
- const TRANSITION_END = 'transitionend'; // Shoutout AngusCroll (https://goo.gl/pxwQGp)
- const toType = obj => {
- if (obj === null || obj === undefined) {
- return `${obj}`;
+ EventHandler.on(document, EVENT_CLICK_DATA_API$5, SELECTOR_DATA_SLIDE, Carousel.dataApiClickHandler);
+ EventHandler.on(window, EVENT_LOAD_DATA_API$2, () => {
+ const carousels = SelectorEngine.find(SELECTOR_DATA_RIDE);
+
+ for (let i = 0, len = carousels.length; i < len; i++) {
+ Carousel.carouselInterface(carousels[i], Carousel.getInstance(carousels[i]));
}
+ });
+ /**
+ * ------------------------------------------------------------------------
+ * jQuery
+ * ------------------------------------------------------------------------
+ * add .Carousel to jQuery only if jQuery is present
+ */
+
+ defineJQueryPlugin(Carousel);
- return {}.toString.call(obj).match(/\s([a-z]+)/i)[1].toLowerCase();
- };
/**
* --------------------------------------------------------------------------
- * Public Util Api
+ * Bootstrap (v5.0.2): collapse.js
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* --------------------------------------------------------------------------
*/
+ /**
+ * ------------------------------------------------------------------------
+ * Constants
+ * ------------------------------------------------------------------------
+ */
-
- const getUID = prefix => {
- do {
- prefix += Math.floor(Math.random() * MAX_UID);
- } while (document.getElementById(prefix));
-
- return prefix;
+ const NAME$9 = 'collapse';
+ const DATA_KEY$8 = 'bs.collapse';
+ const EVENT_KEY$8 = `.${DATA_KEY$8}`;
+ const DATA_API_KEY$5 = '.data-api';
+ const Default$8 = {
+ toggle: true,
+ parent: ''
};
+ const DefaultType$8 = {
+ toggle: 'boolean',
+ parent: '(string|element)'
+ };
+ const EVENT_SHOW$5 = `show${EVENT_KEY$8}`;
+ const EVENT_SHOWN$5 = `shown${EVENT_KEY$8}`;
+ const EVENT_HIDE$5 = `hide${EVENT_KEY$8}`;
+ const EVENT_HIDDEN$5 = `hidden${EVENT_KEY$8}`;
+ const EVENT_CLICK_DATA_API$4 = `click${EVENT_KEY$8}${DATA_API_KEY$5}`;
+ const CLASS_NAME_SHOW$8 = 'show';
+ const CLASS_NAME_COLLAPSE = 'collapse';
+ const CLASS_NAME_COLLAPSING = 'collapsing';
+ const CLASS_NAME_COLLAPSED = 'collapsed';
+ const WIDTH = 'width';
+ const HEIGHT = 'height';
+ const SELECTOR_ACTIVES = '.show, .collapsing';
+ const SELECTOR_DATA_TOGGLE$4 = '[data-bs-toggle="collapse"]';
+ /**
+ * ------------------------------------------------------------------------
+ * Class Definition
+ * ------------------------------------------------------------------------
+ */
- const getSelector = element => {
- let selector = element.getAttribute('data-bs-target');
-
- if (!selector || selector === '#') {
- let hrefAttr = element.getAttribute('href'); // The only valid content that could double as a selector are IDs or classes,
- // so everything starting with `#` or `.`. If a "real" URL is used as the selector,
- // `document.querySelector` will rightfully complain it is invalid.
- // See https://github.com/twbs/bootstrap/issues/32273
+ class Collapse$1 extends BaseComponent {
+ constructor(element, config) {
+ super(element);
+ this._isTransitioning = false;
+ this._config = this._getConfig(config);
+ this._triggerArray = SelectorEngine.find(`${SELECTOR_DATA_TOGGLE$4}[href="#${this._element.id}"],` + `${SELECTOR_DATA_TOGGLE$4}[data-bs-target="#${this._element.id}"]`);
+ const toggleList = SelectorEngine.find(SELECTOR_DATA_TOGGLE$4);
- if (!hrefAttr || !hrefAttr.includes('#') && !hrefAttr.startsWith('.')) {
- return null;
- } // Just in case some CMS puts out a full URL with the anchor appended
+ for (let i = 0, len = toggleList.length; i < len; i++) {
+ const elem = toggleList[i];
+ const selector = getSelectorFromElement(elem);
+ const filterElement = SelectorEngine.find(selector).filter(foundElem => foundElem === this._element);
+ if (selector !== null && filterElement.length) {
+ this._selector = selector;
- if (hrefAttr.includes('#') && !hrefAttr.startsWith('#')) {
- hrefAttr = `#${hrefAttr.split('#')[1]}`;
+ this._triggerArray.push(elem);
+ }
}
- selector = hrefAttr && hrefAttr !== '#' ? hrefAttr.trim() : null;
+ this._parent = this._config.parent ? this._getParent() : null;
+
+ if (!this._config.parent) {
+ this._addAriaAndCollapsedClass(this._element, this._triggerArray);
+ }
+
+ if (this._config.toggle) {
+ this.toggle();
+ }
+ } // Getters
+
+
+ static get Default() {
+ return Default$8;
}
- return selector;
- };
+ static get NAME() {
+ return NAME$9;
+ } // Public
- const getSelectorFromElement = element => {
- const selector = getSelector(element);
- if (selector) {
- return document.querySelector(selector) ? selector : null;
+ toggle() {
+ if (this._element.classList.contains(CLASS_NAME_SHOW$8)) {
+ this.hide();
+ } else {
+ this.show();
+ }
}
- return null;
- };
+ show() {
+ if (this._isTransitioning || this._element.classList.contains(CLASS_NAME_SHOW$8)) {
+ return;
+ }
- const getElementFromSelector = element => {
- const selector = getSelector(element);
- return selector ? document.querySelector(selector) : null;
- };
+ let actives;
+ let activesData;
- const getTransitionDurationFromElement = element => {
- if (!element) {
- return 0;
- } // Get transition-duration of the element
+ if (this._parent) {
+ actives = SelectorEngine.find(SELECTOR_ACTIVES, this._parent).filter(elem => {
+ if (typeof this._config.parent === 'string') {
+ return elem.getAttribute('data-bs-parent') === this._config.parent;
+ }
+ return elem.classList.contains(CLASS_NAME_COLLAPSE);
+ });
- let {
- transitionDuration,
- transitionDelay
- } = window.getComputedStyle(element);
- const floatTransitionDuration = Number.parseFloat(transitionDuration);
- const floatTransitionDelay = Number.parseFloat(transitionDelay); // Return 0 if element or transition duration is not found
+ if (actives.length === 0) {
+ actives = null;
+ }
+ }
- if (!floatTransitionDuration && !floatTransitionDelay) {
- return 0;
- } // If multiple durations are defined, take the first
+ const container = SelectorEngine.findOne(this._selector);
+ if (actives) {
+ const tempActiveData = actives.find(elem => container !== elem);
+ activesData = tempActiveData ? Collapse$1.getInstance(tempActiveData) : null;
- transitionDuration = transitionDuration.split(',')[0];
- transitionDelay = transitionDelay.split(',')[0];
- return (Number.parseFloat(transitionDuration) + Number.parseFloat(transitionDelay)) * MILLISECONDS_MULTIPLIER;
- };
+ if (activesData && activesData._isTransitioning) {
+ return;
+ }
+ }
- const triggerTransitionEnd = element => {
- element.dispatchEvent(new Event(TRANSITION_END));
- };
+ const startEvent = EventHandler.trigger(this._element, EVENT_SHOW$5);
- const isElement = obj => {
- if (!obj || typeof obj !== 'object') {
- return false;
- }
+ if (startEvent.defaultPrevented) {
+ return;
+ }
- if (typeof obj.jquery !== 'undefined') {
- obj = obj[0];
- }
+ if (actives) {
+ actives.forEach(elemActive => {
+ if (container !== elemActive) {
+ Collapse$1.collapseInterface(elemActive, 'hide');
+ }
- return typeof obj.nodeType !== 'undefined';
- };
+ if (!activesData) {
+ Data.set(elemActive, DATA_KEY$8, null);
+ }
+ });
+ }
- const getElement = obj => {
- if (isElement(obj)) {
- // it's a jQuery object or a node element
- return obj.jquery ? obj[0] : obj;
- }
+ const dimension = this._getDimension();
- if (typeof obj === 'string' && obj.length > 0) {
- return SelectorEngine.findOne(obj);
- }
+ this._element.classList.remove(CLASS_NAME_COLLAPSE);
- return null;
- };
+ this._element.classList.add(CLASS_NAME_COLLAPSING);
- const typeCheckConfig = (componentName, config, configTypes) => {
- Object.keys(configTypes).forEach(property => {
- const expectedTypes = configTypes[property];
- const value = config[property];
- const valueType = value && isElement(value) ? 'element' : toType(value);
+ this._element.style[dimension] = 0;
- if (!new RegExp(expectedTypes).test(valueType)) {
- throw new TypeError(`${componentName.toUpperCase()}: Option "${property}" provided type "${valueType}" but expected type "${expectedTypes}".`);
+ if (this._triggerArray.length) {
+ this._triggerArray.forEach(element => {
+ element.classList.remove(CLASS_NAME_COLLAPSED);
+ element.setAttribute('aria-expanded', true);
+ });
}
- });
- };
- const isVisible = element => {
- if (!isElement(element) || element.getClientRects().length === 0) {
- return false;
- }
+ this.setTransitioning(true);
- return getComputedStyle(element).getPropertyValue('visibility') === 'visible';
- };
+ const complete = () => {
+ this._element.classList.remove(CLASS_NAME_COLLAPSING);
- const isDisabled = element => {
- if (!element || element.nodeType !== Node.ELEMENT_NODE) {
- return true;
- }
+ this._element.classList.add(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$8);
- if (element.classList.contains('disabled')) {
- return true;
- }
+ this._element.style[dimension] = '';
+ this.setTransitioning(false);
+ EventHandler.trigger(this._element, EVENT_SHOWN$5);
+ };
- if (typeof element.disabled !== 'undefined') {
- return element.disabled;
+ const capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1);
+ const scrollSize = `scroll${capitalizedDimension}`;
+
+ this._queueCallback(complete, this._element, true);
+
+ this._element.style[dimension] = `${this._element[scrollSize]}px`;
}
- return element.hasAttribute('disabled') && element.getAttribute('disabled') !== 'false';
- };
+ hide() {
+ if (this._isTransitioning || !this._element.classList.contains(CLASS_NAME_SHOW$8)) {
+ return;
+ }
- const findShadowRoot = element => {
- if (!document.documentElement.attachShadow) {
- return null;
- } // Can find the shadow root otherwise it'll return the document
+ const startEvent = EventHandler.trigger(this._element, EVENT_HIDE$5);
+ if (startEvent.defaultPrevented) {
+ return;
+ }
- if (typeof element.getRootNode === 'function') {
- const root = element.getRootNode();
- return root instanceof ShadowRoot ? root : null;
- }
+ const dimension = this._getDimension();
- if (element instanceof ShadowRoot) {
- return element;
- } // when we don't find a shadow root
+ this._element.style[dimension] = `${this._element.getBoundingClientRect()[dimension]}px`;
+ reflow(this._element);
+ this._element.classList.add(CLASS_NAME_COLLAPSING);
- if (!element.parentNode) {
- return null;
- }
+ this._element.classList.remove(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$8);
- return findShadowRoot(element.parentNode);
- };
+ const triggerArrayLength = this._triggerArray.length;
- const noop = () => {};
+ if (triggerArrayLength > 0) {
+ for (let i = 0; i < triggerArrayLength; i++) {
+ const trigger = this._triggerArray[i];
+ const elem = getElementFromSelector(trigger);
- const reflow = element => element.offsetHeight;
+ if (elem && !elem.classList.contains(CLASS_NAME_SHOW$8)) {
+ trigger.classList.add(CLASS_NAME_COLLAPSED);
+ trigger.setAttribute('aria-expanded', false);
+ }
+ }
+ }
- const getjQuery = () => {
- const {
- jQuery
- } = window;
+ this.setTransitioning(true);
- if (jQuery && !document.body.hasAttribute('data-bs-no-jquery')) {
- return jQuery;
- }
+ const complete = () => {
+ this.setTransitioning(false);
- return null;
- };
+ this._element.classList.remove(CLASS_NAME_COLLAPSING);
- const DOMContentLoadedCallbacks = [];
+ this._element.classList.add(CLASS_NAME_COLLAPSE);
- const onDOMContentLoaded = callback => {
- if (document.readyState === 'loading') {
- // add listener on the first call when the document is in loading state
- if (!DOMContentLoadedCallbacks.length) {
- document.addEventListener('DOMContentLoaded', () => {
- DOMContentLoadedCallbacks.forEach(callback => callback());
- });
- }
+ EventHandler.trigger(this._element, EVENT_HIDDEN$5);
+ };
- DOMContentLoadedCallbacks.push(callback);
- } else {
- callback();
+ this._element.style[dimension] = '';
+
+ this._queueCallback(complete, this._element, true);
}
- };
- const isRTL = () => document.documentElement.dir === 'rtl';
+ setTransitioning(isTransitioning) {
+ this._isTransitioning = isTransitioning;
+ } // Private
- const defineJQueryPlugin = plugin => {
- onDOMContentLoaded(() => {
- const $ = getjQuery();
- /* istanbul ignore if */
- if ($) {
- const name = plugin.NAME;
- const JQUERY_NO_CONFLICT = $.fn[name];
- $.fn[name] = plugin.jQueryInterface;
- $.fn[name].Constructor = plugin;
+ _getConfig(config) {
+ config = { ...Default$8,
+ ...config
+ };
+ config.toggle = Boolean(config.toggle); // Coerce string values
- $.fn[name].noConflict = () => {
- $.fn[name] = JQUERY_NO_CONFLICT;
- return plugin.jQueryInterface;
- };
- }
- });
- };
-
- const execute = callback => {
- if (typeof callback === 'function') {
- callback();
+ typeCheckConfig(NAME$9, config, DefaultType$8);
+ return config;
}
- };
- const executeAfterTransition = (callback, transitionElement, waitForTransition = true) => {
- if (!waitForTransition) {
- execute(callback);
- return;
+ _getDimension() {
+ return this._element.classList.contains(WIDTH) ? WIDTH : HEIGHT;
}
- const durationPadding = 5;
- const emulatedDuration = getTransitionDurationFromElement(transitionElement) + durationPadding;
- let called = false;
+ _getParent() {
+ let {
+ parent
+ } = this._config;
+ parent = getElement(parent);
+ const selector = `${SELECTOR_DATA_TOGGLE$4}[data-bs-parent="${parent}"]`;
+ SelectorEngine.find(selector, parent).forEach(element => {
+ const selected = getElementFromSelector(element);
- const handler = ({
- target
- }) => {
- if (target !== transitionElement) {
+ this._addAriaAndCollapsedClass(selected, [element]);
+ });
+ return parent;
+ }
+
+ _addAriaAndCollapsedClass(element, triggerArray) {
+ if (!element || !triggerArray.length) {
return;
}
- called = true;
- transitionElement.removeEventListener(TRANSITION_END, handler);
- execute(callback);
- };
+ const isOpen = element.classList.contains(CLASS_NAME_SHOW$8);
+ triggerArray.forEach(elem => {
+ if (isOpen) {
+ elem.classList.remove(CLASS_NAME_COLLAPSED);
+ } else {
+ elem.classList.add(CLASS_NAME_COLLAPSED);
+ }
- transitionElement.addEventListener(TRANSITION_END, handler);
- setTimeout(() => {
- if (!called) {
- triggerTransitionEnd(transitionElement);
+ elem.setAttribute('aria-expanded', isOpen);
+ });
+ } // Static
+
+
+ static collapseInterface(element, config) {
+ let data = Collapse$1.getInstance(element);
+ const _config = { ...Default$8,
+ ...Manipulator.getDataAttributes(element),
+ ...(typeof config === 'object' && config ? config : {})
+ };
+
+ if (!data && _config.toggle && typeof config === 'string' && /show|hide/.test(config)) {
+ _config.toggle = false;
}
- }, emulatedDuration);
- };
- /**
- * Return the previous/next element of a list.
- *
- * @param {array} list The list of elements
- * @param activeElement The active element
- * @param shouldGetNext Choose to get next or previous element
- * @param isCycleAllowed
- * @return {Element|elem} The proper element
- */
+ if (!data) {
+ data = new Collapse$1(element, _config);
+ }
- const getNextActiveElement = (list, activeElement, shouldGetNext, isCycleAllowed) => {
- let index = list.indexOf(activeElement); // if the element does not exist in the list return an element depending on the direction and if cycle is allowed
+ if (typeof config === 'string') {
+ if (typeof data[config] === 'undefined') {
+ throw new TypeError(`No method named "${config}"`);
+ }
- if (index === -1) {
- return list[!shouldGetNext && isCycleAllowed ? list.length - 1 : 0];
+ data[config]();
+ }
}
- const listLength = list.length;
- index += shouldGetNext ? 1 : -1;
+ static jQueryInterface(config) {
+ return this.each(function () {
+ Collapse$1.collapseInterface(this, config);
+ });
+ }
- if (isCycleAllowed) {
- index = (index + listLength) % listLength;
+ }
+ /**
+ * ------------------------------------------------------------------------
+ * Data Api implementation
+ * ------------------------------------------------------------------------
+ */
+
+
+ EventHandler.on(document, EVENT_CLICK_DATA_API$4, SELECTOR_DATA_TOGGLE$4, function (event) {
+ // preventDefault only for <a> elements (which change the URL) not inside the collapsible element
+ if (event.target.tagName === 'A' || event.delegateTarget && event.delegateTarget.tagName === 'A') {
+ event.preventDefault();
}
- return list[Math.max(0, Math.min(index, listLength - 1))];
- };
+ const triggerData = Manipulator.getDataAttributes(this);
+ const selector = getSelectorFromElement(this);
+ const selectorElements = SelectorEngine.find(selector);
+ selectorElements.forEach(element => {
+ const data = Collapse$1.getInstance(element);
+ let config;
+
+ if (data) {
+ // update parent attribute
+ if (data._parent === null && typeof triggerData.parent === 'string') {
+ data._config.parent = triggerData.parent;
+ data._parent = data._getParent();
+ }
+
+ config = 'toggle';
+ } else {
+ config = triggerData;
+ }
+
+ Collapse$1.collapseInterface(element, config);
+ });
+ });
+ /**
+ * ------------------------------------------------------------------------
+ * jQuery
+ * ------------------------------------------------------------------------
+ * add .Collapse to jQuery only if jQuery is present
+ */
+
+ defineJQueryPlugin(Collapse$1);
/**
* --------------------------------------------------------------------------
- * Bootstrap (v5.0.2): dom/event-handler.js
+ * Bootstrap (v5.0.2): dropdown.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* --------------------------------------------------------------------------
*/
@@ -5262,491 +3830,444 @@
* ------------------------------------------------------------------------
*/
- const namespaceRegex = /[^.]*(?=\..*)\.|.*/;
- const stripNameRegex = /\..*/;
- const stripUidRegex = /::\d+$/;
- const eventRegistry = {}; // Events storage
+ const NAME$8 = 'dropdown';
+ const DATA_KEY$7 = 'bs.dropdown';
+ const EVENT_KEY$7 = `.${DATA_KEY$7}`;
+ const DATA_API_KEY$4 = '.data-api';
+ const ESCAPE_KEY$2 = 'Escape';
+ const SPACE_KEY = 'Space';
+ const TAB_KEY = 'Tab';
+ const ARROW_UP_KEY = 'ArrowUp';
+ const ARROW_DOWN_KEY = 'ArrowDown';
+ const RIGHT_MOUSE_BUTTON = 2; // MouseEvent.button value for the secondary button, usually the right button
- let uidEvent = 1;
- const customEvents = {
- mouseenter: 'mouseover',
- mouseleave: 'mouseout'
+ const REGEXP_KEYDOWN = new RegExp(`${ARROW_UP_KEY}|${ARROW_DOWN_KEY}|${ESCAPE_KEY$2}`);
+ const EVENT_HIDE$4 = `hide${EVENT_KEY$7}`;
+ const EVENT_HIDDEN$4 = `hidden${EVENT_KEY$7}`;
+ const EVENT_SHOW$4 = `show${EVENT_KEY$7}`;
+ const EVENT_SHOWN$4 = `shown${EVENT_KEY$7}`;
+ const EVENT_CLICK = `click${EVENT_KEY$7}`;
+ const EVENT_CLICK_DATA_API$3 = `click${EVENT_KEY$7}${DATA_API_KEY$4}`;
+ const EVENT_KEYDOWN_DATA_API = `keydown${EVENT_KEY$7}${DATA_API_KEY$4}`;
+ const EVENT_KEYUP_DATA_API = `keyup${EVENT_KEY$7}${DATA_API_KEY$4}`;
+ const CLASS_NAME_SHOW$7 = 'show';
+ const CLASS_NAME_DROPUP = 'dropup';
+ const CLASS_NAME_DROPEND = 'dropend';
+ const CLASS_NAME_DROPSTART = 'dropstart';
+ const CLASS_NAME_NAVBAR = 'navbar';
+ const SELECTOR_DATA_TOGGLE$3 = '[data-bs-toggle="dropdown"]';
+ const SELECTOR_MENU = '.dropdown-menu';
+ const SELECTOR_NAVBAR_NAV = '.navbar-nav';
+ const SELECTOR_VISIBLE_ITEMS = '.dropdown-menu .dropdown-item:not(.disabled):not(:disabled)';
+ const PLACEMENT_TOP = isRTL() ? 'top-end' : 'top-start';
+ const PLACEMENT_TOPEND = isRTL() ? 'top-start' : 'top-end';
+ const PLACEMENT_BOTTOM = isRTL() ? 'bottom-end' : 'bottom-start';
+ const PLACEMENT_BOTTOMEND = isRTL() ? 'bottom-start' : 'bottom-end';
+ const PLACEMENT_RIGHT = isRTL() ? 'left-start' : 'right-start';
+ const PLACEMENT_LEFT = isRTL() ? 'right-start' : 'left-start';
+ const Default$7 = {
+ offset: [0, 2],
+ boundary: 'clippingParents',
+ reference: 'toggle',
+ display: 'dynamic',
+ popperConfig: null,
+ autoClose: true
+ };
+ const DefaultType$7 = {
+ offset: '(array|string|function)',
+ boundary: '(string|element)',
+ reference: '(string|element|object)',
+ display: 'string',
+ popperConfig: '(null|object|function)',
+ autoClose: '(boolean|string)'
};
- const customEventsRegex = /^(mouseenter|mouseleave)/i;
- const nativeEvents = new Set(['click', 'dblclick', 'mouseup', 'mousedown', 'contextmenu', 'mousewheel', 'DOMMouseScroll', 'mouseover', 'mouseout', 'mousemove', 'selectstart', 'selectend', 'keydown', 'keypress', 'keyup', 'orientationchange', 'touchstart', 'touchmove', 'touchend', 'touchcancel', 'pointerdown', 'pointermove', 'pointerup', 'pointerleave', 'pointercancel', 'gesturestart', 'gesturechange', 'gestureend', 'focus', 'blur', 'change', 'reset', 'select', 'submit', 'focusin', 'focu [...]
/**
* ------------------------------------------------------------------------
- * Private methods
+ * Class Definition
* ------------------------------------------------------------------------
*/
- function getUidEvent(element, uid) {
- return uid && `${uid}::${uidEvent++}` || element.uidEvent || uidEvent++;
- }
+ class Dropdown$1 extends BaseComponent {
+ constructor(element, config) {
+ super(element);
+ this._popper = null;
+ this._config = this._getConfig(config);
+ this._menu = this._getMenuElement();
+ this._inNavbar = this._detectNavbar();
- function getEvent(element) {
- const uid = getUidEvent(element);
- element.uidEvent = uid;
- eventRegistry[uid] = eventRegistry[uid] || {};
- return eventRegistry[uid];
- }
+ this._addEventListeners();
+ } // Getters
- function bootstrapHandler(element, fn) {
- return function handler(event) {
- event.delegateTarget = element;
- if (handler.oneOff) {
- EventHandler.off(element, event.type, fn);
- }
+ static get Default() {
+ return Default$7;
+ }
- return fn.apply(element, [event]);
- };
- }
+ static get DefaultType() {
+ return DefaultType$7;
+ }
- function bootstrapDelegationHandler(element, selector, fn) {
- return function handler(event) {
- const domElements = element.querySelectorAll(selector);
+ static get NAME() {
+ return NAME$8;
+ } // Public
- for (let {
- target
- } = event; target && target !== this; target = target.parentNode) {
- for (let i = domElements.length; i--;) {
- if (domElements[i] === target) {
- event.delegateTarget = target;
- if (handler.oneOff) {
- // eslint-disable-next-line unicorn/consistent-destructuring
- EventHandler.off(element, event.type, selector, fn);
- }
-
- return fn.apply(target, [event]);
- }
- }
- } // To please ESLint
-
-
- return null;
- };
- }
-
- function findHandler(events, handler, delegationSelector = null) {
- const uidEventList = Object.keys(events);
-
- for (let i = 0, len = uidEventList.length; i < len; i++) {
- const event = events[uidEventList[i]];
-
- if (event.originalHandler === handler && event.delegationSelector === delegationSelector) {
- return event;
+ toggle() {
+ if (isDisabled(this._element)) {
+ return;
}
- }
- return null;
- }
+ const isActive = this._element.classList.contains(CLASS_NAME_SHOW$7);
- function normalizeParams(originalTypeEvent, handler, delegationFn) {
- const delegation = typeof handler === 'string';
- const originalHandler = delegation ? delegationFn : handler;
- let typeEvent = getTypeEvent(originalTypeEvent);
- const isNative = nativeEvents.has(typeEvent);
+ if (isActive) {
+ this.hide();
+ return;
+ }
- if (!isNative) {
- typeEvent = originalTypeEvent;
+ this.show();
}
- return [delegation, originalHandler, typeEvent];
- }
-
- function addHandler(element, originalTypeEvent, handler, delegationFn, oneOff) {
- if (typeof originalTypeEvent !== 'string' || !element) {
- return;
- }
+ show() {
+ if (isDisabled(this._element) || this._menu.classList.contains(CLASS_NAME_SHOW$7)) {
+ return;
+ }
- if (!handler) {
- handler = delegationFn;
- delegationFn = null;
- } // in case of mouseenter or mouseleave wrap the handler within a function that checks for its DOM position
- // this prevents the handler from being dispatched the same way as mouseover or mouseout does
+ const parent = Dropdown$1.getParentFromElement(this._element);
+ const relatedTarget = {
+ relatedTarget: this._element
+ };
+ const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$4, relatedTarget);
+ if (showEvent.defaultPrevented) {
+ return;
+ } // Totally disable Popper for Dropdowns in Navbar
- if (customEventsRegex.test(originalTypeEvent)) {
- const wrapFn = fn => {
- return function (event) {
- if (!event.relatedTarget || event.relatedTarget !== event.delegateTarget && !event.delegateTarget.contains(event.relatedTarget)) {
- return fn.call(this, event);
- }
- };
- };
- if (delegationFn) {
- delegationFn = wrapFn(delegationFn);
+ if (this._inNavbar) {
+ Manipulator.setDataAttribute(this._menu, 'popper', 'none');
} else {
- handler = wrapFn(handler);
- }
- }
+ if (typeof Popper === 'undefined') {
+ throw new TypeError('Bootstrap\'s dropdowns require Popper (https://popper.js.org)');
+ }
- const [delegation, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn);
- const events = getEvent(element);
- const handlers = events[typeEvent] || (events[typeEvent] = {});
- const previousFn = findHandler(handlers, originalHandler, delegation ? handler : null);
+ let referenceElement = this._element;
- if (previousFn) {
- previousFn.oneOff = previousFn.oneOff && oneOff;
- return;
- }
+ if (this._config.reference === 'parent') {
+ referenceElement = parent;
+ } else if (isElement(this._config.reference)) {
+ referenceElement = getElement(this._config.reference);
+ } else if (typeof this._config.reference === 'object') {
+ referenceElement = this._config.reference;
+ }
- const uid = getUidEvent(originalHandler, originalTypeEvent.replace(namespaceRegex, ''));
- const fn = delegation ? bootstrapDelegationHandler(element, handler, delegationFn) : bootstrapHandler(element, handler);
- fn.delegationSelector = delegation ? handler : null;
- fn.originalHandler = originalHandler;
- fn.oneOff = oneOff;
- fn.uidEvent = uid;
- handlers[uid] = fn;
- element.addEventListener(typeEvent, fn, delegation);
- }
+ const popperConfig = this._getPopperConfig();
- function removeHandler(element, events, typeEvent, handler, delegationSelector) {
- const fn = findHandler(events[typeEvent], handler, delegationSelector);
+ const isDisplayStatic = popperConfig.modifiers.find(modifier => modifier.name === 'applyStyles' && modifier.enabled === false);
+ this._popper = createPopper(referenceElement, this._menu, popperConfig);
- if (!fn) {
- return;
- }
+ if (isDisplayStatic) {
+ Manipulator.setDataAttribute(this._menu, 'popper', 'static');
+ }
+ } // If this is a touch-enabled device we add extra
+ // empty mouseover listeners to the body's immediate children;
+ // only needed because of broken event delegation on iOS
+ // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
- element.removeEventListener(typeEvent, fn, Boolean(delegationSelector));
- delete events[typeEvent][fn.uidEvent];
- }
- function removeNamespacedHandlers(element, events, typeEvent, namespace) {
- const storeElementEvent = events[typeEvent] || {};
- Object.keys(storeElementEvent).forEach(handlerKey => {
- if (handlerKey.includes(namespace)) {
- const event = storeElementEvent[handlerKey];
- removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector);
+ if ('ontouchstart' in document.documentElement && !parent.closest(SELECTOR_NAVBAR_NAV)) {
+ [].concat(...document.body.children).forEach(elem => EventHandler.on(elem, 'mouseover', noop));
}
- });
- }
-
- function getTypeEvent(event) {
- // allow to get the native events from namespaced events ('click.bs.button' --> 'click')
- event = event.replace(stripNameRegex, '');
- return customEvents[event] || event;
- }
- const EventHandler = {
- on(element, event, handler, delegationFn) {
- addHandler(element, event, handler, delegationFn, false);
- },
+ this._element.focus();
- one(element, event, handler, delegationFn) {
- addHandler(element, event, handler, delegationFn, true);
- },
+ this._element.setAttribute('aria-expanded', true);
- off(element, originalTypeEvent, handler, delegationFn) {
- if (typeof originalTypeEvent !== 'string' || !element) {
- return;
- }
+ this._menu.classList.toggle(CLASS_NAME_SHOW$7);
- const [delegation, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn);
- const inNamespace = typeEvent !== originalTypeEvent;
- const events = getEvent(element);
- const isNamespace = originalTypeEvent.startsWith('.');
+ this._element.classList.toggle(CLASS_NAME_SHOW$7);
- if (typeof originalHandler !== 'undefined') {
- // Simplest case: handler is passed, remove that listener ONLY.
- if (!events || !events[typeEvent]) {
- return;
- }
+ EventHandler.trigger(this._element, EVENT_SHOWN$4, relatedTarget);
+ }
- removeHandler(element, events, typeEvent, originalHandler, delegation ? handler : null);
+ hide() {
+ if (isDisabled(this._element) || !this._menu.classList.contains(CLASS_NAME_SHOW$7)) {
return;
}
- if (isNamespace) {
- Object.keys(events).forEach(elementEvent => {
- removeNamespacedHandlers(element, events, elementEvent, originalTypeEvent.slice(1));
- });
+ const relatedTarget = {
+ relatedTarget: this._element
+ };
+
+ this._completeHide(relatedTarget);
+ }
+
+ dispose() {
+ if (this._popper) {
+ this._popper.destroy();
}
- const storeElementEvent = events[typeEvent] || {};
- Object.keys(storeElementEvent).forEach(keyHandlers => {
- const handlerKey = keyHandlers.replace(stripUidRegex, '');
+ super.dispose();
+ }
- if (!inNamespace || originalTypeEvent.includes(handlerKey)) {
- const event = storeElementEvent[keyHandlers];
- removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector);
- }
- });
- },
+ update() {
+ this._inNavbar = this._detectNavbar();
- trigger(element, event, args) {
- if (typeof event !== 'string' || !element) {
- return null;
+ if (this._popper) {
+ this._popper.update();
}
+ } // Private
- const $ = getjQuery();
- const typeEvent = getTypeEvent(event);
- const inNamespace = event !== typeEvent;
- const isNative = nativeEvents.has(typeEvent);
- let jQueryEvent;
- let bubbles = true;
- let nativeDispatch = true;
- let defaultPrevented = false;
- let evt = null;
- if (inNamespace && $) {
- jQueryEvent = $.Event(event, args);
- $(element).trigger(jQueryEvent);
- bubbles = !jQueryEvent.isPropagationStopped();
- nativeDispatch = !jQueryEvent.isImmediatePropagationStopped();
- defaultPrevented = jQueryEvent.isDefaultPrevented();
- }
+ _addEventListeners() {
+ EventHandler.on(this._element, EVENT_CLICK, event => {
+ event.preventDefault();
+ this.toggle();
+ });
+ }
- if (isNative) {
- evt = document.createEvent('HTMLEvents');
- evt.initEvent(typeEvent, bubbles, true);
- } else {
- evt = new CustomEvent(event, {
- bubbles,
- cancelable: true
- });
- } // merge custom information in our event
+ _completeHide(relatedTarget) {
+ const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$4, relatedTarget);
+ if (hideEvent.defaultPrevented) {
+ return;
+ } // If this is a touch-enabled device we remove the extra
+ // empty mouseover listeners we added for iOS support
- if (typeof args !== 'undefined') {
- Object.keys(args).forEach(key => {
- Object.defineProperty(evt, key, {
- get() {
- return args[key];
- }
- });
- });
+ if ('ontouchstart' in document.documentElement) {
+ [].concat(...document.body.children).forEach(elem => EventHandler.off(elem, 'mouseover', noop));
}
- if (defaultPrevented) {
- evt.preventDefault();
+ if (this._popper) {
+ this._popper.destroy();
}
- if (nativeDispatch) {
- element.dispatchEvent(evt);
- }
+ this._menu.classList.remove(CLASS_NAME_SHOW$7);
- if (evt.defaultPrevented && typeof jQueryEvent !== 'undefined') {
- jQueryEvent.preventDefault();
- }
+ this._element.classList.remove(CLASS_NAME_SHOW$7);
- return evt;
- }
+ this._element.setAttribute('aria-expanded', 'false');
- };
+ Manipulator.removeDataAttribute(this._menu, 'popper');
+ EventHandler.trigger(this._element, EVENT_HIDDEN$4, relatedTarget);
+ }
- /**
- * --------------------------------------------------------------------------
- * Bootstrap (v5.0.2): dom/data.js
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
- * --------------------------------------------------------------------------
- */
+ _getConfig(config) {
+ config = { ...this.constructor.Default,
+ ...Manipulator.getDataAttributes(this._element),
+ ...config
+ };
+ typeCheckConfig(NAME$8, config, this.constructor.DefaultType);
- /**
- * ------------------------------------------------------------------------
- * Constants
- * ------------------------------------------------------------------------
- */
- const elementMap = new Map();
- var Data = {
- set(element, key, instance) {
- if (!elementMap.has(element)) {
- elementMap.set(element, new Map());
+ if (typeof config.reference === 'object' && !isElement(config.reference) && typeof config.reference.getBoundingClientRect !== 'function') {
+ // Popper virtual elements require a getBoundingClientRect method
+ throw new TypeError(`${NAME$8.toUpperCase()}: Option "reference" provided type "object" without a required "getBoundingClientRect" method.`);
}
- const instanceMap = elementMap.get(element); // make it clear we only want one instance per element
- // can be removed later when multiple key/instances are fine to be used
+ return config;
+ }
- if (!instanceMap.has(key) && instanceMap.size !== 0) {
- // eslint-disable-next-line no-console
- console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(instanceMap.keys())[0]}.`);
- return;
- }
+ _getMenuElement() {
+ return SelectorEngine.next(this._element, SELECTOR_MENU)[0];
+ }
- instanceMap.set(key, instance);
- },
+ _getPlacement() {
+ const parentDropdown = this._element.parentNode;
- get(element, key) {
- if (elementMap.has(element)) {
- return elementMap.get(element).get(key) || null;
+ if (parentDropdown.classList.contains(CLASS_NAME_DROPEND)) {
+ return PLACEMENT_RIGHT;
}
- return null;
- },
+ if (parentDropdown.classList.contains(CLASS_NAME_DROPSTART)) {
+ return PLACEMENT_LEFT;
+ } // We need to trim the value because custom properties can also include spaces
- remove(element, key) {
- if (!elementMap.has(element)) {
- return;
- }
- const instanceMap = elementMap.get(element);
- instanceMap.delete(key); // free up element references if there are no instances left for an element
+ const isEnd = getComputedStyle(this._menu).getPropertyValue('--bs-position').trim() === 'end';
- if (instanceMap.size === 0) {
- elementMap.delete(element);
+ if (parentDropdown.classList.contains(CLASS_NAME_DROPUP)) {
+ return isEnd ? PLACEMENT_TOPEND : PLACEMENT_TOP;
}
- }
- };
+ return isEnd ? PLACEMENT_BOTTOMEND : PLACEMENT_BOTTOM;
+ }
- /**
- * --------------------------------------------------------------------------
- * Bootstrap (v5.0.2): base-component.js
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
- * --------------------------------------------------------------------------
- */
- /**
- * ------------------------------------------------------------------------
- * Constants
- * ------------------------------------------------------------------------
- */
+ _detectNavbar() {
+ return this._element.closest(`.${CLASS_NAME_NAVBAR}`) !== null;
+ }
- const VERSION = '5.0.2';
+ _getOffset() {
+ const {
+ offset
+ } = this._config;
- class BaseComponent {
- constructor(element) {
- element = getElement(element);
+ if (typeof offset === 'string') {
+ return offset.split(',').map(val => Number.parseInt(val, 10));
+ }
- if (!element) {
- return;
+ if (typeof offset === 'function') {
+ return popperData => offset(popperData, this._element);
}
- this._element = element;
- Data.set(this._element, this.constructor.DATA_KEY, this);
+ return offset;
}
- dispose() {
- Data.remove(this._element, this.constructor.DATA_KEY);
- EventHandler.off(this._element, this.constructor.EVENT_KEY);
- Object.getOwnPropertyNames(this).forEach(propertyName => {
- this[propertyName] = null;
- });
- }
+ _getPopperConfig() {
+ const defaultBsPopperConfig = {
+ placement: this._getPlacement(),
+ modifiers: [{
+ name: 'preventOverflow',
+ options: {
+ boundary: this._config.boundary
+ }
+ }, {
+ name: 'offset',
+ options: {
+ offset: this._getOffset()
+ }
+ }]
+ }; // Disable Popper if we have a static display
- _queueCallback(callback, element, isAnimated = true) {
- executeAfterTransition(callback, element, isAnimated);
+ if (this._config.display === 'static') {
+ defaultBsPopperConfig.modifiers = [{
+ name: 'applyStyles',
+ enabled: false
+ }];
+ }
+
+ return { ...defaultBsPopperConfig,
+ ...(typeof this._config.popperConfig === 'function' ? this._config.popperConfig(defaultBsPopperConfig) : this._config.popperConfig)
+ };
}
- /** Static */
+ _selectMenuItem({
+ key,
+ target
+ }) {
+ const items = SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu).filter(isVisible);
- static getInstance(element) {
- return Data.get(element, this.DATA_KEY);
- }
+ if (!items.length) {
+ return;
+ } // if target isn't included in items (e.g. when expanding the dropdown)
+ // allow cycling to get the last item in case key equals ARROW_UP_KEY
- static getOrCreateInstance(element, config = {}) {
- return this.getInstance(element) || new this(element, typeof config === 'object' ? config : null);
- }
- static get VERSION() {
- return VERSION;
- }
+ getNextActiveElement(items, target, key === ARROW_DOWN_KEY, !items.includes(target)).focus();
+ } // Static
- static get NAME() {
- throw new Error('You have to implement the static method "NAME", for each component!');
- }
- static get DATA_KEY() {
- return `bs.${this.NAME}`;
+ static dropdownInterface(element, config) {
+ const data = Dropdown$1.getOrCreateInstance(element, config);
+
+ if (typeof config === 'string') {
+ if (typeof data[config] === 'undefined') {
+ throw new TypeError(`No method named "${config}"`);
+ }
+
+ data[config]();
+ }
}
- static get EVENT_KEY() {
- return `.${this.DATA_KEY}`;
+ static jQueryInterface(config) {
+ return this.each(function () {
+ Dropdown$1.dropdownInterface(this, config);
+ });
}
- }
+ static clearMenus(event) {
+ if (event && (event.button === RIGHT_MOUSE_BUTTON || event.type === 'keyup' && event.key !== TAB_KEY)) {
+ return;
+ }
- /**
- * --------------------------------------------------------------------------
- * Bootstrap (v5.0.2): alert.js
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
- * --------------------------------------------------------------------------
- */
- /**
- * ------------------------------------------------------------------------
- * Constants
- * ------------------------------------------------------------------------
- */
+ const toggles = SelectorEngine.find(SELECTOR_DATA_TOGGLE$3);
- const NAME$c = 'alert';
- const DATA_KEY$b = 'bs.alert';
- const EVENT_KEY$b = `.${DATA_KEY$b}`;
- const DATA_API_KEY$8 = '.data-api';
- const SELECTOR_DISMISS = '[data-bs-dismiss="alert"]';
- const EVENT_CLOSE = `close${EVENT_KEY$b}`;
- const EVENT_CLOSED = `closed${EVENT_KEY$b}`;
- const EVENT_CLICK_DATA_API$7 = `click${EVENT_KEY$b}${DATA_API_KEY$8}`;
- const CLASS_NAME_ALERT = 'alert';
- const CLASS_NAME_FADE$6 = 'fade';
- const CLASS_NAME_SHOW$9 = 'show';
- /**
- * ------------------------------------------------------------------------
- * Class Definition
- * ------------------------------------------------------------------------
- */
+ for (let i = 0, len = toggles.length; i < len; i++) {
+ const context = Dropdown$1.getInstance(toggles[i]);
- class Alert extends BaseComponent {
- // Getters
- static get NAME() {
- return NAME$c;
- } // Public
+ if (!context || context._config.autoClose === false) {
+ continue;
+ }
+ if (!context._element.classList.contains(CLASS_NAME_SHOW$7)) {
+ continue;
+ }
- close(element) {
- const rootElement = element ? this._getRootElement(element) : this._element;
+ const relatedTarget = {
+ relatedTarget: context._element
+ };
- const customEvent = this._triggerCloseEvent(rootElement);
+ if (event) {
+ const composedPath = event.composedPath();
+ const isMenuTarget = composedPath.includes(context._menu);
- if (customEvent === null || customEvent.defaultPrevented) {
- return;
- }
+ if (composedPath.includes(context._element) || context._config.autoClose === 'inside' && !isMenuTarget || context._config.autoClose === 'outside' && isMenuTarget) {
+ continue;
+ } // Tab navigation through the dropdown menu or events from contained inputs shouldn't close the menu
- this._removeElement(rootElement);
- } // Private
+ if (context._menu.contains(event.target) && (event.type === 'keyup' && event.key === TAB_KEY || /input|select|option|textarea|form/i.test(event.target.tagName))) {
+ continue;
+ }
- _getRootElement(element) {
- return getElementFromSelector(element) || element.closest(`.${CLASS_NAME_ALERT}`);
- }
+ if (event.type === 'click') {
+ relatedTarget.clickEvent = event;
+ }
+ }
- _triggerCloseEvent(element) {
- return EventHandler.trigger(element, EVENT_CLOSE);
+ context._completeHide(relatedTarget);
+ }
}
- _removeElement(element) {
- element.classList.remove(CLASS_NAME_SHOW$9);
- const isAnimated = element.classList.contains(CLASS_NAME_FADE$6);
-
- this._queueCallback(() => this._destroyElement(element), element, isAnimated);
+ static getParentFromElement(element) {
+ return getElementFromSelector(element) || element.parentNode;
}
- _destroyElement(element) {
- element.remove();
- EventHandler.trigger(element, EVENT_CLOSED);
- } // Static
+ static dataApiKeydownHandler(event) {
+ // If not input/textarea:
+ // - And not a key in REGEXP_KEYDOWN => not a dropdown command
+ // If input/textarea:
+ // - If space key => not a dropdown command
+ // - If key is other than escape
+ // - If key is not up or down => not a dropdown command
+ // - If trigger inside the menu => not a dropdown command
+ if (/input|textarea/i.test(event.target.tagName) ? event.key === SPACE_KEY || event.key !== ESCAPE_KEY$2 && (event.key !== ARROW_DOWN_KEY && event.key !== ARROW_UP_KEY || event.target.closest(SELECTOR_MENU)) : !REGEXP_KEYDOWN.test(event.key)) {
+ return;
+ }
+ const isActive = this.classList.contains(CLASS_NAME_SHOW$7);
- static jQueryInterface(config) {
- return this.each(function () {
- const data = Alert.getOrCreateInstance(this);
+ if (!isActive && event.key === ESCAPE_KEY$2) {
+ return;
+ }
- if (config === 'close') {
- data[config](this);
- }
- });
- }
+ event.preventDefault();
+ event.stopPropagation();
- static handleDismiss(alertInstance) {
- return function (event) {
- if (event) {
- event.preventDefault();
+ if (isDisabled(this)) {
+ return;
+ }
+
+ const getToggleButton = () => this.matches(SELECTOR_DATA_TOGGLE$3) ? this : SelectorEngine.prev(this, SELECTOR_DATA_TOGGLE$3)[0];
+
+ if (event.key === ESCAPE_KEY$2) {
+ getToggleButton().focus();
+ Dropdown$1.clearMenus();
+ return;
+ }
+
+ if (event.key === ARROW_UP_KEY || event.key === ARROW_DOWN_KEY) {
+ if (!isActive) {
+ getToggleButton().click();
}
- alertInstance.close(this);
- };
+ Dropdown$1.getInstance(getToggleButton())._selectMenuItem(event);
+
+ return;
+ }
+
+ if (!isActive || event.key === SPACE_KEY) {
+ Dropdown$1.clearMenus();
+ }
}
}
@@ -5757,1013 +4278,900 @@
*/
- EventHandler.on(document, EVENT_CLICK_DATA_API$7, SELECTOR_DISMISS, Alert.handleDismiss(new Alert()));
+ EventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_DATA_TOGGLE$3, Dropdown$1.dataApiKeydownHandler);
+ EventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_MENU, Dropdown$1.dataApiKeydownHandler);
+ EventHandler.on(document, EVENT_CLICK_DATA_API$3, Dropdown$1.clearMenus);
+ EventHandler.on(document, EVENT_KEYUP_DATA_API, Dropdown$1.clearMenus);
+ EventHandler.on(document, EVENT_CLICK_DATA_API$3, SELECTOR_DATA_TOGGLE$3, function (event) {
+ event.preventDefault();
+ Dropdown$1.dropdownInterface(this);
+ });
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
- * add .Alert to jQuery only if jQuery is present
+ * add .Dropdown to jQuery only if jQuery is present
*/
- defineJQueryPlugin(Alert);
+ defineJQueryPlugin(Dropdown$1);
/**
* --------------------------------------------------------------------------
- * Bootstrap (v5.0.2): button.js
+ * Bootstrap (v5.0.2): util/scrollBar.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* --------------------------------------------------------------------------
*/
- /**
- * ------------------------------------------------------------------------
- * Constants
- * ------------------------------------------------------------------------
- */
+ const SELECTOR_FIXED_CONTENT = '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top';
+ const SELECTOR_STICKY_CONTENT = '.sticky-top';
- const NAME$b = 'button';
- const DATA_KEY$a = 'bs.button';
- const EVENT_KEY$a = `.${DATA_KEY$a}`;
- const DATA_API_KEY$7 = '.data-api';
- const CLASS_NAME_ACTIVE$3 = 'active';
- const SELECTOR_DATA_TOGGLE$5 = '[data-bs-toggle="button"]';
- const EVENT_CLICK_DATA_API$6 = `click${EVENT_KEY$a}${DATA_API_KEY$7}`;
- /**
- * ------------------------------------------------------------------------
- * Class Definition
- * ------------------------------------------------------------------------
- */
+ class ScrollBarHelper {
+ constructor() {
+ this._element = document.body;
+ }
- class Button extends BaseComponent {
- // Getters
- static get NAME() {
- return NAME$b;
- } // Public
+ getWidth() {
+ // https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth#usage_notes
+ const documentWidth = document.documentElement.clientWidth;
+ return Math.abs(window.innerWidth - documentWidth);
+ }
+ hide() {
+ const width = this.getWidth();
- toggle() {
- // Toggle class and sync the `aria-pressed` attribute with the return value of the `.toggle()` method
- this._element.setAttribute('aria-pressed', this._element.classList.toggle(CLASS_NAME_ACTIVE$3));
- } // Static
+ this._disableOverFlow(); // give padding to element to balance the hidden scrollbar width
- static jQueryInterface(config) {
- return this.each(function () {
- const data = Button.getOrCreateInstance(this);
+ this._setElementAttributes(this._element, 'paddingRight', calculatedValue => calculatedValue + width); // trick: We adjust positive paddingRight and negative marginRight to sticky-top elements to keep showing fullwidth
- if (config === 'toggle') {
- data[config]();
- }
- });
+
+ this._setElementAttributes(SELECTOR_FIXED_CONTENT, 'paddingRight', calculatedValue => calculatedValue + width);
+
+ this._setElementAttributes(SELECTOR_STICKY_CONTENT, 'marginRight', calculatedValue => calculatedValue - width);
}
- }
- /**
- * ------------------------------------------------------------------------
- * Data Api implementation
- * ------------------------------------------------------------------------
- */
+ _disableOverFlow() {
+ this._saveInitialAttribute(this._element, 'overflow');
+ this._element.style.overflow = 'hidden';
+ }
- EventHandler.on(document, EVENT_CLICK_DATA_API$6, SELECTOR_DATA_TOGGLE$5, event => {
- event.preventDefault();
- const button = event.target.closest(SELECTOR_DATA_TOGGLE$5);
- const data = Button.getOrCreateInstance(button);
- data.toggle();
- });
- /**
- * ------------------------------------------------------------------------
- * jQuery
- * ------------------------------------------------------------------------
- * add .Button to jQuery only if jQuery is present
- */
+ _setElementAttributes(selector, styleProp, callback) {
+ const scrollbarWidth = this.getWidth();
- defineJQueryPlugin(Button);
+ const manipulationCallBack = element => {
+ if (element !== this._element && window.innerWidth > element.clientWidth + scrollbarWidth) {
+ return;
+ }
- /**
- * --------------------------------------------------------------------------
- * Bootstrap (v5.0.2): dom/manipulator.js
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
- * --------------------------------------------------------------------------
- */
- function normalizeData(val) {
- if (val === 'true') {
- return true;
- }
+ this._saveInitialAttribute(element, styleProp);
- if (val === 'false') {
- return false;
- }
+ const calculatedValue = window.getComputedStyle(element)[styleProp];
+ element.style[styleProp] = `${callback(Number.parseFloat(calculatedValue))}px`;
+ };
- if (val === Number(val).toString()) {
- return Number(val);
+ this._applyManipulationCallback(selector, manipulationCallBack);
}
- if (val === '' || val === 'null') {
- return null;
- }
+ reset() {
+ this._resetElementAttributes(this._element, 'overflow');
- return val;
- }
+ this._resetElementAttributes(this._element, 'paddingRight');
- function normalizeDataKey(key) {
- return key.replace(/[A-Z]/g, chr => `-${chr.toLowerCase()}`);
- }
+ this._resetElementAttributes(SELECTOR_FIXED_CONTENT, 'paddingRight');
- const Manipulator = {
- setDataAttribute(element, key, value) {
- element.setAttribute(`data-bs-${normalizeDataKey(key)}`, value);
- },
+ this._resetElementAttributes(SELECTOR_STICKY_CONTENT, 'marginRight');
+ }
- removeDataAttribute(element, key) {
- element.removeAttribute(`data-bs-${normalizeDataKey(key)}`);
- },
+ _saveInitialAttribute(element, styleProp) {
+ const actualValue = element.style[styleProp];
- getDataAttributes(element) {
- if (!element) {
- return {};
+ if (actualValue) {
+ Manipulator.setDataAttribute(element, styleProp, actualValue);
}
+ }
- const attributes = {};
- Object.keys(element.dataset).filter(key => key.startsWith('bs')).forEach(key => {
- let pureKey = key.replace(/^bs/, '');
- pureKey = pureKey.charAt(0).toLowerCase() + pureKey.slice(1, pureKey.length);
- attributes[pureKey] = normalizeData(element.dataset[key]);
- });
- return attributes;
- },
-
- getDataAttribute(element, key) {
- return normalizeData(element.getAttribute(`data-bs-${normalizeDataKey(key)}`));
- },
+ _resetElementAttributes(selector, styleProp) {
+ const manipulationCallBack = element => {
+ const value = Manipulator.getDataAttribute(element, styleProp);
- offset(element) {
- const rect = element.getBoundingClientRect();
- return {
- top: rect.top + document.body.scrollTop,
- left: rect.left + document.body.scrollLeft
+ if (typeof value === 'undefined') {
+ element.style.removeProperty(styleProp);
+ } else {
+ Manipulator.removeDataAttribute(element, styleProp);
+ element.style[styleProp] = value;
+ }
};
- },
- position(element) {
- return {
- top: element.offsetTop,
- left: element.offsetLeft
- };
+ this._applyManipulationCallback(selector, manipulationCallBack);
}
- };
+ _applyManipulationCallback(selector, callBack) {
+ if (isElement(selector)) {
+ callBack(selector);
+ } else {
+ SelectorEngine.find(selector, this._element).forEach(callBack);
+ }
+ }
+
+ isOverflowing() {
+ return this.getWidth() > 0;
+ }
+
+ }
/**
* --------------------------------------------------------------------------
- * Bootstrap (v5.0.2): carousel.js
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
+ * Bootstrap (v5.0.2): util/backdrop.js
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
- /**
- * ------------------------------------------------------------------------
- * Constants
- * ------------------------------------------------------------------------
- */
-
- const NAME$a = 'carousel';
- const DATA_KEY$9 = 'bs.carousel';
- const EVENT_KEY$9 = `.${DATA_KEY$9}`;
- const DATA_API_KEY$6 = '.data-api';
- const ARROW_LEFT_KEY = 'ArrowLeft';
- const ARROW_RIGHT_KEY = 'ArrowRight';
- const TOUCHEVENT_COMPAT_WAIT = 500; // Time for mouse compat events to fire after touch
-
- const SWIPE_THRESHOLD = 40;
- const Default$9 = {
- interval: 5000,
- keyboard: true,
- slide: false,
- pause: 'hover',
- wrap: true,
- touch: true
- };
- const DefaultType$9 = {
- interval: '(number|boolean)',
- keyboard: 'boolean',
- slide: '(boolean|string)',
- pause: '(string|boolean)',
- wrap: 'boolean',
- touch: 'boolean'
+ const Default$6 = {
+ isVisible: true,
+ // if false, we use the backdrop helper without adding any element to the dom
+ isAnimated: false,
+ rootElement: 'body',
+ // give the choice to place backdrop under different elements
+ clickCallback: null
};
- const ORDER_NEXT = 'next';
- const ORDER_PREV = 'prev';
- const DIRECTION_LEFT = 'left';
- const DIRECTION_RIGHT = 'right';
- const KEY_TO_DIRECTION = {
- [ARROW_LEFT_KEY]: DIRECTION_RIGHT,
- [ARROW_RIGHT_KEY]: DIRECTION_LEFT
+ const DefaultType$6 = {
+ isVisible: 'boolean',
+ isAnimated: 'boolean',
+ rootElement: '(element|string)',
+ clickCallback: '(function|null)'
};
- const EVENT_SLIDE = `slide${EVENT_KEY$9}`;
- const EVENT_SLID = `slid${EVENT_KEY$9}`;
- const EVENT_KEYDOWN = `keydown${EVENT_KEY$9}`;
- const EVENT_MOUSEENTER = `mouseenter${EVENT_KEY$9}`;
- const EVENT_MOUSELEAVE = `mouseleave${EVENT_KEY$9}`;
- const EVENT_TOUCHSTART = `touchstart${EVENT_KEY$9}`;
- const EVENT_TOUCHMOVE = `touchmove${EVENT_KEY$9}`;
- const EVENT_TOUCHEND = `touchend${EVENT_KEY$9}`;
- const EVENT_POINTERDOWN = `pointerdown${EVENT_KEY$9}`;
- const EVENT_POINTERUP = `pointerup${EVENT_KEY$9}`;
- const EVENT_DRAG_START = `dragstart${EVENT_KEY$9}`;
- const EVENT_LOAD_DATA_API$2 = `load${EVENT_KEY$9}${DATA_API_KEY$6}`;
- const EVENT_CLICK_DATA_API$5 = `click${EVENT_KEY$9}${DATA_API_KEY$6}`;
- const CLASS_NAME_CAROUSEL = 'carousel';
- const CLASS_NAME_ACTIVE$2 = 'active';
- const CLASS_NAME_SLIDE = 'slide';
- const CLASS_NAME_END = 'carousel-item-end';
- const CLASS_NAME_START = 'carousel-item-start';
- const CLASS_NAME_NEXT = 'carousel-item-next';
- const CLASS_NAME_PREV = 'carousel-item-prev';
- const CLASS_NAME_POINTER_EVENT = 'pointer-event';
- const SELECTOR_ACTIVE$1 = '.active';
- const SELECTOR_ACTIVE_ITEM = '.active.carousel-item';
- const SELECTOR_ITEM = '.carousel-item';
- const SELECTOR_ITEM_IMG = '.carousel-item img';
- const SELECTOR_NEXT_PREV = '.carousel-item-next, .carousel-item-prev';
- const SELECTOR_INDICATORS = '.carousel-indicators';
- const SELECTOR_INDICATOR = '[data-bs-target]';
- const SELECTOR_DATA_SLIDE = '[data-bs-slide], [data-bs-slide-to]';
- const SELECTOR_DATA_RIDE = '[data-bs-ride="carousel"]';
- const POINTER_TYPE_TOUCH = 'touch';
- const POINTER_TYPE_PEN = 'pen';
- /**
- * ------------------------------------------------------------------------
- * Class Definition
- * ------------------------------------------------------------------------
- */
+ const NAME$7 = 'backdrop';
+ const CLASS_NAME_BACKDROP = 'modal-backdrop';
+ const CLASS_NAME_FADE$5 = 'fade';
+ const CLASS_NAME_SHOW$6 = 'show';
+ const EVENT_MOUSEDOWN = `mousedown.bs.${NAME$7}`;
- class Carousel extends BaseComponent {
- constructor(element, config) {
- super(element);
- this._items = null;
- this._interval = null;
- this._activeElement = null;
- this._isPaused = false;
- this._isSliding = false;
- this.touchTimeout = null;
- this.touchStartX = 0;
- this.touchDeltaX = 0;
+ class Backdrop {
+ constructor(config) {
this._config = this._getConfig(config);
- this._indicatorsElement = SelectorEngine.findOne(SELECTOR_INDICATORS, this._element);
- this._touchSupported = 'ontouchstart' in document.documentElement || navigator.maxTouchPoints > 0;
- this._pointerEvent = Boolean(window.PointerEvent);
-
- this._addEventListeners();
- } // Getters
-
-
- static get Default() {
- return Default$9;
- }
-
- static get NAME() {
- return NAME$a;
- } // Public
-
-
- next() {
- this._slide(ORDER_NEXT);
+ this._isAppended = false;
+ this._element = null;
}
- nextWhenVisible() {
- // Don't call next when the page isn't visible
- // or the carousel or its parent isn't visible
- if (!document.hidden && isVisible(this._element)) {
- this.next();
+ show(callback) {
+ if (!this._config.isVisible) {
+ execute(callback);
+ return;
}
- }
- prev() {
- this._slide(ORDER_PREV);
- }
+ this._append();
- pause(event) {
- if (!event) {
- this._isPaused = true;
+ if (this._config.isAnimated) {
+ reflow(this._getElement());
}
- if (SelectorEngine.findOne(SELECTOR_NEXT_PREV, this._element)) {
- triggerTransitionEnd(this._element);
- this.cycle(true);
- }
+ this._getElement().classList.add(CLASS_NAME_SHOW$6);
- clearInterval(this._interval);
- this._interval = null;
+ this._emulateAnimation(() => {
+ execute(callback);
+ });
}
- cycle(event) {
- if (!event) {
- this._isPaused = false;
- }
-
- if (this._interval) {
- clearInterval(this._interval);
- this._interval = null;
+ hide(callback) {
+ if (!this._config.isVisible) {
+ execute(callback);
+ return;
}
- if (this._config && this._config.interval && !this._isPaused) {
- this._updateInterval();
-
- this._interval = setInterval((document.visibilityState ? this.nextWhenVisible : this.next).bind(this), this._config.interval);
- }
- }
+ this._getElement().classList.remove(CLASS_NAME_SHOW$6);
- to(index) {
- this._activeElement = SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element);
+ this._emulateAnimation(() => {
+ this.dispose();
+ execute(callback);
+ });
+ } // Private
- const activeIndex = this._getItemIndex(this._activeElement);
- if (index > this._items.length - 1 || index < 0) {
- return;
- }
+ _getElement() {
+ if (!this._element) {
+ const backdrop = document.createElement('div');
+ backdrop.className = CLASS_NAME_BACKDROP;
- if (this._isSliding) {
- EventHandler.one(this._element, EVENT_SLID, () => this.to(index));
- return;
- }
+ if (this._config.isAnimated) {
+ backdrop.classList.add(CLASS_NAME_FADE$5);
+ }
- if (activeIndex === index) {
- this.pause();
- this.cycle();
- return;
+ this._element = backdrop;
}
- const order = index > activeIndex ? ORDER_NEXT : ORDER_PREV;
-
- this._slide(order, this._items[index]);
- } // Private
-
+ return this._element;
+ }
_getConfig(config) {
- config = { ...Default$9,
- ...Manipulator.getDataAttributes(this._element),
+ config = { ...Default$6,
...(typeof config === 'object' ? config : {})
- };
- typeCheckConfig(NAME$a, config, DefaultType$9);
+ }; // use getElement() with the default "body" to get a fresh Element on each instantiation
+
+ config.rootElement = getElement(config.rootElement);
+ typeCheckConfig(NAME$7, config, DefaultType$6);
return config;
}
- _handleSwipe() {
- const absDeltax = Math.abs(this.touchDeltaX);
-
- if (absDeltax <= SWIPE_THRESHOLD) {
+ _append() {
+ if (this._isAppended) {
return;
}
- const direction = absDeltax / this.touchDeltaX;
- this.touchDeltaX = 0;
+ this._config.rootElement.appendChild(this._getElement());
- if (!direction) {
+ EventHandler.on(this._getElement(), EVENT_MOUSEDOWN, () => {
+ execute(this._config.clickCallback);
+ });
+ this._isAppended = true;
+ }
+
+ dispose() {
+ if (!this._isAppended) {
return;
}
- this._slide(direction > 0 ? DIRECTION_RIGHT : DIRECTION_LEFT);
- }
+ EventHandler.off(this._element, EVENT_MOUSEDOWN);
- _addEventListeners() {
- if (this._config.keyboard) {
- EventHandler.on(this._element, EVENT_KEYDOWN, event => this._keydown(event));
- }
+ this._element.remove();
- if (this._config.pause === 'hover') {
- EventHandler.on(this._element, EVENT_MOUSEENTER, event => this.pause(event));
- EventHandler.on(this._element, EVENT_MOUSELEAVE, event => this.cycle(event));
- }
+ this._isAppended = false;
+ }
- if (this._config.touch && this._touchSupported) {
- this._addTouchEventListeners();
- }
+ _emulateAnimation(callback) {
+ executeAfterTransition(callback, this._getElement(), this._config.isAnimated);
}
- _addTouchEventListeners() {
- const start = event => {
- if (this._pointerEvent && (event.pointerType === POINTER_TYPE_PEN || event.pointerType === POINTER_TYPE_TOUCH)) {
- this.touchStartX = event.clientX;
- } else if (!this._pointerEvent) {
- this.touchStartX = event.touches[0].clientX;
- }
- };
-
- const move = event => {
- // ensure swiping with one touch and not pinching
- this.touchDeltaX = event.touches && event.touches.length > 1 ? 0 : event.touches[0].clientX - this.touchStartX;
- };
+ }
- const end = event => {
- if (this._pointerEvent && (event.pointerType === POINTER_TYPE_PEN || event.pointerType === POINTER_TYPE_TOUCH)) {
- this.touchDeltaX = event.clientX - this.touchStartX;
- }
+ /**
+ * --------------------------------------------------------------------------
+ * Bootstrap (v5.0.2): modal.js
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
+ * --------------------------------------------------------------------------
+ */
+ /**
+ * ------------------------------------------------------------------------
+ * Constants
+ * ------------------------------------------------------------------------
+ */
- this._handleSwipe();
+ const NAME$6 = 'modal';
+ const DATA_KEY$6 = 'bs.modal';
+ const EVENT_KEY$6 = `.${DATA_KEY$6}`;
+ const DATA_API_KEY$3 = '.data-api';
+ const ESCAPE_KEY$1 = 'Escape';
+ const Default$5 = {
+ backdrop: true,
+ keyboard: true,
+ focus: true
+ };
+ const DefaultType$5 = {
+ backdrop: '(boolean|string)',
+ keyboard: 'boolean',
+ focus: 'boolean'
+ };
+ const EVENT_HIDE$3 = `hide${EVENT_KEY$6}`;
+ const EVENT_HIDE_PREVENTED = `hidePrevented${EVENT_KEY$6}`;
+ const EVENT_HIDDEN$3 = `hidden${EVENT_KEY$6}`;
+ const EVENT_SHOW$3 = `show${EVENT_KEY$6}`;
+ const EVENT_SHOWN$3 = `shown${EVENT_KEY$6}`;
+ const EVENT_FOCUSIN$2 = `focusin${EVENT_KEY$6}`;
+ const EVENT_RESIZE = `resize${EVENT_KEY$6}`;
+ const EVENT_CLICK_DISMISS$2 = `click.dismiss${EVENT_KEY$6}`;
+ const EVENT_KEYDOWN_DISMISS$1 = `keydown.dismiss${EVENT_KEY$6}`;
+ const EVENT_MOUSEUP_DISMISS = `mouseup.dismiss${EVENT_KEY$6}`;
+ const EVENT_MOUSEDOWN_DISMISS = `mousedown.dismiss${EVENT_KEY$6}`;
+ const EVENT_CLICK_DATA_API$2 = `click${EVENT_KEY$6}${DATA_API_KEY$3}`;
+ const CLASS_NAME_OPEN = 'modal-open';
+ const CLASS_NAME_FADE$4 = 'fade';
+ const CLASS_NAME_SHOW$5 = 'show';
+ const CLASS_NAME_STATIC = 'modal-static';
+ const SELECTOR_DIALOG = '.modal-dialog';
+ const SELECTOR_MODAL_BODY = '.modal-body';
+ const SELECTOR_DATA_TOGGLE$2 = '[data-bs-toggle="modal"]';
+ const SELECTOR_DATA_DISMISS$2 = '[data-bs-dismiss="modal"]';
+ /**
+ * ------------------------------------------------------------------------
+ * Class Definition
+ * ------------------------------------------------------------------------
+ */
- if (this._config.pause === 'hover') {
- // If it's a touch-enabled device, mouseenter/leave are fired as
- // part of the mouse compatibility events on first tap - the carousel
- // would stop cycling until user tapped out of it;
- // here, we listen for touchend, explicitly pause the carousel
- // (as if it's the second time we tap on it, mouseenter compat event
- // is NOT fired) and after a timeout (to allow for mouse compatibility
- // events to fire) we explicitly restart cycling
- this.pause();
+ class Modal extends BaseComponent {
+ constructor(element, config) {
+ super(element);
+ this._config = this._getConfig(config);
+ this._dialog = SelectorEngine.findOne(SELECTOR_DIALOG, this._element);
+ this._backdrop = this._initializeBackDrop();
+ this._isShown = false;
+ this._ignoreBackdropClick = false;
+ this._isTransitioning = false;
+ this._scrollBar = new ScrollBarHelper();
+ } // Getters
- if (this.touchTimeout) {
- clearTimeout(this.touchTimeout);
- }
- this.touchTimeout = setTimeout(event => this.cycle(event), TOUCHEVENT_COMPAT_WAIT + this._config.interval);
- }
- };
+ static get Default() {
+ return Default$5;
+ }
- SelectorEngine.find(SELECTOR_ITEM_IMG, this._element).forEach(itemImg => {
- EventHandler.on(itemImg, EVENT_DRAG_START, e => e.preventDefault());
- });
+ static get NAME() {
+ return NAME$6;
+ } // Public
- if (this._pointerEvent) {
- EventHandler.on(this._element, EVENT_POINTERDOWN, event => start(event));
- EventHandler.on(this._element, EVENT_POINTERUP, event => end(event));
- this._element.classList.add(CLASS_NAME_POINTER_EVENT);
- } else {
- EventHandler.on(this._element, EVENT_TOUCHSTART, event => start(event));
- EventHandler.on(this._element, EVENT_TOUCHMOVE, event => move(event));
- EventHandler.on(this._element, EVENT_TOUCHEND, event => end(event));
- }
+ toggle(relatedTarget) {
+ return this._isShown ? this.hide() : this.show(relatedTarget);
}
- _keydown(event) {
- if (/input|textarea/i.test(event.target.tagName)) {
+ show(relatedTarget) {
+ if (this._isShown || this._isTransitioning) {
return;
}
- const direction = KEY_TO_DIRECTION[event.key];
-
- if (direction) {
- event.preventDefault();
+ const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$3, {
+ relatedTarget
+ });
- this._slide(direction);
+ if (showEvent.defaultPrevented) {
+ return;
}
- }
- _getItemIndex(element) {
- this._items = element && element.parentNode ? SelectorEngine.find(SELECTOR_ITEM, element.parentNode) : [];
- return this._items.indexOf(element);
- }
+ this._isShown = true;
- _getItemByOrder(order, activeElement) {
- const isNext = order === ORDER_NEXT;
- return getNextActiveElement(this._items, activeElement, isNext, this._config.wrap);
- }
+ if (this._isAnimated()) {
+ this._isTransitioning = true;
+ }
- _triggerSlideEvent(relatedTarget, eventDirectionName) {
- const targetIndex = this._getItemIndex(relatedTarget);
+ this._scrollBar.hide();
- const fromIndex = this._getItemIndex(SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element));
+ document.body.classList.add(CLASS_NAME_OPEN);
- return EventHandler.trigger(this._element, EVENT_SLIDE, {
- relatedTarget,
- direction: eventDirectionName,
- from: fromIndex,
- to: targetIndex
- });
- }
+ this._adjustDialog();
- _setActiveIndicatorElement(element) {
- if (this._indicatorsElement) {
- const activeIndicator = SelectorEngine.findOne(SELECTOR_ACTIVE$1, this._indicatorsElement);
- activeIndicator.classList.remove(CLASS_NAME_ACTIVE$2);
- activeIndicator.removeAttribute('aria-current');
- const indicators = SelectorEngine.find(SELECTOR_INDICATOR, this._indicatorsElement);
+ this._setEscapeEvent();
- for (let i = 0; i < indicators.length; i++) {
- if (Number.parseInt(indicators[i].getAttribute('data-bs-slide-to'), 10) === this._getItemIndex(element)) {
- indicators[i].classList.add(CLASS_NAME_ACTIVE$2);
- indicators[i].setAttribute('aria-current', 'true');
- break;
+ this._setResizeEvent();
+
+ EventHandler.on(this._element, EVENT_CLICK_DISMISS$2, SELECTOR_DATA_DISMISS$2, event => this.hide(event));
+ EventHandler.on(this._dialog, EVENT_MOUSEDOWN_DISMISS, () => {
+ EventHandler.one(this._element, EVENT_MOUSEUP_DISMISS, event => {
+ if (event.target === this._element) {
+ this._ignoreBackdropClick = true;
}
- }
- }
+ });
+ });
+
+ this._showBackdrop(() => this._showElement(relatedTarget));
}
- _updateInterval() {
- const element = this._activeElement || SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element);
+ hide(event) {
+ if (event && ['A', 'AREA'].includes(event.target.tagName)) {
+ event.preventDefault();
+ }
- if (!element) {
+ if (!this._isShown || this._isTransitioning) {
return;
}
- const elementInterval = Number.parseInt(element.getAttribute('data-bs-interval'), 10);
+ const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$3);
- if (elementInterval) {
- this._config.defaultInterval = this._config.defaultInterval || this._config.interval;
- this._config.interval = elementInterval;
- } else {
- this._config.interval = this._config.defaultInterval || this._config.interval;
+ if (hideEvent.defaultPrevented) {
+ return;
}
- }
-
- _slide(directionOrOrder, element) {
- const order = this._directionToOrder(directionOrOrder);
- const activeElement = SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element);
+ this._isShown = false;
- const activeElementIndex = this._getItemIndex(activeElement);
+ const isAnimated = this._isAnimated();
- const nextElement = element || this._getItemByOrder(order, activeElement);
+ if (isAnimated) {
+ this._isTransitioning = true;
+ }
- const nextElementIndex = this._getItemIndex(nextElement);
+ this._setEscapeEvent();
- const isCycling = Boolean(this._interval);
- const isNext = order === ORDER_NEXT;
- const directionalClassName = isNext ? CLASS_NAME_START : CLASS_NAME_END;
- const orderClassName = isNext ? CLASS_NAME_NEXT : CLASS_NAME_PREV;
+ this._setResizeEvent();
- const eventDirectionName = this._orderToDirection(order);
+ EventHandler.off(document, EVENT_FOCUSIN$2);
- if (nextElement && nextElement.classList.contains(CLASS_NAME_ACTIVE$2)) {
- this._isSliding = false;
- return;
- }
+ this._element.classList.remove(CLASS_NAME_SHOW$5);
- if (this._isSliding) {
- return;
- }
+ EventHandler.off(this._element, EVENT_CLICK_DISMISS$2);
+ EventHandler.off(this._dialog, EVENT_MOUSEDOWN_DISMISS);
- const slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName);
+ this._queueCallback(() => this._hideModal(), this._element, isAnimated);
+ }
- if (slideEvent.defaultPrevented) {
- return;
- }
+ dispose() {
+ [window, this._dialog].forEach(htmlElement => EventHandler.off(htmlElement, EVENT_KEY$6));
- if (!activeElement || !nextElement) {
- // Some weirdness is happening, so we bail
- return;
- }
+ this._backdrop.dispose();
- this._isSliding = true;
+ super.dispose();
+ /**
+ * `document` has 2 events `EVENT_FOCUSIN` and `EVENT_CLICK_DATA_API`
+ * Do not move `document` in `htmlElements` array
+ * It will remove `EVENT_CLICK_DATA_API` event that should remain
+ */
- if (isCycling) {
- this.pause();
- }
+ EventHandler.off(document, EVENT_FOCUSIN$2);
+ }
- this._setActiveIndicatorElement(nextElement);
+ handleUpdate() {
+ this._adjustDialog();
+ } // Private
- this._activeElement = nextElement;
- const triggerSlidEvent = () => {
- EventHandler.trigger(this._element, EVENT_SLID, {
- relatedTarget: nextElement,
- direction: eventDirectionName,
- from: activeElementIndex,
- to: nextElementIndex
- });
+ _initializeBackDrop() {
+ return new Backdrop({
+ isVisible: Boolean(this._config.backdrop),
+ // 'static' option will be translated to true, and booleans will keep their value
+ isAnimated: this._isAnimated()
+ });
+ }
+
+ _getConfig(config) {
+ config = { ...Default$5,
+ ...Manipulator.getDataAttributes(this._element),
+ ...(typeof config === 'object' ? config : {})
};
+ typeCheckConfig(NAME$6, config, DefaultType$5);
+ return config;
+ }
- if (this._element.classList.contains(CLASS_NAME_SLIDE)) {
- nextElement.classList.add(orderClassName);
- reflow(nextElement);
- activeElement.classList.add(directionalClassName);
- nextElement.classList.add(directionalClassName);
+ _showElement(relatedTarget) {
+ const isAnimated = this._isAnimated();
- const completeCallBack = () => {
- nextElement.classList.remove(directionalClassName, orderClassName);
- nextElement.classList.add(CLASS_NAME_ACTIVE$2);
- activeElement.classList.remove(CLASS_NAME_ACTIVE$2, orderClassName, directionalClassName);
- this._isSliding = false;
- setTimeout(triggerSlidEvent, 0);
- };
+ const modalBody = SelectorEngine.findOne(SELECTOR_MODAL_BODY, this._dialog);
- this._queueCallback(completeCallBack, activeElement, true);
- } else {
- activeElement.classList.remove(CLASS_NAME_ACTIVE$2);
- nextElement.classList.add(CLASS_NAME_ACTIVE$2);
- this._isSliding = false;
- triggerSlidEvent();
+ if (!this._element.parentNode || this._element.parentNode.nodeType !== Node.ELEMENT_NODE) {
+ // Don't move modal's DOM position
+ document.body.appendChild(this._element);
}
- if (isCycling) {
- this.cycle();
+ this._element.style.display = 'block';
+
+ this._element.removeAttribute('aria-hidden');
+
+ this._element.setAttribute('aria-modal', true);
+
+ this._element.setAttribute('role', 'dialog');
+
+ this._element.scrollTop = 0;
+
+ if (modalBody) {
+ modalBody.scrollTop = 0;
}
- }
- _directionToOrder(direction) {
- if (![DIRECTION_RIGHT, DIRECTION_LEFT].includes(direction)) {
- return direction;
+ if (isAnimated) {
+ reflow(this._element);
}
- if (isRTL()) {
- return direction === DIRECTION_LEFT ? ORDER_PREV : ORDER_NEXT;
+ this._element.classList.add(CLASS_NAME_SHOW$5);
+
+ if (this._config.focus) {
+ this._enforceFocus();
}
- return direction === DIRECTION_LEFT ? ORDER_NEXT : ORDER_PREV;
+ const transitionComplete = () => {
+ if (this._config.focus) {
+ this._element.focus();
+ }
+
+ this._isTransitioning = false;
+ EventHandler.trigger(this._element, EVENT_SHOWN$3, {
+ relatedTarget
+ });
+ };
+
+ this._queueCallback(transitionComplete, this._dialog, isAnimated);
}
- _orderToDirection(order) {
- if (![ORDER_NEXT, ORDER_PREV].includes(order)) {
- return order;
+ _enforceFocus() {
+ EventHandler.off(document, EVENT_FOCUSIN$2); // guard against infinite focus loop
+
+ EventHandler.on(document, EVENT_FOCUSIN$2, event => {
+ if (document !== event.target && this._element !== event.target && !this._element.contains(event.target)) {
+ this._element.focus();
+ }
+ });
+ }
+
+ _setEscapeEvent() {
+ if (this._isShown) {
+ EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS$1, event => {
+ if (this._config.keyboard && event.key === ESCAPE_KEY$1) {
+ event.preventDefault();
+ this.hide();
+ } else if (!this._config.keyboard && event.key === ESCAPE_KEY$1) {
+ this._triggerBackdropTransition();
+ }
+ });
+ } else {
+ EventHandler.off(this._element, EVENT_KEYDOWN_DISMISS$1);
}
+ }
- if (isRTL()) {
- return order === ORDER_PREV ? DIRECTION_LEFT : DIRECTION_RIGHT;
+ _setResizeEvent() {
+ if (this._isShown) {
+ EventHandler.on(window, EVENT_RESIZE, () => this._adjustDialog());
+ } else {
+ EventHandler.off(window, EVENT_RESIZE);
}
+ }
- return order === ORDER_PREV ? DIRECTION_RIGHT : DIRECTION_LEFT;
- } // Static
+ _hideModal() {
+ this._element.style.display = 'none';
+ this._element.setAttribute('aria-hidden', true);
- static carouselInterface(element, config) {
- const data = Carousel.getOrCreateInstance(element, config);
- let {
- _config
- } = data;
+ this._element.removeAttribute('aria-modal');
- if (typeof config === 'object') {
- _config = { ..._config,
- ...config
- };
- }
+ this._element.removeAttribute('role');
- const action = typeof config === 'string' ? config : _config.slide;
+ this._isTransitioning = false;
- if (typeof config === 'number') {
- data.to(config);
- } else if (typeof action === 'string') {
- if (typeof data[action] === 'undefined') {
- throw new TypeError(`No method named "${action}"`);
- }
+ this._backdrop.hide(() => {
+ document.body.classList.remove(CLASS_NAME_OPEN);
- data[action]();
- } else if (_config.interval && _config.ride) {
- data.pause();
- data.cycle();
- }
+ this._resetAdjustments();
+
+ this._scrollBar.reset();
+
+ EventHandler.trigger(this._element, EVENT_HIDDEN$3);
+ });
}
- static jQueryInterface(config) {
- return this.each(function () {
- Carousel.carouselInterface(this, config);
+ _showBackdrop(callback) {
+ EventHandler.on(this._element, EVENT_CLICK_DISMISS$2, event => {
+ if (this._ignoreBackdropClick) {
+ this._ignoreBackdropClick = false;
+ return;
+ }
+
+ if (event.target !== event.currentTarget) {
+ return;
+ }
+
+ if (this._config.backdrop === true) {
+ this.hide();
+ } else if (this._config.backdrop === 'static') {
+ this._triggerBackdropTransition();
+ }
});
+
+ this._backdrop.show(callback);
}
- static dataApiClickHandler(event) {
- const target = getElementFromSelector(this);
+ _isAnimated() {
+ return this._element.classList.contains(CLASS_NAME_FADE$4);
+ }
- if (!target || !target.classList.contains(CLASS_NAME_CAROUSEL)) {
+ _triggerBackdropTransition() {
+ const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED);
+
+ if (hideEvent.defaultPrevented) {
return;
}
- const config = { ...Manipulator.getDataAttributes(target),
- ...Manipulator.getDataAttributes(this)
- };
- const slideIndex = this.getAttribute('data-bs-slide-to');
+ const {
+ classList,
+ scrollHeight,
+ style
+ } = this._element;
+ const isModalOverflowing = scrollHeight > document.documentElement.clientHeight; // return if the following background transition hasn't yet completed
- if (slideIndex) {
- config.interval = false;
+ if (!isModalOverflowing && style.overflowY === 'hidden' || classList.contains(CLASS_NAME_STATIC)) {
+ return;
}
- Carousel.carouselInterface(target, config);
... 8113 lines suppressed ...