;\n\n tooltipPosition(useFinalPosition: boolean): Point {\n const {x, y} = this.getProps(['x', 'y'], useFinalPosition);\n return {x, y} as Point;\n }\n\n hasValue() {\n return isNumber(this.x) && isNumber(this.y);\n }\n\n /**\n * Gets the current or final value of each prop. Can return extra properties (whole object).\n * @param props - properties to get\n * @param [final] - get the final value (animation target)\n */\n getProps(props: P, final?: boolean): Pick;\n getProps(props: P[], final?: boolean): Partial>;\n getProps(props: string[], final?: boolean): Partial> {\n const anims = this.$animations;\n if (!final || !anims) {\n // let's not create an object, if not needed\n return this as Record;\n }\n const ret: Record = {};\n props.forEach((prop) => {\n ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : this[prop as string];\n });\n return ret;\n }\n}\n", "import {isNullOrUndef, valueOrDefault} from '../helpers/helpers.core.js';\nimport {_factorize} from '../helpers/helpers.math.js';\n\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n * @typedef {{value:number | string, label?:string, major?:boolean, $context?:any}} Tick\n */\n\n/**\n * Returns a subset of ticks to be plotted to avoid overlapping labels.\n * @param {import('./core.scale.js').default} scale\n * @param {Tick[]} ticks\n * @return {Tick[]}\n * @private\n */\nexport function autoSkip(scale, ticks) {\n const tickOpts = scale.options.ticks;\n const determinedMaxTicks = determineMaxTicks(scale);\n const ticksLimit = Math.min(tickOpts.maxTicksLimit || determinedMaxTicks, determinedMaxTicks);\n const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];\n const numMajorIndices = majorIndices.length;\n const first = majorIndices[0];\n const last = majorIndices[numMajorIndices - 1];\n const newTicks = [];\n\n // If there are too many major ticks to display them all\n if (numMajorIndices > ticksLimit) {\n skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit);\n return newTicks;\n }\n\n const spacing = calculateSpacing(majorIndices, ticks, ticksLimit);\n\n if (numMajorIndices > 0) {\n let i, ilen;\n const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null;\n skip(ticks, newTicks, spacing, isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);\n for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {\n skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]);\n }\n skip(ticks, newTicks, spacing, last, isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);\n return newTicks;\n }\n skip(ticks, newTicks, spacing);\n return newTicks;\n}\n\nfunction determineMaxTicks(scale) {\n const offset = scale.options.offset;\n const tickLength = scale._tickSize();\n const maxScale = scale._length / tickLength + (offset ? 0 : 1);\n const maxChart = scale._maxLength / tickLength;\n return Math.floor(Math.min(maxScale, maxChart));\n}\n\n/**\n * @param {number[]} majorIndices\n * @param {Tick[]} ticks\n * @param {number} ticksLimit\n */\nfunction calculateSpacing(majorIndices, ticks, ticksLimit) {\n const evenMajorSpacing = getEvenSpacing(majorIndices);\n const spacing = ticks.length / ticksLimit;\n\n // If the major ticks are evenly spaced apart, place the minor ticks\n // so that they divide the major ticks into even chunks\n if (!evenMajorSpacing) {\n return Math.max(spacing, 1);\n }\n\n const factors = _factorize(evenMajorSpacing);\n for (let i = 0, ilen = factors.length - 1; i < ilen; i++) {\n const factor = factors[i];\n if (factor > spacing) {\n return factor;\n }\n }\n return Math.max(spacing, 1);\n}\n\n/**\n * @param {Tick[]} ticks\n */\nfunction getMajorIndices(ticks) {\n const result = [];\n let i, ilen;\n for (i = 0, ilen = ticks.length; i < ilen; i++) {\n if (ticks[i].major) {\n result.push(i);\n }\n }\n return result;\n}\n\n/**\n * @param {Tick[]} ticks\n * @param {Tick[]} newTicks\n * @param {number[]} majorIndices\n * @param {number} spacing\n */\nfunction skipMajors(ticks, newTicks, majorIndices, spacing) {\n let count = 0;\n let next = majorIndices[0];\n let i;\n\n spacing = Math.ceil(spacing);\n for (i = 0; i < ticks.length; i++) {\n if (i === next) {\n newTicks.push(ticks[i]);\n count++;\n next = majorIndices[count * spacing];\n }\n }\n}\n\n/**\n * @param {Tick[]} ticks\n * @param {Tick[]} newTicks\n * @param {number} spacing\n * @param {number} [majorStart]\n * @param {number} [majorEnd]\n */\nfunction skip(ticks, newTicks, spacing, majorStart, majorEnd) {\n const start = valueOrDefault(majorStart, 0);\n const end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length);\n let count = 0;\n let length, i, next;\n\n spacing = Math.ceil(spacing);\n if (majorEnd) {\n length = majorEnd - majorStart;\n spacing = length / Math.floor(length / spacing);\n }\n\n next = start;\n\n while (next < 0) {\n count++;\n next = Math.round(start + count * spacing);\n }\n\n for (i = Math.max(start, 0); i < end; i++) {\n if (i === next) {\n newTicks.push(ticks[i]);\n count++;\n next = Math.round(start + count * spacing);\n }\n }\n}\n\n\n/**\n * @param {number[]} arr\n */\nfunction getEvenSpacing(arr) {\n const len = arr.length;\n let i, diff;\n\n if (len < 2) {\n return false;\n }\n\n for (diff = arr[0], i = 1; i < len; ++i) {\n if (arr[i] - arr[i - 1] !== diff) {\n return false;\n }\n }\n return diff;\n}\n", "import Element from './core.element.js';\nimport {_alignPixel, _measureText, renderText, clipArea, unclipArea} from '../helpers/helpers.canvas.js';\nimport {callback as call, each, finiteOrDefault, isArray, isFinite, isNullOrUndef, isObject, valueOrDefault} from '../helpers/helpers.core.js';\nimport {toDegrees, toRadians, _int16Range, _limitValue, HALF_PI} from '../helpers/helpers.math.js';\nimport {_alignStartEnd, _toLeftRightCenter} from '../helpers/helpers.extras.js';\nimport {createContext, toFont, toPadding, _addGrace} from '../helpers/helpers.options.js';\nimport {autoSkip} from './core.scale.autoskip.js';\n\nconst reverseAlign = (align) => align === 'left' ? 'right' : align === 'right' ? 'left' : align;\nconst offsetFromEdge = (scale, edge, offset) => edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset;\nconst getTicksLimit = (ticksLength, maxTicksLimit) => Math.min(maxTicksLimit || ticksLength, ticksLength);\n\n/**\n * @typedef { import('../types/index.js').Chart } Chart\n * @typedef {{value:number | string, label?:string, major?:boolean, $context?:any}} Tick\n */\n\n/**\n * Returns a new array containing numItems from arr\n * @param {any[]} arr\n * @param {number} numItems\n */\nfunction sample(arr, numItems) {\n const result = [];\n const increment = arr.length / numItems;\n const len = arr.length;\n let i = 0;\n\n for (; i < len; i += increment) {\n result.push(arr[Math.floor(i)]);\n }\n return result;\n}\n\n/**\n * @param {Scale} scale\n * @param {number} index\n * @param {boolean} offsetGridLines\n */\nfunction getPixelForGridLine(scale, index, offsetGridLines) {\n const length = scale.ticks.length;\n const validIndex = Math.min(index, length - 1);\n const start = scale._startPixel;\n const end = scale._endPixel;\n const epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.\n let lineValue = scale.getPixelForTick(validIndex);\n let offset;\n\n if (offsetGridLines) {\n if (length === 1) {\n offset = Math.max(lineValue - start, end - lineValue);\n } else if (index === 0) {\n offset = (scale.getPixelForTick(1) - lineValue) / 2;\n } else {\n offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;\n }\n lineValue += validIndex < index ? offset : -offset;\n\n // Return undefined if the pixel is out of the range\n if (lineValue < start - epsilon || lineValue > end + epsilon) {\n return;\n }\n }\n return lineValue;\n}\n\n/**\n * @param {object} caches\n * @param {number} length\n */\nfunction garbageCollect(caches, length) {\n each(caches, (cache) => {\n const gc = cache.gc;\n const gcLen = gc.length / 2;\n let i;\n if (gcLen > length) {\n for (i = 0; i < gcLen; ++i) {\n delete cache.data[gc[i]];\n }\n gc.splice(0, gcLen);\n }\n });\n}\n\n/**\n * @param {object} options\n */\nfunction getTickMarkLength(options) {\n return options.drawTicks ? options.tickLength : 0;\n}\n\n/**\n * @param {object} options\n */\nfunction getTitleHeight(options, fallback) {\n if (!options.display) {\n return 0;\n }\n\n const font = toFont(options.font, fallback);\n const padding = toPadding(options.padding);\n const lines = isArray(options.text) ? options.text.length : 1;\n\n return (lines * font.lineHeight) + padding.height;\n}\n\nfunction createScaleContext(parent, scale) {\n return createContext(parent, {\n scale,\n type: 'scale'\n });\n}\n\nfunction createTickContext(parent, index, tick) {\n return createContext(parent, {\n tick,\n index,\n type: 'tick'\n });\n}\n\nfunction titleAlign(align, position, reverse) {\n /** @type {CanvasTextAlign} */\n let ret = _toLeftRightCenter(align);\n if ((reverse && position !== 'right') || (!reverse && position === 'right')) {\n ret = reverseAlign(ret);\n }\n return ret;\n}\n\nfunction titleArgs(scale, offset, position, align) {\n const {top, left, bottom, right, chart} = scale;\n const {chartArea, scales} = chart;\n let rotation = 0;\n let maxWidth, titleX, titleY;\n const height = bottom - top;\n const width = right - left;\n\n if (scale.isHorizontal()) {\n titleX = _alignStartEnd(align, left, right);\n\n if (isObject(position)) {\n const positionAxisID = Object.keys(position)[0];\n const value = position[positionAxisID];\n titleY = scales[positionAxisID].getPixelForValue(value) + height - offset;\n } else if (position === 'center') {\n titleY = (chartArea.bottom + chartArea.top) / 2 + height - offset;\n } else {\n titleY = offsetFromEdge(scale, position, offset);\n }\n maxWidth = right - left;\n } else {\n if (isObject(position)) {\n const positionAxisID = Object.keys(position)[0];\n const value = position[positionAxisID];\n titleX = scales[positionAxisID].getPixelForValue(value) - width + offset;\n } else if (position === 'center') {\n titleX = (chartArea.left + chartArea.right) / 2 - width + offset;\n } else {\n titleX = offsetFromEdge(scale, position, offset);\n }\n titleY = _alignStartEnd(align, bottom, top);\n rotation = position === 'left' ? -HALF_PI : HALF_PI;\n }\n return {titleX, titleY, maxWidth, rotation};\n}\n\nexport default class Scale extends Element {\n\n // eslint-disable-next-line max-statements\n constructor(cfg) {\n super();\n\n /** @type {string} */\n this.id = cfg.id;\n /** @type {string} */\n this.type = cfg.type;\n /** @type {any} */\n this.options = undefined;\n /** @type {CanvasRenderingContext2D} */\n this.ctx = cfg.ctx;\n /** @type {Chart} */\n this.chart = cfg.chart;\n\n // implements box\n /** @type {number} */\n this.top = undefined;\n /** @type {number} */\n this.bottom = undefined;\n /** @type {number} */\n this.left = undefined;\n /** @type {number} */\n this.right = undefined;\n /** @type {number} */\n this.width = undefined;\n /** @type {number} */\n this.height = undefined;\n this._margins = {\n left: 0,\n right: 0,\n top: 0,\n bottom: 0\n };\n /** @type {number} */\n this.maxWidth = undefined;\n /** @type {number} */\n this.maxHeight = undefined;\n /** @type {number} */\n this.paddingTop = undefined;\n /** @type {number} */\n this.paddingBottom = undefined;\n /** @type {number} */\n this.paddingLeft = undefined;\n /** @type {number} */\n this.paddingRight = undefined;\n\n // scale-specific properties\n /** @type {string=} */\n this.axis = undefined;\n /** @type {number=} */\n this.labelRotation = undefined;\n this.min = undefined;\n this.max = undefined;\n this._range = undefined;\n /** @type {Tick[]} */\n this.ticks = [];\n /** @type {object[]|null} */\n this._gridLineItems = null;\n /** @type {object[]|null} */\n this._labelItems = null;\n /** @type {object|null} */\n this._labelSizes = null;\n this._length = 0;\n this._maxLength = 0;\n this._longestTextCache = {};\n /** @type {number} */\n this._startPixel = undefined;\n /** @type {number} */\n this._endPixel = undefined;\n this._reversePixels = false;\n this._userMax = undefined;\n this._userMin = undefined;\n this._suggestedMax = undefined;\n this._suggestedMin = undefined;\n this._ticksLength = 0;\n this._borderValue = 0;\n this._cache = {};\n this._dataLimitsCached = false;\n this.$context = undefined;\n }\n\n /**\n\t * @param {any} options\n\t * @since 3.0\n\t */\n init(options) {\n this.options = options.setContext(this.getContext());\n\n this.axis = options.axis;\n\n // parse min/max value, so we can properly determine min/max for other scales\n this._userMin = this.parse(options.min);\n this._userMax = this.parse(options.max);\n this._suggestedMin = this.parse(options.suggestedMin);\n this._suggestedMax = this.parse(options.suggestedMax);\n }\n\n /**\n\t * Parse a supported input value to internal representation.\n\t * @param {*} raw\n\t * @param {number} [index]\n\t * @since 3.0\n\t */\n parse(raw, index) { // eslint-disable-line no-unused-vars\n return raw;\n }\n\n /**\n\t * @return {{min: number, max: number, minDefined: boolean, maxDefined: boolean}}\n\t * @protected\n\t * @since 3.0\n\t */\n getUserBounds() {\n let {_userMin, _userMax, _suggestedMin, _suggestedMax} = this;\n _userMin = finiteOrDefault(_userMin, Number.POSITIVE_INFINITY);\n _userMax = finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY);\n _suggestedMin = finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY);\n _suggestedMax = finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY);\n return {\n min: finiteOrDefault(_userMin, _suggestedMin),\n max: finiteOrDefault(_userMax, _suggestedMax),\n minDefined: isFinite(_userMin),\n maxDefined: isFinite(_userMax)\n };\n }\n\n /**\n\t * @param {boolean} canStack\n\t * @return {{min: number, max: number}}\n\t * @protected\n\t * @since 3.0\n\t */\n getMinMax(canStack) {\n // eslint-disable-next-line prefer-const\n let {min, max, minDefined, maxDefined} = this.getUserBounds();\n let range;\n\n if (minDefined && maxDefined) {\n return {min, max};\n }\n\n const metas = this.getMatchingVisibleMetas();\n for (let i = 0, ilen = metas.length; i < ilen; ++i) {\n range = metas[i].controller.getMinMax(this, canStack);\n if (!minDefined) {\n min = Math.min(min, range.min);\n }\n if (!maxDefined) {\n max = Math.max(max, range.max);\n }\n }\n\n // Make sure min <= max when only min or max is defined by user and the data is outside that range\n min = maxDefined && min > max ? max : min;\n max = minDefined && min > max ? min : max;\n\n return {\n min: finiteOrDefault(min, finiteOrDefault(max, min)),\n max: finiteOrDefault(max, finiteOrDefault(min, max))\n };\n }\n\n /**\n\t * Get the padding needed for the scale\n\t * @return {{top: number, left: number, bottom: number, right: number}} the necessary padding\n\t * @private\n\t */\n getPadding() {\n return {\n left: this.paddingLeft || 0,\n top: this.paddingTop || 0,\n right: this.paddingRight || 0,\n bottom: this.paddingBottom || 0\n };\n }\n\n /**\n\t * Returns the scale tick objects\n\t * @return {Tick[]}\n\t * @since 2.7\n\t */\n getTicks() {\n return this.ticks;\n }\n\n /**\n\t * @return {string[]}\n\t */\n getLabels() {\n const data = this.chart.data;\n return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];\n }\n\n /**\n * @return {import('../types.js').LabelItem[]}\n */\n getLabelItems(chartArea = this.chart.chartArea) {\n const items = this._labelItems || (this._labelItems = this._computeLabelItems(chartArea));\n return items;\n }\n\n // When a new layout is created, reset the data limits cache\n beforeLayout() {\n this._cache = {};\n this._dataLimitsCached = false;\n }\n\n // These methods are ordered by lifecycle. Utilities then follow.\n // Any function defined here is inherited by all scale types.\n // Any function can be extended by the scale type\n\n beforeUpdate() {\n call(this.options.beforeUpdate, [this]);\n }\n\n /**\n\t * @param {number} maxWidth - the max width in pixels\n\t * @param {number} maxHeight - the max height in pixels\n\t * @param {{top: number, left: number, bottom: number, right: number}} margins - the space between the edge of the other scales and edge of the chart\n\t * This space comes from two sources:\n\t * - padding - space that's required to show the labels at the edges of the scale\n\t * - thickness of scales or legends in another orientation\n\t */\n update(maxWidth, maxHeight, margins) {\n const {beginAtZero, grace, ticks: tickOpts} = this.options;\n const sampleSize = tickOpts.sampleSize;\n\n // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)\n this.beforeUpdate();\n\n // Absorb the master measurements\n this.maxWidth = maxWidth;\n this.maxHeight = maxHeight;\n this._margins = margins = Object.assign({\n left: 0,\n right: 0,\n top: 0,\n bottom: 0\n }, margins);\n\n this.ticks = null;\n this._labelSizes = null;\n this._gridLineItems = null;\n this._labelItems = null;\n\n // Dimensions\n this.beforeSetDimensions();\n this.setDimensions();\n this.afterSetDimensions();\n\n this._maxLength = this.isHorizontal()\n ? this.width + margins.left + margins.right\n : this.height + margins.top + margins.bottom;\n\n // Data min/max\n if (!this._dataLimitsCached) {\n this.beforeDataLimits();\n this.determineDataLimits();\n this.afterDataLimits();\n this._range = _addGrace(this, grace, beginAtZero);\n this._dataLimitsCached = true;\n }\n\n this.beforeBuildTicks();\n\n this.ticks = this.buildTicks() || [];\n\n // Allow modification of ticks in callback.\n this.afterBuildTicks();\n\n // Compute tick rotation and fit using a sampled subset of labels\n // We generally don't need to compute the size of every single label for determining scale size\n const samplingEnabled = sampleSize < this.ticks.length;\n this._convertTicksToLabels(samplingEnabled ? sample(this.ticks, sampleSize) : this.ticks);\n\n // configure is called twice, once here, once from core.controller.updateLayout.\n // Here we haven't been positioned yet, but dimensions are correct.\n // Variables set in configure are needed for calculateLabelRotation, and\n // it's ok that coordinates are not correct there, only dimensions matter.\n this.configure();\n\n // Tick Rotation\n this.beforeCalculateLabelRotation();\n this.calculateLabelRotation(); // Preconditions: number of ticks and sizes of largest labels must be calculated beforehand\n this.afterCalculateLabelRotation();\n\n // Auto-skip\n if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) {\n this.ticks = autoSkip(this, this.ticks);\n this._labelSizes = null;\n this.afterAutoSkip();\n }\n\n if (samplingEnabled) {\n // Generate labels using all non-skipped ticks\n this._convertTicksToLabels(this.ticks);\n }\n\n this.beforeFit();\n this.fit(); // Preconditions: label rotation and label sizes must be calculated beforehand\n this.afterFit();\n\n // IMPORTANT: after this point, we consider that `this.ticks` will NEVER change!\n\n this.afterUpdate();\n }\n\n /**\n\t * @protected\n\t */\n configure() {\n let reversePixels = this.options.reverse;\n let startPixel, endPixel;\n\n if (this.isHorizontal()) {\n startPixel = this.left;\n endPixel = this.right;\n } else {\n startPixel = this.top;\n endPixel = this.bottom;\n // by default vertical scales are from bottom to top, so pixels are reversed\n reversePixels = !reversePixels;\n }\n this._startPixel = startPixel;\n this._endPixel = endPixel;\n this._reversePixels = reversePixels;\n this._length = endPixel - startPixel;\n this._alignToPixels = this.options.alignToPixels;\n }\n\n afterUpdate() {\n call(this.options.afterUpdate, [this]);\n }\n\n //\n\n beforeSetDimensions() {\n call(this.options.beforeSetDimensions, [this]);\n }\n setDimensions() {\n // Set the unconstrained dimension before label rotation\n if (this.isHorizontal()) {\n // Reset position before calculating rotation\n this.width = this.maxWidth;\n this.left = 0;\n this.right = this.width;\n } else {\n this.height = this.maxHeight;\n\n // Reset position before calculating rotation\n this.top = 0;\n this.bottom = this.height;\n }\n\n // Reset padding\n this.paddingLeft = 0;\n this.paddingTop = 0;\n this.paddingRight = 0;\n this.paddingBottom = 0;\n }\n afterSetDimensions() {\n call(this.options.afterSetDimensions, [this]);\n }\n\n _callHooks(name) {\n this.chart.notifyPlugins(name, this.getContext());\n call(this.options[name], [this]);\n }\n\n // Data limits\n beforeDataLimits() {\n this._callHooks('beforeDataLimits');\n }\n determineDataLimits() {}\n afterDataLimits() {\n this._callHooks('afterDataLimits');\n }\n\n //\n beforeBuildTicks() {\n this._callHooks('beforeBuildTicks');\n }\n /**\n\t * @return {object[]} the ticks\n\t */\n buildTicks() {\n return [];\n }\n afterBuildTicks() {\n this._callHooks('afterBuildTicks');\n }\n\n beforeTickToLabelConversion() {\n call(this.options.beforeTickToLabelConversion, [this]);\n }\n /**\n\t * Convert ticks to label strings\n\t * @param {Tick[]} ticks\n\t */\n generateTickLabels(ticks) {\n const tickOpts = this.options.ticks;\n let i, ilen, tick;\n for (i = 0, ilen = ticks.length; i < ilen; i++) {\n tick = ticks[i];\n tick.label = call(tickOpts.callback, [tick.value, i, ticks], this);\n }\n }\n afterTickToLabelConversion() {\n call(this.options.afterTickToLabelConversion, [this]);\n }\n\n //\n\n beforeCalculateLabelRotation() {\n call(this.options.beforeCalculateLabelRotation, [this]);\n }\n calculateLabelRotation() {\n const options = this.options;\n const tickOpts = options.ticks;\n const numTicks = getTicksLimit(this.ticks.length, options.ticks.maxTicksLimit);\n const minRotation = tickOpts.minRotation || 0;\n const maxRotation = tickOpts.maxRotation;\n let labelRotation = minRotation;\n let tickWidth, maxHeight, maxLabelDiagonal;\n\n if (!this._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !this.isHorizontal()) {\n this.labelRotation = minRotation;\n return;\n }\n\n const labelSizes = this._getLabelSizes();\n const maxLabelWidth = labelSizes.widest.width;\n const maxLabelHeight = labelSizes.highest.height;\n\n // Estimate the width of each grid based on the canvas width, the maximum\n // label width and the number of tick intervals\n const maxWidth = _limitValue(this.chart.width - maxLabelWidth, 0, this.maxWidth);\n tickWidth = options.offset ? this.maxWidth / numTicks : maxWidth / (numTicks - 1);\n\n // Allow 3 pixels x2 padding either side for label readability\n if (maxLabelWidth + 6 > tickWidth) {\n tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));\n maxHeight = this.maxHeight - getTickMarkLength(options.grid)\n\t\t\t\t- tickOpts.padding - getTitleHeight(options.title, this.chart.options.font);\n maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);\n labelRotation = toDegrees(Math.min(\n Math.asin(_limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)),\n Math.asin(_limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(_limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1))\n ));\n labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));\n }\n\n this.labelRotation = labelRotation;\n }\n afterCalculateLabelRotation() {\n call(this.options.afterCalculateLabelRotation, [this]);\n }\n afterAutoSkip() {}\n\n //\n\n beforeFit() {\n call(this.options.beforeFit, [this]);\n }\n fit() {\n // Reset\n const minSize = {\n width: 0,\n height: 0\n };\n\n const {chart, options: {ticks: tickOpts, title: titleOpts, grid: gridOpts}} = this;\n const display = this._isVisible();\n const isHorizontal = this.isHorizontal();\n\n if (display) {\n const titleHeight = getTitleHeight(titleOpts, chart.options.font);\n if (isHorizontal) {\n minSize.width = this.maxWidth;\n minSize.height = getTickMarkLength(gridOpts) + titleHeight;\n } else {\n minSize.height = this.maxHeight; // fill all the height\n minSize.width = getTickMarkLength(gridOpts) + titleHeight;\n }\n\n // Don't bother fitting the ticks if we are not showing the labels\n if (tickOpts.display && this.ticks.length) {\n const {first, last, widest, highest} = this._getLabelSizes();\n const tickPadding = tickOpts.padding * 2;\n const angleRadians = toRadians(this.labelRotation);\n const cos = Math.cos(angleRadians);\n const sin = Math.sin(angleRadians);\n\n if (isHorizontal) {\n // A horizontal axis is more constrained by the height.\n const labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height;\n minSize.height = Math.min(this.maxHeight, minSize.height + labelHeight + tickPadding);\n } else {\n // A vertical axis is more constrained by the width. Labels are the\n // dominant factor here, so get that length first and account for padding\n const labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height;\n\n minSize.width = Math.min(this.maxWidth, minSize.width + labelWidth + tickPadding);\n }\n this._calculatePadding(first, last, sin, cos);\n }\n }\n\n this._handleMargins();\n\n if (isHorizontal) {\n this.width = this._length = chart.width - this._margins.left - this._margins.right;\n this.height = minSize.height;\n } else {\n this.width = minSize.width;\n this.height = this._length = chart.height - this._margins.top - this._margins.bottom;\n }\n }\n\n _calculatePadding(first, last, sin, cos) {\n const {ticks: {align, padding}, position} = this.options;\n const isRotated = this.labelRotation !== 0;\n const labelsBelowTicks = position !== 'top' && this.axis === 'x';\n\n if (this.isHorizontal()) {\n const offsetLeft = this.getPixelForTick(0) - this.left;\n const offsetRight = this.right - this.getPixelForTick(this.ticks.length - 1);\n let paddingLeft = 0;\n let paddingRight = 0;\n\n // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned\n // which means that the right padding is dominated by the font height\n if (isRotated) {\n if (labelsBelowTicks) {\n paddingLeft = cos * first.width;\n paddingRight = sin * last.height;\n } else {\n paddingLeft = sin * first.height;\n paddingRight = cos * last.width;\n }\n } else if (align === 'start') {\n paddingRight = last.width;\n } else if (align === 'end') {\n paddingLeft = first.width;\n } else if (align !== 'inner') {\n paddingLeft = first.width / 2;\n paddingRight = last.width / 2;\n }\n\n // Adjust padding taking into account changes in offsets\n this.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * this.width / (this.width - offsetLeft), 0);\n this.paddingRight = Math.max((paddingRight - offsetRight + padding) * this.width / (this.width - offsetRight), 0);\n } else {\n let paddingTop = last.height / 2;\n let paddingBottom = first.height / 2;\n\n if (align === 'start') {\n paddingTop = 0;\n paddingBottom = first.height;\n } else if (align === 'end') {\n paddingTop = last.height;\n paddingBottom = 0;\n }\n\n this.paddingTop = paddingTop + padding;\n this.paddingBottom = paddingBottom + padding;\n }\n }\n\n /**\n\t * Handle margins and padding interactions\n\t * @private\n\t */\n _handleMargins() {\n if (this._margins) {\n this._margins.left = Math.max(this.paddingLeft, this._margins.left);\n this._margins.top = Math.max(this.paddingTop, this._margins.top);\n this._margins.right = Math.max(this.paddingRight, this._margins.right);\n this._margins.bottom = Math.max(this.paddingBottom, this._margins.bottom);\n }\n }\n\n afterFit() {\n call(this.options.afterFit, [this]);\n }\n\n // Shared Methods\n /**\n\t * @return {boolean}\n\t */\n isHorizontal() {\n const {axis, position} = this.options;\n return position === 'top' || position === 'bottom' || axis === 'x';\n }\n /**\n\t * @return {boolean}\n\t */\n isFullSize() {\n return this.options.fullSize;\n }\n\n /**\n\t * @param {Tick[]} ticks\n\t * @private\n\t */\n _convertTicksToLabels(ticks) {\n this.beforeTickToLabelConversion();\n\n this.generateTickLabels(ticks);\n\n // Ticks should be skipped when callback returns null or undef, so lets remove those.\n let i, ilen;\n for (i = 0, ilen = ticks.length; i < ilen; i++) {\n if (isNullOrUndef(ticks[i].label)) {\n ticks.splice(i, 1);\n ilen--;\n i--;\n }\n }\n\n this.afterTickToLabelConversion();\n }\n\n /**\n\t * @return {{ first: object, last: object, widest: object, highest: object, widths: Array, heights: array }}\n\t * @private\n\t */\n _getLabelSizes() {\n let labelSizes = this._labelSizes;\n\n if (!labelSizes) {\n const sampleSize = this.options.ticks.sampleSize;\n let ticks = this.ticks;\n if (sampleSize < ticks.length) {\n ticks = sample(ticks, sampleSize);\n }\n\n this._labelSizes = labelSizes = this._computeLabelSizes(ticks, ticks.length, this.options.ticks.maxTicksLimit);\n }\n\n return labelSizes;\n }\n\n /**\n\t * Returns {width, height, offset} objects for the first, last, widest, highest tick\n\t * labels where offset indicates the anchor point offset from the top in pixels.\n\t * @return {{ first: object, last: object, widest: object, highest: object, widths: Array, heights: array }}\n\t * @private\n\t */\n _computeLabelSizes(ticks, length, maxTicksLimit) {\n const {ctx, _longestTextCache: caches} = this;\n const widths = [];\n const heights = [];\n const increment = Math.floor(length / getTicksLimit(length, maxTicksLimit));\n let widestLabelSize = 0;\n let highestLabelSize = 0;\n let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel;\n\n for (i = 0; i < length; i += increment) {\n label = ticks[i].label;\n tickFont = this._resolveTickFontOptions(i);\n ctx.font = fontString = tickFont.string;\n cache = caches[fontString] = caches[fontString] || {data: {}, gc: []};\n lineHeight = tickFont.lineHeight;\n width = height = 0;\n // Undefined labels and arrays should not be measured\n if (!isNullOrUndef(label) && !isArray(label)) {\n width = _measureText(ctx, cache.data, cache.gc, width, label);\n height = lineHeight;\n } else if (isArray(label)) {\n // if it is an array let's measure each element\n for (j = 0, jlen = label.length; j < jlen; ++j) {\n nestedLabel = /** @type {string} */ (label[j]);\n // Undefined labels and arrays should not be measured\n if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {\n width = _measureText(ctx, cache.data, cache.gc, width, nestedLabel);\n height += lineHeight;\n }\n }\n }\n widths.push(width);\n heights.push(height);\n widestLabelSize = Math.max(width, widestLabelSize);\n highestLabelSize = Math.max(height, highestLabelSize);\n }\n garbageCollect(caches, length);\n\n const widest = widths.indexOf(widestLabelSize);\n const highest = heights.indexOf(highestLabelSize);\n\n const valueAt = (idx) => ({width: widths[idx] || 0, height: heights[idx] || 0});\n\n return {\n first: valueAt(0),\n last: valueAt(length - 1),\n widest: valueAt(widest),\n highest: valueAt(highest),\n widths,\n heights,\n };\n }\n\n /**\n\t * Used to get the label to display in the tooltip for the given value\n\t * @param {*} value\n\t * @return {string}\n\t */\n getLabelForValue(value) {\n return value;\n }\n\n /**\n\t * Returns the location of the given data point. Value can either be an index or a numerical value\n\t * The coordinate (0, 0) is at the upper-left corner of the canvas\n\t * @param {*} value\n\t * @param {number} [index]\n\t * @return {number}\n\t */\n getPixelForValue(value, index) { // eslint-disable-line no-unused-vars\n return NaN;\n }\n\n /**\n\t * Used to get the data value from a given pixel. This is the inverse of getPixelForValue\n\t * The coordinate (0, 0) is at the upper-left corner of the canvas\n\t * @param {number} pixel\n\t * @return {*}\n\t */\n getValueForPixel(pixel) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * Returns the location of the tick at the given index\n\t * The coordinate (0, 0) is at the upper-left corner of the canvas\n\t * @param {number} index\n\t * @return {number}\n\t */\n getPixelForTick(index) {\n const ticks = this.ticks;\n if (index < 0 || index > ticks.length - 1) {\n return null;\n }\n return this.getPixelForValue(ticks[index].value);\n }\n\n /**\n\t * Utility for getting the pixel location of a percentage of scale\n\t * The coordinate (0, 0) is at the upper-left corner of the canvas\n\t * @param {number} decimal\n\t * @return {number}\n\t */\n getPixelForDecimal(decimal) {\n if (this._reversePixels) {\n decimal = 1 - decimal;\n }\n\n const pixel = this._startPixel + decimal * this._length;\n return _int16Range(this._alignToPixels ? _alignPixel(this.chart, pixel, 0) : pixel);\n }\n\n /**\n\t * @param {number} pixel\n\t * @return {number}\n\t */\n getDecimalForPixel(pixel) {\n const decimal = (pixel - this._startPixel) / this._length;\n return this._reversePixels ? 1 - decimal : decimal;\n }\n\n /**\n\t * Returns the pixel for the minimum chart value\n\t * The coordinate (0, 0) is at the upper-left corner of the canvas\n\t * @return {number}\n\t */\n getBasePixel() {\n return this.getPixelForValue(this.getBaseValue());\n }\n\n /**\n\t * @return {number}\n\t */\n getBaseValue() {\n const {min, max} = this;\n\n return min < 0 && max < 0 ? max :\n min > 0 && max > 0 ? min :\n 0;\n }\n\n /**\n\t * @protected\n\t */\n getContext(index) {\n const ticks = this.ticks || [];\n\n if (index >= 0 && index < ticks.length) {\n const tick = ticks[index];\n return tick.$context ||\n\t\t\t\t(tick.$context = createTickContext(this.getContext(), index, tick));\n }\n return this.$context ||\n\t\t\t(this.$context = createScaleContext(this.chart.getContext(), this));\n }\n\n /**\n\t * @return {number}\n\t * @private\n\t */\n _tickSize() {\n const optionTicks = this.options.ticks;\n\n // Calculate space needed by label in axis direction.\n const rot = toRadians(this.labelRotation);\n const cos = Math.abs(Math.cos(rot));\n const sin = Math.abs(Math.sin(rot));\n\n const labelSizes = this._getLabelSizes();\n const padding = optionTicks.autoSkipPadding || 0;\n const w = labelSizes ? labelSizes.widest.width + padding : 0;\n const h = labelSizes ? labelSizes.highest.height + padding : 0;\n\n // Calculate space needed for 1 tick in axis direction.\n return this.isHorizontal()\n ? h * cos > w * sin ? w / cos : h / sin\n : h * sin < w * cos ? h / cos : w / sin;\n }\n\n /**\n\t * @return {boolean}\n\t * @private\n\t */\n _isVisible() {\n const display = this.options.display;\n\n if (display !== 'auto') {\n return !!display;\n }\n\n return this.getMatchingVisibleMetas().length > 0;\n }\n\n /**\n\t * @private\n\t */\n _computeGridLineItems(chartArea) {\n const axis = this.axis;\n const chart = this.chart;\n const options = this.options;\n const {grid, position, border} = options;\n const offset = grid.offset;\n const isHorizontal = this.isHorizontal();\n const ticks = this.ticks;\n const ticksLength = ticks.length + (offset ? 1 : 0);\n const tl = getTickMarkLength(grid);\n const items = [];\n\n const borderOpts = border.setContext(this.getContext());\n const axisWidth = borderOpts.display ? borderOpts.width : 0;\n const axisHalfWidth = axisWidth / 2;\n const alignBorderValue = function(pixel) {\n return _alignPixel(chart, pixel, axisWidth);\n };\n let borderValue, i, lineValue, alignedLineValue;\n let tx1, ty1, tx2, ty2, x1, y1, x2, y2;\n\n if (position === 'top') {\n borderValue = alignBorderValue(this.bottom);\n ty1 = this.bottom - tl;\n ty2 = borderValue - axisHalfWidth;\n y1 = alignBorderValue(chartArea.top) + axisHalfWidth;\n y2 = chartArea.bottom;\n } else if (position === 'bottom') {\n borderValue = alignBorderValue(this.top);\n y1 = chartArea.top;\n y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;\n ty1 = borderValue + axisHalfWidth;\n ty2 = this.top + tl;\n } else if (position === 'left') {\n borderValue = alignBorderValue(this.right);\n tx1 = this.right - tl;\n tx2 = borderValue - axisHalfWidth;\n x1 = alignBorderValue(chartArea.left) + axisHalfWidth;\n x2 = chartArea.right;\n } else if (position === 'right') {\n borderValue = alignBorderValue(this.left);\n x1 = chartArea.left;\n x2 = alignBorderValue(chartArea.right) - axisHalfWidth;\n tx1 = borderValue + axisHalfWidth;\n tx2 = this.left + tl;\n } else if (axis === 'x') {\n if (position === 'center') {\n borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5);\n } else if (isObject(position)) {\n const positionAxisID = Object.keys(position)[0];\n const value = position[positionAxisID];\n borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value));\n }\n\n y1 = chartArea.top;\n y2 = chartArea.bottom;\n ty1 = borderValue + axisHalfWidth;\n ty2 = ty1 + tl;\n } else if (axis === 'y') {\n if (position === 'center') {\n borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2);\n } else if (isObject(position)) {\n const positionAxisID = Object.keys(position)[0];\n const value = position[positionAxisID];\n borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value));\n }\n\n tx1 = borderValue - axisHalfWidth;\n tx2 = tx1 - tl;\n x1 = chartArea.left;\n x2 = chartArea.right;\n }\n\n const limit = valueOrDefault(options.ticks.maxTicksLimit, ticksLength);\n const step = Math.max(1, Math.ceil(ticksLength / limit));\n for (i = 0; i < ticksLength; i += step) {\n const context = this.getContext(i);\n const optsAtIndex = grid.setContext(context);\n const optsAtIndexBorder = border.setContext(context);\n\n const lineWidth = optsAtIndex.lineWidth;\n const lineColor = optsAtIndex.color;\n const borderDash = optsAtIndexBorder.dash || [];\n const borderDashOffset = optsAtIndexBorder.dashOffset;\n\n const tickWidth = optsAtIndex.tickWidth;\n const tickColor = optsAtIndex.tickColor;\n const tickBorderDash = optsAtIndex.tickBorderDash || [];\n const tickBorderDashOffset = optsAtIndex.tickBorderDashOffset;\n\n lineValue = getPixelForGridLine(this, i, offset);\n\n // Skip if the pixel is out of the range\n if (lineValue === undefined) {\n continue;\n }\n\n alignedLineValue = _alignPixel(chart, lineValue, lineWidth);\n\n if (isHorizontal) {\n tx1 = tx2 = x1 = x2 = alignedLineValue;\n } else {\n ty1 = ty2 = y1 = y2 = alignedLineValue;\n }\n\n items.push({\n tx1,\n ty1,\n tx2,\n ty2,\n x1,\n y1,\n x2,\n y2,\n width: lineWidth,\n color: lineColor,\n borderDash,\n borderDashOffset,\n tickWidth,\n tickColor,\n tickBorderDash,\n tickBorderDashOffset,\n });\n }\n\n this._ticksLength = ticksLength;\n this._borderValue = borderValue;\n\n return items;\n }\n\n /**\n\t * @private\n\t */\n _computeLabelItems(chartArea) {\n const axis = this.axis;\n const options = this.options;\n const {position, ticks: optionTicks} = options;\n const isHorizontal = this.isHorizontal();\n const ticks = this.ticks;\n const {align, crossAlign, padding, mirror} = optionTicks;\n const tl = getTickMarkLength(options.grid);\n const tickAndPadding = tl + padding;\n const hTickAndPadding = mirror ? -padding : tickAndPadding;\n const rotation = -toRadians(this.labelRotation);\n const items = [];\n let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;\n let textBaseline = 'middle';\n\n if (position === 'top') {\n y = this.bottom - hTickAndPadding;\n textAlign = this._getXAxisLabelAlignment();\n } else if (position === 'bottom') {\n y = this.top + hTickAndPadding;\n textAlign = this._getXAxisLabelAlignment();\n } else if (position === 'left') {\n const ret = this._getYAxisLabelAlignment(tl);\n textAlign = ret.textAlign;\n x = ret.x;\n } else if (position === 'right') {\n const ret = this._getYAxisLabelAlignment(tl);\n textAlign = ret.textAlign;\n x = ret.x;\n } else if (axis === 'x') {\n if (position === 'center') {\n y = ((chartArea.top + chartArea.bottom) / 2) + tickAndPadding;\n } else if (isObject(position)) {\n const positionAxisID = Object.keys(position)[0];\n const value = position[positionAxisID];\n y = this.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding;\n }\n textAlign = this._getXAxisLabelAlignment();\n } else if (axis === 'y') {\n if (position === 'center') {\n x = ((chartArea.left + chartArea.right) / 2) - tickAndPadding;\n } else if (isObject(position)) {\n const positionAxisID = Object.keys(position)[0];\n const value = position[positionAxisID];\n x = this.chart.scales[positionAxisID].getPixelForValue(value);\n }\n textAlign = this._getYAxisLabelAlignment(tl).textAlign;\n }\n\n if (axis === 'y') {\n if (align === 'start') {\n textBaseline = 'top';\n } else if (align === 'end') {\n textBaseline = 'bottom';\n }\n }\n\n const labelSizes = this._getLabelSizes();\n for (i = 0, ilen = ticks.length; i < ilen; ++i) {\n tick = ticks[i];\n label = tick.label;\n\n const optsAtIndex = optionTicks.setContext(this.getContext(i));\n pixel = this.getPixelForTick(i) + optionTicks.labelOffset;\n font = this._resolveTickFontOptions(i);\n lineHeight = font.lineHeight;\n lineCount = isArray(label) ? label.length : 1;\n const halfCount = lineCount / 2;\n const color = optsAtIndex.color;\n const strokeColor = optsAtIndex.textStrokeColor;\n const strokeWidth = optsAtIndex.textStrokeWidth;\n let tickTextAlign = textAlign;\n\n if (isHorizontal) {\n x = pixel;\n\n if (textAlign === 'inner') {\n if (i === ilen - 1) {\n tickTextAlign = !this.options.reverse ? 'right' : 'left';\n } else if (i === 0) {\n tickTextAlign = !this.options.reverse ? 'left' : 'right';\n } else {\n tickTextAlign = 'center';\n }\n }\n\n if (position === 'top') {\n if (crossAlign === 'near' || rotation !== 0) {\n textOffset = -lineCount * lineHeight + lineHeight / 2;\n } else if (crossAlign === 'center') {\n textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight;\n } else {\n textOffset = -labelSizes.highest.height + lineHeight / 2;\n }\n } else {\n // eslint-disable-next-line no-lonely-if\n if (crossAlign === 'near' || rotation !== 0) {\n textOffset = lineHeight / 2;\n } else if (crossAlign === 'center') {\n textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight;\n } else {\n textOffset = labelSizes.highest.height - lineCount * lineHeight;\n }\n }\n if (mirror) {\n textOffset *= -1;\n }\n if (rotation !== 0 && !optsAtIndex.showLabelBackdrop) {\n x += (lineHeight / 2) * Math.sin(rotation);\n }\n } else {\n y = pixel;\n textOffset = (1 - lineCount) * lineHeight / 2;\n }\n\n let backdrop;\n\n if (optsAtIndex.showLabelBackdrop) {\n const labelPadding = toPadding(optsAtIndex.backdropPadding);\n const height = labelSizes.heights[i];\n const width = labelSizes.widths[i];\n\n let top = textOffset - labelPadding.top;\n let left = 0 - labelPadding.left;\n\n switch (textBaseline) {\n case 'middle':\n top -= height / 2;\n break;\n case 'bottom':\n top -= height;\n break;\n default:\n break;\n }\n\n switch (textAlign) {\n case 'center':\n left -= width / 2;\n break;\n case 'right':\n left -= width;\n break;\n case 'inner':\n if (i === ilen - 1) {\n left -= width;\n } else if (i > 0) {\n left -= width / 2;\n }\n break;\n default:\n break;\n }\n\n backdrop = {\n left,\n top,\n width: width + labelPadding.width,\n height: height + labelPadding.height,\n\n color: optsAtIndex.backdropColor,\n };\n }\n\n items.push({\n label,\n font,\n textOffset,\n options: {\n rotation,\n color,\n strokeColor,\n strokeWidth,\n textAlign: tickTextAlign,\n textBaseline,\n translation: [x, y],\n backdrop,\n }\n });\n }\n\n return items;\n }\n\n _getXAxisLabelAlignment() {\n const {position, ticks} = this.options;\n const rotation = -toRadians(this.labelRotation);\n\n if (rotation) {\n return position === 'top' ? 'left' : 'right';\n }\n\n let align = 'center';\n\n if (ticks.align === 'start') {\n align = 'left';\n } else if (ticks.align === 'end') {\n align = 'right';\n } else if (ticks.align === 'inner') {\n align = 'inner';\n }\n\n return align;\n }\n\n _getYAxisLabelAlignment(tl) {\n const {position, ticks: {crossAlign, mirror, padding}} = this.options;\n const labelSizes = this._getLabelSizes();\n const tickAndPadding = tl + padding;\n const widest = labelSizes.widest.width;\n\n let textAlign;\n let x;\n\n if (position === 'left') {\n if (mirror) {\n x = this.right + padding;\n\n if (crossAlign === 'near') {\n textAlign = 'left';\n } else if (crossAlign === 'center') {\n textAlign = 'center';\n x += (widest / 2);\n } else {\n textAlign = 'right';\n x += widest;\n }\n } else {\n x = this.right - tickAndPadding;\n\n if (crossAlign === 'near') {\n textAlign = 'right';\n } else if (crossAlign === 'center') {\n textAlign = 'center';\n x -= (widest / 2);\n } else {\n textAlign = 'left';\n x = this.left;\n }\n }\n } else if (position === 'right') {\n if (mirror) {\n x = this.left + padding;\n\n if (crossAlign === 'near') {\n textAlign = 'right';\n } else if (crossAlign === 'center') {\n textAlign = 'center';\n x -= (widest / 2);\n } else {\n textAlign = 'left';\n x -= widest;\n }\n } else {\n x = this.left + tickAndPadding;\n\n if (crossAlign === 'near') {\n textAlign = 'left';\n } else if (crossAlign === 'center') {\n textAlign = 'center';\n x += widest / 2;\n } else {\n textAlign = 'right';\n x = this.right;\n }\n }\n } else {\n textAlign = 'right';\n }\n\n return {textAlign, x};\n }\n\n /**\n\t * @private\n\t */\n _computeLabelArea() {\n if (this.options.ticks.mirror) {\n return;\n }\n\n const chart = this.chart;\n const position = this.options.position;\n\n if (position === 'left' || position === 'right') {\n return {top: 0, left: this.left, bottom: chart.height, right: this.right};\n } if (position === 'top' || position === 'bottom') {\n return {top: this.top, left: 0, bottom: this.bottom, right: chart.width};\n }\n }\n\n /**\n * @protected\n */\n drawBackground() {\n const {ctx, options: {backgroundColor}, left, top, width, height} = this;\n if (backgroundColor) {\n ctx.save();\n ctx.fillStyle = backgroundColor;\n ctx.fillRect(left, top, width, height);\n ctx.restore();\n }\n }\n\n getLineWidthForValue(value) {\n const grid = this.options.grid;\n if (!this._isVisible() || !grid.display) {\n return 0;\n }\n const ticks = this.ticks;\n const index = ticks.findIndex(t => t.value === value);\n if (index >= 0) {\n const opts = grid.setContext(this.getContext(index));\n return opts.lineWidth;\n }\n return 0;\n }\n\n /**\n\t * @protected\n\t */\n drawGrid(chartArea) {\n const grid = this.options.grid;\n const ctx = this.ctx;\n const items = this._gridLineItems || (this._gridLineItems = this._computeGridLineItems(chartArea));\n let i, ilen;\n\n const drawLine = (p1, p2, style) => {\n if (!style.width || !style.color) {\n return;\n }\n ctx.save();\n ctx.lineWidth = style.width;\n ctx.strokeStyle = style.color;\n ctx.setLineDash(style.borderDash || []);\n ctx.lineDashOffset = style.borderDashOffset;\n\n ctx.beginPath();\n ctx.moveTo(p1.x, p1.y);\n ctx.lineTo(p2.x, p2.y);\n ctx.stroke();\n ctx.restore();\n };\n\n if (grid.display) {\n for (i = 0, ilen = items.length; i < ilen; ++i) {\n const item = items[i];\n\n if (grid.drawOnChartArea) {\n drawLine(\n {x: item.x1, y: item.y1},\n {x: item.x2, y: item.y2},\n item\n );\n }\n\n if (grid.drawTicks) {\n drawLine(\n {x: item.tx1, y: item.ty1},\n {x: item.tx2, y: item.ty2},\n {\n color: item.tickColor,\n width: item.tickWidth,\n borderDash: item.tickBorderDash,\n borderDashOffset: item.tickBorderDashOffset\n }\n );\n }\n }\n }\n }\n\n /**\n\t * @protected\n\t */\n drawBorder() {\n const {chart, ctx, options: {border, grid}} = this;\n const borderOpts = border.setContext(this.getContext());\n const axisWidth = border.display ? borderOpts.width : 0;\n if (!axisWidth) {\n return;\n }\n const lastLineWidth = grid.setContext(this.getContext(0)).lineWidth;\n const borderValue = this._borderValue;\n let x1, x2, y1, y2;\n\n if (this.isHorizontal()) {\n x1 = _alignPixel(chart, this.left, axisWidth) - axisWidth / 2;\n x2 = _alignPixel(chart, this.right, lastLineWidth) + lastLineWidth / 2;\n y1 = y2 = borderValue;\n } else {\n y1 = _alignPixel(chart, this.top, axisWidth) - axisWidth / 2;\n y2 = _alignPixel(chart, this.bottom, lastLineWidth) + lastLineWidth / 2;\n x1 = x2 = borderValue;\n }\n ctx.save();\n ctx.lineWidth = borderOpts.width;\n ctx.strokeStyle = borderOpts.color;\n\n ctx.beginPath();\n ctx.moveTo(x1, y1);\n ctx.lineTo(x2, y2);\n ctx.stroke();\n\n ctx.restore();\n }\n\n /**\n\t * @protected\n\t */\n drawLabels(chartArea) {\n const optionTicks = this.options.ticks;\n\n if (!optionTicks.display) {\n return;\n }\n\n const ctx = this.ctx;\n\n const area = this._computeLabelArea();\n if (area) {\n clipArea(ctx, area);\n }\n\n const items = this.getLabelItems(chartArea);\n for (const item of items) {\n const renderTextOptions = item.options;\n const tickFont = item.font;\n const label = item.label;\n const y = item.textOffset;\n renderText(ctx, label, 0, y, tickFont, renderTextOptions);\n }\n\n if (area) {\n unclipArea(ctx);\n }\n }\n\n /**\n\t * @protected\n\t */\n drawTitle() {\n const {ctx, options: {position, title, reverse}} = this;\n\n if (!title.display) {\n return;\n }\n\n const font = toFont(title.font);\n const padding = toPadding(title.padding);\n const align = title.align;\n let offset = font.lineHeight / 2;\n\n if (position === 'bottom' || position === 'center' || isObject(position)) {\n offset += padding.bottom;\n if (isArray(title.text)) {\n offset += font.lineHeight * (title.text.length - 1);\n }\n } else {\n offset += padding.top;\n }\n\n const {titleX, titleY, maxWidth, rotation} = titleArgs(this, offset, position, align);\n\n renderText(ctx, title.text, 0, 0, font, {\n color: title.color,\n maxWidth,\n rotation,\n textAlign: titleAlign(align, position, reverse),\n textBaseline: 'middle',\n translation: [titleX, titleY],\n });\n }\n\n draw(chartArea) {\n if (!this._isVisible()) {\n return;\n }\n\n this.drawBackground();\n this.drawGrid(chartArea);\n this.drawBorder();\n this.drawTitle();\n this.drawLabels(chartArea);\n }\n\n /**\n\t * @return {object[]}\n\t * @private\n\t */\n _layers() {\n const opts = this.options;\n const tz = opts.ticks && opts.ticks.z || 0;\n const gz = valueOrDefault(opts.grid && opts.grid.z, -1);\n const bz = valueOrDefault(opts.border && opts.border.z, 0);\n\n if (!this._isVisible() || this.draw !== Scale.prototype.draw) {\n // backward compatibility: draw has been overridden by custom scale\n return [{\n z: tz,\n draw: (chartArea) => {\n this.draw(chartArea);\n }\n }];\n }\n\n return [{\n z: gz,\n draw: (chartArea) => {\n this.drawBackground();\n this.drawGrid(chartArea);\n this.drawTitle();\n }\n }, {\n z: bz,\n draw: () => {\n this.drawBorder();\n }\n }, {\n z: tz,\n draw: (chartArea) => {\n this.drawLabels(chartArea);\n }\n }];\n }\n\n /**\n\t * Returns visible dataset metas that are attached to this scale\n\t * @param {string} [type] - if specified, also filter by dataset type\n\t * @return {object[]}\n\t */\n getMatchingVisibleMetas(type) {\n const metas = this.chart.getSortedVisibleDatasetMetas();\n const axisID = this.axis + 'AxisID';\n const result = [];\n let i, ilen;\n\n for (i = 0, ilen = metas.length; i < ilen; ++i) {\n const meta = metas[i];\n if (meta[axisID] === this.id && (!type || meta.type === type)) {\n result.push(meta);\n }\n }\n return result;\n }\n\n /**\n\t * @param {number} index\n\t * @return {object}\n\t * @protected\n \t */\n _resolveTickFontOptions(index) {\n const opts = this.options.ticks.setContext(this.getContext(index));\n return toFont(opts.font);\n }\n\n /**\n * @protected\n */\n _maxDigits() {\n const fontSize = this._resolveTickFontOptions(0).lineHeight;\n return (this.isHorizontal() ? this.width : this.height) / fontSize;\n }\n}\n", "import {merge} from '../helpers/index.js';\nimport defaults, {overrides} from './core.defaults.js';\n\n/**\n * @typedef {{id: string, defaults: any, overrides?: any, defaultRoutes: any}} IChartComponent\n */\n\nexport default class TypedRegistry {\n constructor(type, scope, override) {\n this.type = type;\n this.scope = scope;\n this.override = override;\n this.items = Object.create(null);\n }\n\n isForType(type) {\n return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype);\n }\n\n /**\n\t * @param {IChartComponent} item\n\t * @returns {string} The scope where items defaults were registered to.\n\t */\n register(item) {\n const proto = Object.getPrototypeOf(item);\n let parentScope;\n\n if (isIChartComponent(proto)) {\n // Make sure the parent is registered and note the scope where its defaults are.\n parentScope = this.register(proto);\n }\n\n const items = this.items;\n const id = item.id;\n const scope = this.scope + '.' + id;\n\n if (!id) {\n throw new Error('class does not have id: ' + item);\n }\n\n if (id in items) {\n // already registered\n return scope;\n }\n\n items[id] = item;\n registerDefaults(item, scope, parentScope);\n if (this.override) {\n defaults.override(item.id, item.overrides);\n }\n\n return scope;\n }\n\n /**\n\t * @param {string} id\n\t * @returns {object?}\n\t */\n get(id) {\n return this.items[id];\n }\n\n /**\n\t * @param {IChartComponent} item\n\t */\n unregister(item) {\n const items = this.items;\n const id = item.id;\n const scope = this.scope;\n\n if (id in items) {\n delete items[id];\n }\n\n if (scope && id in defaults[scope]) {\n delete defaults[scope][id];\n if (this.override) {\n delete overrides[id];\n }\n }\n }\n}\n\nfunction registerDefaults(item, scope, parentScope) {\n // Inherit the parent's defaults and keep existing defaults\n const itemDefaults = merge(Object.create(null), [\n parentScope ? defaults.get(parentScope) : {},\n defaults.get(scope),\n item.defaults\n ]);\n\n defaults.set(scope, itemDefaults);\n\n if (item.defaultRoutes) {\n routeDefaults(scope, item.defaultRoutes);\n }\n\n if (item.descriptors) {\n defaults.describe(scope, item.descriptors);\n }\n}\n\nfunction routeDefaults(scope, routes) {\n Object.keys(routes).forEach(property => {\n const propertyParts = property.split('.');\n const sourceName = propertyParts.pop();\n const sourceScope = [scope].concat(propertyParts).join('.');\n const parts = routes[property].split('.');\n const targetName = parts.pop();\n const targetScope = parts.join('.');\n defaults.route(sourceScope, sourceName, targetScope, targetName);\n });\n}\n\nfunction isIChartComponent(proto) {\n return 'id' in proto && 'defaults' in proto;\n}\n", "import DatasetController from './core.datasetController.js';\nimport Element from './core.element.js';\nimport Scale from './core.scale.js';\nimport TypedRegistry from './core.typedRegistry.js';\nimport {each, callback as call, _capitalize} from '../helpers/helpers.core.js';\n\n/**\n * Please use the module's default export which provides a singleton instance\n * Note: class is exported for typedoc\n */\nexport class Registry {\n constructor() {\n this.controllers = new TypedRegistry(DatasetController, 'datasets', true);\n this.elements = new TypedRegistry(Element, 'elements');\n this.plugins = new TypedRegistry(Object, 'plugins');\n this.scales = new TypedRegistry(Scale, 'scales');\n // Order is important, Scale has Element in prototype chain,\n // so Scales must be before Elements. Plugins are a fallback, so not listed here.\n this._typedRegistries = [this.controllers, this.scales, this.elements];\n }\n\n /**\n\t * @param {...any} args\n\t */\n add(...args) {\n this._each('register', args);\n }\n\n remove(...args) {\n this._each('unregister', args);\n }\n\n /**\n\t * @param {...typeof DatasetController} args\n\t */\n addControllers(...args) {\n this._each('register', args, this.controllers);\n }\n\n /**\n\t * @param {...typeof Element} args\n\t */\n addElements(...args) {\n this._each('register', args, this.elements);\n }\n\n /**\n\t * @param {...any} args\n\t */\n addPlugins(...args) {\n this._each('register', args, this.plugins);\n }\n\n /**\n\t * @param {...typeof Scale} args\n\t */\n addScales(...args) {\n this._each('register', args, this.scales);\n }\n\n /**\n\t * @param {string} id\n\t * @returns {typeof DatasetController}\n\t */\n getController(id) {\n return this._get(id, this.controllers, 'controller');\n }\n\n /**\n\t * @param {string} id\n\t * @returns {typeof Element}\n\t */\n getElement(id) {\n return this._get(id, this.elements, 'element');\n }\n\n /**\n\t * @param {string} id\n\t * @returns {object}\n\t */\n getPlugin(id) {\n return this._get(id, this.plugins, 'plugin');\n }\n\n /**\n\t * @param {string} id\n\t * @returns {typeof Scale}\n\t */\n getScale(id) {\n return this._get(id, this.scales, 'scale');\n }\n\n /**\n\t * @param {...typeof DatasetController} args\n\t */\n removeControllers(...args) {\n this._each('unregister', args, this.controllers);\n }\n\n /**\n\t * @param {...typeof Element} args\n\t */\n removeElements(...args) {\n this._each('unregister', args, this.elements);\n }\n\n /**\n\t * @param {...any} args\n\t */\n removePlugins(...args) {\n this._each('unregister', args, this.plugins);\n }\n\n /**\n\t * @param {...typeof Scale} args\n\t */\n removeScales(...args) {\n this._each('unregister', args, this.scales);\n }\n\n /**\n\t * @private\n\t */\n _each(method, args, typedRegistry) {\n [...args].forEach(arg => {\n const reg = typedRegistry || this._getRegistryForType(arg);\n if (typedRegistry || reg.isForType(arg) || (reg === this.plugins && arg.id)) {\n this._exec(method, reg, arg);\n } else {\n // Handle loopable args\n // Use case:\n // import * as plugins from './plugins.js';\n // Chart.register(plugins);\n each(arg, item => {\n // If there are mixed types in the loopable, make sure those are\n // registered in correct registry\n // Use case: (treemap exporting controller, elements etc)\n // import * as treemap from 'chartjs-chart-treemap.js';\n // Chart.register(treemap);\n\n const itemReg = typedRegistry || this._getRegistryForType(item);\n this._exec(method, itemReg, item);\n });\n }\n });\n }\n\n /**\n\t * @private\n\t */\n _exec(method, registry, component) {\n const camelMethod = _capitalize(method);\n call(component['before' + camelMethod], [], component); // beforeRegister / beforeUnregister\n registry[method](component);\n call(component['after' + camelMethod], [], component); // afterRegister / afterUnregister\n }\n\n /**\n\t * @private\n\t */\n _getRegistryForType(type) {\n for (let i = 0; i < this._typedRegistries.length; i++) {\n const reg = this._typedRegistries[i];\n if (reg.isForType(type)) {\n return reg;\n }\n }\n // plugins is the fallback registry\n return this.plugins;\n }\n\n /**\n\t * @private\n\t */\n _get(id, typedRegistry, type) {\n const item = typedRegistry.get(id);\n if (item === undefined) {\n throw new Error('\"' + id + '\" is not a registered ' + type + '.');\n }\n return item;\n }\n\n}\n\n// singleton instance\nexport default /* #__PURE__ */ new Registry();\n", "import registry from './core.registry.js';\nimport {callback as callCallback, isNullOrUndef, valueOrDefault} from '../helpers/helpers.core.js';\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n * @typedef { import('../types/index.js').ChartEvent } ChartEvent\n * @typedef { import('../plugins/plugin.tooltip.js').default } Tooltip\n */\n\n/**\n * @callback filterCallback\n * @param {{plugin: object, options: object}} value\n * @param {number} [index]\n * @param {array} [array]\n * @param {object} [thisArg]\n * @return {boolean}\n */\n\n\nexport default class PluginService {\n constructor() {\n this._init = [];\n }\n\n /**\n\t * Calls enabled plugins for `chart` on the specified hook and with the given args.\n\t * This method immediately returns as soon as a plugin explicitly returns false. The\n\t * returned value can be used, for instance, to interrupt the current action.\n\t * @param {Chart} chart - The chart instance for which plugins should be called.\n\t * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').\n\t * @param {object} [args] - Extra arguments to apply to the hook call.\n * @param {filterCallback} [filter] - Filtering function for limiting which plugins are notified\n\t * @returns {boolean} false if any of the plugins return false, else returns true.\n\t */\n notify(chart, hook, args, filter) {\n if (hook === 'beforeInit') {\n this._init = this._createDescriptors(chart, true);\n this._notify(this._init, chart, 'install');\n }\n\n const descriptors = filter ? this._descriptors(chart).filter(filter) : this._descriptors(chart);\n const result = this._notify(descriptors, chart, hook, args);\n\n if (hook === 'afterDestroy') {\n this._notify(descriptors, chart, 'stop');\n this._notify(this._init, chart, 'uninstall');\n }\n return result;\n }\n\n /**\n\t * @private\n\t */\n _notify(descriptors, chart, hook, args) {\n args = args || {};\n for (const descriptor of descriptors) {\n const plugin = descriptor.plugin;\n const method = plugin[hook];\n const params = [chart, args, descriptor.options];\n if (callCallback(method, params, plugin) === false && args.cancelable) {\n return false;\n }\n }\n\n return true;\n }\n\n invalidate() {\n // When plugins are registered, there is the possibility of a double\n // invalidate situation. In this case, we only want to invalidate once.\n // If we invalidate multiple times, the `_oldCache` is lost and all of the\n // plugins are restarted without being correctly stopped.\n // See https://github.com/chartjs/Chart.js/issues/8147\n if (!isNullOrUndef(this._cache)) {\n this._oldCache = this._cache;\n this._cache = undefined;\n }\n }\n\n /**\n\t * @param {Chart} chart\n\t * @private\n\t */\n _descriptors(chart) {\n if (this._cache) {\n return this._cache;\n }\n\n const descriptors = this._cache = this._createDescriptors(chart);\n\n this._notifyStateChanges(chart);\n\n return descriptors;\n }\n\n _createDescriptors(chart, all) {\n const config = chart && chart.config;\n const options = valueOrDefault(config.options && config.options.plugins, {});\n const plugins = allPlugins(config);\n // options === false => all plugins are disabled\n return options === false && !all ? [] : createDescriptors(chart, plugins, options, all);\n }\n\n /**\n\t * @param {Chart} chart\n\t * @private\n\t */\n _notifyStateChanges(chart) {\n const previousDescriptors = this._oldCache || [];\n const descriptors = this._cache;\n const diff = (a, b) => a.filter(x => !b.some(y => x.plugin.id === y.plugin.id));\n this._notify(diff(previousDescriptors, descriptors), chart, 'stop');\n this._notify(diff(descriptors, previousDescriptors), chart, 'start');\n }\n}\n\n/**\n * @param {import('./core.config.js').default} config\n */\nfunction allPlugins(config) {\n const localIds = {};\n const plugins = [];\n const keys = Object.keys(registry.plugins.items);\n for (let i = 0; i < keys.length; i++) {\n plugins.push(registry.getPlugin(keys[i]));\n }\n\n const local = config.plugins || [];\n for (let i = 0; i < local.length; i++) {\n const plugin = local[i];\n\n if (plugins.indexOf(plugin) === -1) {\n plugins.push(plugin);\n localIds[plugin.id] = true;\n }\n }\n\n return {plugins, localIds};\n}\n\nfunction getOpts(options, all) {\n if (!all && options === false) {\n return null;\n }\n if (options === true) {\n return {};\n }\n return options;\n}\n\nfunction createDescriptors(chart, {plugins, localIds}, options, all) {\n const result = [];\n const context = chart.getContext();\n\n for (const plugin of plugins) {\n const id = plugin.id;\n const opts = getOpts(options[id], all);\n if (opts === null) {\n continue;\n }\n result.push({\n plugin,\n options: pluginOpts(chart.config, {plugin, local: localIds[id]}, opts, context)\n });\n }\n\n return result;\n}\n\nfunction pluginOpts(config, {plugin, local}, opts, context) {\n const keys = config.pluginScopeKeys(plugin);\n const scopes = config.getOptionScopes(opts, keys);\n if (local && plugin.defaults) {\n // make sure plugin defaults are in scopes for local (not registered) plugins\n scopes.push(plugin.defaults);\n }\n return config.createResolver(scopes, context, [''], {\n // These are just defaults that plugins can override\n scriptable: false,\n indexable: false,\n allKeys: true\n });\n}\n", "import defaults, {overrides, descriptors} from './core.defaults.js';\nimport {mergeIf, resolveObjectKey, isArray, isFunction, valueOrDefault, isObject} from '../helpers/helpers.core.js';\nimport {_attachContext, _createResolver, _descriptors} from '../helpers/helpers.config.js';\n\nexport function getIndexAxis(type, options) {\n const datasetDefaults = defaults.datasets[type] || {};\n const datasetOptions = (options.datasets || {})[type] || {};\n return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x';\n}\n\nfunction getAxisFromDefaultScaleID(id, indexAxis) {\n let axis = id;\n if (id === '_index_') {\n axis = indexAxis;\n } else if (id === '_value_') {\n axis = indexAxis === 'x' ? 'y' : 'x';\n }\n return axis;\n}\n\nfunction getDefaultScaleIDFromAxis(axis, indexAxis) {\n return axis === indexAxis ? '_index_' : '_value_';\n}\n\nfunction idMatchesAxis(id) {\n if (id === 'x' || id === 'y' || id === 'r') {\n return id;\n }\n}\n\nfunction axisFromPosition(position) {\n if (position === 'top' || position === 'bottom') {\n return 'x';\n }\n if (position === 'left' || position === 'right') {\n return 'y';\n }\n}\n\nexport function determineAxis(id, ...scaleOptions) {\n if (idMatchesAxis(id)) {\n return id;\n }\n for (const opts of scaleOptions) {\n const axis = opts.axis\n || axisFromPosition(opts.position)\n || id.length > 1 && idMatchesAxis(id[0].toLowerCase());\n if (axis) {\n return axis;\n }\n }\n throw new Error(`Cannot determine type of '${id}' axis. Please provide 'axis' or 'position' option.`);\n}\n\nfunction getAxisFromDataset(id, axis, dataset) {\n if (dataset[axis + 'AxisID'] === id) {\n return {axis};\n }\n}\n\nfunction retrieveAxisFromDatasets(id, config) {\n if (config.data && config.data.datasets) {\n const boundDs = config.data.datasets.filter((d) => d.xAxisID === id || d.yAxisID === id);\n if (boundDs.length) {\n return getAxisFromDataset(id, 'x', boundDs[0]) || getAxisFromDataset(id, 'y', boundDs[0]);\n }\n }\n return {};\n}\n\nfunction mergeScaleConfig(config, options) {\n const chartDefaults = overrides[config.type] || {scales: {}};\n const configScales = options.scales || {};\n const chartIndexAxis = getIndexAxis(config.type, options);\n const scales = Object.create(null);\n\n // First figure out first scale id's per axis.\n Object.keys(configScales).forEach(id => {\n const scaleConf = configScales[id];\n if (!isObject(scaleConf)) {\n return console.error(`Invalid scale configuration for scale: ${id}`);\n }\n if (scaleConf._proxy) {\n return console.warn(`Ignoring resolver passed as options for scale: ${id}`);\n }\n const axis = determineAxis(id, scaleConf, retrieveAxisFromDatasets(id, config), defaults.scales[scaleConf.type]);\n const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis);\n const defaultScaleOptions = chartDefaults.scales || {};\n scales[id] = mergeIf(Object.create(null), [{axis}, scaleConf, defaultScaleOptions[axis], defaultScaleOptions[defaultId]]);\n });\n\n // Then merge dataset defaults to scale configs\n config.data.datasets.forEach(dataset => {\n const type = dataset.type || config.type;\n const indexAxis = dataset.indexAxis || getIndexAxis(type, options);\n const datasetDefaults = overrides[type] || {};\n const defaultScaleOptions = datasetDefaults.scales || {};\n Object.keys(defaultScaleOptions).forEach(defaultID => {\n const axis = getAxisFromDefaultScaleID(defaultID, indexAxis);\n const id = dataset[axis + 'AxisID'] || axis;\n scales[id] = scales[id] || Object.create(null);\n mergeIf(scales[id], [{axis}, configScales[id], defaultScaleOptions[defaultID]]);\n });\n });\n\n // apply scale defaults, if not overridden by dataset defaults\n Object.keys(scales).forEach(key => {\n const scale = scales[key];\n mergeIf(scale, [defaults.scales[scale.type], defaults.scale]);\n });\n\n return scales;\n}\n\nfunction initOptions(config) {\n const options = config.options || (config.options = {});\n\n options.plugins = valueOrDefault(options.plugins, {});\n options.scales = mergeScaleConfig(config, options);\n}\n\nfunction initData(data) {\n data = data || {};\n data.datasets = data.datasets || [];\n data.labels = data.labels || [];\n return data;\n}\n\nfunction initConfig(config) {\n config = config || {};\n config.data = initData(config.data);\n\n initOptions(config);\n\n return config;\n}\n\nconst keyCache = new Map();\nconst keysCached = new Set();\n\nfunction cachedKeys(cacheKey, generate) {\n let keys = keyCache.get(cacheKey);\n if (!keys) {\n keys = generate();\n keyCache.set(cacheKey, keys);\n keysCached.add(keys);\n }\n return keys;\n}\n\nconst addIfFound = (set, obj, key) => {\n const opts = resolveObjectKey(obj, key);\n if (opts !== undefined) {\n set.add(opts);\n }\n};\n\nexport default class Config {\n constructor(config) {\n this._config = initConfig(config);\n this._scopeCache = new Map();\n this._resolverCache = new Map();\n }\n\n get platform() {\n return this._config.platform;\n }\n\n get type() {\n return this._config.type;\n }\n\n set type(type) {\n this._config.type = type;\n }\n\n get data() {\n return this._config.data;\n }\n\n set data(data) {\n this._config.data = initData(data);\n }\n\n get options() {\n return this._config.options;\n }\n\n set options(options) {\n this._config.options = options;\n }\n\n get plugins() {\n return this._config.plugins;\n }\n\n update() {\n const config = this._config;\n this.clearCache();\n initOptions(config);\n }\n\n clearCache() {\n this._scopeCache.clear();\n this._resolverCache.clear();\n }\n\n /**\n * Returns the option scope keys for resolving dataset options.\n * These keys do not include the dataset itself, because it is not under options.\n * @param {string} datasetType\n * @return {string[][]}\n */\n datasetScopeKeys(datasetType) {\n return cachedKeys(datasetType,\n () => [[\n `datasets.${datasetType}`,\n ''\n ]]);\n }\n\n /**\n * Returns the option scope keys for resolving dataset animation options.\n * These keys do not include the dataset itself, because it is not under options.\n * @param {string} datasetType\n * @param {string} transition\n * @return {string[][]}\n */\n datasetAnimationScopeKeys(datasetType, transition) {\n return cachedKeys(`${datasetType}.transition.${transition}`,\n () => [\n [\n `datasets.${datasetType}.transitions.${transition}`,\n `transitions.${transition}`,\n ],\n // The following are used for looking up the `animations` and `animation` keys\n [\n `datasets.${datasetType}`,\n ''\n ]\n ]);\n }\n\n /**\n * Returns the options scope keys for resolving element options that belong\n * to an dataset. These keys do not include the dataset itself, because it\n * is not under options.\n * @param {string} datasetType\n * @param {string} elementType\n * @return {string[][]}\n */\n datasetElementScopeKeys(datasetType, elementType) {\n return cachedKeys(`${datasetType}-${elementType}`,\n () => [[\n `datasets.${datasetType}.elements.${elementType}`,\n `datasets.${datasetType}`,\n `elements.${elementType}`,\n ''\n ]]);\n }\n\n /**\n * Returns the options scope keys for resolving plugin options.\n * @param {{id: string, additionalOptionScopes?: string[]}} plugin\n * @return {string[][]}\n */\n pluginScopeKeys(plugin) {\n const id = plugin.id;\n const type = this.type;\n return cachedKeys(`${type}-plugin-${id}`,\n () => [[\n `plugins.${id}`,\n ...plugin.additionalOptionScopes || [],\n ]]);\n }\n\n /**\n * @private\n */\n _cachedScopes(mainScope, resetCache) {\n const _scopeCache = this._scopeCache;\n let cache = _scopeCache.get(mainScope);\n if (!cache || resetCache) {\n cache = new Map();\n _scopeCache.set(mainScope, cache);\n }\n return cache;\n }\n\n /**\n * Resolves the objects from options and defaults for option value resolution.\n * @param {object} mainScope - The main scope object for options\n * @param {string[][]} keyLists - The arrays of keys in resolution order\n * @param {boolean} [resetCache] - reset the cache for this mainScope\n */\n getOptionScopes(mainScope, keyLists, resetCache) {\n const {options, type} = this;\n const cache = this._cachedScopes(mainScope, resetCache);\n const cached = cache.get(keyLists);\n if (cached) {\n return cached;\n }\n\n const scopes = new Set();\n\n keyLists.forEach(keys => {\n if (mainScope) {\n scopes.add(mainScope);\n keys.forEach(key => addIfFound(scopes, mainScope, key));\n }\n keys.forEach(key => addIfFound(scopes, options, key));\n keys.forEach(key => addIfFound(scopes, overrides[type] || {}, key));\n keys.forEach(key => addIfFound(scopes, defaults, key));\n keys.forEach(key => addIfFound(scopes, descriptors, key));\n });\n\n const array = Array.from(scopes);\n if (array.length === 0) {\n array.push(Object.create(null));\n }\n if (keysCached.has(keyLists)) {\n cache.set(keyLists, array);\n }\n return array;\n }\n\n /**\n * Returns the option scopes for resolving chart options\n * @return {object[]}\n */\n chartOptionScopes() {\n const {options, type} = this;\n\n return [\n options,\n overrides[type] || {},\n defaults.datasets[type] || {}, // https://github.com/chartjs/Chart.js/issues/8531\n {type},\n defaults,\n descriptors\n ];\n }\n\n /**\n * @param {object[]} scopes\n * @param {string[]} names\n * @param {function|object} context\n * @param {string[]} [prefixes]\n * @return {object}\n */\n resolveNamedOptions(scopes, names, context, prefixes = ['']) {\n const result = {$shared: true};\n const {resolver, subPrefixes} = getResolver(this._resolverCache, scopes, prefixes);\n let options = resolver;\n if (needContext(resolver, names)) {\n result.$shared = false;\n context = isFunction(context) ? context() : context;\n // subResolver is passed to scriptable options. It should not resolve to hover options.\n const subResolver = this.createResolver(scopes, context, subPrefixes);\n options = _attachContext(resolver, context, subResolver);\n }\n\n for (const prop of names) {\n result[prop] = options[prop];\n }\n return result;\n }\n\n /**\n * @param {object[]} scopes\n * @param {object} [context]\n * @param {string[]} [prefixes]\n * @param {{scriptable: boolean, indexable: boolean, allKeys?: boolean}} [descriptorDefaults]\n */\n createResolver(scopes, context, prefixes = [''], descriptorDefaults) {\n const {resolver} = getResolver(this._resolverCache, scopes, prefixes);\n return isObject(context)\n ? _attachContext(resolver, context, undefined, descriptorDefaults)\n : resolver;\n }\n}\n\nfunction getResolver(resolverCache, scopes, prefixes) {\n let cache = resolverCache.get(scopes);\n if (!cache) {\n cache = new Map();\n resolverCache.set(scopes, cache);\n }\n const cacheKey = prefixes.join();\n let cached = cache.get(cacheKey);\n if (!cached) {\n const resolver = _createResolver(scopes, prefixes);\n cached = {\n resolver,\n subPrefixes: prefixes.filter(p => !p.toLowerCase().includes('hover'))\n };\n cache.set(cacheKey, cached);\n }\n return cached;\n}\n\nconst hasFunction = value => isObject(value)\n && Object.getOwnPropertyNames(value).some((key) => isFunction(value[key]));\n\nfunction needContext(proxy, names) {\n const {isScriptable, isIndexable} = _descriptors(proxy);\n\n for (const prop of names) {\n const scriptable = isScriptable(prop);\n const indexable = isIndexable(prop);\n const value = (indexable || scriptable) && proxy[prop];\n if ((scriptable && (isFunction(value) || hasFunction(value)))\n || (indexable && isArray(value))) {\n return true;\n }\n }\n return false;\n}\n", "import animator from './core.animator.js';\nimport defaults, {overrides} from './core.defaults.js';\nimport Interaction from './core.interaction.js';\nimport layouts from './core.layouts.js';\nimport {_detectPlatform} from '../platform/index.js';\nimport PluginService from './core.plugins.js';\nimport registry from './core.registry.js';\nimport Config, {determineAxis, getIndexAxis} from './core.config.js';\nimport {retinaScale, _isDomSupported} from '../helpers/helpers.dom.js';\nimport {each, callback as callCallback, uid, valueOrDefault, _elementsEqual, isNullOrUndef, setsEqual, defined, isFunction, _isClickEvent} from '../helpers/helpers.core.js';\nimport {clearCanvas, clipArea, createContext, unclipArea, _isPointInArea} from '../helpers/index.js';\n// @ts-ignore\nimport {version} from '../../package.json';\nimport {debounce} from '../helpers/helpers.extras.js';\n\n/**\n * @typedef { import('../types/index.js').ChartEvent } ChartEvent\n * @typedef { import('../types/index.js').Point } Point\n */\n\nconst KNOWN_POSITIONS = ['top', 'bottom', 'left', 'right', 'chartArea'];\nfunction positionIsHorizontal(position, axis) {\n return position === 'top' || position === 'bottom' || (KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x');\n}\n\nfunction compare2Level(l1, l2) {\n return function(a, b) {\n return a[l1] === b[l1]\n ? a[l2] - b[l2]\n : a[l1] - b[l1];\n };\n}\n\nfunction onAnimationsComplete(context) {\n const chart = context.chart;\n const animationOptions = chart.options.animation;\n\n chart.notifyPlugins('afterRender');\n callCallback(animationOptions && animationOptions.onComplete, [context], chart);\n}\n\nfunction onAnimationProgress(context) {\n const chart = context.chart;\n const animationOptions = chart.options.animation;\n callCallback(animationOptions && animationOptions.onProgress, [context], chart);\n}\n\n/**\n * Chart.js can take a string id of a canvas element, a 2d context, or a canvas element itself.\n * Attempt to unwrap the item passed into the chart constructor so that it is a canvas element (if possible).\n */\nfunction getCanvas(item) {\n if (_isDomSupported() && typeof item === 'string') {\n item = document.getElementById(item);\n } else if (item && item.length) {\n // Support for array based queries (such as jQuery)\n item = item[0];\n }\n\n if (item && item.canvas) {\n // Support for any object associated to a canvas (including a context2d)\n item = item.canvas;\n }\n return item;\n}\n\nconst instances = {};\nconst getChart = (key) => {\n const canvas = getCanvas(key);\n return Object.values(instances).filter((c) => c.canvas === canvas).pop();\n};\n\nfunction moveNumericKeys(obj, start, move) {\n const keys = Object.keys(obj);\n for (const key of keys) {\n const intKey = +key;\n if (intKey >= start) {\n const value = obj[key];\n delete obj[key];\n if (move > 0 || intKey > start) {\n obj[intKey + move] = value;\n }\n }\n }\n}\n\n/**\n * @param {ChartEvent} e\n * @param {ChartEvent|null} lastEvent\n * @param {boolean} inChartArea\n * @param {boolean} isClick\n * @returns {ChartEvent|null}\n */\nfunction determineLastEvent(e, lastEvent, inChartArea, isClick) {\n if (!inChartArea || e.type === 'mouseout') {\n return null;\n }\n if (isClick) {\n return lastEvent;\n }\n return e;\n}\n\nfunction getSizeForArea(scale, chartArea, field) {\n return scale.options.clip ? scale[field] : chartArea[field];\n}\n\nfunction getDatasetArea(meta, chartArea) {\n const {xScale, yScale} = meta;\n if (xScale && yScale) {\n return {\n left: getSizeForArea(xScale, chartArea, 'left'),\n right: getSizeForArea(xScale, chartArea, 'right'),\n top: getSizeForArea(yScale, chartArea, 'top'),\n bottom: getSizeForArea(yScale, chartArea, 'bottom')\n };\n }\n return chartArea;\n}\n\nclass Chart {\n\n static defaults = defaults;\n static instances = instances;\n static overrides = overrides;\n static registry = registry;\n static version = version;\n static getChart = getChart;\n\n static register(...items) {\n registry.add(...items);\n invalidatePlugins();\n }\n\n static unregister(...items) {\n registry.remove(...items);\n invalidatePlugins();\n }\n\n // eslint-disable-next-line max-statements\n constructor(item, userConfig) {\n const config = this.config = new Config(userConfig);\n const initialCanvas = getCanvas(item);\n const existingChart = getChart(initialCanvas);\n if (existingChart) {\n throw new Error(\n 'Canvas is already in use. Chart with ID \\'' + existingChart.id + '\\'' +\n\t\t\t\t' must be destroyed before the canvas with ID \\'' + existingChart.canvas.id + '\\' can be reused.'\n );\n }\n\n const options = config.createResolver(config.chartOptionScopes(), this.getContext());\n\n this.platform = new (config.platform || _detectPlatform(initialCanvas))();\n this.platform.updateConfig(config);\n\n const context = this.platform.acquireContext(initialCanvas, options.aspectRatio);\n const canvas = context && context.canvas;\n const height = canvas && canvas.height;\n const width = canvas && canvas.width;\n\n this.id = uid();\n this.ctx = context;\n this.canvas = canvas;\n this.width = width;\n this.height = height;\n this._options = options;\n // Store the previously used aspect ratio to determine if a resize\n // is needed during updates. Do this after _options is set since\n // aspectRatio uses a getter\n this._aspectRatio = this.aspectRatio;\n this._layers = [];\n this._metasets = [];\n this._stacks = undefined;\n this.boxes = [];\n this.currentDevicePixelRatio = undefined;\n this.chartArea = undefined;\n this._active = [];\n this._lastEvent = undefined;\n this._listeners = {};\n /** @type {?{attach?: function, detach?: function, resize?: function}} */\n this._responsiveListeners = undefined;\n this._sortedMetasets = [];\n this.scales = {};\n this._plugins = new PluginService();\n this.$proxies = {};\n this._hiddenIndices = {};\n this.attached = false;\n this._animationsDisabled = undefined;\n this.$context = undefined;\n this._doResize = debounce(mode => this.update(mode), options.resizeDelay || 0);\n this._dataChanges = [];\n\n // Add the chart instance to the global namespace\n instances[this.id] = this;\n\n if (!context || !canvas) {\n // The given item is not a compatible context2d element, let's return before finalizing\n // the chart initialization but after setting basic chart / controller properties that\n // can help to figure out that the chart is not valid (e.g chart.canvas !== null);\n // https://github.com/chartjs/Chart.js/issues/2807\n console.error(\"Failed to create chart: can't acquire context from the given item\");\n return;\n }\n\n animator.listen(this, 'complete', onAnimationsComplete);\n animator.listen(this, 'progress', onAnimationProgress);\n\n this._initialize();\n if (this.attached) {\n this.update();\n }\n }\n\n get aspectRatio() {\n const {options: {aspectRatio, maintainAspectRatio}, width, height, _aspectRatio} = this;\n if (!isNullOrUndef(aspectRatio)) {\n // If aspectRatio is defined in options, use that.\n return aspectRatio;\n }\n\n if (maintainAspectRatio && _aspectRatio) {\n // If maintainAspectRatio is truthly and we had previously determined _aspectRatio, use that\n return _aspectRatio;\n }\n\n // Calculate\n return height ? width / height : null;\n }\n\n get data() {\n return this.config.data;\n }\n\n set data(data) {\n this.config.data = data;\n }\n\n get options() {\n return this._options;\n }\n\n set options(options) {\n this.config.options = options;\n }\n\n get registry() {\n return registry;\n }\n\n /**\n\t * @private\n\t */\n _initialize() {\n // Before init plugin notification\n this.notifyPlugins('beforeInit');\n\n if (this.options.responsive) {\n this.resize();\n } else {\n retinaScale(this, this.options.devicePixelRatio);\n }\n\n this.bindEvents();\n\n // After init plugin notification\n this.notifyPlugins('afterInit');\n\n return this;\n }\n\n clear() {\n clearCanvas(this.canvas, this.ctx);\n return this;\n }\n\n stop() {\n animator.stop(this);\n return this;\n }\n\n /**\n\t * Resize the chart to its container or to explicit dimensions.\n\t * @param {number} [width]\n\t * @param {number} [height]\n\t */\n resize(width, height) {\n if (!animator.running(this)) {\n this._resize(width, height);\n } else {\n this._resizeBeforeDraw = {width, height};\n }\n }\n\n _resize(width, height) {\n const options = this.options;\n const canvas = this.canvas;\n const aspectRatio = options.maintainAspectRatio && this.aspectRatio;\n const newSize = this.platform.getMaximumSize(canvas, width, height, aspectRatio);\n const newRatio = options.devicePixelRatio || this.platform.getDevicePixelRatio();\n const mode = this.width ? 'resize' : 'attach';\n\n this.width = newSize.width;\n this.height = newSize.height;\n this._aspectRatio = this.aspectRatio;\n if (!retinaScale(this, newRatio, true)) {\n return;\n }\n\n this.notifyPlugins('resize', {size: newSize});\n\n callCallback(options.onResize, [this, newSize], this);\n\n if (this.attached) {\n if (this._doResize(mode)) {\n // The resize update is delayed, only draw without updating.\n this.render();\n }\n }\n }\n\n ensureScalesHaveIDs() {\n const options = this.options;\n const scalesOptions = options.scales || {};\n\n each(scalesOptions, (axisOptions, axisID) => {\n axisOptions.id = axisID;\n });\n }\n\n /**\n\t * Builds a map of scale ID to scale object for future lookup.\n\t */\n buildOrUpdateScales() {\n const options = this.options;\n const scaleOpts = options.scales;\n const scales = this.scales;\n const updated = Object.keys(scales).reduce((obj, id) => {\n obj[id] = false;\n return obj;\n }, {});\n let items = [];\n\n if (scaleOpts) {\n items = items.concat(\n Object.keys(scaleOpts).map((id) => {\n const scaleOptions = scaleOpts[id];\n const axis = determineAxis(id, scaleOptions);\n const isRadial = axis === 'r';\n const isHorizontal = axis === 'x';\n return {\n options: scaleOptions,\n dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left',\n dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear'\n };\n })\n );\n }\n\n each(items, (item) => {\n const scaleOptions = item.options;\n const id = scaleOptions.id;\n const axis = determineAxis(id, scaleOptions);\n const scaleType = valueOrDefault(scaleOptions.type, item.dtype);\n\n if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) {\n scaleOptions.position = item.dposition;\n }\n\n updated[id] = true;\n let scale = null;\n if (id in scales && scales[id].type === scaleType) {\n scale = scales[id];\n } else {\n const scaleClass = registry.getScale(scaleType);\n scale = new scaleClass({\n id,\n type: scaleType,\n ctx: this.ctx,\n chart: this\n });\n scales[scale.id] = scale;\n }\n\n scale.init(scaleOptions, options);\n });\n // clear up discarded scales\n each(updated, (hasUpdated, id) => {\n if (!hasUpdated) {\n delete scales[id];\n }\n });\n\n each(scales, (scale) => {\n layouts.configure(this, scale, scale.options);\n layouts.addBox(this, scale);\n });\n }\n\n /**\n\t * @private\n\t */\n _updateMetasets() {\n const metasets = this._metasets;\n const numData = this.data.datasets.length;\n const numMeta = metasets.length;\n\n metasets.sort((a, b) => a.index - b.index);\n if (numMeta > numData) {\n for (let i = numData; i < numMeta; ++i) {\n this._destroyDatasetMeta(i);\n }\n metasets.splice(numData, numMeta - numData);\n }\n this._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index'));\n }\n\n /**\n\t * @private\n\t */\n _removeUnreferencedMetasets() {\n const {_metasets: metasets, data: {datasets}} = this;\n if (metasets.length > datasets.length) {\n delete this._stacks;\n }\n metasets.forEach((meta, index) => {\n if (datasets.filter(x => x === meta._dataset).length === 0) {\n this._destroyDatasetMeta(index);\n }\n });\n }\n\n buildOrUpdateControllers() {\n const newControllers = [];\n const datasets = this.data.datasets;\n let i, ilen;\n\n this._removeUnreferencedMetasets();\n\n for (i = 0, ilen = datasets.length; i < ilen; i++) {\n const dataset = datasets[i];\n let meta = this.getDatasetMeta(i);\n const type = dataset.type || this.config.type;\n\n if (meta.type && meta.type !== type) {\n this._destroyDatasetMeta(i);\n meta = this.getDatasetMeta(i);\n }\n meta.type = type;\n meta.indexAxis = dataset.indexAxis || getIndexAxis(type, this.options);\n meta.order = dataset.order || 0;\n meta.index = i;\n meta.label = '' + dataset.label;\n meta.visible = this.isDatasetVisible(i);\n\n if (meta.controller) {\n meta.controller.updateIndex(i);\n meta.controller.linkScales();\n } else {\n const ControllerClass = registry.getController(type);\n const {datasetElementType, dataElementType} = defaults.datasets[type];\n Object.assign(ControllerClass, {\n dataElementType: registry.getElement(dataElementType),\n datasetElementType: datasetElementType && registry.getElement(datasetElementType)\n });\n meta.controller = new ControllerClass(this, i);\n newControllers.push(meta.controller);\n }\n }\n\n this._updateMetasets();\n return newControllers;\n }\n\n /**\n\t * Reset the elements of all datasets\n\t * @private\n\t */\n _resetElements() {\n each(this.data.datasets, (dataset, datasetIndex) => {\n this.getDatasetMeta(datasetIndex).controller.reset();\n }, this);\n }\n\n /**\n\t* Resets the chart back to its state before the initial animation\n\t*/\n reset() {\n this._resetElements();\n this.notifyPlugins('reset');\n }\n\n update(mode) {\n const config = this.config;\n\n config.update();\n const options = this._options = config.createResolver(config.chartOptionScopes(), this.getContext());\n const animsDisabled = this._animationsDisabled = !options.animation;\n\n this._updateScales();\n this._checkEventBindings();\n this._updateHiddenIndices();\n\n // plugins options references might have change, let's invalidate the cache\n // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167\n this._plugins.invalidate();\n\n if (this.notifyPlugins('beforeUpdate', {mode, cancelable: true}) === false) {\n return;\n }\n\n // Make sure dataset controllers are updated and new controllers are reset\n const newControllers = this.buildOrUpdateControllers();\n\n this.notifyPlugins('beforeElementsUpdate');\n\n // Make sure all dataset controllers have correct meta data counts\n let minPadding = 0;\n for (let i = 0, ilen = this.data.datasets.length; i < ilen; i++) {\n const {controller} = this.getDatasetMeta(i);\n const reset = !animsDisabled && newControllers.indexOf(controller) === -1;\n // New controllers will be reset after the layout pass, so we only want to modify\n // elements added to new datasets\n controller.buildOrUpdateElements(reset);\n minPadding = Math.max(+controller.getMaxOverflow(), minPadding);\n }\n minPadding = this._minPadding = options.layout.autoPadding ? minPadding : 0;\n this._updateLayout(minPadding);\n\n // Only reset the controllers if we have animations\n if (!animsDisabled) {\n // Can only reset the new controllers after the scales have been updated\n // Reset is done to get the starting point for the initial animation\n each(newControllers, (controller) => {\n controller.reset();\n });\n }\n\n this._updateDatasets(mode);\n\n // Do this before render so that any plugins that need final scale updates can use it\n this.notifyPlugins('afterUpdate', {mode});\n\n this._layers.sort(compare2Level('z', '_idx'));\n\n // Replay last event from before update, or set hover styles on active elements\n const {_active, _lastEvent} = this;\n if (_lastEvent) {\n this._eventHandler(_lastEvent, true);\n } else if (_active.length) {\n this._updateHoverStyles(_active, _active, true);\n }\n\n this.render();\n }\n\n /**\n * @private\n */\n _updateScales() {\n each(this.scales, (scale) => {\n layouts.removeBox(this, scale);\n });\n\n this.ensureScalesHaveIDs();\n this.buildOrUpdateScales();\n }\n\n /**\n * @private\n */\n _checkEventBindings() {\n const options = this.options;\n const existingEvents = new Set(Object.keys(this._listeners));\n const newEvents = new Set(options.events);\n\n if (!setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== options.responsive) {\n // The configured events have changed. Rebind.\n this.unbindEvents();\n this.bindEvents();\n }\n }\n\n /**\n * @private\n */\n _updateHiddenIndices() {\n const {_hiddenIndices} = this;\n const changes = this._getUniformDataChanges() || [];\n for (const {method, start, count} of changes) {\n const move = method === '_removeElements' ? -count : count;\n moveNumericKeys(_hiddenIndices, start, move);\n }\n }\n\n /**\n * @private\n */\n _getUniformDataChanges() {\n const _dataChanges = this._dataChanges;\n if (!_dataChanges || !_dataChanges.length) {\n return;\n }\n\n this._dataChanges = [];\n const datasetCount = this.data.datasets.length;\n const makeSet = (idx) => new Set(\n _dataChanges\n .filter(c => c[0] === idx)\n .map((c, i) => i + ',' + c.splice(1).join(','))\n );\n\n const changeSet = makeSet(0);\n for (let i = 1; i < datasetCount; i++) {\n if (!setsEqual(changeSet, makeSet(i))) {\n return;\n }\n }\n return Array.from(changeSet)\n .map(c => c.split(','))\n .map(a => ({method: a[1], start: +a[2], count: +a[3]}));\n }\n\n /**\n\t * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`\n\t * hook, in which case, plugins will not be called on `afterLayout`.\n\t * @private\n\t */\n _updateLayout(minPadding) {\n if (this.notifyPlugins('beforeLayout', {cancelable: true}) === false) {\n return;\n }\n\n layouts.update(this, this.width, this.height, minPadding);\n\n const area = this.chartArea;\n const noArea = area.width <= 0 || area.height <= 0;\n\n this._layers = [];\n each(this.boxes, (box) => {\n if (noArea && box.position === 'chartArea') {\n // Skip drawing and configuring chartArea boxes when chartArea is zero or negative\n return;\n }\n\n // configure is called twice, once in core.scale.update and once here.\n // Here the boxes are fully updated and at their final positions.\n if (box.configure) {\n box.configure();\n }\n this._layers.push(...box._layers());\n }, this);\n\n this._layers.forEach((item, index) => {\n item._idx = index;\n });\n\n this.notifyPlugins('afterLayout');\n }\n\n /**\n\t * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`\n\t * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.\n\t * @private\n\t */\n _updateDatasets(mode) {\n if (this.notifyPlugins('beforeDatasetsUpdate', {mode, cancelable: true}) === false) {\n return;\n }\n\n for (let i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {\n this.getDatasetMeta(i).controller.configure();\n }\n\n for (let i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {\n this._updateDataset(i, isFunction(mode) ? mode({datasetIndex: i}) : mode);\n }\n\n this.notifyPlugins('afterDatasetsUpdate', {mode});\n }\n\n /**\n\t * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`\n\t * hook, in which case, plugins will not be called on `afterDatasetUpdate`.\n\t * @private\n\t */\n _updateDataset(index, mode) {\n const meta = this.getDatasetMeta(index);\n const args = {meta, index, mode, cancelable: true};\n\n if (this.notifyPlugins('beforeDatasetUpdate', args) === false) {\n return;\n }\n\n meta.controller._update(mode);\n\n args.cancelable = false;\n this.notifyPlugins('afterDatasetUpdate', args);\n }\n\n render() {\n if (this.notifyPlugins('beforeRender', {cancelable: true}) === false) {\n return;\n }\n\n if (animator.has(this)) {\n if (this.attached && !animator.running(this)) {\n animator.start(this);\n }\n } else {\n this.draw();\n onAnimationsComplete({chart: this});\n }\n }\n\n draw() {\n let i;\n if (this._resizeBeforeDraw) {\n const {width, height} = this._resizeBeforeDraw;\n this._resize(width, height);\n this._resizeBeforeDraw = null;\n }\n this.clear();\n\n if (this.width <= 0 || this.height <= 0) {\n return;\n }\n\n if (this.notifyPlugins('beforeDraw', {cancelable: true}) === false) {\n return;\n }\n\n // Because of plugin hooks (before/afterDatasetsDraw), datasets can't\n // currently be part of layers. Instead, we draw\n // layers <= 0 before(default, backward compat), and the rest after\n const layers = this._layers;\n for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {\n layers[i].draw(this.chartArea);\n }\n\n this._drawDatasets();\n\n // Rest of layers\n for (; i < layers.length; ++i) {\n layers[i].draw(this.chartArea);\n }\n\n this.notifyPlugins('afterDraw');\n }\n\n /**\n\t * @private\n\t */\n _getSortedDatasetMetas(filterVisible) {\n const metasets = this._sortedMetasets;\n const result = [];\n let i, ilen;\n\n for (i = 0, ilen = metasets.length; i < ilen; ++i) {\n const meta = metasets[i];\n if (!filterVisible || meta.visible) {\n result.push(meta);\n }\n }\n\n return result;\n }\n\n /**\n\t * Gets the visible dataset metas in drawing order\n\t * @return {object[]}\n\t */\n getSortedVisibleDatasetMetas() {\n return this._getSortedDatasetMetas(true);\n }\n\n /**\n\t * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`\n\t * hook, in which case, plugins will not be called on `afterDatasetsDraw`.\n\t * @private\n\t */\n _drawDatasets() {\n if (this.notifyPlugins('beforeDatasetsDraw', {cancelable: true}) === false) {\n return;\n }\n\n const metasets = this.getSortedVisibleDatasetMetas();\n for (let i = metasets.length - 1; i >= 0; --i) {\n this._drawDataset(metasets[i]);\n }\n\n this.notifyPlugins('afterDatasetsDraw');\n }\n\n /**\n\t * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`\n\t * hook, in which case, plugins will not be called on `afterDatasetDraw`.\n\t * @private\n\t */\n _drawDataset(meta) {\n const ctx = this.ctx;\n const clip = meta._clip;\n const useClip = !clip.disabled;\n const area = getDatasetArea(meta, this.chartArea);\n const args = {\n meta,\n index: meta.index,\n cancelable: true\n };\n\n if (this.notifyPlugins('beforeDatasetDraw', args) === false) {\n return;\n }\n\n if (useClip) {\n clipArea(ctx, {\n left: clip.left === false ? 0 : area.left - clip.left,\n right: clip.right === false ? this.width : area.right + clip.right,\n top: clip.top === false ? 0 : area.top - clip.top,\n bottom: clip.bottom === false ? this.height : area.bottom + clip.bottom\n });\n }\n\n meta.controller.draw();\n\n if (useClip) {\n unclipArea(ctx);\n }\n\n args.cancelable = false;\n this.notifyPlugins('afterDatasetDraw', args);\n }\n\n /**\n * Checks whether the given point is in the chart area.\n * @param {Point} point - in relative coordinates (see, e.g., getRelativePosition)\n * @returns {boolean}\n */\n isPointInArea(point) {\n return _isPointInArea(point, this.chartArea, this._minPadding);\n }\n\n getElementsAtEventForMode(e, mode, options, useFinalPosition) {\n const method = Interaction.modes[mode];\n if (typeof method === 'function') {\n return method(this, e, options, useFinalPosition);\n }\n\n return [];\n }\n\n getDatasetMeta(datasetIndex) {\n const dataset = this.data.datasets[datasetIndex];\n const metasets = this._metasets;\n let meta = metasets.filter(x => x && x._dataset === dataset).pop();\n\n if (!meta) {\n meta = {\n type: null,\n data: [],\n dataset: null,\n controller: null,\n hidden: null,\t\t\t// See isDatasetVisible() comment\n xAxisID: null,\n yAxisID: null,\n order: dataset && dataset.order || 0,\n index: datasetIndex,\n _dataset: dataset,\n _parsed: [],\n _sorted: false\n };\n metasets.push(meta);\n }\n\n return meta;\n }\n\n getContext() {\n return this.$context || (this.$context = createContext(null, {chart: this, type: 'chart'}));\n }\n\n getVisibleDatasetCount() {\n return this.getSortedVisibleDatasetMetas().length;\n }\n\n isDatasetVisible(datasetIndex) {\n const dataset = this.data.datasets[datasetIndex];\n if (!dataset) {\n return false;\n }\n\n const meta = this.getDatasetMeta(datasetIndex);\n\n // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,\n // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.\n return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden;\n }\n\n setDatasetVisibility(datasetIndex, visible) {\n const meta = this.getDatasetMeta(datasetIndex);\n meta.hidden = !visible;\n }\n\n toggleDataVisibility(index) {\n this._hiddenIndices[index] = !this._hiddenIndices[index];\n }\n\n getDataVisibility(index) {\n return !this._hiddenIndices[index];\n }\n\n /**\n\t * @private\n\t */\n _updateVisibility(datasetIndex, dataIndex, visible) {\n const mode = visible ? 'show' : 'hide';\n const meta = this.getDatasetMeta(datasetIndex);\n const anims = meta.controller._resolveAnimations(undefined, mode);\n\n if (defined(dataIndex)) {\n meta.data[dataIndex].hidden = !visible;\n this.update();\n } else {\n this.setDatasetVisibility(datasetIndex, visible);\n // Animate visible state, so hide animation can be seen. This could be handled better if update / updateDataset returned a Promise.\n anims.update(meta, {visible});\n this.update((ctx) => ctx.datasetIndex === datasetIndex ? mode : undefined);\n }\n }\n\n hide(datasetIndex, dataIndex) {\n this._updateVisibility(datasetIndex, dataIndex, false);\n }\n\n show(datasetIndex, dataIndex) {\n this._updateVisibility(datasetIndex, dataIndex, true);\n }\n\n /**\n\t * @private\n\t */\n _destroyDatasetMeta(datasetIndex) {\n const meta = this._metasets[datasetIndex];\n if (meta && meta.controller) {\n meta.controller._destroy();\n }\n delete this._metasets[datasetIndex];\n }\n\n _stop() {\n let i, ilen;\n this.stop();\n animator.remove(this);\n\n for (i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {\n this._destroyDatasetMeta(i);\n }\n }\n\n destroy() {\n this.notifyPlugins('beforeDestroy');\n const {canvas, ctx} = this;\n\n this._stop();\n this.config.clearCache();\n\n if (canvas) {\n this.unbindEvents();\n clearCanvas(canvas, ctx);\n this.platform.releaseContext(ctx);\n this.canvas = null;\n this.ctx = null;\n }\n\n delete instances[this.id];\n\n this.notifyPlugins('afterDestroy');\n }\n\n toBase64Image(...args) {\n return this.canvas.toDataURL(...args);\n }\n\n /**\n\t * @private\n\t */\n bindEvents() {\n this.bindUserEvents();\n if (this.options.responsive) {\n this.bindResponsiveEvents();\n } else {\n this.attached = true;\n }\n }\n\n /**\n * @private\n */\n bindUserEvents() {\n const listeners = this._listeners;\n const platform = this.platform;\n\n const _add = (type, listener) => {\n platform.addEventListener(this, type, listener);\n listeners[type] = listener;\n };\n\n const listener = (e, x, y) => {\n e.offsetX = x;\n e.offsetY = y;\n this._eventHandler(e);\n };\n\n each(this.options.events, (type) => _add(type, listener));\n }\n\n /**\n * @private\n */\n bindResponsiveEvents() {\n if (!this._responsiveListeners) {\n this._responsiveListeners = {};\n }\n const listeners = this._responsiveListeners;\n const platform = this.platform;\n\n const _add = (type, listener) => {\n platform.addEventListener(this, type, listener);\n listeners[type] = listener;\n };\n const _remove = (type, listener) => {\n if (listeners[type]) {\n platform.removeEventListener(this, type, listener);\n delete listeners[type];\n }\n };\n\n const listener = (width, height) => {\n if (this.canvas) {\n this.resize(width, height);\n }\n };\n\n let detached; // eslint-disable-line prefer-const\n const attached = () => {\n _remove('attach', attached);\n\n this.attached = true;\n this.resize();\n\n _add('resize', listener);\n _add('detach', detached);\n };\n\n detached = () => {\n this.attached = false;\n\n _remove('resize', listener);\n\n // Stop animating and remove metasets, so when re-attached, the animations start from beginning.\n this._stop();\n this._resize(0, 0);\n\n _add('attach', attached);\n };\n\n if (platform.isAttached(this.canvas)) {\n attached();\n } else {\n detached();\n }\n }\n\n /**\n\t * @private\n\t */\n unbindEvents() {\n each(this._listeners, (listener, type) => {\n this.platform.removeEventListener(this, type, listener);\n });\n this._listeners = {};\n\n each(this._responsiveListeners, (listener, type) => {\n this.platform.removeEventListener(this, type, listener);\n });\n this._responsiveListeners = undefined;\n }\n\n updateHoverStyle(items, mode, enabled) {\n const prefix = enabled ? 'set' : 'remove';\n let meta, item, i, ilen;\n\n if (mode === 'dataset') {\n meta = this.getDatasetMeta(items[0].datasetIndex);\n meta.controller['_' + prefix + 'DatasetHoverStyle']();\n }\n\n for (i = 0, ilen = items.length; i < ilen; ++i) {\n item = items[i];\n const controller = item && this.getDatasetMeta(item.datasetIndex).controller;\n if (controller) {\n controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index);\n }\n }\n }\n\n /**\n\t * Get active (hovered) elements\n\t * @returns array\n\t */\n getActiveElements() {\n return this._active || [];\n }\n\n /**\n\t * Set active (hovered) elements\n\t * @param {array} activeElements New active data points\n\t */\n setActiveElements(activeElements) {\n const lastActive = this._active || [];\n const active = activeElements.map(({datasetIndex, index}) => {\n const meta = this.getDatasetMeta(datasetIndex);\n if (!meta) {\n throw new Error('No dataset found at index ' + datasetIndex);\n }\n\n return {\n datasetIndex,\n element: meta.data[index],\n index,\n };\n });\n const changed = !_elementsEqual(active, lastActive);\n\n if (changed) {\n this._active = active;\n // Make sure we don't use the previous mouse event to override the active elements in update.\n this._lastEvent = null;\n this._updateHoverStyles(active, lastActive);\n }\n }\n\n /**\n\t * Calls enabled plugins on the specified hook and with the given args.\n\t * This method immediately returns as soon as a plugin explicitly returns false. The\n\t * returned value can be used, for instance, to interrupt the current action.\n\t * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').\n\t * @param {Object} [args] - Extra arguments to apply to the hook call.\n * @param {import('./core.plugins.js').filterCallback} [filter] - Filtering function for limiting which plugins are notified\n\t * @returns {boolean} false if any of the plugins return false, else returns true.\n\t */\n notifyPlugins(hook, args, filter) {\n return this._plugins.notify(this, hook, args, filter);\n }\n\n /**\n * Check if a plugin with the specific ID is registered and enabled\n * @param {string} pluginId - The ID of the plugin of which to check if it is enabled\n * @returns {boolean}\n */\n isPluginEnabled(pluginId) {\n return this._plugins._cache.filter(p => p.plugin.id === pluginId).length === 1;\n }\n\n /**\n\t * @private\n\t */\n _updateHoverStyles(active, lastActive, replay) {\n const hoverOptions = this.options.hover;\n const diff = (a, b) => a.filter(x => !b.some(y => x.datasetIndex === y.datasetIndex && x.index === y.index));\n const deactivated = diff(lastActive, active);\n const activated = replay ? active : diff(active, lastActive);\n\n if (deactivated.length) {\n this.updateHoverStyle(deactivated, hoverOptions.mode, false);\n }\n\n if (activated.length && hoverOptions.mode) {\n this.updateHoverStyle(activated, hoverOptions.mode, true);\n }\n }\n\n /**\n\t * @private\n\t */\n _eventHandler(e, replay) {\n const args = {\n event: e,\n replay,\n cancelable: true,\n inChartArea: this.isPointInArea(e)\n };\n const eventFilter = (plugin) => (plugin.options.events || this.options.events).includes(e.native.type);\n\n if (this.notifyPlugins('beforeEvent', args, eventFilter) === false) {\n return;\n }\n\n const changed = this._handleEvent(e, replay, args.inChartArea);\n\n args.cancelable = false;\n this.notifyPlugins('afterEvent', args, eventFilter);\n\n if (changed || args.changed) {\n this.render();\n }\n\n return this;\n }\n\n /**\n\t * Handle an event\n\t * @param {ChartEvent} e the event to handle\n\t * @param {boolean} [replay] - true if the event was replayed by `update`\n * @param {boolean} [inChartArea] - true if the event is inside chartArea\n\t * @return {boolean} true if the chart needs to re-render\n\t * @private\n\t */\n _handleEvent(e, replay, inChartArea) {\n const {_active: lastActive = [], options} = this;\n\n // If the event is replayed from `update`, we should evaluate with the final positions.\n //\n // The `replay`:\n // It's the last event (excluding click) that has occurred before `update`.\n // So mouse has not moved. It's also over the chart, because there is a `replay`.\n //\n // The why:\n // If animations are active, the elements haven't moved yet compared to state before update.\n // But if they will, we are activating the elements that would be active, if this check\n // was done after the animations have completed. => \"final positions\".\n // If there is no animations, the \"final\" and \"current\" positions are equal.\n // This is done so we do not have to evaluate the active elements each animation frame\n // - it would be expensive.\n const useFinalPosition = replay;\n const active = this._getActiveElements(e, lastActive, inChartArea, useFinalPosition);\n const isClick = _isClickEvent(e);\n const lastEvent = determineLastEvent(e, this._lastEvent, inChartArea, isClick);\n\n if (inChartArea) {\n // Set _lastEvent to null while we are processing the event handlers.\n // This prevents recursion if the handler calls chart.update()\n this._lastEvent = null;\n\n // Invoke onHover hook\n callCallback(options.onHover, [e, active, this], this);\n\n if (isClick) {\n callCallback(options.onClick, [e, active, this], this);\n }\n }\n\n const changed = !_elementsEqual(active, lastActive);\n if (changed || replay) {\n this._active = active;\n this._updateHoverStyles(active, lastActive, replay);\n }\n\n this._lastEvent = lastEvent;\n\n return changed;\n }\n\n /**\n * @param {ChartEvent} e - The event\n * @param {import('../types/index.js').ActiveElement[]} lastActive - Previously active elements\n * @param {boolean} inChartArea - Is the envent inside chartArea\n * @param {boolean} useFinalPosition - Should the evaluation be done with current or final (after animation) element positions\n * @returns {import('../types/index.js').ActiveElement[]} - The active elements\n * @pravate\n */\n _getActiveElements(e, lastActive, inChartArea, useFinalPosition) {\n if (e.type === 'mouseout') {\n return [];\n }\n\n if (!inChartArea) {\n // Let user control the active elements outside chartArea. Eg. using Legend.\n return lastActive;\n }\n\n const hoverOptions = this.options.hover;\n return this.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition);\n }\n}\n\n// @ts-ignore\nfunction invalidatePlugins() {\n return each(Chart.instances, (chart) => chart._plugins.invalidate());\n}\n\nexport default Chart;\n", "import Element from '../core/core.element.js';\nimport {_angleBetween, getAngleFromPoint, TAU, HALF_PI, valueOrDefault} from '../helpers/index.js';\nimport {PI, _isBetween, _limitValue} from '../helpers/helpers.math.js';\nimport {_readValueToProps} from '../helpers/helpers.options.js';\nimport type {ArcOptions, Point} from '../types/index.js';\n\n\nfunction clipArc(ctx: CanvasRenderingContext2D, element: ArcElement, endAngle: number) {\n const {startAngle, pixelMargin, x, y, outerRadius, innerRadius} = element;\n let angleMargin = pixelMargin / outerRadius;\n\n // Draw an inner border by clipping the arc and drawing a double-width border\n // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders\n ctx.beginPath();\n ctx.arc(x, y, outerRadius, startAngle - angleMargin, endAngle + angleMargin);\n if (innerRadius > pixelMargin) {\n angleMargin = pixelMargin / innerRadius;\n ctx.arc(x, y, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true);\n } else {\n ctx.arc(x, y, pixelMargin, endAngle + HALF_PI, startAngle - HALF_PI);\n }\n ctx.closePath();\n ctx.clip();\n}\n\nfunction toRadiusCorners(value) {\n return _readValueToProps(value, ['outerStart', 'outerEnd', 'innerStart', 'innerEnd']);\n}\n\n/**\n * Parse border radius from the provided options\n */\nfunction parseBorderRadius(arc: ArcElement, innerRadius: number, outerRadius: number, angleDelta: number) {\n const o = toRadiusCorners(arc.options.borderRadius);\n const halfThickness = (outerRadius - innerRadius) / 2;\n const innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2);\n\n // Outer limits are complicated. We want to compute the available angular distance at\n // a radius of outerRadius - borderRadius because for small angular distances, this term limits.\n // We compute at r = outerRadius - borderRadius because this circle defines the center of the border corners.\n //\n // If the borderRadius is large, that value can become negative.\n // This causes the outer borders to lose their radius entirely, which is rather unexpected. To solve that, if borderRadius > outerRadius\n // we know that the thickness term will dominate and compute the limits at that point\n const computeOuterLimit = (val) => {\n const outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2;\n return _limitValue(val, 0, Math.min(halfThickness, outerArcLimit));\n };\n\n return {\n outerStart: computeOuterLimit(o.outerStart),\n outerEnd: computeOuterLimit(o.outerEnd),\n innerStart: _limitValue(o.innerStart, 0, innerLimit),\n innerEnd: _limitValue(o.innerEnd, 0, innerLimit),\n };\n}\n\n/**\n * Convert (r, \uD835\uDF03) to (x, y)\n */\nfunction rThetaToXY(r: number, theta: number, x: number, y: number) {\n return {\n x: x + r * Math.cos(theta),\n y: y + r * Math.sin(theta),\n };\n}\n\n\n/**\n * Path the arc, respecting border radius by separating into left and right halves.\n *\n * Start End\n *\n * 1--->a--->2 Outer\n * / \\\n * 8 3\n * | |\n * | |\n * 7 4\n * \\ /\n * 6<---b<---5 Inner\n */\nfunction pathArc(\n ctx: CanvasRenderingContext2D,\n element: ArcElement,\n offset: number,\n spacing: number,\n end: number,\n circular: boolean,\n) {\n const {x, y, startAngle: start, pixelMargin, innerRadius: innerR} = element;\n\n const outerRadius = Math.max(element.outerRadius + spacing + offset - pixelMargin, 0);\n const innerRadius = innerR > 0 ? innerR + spacing + offset + pixelMargin : 0;\n\n let spacingOffset = 0;\n const alpha = end - start;\n\n if (spacing) {\n // When spacing is present, it is the same for all items\n // So we adjust the start and end angle of the arc such that\n // the distance is the same as it would be without the spacing\n const noSpacingInnerRadius = innerR > 0 ? innerR - spacing : 0;\n const noSpacingOuterRadius = outerRadius > 0 ? outerRadius - spacing : 0;\n const avNogSpacingRadius = (noSpacingInnerRadius + noSpacingOuterRadius) / 2;\n const adjustedAngle = avNogSpacingRadius !== 0 ? (alpha * avNogSpacingRadius) / (avNogSpacingRadius + spacing) : alpha;\n spacingOffset = (alpha - adjustedAngle) / 2;\n }\n\n const beta = Math.max(0.001, alpha * outerRadius - offset / PI) / outerRadius;\n const angleOffset = (alpha - beta) / 2;\n const startAngle = start + angleOffset + spacingOffset;\n const endAngle = end - angleOffset - spacingOffset;\n const {outerStart, outerEnd, innerStart, innerEnd} = parseBorderRadius(element, innerRadius, outerRadius, endAngle - startAngle);\n\n const outerStartAdjustedRadius = outerRadius - outerStart;\n const outerEndAdjustedRadius = outerRadius - outerEnd;\n const outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius;\n const outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius;\n\n const innerStartAdjustedRadius = innerRadius + innerStart;\n const innerEndAdjustedRadius = innerRadius + innerEnd;\n const innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius;\n const innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius;\n\n ctx.beginPath();\n\n if (circular) {\n // The first arc segments from point 1 to point a to point 2\n const outerMidAdjustedAngle = (outerStartAdjustedAngle + outerEndAdjustedAngle) / 2;\n ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerMidAdjustedAngle);\n ctx.arc(x, y, outerRadius, outerMidAdjustedAngle, outerEndAdjustedAngle);\n\n // The corner segment from point 2 to point 3\n if (outerEnd > 0) {\n const pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y);\n ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + HALF_PI);\n }\n\n // The line from point 3 to point 4\n const p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y);\n ctx.lineTo(p4.x, p4.y);\n\n // The corner segment from point 4 to point 5\n if (innerEnd > 0) {\n const pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y);\n ctx.arc(pCenter.x, pCenter.y, innerEnd, endAngle + HALF_PI, innerEndAdjustedAngle + Math.PI);\n }\n\n // The inner arc from point 5 to point b to point 6\n const innerMidAdjustedAngle = ((endAngle - (innerEnd / innerRadius)) + (startAngle + (innerStart / innerRadius))) / 2;\n ctx.arc(x, y, innerRadius, endAngle - (innerEnd / innerRadius), innerMidAdjustedAngle, true);\n ctx.arc(x, y, innerRadius, innerMidAdjustedAngle, startAngle + (innerStart / innerRadius), true);\n\n // The corner segment from point 6 to point 7\n if (innerStart > 0) {\n const pCenter = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y);\n ctx.arc(pCenter.x, pCenter.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - HALF_PI);\n }\n\n // The line from point 7 to point 8\n const p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y);\n ctx.lineTo(p8.x, p8.y);\n\n // The corner segment from point 8 to point 1\n if (outerStart > 0) {\n const pCenter = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y);\n ctx.arc(pCenter.x, pCenter.y, outerStart, startAngle - HALF_PI, outerStartAdjustedAngle);\n }\n } else {\n ctx.moveTo(x, y);\n\n const outerStartX = Math.cos(outerStartAdjustedAngle) * outerRadius + x;\n const outerStartY = Math.sin(outerStartAdjustedAngle) * outerRadius + y;\n ctx.lineTo(outerStartX, outerStartY);\n\n const outerEndX = Math.cos(outerEndAdjustedAngle) * outerRadius + x;\n const outerEndY = Math.sin(outerEndAdjustedAngle) * outerRadius + y;\n ctx.lineTo(outerEndX, outerEndY);\n }\n\n ctx.closePath();\n}\n\nfunction drawArc(\n ctx: CanvasRenderingContext2D,\n element: ArcElement,\n offset: number,\n spacing: number,\n circular: boolean,\n) {\n const {fullCircles, startAngle, circumference} = element;\n let endAngle = element.endAngle;\n if (fullCircles) {\n pathArc(ctx, element, offset, spacing, endAngle, circular);\n for (let i = 0; i < fullCircles; ++i) {\n ctx.fill();\n }\n if (!isNaN(circumference)) {\n endAngle = startAngle + (circumference % TAU || TAU);\n }\n }\n pathArc(ctx, element, offset, spacing, endAngle, circular);\n ctx.fill();\n return endAngle;\n}\n\nfunction drawBorder(\n ctx: CanvasRenderingContext2D,\n element: ArcElement,\n offset: number,\n spacing: number,\n circular: boolean,\n) {\n const {fullCircles, startAngle, circumference, options} = element;\n const {borderWidth, borderJoinStyle, borderDash, borderDashOffset} = options;\n const inner = options.borderAlign === 'inner';\n\n if (!borderWidth) {\n return;\n }\n\n ctx.setLineDash(borderDash || []);\n ctx.lineDashOffset = borderDashOffset;\n\n if (inner) {\n ctx.lineWidth = borderWidth * 2;\n ctx.lineJoin = borderJoinStyle || 'round';\n } else {\n ctx.lineWidth = borderWidth;\n ctx.lineJoin = borderJoinStyle || 'bevel';\n }\n\n let endAngle = element.endAngle;\n if (fullCircles) {\n pathArc(ctx, element, offset, spacing, endAngle, circular);\n for (let i = 0; i < fullCircles; ++i) {\n ctx.stroke();\n }\n if (!isNaN(circumference)) {\n endAngle = startAngle + (circumference % TAU || TAU);\n }\n }\n\n if (inner) {\n clipArc(ctx, element, endAngle);\n }\n\n if (!fullCircles) {\n pathArc(ctx, element, offset, spacing, endAngle, circular);\n ctx.stroke();\n }\n}\n\nexport interface ArcProps extends Point {\n startAngle: number;\n endAngle: number;\n innerRadius: number;\n outerRadius: number;\n circumference: number;\n}\n\nexport default class ArcElement extends Element {\n\n static id = 'arc';\n\n static defaults = {\n borderAlign: 'center',\n borderColor: '#fff',\n borderDash: [],\n borderDashOffset: 0,\n borderJoinStyle: undefined,\n borderRadius: 0,\n borderWidth: 2,\n offset: 0,\n spacing: 0,\n angle: undefined,\n circular: true,\n };\n\n static defaultRoutes = {\n backgroundColor: 'backgroundColor'\n };\n\n static descriptors = {\n _scriptable: true,\n _indexable: (name) => name !== 'borderDash'\n };\n\n circumference: number;\n endAngle: number;\n fullCircles: number;\n innerRadius: number;\n outerRadius: number;\n pixelMargin: number;\n startAngle: number;\n\n constructor(cfg) {\n super();\n\n this.options = undefined;\n this.circumference = undefined;\n this.startAngle = undefined;\n this.endAngle = undefined;\n this.innerRadius = undefined;\n this.outerRadius = undefined;\n this.pixelMargin = 0;\n this.fullCircles = 0;\n\n if (cfg) {\n Object.assign(this, cfg);\n }\n }\n\n inRange(chartX: number, chartY: number, useFinalPosition: boolean) {\n const point = this.getProps(['x', 'y'], useFinalPosition);\n const {angle, distance} = getAngleFromPoint(point, {x: chartX, y: chartY});\n const {startAngle, endAngle, innerRadius, outerRadius, circumference} = this.getProps([\n 'startAngle',\n 'endAngle',\n 'innerRadius',\n 'outerRadius',\n 'circumference'\n ], useFinalPosition);\n const rAdjust = (this.options.spacing + this.options.borderWidth) / 2;\n const _circumference = valueOrDefault(circumference, endAngle - startAngle);\n const betweenAngles = _circumference >= TAU || _angleBetween(angle, startAngle, endAngle);\n const withinRadius = _isBetween(distance, innerRadius + rAdjust, outerRadius + rAdjust);\n\n return (betweenAngles && withinRadius);\n }\n\n getCenterPoint(useFinalPosition: boolean) {\n const {x, y, startAngle, endAngle, innerRadius, outerRadius} = this.getProps([\n 'x',\n 'y',\n 'startAngle',\n 'endAngle',\n 'innerRadius',\n 'outerRadius'\n ], useFinalPosition);\n const {offset, spacing} = this.options;\n const halfAngle = (startAngle + endAngle) / 2;\n const halfRadius = (innerRadius + outerRadius + spacing + offset) / 2;\n return {\n x: x + Math.cos(halfAngle) * halfRadius,\n y: y + Math.sin(halfAngle) * halfRadius\n };\n }\n\n tooltipPosition(useFinalPosition: boolean) {\n return this.getCenterPoint(useFinalPosition);\n }\n\n draw(ctx: CanvasRenderingContext2D) {\n const {options, circumference} = this;\n const offset = (options.offset || 0) / 4;\n const spacing = (options.spacing || 0) / 2;\n const circular = options.circular;\n this.pixelMargin = (options.borderAlign === 'inner') ? 0.33 : 0;\n this.fullCircles = circumference > TAU ? Math.floor(circumference / TAU) : 0;\n\n if (circumference === 0 || this.innerRadius < 0 || this.outerRadius < 0) {\n return;\n }\n\n ctx.save();\n\n const halfAngle = (this.startAngle + this.endAngle) / 2;\n ctx.translate(Math.cos(halfAngle) * offset, Math.sin(halfAngle) * offset);\n const fix = 1 - Math.sin(Math.min(PI, circumference || 0));\n const radiusOffset = offset * fix;\n\n ctx.fillStyle = options.backgroundColor;\n ctx.strokeStyle = options.borderColor;\n\n drawArc(ctx, this, radiusOffset, spacing, circular);\n drawBorder(ctx, this, radiusOffset, spacing, circular);\n\n ctx.restore();\n }\n}\n", "import Element from '../core/core.element.js';\nimport {_bezierInterpolation, _pointInLine, _steppedInterpolation} from '../helpers/helpers.interpolation.js';\nimport {_computeSegments, _boundSegments} from '../helpers/helpers.segment.js';\nimport {_steppedLineTo, _bezierCurveTo} from '../helpers/helpers.canvas.js';\nimport {_updateBezierControlPoints} from '../helpers/helpers.curve.js';\nimport {valueOrDefault} from '../helpers/index.js';\n\n/**\n * @typedef { import('./element.point.js').default } PointElement\n */\n\nfunction setStyle(ctx, options, style = options) {\n ctx.lineCap = valueOrDefault(style.borderCapStyle, options.borderCapStyle);\n ctx.setLineDash(valueOrDefault(style.borderDash, options.borderDash));\n ctx.lineDashOffset = valueOrDefault(style.borderDashOffset, options.borderDashOffset);\n ctx.lineJoin = valueOrDefault(style.borderJoinStyle, options.borderJoinStyle);\n ctx.lineWidth = valueOrDefault(style.borderWidth, options.borderWidth);\n ctx.strokeStyle = valueOrDefault(style.borderColor, options.borderColor);\n}\n\nfunction lineTo(ctx, previous, target) {\n ctx.lineTo(target.x, target.y);\n}\n\n/**\n * @returns {any}\n */\nfunction getLineMethod(options) {\n if (options.stepped) {\n return _steppedLineTo;\n }\n\n if (options.tension || options.cubicInterpolationMode === 'monotone') {\n return _bezierCurveTo;\n }\n\n return lineTo;\n}\n\nfunction pathVars(points, segment, params = {}) {\n const count = points.length;\n const {start: paramsStart = 0, end: paramsEnd = count - 1} = params;\n const {start: segmentStart, end: segmentEnd} = segment;\n const start = Math.max(paramsStart, segmentStart);\n const end = Math.min(paramsEnd, segmentEnd);\n const outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd;\n\n return {\n count,\n start,\n loop: segment.loop,\n ilen: end < start && !outside ? count + end - start : end - start\n };\n}\n\n/**\n * Create path from points, grouping by truncated x-coordinate\n * Points need to be in order by x-coordinate for this to work efficiently\n * @param {CanvasRenderingContext2D|Path2D} ctx - Context\n * @param {LineElement} line\n * @param {object} segment\n * @param {number} segment.start - start index of the segment, referring the points array\n * @param {number} segment.end - end index of the segment, referring the points array\n * @param {boolean} segment.loop - indicates that the segment is a loop\n * @param {object} params\n * @param {boolean} params.move - move to starting point (vs line to it)\n * @param {boolean} params.reverse - path the segment from end to start\n * @param {number} params.start - limit segment to points starting from `start` index\n * @param {number} params.end - limit segment to points ending at `start` + `count` index\n */\nfunction pathSegment(ctx, line, segment, params) {\n const {points, options} = line;\n const {count, start, loop, ilen} = pathVars(points, segment, params);\n const lineMethod = getLineMethod(options);\n // eslint-disable-next-line prefer-const\n let {move = true, reverse} = params || {};\n let i, point, prev;\n\n for (i = 0; i <= ilen; ++i) {\n point = points[(start + (reverse ? ilen - i : i)) % count];\n\n if (point.skip) {\n // If there is a skipped point inside a segment, spanGaps must be true\n continue;\n } else if (move) {\n ctx.moveTo(point.x, point.y);\n move = false;\n } else {\n lineMethod(ctx, prev, point, reverse, options.stepped);\n }\n\n prev = point;\n }\n\n if (loop) {\n point = points[(start + (reverse ? ilen : 0)) % count];\n lineMethod(ctx, prev, point, reverse, options.stepped);\n }\n\n return !!loop;\n}\n\n/**\n * Create path from points, grouping by truncated x-coordinate\n * Points need to be in order by x-coordinate for this to work efficiently\n * @param {CanvasRenderingContext2D|Path2D} ctx - Context\n * @param {LineElement} line\n * @param {object} segment\n * @param {number} segment.start - start index of the segment, referring the points array\n * @param {number} segment.end - end index of the segment, referring the points array\n * @param {boolean} segment.loop - indicates that the segment is a loop\n * @param {object} params\n * @param {boolean} params.move - move to starting point (vs line to it)\n * @param {boolean} params.reverse - path the segment from end to start\n * @param {number} params.start - limit segment to points starting from `start` index\n * @param {number} params.end - limit segment to points ending at `start` + `count` index\n */\nfunction fastPathSegment(ctx, line, segment, params) {\n const points = line.points;\n const {count, start, ilen} = pathVars(points, segment, params);\n const {move = true, reverse} = params || {};\n let avgX = 0;\n let countX = 0;\n let i, point, prevX, minY, maxY, lastY;\n\n const pointIndex = (index) => (start + (reverse ? ilen - index : index)) % count;\n const drawX = () => {\n if (minY !== maxY) {\n // Draw line to maxY and minY, using the average x-coordinate\n ctx.lineTo(avgX, maxY);\n ctx.lineTo(avgX, minY);\n // Line to y-value of last point in group. So the line continues\n // from correct position. Not using move, to have solid path.\n ctx.lineTo(avgX, lastY);\n }\n };\n\n if (move) {\n point = points[pointIndex(0)];\n ctx.moveTo(point.x, point.y);\n }\n\n for (i = 0; i <= ilen; ++i) {\n point = points[pointIndex(i)];\n\n if (point.skip) {\n // If there is a skipped point inside a segment, spanGaps must be true\n continue;\n }\n\n const x = point.x;\n const y = point.y;\n const truncX = x | 0; // truncated x-coordinate\n\n if (truncX === prevX) {\n // Determine `minY` / `maxY` and `avgX` while we stay within same x-position\n if (y < minY) {\n minY = y;\n } else if (y > maxY) {\n maxY = y;\n }\n // For first point in group, countX is `0`, so average will be `x` / 1.\n avgX = (countX * avgX + x) / ++countX;\n } else {\n drawX();\n // Draw line to next x-position, using the first (or only)\n // y-value in that group\n ctx.lineTo(x, y);\n\n prevX = truncX;\n countX = 0;\n minY = maxY = y;\n }\n // Keep track of the last y-value in group\n lastY = y;\n }\n drawX();\n}\n\n/**\n * @param {LineElement} line - the line\n * @returns {function}\n * @private\n */\nfunction _getSegmentMethod(line) {\n const opts = line.options;\n const borderDash = opts.borderDash && opts.borderDash.length;\n const useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== 'monotone' && !opts.stepped && !borderDash;\n return useFastPath ? fastPathSegment : pathSegment;\n}\n\n/**\n * @private\n */\nfunction _getInterpolationMethod(options) {\n if (options.stepped) {\n return _steppedInterpolation;\n }\n\n if (options.tension || options.cubicInterpolationMode === 'monotone') {\n return _bezierInterpolation;\n }\n\n return _pointInLine;\n}\n\nfunction strokePathWithCache(ctx, line, start, count) {\n let path = line._path;\n if (!path) {\n path = line._path = new Path2D();\n if (line.path(path, start, count)) {\n path.closePath();\n }\n }\n setStyle(ctx, line.options);\n ctx.stroke(path);\n}\n\nfunction strokePathDirect(ctx, line, start, count) {\n const {segments, options} = line;\n const segmentMethod = _getSegmentMethod(line);\n\n for (const segment of segments) {\n setStyle(ctx, options, segment.style);\n ctx.beginPath();\n if (segmentMethod(ctx, line, segment, {start, end: start + count - 1})) {\n ctx.closePath();\n }\n ctx.stroke();\n }\n}\n\nconst usePath2D = typeof Path2D === 'function';\n\nfunction draw(ctx, line, start, count) {\n if (usePath2D && !line.options.segment) {\n strokePathWithCache(ctx, line, start, count);\n } else {\n strokePathDirect(ctx, line, start, count);\n }\n}\n\nexport default class LineElement extends Element {\n\n static id = 'line';\n\n /**\n * @type {any}\n */\n static defaults = {\n borderCapStyle: 'butt',\n borderDash: [],\n borderDashOffset: 0,\n borderJoinStyle: 'miter',\n borderWidth: 3,\n capBezierPoints: true,\n cubicInterpolationMode: 'default',\n fill: false,\n spanGaps: false,\n stepped: false,\n tension: 0,\n };\n\n /**\n * @type {any}\n */\n static defaultRoutes = {\n backgroundColor: 'backgroundColor',\n borderColor: 'borderColor'\n };\n\n\n static descriptors = {\n _scriptable: true,\n _indexable: (name) => name !== 'borderDash' && name !== 'fill',\n };\n\n\n constructor(cfg) {\n super();\n\n this.animated = true;\n this.options = undefined;\n this._chart = undefined;\n this._loop = undefined;\n this._fullLoop = undefined;\n this._path = undefined;\n this._points = undefined;\n this._segments = undefined;\n this._decimated = false;\n this._pointsUpdated = false;\n this._datasetIndex = undefined;\n\n if (cfg) {\n Object.assign(this, cfg);\n }\n }\n\n updateControlPoints(chartArea, indexAxis) {\n const options = this.options;\n if ((options.tension || options.cubicInterpolationMode === 'monotone') && !options.stepped && !this._pointsUpdated) {\n const loop = options.spanGaps ? this._loop : this._fullLoop;\n _updateBezierControlPoints(this._points, options, chartArea, loop, indexAxis);\n this._pointsUpdated = true;\n }\n }\n\n set points(points) {\n this._points = points;\n delete this._segments;\n delete this._path;\n this._pointsUpdated = false;\n }\n\n get points() {\n return this._points;\n }\n\n get segments() {\n return this._segments || (this._segments = _computeSegments(this, this.options.segment));\n }\n\n /**\n\t * First non-skipped point on this line\n\t * @returns {PointElement|undefined}\n\t */\n first() {\n const segments = this.segments;\n const points = this.points;\n return segments.length && points[segments[0].start];\n }\n\n /**\n\t * Last non-skipped point on this line\n\t * @returns {PointElement|undefined}\n\t */\n last() {\n const segments = this.segments;\n const points = this.points;\n const count = segments.length;\n return count && points[segments[count - 1].end];\n }\n\n /**\n\t * Interpolate a point in this line at the same value on `property` as\n\t * the reference `point` provided\n\t * @param {PointElement} point - the reference point\n\t * @param {string} property - the property to match on\n\t * @returns {PointElement|undefined}\n\t */\n interpolate(point, property) {\n const options = this.options;\n const value = point[property];\n const points = this.points;\n const segments = _boundSegments(this, {property, start: value, end: value});\n\n if (!segments.length) {\n return;\n }\n\n const result = [];\n const _interpolate = _getInterpolationMethod(options);\n let i, ilen;\n for (i = 0, ilen = segments.length; i < ilen; ++i) {\n const {start, end} = segments[i];\n const p1 = points[start];\n const p2 = points[end];\n if (p1 === p2) {\n result.push(p1);\n continue;\n }\n const t = Math.abs((value - p1[property]) / (p2[property] - p1[property]));\n const interpolated = _interpolate(p1, p2, t, options.stepped);\n interpolated[property] = point[property];\n result.push(interpolated);\n }\n return result.length === 1 ? result[0] : result;\n }\n\n /**\n\t * Append a segment of this line to current path.\n\t * @param {CanvasRenderingContext2D} ctx\n\t * @param {object} segment\n\t * @param {number} segment.start - start index of the segment, referring the points array\n \t * @param {number} segment.end - end index of the segment, referring the points array\n \t * @param {boolean} segment.loop - indicates that the segment is a loop\n\t * @param {object} params\n\t * @param {boolean} params.move - move to starting point (vs line to it)\n\t * @param {boolean} params.reverse - path the segment from end to start\n\t * @param {number} params.start - limit segment to points starting from `start` index\n\t * @param {number} params.end - limit segment to points ending at `start` + `count` index\n\t * @returns {undefined|boolean} - true if the segment is a full loop (path should be closed)\n\t */\n pathSegment(ctx, segment, params) {\n const segmentMethod = _getSegmentMethod(this);\n return segmentMethod(ctx, this, segment, params);\n }\n\n /**\n\t * Append all segments of this line to current path.\n\t * @param {CanvasRenderingContext2D|Path2D} ctx\n\t * @param {number} [start]\n\t * @param {number} [count]\n\t * @returns {undefined|boolean} - true if line is a full loop (path should be closed)\n\t */\n path(ctx, start, count) {\n const segments = this.segments;\n const segmentMethod = _getSegmentMethod(this);\n let loop = this._loop;\n\n start = start || 0;\n count = count || (this.points.length - start);\n\n for (const segment of segments) {\n loop &= segmentMethod(ctx, this, segment, {start, end: start + count - 1});\n }\n return !!loop;\n }\n\n /**\n\t * Draw\n\t * @param {CanvasRenderingContext2D} ctx\n\t * @param {object} chartArea\n\t * @param {number} [start]\n\t * @param {number} [count]\n\t */\n draw(ctx, chartArea, start, count) {\n const options = this.options || {};\n const points = this.points || [];\n\n if (points.length && options.borderWidth) {\n ctx.save();\n\n draw(ctx, this, start, count);\n\n ctx.restore();\n }\n\n if (this.animated) {\n // When line is animated, the control points and path are not cached.\n this._pointsUpdated = false;\n this._path = undefined;\n }\n }\n}\n", "import Element from '../core/core.element.js';\nimport {drawPoint, _isPointInArea} from '../helpers/helpers.canvas.js';\nimport type {\n CartesianParsedData,\n ChartArea,\n Point,\n PointHoverOptions,\n PointOptions,\n} from '../types/index.js';\n\nfunction inRange(el: PointElement, pos: number, axis: 'x' | 'y', useFinalPosition?: boolean) {\n const options = el.options;\n const {[axis]: value} = el.getProps([axis], useFinalPosition);\n\n return (Math.abs(pos - value) < options.radius + options.hitRadius);\n}\n\nexport type PointProps = Point\n\nexport default class PointElement extends Element {\n\n static id = 'point';\n\n parsed: CartesianParsedData;\n skip?: boolean;\n stop?: boolean;\n\n /**\n * @type {any}\n */\n static defaults = {\n borderWidth: 1,\n hitRadius: 1,\n hoverBorderWidth: 1,\n hoverRadius: 4,\n pointStyle: 'circle',\n radius: 3,\n rotation: 0\n };\n\n /**\n * @type {any}\n */\n static defaultRoutes = {\n backgroundColor: 'backgroundColor',\n borderColor: 'borderColor'\n };\n\n constructor(cfg) {\n super();\n\n this.options = undefined;\n this.parsed = undefined;\n this.skip = undefined;\n this.stop = undefined;\n\n if (cfg) {\n Object.assign(this, cfg);\n }\n }\n\n inRange(mouseX: number, mouseY: number, useFinalPosition?: boolean) {\n const options = this.options;\n const {x, y} = this.getProps(['x', 'y'], useFinalPosition);\n return ((Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2)) < Math.pow(options.hitRadius + options.radius, 2));\n }\n\n inXRange(mouseX: number, useFinalPosition?: boolean) {\n return inRange(this, mouseX, 'x', useFinalPosition);\n }\n\n inYRange(mouseY: number, useFinalPosition?: boolean) {\n return inRange(this, mouseY, 'y', useFinalPosition);\n }\n\n getCenterPoint(useFinalPosition?: boolean) {\n const {x, y} = this.getProps(['x', 'y'], useFinalPosition);\n return {x, y};\n }\n\n size(options?: Partial) {\n options = options || this.options || {};\n let radius = options.radius || 0;\n radius = Math.max(radius, radius && options.hoverRadius || 0);\n const borderWidth = radius && options.borderWidth || 0;\n return (radius + borderWidth) * 2;\n }\n\n draw(ctx: CanvasRenderingContext2D, area: ChartArea) {\n const options = this.options;\n\n if (this.skip || options.radius < 0.1 || !_isPointInArea(this, area, this.size(options) / 2)) {\n return;\n }\n\n ctx.strokeStyle = options.borderColor;\n ctx.lineWidth = options.borderWidth;\n ctx.fillStyle = options.backgroundColor;\n drawPoint(ctx, options, this.x, this.y);\n }\n\n getRange() {\n const options = this.options || {};\n // @ts-expect-error Fallbacks should never be hit in practice\n return options.radius + options.hitRadius;\n }\n}\n", "import Element from '../core/core.element.js';\nimport {isObject, _isBetween, _limitValue} from '../helpers/index.js';\nimport {addRoundedRectPath} from '../helpers/helpers.canvas.js';\nimport {toTRBL, toTRBLCorners} from '../helpers/helpers.options.js';\n\n/** @typedef {{ x: number, y: number, base: number, horizontal: boolean, width: number, height: number }} BarProps */\n\n/**\n * Helper function to get the bounds of the bar regardless of the orientation\n * @param {BarElement} bar the bar\n * @param {boolean} [useFinalPosition]\n * @return {object} bounds of the bar\n * @private\n */\nfunction getBarBounds(bar, useFinalPosition) {\n const {x, y, base, width, height} = /** @type {BarProps} */ (bar.getProps(['x', 'y', 'base', 'width', 'height'], useFinalPosition));\n\n let left, right, top, bottom, half;\n\n if (bar.horizontal) {\n half = height / 2;\n left = Math.min(x, base);\n right = Math.max(x, base);\n top = y - half;\n bottom = y + half;\n } else {\n half = width / 2;\n left = x - half;\n right = x + half;\n top = Math.min(y, base);\n bottom = Math.max(y, base);\n }\n\n return {left, top, right, bottom};\n}\n\nfunction skipOrLimit(skip, value, min, max) {\n return skip ? 0 : _limitValue(value, min, max);\n}\n\nfunction parseBorderWidth(bar, maxW, maxH) {\n const value = bar.options.borderWidth;\n const skip = bar.borderSkipped;\n const o = toTRBL(value);\n\n return {\n t: skipOrLimit(skip.top, o.top, 0, maxH),\n r: skipOrLimit(skip.right, o.right, 0, maxW),\n b: skipOrLimit(skip.bottom, o.bottom, 0, maxH),\n l: skipOrLimit(skip.left, o.left, 0, maxW)\n };\n}\n\nfunction parseBorderRadius(bar, maxW, maxH) {\n const {enableBorderRadius} = bar.getProps(['enableBorderRadius']);\n const value = bar.options.borderRadius;\n const o = toTRBLCorners(value);\n const maxR = Math.min(maxW, maxH);\n const skip = bar.borderSkipped;\n\n // If the value is an object, assume the user knows what they are doing\n // and apply as directed.\n const enableBorder = enableBorderRadius || isObject(value);\n\n return {\n topLeft: skipOrLimit(!enableBorder || skip.top || skip.left, o.topLeft, 0, maxR),\n topRight: skipOrLimit(!enableBorder || skip.top || skip.right, o.topRight, 0, maxR),\n bottomLeft: skipOrLimit(!enableBorder || skip.bottom || skip.left, o.bottomLeft, 0, maxR),\n bottomRight: skipOrLimit(!enableBorder || skip.bottom || skip.right, o.bottomRight, 0, maxR)\n };\n}\n\nfunction boundingRects(bar) {\n const bounds = getBarBounds(bar);\n const width = bounds.right - bounds.left;\n const height = bounds.bottom - bounds.top;\n const border = parseBorderWidth(bar, width / 2, height / 2);\n const radius = parseBorderRadius(bar, width / 2, height / 2);\n\n return {\n outer: {\n x: bounds.left,\n y: bounds.top,\n w: width,\n h: height,\n radius\n },\n inner: {\n x: bounds.left + border.l,\n y: bounds.top + border.t,\n w: width - border.l - border.r,\n h: height - border.t - border.b,\n radius: {\n topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)),\n topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)),\n bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)),\n bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r)),\n }\n }\n };\n}\n\nfunction inRange(bar, x, y, useFinalPosition) {\n const skipX = x === null;\n const skipY = y === null;\n const skipBoth = skipX && skipY;\n const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition);\n\n return bounds\n\t\t&& (skipX || _isBetween(x, bounds.left, bounds.right))\n\t\t&& (skipY || _isBetween(y, bounds.top, bounds.bottom));\n}\n\nfunction hasRadius(radius) {\n return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight;\n}\n\n/**\n * Add a path of a rectangle to the current sub-path\n * @param {CanvasRenderingContext2D} ctx Context\n * @param {*} rect Bounding rect\n */\nfunction addNormalRectPath(ctx, rect) {\n ctx.rect(rect.x, rect.y, rect.w, rect.h);\n}\n\nfunction inflateRect(rect, amount, refRect = {}) {\n const x = rect.x !== refRect.x ? -amount : 0;\n const y = rect.y !== refRect.y ? -amount : 0;\n const w = (rect.x + rect.w !== refRect.x + refRect.w ? amount : 0) - x;\n const h = (rect.y + rect.h !== refRect.y + refRect.h ? amount : 0) - y;\n return {\n x: rect.x + x,\n y: rect.y + y,\n w: rect.w + w,\n h: rect.h + h,\n radius: rect.radius\n };\n}\n\nexport default class BarElement extends Element {\n\n static id = 'bar';\n\n /**\n * @type {any}\n */\n static defaults = {\n borderSkipped: 'start',\n borderWidth: 0,\n borderRadius: 0,\n inflateAmount: 'auto',\n pointStyle: undefined\n };\n\n /**\n * @type {any}\n */\n static defaultRoutes = {\n backgroundColor: 'backgroundColor',\n borderColor: 'borderColor'\n };\n\n constructor(cfg) {\n super();\n\n this.options = undefined;\n this.horizontal = undefined;\n this.base = undefined;\n this.width = undefined;\n this.height = undefined;\n this.inflateAmount = undefined;\n\n if (cfg) {\n Object.assign(this, cfg);\n }\n }\n\n draw(ctx) {\n const {inflateAmount, options: {borderColor, backgroundColor}} = this;\n const {inner, outer} = boundingRects(this);\n const addRectPath = hasRadius(outer.radius) ? addRoundedRectPath : addNormalRectPath;\n\n ctx.save();\n\n if (outer.w !== inner.w || outer.h !== inner.h) {\n ctx.beginPath();\n addRectPath(ctx, inflateRect(outer, inflateAmount, inner));\n ctx.clip();\n addRectPath(ctx, inflateRect(inner, -inflateAmount, outer));\n ctx.fillStyle = borderColor;\n ctx.fill('evenodd');\n }\n\n ctx.beginPath();\n addRectPath(ctx, inflateRect(inner, inflateAmount));\n ctx.fillStyle = backgroundColor;\n ctx.fill();\n\n ctx.restore();\n }\n\n inRange(mouseX, mouseY, useFinalPosition) {\n return inRange(this, mouseX, mouseY, useFinalPosition);\n }\n\n inXRange(mouseX, useFinalPosition) {\n return inRange(this, mouseX, null, useFinalPosition);\n }\n\n inYRange(mouseY, useFinalPosition) {\n return inRange(this, null, mouseY, useFinalPosition);\n }\n\n getCenterPoint(useFinalPosition) {\n const {x, y, base, horizontal} = /** @type {BarProps} */ (this.getProps(['x', 'y', 'base', 'horizontal'], useFinalPosition));\n return {\n x: horizontal ? (x + base) / 2 : x,\n y: horizontal ? y : (y + base) / 2\n };\n }\n\n getRange(axis) {\n return axis === 'x' ? this.width / 2 : this.height / 2;\n }\n}\n", "import {DoughnutController, PolarAreaController} from '../index.js';\nimport type {Chart, ChartDataset} from '../types.js';\n\nexport interface ColorsPluginOptions {\n enabled?: boolean;\n forceOverride?: boolean;\n}\n\ninterface ColorsDescriptor {\n backgroundColor?: unknown;\n borderColor?: unknown;\n}\n\nconst BORDER_COLORS = [\n 'rgb(54, 162, 235)', // blue\n 'rgb(255, 99, 132)', // red\n 'rgb(255, 159, 64)', // orange\n 'rgb(255, 205, 86)', // yellow\n 'rgb(75, 192, 192)', // green\n 'rgb(153, 102, 255)', // purple\n 'rgb(201, 203, 207)' // grey\n];\n\n// Border colors with 50% transparency\nconst BACKGROUND_COLORS = /* #__PURE__ */ BORDER_COLORS.map(color => color.replace('rgb(', 'rgba(').replace(')', ', 0.5)'));\n\nfunction getBorderColor(i: number) {\n return BORDER_COLORS[i % BORDER_COLORS.length];\n}\n\nfunction getBackgroundColor(i: number) {\n return BACKGROUND_COLORS[i % BACKGROUND_COLORS.length];\n}\n\nfunction colorizeDefaultDataset(dataset: ChartDataset, i: number) {\n dataset.borderColor = getBorderColor(i);\n dataset.backgroundColor = getBackgroundColor(i);\n\n return ++i;\n}\n\nfunction colorizeDoughnutDataset(dataset: ChartDataset, i: number) {\n dataset.backgroundColor = dataset.data.map(() => getBorderColor(i++));\n\n return i;\n}\n\nfunction colorizePolarAreaDataset(dataset: ChartDataset, i: number) {\n dataset.backgroundColor = dataset.data.map(() => getBackgroundColor(i++));\n\n return i;\n}\n\nfunction getColorizer(chart: Chart) {\n let i = 0;\n\n return (dataset: ChartDataset, datasetIndex: number) => {\n const controller = chart.getDatasetMeta(datasetIndex).controller;\n\n if (controller instanceof DoughnutController) {\n i = colorizeDoughnutDataset(dataset, i);\n } else if (controller instanceof PolarAreaController) {\n i = colorizePolarAreaDataset(dataset, i);\n } else if (controller) {\n i = colorizeDefaultDataset(dataset, i);\n }\n };\n}\n\nfunction containsColorsDefinitions(\n descriptors: ColorsDescriptor[] | Record\n) {\n let k: number | string;\n\n for (k in descriptors) {\n if (descriptors[k].borderColor || descriptors[k].backgroundColor) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction containsColorsDefinition(\n descriptor: ColorsDescriptor\n) {\n return descriptor && (descriptor.borderColor || descriptor.backgroundColor);\n}\n\nexport default {\n id: 'colors',\n\n defaults: {\n enabled: true,\n forceOverride: false\n } as ColorsPluginOptions,\n\n beforeLayout(chart: Chart, _args, options: ColorsPluginOptions) {\n if (!options.enabled) {\n return;\n }\n\n const {\n data: {datasets},\n options: chartOptions\n } = chart.config;\n const {elements} = chartOptions;\n\n if (!options.forceOverride && (containsColorsDefinitions(datasets) || containsColorsDefinition(chartOptions) || (elements && containsColorsDefinitions(elements)))) {\n return;\n }\n\n const colorizer = getColorizer(chart);\n\n datasets.forEach(colorizer);\n }\n};\n", "import {_limitValue, _lookupByKey, isNullOrUndef, resolve} from '../helpers/index.js';\n\nfunction lttbDecimation(data, start, count, availableWidth, options) {\n /**\n * Implementation of the Largest Triangle Three Buckets algorithm.\n *\n * This implementation is based on the original implementation by Sveinn Steinarsson\n * in https://github.com/sveinn-steinarsson/flot-downsample/blob/master/jquery.flot.downsample.js\n *\n * The original implementation is MIT licensed.\n */\n const samples = options.samples || availableWidth;\n // There are less points than the threshold, returning the whole array\n if (samples >= count) {\n return data.slice(start, start + count);\n }\n\n const decimated = [];\n\n const bucketWidth = (count - 2) / (samples - 2);\n let sampledIndex = 0;\n const endIndex = start + count - 1;\n // Starting from offset\n let a = start;\n let i, maxAreaPoint, maxArea, area, nextA;\n\n decimated[sampledIndex++] = data[a];\n\n for (i = 0; i < samples - 2; i++) {\n let avgX = 0;\n let avgY = 0;\n let j;\n\n // Adding offset\n const avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start;\n const avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start;\n const avgRangeLength = avgRangeEnd - avgRangeStart;\n\n for (j = avgRangeStart; j < avgRangeEnd; j++) {\n avgX += data[j].x;\n avgY += data[j].y;\n }\n\n avgX /= avgRangeLength;\n avgY /= avgRangeLength;\n\n // Adding offset\n const rangeOffs = Math.floor(i * bucketWidth) + 1 + start;\n const rangeTo = Math.min(Math.floor((i + 1) * bucketWidth) + 1, count) + start;\n const {x: pointAx, y: pointAy} = data[a];\n\n // Note that this is changed from the original algorithm which initializes these\n // values to 1. The reason for this change is that if the area is small, nextA\n // would never be set and thus a crash would occur in the next loop as `a` would become\n // `undefined`. Since the area is always positive, but could be 0 in the case of a flat trace,\n // initializing with a negative number is the correct solution.\n maxArea = area = -1;\n\n for (j = rangeOffs; j < rangeTo; j++) {\n area = 0.5 * Math.abs(\n (pointAx - avgX) * (data[j].y - pointAy) -\n (pointAx - data[j].x) * (avgY - pointAy)\n );\n\n if (area > maxArea) {\n maxArea = area;\n maxAreaPoint = data[j];\n nextA = j;\n }\n }\n\n decimated[sampledIndex++] = maxAreaPoint;\n a = nextA;\n }\n\n // Include the last point\n decimated[sampledIndex++] = data[endIndex];\n\n return decimated;\n}\n\nfunction minMaxDecimation(data, start, count, availableWidth) {\n let avgX = 0;\n let countX = 0;\n let i, point, x, y, prevX, minIndex, maxIndex, startIndex, minY, maxY;\n const decimated = [];\n const endIndex = start + count - 1;\n\n const xMin = data[start].x;\n const xMax = data[endIndex].x;\n const dx = xMax - xMin;\n\n for (i = start; i < start + count; ++i) {\n point = data[i];\n x = (point.x - xMin) / dx * availableWidth;\n y = point.y;\n const truncX = x | 0;\n\n if (truncX === prevX) {\n // Determine `minY` / `maxY` and `avgX` while we stay within same x-position\n if (y < minY) {\n minY = y;\n minIndex = i;\n } else if (y > maxY) {\n maxY = y;\n maxIndex = i;\n }\n // For first point in group, countX is `0`, so average will be `x` / 1.\n // Use point.x here because we're computing the average data `x` value\n avgX = (countX * avgX + point.x) / ++countX;\n } else {\n // Push up to 4 points, 3 for the last interval and the first point for this interval\n const lastIndex = i - 1;\n\n if (!isNullOrUndef(minIndex) && !isNullOrUndef(maxIndex)) {\n // The interval is defined by 4 points: start, min, max, end.\n // The starting point is already considered at this point, so we need to determine which\n // of the other points to add. We need to sort these points to ensure the decimated data\n // is still sorted and then ensure there are no duplicates.\n const intermediateIndex1 = Math.min(minIndex, maxIndex);\n const intermediateIndex2 = Math.max(minIndex, maxIndex);\n\n if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) {\n decimated.push({\n ...data[intermediateIndex1],\n x: avgX,\n });\n }\n if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) {\n decimated.push({\n ...data[intermediateIndex2],\n x: avgX\n });\n }\n }\n\n // lastIndex === startIndex will occur when a range has only 1 point which could\n // happen with very uneven data\n if (i > 0 && lastIndex !== startIndex) {\n // Last point in the previous interval\n decimated.push(data[lastIndex]);\n }\n\n // Start of the new interval\n decimated.push(point);\n prevX = truncX;\n countX = 0;\n minY = maxY = y;\n minIndex = maxIndex = startIndex = i;\n }\n }\n\n return decimated;\n}\n\nfunction cleanDecimatedDataset(dataset) {\n if (dataset._decimated) {\n const data = dataset._data;\n delete dataset._decimated;\n delete dataset._data;\n Object.defineProperty(dataset, 'data', {\n configurable: true,\n enumerable: true,\n writable: true,\n value: data,\n });\n }\n}\n\nfunction cleanDecimatedData(chart) {\n chart.data.datasets.forEach((dataset) => {\n cleanDecimatedDataset(dataset);\n });\n}\n\nfunction getStartAndCountOfVisiblePointsSimplified(meta, points) {\n const pointCount = points.length;\n\n let start = 0;\n let count;\n\n const {iScale} = meta;\n const {min, max, minDefined, maxDefined} = iScale.getUserBounds();\n\n if (minDefined) {\n start = _limitValue(_lookupByKey(points, iScale.axis, min).lo, 0, pointCount - 1);\n }\n if (maxDefined) {\n count = _limitValue(_lookupByKey(points, iScale.axis, max).hi + 1, start, pointCount) - start;\n } else {\n count = pointCount - start;\n }\n\n return {start, count};\n}\n\nexport default {\n id: 'decimation',\n\n defaults: {\n algorithm: 'min-max',\n enabled: false,\n },\n\n beforeElementsUpdate: (chart, args, options) => {\n if (!options.enabled) {\n // The decimation plugin may have been previously enabled. Need to remove old `dataset._data` handlers\n cleanDecimatedData(chart);\n return;\n }\n\n // Assume the entire chart is available to show a few more points than needed\n const availableWidth = chart.width;\n\n chart.data.datasets.forEach((dataset, datasetIndex) => {\n const {_data, indexAxis} = dataset;\n const meta = chart.getDatasetMeta(datasetIndex);\n const data = _data || dataset.data;\n\n if (resolve([indexAxis, chart.options.indexAxis]) === 'y') {\n // Decimation is only supported for lines that have an X indexAxis\n return;\n }\n\n if (!meta.controller.supportsDecimation) {\n // Only line datasets are supported\n return;\n }\n\n const xAxis = chart.scales[meta.xAxisID];\n if (xAxis.type !== 'linear' && xAxis.type !== 'time') {\n // Only linear interpolation is supported\n return;\n }\n\n if (chart.options.parsing) {\n // Plugin only supports data that does not need parsing\n return;\n }\n\n let {start, count} = getStartAndCountOfVisiblePointsSimplified(meta, data);\n const threshold = options.threshold || 4 * availableWidth;\n if (count <= threshold) {\n // No decimation is required until we are above this threshold\n cleanDecimatedDataset(dataset);\n return;\n }\n\n if (isNullOrUndef(_data)) {\n // First time we are seeing this dataset\n // We override the 'data' property with a setter that stores the\n // raw data in _data, but reads the decimated data from _decimated\n dataset._data = data;\n delete dataset.data;\n Object.defineProperty(dataset, 'data', {\n configurable: true,\n enumerable: true,\n get: function() {\n return this._decimated;\n },\n set: function(d) {\n this._data = d;\n }\n });\n }\n\n // Point the chart to the decimated data\n let decimated;\n switch (options.algorithm) {\n case 'lttb':\n decimated = lttbDecimation(data, start, count, availableWidth, options);\n break;\n case 'min-max':\n decimated = minMaxDecimation(data, start, count, availableWidth);\n break;\n default:\n throw new Error(`Unsupported decimation algorithm '${options.algorithm}'`);\n }\n\n dataset._decimated = decimated;\n });\n },\n\n destroy(chart) {\n cleanDecimatedData(chart);\n }\n};\n", "import {_boundSegment, _boundSegments, _normalizeAngle} from '../../helpers/index.js';\n\nexport function _segments(line, target, property) {\n const segments = line.segments;\n const points = line.points;\n const tpoints = target.points;\n const parts = [];\n\n for (const segment of segments) {\n let {start, end} = segment;\n end = _findSegmentEnd(start, end, points);\n\n const bounds = _getBounds(property, points[start], points[end], segment.loop);\n\n if (!target.segments) {\n // Special case for boundary not supporting `segments` (simpleArc)\n // Bounds are provided as `target` for partial circle, or undefined for full circle\n parts.push({\n source: segment,\n target: bounds,\n start: points[start],\n end: points[end]\n });\n continue;\n }\n\n // Get all segments from `target` that intersect the bounds of current segment of `line`\n const targetSegments = _boundSegments(target, bounds);\n\n for (const tgt of targetSegments) {\n const subBounds = _getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop);\n const fillSources = _boundSegment(segment, points, subBounds);\n\n for (const fillSource of fillSources) {\n parts.push({\n source: fillSource,\n target: tgt,\n start: {\n [property]: _getEdge(bounds, subBounds, 'start', Math.max)\n },\n end: {\n [property]: _getEdge(bounds, subBounds, 'end', Math.min)\n }\n });\n }\n }\n }\n return parts;\n}\n\nexport function _getBounds(property, first, last, loop) {\n if (loop) {\n return;\n }\n let start = first[property];\n let end = last[property];\n\n if (property === 'angle') {\n start = _normalizeAngle(start);\n end = _normalizeAngle(end);\n }\n return {property, start, end};\n}\n\nexport function _pointsFromSegments(boundary, line) {\n const {x = null, y = null} = boundary || {};\n const linePoints = line.points;\n const points = [];\n line.segments.forEach(({start, end}) => {\n end = _findSegmentEnd(start, end, linePoints);\n const first = linePoints[start];\n const last = linePoints[end];\n if (y !== null) {\n points.push({x: first.x, y});\n points.push({x: last.x, y});\n } else if (x !== null) {\n points.push({x, y: first.y});\n points.push({x, y: last.y});\n }\n });\n return points;\n}\n\nexport function _findSegmentEnd(start, end, points) {\n for (;end > start; end--) {\n const point = points[end];\n if (!isNaN(point.x) && !isNaN(point.y)) {\n break;\n }\n }\n return end;\n}\n\nfunction _getEdge(a, b, prop, fn) {\n if (a && b) {\n return fn(a[prop], b[prop]);\n }\n return a ? a[prop] : b ? b[prop] : 0;\n}\n", "/**\n * @typedef { import('../../core/core.controller.js').default } Chart\n * @typedef { import('../../core/core.scale.js').default } Scale\n * @typedef { import('../../elements/element.point.js').default } PointElement\n */\n\nimport {LineElement} from '../../elements/index.js';\nimport {isArray} from '../../helpers/index.js';\nimport {_pointsFromSegments} from './filler.segment.js';\n\n/**\n * @param {PointElement[] | { x: number; y: number; }} boundary\n * @param {LineElement} line\n * @return {LineElement?}\n */\nexport function _createBoundaryLine(boundary, line) {\n let points = [];\n let _loop = false;\n\n if (isArray(boundary)) {\n _loop = true;\n // @ts-ignore\n points = boundary;\n } else {\n points = _pointsFromSegments(boundary, line);\n }\n\n return points.length ? new LineElement({\n points,\n options: {tension: 0},\n _loop,\n _fullLoop: _loop\n }) : null;\n}\n\nexport function _shouldApplyFill(source) {\n return source && source.fill !== false;\n}\n", "import {isObject, isFinite, valueOrDefault} from '../../helpers/helpers.core.js';\n\n/**\n * @typedef { import('../../core/core.scale.js').default } Scale\n * @typedef { import('../../elements/element.line.js').default } LineElement\n * @typedef { import('../../types/index.js').FillTarget } FillTarget\n * @typedef { import('../../types/index.js').ComplexFillTarget } ComplexFillTarget\n */\n\nexport function _resolveTarget(sources, index, propagate) {\n const source = sources[index];\n let fill = source.fill;\n const visited = [index];\n let target;\n\n if (!propagate) {\n return fill;\n }\n\n while (fill !== false && visited.indexOf(fill) === -1) {\n if (!isFinite(fill)) {\n return fill;\n }\n\n target = sources[fill];\n if (!target) {\n return false;\n }\n\n if (target.visible) {\n return fill;\n }\n\n visited.push(fill);\n fill = target.fill;\n }\n\n return false;\n}\n\n/**\n * @param {LineElement} line\n * @param {number} index\n * @param {number} count\n */\nexport function _decodeFill(line, index, count) {\n /** @type {string | {value: number}} */\n const fill = parseFillOption(line);\n\n if (isObject(fill)) {\n return isNaN(fill.value) ? false : fill;\n }\n\n let target = parseFloat(fill);\n\n if (isFinite(target) && Math.floor(target) === target) {\n return decodeTargetIndex(fill[0], index, target, count);\n }\n\n return ['origin', 'start', 'end', 'stack', 'shape'].indexOf(fill) >= 0 && fill;\n}\n\nfunction decodeTargetIndex(firstCh, index, target, count) {\n if (firstCh === '-' || firstCh === '+') {\n target = index + target;\n }\n\n if (target === index || target < 0 || target >= count) {\n return false;\n }\n\n return target;\n}\n\n/**\n * @param {FillTarget | ComplexFillTarget} fill\n * @param {Scale} scale\n * @returns {number | null}\n */\nexport function _getTargetPixel(fill, scale) {\n let pixel = null;\n if (fill === 'start') {\n pixel = scale.bottom;\n } else if (fill === 'end') {\n pixel = scale.top;\n } else if (isObject(fill)) {\n // @ts-ignore\n pixel = scale.getPixelForValue(fill.value);\n } else if (scale.getBasePixel) {\n pixel = scale.getBasePixel();\n }\n return pixel;\n}\n\n/**\n * @param {FillTarget | ComplexFillTarget} fill\n * @param {Scale} scale\n * @param {number} startValue\n * @returns {number | undefined}\n */\nexport function _getTargetValue(fill, scale, startValue) {\n let value;\n\n if (fill === 'start') {\n value = startValue;\n } else if (fill === 'end') {\n value = scale.options.reverse ? scale.min : scale.max;\n } else if (isObject(fill)) {\n // @ts-ignore\n value = fill.value;\n } else {\n value = scale.getBaseValue();\n }\n return value;\n}\n\n/**\n * @param {LineElement} line\n */\nfunction parseFillOption(line) {\n const options = line.options;\n const fillOption = options.fill;\n let fill = valueOrDefault(fillOption && fillOption.target, fillOption);\n\n if (fill === undefined) {\n fill = !!options.backgroundColor;\n }\n\n if (fill === false || fill === null) {\n return false;\n }\n\n if (fill === true) {\n return 'origin';\n }\n return fill;\n}\n", "/**\n * @typedef { import('../../core/core.controller.js').default } Chart\n * @typedef { import('../../core/core.scale.js').default } Scale\n * @typedef { import('../../elements/element.point.js').default } PointElement\n */\n\nimport {LineElement} from '../../elements/index.js';\nimport {_isBetween} from '../../helpers/index.js';\nimport {_createBoundaryLine} from './filler.helper.js';\n\n/**\n * @param {{ chart: Chart; scale: Scale; index: number; line: LineElement; }} source\n * @return {LineElement}\n */\nexport function _buildStackLine(source) {\n const {scale, index, line} = source;\n const points = [];\n const segments = line.segments;\n const sourcePoints = line.points;\n const linesBelow = getLinesBelow(scale, index);\n linesBelow.push(_createBoundaryLine({x: null, y: scale.bottom}, line));\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n for (let j = segment.start; j <= segment.end; j++) {\n addPointsBelow(points, sourcePoints[j], linesBelow);\n }\n }\n return new LineElement({points, options: {}});\n}\n\n/**\n * @param {Scale} scale\n * @param {number} index\n * @return {LineElement[]}\n */\nfunction getLinesBelow(scale, index) {\n const below = [];\n const metas = scale.getMatchingVisibleMetas('line');\n\n for (let i = 0; i < metas.length; i++) {\n const meta = metas[i];\n if (meta.index === index) {\n break;\n }\n if (!meta.hidden) {\n below.unshift(meta.dataset);\n }\n }\n return below;\n}\n\n/**\n * @param {PointElement[]} points\n * @param {PointElement} sourcePoint\n * @param {LineElement[]} linesBelow\n */\nfunction addPointsBelow(points, sourcePoint, linesBelow) {\n const postponed = [];\n for (let j = 0; j < linesBelow.length; j++) {\n const line = linesBelow[j];\n const {first, last, point} = findPoint(line, sourcePoint, 'x');\n\n if (!point || (first && last)) {\n continue;\n }\n if (first) {\n // First point of an segment -> need to add another point before this,\n // from next line below.\n postponed.unshift(point);\n } else {\n points.push(point);\n if (!last) {\n // In the middle of an segment, no need to add more points.\n break;\n }\n }\n }\n points.push(...postponed);\n}\n\n/**\n * @param {LineElement} line\n * @param {PointElement} sourcePoint\n * @param {string} property\n * @returns {{point?: PointElement, first?: boolean, last?: boolean}}\n */\nfunction findPoint(line, sourcePoint, property) {\n const point = line.interpolate(sourcePoint, property);\n if (!point) {\n return {};\n }\n\n const pointValue = point[property];\n const segments = line.segments;\n const linePoints = line.points;\n let first = false;\n let last = false;\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n const firstValue = linePoints[segment.start][property];\n const lastValue = linePoints[segment.end][property];\n if (_isBetween(pointValue, firstValue, lastValue)) {\n first = pointValue === firstValue;\n last = pointValue === lastValue;\n break;\n }\n }\n return {first, last, point};\n}\n", "import {TAU} from '../../helpers/index.js';\n\n// TODO: use elements.ArcElement instead\nexport class simpleArc {\n constructor(opts) {\n this.x = opts.x;\n this.y = opts.y;\n this.radius = opts.radius;\n }\n\n pathSegment(ctx, bounds, opts) {\n const {x, y, radius} = this;\n bounds = bounds || {start: 0, end: TAU};\n ctx.arc(x, y, radius, bounds.end, bounds.start, true);\n return !opts.bounds;\n }\n\n interpolate(point) {\n const {x, y, radius} = this;\n const angle = point.angle;\n return {\n x: x + Math.cos(angle) * radius,\n y: y + Math.sin(angle) * radius,\n angle\n };\n }\n}\n", "import {isFinite} from '../../helpers/index.js';\nimport {_createBoundaryLine} from './filler.helper.js';\nimport {_getTargetPixel, _getTargetValue} from './filler.options.js';\nimport {_buildStackLine} from './filler.target.stack.js';\nimport {simpleArc} from './simpleArc.js';\n\n/**\n * @typedef { import('../../core/core.controller.js').default } Chart\n * @typedef { import('../../core/core.scale.js').default } Scale\n * @typedef { import('../../elements/element.point.js').default } PointElement\n */\n\nexport function _getTarget(source) {\n const {chart, fill, line} = source;\n\n if (isFinite(fill)) {\n return getLineByIndex(chart, fill);\n }\n\n if (fill === 'stack') {\n return _buildStackLine(source);\n }\n\n if (fill === 'shape') {\n return true;\n }\n\n const boundary = computeBoundary(source);\n\n if (boundary instanceof simpleArc) {\n return boundary;\n }\n\n return _createBoundaryLine(boundary, line);\n}\n\n/**\n * @param {Chart} chart\n * @param {number} index\n */\nfunction getLineByIndex(chart, index) {\n const meta = chart.getDatasetMeta(index);\n const visible = meta && chart.isDatasetVisible(index);\n return visible ? meta.dataset : null;\n}\n\nfunction computeBoundary(source) {\n const scale = source.scale || {};\n\n if (scale.getPointPositionForValue) {\n return computeCircularBoundary(source);\n }\n return computeLinearBoundary(source);\n}\n\n\nfunction computeLinearBoundary(source) {\n const {scale = {}, fill} = source;\n const pixel = _getTargetPixel(fill, scale);\n\n if (isFinite(pixel)) {\n const horizontal = scale.isHorizontal();\n\n return {\n x: horizontal ? pixel : null,\n y: horizontal ? null : pixel\n };\n }\n\n return null;\n}\n\nfunction computeCircularBoundary(source) {\n const {scale, fill} = source;\n const options = scale.options;\n const length = scale.getLabels().length;\n const start = options.reverse ? scale.max : scale.min;\n const value = _getTargetValue(fill, scale, start);\n const target = [];\n\n if (options.grid.circular) {\n const center = scale.getPointPositionForValue(0, start);\n return new simpleArc({\n x: center.x,\n y: center.y,\n radius: scale.getDistanceFromCenterForValue(value)\n });\n }\n\n for (let i = 0; i < length; ++i) {\n target.push(scale.getPointPositionForValue(i, value));\n }\n return target;\n}\n\n", "import {clipArea, unclipArea} from '../../helpers/index.js';\nimport {_findSegmentEnd, _getBounds, _segments} from './filler.segment.js';\nimport {_getTarget} from './filler.target.js';\n\nexport function _drawfill(ctx, source, area) {\n const target = _getTarget(source);\n const {line, scale, axis} = source;\n const lineOpts = line.options;\n const fillOption = lineOpts.fill;\n const color = lineOpts.backgroundColor;\n const {above = color, below = color} = fillOption || {};\n if (target && line.points.length) {\n clipArea(ctx, area);\n doFill(ctx, {line, target, above, below, area, scale, axis});\n unclipArea(ctx);\n }\n}\n\nfunction doFill(ctx, cfg) {\n const {line, target, above, below, area, scale} = cfg;\n const property = line._loop ? 'angle' : cfg.axis;\n\n ctx.save();\n\n if (property === 'x' && below !== above) {\n clipVertical(ctx, target, area.top);\n fill(ctx, {line, target, color: above, scale, property});\n ctx.restore();\n ctx.save();\n clipVertical(ctx, target, area.bottom);\n }\n fill(ctx, {line, target, color: below, scale, property});\n\n ctx.restore();\n}\n\nfunction clipVertical(ctx, target, clipY) {\n const {segments, points} = target;\n let first = true;\n let lineLoop = false;\n\n ctx.beginPath();\n for (const segment of segments) {\n const {start, end} = segment;\n const firstPoint = points[start];\n const lastPoint = points[_findSegmentEnd(start, end, points)];\n if (first) {\n ctx.moveTo(firstPoint.x, firstPoint.y);\n first = false;\n } else {\n ctx.lineTo(firstPoint.x, clipY);\n ctx.lineTo(firstPoint.x, firstPoint.y);\n }\n lineLoop = !!target.pathSegment(ctx, segment, {move: lineLoop});\n if (lineLoop) {\n ctx.closePath();\n } else {\n ctx.lineTo(lastPoint.x, clipY);\n }\n }\n\n ctx.lineTo(target.first().x, clipY);\n ctx.closePath();\n ctx.clip();\n}\n\nfunction fill(ctx, cfg) {\n const {line, target, property, color, scale} = cfg;\n const segments = _segments(line, target, property);\n\n for (const {source: src, target: tgt, start, end} of segments) {\n const {style: {backgroundColor = color} = {}} = src;\n const notShape = target !== true;\n\n ctx.save();\n ctx.fillStyle = backgroundColor;\n\n clipBounds(ctx, scale, notShape && _getBounds(property, start, end));\n\n ctx.beginPath();\n\n const lineLoop = !!line.pathSegment(ctx, src);\n\n let loop;\n if (notShape) {\n if (lineLoop) {\n ctx.closePath();\n } else {\n interpolatedLineTo(ctx, target, end, property);\n }\n\n const targetLoop = !!target.pathSegment(ctx, tgt, {move: lineLoop, reverse: true});\n loop = lineLoop && targetLoop;\n if (!loop) {\n interpolatedLineTo(ctx, target, start, property);\n }\n }\n\n ctx.closePath();\n ctx.fill(loop ? 'evenodd' : 'nonzero');\n\n ctx.restore();\n }\n}\n\nfunction clipBounds(ctx, scale, bounds) {\n const {top, bottom} = scale.chart.chartArea;\n const {property, start, end} = bounds || {};\n if (property === 'x') {\n ctx.beginPath();\n ctx.rect(start, top, end - start, bottom - top);\n ctx.clip();\n }\n}\n\nfunction interpolatedLineTo(ctx, target, point, property) {\n const interpolatedPoint = target.interpolate(point, property);\n if (interpolatedPoint) {\n ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y);\n }\n}\n\n", "/**\n * Plugin based on discussion from the following Chart.js issues:\n * @see https://github.com/chartjs/Chart.js/issues/2380#issuecomment-279961569\n * @see https://github.com/chartjs/Chart.js/issues/2440#issuecomment-256461897\n */\n\nimport LineElement from '../../elements/element.line.js';\nimport {_drawfill} from './filler.drawing.js';\nimport {_shouldApplyFill} from './filler.helper.js';\nimport {_decodeFill, _resolveTarget} from './filler.options.js';\n\nexport default {\n id: 'filler',\n\n afterDatasetsUpdate(chart, _args, options) {\n const count = (chart.data.datasets || []).length;\n const sources = [];\n let meta, i, line, source;\n\n for (i = 0; i < count; ++i) {\n meta = chart.getDatasetMeta(i);\n line = meta.dataset;\n source = null;\n\n if (line && line.options && line instanceof LineElement) {\n source = {\n visible: chart.isDatasetVisible(i),\n index: i,\n fill: _decodeFill(line, i, count),\n chart,\n axis: meta.controller.options.indexAxis,\n scale: meta.vScale,\n line,\n };\n }\n\n meta.$filler = source;\n sources.push(source);\n }\n\n for (i = 0; i < count; ++i) {\n source = sources[i];\n if (!source || source.fill === false) {\n continue;\n }\n\n source.fill = _resolveTarget(sources, i, options.propagate);\n }\n },\n\n beforeDraw(chart, _args, options) {\n const draw = options.drawTime === 'beforeDraw';\n const metasets = chart.getSortedVisibleDatasetMetas();\n const area = chart.chartArea;\n for (let i = metasets.length - 1; i >= 0; --i) {\n const source = metasets[i].$filler;\n if (!source) {\n continue;\n }\n\n source.line.updateControlPoints(area, source.axis);\n if (draw && source.fill) {\n _drawfill(chart.ctx, source, area);\n }\n }\n },\n\n beforeDatasetsDraw(chart, _args, options) {\n if (options.drawTime !== 'beforeDatasetsDraw') {\n return;\n }\n\n const metasets = chart.getSortedVisibleDatasetMetas();\n for (let i = metasets.length - 1; i >= 0; --i) {\n const source = metasets[i].$filler;\n\n if (_shouldApplyFill(source)) {\n _drawfill(chart.ctx, source, chart.chartArea);\n }\n }\n },\n\n beforeDatasetDraw(chart, args, options) {\n const source = args.meta.$filler;\n\n if (!_shouldApplyFill(source) || options.drawTime !== 'beforeDatasetDraw') {\n return;\n }\n\n _drawfill(chart.ctx, source, chart.chartArea);\n },\n\n defaults: {\n propagate: true,\n drawTime: 'beforeDatasetDraw'\n }\n};\n", "import defaults from '../core/core.defaults.js';\nimport Element from '../core/core.element.js';\nimport layouts from '../core/core.layouts.js';\nimport {addRoundedRectPath, drawPointLegend, renderText} from '../helpers/helpers.canvas.js';\nimport {\n _isBetween,\n callback as call,\n clipArea,\n getRtlAdapter,\n overrideTextDirection,\n restoreTextDirection,\n toFont,\n toPadding,\n unclipArea,\n valueOrDefault,\n} from '../helpers/index.js';\nimport {_alignStartEnd, _textX, _toLeftRightCenter} from '../helpers/helpers.extras.js';\nimport {toTRBLCorners} from '../helpers/helpers.options.js';\n\n/**\n * @typedef { import('../types/index.js').ChartEvent } ChartEvent\n */\n\nconst getBoxSize = (labelOpts, fontSize) => {\n let {boxHeight = fontSize, boxWidth = fontSize} = labelOpts;\n\n if (labelOpts.usePointStyle) {\n boxHeight = Math.min(boxHeight, fontSize);\n boxWidth = labelOpts.pointStyleWidth || Math.min(boxWidth, fontSize);\n }\n\n return {\n boxWidth,\n boxHeight,\n itemHeight: Math.max(fontSize, boxHeight)\n };\n};\n\nconst itemsEqual = (a, b) => a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index;\n\nexport class Legend extends Element {\n\n /**\n\t * @param {{ ctx: any; options: any; chart: any; }} config\n\t */\n constructor(config) {\n super();\n\n this._added = false;\n\n // Contains hit boxes for each dataset (in dataset order)\n this.legendHitBoxes = [];\n\n /**\n \t\t * @private\n \t\t */\n this._hoveredItem = null;\n\n // Are we in doughnut mode which has a different data type\n this.doughnutMode = false;\n\n this.chart = config.chart;\n this.options = config.options;\n this.ctx = config.ctx;\n this.legendItems = undefined;\n this.columnSizes = undefined;\n this.lineWidths = undefined;\n this.maxHeight = undefined;\n this.maxWidth = undefined;\n this.top = undefined;\n this.bottom = undefined;\n this.left = undefined;\n this.right = undefined;\n this.height = undefined;\n this.width = undefined;\n this._margins = undefined;\n this.position = undefined;\n this.weight = undefined;\n this.fullSize = undefined;\n }\n\n update(maxWidth, maxHeight, margins) {\n this.maxWidth = maxWidth;\n this.maxHeight = maxHeight;\n this._margins = margins;\n\n this.setDimensions();\n this.buildLabels();\n this.fit();\n }\n\n setDimensions() {\n if (this.isHorizontal()) {\n this.width = this.maxWidth;\n this.left = this._margins.left;\n this.right = this.width;\n } else {\n this.height = this.maxHeight;\n this.top = this._margins.top;\n this.bottom = this.height;\n }\n }\n\n buildLabels() {\n const labelOpts = this.options.labels || {};\n let legendItems = call(labelOpts.generateLabels, [this.chart], this) || [];\n\n if (labelOpts.filter) {\n legendItems = legendItems.filter((item) => labelOpts.filter(item, this.chart.data));\n }\n\n if (labelOpts.sort) {\n legendItems = legendItems.sort((a, b) => labelOpts.sort(a, b, this.chart.data));\n }\n\n if (this.options.reverse) {\n legendItems.reverse();\n }\n\n this.legendItems = legendItems;\n }\n\n fit() {\n const {options, ctx} = this;\n\n // The legend may not be displayed for a variety of reasons including\n // the fact that the defaults got set to `false`.\n // When the legend is not displayed, there are no guarantees that the options\n // are correctly formatted so we need to bail out as early as possible.\n if (!options.display) {\n this.width = this.height = 0;\n return;\n }\n\n const labelOpts = options.labels;\n const labelFont = toFont(labelOpts.font);\n const fontSize = labelFont.size;\n const titleHeight = this._computeTitleHeight();\n const {boxWidth, itemHeight} = getBoxSize(labelOpts, fontSize);\n\n let width, height;\n\n ctx.font = labelFont.string;\n\n if (this.isHorizontal()) {\n width = this.maxWidth; // fill all the width\n height = this._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10;\n } else {\n height = this.maxHeight; // fill all the height\n width = this._fitCols(titleHeight, labelFont, boxWidth, itemHeight) + 10;\n }\n\n this.width = Math.min(width, options.maxWidth || this.maxWidth);\n this.height = Math.min(height, options.maxHeight || this.maxHeight);\n }\n\n /**\n\t * @private\n\t */\n _fitRows(titleHeight, fontSize, boxWidth, itemHeight) {\n const {ctx, maxWidth, options: {labels: {padding}}} = this;\n const hitboxes = this.legendHitBoxes = [];\n // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one\n const lineWidths = this.lineWidths = [0];\n const lineHeight = itemHeight + padding;\n let totalHeight = titleHeight;\n\n ctx.textAlign = 'left';\n ctx.textBaseline = 'middle';\n\n let row = -1;\n let top = -lineHeight;\n this.legendItems.forEach((legendItem, i) => {\n const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;\n\n if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) {\n totalHeight += lineHeight;\n lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;\n top += lineHeight;\n row++;\n }\n\n hitboxes[i] = {left: 0, top, row, width: itemWidth, height: itemHeight};\n\n lineWidths[lineWidths.length - 1] += itemWidth + padding;\n });\n\n return totalHeight;\n }\n\n _fitCols(titleHeight, labelFont, boxWidth, _itemHeight) {\n const {ctx, maxHeight, options: {labels: {padding}}} = this;\n const hitboxes = this.legendHitBoxes = [];\n const columnSizes = this.columnSizes = [];\n const heightLimit = maxHeight - titleHeight;\n\n let totalWidth = padding;\n let currentColWidth = 0;\n let currentColHeight = 0;\n\n let left = 0;\n let col = 0;\n\n this.legendItems.forEach((legendItem, i) => {\n const {itemWidth, itemHeight} = calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight);\n\n // If too tall, go to new column\n if (i > 0 && currentColHeight + itemHeight + 2 * padding > heightLimit) {\n totalWidth += currentColWidth + padding;\n columnSizes.push({width: currentColWidth, height: currentColHeight}); // previous column size\n left += currentColWidth + padding;\n col++;\n currentColWidth = currentColHeight = 0;\n }\n\n // Store the hitbox width and height here. Final position will be updated in `draw`\n hitboxes[i] = {left, top: currentColHeight, col, width: itemWidth, height: itemHeight};\n\n // Get max width\n currentColWidth = Math.max(currentColWidth, itemWidth);\n currentColHeight += itemHeight + padding;\n });\n\n totalWidth += currentColWidth;\n columnSizes.push({width: currentColWidth, height: currentColHeight}); // previous column size\n\n return totalWidth;\n }\n\n adjustHitBoxes() {\n if (!this.options.display) {\n return;\n }\n const titleHeight = this._computeTitleHeight();\n const {legendHitBoxes: hitboxes, options: {align, labels: {padding}, rtl}} = this;\n const rtlHelper = getRtlAdapter(rtl, this.left, this.width);\n if (this.isHorizontal()) {\n let row = 0;\n let left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]);\n for (const hitbox of hitboxes) {\n if (row !== hitbox.row) {\n row = hitbox.row;\n left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]);\n }\n hitbox.top += this.top + titleHeight + padding;\n hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(left), hitbox.width);\n left += hitbox.width + padding;\n }\n } else {\n let col = 0;\n let top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height);\n for (const hitbox of hitboxes) {\n if (hitbox.col !== col) {\n col = hitbox.col;\n top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height);\n }\n hitbox.top = top;\n hitbox.left += this.left + padding;\n hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(hitbox.left), hitbox.width);\n top += hitbox.height + padding;\n }\n }\n }\n\n isHorizontal() {\n return this.options.position === 'top' || this.options.position === 'bottom';\n }\n\n draw() {\n if (this.options.display) {\n const ctx = this.ctx;\n clipArea(ctx, this);\n\n this._draw();\n\n unclipArea(ctx);\n }\n }\n\n /**\n\t * @private\n\t */\n _draw() {\n const {options: opts, columnSizes, lineWidths, ctx} = this;\n const {align, labels: labelOpts} = opts;\n const defaultColor = defaults.color;\n const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width);\n const labelFont = toFont(labelOpts.font);\n const {padding} = labelOpts;\n const fontSize = labelFont.size;\n const halfFontSize = fontSize / 2;\n let cursor;\n\n this.drawTitle();\n\n // Canvas setup\n ctx.textAlign = rtlHelper.textAlign('left');\n ctx.textBaseline = 'middle';\n ctx.lineWidth = 0.5;\n ctx.font = labelFont.string;\n\n const {boxWidth, boxHeight, itemHeight} = getBoxSize(labelOpts, fontSize);\n\n // current position\n const drawLegendBox = function(x, y, legendItem) {\n if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) {\n return;\n }\n\n // Set the ctx for the box\n ctx.save();\n\n const lineWidth = valueOrDefault(legendItem.lineWidth, 1);\n ctx.fillStyle = valueOrDefault(legendItem.fillStyle, defaultColor);\n ctx.lineCap = valueOrDefault(legendItem.lineCap, 'butt');\n ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, 0);\n ctx.lineJoin = valueOrDefault(legendItem.lineJoin, 'miter');\n ctx.lineWidth = lineWidth;\n ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, defaultColor);\n\n ctx.setLineDash(valueOrDefault(legendItem.lineDash, []));\n\n if (labelOpts.usePointStyle) {\n // Recalculate x and y for drawPoint() because its expecting\n // x and y to be center of figure (instead of top left)\n const drawOptions = {\n radius: boxHeight * Math.SQRT2 / 2,\n pointStyle: legendItem.pointStyle,\n rotation: legendItem.rotation,\n borderWidth: lineWidth\n };\n const centerX = rtlHelper.xPlus(x, boxWidth / 2);\n const centerY = y + halfFontSize;\n\n // Draw pointStyle as legend symbol\n drawPointLegend(ctx, drawOptions, centerX, centerY, labelOpts.pointStyleWidth && boxWidth);\n } else {\n // Draw box as legend symbol\n // Adjust position when boxHeight < fontSize (want it centered)\n const yBoxTop = y + Math.max((fontSize - boxHeight) / 2, 0);\n const xBoxLeft = rtlHelper.leftForLtr(x, boxWidth);\n const borderRadius = toTRBLCorners(legendItem.borderRadius);\n\n ctx.beginPath();\n\n if (Object.values(borderRadius).some(v => v !== 0)) {\n addRoundedRectPath(ctx, {\n x: xBoxLeft,\n y: yBoxTop,\n w: boxWidth,\n h: boxHeight,\n radius: borderRadius,\n });\n } else {\n ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight);\n }\n\n ctx.fill();\n if (lineWidth !== 0) {\n ctx.stroke();\n }\n }\n\n ctx.restore();\n };\n\n const fillText = function(x, y, legendItem) {\n renderText(ctx, legendItem.text, x, y + (itemHeight / 2), labelFont, {\n strikethrough: legendItem.hidden,\n textAlign: rtlHelper.textAlign(legendItem.textAlign)\n });\n };\n\n // Horizontal\n const isHorizontal = this.isHorizontal();\n const titleHeight = this._computeTitleHeight();\n if (isHorizontal) {\n cursor = {\n x: _alignStartEnd(align, this.left + padding, this.right - lineWidths[0]),\n y: this.top + padding + titleHeight,\n line: 0\n };\n } else {\n cursor = {\n x: this.left + padding,\n y: _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[0].height),\n line: 0\n };\n }\n\n overrideTextDirection(this.ctx, opts.textDirection);\n\n const lineHeight = itemHeight + padding;\n this.legendItems.forEach((legendItem, i) => {\n ctx.strokeStyle = legendItem.fontColor; // for strikethrough effect\n ctx.fillStyle = legendItem.fontColor; // render in correct colour\n\n const textWidth = ctx.measureText(legendItem.text).width;\n const textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign));\n const width = boxWidth + halfFontSize + textWidth;\n let x = cursor.x;\n let y = cursor.y;\n\n rtlHelper.setWidth(this.width);\n\n if (isHorizontal) {\n if (i > 0 && x + width + padding > this.right) {\n y = cursor.y += lineHeight;\n cursor.line++;\n x = cursor.x = _alignStartEnd(align, this.left + padding, this.right - lineWidths[cursor.line]);\n }\n } else if (i > 0 && y + lineHeight > this.bottom) {\n x = cursor.x = x + columnSizes[cursor.line].width + padding;\n cursor.line++;\n y = cursor.y = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[cursor.line].height);\n }\n\n const realX = rtlHelper.x(x);\n\n drawLegendBox(realX, y, legendItem);\n\n x = _textX(textAlign, x + boxWidth + halfFontSize, isHorizontal ? x + width : this.right, opts.rtl);\n\n // Fill the actual label\n fillText(rtlHelper.x(x), y, legendItem);\n\n if (isHorizontal) {\n cursor.x += width + padding;\n } else if (typeof legendItem.text !== 'string') {\n const fontLineHeight = labelFont.lineHeight;\n cursor.y += calculateLegendItemHeight(legendItem, fontLineHeight) + padding;\n } else {\n cursor.y += lineHeight;\n }\n });\n\n restoreTextDirection(this.ctx, opts.textDirection);\n }\n\n /**\n\t * @protected\n\t */\n drawTitle() {\n const opts = this.options;\n const titleOpts = opts.title;\n const titleFont = toFont(titleOpts.font);\n const titlePadding = toPadding(titleOpts.padding);\n\n if (!titleOpts.display) {\n return;\n }\n\n const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width);\n const ctx = this.ctx;\n const position = titleOpts.position;\n const halfFontSize = titleFont.size / 2;\n const topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize;\n let y;\n\n // These defaults are used when the legend is vertical.\n // When horizontal, they are computed below.\n let left = this.left;\n let maxWidth = this.width;\n\n if (this.isHorizontal()) {\n // Move left / right so that the title is above the legend lines\n maxWidth = Math.max(...this.lineWidths);\n y = this.top + topPaddingPlusHalfFontSize;\n left = _alignStartEnd(opts.align, left, this.right - maxWidth);\n } else {\n // Move down so that the title is above the legend stack in every alignment\n const maxHeight = this.columnSizes.reduce((acc, size) => Math.max(acc, size.height), 0);\n y = topPaddingPlusHalfFontSize + _alignStartEnd(opts.align, this.top, this.bottom - maxHeight - opts.labels.padding - this._computeTitleHeight());\n }\n\n // Now that we know the left edge of the inner legend box, compute the correct\n // X coordinate from the title alignment\n const x = _alignStartEnd(position, left, left + maxWidth);\n\n // Canvas setup\n ctx.textAlign = rtlHelper.textAlign(_toLeftRightCenter(position));\n ctx.textBaseline = 'middle';\n ctx.strokeStyle = titleOpts.color;\n ctx.fillStyle = titleOpts.color;\n ctx.font = titleFont.string;\n\n renderText(ctx, titleOpts.text, x, y, titleFont);\n }\n\n /**\n\t * @private\n\t */\n _computeTitleHeight() {\n const titleOpts = this.options.title;\n const titleFont = toFont(titleOpts.font);\n const titlePadding = toPadding(titleOpts.padding);\n return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0;\n }\n\n /**\n\t * @private\n\t */\n _getLegendItemAt(x, y) {\n let i, hitBox, lh;\n\n if (_isBetween(x, this.left, this.right)\n && _isBetween(y, this.top, this.bottom)) {\n // See if we are touching one of the dataset boxes\n lh = this.legendHitBoxes;\n for (i = 0; i < lh.length; ++i) {\n hitBox = lh[i];\n\n if (_isBetween(x, hitBox.left, hitBox.left + hitBox.width)\n && _isBetween(y, hitBox.top, hitBox.top + hitBox.height)) {\n // Touching an element\n return this.legendItems[i];\n }\n }\n }\n\n return null;\n }\n\n /**\n\t * Handle an event\n\t * @param {ChartEvent} e - The event to handle\n\t */\n handleEvent(e) {\n const opts = this.options;\n if (!isListened(e.type, opts)) {\n return;\n }\n\n // Chart event already has relative position in it\n const hoveredItem = this._getLegendItemAt(e.x, e.y);\n\n if (e.type === 'mousemove' || e.type === 'mouseout') {\n const previous = this._hoveredItem;\n const sameItem = itemsEqual(previous, hoveredItem);\n if (previous && !sameItem) {\n call(opts.onLeave, [e, previous, this], this);\n }\n\n this._hoveredItem = hoveredItem;\n\n if (hoveredItem && !sameItem) {\n call(opts.onHover, [e, hoveredItem, this], this);\n }\n } else if (hoveredItem) {\n call(opts.onClick, [e, hoveredItem, this], this);\n }\n }\n}\n\nfunction calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight) {\n const itemWidth = calculateItemWidth(legendItem, boxWidth, labelFont, ctx);\n const itemHeight = calculateItemHeight(_itemHeight, legendItem, labelFont.lineHeight);\n return {itemWidth, itemHeight};\n}\n\nfunction calculateItemWidth(legendItem, boxWidth, labelFont, ctx) {\n let legendItemText = legendItem.text;\n if (legendItemText && typeof legendItemText !== 'string') {\n legendItemText = legendItemText.reduce((a, b) => a.length > b.length ? a : b);\n }\n return boxWidth + (labelFont.size / 2) + ctx.measureText(legendItemText).width;\n}\n\nfunction calculateItemHeight(_itemHeight, legendItem, fontLineHeight) {\n let itemHeight = _itemHeight;\n if (typeof legendItem.text !== 'string') {\n itemHeight = calculateLegendItemHeight(legendItem, fontLineHeight);\n }\n return itemHeight;\n}\n\nfunction calculateLegendItemHeight(legendItem, fontLineHeight) {\n const labelHeight = legendItem.text ? legendItem.text.length : 0;\n return fontLineHeight * labelHeight;\n}\n\nfunction isListened(type, opts) {\n if ((type === 'mousemove' || type === 'mouseout') && (opts.onHover || opts.onLeave)) {\n return true;\n }\n if (opts.onClick && (type === 'click' || type === 'mouseup')) {\n return true;\n }\n return false;\n}\n\nexport default {\n id: 'legend',\n\n /**\n\t * For tests\n\t * @private\n\t */\n _element: Legend,\n\n start(chart, _args, options) {\n const legend = chart.legend = new Legend({ctx: chart.ctx, options, chart});\n layouts.configure(chart, legend, options);\n layouts.addBox(chart, legend);\n },\n\n stop(chart) {\n layouts.removeBox(chart, chart.legend);\n delete chart.legend;\n },\n\n // During the beforeUpdate step, the layout configuration needs to run\n // This ensures that if the legend position changes (via an option update)\n // the layout system respects the change. See https://github.com/chartjs/Chart.js/issues/7527\n beforeUpdate(chart, _args, options) {\n const legend = chart.legend;\n layouts.configure(chart, legend, options);\n legend.options = options;\n },\n\n // The labels need to be built after datasets are updated to ensure that colors\n // and other styling are correct. See https://github.com/chartjs/Chart.js/issues/6968\n afterUpdate(chart) {\n const legend = chart.legend;\n legend.buildLabels();\n legend.adjustHitBoxes();\n },\n\n\n afterEvent(chart, args) {\n if (!args.replay) {\n chart.legend.handleEvent(args.event);\n }\n },\n\n defaults: {\n display: true,\n position: 'top',\n align: 'center',\n fullSize: true,\n reverse: false,\n weight: 1000,\n\n // a callback that will handle\n onClick(e, legendItem, legend) {\n const index = legendItem.datasetIndex;\n const ci = legend.chart;\n if (ci.isDatasetVisible(index)) {\n ci.hide(index);\n legendItem.hidden = true;\n } else {\n ci.show(index);\n legendItem.hidden = false;\n }\n },\n\n onHover: null,\n onLeave: null,\n\n labels: {\n color: (ctx) => ctx.chart.options.color,\n boxWidth: 40,\n padding: 10,\n // Generates labels shown in the legend\n // Valid properties to return:\n // text : text to display\n // fillStyle : fill of coloured box\n // strokeStyle: stroke of coloured box\n // hidden : if this legend item refers to a hidden item\n // lineCap : cap style for line\n // lineDash\n // lineDashOffset :\n // lineJoin :\n // lineWidth :\n generateLabels(chart) {\n const datasets = chart.data.datasets;\n const {labels: {usePointStyle, pointStyle, textAlign, color, useBorderRadius, borderRadius}} = chart.legend.options;\n\n return chart._getSortedDatasetMetas().map((meta) => {\n const style = meta.controller.getStyle(usePointStyle ? 0 : undefined);\n const borderWidth = toPadding(style.borderWidth);\n\n return {\n text: datasets[meta.index].label,\n fillStyle: style.backgroundColor,\n fontColor: color,\n hidden: !meta.visible,\n lineCap: style.borderCapStyle,\n lineDash: style.borderDash,\n lineDashOffset: style.borderDashOffset,\n lineJoin: style.borderJoinStyle,\n lineWidth: (borderWidth.width + borderWidth.height) / 4,\n strokeStyle: style.borderColor,\n pointStyle: pointStyle || style.pointStyle,\n rotation: style.rotation,\n textAlign: textAlign || style.textAlign,\n borderRadius: useBorderRadius && (borderRadius || style.borderRadius),\n\n // Below is extra data used for toggling the datasets\n datasetIndex: meta.index\n };\n }, this);\n }\n },\n\n title: {\n color: (ctx) => ctx.chart.options.color,\n display: false,\n position: 'center',\n text: '',\n }\n },\n\n descriptors: {\n _scriptable: (name) => !name.startsWith('on'),\n labels: {\n _scriptable: (name) => !['generateLabels', 'filter', 'sort'].includes(name),\n }\n },\n};\n", "import Element from '../core/core.element.js';\nimport layouts from '../core/core.layouts.js';\nimport {PI, isArray, toPadding, toFont} from '../helpers/index.js';\nimport {_toLeftRightCenter, _alignStartEnd} from '../helpers/helpers.extras.js';\nimport {renderText} from '../helpers/helpers.canvas.js';\n\nexport class Title extends Element {\n /**\n\t * @param {{ ctx: any; options: any; chart: any; }} config\n\t */\n constructor(config) {\n super();\n\n this.chart = config.chart;\n this.options = config.options;\n this.ctx = config.ctx;\n this._padding = undefined;\n this.top = undefined;\n this.bottom = undefined;\n this.left = undefined;\n this.right = undefined;\n this.width = undefined;\n this.height = undefined;\n this.position = undefined;\n this.weight = undefined;\n this.fullSize = undefined;\n }\n\n update(maxWidth, maxHeight) {\n const opts = this.options;\n\n this.left = 0;\n this.top = 0;\n\n if (!opts.display) {\n this.width = this.height = this.right = this.bottom = 0;\n return;\n }\n\n this.width = this.right = maxWidth;\n this.height = this.bottom = maxHeight;\n\n const lineCount = isArray(opts.text) ? opts.text.length : 1;\n this._padding = toPadding(opts.padding);\n const textSize = lineCount * toFont(opts.font).lineHeight + this._padding.height;\n\n if (this.isHorizontal()) {\n this.height = textSize;\n } else {\n this.width = textSize;\n }\n }\n\n isHorizontal() {\n const pos = this.options.position;\n return pos === 'top' || pos === 'bottom';\n }\n\n _drawArgs(offset) {\n const {top, left, bottom, right, options} = this;\n const align = options.align;\n let rotation = 0;\n let maxWidth, titleX, titleY;\n\n if (this.isHorizontal()) {\n titleX = _alignStartEnd(align, left, right);\n titleY = top + offset;\n maxWidth = right - left;\n } else {\n if (options.position === 'left') {\n titleX = left + offset;\n titleY = _alignStartEnd(align, bottom, top);\n rotation = PI * -0.5;\n } else {\n titleX = right - offset;\n titleY = _alignStartEnd(align, top, bottom);\n rotation = PI * 0.5;\n }\n maxWidth = bottom - top;\n }\n return {titleX, titleY, maxWidth, rotation};\n }\n\n draw() {\n const ctx = this.ctx;\n const opts = this.options;\n\n if (!opts.display) {\n return;\n }\n\n const fontOpts = toFont(opts.font);\n const lineHeight = fontOpts.lineHeight;\n const offset = lineHeight / 2 + this._padding.top;\n const {titleX, titleY, maxWidth, rotation} = this._drawArgs(offset);\n\n renderText(ctx, opts.text, 0, 0, fontOpts, {\n color: opts.color,\n maxWidth,\n rotation,\n textAlign: _toLeftRightCenter(opts.align),\n textBaseline: 'middle',\n translation: [titleX, titleY],\n });\n }\n}\n\nfunction createTitle(chart, titleOpts) {\n const title = new Title({\n ctx: chart.ctx,\n options: titleOpts,\n chart\n });\n\n layouts.configure(chart, title, titleOpts);\n layouts.addBox(chart, title);\n chart.titleBlock = title;\n}\n\nexport default {\n id: 'title',\n\n /**\n\t * For tests\n\t * @private\n\t */\n _element: Title,\n\n start(chart, _args, options) {\n createTitle(chart, options);\n },\n\n stop(chart) {\n const titleBlock = chart.titleBlock;\n layouts.removeBox(chart, titleBlock);\n delete chart.titleBlock;\n },\n\n beforeUpdate(chart, _args, options) {\n const title = chart.titleBlock;\n layouts.configure(chart, title, options);\n title.options = options;\n },\n\n defaults: {\n align: 'center',\n display: false,\n font: {\n weight: 'bold',\n },\n fullSize: true,\n padding: 10,\n position: 'top',\n text: '',\n weight: 2000 // by default greater than legend (1000) to be above\n },\n\n defaultRoutes: {\n color: 'color'\n },\n\n descriptors: {\n _scriptable: true,\n _indexable: false,\n },\n};\n", "import {Title} from './plugin.title.js';\nimport layouts from '../core/core.layouts.js';\n\nconst map = new WeakMap();\n\nexport default {\n id: 'subtitle',\n\n start(chart, _args, options) {\n const title = new Title({\n ctx: chart.ctx,\n options,\n chart\n });\n\n layouts.configure(chart, title, options);\n layouts.addBox(chart, title);\n map.set(chart, title);\n },\n\n stop(chart) {\n layouts.removeBox(chart, map.get(chart));\n map.delete(chart);\n },\n\n beforeUpdate(chart, _args, options) {\n const title = map.get(chart);\n layouts.configure(chart, title, options);\n title.options = options;\n },\n\n defaults: {\n align: 'center',\n display: false,\n font: {\n weight: 'normal',\n },\n fullSize: true,\n padding: 0,\n position: 'top',\n text: '',\n weight: 1500 // by default greater than legend (1000) and smaller than title (2000)\n },\n\n defaultRoutes: {\n color: 'color'\n },\n\n descriptors: {\n _scriptable: true,\n _indexable: false,\n },\n};\n", "import Animations from '../core/core.animations.js';\nimport Element from '../core/core.element.js';\nimport {addRoundedRectPath} from '../helpers/helpers.canvas.js';\nimport {each, noop, isNullOrUndef, isArray, _elementsEqual, isObject} from '../helpers/helpers.core.js';\nimport {toFont, toPadding, toTRBLCorners} from '../helpers/helpers.options.js';\nimport {getRtlAdapter, overrideTextDirection, restoreTextDirection} from '../helpers/helpers.rtl.js';\nimport {distanceBetweenPoints, _limitValue} from '../helpers/helpers.math.js';\nimport {createContext, drawPoint} from '../helpers/index.js';\n\n/**\n * @typedef { import('../platform/platform.base.js').Chart } Chart\n * @typedef { import('../types/index.js').ChartEvent } ChartEvent\n * @typedef { import('../types/index.js').ActiveElement } ActiveElement\n * @typedef { import('../core/core.interaction.js').InteractionItem } InteractionItem\n */\n\nconst positioners = {\n /**\n\t * Average mode places the tooltip at the average position of the elements shown\n\t */\n average(items) {\n if (!items.length) {\n return false;\n }\n\n let i, len;\n let xSet = new Set();\n let y = 0;\n let count = 0;\n\n for (i = 0, len = items.length; i < len; ++i) {\n const el = items[i].element;\n if (el && el.hasValue()) {\n const pos = el.tooltipPosition();\n xSet.add(pos.x);\n y += pos.y;\n ++count;\n }\n }\n\n const xAverage = [...xSet].reduce((a, b) => a + b) / xSet.size;\n\n return {\n x: xAverage,\n y: y / count\n };\n },\n\n /**\n\t * Gets the tooltip position nearest of the item nearest to the event position\n\t */\n nearest(items, eventPosition) {\n if (!items.length) {\n return false;\n }\n\n let x = eventPosition.x;\n let y = eventPosition.y;\n let minDistance = Number.POSITIVE_INFINITY;\n let i, len, nearestElement;\n\n for (i = 0, len = items.length; i < len; ++i) {\n const el = items[i].element;\n if (el && el.hasValue()) {\n const center = el.getCenterPoint();\n const d = distanceBetweenPoints(eventPosition, center);\n\n if (d < minDistance) {\n minDistance = d;\n nearestElement = el;\n }\n }\n }\n\n if (nearestElement) {\n const tp = nearestElement.tooltipPosition();\n x = tp.x;\n y = tp.y;\n }\n\n return {\n x,\n y\n };\n }\n};\n\n// Helper to push or concat based on if the 2nd parameter is an array or not\nfunction pushOrConcat(base, toPush) {\n if (toPush) {\n if (isArray(toPush)) {\n // base = base.concat(toPush);\n Array.prototype.push.apply(base, toPush);\n } else {\n base.push(toPush);\n }\n }\n\n return base;\n}\n\n/**\n * Returns array of strings split by newline\n * @param {*} str - The value to split by newline.\n * @returns {string|string[]} value if newline present - Returned from String split() method\n * @function\n */\nfunction splitNewlines(str) {\n if ((typeof str === 'string' || str instanceof String) && str.indexOf('\\n') > -1) {\n return str.split('\\n');\n }\n return str;\n}\n\n\n/**\n * Private helper to create a tooltip item model\n * @param {Chart} chart\n * @param {ActiveElement} item - {element, index, datasetIndex} to create the tooltip item for\n * @return new tooltip item\n */\nfunction createTooltipItem(chart, item) {\n const {element, datasetIndex, index} = item;\n const controller = chart.getDatasetMeta(datasetIndex).controller;\n const {label, value} = controller.getLabelAndValue(index);\n\n return {\n chart,\n label,\n parsed: controller.getParsed(index),\n raw: chart.data.datasets[datasetIndex].data[index],\n formattedValue: value,\n dataset: controller.getDataset(),\n dataIndex: index,\n datasetIndex,\n element\n };\n}\n\n/**\n * Get the size of the tooltip\n */\nfunction getTooltipSize(tooltip, options) {\n const ctx = tooltip.chart.ctx;\n const {body, footer, title} = tooltip;\n const {boxWidth, boxHeight} = options;\n const bodyFont = toFont(options.bodyFont);\n const titleFont = toFont(options.titleFont);\n const footerFont = toFont(options.footerFont);\n const titleLineCount = title.length;\n const footerLineCount = footer.length;\n const bodyLineItemCount = body.length;\n\n const padding = toPadding(options.padding);\n let height = padding.height;\n let width = 0;\n\n // Count of all lines in the body\n let combinedBodyLength = body.reduce((count, bodyItem) => count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length, 0);\n combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length;\n\n if (titleLineCount) {\n height += titleLineCount * titleFont.lineHeight\n\t\t\t+ (titleLineCount - 1) * options.titleSpacing\n\t\t\t+ options.titleMarginBottom;\n }\n if (combinedBodyLength) {\n // Body lines may include some extra height depending on boxHeight\n const bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight;\n height += bodyLineItemCount * bodyLineHeight\n\t\t\t+ (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight\n\t\t\t+ (combinedBodyLength - 1) * options.bodySpacing;\n }\n if (footerLineCount) {\n height += options.footerMarginTop\n\t\t\t+ footerLineCount * footerFont.lineHeight\n\t\t\t+ (footerLineCount - 1) * options.footerSpacing;\n }\n\n // Title width\n let widthPadding = 0;\n const maxLineWidth = function(line) {\n width = Math.max(width, ctx.measureText(line).width + widthPadding);\n };\n\n ctx.save();\n\n ctx.font = titleFont.string;\n each(tooltip.title, maxLineWidth);\n\n // Body width\n ctx.font = bodyFont.string;\n each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth);\n\n // Body lines may include some extra width due to the color box\n widthPadding = options.displayColors ? (boxWidth + 2 + options.boxPadding) : 0;\n each(body, (bodyItem) => {\n each(bodyItem.before, maxLineWidth);\n each(bodyItem.lines, maxLineWidth);\n each(bodyItem.after, maxLineWidth);\n });\n\n // Reset back to 0\n widthPadding = 0;\n\n // Footer width\n ctx.font = footerFont.string;\n each(tooltip.footer, maxLineWidth);\n\n ctx.restore();\n\n // Add padding\n width += padding.width;\n\n return {width, height};\n}\n\nfunction determineYAlign(chart, size) {\n const {y, height} = size;\n\n if (y < height / 2) {\n return 'top';\n } else if (y > (chart.height - height / 2)) {\n return 'bottom';\n }\n return 'center';\n}\n\nfunction doesNotFitWithAlign(xAlign, chart, options, size) {\n const {x, width} = size;\n const caret = options.caretSize + options.caretPadding;\n if (xAlign === 'left' && x + width + caret > chart.width) {\n return true;\n }\n\n if (xAlign === 'right' && x - width - caret < 0) {\n return true;\n }\n}\n\nfunction determineXAlign(chart, options, size, yAlign) {\n const {x, width} = size;\n const {width: chartWidth, chartArea: {left, right}} = chart;\n let xAlign = 'center';\n\n if (yAlign === 'center') {\n xAlign = x <= (left + right) / 2 ? 'left' : 'right';\n } else if (x <= width / 2) {\n xAlign = 'left';\n } else if (x >= chartWidth - width / 2) {\n xAlign = 'right';\n }\n\n if (doesNotFitWithAlign(xAlign, chart, options, size)) {\n xAlign = 'center';\n }\n\n return xAlign;\n}\n\n/**\n * Helper to get the alignment of a tooltip given the size\n */\nfunction determineAlignment(chart, options, size) {\n const yAlign = size.yAlign || options.yAlign || determineYAlign(chart, size);\n\n return {\n xAlign: size.xAlign || options.xAlign || determineXAlign(chart, options, size, yAlign),\n yAlign\n };\n}\n\nfunction alignX(size, xAlign) {\n let {x, width} = size;\n if (xAlign === 'right') {\n x -= width;\n } else if (xAlign === 'center') {\n x -= (width / 2);\n }\n return x;\n}\n\nfunction alignY(size, yAlign, paddingAndSize) {\n // eslint-disable-next-line prefer-const\n let {y, height} = size;\n if (yAlign === 'top') {\n y += paddingAndSize;\n } else if (yAlign === 'bottom') {\n y -= height + paddingAndSize;\n } else {\n y -= (height / 2);\n }\n return y;\n}\n\n/**\n * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment\n */\nfunction getBackgroundPoint(options, size, alignment, chart) {\n const {caretSize, caretPadding, cornerRadius} = options;\n const {xAlign, yAlign} = alignment;\n const paddingAndSize = caretSize + caretPadding;\n const {topLeft, topRight, bottomLeft, bottomRight} = toTRBLCorners(cornerRadius);\n\n let x = alignX(size, xAlign);\n const y = alignY(size, yAlign, paddingAndSize);\n\n if (yAlign === 'center') {\n if (xAlign === 'left') {\n x += paddingAndSize;\n } else if (xAlign === 'right') {\n x -= paddingAndSize;\n }\n } else if (xAlign === 'left') {\n x -= Math.max(topLeft, bottomLeft) + caretSize;\n } else if (xAlign === 'right') {\n x += Math.max(topRight, bottomRight) + caretSize;\n }\n\n return {\n x: _limitValue(x, 0, chart.width - size.width),\n y: _limitValue(y, 0, chart.height - size.height)\n };\n}\n\nfunction getAlignedX(tooltip, align, options) {\n const padding = toPadding(options.padding);\n\n return align === 'center'\n ? tooltip.x + tooltip.width / 2\n : align === 'right'\n ? tooltip.x + tooltip.width - padding.right\n : tooltip.x + padding.left;\n}\n\n/**\n * Helper to build before and after body lines\n */\nfunction getBeforeAfterBodyLines(callback) {\n return pushOrConcat([], splitNewlines(callback));\n}\n\nfunction createTooltipContext(parent, tooltip, tooltipItems) {\n return createContext(parent, {\n tooltip,\n tooltipItems,\n type: 'tooltip'\n });\n}\n\nfunction overrideCallbacks(callbacks, context) {\n const override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks;\n return override ? callbacks.override(override) : callbacks;\n}\n\nconst defaultCallbacks = {\n // Args are: (tooltipItems, data)\n beforeTitle: noop,\n title(tooltipItems) {\n if (tooltipItems.length > 0) {\n const item = tooltipItems[0];\n const labels = item.chart.data.labels;\n const labelCount = labels ? labels.length : 0;\n\n if (this && this.options && this.options.mode === 'dataset') {\n return item.dataset.label || '';\n } else if (item.label) {\n return item.label;\n } else if (labelCount > 0 && item.dataIndex < labelCount) {\n return labels[item.dataIndex];\n }\n }\n\n return '';\n },\n afterTitle: noop,\n\n // Args are: (tooltipItems, data)\n beforeBody: noop,\n\n // Args are: (tooltipItem, data)\n beforeLabel: noop,\n label(tooltipItem) {\n if (this && this.options && this.options.mode === 'dataset') {\n return tooltipItem.label + ': ' + tooltipItem.formattedValue || tooltipItem.formattedValue;\n }\n\n let label = tooltipItem.dataset.label || '';\n\n if (label) {\n label += ': ';\n }\n const value = tooltipItem.formattedValue;\n if (!isNullOrUndef(value)) {\n label += value;\n }\n return label;\n },\n labelColor(tooltipItem) {\n const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);\n const options = meta.controller.getStyle(tooltipItem.dataIndex);\n return {\n borderColor: options.borderColor,\n backgroundColor: options.backgroundColor,\n borderWidth: options.borderWidth,\n borderDash: options.borderDash,\n borderDashOffset: options.borderDashOffset,\n borderRadius: 0,\n };\n },\n labelTextColor() {\n return this.options.bodyColor;\n },\n labelPointStyle(tooltipItem) {\n const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);\n const options = meta.controller.getStyle(tooltipItem.dataIndex);\n return {\n pointStyle: options.pointStyle,\n rotation: options.rotation,\n };\n },\n afterLabel: noop,\n\n // Args are: (tooltipItems, data)\n afterBody: noop,\n\n // Args are: (tooltipItems, data)\n beforeFooter: noop,\n footer: noop,\n afterFooter: noop\n};\n\n/**\n * Invoke callback from object with context and arguments.\n * If callback returns `undefined`, then will be invoked default callback.\n * @param {Record} callbacks\n * @param {keyof typeof defaultCallbacks} name\n * @param {*} ctx\n * @param {*} arg\n * @returns {any}\n */\nfunction invokeCallbackWithFallback(callbacks, name, ctx, arg) {\n const result = callbacks[name].call(ctx, arg);\n\n if (typeof result === 'undefined') {\n return defaultCallbacks[name].call(ctx, arg);\n }\n\n return result;\n}\n\nexport class Tooltip extends Element {\n\n /**\n * @namespace Chart.Tooltip.positioners\n */\n static positioners = positioners;\n\n constructor(config) {\n super();\n\n this.opacity = 0;\n this._active = [];\n this._eventPosition = undefined;\n this._size = undefined;\n this._cachedAnimations = undefined;\n this._tooltipItems = [];\n this.$animations = undefined;\n this.$context = undefined;\n this.chart = config.chart;\n this.options = config.options;\n this.dataPoints = undefined;\n this.title = undefined;\n this.beforeBody = undefined;\n this.body = undefined;\n this.afterBody = undefined;\n this.footer = undefined;\n this.xAlign = undefined;\n this.yAlign = undefined;\n this.x = undefined;\n this.y = undefined;\n this.height = undefined;\n this.width = undefined;\n this.caretX = undefined;\n this.caretY = undefined;\n // TODO: V4, make this private, rename to `_labelStyles`, and combine with `labelPointStyles`\n // and `labelTextColors` to create a single variable\n this.labelColors = undefined;\n this.labelPointStyles = undefined;\n this.labelTextColors = undefined;\n }\n\n initialize(options) {\n this.options = options;\n this._cachedAnimations = undefined;\n this.$context = undefined;\n }\n\n /**\n\t * @private\n\t */\n _resolveAnimations() {\n const cached = this._cachedAnimations;\n\n if (cached) {\n return cached;\n }\n\n const chart = this.chart;\n const options = this.options.setContext(this.getContext());\n const opts = options.enabled && chart.options.animation && options.animations;\n const animations = new Animations(this.chart, opts);\n if (opts._cacheable) {\n this._cachedAnimations = Object.freeze(animations);\n }\n\n return animations;\n }\n\n /**\n\t * @protected\n\t */\n getContext() {\n return this.$context ||\n\t\t\t(this.$context = createTooltipContext(this.chart.getContext(), this, this._tooltipItems));\n }\n\n getTitle(context, options) {\n const {callbacks} = options;\n\n const beforeTitle = invokeCallbackWithFallback(callbacks, 'beforeTitle', this, context);\n const title = invokeCallbackWithFallback(callbacks, 'title', this, context);\n const afterTitle = invokeCallbackWithFallback(callbacks, 'afterTitle', this, context);\n\n let lines = [];\n lines = pushOrConcat(lines, splitNewlines(beforeTitle));\n lines = pushOrConcat(lines, splitNewlines(title));\n lines = pushOrConcat(lines, splitNewlines(afterTitle));\n\n return lines;\n }\n\n getBeforeBody(tooltipItems, options) {\n return getBeforeAfterBodyLines(\n invokeCallbackWithFallback(options.callbacks, 'beforeBody', this, tooltipItems)\n );\n }\n\n getBody(tooltipItems, options) {\n const {callbacks} = options;\n const bodyItems = [];\n\n each(tooltipItems, (context) => {\n const bodyItem = {\n before: [],\n lines: [],\n after: []\n };\n const scoped = overrideCallbacks(callbacks, context);\n pushOrConcat(bodyItem.before, splitNewlines(invokeCallbackWithFallback(scoped, 'beforeLabel', this, context)));\n pushOrConcat(bodyItem.lines, invokeCallbackWithFallback(scoped, 'label', this, context));\n pushOrConcat(bodyItem.after, splitNewlines(invokeCallbackWithFallback(scoped, 'afterLabel', this, context)));\n\n bodyItems.push(bodyItem);\n });\n\n return bodyItems;\n }\n\n getAfterBody(tooltipItems, options) {\n return getBeforeAfterBodyLines(\n invokeCallbackWithFallback(options.callbacks, 'afterBody', this, tooltipItems)\n );\n }\n\n // Get the footer and beforeFooter and afterFooter lines\n getFooter(tooltipItems, options) {\n const {callbacks} = options;\n\n const beforeFooter = invokeCallbackWithFallback(callbacks, 'beforeFooter', this, tooltipItems);\n const footer = invokeCallbackWithFallback(callbacks, 'footer', this, tooltipItems);\n const afterFooter = invokeCallbackWithFallback(callbacks, 'afterFooter', this, tooltipItems);\n\n let lines = [];\n lines = pushOrConcat(lines, splitNewlines(beforeFooter));\n lines = pushOrConcat(lines, splitNewlines(footer));\n lines = pushOrConcat(lines, splitNewlines(afterFooter));\n\n return lines;\n }\n\n /**\n\t * @private\n\t */\n _createItems(options) {\n const active = this._active;\n const data = this.chart.data;\n const labelColors = [];\n const labelPointStyles = [];\n const labelTextColors = [];\n let tooltipItems = [];\n let i, len;\n\n for (i = 0, len = active.length; i < len; ++i) {\n tooltipItems.push(createTooltipItem(this.chart, active[i]));\n }\n\n // If the user provided a filter function, use it to modify the tooltip items\n if (options.filter) {\n tooltipItems = tooltipItems.filter((element, index, array) => options.filter(element, index, array, data));\n }\n\n // If the user provided a sorting function, use it to modify the tooltip items\n if (options.itemSort) {\n tooltipItems = tooltipItems.sort((a, b) => options.itemSort(a, b, data));\n }\n\n // Determine colors for boxes\n each(tooltipItems, (context) => {\n const scoped = overrideCallbacks(options.callbacks, context);\n labelColors.push(invokeCallbackWithFallback(scoped, 'labelColor', this, context));\n labelPointStyles.push(invokeCallbackWithFallback(scoped, 'labelPointStyle', this, context));\n labelTextColors.push(invokeCallbackWithFallback(scoped, 'labelTextColor', this, context));\n });\n\n this.labelColors = labelColors;\n this.labelPointStyles = labelPointStyles;\n this.labelTextColors = labelTextColors;\n this.dataPoints = tooltipItems;\n return tooltipItems;\n }\n\n update(changed, replay) {\n const options = this.options.setContext(this.getContext());\n const active = this._active;\n let properties;\n let tooltipItems = [];\n\n if (!active.length) {\n if (this.opacity !== 0) {\n properties = {\n opacity: 0\n };\n }\n } else {\n const position = positioners[options.position].call(this, active, this._eventPosition);\n tooltipItems = this._createItems(options);\n\n this.title = this.getTitle(tooltipItems, options);\n this.beforeBody = this.getBeforeBody(tooltipItems, options);\n this.body = this.getBody(tooltipItems, options);\n this.afterBody = this.getAfterBody(tooltipItems, options);\n this.footer = this.getFooter(tooltipItems, options);\n\n const size = this._size = getTooltipSize(this, options);\n const positionAndSize = Object.assign({}, position, size);\n const alignment = determineAlignment(this.chart, options, positionAndSize);\n const backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, this.chart);\n\n this.xAlign = alignment.xAlign;\n this.yAlign = alignment.yAlign;\n\n properties = {\n opacity: 1,\n x: backgroundPoint.x,\n y: backgroundPoint.y,\n width: size.width,\n height: size.height,\n caretX: position.x,\n caretY: position.y\n };\n }\n\n this._tooltipItems = tooltipItems;\n this.$context = undefined;\n\n if (properties) {\n this._resolveAnimations().update(this, properties);\n }\n\n if (changed && options.external) {\n options.external.call(this, {chart: this.chart, tooltip: this, replay});\n }\n }\n\n drawCaret(tooltipPoint, ctx, size, options) {\n const caretPosition = this.getCaretPosition(tooltipPoint, size, options);\n\n ctx.lineTo(caretPosition.x1, caretPosition.y1);\n ctx.lineTo(caretPosition.x2, caretPosition.y2);\n ctx.lineTo(caretPosition.x3, caretPosition.y3);\n }\n\n getCaretPosition(tooltipPoint, size, options) {\n const {xAlign, yAlign} = this;\n const {caretSize, cornerRadius} = options;\n const {topLeft, topRight, bottomLeft, bottomRight} = toTRBLCorners(cornerRadius);\n const {x: ptX, y: ptY} = tooltipPoint;\n const {width, height} = size;\n let x1, x2, x3, y1, y2, y3;\n\n if (yAlign === 'center') {\n y2 = ptY + (height / 2);\n\n if (xAlign === 'left') {\n x1 = ptX;\n x2 = x1 - caretSize;\n\n // Left draws bottom -> top, this y1 is on the bottom\n y1 = y2 + caretSize;\n y3 = y2 - caretSize;\n } else {\n x1 = ptX + width;\n x2 = x1 + caretSize;\n\n // Right draws top -> bottom, thus y1 is on the top\n y1 = y2 - caretSize;\n y3 = y2 + caretSize;\n }\n\n x3 = x1;\n } else {\n if (xAlign === 'left') {\n x2 = ptX + Math.max(topLeft, bottomLeft) + (caretSize);\n } else if (xAlign === 'right') {\n x2 = ptX + width - Math.max(topRight, bottomRight) - caretSize;\n } else {\n x2 = this.caretX;\n }\n\n if (yAlign === 'top') {\n y1 = ptY;\n y2 = y1 - caretSize;\n\n // Top draws left -> right, thus x1 is on the left\n x1 = x2 - caretSize;\n x3 = x2 + caretSize;\n } else {\n y1 = ptY + height;\n y2 = y1 + caretSize;\n\n // Bottom draws right -> left, thus x1 is on the right\n x1 = x2 + caretSize;\n x3 = x2 - caretSize;\n }\n y3 = y1;\n }\n return {x1, x2, x3, y1, y2, y3};\n }\n\n drawTitle(pt, ctx, options) {\n const title = this.title;\n const length = title.length;\n let titleFont, titleSpacing, i;\n\n if (length) {\n const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);\n\n pt.x = getAlignedX(this, options.titleAlign, options);\n\n ctx.textAlign = rtlHelper.textAlign(options.titleAlign);\n ctx.textBaseline = 'middle';\n\n titleFont = toFont(options.titleFont);\n titleSpacing = options.titleSpacing;\n\n ctx.fillStyle = options.titleColor;\n ctx.font = titleFont.string;\n\n for (i = 0; i < length; ++i) {\n ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFont.lineHeight / 2);\n pt.y += titleFont.lineHeight + titleSpacing; // Line Height and spacing\n\n if (i + 1 === length) {\n pt.y += options.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing\n }\n }\n }\n }\n\n /**\n\t * @private\n\t */\n _drawColorBox(ctx, pt, i, rtlHelper, options) {\n const labelColor = this.labelColors[i];\n const labelPointStyle = this.labelPointStyles[i];\n const {boxHeight, boxWidth} = options;\n const bodyFont = toFont(options.bodyFont);\n const colorX = getAlignedX(this, 'left', options);\n const rtlColorX = rtlHelper.x(colorX);\n const yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0;\n const colorY = pt.y + yOffSet;\n\n if (options.usePointStyle) {\n const drawOptions = {\n radius: Math.min(boxWidth, boxHeight) / 2, // fit the circle in the box\n pointStyle: labelPointStyle.pointStyle,\n rotation: labelPointStyle.rotation,\n borderWidth: 1\n };\n // Recalculate x and y for drawPoint() because its expecting\n // x and y to be center of figure (instead of top left)\n const centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2;\n const centerY = colorY + boxHeight / 2;\n\n // Fill the point with white so that colours merge nicely if the opacity is < 1\n ctx.strokeStyle = options.multiKeyBackground;\n ctx.fillStyle = options.multiKeyBackground;\n drawPoint(ctx, drawOptions, centerX, centerY);\n\n // Draw the point\n ctx.strokeStyle = labelColor.borderColor;\n ctx.fillStyle = labelColor.backgroundColor;\n drawPoint(ctx, drawOptions, centerX, centerY);\n } else {\n // Border\n ctx.lineWidth = isObject(labelColor.borderWidth) ? Math.max(...Object.values(labelColor.borderWidth)) : (labelColor.borderWidth || 1); // TODO, v4 remove fallback\n ctx.strokeStyle = labelColor.borderColor;\n ctx.setLineDash(labelColor.borderDash || []);\n ctx.lineDashOffset = labelColor.borderDashOffset || 0;\n\n // Fill a white rect so that colours merge nicely if the opacity is < 1\n const outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth);\n const innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - 2);\n const borderRadius = toTRBLCorners(labelColor.borderRadius);\n\n if (Object.values(borderRadius).some(v => v !== 0)) {\n ctx.beginPath();\n ctx.fillStyle = options.multiKeyBackground;\n addRoundedRectPath(ctx, {\n x: outerX,\n y: colorY,\n w: boxWidth,\n h: boxHeight,\n radius: borderRadius,\n });\n ctx.fill();\n ctx.stroke();\n\n // Inner square\n ctx.fillStyle = labelColor.backgroundColor;\n ctx.beginPath();\n addRoundedRectPath(ctx, {\n x: innerX,\n y: colorY + 1,\n w: boxWidth - 2,\n h: boxHeight - 2,\n radius: borderRadius,\n });\n ctx.fill();\n } else {\n // Normal rect\n ctx.fillStyle = options.multiKeyBackground;\n ctx.fillRect(outerX, colorY, boxWidth, boxHeight);\n ctx.strokeRect(outerX, colorY, boxWidth, boxHeight);\n // Inner square\n ctx.fillStyle = labelColor.backgroundColor;\n ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2);\n }\n }\n\n // restore fillStyle\n ctx.fillStyle = this.labelTextColors[i];\n }\n\n drawBody(pt, ctx, options) {\n const {body} = this;\n const {bodySpacing, bodyAlign, displayColors, boxHeight, boxWidth, boxPadding} = options;\n const bodyFont = toFont(options.bodyFont);\n let bodyLineHeight = bodyFont.lineHeight;\n let xLinePadding = 0;\n\n const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);\n\n const fillLineOfText = function(line) {\n ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyLineHeight / 2);\n pt.y += bodyLineHeight + bodySpacing;\n };\n\n const bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);\n let bodyItem, textColor, lines, i, j, ilen, jlen;\n\n ctx.textAlign = bodyAlign;\n ctx.textBaseline = 'middle';\n ctx.font = bodyFont.string;\n\n pt.x = getAlignedX(this, bodyAlignForCalculation, options);\n\n // Before body lines\n ctx.fillStyle = options.bodyColor;\n each(this.beforeBody, fillLineOfText);\n\n xLinePadding = displayColors && bodyAlignForCalculation !== 'right'\n ? bodyAlign === 'center' ? (boxWidth / 2 + boxPadding) : (boxWidth + 2 + boxPadding)\n : 0;\n\n // Draw body lines now\n for (i = 0, ilen = body.length; i < ilen; ++i) {\n bodyItem = body[i];\n textColor = this.labelTextColors[i];\n\n ctx.fillStyle = textColor;\n each(bodyItem.before, fillLineOfText);\n\n lines = bodyItem.lines;\n // Draw Legend-like boxes if needed\n if (displayColors && lines.length) {\n this._drawColorBox(ctx, pt, i, rtlHelper, options);\n bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight);\n }\n\n for (j = 0, jlen = lines.length; j < jlen; ++j) {\n fillLineOfText(lines[j]);\n // Reset for any lines that don't include colorbox\n bodyLineHeight = bodyFont.lineHeight;\n }\n\n each(bodyItem.after, fillLineOfText);\n }\n\n // Reset back to 0 for after body\n xLinePadding = 0;\n bodyLineHeight = bodyFont.lineHeight;\n\n // After body lines\n each(this.afterBody, fillLineOfText);\n pt.y -= bodySpacing; // Remove last body spacing\n }\n\n drawFooter(pt, ctx, options) {\n const footer = this.footer;\n const length = footer.length;\n let footerFont, i;\n\n if (length) {\n const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);\n\n pt.x = getAlignedX(this, options.footerAlign, options);\n pt.y += options.footerMarginTop;\n\n ctx.textAlign = rtlHelper.textAlign(options.footerAlign);\n ctx.textBaseline = 'middle';\n\n footerFont = toFont(options.footerFont);\n\n ctx.fillStyle = options.footerColor;\n ctx.font = footerFont.string;\n\n for (i = 0; i < length; ++i) {\n ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFont.lineHeight / 2);\n pt.y += footerFont.lineHeight + options.footerSpacing;\n }\n }\n }\n\n drawBackground(pt, ctx, tooltipSize, options) {\n const {xAlign, yAlign} = this;\n const {x, y} = pt;\n const {width, height} = tooltipSize;\n const {topLeft, topRight, bottomLeft, bottomRight} = toTRBLCorners(options.cornerRadius);\n\n ctx.fillStyle = options.backgroundColor;\n ctx.strokeStyle = options.borderColor;\n ctx.lineWidth = options.borderWidth;\n\n ctx.beginPath();\n ctx.moveTo(x + topLeft, y);\n if (yAlign === 'top') {\n this.drawCaret(pt, ctx, tooltipSize, options);\n }\n ctx.lineTo(x + width - topRight, y);\n ctx.quadraticCurveTo(x + width, y, x + width, y + topRight);\n if (yAlign === 'center' && xAlign === 'right') {\n this.drawCaret(pt, ctx, tooltipSize, options);\n }\n ctx.lineTo(x + width, y + height - bottomRight);\n ctx.quadraticCurveTo(x + width, y + height, x + width - bottomRight, y + height);\n if (yAlign === 'bottom') {\n this.drawCaret(pt, ctx, tooltipSize, options);\n }\n ctx.lineTo(x + bottomLeft, y + height);\n ctx.quadraticCurveTo(x, y + height, x, y + height - bottomLeft);\n if (yAlign === 'center' && xAlign === 'left') {\n this.drawCaret(pt, ctx, tooltipSize, options);\n }\n ctx.lineTo(x, y + topLeft);\n ctx.quadraticCurveTo(x, y, x + topLeft, y);\n ctx.closePath();\n\n ctx.fill();\n\n if (options.borderWidth > 0) {\n ctx.stroke();\n }\n }\n\n /**\n\t * Update x/y animation targets when _active elements are animating too\n\t * @private\n\t */\n _updateAnimationTarget(options) {\n const chart = this.chart;\n const anims = this.$animations;\n const animX = anims && anims.x;\n const animY = anims && anims.y;\n if (animX || animY) {\n const position = positioners[options.position].call(this, this._active, this._eventPosition);\n if (!position) {\n return;\n }\n const size = this._size = getTooltipSize(this, options);\n const positionAndSize = Object.assign({}, position, this._size);\n const alignment = determineAlignment(chart, options, positionAndSize);\n const point = getBackgroundPoint(options, positionAndSize, alignment, chart);\n if (animX._to !== point.x || animY._to !== point.y) {\n this.xAlign = alignment.xAlign;\n this.yAlign = alignment.yAlign;\n this.width = size.width;\n this.height = size.height;\n this.caretX = position.x;\n this.caretY = position.y;\n this._resolveAnimations().update(this, point);\n }\n }\n }\n\n /**\n * Determine if the tooltip will draw anything\n * @returns {boolean} True if the tooltip will render\n */\n _willRender() {\n return !!this.opacity;\n }\n\n draw(ctx) {\n const options = this.options.setContext(this.getContext());\n let opacity = this.opacity;\n\n if (!opacity) {\n return;\n }\n\n this._updateAnimationTarget(options);\n\n const tooltipSize = {\n width: this.width,\n height: this.height\n };\n const pt = {\n x: this.x,\n y: this.y\n };\n\n // IE11/Edge does not like very small opacities, so snap to 0\n opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity;\n\n const padding = toPadding(options.padding);\n\n // Truthy/falsey value for empty tooltip\n const hasTooltipContent = this.title.length || this.beforeBody.length || this.body.length || this.afterBody.length || this.footer.length;\n\n if (options.enabled && hasTooltipContent) {\n ctx.save();\n ctx.globalAlpha = opacity;\n\n // Draw Background\n this.drawBackground(pt, ctx, tooltipSize, options);\n\n overrideTextDirection(ctx, options.textDirection);\n\n pt.y += padding.top;\n\n // Titles\n this.drawTitle(pt, ctx, options);\n\n // Body\n this.drawBody(pt, ctx, options);\n\n // Footer\n this.drawFooter(pt, ctx, options);\n\n restoreTextDirection(ctx, options.textDirection);\n\n ctx.restore();\n }\n }\n\n /**\n\t * Get active elements in the tooltip\n\t * @returns {Array} Array of elements that are active in the tooltip\n\t */\n getActiveElements() {\n return this._active || [];\n }\n\n /**\n\t * Set active elements in the tooltip\n\t * @param {array} activeElements Array of active datasetIndex/index pairs.\n\t * @param {object} eventPosition Synthetic event position used in positioning\n\t */\n setActiveElements(activeElements, eventPosition) {\n const lastActive = this._active;\n const active = activeElements.map(({datasetIndex, index}) => {\n const meta = this.chart.getDatasetMeta(datasetIndex);\n\n if (!meta) {\n throw new Error('Cannot find a dataset at index ' + datasetIndex);\n }\n\n return {\n datasetIndex,\n element: meta.data[index],\n index,\n };\n });\n const changed = !_elementsEqual(lastActive, active);\n const positionChanged = this._positionChanged(active, eventPosition);\n\n if (changed || positionChanged) {\n this._active = active;\n this._eventPosition = eventPosition;\n this._ignoreReplayEvents = true;\n this.update(true);\n }\n }\n\n /**\n\t * Handle an event\n\t * @param {ChartEvent} e - The event to handle\n\t * @param {boolean} [replay] - This is a replayed event (from update)\n\t * @param {boolean} [inChartArea] - The event is inside chartArea\n\t * @returns {boolean} true if the tooltip changed\n\t */\n handleEvent(e, replay, inChartArea = true) {\n if (replay && this._ignoreReplayEvents) {\n return false;\n }\n this._ignoreReplayEvents = false;\n\n const options = this.options;\n const lastActive = this._active || [];\n const active = this._getActiveElements(e, lastActive, replay, inChartArea);\n\n // When there are multiple items shown, but the tooltip position is nearest mode\n // an update may need to be made because our position may have changed even though\n // the items are the same as before.\n const positionChanged = this._positionChanged(active, e);\n\n // Remember Last Actives\n const changed = replay || !_elementsEqual(active, lastActive) || positionChanged;\n\n // Only handle target event on tooltip change\n if (changed) {\n this._active = active;\n\n if (options.enabled || options.external) {\n this._eventPosition = {\n x: e.x,\n y: e.y\n };\n\n this.update(true, replay);\n }\n }\n\n return changed;\n }\n\n /**\n\t * Helper for determining the active elements for event\n\t * @param {ChartEvent} e - The event to handle\n\t * @param {InteractionItem[]} lastActive - Previously active elements\n\t * @param {boolean} [replay] - This is a replayed event (from update)\n\t * @param {boolean} [inChartArea] - The event is inside chartArea\n\t * @returns {InteractionItem[]} - Active elements\n\t * @private\n\t */\n _getActiveElements(e, lastActive, replay, inChartArea) {\n const options = this.options;\n\n if (e.type === 'mouseout') {\n return [];\n }\n\n if (!inChartArea) {\n // Let user control the active elements outside chartArea. Eg. using Legend.\n // But make sure that active elements are still valid.\n return lastActive.filter(i =>\n this.chart.data.datasets[i.datasetIndex] &&\n this.chart.getDatasetMeta(i.datasetIndex).controller.getParsed(i.index) !== undefined\n );\n }\n\n // Find Active Elements for tooltips\n const active = this.chart.getElementsAtEventForMode(e, options.mode, options, replay);\n\n if (options.reverse) {\n active.reverse();\n }\n\n return active;\n }\n\n /**\n\t * Determine if the active elements + event combination changes the\n\t * tooltip position\n\t * @param {array} active - Active elements\n\t * @param {ChartEvent} e - Event that triggered the position change\n\t * @returns {boolean} True if the position has changed\n\t */\n _positionChanged(active, e) {\n const {caretX, caretY, options} = this;\n const position = positioners[options.position].call(this, active, e);\n return position !== false && (caretX !== position.x || caretY !== position.y);\n }\n}\n\nexport default {\n id: 'tooltip',\n _element: Tooltip,\n positioners,\n\n afterInit(chart, _args, options) {\n if (options) {\n chart.tooltip = new Tooltip({chart, options});\n }\n },\n\n beforeUpdate(chart, _args, options) {\n if (chart.tooltip) {\n chart.tooltip.initialize(options);\n }\n },\n\n reset(chart, _args, options) {\n if (chart.tooltip) {\n chart.tooltip.initialize(options);\n }\n },\n\n afterDraw(chart) {\n const tooltip = chart.tooltip;\n\n if (tooltip && tooltip._willRender()) {\n const args = {\n tooltip\n };\n\n if (chart.notifyPlugins('beforeTooltipDraw', {...args, cancelable: true}) === false) {\n return;\n }\n\n tooltip.draw(chart.ctx);\n\n chart.notifyPlugins('afterTooltipDraw', args);\n }\n },\n\n afterEvent(chart, args) {\n if (chart.tooltip) {\n // If the event is replayed from `update`, we should evaluate with the final positions.\n const useFinalPosition = args.replay;\n if (chart.tooltip.handleEvent(args.event, useFinalPosition, args.inChartArea)) {\n // notify chart about the change, so it will render\n args.changed = true;\n }\n }\n },\n\n defaults: {\n enabled: true,\n external: null,\n position: 'average',\n backgroundColor: 'rgba(0,0,0,0.8)',\n titleColor: '#fff',\n titleFont: {\n weight: 'bold',\n },\n titleSpacing: 2,\n titleMarginBottom: 6,\n titleAlign: 'left',\n bodyColor: '#fff',\n bodySpacing: 2,\n bodyFont: {\n },\n bodyAlign: 'left',\n footerColor: '#fff',\n footerSpacing: 2,\n footerMarginTop: 6,\n footerFont: {\n weight: 'bold',\n },\n footerAlign: 'left',\n padding: 6,\n caretPadding: 2,\n caretSize: 5,\n cornerRadius: 6,\n boxHeight: (ctx, opts) => opts.bodyFont.size,\n boxWidth: (ctx, opts) => opts.bodyFont.size,\n multiKeyBackground: '#fff',\n displayColors: true,\n boxPadding: 0,\n borderColor: 'rgba(0,0,0,0)',\n borderWidth: 0,\n animation: {\n duration: 400,\n easing: 'easeOutQuart',\n },\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'width', 'height', 'caretX', 'caretY'],\n },\n opacity: {\n easing: 'linear',\n duration: 200\n }\n },\n callbacks: defaultCallbacks\n },\n\n defaultRoutes: {\n bodyFont: 'font',\n footerFont: 'font',\n titleFont: 'font'\n },\n\n descriptors: {\n _scriptable: (name) => name !== 'filter' && name !== 'itemSort' && name !== 'external',\n _indexable: false,\n callbacks: {\n _scriptable: false,\n _indexable: false,\n },\n animation: {\n _fallback: false\n },\n animations: {\n _fallback: 'animation'\n }\n },\n\n // Resolve additionally from `interaction` options and defaults.\n additionalOptionScopes: ['interaction']\n};\n", "import Scale from '../core/core.scale.js';\nimport {isNullOrUndef, valueOrDefault, _limitValue} from '../helpers/index.js';\n\nconst addIfString = (labels, raw, index, addedLabels) => {\n if (typeof raw === 'string') {\n index = labels.push(raw) - 1;\n addedLabels.unshift({index, label: raw});\n } else if (isNaN(raw)) {\n index = null;\n }\n return index;\n};\n\nfunction findOrAddLabel(labels, raw, index, addedLabels) {\n const first = labels.indexOf(raw);\n if (first === -1) {\n return addIfString(labels, raw, index, addedLabels);\n }\n const last = labels.lastIndexOf(raw);\n return first !== last ? index : first;\n}\n\nconst validIndex = (index, max) => index === null ? null : _limitValue(Math.round(index), 0, max);\n\nfunction _getLabelForValue(value) {\n const labels = this.getLabels();\n\n if (value >= 0 && value < labels.length) {\n return labels[value];\n }\n return value;\n}\n\nexport default class CategoryScale extends Scale {\n\n static id = 'category';\n\n /**\n * @type {any}\n */\n static defaults = {\n ticks: {\n callback: _getLabelForValue\n }\n };\n\n constructor(cfg) {\n super(cfg);\n\n /** @type {number} */\n this._startValue = undefined;\n this._valueRange = 0;\n this._addedLabels = [];\n }\n\n init(scaleOptions) {\n const added = this._addedLabels;\n if (added.length) {\n const labels = this.getLabels();\n for (const {index, label} of added) {\n if (labels[index] === label) {\n labels.splice(index, 1);\n }\n }\n this._addedLabels = [];\n }\n super.init(scaleOptions);\n }\n\n parse(raw, index) {\n if (isNullOrUndef(raw)) {\n return null;\n }\n const labels = this.getLabels();\n index = isFinite(index) && labels[index] === raw ? index\n : findOrAddLabel(labels, raw, valueOrDefault(index, raw), this._addedLabels);\n return validIndex(index, labels.length - 1);\n }\n\n determineDataLimits() {\n const {minDefined, maxDefined} = this.getUserBounds();\n let {min, max} = this.getMinMax(true);\n\n if (this.options.bounds === 'ticks') {\n if (!minDefined) {\n min = 0;\n }\n if (!maxDefined) {\n max = this.getLabels().length - 1;\n }\n }\n\n this.min = min;\n this.max = max;\n }\n\n buildTicks() {\n const min = this.min;\n const max = this.max;\n const offset = this.options.offset;\n const ticks = [];\n let labels = this.getLabels();\n\n // If we are viewing some subset of labels, slice the original array\n labels = (min === 0 && max === labels.length - 1) ? labels : labels.slice(min, max + 1);\n\n this._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1);\n this._startValue = this.min - (offset ? 0.5 : 0);\n\n for (let value = min; value <= max; value++) {\n ticks.push({value});\n }\n return ticks;\n }\n\n getLabelForValue(value) {\n return _getLabelForValue.call(this, value);\n }\n\n /**\n\t * @protected\n\t */\n configure() {\n super.configure();\n\n if (!this.isHorizontal()) {\n // For backward compatibility, vertical category scale reverse is inverted.\n this._reversePixels = !this._reversePixels;\n }\n }\n\n // Used to get data value locations. Value can either be an index or a numerical value\n getPixelForValue(value) {\n if (typeof value !== 'number') {\n value = this.parse(value);\n }\n\n return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);\n }\n\n // Must override base implementation because it calls getPixelForValue\n // and category scale can have duplicate values\n getPixelForTick(index) {\n const ticks = this.ticks;\n if (index < 0 || index > ticks.length - 1) {\n return null;\n }\n return this.getPixelForValue(ticks[index].value);\n }\n\n getValueForPixel(pixel) {\n return Math.round(this._startValue + this.getDecimalForPixel(pixel) * this._valueRange);\n }\n\n getBasePixel() {\n return this.bottom;\n }\n}\n", "import {isNullOrUndef} from '../helpers/helpers.core.js';\nimport {almostEquals, almostWhole, niceNum, _decimalPlaces, _setMinAndMaxByKey, sign, toRadians} from '../helpers/helpers.math.js';\nimport Scale from '../core/core.scale.js';\nimport {formatNumber} from '../helpers/helpers.intl.js';\n\n/**\n * Generate a set of linear ticks for an axis\n * 1. If generationOptions.min, generationOptions.max, and generationOptions.step are defined:\n * if (max - min) / step is an integer, ticks are generated as [min, min + step, ..., max]\n * Note that the generationOptions.maxCount setting is respected in this scenario\n *\n * 2. If generationOptions.min, generationOptions.max, and generationOptions.count is defined\n * spacing = (max - min) / count\n * Ticks are generated as [min, min + spacing, ..., max]\n *\n * 3. If generationOptions.count is defined\n * spacing = (niceMax - niceMin) / count\n *\n * 4. Compute optimal spacing of ticks using niceNum algorithm\n *\n * @param generationOptions the options used to generate the ticks\n * @param dataRange the range of the data\n * @returns {object[]} array of tick objects\n */\nfunction generateTicks(generationOptions, dataRange) {\n const ticks = [];\n // To get a \"nice\" value for the tick spacing, we will use the appropriately named\n // \"nice number\" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks\n // for details.\n\n const MIN_SPACING = 1e-14;\n const {bounds, step, min, max, precision, count, maxTicks, maxDigits, includeBounds} = generationOptions;\n const unit = step || 1;\n const maxSpaces = maxTicks - 1;\n const {min: rmin, max: rmax} = dataRange;\n const minDefined = !isNullOrUndef(min);\n const maxDefined = !isNullOrUndef(max);\n const countDefined = !isNullOrUndef(count);\n const minSpacing = (rmax - rmin) / (maxDigits + 1);\n let spacing = niceNum((rmax - rmin) / maxSpaces / unit) * unit;\n let factor, niceMin, niceMax, numSpaces;\n\n // Beyond MIN_SPACING floating point numbers being to lose precision\n // such that we can't do the math necessary to generate ticks\n if (spacing < MIN_SPACING && !minDefined && !maxDefined) {\n return [{value: rmin}, {value: rmax}];\n }\n\n numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);\n if (numSpaces > maxSpaces) {\n // If the calculated num of spaces exceeds maxNumSpaces, recalculate it\n spacing = niceNum(numSpaces * spacing / maxSpaces / unit) * unit;\n }\n\n if (!isNullOrUndef(precision)) {\n // If the user specified a precision, round to that number of decimal places\n factor = Math.pow(10, precision);\n spacing = Math.ceil(spacing * factor) / factor;\n }\n\n if (bounds === 'ticks') {\n niceMin = Math.floor(rmin / spacing) * spacing;\n niceMax = Math.ceil(rmax / spacing) * spacing;\n } else {\n niceMin = rmin;\n niceMax = rmax;\n }\n\n if (minDefined && maxDefined && step && almostWhole((max - min) / step, spacing / 1000)) {\n // Case 1: If min, max and stepSize are set and they make an evenly spaced scale use it.\n // spacing = step;\n // numSpaces = (max - min) / spacing;\n // Note that we round here to handle the case where almostWhole translated an FP error\n numSpaces = Math.round(Math.min((max - min) / spacing, maxTicks));\n spacing = (max - min) / numSpaces;\n niceMin = min;\n niceMax = max;\n } else if (countDefined) {\n // Cases 2 & 3, we have a count specified. Handle optional user defined edges to the range.\n // Sometimes these are no-ops, but it makes the code a lot clearer\n // and when a user defined range is specified, we want the correct ticks\n niceMin = minDefined ? min : niceMin;\n niceMax = maxDefined ? max : niceMax;\n numSpaces = count - 1;\n spacing = (niceMax - niceMin) / numSpaces;\n } else {\n // Case 4\n numSpaces = (niceMax - niceMin) / spacing;\n\n // If very close to our rounded value, use it.\n if (almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {\n numSpaces = Math.round(numSpaces);\n } else {\n numSpaces = Math.ceil(numSpaces);\n }\n }\n\n // The spacing will have changed in cases 1, 2, and 3 so the factor cannot be computed\n // until this point\n const decimalPlaces = Math.max(\n _decimalPlaces(spacing),\n _decimalPlaces(niceMin)\n );\n factor = Math.pow(10, isNullOrUndef(precision) ? decimalPlaces : precision);\n niceMin = Math.round(niceMin * factor) / factor;\n niceMax = Math.round(niceMax * factor) / factor;\n\n let j = 0;\n if (minDefined) {\n if (includeBounds && niceMin !== min) {\n ticks.push({value: min});\n\n if (niceMin < min) {\n j++; // Skip niceMin\n }\n // If the next nice tick is close to min, skip it\n if (almostEquals(Math.round((niceMin + j * spacing) * factor) / factor, min, relativeLabelSize(min, minSpacing, generationOptions))) {\n j++;\n }\n } else if (niceMin < min) {\n j++;\n }\n }\n\n for (; j < numSpaces; ++j) {\n const tickValue = Math.round((niceMin + j * spacing) * factor) / factor;\n if (maxDefined && tickValue > max) {\n break;\n }\n ticks.push({value: tickValue});\n }\n\n if (maxDefined && includeBounds && niceMax !== max) {\n // If the previous tick is too close to max, replace it with max, else add max\n if (ticks.length && almostEquals(ticks[ticks.length - 1].value, max, relativeLabelSize(max, minSpacing, generationOptions))) {\n ticks[ticks.length - 1].value = max;\n } else {\n ticks.push({value: max});\n }\n } else if (!maxDefined || niceMax === max) {\n ticks.push({value: niceMax});\n }\n\n return ticks;\n}\n\nfunction relativeLabelSize(value, minSpacing, {horizontal, minRotation}) {\n const rad = toRadians(minRotation);\n const ratio = (horizontal ? Math.sin(rad) : Math.cos(rad)) || 0.001;\n const length = 0.75 * minSpacing * ('' + value).length;\n return Math.min(minSpacing / ratio, length);\n}\n\nexport default class LinearScaleBase extends Scale {\n\n constructor(cfg) {\n super(cfg);\n\n /** @type {number} */\n this.start = undefined;\n /** @type {number} */\n this.end = undefined;\n /** @type {number} */\n this._startValue = undefined;\n /** @type {number} */\n this._endValue = undefined;\n this._valueRange = 0;\n }\n\n parse(raw, index) { // eslint-disable-line no-unused-vars\n if (isNullOrUndef(raw)) {\n return null;\n }\n if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) {\n return null;\n }\n\n return +raw;\n }\n\n handleTickRangeOptions() {\n const {beginAtZero} = this.options;\n const {minDefined, maxDefined} = this.getUserBounds();\n let {min, max} = this;\n\n const setMin = v => (min = minDefined ? min : v);\n const setMax = v => (max = maxDefined ? max : v);\n\n if (beginAtZero) {\n const minSign = sign(min);\n const maxSign = sign(max);\n\n if (minSign < 0 && maxSign < 0) {\n setMax(0);\n } else if (minSign > 0 && maxSign > 0) {\n setMin(0);\n }\n }\n\n if (min === max) {\n let offset = max === 0 ? 1 : Math.abs(max * 0.05);\n\n setMax(max + offset);\n\n if (!beginAtZero) {\n setMin(min - offset);\n }\n }\n this.min = min;\n this.max = max;\n }\n\n getTickLimit() {\n const tickOpts = this.options.ticks;\n // eslint-disable-next-line prefer-const\n let {maxTicksLimit, stepSize} = tickOpts;\n let maxTicks;\n\n if (stepSize) {\n maxTicks = Math.ceil(this.max / stepSize) - Math.floor(this.min / stepSize) + 1;\n if (maxTicks > 1000) {\n console.warn(`scales.${this.id}.ticks.stepSize: ${stepSize} would result generating up to ${maxTicks} ticks. Limiting to 1000.`);\n maxTicks = 1000;\n }\n } else {\n maxTicks = this.computeTickLimit();\n maxTicksLimit = maxTicksLimit || 11;\n }\n\n if (maxTicksLimit) {\n maxTicks = Math.min(maxTicksLimit, maxTicks);\n }\n\n return maxTicks;\n }\n\n /**\n\t * @protected\n\t */\n computeTickLimit() {\n return Number.POSITIVE_INFINITY;\n }\n\n buildTicks() {\n const opts = this.options;\n const tickOpts = opts.ticks;\n\n // Figure out what the max number of ticks we can support it is based on the size of\n // the axis area. For now, we say that the minimum tick spacing in pixels must be 40\n // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on\n // the graph. Make sure we always have at least 2 ticks\n let maxTicks = this.getTickLimit();\n maxTicks = Math.max(2, maxTicks);\n\n const numericGeneratorOptions = {\n maxTicks,\n bounds: opts.bounds,\n min: opts.min,\n max: opts.max,\n precision: tickOpts.precision,\n step: tickOpts.stepSize,\n count: tickOpts.count,\n maxDigits: this._maxDigits(),\n horizontal: this.isHorizontal(),\n minRotation: tickOpts.minRotation || 0,\n includeBounds: tickOpts.includeBounds !== false\n };\n const dataRange = this._range || this;\n const ticks = generateTicks(numericGeneratorOptions, dataRange);\n\n // At this point, we need to update our max and min given the tick values,\n // since we probably have expanded the range of the scale\n if (opts.bounds === 'ticks') {\n _setMinAndMaxByKey(ticks, this, 'value');\n }\n\n if (opts.reverse) {\n ticks.reverse();\n\n this.start = this.max;\n this.end = this.min;\n } else {\n this.start = this.min;\n this.end = this.max;\n }\n\n return ticks;\n }\n\n /**\n\t * @protected\n\t */\n configure() {\n const ticks = this.ticks;\n let start = this.min;\n let end = this.max;\n\n super.configure();\n\n if (this.options.offset && ticks.length) {\n const offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;\n start -= offset;\n end += offset;\n }\n this._startValue = start;\n this._endValue = end;\n this._valueRange = end - start;\n }\n\n getLabelForValue(value) {\n return formatNumber(value, this.chart.options.locale, this.options.ticks.format);\n }\n}\n", "import {isFinite} from '../helpers/helpers.core.js';\nimport LinearScaleBase from './scale.linearbase.js';\nimport Ticks from '../core/core.ticks.js';\nimport {toRadians} from '../helpers/index.js';\n\nexport default class LinearScale extends LinearScaleBase {\n\n static id = 'linear';\n\n /**\n * @type {any}\n */\n static defaults = {\n ticks: {\n callback: Ticks.formatters.numeric\n }\n };\n\n\n determineDataLimits() {\n const {min, max} = this.getMinMax(true);\n\n this.min = isFinite(min) ? min : 0;\n this.max = isFinite(max) ? max : 1;\n\n // Common base implementation to handle min, max, beginAtZero\n this.handleTickRangeOptions();\n }\n\n /**\n\t * Returns the maximum number of ticks based on the scale dimension\n\t * @protected\n \t */\n computeTickLimit() {\n const horizontal = this.isHorizontal();\n const length = horizontal ? this.width : this.height;\n const minRotation = toRadians(this.options.ticks.minRotation);\n const ratio = (horizontal ? Math.sin(minRotation) : Math.cos(minRotation)) || 0.001;\n const tickFont = this._resolveTickFontOptions(0);\n return Math.ceil(length / Math.min(40, tickFont.lineHeight / ratio));\n }\n\n // Utils\n getPixelForValue(value) {\n return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);\n }\n\n getValueForPixel(pixel) {\n return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;\n }\n}\n", "import {finiteOrDefault, isFinite} from '../helpers/helpers.core.js';\nimport {formatNumber} from '../helpers/helpers.intl.js';\nimport {_setMinAndMaxByKey, log10} from '../helpers/helpers.math.js';\nimport Scale from '../core/core.scale.js';\nimport LinearScaleBase from './scale.linearbase.js';\nimport Ticks from '../core/core.ticks.js';\n\nconst log10Floor = v => Math.floor(log10(v));\nconst changeExponent = (v, m) => Math.pow(10, log10Floor(v) + m);\n\nfunction isMajor(tickVal) {\n const remain = tickVal / (Math.pow(10, log10Floor(tickVal)));\n return remain === 1;\n}\n\nfunction steps(min, max, rangeExp) {\n const rangeStep = Math.pow(10, rangeExp);\n const start = Math.floor(min / rangeStep);\n const end = Math.ceil(max / rangeStep);\n return end - start;\n}\n\nfunction startExp(min, max) {\n const range = max - min;\n let rangeExp = log10Floor(range);\n while (steps(min, max, rangeExp) > 10) {\n rangeExp++;\n }\n while (steps(min, max, rangeExp) < 10) {\n rangeExp--;\n }\n return Math.min(rangeExp, log10Floor(min));\n}\n\n\n/**\n * Generate a set of logarithmic ticks\n * @param generationOptions the options used to generate the ticks\n * @param dataRange the range of the data\n * @returns {object[]} array of tick objects\n */\nfunction generateTicks(generationOptions, {min, max}) {\n min = finiteOrDefault(generationOptions.min, min);\n const ticks = [];\n const minExp = log10Floor(min);\n let exp = startExp(min, max);\n let precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;\n const stepSize = Math.pow(10, exp);\n const base = minExp > exp ? Math.pow(10, minExp) : 0;\n const start = Math.round((min - base) * precision) / precision;\n const offset = Math.floor((min - base) / stepSize / 10) * stepSize * 10;\n let significand = Math.floor((start - offset) / Math.pow(10, exp));\n let value = finiteOrDefault(generationOptions.min, Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision);\n while (value < max) {\n ticks.push({value, major: isMajor(value), significand});\n if (significand >= 10) {\n significand = significand < 15 ? 15 : 20;\n } else {\n significand++;\n }\n if (significand >= 20) {\n exp++;\n significand = 2;\n precision = exp >= 0 ? 1 : precision;\n }\n value = Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision;\n }\n const lastTick = finiteOrDefault(generationOptions.max, value);\n ticks.push({value: lastTick, major: isMajor(lastTick), significand});\n\n return ticks;\n}\n\nexport default class LogarithmicScale extends Scale {\n\n static id = 'logarithmic';\n\n /**\n * @type {any}\n */\n static defaults = {\n ticks: {\n callback: Ticks.formatters.logarithmic,\n major: {\n enabled: true\n }\n }\n };\n\n\n constructor(cfg) {\n super(cfg);\n\n /** @type {number} */\n this.start = undefined;\n /** @type {number} */\n this.end = undefined;\n /** @type {number} */\n this._startValue = undefined;\n this._valueRange = 0;\n }\n\n parse(raw, index) {\n const value = LinearScaleBase.prototype.parse.apply(this, [raw, index]);\n if (value === 0) {\n this._zero = true;\n return undefined;\n }\n return isFinite(value) && value > 0 ? value : null;\n }\n\n determineDataLimits() {\n const {min, max} = this.getMinMax(true);\n\n this.min = isFinite(min) ? Math.max(0, min) : null;\n this.max = isFinite(max) ? Math.max(0, max) : null;\n\n if (this.options.beginAtZero) {\n this._zero = true;\n }\n\n // if data has `0` in it or `beginAtZero` is true, min (non zero) value is at bottom\n // of scale, and it does not equal suggestedMin, lower the min bound by one exp.\n if (this._zero && this.min !== this._suggestedMin && !isFinite(this._userMin)) {\n this.min = min === changeExponent(this.min, 0) ? changeExponent(this.min, -1) : changeExponent(this.min, 0);\n }\n\n this.handleTickRangeOptions();\n }\n\n handleTickRangeOptions() {\n const {minDefined, maxDefined} = this.getUserBounds();\n let min = this.min;\n let max = this.max;\n\n const setMin = v => (min = minDefined ? min : v);\n const setMax = v => (max = maxDefined ? max : v);\n\n if (min === max) {\n if (min <= 0) { // includes null\n setMin(1);\n setMax(10);\n } else {\n setMin(changeExponent(min, -1));\n setMax(changeExponent(max, +1));\n }\n }\n if (min <= 0) {\n setMin(changeExponent(max, -1));\n }\n if (max <= 0) {\n\n setMax(changeExponent(min, +1));\n }\n\n this.min = min;\n this.max = max;\n }\n\n buildTicks() {\n const opts = this.options;\n\n const generationOptions = {\n min: this._userMin,\n max: this._userMax\n };\n const ticks = generateTicks(generationOptions, this);\n\n // At this point, we need to update our max and min given the tick values,\n // since we probably have expanded the range of the scale\n if (opts.bounds === 'ticks') {\n _setMinAndMaxByKey(ticks, this, 'value');\n }\n\n if (opts.reverse) {\n ticks.reverse();\n\n this.start = this.max;\n this.end = this.min;\n } else {\n this.start = this.min;\n this.end = this.max;\n }\n\n return ticks;\n }\n\n /**\n\t * @param {number} value\n\t * @return {string}\n\t */\n getLabelForValue(value) {\n return value === undefined\n ? '0'\n : formatNumber(value, this.chart.options.locale, this.options.ticks.format);\n }\n\n /**\n\t * @protected\n\t */\n configure() {\n const start = this.min;\n\n super.configure();\n\n this._startValue = log10(start);\n this._valueRange = log10(this.max) - log10(start);\n }\n\n getPixelForValue(value) {\n if (value === undefined || value === 0) {\n value = this.min;\n }\n if (value === null || isNaN(value)) {\n return NaN;\n }\n return this.getPixelForDecimal(value === this.min\n ? 0\n : (log10(value) - this._startValue) / this._valueRange);\n }\n\n getValueForPixel(pixel) {\n const decimal = this.getDecimalForPixel(pixel);\n return Math.pow(10, this._startValue + decimal * this._valueRange);\n }\n}\n", "import defaults from '../core/core.defaults.js';\nimport {_longestText, addRoundedRectPath, renderText, _isPointInArea} from '../helpers/helpers.canvas.js';\nimport {HALF_PI, TAU, toDegrees, toRadians, _normalizeAngle, PI} from '../helpers/helpers.math.js';\nimport LinearScaleBase from './scale.linearbase.js';\nimport Ticks from '../core/core.ticks.js';\nimport {valueOrDefault, isArray, isFinite, callback as callCallback, isNullOrUndef} from '../helpers/helpers.core.js';\nimport {createContext, toFont, toPadding, toTRBLCorners} from '../helpers/helpers.options.js';\n\nfunction getTickBackdropHeight(opts) {\n const tickOpts = opts.ticks;\n\n if (tickOpts.display && opts.display) {\n const padding = toPadding(tickOpts.backdropPadding);\n return valueOrDefault(tickOpts.font && tickOpts.font.size, defaults.font.size) + padding.height;\n }\n return 0;\n}\n\nfunction measureLabelSize(ctx, font, label) {\n label = isArray(label) ? label : [label];\n return {\n w: _longestText(ctx, font.string, label),\n h: label.length * font.lineHeight\n };\n}\n\nfunction determineLimits(angle, pos, size, min, max) {\n if (angle === min || angle === max) {\n return {\n start: pos - (size / 2),\n end: pos + (size / 2)\n };\n } else if (angle < min || angle > max) {\n return {\n start: pos - size,\n end: pos\n };\n }\n\n return {\n start: pos,\n end: pos + size\n };\n}\n\n/**\n * Helper function to fit a radial linear scale with point labels\n */\nfunction fitWithPointLabels(scale) {\n\n // Right, this is really confusing and there is a lot of maths going on here\n // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9\n //\n // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif\n //\n // Solution:\n //\n // We assume the radius of the polygon is half the size of the canvas at first\n // at each index we check if the text overlaps.\n //\n // Where it does, we store that angle and that index.\n //\n // After finding the largest index and angle we calculate how much we need to remove\n // from the shape radius to move the point inwards by that x.\n //\n // We average the left and right distances to get the maximum shape radius that can fit in the box\n // along with labels.\n //\n // Once we have that, we can find the centre point for the chart, by taking the x text protrusion\n // on each side, removing that from the size, halving it and adding the left x protrusion width.\n //\n // This will mean we have a shape fitted to the canvas, as large as it can be with the labels\n // and position it in the most space efficient manner\n //\n // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif\n\n // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.\n // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points\n const orig = {\n l: scale.left + scale._padding.left,\n r: scale.right - scale._padding.right,\n t: scale.top + scale._padding.top,\n b: scale.bottom - scale._padding.bottom\n };\n const limits = Object.assign({}, orig);\n const labelSizes = [];\n const padding = [];\n const valueCount = scale._pointLabels.length;\n const pointLabelOpts = scale.options.pointLabels;\n const additionalAngle = pointLabelOpts.centerPointLabels ? PI / valueCount : 0;\n\n for (let i = 0; i < valueCount; i++) {\n const opts = pointLabelOpts.setContext(scale.getPointLabelContext(i));\n padding[i] = opts.padding;\n const pointPosition = scale.getPointPosition(i, scale.drawingArea + padding[i], additionalAngle);\n const plFont = toFont(opts.font);\n const textSize = measureLabelSize(scale.ctx, plFont, scale._pointLabels[i]);\n labelSizes[i] = textSize;\n\n const angleRadians = _normalizeAngle(scale.getIndexAngle(i) + additionalAngle);\n const angle = Math.round(toDegrees(angleRadians));\n const hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);\n const vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);\n updateLimits(limits, orig, angleRadians, hLimits, vLimits);\n }\n\n scale.setCenterPoint(\n orig.l - limits.l,\n limits.r - orig.r,\n orig.t - limits.t,\n limits.b - orig.b\n );\n\n // Now that text size is determined, compute the full positions\n scale._pointLabelItems = buildPointLabelItems(scale, labelSizes, padding);\n}\n\nfunction updateLimits(limits, orig, angle, hLimits, vLimits) {\n const sin = Math.abs(Math.sin(angle));\n const cos = Math.abs(Math.cos(angle));\n let x = 0;\n let y = 0;\n if (hLimits.start < orig.l) {\n x = (orig.l - hLimits.start) / sin;\n limits.l = Math.min(limits.l, orig.l - x);\n } else if (hLimits.end > orig.r) {\n x = (hLimits.end - orig.r) / sin;\n limits.r = Math.max(limits.r, orig.r + x);\n }\n if (vLimits.start < orig.t) {\n y = (orig.t - vLimits.start) / cos;\n limits.t = Math.min(limits.t, orig.t - y);\n } else if (vLimits.end > orig.b) {\n y = (vLimits.end - orig.b) / cos;\n limits.b = Math.max(limits.b, orig.b + y);\n }\n}\n\nfunction createPointLabelItem(scale, index, itemOpts) {\n const outerDistance = scale.drawingArea;\n const {extra, additionalAngle, padding, size} = itemOpts;\n const pointLabelPosition = scale.getPointPosition(index, outerDistance + extra + padding, additionalAngle);\n const angle = Math.round(toDegrees(_normalizeAngle(pointLabelPosition.angle + HALF_PI)));\n const y = yForAngle(pointLabelPosition.y, size.h, angle);\n const textAlign = getTextAlignForAngle(angle);\n const left = leftForTextAlign(pointLabelPosition.x, size.w, textAlign);\n return {\n // if to draw or overlapped\n visible: true,\n\n // Text position\n x: pointLabelPosition.x,\n y,\n\n // Text rendering data\n textAlign,\n\n // Bounding box\n left,\n top: y,\n right: left + size.w,\n bottom: y + size.h\n };\n}\n\nfunction isNotOverlapped(item, area) {\n if (!area) {\n return true;\n }\n const {left, top, right, bottom} = item;\n const apexesInArea = _isPointInArea({x: left, y: top}, area) || _isPointInArea({x: left, y: bottom}, area) ||\n _isPointInArea({x: right, y: top}, area) || _isPointInArea({x: right, y: bottom}, area);\n return !apexesInArea;\n}\n\nfunction buildPointLabelItems(scale, labelSizes, padding) {\n const items = [];\n const valueCount = scale._pointLabels.length;\n const opts = scale.options;\n const {centerPointLabels, display} = opts.pointLabels;\n const itemOpts = {\n extra: getTickBackdropHeight(opts) / 2,\n additionalAngle: centerPointLabels ? PI / valueCount : 0\n };\n let area;\n\n for (let i = 0; i < valueCount; i++) {\n itemOpts.padding = padding[i];\n itemOpts.size = labelSizes[i];\n\n const item = createPointLabelItem(scale, i, itemOpts);\n items.push(item);\n if (display === 'auto') {\n item.visible = isNotOverlapped(item, area);\n if (item.visible) {\n area = item;\n }\n }\n }\n return items;\n}\n\nfunction getTextAlignForAngle(angle) {\n if (angle === 0 || angle === 180) {\n return 'center';\n } else if (angle < 180) {\n return 'left';\n }\n\n return 'right';\n}\n\nfunction leftForTextAlign(x, w, align) {\n if (align === 'right') {\n x -= w;\n } else if (align === 'center') {\n x -= (w / 2);\n }\n return x;\n}\n\nfunction yForAngle(y, h, angle) {\n if (angle === 90 || angle === 270) {\n y -= (h / 2);\n } else if (angle > 270 || angle < 90) {\n y -= h;\n }\n return y;\n}\n\nfunction drawPointLabelBox(ctx, opts, item) {\n const {left, top, right, bottom} = item;\n const {backdropColor} = opts;\n\n if (!isNullOrUndef(backdropColor)) {\n const borderRadius = toTRBLCorners(opts.borderRadius);\n const padding = toPadding(opts.backdropPadding);\n ctx.fillStyle = backdropColor;\n\n const backdropLeft = left - padding.left;\n const backdropTop = top - padding.top;\n const backdropWidth = right - left + padding.width;\n const backdropHeight = bottom - top + padding.height;\n\n if (Object.values(borderRadius).some(v => v !== 0)) {\n ctx.beginPath();\n addRoundedRectPath(ctx, {\n x: backdropLeft,\n y: backdropTop,\n w: backdropWidth,\n h: backdropHeight,\n radius: borderRadius,\n });\n ctx.fill();\n } else {\n ctx.fillRect(backdropLeft, backdropTop, backdropWidth, backdropHeight);\n }\n }\n}\n\nfunction drawPointLabels(scale, labelCount) {\n const {ctx, options: {pointLabels}} = scale;\n\n for (let i = labelCount - 1; i >= 0; i--) {\n const item = scale._pointLabelItems[i];\n if (!item.visible) {\n // overlapping\n continue;\n }\n const optsAtIndex = pointLabels.setContext(scale.getPointLabelContext(i));\n drawPointLabelBox(ctx, optsAtIndex, item);\n const plFont = toFont(optsAtIndex.font);\n const {x, y, textAlign} = item;\n\n renderText(\n ctx,\n scale._pointLabels[i],\n x,\n y + (plFont.lineHeight / 2),\n plFont,\n {\n color: optsAtIndex.color,\n textAlign: textAlign,\n textBaseline: 'middle'\n }\n );\n }\n}\n\nfunction pathRadiusLine(scale, radius, circular, labelCount) {\n const {ctx} = scale;\n if (circular) {\n // Draw circular arcs between the points\n ctx.arc(scale.xCenter, scale.yCenter, radius, 0, TAU);\n } else {\n // Draw straight lines connecting each index\n let pointPosition = scale.getPointPosition(0, radius);\n ctx.moveTo(pointPosition.x, pointPosition.y);\n\n for (let i = 1; i < labelCount; i++) {\n pointPosition = scale.getPointPosition(i, radius);\n ctx.lineTo(pointPosition.x, pointPosition.y);\n }\n }\n}\n\nfunction drawRadiusLine(scale, gridLineOpts, radius, labelCount, borderOpts) {\n const ctx = scale.ctx;\n const circular = gridLineOpts.circular;\n\n const {color, lineWidth} = gridLineOpts;\n\n if ((!circular && !labelCount) || !color || !lineWidth || radius < 0) {\n return;\n }\n\n ctx.save();\n ctx.strokeStyle = color;\n ctx.lineWidth = lineWidth;\n ctx.setLineDash(borderOpts.dash);\n ctx.lineDashOffset = borderOpts.dashOffset;\n\n ctx.beginPath();\n pathRadiusLine(scale, radius, circular, labelCount);\n ctx.closePath();\n ctx.stroke();\n ctx.restore();\n}\n\nfunction createPointLabelContext(parent, index, label) {\n return createContext(parent, {\n label,\n index,\n type: 'pointLabel'\n });\n}\n\nexport default class RadialLinearScale extends LinearScaleBase {\n\n static id = 'radialLinear';\n\n /**\n * @type {any}\n */\n static defaults = {\n display: true,\n\n // Boolean - Whether to animate scaling the chart from the centre\n animate: true,\n position: 'chartArea',\n\n angleLines: {\n display: true,\n lineWidth: 1,\n borderDash: [],\n borderDashOffset: 0.0\n },\n\n grid: {\n circular: false\n },\n\n startAngle: 0,\n\n // label settings\n ticks: {\n // Boolean - Show a backdrop to the scale label\n showLabelBackdrop: true,\n\n callback: Ticks.formatters.numeric\n },\n\n pointLabels: {\n backdropColor: undefined,\n\n // Number - The backdrop padding above & below the label in pixels\n backdropPadding: 2,\n\n // Boolean - if true, show point labels\n display: true,\n\n // Number - Point label font size in pixels\n font: {\n size: 10\n },\n\n // Function - Used to convert point labels\n callback(label) {\n return label;\n },\n\n // Number - Additionl padding between scale and pointLabel\n padding: 5,\n\n // Boolean - if true, center point labels to slices in polar chart\n centerPointLabels: false\n }\n };\n\n static defaultRoutes = {\n 'angleLines.color': 'borderColor',\n 'pointLabels.color': 'color',\n 'ticks.color': 'color'\n };\n\n static descriptors = {\n angleLines: {\n _fallback: 'grid'\n }\n };\n\n constructor(cfg) {\n super(cfg);\n\n /** @type {number} */\n this.xCenter = undefined;\n /** @type {number} */\n this.yCenter = undefined;\n /** @type {number} */\n this.drawingArea = undefined;\n /** @type {string[]} */\n this._pointLabels = [];\n this._pointLabelItems = [];\n }\n\n setDimensions() {\n // Set the unconstrained dimension before label rotation\n const padding = this._padding = toPadding(getTickBackdropHeight(this.options) / 2);\n const w = this.width = this.maxWidth - padding.width;\n const h = this.height = this.maxHeight - padding.height;\n this.xCenter = Math.floor(this.left + w / 2 + padding.left);\n this.yCenter = Math.floor(this.top + h / 2 + padding.top);\n this.drawingArea = Math.floor(Math.min(w, h) / 2);\n }\n\n determineDataLimits() {\n const {min, max} = this.getMinMax(false);\n\n this.min = isFinite(min) && !isNaN(min) ? min : 0;\n this.max = isFinite(max) && !isNaN(max) ? max : 0;\n\n // Common base implementation to handle min, max, beginAtZero\n this.handleTickRangeOptions();\n }\n\n /**\n\t * Returns the maximum number of ticks based on the scale dimension\n\t * @protected\n\t */\n computeTickLimit() {\n return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));\n }\n\n generateTickLabels(ticks) {\n LinearScaleBase.prototype.generateTickLabels.call(this, ticks);\n\n // Point labels\n this._pointLabels = this.getLabels()\n .map((value, index) => {\n const label = callCallback(this.options.pointLabels.callback, [value, index], this);\n return label || label === 0 ? label : '';\n })\n .filter((v, i) => this.chart.getDataVisibility(i));\n }\n\n fit() {\n const opts = this.options;\n\n if (opts.display && opts.pointLabels.display) {\n fitWithPointLabels(this);\n } else {\n this.setCenterPoint(0, 0, 0, 0);\n }\n }\n\n setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) {\n this.xCenter += Math.floor((leftMovement - rightMovement) / 2);\n this.yCenter += Math.floor((topMovement - bottomMovement) / 2);\n this.drawingArea -= Math.min(this.drawingArea / 2, Math.max(leftMovement, rightMovement, topMovement, bottomMovement));\n }\n\n getIndexAngle(index) {\n const angleMultiplier = TAU / (this._pointLabels.length || 1);\n const startAngle = this.options.startAngle || 0;\n\n return _normalizeAngle(index * angleMultiplier + toRadians(startAngle));\n }\n\n getDistanceFromCenterForValue(value) {\n if (isNullOrUndef(value)) {\n return NaN;\n }\n\n // Take into account half font size + the yPadding of the top value\n const scalingFactor = this.drawingArea / (this.max - this.min);\n if (this.options.reverse) {\n return (this.max - value) * scalingFactor;\n }\n return (value - this.min) * scalingFactor;\n }\n\n getValueForDistanceFromCenter(distance) {\n if (isNullOrUndef(distance)) {\n return NaN;\n }\n\n const scaledDistance = distance / (this.drawingArea / (this.max - this.min));\n return this.options.reverse ? this.max - scaledDistance : this.min + scaledDistance;\n }\n\n getPointLabelContext(index) {\n const pointLabels = this._pointLabels || [];\n\n if (index >= 0 && index < pointLabels.length) {\n const pointLabel = pointLabels[index];\n return createPointLabelContext(this.getContext(), index, pointLabel);\n }\n }\n\n getPointPosition(index, distanceFromCenter, additionalAngle = 0) {\n const angle = this.getIndexAngle(index) - HALF_PI + additionalAngle;\n return {\n x: Math.cos(angle) * distanceFromCenter + this.xCenter,\n y: Math.sin(angle) * distanceFromCenter + this.yCenter,\n angle\n };\n }\n\n getPointPositionForValue(index, value) {\n return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));\n }\n\n getBasePosition(index) {\n return this.getPointPositionForValue(index || 0, this.getBaseValue());\n }\n\n getPointLabelPosition(index) {\n const {left, top, right, bottom} = this._pointLabelItems[index];\n return {\n left,\n top,\n right,\n bottom,\n };\n }\n\n /**\n\t * @protected\n\t */\n drawBackground() {\n const {backgroundColor, grid: {circular}} = this.options;\n if (backgroundColor) {\n const ctx = this.ctx;\n ctx.save();\n ctx.beginPath();\n pathRadiusLine(this, this.getDistanceFromCenterForValue(this._endValue), circular, this._pointLabels.length);\n ctx.closePath();\n ctx.fillStyle = backgroundColor;\n ctx.fill();\n ctx.restore();\n }\n }\n\n /**\n\t * @protected\n\t */\n drawGrid() {\n const ctx = this.ctx;\n const opts = this.options;\n const {angleLines, grid, border} = opts;\n const labelCount = this._pointLabels.length;\n\n let i, offset, position;\n\n if (opts.pointLabels.display) {\n drawPointLabels(this, labelCount);\n }\n\n if (grid.display) {\n this.ticks.forEach((tick, index) => {\n if (index !== 0 || (index === 0 && this.min < 0)) {\n offset = this.getDistanceFromCenterForValue(tick.value);\n const context = this.getContext(index);\n const optsAtIndex = grid.setContext(context);\n const optsAtIndexBorder = border.setContext(context);\n\n drawRadiusLine(this, optsAtIndex, offset, labelCount, optsAtIndexBorder);\n }\n });\n }\n\n if (angleLines.display) {\n ctx.save();\n\n for (i = labelCount - 1; i >= 0; i--) {\n const optsAtIndex = angleLines.setContext(this.getPointLabelContext(i));\n const {color, lineWidth} = optsAtIndex;\n\n if (!lineWidth || !color) {\n continue;\n }\n\n ctx.lineWidth = lineWidth;\n ctx.strokeStyle = color;\n\n ctx.setLineDash(optsAtIndex.borderDash);\n ctx.lineDashOffset = optsAtIndex.borderDashOffset;\n\n offset = this.getDistanceFromCenterForValue(opts.ticks.reverse ? this.min : this.max);\n position = this.getPointPosition(i, offset);\n ctx.beginPath();\n ctx.moveTo(this.xCenter, this.yCenter);\n ctx.lineTo(position.x, position.y);\n ctx.stroke();\n }\n\n ctx.restore();\n }\n }\n\n /**\n\t * @protected\n\t */\n drawBorder() {}\n\n /**\n\t * @protected\n\t */\n drawLabels() {\n const ctx = this.ctx;\n const opts = this.options;\n const tickOpts = opts.ticks;\n\n if (!tickOpts.display) {\n return;\n }\n\n const startAngle = this.getIndexAngle(0);\n let offset, width;\n\n ctx.save();\n ctx.translate(this.xCenter, this.yCenter);\n ctx.rotate(startAngle);\n ctx.textAlign = 'center';\n ctx.textBaseline = 'middle';\n\n this.ticks.forEach((tick, index) => {\n if ((index === 0 && this.min >= 0) && !opts.reverse) {\n return;\n }\n\n const optsAtIndex = tickOpts.setContext(this.getContext(index));\n const tickFont = toFont(optsAtIndex.font);\n offset = this.getDistanceFromCenterForValue(this.ticks[index].value);\n\n if (optsAtIndex.showLabelBackdrop) {\n ctx.font = tickFont.string;\n width = ctx.measureText(tick.label).width;\n ctx.fillStyle = optsAtIndex.backdropColor;\n\n const padding = toPadding(optsAtIndex.backdropPadding);\n ctx.fillRect(\n -width / 2 - padding.left,\n -offset - tickFont.size / 2 - padding.top,\n width + padding.width,\n tickFont.size + padding.height\n );\n }\n\n renderText(ctx, tick.label, 0, -offset, tickFont, {\n color: optsAtIndex.color,\n strokeColor: optsAtIndex.textStrokeColor,\n strokeWidth: optsAtIndex.textStrokeWidth,\n });\n });\n\n ctx.restore();\n }\n\n /**\n\t * @protected\n\t */\n drawTitle() {}\n}\n", "import adapters from '../core/core.adapters.js';\nimport {callback as call, isFinite, isNullOrUndef, mergeIf, valueOrDefault} from '../helpers/helpers.core.js';\nimport {toRadians, isNumber, _limitValue} from '../helpers/helpers.math.js';\nimport Scale from '../core/core.scale.js';\nimport {_arrayUnique, _filterBetween, _lookup} from '../helpers/helpers.collection.js';\n\n/**\n * @typedef { import('../core/core.adapters.js').TimeUnit } Unit\n * @typedef {{common: boolean, size: number, steps?: number}} Interval\n * @typedef { import('../core/core.adapters.js').DateAdapter } DateAdapter\n */\n\n/**\n * @type {Object}\n */\nconst INTERVALS = {\n millisecond: {common: true, size: 1, steps: 1000},\n second: {common: true, size: 1000, steps: 60},\n minute: {common: true, size: 60000, steps: 60},\n hour: {common: true, size: 3600000, steps: 24},\n day: {common: true, size: 86400000, steps: 30},\n week: {common: false, size: 604800000, steps: 4},\n month: {common: true, size: 2.628e9, steps: 12},\n quarter: {common: false, size: 7.884e9, steps: 4},\n year: {common: true, size: 3.154e10}\n};\n\n/**\n * @type {Unit[]}\n */\nconst UNITS = /** @type Unit[] */ /* #__PURE__ */ (Object.keys(INTERVALS));\n\n/**\n * @param {number} a\n * @param {number} b\n */\nfunction sorter(a, b) {\n return a - b;\n}\n\n/**\n * @param {TimeScale} scale\n * @param {*} input\n * @return {number}\n */\nfunction parse(scale, input) {\n if (isNullOrUndef(input)) {\n return null;\n }\n\n const adapter = scale._adapter;\n const {parser, round, isoWeekday} = scale._parseOpts;\n let value = input;\n\n if (typeof parser === 'function') {\n value = parser(value);\n }\n\n // Only parse if it's not a timestamp already\n if (!isFinite(value)) {\n value = typeof parser === 'string'\n ? adapter.parse(value, /** @type {Unit} */ (parser))\n : adapter.parse(value);\n }\n\n if (value === null) {\n return null;\n }\n\n if (round) {\n value = round === 'week' && (isNumber(isoWeekday) || isoWeekday === true)\n ? adapter.startOf(value, 'isoWeek', isoWeekday)\n : adapter.startOf(value, round);\n }\n\n return +value;\n}\n\n/**\n * Figures out what unit results in an appropriate number of auto-generated ticks\n * @param {Unit} minUnit\n * @param {number} min\n * @param {number} max\n * @param {number} capacity\n * @return {object}\n */\nfunction determineUnitForAutoTicks(minUnit, min, max, capacity) {\n const ilen = UNITS.length;\n\n for (let i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {\n const interval = INTERVALS[UNITS[i]];\n const factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER;\n\n if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {\n return UNITS[i];\n }\n }\n\n return UNITS[ilen - 1];\n}\n\n/**\n * Figures out what unit to format a set of ticks with\n * @param {TimeScale} scale\n * @param {number} numTicks\n * @param {Unit} minUnit\n * @param {number} min\n * @param {number} max\n * @return {Unit}\n */\nfunction determineUnitForFormatting(scale, numTicks, minUnit, min, max) {\n for (let i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {\n const unit = UNITS[i];\n if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {\n return unit;\n }\n }\n\n return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];\n}\n\n/**\n * @param {Unit} unit\n * @return {object}\n */\nfunction determineMajorUnit(unit) {\n for (let i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {\n if (INTERVALS[UNITS[i]].common) {\n return UNITS[i];\n }\n }\n}\n\n/**\n * @param {object} ticks\n * @param {number} time\n * @param {number[]} [timestamps] - if defined, snap to these timestamps\n */\nfunction addTick(ticks, time, timestamps) {\n if (!timestamps) {\n ticks[time] = true;\n } else if (timestamps.length) {\n const {lo, hi} = _lookup(timestamps, time);\n const timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi];\n ticks[timestamp] = true;\n }\n}\n\n/**\n * @param {TimeScale} scale\n * @param {object[]} ticks\n * @param {object} map\n * @param {Unit} majorUnit\n * @return {object[]}\n */\nfunction setMajorTicks(scale, ticks, map, majorUnit) {\n const adapter = scale._adapter;\n const first = +adapter.startOf(ticks[0].value, majorUnit);\n const last = ticks[ticks.length - 1].value;\n let major, index;\n\n for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {\n index = map[major];\n if (index >= 0) {\n ticks[index].major = true;\n }\n }\n return ticks;\n}\n\n/**\n * @param {TimeScale} scale\n * @param {number[]} values\n * @param {Unit|undefined} [majorUnit]\n * @return {object[]}\n */\nfunction ticksFromTimestamps(scale, values, majorUnit) {\n const ticks = [];\n /** @type {Object} */\n const map = {};\n const ilen = values.length;\n let i, value;\n\n for (i = 0; i < ilen; ++i) {\n value = values[i];\n map[value] = i;\n\n ticks.push({\n value,\n major: false\n });\n }\n\n // We set the major ticks separately from the above loop because calling startOf for every tick\n // is expensive when there is a large number of ticks\n return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit);\n}\n\nexport default class TimeScale extends Scale {\n\n static id = 'time';\n\n /**\n * @type {any}\n */\n static defaults = {\n /**\n * Scale boundary strategy (bypassed by min/max time options)\n * - `data`: make sure data are fully visible, ticks outside are removed\n * - `ticks`: make sure ticks are fully visible, data outside are truncated\n * @see https://github.com/chartjs/Chart.js/pull/4556\n * @since 2.7.0\n */\n bounds: 'data',\n\n adapters: {},\n time: {\n parser: false, // false == a pattern string from or a custom callback that converts its argument to a timestamp\n unit: false, // false == automatic or override with week, month, year, etc.\n round: false, // none, or override with week, month, year, etc.\n isoWeekday: false, // override week start day\n minUnit: 'millisecond',\n displayFormats: {}\n },\n ticks: {\n /**\n * Ticks generation input values:\n * - 'auto': generates \"optimal\" ticks based on scale size and time options.\n * - 'data': generates ticks from data (including labels from data {t|x|y} objects).\n * - 'labels': generates ticks from user given `data.labels` values ONLY.\n * @see https://github.com/chartjs/Chart.js/pull/4507\n * @since 2.7.0\n */\n source: 'auto',\n\n callback: false,\n\n major: {\n enabled: false\n }\n }\n };\n\n /**\n\t * @param {object} props\n\t */\n constructor(props) {\n super(props);\n\n /** @type {{data: number[], labels: number[], all: number[]}} */\n this._cache = {\n data: [],\n labels: [],\n all: []\n };\n\n /** @type {Unit} */\n this._unit = 'day';\n /** @type {Unit=} */\n this._majorUnit = undefined;\n this._offsets = {};\n this._normalized = false;\n this._parseOpts = undefined;\n }\n\n init(scaleOpts, opts = {}) {\n const time = scaleOpts.time || (scaleOpts.time = {});\n /** @type {DateAdapter} */\n const adapter = this._adapter = new adapters._date(scaleOpts.adapters.date);\n\n adapter.init(opts);\n\n // Backward compatibility: before introducing adapter, `displayFormats` was\n // supposed to contain *all* unit/string pairs but this can't be resolved\n // when loading the scale (adapters are loaded afterward), so let's populate\n // missing formats on update\n mergeIf(time.displayFormats, adapter.formats());\n\n this._parseOpts = {\n parser: time.parser,\n round: time.round,\n isoWeekday: time.isoWeekday\n };\n\n super.init(scaleOpts);\n\n this._normalized = opts.normalized;\n }\n\n /**\n\t * @param {*} raw\n\t * @param {number?} [index]\n\t * @return {number}\n\t */\n parse(raw, index) { // eslint-disable-line no-unused-vars\n if (raw === undefined) {\n return null;\n }\n return parse(this, raw);\n }\n\n beforeLayout() {\n super.beforeLayout();\n this._cache = {\n data: [],\n labels: [],\n all: []\n };\n }\n\n determineDataLimits() {\n const options = this.options;\n const adapter = this._adapter;\n const unit = options.time.unit || 'day';\n // eslint-disable-next-line prefer-const\n let {min, max, minDefined, maxDefined} = this.getUserBounds();\n\n /**\n\t\t * @param {object} bounds\n\t\t */\n function _applyBounds(bounds) {\n if (!minDefined && !isNaN(bounds.min)) {\n min = Math.min(min, bounds.min);\n }\n if (!maxDefined && !isNaN(bounds.max)) {\n max = Math.max(max, bounds.max);\n }\n }\n\n // If we have user provided `min` and `max` labels / data bounds can be ignored\n if (!minDefined || !maxDefined) {\n // Labels are always considered, when user did not force bounds\n _applyBounds(this._getLabelBounds());\n\n // If `bounds` is `'ticks'` and `ticks.source` is `'labels'`,\n // data bounds are ignored (and don't need to be determined)\n if (options.bounds !== 'ticks' || options.ticks.source !== 'labels') {\n _applyBounds(this.getMinMax(false));\n }\n }\n\n min = isFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit);\n max = isFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1;\n\n // Make sure that max is strictly higher than min (required by the timeseries lookup table)\n this.min = Math.min(min, max - 1);\n this.max = Math.max(min + 1, max);\n }\n\n /**\n\t * @private\n\t */\n _getLabelBounds() {\n const arr = this.getLabelTimestamps();\n let min = Number.POSITIVE_INFINITY;\n let max = Number.NEGATIVE_INFINITY;\n\n if (arr.length) {\n min = arr[0];\n max = arr[arr.length - 1];\n }\n return {min, max};\n }\n\n /**\n\t * @return {object[]}\n\t */\n buildTicks() {\n const options = this.options;\n const timeOpts = options.time;\n const tickOpts = options.ticks;\n const timestamps = tickOpts.source === 'labels' ? this.getLabelTimestamps() : this._generate();\n\n if (options.bounds === 'ticks' && timestamps.length) {\n this.min = this._userMin || timestamps[0];\n this.max = this._userMax || timestamps[timestamps.length - 1];\n }\n\n const min = this.min;\n const max = this.max;\n\n const ticks = _filterBetween(timestamps, min, max);\n\n // PRIVATE\n // determineUnitForFormatting relies on the number of ticks so we don't use it when\n // autoSkip is enabled because we don't yet know what the final number of ticks will be\n this._unit = timeOpts.unit || (tickOpts.autoSkip\n ? determineUnitForAutoTicks(timeOpts.minUnit, this.min, this.max, this._getLabelCapacity(min))\n : determineUnitForFormatting(this, ticks.length, timeOpts.minUnit, this.min, this.max));\n this._majorUnit = !tickOpts.major.enabled || this._unit === 'year' ? undefined\n : determineMajorUnit(this._unit);\n this.initOffsets(timestamps);\n\n if (options.reverse) {\n ticks.reverse();\n }\n\n return ticksFromTimestamps(this, ticks, this._majorUnit);\n }\n\n afterAutoSkip() {\n // Offsets for bar charts need to be handled with the auto skipped\n // ticks. Once ticks have been skipped, we re-compute the offsets.\n if (this.options.offsetAfterAutoskip) {\n this.initOffsets(this.ticks.map(tick => +tick.value));\n }\n }\n\n /**\n\t * Returns the start and end offsets from edges in the form of {start, end}\n\t * where each value is a relative width to the scale and ranges between 0 and 1.\n\t * They add extra margins on the both sides by scaling down the original scale.\n\t * Offsets are added when the `offset` option is true.\n\t * @param {number[]} timestamps\n\t * @protected\n\t */\n initOffsets(timestamps = []) {\n let start = 0;\n let end = 0;\n let first, last;\n\n if (this.options.offset && timestamps.length) {\n first = this.getDecimalForValue(timestamps[0]);\n if (timestamps.length === 1) {\n start = 1 - first;\n } else {\n start = (this.getDecimalForValue(timestamps[1]) - first) / 2;\n }\n last = this.getDecimalForValue(timestamps[timestamps.length - 1]);\n if (timestamps.length === 1) {\n end = last;\n } else {\n end = (last - this.getDecimalForValue(timestamps[timestamps.length - 2])) / 2;\n }\n }\n const limit = timestamps.length < 3 ? 0.5 : 0.25;\n start = _limitValue(start, 0, limit);\n end = _limitValue(end, 0, limit);\n\n this._offsets = {start, end, factor: 1 / (start + 1 + end)};\n }\n\n /**\n\t * Generates a maximum of `capacity` timestamps between min and max, rounded to the\n\t * `minor` unit using the given scale time `options`.\n\t * Important: this method can return ticks outside the min and max range, it's the\n\t * responsibility of the calling code to clamp values if needed.\n\t * @protected\n\t */\n _generate() {\n const adapter = this._adapter;\n const min = this.min;\n const max = this.max;\n const options = this.options;\n const timeOpts = options.time;\n // @ts-ignore\n const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, this._getLabelCapacity(min));\n const stepSize = valueOrDefault(options.ticks.stepSize, 1);\n const weekday = minor === 'week' ? timeOpts.isoWeekday : false;\n const hasWeekday = isNumber(weekday) || weekday === true;\n const ticks = {};\n let first = min;\n let time, count;\n\n // For 'week' unit, handle the first day of week option\n if (hasWeekday) {\n first = +adapter.startOf(first, 'isoWeek', weekday);\n }\n\n // Align first ticks on unit\n first = +adapter.startOf(first, hasWeekday ? 'day' : minor);\n\n // Prevent browser from freezing in case user options request millions of milliseconds\n if (adapter.diff(max, min, minor) > 100000 * stepSize) {\n throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor);\n }\n\n const timestamps = options.ticks.source === 'data' && this.getDataTimestamps();\n for (time = first, count = 0; time < max; time = +adapter.add(time, stepSize, minor), count++) {\n addTick(ticks, time, timestamps);\n }\n\n if (time === max || options.bounds === 'ticks' || count === 1) {\n addTick(ticks, time, timestamps);\n }\n\n // @ts-ignore\n return Object.keys(ticks).sort(sorter).map(x => +x);\n }\n\n /**\n\t * @param {number} value\n\t * @return {string}\n\t */\n getLabelForValue(value) {\n const adapter = this._adapter;\n const timeOpts = this.options.time;\n\n if (timeOpts.tooltipFormat) {\n return adapter.format(value, timeOpts.tooltipFormat);\n }\n return adapter.format(value, timeOpts.displayFormats.datetime);\n }\n\n /**\n\t * @param {number} value\n\t * @param {string|undefined} format\n\t * @return {string}\n\t */\n format(value, format) {\n const options = this.options;\n const formats = options.time.displayFormats;\n const unit = this._unit;\n const fmt = format || formats[unit];\n return this._adapter.format(value, fmt);\n }\n\n /**\n\t * Function to format an individual tick mark\n\t * @param {number} time\n\t * @param {number} index\n\t * @param {object[]} ticks\n\t * @param {string|undefined} [format]\n\t * @return {string}\n\t * @private\n\t */\n _tickFormatFunction(time, index, ticks, format) {\n const options = this.options;\n const formatter = options.ticks.callback;\n\n if (formatter) {\n return call(formatter, [time, index, ticks], this);\n }\n\n const formats = options.time.displayFormats;\n const unit = this._unit;\n const majorUnit = this._majorUnit;\n const minorFormat = unit && formats[unit];\n const majorFormat = majorUnit && formats[majorUnit];\n const tick = ticks[index];\n const major = majorUnit && majorFormat && tick && tick.major;\n\n return this._adapter.format(time, format || (major ? majorFormat : minorFormat));\n }\n\n /**\n\t * @param {object[]} ticks\n\t */\n generateTickLabels(ticks) {\n let i, ilen, tick;\n\n for (i = 0, ilen = ticks.length; i < ilen; ++i) {\n tick = ticks[i];\n tick.label = this._tickFormatFunction(tick.value, i, ticks);\n }\n }\n\n /**\n\t * @param {number} value - Milliseconds since epoch (1 January 1970 00:00:00 UTC)\n\t * @return {number}\n\t */\n getDecimalForValue(value) {\n return value === null ? NaN : (value - this.min) / (this.max - this.min);\n }\n\n /**\n\t * @param {number} value - Milliseconds since epoch (1 January 1970 00:00:00 UTC)\n\t * @return {number}\n\t */\n getPixelForValue(value) {\n const offsets = this._offsets;\n const pos = this.getDecimalForValue(value);\n return this.getPixelForDecimal((offsets.start + pos) * offsets.factor);\n }\n\n /**\n\t * @param {number} pixel\n\t * @return {number}\n\t */\n getValueForPixel(pixel) {\n const offsets = this._offsets;\n const pos = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end;\n return this.min + pos * (this.max - this.min);\n }\n\n /**\n\t * @param {string} label\n\t * @return {{w:number, h:number}}\n\t * @private\n\t */\n _getLabelSize(label) {\n const ticksOpts = this.options.ticks;\n const tickLabelWidth = this.ctx.measureText(label).width;\n const angle = toRadians(this.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);\n const cosRotation = Math.cos(angle);\n const sinRotation = Math.sin(angle);\n const tickFontSize = this._resolveTickFontOptions(0).size;\n\n return {\n w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation),\n h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation)\n };\n }\n\n /**\n\t * @param {number} exampleTime\n\t * @return {number}\n\t * @private\n\t */\n _getLabelCapacity(exampleTime) {\n const timeOpts = this.options.time;\n const displayFormats = timeOpts.displayFormats;\n\n // pick the longest format (milliseconds) for guesstimation\n const format = displayFormats[timeOpts.unit] || displayFormats.millisecond;\n const exampleLabel = this._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(this, [exampleTime], this._majorUnit), format);\n const size = this._getLabelSize(exampleLabel);\n // subtract 1 - if offset then there's one less label than tick\n // if not offset then one half label padding is added to each end leaving room for one less label\n const capacity = Math.floor(this.isHorizontal() ? this.width / size.w : this.height / size.h) - 1;\n return capacity > 0 ? capacity : 1;\n }\n\n /**\n\t * @protected\n\t */\n getDataTimestamps() {\n let timestamps = this._cache.data || [];\n let i, ilen;\n\n if (timestamps.length) {\n return timestamps;\n }\n\n const metas = this.getMatchingVisibleMetas();\n\n if (this._normalized && metas.length) {\n return (this._cache.data = metas[0].controller.getAllParsedValues(this));\n }\n\n for (i = 0, ilen = metas.length; i < ilen; ++i) {\n timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(this));\n }\n\n return (this._cache.data = this.normalize(timestamps));\n }\n\n /**\n\t * @protected\n\t */\n getLabelTimestamps() {\n const timestamps = this._cache.labels || [];\n let i, ilen;\n\n if (timestamps.length) {\n return timestamps;\n }\n\n const labels = this.getLabels();\n for (i = 0, ilen = labels.length; i < ilen; ++i) {\n timestamps.push(parse(this, labels[i]));\n }\n\n return (this._cache.labels = this._normalized ? timestamps : this.normalize(timestamps));\n }\n\n /**\n\t * @param {number[]} values\n\t * @protected\n\t */\n normalize(values) {\n // It seems to be somewhat faster to do sorting first\n return _arrayUnique(values.sort(sorter));\n }\n}\n", "import TimeScale from './scale.time.js';\nimport {_lookupByKey} from '../helpers/helpers.collection.js';\n\n/**\n * Linearly interpolates the given source `val` using the table. If value is out of bounds, values\n * at edges are used for the interpolation.\n * @param {object} table\n * @param {number} val\n * @param {boolean} [reverse] lookup time based on position instead of vice versa\n * @return {object}\n */\nfunction interpolate(table, val, reverse) {\n let lo = 0;\n let hi = table.length - 1;\n let prevSource, nextSource, prevTarget, nextTarget;\n if (reverse) {\n if (val >= table[lo].pos && val <= table[hi].pos) {\n ({lo, hi} = _lookupByKey(table, 'pos', val));\n }\n ({pos: prevSource, time: prevTarget} = table[lo]);\n ({pos: nextSource, time: nextTarget} = table[hi]);\n } else {\n if (val >= table[lo].time && val <= table[hi].time) {\n ({lo, hi} = _lookupByKey(table, 'time', val));\n }\n ({time: prevSource, pos: prevTarget} = table[lo]);\n ({time: nextSource, pos: nextTarget} = table[hi]);\n }\n\n const span = nextSource - prevSource;\n return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget;\n}\n\nclass TimeSeriesScale extends TimeScale {\n\n static id = 'timeseries';\n\n /**\n * @type {any}\n */\n static defaults = TimeScale.defaults;\n\n /**\n\t * @param {object} props\n\t */\n constructor(props) {\n super(props);\n\n /** @type {object[]} */\n this._table = [];\n /** @type {number} */\n this._minPos = undefined;\n /** @type {number} */\n this._tableRange = undefined;\n }\n\n /**\n\t * @protected\n\t */\n initOffsets() {\n const timestamps = this._getTimestampsForTable();\n const table = this._table = this.buildLookupTable(timestamps);\n this._minPos = interpolate(table, this.min);\n this._tableRange = interpolate(table, this.max) - this._minPos;\n super.initOffsets(timestamps);\n }\n\n /**\n\t * Returns an array of {time, pos} objects used to interpolate a specific `time` or position\n\t * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is\n\t * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other\n\t * extremity (left + width or top + height). Note that it would be more optimized to directly\n\t * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need\n\t * to create the lookup table. The table ALWAYS contains at least two items: min and max.\n\t * @param {number[]} timestamps\n\t * @return {object[]}\n\t * @protected\n\t */\n buildLookupTable(timestamps) {\n const {min, max} = this;\n const items = [];\n const table = [];\n let i, ilen, prev, curr, next;\n\n for (i = 0, ilen = timestamps.length; i < ilen; ++i) {\n curr = timestamps[i];\n if (curr >= min && curr <= max) {\n items.push(curr);\n }\n }\n\n if (items.length < 2) {\n // In case there is less that 2 timestamps between min and max, the scale is defined by min and max\n return [\n {time: min, pos: 0},\n {time: max, pos: 1}\n ];\n }\n\n for (i = 0, ilen = items.length; i < ilen; ++i) {\n next = items[i + 1];\n prev = items[i - 1];\n curr = items[i];\n\n // only add points that breaks the scale linearity\n if (Math.round((next + prev) / 2) !== curr) {\n table.push({time: curr, pos: i / (ilen - 1)});\n }\n }\n return table;\n }\n\n /**\n * Generates all timestamps defined in the data.\n * Important: this method can return ticks outside the min and max range, it's the\n * responsibility of the calling code to clamp values if needed.\n * @protected\n */\n _generate() {\n const min = this.min;\n const max = this.max;\n let timestamps = super.getDataTimestamps();\n if (!timestamps.includes(min) || !timestamps.length) {\n timestamps.splice(0, 0, min);\n }\n if (!timestamps.includes(max) || timestamps.length === 1) {\n timestamps.push(max);\n }\n return timestamps.sort((a, b) => a - b);\n }\n\n /**\n\t * Returns all timestamps\n\t * @return {number[]}\n\t * @private\n\t */\n _getTimestampsForTable() {\n let timestamps = this._cache.all || [];\n\n if (timestamps.length) {\n return timestamps;\n }\n\n const data = this.getDataTimestamps();\n const label = this.getLabelTimestamps();\n if (data.length && label.length) {\n // If combining labels and data (data might not contain all labels),\n // we need to recheck uniqueness and sort\n timestamps = this.normalize(data.concat(label));\n } else {\n timestamps = data.length ? data : label;\n }\n timestamps = this._cache.all = timestamps;\n\n return timestamps;\n }\n\n /**\n\t * @param {number} value - Milliseconds since epoch (1 January 1970 00:00:00 UTC)\n\t * @return {number}\n\t */\n getDecimalForValue(value) {\n return (interpolate(this._table, value) - this._minPos) / this._tableRange;\n }\n\n /**\n\t * @param {number} pixel\n\t * @return {number}\n\t */\n getValueForPixel(pixel) {\n const offsets = this._offsets;\n const decimal = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end;\n return interpolate(this._table, decimal * this._tableRange + this._minPos, true);\n }\n}\n\nexport default TimeSeriesScale;\n", "export * from './controllers/index.js';\nexport * from './core/index.js';\nexport * from './elements/index.js';\nexport * from './platform/index.js';\nexport * from './plugins/index.js';\nexport * from './scales/index.js';\n\nimport * as controllers from './controllers/index.js';\nimport * as elements from './elements/index.js';\nimport * as plugins from './plugins/index.js';\nimport * as scales from './scales/index.js';\n\nexport {\n controllers,\n elements,\n plugins,\n scales,\n};\n\nexport const registerables = [\n controllers,\n elements,\n plugins,\n scales,\n];\n", "\nexport function setLoadingVisibility(visible: boolean) {\n if (visible) {\n $('#loading_mask').removeClass('invisible');\n } else {\n $('#loading_mask').addClass('invisible');\n }\n}\n", "/**\n * Post JSON, return the result on success, throw an exception on failure\n */\nexport function postJson(url: string, data?: any): Promise {\n // Use the fetch API, if available\n if (window.fetch !== undefined) {\n return postJsonUsingFetch(url, data);\n }\n\n return new Promise((ok, ko) => {\n $.ajax({\n type: 'POST',\n url,\n ...(data ? { data: JSON.stringify(data) } : {}),\n contentType: 'application/json; charset=utf-8',\n dataType: 'json',\n }).done((response: any) => {\n ok(response);\n }).fail((err) => {\n ko(ajaxError(err));\n });\n });\n}\n\n/**\n * Use the fetch API\n *\n * Using this API, we can set `keepalive: true`, which will make the API call\n * complete even if the user navigates away from the page. This way, we can do\n * a \"just-in-time\" save of users programs while the page unloads.\n */\nasync function postJsonUsingFetch(url: string, data?: any): Promise {\n let response;\n try {\n response = await fetch(url, {\n method: 'POST',\n credentials: 'include',\n keepalive: true,\n ...(data ? { body: JSON.stringify(data) } : {}),\n headers: {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Accept': 'application/json',\n },\n });\n } catch (err: any) {\n throw Object.assign(new Error(err.message), {\n internetError: true,\n });\n }\n\n if (response.status >= 400) {\n // The error message is:\n // - response.error, if the response can be parsed as JSON\n // - A generic error message if the response is too big (indicating we're probably getting an HTML page back here)\n // - Otherwise the response text itself\n let errorMessage = await response.text();\n\n try {\n const parsed = JSON.parse(errorMessage);\n if (parsed.error) {\n errorMessage = parsed.error;\n }\n } catch {\n // Not JSON, so probably either plain text or HTML. Check for a sane length, otherwise put a placeholder text here.\n // (No need to translate, this should be very rare.)\n if (errorMessage.length > 500) {\n errorMessage = `the server responded with an error (${response.status} ${response.statusText})`;\n }\n }\n\n throw Object.assign(new Error(errorMessage), {\n responseText: errorMessage,\n status: response.status,\n });\n }\n\n return response.json();\n}\n\nexport function postNoResponse(url: string, data?: any): Promise {\n return new Promise((ok, ko) => {\n $.ajax ({\n type: 'POST',\n url,\n contentType: 'application/json; charset=utf-8',\n ...(data ? { data: JSON.stringify(data) } : {}),\n }).done (() => {\n ok();\n }).fail((err) => {\n ko(ajaxError(err));\n });\n });\n}\n\nfunction ajaxError(err: any) {\n // Some places expect the error object to have the same attributes as\n // the XHR object, so copy them over.\n const error = new Error(err.responseText);\n return Object.assign(error, {\n responseText: err.responseText,\n status: err.status,\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState\n internetError: err.readyState < 4,\n });\n}", "import { modal, tryCatchPopup } from './modal';\nimport { join_class } from './teachers';\nimport { localLoadOnce, localSave } from './local';\nimport { postNoResponse, postJson } from './comm';\n\nconst REDIRECT_AFTER_LOGIN_KEY = 'login-redirect';\n\n// *** Utility functions ***\n\ninterface Dict {\n [key: string]: T;\n}\n\n/**\n * Links to the login page redirect back to the page you come from,\n * by storing the origin address in localstorage (because our login\n * form works via JavaScript/AJAX).\n */\nexport function initializeLoginLinks() {\n $('a[href=\"/login\"]').on('click', () => {\n comeBackHereAfterLogin();\n // Allow the default navigation operation\n });\n}\n\nexport function comeBackHereAfterLogin() {\n localSave(REDIRECT_AFTER_LOGIN_KEY, {\n url: window.location.toString(),\n });\n}\n\nfunction convertFormJSON(form: JQuery) {\n let result : Dict = {};\n $.each($(form).serializeArray(), function() {\n if (result[this.name]) {\n // If this value already exists it's most likely a check button: store all selected ones in an Array\n if ($.isArray(result[this.name])) {\n result[this.name] = $.merge(result[this.name], Array(this.value));\n } else {\n result[this.name] = $.merge(Array(result[this.name]), Array(this.value));\n }\n } else {\n // Only add the current field to the JSON object if it actually contains a value\n if ((this.value)) {\n result[this.name] = this.value;\n }\n }\n });\n return result;\n}\n\nfunction redirect(where: string) {\n where = '/' + where;\n window.location.pathname = where;\n}\n\n// *** User POST without data ***\n\nexport async function logout() {\n await postNoResponse('/auth/logout');\n window.location.reload();\n}\n\n// Todo TB: It might be nice to get a confirmation pop-up from the server instead with some secret key\n// As with the current flow one can destroy an account by \"accidentally\" making an empty POST to /auth/destroy\nexport function destroy(confirmation: string) {\n modal.confirm (confirmation, async () => {\n await postNoResponse('/auth/destroy');\n redirect('');\n });\n}\n\nexport function destroy_public(confirmation: string) {\n modal.confirm (confirmation, async () => {\n await postNoResponse('/auth/destroy_public');\n location.reload();\n });\n}\n\nexport async function turn_into_teacher_account() {\n tryCatchPopup(async () => {\n const response = await postJson('/auth/turn-into-teacher');\n modal.notifySuccess(response.message);\n setTimeout (function () { redirect('for-teachers') }, 2000);\n });\n}\n\n// *** User forms ***\n\nexport function initializeFormSubmits() {\n $('form#signup').on('submit', async function (e) {\n e.preventDefault();\n tryCatchPopup(async () => {\n const body = convertFormJSON($(this))\n await postNoResponse('/auth/signup', body); \n afterLogin({\"first_time\": true, \"is_teacher\": \"is_teacher\" in body});\n });\n });\n\n $('form#login').on('submit', function(e) {\n e.preventDefault();\n tryCatchPopup(async () => {\n const response = await postJson('/auth/login', convertFormJSON($(this)));\n if (response['first_time']) {\n return afterLogin({\"first_time\": true});\n }\n return afterLogin({\"admin\": response['admin'] || false, \"teacher\": response['teacher']} || false);\n });\n });\n\n $('form#profile').on('submit', function(e) {\n e.preventDefault();\n tryCatchPopup(async () => {\n const response = await postJson('/profile', convertFormJSON($(this)));\n if (response.reload) {\n modal.notifySuccess(response.message, 2000);\n setTimeout (function () {location.reload ()}, 2000);\n } else {\n modal.notifySuccess(response.message);\n }\n });\n });\n\n $('form#change_password').on('submit', function(e) {\n e.preventDefault();\n tryCatchPopup(async () => {\n const response = await postJson('/auth/change_password', convertFormJSON($(this)));\n modal.notifySuccess(response.message);\n });\n });\n\n $('form#recover').on('submit', function(e) {\n e.preventDefault();\n tryCatchPopup(async () => {\n const response = await postJson('/auth/recover', convertFormJSON($(this)));\n modal.notifySuccess(response.message);\n $('form#recover').trigger('reset');\n });\n });\n\n $('form#reset').on('submit', function(e) {\n e.preventDefault();\n tryCatchPopup(async () => {\n const response = await postJson('/auth/reset', convertFormJSON($(this)));\n modal.notifySuccess(response.message, 2000);\n $('form#reset').trigger('reset');\n setTimeout(function (){\n redirect ('login');\n }, 2000);\n });\n });\n\n $('form#public_profile').on('submit', function(e) {\n e.preventDefault();\n tryCatchPopup(async () => {\n const response = await postJson('/auth/public_profile', convertFormJSON($(this)));\n modal.notifySuccess(response.message, 2000);\n setTimeout(function () {\n location.reload()\n }, 2000); \n });\n });\n\n // *** LOADERS ***\n\n $('#language').on('change', function () {\n const lang = $(this).val();\n $('#keyword_language').val(\"en\");\n if (lang == \"en\" || !($('#' + lang + '_option').length)) {\n $('#keyword_lang_container').hide();\n } else {\n $('.keyword_lang_option').hide();\n $('#en_option').show();\n $('#' + lang + '_option').show();\n $('#keyword_lang_container').show();\n }\n });\n\n}\n\n// *** Admin functionality ***\n\nexport function changeUserEmail(username: string, email: string) {\n modal.prompt ('Please enter the corrected email', email, async function (correctedEmail) {\n if (correctedEmail === email) return;\n try {\n await postJson('/admin/changeUserEmail', {\n username: username,\n email: correctedEmail\n });\n location.reload ();\n } catch {\n modal.notifyError(['Error when changing the email for user', username].join (' '));\n }\n });\n}\n\nexport function edit_user_tags(username: string) {\n tryCatchPopup(async () => {\n const response = await postJson('/admin/getUserTags', {\n username: username\n });\n console.log(response);\n $('#modal_mask').show();\n $('#tags_username').text(username);\n $('.tags_input').prop('checked', false);\n if (response.tags) {\n console.log(response.tags);\n if (jQuery.inArray(\"certified_teacher\", response.tags) !== -1) {\n $('#certified_tag_input').prop('checked', true);\n }\n if (jQuery.inArray(\"distinguished_user\", response.tags) !== -1) {\n $('#distinguished_tag_input').prop('checked', true);\n }\n if (jQuery.inArray(\"contributor\", response.tags) !== -1) {\n $('#contributor_tag_input').prop('checked', true);\n }\n }\n $('#modal_tags').show();\n });\n}\n\nexport function update_user_tags() {\n tryCatchPopup(async () => {\n const username = $('#tags_username').text();\n const certified = $('#certified_tag_input').prop('checked');\n const distinguished = $('#distinguished_tag_input').prop('checked');\n const contributor = $('#contributor_tag_input').prop('checked');\n\n await postJson('/admin/updateUserTags', {\n username: username,\n certified: certified,\n distinguished: distinguished,\n contributor: contributor\n });\n\n $('#modal_mask').hide();\n $('#modal_tags').hide();\n modal.notifySuccess(\"Tags successfully updated\");\n });\n}\n\n/**\n * After login:\n *\n * - Redirect to a stored URL if present in Local Storage.\n * - Check if we were supposed to be joining a class. If so, join it.\n * - Otherwise redirect to \"my programs\".\n */\nasync function afterLogin(loginData: Dict) {\n const { url } = localLoadOnce(REDIRECT_AFTER_LOGIN_KEY) ?? {};\n if (url && !loginData['first_time']) {\n window.location = url;\n return;\n }\n\n const joinClassString = localStorage.getItem('hedy-join');\n const joinClass = joinClassString ? JSON.parse(joinClassString) : undefined;\n if (joinClass) {\n localStorage.removeItem('hedy-join');\n return join_class(joinClass.id, joinClass.name);\n }\n\n // If the user logs in for the first time and is a teacher -> redirect to the for teacher page\n if (loginData['first_time'] && loginData['is_teacher']) {\n return redirect('for-teachers');\n // If it's a student, send him to the first level\n } else if(loginData['first_time'] && !loginData['is_teacher']) {\n return redirect('hedy/1')\n }\n // If the user is an admin -> re-direct to admin page after login\n if (loginData['admin']) {\n return redirect('admin');\n }\n\n // If the user is a teacher -> re-direct to for-teachers page after login\n if (loginData['teacher']) {\n return redirect('for-teachers');\n }\n // Otherwise, redirect to the programs page\n redirect('');\n}", "/**\n * Show the warning if the \"Run\" button has been clicked this many times\n */\nconst SHOW_AFTER_RUN_CLICKS = 10;\n\n/**\n * Show the warning if the program has hit this length\n */\nconst MIN_LINES_TO_WARN = 20;\n\n/**\n * Show the warning after this many minutes on the same tab\n */\nconst SHOW_AFTER_MINUTES = 10;\n\n/**\n * Holds state to do with the \"make sure you log in\" warning\n */\nexport class LocalSaveWarning {\n private runCounter = 0;\n private loggedIn = false;\n private programLength = 0;\n private timer?: NodeJS.Timeout;\n\n constructor() {\n this.reset();\n }\n\n /**\n * Mark the user as logged in. This disables everything.\n */\n public setLoggedIn() {\n this.loggedIn = true;\n }\n\n public clickRun() {\n this.runCounter += 1;\n if (this.runCounter >= SHOW_AFTER_RUN_CLICKS) {\n this.display(true);\n }\n }\n\n public setProgramLength(lines: number) {\n this.programLength = lines;\n }\n\n public switchTab() {\n this.reset();\n const startTime = Date.now();\n\n if (this.timer) {\n clearInterval(this.timer);\n }\n this.timer = setInterval(() => {\n if (this.programLength >= MIN_LINES_TO_WARN) {\n this.display(true);\n }\n if (Date.now() - startTime >= SHOW_AFTER_MINUTES * 60_000) {\n this.display(true);\n }\n }, 60_000);\n }\n\n private reset() {\n this.runCounter = 0;\n this.programLength = 0;\n this.display(false);\n }\n\n private display(show: boolean) {\n if (this.loggedIn) {\n // Never do it if user is logged in\n return;\n }\n $('#not_logged_in_warning').toggle(show);\n }\n}\n", "import { postJson } from \"./comm\";\nimport { isLoggedIn } from \"./utils\";\n\n// const WAITING_TIME = 5 * 60 * 1000; // 5min in milliseconds\nconst WAITING_TIME = 3000; // 3s for testing\nconst ELEMENT_TO_TRACK = [\n // Debug and Developer buttons\n \"debug_button\",\n \"developers_toggle\",\n\n // Cheatsheet buttons\n \"dropdown_cheatsheet_button\",\n \"try_button1\",\n \"try_button2\",\n \"try_button3\",\n \"try_button4\",\n \"try_button5\",\n \"try_button6\",\n\n // Dropdowns and Toggles\n \"speak_dropdown\",\n \"language_dropdown_button\",\n \"commands_dropdown\",\n \"keyword_toggle\",\n\n // Level buttons\n \"level_button_1\",\n \"level_button_2\",\n \"level_button_3\",\n \"level_button_4\",\n \"level_button_5\",\n \"level_button_6\",\n \"level_button_7\",\n \"level_button_8\",\n \"level_button_9\",\n \"level_button_10\",\n \"level_button_11\",\n \"level_button_12\",\n \"level_button_13\",\n \"level_button_14\",\n \"level_button_15\",\n \"level_button_16\",\n \"level_button_17\",\n \"level_button_18\",\n\n // Class and Adventure buttons\n \"create_class_button\",\n \"create_adventure_button\",\n \"public_adventures_link\",\n \"go_back_button\",\n \"back_to_class\",\n \"customize_class_button\",\n \"live_stats_button\",\n \"grid_overview_button\",\n \n\n // Info buttons\n \"classes_info\",\n \"adventures_info\",\n \"slides_info\",\n \"download_slides_2\",\n \"download_slides_3\",\n \"download_slides_4\",\n \"download_slides_5\",\n \"download_slides_6\",\n \"download_slides_7\",\n \"download_slides_8\",\n \"download_slides_9\",\n \"download_slides_10\",\n \"download_slides_11\",\n \"download_slides_12\",\n \"download_slides_13\",\n \"download_slides_14\",\n \"download_slides_15\",\n \"download_slides_16\",\n \"download_slides_17\",\n \"download_slides_18\",\n\n // Explore page buttons\n \"explore_page_adventure\",\n \"explore_page_level\"\n];\nconst CLICK_COUNTS = \"clickCounts\";\nconst LAST_ACTIVE = \"lastActiveTime\";\nconst INTERVAL_KEY = \"interval\";\n\n\nlet changesSent = false;\nlet amountOfSentActivities = 0;\n\n\nexport function initializeActivity() {\n document.addEventListener(\"DOMContentLoaded\", documentLoaded);\n}\n\n\nfunction documentLoaded() {\n // attach events\n document.addEventListener('click', trackEvent);\n document.addEventListener('change', trackEvent);\n \n \n // initialize variables in localStorage\n handleLocalStorage(CLICK_COUNTS);\n handleLocalStorage(LAST_ACTIVE, Date.now());\n \n if (isLoggedIn()) {\n removeActivityInterval(); // Possibly removing lingering ones.\n setActivityInterval(); // Resume with fresh timer\n }\n}\n\nfunction removeActivityInterval() {\n const storedData = localStorage.getItem(INTERVAL_KEY);\n if (storedData) {\n try {\n const parsedData = JSON.parse(storedData);\n clearInterval(parsedData.id); // Clear any potentially lingering timer\n // console.log(parsedData.id, \" interval was removed\")\n } catch (error) {\n console.error(\"Error parsing activity interval data:\", error);\n }\n }\n\n}\n\nfunction setActivityInterval() {\n const timerId = setInterval(checkUserActivity, WAITING_TIME);\n localStorage.setItem(INTERVAL_KEY, JSON.stringify({ id: timerId, timestamp: Date.now() }));\n}\n\n\nasync function trackEvent(event: Event) {\n // the following check is necessary since some elements issue click and change events.\n const currentTime = Date.now();\n const lastActiveTime = handleLocalStorage(LAST_ACTIVE);\n const inactiveDuration = currentTime - lastActiveTime;\n if (inactiveDuration <= 200) {\n return;\n }\n const target = event.target as HTMLElement;\n // console.log(target, event.type)\n if (target.matches('button') || target.matches('a') || target.matches('input') || target.matches('select') || target.matches(\"div\")) {\n let elementIdOrName = target.id;\n\n if (!elementIdOrName && target.hasAttribute(\"name\")) {\n elementIdOrName = target.getAttribute(\"name\") || \"\";\n }\n\n if (ELEMENT_TO_TRACK.includes(elementIdOrName)) {\n const clickCounts = handleLocalStorage(CLICK_COUNTS);\n \n const page = window.location.pathname;\n\n const value = (target as HTMLInputElement).value || \"\";\n\n clickCounts.push({time: currentTime, id: elementIdOrName, page, extra: value});\n \n // console.log(target, clickCounts)\n // console.log(`Event: ${event.type}, Element ID or Name: ${elementIdOrName}, Click Count: ${clickCounts}`);\n handleUserActivity(clickCounts);\n } \n }\n}\n\n// Function to handle user activity\nfunction handleUserActivity(clickCounts: any) {\n handleLocalStorage(LAST_ACTIVE, Date.now());\n handleLocalStorage(CLICK_COUNTS, clickCounts);\n changesSent = false;\n}\n\n// Retrieve or set items in local storage.\nfunction handleLocalStorage(item: string, value: any = undefined) {\n const retrievedItem = window.localStorage.getItem(item);\n if (!retrievedItem || value !== undefined) {\n value = value || [];\n window.localStorage.setItem(item, JSON.stringify(value));\n } else {\n if (item === CLICK_COUNTS) {\n value = JSON.parse(retrievedItem);\n } else if (item === LAST_ACTIVE) {\n value = parseInt(retrievedItem);\n }\n }\n return value;\n}\n\n// Function to check user activity and send request if inactive for 5 minutes\nasync function checkUserActivity() {\n if (changesSent) {\n // Perhaps add current page with no action by the user.\n // clickCounts = handleLocalStorage(CLICK_COUNTS);\n // const page = window.location.pathname;\n // clickCounts.push({time: lastActiveTime, id: '', page});\n // handleUserActivity(clickCounts);\n return;\n }\n const currentTime = Date.now();\n const lastActiveTime = handleLocalStorage(LAST_ACTIVE);\n const inactiveDuration = currentTime - lastActiveTime;\n if (inactiveDuration >= WAITING_TIME) {\n sendRequestToServer();\n }\n}\n\n// Function to send request to the server\nasync function sendRequestToServer() {\n try {\n let data = handleLocalStorage(CLICK_COUNTS)\n if (data.length) {\n // console.log('Sending request to server...');\n amountOfSentActivities = data.length;\n await postJson('/activity', data);\n // get again since other events may have been registered in the meantime.\n data = handleLocalStorage(CLICK_COUNTS)\n data.splice(0, amountOfSentActivities);\n handleUserActivity(data);\n changesSent = true;\n }\n } catch (error) {\n console.error(error)\n }\n}\n\n\n\n// If not focused on current document, remove interval. Otherwise initialize a new one.\ndocument.addEventListener('visibilitychange', () => {\n if (isLoggedIn()) {\n removeActivityInterval();\n if (!document.hidden) {\n setActivityInterval();\n } else {\n sendRequestToServer();\n }\n }\n});", "import { EventEmitter } from './event-emitter';\n\nexport interface SwitchAdventureEvent {\n readonly oldTab: string;\n readonly newTab: string;\n}\n\nexport interface TabEvents {\n beforeSwitch: SwitchAdventureEvent;\n afterSwitch: SwitchAdventureEvent;\n}\n\nexport interface TabOptions {\n readonly initialTab?: string;\n readonly level?: number;\n}\n\n/**\n * Tabs\n *\n * Protocol:\n *\n * - Tabs consist of a TAB (the sticky-outy bit) and a TARGET\n * (the pane that gets shown and hidden).\n *\n * - TABS should have: <... data-tab=\"SOME-ID\">\n *\n * - TARGETS should have: <... data-tabtarget=\"SOME-ID\">\n *\n * When a TAB is clicked, the TARGET with the matching id is shown\n * (and all other TARGETS in the same containing HTML element are hidden).\n *\n * The active TAB is indicated by the '.tab-selected' class, the active\n * TARGET by the *absence* of the '.hidden' class.\n */\nexport class IndexTabs {\n private _currentTab: string = '';\n private _currentLevel?: number;\n\n private tabEvents = new EventEmitter({\n beforeSwitch: true,\n afterSwitch: true,\n });\n\n constructor(options: TabOptions={}) {\n this._currentLevel = options.level;\n \n $('*[data-tab]').on('click', (e) => {\n const tab = $(e.target);\n const tabName = tab.data('tab') as string;\n const level = tab.data('level')\n e.preventDefault();\n if (this._currentLevel == Number(level))\n this.switchToTab(tabName, Number(level), );\n else\n location.href = `/tryit/${level}#${tabName}`\n });\n\n $('#next_adventure').on('click', () => {\n this.switchPreviousOrNext(true)\n })\n\n $('#previous_adventure').on('click', () => {\n this.switchPreviousOrNext(false)\n })\n\n // Determine initial tab\n // 1. Given by code\n // 2. In the URL\n // 3. Otherwise the first one we find\n let initialTab = options.initialTab;\n if (!initialTab && window.location.hash) {\n const hashFragment = window.location.hash.replace(/^#/, '');\n initialTab = hashFragment;\n }\n if (!initialTab) {\n initialTab = $('.tab:first').attr('data-tab');\n }\n\n if (initialTab && this._currentLevel) {\n this.switchToTab(initialTab, this._currentLevel);\n }\n }\n\n public switchToTab(tabName: string, level: number) {\n const doSwitch = () => {\n const oldTab = this._currentTab;\n this._currentTab = tabName;\n\n // Do a 'replaceState' to add a '#anchor' to the URL\n const hashFragment = tabName !== 'level' ? tabName : '';\n if (window.history) { window.history.replaceState(null, '', '#' + hashFragment); }\n\n // Find the tab that leads to this selection, and its siblings\n const tab = $(`*[data-tab=\"${tabName}\"][data-level=\"${level}\"]`);\n const allTabs = tab.siblings('*[data-tab]');\n\n // Find the target associated with this selection, and its siblings\n const target = $('*[data-tabtarget=\"' + tabName + '\"]');\n const allTargets = target.siblings('*[data-tabtarget]');\n\n allTabs.removeClass('adv-selected');\n allTabs.addClass('not-selected-adv')\n tab.removeClass('not-selected-adv')\n tab.addClass('adv-selected');\n let tab_title = document.getElementById('adventure_name')!\n tab_title.textContent = tab.text().trim()\n const type = tab.data('type');\n tab_title.classList.remove('border-green-300', 'border-[#fdb2c5]', 'border-blue-300', 'border-blue-900')\n if (type == 'teacher') {\n tab_title.classList.add('border-green-300');\n } else if(type == 'command') {\n tab_title.classList.add('border-[#fdb2c5]')\n } else if (type == 'special') {\n tab_title.classList.add('border-blue-300')\n } else {\n tab_title.classList.add('border-blue-900')\n }\n \n // Hide or show the next or previous level button in case we are in the first or last adventure\n // And also depending in which level we are in\n const previous: HTMLElement | null = document.querySelector(`[data-level=\"${tab.data('level')}\"][tabindex=\"${Number(tab.attr('tabindex')) - 1}\"]`)\n if (previous) {\n (document.querySelector('#previous_adventure > p') as HTMLElement).innerText = previous.innerText.trim()\n }\n document.getElementById('back_level')?.classList.toggle('hidden', tab.attr('tabindex') !== '1' || (this._currentLevel ?? 0) === 1)\n document.getElementById('previous_adventure')?.classList.toggle('hidden', tab.attr('tabindex') === '1') \n \n const next: HTMLElement | null = document.querySelector(`[data-level=\"${tab.data('level')}\"][tabindex=\"${Number(tab.attr('tabindex')) + 1}\"]`)\n if (next) {\n (document.querySelector('#next_adventure > p') as HTMLElement).innerText = next.innerText.trim()\n }\n document.getElementById('next_adventure')?.classList.toggle('hidden', next === null)\n document.getElementById('next_level')?.classList.toggle('hidden', next !== null || (this._currentLevel ?? 0) == 18 || tab.data('tab') === 'quiz')\n\n allTargets.addClass('hidden');\n target.removeClass('hidden');\n\n this.tabEvents.emit('afterSwitch', { oldTab, newTab: tabName });\n }\n\n // We don't do a beforeSwitch event for the very first tab switch\n if (this._currentTab != '') {\n const event = this.tabEvents.emit('beforeSwitch', { oldTab: this._currentTab, newTab: tabName });\n event.then(doSwitch);\n } else {\n doSwitch();\n }\n }\n\n private switchPreviousOrNext(toNext: boolean) {\n const selected = document.querySelector('.adv-selected') as HTMLElement\n const i = parseInt(selected?.getAttribute('tabindex') || '0')\n const next = document.querySelector(`li[tabindex='${i + (toNext ? 1 : -1)}'][data-level='${ selected.dataset['level']}']`) as HTMLElement\n \n this.switchToTab(next.dataset['tab']!, Number(next.dataset['level']!))\n document.getElementById('layout')?.scrollIntoView({behavior: 'smooth'})\n }\n\n public get currentTab() {\n return this._currentTab;\n }\n\n public on(key: Parameters[0], handler: Parameters[1]) {\n const ret = this.tabEvents.on(key, handler);\n // Immediately invoke afterSwitch when it's being registered\n if (key === 'afterSwitch') {\n this.tabEvents.emit('afterSwitch', { oldTab: '', newTab: this._currentTab });\n }\n return ret;\n }\n}\n\nexport function getNext() {\n const selected = document.querySelector('.adv-selected')\n if (!selected) return []\n const i = parseInt(selected.getAttribute('tabindex') || '0')\n const next = document.querySelector(`li[tabindex='${i+1}']`)\n return next\n}\n\nexport function getCurrentAdv() {\n const selectedElement = document.querySelector('.adv-selected');\n if (selectedElement) {\n return selectedElement.textContent?.trim() ?? '';\n }\n return '';\n}", "/**\n * Custom integrations we have with HTMX\n */\nimport { initializeHighlightedCodeBlocks } from './app';\nimport { ClientMessages } from './client-messages';\nimport { modal } from './modal';\nimport Sortable from 'sortablejs';\n\ndeclare const htmx: typeof import('./htmx');\n\n/**\n * Disable elements as they are being used to submit HTMX requests.\n *\n * Prevents impatient kids from double-triggering server-side events.\n */\nhtmx.defineExtension('disable-element', {\n onEvent: function (name, evt) {\n let elt = evt.detail.elt;\n if (!elt.getAttribute) {\n return;\n }\n\n let target = elt.getAttribute(\"hx-disable-element\") ?? 'self';\n let targetElement = (target == \"self\") ? elt : document.querySelector(target);\n\n if (name === \"htmx:beforeRequest\" && targetElement) {\n targetElement.disabled = true;\n } else if (name == \"htmx:afterRequest\" && targetElement) {\n targetElement.disabled = false;\n }\n }\n});\n\n/**\n * We have some custom JavaScript to run on new content that's loaded into the DOM.\n *\n * (Notably: turning s into Ace editors)\n */\nhtmx.onLoad((content) => {\n initializeHighlightedCodeBlocks(content, true);\n var sortables = content.querySelectorAll('.sortable');\n for (let i = 0; i < sortables.length; i++) {\n var sortable = sortables[i] as HTMLElement;\n new Sortable(sortable, {\n animation: 150,\n ghostClass: 'drop-adventures-active'\n })\n }\n});\n\ninterface HtmxEvent {\n readonly xhr: XMLHttpRequest;\n readonly error: string;\n}\n\n/**\n * If the server reports an error, we send it into our regular error popup\n */\nhtmx.on('htmx:responseError', (ev) => {\n const event = ev as CustomEvent;\n const xhr: XMLHttpRequest = event.detail.xhr;\n const genericError = event.detail.error;\n modal.notifyError(xhr.responseText.length < 1000 ? xhr.responseText : genericError);\n});\n\nhtmx.on('htmx:sendError', () => {\n modal.notifyError(`${ClientMessages.Connection_error} ${ClientMessages.CheckInternet}`);\n});\n\nhtmx.on(\"htmx:confirm\", function(e: any) {\n e.preventDefault();\n const modalPrompt = e.target.getAttribute(\"hx-confirm\");\n // this is to prevent window.confirm. Just passing true to issueRequest isn't enough.\n if (!modalPrompt) {\n // if no confirm attribute was attached, just continue with the request.\n e.detail.issueRequest(true);\n return;\n }\n modal.confirm(modalPrompt, () => {\n e.target.removeAttribute(\"hx-confirm\");\n e.detail.issueRequest(true);\n });\n});\n", "import { Chart, registerables } from 'chart.js';\nimport {modal} from \"./modal\";\nif (registerables) {\n Chart.register(...registerables);\n}\n\n\nexport function resolve_student(class_id: string, error_id: string, prompt: string) {\n modal.confirm(prompt, function(){\n $.ajax({\n type: 'DELETE',\n url: '/live_stats/class/' + class_id + '/error/' + error_id,\n contentType: 'application/json',\n dataType: 'json'\n }).done(function() {\n location.reload();\n }).fail(function(err) {\n modal.notifyError(err.responseText);\n });\n });\n}\n\nexport function InitLineChart(data: any[], labels: any[]){\n const ctx = document.getElementById(\"runs_over_time\") as HTMLCanvasElement;\n new Chart(ctx, {\n type: 'line',\n data: {\n labels: labels.map(String),\n datasets: [{\n data: data,\n fill: false,\n pointBackgroundColor: function(context) {\n var index = context.dataIndex;\n var value = context.dataset.data[index];\n if (value === 0) {\n return 'red'\n }\n else if (value === 1){\n return 'green'\n }\n return 'blue'\n },\n // backgroundColor: 'rgba(0, 0, 255, 1)',\n borderColor: 'rgba(0, 0, 255, 0.6)',\n borderWidth: 1\n }]\n },\n options: {\n scales: {\n y: {\n ticks: {\n callback: function(index) {\n // Hide every 2nd tick label\n if (index === 0) {\n return 'Fail'\n }\n else if (index === 1){\n return 'Success'\n }\n return ''\n },\n }\n },\n },\n plugins: {\n legend: {\n display: false\n }\n }\n }\n });\n}\n\nexport function toggle_show_students_class_overview(adventure: string) {\n var adventure_panel = \"div[id='adventure_panel_\" + adventure + \"']\";\n if ($(adventure_panel).hasClass('hidden')) {\n $(adventure_panel).removeClass('hidden');\n $(adventure_panel).addClass('block');\n } else {\n $(adventure_panel).removeClass('block');\n $(adventure_panel).addClass('hidden');\n }\n}\n\nexport const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n", "export const logs = {\n\n initialize: function() {\n // Hide irrelevant messages\n $('#logs-spinner').hide();\n $('#search-logs-failed-msg').hide();\n $('#search-logs-empty-msg').hide();\n\n const today = new Date().toISOString().split('T')[0];\n $('#logs-start-date').val(today + ' 00:00:00');\n $('#logs-end-date').val(today + ' 23:59:59');\n },\n\n searchProgramLogs: function (classId: string) {\n var raw_data = $('#logs-search-form').serializeArray();\n var payload: any = {}\n $.map(raw_data, function(n){\n payload[n['name']] = n['value'];\n });\n payload['class_id'] = classId;\n\n $('#search-logs-empty-msg').hide();\n $('#search-logs-failed-msg').hide();\n $('#logs-spinner').show();\n $('#logs-load-more').hide();\n $('#search-logs-button').prop('disabled', true);\n $('#search-logs-table tbody').html('');\n\n const self = this;\n $.ajax ({type: 'POST', url: '/logs/query', data: JSON.stringify (payload), contentType: 'application/json; charset=utf-8'}).done (function (response) {\n if (response['query_status'] === 'SUCCEEDED') {\n self.logsExecutionQueryId = response['query_execution_id'];\n self.logsNextToken = '';\n self.fetchProgramLogsResults();\n } else {\n $('#search-logs-failed-msg').show();\n }\n }).fail (function (error) {\n $('#search-logs-failed-msg').show();\n console.log(error);\n }).always(function() {\n $('#logs-spinner').hide();\n $('#search-logs-button').prop('disabled', false);\n });\n\n return false;\n },\n\n logsExecutionQueryId: '',\n logsNextToken: '',\n\n fetchProgramLogsResults: function() {\n $('#logs-spinner').show();\n $('#search-logs-empty-msg').hide();\n $('#logs-load-more').hide();\n\n const data = {\n query_execution_id: this.logsExecutionQueryId,\n next_token: this.logsNextToken ? this.logsNextToken : undefined\n };\n\n const self = this;\n $.get('/logs/results', data).done (function (response) {\n const $logsTable = $('#search-logs-table tbody');\n\n response.data.forEach ((e: any) => {\n $logsTable.append(` \\\n ${e.date} \\\n ${e.level} \\\n ${e.lang || ''} \\\n ${e.username || ''} \\\n ${e.exception || ''} \\\n \\\n \u21E5 \\\n ${e.code} \\\n `)\n });\n\n if (response.data.length == 0) {\n $('#search-logs-empty-msg').show();\n }\n\n self.logsNextToken = response.next_token;\n\n }).fail (function (error) {\n console.log(error);\n }).always(function() {\n $('#logs-spinner').hide();\n if (self.logsNextToken) {\n $('#logs-load-more').show();\n }\n });\n\n return false;\n },\n\n copyCode: function(el: any) {\n const copyButton = $(el);\n if (navigator.clipboard === undefined) {\n updateCopyButtonText(copyButton, 'Failed!');\n } else {\n navigator.clipboard.writeText(copyButton.next().text()).then(function() {\n updateCopyButtonText(copyButton, 'Copied!');\n }, function() {\n updateCopyButtonText(copyButton, 'Failed!');\n });\n }\n return false;\n },\n}\n\nfunction updateCopyButtonText(copyBtn: any, text: string) {\n copyBtn.text(text);\n setTimeout(function() {copyBtn.html(\"\u21E5\")}, 2000);\n}\n", "export interface InitializeAdminUsersPageOptions {\n readonly page: 'admin-users';\n}\n\nexport function initializeAdminUserPage(_options: InitializeAdminUsersPageOptions) {\n $('.attribute').change(function() {\n const attribute = $(this).attr('id');\n if(!(this as HTMLInputElement).checked) {\n $('#' + attribute + '_header').hide();\n $('.' + attribute + '_cell').hide();\n } else {\n $('#' + attribute + '_header').show();\n $('.' + attribute + '_cell').show();\n }\n });\n // Todo TB: Not sure why I wrote this code here instead of in a .ts file -> re-structure this someday (08-22)\n $('#admin_filter_category').change(function() {\n $('.filter_input').hide();\n if ($('#admin_filter_category').val() == \"email\" || $('#admin_filter_category').val() == \"username\") {\n $('#email_filter_input').show();\n } else if ($('#admin_filter_category').val() == \"language\") {\n $('#language_filter_input').show();\n } else if ($('#admin_filter_category').val() == \"keyword_language\") {\n $('#keyword_language_filter_input').show();\n } else {\n $('#date_filter_input').show();\n }\n });\n\n $('.admin_pagination_btn').click(function(ev) {\n // Copy the token into the hidden input field, then submit the form\n var token = $(ev.target).data('page_token');\n console.log(token);\n $('#hidden_page_input').attr('value', token);\n $('#filterform').submit();\n });\n}\n\nexport function filter_admin() {\n const params: Record = {};\n \n const filter = $('#admin_filter_category').val();\n params['filter'] = filter;\n \n if ($('#hidden_page_input').val()) {\n params['page'] = $('#hidden_page_input').val();\n }\n \n switch (filter) {\n case 'email':\n case 'username':\n params['substring'] = $('#email_filter_input').val();\n break;\n case 'language':\n params['language'] = $('#language_filter_input').val();\n break;\n case 'keyword_language':\n params['keyword_language'] = $('#keyword_language_filter_input').val();\n break;\n default:\n params['start'] = $('#admin_start_date').val();\n params['end'] = $('#admin_end_date').val();\n break;\n }\n \n const queryString = Object.entries(params).map(([k, v]) => k + '=' + encodeURIComponent(v)).join('&');\n window.open('?' + queryString, '_self');\n}", "import { autoSave } from \"./autosave\";\n\nexport interface InitializeMyProfilePage {\n readonly page: 'my-profile';\n}\n\nexport function initializeMyProfilePage(_options: InitializeMyProfilePage) {\n // Autosave my profile page; only users' details.\n autoSave(\"profile\");\n}", "import { initializeAdminUserPage, InitializeAdminUsersPageOptions } from './admin';\nimport { initializeCustomAdventurePage, InitializeCustomizeAdventurePage } from './adventure';\nimport { initializeMyProfilePage, InitializeMyProfilePage } from './profile';\nimport { initializeApp, initializeCodePage, InitializeCodePageOptions, initializeViewProgramPage, InitializeViewProgramPageOptions } from './app';\nimport { initializeFormSubmits } from './auth';\nimport { setClientMessageLanguage } from './client-messages';\nimport { logs } from './logs';\nimport { initializeClassOverviewPage, InitializeClassOverviewPageOptions, initializeCustomizeClassPage, InitializeCustomizeClassPageOptions, initializeTeacherPage, InitializeTeacherPageOptions, initializeCreateAccountsPage, InitializeCreateAccountsPageOptions } from './teachers';\nimport { initializeTutorial } from './tutorials/tutorial';\n\nexport interface InitializeOptions {\n /**\n * Current language\n *\n * Written: by every page, on page load.\n * Used: on the code page, to do speech synthesis and to send to the server.\n */\n readonly lang: string;\n\n /**\n * Current level\n *\n * Written: by every page, on page load.\n *\n * Used: on the code page, to initialize the highlighter, to translate the program,\n * to determine timeouts, to load the quiz iframe, to show the variable inspector,\n * to show a debugger, to load parsons exercises, to initialize a default save name.\n */\n readonly level: number;\n\n /**\n * Current keyword language\n *\n * Written: by every page, on page load.\n *\n * Used: set on the Ace editor, and then is used to do some magic that I don't\n * quite understand.\n */\n readonly keyword_language: string;\n\n readonly logs?: boolean;\n\n /**\n * The URL root where static content is hosted\n */\n readonly staticRoot?: string;\n\n readonly javascriptPageOptions?: InitializePageOptions;\n}\n\ntype InitializePageOptions =\n | InitializeCodePageOptions\n | InitializeCustomizeClassPageOptions\n | InitializeTeacherPageOptions\n | InitializeCreateAccountsPageOptions\n | InitializeViewProgramPageOptions\n | InitializeClassOverviewPageOptions\n | InitializeAdminUsersPageOptions\n | InitializeCustomizeAdventurePage\n | InitializeMyProfilePage\n ;\n\n\n/**\n * This function gets called by the HTML when the page is being initialized.\n */\nexport function initialize(options: InitializeOptions) {\n setClientMessageLanguage(options.lang);\n\n let level = options.level;\n\n if (!level && options.javascriptPageOptions?.page == \"customize-adventure\") {\n level = options.javascriptPageOptions.level\n }\n\n initializeApp({\n level: level,\n keywordLanguage: options.keyword_language,\n staticRoot: options.staticRoot,\n });\n initializeFormSubmits();\n initializeTutorial();\n\n // The above initializations are often also page-specific\n switch (options.javascriptPageOptions?.page) {\n case 'code':\n initializeCodePage(options.javascriptPageOptions);\n break;\n\n case 'customize-class':\n initializeCustomizeClassPage(options.javascriptPageOptions);\n break;\n\n case 'for-teachers':\n initializeTeacherPage(options.javascriptPageOptions);\n break;\n\n case 'create-accounts':\n initializeCreateAccountsPage(options.javascriptPageOptions);\n break;\n\n case 'class-overview':\n initializeClassOverviewPage(options.javascriptPageOptions);\n break;\n\n case 'view-program':\n initializeViewProgramPage(options.javascriptPageOptions);\n break;\n\n case 'admin-users':\n initializeAdminUserPage(options.javascriptPageOptions);\n break;\n \n case 'customize-adventure':\n initializeCustomAdventurePage(options.javascriptPageOptions);\n break;\n\n case 'my-profile':\n initializeMyProfilePage(options.javascriptPageOptions);\n break;\n \n case 'tryit':\n initializeCodePage(options.javascriptPageOptions);\n }\n\n // FIXME: I think this might also be page-specific\n if (options.logs) {\n logs.initialize();\n }\n}\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst mapData = (() => {\r\n const storeData = {};\r\n let id = 1;\r\n return {\r\n set(element, key, data) {\r\n if (typeof element[key] === \"undefined\") {\r\n element[key] = {\r\n key,\r\n id,\r\n };\r\n id++;\r\n }\r\n\r\n storeData[element[key].id] = data;\r\n },\r\n get(element, key) {\r\n if (!element || typeof element[key] === \"undefined\") {\r\n return null;\r\n }\r\n\r\n const keyProperties = element[key];\r\n if (keyProperties.key === key) {\r\n return storeData[keyProperties.id];\r\n }\r\n\r\n return null;\r\n },\r\n delete(element, key) {\r\n if (typeof element[key] === \"undefined\") {\r\n return;\r\n }\r\n\r\n const keyProperties = element[key];\r\n if (keyProperties.key === key) {\r\n delete storeData[keyProperties.id];\r\n delete element[key];\r\n }\r\n },\r\n };\r\n})();\r\n\r\nconst Data = {\r\n setData(instance, key, data) {\r\n mapData.set(instance, key, data);\r\n },\r\n getData(instance, key) {\r\n return mapData.get(instance, key);\r\n },\r\n removeData(instance, key) {\r\n mapData.delete(instance, key);\r\n },\r\n};\r\n\r\nexport default Data;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nconst MAX_UID = 1000000;\r\nconst MILLISECONDS_MULTIPLIER = 1000;\r\nconst TRANSITION_END = \"transitionend\";\r\n\r\n// Shoutout AngusCroll (https://goo.gl/pxwQGp)\r\nconst toType = (obj) => {\r\n if (obj === null || obj === undefined) {\r\n return `${obj}`;\r\n }\r\n\r\n return {}.toString\r\n .call(obj)\r\n .match(/\\s([a-z]+)/i)[1]\r\n .toLowerCase();\r\n};\r\n\r\n/**\r\n * --------------------------------------------------------------------------\r\n * Public Util Api\r\n * --------------------------------------------------------------------------\r\n */\r\n\r\nconst getUID = (prefix) => {\r\n do {\r\n prefix += Math.floor(Math.random() * MAX_UID);\r\n } while (document.getElementById(prefix));\r\n\r\n return prefix;\r\n};\r\n\r\nconst getSelector = (element) => {\r\n let selector = element.getAttribute(\"data-te-target\");\r\n\r\n if (!selector || selector === \"#\") {\r\n let hrefAttr = element.getAttribute(\"href\");\r\n\r\n // The only valid content that could double as a selector are IDs or classes,\r\n // so everything starting with `#` or `.`. If a \"real\" URL is used as the selector,\r\n // `document.querySelector` will rightfully complain it is invalid.\r\n // See https://github.com/twbs/bootstrap/issues/32273\r\n if (!hrefAttr || (!hrefAttr.includes(\"#\") && !hrefAttr.startsWith(\".\"))) {\r\n return null;\r\n }\r\n\r\n // Just in case some CMS puts out a full URL with the anchor appended\r\n if (hrefAttr.includes(\"#\") && !hrefAttr.startsWith(\"#\")) {\r\n hrefAttr = `#${hrefAttr.split(\"#\")[1]}`;\r\n }\r\n\r\n selector = hrefAttr && hrefAttr !== \"#\" ? hrefAttr.trim() : null;\r\n }\r\n\r\n return selector;\r\n};\r\n\r\nconst getSelectorFromElement = (element) => {\r\n const selector = getSelector(element);\r\n\r\n if (selector) {\r\n return document.querySelector(selector) ? selector : null;\r\n }\r\n\r\n return null;\r\n};\r\n\r\nconst getElementFromSelector = (element) => {\r\n const selector = getSelector(element);\r\n\r\n return selector ? document.querySelector(selector) : null;\r\n};\r\n\r\nconst getTransitionDurationFromElement = (element) => {\r\n if (!element) {\r\n return 0;\r\n }\r\n\r\n // Get transition-duration of the element\r\n let { transitionDuration, transitionDelay } =\r\n window.getComputedStyle(element);\r\n\r\n const floatTransitionDuration = Number.parseFloat(transitionDuration);\r\n const floatTransitionDelay = Number.parseFloat(transitionDelay);\r\n\r\n // Return 0 if element or transition duration is not found\r\n if (!floatTransitionDuration && !floatTransitionDelay) {\r\n return 0;\r\n }\r\n\r\n // If multiple durations are defined, take the first\r\n transitionDuration = transitionDuration.split(\",\")[0];\r\n transitionDelay = transitionDelay.split(\",\")[0];\r\n\r\n return (\r\n (Number.parseFloat(transitionDuration) +\r\n Number.parseFloat(transitionDelay)) *\r\n MILLISECONDS_MULTIPLIER\r\n );\r\n};\r\n\r\nconst triggerTransitionEnd = (element) => {\r\n element.dispatchEvent(new Event(TRANSITION_END));\r\n};\r\n\r\nconst isElement = (obj) => {\r\n if (!obj || typeof obj !== \"object\") {\r\n return false;\r\n }\r\n\r\n if (typeof obj.jquery !== \"undefined\") {\r\n obj = obj[0];\r\n }\r\n\r\n return typeof obj.nodeType !== \"undefined\";\r\n};\r\n\r\nconst getElement = (obj) => {\r\n if (isElement(obj)) {\r\n // it's a jQuery object or a node element\r\n return obj.jquery ? obj[0] : obj;\r\n }\r\n\r\n if (typeof obj === \"string\" && obj.length > 0) {\r\n return document.querySelector(obj);\r\n }\r\n\r\n return null;\r\n};\r\n\r\nconst emulateTransitionEnd = (element, duration) => {\r\n let called = false;\r\n const durationPadding = 5;\r\n const emulatedDuration = duration + durationPadding;\r\n\r\n function listener() {\r\n called = true;\r\n element.removeEventListener(TRANSITION_END, listener);\r\n }\r\n\r\n element.addEventListener(TRANSITION_END, listener);\r\n setTimeout(() => {\r\n if (!called) {\r\n triggerTransitionEnd(element);\r\n }\r\n }, emulatedDuration);\r\n};\r\n\r\nconst typeCheckConfig = (componentName, config, configTypes) => {\r\n Object.keys(configTypes).forEach((property) => {\r\n const expectedTypes = configTypes[property];\r\n const value = config[property];\r\n const valueType = value && isElement(value) ? \"element\" : toType(value);\r\n\r\n if (!new RegExp(expectedTypes).test(valueType)) {\r\n throw new Error(\r\n `${componentName.toUpperCase()}: ` +\r\n `Option \"${property}\" provided type \"${valueType}\" ` +\r\n `but expected type \"${expectedTypes}\".`\r\n );\r\n }\r\n });\r\n};\r\n\r\nconst isVisible = (element) => {\r\n if (!element || element.getClientRects().length === 0) {\r\n return false;\r\n }\r\n\r\n if (element.style && element.parentNode && element.parentNode.style) {\r\n const elementStyle = getComputedStyle(element);\r\n const parentNodeStyle = getComputedStyle(element.parentNode);\r\n\r\n return (\r\n getComputedStyle(element).getPropertyValue(\"visibility\") === \"visible\" ||\r\n (elementStyle.display !== \"none\" &&\r\n parentNodeStyle.display !== \"none\" &&\r\n elementStyle.visibility !== \"hidden\")\r\n );\r\n }\r\n\r\n return false;\r\n};\r\n\r\nconst isDisabled = (element) => {\r\n if (!element || element.nodeType !== Node.ELEMENT_NODE) {\r\n return true;\r\n }\r\n\r\n if (element.classList.contains(\"disabled\")) {\r\n return true;\r\n }\r\n\r\n if (typeof element.disabled !== \"undefined\") {\r\n return element.disabled;\r\n }\r\n\r\n return (\r\n element.hasAttribute(\"disabled\") &&\r\n element.getAttribute(\"disabled\") !== \"false\"\r\n );\r\n};\r\n\r\nconst findShadowRoot = (element) => {\r\n if (!document.documentElement.attachShadow) {\r\n return null;\r\n }\r\n\r\n // Can find the shadow root otherwise it'll return the document\r\n if (typeof element.getRootNode === \"function\") {\r\n const root = element.getRootNode();\r\n return root instanceof ShadowRoot ? root : null;\r\n }\r\n\r\n if (element instanceof ShadowRoot) {\r\n return element;\r\n }\r\n\r\n // when we don't find a shadow root\r\n if (!element.parentNode) {\r\n return null;\r\n }\r\n\r\n return findShadowRoot(element.parentNode);\r\n};\r\n\r\nconst noop = () => function () {};\r\n\r\n/**\r\n * Trick to restart an element's animation\r\n *\r\n * @param {HTMLElement} element\r\n * @return void\r\n *\r\n * @see https://www.charistheo.io/blog/2021/02/restart-a-css-animation-with-javascript/#restarting-a-css-animation\r\n */\r\nconst reflow = (element) => {\r\n // eslint-disable-next-line no-unused-expressions\r\n element.offsetHeight;\r\n};\r\n\r\nconst getjQuery = () => {\r\n const { jQuery } = window;\r\n\r\n if (jQuery && !document.body.hasAttribute(\"data-te-no-jquery\")) {\r\n return jQuery;\r\n }\r\n\r\n return null;\r\n};\r\n\r\nconst DOMContentLoadedCallbacks = [];\r\n\r\nconst onDOMContentLoaded = (callback) => {\r\n if (document.readyState === \"loading\") {\r\n // add listener on the first call when the document is in loading state\r\n if (!DOMContentLoadedCallbacks.length) {\r\n document.addEventListener(\"DOMContentLoaded\", () => {\r\n DOMContentLoadedCallbacks.forEach((callback) => callback());\r\n });\r\n }\r\n\r\n DOMContentLoadedCallbacks.push(callback);\r\n } else {\r\n callback();\r\n }\r\n};\r\n\r\nconst isRTL = () => document.documentElement.dir === \"rtl\";\r\n\r\nconst array = (collection) => {\r\n return Array.from(collection);\r\n};\r\n\r\nconst element = (tag) => {\r\n return document.createElement(tag);\r\n};\r\n\r\nconst defineJQueryPlugin = (plugin) => {\r\n onDOMContentLoaded(() => {\r\n const $ = getjQuery();\r\n /* istanbul ignore if */\r\n if ($) {\r\n const name = plugin.NAME;\r\n const JQUERY_NO_CONFLICT = $.fn[name];\r\n $.fn[name] = plugin.jQueryInterface;\r\n $.fn[name].Constructor = plugin;\r\n $.fn[name].noConflict = () => {\r\n $.fn[name] = JQUERY_NO_CONFLICT;\r\n return plugin.jQueryInterface;\r\n };\r\n }\r\n });\r\n};\r\n\r\nconst execute = (callback) => {\r\n if (typeof callback === \"function\") {\r\n callback();\r\n }\r\n};\r\n\r\nconst executeAfterTransition = (\r\n callback,\r\n transitionElement,\r\n waitForTransition = true\r\n) => {\r\n if (!waitForTransition) {\r\n execute(callback);\r\n return;\r\n }\r\n\r\n const durationPadding = 5;\r\n const emulatedDuration =\r\n getTransitionDurationFromElement(transitionElement) + durationPadding;\r\n\r\n let called = false;\r\n\r\n const handler = ({ target }) => {\r\n if (target !== transitionElement) {\r\n return;\r\n }\r\n\r\n called = true;\r\n transitionElement.removeEventListener(TRANSITION_END, handler);\r\n execute(callback);\r\n };\r\n\r\n transitionElement.addEventListener(TRANSITION_END, handler);\r\n setTimeout(() => {\r\n if (!called) {\r\n triggerTransitionEnd(transitionElement);\r\n }\r\n }, emulatedDuration);\r\n};\r\n\r\n/**\r\n * Return the previous/next element of a list.\r\n *\r\n * @param {array} list The list of elements\r\n * @param activeElement The active element\r\n * @param shouldGetNext Choose to get next or previous element\r\n * @param isCycleAllowed\r\n * @return {Element|elem} The proper element\r\n */\r\nconst getNextActiveElement = (\r\n list,\r\n activeElement,\r\n shouldGetNext,\r\n isCycleAllowed\r\n) => {\r\n let index = list.indexOf(activeElement);\r\n\r\n // if the element does not exist in the list return an element depending on the direction and if cycle is allowed\r\n if (index === -1) {\r\n return list[!shouldGetNext && isCycleAllowed ? list.length - 1 : 0];\r\n }\r\n\r\n const listLength = list.length;\r\n\r\n index += shouldGetNext ? 1 : -1;\r\n\r\n if (isCycleAllowed) {\r\n index = (index + listLength) % listLength;\r\n }\r\n\r\n return list[Math.max(0, Math.min(index, listLength - 1))];\r\n};\r\n\r\nexport {\r\n getjQuery,\r\n TRANSITION_END,\r\n getUID,\r\n getSelectorFromElement,\r\n getElementFromSelector,\r\n getTransitionDurationFromElement,\r\n triggerTransitionEnd,\r\n isElement,\r\n emulateTransitionEnd,\r\n typeCheckConfig,\r\n isVisible,\r\n findShadowRoot,\r\n noop,\r\n reflow,\r\n array,\r\n element,\r\n onDOMContentLoaded,\r\n isRTL,\r\n defineJQueryPlugin,\r\n getElement,\r\n isDisabled,\r\n execute,\r\n executeAfterTransition,\r\n getNextActiveElement,\r\n};\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport { getjQuery } from \"../util/index\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst namespaceRegex = /[^.]*(?=\\..*)\\.|.*/;\r\nconst stripNameRegex = /\\..*/;\r\nconst stripUidRegex = /::\\d+$/;\r\nconst eventRegistry = {}; // Events storage\r\nlet uidEvent = 1;\r\nconst customEvents = {\r\n mouseenter: \"mouseover\",\r\n mouseleave: \"mouseout\",\r\n};\r\nconst customEventsRegex = /^(mouseenter|mouseleave)/i;\r\nconst nativeEvents = new Set([\r\n \"click\",\r\n \"dblclick\",\r\n \"mouseup\",\r\n \"mousedown\",\r\n \"contextmenu\",\r\n \"mousewheel\",\r\n \"DOMMouseScroll\",\r\n \"mouseover\",\r\n \"mouseout\",\r\n \"mousemove\",\r\n \"selectstart\",\r\n \"selectend\",\r\n \"keydown\",\r\n \"keypress\",\r\n \"keyup\",\r\n \"orientationchange\",\r\n \"touchstart\",\r\n \"touchmove\",\r\n \"touchend\",\r\n \"touchcancel\",\r\n \"pointerdown\",\r\n \"pointermove\",\r\n \"pointerup\",\r\n \"pointerleave\",\r\n \"pointercancel\",\r\n \"gesturestart\",\r\n \"gesturechange\",\r\n \"gestureend\",\r\n \"focus\",\r\n \"blur\",\r\n \"change\",\r\n \"reset\",\r\n \"select\",\r\n \"submit\",\r\n \"focusin\",\r\n \"focusout\",\r\n \"load\",\r\n \"unload\",\r\n \"beforeunload\",\r\n \"resize\",\r\n \"move\",\r\n \"DOMContentLoaded\",\r\n \"readystatechange\",\r\n \"error\",\r\n \"abort\",\r\n \"scroll\",\r\n]);\r\n\r\n/**\r\n * ------------------------------------------------------------------------\r\n * Private methods\r\n * ------------------------------------------------------------------------\r\n */\r\n\r\nfunction getUidEvent(element, uid) {\r\n return (uid && `${uid}::${uidEvent++}`) || element.uidEvent || uidEvent++;\r\n}\r\n\r\nfunction getEvent(element) {\r\n const uid = getUidEvent(element);\r\n\r\n element.uidEvent = uid;\r\n eventRegistry[uid] = eventRegistry[uid] || {};\r\n\r\n return eventRegistry[uid];\r\n}\r\n\r\nfunction bootstrapHandler(element, fn) {\r\n return function handler(event) {\r\n event.delegateTarget = element;\r\n\r\n if (handler.oneOff) {\r\n EventHandler.off(element, event.type, fn);\r\n }\r\n\r\n return fn.apply(element, [event]);\r\n };\r\n}\r\n\r\nfunction bootstrapDelegationHandler(element, selector, fn) {\r\n return function handler(event) {\r\n const domElements = element.querySelectorAll(selector);\r\n\r\n for (\r\n let { target } = event;\r\n target && target !== this;\r\n target = target.parentNode\r\n ) {\r\n for (let i = domElements.length; i--; \"\") {\r\n if (domElements[i] === target) {\r\n event.delegateTarget = target;\r\n\r\n if (handler.oneOff) {\r\n EventHandler.off(element, event.type, fn);\r\n }\r\n\r\n return fn.apply(target, [event]);\r\n }\r\n }\r\n }\r\n\r\n // To please ESLint\r\n return null;\r\n };\r\n}\r\n\r\nfunction findHandler(events, handler, delegationSelector = null) {\r\n const uidEventList = Object.keys(events);\r\n\r\n for (let i = 0, len = uidEventList.length; i < len; i++) {\r\n const event = events[uidEventList[i]];\r\n\r\n if (\r\n event.originalHandler === handler &&\r\n event.delegationSelector === delegationSelector\r\n ) {\r\n return event;\r\n }\r\n }\r\n\r\n return null;\r\n}\r\n\r\nfunction normalizeParams(originalTypeEvent, handler, delegationFn) {\r\n const delegation = typeof handler === \"string\";\r\n const originalHandler = delegation ? delegationFn : handler;\r\n\r\n let typeEvent = getTypeEvent(originalTypeEvent);\r\n const isNative = nativeEvents.has(typeEvent);\r\n\r\n if (!isNative) {\r\n typeEvent = originalTypeEvent;\r\n }\r\n\r\n return [delegation, originalHandler, typeEvent];\r\n}\r\n\r\nfunction addHandler(element, originalTypeEvent, handler, delegationFn, oneOff) {\r\n if (typeof originalTypeEvent !== \"string\" || !element) {\r\n return;\r\n }\r\n\r\n if (!handler) {\r\n handler = delegationFn;\r\n delegationFn = null;\r\n }\r\n\r\n // in case of mouseenter or mouseleave wrap the handler within a function that checks for its DOM position\r\n // this prevents the handler from being dispatched the same way as mouseover or mouseout does\r\n if (customEventsRegex.test(originalTypeEvent)) {\r\n const wrapFn = (fn) => {\r\n return function (event) {\r\n if (\r\n !event.relatedTarget ||\r\n (event.relatedTarget !== event.delegateTarget &&\r\n !event.delegateTarget.contains(event.relatedTarget))\r\n ) {\r\n return fn.call(this, event);\r\n }\r\n };\r\n };\r\n\r\n if (delegationFn) {\r\n delegationFn = wrapFn(delegationFn);\r\n } else {\r\n handler = wrapFn(handler);\r\n }\r\n }\r\n\r\n const [delegation, originalHandler, typeEvent] = normalizeParams(\r\n originalTypeEvent,\r\n handler,\r\n delegationFn\r\n );\r\n const events = getEvent(element);\r\n const handlers = events[typeEvent] || (events[typeEvent] = {});\r\n const previousFn = findHandler(\r\n handlers,\r\n originalHandler,\r\n delegation ? handler : null\r\n );\r\n\r\n if (previousFn) {\r\n previousFn.oneOff = previousFn.oneOff && oneOff;\r\n\r\n return;\r\n }\r\n\r\n const uid = getUidEvent(\r\n originalHandler,\r\n originalTypeEvent.replace(namespaceRegex, \"\")\r\n );\r\n const fn = delegation\r\n ? bootstrapDelegationHandler(element, handler, delegationFn)\r\n : bootstrapHandler(element, handler);\r\n\r\n fn.delegationSelector = delegation ? handler : null;\r\n fn.originalHandler = originalHandler;\r\n fn.oneOff = oneOff;\r\n fn.uidEvent = uid;\r\n handlers[uid] = fn;\r\n\r\n element.addEventListener(typeEvent, fn, delegation);\r\n}\r\n\r\nfunction removeHandler(\r\n element,\r\n events,\r\n typeEvent,\r\n handler,\r\n delegationSelector\r\n) {\r\n const fn = findHandler(events[typeEvent], handler, delegationSelector);\r\n\r\n if (!fn) {\r\n return;\r\n }\r\n\r\n element.removeEventListener(typeEvent, fn, Boolean(delegationSelector));\r\n delete events[typeEvent][fn.uidEvent];\r\n}\r\n\r\nfunction removeNamespacedHandlers(element, events, typeEvent, namespace) {\r\n const storeElementEvent = events[typeEvent] || {};\r\n\r\n Object.keys(storeElementEvent).forEach((handlerKey) => {\r\n if (handlerKey.includes(namespace)) {\r\n const event = storeElementEvent[handlerKey];\r\n\r\n removeHandler(\r\n element,\r\n events,\r\n typeEvent,\r\n event.originalHandler,\r\n event.delegationSelector\r\n );\r\n }\r\n });\r\n}\r\n\r\nfunction getTypeEvent(event) {\r\n // allow to get the native events from namespaced events ('click.te.button' --> 'click')\r\n event = event.replace(stripNameRegex, \"\");\r\n return customEvents[event] || event;\r\n}\r\n\r\nconst EventHandler = {\r\n on(element, event, handler, delegationFn) {\r\n addHandler(element, event, handler, delegationFn, false);\r\n },\r\n\r\n one(element, event, handler, delegationFn) {\r\n addHandler(element, event, handler, delegationFn, true);\r\n },\r\n\r\n off(element, originalTypeEvent, handler, delegationFn) {\r\n if (typeof originalTypeEvent !== \"string\" || !element) {\r\n return;\r\n }\r\n\r\n const [delegation, originalHandler, typeEvent] = normalizeParams(\r\n originalTypeEvent,\r\n handler,\r\n delegationFn\r\n );\r\n const inNamespace = typeEvent !== originalTypeEvent;\r\n const events = getEvent(element);\r\n const isNamespace = originalTypeEvent.startsWith(\".\");\r\n\r\n if (typeof originalHandler !== \"undefined\") {\r\n // Simplest case: handler is passed, remove that listener ONLY.\r\n if (!events || !events[typeEvent]) {\r\n return;\r\n }\r\n\r\n removeHandler(\r\n element,\r\n events,\r\n typeEvent,\r\n originalHandler,\r\n delegation ? handler : null\r\n );\r\n return;\r\n }\r\n\r\n if (isNamespace) {\r\n Object.keys(events).forEach((elementEvent) => {\r\n removeNamespacedHandlers(\r\n element,\r\n events,\r\n elementEvent,\r\n originalTypeEvent.slice(1)\r\n );\r\n });\r\n }\r\n\r\n const storeElementEvent = events[typeEvent] || {};\r\n Object.keys(storeElementEvent).forEach((keyHandlers) => {\r\n const handlerKey = keyHandlers.replace(stripUidRegex, \"\");\r\n\r\n if (!inNamespace || originalTypeEvent.includes(handlerKey)) {\r\n const event = storeElementEvent[keyHandlers];\r\n\r\n removeHandler(\r\n element,\r\n events,\r\n typeEvent,\r\n event.originalHandler,\r\n event.delegationSelector\r\n );\r\n }\r\n });\r\n },\r\n\r\n trigger(element, event, args) {\r\n if (typeof event !== \"string\" || !element) {\r\n return null;\r\n }\r\n\r\n const $ = getjQuery();\r\n const typeEvent = getTypeEvent(event);\r\n const inNamespace = event !== typeEvent;\r\n const isNative = nativeEvents.has(typeEvent);\r\n\r\n let jQueryEvent;\r\n let bubbles = true;\r\n let nativeDispatch = true;\r\n let defaultPrevented = false;\r\n let evt = null;\r\n\r\n if (inNamespace && $) {\r\n jQueryEvent = $.Event(event, args);\r\n\r\n $(element).trigger(jQueryEvent);\r\n bubbles = !jQueryEvent.isPropagationStopped();\r\n nativeDispatch = !jQueryEvent.isImmediatePropagationStopped();\r\n defaultPrevented = jQueryEvent.isDefaultPrevented();\r\n }\r\n\r\n if (isNative) {\r\n evt = document.createEvent(\"HTMLEvents\");\r\n evt.initEvent(typeEvent, bubbles, true);\r\n } else {\r\n evt = new CustomEvent(event, {\r\n bubbles,\r\n cancelable: true,\r\n });\r\n }\r\n\r\n // merge custom information in our event\r\n if (typeof args !== \"undefined\") {\r\n Object.keys(args).forEach((key) => {\r\n Object.defineProperty(evt, key, {\r\n get() {\r\n return args[key];\r\n },\r\n });\r\n });\r\n }\r\n\r\n if (defaultPrevented) {\r\n evt.preventDefault();\r\n }\r\n\r\n if (nativeDispatch) {\r\n element.dispatchEvent(evt);\r\n }\r\n\r\n if (evt.defaultPrevented && typeof jQueryEvent !== \"undefined\") {\r\n jQueryEvent.preventDefault();\r\n }\r\n\r\n return evt;\r\n },\r\n};\r\n\r\nexport const EventHandlerMulti = {\r\n on(element, eventsName, handler, delegationFn) {\r\n const events = eventsName.split(\" \");\r\n\r\n for (let i = 0; i < events.length; i++) {\r\n EventHandler.on(element, events[i], handler, delegationFn);\r\n }\r\n },\r\n off(element, originalTypeEvent, handler, delegationFn) {\r\n const events = originalTypeEvent.split(\" \");\r\n\r\n for (let i = 0; i < events.length; i++) {\r\n EventHandler.off(element, events[i], handler, delegationFn);\r\n }\r\n },\r\n};\r\n\r\nexport default EventHandler;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport Data from \"./dom/data\";\r\nimport { executeAfterTransition, getElement } from \"./util/index\";\r\nimport EventHandler from \"./dom/event-handler\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst VERSION = \"5.1.3\";\r\n\r\nclass BaseComponent {\r\n constructor(element) {\r\n element = getElement(element);\r\n\r\n if (!element) {\r\n return;\r\n }\r\n\r\n this._element = element;\r\n Data.setData(this._element, this.constructor.DATA_KEY, this);\r\n }\r\n\r\n dispose() {\r\n Data.removeData(this._element, this.constructor.DATA_KEY);\r\n EventHandler.off(this._element, this.constructor.EVENT_KEY);\r\n\r\n Object.getOwnPropertyNames(this).forEach((propertyName) => {\r\n this[propertyName] = null;\r\n });\r\n }\r\n\r\n _queueCallback(callback, element, isAnimated = true) {\r\n executeAfterTransition(callback, element, isAnimated);\r\n }\r\n\r\n /** Static */\r\n\r\n static getInstance(element) {\r\n return Data.getData(getElement(element), this.DATA_KEY);\r\n }\r\n\r\n static getOrCreateInstance(element, config = {}) {\r\n return (\r\n this.getInstance(element) ||\r\n new this(element, typeof config === \"object\" ? config : null)\r\n );\r\n }\r\n\r\n static get VERSION() {\r\n return VERSION;\r\n }\r\n\r\n static get NAME() {\r\n throw new Error(\r\n 'You have to implement the static method \"NAME\", for each component!'\r\n );\r\n }\r\n\r\n static get DATA_KEY() {\r\n return `te.${this.NAME}`;\r\n }\r\n\r\n static get EVENT_KEY() {\r\n return `.${this.DATA_KEY}`;\r\n }\r\n}\r\n\r\nexport default BaseComponent;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport BaseComponent from \"../base-component\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst NAME = \"button\";\r\n\r\nconst CLASS_NAME_ACTIVE = \"active\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nClass Definition\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nclass Button extends BaseComponent {\r\n // Getters\r\n\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n // Public\r\n\r\n toggle() {\r\n // Toggle class and sync the `aria-pressed` attribute with the return value of the `.toggle()` method\r\n this._element.setAttribute(\r\n \"aria-pressed\",\r\n this._element.classList.toggle(CLASS_NAME_ACTIVE)\r\n );\r\n }\r\n\r\n // Static\r\n\r\n static jQueryInterface(config) {\r\n return this.each(function () {\r\n const data = Button.getOrCreateInstance(this);\r\n\r\n if (config === \"toggle\") {\r\n data[config]();\r\n }\r\n });\r\n }\r\n}\r\n\r\nexport default Button;\r\n", "export var top = 'top';\nexport var bottom = 'bottom';\nexport var right = 'right';\nexport var left = 'left';\nexport var auto = 'auto';\nexport var basePlacements = [top, bottom, right, left];\nexport var start = 'start';\nexport var end = 'end';\nexport var clippingParents = 'clippingParents';\nexport var viewport = 'viewport';\nexport var popper = 'popper';\nexport var reference = 'reference';\nexport var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {\n return acc.concat([placement + \"-\" + start, placement + \"-\" + end]);\n}, []);\nexport var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) {\n return acc.concat([placement, placement + \"-\" + start, placement + \"-\" + end]);\n}, []); // modifiers that need to read the DOM\n\nexport var beforeRead = 'beforeRead';\nexport var read = 'read';\nexport var afterRead = 'afterRead'; // pure-logic modifiers\n\nexport var beforeMain = 'beforeMain';\nexport var main = 'main';\nexport var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)\n\nexport var beforeWrite = 'beforeWrite';\nexport var write = 'write';\nexport var afterWrite = 'afterWrite';\nexport var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];", "export default function getNodeName(element) {\n return element ? (element.nodeName || '').toLowerCase() : null;\n}", "export default function getWindow(node) {\n if (node == null) {\n return window;\n }\n\n if (node.toString() !== '[object Window]') {\n var ownerDocument = node.ownerDocument;\n return ownerDocument ? ownerDocument.defaultView || window : window;\n }\n\n return node;\n}", "import getWindow from \"./getWindow.js\";\n\nfunction isElement(node) {\n var OwnElement = getWindow(node).Element;\n return node instanceof OwnElement || node instanceof Element;\n}\n\nfunction isHTMLElement(node) {\n var OwnElement = getWindow(node).HTMLElement;\n return node instanceof OwnElement || node instanceof HTMLElement;\n}\n\nfunction isShadowRoot(node) {\n // IE 11 has no ShadowRoot\n if (typeof ShadowRoot === 'undefined') {\n return false;\n }\n\n var OwnElement = getWindow(node).ShadowRoot;\n return node instanceof OwnElement || node instanceof ShadowRoot;\n}\n\nexport { isElement, isHTMLElement, isShadowRoot };", "import getNodeName from \"../dom-utils/getNodeName.js\";\nimport { isHTMLElement } from \"../dom-utils/instanceOf.js\"; // This modifier takes the styles prepared by the `computeStyles` modifier\n// and applies them to the HTMLElements such as popper and arrow\n\nfunction applyStyles(_ref) {\n var state = _ref.state;\n Object.keys(state.elements).forEach(function (name) {\n var style = state.styles[name] || {};\n var attributes = state.attributes[name] || {};\n var element = state.elements[name]; // arrow is optional + virtual elements\n\n if (!isHTMLElement(element) || !getNodeName(element)) {\n return;\n } // Flow doesn't support to extend this property, but it's the most\n // effective way to apply styles to an HTMLElement\n // $FlowFixMe[cannot-write]\n\n\n Object.assign(element.style, style);\n Object.keys(attributes).forEach(function (name) {\n var value = attributes[name];\n\n if (value === false) {\n element.removeAttribute(name);\n } else {\n element.setAttribute(name, value === true ? '' : value);\n }\n });\n });\n}\n\nfunction effect(_ref2) {\n var state = _ref2.state;\n var initialStyles = {\n popper: {\n position: state.options.strategy,\n left: '0',\n top: '0',\n margin: '0'\n },\n arrow: {\n position: 'absolute'\n },\n reference: {}\n };\n Object.assign(state.elements.popper.style, initialStyles.popper);\n state.styles = initialStyles;\n\n if (state.elements.arrow) {\n Object.assign(state.elements.arrow.style, initialStyles.arrow);\n }\n\n return function () {\n Object.keys(state.elements).forEach(function (name) {\n var element = state.elements[name];\n var attributes = state.attributes[name] || {};\n var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them\n\n var style = styleProperties.reduce(function (style, property) {\n style[property] = '';\n return style;\n }, {}); // arrow is optional + virtual elements\n\n if (!isHTMLElement(element) || !getNodeName(element)) {\n return;\n }\n\n Object.assign(element.style, style);\n Object.keys(attributes).forEach(function (attribute) {\n element.removeAttribute(attribute);\n });\n });\n };\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'applyStyles',\n enabled: true,\n phase: 'write',\n fn: applyStyles,\n effect: effect,\n requires: ['computeStyles']\n};", "import { auto } from \"../enums.js\";\nexport default function getBasePlacement(placement) {\n return placement.split('-')[0];\n}", "export var max = Math.max;\nexport var min = Math.min;\nexport var round = Math.round;", "export default function getUAString() {\n var uaData = navigator.userAgentData;\n\n if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) {\n return uaData.brands.map(function (item) {\n return item.brand + \"/\" + item.version;\n }).join(' ');\n }\n\n return navigator.userAgent;\n}", "import getUAString from \"../utils/userAgent.js\";\nexport default function isLayoutViewport() {\n return !/^((?!chrome|android).)*safari/i.test(getUAString());\n}", "import { isElement, isHTMLElement } from \"./instanceOf.js\";\nimport { round } from \"../utils/math.js\";\nimport getWindow from \"./getWindow.js\";\nimport isLayoutViewport from \"./isLayoutViewport.js\";\nexport default function getBoundingClientRect(element, includeScale, isFixedStrategy) {\n if (includeScale === void 0) {\n includeScale = false;\n }\n\n if (isFixedStrategy === void 0) {\n isFixedStrategy = false;\n }\n\n var clientRect = element.getBoundingClientRect();\n var scaleX = 1;\n var scaleY = 1;\n\n if (includeScale && isHTMLElement(element)) {\n scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1;\n scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1;\n }\n\n var _ref = isElement(element) ? getWindow(element) : window,\n visualViewport = _ref.visualViewport;\n\n var addVisualOffsets = !isLayoutViewport() && isFixedStrategy;\n var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX;\n var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY;\n var width = clientRect.width / scaleX;\n var height = clientRect.height / scaleY;\n return {\n width: width,\n height: height,\n top: y,\n right: x + width,\n bottom: y + height,\n left: x,\n x: x,\n y: y\n };\n}", "import getBoundingClientRect from \"./getBoundingClientRect.js\"; // Returns the layout rect of an element relative to its offsetParent. Layout\n// means it doesn't take into account transforms.\n\nexport default function getLayoutRect(element) {\n var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed.\n // Fixes https://github.com/popperjs/popper-core/issues/1223\n\n var width = element.offsetWidth;\n var height = element.offsetHeight;\n\n if (Math.abs(clientRect.width - width) <= 1) {\n width = clientRect.width;\n }\n\n if (Math.abs(clientRect.height - height) <= 1) {\n height = clientRect.height;\n }\n\n return {\n x: element.offsetLeft,\n y: element.offsetTop,\n width: width,\n height: height\n };\n}", "import { isShadowRoot } from \"./instanceOf.js\";\nexport default function contains(parent, child) {\n var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method\n\n if (parent.contains(child)) {\n return true;\n } // then fallback to custom implementation with Shadow DOM support\n else if (rootNode && isShadowRoot(rootNode)) {\n var next = child;\n\n do {\n if (next && parent.isSameNode(next)) {\n return true;\n } // $FlowFixMe[prop-missing]: need a better way to handle this...\n\n\n next = next.parentNode || next.host;\n } while (next);\n } // Give up, the result is false\n\n\n return false;\n}", "import getWindow from \"./getWindow.js\";\nexport default function getComputedStyle(element) {\n return getWindow(element).getComputedStyle(element);\n}", "import getNodeName from \"./getNodeName.js\";\nexport default function isTableElement(element) {\n return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;\n}", "import { isElement } from \"./instanceOf.js\";\nexport default function getDocumentElement(element) {\n // $FlowFixMe[incompatible-return]: assume body is always available\n return ((isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing]\n element.document) || window.document).documentElement;\n}", "import getNodeName from \"./getNodeName.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport { isShadowRoot } from \"./instanceOf.js\";\nexport default function getParentNode(element) {\n if (getNodeName(element) === 'html') {\n return element;\n }\n\n return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle\n // $FlowFixMe[incompatible-return]\n // $FlowFixMe[prop-missing]\n element.assignedSlot || // step into the shadow DOM of the parent of a slotted node\n element.parentNode || ( // DOM Element detected\n isShadowRoot(element) ? element.host : null) || // ShadowRoot detected\n // $FlowFixMe[incompatible-call]: HTMLElement is a Node\n getDocumentElement(element) // fallback\n\n );\n}", "import getWindow from \"./getWindow.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport { isHTMLElement, isShadowRoot } from \"./instanceOf.js\";\nimport isTableElement from \"./isTableElement.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport getUAString from \"../utils/userAgent.js\";\n\nfunction getTrueOffsetParent(element) {\n if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837\n getComputedStyle(element).position === 'fixed') {\n return null;\n }\n\n return element.offsetParent;\n} // `.offsetParent` reports `null` for fixed elements, while absolute elements\n// return the containing block\n\n\nfunction getContainingBlock(element) {\n var isFirefox = /firefox/i.test(getUAString());\n var isIE = /Trident/i.test(getUAString());\n\n if (isIE && isHTMLElement(element)) {\n // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport\n var elementCss = getComputedStyle(element);\n\n if (elementCss.position === 'fixed') {\n return null;\n }\n }\n\n var currentNode = getParentNode(element);\n\n if (isShadowRoot(currentNode)) {\n currentNode = currentNode.host;\n }\n\n while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) {\n var css = getComputedStyle(currentNode); // This is non-exhaustive but covers the most common CSS properties that\n // create a containing block.\n // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n\n 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') {\n return currentNode;\n } else {\n currentNode = currentNode.parentNode;\n }\n }\n\n return null;\n} // Gets the closest ancestor positioned element. Handles some edge cases,\n// such as table ancestors and cross browser bugs.\n\n\nexport default function getOffsetParent(element) {\n var window = getWindow(element);\n var offsetParent = getTrueOffsetParent(element);\n\n while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === 'static') {\n offsetParent = getTrueOffsetParent(offsetParent);\n }\n\n if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle(offsetParent).position === 'static')) {\n return window;\n }\n\n return offsetParent || getContainingBlock(element) || window;\n}", "export default function getMainAxisFromPlacement(placement) {\n return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y';\n}", "import { max as mathMax, min as mathMin } from \"./math.js\";\nexport function within(min, value, max) {\n return mathMax(min, mathMin(value, max));\n}\nexport function withinMaxClamp(min, value, max) {\n var v = within(min, value, max);\n return v > max ? max : v;\n}", "export default function getFreshSideObject() {\n return {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0\n };\n}", "import getFreshSideObject from \"./getFreshSideObject.js\";\nexport default function mergePaddingObject(paddingObject) {\n return Object.assign({}, getFreshSideObject(), paddingObject);\n}", "export default function expandToHashMap(value, keys) {\n return keys.reduce(function (hashMap, key) {\n hashMap[key] = value;\n return hashMap;\n }, {});\n}", "import getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getLayoutRect from \"../dom-utils/getLayoutRect.js\";\nimport contains from \"../dom-utils/contains.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport getMainAxisFromPlacement from \"../utils/getMainAxisFromPlacement.js\";\nimport { within } from \"../utils/within.js\";\nimport mergePaddingObject from \"../utils/mergePaddingObject.js\";\nimport expandToHashMap from \"../utils/expandToHashMap.js\";\nimport { left, right, basePlacements, top, bottom } from \"../enums.js\";\nimport { isHTMLElement } from \"../dom-utils/instanceOf.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar toPaddingObject = function toPaddingObject(padding, state) {\n padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, {\n placement: state.placement\n })) : padding;\n return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));\n};\n\nfunction arrow(_ref) {\n var _state$modifiersData$;\n\n var state = _ref.state,\n name = _ref.name,\n options = _ref.options;\n var arrowElement = state.elements.arrow;\n var popperOffsets = state.modifiersData.popperOffsets;\n var basePlacement = getBasePlacement(state.placement);\n var axis = getMainAxisFromPlacement(basePlacement);\n var isVertical = [left, right].indexOf(basePlacement) >= 0;\n var len = isVertical ? 'height' : 'width';\n\n if (!arrowElement || !popperOffsets) {\n return;\n }\n\n var paddingObject = toPaddingObject(options.padding, state);\n var arrowRect = getLayoutRect(arrowElement);\n var minProp = axis === 'y' ? top : left;\n var maxProp = axis === 'y' ? bottom : right;\n var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];\n var startDiff = popperOffsets[axis] - state.rects.reference[axis];\n var arrowOffsetParent = getOffsetParent(arrowElement);\n var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;\n var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is\n // outside of the popper bounds\n\n var min = paddingObject[minProp];\n var max = clientSize - arrowRect[len] - paddingObject[maxProp];\n var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;\n var offset = within(min, center, max); // Prevents breaking syntax highlighting...\n\n var axisProp = axis;\n state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);\n}\n\nfunction effect(_ref2) {\n var state = _ref2.state,\n options = _ref2.options;\n var _options$element = options.element,\n arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element;\n\n if (arrowElement == null) {\n return;\n } // CSS selector\n\n\n if (typeof arrowElement === 'string') {\n arrowElement = state.elements.popper.querySelector(arrowElement);\n\n if (!arrowElement) {\n return;\n }\n }\n\n if (process.env.NODE_ENV !== \"production\") {\n if (!isHTMLElement(arrowElement)) {\n console.error(['Popper: \"arrow\" element must be an HTMLElement (not an SVGElement).', 'To use an SVG arrow, wrap it in an HTMLElement that will be used as', 'the arrow.'].join(' '));\n }\n }\n\n if (!contains(state.elements.popper, arrowElement)) {\n if (process.env.NODE_ENV !== \"production\") {\n console.error(['Popper: \"arrow\" modifier\\'s `element` must be a child of the popper', 'element.'].join(' '));\n }\n\n return;\n }\n\n state.elements.arrow = arrowElement;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'arrow',\n enabled: true,\n phase: 'main',\n fn: arrow,\n effect: effect,\n requires: ['popperOffsets'],\n requiresIfExists: ['preventOverflow']\n};", "export default function getVariation(placement) {\n return placement.split('-')[1];\n}", "import { top, left, right, bottom, end } from \"../enums.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport getWindow from \"../dom-utils/getWindow.js\";\nimport getDocumentElement from \"../dom-utils/getDocumentElement.js\";\nimport getComputedStyle from \"../dom-utils/getComputedStyle.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getVariation from \"../utils/getVariation.js\";\nimport { round } from \"../utils/math.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar unsetSides = {\n top: 'auto',\n right: 'auto',\n bottom: 'auto',\n left: 'auto'\n}; // Round the offsets to the nearest suitable subpixel based on the DPR.\n// Zooming can change the DPR, but it seems to report a value that will\n// cleanly divide the values into the appropriate subpixels.\n\nfunction roundOffsetsByDPR(_ref, win) {\n var x = _ref.x,\n y = _ref.y;\n var dpr = win.devicePixelRatio || 1;\n return {\n x: round(x * dpr) / dpr || 0,\n y: round(y * dpr) / dpr || 0\n };\n}\n\nexport function mapToStyles(_ref2) {\n var _Object$assign2;\n\n var popper = _ref2.popper,\n popperRect = _ref2.popperRect,\n placement = _ref2.placement,\n variation = _ref2.variation,\n offsets = _ref2.offsets,\n position = _ref2.position,\n gpuAcceleration = _ref2.gpuAcceleration,\n adaptive = _ref2.adaptive,\n roundOffsets = _ref2.roundOffsets,\n isFixed = _ref2.isFixed;\n var _offsets$x = offsets.x,\n x = _offsets$x === void 0 ? 0 : _offsets$x,\n _offsets$y = offsets.y,\n y = _offsets$y === void 0 ? 0 : _offsets$y;\n\n var _ref3 = typeof roundOffsets === 'function' ? roundOffsets({\n x: x,\n y: y\n }) : {\n x: x,\n y: y\n };\n\n x = _ref3.x;\n y = _ref3.y;\n var hasX = offsets.hasOwnProperty('x');\n var hasY = offsets.hasOwnProperty('y');\n var sideX = left;\n var sideY = top;\n var win = window;\n\n if (adaptive) {\n var offsetParent = getOffsetParent(popper);\n var heightProp = 'clientHeight';\n var widthProp = 'clientWidth';\n\n if (offsetParent === getWindow(popper)) {\n offsetParent = getDocumentElement(popper);\n\n if (getComputedStyle(offsetParent).position !== 'static' && position === 'absolute') {\n heightProp = 'scrollHeight';\n widthProp = 'scrollWidth';\n }\n } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it\n\n\n offsetParent = offsetParent;\n\n if (placement === top || (placement === left || placement === right) && variation === end) {\n sideY = bottom;\n var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : // $FlowFixMe[prop-missing]\n offsetParent[heightProp];\n y -= offsetY - popperRect.height;\n y *= gpuAcceleration ? 1 : -1;\n }\n\n if (placement === left || (placement === top || placement === bottom) && variation === end) {\n sideX = right;\n var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : // $FlowFixMe[prop-missing]\n offsetParent[widthProp];\n x -= offsetX - popperRect.width;\n x *= gpuAcceleration ? 1 : -1;\n }\n }\n\n var commonStyles = Object.assign({\n position: position\n }, adaptive && unsetSides);\n\n var _ref4 = roundOffsets === true ? roundOffsetsByDPR({\n x: x,\n y: y\n }, getWindow(popper)) : {\n x: x,\n y: y\n };\n\n x = _ref4.x;\n y = _ref4.y;\n\n if (gpuAcceleration) {\n var _Object$assign;\n\n return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? \"translate(\" + x + \"px, \" + y + \"px)\" : \"translate3d(\" + x + \"px, \" + y + \"px, 0)\", _Object$assign));\n }\n\n return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + \"px\" : '', _Object$assign2[sideX] = hasX ? x + \"px\" : '', _Object$assign2.transform = '', _Object$assign2));\n}\n\nfunction computeStyles(_ref5) {\n var state = _ref5.state,\n options = _ref5.options;\n var _options$gpuAccelerat = options.gpuAcceleration,\n gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,\n _options$adaptive = options.adaptive,\n adaptive = _options$adaptive === void 0 ? true : _options$adaptive,\n _options$roundOffsets = options.roundOffsets,\n roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;\n\n if (process.env.NODE_ENV !== \"production\") {\n var transitionProperty = getComputedStyle(state.elements.popper).transitionProperty || '';\n\n if (adaptive && ['transform', 'top', 'right', 'bottom', 'left'].some(function (property) {\n return transitionProperty.indexOf(property) >= 0;\n })) {\n console.warn(['Popper: Detected CSS transitions on at least one of the following', 'CSS properties: \"transform\", \"top\", \"right\", \"bottom\", \"left\".', '\\n\\n', 'Disable the \"computeStyles\" modifier\\'s `adaptive` option to allow', 'for smooth transitions, or remove these properties from the CSS', 'transition declaration on the popper element if only transitioning', 'opacity or background-color for example.', '\\n\\n', 'We recommend using the popper element as a wrapper around an inner', 'element that can have any CSS property transitioned for animations.'].join(' '));\n }\n }\n\n var commonStyles = {\n placement: getBasePlacement(state.placement),\n variation: getVariation(state.placement),\n popper: state.elements.popper,\n popperRect: state.rects.popper,\n gpuAcceleration: gpuAcceleration,\n isFixed: state.options.strategy === 'fixed'\n };\n\n if (state.modifiersData.popperOffsets != null) {\n state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {\n offsets: state.modifiersData.popperOffsets,\n position: state.options.strategy,\n adaptive: adaptive,\n roundOffsets: roundOffsets\n })));\n }\n\n if (state.modifiersData.arrow != null) {\n state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {\n offsets: state.modifiersData.arrow,\n position: 'absolute',\n adaptive: false,\n roundOffsets: roundOffsets\n })));\n }\n\n state.attributes.popper = Object.assign({}, state.attributes.popper, {\n 'data-popper-placement': state.placement\n });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'computeStyles',\n enabled: true,\n phase: 'beforeWrite',\n fn: computeStyles,\n data: {}\n};", "import getWindow from \"../dom-utils/getWindow.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar passive = {\n passive: true\n};\n\nfunction effect(_ref) {\n var state = _ref.state,\n instance = _ref.instance,\n options = _ref.options;\n var _options$scroll = options.scroll,\n scroll = _options$scroll === void 0 ? true : _options$scroll,\n _options$resize = options.resize,\n resize = _options$resize === void 0 ? true : _options$resize;\n var window = getWindow(state.elements.popper);\n var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);\n\n if (scroll) {\n scrollParents.forEach(function (scrollParent) {\n scrollParent.addEventListener('scroll', instance.update, passive);\n });\n }\n\n if (resize) {\n window.addEventListener('resize', instance.update, passive);\n }\n\n return function () {\n if (scroll) {\n scrollParents.forEach(function (scrollParent) {\n scrollParent.removeEventListener('scroll', instance.update, passive);\n });\n }\n\n if (resize) {\n window.removeEventListener('resize', instance.update, passive);\n }\n };\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'eventListeners',\n enabled: true,\n phase: 'write',\n fn: function fn() {},\n effect: effect,\n data: {}\n};", "var hash = {\n left: 'right',\n right: 'left',\n bottom: 'top',\n top: 'bottom'\n};\nexport default function getOppositePlacement(placement) {\n return placement.replace(/left|right|bottom|top/g, function (matched) {\n return hash[matched];\n });\n}", "var hash = {\n start: 'end',\n end: 'start'\n};\nexport default function getOppositeVariationPlacement(placement) {\n return placement.replace(/start|end/g, function (matched) {\n return hash[matched];\n });\n}", "import getWindow from \"./getWindow.js\";\nexport default function getWindowScroll(node) {\n var win = getWindow(node);\n var scrollLeft = win.pageXOffset;\n var scrollTop = win.pageYOffset;\n return {\n scrollLeft: scrollLeft,\n scrollTop: scrollTop\n };\n}", "import getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getWindowScroll from \"./getWindowScroll.js\";\nexport default function getWindowScrollBarX(element) {\n // If has a CSS width greater than the viewport, then this will be\n // incorrect for RTL.\n // Popper 1 is broken in this case and never had a bug report so let's assume\n // it's not an issue. I don't think anyone ever specifies width on \n // anyway.\n // Browsers where the left scrollbar doesn't cause an issue report `0` for\n // this (e.g. Edge 2019, IE11, Safari)\n return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;\n}", "import getWindow from \"./getWindow.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport isLayoutViewport from \"./isLayoutViewport.js\";\nexport default function getViewportRect(element, strategy) {\n var win = getWindow(element);\n var html = getDocumentElement(element);\n var visualViewport = win.visualViewport;\n var width = html.clientWidth;\n var height = html.clientHeight;\n var x = 0;\n var y = 0;\n\n if (visualViewport) {\n width = visualViewport.width;\n height = visualViewport.height;\n var layoutViewport = isLayoutViewport();\n\n if (layoutViewport || !layoutViewport && strategy === 'fixed') {\n x = visualViewport.offsetLeft;\n y = visualViewport.offsetTop;\n }\n }\n\n return {\n width: width,\n height: height,\n x: x + getWindowScrollBarX(element),\n y: y\n };\n}", "import getDocumentElement from \"./getDocumentElement.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport getWindowScroll from \"./getWindowScroll.js\";\nimport { max } from \"../utils/math.js\"; // Gets the entire size of the scrollable document area, even extending outside\n// of the `` and `` rect bounds if horizontally scrollable\n\nexport default function getDocumentRect(element) {\n var _element$ownerDocumen;\n\n var html = getDocumentElement(element);\n var winScroll = getWindowScroll(element);\n var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;\n var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);\n var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);\n var x = -winScroll.scrollLeft + getWindowScrollBarX(element);\n var y = -winScroll.scrollTop;\n\n if (getComputedStyle(body || html).direction === 'rtl') {\n x += max(html.clientWidth, body ? body.clientWidth : 0) - width;\n }\n\n return {\n width: width,\n height: height,\n x: x,\n y: y\n };\n}", "import getComputedStyle from \"./getComputedStyle.js\";\nexport default function isScrollParent(element) {\n // Firefox wants us to check `-x` and `-y` variations as well\n var _getComputedStyle = getComputedStyle(element),\n overflow = _getComputedStyle.overflow,\n overflowX = _getComputedStyle.overflowX,\n overflowY = _getComputedStyle.overflowY;\n\n return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);\n}", "import getParentNode from \"./getParentNode.js\";\nimport isScrollParent from \"./isScrollParent.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nexport default function getScrollParent(node) {\n if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {\n // $FlowFixMe[incompatible-return]: assume body is always available\n return node.ownerDocument.body;\n }\n\n if (isHTMLElement(node) && isScrollParent(node)) {\n return node;\n }\n\n return getScrollParent(getParentNode(node));\n}", "import getScrollParent from \"./getScrollParent.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport getWindow from \"./getWindow.js\";\nimport isScrollParent from \"./isScrollParent.js\";\n/*\ngiven a DOM element, return the list of all scroll parents, up the list of ancesors\nuntil we get to the top window object. This list is what we attach scroll listeners\nto, because if any of these parent elements scroll, we'll need to re-calculate the\nreference element's position.\n*/\n\nexport default function listScrollParents(element, list) {\n var _element$ownerDocumen;\n\n if (list === void 0) {\n list = [];\n }\n\n var scrollParent = getScrollParent(element);\n var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);\n var win = getWindow(scrollParent);\n var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;\n var updatedList = list.concat(target);\n return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here\n updatedList.concat(listScrollParents(getParentNode(target)));\n}", "export default function rectToClientRect(rect) {\n return Object.assign({}, rect, {\n left: rect.x,\n top: rect.y,\n right: rect.x + rect.width,\n bottom: rect.y + rect.height\n });\n}", "import { viewport } from \"../enums.js\";\nimport getViewportRect from \"./getViewportRect.js\";\nimport getDocumentRect from \"./getDocumentRect.js\";\nimport listScrollParents from \"./listScrollParents.js\";\nimport getOffsetParent from \"./getOffsetParent.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport { isElement, isHTMLElement } from \"./instanceOf.js\";\nimport getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport contains from \"./contains.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport rectToClientRect from \"../utils/rectToClientRect.js\";\nimport { max, min } from \"../utils/math.js\";\n\nfunction getInnerBoundingClientRect(element, strategy) {\n var rect = getBoundingClientRect(element, false, strategy === 'fixed');\n rect.top = rect.top + element.clientTop;\n rect.left = rect.left + element.clientLeft;\n rect.bottom = rect.top + element.clientHeight;\n rect.right = rect.left + element.clientWidth;\n rect.width = element.clientWidth;\n rect.height = element.clientHeight;\n rect.x = rect.left;\n rect.y = rect.top;\n return rect;\n}\n\nfunction getClientRectFromMixedType(element, clippingParent, strategy) {\n return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element)));\n} // A \"clipping parent\" is an overflowable container with the characteristic of\n// clipping (or hiding) overflowing elements with a position different from\n// `initial`\n\n\nfunction getClippingParents(element) {\n var clippingParents = listScrollParents(getParentNode(element));\n var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle(element).position) >= 0;\n var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;\n\n if (!isElement(clipperElement)) {\n return [];\n } // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414\n\n\n return clippingParents.filter(function (clippingParent) {\n return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body';\n });\n} // Gets the maximum area that the element is visible in due to any number of\n// clipping parents\n\n\nexport default function getClippingRect(element, boundary, rootBoundary, strategy) {\n var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);\n var clippingParents = [].concat(mainClippingParents, [rootBoundary]);\n var firstClippingParent = clippingParents[0];\n var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {\n var rect = getClientRectFromMixedType(element, clippingParent, strategy);\n accRect.top = max(rect.top, accRect.top);\n accRect.right = min(rect.right, accRect.right);\n accRect.bottom = min(rect.bottom, accRect.bottom);\n accRect.left = max(rect.left, accRect.left);\n return accRect;\n }, getClientRectFromMixedType(element, firstClippingParent, strategy));\n clippingRect.width = clippingRect.right - clippingRect.left;\n clippingRect.height = clippingRect.bottom - clippingRect.top;\n clippingRect.x = clippingRect.left;\n clippingRect.y = clippingRect.top;\n return clippingRect;\n}", "import getBasePlacement from \"./getBasePlacement.js\";\nimport getVariation from \"./getVariation.js\";\nimport getMainAxisFromPlacement from \"./getMainAxisFromPlacement.js\";\nimport { top, right, bottom, left, start, end } from \"../enums.js\";\nexport default function computeOffsets(_ref) {\n var reference = _ref.reference,\n element = _ref.element,\n placement = _ref.placement;\n var basePlacement = placement ? getBasePlacement(placement) : null;\n var variation = placement ? getVariation(placement) : null;\n var commonX = reference.x + reference.width / 2 - element.width / 2;\n var commonY = reference.y + reference.height / 2 - element.height / 2;\n var offsets;\n\n switch (basePlacement) {\n case top:\n offsets = {\n x: commonX,\n y: reference.y - element.height\n };\n break;\n\n case bottom:\n offsets = {\n x: commonX,\n y: reference.y + reference.height\n };\n break;\n\n case right:\n offsets = {\n x: reference.x + reference.width,\n y: commonY\n };\n break;\n\n case left:\n offsets = {\n x: reference.x - element.width,\n y: commonY\n };\n break;\n\n default:\n offsets = {\n x: reference.x,\n y: reference.y\n };\n }\n\n var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;\n\n if (mainAxis != null) {\n var len = mainAxis === 'y' ? 'height' : 'width';\n\n switch (variation) {\n case start:\n offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);\n break;\n\n case end:\n offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);\n break;\n\n default:\n }\n }\n\n return offsets;\n}", "import getClippingRect from \"../dom-utils/getClippingRect.js\";\nimport getDocumentElement from \"../dom-utils/getDocumentElement.js\";\nimport getBoundingClientRect from \"../dom-utils/getBoundingClientRect.js\";\nimport computeOffsets from \"./computeOffsets.js\";\nimport rectToClientRect from \"./rectToClientRect.js\";\nimport { clippingParents, reference, popper, bottom, top, right, basePlacements, viewport } from \"../enums.js\";\nimport { isElement } from \"../dom-utils/instanceOf.js\";\nimport mergePaddingObject from \"./mergePaddingObject.js\";\nimport expandToHashMap from \"./expandToHashMap.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport default function detectOverflow(state, options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n _options$placement = _options.placement,\n placement = _options$placement === void 0 ? state.placement : _options$placement,\n _options$strategy = _options.strategy,\n strategy = _options$strategy === void 0 ? state.strategy : _options$strategy,\n _options$boundary = _options.boundary,\n boundary = _options$boundary === void 0 ? clippingParents : _options$boundary,\n _options$rootBoundary = _options.rootBoundary,\n rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary,\n _options$elementConte = _options.elementContext,\n elementContext = _options$elementConte === void 0 ? popper : _options$elementConte,\n _options$altBoundary = _options.altBoundary,\n altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary,\n _options$padding = _options.padding,\n padding = _options$padding === void 0 ? 0 : _options$padding;\n var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));\n var altContext = elementContext === popper ? reference : popper;\n var popperRect = state.rects.popper;\n var element = state.elements[altBoundary ? altContext : elementContext];\n var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy);\n var referenceClientRect = getBoundingClientRect(state.elements.reference);\n var popperOffsets = computeOffsets({\n reference: referenceClientRect,\n element: popperRect,\n strategy: 'absolute',\n placement: placement\n });\n var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets));\n var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect\n // 0 or negative = within the clipping rect\n\n var overflowOffsets = {\n top: clippingClientRect.top - elementClientRect.top + paddingObject.top,\n bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,\n left: clippingClientRect.left - elementClientRect.left + paddingObject.left,\n right: elementClientRect.right - clippingClientRect.right + paddingObject.right\n };\n var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element\n\n if (elementContext === popper && offsetData) {\n var offset = offsetData[placement];\n Object.keys(overflowOffsets).forEach(function (key) {\n var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;\n var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x';\n overflowOffsets[key] += offset[axis] * multiply;\n });\n }\n\n return overflowOffsets;\n}", "import getVariation from \"./getVariation.js\";\nimport { variationPlacements, basePlacements, placements as allPlacements } from \"../enums.js\";\nimport detectOverflow from \"./detectOverflow.js\";\nimport getBasePlacement from \"./getBasePlacement.js\";\nexport default function computeAutoPlacement(state, options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n placement = _options.placement,\n boundary = _options.boundary,\n rootBoundary = _options.rootBoundary,\n padding = _options.padding,\n flipVariations = _options.flipVariations,\n _options$allowedAutoP = _options.allowedAutoPlacements,\n allowedAutoPlacements = _options$allowedAutoP === void 0 ? allPlacements : _options$allowedAutoP;\n var variation = getVariation(placement);\n var placements = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) {\n return getVariation(placement) === variation;\n }) : basePlacements;\n var allowedPlacements = placements.filter(function (placement) {\n return allowedAutoPlacements.indexOf(placement) >= 0;\n });\n\n if (allowedPlacements.length === 0) {\n allowedPlacements = placements;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.error(['Popper: The `allowedAutoPlacements` option did not allow any', 'placements. Ensure the `placement` option matches the variation', 'of the allowed placements.', 'For example, \"auto\" cannot be used to allow \"bottom-start\".', 'Use \"auto-start\" instead.'].join(' '));\n }\n } // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...\n\n\n var overflows = allowedPlacements.reduce(function (acc, placement) {\n acc[placement] = detectOverflow(state, {\n placement: placement,\n boundary: boundary,\n rootBoundary: rootBoundary,\n padding: padding\n })[getBasePlacement(placement)];\n return acc;\n }, {});\n return Object.keys(overflows).sort(function (a, b) {\n return overflows[a] - overflows[b];\n });\n}", "import getOppositePlacement from \"../utils/getOppositePlacement.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getOppositeVariationPlacement from \"../utils/getOppositeVariationPlacement.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\nimport computeAutoPlacement from \"../utils/computeAutoPlacement.js\";\nimport { bottom, top, start, right, left, auto } from \"../enums.js\";\nimport getVariation from \"../utils/getVariation.js\"; // eslint-disable-next-line import/no-unused-modules\n\nfunction getExpandedFallbackPlacements(placement) {\n if (getBasePlacement(placement) === auto) {\n return [];\n }\n\n var oppositePlacement = getOppositePlacement(placement);\n return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];\n}\n\nfunction flip(_ref) {\n var state = _ref.state,\n options = _ref.options,\n name = _ref.name;\n\n if (state.modifiersData[name]._skip) {\n return;\n }\n\n var _options$mainAxis = options.mainAxis,\n checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,\n _options$altAxis = options.altAxis,\n checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,\n specifiedFallbackPlacements = options.fallbackPlacements,\n padding = options.padding,\n boundary = options.boundary,\n rootBoundary = options.rootBoundary,\n altBoundary = options.altBoundary,\n _options$flipVariatio = options.flipVariations,\n flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,\n allowedAutoPlacements = options.allowedAutoPlacements;\n var preferredPlacement = state.options.placement;\n var basePlacement = getBasePlacement(preferredPlacement);\n var isBasePlacement = basePlacement === preferredPlacement;\n var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));\n var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {\n return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, {\n placement: placement,\n boundary: boundary,\n rootBoundary: rootBoundary,\n padding: padding,\n flipVariations: flipVariations,\n allowedAutoPlacements: allowedAutoPlacements\n }) : placement);\n }, []);\n var referenceRect = state.rects.reference;\n var popperRect = state.rects.popper;\n var checksMap = new Map();\n var makeFallbackChecks = true;\n var firstFittingPlacement = placements[0];\n\n for (var i = 0; i < placements.length; i++) {\n var placement = placements[i];\n\n var _basePlacement = getBasePlacement(placement);\n\n var isStartVariation = getVariation(placement) === start;\n var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;\n var len = isVertical ? 'width' : 'height';\n var overflow = detectOverflow(state, {\n placement: placement,\n boundary: boundary,\n rootBoundary: rootBoundary,\n altBoundary: altBoundary,\n padding: padding\n });\n var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;\n\n if (referenceRect[len] > popperRect[len]) {\n mainVariationSide = getOppositePlacement(mainVariationSide);\n }\n\n var altVariationSide = getOppositePlacement(mainVariationSide);\n var checks = [];\n\n if (checkMainAxis) {\n checks.push(overflow[_basePlacement] <= 0);\n }\n\n if (checkAltAxis) {\n checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);\n }\n\n if (checks.every(function (check) {\n return check;\n })) {\n firstFittingPlacement = placement;\n makeFallbackChecks = false;\n break;\n }\n\n checksMap.set(placement, checks);\n }\n\n if (makeFallbackChecks) {\n // `2` may be desired in some cases \u2013 research later\n var numberOfChecks = flipVariations ? 3 : 1;\n\n var _loop = function _loop(_i) {\n var fittingPlacement = placements.find(function (placement) {\n var checks = checksMap.get(placement);\n\n if (checks) {\n return checks.slice(0, _i).every(function (check) {\n return check;\n });\n }\n });\n\n if (fittingPlacement) {\n firstFittingPlacement = fittingPlacement;\n return \"break\";\n }\n };\n\n for (var _i = numberOfChecks; _i > 0; _i--) {\n var _ret = _loop(_i);\n\n if (_ret === \"break\") break;\n }\n }\n\n if (state.placement !== firstFittingPlacement) {\n state.modifiersData[name]._skip = true;\n state.placement = firstFittingPlacement;\n state.reset = true;\n }\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'flip',\n enabled: true,\n phase: 'main',\n fn: flip,\n requiresIfExists: ['offset'],\n data: {\n _skip: false\n }\n};", "import { top, bottom, left, right } from \"../enums.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\n\nfunction getSideOffsets(overflow, rect, preventedOffsets) {\n if (preventedOffsets === void 0) {\n preventedOffsets = {\n x: 0,\n y: 0\n };\n }\n\n return {\n top: overflow.top - rect.height - preventedOffsets.y,\n right: overflow.right - rect.width + preventedOffsets.x,\n bottom: overflow.bottom - rect.height + preventedOffsets.y,\n left: overflow.left - rect.width - preventedOffsets.x\n };\n}\n\nfunction isAnySideFullyClipped(overflow) {\n return [top, right, bottom, left].some(function (side) {\n return overflow[side] >= 0;\n });\n}\n\nfunction hide(_ref) {\n var state = _ref.state,\n name = _ref.name;\n var referenceRect = state.rects.reference;\n var popperRect = state.rects.popper;\n var preventedOffsets = state.modifiersData.preventOverflow;\n var referenceOverflow = detectOverflow(state, {\n elementContext: 'reference'\n });\n var popperAltOverflow = detectOverflow(state, {\n altBoundary: true\n });\n var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);\n var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);\n var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);\n var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);\n state.modifiersData[name] = {\n referenceClippingOffsets: referenceClippingOffsets,\n popperEscapeOffsets: popperEscapeOffsets,\n isReferenceHidden: isReferenceHidden,\n hasPopperEscaped: hasPopperEscaped\n };\n state.attributes.popper = Object.assign({}, state.attributes.popper, {\n 'data-popper-reference-hidden': isReferenceHidden,\n 'data-popper-escaped': hasPopperEscaped\n });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'hide',\n enabled: true,\n phase: 'main',\n requiresIfExists: ['preventOverflow'],\n fn: hide\n};", "import getBasePlacement from \"../utils/getBasePlacement.js\";\nimport { top, left, right, placements } from \"../enums.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport function distanceAndSkiddingToXY(placement, rects, offset) {\n var basePlacement = getBasePlacement(placement);\n var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;\n\n var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, {\n placement: placement\n })) : offset,\n skidding = _ref[0],\n distance = _ref[1];\n\n skidding = skidding || 0;\n distance = (distance || 0) * invertDistance;\n return [left, right].indexOf(basePlacement) >= 0 ? {\n x: distance,\n y: skidding\n } : {\n x: skidding,\n y: distance\n };\n}\n\nfunction offset(_ref2) {\n var state = _ref2.state,\n options = _ref2.options,\n name = _ref2.name;\n var _options$offset = options.offset,\n offset = _options$offset === void 0 ? [0, 0] : _options$offset;\n var data = placements.reduce(function (acc, placement) {\n acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset);\n return acc;\n }, {});\n var _data$state$placement = data[state.placement],\n x = _data$state$placement.x,\n y = _data$state$placement.y;\n\n if (state.modifiersData.popperOffsets != null) {\n state.modifiersData.popperOffsets.x += x;\n state.modifiersData.popperOffsets.y += y;\n }\n\n state.modifiersData[name] = data;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'offset',\n enabled: true,\n phase: 'main',\n requires: ['popperOffsets'],\n fn: offset\n};", "import computeOffsets from \"../utils/computeOffsets.js\";\n\nfunction popperOffsets(_ref) {\n var state = _ref.state,\n name = _ref.name;\n // Offsets are the actual position the popper needs to have to be\n // properly positioned near its reference element\n // This is the most basic placement, and will be adjusted by\n // the modifiers in the next step\n state.modifiersData[name] = computeOffsets({\n reference: state.rects.reference,\n element: state.rects.popper,\n strategy: 'absolute',\n placement: state.placement\n });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'popperOffsets',\n enabled: true,\n phase: 'read',\n fn: popperOffsets,\n data: {}\n};", "export default function getAltAxis(axis) {\n return axis === 'x' ? 'y' : 'x';\n}", "import { top, left, right, bottom, start } from \"../enums.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getMainAxisFromPlacement from \"../utils/getMainAxisFromPlacement.js\";\nimport getAltAxis from \"../utils/getAltAxis.js\";\nimport { within, withinMaxClamp } from \"../utils/within.js\";\nimport getLayoutRect from \"../dom-utils/getLayoutRect.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\nimport getVariation from \"../utils/getVariation.js\";\nimport getFreshSideObject from \"../utils/getFreshSideObject.js\";\nimport { min as mathMin, max as mathMax } from \"../utils/math.js\";\n\nfunction preventOverflow(_ref) {\n var state = _ref.state,\n options = _ref.options,\n name = _ref.name;\n var _options$mainAxis = options.mainAxis,\n checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,\n _options$altAxis = options.altAxis,\n checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis,\n boundary = options.boundary,\n rootBoundary = options.rootBoundary,\n altBoundary = options.altBoundary,\n padding = options.padding,\n _options$tether = options.tether,\n tether = _options$tether === void 0 ? true : _options$tether,\n _options$tetherOffset = options.tetherOffset,\n tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;\n var overflow = detectOverflow(state, {\n boundary: boundary,\n rootBoundary: rootBoundary,\n padding: padding,\n altBoundary: altBoundary\n });\n var basePlacement = getBasePlacement(state.placement);\n var variation = getVariation(state.placement);\n var isBasePlacement = !variation;\n var mainAxis = getMainAxisFromPlacement(basePlacement);\n var altAxis = getAltAxis(mainAxis);\n var popperOffsets = state.modifiersData.popperOffsets;\n var referenceRect = state.rects.reference;\n var popperRect = state.rects.popper;\n var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, {\n placement: state.placement\n })) : tetherOffset;\n var normalizedTetherOffsetValue = typeof tetherOffsetValue === 'number' ? {\n mainAxis: tetherOffsetValue,\n altAxis: tetherOffsetValue\n } : Object.assign({\n mainAxis: 0,\n altAxis: 0\n }, tetherOffsetValue);\n var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;\n var data = {\n x: 0,\n y: 0\n };\n\n if (!popperOffsets) {\n return;\n }\n\n if (checkMainAxis) {\n var _offsetModifierState$;\n\n var mainSide = mainAxis === 'y' ? top : left;\n var altSide = mainAxis === 'y' ? bottom : right;\n var len = mainAxis === 'y' ? 'height' : 'width';\n var offset = popperOffsets[mainAxis];\n var min = offset + overflow[mainSide];\n var max = offset - overflow[altSide];\n var additive = tether ? -popperRect[len] / 2 : 0;\n var minLen = variation === start ? referenceRect[len] : popperRect[len];\n var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go\n // outside the reference bounds\n\n var arrowElement = state.elements.arrow;\n var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {\n width: 0,\n height: 0\n };\n var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject();\n var arrowPaddingMin = arrowPaddingObject[mainSide];\n var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want\n // to include its full size in the calculation. If the reference is small\n // and near the edge of a boundary, the popper can overflow even if the\n // reference is not overflowing as well (e.g. virtual elements with no\n // width or height)\n\n var arrowLen = within(0, referenceRect[len], arrowRect[len]);\n var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;\n var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;\n var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);\n var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;\n var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;\n var tetherMin = offset + minOffset - offsetModifierValue - clientOffset;\n var tetherMax = offset + maxOffset - offsetModifierValue;\n var preventedOffset = within(tether ? mathMin(min, tetherMin) : min, offset, tether ? mathMax(max, tetherMax) : max);\n popperOffsets[mainAxis] = preventedOffset;\n data[mainAxis] = preventedOffset - offset;\n }\n\n if (checkAltAxis) {\n var _offsetModifierState$2;\n\n var _mainSide = mainAxis === 'x' ? top : left;\n\n var _altSide = mainAxis === 'x' ? bottom : right;\n\n var _offset = popperOffsets[altAxis];\n\n var _len = altAxis === 'y' ? 'height' : 'width';\n\n var _min = _offset + overflow[_mainSide];\n\n var _max = _offset - overflow[_altSide];\n\n var isOriginSide = [top, left].indexOf(basePlacement) !== -1;\n\n var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;\n\n var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;\n\n var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;\n\n var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);\n\n popperOffsets[altAxis] = _preventedOffset;\n data[altAxis] = _preventedOffset - _offset;\n }\n\n state.modifiersData[name] = data;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'preventOverflow',\n enabled: true,\n phase: 'main',\n fn: preventOverflow,\n requiresIfExists: ['offset']\n};", "export default function getHTMLElementScroll(element) {\n return {\n scrollLeft: element.scrollLeft,\n scrollTop: element.scrollTop\n };\n}", "import getWindowScroll from \"./getWindowScroll.js\";\nimport getWindow from \"./getWindow.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nimport getHTMLElementScroll from \"./getHTMLElementScroll.js\";\nexport default function getNodeScroll(node) {\n if (node === getWindow(node) || !isHTMLElement(node)) {\n return getWindowScroll(node);\n } else {\n return getHTMLElementScroll(node);\n }\n}", "import getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getNodeScroll from \"./getNodeScroll.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport isScrollParent from \"./isScrollParent.js\";\nimport { round } from \"../utils/math.js\";\n\nfunction isElementScaled(element) {\n var rect = element.getBoundingClientRect();\n var scaleX = round(rect.width) / element.offsetWidth || 1;\n var scaleY = round(rect.height) / element.offsetHeight || 1;\n return scaleX !== 1 || scaleY !== 1;\n} // Returns the composite rect of an element relative to its offsetParent.\n// Composite means it takes into account transforms as well as layout.\n\n\nexport default function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {\n if (isFixed === void 0) {\n isFixed = false;\n }\n\n var isOffsetParentAnElement = isHTMLElement(offsetParent);\n var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent);\n var documentElement = getDocumentElement(offsetParent);\n var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed);\n var scroll = {\n scrollLeft: 0,\n scrollTop: 0\n };\n var offsets = {\n x: 0,\n y: 0\n };\n\n if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078\n isScrollParent(documentElement)) {\n scroll = getNodeScroll(offsetParent);\n }\n\n if (isHTMLElement(offsetParent)) {\n offsets = getBoundingClientRect(offsetParent, true);\n offsets.x += offsetParent.clientLeft;\n offsets.y += offsetParent.clientTop;\n } else if (documentElement) {\n offsets.x = getWindowScrollBarX(documentElement);\n }\n }\n\n return {\n x: rect.left + scroll.scrollLeft - offsets.x,\n y: rect.top + scroll.scrollTop - offsets.y,\n width: rect.width,\n height: rect.height\n };\n}", "import { modifierPhases } from \"../enums.js\"; // source: https://stackoverflow.com/questions/49875255\n\nfunction order(modifiers) {\n var map = new Map();\n var visited = new Set();\n var result = [];\n modifiers.forEach(function (modifier) {\n map.set(modifier.name, modifier);\n }); // On visiting object, check for its dependencies and visit them recursively\n\n function sort(modifier) {\n visited.add(modifier.name);\n var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);\n requires.forEach(function (dep) {\n if (!visited.has(dep)) {\n var depModifier = map.get(dep);\n\n if (depModifier) {\n sort(depModifier);\n }\n }\n });\n result.push(modifier);\n }\n\n modifiers.forEach(function (modifier) {\n if (!visited.has(modifier.name)) {\n // check for visited object\n sort(modifier);\n }\n });\n return result;\n}\n\nexport default function orderModifiers(modifiers) {\n // order based on dependencies\n var orderedModifiers = order(modifiers); // order based on phase\n\n return modifierPhases.reduce(function (acc, phase) {\n return acc.concat(orderedModifiers.filter(function (modifier) {\n return modifier.phase === phase;\n }));\n }, []);\n}", "export default function debounce(fn) {\n var pending;\n return function () {\n if (!pending) {\n pending = new Promise(function (resolve) {\n Promise.resolve().then(function () {\n pending = undefined;\n resolve(fn());\n });\n });\n }\n\n return pending;\n };\n}", "export default function format(str) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n return [].concat(args).reduce(function (p, c) {\n return p.replace(/%s/, c);\n }, str);\n}", "import format from \"./format.js\";\nimport { modifierPhases } from \"../enums.js\";\nvar INVALID_MODIFIER_ERROR = 'Popper: modifier \"%s\" provided an invalid %s property, expected %s but got %s';\nvar MISSING_DEPENDENCY_ERROR = 'Popper: modifier \"%s\" requires \"%s\", but \"%s\" modifier is not available';\nvar VALID_PROPERTIES = ['name', 'enabled', 'phase', 'fn', 'effect', 'requires', 'options'];\nexport default function validateModifiers(modifiers) {\n modifiers.forEach(function (modifier) {\n [].concat(Object.keys(modifier), VALID_PROPERTIES) // IE11-compatible replacement for `new Set(iterable)`\n .filter(function (value, index, self) {\n return self.indexOf(value) === index;\n }).forEach(function (key) {\n switch (key) {\n case 'name':\n if (typeof modifier.name !== 'string') {\n console.error(format(INVALID_MODIFIER_ERROR, String(modifier.name), '\"name\"', '\"string\"', \"\\\"\" + String(modifier.name) + \"\\\"\"));\n }\n\n break;\n\n case 'enabled':\n if (typeof modifier.enabled !== 'boolean') {\n console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '\"enabled\"', '\"boolean\"', \"\\\"\" + String(modifier.enabled) + \"\\\"\"));\n }\n\n break;\n\n case 'phase':\n if (modifierPhases.indexOf(modifier.phase) < 0) {\n console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '\"phase\"', \"either \" + modifierPhases.join(', '), \"\\\"\" + String(modifier.phase) + \"\\\"\"));\n }\n\n break;\n\n case 'fn':\n if (typeof modifier.fn !== 'function') {\n console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '\"fn\"', '\"function\"', \"\\\"\" + String(modifier.fn) + \"\\\"\"));\n }\n\n break;\n\n case 'effect':\n if (modifier.effect != null && typeof modifier.effect !== 'function') {\n console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '\"effect\"', '\"function\"', \"\\\"\" + String(modifier.fn) + \"\\\"\"));\n }\n\n break;\n\n case 'requires':\n if (modifier.requires != null && !Array.isArray(modifier.requires)) {\n console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '\"requires\"', '\"array\"', \"\\\"\" + String(modifier.requires) + \"\\\"\"));\n }\n\n break;\n\n case 'requiresIfExists':\n if (!Array.isArray(modifier.requiresIfExists)) {\n console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '\"requiresIfExists\"', '\"array\"', \"\\\"\" + String(modifier.requiresIfExists) + \"\\\"\"));\n }\n\n break;\n\n case 'options':\n case 'data':\n break;\n\n default:\n console.error(\"PopperJS: an invalid property has been provided to the \\\"\" + modifier.name + \"\\\" modifier, valid properties are \" + VALID_PROPERTIES.map(function (s) {\n return \"\\\"\" + s + \"\\\"\";\n }).join(', ') + \"; but \\\"\" + key + \"\\\" was provided.\");\n }\n\n modifier.requires && modifier.requires.forEach(function (requirement) {\n if (modifiers.find(function (mod) {\n return mod.name === requirement;\n }) == null) {\n console.error(format(MISSING_DEPENDENCY_ERROR, String(modifier.name), requirement, requirement));\n }\n });\n });\n });\n}", "export default function uniqueBy(arr, fn) {\n var identifiers = new Set();\n return arr.filter(function (item) {\n var identifier = fn(item);\n\n if (!identifiers.has(identifier)) {\n identifiers.add(identifier);\n return true;\n }\n });\n}", "export default function mergeByName(modifiers) {\n var merged = modifiers.reduce(function (merged, current) {\n var existing = merged[current.name];\n merged[current.name] = existing ? Object.assign({}, existing, current, {\n options: Object.assign({}, existing.options, current.options),\n data: Object.assign({}, existing.data, current.data)\n }) : current;\n return merged;\n }, {}); // IE11 does not support Object.values\n\n return Object.keys(merged).map(function (key) {\n return merged[key];\n });\n}", "import getCompositeRect from \"./dom-utils/getCompositeRect.js\";\nimport getLayoutRect from \"./dom-utils/getLayoutRect.js\";\nimport listScrollParents from \"./dom-utils/listScrollParents.js\";\nimport getOffsetParent from \"./dom-utils/getOffsetParent.js\";\nimport getComputedStyle from \"./dom-utils/getComputedStyle.js\";\nimport orderModifiers from \"./utils/orderModifiers.js\";\nimport debounce from \"./utils/debounce.js\";\nimport validateModifiers from \"./utils/validateModifiers.js\";\nimport uniqueBy from \"./utils/uniqueBy.js\";\nimport getBasePlacement from \"./utils/getBasePlacement.js\";\nimport mergeByName from \"./utils/mergeByName.js\";\nimport detectOverflow from \"./utils/detectOverflow.js\";\nimport { isElement } from \"./dom-utils/instanceOf.js\";\nimport { auto } from \"./enums.js\";\nvar INVALID_ELEMENT_ERROR = 'Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element.';\nvar INFINITE_LOOP_ERROR = 'Popper: An infinite loop in the modifiers cycle has been detected! The cycle has been interrupted to prevent a browser crash.';\nvar DEFAULT_OPTIONS = {\n placement: 'bottom',\n modifiers: [],\n strategy: 'absolute'\n};\n\nfunction areValidElements() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return !args.some(function (element) {\n return !(element && typeof element.getBoundingClientRect === 'function');\n });\n}\n\nexport function popperGenerator(generatorOptions) {\n if (generatorOptions === void 0) {\n generatorOptions = {};\n }\n\n var _generatorOptions = generatorOptions,\n _generatorOptions$def = _generatorOptions.defaultModifiers,\n defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,\n _generatorOptions$def2 = _generatorOptions.defaultOptions,\n defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;\n return function createPopper(reference, popper, options) {\n if (options === void 0) {\n options = defaultOptions;\n }\n\n var state = {\n placement: 'bottom',\n orderedModifiers: [],\n options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),\n modifiersData: {},\n elements: {\n reference: reference,\n popper: popper\n },\n attributes: {},\n styles: {}\n };\n var effectCleanupFns = [];\n var isDestroyed = false;\n var instance = {\n state: state,\n setOptions: function setOptions(setOptionsAction) {\n var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction;\n cleanupModifierEffects();\n state.options = Object.assign({}, defaultOptions, state.options, options);\n state.scrollParents = {\n reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],\n popper: listScrollParents(popper)\n }; // Orders the modifiers based on their dependencies and `phase`\n // properties\n\n var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers\n\n state.orderedModifiers = orderedModifiers.filter(function (m) {\n return m.enabled;\n }); // Validate the provided modifiers so that the consumer will get warned\n // if one of the modifiers is invalid for any reason\n\n if (process.env.NODE_ENV !== \"production\") {\n var modifiers = uniqueBy([].concat(orderedModifiers, state.options.modifiers), function (_ref) {\n var name = _ref.name;\n return name;\n });\n validateModifiers(modifiers);\n\n if (getBasePlacement(state.options.placement) === auto) {\n var flipModifier = state.orderedModifiers.find(function (_ref2) {\n var name = _ref2.name;\n return name === 'flip';\n });\n\n if (!flipModifier) {\n console.error(['Popper: \"auto\" placements require the \"flip\" modifier be', 'present and enabled to work.'].join(' '));\n }\n }\n\n var _getComputedStyle = getComputedStyle(popper),\n marginTop = _getComputedStyle.marginTop,\n marginRight = _getComputedStyle.marginRight,\n marginBottom = _getComputedStyle.marginBottom,\n marginLeft = _getComputedStyle.marginLeft; // We no longer take into account `margins` on the popper, and it can\n // cause bugs with positioning, so we'll warn the consumer\n\n\n if ([marginTop, marginRight, marginBottom, marginLeft].some(function (margin) {\n return parseFloat(margin);\n })) {\n console.warn(['Popper: CSS \"margin\" styles cannot be used to apply padding', 'between the popper and its reference element or boundary.', 'To replicate margin, use the `offset` modifier, as well as', 'the `padding` option in the `preventOverflow` and `flip`', 'modifiers.'].join(' '));\n }\n }\n\n runModifierEffects();\n return instance.update();\n },\n // Sync update \u2013 it will always be executed, even if not necessary. This\n // is useful for low frequency updates where sync behavior simplifies the\n // logic.\n // For high frequency updates (e.g. `resize` and `scroll` events), always\n // prefer the async Popper#update method\n forceUpdate: function forceUpdate() {\n if (isDestroyed) {\n return;\n }\n\n var _state$elements = state.elements,\n reference = _state$elements.reference,\n popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements\n // anymore\n\n if (!areValidElements(reference, popper)) {\n if (process.env.NODE_ENV !== \"production\") {\n console.error(INVALID_ELEMENT_ERROR);\n }\n\n return;\n } // Store the reference and popper rects to be read by modifiers\n\n\n state.rects = {\n reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'),\n popper: getLayoutRect(popper)\n }; // Modifiers have the ability to reset the current update cycle. The\n // most common use case for this is the `flip` modifier changing the\n // placement, which then needs to re-run all the modifiers, because the\n // logic was previously ran for the previous placement and is therefore\n // stale/incorrect\n\n state.reset = false;\n state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier\n // is filled with the initial data specified by the modifier. This means\n // it doesn't persist and is fresh on each update.\n // To ensure persistent data, use `${name}#persistent`\n\n state.orderedModifiers.forEach(function (modifier) {\n return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);\n });\n var __debug_loops__ = 0;\n\n for (var index = 0; index < state.orderedModifiers.length; index++) {\n if (process.env.NODE_ENV !== \"production\") {\n __debug_loops__ += 1;\n\n if (__debug_loops__ > 100) {\n console.error(INFINITE_LOOP_ERROR);\n break;\n }\n }\n\n if (state.reset === true) {\n state.reset = false;\n index = -1;\n continue;\n }\n\n var _state$orderedModifie = state.orderedModifiers[index],\n fn = _state$orderedModifie.fn,\n _state$orderedModifie2 = _state$orderedModifie.options,\n _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,\n name = _state$orderedModifie.name;\n\n if (typeof fn === 'function') {\n state = fn({\n state: state,\n options: _options,\n name: name,\n instance: instance\n }) || state;\n }\n }\n },\n // Async and optimistically optimized update \u2013 it will not be executed if\n // not necessary (debounced to run at most once-per-tick)\n update: debounce(function () {\n return new Promise(function (resolve) {\n instance.forceUpdate();\n resolve(state);\n });\n }),\n destroy: function destroy() {\n cleanupModifierEffects();\n isDestroyed = true;\n }\n };\n\n if (!areValidElements(reference, popper)) {\n if (process.env.NODE_ENV !== \"production\") {\n console.error(INVALID_ELEMENT_ERROR);\n }\n\n return instance;\n }\n\n instance.setOptions(options).then(function (state) {\n if (!isDestroyed && options.onFirstUpdate) {\n options.onFirstUpdate(state);\n }\n }); // Modifiers have the ability to execute arbitrary code before the first\n // update cycle runs. They will be executed in the same order as the update\n // cycle. This is useful when a modifier adds some persistent data that\n // other modifiers need to use, but the modifier is run after the dependent\n // one.\n\n function runModifierEffects() {\n state.orderedModifiers.forEach(function (_ref3) {\n var name = _ref3.name,\n _ref3$options = _ref3.options,\n options = _ref3$options === void 0 ? {} : _ref3$options,\n effect = _ref3.effect;\n\n if (typeof effect === 'function') {\n var cleanupFn = effect({\n state: state,\n name: name,\n instance: instance,\n options: options\n });\n\n var noopFn = function noopFn() {};\n\n effectCleanupFns.push(cleanupFn || noopFn);\n }\n });\n }\n\n function cleanupModifierEffects() {\n effectCleanupFns.forEach(function (fn) {\n return fn();\n });\n effectCleanupFns = [];\n }\n\n return instance;\n };\n}\nexport var createPopper = /*#__PURE__*/popperGenerator(); // eslint-disable-next-line import/no-unused-modules\n\nexport { detectOverflow };", "import { popperGenerator, detectOverflow } from \"./createPopper.js\";\nimport eventListeners from \"./modifiers/eventListeners.js\";\nimport popperOffsets from \"./modifiers/popperOffsets.js\";\nimport computeStyles from \"./modifiers/computeStyles.js\";\nimport applyStyles from \"./modifiers/applyStyles.js\";\nvar defaultModifiers = [eventListeners, popperOffsets, computeStyles, applyStyles];\nvar createPopper = /*#__PURE__*/popperGenerator({\n defaultModifiers: defaultModifiers\n}); // eslint-disable-next-line import/no-unused-modules\n\nexport { createPopper, popperGenerator, defaultModifiers, detectOverflow };", "import { popperGenerator, detectOverflow } from \"./createPopper.js\";\nimport eventListeners from \"./modifiers/eventListeners.js\";\nimport popperOffsets from \"./modifiers/popperOffsets.js\";\nimport computeStyles from \"./modifiers/computeStyles.js\";\nimport applyStyles from \"./modifiers/applyStyles.js\";\nimport offset from \"./modifiers/offset.js\";\nimport flip from \"./modifiers/flip.js\";\nimport preventOverflow from \"./modifiers/preventOverflow.js\";\nimport arrow from \"./modifiers/arrow.js\";\nimport hide from \"./modifiers/hide.js\";\nvar defaultModifiers = [eventListeners, popperOffsets, computeStyles, applyStyles, offset, flip, preventOverflow, arrow, hide];\nvar createPopper = /*#__PURE__*/popperGenerator({\n defaultModifiers: defaultModifiers\n}); // eslint-disable-next-line import/no-unused-modules\n\nexport { createPopper, popperGenerator, defaultModifiers, detectOverflow }; // eslint-disable-next-line import/no-unused-modules\n\nexport { createPopper as createPopperLite } from \"./popper-lite.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport * from \"./modifiers/index.js\";", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nfunction normalizeData(val) {\r\n if (val === \"true\") {\r\n return true;\r\n }\r\n\r\n if (val === \"false\") {\r\n return false;\r\n }\r\n\r\n if (val === Number(val).toString()) {\r\n return Number(val);\r\n }\r\n\r\n if (val === \"\" || val === \"null\") {\r\n return null;\r\n }\r\n\r\n return val;\r\n}\r\n\r\nfunction normalizeDataKey(key) {\r\n return key.replace(/[A-Z]/g, (chr) => `-${chr.toLowerCase()}`);\r\n}\r\n\r\nconst Manipulator = {\r\n setDataAttribute(element, key, value) {\r\n element.setAttribute(`data-te-${normalizeDataKey(key)}`, value);\r\n },\r\n\r\n removeDataAttribute(element, key) {\r\n element.removeAttribute(`data-te-${normalizeDataKey(key)}`);\r\n },\r\n\r\n getDataAttributes(element) {\r\n if (!element) {\r\n return {};\r\n }\r\n\r\n const attributes = {};\r\n\r\n Object.keys(element.dataset)\r\n .filter((key) => key.startsWith(\"te\"))\r\n .forEach((key) => {\r\n if (key.startsWith(\"teClass\")) {\r\n return;\r\n }\r\n\r\n let pureKey = key.replace(/^te/, \"\");\r\n pureKey =\r\n pureKey.charAt(0).toLowerCase() + pureKey.slice(1, pureKey.length);\r\n attributes[pureKey] = normalizeData(element.dataset[key]);\r\n });\r\n\r\n return attributes;\r\n },\r\n\r\n getDataClassAttributes(element) {\r\n if (!element) {\r\n return {};\r\n }\r\n\r\n const attributes = {\r\n ...element.dataset,\r\n };\r\n\r\n Object.keys(attributes)\r\n .filter((key) => key.startsWith(\"teClass\"))\r\n .forEach((key) => {\r\n let pureKey = key.replace(/^teClass/, \"\");\r\n pureKey =\r\n pureKey.charAt(0).toLowerCase() + pureKey.slice(1, pureKey.length);\r\n attributes[pureKey] = normalizeData(attributes[key]);\r\n });\r\n\r\n return attributes;\r\n },\r\n\r\n getDataAttribute(element, key) {\r\n return normalizeData(\r\n element.getAttribute(`data-te-${normalizeDataKey(key)}`)\r\n );\r\n },\r\n\r\n offset(element) {\r\n const rect = element.getBoundingClientRect();\r\n\r\n return {\r\n top: rect.top + document.body.scrollTop,\r\n left: rect.left + document.body.scrollLeft,\r\n };\r\n },\r\n\r\n position(element) {\r\n return {\r\n top: element.offsetTop,\r\n left: element.offsetLeft,\r\n };\r\n },\r\n\r\n style(element, style) {\r\n Object.assign(element.style, style);\r\n },\r\n\r\n toggleClass(element, classNameOrList) {\r\n if (!element) {\r\n return;\r\n }\r\n\r\n _classNameOrListToArray(classNameOrList).forEach((className) => {\r\n if (element.classList.contains(className)) {\r\n element.classList.remove(className);\r\n } else {\r\n element.classList.add(className);\r\n }\r\n });\r\n },\r\n\r\n addClass(element, classNameOrList) {\r\n _classNameOrListToArray(classNameOrList).forEach(\r\n (className) =>\r\n !element.classList.contains(className) &&\r\n element.classList.add(className)\r\n );\r\n },\r\n\r\n addStyle(element, style) {\r\n Object.keys(style).forEach((property) => {\r\n element.style[property] = style[property];\r\n });\r\n },\r\n\r\n removeClass(element, classNameOrList) {\r\n _classNameOrListToArray(classNameOrList).forEach(\r\n (className) =>\r\n element.classList.contains(className) &&\r\n element.classList.remove(className)\r\n );\r\n },\r\n\r\n hasClass(element, className) {\r\n return element.classList.contains(className);\r\n },\r\n\r\n maxOffset(element) {\r\n const rect = element.getBoundingClientRect();\r\n\r\n return {\r\n top:\r\n rect.top +\r\n Math.max(\r\n document.body.scrollTop,\r\n document.documentElement.scrollTop,\r\n window.scrollY\r\n ),\r\n left:\r\n rect.left +\r\n Math.max(\r\n document.body.scrollLeft,\r\n document.documentElement.scrollLeft,\r\n window.scrollX\r\n ),\r\n };\r\n },\r\n};\r\n\r\nfunction _classNameOrListToArray(classNameOrList) {\r\n if (typeof classNameOrList === \"string\") {\r\n return classNameOrList.split(\" \");\r\n } else if (Array.isArray(classNameOrList)) {\r\n return classNameOrList;\r\n }\r\n\r\n return false;\r\n}\r\n\r\nexport default Manipulator;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nimport { isDisabled, isVisible } from \"../util/index\";\r\n\r\nconst NODE_TEXT = 3;\r\n\r\nconst SelectorEngine = {\r\n closest(element, selector) {\r\n return element.closest(selector);\r\n },\r\n\r\n matches(element, selector) {\r\n return element.matches(selector);\r\n },\r\n\r\n find(selector, element = document.documentElement) {\r\n return [].concat(\r\n ...Element.prototype.querySelectorAll.call(element, selector)\r\n );\r\n },\r\n\r\n findOne(selector, element = document.documentElement) {\r\n return Element.prototype.querySelector.call(element, selector);\r\n },\r\n\r\n children(element, selector) {\r\n const children = [].concat(...element.children);\r\n\r\n return children.filter((child) => child.matches(selector));\r\n },\r\n\r\n parents(element, selector) {\r\n const parents = [];\r\n\r\n let ancestor = element.parentNode;\r\n\r\n while (\r\n ancestor &&\r\n ancestor.nodeType === Node.ELEMENT_NODE &&\r\n ancestor.nodeType !== NODE_TEXT\r\n ) {\r\n if (this.matches(ancestor, selector)) {\r\n parents.push(ancestor);\r\n }\r\n\r\n ancestor = ancestor.parentNode;\r\n }\r\n\r\n return parents;\r\n },\r\n\r\n prev(element, selector) {\r\n let previous = element.previousElementSibling;\r\n\r\n while (previous) {\r\n if (previous.matches(selector)) {\r\n return [previous];\r\n }\r\n\r\n previous = previous.previousElementSibling;\r\n }\r\n\r\n return [];\r\n },\r\n\r\n next(element, selector) {\r\n let next = element.nextElementSibling;\r\n\r\n while (next) {\r\n if (this.matches(next, selector)) {\r\n return [next];\r\n }\r\n\r\n next = next.nextElementSibling;\r\n }\r\n\r\n return [];\r\n },\r\n\r\n focusableChildren(element) {\r\n const focusables = [\r\n \"a\",\r\n \"button\",\r\n \"input\",\r\n \"textarea\",\r\n \"select\",\r\n \"details\",\r\n \"[tabindex]\",\r\n '[contenteditable=\"true\"]',\r\n ]\r\n .map((selector) => `${selector}:not([tabindex^=\"-\"])`)\r\n .join(\", \");\r\n\r\n return this.find(focusables, element).filter(\r\n (el) => !isDisabled(el) && isVisible(el)\r\n );\r\n },\r\n};\r\n\r\nexport default SelectorEngine;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\nimport * as Popper from \"@popperjs/core\";\r\n\r\nimport {\r\n getElement,\r\n getElementFromSelector,\r\n getNextActiveElement,\r\n isDisabled,\r\n isElement,\r\n isRTL,\r\n isVisible,\r\n noop,\r\n typeCheckConfig,\r\n} from \"../util/index\";\r\nimport EventHandler from \"../dom/event-handler\";\r\nimport Manipulator from \"../dom/manipulator\";\r\nimport SelectorEngine from \"../dom/selector-engine\";\r\nimport BaseComponent from \"../base-component\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst NAME = \"dropdown\";\r\nconst DATA_KEY = \"te.dropdown\";\r\nconst EVENT_KEY = `.${DATA_KEY}`;\r\nconst DATA_API_KEY = \".data-api\";\r\n\r\nconst ESCAPE_KEY = \"Escape\";\r\nconst SPACE_KEY = \"Space\";\r\nconst TAB_KEY = \"Tab\";\r\nconst ARROW_UP_KEY = \"ArrowUp\";\r\nconst ARROW_DOWN_KEY = \"ArrowDown\";\r\nconst RIGHT_MOUSE_BUTTON = 2; // MouseEvent.button value for the secondary button, usually the right button\r\n\r\nconst REGEXP_KEYDOWN = new RegExp(\r\n `${ARROW_UP_KEY}|${ARROW_DOWN_KEY}|${ESCAPE_KEY}`\r\n);\r\n\r\nconst EVENT_HIDE = `hide${EVENT_KEY}`;\r\nconst EVENT_HIDDEN = `hidden${EVENT_KEY}`;\r\nconst EVENT_SHOW = `show${EVENT_KEY}`;\r\nconst EVENT_SHOWN = `shown${EVENT_KEY}`;\r\nconst EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`;\r\nconst EVENT_KEYDOWN_DATA_API = `keydown${EVENT_KEY}${DATA_API_KEY}`;\r\nconst EVENT_KEYUP_DATA_API = `keyup${EVENT_KEY}${DATA_API_KEY}`;\r\n\r\nconst CLASS_NAME_SHOW = \"show\";\r\nconst CLASS_NAME_DROPUP = \"dropup\";\r\nconst CLASS_NAME_DROPEND = \"dropend\";\r\nconst CLASS_NAME_DROPSTART = \"dropstart\";\r\n\r\nconst SELECTOR_NAVBAR = \"[data-te-navbar-ref]\";\r\nconst SELECTOR_DATA_TOGGLE = \"[data-te-dropdown-toggle-ref]\";\r\nconst SELECTOR_MENU = \"[data-te-dropdown-menu-ref]\";\r\nconst SELECTOR_NAVBAR_NAV = \"[data-te-navbar-nav-ref]\";\r\nconst SELECTOR_VISIBLE_ITEMS =\r\n \"[data-te-dropdown-menu-ref] [data-te-dropdown-item-ref]:not(.disabled):not(:disabled)\";\r\n\r\nconst PLACEMENT_TOP = isRTL() ? \"top-end\" : \"top-start\";\r\nconst PLACEMENT_TOPEND = isRTL() ? \"top-start\" : \"top-end\";\r\nconst PLACEMENT_BOTTOM = isRTL() ? \"bottom-end\" : \"bottom-start\";\r\nconst PLACEMENT_BOTTOMEND = isRTL() ? \"bottom-start\" : \"bottom-end\";\r\nconst PLACEMENT_RIGHT = isRTL() ? \"left-start\" : \"right-start\";\r\nconst PLACEMENT_LEFT = isRTL() ? \"right-start\" : \"left-start\";\r\n\r\nconst ANIMATION_FADE_IN = [{ opacity: \"0\" }, { opacity: \"1\" }];\r\nconst ANIMATION_FADE_OUT = [{ opacity: \"1\" }, { opacity: \"0\" }];\r\n\r\nconst ANIMATION_TIMING = {\r\n duration: 550,\r\n iterations: 1,\r\n easing: \"ease\",\r\n fill: \"both\",\r\n};\r\n\r\nconst Default = {\r\n offset: [0, 2],\r\n boundary: \"clippingParents\",\r\n reference: \"toggle\",\r\n display: \"dynamic\",\r\n popperConfig: null,\r\n autoClose: true,\r\n dropdownAnimation: \"on\",\r\n};\r\n\r\nconst DefaultType = {\r\n offset: \"(array|string|function)\",\r\n boundary: \"(string|element)\",\r\n reference: \"(string|element|object)\",\r\n display: \"string\",\r\n popperConfig: \"(null|object|function)\",\r\n autoClose: \"(boolean|string)\",\r\n dropdownAnimation: \"string\",\r\n};\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nClass Definition\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nclass Dropdown extends BaseComponent {\r\n constructor(element, config) {\r\n super(element);\r\n\r\n this._popper = null;\r\n this._config = this._getConfig(config);\r\n this._menu = this._getMenuElement();\r\n this._inNavbar = this._detectNavbar();\r\n this._fadeOutAnimate = null;\r\n\r\n //* prevents dropdown close issue when system animation is turned off\r\n const isPrefersReducedMotionSet = window.matchMedia(\r\n \"(prefers-reduced-motion: reduce)\"\r\n ).matches;\r\n this._animationCanPlay =\r\n this._config.dropdownAnimation === \"on\" && !isPrefersReducedMotionSet;\r\n\r\n this._didInit = false;\r\n this._init();\r\n }\r\n\r\n // Getters\r\n\r\n static get Default() {\r\n return Default;\r\n }\r\n\r\n static get DefaultType() {\r\n return DefaultType;\r\n }\r\n\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n // Public\r\n\r\n toggle() {\r\n return this._isShown() ? this.hide() : this.show();\r\n }\r\n\r\n show() {\r\n if (isDisabled(this._element) || this._isShown(this._menu)) {\r\n return;\r\n }\r\n\r\n const relatedTarget = {\r\n relatedTarget: this._element,\r\n };\r\n\r\n const showEvent = EventHandler.trigger(\r\n this._element,\r\n EVENT_SHOW,\r\n relatedTarget\r\n );\r\n\r\n if (showEvent.defaultPrevented) {\r\n return;\r\n }\r\n\r\n const parent = Dropdown.getParentFromElement(this._element);\r\n // Totally disable Popper for Dropdowns in Navbar\r\n if (this._inNavbar) {\r\n Manipulator.setDataAttribute(this._menu, \"popper\", \"none\");\r\n } else {\r\n this._createPopper(parent);\r\n }\r\n\r\n // If this is a touch-enabled device we add extra\r\n // empty mouseover listeners to the body's immediate children;\r\n // only needed because of broken event delegation on iOS\r\n // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html\r\n if (\r\n \"ontouchstart\" in document.documentElement &&\r\n !parent.closest(SELECTOR_NAVBAR_NAV)\r\n ) {\r\n []\r\n .concat(...document.body.children)\r\n .forEach((elem) => EventHandler.on(elem, \"mouseover\", noop));\r\n }\r\n\r\n this._element.focus();\r\n this._element.setAttribute(\"aria-expanded\", true);\r\n\r\n this._menu.setAttribute(`data-te-dropdown-${CLASS_NAME_SHOW}`, \"\");\r\n this._animationCanPlay &&\r\n this._menu.animate(ANIMATION_FADE_IN, ANIMATION_TIMING);\r\n this._element.setAttribute(`data-te-dropdown-${CLASS_NAME_SHOW}`, \"\");\r\n\r\n setTimeout(\r\n () => {\r\n EventHandler.trigger(this._element, EVENT_SHOWN, relatedTarget);\r\n },\r\n this._animationCanPlay ? ANIMATION_TIMING.duration : 0\r\n );\r\n }\r\n\r\n hide() {\r\n if (isDisabled(this._element) || !this._isShown(this._menu)) {\r\n return;\r\n }\r\n\r\n const relatedTarget = {\r\n relatedTarget: this._element,\r\n };\r\n\r\n this._completeHide(relatedTarget);\r\n }\r\n\r\n dispose() {\r\n if (this._popper) {\r\n this._popper.destroy();\r\n }\r\n\r\n super.dispose();\r\n }\r\n\r\n update() {\r\n this._inNavbar = this._detectNavbar();\r\n if (this._popper) {\r\n this._popper.update();\r\n }\r\n }\r\n\r\n // Private\r\n _init() {\r\n if (this._didInit) {\r\n return;\r\n }\r\n\r\n EventHandler.on(\r\n document,\r\n EVENT_KEYDOWN_DATA_API,\r\n SELECTOR_DATA_TOGGLE,\r\n Dropdown.dataApiKeydownHandler\r\n );\r\n EventHandler.on(\r\n document,\r\n EVENT_KEYDOWN_DATA_API,\r\n SELECTOR_MENU,\r\n Dropdown.dataApiKeydownHandler\r\n );\r\n EventHandler.on(document, EVENT_CLICK_DATA_API, Dropdown.clearMenus);\r\n EventHandler.on(document, EVENT_KEYUP_DATA_API, Dropdown.clearMenus);\r\n\r\n this._didInit = true;\r\n }\r\n\r\n _completeHide(relatedTarget) {\r\n if (this._fadeOutAnimate && this._fadeOutAnimate.playState === \"running\") {\r\n return;\r\n }\r\n\r\n const hideEvent = EventHandler.trigger(\r\n this._element,\r\n EVENT_HIDE,\r\n relatedTarget\r\n );\r\n if (hideEvent.defaultPrevented) {\r\n return;\r\n }\r\n\r\n // If this is a touch-enabled device we remove the extra\r\n // empty mouseover listeners we added for iOS support\r\n if (\"ontouchstart\" in document.documentElement) {\r\n []\r\n .concat(...document.body.children)\r\n .forEach((elem) => EventHandler.off(elem, \"mouseover\", noop));\r\n }\r\n\r\n if (this._animationCanPlay) {\r\n this._fadeOutAnimate = this._menu.animate(\r\n ANIMATION_FADE_OUT,\r\n ANIMATION_TIMING\r\n );\r\n }\r\n\r\n setTimeout(\r\n () => {\r\n if (this._popper) {\r\n this._popper.destroy();\r\n }\r\n\r\n this._menu.removeAttribute(`data-te-dropdown-${CLASS_NAME_SHOW}`);\r\n this._element.removeAttribute(`data-te-dropdown-${CLASS_NAME_SHOW}`);\r\n\r\n this._element.setAttribute(\"aria-expanded\", \"false\");\r\n Manipulator.removeDataAttribute(this._menu, \"popper\");\r\n EventHandler.trigger(this._element, EVENT_HIDDEN, relatedTarget);\r\n },\r\n this._animationCanPlay ? ANIMATION_TIMING.duration : 0\r\n );\r\n }\r\n\r\n _getConfig(config) {\r\n config = {\r\n ...this.constructor.Default,\r\n ...Manipulator.getDataAttributes(this._element),\r\n ...config,\r\n };\r\n\r\n typeCheckConfig(NAME, config, this.constructor.DefaultType);\r\n\r\n if (\r\n typeof config.reference === \"object\" &&\r\n !isElement(config.reference) &&\r\n typeof config.reference.getBoundingClientRect !== \"function\"\r\n ) {\r\n // Popper virtual elements require a getBoundingClientRect method\r\n throw new TypeError(\r\n `${NAME.toUpperCase()}: Option \"reference\" provided type \"object\" without a required \"getBoundingClientRect\" method.`\r\n );\r\n }\r\n\r\n return config;\r\n }\r\n\r\n _createPopper(parent) {\r\n if (typeof Popper === \"undefined\") {\r\n throw new TypeError(\r\n \"Bootstrap's dropdowns require Popper (https://popper.js.org)\"\r\n );\r\n }\r\n\r\n let referenceElement = this._element;\r\n\r\n if (this._config.reference === \"parent\") {\r\n referenceElement = parent;\r\n } else if (isElement(this._config.reference)) {\r\n referenceElement = getElement(this._config.reference);\r\n } else if (typeof this._config.reference === \"object\") {\r\n referenceElement = this._config.reference;\r\n }\r\n\r\n const popperConfig = this._getPopperConfig();\r\n const isDisplayStatic = popperConfig.modifiers.find(\r\n (modifier) =>\r\n modifier.name === \"applyStyles\" && modifier.enabled === false\r\n );\r\n\r\n this._popper = Popper.createPopper(\r\n referenceElement,\r\n this._menu,\r\n popperConfig\r\n );\r\n\r\n if (isDisplayStatic) {\r\n Manipulator.setDataAttribute(this._menu, \"popper\", \"static\");\r\n }\r\n }\r\n\r\n _isShown(element = this._element) {\r\n return (\r\n element.dataset[\r\n `teDropdown${\r\n CLASS_NAME_SHOW.charAt(0).toUpperCase() + CLASS_NAME_SHOW.slice(1)\r\n }`\r\n ] === \"\"\r\n );\r\n }\r\n\r\n _getMenuElement() {\r\n return SelectorEngine.next(this._element, SELECTOR_MENU)[0];\r\n }\r\n\r\n _getPlacement() {\r\n const parentDropdown = this._element.parentNode;\r\n\r\n if (parentDropdown.dataset.teDropdownPosition === CLASS_NAME_DROPEND) {\r\n return PLACEMENT_RIGHT;\r\n }\r\n\r\n if (parentDropdown.dataset.teDropdownPosition === CLASS_NAME_DROPSTART) {\r\n return PLACEMENT_LEFT;\r\n }\r\n\r\n // We need to trim the value because custom properties can also include spaces\r\n const isEnd = parentDropdown.dataset.teDropdownAlignment === \"end\";\r\n\r\n if (parentDropdown.dataset.teDropdownPosition === CLASS_NAME_DROPUP) {\r\n return isEnd ? PLACEMENT_TOPEND : PLACEMENT_TOP;\r\n }\r\n\r\n return isEnd ? PLACEMENT_BOTTOMEND : PLACEMENT_BOTTOM;\r\n }\r\n\r\n _detectNavbar() {\r\n return this._element.closest(SELECTOR_NAVBAR) !== null;\r\n }\r\n\r\n _getOffset() {\r\n const { offset } = this._config;\r\n\r\n if (typeof offset === \"string\") {\r\n return offset.split(\",\").map((val) => Number.parseInt(val, 10));\r\n }\r\n\r\n if (typeof offset === \"function\") {\r\n return (popperData) => offset(popperData, this._element);\r\n }\r\n\r\n return offset;\r\n }\r\n\r\n _getPopperConfig() {\r\n const defaultBsPopperConfig = {\r\n placement: this._getPlacement(),\r\n modifiers: [\r\n {\r\n name: \"preventOverflow\",\r\n options: {\r\n boundary: this._config.boundary,\r\n },\r\n },\r\n {\r\n name: \"offset\",\r\n options: {\r\n offset: this._getOffset(),\r\n },\r\n },\r\n ],\r\n };\r\n\r\n // Disable Popper if we have a static display\r\n if (this._config.display === \"static\") {\r\n defaultBsPopperConfig.modifiers = [\r\n {\r\n name: \"applyStyles\",\r\n enabled: false,\r\n },\r\n ];\r\n }\r\n\r\n return {\r\n ...defaultBsPopperConfig,\r\n ...(typeof this._config.popperConfig === \"function\"\r\n ? this._config.popperConfig(defaultBsPopperConfig)\r\n : this._config.popperConfig),\r\n };\r\n }\r\n\r\n _selectMenuItem({ key, target }) {\r\n const items = SelectorEngine.find(\r\n SELECTOR_VISIBLE_ITEMS,\r\n this._menu\r\n ).filter(isVisible);\r\n\r\n if (!items.length) {\r\n return;\r\n }\r\n\r\n // if target isn't included in items (e.g. when expanding the dropdown)\r\n // allow cycling to get the last item in case key equals ARROW_UP_KEY\r\n getNextActiveElement(\r\n items,\r\n target,\r\n key === ARROW_DOWN_KEY,\r\n !items.includes(target)\r\n ).focus();\r\n }\r\n\r\n // Static\r\n\r\n static jQueryInterface(config) {\r\n return this.each(function () {\r\n const data = Dropdown.getOrCreateInstance(this, config);\r\n\r\n if (typeof config !== \"string\") {\r\n return;\r\n }\r\n\r\n if (typeof data[config] === \"undefined\") {\r\n throw new TypeError(`No method named \"${config}\"`);\r\n }\r\n\r\n data[config]();\r\n });\r\n }\r\n\r\n static clearMenus(event) {\r\n if (\r\n event &&\r\n (event.button === RIGHT_MOUSE_BUTTON ||\r\n (event.type === \"keyup\" && event.key !== TAB_KEY))\r\n ) {\r\n return;\r\n }\r\n\r\n const toggles = SelectorEngine.find(SELECTOR_DATA_TOGGLE);\r\n\r\n for (let i = 0, len = toggles.length; i < len; i++) {\r\n const context = Dropdown.getInstance(toggles[i]);\r\n if (!context || context._config.autoClose === false) {\r\n continue;\r\n }\r\n\r\n if (!context._isShown()) {\r\n continue;\r\n }\r\n\r\n const relatedTarget = {\r\n relatedTarget: context._element,\r\n };\r\n\r\n if (event) {\r\n const composedPath = event.composedPath();\r\n const isMenuTarget = composedPath.includes(context._menu);\r\n if (\r\n composedPath.includes(context._element) ||\r\n (context._config.autoClose === \"inside\" && !isMenuTarget) ||\r\n (context._config.autoClose === \"outside\" && isMenuTarget)\r\n ) {\r\n continue;\r\n }\r\n\r\n // Tab navigation through the dropdown menu or events from contained inputs shouldn't close the menu\r\n if (\r\n context._menu.contains(event.target) &&\r\n ((event.type === \"keyup\" && event.key === TAB_KEY) ||\r\n /input|select|option|textarea|form/i.test(event.target.tagName))\r\n ) {\r\n continue;\r\n }\r\n\r\n if (event.type === \"click\") {\r\n relatedTarget.clickEvent = event;\r\n }\r\n }\r\n\r\n context._completeHide(relatedTarget);\r\n }\r\n }\r\n\r\n static getParentFromElement(element) {\r\n return getElementFromSelector(element) || element.parentNode;\r\n }\r\n\r\n static dataApiKeydownHandler(event) {\r\n // If not input/textarea:\r\n // - And not a key in REGEXP_KEYDOWN => not a dropdown command\r\n // If input/textarea:\r\n // - If space key => not a dropdown command\r\n // - If key is other than escape\r\n // - If key is not up or down => not a dropdown command\r\n // - If trigger inside the menu => not a dropdown command\r\n if (\r\n /input|textarea/i.test(event.target.tagName)\r\n ? event.key === SPACE_KEY ||\r\n (event.key !== ESCAPE_KEY &&\r\n ((event.key !== ARROW_DOWN_KEY && event.key !== ARROW_UP_KEY) ||\r\n event.target.closest(SELECTOR_MENU)))\r\n : !REGEXP_KEYDOWN.test(event.key)\r\n ) {\r\n return;\r\n }\r\n\r\n const isActive =\r\n this.dataset[\r\n `teDropdown${\r\n CLASS_NAME_SHOW.charAt(0).toUpperCase() + CLASS_NAME_SHOW.slice(1)\r\n }`\r\n ] === \"\";\r\n\r\n if (!isActive && event.key === ESCAPE_KEY) {\r\n return;\r\n }\r\n\r\n event.preventDefault();\r\n event.stopPropagation();\r\n\r\n if (isDisabled(this)) {\r\n return;\r\n }\r\n\r\n const getToggleButton = this.matches(SELECTOR_DATA_TOGGLE)\r\n ? this\r\n : SelectorEngine.prev(this, SELECTOR_DATA_TOGGLE)[0];\r\n const instance = Dropdown.getOrCreateInstance(getToggleButton);\r\n\r\n if (event.key === ESCAPE_KEY) {\r\n instance.hide();\r\n return;\r\n }\r\n\r\n if (event.key === ARROW_UP_KEY || event.key === ARROW_DOWN_KEY) {\r\n if (!isActive) {\r\n instance.show();\r\n }\r\n\r\n instance._selectMenuItem(event);\r\n return;\r\n }\r\n\r\n if (!isActive || event.key === SPACE_KEY) {\r\n Dropdown.clearMenus();\r\n }\r\n }\r\n}\r\n\r\nexport default Dropdown;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport {\r\n getElement,\r\n getSelectorFromElement,\r\n getElementFromSelector,\r\n reflow,\r\n typeCheckConfig,\r\n} from \"../util/index\";\r\nimport Data from \"../dom/data\";\r\nimport EventHandler from \"../dom/event-handler\";\r\nimport Manipulator from \"../dom/manipulator\";\r\nimport SelectorEngine from \"../dom/selector-engine\";\r\nimport BaseComponent from \"../base-component\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst NAME = \"collapse\";\r\nconst DATA_KEY = \"te.collapse\";\r\nconst EVENT_KEY = `.${DATA_KEY}`;\r\n\r\nconst Default = {\r\n toggle: true,\r\n parent: null,\r\n};\r\n\r\nconst DefaultType = {\r\n toggle: \"boolean\",\r\n parent: \"(null|element)\",\r\n};\r\n\r\nconst EVENT_SHOW = `show${EVENT_KEY}`;\r\nconst EVENT_SHOWN = `shown${EVENT_KEY}`;\r\nconst EVENT_HIDE = `hide${EVENT_KEY}`;\r\nconst EVENT_HIDDEN = `hidden${EVENT_KEY}`;\r\n\r\nconst ATTR_SHOW = \"data-te-collapse-show\";\r\nconst ATTR_COLLAPSED = \"data-te-collapse-collapsed\";\r\nconst ATTR_COLLAPSING = \"data-te-collapse-collapsing\";\r\nconst ATTR_HORIZONTAL = \"data-te-collapse-horizontal\";\r\nconst ATTR_COLLAPSE_ITEM = \"data-te-collapse-item\";\r\nconst ATTR_COLLAPSE_DEEPER_CHILDREN = `:scope [${ATTR_COLLAPSE_ITEM}] [${ATTR_COLLAPSE_ITEM}]`;\r\n\r\nconst WIDTH = \"width\";\r\nconst HEIGHT = \"height\";\r\n\r\nconst SELECTOR_DATA_ACTIVES =\r\n \"[data-te-collapse-item][data-te-collapse-show], [data-te-collapse-item][data-te-collapse-collapsing]\";\r\nconst SELECTOR_DATA_COLLAPSE_INIT = \"[data-te-collapse-init]\";\r\n\r\nconst DefaultClasses = {\r\n visible: \"!visible\",\r\n hidden: \"hidden\",\r\n baseTransition:\r\n \"overflow-hidden duration-[350ms] ease-[cubic-bezier(0.25,0.1,0.25,1.0)] motion-reduce:transition-none\",\r\n collapsing:\r\n \"h-0 transition-[height] overflow-hidden duration-[350ms] ease-[cubic-bezier(0.25,0.1,0.25,1.0)] motion-reduce:transition-none\",\r\n collapsingHorizontal:\r\n \"w-0 h-auto transition-[width] overflow-hidden duration-[350ms] ease-[cubic-bezier(0.25,0.1,0.25,1.0)] motion-reduce:transition-none\",\r\n};\r\n\r\nconst DefaultClassesType = {\r\n visible: \"string\",\r\n hidden: \"string\",\r\n baseTransition: \"string\",\r\n collapsing: \"string\",\r\n collapsingHorizontal: \"string\",\r\n};\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nClass Definition\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nclass Collapse extends BaseComponent {\r\n constructor(element, config, classes) {\r\n super(element);\r\n\r\n this._isTransitioning = false;\r\n this._config = this._getConfig(config);\r\n this._classes = this._getClasses(classes);\r\n this._triggerArray = [];\r\n\r\n const toggleList = SelectorEngine.find(SELECTOR_DATA_COLLAPSE_INIT);\r\n\r\n for (let i = 0, len = toggleList.length; i < len; i++) {\r\n const elem = toggleList[i];\r\n const selector = getSelectorFromElement(elem);\r\n const filterElement = SelectorEngine.find(selector).filter(\r\n (foundElem) => foundElem === this._element\r\n );\r\n\r\n if (selector !== null && filterElement.length) {\r\n this._selector = selector;\r\n this._triggerArray.push(elem);\r\n }\r\n }\r\n\r\n this._initializeChildren();\r\n\r\n if (!this._config.parent) {\r\n this._addAriaAndCollapsedClass(this._triggerArray, this._isShown());\r\n }\r\n\r\n if (this._config.toggle) {\r\n this.toggle();\r\n }\r\n }\r\n\r\n // Getters\r\n\r\n static get Default() {\r\n return Default;\r\n }\r\n\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n // Public\r\n\r\n toggle() {\r\n if (this._isShown()) {\r\n this.hide();\r\n } else {\r\n this.show();\r\n }\r\n }\r\n\r\n show() {\r\n if (this._isTransitioning || this._isShown()) {\r\n return;\r\n }\r\n\r\n let actives = [];\r\n let activesData;\r\n\r\n if (this._config.parent) {\r\n const children = SelectorEngine.find(\r\n ATTR_COLLAPSE_DEEPER_CHILDREN,\r\n this._config.parent\r\n );\r\n actives = SelectorEngine.find(\r\n SELECTOR_DATA_ACTIVES,\r\n this._config.parent\r\n ).filter((elem) => !children.includes(elem)); // remove children if greater depth\r\n }\r\n\r\n const container = SelectorEngine.findOne(this._selector);\r\n if (actives.length) {\r\n const tempActiveData = actives.find((elem) => container !== elem);\r\n activesData = tempActiveData\r\n ? Collapse.getInstance(tempActiveData)\r\n : null;\r\n\r\n if (activesData && activesData._isTransitioning) {\r\n return;\r\n }\r\n }\r\n\r\n const startEvent = EventHandler.trigger(this._element, EVENT_SHOW);\r\n if (startEvent.defaultPrevented) {\r\n return;\r\n }\r\n\r\n actives.forEach((elemActive) => {\r\n if (container !== elemActive) {\r\n Collapse.getOrCreateInstance(elemActive, { toggle: false }).hide();\r\n }\r\n\r\n if (!activesData) {\r\n Data.setData(elemActive, DATA_KEY, null);\r\n }\r\n });\r\n\r\n const dimension = this._getDimension();\r\n const CLASS_NAME_TRANSITION =\r\n dimension === \"height\"\r\n ? this._classes.collapsing\r\n : this._classes.collapsingHorizontal;\r\n\r\n Manipulator.removeClass(this._element, this._classes.visible);\r\n Manipulator.removeClass(this._element, this._classes.hidden);\r\n Manipulator.addClass(this._element, CLASS_NAME_TRANSITION);\r\n this._element.removeAttribute(ATTR_COLLAPSE_ITEM);\r\n this._element.setAttribute(ATTR_COLLAPSING, \"\");\r\n\r\n this._element.style[dimension] = 0;\r\n\r\n this._addAriaAndCollapsedClass(this._triggerArray, true);\r\n this._isTransitioning = true;\r\n\r\n const complete = () => {\r\n this._isTransitioning = false;\r\n\r\n Manipulator.removeClass(this._element, this._classes.hidden);\r\n Manipulator.removeClass(this._element, CLASS_NAME_TRANSITION);\r\n Manipulator.addClass(this._element, this._classes.visible);\r\n this._element.removeAttribute(ATTR_COLLAPSING);\r\n this._element.setAttribute(ATTR_COLLAPSE_ITEM, \"\");\r\n this._element.setAttribute(ATTR_SHOW, \"\");\r\n\r\n this._element.style[dimension] = \"\";\r\n\r\n EventHandler.trigger(this._element, EVENT_SHOWN);\r\n };\r\n\r\n const capitalizedDimension =\r\n dimension[0].toUpperCase() + dimension.slice(1);\r\n const scrollSize = `scroll${capitalizedDimension}`;\r\n\r\n this._queueCallback(complete, this._element, true);\r\n this._element.style[dimension] = `${this._element[scrollSize]}px`;\r\n }\r\n\r\n hide() {\r\n if (this._isTransitioning || !this._isShown()) {\r\n return;\r\n }\r\n\r\n const startEvent = EventHandler.trigger(this._element, EVENT_HIDE);\r\n if (startEvent.defaultPrevented) {\r\n return;\r\n }\r\n\r\n const dimension = this._getDimension();\r\n const CLASS_NAME_TRANSITION =\r\n dimension === \"height\"\r\n ? this._classes.collapsing\r\n : this._classes.collapsingHorizontal;\r\n\r\n this._element.style[dimension] = `${\r\n this._element.getBoundingClientRect()[dimension]\r\n }px`;\r\n\r\n reflow(this._element);\r\n\r\n Manipulator.addClass(this._element, CLASS_NAME_TRANSITION);\r\n Manipulator.removeClass(this._element, this._classes.visible);\r\n Manipulator.removeClass(this._element, this._classes.hidden);\r\n this._element.setAttribute(ATTR_COLLAPSING, \"\");\r\n this._element.removeAttribute(ATTR_COLLAPSE_ITEM);\r\n this._element.removeAttribute(ATTR_SHOW);\r\n\r\n const triggerArrayLength = this._triggerArray.length;\r\n for (let i = 0; i < triggerArrayLength; i++) {\r\n const trigger = this._triggerArray[i];\r\n const elem = getElementFromSelector(trigger);\r\n\r\n if (elem && !this._isShown(elem)) {\r\n this._addAriaAndCollapsedClass([trigger], false);\r\n }\r\n }\r\n\r\n this._isTransitioning = true;\r\n\r\n const complete = () => {\r\n this._isTransitioning = false;\r\n\r\n Manipulator.removeClass(this._element, CLASS_NAME_TRANSITION);\r\n Manipulator.addClass(this._element, this._classes.visible);\r\n Manipulator.addClass(this._element, this._classes.hidden);\r\n\r\n this._element.removeAttribute(ATTR_COLLAPSING);\r\n this._element.setAttribute(ATTR_COLLAPSE_ITEM, \"\");\r\n\r\n EventHandler.trigger(this._element, EVENT_HIDDEN);\r\n };\r\n\r\n this._element.style[dimension] = \"\";\r\n\r\n this._queueCallback(complete, this._element, true);\r\n }\r\n\r\n _isShown(element = this._element) {\r\n return element.hasAttribute(ATTR_SHOW);\r\n }\r\n\r\n // Private\r\n _getConfig(config) {\r\n config = {\r\n ...Default,\r\n ...Manipulator.getDataAttributes(this._element),\r\n ...config,\r\n };\r\n config.toggle = Boolean(config.toggle); // Coerce string values\r\n config.parent = getElement(config.parent);\r\n typeCheckConfig(NAME, config, DefaultType);\r\n return config;\r\n }\r\n\r\n _getClasses(classes) {\r\n const dataAttributes = Manipulator.getDataClassAttributes(this._element);\r\n\r\n classes = {\r\n ...DefaultClasses,\r\n ...dataAttributes,\r\n ...classes,\r\n };\r\n\r\n typeCheckConfig(NAME, classes, DefaultClassesType);\r\n return classes;\r\n }\r\n\r\n _getDimension() {\r\n return this._element.hasAttribute(ATTR_HORIZONTAL) ? WIDTH : HEIGHT;\r\n }\r\n\r\n _initializeChildren() {\r\n if (!this._config.parent) {\r\n return;\r\n }\r\n\r\n const children = SelectorEngine.find(\r\n ATTR_COLLAPSE_DEEPER_CHILDREN,\r\n this._config.parent\r\n );\r\n SelectorEngine.find(SELECTOR_DATA_COLLAPSE_INIT, this._config.parent)\r\n .filter((elem) => !children.includes(elem))\r\n .forEach((element) => {\r\n const selected = getElementFromSelector(element);\r\n\r\n if (selected) {\r\n this._addAriaAndCollapsedClass([element], this._isShown(selected));\r\n }\r\n });\r\n }\r\n\r\n _addAriaAndCollapsedClass(triggerArray, isOpen) {\r\n if (!triggerArray.length) {\r\n return;\r\n }\r\n\r\n triggerArray.forEach((elem) => {\r\n if (isOpen) {\r\n elem.removeAttribute(ATTR_COLLAPSED);\r\n } else {\r\n elem.setAttribute(`${ATTR_COLLAPSED}`, \"\");\r\n }\r\n\r\n elem.setAttribute(\"aria-expanded\", isOpen);\r\n });\r\n }\r\n\r\n // Static\r\n\r\n static jQueryInterface(config) {\r\n return this.each(function () {\r\n const _config = {};\r\n if (typeof config === \"string\" && /show|hide/.test(config)) {\r\n _config.toggle = false;\r\n }\r\n\r\n const data = Collapse.getOrCreateInstance(this, _config);\r\n\r\n if (typeof config === \"string\") {\r\n if (typeof data[config] === \"undefined\") {\r\n throw new TypeError(`No method named \"${config}\"`);\r\n }\r\n\r\n data[config]();\r\n }\r\n });\r\n }\r\n}\r\n\r\nexport default Collapse;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport SelectorEngine from \"../dom/selector-engine\";\r\nimport Manipulator from \"../dom/manipulator\";\r\nimport { isElement } from \"./index\";\r\n\r\nconst SELECTOR_FIXED_CONTENT =\r\n \".fixed-top, .fixed-bottom, .is-fixed, .sticky-top\";\r\nconst SELECTOR_STICKY_CONTENT = \".sticky-top\";\r\n\r\nclass ScrollBarHelper {\r\n constructor() {\r\n this._element = document.body;\r\n }\r\n\r\n getWidth() {\r\n // https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth#usage_notes\r\n const documentWidth = document.documentElement.clientWidth;\r\n return Math.abs(window.innerWidth - documentWidth);\r\n }\r\n\r\n hide() {\r\n const width = this.getWidth();\r\n this._disableOverFlow();\r\n // give padding to element to balance the hidden scrollbar width\r\n this._setElementAttributes(\r\n this._element,\r\n \"paddingRight\",\r\n (calculatedValue) => calculatedValue + width\r\n );\r\n // trick: We adjust positive paddingRight and negative marginRight to sticky-top elements to keep showing fullwidth\r\n this._setElementAttributes(\r\n SELECTOR_FIXED_CONTENT,\r\n \"paddingRight\",\r\n (calculatedValue) => calculatedValue + width\r\n );\r\n this._setElementAttributes(\r\n SELECTOR_STICKY_CONTENT,\r\n \"marginRight\",\r\n (calculatedValue) => calculatedValue - width\r\n );\r\n }\r\n\r\n _disableOverFlow() {\r\n this._saveInitialAttribute(this._element, \"overflow\");\r\n this._element.style.overflow = \"hidden\";\r\n }\r\n\r\n _setElementAttributes(selector, styleProp, callback) {\r\n const scrollbarWidth = this.getWidth();\r\n const manipulationCallBack = (element) => {\r\n if (\r\n element !== this._element &&\r\n window.innerWidth > element.clientWidth + scrollbarWidth\r\n ) {\r\n return;\r\n }\r\n\r\n this._saveInitialAttribute(element, styleProp);\r\n const calculatedValue = window.getComputedStyle(element)[styleProp];\r\n element.style[styleProp] = `${callback(\r\n Number.parseFloat(calculatedValue)\r\n )}px`;\r\n };\r\n\r\n this._applyManipulationCallback(selector, manipulationCallBack);\r\n }\r\n\r\n reset() {\r\n this._resetElementAttributes(this._element, \"overflow\");\r\n this._resetElementAttributes(this._element, \"paddingRight\");\r\n this._resetElementAttributes(SELECTOR_FIXED_CONTENT, \"paddingRight\");\r\n this._resetElementAttributes(SELECTOR_STICKY_CONTENT, \"marginRight\");\r\n }\r\n\r\n _saveInitialAttribute(element, styleProp) {\r\n const actualValue = element.style[styleProp];\r\n if (actualValue) {\r\n Manipulator.setDataAttribute(element, styleProp, actualValue);\r\n }\r\n }\r\n\r\n _resetElementAttributes(selector, styleProp) {\r\n const manipulationCallBack = (element) => {\r\n const value = Manipulator.getDataAttribute(element, styleProp);\r\n if (typeof value === \"undefined\") {\r\n element.style.removeProperty(styleProp);\r\n } else {\r\n Manipulator.removeDataAttribute(element, styleProp);\r\n element.style[styleProp] = value;\r\n }\r\n };\r\n\r\n this._applyManipulationCallback(selector, manipulationCallBack);\r\n }\r\n\r\n _applyManipulationCallback(selector, callBack) {\r\n if (isElement(selector)) {\r\n callBack(selector);\r\n } else {\r\n SelectorEngine.find(selector, this._element).forEach(callBack);\r\n }\r\n }\r\n\r\n isOverflowing() {\r\n return this.getWidth() > 0;\r\n }\r\n}\r\n\r\nexport default ScrollBarHelper;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport EventHandler from \"../dom/event-handler\";\r\nimport Manipulator from \"../dom/manipulator\";\r\nimport {\r\n execute,\r\n executeAfterTransition,\r\n getElement,\r\n reflow,\r\n typeCheckConfig,\r\n} from \"./index\";\r\n\r\nconst Default = {\r\n isVisible: true, // if false, we use the backdrop helper without adding any element to the dom\r\n isAnimated: false,\r\n rootElement: \"body\", // give the choice to place backdrop under different elements\r\n clickCallback: null,\r\n backdropClasses: null,\r\n};\r\n\r\nconst DefaultType = {\r\n isVisible: \"boolean\",\r\n isAnimated: \"boolean\",\r\n rootElement: \"(element|string)\",\r\n clickCallback: \"(function|null)\",\r\n backdropClasses: \"(array|null)\",\r\n};\r\nconst NAME = \"backdrop\";\r\nconst EVENT_MOUSEDOWN = `mousedown.te.${NAME}`;\r\n\r\nclass Backdrop {\r\n constructor(config) {\r\n this._config = this._getConfig(config);\r\n this._isAppended = false;\r\n this._element = null;\r\n }\r\n\r\n show(callback) {\r\n if (!this._config.isVisible) {\r\n execute(callback);\r\n return;\r\n }\r\n\r\n this._append();\r\n\r\n if (this._config.isAnimated) {\r\n reflow(this._getElement());\r\n }\r\n\r\n const backdropClasses = this._config.backdropClasses || [\r\n \"opacity-50\",\r\n \"transition-all\",\r\n \"duration-300\",\r\n \"ease-in-out\",\r\n \"fixed\",\r\n \"top-0\",\r\n \"left-0\",\r\n \"z-[1040]\",\r\n \"bg-black\",\r\n \"w-screen\",\r\n \"h-screen\",\r\n ];\r\n\r\n Manipulator.removeClass(this._getElement(), \"opacity-0\");\r\n Manipulator.addClass(this._getElement(), backdropClasses);\r\n this._element.setAttribute(\"data-te-backdrop-show\", \"\");\r\n\r\n this._emulateAnimation(() => {\r\n execute(callback);\r\n });\r\n }\r\n\r\n hide(callback) {\r\n if (!this._config.isVisible) {\r\n execute(callback);\r\n return;\r\n }\r\n\r\n this._element.removeAttribute(\"data-te-backdrop-show\");\r\n this._getElement().classList.add(\"opacity-0\");\r\n this._getElement().classList.remove(\"opacity-50\");\r\n\r\n this._emulateAnimation(() => {\r\n this.dispose();\r\n execute(callback);\r\n });\r\n }\r\n\r\n // Private\r\n\r\n _getElement() {\r\n if (!this._element) {\r\n const backdrop = document.createElement(\"div\");\r\n backdrop.className = this._config.className;\r\n if (this._config.isAnimated) {\r\n backdrop.classList.add(\"opacity-50\");\r\n }\r\n\r\n this._element = backdrop;\r\n }\r\n\r\n return this._element;\r\n }\r\n\r\n _getConfig(config) {\r\n config = {\r\n ...Default,\r\n ...(typeof config === \"object\" ? config : {}),\r\n };\r\n\r\n // use getElement() with the default \"body\" to get a fresh Element on each instantiation\r\n config.rootElement = getElement(config.rootElement);\r\n typeCheckConfig(NAME, config, DefaultType);\r\n return config;\r\n }\r\n\r\n _append() {\r\n if (this._isAppended) {\r\n return;\r\n }\r\n\r\n this._config.rootElement.append(this._getElement());\r\n\r\n EventHandler.on(this._getElement(), EVENT_MOUSEDOWN, () => {\r\n execute(this._config.clickCallback);\r\n });\r\n\r\n this._isAppended = true;\r\n }\r\n\r\n dispose() {\r\n if (!this._isAppended) {\r\n return;\r\n }\r\n\r\n EventHandler.off(this._element, EVENT_MOUSEDOWN);\r\n\r\n this._element.remove();\r\n this._isAppended = false;\r\n }\r\n\r\n _emulateAnimation(callback) {\r\n executeAfterTransition(\r\n callback,\r\n this._getElement(),\r\n this._config.isAnimated\r\n );\r\n }\r\n}\r\n\r\nexport default Backdrop;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport SelectorEngine from \"../dom/selector-engine\";\r\nimport { isVisible } from \"./index\";\r\n\r\nclass FocusTrap {\r\n constructor(element, options = {}, toggler) {\r\n this._element = element;\r\n this._toggler = toggler;\r\n this._event = options.event || \"blur\";\r\n this._condition = options.condition || (() => true);\r\n this._selector =\r\n options.selector ||\r\n 'button, a, input, select, textarea, [tabindex]:not([tabindex=\"-1\"])';\r\n this._onlyVisible = options.onlyVisible || false;\r\n this._focusableElements = [];\r\n this._firstElement = null;\r\n this._lastElement = null;\r\n\r\n this.handler = (e) => {\r\n if (this._condition(e) && !e.shiftKey && e.target === this._lastElement) {\r\n e.preventDefault();\r\n this._firstElement.focus();\r\n } else if (\r\n this._condition(e) &&\r\n e.shiftKey &&\r\n e.target === this._firstElement\r\n ) {\r\n e.preventDefault();\r\n this._lastElement.focus();\r\n }\r\n };\r\n }\r\n\r\n trap() {\r\n this._setElements();\r\n this._init();\r\n this._setFocusTrap();\r\n }\r\n\r\n disable() {\r\n this._focusableElements.forEach((element) => {\r\n element.removeEventListener(this._event, this.handler);\r\n });\r\n\r\n if (this._toggler) {\r\n this._toggler.focus();\r\n }\r\n }\r\n\r\n update() {\r\n this._setElements();\r\n this._setFocusTrap();\r\n }\r\n\r\n _init() {\r\n const handler = (e) => {\r\n if (\r\n !this._firstElement ||\r\n e.key !== \"Tab\" ||\r\n this._focusableElements.includes(e.target)\r\n ) {\r\n return;\r\n }\r\n\r\n e.preventDefault();\r\n this._firstElement.focus();\r\n\r\n window.removeEventListener(\"keydown\", handler);\r\n };\r\n\r\n window.addEventListener(\"keydown\", handler);\r\n }\r\n\r\n _filterVisible(elements) {\r\n return elements.filter((el) => {\r\n if (!isVisible(el)) return false;\r\n\r\n const ancestors = SelectorEngine.parents(el, \"*\");\r\n\r\n for (let i = 0; i < ancestors.length; i++) {\r\n const style = window.getComputedStyle(ancestors[i]);\r\n if (\r\n style &&\r\n (style.display === \"none\" || style.visibility === \"hidden\")\r\n )\r\n return false;\r\n }\r\n return true;\r\n });\r\n }\r\n\r\n _setElements() {\r\n this._focusableElements = SelectorEngine.focusableChildren(this._element);\r\n\r\n if (this._onlyVisible) {\r\n this._focusableElements = this._filterVisible(this._focusableElements);\r\n }\r\n\r\n this._firstElement = this._focusableElements[0];\r\n this._lastElement =\r\n this._focusableElements[this._focusableElements.length - 1];\r\n }\r\n\r\n _setFocusTrap() {\r\n this._focusableElements.forEach((element, i) => {\r\n if (i === this._focusableElements.length - 1 || i === 0) {\r\n element.addEventListener(this._event, this.handler);\r\n } else {\r\n element.removeEventListener(this._event, this.handler);\r\n }\r\n });\r\n }\r\n}\r\n\r\nexport default FocusTrap;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport EventHandler from \"../dom/event-handler\";\r\nimport { getElementFromSelector, isDisabled } from \"./index\";\r\nlet addedEventsList = [];\r\n\r\nconst enableDismissTrigger = (component, method = \"hide\") => {\r\n const clickEvent = `click.dismiss${component.EVENT_KEY}`;\r\n const name = component.NAME;\r\n\r\n if (addedEventsList.includes(name)) {\r\n return;\r\n }\r\n\r\n addedEventsList.push(name);\r\n\r\n EventHandler.on(\r\n document,\r\n clickEvent,\r\n `[data-te-${name}-dismiss]`,\r\n function (event) {\r\n if ([\"A\", \"AREA\"].includes(this.tagName)) {\r\n event.preventDefault();\r\n }\r\n\r\n if (isDisabled(this)) {\r\n return;\r\n }\r\n\r\n const target =\r\n getElementFromSelector(this) ||\r\n this.closest(`.${name}`) ||\r\n this.closest(`[data-te-${name}-init]`);\r\n\r\n if (!target) {\r\n return;\r\n }\r\n const instance = component.getOrCreateInstance(target);\r\n\r\n // Method argument is left, for Alert and only, as it doesn't implement the 'hide' method\r\n instance[method]();\r\n }\r\n );\r\n};\r\n\r\nexport { enableDismissTrigger };\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport { typeCheckConfig } from \"../util/index\";\r\nimport ScrollBarHelper from \"../util/scrollbar\";\r\nimport EventHandler from \"../dom/event-handler\";\r\nimport BaseComponent from \"../base-component\";\r\nimport SelectorEngine from \"../dom/selector-engine\";\r\nimport Manipulator from \"../dom/manipulator\";\r\nimport Backdrop from \"../util/backdrop\";\r\nimport FocusTrap from \"../util/focusTrap\";\r\nimport { enableDismissTrigger } from \"../util/component-functions\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst NAME = \"offcanvas\";\r\nconst DATA_KEY = \"te.offcanvas\";\r\nconst EVENT_KEY = `.${DATA_KEY}`;\r\nconst DATA_API_KEY = \".data-api\";\r\nconst EVENT_LOAD_DATA_API = `load${EVENT_KEY}${DATA_API_KEY}`;\r\nconst ESCAPE_KEY = \"Escape\";\r\n\r\nconst Default = {\r\n backdrop: true,\r\n keyboard: true,\r\n scroll: false,\r\n};\r\n\r\nconst DefaultType = {\r\n backdrop: \"boolean\",\r\n keyboard: \"boolean\",\r\n scroll: \"boolean\",\r\n};\r\n\r\nconst CLASS_NAME_SHOW = \"show\";\r\nconst OPEN_SELECTOR = \"[data-te-offcanvas-init][data-te-offcanvas-show]\";\r\n\r\nconst EVENT_SHOW = `show${EVENT_KEY}`;\r\nconst EVENT_SHOWN = `shown${EVENT_KEY}`;\r\nconst EVENT_HIDE = `hide${EVENT_KEY}`;\r\nconst EVENT_HIDDEN = `hidden${EVENT_KEY}`;\r\nconst EVENT_KEYDOWN_DISMISS = `keydown.dismiss${EVENT_KEY}`;\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nClass Definition\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nclass Offcanvas extends BaseComponent {\r\n constructor(element, config) {\r\n super(element);\r\n\r\n this._config = this._getConfig(config);\r\n this._isShown = false;\r\n this._backdrop = this._initializeBackDrop();\r\n this._focustrap = this._initializeFocusTrap();\r\n this._addEventListeners();\r\n this._didInit = false;\r\n this._init();\r\n }\r\n\r\n // Getters\r\n\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n static get Default() {\r\n return Default;\r\n }\r\n\r\n // Public\r\n\r\n toggle(relatedTarget) {\r\n return this._isShown ? this.hide() : this.show(relatedTarget);\r\n }\r\n\r\n show(relatedTarget) {\r\n if (this._isShown) {\r\n return;\r\n }\r\n\r\n const showEvent = EventHandler.trigger(this._element, EVENT_SHOW, {\r\n relatedTarget,\r\n });\r\n\r\n if (showEvent.defaultPrevented) {\r\n return;\r\n }\r\n\r\n this._isShown = true;\r\n this._element.style.visibility = \"visible\";\r\n\r\n this._backdrop.show();\r\n\r\n if (!this._config.scroll) {\r\n new ScrollBarHelper().hide();\r\n }\r\n\r\n this._element.removeAttribute(\"aria-hidden\");\r\n this._element.setAttribute(\"aria-modal\", true);\r\n this._element.setAttribute(\"role\", \"dialog\");\r\n this._element.setAttribute(`data-te-offcanvas-${CLASS_NAME_SHOW}`, \"\");\r\n\r\n const completeCallBack = () => {\r\n if (!this._config.scroll) {\r\n this._focustrap.trap();\r\n }\r\n\r\n EventHandler.trigger(this._element, EVENT_SHOWN, { relatedTarget });\r\n };\r\n\r\n this._queueCallback(completeCallBack, this._element, true);\r\n }\r\n\r\n hide() {\r\n if (!this._isShown) {\r\n return;\r\n }\r\n\r\n const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE);\r\n\r\n if (hideEvent.defaultPrevented) {\r\n return;\r\n }\r\n\r\n this._focustrap.disable();\r\n this._element.blur();\r\n this._isShown = false;\r\n this._element.removeAttribute(`data-te-offcanvas-${CLASS_NAME_SHOW}`);\r\n this._backdrop.hide();\r\n\r\n const completeCallback = () => {\r\n this._element.setAttribute(\"aria-hidden\", true);\r\n this._element.removeAttribute(\"aria-modal\");\r\n this._element.removeAttribute(\"role\");\r\n this._element.style.visibility = \"hidden\";\r\n\r\n if (!this._config.scroll) {\r\n new ScrollBarHelper().reset();\r\n }\r\n\r\n EventHandler.trigger(this._element, EVENT_HIDDEN);\r\n };\r\n\r\n this._queueCallback(completeCallback, this._element, true);\r\n }\r\n\r\n dispose() {\r\n this._backdrop.dispose();\r\n this._focustrap.disable();\r\n super.dispose();\r\n }\r\n\r\n // Private\r\n _init() {\r\n if (this._didInit) {\r\n return;\r\n }\r\n\r\n EventHandler.on(window, EVENT_LOAD_DATA_API, () =>\r\n SelectorEngine.find(OPEN_SELECTOR).forEach((el) =>\r\n Offcanvas.getOrCreateInstance(el).show()\r\n )\r\n );\r\n\r\n this._didInit = true;\r\n enableDismissTrigger(Offcanvas);\r\n }\r\n\r\n _getConfig(config) {\r\n config = {\r\n ...Default,\r\n ...Manipulator.getDataAttributes(this._element),\r\n ...(typeof config === \"object\" ? config : {}),\r\n };\r\n typeCheckConfig(NAME, config, DefaultType);\r\n return config;\r\n }\r\n\r\n _initializeBackDrop() {\r\n return new Backdrop({\r\n isVisible: this._config.backdrop,\r\n isAnimated: true,\r\n rootElement: this._element.parentNode,\r\n clickCallback: () => this.hide(),\r\n });\r\n }\r\n\r\n _initializeFocusTrap() {\r\n return new FocusTrap(this._element, {\r\n event: \"keydown\",\r\n condition: (event) => event.key === \"Tab\",\r\n });\r\n }\r\n\r\n _addEventListeners() {\r\n EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS, (event) => {\r\n if (this._config.keyboard && event.key === ESCAPE_KEY) {\r\n this.hide();\r\n }\r\n });\r\n }\r\n\r\n // Static\r\n\r\n static jQueryInterface(config) {\r\n return this.each(function () {\r\n const data = Offcanvas.getOrCreateInstance(this, config);\r\n\r\n if (typeof config !== \"string\") {\r\n return;\r\n }\r\n\r\n if (\r\n data[config] === undefined ||\r\n config.startsWith(\"_\") ||\r\n config === \"constructor\"\r\n ) {\r\n throw new TypeError(`No method named \"${config}\"`);\r\n }\r\n\r\n data[config](this);\r\n });\r\n }\r\n}\r\n\r\nexport default Offcanvas;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport { typeCheckConfig, isVisible } from \"../util/index\";\r\nimport EventHandler from \"../dom/event-handler\";\r\nimport BaseComponent from \"../base-component\";\r\nimport Manipulator from \"../dom/manipulator\";\r\nimport { enableDismissTrigger } from \"../util/component-functions\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst NAME = \"alert\";\r\nconst DATA_KEY = \"te.alert\";\r\nconst EVENT_KEY = `.${DATA_KEY}`;\r\n\r\nconst EVENT_CLOSE = `close${EVENT_KEY}`;\r\nconst EVENT_CLOSED = `closed${EVENT_KEY}`;\r\n\r\nconst SHOW_DATA_ATTRIBUTE = \"data-te-alert-show\";\r\n\r\nconst DefaultType = {\r\n animation: \"boolean\",\r\n autohide: \"boolean\",\r\n delay: \"number\",\r\n};\r\n\r\nconst Default = {\r\n animation: true,\r\n autohide: true,\r\n delay: 1000,\r\n};\r\n\r\nconst DefaultClasses = {\r\n fadeIn:\r\n \"animate-[fade-in_0.3s_both] p-[auto] motion-reduce:transition-none motion-reduce:animate-none\",\r\n fadeOut:\r\n \"animate-[fade-out_0.3s_both] p-[auto] motion-reduce:transition-none motion-reduce:animate-none\",\r\n};\r\n\r\nconst DefaultClassesType = {\r\n fadeIn: \"string\",\r\n fadeOut: \"string\",\r\n};\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nClass Definition\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nclass Alert extends BaseComponent {\r\n constructor(element, config, classes) {\r\n super(element);\r\n this._element = element;\r\n this._config = this._getConfig(config);\r\n this._classes = this._getClasses(classes);\r\n this._didInit = false;\r\n this._init();\r\n }\r\n\r\n // Getters\r\n static get DefaultType() {\r\n return DefaultType;\r\n }\r\n\r\n static get Default() {\r\n return Default;\r\n }\r\n\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n // Public\r\n\r\n close() {\r\n const closeEvent = EventHandler.trigger(this._element, EVENT_CLOSE);\r\n\r\n if (closeEvent.defaultPrevented) {\r\n return;\r\n }\r\n\r\n let timeout = 0;\r\n if (this._config.animation) {\r\n timeout = 300;\r\n Manipulator.addClass(this._element, this._classes.fadeOut);\r\n }\r\n this._element.removeAttribute(SHOW_DATA_ATTRIBUTE);\r\n\r\n setTimeout(() => {\r\n this._queueCallback(\r\n () => this._destroyElement(),\r\n this._element,\r\n this._config.animation\r\n );\r\n }, timeout);\r\n }\r\n\r\n show() {\r\n if (!this._element) {\r\n return;\r\n }\r\n\r\n if (this._config.autohide) {\r\n this._setupAutohide();\r\n }\r\n if (!this._element.hasAttribute(SHOW_DATA_ATTRIBUTE)) {\r\n Manipulator.removeClass(this._element, \"hidden\");\r\n Manipulator.addClass(this._element, \"block\");\r\n if (isVisible(this._element)) {\r\n const handler = (e) => {\r\n Manipulator.removeClass(this._element, \"hidden\");\r\n Manipulator.addClass(this._element, \"block\");\r\n EventHandler.off(e.target, \"animationend\", handler);\r\n };\r\n this._element.setAttribute(SHOW_DATA_ATTRIBUTE, \"\");\r\n\r\n EventHandler.on(this._element, \"animationend\", handler);\r\n }\r\n }\r\n\r\n if (this._config.animation) {\r\n Manipulator.removeClass(this._element, this._classes.fadeOut);\r\n Manipulator.addClass(this._element, this._classes.fadeIn);\r\n }\r\n }\r\n\r\n hide() {\r\n if (!this._element) {\r\n return;\r\n }\r\n if (this._element.hasAttribute(SHOW_DATA_ATTRIBUTE)) {\r\n this._element.removeAttribute(SHOW_DATA_ATTRIBUTE);\r\n const handler = (e) => {\r\n Manipulator.addClass(this._element, \"hidden\");\r\n Manipulator.removeClass(this._element, \"block\");\r\n\r\n if (this._timeout !== null) {\r\n clearTimeout(this._timeout);\r\n this._timeout = null;\r\n }\r\n\r\n EventHandler.off(e.target, \"animationend\", handler);\r\n };\r\n\r\n EventHandler.on(this._element, \"animationend\", handler);\r\n\r\n Manipulator.removeClass(this._element, this._classes.fadeIn);\r\n Manipulator.addClass(this._element, this._classes.fadeOut);\r\n }\r\n }\r\n\r\n // Private\r\n _init() {\r\n if (this._didInit) {\r\n return;\r\n }\r\n enableDismissTrigger(Alert, \"close\");\r\n this._didInit = true;\r\n }\r\n\r\n _getConfig(config) {\r\n config = {\r\n ...Default,\r\n ...Manipulator.getDataAttributes(this._element),\r\n ...(typeof config === \"object\" && config ? config : {}),\r\n };\r\n\r\n typeCheckConfig(NAME, config, this.constructor.DefaultType);\r\n\r\n return config;\r\n }\r\n\r\n _getClasses(classes) {\r\n const dataAttributes = Manipulator.getDataClassAttributes(this._element);\r\n\r\n classes = {\r\n ...DefaultClasses,\r\n ...dataAttributes,\r\n ...classes,\r\n };\r\n\r\n typeCheckConfig(NAME, classes, DefaultClassesType);\r\n\r\n return classes;\r\n }\r\n\r\n _setupAutohide() {\r\n this._timeout = setTimeout(() => {\r\n this.hide();\r\n }, this._config.delay);\r\n }\r\n\r\n _destroyElement() {\r\n this._element.remove();\r\n EventHandler.trigger(this._element, EVENT_CLOSED);\r\n this.dispose();\r\n }\r\n\r\n // Static\r\n\r\n static jQueryInterface(config) {\r\n return this.each(function () {\r\n const data = Alert.getOrCreateInstance(this);\r\n\r\n if (typeof config !== \"string\") {\r\n return;\r\n }\r\n\r\n if (\r\n data[config] === undefined ||\r\n config.startsWith(\"_\") ||\r\n config === \"constructor\"\r\n ) {\r\n throw new TypeError(`No method named \"${config}\"`);\r\n }\r\n\r\n data[config](this);\r\n });\r\n }\r\n}\r\n\r\nexport default Alert;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport {\r\n getElementFromSelector,\r\n isRTL,\r\n isVisible,\r\n getNextActiveElement,\r\n reflow,\r\n triggerTransitionEnd,\r\n typeCheckConfig,\r\n} from \"../util/index\";\r\nimport EventHandler from \"../dom/event-handler\";\r\nimport Manipulator from \"../dom/manipulator\";\r\nimport SelectorEngine from \"../dom/selector-engine\";\r\nimport BaseComponent from \"../base-component\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst NAME = \"carousel\";\r\nconst DATA_KEY = \"te.carousel\";\r\nconst EVENT_KEY = `.${DATA_KEY}`;\r\nconst DATA_API_KEY = \".data-api\";\r\n\r\nconst ARROW_LEFT_KEY = \"ArrowLeft\";\r\nconst ARROW_RIGHT_KEY = \"ArrowRight\";\r\nconst TOUCHEVENT_COMPAT_WAIT = 500; // Time for mouse compat events to fire after touch\r\nconst SWIPE_THRESHOLD = 40;\r\n\r\nconst Default = {\r\n interval: 5000,\r\n keyboard: true,\r\n ride: false,\r\n pause: \"hover\",\r\n wrap: true,\r\n touch: true,\r\n};\r\n\r\nconst DefaultType = {\r\n interval: \"(number|boolean)\",\r\n keyboard: \"boolean\",\r\n ride: \"(boolean|string)\",\r\n pause: \"(string|boolean)\",\r\n wrap: \"boolean\",\r\n touch: \"boolean\",\r\n};\r\n\r\nconst DefaultClasses = {\r\n pointer: \"touch-pan-y\",\r\n block: \"!block\",\r\n visible: \"data-[te-carousel-fade]:opacity-100 data-[te-carousel-fade]:z-[1]\",\r\n invisible:\r\n \"data-[te-carousel-fade]:z-0 data-[te-carousel-fade]:opacity-0 data-[te-carousel-fade]:duration-[600ms] data-[te-carousel-fade]:delay-600\",\r\n slideRight: \"translate-x-full\",\r\n slideLeft: \"-translate-x-full\",\r\n};\r\n\r\nconst DefaultClassesType = {\r\n pointer: \"string\",\r\n block: \"string\",\r\n visible: \"string\",\r\n invisible: \"string\",\r\n slideRight: \"string\",\r\n slideLeft: \"string\",\r\n};\r\n\r\nconst ORDER_NEXT = \"next\";\r\nconst ORDER_PREV = \"prev\";\r\nconst DIRECTION_LEFT = \"left\";\r\nconst DIRECTION_RIGHT = \"right\";\r\n\r\nconst KEY_TO_DIRECTION = {\r\n [ARROW_LEFT_KEY]: DIRECTION_RIGHT,\r\n [ARROW_RIGHT_KEY]: DIRECTION_LEFT,\r\n};\r\n\r\nconst EVENT_SLIDE = `slide${EVENT_KEY}`;\r\nconst EVENT_SLID = `slid${EVENT_KEY}`;\r\nconst EVENT_KEYDOWN = `keydown${EVENT_KEY}`;\r\nconst EVENT_MOUSEENTER = `mouseenter${EVENT_KEY}`;\r\nconst EVENT_MOUSELEAVE = `mouseleave${EVENT_KEY}`;\r\nconst EVENT_TOUCHSTART = `touchstart${EVENT_KEY}`;\r\nconst EVENT_TOUCHMOVE = `touchmove${EVENT_KEY}`;\r\nconst EVENT_TOUCHEND = `touchend${EVENT_KEY}`;\r\nconst EVENT_POINTERDOWN = `pointerdown${EVENT_KEY}`;\r\nconst EVENT_POINTERUP = `pointerup${EVENT_KEY}`;\r\nconst EVENT_DRAG_START = `dragstart${EVENT_KEY}`;\r\nconst EVENT_LOAD_DATA_API = `load${EVENT_KEY}${DATA_API_KEY}`;\r\nconst EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`;\r\n\r\nconst ATTR_CAROUSEL = \"data-te-carousel-init\";\r\nconst ATTR_ACTIVE = \"data-te-carousel-active\";\r\nconst ATTR_END = \"data-te-carousel-item-end\";\r\nconst ATTR_START = \"data-te-carousel-item-start\";\r\nconst ATTR_NEXT = \"data-te-carousel-item-next\";\r\nconst ATTR_PREV = \"data-te-carousel-item-prev\";\r\nconst ATTR_POINTER_EVENT = \"data-te-carousel-pointer-event\";\r\n\r\nconst SELECTOR_DATA_CAROUSEL_INIT = \"[data-te-carousel-init]\";\r\nconst SELECTOR_DATA_ACTIVE = \"[data-te-carousel-active]\";\r\nconst SELECTOR_DATA_ITEM = \"[data-te-carousel-item]\";\r\nconst SELECTOR_DATA_ACTIVE_ITEM = `${SELECTOR_DATA_ACTIVE}${SELECTOR_DATA_ITEM}`;\r\nconst SELECTOR_DATA_ITEM_IMG = `${SELECTOR_DATA_ITEM} img`;\r\nconst SELECTOR_DATA_NEXT_PREV =\r\n \"[data-te-carousel-item-next], [data-te-carousel-item-prev]\";\r\nconst SELECTOR_DATA_INDICATORS = \"[data-te-carousel-indicators]\";\r\nconst SELECTOR_INDICATOR = \"[data-te-target]\";\r\nconst SELECTOR_DATA_SLIDE = \"[data-te-slide], [data-te-slide-to]\";\r\n\r\nconst POINTER_TYPE_TOUCH = \"touch\";\r\nconst POINTER_TYPE_PEN = \"pen\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nClass Definition\r\n------------------------------------------------------------------------\r\n*/\r\nclass Carousel extends BaseComponent {\r\n constructor(element, config, classes) {\r\n super(element);\r\n\r\n this._items = null;\r\n this._interval = null;\r\n this._activeElement = null;\r\n this._isPaused = false;\r\n this._isSliding = false;\r\n this.touchTimeout = null;\r\n this.touchStartX = 0;\r\n this.touchDeltaX = 0;\r\n\r\n this._config = this._getConfig(config);\r\n this._classes = this._getClasses(classes);\r\n this._indicatorsElement = SelectorEngine.findOne(\r\n SELECTOR_DATA_INDICATORS,\r\n this._element\r\n );\r\n this._touchSupported =\r\n \"ontouchstart\" in document.documentElement ||\r\n navigator.maxTouchPoints > 0;\r\n this._pointerEvent = Boolean(window.PointerEvent);\r\n\r\n this._setActiveElementClass();\r\n this._addEventListeners();\r\n this._didInit = false;\r\n this._init();\r\n if (this._config.ride === \"carousel\") {\r\n this.cycle();\r\n }\r\n }\r\n\r\n // Getters\r\n\r\n static get Default() {\r\n return Default;\r\n }\r\n\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n // Public\r\n\r\n next() {\r\n this._slide(ORDER_NEXT);\r\n }\r\n\r\n nextWhenVisible() {\r\n // Don't call next when the page isn't visible\r\n // or the carousel or its parent isn't visible\r\n if (!document.hidden && isVisible(this._element)) {\r\n this.next();\r\n }\r\n }\r\n\r\n prev() {\r\n this._slide(ORDER_PREV);\r\n }\r\n\r\n pause(event) {\r\n if (!event) {\r\n this._isPaused = true;\r\n }\r\n\r\n if (SelectorEngine.findOne(SELECTOR_DATA_NEXT_PREV, this._element)) {\r\n triggerTransitionEnd(this._element);\r\n this.cycle(true);\r\n }\r\n\r\n clearInterval(this._interval);\r\n this._interval = null;\r\n }\r\n\r\n cycle(event) {\r\n if (!event) {\r\n this._isPaused = false;\r\n }\r\n\r\n if (this._interval) {\r\n clearInterval(this._interval);\r\n this._interval = null;\r\n }\r\n\r\n if (this._config && this._config.interval && !this._isPaused) {\r\n this._updateInterval();\r\n\r\n this._interval = setInterval(\r\n (document.visibilityState ? this.nextWhenVisible : this.next).bind(\r\n this\r\n ),\r\n this._config.interval\r\n );\r\n }\r\n }\r\n\r\n to(index) {\r\n this._activeElement = SelectorEngine.findOne(\r\n SELECTOR_DATA_ACTIVE_ITEM,\r\n this._element\r\n );\r\n const activeIndex = this._getItemIndex(this._activeElement);\r\n\r\n if (index > this._items.length - 1 || index < 0) {\r\n return;\r\n }\r\n\r\n if (this._isSliding) {\r\n EventHandler.one(this._element, EVENT_SLID, () => this.to(index));\r\n return;\r\n }\r\n\r\n if (activeIndex === index) {\r\n this.pause();\r\n this.cycle();\r\n return;\r\n }\r\n\r\n const order = index > activeIndex ? ORDER_NEXT : ORDER_PREV;\r\n\r\n this._slide(order, this._items[index]);\r\n }\r\n\r\n // Private\r\n _init() {\r\n if (this._didInit) {\r\n return;\r\n }\r\n EventHandler.on(\r\n document,\r\n EVENT_CLICK_DATA_API,\r\n SELECTOR_DATA_SLIDE,\r\n Carousel.dataApiClickHandler\r\n );\r\n\r\n EventHandler.on(window, EVENT_LOAD_DATA_API, () => {\r\n const carousels = SelectorEngine.find(SELECTOR_DATA_CAROUSEL_INIT);\r\n\r\n for (let i = 0, len = carousels.length; i < len; i++) {\r\n Carousel.carouselInterface(\r\n carousels[i],\r\n Carousel.getInstance(carousels[i])\r\n );\r\n }\r\n });\r\n\r\n this._didInit = true;\r\n }\r\n\r\n _getConfig(config) {\r\n config = {\r\n ...Default,\r\n ...Manipulator.getDataAttributes(this._element),\r\n ...(typeof config === \"object\" ? config : {}),\r\n };\r\n typeCheckConfig(NAME, config, DefaultType);\r\n return config;\r\n }\r\n\r\n _getClasses(classes) {\r\n const dataAttributes = Manipulator.getDataClassAttributes(this._element);\r\n\r\n classes = {\r\n ...DefaultClasses,\r\n ...dataAttributes,\r\n ...classes,\r\n };\r\n\r\n typeCheckConfig(NAME, classes, DefaultClassesType);\r\n\r\n return classes;\r\n }\r\n\r\n _enableCycle() {\r\n if (!this._config.ride) {\r\n return;\r\n }\r\n\r\n if (this._isSliding) {\r\n EventHandler.one(this._element, EVENT_SLID, () => this.cycle());\r\n return;\r\n }\r\n\r\n this.cycle();\r\n }\r\n\r\n _applyInitialClasses() {\r\n const activeElement = SelectorEngine.findOne(\r\n SELECTOR_DATA_ACTIVE_ITEM,\r\n this._element\r\n );\r\n activeElement.classList.add(\r\n this._classes.block,\r\n ...this._classes.visible.split(\" \")\r\n );\r\n\r\n this._setActiveIndicatorElement(activeElement);\r\n }\r\n\r\n _handleSwipe() {\r\n const absDeltax = Math.abs(this.touchDeltaX);\r\n\r\n if (absDeltax <= SWIPE_THRESHOLD) {\r\n return;\r\n }\r\n\r\n const direction = absDeltax / this.touchDeltaX;\r\n\r\n this.touchDeltaX = 0;\r\n\r\n if (!direction) {\r\n return;\r\n }\r\n\r\n this._slide(direction > 0 ? DIRECTION_RIGHT : DIRECTION_LEFT);\r\n }\r\n\r\n _setActiveElementClass() {\r\n this._activeElement = SelectorEngine.findOne(\r\n SELECTOR_DATA_ACTIVE_ITEM,\r\n this._element\r\n );\r\n Manipulator.addClass(this._activeElement, \"hidden\");\r\n }\r\n\r\n _addEventListeners() {\r\n if (this._config.keyboard) {\r\n EventHandler.on(this._element, EVENT_KEYDOWN, (event) =>\r\n this._keydown(event)\r\n );\r\n }\r\n\r\n if (this._config.pause === \"hover\") {\r\n EventHandler.on(this._element, EVENT_MOUSEENTER, (event) =>\r\n this.pause(event)\r\n );\r\n EventHandler.on(this._element, EVENT_MOUSELEAVE, (event) =>\r\n this._enableCycle(event)\r\n );\r\n }\r\n\r\n if (this._config.touch && this._touchSupported) {\r\n this._addTouchEventListeners();\r\n }\r\n\r\n this._applyInitialClasses();\r\n }\r\n\r\n _addTouchEventListeners() {\r\n const hasPointerPenTouch = (event) => {\r\n return (\r\n this._pointerEvent &&\r\n (event.pointerType === POINTER_TYPE_PEN ||\r\n event.pointerType === POINTER_TYPE_TOUCH)\r\n );\r\n };\r\n\r\n const start = (event) => {\r\n if (hasPointerPenTouch(event)) {\r\n this.touchStartX = event.clientX;\r\n } else if (!this._pointerEvent) {\r\n this.touchStartX = event.touches[0].clientX;\r\n }\r\n };\r\n\r\n const move = (event) => {\r\n // ensure swiping with one touch and not pinching\r\n this.touchDeltaX =\r\n event.touches && event.touches.length > 1\r\n ? 0\r\n : event.touches[0].clientX - this.touchStartX;\r\n };\r\n\r\n const end = (event) => {\r\n if (hasPointerPenTouch(event)) {\r\n this.touchDeltaX = event.clientX - this.touchStartX;\r\n }\r\n\r\n this._handleSwipe();\r\n if (this._config.pause === \"hover\") {\r\n // If it's a touch-enabled device, mouseenter/leave are fired as\r\n // part of the mouse compatibility events on first tap - the carousel\r\n // would stop cycling until user tapped out of it;\r\n // here, we listen for touchend, explicitly pause the carousel\r\n // (as if it's the second time we tap on it, mouseenter compat event\r\n // is NOT fired) and after a timeout (to allow for mouse compatibility\r\n // events to fire) we explicitly restart cycling\r\n\r\n this.pause();\r\n if (this.touchTimeout) {\r\n clearTimeout(this.touchTimeout);\r\n }\r\n\r\n this.touchTimeout = setTimeout(\r\n (event) => this._enableCycle(event),\r\n TOUCHEVENT_COMPAT_WAIT + this._config.interval\r\n );\r\n }\r\n };\r\n\r\n SelectorEngine.find(SELECTOR_DATA_ITEM_IMG, this._element).forEach(\r\n (itemImg) => {\r\n EventHandler.on(itemImg, EVENT_DRAG_START, (event) =>\r\n event.preventDefault()\r\n );\r\n }\r\n );\r\n\r\n if (this._pointerEvent) {\r\n EventHandler.on(this._element, EVENT_POINTERDOWN, (event) =>\r\n start(event)\r\n );\r\n EventHandler.on(this._element, EVENT_POINTERUP, (event) => end(event));\r\n\r\n this._element.classList.add(this._classes.pointer);\r\n this._element.setAttribute(`${ATTR_POINTER_EVENT}`, \"\");\r\n } else {\r\n EventHandler.on(this._element, EVENT_TOUCHSTART, (event) => start(event));\r\n EventHandler.on(this._element, EVENT_TOUCHMOVE, (event) => move(event));\r\n EventHandler.on(this._element, EVENT_TOUCHEND, (event) => end(event));\r\n }\r\n }\r\n\r\n _keydown(event) {\r\n if (/input|textarea/i.test(event.target.tagName)) {\r\n return;\r\n }\r\n\r\n const direction = KEY_TO_DIRECTION[event.key];\r\n if (direction) {\r\n event.preventDefault();\r\n this._slide(direction);\r\n }\r\n }\r\n\r\n _getItemIndex(element) {\r\n this._items =\r\n element && element.parentNode\r\n ? SelectorEngine.find(SELECTOR_DATA_ITEM, element.parentNode)\r\n : [];\r\n\r\n return this._items.indexOf(element);\r\n }\r\n\r\n _getItemByOrder(order, activeElement) {\r\n const isNext = order === ORDER_NEXT;\r\n return getNextActiveElement(\r\n this._items,\r\n activeElement,\r\n isNext,\r\n this._config.wrap\r\n );\r\n }\r\n\r\n _triggerSlideEvent(relatedTarget, eventDirectionName) {\r\n const targetIndex = this._getItemIndex(relatedTarget);\r\n const fromIndex = this._getItemIndex(\r\n SelectorEngine.findOne(SELECTOR_DATA_ACTIVE_ITEM, this._element)\r\n );\r\n\r\n return EventHandler.trigger(this._element, EVENT_SLIDE, {\r\n relatedTarget,\r\n direction: eventDirectionName,\r\n from: fromIndex,\r\n to: targetIndex,\r\n });\r\n }\r\n\r\n _setActiveIndicatorElement(element) {\r\n if (this._indicatorsElement) {\r\n const activeIndicator = SelectorEngine.findOne(\r\n SELECTOR_DATA_ACTIVE,\r\n this._indicatorsElement\r\n );\r\n\r\n activeIndicator.removeAttribute(ATTR_ACTIVE);\r\n activeIndicator.removeAttribute(\"aria-current\");\r\n activeIndicator.classList.remove(\"!opacity-100\");\r\n\r\n const indicators = SelectorEngine.find(\r\n SELECTOR_INDICATOR,\r\n this._indicatorsElement\r\n );\r\n\r\n for (let i = 0; i < indicators.length; i++) {\r\n if (\r\n Number.parseInt(\r\n indicators[i].getAttribute(\"data-te-slide-to\"),\r\n 10\r\n ) === this._getItemIndex(element)\r\n ) {\r\n indicators[i].setAttribute(`${ATTR_ACTIVE}`, \"\");\r\n indicators[i].setAttribute(\"aria-current\", \"true\");\r\n indicators[i].classList.add(\"!opacity-100\");\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n _updateInterval() {\r\n const element =\r\n this._activeElement ||\r\n SelectorEngine.findOne(SELECTOR_DATA_ACTIVE_ITEM, this._element);\r\n\r\n if (!element) {\r\n return;\r\n }\r\n\r\n const elementInterval = Number.parseInt(\r\n element.getAttribute(\"data-te-interval\"),\r\n 10\r\n );\r\n\r\n if (elementInterval) {\r\n this._config.defaultInterval =\r\n this._config.defaultInterval || this._config.interval;\r\n this._config.interval = elementInterval;\r\n } else {\r\n this._config.interval =\r\n this._config.defaultInterval || this._config.interval;\r\n }\r\n }\r\n\r\n _slide(directionOrOrder, element) {\r\n const order = this._directionToOrder(directionOrOrder);\r\n\r\n const activeElement = SelectorEngine.findOne(\r\n SELECTOR_DATA_ACTIVE_ITEM,\r\n this._element\r\n );\r\n const activeElementIndex = this._getItemIndex(activeElement);\r\n\r\n const nextElement = element || this._getItemByOrder(order, activeElement);\r\n const nextElementIndex = this._getItemIndex(nextElement);\r\n\r\n const isCycling = Boolean(this._interval);\r\n\r\n const isNext = order === ORDER_NEXT;\r\n const directionalAttr = isNext ? ATTR_START : ATTR_END;\r\n const orderAttr = isNext ? ATTR_NEXT : ATTR_PREV;\r\n const eventDirectionName = this._orderToDirection(order);\r\n\r\n const activeClass =\r\n directionalAttr === ATTR_START\r\n ? this._classes.slideLeft\r\n : this._classes.slideRight;\r\n const nextClass =\r\n directionalAttr !== ATTR_START\r\n ? this._classes.slideLeft\r\n : this._classes.slideRight;\r\n\r\n if (nextElement && nextElement.hasAttribute(ATTR_ACTIVE)) {\r\n this._isSliding = false;\r\n return;\r\n }\r\n\r\n if (this._isSliding) {\r\n return;\r\n }\r\n\r\n const slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName);\r\n if (slideEvent.defaultPrevented) {\r\n return;\r\n }\r\n\r\n if (!activeElement || !nextElement) {\r\n // Some weirdness is happening, so we bail\r\n return;\r\n }\r\n\r\n this._isSliding = true;\r\n\r\n if (isCycling) {\r\n this.pause();\r\n }\r\n\r\n this._setActiveIndicatorElement(nextElement);\r\n this._activeElement = nextElement;\r\n\r\n const triggerSlidEvent = () => {\r\n EventHandler.trigger(this._element, EVENT_SLID, {\r\n relatedTarget: nextElement,\r\n direction: eventDirectionName,\r\n from: activeElementIndex,\r\n to: nextElementIndex,\r\n });\r\n };\r\n\r\n if (this._element.hasAttribute(ATTR_CAROUSEL)) {\r\n nextElement.setAttribute(`${orderAttr}`, \"\");\r\n nextElement.classList.add(this._classes.block, nextClass);\r\n\r\n reflow(nextElement);\r\n\r\n activeElement.setAttribute(`${directionalAttr}`, \"\");\r\n activeElement.classList.add(\r\n activeClass,\r\n ...this._classes.invisible.split(\" \")\r\n );\r\n activeElement.classList.remove(...this._classes.visible.split(\" \"));\r\n\r\n nextElement.setAttribute(`${directionalAttr}`, \"\");\r\n nextElement.classList.add(...this._classes.visible.split(\" \"));\r\n nextElement.classList.remove(\r\n this._classes.slideRight,\r\n this._classes.slideLeft\r\n );\r\n\r\n const completeCallBack = () => {\r\n nextElement.removeAttribute(directionalAttr);\r\n nextElement.removeAttribute(orderAttr);\r\n nextElement.setAttribute(`${ATTR_ACTIVE}`, \"\");\r\n\r\n activeElement.removeAttribute(ATTR_ACTIVE);\r\n activeElement.classList.remove(\r\n activeClass,\r\n ...this._classes.invisible.split(\" \"),\r\n this._classes.block\r\n );\r\n activeElement.removeAttribute(orderAttr);\r\n activeElement.removeAttribute(directionalAttr);\r\n\r\n this._isSliding = false;\r\n\r\n setTimeout(triggerSlidEvent, 0);\r\n };\r\n\r\n this._queueCallback(completeCallBack, activeElement, true);\r\n } else {\r\n activeElement.removeAttribute(ATTR_ACTIVE);\r\n activeElement.classList.remove(this._classes.block);\r\n\r\n nextElement.setAttribute(`${ATTR_ACTIVE}`, \"\");\r\n nextElement.classList.add(this._classes.block);\r\n\r\n this._isSliding = false;\r\n triggerSlidEvent();\r\n }\r\n\r\n if (isCycling) {\r\n this.cycle();\r\n }\r\n }\r\n\r\n _directionToOrder(direction) {\r\n if (![DIRECTION_RIGHT, DIRECTION_LEFT].includes(direction)) {\r\n return direction;\r\n }\r\n\r\n if (isRTL()) {\r\n return direction === DIRECTION_LEFT ? ORDER_PREV : ORDER_NEXT;\r\n }\r\n\r\n return direction === DIRECTION_LEFT ? ORDER_NEXT : ORDER_PREV;\r\n }\r\n\r\n _orderToDirection(order) {\r\n if (![ORDER_NEXT, ORDER_PREV].includes(order)) {\r\n return order;\r\n }\r\n\r\n if (isRTL()) {\r\n return order === ORDER_PREV ? DIRECTION_LEFT : DIRECTION_RIGHT;\r\n }\r\n\r\n return order === ORDER_PREV ? DIRECTION_RIGHT : DIRECTION_LEFT;\r\n }\r\n\r\n // Static\r\n\r\n static carouselInterface(element, config) {\r\n const data = Carousel.getOrCreateInstance(element, config);\r\n\r\n let { _config } = data;\r\n if (typeof config === \"object\") {\r\n _config = {\r\n ..._config,\r\n ...config,\r\n };\r\n }\r\n const action = typeof config === \"string\" ? config : config.slide;\r\n\r\n if (typeof config === \"number\") {\r\n data.to(config);\r\n return;\r\n }\r\n if (typeof action === \"string\") {\r\n if (typeof data[action] === \"undefined\") {\r\n throw new TypeError(`No method named \"${action}\"`);\r\n }\r\n\r\n data[action]();\r\n } else if (_config.interval && _config.ride === true) {\r\n data.pause();\r\n }\r\n }\r\n\r\n static jQueryInterface(config) {\r\n return this.each(function () {\r\n Carousel.carouselInterface(this, config);\r\n });\r\n }\r\n\r\n static dataApiClickHandler(event) {\r\n const target = getElementFromSelector(this);\r\n\r\n if (!target || !target.hasAttribute(ATTR_CAROUSEL)) {\r\n return;\r\n }\r\n\r\n const config = {\r\n ...Manipulator.getDataAttributes(target),\r\n ...Manipulator.getDataAttributes(this),\r\n };\r\n const slideIndex = this.getAttribute(\"data-te-slide-to\");\r\n\r\n if (slideIndex) {\r\n config.interval = false;\r\n }\r\n\r\n Carousel.carouselInterface(target, config);\r\n\r\n if (slideIndex) {\r\n Carousel.getInstance(target).to(slideIndex);\r\n }\r\n\r\n event.preventDefault();\r\n }\r\n}\r\n\r\nexport default Carousel;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport { isRTL, reflow, typeCheckConfig } from \"../util/index\";\r\nimport EventHandler from \"../dom/event-handler\";\r\nimport Manipulator from \"../dom/manipulator\";\r\nimport SelectorEngine from \"../dom/selector-engine\";\r\nimport ScrollBarHelper from \"../util/scrollbar\";\r\nimport BaseComponent from \"../base-component\";\r\nimport Backdrop from \"../util/backdrop\";\r\nimport FocusTrap from \"../util/focusTrap\";\r\n\r\nimport { enableDismissTrigger } from \"../util/component-functions\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst NAME = \"modal\";\r\nconst DATA_KEY = \"te.modal\";\r\nconst EVENT_KEY = `.${DATA_KEY}`;\r\nconst ESCAPE_KEY = \"Escape\";\r\n\r\nconst Default = {\r\n backdrop: true,\r\n keyboard: true,\r\n focus: true,\r\n modalNonInvasive: false,\r\n};\r\n\r\nconst DefaultType = {\r\n backdrop: \"(boolean|string)\",\r\n keyboard: \"boolean\",\r\n focus: \"boolean\",\r\n modalNonInvasive: \"boolean\",\r\n};\r\n\r\nconst DefaultClasses = {\r\n show: \"transform-none\",\r\n static: \"scale-[1.02]\",\r\n staticProperties: \"transition-scale duration-300 ease-in-out\",\r\n};\r\n\r\nconst DefaultClassesType = {\r\n show: \"string\",\r\n static: \"string\",\r\n staticProperties: \"string\",\r\n};\r\n\r\nconst EVENT_HIDE = `hide${EVENT_KEY}`;\r\nconst EVENT_HIDE_PREVENTED = `hidePrevented${EVENT_KEY}`;\r\nconst EVENT_HIDDEN = `hidden${EVENT_KEY}`;\r\nconst EVENT_SHOW = `show${EVENT_KEY}`;\r\nconst EVENT_SHOWN = `shown${EVENT_KEY}`;\r\nconst EVENT_RESIZE = `resize${EVENT_KEY}`;\r\nconst EVENT_CLICK_DISMISS = `click.dismiss${EVENT_KEY}`;\r\nconst EVENT_KEYDOWN_DISMISS = `keydown.dismiss${EVENT_KEY}`;\r\nconst EVENT_MOUSEUP_DISMISS = `mouseup.dismiss${EVENT_KEY}`;\r\nconst EVENT_MOUSEDOWN_DISMISS = `mousedown.dismiss${EVENT_KEY}`;\r\n\r\nconst OPEN_SELECTOR_BODY = \"data-te-modal-open\";\r\nconst OPEN_SELECTOR = \"data-te-open\";\r\nconst SELECTOR_DIALOG = \"[data-te-modal-dialog-ref]\";\r\nconst SELECTOR_MODAL_BODY = \"[data-te-modal-body-ref]\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nClass Definition\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nclass Modal extends BaseComponent {\r\n constructor(element, config, classes) {\r\n super(element);\r\n\r\n this._config = this._getConfig(config);\r\n this._classes = this._getClasses(classes);\r\n this._dialog = SelectorEngine.findOne(SELECTOR_DIALOG, this._element);\r\n this._backdrop = this._config.modalNonInvasive\r\n ? null\r\n : this._initializeBackDrop();\r\n this._focustrap = this._initializeFocusTrap();\r\n this._isShown = false;\r\n this._ignoreBackdropClick = false;\r\n this._isTransitioning = false;\r\n this._scrollBar = new ScrollBarHelper();\r\n this._didInit = false;\r\n this._init();\r\n }\r\n\r\n // Getters\r\n\r\n static get Default() {\r\n return Default;\r\n }\r\n\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n // Public\r\n\r\n toggle(relatedTarget) {\r\n return this._isShown ? this.hide() : this.show(relatedTarget);\r\n }\r\n\r\n show(relatedTarget) {\r\n if (this._isShown || this._isTransitioning) {\r\n return;\r\n }\r\n\r\n const showEvent = EventHandler.trigger(this._element, EVENT_SHOW, {\r\n relatedTarget,\r\n });\r\n\r\n if (showEvent.defaultPrevented) {\r\n return;\r\n }\r\n\r\n this._isShown = true;\r\n\r\n if (this._isAnimated()) {\r\n this._isTransitioning = true;\r\n }\r\n\r\n !this._config.modalNonInvasive && this._scrollBar.hide();\r\n\r\n document.body.setAttribute(OPEN_SELECTOR_BODY, \"true\");\r\n\r\n this._adjustDialog();\r\n\r\n this._setEscapeEvent();\r\n this._setResizeEvent();\r\n\r\n EventHandler.on(this._dialog, EVENT_MOUSEDOWN_DISMISS, () => {\r\n EventHandler.one(this._element, EVENT_MOUSEUP_DISMISS, (event) => {\r\n if (event.target === this._element) {\r\n this._ignoreBackdropClick = true;\r\n }\r\n });\r\n });\r\n this._showElement(relatedTarget);\r\n !this._config.modalNonInvasive && this._showBackdrop();\r\n }\r\n\r\n hide() {\r\n if (!this._isShown || this._isTransitioning) {\r\n return;\r\n }\r\n const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE);\r\n\r\n if (hideEvent.defaultPrevented) {\r\n return;\r\n }\r\n\r\n this._isShown = false;\r\n const isAnimated = this._isAnimated();\r\n\r\n if (isAnimated) {\r\n this._isTransitioning = true;\r\n }\r\n\r\n this._setEscapeEvent();\r\n this._setResizeEvent();\r\n\r\n this._focustrap.disable();\r\n\r\n const modalDialog = SelectorEngine.findOne(SELECTOR_DIALOG, this._element);\r\n modalDialog.classList.remove(this._classes.show);\r\n\r\n EventHandler.off(this._element, EVENT_CLICK_DISMISS);\r\n EventHandler.off(this._dialog, EVENT_MOUSEDOWN_DISMISS);\r\n\r\n this._queueCallback(() => this._hideModal(), this._element, isAnimated);\r\n this._element.removeAttribute(OPEN_SELECTOR);\r\n }\r\n\r\n dispose() {\r\n [window, this._dialog].forEach((htmlElement) =>\r\n EventHandler.off(htmlElement, EVENT_KEY)\r\n );\r\n\r\n this._backdrop && this._backdrop.dispose();\r\n this._focustrap.disable();\r\n super.dispose();\r\n }\r\n\r\n handleUpdate() {\r\n this._adjustDialog();\r\n }\r\n\r\n // Private\r\n\r\n _init() {\r\n if (this._didInit) {\r\n return;\r\n }\r\n\r\n enableDismissTrigger(Modal);\r\n\r\n this._didInit = true;\r\n }\r\n\r\n _initializeBackDrop() {\r\n return new Backdrop({\r\n isVisible: Boolean(this._config.backdrop), // 'static' option will be translated to true, and booleans will keep their value\r\n isAnimated: this._isAnimated(),\r\n });\r\n }\r\n\r\n _initializeFocusTrap() {\r\n return new FocusTrap(this._element, {\r\n event: \"keydown\",\r\n condition: (event) => event.key === \"Tab\",\r\n });\r\n }\r\n\r\n _getConfig(config) {\r\n config = {\r\n ...Default,\r\n ...Manipulator.getDataAttributes(this._element),\r\n ...(typeof config === \"object\" ? config : {}),\r\n };\r\n typeCheckConfig(NAME, config, DefaultType);\r\n return config;\r\n }\r\n\r\n _getClasses(classes) {\r\n const dataAttributes = Manipulator.getDataClassAttributes(this._element);\r\n\r\n classes = {\r\n ...DefaultClasses,\r\n ...dataAttributes,\r\n ...classes,\r\n };\r\n\r\n typeCheckConfig(NAME, classes, DefaultClassesType);\r\n\r\n return classes;\r\n }\r\n\r\n _showElement(relatedTarget) {\r\n const isAnimated = this._isAnimated();\r\n const modalBody = SelectorEngine.findOne(SELECTOR_MODAL_BODY, this._dialog);\r\n\r\n if (\r\n !this._element.parentNode ||\r\n this._element.parentNode.nodeType !== Node.ELEMENT_NODE\r\n ) {\r\n // Don't move modal's DOM position\r\n document.body.append(this._element);\r\n }\r\n\r\n this._element.style.display = \"block\";\r\n this._element.classList.remove(\"hidden\");\r\n this._element.removeAttribute(\"aria-hidden\");\r\n this._element.setAttribute(\"aria-modal\", true);\r\n this._element.setAttribute(\"role\", \"dialog\");\r\n this._element.setAttribute(`${OPEN_SELECTOR}`, \"true\");\r\n this._element.scrollTop = 0;\r\n\r\n const modalDialog = SelectorEngine.findOne(SELECTOR_DIALOG, this._element);\r\n\r\n modalDialog.classList.add(this._classes.show);\r\n modalDialog.classList.remove(\"opacity-0\");\r\n modalDialog.classList.add(\"opacity-100\");\r\n\r\n if (modalBody) {\r\n modalBody.scrollTop = 0;\r\n }\r\n\r\n if (isAnimated) {\r\n reflow(this._element);\r\n }\r\n\r\n const transitionComplete = () => {\r\n if (this._config.focus) {\r\n this._focustrap.trap();\r\n }\r\n\r\n this._isTransitioning = false;\r\n EventHandler.trigger(this._element, EVENT_SHOWN, {\r\n relatedTarget,\r\n });\r\n };\r\n\r\n this._queueCallback(transitionComplete, this._dialog, isAnimated);\r\n }\r\n\r\n _setEscapeEvent() {\r\n if (this._isShown) {\r\n EventHandler.on(document, EVENT_KEYDOWN_DISMISS, (event) => {\r\n if (this._config.keyboard && event.key === ESCAPE_KEY) {\r\n event.preventDefault();\r\n this.hide();\r\n } else if (!this._config.keyboard && event.key === ESCAPE_KEY) {\r\n this._triggerBackdropTransition();\r\n }\r\n });\r\n } else {\r\n EventHandler.off(this._element, EVENT_KEYDOWN_DISMISS);\r\n }\r\n }\r\n\r\n _setResizeEvent() {\r\n if (this._isShown) {\r\n EventHandler.on(window, EVENT_RESIZE, () => this._adjustDialog());\r\n } else {\r\n EventHandler.off(window, EVENT_RESIZE);\r\n }\r\n }\r\n\r\n _hideModal() {\r\n const modalDialog = SelectorEngine.findOne(SELECTOR_DIALOG, this._element);\r\n modalDialog.classList.remove(this._classes.show);\r\n modalDialog.classList.remove(\"opacity-100\");\r\n modalDialog.classList.add(\"opacity-0\");\r\n\r\n setTimeout(() => {\r\n this._element.style.display = \"none\";\r\n }, 300);\r\n\r\n this._element.setAttribute(\"aria-hidden\", true);\r\n this._element.removeAttribute(\"aria-modal\");\r\n this._element.removeAttribute(\"role\");\r\n this._isTransitioning = false;\r\n this._backdrop &&\r\n this._backdrop.hide(() => {\r\n document.body.removeAttribute(OPEN_SELECTOR_BODY);\r\n this._resetAdjustments();\r\n !this._config.modalNonInvasive && this._scrollBar.reset();\r\n EventHandler.trigger(this._element, EVENT_HIDDEN);\r\n });\r\n }\r\n\r\n _showBackdrop(callback) {\r\n EventHandler.on(this._element, EVENT_CLICK_DISMISS, (event) => {\r\n if (this._ignoreBackdropClick) {\r\n this._ignoreBackdropClick = false;\r\n return;\r\n }\r\n\r\n if (event.target !== event.currentTarget) {\r\n return;\r\n }\r\n\r\n if (this._config.backdrop === true) {\r\n this.hide();\r\n } else if (this._config.backdrop === \"static\") {\r\n this._triggerBackdropTransition();\r\n }\r\n });\r\n\r\n this._backdrop && this._backdrop.show(callback);\r\n }\r\n\r\n _isAnimated() {\r\n const animate = SelectorEngine.findOne(SELECTOR_DIALOG, this._element);\r\n return !!animate;\r\n }\r\n\r\n _triggerBackdropTransition() {\r\n const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED);\r\n if (hideEvent.defaultPrevented) {\r\n return;\r\n }\r\n\r\n const { classList, scrollHeight, style } = this._element;\r\n const isModalOverflowing =\r\n scrollHeight > document.documentElement.clientHeight;\r\n\r\n // return if the following background transition hasn't yet completed\r\n if (\r\n (!isModalOverflowing && style.overflowY === \"hidden\") ||\r\n classList.contains(this._classes.static)\r\n ) {\r\n return;\r\n }\r\n\r\n if (!isModalOverflowing) {\r\n style.overflowY = \"hidden\";\r\n }\r\n\r\n classList.add(...this._classes.static.split(\" \"));\r\n classList.add(...this._classes.staticProperties.split(\" \"));\r\n\r\n this._queueCallback(() => {\r\n classList.remove(this._classes.static);\r\n\r\n setTimeout(() => {\r\n classList.remove(...this._classes.staticProperties.split(\" \"));\r\n }, 300);\r\n\r\n if (!isModalOverflowing) {\r\n this._queueCallback(() => {\r\n style.overflowY = \"\";\r\n }, this._dialog);\r\n }\r\n }, this._dialog);\r\n\r\n this._element.focus();\r\n }\r\n\r\n // ----------------------------------------------------------------------\r\n // the following methods are used to handle overflowing modals\r\n // ----------------------------------------------------------------------\r\n\r\n _adjustDialog() {\r\n const isModalOverflowing =\r\n this._element.scrollHeight > document.documentElement.clientHeight;\r\n const scrollbarWidth = this._scrollBar.getWidth();\r\n const isBodyOverflowing = scrollbarWidth > 0;\r\n\r\n if (\r\n (!isBodyOverflowing && isModalOverflowing && !isRTL()) ||\r\n (isBodyOverflowing && !isModalOverflowing && isRTL())\r\n ) {\r\n this._element.style.paddingLeft = `${scrollbarWidth}px`;\r\n }\r\n\r\n if (\r\n (isBodyOverflowing && !isModalOverflowing && !isRTL()) ||\r\n (!isBodyOverflowing && isModalOverflowing && isRTL())\r\n ) {\r\n this._element.style.paddingRight = `${scrollbarWidth}px`;\r\n }\r\n }\r\n\r\n _resetAdjustments() {\r\n this._element.style.paddingLeft = \"\";\r\n this._element.style.paddingRight = \"\";\r\n }\r\n\r\n // Static\r\n\r\n static jQueryInterface(config, relatedTarget) {\r\n return this.each(function () {\r\n const data = Modal.getOrCreateInstance(this, config);\r\n\r\n if (typeof config !== \"string\") {\r\n return;\r\n }\r\n\r\n if (typeof data[config] === \"undefined\") {\r\n throw new TypeError(`No method named \"${config}\"`);\r\n }\r\n\r\n data[config](relatedTarget);\r\n });\r\n }\r\n}\r\n\r\nexport default Modal;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nconst uriAttributes = new Set([\r\n \"background\",\r\n \"cite\",\r\n \"href\",\r\n \"itemtype\",\r\n \"longdesc\",\r\n \"poster\",\r\n \"src\",\r\n \"xlink:href\",\r\n]);\r\n\r\nconst ARIA_ATTRIBUTE_PATTERN = /^aria-[\\w-]*$/i;\r\n\r\n/**\r\n * A pattern that recognizes a commonly useful subset of URLs that are safe.\r\n *\r\n * Shoutout to Angular https://github.com/angular/angular/blob/12.2.x/packages/core/src/sanitization/url_sanitizer.ts\r\n */\r\nconst SAFE_URL_PATTERN =\r\n /^(?:(?:https?|mailto|ftp|tel|file|sms):|[^#&/:?]*(?:[#/?]|$))/i;\r\n\r\n/**\r\n * A pattern that matches safe data URLs. Only matches image, video and audio types.\r\n *\r\n * Shoutout to Angular https://github.com/angular/angular/blob/12.2.x/packages/core/src/sanitization/url_sanitizer.ts\r\n */\r\nconst DATA_URL_PATTERN =\r\n /^data:(?:image\\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\\/(?:mpeg|mp4|ogg|webm)|audio\\/(?:mp3|oga|ogg|opus));base64,[\\d+/a-z]+=*$/i;\r\n\r\nconst allowedAttribute = (attribute, allowedAttributeList) => {\r\n const attributeName = attribute.nodeName.toLowerCase();\r\n\r\n if (allowedAttributeList.includes(attributeName)) {\r\n if (uriAttributes.has(attributeName)) {\r\n return Boolean(\r\n SAFE_URL_PATTERN.test(attribute.nodeValue) ||\r\n DATA_URL_PATTERN.test(attribute.nodeValue)\r\n );\r\n }\r\n\r\n return true;\r\n }\r\n\r\n const regExp = allowedAttributeList.filter(\r\n (attributeRegex) => attributeRegex instanceof RegExp\r\n );\r\n\r\n // Check if a regular expression validates the attribute.\r\n for (let i = 0, len = regExp.length; i < len; i++) {\r\n if (regExp[i].test(attributeName)) {\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n};\r\n\r\nexport const DefaultAllowlist = {\r\n // Global attributes allowed on any supplied element below.\r\n \"*\": [\"class\", \"dir\", \"id\", \"lang\", \"role\", ARIA_ATTRIBUTE_PATTERN],\r\n a: [\"target\", \"href\", \"title\", \"rel\"],\r\n area: [],\r\n b: [],\r\n br: [],\r\n col: [],\r\n code: [],\r\n div: [],\r\n em: [],\r\n hr: [],\r\n h1: [],\r\n h2: [],\r\n h3: [],\r\n h4: [],\r\n h5: [],\r\n h6: [],\r\n i: [],\r\n img: [\"src\", \"srcset\", \"alt\", \"title\", \"width\", \"height\"],\r\n li: [],\r\n ol: [],\r\n p: [],\r\n pre: [],\r\n s: [],\r\n small: [],\r\n span: [],\r\n sub: [],\r\n sup: [],\r\n strong: [],\r\n u: [],\r\n ul: [],\r\n};\r\n\r\nexport function sanitizeHtml(unsafeHtml, allowList, sanitizeFn) {\r\n if (!unsafeHtml.length) {\r\n return unsafeHtml;\r\n }\r\n\r\n if (sanitizeFn && typeof sanitizeFn === \"function\") {\r\n return sanitizeFn(unsafeHtml);\r\n }\r\n\r\n const domParser = new window.DOMParser();\r\n const createdDocument = domParser.parseFromString(unsafeHtml, \"text/html\");\r\n const elements = [].concat(...createdDocument.body.querySelectorAll(\"*\"));\r\n\r\n for (let i = 0, len = elements.length; i < len; i++) {\r\n const element = elements[i];\r\n const elementName = element.nodeName.toLowerCase();\r\n\r\n if (!Object.keys(allowList).includes(elementName)) {\r\n element.remove();\r\n\r\n continue;\r\n }\r\n\r\n const attributeList = [].concat(...element.attributes);\r\n const allowedAttributes = [].concat(\r\n allowList[\"*\"] || [],\r\n allowList[elementName] || []\r\n );\r\n\r\n attributeList.forEach((attribute) => {\r\n if (!allowedAttribute(attribute, allowedAttributes)) {\r\n element.removeAttribute(attribute.nodeName);\r\n }\r\n });\r\n }\r\n\r\n return createdDocument.body.innerHTML;\r\n}\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport * as Popper from \"@popperjs/core\";\r\n\r\nimport {\r\n findShadowRoot,\r\n getElement,\r\n getUID,\r\n isElement,\r\n isRTL,\r\n noop,\r\n typeCheckConfig,\r\n} from \"../util/index\";\r\nimport { DefaultAllowlist, sanitizeHtml } from \"../util/sanitizer\";\r\nimport Data from \"../dom/data\";\r\nimport EventHandler from \"../dom/event-handler\";\r\nimport Manipulator from \"../dom/manipulator\";\r\nimport SelectorEngine from \"../dom/selector-engine\";\r\nimport BaseComponent from \"../base-component\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst NAME = \"tooltip\";\r\nconst DATA_KEY = \"te.tooltip\";\r\nconst EVENT_KEY = `.${DATA_KEY}`;\r\nconst CLASS_PREFIX = \"te-tooltip\";\r\nconst DISALLOWED_ATTRIBUTES = new Set([\"sanitize\", \"allowList\", \"sanitizeFn\"]);\r\n\r\nconst DefaultType = {\r\n animation: \"boolean\",\r\n template: \"string\",\r\n title: \"(string|element|function)\",\r\n trigger: \"string\",\r\n delay: \"(number|object)\",\r\n html: \"boolean\",\r\n selector: \"(string|boolean)\",\r\n placement: \"(string|function)\",\r\n offset: \"(array|string|function)\",\r\n container: \"(string|element|boolean)\",\r\n fallbackPlacements: \"array\",\r\n boundary: \"(string|element)\",\r\n customClass: \"(string|function)\",\r\n sanitize: \"boolean\",\r\n sanitizeFn: \"(null|function)\",\r\n allowList: \"object\",\r\n popperConfig: \"(null|object|function)\",\r\n};\r\n\r\nconst AttachmentMap = {\r\n AUTO: \"auto\",\r\n TOP: \"top\",\r\n RIGHT: isRTL() ? \"left\" : \"right\",\r\n BOTTOM: \"bottom\",\r\n LEFT: isRTL() ? \"right\" : \"left\",\r\n};\r\n\r\nconst Default = {\r\n animation: true,\r\n template:\r\n '\",\r\n trigger: \"hover focus\",\r\n title: \"\",\r\n delay: 0,\r\n html: false,\r\n selector: false,\r\n placement: \"top\",\r\n offset: [0, 0],\r\n container: false,\r\n fallbackPlacements: [\"top\", \"right\", \"bottom\", \"left\"],\r\n boundary: \"clippingParents\",\r\n customClass: \"\",\r\n sanitize: true,\r\n sanitizeFn: null,\r\n allowList: DefaultAllowlist,\r\n popperConfig: { hide: true },\r\n};\r\n\r\nconst Event = {\r\n HIDE: `hide${EVENT_KEY}`,\r\n HIDDEN: `hidden${EVENT_KEY}`,\r\n SHOW: `show${EVENT_KEY}`,\r\n SHOWN: `shown${EVENT_KEY}`,\r\n INSERTED: `inserted${EVENT_KEY}`,\r\n CLICK: `click${EVENT_KEY}`,\r\n FOCUSIN: `focusin${EVENT_KEY}`,\r\n FOCUSOUT: `focusout${EVENT_KEY}`,\r\n MOUSEENTER: `mouseenter${EVENT_KEY}`,\r\n MOUSELEAVE: `mouseleave${EVENT_KEY}`,\r\n};\r\n\r\nconst CLASS_NAME_FADE = \"fade\";\r\nconst CLASS_NAME_MODAL = \"modal\";\r\nconst CLASS_NAME_SHOW = \"show\";\r\n\r\nconst HOVER_STATE_SHOW = \"show\";\r\nconst HOVER_STATE_OUT = \"out\";\r\n\r\nconst SELECTOR_TOOLTIP_INNER = \".tooltip-inner\";\r\nconst SELECTOR_MODAL = `.${CLASS_NAME_MODAL}`;\r\n\r\nconst EVENT_MODAL_HIDE = \"hide.te.modal\";\r\n\r\nconst TRIGGER_HOVER = \"hover\";\r\nconst TRIGGER_FOCUS = \"focus\";\r\nconst TRIGGER_CLICK = \"click\";\r\nconst TRIGGER_MANUAL = \"manual\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nClass Definition\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nclass Tooltip extends BaseComponent {\r\n constructor(element, config) {\r\n if (typeof Popper === \"undefined\") {\r\n throw new TypeError(\r\n \"Bootstrap's tooltips require Popper (https://popper.js.org)\"\r\n );\r\n }\r\n\r\n super(element);\r\n\r\n // private\r\n this._isEnabled = true;\r\n this._timeout = 0;\r\n this._hoverState = \"\";\r\n this._activeTrigger = {};\r\n this._popper = null;\r\n\r\n // Protected\r\n this._config = this._getConfig(config);\r\n this.tip = null;\r\n\r\n this._setListeners();\r\n }\r\n\r\n // Getters\r\n\r\n static get Default() {\r\n return Default;\r\n }\r\n\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n static get Event() {\r\n return Event;\r\n }\r\n\r\n static get DefaultType() {\r\n return DefaultType;\r\n }\r\n\r\n // Public\r\n\r\n enable() {\r\n this._isEnabled = true;\r\n }\r\n\r\n disable() {\r\n this._isEnabled = false;\r\n }\r\n\r\n toggleEnabled() {\r\n this._isEnabled = !this._isEnabled;\r\n }\r\n\r\n toggle(event) {\r\n if (!this._isEnabled) {\r\n return;\r\n }\r\n\r\n if (event) {\r\n const context = this._initializeOnDelegatedTarget(event);\r\n\r\n context._activeTrigger.click = !context._activeTrigger.click;\r\n\r\n if (context._isWithActiveTrigger()) {\r\n context._enter(null, context);\r\n } else {\r\n context._leave(null, context);\r\n }\r\n } else {\r\n if (this.getTipElement().classList.contains(CLASS_NAME_SHOW)) {\r\n this._leave(null, this);\r\n return;\r\n }\r\n\r\n this._enter(null, this);\r\n }\r\n }\r\n\r\n dispose() {\r\n clearTimeout(this._timeout);\r\n\r\n EventHandler.off(\r\n this._element.closest(SELECTOR_MODAL),\r\n EVENT_MODAL_HIDE,\r\n this._hideModalHandler\r\n );\r\n\r\n if (this.tip) {\r\n this.tip.remove();\r\n }\r\n\r\n this._disposePopper();\r\n super.dispose();\r\n }\r\n\r\n show() {\r\n if (this._element.style.display === \"none\") {\r\n throw new Error(\"Please use show on visible elements\");\r\n }\r\n\r\n if (!(this.isWithContent() && this._isEnabled)) {\r\n return;\r\n }\r\n\r\n const showEvent = EventHandler.trigger(\r\n this._element,\r\n this.constructor.Event.SHOW\r\n );\r\n const shadowRoot = findShadowRoot(this._element);\r\n const isInTheDom =\r\n shadowRoot === null\r\n ? this._element.ownerDocument.documentElement.contains(this._element)\r\n : shadowRoot.contains(this._element);\r\n\r\n if (showEvent.defaultPrevented || !isInTheDom) {\r\n return;\r\n }\r\n\r\n // A trick to recreate a tooltip in case a new title is given by using the NOT documented `data-te-original-title`\r\n // This will be removed later in favor of a `setContent` method\r\n if (\r\n this.constructor.NAME === \"tooltip\" &&\r\n this.tip &&\r\n this.getTitle() !==\r\n this.tip.querySelector(SELECTOR_TOOLTIP_INNER).innerHTML\r\n ) {\r\n this._disposePopper();\r\n this.tip.remove();\r\n this.tip = null;\r\n }\r\n\r\n const tip = this.getTipElement();\r\n const tipId = getUID(this.constructor.NAME);\r\n\r\n tip.setAttribute(\"id\", tipId);\r\n this._element.setAttribute(\"aria-describedby\", tipId);\r\n\r\n if (this._config.animation) {\r\n setTimeout(() => {\r\n this.tip.classList.add(\"opacity-100\");\r\n this.tip.classList.remove(\"opacity-0\");\r\n }, 100);\r\n }\r\n\r\n const placement =\r\n typeof this._config.placement === \"function\"\r\n ? this._config.placement.call(this, tip, this._element)\r\n : this._config.placement;\r\n\r\n const attachment = this._getAttachment(placement);\r\n this._addAttachmentClass(attachment);\r\n\r\n const { container } = this._config;\r\n Data.setData(tip, this.constructor.DATA_KEY, this);\r\n\r\n if (!this._element.ownerDocument.documentElement.contains(this.tip)) {\r\n container.append(tip);\r\n EventHandler.trigger(this._element, this.constructor.Event.INSERTED);\r\n }\r\n\r\n if (this._popper) {\r\n this._popper.update();\r\n } else {\r\n this._popper = Popper.createPopper(\r\n this._element,\r\n tip,\r\n this._getPopperConfig(attachment)\r\n );\r\n }\r\n\r\n const notPopover = tip.getAttribute(\"id\").includes(\"tooltip\");\r\n if (notPopover) {\r\n switch (placement) {\r\n case \"bottom\":\r\n tip.classList.add(\"py-[0.4rem]\");\r\n break;\r\n case \"left\":\r\n tip.classList.add(\"px-[0.4rem]\");\r\n break;\r\n case \"right\":\r\n tip.classList.add(\"px-[0.4rem]\");\r\n break;\r\n\r\n default:\r\n tip.classList.add(\"py-[0.4rem]\");\r\n break;\r\n }\r\n }\r\n\r\n const customClass = this._resolvePossibleFunction(this._config.customClass);\r\n if (customClass) {\r\n tip.classList.add(...customClass.split(\" \"));\r\n }\r\n\r\n // If this is a touch-enabled device we add extra\r\n // empty mouseover listeners to the body's immediate children;\r\n // only needed because of broken event delegation on iOS\r\n // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html\r\n if (\"ontouchstart\" in document.documentElement) {\r\n [].concat(...document.body.children).forEach((element) => {\r\n EventHandler.on(element, \"mouseover\", noop);\r\n });\r\n }\r\n\r\n const complete = () => {\r\n const prevHoverState = this._hoverState;\r\n\r\n this._hoverState = null;\r\n EventHandler.trigger(this._element, this.constructor.Event.SHOWN);\r\n\r\n if (prevHoverState === HOVER_STATE_OUT) {\r\n this._leave(null, this);\r\n }\r\n };\r\n\r\n const isAnimated = this.tip.classList.contains(\"transition-opacity\");\r\n this._queueCallback(complete, this.tip, isAnimated);\r\n }\r\n\r\n hide() {\r\n if (!this._popper) {\r\n return;\r\n }\r\n\r\n const tip = this.getTipElement();\r\n const complete = () => {\r\n if (this._isWithActiveTrigger()) {\r\n return;\r\n }\r\n\r\n if (this._hoverState !== HOVER_STATE_SHOW) {\r\n tip.remove();\r\n }\r\n\r\n this._cleanTipClass();\r\n this._element.removeAttribute(\"aria-describedby\");\r\n EventHandler.trigger(this._element, this.constructor.Event.HIDDEN);\r\n\r\n this._disposePopper();\r\n };\r\n\r\n const hideEvent = EventHandler.trigger(\r\n this._element,\r\n this.constructor.Event.HIDE\r\n );\r\n if (hideEvent.defaultPrevented) {\r\n return;\r\n }\r\n\r\n tip.classList.add(\"opacity-0\");\r\n tip.classList.remove(\"opacity-100\");\r\n\r\n // If this is a touch-enabled device we remove the extra\r\n // empty mouseover listeners we added for iOS support\r\n if (\"ontouchstart\" in document.documentElement) {\r\n []\r\n .concat(...document.body.children)\r\n .forEach((element) => EventHandler.off(element, \"mouseover\", noop));\r\n }\r\n\r\n this._activeTrigger[TRIGGER_CLICK] = false;\r\n this._activeTrigger[TRIGGER_FOCUS] = false;\r\n this._activeTrigger[TRIGGER_HOVER] = false;\r\n\r\n const isAnimated = this.tip.classList.contains(\"opacity-0\");\r\n this._queueCallback(complete, this.tip, isAnimated);\r\n this._hoverState = \"\";\r\n }\r\n\r\n update() {\r\n if (this._popper !== null) {\r\n this._popper.update();\r\n }\r\n }\r\n\r\n // Protected\r\n\r\n isWithContent() {\r\n return Boolean(this.getTitle());\r\n }\r\n\r\n getTipElement() {\r\n if (this.tip) {\r\n return this.tip;\r\n }\r\n\r\n const element = document.createElement(\"div\");\r\n element.innerHTML = this._config.template;\r\n\r\n const tip = element.children[0];\r\n this.setContent(tip);\r\n tip.classList.remove(CLASS_NAME_FADE, CLASS_NAME_SHOW);\r\n\r\n this.tip = tip;\r\n return this.tip;\r\n }\r\n\r\n setContent(tip) {\r\n this._sanitizeAndSetContent(tip, this.getTitle(), SELECTOR_TOOLTIP_INNER);\r\n }\r\n\r\n _sanitizeAndSetContent(template, content, selector) {\r\n const templateElement = SelectorEngine.findOne(selector, template);\r\n\r\n if (!content && templateElement) {\r\n templateElement.remove();\r\n return;\r\n }\r\n\r\n // we use append for html objects to maintain js events\r\n this.setElementContent(templateElement, content);\r\n }\r\n\r\n setElementContent(element, content) {\r\n if (element === null) {\r\n return;\r\n }\r\n\r\n if (isElement(content)) {\r\n content = getElement(content);\r\n\r\n // content is a DOM node or a jQuery\r\n if (this._config.html) {\r\n if (content.parentNode !== element) {\r\n element.innerHTML = \"\";\r\n element.append(content);\r\n }\r\n } else {\r\n element.textContent = content.textContent;\r\n }\r\n\r\n return;\r\n }\r\n\r\n if (this._config.html) {\r\n if (this._config.sanitize) {\r\n content = sanitizeHtml(\r\n content,\r\n this._config.allowList,\r\n this._config.sanitizeFn\r\n );\r\n }\r\n\r\n element.innerHTML = content;\r\n } else {\r\n element.textContent = content;\r\n }\r\n }\r\n\r\n getTitle() {\r\n const title =\r\n this._element.getAttribute(\"data-te-original-title\") ||\r\n this._config.title;\r\n\r\n return this._resolvePossibleFunction(title);\r\n }\r\n\r\n updateAttachment(attachment) {\r\n if (attachment === \"right\") {\r\n return \"end\";\r\n }\r\n\r\n if (attachment === \"left\") {\r\n return \"start\";\r\n }\r\n\r\n return attachment;\r\n }\r\n\r\n // Private\r\n\r\n _initializeOnDelegatedTarget(event, context) {\r\n return (\r\n context ||\r\n this.constructor.getOrCreateInstance(\r\n event.delegateTarget,\r\n this._getDelegateConfig()\r\n )\r\n );\r\n }\r\n\r\n _getOffset() {\r\n const { offset } = this._config;\r\n\r\n if (typeof offset === \"string\") {\r\n return offset.split(\",\").map((val) => Number.parseInt(val, 10));\r\n }\r\n\r\n if (typeof offset === \"function\") {\r\n return (popperData) => offset(popperData, this._element);\r\n }\r\n\r\n return offset;\r\n }\r\n\r\n _resolvePossibleFunction(content) {\r\n return typeof content === \"function\"\r\n ? content.call(this._element)\r\n : content;\r\n }\r\n\r\n _getPopperConfig(attachment) {\r\n const defaultBsPopperConfig = {\r\n placement: attachment,\r\n modifiers: [\r\n {\r\n name: \"flip\",\r\n options: {\r\n fallbackPlacements: this._config.fallbackPlacements,\r\n },\r\n },\r\n {\r\n name: \"offset\",\r\n options: {\r\n offset: this._getOffset(),\r\n },\r\n },\r\n {\r\n name: \"preventOverflow\",\r\n options: {\r\n boundary: this._config.boundary,\r\n },\r\n },\r\n {\r\n name: \"arrow\",\r\n options: {\r\n element: `.${this.constructor.NAME}-arrow`,\r\n },\r\n },\r\n {\r\n name: \"onChange\",\r\n enabled: true,\r\n phase: \"afterWrite\",\r\n fn: (data) => this._handlePopperPlacementChange(data),\r\n },\r\n ],\r\n onFirstUpdate: (data) => {\r\n if (data.options.placement !== data.placement) {\r\n this._handlePopperPlacementChange(data);\r\n }\r\n },\r\n };\r\n\r\n return {\r\n ...defaultBsPopperConfig,\r\n ...(typeof this._config.popperConfig === \"function\"\r\n ? this._config.popperConfig(defaultBsPopperConfig)\r\n : this._config.popperConfig),\r\n };\r\n }\r\n\r\n _addAttachmentClass(attachment) {\r\n this.getTipElement().classList.add(\r\n `${this._getBasicClassPrefix()}-${this.updateAttachment(attachment)}`\r\n );\r\n }\r\n\r\n _getAttachment(placement) {\r\n return AttachmentMap[placement.toUpperCase()];\r\n }\r\n\r\n _setListeners() {\r\n const triggers = this._config.trigger.split(\" \");\r\n\r\n triggers.forEach((trigger) => {\r\n if (trigger === \"click\") {\r\n EventHandler.on(\r\n this._element,\r\n this.constructor.Event.CLICK,\r\n this._config.selector,\r\n (event) => this.toggle(event)\r\n );\r\n } else if (trigger !== TRIGGER_MANUAL) {\r\n const eventIn =\r\n trigger === TRIGGER_HOVER\r\n ? this.constructor.Event.MOUSEENTER\r\n : this.constructor.Event.FOCUSIN;\r\n const eventOut =\r\n trigger === TRIGGER_HOVER\r\n ? this.constructor.Event.MOUSELEAVE\r\n : this.constructor.Event.FOCUSOUT;\r\n\r\n EventHandler.on(\r\n this._element,\r\n eventIn,\r\n this._config.selector,\r\n (event) => this._enter(event)\r\n );\r\n EventHandler.on(\r\n this._element,\r\n eventOut,\r\n this._config.selector,\r\n (event) => this._leave(event)\r\n );\r\n }\r\n });\r\n\r\n this._hideModalHandler = () => {\r\n if (this._element) {\r\n this.hide();\r\n }\r\n };\r\n\r\n EventHandler.on(\r\n this._element.closest(SELECTOR_MODAL),\r\n EVENT_MODAL_HIDE,\r\n this._hideModalHandler\r\n );\r\n\r\n if (this._config.selector) {\r\n this._config = {\r\n ...this._config,\r\n trigger: \"manual\",\r\n selector: \"\",\r\n };\r\n } else {\r\n this._fixTitle();\r\n }\r\n }\r\n\r\n _fixTitle() {\r\n const title = this._element.getAttribute(\"title\");\r\n const originalTitleType = typeof this._element.getAttribute(\r\n \"data-te-original-title\"\r\n );\r\n\r\n if (title || originalTitleType !== \"string\") {\r\n this._element.setAttribute(\"data-te-original-title\", title || \"\");\r\n if (\r\n title &&\r\n !this._element.getAttribute(\"aria-label\") &&\r\n !this._element.textContent\r\n ) {\r\n this._element.setAttribute(\"aria-label\", title);\r\n }\r\n\r\n this._element.setAttribute(\"title\", \"\");\r\n }\r\n }\r\n\r\n _enter(event, context) {\r\n context = this._initializeOnDelegatedTarget(event, context);\r\n\r\n if (event) {\r\n context._activeTrigger[\r\n event.type === \"focusin\" ? TRIGGER_FOCUS : TRIGGER_HOVER\r\n ] = true;\r\n }\r\n\r\n if (\r\n context.getTipElement().classList.contains(CLASS_NAME_SHOW) ||\r\n context._hoverState === HOVER_STATE_SHOW\r\n ) {\r\n context._hoverState = HOVER_STATE_SHOW;\r\n return;\r\n }\r\n\r\n clearTimeout(context._timeout);\r\n\r\n context._hoverState = HOVER_STATE_SHOW;\r\n\r\n if (!context._config.delay || !context._config.delay.show) {\r\n context.show();\r\n return;\r\n }\r\n\r\n context._timeout = setTimeout(() => {\r\n if (context._hoverState === HOVER_STATE_SHOW) {\r\n context.show();\r\n }\r\n }, context._config.delay.show);\r\n }\r\n\r\n _leave(event, context) {\r\n context = this._initializeOnDelegatedTarget(event, context);\r\n\r\n if (event) {\r\n context._activeTrigger[\r\n event.type === \"focusout\" ? TRIGGER_FOCUS : TRIGGER_HOVER\r\n ] = context._element.contains(event.relatedTarget);\r\n }\r\n\r\n if (context._isWithActiveTrigger()) {\r\n return;\r\n }\r\n\r\n clearTimeout(context._timeout);\r\n\r\n context._hoverState = HOVER_STATE_OUT;\r\n\r\n if (!context._config.delay || !context._config.delay.hide) {\r\n context.hide();\r\n return;\r\n }\r\n\r\n context._timeout = setTimeout(() => {\r\n if (context._hoverState === HOVER_STATE_OUT) {\r\n context.hide();\r\n }\r\n }, context._config.delay.hide);\r\n }\r\n\r\n _isWithActiveTrigger() {\r\n for (const trigger in this._activeTrigger) {\r\n if (this._activeTrigger[trigger]) {\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n }\r\n\r\n _getConfig(config) {\r\n const dataAttributes = Manipulator.getDataAttributes(this._element);\r\n\r\n Object.keys(dataAttributes).forEach((dataAttr) => {\r\n if (DISALLOWED_ATTRIBUTES.has(dataAttr)) {\r\n delete dataAttributes[dataAttr];\r\n }\r\n });\r\n\r\n config = {\r\n ...this.constructor.Default,\r\n ...dataAttributes,\r\n ...(typeof config === \"object\" && config ? config : {}),\r\n };\r\n\r\n config.container =\r\n config.container === false ? document.body : getElement(config.container);\r\n\r\n if (typeof config.delay === \"number\") {\r\n config.delay = {\r\n show: config.delay,\r\n hide: config.delay,\r\n };\r\n }\r\n\r\n if (typeof config.title === \"number\") {\r\n config.title = config.title.toString();\r\n }\r\n\r\n if (typeof config.content === \"number\") {\r\n config.content = config.content.toString();\r\n }\r\n\r\n typeCheckConfig(NAME, config, this.constructor.DefaultType);\r\n\r\n if (config.sanitize) {\r\n config.template = sanitizeHtml(\r\n config.template,\r\n config.allowList,\r\n config.sanitizeFn\r\n );\r\n }\r\n\r\n return config;\r\n }\r\n\r\n _getDelegateConfig() {\r\n const config = {};\r\n\r\n for (const key in this._config) {\r\n if (this.constructor.Default[key] !== this._config[key]) {\r\n config[key] = this._config[key];\r\n }\r\n }\r\n\r\n // In the future can be replaced with:\r\n // const keysWithDifferentValues = Object.entries(this._config).filter(entry => this.constructor.Default[entry[0]] !== this._config[entry[0]])\r\n // `Object.fromEntries(keysWithDifferentValues)`\r\n return config;\r\n }\r\n\r\n _cleanTipClass() {\r\n const tip = this.getTipElement();\r\n const basicClassPrefixRegex = new RegExp(\r\n `(^|\\\\s)${this._getBasicClassPrefix()}\\\\S+`,\r\n \"g\"\r\n );\r\n const tabClass = tip.getAttribute(\"class\").match(basicClassPrefixRegex);\r\n if (tabClass !== null && tabClass.length > 0) {\r\n tabClass\r\n .map((token) => token.trim())\r\n .forEach((tClass) => tip.classList.remove(tClass));\r\n }\r\n }\r\n\r\n _getBasicClassPrefix() {\r\n return CLASS_PREFIX;\r\n }\r\n\r\n _handlePopperPlacementChange(popperData) {\r\n const { state } = popperData;\r\n\r\n if (!state) {\r\n return;\r\n }\r\n\r\n this.tip = state.elements.popper;\r\n this._cleanTipClass();\r\n this._addAttachmentClass(this._getAttachment(state.placement));\r\n }\r\n\r\n _disposePopper() {\r\n if (this._popper) {\r\n this._popper.destroy();\r\n this._popper = null;\r\n }\r\n }\r\n\r\n // Static\r\n\r\n static jQueryInterface(config) {\r\n return this.each(function () {\r\n const data = Tooltip.getOrCreateInstance(this, config);\r\n\r\n if (typeof config === \"string\") {\r\n if (typeof data[config] === \"undefined\") {\r\n throw new TypeError(`No method named \"${config}\"`);\r\n }\r\n\r\n data[config]();\r\n }\r\n });\r\n }\r\n}\r\n\r\nexport default Tooltip;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport Tooltip from \"./tooltip\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst NAME = \"popover\";\r\nconst DATA_KEY = \"te.popover\";\r\nconst EVENT_KEY = `.${DATA_KEY}`;\r\nconst CLASS_PREFIX = \"te-popover\";\r\n\r\nconst Default = {\r\n ...Tooltip.Default,\r\n placement: \"right\",\r\n offset: [0, 8],\r\n trigger: \"click\",\r\n content: \"\",\r\n template:\r\n '' +\r\n '' +\r\n '
' +\r\n \"
\",\r\n};\r\n\r\nconst DefaultType = {\r\n ...Tooltip.DefaultType,\r\n content: \"(string|element|function)\",\r\n};\r\n\r\nconst Event = {\r\n HIDE: `hide${EVENT_KEY}`,\r\n HIDDEN: `hidden${EVENT_KEY}`,\r\n SHOW: `show${EVENT_KEY}`,\r\n SHOWN: `shown${EVENT_KEY}`,\r\n INSERTED: `inserted${EVENT_KEY}`,\r\n CLICK: `click${EVENT_KEY}`,\r\n FOCUSIN: `focusin${EVENT_KEY}`,\r\n FOCUSOUT: `focusout${EVENT_KEY}`,\r\n MOUSEENTER: `mouseenter${EVENT_KEY}`,\r\n MOUSELEAVE: `mouseleave${EVENT_KEY}`,\r\n};\r\n\r\nconst SELECTOR_TITLE = \".popover-header\";\r\nconst SELECTOR_CONTENT = \".popover-body\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nClass Definition\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nclass Popover extends Tooltip {\r\n // Getters\r\n\r\n static get Default() {\r\n return Default;\r\n }\r\n\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n static get Event() {\r\n return Event;\r\n }\r\n\r\n static get DefaultType() {\r\n return DefaultType;\r\n }\r\n\r\n // Overrides\r\n\r\n isWithContent() {\r\n return this.getTitle() || this._getContent();\r\n }\r\n\r\n setContent(tip) {\r\n this._sanitizeAndSetContent(tip, this.getTitle(), SELECTOR_TITLE);\r\n this._sanitizeAndSetContent(tip, this._getContent(), SELECTOR_CONTENT);\r\n }\r\n\r\n // Private\r\n\r\n _getContent() {\r\n return this._resolvePossibleFunction(this._config.content);\r\n }\r\n\r\n _getBasicClassPrefix() {\r\n return CLASS_PREFIX;\r\n }\r\n\r\n // Static\r\n\r\n static jQueryInterface(config) {\r\n return this.each(function () {\r\n const data = Popover.getOrCreateInstance(this, config);\r\n\r\n if (typeof config === \"string\") {\r\n if (typeof data[config] === \"undefined\") {\r\n throw new TypeError(`No method named \"${config}\"`);\r\n }\r\n\r\n data[config]();\r\n }\r\n });\r\n }\r\n}\r\n\r\nexport default Popover;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport {\r\n getElement,\r\n getSelectorFromElement,\r\n typeCheckConfig,\r\n} from \"../util/index\";\r\nimport EventHandler from \"../dom/event-handler\";\r\nimport Manipulator from \"../dom/manipulator\";\r\nimport MDBManipulator from \"../dom/manipulator\";\r\nimport SelectorEngine from \"../dom/selector-engine\";\r\nimport BaseComponent from \"../base-component\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst NAME = \"scrollspy\";\r\nconst DATA_KEY = \"te.scrollspy\";\r\nconst EVENT_KEY = `.${DATA_KEY}`;\r\n\r\nconst Default = {\r\n offset: 10,\r\n method: \"auto\",\r\n target: \"\",\r\n};\r\n\r\nconst DefaultType = {\r\n offset: \"number\",\r\n method: \"string\",\r\n target: \"(string|element)\",\r\n};\r\n\r\nconst DefaultClasses = {\r\n active:\r\n \"!text-primary dark:!text-primary-400 font-semibold border-l-[0.125rem] border-solid border-primary dark:border-primary-400\",\r\n};\r\n\r\nconst DefaultClassesType = {\r\n active: \"string\",\r\n};\r\n\r\nconst EVENT_ACTIVATE = `activate${EVENT_KEY}`;\r\nconst EVENT_SCROLL = `scroll${EVENT_KEY}`;\r\n\r\nconst LINK_ACTIVE = \"data-te-nav-link-active\";\r\nconst SELECTOR_DROPDOWN_ITEM = \"[data-te-dropdown-item-ref]\";\r\nconst SELECTOR_NAV_LIST_GROUP = \"[data-te-nav-list-ref]\";\r\nconst SELECTOR_NAV_LINKS = \"[data-te-nav-link-ref]\";\r\nconst SELECTOR_NAV_ITEMS = \"[data-te-nav-item-ref]\";\r\nconst SELECTOR_LIST_ITEMS = \"[data-te-list-group-item-ref]\";\r\nconst SELECTOR_LINK_ITEMS = `${SELECTOR_NAV_LINKS}, ${SELECTOR_LIST_ITEMS}, ${SELECTOR_DROPDOWN_ITEM}`;\r\nconst SELECTOR_DROPDOWN = \"[data-te-dropdown-ref]\";\r\nconst SELECTOR_DROPDOWN_TOGGLE = \"[data-te-dropdown-toggle-ref]\";\r\n\r\nconst METHOD_OFFSET = \"maxOffset\";\r\nconst METHOD_POSITION = \"position\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nClass Definition\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nclass ScrollSpy extends BaseComponent {\r\n constructor(element, config, classes) {\r\n super(element);\r\n this._scrollElement =\r\n this._element.tagName === \"BODY\" ? window : this._element;\r\n this._config = this._getConfig(config);\r\n this._classes = this._getClasses(classes);\r\n this._offsets = [];\r\n this._targets = [];\r\n this._activeTarget = null;\r\n this._scrollHeight = 0;\r\n\r\n EventHandler.on(this._scrollElement, EVENT_SCROLL, () => this._process());\r\n\r\n this.refresh();\r\n this._process();\r\n }\r\n\r\n // Getters\r\n\r\n static get Default() {\r\n return Default;\r\n }\r\n\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n // Public\r\n\r\n refresh() {\r\n const autoMethod =\r\n this._scrollElement === this._scrollElement.window\r\n ? METHOD_OFFSET\r\n : METHOD_POSITION;\r\n\r\n const offsetMethod =\r\n this._config.method === \"auto\" ? autoMethod : this._config.method;\r\n\r\n const offsetBase =\r\n offsetMethod === METHOD_POSITION ? this._getScrollTop() : 0;\r\n\r\n this._offsets = [];\r\n this._targets = [];\r\n this._scrollHeight = this._getScrollHeight();\r\n\r\n const targets = SelectorEngine.find(\r\n SELECTOR_LINK_ITEMS,\r\n this._config.target\r\n );\r\n\r\n targets\r\n .map((element) => {\r\n const targetSelector = getSelectorFromElement(element);\r\n const target = targetSelector\r\n ? SelectorEngine.findOne(targetSelector)\r\n : null;\r\n\r\n if (target) {\r\n const targetBCR = target.getBoundingClientRect();\r\n if (targetBCR.width || targetBCR.height) {\r\n return [\r\n Manipulator[offsetMethod](target).top + offsetBase,\r\n targetSelector,\r\n ];\r\n }\r\n }\r\n\r\n return null;\r\n })\r\n .filter((item) => item)\r\n .sort((a, b) => a[0] - b[0])\r\n .forEach((item) => {\r\n this._offsets.push(item[0]);\r\n this._targets.push(item[1]);\r\n });\r\n }\r\n\r\n dispose() {\r\n EventHandler.off(this._scrollElement, EVENT_KEY);\r\n super.dispose();\r\n }\r\n\r\n // Private\r\n _getConfig(config) {\r\n config = {\r\n ...Default,\r\n ...Manipulator.getDataAttributes(this._element),\r\n ...(typeof config === \"object\" && config ? config : {}),\r\n };\r\n\r\n config.target = getElement(config.target) || document.documentElement;\r\n\r\n typeCheckConfig(NAME, config, DefaultType);\r\n\r\n return config;\r\n }\r\n\r\n _getClasses(classes) {\r\n const dataAttributes = MDBManipulator.getDataClassAttributes(this._element);\r\n\r\n classes = {\r\n ...DefaultClasses,\r\n ...dataAttributes,\r\n ...classes,\r\n };\r\n\r\n typeCheckConfig(NAME, classes, DefaultClassesType);\r\n\r\n return classes;\r\n }\r\n\r\n _getScrollTop() {\r\n return this._scrollElement === window\r\n ? this._scrollElement.pageYOffset\r\n : this._scrollElement.scrollTop;\r\n }\r\n\r\n _getScrollHeight() {\r\n return (\r\n this._scrollElement.scrollHeight ||\r\n Math.max(\r\n document.body.scrollHeight,\r\n document.documentElement.scrollHeight\r\n )\r\n );\r\n }\r\n\r\n _getOffsetHeight() {\r\n return this._scrollElement === window\r\n ? window.innerHeight\r\n : this._scrollElement.getBoundingClientRect().height;\r\n }\r\n\r\n _process() {\r\n const scrollTop = this._getScrollTop() + this._config.offset;\r\n const scrollHeight = this._getScrollHeight();\r\n const maxScroll =\r\n this._config.offset + scrollHeight - this._getOffsetHeight();\r\n\r\n if (this._scrollHeight !== scrollHeight) {\r\n this.refresh();\r\n }\r\n\r\n if (scrollTop >= maxScroll) {\r\n const target = this._targets[this._targets.length - 1];\r\n\r\n if (this._activeTarget !== target) {\r\n this._activate(target);\r\n }\r\n\r\n return;\r\n }\r\n\r\n if (\r\n this._activeTarget &&\r\n scrollTop < this._offsets[0] &&\r\n this._offsets[0] > 0\r\n ) {\r\n this._activeTarget = null;\r\n this._clear();\r\n return;\r\n }\r\n\r\n for (let i = this._offsets.length; i--; ) {\r\n const isActiveTarget =\r\n this._activeTarget !== this._targets[i] &&\r\n scrollTop >= this._offsets[i] &&\r\n (typeof this._offsets[i + 1] === \"undefined\" ||\r\n scrollTop < this._offsets[i + 1]);\r\n\r\n if (isActiveTarget) {\r\n this._activate(this._targets[i]);\r\n }\r\n }\r\n }\r\n\r\n _activate(target) {\r\n this._activeTarget = target;\r\n\r\n this._clear();\r\n\r\n const queries = SELECTOR_LINK_ITEMS.split(\",\").map(\r\n (selector) =>\r\n `${selector}[data-te-target=\"${target}\"],${selector}[href=\"${target}\"]`\r\n );\r\n\r\n const link = SelectorEngine.findOne(queries.join(\",\"), this._config.target);\r\n\r\n link.classList.add(...this._classes.active.split(\" \"));\r\n link.setAttribute(LINK_ACTIVE, \"\");\r\n\r\n if (link.getAttribute(SELECTOR_DROPDOWN_ITEM)) {\r\n SelectorEngine.findOne(\r\n SELECTOR_DROPDOWN_TOGGLE,\r\n link.closest(SELECTOR_DROPDOWN)\r\n ).classList.add(...this._classes.active.split(\" \"));\r\n } else {\r\n SelectorEngine.parents(link, SELECTOR_NAV_LIST_GROUP).forEach(\r\n (listGroup) => {\r\n // Set triggered links parents as active\r\n // With both and markup a parent is the previous sibling of any nav ancestor\r\n SelectorEngine.prev(\r\n listGroup,\r\n `${SELECTOR_NAV_LINKS}, ${SELECTOR_LIST_ITEMS}`\r\n ).forEach((item) => {\r\n item.classList.add(...this._classes.active.split(\" \"));\r\n item.setAttribute(LINK_ACTIVE, \"\");\r\n });\r\n\r\n // Handle special case when .nav-link is inside .nav-item\r\n SelectorEngine.prev(listGroup, SELECTOR_NAV_ITEMS).forEach(\r\n (navItem) => {\r\n SelectorEngine.children(navItem, SELECTOR_NAV_LINKS).forEach(\r\n (item) => item.classList.add(...this._classes.active.split(\" \"))\r\n );\r\n }\r\n );\r\n }\r\n );\r\n }\r\n\r\n EventHandler.trigger(this._scrollElement, EVENT_ACTIVATE, {\r\n relatedTarget: target,\r\n });\r\n }\r\n\r\n _clear() {\r\n SelectorEngine.find(SELECTOR_LINK_ITEMS, this._config.target)\r\n .filter((node) =>\r\n node.classList.contains(...this._classes.active.split(\" \"))\r\n )\r\n .forEach((node) => {\r\n node.classList.remove(...this._classes.active.split(\" \"));\r\n node.removeAttribute(LINK_ACTIVE);\r\n });\r\n }\r\n\r\n // Static\r\n\r\n static jQueryInterface(config) {\r\n return this.each(function () {\r\n const data = ScrollSpy.getOrCreateInstance(this, config);\r\n\r\n if (typeof config !== \"string\") {\r\n return;\r\n }\r\n\r\n if (typeof data[config] === \"undefined\") {\r\n throw new TypeError(`No method named \"${config}\"`);\r\n }\r\n\r\n data[config]();\r\n });\r\n }\r\n}\r\n\r\nexport default ScrollSpy;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport { getElementFromSelector, reflow, typeCheckConfig } from \"../util/index\";\r\nimport Manipulator from \"../dom/manipulator\";\r\nimport EventHandler from \"../dom/event-handler\";\r\nimport SelectorEngine from \"../dom/selector-engine\";\r\nimport BaseComponent from \"../base-component\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst NAME = \"tab\";\r\nconst DATA_KEY = \"te.tab\";\r\nconst EVENT_KEY = `.${DATA_KEY}`;\r\n\r\nconst EVENT_HIDE = `hide${EVENT_KEY}`;\r\nconst EVENT_HIDDEN = `hidden${EVENT_KEY}`;\r\nconst EVENT_SHOW = `show${EVENT_KEY}`;\r\nconst EVENT_SHOWN = `shown${EVENT_KEY}`;\r\n\r\nconst DATA_NAME_DROPDOWN_MENU = \"data-te-dropdown-menu-ref\";\r\nconst TAB_ACTIVE = \"data-te-tab-active\";\r\nconst NAV_ACTIVE = \"data-te-nav-active\";\r\n\r\nconst SELECTOR_DROPDOWN = \"[data-te-dropdown-ref]\";\r\nconst SELECTOR_NAV = \"[data-te-nav-ref]\";\r\nconst SELECTOR_TAB_ACTIVE = `[${TAB_ACTIVE}]`;\r\nconst SELECTOR_NAV_ACTIVE = `[${NAV_ACTIVE}]`;\r\nconst SELECTOR_ACTIVE_UL = \":scope > li > .active\";\r\nconst SELECTOR_DROPDOWN_TOGGLE = \"[data-te-dropdown-toggle-ref]\";\r\nconst SELECTOR_DROPDOWN_ACTIVE_CHILD =\r\n \":scope > [data-te-dropdown-menu-ref] [data-te-dropdown-show]\";\r\n\r\nconst DefaultClasses = {\r\n show: \"opacity-100\",\r\n hide: \"opacity-0\",\r\n};\r\n\r\nconst DefaultClassesType = {\r\n show: \"string\",\r\n hide: \"string\",\r\n};\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nClass Definition\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nclass Tab extends BaseComponent {\r\n constructor(element, classes) {\r\n super(element);\r\n this._classes = this._getClasses(classes);\r\n }\r\n // Getters\r\n\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n // Public\r\n\r\n show() {\r\n if (\r\n this._element.parentNode &&\r\n this._element.parentNode.nodeType === Node.ELEMENT_NODE &&\r\n this._element.getAttribute(NAV_ACTIVE) === \"\"\r\n ) {\r\n return;\r\n }\r\n\r\n let previous;\r\n const target = getElementFromSelector(this._element);\r\n const listElement = this._element.closest(SELECTOR_NAV);\r\n const activeNavElement = SelectorEngine.findOne(\r\n SELECTOR_NAV_ACTIVE,\r\n listElement\r\n );\r\n\r\n if (listElement) {\r\n const itemSelector =\r\n listElement.nodeName === \"UL\" || listElement.nodeName === \"OL\"\r\n ? SELECTOR_ACTIVE_UL\r\n : SELECTOR_TAB_ACTIVE;\r\n previous = SelectorEngine.find(itemSelector, listElement);\r\n previous = previous[previous.length - 1];\r\n }\r\n\r\n const hideEvent = previous\r\n ? EventHandler.trigger(previous, EVENT_HIDE, {\r\n relatedTarget: this._element,\r\n })\r\n : null;\r\n\r\n const showEvent = EventHandler.trigger(this._element, EVENT_SHOW, {\r\n relatedTarget: previous,\r\n });\r\n\r\n if (\r\n showEvent.defaultPrevented ||\r\n (hideEvent !== null && hideEvent.defaultPrevented)\r\n ) {\r\n return;\r\n }\r\n\r\n this._activate(\r\n this._element,\r\n listElement,\r\n null,\r\n activeNavElement,\r\n this._element\r\n );\r\n\r\n const complete = () => {\r\n EventHandler.trigger(previous, EVENT_HIDDEN, {\r\n relatedTarget: this._element,\r\n });\r\n EventHandler.trigger(this._element, EVENT_SHOWN, {\r\n relatedTarget: previous,\r\n });\r\n };\r\n\r\n if (target) {\r\n this._activate(\r\n target,\r\n target.parentNode,\r\n complete,\r\n activeNavElement,\r\n this._element\r\n );\r\n } else {\r\n complete();\r\n }\r\n }\r\n\r\n // Private\r\n\r\n _getClasses(classes) {\r\n const dataAttributes = Manipulator.getDataClassAttributes(this._element);\r\n\r\n classes = {\r\n ...DefaultClasses,\r\n ...dataAttributes,\r\n ...classes,\r\n };\r\n\r\n typeCheckConfig(NAME, classes, DefaultClassesType);\r\n\r\n return classes;\r\n }\r\n\r\n _activate(element, container, callback, activeNavElement, navElement) {\r\n const activeElements =\r\n container && (container.nodeName === \"UL\" || container.nodeName === \"OL\")\r\n ? SelectorEngine.find(SELECTOR_ACTIVE_UL, container)\r\n : SelectorEngine.children(container, SELECTOR_TAB_ACTIVE);\r\n\r\n const active = activeElements[0];\r\n const isTransitioning =\r\n callback && active && active.hasAttribute(TAB_ACTIVE);\r\n\r\n const complete = () =>\r\n this._transitionComplete(\r\n element,\r\n active,\r\n callback,\r\n activeNavElement,\r\n navElement\r\n );\r\n\r\n if (active && isTransitioning) {\r\n Manipulator.removeClass(active, this._classes.show);\r\n Manipulator.addClass(active, this._classes.hide);\r\n this._queueCallback(complete, element, true);\r\n } else {\r\n complete();\r\n }\r\n }\r\n\r\n _transitionComplete(element, active, callback, activeNavElement, navElement) {\r\n if (active && activeNavElement) {\r\n active.removeAttribute(TAB_ACTIVE);\r\n activeNavElement.removeAttribute(NAV_ACTIVE);\r\n\r\n const dropdownChild = SelectorEngine.findOne(\r\n SELECTOR_DROPDOWN_ACTIVE_CHILD,\r\n active.parentNode\r\n );\r\n\r\n if (dropdownChild) {\r\n dropdownChild.removeAttribute(TAB_ACTIVE);\r\n }\r\n\r\n if (active.getAttribute(\"role\") === \"tab\") {\r\n active.setAttribute(\"aria-selected\", false);\r\n }\r\n }\r\n\r\n element.setAttribute(TAB_ACTIVE, \"\");\r\n navElement.setAttribute(NAV_ACTIVE, \"\");\r\n\r\n if (element.getAttribute(\"role\") === \"tab\") {\r\n element.setAttribute(\"aria-selected\", true);\r\n }\r\n\r\n reflow(element);\r\n\r\n if (element.classList.contains(this._classes.hide)) {\r\n Manipulator.removeClass(element, this._classes.hide);\r\n Manipulator.addClass(element, this._classes.show);\r\n }\r\n\r\n let parent = element.parentNode;\r\n if (parent && parent.nodeName === \"LI\") {\r\n parent = parent.parentNode;\r\n }\r\n\r\n if (parent && parent.hasAttribute(DATA_NAME_DROPDOWN_MENU)) {\r\n const dropdownElement = element.closest(SELECTOR_DROPDOWN);\r\n\r\n if (dropdownElement) {\r\n SelectorEngine.find(SELECTOR_DROPDOWN_TOGGLE, dropdownElement).forEach(\r\n (dropdown) => dropdown.setAttribute(TAB_ACTIVE, \"\")\r\n );\r\n }\r\n\r\n element.setAttribute(\"aria-expanded\", true);\r\n }\r\n\r\n if (callback) {\r\n callback();\r\n }\r\n }\r\n\r\n // Static\r\n\r\n static jQueryInterface(config) {\r\n return this.each(function () {\r\n const data = Tab.getOrCreateInstance(this);\r\n\r\n if (typeof config === \"string\") {\r\n if (typeof data[config] === \"undefined\") {\r\n throw new TypeError(`No method named \"${config}\"`);\r\n }\r\n\r\n data[config]();\r\n }\r\n });\r\n }\r\n}\r\n\r\nexport default Tab;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport { reflow, typeCheckConfig } from \"../util/index\";\r\nimport EventHandler from \"../dom/event-handler\";\r\nimport Manipulator from \"../dom/manipulator\";\r\nimport BaseComponent from \"../base-component\";\r\nimport { enableDismissTrigger } from \"../util/component-functions\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst NAME = \"toast\";\r\nconst DATA_KEY = \"te.toast\";\r\nconst EVENT_KEY = `.${DATA_KEY}`;\r\n\r\nconst EVENT_MOUSEOVER = `mouseover${EVENT_KEY}`;\r\nconst EVENT_MOUSEOUT = `mouseout${EVENT_KEY}`;\r\nconst EVENT_FOCUSIN = `focusin${EVENT_KEY}`;\r\nconst EVENT_FOCUSOUT = `focusout${EVENT_KEY}`;\r\nconst EVENT_HIDE = `hide${EVENT_KEY}`;\r\nconst EVENT_HIDDEN = `hidden${EVENT_KEY}`;\r\nconst EVENT_SHOW = `show${EVENT_KEY}`;\r\nconst EVENT_SHOWN = `shown${EVENT_KEY}`;\r\n\r\nconst HIDE_DATA_ATTRIBUTE = \"data-te-toast-hide\";\r\nconst SHOW_DATA_ATTRIBUTE = \"data-te-toast-show\";\r\nconst SHOWING_DATA_ATTRIBUTE = \"data-te-toast-showing\";\r\n\r\nconst DefaultType = {\r\n animation: \"boolean\",\r\n autohide: \"boolean\",\r\n delay: \"number\",\r\n};\r\n\r\nconst Default = {\r\n animation: true,\r\n autohide: true,\r\n delay: 5000,\r\n};\r\n\r\nconst DefaultClasses = {\r\n fadeIn:\r\n \"animate-[fade-in_0.3s_both] p-[auto] motion-reduce:transition-none motion-reduce:animate-none\",\r\n fadeOut:\r\n \"animate-[fade-out_0.3s_both] p-[auto] motion-reduce:transition-none motion-reduce:animate-none\",\r\n};\r\n\r\nconst DefaultClassesType = {\r\n fadeIn: \"string\",\r\n fadeOut: \"string\",\r\n};\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nClass Definition\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nclass Toast extends BaseComponent {\r\n constructor(element, config, classes) {\r\n super(element);\r\n\r\n this._config = this._getConfig(config);\r\n this._classes = this._getClasses(classes);\r\n this._timeout = null;\r\n this._hasMouseInteraction = false;\r\n this._hasKeyboardInteraction = false;\r\n this._setListeners();\r\n this._didInit = false;\r\n this._init();\r\n }\r\n\r\n // Getters\r\n\r\n static get DefaultType() {\r\n return DefaultType;\r\n }\r\n\r\n static get Default() {\r\n return Default;\r\n }\r\n\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n // Public\r\n\r\n show() {\r\n const showEvent = EventHandler.trigger(this._element, EVENT_SHOW);\r\n\r\n if (showEvent.defaultPrevented) {\r\n return;\r\n }\r\n\r\n this._clearTimeout();\r\n\r\n if (this._config.animation) {\r\n Manipulator.removeClass(this._element, this._classes.fadeOut);\r\n Manipulator.addClass(this._element, this._classes.fadeIn);\r\n }\r\n\r\n const complete = () => {\r\n this._element.removeAttribute(SHOWING_DATA_ATTRIBUTE);\r\n EventHandler.trigger(this._element, EVENT_SHOWN);\r\n\r\n this._maybeScheduleHide();\r\n };\r\n\r\n this._element.removeAttribute(HIDE_DATA_ATTRIBUTE);\r\n reflow(this._element);\r\n this._element.setAttribute(SHOW_DATA_ATTRIBUTE, \"\");\r\n this._element.setAttribute(SHOWING_DATA_ATTRIBUTE, \"\");\r\n\r\n this._queueCallback(complete, this._element, this._config.animation);\r\n }\r\n\r\n hide() {\r\n if (!this._element || this._element.dataset.teToastShow === undefined) {\r\n return;\r\n }\r\n\r\n const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE);\r\n\r\n if (hideEvent.defaultPrevented) {\r\n return;\r\n }\r\n\r\n const complete = () => {\r\n let timeout = 0;\r\n if (this._config.animation) {\r\n timeout = 300;\r\n Manipulator.removeClass(this._element, this._classes.fadeIn);\r\n Manipulator.addClass(this._element, this._classes.fadeOut);\r\n }\r\n setTimeout(() => {\r\n this._element.setAttribute(HIDE_DATA_ATTRIBUTE, \"\");\r\n this._element.removeAttribute(SHOWING_DATA_ATTRIBUTE);\r\n this._element.removeAttribute(SHOW_DATA_ATTRIBUTE);\r\n EventHandler.trigger(this._element, EVENT_HIDDEN);\r\n }, timeout);\r\n };\r\n\r\n this._element.setAttribute(SHOWING_DATA_ATTRIBUTE, \"\");\r\n this._queueCallback(complete, this._element, this._config.animation);\r\n }\r\n\r\n dispose() {\r\n this._clearTimeout();\r\n\r\n if (this._element.dataset.teToastShow !== undefined) {\r\n this._element.removeAttribute(SHOW_DATA_ATTRIBUTE);\r\n }\r\n\r\n super.dispose();\r\n }\r\n\r\n // Private\r\n _init() {\r\n if (this._didInit) {\r\n return;\r\n }\r\n\r\n enableDismissTrigger(Toast);\r\n this._didInit = true;\r\n }\r\n\r\n _getConfig(config) {\r\n config = {\r\n ...Default,\r\n ...Manipulator.getDataAttributes(this._element),\r\n ...(typeof config === \"object\" && config ? config : {}),\r\n };\r\n\r\n typeCheckConfig(NAME, config, this.constructor.DefaultType);\r\n\r\n return config;\r\n }\r\n\r\n _getClasses(classes) {\r\n const dataAttributes = Manipulator.getDataClassAttributes(this._element);\r\n\r\n classes = {\r\n ...DefaultClasses,\r\n ...dataAttributes,\r\n ...classes,\r\n };\r\n\r\n typeCheckConfig(NAME, classes, DefaultClassesType);\r\n\r\n return classes;\r\n }\r\n\r\n _maybeScheduleHide() {\r\n if (!this._config.autohide) {\r\n return;\r\n }\r\n\r\n if (this._hasMouseInteraction || this._hasKeyboardInteraction) {\r\n return;\r\n }\r\n\r\n this._timeout = setTimeout(() => {\r\n this.hide();\r\n }, this._config.delay);\r\n }\r\n\r\n _onInteraction(event, isInteracting) {\r\n switch (event.type) {\r\n case \"mouseover\":\r\n case \"mouseout\":\r\n this._hasMouseInteraction = isInteracting;\r\n break;\r\n case \"focusin\":\r\n case \"focusout\":\r\n this._hasKeyboardInteraction = isInteracting;\r\n break;\r\n default:\r\n break;\r\n }\r\n\r\n if (isInteracting) {\r\n this._clearTimeout();\r\n return;\r\n }\r\n\r\n const nextElement = event.relatedTarget;\r\n if (this._element === nextElement || this._element.contains(nextElement)) {\r\n return;\r\n }\r\n\r\n this._maybeScheduleHide();\r\n }\r\n\r\n _setListeners() {\r\n EventHandler.on(this._element, EVENT_MOUSEOVER, (event) =>\r\n this._onInteraction(event, true)\r\n );\r\n EventHandler.on(this._element, EVENT_MOUSEOUT, (event) =>\r\n this._onInteraction(event, false)\r\n );\r\n EventHandler.on(this._element, EVENT_FOCUSIN, (event) =>\r\n this._onInteraction(event, true)\r\n );\r\n EventHandler.on(this._element, EVENT_FOCUSOUT, (event) =>\r\n this._onInteraction(event, false)\r\n );\r\n }\r\n\r\n _clearTimeout() {\r\n clearTimeout(this._timeout);\r\n this._timeout = null;\r\n }\r\n\r\n // Static\r\n\r\n static jQueryInterface(config) {\r\n return this.each(function () {\r\n const data = Toast.getOrCreateInstance(this, config);\r\n\r\n if (typeof config === \"string\") {\r\n if (typeof data[config] === \"undefined\") {\r\n throw new TypeError(`No method named \"${config}\"`);\r\n }\r\n\r\n data[config](this);\r\n }\r\n });\r\n }\r\n}\r\n\r\nexport default Toast;\r\n", "(()=>{var e={454:(e,t,n)=>{\"use strict\";n.d(t,{Z:()=>a});var r=n(645),o=n.n(r)()((function(e){return e[1]}));o.push([e.id,\"INPUT:-webkit-autofill,SELECT:-webkit-autofill,TEXTAREA:-webkit-autofill{animation-name:onautofillstart}INPUT:not(:-webkit-autofill),SELECT:not(:-webkit-autofill),TEXTAREA:not(:-webkit-autofill){animation-name:onautofillcancel}@keyframes onautofillstart{}@keyframes onautofillcancel{}\",\"\"]);const a=o},645:e=>{\"use strict\";e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var n=e(t);return t[2]?\"@media \".concat(t[2],\" {\").concat(n,\"}\"):n})).join(\"\")},t.i=function(e,n,r){\"string\"==typeof e&&(e=[[null,e,\"\"]]);var o={};if(r)for(var a=0;a{!function(){if(\"undefined\"!=typeof window)try{var e=new window.CustomEvent(\"test\",{cancelable:!0});if(e.preventDefault(),!0!==e.defaultPrevented)throw new Error(\"Could not prevent default\")}catch(e){var t=function(e,t){var n,r;return(t=t||{}).bubbles=!!t.bubbles,t.cancelable=!!t.cancelable,(n=document.createEvent(\"CustomEvent\")).initCustomEvent(e,t.bubbles,t.cancelable,t.detail),r=n.preventDefault,n.preventDefault=function(){r.call(this);try{Object.defineProperty(this,\"defaultPrevented\",{get:function(){return!0}})}catch(e){this.defaultPrevented=!0}},n};t.prototype=window.Event.prototype,window.CustomEvent=t}}()},379:(e,t,n)=>{\"use strict\";var r,o=function(){var e={};return function(t){if(void 0===e[t]){var n=document.querySelector(t);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(e){n=null}e[t]=n}return e[t]}}(),a=[];function i(e){for(var t=-1,n=0;n{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{\"use strict\";var e=n(379),t=n.n(e),r=n(454);function o(e){if(!e.hasAttribute(\"autocompleted\")){e.setAttribute(\"autocompleted\",\"\");var t=new window.CustomEvent(\"onautocomplete\",{bubbles:!0,cancelable:!0,detail:null});e.dispatchEvent(t)||(e.value=\"\")}}function a(e){e.hasAttribute(\"autocompleted\")&&(e.removeAttribute(\"autocompleted\"),e.dispatchEvent(new window.CustomEvent(\"onautocomplete\",{bubbles:!0,cancelable:!1,detail:null})))}t()(r.Z,{insert:\"head\",singleton:!1}),r.Z.locals,n(810),document.addEventListener(\"animationstart\",(function(e){\"onautofillstart\"===e.animationName?o(e.target):a(e.target)}),!0),document.addEventListener(\"input\",(function(e){\"insertReplacementText\"!==e.inputType&&\"data\"in e?a(e.target):o(e.target)}),!0)})()})();", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport { element, onDOMContentLoaded, typeCheckConfig } from \"../util/index\";\r\nimport Data from \"../dom/data\";\r\nimport EventHandler from \"../dom/event-handler\";\r\nimport Manipulator from \"../dom/manipulator\";\r\nimport SelectorEngine from \"../dom/selector-engine\";\r\nimport \"detect-autofill\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst NAME = \"input\";\r\nconst DATA_KEY = \"te.input\";\r\nconst DATA_WRAPPER = \"data-te-input-wrapper-init\";\r\nconst DATA_NOTCH = \"data-te-input-notch-ref\";\r\nconst DATA_NOTCH_LEADING = \"data-te-input-notch-leading-ref\";\r\nconst DATA_NOTCH_MIDDLE = \"data-te-input-notch-middle-ref\";\r\nconst DATA_NOTCH_TRAILING = \"data-te-input-notch-trailing-ref\";\r\nconst DATA_HELPER = \"data-te-input-helper-ref\";\r\nconst DATA_PLACEHOLDER_ACTIVE = \"data-te-input-placeholder-active\";\r\nconst DATA_ACTIVE = \"data-te-input-state-active\";\r\nconst DATA_FOCUSED = \"data-te-input-focused\";\r\nconst DATA_FORM_COUNTER = \"data-te-input-form-counter\";\r\n\r\nconst SELECTOR_OUTLINE_INPUT = `[${DATA_WRAPPER}] input`;\r\nconst SELECTOR_OUTLINE_TEXTAREA = `[${DATA_WRAPPER}] textarea`;\r\n\r\nconst SELECTOR_NOTCH = `[${DATA_NOTCH}]`;\r\nconst SELECTOR_NOTCH_LEADING = `[${DATA_NOTCH_LEADING}]`;\r\nconst SELECTOR_NOTCH_MIDDLE = `[${DATA_NOTCH_MIDDLE}]`;\r\nconst SELECTOR_HELPER = `[${DATA_HELPER}]`;\r\n\r\nconst Default = {\r\n inputFormWhite: false,\r\n};\r\n\r\nconst DefaultType = {\r\n inputFormWhite: \"(boolean)\",\r\n};\r\n\r\nexport const DefaultClasses = {\r\n notch:\r\n \"group flex absolute left-0 top-0 w-full max-w-full h-full text-left pointer-events-none\",\r\n notchLeading:\r\n \"pointer-events-none border border-solid box-border bg-transparent transition-all duration-200 ease-linear motion-reduce:transition-none left-0 top-0 h-full w-2 border-r-0 rounded-l-[0.25rem] group-data-[te-input-focused]:border-r-0 group-data-[te-input-state-active]:border-r-0\",\r\n notchLeadingNormal:\r\n \"border-neutral-300 dark:border-neutral-600 group-data-[te-input-focused]:shadow-[-1px_0_0_#3b71ca,_0_1px_0_0_#3b71ca,_0_-1px_0_0_#3b71ca] group-data-[te-input-focused]:border-primary\",\r\n notchLeadingWhite:\r\n \"border-neutral-200 group-data-[te-input-focused]:shadow-[-1px_0_0_#ffffff,_0_1px_0_0_#ffffff,_0_-1px_0_0_#ffffff] group-data-[te-input-focused]:border-white\",\r\n notchMiddle:\r\n \"pointer-events-none border border-solid box-border bg-transparent transition-all duration-200 ease-linear motion-reduce:transition-none grow-0 shrink-0 basis-auto w-auto max-w-[calc(100%-1rem)] h-full border-r-0 border-l-0 group-data-[te-input-focused]:border-x-0 group-data-[te-input-state-active]:border-x-0 group-data-[te-input-focused]:border-t group-data-[te-input-state-active]:border-t group-data-[te-input-focused]:border-solid group-data-[te-input-state-active]:border-solid group-data-[te-input-focused]:border-t-transparent group-data-[te-input-state-active]:border-t-transparent\",\r\n notchMiddleNormal:\r\n \"border-neutral-300 dark:border-neutral-600 group-data-[te-input-focused]:shadow-[0_1px_0_0_#3b71ca] group-data-[te-input-focused]:border-primary\",\r\n notchMiddleWhite:\r\n \"border-neutral-200 group-data-[te-input-focused]:shadow-[0_1px_0_0_#ffffff] group-data-[te-input-focused]:border-white\",\r\n notchTrailing:\r\n \"pointer-events-none border border-solid box-border bg-transparent transition-all duration-200 ease-linear motion-reduce:transition-none grow h-full border-l-0 rounded-r-[0.25rem] group-data-[te-input-focused]:border-l-0 group-data-[te-input-state-active]:border-l-0\",\r\n notchTrailingNormal:\r\n \"border-neutral-300 dark:border-neutral-600 group-data-[te-input-focused]:shadow-[1px_0_0_#3b71ca,_0_-1px_0_0_#3b71ca,_0_1px_0_0_#3b71ca] group-data-[te-input-focused]:border-primary\",\r\n notchTrailingWhite:\r\n \"border-neutral-200 group-data-[te-input-focused]:shadow-[1px_0_0_#ffffff,_0_-1px_0_0_#ffffff,_0_1px_0_0_#ffffff] group-data-[te-input-focused]:border-white\",\r\n counter: \"text-right leading-[1.6]\",\r\n};\r\n\r\nconst DefaultClassesType = {\r\n notch: \"string\",\r\n notchLeading: \"string\",\r\n notchLeadingNormal: \"string\",\r\n notchLeadingWhite: \"string\",\r\n notchMiddle: \"string\",\r\n notchMiddleNormal: \"string\",\r\n notchMiddleWhite: \"string\",\r\n notchTrailing: \"string\",\r\n notchTrailingNormal: \"string\",\r\n notchTrailingWhite: \"string\",\r\n counter: \"string\",\r\n};\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nClass Definition\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nclass Input {\r\n constructor(element, config, classes) {\r\n this._config = this._getConfig(config, element);\r\n this._element = element;\r\n this._classes = this._getClasses(classes);\r\n this._label = null;\r\n this._labelWidth = 0;\r\n this._labelMarginLeft = 0;\r\n this._notchLeading = null;\r\n this._notchMiddle = null;\r\n this._notchTrailing = null;\r\n this._initiated = false;\r\n this._helper = null;\r\n this._counter = false;\r\n this._counterElement = null;\r\n this._maxLength = 0;\r\n this._leadingIcon = null;\r\n if (this._element) {\r\n Data.setData(element, DATA_KEY, this);\r\n this.init();\r\n }\r\n }\r\n\r\n // Getters\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n get input() {\r\n const inputElement =\r\n SelectorEngine.findOne(\"input\", this._element) ||\r\n SelectorEngine.findOne(\"textarea\", this._element);\r\n return inputElement;\r\n }\r\n\r\n // Public\r\n init() {\r\n if (this._initiated) {\r\n return;\r\n }\r\n this._getLabelData();\r\n this._applyDivs();\r\n this._applyNotch();\r\n this._activate();\r\n this._getHelper();\r\n this._getCounter();\r\n this._getEvents();\r\n this._initiated = true;\r\n }\r\n\r\n update() {\r\n this._getLabelData();\r\n this._getNotchData();\r\n this._applyNotch();\r\n this._activate();\r\n this._getHelper();\r\n this._getCounter();\r\n }\r\n\r\n forceActive() {\r\n this.input.setAttribute(DATA_ACTIVE, \"\");\r\n\r\n SelectorEngine.findOne(SELECTOR_NOTCH, this.input.parentNode).setAttribute(\r\n DATA_ACTIVE,\r\n \"\"\r\n );\r\n }\r\n\r\n forceInactive() {\r\n this.input.removeAttribute(DATA_ACTIVE);\r\n\r\n SelectorEngine.findOne(\r\n SELECTOR_NOTCH,\r\n this.input.parentNode\r\n ).removeAttribute(DATA_ACTIVE);\r\n }\r\n\r\n dispose() {\r\n this._removeBorder();\r\n\r\n Data.removeData(this._element, DATA_KEY);\r\n this._element = null;\r\n }\r\n\r\n // Private\r\n\r\n _getConfig(config, element) {\r\n config = {\r\n ...Default,\r\n ...Manipulator.getDataAttributes(element),\r\n ...(typeof config === \"object\" ? config : {}),\r\n };\r\n typeCheckConfig(NAME, config, DefaultType);\r\n return config;\r\n }\r\n\r\n _getClasses(classes) {\r\n const dataAttributes = Manipulator.getDataClassAttributes(this._element);\r\n\r\n classes = {\r\n ...DefaultClasses,\r\n ...dataAttributes,\r\n ...classes,\r\n };\r\n\r\n typeCheckConfig(NAME, classes, DefaultClassesType);\r\n\r\n return classes;\r\n }\r\n\r\n _getLabelData() {\r\n this._label = SelectorEngine.findOne(\"label\", this._element);\r\n\r\n if (this._label === null) {\r\n this._showPlaceholder();\r\n } else {\r\n this._getLabelWidth();\r\n this._getLabelPositionInInputGroup();\r\n this._toggleDefaultDatePlaceholder();\r\n }\r\n }\r\n\r\n _getHelper() {\r\n this._helper = SelectorEngine.findOne(SELECTOR_HELPER, this._element);\r\n }\r\n\r\n _getCounter() {\r\n this._counter = Manipulator.getDataAttribute(\r\n this.input,\r\n \"inputShowcounter\"\r\n );\r\n if (this._counter) {\r\n this._maxLength = this.input.maxLength;\r\n this._showCounter();\r\n }\r\n }\r\n\r\n _getEvents() {\r\n EventHandler.on(\r\n document,\r\n \"focus\",\r\n SELECTOR_OUTLINE_INPUT,\r\n Input.activate(new Input())\r\n );\r\n EventHandler.on(\r\n document,\r\n \"input\",\r\n SELECTOR_OUTLINE_INPUT,\r\n Input.activate(new Input())\r\n );\r\n EventHandler.on(\r\n document,\r\n \"blur\",\r\n SELECTOR_OUTLINE_INPUT,\r\n Input.deactivate(new Input())\r\n );\r\n\r\n EventHandler.on(\r\n document,\r\n \"focus\",\r\n SELECTOR_OUTLINE_TEXTAREA,\r\n Input.activate(new Input())\r\n );\r\n EventHandler.on(\r\n document,\r\n \"input\",\r\n SELECTOR_OUTLINE_TEXTAREA,\r\n Input.activate(new Input())\r\n );\r\n EventHandler.on(\r\n document,\r\n \"blur\",\r\n SELECTOR_OUTLINE_TEXTAREA,\r\n Input.deactivate(new Input())\r\n );\r\n\r\n EventHandler.on(window, \"shown.te.modal\", (e) => {\r\n SelectorEngine.find(SELECTOR_OUTLINE_INPUT, e.target).forEach(\r\n (element) => {\r\n const instance = Input.getInstance(element.parentNode);\r\n if (!instance) {\r\n return;\r\n }\r\n instance.update();\r\n }\r\n );\r\n SelectorEngine.find(SELECTOR_OUTLINE_TEXTAREA, e.target).forEach(\r\n (element) => {\r\n const instance = Input.getInstance(element.parentNode);\r\n if (!instance) {\r\n return;\r\n }\r\n instance.update();\r\n }\r\n );\r\n });\r\n\r\n EventHandler.on(window, \"shown.te.dropdown\", (e) => {\r\n const target = e.target.parentNode.querySelector(\r\n \"[data-te-dropdown-menu-ref]\"\r\n );\r\n if (target) {\r\n SelectorEngine.find(SELECTOR_OUTLINE_INPUT, target).forEach(\r\n (element) => {\r\n const instance = Input.getInstance(element.parentNode);\r\n if (!instance) {\r\n return;\r\n }\r\n instance.update();\r\n }\r\n );\r\n SelectorEngine.find(SELECTOR_OUTLINE_TEXTAREA, target).forEach(\r\n (element) => {\r\n const instance = Input.getInstance(element.parentNode);\r\n if (!instance) {\r\n return;\r\n }\r\n instance.update();\r\n }\r\n );\r\n }\r\n });\r\n\r\n EventHandler.on(window, \"shown.te.tab\", (e) => {\r\n let targetId;\r\n\r\n if (e.target.href) {\r\n targetId = e.target.href.split(\"#\")[1];\r\n } else {\r\n targetId = Manipulator.getDataAttribute(e.target, \"target\").split(\r\n \"#\"\r\n )[1];\r\n }\r\n\r\n const target = SelectorEngine.findOne(`#${targetId}`);\r\n SelectorEngine.find(SELECTOR_OUTLINE_INPUT, target).forEach((element) => {\r\n const instance = Input.getInstance(element.parentNode);\r\n if (!instance) {\r\n return;\r\n }\r\n instance.update();\r\n });\r\n SelectorEngine.find(SELECTOR_OUTLINE_TEXTAREA, target).forEach(\r\n (element) => {\r\n const instance = Input.getInstance(element.parentNode);\r\n if (!instance) {\r\n return;\r\n }\r\n instance.update();\r\n }\r\n );\r\n });\r\n\r\n // form reset handler\r\n EventHandler.on(window, \"reset\", (e) => {\r\n SelectorEngine.find(SELECTOR_OUTLINE_INPUT, e.target).forEach(\r\n (element) => {\r\n const instance = Input.getInstance(element.parentNode);\r\n if (!instance) {\r\n return;\r\n }\r\n instance.forceInactive();\r\n }\r\n );\r\n SelectorEngine.find(SELECTOR_OUTLINE_TEXTAREA, e.target).forEach(\r\n (element) => {\r\n const instance = Input.getInstance(element.parentNode);\r\n if (!instance) {\r\n return;\r\n }\r\n instance.forceInactive();\r\n }\r\n );\r\n });\r\n\r\n // auto-fill\r\n EventHandler.on(window, \"onautocomplete\", (e) => {\r\n const instance = Input.getInstance(e.target.parentNode);\r\n if (!instance || !e.cancelable) {\r\n return;\r\n }\r\n instance.forceActive();\r\n });\r\n }\r\n\r\n _showCounter() {\r\n const counters = SelectorEngine.find(\r\n `[${DATA_FORM_COUNTER}]`,\r\n this._element\r\n );\r\n if (counters.length > 0) {\r\n return;\r\n }\r\n this._counterElement = document.createElement(\"div\");\r\n Manipulator.addClass(this._counterElement, this._classes.counter);\r\n this._counterElement.setAttribute(DATA_FORM_COUNTER, \"\");\r\n const actualLength = this.input.value.length;\r\n this._counterElement.innerHTML = `${actualLength} / ${this._maxLength}`;\r\n this._helper.appendChild(this._counterElement);\r\n this._bindCounter();\r\n }\r\n\r\n _bindCounter() {\r\n EventHandler.on(this.input, \"input\", () => {\r\n const actualLength = this.input.value.length;\r\n this._counterElement.innerHTML = `${actualLength} / ${this._maxLength}`;\r\n });\r\n }\r\n\r\n _toggleDefaultDatePlaceholder(input = this.input) {\r\n const isTypeDate = input.getAttribute(\"type\") === \"date\";\r\n if (!isTypeDate) {\r\n return;\r\n }\r\n const isInputFocused = document.activeElement === input;\r\n\r\n if (!isInputFocused && !input.value) {\r\n input.style.opacity = 0;\r\n } else {\r\n input.style.opacity = 1;\r\n }\r\n }\r\n\r\n _showPlaceholder() {\r\n this.input.setAttribute(DATA_PLACEHOLDER_ACTIVE, \"\");\r\n }\r\n\r\n _getNotchData() {\r\n this._notchMiddle = SelectorEngine.findOne(\r\n SELECTOR_NOTCH_MIDDLE,\r\n this._element\r\n );\r\n this._notchLeading = SelectorEngine.findOne(\r\n SELECTOR_NOTCH_LEADING,\r\n this._element\r\n );\r\n }\r\n\r\n _getLabelWidth() {\r\n this._labelWidth = this._label.clientWidth * 0.8 + 8;\r\n }\r\n\r\n _getLabelPositionInInputGroup() {\r\n this._labelMarginLeft = 0;\r\n if (!this._element.hasAttribute(\"data-te-input-group-ref\")) return;\r\n const input = this.input;\r\n const prefix = SelectorEngine.prev(\r\n input,\r\n \"[data-te-input-group-text-ref]\"\r\n )[0];\r\n if (prefix === undefined) {\r\n this._labelMarginLeft = 0;\r\n } else {\r\n this._labelMarginLeft = prefix.offsetWidth - 1;\r\n }\r\n }\r\n\r\n _applyDivs() {\r\n const shadowLeading = this._config.inputFormWhite\r\n ? this._classes.notchLeadingWhite\r\n : this._classes.notchLeadingNormal;\r\n const shadowMiddle = this._config.inputFormWhite\r\n ? this._classes.notchMiddleWhite\r\n : this._classes.notchMiddleNormal;\r\n const shadowTrailing = this._config.inputFormWhite\r\n ? this._classes.notchTrailingWhite\r\n : this._classes.notchTrailingNormal;\r\n\r\n const allNotchWrappers = SelectorEngine.find(SELECTOR_NOTCH, this._element);\r\n const notchWrapper = element(\"div\");\r\n Manipulator.addClass(notchWrapper, this._classes.notch);\r\n notchWrapper.setAttribute(DATA_NOTCH, \"\");\r\n this._notchLeading = element(\"div\");\r\n\r\n Manipulator.addClass(\r\n this._notchLeading,\r\n `${this._classes.notchLeading} ${shadowLeading}`\r\n );\r\n this._notchLeading.setAttribute(DATA_NOTCH_LEADING, \"\");\r\n this._notchMiddle = element(\"div\");\r\n\r\n Manipulator.addClass(\r\n this._notchMiddle,\r\n `${this._classes.notchMiddle} ${shadowMiddle}`\r\n );\r\n this._notchMiddle.setAttribute(DATA_NOTCH_MIDDLE, \"\");\r\n this._notchTrailing = element(\"div\");\r\n\r\n Manipulator.addClass(\r\n this._notchTrailing,\r\n `${this._classes.notchTrailing} ${shadowTrailing}`\r\n );\r\n this._notchTrailing.setAttribute(DATA_NOTCH_TRAILING, \"\");\r\n if (allNotchWrappers.length >= 1) {\r\n return;\r\n }\r\n notchWrapper.append(this._notchLeading);\r\n notchWrapper.append(this._notchMiddle);\r\n notchWrapper.append(this._notchTrailing);\r\n this._element.append(notchWrapper);\r\n }\r\n\r\n _applyNotch() {\r\n this._notchMiddle.style.width = `${this._labelWidth}px`;\r\n this._notchLeading.style.width = `${this._labelMarginLeft + 9}px`;\r\n\r\n if (this._label === null) return;\r\n this._label.style.marginLeft = `${this._labelMarginLeft}px`;\r\n }\r\n\r\n _removeBorder() {\r\n const border = SelectorEngine.findOne(SELECTOR_NOTCH, this._element);\r\n if (border) border.remove();\r\n }\r\n\r\n _activate(event) {\r\n onDOMContentLoaded(() => {\r\n this._getElements(event);\r\n const input = event ? event.target : this.input;\r\n const notchWrapper = SelectorEngine.findOne(\r\n SELECTOR_NOTCH,\r\n this._element\r\n );\r\n\r\n if (event && event.type === \"focus\") {\r\n notchWrapper && notchWrapper.setAttribute(DATA_FOCUSED, \"\");\r\n }\r\n\r\n if (input.value !== \"\") {\r\n input.setAttribute(DATA_ACTIVE, \"\");\r\n notchWrapper && notchWrapper.setAttribute(DATA_ACTIVE, \"\");\r\n }\r\n this._toggleDefaultDatePlaceholder(input);\r\n });\r\n }\r\n\r\n _getElements(event) {\r\n if (event) {\r\n this._element = event.target.parentNode;\r\n this._label = SelectorEngine.findOne(\"label\", this._element);\r\n }\r\n\r\n if (event && this._label) {\r\n const prevLabelWidth = this._labelWidth;\r\n this._getLabelData();\r\n\r\n if (prevLabelWidth !== this._labelWidth) {\r\n this._notchMiddle = SelectorEngine.findOne(\r\n SELECTOR_NOTCH_MIDDLE,\r\n event.target.parentNode\r\n );\r\n this._notchLeading = SelectorEngine.findOne(\r\n SELECTOR_NOTCH_LEADING,\r\n event.target.parentNode\r\n );\r\n this._applyNotch();\r\n }\r\n }\r\n }\r\n\r\n _deactivate(event) {\r\n const input = event ? event.target : this.input;\r\n const notchWrapper = SelectorEngine.findOne(\r\n SELECTOR_NOTCH,\r\n input.parentNode\r\n );\r\n notchWrapper.removeAttribute(DATA_FOCUSED);\r\n\r\n if (input.value === \"\") {\r\n input.removeAttribute(DATA_ACTIVE);\r\n notchWrapper.removeAttribute(DATA_ACTIVE);\r\n }\r\n this._toggleDefaultDatePlaceholder(input);\r\n }\r\n\r\n static activate(instance) {\r\n return function (event) {\r\n instance._activate(event);\r\n };\r\n }\r\n\r\n static deactivate(instance) {\r\n return function (event) {\r\n instance._deactivate(event);\r\n };\r\n }\r\n\r\n static jQueryInterface(config, options) {\r\n return this.each(function () {\r\n let data = Data.getData(this, DATA_KEY);\r\n const _config = typeof config === \"object\" && config;\r\n if (!data && /dispose/.test(config)) {\r\n return;\r\n }\r\n if (!data) {\r\n data = new Input(this, _config);\r\n }\r\n if (typeof config === \"string\") {\r\n if (typeof data[config] === \"undefined\") {\r\n throw new TypeError(`No method named \"${config}\"`);\r\n }\r\n data[config](options);\r\n }\r\n });\r\n }\r\n\r\n static getInstance(element) {\r\n return Data.getData(element, DATA_KEY);\r\n }\r\n\r\n static getOrCreateInstance(element, config = {}) {\r\n return (\r\n this.getInstance(element) ||\r\n new this(element, typeof config === \"object\" ? config : null)\r\n );\r\n }\r\n}\r\n\r\nexport default Input;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport { typeCheckConfig } from \"../util/index\";\r\nimport Data from \"../dom/data\";\r\nimport Manipulator from \"../dom/manipulator\";\r\nimport SelectorEngine from \"../dom/selector-engine\";\r\nimport EventHandler from \"../dom/event-handler\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst NAME = \"animation\";\r\nconst DATA_KEY = \"te.animation\";\r\n\r\nconst DefaultType = {\r\n animation: \"string\",\r\n animationStart: \"string\",\r\n animationShowOnLoad: \"boolean\",\r\n onStart: \"(null|function)\",\r\n onEnd: \"(null|function)\",\r\n onHide: \"(null|function)\",\r\n onShow: \"(null|function)\",\r\n animationOnScroll: \"(string)\",\r\n animationWindowHeight: \"number\",\r\n animationOffset: \"(number|string)\",\r\n animationDelay: \"(number|string)\",\r\n animationReverse: \"boolean\",\r\n animationInterval: \"(number|string)\",\r\n animationRepeat: \"(number|boolean)\",\r\n animationReset: \"boolean\",\r\n};\r\n\r\nconst Default = {\r\n animation: \"fade\",\r\n animationStart: \"onClick\",\r\n animationShowOnLoad: true,\r\n onStart: null,\r\n onEnd: null,\r\n onHide: null,\r\n onShow: null,\r\n animationOnScroll: \"once\",\r\n animationWindowHeight: 0,\r\n animationOffset: 0,\r\n animationDelay: 0,\r\n animationReverse: false,\r\n animationInterval: 0,\r\n animationRepeat: false,\r\n animationReset: false,\r\n};\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nClass Definition\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nclass Animate {\r\n constructor(element, options) {\r\n this._element = element;\r\n this._animateElement = this._getAnimateElement();\r\n this._isFirstScroll = true;\r\n this._repeatAnimateOnScroll = true;\r\n this._options = this._getConfig(options);\r\n\r\n if (this._element) {\r\n Data.setData(element, DATA_KEY, this);\r\n this._init();\r\n }\r\n }\r\n\r\n // Getters\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n // Public\r\n init() {\r\n this._init();\r\n }\r\n\r\n startAnimation() {\r\n this._startAnimation();\r\n }\r\n\r\n stopAnimation() {\r\n this._clearAnimationClass();\r\n }\r\n\r\n changeAnimationType(animation) {\r\n this._options.animation = animation;\r\n }\r\n\r\n dispose() {\r\n EventHandler.off(this._element, \"mousedown\");\r\n EventHandler.off(this._animateElement, \"animationend\");\r\n EventHandler.off(window, \"scroll\");\r\n EventHandler.off(this._element, \"mouseover\");\r\n\r\n Data.removeData(this._element, DATA_KEY);\r\n this._element = null;\r\n this._animateElement = null;\r\n this._isFirstScroll = null;\r\n this._repeatAnimateOnScroll = null;\r\n this._options = null;\r\n }\r\n\r\n // Private\r\n _init() {\r\n switch (this._options.animationStart) {\r\n case \"onHover\":\r\n this._bindHoverEvents();\r\n break;\r\n case \"onLoad\":\r\n this._startAnimation();\r\n break;\r\n case \"onScroll\":\r\n this._bindScrollEvents();\r\n break;\r\n case \"onClick\":\r\n this._bindClickEvents();\r\n break;\r\n default:\r\n break;\r\n }\r\n\r\n this._bindTriggerOnEndCallback();\r\n if (this._options.animationReset) {\r\n this._bindResetAnimationAfterFinish();\r\n }\r\n }\r\n\r\n _getAnimateElement() {\r\n const targetId = Manipulator.getDataAttribute(\r\n this._element,\r\n \"animation-target\"\r\n );\r\n return targetId ? SelectorEngine.find(targetId)[0] : this._element;\r\n }\r\n\r\n _getConfig(config) {\r\n const dataAttributes = Manipulator.getDataAttributes(this._animateElement);\r\n\r\n config = {\r\n ...Default,\r\n ...dataAttributes,\r\n ...config,\r\n };\r\n\r\n typeCheckConfig(NAME, config, DefaultType);\r\n\r\n return config;\r\n }\r\n\r\n _animateOnScroll() {\r\n const elementOffsetTop = Manipulator.offset(this._animateElement).top;\r\n const elementHeight = this._animateElement.offsetHeight;\r\n const windowHeight = window.innerHeight;\r\n const shouldBeVisible =\r\n elementOffsetTop + this._options.animationOffset <= windowHeight &&\r\n elementOffsetTop + this._options.animationOffset + elementHeight >= 0;\r\n const isElementVisible =\r\n this._animateElement.style.visibility === \"visible\";\r\n\r\n switch (true) {\r\n case shouldBeVisible && this._isFirstScroll:\r\n this._isFirstScroll = false;\r\n this._startAnimation();\r\n break;\r\n case !shouldBeVisible && this._isFirstScroll:\r\n this._isFirstScroll = false;\r\n this._hideAnimateElement();\r\n break;\r\n case shouldBeVisible && !isElementVisible && this._repeatAnimateOnScroll:\r\n if (this._options.animationOnScroll !== \"repeat\") {\r\n this._repeatAnimateOnScroll = false;\r\n }\r\n this._callback(this._options.onShow);\r\n this._showAnimateElement();\r\n this._startAnimation();\r\n break;\r\n case !shouldBeVisible && isElementVisible && this._repeatAnimateOnScroll:\r\n this._hideAnimateElement();\r\n this._clearAnimationClass();\r\n this._callback(this._options.onHide);\r\n break;\r\n default:\r\n break;\r\n }\r\n }\r\n\r\n _addAnimatedClass() {\r\n Manipulator.addClass(\r\n this._animateElement,\r\n `animate-${this._options.animation}`\r\n );\r\n }\r\n\r\n _clearAnimationClass() {\r\n this._animateElement.classList.remove(`animate-${this._options.animation}`);\r\n }\r\n\r\n _startAnimation() {\r\n this._callback(this._options.onStart);\r\n\r\n this._addAnimatedClass();\r\n\r\n if (this._options.animationRepeat && !this._options.animationInterval) {\r\n this._setAnimationRepeat();\r\n }\r\n\r\n if (this._options.animationReverse) {\r\n this._setAnimationReverse();\r\n }\r\n\r\n if (this._options.animationDelay) {\r\n this._setAnimationDelay();\r\n }\r\n\r\n if (this._options.animationDuration) {\r\n this._setAnimationDuration();\r\n }\r\n\r\n if (this._options.animationInterval) {\r\n this._setAnimationInterval();\r\n }\r\n }\r\n\r\n _setAnimationReverse() {\r\n Manipulator.style(this._animateElement, {\r\n animationIterationCount:\r\n this._options.animationRepeat === true ? \"infinite\" : \"2\",\r\n animationDirection: \"alternate\",\r\n });\r\n }\r\n\r\n _setAnimationDuration() {\r\n Manipulator.style(this._animateElement, {\r\n animationDuration: `${this._options.animationDuration}ms`,\r\n });\r\n }\r\n\r\n _setAnimationDelay() {\r\n Manipulator.style(this._animateElement, {\r\n animationDelay: `${this._options.animationDelay}ms`,\r\n });\r\n }\r\n\r\n _setAnimationRepeat() {\r\n Manipulator.style(this._animateElement, {\r\n animationIterationCount:\r\n this._options.animationRepeat === true\r\n ? \"infinite\"\r\n : this._options.animationRepeat,\r\n });\r\n }\r\n\r\n _setAnimationInterval() {\r\n EventHandler.on(this._animateElement, \"click\", () => {\r\n this._clearAnimationClass();\r\n setTimeout(() => {\r\n this._addAnimatedClass();\r\n }, this._options.animationInterval);\r\n });\r\n }\r\n\r\n _hideAnimateElement() {\r\n Manipulator.style(this._animateElement, { visibility: \"hidden\" });\r\n }\r\n\r\n _showAnimateElement() {\r\n Manipulator.style(this._animateElement, { visibility: \"visible\" });\r\n }\r\n\r\n _bindResetAnimationAfterFinish() {\r\n EventHandler.on(this._animateElement, \"animationend\", () => {\r\n this._clearAnimationClass();\r\n });\r\n }\r\n\r\n _bindTriggerOnEndCallback() {\r\n EventHandler.on(this._animateElement, \"animationend\", () => {\r\n this._callback(this._options.onEnd);\r\n });\r\n }\r\n\r\n _bindScrollEvents() {\r\n if (!this._options.animationShowOnLoad) {\r\n this._animateOnScroll();\r\n }\r\n\r\n EventHandler.on(window, \"scroll\", () => {\r\n this._animateOnScroll();\r\n });\r\n }\r\n\r\n _bindClickEvents() {\r\n EventHandler.on(this._element, \"mousedown\", () => {\r\n this._startAnimation();\r\n });\r\n }\r\n\r\n _bindHoverEvents() {\r\n EventHandler.one(this._element, \"mouseover\", () => {\r\n this._startAnimation();\r\n });\r\n EventHandler.one(this._animateElement, \"animationend\", () => {\r\n // wait after bind hoverEvents to prevent animation looping\r\n setTimeout(() => {\r\n this._bindHoverEvents();\r\n }, 100);\r\n });\r\n }\r\n\r\n _callback(fn) {\r\n if (fn instanceof Function) {\r\n fn();\r\n }\r\n }\r\n\r\n // Static\r\n static autoInit(instance) {\r\n instance._init();\r\n }\r\n\r\n static jQueryInterface(options) {\r\n const animate = new Animate(this[0], options);\r\n animate.init();\r\n }\r\n\r\n static getInstance(element) {\r\n return Data.getData(element, DATA_KEY);\r\n }\r\n\r\n static getOrCreateInstance(element, config = {}) {\r\n return (\r\n this.getInstance(element) ||\r\n new this(element, typeof config === \"object\" ? config : null)\r\n );\r\n }\r\n}\r\n\r\nexport default Animate;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport { element, typeCheckConfig } from \"../util/index\";\r\nimport Data from \"../dom/data\";\r\nimport EventHandler from \"../dom/event-handler\";\r\nimport Manipulator from \"../dom/manipulator\";\r\nimport SelectorEngine from \"../dom/selector-engine\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst NAME = \"ripple\";\r\nconst DATA_KEY = \"te.ripple\";\r\n\r\nconst GRADIENT =\r\n \"rgba({{color}}, 0.2) 0, rgba({{color}}, 0.3) 40%, rgba({{color}}, 0.4) 50%, rgba({{color}}, 0.5) 60%, rgba({{color}}, 0) 70%\";\r\n\r\nconst SELECTOR_COMPONENT = [\"[data-te-ripple-init]\"];\r\nconst DEFAULT_RIPPLE_COLOR = [0, 0, 0];\r\n\r\nconst BOOTSTRAP_COLORS = [\r\n { name: \"primary\", gradientColor: \"#3B71CA\" },\r\n { name: \"secondary\", gradientColor: \"#9FA6B2\" },\r\n { name: \"success\", gradientColor: \"#14A44D\" },\r\n { name: \"danger\", gradientColor: \"#DC4C64\" },\r\n { name: \"warning\", gradientColor: \"#E4A11B\" },\r\n { name: \"info\", gradientColor: \"#54B4D3\" },\r\n { name: \"light\", gradientColor: \"#fbfbfb\" },\r\n { name: \"dark\", gradientColor: \"#262626\" },\r\n];\r\n\r\n// Sets value when run opacity transition\r\n// Hide element after 50% (0.5) time of animation and finish on 100%\r\nconst TRANSITION_BREAK_OPACITY = 0.5;\r\n\r\nconst Default = {\r\n rippleCentered: false,\r\n rippleColor: \"\",\r\n rippleColorDark: \"\",\r\n rippleDuration: \"500ms\",\r\n rippleRadius: 0,\r\n rippleUnbound: false,\r\n};\r\n\r\nconst DefaultType = {\r\n rippleCentered: \"boolean\",\r\n rippleColor: \"string\",\r\n rippleColorDark: \"string\",\r\n rippleDuration: \"string\",\r\n rippleRadius: \"number\",\r\n rippleUnbound: \"boolean\",\r\n};\r\n\r\nconst DefaultClasses = {\r\n ripple: \"relative overflow-hidden inline-block align-bottom\",\r\n rippleWave:\r\n \"rounded-[50%] opacity-50 pointer-events-none absolute touch-none scale-0 transition-[transform,_opacity] ease-[cubic-bezier(0,0,0.15,1),_cubic-bezier(0,0,0.15,1)] z-[999]\",\r\n unbound: \"overflow-visible\",\r\n};\r\n\r\nconst DefaultClassesType = {\r\n ripple: \"string\",\r\n rippleWave: \"string\",\r\n unbound: \"string\",\r\n};\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nClass Definition\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nclass Ripple {\r\n constructor(element, options, classes) {\r\n this._element = element;\r\n this._options = this._getConfig(options);\r\n this._classes = this._getClasses(classes);\r\n\r\n if (this._element) {\r\n Data.setData(element, DATA_KEY, this);\r\n Manipulator.addClass(this._element, this._classes.ripple);\r\n }\r\n this._clickHandler = this._createRipple.bind(this);\r\n this._rippleTimer = null;\r\n this._isMinWidthSet = false;\r\n this._initialClasses = null;\r\n\r\n this.init();\r\n }\r\n\r\n // Getters\r\n\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n // Public\r\n\r\n init() {\r\n this._addClickEvent(this._element);\r\n }\r\n\r\n dispose() {\r\n Data.removeData(this._element, DATA_KEY);\r\n EventHandler.off(this._element, \"click\", this._clickHandler);\r\n this._element = null;\r\n this._options = null;\r\n }\r\n\r\n // Private\r\n\r\n _autoInit(event) {\r\n SELECTOR_COMPONENT.forEach((selector) => {\r\n const target = SelectorEngine.closest(event.target, selector);\r\n if (target) {\r\n this._element = SelectorEngine.closest(event.target, selector);\r\n }\r\n });\r\n\r\n if (!this._element.style.minWidth) {\r\n Manipulator.style(this._element, {\r\n \"min-width\": getComputedStyle(this._element).width,\r\n });\r\n this._isMinWidthSet = true;\r\n }\r\n\r\n this._options = this._getConfig();\r\n this._classes = this._getClasses();\r\n\r\n this._initialClasses = [...this._element.classList];\r\n Manipulator.addClass(this._element, this._classes.ripple);\r\n this._createRipple(event);\r\n }\r\n\r\n _addClickEvent(target) {\r\n EventHandler.on(target, \"mousedown\", this._clickHandler);\r\n }\r\n\r\n _createRipple(event) {\r\n if (this._element.className.indexOf(this._classes.ripple) < 0) {\r\n Manipulator.addClass(this._element, this._classes.ripple);\r\n }\r\n\r\n const { layerX, layerY } = event;\r\n const offsetX = event.offsetX || layerX;\r\n const offsetY = event.offsetY || layerY;\r\n const height = this._element.offsetHeight;\r\n const width = this._element.offsetWidth;\r\n const duration = this._durationToMsNumber(this._options.rippleDuration);\r\n const diameterOptions = {\r\n offsetX: this._options.rippleCentered ? height / 2 : offsetX,\r\n offsetY: this._options.rippleCentered ? width / 2 : offsetY,\r\n height,\r\n width,\r\n };\r\n const diameter = this._getDiameter(diameterOptions);\r\n const radiusValue = this._options.rippleRadius || diameter / 2;\r\n\r\n const opacity = {\r\n delay: duration * TRANSITION_BREAK_OPACITY,\r\n duration: duration - duration * TRANSITION_BREAK_OPACITY,\r\n };\r\n\r\n const styles = {\r\n left: this._options.rippleCentered\r\n ? `${width / 2 - radiusValue}px`\r\n : `${offsetX - radiusValue}px`,\r\n top: this._options.rippleCentered\r\n ? `${height / 2 - radiusValue}px`\r\n : `${offsetY - radiusValue}px`,\r\n height: `${this._options.rippleRadius * 2 || diameter}px`,\r\n width: `${this._options.rippleRadius * 2 || diameter}px`,\r\n transitionDelay: `0s, ${opacity.delay}ms`,\r\n transitionDuration: `${duration}ms, ${opacity.duration}ms`,\r\n };\r\n\r\n const rippleHTML = element(\"div\");\r\n\r\n this._createHTMLRipple({\r\n wrapper: this._element,\r\n ripple: rippleHTML,\r\n styles,\r\n });\r\n this._removeHTMLRipple({ ripple: rippleHTML, duration });\r\n }\r\n\r\n _createHTMLRipple({ wrapper, ripple, styles }) {\r\n Object.keys(styles).forEach(\r\n (property) => (ripple.style[property] = styles[property])\r\n );\r\n Manipulator.addClass(ripple, this._classes.rippleWave);\r\n ripple.setAttribute(\"data-te-ripple-ref\", \"\");\r\n this._addColor(ripple, wrapper);\r\n\r\n this._toggleUnbound(wrapper);\r\n this._appendRipple(ripple, wrapper);\r\n }\r\n\r\n _removeHTMLRipple({ ripple, duration }) {\r\n if (this._rippleTimer) {\r\n clearTimeout(this._rippleTimer);\r\n this._rippleTimer = null;\r\n }\r\n if (ripple) {\r\n setTimeout(() => {\r\n ripple.classList.add(\"!opacity-0\");\r\n }, 10);\r\n }\r\n this._rippleTimer = setTimeout(() => {\r\n if (ripple) {\r\n ripple.remove();\r\n if (this._element) {\r\n SelectorEngine.find(\"[data-te-ripple-ref]\", this._element).forEach(\r\n (rippleEl) => {\r\n rippleEl.remove();\r\n }\r\n );\r\n if (this._isMinWidthSet) {\r\n Manipulator.style(this._element, { \"min-width\": \"\" });\r\n this._isMinWidthSet = false;\r\n }\r\n // check if added ripple classes wasn't there initialy\r\n const classesToRemove = this._initialClasses\r\n ? this._addedNewRippleClasses(\r\n this._classes.ripple,\r\n this._initialClasses\r\n )\r\n : this._classes.ripple.split(\" \");\r\n Manipulator.removeClass(this._element, classesToRemove);\r\n }\r\n }\r\n }, duration);\r\n }\r\n\r\n _addedNewRippleClasses(defaultRipple, initialClasses) {\r\n return defaultRipple\r\n .split(\" \")\r\n .filter(\r\n (item) => initialClasses.findIndex((init) => item === init) === -1\r\n );\r\n }\r\n\r\n _durationToMsNumber(time) {\r\n return Number(time.replace(\"ms\", \"\").replace(\"s\", \"000\"));\r\n }\r\n\r\n _getConfig(config = {}) {\r\n const dataAttributes = Manipulator.getDataAttributes(this._element);\r\n\r\n config = {\r\n ...Default,\r\n ...dataAttributes,\r\n ...config,\r\n };\r\n\r\n typeCheckConfig(NAME, config, DefaultType);\r\n return config;\r\n }\r\n\r\n _getClasses(classes = {}) {\r\n const dataAttributes = Manipulator.getDataClassAttributes(this._element);\r\n\r\n classes = {\r\n ...DefaultClasses,\r\n ...dataAttributes,\r\n ...classes,\r\n };\r\n\r\n typeCheckConfig(NAME, classes, DefaultClassesType);\r\n\r\n return classes;\r\n }\r\n\r\n _getDiameter({ offsetX, offsetY, height, width }) {\r\n const top = offsetY <= height / 2;\r\n const left = offsetX <= width / 2;\r\n const pythagorean = (sideA, sideB) => Math.sqrt(sideA ** 2 + sideB ** 2);\r\n\r\n const positionCenter = offsetY === height / 2 && offsetX === width / 2;\r\n // mouse position on the quadrants of the coordinate system\r\n const quadrant = {\r\n first: top === true && left === false,\r\n second: top === true && left === true,\r\n third: top === false && left === true,\r\n fourth: top === false && left === false,\r\n };\r\n\r\n const getCorner = {\r\n topLeft: pythagorean(offsetX, offsetY),\r\n topRight: pythagorean(width - offsetX, offsetY),\r\n bottomLeft: pythagorean(offsetX, height - offsetY),\r\n bottomRight: pythagorean(width - offsetX, height - offsetY),\r\n };\r\n\r\n let diameter = 0;\r\n\r\n if (positionCenter || quadrant.fourth) {\r\n diameter = getCorner.topLeft;\r\n } else if (quadrant.third) {\r\n diameter = getCorner.topRight;\r\n } else if (quadrant.second) {\r\n diameter = getCorner.bottomRight;\r\n } else if (quadrant.first) {\r\n diameter = getCorner.bottomLeft;\r\n }\r\n return diameter * 2;\r\n }\r\n\r\n _appendRipple(target, parent) {\r\n const FIX_ADD_RIPPLE_EFFECT = 50; // delay for active animations\r\n parent.appendChild(target);\r\n setTimeout(() => {\r\n Manipulator.addClass(target, \"opacity-0 scale-100\");\r\n }, FIX_ADD_RIPPLE_EFFECT);\r\n }\r\n\r\n _toggleUnbound(target) {\r\n if (this._options.rippleUnbound === true) {\r\n Manipulator.addClass(target, this._classes.unbound);\r\n } else {\r\n Manipulator.removeClass(target, this._classes.unbound);\r\n }\r\n }\r\n\r\n _addColor(target) {\r\n let rippleColor = this._options.rippleColor || \"rgb(0,0,0)\";\r\n\r\n if (\r\n localStorage.theme === \"dark\" ||\r\n (!(\"theme\" in localStorage) &&\r\n window.matchMedia(\"(prefers-color-scheme: dark)\").matches)\r\n ) {\r\n rippleColor = this._options.rippleColorDark || this._options.rippleColor;\r\n }\r\n\r\n const IS_BOOTSTRAP_COLOR = BOOTSTRAP_COLORS.find(\r\n (color) => color.name === rippleColor.toLowerCase()\r\n );\r\n\r\n const rgbValue = IS_BOOTSTRAP_COLOR\r\n ? this._colorToRGB(IS_BOOTSTRAP_COLOR.gradientColor).join(\",\")\r\n : this._colorToRGB(rippleColor).join(\",\");\r\n\r\n const gradientImage = GRADIENT.split(\"{{color}}\").join(`${rgbValue}`);\r\n target.style.backgroundImage = `radial-gradient(circle, ${gradientImage})`;\r\n }\r\n\r\n _colorToRGB(color) {\r\n function hexToRgb(color) {\r\n const HEX_COLOR_LENGTH = 7;\r\n const IS_SHORT_HEX = color.length < HEX_COLOR_LENGTH;\r\n if (IS_SHORT_HEX) {\r\n color = `#${color[1]}${color[1]}${color[2]}${color[2]}${color[3]}${color[3]}`;\r\n }\r\n return [\r\n parseInt(color.substr(1, 2), 16),\r\n parseInt(color.substr(3, 2), 16),\r\n parseInt(color.substr(5, 2), 16),\r\n ];\r\n }\r\n\r\n function namedColorsToRgba(color) {\r\n const tempElem = document.body.appendChild(\r\n document.createElement(\"fictum\")\r\n );\r\n const flag = \"rgb(1, 2, 3)\";\r\n tempElem.style.color = flag;\r\n if (tempElem.style.color !== flag) {\r\n return DEFAULT_RIPPLE_COLOR;\r\n }\r\n tempElem.style.color = color;\r\n if (tempElem.style.color === flag || tempElem.style.color === \"\") {\r\n return DEFAULT_RIPPLE_COLOR;\r\n } // color parse failed\r\n color = getComputedStyle(tempElem).color;\r\n document.body.removeChild(tempElem);\r\n return color;\r\n }\r\n\r\n function rgbaToRgb(color) {\r\n color = color.match(/[.\\d]+/g).map((a) => +Number(a));\r\n color.length = 3;\r\n return color;\r\n }\r\n\r\n if (color.toLowerCase() === \"transparent\") {\r\n return DEFAULT_RIPPLE_COLOR;\r\n }\r\n if (color[0] === \"#\") {\r\n return hexToRgb(color);\r\n }\r\n if (color.indexOf(\"rgb\") === -1) {\r\n color = namedColorsToRgba(color);\r\n }\r\n if (color.indexOf(\"rgb\") === 0) {\r\n return rgbaToRgb(color);\r\n }\r\n\r\n return DEFAULT_RIPPLE_COLOR;\r\n }\r\n\r\n // Static\r\n static autoInitial(instance) {\r\n return function (event) {\r\n instance._autoInit(event);\r\n };\r\n }\r\n\r\n static jQueryInterface(options) {\r\n return this.each(function () {\r\n const data = Data.getData(this, DATA_KEY);\r\n if (!data) {\r\n return new Ripple(this, options);\r\n }\r\n\r\n return null;\r\n });\r\n }\r\n\r\n static getInstance(element) {\r\n return Data.getData(element, DATA_KEY);\r\n }\r\n\r\n static getOrCreateInstance(element, config = {}) {\r\n return (\r\n this.getInstance(element) ||\r\n new this(element, typeof config === \"object\" ? config : null)\r\n );\r\n }\r\n}\r\n\r\nexport default Ripple;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nexport function getDate(date) {\r\n return date.getDate();\r\n}\r\n\r\nexport function getDayNumber(date) {\r\n return date.getDay();\r\n}\r\n\r\nexport function getMonth(date) {\r\n return date.getMonth();\r\n}\r\n\r\nexport function getYear(date) {\r\n return date.getFullYear();\r\n}\r\n\r\nexport function getFirstDayOfWeek(year, month, options) {\r\n const firstDayIndex = options.startDay;\r\n const sundayIndex = firstDayIndex > 0 ? 7 - firstDayIndex : 0;\r\n const date = new Date(year, month);\r\n const index = date.getDay() + sundayIndex;\r\n const newIndex = index >= 7 ? index - 7 : index;\r\n return newIndex;\r\n}\r\n\r\nexport function getDaysInMonth(date) {\r\n return getMonthEnd(date).getDate();\r\n}\r\n\r\nexport function getMonthEnd(date) {\r\n return createDate(date.getFullYear(), date.getMonth() + 1, 0);\r\n}\r\n\r\nexport function getToday() {\r\n return new Date();\r\n}\r\n\r\nexport function addYears(date, years) {\r\n return addMonths(date, years * 12);\r\n}\r\n\r\nexport function addMonths(date, months) {\r\n const month = createDate(\r\n date.getFullYear(),\r\n date.getMonth() + months,\r\n date.getDate()\r\n );\r\n const dayOfPreviousMonth = getDate(date);\r\n const dayOfNewMonth = getDate(month);\r\n\r\n // Solution for edge cases, like moving from a month with a greater number\r\n // of days than the destination month. For example, when we move from 31 Mar 2020 to\r\n // February, createDate(2020, 2, 31) will return 2 Mar 2020, not the desired 29 Feb 2020.\r\n // We need to use setDate(0) to move back to the last day of the previous month (29 Feb 2020)\r\n if (dayOfPreviousMonth !== dayOfNewMonth) {\r\n month.setDate(0);\r\n }\r\n\r\n return month;\r\n}\r\n\r\nexport function addDays(date, days) {\r\n return createDate(date.getFullYear(), date.getMonth(), date.getDate() + days);\r\n}\r\n\r\nexport function createDate(year, month, day) {\r\n const result = new Date(year, month, day);\r\n\r\n // In js native date years from 0 to 99 are treated as abbreviation\r\n // for dates like 19xx\r\n if (year >= 0 && year < 100) {\r\n result.setFullYear(result.getFullYear() - 1900);\r\n }\r\n return result;\r\n}\r\n\r\nexport function convertStringToDate(dateString) {\r\n const dateArr = dateString.split(\"-\");\r\n const year = dateArr[0];\r\n const month = dateArr[1];\r\n const day = dateArr[2];\r\n\r\n return createDate(year, month, day);\r\n}\r\n\r\nexport function isValidDate(date) {\r\n return !Number.isNaN(date.getTime());\r\n}\r\n\r\nexport function compareDates(date1, date2) {\r\n return (\r\n getYear(date1) - getYear(date2) ||\r\n getMonth(date1) - getMonth(date2) ||\r\n getDate(date1) - getDate(date2)\r\n );\r\n}\r\n\r\nexport function isSameDate(date1, date2) {\r\n date1.setHours(0, 0, 0, 0);\r\n date2.setHours(0, 0, 0, 0);\r\n\r\n return date1.getTime() === date2.getTime();\r\n}\r\n\r\nexport function getYearsOffset(activeDate, yearsInView) {\r\n const activeYear = getYear(activeDate);\r\n const yearsDifference = activeYear - getStartYear();\r\n return modulo(yearsDifference, yearsInView);\r\n}\r\n\r\nfunction modulo(a, b) {\r\n return ((a % b) + b) % b;\r\n}\r\n\r\nexport function getStartYear(yearsInView, minDate, maxDate) {\r\n let startYear = 0;\r\n\r\n if (maxDate) {\r\n const maxYear = getYear(maxDate);\r\n startYear = maxYear - yearsInView + 1;\r\n } else if (minDate) {\r\n startYear = getYear(minDate);\r\n }\r\n\r\n return startYear;\r\n}\r\n\r\nexport function isDateDisabled(\r\n date,\r\n minDate,\r\n maxDate,\r\n filter,\r\n disabledPast,\r\n disabledFuture\r\n) {\r\n const currentDate = new Date();\r\n currentDate.setHours(0, 0, 0, 0);\r\n\r\n const isBeforeMin = minDate && compareDates(date, minDate) <= -1;\r\n const isAfterMax = maxDate && compareDates(date, maxDate) >= 1;\r\n\r\n const isDisabledPast = disabledPast && compareDates(date, currentDate) <= -1;\r\n const isDisabledFuture =\r\n disabledFuture && compareDates(date, currentDate) >= 1;\r\n\r\n const isDisabled = filter && filter(date) === false;\r\n\r\n return (\r\n isBeforeMin ||\r\n isAfterMax ||\r\n isDisabled ||\r\n isDisabledPast ||\r\n isDisabledFuture\r\n );\r\n}\r\n\r\nexport function isMonthDisabled(\r\n month,\r\n year,\r\n minDate,\r\n maxDate,\r\n disabledPast,\r\n disabledFuture\r\n) {\r\n const currentDate = new Date();\r\n const maxYear = maxDate && getYear(maxDate);\r\n const maxMonth = maxDate && getMonth(maxDate);\r\n const minYear = minDate && getYear(minDate);\r\n const minMonth = minDate && getMonth(minDate);\r\n const currentYear = getYear(currentDate);\r\n const currentMonth = getMonth(currentDate);\r\n\r\n const isMonthAndYearAfterMax =\r\n maxMonth &&\r\n maxYear &&\r\n (year > maxYear || (year === maxYear && month > maxMonth));\r\n\r\n const isMonthAndYearBeforeMin =\r\n minMonth &&\r\n minYear &&\r\n (year < minYear || (year === minYear && month < minMonth));\r\n\r\n const isMonthAndYearDisabledPast =\r\n disabledPast &&\r\n (year < currentYear || (year === currentYear && month < currentMonth));\r\n const isMonthAndYearDisabledFuture =\r\n disabledFuture &&\r\n (year > currentYear || (year === currentYear && month > currentMonth));\r\n\r\n return (\r\n isMonthAndYearAfterMax ||\r\n isMonthAndYearBeforeMin ||\r\n isMonthAndYearDisabledPast ||\r\n isMonthAndYearDisabledFuture\r\n );\r\n}\r\n\r\nexport function isYearDisabled(\r\n year,\r\n minDate,\r\n maxDate,\r\n disabledPast,\r\n disabledFuture\r\n) {\r\n const min = minDate && getYear(minDate);\r\n const max = maxDate && getYear(maxDate);\r\n const currentYear = getYear(new Date());\r\n\r\n const isAfterMax = max && year > max;\r\n const isBeforeMin = min && year < min;\r\n const isDisabledPast = disabledPast && year < currentYear;\r\n const isDisabledFuture = disabledFuture && year > currentYear;\r\n\r\n return isAfterMax || isBeforeMin || isDisabledPast || isDisabledFuture;\r\n}\r\n\r\nexport function isNextDateDisabled(\r\n disabledFuture,\r\n activeDate,\r\n view,\r\n yearsInView,\r\n minDate,\r\n maxDate,\r\n lastYearInView,\r\n firstYearInView\r\n) {\r\n const currentDate = new Date();\r\n currentDate.setHours(0, 0, 0, 0);\r\n if (disabledFuture && maxDate && compareDates(maxDate, currentDate) < 0) {\r\n maxDate = currentDate;\r\n } else if (disabledFuture) {\r\n maxDate = currentDate;\r\n }\r\n return (\r\n maxDate &&\r\n areDatesInSameView(\r\n activeDate,\r\n maxDate,\r\n view,\r\n yearsInView,\r\n minDate,\r\n maxDate,\r\n lastYearInView,\r\n firstYearInView\r\n )\r\n );\r\n}\r\n\r\nexport function isPreviousDateDisabled(\r\n disabledPast,\r\n activeDate,\r\n view,\r\n yearsInView,\r\n minDate,\r\n maxDate,\r\n lastYearInView,\r\n firstYearInView\r\n) {\r\n const currentDate = new Date();\r\n currentDate.setHours(0, 0, 0, 0);\r\n if (disabledPast && minDate && compareDates(minDate, currentDate) < 0) {\r\n minDate = currentDate;\r\n } else if (disabledPast) {\r\n minDate = currentDate;\r\n }\r\n return (\r\n minDate &&\r\n areDatesInSameView(\r\n activeDate,\r\n minDate,\r\n view,\r\n yearsInView,\r\n minDate,\r\n maxDate,\r\n lastYearInView,\r\n firstYearInView\r\n )\r\n );\r\n}\r\n\r\nexport function areDatesInSameView(\r\n date1,\r\n date2,\r\n view,\r\n yearsInView,\r\n minDate,\r\n maxDate,\r\n lastYearInView,\r\n firstYearInView\r\n) {\r\n if (view === \"days\") {\r\n return (\r\n getYear(date1) === getYear(date2) && getMonth(date1) === getMonth(date2)\r\n );\r\n }\r\n\r\n if (view === \"months\") {\r\n return getYear(date1) === getYear(date2);\r\n }\r\n\r\n if (view === \"years\") {\r\n return (\r\n getYear(date2) >= firstYearInView && getYear(date2) <= lastYearInView\r\n );\r\n }\r\n\r\n return false;\r\n}\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\n/* eslint-disable indent */\r\n\r\nimport Manipulator from \"../../dom/manipulator\";\r\nimport { element } from \"../../util\";\r\nimport {\r\n getYear,\r\n getMonth,\r\n getDate,\r\n getDayNumber,\r\n getFirstDayOfWeek,\r\n addMonths,\r\n getDaysInMonth,\r\n createDate,\r\n isSameDate,\r\n getToday,\r\n getYearsOffset,\r\n isDateDisabled,\r\n isMonthDisabled,\r\n isYearDisabled,\r\n} from \"./date-utils\";\r\n\r\nconst MODAL_CONTAINER_REF = \"data-te-datepicker-modal-container-ref\";\r\nconst DROPDOWN_CONTAINER_REF = \"data-te-datepicker-dropdown-container-ref\";\r\nconst BACKDROP_REF = \"data-te-dropdown-backdrop-ref\";\r\nconst DATE_TEXT_REF = \"data-te-datepicker-date-text-ref\";\r\nconst VIEW_REF = \"data-te-datepicker-view-ref\";\r\nconst PREVIOUS_BUTTON_REF = \"data-te-datepicker-previous-button-ref\";\r\nconst NEXT_BUTTON_REF = \"data-te-datepicker-next-button-ref\";\r\nconst OK_BUTTON_REF = \"data-te-datepicker-ok-button-ref\";\r\nconst CANCEL_BUTTON_REF = \"data-te-datepicker-cancel-button-ref\";\r\nconst CLEAR_BUTTON_REF = \"data-te-datepicker-clear-button-ref\";\r\nconst VIEW_CHANGE_BUTTON_REF = \"data-te-datepicker-view-change-button-ref\";\r\n\r\nexport function getDatepickerTemplate(\r\n date,\r\n selectedDate,\r\n selectedYear,\r\n selectedMonth,\r\n options,\r\n monthsInRow,\r\n yearsInView,\r\n yearsInRow,\r\n id,\r\n classes\r\n) {\r\n const month = getMonth(date);\r\n const year = getYear(date);\r\n const day = getDate(date);\r\n const dayNumber = getDayNumber(date);\r\n const template = element(\"div\");\r\n const inlineContent = `\r\n ${createMainContent(\r\n date,\r\n month,\r\n year,\r\n selectedDate,\r\n selectedYear,\r\n selectedMonth,\r\n options,\r\n monthsInRow,\r\n yearsInView,\r\n yearsInRow,\r\n classes\r\n )}\r\n `;\r\n const modalContent = `\r\n ${createHeader(day, dayNumber, month, options, classes)}\r\n ${createMainContent(\r\n date,\r\n month,\r\n year,\r\n selectedDate,\r\n selectedYear,\r\n selectedMonth,\r\n options,\r\n monthsInRow,\r\n yearsInView,\r\n yearsInRow,\r\n classes\r\n )}\r\n `;\r\n\r\n if (options.inline) {\r\n Manipulator.addClass(template, classes.datepickerDropdownContainer);\r\n template.setAttribute(DROPDOWN_CONTAINER_REF, id);\r\n\r\n template.innerHTML = inlineContent;\r\n } else {\r\n Manipulator.addClass(template, classes.modalContainer);\r\n template.setAttribute(MODAL_CONTAINER_REF, id);\r\n\r\n template.innerHTML = modalContent;\r\n }\r\n\r\n return template;\r\n}\r\n\r\nexport function getBackdropTemplate(backdropClasses) {\r\n const backdrop = element(\"div\");\r\n Manipulator.addClass(backdrop, backdropClasses);\r\n backdrop.setAttribute(BACKDROP_REF, \"\");\r\n\r\n return backdrop;\r\n}\r\n\r\nexport function createContainer(modalContainerClasses) {\r\n const container = element(\"div\");\r\n Manipulator.addClass(container, modalContainerClasses);\r\n container.setAttribute(MODAL_CONTAINER_REF, \"\");\r\n\r\n return container;\r\n}\r\n\r\nfunction createHeader(day, dayNumber, month, options, classes) {\r\n return `\r\n \r\n `;\r\n}\r\n\r\nfunction createMainContent(\r\n date,\r\n month,\r\n year,\r\n selectedDate,\r\n selectedYear,\r\n selectedMonth,\r\n options,\r\n monthsInRow,\r\n yearsInView,\r\n yearsInRow,\r\n classes\r\n) {\r\n let mainContentTemplate;\r\n if (options.inline) {\r\n mainContentTemplate = `\r\n \r\n ${createControls(month, year, options, classes)}\r\n
\r\n ${createViewTemplate(\r\n date,\r\n year,\r\n selectedDate,\r\n selectedYear,\r\n selectedMonth,\r\n options,\r\n monthsInRow,\r\n yearsInView,\r\n yearsInRow,\r\n classes\r\n )}\r\n
\r\n
\r\n `;\r\n } else {\r\n mainContentTemplate = `\r\n \r\n ${createControls(month, year, options, classes)}\r\n
\r\n ${createViewTemplate(\r\n date,\r\n year,\r\n selectedDate,\r\n selectedYear,\r\n selectedMonth,\r\n options,\r\n monthsInRow,\r\n yearsInView,\r\n yearsInRow,\r\n classes\r\n )}\r\n
\r\n ${createFooter(options, classes)}\r\n
\r\n `;\r\n }\r\n\r\n return mainContentTemplate;\r\n}\r\n\r\nfunction createViewTemplate(\r\n date,\r\n year,\r\n selectedDate,\r\n selectedYear,\r\n selectedMonth,\r\n options,\r\n monthsInRow,\r\n yearsInView,\r\n yearsInRow,\r\n classes\r\n) {\r\n let viewTemplate;\r\n if (options.view === \"days\") {\r\n viewTemplate = createDayViewTemplate(date, selectedDate, options, classes);\r\n } else if (options.view === \"months\") {\r\n viewTemplate = createMonthViewTemplate(\r\n year,\r\n selectedYear,\r\n selectedMonth,\r\n options,\r\n monthsInRow,\r\n classes\r\n );\r\n } else {\r\n viewTemplate = createYearViewTemplate(\r\n date,\r\n selectedYear,\r\n options,\r\n yearsInView,\r\n yearsInRow,\r\n classes\r\n );\r\n }\r\n\r\n return viewTemplate;\r\n}\r\n\r\nfunction createControls(month, year, options, classes) {\r\n return `\r\n \r\n
\r\n ${options.monthsFull[month]} ${year} ${createViewChangeButtonIcon(\r\n options,\r\n classes\r\n )}\r\n \r\n
\r\n ${options.changeMonthIconTemplate} \r\n ${options.changeMonthIconTemplate} \r\n
\r\n
\r\n `;\r\n}\r\n\r\nexport function createViewChangeButtonIcon(options, classes) {\r\n return `\r\n \r\n ${options.viewChangeIconTemplate}\r\n \r\n `;\r\n}\r\n\r\nfunction createFooter(options, classes) {\r\n const okBtn = ``;\r\n const cancelButton = ``;\r\n const clearButton = ``;\r\n\r\n return `\r\n \r\n `;\r\n}\r\n\r\nexport function createDayViewTemplate(date, headerDate, options, classes) {\r\n const dates = getDatesArray(date, headerDate, options);\r\n const dayNames = options.weekdaysNarrow;\r\n\r\n const tableHeadContent = `\r\n \r\n ${dayNames\r\n .map((name, i) => {\r\n return `${name} `;\r\n })\r\n .join(\"\")}\r\n \r\n `;\r\n\r\n const tableBodyContent = dates\r\n .map((week) => {\r\n return `\r\n \r\n ${week\r\n .map((day) => {\r\n return `\r\n \r\n \r\n ${day.dayNumber}\r\n
\r\n \r\n `;\r\n })\r\n .join(\"\")}\r\n \r\n `;\r\n })\r\n .join(\"\");\r\n\r\n return `\r\n \r\n \r\n ${tableHeadContent}\r\n \r\n \r\n ${tableBodyContent}\r\n \r\n
\r\n `;\r\n}\r\n\r\nfunction getDatesArray(activeDate, headerDate, options) {\r\n const dates = [];\r\n\r\n const month = getMonth(activeDate);\r\n const previousMonth = getMonth(addMonths(activeDate, -1));\r\n const nextMonth = getMonth(addMonths(activeDate, 1));\r\n const year = getYear(activeDate);\r\n\r\n const firstDay = getFirstDayOfWeek(year, month, options);\r\n const daysInMonth = getDaysInMonth(activeDate);\r\n const daysInPreviousMonth = getDaysInMonth(addMonths(activeDate, -1));\r\n const daysInWeek = 7;\r\n\r\n let dayNumber = 1;\r\n let isCurrentMonth = false;\r\n for (let i = 1; i < daysInWeek; i++) {\r\n const week = [];\r\n if (i === 1) {\r\n // First week\r\n const previousMonthDay = daysInPreviousMonth - firstDay + 1;\r\n // Previous month\r\n for (let j = previousMonthDay; j <= daysInPreviousMonth; j++) {\r\n const date = createDate(year, previousMonth, j);\r\n\r\n week.push({\r\n date,\r\n currentMonth: isCurrentMonth,\r\n isSelected: headerDate && isSameDate(date, headerDate),\r\n isToday: isSameDate(date, getToday()),\r\n dayNumber: getDate(date),\r\n });\r\n }\r\n\r\n isCurrentMonth = true;\r\n // Current month\r\n const daysLeft = daysInWeek - week.length;\r\n for (let j = 0; j < daysLeft; j++) {\r\n const date = createDate(year, month, dayNumber);\r\n\r\n week.push({\r\n date,\r\n currentMonth: isCurrentMonth,\r\n isSelected: headerDate && isSameDate(date, headerDate),\r\n isToday: isSameDate(date, getToday()),\r\n dayNumber: getDate(date),\r\n disabled: isDateDisabled(\r\n date,\r\n options.min,\r\n options.max,\r\n options.filter,\r\n options.disablePast,\r\n options.disableFuture\r\n ),\r\n });\r\n dayNumber++;\r\n }\r\n } else {\r\n // Rest of the weeks\r\n for (let j = 1; j < 8; j++) {\r\n if (dayNumber > daysInMonth) {\r\n // Next month\r\n dayNumber = 1;\r\n isCurrentMonth = false;\r\n }\r\n const date = createDate(\r\n year,\r\n isCurrentMonth ? month : nextMonth,\r\n dayNumber\r\n );\r\n\r\n week.push({\r\n date,\r\n currentMonth: isCurrentMonth,\r\n isSelected: headerDate && isSameDate(date, headerDate),\r\n isToday: isSameDate(date, getToday()),\r\n dayNumber: getDate(date),\r\n disabled: isDateDisabled(\r\n date,\r\n options.min,\r\n options.max,\r\n options.filter,\r\n options.disablePast,\r\n options.disableFuture\r\n ),\r\n });\r\n dayNumber++;\r\n }\r\n }\r\n dates.push(week);\r\n }\r\n\r\n return dates;\r\n}\r\n\r\nexport function createMonthViewTemplate(\r\n year,\r\n selectedYear,\r\n selectedMonth,\r\n options,\r\n monthsInRow,\r\n classes\r\n) {\r\n const months = getMonthsArray(options, monthsInRow);\r\n const currentMonth = getMonth(getToday());\r\n const currentYear = getYear(getToday());\r\n\r\n const tableBodyContent = `\r\n ${months\r\n .map((row) => {\r\n return `\r\n \r\n ${row\r\n .map((month) => {\r\n const monthIndex = options.monthsShort.indexOf(month);\r\n return `\r\n \r\n ${month}
\r\n \r\n `;\r\n })\r\n .join(\"\")}\r\n \r\n `;\r\n })\r\n .join(\"\")}\r\n `;\r\n\r\n return `\r\n \r\n \r\n ${tableBodyContent}\r\n \r\n
\r\n `;\r\n}\r\n\r\nfunction getMonthsArray(options, monthsInRow) {\r\n const months = [];\r\n\r\n let row = [];\r\n\r\n for (let i = 0; i < options.monthsShort.length; i++) {\r\n row.push(options.monthsShort[i]);\r\n\r\n if (row.length === monthsInRow) {\r\n const monthsRow = row;\r\n months.push(monthsRow);\r\n row = [];\r\n }\r\n }\r\n\r\n return months;\r\n}\r\n\r\nexport function createYearViewTemplate(\r\n date,\r\n selectedYear,\r\n options,\r\n yearsInView,\r\n yearsInRow,\r\n classes\r\n) {\r\n const years = getYearsArray(date, yearsInView, yearsInRow);\r\n const currentYear = getYear(getToday());\r\n\r\n const tableBodyContent = `\r\n ${years\r\n .map((row) => {\r\n return `\r\n \r\n ${row\r\n .map((year) => {\r\n return `\r\n \r\n ${year}
\r\n \r\n `;\r\n })\r\n .join(\"\")}\r\n \r\n `;\r\n })\r\n .join(\"\")}\r\n `;\r\n\r\n return `\r\n \r\n \r\n ${tableBodyContent}\r\n \r\n
\r\n `;\r\n}\r\n\r\nfunction getYearsArray(date, yearsInView, yearsInRow) {\r\n const years = [];\r\n const activeYear = getYear(date);\r\n const yearsOffset = getYearsOffset(date, yearsInView);\r\n\r\n const firstYearInView = activeYear - yearsOffset;\r\n\r\n let row = [];\r\n\r\n for (let i = 0; i < yearsInView; i++) {\r\n row.push(firstYearInView + i);\r\n\r\n if (row.length === yearsInRow) {\r\n const yearsRow = row;\r\n years.push(yearsRow);\r\n row = [];\r\n }\r\n }\r\n\r\n return years;\r\n}\r\n\r\nexport function getToggleButtonTemplate(id, toggleBtnClasses) {\r\n return `\r\n \r\n \r\n \r\n \r\n \r\n `;\r\n}\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nexport const LEFT_ARROW = 37;\r\nexport const UP_ARROW = 38;\r\nexport const RIGHT_ARROW = 39;\r\nexport const DOWN_ARROW = 40;\r\nexport const HOME = 36;\r\nexport const END = 35;\r\nexport const PAGE_UP = 33;\r\nexport const PAGE_DOWN = 34;\r\nexport const ENTER = 13;\r\nexport const SPACE = 32;\r\nexport const ESCAPE = 27;\r\nexport const TAB = 9;\r\nexport const BACKSPACE = 8;\r\nexport const DELETE = 46;\r\nexport const A = 65;\r\nexport const B = 66;\r\nexport const C = 67;\r\nexport const D = 68;\r\nexport const E = 69;\r\nexport const F = 70;\r\nexport const G = 71;\r\nexport const H = 72;\r\nexport const I = 73;\r\nexport const J = 74;\r\nexport const K = 75;\r\nexport const L = 76;\r\nexport const M = 77;\r\nexport const N = 78;\r\nexport const O = 79;\r\nexport const P = 80;\r\nexport const Q = 81;\r\nexport const R = 82;\r\nexport const S = 83;\r\nexport const T = 84;\r\nexport const U = 85;\r\nexport const V = 86;\r\nexport const W = 87;\r\nexport const X = 88;\r\nexport const Y = 89;\r\nexport const Z = 90;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport { createPopper } from \"@popperjs/core\";\r\nimport Data from \"../../dom/data\";\r\nimport EventHandler from \"../../dom/event-handler\";\r\nimport Manipulator from \"../../dom/manipulator\";\r\nimport SelectorEngine from \"../../dom/selector-engine\";\r\nimport ScrollBarHelper from \"../../util/scrollbar\";\r\nimport { typeCheckConfig, getUID, isRTL } from \"../../util/index\";\r\nimport FocusTrap from \"../../util/focusTrap\";\r\nimport {\r\n getDate,\r\n getDayNumber,\r\n getMonth,\r\n getYear,\r\n getDaysInMonth,\r\n addYears,\r\n addMonths,\r\n addDays,\r\n createDate,\r\n convertStringToDate,\r\n isSameDate,\r\n areDatesInSameView,\r\n isDateDisabled,\r\n isMonthDisabled,\r\n isYearDisabled,\r\n isNextDateDisabled,\r\n isPreviousDateDisabled,\r\n getYearsOffset,\r\n isValidDate,\r\n} from \"./date-utils\";\r\nimport {\r\n getBackdropTemplate,\r\n getDatepickerTemplate,\r\n createDayViewTemplate,\r\n createMonthViewTemplate,\r\n createYearViewTemplate,\r\n getToggleButtonTemplate,\r\n createViewChangeButtonIcon,\r\n} from \"./templates\";\r\nimport {\r\n ENTER,\r\n SPACE,\r\n ESCAPE,\r\n LEFT_ARROW,\r\n RIGHT_ARROW,\r\n DOWN_ARROW,\r\n UP_ARROW,\r\n HOME,\r\n END,\r\n PAGE_UP,\r\n PAGE_DOWN,\r\n} from \"../../util/keycodes\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst YEARS_IN_VIEW = 24;\r\nconst YEARS_IN_ROW = 4;\r\nconst MONTHS_IN_ROW = 4;\r\n\r\nconst NAME = \"datepicker\";\r\nconst DATA_KEY = \"te.datepicker\";\r\nconst EVENT_KEY = `.${DATA_KEY}`;\r\nconst DATA_API_KEY = \".data-api\";\r\n\r\nconst EVENT_CLOSE = `close${EVENT_KEY}`;\r\nconst EVENT_OPEN = `open${EVENT_KEY}`;\r\nconst EVENT_DATE_CHANGE = `dateChange${EVENT_KEY}`;\r\nconst EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`;\r\n\r\nconst MODAL_CONTAINER_NAME = \"data-te-datepicker-modal-container-ref\";\r\nconst DROPDOWN_CONTAINER_NAME = \"data-te-datepicker-dropdown-container-ref\";\r\n\r\nconst DATEPICKER_TOGGLE_SELECTOR = \"[data-te-datepicker-toggle-ref]\";\r\nconst MODAL_CONTAINER_SELECTOR = `[${MODAL_CONTAINER_NAME}]`;\r\nconst DROPDOWN_CONTAINER_SELECTOR = `[${DROPDOWN_CONTAINER_NAME}]`;\r\nconst VIEW_CHANGE_BUTTON_SELECTOR =\r\n \"[data-te-datepicker-view-change-button-ref]\";\r\nconst PREVIOUS_BUTTON_SELECTOR = \"[data-te-datepicker-previous-button-ref]\";\r\nconst NEXT_BUTTON_SELECTOR = \"[data-te-datepicker-next-button-ref]\";\r\nconst OK_BUTTON_SELECTOR = \"[data-te-datepicker-ok-button-ref]\";\r\nconst CANCEL_BUTTON_SELECTOR = \"[data-te-datepicker-cancel-button-ref]\";\r\nconst CLEAR_BUTTON_SELECTOR = \"[data-te-datepicker-clear-button-ref]\";\r\nconst VIEW_SELECTOR = \"[data-te-datepicker-view-ref]\";\r\nconst TOGGLE_BUTTON_SELECTOR = \"[data-te-datepicker-toggle-button-ref]\";\r\nconst DATE_TEXT_SELECTOR = \"[data-te-datepicker-date-text-ref]\";\r\nconst BACKDROP_SELECTOR = \"[data-te-dropdown-backdrop-ref]\";\r\n\r\nconst FADE_IN_CLASSES =\r\n \"animate-[fade-in_0.3s_both] px-[auto] motion-reduce:transition-none motion-reduce:animate-none\";\r\nconst FADE_OUT_CLASSES =\r\n \"animate-[fade-out_0.3s_both] px-[auto] motion-reduce:transition-none motion-reduce:animate-none\";\r\nconst FADE_IN_SHORT_CLASSES =\r\n \"animate-[fade-in_0.15s_both] px-[auto] motion-reduce:transition-none motion-reduce:animate-none\";\r\nconst FADE_OUT_SHORT_CLASSES =\r\n \"animate-[fade-out_0.15s_both] px-[auto] motion-reduce:transition-none motion-reduce:animate-none\";\r\n\r\n// templates classes\r\nconst MODAL_CONTAINER_CLASSES =\r\n \"flex flex-col fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[328px] h-[512px] bg-white rounded-[0.6rem] shadow-lg z-[1066] xs:max-md:landscape:w-[475px] xs:max-md:landscape:h-[360px] xs:max-md:landscape:flex-row dark:bg-zinc-700\";\r\nconst DATEPICKER_BACKDROP_CLASSES =\r\n \"w-full h-full fixed top-0 right-0 left-0 bottom-0 bg-black/40 z-[1065]\";\r\nconst DATEPICKER_MAIN_CLASSES = \"relative h-full\";\r\nconst DATEPICKER_HEADER_CLASSES =\r\n \"xs:max-md:landscape:h-full h-[120px] px-6 bg-primary flex flex-col rounded-t-lg dark:bg-zinc-800\";\r\nconst DATEPICKER_TITLE_CLASSES = \"h-8 flex flex-col justify-end\";\r\nconst DATEPICKER_TITLE_TEXT_CLASSES =\r\n \"text-[10px] font-normal uppercase tracking-[1.7px] text-white\";\r\nconst DATEPICKER_DATE_CLASSES =\r\n \"xs:max-md:landscape:mt-24 h-[72px] flex flex-col justify-end\";\r\nconst DATEPICKER_DATE_TEXT_CLASSES = \"text-[34px] font-normal text-white\";\r\nconst DATEPICKER_VIEW_CLASSES = \"outline-none px-3\";\r\nconst DATEPICKER_DATE_CONTROLS_CLASSES =\r\n \"px-3 pt-2.5 pb-0 flex justify-between text-black/[64]\";\r\nconst DATEPICKER_VIEW_CHANGE_BUTTON_CLASSES = `flex items-center outline-none p-2.5 text-neutral-500 font-medium text-[0.9rem] rounded-xl shadow-none bg-transparent m-0 border-none hover:bg-neutral-200 focus:bg-neutral-200 dark:text-white dark:hover:bg-white/10 dark:focus:bg-white/10`;\r\nconst DATEPICKER_ARROW_CONTROLS_CLASSES = \"mt-2.5\";\r\nconst DATEPICKER_PREVIOUS_BUTTON_CLASSES =\r\n \"p-0 w-10 h-10 leading-10 border-none outline-none m-0 text-gray-600 bg-transparent mr-6 hover:bg-neutral-200 hover:rounded-[50%] focus:bg-neutral-200 focus:rounded-[50%] dark:text-white dark:hover:bg-white/10 dark:focus:bg-white/10 [&>svg]:w-4 [&>svg]:h-4 [&>svg]:mx-auto\";\r\nconst DATEPICKER_NEXT_BUTTON_CLASSES =\r\n \"p-0 w-10 h-10 leading-10 border-none outline-none m-0 text-gray-600 bg-transparent hover:bg-neutral-200 hover:rounded-[50%] focus:bg-neutral-200 focus:rounded-[50%] dark:text-white dark:hover:bg-white/10 dark:focus:bg-white/10 [&>svg]:w-4 [&>svg]:h-4 [&>svg]:rotate-180 [&>svg]:mx-auto\";\r\nconst DATEPICKER_FOOTER_CLASSES =\r\n \"h-14 flex absolute w-full bottom-0 justify-end items-center px-3\";\r\nconst DATEPICKER_FOOTER_BTN_CLASSES =\r\n \"outline-none bg-white text-primary border-none cursor-pointer py-0 px-2.5 uppercase text-[0.8rem] leading-10 font-medium h-10 tracking-[.1rem] rounded-[10px] mb-2.5 hover:bg-neutral-200 focus:bg-neutral-200 dark:bg-transparent dark:text-white dark:hover:bg-white/10 dark:focus:bg-white/10\";\r\nconst DATEPICKER_CLEAR_BTN_CLASSES = \"mr-auto\";\r\nconst DATEPICKER_DAY_HEADING_CLASSES =\r\n \"w-10 h-10 text-center text-[12px] font-normal dark:text-white\";\r\nconst DATEPICKER_CELL_CLASSES =\r\n \"text-center data-[te-datepicker-cell-disabled]:text-neutral-300 data-[te-datepicker-cell-disabled]:cursor-default data-[te-datepicker-cell-disabled]:pointer-events-none data-[te-datepicker-cell-disabled]:hover:cursor-default hover:cursor-pointer group\";\r\nconst DATEPICKER_CELL_SMALL_CLASSES =\r\n \"w-10 h-10 xs:max-md:landscape:w-8 xs:max-md:landscape:h-8\";\r\nconst DATEPICKER_CELL_LARGE_CLASSES = \"w-[76px] h-[42px]\";\r\nconst DATEPICKER_CELL_CONTENT_CLASSES =\r\n \"mx-auto group-[:not([data-te-datepicker-cell-disabled]):not([data-te-datepicker-cell-selected]):hover]:bg-neutral-300 group-[[data-te-datepicker-cell-selected]]:bg-primary group-[[data-te-datepicker-cell-selected]]:text-white group-[:not([data-te-datepicker-cell-selected])[data-te-datepicker-cell-focused]]:bg-neutral-100 group-[[data-te-datepicker-cell-focused]]:data-[te-datepicker-cell-selected]:bg-primary group-[[data-te-datepicker-cell-current]]:border-solid group-[[data-te-datepicker-cell-current]]:border-black group-[[data-te-datepicker-cell-current]]:border dark:group-[:not([data-te-datepicker-cell-disabled]):not([data-te-datepicker-cell-selected]):hover]:bg-white/10 dark:group-[[data-te-datepicker-cell-current]]:border-white dark:text-white dark:group-[:not([data-te-datepicker-cell-selected])[data-te-datepicker-cell-focused]]:bg-white/10 dark:group-[[data-te-datepicker-cell-disabled]]:text-neutral-500\";\r\nconst DATEPICKER_CELL_CONTENT_SMALL_CLASSES =\r\n \"w-9 h-9 leading-9 rounded-[50%] text-[13px]\";\r\nconst DATEPICKER_CELL_CONTENT_LARGE_CLASSES =\r\n \"w-[72px] h-10 leading-10 py-[1px] px-0.5 rounded-[999px]\";\r\nconst DATEPICKER_TABLE_CLASSES = \"mx-auto w-[304px]\";\r\nconst DATEPICKER_TOGGLE_BUTTON_CLASSES =\r\n \"flex items-center justify-content-center [&>svg]:w-5 [&>svg]:h-5 absolute outline-none border-none bg-transparent right-0.5 top-1/2 -translate-x-1/2 -translate-y-1/2 hover:text-primary focus:text-primary dark:hover:text-primary-400 dark:focus:text-primary-400 dark:text-neutral-200\";\r\nconst DATEPICKER_VIEW_CHANGE_ICON_CLASSES =\r\n \"inline-block pointer-events-none ml-[3px] [&>svg]:w-4 [&>svg]:h-4 [&>svg]:fill-neutral-500 dark:[&>svg]:fill-white\";\r\nconst DATEPICKER_DROPDOWN_CONTAINER_CLASSES =\r\n \"w-[328px] h-[380px] bg-white rounded-lg shadow-[0px_2px_15px_-3px_rgba(0,0,0,.07),_0px_10px_20px_-2px_rgba(0,0,0,.04)] z-[1066] dark:bg-zinc-700\";\r\n\r\nconst Default = {\r\n title: \"Select date\",\r\n container: \"body\",\r\n disablePast: false,\r\n disableFuture: false,\r\n monthsFull: [\r\n \"January\",\r\n \"February\",\r\n \"March\",\r\n \"April\",\r\n \"May\",\r\n \"June\",\r\n \"July\",\r\n \"August\",\r\n \"September\",\r\n \"October\",\r\n \"November\",\r\n \"December\",\r\n ],\r\n monthsShort: [\r\n \"Jan\",\r\n \"Feb\",\r\n \"Mar\",\r\n \"Apr\",\r\n \"May\",\r\n \"Jun\",\r\n \"Jul\",\r\n \"Aug\",\r\n \"Sep\",\r\n \"Oct\",\r\n \"Nov\",\r\n \"Dec\",\r\n ],\r\n weekdaysFull: [\r\n \"Sunday\",\r\n \"Monday\",\r\n \"Tuesday\",\r\n \"Wednesday\",\r\n \"Thursday\",\r\n \"Friday\",\r\n \"Saturday\",\r\n ],\r\n weekdaysShort: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"],\r\n weekdaysNarrow: [\"S\", \"M\", \"T\", \"W\", \"T\", \"F\", \"S\"],\r\n okBtnText: \"Ok\",\r\n clearBtnText: \"Clear\",\r\n cancelBtnText: \"Cancel\",\r\n\r\n okBtnLabel: \"Confirm selection\",\r\n clearBtnLabel: \"Clear selection\",\r\n cancelBtnLabel: \"Cancel selection\",\r\n nextMonthLabel: \"Next month\",\r\n prevMonthLabel: \"Previous month\",\r\n nextYearLabel: \"Next year\",\r\n prevYearLabel: \"Previous year\",\r\n changeMonthIconTemplate: `\r\n \r\n \r\n `,\r\n nextMultiYearLabel: \"Next 24 years\",\r\n prevMultiYearLabel: \"Previous 24 years\",\r\n switchToMultiYearViewLabel: \"Choose year and month\",\r\n switchToMonthViewLabel: \"Choose date\",\r\n switchToDayViewLabel: \"Choose date\",\r\n\r\n startDate: null,\r\n startDay: 0,\r\n format: \"dd/mm/yyyy\",\r\n view: \"days\",\r\n viewChangeIconTemplate: `\r\n \r\n \r\n `,\r\n\r\n min: null,\r\n max: null,\r\n filter: null,\r\n\r\n inline: false,\r\n toggleButton: true,\r\n disableToggleButton: false,\r\n disableInput: false,\r\n animations: true,\r\n confirmDateOnSelect: false,\r\n removeOkBtn: false,\r\n removeCancelBtn: false,\r\n removeClearBtn: false,\r\n};\r\n\r\nconst DefaultType = {\r\n title: \"string\",\r\n container: \"string\",\r\n disablePast: \"boolean\",\r\n disableFuture: \"boolean\",\r\n monthsFull: \"array\",\r\n monthsShort: \"array\",\r\n weekdaysFull: \"array\",\r\n weekdaysShort: \"array\",\r\n weekdaysNarrow: \"array\",\r\n\r\n okBtnText: \"string\",\r\n clearBtnText: \"string\",\r\n cancelBtnText: \"string\",\r\n okBtnLabel: \"string\",\r\n clearBtnLabel: \"string\",\r\n cancelBtnLabel: \"string\",\r\n nextMonthLabel: \"string\",\r\n prevMonthLabel: \"string\",\r\n nextYearLabel: \"string\",\r\n prevYearLabel: \"string\",\r\n nextMultiYearLabel: \"string\",\r\n prevMultiYearLabel: \"string\",\r\n changeMonthIconTemplate: \"string\",\r\n switchToMultiYearViewLabel: \"string\",\r\n switchToMonthViewLabel: \"string\",\r\n switchToDayViewLabel: \"string\",\r\n\r\n startDate: \"(null|string|date)\",\r\n startDay: \"number\",\r\n format: \"string\",\r\n view: \"string\",\r\n viewChangeIconTemplate: \"string\",\r\n\r\n min: \"(null|string|date)\",\r\n max: \"(null|string|date)\",\r\n filter: \"(null|function)\",\r\n\r\n inline: \"boolean\",\r\n toggleButton: \"boolean\",\r\n disableToggleButton: \"boolean\",\r\n disableInput: \"boolean\",\r\n animations: \"boolean\",\r\n confirmDateOnSelect: \"boolean\",\r\n removeOkBtn: \"boolean\",\r\n removeCancelBtn: \"boolean\",\r\n removeClearBtn: \"boolean\",\r\n};\r\n\r\nconst DefaultClasses = {\r\n fadeIn: FADE_IN_CLASSES,\r\n fadeOut: FADE_OUT_CLASSES,\r\n fadeInShort: FADE_IN_SHORT_CLASSES,\r\n fadeOutShort: FADE_OUT_SHORT_CLASSES,\r\n modalContainer: MODAL_CONTAINER_CLASSES,\r\n datepickerBackdrop: DATEPICKER_BACKDROP_CLASSES,\r\n datepickerMain: DATEPICKER_MAIN_CLASSES,\r\n datepickerHeader: DATEPICKER_HEADER_CLASSES,\r\n datepickerTitle: DATEPICKER_TITLE_CLASSES,\r\n datepickerTitleText: DATEPICKER_TITLE_TEXT_CLASSES,\r\n datepickerDate: DATEPICKER_DATE_CLASSES,\r\n datepickerDateText: DATEPICKER_DATE_TEXT_CLASSES,\r\n datepickerView: DATEPICKER_VIEW_CLASSES,\r\n datepickerDateControls: DATEPICKER_DATE_CONTROLS_CLASSES,\r\n datepickerViewChangeButton: DATEPICKER_VIEW_CHANGE_BUTTON_CLASSES,\r\n datepickerViewChangeIcon: DATEPICKER_VIEW_CHANGE_ICON_CLASSES,\r\n datepickerArrowControls: DATEPICKER_ARROW_CONTROLS_CLASSES,\r\n datepickerPreviousButton: DATEPICKER_PREVIOUS_BUTTON_CLASSES,\r\n datepickerNextButton: DATEPICKER_NEXT_BUTTON_CLASSES,\r\n datepickerFooter: DATEPICKER_FOOTER_CLASSES,\r\n datepickerFooterBtn: DATEPICKER_FOOTER_BTN_CLASSES,\r\n datepickerClearBtn: DATEPICKER_CLEAR_BTN_CLASSES,\r\n datepickerDayHeading: DATEPICKER_DAY_HEADING_CLASSES,\r\n datepickerCell: DATEPICKER_CELL_CLASSES,\r\n datepickerCellSmall: DATEPICKER_CELL_SMALL_CLASSES,\r\n datepickerCellLarge: DATEPICKER_CELL_LARGE_CLASSES,\r\n datepickerCellContent: DATEPICKER_CELL_CONTENT_CLASSES,\r\n datepickerCellContentSmall: DATEPICKER_CELL_CONTENT_SMALL_CLASSES,\r\n datepickerCellContentLarge: DATEPICKER_CELL_CONTENT_LARGE_CLASSES,\r\n datepickerTable: DATEPICKER_TABLE_CLASSES,\r\n datepickerToggleButton: DATEPICKER_TOGGLE_BUTTON_CLASSES,\r\n datepickerDropdownContainer: DATEPICKER_DROPDOWN_CONTAINER_CLASSES,\r\n};\r\n\r\nconst DefaultClassesType = {\r\n fadeIn: \"string\",\r\n fadeOut: \"string\",\r\n fadeInShort: \"string\",\r\n fadeOutShort: \"string\",\r\n modalContainer: \"string\",\r\n datepickerBackdrop: \"string\",\r\n datepickerMain: \"string\",\r\n datepickerHeader: \"string\",\r\n datepickerTitle: \"string\",\r\n datepickerTitleText: \"string\",\r\n datepickerDate: \"string\",\r\n datepickerDateText: \"string\",\r\n datepickerView: \"string\",\r\n datepickerDateControls: \"string\",\r\n datepickerViewChangeButton: \"string\",\r\n datepickerArrowControls: \"string\",\r\n datepickerPreviousButton: \"string\",\r\n datepickerNextButton: \"string\",\r\n datepickerFooter: \"string\",\r\n datepickerFooterBtn: \"string\",\r\n datepickerClearBtn: \"string\",\r\n datepickerDayHeading: \"string\",\r\n datepickerCell: \"string\",\r\n datepickerCellSmall: \"string\",\r\n datepickerCellLarge: \"string\",\r\n datepickerCellContent: \"string\",\r\n datepickerCellContentSmall: \"string\",\r\n datepickerCellContentLarge: \"string\",\r\n datepickerTable: \"string\",\r\n datepickerToggleButton: \"string\",\r\n datepickerDropdownContainer: \"string\",\r\n};\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nClass Definition\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nclass Datepicker {\r\n constructor(element, options, classes) {\r\n this._element = element;\r\n this._input = SelectorEngine.findOne(\"input\", this._element);\r\n this._options = this._getConfig(options);\r\n this._classes = this._getClasses(classes);\r\n this._activeDate = new Date();\r\n this._selectedDate = null;\r\n this._selectedYear = null;\r\n this._selectedMonth = null;\r\n this._headerDate = null;\r\n this._headerYear = null;\r\n this._headerMonth = null;\r\n this._view = this._options.view;\r\n this._popper = null;\r\n this._focusTrap = null;\r\n this._isOpen = false;\r\n this._toggleButtonId = getUID(\"datepicker-toggle-\");\r\n this._animations =\r\n !window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches &&\r\n this._options.animations;\r\n\r\n this._scrollBar = new ScrollBarHelper();\r\n\r\n if (this._element) {\r\n Data.setData(element, DATA_KEY, this);\r\n }\r\n\r\n this._init();\r\n\r\n if (this.toggleButton && this._options.disableToggle) {\r\n this.toggleButton.disabled = \"true\";\r\n }\r\n\r\n if (this._options.disableInput) {\r\n this._input.disabled = \"true\";\r\n }\r\n }\r\n\r\n // Getters\r\n\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n get container() {\r\n return (\r\n SelectorEngine.findOne(\r\n `[${MODAL_CONTAINER_NAME}='${this._toggleButtonId}']`\r\n ) ||\r\n SelectorEngine.findOne(\r\n `[${DROPDOWN_CONTAINER_NAME}='${this._toggleButtonId}']`\r\n )\r\n );\r\n }\r\n\r\n get options() {\r\n return this._options;\r\n }\r\n\r\n get activeCell() {\r\n let activeCell;\r\n\r\n if (this._view === \"days\") {\r\n activeCell = this._getActiveDayCell();\r\n }\r\n\r\n if (this._view === \"months\") {\r\n activeCell = this._getActiveMonthCell();\r\n }\r\n\r\n if (this._view === \"years\") {\r\n activeCell = this._getActiveYearCell();\r\n }\r\n\r\n return activeCell;\r\n }\r\n\r\n get activeDay() {\r\n return getDate(this._activeDate);\r\n }\r\n\r\n get activeMonth() {\r\n return getMonth(this._activeDate);\r\n }\r\n\r\n get activeYear() {\r\n return getYear(this._activeDate);\r\n }\r\n\r\n get firstYearInView() {\r\n return this.activeYear - getYearsOffset(this._activeDate, YEARS_IN_VIEW);\r\n }\r\n\r\n get lastYearInView() {\r\n return this.firstYearInView + YEARS_IN_VIEW - 1;\r\n }\r\n\r\n get viewChangeButton() {\r\n return SelectorEngine.findOne(VIEW_CHANGE_BUTTON_SELECTOR, this.container);\r\n }\r\n\r\n get previousButton() {\r\n return SelectorEngine.findOne(PREVIOUS_BUTTON_SELECTOR, this.container);\r\n }\r\n\r\n get nextButton() {\r\n return SelectorEngine.findOne(NEXT_BUTTON_SELECTOR, this.container);\r\n }\r\n\r\n get okButton() {\r\n return SelectorEngine.findOne(OK_BUTTON_SELECTOR, this.container);\r\n }\r\n\r\n get cancelButton() {\r\n return SelectorEngine.findOne(CANCEL_BUTTON_SELECTOR, this.container);\r\n }\r\n\r\n get clearButton() {\r\n return SelectorEngine.findOne(CLEAR_BUTTON_SELECTOR, this.container);\r\n }\r\n\r\n get datesContainer() {\r\n return SelectorEngine.findOne(VIEW_SELECTOR, this.container);\r\n }\r\n\r\n get toggleButton() {\r\n return SelectorEngine.findOne(TOGGLE_BUTTON_SELECTOR, this._element);\r\n }\r\n\r\n update(options = {}) {\r\n this._options = this._getConfig({ ...this._options, ...options });\r\n }\r\n\r\n _getConfig(config) {\r\n const dataAttributes = Manipulator.getDataAttributes(this._element);\r\n\r\n config = {\r\n ...Default,\r\n ...dataAttributes,\r\n ...config,\r\n };\r\n\r\n typeCheckConfig(NAME, config, DefaultType);\r\n\r\n if (config.max && typeof config.max === \"string\") {\r\n config.max = new Date(config.max);\r\n }\r\n\r\n if (config.min && typeof config.min === \"string\") {\r\n config.min = new Date(config.min);\r\n }\r\n\r\n if (config.startDay && config.startDay !== 0) {\r\n const sortedWeekdaysNarrow = this._getNewDaysOrderArray(config);\r\n config.weekdaysNarrow = sortedWeekdaysNarrow;\r\n }\r\n\r\n return config;\r\n }\r\n\r\n _getClasses(classes) {\r\n const dataAttributes = Manipulator.getDataClassAttributes(this._element);\r\n\r\n classes = {\r\n ...DefaultClasses,\r\n ...dataAttributes,\r\n ...classes,\r\n };\r\n\r\n typeCheckConfig(NAME, classes, DefaultClassesType);\r\n\r\n return classes;\r\n }\r\n\r\n _getContainer() {\r\n return SelectorEngine.findOne(this._options.container);\r\n }\r\n\r\n _getNewDaysOrderArray(config) {\r\n const index = config.startDay;\r\n\r\n const weekdaysNarrow = config.weekdaysNarrow;\r\n const sortedWeekdays = weekdaysNarrow\r\n .slice(index)\r\n .concat(weekdaysNarrow.slice(0, index));\r\n\r\n return sortedWeekdays;\r\n }\r\n\r\n _init() {\r\n if (!this.toggleButton && this._options.toggleButton) {\r\n this._appendToggleButton();\r\n if (this._input.readOnly || this._input.disabled) {\r\n this.toggleButton.style.pointerEvents = \"none\";\r\n }\r\n }\r\n\r\n this._listenToUserInput();\r\n this._listenToToggleClick();\r\n this._listenToToggleKeydown();\r\n }\r\n\r\n _appendToggleButton() {\r\n const toggleButton = getToggleButtonTemplate(\r\n this._toggleButtonId,\r\n this._classes.datepickerToggleButton\r\n );\r\n this._element.insertAdjacentHTML(\"beforeend\", toggleButton);\r\n }\r\n\r\n open() {\r\n if (this._input.readOnly || this._input.disabled) {\r\n return;\r\n }\r\n const openEvent = EventHandler.trigger(this._element, EVENT_OPEN);\r\n\r\n if (this._isOpen || openEvent.defaultPrevented) {\r\n return;\r\n }\r\n\r\n this._setInitialDate();\r\n\r\n const backdrop = getBackdropTemplate(this._classes.datepickerBackdrop);\r\n const template = getDatepickerTemplate(\r\n this._activeDate,\r\n this._selectedDate,\r\n this._selectedYear,\r\n this._selectedMonth,\r\n this._options,\r\n MONTHS_IN_ROW,\r\n YEARS_IN_VIEW,\r\n YEARS_IN_ROW,\r\n this._toggleButtonId,\r\n this._classes\r\n );\r\n\r\n if (this._options.inline) {\r\n this._openDropdown(template);\r\n } else {\r\n this._openModal(backdrop, template);\r\n this._scrollBar.hide();\r\n }\r\n\r\n if (this._animations) {\r\n Manipulator.addClass(this.container, this._classes.fadeIn);\r\n Manipulator.addClass(backdrop, this._classes.fadeInShort);\r\n }\r\n\r\n this._setFocusTrap(this.container);\r\n\r\n this._listenToDateSelection();\r\n this._addControlsListeners();\r\n this._updateControlsDisabledState();\r\n this._listenToEscapeClick();\r\n this._listenToKeyboardNavigation();\r\n this._listenToDatesContainerFocus();\r\n this._listenToDatesContainerBlur();\r\n\r\n // We need to wait for popper initialization to avoid bug with\r\n // focusing dates container, otherwise dates container will be\r\n // focused before popper position update which can change the\r\n // scroll position on the page\r\n this._asyncFocusDatesContainer();\r\n this._updateViewControlsAndAttributes(this._view);\r\n this._isOpen = true;\r\n\r\n // Wait for the component to open to prevent immediate calling of the\r\n // close method upon detecting a click on toggle element (input/button)\r\n setTimeout(() => {\r\n this._listenToOutsideClick();\r\n }, 0);\r\n }\r\n\r\n _openDropdown(template) {\r\n this._popper = createPopper(this._input, template, {\r\n placement: \"bottom-start\",\r\n });\r\n const container = this._getContainer();\r\n container.appendChild(template);\r\n }\r\n\r\n _openModal(backdrop, template) {\r\n const container = this._getContainer();\r\n container.appendChild(backdrop);\r\n container.appendChild(template);\r\n }\r\n\r\n _setFocusTrap(element) {\r\n this._focusTrap = new FocusTrap(element, {\r\n event: \"keydown\",\r\n condition: (event) => event.key === \"Tab\",\r\n });\r\n this._focusTrap.trap();\r\n }\r\n\r\n _listenToUserInput() {\r\n EventHandler.on(this._input, \"input\", (event) => {\r\n this._handleUserInput(event.target.value);\r\n });\r\n }\r\n\r\n _listenToToggleClick() {\r\n EventHandler.on(\r\n this._element,\r\n EVENT_CLICK_DATA_API,\r\n DATEPICKER_TOGGLE_SELECTOR,\r\n (event) => {\r\n event.preventDefault();\r\n this.open();\r\n }\r\n );\r\n }\r\n\r\n _listenToToggleKeydown() {\r\n EventHandler.on(\r\n this._element,\r\n \"keydown\",\r\n DATEPICKER_TOGGLE_SELECTOR,\r\n (event) => {\r\n if (event.keyCode === ENTER && !this._isOpen) {\r\n this.open();\r\n }\r\n }\r\n );\r\n }\r\n\r\n _listenToDateSelection() {\r\n EventHandler.on(this.datesContainer, \"click\", (e) => {\r\n this._handleDateSelection(e);\r\n });\r\n }\r\n\r\n _handleDateSelection(e) {\r\n const dataset =\r\n e.target.nodeName === \"DIV\"\r\n ? e.target.parentNode.dataset\r\n : e.target.dataset;\r\n const cell = e.target.nodeName === \"DIV\" ? e.target.parentNode : e.target;\r\n\r\n if (dataset.teDate) {\r\n this._pickDay(dataset.teDate, cell);\r\n }\r\n\r\n if (dataset.teMonth && dataset.teYear) {\r\n const month = parseInt(dataset.teMonth, 10);\r\n const year = parseInt(dataset.teYear, 10);\r\n this._pickMonth(month, year);\r\n }\r\n\r\n if (dataset.teYear && !dataset.teMonth) {\r\n const year = parseInt(dataset.teYear, 10);\r\n this._pickYear(year);\r\n }\r\n\r\n if (!this._options.inline) {\r\n this._updateHeaderDate(\r\n this._activeDate,\r\n this._options.monthsShort,\r\n this._options.weekdaysShort\r\n );\r\n }\r\n }\r\n\r\n _updateHeaderDate(date, monthNames, dayNames) {\r\n const headerDateEl = SelectorEngine.findOne(\r\n DATE_TEXT_SELECTOR,\r\n this.container\r\n );\r\n const month = getMonth(date);\r\n const day = getDate(date);\r\n const dayNumber = getDayNumber(date);\r\n headerDateEl.innerHTML = `${dayNames[dayNumber]}, ${monthNames[month]} ${day}`;\r\n }\r\n\r\n _addControlsListeners() {\r\n EventHandler.on(this.nextButton, \"click\", () => {\r\n if (this._view === \"days\") {\r\n this.nextMonth();\r\n } else if (this._view === \"years\") {\r\n this.nextYears();\r\n } else {\r\n this.nextYear();\r\n }\r\n this._updateControlsDisabledState();\r\n });\r\n\r\n EventHandler.on(this.previousButton, \"click\", () => {\r\n if (this._view === \"days\") {\r\n this.previousMonth();\r\n } else if (this._view === \"years\") {\r\n this.previousYears();\r\n } else {\r\n this.previousYear();\r\n }\r\n this._updateControlsDisabledState();\r\n });\r\n\r\n EventHandler.on(this.viewChangeButton, \"click\", () => {\r\n if (this._view === \"days\") {\r\n this._changeView(\"years\");\r\n } else if (this._view === \"years\" || this._view === \"months\") {\r\n this._changeView(\"days\");\r\n }\r\n });\r\n\r\n if (!this._options.inline) {\r\n this._listenToFooterButtonsClick();\r\n }\r\n }\r\n\r\n _listenToFooterButtonsClick() {\r\n EventHandler.on(this.okButton, \"click\", () => this.handleOk());\r\n EventHandler.on(this.cancelButton, \"click\", () => this.handleCancel());\r\n EventHandler.on(this.clearButton, \"click\", () => this.handleClear());\r\n }\r\n\r\n _listenToOutsideClick() {\r\n EventHandler.on(document, EVENT_CLICK_DATA_API, (e) => {\r\n const isContainer = e.target === this.container;\r\n const isContainerContent =\r\n this.container && this.container.contains(e.target);\r\n\r\n if (!isContainer && !isContainerContent) {\r\n this.close();\r\n }\r\n });\r\n }\r\n\r\n _listenToEscapeClick() {\r\n EventHandler.on(document, \"keydown\", (event) => {\r\n if (event.keyCode === ESCAPE && this._isOpen) {\r\n this.close();\r\n }\r\n });\r\n }\r\n\r\n _listenToKeyboardNavigation() {\r\n EventHandler.on(this.datesContainer, \"keydown\", (event) => {\r\n this._handleKeydown(event);\r\n });\r\n }\r\n\r\n _listenToDatesContainerFocus() {\r\n EventHandler.on(this.datesContainer, \"focus\", () => {\r\n this._focusActiveCell(this.activeCell);\r\n });\r\n }\r\n\r\n _listenToDatesContainerBlur() {\r\n EventHandler.on(this.datesContainer, \"blur\", () => {\r\n this._removeCurrentFocusStyles();\r\n });\r\n }\r\n\r\n _handleKeydown(event) {\r\n if (this._view === \"days\") {\r\n this._handleDaysViewKeydown(event);\r\n }\r\n\r\n if (this._view === \"months\") {\r\n this._handleMonthsViewKeydown(event);\r\n }\r\n\r\n if (this._view === \"years\") {\r\n this._handleYearsViewKeydown(event);\r\n }\r\n }\r\n\r\n _handleDaysViewKeydown(event) {\r\n const oldActiveDate = this._activeDate;\r\n const previousActiveCell = this.activeCell;\r\n\r\n switch (event.keyCode) {\r\n case LEFT_ARROW:\r\n this._activeDate = addDays(this._activeDate, isRTL() ? 1 : -1);\r\n break;\r\n case RIGHT_ARROW:\r\n this._activeDate = addDays(this._activeDate, isRTL() ? -1 : 1);\r\n break;\r\n case UP_ARROW:\r\n this._activeDate = addDays(this._activeDate, -7);\r\n break;\r\n case DOWN_ARROW:\r\n this._activeDate = addDays(this._activeDate, 7);\r\n break;\r\n case HOME:\r\n this._activeDate = addDays(\r\n this._activeDate,\r\n 1 - getDate(this._activeDate)\r\n );\r\n break;\r\n case END:\r\n this._activeDate = addDays(\r\n this._activeDate,\r\n getDaysInMonth(this._activeDate) - getDate(this._activeDate)\r\n );\r\n break;\r\n case PAGE_UP:\r\n this._activeDate = addMonths(this._activeDate, -1);\r\n break;\r\n case PAGE_DOWN:\r\n this._activeDate = addMonths(this._activeDate, 1);\r\n break;\r\n case ENTER:\r\n case SPACE:\r\n this._selectDate(this._activeDate);\r\n this._handleDateSelection(event);\r\n event.preventDefault();\r\n return;\r\n default:\r\n return;\r\n }\r\n\r\n if (\r\n !areDatesInSameView(\r\n oldActiveDate,\r\n this._activeDate,\r\n this._view,\r\n YEARS_IN_VIEW,\r\n this._options.min,\r\n this._options.max\r\n )\r\n ) {\r\n this._changeView(\"days\");\r\n }\r\n\r\n this._removeHighlightFromCell(previousActiveCell);\r\n this._focusActiveCell(this.activeCell);\r\n event.preventDefault();\r\n }\r\n\r\n _asyncFocusDatesContainer() {\r\n setTimeout(() => {\r\n this.datesContainer.focus();\r\n }, 0);\r\n }\r\n\r\n _focusActiveCell(cell) {\r\n if (cell) {\r\n cell.setAttribute(\"data-te-datepicker-cell-focused\", \"\");\r\n }\r\n }\r\n\r\n _removeHighlightFromCell(cell) {\r\n if (cell) {\r\n cell.removeAttribute(\"data-te-datepicker-cell-focused\");\r\n }\r\n }\r\n\r\n _getActiveDayCell() {\r\n const cells = SelectorEngine.find(\"td\", this.datesContainer);\r\n\r\n const activeCell = Array.from(cells).find((cell) => {\r\n const cellDate = convertStringToDate(cell.dataset.teDate);\r\n return isSameDate(cellDate, this._activeDate);\r\n });\r\n\r\n return activeCell;\r\n }\r\n\r\n _handleMonthsViewKeydown(event) {\r\n const oldActiveDate = this._activeDate;\r\n const previousActiveCell = this.activeCell;\r\n\r\n switch (event.keyCode) {\r\n case LEFT_ARROW:\r\n this._activeDate = addMonths(this._activeDate, isRTL() ? 1 : -1);\r\n break;\r\n case RIGHT_ARROW:\r\n this._activeDate = addMonths(this._activeDate, isRTL() ? -1 : 1);\r\n break;\r\n case UP_ARROW:\r\n this._activeDate = addMonths(this._activeDate, -4);\r\n break;\r\n case DOWN_ARROW:\r\n this._activeDate = addMonths(this._activeDate, 4);\r\n break;\r\n case HOME:\r\n this._activeDate = addMonths(this._activeDate, -this.activeMonth);\r\n break;\r\n case END:\r\n this._activeDate = addMonths(this._activeDate, 11 - this.activeMonth);\r\n break;\r\n case PAGE_UP:\r\n this._activeDate = addYears(this._activeDate, -1);\r\n break;\r\n case PAGE_DOWN:\r\n this._activeDate = addYears(this._activeDate, 1);\r\n break;\r\n case ENTER:\r\n case SPACE:\r\n this._selectMonth(this.activeMonth);\r\n return;\r\n default:\r\n return;\r\n }\r\n\r\n if (\r\n !areDatesInSameView(\r\n oldActiveDate,\r\n this._activeDate,\r\n this._view,\r\n YEARS_IN_VIEW,\r\n this._options.min,\r\n this._options.max\r\n )\r\n ) {\r\n this._changeView(\"months\");\r\n }\r\n\r\n this._removeHighlightFromCell(previousActiveCell);\r\n this._focusActiveCell(this.activeCell);\r\n event.preventDefault();\r\n }\r\n\r\n _getActiveMonthCell() {\r\n const cells = SelectorEngine.find(\"td\", this.datesContainer);\r\n\r\n const activeCell = Array.from(cells).find((cell) => {\r\n const cellYear = parseInt(cell.dataset.teYear, 10);\r\n const cellMonth = parseInt(cell.dataset.teMonth, 10);\r\n return cellYear === this.activeYear && cellMonth === this.activeMonth;\r\n });\r\n\r\n return activeCell;\r\n }\r\n\r\n _handleYearsViewKeydown(event) {\r\n const oldActiveDate = this._activeDate;\r\n const previousActiveCell = this.activeCell;\r\n const yearsPerRow = 4;\r\n const yearsPerPage = 24;\r\n\r\n switch (event.keyCode) {\r\n case LEFT_ARROW:\r\n this._activeDate = addYears(this._activeDate, isRTL() ? 1 : -1);\r\n break;\r\n case RIGHT_ARROW:\r\n this._activeDate = addYears(this._activeDate, isRTL() ? -1 : 1);\r\n break;\r\n case UP_ARROW:\r\n this._activeDate = addYears(this._activeDate, -yearsPerRow);\r\n break;\r\n case DOWN_ARROW:\r\n this._activeDate = addYears(this._activeDate, yearsPerRow);\r\n break;\r\n case HOME:\r\n this._activeDate = addYears(\r\n this._activeDate,\r\n -getYearsOffset(this._activeDate, yearsPerPage)\r\n );\r\n break;\r\n case END:\r\n this._activeDate = addYears(\r\n this._activeDate,\r\n yearsPerPage - getYearsOffset(this._activeDate, yearsPerPage) - 1\r\n );\r\n break;\r\n case PAGE_UP:\r\n this._activeDate = addYears(this._activeDate, -yearsPerPage);\r\n break;\r\n case PAGE_DOWN:\r\n this._activeDate = addYears(this._activeDate, yearsPerPage);\r\n break;\r\n case ENTER:\r\n case SPACE:\r\n this._selectYear(this.activeYear);\r\n return;\r\n default:\r\n return;\r\n }\r\n\r\n if (\r\n !areDatesInSameView(\r\n oldActiveDate,\r\n this._activeDate,\r\n this._view,\r\n YEARS_IN_VIEW,\r\n this._options.min,\r\n this._options.max\r\n )\r\n ) {\r\n this._changeView(\"years\");\r\n }\r\n\r\n this._removeHighlightFromCell(previousActiveCell);\r\n this._focusActiveCell(this.activeCell);\r\n event.preventDefault();\r\n }\r\n\r\n _getActiveYearCell() {\r\n const cells = SelectorEngine.find(\"td\", this.datesContainer);\r\n\r\n const activeCell = Array.from(cells).find((cell) => {\r\n const cellYear = parseInt(cell.dataset.teYear, 10);\r\n return cellYear === this.activeYear;\r\n });\r\n\r\n return activeCell;\r\n }\r\n\r\n _setInitialDate() {\r\n if (this._input.value) {\r\n this._handleUserInput(this._input.value);\r\n } else if (this._options.startDate) {\r\n this._activeDate = new Date(this._options.startDate);\r\n } else {\r\n this._activeDate = new Date();\r\n }\r\n }\r\n\r\n close() {\r\n const closeEvent = EventHandler.trigger(this._element, EVENT_CLOSE);\r\n\r\n if (!this._isOpen || closeEvent.defaultPrevented) {\r\n return;\r\n }\r\n\r\n this._removeDatepickerListeners();\r\n\r\n if (this._animations) {\r\n Manipulator.addClass(this.container, this._classes.fadeOut);\r\n }\r\n\r\n if (this._options.inline) {\r\n this._closeDropdown();\r\n } else {\r\n this._closeModal();\r\n }\r\n\r\n this._isOpen = false;\r\n this._view = this._options.view;\r\n\r\n if (this.toggleButton) {\r\n this.toggleButton.focus();\r\n } else {\r\n this._input.focus();\r\n }\r\n }\r\n\r\n _closeDropdown() {\r\n const datepicker = SelectorEngine.findOne(DROPDOWN_CONTAINER_SELECTOR);\r\n const container = this._getContainer();\r\n if (window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches) {\r\n if (datepicker) {\r\n container.removeChild(datepicker);\r\n }\r\n\r\n if (this._popper) {\r\n this._popper.destroy();\r\n }\r\n }\r\n datepicker.addEventListener(\"animationend\", () => {\r\n if (datepicker) {\r\n container.removeChild(datepicker);\r\n }\r\n\r\n if (this._popper) {\r\n this._popper.destroy();\r\n }\r\n });\r\n this._removeFocusTrap();\r\n }\r\n\r\n _closeModal() {\r\n const backdrop = SelectorEngine.findOne(BACKDROP_SELECTOR);\r\n const datepicker = SelectorEngine.findOne(MODAL_CONTAINER_SELECTOR);\r\n\r\n if (!datepicker || !backdrop) {\r\n return;\r\n }\r\n\r\n if (this._animations) {\r\n Manipulator.addClass(backdrop, this._classes.fadeOutShort);\r\n\r\n backdrop.addEventListener(\"animationend\", () => {\r\n this._removePicker(backdrop, datepicker);\r\n this._scrollBar.reset();\r\n });\r\n } else {\r\n this._removePicker(backdrop, datepicker);\r\n this._scrollBar.reset();\r\n }\r\n }\r\n\r\n _removePicker(backdrop, datepicker) {\r\n const container = this._getContainer();\r\n\r\n container.removeChild(backdrop);\r\n container.removeChild(datepicker);\r\n }\r\n\r\n _removeFocusTrap() {\r\n if (this._focusTrap) {\r\n this._focusTrap.disable();\r\n this._focusTrap = null;\r\n }\r\n }\r\n\r\n _removeDatepickerListeners() {\r\n EventHandler.off(this.nextButton, \"click\");\r\n EventHandler.off(this.previousButton, \"click\");\r\n EventHandler.off(this.viewChangeButton, \"click\");\r\n EventHandler.off(this.okButton, \"click\");\r\n EventHandler.off(this.cancelButton, \"click\");\r\n EventHandler.off(this.clearButton, \"click\");\r\n\r\n EventHandler.off(this.datesContainer, \"click\");\r\n EventHandler.off(this.datesContainer, \"keydown\");\r\n EventHandler.off(this.datesContainer, \"focus\");\r\n EventHandler.off(this.datesContainer, \"blur\");\r\n\r\n EventHandler.off(document, EVENT_CLICK_DATA_API);\r\n }\r\n\r\n dispose() {\r\n if (this._isOpen) {\r\n this.close();\r\n }\r\n\r\n this._removeInputAndToggleListeners();\r\n\r\n const generatedToggleButton = SelectorEngine.findOne(\r\n `#${this._toggleButtonId}`\r\n );\r\n\r\n if (generatedToggleButton) {\r\n this._element.removeChild(generatedToggleButton);\r\n }\r\n\r\n Data.removeData(this._element, DATA_KEY);\r\n\r\n this._element = null;\r\n this._input = null;\r\n this._options = null;\r\n this._activeDate = null;\r\n this._selectedDate = null;\r\n this._selectedYear = null;\r\n this._selectedMonth = null;\r\n this._headerDate = null;\r\n this._headerYear = null;\r\n this._headerMonth = null;\r\n this._view = null;\r\n this._popper = null;\r\n this._focusTrap = null;\r\n }\r\n\r\n _removeInputAndToggleListeners() {\r\n EventHandler.off(this._input, \"input\");\r\n EventHandler.off(\r\n this._element,\r\n EVENT_CLICK_DATA_API,\r\n DATEPICKER_TOGGLE_SELECTOR\r\n );\r\n EventHandler.off(this._element, \"keydown\", DATEPICKER_TOGGLE_SELECTOR);\r\n }\r\n\r\n handleOk() {\r\n this._confirmSelection(this._headerDate);\r\n this.close();\r\n }\r\n\r\n _selectDate(date, cell = this.activeCell) {\r\n const { min, max, filter, disablePast, disableFuture } = this._options;\r\n\r\n if (isDateDisabled(date, min, max, filter, disablePast, disableFuture)) {\r\n return;\r\n }\r\n\r\n this._removeCurrentSelectionStyles();\r\n this._removeCurrentFocusStyles();\r\n this._addSelectedStyles(cell);\r\n this._selectedDate = date;\r\n this._selectedYear = getYear(date);\r\n this._selectedMonth = getMonth(date);\r\n this._headerDate = date;\r\n\r\n if (this._options.inline || this.options.confirmDateOnSelect) {\r\n this._confirmSelection(date);\r\n this.close();\r\n }\r\n }\r\n\r\n _selectYear(year, cell = this.activeCell) {\r\n this._removeCurrentSelectionStyles();\r\n this._removeCurrentFocusStyles();\r\n this._addSelectedStyles(cell);\r\n this._headerYear = year;\r\n\r\n this._asyncChangeView(\"months\");\r\n }\r\n\r\n _selectMonth(month, cell = this.activeCell) {\r\n this._removeCurrentSelectionStyles();\r\n this._removeCurrentFocusStyles();\r\n this._addSelectedStyles(cell);\r\n this._headerMonth = month;\r\n\r\n this._asyncChangeView(\"days\");\r\n }\r\n\r\n _removeSelectedStyles(cell) {\r\n if (cell) {\r\n cell.removeAttribute(\"data-te-datepicker-cell-selected\");\r\n }\r\n }\r\n\r\n _addSelectedStyles(cell) {\r\n if (cell) {\r\n cell.setAttribute(\"data-te-datepicker-cell-selected\", \"\");\r\n }\r\n }\r\n\r\n _confirmSelection(date) {\r\n if (date) {\r\n const dateString = this.formatDate(date);\r\n this._input.value = dateString;\r\n EventHandler.trigger(this._element, EVENT_DATE_CHANGE, { date });\r\n EventHandler.trigger(this._input, \"input\");\r\n }\r\n }\r\n\r\n handleCancel() {\r\n this._selectedDate = null;\r\n this._selectedYear = null;\r\n this._selectedMonth = null;\r\n this.close();\r\n }\r\n\r\n handleClear() {\r\n this._selectedDate = null;\r\n this._selectedMonth = null;\r\n this._selectedYear = null;\r\n this._headerDate = null;\r\n this._headerMonth = null;\r\n this._headerYear = null;\r\n this._removeCurrentSelectionStyles();\r\n this._input.value = \"\";\r\n this._setInitialDate();\r\n this._changeView(\"days\");\r\n this._updateHeaderDate(\r\n this._activeDate,\r\n this._options.monthsShort,\r\n this._options.weekdaysShort\r\n );\r\n }\r\n\r\n _removeCurrentSelectionStyles() {\r\n const currentSelected = SelectorEngine.findOne(\r\n \"[data-te-datepicker-cell-selected]\",\r\n this.container\r\n );\r\n\r\n if (currentSelected) {\r\n currentSelected.removeAttribute(\"data-te-datepicker-cell-selected\");\r\n }\r\n }\r\n\r\n _removeCurrentFocusStyles() {\r\n const currentFocused = SelectorEngine.findOne(\r\n \"[data-te-datepicker-cell-focused]\",\r\n this.container\r\n );\r\n\r\n if (currentFocused) {\r\n currentFocused.removeAttribute(\"data-te-datepicker-cell-focused\");\r\n }\r\n }\r\n\r\n formatDate(date) {\r\n const d = getDate(date);\r\n const dd = this._addLeadingZero(getDate(date));\r\n const ddd = this._options.weekdaysShort[getDayNumber(date)];\r\n const dddd = this._options.weekdaysFull[getDayNumber(date)];\r\n const m = getMonth(date) + 1;\r\n const mm = this._addLeadingZero(getMonth(date) + 1);\r\n const mmm = this._options.monthsShort[getMonth(date)];\r\n const mmmm = this._options.monthsFull[getMonth(date)];\r\n const yy =\r\n getYear(date).toString().length === 2\r\n ? getYear(date)\r\n : getYear(date).toString().slice(2, 4);\r\n const yyyy = getYear(date);\r\n\r\n const preformatted = this._options.format.split(\r\n /(d{1,4}|m{1,4}|y{4}|yy|!.)/g\r\n );\r\n let formatted = \"\";\r\n preformatted.forEach((datePart) => {\r\n switch (datePart) {\r\n case \"dddd\":\r\n datePart = datePart.replace(datePart, dddd);\r\n break;\r\n case \"ddd\":\r\n datePart = datePart.replace(datePart, ddd);\r\n break;\r\n case \"dd\":\r\n datePart = datePart.replace(datePart, dd);\r\n break;\r\n case \"d\":\r\n datePart = datePart.replace(datePart, d);\r\n break;\r\n case \"mmmm\":\r\n datePart = datePart.replace(datePart, mmmm);\r\n break;\r\n case \"mmm\":\r\n datePart = datePart.replace(datePart, mmm);\r\n break;\r\n case \"mm\":\r\n datePart = datePart.replace(datePart, mm);\r\n break;\r\n case \"m\":\r\n datePart = datePart.replace(datePart, m);\r\n break;\r\n case \"yyyy\":\r\n datePart = datePart.replace(datePart, yyyy);\r\n break;\r\n case \"yy\":\r\n datePart = datePart.replace(datePart, yy);\r\n break;\r\n default:\r\n }\r\n formatted += datePart;\r\n });\r\n\r\n return formatted;\r\n }\r\n\r\n _addLeadingZero(value) {\r\n return parseInt(value, 10) < 10 ? `0${value}` : value;\r\n }\r\n\r\n _pickDay(day, el) {\r\n const date = convertStringToDate(day);\r\n const { min, max, filter, disablePast, disableFuture } = this._options;\r\n\r\n if (isDateDisabled(date, min, max, filter, disablePast, disableFuture)) {\r\n return;\r\n }\r\n\r\n this._activeDate = date;\r\n this._selectDate(date, el);\r\n }\r\n\r\n _pickYear(year) {\r\n const { min, max, disablePast, disableFuture } = this._options;\r\n\r\n if (isYearDisabled(year, min, max, disablePast, disableFuture)) {\r\n return;\r\n }\r\n\r\n const newDate = createDate(year, this.activeMonth, this.activeDay);\r\n\r\n this._activeDate = newDate;\r\n this._selectedDate = newDate;\r\n this._selectYear(year);\r\n }\r\n\r\n _pickMonth(month, year) {\r\n const { min, max, disablePast, disableFuture } = this._options;\r\n\r\n if (\r\n isMonthDisabled(month, year, min, max, disablePast, disableFuture) ||\r\n isYearDisabled(year, min, max, disablePast, disableFuture)\r\n ) {\r\n return;\r\n }\r\n\r\n const newDate = createDate(year, month, this.activeDay);\r\n\r\n this._activeDate = newDate;\r\n this._selectMonth(month);\r\n }\r\n\r\n nextMonth() {\r\n const nextMonth = addMonths(this._activeDate, 1);\r\n const template = createDayViewTemplate(\r\n nextMonth,\r\n this._headerDate,\r\n this._options,\r\n this._classes\r\n );\r\n this._activeDate = nextMonth;\r\n this.viewChangeButton.textContent = `${\r\n this._options.monthsFull[this.activeMonth]\r\n } ${this.activeYear}`;\r\n this.viewChangeButton.innerHTML += createViewChangeButtonIcon(\r\n this._options,\r\n this._classes\r\n );\r\n this.datesContainer.innerHTML = template;\r\n }\r\n\r\n previousMonth() {\r\n const previousMonth = addMonths(this._activeDate, -1);\r\n this._activeDate = previousMonth;\r\n const template = createDayViewTemplate(\r\n previousMonth,\r\n this._headerDate,\r\n this._options,\r\n this._classes\r\n );\r\n this.viewChangeButton.textContent = `${\r\n this._options.monthsFull[this.activeMonth]\r\n } ${this.activeYear}`;\r\n this.viewChangeButton.innerHTML += createViewChangeButtonIcon(\r\n this._options,\r\n this._classes\r\n );\r\n this.datesContainer.innerHTML = template;\r\n }\r\n\r\n nextYear() {\r\n const nextYear = addYears(this._activeDate, 1);\r\n this._activeDate = nextYear;\r\n this.viewChangeButton.textContent = `${this.activeYear}`;\r\n this.viewChangeButton.innerHTML += createViewChangeButtonIcon(\r\n this._options,\r\n this._classes\r\n );\r\n const template = createMonthViewTemplate(\r\n this.activeYear,\r\n this._selectedYear,\r\n this._selectedMonth,\r\n this._options,\r\n MONTHS_IN_ROW,\r\n this._classes\r\n );\r\n this.datesContainer.innerHTML = template;\r\n }\r\n\r\n previousYear() {\r\n const previousYear = addYears(this._activeDate, -1);\r\n this._activeDate = previousYear;\r\n this.viewChangeButton.textContent = `${this.activeYear}`;\r\n this.viewChangeButton.innerHTML += createViewChangeButtonIcon(\r\n this._options,\r\n this._classes\r\n );\r\n const template = createMonthViewTemplate(\r\n this.activeYear,\r\n this._selectedYear,\r\n this._selectedMonth,\r\n this._options,\r\n MONTHS_IN_ROW,\r\n this._classes\r\n );\r\n this.datesContainer.innerHTML = template;\r\n }\r\n\r\n nextYears() {\r\n const nextYear = addYears(this._activeDate, 24);\r\n this._activeDate = nextYear;\r\n const template = createYearViewTemplate(\r\n nextYear,\r\n this._selectedYear,\r\n this._options,\r\n YEARS_IN_VIEW,\r\n YEARS_IN_ROW,\r\n this._classes\r\n );\r\n this.viewChangeButton.textContent = `${this.firstYearInView} - ${this.lastYearInView}`;\r\n this.viewChangeButton.innerHTML += createViewChangeButtonIcon(\r\n this._options,\r\n this._classes\r\n );\r\n this.datesContainer.innerHTML = template;\r\n }\r\n\r\n previousYears() {\r\n const previousYear = addYears(this._activeDate, -24);\r\n this._activeDate = previousYear;\r\n const template = createYearViewTemplate(\r\n previousYear,\r\n this._selectedYear,\r\n this._options,\r\n YEARS_IN_VIEW,\r\n YEARS_IN_ROW,\r\n this._classes\r\n );\r\n this.viewChangeButton.textContent = `${this.firstYearInView} - ${this.lastYearInView}`;\r\n this.viewChangeButton.innerHTML += createViewChangeButtonIcon(\r\n this._options,\r\n this._classes\r\n );\r\n this.datesContainer.innerHTML = template;\r\n }\r\n\r\n _asyncChangeView(view) {\r\n setTimeout(() => {\r\n this._changeView(view);\r\n }, 0);\r\n }\r\n\r\n _changeView(view) {\r\n this._view = view;\r\n // We need to add blur event here to reapply focus to\r\n // dates container when switching from years to months\r\n // view after selecting year\r\n this.datesContainer.blur();\r\n\r\n if (view === \"days\") {\r\n this.datesContainer.innerHTML = createDayViewTemplate(\r\n this._activeDate,\r\n this._headerDate,\r\n this._options,\r\n this._classes\r\n );\r\n }\r\n\r\n if (view === \"months\") {\r\n this.datesContainer.innerHTML = createMonthViewTemplate(\r\n this.activeYear,\r\n this._selectedYear,\r\n this._selectedMonth,\r\n this._options,\r\n MONTHS_IN_ROW,\r\n this._classes\r\n );\r\n }\r\n\r\n if (view === \"years\") {\r\n this.datesContainer.innerHTML = createYearViewTemplate(\r\n this._activeDate,\r\n this._selectedYear,\r\n this._options,\r\n YEARS_IN_VIEW,\r\n YEARS_IN_ROW,\r\n this._classes\r\n );\r\n }\r\n\r\n this.datesContainer.focus();\r\n this._updateViewControlsAndAttributes(view);\r\n this._updateControlsDisabledState();\r\n }\r\n\r\n _updateViewControlsAndAttributes(view) {\r\n if (view === \"days\") {\r\n this.viewChangeButton.textContent = `${\r\n this._options.monthsFull[this.activeMonth]\r\n } ${this.activeYear}`;\r\n this.viewChangeButton.innerHTML += createViewChangeButtonIcon(\r\n this._options,\r\n this._classes\r\n );\r\n this.viewChangeButton.setAttribute(\r\n \"aria-label\",\r\n this._options.switchToMultiYearViewLabel\r\n );\r\n this.previousButton.setAttribute(\r\n \"aria-label\",\r\n this._options.prevMonthLabel\r\n );\r\n this.nextButton.setAttribute(\"aria-label\", this._options.nextMonthLabel);\r\n }\r\n\r\n if (view === \"months\") {\r\n this.viewChangeButton.textContent = `${this.activeYear}`;\r\n this.viewChangeButton.innerHTML += createViewChangeButtonIcon(\r\n this._options,\r\n this._classes\r\n );\r\n this.viewChangeButton.setAttribute(\r\n \"aria-label\",\r\n this._options.switchToDayViewLabel\r\n );\r\n this.previousButton.setAttribute(\r\n \"aria-label\",\r\n this._options.prevYearLabel\r\n );\r\n this.nextButton.setAttribute(\"aria-label\", this._options.nextYearLabel);\r\n }\r\n\r\n if (view === \"years\") {\r\n this.viewChangeButton.textContent = `${this.firstYearInView} - ${this.lastYearInView}`;\r\n this.viewChangeButton.innerHTML += createViewChangeButtonIcon(\r\n this._options,\r\n this._classes\r\n );\r\n this.viewChangeButton.setAttribute(\r\n \"aria-label\",\r\n this._options.switchToMonthViewLabel\r\n );\r\n this.previousButton.setAttribute(\r\n \"aria-label\",\r\n this._options.prevMultiYearLabel\r\n );\r\n this.nextButton.setAttribute(\r\n \"aria-label\",\r\n this._options.nextMultiYearLabel\r\n );\r\n }\r\n }\r\n\r\n _updateControlsDisabledState() {\r\n if (\r\n isNextDateDisabled(\r\n this._options.disableFuture,\r\n this._activeDate,\r\n this._view,\r\n YEARS_IN_VIEW,\r\n this._options.min,\r\n this._options.max,\r\n this.lastYearInView,\r\n this.firstYearInView\r\n )\r\n ) {\r\n this.nextButton.disabled = true;\r\n } else {\r\n this.nextButton.disabled = false;\r\n }\r\n\r\n if (\r\n isPreviousDateDisabled(\r\n this._options.disablePast,\r\n this._activeDate,\r\n this._view,\r\n YEARS_IN_VIEW,\r\n this._options.min,\r\n this._options.max,\r\n this.lastYearInView,\r\n this.firstYearInView\r\n )\r\n ) {\r\n this.previousButton.disabled = true;\r\n } else {\r\n this.previousButton.disabled = false;\r\n }\r\n }\r\n\r\n _handleUserInput(input) {\r\n const delimeters = this._getDelimeters(this._options.format);\r\n const date = this._parseDate(input, this._options.format, delimeters);\r\n\r\n if (isValidDate(date)) {\r\n this._activeDate = date;\r\n this._selectedDate = date;\r\n this._selectedYear = getYear(date);\r\n this._selectedMonth = getMonth(date);\r\n this._headerDate = date;\r\n } else {\r\n this._activeDate = new Date();\r\n this._selectedDate = null;\r\n this._selectedMonth = null;\r\n this._selectedYear = null;\r\n this._headerDate = null;\r\n this._headerMonth = null;\r\n this._headerYear = null;\r\n }\r\n }\r\n\r\n _getDelimeters(format) {\r\n return format.match(/[^(dmy)]{1,}/g);\r\n }\r\n\r\n _parseDate(dateString, format, delimeters) {\r\n let delimeterPattern;\r\n\r\n if (delimeters[0] !== delimeters[1]) {\r\n delimeterPattern = delimeters[0] + delimeters[1];\r\n } else {\r\n delimeterPattern = delimeters[0];\r\n }\r\n\r\n const regExp = new RegExp(`[${delimeterPattern}]`);\r\n const dateParts = dateString.split(regExp);\r\n const formatParts = format.split(regExp);\r\n const isMonthString = format.indexOf(\"mmm\") !== -1;\r\n\r\n const datesArray = [];\r\n\r\n for (let i = 0; i < formatParts.length; i++) {\r\n if (formatParts[i].indexOf(\"yy\") !== -1) {\r\n datesArray[0] = { value: dateParts[i], format: formatParts[i] };\r\n }\r\n if (formatParts[i].indexOf(\"m\") !== -1) {\r\n datesArray[1] = { value: dateParts[i], format: formatParts[i] };\r\n }\r\n if (formatParts[i].indexOf(\"d\") !== -1 && formatParts[i].length <= 2) {\r\n datesArray[2] = { value: dateParts[i], format: formatParts[i] };\r\n }\r\n }\r\n\r\n let monthsNames;\r\n\r\n if (format.indexOf(\"mmmm\") !== -1) {\r\n monthsNames = this._options.monthsFull;\r\n } else {\r\n monthsNames = this._options.monthsShort;\r\n }\r\n\r\n const year = Number(datesArray[0].value);\r\n const month = isMonthString\r\n ? this.getMonthNumberByMonthName(datesArray[1].value, monthsNames)\r\n : Number(datesArray[1].value) - 1;\r\n const day = Number(datesArray[2].value);\r\n\r\n const parsedDate = createDate(year, month, day);\r\n return parsedDate;\r\n }\r\n\r\n getMonthNumberByMonthName(monthValue, monthLabels) {\r\n return monthLabels.findIndex((monthLabel) => monthLabel === monthValue);\r\n }\r\n\r\n static getInstance(element) {\r\n return Data.getData(element, DATA_KEY);\r\n }\r\n\r\n static getOrCreateInstance(element, config = {}) {\r\n return (\r\n this.getInstance(element) ||\r\n new this(element, typeof config === \"object\" ? config : null)\r\n );\r\n }\r\n}\r\n\r\nexport default Datepicker;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nexport const getTimepickerTemplate = (\r\n {\r\n format24,\r\n okLabel,\r\n cancelLabel,\r\n headID,\r\n footerID,\r\n bodyID,\r\n pickerID,\r\n clearLabel,\r\n inline,\r\n showClearBtn,\r\n amLabel,\r\n pmLabel,\r\n },\r\n classes\r\n) => {\r\n const normalTemplate = `\r\n
\r\n
\r\n
\r\n
\r\n
\r\n \r\n 21 \r\n \r\n : \r\n \r\n 21 \r\n \r\n
\r\n ${\r\n !format24\r\n ? `
\r\n ${amLabel} \r\n ${pmLabel} \r\n
`\r\n : \"\"\r\n }\r\n
\r\n
\r\n ${\r\n !inline\r\n ? `
\r\n
\r\n
\r\n
\r\n ${\r\n format24\r\n ? '
'\r\n : \"\"\r\n }\r\n
\r\n
`\r\n : \"\"\r\n }\r\n
\r\n \r\n
\r\n
`;\r\n\r\n const inlineTemplate = `\r\n
\r\n
\r\n
\r\n
\r\n
\r\n
\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n 21 \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n
: \r\n
\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n 21 \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n
\r\n ${\r\n !format24\r\n ? `
\r\n ${amLabel} \r\n ${pmLabel} \r\n ${okLabel} \r\n
`\r\n : \"\"\r\n }\r\n ${\r\n format24\r\n ? `
${okLabel} `\r\n : \"\"\r\n }\r\n
\r\n
\r\n
\r\n
\r\n
`;\r\n return inline ? inlineTemplate : normalTemplate;\r\n};\r\n\r\nexport const getToggleButtonTemplate = (options, id, classes) => {\r\n const { iconSVG } = options;\r\n\r\n return `\r\n \r\n ${iconSVG}\r\n \r\n`;\r\n};\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\n/* eslint-disable consistent-return */\r\nimport EventHandler from \"../../dom/event-handler\";\r\nimport Manipulator from \"../../dom/manipulator\";\r\n\r\nconst ATTR_TIMEPICKER_DISABLED = \"data-te-timepicker-disabled\";\r\nconst ATTR_TIMEPICKER_ACTIVE = \"data-te-timepicker-active\";\r\n\r\nconst formatToAmPm = (date) => {\r\n if (date === \"\") return;\r\n let hours;\r\n let minutes;\r\n let amOrPm;\r\n let originalHours;\r\n\r\n if (isValidDate(date)) {\r\n hours = date.getHours();\r\n originalHours = hours;\r\n minutes = date.getMinutes();\r\n hours %= 12;\r\n if (originalHours === 0 && hours === 0) {\r\n amOrPm = \"AM\";\r\n }\r\n\r\n hours = hours || 12;\r\n\r\n if (amOrPm === undefined) {\r\n amOrPm = Number(originalHours) >= 12 ? \"PM\" : \"AM\";\r\n }\r\n\r\n minutes = minutes < 10 ? `0${minutes}` : minutes;\r\n } else {\r\n [hours, minutes, amOrPm] = takeValue(date, false);\r\n originalHours = hours;\r\n\r\n hours %= 12;\r\n if (originalHours === 0 && hours === 0) {\r\n amOrPm = \"AM\";\r\n }\r\n hours = hours || 12;\r\n\r\n if (amOrPm === undefined) {\r\n amOrPm = Number(originalHours) >= 12 ? \"PM\" : \"AM\";\r\n }\r\n }\r\n\r\n return {\r\n hours,\r\n minutes,\r\n amOrPm,\r\n };\r\n};\r\n\r\nconst isValidDate = (date) => {\r\n return (\r\n date &&\r\n Object.prototype.toString.call(date) === \"[object Date]\" &&\r\n !Number.isNaN(date)\r\n );\r\n};\r\n\r\nconst formatNormalHours = (date) => {\r\n if (date === \"\") return;\r\n\r\n let hours;\r\n let minutes;\r\n\r\n if (!isValidDate(date)) {\r\n [hours, minutes] = takeValue(date, false);\r\n } else {\r\n hours = date.getHours();\r\n minutes = date.getMinutes();\r\n }\r\n\r\n minutes = Number(minutes) < 10 ? `0${Number(minutes)}` : minutes;\r\n\r\n return {\r\n hours,\r\n minutes,\r\n };\r\n};\r\n\r\nconst toggleClassHandler = (event, selector, classes) => {\r\n return EventHandler.on(document, event, selector, ({ target }) => {\r\n if (target.hasAttribute(ATTR_TIMEPICKER_ACTIVE)) return;\r\n\r\n const allElements = document.querySelectorAll(selector);\r\n\r\n allElements.forEach((element) => {\r\n if (!element.hasAttribute(ATTR_TIMEPICKER_ACTIVE)) return;\r\n\r\n Manipulator.removeClass(element, classes.opacity);\r\n element.removeAttribute(ATTR_TIMEPICKER_ACTIVE);\r\n });\r\n\r\n Manipulator.addClass(target, classes.opacity);\r\n target.setAttribute(ATTR_TIMEPICKER_ACTIVE, \"\");\r\n });\r\n};\r\n\r\nconst findMousePosition = (\r\n { clientX, clientY, touches },\r\n object,\r\n isMobile = false\r\n) => {\r\n const { left, top } = object.getBoundingClientRect();\r\n let obj = {};\r\n if (!isMobile || !touches) {\r\n obj = {\r\n x: clientX - left,\r\n y: clientY - top,\r\n };\r\n } else if (isMobile && Object.keys(touches).length > 0) {\r\n obj = {\r\n x: touches[0].clientX - left,\r\n y: touches[0].clientY - top,\r\n };\r\n }\r\n\r\n return obj;\r\n};\r\n\r\nconst checkBrowser = () => {\r\n const isBrowserMatched =\r\n (navigator.maxTouchPoints &&\r\n navigator.maxTouchPoints > 2 &&\r\n /MacIntel/.test(navigator.platform)) ||\r\n /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(\r\n navigator.userAgent\r\n );\r\n\r\n return isBrowserMatched;\r\n};\r\n\r\nconst takeValue = (element, isInput = true) => {\r\n if (isInput) return element.value.replace(/:/gi, \" \").split(\" \");\r\n\r\n return element.replace(/:/gi, \" \").split(\" \");\r\n};\r\n\r\nconst compareTimes = (time1, time2) => {\r\n const [time1Hour, time1Minutes, time1maxTimeFormat] = takeValue(time1, false);\r\n const [time2Hour, time2Minutes, time2maxTimeFormat] = takeValue(time2, false);\r\n\r\n const bothFormatsEqual = time1maxTimeFormat === time2maxTimeFormat;\r\n const condition =\r\n (time1maxTimeFormat === \"PM\" && time2maxTimeFormat === \"AM\") ||\r\n (bothFormatsEqual && time1Hour > time2Hour) ||\r\n time1Minutes > time2Minutes;\r\n\r\n return condition;\r\n};\r\n\r\nconst getCurrentTime = () => {\r\n const date = new Date();\r\n const currentHours = date.getHours();\r\n const currentMinutes = date.getMinutes();\r\n\r\n const currentTime = `${currentHours}:${\r\n currentMinutes < 10 ? `0${currentMinutes}` : currentMinutes\r\n }`;\r\n\r\n return currentTime;\r\n};\r\n\r\nconst setMinTime = (minTime, disabledPast, format12) => {\r\n if (!disabledPast) {\r\n return minTime;\r\n }\r\n let currentTime = getCurrentTime();\r\n\r\n if (format12) {\r\n currentTime = `${formatToAmPm(currentTime).hours}:${\r\n formatToAmPm(currentTime).minutes\r\n } ${formatToAmPm(currentTime).amOrPm}`;\r\n }\r\n if (\r\n (minTime !== \"\" && compareTimes(currentTime, minTime)) ||\r\n minTime === \"\"\r\n ) {\r\n minTime = currentTime;\r\n }\r\n return minTime;\r\n};\r\n\r\nconst setMaxTime = (maxTime, disabledFuture, format12) => {\r\n if (!disabledFuture) return maxTime;\r\n\r\n let currentTime = getCurrentTime();\r\n\r\n if (format12) {\r\n currentTime = `${formatToAmPm(currentTime).hours}:${\r\n formatToAmPm(currentTime).minutes\r\n } ${formatToAmPm(currentTime).amOrPm}`;\r\n }\r\n\r\n if (\r\n (maxTime !== \"\" && !compareTimes(currentTime, maxTime)) ||\r\n maxTime === \"\"\r\n ) {\r\n maxTime = currentTime;\r\n }\r\n\r\n return maxTime;\r\n};\r\n\r\nconst checkValueBeforeAccept = (\r\n { format12, maxTime, minTime, disablePast, disableFuture },\r\n input,\r\n hourHeader\r\n) => {\r\n const minute = takeValue(input)[1];\r\n\r\n minTime = setMinTime(minTime, disablePast, format12);\r\n maxTime = setMaxTime(maxTime, disableFuture, format12);\r\n\r\n const [maxTimeHour, maxTimeMin, maxTimeFormat] = takeValue(maxTime, false);\r\n const [minTimeHour, minTimeMin, minTimeFormat] = takeValue(minTime, false);\r\n\r\n if (maxTimeFormat !== undefined || minTimeFormat !== undefined)\r\n return [hourHeader, minute];\r\n\r\n if (\r\n maxTimeHour !== \"\" &&\r\n minTimeHour === \"\" &&\r\n Number(hourHeader) > Number(maxTimeHour)\r\n )\r\n return;\r\n\r\n if (\r\n maxTimeHour === \"\" &&\r\n minTimeHour !== \"\" &&\r\n maxTimeMin === undefined &&\r\n minTimeMin !== \"\" &&\r\n Number(hourHeader) < Number(minTimeHour)\r\n )\r\n return;\r\n\r\n return [hourHeader, minute];\r\n};\r\n\r\nconst _verifyMaxTimeHourAndAddDisabledClass = (\r\n tips,\r\n maxTimeHour,\r\n classes,\r\n format12\r\n) => {\r\n tips.forEach((tip) => {\r\n maxTimeHour = maxTimeHour === \"12\" && format12 ? \"0\" : maxTimeHour;\r\n if (\r\n tip.textContent === \"00\" ||\r\n Number(tip.textContent === \"12\" && format12 ? \"0\" : tip.textContent) >\r\n maxTimeHour\r\n ) {\r\n Manipulator.addClass(tip, classes.tipsDisabled);\r\n tip.setAttribute(ATTR_TIMEPICKER_DISABLED, \"\");\r\n }\r\n });\r\n};\r\n\r\nconst _verifyMinTimeHourAndAddDisabledClass = (\r\n tips,\r\n minTimeHour,\r\n classes,\r\n format12\r\n) => {\r\n tips.forEach((tip) => {\r\n minTimeHour = minTimeHour === \"12\" && format12 ? \"0\" : minTimeHour;\r\n if (\r\n tip.textContent !== \"00\" &&\r\n Number(tip.textContent === \"12\" && format12 ? \"0\" : tip.textContent) <\r\n Number(minTimeHour)\r\n ) {\r\n Manipulator.addClass(tip, classes.tipsDisabled);\r\n tip.setAttribute(ATTR_TIMEPICKER_DISABLED, \"\");\r\n }\r\n });\r\n};\r\n\r\nconst _isHourDisabled = (selectedHour, timeHour, format12, operator) => {\r\n if (timeHour === \"12\" || timeHour === \"24\") {\r\n return;\r\n }\r\n\r\n const hourChange = format12 ? 12 : 24;\r\n\r\n if (operator === \"max\") {\r\n return (\r\n (Number(selectedHour) === hourChange ? 0 : Number(selectedHour)) >\r\n Number(timeHour)\r\n );\r\n }\r\n return (\r\n (Number(selectedHour) === hourChange ? 0 : Number(selectedHour)) <\r\n Number(timeHour)\r\n );\r\n};\r\n\r\nconst _verifyMaxTimeMinutesTipsAndAddDisabledClass = (\r\n tips,\r\n maxMinutes,\r\n maxHour,\r\n currHour,\r\n classes,\r\n format12\r\n) => {\r\n tips.forEach((tip) => {\r\n if (\r\n _isHourDisabled(currHour, maxHour, format12, \"max\") ||\r\n (Number(tip.textContent) > maxMinutes &&\r\n Number(currHour) === Number(maxHour))\r\n ) {\r\n Manipulator.addClass(tip, classes.tipsDisabled);\r\n tip.setAttribute(ATTR_TIMEPICKER_DISABLED, \"\");\r\n }\r\n });\r\n};\r\n\r\nconst _verifyMinTimeMinutesTipsAndAddDisabledClass = (\r\n tips,\r\n minMinutes,\r\n minHour,\r\n currHour,\r\n classes,\r\n format12\r\n) => {\r\n tips.forEach((tip) => {\r\n if (\r\n _isHourDisabled(currHour, minHour, format12, \"min\") ||\r\n (Number(tip.textContent) < minMinutes &&\r\n Number(currHour) === Number(minHour))\r\n ) {\r\n Manipulator.addClass(tip, classes.tipsDisabled);\r\n tip.setAttribute(ATTR_TIMEPICKER_DISABLED, \"\");\r\n }\r\n });\r\n};\r\n\r\nconst _convertHourToNumber = (string) => {\r\n if (string.startsWith(\"0\")) return Number(string.slice(1));\r\n\r\n return Number(string);\r\n};\r\n\r\nexport {\r\n checkBrowser,\r\n findMousePosition,\r\n formatNormalHours,\r\n formatToAmPm,\r\n toggleClassHandler,\r\n checkValueBeforeAccept,\r\n takeValue,\r\n compareTimes,\r\n setMinTime,\r\n setMaxTime,\r\n _verifyMinTimeHourAndAddDisabledClass,\r\n _verifyMaxTimeMinutesTipsAndAddDisabledClass,\r\n _verifyMinTimeMinutesTipsAndAddDisabledClass,\r\n _verifyMaxTimeHourAndAddDisabledClass,\r\n _convertHourToNumber,\r\n};\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\n/* eslint-disable consistent-return */\r\n/* eslint-disable no-else-return */\r\nimport { createPopper } from \"@popperjs/core\";\r\nimport { typeCheckConfig, element, getUID } from \"../../util/index\";\r\nimport { getTimepickerTemplate, getToggleButtonTemplate } from \"./templates\";\r\nimport Data from \"../../dom/data\";\r\nimport Manipulator from \"../../dom/manipulator\";\r\nimport EventHandler, { EventHandlerMulti } from \"../../dom/event-handler\";\r\nimport {\r\n formatToAmPm,\r\n toggleClassHandler,\r\n checkBrowser,\r\n findMousePosition,\r\n takeValue,\r\n formatNormalHours,\r\n setMinTime,\r\n setMaxTime,\r\n _convertHourToNumber,\r\n checkValueBeforeAccept,\r\n _verifyMaxTimeHourAndAddDisabledClass,\r\n _verifyMaxTimeMinutesTipsAndAddDisabledClass,\r\n _verifyMinTimeHourAndAddDisabledClass,\r\n _verifyMinTimeMinutesTipsAndAddDisabledClass,\r\n} from \"./utils\";\r\nimport ScrollBarHelper from \"../../util/scrollbar\";\r\nimport FocusTrap from \"../../util/focusTrap\";\r\nimport SelectorEngine from \"../../dom/selector-engine\";\r\nimport {\r\n UP_ARROW,\r\n DOWN_ARROW,\r\n LEFT_ARROW,\r\n RIGHT_ARROW,\r\n ESCAPE,\r\n ENTER,\r\n} from \"../../util/keycodes\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst NAME = \"timepicker\";\r\nconst ATTR_NAME = `data-te-${NAME}`;\r\nconst SELECTOR_DATA_TE_TOGGLE = \"[data-te-toggle]\";\r\n\r\nconst DATA_KEY = `te.${NAME}`;\r\nconst EVENT_KEY = `.${DATA_KEY}`;\r\nconst DATA_API_KEY = \".data-api\";\r\nconst EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`;\r\nconst EVENT_KEYDOWN_DATA_API = `keydown${EVENT_KEY}${DATA_API_KEY}`;\r\nconst EVENT_MOUSEDOWN_DATA_API = `mousedown${EVENT_KEY}${DATA_API_KEY}`;\r\nconst EVENT_MOUSEUP_DATA_API = `mouseup${EVENT_KEY}${DATA_API_KEY}`;\r\nconst EVENT_MOUSEMOVE_DATA_API = `mousemove${EVENT_KEY}${DATA_API_KEY}`;\r\nconst EVENT_MOUSELEAVE_DATA_API = `mouseleave${EVENT_KEY}${DATA_API_KEY}`;\r\nconst EVENT_MOUSEOVER_DATA_API = `mouseover${EVENT_KEY}${DATA_API_KEY}`;\r\nconst EVENT_TOUCHMOVE_DATA_API = `touchmove${EVENT_KEY}${DATA_API_KEY}`;\r\nconst EVENT_TOUCHEND_DATA_API = `touchend${EVENT_KEY}${DATA_API_KEY}`;\r\nconst EVENT_TOUCHSTART_DATA_API = `touchstart${EVENT_KEY}${DATA_API_KEY}`;\r\n\r\nconst SELECTOR_ATTR_TIMEPICKER_AM = `[${ATTR_NAME}-am]`;\r\nconst SELECTOR_ATTR_TIMEPICKER_PM = `[${ATTR_NAME}-pm]`;\r\nconst SELECTOR_ATTR_TIMEPICKER_FORMAT24 = `[${ATTR_NAME}-format24]`;\r\nconst SELECTOR_ATTR_TIMEPICKER_CURRENT = `[${ATTR_NAME}-current]`;\r\nconst SELECTOR_ATTR_TIMEPICKER_HOUR_MODE = `[${ATTR_NAME}-hour-mode]`;\r\nconst SELECTOR_ATTR_TIMEPICKER_TOGGLE_BUTTON = `[${ATTR_NAME}-toggle-button]`;\r\n\r\nconst ATTR_TIMEPICKER_BUTTON_CANCEL = `${ATTR_NAME}-cancel`;\r\nconst ATTR_TIMEPICKER_BUTTON_CLEAR = `${ATTR_NAME}-clear`;\r\nconst ATTR_TIMEPICKER_BUTTON_SUBMIT = `${ATTR_NAME}-submit`;\r\nconst ATTR_TIMEPICKER_ICON = `${ATTR_NAME}-icon`;\r\nconst ATTR_TIMEPICKER_ICON_UP = `${ATTR_NAME}-icon-up`;\r\nconst ATTR_TIMEPICKER_ICON_DOWN = `${ATTR_NAME}-icon-down`;\r\nconst ATTR_TIMEPICKER_ICON_INLINE_HOUR = `${ATTR_NAME}-icon-inline-hour`;\r\nconst ATTR_TIMEPICKER_ICON_INLINE_MINUTE = `${ATTR_NAME}-icon-inline-minute`;\r\nconst ATTR_TIMEPICKER_ICONS_HOUR_INLINE = `${ATTR_NAME}-inline-hour-icons`;\r\nconst ATTR_TIMEPICKER_CURRENT_INLINE = `${ATTR_NAME}-current-inline`;\r\n\r\nconst ATTR_READONLY = \"readonly\";\r\nconst ATTR_TIMEPICKER_INVALID_FEEDBACK = `${ATTR_NAME}-invalid-feedback`;\r\nconst ATTR_TIMEPICKER_IS_INVALID = `${ATTR_NAME}-is-invalid`;\r\nconst ATTR_TIMEPICKER_DISABLED = `${ATTR_NAME}-disabled`;\r\nconst ATTR_TIMEPICKER_ACTIVE = `${ATTR_NAME}-active`;\r\n\r\nconst ATTR_TIMEPICKER_INPUT = `${ATTR_NAME}-input`;\r\nconst ATTR_TIMEPICKER_CLOCK = `${ATTR_NAME}-clock`;\r\nconst ATTR_TIMEPICKER_CLOCK_INNER = `${ATTR_NAME}-clock-inner`;\r\nconst ATTR_TIMEPICKER_WRAPPER = `${ATTR_NAME}-wrapper`;\r\nconst ATTR_TIMEPICKER_CLOCK_WRAPPER = `${ATTR_NAME}-clock-wrapper`;\r\nconst ATTR_TIMEPICKER_HOUR = `${ATTR_NAME}-hour`;\r\nconst ATTR_TIMEPICKER_MINUTE = `${ATTR_NAME}-minute`;\r\nconst ATTR_TIMEPICKER_TIPS_ELEMENT = `${ATTR_NAME}-tips-element`;\r\nconst ATTR_TIMEPICKER_TIPS_HOURS = `${ATTR_NAME}-tips-hours`;\r\nconst ATTR_TIMEPICKER_TIPS_MINUTES = `${ATTR_NAME}-tips-minutes`;\r\nconst ATTR_TIMEPICKER_INNER_HOURS = `${ATTR_NAME}-tips-inner`;\r\nconst ATTR_TIMEPICKER_TIPS_INNER_ELEMENT = `${ATTR_NAME}-tips-inner-element`;\r\nconst ATTR_TIMEPICKER_MIDDLE_DOT = `${ATTR_NAME}-middle-dot`;\r\nconst ATTR_TIMEPICKER_HAND_POINTER = `${ATTR_NAME}-hand-pointer`;\r\nconst ATTR_TIMEPICKER_CIRCLE = `${ATTR_NAME}-circle`;\r\nconst ATTR_TIMEPICKER_MODAL = `${ATTR_NAME}-modal`;\r\n\r\nconst defaultIcon = `\r\n \r\n `;\r\n\r\nconst Default = {\r\n appendValidationInfo: true,\r\n bodyID: \"\",\r\n cancelLabel: \"Cancel\",\r\n clearLabel: \"Clear\",\r\n closeModalOnBackdropClick: true,\r\n closeModalOnMinutesClick: false,\r\n container: \"body\",\r\n defaultTime: \"\",\r\n disabled: false,\r\n disablePast: false,\r\n disableFuture: false,\r\n enableValidation: true,\r\n focusInputAfterApprove: false,\r\n footerID: \"\",\r\n format12: true,\r\n format24: false,\r\n headID: \"\",\r\n increment: false,\r\n inline: false,\r\n invalidLabel: \"Invalid Time Format\",\r\n maxTime: \"\",\r\n minTime: \"\",\r\n modalID: \"\",\r\n okLabel: \"Ok\",\r\n overflowHidden: true,\r\n pickerID: \"\",\r\n readOnly: false,\r\n showClearBtn: true,\r\n switchHoursToMinutesOnClick: true,\r\n iconSVG: defaultIcon,\r\n withIcon: true,\r\n pmLabel: \"PM\",\r\n amLabel: \"AM\",\r\n animations: true,\r\n};\r\n\r\nconst DefaultType = {\r\n appendValidationInfo: \"boolean\",\r\n bodyID: \"string\",\r\n cancelLabel: \"string\",\r\n clearLabel: \"string\",\r\n closeModalOnBackdropClick: \"boolean\",\r\n closeModalOnMinutesClick: \"boolean\",\r\n container: \"string\",\r\n disabled: \"boolean\",\r\n disablePast: \"boolean\",\r\n disableFuture: \"boolean\",\r\n enableValidation: \"boolean\",\r\n footerID: \"string\",\r\n format12: \"boolean\",\r\n format24: \"boolean\",\r\n headID: \"string\",\r\n increment: \"boolean\",\r\n inline: \"boolean\",\r\n invalidLabel: \"string\",\r\n modalID: \"string\",\r\n okLabel: \"string\",\r\n overflowHidden: \"boolean\",\r\n pickerID: \"string\",\r\n readOnly: \"boolean\",\r\n showClearBtn: \"boolean\",\r\n switchHoursToMinutesOnClick: \"boolean\",\r\n defaultTime: \"(string|date|number)\",\r\n iconSVG: \"string\",\r\n withIcon: \"boolean\",\r\n pmLabel: \"string\",\r\n amLabel: \"string\",\r\n animations: \"boolean\",\r\n};\r\n\r\nconst DefaultClasses = {\r\n tips: \"absolute rounded-[100%] w-[32px] h-[32px] text-center cursor-pointer text-[1.1rem] rounded-[100%] bg-transparent flex justify-center items-center font-light focus:outline-none selection:bg-transparent\",\r\n tipsActive: \"text-white bg-[#3b71ca] font-normal\",\r\n tipsDisabled: \"text-[#b3afaf] pointer-events-none bg-transparent\",\r\n transform: \"transition-[transform,height] ease-in-out duration-[400ms]\",\r\n modal: \"z-[1065]\",\r\n clockAnimation: \"animate-[show-up-clock_350ms_linear]\",\r\n opacity: \"!opacity-100\",\r\n timepickerWrapper:\r\n \"touch-none opacity-100 z-[1065] inset-0 bg-[#00000066] h-full flex items-center justify-center flex-col fixed\",\r\n timepickerContainer:\r\n \"flex items-center justify-center flex-col max-h-[calc(100%-64px)] overflow-y-auto shadow-[0_10px_15px_-3px_rgba(0,0,0,0.07),0_4px_6px_-2px_rgba(0,0,0,0.05)] min-[320px]:max-[825px]:landscape:rounded-lg\",\r\n timepickerElements:\r\n \"flex flex-col min-w-[310px] min-h-[325px] bg-white rounded-t-[0.6rem] min-[320px]:max-[825px]:landscape:!flex-row min-[320px]:max-[825px]:landscape:min-w-[auto] min-[320px]:max-[825px]:landscape:min-h-[auto] min-[320px]:max-[825px]:landscape:overflow-y-auto justify-around\",\r\n timepickerHead:\r\n \"bg-[#3b71ca] dark:bg-zinc-700 h-[100px] rounded-t-lg pr-[24px] pl-[50px] py-[10px] min-[320px]:max-[825px]:landscape:rounded-tr-none min-[320px]:max-[825px]:landscape:rounded-bl-none min-[320px]:max-[825px]:landscape:p-[10px] min-[320px]:max-[825px]:landscape:pr-[10px] min-[320px]:max-[825px]:landscape:h-auto min-[320px]:max-[825px]:landscape:min-h-[305px] flex flex-row items-center justify-center\",\r\n timepickerHeadContent:\r\n \"min-[320px]:max-[825px]:landscape:flex-col flex w-full justify-evenly\",\r\n timepickerCurrentWrapper: \"[direction:ltr] rtl:[direction:rtl]\",\r\n timepickerCurrentButtonWrapper: \"relative h-full\",\r\n timepickerCurrentButton:\r\n \"text-[3.75rem] font-light leading-[1.2] tracking-[-0.00833em] text-white opacity-[.54] border-none bg-transparent p-0 min-[320px]:max-[825px]:landscape:text-5xl min-[320px]:max-[825px]:landscape:font-normal cursor-pointer hover:bg-[#00000026] hover:outline-none focus:bg-[#00000026] focus:outline-none \",\r\n timepickerDot:\r\n \"font-light leading-[1.2] tracking-[-0.00833em] text-[3.75rem] opacity-[.54] border-none bg-transparent p-0 text-white min-[320px]:max-[825px]:landscape:text-[3rem] min-[320px]:max-[825px]:landscape:font-normal\",\r\n timepickerModeWrapper:\r\n \"flex flex-col justify-center text-[18px] text-[#ffffff8a] min-[320px]:max-[825px]:landscape:!justify-around min-[320px]:max-[825px]:landscape:!flex-row\",\r\n timepickerModeAm:\r\n \"p-0 bg-transparent border-none text-white opacity-[.54] cursor-pointer hover:bg-[#00000026] hover:outline-none focus:bg-[#00000026] focus:outline-none\",\r\n timepickerModePm:\r\n \"p-0 bg-transparent border-none text-white opacity-[.54] cursor-pointer hover:bg-[#00000026] hover:outline-none focus:bg-[#00000026] focus:outline-none\",\r\n timepickerClockWrapper:\r\n \"min-w-[310px] max-w-[325px] min-h-[305px] overflow-x-hidden h-full flex justify-center flex-col items-center dark:bg-zinc-500\",\r\n timepickerClock:\r\n \"relative rounded-[100%] w-[260px] h-[260px] cursor-default my-0 mx-auto bg-[#00000012] dark:bg-zinc-600/50\",\r\n timepickerMiddleDot:\r\n \"top-1/2 left-1/2 w-[6px] h-[6px] -translate-y-1/2 -translate-x-1/2 rounded-[50%] bg-[#3b71ca] absolute\",\r\n timepickerHandPointer:\r\n \"bg-[#3b71ca] bottom-1/2 h-2/5 left-[calc(50%-1px)] rtl:!left-auto origin-[center_bottom_0] rtl:!origin-[50%_50%_0] w-[2px] absolute\",\r\n timepickerPointerCircle:\r\n \"-top-[21px] -left-[15px] w-[4px] border-[14px] border-solid border-[#3b71ca] h-[4px] box-content rounded-[100%] absolute\",\r\n timepickerClockInner:\r\n \"absolute top-1/2 left-1/2 -translate-y-1/2 -translate-x-1/2 w-[160px] h-[160px] rounded-[100%]\",\r\n timepickerFooterWrapper:\r\n \"rounded-b-lg flex justify-between items-center w-full h-[56px] px-[12px] bg-white dark:bg-zinc-500\",\r\n timepickerFooter: \"w-full flex justify-between\",\r\n timepickerFooterButton:\r\n \"text-[0.8rem] min-w-[64px] box-border font-medium leading-[40px] rounded-[10px] tracking-[0.1rem] uppercase text-[#3b71ca] dark:text-white border-none bg-transparent transition-[background-color,box-shadow,border] duration-[250ms] ease-[cubic-bezier(0.4,0,0.2,1)] delay-[0ms] outline-none py-0 px-[10px] h-[40px] mb-[10px] hover:bg-[#00000014] focus:bg-[#00000014] focus:outline-none\",\r\n timepickerInlineWrapper:\r\n \"touch-none opacity-100 z-[1065] inset-0 bg-[#00000066] h-full flex items-center justify-center flex-col rounded-lg\",\r\n timepickerInlineContainer:\r\n \"flex items-center justify-center flex-col max-h-[calc(100%-64px)] overflow-y-auto shadow-[0_10px_15px_-3px_rgba(0,0,0,0.07),0_4px_6px_-2px_rgba(0,0,0,0.05)]\",\r\n timepickerInlineElements:\r\n \"flex flex-col min-h-[auto] min-w-[310px] bg-white rounded-[0.6rem] min-[320px]:max-[825px]:landscape:!flex-row min-[320px]:max-[825px]:landscape:rounded-bl-lg min-[320px]:max-[825px]:landscape:min-w-[auto] min-[320px]:max-[825px]:landscape::min-h-[auto] min-[320px]:max-[825px]:landscape:overflow-y-auto justify-around\",\r\n timepickerInlineHead:\r\n \"bg-[#3b71ca] dark:bg-zinc-700 h-[100px] rounded-t-lg min-[320px]:max-[825px]:landscape:rounded-tr-none min-[320px]:max-[825px]:landscape:rounded-bl-none min-[320px]:max-[825px]:landscape:p-[10px] min-[320px]:max-[825px]:landscape:pr-[10px] min-[320px]:max-[825px]:landscape:h-auto min-[320px]:max-[825px]:landscape:min-h-[305px] flex flex-row items-center justify-center p-0 rounded-b-lg\",\r\n timepickerInlineHeadContent:\r\n \"min-[320px]:max-[825px]:landscape:flex-col flex w-full justify-evenly items-center\",\r\n timepickerInlineHourWrapper: \"relative h-full !opacity-100\",\r\n timepickerCurrentMinuteWrapper: \"relative h-full\",\r\n timepickerInlineIconUp:\r\n \"absolute text-white -top-[35px] opacity-0 hover:opacity-100 transition-all duration-200 ease-[ease] cursor-pointer -translate-x-1/2 -translate-y-1/2 left-1/2 w-[30px] h-[30px] flex justify-center items-center\",\r\n timepickerInlineIconSvg: \"h-4 w-4\",\r\n timepickerInlineCurrentButton:\r\n \"font-light leading-[1.2] tracking-[-0.00833em] text-white border-none bg-transparent p-0 min-[320px]:max-[825px]:landscape:text-5xl min-[320px]:max-[825px]:landscape:font-normal !opacity-100 cursor-pointer focus:bg-[#00000026] hover:outline-none focus:outline-none text-[2.5rem] hover:bg-[unset]\",\r\n timepickerInlineIconDown:\r\n \"absolute text-white -bottom-[47px] opacity-0 hover:opacity-100 transition-all duration-200 ease-[ease] cursor-pointer -translate-x-1/2 -translate-y-1/2 left-1/2 w-[30px] h-[30px] flex justify-center items-center\",\r\n timepickerInlineDot:\r\n \"font-light leading-[1.2] tracking-[-0.00833em] opacity-[.54] border-none bg-transparent p-0 text-white min-[320px]:max-[825px]:landscape:text-[3rem] min-[320px]:max-[825px]:landscape:font-normal text-[2.5rem]\",\r\n timepickerInlineModeWrapper:\r\n \"flex justify-center text-[18px] text-[#ffffff8a] min-[320px]:max-[825px]:landscape:!justify-around min-[320px]:max-[825px]:landscape:!flex-row\",\r\n timepickerInlineModeAm:\r\n \"hover:bg-[#00000026] hover:outline-none focus:bg-[#00000026] focus:outline-none p-0 bg-transparent border-none text-white opacity-[.54] cursor-pointer mr-2 ml-6\",\r\n timepickerInlineModePm:\r\n \"hover:bg-[#00000026] hover:outline-none focus:bg-[#00000026] focus:outline-none p-0 bg-transparent border-none text-white opacity-[.54] cursor-pointer\",\r\n timepickerInlineSubmitButton:\r\n \"hover:bg-[#00000014] focus:bg-[#00000014] focus:outline-none text-[0.8rem] box-border font-medium leading-[40px] tracking-[.1rem] uppercase border-none bg-transparent [transition:background-color_250ms_cubic-bezier(0.4,0,0.2,1)_0ms,box-shadow_250ms_cubic-bezier(0.4,0,0.2,1)_0ms,border_250ms_cubic-bezier(0.4,0,0.2,1)_0ms] outline-none rounded-[100%] h-[48px] min-w-[48px] inline-block ml-[30px] text-white py-1 px-2 mb-0\",\r\n timepickerToggleButton:\r\n \"h-4 w-4 ml-auto absolute outline-none border-none bg-transparent right-1.5 top-1/2 -translate-x-1/2 -translate-y-1/2 transition-all duration-300 ease-[cubic-bezier(0.25,0.1,0.25,1)] cursor-pointer hover:text-[#3b71ca] focus:text-[#3b71ca] dark:hover:text-[#3b71ca] dark:focus:text-[#3b71ca] dark:text-white\",\r\n};\r\n\r\nconst DefaultClassesType = {\r\n tips: \"string\",\r\n tipsActive: \"string\",\r\n tipsDisabled: \"string\",\r\n transform: \"string\",\r\n modal: \"string\",\r\n clockAnimation: \"string\",\r\n opacity: \"string\",\r\n timepickerWrapper: \"string\",\r\n timepickerContainer: \"string\",\r\n timepickerElements: \"string\",\r\n timepickerHead: \"string\",\r\n timepickerHeadContent: \"string\",\r\n timepickerCurrentWrapper: \"string\",\r\n timepickerCurrentButtonWrapper: \"string\",\r\n timepickerCurrentButton: \"string\",\r\n timepickerDot: \"string\",\r\n timepickerModeWrapper: \"string\",\r\n timepickerModeAm: \"string\",\r\n timepickerModePm: \"string\",\r\n timepickerClockWrapper: \"string\",\r\n timepickerClock: \"string\",\r\n timepickerMiddleDot: \"string\",\r\n timepickerHandPointer: \"string\",\r\n timepickerPointerCircle: \"string\",\r\n timepickerClockInner: \"string\",\r\n timepickerFooterWrapper: \"string\",\r\n timepickerFooterButton: \"string\",\r\n timepickerInlineWrapper: \"string\",\r\n timepickerInlineContainer: \"string\",\r\n timepickerInlineElements: \"string\",\r\n timepickerInlineHead: \"string\",\r\n timepickerInlineHeadContent: \"string\",\r\n timepickerInlineHourWrapper: \"string\",\r\n timepickerCurrentMinuteWrapper: \"string\",\r\n timepickerInlineIconUp: \"string\",\r\n timepickerInlineIconSvg: \"string\",\r\n timepickerInlineCurrentButton: \"string\",\r\n timepickerInlineIconDown: \"string\",\r\n timepickerInlineDot: \"string\",\r\n timepickerInlineModeWrapper: \"string\",\r\n timepickerInlineModeAm: \"string\",\r\n timepickerInlineModePm: \"string\",\r\n timepickerInlineSubmitButton: \"string\",\r\n timepickerToggleButton: \"string\",\r\n};\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nClass Definition\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nclass Timepicker {\r\n constructor(element, options = {}, classes) {\r\n this._element = element;\r\n\r\n if (this._element) {\r\n Data.setData(element, DATA_KEY, this);\r\n }\r\n\r\n this._document = document;\r\n this._options = this._getConfig(options);\r\n this._classes = this._getClasses(classes);\r\n this._currentTime = null;\r\n this._toggleButtonId = getUID(\"timepicker-toggle-\");\r\n\r\n this.hoursArray = [\r\n \"12\",\r\n \"1\",\r\n \"2\",\r\n \"3\",\r\n \"4\",\r\n \"5\",\r\n \"6\",\r\n \"7\",\r\n \"8\",\r\n \"9\",\r\n \"10\",\r\n \"11\",\r\n ];\r\n this.innerHours = [\r\n \"00\",\r\n \"13\",\r\n \"14\",\r\n \"15\",\r\n \"16\",\r\n \"17\",\r\n \"18\",\r\n \"19\",\r\n \"20\",\r\n \"21\",\r\n \"22\",\r\n \"23\",\r\n ];\r\n this.minutesArray = [\r\n \"00\",\r\n \"05\",\r\n \"10\",\r\n \"15\",\r\n \"20\",\r\n \"25\",\r\n \"30\",\r\n \"35\",\r\n \"40\",\r\n \"45\",\r\n \"50\",\r\n \"55\",\r\n ];\r\n\r\n this.input = SelectorEngine.findOne(\"input\", this._element);\r\n this.dataWithIcon = element.dataset.withIcon;\r\n this.dataToggle = element.dataset.toggle;\r\n this.customIcon = SelectorEngine.findOne(\r\n SELECTOR_ATTR_TIMEPICKER_TOGGLE_BUTTON,\r\n this._element\r\n );\r\n\r\n this._checkToggleButton();\r\n\r\n this.inputFormatShow = SelectorEngine.findOne(\r\n SELECTOR_ATTR_TIMEPICKER_FORMAT24,\r\n this._element\r\n );\r\n\r\n this.inputFormat =\r\n this.inputFormatShow === null\r\n ? \"\"\r\n : Object.values(this.inputFormatShow.dataset)[0];\r\n this.elementToggle = SelectorEngine.findOne(\r\n SELECTOR_DATA_TE_TOGGLE,\r\n this._element\r\n );\r\n this.toggleElement = Object.values(\r\n element.querySelector(SELECTOR_DATA_TE_TOGGLE).dataset\r\n )[0];\r\n\r\n this._hour = null;\r\n this._minutes = null;\r\n this._AM = null;\r\n this._PM = null;\r\n this._wrapper = null;\r\n this._modal = null;\r\n this._hand = null;\r\n this._circle = null;\r\n this._focusTrap = null;\r\n this._popper = null;\r\n this._interval = null;\r\n this._timeoutInterval = null;\r\n\r\n this._inputValue =\r\n this._options.defaultTime !== \"\"\r\n ? this._options.defaultTime\r\n : this.input.value;\r\n\r\n if (this._options.format24) {\r\n this._options.format12 = false;\r\n\r\n this._currentTime = formatNormalHours(this._inputValue);\r\n }\r\n\r\n if (this._options.format12) {\r\n this._options.format24 = false;\r\n\r\n this._currentTime = formatToAmPm(this._inputValue);\r\n }\r\n\r\n if (this._options.readOnly) {\r\n this.input.setAttribute(ATTR_READONLY, true);\r\n }\r\n\r\n if (this.inputFormat === \"true\" && this.inputFormat !== \"\") {\r\n this._options.format12 = false;\r\n this._options.format24 = true;\r\n this._currentTime = formatNormalHours(this._inputValue);\r\n }\r\n\r\n this._animations =\r\n !window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches &&\r\n this._options.animations;\r\n\r\n this.init();\r\n\r\n this._isHours = true;\r\n this._isMinutes = false;\r\n this._isInvalidTimeFormat = false;\r\n this._isMouseMove = false;\r\n this._isInner = false;\r\n this._isAmEnabled = false;\r\n this._isPmEnabled = false;\r\n\r\n if (this._options.format12 && !this._options.defaultTime) {\r\n this._isPmEnabled = true;\r\n }\r\n\r\n this._objWithDataOnChange = { degrees: null };\r\n\r\n this._scrollBar = new ScrollBarHelper();\r\n }\r\n\r\n // Getters\r\n\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n // Public\r\n\r\n init() {\r\n const { format12, format24, enableValidation } = this._options;\r\n let zero;\r\n let hoursFormat;\r\n let _amOrPm;\r\n\r\n this.input.setAttribute(ATTR_TIMEPICKER_INPUT, \"\");\r\n\r\n if (this._currentTime !== undefined) {\r\n const { hours, minutes, amOrPm } = this._currentTime;\r\n\r\n zero = Number(hours) < 10 ? 0 : \"\";\r\n hoursFormat = `${zero}${Number(hours)}:${minutes}`;\r\n _amOrPm = amOrPm;\r\n\r\n if (format12) {\r\n this.input.value = `${hoursFormat} ${_amOrPm}`;\r\n } else if (format24) {\r\n this.input.value = `${hoursFormat}`;\r\n }\r\n } else {\r\n zero = \"\";\r\n hoursFormat = \"\";\r\n _amOrPm = \"\";\r\n\r\n this.input.value = \"\";\r\n }\r\n\r\n if (this.input.value.length > 0 && this.input.value !== \"\") {\r\n this.input.setAttribute(ATTR_TIMEPICKER_ACTIVE, \"\");\r\n EventHandler.trigger(this.input, \"input\");\r\n }\r\n\r\n if (this._options === null && this._element === null) return;\r\n\r\n if (enableValidation) {\r\n this._getValidate(\"keydown change blur focus\");\r\n }\r\n\r\n this._handleOpen();\r\n this._listenToToggleKeydown();\r\n }\r\n\r\n dispose() {\r\n this._removeModal();\r\n\r\n if (this._element !== null) {\r\n Data.removeData(this._element, DATA_KEY);\r\n }\r\n\r\n setTimeout(() => {\r\n this._element = null;\r\n this._options = null;\r\n this.input = null;\r\n this._focusTrap = null;\r\n }, 350);\r\n\r\n EventHandler.off(\r\n this._document,\r\n \"click\",\r\n `[data-te-toggle='${this.toggleElement}']`\r\n );\r\n EventHandler.off(\r\n this._element,\r\n \"keydown\",\r\n `[data-te-toggle='${this.toggleElement}']`\r\n );\r\n }\r\n\r\n update(options = {}) {\r\n this._options = this._getConfig({ ...this._options, ...options });\r\n }\r\n\r\n // private\r\n\r\n _checkToggleButton() {\r\n if (this.customIcon !== null) return;\r\n\r\n if (this.dataWithIcon !== undefined) {\r\n this._options.withIcon = null;\r\n\r\n if (this.dataWithIcon === \"true\") {\r\n this._appendToggleButton(this._options);\r\n }\r\n }\r\n\r\n if (this._options.withIcon) {\r\n this._appendToggleButton(this._options);\r\n }\r\n }\r\n\r\n _appendToggleButton() {\r\n const toggleButton = getToggleButtonTemplate(\r\n this._options,\r\n this._toggleButtonId,\r\n this._classes\r\n );\r\n\r\n this.input.insertAdjacentHTML(\"afterend\", toggleButton);\r\n }\r\n\r\n _getDomElements() {\r\n this._hour = SelectorEngine.findOne(`[${ATTR_TIMEPICKER_HOUR}]`);\r\n this._minutes = SelectorEngine.findOne(`[${ATTR_TIMEPICKER_MINUTE}]`);\r\n this._AM = SelectorEngine.findOne(SELECTOR_ATTR_TIMEPICKER_AM);\r\n this._PM = SelectorEngine.findOne(SELECTOR_ATTR_TIMEPICKER_PM);\r\n this._wrapper = SelectorEngine.findOne(`[${ATTR_TIMEPICKER_WRAPPER}]`);\r\n this._modal = SelectorEngine.findOne(`[${ATTR_TIMEPICKER_MODAL}]`);\r\n this._hand = SelectorEngine.findOne(`[${ATTR_TIMEPICKER_HAND_POINTER}]`);\r\n this._circle = SelectorEngine.findOne(`[${ATTR_TIMEPICKER_CIRCLE}]`);\r\n this._clock = SelectorEngine.findOne(`[${ATTR_TIMEPICKER_CLOCK}]`);\r\n this._clockInner = SelectorEngine.findOne(\r\n `[${ATTR_TIMEPICKER_CLOCK_INNER}]`\r\n );\r\n }\r\n\r\n _handlerMaxMinHoursOptions(\r\n degrees,\r\n maxHour,\r\n minHour,\r\n maxFormat,\r\n minFormat,\r\n e\r\n ) {\r\n if (!maxHour && !minHour) return true;\r\n\r\n const { format24, format12, disablePast, disableFuture } = this._options;\r\n const { _isAmEnabled, _isPmEnabled } = this;\r\n const key = e.keyCode;\r\n\r\n const _isMouseOnInnerClock =\r\n e.target.hasAttribute(ATTR_TIMEPICKER_CLOCK_INNER) ||\r\n e.target.hasAttribute(ATTR_TIMEPICKER_INNER_HOURS) ||\r\n e.target.hasAttribute(ATTR_TIMEPICKER_TIPS_INNER_ELEMENT);\r\n\r\n minHour = setMinTime(minHour, disablePast, format12);\r\n maxHour = setMaxTime(maxHour, disableFuture, format12);\r\n typeof maxHour !== \"number\" && (maxHour = takeValue(maxHour, false)[0]);\r\n\r\n const maxHourDegrees = maxHour !== \"\" ? maxHour * 30 : \"\";\r\n const minHourDegrees = minHour !== \"\" ? minHour * 30 : \"\";\r\n\r\n if (degrees < 0) {\r\n degrees = 360 + degrees;\r\n }\r\n\r\n degrees = degrees === 360 ? 0 : degrees;\r\n\r\n const _handleKeyboardEvents = () => {\r\n const tips = document.querySelectorAll(\r\n `[${ATTR_TIMEPICKER_TIPS_ELEMENT}]`\r\n );\r\n const innerTips = document.querySelectorAll(\r\n `[${ATTR_TIMEPICKER_TIPS_INNER_ELEMENT}]`\r\n );\r\n\r\n const currentHour = _convertHourToNumber(this._hour.innerText);\r\n let nextHourTip;\r\n let numberToAdd;\r\n let nextHour;\r\n\r\n if (key === UP_ARROW) {\r\n numberToAdd = 1;\r\n } else if (key === DOWN_ARROW) {\r\n numberToAdd = -1;\r\n }\r\n\r\n if (currentHour === 12 && key === UP_ARROW) {\r\n nextHour = 1;\r\n } else if (currentHour === 0 && key === UP_ARROW) {\r\n nextHour = 13;\r\n } else if (currentHour === 0 && key === DOWN_ARROW) {\r\n nextHour = 23;\r\n } else if (currentHour === 13 && key === DOWN_ARROW) {\r\n nextHour = 0;\r\n } else if (currentHour === 1 && key === DOWN_ARROW) {\r\n nextHour = 12;\r\n } else {\r\n nextHour = currentHour + numberToAdd;\r\n }\r\n\r\n tips.forEach((tip) => {\r\n if (Number(tip.textContent) === nextHour) {\r\n nextHourTip = tip;\r\n }\r\n });\r\n innerTips.forEach((innerTip) => {\r\n if (Number(innerTip.textContent) === nextHour) {\r\n nextHourTip = innerTip;\r\n }\r\n });\r\n\r\n return !nextHourTip.parentElement.hasAttribute(ATTR_TIMEPICKER_DISABLED);\r\n };\r\n\r\n const _handle24FormatMouseEvents = () => {\r\n const minInnerHourDegrees =\r\n minHour !== \"\" && minHour > 12 ? (minHour - 12) * 30 : \"\";\r\n const maxInnerHourDegrees =\r\n maxHour !== \"\" && maxHour > 12 ? (maxHour - 12) * 30 : \"\";\r\n\r\n if (\r\n (minInnerHourDegrees && degrees < minInnerHourDegrees) ||\r\n (maxInnerHourDegrees && degrees > maxInnerHourDegrees) ||\r\n (maxHour && maxHour < 12)\r\n ) {\r\n return;\r\n }\r\n return true;\r\n };\r\n\r\n if (format24 && e.type !== \"keydown\" && _isMouseOnInnerClock) {\r\n return _handle24FormatMouseEvents();\r\n }\r\n if (e.type === \"keydown\") {\r\n return _handleKeyboardEvents(e);\r\n }\r\n\r\n const minFormatAndCurrentFormatEqual =\r\n !minFormat ||\r\n (minFormat === \"PM\" && _isPmEnabled) ||\r\n (minHour !== \"\" && minFormat === \"AM\" && _isAmEnabled);\r\n\r\n const maxFormatAndCurrentFormatEqual =\r\n !maxFormat ||\r\n (maxFormat === \"PM\" && _isPmEnabled) ||\r\n (maxHour !== \"\" && maxFormat === \"AM\" && _isAmEnabled);\r\n\r\n const isMinHourValid = () => {\r\n const minDegrees =\r\n minHourDegrees === 360 && format12 ? 0 : minHourDegrees;\r\n if (!minHour) {\r\n return true;\r\n } else if (\r\n (minFormat === \"PM\" && _isAmEnabled) ||\r\n (minFormatAndCurrentFormatEqual && degrees < minDegrees)\r\n ) {\r\n return;\r\n }\r\n return true;\r\n };\r\n\r\n const isMaxHourValid = () => {\r\n const maxDegrees =\r\n maxHourDegrees === 360 && format12 ? 0 : maxHourDegrees;\r\n if (!maxHour) {\r\n return true;\r\n } else if (\r\n (maxFormat === \"AM\" && _isPmEnabled) ||\r\n (maxFormatAndCurrentFormatEqual && degrees > maxDegrees)\r\n ) {\r\n return;\r\n }\r\n return true;\r\n };\r\n\r\n return isMinHourValid() && isMaxHourValid();\r\n }\r\n\r\n _handleKeyboard() {\r\n EventHandler.on(this._document, EVENT_KEYDOWN_DATA_API, \"\", (e) => {\r\n let hour;\r\n let minute;\r\n let innerHour;\r\n const {\r\n increment,\r\n maxTime,\r\n minTime,\r\n format12,\r\n disablePast,\r\n disableFuture,\r\n } = this._options;\r\n\r\n let minHour = takeValue(minTime, false)[0];\r\n let maxHour = takeValue(maxTime, false)[0];\r\n const minFormat = takeValue(minTime, false)[2];\r\n const maxFormat = takeValue(maxTime, false)[2];\r\n\r\n minHour = setMinTime(minHour, disablePast, format12);\r\n maxHour = setMaxTime(maxHour, disableFuture, format12);\r\n\r\n typeof maxHour !== \"number\" && (maxHour = takeValue(maxHour, false)[0]);\r\n\r\n const hoursView =\r\n SelectorEngine.findOne(`[${ATTR_TIMEPICKER_TIPS_MINUTES}]`) === null;\r\n const innerHoursExist =\r\n SelectorEngine.findOne(`[${ATTR_TIMEPICKER_INNER_HOURS}]`) !== null;\r\n\r\n const degrees = Number(this._hand.style.transform.replace(/[^\\d-]/g, \"\"));\r\n\r\n const allTipsMinutes = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_TIPS_MINUTES}]`,\r\n this._modal\r\n );\r\n const allTipsHours = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_TIPS_HOURS}]`,\r\n this._modal\r\n );\r\n const allInnerTips = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_INNER_HOURS}]`,\r\n this._modal\r\n );\r\n\r\n let hourTime = this._makeHourDegrees(e.target, degrees, hour).hour;\r\n const { degrees: hourObjDegrees, addDegrees } = this._makeHourDegrees(\r\n e.target,\r\n degrees,\r\n hour\r\n );\r\n\r\n let { minute: minHourMinutes, degrees: minObjDegrees } =\r\n this._makeMinutesDegrees(degrees, minute);\r\n const addMinDegrees = this._makeMinutesDegrees(\r\n degrees,\r\n minute\r\n ).addDegrees;\r\n\r\n let { hour: innerHourDegrees } = this._makeInnerHoursDegrees(\r\n degrees,\r\n innerHour\r\n );\r\n\r\n if (e.keyCode === ESCAPE) {\r\n const cancelBtn = SelectorEngine.findOne(\r\n `[${ATTR_TIMEPICKER_BUTTON_CANCEL}]`,\r\n this._modal\r\n );\r\n EventHandler.trigger(cancelBtn, \"click\");\r\n } else if (hoursView) {\r\n if (innerHoursExist) {\r\n if (e.keyCode === RIGHT_ARROW) {\r\n this._isInner = false;\r\n Manipulator.addStyle(this._hand, {\r\n height: \"calc(40% + 1px)\",\r\n });\r\n this._hour.textContent = this._setHourOrMinute(\r\n hourTime > 12 ? 1 : hourTime\r\n );\r\n this._toggleClassActive(this.hoursArray, this._hour, allTipsHours);\r\n this._toggleClassActive(this.innerHours, this._hour, allInnerTips);\r\n }\r\n\r\n if (e.keyCode === LEFT_ARROW) {\r\n this._isInner = true;\r\n Manipulator.addStyle(this._hand, {\r\n height: \"21.5%\",\r\n });\r\n\r\n this._hour.textContent = this._setHourOrMinute(\r\n innerHourDegrees >= 24 || innerHourDegrees === \"00\"\r\n ? 0\r\n : innerHourDegrees\r\n );\r\n this._toggleClassActive(this.innerHours, this._hour, allInnerTips);\r\n this._toggleClassActive(\r\n this.hoursArray,\r\n this._hour - 1,\r\n allTipsHours\r\n );\r\n }\r\n }\r\n if (e.keyCode === UP_ARROW) {\r\n const isNextHourValid = this._handlerMaxMinHoursOptions(\r\n hourObjDegrees + 30,\r\n maxHour,\r\n minHour,\r\n maxFormat,\r\n minFormat,\r\n e\r\n );\r\n\r\n if (!isNextHourValid) return;\r\n\r\n Manipulator.addStyle(this._hand, {\r\n transform: `rotateZ(${hourObjDegrees + addDegrees}deg)`,\r\n });\r\n\r\n if (this._isInner) {\r\n innerHourDegrees += 1;\r\n\r\n if (innerHourDegrees === 24) {\r\n innerHourDegrees = 0;\r\n } else if (innerHourDegrees === 25 || innerHourDegrees === \"001\") {\r\n innerHourDegrees = 13;\r\n }\r\n\r\n this._hour.textContent = this._setHourOrMinute(innerHourDegrees);\r\n this._toggleClassActive(this.innerHours, this._hour, allInnerTips);\r\n } else {\r\n hourTime += 1;\r\n this._hour.textContent = this._setHourOrMinute(\r\n hourTime > 12 ? 1 : hourTime\r\n );\r\n this._toggleClassActive(this.hoursArray, this._hour, allTipsHours);\r\n }\r\n }\r\n if (e.keyCode === DOWN_ARROW) {\r\n const isNextHourValid = this._handlerMaxMinHoursOptions(\r\n hourObjDegrees - 30,\r\n maxHour,\r\n minHour,\r\n maxFormat,\r\n minFormat,\r\n e\r\n );\r\n\r\n if (!isNextHourValid) return;\r\n\r\n Manipulator.addStyle(this._hand, {\r\n transform: `rotateZ(${hourObjDegrees - addDegrees}deg)`,\r\n });\r\n\r\n if (this._isInner) {\r\n innerHourDegrees -= 1;\r\n\r\n if (innerHourDegrees === 12) {\r\n innerHourDegrees = 0;\r\n } else if (innerHourDegrees === -1) {\r\n innerHourDegrees = 23;\r\n }\r\n\r\n this._hour.textContent = this._setHourOrMinute(innerHourDegrees);\r\n this._toggleClassActive(this.innerHours, this._hour, allInnerTips);\r\n } else {\r\n hourTime -= 1;\r\n this._hour.textContent = this._setHourOrMinute(\r\n hourTime === 0 ? 12 : hourTime\r\n );\r\n this._toggleClassActive(this.hoursArray, this._hour, allTipsHours);\r\n }\r\n }\r\n } else {\r\n if (e.keyCode === UP_ARROW) {\r\n minObjDegrees += addMinDegrees;\r\n Manipulator.addStyle(this._hand, {\r\n transform: `rotateZ(${minObjDegrees}deg)`,\r\n });\r\n minHourMinutes += 1;\r\n if (increment) {\r\n minHourMinutes += 4;\r\n\r\n if (minHourMinutes === \"0014\") {\r\n minHourMinutes = 5;\r\n }\r\n }\r\n\r\n this._minutes.textContent = this._setHourOrMinute(\r\n minHourMinutes > 59 ? 0 : minHourMinutes\r\n );\r\n this._toggleClassActive(\r\n this.minutesArray,\r\n this._minutes,\r\n allTipsMinutes\r\n );\r\n this._toggleBackgroundColorCircle(\r\n `[${ATTR_TIMEPICKER_TIPS_MINUTES}]`\r\n );\r\n }\r\n if (e.keyCode === DOWN_ARROW) {\r\n minObjDegrees -= addMinDegrees;\r\n Manipulator.addStyle(this._hand, {\r\n transform: `rotateZ(${minObjDegrees}deg)`,\r\n });\r\n if (increment) {\r\n minHourMinutes -= 5;\r\n } else {\r\n minHourMinutes -= 1;\r\n }\r\n\r\n if (minHourMinutes === -1) {\r\n minHourMinutes = 59;\r\n } else if (minHourMinutes === -5) {\r\n minHourMinutes = 55;\r\n }\r\n\r\n this._minutes.textContent = this._setHourOrMinute(minHourMinutes);\r\n this._toggleClassActive(\r\n this.minutesArray,\r\n this._minutes,\r\n allTipsMinutes\r\n );\r\n this._toggleBackgroundColorCircle(\r\n `[${ATTR_TIMEPICKER_TIPS_MINUTES}]`\r\n );\r\n }\r\n }\r\n });\r\n }\r\n\r\n _setActiveClassToTipsOnOpen(hour, ...rest) {\r\n if (this._isInvalidTimeFormat) return;\r\n\r\n if (!this._options.format24) {\r\n [...rest].filter((e) => {\r\n if (e === \"PM\") {\r\n Manipulator.addClass(this._PM, this._classes.opacity);\r\n this._PM.setAttribute(ATTR_TIMEPICKER_ACTIVE, \"\");\r\n } else if (e === \"AM\") {\r\n Manipulator.addClass(this._AM, this._classes.opacity);\r\n this._AM.setAttribute(ATTR_TIMEPICKER_ACTIVE, \"\");\r\n } else {\r\n Manipulator.removeClass(this._AM, this._classes.opacity);\r\n Manipulator.removeClass(this._PM, this._classes.opacity);\r\n this._AM.removeAttribute(ATTR_TIMEPICKER_ACTIVE);\r\n this._PM.removeAttribute(ATTR_TIMEPICKER_ACTIVE);\r\n }\r\n\r\n return e;\r\n });\r\n\r\n const allTipsHours = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_TIPS_HOURS}]`,\r\n this._modal\r\n );\r\n this._addActiveClassToTip(allTipsHours, hour);\r\n } else {\r\n const allTipsHours = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_TIPS_HOURS}]`,\r\n this._modal\r\n );\r\n const allInnerTips = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_INNER_HOURS}]`,\r\n this._modal\r\n );\r\n\r\n this._addActiveClassToTip(allTipsHours, hour);\r\n this._addActiveClassToTip(allInnerTips, hour);\r\n }\r\n }\r\n\r\n _setTipsAndTimesDependOnInputValue(hour, minute) {\r\n const { inline, format12 } = this._options;\r\n\r\n if (!this._isInvalidTimeFormat) {\r\n const rotateDegrees = hour > 12 ? hour * 30 - 360 : hour * 30;\r\n this._hour.textContent = hour;\r\n this._minutes.textContent = minute;\r\n\r\n if (!inline) {\r\n Manipulator.addStyle(this._hand, {\r\n transform: `rotateZ(${rotateDegrees}deg)`,\r\n });\r\n Manipulator.addStyle(this._circle, {\r\n backgroundColor: \"#1976d2\",\r\n });\r\n\r\n if (Number(hour) > 12 || hour === \"00\") {\r\n Manipulator.addStyle(this._hand, {\r\n height: \"21.5%\",\r\n });\r\n }\r\n }\r\n } else {\r\n this._hour.textContent = \"12\";\r\n this._minutes.textContent = \"00\";\r\n\r\n if (!inline) {\r\n Manipulator.addStyle(this._hand, {\r\n transform: \"rotateZ(0deg)\",\r\n });\r\n }\r\n if (format12) {\r\n Manipulator.addClass(this._PM, this._classes.opacity);\r\n this._PM.setAttribute(ATTR_TIMEPICKER_ACTIVE, \"\");\r\n }\r\n }\r\n }\r\n\r\n _listenToToggleKeydown() {\r\n EventHandler.on(\r\n this._element,\r\n \"keydown\",\r\n `[data-te-toggle='${this.toggleElement}']`,\r\n (e) => {\r\n if (e.keyCode === ENTER) {\r\n e.preventDefault();\r\n EventHandler.trigger(this.elementToggle, \"click\");\r\n }\r\n }\r\n );\r\n }\r\n\r\n _handleOpen() {\r\n const container = this._getContainer();\r\n EventHandlerMulti.on(\r\n this._element,\r\n \"click\",\r\n `[data-te-toggle='${this.toggleElement}']`,\r\n (e) => {\r\n if (this._options === null) return;\r\n\r\n // Fix for input with open, if is not for settimeout input has incorrent jumping label\r\n const fixForInput =\r\n Manipulator.getDataAttribute(this.input, \"toggle\") !== null ? 200 : 0;\r\n\r\n setTimeout(() => {\r\n Manipulator.addStyle(this.elementToggle, {\r\n pointerEvents: \"none\",\r\n });\r\n\r\n this.elementToggle.blur();\r\n\r\n let checkInputValue;\r\n\r\n if (takeValue(this.input)[0] === \"\") {\r\n checkInputValue = [\"12\", \"00\", \"PM\"];\r\n } else {\r\n checkInputValue = takeValue(this.input);\r\n }\r\n\r\n const { modalID, inline, format12 } = this._options;\r\n const [hour, minute, format] = checkInputValue;\r\n const div = element(\"div\");\r\n\r\n if (Number(hour) > 12 || hour === \"00\") {\r\n this._isInner = true;\r\n }\r\n\r\n this.input.blur();\r\n e.target.blur();\r\n\r\n div.innerHTML = getTimepickerTemplate(this._options, this._classes);\r\n Manipulator.addClass(div, this._classes.modal);\r\n div.setAttribute(ATTR_TIMEPICKER_MODAL, \"\");\r\n\r\n div.setAttribute(\"role\", \"dialog\");\r\n div.setAttribute(\"tabIndex\", \"-1\");\r\n div.setAttribute(\"id\", modalID);\r\n\r\n if (!inline) {\r\n container.appendChild(div);\r\n this._scrollBar.hide();\r\n } else {\r\n this._popper = createPopper(this.input, div, {\r\n placement: \"bottom-start\",\r\n });\r\n\r\n container.appendChild(div);\r\n }\r\n\r\n this._getDomElements();\r\n if (this._animations) {\r\n this._toggleBackdropAnimation();\r\n } else {\r\n Manipulator.addClass(this._wrapper, this._classes.opacity);\r\n }\r\n this._setActiveClassToTipsOnOpen(hour, minute, format);\r\n this._appendTimes();\r\n this._setActiveClassToTipsOnOpen(hour, minute, format);\r\n this._setTipsAndTimesDependOnInputValue(hour, minute);\r\n\r\n if (this.input.value === \"\") {\r\n const allTipsHours = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_TIPS_HOURS}]`,\r\n this._modal\r\n );\r\n\r\n if (format12) {\r\n Manipulator.addClass(this._PM, this._classes.opacity);\r\n this._PM.setAttribute(ATTR_TIMEPICKER_ACTIVE, \"\");\r\n }\r\n\r\n this._hour.textContent = \"12\";\r\n this._minutes.textContent = \"00\";\r\n this._addActiveClassToTip(\r\n allTipsHours,\r\n Number(this._hour.textContent)\r\n );\r\n }\r\n\r\n this._handleSwitchTimeMode();\r\n this._handleOkButton();\r\n this._handleClose();\r\n\r\n if (inline) {\r\n this._handleHoverInlineBtn();\r\n this._handleDocumentClickInline();\r\n this._handleInlineClicks();\r\n } else {\r\n this._handleSwitchHourMinute();\r\n this._handleClockClick();\r\n this._handleKeyboard();\r\n\r\n // initial opacity on hour/minute mode fix\r\n const initActive = document.querySelector(\r\n `${SELECTOR_ATTR_TIMEPICKER_CURRENT}[${ATTR_TIMEPICKER_ACTIVE}]`\r\n );\r\n Manipulator.addClass(initActive, this._classes.opacity);\r\n\r\n Manipulator.addStyle(this._hour, {\r\n pointerEvents: \"none\",\r\n });\r\n Manipulator.addStyle(this._minutes, {\r\n pointerEvents: \"\",\r\n });\r\n }\r\n\r\n this._focusTrap = new FocusTrap(this._wrapper, {\r\n event: \"keydown\",\r\n condition: ({ key }) => key === \"Tab\",\r\n });\r\n this._focusTrap.trap();\r\n }, fixForInput);\r\n }\r\n );\r\n }\r\n\r\n _handleInlineClicks() {\r\n let selectedHour;\r\n let minuteNumber;\r\n const countMinutes = (count) => {\r\n let minutes = count;\r\n\r\n if (minutes > 59) {\r\n minutes = 0;\r\n } else if (minutes < 0) {\r\n minutes = 59;\r\n }\r\n\r\n return minutes;\r\n };\r\n\r\n const countHours = (count) => {\r\n let hour = count;\r\n\r\n if (this._options.format24) {\r\n if (hour > 24) {\r\n hour = 1;\r\n } else if (hour < 0) {\r\n hour = 23;\r\n }\r\n\r\n if (hour > 23) {\r\n hour = 0;\r\n }\r\n } else {\r\n if (hour > 12) {\r\n hour = 1;\r\n } else if (hour < 1) {\r\n hour = 12;\r\n }\r\n\r\n if (hour > 12) {\r\n hour = 1;\r\n }\r\n }\r\n\r\n return hour;\r\n };\r\n\r\n const incrementHours = (hour) => {\r\n const counteredNumber = countHours(hour);\r\n this._hour.textContent = this._setHourOrMinute(counteredNumber);\r\n };\r\n const incrementMinutes = (minutes) => {\r\n const counteredNumber = countMinutes(minutes);\r\n this._minutes.textContent = this._setHourOrMinute(counteredNumber);\r\n };\r\n\r\n const addHours = () => {\r\n selectedHour = countHours(selectedHour) + 1;\r\n incrementHours(selectedHour);\r\n };\r\n const addMinutes = () => {\r\n minuteNumber = countMinutes(minuteNumber) + 1;\r\n incrementMinutes(minuteNumber);\r\n };\r\n\r\n const subHours = () => {\r\n selectedHour = countHours(selectedHour) - 1;\r\n incrementHours(selectedHour);\r\n };\r\n\r\n const subMinutes = () => {\r\n minuteNumber = countMinutes(minuteNumber) - 1;\r\n incrementMinutes(minuteNumber);\r\n };\r\n\r\n const _clearAsyncs = () => {\r\n clearInterval(this._interval);\r\n clearTimeout(this._timeoutInterval);\r\n };\r\n\r\n const _clearAndSetThisInterval = (addHoursOrAddMinutes) => {\r\n _clearAsyncs();\r\n this._timeoutInterval = setTimeout(() => {\r\n this._interval = setInterval(addHoursOrAddMinutes, 100);\r\n }, 500);\r\n };\r\n EventHandlerMulti.on(\r\n this._modal,\r\n \"click mousedown mouseup touchstart touchend contextmenu\",\r\n `[${ATTR_TIMEPICKER_ICON_UP}], [${ATTR_TIMEPICKER_ICON_DOWN}]`,\r\n (e) => {\r\n selectedHour = Number(this._hour.textContent);\r\n minuteNumber = Number(this._minutes.textContent);\r\n const { target, type } = e;\r\n const isEventTypeMousedownOrTouchstart =\r\n type === \"mousedown\" || type === \"touchstart\";\r\n\r\n if (target.closest(`[${ATTR_TIMEPICKER_ICON_UP}]`)) {\r\n if (\r\n target\r\n .closest(`[${ATTR_TIMEPICKER_ICON_UP}]`)\r\n .parentNode.hasAttribute(ATTR_TIMEPICKER_ICONS_HOUR_INLINE)\r\n ) {\r\n if (isEventTypeMousedownOrTouchstart) {\r\n _clearAndSetThisInterval(addHours);\r\n } else if (\r\n type === \"mouseup\" ||\r\n type === \"touchend\" ||\r\n type === \"contextmenu\"\r\n ) {\r\n _clearAsyncs();\r\n } else {\r\n addHours();\r\n }\r\n } else {\r\n // eslint-disable-next-line no-lonely-if\r\n if (isEventTypeMousedownOrTouchstart) {\r\n _clearAndSetThisInterval(addMinutes);\r\n } else if (\r\n type === \"mouseup\" ||\r\n type === \"touchend\" ||\r\n type === \"contextmenu\"\r\n ) {\r\n _clearAsyncs();\r\n } else {\r\n addMinutes();\r\n }\r\n }\r\n } else if (target.closest(`[${ATTR_TIMEPICKER_ICON_DOWN}]`)) {\r\n if (\r\n target\r\n .closest(`[${ATTR_TIMEPICKER_ICON_DOWN}]`)\r\n .parentNode.hasAttribute(ATTR_TIMEPICKER_ICONS_HOUR_INLINE)\r\n ) {\r\n if (isEventTypeMousedownOrTouchstart) {\r\n _clearAndSetThisInterval(subHours);\r\n } else if (type === \"mouseup\" || type === \"touchend\") {\r\n _clearAsyncs();\r\n } else {\r\n subHours();\r\n }\r\n } else {\r\n // eslint-disable-next-line no-lonely-if\r\n if (isEventTypeMousedownOrTouchstart) {\r\n _clearAndSetThisInterval(subMinutes);\r\n } else if (type === \"mouseup\" || type === \"touchend\") {\r\n _clearAsyncs();\r\n } else {\r\n subMinutes();\r\n }\r\n }\r\n }\r\n }\r\n );\r\n EventHandler.on(window, EVENT_KEYDOWN_DATA_API, (e) => {\r\n const key = e.code;\r\n const isHourBtnFocused =\r\n document.activeElement.hasAttribute(ATTR_TIMEPICKER_HOUR);\r\n const isMinuteBtnFocused = document.activeElement.hasAttribute(\r\n ATTR_TIMEPICKER_MINUTE\r\n );\r\n const isBodyFocused = document.activeElement === document.body;\r\n\r\n selectedHour = Number(this._hour.textContent);\r\n minuteNumber = Number(this._minutes.textContent);\r\n\r\n switch (key) {\r\n case \"ArrowUp\":\r\n e.preventDefault();\r\n if (isBodyFocused || isHourBtnFocused) {\r\n this._hour.focus();\r\n addHours();\r\n } else if (isMinuteBtnFocused) {\r\n addMinutes();\r\n }\r\n break;\r\n case \"ArrowDown\":\r\n e.preventDefault();\r\n if (isBodyFocused || isHourBtnFocused) {\r\n this._hour.focus();\r\n subHours();\r\n } else if (isMinuteBtnFocused) {\r\n subMinutes();\r\n }\r\n break;\r\n default:\r\n break;\r\n }\r\n });\r\n }\r\n\r\n _handleClose() {\r\n EventHandler.on(\r\n this._modal,\r\n \"click\",\r\n `[${ATTR_TIMEPICKER_WRAPPER}], [${ATTR_TIMEPICKER_BUTTON_CANCEL}], [${ATTR_TIMEPICKER_BUTTON_CLEAR}]`,\r\n ({ target }) => {\r\n const { closeModalOnBackdropClick } = this._options;\r\n\r\n const runRemoveFunction = () => {\r\n Manipulator.addStyle(this.elementToggle, {\r\n pointerEvents: \"auto\",\r\n });\r\n\r\n if (this._animations) {\r\n this._toggleBackdropAnimation(true);\r\n }\r\n\r\n this._removeModal();\r\n this._focusTrap?.disable();\r\n this._focusTrap = null;\r\n\r\n if (this.elementToggle) {\r\n this.elementToggle.focus();\r\n } else if (this.input) {\r\n this.input.focus();\r\n }\r\n };\r\n\r\n if (target.hasAttribute(ATTR_TIMEPICKER_BUTTON_CLEAR)) {\r\n this._toggleAmPm(\"PM\");\r\n this.input.value = \"\";\r\n this.input.removeAttribute(ATTR_TIMEPICKER_ACTIVE);\r\n\r\n let checkInputValue;\r\n\r\n if (takeValue(this.input)[0] === \"\") {\r\n checkInputValue = [\"12\", \"00\", \"PM\"];\r\n } else {\r\n checkInputValue = takeValue(this.input);\r\n }\r\n\r\n const [hour, minute, format] = checkInputValue;\r\n this._setTipsAndTimesDependOnInputValue(\"12\", \"00\");\r\n this._setActiveClassToTipsOnOpen(hour, minute, format);\r\n this._hour.click();\r\n } else if (\r\n target.hasAttribute(ATTR_TIMEPICKER_BUTTON_CANCEL) ||\r\n target.hasAttribute(ATTR_TIMEPICKER_BUTTON_SUBMIT)\r\n ) {\r\n runRemoveFunction();\r\n } else if (\r\n target.hasAttribute(ATTR_TIMEPICKER_WRAPPER) &&\r\n closeModalOnBackdropClick\r\n ) {\r\n runRemoveFunction();\r\n }\r\n }\r\n );\r\n }\r\n\r\n showValueInput() {\r\n return this.input.value;\r\n }\r\n\r\n _handleOkButton() {\r\n EventHandlerMulti.on(\r\n this._modal,\r\n \"click\",\r\n `[${ATTR_TIMEPICKER_BUTTON_SUBMIT}]`,\r\n () => {\r\n let { maxTime, minTime } = this._options;\r\n const {\r\n format12,\r\n format24,\r\n readOnly,\r\n focusInputAfterApprove,\r\n disablePast,\r\n disableFuture,\r\n } = this._options;\r\n const hourModeActive = this._document.querySelector(\r\n `${SELECTOR_ATTR_TIMEPICKER_HOUR_MODE}[${ATTR_TIMEPICKER_ACTIVE}]`\r\n );\r\n\r\n const currentValue = `${this._hour.textContent}:${this._minutes.textContent}`;\r\n const selectedHourContent = Number(this._hour.textContent);\r\n const selectedHour =\r\n selectedHourContent === 12 && format12 ? 0 : selectedHourContent;\r\n const selectedMinutes = Number(this._minutes.textContent);\r\n\r\n minTime = setMinTime(minTime, disablePast, format12);\r\n maxTime = setMaxTime(maxTime, disableFuture, format12);\r\n\r\n let [maxTimeHour, maxTimeMinutes, maxTimeFormat] = takeValue(\r\n maxTime,\r\n false\r\n );\r\n let [minTimeHour, minTimeMinutes, minTimeFormat] = takeValue(\r\n minTime,\r\n false\r\n );\r\n\r\n minTimeHour = minTimeHour === \"12\" && format12 ? \"00\" : minTimeHour;\r\n maxTimeHour = maxTimeHour === \"12\" && format12 ? \"00\" : maxTimeHour;\r\n\r\n const isHourLessThanMinHour = selectedHour < Number(minTimeHour);\r\n const isHourGreaterThanMaxHour = selectedHour > Number(maxTimeHour);\r\n let maxFormatAndCurrentFormatEqual = true;\r\n if (hourModeActive) {\r\n maxFormatAndCurrentFormatEqual =\r\n maxTimeFormat === hourModeActive.textContent;\r\n }\r\n\r\n let minFormatAndCurrentFormatEqual = true;\r\n if (hourModeActive) {\r\n minFormatAndCurrentFormatEqual =\r\n minTimeFormat === hourModeActive.textContent;\r\n }\r\n\r\n const hourEqualToMaxAndMinutesGreaterThanMax =\r\n selectedMinutes > maxTimeMinutes &&\r\n selectedHour === Number(maxTimeHour);\r\n const hourEqualToMinAndMinutesLessThanMin =\r\n selectedMinutes < minTimeMinutes &&\r\n selectedHour === Number(minTimeHour);\r\n\r\n this.input.setAttribute(ATTR_TIMEPICKER_ACTIVE, \"\");\r\n Manipulator.addStyle(this.elementToggle, {\r\n pointerEvents: \"auto\",\r\n });\r\n\r\n if (maxTime !== \"\") {\r\n if (\r\n maxFormatAndCurrentFormatEqual &&\r\n (isHourGreaterThanMaxHour || hourEqualToMaxAndMinutesGreaterThanMax)\r\n ) {\r\n return;\r\n } else if (\r\n maxTimeFormat === \"AM\" &&\r\n hourModeActive.textContent === \"PM\"\r\n ) {\r\n return;\r\n }\r\n }\r\n if (minTime !== \"\") {\r\n if (\r\n minFormatAndCurrentFormatEqual &&\r\n (isHourLessThanMinHour || hourEqualToMinAndMinutesLessThanMin)\r\n ) {\r\n return;\r\n }\r\n if (minTimeFormat === \"PM\" && hourModeActive.textContent === \"AM\") {\r\n return;\r\n }\r\n }\r\n\r\n if (\r\n checkValueBeforeAccept(\r\n this._options,\r\n this.input,\r\n this._hour.textContent\r\n ) === undefined\r\n ) {\r\n return;\r\n }\r\n\r\n if (this._isInvalidTimeFormat) {\r\n this.input.removeAttribute(ATTR_TIMEPICKER_IS_INVALID);\r\n }\r\n\r\n if (!readOnly && focusInputAfterApprove) {\r\n this.input.focus();\r\n }\r\n\r\n Manipulator.addStyle(this.elementToggle, {\r\n pointerEvents: \"auto\",\r\n });\r\n\r\n if (format24) {\r\n this.input.value = currentValue;\r\n } else if (hourModeActive === null) {\r\n this.input.value = `${currentValue} PM`;\r\n } else {\r\n this.input.value = `${currentValue} ${hourModeActive.textContent}`;\r\n }\r\n\r\n if (this._animations) {\r\n this._toggleBackdropAnimation(true);\r\n }\r\n\r\n this._removeModal();\r\n\r\n EventHandler.trigger(this.input, \"input.te.timepicker\");\r\n EventHandler.trigger(this.input, \"input\");\r\n }\r\n );\r\n }\r\n\r\n _handleHoverInlineBtn() {\r\n EventHandlerMulti.on(\r\n this._modal,\r\n \"mouseover mouseleave\",\r\n `[${ATTR_TIMEPICKER_CURRENT_INLINE}]`,\r\n ({ type, target }) => {\r\n const allIconsInlineHour = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_ICON_INLINE_HOUR}]`,\r\n this._modal\r\n );\r\n const allIconsInlineMinute = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_ICON_INLINE_MINUTE}]`,\r\n this._modal\r\n );\r\n\r\n const modifyIcons = (elements, shouldAdd) => {\r\n return elements.forEach((icon) => {\r\n if (shouldAdd) {\r\n Manipulator.addClass(icon, this._classes.opacity);\r\n icon.setAttribute(ATTR_TIMEPICKER_ACTIVE, \"\");\r\n return;\r\n }\r\n\r\n Manipulator.removeClass(icon, this._classes.opacity);\r\n icon.removeAttribute(ATTR_TIMEPICKER_ACTIVE);\r\n });\r\n };\r\n\r\n const pickerHasHourAttr = target.hasAttribute(ATTR_TIMEPICKER_HOUR);\r\n const iconElements = pickerHasHourAttr\r\n ? allIconsInlineHour\r\n : allIconsInlineMinute;\r\n\r\n modifyIcons(iconElements, type === \"mouseover\");\r\n }\r\n );\r\n }\r\n\r\n _handleDocumentClickInline() {\r\n EventHandler.on(document, EVENT_CLICK_DATA_API, ({ target }) => {\r\n if (\r\n this._modal &&\r\n !this._modal.contains(target) &&\r\n !target.hasAttribute(ATTR_TIMEPICKER_ICON)\r\n ) {\r\n clearInterval(this._interval);\r\n Manipulator.addStyle(this.elementToggle, {\r\n pointerEvents: \"auto\",\r\n });\r\n this._removeModal();\r\n\r\n if (!this._animations) return;\r\n\r\n this._toggleBackdropAnimation(true);\r\n }\r\n });\r\n }\r\n\r\n _handleSwitchHourMinute() {\r\n toggleClassHandler(\r\n \"click\",\r\n SELECTOR_ATTR_TIMEPICKER_CURRENT,\r\n this._classes\r\n );\r\n\r\n EventHandler.on(\r\n this._modal,\r\n \"click\",\r\n SELECTOR_ATTR_TIMEPICKER_CURRENT,\r\n () => {\r\n const { format24 } = this._options;\r\n const current = SelectorEngine.find(\r\n SELECTOR_ATTR_TIMEPICKER_CURRENT,\r\n this._modal\r\n );\r\n const allTipsMinutes = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_TIPS_MINUTES}]`,\r\n this._modal\r\n );\r\n const allTipsHours = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_TIPS_HOURS}]`,\r\n this._modal\r\n );\r\n const allInnerTips = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_INNER_HOURS}]`,\r\n this._modal\r\n );\r\n const hourValue = Number(this._hour.textContent);\r\n const minuteValue = Number(this._minutes.textContent);\r\n\r\n const switchTips = (array, classes) => {\r\n allTipsHours.forEach((tip) => tip.remove());\r\n allTipsMinutes.forEach((tip) => tip.remove());\r\n Manipulator.addClass(this._hand, this._classes.transform);\r\n\r\n setTimeout(() => {\r\n Manipulator.removeClass(this._hand, this._classes.transform);\r\n }, 401);\r\n\r\n this._getAppendClock(array, `[${ATTR_TIMEPICKER_CLOCK}]`, classes);\r\n\r\n const toggleActiveClass = () => {\r\n const allTipsHours = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_TIPS_HOURS}]`,\r\n this._modal\r\n );\r\n const allTipsMinutes = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_TIPS_MINUTES}]`,\r\n this._modal\r\n );\r\n\r\n this._addActiveClassToTip(allTipsHours, hourValue);\r\n this._addActiveClassToTip(allTipsMinutes, minuteValue);\r\n };\r\n\r\n if (!format24) {\r\n setTimeout(() => {\r\n toggleActiveClass();\r\n }, 401);\r\n } else {\r\n const allTipsInnerHours = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_INNER_HOURS}]`,\r\n this._modal\r\n );\r\n\r\n setTimeout(() => {\r\n this._addActiveClassToTip(allTipsInnerHours, hourValue);\r\n toggleActiveClass();\r\n }, 401);\r\n }\r\n };\r\n\r\n current.forEach((e) => {\r\n if (e.hasAttribute(ATTR_TIMEPICKER_ACTIVE)) {\r\n if (e.hasAttribute(ATTR_TIMEPICKER_MINUTE)) {\r\n Manipulator.addClass(this._hand, this._classes.transform);\r\n\r\n Manipulator.addStyle(this._hand, {\r\n transform: `rotateZ(${this._minutes.textContent * 6}deg)`,\r\n height: \"calc(40% + 1px)\",\r\n });\r\n\r\n if (format24 && allInnerTips.length > 0) {\r\n allInnerTips.forEach((innerTip) => innerTip.remove());\r\n }\r\n switchTips(\r\n this.minutesArray,\r\n ATTR_TIMEPICKER_TIPS_MINUTES,\r\n allTipsMinutes\r\n );\r\n this._hour.style.pointerEvents = \"\";\r\n this._minutes.style.pointerEvents = \"none\";\r\n } else if (e.hasAttribute(ATTR_TIMEPICKER_HOUR)) {\r\n Manipulator.addStyle(this._hand, {\r\n transform: `rotateZ(${this._hour.textContent * 30}deg)`,\r\n });\r\n\r\n if (Number(this._hour.textContent) > 12) {\r\n Manipulator.addStyle(this._hand, {\r\n transform: `rotateZ(${this._hour.textContent * 30 - 360}deg)`,\r\n height: \"21.5%\",\r\n });\r\n\r\n if (Number(this._hour.textContent) > 12) {\r\n Manipulator.addStyle(this._hand, {\r\n height: \"21.5%\",\r\n });\r\n }\r\n } else {\r\n Manipulator.addStyle(this._hand, {\r\n height: \"calc(40% + 1px)\",\r\n });\r\n }\r\n\r\n if (format24) {\r\n this._getAppendClock(\r\n this.innerHours,\r\n `[${ATTR_TIMEPICKER_CLOCK_INNER}]`,\r\n ATTR_TIMEPICKER_INNER_HOURS\r\n );\r\n }\r\n\r\n if (allInnerTips.length > 0) {\r\n allInnerTips.forEach((innerTip) => innerTip.remove());\r\n }\r\n\r\n switchTips(\r\n this.hoursArray,\r\n ATTR_TIMEPICKER_TIPS_HOURS,\r\n allTipsHours\r\n );\r\n\r\n Manipulator.addStyle(this._hour, {\r\n pointerEvents: \"none\",\r\n });\r\n Manipulator.addStyle(this._minutes, {\r\n pointerEvents: \"\",\r\n });\r\n }\r\n }\r\n });\r\n }\r\n );\r\n }\r\n\r\n _handleDisablingTipsMaxTime(\r\n selectedFormat,\r\n maxTimeFormat,\r\n maxTimeMinutes,\r\n maxTimeHour\r\n ) {\r\n if (!this._options.maxTime && !this._options.disableFuture) {\r\n return;\r\n }\r\n\r\n const outerHoursTips = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_TIPS_HOURS}]`\r\n );\r\n const innerHoursTips = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_INNER_HOURS}]`\r\n );\r\n const allTipsMinutes = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_TIPS_MINUTES}]`\r\n );\r\n\r\n if (!maxTimeFormat || maxTimeFormat === selectedFormat) {\r\n _verifyMaxTimeHourAndAddDisabledClass(\r\n innerHoursTips,\r\n maxTimeHour,\r\n this._classes,\r\n this._options.format12\r\n );\r\n _verifyMaxTimeHourAndAddDisabledClass(\r\n outerHoursTips,\r\n maxTimeHour,\r\n this._classes,\r\n this._options.format12\r\n );\r\n _verifyMaxTimeMinutesTipsAndAddDisabledClass(\r\n allTipsMinutes,\r\n maxTimeMinutes,\r\n maxTimeHour,\r\n this._hour.textContent,\r\n this._classes,\r\n this._options.format12\r\n );\r\n return;\r\n }\r\n if (maxTimeFormat === \"AM\" && selectedFormat === \"PM\") {\r\n outerHoursTips.forEach((tip) => {\r\n Manipulator.addClass(tip, this._classes.tipsDisabled);\r\n tip.setAttribute(ATTR_TIMEPICKER_DISABLED, \"\");\r\n });\r\n allTipsMinutes.forEach((tip) => {\r\n Manipulator.addClass(tip, this._classes.tipsDisabled);\r\n tip.setAttribute(ATTR_TIMEPICKER_DISABLED, \"\");\r\n });\r\n }\r\n }\r\n\r\n _handleDisablingTipsMinTime(\r\n selectedFormat,\r\n minTimeFormat,\r\n minTimeMinutes,\r\n minTimeHour\r\n ) {\r\n if (!this._options.minTime && !this._options.disablePast) {\r\n return;\r\n }\r\n\r\n const outerHoursTips = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_TIPS_HOURS}]`\r\n );\r\n const innerHoursTips = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_INNER_HOURS}]`\r\n );\r\n const allTipsMinutes = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_TIPS_MINUTES}]`\r\n );\r\n\r\n if (!minTimeFormat || minTimeFormat === selectedFormat) {\r\n _verifyMinTimeHourAndAddDisabledClass(\r\n outerHoursTips,\r\n minTimeHour,\r\n this._classes,\r\n this._options.format12\r\n );\r\n _verifyMinTimeHourAndAddDisabledClass(\r\n innerHoursTips,\r\n minTimeHour,\r\n this._classes,\r\n this._options.format12\r\n );\r\n _verifyMinTimeMinutesTipsAndAddDisabledClass(\r\n allTipsMinutes,\r\n minTimeMinutes,\r\n minTimeHour,\r\n this._hour.textContent,\r\n this._classes,\r\n this._options.format12\r\n );\r\n } else if (minTimeFormat === \"PM\" && selectedFormat === \"AM\") {\r\n outerHoursTips.forEach((tip) => {\r\n Manipulator.addClass(tip, this._classes.tipsDisabled);\r\n tip.setAttribute(ATTR_TIMEPICKER_DISABLED, \"\");\r\n });\r\n allTipsMinutes.forEach((tip) => {\r\n Manipulator.addClass(tip, this._classes.tipsDisabled);\r\n tip.setAttribute(ATTR_TIMEPICKER_DISABLED, \"\");\r\n });\r\n }\r\n }\r\n\r\n _toggleAmPm = (enabled) => {\r\n if (enabled === \"PM\") {\r\n this._isPmEnabled = true;\r\n this._isAmEnabled = false;\r\n } else if (enabled === \"AM\") {\r\n this._isPmEnabled = false;\r\n this._isAmEnabled = true;\r\n }\r\n };\r\n\r\n _handleSwitchTimeMode() {\r\n EventHandler.on(\r\n document,\r\n \"click\",\r\n SELECTOR_ATTR_TIMEPICKER_HOUR_MODE,\r\n ({ target }) => {\r\n let { maxTime, minTime } = this._options;\r\n const { disablePast, disableFuture, format12 } = this._options;\r\n\r\n minTime = setMinTime(minTime, disablePast, format12);\r\n maxTime = setMaxTime(maxTime, disableFuture, format12);\r\n\r\n const [maxTimeHour, maxTimeMinutes, maxTimeFormat] = takeValue(\r\n maxTime,\r\n false\r\n );\r\n const [minTimeHour, minTimeMinutes, minTimeFormat] = takeValue(\r\n minTime,\r\n false\r\n );\r\n\r\n const allTipsHour = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_TIPS_HOURS}]`\r\n );\r\n const allTipsMinutes = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_TIPS_MINUTES}]`\r\n );\r\n\r\n const clearDisabledClassForAllTips = () => {\r\n allTipsHour.forEach((tip) => {\r\n Manipulator.removeClass(tip, this._classes.tipsDisabled);\r\n tip.removeAttribute(ATTR_TIMEPICKER_DISABLED);\r\n });\r\n\r\n allTipsMinutes.forEach((tip) => {\r\n Manipulator.removeClass(tip, this._classes.tipsDisabled);\r\n tip.removeAttribute(ATTR_TIMEPICKER_DISABLED);\r\n });\r\n };\r\n\r\n clearDisabledClassForAllTips();\r\n this._handleDisablingTipsMinTime(\r\n target.textContent,\r\n minTimeFormat,\r\n minTimeMinutes,\r\n minTimeHour\r\n );\r\n this._handleDisablingTipsMaxTime(\r\n target.textContent,\r\n maxTimeFormat,\r\n maxTimeMinutes,\r\n maxTimeHour\r\n );\r\n this._toggleAmPm(target.textContent);\r\n if (!target.hasAttribute(ATTR_TIMEPICKER_ACTIVE)) {\r\n const allHoursMode = SelectorEngine.find(\r\n SELECTOR_ATTR_TIMEPICKER_HOUR_MODE\r\n );\r\n\r\n allHoursMode.forEach((element) => {\r\n if (element.hasAttribute(ATTR_TIMEPICKER_ACTIVE)) {\r\n Manipulator.removeClass(element, this._classes.opacity);\r\n element.removeAttribute(ATTR_TIMEPICKER_ACTIVE);\r\n }\r\n });\r\n\r\n Manipulator.addClass(target, this._classes.opacity);\r\n target.setAttribute(ATTR_TIMEPICKER_ACTIVE, \"\");\r\n }\r\n }\r\n );\r\n }\r\n\r\n _handleClockClick() {\r\n let { maxTime, minTime } = this._options;\r\n const { disablePast, disableFuture, format12 } = this._options;\r\n\r\n minTime = setMinTime(minTime, disablePast, format12);\r\n maxTime = setMaxTime(maxTime, disableFuture, format12);\r\n\r\n const maxTimeFormat = takeValue(maxTime, false)[2];\r\n const minTimeFormat = takeValue(minTime, false)[2];\r\n\r\n const maxTimeHour = takeValue(maxTime, false)[0];\r\n const minTimeHour = takeValue(minTime, false)[0];\r\n\r\n const clockWrapper = SelectorEngine.findOne(\r\n `[${ATTR_TIMEPICKER_CLOCK_WRAPPER}]`\r\n );\r\n EventHandlerMulti.on(\r\n document,\r\n `${EVENT_MOUSEDOWN_DATA_API} ${EVENT_MOUSEUP_DATA_API} ${EVENT_MOUSEMOVE_DATA_API} ${EVENT_MOUSELEAVE_DATA_API} ${EVENT_MOUSEOVER_DATA_API} ${EVENT_TOUCHSTART_DATA_API} ${EVENT_TOUCHMOVE_DATA_API} ${EVENT_TOUCHEND_DATA_API}`,\r\n \"\",\r\n (e) => {\r\n if (!checkBrowser()) {\r\n e.preventDefault();\r\n }\r\n\r\n const { type, target } = e;\r\n const { closeModalOnMinutesClick, switchHoursToMinutesOnClick } =\r\n this._options;\r\n const minutes =\r\n SelectorEngine.findOne(\r\n `[${ATTR_TIMEPICKER_TIPS_MINUTES}]`,\r\n this._modal\r\n ) !== null;\r\n const hours =\r\n SelectorEngine.findOne(\r\n `[${ATTR_TIMEPICKER_TIPS_HOURS}]`,\r\n this._modal\r\n ) !== null;\r\n const innerHours =\r\n SelectorEngine.findOne(\r\n `[${ATTR_TIMEPICKER_INNER_HOURS}]`,\r\n this._modal\r\n ) !== null;\r\n\r\n const allTipsMinutes = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_TIPS_MINUTES}]`,\r\n this._modal\r\n );\r\n\r\n const mouseClick = findMousePosition(e, clockWrapper);\r\n const radius = clockWrapper.offsetWidth / 2;\r\n\r\n let rds = Math.atan2(mouseClick.y - radius, mouseClick.x - radius);\r\n if (checkBrowser()) {\r\n const touchClick = findMousePosition(e, clockWrapper, true);\r\n rds = Math.atan2(touchClick.y - radius, touchClick.x - radius);\r\n }\r\n\r\n let xPos = null;\r\n let yPos = null;\r\n let elFromPoint = null;\r\n\r\n if (\r\n type === \"mousedown\" ||\r\n type === \"mousemove\" ||\r\n type === \"touchmove\" ||\r\n type === \"touchstart\"\r\n ) {\r\n if (\r\n type === \"mousedown\" ||\r\n type === \"touchstart\" ||\r\n type === \"touchmove\"\r\n ) {\r\n if (\r\n this._hasTargetInnerClass(target) ||\r\n target.hasAttribute(ATTR_TIMEPICKER_CLOCK_WRAPPER) ||\r\n target.hasAttribute(ATTR_TIMEPICKER_CLOCK) ||\r\n target.hasAttribute(ATTR_TIMEPICKER_TIPS_MINUTES) ||\r\n target.hasAttribute(ATTR_TIMEPICKER_TIPS_HOURS) ||\r\n target.hasAttribute(ATTR_TIMEPICKER_CIRCLE) ||\r\n target.hasAttribute(ATTR_TIMEPICKER_HAND_POINTER) ||\r\n target.hasAttribute(ATTR_TIMEPICKER_MIDDLE_DOT) ||\r\n target.hasAttribute(ATTR_TIMEPICKER_TIPS_ELEMENT)\r\n ) {\r\n this._isMouseMove = true;\r\n\r\n if (checkBrowser() && e.touches) {\r\n xPos = e.touches[0].clientX;\r\n yPos = e.touches[0].clientY;\r\n elFromPoint = document.elementFromPoint(xPos, yPos);\r\n }\r\n }\r\n }\r\n } else if (type === \"mouseup\" || type === \"touchend\") {\r\n this._isMouseMove = false;\r\n\r\n if (\r\n this._hasTargetInnerClass(target) ||\r\n target.hasAttribute(ATTR_TIMEPICKER_CLOCK) ||\r\n target.hasAttribute(ATTR_TIMEPICKER_TIPS_HOURS) ||\r\n target.hasAttribute(ATTR_TIMEPICKER_CIRCLE) ||\r\n target.hasAttribute(ATTR_TIMEPICKER_HAND_POINTER) ||\r\n target.hasAttribute(ATTR_TIMEPICKER_MIDDLE_DOT) ||\r\n target.hasAttribute(ATTR_TIMEPICKER_TIPS_ELEMENT)\r\n ) {\r\n if ((hours || innerHours) && switchHoursToMinutesOnClick) {\r\n const isHourlessThanMinOrGreaterThanMax =\r\n Number(this._hour.textContent) > maxTimeHour ||\r\n Number(this._hour.textContent) < minTimeHour;\r\n if (\r\n this._options.format24 &&\r\n maxTimeHour !== \"\" &&\r\n minTimeHour !== \"\" &&\r\n isHourlessThanMinOrGreaterThanMax\r\n ) {\r\n return;\r\n } else if (\r\n this._options.format24 &&\r\n minTimeHour !== \"\" &&\r\n Number(this._hour.textContent) < minTimeHour\r\n ) {\r\n return;\r\n }\r\n }\r\n EventHandler.trigger(this._minutes, \"click\");\r\n }\r\n\r\n if (minutes && closeModalOnMinutesClick) {\r\n const submitBtn = SelectorEngine.findOne(\r\n `[${ATTR_TIMEPICKER_BUTTON_SUBMIT}]`,\r\n this._modal\r\n );\r\n EventHandler.trigger(submitBtn, \"click\");\r\n }\r\n }\r\n\r\n if (minutes) {\r\n let minute;\r\n\r\n const degrees = Math.trunc((rds * 180) / Math.PI) + 90;\r\n\r\n const { degrees: minDegrees, minute: minTimeObj } =\r\n this._makeMinutesDegrees(degrees, minute);\r\n\r\n if (\r\n this._handlerMaxMinMinutesOptions(minDegrees, minTimeObj) ===\r\n undefined\r\n ) {\r\n return;\r\n }\r\n\r\n const { degrees: _degrees, minute: minuteTimes } =\r\n this._handlerMaxMinMinutesOptions(minDegrees, minTimeObj);\r\n\r\n if (this._isMouseMove) {\r\n Manipulator.addStyle(this._hand, {\r\n transform: `rotateZ(${_degrees}deg)`,\r\n });\r\n\r\n if (minuteTimes === undefined) {\r\n return;\r\n }\r\n\r\n const changeMinutes = () => {\r\n return minuteTimes >= 10 || minuteTimes === \"00\"\r\n ? minuteTimes\r\n : `0${minuteTimes}`;\r\n };\r\n\r\n this._minutes.textContent = changeMinutes();\r\n\r\n this._toggleClassActive(\r\n this.minutesArray,\r\n this._minutes,\r\n allTipsMinutes\r\n );\r\n this._toggleBackgroundColorCircle(\r\n `[${ATTR_TIMEPICKER_TIPS_MINUTES}]`\r\n );\r\n\r\n this._objWithDataOnChange.degreesMinutes = _degrees;\r\n this._objWithDataOnChange.minutes = minuteTimes;\r\n }\r\n }\r\n\r\n if (hours || innerHours) {\r\n let hour;\r\n\r\n let degrees = Math.trunc((rds * 180) / Math.PI) + 90;\r\n degrees = Math.round(degrees / 30) * 30;\r\n\r\n Manipulator.addStyle(this._circle, {\r\n backgroundColor: \"#1976d2\",\r\n });\r\n if (this._makeHourDegrees(target, degrees, hour) === undefined) {\r\n return;\r\n }\r\n const makeDegrees = () => {\r\n if (checkBrowser() && degrees && elFromPoint) {\r\n const { degrees: touchDegrees, hour: touchHours } =\r\n this._makeHourDegrees(elFromPoint, degrees, hour);\r\n\r\n return this._handleMoveHand(\r\n elFromPoint,\r\n touchHours,\r\n touchDegrees\r\n );\r\n } else {\r\n const { degrees: movedDegrees, hour: movedHours } =\r\n this._makeHourDegrees(target, degrees, hour);\r\n\r\n return this._handleMoveHand(target, movedHours, movedDegrees);\r\n }\r\n };\r\n\r\n this._objWithDataOnChange.degreesHours = degrees;\r\n\r\n if (\r\n this._handlerMaxMinHoursOptions(\r\n degrees,\r\n maxTimeHour,\r\n minTimeHour,\r\n maxTimeFormat,\r\n minTimeFormat,\r\n e\r\n )\r\n ) {\r\n makeDegrees();\r\n }\r\n }\r\n\r\n e.stopPropagation();\r\n }\r\n );\r\n }\r\n\r\n _hasTargetInnerClass(target) {\r\n return (\r\n target.hasAttribute(ATTR_TIMEPICKER_CLOCK_INNER) ||\r\n target.hasAttribute(ATTR_TIMEPICKER_INNER_HOURS) ||\r\n target.hasAttribute(ATTR_TIMEPICKER_TIPS_INNER_ELEMENT)\r\n );\r\n }\r\n\r\n _handleMoveHand(target, hour, degrees) {\r\n const allTipsHours = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_TIPS_HOURS}]`,\r\n this._modal\r\n );\r\n const allTipsInner = SelectorEngine.find(\r\n `[${ATTR_TIMEPICKER_INNER_HOURS}]`,\r\n this._modal\r\n );\r\n\r\n if (!this._isMouseMove) return;\r\n\r\n if (this._hasTargetInnerClass(target)) {\r\n Manipulator.addStyle(this._hand, {\r\n height: \"21.5%\",\r\n });\r\n } else {\r\n Manipulator.addStyle(this._hand, {\r\n height: \"calc(40% + 1px)\",\r\n });\r\n }\r\n\r\n Manipulator.addStyle(this._hand, {\r\n transform: `rotateZ(${degrees}deg)`,\r\n });\r\n\r\n this._hour.textContent = hour >= 10 || hour === \"00\" ? hour : `0${hour}`;\r\n\r\n this._toggleClassActive(this.hoursArray, this._hour, allTipsHours);\r\n this._toggleClassActive(this.innerHours, this._hour, allTipsInner);\r\n\r\n this._objWithDataOnChange.hour =\r\n hour >= 10 || hour === \"00\" ? hour : `0${hour}`;\r\n }\r\n\r\n _handlerMaxMinMinutesOptions(degrees, minute) {\r\n let { maxTime, minTime } = this._options;\r\n const { format12, increment, disablePast, disableFuture } = this._options;\r\n\r\n minTime = setMinTime(minTime, disablePast, format12);\r\n maxTime = setMaxTime(maxTime, disableFuture, format12);\r\n\r\n const maxMin = takeValue(maxTime, false)[1];\r\n const minMin = takeValue(minTime, false)[1];\r\n const maxHourTimeValue = takeValue(maxTime, false)[0];\r\n const minHourTimeValue = takeValue(minTime, false)[0];\r\n const minHourTime =\r\n minHourTimeValue === \"12\" && format12 ? \"0\" : minHourTimeValue;\r\n const maxHourTime =\r\n maxHourTimeValue === \"12\" && format12 ? \"0\" : maxHourTimeValue;\r\n\r\n const maxTimeFormat = takeValue(maxTime, false)[2];\r\n const minTimeFormat = takeValue(minTime, false)[2];\r\n\r\n const maxMinDegrees = maxMin !== \"\" ? maxMin * 6 : \"\";\r\n const minMinDegrees = minMin !== \"\" ? minMin * 6 : \"\";\r\n\r\n const selectedHourContent = Number(this._hour.textContent);\r\n const selectedHour =\r\n selectedHourContent === 12 && format12 ? 0 : selectedHourContent;\r\n\r\n if (!maxTimeFormat && !minTimeFormat) {\r\n if (maxTime !== \"\" && minTime !== \"\") {\r\n if (\r\n (Number(maxHourTime) === selectedHour && degrees > maxMinDegrees) ||\r\n (Number(minHourTime) === selectedHour && degrees < minMinDegrees)\r\n ) {\r\n return degrees;\r\n }\r\n } else if (minTime !== \"\" && selectedHour <= Number(minHourTime)) {\r\n if (degrees <= minMinDegrees - 6) {\r\n return degrees;\r\n }\r\n } else if (maxTime !== \"\" && selectedHour >= Number(maxHourTime)) {\r\n if (degrees >= maxMinDegrees + 6) {\r\n return degrees;\r\n }\r\n }\r\n } else {\r\n // eslint-disable-next-line no-lonely-if\r\n if (minTime !== \"\") {\r\n if (minTimeFormat === \"PM\" && this._isAmEnabled) {\r\n return;\r\n }\r\n\r\n if (minTimeFormat === \"PM\" && this._isPmEnabled) {\r\n if (selectedHour < Number(minHourTime)) {\r\n return;\r\n }\r\n\r\n if (selectedHour <= Number(minHourTime)) {\r\n if (degrees <= minMinDegrees - 6) {\r\n return degrees;\r\n }\r\n }\r\n } else if (minTimeFormat === \"AM\" && this._isAmEnabled) {\r\n if (selectedHour < Number(minHourTime)) {\r\n return;\r\n }\r\n\r\n if (selectedHour <= Number(minHourTime)) {\r\n if (degrees <= minMinDegrees - 6) {\r\n return degrees;\r\n }\r\n }\r\n }\r\n }\r\n if (maxTime !== \"\") {\r\n if (maxTimeFormat === \"AM\" && this._isPmEnabled) {\r\n return;\r\n }\r\n\r\n if (maxTimeFormat === \"PM\" && this._isPmEnabled) {\r\n if (selectedHour >= Number(maxHourTime)) {\r\n if (degrees >= maxMinDegrees + 6) {\r\n return degrees;\r\n }\r\n }\r\n } else if (maxTimeFormat === \"AM\" && this._isAmEnabled) {\r\n if (selectedHour >= Number(maxHourTime)) {\r\n if (degrees >= maxMinDegrees + 6) {\r\n return degrees;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (increment) {\r\n degrees = Math.round(degrees / 30) * 30;\r\n }\r\n\r\n if (degrees < 0) {\r\n degrees = 360 + degrees;\r\n } else if (degrees >= 360) {\r\n degrees = 0;\r\n }\r\n\r\n return {\r\n degrees,\r\n minute,\r\n };\r\n }\r\n\r\n _removeModal() {\r\n if (this._animations) {\r\n setTimeout(() => {\r\n this._removeModalElements();\r\n this._scrollBar.reset();\r\n }, 300);\r\n } else {\r\n this._removeModalElements();\r\n this._scrollBar.reset();\r\n }\r\n\r\n EventHandlerMulti.off(\r\n this._document,\r\n `${EVENT_CLICK_DATA_API} ${EVENT_KEYDOWN_DATA_API} ${EVENT_MOUSEDOWN_DATA_API} ${EVENT_MOUSEUP_DATA_API} ${EVENT_MOUSEMOVE_DATA_API} ${EVENT_MOUSELEAVE_DATA_API} ${EVENT_MOUSEOVER_DATA_API} ${EVENT_TOUCHSTART_DATA_API} ${EVENT_TOUCHMOVE_DATA_API} ${EVENT_TOUCHEND_DATA_API}`\r\n );\r\n EventHandler.off(window, EVENT_KEYDOWN_DATA_API);\r\n }\r\n\r\n _removeModalElements() {\r\n if (this._modal) this._modal.remove();\r\n }\r\n\r\n _toggleBackdropAnimation(isToRemove = false) {\r\n if (isToRemove) {\r\n this._wrapper.classList.add(\"animate-[fade-out_350ms_ease-in-out]\");\r\n } else {\r\n this._wrapper.classList.add(\"animate-[fade-in_350ms_ease-in-out]\");\r\n\r\n if (!this._options.inline)\r\n Manipulator.addClass(this._clock, this._classes.clockAnimation);\r\n }\r\n\r\n setTimeout(() => {\r\n this._wrapper.classList.remove(\r\n \"animate-[fade-out_350ms_ease-in-out]\",\r\n \"animate-[fade-in_350ms_ease-in-out]\"\r\n );\r\n }, 351);\r\n }\r\n\r\n _toggleBackgroundColorCircle = (classes) => {\r\n const tips =\r\n this._modal.querySelector(`${classes}[${ATTR_TIMEPICKER_ACTIVE}]`) !==\r\n null;\r\n if (tips) {\r\n Manipulator.addStyle(this._circle, {\r\n backgroundColor: \"#1976d2\",\r\n });\r\n\r\n return;\r\n }\r\n\r\n Manipulator.addStyle(this._circle, {\r\n backgroundColor: \"transparent\",\r\n });\r\n };\r\n\r\n _toggleClassActive = (array, { textContent }, tips) => {\r\n const findInArray = [...array].find(\r\n (e) => Number(e) === Number(textContent)\r\n );\r\n\r\n return tips.forEach((e) => {\r\n if (e.hasAttribute(ATTR_TIMEPICKER_DISABLED)) return;\r\n\r\n if (e.textContent === findInArray) {\r\n Manipulator.addClass(e, this._classes.tipsActive);\r\n e.setAttribute(ATTR_TIMEPICKER_ACTIVE, \"\");\r\n return;\r\n }\r\n\r\n Manipulator.removeClass(e, this._classes.tipsActive);\r\n e.removeAttribute(ATTR_TIMEPICKER_ACTIVE);\r\n });\r\n };\r\n\r\n _addActiveClassToTip(tips, value) {\r\n tips.forEach((tip) => {\r\n if (Number(tip.textContent) === Number(value)) {\r\n Manipulator.addClass(tip, this._classes.tipsActive);\r\n tip.setAttribute(ATTR_TIMEPICKER_ACTIVE, \"\");\r\n }\r\n });\r\n }\r\n\r\n _makeMinutesDegrees = (degrees, minute) => {\r\n const { increment } = this._options;\r\n\r\n if (degrees < 0) {\r\n minute = Math.round(360 + degrees / 6) % 60;\r\n degrees = 360 + Math.round(degrees / 6) * 6;\r\n } else {\r\n minute = Math.round(degrees / 6) % 60;\r\n degrees = Math.round(degrees / 6) * 6;\r\n }\r\n\r\n if (increment) {\r\n degrees = Math.round(degrees / 30) * 30;\r\n minute = (Math.round(degrees / 6) * 6) / 6;\r\n\r\n if (minute === 60) {\r\n minute = \"00\";\r\n }\r\n }\r\n\r\n if (degrees >= 360) {\r\n degrees = 0;\r\n }\r\n\r\n return {\r\n degrees,\r\n minute,\r\n addDegrees: increment ? 30 : 6,\r\n };\r\n };\r\n\r\n _makeHourDegrees = (target, degrees, hour) => {\r\n if (!target) {\r\n return;\r\n }\r\n if (this._hasTargetInnerClass(target)) {\r\n if (degrees < 0) {\r\n hour = Math.round(360 + degrees / 30) % 24;\r\n degrees = 360 + degrees;\r\n } else {\r\n hour = Math.round(degrees / 30) + 12;\r\n if (hour === 12) {\r\n hour = \"00\";\r\n }\r\n }\r\n } else if (degrees < 0) {\r\n hour = Math.round(360 + degrees / 30) % 12;\r\n degrees = 360 + degrees;\r\n } else {\r\n hour = Math.round(degrees / 30) % 12;\r\n if (hour === 0 || hour > 12) {\r\n hour = 12;\r\n }\r\n }\r\n\r\n if (degrees >= 360) {\r\n degrees = 0;\r\n }\r\n\r\n return {\r\n degrees,\r\n hour,\r\n addDegrees: 30,\r\n };\r\n };\r\n\r\n _makeInnerHoursDegrees = (degrees, hour) => {\r\n if (degrees < 0) {\r\n hour = Math.round(360 + degrees / 30) % 24;\r\n degrees = 360 + degrees;\r\n } else {\r\n hour = Math.round(degrees / 30) + 12;\r\n if (hour === 12) {\r\n hour = \"00\";\r\n }\r\n }\r\n\r\n return {\r\n degrees,\r\n hour,\r\n addDegrees: 30,\r\n };\r\n };\r\n\r\n _setHourOrMinute(number) {\r\n return number < 10 ? `0${number}` : number;\r\n }\r\n\r\n _appendTimes() {\r\n const { format24 } = this._options;\r\n\r\n if (format24) {\r\n this._getAppendClock(\r\n this.hoursArray,\r\n `[${ATTR_TIMEPICKER_CLOCK}]`,\r\n ATTR_TIMEPICKER_TIPS_HOURS\r\n );\r\n this._getAppendClock(\r\n this.innerHours,\r\n `[${ATTR_TIMEPICKER_CLOCK_INNER}]`,\r\n ATTR_TIMEPICKER_INNER_HOURS\r\n );\r\n\r\n return;\r\n }\r\n\r\n this._getAppendClock(\r\n this.hoursArray,\r\n `[${ATTR_TIMEPICKER_CLOCK}]`,\r\n ATTR_TIMEPICKER_TIPS_HOURS\r\n );\r\n }\r\n\r\n _getAppendClock = (\r\n array = [],\r\n clockClass = `[${ATTR_TIMEPICKER_CLOCK}]`,\r\n tipsClass\r\n ) => {\r\n let { minTime, maxTime } = this._options;\r\n const { inline, format12, disablePast, disableFuture } = this._options;\r\n\r\n minTime = setMinTime(minTime, disablePast, format12);\r\n maxTime = setMaxTime(maxTime, disableFuture, format12);\r\n\r\n const [maxTimeHour, maxTimeMinutes, maxTimeFormat] = takeValue(\r\n maxTime,\r\n false\r\n );\r\n const [minTimeHour, minTimeMinutes, minTimeFormat] = takeValue(\r\n minTime,\r\n false\r\n );\r\n\r\n // fix for append clock for max/min if input has invalid value\r\n if (\r\n !inline &&\r\n format12 &&\r\n this._isInvalidTimeFormat &&\r\n !this._AM.hasAttribute(ATTR_TIMEPICKER_ACTIVE)\r\n ) {\r\n Manipulator.addClass(this._PM, this._classes.opacity);\r\n this._PM.setAttribute(ATTR_TIMEPICKER_ACTIVE, \"\");\r\n }\r\n\r\n const clock = SelectorEngine.findOne(clockClass);\r\n\r\n const elements = 360 / array.length;\r\n\r\n function rad(el) {\r\n return el * (Math.PI / 180);\r\n }\r\n\r\n if (clock === null) return;\r\n\r\n const clockWidth = (clock.offsetWidth - 32) / 2;\r\n const clockHeight = (clock.offsetHeight - 32) / 2;\r\n const radius = clockWidth - 4;\r\n\r\n setTimeout(() => {\r\n let currentFormat;\r\n if (format12) {\r\n currentFormat = SelectorEngine.findOne(\r\n `${SELECTOR_ATTR_TIMEPICKER_HOUR_MODE}[${ATTR_TIMEPICKER_ACTIVE}]`\r\n ).textContent;\r\n }\r\n this._handleDisablingTipsMinTime(\r\n currentFormat,\r\n minTimeFormat,\r\n minTimeMinutes,\r\n minTimeHour\r\n );\r\n this._handleDisablingTipsMaxTime(\r\n currentFormat,\r\n maxTimeFormat,\r\n maxTimeMinutes,\r\n maxTimeHour\r\n );\r\n }, 0);\r\n\r\n [...array].forEach((e, i) => {\r\n const angle = rad(i * elements);\r\n\r\n const span = element(\"span\");\r\n const spanToTips = element(\"span\");\r\n\r\n spanToTips.innerHTML = e;\r\n Manipulator.addClass(span, this._classes.tips);\r\n span.setAttribute(tipsClass, \"\");\r\n\r\n const itemWidth = span.offsetWidth;\r\n const itemHeight = span.offsetHeight;\r\n\r\n Manipulator.addStyle(span, {\r\n left: `${clockWidth + Math.sin(angle) * radius - itemWidth}px`,\r\n bottom: `${clockHeight + Math.cos(angle) * radius - itemHeight}px`,\r\n });\r\n\r\n if (array.includes(\"05\")) {\r\n span.setAttribute(ATTR_TIMEPICKER_TIPS_MINUTES, \"\");\r\n }\r\n\r\n if (array.includes(\"13\")) {\r\n spanToTips.setAttribute(ATTR_TIMEPICKER_TIPS_INNER_ELEMENT, \"\");\r\n } else {\r\n spanToTips.setAttribute(ATTR_TIMEPICKER_TIPS_ELEMENT, \"\");\r\n }\r\n\r\n span.appendChild(spanToTips);\r\n return clock.appendChild(span);\r\n });\r\n };\r\n\r\n _getConfig(config) {\r\n const dataAttributes = Manipulator.getDataAttributes(this._element);\r\n\r\n config = {\r\n ...Default,\r\n ...dataAttributes,\r\n ...config,\r\n };\r\n\r\n typeCheckConfig(NAME, config, DefaultType);\r\n return config;\r\n }\r\n\r\n _getClasses(classes) {\r\n const dataAttributes = Manipulator.getDataClassAttributes(this._element);\r\n\r\n classes = {\r\n ...DefaultClasses,\r\n ...dataAttributes,\r\n ...classes,\r\n };\r\n\r\n typeCheckConfig(NAME, classes, DefaultClassesType);\r\n\r\n return classes;\r\n }\r\n\r\n _getContainer() {\r\n return SelectorEngine.findOne(this._options.container);\r\n }\r\n\r\n _getValidate(event) {\r\n const { format24, format12, appendValidationInfo } = this._options;\r\n\r\n EventHandlerMulti.on(this.input, event, ({ target }) => {\r\n if (this._options === null || this.input.value === \"\") return;\r\n\r\n const regexAMFormat = /^(0?[1-9]|1[012])(:[0-5]\\d) [APap][mM]$/;\r\n const regexNormalFormat = /^([01]\\d|2[0-3])(:[0-5]\\d)$/;\r\n const testedAMRegex = regexAMFormat.test(target.value);\r\n const testedNormalRegex = regexNormalFormat.test(target.value);\r\n\r\n if (\r\n (testedNormalRegex !== true && format24) ||\r\n (testedAMRegex !== true && format12)\r\n ) {\r\n if (appendValidationInfo) {\r\n this.input.setAttribute(ATTR_TIMEPICKER_IS_INVALID, \"\");\r\n }\r\n\r\n Manipulator.addStyle(target, { marginBottom: 0 });\r\n\r\n this._isInvalidTimeFormat = true;\r\n return;\r\n }\r\n\r\n this.input.removeAttribute(ATTR_TIMEPICKER_IS_INVALID);\r\n this._isInvalidTimeFormat = false;\r\n const allInvalid = SelectorEngine.findOne(\r\n `[${ATTR_TIMEPICKER_INVALID_FEEDBACK}]`\r\n );\r\n\r\n if (allInvalid === null) return;\r\n\r\n allInvalid.remove();\r\n });\r\n }\r\n\r\n // Static\r\n static getInstance(element) {\r\n return Data.getData(element, DATA_KEY);\r\n }\r\n\r\n static getOrCreateInstance(element, config = {}) {\r\n return (\r\n this.getInstance(element) ||\r\n new this(element, typeof config === \"object\" ? config : null)\r\n );\r\n }\r\n}\r\n\r\nexport default Timepicker;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport EventHandler from \"../../dom/event-handler\";\r\n\r\nconst DEFAULT_OPTIONS = {\r\n threshold: 10,\r\n direction: \"all\",\r\n};\r\n\r\nclass Swipe {\r\n constructor(element, options) {\r\n this._element = element;\r\n this._startPosition = null;\r\n this._options = {\r\n ...DEFAULT_OPTIONS,\r\n ...options,\r\n };\r\n }\r\n\r\n handleTouchStart(e) {\r\n this._startPosition = this._getCoordinates(e);\r\n }\r\n\r\n handleTouchMove(e) {\r\n if (!this._startPosition) return;\r\n\r\n const position = this._getCoordinates(e);\r\n const displacement = {\r\n x: position.x - this._startPosition.x,\r\n y: position.y - this._startPosition.y,\r\n };\r\n\r\n const swipe = this._getDirection(displacement);\r\n\r\n if (this._options.direction === \"all\") {\r\n if (\r\n swipe.y.value < this._options.threshold &&\r\n swipe.x.value < this._options.threshold\r\n ) {\r\n return;\r\n }\r\n const direction =\r\n swipe.y.value > swipe.x.value ? swipe.y.direction : swipe.x.direction;\r\n EventHandler.trigger(this._element, `swipe${direction}`);\r\n EventHandler.trigger(this._element, \"swipe\", { direction });\r\n this._startPosition = null;\r\n return;\r\n }\r\n\r\n const axis =\r\n this._options.direction === \"left\" || this._options === \"right\"\r\n ? \"x\"\r\n : \"y\";\r\n\r\n if (\r\n swipe[axis].direction === this._options.direction &&\r\n swipe[axis].value > this._options.threshold\r\n ) {\r\n EventHandler.trigger(this._element, `swipe${swipe[axis].direction}`);\r\n this._startPosition = null;\r\n }\r\n }\r\n\r\n handleTouchEnd() {\r\n this._startPosition = null;\r\n }\r\n\r\n _getCoordinates(e) {\r\n const [touch] = e.touches;\r\n return {\r\n x: touch.clientX,\r\n y: touch.clientY,\r\n };\r\n }\r\n\r\n _getDirection(displacement) {\r\n return {\r\n x: {\r\n direction: displacement.x < 0 ? \"left\" : \"right\",\r\n value: Math.abs(displacement.x),\r\n },\r\n y: {\r\n direction: displacement.y < 0 ? \"up\" : \"down\",\r\n value: Math.abs(displacement.y),\r\n },\r\n };\r\n }\r\n}\r\n\r\nexport default Swipe;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport Swipe from \"./swipe\";\r\n\r\nclass Touch {\r\n constructor(element, event = \"swipe\", options = {}) {\r\n this._element = element;\r\n this._event = event;\r\n\r\n // events\r\n\r\n this.swipe = new Swipe(element, options);\r\n\r\n // handlers\r\n\r\n this._touchStartHandler = this._handleTouchStart.bind(this);\r\n this._touchMoveHandler = this._handleTouchMove.bind(this);\r\n this._touchEndHandler = this._handleTouchEnd.bind(this);\r\n }\r\n\r\n dispose() {\r\n this._element.removeEventListener(\"touchstart\", this._touchStartHandler);\r\n this._element.removeEventListener(\"touchmove\", this._touchMoveHandler);\r\n window.removeEventListener(\"touchend\", this._touchEndHandler);\r\n }\r\n\r\n init() {\r\n // istanbul ignore next\r\n this._element.addEventListener(\"touchstart\", (e) =>\r\n this._handleTouchStart(e)\r\n );\r\n // istanbul ignore next\r\n this._element.addEventListener(\"touchmove\", (e) =>\r\n this._handleTouchMove(e)\r\n );\r\n // istanbul ignore next\r\n window.addEventListener(\"touchend\", (e) => this._handleTouchEnd(e));\r\n }\r\n\r\n _handleTouchStart(e) {\r\n this[this._event].handleTouchStart(e);\r\n }\r\n\r\n _handleTouchMove(e) {\r\n this[this._event].handleTouchMove(e);\r\n }\r\n\r\n _handleTouchEnd(e) {\r\n this[this._event].handleTouchEnd(e);\r\n }\r\n}\r\n\r\nexport default Touch;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport {\r\n array,\r\n isVisible,\r\n typeCheckConfig,\r\n isRTL,\r\n getUID,\r\n} from \"../util/index\";\r\nimport FocusTrap from \"../util/focusTrap\";\r\nimport { ENTER, TAB, ESCAPE } from \"../util/keycodes\";\r\nimport Touch from \"../util/touch/index\";\r\nimport Collapse from \"../components/collapse\";\r\nimport Data from \"../dom/data\";\r\nimport EventHandler from \"../dom/event-handler\";\r\nimport Manipulator from \"../dom/manipulator\";\r\nimport SelectorEngine from \"../dom/selector-engine\";\r\nimport Ripple from \"../methods/ripple\";\r\nimport Backdrop from \"../util/backdrop\";\r\nimport { PerfectScrollbar } from \"../index.es\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst NAME = \"sidenav\";\r\nconst DATA_KEY = \"te.sidenav\";\r\nconst ARROW_DATA = \"data-te-sidenav-rotate-icon-ref\";\r\nconst SELECTOR_TOGGLE = \"[data-te-sidenav-toggle-ref]\";\r\n\r\nconst SELECTOR_TOGGLE_COLLAPSE = \"[data-te-collapse-init]\";\r\n\r\nconst SELECTOR_SHOW_SLIM = '[data-te-sidenav-slim=\"true\"]';\r\nconst SELECTOR_HIDE_SLIM = '[data-te-sidenav-slim=\"false\"]';\r\n\r\nconst SELECTOR_NAVIGATION = \"[data-te-sidenav-menu-ref]\";\r\nconst SELECTOR_COLLAPSE = \"[data-te-sidenav-collapse-ref]\";\r\nconst SELECTOR_LINK = \"[data-te-sidenav-link-ref]\";\r\n\r\nconst TRANSLATION_LEFT = isRTL() ? 100 : -100;\r\nconst TRANSLATION_RIGHT = isRTL() ? -100 : 100;\r\n\r\nconst OPTIONS_TYPE = {\r\n sidenavAccordion: \"(boolean)\",\r\n sidenavBackdrop: \"(boolean)\",\r\n sidenavBackdropClass: \"(null|string)\",\r\n sidenavCloseOnEsc: \"(boolean)\",\r\n sidenavColor: \"(string)\",\r\n sidenavContent: \"(null|string)\",\r\n sidenavExpandable: \"(boolean)\",\r\n sidenavExpandOnHover: \"(boolean)\",\r\n sidenavFocusTrap: \"(boolean)\",\r\n sidenavHidden: \"(boolean)\",\r\n sidenavMode: \"(string)\",\r\n sidenavModeBreakpointOver: \"(null|string|number)\",\r\n sidenavModeBreakpointSide: \"(null|string|number)\",\r\n sidenavModeBreakpointPush: \"(null|string|number)\",\r\n sidenavBreakpointSm: \"(number)\",\r\n sidenavBreakpointMd: \"(number)\",\r\n sidenavBreakpointLg: \"(number)\",\r\n sidenavBreakpointXl: \"(number)\",\r\n sidenavBreakpoint2xl: \"(number)\",\r\n sidenavScrollContainer: \"(null|string)\",\r\n sidenavSlim: \"(boolean)\",\r\n sidenavSlimCollapsed: \"(boolean)\",\r\n sidenavSlimWidth: \"(number)\",\r\n sidenavPosition: \"(string)\",\r\n sidenavRight: \"(boolean)\",\r\n sidenavTransitionDuration: \"(number)\",\r\n sidenavWidth: \"(number)\",\r\n};\r\n\r\nconst DEFAULT_OPTIONS = {\r\n sidenavAccordion: false,\r\n sidenavBackdrop: true,\r\n sidenavBackdropClass: null,\r\n sidenavCloseOnEsc: true,\r\n sidenavColor: \"primary\",\r\n sidenavContent: null,\r\n sidenavExpandable: true,\r\n sidenavExpandOnHover: false,\r\n sidenavFocusTrap: true,\r\n sidenavHidden: true,\r\n sidenavMode: \"over\",\r\n sidenavModeBreakpointOver: null,\r\n sidenavModeBreakpointSide: null,\r\n sidenavModeBreakpointPush: null,\r\n sidenavBreakpointSm: 640,\r\n sidenavBreakpointMd: 768,\r\n sidenavBreakpointLg: 1024,\r\n sidenavBreakpointXl: 1280,\r\n sidenavBreakpoint2xl: 1536,\r\n sidenavScrollContainer: null,\r\n sidenavSlim: false,\r\n sidenavSlimCollapsed: false,\r\n sidenavSlimWidth: 77,\r\n sidenavPosition: \"fixed\",\r\n sidenavRight: false,\r\n sidenavTransitionDuration: 300,\r\n sidenavWidth: 240,\r\n};\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nClass Definition\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nclass Sidenav {\r\n constructor(node, options = {}) {\r\n this._element = node;\r\n this._options = options;\r\n\r\n this._ID = getUID(\"\");\r\n\r\n this._content = null;\r\n this._initialContentStyle = null;\r\n this._slimCollapsed = false;\r\n\r\n this._activeNode = null;\r\n\r\n this._tempSlim = false;\r\n this._backdrop = this._initializeBackDrop();\r\n\r\n this._focusTrap = null;\r\n this._perfectScrollbar = null;\r\n this._touch = null;\r\n\r\n this._setModeFromBreakpoints();\r\n\r\n this.escHandler = (e) => {\r\n if (e.keyCode === ESCAPE && this.toggler && isVisible(this.toggler)) {\r\n this._update(false);\r\n\r\n EventHandler.off(window, \"keydown\", this.escHandler);\r\n }\r\n };\r\n\r\n this.hashHandler = () => {\r\n this._setActiveElements();\r\n };\r\n\r\n if (node) {\r\n Data.setData(node, DATA_KEY, this);\r\n\r\n this._setup();\r\n }\r\n\r\n if (\r\n this.options.sidenavBackdrop &&\r\n !this.options.sidenavHidden &&\r\n this.options.sidenavMode === \"over\"\r\n ) {\r\n EventHandler.on(this._element, \"transitionend\", this._addBackdropOnInit);\r\n }\r\n\r\n this._didInit = false;\r\n this._init();\r\n }\r\n\r\n // Getters\r\n\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n get container() {\r\n if (this.options.sidenavPosition === \"fixed\") {\r\n return SelectorEngine.findOne(\"body\");\r\n }\r\n\r\n const findContainer = (el) => {\r\n if (!el.parentNode || el.parentNode === document) {\r\n return el;\r\n }\r\n if (\r\n el.parentNode.style.position === \"relative\" ||\r\n el.parentNode.classList.contains(\"relative\")\r\n ) {\r\n return el.parentNode;\r\n }\r\n return findContainer(el.parentNode);\r\n };\r\n\r\n return findContainer(this._element);\r\n }\r\n\r\n get isVisible() {\r\n let containerStart = 0;\r\n let containerEnd = window.innerWidth;\r\n\r\n if (this.options.sidenavPosition !== \"fixed\") {\r\n const boundry = this.container.getBoundingClientRect();\r\n containerStart = boundry.x;\r\n containerEnd = boundry.x + boundry.width;\r\n }\r\n\r\n const { x } = this._element.getBoundingClientRect();\r\n\r\n if (this.options.sidenavRight) {\r\n return Math.abs(x - containerEnd) > 10;\r\n }\r\n\r\n return Math.abs(x - containerStart) < 10;\r\n }\r\n\r\n get links() {\r\n return SelectorEngine.find(SELECTOR_LINK, this._element);\r\n }\r\n\r\n get navigation() {\r\n return SelectorEngine.find(SELECTOR_NAVIGATION, this._element);\r\n }\r\n\r\n get options() {\r\n const config = {\r\n ...DEFAULT_OPTIONS,\r\n ...Manipulator.getDataAttributes(this._element),\r\n ...this._options,\r\n };\r\n\r\n typeCheckConfig(NAME, config, OPTIONS_TYPE);\r\n\r\n return config;\r\n }\r\n\r\n get sidenavStyle() {\r\n return {\r\n width: `${this.width}px`,\r\n height: this.options.sidenavPosition === \"fixed\" ? \"100vh\" : \"100%\",\r\n position: this.options.sidenavPosition,\r\n transition: `all ${this.transitionDuration} linear`,\r\n };\r\n }\r\n\r\n get toggler() {\r\n const toggleElement = SelectorEngine.find(SELECTOR_TOGGLE).find(\r\n (toggler) => {\r\n const target = Manipulator.getDataAttribute(toggler, \"target\");\r\n return SelectorEngine.findOne(target) === this._element;\r\n }\r\n );\r\n return toggleElement;\r\n }\r\n\r\n get transitionDuration() {\r\n return `${this.options.sidenavTransitionDuration / 1000}s`;\r\n }\r\n\r\n get translation() {\r\n return this.options.sidenavRight ? TRANSLATION_RIGHT : TRANSLATION_LEFT;\r\n }\r\n\r\n get width() {\r\n return this._slimCollapsed\r\n ? this.options.sidenavSlimWidth\r\n : this.options.sidenavWidth;\r\n }\r\n\r\n get isBackdropVisible() {\r\n return Boolean(this._backdrop._element);\r\n }\r\n\r\n // Public\r\n\r\n changeMode(mode) {\r\n this._setMode(mode);\r\n }\r\n\r\n dispose() {\r\n EventHandler.off(window, \"keydown\", this.escHandler);\r\n this.options.sidenavBackdrop && this._backdrop.dispose();\r\n\r\n EventHandler.off(window, \"hashchange\", this.hashHandler);\r\n\r\n this._touch.dispose();\r\n\r\n Data.removeData(this._element, DATA_KEY);\r\n\r\n this._element = null;\r\n }\r\n\r\n hide() {\r\n this._emitEvents(false);\r\n this._update(false);\r\n this._options.sidenavBackdrop &&\r\n this.isBackdropVisible &&\r\n this._backdrop.hide();\r\n }\r\n\r\n show() {\r\n this._emitEvents(true);\r\n this._update(true);\r\n this._options.sidenavBackdrop &&\r\n this._options.sidenavMode === \"over\" &&\r\n this._backdrop.show();\r\n }\r\n\r\n toggle() {\r\n this._emitEvents(!this.isVisible);\r\n this._update(!this.isVisible);\r\n }\r\n\r\n toggleSlim() {\r\n this._setSlim(!this._slimCollapsed);\r\n }\r\n\r\n update(options) {\r\n this._options = options;\r\n\r\n this._setup();\r\n }\r\n\r\n getBreakpoint(prefix) {\r\n return this._transformBreakpointValuesToObject()[prefix];\r\n }\r\n\r\n // Private\r\n _init() {\r\n if (this._didInit) {\r\n return;\r\n }\r\n EventHandler.on(\r\n document,\r\n \"click\",\r\n SELECTOR_TOGGLE,\r\n Sidenav.toggleSidenav()\r\n );\r\n this._didInit = true;\r\n }\r\n\r\n _transformBreakpointValuesToObject() {\r\n return {\r\n sm: this.options.sidenavBreakpointSm,\r\n md: this.options.sidenavBreakpointMd,\r\n lg: this.options.sidenavBreakpointLg,\r\n xl: this.options.sidenavBreakpointXl,\r\n \"2xl\": this.options.sidenavBreakpoint2xl,\r\n };\r\n }\r\n\r\n _setModeFromBreakpoints() {\r\n const innerWidth = window.innerWidth;\r\n const breakpointsList = this._transformBreakpointValuesToObject();\r\n\r\n if (innerWidth === undefined || !breakpointsList) {\r\n return;\r\n }\r\n\r\n const overCalculated =\r\n typeof this.options.sidenavModeBreakpointOver === \"number\"\r\n ? innerWidth - this.options.sidenavModeBreakpointOver\r\n : innerWidth - breakpointsList[this.options.sidenavModeBreakpointOver];\r\n\r\n const sideCalculated =\r\n typeof this.options.sidenavModeBreakpointSide === \"number\"\r\n ? innerWidth - this.options.sidenavModeBreakpointSide\r\n : innerWidth - breakpointsList[this.options.sidenavModeBreakpointSide];\r\n\r\n const pushCalculated =\r\n typeof this.options.sidenavModeBreakpointPush === \"number\"\r\n ? innerWidth - this.options.sidenavModeBreakpointPush\r\n : innerWidth - breakpointsList[this.options.sidenavModeBreakpointPush];\r\n\r\n const sortAsc = (a, b) => {\r\n if (a - b < 0) return -1;\r\n if (b - a < 0) return 1;\r\n return 0;\r\n };\r\n\r\n const closestPositive = [overCalculated, sideCalculated, pushCalculated]\r\n .filter((value) => value != null && value >= 0)\r\n .sort(sortAsc)[0];\r\n\r\n if (overCalculated > 0 && overCalculated === closestPositive) {\r\n this._options.sidenavMode = \"over\";\r\n this._options.sidenavHidden = true;\r\n } else if (sideCalculated > 0 && sideCalculated === closestPositive) {\r\n this._options.sidenavMode = \"side\";\r\n } else if (pushCalculated > 0 && pushCalculated === closestPositive) {\r\n this._options.sidenavMode = \"push\";\r\n }\r\n }\r\n\r\n _collapseItems() {\r\n this.navigation.forEach((menu) => {\r\n const collapseElements = SelectorEngine.find(SELECTOR_COLLAPSE, menu);\r\n collapseElements.forEach((el) => {\r\n Collapse.getInstance(el).hide();\r\n });\r\n });\r\n }\r\n\r\n _getOffsetValue(show, { index, property, offsets }) {\r\n const initialValue = this._getPxValue(\r\n this._initialContentStyle[index][offsets[property].property]\r\n );\r\n\r\n const offset = show ? offsets[property].value : 0;\r\n return initialValue + offset;\r\n }\r\n\r\n _getProperty(...args) {\r\n return args\r\n .map((arg, i) => {\r\n if (i === 0) {\r\n return arg;\r\n }\r\n return arg[0].toUpperCase().concat(arg.slice(1));\r\n })\r\n .join(\"\");\r\n }\r\n\r\n _getPxValue(property) {\r\n if (!property) {\r\n return 0;\r\n }\r\n return parseFloat(property);\r\n }\r\n\r\n _handleSwipe(e, inverseDirecion) {\r\n if (\r\n inverseDirecion &&\r\n this._slimCollapsed &&\r\n this.options.sidenavSlim &&\r\n this.options.sidenavExpandable\r\n ) {\r\n this.toggleSlim();\r\n } else if (!inverseDirecion) {\r\n if (\r\n this._slimCollapsed ||\r\n !this.options.sidenavSlim ||\r\n !this.options.sidenavExpandable\r\n ) {\r\n if (this.toggler && isVisible(this.toggler)) {\r\n this.toggle();\r\n }\r\n } else {\r\n this.toggleSlim();\r\n }\r\n }\r\n }\r\n\r\n _isActive(link, reference) {\r\n if (reference) {\r\n return reference === link;\r\n }\r\n\r\n if (link.attributes.href) {\r\n return new URL(link, window.location.href).href === window.location.href;\r\n }\r\n\r\n return false;\r\n }\r\n\r\n _isAllToBeCollapsed() {\r\n const collapseElements = SelectorEngine.find(\r\n SELECTOR_TOGGLE_COLLAPSE,\r\n this._element\r\n );\r\n const collapseElementsExpanded = collapseElements.filter(\r\n (collapsible) => collapsible.getAttribute(\"aria-expanded\") === \"true\"\r\n );\r\n return collapseElementsExpanded.length === 0;\r\n }\r\n\r\n _isAllCollapsed() {\r\n return (\r\n SelectorEngine.find(SELECTOR_COLLAPSE, this._element).filter((el) =>\r\n isVisible(el)\r\n ).length === 0\r\n );\r\n }\r\n\r\n _initializeBackDrop() {\r\n if (!this.options.sidenavBackdrop) {\r\n return;\r\n }\r\n const backdropClasses = this.options.sidenavBackdropClass\r\n ? this.options.sidenavBackdropClass.split(\" \")\r\n : this.options.sidenavPosition\r\n ? [\r\n \"opacity-50\",\r\n \"transition-all\",\r\n \"duration-300\",\r\n \"ease-in-out\",\r\n this.options.sidenavPosition,\r\n \"top-0\",\r\n \"left-0\",\r\n \"z-50\",\r\n \"bg-black/10\",\r\n \"dark:bg-black-60\",\r\n \"w-full\",\r\n \"h-full\",\r\n this._element.id,\r\n ]\r\n : null;\r\n\r\n return new Backdrop({\r\n isVisible: this.options.sidenavBackdrop,\r\n isAnimated: true,\r\n rootElement: this._element.parentNode,\r\n backdropClasses,\r\n clickCallback: () => this.hide(),\r\n });\r\n }\r\n\r\n _updateBackdrop(show) {\r\n if (this.options.sidenavMode === \"over\") {\r\n show\r\n ? this._backdrop.show()\r\n : this.isBackdropVisible && this._backdrop.hide();\r\n return;\r\n }\r\n this.isBackdropVisible && this._backdrop.hide();\r\n }\r\n\r\n _setup() {\r\n // Touch events\r\n this._setupTouch();\r\n\r\n // Focus trap\r\n\r\n if (this.options.sidenavFocusTrap) {\r\n this._setupFocusTrap();\r\n }\r\n\r\n // Collapse\r\n\r\n this._setupCollapse();\r\n\r\n // Slim\r\n\r\n if (this.options.sidenavSlim) {\r\n this._setupSlim();\r\n }\r\n\r\n // Initial position\r\n\r\n this._setupInitialStyling();\r\n\r\n // Perfect Scrollbar\r\n\r\n this._setupScrolling();\r\n\r\n // Content\r\n\r\n if (this.options.sidenavContent) {\r\n this._setupContent();\r\n }\r\n\r\n // Active link\r\n\r\n this._setupActiveState();\r\n\r\n // Ripple\r\n\r\n this._setupRippleEffect();\r\n\r\n // Shown on init\r\n\r\n if (!this.options.sidenavHidden) {\r\n this._updateOffsets(true, true);\r\n }\r\n\r\n if (this.options.sidenavMode === \"over\") {\r\n this._setTabindex(true);\r\n }\r\n }\r\n\r\n _setupActiveState() {\r\n this._setActiveElements();\r\n\r\n this.links.forEach((link) => {\r\n EventHandler.on(link, \"click\", () => this._setActiveElements(link));\r\n EventHandler.on(link, \"keydown\", (e) => {\r\n if (e.keyCode === ENTER) {\r\n this._setActiveElements(link);\r\n }\r\n });\r\n });\r\n\r\n EventHandler.on(window, \"hashchange\", this.hashHandler);\r\n }\r\n\r\n _setupCollapse() {\r\n this.navigation.forEach((menu, menuIndex) => {\r\n const categories = SelectorEngine.find(SELECTOR_COLLAPSE, menu);\r\n categories.forEach((list, index) =>\r\n this._setupCollapseList({ list, index, menu, menuIndex })\r\n );\r\n });\r\n }\r\n\r\n _generateCollpaseID(index, menuIndex) {\r\n return `sidenav-collapse-${this._ID}-${menuIndex}-${index}`;\r\n }\r\n\r\n _setupCollapseList({ list, index, menu, menuIndex }) {\r\n const ID = this._generateCollpaseID(index, menuIndex);\r\n\r\n list.setAttribute(\"id\", ID);\r\n list.setAttribute(\"data-te-collapse-item\", \"\");\r\n\r\n const [toggler] = SelectorEngine.prev(list, SELECTOR_LINK);\r\n\r\n Manipulator.setDataAttribute(toggler, \"collapse-init\", \"\");\r\n toggler.setAttribute(\"href\", `#${ID}`);\r\n toggler.setAttribute(\"role\", \"button\");\r\n\r\n const instance =\r\n Collapse.getInstance(list) ||\r\n new Collapse(list, {\r\n toggle: false,\r\n parent: this.options.sidenavAccordion ? menu : list,\r\n });\r\n\r\n // Arrow\r\n\r\n if (\r\n list.dataset.teSidenavStateShow === \"\" ||\r\n list.dataset.teCollapseShow === \"\"\r\n ) {\r\n this._rotateArrow(toggler, false);\r\n }\r\n\r\n // Event listeners\r\n\r\n EventHandler.on(toggler, \"click\", (e) => {\r\n this._toggleCategory(e, instance, list);\r\n if (this._tempSlim && this._isAllToBeCollapsed()) {\r\n this._setSlim(true);\r\n\r\n this._tempSlim = false;\r\n }\r\n\r\n if (this.options.sidenavMode === \"over\" && this._focusTrap) {\r\n this._focusTrap.update();\r\n }\r\n });\r\n\r\n EventHandler.on(list, \"show.te.collapse\", () =>\r\n this._rotateArrow(toggler, false)\r\n );\r\n\r\n EventHandler.on(list, \"hide.te.collapse\", () =>\r\n this._rotateArrow(toggler, true)\r\n );\r\n\r\n EventHandler.on(list, \"shown.te.collapse\", () => {\r\n if (this.options.sidenavMode === \"over\" && this._focusTrap) {\r\n this._focusTrap.update();\r\n }\r\n });\r\n\r\n EventHandler.on(list, \"hidden.te.collapse\", () => {\r\n if (this._tempSlim && this._isAllCollapsed()) {\r\n this._setSlim(true);\r\n\r\n this._tempSlim = false;\r\n }\r\n if (this.options.sidenavMode === \"over\" && this._focusTrap) {\r\n this._focusTrap.update();\r\n }\r\n });\r\n }\r\n\r\n _setupContent() {\r\n this._content = SelectorEngine.find(this.options.sidenavContent);\r\n\r\n this._content.forEach((el) => {\r\n const searchFor = [\r\n \"!p\",\r\n \"!m\",\r\n \"!px\",\r\n \"!pl\",\r\n \"!pr\",\r\n \"!mx\",\r\n \"!ml\",\r\n \"!mr\",\r\n \"!-p\",\r\n \"!-m\",\r\n \"!-px\",\r\n \"!-pl\",\r\n \"!-pr\",\r\n \"!-mx\",\r\n \"!-ml\",\r\n \"!-mr\",\r\n ];\r\n const classesToRemove = [...el.classList].filter(\r\n (singleClass) =>\r\n searchFor.findIndex((el) => singleClass.includes(el)) >= 0\r\n );\r\n classesToRemove.forEach((remove) => el.classList.remove(remove));\r\n });\r\n\r\n this._initialContentStyle = this._content.map((el) => {\r\n const { paddingLeft, paddingRight, marginLeft, marginRight, transition } =\r\n window.getComputedStyle(el);\r\n return { paddingLeft, paddingRight, marginLeft, marginRight, transition };\r\n });\r\n }\r\n\r\n _setupFocusTrap() {\r\n this._focusTrap = new FocusTrap(\r\n this._element,\r\n {\r\n event: \"keydown\",\r\n condition: (e) => e.keyCode === TAB,\r\n onlyVisible: true,\r\n },\r\n this.toggler\r\n );\r\n }\r\n\r\n _setupInitialStyling() {\r\n this._setColor();\r\n Manipulator.style(this._element, this.sidenavStyle);\r\n }\r\n\r\n _setupScrolling() {\r\n let container = this._element;\r\n\r\n if (this.options.sidenavScrollContainer) {\r\n container = SelectorEngine.findOne(\r\n this.options.sidenavScrollContainer,\r\n this._element\r\n );\r\n\r\n const siblings = array(container.parentNode.children).filter(\r\n (el) => el !== container\r\n );\r\n\r\n const siblingsHeight = siblings.reduce((a, b) => {\r\n return a + b.clientHeight;\r\n }, 0);\r\n\r\n Manipulator.style(container, {\r\n maxHeight: `calc(100% - ${siblingsHeight}px)`,\r\n position: \"relative\",\r\n });\r\n }\r\n\r\n this._perfectScrollbar = new PerfectScrollbar(container, {\r\n suppressScrollX: true,\r\n handlers: [\"click-rail\", \"drag-thumb\", \"wheel\", \"touch\"],\r\n });\r\n }\r\n\r\n _setupSlim() {\r\n this._slimCollapsed = this.options.sidenavSlimCollapsed;\r\n\r\n this._toggleSlimDisplay(this._slimCollapsed);\r\n\r\n if (this.options.sidenavExpandOnHover) {\r\n this._element.addEventListener(\"mouseenter\", () => {\r\n if (this._slimCollapsed) {\r\n this._setSlim(false);\r\n }\r\n });\r\n\r\n this._element.addEventListener(\"mouseleave\", () => {\r\n if (!this._slimCollapsed) {\r\n this._setSlim(true);\r\n }\r\n });\r\n }\r\n }\r\n\r\n _setupRippleEffect() {\r\n this.links.forEach((link) => {\r\n let wave = Ripple.getInstance(link);\r\n let color = this.options.sidenavColor;\r\n\r\n if (wave && wave._options.sidenavColor !== this.options.sidenavColor) {\r\n wave.dispose();\r\n } else if (wave) {\r\n return;\r\n }\r\n\r\n if (\r\n localStorage.theme === \"dark\" ||\r\n (!(\"theme\" in localStorage) &&\r\n window.matchMedia(\"(prefers-color-scheme: dark)\").matches)\r\n ) {\r\n color = \"white\";\r\n }\r\n\r\n wave = new Ripple(link, { rippleColor: color });\r\n });\r\n }\r\n\r\n _setupTouch() {\r\n this._touch = new Touch(this._element, \"swipe\", { threshold: 20 });\r\n this._touch.init();\r\n\r\n EventHandler.on(this._element, \"swipeleft\", (e) =>\r\n this._handleSwipe(e, this.options.sidenavRight)\r\n );\r\n\r\n EventHandler.on(this._element, \"swiperight\", (e) =>\r\n this._handleSwipe(e, !this.options.sidenavRight)\r\n );\r\n }\r\n\r\n _setActive(link, reference) {\r\n // Link\r\n link.setAttribute(\"data-te-sidebar-state-active\", \"\");\r\n\r\n if (this._activeNode) {\r\n link.removeAttribute(\"data-te-sidebar-state-active\");\r\n }\r\n this._activeNode = link;\r\n\r\n // Collapse\r\n\r\n const [collapse] = SelectorEngine.parents(\r\n this._activeNode,\r\n SELECTOR_COLLAPSE\r\n );\r\n\r\n if (!collapse) {\r\n this._setActiveCategory();\r\n return;\r\n }\r\n\r\n // Category\r\n\r\n const [category] = SelectorEngine.prev(collapse, SELECTOR_LINK);\r\n this._setActiveCategory(category);\r\n\r\n // Expand active collapse\r\n\r\n if (!reference && !this._slimCollapsed) {\r\n Collapse.getInstance(collapse).show();\r\n }\r\n }\r\n\r\n _setActiveCategory(el) {\r\n this.navigation.forEach((menu) => {\r\n const categories = SelectorEngine.find(SELECTOR_COLLAPSE, menu);\r\n\r\n categories.forEach((collapse) => {\r\n const [collapseToggler] = SelectorEngine.prev(collapse, SELECTOR_LINK);\r\n\r\n if (collapseToggler !== el) {\r\n collapseToggler.removeAttribute(\"data-te-sidenav-state-active\");\r\n } else {\r\n collapseToggler.setAttribute(\"data-te-sidenav-state-active\", \"\");\r\n }\r\n });\r\n });\r\n }\r\n\r\n _setActiveElements(reference) {\r\n this.navigation.forEach((menu) => {\r\n const links = SelectorEngine.find(SELECTOR_LINK, menu);\r\n links\r\n .filter((link) => {\r\n return SelectorEngine.next(link, SELECTOR_COLLAPSE).length === 0;\r\n })\r\n .forEach((link) => {\r\n if (this._isActive(link, reference) && link !== this._activeNode) {\r\n this._setActive(link, reference);\r\n }\r\n });\r\n });\r\n reference && this._updateFocus(this.isVisible);\r\n }\r\n\r\n _setColor() {\r\n const colors = [\r\n \"primary\",\r\n \"secondary\",\r\n \"success\",\r\n \"info\",\r\n \"warning\",\r\n \"danger\",\r\n \"light\",\r\n \"dark\",\r\n ];\r\n const { sidenavColor: optionColor } = this.options;\r\n const color = colors.includes(optionColor) ? optionColor : \"primary\";\r\n\r\n colors.forEach((color) => {\r\n this._element.classList.remove(`sidenav-${color}`);\r\n });\r\n\r\n Manipulator.addClass(this._element, `sidenav-${color}`);\r\n }\r\n\r\n _setContentOffsets(show, offsets, initial) {\r\n this._content.forEach((el, i) => {\r\n const padding = this._getOffsetValue(show, {\r\n index: i,\r\n property: \"padding\",\r\n offsets,\r\n });\r\n const margin = this._getOffsetValue(show, {\r\n index: i,\r\n property: \"margin\",\r\n offsets,\r\n });\r\n\r\n const style = {};\r\n\r\n if (!initial) {\r\n style.transition = `all ${this.transitionDuration} linear`;\r\n }\r\n\r\n style[offsets.padding.property] = `${padding}px`;\r\n\r\n style[offsets.margin.property] = `${margin}px`;\r\n\r\n Manipulator.style(el, style);\r\n\r\n if (!show) {\r\n return;\r\n }\r\n\r\n if (initial) {\r\n Manipulator.style(el, {\r\n transition: this._initialContentStyle[i].transition,\r\n });\r\n return;\r\n }\r\n\r\n EventHandler.on(el, \"transitionend\", () => {\r\n Manipulator.style(el, {\r\n transition: this._initialContentStyle[i].transition,\r\n });\r\n });\r\n });\r\n }\r\n\r\n _setMode(mode) {\r\n if (this.options.sidenavMode === mode) {\r\n return;\r\n }\r\n\r\n this._options.sidenavMode = mode;\r\n\r\n this._update(this.isVisible);\r\n }\r\n\r\n _setSlim(isSlimCollapsed) {\r\n const events = isSlimCollapsed\r\n ? [\"collapse\", \"collapsed\"]\r\n : [\"expand\", \"expanded\"];\r\n this._triggerEvents(...events);\r\n\r\n if (isSlimCollapsed) {\r\n this._collapseItems();\r\n }\r\n\r\n this._slimCollapsed = isSlimCollapsed;\r\n\r\n this._toggleSlimDisplay(isSlimCollapsed);\r\n\r\n Manipulator.style(this._element, { width: `${this.width}px` });\r\n\r\n this._updateOffsets(this.isVisible);\r\n }\r\n\r\n _setTabindex(tabIndexValue) {\r\n this.links.forEach((link) => {\r\n link.tabIndex = tabIndexValue ? 0 : -1;\r\n });\r\n }\r\n\r\n _emitEvents(show) {\r\n const events = show ? [\"show\", \"shown\"] : [\"hide\", \"hidden\"];\r\n this._triggerEvents(...events);\r\n }\r\n\r\n _rotateArrow(toggler, collapsed) {\r\n const [arrow] = SelectorEngine.children(toggler, `[${ARROW_DATA}]`);\r\n\r\n if (!arrow) {\r\n return;\r\n }\r\n\r\n collapsed\r\n ? Manipulator.removeClass(arrow, \"rotate-180\")\r\n : Manipulator.addClass(arrow, \"rotate-180\");\r\n }\r\n\r\n _toggleCategory(e, instance) {\r\n e.preventDefault();\r\n\r\n instance.toggle();\r\n\r\n if (this._slimCollapsed && this.options.sidenavExpandable) {\r\n this._tempSlim = true;\r\n\r\n this._setSlim(false);\r\n }\r\n }\r\n\r\n _toggleSlimDisplay(slim) {\r\n const slimCollapsedElements = SelectorEngine.find(\r\n SELECTOR_SHOW_SLIM,\r\n this._element\r\n );\r\n const fullWidthElements = SelectorEngine.find(\r\n SELECTOR_HIDE_SLIM,\r\n this._element\r\n );\r\n\r\n const toggleElements = () => {\r\n slimCollapsedElements.forEach((el) => {\r\n Manipulator.style(el, {\r\n display: this._slimCollapsed ? \"unset\" : \"none\",\r\n });\r\n });\r\n\r\n fullWidthElements.forEach((el) => {\r\n Manipulator.style(el, {\r\n display: this._slimCollapsed ? \"none\" : \"unset\",\r\n });\r\n });\r\n };\r\n\r\n if (slim) {\r\n setTimeout(\r\n () => toggleElements(true),\r\n this.options.sidenavTransitionDuration\r\n );\r\n } else {\r\n toggleElements();\r\n }\r\n }\r\n\r\n async _triggerEvents(startEvent, completeEvent) {\r\n EventHandler.trigger(this._element, `${startEvent}.te.sidenav`);\r\n\r\n if (completeEvent) {\r\n await setTimeout(() => {\r\n EventHandler.trigger(this._element, `${completeEvent}.te.sidenav`);\r\n }, this.options.sidenavTransitionDuration + 5);\r\n }\r\n }\r\n\r\n _isiPhone() {\r\n return /iPhone|iPod/i.test(navigator.userAgent);\r\n }\r\n\r\n _update(show) {\r\n // workaround for iphone issues\r\n if (show && this._isiPhone()) {\r\n Manipulator.addClass(this._element, \"ps--scrolling-y\");\r\n }\r\n\r\n if (this.toggler) {\r\n this._updateTogglerAria(show);\r\n }\r\n\r\n this._updateDisplay(show);\r\n\r\n if (this.options.sidenavBackdrop) {\r\n this._updateBackdrop(show);\r\n }\r\n\r\n this._updateOffsets(show);\r\n\r\n if (\r\n show &&\r\n this.options.sidenavCloseOnEsc &&\r\n this.options.sidenavMode !== \"side\"\r\n ) {\r\n EventHandler.on(window, \"keydown\", this.escHandler);\r\n }\r\n\r\n if (this.options.sidenavFocusTrap) {\r\n this._updateFocus(show);\r\n }\r\n }\r\n\r\n _updateDisplay(show) {\r\n const translation = show ? 0 : this.translation;\r\n Manipulator.style(this._element, {\r\n transform: `translateX(${translation}%)`,\r\n });\r\n }\r\n\r\n _updateFocus(show) {\r\n this._setTabindex(show);\r\n\r\n if (this.options.sidenavMode === \"over\" && this.options.sidenavFocusTrap) {\r\n if (show) {\r\n this._focusTrap.trap();\r\n return;\r\n }\r\n\r\n this._focusTrap.disable();\r\n }\r\n\r\n this._focusTrap.disable();\r\n }\r\n\r\n _updateOffsets(show, initial = false) {\r\n const [paddingPosition, marginPosition] = this.options.sidenavRight\r\n ? [\"right\", \"left\"]\r\n : [\"left\", \"right\"];\r\n\r\n const padding = {\r\n property: this._getProperty(\"padding\", paddingPosition),\r\n value: this.options.sidenavMode === \"over\" ? 0 : this.width,\r\n };\r\n\r\n const margin = {\r\n property: this._getProperty(\"margin\", marginPosition),\r\n value: this.options.sidenavMode === \"push\" ? -1 * this.width : 0,\r\n };\r\n\r\n EventHandler.trigger(this._element, \"update.te.sidenav\", {\r\n margin,\r\n padding,\r\n });\r\n\r\n if (!this._content) {\r\n return;\r\n }\r\n this._content.className = \"\";\r\n\r\n this._setContentOffsets(show, { padding, margin }, initial);\r\n }\r\n\r\n _updateTogglerAria(show) {\r\n this.toggler.setAttribute(\"aria-expanded\", show);\r\n }\r\n\r\n _addBackdropOnInit = () => {\r\n if (this._options.sidenavHidden) {\r\n return;\r\n }\r\n this._backdrop.show();\r\n EventHandler.off(this._element, \"transitionend\", this._addBackdropOnInit);\r\n };\r\n\r\n // Static\r\n\r\n static toggleSidenav() {\r\n return function (e) {\r\n const toggler = SelectorEngine.closest(e.target, SELECTOR_TOGGLE);\r\n\r\n const elementSelector = Manipulator.getDataAttributes(toggler).target;\r\n SelectorEngine.find(elementSelector).forEach((element) => {\r\n const instance = Sidenav.getInstance(element) || new Sidenav(element);\r\n instance.toggle();\r\n });\r\n };\r\n }\r\n\r\n static jQueryInterface(config, options) {\r\n return this.each(function () {\r\n let data = Data.getData(this, DATA_KEY);\r\n const _config = typeof config === \"object\" && config;\r\n\r\n if (!data && /dispose/.test(config)) {\r\n return;\r\n }\r\n\r\n if (!data) {\r\n data = new Sidenav(this, _config);\r\n }\r\n\r\n if (typeof config === \"string\") {\r\n if (typeof data[config] === \"undefined\") {\r\n throw new TypeError(`No method named \"${config}\"`);\r\n }\r\n\r\n data[config](options);\r\n }\r\n });\r\n }\r\n\r\n static getInstance(element) {\r\n return Data.getData(element, DATA_KEY);\r\n }\r\n\r\n static getOrCreateInstance(element, config = {}) {\r\n return (\r\n this.getInstance(element) ||\r\n new this(element, typeof config === \"object\" ? config : null)\r\n );\r\n }\r\n}\r\n\r\nexport default Sidenav;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport Data from \"../dom/data\";\r\nimport EventHandler from \"../dom/event-handler\";\r\nimport SelectorEngine from \"../dom/selector-engine\";\r\nimport Manipulator from \"../dom/manipulator\";\r\nimport { typeCheckConfig } from \"../util/index\";\r\nimport {\r\n LEFT_ARROW,\r\n RIGHT_ARROW,\r\n UP_ARROW,\r\n DOWN_ARROW,\r\n HOME,\r\n END,\r\n ENTER,\r\n SPACE,\r\n TAB,\r\n} from \"../util/keycodes\";\r\n\r\n/*\r\n------------------------------------------------------------------------\r\nConstants\r\n------------------------------------------------------------------------\r\n*/\r\n\r\nconst NAME = \"stepper\";\r\nconst DATA_KEY = \"te.stepper\";\r\nconst EVENT_KEY = `.${DATA_KEY}`;\r\nconst REF = `data-te-${NAME}`;\r\n\r\nconst STEPPER_HORIZONTAL = \"horizontal\";\r\nconst STEPPER_VERTICAL = \"vertical\";\r\n\r\nconst DefaultType = {\r\n stepperType: \"string\",\r\n stepperLinear: \"boolean\",\r\n stepperNoEditable: \"boolean\",\r\n stepperActive: \"string\",\r\n stepperCompleted: \"string\",\r\n stepperInvalid: \"string\",\r\n stepperDisabled: \"string\",\r\n stepperVerticalBreakpoint: \"number\",\r\n stepperMobileBreakpoint: \"number\",\r\n stepperMobileBarBreakpoint: \"number\",\r\n};\r\n\r\nconst Default = {\r\n stepperType: STEPPER_HORIZONTAL,\r\n stepperLinear: false,\r\n stepperNoEditable: false,\r\n stepperActive: \"\",\r\n stepperCompleted: \"\",\r\n stepperInvalid: \"\",\r\n stepperDisabled: \"\",\r\n stepperVerticalBreakpoint: 0,\r\n stepperMobileBreakpoint: 0,\r\n stepperMobileBarBreakpoint: 4,\r\n};\r\n\r\nconst EVENT_MOUSEDOWN = `mousedown${EVENT_KEY}`;\r\nconst EVENT_KEYDOWN = `keydown${EVENT_KEY}`;\r\nconst EVENT_KEYUP = `keyup${EVENT_KEY}`;\r\nconst EVENT_RESIZE = `resize${EVENT_KEY}`;\r\n\r\nconst STEP_REF = `[${REF}-step-ref]`;\r\nconst HEAD_REF = `[${REF}-head-ref]`;\r\nconst HEAD_TEXT_REF = `[${REF}-head-text-ref]`;\r\nconst HEAD_ICON_REF = `[${REF}-head-icon-ref]`;\r\nconst CONTENT_REF = `[${REF}-content-ref]`;\r\n\r\nclass Stepper {\r\n constructor(element, options) {\r\n this._element = element;\r\n this._options = this._getConfig(options);\r\n this._elementHeight = 0;\r\n this._steps = SelectorEngine.find(`${STEP_REF}`, this._element);\r\n this._currentView = \"\";\r\n this._activeStepIndex = 0;\r\n this._verticalStepperStyles = [];\r\n\r\n if (this._element) {\r\n Data.setData(element, DATA_KEY, this);\r\n this._init();\r\n }\r\n }\r\n\r\n // Getters\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n get activeStep() {\r\n return this._steps[this._activeStepIndex];\r\n }\r\n\r\n get activeStepIndex() {\r\n return this._activeStepIndex;\r\n }\r\n\r\n // Public\r\n\r\n dispose() {\r\n this._steps.forEach((el) => {\r\n EventHandler.off(el, EVENT_MOUSEDOWN);\r\n EventHandler.off(el, EVENT_KEYDOWN);\r\n });\r\n\r\n EventHandler.off(window, EVENT_RESIZE);\r\n\r\n Data.removeData(this._element, DATA_KEY);\r\n this._element = null;\r\n }\r\n\r\n changeStep(index) {\r\n this._toggleStep(index);\r\n }\r\n\r\n nextStep() {\r\n this._toggleStep(this._activeStepIndex + 1);\r\n }\r\n\r\n previousStep() {\r\n this._toggleStep(this._activeStepIndex - 1);\r\n }\r\n\r\n // Private\r\n _init() {\r\n const activeStep = SelectorEngine.find(`${STEP_REF}`, this._element)[\r\n this._activeStepIndex\r\n ].setAttribute(\"data-te\", \"active-step\");\r\n const stepperHeadText = SelectorEngine.find(\r\n `${HEAD_TEXT_REF}`,\r\n this._element\r\n );\r\n const stepperHeadIcon = SelectorEngine.find(\r\n `${HEAD_ICON_REF}`,\r\n this._element\r\n );\r\n\r\n if (activeStep) {\r\n this._activeStepIndex = this._steps.indexOf(activeStep);\r\n this._toggleStepClass(\r\n this._activeStepIndex,\r\n \"add\",\r\n this._options.stepperActive\r\n );\r\n\r\n stepperHeadText[this._activeStepIndex].classList.add(\"font-medium\");\r\n stepperHeadIcon[this._activeStepIndex].classList.add(\"!bg-primary-100\");\r\n stepperHeadIcon[this._activeStepIndex].classList.add(\"!text-primary-700\");\r\n } else {\r\n stepperHeadText[this._activeStepIndex].classList.add(\"font-medium\");\r\n stepperHeadIcon[this._activeStepIndex].classList.add(\"!bg-primary-100\");\r\n stepperHeadIcon[this._activeStepIndex].classList.add(\"!text-primary-700\");\r\n this._toggleStepClass(\r\n this._activeStepIndex,\r\n \"add\",\r\n this._options.stepperActive\r\n );\r\n }\r\n\r\n this._bindMouseDown();\r\n this._bindKeysNavigation();\r\n\r\n switch (this._options.stepperType) {\r\n case STEPPER_VERTICAL:\r\n this._toggleVertical();\r\n break;\r\n default:\r\n this._toggleHorizontal();\r\n break;\r\n }\r\n\r\n if (\r\n this._options.stepperVerticalBreakpoint ||\r\n this._options.stepperMobileBreakpoint\r\n ) {\r\n this._toggleStepperView();\r\n }\r\n\r\n this._bindResize();\r\n }\r\n\r\n _getConfig(config) {\r\n const dataAttributes = Manipulator.getDataAttributes(this._element);\r\n\r\n config = {\r\n ...Default,\r\n ...dataAttributes,\r\n ...config,\r\n };\r\n\r\n typeCheckConfig(NAME, config, DefaultType);\r\n\r\n return config;\r\n }\r\n\r\n _bindMouseDown() {\r\n this._steps.forEach((el) => {\r\n const stepHead = SelectorEngine.findOne(`${HEAD_REF}`, el);\r\n\r\n EventHandler.on(stepHead, EVENT_MOUSEDOWN, (e) => {\r\n const step = SelectorEngine.parents(e.target, `${STEP_REF}`)[0];\r\n const stepIndex = this._steps.indexOf(step);\r\n\r\n e.preventDefault();\r\n this._toggleStep(stepIndex);\r\n });\r\n });\r\n }\r\n\r\n _bindResize() {\r\n EventHandler.on(window, EVENT_RESIZE, () => {\r\n if (this._currentView === STEPPER_VERTICAL) {\r\n this._setSingleStepHeight(this.activeStep);\r\n }\r\n\r\n if (this._currentView === STEPPER_HORIZONTAL) {\r\n this._setHeight(this.activeStep);\r\n }\r\n\r\n if (\r\n this._options.stepperVerticalBreakpoint ||\r\n this._options.stepperMobileBreakpoint\r\n ) {\r\n this._toggleStepperView();\r\n }\r\n });\r\n }\r\n\r\n _toggleStepperView() {\r\n const shouldBeHorizontal =\r\n this._options.stepperVerticalBreakpoint < window.innerWidth;\r\n const shouldBeVertical =\r\n this._options.stepperVerticalBreakpoint > window.innerWidth;\r\n const shouldBeMobile =\r\n this._options.stepperMobileBreakpoint > window.innerWidth;\r\n\r\n if (shouldBeHorizontal && this._currentView !== STEPPER_HORIZONTAL) {\r\n this._toggleHorizontal();\r\n }\r\n\r\n if (\r\n shouldBeVertical &&\r\n !shouldBeMobile &&\r\n this._currentView !== STEPPER_VERTICAL\r\n ) {\r\n this._steps.forEach((el) => {\r\n const stepContent = SelectorEngine.findOne(`${CONTENT_REF}`, el);\r\n\r\n this._resetStepperHeight();\r\n this._showElement(stepContent);\r\n });\r\n\r\n this._toggleVertical();\r\n }\r\n }\r\n\r\n _toggleStep(index) {\r\n if (this._activeStepIndex === index) {\r\n return;\r\n }\r\n\r\n if (this._options.stepperNoEditable) {\r\n this._toggleDisabled();\r\n }\r\n\r\n this._showElement(\r\n SelectorEngine.findOne(`${CONTENT_REF}`, this._steps[index])\r\n );\r\n this._toggleActive(index);\r\n\r\n if (index > this._activeStepIndex) {\r\n this._toggleCompleted(this._activeStepIndex);\r\n }\r\n\r\n if (this._currentView === STEPPER_HORIZONTAL) {\r\n this._animateHorizontalStep(index);\r\n } else {\r\n this._animateVerticalStep(index);\r\n this._setSingleStepHeight(this._steps[index]);\r\n }\r\n\r\n this._toggleStepTabIndex(\r\n SelectorEngine.findOne(`${HEAD_REF}`, this.activeStep),\r\n SelectorEngine.findOne(`${HEAD_REF}`, this._steps[index])\r\n );\r\n\r\n this._activeStepIndex = index;\r\n\r\n this._steps[this._activeStepIndex].setAttribute(\"data-te\", \"active-step\");\r\n this._steps.forEach((step, index) => {\r\n if (step[this._activeStepIndex] !== index) {\r\n step.removeAttribute(\"data-te\");\r\n }\r\n });\r\n }\r\n\r\n _resetStepperHeight() {\r\n this._element.style.height = \"\";\r\n }\r\n\r\n _setStepsHeight() {\r\n this._steps.forEach((el) => {\r\n const stepContent = SelectorEngine.findOne(`${CONTENT_REF}`, el);\r\n const stepComputed = window.getComputedStyle(stepContent);\r\n this._verticalStepperStyles.push({\r\n paddingTop: parseFloat(stepComputed.paddingTop),\r\n paddingBottom: parseFloat(stepComputed.paddingBottom),\r\n });\r\n const stepHeight = stepContent.scrollHeight;\r\n stepContent.style.height = `${stepHeight}px`;\r\n });\r\n }\r\n\r\n _setSingleStepHeight(step) {\r\n const stepContent = SelectorEngine.findOne(`${CONTENT_REF}`, step);\r\n const isActiveStep = this.activeStep === step;\r\n const stepIndex = this._steps.indexOf(step);\r\n let stepContentHeight;\r\n\r\n if (!isActiveStep) {\r\n stepContentHeight =\r\n stepContent.scrollHeight +\r\n this._verticalStepperStyles[stepIndex].paddingTop +\r\n this._verticalStepperStyles[stepIndex].paddingBottom;\r\n } else {\r\n stepContent.style.height = \"\";\r\n stepContentHeight = stepContent.scrollHeight;\r\n }\r\n\r\n stepContent.style.height = `${stepContentHeight}px`;\r\n }\r\n\r\n _toggleVertical() {\r\n this._currentView = STEPPER_VERTICAL;\r\n\r\n this._setStepsHeight();\r\n this._hideInactiveSteps();\r\n }\r\n\r\n _toggleHorizontal() {\r\n this._currentView = STEPPER_HORIZONTAL;\r\n\r\n this._setHeight(this.activeStep);\r\n this._hideInactiveSteps();\r\n }\r\n\r\n _toggleStepperClass() {\r\n const vertical = SelectorEngine.findOne(\r\n \"[data-te-stepper-type]\",\r\n this._element\r\n );\r\n\r\n if (vertical !== null) {\r\n this._steps.forEach((el) => {\r\n SelectorEngine.findOne(`${CONTENT_REF}`, el).classList.remove(\"!my-0\");\r\n SelectorEngine.findOne(`${CONTENT_REF}`, el).classList.remove(\"!py-0\");\r\n SelectorEngine.findOne(`${CONTENT_REF}`, el).classList.remove(\"!h-0\");\r\n });\r\n }\r\n }\r\n\r\n _toggleStepClass(index, action, className) {\r\n // condition to prevent errors if the user has not set any custom classes like active, disabled etc.\r\n if (className) {\r\n this._steps[index].classList[action](className);\r\n }\r\n }\r\n\r\n _bindKeysNavigation() {\r\n this._toggleStepTabIndex(\r\n false,\r\n SelectorEngine.findOne(`${HEAD_REF}`, this.activeStep)\r\n );\r\n\r\n this._steps.forEach((el) => {\r\n const stepHead = SelectorEngine.findOne(`${HEAD_REF}`, el);\r\n\r\n EventHandler.on(stepHead, EVENT_KEYDOWN, (e) => {\r\n const focusedStep = SelectorEngine.parents(\r\n e.currentTarget,\r\n `${STEP_REF}`\r\n )[0];\r\n const nextStep = SelectorEngine.next(focusedStep, `${STEP_REF}`)[0];\r\n const prevStep = SelectorEngine.prev(focusedStep, `${STEP_REF}`)[0];\r\n const focusedStepHead = SelectorEngine.findOne(\r\n `${HEAD_REF}`,\r\n focusedStep\r\n );\r\n const activeStepHead = SelectorEngine.findOne(\r\n `${HEAD_REF}`,\r\n this.activeStep\r\n );\r\n let nextStepHead = null;\r\n let prevStepHead = null;\r\n\r\n if (nextStep) {\r\n nextStepHead = SelectorEngine.findOne(`${HEAD_REF}`, nextStep);\r\n }\r\n\r\n if (prevStep) {\r\n prevStepHead = SelectorEngine.findOne(`${HEAD_REF}`, prevStep);\r\n }\r\n\r\n if (\r\n e.keyCode === LEFT_ARROW &&\r\n this._currentView !== STEPPER_VERTICAL\r\n ) {\r\n if (prevStepHead) {\r\n this._toggleStepTabIndex(focusedStepHead, prevStepHead);\r\n this._toggleOutlineStyles(focusedStepHead, prevStepHead);\r\n\r\n prevStepHead.focus();\r\n } else if (nextStepHead) {\r\n this._toggleStepTabIndex(focusedStepHead, nextStepHead);\r\n this._toggleOutlineStyles(focusedStepHead, nextStepHead);\r\n\r\n nextStepHead.focus();\r\n }\r\n }\r\n\r\n if (\r\n e.keyCode === RIGHT_ARROW &&\r\n this._currentView !== STEPPER_VERTICAL\r\n ) {\r\n if (nextStepHead) {\r\n this._toggleStepTabIndex(focusedStepHead, nextStepHead);\r\n this._toggleOutlineStyles(focusedStepHead, nextStepHead);\r\n\r\n nextStepHead.focus();\r\n } else if (prevStepHead) {\r\n this._toggleStepTabIndex(focusedStepHead, prevStepHead);\r\n this._toggleOutlineStyles(focusedStepHead, prevStepHead);\r\n\r\n prevStepHead.focus();\r\n }\r\n }\r\n\r\n if (\r\n e.keyCode === DOWN_ARROW &&\r\n this._currentView === STEPPER_VERTICAL\r\n ) {\r\n e.preventDefault();\r\n\r\n if (nextStepHead) {\r\n this._toggleStepTabIndex(focusedStepHead, nextStepHead);\r\n this._toggleOutlineStyles(focusedStepHead, nextStepHead);\r\n\r\n nextStepHead.focus();\r\n }\r\n }\r\n\r\n if (e.keyCode === UP_ARROW && this._currentView === STEPPER_VERTICAL) {\r\n e.preventDefault();\r\n\r\n if (prevStepHead) {\r\n this._toggleStepTabIndex(focusedStepHead, prevStepHead);\r\n this._toggleOutlineStyles(focusedStepHead, prevStepHead);\r\n\r\n prevStepHead.focus();\r\n }\r\n }\r\n\r\n if (e.keyCode === HOME) {\r\n const firstStepHead = SelectorEngine.findOne(\r\n `${HEAD_REF}`,\r\n this._steps[0]\r\n );\r\n\r\n this._toggleStepTabIndex(focusedStepHead, firstStepHead);\r\n this._toggleOutlineStyles(focusedStepHead, firstStepHead);\r\n\r\n firstStepHead.focus();\r\n }\r\n\r\n if (e.keyCode === END) {\r\n const lastStep = this._steps[this._steps.length - 1];\r\n const lastStepHead = SelectorEngine.findOne(`${HEAD_REF}`, lastStep);\r\n this._toggleStepTabIndex(focusedStepHead, lastStepHead);\r\n this._toggleOutlineStyles(focusedStepHead, lastStepHead);\r\n\r\n lastStepHead.focus();\r\n }\r\n\r\n if (e.keyCode === ENTER || e.keyCode === SPACE) {\r\n e.preventDefault();\r\n\r\n this.changeStep(this._steps.indexOf(focusedStep));\r\n }\r\n\r\n if (e.keyCode === TAB) {\r\n this._toggleStepTabIndex(focusedStepHead, activeStepHead);\r\n this._toggleOutlineStyles(focusedStepHead, false);\r\n\r\n activeStepHead.focus();\r\n }\r\n });\r\n\r\n EventHandler.on(stepHead, EVENT_KEYUP, (e) => {\r\n const focusedStep = SelectorEngine.parents(\r\n e.currentTarget,\r\n `${STEP_REF}`\r\n )[0];\r\n const focusedStepHead = SelectorEngine.findOne(\r\n `${HEAD_REF}`,\r\n focusedStep\r\n );\r\n const activeStepHead = SelectorEngine.findOne(\r\n `${HEAD_REF}`,\r\n this.activeStep\r\n );\r\n\r\n if (e.keyCode === TAB) {\r\n this._toggleStepTabIndex(focusedStepHead, activeStepHead);\r\n this._toggleOutlineStyles(false, activeStepHead);\r\n\r\n activeStepHead.focus();\r\n }\r\n });\r\n });\r\n }\r\n\r\n _toggleStepTabIndex(focusedElement, newTarget) {\r\n if (focusedElement) {\r\n focusedElement.setAttribute(\"tabIndex\", -1);\r\n }\r\n\r\n if (newTarget) {\r\n newTarget.setAttribute(\"tabIndex\", 0);\r\n }\r\n }\r\n\r\n _toggleOutlineStyles(focusedElement, newTarget) {\r\n if (focusedElement) {\r\n focusedElement.style.outline = \"\";\r\n }\r\n\r\n if (newTarget) {\r\n newTarget.style.outline = \"revert\";\r\n }\r\n }\r\n\r\n _toggleDisabled() {\r\n const stepperHead = SelectorEngine.find(`${HEAD_REF}`, this._element);\r\n const stepperHeadIcon = SelectorEngine.find(\r\n `${HEAD_ICON_REF}`,\r\n this._element\r\n );\r\n\r\n stepperHead[this._activeStepIndex].classList.add(\"color-[#858585]\");\r\n stepperHead[this._activeStepIndex].classList.add(\"cursor-default\");\r\n stepperHeadIcon[this._activeStepIndex].classList.add(\"!bg-[#858585]\");\r\n this._toggleStepClass(\r\n this._activeStepIndex,\r\n \"add\",\r\n this._options.stepperDisabled\r\n );\r\n }\r\n\r\n _toggleActive(index) {\r\n const stepperHeadText = SelectorEngine.find(\r\n `${HEAD_TEXT_REF}`,\r\n this._element\r\n );\r\n const stepperHeadIcon = SelectorEngine.find(\r\n `${HEAD_ICON_REF}`,\r\n this._element\r\n );\r\n\r\n stepperHeadText[index].classList.add(\"font-medium\");\r\n stepperHeadIcon[index].classList.add(\"!bg-primary-100\");\r\n stepperHeadIcon[index].classList.add(\"!text-primary-700\");\r\n stepperHeadIcon[index].classList.remove(\"!bg-success-100\");\r\n stepperHeadIcon[index].classList.remove(\"!text-success-700\");\r\n\r\n stepperHeadText[this._activeStepIndex].classList.remove(\"font-medium\");\r\n stepperHeadIcon[this._activeStepIndex].classList.remove(\"!bg-primary-100\");\r\n stepperHeadIcon[this._activeStepIndex].classList.remove(\r\n \"!text-primary-700\"\r\n );\r\n\r\n this._toggleStepClass(index, \"add\", this._options.stepperActive);\r\n this._toggleStepClass(\r\n this._activeStepIndex,\r\n \"remove\",\r\n this._options.stepperActive\r\n );\r\n }\r\n\r\n _toggleCompleted(index) {\r\n const stepperHeadIcon = SelectorEngine.find(\r\n `${HEAD_ICON_REF}`,\r\n this._element\r\n );\r\n stepperHeadIcon[index].classList.add(\"!bg-success-100\");\r\n stepperHeadIcon[index].classList.add(\"!text-success-700\");\r\n stepperHeadIcon[index].classList.remove(\"!bg-danger-100\");\r\n stepperHeadIcon[index].classList.remove(\"!text-danger-700\");\r\n\r\n this._toggleStepClass(index, \"add\", this._options.stepperCompleted);\r\n this._toggleStepClass(index, \"remove\", this._options.stepperInvalid);\r\n }\r\n\r\n _hideInactiveSteps() {\r\n this._steps.forEach((el) => {\r\n if (!el.getAttribute(\"data-te\")) {\r\n this._hideElement(SelectorEngine.findOne(`${CONTENT_REF}`, el));\r\n }\r\n });\r\n }\r\n\r\n _setHeight(stepElement) {\r\n const stepContent = SelectorEngine.findOne(`${CONTENT_REF}`, stepElement);\r\n const contentStyle = getComputedStyle(stepContent);\r\n const stepHead = SelectorEngine.findOne(`${HEAD_REF}`, stepElement);\r\n\r\n const headStyle = getComputedStyle(stepHead);\r\n const stepContentHeight =\r\n stepContent.offsetHeight +\r\n parseFloat(contentStyle.marginTop) +\r\n parseFloat(contentStyle.marginBottom);\r\n\r\n const stepHeadHeight =\r\n stepHead.offsetHeight +\r\n parseFloat(headStyle.marginTop) +\r\n parseFloat(headStyle.marginBottom);\r\n\r\n this._element.style.height = `${stepHeadHeight + stepContentHeight}px`;\r\n }\r\n\r\n _hideElement(stepContent) {\r\n const isActive = SelectorEngine.parents(\r\n stepContent,\r\n `${STEP_REF}`\r\n )[0].getAttribute(\"data-te\");\r\n\r\n // prevent hiding during a quick step change\r\n if (!isActive && this._currentView !== STEPPER_VERTICAL) {\r\n // stepContent.style.display = 'none';\r\n } else {\r\n stepContent.classList.add(\"!my-0\");\r\n stepContent.classList.add(\"!py-0\");\r\n stepContent.classList.add(\"!h-0\");\r\n }\r\n }\r\n\r\n _showElement(stepContent) {\r\n if (this._currentView === STEPPER_VERTICAL) {\r\n stepContent.classList.remove(\"!my-0\");\r\n stepContent.classList.remove(\"!py-0\");\r\n stepContent.classList.remove(\"!h-0\");\r\n } else {\r\n stepContent.style.display = \"block\";\r\n }\r\n }\r\n\r\n _animateHorizontalStep(index) {\r\n const isForward = index > this._activeStepIndex;\r\n const nextStepContent = SelectorEngine.findOne(\r\n `${CONTENT_REF}`,\r\n this._steps[index]\r\n );\r\n const activeStepContent = SelectorEngine.findOne(\r\n `${CONTENT_REF}`,\r\n this.activeStep\r\n );\r\n\r\n let nextStepAnimation;\r\n let activeStepAnimation;\r\n\r\n this._steps.forEach((el, i) => {\r\n const stepContent = SelectorEngine.findOne(`${CONTENT_REF}`, el);\r\n\r\n if (i !== index && i !== this._activeStepIndex) {\r\n this._hideElement(stepContent);\r\n }\r\n });\r\n\r\n const CLASS_NAME_SLIDE_RIGHT = \"translate-x-[150%]\";\r\n const CLASS_NAME_SLIDE_LEFT = \"-translate-x-[150%]\";\r\n const CLASS_NAME_SLIDE_IN = \"translate-0\";\r\n\r\n if (isForward) {\r\n activeStepAnimation = CLASS_NAME_SLIDE_LEFT;\r\n nextStepAnimation = CLASS_NAME_SLIDE_IN;\r\n nextStepContent.classList.remove(\"translate-x-[150%]\");\r\n nextStepContent.classList.remove(\"-translate-x-[150%]\");\r\n } else {\r\n activeStepAnimation = CLASS_NAME_SLIDE_RIGHT;\r\n nextStepAnimation = CLASS_NAME_SLIDE_IN;\r\n nextStepContent.classList.remove(\"-translate-x-[150%]\");\r\n nextStepContent.classList.remove(\"translate-x-[150%]\");\r\n }\r\n\r\n activeStepContent.classList.add(activeStepAnimation);\r\n nextStepContent.classList.add(nextStepAnimation);\r\n\r\n this._setHeight(this._steps[index]);\r\n }\r\n\r\n _animateVerticalStep(index) {\r\n const nextStepContent = SelectorEngine.findOne(\r\n `${CONTENT_REF}`,\r\n this._steps[index]\r\n );\r\n const activeStepContent = SelectorEngine.findOne(\r\n `${CONTENT_REF}`,\r\n this.activeStep\r\n );\r\n\r\n this._hideElement(activeStepContent);\r\n this._showElement(nextStepContent);\r\n }\r\n\r\n static getInstance(element) {\r\n return Data.getData(element, DATA_KEY);\r\n }\r\n\r\n static getOrCreateInstance(element, config = {}) {\r\n return (\r\n this.getInstance(element) ||\r\n new this(element, typeof config === \"object\" ? config : null)\r\n );\r\n }\r\n}\r\n\r\nexport default Stepper;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport SelectorEngine from \"../../dom/selector-engine\";\r\n\r\nconst DATA_ACTIVE = \"data-te-input-state-active\";\r\nconst DATA_SELECTED = \"data-te-input-selected\";\r\nconst DATA_MULTIPLE_ACTIVE = \"data-te-input-multiple-active\";\r\n\r\nconst SELECTOR_FORM_CHECK_INPUT = \"[data-te-form-check-input]\";\r\n\r\nclass SelectOption {\r\n constructor(\r\n id,\r\n nativeOption,\r\n multiple,\r\n value,\r\n label,\r\n selected,\r\n disabled,\r\n hidden,\r\n secondaryText,\r\n groupId,\r\n icon\r\n ) {\r\n this.id = id;\r\n this.nativeOption = nativeOption;\r\n this.multiple = multiple;\r\n this.value = value;\r\n this.label = label;\r\n this.selected = selected;\r\n this.disabled = disabled;\r\n this.hidden = hidden;\r\n this.secondaryText = secondaryText;\r\n this.groupId = groupId;\r\n this.icon = icon;\r\n this.node = null;\r\n this.active = false;\r\n }\r\n\r\n select() {\r\n if (this.multiple) {\r\n this._selectMultiple();\r\n } else {\r\n this._selectSingle();\r\n }\r\n }\r\n\r\n _selectSingle() {\r\n if (!this.selected) {\r\n this.node.setAttribute(DATA_SELECTED, \"\");\r\n this.node.setAttribute(\"aria-selected\", true);\r\n this.selected = true;\r\n\r\n if (this.nativeOption) {\r\n this.nativeOption.selected = true;\r\n }\r\n }\r\n }\r\n\r\n _selectMultiple() {\r\n if (!this.selected) {\r\n const checkbox = SelectorEngine.findOne(\r\n SELECTOR_FORM_CHECK_INPUT,\r\n this.node\r\n );\r\n checkbox.checked = true;\r\n this.node.setAttribute(DATA_SELECTED, \"\");\r\n\r\n this.node.setAttribute(\"aria-selected\", true);\r\n this.selected = true;\r\n\r\n if (this.nativeOption) {\r\n this.nativeOption.selected = true;\r\n }\r\n }\r\n }\r\n\r\n deselect() {\r\n if (this.multiple) {\r\n this._deselectMultiple();\r\n } else {\r\n this._deselectSingle();\r\n }\r\n }\r\n\r\n _deselectSingle() {\r\n if (this.selected) {\r\n this.node.removeAttribute(DATA_SELECTED);\r\n\r\n this.node.setAttribute(\"aria-selected\", false);\r\n this.selected = false;\r\n\r\n if (this.nativeOption) {\r\n this.nativeOption.selected = false;\r\n }\r\n }\r\n }\r\n\r\n _deselectMultiple() {\r\n if (this.selected) {\r\n const checkbox = SelectorEngine.findOne(\r\n SELECTOR_FORM_CHECK_INPUT,\r\n this.node\r\n );\r\n checkbox.checked = false;\r\n this.node.removeAttribute(DATA_SELECTED);\r\n\r\n this.node.setAttribute(\"aria-selected\", false);\r\n this.selected = false;\r\n\r\n if (this.nativeOption) {\r\n this.nativeOption.selected = false;\r\n }\r\n }\r\n }\r\n\r\n setNode(node) {\r\n this.node = node;\r\n }\r\n\r\n setActiveStyles() {\r\n if (!this.active) {\r\n if (this.multiple) {\r\n this.node.setAttribute(DATA_MULTIPLE_ACTIVE, \"\");\r\n return;\r\n }\r\n this.active = true;\r\n this.node.setAttribute(DATA_ACTIVE, \"\");\r\n }\r\n }\r\n\r\n removeActiveStyles() {\r\n if (this.active) {\r\n this.active = false;\r\n this.node.removeAttribute(DATA_ACTIVE);\r\n }\r\n if (this.multiple) {\r\n this.node.removeAttribute(DATA_MULTIPLE_ACTIVE);\r\n }\r\n }\r\n}\r\n\r\nexport default SelectOption;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nclass SelectionModel {\r\n constructor(multiple = false) {\r\n this._multiple = multiple;\r\n this._selections = [];\r\n }\r\n\r\n select(option) {\r\n if (this._multiple) {\r\n this._selections.push(option);\r\n } else {\r\n this._selections = [option];\r\n }\r\n }\r\n\r\n deselect(option) {\r\n if (this._multiple) {\r\n const optionIndex = this._selections.findIndex(\r\n (selection) => option === selection\r\n );\r\n this._selections.splice(optionIndex, 1);\r\n } else {\r\n this._selections = [];\r\n }\r\n }\r\n\r\n clear() {\r\n this._selections = [];\r\n }\r\n\r\n get selection() {\r\n return this._selections[0];\r\n }\r\n\r\n get selections() {\r\n return this._selections;\r\n }\r\n\r\n get label() {\r\n return this._selections[0] && this.selection.label;\r\n }\r\n\r\n get labels() {\r\n return this._selections.map((selection) => selection.label).join(\", \");\r\n }\r\n\r\n get value() {\r\n return this.selections[0] && this.selection.value;\r\n }\r\n\r\n get values() {\r\n return this._selections.map((selection) => selection.value);\r\n }\r\n}\r\n\r\nexport default SelectionModel;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nexport default function allOptionsSelected(options) {\r\n return options\r\n .filter((option) => !option.disabled)\r\n .every((option) => {\r\n return option.selected;\r\n });\r\n}\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport { element } from \"../../util/index\";\r\nimport Manipulator from \"../../dom/manipulator\";\r\nimport allOptionsSelected from \"./util\";\r\n\r\nconst DATA_FORM_OUTLINE = \"data-te-select-form-outline-ref\";\r\nconst DATA_SELECT_WRAPPER = \"data-te-select-wrapper-ref\";\r\nconst DATA_SELECT_INPUT = \"data-te-select-input-ref\";\r\nconst DATA_CLEAR_BUTTON = \"data-te-select-clear-btn-ref\";\r\nconst DATA_SELECT_DROPDOWN_CONTAINER = \"data-te-select-dropdown-container-ref\";\r\nconst DATA_DROPDOWN = \"data-te-select-dropdown-ref\";\r\nconst DATA_OPTIONS_WRAPPER = \"data-te-select-options-wrapper-ref\";\r\nconst DATA_OPTIONS_LIST = \"data-te-select-options-list-ref\";\r\nconst DATA_FILTER_INPUT = \"data-te-select-input-filter-ref\";\r\nconst DATA_OPTION = \"data-te-select-option-ref\";\r\nconst DATA_OPTION_ALL = \"data-te-select-option-all-ref\";\r\nconst DATA_SELECT_OPTION_TEXT = \"data-te-select-option-text-ref\";\r\nconst DATA_FORM_CHECK_INPUT = \"data-te-form-check-input\";\r\nconst DATA_SELECT_OPTION_GROUP = \"data-te-select-option-group-ref\";\r\nconst DATA_SELECT_OPTION_GROUP_LABEL = \"data-te-select-option-group-label-ref\";\r\n\r\nconst DATA_SELECTED = \"data-te-select-selected\";\r\n\r\nconst iconSVGTemplate = `\r\n\r\n \r\n \r\n`;\r\n\r\nconst preventKeydown = (event) => {\r\n if (event.code === \"Tab\" || event.code === \"Esc\") {\r\n return;\r\n }\r\n\r\n event.preventDefault();\r\n};\r\n\r\nfunction _setSizeClasses(element, config, defaultSize, smSize, lgSize) {\r\n if (config.selectSize === \"default\") {\r\n Manipulator.addClass(element, defaultSize);\r\n }\r\n\r\n if (config.selectSize === \"sm\") {\r\n Manipulator.addClass(element, smSize);\r\n }\r\n\r\n if (config.selectSize === \"lg\") {\r\n Manipulator.addClass(element, lgSize);\r\n }\r\n}\r\n\r\nexport function getWrapperTemplate(id, config, label, classes, selectName) {\r\n const wrapper = document.createElement(\"div\");\r\n wrapper.setAttribute(\"id\", id);\r\n wrapper.setAttribute(DATA_SELECT_WRAPPER, \"\");\r\n\r\n const formOutline = element(\"div\");\r\n formOutline.setAttribute(DATA_FORM_OUTLINE, \"\");\r\n Manipulator.addClass(formOutline, classes.formOutline);\r\n\r\n const input = element(\"input\");\r\n const role = config.selectFilter ? \"combobox\" : \"listbox\";\r\n const multiselectable = config.multiple ? \"true\" : \"false\";\r\n const disabled = config.disabled ? \"true\" : \"false\";\r\n input.setAttribute(DATA_SELECT_INPUT, \"\");\r\n Manipulator.addClass(input, classes.selectInput);\r\n\r\n _setSizeClasses(\r\n input,\r\n config,\r\n classes.selectInputSizeDefault,\r\n classes.selectInputSizeSm,\r\n classes.selectInputSizeLg\r\n );\r\n\r\n if (config.selectFormWhite) {\r\n Manipulator.addClass(input, classes.selectInputWhite);\r\n }\r\n\r\n input.setAttribute(\"type\", \"text\");\r\n input.setAttribute(\"role\", role);\r\n input.setAttribute(\"aria-multiselectable\", multiselectable);\r\n input.setAttribute(\"aria-disabled\", disabled);\r\n input.setAttribute(\"aria-haspopup\", \"true\");\r\n input.setAttribute(\"aria-expanded\", false);\r\n input.name = selectName;\r\n\r\n if (config.tabIndex) {\r\n input.setAttribute(\"tabIndex\", config.tabIndex);\r\n }\r\n\r\n if (config.disabled) {\r\n input.setAttribute(\"disabled\", \"\");\r\n }\r\n\r\n if (config.selectPlaceholder !== \"\") {\r\n input.setAttribute(\"placeholder\", config.selectPlaceholder);\r\n }\r\n\r\n if (config.selectValidation) {\r\n Manipulator.addStyle(input, {\r\n \"pointer-events\": \"none\",\r\n \"caret-color\": \"transparent\",\r\n });\r\n Manipulator.addStyle(formOutline, { cursor: \"pointer\" });\r\n } else {\r\n input.setAttribute(\"readonly\", \"true\");\r\n }\r\n\r\n if (config.selectValidation) {\r\n input.setAttribute(\"required\", \"true\");\r\n input.setAttribute(\"aria-required\", \"true\");\r\n input.addEventListener(\"keydown\", preventKeydown);\r\n }\r\n\r\n const validFeedback = element(\"div\");\r\n Manipulator.addClass(validFeedback, classes.selectValidationValid);\r\n\r\n const validFeedBackText = document.createTextNode(\r\n `${config.selectValidFeedback}`\r\n );\r\n validFeedback.appendChild(validFeedBackText);\r\n\r\n const invalidFeedback = element(\"div\");\r\n Manipulator.addClass(invalidFeedback, classes.selectValidationInvalid);\r\n\r\n const invalidFeedBackText = document.createTextNode(\r\n `${config.selectInvalidFeedback}`\r\n );\r\n invalidFeedback.appendChild(invalidFeedBackText);\r\n\r\n const clearBtn = element(\"span\");\r\n clearBtn.setAttribute(DATA_CLEAR_BUTTON, \"\");\r\n\r\n Manipulator.addClass(clearBtn, classes.selectClearBtn);\r\n\r\n _setSizeClasses(\r\n clearBtn,\r\n config,\r\n classes.selectClearBtnDefault,\r\n classes.selectClearBtnSm,\r\n classes.selectClearBtnLg\r\n );\r\n\r\n if (config.selectFormWhite) {\r\n Manipulator.addClass(clearBtn, classes.selectClearBtnWhite);\r\n }\r\n\r\n const clearBtnText = document.createTextNode(\"\\u2715\");\r\n clearBtn.appendChild(clearBtnText);\r\n clearBtn.setAttribute(\"tabindex\", \"0\");\r\n\r\n const arrow = element(\"span\");\r\n Manipulator.addClass(arrow, classes.selectArrow);\r\n\r\n _setSizeClasses(\r\n arrow,\r\n config,\r\n classes.selectArrowDefault,\r\n classes.selectArrowSm,\r\n classes.selectArrowLg\r\n );\r\n\r\n if (config.selectFormWhite) {\r\n Manipulator.addClass(arrow, classes.selectArrowWhite);\r\n }\r\n\r\n arrow.innerHTML = iconSVGTemplate;\r\n\r\n formOutline.appendChild(input);\r\n\r\n if (label) {\r\n Manipulator.addClass(label, classes.selectLabel);\r\n\r\n _setSizeClasses(\r\n label,\r\n config,\r\n classes.selectLabelSizeDefault,\r\n classes.selectLabelSizeSm,\r\n classes.selectLabelSizeLg\r\n );\r\n\r\n if (config.selectFormWhite) {\r\n Manipulator.addClass(label, classes.selectLabelWhite);\r\n }\r\n\r\n formOutline.appendChild(label);\r\n }\r\n\r\n if (config.selectValidation) {\r\n formOutline.appendChild(validFeedback);\r\n formOutline.appendChild(invalidFeedback);\r\n }\r\n\r\n if (config.selectClearButton) {\r\n formOutline.appendChild(clearBtn);\r\n }\r\n\r\n formOutline.appendChild(arrow);\r\n\r\n wrapper.appendChild(formOutline);\r\n return wrapper;\r\n}\r\n\r\nexport function getDropdownTemplate(\r\n id,\r\n config,\r\n width,\r\n height,\r\n selectAllOption,\r\n options,\r\n customContent,\r\n classes\r\n) {\r\n const dropdownContainer = document.createElement(\"div\");\r\n dropdownContainer.setAttribute(DATA_SELECT_DROPDOWN_CONTAINER, \"\");\r\n Manipulator.addClass(dropdownContainer, classes.selectDropdownContainer);\r\n\r\n dropdownContainer.setAttribute(\"id\", `${id}`);\r\n dropdownContainer.style.width = `${width}px`;\r\n\r\n const dropdown = document.createElement(\"div\");\r\n dropdown.setAttribute(\"tabindex\", 0);\r\n dropdown.setAttribute(DATA_DROPDOWN, \"\");\r\n Manipulator.addClass(dropdown, classes.dropdown);\r\n\r\n const optionsWrapper = element(\"div\");\r\n optionsWrapper.setAttribute(DATA_OPTIONS_WRAPPER, \"\");\r\n Manipulator.addClass(optionsWrapper, classes.optionsWrapper);\r\n Manipulator.addClass(optionsWrapper, classes.optionsWrapperScrollbar);\r\n optionsWrapper.style.maxHeight = `${height}px`;\r\n\r\n const optionsList = getOptionsListTemplate(\r\n options,\r\n selectAllOption,\r\n config,\r\n classes\r\n );\r\n\r\n optionsWrapper.appendChild(optionsList);\r\n\r\n if (config.selectFilter) {\r\n dropdown.appendChild(\r\n getFilterTemplate(config.selectSearchPlaceholder, classes)\r\n );\r\n }\r\n\r\n dropdown.appendChild(optionsWrapper);\r\n if (customContent) {\r\n dropdown.appendChild(customContent);\r\n }\r\n\r\n dropdownContainer.appendChild(dropdown);\r\n\r\n return dropdownContainer;\r\n}\r\n\r\nexport function getOptionsListTemplate(\r\n options,\r\n selectAllOption,\r\n config,\r\n classes\r\n) {\r\n const optionsList = element(\"div\");\r\n optionsList.setAttribute(DATA_OPTIONS_LIST, \"\");\r\n Manipulator.addClass(optionsList, classes.optionsList);\r\n\r\n let optionsNodes;\r\n\r\n if (config.multiple) {\r\n optionsNodes = getMultipleOptionsNodes(\r\n options,\r\n selectAllOption,\r\n config,\r\n classes\r\n );\r\n } else {\r\n optionsNodes = getSingleOptionsNodes(options, config, classes);\r\n }\r\n\r\n optionsNodes.forEach((node) => {\r\n optionsList.appendChild(node);\r\n });\r\n\r\n return optionsList;\r\n}\r\n\r\nexport function getFilterTemplate(placeholder, classes) {\r\n const inputGroup = element(\"div\");\r\n Manipulator.addClass(inputGroup, classes.inputGroup);\r\n\r\n const input = element(\"input\");\r\n\r\n input.setAttribute(DATA_FILTER_INPUT, \"\");\r\n Manipulator.addClass(input, classes.selectFilterInput);\r\n input.placeholder = placeholder;\r\n input.setAttribute(\"role\", \"searchbox\");\r\n input.setAttribute(\"type\", \"text\");\r\n\r\n inputGroup.appendChild(input);\r\n\r\n return inputGroup;\r\n}\r\n\r\nfunction getSingleOptionsNodes(options, config, classes) {\r\n const nodes = getOptionsNodes(options, config, classes);\r\n return nodes;\r\n}\r\n\r\nfunction getMultipleOptionsNodes(options, selectAllOption, config, classes) {\r\n let selectAllNode = null;\r\n\r\n if (config.selectAll) {\r\n selectAllNode = createSelectAllNode(\r\n selectAllOption,\r\n options,\r\n config,\r\n classes\r\n );\r\n }\r\n const optionsNodes = getOptionsNodes(options, config, classes);\r\n const nodes = selectAllNode ? [selectAllNode, ...optionsNodes] : optionsNodes;\r\n return nodes;\r\n}\r\n\r\nfunction getOptionsNodes(options, config, classes) {\r\n const nodes = [];\r\n\r\n options.forEach((option) => {\r\n const isOptionGroup = Object.prototype.hasOwnProperty.call(\r\n option,\r\n \"options\"\r\n );\r\n if (isOptionGroup) {\r\n const group = createOptionGroupTemplate(option, config, classes);\r\n nodes.push(group);\r\n } else {\r\n nodes.push(createOptionTemplate(option, config, classes));\r\n }\r\n });\r\n\r\n return nodes;\r\n}\r\n\r\nfunction createSelectAllNode(option, options, config, classes) {\r\n const isSelected = allOptionsSelected(options);\r\n const optionNode = element(\"div\");\r\n optionNode.setAttribute(DATA_OPTION, \"\");\r\n Manipulator.addClass(optionNode, classes.selectOption);\r\n optionNode.setAttribute(DATA_OPTION_ALL, \"\");\r\n Manipulator.addStyle(optionNode, {\r\n height: `${config.selectOptionHeight}px`,\r\n });\r\n optionNode.setAttribute(\"role\", \"option\");\r\n optionNode.setAttribute(\"aria-selected\", isSelected);\r\n\r\n if (isSelected) {\r\n optionNode.setAttribute(DATA_SELECTED, \"\");\r\n }\r\n\r\n optionNode.appendChild(getOptionContentTemplate(option, config, classes));\r\n option.setNode(optionNode);\r\n\r\n return optionNode;\r\n}\r\n\r\nfunction createOptionTemplate(option, config, classes) {\r\n if (option.node) {\r\n return option.node;\r\n }\r\n const optionNode = element(\"div\");\r\n optionNode.setAttribute(DATA_OPTION, \"\");\r\n Manipulator.addClass(optionNode, classes.selectOption);\r\n\r\n Manipulator.addStyle(optionNode, {\r\n height: `${config.selectOptionHeight}px`,\r\n });\r\n Manipulator.setDataAttribute(optionNode, \"id\", option.id);\r\n optionNode.setAttribute(\"role\", \"option\");\r\n optionNode.setAttribute(\"aria-selected\", option.selected);\r\n optionNode.setAttribute(\"aria-disabled\", option.disabled);\r\n\r\n if (option.selected) {\r\n optionNode.setAttribute(DATA_SELECTED, \"\");\r\n }\r\n\r\n if (option.disabled) {\r\n optionNode.setAttribute(\"data-te-select-option-disabled\", true);\r\n }\r\n\r\n if (option.hidden) {\r\n Manipulator.addClass(optionNode, \"hidden\");\r\n }\r\n\r\n optionNode.appendChild(getOptionContentTemplate(option, config, classes));\r\n\r\n if (option.icon) {\r\n optionNode.appendChild(getOptionIconTemplate(option, classes));\r\n }\r\n\r\n option.setNode(optionNode);\r\n\r\n return optionNode;\r\n}\r\n\r\nfunction getOptionContentTemplate(option, config, classes) {\r\n const content = element(\"span\");\r\n content.setAttribute(DATA_SELECT_OPTION_TEXT, \"\");\r\n Manipulator.addClass(content, classes.selectOptionText);\r\n\r\n const label = document.createTextNode(option.label);\r\n\r\n if (config.multiple) {\r\n content.appendChild(getCheckboxTemplate(option, classes));\r\n }\r\n\r\n content.appendChild(label);\r\n if (option.secondaryText || typeof option.secondaryText === \"number\") {\r\n content.appendChild(\r\n getSecondaryTextTemplate(option.secondaryText, classes)\r\n );\r\n }\r\n\r\n return content;\r\n}\r\n\r\nfunction getSecondaryTextTemplate(text, classes) {\r\n const span = element(\"span\");\r\n Manipulator.addClass(span, classes.selectOptionSecondaryText);\r\n const textContent = document.createTextNode(text);\r\n span.appendChild(textContent);\r\n return span;\r\n}\r\n\r\nfunction getCheckboxTemplate(option, classes) {\r\n const checkbox = element(\"input\");\r\n checkbox.setAttribute(\"type\", \"checkbox\");\r\n Manipulator.addClass(checkbox, classes.formCheckInput);\r\n checkbox.setAttribute(DATA_FORM_CHECK_INPUT, \"\");\r\n\r\n const label = element(\"label\");\r\n\r\n if (option.selected) {\r\n checkbox.setAttribute(\"checked\", true);\r\n }\r\n\r\n if (option.disabled) {\r\n checkbox.setAttribute(\"disabled\", true);\r\n }\r\n\r\n checkbox.appendChild(label);\r\n return checkbox;\r\n}\r\n\r\nfunction getOptionIconTemplate(option, classes) {\r\n const container = element(\"span\");\r\n const image = element(\"img\");\r\n Manipulator.addClass(image, classes.selectOptionIcon);\r\n\r\n image.src = option.icon;\r\n\r\n container.appendChild(image);\r\n return container;\r\n}\r\n\r\nfunction createOptionGroupTemplate(optionGroup, config, classes) {\r\n const group = element(\"div\");\r\n\r\n group.setAttribute(DATA_SELECT_OPTION_GROUP, \"\");\r\n Manipulator.addClass(group, classes.selectOptionGroup);\r\n\r\n group.setAttribute(\"role\", \"group\");\r\n group.setAttribute(\"id\", optionGroup.id);\r\n\r\n if (optionGroup.hidden) {\r\n Manipulator.addClass(group, \"hidden\");\r\n }\r\n\r\n const label = element(\"label\");\r\n label.setAttribute(DATA_SELECT_OPTION_GROUP_LABEL, \"\");\r\n Manipulator.addClass(label, classes.selectOptionGroupLabel);\r\n\r\n Manipulator.addStyle(label, { height: `${config.selectOptionHeight}px` });\r\n label.setAttribute(\"for\", optionGroup.id);\r\n label.textContent = optionGroup.label;\r\n\r\n group.appendChild(label);\r\n\r\n optionGroup.options.forEach((option) => {\r\n group.appendChild(createOptionTemplate(option, config, classes));\r\n });\r\n\r\n return group;\r\n}\r\n\r\nexport function getFakeValueTemplate(value, classes) {\r\n const fakeValue = element(\"div\");\r\n fakeValue.innerHTML = value;\r\n Manipulator.addClass(fakeValue, classes.selectLabel);\r\n\r\n Manipulator.addClass(fakeValue, classes.selectFakeValue);\r\n\r\n return fakeValue;\r\n}\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nimport { createPopper } from \"@popperjs/core\";\r\nimport Data from \"../../dom/data\";\r\nimport EventHandler from \"../../dom/event-handler\";\r\nimport Manipulator from \"../../dom/manipulator\";\r\nimport SelectorEngine from \"../../dom/selector-engine\";\r\nimport { typeCheckConfig, getUID } from \"../../util/index\";\r\nimport Input from \"../input\";\r\nimport SelectOption from \"./select-option\";\r\nimport SelectionModel from \"./selection-model\";\r\nimport {\r\n ESCAPE,\r\n ENTER,\r\n DOWN_ARROW,\r\n UP_ARROW,\r\n HOME,\r\n END,\r\n TAB,\r\n} from \"../../util/keycodes\";\r\nimport allOptionsSelected from \"./util\";\r\nimport {\r\n getWrapperTemplate,\r\n getDropdownTemplate,\r\n getOptionsListTemplate,\r\n getFakeValueTemplate,\r\n} from \"./templates\";\r\n\r\nconst NAME = \"select\";\r\nconst DATA_KEY = \"te.select\";\r\n\r\nconst EVENT_KEY = `.${DATA_KEY}`;\r\nconst EVENT_CLOSE = `close${EVENT_KEY}`;\r\nconst EVENT_OPEN = `open${EVENT_KEY}`;\r\nconst EVENT_SELECT = `optionSelect${EVENT_KEY}`;\r\nconst EVENT_DESELECT = `optionDeselect${EVENT_KEY}`;\r\nconst EVENT_VALUE_CHANGE = `valueChange${EVENT_KEY}`;\r\nconst EVENT_CHANGE = \"change\";\r\n\r\nconst DATA_SELECT_INIT = \"data-te-select-init\";\r\nconst DATA_NO_RESULT = \"data-te-select-no-results-ref\";\r\nconst DATA_OPEN = \"data-te-select-open\";\r\nconst DATA_ACTIVE = \"data-te-input-state-active\";\r\nconst DATA_FOCUSED = \"data-te-input-focused\";\r\nconst DATA_DISABLED = \"data-te-input-disabled\";\r\nconst DATA_SELECT_OPTION_GROUP_LABEL = \"data-te-select-option-group-label-ref\";\r\nconst DATA_OPTION_ALL = \"data-te-select-option-all-ref\";\r\nconst DATA_SELECTED = \"data-te-select-selected\";\r\n\r\nconst SELECTOR_LABEL = \"[data-te-select-label-ref]\";\r\nconst SELECTOR_INPUT = \"[data-te-select-input-ref]\";\r\nconst SELECTOR_FILTER_INPUT = \"[data-te-select-input-filter-ref]\";\r\nconst SELECTOR_DROPDOWN = \"[data-te-select-dropdown-ref]\";\r\nconst SELECTOR_OPTIONS_WRAPPER = \"[data-te-select-options-wrapper-ref]\";\r\nconst SELECTOR_OPTIONS_LIST = \"[data-te-select-options-list-ref]\";\r\nconst SELECTOR_OPTION = \"[data-te-select-option-ref]\";\r\nconst SELECTOR_CLEAR_BUTTON = \"[data-te-select-clear-btn-ref]\";\r\nconst SELECTOR_CUSTOM_CONTENT = \"[data-te-select-custom-content-ref]\";\r\nconst SELECTOR_NO_RESULTS = `[${DATA_NO_RESULT}]`;\r\nconst SELECTOR_FORM_OUTLINE = \"[data-te-select-form-outline-ref]\";\r\nconst SELECTOR_TOGGLE = \"[data-te-select-toggle]\";\r\nconst SELECTOR_NOTCH = \"[data-te-input-notch-ref]\";\r\n\r\nconst ANIMATION_TRANSITION_TIME = 200;\r\n\r\nconst Default = {\r\n selectAutoSelect: false,\r\n selectContainer: \"body\",\r\n selectClearButton: false,\r\n disabled: false,\r\n selectDisplayedLabels: 5,\r\n selectFormWhite: false,\r\n multiple: false,\r\n selectOptionsSelectedLabel: \"options selected\",\r\n selectOptionHeight: 38,\r\n selectAll: true,\r\n selectAllLabel: \"Select all\",\r\n selectSearchPlaceholder: \"Search...\",\r\n selectSize: \"default\",\r\n selectVisibleOptions: 5,\r\n selectFilter: false,\r\n selectFilterDebounce: 300,\r\n selectNoResultText: \"No results\",\r\n selectValidation: false,\r\n selectValidFeedback: \"Valid\",\r\n selectInvalidFeedback: \"Invalid\",\r\n selectPlaceholder: \"\",\r\n};\r\n\r\nconst DefaultType = {\r\n selectAutoSelect: \"boolean\",\r\n selectContainer: \"string\",\r\n selectClearButton: \"boolean\",\r\n disabled: \"boolean\",\r\n selectDisplayedLabels: \"number\",\r\n selectFormWhite: \"boolean\",\r\n multiple: \"boolean\",\r\n selectOptionsSelectedLabel: \"string\",\r\n selectOptionHeight: \"number\",\r\n selectAll: \"boolean\",\r\n selectAllLabel: \"string\",\r\n selectSearchPlaceholder: \"string\",\r\n selectSize: \"string\",\r\n selectVisibleOptions: \"number\",\r\n selectFilter: \"boolean\",\r\n selectFilterDebounce: \"number\",\r\n selectNoResultText: \"string\",\r\n selectValidation: \"boolean\",\r\n selectValidFeedback: \"string\",\r\n selectInvalidFeedback: \"string\",\r\n selectPlaceholder: \"string\",\r\n};\r\n\r\nconst DefaultClasses = {\r\n dropdown:\r\n \"relative outline-none min-w-[100px] m-0 scale-[0.8] opacity-0 bg-white shadow-[0_2px_5px_0_rgba(0,0,0,0.16),_0_2px_10px_0_rgba(0,0,0,0.12)] transition duration-200 motion-reduce:transition-none data-[te-select-open]:scale-100 data-[te-select-open]:opacity-100 dark:bg-zinc-700\",\r\n formCheckInput:\r\n \"relative float-left mt-[0.15rem] mr-[8px] h-[1.125rem] w-[1.125rem] appearance-none rounded-[0.25rem] border-[0.125rem] border-solid border-neutral-300 dark:border-neutral-600 outline-none before:pointer-events-none before:absolute before:h-[0.875rem] before:w-[0.875rem] before:scale-0 before:rounded-full before:bg-transparent before:opacity-0 before:shadow-[0px_0px_0px_13px_transparent] before:content-[''] checked:border-primary dark:checked:border-primary checked:bg-primary dark:checked:bg-primary checked:before:opacity-[0.16] checked:after:absolute checked:after:ml-[0.25rem] checked:after:-mt-px checked:after:block checked:after:h-[0.8125rem] checked:after:w-[0.375rem] checked:after:rotate-45 checked:after:border-[0.125rem] checked:after:border-t-0 checked:after:border-l-0 checked:after:border-solid checked:after:border-white checked:after:bg-transparent checked:after:content-[''] hover:cursor-pointer hover:before:opacity-[0.04] hover:before:shadow-[0px_0px_0px_13px_rgba(0,0,0,0.6)] focus:shadow-none focus:transition-[border-color_0.2s] focus:before:scale-100 focus:before:opacity-[0.12] focus:before:shadow-[0px_0px_0px_13px_rgba(0,0,0,0.6)] dark:focus:before:shadow-[0px_0px_0px_13px_rgba(255,255,255,0.4)] focus:before:transition-[box-shadow_0.2s,transform_0.2s] focus:after:absolute focus:after:z-[1] focus:after:block focus:after:h-[0.875rem] focus:after:w-[0.875rem] focus:after:rounded-[0.125rem] focus:after:content-[''] checked:focus:before:scale-100 checked:focus:before:shadow-[0px_0px_0px_13px_#3b71ca] dark:checked:focus:before:shadow-[0px_0px_0px_13px_#3b71ca] checked:focus:before:transition-[box-shadow_0.2s,transform_0.2s] checked:focus:after:ml-[0.25rem] checked:focus:after:-mt-px checked:focus:after:h-[0.8125rem] checked:focus:after:w-[0.375rem] checked:focus:after:rotate-45 checked:focus:after:rounded-none checked:focus:after:border-[0.125rem] checked:focus:after:border-t-0 checked:focus:after:border-l-0 checked:focus:after:border-solid checked:focus:after:border-white checked:focus:after:bg-transparent\",\r\n formOutline: \"relative\",\r\n initialized: \"hidden\",\r\n inputGroup:\r\n \"flex items-center whitespace-nowrap p-2.5 text-center text-base font-normal leading-[1.6] text-gray-700 dark:bg-zinc-800 dark:text-gray-200 dark:placeholder:text-gray-200\",\r\n noResult: \"flex items-center px-4\",\r\n optionsList: \"list-none m-0 p-0\",\r\n optionsWrapper: \"overflow-y-auto\",\r\n optionsWrapperScrollbar:\r\n \"[&::-webkit-scrollbar]:w-1 [&::-webkit-scrollbar]:h-1 [&::-webkit-scrollbar-button]:block [&::-webkit-scrollbar-button]:h-0 [&::-webkit-scrollbar-button]:bg-transparent [&::-webkit-scrollbar-track-piece]:bg-transparent [&::-webkit-scrollbar-track-piece]:rounded-none [&::-webkit-scrollbar-track-piece]: [&::-webkit-scrollbar-track-piece]:rounded-l [&::-webkit-scrollbar-thumb]:h-[50px] [&::-webkit-scrollbar-thumb]:bg-[#999] [&::-webkit-scrollbar-thumb]:rounded\",\r\n selectArrow:\r\n \"absolute right-3 text-[0.8rem] cursor-pointer peer-focus:text-primary peer-data-[te-input-focused]:text-primary group-data-[te-was-validated]/validation:peer-valid:text-green-600 group-data-[te-was-validated]/validation:peer-invalid:text-[rgb(220,76,100)] w-5 h-5\",\r\n selectArrowWhite:\r\n \"text-gray-50 peer-focus:!text-white peer-data-[te-input-focused]:!text-white\",\r\n selectArrowDefault: \"top-2\",\r\n selectArrowLg: \"top-[13px]\",\r\n selectArrowSm: \"top-1\",\r\n selectClearBtn:\r\n \"absolute top-2 right-9 text-black cursor-pointer focus:text-primary outline-none dark:text-gray-200\",\r\n selectClearBtnWhite: \"!text-gray-50\",\r\n selectClearBtnDefault: \"top-2 text-base\",\r\n selectClearBtnLg: \"top-[11px] text-base\",\r\n selectClearBtnSm: \"top-1 text-[0.8rem]\",\r\n selectDropdownContainer: \"z-[1070]\",\r\n selectFakeValue: \"transform-none hidden data-[te-input-state-active]:block\",\r\n selectFilterInput:\r\n \"relative m-0 block w-full min-w-0 flex-auto rounded border border-solid border-gray-300 bg-transparent bg-clip-padding px-3 py-1.5 text-base font-normal text-gray-700 transition duration-300 ease-in-out motion-reduce:transition-none focus:border-primary focus:text-gray-700 focus:shadow-te-primary focus:outline-none dark:text-gray-200 dark:placeholder:text-gray-200\",\r\n selectInput:\r\n \"peer block min-h-[auto] w-full rounded border-0 bg-transparent outline-none transition-all duration-200 ease-linear focus:placeholder:opacity-100 data-[te-input-state-active]:placeholder:opacity-100 motion-reduce:transition-none dark:text-gray-200 dark:placeholder:text-gray-200 [&:not([data-te-input-placeholder-active])]:placeholder:opacity-0 cursor-pointer data-[te-input-disabled]:bg-[#e9ecef] data-[te-input-disabled]:cursor-default group-data-[te-was-validated]/validation:mb-4 dark:data-[te-input-disabled]:bg-zinc-600\",\r\n selectInputWhite: \"!text-gray-50\",\r\n selectInputSizeDefault: \"py-[0.32rem] px-3 leading-[1.6]\",\r\n selectInputSizeLg: \"py-[0.32rem] px-3 leading-[2.15]\",\r\n selectInputSizeSm: \"py-[0.33rem] px-3 text-xs leading-[1.5]\",\r\n selectLabel:\r\n \"pointer-events-none absolute top-0 left-3 mb-0 max-w-[90%] origin-[0_0] truncate text-gray-500 transition-all duration-200 ease-out peer-focus:scale-[0.8] peer-focus:text-primary peer-data-[te-input-state-active]:scale-[0.8] motion-reduce:transition-none dark:text-gray-200 dark:peer-focus:text-gray-200 data-[te-input-state-active]:scale-[0.8] dark:peer-focus:text-primary\",\r\n selectLabelWhite: \"!text-gray-50\",\r\n selectLabelSizeDefault:\r\n \"pt-[0.37rem] leading-[1.6] peer-focus:-translate-y-[0.9rem] peer-data-[te-input-state-active]:-translate-y-[0.9rem] data-[te-input-state-active]:-translate-y-[0.9rem]\",\r\n selectLabelSizeLg:\r\n \"pt-[0.37rem] leading-[2.15] peer-focus:-translate-y-[1.15rem] peer-data-[te-input-state-active]:-translate-y-[1.15rem] data-[te-input-state-active]:-translate-y-[1.15rem]\",\r\n selectLabelSizeSm:\r\n \"pt-[0.37rem] text-xs leading-[1.5] peer-focus:-translate-y-[0.75rem] peer-data-[te-input-state-active]:-translate-y-[0.75rem] data-[te-input-state-active]:-translate-y-[0.75rem]\",\r\n selectOption:\r\n \"flex flex-row items-center justify-between w-full px-4 truncate text-gray-700 bg-transparent select-none cursor-pointer data-[te-input-multiple-active]:bg-black/5 hover:[&:not([data-te-select-option-disabled])]:bg-black/5 data-[te-input-state-active]:bg-black/5 data-[te-select-option-selected]:data-[te-input-state-active]:bg-black/5 data-[te-select-selected]:data-[te-select-option-disabled]:cursor-default data-[te-select-selected]:data-[te-select-option-disabled]:text-gray-400 data-[te-select-selected]:data-[te-select-option-disabled]:bg-transparent data-[te-select-option-selected]:bg-black/[0.02] data-[te-select-option-disabled]:text-gray-400 data-[te-select-option-disabled]:cursor-default group-data-[te-select-option-group-ref]/opt:pl-7 dark:text-gray-200 dark:hover:[&:not([data-te-select-option-disabled])]:bg-white/30 dark:data-[te-input-state-active]:bg-white/30 dark:data-[te-select-option-selected]:data-[te-input-state-active]:bg-white/30 dark:data-[te-select-option-disabled]:text-gray-400 dark:data-[te-input-multiple-active]:bg-white/30\",\r\n selectOptionGroup: \"group/opt\",\r\n selectOptionGroupLabel:\r\n \"flex flex-row items-center w-full px-4 truncate bg-transparent text-black/50 select-none dark:text-gray-300\",\r\n selectOptionIcon: \"w-7 h-7 rounded-full\",\r\n selectOptionSecondaryText:\r\n \"block text-[0.8rem] text-gray-500 dark:text-gray-300\",\r\n selectOptionText: \"group\",\r\n selectValidationValid:\r\n \"hidden absolute -mt-3 w-auto text-sm text-green-600 cursor-pointer group-data-[te-was-validated]/validation:peer-valid:block\",\r\n selectValidationInvalid:\r\n \"hidden absolute -mt-3 w-auto text-sm text-[rgb(220,76,100)] cursor-pointer group-data-[te-was-validated]/validation:peer-invalid:block\",\r\n};\r\n\r\nconst DefaultClassesType = {\r\n dropdown: \"string\",\r\n formCheckInput: \"string\",\r\n formOutline: \"string\",\r\n initialized: \"string\",\r\n inputGroup: \"string\",\r\n noResult: \"string\",\r\n optionsList: \"string\",\r\n optionsWrapper: \"string\",\r\n optionsWrapperScrollbar: \"string\",\r\n selectArrow: \"string\",\r\n selectArrowDefault: \"string\",\r\n selectArrowLg: \"string\",\r\n selectArrowSm: \"string\",\r\n selectClearBtn: \"string\",\r\n selectClearBtnDefault: \"string\",\r\n selectClearBtnLg: \"string\",\r\n selectClearBtnSm: \"string\",\r\n selectDropdownContainer: \"string\",\r\n selectFakeValue: \"string\",\r\n selectFilterInput: \"string\",\r\n selectInput: \"string\",\r\n selectInputSizeDefault: \"string\",\r\n selectInputSizeLg: \"string\",\r\n selectInputSizeSm: \"string\",\r\n selectLabel: \"string\",\r\n selectLabelSizeDefault: \"string\",\r\n selectLabelSizeLg: \"string\",\r\n selectLabelSizeSm: \"string\",\r\n selectOption: \"string\",\r\n selectOptionGroup: \"string\",\r\n selectOptionGroupLabel: \"string\",\r\n selectOptionIcon: \"string\",\r\n selectOptionSecondaryText: \"string\",\r\n selectOptionText: \"string\",\r\n};\r\n\r\nclass Select {\r\n constructor(element, config, classes) {\r\n this._element = element;\r\n this._config = this._getConfig(config);\r\n this._classes = this._getClasses(classes);\r\n\r\n if (this._config.selectPlaceholder && !this._config.multiple) {\r\n this._addPlaceholderOption();\r\n }\r\n\r\n this._optionsToRender = this._getOptionsToRender(element);\r\n\r\n // optionsToRender may contain option groups and nested options, in this case\r\n // we need a list of plain options to manage selections and keyboard navigation\r\n this._plainOptions = this._getPlainOptions(this._optionsToRender);\r\n this._filteredOptionsList = null;\r\n\r\n this._selectionModel = new SelectionModel(this.multiple);\r\n\r\n this._activeOptionIndex = -1;\r\n this._activeOption = null;\r\n\r\n this._wrapperId = getUID(\"select-wrapper-\");\r\n this._dropdownContainerId = getUID(\"select-dropdown-container-\");\r\n this._selectAllId = getUID(\"select-all-\");\r\n this._debounceTimeoutId = null;\r\n\r\n this._dropdownHeight =\r\n this._config.selectOptionHeight * this._config.selectVisibleOptions;\r\n\r\n this._popper = null;\r\n this._input = null;\r\n this._label = SelectorEngine.next(this._element, SELECTOR_LABEL)[0];\r\n this._notch = null;\r\n this._fakeValue = null;\r\n this._isFakeValueActive = false;\r\n\r\n this._customContent = SelectorEngine.next(\r\n element,\r\n SELECTOR_CUSTOM_CONTENT\r\n )[0];\r\n\r\n this._toggleButton = null;\r\n this._elementToggle = null;\r\n\r\n this._wrapper = null;\r\n this._inputEl = null;\r\n this._dropdownContainer = null;\r\n this._container = null;\r\n this._selectAllOption = null;\r\n\r\n this._init();\r\n\r\n this._mutationObserver = null;\r\n this._isOpen = false;\r\n\r\n this._addMutationObserver();\r\n\r\n if (this._element) {\r\n Data.setData(element, DATA_KEY, this);\r\n }\r\n }\r\n\r\n static get NAME() {\r\n return NAME;\r\n }\r\n\r\n get filterInput() {\r\n return SelectorEngine.findOne(\r\n SELECTOR_FILTER_INPUT,\r\n this._dropdownContainer\r\n );\r\n }\r\n\r\n get dropdown() {\r\n return SelectorEngine.findOne(SELECTOR_DROPDOWN, this._dropdownContainer);\r\n }\r\n\r\n get optionsList() {\r\n return SelectorEngine.findOne(\r\n SELECTOR_OPTIONS_LIST,\r\n this._dropdownContainer\r\n );\r\n }\r\n\r\n get optionsWrapper() {\r\n return SelectorEngine.findOne(\r\n SELECTOR_OPTIONS_WRAPPER,\r\n this._dropdownContainer\r\n );\r\n }\r\n\r\n get clearButton() {\r\n return SelectorEngine.findOne(SELECTOR_CLEAR_BUTTON, this._wrapper);\r\n }\r\n\r\n get options() {\r\n return this._filteredOptionsList\r\n ? this._filteredOptionsList\r\n : this._plainOptions;\r\n }\r\n\r\n get value() {\r\n return this.multiple\r\n ? this._selectionModel.values\r\n : this._selectionModel.value;\r\n }\r\n\r\n get multiple() {\r\n return this._config.multiple;\r\n }\r\n\r\n get hasSelectAll() {\r\n return this.multiple && this._config.selectAll;\r\n }\r\n\r\n get hasSelection() {\r\n return (\r\n this._selectionModel.selection ||\r\n this._selectionModel.selections.length > 0\r\n );\r\n }\r\n\r\n _getConfig(config) {\r\n const dataAttributes = Manipulator.getDataAttributes(this._element);\r\n\r\n config = {\r\n ...Default,\r\n ...dataAttributes,\r\n ...config,\r\n };\r\n\r\n if (this._element.hasAttribute(\"multiple\")) {\r\n config.multiple = true;\r\n }\r\n\r\n if (this._element.hasAttribute(\"disabled\")) {\r\n config.disabled = true;\r\n }\r\n\r\n if (this._element.tabIndex) {\r\n config.tabIndex = this._element.getAttribute(\"tabIndex\");\r\n }\r\n\r\n typeCheckConfig(NAME, config, DefaultType);\r\n\r\n return config;\r\n }\r\n\r\n _getClasses(classes) {\r\n const dataAttributes = Manipulator.getDataClassAttributes(this._element);\r\n\r\n classes = {\r\n ...DefaultClasses,\r\n ...dataAttributes,\r\n ...classes,\r\n };\r\n\r\n typeCheckConfig(NAME, classes, DefaultClassesType);\r\n\r\n return classes;\r\n }\r\n\r\n _addPlaceholderOption() {\r\n const placeholderOption = new Option(\"\", \"\", true, true);\r\n placeholderOption.hidden = true;\r\n placeholderOption.selected = true;\r\n\r\n this._element.prepend(placeholderOption);\r\n }\r\n\r\n _getOptionsToRender(select) {\r\n const options = [];\r\n\r\n const nodes = select.childNodes;\r\n\r\n nodes.forEach((node) => {\r\n if (node.nodeName === \"OPTGROUP\") {\r\n const optionGroup = {\r\n id: getUID(\"group-\"),\r\n label: node.label,\r\n disabled: node.hasAttribute(\"disabled\"),\r\n hidden: node.hasAttribute(\"hidden\"),\r\n options: [],\r\n };\r\n const groupOptions = node.childNodes;\r\n groupOptions.forEach((option) => {\r\n if (option.nodeName === \"OPTION\") {\r\n optionGroup.options.push(\r\n this._createOptionObject(option, optionGroup)\r\n );\r\n }\r\n });\r\n options.push(optionGroup);\r\n } else if (node.nodeName === \"OPTION\") {\r\n options.push(this._createOptionObject(node));\r\n }\r\n });\r\n return options;\r\n }\r\n\r\n _getPlainOptions(optionsToRender) {\r\n const hasOptionGroup = SelectorEngine.findOne(\"optgroup\", this._element);\r\n\r\n if (!hasOptionGroup) {\r\n return optionsToRender;\r\n }\r\n\r\n const options = [];\r\n\r\n optionsToRender.forEach((option) => {\r\n const isOptionGroup = Object.prototype.hasOwnProperty.call(\r\n option,\r\n \"options\"\r\n );\r\n\r\n if (isOptionGroup) {\r\n option.options.forEach((nestedOption) => {\r\n options.push(nestedOption);\r\n });\r\n } else {\r\n options.push(option);\r\n }\r\n });\r\n\r\n return options;\r\n }\r\n\r\n _createOptionObject(nativeOption, group = {}) {\r\n const id = getUID(\"option-\");\r\n const groupId = group.id ? group.id : null;\r\n const groupDisabled = group.disabled ? group.disabled : false;\r\n const selected =\r\n nativeOption.selected || nativeOption.hasAttribute(DATA_SELECTED);\r\n const disabled = nativeOption.hasAttribute(\"disabled\") || groupDisabled;\r\n const hidden =\r\n nativeOption.hasAttribute(\"hidden\") || (group && group.hidden);\r\n const multiple = this.multiple;\r\n const value = nativeOption.value;\r\n const label = nativeOption.label;\r\n const secondaryText = Manipulator.getDataAttribute(\r\n nativeOption,\r\n \"selectSecondaryText\"\r\n );\r\n const icon = Manipulator.getDataAttribute(nativeOption, \"select-icon\");\r\n return new SelectOption(\r\n id,\r\n nativeOption,\r\n multiple,\r\n value,\r\n label,\r\n selected,\r\n disabled,\r\n hidden,\r\n secondaryText,\r\n groupId,\r\n icon\r\n );\r\n }\r\n\r\n _getNavigationOptions() {\r\n const availableOptions = this.options.filter((option) => !option.hidden);\r\n\r\n return this.hasSelectAll\r\n ? [this._selectAllOption, ...availableOptions]\r\n : availableOptions;\r\n }\r\n\r\n _init() {\r\n this._renderMaterialWrapper();\r\n\r\n this._wrapper = SelectorEngine.findOne(`#${this._wrapperId}`);\r\n this._input = SelectorEngine.findOne(SELECTOR_INPUT, this._wrapper);\r\n this._config.disabled && this._input.setAttribute(DATA_DISABLED, \"\");\r\n\r\n const containerSelector = this._config.selectContainer;\r\n\r\n if (containerSelector === \"body\") {\r\n this._container = document.body;\r\n } else {\r\n this._container = SelectorEngine.findOne(containerSelector);\r\n }\r\n\r\n this._initOutlineInput();\r\n this._setDefaultSelections();\r\n this._updateInputValue();\r\n this._appendFakeValue();\r\n this._updateFakeLabelPosition();\r\n this._updateLabelPosition();\r\n this._updateClearButtonVisibility();\r\n\r\n this._bindComponentEvents();\r\n\r\n if (this.hasSelectAll) {\r\n this._selectAllOption = this._createSelectAllOption();\r\n }\r\n\r\n this._dropdownContainer = getDropdownTemplate(\r\n this._dropdownContainerId,\r\n this._config,\r\n this._input.offsetWidth,\r\n this._dropdownHeight,\r\n this._selectAllOption,\r\n this._optionsToRender,\r\n this._customContent,\r\n this._classes\r\n );\r\n\r\n this._setFirstActiveOption();\r\n this._listenToFocusChange();\r\n }\r\n\r\n _renderMaterialWrapper() {\r\n const template = getWrapperTemplate(\r\n this._wrapperId,\r\n this._config,\r\n this._label,\r\n this._classes,\r\n this._element.name\r\n );\r\n this._element.parentNode.insertBefore(template, this._element);\r\n Manipulator.addClass(this._element, this._classes.initialized);\r\n template.appendChild(this._element);\r\n }\r\n\r\n _initOutlineInput() {\r\n const inputWrapper = SelectorEngine.findOne(\r\n SELECTOR_FORM_OUTLINE,\r\n this._wrapper\r\n );\r\n const outlineInput = new Input(\r\n inputWrapper,\r\n {\r\n inputFormWhite: this._config.selectFormWhite,\r\n },\r\n this._classes\r\n );\r\n outlineInput.init();\r\n this._notch = SelectorEngine.findOne(SELECTOR_NOTCH, this._wrapper);\r\n }\r\n\r\n _bindComponentEvents() {\r\n this._listenToComponentKeydown();\r\n this._listenToWrapperClick();\r\n this._listenToClearBtnClick();\r\n this._listenToClearBtnKeydown();\r\n }\r\n\r\n _setDefaultSelections() {\r\n this.options.forEach((option) => {\r\n if (option.selected) {\r\n this._selectionModel.select(option);\r\n }\r\n });\r\n }\r\n\r\n _listenToComponentKeydown() {\r\n EventHandler.on(this._wrapper, \"keydown\", this._handleKeydown.bind(this));\r\n }\r\n\r\n _handleKeydown(event) {\r\n if (this._isOpen && !this._config.selectFilter) {\r\n this._handleOpenKeydown(event);\r\n } else {\r\n this._handleClosedKeydown(event);\r\n }\r\n }\r\n\r\n _handleOpenKeydown(event) {\r\n const key = event.keyCode;\r\n const isCloseKey =\r\n key === ESCAPE || (key === UP_ARROW && event.altKey) || key === TAB;\r\n\r\n if (key === TAB && this._config.selectAutoSelect && !this.multiple) {\r\n this._handleAutoSelection(this._activeOption);\r\n }\r\n\r\n if (isCloseKey) {\r\n this.close();\r\n this._input.focus();\r\n return;\r\n }\r\n\r\n switch (key) {\r\n case DOWN_ARROW:\r\n this._setNextOptionActive();\r\n this._scrollToOption(this._activeOption);\r\n break;\r\n case UP_ARROW:\r\n this._setPreviousOptionActive();\r\n this._scrollToOption(this._activeOption);\r\n break;\r\n case HOME:\r\n this._setFirstOptionActive();\r\n this._scrollToOption(this._activeOption);\r\n break;\r\n case END:\r\n this._setLastOptionActive();\r\n this._scrollToOption(this._activeOption);\r\n break;\r\n case ENTER:\r\n event.preventDefault();\r\n if (this._activeOption) {\r\n if (this.hasSelectAll && this._activeOptionIndex === 0) {\r\n this._handleSelectAll();\r\n } else {\r\n this._handleSelection(this._activeOption);\r\n }\r\n }\r\n return;\r\n default:\r\n return;\r\n }\r\n\r\n event.preventDefault();\r\n }\r\n\r\n _handleClosedKeydown(event) {\r\n const key = event.keyCode;\r\n if (key === ENTER) {\r\n event.preventDefault();\r\n }\r\n const isOpenKey =\r\n key === ENTER ||\r\n (key === DOWN_ARROW && event.altKey) ||\r\n (key === DOWN_ARROW && this.multiple);\r\n\r\n if (isOpenKey) {\r\n this.open();\r\n }\r\n\r\n if (!this.multiple) {\r\n switch (key) {\r\n case DOWN_ARROW:\r\n this._setNextOptionActive();\r\n this._handleSelection(this._activeOption);\r\n break;\r\n case UP_ARROW:\r\n this._setPreviousOptionActive();\r\n this._handleSelection(this._activeOption);\r\n break;\r\n case HOME:\r\n this._setFirstOptionActive();\r\n this._handleSelection(this._activeOption);\r\n break;\r\n case END:\r\n this._setLastOptionActive();\r\n this._handleSelection(this._activeOption);\r\n break;\r\n default:\r\n return;\r\n }\r\n } else {\r\n switch (key) {\r\n case DOWN_ARROW:\r\n this.open();\r\n break;\r\n case UP_ARROW:\r\n this.open();\r\n break;\r\n default:\r\n return;\r\n }\r\n }\r\n\r\n event.preventDefault();\r\n }\r\n\r\n _scrollToOption(option) {\r\n if (!option) {\r\n return;\r\n }\r\n\r\n let optionIndex;\r\n\r\n const visibleOptions = this.options.filter((option) => !option.hidden);\r\n\r\n if (this.hasSelectAll) {\r\n optionIndex = visibleOptions.indexOf(option) + 1;\r\n } else {\r\n optionIndex = visibleOptions.indexOf(option);\r\n }\r\n\r\n const groupsNumber = this._getNumberOfGroupsBeforeOption(optionIndex);\r\n\r\n const scrollToIndex = optionIndex + groupsNumber;\r\n\r\n const list = this.optionsWrapper;\r\n const listHeight = list.offsetHeight;\r\n const optionHeight = this._config.selectOptionHeight;\r\n const scrollTop = list.scrollTop;\r\n\r\n if (optionIndex > -1) {\r\n const optionOffset = scrollToIndex * optionHeight;\r\n const isBelow = optionOffset + optionHeight > scrollTop + listHeight;\r\n const isAbove = optionOffset < scrollTop;\r\n\r\n if (isAbove) {\r\n list.scrollTop = optionOffset;\r\n } else if (isBelow) {\r\n list.scrollTop = optionOffset - listHeight + optionHeight;\r\n } else {\r\n list.scrollTop = scrollTop;\r\n }\r\n }\r\n }\r\n\r\n _getNumberOfGroupsBeforeOption(optionIndex) {\r\n const optionsList = this.options.filter((option) => !option.hidden);\r\n const groupsList = this._optionsToRender.filter((group) => !group.hidden);\r\n const index = this.hasSelectAll ? optionIndex - 1 : optionIndex;\r\n let groupsNumber = 0;\r\n\r\n for (let i = 0; i <= index; i++) {\r\n if (\r\n optionsList[i].groupId &&\r\n groupsList[groupsNumber] &&\r\n groupsList[groupsNumber].id &&\r\n optionsList[i].groupId === groupsList[groupsNumber].id\r\n ) {\r\n groupsNumber++;\r\n }\r\n }\r\n\r\n return groupsNumber;\r\n }\r\n\r\n _setNextOptionActive() {\r\n let index = this._activeOptionIndex + 1;\r\n const options = this._getNavigationOptions();\r\n\r\n if (!options[index]) {\r\n return;\r\n }\r\n\r\n while (options[index].disabled) {\r\n index += 1;\r\n\r\n if (!options[index]) {\r\n return;\r\n }\r\n }\r\n\r\n this._updateActiveOption(options[index], index);\r\n }\r\n\r\n _setPreviousOptionActive() {\r\n let index = this._activeOptionIndex - 1;\r\n const options = this._getNavigationOptions();\r\n\r\n if (!options[index]) {\r\n return;\r\n }\r\n\r\n while (options[index].disabled) {\r\n index -= 1;\r\n\r\n if (!options[index]) {\r\n return;\r\n }\r\n }\r\n\r\n this._updateActiveOption(options[index], index);\r\n }\r\n\r\n _setFirstOptionActive() {\r\n const index = 0;\r\n const options = this._getNavigationOptions();\r\n\r\n this._updateActiveOption(options[index], index);\r\n }\r\n\r\n _setLastOptionActive() {\r\n const options = this._getNavigationOptions();\r\n const index = options.length - 1;\r\n\r\n this._updateActiveOption(options[index], index);\r\n }\r\n\r\n _updateActiveOption(newActiveOption, index) {\r\n const currentActiveOption = this._activeOption;\r\n\r\n if (currentActiveOption) {\r\n currentActiveOption.removeActiveStyles();\r\n }\r\n\r\n newActiveOption.setActiveStyles();\r\n this._activeOptionIndex = index;\r\n this._activeOption = newActiveOption;\r\n }\r\n\r\n _listenToWrapperClick() {\r\n EventHandler.on(this._wrapper, \"click\", () => {\r\n this.toggle();\r\n });\r\n }\r\n\r\n _listenToClearBtnClick() {\r\n EventHandler.on(this.clearButton, \"click\", (event) => {\r\n event.preventDefault();\r\n event.stopPropagation();\r\n this._handleClear();\r\n });\r\n }\r\n\r\n _listenToClearBtnKeydown() {\r\n EventHandler.on(this.clearButton, \"keydown\", (event) => {\r\n if (event.keyCode === ENTER) {\r\n this._handleClear();\r\n event.preventDefault();\r\n event.stopPropagation();\r\n }\r\n });\r\n }\r\n\r\n _handleClear() {\r\n if (this.multiple) {\r\n this._selectionModel.clear();\r\n this._deselectAllOptions(this.options);\r\n\r\n if (this.hasSelectAll) {\r\n this._updateSelectAllState();\r\n }\r\n } else {\r\n const selected = this._selectionModel.selection;\r\n this._selectionModel.clear();\r\n selected.deselect();\r\n }\r\n this._fakeValue.innerHTML = \"\";\r\n this._updateInputValue();\r\n this._updateFakeLabelPosition();\r\n this._updateLabelPosition();\r\n this._updateClearButtonVisibility();\r\n\r\n this._emitValueChangeEvent(null);\r\n this._emitNativeChangeEvent();\r\n }\r\n\r\n _listenToOptionsClick() {\r\n EventHandler.on(this.optionsWrapper, \"click\", (event) => {\r\n const optionGroupLabel = event.target.hasAttribute(\r\n DATA_SELECT_OPTION_GROUP_LABEL\r\n );\r\n\r\n if (optionGroupLabel) {\r\n return;\r\n }\r\n\r\n const target =\r\n event.target.nodeName === \"DIV\"\r\n ? event.target\r\n : SelectorEngine.closest(event.target, SELECTOR_OPTION);\r\n\r\n const selectAllOption = target.hasAttribute(DATA_OPTION_ALL);\r\n\r\n if (selectAllOption) {\r\n this._handleSelectAll();\r\n return;\r\n }\r\n\r\n const id = target.dataset.teId;\r\n const option = this.options.find((option) => option.id === id);\r\n\r\n if (option && !option.disabled) {\r\n this._handleSelection(option);\r\n }\r\n });\r\n }\r\n\r\n _handleSelectAll() {\r\n const selected = this._selectAllOption.selected;\r\n\r\n if (selected) {\r\n this._deselectAllOptions(this.options);\r\n this._selectAllOption.deselect();\r\n } else {\r\n this._selectAllOptions(this.options);\r\n this._selectAllOption.select();\r\n }\r\n\r\n this._updateInputValue();\r\n this._updateFakeLabelPosition();\r\n this._updateLabelPosition();\r\n this._updateClearButtonVisibility();\r\n\r\n this._emitValueChangeEvent(this.value);\r\n this._emitNativeChangeEvent();\r\n }\r\n\r\n _selectAllOptions(options) {\r\n options.forEach((option) => {\r\n if (!option.selected && !option.disabled) {\r\n this._selectionModel.select(option);\r\n option.select();\r\n }\r\n });\r\n }\r\n\r\n _deselectAllOptions(options) {\r\n options.forEach((option) => {\r\n if (option.selected && !option.disabled) {\r\n this._selectionModel.deselect(option);\r\n option.deselect();\r\n }\r\n });\r\n }\r\n\r\n _handleSelection(option) {\r\n if (this.multiple) {\r\n this._handleMultiSelection(option);\r\n\r\n if (this.hasSelectAll) {\r\n this._updateSelectAllState();\r\n }\r\n } else {\r\n this._handleSingleSelection(option);\r\n }\r\n\r\n this._updateInputValue();\r\n this._updateFakeLabelPosition();\r\n this._updateLabelPosition();\r\n this._updateClearButtonVisibility();\r\n }\r\n\r\n _handleAutoSelection(option) {\r\n this._singleOptionSelect(option);\r\n this._updateInputValue();\r\n this._updateFakeLabelPosition();\r\n this._updateLabelPosition();\r\n this._updateClearButtonVisibility();\r\n }\r\n\r\n _handleSingleSelection(option) {\r\n this._singleOptionSelect(option);\r\n this.close();\r\n this._input.focus();\r\n }\r\n\r\n _singleOptionSelect(option) {\r\n const currentSelected = this._selectionModel.selections[0];\r\n\r\n if (currentSelected && currentSelected !== option) {\r\n this._selectionModel.deselect(currentSelected);\r\n currentSelected.deselect();\r\n currentSelected.node.setAttribute(DATA_SELECTED, false);\r\n EventHandler.trigger(this._element, EVENT_DESELECT, {\r\n value: currentSelected.value,\r\n });\r\n }\r\n\r\n if (!currentSelected || (currentSelected && option !== currentSelected)) {\r\n this._selectionModel.select(option);\r\n option.select();\r\n option.node.setAttribute(DATA_SELECTED, true);\r\n EventHandler.trigger(this._element, EVENT_SELECT, {\r\n value: option.value,\r\n });\r\n this._emitValueChangeEvent(this.value);\r\n this._emitNativeChangeEvent();\r\n }\r\n }\r\n\r\n _handleMultiSelection(option) {\r\n if (option.selected) {\r\n this._selectionModel.deselect(option);\r\n option.deselect();\r\n option.node.setAttribute(DATA_SELECTED, false);\r\n EventHandler.trigger(this._element, EVENT_DESELECT, {\r\n value: option.value,\r\n });\r\n } else {\r\n this._selectionModel.select(option);\r\n option.select();\r\n option.node.setAttribute(DATA_SELECTED, true);\r\n EventHandler.trigger(this._element, EVENT_SELECT, {\r\n value: option.value,\r\n });\r\n }\r\n\r\n this._emitValueChangeEvent(this.value);\r\n this._emitNativeChangeEvent();\r\n }\r\n\r\n _emitValueChangeEvent(value) {\r\n EventHandler.trigger(this._element, EVENT_VALUE_CHANGE, { value });\r\n }\r\n\r\n _emitNativeChangeEvent() {\r\n EventHandler.trigger(this._element, EVENT_CHANGE);\r\n }\r\n\r\n _updateInputValue() {\r\n const labels = this.multiple\r\n ? this._selectionModel.labels\r\n : this._selectionModel.label;\r\n let value;\r\n\r\n if (\r\n this.multiple &&\r\n this._config.selectDisplayedLabels !== -1 &&\r\n this._selectionModel.selections.length >\r\n this._config.selectDisplayedLabels\r\n ) {\r\n value = `${this._selectionModel.selections.length} ${this._config.selectOptionsSelectedLabel}`;\r\n } else {\r\n value = labels;\r\n }\r\n\r\n if (\r\n !this.multiple &&\r\n !this._isSelectionValid(this._selectionModel.selection)\r\n ) {\r\n this._input.value = \"\";\r\n } else if (this._isLabelEmpty(this._selectionModel.selection)) {\r\n this._input.value = \" \";\r\n } else if (value) {\r\n this._input.value = value;\r\n } else {\r\n // prettier-ignore\r\n // eslint-disable-next-line\r\n this.multiple || !this._optionsToRender[0] ? (this._input.value = '') : (this._input.value = this._optionsToRender[0].label);\r\n }\r\n }\r\n\r\n _isSelectionValid(selection) {\r\n if (selection && (selection.disabled || selection.value === \"\")) {\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n _isLabelEmpty(selection) {\r\n if (selection && selection.label === \"\") {\r\n return true;\r\n }\r\n\r\n return false;\r\n }\r\n\r\n _appendFakeValue() {\r\n if (!this._selectionModel.selection || this._selectionModel._multiple) {\r\n return;\r\n }\r\n\r\n const value = this._selectionModel.selection.label;\r\n this._fakeValue = getFakeValueTemplate(value, this._classes);\r\n const inputWrapper = SelectorEngine.findOne(\r\n SELECTOR_FORM_OUTLINE,\r\n this._wrapper\r\n );\r\n inputWrapper.appendChild(this._fakeValue);\r\n }\r\n\r\n _updateLabelPosition() {\r\n const isInitialized = this._element.hasAttribute(DATA_SELECT_INIT);\r\n\r\n const isValueEmpty = this._input.value !== \"\";\r\n if (!this._label) {\r\n return;\r\n }\r\n\r\n if (\r\n isInitialized &&\r\n (isValueEmpty || this._isOpen || this._isFakeValueActive)\r\n ) {\r\n this._label.setAttribute(DATA_ACTIVE, \"\");\r\n this._notch.setAttribute(DATA_ACTIVE, \"\");\r\n } else {\r\n this._label.removeAttribute(DATA_ACTIVE);\r\n this._notch.removeAttribute(DATA_ACTIVE, \"\");\r\n }\r\n }\r\n\r\n _updateLabelPositionWhileClosing() {\r\n if (!this._label) {\r\n return;\r\n }\r\n\r\n if (this._input.value !== \"\" || this._isFakeValueActive) {\r\n this._label.setAttribute(DATA_ACTIVE, \"\");\r\n this._notch.setAttribute(DATA_ACTIVE, \"\");\r\n } else {\r\n this._label.removeAttribute(DATA_ACTIVE);\r\n this._notch.removeAttribute(DATA_ACTIVE);\r\n }\r\n }\r\n\r\n _updateFakeLabelPosition() {\r\n if (!this._fakeValue) {\r\n return;\r\n }\r\n\r\n if (\r\n this._input.value === \"\" &&\r\n this._fakeValue.innerHTML !== \"\" &&\r\n !this._config.selectPlaceholder\r\n ) {\r\n this._isFakeValueActive = true;\r\n this._fakeValue.setAttribute(DATA_ACTIVE, \"\");\r\n } else {\r\n this._isFakeValueActive = false;\r\n this._fakeValue.removeAttribute(DATA_ACTIVE);\r\n }\r\n }\r\n\r\n _updateClearButtonVisibility() {\r\n if (!this.clearButton) {\r\n return;\r\n }\r\n\r\n const hasSelection =\r\n this._selectionModel.selection ||\r\n this._selectionModel.selections.length > 0;\r\n\r\n if (hasSelection) {\r\n Manipulator.addStyle(this.clearButton, { display: \"block\" });\r\n } else {\r\n Manipulator.addStyle(this.clearButton, { display: \"none\" });\r\n }\r\n }\r\n\r\n _updateSelectAllState() {\r\n const selectAllSelected = this._selectAllOption.selected;\r\n const allSelected = allOptionsSelected(this.options);\r\n if (!allSelected && selectAllSelected) {\r\n this._selectAllOption.deselect();\r\n } else if (allSelected && !selectAllSelected) {\r\n this._selectAllOption.select();\r\n }\r\n }\r\n\r\n toggle() {\r\n if (this._isOpen) {\r\n this.close();\r\n } else {\r\n this.open();\r\n }\r\n }\r\n\r\n open() {\r\n const isDisabled = this._config.disabled;\r\n const openEvent = EventHandler.trigger(this._element, EVENT_OPEN);\r\n\r\n if (this._isOpen || isDisabled || openEvent.defaultPrevented) {\r\n return;\r\n }\r\n\r\n this._openDropdown();\r\n this._updateDropdownWidth();\r\n this._setFirstActiveOption();\r\n this._scrollToOption(this._activeOption);\r\n\r\n if (this._config.selectFilter) {\r\n // We need to wait for popper initialization, otherwise\r\n // dates container will be focused before popper position\r\n // update which can change the scroll position on the page\r\n setTimeout(() => {\r\n this.filterInput.focus();\r\n }, 0);\r\n\r\n this._listenToSelectSearch();\r\n\r\n // New listener for dropdown navigation is needed, because\r\n // we focus search input inside dropdown template, wchich is\r\n // appended to the body. In this case listener attached to the\r\n // select wrapper won't work\r\n this._listenToDropdownKeydown();\r\n }\r\n\r\n this._listenToOptionsClick();\r\n this._listenToOutsideClick();\r\n this._listenToWindowResize();\r\n\r\n this._isOpen = true;\r\n\r\n this._updateLabelPosition();\r\n this._setInputActiveStyles();\r\n }\r\n\r\n _openDropdown() {\r\n this._popper = createPopper(this._input, this._dropdownContainer, {\r\n placement: \"bottom-start\",\r\n modifiers: [\r\n {\r\n name: \"offset\",\r\n options: {\r\n offset: [0, 1],\r\n },\r\n },\r\n ],\r\n });\r\n this._container.appendChild(this._dropdownContainer);\r\n\r\n // We need to add delay to wait for the popper initialization\r\n // and position update\r\n setTimeout(() => {\r\n this.dropdown.setAttribute(DATA_OPEN, \"\");\r\n }, 0);\r\n }\r\n\r\n _updateDropdownWidth() {\r\n const inputWidth = this._input.offsetWidth;\r\n Manipulator.addStyle(this._dropdownContainer, { width: `${inputWidth}px` });\r\n }\r\n\r\n _setFirstActiveOption() {\r\n const options = this._getNavigationOptions();\r\n const currentActive = this._activeOption;\r\n\r\n if (currentActive) {\r\n currentActive.removeActiveStyles();\r\n }\r\n\r\n const firstSelected = this.multiple\r\n ? this._selectionModel.selections[0]\r\n : this._selectionModel.selection;\r\n\r\n if (firstSelected) {\r\n this._activeOption = firstSelected;\r\n firstSelected.setActiveStyles();\r\n this._activeOptionIndex = options.findIndex(\r\n (option) => option === firstSelected\r\n );\r\n } else {\r\n this._activeOption = null;\r\n this._activeOptionIndex = -1;\r\n }\r\n }\r\n\r\n _setInputActiveStyles() {\r\n this._input.setAttribute(DATA_FOCUSED, \"\");\r\n SelectorEngine.findOne(SELECTOR_NOTCH, this._wrapper).setAttribute(\r\n DATA_FOCUSED,\r\n \"\"\r\n );\r\n }\r\n\r\n _listenToWindowResize() {\r\n EventHandler.on(window, \"resize\", this._handleWindowResize.bind(this));\r\n }\r\n\r\n _handleWindowResize() {\r\n if (this._dropdownContainer) {\r\n this._updateDropdownWidth();\r\n }\r\n }\r\n\r\n _listenToSelectSearch() {\r\n this.filterInput.addEventListener(\"input\", (event) => {\r\n const searchTerm = event.target.value;\r\n const debounceTime = this._config.selectFilterDebounce;\r\n this._debounceFilter(searchTerm, debounceTime);\r\n });\r\n }\r\n\r\n _debounceFilter(searchTerm, debounceTime) {\r\n if (this._debounceTimeoutId) {\r\n clearTimeout(this._debounceTimeoutId);\r\n }\r\n\r\n this._debounceTimeoutId = setTimeout(() => {\r\n this._filterOptions(searchTerm);\r\n }, debounceTime);\r\n }\r\n\r\n _filterOptions(searchTerm) {\r\n const filtered = [];\r\n\r\n this._optionsToRender.forEach((option) => {\r\n const isOptionGroup = Object.prototype.hasOwnProperty.call(\r\n option,\r\n \"options\"\r\n );\r\n\r\n const isValidOption =\r\n !isOptionGroup &&\r\n option.label.toLowerCase().includes(searchTerm.toLowerCase());\r\n const group = {};\r\n\r\n if (isOptionGroup) {\r\n group.label = option.label;\r\n group.options = this._filter(searchTerm, option.options);\r\n\r\n if (group.options.length > 0) {\r\n filtered.push(group);\r\n }\r\n }\r\n\r\n if (isValidOption) {\r\n filtered.push(option);\r\n }\r\n });\r\n\r\n const hasNoResultsText = this._config.selectNoResultText !== \"\";\r\n const hasFilteredOptions = filtered.length !== 0;\r\n\r\n if (hasFilteredOptions) {\r\n this._updateOptionsListTemplate(filtered);\r\n this._popper.forceUpdate();\r\n this._filteredOptionsList = this._getPlainOptions(filtered);\r\n\r\n if (this.hasSelectAll) {\r\n this._updateSelectAllState();\r\n }\r\n\r\n this._setFirstActiveOption();\r\n } else if (!hasFilteredOptions && hasNoResultsText) {\r\n const noResultsTemplate = this._getNoResultTemplate();\r\n this.optionsWrapper.innerHTML = noResultsTemplate;\r\n }\r\n }\r\n\r\n _updateOptionsListTemplate(optionsToRender) {\r\n const optionsWrapperContent =\r\n SelectorEngine.findOne(SELECTOR_OPTIONS_LIST, this._dropdownContainer) ||\r\n SelectorEngine.findOne(SELECTOR_NO_RESULTS, this._dropdownContainer);\r\n\r\n const optionsListTemplate = getOptionsListTemplate(\r\n optionsToRender,\r\n this._selectAllOption,\r\n this._config,\r\n this._classes\r\n );\r\n\r\n this.optionsWrapper.removeChild(optionsWrapperContent);\r\n this.optionsWrapper.appendChild(optionsListTemplate);\r\n }\r\n\r\n _getNoResultTemplate() {\r\n return `${this._config.selectNoResultText}
`;\r\n }\r\n\r\n _filter(value, options) {\r\n const filterValue = value.toLowerCase();\r\n return options.filter((option) =>\r\n option.label.toLowerCase().includes(filterValue)\r\n );\r\n }\r\n\r\n _listenToDropdownKeydown() {\r\n EventHandler.on(\r\n this.dropdown,\r\n \"keydown\",\r\n this._handleOpenKeydown.bind(this)\r\n );\r\n }\r\n\r\n _listenToOutsideClick() {\r\n this._outsideClick = this._handleOutSideClick.bind(this);\r\n EventHandler.on(document, \"click\", this._outsideClick);\r\n }\r\n\r\n _listenToFocusChange(add = true) {\r\n if (add === false) {\r\n EventHandler.off(this._input, \"focus\", () =>\r\n this._notch.setAttribute(DATA_FOCUSED, \"\")\r\n );\r\n\r\n EventHandler.off(this._input, \"blur\", () =>\r\n this._notch.removeAttribute(DATA_FOCUSED)\r\n );\r\n return;\r\n }\r\n EventHandler.on(this._input, \"focus\", () =>\r\n this._notch.setAttribute(DATA_FOCUSED, \"\")\r\n );\r\n\r\n EventHandler.on(this._input, \"blur\", () =>\r\n this._notch.removeAttribute(DATA_FOCUSED)\r\n );\r\n }\r\n\r\n _handleOutSideClick(event) {\r\n const isSelectContent =\r\n this._wrapper && this._wrapper.contains(event.target);\r\n const isDropdown = event.target === this._dropdownContainer;\r\n const isDropdownContent =\r\n this._dropdownContainer && this._dropdownContainer.contains(event.target);\r\n\r\n let isButton;\r\n if (!this._toggleButton) {\r\n this._elementToggle = SelectorEngine.find(SELECTOR_TOGGLE);\r\n }\r\n if (this._elementToggle) {\r\n this._elementToggle.forEach((button) => {\r\n const attributes = Manipulator.getDataAttribute(\r\n button,\r\n \"select-toggle\"\r\n );\r\n if (\r\n attributes === this._element.id ||\r\n this._element.classList.contains(attributes)\r\n ) {\r\n this._toggleButton = button;\r\n isButton = this._toggleButton.contains(event.target);\r\n }\r\n });\r\n }\r\n\r\n if (!isSelectContent && !isDropdown && !isDropdownContent && !isButton) {\r\n this.close();\r\n }\r\n }\r\n\r\n close() {\r\n const closeEvent = EventHandler.trigger(this._element, EVENT_CLOSE);\r\n\r\n if (!this._isOpen || closeEvent.defaultPrevented) {\r\n return;\r\n }\r\n\r\n if (this._config.selectFilter && this.hasSelectAll) {\r\n this._resetFilterState();\r\n this._updateOptionsListTemplate(this._optionsToRender);\r\n if (this._config.multiple) {\r\n this._updateSelectAllState();\r\n }\r\n }\r\n\r\n this._removeDropdownEvents();\r\n\r\n this.dropdown.removeAttribute(DATA_OPEN);\r\n\r\n setTimeout(() => {\r\n this._input.removeAttribute(DATA_FOCUSED);\r\n this._input.blur();\r\n\r\n SelectorEngine.findOne(SELECTOR_NOTCH, this._wrapper).removeAttribute(\r\n DATA_FOCUSED\r\n );\r\n if (this._label && !this.hasSelection) {\r\n this._label.removeAttribute(DATA_ACTIVE);\r\n this._notch.setAttribute(DATA_ACTIVE, \"\");\r\n\r\n this._input.removeAttribute(DATA_ACTIVE);\r\n this._notch.removeAttribute(DATA_ACTIVE);\r\n }\r\n this._updateLabelPositionWhileClosing();\r\n }, 0);\r\n\r\n setTimeout(() => {\r\n if (\r\n this._container &&\r\n this._dropdownContainer.parentNode === this._container\r\n ) {\r\n this._container.removeChild(this._dropdownContainer);\r\n }\r\n this._popper.destroy();\r\n this._isOpen = false;\r\n EventHandler.off(this.dropdown, \"transitionend\");\r\n }, ANIMATION_TRANSITION_TIME);\r\n }\r\n\r\n _resetFilterState() {\r\n this.filterInput.value = \"\";\r\n this._filteredOptionsList = null;\r\n }\r\n\r\n _removeDropdownEvents() {\r\n EventHandler.off(document, \"click\", this._outsideClick);\r\n\r\n if (this._config.selectFilter) {\r\n EventHandler.off(this.dropdown, \"keydown\");\r\n }\r\n\r\n EventHandler.off(this.optionsWrapper, \"click\");\r\n }\r\n\r\n _addMutationObserver() {\r\n this._mutationObserver = new MutationObserver(() => {\r\n if (this._wrapper) {\r\n this._updateSelections();\r\n this._updateDisabledState();\r\n }\r\n });\r\n\r\n this._observeMutationObserver();\r\n }\r\n\r\n _updateSelections() {\r\n this._optionsToRender = this._getOptionsToRender(this._element);\r\n this._plainOptions = this._getPlainOptions(this._optionsToRender);\r\n this._selectionModel.clear();\r\n this._setDefaultSelections();\r\n this._updateInputValue();\r\n this._updateFakeLabelPosition();\r\n this._updateLabelPosition();\r\n this._updateClearButtonVisibility();\r\n\r\n if (this.hasSelectAll) {\r\n this._updateSelectAllState();\r\n }\r\n\r\n const hasFilterValue =\r\n this._config.filter && this.filterInput && this.filterInput.value;\r\n\r\n if (this._isOpen && !hasFilterValue) {\r\n this._updateOptionsListTemplate(this._optionsToRender);\r\n this._setFirstActiveOption();\r\n } else if (this._isOpen && hasFilterValue) {\r\n this._filterOptions(this.filterInput.value);\r\n this._setFirstActiveOption();\r\n } else {\r\n this._dropdownContainer = getDropdownTemplate(\r\n this._dropdownContainerId,\r\n this._config,\r\n this._input.offsetWidth,\r\n this._dropdownHeight,\r\n this._selectAllOption,\r\n this._optionsToRender,\r\n this._customContent,\r\n this._classes\r\n );\r\n }\r\n }\r\n\r\n _updateDisabledState() {\r\n const input = SelectorEngine.findOne(SELECTOR_INPUT, this._wrapper);\r\n\r\n if (this._element.hasAttribute(\"disabled\")) {\r\n this._config.disabled = true;\r\n input.setAttribute(\"disabled\", \"\");\r\n input.setAttribute(DATA_DISABLED, \"\");\r\n } else {\r\n this._config.disabled = false;\r\n input.removeAttribute(\"disabled\");\r\n input.removeAttribute(DATA_DISABLED);\r\n }\r\n }\r\n\r\n _observeMutationObserver() {\r\n if (!this._mutationObserver) {\r\n return;\r\n }\r\n\r\n this._mutationObserver.observe(this._element, {\r\n attributes: true,\r\n childList: true,\r\n characterData: true,\r\n subtree: true,\r\n });\r\n }\r\n\r\n _disconnectMutationObserver() {\r\n if (this.mutationObserver) {\r\n this._mutationObserver.disconnect();\r\n this._mutationObserver = null;\r\n }\r\n }\r\n\r\n _createSelectAllOption() {\r\n const id = this._selectAllId;\r\n const nativeOption = null;\r\n const multiple = true;\r\n const value = \"select-all\";\r\n const label = this._config.selectAllLabel;\r\n const selected = allOptionsSelected(this.options);\r\n const disabled = false;\r\n const hidden = false;\r\n const secondaryText = null;\r\n const groupId = null;\r\n const icon = null;\r\n\r\n return new SelectOption(\r\n id,\r\n nativeOption,\r\n multiple,\r\n value,\r\n label,\r\n selected,\r\n disabled,\r\n hidden,\r\n secondaryText,\r\n groupId,\r\n icon\r\n );\r\n }\r\n\r\n dispose() {\r\n this._removeComponentEvents();\r\n\r\n this._destroyMaterialSelect();\r\n this._listenToFocusChange(false);\r\n\r\n Data.removeData(this._element, DATA_KEY);\r\n }\r\n\r\n _removeComponentEvents() {\r\n EventHandler.off(this.input, \"click\");\r\n EventHandler.off(this.wrapper, this._handleKeydown.bind(this));\r\n EventHandler.off(this.clearButton, \"click\");\r\n EventHandler.off(this.clearButton, \"keydown\");\r\n EventHandler.off(window, \"resize\", this._handleWindowResize.bind(this));\r\n }\r\n\r\n _destroyMaterialSelect() {\r\n if (this._isOpen) {\r\n this.close();\r\n }\r\n\r\n this._destroyMaterialTemplate();\r\n }\r\n\r\n _destroyMaterialTemplate() {\r\n const wrapperParent = this._wrapper.parentNode;\r\n const labels = SelectorEngine.find(\"label\", this._wrapper);\r\n\r\n wrapperParent.appendChild(this._element);\r\n labels.forEach((label) => {\r\n wrapperParent.appendChild(label);\r\n });\r\n\r\n labels.forEach((label) => {\r\n label.removeAttribute(DATA_ACTIVE);\r\n });\r\n Manipulator.removeClass(this._element, this._classes.initialized);\r\n this._element.removeAttribute(DATA_SELECT_INIT);\r\n\r\n wrapperParent.removeChild(this._wrapper);\r\n }\r\n\r\n setValue(value) {\r\n this.options\r\n .filter((option) => option.selected)\r\n .forEach((selection) => (selection.nativeOption.selected = false));\r\n\r\n const isMultipleValue = Array.isArray(value);\r\n\r\n if (isMultipleValue) {\r\n value.forEach((selectionValue) => {\r\n this._selectByValue(selectionValue);\r\n });\r\n } else {\r\n this._selectByValue(value);\r\n }\r\n\r\n this._updateSelections();\r\n }\r\n\r\n _selectByValue(value) {\r\n const correspondingOption = this.options.find(\r\n (option) => option.value === value\r\n );\r\n if (!correspondingOption) {\r\n return false;\r\n }\r\n correspondingOption.nativeOption.selected = true;\r\n return true;\r\n }\r\n\r\n static jQueryInterface(config, options) {\r\n return this.each(function () {\r\n let data = Data.getData(this, DATA_KEY);\r\n const _config = typeof config === \"object\" && config;\r\n\r\n if (!data && /dispose/.test(config)) {\r\n return;\r\n }\r\n\r\n if (!data) {\r\n data = new Select(this, _config);\r\n }\r\n\r\n if (typeof config === \"string\") {\r\n if (typeof data[config] === \"undefined\") {\r\n throw new TypeError(`No method named \"${config}\"`);\r\n }\r\n\r\n data[config](options);\r\n }\r\n });\r\n }\r\n\r\n static getInstance(element) {\r\n return Data.getData(element, DATA_KEY);\r\n }\r\n\r\n static getOrCreateInstance(element, config = {}) {\r\n return (\r\n this.getInstance(element) ||\r\n new this(element, typeof config === \"object\" ? config : null)\r\n );\r\n }\r\n}\r\n\r\nexport default Select;\r\n", "/*\r\n--------------------------------------------------------------------------\r\nTailwind Elements is an open-source UI kit of advanced components for TailwindCSS.\r\nCopyright \u00A9 2023 MDBootstrap.com\r\n\r\nUnless a custom, individually assigned license has been granted, this program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\r\nIn addition, a custom license may be available upon request, subject to the terms and conditions of that license. Please contact tailwind@mdbootstrap.com for more information on obtaining a custom license.\r\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\r\n--------------------------------------------------------------------------\r\n*/\r\n\r\nexport const getInputField = ({ inputID, labelText }, classes) => {\r\n return `\r\n \r\n ${labelText}\r\n \r\n
\r\n