diff --git a/frontend/node_modules/chart.js/LICENSE.md b/frontend/node_modules/chart.js/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..f216610fd7edadc57a11668b3ca5b7a400e5b96e --- /dev/null +++ b/frontend/node_modules/chart.js/LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2014-2024 Chart.js Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/frontend/node_modules/chart.js/README.md b/frontend/node_modules/chart.js/README.md new file mode 100644 index 0000000000000000000000000000000000000000..df7334ee258201c7bdbd838f42a93c62d5926f1b --- /dev/null +++ b/frontend/node_modules/chart.js/README.md @@ -0,0 +1,38 @@ +

+ + https://www.chartjs.org/
+
+ Simple yet flexible JavaScript charting for designers & developers +

+ +

+ Downloads + GitHub Workflow Status + Coverage + Awesome + Discord +

+ +## Documentation + +All the links point to the new version 4 of the lib. + +* [Introduction](https://www.chartjs.org/docs/latest/) +* [Getting Started](https://www.chartjs.org/docs/latest/getting-started/index) +* [General](https://www.chartjs.org/docs/latest/general/data-structures) +* [Configuration](https://www.chartjs.org/docs/latest/configuration/index) +* [Charts](https://www.chartjs.org/docs/latest/charts/line) +* [Axes](https://www.chartjs.org/docs/latest/axes/index) +* [Developers](https://www.chartjs.org/docs/latest/developers/index) +* [Popular Extensions](https://github.com/chartjs/awesome) +* [Samples](https://www.chartjs.org/samples/) + +In case you are looking for an older version of the docs, you will have to specify the specific version in the url like this: [https://www.chartjs.org/docs/2.9.4/](https://www.chartjs.org/docs/2.9.4/) + +## Contributing + +Instructions on building and testing Chart.js can be found in [the documentation](https://www.chartjs.org/docs/master/developers/contributing.html#building-and-testing). Before submitting an issue or a pull request, please take a moment to look over the [contributing guidelines](https://www.chartjs.org/docs/master/developers/contributing) first. For support, please post questions on [Stack Overflow](https://stackoverflow.com/questions/tagged/chart.js) with the `chart.js` tag. + +## License + +Chart.js is available under the [MIT license](LICENSE.md). diff --git a/frontend/node_modules/chart.js/auto/auto.cjs b/frontend/node_modules/chart.js/auto/auto.cjs new file mode 100644 index 0000000000000000000000000000000000000000..62e08b16dfc2f6e83a9673fe018a8dce5c6d18ae --- /dev/null +++ b/frontend/node_modules/chart.js/auto/auto.cjs @@ -0,0 +1,6 @@ +const chartjs = require('../dist/chart.cjs'); +const {Chart, registerables} = chartjs; + +Chart.register(...registerables); + +module.exports = Object.assign(Chart, chartjs); diff --git a/frontend/node_modules/chart.js/auto/auto.d.ts b/frontend/node_modules/chart.js/auto/auto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fb1263ae5c9987c38407184688af5a1e5ed2ac02 --- /dev/null +++ b/frontend/node_modules/chart.js/auto/auto.d.ts @@ -0,0 +1,4 @@ +import {Chart} from '../dist/types.js'; + +export * from '../dist/types.js'; +export default Chart; diff --git a/frontend/node_modules/chart.js/auto/auto.js b/frontend/node_modules/chart.js/auto/auto.js new file mode 100644 index 0000000000000000000000000000000000000000..924a0f900ed84bb840fd6f989cea061f60a38d6b --- /dev/null +++ b/frontend/node_modules/chart.js/auto/auto.js @@ -0,0 +1,6 @@ +import {Chart, registerables} from '../dist/chart.js'; + +Chart.register(...registerables); + +export * from '../dist/chart.js'; +export default Chart; diff --git a/frontend/node_modules/chart.js/auto/package.json b/frontend/node_modules/chart.js/auto/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7e0ca323fb2134f3e72952277e8808da93286e81 --- /dev/null +++ b/frontend/node_modules/chart.js/auto/package.json @@ -0,0 +1,14 @@ +{ + "name": "chart.js-auto", + "private": true, + "description": "Auto registering package. Exists to support bundlers without exports support such as webpack 4.", + "type": "module", + "main": "./auto.cjs", + "module": "./auto.js", + "exports": { + "types": "./auto.d.ts", + "import": "./auto.js", + "require": "./auto.cjs" + }, + "types": "./auto.d.ts" +} diff --git a/frontend/node_modules/chart.js/dist/chart.cjs b/frontend/node_modules/chart.js/dist/chart.cjs new file mode 100644 index 0000000000000000000000000000000000000000..7d89de629a36f46123f83bfddb064c455b0971db --- /dev/null +++ b/frontend/node_modules/chart.js/dist/chart.cjs @@ -0,0 +1,11638 @@ +/*! + * Chart.js v4.5.0 + * https://www.chartjs.org + * (c) 2025 Chart.js Contributors + * Released under the MIT License + */ +'use strict'; + +var helpers_dataset = require('./chunks/helpers.dataset.cjs'); +require('@kurkle/color'); + +class Animator { + constructor(){ + this._request = null; + this._charts = new Map(); + this._running = false; + this._lastDate = undefined; + } + _notify(chart, anims, date, type) { + const callbacks = anims.listeners[type]; + const numSteps = anims.duration; + callbacks.forEach((fn)=>fn({ + chart, + initial: anims.initial, + numSteps, + currentStep: Math.min(date - anims.start, numSteps) + })); + } + _refresh() { + if (this._request) { + return; + } + this._running = true; + this._request = helpers_dataset.requestAnimFrame.call(window, ()=>{ + this._update(); + this._request = null; + if (this._running) { + this._refresh(); + } + }); + } + _update(date = Date.now()) { + let remaining = 0; + this._charts.forEach((anims, chart)=>{ + if (!anims.running || !anims.items.length) { + return; + } + const items = anims.items; + let i = items.length - 1; + let draw = false; + let item; + for(; i >= 0; --i){ + item = items[i]; + if (item._active) { + if (item._total > anims.duration) { + anims.duration = item._total; + } + item.tick(date); + draw = true; + } else { + items[i] = items[items.length - 1]; + items.pop(); + } + } + if (draw) { + chart.draw(); + this._notify(chart, anims, date, 'progress'); + } + if (!items.length) { + anims.running = false; + this._notify(chart, anims, date, 'complete'); + anims.initial = false; + } + remaining += items.length; + }); + this._lastDate = date; + if (remaining === 0) { + this._running = false; + } + } + _getAnims(chart) { + const charts = this._charts; + let anims = charts.get(chart); + if (!anims) { + anims = { + running: false, + initial: true, + items: [], + listeners: { + complete: [], + progress: [] + } + }; + charts.set(chart, anims); + } + return anims; + } + listen(chart, event, cb) { + this._getAnims(chart).listeners[event].push(cb); + } + add(chart, items) { + if (!items || !items.length) { + return; + } + this._getAnims(chart).items.push(...items); + } + has(chart) { + return this._getAnims(chart).items.length > 0; + } + start(chart) { + const anims = this._charts.get(chart); + if (!anims) { + return; + } + anims.running = true; + anims.start = Date.now(); + anims.duration = anims.items.reduce((acc, cur)=>Math.max(acc, cur._duration), 0); + this._refresh(); + } + running(chart) { + if (!this._running) { + return false; + } + const anims = this._charts.get(chart); + if (!anims || !anims.running || !anims.items.length) { + return false; + } + return true; + } + stop(chart) { + const anims = this._charts.get(chart); + if (!anims || !anims.items.length) { + return; + } + const items = anims.items; + let i = items.length - 1; + for(; i >= 0; --i){ + items[i].cancel(); + } + anims.items = []; + this._notify(chart, anims, Date.now(), 'complete'); + } + remove(chart) { + return this._charts.delete(chart); + } +} +var animator = /* #__PURE__ */ new Animator(); + +const transparent = 'transparent'; +const interpolators = { + boolean (from, to, factor) { + return factor > 0.5 ? to : from; + }, + color (from, to, factor) { + const c0 = helpers_dataset.color(from || transparent); + const c1 = c0.valid && helpers_dataset.color(to || transparent); + return c1 && c1.valid ? c1.mix(c0, factor).hexString() : to; + }, + number (from, to, factor) { + return from + (to - from) * factor; + } +}; +class Animation { + constructor(cfg, target, prop, to){ + const currentValue = target[prop]; + to = helpers_dataset.resolve([ + cfg.to, + to, + currentValue, + cfg.from + ]); + const from = helpers_dataset.resolve([ + cfg.from, + currentValue, + to + ]); + this._active = true; + this._fn = cfg.fn || interpolators[cfg.type || typeof from]; + this._easing = helpers_dataset.effects[cfg.easing] || helpers_dataset.effects.linear; + this._start = Math.floor(Date.now() + (cfg.delay || 0)); + this._duration = this._total = Math.floor(cfg.duration); + this._loop = !!cfg.loop; + this._target = target; + this._prop = prop; + this._from = from; + this._to = to; + this._promises = undefined; + } + active() { + return this._active; + } + update(cfg, to, date) { + if (this._active) { + this._notify(false); + const currentValue = this._target[this._prop]; + const elapsed = date - this._start; + const remain = this._duration - elapsed; + this._start = date; + this._duration = Math.floor(Math.max(remain, cfg.duration)); + this._total += elapsed; + this._loop = !!cfg.loop; + this._to = helpers_dataset.resolve([ + cfg.to, + to, + currentValue, + cfg.from + ]); + this._from = helpers_dataset.resolve([ + cfg.from, + currentValue, + to + ]); + } + } + cancel() { + if (this._active) { + this.tick(Date.now()); + this._active = false; + this._notify(false); + } + } + tick(date) { + const elapsed = date - this._start; + const duration = this._duration; + const prop = this._prop; + const from = this._from; + const loop = this._loop; + const to = this._to; + let factor; + this._active = from !== to && (loop || elapsed < duration); + if (!this._active) { + this._target[prop] = to; + this._notify(true); + return; + } + if (elapsed < 0) { + this._target[prop] = from; + return; + } + factor = elapsed / duration % 2; + factor = loop && factor > 1 ? 2 - factor : factor; + factor = this._easing(Math.min(1, Math.max(0, factor))); + this._target[prop] = this._fn(from, to, factor); + } + wait() { + const promises = this._promises || (this._promises = []); + return new Promise((res, rej)=>{ + promises.push({ + res, + rej + }); + }); + } + _notify(resolved) { + const method = resolved ? 'res' : 'rej'; + const promises = this._promises || []; + for(let i = 0; i < promises.length; i++){ + promises[i][method](); + } + } +} + +class Animations { + constructor(chart, config){ + this._chart = chart; + this._properties = new Map(); + this.configure(config); + } + configure(config) { + if (!helpers_dataset.isObject(config)) { + return; + } + const animationOptions = Object.keys(helpers_dataset.defaults.animation); + const animatedProps = this._properties; + Object.getOwnPropertyNames(config).forEach((key)=>{ + const cfg = config[key]; + if (!helpers_dataset.isObject(cfg)) { + return; + } + const resolved = {}; + for (const option of animationOptions){ + resolved[option] = cfg[option]; + } + (helpers_dataset.isArray(cfg.properties) && cfg.properties || [ + key + ]).forEach((prop)=>{ + if (prop === key || !animatedProps.has(prop)) { + animatedProps.set(prop, resolved); + } + }); + }); + } + _animateOptions(target, values) { + const newOptions = values.options; + const options = resolveTargetOptions(target, newOptions); + if (!options) { + return []; + } + const animations = this._createAnimations(options, newOptions); + if (newOptions.$shared) { + awaitAll(target.options.$animations, newOptions).then(()=>{ + target.options = newOptions; + }, ()=>{ + }); + } + return animations; + } + _createAnimations(target, values) { + const animatedProps = this._properties; + const animations = []; + const running = target.$animations || (target.$animations = {}); + const props = Object.keys(values); + const date = Date.now(); + let i; + for(i = props.length - 1; i >= 0; --i){ + const prop = props[i]; + if (prop.charAt(0) === '$') { + continue; + } + if (prop === 'options') { + animations.push(...this._animateOptions(target, values)); + continue; + } + const value = values[prop]; + let animation = running[prop]; + const cfg = animatedProps.get(prop); + if (animation) { + if (cfg && animation.active()) { + animation.update(cfg, value, date); + continue; + } else { + animation.cancel(); + } + } + if (!cfg || !cfg.duration) { + target[prop] = value; + continue; + } + running[prop] = animation = new Animation(cfg, target, prop, value); + animations.push(animation); + } + return animations; + } + update(target, values) { + if (this._properties.size === 0) { + Object.assign(target, values); + return; + } + const animations = this._createAnimations(target, values); + if (animations.length) { + animator.add(this._chart, animations); + return true; + } + } +} +function awaitAll(animations, properties) { + const running = []; + const keys = Object.keys(properties); + for(let i = 0; i < keys.length; i++){ + const anim = animations[keys[i]]; + if (anim && anim.active()) { + running.push(anim.wait()); + } + } + return Promise.all(running); +} +function resolveTargetOptions(target, newOptions) { + if (!newOptions) { + return; + } + let options = target.options; + if (!options) { + target.options = newOptions; + return; + } + if (options.$shared) { + target.options = options = Object.assign({}, options, { + $shared: false, + $animations: {} + }); + } + return options; +} + +function scaleClip(scale, allowedOverflow) { + const opts = scale && scale.options || {}; + const reverse = opts.reverse; + const min = opts.min === undefined ? allowedOverflow : 0; + const max = opts.max === undefined ? allowedOverflow : 0; + return { + start: reverse ? max : min, + end: reverse ? min : max + }; +} +function defaultClip(xScale, yScale, allowedOverflow) { + if (allowedOverflow === false) { + return false; + } + const x = scaleClip(xScale, allowedOverflow); + const y = scaleClip(yScale, allowedOverflow); + return { + top: y.end, + right: x.end, + bottom: y.start, + left: x.start + }; +} +function toClip(value) { + let t, r, b, l; + if (helpers_dataset.isObject(value)) { + t = value.top; + r = value.right; + b = value.bottom; + l = value.left; + } else { + t = r = b = l = value; + } + return { + top: t, + right: r, + bottom: b, + left: l, + disabled: value === false + }; +} +function getSortedDatasetIndices(chart, filterVisible) { + const keys = []; + const metasets = chart._getSortedDatasetMetas(filterVisible); + let i, ilen; + for(i = 0, ilen = metasets.length; i < ilen; ++i){ + keys.push(metasets[i].index); + } + return keys; +} +function applyStack(stack, value, dsIndex, options = {}) { + const keys = stack.keys; + const singleMode = options.mode === 'single'; + let i, ilen, datasetIndex, otherValue; + if (value === null) { + return; + } + let found = false; + for(i = 0, ilen = keys.length; i < ilen; ++i){ + datasetIndex = +keys[i]; + if (datasetIndex === dsIndex) { + found = true; + if (options.all) { + continue; + } + break; + } + otherValue = stack.values[datasetIndex]; + if (helpers_dataset.isNumberFinite(otherValue) && (singleMode || value === 0 || helpers_dataset.sign(value) === helpers_dataset.sign(otherValue))) { + value += otherValue; + } + } + if (!found && !options.all) { + return 0; + } + return value; +} +function convertObjectDataToArray(data, meta) { + const { iScale , vScale } = meta; + const iAxisKey = iScale.axis === 'x' ? 'x' : 'y'; + const vAxisKey = vScale.axis === 'x' ? 'x' : 'y'; + const keys = Object.keys(data); + const adata = new Array(keys.length); + let i, ilen, key; + for(i = 0, ilen = keys.length; i < ilen; ++i){ + key = keys[i]; + adata[i] = { + [iAxisKey]: key, + [vAxisKey]: data[key] + }; + } + return adata; +} +function isStacked(scale, meta) { + const stacked = scale && scale.options.stacked; + return stacked || stacked === undefined && meta.stack !== undefined; +} +function getStackKey(indexScale, valueScale, meta) { + return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`; +} +function getUserBounds(scale) { + const { min , max , minDefined , maxDefined } = scale.getUserBounds(); + return { + min: minDefined ? min : Number.NEGATIVE_INFINITY, + max: maxDefined ? max : Number.POSITIVE_INFINITY + }; +} +function getOrCreateStack(stacks, stackKey, indexValue) { + const subStack = stacks[stackKey] || (stacks[stackKey] = {}); + return subStack[indexValue] || (subStack[indexValue] = {}); +} +function getLastIndexInStack(stack, vScale, positive, type) { + for (const meta of vScale.getMatchingVisibleMetas(type).reverse()){ + const value = stack[meta.index]; + if (positive && value > 0 || !positive && value < 0) { + return meta.index; + } + } + return null; +} +function updateStacks(controller, parsed) { + const { chart , _cachedMeta: meta } = controller; + const stacks = chart._stacks || (chart._stacks = {}); + const { iScale , vScale , index: datasetIndex } = meta; + const iAxis = iScale.axis; + const vAxis = vScale.axis; + const key = getStackKey(iScale, vScale, meta); + const ilen = parsed.length; + let stack; + for(let i = 0; i < ilen; ++i){ + const item = parsed[i]; + const { [iAxis]: index , [vAxis]: value } = item; + const itemStacks = item._stacks || (item._stacks = {}); + stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index); + stack[datasetIndex] = value; + stack._top = getLastIndexInStack(stack, vScale, true, meta.type); + stack._bottom = getLastIndexInStack(stack, vScale, false, meta.type); + const visualValues = stack._visualValues || (stack._visualValues = {}); + visualValues[datasetIndex] = value; + } +} +function getFirstScaleId(chart, axis) { + const scales = chart.scales; + return Object.keys(scales).filter((key)=>scales[key].axis === axis).shift(); +} +function createDatasetContext(parent, index) { + return helpers_dataset.createContext(parent, { + active: false, + dataset: undefined, + datasetIndex: index, + index, + mode: 'default', + type: 'dataset' + }); +} +function createDataContext(parent, index, element) { + return helpers_dataset.createContext(parent, { + active: false, + dataIndex: index, + parsed: undefined, + raw: undefined, + element, + index, + mode: 'default', + type: 'data' + }); +} +function clearStacks(meta, items) { + const datasetIndex = meta.controller.index; + const axis = meta.vScale && meta.vScale.axis; + if (!axis) { + return; + } + items = items || meta._parsed; + for (const parsed of items){ + const stacks = parsed._stacks; + if (!stacks || stacks[axis] === undefined || stacks[axis][datasetIndex] === undefined) { + return; + } + delete stacks[axis][datasetIndex]; + if (stacks[axis]._visualValues !== undefined && stacks[axis]._visualValues[datasetIndex] !== undefined) { + delete stacks[axis]._visualValues[datasetIndex]; + } + } +} +const isDirectUpdateMode = (mode)=>mode === 'reset' || mode === 'none'; +const cloneIfNotShared = (cached, shared)=>shared ? cached : Object.assign({}, cached); +const createStack = (canStack, meta, chart)=>canStack && !meta.hidden && meta._stacked && { + keys: getSortedDatasetIndices(chart, true), + values: null + }; +class DatasetController { + static defaults = {}; + static datasetElementType = null; + static dataElementType = null; + constructor(chart, datasetIndex){ + this.chart = chart; + this._ctx = chart.ctx; + this.index = datasetIndex; + this._cachedDataOpts = {}; + this._cachedMeta = this.getMeta(); + this._type = this._cachedMeta.type; + this.options = undefined; + this._parsing = false; + this._data = undefined; + this._objectData = undefined; + this._sharedOptions = undefined; + this._drawStart = undefined; + this._drawCount = undefined; + this.enableOptionSharing = false; + this.supportsDecimation = false; + this.$context = undefined; + this._syncList = []; + this.datasetElementType = new.target.datasetElementType; + this.dataElementType = new.target.dataElementType; + this.initialize(); + } + initialize() { + const meta = this._cachedMeta; + this.configure(); + this.linkScales(); + meta._stacked = isStacked(meta.vScale, meta); + this.addElements(); + if (this.options.fill && !this.chart.isPluginEnabled('filler')) { + console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options"); + } + } + updateIndex(datasetIndex) { + if (this.index !== datasetIndex) { + clearStacks(this._cachedMeta); + } + this.index = datasetIndex; + } + linkScales() { + const chart = this.chart; + const meta = this._cachedMeta; + const dataset = this.getDataset(); + const chooseId = (axis, x, y, r)=>axis === 'x' ? x : axis === 'r' ? r : y; + const xid = meta.xAxisID = helpers_dataset.valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x')); + const yid = meta.yAxisID = helpers_dataset.valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y')); + const rid = meta.rAxisID = helpers_dataset.valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r')); + const indexAxis = meta.indexAxis; + const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid); + const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid); + meta.xScale = this.getScaleForId(xid); + meta.yScale = this.getScaleForId(yid); + meta.rScale = this.getScaleForId(rid); + meta.iScale = this.getScaleForId(iid); + meta.vScale = this.getScaleForId(vid); + } + getDataset() { + return this.chart.data.datasets[this.index]; + } + getMeta() { + return this.chart.getDatasetMeta(this.index); + } + getScaleForId(scaleID) { + return this.chart.scales[scaleID]; + } + _getOtherScale(scale) { + const meta = this._cachedMeta; + return scale === meta.iScale ? meta.vScale : meta.iScale; + } + reset() { + this._update('reset'); + } + _destroy() { + const meta = this._cachedMeta; + if (this._data) { + helpers_dataset.unlistenArrayEvents(this._data, this); + } + if (meta._stacked) { + clearStacks(meta); + } + } + _dataCheck() { + const dataset = this.getDataset(); + const data = dataset.data || (dataset.data = []); + const _data = this._data; + if (helpers_dataset.isObject(data)) { + const meta = this._cachedMeta; + this._data = convertObjectDataToArray(data, meta); + } else if (_data !== data) { + if (_data) { + helpers_dataset.unlistenArrayEvents(_data, this); + const meta = this._cachedMeta; + clearStacks(meta); + meta._parsed = []; + } + if (data && Object.isExtensible(data)) { + helpers_dataset.listenArrayEvents(data, this); + } + this._syncList = []; + this._data = data; + } + } + addElements() { + const meta = this._cachedMeta; + this._dataCheck(); + if (this.datasetElementType) { + meta.dataset = new this.datasetElementType(); + } + } + buildOrUpdateElements(resetNewElements) { + const meta = this._cachedMeta; + const dataset = this.getDataset(); + let stackChanged = false; + this._dataCheck(); + const oldStacked = meta._stacked; + meta._stacked = isStacked(meta.vScale, meta); + if (meta.stack !== dataset.stack) { + stackChanged = true; + clearStacks(meta); + meta.stack = dataset.stack; + } + this._resyncElements(resetNewElements); + if (stackChanged || oldStacked !== meta._stacked) { + updateStacks(this, meta._parsed); + meta._stacked = isStacked(meta.vScale, meta); + } + } + configure() { + const config = this.chart.config; + const scopeKeys = config.datasetScopeKeys(this._type); + const scopes = config.getOptionScopes(this.getDataset(), scopeKeys, true); + this.options = config.createResolver(scopes, this.getContext()); + this._parsing = this.options.parsing; + this._cachedDataOpts = {}; + } + parse(start, count) { + const { _cachedMeta: meta , _data: data } = this; + const { iScale , _stacked } = meta; + const iAxis = iScale.axis; + let sorted = start === 0 && count === data.length ? true : meta._sorted; + let prev = start > 0 && meta._parsed[start - 1]; + let i, cur, parsed; + if (this._parsing === false) { + meta._parsed = data; + meta._sorted = true; + parsed = data; + } else { + if (helpers_dataset.isArray(data[start])) { + parsed = this.parseArrayData(meta, data, start, count); + } else if (helpers_dataset.isObject(data[start])) { + parsed = this.parseObjectData(meta, data, start, count); + } else { + parsed = this.parsePrimitiveData(meta, data, start, count); + } + const isNotInOrderComparedToPrev = ()=>cur[iAxis] === null || prev && cur[iAxis] < prev[iAxis]; + for(i = 0; i < count; ++i){ + meta._parsed[i + start] = cur = parsed[i]; + if (sorted) { + if (isNotInOrderComparedToPrev()) { + sorted = false; + } + prev = cur; + } + } + meta._sorted = sorted; + } + if (_stacked) { + updateStacks(this, parsed); + } + } + parsePrimitiveData(meta, data, start, count) { + const { iScale , vScale } = meta; + const iAxis = iScale.axis; + const vAxis = vScale.axis; + const labels = iScale.getLabels(); + const singleScale = iScale === vScale; + const parsed = new Array(count); + let i, ilen, index; + for(i = 0, ilen = count; i < ilen; ++i){ + index = i + start; + parsed[i] = { + [iAxis]: singleScale || iScale.parse(labels[index], index), + [vAxis]: vScale.parse(data[index], index) + }; + } + return parsed; + } + parseArrayData(meta, data, start, count) { + const { xScale , yScale } = meta; + const parsed = new Array(count); + let i, ilen, index, item; + for(i = 0, ilen = count; i < ilen; ++i){ + index = i + start; + item = data[index]; + parsed[i] = { + x: xScale.parse(item[0], index), + y: yScale.parse(item[1], index) + }; + } + return parsed; + } + parseObjectData(meta, data, start, count) { + const { xScale , yScale } = meta; + const { xAxisKey ='x' , yAxisKey ='y' } = this._parsing; + const parsed = new Array(count); + let i, ilen, index, item; + for(i = 0, ilen = count; i < ilen; ++i){ + index = i + start; + item = data[index]; + parsed[i] = { + x: xScale.parse(helpers_dataset.resolveObjectKey(item, xAxisKey), index), + y: yScale.parse(helpers_dataset.resolveObjectKey(item, yAxisKey), index) + }; + } + return parsed; + } + getParsed(index) { + return this._cachedMeta._parsed[index]; + } + getDataElement(index) { + return this._cachedMeta.data[index]; + } + applyStack(scale, parsed, mode) { + const chart = this.chart; + const meta = this._cachedMeta; + const value = parsed[scale.axis]; + const stack = { + keys: getSortedDatasetIndices(chart, true), + values: parsed._stacks[scale.axis]._visualValues + }; + return applyStack(stack, value, meta.index, { + mode + }); + } + updateRangeFromParsed(range, scale, parsed, stack) { + const parsedValue = parsed[scale.axis]; + let value = parsedValue === null ? NaN : parsedValue; + const values = stack && parsed._stacks[scale.axis]; + if (stack && values) { + stack.values = values; + value = applyStack(stack, parsedValue, this._cachedMeta.index); + } + range.min = Math.min(range.min, value); + range.max = Math.max(range.max, value); + } + getMinMax(scale, canStack) { + const meta = this._cachedMeta; + const _parsed = meta._parsed; + const sorted = meta._sorted && scale === meta.iScale; + const ilen = _parsed.length; + const otherScale = this._getOtherScale(scale); + const stack = createStack(canStack, meta, this.chart); + const range = { + min: Number.POSITIVE_INFINITY, + max: Number.NEGATIVE_INFINITY + }; + const { min: otherMin , max: otherMax } = getUserBounds(otherScale); + let i, parsed; + function _skip() { + parsed = _parsed[i]; + const otherValue = parsed[otherScale.axis]; + return !helpers_dataset.isNumberFinite(parsed[scale.axis]) || otherMin > otherValue || otherMax < otherValue; + } + for(i = 0; i < ilen; ++i){ + if (_skip()) { + continue; + } + this.updateRangeFromParsed(range, scale, parsed, stack); + if (sorted) { + break; + } + } + if (sorted) { + for(i = ilen - 1; i >= 0; --i){ + if (_skip()) { + continue; + } + this.updateRangeFromParsed(range, scale, parsed, stack); + break; + } + } + return range; + } + getAllParsedValues(scale) { + const parsed = this._cachedMeta._parsed; + const values = []; + let i, ilen, value; + for(i = 0, ilen = parsed.length; i < ilen; ++i){ + value = parsed[i][scale.axis]; + if (helpers_dataset.isNumberFinite(value)) { + values.push(value); + } + } + return values; + } + getMaxOverflow() { + return false; + } + getLabelAndValue(index) { + const meta = this._cachedMeta; + const iScale = meta.iScale; + const vScale = meta.vScale; + const parsed = this.getParsed(index); + return { + label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '', + value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : '' + }; + } + _update(mode) { + const meta = this._cachedMeta; + this.update(mode || 'default'); + meta._clip = toClip(helpers_dataset.valueOrDefault(this.options.clip, defaultClip(meta.xScale, meta.yScale, this.getMaxOverflow()))); + } + update(mode) {} + draw() { + const ctx = this._ctx; + const chart = this.chart; + const meta = this._cachedMeta; + const elements = meta.data || []; + const area = chart.chartArea; + const active = []; + const start = this._drawStart || 0; + const count = this._drawCount || elements.length - start; + const drawActiveElementsOnTop = this.options.drawActiveElementsOnTop; + let i; + if (meta.dataset) { + meta.dataset.draw(ctx, area, start, count); + } + for(i = start; i < start + count; ++i){ + const element = elements[i]; + if (element.hidden) { + continue; + } + if (element.active && drawActiveElementsOnTop) { + active.push(element); + } else { + element.draw(ctx, area); + } + } + for(i = 0; i < active.length; ++i){ + active[i].draw(ctx, area); + } + } + getStyle(index, active) { + const mode = active ? 'active' : 'default'; + return index === undefined && this._cachedMeta.dataset ? this.resolveDatasetElementOptions(mode) : this.resolveDataElementOptions(index || 0, mode); + } + getContext(index, active, mode) { + const dataset = this.getDataset(); + let context; + if (index >= 0 && index < this._cachedMeta.data.length) { + const element = this._cachedMeta.data[index]; + context = element.$context || (element.$context = createDataContext(this.getContext(), index, element)); + context.parsed = this.getParsed(index); + context.raw = dataset.data[index]; + context.index = context.dataIndex = index; + } else { + context = this.$context || (this.$context = createDatasetContext(this.chart.getContext(), this.index)); + context.dataset = dataset; + context.index = context.datasetIndex = this.index; + } + context.active = !!active; + context.mode = mode; + return context; + } + resolveDatasetElementOptions(mode) { + return this._resolveElementOptions(this.datasetElementType.id, mode); + } + resolveDataElementOptions(index, mode) { + return this._resolveElementOptions(this.dataElementType.id, mode, index); + } + _resolveElementOptions(elementType, mode = 'default', index) { + const active = mode === 'active'; + const cache = this._cachedDataOpts; + const cacheKey = elementType + '-' + mode; + const cached = cache[cacheKey]; + const sharing = this.enableOptionSharing && helpers_dataset.defined(index); + if (cached) { + return cloneIfNotShared(cached, sharing); + } + const config = this.chart.config; + const scopeKeys = config.datasetElementScopeKeys(this._type, elementType); + const prefixes = active ? [ + `${elementType}Hover`, + 'hover', + elementType, + '' + ] : [ + elementType, + '' + ]; + const scopes = config.getOptionScopes(this.getDataset(), scopeKeys); + const names = Object.keys(helpers_dataset.defaults.elements[elementType]); + const context = ()=>this.getContext(index, active, mode); + const values = config.resolveNamedOptions(scopes, names, context, prefixes); + if (values.$shared) { + values.$shared = sharing; + cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing)); + } + return values; + } + _resolveAnimations(index, transition, active) { + const chart = this.chart; + const cache = this._cachedDataOpts; + const cacheKey = `animation-${transition}`; + const cached = cache[cacheKey]; + if (cached) { + return cached; + } + let options; + if (chart.options.animation !== false) { + const config = this.chart.config; + const scopeKeys = config.datasetAnimationScopeKeys(this._type, transition); + const scopes = config.getOptionScopes(this.getDataset(), scopeKeys); + options = config.createResolver(scopes, this.getContext(index, active, transition)); + } + const animations = new Animations(chart, options && options.animations); + if (options && options._cacheable) { + cache[cacheKey] = Object.freeze(animations); + } + return animations; + } + getSharedOptions(options) { + if (!options.$shared) { + return; + } + return this._sharedOptions || (this._sharedOptions = Object.assign({}, options)); + } + includeOptions(mode, sharedOptions) { + return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled; + } + _getSharedOptions(start, mode) { + const firstOpts = this.resolveDataElementOptions(start, mode); + const previouslySharedOptions = this._sharedOptions; + const sharedOptions = this.getSharedOptions(firstOpts); + const includeOptions = this.includeOptions(mode, sharedOptions) || sharedOptions !== previouslySharedOptions; + this.updateSharedOptions(sharedOptions, mode, firstOpts); + return { + sharedOptions, + includeOptions + }; + } + updateElement(element, index, properties, mode) { + if (isDirectUpdateMode(mode)) { + Object.assign(element, properties); + } else { + this._resolveAnimations(index, mode).update(element, properties); + } + } + updateSharedOptions(sharedOptions, mode, newOptions) { + if (sharedOptions && !isDirectUpdateMode(mode)) { + this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions); + } + } + _setStyle(element, index, mode, active) { + element.active = active; + const options = this.getStyle(index, active); + this._resolveAnimations(index, mode, active).update(element, { + options: !active && this.getSharedOptions(options) || options + }); + } + removeHoverStyle(element, datasetIndex, index) { + this._setStyle(element, index, 'active', false); + } + setHoverStyle(element, datasetIndex, index) { + this._setStyle(element, index, 'active', true); + } + _removeDatasetHoverStyle() { + const element = this._cachedMeta.dataset; + if (element) { + this._setStyle(element, undefined, 'active', false); + } + } + _setDatasetHoverStyle() { + const element = this._cachedMeta.dataset; + if (element) { + this._setStyle(element, undefined, 'active', true); + } + } + _resyncElements(resetNewElements) { + const data = this._data; + const elements = this._cachedMeta.data; + for (const [method, arg1, arg2] of this._syncList){ + this[method](arg1, arg2); + } + this._syncList = []; + const numMeta = elements.length; + const numData = data.length; + const count = Math.min(numData, numMeta); + if (count) { + this.parse(0, count); + } + if (numData > numMeta) { + this._insertElements(numMeta, numData - numMeta, resetNewElements); + } else if (numData < numMeta) { + this._removeElements(numData, numMeta - numData); + } + } + _insertElements(start, count, resetNewElements = true) { + const meta = this._cachedMeta; + const data = meta.data; + const end = start + count; + let i; + const move = (arr)=>{ + arr.length += count; + for(i = arr.length - 1; i >= end; i--){ + arr[i] = arr[i - count]; + } + }; + move(data); + for(i = start; i < end; ++i){ + data[i] = new this.dataElementType(); + } + if (this._parsing) { + move(meta._parsed); + } + this.parse(start, count); + if (resetNewElements) { + this.updateElements(data, start, count, 'reset'); + } + } + updateElements(element, start, count, mode) {} + _removeElements(start, count) { + const meta = this._cachedMeta; + if (this._parsing) { + const removed = meta._parsed.splice(start, count); + if (meta._stacked) { + clearStacks(meta, removed); + } + } + meta.data.splice(start, count); + } + _sync(args) { + if (this._parsing) { + this._syncList.push(args); + } else { + const [method, arg1, arg2] = args; + this[method](arg1, arg2); + } + this.chart._dataChanges.push([ + this.index, + ...args + ]); + } + _onDataPush() { + const count = arguments.length; + this._sync([ + '_insertElements', + this.getDataset().data.length - count, + count + ]); + } + _onDataPop() { + this._sync([ + '_removeElements', + this._cachedMeta.data.length - 1, + 1 + ]); + } + _onDataShift() { + this._sync([ + '_removeElements', + 0, + 1 + ]); + } + _onDataSplice(start, count) { + if (count) { + this._sync([ + '_removeElements', + start, + count + ]); + } + const newCount = arguments.length - 2; + if (newCount) { + this._sync([ + '_insertElements', + start, + newCount + ]); + } + } + _onDataUnshift() { + this._sync([ + '_insertElements', + 0, + arguments.length + ]); + } +} + +function getAllScaleValues(scale, type) { + if (!scale._cache.$bar) { + const visibleMetas = scale.getMatchingVisibleMetas(type); + let values = []; + for(let i = 0, ilen = visibleMetas.length; i < ilen; i++){ + values = values.concat(visibleMetas[i].controller.getAllParsedValues(scale)); + } + scale._cache.$bar = helpers_dataset._arrayUnique(values.sort((a, b)=>a - b)); + } + return scale._cache.$bar; +} + function computeMinSampleSize(meta) { + const scale = meta.iScale; + const values = getAllScaleValues(scale, meta.type); + let min = scale._length; + let i, ilen, curr, prev; + const updateMinAndPrev = ()=>{ + if (curr === 32767 || curr === -32768) { + return; + } + if (helpers_dataset.defined(prev)) { + min = Math.min(min, Math.abs(curr - prev) || min); + } + prev = curr; + }; + for(i = 0, ilen = values.length; i < ilen; ++i){ + curr = scale.getPixelForValue(values[i]); + updateMinAndPrev(); + } + prev = undefined; + for(i = 0, ilen = scale.ticks.length; i < ilen; ++i){ + curr = scale.getPixelForTick(i); + updateMinAndPrev(); + } + return min; +} + function computeFitCategoryTraits(index, ruler, options, stackCount) { + const thickness = options.barThickness; + let size, ratio; + if (helpers_dataset.isNullOrUndef(thickness)) { + size = ruler.min * options.categoryPercentage; + ratio = options.barPercentage; + } else { + size = thickness * stackCount; + ratio = 1; + } + return { + chunk: size / stackCount, + ratio, + start: ruler.pixels[index] - size / 2 + }; +} + function computeFlexCategoryTraits(index, ruler, options, stackCount) { + const pixels = ruler.pixels; + const curr = pixels[index]; + let prev = index > 0 ? pixels[index - 1] : null; + let next = index < pixels.length - 1 ? pixels[index + 1] : null; + const percent = options.categoryPercentage; + if (prev === null) { + prev = curr - (next === null ? ruler.end - ruler.start : next - curr); + } + if (next === null) { + next = curr + curr - prev; + } + const start = curr - (curr - Math.min(prev, next)) / 2 * percent; + const size = Math.abs(next - prev) / 2 * percent; + return { + chunk: size / stackCount, + ratio: options.barPercentage, + start + }; +} +function parseFloatBar(entry, item, vScale, i) { + const startValue = vScale.parse(entry[0], i); + const endValue = vScale.parse(entry[1], i); + const min = Math.min(startValue, endValue); + const max = Math.max(startValue, endValue); + let barStart = min; + let barEnd = max; + if (Math.abs(min) > Math.abs(max)) { + barStart = max; + barEnd = min; + } + item[vScale.axis] = barEnd; + item._custom = { + barStart, + barEnd, + start: startValue, + end: endValue, + min, + max + }; +} +function parseValue(entry, item, vScale, i) { + if (helpers_dataset.isArray(entry)) { + parseFloatBar(entry, item, vScale, i); + } else { + item[vScale.axis] = vScale.parse(entry, i); + } + return item; +} +function parseArrayOrPrimitive(meta, data, start, count) { + const iScale = meta.iScale; + const vScale = meta.vScale; + const labels = iScale.getLabels(); + const singleScale = iScale === vScale; + const parsed = []; + let i, ilen, item, entry; + for(i = start, ilen = start + count; i < ilen; ++i){ + entry = data[i]; + item = {}; + item[iScale.axis] = singleScale || iScale.parse(labels[i], i); + parsed.push(parseValue(entry, item, vScale, i)); + } + return parsed; +} +function isFloatBar(custom) { + return custom && custom.barStart !== undefined && custom.barEnd !== undefined; +} +function barSign(size, vScale, actualBase) { + if (size !== 0) { + return helpers_dataset.sign(size); + } + return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1); +} +function borderProps(properties) { + let reverse, start, end, top, bottom; + if (properties.horizontal) { + reverse = properties.base > properties.x; + start = 'left'; + end = 'right'; + } else { + reverse = properties.base < properties.y; + start = 'bottom'; + end = 'top'; + } + if (reverse) { + top = 'end'; + bottom = 'start'; + } else { + top = 'start'; + bottom = 'end'; + } + return { + start, + end, + reverse, + top, + bottom + }; +} +function setBorderSkipped(properties, options, stack, index) { + let edge = options.borderSkipped; + const res = {}; + if (!edge) { + properties.borderSkipped = res; + return; + } + if (edge === true) { + properties.borderSkipped = { + top: true, + right: true, + bottom: true, + left: true + }; + return; + } + const { start , end , reverse , top , bottom } = borderProps(properties); + if (edge === 'middle' && stack) { + properties.enableBorderRadius = true; + if ((stack._top || 0) === index) { + edge = top; + } else if ((stack._bottom || 0) === index) { + edge = bottom; + } else { + res[parseEdge(bottom, start, end, reverse)] = true; + edge = top; + } + } + res[parseEdge(edge, start, end, reverse)] = true; + properties.borderSkipped = res; +} +function parseEdge(edge, a, b, reverse) { + if (reverse) { + edge = swap(edge, a, b); + edge = startEnd(edge, b, a); + } else { + edge = startEnd(edge, a, b); + } + return edge; +} +function swap(orig, v1, v2) { + return orig === v1 ? v2 : orig === v2 ? v1 : orig; +} +function startEnd(v, start, end) { + return v === 'start' ? start : v === 'end' ? end : v; +} +function setInflateAmount(properties, { inflateAmount }, ratio) { + properties.inflateAmount = inflateAmount === 'auto' ? ratio === 1 ? 0.33 : 0 : inflateAmount; +} +class BarController extends DatasetController { + static id = 'bar'; + static defaults = { + datasetElementType: false, + dataElementType: 'bar', + categoryPercentage: 0.8, + barPercentage: 0.9, + grouped: true, + animations: { + numbers: { + type: 'number', + properties: [ + 'x', + 'y', + 'base', + 'width', + 'height' + ] + } + } + }; + static overrides = { + scales: { + _index_: { + type: 'category', + offset: true, + grid: { + offset: true + } + }, + _value_: { + type: 'linear', + beginAtZero: true + } + } + }; + parsePrimitiveData(meta, data, start, count) { + return parseArrayOrPrimitive(meta, data, start, count); + } + parseArrayData(meta, data, start, count) { + return parseArrayOrPrimitive(meta, data, start, count); + } + parseObjectData(meta, data, start, count) { + const { iScale , vScale } = meta; + const { xAxisKey ='x' , yAxisKey ='y' } = this._parsing; + const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey; + const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey; + const parsed = []; + let i, ilen, item, obj; + for(i = start, ilen = start + count; i < ilen; ++i){ + obj = data[i]; + item = {}; + item[iScale.axis] = iScale.parse(helpers_dataset.resolveObjectKey(obj, iAxisKey), i); + parsed.push(parseValue(helpers_dataset.resolveObjectKey(obj, vAxisKey), item, vScale, i)); + } + return parsed; + } + updateRangeFromParsed(range, scale, parsed, stack) { + super.updateRangeFromParsed(range, scale, parsed, stack); + const custom = parsed._custom; + if (custom && scale === this._cachedMeta.vScale) { + range.min = Math.min(range.min, custom.min); + range.max = Math.max(range.max, custom.max); + } + } + getMaxOverflow() { + return 0; + } + getLabelAndValue(index) { + const meta = this._cachedMeta; + const { iScale , vScale } = meta; + const parsed = this.getParsed(index); + const custom = parsed._custom; + const value = isFloatBar(custom) ? '[' + custom.start + ', ' + custom.end + ']' : '' + vScale.getLabelForValue(parsed[vScale.axis]); + return { + label: '' + iScale.getLabelForValue(parsed[iScale.axis]), + value + }; + } + initialize() { + this.enableOptionSharing = true; + super.initialize(); + const meta = this._cachedMeta; + meta.stack = this.getDataset().stack; + } + update(mode) { + const meta = this._cachedMeta; + this.updateElements(meta.data, 0, meta.data.length, mode); + } + updateElements(bars, start, count, mode) { + const reset = mode === 'reset'; + const { index , _cachedMeta: { vScale } } = this; + const base = vScale.getBasePixel(); + const horizontal = vScale.isHorizontal(); + const ruler = this._getRuler(); + const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode); + for(let i = start; i < start + count; i++){ + const parsed = this.getParsed(i); + const vpixels = reset || helpers_dataset.isNullOrUndef(parsed[vScale.axis]) ? { + base, + head: base + } : this._calculateBarValuePixels(i); + const ipixels = this._calculateBarIndexPixels(i, ruler); + const stack = (parsed._stacks || {})[vScale.axis]; + const properties = { + horizontal, + base: vpixels.base, + enableBorderRadius: !stack || isFloatBar(parsed._custom) || index === stack._top || index === stack._bottom, + x: horizontal ? vpixels.head : ipixels.center, + y: horizontal ? ipixels.center : vpixels.head, + height: horizontal ? ipixels.size : Math.abs(vpixels.size), + width: horizontal ? Math.abs(vpixels.size) : ipixels.size + }; + if (includeOptions) { + properties.options = sharedOptions || this.resolveDataElementOptions(i, bars[i].active ? 'active' : mode); + } + const options = properties.options || bars[i].options; + setBorderSkipped(properties, options, stack, index); + setInflateAmount(properties, options, ruler.ratio); + this.updateElement(bars[i], i, properties, mode); + } + } + _getStacks(last, dataIndex) { + const { iScale } = this._cachedMeta; + const metasets = iScale.getMatchingVisibleMetas(this._type).filter((meta)=>meta.controller.options.grouped); + const stacked = iScale.options.stacked; + const stacks = []; + const currentParsed = this._cachedMeta.controller.getParsed(dataIndex); + const iScaleValue = currentParsed && currentParsed[iScale.axis]; + const skipNull = (meta)=>{ + const parsed = meta._parsed.find((item)=>item[iScale.axis] === iScaleValue); + const val = parsed && parsed[meta.vScale.axis]; + if (helpers_dataset.isNullOrUndef(val) || isNaN(val)) { + return true; + } + }; + for (const meta of metasets){ + if (dataIndex !== undefined && skipNull(meta)) { + continue; + } + if (stacked === false || stacks.indexOf(meta.stack) === -1 || stacked === undefined && meta.stack === undefined) { + stacks.push(meta.stack); + } + if (meta.index === last) { + break; + } + } + if (!stacks.length) { + stacks.push(undefined); + } + return stacks; + } + _getStackCount(index) { + return this._getStacks(undefined, index).length; + } + _getAxisCount() { + return this._getAxis().length; + } + getFirstScaleIdForIndexAxis() { + const scales = this.chart.scales; + const indexScaleId = this.chart.options.indexAxis; + return Object.keys(scales).filter((key)=>scales[key].axis === indexScaleId).shift(); + } + _getAxis() { + const axis = {}; + const firstScaleAxisId = this.getFirstScaleIdForIndexAxis(); + for (const dataset of this.chart.data.datasets){ + axis[helpers_dataset.valueOrDefault(this.chart.options.indexAxis === 'x' ? dataset.xAxisID : dataset.yAxisID, firstScaleAxisId)] = true; + } + return Object.keys(axis); + } + _getStackIndex(datasetIndex, name, dataIndex) { + const stacks = this._getStacks(datasetIndex, dataIndex); + const index = name !== undefined ? stacks.indexOf(name) : -1; + return index === -1 ? stacks.length - 1 : index; + } + _getRuler() { + const opts = this.options; + const meta = this._cachedMeta; + const iScale = meta.iScale; + const pixels = []; + let i, ilen; + for(i = 0, ilen = meta.data.length; i < ilen; ++i){ + pixels.push(iScale.getPixelForValue(this.getParsed(i)[iScale.axis], i)); + } + const barThickness = opts.barThickness; + const min = barThickness || computeMinSampleSize(meta); + return { + min, + pixels, + start: iScale._startPixel, + end: iScale._endPixel, + stackCount: this._getStackCount(), + scale: iScale, + grouped: opts.grouped, + ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage + }; + } + _calculateBarValuePixels(index) { + const { _cachedMeta: { vScale , _stacked , index: datasetIndex } , options: { base: baseValue , minBarLength } } = this; + const actualBase = baseValue || 0; + const parsed = this.getParsed(index); + const custom = parsed._custom; + const floating = isFloatBar(custom); + let value = parsed[vScale.axis]; + let start = 0; + let length = _stacked ? this.applyStack(vScale, parsed, _stacked) : value; + let head, size; + if (length !== value) { + start = length - value; + length = value; + } + if (floating) { + value = custom.barStart; + length = custom.barEnd - custom.barStart; + if (value !== 0 && helpers_dataset.sign(value) !== helpers_dataset.sign(custom.barEnd)) { + start = 0; + } + start += value; + } + const startValue = !helpers_dataset.isNullOrUndef(baseValue) && !floating ? baseValue : start; + let base = vScale.getPixelForValue(startValue); + if (this.chart.getDataVisibility(index)) { + head = vScale.getPixelForValue(start + length); + } else { + head = base; + } + size = head - base; + if (Math.abs(size) < minBarLength) { + size = barSign(size, vScale, actualBase) * minBarLength; + if (value === actualBase) { + base -= size / 2; + } + const startPixel = vScale.getPixelForDecimal(0); + const endPixel = vScale.getPixelForDecimal(1); + const min = Math.min(startPixel, endPixel); + const max = Math.max(startPixel, endPixel); + base = Math.max(Math.min(base, max), min); + head = base + size; + if (_stacked && !floating) { + parsed._stacks[vScale.axis]._visualValues[datasetIndex] = vScale.getValueForPixel(head) - vScale.getValueForPixel(base); + } + } + if (base === vScale.getPixelForValue(actualBase)) { + const halfGrid = helpers_dataset.sign(size) * vScale.getLineWidthForValue(actualBase) / 2; + base += halfGrid; + size -= halfGrid; + } + return { + size, + base, + head, + center: head + size / 2 + }; + } + _calculateBarIndexPixels(index, ruler) { + const scale = ruler.scale; + const options = this.options; + const skipNull = options.skipNull; + const maxBarThickness = helpers_dataset.valueOrDefault(options.maxBarThickness, Infinity); + let center, size; + const axisCount = this._getAxisCount(); + if (ruler.grouped) { + const stackCount = skipNull ? this._getStackCount(index) : ruler.stackCount; + const range = options.barThickness === 'flex' ? computeFlexCategoryTraits(index, ruler, options, stackCount * axisCount) : computeFitCategoryTraits(index, ruler, options, stackCount * axisCount); + const axisID = this.chart.options.indexAxis === 'x' ? this.getDataset().xAxisID : this.getDataset().yAxisID; + const axisNumber = this._getAxis().indexOf(helpers_dataset.valueOrDefault(axisID, this.getFirstScaleIdForIndexAxis())); + const stackIndex = this._getStackIndex(this.index, this._cachedMeta.stack, skipNull ? index : undefined) + axisNumber; + center = range.start + range.chunk * stackIndex + range.chunk / 2; + size = Math.min(maxBarThickness, range.chunk * range.ratio); + } else { + center = scale.getPixelForValue(this.getParsed(index)[scale.axis], index); + size = Math.min(maxBarThickness, ruler.min * ruler.ratio); + } + return { + base: center - size / 2, + head: center + size / 2, + center, + size + }; + } + draw() { + const meta = this._cachedMeta; + const vScale = meta.vScale; + const rects = meta.data; + const ilen = rects.length; + let i = 0; + for(; i < ilen; ++i){ + if (this.getParsed(i)[vScale.axis] !== null && !rects[i].hidden) { + rects[i].draw(this._ctx); + } + } + } +} + +class BubbleController extends DatasetController { + static id = 'bubble'; + static defaults = { + datasetElementType: false, + dataElementType: 'point', + animations: { + numbers: { + type: 'number', + properties: [ + 'x', + 'y', + 'borderWidth', + 'radius' + ] + } + } + }; + static overrides = { + scales: { + x: { + type: 'linear' + }, + y: { + type: 'linear' + } + } + }; + initialize() { + this.enableOptionSharing = true; + super.initialize(); + } + parsePrimitiveData(meta, data, start, count) { + const parsed = super.parsePrimitiveData(meta, data, start, count); + for(let i = 0; i < parsed.length; i++){ + parsed[i]._custom = this.resolveDataElementOptions(i + start).radius; + } + return parsed; + } + parseArrayData(meta, data, start, count) { + const parsed = super.parseArrayData(meta, data, start, count); + for(let i = 0; i < parsed.length; i++){ + const item = data[start + i]; + parsed[i]._custom = helpers_dataset.valueOrDefault(item[2], this.resolveDataElementOptions(i + start).radius); + } + return parsed; + } + parseObjectData(meta, data, start, count) { + const parsed = super.parseObjectData(meta, data, start, count); + for(let i = 0; i < parsed.length; i++){ + const item = data[start + i]; + parsed[i]._custom = helpers_dataset.valueOrDefault(item && item.r && +item.r, this.resolveDataElementOptions(i + start).radius); + } + return parsed; + } + getMaxOverflow() { + const data = this._cachedMeta.data; + let max = 0; + for(let i = data.length - 1; i >= 0; --i){ + max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2); + } + return max > 0 && max; + } + getLabelAndValue(index) { + const meta = this._cachedMeta; + const labels = this.chart.data.labels || []; + const { xScale , yScale } = meta; + const parsed = this.getParsed(index); + const x = xScale.getLabelForValue(parsed.x); + const y = yScale.getLabelForValue(parsed.y); + const r = parsed._custom; + return { + label: labels[index] || '', + value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')' + }; + } + update(mode) { + const points = this._cachedMeta.data; + this.updateElements(points, 0, points.length, mode); + } + updateElements(points, start, count, mode) { + const reset = mode === 'reset'; + const { iScale , vScale } = this._cachedMeta; + const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode); + const iAxis = iScale.axis; + const vAxis = vScale.axis; + for(let i = start; i < start + count; i++){ + const point = points[i]; + const parsed = !reset && this.getParsed(i); + const properties = {}; + const iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]); + const vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]); + properties.skip = isNaN(iPixel) || isNaN(vPixel); + if (includeOptions) { + properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode); + if (reset) { + properties.options.radius = 0; + } + } + this.updateElement(point, i, properties, mode); + } + } + resolveDataElementOptions(index, mode) { + const parsed = this.getParsed(index); + let values = super.resolveDataElementOptions(index, mode); + if (values.$shared) { + values = Object.assign({}, values, { + $shared: false + }); + } + const radius = values.radius; + if (mode !== 'active') { + values.radius = 0; + } + values.radius += helpers_dataset.valueOrDefault(parsed && parsed._custom, radius); + return values; + } +} + +function getRatioAndOffset(rotation, circumference, cutout) { + let ratioX = 1; + let ratioY = 1; + let offsetX = 0; + let offsetY = 0; + if (circumference < helpers_dataset.TAU) { + const startAngle = rotation; + const endAngle = startAngle + circumference; + const startX = Math.cos(startAngle); + const startY = Math.sin(startAngle); + const endX = Math.cos(endAngle); + const endY = Math.sin(endAngle); + const calcMax = (angle, a, b)=>helpers_dataset._angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout); + const calcMin = (angle, a, b)=>helpers_dataset._angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout); + const maxX = calcMax(0, startX, endX); + const maxY = calcMax(helpers_dataset.HALF_PI, startY, endY); + const minX = calcMin(helpers_dataset.PI, startX, endX); + const minY = calcMin(helpers_dataset.PI + helpers_dataset.HALF_PI, startY, endY); + ratioX = (maxX - minX) / 2; + ratioY = (maxY - minY) / 2; + offsetX = -(maxX + minX) / 2; + offsetY = -(maxY + minY) / 2; + } + return { + ratioX, + ratioY, + offsetX, + offsetY + }; +} +class DoughnutController extends DatasetController { + static id = 'doughnut'; + static defaults = { + datasetElementType: false, + dataElementType: 'arc', + animation: { + animateRotate: true, + animateScale: false + }, + animations: { + numbers: { + type: 'number', + properties: [ + 'circumference', + 'endAngle', + 'innerRadius', + 'outerRadius', + 'startAngle', + 'x', + 'y', + 'offset', + 'borderWidth', + 'spacing' + ] + } + }, + cutout: '50%', + rotation: 0, + circumference: 360, + radius: '100%', + spacing: 0, + indexAxis: 'r' + }; + static descriptors = { + _scriptable: (name)=>name !== 'spacing', + _indexable: (name)=>name !== 'spacing' && !name.startsWith('borderDash') && !name.startsWith('hoverBorderDash') + }; + static overrides = { + aspectRatio: 1, + plugins: { + legend: { + labels: { + generateLabels (chart) { + const data = chart.data; + if (data.labels.length && data.datasets.length) { + const { labels: { pointStyle , color } } = chart.legend.options; + return data.labels.map((label, i)=>{ + const meta = chart.getDatasetMeta(0); + const style = meta.controller.getStyle(i); + return { + text: label, + fillStyle: style.backgroundColor, + strokeStyle: style.borderColor, + fontColor: color, + lineWidth: style.borderWidth, + pointStyle: pointStyle, + hidden: !chart.getDataVisibility(i), + index: i + }; + }); + } + return []; + } + }, + onClick (e, legendItem, legend) { + legend.chart.toggleDataVisibility(legendItem.index); + legend.chart.update(); + } + } + } + }; + constructor(chart, datasetIndex){ + super(chart, datasetIndex); + this.enableOptionSharing = true; + this.innerRadius = undefined; + this.outerRadius = undefined; + this.offsetX = undefined; + this.offsetY = undefined; + } + linkScales() {} + parse(start, count) { + const data = this.getDataset().data; + const meta = this._cachedMeta; + if (this._parsing === false) { + meta._parsed = data; + } else { + let getter = (i)=>+data[i]; + if (helpers_dataset.isObject(data[start])) { + const { key ='value' } = this._parsing; + getter = (i)=>+helpers_dataset.resolveObjectKey(data[i], key); + } + let i, ilen; + for(i = start, ilen = start + count; i < ilen; ++i){ + meta._parsed[i] = getter(i); + } + } + } + _getRotation() { + return helpers_dataset.toRadians(this.options.rotation - 90); + } + _getCircumference() { + return helpers_dataset.toRadians(this.options.circumference); + } + _getRotationExtents() { + let min = helpers_dataset.TAU; + let max = -helpers_dataset.TAU; + for(let i = 0; i < this.chart.data.datasets.length; ++i){ + if (this.chart.isDatasetVisible(i) && this.chart.getDatasetMeta(i).type === this._type) { + const controller = this.chart.getDatasetMeta(i).controller; + const rotation = controller._getRotation(); + const circumference = controller._getCircumference(); + min = Math.min(min, rotation); + max = Math.max(max, rotation + circumference); + } + } + return { + rotation: min, + circumference: max - min + }; + } + update(mode) { + const chart = this.chart; + const { chartArea } = chart; + const meta = this._cachedMeta; + const arcs = meta.data; + const spacing = this.getMaxBorderWidth() + this.getMaxOffset(arcs) + this.options.spacing; + const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0); + const cutout = Math.min(helpers_dataset.toPercentage(this.options.cutout, maxSize), 1); + const chartWeight = this._getRingWeight(this.index); + const { circumference , rotation } = this._getRotationExtents(); + const { ratioX , ratioY , offsetX , offsetY } = getRatioAndOffset(rotation, circumference, cutout); + const maxWidth = (chartArea.width - spacing) / ratioX; + const maxHeight = (chartArea.height - spacing) / ratioY; + const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0); + const outerRadius = helpers_dataset.toDimension(this.options.radius, maxRadius); + const innerRadius = Math.max(outerRadius * cutout, 0); + const radiusLength = (outerRadius - innerRadius) / this._getVisibleDatasetWeightTotal(); + this.offsetX = offsetX * outerRadius; + this.offsetY = offsetY * outerRadius; + meta.total = this.calculateTotal(); + this.outerRadius = outerRadius - radiusLength * this._getRingWeightOffset(this.index); + this.innerRadius = Math.max(this.outerRadius - radiusLength * chartWeight, 0); + this.updateElements(arcs, 0, arcs.length, mode); + } + _circumference(i, reset) { + const opts = this.options; + const meta = this._cachedMeta; + const circumference = this._getCircumference(); + if (reset && opts.animation.animateRotate || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) { + return 0; + } + return this.calculateCircumference(meta._parsed[i] * circumference / helpers_dataset.TAU); + } + updateElements(arcs, start, count, mode) { + const reset = mode === 'reset'; + const chart = this.chart; + const chartArea = chart.chartArea; + const opts = chart.options; + const animationOpts = opts.animation; + const centerX = (chartArea.left + chartArea.right) / 2; + const centerY = (chartArea.top + chartArea.bottom) / 2; + const animateScale = reset && animationOpts.animateScale; + const innerRadius = animateScale ? 0 : this.innerRadius; + const outerRadius = animateScale ? 0 : this.outerRadius; + const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode); + let startAngle = this._getRotation(); + let i; + for(i = 0; i < start; ++i){ + startAngle += this._circumference(i, reset); + } + for(i = start; i < start + count; ++i){ + const circumference = this._circumference(i, reset); + const arc = arcs[i]; + const properties = { + x: centerX + this.offsetX, + y: centerY + this.offsetY, + startAngle, + endAngle: startAngle + circumference, + circumference, + outerRadius, + innerRadius + }; + if (includeOptions) { + properties.options = sharedOptions || this.resolveDataElementOptions(i, arc.active ? 'active' : mode); + } + startAngle += circumference; + this.updateElement(arc, i, properties, mode); + } + } + calculateTotal() { + const meta = this._cachedMeta; + const metaData = meta.data; + let total = 0; + let i; + for(i = 0; i < metaData.length; i++){ + const value = meta._parsed[i]; + if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) { + total += Math.abs(value); + } + } + return total; + } + calculateCircumference(value) { + const total = this._cachedMeta.total; + if (total > 0 && !isNaN(value)) { + return helpers_dataset.TAU * (Math.abs(value) / total); + } + return 0; + } + getLabelAndValue(index) { + const meta = this._cachedMeta; + const chart = this.chart; + const labels = chart.data.labels || []; + const value = helpers_dataset.formatNumber(meta._parsed[index], chart.options.locale); + return { + label: labels[index] || '', + value + }; + } + getMaxBorderWidth(arcs) { + let max = 0; + const chart = this.chart; + let i, ilen, meta, controller, options; + if (!arcs) { + for(i = 0, ilen = chart.data.datasets.length; i < ilen; ++i){ + if (chart.isDatasetVisible(i)) { + meta = chart.getDatasetMeta(i); + arcs = meta.data; + controller = meta.controller; + break; + } + } + } + if (!arcs) { + return 0; + } + for(i = 0, ilen = arcs.length; i < ilen; ++i){ + options = controller.resolveDataElementOptions(i); + if (options.borderAlign !== 'inner') { + max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0); + } + } + return max; + } + getMaxOffset(arcs) { + let max = 0; + for(let i = 0, ilen = arcs.length; i < ilen; ++i){ + const options = this.resolveDataElementOptions(i); + max = Math.max(max, options.offset || 0, options.hoverOffset || 0); + } + return max; + } + _getRingWeightOffset(datasetIndex) { + let ringWeightOffset = 0; + for(let i = 0; i < datasetIndex; ++i){ + if (this.chart.isDatasetVisible(i)) { + ringWeightOffset += this._getRingWeight(i); + } + } + return ringWeightOffset; + } + _getRingWeight(datasetIndex) { + return Math.max(helpers_dataset.valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0); + } + _getVisibleDatasetWeightTotal() { + return this._getRingWeightOffset(this.chart.data.datasets.length) || 1; + } +} + +class LineController extends DatasetController { + static id = 'line'; + static defaults = { + datasetElementType: 'line', + dataElementType: 'point', + showLine: true, + spanGaps: false + }; + static overrides = { + scales: { + _index_: { + type: 'category' + }, + _value_: { + type: 'linear' + } + } + }; + initialize() { + this.enableOptionSharing = true; + this.supportsDecimation = true; + super.initialize(); + } + update(mode) { + const meta = this._cachedMeta; + const { dataset: line , data: points = [] , _dataset } = meta; + const animationsDisabled = this.chart._animationsDisabled; + let { start , count } = helpers_dataset._getStartAndCountOfVisiblePoints(meta, points, animationsDisabled); + this._drawStart = start; + this._drawCount = count; + if (helpers_dataset._scaleRangesChanged(meta)) { + start = 0; + count = points.length; + } + line._chart = this.chart; + line._datasetIndex = this.index; + line._decimated = !!_dataset._decimated; + line.points = points; + const options = this.resolveDatasetElementOptions(mode); + if (!this.options.showLine) { + options.borderWidth = 0; + } + options.segment = this.options.segment; + this.updateElement(line, undefined, { + animated: !animationsDisabled, + options + }, mode); + this.updateElements(points, start, count, mode); + } + updateElements(points, start, count, mode) { + const reset = mode === 'reset'; + const { iScale , vScale , _stacked , _dataset } = this._cachedMeta; + const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode); + const iAxis = iScale.axis; + const vAxis = vScale.axis; + const { spanGaps , segment } = this.options; + const maxGapLength = helpers_dataset.isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY; + const directUpdate = this.chart._animationsDisabled || reset || mode === 'none'; + const end = start + count; + const pointsCount = points.length; + let prevParsed = start > 0 && this.getParsed(start - 1); + for(let i = 0; i < pointsCount; ++i){ + const point = points[i]; + const properties = directUpdate ? point : {}; + if (i < start || i >= end) { + properties.skip = true; + continue; + } + const parsed = this.getParsed(i); + const nullData = helpers_dataset.isNullOrUndef(parsed[vAxis]); + const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i); + const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i); + properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData; + properties.stop = i > 0 && Math.abs(parsed[iAxis] - prevParsed[iAxis]) > maxGapLength; + if (segment) { + properties.parsed = parsed; + properties.raw = _dataset.data[i]; + } + if (includeOptions) { + properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode); + } + if (!directUpdate) { + this.updateElement(point, i, properties, mode); + } + prevParsed = parsed; + } + } + getMaxOverflow() { + const meta = this._cachedMeta; + const dataset = meta.dataset; + const border = dataset.options && dataset.options.borderWidth || 0; + const data = meta.data || []; + if (!data.length) { + return border; + } + const firstPoint = data[0].size(this.resolveDataElementOptions(0)); + const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1)); + return Math.max(border, firstPoint, lastPoint) / 2; + } + draw() { + const meta = this._cachedMeta; + meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis); + super.draw(); + } +} + +class PolarAreaController extends DatasetController { + static id = 'polarArea'; + static defaults = { + dataElementType: 'arc', + animation: { + animateRotate: true, + animateScale: true + }, + animations: { + numbers: { + type: 'number', + properties: [ + 'x', + 'y', + 'startAngle', + 'endAngle', + 'innerRadius', + 'outerRadius' + ] + } + }, + indexAxis: 'r', + startAngle: 0 + }; + static overrides = { + aspectRatio: 1, + plugins: { + legend: { + labels: { + generateLabels (chart) { + const data = chart.data; + if (data.labels.length && data.datasets.length) { + const { labels: { pointStyle , color } } = chart.legend.options; + return data.labels.map((label, i)=>{ + const meta = chart.getDatasetMeta(0); + const style = meta.controller.getStyle(i); + return { + text: label, + fillStyle: style.backgroundColor, + strokeStyle: style.borderColor, + fontColor: color, + lineWidth: style.borderWidth, + pointStyle: pointStyle, + hidden: !chart.getDataVisibility(i), + index: i + }; + }); + } + return []; + } + }, + onClick (e, legendItem, legend) { + legend.chart.toggleDataVisibility(legendItem.index); + legend.chart.update(); + } + } + }, + scales: { + r: { + type: 'radialLinear', + angleLines: { + display: false + }, + beginAtZero: true, + grid: { + circular: true + }, + pointLabels: { + display: false + }, + startAngle: 0 + } + } + }; + constructor(chart, datasetIndex){ + super(chart, datasetIndex); + this.innerRadius = undefined; + this.outerRadius = undefined; + } + getLabelAndValue(index) { + const meta = this._cachedMeta; + const chart = this.chart; + const labels = chart.data.labels || []; + const value = helpers_dataset.formatNumber(meta._parsed[index].r, chart.options.locale); + return { + label: labels[index] || '', + value + }; + } + parseObjectData(meta, data, start, count) { + return helpers_dataset._parseObjectDataRadialScale.bind(this)(meta, data, start, count); + } + update(mode) { + const arcs = this._cachedMeta.data; + this._updateRadius(); + this.updateElements(arcs, 0, arcs.length, mode); + } + getMinMax() { + const meta = this._cachedMeta; + const range = { + min: Number.POSITIVE_INFINITY, + max: Number.NEGATIVE_INFINITY + }; + meta.data.forEach((element, index)=>{ + const parsed = this.getParsed(index).r; + if (!isNaN(parsed) && this.chart.getDataVisibility(index)) { + if (parsed < range.min) { + range.min = parsed; + } + if (parsed > range.max) { + range.max = parsed; + } + } + }); + return range; + } + _updateRadius() { + const chart = this.chart; + const chartArea = chart.chartArea; + const opts = chart.options; + const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top); + const outerRadius = Math.max(minSize / 2, 0); + const innerRadius = Math.max(opts.cutoutPercentage ? outerRadius / 100 * opts.cutoutPercentage : 1, 0); + const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount(); + this.outerRadius = outerRadius - radiusLength * this.index; + this.innerRadius = this.outerRadius - radiusLength; + } + updateElements(arcs, start, count, mode) { + const reset = mode === 'reset'; + const chart = this.chart; + const opts = chart.options; + const animationOpts = opts.animation; + const scale = this._cachedMeta.rScale; + const centerX = scale.xCenter; + const centerY = scale.yCenter; + const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * helpers_dataset.PI; + let angle = datasetStartAngle; + let i; + const defaultAngle = 360 / this.countVisibleElements(); + for(i = 0; i < start; ++i){ + angle += this._computeAngle(i, mode, defaultAngle); + } + for(i = start; i < start + count; i++){ + const arc = arcs[i]; + let startAngle = angle; + let endAngle = angle + this._computeAngle(i, mode, defaultAngle); + let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(this.getParsed(i).r) : 0; + angle = endAngle; + if (reset) { + if (animationOpts.animateScale) { + outerRadius = 0; + } + if (animationOpts.animateRotate) { + startAngle = endAngle = datasetStartAngle; + } + } + const properties = { + x: centerX, + y: centerY, + innerRadius: 0, + outerRadius, + startAngle, + endAngle, + options: this.resolveDataElementOptions(i, arc.active ? 'active' : mode) + }; + this.updateElement(arc, i, properties, mode); + } + } + countVisibleElements() { + const meta = this._cachedMeta; + let count = 0; + meta.data.forEach((element, index)=>{ + if (!isNaN(this.getParsed(index).r) && this.chart.getDataVisibility(index)) { + count++; + } + }); + return count; + } + _computeAngle(index, mode, defaultAngle) { + return this.chart.getDataVisibility(index) ? helpers_dataset.toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle) : 0; + } +} + +class PieController extends DoughnutController { + static id = 'pie'; + static defaults = { + cutout: 0, + rotation: 0, + circumference: 360, + radius: '100%' + }; +} + +class RadarController extends DatasetController { + static id = 'radar'; + static defaults = { + datasetElementType: 'line', + dataElementType: 'point', + indexAxis: 'r', + showLine: true, + elements: { + line: { + fill: 'start' + } + } + }; + static overrides = { + aspectRatio: 1, + scales: { + r: { + type: 'radialLinear' + } + } + }; + getLabelAndValue(index) { + const vScale = this._cachedMeta.vScale; + const parsed = this.getParsed(index); + return { + label: vScale.getLabels()[index], + value: '' + vScale.getLabelForValue(parsed[vScale.axis]) + }; + } + parseObjectData(meta, data, start, count) { + return helpers_dataset._parseObjectDataRadialScale.bind(this)(meta, data, start, count); + } + update(mode) { + const meta = this._cachedMeta; + const line = meta.dataset; + const points = meta.data || []; + const labels = meta.iScale.getLabels(); + line.points = points; + if (mode !== 'resize') { + const options = this.resolveDatasetElementOptions(mode); + if (!this.options.showLine) { + options.borderWidth = 0; + } + const properties = { + _loop: true, + _fullLoop: labels.length === points.length, + options + }; + this.updateElement(line, undefined, properties, mode); + } + this.updateElements(points, 0, points.length, mode); + } + updateElements(points, start, count, mode) { + const scale = this._cachedMeta.rScale; + const reset = mode === 'reset'; + for(let i = start; i < start + count; i++){ + const point = points[i]; + const options = this.resolveDataElementOptions(i, point.active ? 'active' : mode); + const pointPosition = scale.getPointPositionForValue(i, this.getParsed(i).r); + const x = reset ? scale.xCenter : pointPosition.x; + const y = reset ? scale.yCenter : pointPosition.y; + const properties = { + x, + y, + angle: pointPosition.angle, + skip: isNaN(x) || isNaN(y), + options + }; + this.updateElement(point, i, properties, mode); + } + } +} + +class ScatterController extends DatasetController { + static id = 'scatter'; + static defaults = { + datasetElementType: false, + dataElementType: 'point', + showLine: false, + fill: false + }; + static overrides = { + interaction: { + mode: 'point' + }, + scales: { + x: { + type: 'linear' + }, + y: { + type: 'linear' + } + } + }; + getLabelAndValue(index) { + const meta = this._cachedMeta; + const labels = this.chart.data.labels || []; + const { xScale , yScale } = meta; + const parsed = this.getParsed(index); + const x = xScale.getLabelForValue(parsed.x); + const y = yScale.getLabelForValue(parsed.y); + return { + label: labels[index] || '', + value: '(' + x + ', ' + y + ')' + }; + } + update(mode) { + const meta = this._cachedMeta; + const { data: points = [] } = meta; + const animationsDisabled = this.chart._animationsDisabled; + let { start , count } = helpers_dataset._getStartAndCountOfVisiblePoints(meta, points, animationsDisabled); + this._drawStart = start; + this._drawCount = count; + if (helpers_dataset._scaleRangesChanged(meta)) { + start = 0; + count = points.length; + } + if (this.options.showLine) { + if (!this.datasetElementType) { + this.addElements(); + } + const { dataset: line , _dataset } = meta; + line._chart = this.chart; + line._datasetIndex = this.index; + line._decimated = !!_dataset._decimated; + line.points = points; + const options = this.resolveDatasetElementOptions(mode); + options.segment = this.options.segment; + this.updateElement(line, undefined, { + animated: !animationsDisabled, + options + }, mode); + } else if (this.datasetElementType) { + delete meta.dataset; + this.datasetElementType = false; + } + this.updateElements(points, start, count, mode); + } + addElements() { + const { showLine } = this.options; + if (!this.datasetElementType && showLine) { + this.datasetElementType = this.chart.registry.getElement('line'); + } + super.addElements(); + } + updateElements(points, start, count, mode) { + const reset = mode === 'reset'; + const { iScale , vScale , _stacked , _dataset } = this._cachedMeta; + const firstOpts = this.resolveDataElementOptions(start, mode); + const sharedOptions = this.getSharedOptions(firstOpts); + const includeOptions = this.includeOptions(mode, sharedOptions); + const iAxis = iScale.axis; + const vAxis = vScale.axis; + const { spanGaps , segment } = this.options; + const maxGapLength = helpers_dataset.isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY; + const directUpdate = this.chart._animationsDisabled || reset || mode === 'none'; + let prevParsed = start > 0 && this.getParsed(start - 1); + for(let i = start; i < start + count; ++i){ + const point = points[i]; + const parsed = this.getParsed(i); + const properties = directUpdate ? point : {}; + const nullData = helpers_dataset.isNullOrUndef(parsed[vAxis]); + const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i); + const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i); + properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData; + properties.stop = i > 0 && Math.abs(parsed[iAxis] - prevParsed[iAxis]) > maxGapLength; + if (segment) { + properties.parsed = parsed; + properties.raw = _dataset.data[i]; + } + if (includeOptions) { + properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode); + } + if (!directUpdate) { + this.updateElement(point, i, properties, mode); + } + prevParsed = parsed; + } + this.updateSharedOptions(sharedOptions, mode, firstOpts); + } + getMaxOverflow() { + const meta = this._cachedMeta; + const data = meta.data || []; + if (!this.options.showLine) { + let max = 0; + for(let i = data.length - 1; i >= 0; --i){ + max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2); + } + return max > 0 && max; + } + const dataset = meta.dataset; + const border = dataset.options && dataset.options.borderWidth || 0; + if (!data.length) { + return border; + } + const firstPoint = data[0].size(this.resolveDataElementOptions(0)); + const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1)); + return Math.max(border, firstPoint, lastPoint) / 2; + } +} + +var controllers = /*#__PURE__*/Object.freeze({ +__proto__: null, +BarController: BarController, +BubbleController: BubbleController, +DoughnutController: DoughnutController, +LineController: LineController, +PieController: PieController, +PolarAreaController: PolarAreaController, +RadarController: RadarController, +ScatterController: ScatterController +}); + +/** + * @namespace Chart._adapters + * @since 2.8.0 + * @private + */ function abstract() { + throw new Error('This method is not implemented: Check that a complete date adapter is provided.'); +} +/** + * Date adapter (current used by the time scale) + * @namespace Chart._adapters._date + * @memberof Chart._adapters + * @private + */ class DateAdapterBase { + /** + * Override default date adapter methods. + * Accepts type parameter to define options type. + * @example + * Chart._adapters._date.override<{myAdapterOption: string}>({ + * init() { + * console.log(this.options.myAdapterOption); + * } + * }) + */ static override(members) { + Object.assign(DateAdapterBase.prototype, members); + } + options; + constructor(options){ + this.options = options || {}; + } + // eslint-disable-next-line @typescript-eslint/no-empty-function + init() {} + formats() { + return abstract(); + } + parse() { + return abstract(); + } + format() { + return abstract(); + } + add() { + return abstract(); + } + diff() { + return abstract(); + } + startOf() { + return abstract(); + } + endOf() { + return abstract(); + } +} +var adapters = { + _date: DateAdapterBase +}; + +function binarySearch(metaset, axis, value, intersect) { + const { controller , data , _sorted } = metaset; + const iScale = controller._cachedMeta.iScale; + const spanGaps = metaset.dataset ? metaset.dataset.options ? metaset.dataset.options.spanGaps : null : null; + if (iScale && axis === iScale.axis && axis !== 'r' && _sorted && data.length) { + const lookupMethod = iScale._reversePixels ? helpers_dataset._rlookupByKey : helpers_dataset._lookupByKey; + if (!intersect) { + const result = lookupMethod(data, axis, value); + if (spanGaps) { + const { vScale } = controller._cachedMeta; + const { _parsed } = metaset; + const distanceToDefinedLo = _parsed.slice(0, result.lo + 1).reverse().findIndex((point)=>!helpers_dataset.isNullOrUndef(point[vScale.axis])); + result.lo -= Math.max(0, distanceToDefinedLo); + const distanceToDefinedHi = _parsed.slice(result.hi).findIndex((point)=>!helpers_dataset.isNullOrUndef(point[vScale.axis])); + result.hi += Math.max(0, distanceToDefinedHi); + } + return result; + } else if (controller._sharedOptions) { + const el = data[0]; + const range = typeof el.getRange === 'function' && el.getRange(axis); + if (range) { + const start = lookupMethod(data, axis, value - range); + const end = lookupMethod(data, axis, value + range); + return { + lo: start.lo, + hi: end.hi + }; + } + } + } + return { + lo: 0, + hi: data.length - 1 + }; +} + function evaluateInteractionItems(chart, axis, position, handler, intersect) { + const metasets = chart.getSortedVisibleDatasetMetas(); + const value = position[axis]; + for(let i = 0, ilen = metasets.length; i < ilen; ++i){ + const { index , data } = metasets[i]; + const { lo , hi } = binarySearch(metasets[i], axis, value, intersect); + for(let j = lo; j <= hi; ++j){ + const element = data[j]; + if (!element.skip) { + handler(element, index, j); + } + } + } +} + function getDistanceMetricForAxis(axis) { + const useX = axis.indexOf('x') !== -1; + const useY = axis.indexOf('y') !== -1; + return function(pt1, pt2) { + const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0; + const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0; + return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)); + }; +} + function getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) { + const items = []; + if (!includeInvisible && !chart.isPointInArea(position)) { + return items; + } + const evaluationFunc = function(element, datasetIndex, index) { + if (!includeInvisible && !helpers_dataset._isPointInArea(element, chart.chartArea, 0)) { + return; + } + if (element.inRange(position.x, position.y, useFinalPosition)) { + items.push({ + element, + datasetIndex, + index + }); + } + }; + evaluateInteractionItems(chart, axis, position, evaluationFunc, true); + return items; +} + function getNearestRadialItems(chart, position, axis, useFinalPosition) { + let items = []; + function evaluationFunc(element, datasetIndex, index) { + const { startAngle , endAngle } = element.getProps([ + 'startAngle', + 'endAngle' + ], useFinalPosition); + const { angle } = helpers_dataset.getAngleFromPoint(element, { + x: position.x, + y: position.y + }); + if (helpers_dataset._angleBetween(angle, startAngle, endAngle)) { + items.push({ + element, + datasetIndex, + index + }); + } + } + evaluateInteractionItems(chart, axis, position, evaluationFunc); + return items; +} + function getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) { + let items = []; + const distanceMetric = getDistanceMetricForAxis(axis); + let minDistance = Number.POSITIVE_INFINITY; + function evaluationFunc(element, datasetIndex, index) { + const inRange = element.inRange(position.x, position.y, useFinalPosition); + if (intersect && !inRange) { + return; + } + const center = element.getCenterPoint(useFinalPosition); + const pointInArea = !!includeInvisible || chart.isPointInArea(center); + if (!pointInArea && !inRange) { + return; + } + const distance = distanceMetric(position, center); + if (distance < minDistance) { + items = [ + { + element, + datasetIndex, + index + } + ]; + minDistance = distance; + } else if (distance === minDistance) { + items.push({ + element, + datasetIndex, + index + }); + } + } + evaluateInteractionItems(chart, axis, position, evaluationFunc); + return items; +} + function getNearestItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) { + if (!includeInvisible && !chart.isPointInArea(position)) { + return []; + } + return axis === 'r' && !intersect ? getNearestRadialItems(chart, position, axis, useFinalPosition) : getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible); +} + function getAxisItems(chart, position, axis, intersect, useFinalPosition) { + const items = []; + const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange'; + let intersectsItem = false; + evaluateInteractionItems(chart, axis, position, (element, datasetIndex, index)=>{ + if (element[rangeMethod] && element[rangeMethod](position[axis], useFinalPosition)) { + items.push({ + element, + datasetIndex, + index + }); + intersectsItem = intersectsItem || element.inRange(position.x, position.y, useFinalPosition); + } + }); + if (intersect && !intersectsItem) { + return []; + } + return items; +} + var Interaction = { + evaluateInteractionItems, + modes: { + index (chart, e, options, useFinalPosition) { + const position = helpers_dataset.getRelativePosition(e, chart); + const axis = options.axis || 'x'; + const includeInvisible = options.includeInvisible || false; + const items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible); + const elements = []; + if (!items.length) { + return []; + } + chart.getSortedVisibleDatasetMetas().forEach((meta)=>{ + const index = items[0].index; + const element = meta.data[index]; + if (element && !element.skip) { + elements.push({ + element, + datasetIndex: meta.index, + index + }); + } + }); + return elements; + }, + dataset (chart, e, options, useFinalPosition) { + const position = helpers_dataset.getRelativePosition(e, chart); + const axis = options.axis || 'xy'; + const includeInvisible = options.includeInvisible || false; + let items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible); + if (items.length > 0) { + const datasetIndex = items[0].datasetIndex; + const data = chart.getDatasetMeta(datasetIndex).data; + items = []; + for(let i = 0; i < data.length; ++i){ + items.push({ + element: data[i], + datasetIndex, + index: i + }); + } + } + return items; + }, + point (chart, e, options, useFinalPosition) { + const position = helpers_dataset.getRelativePosition(e, chart); + const axis = options.axis || 'xy'; + const includeInvisible = options.includeInvisible || false; + return getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible); + }, + nearest (chart, e, options, useFinalPosition) { + const position = helpers_dataset.getRelativePosition(e, chart); + const axis = options.axis || 'xy'; + const includeInvisible = options.includeInvisible || false; + return getNearestItems(chart, position, axis, options.intersect, useFinalPosition, includeInvisible); + }, + x (chart, e, options, useFinalPosition) { + const position = helpers_dataset.getRelativePosition(e, chart); + return getAxisItems(chart, position, 'x', options.intersect, useFinalPosition); + }, + y (chart, e, options, useFinalPosition) { + const position = helpers_dataset.getRelativePosition(e, chart); + return getAxisItems(chart, position, 'y', options.intersect, useFinalPosition); + } + } +}; + +const STATIC_POSITIONS = [ + 'left', + 'top', + 'right', + 'bottom' +]; +function filterByPosition(array, position) { + return array.filter((v)=>v.pos === position); +} +function filterDynamicPositionByAxis(array, axis) { + return array.filter((v)=>STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis); +} +function sortByWeight(array, reverse) { + return array.sort((a, b)=>{ + const v0 = reverse ? b : a; + const v1 = reverse ? a : b; + return v0.weight === v1.weight ? v0.index - v1.index : v0.weight - v1.weight; + }); +} +function wrapBoxes(boxes) { + const layoutBoxes = []; + let i, ilen, box, pos, stack, stackWeight; + for(i = 0, ilen = (boxes || []).length; i < ilen; ++i){ + box = boxes[i]; + ({ position: pos , options: { stack , stackWeight =1 } } = box); + layoutBoxes.push({ + index: i, + box, + pos, + horizontal: box.isHorizontal(), + weight: box.weight, + stack: stack && pos + stack, + stackWeight + }); + } + return layoutBoxes; +} +function buildStacks(layouts) { + const stacks = {}; + for (const wrap of layouts){ + const { stack , pos , stackWeight } = wrap; + if (!stack || !STATIC_POSITIONS.includes(pos)) { + continue; + } + const _stack = stacks[stack] || (stacks[stack] = { + count: 0, + placed: 0, + weight: 0, + size: 0 + }); + _stack.count++; + _stack.weight += stackWeight; + } + return stacks; +} + function setLayoutDims(layouts, params) { + const stacks = buildStacks(layouts); + const { vBoxMaxWidth , hBoxMaxHeight } = params; + let i, ilen, layout; + for(i = 0, ilen = layouts.length; i < ilen; ++i){ + layout = layouts[i]; + const { fullSize } = layout.box; + const stack = stacks[layout.stack]; + const factor = stack && layout.stackWeight / stack.weight; + if (layout.horizontal) { + layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth; + layout.height = hBoxMaxHeight; + } else { + layout.width = vBoxMaxWidth; + layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight; + } + } + return stacks; +} +function buildLayoutBoxes(boxes) { + const layoutBoxes = wrapBoxes(boxes); + const fullSize = sortByWeight(layoutBoxes.filter((wrap)=>wrap.box.fullSize), true); + const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true); + const right = sortByWeight(filterByPosition(layoutBoxes, 'right')); + const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true); + const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom')); + const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x'); + const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y'); + return { + fullSize, + leftAndTop: left.concat(top), + rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal), + chartArea: filterByPosition(layoutBoxes, 'chartArea'), + vertical: left.concat(right).concat(centerVertical), + horizontal: top.concat(bottom).concat(centerHorizontal) + }; +} +function getCombinedMax(maxPadding, chartArea, a, b) { + return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]); +} +function updateMaxPadding(maxPadding, boxPadding) { + maxPadding.top = Math.max(maxPadding.top, boxPadding.top); + maxPadding.left = Math.max(maxPadding.left, boxPadding.left); + maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom); + maxPadding.right = Math.max(maxPadding.right, boxPadding.right); +} +function updateDims(chartArea, params, layout, stacks) { + const { pos , box } = layout; + const maxPadding = chartArea.maxPadding; + if (!helpers_dataset.isObject(pos)) { + if (layout.size) { + chartArea[pos] -= layout.size; + } + const stack = stacks[layout.stack] || { + size: 0, + count: 1 + }; + stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width); + layout.size = stack.size / stack.count; + chartArea[pos] += layout.size; + } + if (box.getPadding) { + updateMaxPadding(maxPadding, box.getPadding()); + } + const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right')); + const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom')); + const widthChanged = newWidth !== chartArea.w; + const heightChanged = newHeight !== chartArea.h; + chartArea.w = newWidth; + chartArea.h = newHeight; + return layout.horizontal ? { + same: widthChanged, + other: heightChanged + } : { + same: heightChanged, + other: widthChanged + }; +} +function handleMaxPadding(chartArea) { + const maxPadding = chartArea.maxPadding; + function updatePos(pos) { + const change = Math.max(maxPadding[pos] - chartArea[pos], 0); + chartArea[pos] += change; + return change; + } + chartArea.y += updatePos('top'); + chartArea.x += updatePos('left'); + updatePos('right'); + updatePos('bottom'); +} +function getMargins(horizontal, chartArea) { + const maxPadding = chartArea.maxPadding; + function marginForPositions(positions) { + const margin = { + left: 0, + top: 0, + right: 0, + bottom: 0 + }; + positions.forEach((pos)=>{ + margin[pos] = Math.max(chartArea[pos], maxPadding[pos]); + }); + return margin; + } + return horizontal ? marginForPositions([ + 'left', + 'right' + ]) : marginForPositions([ + 'top', + 'bottom' + ]); +} +function fitBoxes(boxes, chartArea, params, stacks) { + const refitBoxes = []; + let i, ilen, layout, box, refit, changed; + for(i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i){ + layout = boxes[i]; + box = layout.box; + box.update(layout.width || chartArea.w, layout.height || chartArea.h, getMargins(layout.horizontal, chartArea)); + const { same , other } = updateDims(chartArea, params, layout, stacks); + refit |= same && refitBoxes.length; + changed = changed || other; + if (!box.fullSize) { + refitBoxes.push(layout); + } + } + return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed; +} +function setBoxDims(box, left, top, width, height) { + box.top = top; + box.left = left; + box.right = left + width; + box.bottom = top + height; + box.width = width; + box.height = height; +} +function placeBoxes(boxes, chartArea, params, stacks) { + const userPadding = params.padding; + let { x , y } = chartArea; + for (const layout of boxes){ + const box = layout.box; + const stack = stacks[layout.stack] || { + count: 1, + placed: 0, + weight: 1 + }; + const weight = layout.stackWeight / stack.weight || 1; + if (layout.horizontal) { + const width = chartArea.w * weight; + const height = stack.size || box.height; + if (helpers_dataset.defined(stack.start)) { + y = stack.start; + } + if (box.fullSize) { + setBoxDims(box, userPadding.left, y, params.outerWidth - userPadding.right - userPadding.left, height); + } else { + setBoxDims(box, chartArea.left + stack.placed, y, width, height); + } + stack.start = y; + stack.placed += width; + y = box.bottom; + } else { + const height = chartArea.h * weight; + const width = stack.size || box.width; + if (helpers_dataset.defined(stack.start)) { + x = stack.start; + } + if (box.fullSize) { + setBoxDims(box, x, userPadding.top, width, params.outerHeight - userPadding.bottom - userPadding.top); + } else { + setBoxDims(box, x, chartArea.top + stack.placed, width, height); + } + stack.start = x; + stack.placed += height; + x = box.right; + } + } + chartArea.x = x; + chartArea.y = y; +} +var layouts = { + addBox (chart, item) { + if (!chart.boxes) { + chart.boxes = []; + } + item.fullSize = item.fullSize || false; + item.position = item.position || 'top'; + item.weight = item.weight || 0; + item._layers = item._layers || function() { + return [ + { + z: 0, + draw (chartArea) { + item.draw(chartArea); + } + } + ]; + }; + chart.boxes.push(item); + }, + removeBox (chart, layoutItem) { + const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1; + if (index !== -1) { + chart.boxes.splice(index, 1); + } + }, + configure (chart, item, options) { + item.fullSize = options.fullSize; + item.position = options.position; + item.weight = options.weight; + }, + update (chart, width, height, minPadding) { + if (!chart) { + return; + } + const padding = helpers_dataset.toPadding(chart.options.layout.padding); + const availableWidth = Math.max(width - padding.width, 0); + const availableHeight = Math.max(height - padding.height, 0); + const boxes = buildLayoutBoxes(chart.boxes); + const verticalBoxes = boxes.vertical; + const horizontalBoxes = boxes.horizontal; + helpers_dataset.each(chart.boxes, (box)=>{ + if (typeof box.beforeLayout === 'function') { + box.beforeLayout(); + } + }); + const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap)=>wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1; + const params = Object.freeze({ + outerWidth: width, + outerHeight: height, + padding, + availableWidth, + availableHeight, + vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount, + hBoxMaxHeight: availableHeight / 2 + }); + const maxPadding = Object.assign({}, padding); + updateMaxPadding(maxPadding, helpers_dataset.toPadding(minPadding)); + const chartArea = Object.assign({ + maxPadding, + w: availableWidth, + h: availableHeight, + x: padding.left, + y: padding.top + }, padding); + const stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params); + fitBoxes(boxes.fullSize, chartArea, params, stacks); + fitBoxes(verticalBoxes, chartArea, params, stacks); + if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) { + fitBoxes(verticalBoxes, chartArea, params, stacks); + } + handleMaxPadding(chartArea); + placeBoxes(boxes.leftAndTop, chartArea, params, stacks); + chartArea.x += chartArea.w; + chartArea.y += chartArea.h; + placeBoxes(boxes.rightAndBottom, chartArea, params, stacks); + chart.chartArea = { + left: chartArea.left, + top: chartArea.top, + right: chartArea.left + chartArea.w, + bottom: chartArea.top + chartArea.h, + height: chartArea.h, + width: chartArea.w + }; + helpers_dataset.each(boxes.chartArea, (layout)=>{ + const box = layout.box; + Object.assign(box, chart.chartArea); + box.update(chartArea.w, chartArea.h, { + left: 0, + top: 0, + right: 0, + bottom: 0 + }); + }); + } +}; + +class BasePlatform { + acquireContext(canvas, aspectRatio) {} + releaseContext(context) { + return false; + } + addEventListener(chart, type, listener) {} + removeEventListener(chart, type, listener) {} + getDevicePixelRatio() { + return 1; + } + getMaximumSize(element, width, height, aspectRatio) { + width = Math.max(0, width || element.width); + height = height || element.height; + return { + width, + height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height) + }; + } + isAttached(canvas) { + return true; + } + updateConfig(config) { + } +} + +class BasicPlatform extends BasePlatform { + acquireContext(item) { + return item && item.getContext && item.getContext('2d') || null; + } + updateConfig(config) { + config.options.animation = false; + } +} + +const EXPANDO_KEY = '$chartjs'; + const EVENT_TYPES = { + touchstart: 'mousedown', + touchmove: 'mousemove', + touchend: 'mouseup', + pointerenter: 'mouseenter', + pointerdown: 'mousedown', + pointermove: 'mousemove', + pointerup: 'mouseup', + pointerleave: 'mouseout', + pointerout: 'mouseout' +}; +const isNullOrEmpty = (value)=>value === null || value === ''; + function initCanvas(canvas, aspectRatio) { + const style = canvas.style; + const renderHeight = canvas.getAttribute('height'); + const renderWidth = canvas.getAttribute('width'); + canvas[EXPANDO_KEY] = { + initial: { + height: renderHeight, + width: renderWidth, + style: { + display: style.display, + height: style.height, + width: style.width + } + } + }; + style.display = style.display || 'block'; + style.boxSizing = style.boxSizing || 'border-box'; + if (isNullOrEmpty(renderWidth)) { + const displayWidth = helpers_dataset.readUsedSize(canvas, 'width'); + if (displayWidth !== undefined) { + canvas.width = displayWidth; + } + } + if (isNullOrEmpty(renderHeight)) { + if (canvas.style.height === '') { + canvas.height = canvas.width / (aspectRatio || 2); + } else { + const displayHeight = helpers_dataset.readUsedSize(canvas, 'height'); + if (displayHeight !== undefined) { + canvas.height = displayHeight; + } + } + } + return canvas; +} +const eventListenerOptions = helpers_dataset.supportsEventListenerOptions ? { + passive: true +} : false; +function addListener(node, type, listener) { + if (node) { + node.addEventListener(type, listener, eventListenerOptions); + } +} +function removeListener(chart, type, listener) { + if (chart && chart.canvas) { + chart.canvas.removeEventListener(type, listener, eventListenerOptions); + } +} +function fromNativeEvent(event, chart) { + const type = EVENT_TYPES[event.type] || event.type; + const { x , y } = helpers_dataset.getRelativePosition(event, chart); + return { + type, + chart, + native: event, + x: x !== undefined ? x : null, + y: y !== undefined ? y : null + }; +} +function nodeListContains(nodeList, canvas) { + for (const node of nodeList){ + if (node === canvas || node.contains(canvas)) { + return true; + } + } +} +function createAttachObserver(chart, type, listener) { + const canvas = chart.canvas; + const observer = new MutationObserver((entries)=>{ + let trigger = false; + for (const entry of entries){ + trigger = trigger || nodeListContains(entry.addedNodes, canvas); + trigger = trigger && !nodeListContains(entry.removedNodes, canvas); + } + if (trigger) { + listener(); + } + }); + observer.observe(document, { + childList: true, + subtree: true + }); + return observer; +} +function createDetachObserver(chart, type, listener) { + const canvas = chart.canvas; + const observer = new MutationObserver((entries)=>{ + let trigger = false; + for (const entry of entries){ + trigger = trigger || nodeListContains(entry.removedNodes, canvas); + trigger = trigger && !nodeListContains(entry.addedNodes, canvas); + } + if (trigger) { + listener(); + } + }); + observer.observe(document, { + childList: true, + subtree: true + }); + return observer; +} +const drpListeningCharts = new Map(); +let oldDevicePixelRatio = 0; +function onWindowResize() { + const dpr = window.devicePixelRatio; + if (dpr === oldDevicePixelRatio) { + return; + } + oldDevicePixelRatio = dpr; + drpListeningCharts.forEach((resize, chart)=>{ + if (chart.currentDevicePixelRatio !== dpr) { + resize(); + } + }); +} +function listenDevicePixelRatioChanges(chart, resize) { + if (!drpListeningCharts.size) { + window.addEventListener('resize', onWindowResize); + } + drpListeningCharts.set(chart, resize); +} +function unlistenDevicePixelRatioChanges(chart) { + drpListeningCharts.delete(chart); + if (!drpListeningCharts.size) { + window.removeEventListener('resize', onWindowResize); + } +} +function createResizeObserver(chart, type, listener) { + const canvas = chart.canvas; + const container = canvas && helpers_dataset._getParentNode(canvas); + if (!container) { + return; + } + const resize = helpers_dataset.throttled((width, height)=>{ + const w = container.clientWidth; + listener(width, height); + if (w < container.clientWidth) { + listener(); + } + }, window); + const observer = new ResizeObserver((entries)=>{ + const entry = entries[0]; + const width = entry.contentRect.width; + const height = entry.contentRect.height; + if (width === 0 && height === 0) { + return; + } + resize(width, height); + }); + observer.observe(container); + listenDevicePixelRatioChanges(chart, resize); + return observer; +} +function releaseObserver(chart, type, observer) { + if (observer) { + observer.disconnect(); + } + if (type === 'resize') { + unlistenDevicePixelRatioChanges(chart); + } +} +function createProxyAndListen(chart, type, listener) { + const canvas = chart.canvas; + const proxy = helpers_dataset.throttled((event)=>{ + if (chart.ctx !== null) { + listener(fromNativeEvent(event, chart)); + } + }, chart); + addListener(canvas, type, proxy); + return proxy; +} + class DomPlatform extends BasePlatform { + acquireContext(canvas, aspectRatio) { + const context = canvas && canvas.getContext && canvas.getContext('2d'); + if (context && context.canvas === canvas) { + initCanvas(canvas, aspectRatio); + return context; + } + return null; + } + releaseContext(context) { + const canvas = context.canvas; + if (!canvas[EXPANDO_KEY]) { + return false; + } + const initial = canvas[EXPANDO_KEY].initial; + [ + 'height', + 'width' + ].forEach((prop)=>{ + const value = initial[prop]; + if (helpers_dataset.isNullOrUndef(value)) { + canvas.removeAttribute(prop); + } else { + canvas.setAttribute(prop, value); + } + }); + const style = initial.style || {}; + Object.keys(style).forEach((key)=>{ + canvas.style[key] = style[key]; + }); + canvas.width = canvas.width; + delete canvas[EXPANDO_KEY]; + return true; + } + addEventListener(chart, type, listener) { + this.removeEventListener(chart, type); + const proxies = chart.$proxies || (chart.$proxies = {}); + const handlers = { + attach: createAttachObserver, + detach: createDetachObserver, + resize: createResizeObserver + }; + const handler = handlers[type] || createProxyAndListen; + proxies[type] = handler(chart, type, listener); + } + removeEventListener(chart, type) { + const proxies = chart.$proxies || (chart.$proxies = {}); + const proxy = proxies[type]; + if (!proxy) { + return; + } + const handlers = { + attach: releaseObserver, + detach: releaseObserver, + resize: releaseObserver + }; + const handler = handlers[type] || removeListener; + handler(chart, type, proxy); + proxies[type] = undefined; + } + getDevicePixelRatio() { + return window.devicePixelRatio; + } + getMaximumSize(canvas, width, height, aspectRatio) { + return helpers_dataset.getMaximumSize(canvas, width, height, aspectRatio); + } + isAttached(canvas) { + const container = canvas && helpers_dataset._getParentNode(canvas); + return !!(container && container.isConnected); + } +} + +function _detectPlatform(canvas) { + if (!helpers_dataset._isDomSupported() || typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas) { + return BasicPlatform; + } + return DomPlatform; +} + +class Element { + static defaults = {}; + static defaultRoutes = undefined; + x; + y; + active = false; + options; + $animations; + tooltipPosition(useFinalPosition) { + const { x , y } = this.getProps([ + 'x', + 'y' + ], useFinalPosition); + return { + x, + y + }; + } + hasValue() { + return helpers_dataset.isNumber(this.x) && helpers_dataset.isNumber(this.y); + } + getProps(props, final) { + const anims = this.$animations; + if (!final || !anims) { + // let's not create an object, if not needed + return this; + } + const ret = {}; + props.forEach((prop)=>{ + ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : this[prop]; + }); + return ret; + } +} + +function autoSkip(scale, ticks) { + const tickOpts = scale.options.ticks; + const determinedMaxTicks = determineMaxTicks(scale); + const ticksLimit = Math.min(tickOpts.maxTicksLimit || determinedMaxTicks, determinedMaxTicks); + const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : []; + const numMajorIndices = majorIndices.length; + const first = majorIndices[0]; + const last = majorIndices[numMajorIndices - 1]; + const newTicks = []; + if (numMajorIndices > ticksLimit) { + skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit); + return newTicks; + } + const spacing = calculateSpacing(majorIndices, ticks, ticksLimit); + if (numMajorIndices > 0) { + let i, ilen; + const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null; + skip(ticks, newTicks, spacing, helpers_dataset.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first); + for(i = 0, ilen = numMajorIndices - 1; i < ilen; i++){ + skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]); + } + skip(ticks, newTicks, spacing, last, helpers_dataset.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing); + return newTicks; + } + skip(ticks, newTicks, spacing); + return newTicks; +} +function determineMaxTicks(scale) { + const offset = scale.options.offset; + const tickLength = scale._tickSize(); + const maxScale = scale._length / tickLength + (offset ? 0 : 1); + const maxChart = scale._maxLength / tickLength; + return Math.floor(Math.min(maxScale, maxChart)); +} + function calculateSpacing(majorIndices, ticks, ticksLimit) { + const evenMajorSpacing = getEvenSpacing(majorIndices); + const spacing = ticks.length / ticksLimit; + if (!evenMajorSpacing) { + return Math.max(spacing, 1); + } + const factors = helpers_dataset._factorize(evenMajorSpacing); + for(let i = 0, ilen = factors.length - 1; i < ilen; i++){ + const factor = factors[i]; + if (factor > spacing) { + return factor; + } + } + return Math.max(spacing, 1); +} + function getMajorIndices(ticks) { + const result = []; + let i, ilen; + for(i = 0, ilen = ticks.length; i < ilen; i++){ + if (ticks[i].major) { + result.push(i); + } + } + return result; +} + function skipMajors(ticks, newTicks, majorIndices, spacing) { + let count = 0; + let next = majorIndices[0]; + let i; + spacing = Math.ceil(spacing); + for(i = 0; i < ticks.length; i++){ + if (i === next) { + newTicks.push(ticks[i]); + count++; + next = majorIndices[count * spacing]; + } + } +} + function skip(ticks, newTicks, spacing, majorStart, majorEnd) { + const start = helpers_dataset.valueOrDefault(majorStart, 0); + const end = Math.min(helpers_dataset.valueOrDefault(majorEnd, ticks.length), ticks.length); + let count = 0; + let length, i, next; + spacing = Math.ceil(spacing); + if (majorEnd) { + length = majorEnd - majorStart; + spacing = length / Math.floor(length / spacing); + } + next = start; + while(next < 0){ + count++; + next = Math.round(start + count * spacing); + } + for(i = Math.max(start, 0); i < end; i++){ + if (i === next) { + newTicks.push(ticks[i]); + count++; + next = Math.round(start + count * spacing); + } + } +} + function getEvenSpacing(arr) { + const len = arr.length; + let i, diff; + if (len < 2) { + return false; + } + for(diff = arr[0], i = 1; i < len; ++i){ + if (arr[i] - arr[i - 1] !== diff) { + return false; + } + } + return diff; +} + +const reverseAlign = (align)=>align === 'left' ? 'right' : align === 'right' ? 'left' : align; +const offsetFromEdge = (scale, edge, offset)=>edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset; +const getTicksLimit = (ticksLength, maxTicksLimit)=>Math.min(maxTicksLimit || ticksLength, ticksLength); + function sample(arr, numItems) { + const result = []; + const increment = arr.length / numItems; + const len = arr.length; + let i = 0; + for(; i < len; i += increment){ + result.push(arr[Math.floor(i)]); + } + return result; +} + function getPixelForGridLine(scale, index, offsetGridLines) { + const length = scale.ticks.length; + const validIndex = Math.min(index, length - 1); + const start = scale._startPixel; + const end = scale._endPixel; + const epsilon = 1e-6; + let lineValue = scale.getPixelForTick(validIndex); + let offset; + if (offsetGridLines) { + if (length === 1) { + offset = Math.max(lineValue - start, end - lineValue); + } else if (index === 0) { + offset = (scale.getPixelForTick(1) - lineValue) / 2; + } else { + offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2; + } + lineValue += validIndex < index ? offset : -offset; + if (lineValue < start - epsilon || lineValue > end + epsilon) { + return; + } + } + return lineValue; +} + function garbageCollect(caches, length) { + helpers_dataset.each(caches, (cache)=>{ + const gc = cache.gc; + const gcLen = gc.length / 2; + let i; + if (gcLen > length) { + for(i = 0; i < gcLen; ++i){ + delete cache.data[gc[i]]; + } + gc.splice(0, gcLen); + } + }); +} + function getTickMarkLength(options) { + return options.drawTicks ? options.tickLength : 0; +} + function getTitleHeight(options, fallback) { + if (!options.display) { + return 0; + } + const font = helpers_dataset.toFont(options.font, fallback); + const padding = helpers_dataset.toPadding(options.padding); + const lines = helpers_dataset.isArray(options.text) ? options.text.length : 1; + return lines * font.lineHeight + padding.height; +} +function createScaleContext(parent, scale) { + return helpers_dataset.createContext(parent, { + scale, + type: 'scale' + }); +} +function createTickContext(parent, index, tick) { + return helpers_dataset.createContext(parent, { + tick, + index, + type: 'tick' + }); +} +function titleAlign(align, position, reverse) { + let ret = helpers_dataset._toLeftRightCenter(align); + if (reverse && position !== 'right' || !reverse && position === 'right') { + ret = reverseAlign(ret); + } + return ret; +} +function titleArgs(scale, offset, position, align) { + const { top , left , bottom , right , chart } = scale; + const { chartArea , scales } = chart; + let rotation = 0; + let maxWidth, titleX, titleY; + const height = bottom - top; + const width = right - left; + if (scale.isHorizontal()) { + titleX = helpers_dataset._alignStartEnd(align, left, right); + if (helpers_dataset.isObject(position)) { + const positionAxisID = Object.keys(position)[0]; + const value = position[positionAxisID]; + titleY = scales[positionAxisID].getPixelForValue(value) + height - offset; + } else if (position === 'center') { + titleY = (chartArea.bottom + chartArea.top) / 2 + height - offset; + } else { + titleY = offsetFromEdge(scale, position, offset); + } + maxWidth = right - left; + } else { + if (helpers_dataset.isObject(position)) { + const positionAxisID = Object.keys(position)[0]; + const value = position[positionAxisID]; + titleX = scales[positionAxisID].getPixelForValue(value) - width + offset; + } else if (position === 'center') { + titleX = (chartArea.left + chartArea.right) / 2 - width + offset; + } else { + titleX = offsetFromEdge(scale, position, offset); + } + titleY = helpers_dataset._alignStartEnd(align, bottom, top); + rotation = position === 'left' ? -helpers_dataset.HALF_PI : helpers_dataset.HALF_PI; + } + return { + titleX, + titleY, + maxWidth, + rotation + }; +} +class Scale extends Element { + constructor(cfg){ + super(); + this.id = cfg.id; + this.type = cfg.type; + this.options = undefined; + this.ctx = cfg.ctx; + this.chart = cfg.chart; + this.top = undefined; + this.bottom = undefined; + this.left = undefined; + this.right = undefined; + this.width = undefined; + this.height = undefined; + this._margins = { + left: 0, + right: 0, + top: 0, + bottom: 0 + }; + this.maxWidth = undefined; + this.maxHeight = undefined; + this.paddingTop = undefined; + this.paddingBottom = undefined; + this.paddingLeft = undefined; + this.paddingRight = undefined; + this.axis = undefined; + this.labelRotation = undefined; + this.min = undefined; + this.max = undefined; + this._range = undefined; + this.ticks = []; + this._gridLineItems = null; + this._labelItems = null; + this._labelSizes = null; + this._length = 0; + this._maxLength = 0; + this._longestTextCache = {}; + this._startPixel = undefined; + this._endPixel = undefined; + this._reversePixels = false; + this._userMax = undefined; + this._userMin = undefined; + this._suggestedMax = undefined; + this._suggestedMin = undefined; + this._ticksLength = 0; + this._borderValue = 0; + this._cache = {}; + this._dataLimitsCached = false; + this.$context = undefined; + } + init(options) { + this.options = options.setContext(this.getContext()); + this.axis = options.axis; + this._userMin = this.parse(options.min); + this._userMax = this.parse(options.max); + this._suggestedMin = this.parse(options.suggestedMin); + this._suggestedMax = this.parse(options.suggestedMax); + } + parse(raw, index) { + return raw; + } + getUserBounds() { + let { _userMin , _userMax , _suggestedMin , _suggestedMax } = this; + _userMin = helpers_dataset.finiteOrDefault(_userMin, Number.POSITIVE_INFINITY); + _userMax = helpers_dataset.finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY); + _suggestedMin = helpers_dataset.finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY); + _suggestedMax = helpers_dataset.finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY); + return { + min: helpers_dataset.finiteOrDefault(_userMin, _suggestedMin), + max: helpers_dataset.finiteOrDefault(_userMax, _suggestedMax), + minDefined: helpers_dataset.isNumberFinite(_userMin), + maxDefined: helpers_dataset.isNumberFinite(_userMax) + }; + } + getMinMax(canStack) { + let { min , max , minDefined , maxDefined } = this.getUserBounds(); + let range; + if (minDefined && maxDefined) { + return { + min, + max + }; + } + const metas = this.getMatchingVisibleMetas(); + for(let i = 0, ilen = metas.length; i < ilen; ++i){ + range = metas[i].controller.getMinMax(this, canStack); + if (!minDefined) { + min = Math.min(min, range.min); + } + if (!maxDefined) { + max = Math.max(max, range.max); + } + } + min = maxDefined && min > max ? max : min; + max = minDefined && min > max ? min : max; + return { + min: helpers_dataset.finiteOrDefault(min, helpers_dataset.finiteOrDefault(max, min)), + max: helpers_dataset.finiteOrDefault(max, helpers_dataset.finiteOrDefault(min, max)) + }; + } + getPadding() { + return { + left: this.paddingLeft || 0, + top: this.paddingTop || 0, + right: this.paddingRight || 0, + bottom: this.paddingBottom || 0 + }; + } + getTicks() { + return this.ticks; + } + getLabels() { + const data = this.chart.data; + return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || []; + } + getLabelItems(chartArea = this.chart.chartArea) { + const items = this._labelItems || (this._labelItems = this._computeLabelItems(chartArea)); + return items; + } + beforeLayout() { + this._cache = {}; + this._dataLimitsCached = false; + } + beforeUpdate() { + helpers_dataset.callback(this.options.beforeUpdate, [ + this + ]); + } + update(maxWidth, maxHeight, margins) { + const { beginAtZero , grace , ticks: tickOpts } = this.options; + const sampleSize = tickOpts.sampleSize; + this.beforeUpdate(); + this.maxWidth = maxWidth; + this.maxHeight = maxHeight; + this._margins = margins = Object.assign({ + left: 0, + right: 0, + top: 0, + bottom: 0 + }, margins); + this.ticks = null; + this._labelSizes = null; + this._gridLineItems = null; + this._labelItems = null; + this.beforeSetDimensions(); + this.setDimensions(); + this.afterSetDimensions(); + this._maxLength = this.isHorizontal() ? this.width + margins.left + margins.right : this.height + margins.top + margins.bottom; + if (!this._dataLimitsCached) { + this.beforeDataLimits(); + this.determineDataLimits(); + this.afterDataLimits(); + this._range = helpers_dataset._addGrace(this, grace, beginAtZero); + this._dataLimitsCached = true; + } + this.beforeBuildTicks(); + this.ticks = this.buildTicks() || []; + this.afterBuildTicks(); + const samplingEnabled = sampleSize < this.ticks.length; + this._convertTicksToLabels(samplingEnabled ? sample(this.ticks, sampleSize) : this.ticks); + this.configure(); + this.beforeCalculateLabelRotation(); + this.calculateLabelRotation(); + this.afterCalculateLabelRotation(); + if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) { + this.ticks = autoSkip(this, this.ticks); + this._labelSizes = null; + this.afterAutoSkip(); + } + if (samplingEnabled) { + this._convertTicksToLabels(this.ticks); + } + this.beforeFit(); + this.fit(); + this.afterFit(); + this.afterUpdate(); + } + configure() { + let reversePixels = this.options.reverse; + let startPixel, endPixel; + if (this.isHorizontal()) { + startPixel = this.left; + endPixel = this.right; + } else { + startPixel = this.top; + endPixel = this.bottom; + reversePixels = !reversePixels; + } + this._startPixel = startPixel; + this._endPixel = endPixel; + this._reversePixels = reversePixels; + this._length = endPixel - startPixel; + this._alignToPixels = this.options.alignToPixels; + } + afterUpdate() { + helpers_dataset.callback(this.options.afterUpdate, [ + this + ]); + } + beforeSetDimensions() { + helpers_dataset.callback(this.options.beforeSetDimensions, [ + this + ]); + } + setDimensions() { + if (this.isHorizontal()) { + this.width = this.maxWidth; + this.left = 0; + this.right = this.width; + } else { + this.height = this.maxHeight; + this.top = 0; + this.bottom = this.height; + } + this.paddingLeft = 0; + this.paddingTop = 0; + this.paddingRight = 0; + this.paddingBottom = 0; + } + afterSetDimensions() { + helpers_dataset.callback(this.options.afterSetDimensions, [ + this + ]); + } + _callHooks(name) { + this.chart.notifyPlugins(name, this.getContext()); + helpers_dataset.callback(this.options[name], [ + this + ]); + } + beforeDataLimits() { + this._callHooks('beforeDataLimits'); + } + determineDataLimits() {} + afterDataLimits() { + this._callHooks('afterDataLimits'); + } + beforeBuildTicks() { + this._callHooks('beforeBuildTicks'); + } + buildTicks() { + return []; + } + afterBuildTicks() { + this._callHooks('afterBuildTicks'); + } + beforeTickToLabelConversion() { + helpers_dataset.callback(this.options.beforeTickToLabelConversion, [ + this + ]); + } + generateTickLabels(ticks) { + const tickOpts = this.options.ticks; + let i, ilen, tick; + for(i = 0, ilen = ticks.length; i < ilen; i++){ + tick = ticks[i]; + tick.label = helpers_dataset.callback(tickOpts.callback, [ + tick.value, + i, + ticks + ], this); + } + } + afterTickToLabelConversion() { + helpers_dataset.callback(this.options.afterTickToLabelConversion, [ + this + ]); + } + beforeCalculateLabelRotation() { + helpers_dataset.callback(this.options.beforeCalculateLabelRotation, [ + this + ]); + } + calculateLabelRotation() { + const options = this.options; + const tickOpts = options.ticks; + const numTicks = getTicksLimit(this.ticks.length, options.ticks.maxTicksLimit); + const minRotation = tickOpts.minRotation || 0; + const maxRotation = tickOpts.maxRotation; + let labelRotation = minRotation; + let tickWidth, maxHeight, maxLabelDiagonal; + if (!this._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !this.isHorizontal()) { + this.labelRotation = minRotation; + return; + } + const labelSizes = this._getLabelSizes(); + const maxLabelWidth = labelSizes.widest.width; + const maxLabelHeight = labelSizes.highest.height; + const maxWidth = helpers_dataset._limitValue(this.chart.width - maxLabelWidth, 0, this.maxWidth); + tickWidth = options.offset ? this.maxWidth / numTicks : maxWidth / (numTicks - 1); + if (maxLabelWidth + 6 > tickWidth) { + tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1)); + maxHeight = this.maxHeight - getTickMarkLength(options.grid) - tickOpts.padding - getTitleHeight(options.title, this.chart.options.font); + maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight); + labelRotation = helpers_dataset.toDegrees(Math.min(Math.asin(helpers_dataset._limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)), Math.asin(helpers_dataset._limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(helpers_dataset._limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1)))); + labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation)); + } + this.labelRotation = labelRotation; + } + afterCalculateLabelRotation() { + helpers_dataset.callback(this.options.afterCalculateLabelRotation, [ + this + ]); + } + afterAutoSkip() {} + beforeFit() { + helpers_dataset.callback(this.options.beforeFit, [ + this + ]); + } + fit() { + const minSize = { + width: 0, + height: 0 + }; + const { chart , options: { ticks: tickOpts , title: titleOpts , grid: gridOpts } } = this; + const display = this._isVisible(); + const isHorizontal = this.isHorizontal(); + if (display) { + const titleHeight = getTitleHeight(titleOpts, chart.options.font); + if (isHorizontal) { + minSize.width = this.maxWidth; + minSize.height = getTickMarkLength(gridOpts) + titleHeight; + } else { + minSize.height = this.maxHeight; + minSize.width = getTickMarkLength(gridOpts) + titleHeight; + } + if (tickOpts.display && this.ticks.length) { + const { first , last , widest , highest } = this._getLabelSizes(); + const tickPadding = tickOpts.padding * 2; + const angleRadians = helpers_dataset.toRadians(this.labelRotation); + const cos = Math.cos(angleRadians); + const sin = Math.sin(angleRadians); + if (isHorizontal) { + const labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height; + minSize.height = Math.min(this.maxHeight, minSize.height + labelHeight + tickPadding); + } else { + const labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height; + minSize.width = Math.min(this.maxWidth, minSize.width + labelWidth + tickPadding); + } + this._calculatePadding(first, last, sin, cos); + } + } + this._handleMargins(); + if (isHorizontal) { + this.width = this._length = chart.width - this._margins.left - this._margins.right; + this.height = minSize.height; + } else { + this.width = minSize.width; + this.height = this._length = chart.height - this._margins.top - this._margins.bottom; + } + } + _calculatePadding(first, last, sin, cos) { + const { ticks: { align , padding } , position } = this.options; + const isRotated = this.labelRotation !== 0; + const labelsBelowTicks = position !== 'top' && this.axis === 'x'; + if (this.isHorizontal()) { + const offsetLeft = this.getPixelForTick(0) - this.left; + const offsetRight = this.right - this.getPixelForTick(this.ticks.length - 1); + let paddingLeft = 0; + let paddingRight = 0; + if (isRotated) { + if (labelsBelowTicks) { + paddingLeft = cos * first.width; + paddingRight = sin * last.height; + } else { + paddingLeft = sin * first.height; + paddingRight = cos * last.width; + } + } else if (align === 'start') { + paddingRight = last.width; + } else if (align === 'end') { + paddingLeft = first.width; + } else if (align !== 'inner') { + paddingLeft = first.width / 2; + paddingRight = last.width / 2; + } + this.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * this.width / (this.width - offsetLeft), 0); + this.paddingRight = Math.max((paddingRight - offsetRight + padding) * this.width / (this.width - offsetRight), 0); + } else { + let paddingTop = last.height / 2; + let paddingBottom = first.height / 2; + if (align === 'start') { + paddingTop = 0; + paddingBottom = first.height; + } else if (align === 'end') { + paddingTop = last.height; + paddingBottom = 0; + } + this.paddingTop = paddingTop + padding; + this.paddingBottom = paddingBottom + padding; + } + } + _handleMargins() { + if (this._margins) { + this._margins.left = Math.max(this.paddingLeft, this._margins.left); + this._margins.top = Math.max(this.paddingTop, this._margins.top); + this._margins.right = Math.max(this.paddingRight, this._margins.right); + this._margins.bottom = Math.max(this.paddingBottom, this._margins.bottom); + } + } + afterFit() { + helpers_dataset.callback(this.options.afterFit, [ + this + ]); + } + isHorizontal() { + const { axis , position } = this.options; + return position === 'top' || position === 'bottom' || axis === 'x'; + } + isFullSize() { + return this.options.fullSize; + } + _convertTicksToLabels(ticks) { + this.beforeTickToLabelConversion(); + this.generateTickLabels(ticks); + let i, ilen; + for(i = 0, ilen = ticks.length; i < ilen; i++){ + if (helpers_dataset.isNullOrUndef(ticks[i].label)) { + ticks.splice(i, 1); + ilen--; + i--; + } + } + this.afterTickToLabelConversion(); + } + _getLabelSizes() { + let labelSizes = this._labelSizes; + if (!labelSizes) { + const sampleSize = this.options.ticks.sampleSize; + let ticks = this.ticks; + if (sampleSize < ticks.length) { + ticks = sample(ticks, sampleSize); + } + this._labelSizes = labelSizes = this._computeLabelSizes(ticks, ticks.length, this.options.ticks.maxTicksLimit); + } + return labelSizes; + } + _computeLabelSizes(ticks, length, maxTicksLimit) { + const { ctx , _longestTextCache: caches } = this; + const widths = []; + const heights = []; + const increment = Math.floor(length / getTicksLimit(length, maxTicksLimit)); + let widestLabelSize = 0; + let highestLabelSize = 0; + let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel; + for(i = 0; i < length; i += increment){ + label = ticks[i].label; + tickFont = this._resolveTickFontOptions(i); + ctx.font = fontString = tickFont.string; + cache = caches[fontString] = caches[fontString] || { + data: {}, + gc: [] + }; + lineHeight = tickFont.lineHeight; + width = height = 0; + if (!helpers_dataset.isNullOrUndef(label) && !helpers_dataset.isArray(label)) { + width = helpers_dataset._measureText(ctx, cache.data, cache.gc, width, label); + height = lineHeight; + } else if (helpers_dataset.isArray(label)) { + for(j = 0, jlen = label.length; j < jlen; ++j){ + nestedLabel = label[j]; + if (!helpers_dataset.isNullOrUndef(nestedLabel) && !helpers_dataset.isArray(nestedLabel)) { + width = helpers_dataset._measureText(ctx, cache.data, cache.gc, width, nestedLabel); + height += lineHeight; + } + } + } + widths.push(width); + heights.push(height); + widestLabelSize = Math.max(width, widestLabelSize); + highestLabelSize = Math.max(height, highestLabelSize); + } + garbageCollect(caches, length); + const widest = widths.indexOf(widestLabelSize); + const highest = heights.indexOf(highestLabelSize); + const valueAt = (idx)=>({ + width: widths[idx] || 0, + height: heights[idx] || 0 + }); + return { + first: valueAt(0), + last: valueAt(length - 1), + widest: valueAt(widest), + highest: valueAt(highest), + widths, + heights + }; + } + getLabelForValue(value) { + return value; + } + getPixelForValue(value, index) { + return NaN; + } + getValueForPixel(pixel) {} + getPixelForTick(index) { + const ticks = this.ticks; + if (index < 0 || index > ticks.length - 1) { + return null; + } + return this.getPixelForValue(ticks[index].value); + } + getPixelForDecimal(decimal) { + if (this._reversePixels) { + decimal = 1 - decimal; + } + const pixel = this._startPixel + decimal * this._length; + return helpers_dataset._int16Range(this._alignToPixels ? helpers_dataset._alignPixel(this.chart, pixel, 0) : pixel); + } + getDecimalForPixel(pixel) { + const decimal = (pixel - this._startPixel) / this._length; + return this._reversePixels ? 1 - decimal : decimal; + } + getBasePixel() { + return this.getPixelForValue(this.getBaseValue()); + } + getBaseValue() { + const { min , max } = this; + return min < 0 && max < 0 ? max : min > 0 && max > 0 ? min : 0; + } + getContext(index) { + const ticks = this.ticks || []; + if (index >= 0 && index < ticks.length) { + const tick = ticks[index]; + return tick.$context || (tick.$context = createTickContext(this.getContext(), index, tick)); + } + return this.$context || (this.$context = createScaleContext(this.chart.getContext(), this)); + } + _tickSize() { + const optionTicks = this.options.ticks; + const rot = helpers_dataset.toRadians(this.labelRotation); + const cos = Math.abs(Math.cos(rot)); + const sin = Math.abs(Math.sin(rot)); + const labelSizes = this._getLabelSizes(); + const padding = optionTicks.autoSkipPadding || 0; + const w = labelSizes ? labelSizes.widest.width + padding : 0; + const h = labelSizes ? labelSizes.highest.height + padding : 0; + return this.isHorizontal() ? h * cos > w * sin ? w / cos : h / sin : h * sin < w * cos ? h / cos : w / sin; + } + _isVisible() { + const display = this.options.display; + if (display !== 'auto') { + return !!display; + } + return this.getMatchingVisibleMetas().length > 0; + } + _computeGridLineItems(chartArea) { + const axis = this.axis; + const chart = this.chart; + const options = this.options; + const { grid , position , border } = options; + const offset = grid.offset; + const isHorizontal = this.isHorizontal(); + const ticks = this.ticks; + const ticksLength = ticks.length + (offset ? 1 : 0); + const tl = getTickMarkLength(grid); + const items = []; + const borderOpts = border.setContext(this.getContext()); + const axisWidth = borderOpts.display ? borderOpts.width : 0; + const axisHalfWidth = axisWidth / 2; + const alignBorderValue = function(pixel) { + return helpers_dataset._alignPixel(chart, pixel, axisWidth); + }; + let borderValue, i, lineValue, alignedLineValue; + let tx1, ty1, tx2, ty2, x1, y1, x2, y2; + if (position === 'top') { + borderValue = alignBorderValue(this.bottom); + ty1 = this.bottom - tl; + ty2 = borderValue - axisHalfWidth; + y1 = alignBorderValue(chartArea.top) + axisHalfWidth; + y2 = chartArea.bottom; + } else if (position === 'bottom') { + borderValue = alignBorderValue(this.top); + y1 = chartArea.top; + y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth; + ty1 = borderValue + axisHalfWidth; + ty2 = this.top + tl; + } else if (position === 'left') { + borderValue = alignBorderValue(this.right); + tx1 = this.right - tl; + tx2 = borderValue - axisHalfWidth; + x1 = alignBorderValue(chartArea.left) + axisHalfWidth; + x2 = chartArea.right; + } else if (position === 'right') { + borderValue = alignBorderValue(this.left); + x1 = chartArea.left; + x2 = alignBorderValue(chartArea.right) - axisHalfWidth; + tx1 = borderValue + axisHalfWidth; + tx2 = this.left + tl; + } else if (axis === 'x') { + if (position === 'center') { + borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5); + } else if (helpers_dataset.isObject(position)) { + const positionAxisID = Object.keys(position)[0]; + const value = position[positionAxisID]; + borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value)); + } + y1 = chartArea.top; + y2 = chartArea.bottom; + ty1 = borderValue + axisHalfWidth; + ty2 = ty1 + tl; + } else if (axis === 'y') { + if (position === 'center') { + borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2); + } else if (helpers_dataset.isObject(position)) { + const positionAxisID = Object.keys(position)[0]; + const value = position[positionAxisID]; + borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value)); + } + tx1 = borderValue - axisHalfWidth; + tx2 = tx1 - tl; + x1 = chartArea.left; + x2 = chartArea.right; + } + const limit = helpers_dataset.valueOrDefault(options.ticks.maxTicksLimit, ticksLength); + const step = Math.max(1, Math.ceil(ticksLength / limit)); + for(i = 0; i < ticksLength; i += step){ + const context = this.getContext(i); + const optsAtIndex = grid.setContext(context); + const optsAtIndexBorder = border.setContext(context); + const lineWidth = optsAtIndex.lineWidth; + const lineColor = optsAtIndex.color; + const borderDash = optsAtIndexBorder.dash || []; + const borderDashOffset = optsAtIndexBorder.dashOffset; + const tickWidth = optsAtIndex.tickWidth; + const tickColor = optsAtIndex.tickColor; + const tickBorderDash = optsAtIndex.tickBorderDash || []; + const tickBorderDashOffset = optsAtIndex.tickBorderDashOffset; + lineValue = getPixelForGridLine(this, i, offset); + if (lineValue === undefined) { + continue; + } + alignedLineValue = helpers_dataset._alignPixel(chart, lineValue, lineWidth); + if (isHorizontal) { + tx1 = tx2 = x1 = x2 = alignedLineValue; + } else { + ty1 = ty2 = y1 = y2 = alignedLineValue; + } + items.push({ + tx1, + ty1, + tx2, + ty2, + x1, + y1, + x2, + y2, + width: lineWidth, + color: lineColor, + borderDash, + borderDashOffset, + tickWidth, + tickColor, + tickBorderDash, + tickBorderDashOffset + }); + } + this._ticksLength = ticksLength; + this._borderValue = borderValue; + return items; + } + _computeLabelItems(chartArea) { + const axis = this.axis; + const options = this.options; + const { position , ticks: optionTicks } = options; + const isHorizontal = this.isHorizontal(); + const ticks = this.ticks; + const { align , crossAlign , padding , mirror } = optionTicks; + const tl = getTickMarkLength(options.grid); + const tickAndPadding = tl + padding; + const hTickAndPadding = mirror ? -padding : tickAndPadding; + const rotation = -helpers_dataset.toRadians(this.labelRotation); + const items = []; + let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset; + let textBaseline = 'middle'; + if (position === 'top') { + y = this.bottom - hTickAndPadding; + textAlign = this._getXAxisLabelAlignment(); + } else if (position === 'bottom') { + y = this.top + hTickAndPadding; + textAlign = this._getXAxisLabelAlignment(); + } else if (position === 'left') { + const ret = this._getYAxisLabelAlignment(tl); + textAlign = ret.textAlign; + x = ret.x; + } else if (position === 'right') { + const ret = this._getYAxisLabelAlignment(tl); + textAlign = ret.textAlign; + x = ret.x; + } else if (axis === 'x') { + if (position === 'center') { + y = (chartArea.top + chartArea.bottom) / 2 + tickAndPadding; + } else if (helpers_dataset.isObject(position)) { + const positionAxisID = Object.keys(position)[0]; + const value = position[positionAxisID]; + y = this.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding; + } + textAlign = this._getXAxisLabelAlignment(); + } else if (axis === 'y') { + if (position === 'center') { + x = (chartArea.left + chartArea.right) / 2 - tickAndPadding; + } else if (helpers_dataset.isObject(position)) { + const positionAxisID = Object.keys(position)[0]; + const value = position[positionAxisID]; + x = this.chart.scales[positionAxisID].getPixelForValue(value); + } + textAlign = this._getYAxisLabelAlignment(tl).textAlign; + } + if (axis === 'y') { + if (align === 'start') { + textBaseline = 'top'; + } else if (align === 'end') { + textBaseline = 'bottom'; + } + } + const labelSizes = this._getLabelSizes(); + for(i = 0, ilen = ticks.length; i < ilen; ++i){ + tick = ticks[i]; + label = tick.label; + const optsAtIndex = optionTicks.setContext(this.getContext(i)); + pixel = this.getPixelForTick(i) + optionTicks.labelOffset; + font = this._resolveTickFontOptions(i); + lineHeight = font.lineHeight; + lineCount = helpers_dataset.isArray(label) ? label.length : 1; + const halfCount = lineCount / 2; + const color = optsAtIndex.color; + const strokeColor = optsAtIndex.textStrokeColor; + const strokeWidth = optsAtIndex.textStrokeWidth; + let tickTextAlign = textAlign; + if (isHorizontal) { + x = pixel; + if (textAlign === 'inner') { + if (i === ilen - 1) { + tickTextAlign = !this.options.reverse ? 'right' : 'left'; + } else if (i === 0) { + tickTextAlign = !this.options.reverse ? 'left' : 'right'; + } else { + tickTextAlign = 'center'; + } + } + if (position === 'top') { + if (crossAlign === 'near' || rotation !== 0) { + textOffset = -lineCount * lineHeight + lineHeight / 2; + } else if (crossAlign === 'center') { + textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight; + } else { + textOffset = -labelSizes.highest.height + lineHeight / 2; + } + } else { + if (crossAlign === 'near' || rotation !== 0) { + textOffset = lineHeight / 2; + } else if (crossAlign === 'center') { + textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight; + } else { + textOffset = labelSizes.highest.height - lineCount * lineHeight; + } + } + if (mirror) { + textOffset *= -1; + } + if (rotation !== 0 && !optsAtIndex.showLabelBackdrop) { + x += lineHeight / 2 * Math.sin(rotation); + } + } else { + y = pixel; + textOffset = (1 - lineCount) * lineHeight / 2; + } + let backdrop; + if (optsAtIndex.showLabelBackdrop) { + const labelPadding = helpers_dataset.toPadding(optsAtIndex.backdropPadding); + const height = labelSizes.heights[i]; + const width = labelSizes.widths[i]; + let top = textOffset - labelPadding.top; + let left = 0 - labelPadding.left; + switch(textBaseline){ + case 'middle': + top -= height / 2; + break; + case 'bottom': + top -= height; + break; + } + switch(textAlign){ + case 'center': + left -= width / 2; + break; + case 'right': + left -= width; + break; + case 'inner': + if (i === ilen - 1) { + left -= width; + } else if (i > 0) { + left -= width / 2; + } + break; + } + backdrop = { + left, + top, + width: width + labelPadding.width, + height: height + labelPadding.height, + color: optsAtIndex.backdropColor + }; + } + items.push({ + label, + font, + textOffset, + options: { + rotation, + color, + strokeColor, + strokeWidth, + textAlign: tickTextAlign, + textBaseline, + translation: [ + x, + y + ], + backdrop + } + }); + } + return items; + } + _getXAxisLabelAlignment() { + const { position , ticks } = this.options; + const rotation = -helpers_dataset.toRadians(this.labelRotation); + if (rotation) { + return position === 'top' ? 'left' : 'right'; + } + let align = 'center'; + if (ticks.align === 'start') { + align = 'left'; + } else if (ticks.align === 'end') { + align = 'right'; + } else if (ticks.align === 'inner') { + align = 'inner'; + } + return align; + } + _getYAxisLabelAlignment(tl) { + const { position , ticks: { crossAlign , mirror , padding } } = this.options; + const labelSizes = this._getLabelSizes(); + const tickAndPadding = tl + padding; + const widest = labelSizes.widest.width; + let textAlign; + let x; + if (position === 'left') { + if (mirror) { + x = this.right + padding; + if (crossAlign === 'near') { + textAlign = 'left'; + } else if (crossAlign === 'center') { + textAlign = 'center'; + x += widest / 2; + } else { + textAlign = 'right'; + x += widest; + } + } else { + x = this.right - tickAndPadding; + if (crossAlign === 'near') { + textAlign = 'right'; + } else if (crossAlign === 'center') { + textAlign = 'center'; + x -= widest / 2; + } else { + textAlign = 'left'; + x = this.left; + } + } + } else if (position === 'right') { + if (mirror) { + x = this.left + padding; + if (crossAlign === 'near') { + textAlign = 'right'; + } else if (crossAlign === 'center') { + textAlign = 'center'; + x -= widest / 2; + } else { + textAlign = 'left'; + x -= widest; + } + } else { + x = this.left + tickAndPadding; + if (crossAlign === 'near') { + textAlign = 'left'; + } else if (crossAlign === 'center') { + textAlign = 'center'; + x += widest / 2; + } else { + textAlign = 'right'; + x = this.right; + } + } + } else { + textAlign = 'right'; + } + return { + textAlign, + x + }; + } + _computeLabelArea() { + if (this.options.ticks.mirror) { + return; + } + const chart = this.chart; + const position = this.options.position; + if (position === 'left' || position === 'right') { + return { + top: 0, + left: this.left, + bottom: chart.height, + right: this.right + }; + } + if (position === 'top' || position === 'bottom') { + return { + top: this.top, + left: 0, + bottom: this.bottom, + right: chart.width + }; + } + } + drawBackground() { + const { ctx , options: { backgroundColor } , left , top , width , height } = this; + if (backgroundColor) { + ctx.save(); + ctx.fillStyle = backgroundColor; + ctx.fillRect(left, top, width, height); + ctx.restore(); + } + } + getLineWidthForValue(value) { + const grid = this.options.grid; + if (!this._isVisible() || !grid.display) { + return 0; + } + const ticks = this.ticks; + const index = ticks.findIndex((t)=>t.value === value); + if (index >= 0) { + const opts = grid.setContext(this.getContext(index)); + return opts.lineWidth; + } + return 0; + } + drawGrid(chartArea) { + const grid = this.options.grid; + const ctx = this.ctx; + const items = this._gridLineItems || (this._gridLineItems = this._computeGridLineItems(chartArea)); + let i, ilen; + const drawLine = (p1, p2, style)=>{ + if (!style.width || !style.color) { + return; + } + ctx.save(); + ctx.lineWidth = style.width; + ctx.strokeStyle = style.color; + ctx.setLineDash(style.borderDash || []); + ctx.lineDashOffset = style.borderDashOffset; + ctx.beginPath(); + ctx.moveTo(p1.x, p1.y); + ctx.lineTo(p2.x, p2.y); + ctx.stroke(); + ctx.restore(); + }; + if (grid.display) { + for(i = 0, ilen = items.length; i < ilen; ++i){ + const item = items[i]; + if (grid.drawOnChartArea) { + drawLine({ + x: item.x1, + y: item.y1 + }, { + x: item.x2, + y: item.y2 + }, item); + } + if (grid.drawTicks) { + drawLine({ + x: item.tx1, + y: item.ty1 + }, { + x: item.tx2, + y: item.ty2 + }, { + color: item.tickColor, + width: item.tickWidth, + borderDash: item.tickBorderDash, + borderDashOffset: item.tickBorderDashOffset + }); + } + } + } + } + drawBorder() { + const { chart , ctx , options: { border , grid } } = this; + const borderOpts = border.setContext(this.getContext()); + const axisWidth = border.display ? borderOpts.width : 0; + if (!axisWidth) { + return; + } + const lastLineWidth = grid.setContext(this.getContext(0)).lineWidth; + const borderValue = this._borderValue; + let x1, x2, y1, y2; + if (this.isHorizontal()) { + x1 = helpers_dataset._alignPixel(chart, this.left, axisWidth) - axisWidth / 2; + x2 = helpers_dataset._alignPixel(chart, this.right, lastLineWidth) + lastLineWidth / 2; + y1 = y2 = borderValue; + } else { + y1 = helpers_dataset._alignPixel(chart, this.top, axisWidth) - axisWidth / 2; + y2 = helpers_dataset._alignPixel(chart, this.bottom, lastLineWidth) + lastLineWidth / 2; + x1 = x2 = borderValue; + } + ctx.save(); + ctx.lineWidth = borderOpts.width; + ctx.strokeStyle = borderOpts.color; + ctx.beginPath(); + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + ctx.stroke(); + ctx.restore(); + } + drawLabels(chartArea) { + const optionTicks = this.options.ticks; + if (!optionTicks.display) { + return; + } + const ctx = this.ctx; + const area = this._computeLabelArea(); + if (area) { + helpers_dataset.clipArea(ctx, area); + } + const items = this.getLabelItems(chartArea); + for (const item of items){ + const renderTextOptions = item.options; + const tickFont = item.font; + const label = item.label; + const y = item.textOffset; + helpers_dataset.renderText(ctx, label, 0, y, tickFont, renderTextOptions); + } + if (area) { + helpers_dataset.unclipArea(ctx); + } + } + drawTitle() { + const { ctx , options: { position , title , reverse } } = this; + if (!title.display) { + return; + } + const font = helpers_dataset.toFont(title.font); + const padding = helpers_dataset.toPadding(title.padding); + const align = title.align; + let offset = font.lineHeight / 2; + if (position === 'bottom' || position === 'center' || helpers_dataset.isObject(position)) { + offset += padding.bottom; + if (helpers_dataset.isArray(title.text)) { + offset += font.lineHeight * (title.text.length - 1); + } + } else { + offset += padding.top; + } + const { titleX , titleY , maxWidth , rotation } = titleArgs(this, offset, position, align); + helpers_dataset.renderText(ctx, title.text, 0, 0, font, { + color: title.color, + maxWidth, + rotation, + textAlign: titleAlign(align, position, reverse), + textBaseline: 'middle', + translation: [ + titleX, + titleY + ] + }); + } + draw(chartArea) { + if (!this._isVisible()) { + return; + } + this.drawBackground(); + this.drawGrid(chartArea); + this.drawBorder(); + this.drawTitle(); + this.drawLabels(chartArea); + } + _layers() { + const opts = this.options; + const tz = opts.ticks && opts.ticks.z || 0; + const gz = helpers_dataset.valueOrDefault(opts.grid && opts.grid.z, -1); + const bz = helpers_dataset.valueOrDefault(opts.border && opts.border.z, 0); + if (!this._isVisible() || this.draw !== Scale.prototype.draw) { + return [ + { + z: tz, + draw: (chartArea)=>{ + this.draw(chartArea); + } + } + ]; + } + return [ + { + z: gz, + draw: (chartArea)=>{ + this.drawBackground(); + this.drawGrid(chartArea); + this.drawTitle(); + } + }, + { + z: bz, + draw: ()=>{ + this.drawBorder(); + } + }, + { + z: tz, + draw: (chartArea)=>{ + this.drawLabels(chartArea); + } + } + ]; + } + getMatchingVisibleMetas(type) { + const metas = this.chart.getSortedVisibleDatasetMetas(); + const axisID = this.axis + 'AxisID'; + const result = []; + let i, ilen; + for(i = 0, ilen = metas.length; i < ilen; ++i){ + const meta = metas[i]; + if (meta[axisID] === this.id && (!type || meta.type === type)) { + result.push(meta); + } + } + return result; + } + _resolveTickFontOptions(index) { + const opts = this.options.ticks.setContext(this.getContext(index)); + return helpers_dataset.toFont(opts.font); + } + _maxDigits() { + const fontSize = this._resolveTickFontOptions(0).lineHeight; + return (this.isHorizontal() ? this.width : this.height) / fontSize; + } +} + +class TypedRegistry { + constructor(type, scope, override){ + this.type = type; + this.scope = scope; + this.override = override; + this.items = Object.create(null); + } + isForType(type) { + return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype); + } + register(item) { + const proto = Object.getPrototypeOf(item); + let parentScope; + if (isIChartComponent(proto)) { + parentScope = this.register(proto); + } + const items = this.items; + const id = item.id; + const scope = this.scope + '.' + id; + if (!id) { + throw new Error('class does not have id: ' + item); + } + if (id in items) { + return scope; + } + items[id] = item; + registerDefaults(item, scope, parentScope); + if (this.override) { + helpers_dataset.defaults.override(item.id, item.overrides); + } + return scope; + } + get(id) { + return this.items[id]; + } + unregister(item) { + const items = this.items; + const id = item.id; + const scope = this.scope; + if (id in items) { + delete items[id]; + } + if (scope && id in helpers_dataset.defaults[scope]) { + delete helpers_dataset.defaults[scope][id]; + if (this.override) { + delete helpers_dataset.overrides[id]; + } + } + } +} +function registerDefaults(item, scope, parentScope) { + const itemDefaults = helpers_dataset.merge(Object.create(null), [ + parentScope ? helpers_dataset.defaults.get(parentScope) : {}, + helpers_dataset.defaults.get(scope), + item.defaults + ]); + helpers_dataset.defaults.set(scope, itemDefaults); + if (item.defaultRoutes) { + routeDefaults(scope, item.defaultRoutes); + } + if (item.descriptors) { + helpers_dataset.defaults.describe(scope, item.descriptors); + } +} +function routeDefaults(scope, routes) { + Object.keys(routes).forEach((property)=>{ + const propertyParts = property.split('.'); + const sourceName = propertyParts.pop(); + const sourceScope = [ + scope + ].concat(propertyParts).join('.'); + const parts = routes[property].split('.'); + const targetName = parts.pop(); + const targetScope = parts.join('.'); + helpers_dataset.defaults.route(sourceScope, sourceName, targetScope, targetName); + }); +} +function isIChartComponent(proto) { + return 'id' in proto && 'defaults' in proto; +} + +class Registry { + constructor(){ + this.controllers = new TypedRegistry(DatasetController, 'datasets', true); + this.elements = new TypedRegistry(Element, 'elements'); + this.plugins = new TypedRegistry(Object, 'plugins'); + this.scales = new TypedRegistry(Scale, 'scales'); + this._typedRegistries = [ + this.controllers, + this.scales, + this.elements + ]; + } + add(...args) { + this._each('register', args); + } + remove(...args) { + this._each('unregister', args); + } + addControllers(...args) { + this._each('register', args, this.controllers); + } + addElements(...args) { + this._each('register', args, this.elements); + } + addPlugins(...args) { + this._each('register', args, this.plugins); + } + addScales(...args) { + this._each('register', args, this.scales); + } + getController(id) { + return this._get(id, this.controllers, 'controller'); + } + getElement(id) { + return this._get(id, this.elements, 'element'); + } + getPlugin(id) { + return this._get(id, this.plugins, 'plugin'); + } + getScale(id) { + return this._get(id, this.scales, 'scale'); + } + removeControllers(...args) { + this._each('unregister', args, this.controllers); + } + removeElements(...args) { + this._each('unregister', args, this.elements); + } + removePlugins(...args) { + this._each('unregister', args, this.plugins); + } + removeScales(...args) { + this._each('unregister', args, this.scales); + } + _each(method, args, typedRegistry) { + [ + ...args + ].forEach((arg)=>{ + const reg = typedRegistry || this._getRegistryForType(arg); + if (typedRegistry || reg.isForType(arg) || reg === this.plugins && arg.id) { + this._exec(method, reg, arg); + } else { + helpers_dataset.each(arg, (item)=>{ + const itemReg = typedRegistry || this._getRegistryForType(item); + this._exec(method, itemReg, item); + }); + } + }); + } + _exec(method, registry, component) { + const camelMethod = helpers_dataset._capitalize(method); + helpers_dataset.callback(component['before' + camelMethod], [], component); + registry[method](component); + helpers_dataset.callback(component['after' + camelMethod], [], component); + } + _getRegistryForType(type) { + for(let i = 0; i < this._typedRegistries.length; i++){ + const reg = this._typedRegistries[i]; + if (reg.isForType(type)) { + return reg; + } + } + return this.plugins; + } + _get(id, typedRegistry, type) { + const item = typedRegistry.get(id); + if (item === undefined) { + throw new Error('"' + id + '" is not a registered ' + type + '.'); + } + return item; + } +} +var registry = /* #__PURE__ */ new Registry(); + +class PluginService { + constructor(){ + this._init = []; + } + notify(chart, hook, args, filter) { + if (hook === 'beforeInit') { + this._init = this._createDescriptors(chart, true); + this._notify(this._init, chart, 'install'); + } + const descriptors = filter ? this._descriptors(chart).filter(filter) : this._descriptors(chart); + const result = this._notify(descriptors, chart, hook, args); + if (hook === 'afterDestroy') { + this._notify(descriptors, chart, 'stop'); + this._notify(this._init, chart, 'uninstall'); + } + return result; + } + _notify(descriptors, chart, hook, args) { + args = args || {}; + for (const descriptor of descriptors){ + const plugin = descriptor.plugin; + const method = plugin[hook]; + const params = [ + chart, + args, + descriptor.options + ]; + if (helpers_dataset.callback(method, params, plugin) === false && args.cancelable) { + return false; + } + } + return true; + } + invalidate() { + if (!helpers_dataset.isNullOrUndef(this._cache)) { + this._oldCache = this._cache; + this._cache = undefined; + } + } + _descriptors(chart) { + if (this._cache) { + return this._cache; + } + const descriptors = this._cache = this._createDescriptors(chart); + this._notifyStateChanges(chart); + return descriptors; + } + _createDescriptors(chart, all) { + const config = chart && chart.config; + const options = helpers_dataset.valueOrDefault(config.options && config.options.plugins, {}); + const plugins = allPlugins(config); + return options === false && !all ? [] : createDescriptors(chart, plugins, options, all); + } + _notifyStateChanges(chart) { + const previousDescriptors = this._oldCache || []; + const descriptors = this._cache; + const diff = (a, b)=>a.filter((x)=>!b.some((y)=>x.plugin.id === y.plugin.id)); + this._notify(diff(previousDescriptors, descriptors), chart, 'stop'); + this._notify(diff(descriptors, previousDescriptors), chart, 'start'); + } +} + function allPlugins(config) { + const localIds = {}; + const plugins = []; + const keys = Object.keys(registry.plugins.items); + for(let i = 0; i < keys.length; i++){ + plugins.push(registry.getPlugin(keys[i])); + } + const local = config.plugins || []; + for(let i = 0; i < local.length; i++){ + const plugin = local[i]; + if (plugins.indexOf(plugin) === -1) { + plugins.push(plugin); + localIds[plugin.id] = true; + } + } + return { + plugins, + localIds + }; +} +function getOpts(options, all) { + if (!all && options === false) { + return null; + } + if (options === true) { + return {}; + } + return options; +} +function createDescriptors(chart, { plugins , localIds }, options, all) { + const result = []; + const context = chart.getContext(); + for (const plugin of plugins){ + const id = plugin.id; + const opts = getOpts(options[id], all); + if (opts === null) { + continue; + } + result.push({ + plugin, + options: pluginOpts(chart.config, { + plugin, + local: localIds[id] + }, opts, context) + }); + } + return result; +} +function pluginOpts(config, { plugin , local }, opts, context) { + const keys = config.pluginScopeKeys(plugin); + const scopes = config.getOptionScopes(opts, keys); + if (local && plugin.defaults) { + scopes.push(plugin.defaults); + } + return config.createResolver(scopes, context, [ + '' + ], { + scriptable: false, + indexable: false, + allKeys: true + }); +} + +function getIndexAxis(type, options) { + const datasetDefaults = helpers_dataset.defaults.datasets[type] || {}; + const datasetOptions = (options.datasets || {})[type] || {}; + return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x'; +} +function getAxisFromDefaultScaleID(id, indexAxis) { + let axis = id; + if (id === '_index_') { + axis = indexAxis; + } else if (id === '_value_') { + axis = indexAxis === 'x' ? 'y' : 'x'; + } + return axis; +} +function getDefaultScaleIDFromAxis(axis, indexAxis) { + return axis === indexAxis ? '_index_' : '_value_'; +} +function idMatchesAxis(id) { + if (id === 'x' || id === 'y' || id === 'r') { + return id; + } +} +function axisFromPosition(position) { + if (position === 'top' || position === 'bottom') { + return 'x'; + } + if (position === 'left' || position === 'right') { + return 'y'; + } +} +function determineAxis(id, ...scaleOptions) { + if (idMatchesAxis(id)) { + return id; + } + for (const opts of scaleOptions){ + const axis = opts.axis || axisFromPosition(opts.position) || id.length > 1 && idMatchesAxis(id[0].toLowerCase()); + if (axis) { + return axis; + } + } + throw new Error(`Cannot determine type of '${id}' axis. Please provide 'axis' or 'position' option.`); +} +function getAxisFromDataset(id, axis, dataset) { + if (dataset[axis + 'AxisID'] === id) { + return { + axis + }; + } +} +function retrieveAxisFromDatasets(id, config) { + if (config.data && config.data.datasets) { + const boundDs = config.data.datasets.filter((d)=>d.xAxisID === id || d.yAxisID === id); + if (boundDs.length) { + return getAxisFromDataset(id, 'x', boundDs[0]) || getAxisFromDataset(id, 'y', boundDs[0]); + } + } + return {}; +} +function mergeScaleConfig(config, options) { + const chartDefaults = helpers_dataset.overrides[config.type] || { + scales: {} + }; + const configScales = options.scales || {}; + const chartIndexAxis = getIndexAxis(config.type, options); + const scales = Object.create(null); + Object.keys(configScales).forEach((id)=>{ + const scaleConf = configScales[id]; + if (!helpers_dataset.isObject(scaleConf)) { + return console.error(`Invalid scale configuration for scale: ${id}`); + } + if (scaleConf._proxy) { + return console.warn(`Ignoring resolver passed as options for scale: ${id}`); + } + const axis = determineAxis(id, scaleConf, retrieveAxisFromDatasets(id, config), helpers_dataset.defaults.scales[scaleConf.type]); + const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis); + const defaultScaleOptions = chartDefaults.scales || {}; + scales[id] = helpers_dataset.mergeIf(Object.create(null), [ + { + axis + }, + scaleConf, + defaultScaleOptions[axis], + defaultScaleOptions[defaultId] + ]); + }); + config.data.datasets.forEach((dataset)=>{ + const type = dataset.type || config.type; + const indexAxis = dataset.indexAxis || getIndexAxis(type, options); + const datasetDefaults = helpers_dataset.overrides[type] || {}; + const defaultScaleOptions = datasetDefaults.scales || {}; + Object.keys(defaultScaleOptions).forEach((defaultID)=>{ + const axis = getAxisFromDefaultScaleID(defaultID, indexAxis); + const id = dataset[axis + 'AxisID'] || axis; + scales[id] = scales[id] || Object.create(null); + helpers_dataset.mergeIf(scales[id], [ + { + axis + }, + configScales[id], + defaultScaleOptions[defaultID] + ]); + }); + }); + Object.keys(scales).forEach((key)=>{ + const scale = scales[key]; + helpers_dataset.mergeIf(scale, [ + helpers_dataset.defaults.scales[scale.type], + helpers_dataset.defaults.scale + ]); + }); + return scales; +} +function initOptions(config) { + const options = config.options || (config.options = {}); + options.plugins = helpers_dataset.valueOrDefault(options.plugins, {}); + options.scales = mergeScaleConfig(config, options); +} +function initData(data) { + data = data || {}; + data.datasets = data.datasets || []; + data.labels = data.labels || []; + return data; +} +function initConfig(config) { + config = config || {}; + config.data = initData(config.data); + initOptions(config); + return config; +} +const keyCache = new Map(); +const keysCached = new Set(); +function cachedKeys(cacheKey, generate) { + let keys = keyCache.get(cacheKey); + if (!keys) { + keys = generate(); + keyCache.set(cacheKey, keys); + keysCached.add(keys); + } + return keys; +} +const addIfFound = (set, obj, key)=>{ + const opts = helpers_dataset.resolveObjectKey(obj, key); + if (opts !== undefined) { + set.add(opts); + } +}; +class Config { + constructor(config){ + this._config = initConfig(config); + this._scopeCache = new Map(); + this._resolverCache = new Map(); + } + get platform() { + return this._config.platform; + } + get type() { + return this._config.type; + } + set type(type) { + this._config.type = type; + } + get data() { + return this._config.data; + } + set data(data) { + this._config.data = initData(data); + } + get options() { + return this._config.options; + } + set options(options) { + this._config.options = options; + } + get plugins() { + return this._config.plugins; + } + update() { + const config = this._config; + this.clearCache(); + initOptions(config); + } + clearCache() { + this._scopeCache.clear(); + this._resolverCache.clear(); + } + datasetScopeKeys(datasetType) { + return cachedKeys(datasetType, ()=>[ + [ + `datasets.${datasetType}`, + '' + ] + ]); + } + datasetAnimationScopeKeys(datasetType, transition) { + return cachedKeys(`${datasetType}.transition.${transition}`, ()=>[ + [ + `datasets.${datasetType}.transitions.${transition}`, + `transitions.${transition}` + ], + [ + `datasets.${datasetType}`, + '' + ] + ]); + } + datasetElementScopeKeys(datasetType, elementType) { + return cachedKeys(`${datasetType}-${elementType}`, ()=>[ + [ + `datasets.${datasetType}.elements.${elementType}`, + `datasets.${datasetType}`, + `elements.${elementType}`, + '' + ] + ]); + } + pluginScopeKeys(plugin) { + const id = plugin.id; + const type = this.type; + return cachedKeys(`${type}-plugin-${id}`, ()=>[ + [ + `plugins.${id}`, + ...plugin.additionalOptionScopes || [] + ] + ]); + } + _cachedScopes(mainScope, resetCache) { + const _scopeCache = this._scopeCache; + let cache = _scopeCache.get(mainScope); + if (!cache || resetCache) { + cache = new Map(); + _scopeCache.set(mainScope, cache); + } + return cache; + } + getOptionScopes(mainScope, keyLists, resetCache) { + const { options , type } = this; + const cache = this._cachedScopes(mainScope, resetCache); + const cached = cache.get(keyLists); + if (cached) { + return cached; + } + const scopes = new Set(); + keyLists.forEach((keys)=>{ + if (mainScope) { + scopes.add(mainScope); + keys.forEach((key)=>addIfFound(scopes, mainScope, key)); + } + keys.forEach((key)=>addIfFound(scopes, options, key)); + keys.forEach((key)=>addIfFound(scopes, helpers_dataset.overrides[type] || {}, key)); + keys.forEach((key)=>addIfFound(scopes, helpers_dataset.defaults, key)); + keys.forEach((key)=>addIfFound(scopes, helpers_dataset.descriptors, key)); + }); + const array = Array.from(scopes); + if (array.length === 0) { + array.push(Object.create(null)); + } + if (keysCached.has(keyLists)) { + cache.set(keyLists, array); + } + return array; + } + chartOptionScopes() { + const { options , type } = this; + return [ + options, + helpers_dataset.overrides[type] || {}, + helpers_dataset.defaults.datasets[type] || {}, + { + type + }, + helpers_dataset.defaults, + helpers_dataset.descriptors + ]; + } + resolveNamedOptions(scopes, names, context, prefixes = [ + '' + ]) { + const result = { + $shared: true + }; + const { resolver , subPrefixes } = getResolver(this._resolverCache, scopes, prefixes); + let options = resolver; + if (needContext(resolver, names)) { + result.$shared = false; + context = helpers_dataset.isFunction(context) ? context() : context; + const subResolver = this.createResolver(scopes, context, subPrefixes); + options = helpers_dataset._attachContext(resolver, context, subResolver); + } + for (const prop of names){ + result[prop] = options[prop]; + } + return result; + } + createResolver(scopes, context, prefixes = [ + '' + ], descriptorDefaults) { + const { resolver } = getResolver(this._resolverCache, scopes, prefixes); + return helpers_dataset.isObject(context) ? helpers_dataset._attachContext(resolver, context, undefined, descriptorDefaults) : resolver; + } +} +function getResolver(resolverCache, scopes, prefixes) { + let cache = resolverCache.get(scopes); + if (!cache) { + cache = new Map(); + resolverCache.set(scopes, cache); + } + const cacheKey = prefixes.join(); + let cached = cache.get(cacheKey); + if (!cached) { + const resolver = helpers_dataset._createResolver(scopes, prefixes); + cached = { + resolver, + subPrefixes: prefixes.filter((p)=>!p.toLowerCase().includes('hover')) + }; + cache.set(cacheKey, cached); + } + return cached; +} +const hasFunction = (value)=>helpers_dataset.isObject(value) && Object.getOwnPropertyNames(value).some((key)=>helpers_dataset.isFunction(value[key])); +function needContext(proxy, names) { + const { isScriptable , isIndexable } = helpers_dataset._descriptors(proxy); + for (const prop of names){ + const scriptable = isScriptable(prop); + const indexable = isIndexable(prop); + const value = (indexable || scriptable) && proxy[prop]; + if (scriptable && (helpers_dataset.isFunction(value) || hasFunction(value)) || indexable && helpers_dataset.isArray(value)) { + return true; + } + } + return false; +} + +var version = "4.5.0"; + +const KNOWN_POSITIONS = [ + 'top', + 'bottom', + 'left', + 'right', + 'chartArea' +]; +function positionIsHorizontal(position, axis) { + return position === 'top' || position === 'bottom' || KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x'; +} +function compare2Level(l1, l2) { + return function(a, b) { + return a[l1] === b[l1] ? a[l2] - b[l2] : a[l1] - b[l1]; + }; +} +function onAnimationsComplete(context) { + const chart = context.chart; + const animationOptions = chart.options.animation; + chart.notifyPlugins('afterRender'); + helpers_dataset.callback(animationOptions && animationOptions.onComplete, [ + context + ], chart); +} +function onAnimationProgress(context) { + const chart = context.chart; + const animationOptions = chart.options.animation; + helpers_dataset.callback(animationOptions && animationOptions.onProgress, [ + context + ], chart); +} + function getCanvas(item) { + if (helpers_dataset._isDomSupported() && typeof item === 'string') { + item = document.getElementById(item); + } else if (item && item.length) { + item = item[0]; + } + if (item && item.canvas) { + item = item.canvas; + } + return item; +} +const instances = {}; +const getChart = (key)=>{ + const canvas = getCanvas(key); + return Object.values(instances).filter((c)=>c.canvas === canvas).pop(); +}; +function moveNumericKeys(obj, start, move) { + const keys = Object.keys(obj); + for (const key of keys){ + const intKey = +key; + if (intKey >= start) { + const value = obj[key]; + delete obj[key]; + if (move > 0 || intKey > start) { + obj[intKey + move] = value; + } + } + } +} + function determineLastEvent(e, lastEvent, inChartArea, isClick) { + if (!inChartArea || e.type === 'mouseout') { + return null; + } + if (isClick) { + return lastEvent; + } + return e; +} +class Chart { + static defaults = helpers_dataset.defaults; + static instances = instances; + static overrides = helpers_dataset.overrides; + static registry = registry; + static version = version; + static getChart = getChart; + static register(...items) { + registry.add(...items); + invalidatePlugins(); + } + static unregister(...items) { + registry.remove(...items); + invalidatePlugins(); + } + constructor(item, userConfig){ + const config = this.config = new Config(userConfig); + const initialCanvas = getCanvas(item); + const existingChart = getChart(initialCanvas); + if (existingChart) { + throw new Error('Canvas is already in use. Chart with ID \'' + existingChart.id + '\'' + ' must be destroyed before the canvas with ID \'' + existingChart.canvas.id + '\' can be reused.'); + } + const options = config.createResolver(config.chartOptionScopes(), this.getContext()); + this.platform = new (config.platform || _detectPlatform(initialCanvas))(); + this.platform.updateConfig(config); + const context = this.platform.acquireContext(initialCanvas, options.aspectRatio); + const canvas = context && context.canvas; + const height = canvas && canvas.height; + const width = canvas && canvas.width; + this.id = helpers_dataset.uid(); + this.ctx = context; + this.canvas = canvas; + this.width = width; + this.height = height; + this._options = options; + this._aspectRatio = this.aspectRatio; + this._layers = []; + this._metasets = []; + this._stacks = undefined; + this.boxes = []; + this.currentDevicePixelRatio = undefined; + this.chartArea = undefined; + this._active = []; + this._lastEvent = undefined; + this._listeners = {}; + this._responsiveListeners = undefined; + this._sortedMetasets = []; + this.scales = {}; + this._plugins = new PluginService(); + this.$proxies = {}; + this._hiddenIndices = {}; + this.attached = false; + this._animationsDisabled = undefined; + this.$context = undefined; + this._doResize = helpers_dataset.debounce((mode)=>this.update(mode), options.resizeDelay || 0); + this._dataChanges = []; + instances[this.id] = this; + if (!context || !canvas) { + console.error("Failed to create chart: can't acquire context from the given item"); + return; + } + animator.listen(this, 'complete', onAnimationsComplete); + animator.listen(this, 'progress', onAnimationProgress); + this._initialize(); + if (this.attached) { + this.update(); + } + } + get aspectRatio() { + const { options: { aspectRatio , maintainAspectRatio } , width , height , _aspectRatio } = this; + if (!helpers_dataset.isNullOrUndef(aspectRatio)) { + return aspectRatio; + } + if (maintainAspectRatio && _aspectRatio) { + return _aspectRatio; + } + return height ? width / height : null; + } + get data() { + return this.config.data; + } + set data(data) { + this.config.data = data; + } + get options() { + return this._options; + } + set options(options) { + this.config.options = options; + } + get registry() { + return registry; + } + _initialize() { + this.notifyPlugins('beforeInit'); + if (this.options.responsive) { + this.resize(); + } else { + helpers_dataset.retinaScale(this, this.options.devicePixelRatio); + } + this.bindEvents(); + this.notifyPlugins('afterInit'); + return this; + } + clear() { + helpers_dataset.clearCanvas(this.canvas, this.ctx); + return this; + } + stop() { + animator.stop(this); + return this; + } + resize(width, height) { + if (!animator.running(this)) { + this._resize(width, height); + } else { + this._resizeBeforeDraw = { + width, + height + }; + } + } + _resize(width, height) { + const options = this.options; + const canvas = this.canvas; + const aspectRatio = options.maintainAspectRatio && this.aspectRatio; + const newSize = this.platform.getMaximumSize(canvas, width, height, aspectRatio); + const newRatio = options.devicePixelRatio || this.platform.getDevicePixelRatio(); + const mode = this.width ? 'resize' : 'attach'; + this.width = newSize.width; + this.height = newSize.height; + this._aspectRatio = this.aspectRatio; + if (!helpers_dataset.retinaScale(this, newRatio, true)) { + return; + } + this.notifyPlugins('resize', { + size: newSize + }); + helpers_dataset.callback(options.onResize, [ + this, + newSize + ], this); + if (this.attached) { + if (this._doResize(mode)) { + this.render(); + } + } + } + ensureScalesHaveIDs() { + const options = this.options; + const scalesOptions = options.scales || {}; + helpers_dataset.each(scalesOptions, (axisOptions, axisID)=>{ + axisOptions.id = axisID; + }); + } + buildOrUpdateScales() { + const options = this.options; + const scaleOpts = options.scales; + const scales = this.scales; + const updated = Object.keys(scales).reduce((obj, id)=>{ + obj[id] = false; + return obj; + }, {}); + let items = []; + if (scaleOpts) { + items = items.concat(Object.keys(scaleOpts).map((id)=>{ + const scaleOptions = scaleOpts[id]; + const axis = determineAxis(id, scaleOptions); + const isRadial = axis === 'r'; + const isHorizontal = axis === 'x'; + return { + options: scaleOptions, + dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left', + dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear' + }; + })); + } + helpers_dataset.each(items, (item)=>{ + const scaleOptions = item.options; + const id = scaleOptions.id; + const axis = determineAxis(id, scaleOptions); + const scaleType = helpers_dataset.valueOrDefault(scaleOptions.type, item.dtype); + if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) { + scaleOptions.position = item.dposition; + } + updated[id] = true; + let scale = null; + if (id in scales && scales[id].type === scaleType) { + scale = scales[id]; + } else { + const scaleClass = registry.getScale(scaleType); + scale = new scaleClass({ + id, + type: scaleType, + ctx: this.ctx, + chart: this + }); + scales[scale.id] = scale; + } + scale.init(scaleOptions, options); + }); + helpers_dataset.each(updated, (hasUpdated, id)=>{ + if (!hasUpdated) { + delete scales[id]; + } + }); + helpers_dataset.each(scales, (scale)=>{ + layouts.configure(this, scale, scale.options); + layouts.addBox(this, scale); + }); + } + _updateMetasets() { + const metasets = this._metasets; + const numData = this.data.datasets.length; + const numMeta = metasets.length; + metasets.sort((a, b)=>a.index - b.index); + if (numMeta > numData) { + for(let i = numData; i < numMeta; ++i){ + this._destroyDatasetMeta(i); + } + metasets.splice(numData, numMeta - numData); + } + this._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index')); + } + _removeUnreferencedMetasets() { + const { _metasets: metasets , data: { datasets } } = this; + if (metasets.length > datasets.length) { + delete this._stacks; + } + metasets.forEach((meta, index)=>{ + if (datasets.filter((x)=>x === meta._dataset).length === 0) { + this._destroyDatasetMeta(index); + } + }); + } + buildOrUpdateControllers() { + const newControllers = []; + const datasets = this.data.datasets; + let i, ilen; + this._removeUnreferencedMetasets(); + for(i = 0, ilen = datasets.length; i < ilen; i++){ + const dataset = datasets[i]; + let meta = this.getDatasetMeta(i); + const type = dataset.type || this.config.type; + if (meta.type && meta.type !== type) { + this._destroyDatasetMeta(i); + meta = this.getDatasetMeta(i); + } + meta.type = type; + meta.indexAxis = dataset.indexAxis || getIndexAxis(type, this.options); + meta.order = dataset.order || 0; + meta.index = i; + meta.label = '' + dataset.label; + meta.visible = this.isDatasetVisible(i); + if (meta.controller) { + meta.controller.updateIndex(i); + meta.controller.linkScales(); + } else { + const ControllerClass = registry.getController(type); + const { datasetElementType , dataElementType } = helpers_dataset.defaults.datasets[type]; + Object.assign(ControllerClass, { + dataElementType: registry.getElement(dataElementType), + datasetElementType: datasetElementType && registry.getElement(datasetElementType) + }); + meta.controller = new ControllerClass(this, i); + newControllers.push(meta.controller); + } + } + this._updateMetasets(); + return newControllers; + } + _resetElements() { + helpers_dataset.each(this.data.datasets, (dataset, datasetIndex)=>{ + this.getDatasetMeta(datasetIndex).controller.reset(); + }, this); + } + reset() { + this._resetElements(); + this.notifyPlugins('reset'); + } + update(mode) { + const config = this.config; + config.update(); + const options = this._options = config.createResolver(config.chartOptionScopes(), this.getContext()); + const animsDisabled = this._animationsDisabled = !options.animation; + this._updateScales(); + this._checkEventBindings(); + this._updateHiddenIndices(); + this._plugins.invalidate(); + if (this.notifyPlugins('beforeUpdate', { + mode, + cancelable: true + }) === false) { + return; + } + const newControllers = this.buildOrUpdateControllers(); + this.notifyPlugins('beforeElementsUpdate'); + let minPadding = 0; + for(let i = 0, ilen = this.data.datasets.length; i < ilen; i++){ + const { controller } = this.getDatasetMeta(i); + const reset = !animsDisabled && newControllers.indexOf(controller) === -1; + controller.buildOrUpdateElements(reset); + minPadding = Math.max(+controller.getMaxOverflow(), minPadding); + } + minPadding = this._minPadding = options.layout.autoPadding ? minPadding : 0; + this._updateLayout(minPadding); + if (!animsDisabled) { + helpers_dataset.each(newControllers, (controller)=>{ + controller.reset(); + }); + } + this._updateDatasets(mode); + this.notifyPlugins('afterUpdate', { + mode + }); + this._layers.sort(compare2Level('z', '_idx')); + const { _active , _lastEvent } = this; + if (_lastEvent) { + this._eventHandler(_lastEvent, true); + } else if (_active.length) { + this._updateHoverStyles(_active, _active, true); + } + this.render(); + } + _updateScales() { + helpers_dataset.each(this.scales, (scale)=>{ + layouts.removeBox(this, scale); + }); + this.ensureScalesHaveIDs(); + this.buildOrUpdateScales(); + } + _checkEventBindings() { + const options = this.options; + const existingEvents = new Set(Object.keys(this._listeners)); + const newEvents = new Set(options.events); + if (!helpers_dataset.setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== options.responsive) { + this.unbindEvents(); + this.bindEvents(); + } + } + _updateHiddenIndices() { + const { _hiddenIndices } = this; + const changes = this._getUniformDataChanges() || []; + for (const { method , start , count } of changes){ + const move = method === '_removeElements' ? -count : count; + moveNumericKeys(_hiddenIndices, start, move); + } + } + _getUniformDataChanges() { + const _dataChanges = this._dataChanges; + if (!_dataChanges || !_dataChanges.length) { + return; + } + this._dataChanges = []; + const datasetCount = this.data.datasets.length; + const makeSet = (idx)=>new Set(_dataChanges.filter((c)=>c[0] === idx).map((c, i)=>i + ',' + c.splice(1).join(','))); + const changeSet = makeSet(0); + for(let i = 1; i < datasetCount; i++){ + if (!helpers_dataset.setsEqual(changeSet, makeSet(i))) { + return; + } + } + return Array.from(changeSet).map((c)=>c.split(',')).map((a)=>({ + method: a[1], + start: +a[2], + count: +a[3] + })); + } + _updateLayout(minPadding) { + if (this.notifyPlugins('beforeLayout', { + cancelable: true + }) === false) { + return; + } + layouts.update(this, this.width, this.height, minPadding); + const area = this.chartArea; + const noArea = area.width <= 0 || area.height <= 0; + this._layers = []; + helpers_dataset.each(this.boxes, (box)=>{ + if (noArea && box.position === 'chartArea') { + return; + } + if (box.configure) { + box.configure(); + } + this._layers.push(...box._layers()); + }, this); + this._layers.forEach((item, index)=>{ + item._idx = index; + }); + this.notifyPlugins('afterLayout'); + } + _updateDatasets(mode) { + if (this.notifyPlugins('beforeDatasetsUpdate', { + mode, + cancelable: true + }) === false) { + return; + } + for(let i = 0, ilen = this.data.datasets.length; i < ilen; ++i){ + this.getDatasetMeta(i).controller.configure(); + } + for(let i = 0, ilen = this.data.datasets.length; i < ilen; ++i){ + this._updateDataset(i, helpers_dataset.isFunction(mode) ? mode({ + datasetIndex: i + }) : mode); + } + this.notifyPlugins('afterDatasetsUpdate', { + mode + }); + } + _updateDataset(index, mode) { + const meta = this.getDatasetMeta(index); + const args = { + meta, + index, + mode, + cancelable: true + }; + if (this.notifyPlugins('beforeDatasetUpdate', args) === false) { + return; + } + meta.controller._update(mode); + args.cancelable = false; + this.notifyPlugins('afterDatasetUpdate', args); + } + render() { + if (this.notifyPlugins('beforeRender', { + cancelable: true + }) === false) { + return; + } + if (animator.has(this)) { + if (this.attached && !animator.running(this)) { + animator.start(this); + } + } else { + this.draw(); + onAnimationsComplete({ + chart: this + }); + } + } + draw() { + let i; + if (this._resizeBeforeDraw) { + const { width , height } = this._resizeBeforeDraw; + this._resizeBeforeDraw = null; + this._resize(width, height); + } + this.clear(); + if (this.width <= 0 || this.height <= 0) { + return; + } + if (this.notifyPlugins('beforeDraw', { + cancelable: true + }) === false) { + return; + } + const layers = this._layers; + for(i = 0; i < layers.length && layers[i].z <= 0; ++i){ + layers[i].draw(this.chartArea); + } + this._drawDatasets(); + for(; i < layers.length; ++i){ + layers[i].draw(this.chartArea); + } + this.notifyPlugins('afterDraw'); + } + _getSortedDatasetMetas(filterVisible) { + const metasets = this._sortedMetasets; + const result = []; + let i, ilen; + for(i = 0, ilen = metasets.length; i < ilen; ++i){ + const meta = metasets[i]; + if (!filterVisible || meta.visible) { + result.push(meta); + } + } + return result; + } + getSortedVisibleDatasetMetas() { + return this._getSortedDatasetMetas(true); + } + _drawDatasets() { + if (this.notifyPlugins('beforeDatasetsDraw', { + cancelable: true + }) === false) { + return; + } + const metasets = this.getSortedVisibleDatasetMetas(); + for(let i = metasets.length - 1; i >= 0; --i){ + this._drawDataset(metasets[i]); + } + this.notifyPlugins('afterDatasetsDraw'); + } + _drawDataset(meta) { + const ctx = this.ctx; + const args = { + meta, + index: meta.index, + cancelable: true + }; + const clip = helpers_dataset.getDatasetClipArea(this, meta); + if (this.notifyPlugins('beforeDatasetDraw', args) === false) { + return; + } + if (clip) { + helpers_dataset.clipArea(ctx, clip); + } + meta.controller.draw(); + if (clip) { + helpers_dataset.unclipArea(ctx); + } + args.cancelable = false; + this.notifyPlugins('afterDatasetDraw', args); + } + isPointInArea(point) { + return helpers_dataset._isPointInArea(point, this.chartArea, this._minPadding); + } + getElementsAtEventForMode(e, mode, options, useFinalPosition) { + const method = Interaction.modes[mode]; + if (typeof method === 'function') { + return method(this, e, options, useFinalPosition); + } + return []; + } + getDatasetMeta(datasetIndex) { + const dataset = this.data.datasets[datasetIndex]; + const metasets = this._metasets; + let meta = metasets.filter((x)=>x && x._dataset === dataset).pop(); + if (!meta) { + meta = { + type: null, + data: [], + dataset: null, + controller: null, + hidden: null, + xAxisID: null, + yAxisID: null, + order: dataset && dataset.order || 0, + index: datasetIndex, + _dataset: dataset, + _parsed: [], + _sorted: false + }; + metasets.push(meta); + } + return meta; + } + getContext() { + return this.$context || (this.$context = helpers_dataset.createContext(null, { + chart: this, + type: 'chart' + })); + } + getVisibleDatasetCount() { + return this.getSortedVisibleDatasetMetas().length; + } + isDatasetVisible(datasetIndex) { + const dataset = this.data.datasets[datasetIndex]; + if (!dataset) { + return false; + } + const meta = this.getDatasetMeta(datasetIndex); + return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden; + } + setDatasetVisibility(datasetIndex, visible) { + const meta = this.getDatasetMeta(datasetIndex); + meta.hidden = !visible; + } + toggleDataVisibility(index) { + this._hiddenIndices[index] = !this._hiddenIndices[index]; + } + getDataVisibility(index) { + return !this._hiddenIndices[index]; + } + _updateVisibility(datasetIndex, dataIndex, visible) { + const mode = visible ? 'show' : 'hide'; + const meta = this.getDatasetMeta(datasetIndex); + const anims = meta.controller._resolveAnimations(undefined, mode); + if (helpers_dataset.defined(dataIndex)) { + meta.data[dataIndex].hidden = !visible; + this.update(); + } else { + this.setDatasetVisibility(datasetIndex, visible); + anims.update(meta, { + visible + }); + this.update((ctx)=>ctx.datasetIndex === datasetIndex ? mode : undefined); + } + } + hide(datasetIndex, dataIndex) { + this._updateVisibility(datasetIndex, dataIndex, false); + } + show(datasetIndex, dataIndex) { + this._updateVisibility(datasetIndex, dataIndex, true); + } + _destroyDatasetMeta(datasetIndex) { + const meta = this._metasets[datasetIndex]; + if (meta && meta.controller) { + meta.controller._destroy(); + } + delete this._metasets[datasetIndex]; + } + _stop() { + let i, ilen; + this.stop(); + animator.remove(this); + for(i = 0, ilen = this.data.datasets.length; i < ilen; ++i){ + this._destroyDatasetMeta(i); + } + } + destroy() { + this.notifyPlugins('beforeDestroy'); + const { canvas , ctx } = this; + this._stop(); + this.config.clearCache(); + if (canvas) { + this.unbindEvents(); + helpers_dataset.clearCanvas(canvas, ctx); + this.platform.releaseContext(ctx); + this.canvas = null; + this.ctx = null; + } + delete instances[this.id]; + this.notifyPlugins('afterDestroy'); + } + toBase64Image(...args) { + return this.canvas.toDataURL(...args); + } + bindEvents() { + this.bindUserEvents(); + if (this.options.responsive) { + this.bindResponsiveEvents(); + } else { + this.attached = true; + } + } + bindUserEvents() { + const listeners = this._listeners; + const platform = this.platform; + const _add = (type, listener)=>{ + platform.addEventListener(this, type, listener); + listeners[type] = listener; + }; + const listener = (e, x, y)=>{ + e.offsetX = x; + e.offsetY = y; + this._eventHandler(e); + }; + helpers_dataset.each(this.options.events, (type)=>_add(type, listener)); + } + bindResponsiveEvents() { + if (!this._responsiveListeners) { + this._responsiveListeners = {}; + } + const listeners = this._responsiveListeners; + const platform = this.platform; + const _add = (type, listener)=>{ + platform.addEventListener(this, type, listener); + listeners[type] = listener; + }; + const _remove = (type, listener)=>{ + if (listeners[type]) { + platform.removeEventListener(this, type, listener); + delete listeners[type]; + } + }; + const listener = (width, height)=>{ + if (this.canvas) { + this.resize(width, height); + } + }; + let detached; + const attached = ()=>{ + _remove('attach', attached); + this.attached = true; + this.resize(); + _add('resize', listener); + _add('detach', detached); + }; + detached = ()=>{ + this.attached = false; + _remove('resize', listener); + this._stop(); + this._resize(0, 0); + _add('attach', attached); + }; + if (platform.isAttached(this.canvas)) { + attached(); + } else { + detached(); + } + } + unbindEvents() { + helpers_dataset.each(this._listeners, (listener, type)=>{ + this.platform.removeEventListener(this, type, listener); + }); + this._listeners = {}; + helpers_dataset.each(this._responsiveListeners, (listener, type)=>{ + this.platform.removeEventListener(this, type, listener); + }); + this._responsiveListeners = undefined; + } + updateHoverStyle(items, mode, enabled) { + const prefix = enabled ? 'set' : 'remove'; + let meta, item, i, ilen; + if (mode === 'dataset') { + meta = this.getDatasetMeta(items[0].datasetIndex); + meta.controller['_' + prefix + 'DatasetHoverStyle'](); + } + for(i = 0, ilen = items.length; i < ilen; ++i){ + item = items[i]; + const controller = item && this.getDatasetMeta(item.datasetIndex).controller; + if (controller) { + controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index); + } + } + } + getActiveElements() { + return this._active || []; + } + setActiveElements(activeElements) { + const lastActive = this._active || []; + const active = activeElements.map(({ datasetIndex , index })=>{ + const meta = this.getDatasetMeta(datasetIndex); + if (!meta) { + throw new Error('No dataset found at index ' + datasetIndex); + } + return { + datasetIndex, + element: meta.data[index], + index + }; + }); + const changed = !helpers_dataset._elementsEqual(active, lastActive); + if (changed) { + this._active = active; + this._lastEvent = null; + this._updateHoverStyles(active, lastActive); + } + } + notifyPlugins(hook, args, filter) { + return this._plugins.notify(this, hook, args, filter); + } + isPluginEnabled(pluginId) { + return this._plugins._cache.filter((p)=>p.plugin.id === pluginId).length === 1; + } + _updateHoverStyles(active, lastActive, replay) { + const hoverOptions = this.options.hover; + const diff = (a, b)=>a.filter((x)=>!b.some((y)=>x.datasetIndex === y.datasetIndex && x.index === y.index)); + const deactivated = diff(lastActive, active); + const activated = replay ? active : diff(active, lastActive); + if (deactivated.length) { + this.updateHoverStyle(deactivated, hoverOptions.mode, false); + } + if (activated.length && hoverOptions.mode) { + this.updateHoverStyle(activated, hoverOptions.mode, true); + } + } + _eventHandler(e, replay) { + const args = { + event: e, + replay, + cancelable: true, + inChartArea: this.isPointInArea(e) + }; + const eventFilter = (plugin)=>(plugin.options.events || this.options.events).includes(e.native.type); + if (this.notifyPlugins('beforeEvent', args, eventFilter) === false) { + return; + } + const changed = this._handleEvent(e, replay, args.inChartArea); + args.cancelable = false; + this.notifyPlugins('afterEvent', args, eventFilter); + if (changed || args.changed) { + this.render(); + } + return this; + } + _handleEvent(e, replay, inChartArea) { + const { _active: lastActive = [] , options } = this; + const useFinalPosition = replay; + const active = this._getActiveElements(e, lastActive, inChartArea, useFinalPosition); + const isClick = helpers_dataset._isClickEvent(e); + const lastEvent = determineLastEvent(e, this._lastEvent, inChartArea, isClick); + if (inChartArea) { + this._lastEvent = null; + helpers_dataset.callback(options.onHover, [ + e, + active, + this + ], this); + if (isClick) { + helpers_dataset.callback(options.onClick, [ + e, + active, + this + ], this); + } + } + const changed = !helpers_dataset._elementsEqual(active, lastActive); + if (changed || replay) { + this._active = active; + this._updateHoverStyles(active, lastActive, replay); + } + this._lastEvent = lastEvent; + return changed; + } + _getActiveElements(e, lastActive, inChartArea, useFinalPosition) { + if (e.type === 'mouseout') { + return []; + } + if (!inChartArea) { + return lastActive; + } + const hoverOptions = this.options.hover; + return this.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition); + } +} +function invalidatePlugins() { + return helpers_dataset.each(Chart.instances, (chart)=>chart._plugins.invalidate()); +} + +function clipSelf(ctx, element, endAngle) { + const { startAngle , x , y , outerRadius , innerRadius , options } = element; + const { borderWidth , borderJoinStyle } = options; + const outerAngleClip = Math.min(borderWidth / outerRadius, helpers_dataset._normalizeAngle(startAngle - endAngle)); + ctx.beginPath(); + ctx.arc(x, y, outerRadius - borderWidth / 2, startAngle + outerAngleClip / 2, endAngle - outerAngleClip / 2); + if (innerRadius > 0) { + const innerAngleClip = Math.min(borderWidth / innerRadius, helpers_dataset._normalizeAngle(startAngle - endAngle)); + ctx.arc(x, y, innerRadius + borderWidth / 2, endAngle - innerAngleClip / 2, startAngle + innerAngleClip / 2, true); + } else { + const clipWidth = Math.min(borderWidth / 2, outerRadius * helpers_dataset._normalizeAngle(startAngle - endAngle)); + if (borderJoinStyle === 'round') { + ctx.arc(x, y, clipWidth, endAngle - helpers_dataset.PI / 2, startAngle + helpers_dataset.PI / 2, true); + } else if (borderJoinStyle === 'bevel') { + const r = 2 * clipWidth * clipWidth; + const endX = -r * Math.cos(endAngle + helpers_dataset.PI / 2) + x; + const endY = -r * Math.sin(endAngle + helpers_dataset.PI / 2) + y; + const startX = r * Math.cos(startAngle + helpers_dataset.PI / 2) + x; + const startY = r * Math.sin(startAngle + helpers_dataset.PI / 2) + y; + ctx.lineTo(endX, endY); + ctx.lineTo(startX, startY); + } + } + ctx.closePath(); + ctx.moveTo(0, 0); + ctx.rect(0, 0, ctx.canvas.width, ctx.canvas.height); + ctx.clip('evenodd'); +} +function clipArc(ctx, element, endAngle) { + const { startAngle , pixelMargin , x , y , outerRadius , innerRadius } = element; + let angleMargin = pixelMargin / outerRadius; + // Draw an inner border by clipping the arc and drawing a double-width border + // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders + ctx.beginPath(); + ctx.arc(x, y, outerRadius, startAngle - angleMargin, endAngle + angleMargin); + if (innerRadius > pixelMargin) { + angleMargin = pixelMargin / innerRadius; + ctx.arc(x, y, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true); + } else { + ctx.arc(x, y, pixelMargin, endAngle + helpers_dataset.HALF_PI, startAngle - helpers_dataset.HALF_PI); + } + ctx.closePath(); + ctx.clip(); +} +function toRadiusCorners(value) { + return helpers_dataset._readValueToProps(value, [ + 'outerStart', + 'outerEnd', + 'innerStart', + 'innerEnd' + ]); +} +/** + * Parse border radius from the provided options + */ function parseBorderRadius$1(arc, innerRadius, outerRadius, angleDelta) { + const o = toRadiusCorners(arc.options.borderRadius); + const halfThickness = (outerRadius - innerRadius) / 2; + const innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2); + // Outer limits are complicated. We want to compute the available angular distance at + // a radius of outerRadius - borderRadius because for small angular distances, this term limits. + // We compute at r = outerRadius - borderRadius because this circle defines the center of the border corners. + // + // If the borderRadius is large, that value can become negative. + // This causes the outer borders to lose their radius entirely, which is rather unexpected. To solve that, if borderRadius > outerRadius + // we know that the thickness term will dominate and compute the limits at that point + const computeOuterLimit = (val)=>{ + const outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2; + return helpers_dataset._limitValue(val, 0, Math.min(halfThickness, outerArcLimit)); + }; + return { + outerStart: computeOuterLimit(o.outerStart), + outerEnd: computeOuterLimit(o.outerEnd), + innerStart: helpers_dataset._limitValue(o.innerStart, 0, innerLimit), + innerEnd: helpers_dataset._limitValue(o.innerEnd, 0, innerLimit) + }; +} +/** + * Convert (r, 𝜃) to (x, y) + */ function rThetaToXY(r, theta, x, y) { + return { + x: x + r * Math.cos(theta), + y: y + r * Math.sin(theta) + }; +} +/** + * Path the arc, respecting border radius by separating into left and right halves. + * + * Start End + * + * 1--->a--->2 Outer + * / \ + * 8 3 + * | | + * | | + * 7 4 + * \ / + * 6<---b<---5 Inner + */ function pathArc(ctx, element, offset, spacing, end, circular) { + const { x , y , startAngle: start , pixelMargin , innerRadius: innerR } = element; + const outerRadius = Math.max(element.outerRadius + spacing + offset - pixelMargin, 0); + const innerRadius = innerR > 0 ? innerR + spacing + offset + pixelMargin : 0; + let spacingOffset = 0; + const alpha = end - start; + if (spacing) { + // When spacing is present, it is the same for all items + // So we adjust the start and end angle of the arc such that + // the distance is the same as it would be without the spacing + const noSpacingInnerRadius = innerR > 0 ? innerR - spacing : 0; + const noSpacingOuterRadius = outerRadius > 0 ? outerRadius - spacing : 0; + const avNogSpacingRadius = (noSpacingInnerRadius + noSpacingOuterRadius) / 2; + const adjustedAngle = avNogSpacingRadius !== 0 ? alpha * avNogSpacingRadius / (avNogSpacingRadius + spacing) : alpha; + spacingOffset = (alpha - adjustedAngle) / 2; + } + const beta = Math.max(0.001, alpha * outerRadius - offset / helpers_dataset.PI) / outerRadius; + const angleOffset = (alpha - beta) / 2; + const startAngle = start + angleOffset + spacingOffset; + const endAngle = end - angleOffset - spacingOffset; + const { outerStart , outerEnd , innerStart , innerEnd } = parseBorderRadius$1(element, innerRadius, outerRadius, endAngle - startAngle); + const outerStartAdjustedRadius = outerRadius - outerStart; + const outerEndAdjustedRadius = outerRadius - outerEnd; + const outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius; + const outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius; + const innerStartAdjustedRadius = innerRadius + innerStart; + const innerEndAdjustedRadius = innerRadius + innerEnd; + const innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius; + const innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius; + ctx.beginPath(); + if (circular) { + // The first arc segments from point 1 to point a to point 2 + const outerMidAdjustedAngle = (outerStartAdjustedAngle + outerEndAdjustedAngle) / 2; + ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerMidAdjustedAngle); + ctx.arc(x, y, outerRadius, outerMidAdjustedAngle, outerEndAdjustedAngle); + // The corner segment from point 2 to point 3 + if (outerEnd > 0) { + const pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y); + ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + helpers_dataset.HALF_PI); + } + // The line from point 3 to point 4 + const p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y); + ctx.lineTo(p4.x, p4.y); + // The corner segment from point 4 to point 5 + if (innerEnd > 0) { + const pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y); + ctx.arc(pCenter.x, pCenter.y, innerEnd, endAngle + helpers_dataset.HALF_PI, innerEndAdjustedAngle + Math.PI); + } + // The inner arc from point 5 to point b to point 6 + const innerMidAdjustedAngle = (endAngle - innerEnd / innerRadius + (startAngle + innerStart / innerRadius)) / 2; + ctx.arc(x, y, innerRadius, endAngle - innerEnd / innerRadius, innerMidAdjustedAngle, true); + ctx.arc(x, y, innerRadius, innerMidAdjustedAngle, startAngle + innerStart / innerRadius, true); + // The corner segment from point 6 to point 7 + if (innerStart > 0) { + const pCenter = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y); + ctx.arc(pCenter.x, pCenter.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - helpers_dataset.HALF_PI); + } + // The line from point 7 to point 8 + const p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y); + ctx.lineTo(p8.x, p8.y); + // The corner segment from point 8 to point 1 + if (outerStart > 0) { + const pCenter = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y); + ctx.arc(pCenter.x, pCenter.y, outerStart, startAngle - helpers_dataset.HALF_PI, outerStartAdjustedAngle); + } + } else { + ctx.moveTo(x, y); + const outerStartX = Math.cos(outerStartAdjustedAngle) * outerRadius + x; + const outerStartY = Math.sin(outerStartAdjustedAngle) * outerRadius + y; + ctx.lineTo(outerStartX, outerStartY); + const outerEndX = Math.cos(outerEndAdjustedAngle) * outerRadius + x; + const outerEndY = Math.sin(outerEndAdjustedAngle) * outerRadius + y; + ctx.lineTo(outerEndX, outerEndY); + } + ctx.closePath(); +} +function drawArc(ctx, element, offset, spacing, circular) { + const { fullCircles , startAngle , circumference } = element; + let endAngle = element.endAngle; + if (fullCircles) { + pathArc(ctx, element, offset, spacing, endAngle, circular); + for(let i = 0; i < fullCircles; ++i){ + ctx.fill(); + } + if (!isNaN(circumference)) { + endAngle = startAngle + (circumference % helpers_dataset.TAU || helpers_dataset.TAU); + } + } + pathArc(ctx, element, offset, spacing, endAngle, circular); + ctx.fill(); + return endAngle; +} +function drawBorder(ctx, element, offset, spacing, circular) { + const { fullCircles , startAngle , circumference , options } = element; + const { borderWidth , borderJoinStyle , borderDash , borderDashOffset , borderRadius } = options; + const inner = options.borderAlign === 'inner'; + if (!borderWidth) { + return; + } + ctx.setLineDash(borderDash || []); + ctx.lineDashOffset = borderDashOffset; + if (inner) { + ctx.lineWidth = borderWidth * 2; + ctx.lineJoin = borderJoinStyle || 'round'; + } else { + ctx.lineWidth = borderWidth; + ctx.lineJoin = borderJoinStyle || 'bevel'; + } + let endAngle = element.endAngle; + if (fullCircles) { + pathArc(ctx, element, offset, spacing, endAngle, circular); + for(let i = 0; i < fullCircles; ++i){ + ctx.stroke(); + } + if (!isNaN(circumference)) { + endAngle = startAngle + (circumference % helpers_dataset.TAU || helpers_dataset.TAU); + } + } + if (inner) { + clipArc(ctx, element, endAngle); + } + if (options.selfJoin && endAngle - startAngle >= helpers_dataset.PI && borderRadius === 0 && borderJoinStyle !== 'miter') { + clipSelf(ctx, element, endAngle); + } + if (!fullCircles) { + pathArc(ctx, element, offset, spacing, endAngle, circular); + ctx.stroke(); + } +} +class ArcElement extends Element { + static id = 'arc'; + static defaults = { + borderAlign: 'center', + borderColor: '#fff', + borderDash: [], + borderDashOffset: 0, + borderJoinStyle: undefined, + borderRadius: 0, + borderWidth: 2, + offset: 0, + spacing: 0, + angle: undefined, + circular: true, + selfJoin: false + }; + static defaultRoutes = { + backgroundColor: 'backgroundColor' + }; + static descriptors = { + _scriptable: true, + _indexable: (name)=>name !== 'borderDash' + }; + circumference; + endAngle; + fullCircles; + innerRadius; + outerRadius; + pixelMargin; + startAngle; + constructor(cfg){ + super(); + this.options = undefined; + this.circumference = undefined; + this.startAngle = undefined; + this.endAngle = undefined; + this.innerRadius = undefined; + this.outerRadius = undefined; + this.pixelMargin = 0; + this.fullCircles = 0; + if (cfg) { + Object.assign(this, cfg); + } + } + inRange(chartX, chartY, useFinalPosition) { + const point = this.getProps([ + 'x', + 'y' + ], useFinalPosition); + const { angle , distance } = helpers_dataset.getAngleFromPoint(point, { + x: chartX, + y: chartY + }); + const { startAngle , endAngle , innerRadius , outerRadius , circumference } = this.getProps([ + 'startAngle', + 'endAngle', + 'innerRadius', + 'outerRadius', + 'circumference' + ], useFinalPosition); + const rAdjust = (this.options.spacing + this.options.borderWidth) / 2; + const _circumference = helpers_dataset.valueOrDefault(circumference, endAngle - startAngle); + const nonZeroBetween = helpers_dataset._angleBetween(angle, startAngle, endAngle) && startAngle !== endAngle; + const betweenAngles = _circumference >= helpers_dataset.TAU || nonZeroBetween; + const withinRadius = helpers_dataset._isBetween(distance, innerRadius + rAdjust, outerRadius + rAdjust); + return betweenAngles && withinRadius; + } + getCenterPoint(useFinalPosition) { + const { x , y , startAngle , endAngle , innerRadius , outerRadius } = this.getProps([ + 'x', + 'y', + 'startAngle', + 'endAngle', + 'innerRadius', + 'outerRadius' + ], useFinalPosition); + const { offset , spacing } = this.options; + const halfAngle = (startAngle + endAngle) / 2; + const halfRadius = (innerRadius + outerRadius + spacing + offset) / 2; + return { + x: x + Math.cos(halfAngle) * halfRadius, + y: y + Math.sin(halfAngle) * halfRadius + }; + } + tooltipPosition(useFinalPosition) { + return this.getCenterPoint(useFinalPosition); + } + draw(ctx) { + const { options , circumference } = this; + const offset = (options.offset || 0) / 4; + const spacing = (options.spacing || 0) / 2; + const circular = options.circular; + this.pixelMargin = options.borderAlign === 'inner' ? 0.33 : 0; + this.fullCircles = circumference > helpers_dataset.TAU ? Math.floor(circumference / helpers_dataset.TAU) : 0; + if (circumference === 0 || this.innerRadius < 0 || this.outerRadius < 0) { + return; + } + ctx.save(); + const halfAngle = (this.startAngle + this.endAngle) / 2; + ctx.translate(Math.cos(halfAngle) * offset, Math.sin(halfAngle) * offset); + const fix = 1 - Math.sin(Math.min(helpers_dataset.PI, circumference || 0)); + const radiusOffset = offset * fix; + ctx.fillStyle = options.backgroundColor; + ctx.strokeStyle = options.borderColor; + drawArc(ctx, this, radiusOffset, spacing, circular); + drawBorder(ctx, this, radiusOffset, spacing, circular); + ctx.restore(); + } +} + +function setStyle(ctx, options, style = options) { + ctx.lineCap = helpers_dataset.valueOrDefault(style.borderCapStyle, options.borderCapStyle); + ctx.setLineDash(helpers_dataset.valueOrDefault(style.borderDash, options.borderDash)); + ctx.lineDashOffset = helpers_dataset.valueOrDefault(style.borderDashOffset, options.borderDashOffset); + ctx.lineJoin = helpers_dataset.valueOrDefault(style.borderJoinStyle, options.borderJoinStyle); + ctx.lineWidth = helpers_dataset.valueOrDefault(style.borderWidth, options.borderWidth); + ctx.strokeStyle = helpers_dataset.valueOrDefault(style.borderColor, options.borderColor); +} +function lineTo(ctx, previous, target) { + ctx.lineTo(target.x, target.y); +} + function getLineMethod(options) { + if (options.stepped) { + return helpers_dataset._steppedLineTo; + } + if (options.tension || options.cubicInterpolationMode === 'monotone') { + return helpers_dataset._bezierCurveTo; + } + return lineTo; +} +function pathVars(points, segment, params = {}) { + const count = points.length; + const { start: paramsStart = 0 , end: paramsEnd = count - 1 } = params; + const { start: segmentStart , end: segmentEnd } = segment; + const start = Math.max(paramsStart, segmentStart); + const end = Math.min(paramsEnd, segmentEnd); + const outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd; + return { + count, + start, + loop: segment.loop, + ilen: end < start && !outside ? count + end - start : end - start + }; +} + function pathSegment(ctx, line, segment, params) { + const { points , options } = line; + const { count , start , loop , ilen } = pathVars(points, segment, params); + const lineMethod = getLineMethod(options); + let { move =true , reverse } = params || {}; + let i, point, prev; + for(i = 0; i <= ilen; ++i){ + point = points[(start + (reverse ? ilen - i : i)) % count]; + if (point.skip) { + continue; + } else if (move) { + ctx.moveTo(point.x, point.y); + move = false; + } else { + lineMethod(ctx, prev, point, reverse, options.stepped); + } + prev = point; + } + if (loop) { + point = points[(start + (reverse ? ilen : 0)) % count]; + lineMethod(ctx, prev, point, reverse, options.stepped); + } + return !!loop; +} + function fastPathSegment(ctx, line, segment, params) { + const points = line.points; + const { count , start , ilen } = pathVars(points, segment, params); + const { move =true , reverse } = params || {}; + let avgX = 0; + let countX = 0; + let i, point, prevX, minY, maxY, lastY; + const pointIndex = (index)=>(start + (reverse ? ilen - index : index)) % count; + const drawX = ()=>{ + if (minY !== maxY) { + ctx.lineTo(avgX, maxY); + ctx.lineTo(avgX, minY); + ctx.lineTo(avgX, lastY); + } + }; + if (move) { + point = points[pointIndex(0)]; + ctx.moveTo(point.x, point.y); + } + for(i = 0; i <= ilen; ++i){ + point = points[pointIndex(i)]; + if (point.skip) { + continue; + } + const x = point.x; + const y = point.y; + const truncX = x | 0; + if (truncX === prevX) { + if (y < minY) { + minY = y; + } else if (y > maxY) { + maxY = y; + } + avgX = (countX * avgX + x) / ++countX; + } else { + drawX(); + ctx.lineTo(x, y); + prevX = truncX; + countX = 0; + minY = maxY = y; + } + lastY = y; + } + drawX(); +} + function _getSegmentMethod(line) { + const opts = line.options; + const borderDash = opts.borderDash && opts.borderDash.length; + const useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== 'monotone' && !opts.stepped && !borderDash; + return useFastPath ? fastPathSegment : pathSegment; +} + function _getInterpolationMethod(options) { + if (options.stepped) { + return helpers_dataset._steppedInterpolation; + } + if (options.tension || options.cubicInterpolationMode === 'monotone') { + return helpers_dataset._bezierInterpolation; + } + return helpers_dataset._pointInLine; +} +function strokePathWithCache(ctx, line, start, count) { + let path = line._path; + if (!path) { + path = line._path = new Path2D(); + if (line.path(path, start, count)) { + path.closePath(); + } + } + setStyle(ctx, line.options); + ctx.stroke(path); +} +function strokePathDirect(ctx, line, start, count) { + const { segments , options } = line; + const segmentMethod = _getSegmentMethod(line); + for (const segment of segments){ + setStyle(ctx, options, segment.style); + ctx.beginPath(); + if (segmentMethod(ctx, line, segment, { + start, + end: start + count - 1 + })) { + ctx.closePath(); + } + ctx.stroke(); + } +} +const usePath2D = typeof Path2D === 'function'; +function draw(ctx, line, start, count) { + if (usePath2D && !line.options.segment) { + strokePathWithCache(ctx, line, start, count); + } else { + strokePathDirect(ctx, line, start, count); + } +} +class LineElement extends Element { + static id = 'line'; + static defaults = { + borderCapStyle: 'butt', + borderDash: [], + borderDashOffset: 0, + borderJoinStyle: 'miter', + borderWidth: 3, + capBezierPoints: true, + cubicInterpolationMode: 'default', + fill: false, + spanGaps: false, + stepped: false, + tension: 0 + }; + static defaultRoutes = { + backgroundColor: 'backgroundColor', + borderColor: 'borderColor' + }; + static descriptors = { + _scriptable: true, + _indexable: (name)=>name !== 'borderDash' && name !== 'fill' + }; + constructor(cfg){ + super(); + this.animated = true; + this.options = undefined; + this._chart = undefined; + this._loop = undefined; + this._fullLoop = undefined; + this._path = undefined; + this._points = undefined; + this._segments = undefined; + this._decimated = false; + this._pointsUpdated = false; + this._datasetIndex = undefined; + if (cfg) { + Object.assign(this, cfg); + } + } + updateControlPoints(chartArea, indexAxis) { + const options = this.options; + if ((options.tension || options.cubicInterpolationMode === 'monotone') && !options.stepped && !this._pointsUpdated) { + const loop = options.spanGaps ? this._loop : this._fullLoop; + helpers_dataset._updateBezierControlPoints(this._points, options, chartArea, loop, indexAxis); + this._pointsUpdated = true; + } + } + set points(points) { + this._points = points; + delete this._segments; + delete this._path; + this._pointsUpdated = false; + } + get points() { + return this._points; + } + get segments() { + return this._segments || (this._segments = helpers_dataset._computeSegments(this, this.options.segment)); + } + first() { + const segments = this.segments; + const points = this.points; + return segments.length && points[segments[0].start]; + } + last() { + const segments = this.segments; + const points = this.points; + const count = segments.length; + return count && points[segments[count - 1].end]; + } + interpolate(point, property) { + const options = this.options; + const value = point[property]; + const points = this.points; + const segments = helpers_dataset._boundSegments(this, { + property, + start: value, + end: value + }); + if (!segments.length) { + return; + } + const result = []; + const _interpolate = _getInterpolationMethod(options); + let i, ilen; + for(i = 0, ilen = segments.length; i < ilen; ++i){ + const { start , end } = segments[i]; + const p1 = points[start]; + const p2 = points[end]; + if (p1 === p2) { + result.push(p1); + continue; + } + const t = Math.abs((value - p1[property]) / (p2[property] - p1[property])); + const interpolated = _interpolate(p1, p2, t, options.stepped); + interpolated[property] = point[property]; + result.push(interpolated); + } + return result.length === 1 ? result[0] : result; + } + pathSegment(ctx, segment, params) { + const segmentMethod = _getSegmentMethod(this); + return segmentMethod(ctx, this, segment, params); + } + path(ctx, start, count) { + const segments = this.segments; + const segmentMethod = _getSegmentMethod(this); + let loop = this._loop; + start = start || 0; + count = count || this.points.length - start; + for (const segment of segments){ + loop &= segmentMethod(ctx, this, segment, { + start, + end: start + count - 1 + }); + } + return !!loop; + } + draw(ctx, chartArea, start, count) { + const options = this.options || {}; + const points = this.points || []; + if (points.length && options.borderWidth) { + ctx.save(); + draw(ctx, this, start, count); + ctx.restore(); + } + if (this.animated) { + this._pointsUpdated = false; + this._path = undefined; + } + } +} + +function inRange$1(el, pos, axis, useFinalPosition) { + const options = el.options; + const { [axis]: value } = el.getProps([ + axis + ], useFinalPosition); + return Math.abs(pos - value) < options.radius + options.hitRadius; +} +class PointElement extends Element { + static id = 'point'; + parsed; + skip; + stop; + /** + * @type {any} + */ static defaults = { + borderWidth: 1, + hitRadius: 1, + hoverBorderWidth: 1, + hoverRadius: 4, + pointStyle: 'circle', + radius: 3, + rotation: 0 + }; + /** + * @type {any} + */ static defaultRoutes = { + backgroundColor: 'backgroundColor', + borderColor: 'borderColor' + }; + constructor(cfg){ + super(); + this.options = undefined; + this.parsed = undefined; + this.skip = undefined; + this.stop = undefined; + if (cfg) { + Object.assign(this, cfg); + } + } + inRange(mouseX, mouseY, useFinalPosition) { + const options = this.options; + const { x , y } = this.getProps([ + 'x', + 'y' + ], useFinalPosition); + return Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2) < Math.pow(options.hitRadius + options.radius, 2); + } + inXRange(mouseX, useFinalPosition) { + return inRange$1(this, mouseX, 'x', useFinalPosition); + } + inYRange(mouseY, useFinalPosition) { + return inRange$1(this, mouseY, 'y', useFinalPosition); + } + getCenterPoint(useFinalPosition) { + const { x , y } = this.getProps([ + 'x', + 'y' + ], useFinalPosition); + return { + x, + y + }; + } + size(options) { + options = options || this.options || {}; + let radius = options.radius || 0; + radius = Math.max(radius, radius && options.hoverRadius || 0); + const borderWidth = radius && options.borderWidth || 0; + return (radius + borderWidth) * 2; + } + draw(ctx, area) { + const options = this.options; + if (this.skip || options.radius < 0.1 || !helpers_dataset._isPointInArea(this, area, this.size(options) / 2)) { + return; + } + ctx.strokeStyle = options.borderColor; + ctx.lineWidth = options.borderWidth; + ctx.fillStyle = options.backgroundColor; + helpers_dataset.drawPoint(ctx, options, this.x, this.y); + } + getRange() { + const options = this.options || {}; + // @ts-expect-error Fallbacks should never be hit in practice + return options.radius + options.hitRadius; + } +} + +function getBarBounds(bar, useFinalPosition) { + const { x , y , base , width , height } = bar.getProps([ + 'x', + 'y', + 'base', + 'width', + 'height' + ], useFinalPosition); + let left, right, top, bottom, half; + if (bar.horizontal) { + half = height / 2; + left = Math.min(x, base); + right = Math.max(x, base); + top = y - half; + bottom = y + half; + } else { + half = width / 2; + left = x - half; + right = x + half; + top = Math.min(y, base); + bottom = Math.max(y, base); + } + return { + left, + top, + right, + bottom + }; +} +function skipOrLimit(skip, value, min, max) { + return skip ? 0 : helpers_dataset._limitValue(value, min, max); +} +function parseBorderWidth(bar, maxW, maxH) { + const value = bar.options.borderWidth; + const skip = bar.borderSkipped; + const o = helpers_dataset.toTRBL(value); + return { + t: skipOrLimit(skip.top, o.top, 0, maxH), + r: skipOrLimit(skip.right, o.right, 0, maxW), + b: skipOrLimit(skip.bottom, o.bottom, 0, maxH), + l: skipOrLimit(skip.left, o.left, 0, maxW) + }; +} +function parseBorderRadius(bar, maxW, maxH) { + const { enableBorderRadius } = bar.getProps([ + 'enableBorderRadius' + ]); + const value = bar.options.borderRadius; + const o = helpers_dataset.toTRBLCorners(value); + const maxR = Math.min(maxW, maxH); + const skip = bar.borderSkipped; + const enableBorder = enableBorderRadius || helpers_dataset.isObject(value); + return { + topLeft: skipOrLimit(!enableBorder || skip.top || skip.left, o.topLeft, 0, maxR), + topRight: skipOrLimit(!enableBorder || skip.top || skip.right, o.topRight, 0, maxR), + bottomLeft: skipOrLimit(!enableBorder || skip.bottom || skip.left, o.bottomLeft, 0, maxR), + bottomRight: skipOrLimit(!enableBorder || skip.bottom || skip.right, o.bottomRight, 0, maxR) + }; +} +function boundingRects(bar) { + const bounds = getBarBounds(bar); + const width = bounds.right - bounds.left; + const height = bounds.bottom - bounds.top; + const border = parseBorderWidth(bar, width / 2, height / 2); + const radius = parseBorderRadius(bar, width / 2, height / 2); + return { + outer: { + x: bounds.left, + y: bounds.top, + w: width, + h: height, + radius + }, + inner: { + x: bounds.left + border.l, + y: bounds.top + border.t, + w: width - border.l - border.r, + h: height - border.t - border.b, + radius: { + topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)), + topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)), + bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)), + bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r)) + } + } + }; +} +function inRange(bar, x, y, useFinalPosition) { + const skipX = x === null; + const skipY = y === null; + const skipBoth = skipX && skipY; + const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition); + return bounds && (skipX || helpers_dataset._isBetween(x, bounds.left, bounds.right)) && (skipY || helpers_dataset._isBetween(y, bounds.top, bounds.bottom)); +} +function hasRadius(radius) { + return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight; +} + function addNormalRectPath(ctx, rect) { + ctx.rect(rect.x, rect.y, rect.w, rect.h); +} +function inflateRect(rect, amount, refRect = {}) { + const x = rect.x !== refRect.x ? -amount : 0; + const y = rect.y !== refRect.y ? -amount : 0; + const w = (rect.x + rect.w !== refRect.x + refRect.w ? amount : 0) - x; + const h = (rect.y + rect.h !== refRect.y + refRect.h ? amount : 0) - y; + return { + x: rect.x + x, + y: rect.y + y, + w: rect.w + w, + h: rect.h + h, + radius: rect.radius + }; +} +class BarElement extends Element { + static id = 'bar'; + static defaults = { + borderSkipped: 'start', + borderWidth: 0, + borderRadius: 0, + inflateAmount: 'auto', + pointStyle: undefined + }; + static defaultRoutes = { + backgroundColor: 'backgroundColor', + borderColor: 'borderColor' + }; + constructor(cfg){ + super(); + this.options = undefined; + this.horizontal = undefined; + this.base = undefined; + this.width = undefined; + this.height = undefined; + this.inflateAmount = undefined; + if (cfg) { + Object.assign(this, cfg); + } + } + draw(ctx) { + const { inflateAmount , options: { borderColor , backgroundColor } } = this; + const { inner , outer } = boundingRects(this); + const addRectPath = hasRadius(outer.radius) ? helpers_dataset.addRoundedRectPath : addNormalRectPath; + ctx.save(); + if (outer.w !== inner.w || outer.h !== inner.h) { + ctx.beginPath(); + addRectPath(ctx, inflateRect(outer, inflateAmount, inner)); + ctx.clip(); + addRectPath(ctx, inflateRect(inner, -inflateAmount, outer)); + ctx.fillStyle = borderColor; + ctx.fill('evenodd'); + } + ctx.beginPath(); + addRectPath(ctx, inflateRect(inner, inflateAmount)); + ctx.fillStyle = backgroundColor; + ctx.fill(); + ctx.restore(); + } + inRange(mouseX, mouseY, useFinalPosition) { + return inRange(this, mouseX, mouseY, useFinalPosition); + } + inXRange(mouseX, useFinalPosition) { + return inRange(this, mouseX, null, useFinalPosition); + } + inYRange(mouseY, useFinalPosition) { + return inRange(this, null, mouseY, useFinalPosition); + } + getCenterPoint(useFinalPosition) { + const { x , y , base , horizontal } = this.getProps([ + 'x', + 'y', + 'base', + 'horizontal' + ], useFinalPosition); + return { + x: horizontal ? (x + base) / 2 : x, + y: horizontal ? y : (y + base) / 2 + }; + } + getRange(axis) { + return axis === 'x' ? this.width / 2 : this.height / 2; + } +} + +var elements = /*#__PURE__*/Object.freeze({ +__proto__: null, +ArcElement: ArcElement, +BarElement: BarElement, +LineElement: LineElement, +PointElement: PointElement +}); + +const BORDER_COLORS = [ + 'rgb(54, 162, 235)', + 'rgb(255, 99, 132)', + 'rgb(255, 159, 64)', + 'rgb(255, 205, 86)', + 'rgb(75, 192, 192)', + 'rgb(153, 102, 255)', + 'rgb(201, 203, 207)' // grey +]; +// Border colors with 50% transparency +const BACKGROUND_COLORS = /* #__PURE__ */ BORDER_COLORS.map((color)=>color.replace('rgb(', 'rgba(').replace(')', ', 0.5)')); +function getBorderColor(i) { + return BORDER_COLORS[i % BORDER_COLORS.length]; +} +function getBackgroundColor(i) { + return BACKGROUND_COLORS[i % BACKGROUND_COLORS.length]; +} +function colorizeDefaultDataset(dataset, i) { + dataset.borderColor = getBorderColor(i); + dataset.backgroundColor = getBackgroundColor(i); + return ++i; +} +function colorizeDoughnutDataset(dataset, i) { + dataset.backgroundColor = dataset.data.map(()=>getBorderColor(i++)); + return i; +} +function colorizePolarAreaDataset(dataset, i) { + dataset.backgroundColor = dataset.data.map(()=>getBackgroundColor(i++)); + return i; +} +function getColorizer(chart) { + let i = 0; + return (dataset, datasetIndex)=>{ + const controller = chart.getDatasetMeta(datasetIndex).controller; + if (controller instanceof DoughnutController) { + i = colorizeDoughnutDataset(dataset, i); + } else if (controller instanceof PolarAreaController) { + i = colorizePolarAreaDataset(dataset, i); + } else if (controller) { + i = colorizeDefaultDataset(dataset, i); + } + }; +} +function containsColorsDefinitions(descriptors) { + let k; + for(k in descriptors){ + if (descriptors[k].borderColor || descriptors[k].backgroundColor) { + return true; + } + } + return false; +} +function containsColorsDefinition(descriptor) { + return descriptor && (descriptor.borderColor || descriptor.backgroundColor); +} +function containsDefaultColorsDefenitions() { + return helpers_dataset.defaults.borderColor !== 'rgba(0,0,0,0.1)' || helpers_dataset.defaults.backgroundColor !== 'rgba(0,0,0,0.1)'; +} +var plugin_colors = { + id: 'colors', + defaults: { + enabled: true, + forceOverride: false + }, + beforeLayout (chart, _args, options) { + if (!options.enabled) { + return; + } + const { data: { datasets } , options: chartOptions } = chart.config; + const { elements } = chartOptions; + const containsColorDefenition = containsColorsDefinitions(datasets) || containsColorsDefinition(chartOptions) || elements && containsColorsDefinitions(elements) || containsDefaultColorsDefenitions(); + if (!options.forceOverride && containsColorDefenition) { + return; + } + const colorizer = getColorizer(chart); + datasets.forEach(colorizer); + } +}; + +function lttbDecimation(data, start, count, availableWidth, options) { + const samples = options.samples || availableWidth; + if (samples >= count) { + return data.slice(start, start + count); + } + const decimated = []; + const bucketWidth = (count - 2) / (samples - 2); + let sampledIndex = 0; + const endIndex = start + count - 1; + let a = start; + let i, maxAreaPoint, maxArea, area, nextA; + decimated[sampledIndex++] = data[a]; + for(i = 0; i < samples - 2; i++){ + let avgX = 0; + let avgY = 0; + let j; + const avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start; + const avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start; + const avgRangeLength = avgRangeEnd - avgRangeStart; + for(j = avgRangeStart; j < avgRangeEnd; j++){ + avgX += data[j].x; + avgY += data[j].y; + } + avgX /= avgRangeLength; + avgY /= avgRangeLength; + const rangeOffs = Math.floor(i * bucketWidth) + 1 + start; + const rangeTo = Math.min(Math.floor((i + 1) * bucketWidth) + 1, count) + start; + const { x: pointAx , y: pointAy } = data[a]; + maxArea = area = -1; + for(j = rangeOffs; j < rangeTo; j++){ + area = 0.5 * Math.abs((pointAx - avgX) * (data[j].y - pointAy) - (pointAx - data[j].x) * (avgY - pointAy)); + if (area > maxArea) { + maxArea = area; + maxAreaPoint = data[j]; + nextA = j; + } + } + decimated[sampledIndex++] = maxAreaPoint; + a = nextA; + } + decimated[sampledIndex++] = data[endIndex]; + return decimated; +} +function minMaxDecimation(data, start, count, availableWidth) { + let avgX = 0; + let countX = 0; + let i, point, x, y, prevX, minIndex, maxIndex, startIndex, minY, maxY; + const decimated = []; + const endIndex = start + count - 1; + const xMin = data[start].x; + const xMax = data[endIndex].x; + const dx = xMax - xMin; + for(i = start; i < start + count; ++i){ + point = data[i]; + x = (point.x - xMin) / dx * availableWidth; + y = point.y; + const truncX = x | 0; + if (truncX === prevX) { + if (y < minY) { + minY = y; + minIndex = i; + } else if (y > maxY) { + maxY = y; + maxIndex = i; + } + avgX = (countX * avgX + point.x) / ++countX; + } else { + const lastIndex = i - 1; + if (!helpers_dataset.isNullOrUndef(minIndex) && !helpers_dataset.isNullOrUndef(maxIndex)) { + const intermediateIndex1 = Math.min(minIndex, maxIndex); + const intermediateIndex2 = Math.max(minIndex, maxIndex); + if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) { + decimated.push({ + ...data[intermediateIndex1], + x: avgX + }); + } + if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) { + decimated.push({ + ...data[intermediateIndex2], + x: avgX + }); + } + } + if (i > 0 && lastIndex !== startIndex) { + decimated.push(data[lastIndex]); + } + decimated.push(point); + prevX = truncX; + countX = 0; + minY = maxY = y; + minIndex = maxIndex = startIndex = i; + } + } + return decimated; +} +function cleanDecimatedDataset(dataset) { + if (dataset._decimated) { + const data = dataset._data; + delete dataset._decimated; + delete dataset._data; + Object.defineProperty(dataset, 'data', { + configurable: true, + enumerable: true, + writable: true, + value: data + }); + } +} +function cleanDecimatedData(chart) { + chart.data.datasets.forEach((dataset)=>{ + cleanDecimatedDataset(dataset); + }); +} +function getStartAndCountOfVisiblePointsSimplified(meta, points) { + const pointCount = points.length; + let start = 0; + let count; + const { iScale } = meta; + const { min , max , minDefined , maxDefined } = iScale.getUserBounds(); + if (minDefined) { + start = helpers_dataset._limitValue(helpers_dataset._lookupByKey(points, iScale.axis, min).lo, 0, pointCount - 1); + } + if (maxDefined) { + count = helpers_dataset._limitValue(helpers_dataset._lookupByKey(points, iScale.axis, max).hi + 1, start, pointCount) - start; + } else { + count = pointCount - start; + } + return { + start, + count + }; +} +var plugin_decimation = { + id: 'decimation', + defaults: { + algorithm: 'min-max', + enabled: false + }, + beforeElementsUpdate: (chart, args, options)=>{ + if (!options.enabled) { + cleanDecimatedData(chart); + return; + } + const availableWidth = chart.width; + chart.data.datasets.forEach((dataset, datasetIndex)=>{ + const { _data , indexAxis } = dataset; + const meta = chart.getDatasetMeta(datasetIndex); + const data = _data || dataset.data; + if (helpers_dataset.resolve([ + indexAxis, + chart.options.indexAxis + ]) === 'y') { + return; + } + if (!meta.controller.supportsDecimation) { + return; + } + const xAxis = chart.scales[meta.xAxisID]; + if (xAxis.type !== 'linear' && xAxis.type !== 'time') { + return; + } + if (chart.options.parsing) { + return; + } + let { start , count } = getStartAndCountOfVisiblePointsSimplified(meta, data); + const threshold = options.threshold || 4 * availableWidth; + if (count <= threshold) { + cleanDecimatedDataset(dataset); + return; + } + if (helpers_dataset.isNullOrUndef(_data)) { + dataset._data = data; + delete dataset.data; + Object.defineProperty(dataset, 'data', { + configurable: true, + enumerable: true, + get: function() { + return this._decimated; + }, + set: function(d) { + this._data = d; + } + }); + } + let decimated; + switch(options.algorithm){ + case 'lttb': + decimated = lttbDecimation(data, start, count, availableWidth, options); + break; + case 'min-max': + decimated = minMaxDecimation(data, start, count, availableWidth); + break; + default: + throw new Error(`Unsupported decimation algorithm '${options.algorithm}'`); + } + dataset._decimated = decimated; + }); + }, + destroy (chart) { + cleanDecimatedData(chart); + } +}; + +function _segments(line, target, property) { + const segments = line.segments; + const points = line.points; + const tpoints = target.points; + const parts = []; + for (const segment of segments){ + let { start , end } = segment; + end = _findSegmentEnd(start, end, points); + const bounds = _getBounds(property, points[start], points[end], segment.loop); + if (!target.segments) { + parts.push({ + source: segment, + target: bounds, + start: points[start], + end: points[end] + }); + continue; + } + const targetSegments = helpers_dataset._boundSegments(target, bounds); + for (const tgt of targetSegments){ + const subBounds = _getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop); + const fillSources = helpers_dataset._boundSegment(segment, points, subBounds); + for (const fillSource of fillSources){ + parts.push({ + source: fillSource, + target: tgt, + start: { + [property]: _getEdge(bounds, subBounds, 'start', Math.max) + }, + end: { + [property]: _getEdge(bounds, subBounds, 'end', Math.min) + } + }); + } + } + } + return parts; +} +function _getBounds(property, first, last, loop) { + if (loop) { + return; + } + let start = first[property]; + let end = last[property]; + if (property === 'angle') { + start = helpers_dataset._normalizeAngle(start); + end = helpers_dataset._normalizeAngle(end); + } + return { + property, + start, + end + }; +} +function _pointsFromSegments(boundary, line) { + const { x =null , y =null } = boundary || {}; + const linePoints = line.points; + const points = []; + line.segments.forEach(({ start , end })=>{ + end = _findSegmentEnd(start, end, linePoints); + const first = linePoints[start]; + const last = linePoints[end]; + if (y !== null) { + points.push({ + x: first.x, + y + }); + points.push({ + x: last.x, + y + }); + } else if (x !== null) { + points.push({ + x, + y: first.y + }); + points.push({ + x, + y: last.y + }); + } + }); + return points; +} +function _findSegmentEnd(start, end, points) { + for(; end > start; end--){ + const point = points[end]; + if (!isNaN(point.x) && !isNaN(point.y)) { + break; + } + } + return end; +} +function _getEdge(a, b, prop, fn) { + if (a && b) { + return fn(a[prop], b[prop]); + } + return a ? a[prop] : b ? b[prop] : 0; +} + +function _createBoundaryLine(boundary, line) { + let points = []; + let _loop = false; + if (helpers_dataset.isArray(boundary)) { + _loop = true; + points = boundary; + } else { + points = _pointsFromSegments(boundary, line); + } + return points.length ? new LineElement({ + points, + options: { + tension: 0 + }, + _loop, + _fullLoop: _loop + }) : null; +} +function _shouldApplyFill(source) { + return source && source.fill !== false; +} + +function _resolveTarget(sources, index, propagate) { + const source = sources[index]; + let fill = source.fill; + const visited = [ + index + ]; + let target; + if (!propagate) { + return fill; + } + while(fill !== false && visited.indexOf(fill) === -1){ + if (!helpers_dataset.isNumberFinite(fill)) { + return fill; + } + target = sources[fill]; + if (!target) { + return false; + } + if (target.visible) { + return fill; + } + visited.push(fill); + fill = target.fill; + } + return false; +} + function _decodeFill(line, index, count) { + const fill = parseFillOption(line); + if (helpers_dataset.isObject(fill)) { + return isNaN(fill.value) ? false : fill; + } + let target = parseFloat(fill); + if (helpers_dataset.isNumberFinite(target) && Math.floor(target) === target) { + return decodeTargetIndex(fill[0], index, target, count); + } + return [ + 'origin', + 'start', + 'end', + 'stack', + 'shape' + ].indexOf(fill) >= 0 && fill; +} +function decodeTargetIndex(firstCh, index, target, count) { + if (firstCh === '-' || firstCh === '+') { + target = index + target; + } + if (target === index || target < 0 || target >= count) { + return false; + } + return target; +} + function _getTargetPixel(fill, scale) { + let pixel = null; + if (fill === 'start') { + pixel = scale.bottom; + } else if (fill === 'end') { + pixel = scale.top; + } else if (helpers_dataset.isObject(fill)) { + pixel = scale.getPixelForValue(fill.value); + } else if (scale.getBasePixel) { + pixel = scale.getBasePixel(); + } + return pixel; +} + function _getTargetValue(fill, scale, startValue) { + let value; + if (fill === 'start') { + value = startValue; + } else if (fill === 'end') { + value = scale.options.reverse ? scale.min : scale.max; + } else if (helpers_dataset.isObject(fill)) { + value = fill.value; + } else { + value = scale.getBaseValue(); + } + return value; +} + function parseFillOption(line) { + const options = line.options; + const fillOption = options.fill; + let fill = helpers_dataset.valueOrDefault(fillOption && fillOption.target, fillOption); + if (fill === undefined) { + fill = !!options.backgroundColor; + } + if (fill === false || fill === null) { + return false; + } + if (fill === true) { + return 'origin'; + } + return fill; +} + +function _buildStackLine(source) { + const { scale , index , line } = source; + const points = []; + const segments = line.segments; + const sourcePoints = line.points; + const linesBelow = getLinesBelow(scale, index); + linesBelow.push(_createBoundaryLine({ + x: null, + y: scale.bottom + }, line)); + for(let i = 0; i < segments.length; i++){ + const segment = segments[i]; + for(let j = segment.start; j <= segment.end; j++){ + addPointsBelow(points, sourcePoints[j], linesBelow); + } + } + return new LineElement({ + points, + options: {} + }); +} + function getLinesBelow(scale, index) { + const below = []; + const metas = scale.getMatchingVisibleMetas('line'); + for(let i = 0; i < metas.length; i++){ + const meta = metas[i]; + if (meta.index === index) { + break; + } + if (!meta.hidden) { + below.unshift(meta.dataset); + } + } + return below; +} + function addPointsBelow(points, sourcePoint, linesBelow) { + const postponed = []; + for(let j = 0; j < linesBelow.length; j++){ + const line = linesBelow[j]; + const { first , last , point } = findPoint(line, sourcePoint, 'x'); + if (!point || first && last) { + continue; + } + if (first) { + postponed.unshift(point); + } else { + points.push(point); + if (!last) { + break; + } + } + } + points.push(...postponed); +} + function findPoint(line, sourcePoint, property) { + const point = line.interpolate(sourcePoint, property); + if (!point) { + return {}; + } + const pointValue = point[property]; + const segments = line.segments; + const linePoints = line.points; + let first = false; + let last = false; + for(let i = 0; i < segments.length; i++){ + const segment = segments[i]; + const firstValue = linePoints[segment.start][property]; + const lastValue = linePoints[segment.end][property]; + if (helpers_dataset._isBetween(pointValue, firstValue, lastValue)) { + first = pointValue === firstValue; + last = pointValue === lastValue; + break; + } + } + return { + first, + last, + point + }; +} + +class simpleArc { + constructor(opts){ + this.x = opts.x; + this.y = opts.y; + this.radius = opts.radius; + } + pathSegment(ctx, bounds, opts) { + const { x , y , radius } = this; + bounds = bounds || { + start: 0, + end: helpers_dataset.TAU + }; + ctx.arc(x, y, radius, bounds.end, bounds.start, true); + return !opts.bounds; + } + interpolate(point) { + const { x , y , radius } = this; + const angle = point.angle; + return { + x: x + Math.cos(angle) * radius, + y: y + Math.sin(angle) * radius, + angle + }; + } +} + +function _getTarget(source) { + const { chart , fill , line } = source; + if (helpers_dataset.isNumberFinite(fill)) { + return getLineByIndex(chart, fill); + } + if (fill === 'stack') { + return _buildStackLine(source); + } + if (fill === 'shape') { + return true; + } + const boundary = computeBoundary(source); + if (boundary instanceof simpleArc) { + return boundary; + } + return _createBoundaryLine(boundary, line); +} + function getLineByIndex(chart, index) { + const meta = chart.getDatasetMeta(index); + const visible = meta && chart.isDatasetVisible(index); + return visible ? meta.dataset : null; +} +function computeBoundary(source) { + const scale = source.scale || {}; + if (scale.getPointPositionForValue) { + return computeCircularBoundary(source); + } + return computeLinearBoundary(source); +} +function computeLinearBoundary(source) { + const { scale ={} , fill } = source; + const pixel = _getTargetPixel(fill, scale); + if (helpers_dataset.isNumberFinite(pixel)) { + const horizontal = scale.isHorizontal(); + return { + x: horizontal ? pixel : null, + y: horizontal ? null : pixel + }; + } + return null; +} +function computeCircularBoundary(source) { + const { scale , fill } = source; + const options = scale.options; + const length = scale.getLabels().length; + const start = options.reverse ? scale.max : scale.min; + const value = _getTargetValue(fill, scale, start); + const target = []; + if (options.grid.circular) { + const center = scale.getPointPositionForValue(0, start); + return new simpleArc({ + x: center.x, + y: center.y, + radius: scale.getDistanceFromCenterForValue(value) + }); + } + for(let i = 0; i < length; ++i){ + target.push(scale.getPointPositionForValue(i, value)); + } + return target; +} + +function _drawfill(ctx, source, area) { + const target = _getTarget(source); + const { chart , index , line , scale , axis } = source; + const lineOpts = line.options; + const fillOption = lineOpts.fill; + const color = lineOpts.backgroundColor; + const { above =color , below =color } = fillOption || {}; + const meta = chart.getDatasetMeta(index); + const clip = helpers_dataset.getDatasetClipArea(chart, meta); + if (target && line.points.length) { + helpers_dataset.clipArea(ctx, area); + doFill(ctx, { + line, + target, + above, + below, + area, + scale, + axis, + clip + }); + helpers_dataset.unclipArea(ctx); + } +} +function doFill(ctx, cfg) { + const { line , target , above , below , area , scale , clip } = cfg; + const property = line._loop ? 'angle' : cfg.axis; + ctx.save(); + let fillColor = below; + if (below !== above) { + if (property === 'x') { + clipVertical(ctx, target, area.top); + fill(ctx, { + line, + target, + color: above, + scale, + property, + clip + }); + ctx.restore(); + ctx.save(); + clipVertical(ctx, target, area.bottom); + } else if (property === 'y') { + clipHorizontal(ctx, target, area.left); + fill(ctx, { + line, + target, + color: below, + scale, + property, + clip + }); + ctx.restore(); + ctx.save(); + clipHorizontal(ctx, target, area.right); + fillColor = above; + } + } + fill(ctx, { + line, + target, + color: fillColor, + scale, + property, + clip + }); + ctx.restore(); +} +function clipVertical(ctx, target, clipY) { + const { segments , points } = target; + let first = true; + let lineLoop = false; + ctx.beginPath(); + for (const segment of segments){ + const { start , end } = segment; + const firstPoint = points[start]; + const lastPoint = points[_findSegmentEnd(start, end, points)]; + if (first) { + ctx.moveTo(firstPoint.x, firstPoint.y); + first = false; + } else { + ctx.lineTo(firstPoint.x, clipY); + ctx.lineTo(firstPoint.x, firstPoint.y); + } + lineLoop = !!target.pathSegment(ctx, segment, { + move: lineLoop + }); + if (lineLoop) { + ctx.closePath(); + } else { + ctx.lineTo(lastPoint.x, clipY); + } + } + ctx.lineTo(target.first().x, clipY); + ctx.closePath(); + ctx.clip(); +} +function clipHorizontal(ctx, target, clipX) { + const { segments , points } = target; + let first = true; + let lineLoop = false; + ctx.beginPath(); + for (const segment of segments){ + const { start , end } = segment; + const firstPoint = points[start]; + const lastPoint = points[_findSegmentEnd(start, end, points)]; + if (first) { + ctx.moveTo(firstPoint.x, firstPoint.y); + first = false; + } else { + ctx.lineTo(clipX, firstPoint.y); + ctx.lineTo(firstPoint.x, firstPoint.y); + } + lineLoop = !!target.pathSegment(ctx, segment, { + move: lineLoop + }); + if (lineLoop) { + ctx.closePath(); + } else { + ctx.lineTo(clipX, lastPoint.y); + } + } + ctx.lineTo(clipX, target.first().y); + ctx.closePath(); + ctx.clip(); +} +function fill(ctx, cfg) { + const { line , target , property , color , scale , clip } = cfg; + const segments = _segments(line, target, property); + for (const { source: src , target: tgt , start , end } of segments){ + const { style: { backgroundColor =color } = {} } = src; + const notShape = target !== true; + ctx.save(); + ctx.fillStyle = backgroundColor; + clipBounds(ctx, scale, clip, notShape && _getBounds(property, start, end)); + ctx.beginPath(); + const lineLoop = !!line.pathSegment(ctx, src); + let loop; + if (notShape) { + if (lineLoop) { + ctx.closePath(); + } else { + interpolatedLineTo(ctx, target, end, property); + } + const targetLoop = !!target.pathSegment(ctx, tgt, { + move: lineLoop, + reverse: true + }); + loop = lineLoop && targetLoop; + if (!loop) { + interpolatedLineTo(ctx, target, start, property); + } + } + ctx.closePath(); + ctx.fill(loop ? 'evenodd' : 'nonzero'); + ctx.restore(); + } +} +function clipBounds(ctx, scale, clip, bounds) { + const chartArea = scale.chart.chartArea; + const { property , start , end } = bounds || {}; + if (property === 'x' || property === 'y') { + let left, top, right, bottom; + if (property === 'x') { + left = start; + top = chartArea.top; + right = end; + bottom = chartArea.bottom; + } else { + left = chartArea.left; + top = start; + right = chartArea.right; + bottom = end; + } + ctx.beginPath(); + if (clip) { + left = Math.max(left, clip.left); + right = Math.min(right, clip.right); + top = Math.max(top, clip.top); + bottom = Math.min(bottom, clip.bottom); + } + ctx.rect(left, top, right - left, bottom - top); + ctx.clip(); + } +} +function interpolatedLineTo(ctx, target, point, property) { + const interpolatedPoint = target.interpolate(point, property); + if (interpolatedPoint) { + ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y); + } +} + +var index = { + id: 'filler', + afterDatasetsUpdate (chart, _args, options) { + const count = (chart.data.datasets || []).length; + const sources = []; + let meta, i, line, source; + for(i = 0; i < count; ++i){ + meta = chart.getDatasetMeta(i); + line = meta.dataset; + source = null; + if (line && line.options && line instanceof LineElement) { + source = { + visible: chart.isDatasetVisible(i), + index: i, + fill: _decodeFill(line, i, count), + chart, + axis: meta.controller.options.indexAxis, + scale: meta.vScale, + line + }; + } + meta.$filler = source; + sources.push(source); + } + for(i = 0; i < count; ++i){ + source = sources[i]; + if (!source || source.fill === false) { + continue; + } + source.fill = _resolveTarget(sources, i, options.propagate); + } + }, + beforeDraw (chart, _args, options) { + const draw = options.drawTime === 'beforeDraw'; + const metasets = chart.getSortedVisibleDatasetMetas(); + const area = chart.chartArea; + for(let i = metasets.length - 1; i >= 0; --i){ + const source = metasets[i].$filler; + if (!source) { + continue; + } + source.line.updateControlPoints(area, source.axis); + if (draw && source.fill) { + _drawfill(chart.ctx, source, area); + } + } + }, + beforeDatasetsDraw (chart, _args, options) { + if (options.drawTime !== 'beforeDatasetsDraw') { + return; + } + const metasets = chart.getSortedVisibleDatasetMetas(); + for(let i = metasets.length - 1; i >= 0; --i){ + const source = metasets[i].$filler; + if (_shouldApplyFill(source)) { + _drawfill(chart.ctx, source, chart.chartArea); + } + } + }, + beforeDatasetDraw (chart, args, options) { + const source = args.meta.$filler; + if (!_shouldApplyFill(source) || options.drawTime !== 'beforeDatasetDraw') { + return; + } + _drawfill(chart.ctx, source, chart.chartArea); + }, + defaults: { + propagate: true, + drawTime: 'beforeDatasetDraw' + } +}; + +const getBoxSize = (labelOpts, fontSize)=>{ + let { boxHeight =fontSize , boxWidth =fontSize } = labelOpts; + if (labelOpts.usePointStyle) { + boxHeight = Math.min(boxHeight, fontSize); + boxWidth = labelOpts.pointStyleWidth || Math.min(boxWidth, fontSize); + } + return { + boxWidth, + boxHeight, + itemHeight: Math.max(fontSize, boxHeight) + }; +}; +const itemsEqual = (a, b)=>a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index; +class Legend extends Element { + constructor(config){ + super(); + this._added = false; + this.legendHitBoxes = []; + this._hoveredItem = null; + this.doughnutMode = false; + this.chart = config.chart; + this.options = config.options; + this.ctx = config.ctx; + this.legendItems = undefined; + this.columnSizes = undefined; + this.lineWidths = undefined; + this.maxHeight = undefined; + this.maxWidth = undefined; + this.top = undefined; + this.bottom = undefined; + this.left = undefined; + this.right = undefined; + this.height = undefined; + this.width = undefined; + this._margins = undefined; + this.position = undefined; + this.weight = undefined; + this.fullSize = undefined; + } + update(maxWidth, maxHeight, margins) { + this.maxWidth = maxWidth; + this.maxHeight = maxHeight; + this._margins = margins; + this.setDimensions(); + this.buildLabels(); + this.fit(); + } + setDimensions() { + if (this.isHorizontal()) { + this.width = this.maxWidth; + this.left = this._margins.left; + this.right = this.width; + } else { + this.height = this.maxHeight; + this.top = this._margins.top; + this.bottom = this.height; + } + } + buildLabels() { + const labelOpts = this.options.labels || {}; + let legendItems = helpers_dataset.callback(labelOpts.generateLabels, [ + this.chart + ], this) || []; + if (labelOpts.filter) { + legendItems = legendItems.filter((item)=>labelOpts.filter(item, this.chart.data)); + } + if (labelOpts.sort) { + legendItems = legendItems.sort((a, b)=>labelOpts.sort(a, b, this.chart.data)); + } + if (this.options.reverse) { + legendItems.reverse(); + } + this.legendItems = legendItems; + } + fit() { + const { options , ctx } = this; + if (!options.display) { + this.width = this.height = 0; + return; + } + const labelOpts = options.labels; + const labelFont = helpers_dataset.toFont(labelOpts.font); + const fontSize = labelFont.size; + const titleHeight = this._computeTitleHeight(); + const { boxWidth , itemHeight } = getBoxSize(labelOpts, fontSize); + let width, height; + ctx.font = labelFont.string; + if (this.isHorizontal()) { + width = this.maxWidth; + height = this._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10; + } else { + height = this.maxHeight; + width = this._fitCols(titleHeight, labelFont, boxWidth, itemHeight) + 10; + } + this.width = Math.min(width, options.maxWidth || this.maxWidth); + this.height = Math.min(height, options.maxHeight || this.maxHeight); + } + _fitRows(titleHeight, fontSize, boxWidth, itemHeight) { + const { ctx , maxWidth , options: { labels: { padding } } } = this; + const hitboxes = this.legendHitBoxes = []; + const lineWidths = this.lineWidths = [ + 0 + ]; + const lineHeight = itemHeight + padding; + let totalHeight = titleHeight; + ctx.textAlign = 'left'; + ctx.textBaseline = 'middle'; + let row = -1; + let top = -lineHeight; + this.legendItems.forEach((legendItem, i)=>{ + const itemWidth = boxWidth + fontSize / 2 + ctx.measureText(legendItem.text).width; + if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) { + totalHeight += lineHeight; + lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0; + top += lineHeight; + row++; + } + hitboxes[i] = { + left: 0, + top, + row, + width: itemWidth, + height: itemHeight + }; + lineWidths[lineWidths.length - 1] += itemWidth + padding; + }); + return totalHeight; + } + _fitCols(titleHeight, labelFont, boxWidth, _itemHeight) { + const { ctx , maxHeight , options: { labels: { padding } } } = this; + const hitboxes = this.legendHitBoxes = []; + const columnSizes = this.columnSizes = []; + const heightLimit = maxHeight - titleHeight; + let totalWidth = padding; + let currentColWidth = 0; + let currentColHeight = 0; + let left = 0; + let col = 0; + this.legendItems.forEach((legendItem, i)=>{ + const { itemWidth , itemHeight } = calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight); + if (i > 0 && currentColHeight + itemHeight + 2 * padding > heightLimit) { + totalWidth += currentColWidth + padding; + columnSizes.push({ + width: currentColWidth, + height: currentColHeight + }); + left += currentColWidth + padding; + col++; + currentColWidth = currentColHeight = 0; + } + hitboxes[i] = { + left, + top: currentColHeight, + col, + width: itemWidth, + height: itemHeight + }; + currentColWidth = Math.max(currentColWidth, itemWidth); + currentColHeight += itemHeight + padding; + }); + totalWidth += currentColWidth; + columnSizes.push({ + width: currentColWidth, + height: currentColHeight + }); + return totalWidth; + } + adjustHitBoxes() { + if (!this.options.display) { + return; + } + const titleHeight = this._computeTitleHeight(); + const { legendHitBoxes: hitboxes , options: { align , labels: { padding } , rtl } } = this; + const rtlHelper = helpers_dataset.getRtlAdapter(rtl, this.left, this.width); + if (this.isHorizontal()) { + let row = 0; + let left = helpers_dataset._alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]); + for (const hitbox of hitboxes){ + if (row !== hitbox.row) { + row = hitbox.row; + left = helpers_dataset._alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]); + } + hitbox.top += this.top + titleHeight + padding; + hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(left), hitbox.width); + left += hitbox.width + padding; + } + } else { + let col = 0; + let top = helpers_dataset._alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height); + for (const hitbox of hitboxes){ + if (hitbox.col !== col) { + col = hitbox.col; + top = helpers_dataset._alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height); + } + hitbox.top = top; + hitbox.left += this.left + padding; + hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(hitbox.left), hitbox.width); + top += hitbox.height + padding; + } + } + } + isHorizontal() { + return this.options.position === 'top' || this.options.position === 'bottom'; + } + draw() { + if (this.options.display) { + const ctx = this.ctx; + helpers_dataset.clipArea(ctx, this); + this._draw(); + helpers_dataset.unclipArea(ctx); + } + } + _draw() { + const { options: opts , columnSizes , lineWidths , ctx } = this; + const { align , labels: labelOpts } = opts; + const defaultColor = helpers_dataset.defaults.color; + const rtlHelper = helpers_dataset.getRtlAdapter(opts.rtl, this.left, this.width); + const labelFont = helpers_dataset.toFont(labelOpts.font); + const { padding } = labelOpts; + const fontSize = labelFont.size; + const halfFontSize = fontSize / 2; + let cursor; + this.drawTitle(); + ctx.textAlign = rtlHelper.textAlign('left'); + ctx.textBaseline = 'middle'; + ctx.lineWidth = 0.5; + ctx.font = labelFont.string; + const { boxWidth , boxHeight , itemHeight } = getBoxSize(labelOpts, fontSize); + const drawLegendBox = function(x, y, legendItem) { + if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) { + return; + } + ctx.save(); + const lineWidth = helpers_dataset.valueOrDefault(legendItem.lineWidth, 1); + ctx.fillStyle = helpers_dataset.valueOrDefault(legendItem.fillStyle, defaultColor); + ctx.lineCap = helpers_dataset.valueOrDefault(legendItem.lineCap, 'butt'); + ctx.lineDashOffset = helpers_dataset.valueOrDefault(legendItem.lineDashOffset, 0); + ctx.lineJoin = helpers_dataset.valueOrDefault(legendItem.lineJoin, 'miter'); + ctx.lineWidth = lineWidth; + ctx.strokeStyle = helpers_dataset.valueOrDefault(legendItem.strokeStyle, defaultColor); + ctx.setLineDash(helpers_dataset.valueOrDefault(legendItem.lineDash, [])); + if (labelOpts.usePointStyle) { + const drawOptions = { + radius: boxHeight * Math.SQRT2 / 2, + pointStyle: legendItem.pointStyle, + rotation: legendItem.rotation, + borderWidth: lineWidth + }; + const centerX = rtlHelper.xPlus(x, boxWidth / 2); + const centerY = y + halfFontSize; + helpers_dataset.drawPointLegend(ctx, drawOptions, centerX, centerY, labelOpts.pointStyleWidth && boxWidth); + } else { + const yBoxTop = y + Math.max((fontSize - boxHeight) / 2, 0); + const xBoxLeft = rtlHelper.leftForLtr(x, boxWidth); + const borderRadius = helpers_dataset.toTRBLCorners(legendItem.borderRadius); + ctx.beginPath(); + if (Object.values(borderRadius).some((v)=>v !== 0)) { + helpers_dataset.addRoundedRectPath(ctx, { + x: xBoxLeft, + y: yBoxTop, + w: boxWidth, + h: boxHeight, + radius: borderRadius + }); + } else { + ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight); + } + ctx.fill(); + if (lineWidth !== 0) { + ctx.stroke(); + } + } + ctx.restore(); + }; + const fillText = function(x, y, legendItem) { + helpers_dataset.renderText(ctx, legendItem.text, x, y + itemHeight / 2, labelFont, { + strikethrough: legendItem.hidden, + textAlign: rtlHelper.textAlign(legendItem.textAlign) + }); + }; + const isHorizontal = this.isHorizontal(); + const titleHeight = this._computeTitleHeight(); + if (isHorizontal) { + cursor = { + x: helpers_dataset._alignStartEnd(align, this.left + padding, this.right - lineWidths[0]), + y: this.top + padding + titleHeight, + line: 0 + }; + } else { + cursor = { + x: this.left + padding, + y: helpers_dataset._alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[0].height), + line: 0 + }; + } + helpers_dataset.overrideTextDirection(this.ctx, opts.textDirection); + const lineHeight = itemHeight + padding; + this.legendItems.forEach((legendItem, i)=>{ + ctx.strokeStyle = legendItem.fontColor; + ctx.fillStyle = legendItem.fontColor; + const textWidth = ctx.measureText(legendItem.text).width; + const textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign)); + const width = boxWidth + halfFontSize + textWidth; + let x = cursor.x; + let y = cursor.y; + rtlHelper.setWidth(this.width); + if (isHorizontal) { + if (i > 0 && x + width + padding > this.right) { + y = cursor.y += lineHeight; + cursor.line++; + x = cursor.x = helpers_dataset._alignStartEnd(align, this.left + padding, this.right - lineWidths[cursor.line]); + } + } else if (i > 0 && y + lineHeight > this.bottom) { + x = cursor.x = x + columnSizes[cursor.line].width + padding; + cursor.line++; + y = cursor.y = helpers_dataset._alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[cursor.line].height); + } + const realX = rtlHelper.x(x); + drawLegendBox(realX, y, legendItem); + x = helpers_dataset._textX(textAlign, x + boxWidth + halfFontSize, isHorizontal ? x + width : this.right, opts.rtl); + fillText(rtlHelper.x(x), y, legendItem); + if (isHorizontal) { + cursor.x += width + padding; + } else if (typeof legendItem.text !== 'string') { + const fontLineHeight = labelFont.lineHeight; + cursor.y += calculateLegendItemHeight(legendItem, fontLineHeight) + padding; + } else { + cursor.y += lineHeight; + } + }); + helpers_dataset.restoreTextDirection(this.ctx, opts.textDirection); + } + drawTitle() { + const opts = this.options; + const titleOpts = opts.title; + const titleFont = helpers_dataset.toFont(titleOpts.font); + const titlePadding = helpers_dataset.toPadding(titleOpts.padding); + if (!titleOpts.display) { + return; + } + const rtlHelper = helpers_dataset.getRtlAdapter(opts.rtl, this.left, this.width); + const ctx = this.ctx; + const position = titleOpts.position; + const halfFontSize = titleFont.size / 2; + const topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize; + let y; + let left = this.left; + let maxWidth = this.width; + if (this.isHorizontal()) { + maxWidth = Math.max(...this.lineWidths); + y = this.top + topPaddingPlusHalfFontSize; + left = helpers_dataset._alignStartEnd(opts.align, left, this.right - maxWidth); + } else { + const maxHeight = this.columnSizes.reduce((acc, size)=>Math.max(acc, size.height), 0); + y = topPaddingPlusHalfFontSize + helpers_dataset._alignStartEnd(opts.align, this.top, this.bottom - maxHeight - opts.labels.padding - this._computeTitleHeight()); + } + const x = helpers_dataset._alignStartEnd(position, left, left + maxWidth); + ctx.textAlign = rtlHelper.textAlign(helpers_dataset._toLeftRightCenter(position)); + ctx.textBaseline = 'middle'; + ctx.strokeStyle = titleOpts.color; + ctx.fillStyle = titleOpts.color; + ctx.font = titleFont.string; + helpers_dataset.renderText(ctx, titleOpts.text, x, y, titleFont); + } + _computeTitleHeight() { + const titleOpts = this.options.title; + const titleFont = helpers_dataset.toFont(titleOpts.font); + const titlePadding = helpers_dataset.toPadding(titleOpts.padding); + return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0; + } + _getLegendItemAt(x, y) { + let i, hitBox, lh; + if (helpers_dataset._isBetween(x, this.left, this.right) && helpers_dataset._isBetween(y, this.top, this.bottom)) { + lh = this.legendHitBoxes; + for(i = 0; i < lh.length; ++i){ + hitBox = lh[i]; + if (helpers_dataset._isBetween(x, hitBox.left, hitBox.left + hitBox.width) && helpers_dataset._isBetween(y, hitBox.top, hitBox.top + hitBox.height)) { + return this.legendItems[i]; + } + } + } + return null; + } + handleEvent(e) { + const opts = this.options; + if (!isListened(e.type, opts)) { + return; + } + const hoveredItem = this._getLegendItemAt(e.x, e.y); + if (e.type === 'mousemove' || e.type === 'mouseout') { + const previous = this._hoveredItem; + const sameItem = itemsEqual(previous, hoveredItem); + if (previous && !sameItem) { + helpers_dataset.callback(opts.onLeave, [ + e, + previous, + this + ], this); + } + this._hoveredItem = hoveredItem; + if (hoveredItem && !sameItem) { + helpers_dataset.callback(opts.onHover, [ + e, + hoveredItem, + this + ], this); + } + } else if (hoveredItem) { + helpers_dataset.callback(opts.onClick, [ + e, + hoveredItem, + this + ], this); + } + } +} +function calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight) { + const itemWidth = calculateItemWidth(legendItem, boxWidth, labelFont, ctx); + const itemHeight = calculateItemHeight(_itemHeight, legendItem, labelFont.lineHeight); + return { + itemWidth, + itemHeight + }; +} +function calculateItemWidth(legendItem, boxWidth, labelFont, ctx) { + let legendItemText = legendItem.text; + if (legendItemText && typeof legendItemText !== 'string') { + legendItemText = legendItemText.reduce((a, b)=>a.length > b.length ? a : b); + } + return boxWidth + labelFont.size / 2 + ctx.measureText(legendItemText).width; +} +function calculateItemHeight(_itemHeight, legendItem, fontLineHeight) { + let itemHeight = _itemHeight; + if (typeof legendItem.text !== 'string') { + itemHeight = calculateLegendItemHeight(legendItem, fontLineHeight); + } + return itemHeight; +} +function calculateLegendItemHeight(legendItem, fontLineHeight) { + const labelHeight = legendItem.text ? legendItem.text.length : 0; + return fontLineHeight * labelHeight; +} +function isListened(type, opts) { + if ((type === 'mousemove' || type === 'mouseout') && (opts.onHover || opts.onLeave)) { + return true; + } + if (opts.onClick && (type === 'click' || type === 'mouseup')) { + return true; + } + return false; +} +var plugin_legend = { + id: 'legend', + _element: Legend, + start (chart, _args, options) { + const legend = chart.legend = new Legend({ + ctx: chart.ctx, + options, + chart + }); + layouts.configure(chart, legend, options); + layouts.addBox(chart, legend); + }, + stop (chart) { + layouts.removeBox(chart, chart.legend); + delete chart.legend; + }, + beforeUpdate (chart, _args, options) { + const legend = chart.legend; + layouts.configure(chart, legend, options); + legend.options = options; + }, + afterUpdate (chart) { + const legend = chart.legend; + legend.buildLabels(); + legend.adjustHitBoxes(); + }, + afterEvent (chart, args) { + if (!args.replay) { + chart.legend.handleEvent(args.event); + } + }, + defaults: { + display: true, + position: 'top', + align: 'center', + fullSize: true, + reverse: false, + weight: 1000, + onClick (e, legendItem, legend) { + const index = legendItem.datasetIndex; + const ci = legend.chart; + if (ci.isDatasetVisible(index)) { + ci.hide(index); + legendItem.hidden = true; + } else { + ci.show(index); + legendItem.hidden = false; + } + }, + onHover: null, + onLeave: null, + labels: { + color: (ctx)=>ctx.chart.options.color, + boxWidth: 40, + padding: 10, + generateLabels (chart) { + const datasets = chart.data.datasets; + const { labels: { usePointStyle , pointStyle , textAlign , color , useBorderRadius , borderRadius } } = chart.legend.options; + return chart._getSortedDatasetMetas().map((meta)=>{ + const style = meta.controller.getStyle(usePointStyle ? 0 : undefined); + const borderWidth = helpers_dataset.toPadding(style.borderWidth); + return { + text: datasets[meta.index].label, + fillStyle: style.backgroundColor, + fontColor: color, + hidden: !meta.visible, + lineCap: style.borderCapStyle, + lineDash: style.borderDash, + lineDashOffset: style.borderDashOffset, + lineJoin: style.borderJoinStyle, + lineWidth: (borderWidth.width + borderWidth.height) / 4, + strokeStyle: style.borderColor, + pointStyle: pointStyle || style.pointStyle, + rotation: style.rotation, + textAlign: textAlign || style.textAlign, + borderRadius: useBorderRadius && (borderRadius || style.borderRadius), + datasetIndex: meta.index + }; + }, this); + } + }, + title: { + color: (ctx)=>ctx.chart.options.color, + display: false, + position: 'center', + text: '' + } + }, + descriptors: { + _scriptable: (name)=>!name.startsWith('on'), + labels: { + _scriptable: (name)=>![ + 'generateLabels', + 'filter', + 'sort' + ].includes(name) + } + } +}; + +class Title extends Element { + constructor(config){ + super(); + this.chart = config.chart; + this.options = config.options; + this.ctx = config.ctx; + this._padding = undefined; + this.top = undefined; + this.bottom = undefined; + this.left = undefined; + this.right = undefined; + this.width = undefined; + this.height = undefined; + this.position = undefined; + this.weight = undefined; + this.fullSize = undefined; + } + update(maxWidth, maxHeight) { + const opts = this.options; + this.left = 0; + this.top = 0; + if (!opts.display) { + this.width = this.height = this.right = this.bottom = 0; + return; + } + this.width = this.right = maxWidth; + this.height = this.bottom = maxHeight; + const lineCount = helpers_dataset.isArray(opts.text) ? opts.text.length : 1; + this._padding = helpers_dataset.toPadding(opts.padding); + const textSize = lineCount * helpers_dataset.toFont(opts.font).lineHeight + this._padding.height; + if (this.isHorizontal()) { + this.height = textSize; + } else { + this.width = textSize; + } + } + isHorizontal() { + const pos = this.options.position; + return pos === 'top' || pos === 'bottom'; + } + _drawArgs(offset) { + const { top , left , bottom , right , options } = this; + const align = options.align; + let rotation = 0; + let maxWidth, titleX, titleY; + if (this.isHorizontal()) { + titleX = helpers_dataset._alignStartEnd(align, left, right); + titleY = top + offset; + maxWidth = right - left; + } else { + if (options.position === 'left') { + titleX = left + offset; + titleY = helpers_dataset._alignStartEnd(align, bottom, top); + rotation = helpers_dataset.PI * -0.5; + } else { + titleX = right - offset; + titleY = helpers_dataset._alignStartEnd(align, top, bottom); + rotation = helpers_dataset.PI * 0.5; + } + maxWidth = bottom - top; + } + return { + titleX, + titleY, + maxWidth, + rotation + }; + } + draw() { + const ctx = this.ctx; + const opts = this.options; + if (!opts.display) { + return; + } + const fontOpts = helpers_dataset.toFont(opts.font); + const lineHeight = fontOpts.lineHeight; + const offset = lineHeight / 2 + this._padding.top; + const { titleX , titleY , maxWidth , rotation } = this._drawArgs(offset); + helpers_dataset.renderText(ctx, opts.text, 0, 0, fontOpts, { + color: opts.color, + maxWidth, + rotation, + textAlign: helpers_dataset._toLeftRightCenter(opts.align), + textBaseline: 'middle', + translation: [ + titleX, + titleY + ] + }); + } +} +function createTitle(chart, titleOpts) { + const title = new Title({ + ctx: chart.ctx, + options: titleOpts, + chart + }); + layouts.configure(chart, title, titleOpts); + layouts.addBox(chart, title); + chart.titleBlock = title; +} +var plugin_title = { + id: 'title', + _element: Title, + start (chart, _args, options) { + createTitle(chart, options); + }, + stop (chart) { + const titleBlock = chart.titleBlock; + layouts.removeBox(chart, titleBlock); + delete chart.titleBlock; + }, + beforeUpdate (chart, _args, options) { + const title = chart.titleBlock; + layouts.configure(chart, title, options); + title.options = options; + }, + defaults: { + align: 'center', + display: false, + font: { + weight: 'bold' + }, + fullSize: true, + padding: 10, + position: 'top', + text: '', + weight: 2000 + }, + defaultRoutes: { + color: 'color' + }, + descriptors: { + _scriptable: true, + _indexable: false + } +}; + +const map = new WeakMap(); +var plugin_subtitle = { + id: 'subtitle', + start (chart, _args, options) { + const title = new Title({ + ctx: chart.ctx, + options, + chart + }); + layouts.configure(chart, title, options); + layouts.addBox(chart, title); + map.set(chart, title); + }, + stop (chart) { + layouts.removeBox(chart, map.get(chart)); + map.delete(chart); + }, + beforeUpdate (chart, _args, options) { + const title = map.get(chart); + layouts.configure(chart, title, options); + title.options = options; + }, + defaults: { + align: 'center', + display: false, + font: { + weight: 'normal' + }, + fullSize: true, + padding: 0, + position: 'top', + text: '', + weight: 1500 + }, + defaultRoutes: { + color: 'color' + }, + descriptors: { + _scriptable: true, + _indexable: false + } +}; + +const positioners = { + average (items) { + if (!items.length) { + return false; + } + let i, len; + let xSet = new Set(); + let y = 0; + let count = 0; + for(i = 0, len = items.length; i < len; ++i){ + const el = items[i].element; + if (el && el.hasValue()) { + const pos = el.tooltipPosition(); + xSet.add(pos.x); + y += pos.y; + ++count; + } + } + if (count === 0 || xSet.size === 0) { + return false; + } + const xAverage = [ + ...xSet + ].reduce((a, b)=>a + b) / xSet.size; + return { + x: xAverage, + y: y / count + }; + }, + nearest (items, eventPosition) { + if (!items.length) { + return false; + } + let x = eventPosition.x; + let y = eventPosition.y; + let minDistance = Number.POSITIVE_INFINITY; + let i, len, nearestElement; + for(i = 0, len = items.length; i < len; ++i){ + const el = items[i].element; + if (el && el.hasValue()) { + const center = el.getCenterPoint(); + const d = helpers_dataset.distanceBetweenPoints(eventPosition, center); + if (d < minDistance) { + minDistance = d; + nearestElement = el; + } + } + } + if (nearestElement) { + const tp = nearestElement.tooltipPosition(); + x = tp.x; + y = tp.y; + } + return { + x, + y + }; + } +}; +function pushOrConcat(base, toPush) { + if (toPush) { + if (helpers_dataset.isArray(toPush)) { + Array.prototype.push.apply(base, toPush); + } else { + base.push(toPush); + } + } + return base; +} + function splitNewlines(str) { + if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) { + return str.split('\n'); + } + return str; +} + function createTooltipItem(chart, item) { + const { element , datasetIndex , index } = item; + const controller = chart.getDatasetMeta(datasetIndex).controller; + const { label , value } = controller.getLabelAndValue(index); + return { + chart, + label, + parsed: controller.getParsed(index), + raw: chart.data.datasets[datasetIndex].data[index], + formattedValue: value, + dataset: controller.getDataset(), + dataIndex: index, + datasetIndex, + element + }; +} + function getTooltipSize(tooltip, options) { + const ctx = tooltip.chart.ctx; + const { body , footer , title } = tooltip; + const { boxWidth , boxHeight } = options; + const bodyFont = helpers_dataset.toFont(options.bodyFont); + const titleFont = helpers_dataset.toFont(options.titleFont); + const footerFont = helpers_dataset.toFont(options.footerFont); + const titleLineCount = title.length; + const footerLineCount = footer.length; + const bodyLineItemCount = body.length; + const padding = helpers_dataset.toPadding(options.padding); + let height = padding.height; + let width = 0; + let combinedBodyLength = body.reduce((count, bodyItem)=>count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length, 0); + combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length; + if (titleLineCount) { + height += titleLineCount * titleFont.lineHeight + (titleLineCount - 1) * options.titleSpacing + options.titleMarginBottom; + } + if (combinedBodyLength) { + const bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight; + height += bodyLineItemCount * bodyLineHeight + (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight + (combinedBodyLength - 1) * options.bodySpacing; + } + if (footerLineCount) { + height += options.footerMarginTop + footerLineCount * footerFont.lineHeight + (footerLineCount - 1) * options.footerSpacing; + } + let widthPadding = 0; + const maxLineWidth = function(line) { + width = Math.max(width, ctx.measureText(line).width + widthPadding); + }; + ctx.save(); + ctx.font = titleFont.string; + helpers_dataset.each(tooltip.title, maxLineWidth); + ctx.font = bodyFont.string; + helpers_dataset.each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth); + widthPadding = options.displayColors ? boxWidth + 2 + options.boxPadding : 0; + helpers_dataset.each(body, (bodyItem)=>{ + helpers_dataset.each(bodyItem.before, maxLineWidth); + helpers_dataset.each(bodyItem.lines, maxLineWidth); + helpers_dataset.each(bodyItem.after, maxLineWidth); + }); + widthPadding = 0; + ctx.font = footerFont.string; + helpers_dataset.each(tooltip.footer, maxLineWidth); + ctx.restore(); + width += padding.width; + return { + width, + height + }; +} +function determineYAlign(chart, size) { + const { y , height } = size; + if (y < height / 2) { + return 'top'; + } else if (y > chart.height - height / 2) { + return 'bottom'; + } + return 'center'; +} +function doesNotFitWithAlign(xAlign, chart, options, size) { + const { x , width } = size; + const caret = options.caretSize + options.caretPadding; + if (xAlign === 'left' && x + width + caret > chart.width) { + return true; + } + if (xAlign === 'right' && x - width - caret < 0) { + return true; + } +} +function determineXAlign(chart, options, size, yAlign) { + const { x , width } = size; + const { width: chartWidth , chartArea: { left , right } } = chart; + let xAlign = 'center'; + if (yAlign === 'center') { + xAlign = x <= (left + right) / 2 ? 'left' : 'right'; + } else if (x <= width / 2) { + xAlign = 'left'; + } else if (x >= chartWidth - width / 2) { + xAlign = 'right'; + } + if (doesNotFitWithAlign(xAlign, chart, options, size)) { + xAlign = 'center'; + } + return xAlign; +} + function determineAlignment(chart, options, size) { + const yAlign = size.yAlign || options.yAlign || determineYAlign(chart, size); + return { + xAlign: size.xAlign || options.xAlign || determineXAlign(chart, options, size, yAlign), + yAlign + }; +} +function alignX(size, xAlign) { + let { x , width } = size; + if (xAlign === 'right') { + x -= width; + } else if (xAlign === 'center') { + x -= width / 2; + } + return x; +} +function alignY(size, yAlign, paddingAndSize) { + let { y , height } = size; + if (yAlign === 'top') { + y += paddingAndSize; + } else if (yAlign === 'bottom') { + y -= height + paddingAndSize; + } else { + y -= height / 2; + } + return y; +} + function getBackgroundPoint(options, size, alignment, chart) { + const { caretSize , caretPadding , cornerRadius } = options; + const { xAlign , yAlign } = alignment; + const paddingAndSize = caretSize + caretPadding; + const { topLeft , topRight , bottomLeft , bottomRight } = helpers_dataset.toTRBLCorners(cornerRadius); + let x = alignX(size, xAlign); + const y = alignY(size, yAlign, paddingAndSize); + if (yAlign === 'center') { + if (xAlign === 'left') { + x += paddingAndSize; + } else if (xAlign === 'right') { + x -= paddingAndSize; + } + } else if (xAlign === 'left') { + x -= Math.max(topLeft, bottomLeft) + caretSize; + } else if (xAlign === 'right') { + x += Math.max(topRight, bottomRight) + caretSize; + } + return { + x: helpers_dataset._limitValue(x, 0, chart.width - size.width), + y: helpers_dataset._limitValue(y, 0, chart.height - size.height) + }; +} +function getAlignedX(tooltip, align, options) { + const padding = helpers_dataset.toPadding(options.padding); + return align === 'center' ? tooltip.x + tooltip.width / 2 : align === 'right' ? tooltip.x + tooltip.width - padding.right : tooltip.x + padding.left; +} + function getBeforeAfterBodyLines(callback) { + return pushOrConcat([], splitNewlines(callback)); +} +function createTooltipContext(parent, tooltip, tooltipItems) { + return helpers_dataset.createContext(parent, { + tooltip, + tooltipItems, + type: 'tooltip' + }); +} +function overrideCallbacks(callbacks, context) { + const override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks; + return override ? callbacks.override(override) : callbacks; +} +const defaultCallbacks = { + beforeTitle: helpers_dataset.noop, + title (tooltipItems) { + if (tooltipItems.length > 0) { + const item = tooltipItems[0]; + const labels = item.chart.data.labels; + const labelCount = labels ? labels.length : 0; + if (this && this.options && this.options.mode === 'dataset') { + return item.dataset.label || ''; + } else if (item.label) { + return item.label; + } else if (labelCount > 0 && item.dataIndex < labelCount) { + return labels[item.dataIndex]; + } + } + return ''; + }, + afterTitle: helpers_dataset.noop, + beforeBody: helpers_dataset.noop, + beforeLabel: helpers_dataset.noop, + label (tooltipItem) { + if (this && this.options && this.options.mode === 'dataset') { + return tooltipItem.label + ': ' + tooltipItem.formattedValue || tooltipItem.formattedValue; + } + let label = tooltipItem.dataset.label || ''; + if (label) { + label += ': '; + } + const value = tooltipItem.formattedValue; + if (!helpers_dataset.isNullOrUndef(value)) { + label += value; + } + return label; + }, + labelColor (tooltipItem) { + const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex); + const options = meta.controller.getStyle(tooltipItem.dataIndex); + return { + borderColor: options.borderColor, + backgroundColor: options.backgroundColor, + borderWidth: options.borderWidth, + borderDash: options.borderDash, + borderDashOffset: options.borderDashOffset, + borderRadius: 0 + }; + }, + labelTextColor () { + return this.options.bodyColor; + }, + labelPointStyle (tooltipItem) { + const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex); + const options = meta.controller.getStyle(tooltipItem.dataIndex); + return { + pointStyle: options.pointStyle, + rotation: options.rotation + }; + }, + afterLabel: helpers_dataset.noop, + afterBody: helpers_dataset.noop, + beforeFooter: helpers_dataset.noop, + footer: helpers_dataset.noop, + afterFooter: helpers_dataset.noop +}; + function invokeCallbackWithFallback(callbacks, name, ctx, arg) { + const result = callbacks[name].call(ctx, arg); + if (typeof result === 'undefined') { + return defaultCallbacks[name].call(ctx, arg); + } + return result; +} +class Tooltip extends Element { + static positioners = positioners; + constructor(config){ + super(); + this.opacity = 0; + this._active = []; + this._eventPosition = undefined; + this._size = undefined; + this._cachedAnimations = undefined; + this._tooltipItems = []; + this.$animations = undefined; + this.$context = undefined; + this.chart = config.chart; + this.options = config.options; + this.dataPoints = undefined; + this.title = undefined; + this.beforeBody = undefined; + this.body = undefined; + this.afterBody = undefined; + this.footer = undefined; + this.xAlign = undefined; + this.yAlign = undefined; + this.x = undefined; + this.y = undefined; + this.height = undefined; + this.width = undefined; + this.caretX = undefined; + this.caretY = undefined; + this.labelColors = undefined; + this.labelPointStyles = undefined; + this.labelTextColors = undefined; + } + initialize(options) { + this.options = options; + this._cachedAnimations = undefined; + this.$context = undefined; + } + _resolveAnimations() { + const cached = this._cachedAnimations; + if (cached) { + return cached; + } + const chart = this.chart; + const options = this.options.setContext(this.getContext()); + const opts = options.enabled && chart.options.animation && options.animations; + const animations = new Animations(this.chart, opts); + if (opts._cacheable) { + this._cachedAnimations = Object.freeze(animations); + } + return animations; + } + getContext() { + return this.$context || (this.$context = createTooltipContext(this.chart.getContext(), this, this._tooltipItems)); + } + getTitle(context, options) { + const { callbacks } = options; + const beforeTitle = invokeCallbackWithFallback(callbacks, 'beforeTitle', this, context); + const title = invokeCallbackWithFallback(callbacks, 'title', this, context); + const afterTitle = invokeCallbackWithFallback(callbacks, 'afterTitle', this, context); + let lines = []; + lines = pushOrConcat(lines, splitNewlines(beforeTitle)); + lines = pushOrConcat(lines, splitNewlines(title)); + lines = pushOrConcat(lines, splitNewlines(afterTitle)); + return lines; + } + getBeforeBody(tooltipItems, options) { + return getBeforeAfterBodyLines(invokeCallbackWithFallback(options.callbacks, 'beforeBody', this, tooltipItems)); + } + getBody(tooltipItems, options) { + const { callbacks } = options; + const bodyItems = []; + helpers_dataset.each(tooltipItems, (context)=>{ + const bodyItem = { + before: [], + lines: [], + after: [] + }; + const scoped = overrideCallbacks(callbacks, context); + pushOrConcat(bodyItem.before, splitNewlines(invokeCallbackWithFallback(scoped, 'beforeLabel', this, context))); + pushOrConcat(bodyItem.lines, invokeCallbackWithFallback(scoped, 'label', this, context)); + pushOrConcat(bodyItem.after, splitNewlines(invokeCallbackWithFallback(scoped, 'afterLabel', this, context))); + bodyItems.push(bodyItem); + }); + return bodyItems; + } + getAfterBody(tooltipItems, options) { + return getBeforeAfterBodyLines(invokeCallbackWithFallback(options.callbacks, 'afterBody', this, tooltipItems)); + } + getFooter(tooltipItems, options) { + const { callbacks } = options; + const beforeFooter = invokeCallbackWithFallback(callbacks, 'beforeFooter', this, tooltipItems); + const footer = invokeCallbackWithFallback(callbacks, 'footer', this, tooltipItems); + const afterFooter = invokeCallbackWithFallback(callbacks, 'afterFooter', this, tooltipItems); + let lines = []; + lines = pushOrConcat(lines, splitNewlines(beforeFooter)); + lines = pushOrConcat(lines, splitNewlines(footer)); + lines = pushOrConcat(lines, splitNewlines(afterFooter)); + return lines; + } + _createItems(options) { + const active = this._active; + const data = this.chart.data; + const labelColors = []; + const labelPointStyles = []; + const labelTextColors = []; + let tooltipItems = []; + let i, len; + for(i = 0, len = active.length; i < len; ++i){ + tooltipItems.push(createTooltipItem(this.chart, active[i])); + } + if (options.filter) { + tooltipItems = tooltipItems.filter((element, index, array)=>options.filter(element, index, array, data)); + } + if (options.itemSort) { + tooltipItems = tooltipItems.sort((a, b)=>options.itemSort(a, b, data)); + } + helpers_dataset.each(tooltipItems, (context)=>{ + const scoped = overrideCallbacks(options.callbacks, context); + labelColors.push(invokeCallbackWithFallback(scoped, 'labelColor', this, context)); + labelPointStyles.push(invokeCallbackWithFallback(scoped, 'labelPointStyle', this, context)); + labelTextColors.push(invokeCallbackWithFallback(scoped, 'labelTextColor', this, context)); + }); + this.labelColors = labelColors; + this.labelPointStyles = labelPointStyles; + this.labelTextColors = labelTextColors; + this.dataPoints = tooltipItems; + return tooltipItems; + } + update(changed, replay) { + const options = this.options.setContext(this.getContext()); + const active = this._active; + let properties; + let tooltipItems = []; + if (!active.length) { + if (this.opacity !== 0) { + properties = { + opacity: 0 + }; + } + } else { + const position = positioners[options.position].call(this, active, this._eventPosition); + tooltipItems = this._createItems(options); + this.title = this.getTitle(tooltipItems, options); + this.beforeBody = this.getBeforeBody(tooltipItems, options); + this.body = this.getBody(tooltipItems, options); + this.afterBody = this.getAfterBody(tooltipItems, options); + this.footer = this.getFooter(tooltipItems, options); + const size = this._size = getTooltipSize(this, options); + const positionAndSize = Object.assign({}, position, size); + const alignment = determineAlignment(this.chart, options, positionAndSize); + const backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, this.chart); + this.xAlign = alignment.xAlign; + this.yAlign = alignment.yAlign; + properties = { + opacity: 1, + x: backgroundPoint.x, + y: backgroundPoint.y, + width: size.width, + height: size.height, + caretX: position.x, + caretY: position.y + }; + } + this._tooltipItems = tooltipItems; + this.$context = undefined; + if (properties) { + this._resolveAnimations().update(this, properties); + } + if (changed && options.external) { + options.external.call(this, { + chart: this.chart, + tooltip: this, + replay + }); + } + } + drawCaret(tooltipPoint, ctx, size, options) { + const caretPosition = this.getCaretPosition(tooltipPoint, size, options); + ctx.lineTo(caretPosition.x1, caretPosition.y1); + ctx.lineTo(caretPosition.x2, caretPosition.y2); + ctx.lineTo(caretPosition.x3, caretPosition.y3); + } + getCaretPosition(tooltipPoint, size, options) { + const { xAlign , yAlign } = this; + const { caretSize , cornerRadius } = options; + const { topLeft , topRight , bottomLeft , bottomRight } = helpers_dataset.toTRBLCorners(cornerRadius); + const { x: ptX , y: ptY } = tooltipPoint; + const { width , height } = size; + let x1, x2, x3, y1, y2, y3; + if (yAlign === 'center') { + y2 = ptY + height / 2; + if (xAlign === 'left') { + x1 = ptX; + x2 = x1 - caretSize; + y1 = y2 + caretSize; + y3 = y2 - caretSize; + } else { + x1 = ptX + width; + x2 = x1 + caretSize; + y1 = y2 - caretSize; + y3 = y2 + caretSize; + } + x3 = x1; + } else { + if (xAlign === 'left') { + x2 = ptX + Math.max(topLeft, bottomLeft) + caretSize; + } else if (xAlign === 'right') { + x2 = ptX + width - Math.max(topRight, bottomRight) - caretSize; + } else { + x2 = this.caretX; + } + if (yAlign === 'top') { + y1 = ptY; + y2 = y1 - caretSize; + x1 = x2 - caretSize; + x3 = x2 + caretSize; + } else { + y1 = ptY + height; + y2 = y1 + caretSize; + x1 = x2 + caretSize; + x3 = x2 - caretSize; + } + y3 = y1; + } + return { + x1, + x2, + x3, + y1, + y2, + y3 + }; + } + drawTitle(pt, ctx, options) { + const title = this.title; + const length = title.length; + let titleFont, titleSpacing, i; + if (length) { + const rtlHelper = helpers_dataset.getRtlAdapter(options.rtl, this.x, this.width); + pt.x = getAlignedX(this, options.titleAlign, options); + ctx.textAlign = rtlHelper.textAlign(options.titleAlign); + ctx.textBaseline = 'middle'; + titleFont = helpers_dataset.toFont(options.titleFont); + titleSpacing = options.titleSpacing; + ctx.fillStyle = options.titleColor; + ctx.font = titleFont.string; + for(i = 0; i < length; ++i){ + ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFont.lineHeight / 2); + pt.y += titleFont.lineHeight + titleSpacing; + if (i + 1 === length) { + pt.y += options.titleMarginBottom - titleSpacing; + } + } + } + } + _drawColorBox(ctx, pt, i, rtlHelper, options) { + const labelColor = this.labelColors[i]; + const labelPointStyle = this.labelPointStyles[i]; + const { boxHeight , boxWidth } = options; + const bodyFont = helpers_dataset.toFont(options.bodyFont); + const colorX = getAlignedX(this, 'left', options); + const rtlColorX = rtlHelper.x(colorX); + const yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0; + const colorY = pt.y + yOffSet; + if (options.usePointStyle) { + const drawOptions = { + radius: Math.min(boxWidth, boxHeight) / 2, + pointStyle: labelPointStyle.pointStyle, + rotation: labelPointStyle.rotation, + borderWidth: 1 + }; + const centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2; + const centerY = colorY + boxHeight / 2; + ctx.strokeStyle = options.multiKeyBackground; + ctx.fillStyle = options.multiKeyBackground; + helpers_dataset.drawPoint(ctx, drawOptions, centerX, centerY); + ctx.strokeStyle = labelColor.borderColor; + ctx.fillStyle = labelColor.backgroundColor; + helpers_dataset.drawPoint(ctx, drawOptions, centerX, centerY); + } else { + ctx.lineWidth = helpers_dataset.isObject(labelColor.borderWidth) ? Math.max(...Object.values(labelColor.borderWidth)) : labelColor.borderWidth || 1; + ctx.strokeStyle = labelColor.borderColor; + ctx.setLineDash(labelColor.borderDash || []); + ctx.lineDashOffset = labelColor.borderDashOffset || 0; + const outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth); + const innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - 2); + const borderRadius = helpers_dataset.toTRBLCorners(labelColor.borderRadius); + if (Object.values(borderRadius).some((v)=>v !== 0)) { + ctx.beginPath(); + ctx.fillStyle = options.multiKeyBackground; + helpers_dataset.addRoundedRectPath(ctx, { + x: outerX, + y: colorY, + w: boxWidth, + h: boxHeight, + radius: borderRadius + }); + ctx.fill(); + ctx.stroke(); + ctx.fillStyle = labelColor.backgroundColor; + ctx.beginPath(); + helpers_dataset.addRoundedRectPath(ctx, { + x: innerX, + y: colorY + 1, + w: boxWidth - 2, + h: boxHeight - 2, + radius: borderRadius + }); + ctx.fill(); + } else { + ctx.fillStyle = options.multiKeyBackground; + ctx.fillRect(outerX, colorY, boxWidth, boxHeight); + ctx.strokeRect(outerX, colorY, boxWidth, boxHeight); + ctx.fillStyle = labelColor.backgroundColor; + ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2); + } + } + ctx.fillStyle = this.labelTextColors[i]; + } + drawBody(pt, ctx, options) { + const { body } = this; + const { bodySpacing , bodyAlign , displayColors , boxHeight , boxWidth , boxPadding } = options; + const bodyFont = helpers_dataset.toFont(options.bodyFont); + let bodyLineHeight = bodyFont.lineHeight; + let xLinePadding = 0; + const rtlHelper = helpers_dataset.getRtlAdapter(options.rtl, this.x, this.width); + const fillLineOfText = function(line) { + ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyLineHeight / 2); + pt.y += bodyLineHeight + bodySpacing; + }; + const bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign); + let bodyItem, textColor, lines, i, j, ilen, jlen; + ctx.textAlign = bodyAlign; + ctx.textBaseline = 'middle'; + ctx.font = bodyFont.string; + pt.x = getAlignedX(this, bodyAlignForCalculation, options); + ctx.fillStyle = options.bodyColor; + helpers_dataset.each(this.beforeBody, fillLineOfText); + xLinePadding = displayColors && bodyAlignForCalculation !== 'right' ? bodyAlign === 'center' ? boxWidth / 2 + boxPadding : boxWidth + 2 + boxPadding : 0; + for(i = 0, ilen = body.length; i < ilen; ++i){ + bodyItem = body[i]; + textColor = this.labelTextColors[i]; + ctx.fillStyle = textColor; + helpers_dataset.each(bodyItem.before, fillLineOfText); + lines = bodyItem.lines; + if (displayColors && lines.length) { + this._drawColorBox(ctx, pt, i, rtlHelper, options); + bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight); + } + for(j = 0, jlen = lines.length; j < jlen; ++j){ + fillLineOfText(lines[j]); + bodyLineHeight = bodyFont.lineHeight; + } + helpers_dataset.each(bodyItem.after, fillLineOfText); + } + xLinePadding = 0; + bodyLineHeight = bodyFont.lineHeight; + helpers_dataset.each(this.afterBody, fillLineOfText); + pt.y -= bodySpacing; + } + drawFooter(pt, ctx, options) { + const footer = this.footer; + const length = footer.length; + let footerFont, i; + if (length) { + const rtlHelper = helpers_dataset.getRtlAdapter(options.rtl, this.x, this.width); + pt.x = getAlignedX(this, options.footerAlign, options); + pt.y += options.footerMarginTop; + ctx.textAlign = rtlHelper.textAlign(options.footerAlign); + ctx.textBaseline = 'middle'; + footerFont = helpers_dataset.toFont(options.footerFont); + ctx.fillStyle = options.footerColor; + ctx.font = footerFont.string; + for(i = 0; i < length; ++i){ + ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFont.lineHeight / 2); + pt.y += footerFont.lineHeight + options.footerSpacing; + } + } + } + drawBackground(pt, ctx, tooltipSize, options) { + const { xAlign , yAlign } = this; + const { x , y } = pt; + const { width , height } = tooltipSize; + const { topLeft , topRight , bottomLeft , bottomRight } = helpers_dataset.toTRBLCorners(options.cornerRadius); + ctx.fillStyle = options.backgroundColor; + ctx.strokeStyle = options.borderColor; + ctx.lineWidth = options.borderWidth; + ctx.beginPath(); + ctx.moveTo(x + topLeft, y); + if (yAlign === 'top') { + this.drawCaret(pt, ctx, tooltipSize, options); + } + ctx.lineTo(x + width - topRight, y); + ctx.quadraticCurveTo(x + width, y, x + width, y + topRight); + if (yAlign === 'center' && xAlign === 'right') { + this.drawCaret(pt, ctx, tooltipSize, options); + } + ctx.lineTo(x + width, y + height - bottomRight); + ctx.quadraticCurveTo(x + width, y + height, x + width - bottomRight, y + height); + if (yAlign === 'bottom') { + this.drawCaret(pt, ctx, tooltipSize, options); + } + ctx.lineTo(x + bottomLeft, y + height); + ctx.quadraticCurveTo(x, y + height, x, y + height - bottomLeft); + if (yAlign === 'center' && xAlign === 'left') { + this.drawCaret(pt, ctx, tooltipSize, options); + } + ctx.lineTo(x, y + topLeft); + ctx.quadraticCurveTo(x, y, x + topLeft, y); + ctx.closePath(); + ctx.fill(); + if (options.borderWidth > 0) { + ctx.stroke(); + } + } + _updateAnimationTarget(options) { + const chart = this.chart; + const anims = this.$animations; + const animX = anims && anims.x; + const animY = anims && anims.y; + if (animX || animY) { + const position = positioners[options.position].call(this, this._active, this._eventPosition); + if (!position) { + return; + } + const size = this._size = getTooltipSize(this, options); + const positionAndSize = Object.assign({}, position, this._size); + const alignment = determineAlignment(chart, options, positionAndSize); + const point = getBackgroundPoint(options, positionAndSize, alignment, chart); + if (animX._to !== point.x || animY._to !== point.y) { + this.xAlign = alignment.xAlign; + this.yAlign = alignment.yAlign; + this.width = size.width; + this.height = size.height; + this.caretX = position.x; + this.caretY = position.y; + this._resolveAnimations().update(this, point); + } + } + } + _willRender() { + return !!this.opacity; + } + draw(ctx) { + const options = this.options.setContext(this.getContext()); + let opacity = this.opacity; + if (!opacity) { + return; + } + this._updateAnimationTarget(options); + const tooltipSize = { + width: this.width, + height: this.height + }; + const pt = { + x: this.x, + y: this.y + }; + opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity; + const padding = helpers_dataset.toPadding(options.padding); + const hasTooltipContent = this.title.length || this.beforeBody.length || this.body.length || this.afterBody.length || this.footer.length; + if (options.enabled && hasTooltipContent) { + ctx.save(); + ctx.globalAlpha = opacity; + this.drawBackground(pt, ctx, tooltipSize, options); + helpers_dataset.overrideTextDirection(ctx, options.textDirection); + pt.y += padding.top; + this.drawTitle(pt, ctx, options); + this.drawBody(pt, ctx, options); + this.drawFooter(pt, ctx, options); + helpers_dataset.restoreTextDirection(ctx, options.textDirection); + ctx.restore(); + } + } + getActiveElements() { + return this._active || []; + } + setActiveElements(activeElements, eventPosition) { + const lastActive = this._active; + const active = activeElements.map(({ datasetIndex , index })=>{ + const meta = this.chart.getDatasetMeta(datasetIndex); + if (!meta) { + throw new Error('Cannot find a dataset at index ' + datasetIndex); + } + return { + datasetIndex, + element: meta.data[index], + index + }; + }); + const changed = !helpers_dataset._elementsEqual(lastActive, active); + const positionChanged = this._positionChanged(active, eventPosition); + if (changed || positionChanged) { + this._active = active; + this._eventPosition = eventPosition; + this._ignoreReplayEvents = true; + this.update(true); + } + } + handleEvent(e, replay, inChartArea = true) { + if (replay && this._ignoreReplayEvents) { + return false; + } + this._ignoreReplayEvents = false; + const options = this.options; + const lastActive = this._active || []; + const active = this._getActiveElements(e, lastActive, replay, inChartArea); + const positionChanged = this._positionChanged(active, e); + const changed = replay || !helpers_dataset._elementsEqual(active, lastActive) || positionChanged; + if (changed) { + this._active = active; + if (options.enabled || options.external) { + this._eventPosition = { + x: e.x, + y: e.y + }; + this.update(true, replay); + } + } + return changed; + } + _getActiveElements(e, lastActive, replay, inChartArea) { + const options = this.options; + if (e.type === 'mouseout') { + return []; + } + if (!inChartArea) { + return lastActive.filter((i)=>this.chart.data.datasets[i.datasetIndex] && this.chart.getDatasetMeta(i.datasetIndex).controller.getParsed(i.index) !== undefined); + } + const active = this.chart.getElementsAtEventForMode(e, options.mode, options, replay); + if (options.reverse) { + active.reverse(); + } + return active; + } + _positionChanged(active, e) { + const { caretX , caretY , options } = this; + const position = positioners[options.position].call(this, active, e); + return position !== false && (caretX !== position.x || caretY !== position.y); + } +} +var plugin_tooltip = { + id: 'tooltip', + _element: Tooltip, + positioners, + afterInit (chart, _args, options) { + if (options) { + chart.tooltip = new Tooltip({ + chart, + options + }); + } + }, + beforeUpdate (chart, _args, options) { + if (chart.tooltip) { + chart.tooltip.initialize(options); + } + }, + reset (chart, _args, options) { + if (chart.tooltip) { + chart.tooltip.initialize(options); + } + }, + afterDraw (chart) { + const tooltip = chart.tooltip; + if (tooltip && tooltip._willRender()) { + const args = { + tooltip + }; + if (chart.notifyPlugins('beforeTooltipDraw', { + ...args, + cancelable: true + }) === false) { + return; + } + tooltip.draw(chart.ctx); + chart.notifyPlugins('afterTooltipDraw', args); + } + }, + afterEvent (chart, args) { + if (chart.tooltip) { + const useFinalPosition = args.replay; + if (chart.tooltip.handleEvent(args.event, useFinalPosition, args.inChartArea)) { + args.changed = true; + } + } + }, + defaults: { + enabled: true, + external: null, + position: 'average', + backgroundColor: 'rgba(0,0,0,0.8)', + titleColor: '#fff', + titleFont: { + weight: 'bold' + }, + titleSpacing: 2, + titleMarginBottom: 6, + titleAlign: 'left', + bodyColor: '#fff', + bodySpacing: 2, + bodyFont: {}, + bodyAlign: 'left', + footerColor: '#fff', + footerSpacing: 2, + footerMarginTop: 6, + footerFont: { + weight: 'bold' + }, + footerAlign: 'left', + padding: 6, + caretPadding: 2, + caretSize: 5, + cornerRadius: 6, + boxHeight: (ctx, opts)=>opts.bodyFont.size, + boxWidth: (ctx, opts)=>opts.bodyFont.size, + multiKeyBackground: '#fff', + displayColors: true, + boxPadding: 0, + borderColor: 'rgba(0,0,0,0)', + borderWidth: 0, + animation: { + duration: 400, + easing: 'easeOutQuart' + }, + animations: { + numbers: { + type: 'number', + properties: [ + 'x', + 'y', + 'width', + 'height', + 'caretX', + 'caretY' + ] + }, + opacity: { + easing: 'linear', + duration: 200 + } + }, + callbacks: defaultCallbacks + }, + defaultRoutes: { + bodyFont: 'font', + footerFont: 'font', + titleFont: 'font' + }, + descriptors: { + _scriptable: (name)=>name !== 'filter' && name !== 'itemSort' && name !== 'external', + _indexable: false, + callbacks: { + _scriptable: false, + _indexable: false + }, + animation: { + _fallback: false + }, + animations: { + _fallback: 'animation' + } + }, + additionalOptionScopes: [ + 'interaction' + ] +}; + +var plugins = /*#__PURE__*/Object.freeze({ +__proto__: null, +Colors: plugin_colors, +Decimation: plugin_decimation, +Filler: index, +Legend: plugin_legend, +SubTitle: plugin_subtitle, +Title: plugin_title, +Tooltip: plugin_tooltip +}); + +const addIfString = (labels, raw, index, addedLabels)=>{ + if (typeof raw === 'string') { + index = labels.push(raw) - 1; + addedLabels.unshift({ + index, + label: raw + }); + } else if (isNaN(raw)) { + index = null; + } + return index; +}; +function findOrAddLabel(labels, raw, index, addedLabels) { + const first = labels.indexOf(raw); + if (first === -1) { + return addIfString(labels, raw, index, addedLabels); + } + const last = labels.lastIndexOf(raw); + return first !== last ? index : first; +} +const validIndex = (index, max)=>index === null ? null : helpers_dataset._limitValue(Math.round(index), 0, max); +function _getLabelForValue(value) { + const labels = this.getLabels(); + if (value >= 0 && value < labels.length) { + return labels[value]; + } + return value; +} +class CategoryScale extends Scale { + static id = 'category'; + static defaults = { + ticks: { + callback: _getLabelForValue + } + }; + constructor(cfg){ + super(cfg); + this._startValue = undefined; + this._valueRange = 0; + this._addedLabels = []; + } + init(scaleOptions) { + const added = this._addedLabels; + if (added.length) { + const labels = this.getLabels(); + for (const { index , label } of added){ + if (labels[index] === label) { + labels.splice(index, 1); + } + } + this._addedLabels = []; + } + super.init(scaleOptions); + } + parse(raw, index) { + if (helpers_dataset.isNullOrUndef(raw)) { + return null; + } + const labels = this.getLabels(); + index = isFinite(index) && labels[index] === raw ? index : findOrAddLabel(labels, raw, helpers_dataset.valueOrDefault(index, raw), this._addedLabels); + return validIndex(index, labels.length - 1); + } + determineDataLimits() { + const { minDefined , maxDefined } = this.getUserBounds(); + let { min , max } = this.getMinMax(true); + if (this.options.bounds === 'ticks') { + if (!minDefined) { + min = 0; + } + if (!maxDefined) { + max = this.getLabels().length - 1; + } + } + this.min = min; + this.max = max; + } + buildTicks() { + const min = this.min; + const max = this.max; + const offset = this.options.offset; + const ticks = []; + let labels = this.getLabels(); + labels = min === 0 && max === labels.length - 1 ? labels : labels.slice(min, max + 1); + this._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1); + this._startValue = this.min - (offset ? 0.5 : 0); + for(let value = min; value <= max; value++){ + ticks.push({ + value + }); + } + return ticks; + } + getLabelForValue(value) { + return _getLabelForValue.call(this, value); + } + configure() { + super.configure(); + if (!this.isHorizontal()) { + this._reversePixels = !this._reversePixels; + } + } + getPixelForValue(value) { + if (typeof value !== 'number') { + value = this.parse(value); + } + return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange); + } + getPixelForTick(index) { + const ticks = this.ticks; + if (index < 0 || index > ticks.length - 1) { + return null; + } + return this.getPixelForValue(ticks[index].value); + } + getValueForPixel(pixel) { + return Math.round(this._startValue + this.getDecimalForPixel(pixel) * this._valueRange); + } + getBasePixel() { + return this.bottom; + } +} + +function generateTicks$1(generationOptions, dataRange) { + const ticks = []; + const MIN_SPACING = 1e-14; + const { bounds , step , min , max , precision , count , maxTicks , maxDigits , includeBounds } = generationOptions; + const unit = step || 1; + const maxSpaces = maxTicks - 1; + const { min: rmin , max: rmax } = dataRange; + const minDefined = !helpers_dataset.isNullOrUndef(min); + const maxDefined = !helpers_dataset.isNullOrUndef(max); + const countDefined = !helpers_dataset.isNullOrUndef(count); + const minSpacing = (rmax - rmin) / (maxDigits + 1); + let spacing = helpers_dataset.niceNum((rmax - rmin) / maxSpaces / unit) * unit; + let factor, niceMin, niceMax, numSpaces; + if (spacing < MIN_SPACING && !minDefined && !maxDefined) { + return [ + { + value: rmin + }, + { + value: rmax + } + ]; + } + numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing); + if (numSpaces > maxSpaces) { + spacing = helpers_dataset.niceNum(numSpaces * spacing / maxSpaces / unit) * unit; + } + if (!helpers_dataset.isNullOrUndef(precision)) { + factor = Math.pow(10, precision); + spacing = Math.ceil(spacing * factor) / factor; + } + if (bounds === 'ticks') { + niceMin = Math.floor(rmin / spacing) * spacing; + niceMax = Math.ceil(rmax / spacing) * spacing; + } else { + niceMin = rmin; + niceMax = rmax; + } + if (minDefined && maxDefined && step && helpers_dataset.almostWhole((max - min) / step, spacing / 1000)) { + numSpaces = Math.round(Math.min((max - min) / spacing, maxTicks)); + spacing = (max - min) / numSpaces; + niceMin = min; + niceMax = max; + } else if (countDefined) { + niceMin = minDefined ? min : niceMin; + niceMax = maxDefined ? max : niceMax; + numSpaces = count - 1; + spacing = (niceMax - niceMin) / numSpaces; + } else { + numSpaces = (niceMax - niceMin) / spacing; + if (helpers_dataset.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) { + numSpaces = Math.round(numSpaces); + } else { + numSpaces = Math.ceil(numSpaces); + } + } + const decimalPlaces = Math.max(helpers_dataset._decimalPlaces(spacing), helpers_dataset._decimalPlaces(niceMin)); + factor = Math.pow(10, helpers_dataset.isNullOrUndef(precision) ? decimalPlaces : precision); + niceMin = Math.round(niceMin * factor) / factor; + niceMax = Math.round(niceMax * factor) / factor; + let j = 0; + if (minDefined) { + if (includeBounds && niceMin !== min) { + ticks.push({ + value: min + }); + if (niceMin < min) { + j++; + } + if (helpers_dataset.almostEquals(Math.round((niceMin + j * spacing) * factor) / factor, min, relativeLabelSize(min, minSpacing, generationOptions))) { + j++; + } + } else if (niceMin < min) { + j++; + } + } + for(; j < numSpaces; ++j){ + const tickValue = Math.round((niceMin + j * spacing) * factor) / factor; + if (maxDefined && tickValue > max) { + break; + } + ticks.push({ + value: tickValue + }); + } + if (maxDefined && includeBounds && niceMax !== max) { + if (ticks.length && helpers_dataset.almostEquals(ticks[ticks.length - 1].value, max, relativeLabelSize(max, minSpacing, generationOptions))) { + ticks[ticks.length - 1].value = max; + } else { + ticks.push({ + value: max + }); + } + } else if (!maxDefined || niceMax === max) { + ticks.push({ + value: niceMax + }); + } + return ticks; +} +function relativeLabelSize(value, minSpacing, { horizontal , minRotation }) { + const rad = helpers_dataset.toRadians(minRotation); + const ratio = (horizontal ? Math.sin(rad) : Math.cos(rad)) || 0.001; + const length = 0.75 * minSpacing * ('' + value).length; + return Math.min(minSpacing / ratio, length); +} +class LinearScaleBase extends Scale { + constructor(cfg){ + super(cfg); + this.start = undefined; + this.end = undefined; + this._startValue = undefined; + this._endValue = undefined; + this._valueRange = 0; + } + parse(raw, index) { + if (helpers_dataset.isNullOrUndef(raw)) { + return null; + } + if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) { + return null; + } + return +raw; + } + handleTickRangeOptions() { + const { beginAtZero } = this.options; + const { minDefined , maxDefined } = this.getUserBounds(); + let { min , max } = this; + const setMin = (v)=>min = minDefined ? min : v; + const setMax = (v)=>max = maxDefined ? max : v; + if (beginAtZero) { + const minSign = helpers_dataset.sign(min); + const maxSign = helpers_dataset.sign(max); + if (minSign < 0 && maxSign < 0) { + setMax(0); + } else if (minSign > 0 && maxSign > 0) { + setMin(0); + } + } + if (min === max) { + let offset = max === 0 ? 1 : Math.abs(max * 0.05); + setMax(max + offset); + if (!beginAtZero) { + setMin(min - offset); + } + } + this.min = min; + this.max = max; + } + getTickLimit() { + const tickOpts = this.options.ticks; + let { maxTicksLimit , stepSize } = tickOpts; + let maxTicks; + if (stepSize) { + maxTicks = Math.ceil(this.max / stepSize) - Math.floor(this.min / stepSize) + 1; + if (maxTicks > 1000) { + console.warn(`scales.${this.id}.ticks.stepSize: ${stepSize} would result generating up to ${maxTicks} ticks. Limiting to 1000.`); + maxTicks = 1000; + } + } else { + maxTicks = this.computeTickLimit(); + maxTicksLimit = maxTicksLimit || 11; + } + if (maxTicksLimit) { + maxTicks = Math.min(maxTicksLimit, maxTicks); + } + return maxTicks; + } + computeTickLimit() { + return Number.POSITIVE_INFINITY; + } + buildTicks() { + const opts = this.options; + const tickOpts = opts.ticks; + let maxTicks = this.getTickLimit(); + maxTicks = Math.max(2, maxTicks); + const numericGeneratorOptions = { + maxTicks, + bounds: opts.bounds, + min: opts.min, + max: opts.max, + precision: tickOpts.precision, + step: tickOpts.stepSize, + count: tickOpts.count, + maxDigits: this._maxDigits(), + horizontal: this.isHorizontal(), + minRotation: tickOpts.minRotation || 0, + includeBounds: tickOpts.includeBounds !== false + }; + const dataRange = this._range || this; + const ticks = generateTicks$1(numericGeneratorOptions, dataRange); + if (opts.bounds === 'ticks') { + helpers_dataset._setMinAndMaxByKey(ticks, this, 'value'); + } + if (opts.reverse) { + ticks.reverse(); + this.start = this.max; + this.end = this.min; + } else { + this.start = this.min; + this.end = this.max; + } + return ticks; + } + configure() { + const ticks = this.ticks; + let start = this.min; + let end = this.max; + super.configure(); + if (this.options.offset && ticks.length) { + const offset = (end - start) / Math.max(ticks.length - 1, 1) / 2; + start -= offset; + end += offset; + } + this._startValue = start; + this._endValue = end; + this._valueRange = end - start; + } + getLabelForValue(value) { + return helpers_dataset.formatNumber(value, this.chart.options.locale, this.options.ticks.format); + } +} + +class LinearScale extends LinearScaleBase { + static id = 'linear'; + static defaults = { + ticks: { + callback: helpers_dataset.Ticks.formatters.numeric + } + }; + determineDataLimits() { + const { min , max } = this.getMinMax(true); + this.min = helpers_dataset.isNumberFinite(min) ? min : 0; + this.max = helpers_dataset.isNumberFinite(max) ? max : 1; + this.handleTickRangeOptions(); + } + computeTickLimit() { + const horizontal = this.isHorizontal(); + const length = horizontal ? this.width : this.height; + const minRotation = helpers_dataset.toRadians(this.options.ticks.minRotation); + const ratio = (horizontal ? Math.sin(minRotation) : Math.cos(minRotation)) || 0.001; + const tickFont = this._resolveTickFontOptions(0); + return Math.ceil(length / Math.min(40, tickFont.lineHeight / ratio)); + } + getPixelForValue(value) { + return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange); + } + getValueForPixel(pixel) { + return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange; + } +} + +const log10Floor = (v)=>Math.floor(helpers_dataset.log10(v)); +const changeExponent = (v, m)=>Math.pow(10, log10Floor(v) + m); +function isMajor(tickVal) { + const remain = tickVal / Math.pow(10, log10Floor(tickVal)); + return remain === 1; +} +function steps(min, max, rangeExp) { + const rangeStep = Math.pow(10, rangeExp); + const start = Math.floor(min / rangeStep); + const end = Math.ceil(max / rangeStep); + return end - start; +} +function startExp(min, max) { + const range = max - min; + let rangeExp = log10Floor(range); + while(steps(min, max, rangeExp) > 10){ + rangeExp++; + } + while(steps(min, max, rangeExp) < 10){ + rangeExp--; + } + return Math.min(rangeExp, log10Floor(min)); +} + function generateTicks(generationOptions, { min , max }) { + min = helpers_dataset.finiteOrDefault(generationOptions.min, min); + const ticks = []; + const minExp = log10Floor(min); + let exp = startExp(min, max); + let precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1; + const stepSize = Math.pow(10, exp); + const base = minExp > exp ? Math.pow(10, minExp) : 0; + const start = Math.round((min - base) * precision) / precision; + const offset = Math.floor((min - base) / stepSize / 10) * stepSize * 10; + let significand = Math.floor((start - offset) / Math.pow(10, exp)); + let value = helpers_dataset.finiteOrDefault(generationOptions.min, Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision); + while(value < max){ + ticks.push({ + value, + major: isMajor(value), + significand + }); + if (significand >= 10) { + significand = significand < 15 ? 15 : 20; + } else { + significand++; + } + if (significand >= 20) { + exp++; + significand = 2; + precision = exp >= 0 ? 1 : precision; + } + value = Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision; + } + const lastTick = helpers_dataset.finiteOrDefault(generationOptions.max, value); + ticks.push({ + value: lastTick, + major: isMajor(lastTick), + significand + }); + return ticks; +} +class LogarithmicScale extends Scale { + static id = 'logarithmic'; + static defaults = { + ticks: { + callback: helpers_dataset.Ticks.formatters.logarithmic, + major: { + enabled: true + } + } + }; + constructor(cfg){ + super(cfg); + this.start = undefined; + this.end = undefined; + this._startValue = undefined; + this._valueRange = 0; + } + parse(raw, index) { + const value = LinearScaleBase.prototype.parse.apply(this, [ + raw, + index + ]); + if (value === 0) { + this._zero = true; + return undefined; + } + return helpers_dataset.isNumberFinite(value) && value > 0 ? value : null; + } + determineDataLimits() { + const { min , max } = this.getMinMax(true); + this.min = helpers_dataset.isNumberFinite(min) ? Math.max(0, min) : null; + this.max = helpers_dataset.isNumberFinite(max) ? Math.max(0, max) : null; + if (this.options.beginAtZero) { + this._zero = true; + } + if (this._zero && this.min !== this._suggestedMin && !helpers_dataset.isNumberFinite(this._userMin)) { + this.min = min === changeExponent(this.min, 0) ? changeExponent(this.min, -1) : changeExponent(this.min, 0); + } + this.handleTickRangeOptions(); + } + handleTickRangeOptions() { + const { minDefined , maxDefined } = this.getUserBounds(); + let min = this.min; + let max = this.max; + const setMin = (v)=>min = minDefined ? min : v; + const setMax = (v)=>max = maxDefined ? max : v; + if (min === max) { + if (min <= 0) { + setMin(1); + setMax(10); + } else { + setMin(changeExponent(min, -1)); + setMax(changeExponent(max, +1)); + } + } + if (min <= 0) { + setMin(changeExponent(max, -1)); + } + if (max <= 0) { + setMax(changeExponent(min, +1)); + } + this.min = min; + this.max = max; + } + buildTicks() { + const opts = this.options; + const generationOptions = { + min: this._userMin, + max: this._userMax + }; + const ticks = generateTicks(generationOptions, this); + if (opts.bounds === 'ticks') { + helpers_dataset._setMinAndMaxByKey(ticks, this, 'value'); + } + if (opts.reverse) { + ticks.reverse(); + this.start = this.max; + this.end = this.min; + } else { + this.start = this.min; + this.end = this.max; + } + return ticks; + } + getLabelForValue(value) { + return value === undefined ? '0' : helpers_dataset.formatNumber(value, this.chart.options.locale, this.options.ticks.format); + } + configure() { + const start = this.min; + super.configure(); + this._startValue = helpers_dataset.log10(start); + this._valueRange = helpers_dataset.log10(this.max) - helpers_dataset.log10(start); + } + getPixelForValue(value) { + if (value === undefined || value === 0) { + value = this.min; + } + if (value === null || isNaN(value)) { + return NaN; + } + return this.getPixelForDecimal(value === this.min ? 0 : (helpers_dataset.log10(value) - this._startValue) / this._valueRange); + } + getValueForPixel(pixel) { + const decimal = this.getDecimalForPixel(pixel); + return Math.pow(10, this._startValue + decimal * this._valueRange); + } +} + +function getTickBackdropHeight(opts) { + const tickOpts = opts.ticks; + if (tickOpts.display && opts.display) { + const padding = helpers_dataset.toPadding(tickOpts.backdropPadding); + return helpers_dataset.valueOrDefault(tickOpts.font && tickOpts.font.size, helpers_dataset.defaults.font.size) + padding.height; + } + return 0; +} +function measureLabelSize(ctx, font, label) { + label = helpers_dataset.isArray(label) ? label : [ + label + ]; + return { + w: helpers_dataset._longestText(ctx, font.string, label), + h: label.length * font.lineHeight + }; +} +function determineLimits(angle, pos, size, min, max) { + if (angle === min || angle === max) { + return { + start: pos - size / 2, + end: pos + size / 2 + }; + } else if (angle < min || angle > max) { + return { + start: pos - size, + end: pos + }; + } + return { + start: pos, + end: pos + size + }; +} + function fitWithPointLabels(scale) { + const orig = { + l: scale.left + scale._padding.left, + r: scale.right - scale._padding.right, + t: scale.top + scale._padding.top, + b: scale.bottom - scale._padding.bottom + }; + const limits = Object.assign({}, orig); + const labelSizes = []; + const padding = []; + const valueCount = scale._pointLabels.length; + const pointLabelOpts = scale.options.pointLabels; + const additionalAngle = pointLabelOpts.centerPointLabels ? helpers_dataset.PI / valueCount : 0; + for(let i = 0; i < valueCount; i++){ + const opts = pointLabelOpts.setContext(scale.getPointLabelContext(i)); + padding[i] = opts.padding; + const pointPosition = scale.getPointPosition(i, scale.drawingArea + padding[i], additionalAngle); + const plFont = helpers_dataset.toFont(opts.font); + const textSize = measureLabelSize(scale.ctx, plFont, scale._pointLabels[i]); + labelSizes[i] = textSize; + const angleRadians = helpers_dataset._normalizeAngle(scale.getIndexAngle(i) + additionalAngle); + const angle = Math.round(helpers_dataset.toDegrees(angleRadians)); + const hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180); + const vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270); + updateLimits(limits, orig, angleRadians, hLimits, vLimits); + } + scale.setCenterPoint(orig.l - limits.l, limits.r - orig.r, orig.t - limits.t, limits.b - orig.b); + scale._pointLabelItems = buildPointLabelItems(scale, labelSizes, padding); +} +function updateLimits(limits, orig, angle, hLimits, vLimits) { + const sin = Math.abs(Math.sin(angle)); + const cos = Math.abs(Math.cos(angle)); + let x = 0; + let y = 0; + if (hLimits.start < orig.l) { + x = (orig.l - hLimits.start) / sin; + limits.l = Math.min(limits.l, orig.l - x); + } else if (hLimits.end > orig.r) { + x = (hLimits.end - orig.r) / sin; + limits.r = Math.max(limits.r, orig.r + x); + } + if (vLimits.start < orig.t) { + y = (orig.t - vLimits.start) / cos; + limits.t = Math.min(limits.t, orig.t - y); + } else if (vLimits.end > orig.b) { + y = (vLimits.end - orig.b) / cos; + limits.b = Math.max(limits.b, orig.b + y); + } +} +function createPointLabelItem(scale, index, itemOpts) { + const outerDistance = scale.drawingArea; + const { extra , additionalAngle , padding , size } = itemOpts; + const pointLabelPosition = scale.getPointPosition(index, outerDistance + extra + padding, additionalAngle); + const angle = Math.round(helpers_dataset.toDegrees(helpers_dataset._normalizeAngle(pointLabelPosition.angle + helpers_dataset.HALF_PI))); + const y = yForAngle(pointLabelPosition.y, size.h, angle); + const textAlign = getTextAlignForAngle(angle); + const left = leftForTextAlign(pointLabelPosition.x, size.w, textAlign); + return { + visible: true, + x: pointLabelPosition.x, + y, + textAlign, + left, + top: y, + right: left + size.w, + bottom: y + size.h + }; +} +function isNotOverlapped(item, area) { + if (!area) { + return true; + } + const { left , top , right , bottom } = item; + const apexesInArea = helpers_dataset._isPointInArea({ + x: left, + y: top + }, area) || helpers_dataset._isPointInArea({ + x: left, + y: bottom + }, area) || helpers_dataset._isPointInArea({ + x: right, + y: top + }, area) || helpers_dataset._isPointInArea({ + x: right, + y: bottom + }, area); + return !apexesInArea; +} +function buildPointLabelItems(scale, labelSizes, padding) { + const items = []; + const valueCount = scale._pointLabels.length; + const opts = scale.options; + const { centerPointLabels , display } = opts.pointLabels; + const itemOpts = { + extra: getTickBackdropHeight(opts) / 2, + additionalAngle: centerPointLabels ? helpers_dataset.PI / valueCount : 0 + }; + let area; + for(let i = 0; i < valueCount; i++){ + itemOpts.padding = padding[i]; + itemOpts.size = labelSizes[i]; + const item = createPointLabelItem(scale, i, itemOpts); + items.push(item); + if (display === 'auto') { + item.visible = isNotOverlapped(item, area); + if (item.visible) { + area = item; + } + } + } + return items; +} +function getTextAlignForAngle(angle) { + if (angle === 0 || angle === 180) { + return 'center'; + } else if (angle < 180) { + return 'left'; + } + return 'right'; +} +function leftForTextAlign(x, w, align) { + if (align === 'right') { + x -= w; + } else if (align === 'center') { + x -= w / 2; + } + return x; +} +function yForAngle(y, h, angle) { + if (angle === 90 || angle === 270) { + y -= h / 2; + } else if (angle > 270 || angle < 90) { + y -= h; + } + return y; +} +function drawPointLabelBox(ctx, opts, item) { + const { left , top , right , bottom } = item; + const { backdropColor } = opts; + if (!helpers_dataset.isNullOrUndef(backdropColor)) { + const borderRadius = helpers_dataset.toTRBLCorners(opts.borderRadius); + const padding = helpers_dataset.toPadding(opts.backdropPadding); + ctx.fillStyle = backdropColor; + const backdropLeft = left - padding.left; + const backdropTop = top - padding.top; + const backdropWidth = right - left + padding.width; + const backdropHeight = bottom - top + padding.height; + if (Object.values(borderRadius).some((v)=>v !== 0)) { + ctx.beginPath(); + helpers_dataset.addRoundedRectPath(ctx, { + x: backdropLeft, + y: backdropTop, + w: backdropWidth, + h: backdropHeight, + radius: borderRadius + }); + ctx.fill(); + } else { + ctx.fillRect(backdropLeft, backdropTop, backdropWidth, backdropHeight); + } + } +} +function drawPointLabels(scale, labelCount) { + const { ctx , options: { pointLabels } } = scale; + for(let i = labelCount - 1; i >= 0; i--){ + const item = scale._pointLabelItems[i]; + if (!item.visible) { + continue; + } + const optsAtIndex = pointLabels.setContext(scale.getPointLabelContext(i)); + drawPointLabelBox(ctx, optsAtIndex, item); + const plFont = helpers_dataset.toFont(optsAtIndex.font); + const { x , y , textAlign } = item; + helpers_dataset.renderText(ctx, scale._pointLabels[i], x, y + plFont.lineHeight / 2, plFont, { + color: optsAtIndex.color, + textAlign: textAlign, + textBaseline: 'middle' + }); + } +} +function pathRadiusLine(scale, radius, circular, labelCount) { + const { ctx } = scale; + if (circular) { + ctx.arc(scale.xCenter, scale.yCenter, radius, 0, helpers_dataset.TAU); + } else { + let pointPosition = scale.getPointPosition(0, radius); + ctx.moveTo(pointPosition.x, pointPosition.y); + for(let i = 1; i < labelCount; i++){ + pointPosition = scale.getPointPosition(i, radius); + ctx.lineTo(pointPosition.x, pointPosition.y); + } + } +} +function drawRadiusLine(scale, gridLineOpts, radius, labelCount, borderOpts) { + const ctx = scale.ctx; + const circular = gridLineOpts.circular; + const { color , lineWidth } = gridLineOpts; + if (!circular && !labelCount || !color || !lineWidth || radius < 0) { + return; + } + ctx.save(); + ctx.strokeStyle = color; + ctx.lineWidth = lineWidth; + ctx.setLineDash(borderOpts.dash || []); + ctx.lineDashOffset = borderOpts.dashOffset; + ctx.beginPath(); + pathRadiusLine(scale, radius, circular, labelCount); + ctx.closePath(); + ctx.stroke(); + ctx.restore(); +} +function createPointLabelContext(parent, index, label) { + return helpers_dataset.createContext(parent, { + label, + index, + type: 'pointLabel' + }); +} +class RadialLinearScale extends LinearScaleBase { + static id = 'radialLinear'; + static defaults = { + display: true, + animate: true, + position: 'chartArea', + angleLines: { + display: true, + lineWidth: 1, + borderDash: [], + borderDashOffset: 0.0 + }, + grid: { + circular: false + }, + startAngle: 0, + ticks: { + showLabelBackdrop: true, + callback: helpers_dataset.Ticks.formatters.numeric + }, + pointLabels: { + backdropColor: undefined, + backdropPadding: 2, + display: true, + font: { + size: 10 + }, + callback (label) { + return label; + }, + padding: 5, + centerPointLabels: false + } + }; + static defaultRoutes = { + 'angleLines.color': 'borderColor', + 'pointLabels.color': 'color', + 'ticks.color': 'color' + }; + static descriptors = { + angleLines: { + _fallback: 'grid' + } + }; + constructor(cfg){ + super(cfg); + this.xCenter = undefined; + this.yCenter = undefined; + this.drawingArea = undefined; + this._pointLabels = []; + this._pointLabelItems = []; + } + setDimensions() { + const padding = this._padding = helpers_dataset.toPadding(getTickBackdropHeight(this.options) / 2); + const w = this.width = this.maxWidth - padding.width; + const h = this.height = this.maxHeight - padding.height; + this.xCenter = Math.floor(this.left + w / 2 + padding.left); + this.yCenter = Math.floor(this.top + h / 2 + padding.top); + this.drawingArea = Math.floor(Math.min(w, h) / 2); + } + determineDataLimits() { + const { min , max } = this.getMinMax(false); + this.min = helpers_dataset.isNumberFinite(min) && !isNaN(min) ? min : 0; + this.max = helpers_dataset.isNumberFinite(max) && !isNaN(max) ? max : 0; + this.handleTickRangeOptions(); + } + computeTickLimit() { + return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options)); + } + generateTickLabels(ticks) { + LinearScaleBase.prototype.generateTickLabels.call(this, ticks); + this._pointLabels = this.getLabels().map((value, index)=>{ + const label = helpers_dataset.callback(this.options.pointLabels.callback, [ + value, + index + ], this); + return label || label === 0 ? label : ''; + }).filter((v, i)=>this.chart.getDataVisibility(i)); + } + fit() { + const opts = this.options; + if (opts.display && opts.pointLabels.display) { + fitWithPointLabels(this); + } else { + this.setCenterPoint(0, 0, 0, 0); + } + } + setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) { + this.xCenter += Math.floor((leftMovement - rightMovement) / 2); + this.yCenter += Math.floor((topMovement - bottomMovement) / 2); + this.drawingArea -= Math.min(this.drawingArea / 2, Math.max(leftMovement, rightMovement, topMovement, bottomMovement)); + } + getIndexAngle(index) { + const angleMultiplier = helpers_dataset.TAU / (this._pointLabels.length || 1); + const startAngle = this.options.startAngle || 0; + return helpers_dataset._normalizeAngle(index * angleMultiplier + helpers_dataset.toRadians(startAngle)); + } + getDistanceFromCenterForValue(value) { + if (helpers_dataset.isNullOrUndef(value)) { + return NaN; + } + const scalingFactor = this.drawingArea / (this.max - this.min); + if (this.options.reverse) { + return (this.max - value) * scalingFactor; + } + return (value - this.min) * scalingFactor; + } + getValueForDistanceFromCenter(distance) { + if (helpers_dataset.isNullOrUndef(distance)) { + return NaN; + } + const scaledDistance = distance / (this.drawingArea / (this.max - this.min)); + return this.options.reverse ? this.max - scaledDistance : this.min + scaledDistance; + } + getPointLabelContext(index) { + const pointLabels = this._pointLabels || []; + if (index >= 0 && index < pointLabels.length) { + const pointLabel = pointLabels[index]; + return createPointLabelContext(this.getContext(), index, pointLabel); + } + } + getPointPosition(index, distanceFromCenter, additionalAngle = 0) { + const angle = this.getIndexAngle(index) - helpers_dataset.HALF_PI + additionalAngle; + return { + x: Math.cos(angle) * distanceFromCenter + this.xCenter, + y: Math.sin(angle) * distanceFromCenter + this.yCenter, + angle + }; + } + getPointPositionForValue(index, value) { + return this.getPointPosition(index, this.getDistanceFromCenterForValue(value)); + } + getBasePosition(index) { + return this.getPointPositionForValue(index || 0, this.getBaseValue()); + } + getPointLabelPosition(index) { + const { left , top , right , bottom } = this._pointLabelItems[index]; + return { + left, + top, + right, + bottom + }; + } + drawBackground() { + const { backgroundColor , grid: { circular } } = this.options; + if (backgroundColor) { + const ctx = this.ctx; + ctx.save(); + ctx.beginPath(); + pathRadiusLine(this, this.getDistanceFromCenterForValue(this._endValue), circular, this._pointLabels.length); + ctx.closePath(); + ctx.fillStyle = backgroundColor; + ctx.fill(); + ctx.restore(); + } + } + drawGrid() { + const ctx = this.ctx; + const opts = this.options; + const { angleLines , grid , border } = opts; + const labelCount = this._pointLabels.length; + let i, offset, position; + if (opts.pointLabels.display) { + drawPointLabels(this, labelCount); + } + if (grid.display) { + this.ticks.forEach((tick, index)=>{ + if (index !== 0 || index === 0 && this.min < 0) { + offset = this.getDistanceFromCenterForValue(tick.value); + const context = this.getContext(index); + const optsAtIndex = grid.setContext(context); + const optsAtIndexBorder = border.setContext(context); + drawRadiusLine(this, optsAtIndex, offset, labelCount, optsAtIndexBorder); + } + }); + } + if (angleLines.display) { + ctx.save(); + for(i = labelCount - 1; i >= 0; i--){ + const optsAtIndex = angleLines.setContext(this.getPointLabelContext(i)); + const { color , lineWidth } = optsAtIndex; + if (!lineWidth || !color) { + continue; + } + ctx.lineWidth = lineWidth; + ctx.strokeStyle = color; + ctx.setLineDash(optsAtIndex.borderDash); + ctx.lineDashOffset = optsAtIndex.borderDashOffset; + offset = this.getDistanceFromCenterForValue(opts.reverse ? this.min : this.max); + position = this.getPointPosition(i, offset); + ctx.beginPath(); + ctx.moveTo(this.xCenter, this.yCenter); + ctx.lineTo(position.x, position.y); + ctx.stroke(); + } + ctx.restore(); + } + } + drawBorder() {} + drawLabels() { + const ctx = this.ctx; + const opts = this.options; + const tickOpts = opts.ticks; + if (!tickOpts.display) { + return; + } + const startAngle = this.getIndexAngle(0); + let offset, width; + ctx.save(); + ctx.translate(this.xCenter, this.yCenter); + ctx.rotate(startAngle); + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + this.ticks.forEach((tick, index)=>{ + if (index === 0 && this.min >= 0 && !opts.reverse) { + return; + } + const optsAtIndex = tickOpts.setContext(this.getContext(index)); + const tickFont = helpers_dataset.toFont(optsAtIndex.font); + offset = this.getDistanceFromCenterForValue(this.ticks[index].value); + if (optsAtIndex.showLabelBackdrop) { + ctx.font = tickFont.string; + width = ctx.measureText(tick.label).width; + ctx.fillStyle = optsAtIndex.backdropColor; + const padding = helpers_dataset.toPadding(optsAtIndex.backdropPadding); + ctx.fillRect(-width / 2 - padding.left, -offset - tickFont.size / 2 - padding.top, width + padding.width, tickFont.size + padding.height); + } + helpers_dataset.renderText(ctx, tick.label, 0, -offset, tickFont, { + color: optsAtIndex.color, + strokeColor: optsAtIndex.textStrokeColor, + strokeWidth: optsAtIndex.textStrokeWidth + }); + }); + ctx.restore(); + } + drawTitle() {} +} + +const INTERVALS = { + millisecond: { + common: true, + size: 1, + steps: 1000 + }, + second: { + common: true, + size: 1000, + steps: 60 + }, + minute: { + common: true, + size: 60000, + steps: 60 + }, + hour: { + common: true, + size: 3600000, + steps: 24 + }, + day: { + common: true, + size: 86400000, + steps: 30 + }, + week: { + common: false, + size: 604800000, + steps: 4 + }, + month: { + common: true, + size: 2.628e9, + steps: 12 + }, + quarter: { + common: false, + size: 7.884e9, + steps: 4 + }, + year: { + common: true, + size: 3.154e10 + } +}; + const UNITS = /* #__PURE__ */ Object.keys(INTERVALS); + function sorter(a, b) { + return a - b; +} + function parse(scale, input) { + if (helpers_dataset.isNullOrUndef(input)) { + return null; + } + const adapter = scale._adapter; + const { parser , round , isoWeekday } = scale._parseOpts; + let value = input; + if (typeof parser === 'function') { + value = parser(value); + } + if (!helpers_dataset.isNumberFinite(value)) { + value = typeof parser === 'string' ? adapter.parse(value, parser) : adapter.parse(value); + } + if (value === null) { + return null; + } + if (round) { + value = round === 'week' && (helpers_dataset.isNumber(isoWeekday) || isoWeekday === true) ? adapter.startOf(value, 'isoWeek', isoWeekday) : adapter.startOf(value, round); + } + return +value; +} + function determineUnitForAutoTicks(minUnit, min, max, capacity) { + const ilen = UNITS.length; + for(let i = UNITS.indexOf(minUnit); i < ilen - 1; ++i){ + const interval = INTERVALS[UNITS[i]]; + const factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER; + if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) { + return UNITS[i]; + } + } + return UNITS[ilen - 1]; +} + function determineUnitForFormatting(scale, numTicks, minUnit, min, max) { + for(let i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--){ + const unit = UNITS[i]; + if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) { + return unit; + } + } + return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0]; +} + function determineMajorUnit(unit) { + for(let i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i){ + if (INTERVALS[UNITS[i]].common) { + return UNITS[i]; + } + } +} + function addTick(ticks, time, timestamps) { + if (!timestamps) { + ticks[time] = true; + } else if (timestamps.length) { + const { lo , hi } = helpers_dataset._lookup(timestamps, time); + const timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi]; + ticks[timestamp] = true; + } +} + function setMajorTicks(scale, ticks, map, majorUnit) { + const adapter = scale._adapter; + const first = +adapter.startOf(ticks[0].value, majorUnit); + const last = ticks[ticks.length - 1].value; + let major, index; + for(major = first; major <= last; major = +adapter.add(major, 1, majorUnit)){ + index = map[major]; + if (index >= 0) { + ticks[index].major = true; + } + } + return ticks; +} + function ticksFromTimestamps(scale, values, majorUnit) { + const ticks = []; + const map = {}; + const ilen = values.length; + let i, value; + for(i = 0; i < ilen; ++i){ + value = values[i]; + map[value] = i; + ticks.push({ + value, + major: false + }); + } + return ilen === 0 || !majorUnit ? ticks : setMajorTicks(scale, ticks, map, majorUnit); +} +class TimeScale extends Scale { + static id = 'time'; + static defaults = { + bounds: 'data', + adapters: {}, + time: { + parser: false, + unit: false, + round: false, + isoWeekday: false, + minUnit: 'millisecond', + displayFormats: {} + }, + ticks: { + source: 'auto', + callback: false, + major: { + enabled: false + } + } + }; + constructor(props){ + super(props); + this._cache = { + data: [], + labels: [], + all: [] + }; + this._unit = 'day'; + this._majorUnit = undefined; + this._offsets = {}; + this._normalized = false; + this._parseOpts = undefined; + } + init(scaleOpts, opts = {}) { + const time = scaleOpts.time || (scaleOpts.time = {}); + const adapter = this._adapter = new adapters._date(scaleOpts.adapters.date); + adapter.init(opts); + helpers_dataset.mergeIf(time.displayFormats, adapter.formats()); + this._parseOpts = { + parser: time.parser, + round: time.round, + isoWeekday: time.isoWeekday + }; + super.init(scaleOpts); + this._normalized = opts.normalized; + } + parse(raw, index) { + if (raw === undefined) { + return null; + } + return parse(this, raw); + } + beforeLayout() { + super.beforeLayout(); + this._cache = { + data: [], + labels: [], + all: [] + }; + } + determineDataLimits() { + const options = this.options; + const adapter = this._adapter; + const unit = options.time.unit || 'day'; + let { min , max , minDefined , maxDefined } = this.getUserBounds(); + function _applyBounds(bounds) { + if (!minDefined && !isNaN(bounds.min)) { + min = Math.min(min, bounds.min); + } + if (!maxDefined && !isNaN(bounds.max)) { + max = Math.max(max, bounds.max); + } + } + if (!minDefined || !maxDefined) { + _applyBounds(this._getLabelBounds()); + if (options.bounds !== 'ticks' || options.ticks.source !== 'labels') { + _applyBounds(this.getMinMax(false)); + } + } + min = helpers_dataset.isNumberFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit); + max = helpers_dataset.isNumberFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1; + this.min = Math.min(min, max - 1); + this.max = Math.max(min + 1, max); + } + _getLabelBounds() { + const arr = this.getLabelTimestamps(); + let min = Number.POSITIVE_INFINITY; + let max = Number.NEGATIVE_INFINITY; + if (arr.length) { + min = arr[0]; + max = arr[arr.length - 1]; + } + return { + min, + max + }; + } + buildTicks() { + const options = this.options; + const timeOpts = options.time; + const tickOpts = options.ticks; + const timestamps = tickOpts.source === 'labels' ? this.getLabelTimestamps() : this._generate(); + if (options.bounds === 'ticks' && timestamps.length) { + this.min = this._userMin || timestamps[0]; + this.max = this._userMax || timestamps[timestamps.length - 1]; + } + const min = this.min; + const max = this.max; + const ticks = helpers_dataset._filterBetween(timestamps, min, max); + this._unit = timeOpts.unit || (tickOpts.autoSkip ? determineUnitForAutoTicks(timeOpts.minUnit, this.min, this.max, this._getLabelCapacity(min)) : determineUnitForFormatting(this, ticks.length, timeOpts.minUnit, this.min, this.max)); + this._majorUnit = !tickOpts.major.enabled || this._unit === 'year' ? undefined : determineMajorUnit(this._unit); + this.initOffsets(timestamps); + if (options.reverse) { + ticks.reverse(); + } + return ticksFromTimestamps(this, ticks, this._majorUnit); + } + afterAutoSkip() { + if (this.options.offsetAfterAutoskip) { + this.initOffsets(this.ticks.map((tick)=>+tick.value)); + } + } + initOffsets(timestamps = []) { + let start = 0; + let end = 0; + let first, last; + if (this.options.offset && timestamps.length) { + first = this.getDecimalForValue(timestamps[0]); + if (timestamps.length === 1) { + start = 1 - first; + } else { + start = (this.getDecimalForValue(timestamps[1]) - first) / 2; + } + last = this.getDecimalForValue(timestamps[timestamps.length - 1]); + if (timestamps.length === 1) { + end = last; + } else { + end = (last - this.getDecimalForValue(timestamps[timestamps.length - 2])) / 2; + } + } + const limit = timestamps.length < 3 ? 0.5 : 0.25; + start = helpers_dataset._limitValue(start, 0, limit); + end = helpers_dataset._limitValue(end, 0, limit); + this._offsets = { + start, + end, + factor: 1 / (start + 1 + end) + }; + } + _generate() { + const adapter = this._adapter; + const min = this.min; + const max = this.max; + const options = this.options; + const timeOpts = options.time; + const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, this._getLabelCapacity(min)); + const stepSize = helpers_dataset.valueOrDefault(options.ticks.stepSize, 1); + const weekday = minor === 'week' ? timeOpts.isoWeekday : false; + const hasWeekday = helpers_dataset.isNumber(weekday) || weekday === true; + const ticks = {}; + let first = min; + let time, count; + if (hasWeekday) { + first = +adapter.startOf(first, 'isoWeek', weekday); + } + first = +adapter.startOf(first, hasWeekday ? 'day' : minor); + if (adapter.diff(max, min, minor) > 100000 * stepSize) { + throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor); + } + const timestamps = options.ticks.source === 'data' && this.getDataTimestamps(); + for(time = first, count = 0; time < max; time = +adapter.add(time, stepSize, minor), count++){ + addTick(ticks, time, timestamps); + } + if (time === max || options.bounds === 'ticks' || count === 1) { + addTick(ticks, time, timestamps); + } + return Object.keys(ticks).sort(sorter).map((x)=>+x); + } + getLabelForValue(value) { + const adapter = this._adapter; + const timeOpts = this.options.time; + if (timeOpts.tooltipFormat) { + return adapter.format(value, timeOpts.tooltipFormat); + } + return adapter.format(value, timeOpts.displayFormats.datetime); + } + format(value, format) { + const options = this.options; + const formats = options.time.displayFormats; + const unit = this._unit; + const fmt = format || formats[unit]; + return this._adapter.format(value, fmt); + } + _tickFormatFunction(time, index, ticks, format) { + const options = this.options; + const formatter = options.ticks.callback; + if (formatter) { + return helpers_dataset.callback(formatter, [ + time, + index, + ticks + ], this); + } + const formats = options.time.displayFormats; + const unit = this._unit; + const majorUnit = this._majorUnit; + const minorFormat = unit && formats[unit]; + const majorFormat = majorUnit && formats[majorUnit]; + const tick = ticks[index]; + const major = majorUnit && majorFormat && tick && tick.major; + return this._adapter.format(time, format || (major ? majorFormat : minorFormat)); + } + generateTickLabels(ticks) { + let i, ilen, tick; + for(i = 0, ilen = ticks.length; i < ilen; ++i){ + tick = ticks[i]; + tick.label = this._tickFormatFunction(tick.value, i, ticks); + } + } + getDecimalForValue(value) { + return value === null ? NaN : (value - this.min) / (this.max - this.min); + } + getPixelForValue(value) { + const offsets = this._offsets; + const pos = this.getDecimalForValue(value); + return this.getPixelForDecimal((offsets.start + pos) * offsets.factor); + } + getValueForPixel(pixel) { + const offsets = this._offsets; + const pos = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end; + return this.min + pos * (this.max - this.min); + } + _getLabelSize(label) { + const ticksOpts = this.options.ticks; + const tickLabelWidth = this.ctx.measureText(label).width; + const angle = helpers_dataset.toRadians(this.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation); + const cosRotation = Math.cos(angle); + const sinRotation = Math.sin(angle); + const tickFontSize = this._resolveTickFontOptions(0).size; + return { + w: tickLabelWidth * cosRotation + tickFontSize * sinRotation, + h: tickLabelWidth * sinRotation + tickFontSize * cosRotation + }; + } + _getLabelCapacity(exampleTime) { + const timeOpts = this.options.time; + const displayFormats = timeOpts.displayFormats; + const format = displayFormats[timeOpts.unit] || displayFormats.millisecond; + const exampleLabel = this._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(this, [ + exampleTime + ], this._majorUnit), format); + const size = this._getLabelSize(exampleLabel); + const capacity = Math.floor(this.isHorizontal() ? this.width / size.w : this.height / size.h) - 1; + return capacity > 0 ? capacity : 1; + } + getDataTimestamps() { + let timestamps = this._cache.data || []; + let i, ilen; + if (timestamps.length) { + return timestamps; + } + const metas = this.getMatchingVisibleMetas(); + if (this._normalized && metas.length) { + return this._cache.data = metas[0].controller.getAllParsedValues(this); + } + for(i = 0, ilen = metas.length; i < ilen; ++i){ + timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(this)); + } + return this._cache.data = this.normalize(timestamps); + } + getLabelTimestamps() { + const timestamps = this._cache.labels || []; + let i, ilen; + if (timestamps.length) { + return timestamps; + } + const labels = this.getLabels(); + for(i = 0, ilen = labels.length; i < ilen; ++i){ + timestamps.push(parse(this, labels[i])); + } + return this._cache.labels = this._normalized ? timestamps : this.normalize(timestamps); + } + normalize(values) { + return helpers_dataset._arrayUnique(values.sort(sorter)); + } +} + +function interpolate(table, val, reverse) { + let lo = 0; + let hi = table.length - 1; + let prevSource, nextSource, prevTarget, nextTarget; + if (reverse) { + if (val >= table[lo].pos && val <= table[hi].pos) { + ({ lo , hi } = helpers_dataset._lookupByKey(table, 'pos', val)); + } + ({ pos: prevSource , time: prevTarget } = table[lo]); + ({ pos: nextSource , time: nextTarget } = table[hi]); + } else { + if (val >= table[lo].time && val <= table[hi].time) { + ({ lo , hi } = helpers_dataset._lookupByKey(table, 'time', val)); + } + ({ time: prevSource , pos: prevTarget } = table[lo]); + ({ time: nextSource , pos: nextTarget } = table[hi]); + } + const span = nextSource - prevSource; + return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget; +} +class TimeSeriesScale extends TimeScale { + static id = 'timeseries'; + static defaults = TimeScale.defaults; + constructor(props){ + super(props); + this._table = []; + this._minPos = undefined; + this._tableRange = undefined; + } + initOffsets() { + const timestamps = this._getTimestampsForTable(); + const table = this._table = this.buildLookupTable(timestamps); + this._minPos = interpolate(table, this.min); + this._tableRange = interpolate(table, this.max) - this._minPos; + super.initOffsets(timestamps); + } + buildLookupTable(timestamps) { + const { min , max } = this; + const items = []; + const table = []; + let i, ilen, prev, curr, next; + for(i = 0, ilen = timestamps.length; i < ilen; ++i){ + curr = timestamps[i]; + if (curr >= min && curr <= max) { + items.push(curr); + } + } + if (items.length < 2) { + return [ + { + time: min, + pos: 0 + }, + { + time: max, + pos: 1 + } + ]; + } + for(i = 0, ilen = items.length; i < ilen; ++i){ + next = items[i + 1]; + prev = items[i - 1]; + curr = items[i]; + if (Math.round((next + prev) / 2) !== curr) { + table.push({ + time: curr, + pos: i / (ilen - 1) + }); + } + } + return table; + } + _generate() { + const min = this.min; + const max = this.max; + let timestamps = super.getDataTimestamps(); + if (!timestamps.includes(min) || !timestamps.length) { + timestamps.splice(0, 0, min); + } + if (!timestamps.includes(max) || timestamps.length === 1) { + timestamps.push(max); + } + return timestamps.sort((a, b)=>a - b); + } + _getTimestampsForTable() { + let timestamps = this._cache.all || []; + if (timestamps.length) { + return timestamps; + } + const data = this.getDataTimestamps(); + const label = this.getLabelTimestamps(); + if (data.length && label.length) { + timestamps = this.normalize(data.concat(label)); + } else { + timestamps = data.length ? data : label; + } + timestamps = this._cache.all = timestamps; + return timestamps; + } + getDecimalForValue(value) { + return (interpolate(this._table, value) - this._minPos) / this._tableRange; + } + getValueForPixel(pixel) { + const offsets = this._offsets; + const decimal = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end; + return interpolate(this._table, decimal * this._tableRange + this._minPos, true); + } +} + +var scales = /*#__PURE__*/Object.freeze({ +__proto__: null, +CategoryScale: CategoryScale, +LinearScale: LinearScale, +LogarithmicScale: LogarithmicScale, +RadialLinearScale: RadialLinearScale, +TimeScale: TimeScale, +TimeSeriesScale: TimeSeriesScale +}); + +const registerables = [ + controllers, + elements, + plugins, + scales +]; + +exports.Ticks = helpers_dataset.Ticks; +exports.defaults = helpers_dataset.defaults; +exports.Animation = Animation; +exports.Animations = Animations; +exports.ArcElement = ArcElement; +exports.BarController = BarController; +exports.BarElement = BarElement; +exports.BasePlatform = BasePlatform; +exports.BasicPlatform = BasicPlatform; +exports.BubbleController = BubbleController; +exports.CategoryScale = CategoryScale; +exports.Chart = Chart; +exports.Colors = plugin_colors; +exports.DatasetController = DatasetController; +exports.Decimation = plugin_decimation; +exports.DomPlatform = DomPlatform; +exports.DoughnutController = DoughnutController; +exports.Element = Element; +exports.Filler = index; +exports.Interaction = Interaction; +exports.Legend = plugin_legend; +exports.LineController = LineController; +exports.LineElement = LineElement; +exports.LinearScale = LinearScale; +exports.LogarithmicScale = LogarithmicScale; +exports.PieController = PieController; +exports.PointElement = PointElement; +exports.PolarAreaController = PolarAreaController; +exports.RadarController = RadarController; +exports.RadialLinearScale = RadialLinearScale; +exports.Scale = Scale; +exports.ScatterController = ScatterController; +exports.SubTitle = plugin_subtitle; +exports.TimeScale = TimeScale; +exports.TimeSeriesScale = TimeSeriesScale; +exports.Title = plugin_title; +exports.Tooltip = plugin_tooltip; +exports._adapters = adapters; +exports._detectPlatform = _detectPlatform; +exports.animator = animator; +exports.controllers = controllers; +exports.elements = elements; +exports.layouts = layouts; +exports.plugins = plugins; +exports.registerables = registerables; +exports.registry = registry; +exports.scales = scales; +//# sourceMappingURL=chart.cjs.map diff --git a/frontend/node_modules/chart.js/dist/chart.cjs.map b/frontend/node_modules/chart.js/dist/chart.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..54bfb1f6a51e89b48c455dc9aa154875002abe85 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/chart.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"chart.cjs","sources":["../src/core/core.animator.js","../src/core/core.animation.js","../src/core/core.animations.js","../src/core/core.datasetController.js","../src/controllers/controller.bar.js","../src/controllers/controller.bubble.js","../src/controllers/controller.doughnut.js","../src/controllers/controller.line.js","../src/controllers/controller.polarArea.js","../src/controllers/controller.pie.js","../src/controllers/controller.radar.js","../src/controllers/controller.scatter.js","../src/core/core.adapters.ts","../src/core/core.interaction.js","../src/core/core.layouts.js","../src/platform/platform.base.js","../src/platform/platform.basic.js","../src/platform/platform.dom.js","../src/platform/index.js","../src/core/core.element.ts","../src/core/core.scale.autoskip.js","../src/core/core.scale.js","../src/core/core.typedRegistry.js","../src/core/core.registry.js","../src/core/core.plugins.js","../src/core/core.config.js","../src/core/core.controller.js","../src/elements/element.arc.ts","../src/elements/element.line.js","../src/elements/element.point.ts","../src/elements/element.bar.js","../src/plugins/plugin.colors.ts","../src/plugins/plugin.decimation.js","../src/plugins/plugin.filler/filler.segment.js","../src/plugins/plugin.filler/filler.helper.js","../src/plugins/plugin.filler/filler.options.js","../src/plugins/plugin.filler/filler.target.stack.js","../src/plugins/plugin.filler/simpleArc.js","../src/plugins/plugin.filler/filler.target.js","../src/plugins/plugin.filler/filler.drawing.js","../src/plugins/plugin.filler/index.js","../src/plugins/plugin.legend.js","../src/plugins/plugin.title.js","../src/plugins/plugin.subtitle.js","../src/plugins/plugin.tooltip.js","../src/scales/scale.category.js","../src/scales/scale.linearbase.js","../src/scales/scale.linear.js","../src/scales/scale.logarithmic.js","../src/scales/scale.radialLinear.js","../src/scales/scale.time.js","../src/scales/scale.timeseries.js","../src/index.ts"],"sourcesContent":["import {requestAnimFrame} from '../helpers/helpers.extras.js';\n\n/**\n * @typedef { import('./core.animation.js').default } Animation\n * @typedef { import('./core.controller.js').default } Chart\n */\n\n/**\n * Please use the module's default export which provides a singleton instance\n * Note: class is export for typedoc\n */\nexport class Animator {\n constructor() {\n this._request = null;\n this._charts = new Map();\n this._running = false;\n this._lastDate = undefined;\n }\n\n /**\n\t * @private\n\t */\n _notify(chart, anims, date, type) {\n const callbacks = anims.listeners[type];\n const numSteps = anims.duration;\n\n callbacks.forEach(fn => fn({\n chart,\n initial: anims.initial,\n numSteps,\n currentStep: Math.min(date - anims.start, numSteps)\n }));\n }\n\n /**\n\t * @private\n\t */\n _refresh() {\n if (this._request) {\n return;\n }\n this._running = true;\n\n this._request = requestAnimFrame.call(window, () => {\n this._update();\n this._request = null;\n\n if (this._running) {\n this._refresh();\n }\n });\n }\n\n /**\n\t * @private\n\t */\n _update(date = Date.now()) {\n let remaining = 0;\n\n this._charts.forEach((anims, chart) => {\n if (!anims.running || !anims.items.length) {\n return;\n }\n const items = anims.items;\n let i = items.length - 1;\n let draw = false;\n let item;\n\n for (; i >= 0; --i) {\n item = items[i];\n\n if (item._active) {\n if (item._total > anims.duration) {\n // if the animation has been updated and its duration prolonged,\n // update to total duration of current animations run (for progress event)\n anims.duration = item._total;\n }\n item.tick(date);\n draw = true;\n } else {\n // Remove the item by replacing it with last item and removing the last\n // A lot faster than splice.\n items[i] = items[items.length - 1];\n items.pop();\n }\n }\n\n if (draw) {\n chart.draw();\n this._notify(chart, anims, date, 'progress');\n }\n\n if (!items.length) {\n anims.running = false;\n this._notify(chart, anims, date, 'complete');\n anims.initial = false;\n }\n\n remaining += items.length;\n });\n\n this._lastDate = date;\n\n if (remaining === 0) {\n this._running = false;\n }\n }\n\n /**\n\t * @private\n\t */\n _getAnims(chart) {\n const charts = this._charts;\n let anims = charts.get(chart);\n if (!anims) {\n anims = {\n running: false,\n initial: true,\n items: [],\n listeners: {\n complete: [],\n progress: []\n }\n };\n charts.set(chart, anims);\n }\n return anims;\n }\n\n /**\n\t * @param {Chart} chart\n\t * @param {string} event - event name\n\t * @param {Function} cb - callback\n\t */\n listen(chart, event, cb) {\n this._getAnims(chart).listeners[event].push(cb);\n }\n\n /**\n\t * Add animations\n\t * @param {Chart} chart\n\t * @param {Animation[]} items - animations\n\t */\n add(chart, items) {\n if (!items || !items.length) {\n return;\n }\n this._getAnims(chart).items.push(...items);\n }\n\n /**\n\t * Counts number of active animations for the chart\n\t * @param {Chart} chart\n\t */\n has(chart) {\n return this._getAnims(chart).items.length > 0;\n }\n\n /**\n\t * Start animating (all charts)\n\t * @param {Chart} chart\n\t */\n start(chart) {\n const anims = this._charts.get(chart);\n if (!anims) {\n return;\n }\n anims.running = true;\n anims.start = Date.now();\n anims.duration = anims.items.reduce((acc, cur) => Math.max(acc, cur._duration), 0);\n this._refresh();\n }\n\n running(chart) {\n if (!this._running) {\n return false;\n }\n const anims = this._charts.get(chart);\n if (!anims || !anims.running || !anims.items.length) {\n return false;\n }\n return true;\n }\n\n /**\n\t * Stop all animations for the chart\n\t * @param {Chart} chart\n\t */\n stop(chart) {\n const anims = this._charts.get(chart);\n if (!anims || !anims.items.length) {\n return;\n }\n const items = anims.items;\n let i = items.length - 1;\n\n for (; i >= 0; --i) {\n items[i].cancel();\n }\n anims.items = [];\n this._notify(chart, anims, Date.now(), 'complete');\n }\n\n /**\n\t * Remove chart from Animator\n\t * @param {Chart} chart\n\t */\n remove(chart) {\n return this._charts.delete(chart);\n }\n}\n\n// singleton instance\nexport default /* #__PURE__ */ new Animator();\n","import effects from '../helpers/helpers.easing.js';\nimport {resolve} from '../helpers/helpers.options.js';\nimport {color as helpersColor} from '../helpers/helpers.color.js';\n\nconst transparent = 'transparent';\nconst interpolators = {\n boolean(from, to, factor) {\n return factor > 0.5 ? to : from;\n },\n /**\n * @param {string} from\n * @param {string} to\n * @param {number} factor\n */\n color(from, to, factor) {\n const c0 = helpersColor(from || transparent);\n const c1 = c0.valid && helpersColor(to || transparent);\n return c1 && c1.valid\n ? c1.mix(c0, factor).hexString()\n : to;\n },\n number(from, to, factor) {\n return from + (to - from) * factor;\n }\n};\n\nexport default class Animation {\n constructor(cfg, target, prop, to) {\n const currentValue = target[prop];\n\n to = resolve([cfg.to, to, currentValue, cfg.from]);\n const from = resolve([cfg.from, currentValue, to]);\n\n this._active = true;\n this._fn = cfg.fn || interpolators[cfg.type || typeof from];\n this._easing = effects[cfg.easing] || effects.linear;\n this._start = Math.floor(Date.now() + (cfg.delay || 0));\n this._duration = this._total = Math.floor(cfg.duration);\n this._loop = !!cfg.loop;\n this._target = target;\n this._prop = prop;\n this._from = from;\n this._to = to;\n this._promises = undefined;\n }\n\n active() {\n return this._active;\n }\n\n update(cfg, to, date) {\n if (this._active) {\n this._notify(false);\n\n const currentValue = this._target[this._prop];\n const elapsed = date - this._start;\n const remain = this._duration - elapsed;\n this._start = date;\n this._duration = Math.floor(Math.max(remain, cfg.duration));\n this._total += elapsed;\n this._loop = !!cfg.loop;\n this._to = resolve([cfg.to, to, currentValue, cfg.from]);\n this._from = resolve([cfg.from, currentValue, to]);\n }\n }\n\n cancel() {\n if (this._active) {\n // update current evaluated value, for smoother animations\n this.tick(Date.now());\n this._active = false;\n this._notify(false);\n }\n }\n\n tick(date) {\n const elapsed = date - this._start;\n const duration = this._duration;\n const prop = this._prop;\n const from = this._from;\n const loop = this._loop;\n const to = this._to;\n let factor;\n\n this._active = from !== to && (loop || (elapsed < duration));\n\n if (!this._active) {\n this._target[prop] = to;\n this._notify(true);\n return;\n }\n\n if (elapsed < 0) {\n this._target[prop] = from;\n return;\n }\n\n factor = (elapsed / duration) % 2;\n factor = loop && factor > 1 ? 2 - factor : factor;\n factor = this._easing(Math.min(1, Math.max(0, factor)));\n\n this._target[prop] = this._fn(from, to, factor);\n }\n\n wait() {\n const promises = this._promises || (this._promises = []);\n return new Promise((res, rej) => {\n promises.push({res, rej});\n });\n }\n\n _notify(resolved) {\n const method = resolved ? 'res' : 'rej';\n const promises = this._promises || [];\n for (let i = 0; i < promises.length; i++) {\n promises[i][method]();\n }\n }\n}\n","import animator from './core.animator.js';\nimport Animation from './core.animation.js';\nimport defaults from './core.defaults.js';\nimport {isArray, isObject} from '../helpers/helpers.core.js';\n\nexport default class Animations {\n constructor(chart, config) {\n this._chart = chart;\n this._properties = new Map();\n this.configure(config);\n }\n\n configure(config) {\n if (!isObject(config)) {\n return;\n }\n\n const animationOptions = Object.keys(defaults.animation);\n const animatedProps = this._properties;\n\n Object.getOwnPropertyNames(config).forEach(key => {\n const cfg = config[key];\n if (!isObject(cfg)) {\n return;\n }\n const resolved = {};\n for (const option of animationOptions) {\n resolved[option] = cfg[option];\n }\n\n (isArray(cfg.properties) && cfg.properties || [key]).forEach((prop) => {\n if (prop === key || !animatedProps.has(prop)) {\n animatedProps.set(prop, resolved);\n }\n });\n });\n }\n\n /**\n\t * Utility to handle animation of `options`.\n\t * @private\n\t */\n _animateOptions(target, values) {\n const newOptions = values.options;\n const options = resolveTargetOptions(target, newOptions);\n if (!options) {\n return [];\n }\n\n const animations = this._createAnimations(options, newOptions);\n if (newOptions.$shared) {\n // Going to shared options:\n // After all animations are done, assign the shared options object to the element\n // So any new updates to the shared options are observed\n awaitAll(target.options.$animations, newOptions).then(() => {\n target.options = newOptions;\n }, () => {\n // rejected, noop\n });\n }\n\n return animations;\n }\n\n /**\n\t * @private\n\t */\n _createAnimations(target, values) {\n const animatedProps = this._properties;\n const animations = [];\n const running = target.$animations || (target.$animations = {});\n const props = Object.keys(values);\n const date = Date.now();\n let i;\n\n for (i = props.length - 1; i >= 0; --i) {\n const prop = props[i];\n if (prop.charAt(0) === '$') {\n continue;\n }\n\n if (prop === 'options') {\n animations.push(...this._animateOptions(target, values));\n continue;\n }\n const value = values[prop];\n let animation = running[prop];\n const cfg = animatedProps.get(prop);\n\n if (animation) {\n if (cfg && animation.active()) {\n // There is an existing active animation, let's update that\n animation.update(cfg, value, date);\n continue;\n } else {\n animation.cancel();\n }\n }\n if (!cfg || !cfg.duration) {\n // not animated, set directly to new value\n target[prop] = value;\n continue;\n }\n\n running[prop] = animation = new Animation(cfg, target, prop, value);\n animations.push(animation);\n }\n return animations;\n }\n\n\n /**\n\t * Update `target` properties to new values, using configured animations\n\t * @param {object} target - object to update\n\t * @param {object} values - new target properties\n\t * @returns {boolean|undefined} - `true` if animations were started\n\t **/\n update(target, values) {\n if (this._properties.size === 0) {\n // Nothing is animated, just apply the new values.\n Object.assign(target, values);\n return;\n }\n\n const animations = this._createAnimations(target, values);\n\n if (animations.length) {\n animator.add(this._chart, animations);\n return true;\n }\n }\n}\n\nfunction awaitAll(animations, properties) {\n const running = [];\n const keys = Object.keys(properties);\n for (let i = 0; i < keys.length; i++) {\n const anim = animations[keys[i]];\n if (anim && anim.active()) {\n running.push(anim.wait());\n }\n }\n // @ts-ignore\n return Promise.all(running);\n}\n\nfunction resolveTargetOptions(target, newOptions) {\n if (!newOptions) {\n return;\n }\n let options = target.options;\n if (!options) {\n target.options = newOptions;\n return;\n }\n if (options.$shared) {\n // Going from shared options to distinct one:\n // Create new options object containing the old shared values and start updating that.\n target.options = options = Object.assign({}, options, {$shared: false, $animations: {}});\n }\n return options;\n}\n","import Animations from './core.animations.js';\nimport defaults from './core.defaults.js';\nimport {isArray, isFinite, isObject, valueOrDefault, resolveObjectKey, defined} from '../helpers/helpers.core.js';\nimport {listenArrayEvents, unlistenArrayEvents} from '../helpers/helpers.collection.js';\nimport {createContext, sign} from '../helpers/index.js';\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n * @typedef { import('./core.scale.js').default } Scale\n */\n\nfunction scaleClip(scale, allowedOverflow) {\n const opts = scale && scale.options || {};\n const reverse = opts.reverse;\n const min = opts.min === undefined ? allowedOverflow : 0;\n const max = opts.max === undefined ? allowedOverflow : 0;\n return {\n start: reverse ? max : min,\n end: reverse ? min : max\n };\n}\n\nfunction defaultClip(xScale, yScale, allowedOverflow) {\n if (allowedOverflow === false) {\n return false;\n }\n const x = scaleClip(xScale, allowedOverflow);\n const y = scaleClip(yScale, allowedOverflow);\n\n return {\n top: y.end,\n right: x.end,\n bottom: y.start,\n left: x.start\n };\n}\n\nfunction toClip(value) {\n let t, r, b, l;\n\n if (isObject(value)) {\n t = value.top;\n r = value.right;\n b = value.bottom;\n l = value.left;\n } else {\n t = r = b = l = value;\n }\n\n return {\n top: t,\n right: r,\n bottom: b,\n left: l,\n disabled: value === false\n };\n}\n\nfunction getSortedDatasetIndices(chart, filterVisible) {\n const keys = [];\n const metasets = chart._getSortedDatasetMetas(filterVisible);\n let i, ilen;\n\n for (i = 0, ilen = metasets.length; i < ilen; ++i) {\n keys.push(metasets[i].index);\n }\n return keys;\n}\n\nfunction applyStack(stack, value, dsIndex, options = {}) {\n const keys = stack.keys;\n const singleMode = options.mode === 'single';\n let i, ilen, datasetIndex, otherValue;\n\n if (value === null) {\n return;\n }\n\n let found = false;\n for (i = 0, ilen = keys.length; i < ilen; ++i) {\n datasetIndex = +keys[i];\n if (datasetIndex === dsIndex) {\n found = true;\n if (options.all) {\n continue;\n }\n break;\n }\n otherValue = stack.values[datasetIndex];\n if (isFinite(otherValue) && (singleMode || (value === 0 || sign(value) === sign(otherValue)))) {\n value += otherValue;\n }\n }\n\n if (!found && !options.all) {\n return 0;\n }\n\n return value;\n}\n\nfunction convertObjectDataToArray(data, meta) {\n const {iScale, vScale} = meta;\n const iAxisKey = iScale.axis === 'x' ? 'x' : 'y';\n const vAxisKey = vScale.axis === 'x' ? 'x' : 'y';\n const keys = Object.keys(data);\n const adata = new Array(keys.length);\n let i, ilen, key;\n for (i = 0, ilen = keys.length; i < ilen; ++i) {\n key = keys[i];\n adata[i] = {\n [iAxisKey]: key,\n [vAxisKey]: data[key]\n };\n }\n return adata;\n}\n\nfunction isStacked(scale, meta) {\n const stacked = scale && scale.options.stacked;\n return stacked || (stacked === undefined && meta.stack !== undefined);\n}\n\nfunction getStackKey(indexScale, valueScale, meta) {\n return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`;\n}\n\nfunction getUserBounds(scale) {\n const {min, max, minDefined, maxDefined} = scale.getUserBounds();\n return {\n min: minDefined ? min : Number.NEGATIVE_INFINITY,\n max: maxDefined ? max : Number.POSITIVE_INFINITY\n };\n}\n\nfunction getOrCreateStack(stacks, stackKey, indexValue) {\n const subStack = stacks[stackKey] || (stacks[stackKey] = {});\n return subStack[indexValue] || (subStack[indexValue] = {});\n}\n\nfunction getLastIndexInStack(stack, vScale, positive, type) {\n for (const meta of vScale.getMatchingVisibleMetas(type).reverse()) {\n const value = stack[meta.index];\n if ((positive && value > 0) || (!positive && value < 0)) {\n return meta.index;\n }\n }\n\n return null;\n}\n\nfunction updateStacks(controller, parsed) {\n const {chart, _cachedMeta: meta} = controller;\n const stacks = chart._stacks || (chart._stacks = {}); // map structure is {stackKey: {datasetIndex: value}}\n const {iScale, vScale, index: datasetIndex} = meta;\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const key = getStackKey(iScale, vScale, meta);\n const ilen = parsed.length;\n let stack;\n\n for (let i = 0; i < ilen; ++i) {\n const item = parsed[i];\n const {[iAxis]: index, [vAxis]: value} = item;\n const itemStacks = item._stacks || (item._stacks = {});\n stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index);\n stack[datasetIndex] = value;\n\n stack._top = getLastIndexInStack(stack, vScale, true, meta.type);\n stack._bottom = getLastIndexInStack(stack, vScale, false, meta.type);\n\n const visualValues = stack._visualValues || (stack._visualValues = {});\n visualValues[datasetIndex] = value;\n }\n}\n\nfunction getFirstScaleId(chart, axis) {\n const scales = chart.scales;\n return Object.keys(scales).filter(key => scales[key].axis === axis).shift();\n}\n\nfunction createDatasetContext(parent, index) {\n return createContext(parent,\n {\n active: false,\n dataset: undefined,\n datasetIndex: index,\n index,\n mode: 'default',\n type: 'dataset'\n }\n );\n}\n\nfunction createDataContext(parent, index, element) {\n return createContext(parent, {\n active: false,\n dataIndex: index,\n parsed: undefined,\n raw: undefined,\n element,\n index,\n mode: 'default',\n type: 'data'\n });\n}\n\nfunction clearStacks(meta, items) {\n // Not using meta.index here, because it might be already updated if the dataset changed location\n const datasetIndex = meta.controller.index;\n const axis = meta.vScale && meta.vScale.axis;\n if (!axis) {\n return;\n }\n\n items = items || meta._parsed;\n for (const parsed of items) {\n const stacks = parsed._stacks;\n if (!stacks || stacks[axis] === undefined || stacks[axis][datasetIndex] === undefined) {\n return;\n }\n delete stacks[axis][datasetIndex];\n if (stacks[axis]._visualValues !== undefined && stacks[axis]._visualValues[datasetIndex] !== undefined) {\n delete stacks[axis]._visualValues[datasetIndex];\n }\n }\n}\n\nconst isDirectUpdateMode = (mode) => mode === 'reset' || mode === 'none';\nconst cloneIfNotShared = (cached, shared) => shared ? cached : Object.assign({}, cached);\nconst createStack = (canStack, meta, chart) => canStack && !meta.hidden && meta._stacked\n && {keys: getSortedDatasetIndices(chart, true), values: null};\n\nexport default class DatasetController {\n\n /**\n * @type {any}\n */\n static defaults = {};\n\n /**\n * Element type used to generate a meta dataset (e.g. Chart.element.LineElement).\n */\n static datasetElementType = null;\n\n /**\n * Element type used to generate a meta data (e.g. Chart.element.PointElement).\n */\n static dataElementType = null;\n\n /**\n\t * @param {Chart} chart\n\t * @param {number} datasetIndex\n\t */\n constructor(chart, datasetIndex) {\n this.chart = chart;\n this._ctx = chart.ctx;\n this.index = datasetIndex;\n this._cachedDataOpts = {};\n this._cachedMeta = this.getMeta();\n this._type = this._cachedMeta.type;\n this.options = undefined;\n /** @type {boolean | object} */\n this._parsing = false;\n this._data = undefined;\n this._objectData = undefined;\n this._sharedOptions = undefined;\n this._drawStart = undefined;\n this._drawCount = undefined;\n this.enableOptionSharing = false;\n this.supportsDecimation = false;\n this.$context = undefined;\n this._syncList = [];\n this.datasetElementType = new.target.datasetElementType;\n this.dataElementType = new.target.dataElementType;\n\n this.initialize();\n }\n\n initialize() {\n const meta = this._cachedMeta;\n this.configure();\n this.linkScales();\n meta._stacked = isStacked(meta.vScale, meta);\n this.addElements();\n\n if (this.options.fill && !this.chart.isPluginEnabled('filler')) {\n console.warn(\"Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options\");\n }\n }\n\n updateIndex(datasetIndex) {\n if (this.index !== datasetIndex) {\n clearStacks(this._cachedMeta);\n }\n this.index = datasetIndex;\n }\n\n linkScales() {\n const chart = this.chart;\n const meta = this._cachedMeta;\n const dataset = this.getDataset();\n\n const chooseId = (axis, x, y, r) => axis === 'x' ? x : axis === 'r' ? r : y;\n\n const xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x'));\n const yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y'));\n const rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r'));\n const indexAxis = meta.indexAxis;\n const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid);\n const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid);\n meta.xScale = this.getScaleForId(xid);\n meta.yScale = this.getScaleForId(yid);\n meta.rScale = this.getScaleForId(rid);\n meta.iScale = this.getScaleForId(iid);\n meta.vScale = this.getScaleForId(vid);\n }\n\n getDataset() {\n return this.chart.data.datasets[this.index];\n }\n\n getMeta() {\n return this.chart.getDatasetMeta(this.index);\n }\n\n /**\n\t * @param {string} scaleID\n\t * @return {Scale}\n\t */\n getScaleForId(scaleID) {\n return this.chart.scales[scaleID];\n }\n\n /**\n\t * @private\n\t */\n _getOtherScale(scale) {\n const meta = this._cachedMeta;\n return scale === meta.iScale\n ? meta.vScale\n : meta.iScale;\n }\n\n reset() {\n this._update('reset');\n }\n\n /**\n\t * @private\n\t */\n _destroy() {\n const meta = this._cachedMeta;\n if (this._data) {\n unlistenArrayEvents(this._data, this);\n }\n if (meta._stacked) {\n clearStacks(meta);\n }\n }\n\n /**\n\t * @private\n\t */\n _dataCheck() {\n const dataset = this.getDataset();\n const data = dataset.data || (dataset.data = []);\n const _data = this._data;\n\n // In order to correctly handle data addition/deletion animation (and thus simulate\n // real-time charts), we need to monitor these data modifications and synchronize\n // the internal metadata accordingly.\n\n if (isObject(data)) {\n const meta = this._cachedMeta;\n this._data = convertObjectDataToArray(data, meta);\n } else if (_data !== data) {\n if (_data) {\n // This case happens when the user replaced the data array instance.\n unlistenArrayEvents(_data, this);\n // Discard old parsed data and stacks\n const meta = this._cachedMeta;\n clearStacks(meta);\n meta._parsed = [];\n }\n if (data && Object.isExtensible(data)) {\n listenArrayEvents(data, this);\n }\n this._syncList = [];\n this._data = data;\n }\n }\n\n addElements() {\n const meta = this._cachedMeta;\n\n this._dataCheck();\n\n if (this.datasetElementType) {\n meta.dataset = new this.datasetElementType();\n }\n }\n\n buildOrUpdateElements(resetNewElements) {\n const meta = this._cachedMeta;\n const dataset = this.getDataset();\n let stackChanged = false;\n\n this._dataCheck();\n\n // make sure cached _stacked status is current\n const oldStacked = meta._stacked;\n meta._stacked = isStacked(meta.vScale, meta);\n\n // detect change in stack option\n if (meta.stack !== dataset.stack) {\n stackChanged = true;\n // remove values from old stack\n clearStacks(meta);\n meta.stack = dataset.stack;\n }\n\n // Re-sync meta data in case the user replaced the data array or if we missed\n // any updates and so make sure that we handle number of datapoints changing.\n this._resyncElements(resetNewElements);\n\n // if stack changed, update stack values for the whole dataset\n if (stackChanged || oldStacked !== meta._stacked) {\n updateStacks(this, meta._parsed);\n meta._stacked = isStacked(meta.vScale, meta);\n }\n }\n\n /**\n\t * Merges user-supplied and default dataset-level options\n\t * @private\n\t */\n configure() {\n const config = this.chart.config;\n const scopeKeys = config.datasetScopeKeys(this._type);\n const scopes = config.getOptionScopes(this.getDataset(), scopeKeys, true);\n this.options = config.createResolver(scopes, this.getContext());\n this._parsing = this.options.parsing;\n this._cachedDataOpts = {};\n }\n\n /**\n\t * @param {number} start\n\t * @param {number} count\n\t */\n parse(start, count) {\n const {_cachedMeta: meta, _data: data} = this;\n const {iScale, _stacked} = meta;\n const iAxis = iScale.axis;\n\n let sorted = start === 0 && count === data.length ? true : meta._sorted;\n let prev = start > 0 && meta._parsed[start - 1];\n let i, cur, parsed;\n\n if (this._parsing === false) {\n meta._parsed = data;\n meta._sorted = true;\n parsed = data;\n } else {\n if (isArray(data[start])) {\n parsed = this.parseArrayData(meta, data, start, count);\n } else if (isObject(data[start])) {\n parsed = this.parseObjectData(meta, data, start, count);\n } else {\n parsed = this.parsePrimitiveData(meta, data, start, count);\n }\n\n const isNotInOrderComparedToPrev = () => cur[iAxis] === null || (prev && cur[iAxis] < prev[iAxis]);\n for (i = 0; i < count; ++i) {\n meta._parsed[i + start] = cur = parsed[i];\n if (sorted) {\n if (isNotInOrderComparedToPrev()) {\n sorted = false;\n }\n prev = cur;\n }\n }\n meta._sorted = sorted;\n }\n\n if (_stacked) {\n updateStacks(this, parsed);\n }\n }\n\n /**\n\t * Parse array of primitive values\n\t * @param {object} meta - dataset meta\n\t * @param {array} data - data array. Example [1,3,4]\n\t * @param {number} start - start index\n\t * @param {number} count - number of items to parse\n\t * @returns {object} parsed item - item containing index and a parsed value\n\t * for each scale id.\n\t * Example: {xScale0: 0, yScale0: 1}\n\t * @protected\n\t */\n parsePrimitiveData(meta, data, start, count) {\n const {iScale, vScale} = meta;\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const labels = iScale.getLabels();\n const singleScale = iScale === vScale;\n const parsed = new Array(count);\n let i, ilen, index;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n parsed[i] = {\n [iAxis]: singleScale || iScale.parse(labels[index], index),\n [vAxis]: vScale.parse(data[index], index)\n };\n }\n return parsed;\n }\n\n /**\n\t * Parse array of arrays\n\t * @param {object} meta - dataset meta\n\t * @param {array} data - data array. Example [[1,2],[3,4]]\n\t * @param {number} start - start index\n\t * @param {number} count - number of items to parse\n\t * @returns {object} parsed item - item containing index and a parsed value\n\t * for each scale id.\n\t * Example: {x: 0, y: 1}\n\t * @protected\n\t */\n parseArrayData(meta, data, start, count) {\n const {xScale, yScale} = meta;\n const parsed = new Array(count);\n let i, ilen, index, item;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n item = data[index];\n parsed[i] = {\n x: xScale.parse(item[0], index),\n y: yScale.parse(item[1], index)\n };\n }\n return parsed;\n }\n\n /**\n\t * Parse array of objects\n\t * @param {object} meta - dataset meta\n\t * @param {array} data - data array. Example [{x:1, y:5}, {x:2, y:10}]\n\t * @param {number} start - start index\n\t * @param {number} count - number of items to parse\n\t * @returns {object} parsed item - item containing index and a parsed value\n\t * for each scale id. _custom is optional\n\t * Example: {xScale0: 0, yScale0: 1, _custom: {r: 10, foo: 'bar'}}\n\t * @protected\n\t */\n parseObjectData(meta, data, start, count) {\n const {xScale, yScale} = meta;\n const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;\n const parsed = new Array(count);\n let i, ilen, index, item;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n item = data[index];\n parsed[i] = {\n x: xScale.parse(resolveObjectKey(item, xAxisKey), index),\n y: yScale.parse(resolveObjectKey(item, yAxisKey), index)\n };\n }\n return parsed;\n }\n\n /**\n\t * @protected\n\t */\n getParsed(index) {\n return this._cachedMeta._parsed[index];\n }\n\n /**\n\t * @protected\n\t */\n getDataElement(index) {\n return this._cachedMeta.data[index];\n }\n\n /**\n\t * @protected\n\t */\n applyStack(scale, parsed, mode) {\n const chart = this.chart;\n const meta = this._cachedMeta;\n const value = parsed[scale.axis];\n const stack = {\n keys: getSortedDatasetIndices(chart, true),\n values: parsed._stacks[scale.axis]._visualValues\n };\n return applyStack(stack, value, meta.index, {mode});\n }\n\n /**\n\t * @protected\n\t */\n updateRangeFromParsed(range, scale, parsed, stack) {\n const parsedValue = parsed[scale.axis];\n let value = parsedValue === null ? NaN : parsedValue;\n const values = stack && parsed._stacks[scale.axis];\n if (stack && values) {\n stack.values = values;\n value = applyStack(stack, parsedValue, this._cachedMeta.index);\n }\n range.min = Math.min(range.min, value);\n range.max = Math.max(range.max, value);\n }\n\n /**\n\t * @protected\n\t */\n getMinMax(scale, canStack) {\n const meta = this._cachedMeta;\n const _parsed = meta._parsed;\n const sorted = meta._sorted && scale === meta.iScale;\n const ilen = _parsed.length;\n const otherScale = this._getOtherScale(scale);\n const stack = createStack(canStack, meta, this.chart);\n const range = {min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY};\n const {min: otherMin, max: otherMax} = getUserBounds(otherScale);\n let i, parsed;\n\n function _skip() {\n parsed = _parsed[i];\n const otherValue = parsed[otherScale.axis];\n return !isFinite(parsed[scale.axis]) || otherMin > otherValue || otherMax < otherValue;\n }\n\n for (i = 0; i < ilen; ++i) {\n if (_skip()) {\n continue;\n }\n this.updateRangeFromParsed(range, scale, parsed, stack);\n if (sorted) {\n // if the data is sorted, we don't need to check further from this end of array\n break;\n }\n }\n if (sorted) {\n // in the sorted case, find first non-skipped value from other end of array\n for (i = ilen - 1; i >= 0; --i) {\n if (_skip()) {\n continue;\n }\n this.updateRangeFromParsed(range, scale, parsed, stack);\n break;\n }\n }\n return range;\n }\n\n getAllParsedValues(scale) {\n const parsed = this._cachedMeta._parsed;\n const values = [];\n let i, ilen, value;\n\n for (i = 0, ilen = parsed.length; i < ilen; ++i) {\n value = parsed[i][scale.axis];\n if (isFinite(value)) {\n values.push(value);\n }\n }\n return values;\n }\n\n /**\n\t * @return {number|boolean}\n\t * @protected\n\t */\n getMaxOverflow() {\n return false;\n }\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const iScale = meta.iScale;\n const vScale = meta.vScale;\n const parsed = this.getParsed(index);\n return {\n label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '',\n value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : ''\n };\n }\n\n /**\n\t * @private\n\t */\n _update(mode) {\n const meta = this._cachedMeta;\n this.update(mode || 'default');\n meta._clip = toClip(valueOrDefault(this.options.clip, defaultClip(meta.xScale, meta.yScale, this.getMaxOverflow())));\n }\n\n /**\n\t * @param {string} mode\n\t */\n update(mode) {} // eslint-disable-line no-unused-vars\n\n draw() {\n const ctx = this._ctx;\n const chart = this.chart;\n const meta = this._cachedMeta;\n const elements = meta.data || [];\n const area = chart.chartArea;\n const active = [];\n const start = this._drawStart || 0;\n const count = this._drawCount || (elements.length - start);\n const drawActiveElementsOnTop = this.options.drawActiveElementsOnTop;\n let i;\n\n if (meta.dataset) {\n meta.dataset.draw(ctx, area, start, count);\n }\n\n for (i = start; i < start + count; ++i) {\n const element = elements[i];\n if (element.hidden) {\n continue;\n }\n if (element.active && drawActiveElementsOnTop) {\n active.push(element);\n } else {\n element.draw(ctx, area);\n }\n }\n\n for (i = 0; i < active.length; ++i) {\n active[i].draw(ctx, area);\n }\n }\n\n /**\n\t * Returns a set of predefined style properties that should be used to represent the dataset\n\t * or the data if the index is specified\n\t * @param {number} index - data index\n\t * @param {boolean} [active] - true if hover\n\t * @return {object} style object\n\t */\n getStyle(index, active) {\n const mode = active ? 'active' : 'default';\n return index === undefined && this._cachedMeta.dataset\n ? this.resolveDatasetElementOptions(mode)\n : this.resolveDataElementOptions(index || 0, mode);\n }\n\n /**\n\t * @protected\n\t */\n getContext(index, active, mode) {\n const dataset = this.getDataset();\n let context;\n if (index >= 0 && index < this._cachedMeta.data.length) {\n const element = this._cachedMeta.data[index];\n context = element.$context ||\n (element.$context = createDataContext(this.getContext(), index, element));\n context.parsed = this.getParsed(index);\n context.raw = dataset.data[index];\n context.index = context.dataIndex = index;\n } else {\n context = this.$context ||\n (this.$context = createDatasetContext(this.chart.getContext(), this.index));\n context.dataset = dataset;\n context.index = context.datasetIndex = this.index;\n }\n\n context.active = !!active;\n context.mode = mode;\n return context;\n }\n\n /**\n\t * @param {string} [mode]\n\t * @protected\n\t */\n resolveDatasetElementOptions(mode) {\n return this._resolveElementOptions(this.datasetElementType.id, mode);\n }\n\n /**\n\t * @param {number} index\n\t * @param {string} [mode]\n\t * @protected\n\t */\n resolveDataElementOptions(index, mode) {\n return this._resolveElementOptions(this.dataElementType.id, mode, index);\n }\n\n /**\n\t * @private\n\t */\n _resolveElementOptions(elementType, mode = 'default', index) {\n const active = mode === 'active';\n const cache = this._cachedDataOpts;\n const cacheKey = elementType + '-' + mode;\n const cached = cache[cacheKey];\n const sharing = this.enableOptionSharing && defined(index);\n if (cached) {\n return cloneIfNotShared(cached, sharing);\n }\n const config = this.chart.config;\n const scopeKeys = config.datasetElementScopeKeys(this._type, elementType);\n const prefixes = active ? [`${elementType}Hover`, 'hover', elementType, ''] : [elementType, ''];\n const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);\n const names = Object.keys(defaults.elements[elementType]);\n // context is provided as a function, and is called only if needed,\n // so we don't create a context for each element if not needed.\n const context = () => this.getContext(index, active, mode);\n const values = config.resolveNamedOptions(scopes, names, context, prefixes);\n\n if (values.$shared) {\n // `$shared` indicates this set of options can be shared between multiple elements.\n // Sharing is used to reduce number of properties to change during animation.\n values.$shared = sharing;\n\n // We cache options by `mode`, which can be 'active' for example. This enables us\n // to have the 'active' element options and 'default' options to switch between\n // when interacting.\n cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing));\n }\n\n return values;\n }\n\n\n /**\n\t * @private\n\t */\n _resolveAnimations(index, transition, active) {\n const chart = this.chart;\n const cache = this._cachedDataOpts;\n const cacheKey = `animation-${transition}`;\n const cached = cache[cacheKey];\n if (cached) {\n return cached;\n }\n let options;\n if (chart.options.animation !== false) {\n const config = this.chart.config;\n const scopeKeys = config.datasetAnimationScopeKeys(this._type, transition);\n const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);\n options = config.createResolver(scopes, this.getContext(index, active, transition));\n }\n const animations = new Animations(chart, options && options.animations);\n if (options && options._cacheable) {\n cache[cacheKey] = Object.freeze(animations);\n }\n return animations;\n }\n\n /**\n\t * Utility for getting the options object shared between elements\n\t * @protected\n\t */\n getSharedOptions(options) {\n if (!options.$shared) {\n return;\n }\n return this._sharedOptions || (this._sharedOptions = Object.assign({}, options));\n }\n\n /**\n\t * Utility for determining if `options` should be included in the updated properties\n\t * @protected\n\t */\n includeOptions(mode, sharedOptions) {\n return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled;\n }\n\n /**\n * @todo v4, rename to getSharedOptions and remove excess functions\n */\n _getSharedOptions(start, mode) {\n const firstOpts = this.resolveDataElementOptions(start, mode);\n const previouslySharedOptions = this._sharedOptions;\n const sharedOptions = this.getSharedOptions(firstOpts);\n const includeOptions = this.includeOptions(mode, sharedOptions) || (sharedOptions !== previouslySharedOptions);\n this.updateSharedOptions(sharedOptions, mode, firstOpts);\n return {sharedOptions, includeOptions};\n }\n\n /**\n\t * Utility for updating an element with new properties, using animations when appropriate.\n\t * @protected\n\t */\n updateElement(element, index, properties, mode) {\n if (isDirectUpdateMode(mode)) {\n Object.assign(element, properties);\n } else {\n this._resolveAnimations(index, mode).update(element, properties);\n }\n }\n\n /**\n\t * Utility to animate the shared options, that are potentially affecting multiple elements.\n\t * @protected\n\t */\n updateSharedOptions(sharedOptions, mode, newOptions) {\n if (sharedOptions && !isDirectUpdateMode(mode)) {\n this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions);\n }\n }\n\n /**\n\t * @private\n\t */\n _setStyle(element, index, mode, active) {\n element.active = active;\n const options = this.getStyle(index, active);\n this._resolveAnimations(index, mode, active).update(element, {\n // When going from active to inactive, we need to update to the shared options.\n // This way the once hovered element will end up with the same original shared options instance, after animation.\n options: (!active && this.getSharedOptions(options)) || options\n });\n }\n\n removeHoverStyle(element, datasetIndex, index) {\n this._setStyle(element, index, 'active', false);\n }\n\n setHoverStyle(element, datasetIndex, index) {\n this._setStyle(element, index, 'active', true);\n }\n\n /**\n\t * @private\n\t */\n _removeDatasetHoverStyle() {\n const element = this._cachedMeta.dataset;\n\n if (element) {\n this._setStyle(element, undefined, 'active', false);\n }\n }\n\n /**\n\t * @private\n\t */\n _setDatasetHoverStyle() {\n const element = this._cachedMeta.dataset;\n\n if (element) {\n this._setStyle(element, undefined, 'active', true);\n }\n }\n\n /**\n\t * @private\n\t */\n _resyncElements(resetNewElements) {\n const data = this._data;\n const elements = this._cachedMeta.data;\n\n // Apply changes detected through array listeners\n for (const [method, arg1, arg2] of this._syncList) {\n this[method](arg1, arg2);\n }\n this._syncList = [];\n\n const numMeta = elements.length;\n const numData = data.length;\n const count = Math.min(numData, numMeta);\n\n if (count) {\n // TODO: It is not optimal to always parse the old data\n // This is done because we are not detecting direct assignments:\n // chart.data.datasets[0].data[5] = 10;\n // chart.data.datasets[0].data[5].y = 10;\n this.parse(0, count);\n }\n\n if (numData > numMeta) {\n this._insertElements(numMeta, numData - numMeta, resetNewElements);\n } else if (numData < numMeta) {\n this._removeElements(numData, numMeta - numData);\n }\n }\n\n /**\n\t * @private\n\t */\n _insertElements(start, count, resetNewElements = true) {\n const meta = this._cachedMeta;\n const data = meta.data;\n const end = start + count;\n let i;\n\n const move = (arr) => {\n arr.length += count;\n for (i = arr.length - 1; i >= end; i--) {\n arr[i] = arr[i - count];\n }\n };\n move(data);\n\n for (i = start; i < end; ++i) {\n data[i] = new this.dataElementType();\n }\n\n if (this._parsing) {\n move(meta._parsed);\n }\n this.parse(start, count);\n\n if (resetNewElements) {\n this.updateElements(data, start, count, 'reset');\n }\n }\n\n updateElements(element, start, count, mode) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * @private\n\t */\n _removeElements(start, count) {\n const meta = this._cachedMeta;\n if (this._parsing) {\n const removed = meta._parsed.splice(start, count);\n if (meta._stacked) {\n clearStacks(meta, removed);\n }\n }\n meta.data.splice(start, count);\n }\n\n /**\n\t * @private\n */\n _sync(args) {\n if (this._parsing) {\n this._syncList.push(args);\n } else {\n const [method, arg1, arg2] = args;\n this[method](arg1, arg2);\n }\n this.chart._dataChanges.push([this.index, ...args]);\n }\n\n _onDataPush() {\n const count = arguments.length;\n this._sync(['_insertElements', this.getDataset().data.length - count, count]);\n }\n\n _onDataPop() {\n this._sync(['_removeElements', this._cachedMeta.data.length - 1, 1]);\n }\n\n _onDataShift() {\n this._sync(['_removeElements', 0, 1]);\n }\n\n _onDataSplice(start, count) {\n if (count) {\n this._sync(['_removeElements', start, count]);\n }\n const newCount = arguments.length - 2;\n if (newCount) {\n this._sync(['_insertElements', start, newCount]);\n }\n }\n\n _onDataUnshift() {\n this._sync(['_insertElements', 0, arguments.length]);\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {\n _arrayUnique, isArray, isNullOrUndef,\n valueOrDefault, resolveObjectKey, sign, defined\n} from '../helpers/index.js';\n\nfunction getAllScaleValues(scale, type) {\n if (!scale._cache.$bar) {\n const visibleMetas = scale.getMatchingVisibleMetas(type);\n let values = [];\n\n for (let i = 0, ilen = visibleMetas.length; i < ilen; i++) {\n values = values.concat(visibleMetas[i].controller.getAllParsedValues(scale));\n }\n scale._cache.$bar = _arrayUnique(values.sort((a, b) => a - b));\n }\n return scale._cache.$bar;\n}\n\n/**\n * Computes the \"optimal\" sample size to maintain bars equally sized while preventing overlap.\n * @private\n */\nfunction computeMinSampleSize(meta) {\n const scale = meta.iScale;\n const values = getAllScaleValues(scale, meta.type);\n let min = scale._length;\n let i, ilen, curr, prev;\n const updateMinAndPrev = () => {\n if (curr === 32767 || curr === -32768) {\n // Ignore truncated pixels\n return;\n }\n if (defined(prev)) {\n // curr - prev === 0 is ignored\n min = Math.min(min, Math.abs(curr - prev) || min);\n }\n prev = curr;\n };\n\n for (i = 0, ilen = values.length; i < ilen; ++i) {\n curr = scale.getPixelForValue(values[i]);\n updateMinAndPrev();\n }\n\n prev = undefined;\n for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) {\n curr = scale.getPixelForTick(i);\n updateMinAndPrev();\n }\n\n return min;\n}\n\n/**\n * Computes an \"ideal\" category based on the absolute bar thickness or, if undefined or null,\n * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This\n * mode currently always generates bars equally sized (until we introduce scriptable options?).\n * @private\n */\nfunction computeFitCategoryTraits(index, ruler, options, stackCount) {\n const thickness = options.barThickness;\n let size, ratio;\n\n if (isNullOrUndef(thickness)) {\n size = ruler.min * options.categoryPercentage;\n ratio = options.barPercentage;\n } else {\n // When bar thickness is enforced, category and bar percentages are ignored.\n // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')\n // and deprecate barPercentage since this value is ignored when thickness is absolute.\n size = thickness * stackCount;\n ratio = 1;\n }\n\n return {\n chunk: size / stackCount,\n ratio,\n start: ruler.pixels[index] - (size / 2)\n };\n}\n\n/**\n * Computes an \"optimal\" category that globally arranges bars side by side (no gap when\n * percentage options are 1), based on the previous and following categories. This mode\n * generates bars with different widths when data are not evenly spaced.\n * @private\n */\nfunction computeFlexCategoryTraits(index, ruler, options, stackCount) {\n const pixels = ruler.pixels;\n const curr = pixels[index];\n let prev = index > 0 ? pixels[index - 1] : null;\n let next = index < pixels.length - 1 ? pixels[index + 1] : null;\n const percent = options.categoryPercentage;\n\n if (prev === null) {\n // first data: its size is double based on the next point or,\n // if it's also the last data, we use the scale size.\n prev = curr - (next === null ? ruler.end - ruler.start : next - curr);\n }\n\n if (next === null) {\n // last data: its size is also double based on the previous point.\n next = curr + curr - prev;\n }\n\n const start = curr - (curr - Math.min(prev, next)) / 2 * percent;\n const size = Math.abs(next - prev) / 2 * percent;\n\n return {\n chunk: size / stackCount,\n ratio: options.barPercentage,\n start\n };\n}\n\nfunction parseFloatBar(entry, item, vScale, i) {\n const startValue = vScale.parse(entry[0], i);\n const endValue = vScale.parse(entry[1], i);\n const min = Math.min(startValue, endValue);\n const max = Math.max(startValue, endValue);\n let barStart = min;\n let barEnd = max;\n\n if (Math.abs(min) > Math.abs(max)) {\n barStart = max;\n barEnd = min;\n }\n\n // Store `barEnd` (furthest away from origin) as parsed value,\n // to make stacking straight forward\n item[vScale.axis] = barEnd;\n\n item._custom = {\n barStart,\n barEnd,\n start: startValue,\n end: endValue,\n min,\n max\n };\n}\n\nfunction parseValue(entry, item, vScale, i) {\n if (isArray(entry)) {\n parseFloatBar(entry, item, vScale, i);\n } else {\n item[vScale.axis] = vScale.parse(entry, i);\n }\n return item;\n}\n\nfunction parseArrayOrPrimitive(meta, data, start, count) {\n const iScale = meta.iScale;\n const vScale = meta.vScale;\n const labels = iScale.getLabels();\n const singleScale = iScale === vScale;\n const parsed = [];\n let i, ilen, item, entry;\n\n for (i = start, ilen = start + count; i < ilen; ++i) {\n entry = data[i];\n item = {};\n item[iScale.axis] = singleScale || iScale.parse(labels[i], i);\n parsed.push(parseValue(entry, item, vScale, i));\n }\n return parsed;\n}\n\nfunction isFloatBar(custom) {\n return custom && custom.barStart !== undefined && custom.barEnd !== undefined;\n}\n\nfunction barSign(size, vScale, actualBase) {\n if (size !== 0) {\n return sign(size);\n }\n return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1);\n}\n\nfunction borderProps(properties) {\n let reverse, start, end, top, bottom;\n if (properties.horizontal) {\n reverse = properties.base > properties.x;\n start = 'left';\n end = 'right';\n } else {\n reverse = properties.base < properties.y;\n start = 'bottom';\n end = 'top';\n }\n if (reverse) {\n top = 'end';\n bottom = 'start';\n } else {\n top = 'start';\n bottom = 'end';\n }\n return {start, end, reverse, top, bottom};\n}\n\nfunction setBorderSkipped(properties, options, stack, index) {\n let edge = options.borderSkipped;\n const res = {};\n\n if (!edge) {\n properties.borderSkipped = res;\n return;\n }\n\n if (edge === true) {\n properties.borderSkipped = {top: true, right: true, bottom: true, left: true};\n return;\n }\n\n const {start, end, reverse, top, bottom} = borderProps(properties);\n\n if (edge === 'middle' && stack) {\n properties.enableBorderRadius = true;\n if ((stack._top || 0) === index) {\n edge = top;\n } else if ((stack._bottom || 0) === index) {\n edge = bottom;\n } else {\n res[parseEdge(bottom, start, end, reverse)] = true;\n edge = top;\n }\n }\n\n res[parseEdge(edge, start, end, reverse)] = true;\n properties.borderSkipped = res;\n}\n\nfunction parseEdge(edge, a, b, reverse) {\n if (reverse) {\n edge = swap(edge, a, b);\n edge = startEnd(edge, b, a);\n } else {\n edge = startEnd(edge, a, b);\n }\n return edge;\n}\n\nfunction swap(orig, v1, v2) {\n return orig === v1 ? v2 : orig === v2 ? v1 : orig;\n}\n\nfunction startEnd(v, start, end) {\n return v === 'start' ? start : v === 'end' ? end : v;\n}\n\nfunction setInflateAmount(properties, {inflateAmount}, ratio) {\n properties.inflateAmount = inflateAmount === 'auto'\n ? ratio === 1 ? 0.33 : 0\n : inflateAmount;\n}\n\nexport default class BarController extends DatasetController {\n\n static id = 'bar';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'bar',\n\n categoryPercentage: 0.8,\n barPercentage: 0.9,\n grouped: true,\n\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'base', 'width', 'height']\n }\n }\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n scales: {\n _index_: {\n type: 'category',\n offset: true,\n grid: {\n offset: true\n }\n },\n _value_: {\n type: 'linear',\n beginAtZero: true,\n }\n }\n };\n\n\n /**\n\t * Overriding primitive data parsing since we support mixed primitive/array\n\t * data for float bars\n\t * @protected\n\t */\n parsePrimitiveData(meta, data, start, count) {\n return parseArrayOrPrimitive(meta, data, start, count);\n }\n\n /**\n\t * Overriding array data parsing since we support mixed primitive/array\n\t * data for float bars\n\t * @protected\n\t */\n parseArrayData(meta, data, start, count) {\n return parseArrayOrPrimitive(meta, data, start, count);\n }\n\n /**\n\t * Overriding object data parsing since we support mixed primitive/array\n\t * value-scale data for float bars\n\t * @protected\n\t */\n parseObjectData(meta, data, start, count) {\n const {iScale, vScale} = meta;\n const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;\n const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey;\n const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey;\n const parsed = [];\n let i, ilen, item, obj;\n for (i = start, ilen = start + count; i < ilen; ++i) {\n obj = data[i];\n item = {};\n item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i);\n parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i));\n }\n return parsed;\n }\n\n /**\n\t * @protected\n\t */\n updateRangeFromParsed(range, scale, parsed, stack) {\n super.updateRangeFromParsed(range, scale, parsed, stack);\n const custom = parsed._custom;\n if (custom && scale === this._cachedMeta.vScale) {\n // float bar: only one end of the bar is considered by `super`\n range.min = Math.min(range.min, custom.min);\n range.max = Math.max(range.max, custom.max);\n }\n }\n\n /**\n\t * @return {number|boolean}\n\t * @protected\n\t */\n getMaxOverflow() {\n return 0;\n }\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const {iScale, vScale} = meta;\n const parsed = this.getParsed(index);\n const custom = parsed._custom;\n const value = isFloatBar(custom)\n ? '[' + custom.start + ', ' + custom.end + ']'\n : '' + vScale.getLabelForValue(parsed[vScale.axis]);\n\n return {\n label: '' + iScale.getLabelForValue(parsed[iScale.axis]),\n value\n };\n }\n\n initialize() {\n this.enableOptionSharing = true;\n\n super.initialize();\n\n const meta = this._cachedMeta;\n meta.stack = this.getDataset().stack;\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n this.updateElements(meta.data, 0, meta.data.length, mode);\n }\n\n updateElements(bars, start, count, mode) {\n const reset = mode === 'reset';\n const {index, _cachedMeta: {vScale}} = this;\n const base = vScale.getBasePixel();\n const horizontal = vScale.isHorizontal();\n const ruler = this._getRuler();\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n\n for (let i = start; i < start + count; i++) {\n const parsed = this.getParsed(i);\n const vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? {base, head: base} : this._calculateBarValuePixels(i);\n const ipixels = this._calculateBarIndexPixels(i, ruler);\n const stack = (parsed._stacks || {})[vScale.axis];\n\n const properties = {\n horizontal,\n base: vpixels.base,\n enableBorderRadius: !stack || isFloatBar(parsed._custom) || (index === stack._top || index === stack._bottom),\n x: horizontal ? vpixels.head : ipixels.center,\n y: horizontal ? ipixels.center : vpixels.head,\n height: horizontal ? ipixels.size : Math.abs(vpixels.size),\n width: horizontal ? Math.abs(vpixels.size) : ipixels.size\n };\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, bars[i].active ? 'active' : mode);\n }\n const options = properties.options || bars[i].options;\n setBorderSkipped(properties, options, stack, index);\n setInflateAmount(properties, options, ruler.ratio);\n this.updateElement(bars[i], i, properties, mode);\n }\n }\n\n /**\n\t * Returns the stacks based on groups and bar visibility.\n\t * @param {number} [last] - The dataset index\n\t * @param {number} [dataIndex] - The data index of the ruler\n\t * @returns {string[]} The list of stack IDs\n\t * @private\n\t */\n _getStacks(last, dataIndex) {\n const {iScale} = this._cachedMeta;\n const metasets = iScale.getMatchingVisibleMetas(this._type)\n .filter(meta => meta.controller.options.grouped);\n const stacked = iScale.options.stacked;\n const stacks = [];\n const currentParsed = this._cachedMeta.controller.getParsed(dataIndex);\n const iScaleValue = currentParsed && currentParsed[iScale.axis];\n\n const skipNull = (meta) => {\n const parsed = meta._parsed.find(item => item[iScale.axis] === iScaleValue);\n const val = parsed && parsed[meta.vScale.axis];\n\n if (isNullOrUndef(val) || isNaN(val)) {\n return true;\n }\n };\n\n for (const meta of metasets) {\n if (dataIndex !== undefined && skipNull(meta)) {\n continue;\n }\n\n // stacked | meta.stack\n // | found | not found | undefined\n // false | x | x | x\n // true | | x |\n // undefined | | x | x\n if (stacked === false || stacks.indexOf(meta.stack) === -1 ||\n\t\t\t\t(stacked === undefined && meta.stack === undefined)) {\n stacks.push(meta.stack);\n }\n if (meta.index === last) {\n break;\n }\n }\n\n // No stacks? that means there is no visible data. Let's still initialize an `undefined`\n // stack where possible invisible bars will be located.\n // https://github.com/chartjs/Chart.js/issues/6368\n if (!stacks.length) {\n stacks.push(undefined);\n }\n\n return stacks;\n }\n\n /**\n\t * Returns the effective number of stacks based on groups and bar visibility.\n\t * @private\n\t */\n _getStackCount(index) {\n return this._getStacks(undefined, index).length;\n }\n\n _getAxisCount() {\n return this._getAxis().length;\n }\n\n getFirstScaleIdForIndexAxis() {\n const scales = this.chart.scales;\n const indexScaleId = this.chart.options.indexAxis;\n return Object.keys(scales).filter(key => scales[key].axis === indexScaleId).shift();\n }\n\n _getAxis() {\n const axis = {};\n const firstScaleAxisId = this.getFirstScaleIdForIndexAxis();\n for (const dataset of this.chart.data.datasets) {\n axis[valueOrDefault(\n this.chart.options.indexAxis === 'x' ? dataset.xAxisID : dataset.yAxisID, firstScaleAxisId\n )] = true;\n }\n return Object.keys(axis);\n }\n\n /**\n\t * Returns the stack index for the given dataset based on groups and bar visibility.\n\t * @param {number} [datasetIndex] - The dataset index\n\t * @param {string} [name] - The stack name to find\n * @param {number} [dataIndex]\n\t * @returns {number} The stack index\n\t * @private\n\t */\n _getStackIndex(datasetIndex, name, dataIndex) {\n const stacks = this._getStacks(datasetIndex, dataIndex);\n const index = (name !== undefined)\n ? stacks.indexOf(name)\n : -1; // indexOf returns -1 if element is not present\n\n return (index === -1)\n ? stacks.length - 1\n : index;\n }\n\n /**\n\t * @private\n\t */\n _getRuler() {\n const opts = this.options;\n const meta = this._cachedMeta;\n const iScale = meta.iScale;\n const pixels = [];\n let i, ilen;\n\n for (i = 0, ilen = meta.data.length; i < ilen; ++i) {\n pixels.push(iScale.getPixelForValue(this.getParsed(i)[iScale.axis], i));\n }\n\n const barThickness = opts.barThickness;\n const min = barThickness || computeMinSampleSize(meta);\n\n return {\n min,\n pixels,\n start: iScale._startPixel,\n end: iScale._endPixel,\n stackCount: this._getStackCount(),\n scale: iScale,\n grouped: opts.grouped,\n // bar thickness ratio used for non-grouped bars\n ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage\n };\n }\n\n /**\n\t * Note: pixel values are not clamped to the scale area.\n\t * @private\n\t */\n _calculateBarValuePixels(index) {\n const {_cachedMeta: {vScale, _stacked, index: datasetIndex}, options: {base: baseValue, minBarLength}} = this;\n const actualBase = baseValue || 0;\n const parsed = this.getParsed(index);\n const custom = parsed._custom;\n const floating = isFloatBar(custom);\n let value = parsed[vScale.axis];\n let start = 0;\n let length = _stacked ? this.applyStack(vScale, parsed, _stacked) : value;\n let head, size;\n\n if (length !== value) {\n start = length - value;\n length = value;\n }\n\n if (floating) {\n value = custom.barStart;\n length = custom.barEnd - custom.barStart;\n // bars crossing origin are not stacked\n if (value !== 0 && sign(value) !== sign(custom.barEnd)) {\n start = 0;\n }\n start += value;\n }\n\n const startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start;\n let base = vScale.getPixelForValue(startValue);\n\n if (this.chart.getDataVisibility(index)) {\n head = vScale.getPixelForValue(start + length);\n } else {\n // When not visible, no height\n head = base;\n }\n\n size = head - base;\n\n if (Math.abs(size) < minBarLength) {\n size = barSign(size, vScale, actualBase) * minBarLength;\n if (value === actualBase) {\n base -= size / 2;\n }\n const startPixel = vScale.getPixelForDecimal(0);\n const endPixel = vScale.getPixelForDecimal(1);\n const min = Math.min(startPixel, endPixel);\n const max = Math.max(startPixel, endPixel);\n base = Math.max(Math.min(base, max), min);\n head = base + size;\n\n if (_stacked && !floating) {\n // visual data coordinates after applying minBarLength\n parsed._stacks[vScale.axis]._visualValues[datasetIndex] = vScale.getValueForPixel(head) - vScale.getValueForPixel(base);\n }\n }\n\n if (base === vScale.getPixelForValue(actualBase)) {\n const halfGrid = sign(size) * vScale.getLineWidthForValue(actualBase) / 2;\n base += halfGrid;\n size -= halfGrid;\n }\n\n return {\n size,\n base,\n head,\n center: head + size / 2\n };\n }\n\n /**\n\t * @private\n\t */\n _calculateBarIndexPixels(index, ruler) {\n const scale = ruler.scale;\n const options = this.options;\n const skipNull = options.skipNull;\n const maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity);\n let center, size;\n const axisCount = this._getAxisCount();\n if (ruler.grouped) {\n const stackCount = skipNull ? this._getStackCount(index) : ruler.stackCount;\n const range = options.barThickness === 'flex'\n ? computeFlexCategoryTraits(index, ruler, options, stackCount * axisCount)\n : computeFitCategoryTraits(index, ruler, options, stackCount * axisCount);\n const axisID = this.chart.options.indexAxis === 'x' ? this.getDataset().xAxisID : this.getDataset().yAxisID;\n const axisNumber = this._getAxis().indexOf(valueOrDefault(axisID, this.getFirstScaleIdForIndexAxis()));\n const stackIndex = this._getStackIndex(this.index, this._cachedMeta.stack, skipNull ? index : undefined) + axisNumber;\n center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);\n size = Math.min(maxBarThickness, range.chunk * range.ratio);\n } else {\n // For non-grouped bar charts, exact pixel values are used\n center = scale.getPixelForValue(this.getParsed(index)[scale.axis], index);\n size = Math.min(maxBarThickness, ruler.min * ruler.ratio);\n }\n\n\n return {\n base: center - size / 2,\n head: center + size / 2,\n center,\n size\n };\n }\n\n draw() {\n const meta = this._cachedMeta;\n const vScale = meta.vScale;\n const rects = meta.data;\n const ilen = rects.length;\n let i = 0;\n\n for (; i < ilen; ++i) {\n if (this.getParsed(i)[vScale.axis] !== null && !rects[i].hidden) {\n rects[i].draw(this._ctx);\n }\n }\n }\n\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {valueOrDefault} from '../helpers/helpers.core.js';\n\nexport default class BubbleController extends DatasetController {\n\n static id = 'bubble';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'point',\n\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'borderWidth', 'radius']\n }\n }\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n scales: {\n x: {\n type: 'linear'\n },\n y: {\n type: 'linear'\n }\n }\n };\n\n initialize() {\n this.enableOptionSharing = true;\n super.initialize();\n }\n\n /**\n\t * Parse array of primitive values\n\t * @protected\n\t */\n parsePrimitiveData(meta, data, start, count) {\n const parsed = super.parsePrimitiveData(meta, data, start, count);\n for (let i = 0; i < parsed.length; i++) {\n parsed[i]._custom = this.resolveDataElementOptions(i + start).radius;\n }\n return parsed;\n }\n\n /**\n\t * Parse array of arrays\n\t * @protected\n\t */\n parseArrayData(meta, data, start, count) {\n const parsed = super.parseArrayData(meta, data, start, count);\n for (let i = 0; i < parsed.length; i++) {\n const item = data[start + i];\n parsed[i]._custom = valueOrDefault(item[2], this.resolveDataElementOptions(i + start).radius);\n }\n return parsed;\n }\n\n /**\n\t * Parse array of objects\n\t * @protected\n\t */\n parseObjectData(meta, data, start, count) {\n const parsed = super.parseObjectData(meta, data, start, count);\n for (let i = 0; i < parsed.length; i++) {\n const item = data[start + i];\n parsed[i]._custom = valueOrDefault(item && item.r && +item.r, this.resolveDataElementOptions(i + start).radius);\n }\n return parsed;\n }\n\n /**\n\t * @protected\n\t */\n getMaxOverflow() {\n const data = this._cachedMeta.data;\n\n let max = 0;\n for (let i = data.length - 1; i >= 0; --i) {\n max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);\n }\n return max > 0 && max;\n }\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const labels = this.chart.data.labels || [];\n const {xScale, yScale} = meta;\n const parsed = this.getParsed(index);\n const x = xScale.getLabelForValue(parsed.x);\n const y = yScale.getLabelForValue(parsed.y);\n const r = parsed._custom;\n\n return {\n label: labels[index] || '',\n value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')'\n };\n }\n\n update(mode) {\n const points = this._cachedMeta.data;\n\n // Update Points\n this.updateElements(points, 0, points.length, mode);\n }\n\n updateElements(points, start, count, mode) {\n const reset = mode === 'reset';\n const {iScale, vScale} = this._cachedMeta;\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n\n for (let i = start; i < start + count; i++) {\n const point = points[i];\n const parsed = !reset && this.getParsed(i);\n const properties = {};\n const iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]);\n const vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]);\n\n properties.skip = isNaN(iPixel) || isNaN(vPixel);\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n\n if (reset) {\n properties.options.radius = 0;\n }\n }\n\n this.updateElement(point, i, properties, mode);\n }\n }\n\n /**\n\t * @param {number} index\n\t * @param {string} [mode]\n\t * @protected\n\t */\n resolveDataElementOptions(index, mode) {\n const parsed = this.getParsed(index);\n let values = super.resolveDataElementOptions(index, mode);\n\n // In case values were cached (and thus frozen), we need to clone the values\n if (values.$shared) {\n values = Object.assign({}, values, {$shared: false});\n }\n\n // Custom radius resolution\n const radius = values.radius;\n if (mode !== 'active') {\n values.radius = 0;\n }\n values.radius += valueOrDefault(parsed && parsed._custom, radius);\n\n return values;\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {isObject, resolveObjectKey, toPercentage, toDimension, valueOrDefault} from '../helpers/helpers.core.js';\nimport {formatNumber} from '../helpers/helpers.intl.js';\nimport {toRadians, PI, TAU, HALF_PI, _angleBetween} from '../helpers/helpers.math.js';\n\n/**\n * @typedef { import('../core/core.controller.js').default } Chart\n */\n\nfunction getRatioAndOffset(rotation, circumference, cutout) {\n let ratioX = 1;\n let ratioY = 1;\n let offsetX = 0;\n let offsetY = 0;\n // If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc\n if (circumference < TAU) {\n const startAngle = rotation;\n const endAngle = startAngle + circumference;\n const startX = Math.cos(startAngle);\n const startY = Math.sin(startAngle);\n const endX = Math.cos(endAngle);\n const endY = Math.sin(endAngle);\n const calcMax = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout);\n const calcMin = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout);\n const maxX = calcMax(0, startX, endX);\n const maxY = calcMax(HALF_PI, startY, endY);\n const minX = calcMin(PI, startX, endX);\n const minY = calcMin(PI + HALF_PI, startY, endY);\n ratioX = (maxX - minX) / 2;\n ratioY = (maxY - minY) / 2;\n offsetX = -(maxX + minX) / 2;\n offsetY = -(maxY + minY) / 2;\n }\n return {ratioX, ratioY, offsetX, offsetY};\n}\n\nexport default class DoughnutController extends DatasetController {\n\n static id = 'doughnut';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'arc',\n animation: {\n // Boolean - Whether we animate the rotation of the Doughnut\n animateRotate: true,\n // Boolean - Whether we animate scaling the Doughnut from the centre\n animateScale: false\n },\n animations: {\n numbers: {\n type: 'number',\n properties: ['circumference', 'endAngle', 'innerRadius', 'outerRadius', 'startAngle', 'x', 'y', 'offset', 'borderWidth', 'spacing']\n },\n },\n // The percentage of the chart that we cut out of the middle.\n cutout: '50%',\n\n // The rotation of the chart, where the first data arc begins.\n rotation: 0,\n\n // The total circumference of the chart.\n circumference: 360,\n\n // The outer radius of the chart\n radius: '100%',\n\n // Spacing between arcs\n spacing: 0,\n\n indexAxis: 'r',\n };\n\n static descriptors = {\n _scriptable: (name) => name !== 'spacing',\n _indexable: (name) => name !== 'spacing' && !name.startsWith('borderDash') && !name.startsWith('hoverBorderDash'),\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n aspectRatio: 1,\n\n // Need to override these to give a nice default\n plugins: {\n legend: {\n labels: {\n generateLabels(chart) {\n const data = chart.data;\n if (data.labels.length && data.datasets.length) {\n const {labels: {pointStyle, color}} = chart.legend.options;\n\n return data.labels.map((label, i) => {\n const meta = chart.getDatasetMeta(0);\n const style = meta.controller.getStyle(i);\n\n return {\n text: label,\n fillStyle: style.backgroundColor,\n strokeStyle: style.borderColor,\n fontColor: color,\n lineWidth: style.borderWidth,\n pointStyle: pointStyle,\n hidden: !chart.getDataVisibility(i),\n\n // Extra data used for toggling the correct item\n index: i\n };\n });\n }\n return [];\n }\n },\n\n onClick(e, legendItem, legend) {\n legend.chart.toggleDataVisibility(legendItem.index);\n legend.chart.update();\n }\n }\n }\n };\n\n constructor(chart, datasetIndex) {\n super(chart, datasetIndex);\n\n this.enableOptionSharing = true;\n this.innerRadius = undefined;\n this.outerRadius = undefined;\n this.offsetX = undefined;\n this.offsetY = undefined;\n }\n\n linkScales() {}\n\n /**\n\t * Override data parsing, since we are not using scales\n\t */\n parse(start, count) {\n const data = this.getDataset().data;\n const meta = this._cachedMeta;\n\n if (this._parsing === false) {\n meta._parsed = data;\n } else {\n let getter = (i) => +data[i];\n\n if (isObject(data[start])) {\n const {key = 'value'} = this._parsing;\n getter = (i) => +resolveObjectKey(data[i], key);\n }\n\n let i, ilen;\n for (i = start, ilen = start + count; i < ilen; ++i) {\n meta._parsed[i] = getter(i);\n }\n }\n }\n\n /**\n\t * @private\n\t */\n _getRotation() {\n return toRadians(this.options.rotation - 90);\n }\n\n /**\n\t * @private\n\t */\n _getCircumference() {\n return toRadians(this.options.circumference);\n }\n\n /**\n\t * Get the maximal rotation & circumference extents\n\t * across all visible datasets.\n\t */\n _getRotationExtents() {\n let min = TAU;\n let max = -TAU;\n\n for (let i = 0; i < this.chart.data.datasets.length; ++i) {\n if (this.chart.isDatasetVisible(i) && this.chart.getDatasetMeta(i).type === this._type) {\n const controller = this.chart.getDatasetMeta(i).controller;\n const rotation = controller._getRotation();\n const circumference = controller._getCircumference();\n\n min = Math.min(min, rotation);\n max = Math.max(max, rotation + circumference);\n }\n }\n\n return {\n rotation: min,\n circumference: max - min,\n };\n }\n\n /**\n\t * @param {string} mode\n\t */\n update(mode) {\n const chart = this.chart;\n const {chartArea} = chart;\n const meta = this._cachedMeta;\n const arcs = meta.data;\n const spacing = this.getMaxBorderWidth() + this.getMaxOffset(arcs) + this.options.spacing;\n const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0);\n const cutout = Math.min(toPercentage(this.options.cutout, maxSize), 1);\n const chartWeight = this._getRingWeight(this.index);\n\n // Compute the maximal rotation & circumference limits.\n // If we only consider our dataset, this can cause problems when two datasets\n // are both less than a circle with different rotations (starting angles)\n const {circumference, rotation} = this._getRotationExtents();\n const {ratioX, ratioY, offsetX, offsetY} = getRatioAndOffset(rotation, circumference, cutout);\n const maxWidth = (chartArea.width - spacing) / ratioX;\n const maxHeight = (chartArea.height - spacing) / ratioY;\n const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);\n const outerRadius = toDimension(this.options.radius, maxRadius);\n const innerRadius = Math.max(outerRadius * cutout, 0);\n const radiusLength = (outerRadius - innerRadius) / this._getVisibleDatasetWeightTotal();\n this.offsetX = offsetX * outerRadius;\n this.offsetY = offsetY * outerRadius;\n\n meta.total = this.calculateTotal();\n\n this.outerRadius = outerRadius - radiusLength * this._getRingWeightOffset(this.index);\n this.innerRadius = Math.max(this.outerRadius - radiusLength * chartWeight, 0);\n\n this.updateElements(arcs, 0, arcs.length, mode);\n }\n\n /**\n * @private\n */\n _circumference(i, reset) {\n const opts = this.options;\n const meta = this._cachedMeta;\n const circumference = this._getCircumference();\n if ((reset && opts.animation.animateRotate) || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) {\n return 0;\n }\n return this.calculateCircumference(meta._parsed[i] * circumference / TAU);\n }\n\n updateElements(arcs, start, count, mode) {\n const reset = mode === 'reset';\n const chart = this.chart;\n const chartArea = chart.chartArea;\n const opts = chart.options;\n const animationOpts = opts.animation;\n const centerX = (chartArea.left + chartArea.right) / 2;\n const centerY = (chartArea.top + chartArea.bottom) / 2;\n const animateScale = reset && animationOpts.animateScale;\n const innerRadius = animateScale ? 0 : this.innerRadius;\n const outerRadius = animateScale ? 0 : this.outerRadius;\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n let startAngle = this._getRotation();\n let i;\n\n for (i = 0; i < start; ++i) {\n startAngle += this._circumference(i, reset);\n }\n\n for (i = start; i < start + count; ++i) {\n const circumference = this._circumference(i, reset);\n const arc = arcs[i];\n const properties = {\n x: centerX + this.offsetX,\n y: centerY + this.offsetY,\n startAngle,\n endAngle: startAngle + circumference,\n circumference,\n outerRadius,\n innerRadius\n };\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, arc.active ? 'active' : mode);\n }\n startAngle += circumference;\n\n this.updateElement(arc, i, properties, mode);\n }\n }\n\n calculateTotal() {\n const meta = this._cachedMeta;\n const metaData = meta.data;\n let total = 0;\n let i;\n\n for (i = 0; i < metaData.length; i++) {\n const value = meta._parsed[i];\n if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) {\n total += Math.abs(value);\n }\n }\n\n return total;\n }\n\n calculateCircumference(value) {\n const total = this._cachedMeta.total;\n if (total > 0 && !isNaN(value)) {\n return TAU * (Math.abs(value) / total);\n }\n return 0;\n }\n\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const chart = this.chart;\n const labels = chart.data.labels || [];\n const value = formatNumber(meta._parsed[index], chart.options.locale);\n\n return {\n label: labels[index] || '',\n value,\n };\n }\n\n getMaxBorderWidth(arcs) {\n let max = 0;\n const chart = this.chart;\n let i, ilen, meta, controller, options;\n\n if (!arcs) {\n // Find the outmost visible dataset\n for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {\n if (chart.isDatasetVisible(i)) {\n meta = chart.getDatasetMeta(i);\n arcs = meta.data;\n controller = meta.controller;\n break;\n }\n }\n }\n\n if (!arcs) {\n return 0;\n }\n\n for (i = 0, ilen = arcs.length; i < ilen; ++i) {\n options = controller.resolveDataElementOptions(i);\n if (options.borderAlign !== 'inner') {\n max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0);\n }\n }\n return max;\n }\n\n getMaxOffset(arcs) {\n let max = 0;\n\n for (let i = 0, ilen = arcs.length; i < ilen; ++i) {\n const options = this.resolveDataElementOptions(i);\n max = Math.max(max, options.offset || 0, options.hoverOffset || 0);\n }\n return max;\n }\n\n /**\n\t * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly\n\t * @private\n\t */\n _getRingWeightOffset(datasetIndex) {\n let ringWeightOffset = 0;\n\n for (let i = 0; i < datasetIndex; ++i) {\n if (this.chart.isDatasetVisible(i)) {\n ringWeightOffset += this._getRingWeight(i);\n }\n }\n\n return ringWeightOffset;\n }\n\n /**\n\t * @private\n\t */\n _getRingWeight(datasetIndex) {\n return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0);\n }\n\n /**\n\t * Returns the sum of all visible data set weights.\n\t * @private\n\t */\n _getVisibleDatasetWeightTotal() {\n return this._getRingWeightOffset(this.chart.data.datasets.length) || 1;\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {isNullOrUndef} from '../helpers/index.js';\nimport {isNumber} from '../helpers/helpers.math.js';\nimport {_getStartAndCountOfVisiblePoints, _scaleRangesChanged} from '../helpers/helpers.extras.js';\n\nexport default class LineController extends DatasetController {\n\n static id = 'line';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: 'line',\n dataElementType: 'point',\n\n showLine: true,\n spanGaps: false,\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n scales: {\n _index_: {\n type: 'category',\n },\n _value_: {\n type: 'linear',\n },\n }\n };\n\n initialize() {\n this.enableOptionSharing = true;\n this.supportsDecimation = true;\n super.initialize();\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n const {dataset: line, data: points = [], _dataset} = meta;\n // @ts-ignore\n const animationsDisabled = this.chart._animationsDisabled;\n let {start, count} = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);\n\n this._drawStart = start;\n this._drawCount = count;\n\n if (_scaleRangesChanged(meta)) {\n start = 0;\n count = points.length;\n }\n\n // Update Line\n line._chart = this.chart;\n line._datasetIndex = this.index;\n line._decimated = !!_dataset._decimated;\n line.points = points;\n\n const options = this.resolveDatasetElementOptions(mode);\n if (!this.options.showLine) {\n options.borderWidth = 0;\n }\n options.segment = this.options.segment;\n this.updateElement(line, undefined, {\n animated: !animationsDisabled,\n options\n }, mode);\n\n // Update Points\n this.updateElements(points, start, count, mode);\n }\n\n updateElements(points, start, count, mode) {\n const reset = mode === 'reset';\n const {iScale, vScale, _stacked, _dataset} = this._cachedMeta;\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const {spanGaps, segment} = this.options;\n const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;\n const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';\n const end = start + count;\n const pointsCount = points.length;\n let prevParsed = start > 0 && this.getParsed(start - 1);\n\n for (let i = 0; i < pointsCount; ++i) {\n const point = points[i];\n const properties = directUpdate ? point : {};\n\n if (i < start || i >= end) {\n properties.skip = true;\n continue;\n }\n\n const parsed = this.getParsed(i);\n const nullData = isNullOrUndef(parsed[vAxis]);\n const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);\n const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);\n\n properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;\n properties.stop = i > 0 && (Math.abs(parsed[iAxis] - prevParsed[iAxis])) > maxGapLength;\n if (segment) {\n properties.parsed = parsed;\n properties.raw = _dataset.data[i];\n }\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n }\n\n if (!directUpdate) {\n this.updateElement(point, i, properties, mode);\n }\n\n prevParsed = parsed;\n }\n }\n\n /**\n\t * @protected\n\t */\n getMaxOverflow() {\n const meta = this._cachedMeta;\n const dataset = meta.dataset;\n const border = dataset.options && dataset.options.borderWidth || 0;\n const data = meta.data || [];\n if (!data.length) {\n return border;\n }\n const firstPoint = data[0].size(this.resolveDataElementOptions(0));\n const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));\n return Math.max(border, firstPoint, lastPoint) / 2;\n }\n\n draw() {\n const meta = this._cachedMeta;\n meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis);\n super.draw();\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {toRadians, PI, formatNumber, _parseObjectDataRadialScale} from '../helpers/index.js';\n\nexport default class PolarAreaController extends DatasetController {\n\n static id = 'polarArea';\n\n /**\n * @type {any}\n */\n static defaults = {\n dataElementType: 'arc',\n animation: {\n animateRotate: true,\n animateScale: true\n },\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'startAngle', 'endAngle', 'innerRadius', 'outerRadius']\n },\n },\n indexAxis: 'r',\n startAngle: 0,\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n aspectRatio: 1,\n\n plugins: {\n legend: {\n labels: {\n generateLabels(chart) {\n const data = chart.data;\n if (data.labels.length && data.datasets.length) {\n const {labels: {pointStyle, color}} = chart.legend.options;\n\n return data.labels.map((label, i) => {\n const meta = chart.getDatasetMeta(0);\n const style = meta.controller.getStyle(i);\n\n return {\n text: label,\n fillStyle: style.backgroundColor,\n strokeStyle: style.borderColor,\n fontColor: color,\n lineWidth: style.borderWidth,\n pointStyle: pointStyle,\n hidden: !chart.getDataVisibility(i),\n\n // Extra data used for toggling the correct item\n index: i\n };\n });\n }\n return [];\n }\n },\n\n onClick(e, legendItem, legend) {\n legend.chart.toggleDataVisibility(legendItem.index);\n legend.chart.update();\n }\n }\n },\n\n scales: {\n r: {\n type: 'radialLinear',\n angleLines: {\n display: false\n },\n beginAtZero: true,\n grid: {\n circular: true\n },\n pointLabels: {\n display: false\n },\n startAngle: 0\n }\n }\n };\n\n constructor(chart, datasetIndex) {\n super(chart, datasetIndex);\n\n this.innerRadius = undefined;\n this.outerRadius = undefined;\n }\n\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const chart = this.chart;\n const labels = chart.data.labels || [];\n const value = formatNumber(meta._parsed[index].r, chart.options.locale);\n\n return {\n label: labels[index] || '',\n value,\n };\n }\n\n parseObjectData(meta, data, start, count) {\n return _parseObjectDataRadialScale.bind(this)(meta, data, start, count);\n }\n\n update(mode) {\n const arcs = this._cachedMeta.data;\n\n this._updateRadius();\n this.updateElements(arcs, 0, arcs.length, mode);\n }\n\n /**\n * @protected\n */\n getMinMax() {\n const meta = this._cachedMeta;\n const range = {min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY};\n\n meta.data.forEach((element, index) => {\n const parsed = this.getParsed(index).r;\n\n if (!isNaN(parsed) && this.chart.getDataVisibility(index)) {\n if (parsed < range.min) {\n range.min = parsed;\n }\n\n if (parsed > range.max) {\n range.max = parsed;\n }\n }\n });\n\n return range;\n }\n\n /**\n\t * @private\n\t */\n _updateRadius() {\n const chart = this.chart;\n const chartArea = chart.chartArea;\n const opts = chart.options;\n const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);\n\n const outerRadius = Math.max(minSize / 2, 0);\n const innerRadius = Math.max(opts.cutoutPercentage ? (outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);\n const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount();\n\n this.outerRadius = outerRadius - (radiusLength * this.index);\n this.innerRadius = this.outerRadius - radiusLength;\n }\n\n updateElements(arcs, start, count, mode) {\n const reset = mode === 'reset';\n const chart = this.chart;\n const opts = chart.options;\n const animationOpts = opts.animation;\n const scale = this._cachedMeta.rScale;\n const centerX = scale.xCenter;\n const centerY = scale.yCenter;\n const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI;\n let angle = datasetStartAngle;\n let i;\n\n const defaultAngle = 360 / this.countVisibleElements();\n\n for (i = 0; i < start; ++i) {\n angle += this._computeAngle(i, mode, defaultAngle);\n }\n for (i = start; i < start + count; i++) {\n const arc = arcs[i];\n let startAngle = angle;\n let endAngle = angle + this._computeAngle(i, mode, defaultAngle);\n let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(this.getParsed(i).r) : 0;\n angle = endAngle;\n\n if (reset) {\n if (animationOpts.animateScale) {\n outerRadius = 0;\n }\n if (animationOpts.animateRotate) {\n startAngle = endAngle = datasetStartAngle;\n }\n }\n\n const properties = {\n x: centerX,\n y: centerY,\n innerRadius: 0,\n outerRadius,\n startAngle,\n endAngle,\n options: this.resolveDataElementOptions(i, arc.active ? 'active' : mode)\n };\n\n this.updateElement(arc, i, properties, mode);\n }\n }\n\n countVisibleElements() {\n const meta = this._cachedMeta;\n let count = 0;\n\n meta.data.forEach((element, index) => {\n if (!isNaN(this.getParsed(index).r) && this.chart.getDataVisibility(index)) {\n count++;\n }\n });\n\n return count;\n }\n\n /**\n\t * @private\n\t */\n _computeAngle(index, mode, defaultAngle) {\n return this.chart.getDataVisibility(index)\n ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle)\n : 0;\n }\n}\n","import DoughnutController from './controller.doughnut.js';\n\n// Pie charts are Doughnut chart with different defaults\nexport default class PieController extends DoughnutController {\n\n static id = 'pie';\n\n /**\n * @type {any}\n */\n static defaults = {\n // The percentage of the chart that we cut out of the middle.\n cutout: 0,\n\n // The rotation of the chart, where the first data arc begins.\n rotation: 0,\n\n // The total circumference of the chart.\n circumference: 360,\n\n // The outer radius of the chart\n radius: '100%'\n };\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {_parseObjectDataRadialScale} from '../helpers/index.js';\n\nexport default class RadarController extends DatasetController {\n\n static id = 'radar';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: 'line',\n dataElementType: 'point',\n indexAxis: 'r',\n showLine: true,\n elements: {\n line: {\n fill: 'start'\n }\n },\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n aspectRatio: 1,\n\n scales: {\n r: {\n type: 'radialLinear',\n }\n }\n };\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const vScale = this._cachedMeta.vScale;\n const parsed = this.getParsed(index);\n\n return {\n label: vScale.getLabels()[index],\n value: '' + vScale.getLabelForValue(parsed[vScale.axis])\n };\n }\n\n parseObjectData(meta, data, start, count) {\n return _parseObjectDataRadialScale.bind(this)(meta, data, start, count);\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n const line = meta.dataset;\n const points = meta.data || [];\n const labels = meta.iScale.getLabels();\n\n // Update Line\n line.points = points;\n // In resize mode only point locations change, so no need to set the points or options.\n if (mode !== 'resize') {\n const options = this.resolveDatasetElementOptions(mode);\n if (!this.options.showLine) {\n options.borderWidth = 0;\n }\n\n const properties = {\n _loop: true,\n _fullLoop: labels.length === points.length,\n options\n };\n\n this.updateElement(line, undefined, properties, mode);\n }\n\n // Update Points\n this.updateElements(points, 0, points.length, mode);\n }\n\n updateElements(points, start, count, mode) {\n const scale = this._cachedMeta.rScale;\n const reset = mode === 'reset';\n\n for (let i = start; i < start + count; i++) {\n const point = points[i];\n const options = this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n const pointPosition = scale.getPointPositionForValue(i, this.getParsed(i).r);\n\n const x = reset ? scale.xCenter : pointPosition.x;\n const y = reset ? scale.yCenter : pointPosition.y;\n\n const properties = {\n x,\n y,\n angle: pointPosition.angle,\n skip: isNaN(x) || isNaN(y),\n options\n };\n\n this.updateElement(point, i, properties, mode);\n }\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {isNullOrUndef} from '../helpers/index.js';\nimport {isNumber} from '../helpers/helpers.math.js';\nimport {_getStartAndCountOfVisiblePoints, _scaleRangesChanged} from '../helpers/helpers.extras.js';\n\nexport default class ScatterController extends DatasetController {\n\n static id = 'scatter';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'point',\n showLine: false,\n fill: false\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n\n interaction: {\n mode: 'point'\n },\n\n scales: {\n x: {\n type: 'linear'\n },\n y: {\n type: 'linear'\n }\n }\n };\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const labels = this.chart.data.labels || [];\n const {xScale, yScale} = meta;\n const parsed = this.getParsed(index);\n const x = xScale.getLabelForValue(parsed.x);\n const y = yScale.getLabelForValue(parsed.y);\n\n return {\n label: labels[index] || '',\n value: '(' + x + ', ' + y + ')'\n };\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n const {data: points = []} = meta;\n // @ts-ignore\n const animationsDisabled = this.chart._animationsDisabled;\n let {start, count} = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);\n\n this._drawStart = start;\n this._drawCount = count;\n\n if (_scaleRangesChanged(meta)) {\n start = 0;\n count = points.length;\n }\n\n if (this.options.showLine) {\n\n // https://github.com/chartjs/Chart.js/issues/11333\n if (!this.datasetElementType) {\n this.addElements();\n }\n const {dataset: line, _dataset} = meta;\n\n // Update Line\n line._chart = this.chart;\n line._datasetIndex = this.index;\n line._decimated = !!_dataset._decimated;\n line.points = points;\n\n const options = this.resolveDatasetElementOptions(mode);\n options.segment = this.options.segment;\n this.updateElement(line, undefined, {\n animated: !animationsDisabled,\n options\n }, mode);\n } else if (this.datasetElementType) {\n // https://github.com/chartjs/Chart.js/issues/11333\n delete meta.dataset;\n this.datasetElementType = false;\n }\n\n // Update Points\n this.updateElements(points, start, count, mode);\n }\n\n addElements() {\n const {showLine} = this.options;\n\n if (!this.datasetElementType && showLine) {\n this.datasetElementType = this.chart.registry.getElement('line');\n }\n\n super.addElements();\n }\n\n updateElements(points, start, count, mode) {\n const reset = mode === 'reset';\n const {iScale, vScale, _stacked, _dataset} = this._cachedMeta;\n const firstOpts = this.resolveDataElementOptions(start, mode);\n const sharedOptions = this.getSharedOptions(firstOpts);\n const includeOptions = this.includeOptions(mode, sharedOptions);\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const {spanGaps, segment} = this.options;\n const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;\n const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';\n let prevParsed = start > 0 && this.getParsed(start - 1);\n\n for (let i = start; i < start + count; ++i) {\n const point = points[i];\n const parsed = this.getParsed(i);\n const properties = directUpdate ? point : {};\n const nullData = isNullOrUndef(parsed[vAxis]);\n const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);\n const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);\n\n properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;\n properties.stop = i > 0 && (Math.abs(parsed[iAxis] - prevParsed[iAxis])) > maxGapLength;\n if (segment) {\n properties.parsed = parsed;\n properties.raw = _dataset.data[i];\n }\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n }\n\n if (!directUpdate) {\n this.updateElement(point, i, properties, mode);\n }\n\n prevParsed = parsed;\n }\n\n this.updateSharedOptions(sharedOptions, mode, firstOpts);\n }\n\n /**\n\t * @protected\n\t */\n getMaxOverflow() {\n const meta = this._cachedMeta;\n const data = meta.data || [];\n\n if (!this.options.showLine) {\n let max = 0;\n for (let i = data.length - 1; i >= 0; --i) {\n max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);\n }\n return max > 0 && max;\n }\n\n const dataset = meta.dataset;\n const border = dataset.options && dataset.options.borderWidth || 0;\n\n if (!data.length) {\n return border;\n }\n\n const firstPoint = data[0].size(this.resolveDataElementOptions(0));\n const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));\n return Math.max(border, firstPoint, lastPoint) / 2;\n }\n}\n","/**\n * @namespace Chart._adapters\n * @since 2.8.0\n * @private\n */\n\nimport type {AnyObject} from '../types/basic.js';\nimport type {ChartOptions} from '../types/index.js';\n\nexport type TimeUnit = 'millisecond' | 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year';\n\nexport interface DateAdapter {\n readonly options: T;\n /**\n * Will called with chart options after adapter creation.\n */\n init(this: DateAdapter, chartOptions: ChartOptions): void;\n /**\n * Returns a map of time formats for the supported formatting units defined\n * in Unit as well as 'datetime' representing a detailed date/time string.\n */\n formats(this: DateAdapter): Record;\n /**\n * Parses the given `value` and return the associated timestamp.\n * @param value - the value to parse (usually comes from the data)\n * @param [format] - the expected data format\n */\n parse(this: DateAdapter, value: unknown, format?: string): number | null;\n /**\n * Returns the formatted date in the specified `format` for a given `timestamp`.\n * @param timestamp - the timestamp to format\n * @param format - the date/time token\n */\n format(this: DateAdapter, timestamp: number, format: string): string;\n /**\n * Adds the specified `amount` of `unit` to the given `timestamp`.\n * @param timestamp - the input timestamp\n * @param amount - the amount to add\n * @param unit - the unit as string\n */\n add(this: DateAdapter, timestamp: number, amount: number, unit: TimeUnit): number;\n /**\n * Returns the number of `unit` between the given timestamps.\n * @param a - the input timestamp (reference)\n * @param b - the timestamp to subtract\n * @param unit - the unit as string\n */\n diff(this: DateAdapter, a: number, b: number, unit: TimeUnit): number;\n /**\n * Returns start of `unit` for the given `timestamp`.\n * @param timestamp - the input timestamp\n * @param unit - the unit as string\n * @param [weekday] - the ISO day of the week with 1 being Monday\n * and 7 being Sunday (only needed if param *unit* is `isoWeek`).\n */\n startOf(this: DateAdapter, timestamp: number, unit: TimeUnit | 'isoWeek', weekday?: number | boolean): number;\n /**\n * Returns end of `unit` for the given `timestamp`.\n * @param timestamp - the input timestamp\n * @param unit - the unit as string\n */\n endOf(this: DateAdapter, timestamp: number, unit: TimeUnit): number;\n}\n\nfunction abstract(): T {\n throw new Error('This method is not implemented: Check that a complete date adapter is provided.');\n}\n\n/**\n * Date adapter (current used by the time scale)\n * @namespace Chart._adapters._date\n * @memberof Chart._adapters\n * @private\n */\nclass DateAdapterBase implements DateAdapter {\n\n /**\n * Override default date adapter methods.\n * Accepts type parameter to define options type.\n * @example\n * Chart._adapters._date.override<{myAdapterOption: string}>({\n * init() {\n * console.log(this.options.myAdapterOption);\n * }\n * })\n */\n static override(\n members: Partial, 'options'>>\n ) {\n Object.assign(DateAdapterBase.prototype, members);\n }\n\n readonly options: AnyObject;\n\n constructor(options?: AnyObject) {\n this.options = options || {};\n }\n\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n init() {}\n\n formats(): Record {\n return abstract();\n }\n\n parse(): number | null {\n return abstract();\n }\n\n format(): string {\n return abstract();\n }\n\n add(): number {\n return abstract();\n }\n\n diff(): number {\n return abstract();\n }\n\n startOf(): number {\n return abstract();\n }\n\n endOf(): number {\n return abstract();\n }\n}\n\nexport default {\n _date: DateAdapterBase as {\n new (options?: AnyObject): DateAdapter;\n override(\n members: Partial, 'options'>>\n ): void;\n }\n};\n","import {_lookupByKey, _rlookupByKey} from '../helpers/helpers.collection.js';\nimport {getRelativePosition} from '../helpers/helpers.dom.js';\nimport {_angleBetween, getAngleFromPoint} from '../helpers/helpers.math.js';\nimport {_isPointInArea, isNullOrUndef} from '../helpers/index.js';\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n * @typedef { import('../types/index.js').ChartEvent } ChartEvent\n * @typedef {{axis?: string, intersect?: boolean, includeInvisible?: boolean}} InteractionOptions\n * @typedef {{datasetIndex: number, index: number, element: import('./core.element.js').default}} InteractionItem\n * @typedef { import('../types/index.js').Point } Point\n */\n\n/**\n * Helper function to do binary search when possible\n * @param {object} metaset - the dataset meta\n * @param {string} axis - the axis mode. x|y|xy|r\n * @param {number} value - the value to find\n * @param {boolean} [intersect] - should the element intersect\n * @returns {{lo:number, hi:number}} indices to search data array between\n */\nfunction binarySearch(metaset, axis, value, intersect) {\n const {controller, data, _sorted} = metaset;\n const iScale = controller._cachedMeta.iScale;\n const spanGaps = metaset.dataset ? metaset.dataset.options ? metaset.dataset.options.spanGaps : null : null;\n\n if (iScale && axis === iScale.axis && axis !== 'r' && _sorted && data.length) {\n const lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey;\n if (!intersect) {\n const result = lookupMethod(data, axis, value);\n if (spanGaps) {\n const {vScale} = controller._cachedMeta;\n const {_parsed} = metaset;\n\n const distanceToDefinedLo = (_parsed\n .slice(0, result.lo + 1)\n .reverse()\n .findIndex(\n point => !isNullOrUndef(point[vScale.axis])));\n result.lo -= Math.max(0, distanceToDefinedLo);\n\n const distanceToDefinedHi = (_parsed\n .slice(result.hi)\n .findIndex(\n point => !isNullOrUndef(point[vScale.axis])));\n result.hi += Math.max(0, distanceToDefinedHi);\n }\n return result;\n } else if (controller._sharedOptions) {\n // _sharedOptions indicates that each element has equal options -> equal proportions\n // So we can do a ranged binary search based on the range of first element and\n // be confident to get the full range of indices that can intersect with the value.\n const el = data[0];\n const range = typeof el.getRange === 'function' && el.getRange(axis);\n if (range) {\n const start = lookupMethod(data, axis, value - range);\n const end = lookupMethod(data, axis, value + range);\n return {lo: start.lo, hi: end.hi};\n }\n }\n }\n // Default to all elements, when binary search can not be used.\n return {lo: 0, hi: data.length - 1};\n}\n\n/**\n * Helper function to select candidate elements for interaction\n * @param {Chart} chart - the chart\n * @param {string} axis - the axis mode. x|y|xy|r\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {function} handler - the callback to execute for each visible item\n * @param {boolean} [intersect] - consider intersecting items\n */\nfunction evaluateInteractionItems(chart, axis, position, handler, intersect) {\n const metasets = chart.getSortedVisibleDatasetMetas();\n const value = position[axis];\n for (let i = 0, ilen = metasets.length; i < ilen; ++i) {\n const {index, data} = metasets[i];\n const {lo, hi} = binarySearch(metasets[i], axis, value, intersect);\n for (let j = lo; j <= hi; ++j) {\n const element = data[j];\n if (!element.skip) {\n handler(element, index, j);\n }\n }\n }\n}\n\n/**\n * Get a distance metric function for two points based on the\n * axis mode setting\n * @param {string} axis - the axis mode. x|y|xy|r\n */\nfunction getDistanceMetricForAxis(axis) {\n const useX = axis.indexOf('x') !== -1;\n const useY = axis.indexOf('y') !== -1;\n\n return function(pt1, pt2) {\n const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;\n const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;\n return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));\n };\n}\n\n/**\n * Helper function to get the items that intersect the event position\n * @param {Chart} chart - the chart\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axis mode. x|y|xy|r\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @param {boolean} [includeInvisible] - include invisible points that are outside of the chart area\n * @return {InteractionItem[]} the nearest items\n */\nfunction getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) {\n const items = [];\n\n if (!includeInvisible && !chart.isPointInArea(position)) {\n return items;\n }\n\n const evaluationFunc = function(element, datasetIndex, index) {\n if (!includeInvisible && !_isPointInArea(element, chart.chartArea, 0)) {\n return;\n }\n if (element.inRange(position.x, position.y, useFinalPosition)) {\n items.push({element, datasetIndex, index});\n }\n };\n\n evaluateInteractionItems(chart, axis, position, evaluationFunc, true);\n return items;\n}\n\n/**\n * Helper function to get the items nearest to the event position for a radial chart\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axes along which to measure distance\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @return {InteractionItem[]} the nearest items\n */\nfunction getNearestRadialItems(chart, position, axis, useFinalPosition) {\n let items = [];\n\n function evaluationFunc(element, datasetIndex, index) {\n const {startAngle, endAngle} = element.getProps(['startAngle', 'endAngle'], useFinalPosition);\n const {angle} = getAngleFromPoint(element, {x: position.x, y: position.y});\n\n if (_angleBetween(angle, startAngle, endAngle)) {\n items.push({element, datasetIndex, index});\n }\n }\n\n evaluateInteractionItems(chart, axis, position, evaluationFunc);\n return items;\n}\n\n/**\n * Helper function to get the items nearest to the event position for a cartesian chart\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axes along which to measure distance\n * @param {boolean} [intersect] - if true, only consider items that intersect the position\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @param {boolean} [includeInvisible] - include invisible points that are outside of the chart area\n * @return {InteractionItem[]} the nearest items\n */\nfunction getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {\n let items = [];\n const distanceMetric = getDistanceMetricForAxis(axis);\n let minDistance = Number.POSITIVE_INFINITY;\n\n function evaluationFunc(element, datasetIndex, index) {\n const inRange = element.inRange(position.x, position.y, useFinalPosition);\n if (intersect && !inRange) {\n return;\n }\n\n const center = element.getCenterPoint(useFinalPosition);\n const pointInArea = !!includeInvisible || chart.isPointInArea(center);\n if (!pointInArea && !inRange) {\n return;\n }\n\n const distance = distanceMetric(position, center);\n if (distance < minDistance) {\n items = [{element, datasetIndex, index}];\n minDistance = distance;\n } else if (distance === minDistance) {\n // Can have multiple items at the same distance in which case we sort by size\n items.push({element, datasetIndex, index});\n }\n }\n\n evaluateInteractionItems(chart, axis, position, evaluationFunc);\n return items;\n}\n\n/**\n * Helper function to get the items nearest to the event position considering all visible items in the chart\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axes along which to measure distance\n * @param {boolean} [intersect] - if true, only consider items that intersect the position\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @param {boolean} [includeInvisible] - include invisible points that are outside of the chart area\n * @return {InteractionItem[]} the nearest items\n */\nfunction getNearestItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {\n if (!includeInvisible && !chart.isPointInArea(position)) {\n return [];\n }\n\n return axis === 'r' && !intersect\n ? getNearestRadialItems(chart, position, axis, useFinalPosition)\n : getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible);\n}\n\n/**\n * Helper function to get the items matching along the given X or Y axis\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axis to match\n * @param {boolean} [intersect] - if true, only consider items that intersect the position\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @return {InteractionItem[]} the nearest items\n */\nfunction getAxisItems(chart, position, axis, intersect, useFinalPosition) {\n const items = [];\n const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange';\n let intersectsItem = false;\n\n evaluateInteractionItems(chart, axis, position, (element, datasetIndex, index) => {\n if (element[rangeMethod] && element[rangeMethod](position[axis], useFinalPosition)) {\n items.push({element, datasetIndex, index});\n intersectsItem = intersectsItem || element.inRange(position.x, position.y, useFinalPosition);\n }\n });\n\n // If we want to trigger on an intersect and we don't have any items\n // that intersect the position, return nothing\n if (intersect && !intersectsItem) {\n return [];\n }\n return items;\n}\n\n/**\n * Contains interaction related functions\n * @namespace Chart.Interaction\n */\nexport default {\n // Part of the public API to facilitate developers creating their own modes\n evaluateInteractionItems,\n\n // Helper function for different modes\n modes: {\n /**\n\t\t * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something\n\t\t * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item\n\t\t * @function Chart.Interaction.modes.index\n\t\t * @since v2.4.0\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n index(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n // Default axis for index mode is 'x' to match old behaviour\n const axis = options.axis || 'x';\n const includeInvisible = options.includeInvisible || false;\n const items = options.intersect\n ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible)\n : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);\n const elements = [];\n\n if (!items.length) {\n return [];\n }\n\n chart.getSortedVisibleDatasetMetas().forEach((meta) => {\n const index = items[0].index;\n const element = meta.data[index];\n\n // don't count items that are skipped (null data)\n if (element && !element.skip) {\n elements.push({element, datasetIndex: meta.index, index});\n }\n });\n\n return elements;\n },\n\n /**\n\t\t * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something\n\t\t * If the options.intersect is false, we find the nearest item and return the items in that dataset\n\t\t * @function Chart.Interaction.modes.dataset\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n dataset(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'xy';\n const includeInvisible = options.includeInvisible || false;\n let items = options.intersect\n ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) :\n getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);\n\n if (items.length > 0) {\n const datasetIndex = items[0].datasetIndex;\n const data = chart.getDatasetMeta(datasetIndex).data;\n items = [];\n for (let i = 0; i < data.length; ++i) {\n items.push({element: data[i], datasetIndex, index: i});\n }\n }\n\n return items;\n },\n\n /**\n\t\t * Point mode returns all elements that hit test based on the event position\n\t\t * of the event\n\t\t * @function Chart.Interaction.modes.intersect\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n point(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'xy';\n const includeInvisible = options.includeInvisible || false;\n return getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible);\n },\n\n /**\n\t\t * nearest mode returns the element closest to the point\n\t\t * @function Chart.Interaction.modes.intersect\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n nearest(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'xy';\n const includeInvisible = options.includeInvisible || false;\n return getNearestItems(chart, position, axis, options.intersect, useFinalPosition, includeInvisible);\n },\n\n /**\n\t\t * x mode returns the elements that hit-test at the current x coordinate\n\t\t * @function Chart.Interaction.modes.x\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n x(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n return getAxisItems(chart, position, 'x', options.intersect, useFinalPosition);\n },\n\n /**\n\t\t * y mode returns the elements that hit-test at the current y coordinate\n\t\t * @function Chart.Interaction.modes.y\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n y(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n return getAxisItems(chart, position, 'y', options.intersect, useFinalPosition);\n }\n }\n};\n","import {defined, each, isObject} from '../helpers/helpers.core.js';\nimport {toPadding} from '../helpers/helpers.options.js';\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n */\n\nconst STATIC_POSITIONS = ['left', 'top', 'right', 'bottom'];\n\nfunction filterByPosition(array, position) {\n return array.filter(v => v.pos === position);\n}\n\nfunction filterDynamicPositionByAxis(array, axis) {\n return array.filter(v => STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis);\n}\n\nfunction sortByWeight(array, reverse) {\n return array.sort((a, b) => {\n const v0 = reverse ? b : a;\n const v1 = reverse ? a : b;\n return v0.weight === v1.weight ?\n v0.index - v1.index :\n v0.weight - v1.weight;\n });\n}\n\nfunction wrapBoxes(boxes) {\n const layoutBoxes = [];\n let i, ilen, box, pos, stack, stackWeight;\n\n for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {\n box = boxes[i];\n ({position: pos, options: {stack, stackWeight = 1}} = box);\n layoutBoxes.push({\n index: i,\n box,\n pos,\n horizontal: box.isHorizontal(),\n weight: box.weight,\n stack: stack && (pos + stack),\n stackWeight\n });\n }\n return layoutBoxes;\n}\n\nfunction buildStacks(layouts) {\n const stacks = {};\n for (const wrap of layouts) {\n const {stack, pos, stackWeight} = wrap;\n if (!stack || !STATIC_POSITIONS.includes(pos)) {\n continue;\n }\n const _stack = stacks[stack] || (stacks[stack] = {count: 0, placed: 0, weight: 0, size: 0});\n _stack.count++;\n _stack.weight += stackWeight;\n }\n return stacks;\n}\n\n/**\n * store dimensions used instead of available chartArea in fitBoxes\n **/\nfunction setLayoutDims(layouts, params) {\n const stacks = buildStacks(layouts);\n const {vBoxMaxWidth, hBoxMaxHeight} = params;\n let i, ilen, layout;\n for (i = 0, ilen = layouts.length; i < ilen; ++i) {\n layout = layouts[i];\n const {fullSize} = layout.box;\n const stack = stacks[layout.stack];\n const factor = stack && layout.stackWeight / stack.weight;\n if (layout.horizontal) {\n layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth;\n layout.height = hBoxMaxHeight;\n } else {\n layout.width = vBoxMaxWidth;\n layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight;\n }\n }\n return stacks;\n}\n\nfunction buildLayoutBoxes(boxes) {\n const layoutBoxes = wrapBoxes(boxes);\n const fullSize = sortByWeight(layoutBoxes.filter(wrap => wrap.box.fullSize), true);\n const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);\n const right = sortByWeight(filterByPosition(layoutBoxes, 'right'));\n const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);\n const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));\n const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x');\n const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y');\n\n return {\n fullSize,\n leftAndTop: left.concat(top),\n rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal),\n chartArea: filterByPosition(layoutBoxes, 'chartArea'),\n vertical: left.concat(right).concat(centerVertical),\n horizontal: top.concat(bottom).concat(centerHorizontal)\n };\n}\n\nfunction getCombinedMax(maxPadding, chartArea, a, b) {\n return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);\n}\n\nfunction updateMaxPadding(maxPadding, boxPadding) {\n maxPadding.top = Math.max(maxPadding.top, boxPadding.top);\n maxPadding.left = Math.max(maxPadding.left, boxPadding.left);\n maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);\n maxPadding.right = Math.max(maxPadding.right, boxPadding.right);\n}\n\nfunction updateDims(chartArea, params, layout, stacks) {\n const {pos, box} = layout;\n const maxPadding = chartArea.maxPadding;\n\n // dynamically placed boxes size is not considered\n if (!isObject(pos)) {\n if (layout.size) {\n // this layout was already counted for, lets first reduce old size\n chartArea[pos] -= layout.size;\n }\n const stack = stacks[layout.stack] || {size: 0, count: 1};\n stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width);\n layout.size = stack.size / stack.count;\n chartArea[pos] += layout.size;\n }\n\n if (box.getPadding) {\n updateMaxPadding(maxPadding, box.getPadding());\n }\n\n const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right'));\n const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom'));\n const widthChanged = newWidth !== chartArea.w;\n const heightChanged = newHeight !== chartArea.h;\n chartArea.w = newWidth;\n chartArea.h = newHeight;\n\n // return booleans on the changes per direction\n return layout.horizontal\n ? {same: widthChanged, other: heightChanged}\n : {same: heightChanged, other: widthChanged};\n}\n\nfunction handleMaxPadding(chartArea) {\n const maxPadding = chartArea.maxPadding;\n\n function updatePos(pos) {\n const change = Math.max(maxPadding[pos] - chartArea[pos], 0);\n chartArea[pos] += change;\n return change;\n }\n chartArea.y += updatePos('top');\n chartArea.x += updatePos('left');\n updatePos('right');\n updatePos('bottom');\n}\n\nfunction getMargins(horizontal, chartArea) {\n const maxPadding = chartArea.maxPadding;\n\n function marginForPositions(positions) {\n const margin = {left: 0, top: 0, right: 0, bottom: 0};\n positions.forEach((pos) => {\n margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);\n });\n return margin;\n }\n\n return horizontal\n ? marginForPositions(['left', 'right'])\n : marginForPositions(['top', 'bottom']);\n}\n\nfunction fitBoxes(boxes, chartArea, params, stacks) {\n const refitBoxes = [];\n let i, ilen, layout, box, refit, changed;\n\n for (i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i) {\n layout = boxes[i];\n box = layout.box;\n\n box.update(\n layout.width || chartArea.w,\n layout.height || chartArea.h,\n getMargins(layout.horizontal, chartArea)\n );\n const {same, other} = updateDims(chartArea, params, layout, stacks);\n\n // Dimensions changed and there were non full width boxes before this\n // -> we have to refit those\n refit |= same && refitBoxes.length;\n\n // Chart area changed in the opposite direction\n changed = changed || other;\n\n if (!box.fullSize) { // fullSize boxes don't need to be re-fitted in any case\n refitBoxes.push(layout);\n }\n }\n\n return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed;\n}\n\nfunction setBoxDims(box, left, top, width, height) {\n box.top = top;\n box.left = left;\n box.right = left + width;\n box.bottom = top + height;\n box.width = width;\n box.height = height;\n}\n\nfunction placeBoxes(boxes, chartArea, params, stacks) {\n const userPadding = params.padding;\n let {x, y} = chartArea;\n\n for (const layout of boxes) {\n const box = layout.box;\n const stack = stacks[layout.stack] || {count: 1, placed: 0, weight: 1};\n const weight = (layout.stackWeight / stack.weight) || 1;\n if (layout.horizontal) {\n const width = chartArea.w * weight;\n const height = stack.size || box.height;\n if (defined(stack.start)) {\n y = stack.start;\n }\n if (box.fullSize) {\n setBoxDims(box, userPadding.left, y, params.outerWidth - userPadding.right - userPadding.left, height);\n } else {\n setBoxDims(box, chartArea.left + stack.placed, y, width, height);\n }\n stack.start = y;\n stack.placed += width;\n y = box.bottom;\n } else {\n const height = chartArea.h * weight;\n const width = stack.size || box.width;\n if (defined(stack.start)) {\n x = stack.start;\n }\n if (box.fullSize) {\n setBoxDims(box, x, userPadding.top, width, params.outerHeight - userPadding.bottom - userPadding.top);\n } else {\n setBoxDims(box, x, chartArea.top + stack.placed, width, height);\n }\n stack.start = x;\n stack.placed += height;\n x = box.right;\n }\n }\n\n chartArea.x = x;\n chartArea.y = y;\n}\n\n/**\n * @interface LayoutItem\n * @typedef {object} LayoutItem\n * @prop {string} position - The position of the item in the chart layout. Possible values are\n * 'left', 'top', 'right', 'bottom', and 'chartArea'\n * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area\n * @prop {boolean} fullSize - if true, and the item is horizontal, then push vertical boxes down\n * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)\n * @prop {function} update - Takes two parameters: width and height. Returns size of item\n * @prop {function} draw - Draws the element\n * @prop {function} [getPadding] - Returns an object with padding on the edges\n * @prop {number} width - Width of item. Must be valid after update()\n * @prop {number} height - Height of item. Must be valid after update()\n * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update\n * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update\n * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update\n * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update\n */\n\n// The layout service is very self explanatory. It's responsible for the layout within a chart.\n// Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need\n// It is this service's responsibility of carrying out that layout.\nexport default {\n\n /**\n\t * Register a box to a chart.\n\t * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.\n\t * @param {Chart} chart - the chart to use\n\t * @param {LayoutItem} item - the item to add to be laid out\n\t */\n addBox(chart, item) {\n if (!chart.boxes) {\n chart.boxes = [];\n }\n\n // initialize item with default values\n item.fullSize = item.fullSize || false;\n item.position = item.position || 'top';\n item.weight = item.weight || 0;\n // @ts-ignore\n item._layers = item._layers || function() {\n return [{\n z: 0,\n draw(chartArea) {\n item.draw(chartArea);\n }\n }];\n };\n\n chart.boxes.push(item);\n },\n\n /**\n\t * Remove a layoutItem from a chart\n\t * @param {Chart} chart - the chart to remove the box from\n\t * @param {LayoutItem} layoutItem - the item to remove from the layout\n\t */\n removeBox(chart, layoutItem) {\n const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;\n if (index !== -1) {\n chart.boxes.splice(index, 1);\n }\n },\n\n /**\n\t * Sets (or updates) options on the given `item`.\n\t * @param {Chart} chart - the chart in which the item lives (or will be added to)\n\t * @param {LayoutItem} item - the item to configure with the given options\n\t * @param {object} options - the new item options.\n\t */\n configure(chart, item, options) {\n item.fullSize = options.fullSize;\n item.position = options.position;\n item.weight = options.weight;\n },\n\n /**\n\t * Fits boxes of the given chart into the given size by having each box measure itself\n\t * then running a fitting algorithm\n\t * @param {Chart} chart - the chart\n\t * @param {number} width - the width to fit into\n\t * @param {number} height - the height to fit into\n * @param {number} minPadding - minimum padding required for each side of chart area\n\t */\n update(chart, width, height, minPadding) {\n if (!chart) {\n return;\n }\n\n const padding = toPadding(chart.options.layout.padding);\n const availableWidth = Math.max(width - padding.width, 0);\n const availableHeight = Math.max(height - padding.height, 0);\n const boxes = buildLayoutBoxes(chart.boxes);\n const verticalBoxes = boxes.vertical;\n const horizontalBoxes = boxes.horizontal;\n\n // Before any changes are made, notify boxes that an update is about to being\n // This is used to clear any cached data (e.g. scale limits)\n each(chart.boxes, box => {\n if (typeof box.beforeLayout === 'function') {\n box.beforeLayout();\n }\n });\n\n // Essentially we now have any number of boxes on each of the 4 sides.\n // Our canvas looks like the following.\n // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and\n // B1 is the bottom axis\n // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays\n // These locations are single-box locations only, when trying to register a chartArea location that is already taken,\n // an error will be thrown.\n //\n // |----------------------------------------------------|\n // | T1 (Full Width) |\n // |----------------------------------------------------|\n // | | | T2 | |\n // | |----|-------------------------------------|----|\n // | | | C1 | | C2 | |\n // | | |----| |----| |\n // | | | | |\n // | L1 | L2 | ChartArea (C0) | R1 |\n // | | | | |\n // | | |----| |----| |\n // | | | C3 | | C4 | |\n // | |----|-------------------------------------|----|\n // | | | B1 | |\n // |----------------------------------------------------|\n // | B2 (Full Width) |\n // |----------------------------------------------------|\n //\n\n const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap) =>\n wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1;\n\n const params = Object.freeze({\n outerWidth: width,\n outerHeight: height,\n padding,\n availableWidth,\n availableHeight,\n vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount,\n hBoxMaxHeight: availableHeight / 2\n });\n const maxPadding = Object.assign({}, padding);\n updateMaxPadding(maxPadding, toPadding(minPadding));\n const chartArea = Object.assign({\n maxPadding,\n w: availableWidth,\n h: availableHeight,\n x: padding.left,\n y: padding.top\n }, padding);\n\n const stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);\n\n // First fit the fullSize boxes, to reduce probability of re-fitting.\n fitBoxes(boxes.fullSize, chartArea, params, stacks);\n\n // Then fit vertical boxes\n fitBoxes(verticalBoxes, chartArea, params, stacks);\n\n // Then fit horizontal boxes\n if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) {\n // if the area changed, re-fit vertical boxes\n fitBoxes(verticalBoxes, chartArea, params, stacks);\n }\n\n handleMaxPadding(chartArea);\n\n // Finally place the boxes to correct coordinates\n placeBoxes(boxes.leftAndTop, chartArea, params, stacks);\n\n // Move to opposite side of chart\n chartArea.x += chartArea.w;\n chartArea.y += chartArea.h;\n\n placeBoxes(boxes.rightAndBottom, chartArea, params, stacks);\n\n chart.chartArea = {\n left: chartArea.left,\n top: chartArea.top,\n right: chartArea.left + chartArea.w,\n bottom: chartArea.top + chartArea.h,\n height: chartArea.h,\n width: chartArea.w,\n };\n\n // Finally update boxes in chartArea (radial scale for example)\n each(boxes.chartArea, (layout) => {\n const box = layout.box;\n Object.assign(box, chart.chartArea);\n box.update(chartArea.w, chartArea.h, {left: 0, top: 0, right: 0, bottom: 0});\n });\n }\n};\n","\n/**\n * @typedef { import('../core/core.controller.js').default } Chart\n */\n\n/**\n * Abstract class that allows abstracting platform dependencies away from the chart.\n */\nexport default class BasePlatform {\n /**\n\t * Called at chart construction time, returns a context2d instance implementing\n\t * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.\n\t * @param {HTMLCanvasElement} canvas - The canvas from which to acquire context (platform specific)\n\t * @param {number} [aspectRatio] - The chart options\n\t */\n acquireContext(canvas, aspectRatio) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * Called at chart destruction time, releases any resources associated to the context\n\t * previously returned by the acquireContext() method.\n\t * @param {CanvasRenderingContext2D} context - The context2d instance\n\t * @returns {boolean} true if the method succeeded, else false\n\t */\n releaseContext(context) { // eslint-disable-line no-unused-vars\n return false;\n }\n\n /**\n\t * Registers the specified listener on the given chart.\n\t * @param {Chart} chart - Chart from which to listen for event\n\t * @param {string} type - The ({@link ChartEvent}) type to listen for\n\t * @param {function} listener - Receives a notification (an object that implements\n\t * the {@link ChartEvent} interface) when an event of the specified type occurs.\n\t */\n addEventListener(chart, type, listener) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * Removes the specified listener previously registered with addEventListener.\n\t * @param {Chart} chart - Chart from which to remove the listener\n\t * @param {string} type - The ({@link ChartEvent}) type to remove\n\t * @param {function} listener - The listener function to remove from the event target.\n\t */\n removeEventListener(chart, type, listener) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * @returns {number} the current devicePixelRatio of the device this platform is connected to.\n\t */\n getDevicePixelRatio() {\n return 1;\n }\n\n /**\n\t * Returns the maximum size in pixels of given canvas element.\n\t * @param {HTMLCanvasElement} element\n\t * @param {number} [width] - content width of parent element\n\t * @param {number} [height] - content height of parent element\n\t * @param {number} [aspectRatio] - aspect ratio to maintain\n\t */\n getMaximumSize(element, width, height, aspectRatio) {\n width = Math.max(0, width || element.width);\n height = height || element.height;\n return {\n width,\n height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height)\n };\n }\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t * @returns {boolean} true if the canvas is attached to the platform, false if not.\n\t */\n isAttached(canvas) { // eslint-disable-line no-unused-vars\n return true;\n }\n\n /**\n * Updates config with platform specific requirements\n * @param {import('../core/core.config.js').default} config\n */\n updateConfig(config) { // eslint-disable-line no-unused-vars\n // no-op\n }\n}\n","/**\n * Platform fallback implementation (minimal).\n * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939\n */\n\nimport BasePlatform from './platform.base.js';\n\n/**\n * Platform class for charts without access to the DOM or to many element properties\n * This platform is used by default for any chart passed an OffscreenCanvas.\n * @extends BasePlatform\n */\nexport default class BasicPlatform extends BasePlatform {\n acquireContext(item) {\n // To prevent canvas fingerprinting, some add-ons undefine the getContext\n // method, for example: https://github.com/kkapsner/CanvasBlocker\n // https://github.com/chartjs/Chart.js/issues/2807\n return item && item.getContext && item.getContext('2d') || null;\n }\n updateConfig(config) {\n config.options.animation = false;\n }\n}\n","/**\n * Chart.Platform implementation for targeting a web browser\n */\n\nimport BasePlatform from './platform.base.js';\nimport {_getParentNode, getRelativePosition, supportsEventListenerOptions, readUsedSize, getMaximumSize} from '../helpers/helpers.dom.js';\nimport {throttled} from '../helpers/helpers.extras.js';\nimport {isNullOrUndef} from '../helpers/helpers.core.js';\n\n/**\n * @typedef { import('../core/core.controller.js').default } Chart\n */\n\nconst EXPANDO_KEY = '$chartjs';\n\n/**\n * DOM event types -> Chart.js event types.\n * Note: only events with different types are mapped.\n * @see https://developer.mozilla.org/en-US/docs/Web/Events\n */\nconst EVENT_TYPES = {\n touchstart: 'mousedown',\n touchmove: 'mousemove',\n touchend: 'mouseup',\n pointerenter: 'mouseenter',\n pointerdown: 'mousedown',\n pointermove: 'mousemove',\n pointerup: 'mouseup',\n pointerleave: 'mouseout',\n pointerout: 'mouseout'\n};\n\nconst isNullOrEmpty = value => value === null || value === '';\n/**\n * Initializes the canvas style and render size without modifying the canvas display size,\n * since responsiveness is handled by the controller.resize() method. The config is used\n * to determine the aspect ratio to apply in case no explicit height has been specified.\n * @param {HTMLCanvasElement} canvas\n * @param {number} [aspectRatio]\n */\nfunction initCanvas(canvas, aspectRatio) {\n const style = canvas.style;\n\n // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it\n // returns null or '' if no explicit value has been set to the canvas attribute.\n const renderHeight = canvas.getAttribute('height');\n const renderWidth = canvas.getAttribute('width');\n\n // Chart.js modifies some canvas values that we want to restore on destroy\n canvas[EXPANDO_KEY] = {\n initial: {\n height: renderHeight,\n width: renderWidth,\n style: {\n display: style.display,\n height: style.height,\n width: style.width\n }\n }\n };\n\n // Force canvas to display as block to avoid extra space caused by inline\n // elements, which would interfere with the responsive resize process.\n // https://github.com/chartjs/Chart.js/issues/2538\n style.display = style.display || 'block';\n // Include possible borders in the size\n style.boxSizing = style.boxSizing || 'border-box';\n\n if (isNullOrEmpty(renderWidth)) {\n const displayWidth = readUsedSize(canvas, 'width');\n if (displayWidth !== undefined) {\n canvas.width = displayWidth;\n }\n }\n\n if (isNullOrEmpty(renderHeight)) {\n if (canvas.style.height === '') {\n // If no explicit render height and style height, let's apply the aspect ratio,\n // which one can be specified by the user but also by charts as default option\n // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.\n canvas.height = canvas.width / (aspectRatio || 2);\n } else {\n const displayHeight = readUsedSize(canvas, 'height');\n if (displayHeight !== undefined) {\n canvas.height = displayHeight;\n }\n }\n }\n\n return canvas;\n}\n\n// Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.\n// https://github.com/chartjs/Chart.js/issues/4287\nconst eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;\n\nfunction addListener(node, type, listener) {\n if (node) {\n node.addEventListener(type, listener, eventListenerOptions);\n }\n}\n\nfunction removeListener(chart, type, listener) {\n if (chart && chart.canvas) {\n chart.canvas.removeEventListener(type, listener, eventListenerOptions);\n }\n}\n\nfunction fromNativeEvent(event, chart) {\n const type = EVENT_TYPES[event.type] || event.type;\n const {x, y} = getRelativePosition(event, chart);\n return {\n type,\n chart,\n native: event,\n x: x !== undefined ? x : null,\n y: y !== undefined ? y : null,\n };\n}\n\nfunction nodeListContains(nodeList, canvas) {\n for (const node of nodeList) {\n if (node === canvas || node.contains(canvas)) {\n return true;\n }\n }\n}\n\nfunction createAttachObserver(chart, type, listener) {\n const canvas = chart.canvas;\n const observer = new MutationObserver(entries => {\n let trigger = false;\n for (const entry of entries) {\n trigger = trigger || nodeListContains(entry.addedNodes, canvas);\n trigger = trigger && !nodeListContains(entry.removedNodes, canvas);\n }\n if (trigger) {\n listener();\n }\n });\n observer.observe(document, {childList: true, subtree: true});\n return observer;\n}\n\nfunction createDetachObserver(chart, type, listener) {\n const canvas = chart.canvas;\n const observer = new MutationObserver(entries => {\n let trigger = false;\n for (const entry of entries) {\n trigger = trigger || nodeListContains(entry.removedNodes, canvas);\n trigger = trigger && !nodeListContains(entry.addedNodes, canvas);\n }\n if (trigger) {\n listener();\n }\n });\n observer.observe(document, {childList: true, subtree: true});\n return observer;\n}\n\nconst drpListeningCharts = new Map();\nlet oldDevicePixelRatio = 0;\n\nfunction onWindowResize() {\n const dpr = window.devicePixelRatio;\n if (dpr === oldDevicePixelRatio) {\n return;\n }\n oldDevicePixelRatio = dpr;\n drpListeningCharts.forEach((resize, chart) => {\n if (chart.currentDevicePixelRatio !== dpr) {\n resize();\n }\n });\n}\n\nfunction listenDevicePixelRatioChanges(chart, resize) {\n if (!drpListeningCharts.size) {\n window.addEventListener('resize', onWindowResize);\n }\n drpListeningCharts.set(chart, resize);\n}\n\nfunction unlistenDevicePixelRatioChanges(chart) {\n drpListeningCharts.delete(chart);\n if (!drpListeningCharts.size) {\n window.removeEventListener('resize', onWindowResize);\n }\n}\n\nfunction createResizeObserver(chart, type, listener) {\n const canvas = chart.canvas;\n const container = canvas && _getParentNode(canvas);\n if (!container) {\n return;\n }\n const resize = throttled((width, height) => {\n const w = container.clientWidth;\n listener(width, height);\n if (w < container.clientWidth) {\n // If the container size shrank during chart resize, let's assume\n // scrollbar appeared. So we resize again with the scrollbar visible -\n // effectively making chart smaller and the scrollbar hidden again.\n // Because we are inside `throttled`, and currently `ticking`, scroll\n // events are ignored during this whole 2 resize process.\n // If we assumed wrong and something else happened, we are resizing\n // twice in a frame (potential performance issue)\n listener();\n }\n }, window);\n\n // @ts-ignore until https://github.com/microsoft/TypeScript/issues/37861 implemented\n const observer = new ResizeObserver(entries => {\n const entry = entries[0];\n const width = entry.contentRect.width;\n const height = entry.contentRect.height;\n // When its container's display is set to 'none' the callback will be called with a\n // size of (0, 0), which will cause the chart to lose its original height, so skip\n // resizing in such case.\n if (width === 0 && height === 0) {\n return;\n }\n resize(width, height);\n });\n observer.observe(container);\n listenDevicePixelRatioChanges(chart, resize);\n\n return observer;\n}\n\nfunction releaseObserver(chart, type, observer) {\n if (observer) {\n observer.disconnect();\n }\n if (type === 'resize') {\n unlistenDevicePixelRatioChanges(chart);\n }\n}\n\nfunction createProxyAndListen(chart, type, listener) {\n const canvas = chart.canvas;\n const proxy = throttled((event) => {\n // This case can occur if the chart is destroyed while waiting\n // for the throttled function to occur. We prevent crashes by checking\n // for a destroyed chart\n if (chart.ctx !== null) {\n listener(fromNativeEvent(event, chart));\n }\n }, chart);\n\n addListener(canvas, type, proxy);\n\n return proxy;\n}\n\n/**\n * Platform class for charts that can access the DOM and global window/document properties\n * @extends BasePlatform\n */\nexport default class DomPlatform extends BasePlatform {\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t * @param {number} [aspectRatio]\n\t * @return {CanvasRenderingContext2D|null}\n\t */\n acquireContext(canvas, aspectRatio) {\n // To prevent canvas fingerprinting, some add-ons undefine the getContext\n // method, for example: https://github.com/kkapsner/CanvasBlocker\n // https://github.com/chartjs/Chart.js/issues/2807\n const context = canvas && canvas.getContext && canvas.getContext('2d');\n\n // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the canvas is\n // inside an iframe or when running in a protected environment. We could guess the\n // types from their toString() value but let's keep things flexible and assume it's\n // a sufficient condition if the canvas has a context2D which has canvas as `canvas`.\n // https://github.com/chartjs/Chart.js/issues/3887\n // https://github.com/chartjs/Chart.js/issues/4102\n // https://github.com/chartjs/Chart.js/issues/4152\n if (context && context.canvas === canvas) {\n // Load platform resources on first chart creation, to make it possible to\n // import the library before setting platform options.\n initCanvas(canvas, aspectRatio);\n return context;\n }\n\n return null;\n }\n\n /**\n\t * @param {CanvasRenderingContext2D} context\n\t */\n releaseContext(context) {\n const canvas = context.canvas;\n if (!canvas[EXPANDO_KEY]) {\n return false;\n }\n\n const initial = canvas[EXPANDO_KEY].initial;\n ['height', 'width'].forEach((prop) => {\n const value = initial[prop];\n if (isNullOrUndef(value)) {\n canvas.removeAttribute(prop);\n } else {\n canvas.setAttribute(prop, value);\n }\n });\n\n const style = initial.style || {};\n Object.keys(style).forEach((key) => {\n canvas.style[key] = style[key];\n });\n\n // The canvas render size might have been changed (and thus the state stack discarded),\n // we can't use save() and restore() to restore the initial state. So make sure that at\n // least the canvas context is reset to the default state by setting the canvas width.\n // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html\n // eslint-disable-next-line no-self-assign\n canvas.width = canvas.width;\n\n delete canvas[EXPANDO_KEY];\n return true;\n }\n\n /**\n\t *\n\t * @param {Chart} chart\n\t * @param {string} type\n\t * @param {function} listener\n\t */\n addEventListener(chart, type, listener) {\n // Can have only one listener per type, so make sure previous is removed\n this.removeEventListener(chart, type);\n\n const proxies = chart.$proxies || (chart.$proxies = {});\n const handlers = {\n attach: createAttachObserver,\n detach: createDetachObserver,\n resize: createResizeObserver\n };\n const handler = handlers[type] || createProxyAndListen;\n proxies[type] = handler(chart, type, listener);\n }\n\n\n /**\n\t * @param {Chart} chart\n\t * @param {string} type\n\t */\n removeEventListener(chart, type) {\n const proxies = chart.$proxies || (chart.$proxies = {});\n const proxy = proxies[type];\n\n if (!proxy) {\n return;\n }\n\n const handlers = {\n attach: releaseObserver,\n detach: releaseObserver,\n resize: releaseObserver\n };\n const handler = handlers[type] || removeListener;\n handler(chart, type, proxy);\n proxies[type] = undefined;\n }\n\n getDevicePixelRatio() {\n return window.devicePixelRatio;\n }\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t * @param {number} [width] - content width of parent element\n\t * @param {number} [height] - content height of parent element\n\t * @param {number} [aspectRatio] - aspect ratio to maintain\n\t */\n getMaximumSize(canvas, width, height, aspectRatio) {\n return getMaximumSize(canvas, width, height, aspectRatio);\n }\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t */\n isAttached(canvas) {\n const container = canvas && _getParentNode(canvas);\n return !!(container && container.isConnected);\n }\n}\n","import {_isDomSupported} from '../helpers/index.js';\nimport BasePlatform from './platform.base.js';\nimport BasicPlatform from './platform.basic.js';\nimport DomPlatform from './platform.dom.js';\n\nexport function _detectPlatform(canvas) {\n if (!_isDomSupported() || (typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas)) {\n return BasicPlatform;\n }\n return DomPlatform;\n}\n\nexport {BasePlatform, BasicPlatform, DomPlatform};\n","import type {AnyObject} from '../types/basic.js';\nimport type {Point} from '../types/geometric.js';\nimport type {Animation} from '../types/animation.js';\nimport {isNumber} from '../helpers/helpers.math.js';\n\nexport default class Element {\n\n static defaults = {};\n static defaultRoutes = undefined;\n\n x: number;\n y: number;\n active = false;\n options: O;\n $animations: Record;\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 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 {each, callback as callCallback, uid, valueOrDefault, _elementsEqual, isNullOrUndef, setsEqual, defined, isFunction, _isClickEvent} from '../helpers/helpers.core.js';\nimport {clearCanvas, clipArea, createContext, unclipArea, _isPointInArea, _isDomSupported, retinaScale, getDatasetClipArea} 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\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 // Unset pending resize request now to avoid possible recursion within _resize\n this._resizeBeforeDraw = null;\n this._resize(width, height);\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 args = {\n meta,\n index: meta.index,\n cancelable: true\n };\n // @ts-expect-error\n const clip = getDatasetClipArea(this, meta);\n\n if (this.notifyPlugins('beforeDatasetDraw', args) === false) {\n return;\n }\n\n if (clip) {\n clipArea(ctx, clip);\n }\n\n meta.controller.draw();\n\n if (clip) {\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 event 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, _angleDiff, _normalizeAngle, _isBetween, _limitValue} from '../helpers/helpers.math.js';\nimport {_readValueToProps} from '../helpers/helpers.options.js';\nimport type {ArcOptions, Point} from '../types/index.js';\n\nfunction clipSelf(ctx: CanvasRenderingContext2D, element: ArcElement, endAngle: number) {\n const {startAngle, x, y, outerRadius, innerRadius, options} = element;\n const {borderWidth, borderJoinStyle} = options;\n const outerAngleClip = Math.min(borderWidth / outerRadius, _normalizeAngle(startAngle - endAngle));\n ctx.beginPath();\n ctx.arc(x, y, outerRadius - borderWidth / 2, startAngle + outerAngleClip / 2, endAngle - outerAngleClip / 2);\n\n if (innerRadius > 0) {\n const innerAngleClip = Math.min(borderWidth / innerRadius, _normalizeAngle(startAngle - endAngle));\n ctx.arc(x, y, innerRadius + borderWidth / 2, endAngle - innerAngleClip / 2, startAngle + innerAngleClip / 2, true);\n } else {\n const clipWidth = Math.min(borderWidth / 2, outerRadius * _normalizeAngle(startAngle - endAngle));\n\n if (borderJoinStyle === 'round') {\n ctx.arc(x, y, clipWidth, endAngle - PI / 2, startAngle + PI / 2, true);\n } else if (borderJoinStyle === 'bevel') {\n const r = 2 * clipWidth * clipWidth;\n const endX = -r * Math.cos(endAngle + PI / 2) + x;\n const endY = -r * Math.sin(endAngle + PI / 2) + y;\n const startX = r * Math.cos(startAngle + PI / 2) + x;\n const startY = r * Math.sin(startAngle + PI / 2) + y;\n ctx.lineTo(endX, endY);\n ctx.lineTo(startX, startY);\n }\n }\n ctx.closePath();\n\n ctx.moveTo(0, 0);\n ctx.rect(0, 0, ctx.canvas.width, ctx.canvas.height);\n\n ctx.clip('evenodd');\n}\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, 𝜃) 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, borderRadius} = 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 (options.selfJoin && endAngle - startAngle >= PI && borderRadius === 0 && borderJoinStyle !== 'miter') {\n clipSelf(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 selfJoin: false,\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 nonZeroBetween = _angleBetween(angle, startAngle, endAngle) && startAngle !== endAngle;\n const betweenAngles = _circumference >= TAU || nonZeroBetween;\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, defaults} 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\nfunction containsDefaultColorsDefenitions() {\n return defaults.borderColor !== 'rgba(0,0,0,0.1)' || defaults.backgroundColor !== 'rgba(0,0,0,0.1)';\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 const containsColorDefenition = (\n containsColorsDefinitions(datasets) ||\n containsColorsDefinition(chartOptions) ||\n (elements && containsColorsDefinitions(elements)) ||\n containsDefaultColorsDefenitions());\n\n if (!options.forceOverride && containsColorDefenition) {\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 a segment -> need to add another point before this,\n postponed.unshift(point);\n } else {\n points.push(point);\n if (!last) {\n // In the middle of a 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, getDatasetClipArea} 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 {chart, index, 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 const meta = chart.getDatasetMeta(index);\n const clip = getDatasetClipArea(chart, meta);\n if (target && line.points.length) {\n clipArea(ctx, area);\n doFill(ctx, {line, target, above, below, area, scale, axis, clip});\n unclipArea(ctx);\n }\n}\n\nfunction doFill(ctx, cfg) {\n const {line, target, above, below, area, scale, clip} = cfg;\n const property = line._loop ? 'angle' : cfg.axis;\n\n ctx.save();\n\n let fillColor = below;\n if (below !== above) {\n if (property === 'x') {\n clipVertical(ctx, target, area.top);\n fill(ctx, {line, target, color: above, scale, property, clip});\n ctx.restore();\n ctx.save();\n clipVertical(ctx, target, area.bottom);\n } else if (property === 'y') {\n clipHorizontal(ctx, target, area.left);\n fill(ctx, {line, target, color: below, scale, property, clip});\n ctx.restore();\n ctx.save();\n clipHorizontal(ctx, target, area.right);\n fillColor = above;\n }\n }\n fill(ctx, {line, target, color: fillColor, scale, property, clip});\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 clipHorizontal(ctx, target, clipX) {\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(clipX, firstPoint.y);\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(clipX, lastPoint.y);\n }\n }\n\n ctx.lineTo(clipX, target.first().y);\n ctx.closePath();\n ctx.clip();\n}\n\nfunction fill(ctx, cfg) {\n const {line, target, property, color, scale, clip} = 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, clip, 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, clip, bounds) {\n const chartArea = scale.chart.chartArea;\n const {property, start, end} = bounds || {};\n\n if (property === 'x' || property === 'y') {\n let left, top, right, bottom;\n\n if (property === 'x') {\n left = start;\n top = chartArea.top;\n right = end;\n bottom = chartArea.bottom;\n } else {\n left = chartArea.left;\n top = start;\n right = chartArea.right;\n bottom = end;\n }\n\n ctx.beginPath();\n\n if (clip) {\n left = Math.max(left, clip.left);\n right = Math.min(right, clip.right);\n top = Math.max(top, clip.top);\n bottom = Math.min(bottom, clip.bottom);\n }\n\n ctx.rect(left, top, right - left, 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 // No visible items where found, return false so we don't have to divide by 0 which reduces in NaN\n if (count === 0 || xSet.size === 0) {\n return false;\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.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, 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"],"names":["Animator","constructor","_request","_charts","Map","_running","_lastDate","undefined","_notify","chart","anims","date","type","callbacks","listeners","numSteps","duration","forEach","fn","initial","currentStep","Math","min","start","_refresh","requestAnimFrame","call","window","_update","Date","now","remaining","running","items","length","i","draw","item","_active","_total","tick","pop","_getAnims","charts","get","complete","progress","set","listen","event","cb","push","add","has","reduce","acc","cur","max","_duration","stop","cancel","remove","delete","transparent","interpolators","boolean","from","to","factor","color","c0","helpersColor","c1","valid","mix","hexString","number","Animation","cfg","target","prop","currentValue","resolve","_fn","_easing","effects","easing","linear","_start","floor","delay","_loop","loop","_target","_prop","_from","_to","_promises","active","update","elapsed","remain","wait","promises","Promise","res","rej","resolved","method","Animations","config","_chart","_properties","configure","isObject","animationOptions","Object","keys","defaults","animation","animatedProps","getOwnPropertyNames","key","option","isArray","properties","_animateOptions","values","newOptions","options","resolveTargetOptions","animations","_createAnimations","$shared","awaitAll","$animations","then","props","charAt","value","size","assign","animator","anim","all","scaleClip","scale","allowedOverflow","opts","reverse","end","defaultClip","xScale","yScale","x","y","top","right","bottom","left","toClip","t","r","b","l","disabled","getSortedDatasetIndices","filterVisible","metasets","_getSortedDatasetMetas","ilen","index","applyStack","stack","dsIndex","singleMode","mode","datasetIndex","otherValue","found","isFinite","sign","convertObjectDataToArray","data","meta","iScale","vScale","iAxisKey","axis","vAxisKey","adata","Array","isStacked","stacked","getStackKey","indexScale","valueScale","id","getUserBounds","minDefined","maxDefined","Number","NEGATIVE_INFINITY","POSITIVE_INFINITY","getOrCreateStack","stacks","stackKey","indexValue","subStack","getLastIndexInStack","positive","getMatchingVisibleMetas","updateStacks","controller","parsed","_cachedMeta","_stacks","iAxis","vAxis","itemStacks","_top","_bottom","visualValues","_visualValues","getFirstScaleId","scales","filter","shift","createDatasetContext","parent","createContext","dataset","createDataContext","element","dataIndex","raw","clearStacks","_parsed","isDirectUpdateMode","cloneIfNotShared","cached","shared","createStack","canStack","hidden","_stacked","DatasetController","datasetElementType","dataElementType","_ctx","ctx","_cachedDataOpts","getMeta","_type","_parsing","_data","_objectData","_sharedOptions","_drawStart","_drawCount","enableOptionSharing","supportsDecimation","$context","_syncList","initialize","linkScales","addElements","fill","isPluginEnabled","console","warn","updateIndex","getDataset","chooseId","xid","xAxisID","valueOrDefault","yid","yAxisID","rid","rAxisID","indexAxis","iid","iAxisID","vid","vAxisID","getScaleForId","rScale","datasets","getDatasetMeta","scaleID","_getOtherScale","reset","_destroy","unlistenArrayEvents","_dataCheck","isExtensible","listenArrayEvents","buildOrUpdateElements","resetNewElements","stackChanged","oldStacked","_resyncElements","scopeKeys","datasetScopeKeys","scopes","getOptionScopes","createResolver","getContext","parsing","parse","count","sorted","_sorted","prev","parseArrayData","parseObjectData","parsePrimitiveData","isNotInOrderComparedToPrev","labels","getLabels","singleScale","xAxisKey","yAxisKey","resolveObjectKey","getParsed","getDataElement","updateRangeFromParsed","range","parsedValue","NaN","getMinMax","otherScale","otherMin","otherMax","_skip","getAllParsedValues","getMaxOverflow","getLabelAndValue","label","getLabelForValue","_clip","clip","elements","area","chartArea","drawActiveElementsOnTop","getStyle","resolveDatasetElementOptions","resolveDataElementOptions","context","_resolveElementOptions","elementType","cache","cacheKey","sharing","defined","datasetElementScopeKeys","prefixes","names","resolveNamedOptions","freeze","_resolveAnimations","transition","datasetAnimationScopeKeys","_cacheable","getSharedOptions","includeOptions","sharedOptions","_animationsDisabled","_getSharedOptions","firstOpts","previouslySharedOptions","updateSharedOptions","updateElement","_setStyle","removeHoverStyle","setHoverStyle","_removeDatasetHoverStyle","_setDatasetHoverStyle","arg1","arg2","numMeta","numData","_insertElements","_removeElements","move","arr","updateElements","removed","splice","_sync","args","_dataChanges","_onDataPush","arguments","_onDataPop","_onDataShift","_onDataSplice","newCount","_onDataUnshift","getAllScaleValues","_cache","$bar","visibleMetas","concat","_arrayUnique","sort","a","computeMinSampleSize","_length","curr","updateMinAndPrev","abs","getPixelForValue","ticks","getPixelForTick","computeFitCategoryTraits","ruler","stackCount","thickness","barThickness","ratio","isNullOrUndef","categoryPercentage","barPercentage","chunk","pixels","computeFlexCategoryTraits","next","percent","parseFloatBar","entry","startValue","endValue","barStart","barEnd","_custom","parseValue","parseArrayOrPrimitive","isFloatBar","custom","barSign","actualBase","isHorizontal","borderProps","horizontal","base","setBorderSkipped","edge","borderSkipped","enableBorderRadius","parseEdge","swap","startEnd","orig","v1","v2","v","setInflateAmount","inflateAmount","BarController","grouped","numbers","overrides","_index_","offset","grid","_value_","beginAtZero","obj","bars","getBasePixel","_getRuler","vpixels","head","_calculateBarValuePixels","ipixels","_calculateBarIndexPixels","center","height","width","_getStacks","last","currentParsed","iScaleValue","skipNull","find","val","isNaN","indexOf","_getStackCount","_getAxisCount","_getAxis","getFirstScaleIdForIndexAxis","indexScaleId","firstScaleAxisId","_getStackIndex","name","_startPixel","_endPixel","baseValue","minBarLength","floating","getDataVisibility","startPixel","getPixelForDecimal","endPixel","getValueForPixel","halfGrid","getLineWidthForValue","maxBarThickness","Infinity","axisCount","axisID","axisNumber","stackIndex","rects","BubbleController","radius","points","point","iPixel","vPixel","skip","getRatioAndOffset","rotation","circumference","cutout","ratioX","ratioY","offsetX","offsetY","TAU","startAngle","endAngle","startX","cos","startY","sin","endX","endY","calcMax","angle","_angleBetween","calcMin","maxX","maxY","HALF_PI","minX","PI","minY","DoughnutController","animateRotate","animateScale","spacing","descriptors","_scriptable","_indexable","startsWith","aspectRatio","plugins","legend","generateLabels","pointStyle","map","style","text","fillStyle","backgroundColor","strokeStyle","borderColor","fontColor","lineWidth","borderWidth","onClick","e","legendItem","toggleDataVisibility","innerRadius","outerRadius","getter","_getRotation","toRadians","_getCircumference","_getRotationExtents","isDatasetVisible","arcs","getMaxBorderWidth","getMaxOffset","maxSize","toPercentage","chartWeight","_getRingWeight","maxWidth","maxHeight","maxRadius","toDimension","radiusLength","_getVisibleDatasetWeightTotal","total","calculateTotal","_getRingWeightOffset","_circumference","calculateCircumference","animationOpts","centerX","centerY","arc","metaData","formatNumber","locale","borderAlign","hoverBorderWidth","hoverOffset","ringWeightOffset","weight","LineController","showLine","spanGaps","line","_dataset","animationsDisabled","_getStartAndCountOfVisiblePoints","_scaleRangesChanged","_datasetIndex","_decimated","segment","animated","maxGapLength","isNumber","directUpdate","pointsCount","prevParsed","nullData","border","firstPoint","lastPoint","updateControlPoints","PolarAreaController","angleLines","display","circular","pointLabels","_parseObjectDataRadialScale","bind","_updateRadius","minSize","cutoutPercentage","getVisibleDatasetCount","xCenter","yCenter","datasetStartAngle","getIndexAngle","defaultAngle","countVisibleElements","_computeAngle","getDistanceFromCenterForValue","PieController","RadarController","_fullLoop","pointPosition","getPointPositionForValue","ScatterController","interaction","registry","getElement","abstract","Error","DateAdapterBase","override","members","prototype","init","formats","format","diff","startOf","endOf","_date","binarySearch","metaset","intersect","lookupMethod","_reversePixels","_rlookupByKey","_lookupByKey","result","distanceToDefinedLo","slice","lo","findIndex","distanceToDefinedHi","hi","el","getRange","evaluateInteractionItems","position","handler","getSortedVisibleDatasetMetas","j","getDistanceMetricForAxis","useX","useY","pt1","pt2","deltaX","deltaY","sqrt","pow","getIntersectItems","useFinalPosition","includeInvisible","isPointInArea","evaluationFunc","_isPointInArea","inRange","getNearestRadialItems","getProps","getAngleFromPoint","getNearestCartesianItems","distanceMetric","minDistance","getCenterPoint","pointInArea","distance","getNearestItems","getAxisItems","rangeMethod","intersectsItem","modes","getRelativePosition","nearest","STATIC_POSITIONS","filterByPosition","array","pos","filterDynamicPositionByAxis","box","sortByWeight","v0","wrapBoxes","boxes","layoutBoxes","stackWeight","buildStacks","layouts","wrap","includes","_stack","placed","setLayoutDims","params","vBoxMaxWidth","hBoxMaxHeight","layout","fullSize","availableWidth","availableHeight","buildLayoutBoxes","centerHorizontal","centerVertical","leftAndTop","rightAndBottom","vertical","getCombinedMax","maxPadding","updateMaxPadding","boxPadding","updateDims","getPadding","newWidth","outerWidth","newHeight","outerHeight","widthChanged","w","heightChanged","h","same","other","handleMaxPadding","updatePos","change","getMargins","marginForPositions","positions","margin","fitBoxes","refitBoxes","refit","changed","setBoxDims","placeBoxes","userPadding","padding","addBox","_layers","z","removeBox","layoutItem","minPadding","toPadding","verticalBoxes","horizontalBoxes","each","beforeLayout","visibleVerticalBoxCount","BasePlatform","acquireContext","canvas","releaseContext","addEventListener","listener","removeEventListener","getDevicePixelRatio","getMaximumSize","isAttached","updateConfig","BasicPlatform","EXPANDO_KEY","EVENT_TYPES","touchstart","touchmove","touchend","pointerenter","pointerdown","pointermove","pointerup","pointerleave","pointerout","isNullOrEmpty","initCanvas","renderHeight","getAttribute","renderWidth","boxSizing","displayWidth","readUsedSize","displayHeight","eventListenerOptions","supportsEventListenerOptions","passive","addListener","node","removeListener","fromNativeEvent","native","nodeListContains","nodeList","contains","createAttachObserver","observer","MutationObserver","entries","trigger","addedNodes","removedNodes","observe","document","childList","subtree","createDetachObserver","drpListeningCharts","oldDevicePixelRatio","onWindowResize","dpr","devicePixelRatio","resize","currentDevicePixelRatio","listenDevicePixelRatioChanges","unlistenDevicePixelRatioChanges","createResizeObserver","container","_getParentNode","throttled","clientWidth","ResizeObserver","contentRect","releaseObserver","disconnect","createProxyAndListen","proxy","DomPlatform","removeAttribute","setAttribute","proxies","$proxies","handlers","attach","detach","isConnected","_detectPlatform","_isDomSupported","OffscreenCanvas","Element","defaultRoutes","tooltipPosition","hasValue","final","ret","autoSkip","tickOpts","determinedMaxTicks","determineMaxTicks","ticksLimit","maxTicksLimit","majorIndices","major","enabled","getMajorIndices","numMajorIndices","first","newTicks","skipMajors","calculateSpacing","avgMajorSpacing","round","tickLength","_tickSize","maxScale","maxChart","_maxLength","evenMajorSpacing","getEvenSpacing","factors","_factorize","ceil","majorStart","majorEnd","len","reverseAlign","align","offsetFromEdge","getTicksLimit","ticksLength","sample","numItems","increment","getPixelForGridLine","offsetGridLines","validIndex","epsilon","lineValue","garbageCollect","caches","gc","gcLen","getTickMarkLength","drawTicks","getTitleHeight","fallback","font","toFont","lines","lineHeight","createScaleContext","createTickContext","titleAlign","_toLeftRightCenter","titleArgs","titleX","titleY","_alignStartEnd","positionAxisID","Scale","_margins","paddingTop","paddingBottom","paddingLeft","paddingRight","labelRotation","_range","_gridLineItems","_labelItems","_labelSizes","_longestTextCache","_userMax","_userMin","_suggestedMax","_suggestedMin","_ticksLength","_borderValue","_dataLimitsCached","setContext","suggestedMin","suggestedMax","finiteOrDefault","metas","getTicks","xLabels","yLabels","getLabelItems","_computeLabelItems","beforeUpdate","margins","grace","sampleSize","beforeSetDimensions","setDimensions","afterSetDimensions","beforeDataLimits","determineDataLimits","afterDataLimits","_addGrace","beforeBuildTicks","buildTicks","afterBuildTicks","samplingEnabled","_convertTicksToLabels","beforeCalculateLabelRotation","calculateLabelRotation","afterCalculateLabelRotation","source","afterAutoSkip","beforeFit","fit","afterFit","afterUpdate","reversePixels","_alignToPixels","alignToPixels","_callHooks","notifyPlugins","beforeTickToLabelConversion","generateTickLabels","callback","afterTickToLabelConversion","numTicks","minRotation","maxRotation","tickWidth","maxLabelDiagonal","_isVisible","labelSizes","_getLabelSizes","maxLabelWidth","widest","maxLabelHeight","highest","_limitValue","title","toDegrees","asin","titleOpts","gridOpts","titleHeight","tickPadding","angleRadians","labelHeight","mirror","labelWidth","_calculatePadding","_handleMargins","isRotated","labelsBelowTicks","offsetLeft","offsetRight","isFullSize","_computeLabelSizes","widths","heights","widestLabelSize","highestLabelSize","jlen","tickFont","fontString","nestedLabel","_resolveTickFontOptions","string","_measureText","valueAt","idx","pixel","decimal","_int16Range","_alignPixel","getDecimalForPixel","getBaseValue","optionTicks","rot","autoSkipPadding","_computeGridLineItems","tl","borderOpts","axisWidth","axisHalfWidth","alignBorderValue","borderValue","alignedLineValue","tx1","ty1","tx2","ty2","x1","y1","x2","y2","limit","step","optsAtIndex","optsAtIndexBorder","lineColor","borderDash","dash","borderDashOffset","dashOffset","tickColor","tickBorderDash","tickBorderDashOffset","crossAlign","tickAndPadding","hTickAndPadding","textAlign","lineCount","textOffset","textBaseline","_getXAxisLabelAlignment","_getYAxisLabelAlignment","labelOffset","halfCount","strokeColor","textStrokeColor","strokeWidth","textStrokeWidth","tickTextAlign","showLabelBackdrop","backdrop","labelPadding","backdropPadding","backdropColor","translation","_computeLabelArea","drawBackground","save","fillRect","restore","drawGrid","drawLine","p1","p2","setLineDash","lineDashOffset","beginPath","moveTo","lineTo","stroke","drawOnChartArea","drawBorder","lastLineWidth","drawLabels","clipArea","renderTextOptions","renderText","unclipArea","drawTitle","tz","gz","bz","_maxDigits","fontSize","TypedRegistry","scope","create","isForType","isPrototypeOf","register","proto","getPrototypeOf","parentScope","isIChartComponent","registerDefaults","unregister","itemDefaults","merge","routeDefaults","describe","routes","property","propertyParts","split","sourceName","sourceScope","join","parts","targetName","targetScope","route","Registry","controllers","_typedRegistries","_each","addControllers","addPlugins","addScales","getController","_get","getPlugin","getScale","removeControllers","removeElements","removePlugins","removeScales","typedRegistry","arg","reg","_getRegistryForType","_exec","itemReg","component","camelMethod","_capitalize","PluginService","_init","notify","hook","_createDescriptors","_descriptors","descriptor","plugin","callCallback","cancelable","invalidate","_oldCache","_notifyStateChanges","allPlugins","createDescriptors","previousDescriptors","some","localIds","local","getOpts","pluginOpts","pluginScopeKeys","scriptable","indexable","allKeys","getIndexAxis","datasetDefaults","datasetOptions","getAxisFromDefaultScaleID","getDefaultScaleIDFromAxis","idMatchesAxis","axisFromPosition","determineAxis","scaleOptions","toLowerCase","getAxisFromDataset","retrieveAxisFromDatasets","boundDs","d","mergeScaleConfig","chartDefaults","configScales","chartIndexAxis","scaleConf","error","_proxy","defaultId","defaultScaleOptions","mergeIf","defaultID","initOptions","initData","initConfig","keyCache","keysCached","Set","cachedKeys","generate","addIfFound","Config","_config","_scopeCache","_resolverCache","platform","clearCache","clear","datasetType","additionalOptionScopes","_cachedScopes","mainScope","resetCache","keyLists","chartOptionScopes","resolver","subPrefixes","getResolver","needContext","isFunction","subResolver","_attachContext","descriptorDefaults","resolverCache","_createResolver","p","hasFunction","isScriptable","isIndexable","KNOWN_POSITIONS","positionIsHorizontal","compare2Level","l1","l2","onAnimationsComplete","onComplete","onAnimationProgress","onProgress","getCanvas","getElementById","instances","getChart","c","moveNumericKeys","intKey","determineLastEvent","lastEvent","inChartArea","isClick","Chart","version","invalidatePlugins","userConfig","initialCanvas","existingChart","uid","_options","_aspectRatio","_metasets","_lastEvent","_listeners","_responsiveListeners","_sortedMetasets","_plugins","_hiddenIndices","attached","_doResize","debounce","resizeDelay","_initialize","maintainAspectRatio","responsive","retinaScale","bindEvents","clearCanvas","_resize","_resizeBeforeDraw","newSize","newRatio","onResize","render","ensureScalesHaveIDs","scalesOptions","axisOptions","buildOrUpdateScales","scaleOpts","updated","isRadial","dposition","dtype","scaleType","scaleClass","hasUpdated","_updateMetasets","_destroyDatasetMeta","_removeUnreferencedMetasets","buildOrUpdateControllers","newControllers","order","visible","ControllerClass","_resetElements","animsDisabled","_updateScales","_checkEventBindings","_updateHiddenIndices","_minPadding","autoPadding","_updateLayout","_updateDatasets","_eventHandler","_updateHoverStyles","existingEvents","newEvents","events","setsEqual","unbindEvents","changes","_getUniformDataChanges","datasetCount","makeSet","changeSet","noArea","_idx","_updateDataset","layers","_drawDatasets","_drawDataset","getDatasetClipArea","getElementsAtEventForMode","Interaction","setDatasetVisibility","_updateVisibility","hide","show","_stop","destroy","toBase64Image","toDataURL","bindUserEvents","bindResponsiveEvents","_add","_remove","detached","updateHoverStyle","prefix","getActiveElements","setActiveElements","activeElements","lastActive","_elementsEqual","pluginId","replay","hoverOptions","hover","deactivated","activated","eventFilter","_handleEvent","_getActiveElements","_isClickEvent","onHover","clipSelf","borderJoinStyle","outerAngleClip","_normalizeAngle","innerAngleClip","clipWidth","closePath","rect","clipArc","pixelMargin","angleMargin","toRadiusCorners","_readValueToProps","parseBorderRadius","angleDelta","o","borderRadius","halfThickness","innerLimit","computeOuterLimit","outerArcLimit","outerStart","outerEnd","innerStart","innerEnd","rThetaToXY","theta","pathArc","innerR","spacingOffset","alpha","noSpacingInnerRadius","noSpacingOuterRadius","avNogSpacingRadius","adjustedAngle","beta","angleOffset","outerStartAdjustedRadius","outerEndAdjustedRadius","outerStartAdjustedAngle","outerEndAdjustedAngle","innerStartAdjustedRadius","innerEndAdjustedRadius","innerStartAdjustedAngle","innerEndAdjustedAngle","outerMidAdjustedAngle","pCenter","p4","innerMidAdjustedAngle","p8","outerStartX","outerStartY","outerEndX","outerEndY","drawArc","fullCircles","inner","lineJoin","selfJoin","ArcElement","chartX","chartY","rAdjust","nonZeroBetween","betweenAngles","withinRadius","_isBetween","halfAngle","halfRadius","translate","fix","radiusOffset","setStyle","lineCap","borderCapStyle","previous","getLineMethod","stepped","_steppedLineTo","tension","cubicInterpolationMode","_bezierCurveTo","pathVars","paramsStart","paramsEnd","segmentStart","segmentEnd","outside","pathSegment","lineMethod","fastPathSegment","avgX","countX","prevX","lastY","pointIndex","drawX","truncX","_getSegmentMethod","useFastPath","_getInterpolationMethod","_steppedInterpolation","_bezierInterpolation","_pointInLine","strokePathWithCache","path","_path","Path2D","strokePathDirect","segments","segmentMethod","usePath2D","LineElement","capBezierPoints","_points","_segments","_pointsUpdated","_updateBezierControlPoints","_computeSegments","interpolate","_boundSegments","_interpolate","interpolated","hitRadius","PointElement","hoverRadius","mouseX","mouseY","inXRange","inYRange","drawPoint","getBarBounds","bar","half","skipOrLimit","parseBorderWidth","maxW","maxH","toTRBL","toTRBLCorners","maxR","enableBorder","topLeft","topRight","bottomLeft","bottomRight","boundingRects","bounds","outer","skipX","skipY","skipBoth","hasRadius","addNormalRectPath","inflateRect","amount","refRect","BarElement","addRectPath","addRoundedRectPath","BORDER_COLORS","BACKGROUND_COLORS","replace","getBorderColor","getBackgroundColor","colorizeDefaultDataset","colorizeDoughnutDataset","colorizePolarAreaDataset","getColorizer","containsColorsDefinitions","k","containsColorsDefinition","containsDefaultColorsDefenitions","forceOverride","_args","chartOptions","containsColorDefenition","colorizer","lttbDecimation","samples","decimated","bucketWidth","sampledIndex","endIndex","maxAreaPoint","maxArea","nextA","avgY","avgRangeStart","avgRangeEnd","avgRangeLength","rangeOffs","rangeTo","pointAx","pointAy","minMaxDecimation","minIndex","maxIndex","startIndex","xMin","xMax","dx","lastIndex","intermediateIndex1","intermediateIndex2","cleanDecimatedDataset","defineProperty","configurable","enumerable","writable","cleanDecimatedData","getStartAndCountOfVisiblePointsSimplified","pointCount","algorithm","beforeElementsUpdate","xAxis","threshold","tpoints","_findSegmentEnd","_getBounds","targetSegments","tgt","subBounds","fillSources","_boundSegment","fillSource","_getEdge","_pointsFromSegments","boundary","linePoints","_createBoundaryLine","_shouldApplyFill","_resolveTarget","sources","propagate","visited","_decodeFill","parseFillOption","parseFloat","decodeTargetIndex","firstCh","_getTargetPixel","_getTargetValue","fillOption","_buildStackLine","sourcePoints","linesBelow","getLinesBelow","addPointsBelow","below","unshift","sourcePoint","postponed","findPoint","pointValue","firstValue","lastValue","simpleArc","_getTarget","getLineByIndex","computeBoundary","computeCircularBoundary","computeLinearBoundary","_drawfill","lineOpts","above","doFill","fillColor","clipVertical","clipHorizontal","clipY","lineLoop","clipX","src","notShape","clipBounds","interpolatedLineTo","targetLoop","interpolatedPoint","afterDatasetsUpdate","$filler","beforeDraw","drawTime","beforeDatasetsDraw","beforeDatasetDraw","getBoxSize","labelOpts","boxHeight","boxWidth","usePointStyle","pointStyleWidth","itemHeight","itemsEqual","Legend","_added","legendHitBoxes","_hoveredItem","doughnutMode","legendItems","columnSizes","lineWidths","buildLabels","labelFont","_computeTitleHeight","_fitRows","_fitCols","hitboxes","totalHeight","row","itemWidth","measureText","_itemHeight","heightLimit","totalWidth","currentColWidth","currentColHeight","col","calculateItemSize","adjustHitBoxes","rtl","rtlHelper","getRtlAdapter","hitbox","leftForLtr","_draw","defaultColor","halfFontSize","cursor","drawLegendBox","lineDash","drawOptions","SQRT2","xPlus","drawPointLegend","yBoxTop","xBoxLeft","fillText","strikethrough","overrideTextDirection","textDirection","textWidth","setWidth","realX","_textX","fontLineHeight","calculateLegendItemHeight","restoreTextDirection","titleFont","titlePadding","topPaddingPlusHalfFontSize","_getLegendItemAt","hitBox","lh","handleEvent","isListened","hoveredItem","sameItem","onLeave","calculateItemWidth","calculateItemHeight","legendItemText","_element","afterEvent","ci","useBorderRadius","Title","_padding","textSize","_drawArgs","fontOpts","createTitle","titleBlock","WeakMap","positioners","average","xSet","xAverage","eventPosition","nearestElement","distanceBetweenPoints","tp","pushOrConcat","toPush","apply","splitNewlines","str","String","createTooltipItem","formattedValue","getTooltipSize","tooltip","body","footer","bodyFont","footerFont","titleLineCount","footerLineCount","bodyLineItemCount","combinedBodyLength","bodyItem","before","after","beforeBody","afterBody","titleSpacing","titleMarginBottom","bodyLineHeight","displayColors","bodySpacing","footerMarginTop","footerSpacing","widthPadding","maxLineWidth","determineYAlign","doesNotFitWithAlign","xAlign","caret","caretSize","caretPadding","determineXAlign","yAlign","chartWidth","determineAlignment","alignX","alignY","paddingAndSize","getBackgroundPoint","alignment","cornerRadius","getAlignedX","getBeforeAfterBodyLines","createTooltipContext","tooltipItems","overrideCallbacks","defaultCallbacks","beforeTitle","noop","labelCount","afterTitle","beforeLabel","tooltipItem","labelColor","labelTextColor","bodyColor","labelPointStyle","afterLabel","beforeFooter","afterFooter","invokeCallbackWithFallback","Tooltip","opacity","_eventPosition","_size","_cachedAnimations","_tooltipItems","dataPoints","caretX","caretY","labelColors","labelPointStyles","labelTextColors","getTitle","getBeforeBody","getBody","bodyItems","scoped","getAfterBody","getFooter","_createItems","itemSort","positionAndSize","backgroundPoint","external","drawCaret","tooltipPoint","caretPosition","getCaretPosition","x3","y3","ptX","ptY","pt","titleColor","_drawColorBox","colorX","rtlColorX","yOffSet","colorY","multiKeyBackground","outerX","innerX","strokeRect","drawBody","bodyAlign","xLinePadding","fillLineOfText","bodyAlignForCalculation","textColor","drawFooter","footerAlign","footerColor","tooltipSize","quadraticCurveTo","_updateAnimationTarget","animX","animY","_willRender","hasTooltipContent","globalAlpha","positionChanged","_positionChanged","_ignoreReplayEvents","afterInit","afterDraw","_fallback","addIfString","addedLabels","findOrAddLabel","lastIndexOf","_getLabelForValue","CategoryScale","_startValue","_valueRange","_addedLabels","added","generateTicks","generationOptions","dataRange","MIN_SPACING","precision","maxTicks","maxDigits","includeBounds","unit","maxSpaces","rmin","rmax","countDefined","minSpacing","niceNum","niceMin","niceMax","numSpaces","almostWhole","almostEquals","decimalPlaces","_decimalPlaces","relativeLabelSize","tickValue","rad","LinearScaleBase","_endValue","handleTickRangeOptions","setMin","setMax","minSign","maxSign","getTickLimit","stepSize","computeTickLimit","numericGeneratorOptions","_setMinAndMaxByKey","LinearScale","Ticks","formatters","numeric","log10Floor","log10","changeExponent","m","isMajor","tickVal","steps","rangeExp","rangeStep","startExp","minExp","exp","significand","lastTick","LogarithmicScale","logarithmic","_zero","getTickBackdropHeight","measureLabelSize","_longestText","determineLimits","fitWithPointLabels","limits","valueCount","_pointLabels","pointLabelOpts","additionalAngle","centerPointLabels","getPointLabelContext","getPointPosition","drawingArea","plFont","hLimits","vLimits","updateLimits","setCenterPoint","_pointLabelItems","buildPointLabelItems","createPointLabelItem","itemOpts","outerDistance","extra","pointLabelPosition","yForAngle","getTextAlignForAngle","leftForTextAlign","isNotOverlapped","apexesInArea","drawPointLabelBox","backdropLeft","backdropTop","backdropWidth","backdropHeight","drawPointLabels","pathRadiusLine","drawRadiusLine","gridLineOpts","createPointLabelContext","RadialLinearScale","animate","leftMovement","rightMovement","topMovement","bottomMovement","angleMultiplier","scalingFactor","getValueForDistanceFromCenter","scaledDistance","pointLabel","distanceFromCenter","getBasePosition","getPointLabelPosition","rotate","INTERVALS","millisecond","common","second","minute","hour","day","week","month","quarter","year","UNITS","sorter","input","adapter","_adapter","parser","isoWeekday","_parseOpts","determineUnitForAutoTicks","minUnit","capacity","interval","MAX_SAFE_INTEGER","determineUnitForFormatting","determineMajorUnit","addTick","time","timestamps","_lookup","timestamp","setMajorTicks","majorUnit","ticksFromTimestamps","TimeScale","adapters","displayFormats","_unit","_majorUnit","_offsets","_normalized","normalized","_applyBounds","_getLabelBounds","getLabelTimestamps","timeOpts","_generate","_filterBetween","_getLabelCapacity","initOffsets","offsetAfterAutoskip","getDecimalForValue","minor","weekday","hasWeekday","getDataTimestamps","tooltipFormat","datetime","fmt","_tickFormatFunction","formatter","minorFormat","majorFormat","offsets","_getLabelSize","ticksOpts","tickLabelWidth","cosRotation","sinRotation","tickFontSize","exampleTime","exampleLabel","normalize","table","prevSource","nextSource","prevTarget","nextTarget","span","TimeSeriesScale","_table","_minPos","_tableRange","_getTimestampsForTable","buildLookupTable","registerables"],"mappings":";;;;;;;;;;;AAWO,MAAMA,QAAAA,CAAAA;IACXC,WAAc,EAAA;QACZ,IAAI,CAACC,QAAQ,GAAG,IAAI,CAAA;QACpB,IAAI,CAACC,OAAO,GAAG,IAAIC,GAAAA,EAAAA,CAAAA;QACnB,IAAI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AAK8N,MAAM,CAAClE,KAAAA,CAAAA,CAAAA,CAAAA;SACnC,MAAA;AACLguD,YAAAA,UAAAA,GAAa53D,IAAKrJ,CAAAA,MAAM,GAAGqJ,IAAAA,GAAO4J,KAAK,CAAA;SACxC;AACDguD,QAAAA,UAAAA,GAAa,IAAI,CAACjqD,MAAM,CAAClQ,GAAG,GAAGm6D,UAAAA,CAAAA;QAE/B,OAAOA,UAAAA,CAAAA;AACT,KAAA;AAMAuB,CAAAA,kBAAAA,CAAmB/7D,KAAK,EAAE;AACxB,QAAA,OAAO,CAACo4C,WAAY,CAAA,IAAI,CAACwlB,MAAM,EAAE59D,KAAS,CAAA,GAAA,IAAI,CAAC69D,OAAM,IAAK,IAAI,CAACC,WAAW,CAAA;AAC5E,KAAA;AAMA7mD,CAAAA,gBAAAA,CAAiBqjB,KAAK,EAAE;QACtB,MAAMqiC,OAAAA,GAAU,IAAI,CAACxB,QAAQ,CAAA;QAC7B,MAAM5gC,OAAAA,GAAU,IAAI,CAACG,kBAAkB,CAACJ,SAASqiC,OAAQlhE,CAAAA,MAAM,GAAGkhE,OAAAA,CAAQh8D,GAAG,CAAA;AAC7E,QAAA,OAAOy3C,WAAY,CAAA,IAAI,CAACwlB,MAAM,EAAErjC,OAAU,GAAA,IAAI,CAACujC,WAAW,GAAG,IAAI,CAACD,OAAO,EAAE,IAAI,CAAA,CAAA;AACjF,KAAA;AACF;;;;;;;;;;;;MC3JaI,aAAgB,GAAA;AAC3Bv8B,IAAAA,WAAAA;AACA90B,IAAAA,QAAAA;AACA0N,IAAAA,OAAAA;AACAhV,IAAAA,MAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/frontend/node_modules/chart.js/dist/chart.js b/frontend/node_modules/chart.js/dist/chart.js new file mode 100644 index 0000000000000000000000000000000000000000..5c2de63cfc95d5d92ba9aafad13df95fe798e665 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/chart.js @@ -0,0 +1,11590 @@ +/*! + * Chart.js v4.5.0 + * https://www.chartjs.org + * (c) 2025 Chart.js Contributors + * Released under the MIT License + */ +import { r as requestAnimFrame, a as resolve, e as effects, c as color, i as isObject, d as defaults, b as isArray, v as valueOrDefault, u as unlistenArrayEvents, l as listenArrayEvents, f as resolveObjectKey, g as isNumberFinite, h as defined, s as sign, j as createContext, k as isNullOrUndef, _ as _arrayUnique, t as toRadians, m as toPercentage, n as toDimension, T as TAU, o as formatNumber, p as _angleBetween, H as HALF_PI, P as PI, q as _getStartAndCountOfVisiblePoints, w as _scaleRangesChanged, x as isNumber, y as _parseObjectDataRadialScale, z as getRelativePosition, A as _rlookupByKey, B as _lookupByKey, C as _isPointInArea, D as getAngleFromPoint, E as toPadding, F as each, G as getMaximumSize, I as _getParentNode, J as readUsedSize, K as supportsEventListenerOptions, L as throttled, M as _isDomSupported, N as _factorize, O as finiteOrDefault, Q as callback, R as _addGrace, S as _limitValue, U as toDegrees, V as _measureText, W as _int16Range, X as _alignPixel, Y as clipArea, Z as renderText, $ as unclipArea, a0 as toFont, a1 as _toLeftRightCenter, a2 as _alignStartEnd, a3 as overrides, a4 as merge, a5 as _capitalize, a6 as descriptors, a7 as isFunction, a8 as _attachContext, a9 as _createResolver, aa as _descriptors, ab as mergeIf, ac as uid, ad as debounce, ae as retinaScale, af as clearCanvas, ag as setsEqual, ah as getDatasetClipArea, ai as _elementsEqual, aj as _isClickEvent, ak as _isBetween, al as _normalizeAngle, am as _readValueToProps, an as _updateBezierControlPoints, ao as _computeSegments, ap as _boundSegments, aq as _steppedInterpolation, ar as _bezierInterpolation, as as _pointInLine, at as _steppedLineTo, au as _bezierCurveTo, av as drawPoint, aw as addRoundedRectPath, ax as toTRBL, ay as toTRBLCorners, az as _boundSegment, aA as getRtlAdapter, aB as overrideTextDirection, aC as _textX, aD as restoreTextDirection, aE as drawPointLegend, aF as distanceBetweenPoints, aG as noop, aH as _setMinAndMaxByKey, aI as niceNum, aJ as almostWhole, aK as almostEquals, aL as _decimalPlaces, aM as Ticks, aN as log10, aO as _longestText, aP as _filterBetween, aQ as _lookup } from './chunks/helpers.dataset.js'; +import '@kurkle/color'; + +class Animator { + constructor(){ + this._request = null; + this._charts = new Map(); + this._running = false; + this._lastDate = undefined; + } + _notify(chart, anims, date, type) { + const callbacks = anims.listeners[type]; + const numSteps = anims.duration; + callbacks.forEach((fn)=>fn({ + chart, + initial: anims.initial, + numSteps, + currentStep: Math.min(date - anims.start, numSteps) + })); + } + _refresh() { + if (this._request) { + return; + } + this._running = true; + this._request = requestAnimFrame.call(window, ()=>{ + this._update(); + this._request = null; + if (this._running) { + this._refresh(); + } + }); + } + _update(date = Date.now()) { + let remaining = 0; + this._charts.forEach((anims, chart)=>{ + if (!anims.running || !anims.items.length) { + return; + } + const items = anims.items; + let i = items.length - 1; + let draw = false; + let item; + for(; i >= 0; --i){ + item = items[i]; + if (item._active) { + if (item._total > anims.duration) { + anims.duration = item._total; + } + item.tick(date); + draw = true; + } else { + items[i] = items[items.length - 1]; + items.pop(); + } + } + if (draw) { + chart.draw(); + this._notify(chart, anims, date, 'progress'); + } + if (!items.length) { + anims.running = false; + this._notify(chart, anims, date, 'complete'); + anims.initial = false; + } + remaining += items.length; + }); + this._lastDate = date; + if (remaining === 0) { + this._running = false; + } + } + _getAnims(chart) { + const charts = this._charts; + let anims = charts.get(chart); + if (!anims) { + anims = { + running: false, + initial: true, + items: [], + listeners: { + complete: [], + progress: [] + } + }; + charts.set(chart, anims); + } + return anims; + } + listen(chart, event, cb) { + this._getAnims(chart).listeners[event].push(cb); + } + add(chart, items) { + if (!items || !items.length) { + return; + } + this._getAnims(chart).items.push(...items); + } + has(chart) { + return this._getAnims(chart).items.length > 0; + } + start(chart) { + const anims = this._charts.get(chart); + if (!anims) { + return; + } + anims.running = true; + anims.start = Date.now(); + anims.duration = anims.items.reduce((acc, cur)=>Math.max(acc, cur._duration), 0); + this._refresh(); + } + running(chart) { + if (!this._running) { + return false; + } + const anims = this._charts.get(chart); + if (!anims || !anims.running || !anims.items.length) { + return false; + } + return true; + } + stop(chart) { + const anims = this._charts.get(chart); + if (!anims || !anims.items.length) { + return; + } + const items = anims.items; + let i = items.length - 1; + for(; i >= 0; --i){ + items[i].cancel(); + } + anims.items = []; + this._notify(chart, anims, Date.now(), 'complete'); + } + remove(chart) { + return this._charts.delete(chart); + } +} +var animator = /* #__PURE__ */ new Animator(); + +const transparent = 'transparent'; +const interpolators = { + boolean (from, to, factor) { + return factor > 0.5 ? to : from; + }, + color (from, to, factor) { + const c0 = color(from || transparent); + const c1 = c0.valid && color(to || transparent); + return c1 && c1.valid ? c1.mix(c0, factor).hexString() : to; + }, + number (from, to, factor) { + return from + (to - from) * factor; + } +}; +class Animation { + constructor(cfg, target, prop, to){ + const currentValue = target[prop]; + to = resolve([ + cfg.to, + to, + currentValue, + cfg.from + ]); + const from = resolve([ + cfg.from, + currentValue, + to + ]); + this._active = true; + this._fn = cfg.fn || interpolators[cfg.type || typeof from]; + this._easing = effects[cfg.easing] || effects.linear; + this._start = Math.floor(Date.now() + (cfg.delay || 0)); + this._duration = this._total = Math.floor(cfg.duration); + this._loop = !!cfg.loop; + this._target = target; + this._prop = prop; + this._from = from; + this._to = to; + this._promises = undefined; + } + active() { + return this._active; + } + update(cfg, to, date) { + if (this._active) { + this._notify(false); + const currentValue = this._target[this._prop]; + const elapsed = date - this._start; + const remain = this._duration - elapsed; + this._start = date; + this._duration = Math.floor(Math.max(remain, cfg.duration)); + this._total += elapsed; + this._loop = !!cfg.loop; + this._to = resolve([ + cfg.to, + to, + currentValue, + cfg.from + ]); + this._from = resolve([ + cfg.from, + currentValue, + to + ]); + } + } + cancel() { + if (this._active) { + this.tick(Date.now()); + this._active = false; + this._notify(false); + } + } + tick(date) { + const elapsed = date - this._start; + const duration = this._duration; + const prop = this._prop; + const from = this._from; + const loop = this._loop; + const to = this._to; + let factor; + this._active = from !== to && (loop || elapsed < duration); + if (!this._active) { + this._target[prop] = to; + this._notify(true); + return; + } + if (elapsed < 0) { + this._target[prop] = from; + return; + } + factor = elapsed / duration % 2; + factor = loop && factor > 1 ? 2 - factor : factor; + factor = this._easing(Math.min(1, Math.max(0, factor))); + this._target[prop] = this._fn(from, to, factor); + } + wait() { + const promises = this._promises || (this._promises = []); + return new Promise((res, rej)=>{ + promises.push({ + res, + rej + }); + }); + } + _notify(resolved) { + const method = resolved ? 'res' : 'rej'; + const promises = this._promises || []; + for(let i = 0; i < promises.length; i++){ + promises[i][method](); + } + } +} + +class Animations { + constructor(chart, config){ + this._chart = chart; + this._properties = new Map(); + this.configure(config); + } + configure(config) { + if (!isObject(config)) { + return; + } + const animationOptions = Object.keys(defaults.animation); + const animatedProps = this._properties; + Object.getOwnPropertyNames(config).forEach((key)=>{ + const cfg = config[key]; + if (!isObject(cfg)) { + return; + } + const resolved = {}; + for (const option of animationOptions){ + resolved[option] = cfg[option]; + } + (isArray(cfg.properties) && cfg.properties || [ + key + ]).forEach((prop)=>{ + if (prop === key || !animatedProps.has(prop)) { + animatedProps.set(prop, resolved); + } + }); + }); + } + _animateOptions(target, values) { + const newOptions = values.options; + const options = resolveTargetOptions(target, newOptions); + if (!options) { + return []; + } + const animations = this._createAnimations(options, newOptions); + if (newOptions.$shared) { + awaitAll(target.options.$animations, newOptions).then(()=>{ + target.options = newOptions; + }, ()=>{ + }); + } + return animations; + } + _createAnimations(target, values) { + const animatedProps = this._properties; + const animations = []; + const running = target.$animations || (target.$animations = {}); + const props = Object.keys(values); + const date = Date.now(); + let i; + for(i = props.length - 1; i >= 0; --i){ + const prop = props[i]; + if (prop.charAt(0) === '$') { + continue; + } + if (prop === 'options') { + animations.push(...this._animateOptions(target, values)); + continue; + } + const value = values[prop]; + let animation = running[prop]; + const cfg = animatedProps.get(prop); + if (animation) { + if (cfg && animation.active()) { + animation.update(cfg, value, date); + continue; + } else { + animation.cancel(); + } + } + if (!cfg || !cfg.duration) { + target[prop] = value; + continue; + } + running[prop] = animation = new Animation(cfg, target, prop, value); + animations.push(animation); + } + return animations; + } + update(target, values) { + if (this._properties.size === 0) { + Object.assign(target, values); + return; + } + const animations = this._createAnimations(target, values); + if (animations.length) { + animator.add(this._chart, animations); + return true; + } + } +} +function awaitAll(animations, properties) { + const running = []; + const keys = Object.keys(properties); + for(let i = 0; i < keys.length; i++){ + const anim = animations[keys[i]]; + if (anim && anim.active()) { + running.push(anim.wait()); + } + } + return Promise.all(running); +} +function resolveTargetOptions(target, newOptions) { + if (!newOptions) { + return; + } + let options = target.options; + if (!options) { + target.options = newOptions; + return; + } + if (options.$shared) { + target.options = options = Object.assign({}, options, { + $shared: false, + $animations: {} + }); + } + return options; +} + +function scaleClip(scale, allowedOverflow) { + const opts = scale && scale.options || {}; + const reverse = opts.reverse; + const min = opts.min === undefined ? allowedOverflow : 0; + const max = opts.max === undefined ? allowedOverflow : 0; + return { + start: reverse ? max : min, + end: reverse ? min : max + }; +} +function defaultClip(xScale, yScale, allowedOverflow) { + if (allowedOverflow === false) { + return false; + } + const x = scaleClip(xScale, allowedOverflow); + const y = scaleClip(yScale, allowedOverflow); + return { + top: y.end, + right: x.end, + bottom: y.start, + left: x.start + }; +} +function toClip(value) { + let t, r, b, l; + if (isObject(value)) { + t = value.top; + r = value.right; + b = value.bottom; + l = value.left; + } else { + t = r = b = l = value; + } + return { + top: t, + right: r, + bottom: b, + left: l, + disabled: value === false + }; +} +function getSortedDatasetIndices(chart, filterVisible) { + const keys = []; + const metasets = chart._getSortedDatasetMetas(filterVisible); + let i, ilen; + for(i = 0, ilen = metasets.length; i < ilen; ++i){ + keys.push(metasets[i].index); + } + return keys; +} +function applyStack(stack, value, dsIndex, options = {}) { + const keys = stack.keys; + const singleMode = options.mode === 'single'; + let i, ilen, datasetIndex, otherValue; + if (value === null) { + return; + } + let found = false; + for(i = 0, ilen = keys.length; i < ilen; ++i){ + datasetIndex = +keys[i]; + if (datasetIndex === dsIndex) { + found = true; + if (options.all) { + continue; + } + break; + } + otherValue = stack.values[datasetIndex]; + if (isNumberFinite(otherValue) && (singleMode || value === 0 || sign(value) === sign(otherValue))) { + value += otherValue; + } + } + if (!found && !options.all) { + return 0; + } + return value; +} +function convertObjectDataToArray(data, meta) { + const { iScale , vScale } = meta; + const iAxisKey = iScale.axis === 'x' ? 'x' : 'y'; + const vAxisKey = vScale.axis === 'x' ? 'x' : 'y'; + const keys = Object.keys(data); + const adata = new Array(keys.length); + let i, ilen, key; + for(i = 0, ilen = keys.length; i < ilen; ++i){ + key = keys[i]; + adata[i] = { + [iAxisKey]: key, + [vAxisKey]: data[key] + }; + } + return adata; +} +function isStacked(scale, meta) { + const stacked = scale && scale.options.stacked; + return stacked || stacked === undefined && meta.stack !== undefined; +} +function getStackKey(indexScale, valueScale, meta) { + return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`; +} +function getUserBounds(scale) { + const { min , max , minDefined , maxDefined } = scale.getUserBounds(); + return { + min: minDefined ? min : Number.NEGATIVE_INFINITY, + max: maxDefined ? max : Number.POSITIVE_INFINITY + }; +} +function getOrCreateStack(stacks, stackKey, indexValue) { + const subStack = stacks[stackKey] || (stacks[stackKey] = {}); + return subStack[indexValue] || (subStack[indexValue] = {}); +} +function getLastIndexInStack(stack, vScale, positive, type) { + for (const meta of vScale.getMatchingVisibleMetas(type).reverse()){ + const value = stack[meta.index]; + if (positive && value > 0 || !positive && value < 0) { + return meta.index; + } + } + return null; +} +function updateStacks(controller, parsed) { + const { chart , _cachedMeta: meta } = controller; + const stacks = chart._stacks || (chart._stacks = {}); + const { iScale , vScale , index: datasetIndex } = meta; + const iAxis = iScale.axis; + const vAxis = vScale.axis; + const key = getStackKey(iScale, vScale, meta); + const ilen = parsed.length; + let stack; + for(let i = 0; i < ilen; ++i){ + const item = parsed[i]; + const { [iAxis]: index , [vAxis]: value } = item; + const itemStacks = item._stacks || (item._stacks = {}); + stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index); + stack[datasetIndex] = value; + stack._top = getLastIndexInStack(stack, vScale, true, meta.type); + stack._bottom = getLastIndexInStack(stack, vScale, false, meta.type); + const visualValues = stack._visualValues || (stack._visualValues = {}); + visualValues[datasetIndex] = value; + } +} +function getFirstScaleId(chart, axis) { + const scales = chart.scales; + return Object.keys(scales).filter((key)=>scales[key].axis === axis).shift(); +} +function createDatasetContext(parent, index) { + return createContext(parent, { + active: false, + dataset: undefined, + datasetIndex: index, + index, + mode: 'default', + type: 'dataset' + }); +} +function createDataContext(parent, index, element) { + return createContext(parent, { + active: false, + dataIndex: index, + parsed: undefined, + raw: undefined, + element, + index, + mode: 'default', + type: 'data' + }); +} +function clearStacks(meta, items) { + const datasetIndex = meta.controller.index; + const axis = meta.vScale && meta.vScale.axis; + if (!axis) { + return; + } + items = items || meta._parsed; + for (const parsed of items){ + const stacks = parsed._stacks; + if (!stacks || stacks[axis] === undefined || stacks[axis][datasetIndex] === undefined) { + return; + } + delete stacks[axis][datasetIndex]; + if (stacks[axis]._visualValues !== undefined && stacks[axis]._visualValues[datasetIndex] !== undefined) { + delete stacks[axis]._visualValues[datasetIndex]; + } + } +} +const isDirectUpdateMode = (mode)=>mode === 'reset' || mode === 'none'; +const cloneIfNotShared = (cached, shared)=>shared ? cached : Object.assign({}, cached); +const createStack = (canStack, meta, chart)=>canStack && !meta.hidden && meta._stacked && { + keys: getSortedDatasetIndices(chart, true), + values: null + }; +class DatasetController { + static defaults = {}; + static datasetElementType = null; + static dataElementType = null; + constructor(chart, datasetIndex){ + this.chart = chart; + this._ctx = chart.ctx; + this.index = datasetIndex; + this._cachedDataOpts = {}; + this._cachedMeta = this.getMeta(); + this._type = this._cachedMeta.type; + this.options = undefined; + this._parsing = false; + this._data = undefined; + this._objectData = undefined; + this._sharedOptions = undefined; + this._drawStart = undefined; + this._drawCount = undefined; + this.enableOptionSharing = false; + this.supportsDecimation = false; + this.$context = undefined; + this._syncList = []; + this.datasetElementType = new.target.datasetElementType; + this.dataElementType = new.target.dataElementType; + this.initialize(); + } + initialize() { + const meta = this._cachedMeta; + this.configure(); + this.linkScales(); + meta._stacked = isStacked(meta.vScale, meta); + this.addElements(); + if (this.options.fill && !this.chart.isPluginEnabled('filler')) { + console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options"); + } + } + updateIndex(datasetIndex) { + if (this.index !== datasetIndex) { + clearStacks(this._cachedMeta); + } + this.index = datasetIndex; + } + linkScales() { + const chart = this.chart; + const meta = this._cachedMeta; + const dataset = this.getDataset(); + const chooseId = (axis, x, y, r)=>axis === 'x' ? x : axis === 'r' ? r : y; + const xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x')); + const yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y')); + const rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r')); + const indexAxis = meta.indexAxis; + const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid); + const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid); + meta.xScale = this.getScaleForId(xid); + meta.yScale = this.getScaleForId(yid); + meta.rScale = this.getScaleForId(rid); + meta.iScale = this.getScaleForId(iid); + meta.vScale = this.getScaleForId(vid); + } + getDataset() { + return this.chart.data.datasets[this.index]; + } + getMeta() { + return this.chart.getDatasetMeta(this.index); + } + getScaleForId(scaleID) { + return this.chart.scales[scaleID]; + } + _getOtherScale(scale) { + const meta = this._cachedMeta; + return scale === meta.iScale ? meta.vScale : meta.iScale; + } + reset() { + this._update('reset'); + } + _destroy() { + const meta = this._cachedMeta; + if (this._data) { + unlistenArrayEvents(this._data, this); + } + if (meta._stacked) { + clearStacks(meta); + } + } + _dataCheck() { + const dataset = this.getDataset(); + const data = dataset.data || (dataset.data = []); + const _data = this._data; + if (isObject(data)) { + const meta = this._cachedMeta; + this._data = convertObjectDataToArray(data, meta); + } else if (_data !== data) { + if (_data) { + unlistenArrayEvents(_data, this); + const meta = this._cachedMeta; + clearStacks(meta); + meta._parsed = []; + } + if (data && Object.isExtensible(data)) { + listenArrayEvents(data, this); + } + this._syncList = []; + this._data = data; + } + } + addElements() { + const meta = this._cachedMeta; + this._dataCheck(); + if (this.datasetElementType) { + meta.dataset = new this.datasetElementType(); + } + } + buildOrUpdateElements(resetNewElements) { + const meta = this._cachedMeta; + const dataset = this.getDataset(); + let stackChanged = false; + this._dataCheck(); + const oldStacked = meta._stacked; + meta._stacked = isStacked(meta.vScale, meta); + if (meta.stack !== dataset.stack) { + stackChanged = true; + clearStacks(meta); + meta.stack = dataset.stack; + } + this._resyncElements(resetNewElements); + if (stackChanged || oldStacked !== meta._stacked) { + updateStacks(this, meta._parsed); + meta._stacked = isStacked(meta.vScale, meta); + } + } + configure() { + const config = this.chart.config; + const scopeKeys = config.datasetScopeKeys(this._type); + const scopes = config.getOptionScopes(this.getDataset(), scopeKeys, true); + this.options = config.createResolver(scopes, this.getContext()); + this._parsing = this.options.parsing; + this._cachedDataOpts = {}; + } + parse(start, count) { + const { _cachedMeta: meta , _data: data } = this; + const { iScale , _stacked } = meta; + const iAxis = iScale.axis; + let sorted = start === 0 && count === data.length ? true : meta._sorted; + let prev = start > 0 && meta._parsed[start - 1]; + let i, cur, parsed; + if (this._parsing === false) { + meta._parsed = data; + meta._sorted = true; + parsed = data; + } else { + if (isArray(data[start])) { + parsed = this.parseArrayData(meta, data, start, count); + } else if (isObject(data[start])) { + parsed = this.parseObjectData(meta, data, start, count); + } else { + parsed = this.parsePrimitiveData(meta, data, start, count); + } + const isNotInOrderComparedToPrev = ()=>cur[iAxis] === null || prev && cur[iAxis] < prev[iAxis]; + for(i = 0; i < count; ++i){ + meta._parsed[i + start] = cur = parsed[i]; + if (sorted) { + if (isNotInOrderComparedToPrev()) { + sorted = false; + } + prev = cur; + } + } + meta._sorted = sorted; + } + if (_stacked) { + updateStacks(this, parsed); + } + } + parsePrimitiveData(meta, data, start, count) { + const { iScale , vScale } = meta; + const iAxis = iScale.axis; + const vAxis = vScale.axis; + const labels = iScale.getLabels(); + const singleScale = iScale === vScale; + const parsed = new Array(count); + let i, ilen, index; + for(i = 0, ilen = count; i < ilen; ++i){ + index = i + start; + parsed[i] = { + [iAxis]: singleScale || iScale.parse(labels[index], index), + [vAxis]: vScale.parse(data[index], index) + }; + } + return parsed; + } + parseArrayData(meta, data, start, count) { + const { xScale , yScale } = meta; + const parsed = new Array(count); + let i, ilen, index, item; + for(i = 0, ilen = count; i < ilen; ++i){ + index = i + start; + item = data[index]; + parsed[i] = { + x: xScale.parse(item[0], index), + y: yScale.parse(item[1], index) + }; + } + return parsed; + } + parseObjectData(meta, data, start, count) { + const { xScale , yScale } = meta; + const { xAxisKey ='x' , yAxisKey ='y' } = this._parsing; + const parsed = new Array(count); + let i, ilen, index, item; + for(i = 0, ilen = count; i < ilen; ++i){ + index = i + start; + item = data[index]; + parsed[i] = { + x: xScale.parse(resolveObjectKey(item, xAxisKey), index), + y: yScale.parse(resolveObjectKey(item, yAxisKey), index) + }; + } + return parsed; + } + getParsed(index) { + return this._cachedMeta._parsed[index]; + } + getDataElement(index) { + return this._cachedMeta.data[index]; + } + applyStack(scale, parsed, mode) { + const chart = this.chart; + const meta = this._cachedMeta; + const value = parsed[scale.axis]; + const stack = { + keys: getSortedDatasetIndices(chart, true), + values: parsed._stacks[scale.axis]._visualValues + }; + return applyStack(stack, value, meta.index, { + mode + }); + } + updateRangeFromParsed(range, scale, parsed, stack) { + const parsedValue = parsed[scale.axis]; + let value = parsedValue === null ? NaN : parsedValue; + const values = stack && parsed._stacks[scale.axis]; + if (stack && values) { + stack.values = values; + value = applyStack(stack, parsedValue, this._cachedMeta.index); + } + range.min = Math.min(range.min, value); + range.max = Math.max(range.max, value); + } + getMinMax(scale, canStack) { + const meta = this._cachedMeta; + const _parsed = meta._parsed; + const sorted = meta._sorted && scale === meta.iScale; + const ilen = _parsed.length; + const otherScale = this._getOtherScale(scale); + const stack = createStack(canStack, meta, this.chart); + const range = { + min: Number.POSITIVE_INFINITY, + max: Number.NEGATIVE_INFINITY + }; + const { min: otherMin , max: otherMax } = getUserBounds(otherScale); + let i, parsed; + function _skip() { + parsed = _parsed[i]; + const otherValue = parsed[otherScale.axis]; + return !isNumberFinite(parsed[scale.axis]) || otherMin > otherValue || otherMax < otherValue; + } + for(i = 0; i < ilen; ++i){ + if (_skip()) { + continue; + } + this.updateRangeFromParsed(range, scale, parsed, stack); + if (sorted) { + break; + } + } + if (sorted) { + for(i = ilen - 1; i >= 0; --i){ + if (_skip()) { + continue; + } + this.updateRangeFromParsed(range, scale, parsed, stack); + break; + } + } + return range; + } + getAllParsedValues(scale) { + const parsed = this._cachedMeta._parsed; + const values = []; + let i, ilen, value; + for(i = 0, ilen = parsed.length; i < ilen; ++i){ + value = parsed[i][scale.axis]; + if (isNumberFinite(value)) { + values.push(value); + } + } + return values; + } + getMaxOverflow() { + return false; + } + getLabelAndValue(index) { + const meta = this._cachedMeta; + const iScale = meta.iScale; + const vScale = meta.vScale; + const parsed = this.getParsed(index); + return { + label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '', + value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : '' + }; + } + _update(mode) { + const meta = this._cachedMeta; + this.update(mode || 'default'); + meta._clip = toClip(valueOrDefault(this.options.clip, defaultClip(meta.xScale, meta.yScale, this.getMaxOverflow()))); + } + update(mode) {} + draw() { + const ctx = this._ctx; + const chart = this.chart; + const meta = this._cachedMeta; + const elements = meta.data || []; + const area = chart.chartArea; + const active = []; + const start = this._drawStart || 0; + const count = this._drawCount || elements.length - start; + const drawActiveElementsOnTop = this.options.drawActiveElementsOnTop; + let i; + if (meta.dataset) { + meta.dataset.draw(ctx, area, start, count); + } + for(i = start; i < start + count; ++i){ + const element = elements[i]; + if (element.hidden) { + continue; + } + if (element.active && drawActiveElementsOnTop) { + active.push(element); + } else { + element.draw(ctx, area); + } + } + for(i = 0; i < active.length; ++i){ + active[i].draw(ctx, area); + } + } + getStyle(index, active) { + const mode = active ? 'active' : 'default'; + return index === undefined && this._cachedMeta.dataset ? this.resolveDatasetElementOptions(mode) : this.resolveDataElementOptions(index || 0, mode); + } + getContext(index, active, mode) { + const dataset = this.getDataset(); + let context; + if (index >= 0 && index < this._cachedMeta.data.length) { + const element = this._cachedMeta.data[index]; + context = element.$context || (element.$context = createDataContext(this.getContext(), index, element)); + context.parsed = this.getParsed(index); + context.raw = dataset.data[index]; + context.index = context.dataIndex = index; + } else { + context = this.$context || (this.$context = createDatasetContext(this.chart.getContext(), this.index)); + context.dataset = dataset; + context.index = context.datasetIndex = this.index; + } + context.active = !!active; + context.mode = mode; + return context; + } + resolveDatasetElementOptions(mode) { + return this._resolveElementOptions(this.datasetElementType.id, mode); + } + resolveDataElementOptions(index, mode) { + return this._resolveElementOptions(this.dataElementType.id, mode, index); + } + _resolveElementOptions(elementType, mode = 'default', index) { + const active = mode === 'active'; + const cache = this._cachedDataOpts; + const cacheKey = elementType + '-' + mode; + const cached = cache[cacheKey]; + const sharing = this.enableOptionSharing && defined(index); + if (cached) { + return cloneIfNotShared(cached, sharing); + } + const config = this.chart.config; + const scopeKeys = config.datasetElementScopeKeys(this._type, elementType); + const prefixes = active ? [ + `${elementType}Hover`, + 'hover', + elementType, + '' + ] : [ + elementType, + '' + ]; + const scopes = config.getOptionScopes(this.getDataset(), scopeKeys); + const names = Object.keys(defaults.elements[elementType]); + const context = ()=>this.getContext(index, active, mode); + const values = config.resolveNamedOptions(scopes, names, context, prefixes); + if (values.$shared) { + values.$shared = sharing; + cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing)); + } + return values; + } + _resolveAnimations(index, transition, active) { + const chart = this.chart; + const cache = this._cachedDataOpts; + const cacheKey = `animation-${transition}`; + const cached = cache[cacheKey]; + if (cached) { + return cached; + } + let options; + if (chart.options.animation !== false) { + const config = this.chart.config; + const scopeKeys = config.datasetAnimationScopeKeys(this._type, transition); + const scopes = config.getOptionScopes(this.getDataset(), scopeKeys); + options = config.createResolver(scopes, this.getContext(index, active, transition)); + } + const animations = new Animations(chart, options && options.animations); + if (options && options._cacheable) { + cache[cacheKey] = Object.freeze(animations); + } + return animations; + } + getSharedOptions(options) { + if (!options.$shared) { + return; + } + return this._sharedOptions || (this._sharedOptions = Object.assign({}, options)); + } + includeOptions(mode, sharedOptions) { + return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled; + } + _getSharedOptions(start, mode) { + const firstOpts = this.resolveDataElementOptions(start, mode); + const previouslySharedOptions = this._sharedOptions; + const sharedOptions = this.getSharedOptions(firstOpts); + const includeOptions = this.includeOptions(mode, sharedOptions) || sharedOptions !== previouslySharedOptions; + this.updateSharedOptions(sharedOptions, mode, firstOpts); + return { + sharedOptions, + includeOptions + }; + } + updateElement(element, index, properties, mode) { + if (isDirectUpdateMode(mode)) { + Object.assign(element, properties); + } else { + this._resolveAnimations(index, mode).update(element, properties); + } + } + updateSharedOptions(sharedOptions, mode, newOptions) { + if (sharedOptions && !isDirectUpdateMode(mode)) { + this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions); + } + } + _setStyle(element, index, mode, active) { + element.active = active; + const options = this.getStyle(index, active); + this._resolveAnimations(index, mode, active).update(element, { + options: !active && this.getSharedOptions(options) || options + }); + } + removeHoverStyle(element, datasetIndex, index) { + this._setStyle(element, index, 'active', false); + } + setHoverStyle(element, datasetIndex, index) { + this._setStyle(element, index, 'active', true); + } + _removeDatasetHoverStyle() { + const element = this._cachedMeta.dataset; + if (element) { + this._setStyle(element, undefined, 'active', false); + } + } + _setDatasetHoverStyle() { + const element = this._cachedMeta.dataset; + if (element) { + this._setStyle(element, undefined, 'active', true); + } + } + _resyncElements(resetNewElements) { + const data = this._data; + const elements = this._cachedMeta.data; + for (const [method, arg1, arg2] of this._syncList){ + this[method](arg1, arg2); + } + this._syncList = []; + const numMeta = elements.length; + const numData = data.length; + const count = Math.min(numData, numMeta); + if (count) { + this.parse(0, count); + } + if (numData > numMeta) { + this._insertElements(numMeta, numData - numMeta, resetNewElements); + } else if (numData < numMeta) { + this._removeElements(numData, numMeta - numData); + } + } + _insertElements(start, count, resetNewElements = true) { + const meta = this._cachedMeta; + const data = meta.data; + const end = start + count; + let i; + const move = (arr)=>{ + arr.length += count; + for(i = arr.length - 1; i >= end; i--){ + arr[i] = arr[i - count]; + } + }; + move(data); + for(i = start; i < end; ++i){ + data[i] = new this.dataElementType(); + } + if (this._parsing) { + move(meta._parsed); + } + this.parse(start, count); + if (resetNewElements) { + this.updateElements(data, start, count, 'reset'); + } + } + updateElements(element, start, count, mode) {} + _removeElements(start, count) { + const meta = this._cachedMeta; + if (this._parsing) { + const removed = meta._parsed.splice(start, count); + if (meta._stacked) { + clearStacks(meta, removed); + } + } + meta.data.splice(start, count); + } + _sync(args) { + if (this._parsing) { + this._syncList.push(args); + } else { + const [method, arg1, arg2] = args; + this[method](arg1, arg2); + } + this.chart._dataChanges.push([ + this.index, + ...args + ]); + } + _onDataPush() { + const count = arguments.length; + this._sync([ + '_insertElements', + this.getDataset().data.length - count, + count + ]); + } + _onDataPop() { + this._sync([ + '_removeElements', + this._cachedMeta.data.length - 1, + 1 + ]); + } + _onDataShift() { + this._sync([ + '_removeElements', + 0, + 1 + ]); + } + _onDataSplice(start, count) { + if (count) { + this._sync([ + '_removeElements', + start, + count + ]); + } + const newCount = arguments.length - 2; + if (newCount) { + this._sync([ + '_insertElements', + start, + newCount + ]); + } + } + _onDataUnshift() { + this._sync([ + '_insertElements', + 0, + arguments.length + ]); + } +} + +function getAllScaleValues(scale, type) { + if (!scale._cache.$bar) { + const visibleMetas = scale.getMatchingVisibleMetas(type); + let values = []; + for(let i = 0, ilen = visibleMetas.length; i < ilen; i++){ + values = values.concat(visibleMetas[i].controller.getAllParsedValues(scale)); + } + scale._cache.$bar = _arrayUnique(values.sort((a, b)=>a - b)); + } + return scale._cache.$bar; +} + function computeMinSampleSize(meta) { + const scale = meta.iScale; + const values = getAllScaleValues(scale, meta.type); + let min = scale._length; + let i, ilen, curr, prev; + const updateMinAndPrev = ()=>{ + if (curr === 32767 || curr === -32768) { + return; + } + if (defined(prev)) { + min = Math.min(min, Math.abs(curr - prev) || min); + } + prev = curr; + }; + for(i = 0, ilen = values.length; i < ilen; ++i){ + curr = scale.getPixelForValue(values[i]); + updateMinAndPrev(); + } + prev = undefined; + for(i = 0, ilen = scale.ticks.length; i < ilen; ++i){ + curr = scale.getPixelForTick(i); + updateMinAndPrev(); + } + return min; +} + function computeFitCategoryTraits(index, ruler, options, stackCount) { + const thickness = options.barThickness; + let size, ratio; + if (isNullOrUndef(thickness)) { + size = ruler.min * options.categoryPercentage; + ratio = options.barPercentage; + } else { + size = thickness * stackCount; + ratio = 1; + } + return { + chunk: size / stackCount, + ratio, + start: ruler.pixels[index] - size / 2 + }; +} + function computeFlexCategoryTraits(index, ruler, options, stackCount) { + const pixels = ruler.pixels; + const curr = pixels[index]; + let prev = index > 0 ? pixels[index - 1] : null; + let next = index < pixels.length - 1 ? pixels[index + 1] : null; + const percent = options.categoryPercentage; + if (prev === null) { + prev = curr - (next === null ? ruler.end - ruler.start : next - curr); + } + if (next === null) { + next = curr + curr - prev; + } + const start = curr - (curr - Math.min(prev, next)) / 2 * percent; + const size = Math.abs(next - prev) / 2 * percent; + return { + chunk: size / stackCount, + ratio: options.barPercentage, + start + }; +} +function parseFloatBar(entry, item, vScale, i) { + const startValue = vScale.parse(entry[0], i); + const endValue = vScale.parse(entry[1], i); + const min = Math.min(startValue, endValue); + const max = Math.max(startValue, endValue); + let barStart = min; + let barEnd = max; + if (Math.abs(min) > Math.abs(max)) { + barStart = max; + barEnd = min; + } + item[vScale.axis] = barEnd; + item._custom = { + barStart, + barEnd, + start: startValue, + end: endValue, + min, + max + }; +} +function parseValue(entry, item, vScale, i) { + if (isArray(entry)) { + parseFloatBar(entry, item, vScale, i); + } else { + item[vScale.axis] = vScale.parse(entry, i); + } + return item; +} +function parseArrayOrPrimitive(meta, data, start, count) { + const iScale = meta.iScale; + const vScale = meta.vScale; + const labels = iScale.getLabels(); + const singleScale = iScale === vScale; + const parsed = []; + let i, ilen, item, entry; + for(i = start, ilen = start + count; i < ilen; ++i){ + entry = data[i]; + item = {}; + item[iScale.axis] = singleScale || iScale.parse(labels[i], i); + parsed.push(parseValue(entry, item, vScale, i)); + } + return parsed; +} +function isFloatBar(custom) { + return custom && custom.barStart !== undefined && custom.barEnd !== undefined; +} +function barSign(size, vScale, actualBase) { + if (size !== 0) { + return sign(size); + } + return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1); +} +function borderProps(properties) { + let reverse, start, end, top, bottom; + if (properties.horizontal) { + reverse = properties.base > properties.x; + start = 'left'; + end = 'right'; + } else { + reverse = properties.base < properties.y; + start = 'bottom'; + end = 'top'; + } + if (reverse) { + top = 'end'; + bottom = 'start'; + } else { + top = 'start'; + bottom = 'end'; + } + return { + start, + end, + reverse, + top, + bottom + }; +} +function setBorderSkipped(properties, options, stack, index) { + let edge = options.borderSkipped; + const res = {}; + if (!edge) { + properties.borderSkipped = res; + return; + } + if (edge === true) { + properties.borderSkipped = { + top: true, + right: true, + bottom: true, + left: true + }; + return; + } + const { start , end , reverse , top , bottom } = borderProps(properties); + if (edge === 'middle' && stack) { + properties.enableBorderRadius = true; + if ((stack._top || 0) === index) { + edge = top; + } else if ((stack._bottom || 0) === index) { + edge = bottom; + } else { + res[parseEdge(bottom, start, end, reverse)] = true; + edge = top; + } + } + res[parseEdge(edge, start, end, reverse)] = true; + properties.borderSkipped = res; +} +function parseEdge(edge, a, b, reverse) { + if (reverse) { + edge = swap(edge, a, b); + edge = startEnd(edge, b, a); + } else { + edge = startEnd(edge, a, b); + } + return edge; +} +function swap(orig, v1, v2) { + return orig === v1 ? v2 : orig === v2 ? v1 : orig; +} +function startEnd(v, start, end) { + return v === 'start' ? start : v === 'end' ? end : v; +} +function setInflateAmount(properties, { inflateAmount }, ratio) { + properties.inflateAmount = inflateAmount === 'auto' ? ratio === 1 ? 0.33 : 0 : inflateAmount; +} +class BarController extends DatasetController { + static id = 'bar'; + static defaults = { + datasetElementType: false, + dataElementType: 'bar', + categoryPercentage: 0.8, + barPercentage: 0.9, + grouped: true, + animations: { + numbers: { + type: 'number', + properties: [ + 'x', + 'y', + 'base', + 'width', + 'height' + ] + } + } + }; + static overrides = { + scales: { + _index_: { + type: 'category', + offset: true, + grid: { + offset: true + } + }, + _value_: { + type: 'linear', + beginAtZero: true + } + } + }; + parsePrimitiveData(meta, data, start, count) { + return parseArrayOrPrimitive(meta, data, start, count); + } + parseArrayData(meta, data, start, count) { + return parseArrayOrPrimitive(meta, data, start, count); + } + parseObjectData(meta, data, start, count) { + const { iScale , vScale } = meta; + const { xAxisKey ='x' , yAxisKey ='y' } = this._parsing; + const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey; + const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey; + const parsed = []; + let i, ilen, item, obj; + for(i = start, ilen = start + count; i < ilen; ++i){ + obj = data[i]; + item = {}; + item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i); + parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i)); + } + return parsed; + } + updateRangeFromParsed(range, scale, parsed, stack) { + super.updateRangeFromParsed(range, scale, parsed, stack); + const custom = parsed._custom; + if (custom && scale === this._cachedMeta.vScale) { + range.min = Math.min(range.min, custom.min); + range.max = Math.max(range.max, custom.max); + } + } + getMaxOverflow() { + return 0; + } + getLabelAndValue(index) { + const meta = this._cachedMeta; + const { iScale , vScale } = meta; + const parsed = this.getParsed(index); + const custom = parsed._custom; + const value = isFloatBar(custom) ? '[' + custom.start + ', ' + custom.end + ']' : '' + vScale.getLabelForValue(parsed[vScale.axis]); + return { + label: '' + iScale.getLabelForValue(parsed[iScale.axis]), + value + }; + } + initialize() { + this.enableOptionSharing = true; + super.initialize(); + const meta = this._cachedMeta; + meta.stack = this.getDataset().stack; + } + update(mode) { + const meta = this._cachedMeta; + this.updateElements(meta.data, 0, meta.data.length, mode); + } + updateElements(bars, start, count, mode) { + const reset = mode === 'reset'; + const { index , _cachedMeta: { vScale } } = this; + const base = vScale.getBasePixel(); + const horizontal = vScale.isHorizontal(); + const ruler = this._getRuler(); + const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode); + for(let i = start; i < start + count; i++){ + const parsed = this.getParsed(i); + const vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? { + base, + head: base + } : this._calculateBarValuePixels(i); + const ipixels = this._calculateBarIndexPixels(i, ruler); + const stack = (parsed._stacks || {})[vScale.axis]; + const properties = { + horizontal, + base: vpixels.base, + enableBorderRadius: !stack || isFloatBar(parsed._custom) || index === stack._top || index === stack._bottom, + x: horizontal ? vpixels.head : ipixels.center, + y: horizontal ? ipixels.center : vpixels.head, + height: horizontal ? ipixels.size : Math.abs(vpixels.size), + width: horizontal ? Math.abs(vpixels.size) : ipixels.size + }; + if (includeOptions) { + properties.options = sharedOptions || this.resolveDataElementOptions(i, bars[i].active ? 'active' : mode); + } + const options = properties.options || bars[i].options; + setBorderSkipped(properties, options, stack, index); + setInflateAmount(properties, options, ruler.ratio); + this.updateElement(bars[i], i, properties, mode); + } + } + _getStacks(last, dataIndex) { + const { iScale } = this._cachedMeta; + const metasets = iScale.getMatchingVisibleMetas(this._type).filter((meta)=>meta.controller.options.grouped); + const stacked = iScale.options.stacked; + const stacks = []; + const currentParsed = this._cachedMeta.controller.getParsed(dataIndex); + const iScaleValue = currentParsed && currentParsed[iScale.axis]; + const skipNull = (meta)=>{ + const parsed = meta._parsed.find((item)=>item[iScale.axis] === iScaleValue); + const val = parsed && parsed[meta.vScale.axis]; + if (isNullOrUndef(val) || isNaN(val)) { + return true; + } + }; + for (const meta of metasets){ + if (dataIndex !== undefined && skipNull(meta)) { + continue; + } + if (stacked === false || stacks.indexOf(meta.stack) === -1 || stacked === undefined && meta.stack === undefined) { + stacks.push(meta.stack); + } + if (meta.index === last) { + break; + } + } + if (!stacks.length) { + stacks.push(undefined); + } + return stacks; + } + _getStackCount(index) { + return this._getStacks(undefined, index).length; + } + _getAxisCount() { + return this._getAxis().length; + } + getFirstScaleIdForIndexAxis() { + const scales = this.chart.scales; + const indexScaleId = this.chart.options.indexAxis; + return Object.keys(scales).filter((key)=>scales[key].axis === indexScaleId).shift(); + } + _getAxis() { + const axis = {}; + const firstScaleAxisId = this.getFirstScaleIdForIndexAxis(); + for (const dataset of this.chart.data.datasets){ + axis[valueOrDefault(this.chart.options.indexAxis === 'x' ? dataset.xAxisID : dataset.yAxisID, firstScaleAxisId)] = true; + } + return Object.keys(axis); + } + _getStackIndex(datasetIndex, name, dataIndex) { + const stacks = this._getStacks(datasetIndex, dataIndex); + const index = name !== undefined ? stacks.indexOf(name) : -1; + return index === -1 ? stacks.length - 1 : index; + } + _getRuler() { + const opts = this.options; + const meta = this._cachedMeta; + const iScale = meta.iScale; + const pixels = []; + let i, ilen; + for(i = 0, ilen = meta.data.length; i < ilen; ++i){ + pixels.push(iScale.getPixelForValue(this.getParsed(i)[iScale.axis], i)); + } + const barThickness = opts.barThickness; + const min = barThickness || computeMinSampleSize(meta); + return { + min, + pixels, + start: iScale._startPixel, + end: iScale._endPixel, + stackCount: this._getStackCount(), + scale: iScale, + grouped: opts.grouped, + ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage + }; + } + _calculateBarValuePixels(index) { + const { _cachedMeta: { vScale , _stacked , index: datasetIndex } , options: { base: baseValue , minBarLength } } = this; + const actualBase = baseValue || 0; + const parsed = this.getParsed(index); + const custom = parsed._custom; + const floating = isFloatBar(custom); + let value = parsed[vScale.axis]; + let start = 0; + let length = _stacked ? this.applyStack(vScale, parsed, _stacked) : value; + let head, size; + if (length !== value) { + start = length - value; + length = value; + } + if (floating) { + value = custom.barStart; + length = custom.barEnd - custom.barStart; + if (value !== 0 && sign(value) !== sign(custom.barEnd)) { + start = 0; + } + start += value; + } + const startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start; + let base = vScale.getPixelForValue(startValue); + if (this.chart.getDataVisibility(index)) { + head = vScale.getPixelForValue(start + length); + } else { + head = base; + } + size = head - base; + if (Math.abs(size) < minBarLength) { + size = barSign(size, vScale, actualBase) * minBarLength; + if (value === actualBase) { + base -= size / 2; + } + const startPixel = vScale.getPixelForDecimal(0); + const endPixel = vScale.getPixelForDecimal(1); + const min = Math.min(startPixel, endPixel); + const max = Math.max(startPixel, endPixel); + base = Math.max(Math.min(base, max), min); + head = base + size; + if (_stacked && !floating) { + parsed._stacks[vScale.axis]._visualValues[datasetIndex] = vScale.getValueForPixel(head) - vScale.getValueForPixel(base); + } + } + if (base === vScale.getPixelForValue(actualBase)) { + const halfGrid = sign(size) * vScale.getLineWidthForValue(actualBase) / 2; + base += halfGrid; + size -= halfGrid; + } + return { + size, + base, + head, + center: head + size / 2 + }; + } + _calculateBarIndexPixels(index, ruler) { + const scale = ruler.scale; + const options = this.options; + const skipNull = options.skipNull; + const maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity); + let center, size; + const axisCount = this._getAxisCount(); + if (ruler.grouped) { + const stackCount = skipNull ? this._getStackCount(index) : ruler.stackCount; + const range = options.barThickness === 'flex' ? computeFlexCategoryTraits(index, ruler, options, stackCount * axisCount) : computeFitCategoryTraits(index, ruler, options, stackCount * axisCount); + const axisID = this.chart.options.indexAxis === 'x' ? this.getDataset().xAxisID : this.getDataset().yAxisID; + const axisNumber = this._getAxis().indexOf(valueOrDefault(axisID, this.getFirstScaleIdForIndexAxis())); + const stackIndex = this._getStackIndex(this.index, this._cachedMeta.stack, skipNull ? index : undefined) + axisNumber; + center = range.start + range.chunk * stackIndex + range.chunk / 2; + size = Math.min(maxBarThickness, range.chunk * range.ratio); + } else { + center = scale.getPixelForValue(this.getParsed(index)[scale.axis], index); + size = Math.min(maxBarThickness, ruler.min * ruler.ratio); + } + return { + base: center - size / 2, + head: center + size / 2, + center, + size + }; + } + draw() { + const meta = this._cachedMeta; + const vScale = meta.vScale; + const rects = meta.data; + const ilen = rects.length; + let i = 0; + for(; i < ilen; ++i){ + if (this.getParsed(i)[vScale.axis] !== null && !rects[i].hidden) { + rects[i].draw(this._ctx); + } + } + } +} + +class BubbleController extends DatasetController { + static id = 'bubble'; + static defaults = { + datasetElementType: false, + dataElementType: 'point', + animations: { + numbers: { + type: 'number', + properties: [ + 'x', + 'y', + 'borderWidth', + 'radius' + ] + } + } + }; + static overrides = { + scales: { + x: { + type: 'linear' + }, + y: { + type: 'linear' + } + } + }; + initialize() { + this.enableOptionSharing = true; + super.initialize(); + } + parsePrimitiveData(meta, data, start, count) { + const parsed = super.parsePrimitiveData(meta, data, start, count); + for(let i = 0; i < parsed.length; i++){ + parsed[i]._custom = this.resolveDataElementOptions(i + start).radius; + } + return parsed; + } + parseArrayData(meta, data, start, count) { + const parsed = super.parseArrayData(meta, data, start, count); + for(let i = 0; i < parsed.length; i++){ + const item = data[start + i]; + parsed[i]._custom = valueOrDefault(item[2], this.resolveDataElementOptions(i + start).radius); + } + return parsed; + } + parseObjectData(meta, data, start, count) { + const parsed = super.parseObjectData(meta, data, start, count); + for(let i = 0; i < parsed.length; i++){ + const item = data[start + i]; + parsed[i]._custom = valueOrDefault(item && item.r && +item.r, this.resolveDataElementOptions(i + start).radius); + } + return parsed; + } + getMaxOverflow() { + const data = this._cachedMeta.data; + let max = 0; + for(let i = data.length - 1; i >= 0; --i){ + max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2); + } + return max > 0 && max; + } + getLabelAndValue(index) { + const meta = this._cachedMeta; + const labels = this.chart.data.labels || []; + const { xScale , yScale } = meta; + const parsed = this.getParsed(index); + const x = xScale.getLabelForValue(parsed.x); + const y = yScale.getLabelForValue(parsed.y); + const r = parsed._custom; + return { + label: labels[index] || '', + value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')' + }; + } + update(mode) { + const points = this._cachedMeta.data; + this.updateElements(points, 0, points.length, mode); + } + updateElements(points, start, count, mode) { + const reset = mode === 'reset'; + const { iScale , vScale } = this._cachedMeta; + const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode); + const iAxis = iScale.axis; + const vAxis = vScale.axis; + for(let i = start; i < start + count; i++){ + const point = points[i]; + const parsed = !reset && this.getParsed(i); + const properties = {}; + const iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]); + const vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]); + properties.skip = isNaN(iPixel) || isNaN(vPixel); + if (includeOptions) { + properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode); + if (reset) { + properties.options.radius = 0; + } + } + this.updateElement(point, i, properties, mode); + } + } + resolveDataElementOptions(index, mode) { + const parsed = this.getParsed(index); + let values = super.resolveDataElementOptions(index, mode); + if (values.$shared) { + values = Object.assign({}, values, { + $shared: false + }); + } + const radius = values.radius; + if (mode !== 'active') { + values.radius = 0; + } + values.radius += valueOrDefault(parsed && parsed._custom, radius); + return values; + } +} + +function getRatioAndOffset(rotation, circumference, cutout) { + let ratioX = 1; + let ratioY = 1; + let offsetX = 0; + let offsetY = 0; + if (circumference < TAU) { + const startAngle = rotation; + const endAngle = startAngle + circumference; + const startX = Math.cos(startAngle); + const startY = Math.sin(startAngle); + const endX = Math.cos(endAngle); + const endY = Math.sin(endAngle); + const calcMax = (angle, a, b)=>_angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout); + const calcMin = (angle, a, b)=>_angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout); + const maxX = calcMax(0, startX, endX); + const maxY = calcMax(HALF_PI, startY, endY); + const minX = calcMin(PI, startX, endX); + const minY = calcMin(PI + HALF_PI, startY, endY); + ratioX = (maxX - minX) / 2; + ratioY = (maxY - minY) / 2; + offsetX = -(maxX + minX) / 2; + offsetY = -(maxY + minY) / 2; + } + return { + ratioX, + ratioY, + offsetX, + offsetY + }; +} +class DoughnutController extends DatasetController { + static id = 'doughnut'; + static defaults = { + datasetElementType: false, + dataElementType: 'arc', + animation: { + animateRotate: true, + animateScale: false + }, + animations: { + numbers: { + type: 'number', + properties: [ + 'circumference', + 'endAngle', + 'innerRadius', + 'outerRadius', + 'startAngle', + 'x', + 'y', + 'offset', + 'borderWidth', + 'spacing' + ] + } + }, + cutout: '50%', + rotation: 0, + circumference: 360, + radius: '100%', + spacing: 0, + indexAxis: 'r' + }; + static descriptors = { + _scriptable: (name)=>name !== 'spacing', + _indexable: (name)=>name !== 'spacing' && !name.startsWith('borderDash') && !name.startsWith('hoverBorderDash') + }; + static overrides = { + aspectRatio: 1, + plugins: { + legend: { + labels: { + generateLabels (chart) { + const data = chart.data; + if (data.labels.length && data.datasets.length) { + const { labels: { pointStyle , color } } = chart.legend.options; + return data.labels.map((label, i)=>{ + const meta = chart.getDatasetMeta(0); + const style = meta.controller.getStyle(i); + return { + text: label, + fillStyle: style.backgroundColor, + strokeStyle: style.borderColor, + fontColor: color, + lineWidth: style.borderWidth, + pointStyle: pointStyle, + hidden: !chart.getDataVisibility(i), + index: i + }; + }); + } + return []; + } + }, + onClick (e, legendItem, legend) { + legend.chart.toggleDataVisibility(legendItem.index); + legend.chart.update(); + } + } + } + }; + constructor(chart, datasetIndex){ + super(chart, datasetIndex); + this.enableOptionSharing = true; + this.innerRadius = undefined; + this.outerRadius = undefined; + this.offsetX = undefined; + this.offsetY = undefined; + } + linkScales() {} + parse(start, count) { + const data = this.getDataset().data; + const meta = this._cachedMeta; + if (this._parsing === false) { + meta._parsed = data; + } else { + let getter = (i)=>+data[i]; + if (isObject(data[start])) { + const { key ='value' } = this._parsing; + getter = (i)=>+resolveObjectKey(data[i], key); + } + let i, ilen; + for(i = start, ilen = start + count; i < ilen; ++i){ + meta._parsed[i] = getter(i); + } + } + } + _getRotation() { + return toRadians(this.options.rotation - 90); + } + _getCircumference() { + return toRadians(this.options.circumference); + } + _getRotationExtents() { + let min = TAU; + let max = -TAU; + for(let i = 0; i < this.chart.data.datasets.length; ++i){ + if (this.chart.isDatasetVisible(i) && this.chart.getDatasetMeta(i).type === this._type) { + const controller = this.chart.getDatasetMeta(i).controller; + const rotation = controller._getRotation(); + const circumference = controller._getCircumference(); + min = Math.min(min, rotation); + max = Math.max(max, rotation + circumference); + } + } + return { + rotation: min, + circumference: max - min + }; + } + update(mode) { + const chart = this.chart; + const { chartArea } = chart; + const meta = this._cachedMeta; + const arcs = meta.data; + const spacing = this.getMaxBorderWidth() + this.getMaxOffset(arcs) + this.options.spacing; + const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0); + const cutout = Math.min(toPercentage(this.options.cutout, maxSize), 1); + const chartWeight = this._getRingWeight(this.index); + const { circumference , rotation } = this._getRotationExtents(); + const { ratioX , ratioY , offsetX , offsetY } = getRatioAndOffset(rotation, circumference, cutout); + const maxWidth = (chartArea.width - spacing) / ratioX; + const maxHeight = (chartArea.height - spacing) / ratioY; + const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0); + const outerRadius = toDimension(this.options.radius, maxRadius); + const innerRadius = Math.max(outerRadius * cutout, 0); + const radiusLength = (outerRadius - innerRadius) / this._getVisibleDatasetWeightTotal(); + this.offsetX = offsetX * outerRadius; + this.offsetY = offsetY * outerRadius; + meta.total = this.calculateTotal(); + this.outerRadius = outerRadius - radiusLength * this._getRingWeightOffset(this.index); + this.innerRadius = Math.max(this.outerRadius - radiusLength * chartWeight, 0); + this.updateElements(arcs, 0, arcs.length, mode); + } + _circumference(i, reset) { + const opts = this.options; + const meta = this._cachedMeta; + const circumference = this._getCircumference(); + if (reset && opts.animation.animateRotate || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) { + return 0; + } + return this.calculateCircumference(meta._parsed[i] * circumference / TAU); + } + updateElements(arcs, start, count, mode) { + const reset = mode === 'reset'; + const chart = this.chart; + const chartArea = chart.chartArea; + const opts = chart.options; + const animationOpts = opts.animation; + const centerX = (chartArea.left + chartArea.right) / 2; + const centerY = (chartArea.top + chartArea.bottom) / 2; + const animateScale = reset && animationOpts.animateScale; + const innerRadius = animateScale ? 0 : this.innerRadius; + const outerRadius = animateScale ? 0 : this.outerRadius; + const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode); + let startAngle = this._getRotation(); + let i; + for(i = 0; i < start; ++i){ + startAngle += this._circumference(i, reset); + } + for(i = start; i < start + count; ++i){ + const circumference = this._circumference(i, reset); + const arc = arcs[i]; + const properties = { + x: centerX + this.offsetX, + y: centerY + this.offsetY, + startAngle, + endAngle: startAngle + circumference, + circumference, + outerRadius, + innerRadius + }; + if (includeOptions) { + properties.options = sharedOptions || this.resolveDataElementOptions(i, arc.active ? 'active' : mode); + } + startAngle += circumference; + this.updateElement(arc, i, properties, mode); + } + } + calculateTotal() { + const meta = this._cachedMeta; + const metaData = meta.data; + let total = 0; + let i; + for(i = 0; i < metaData.length; i++){ + const value = meta._parsed[i]; + if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) { + total += Math.abs(value); + } + } + return total; + } + calculateCircumference(value) { + const total = this._cachedMeta.total; + if (total > 0 && !isNaN(value)) { + return TAU * (Math.abs(value) / total); + } + return 0; + } + getLabelAndValue(index) { + const meta = this._cachedMeta; + const chart = this.chart; + const labels = chart.data.labels || []; + const value = formatNumber(meta._parsed[index], chart.options.locale); + return { + label: labels[index] || '', + value + }; + } + getMaxBorderWidth(arcs) { + let max = 0; + const chart = this.chart; + let i, ilen, meta, controller, options; + if (!arcs) { + for(i = 0, ilen = chart.data.datasets.length; i < ilen; ++i){ + if (chart.isDatasetVisible(i)) { + meta = chart.getDatasetMeta(i); + arcs = meta.data; + controller = meta.controller; + break; + } + } + } + if (!arcs) { + return 0; + } + for(i = 0, ilen = arcs.length; i < ilen; ++i){ + options = controller.resolveDataElementOptions(i); + if (options.borderAlign !== 'inner') { + max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0); + } + } + return max; + } + getMaxOffset(arcs) { + let max = 0; + for(let i = 0, ilen = arcs.length; i < ilen; ++i){ + const options = this.resolveDataElementOptions(i); + max = Math.max(max, options.offset || 0, options.hoverOffset || 0); + } + return max; + } + _getRingWeightOffset(datasetIndex) { + let ringWeightOffset = 0; + for(let i = 0; i < datasetIndex; ++i){ + if (this.chart.isDatasetVisible(i)) { + ringWeightOffset += this._getRingWeight(i); + } + } + return ringWeightOffset; + } + _getRingWeight(datasetIndex) { + return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0); + } + _getVisibleDatasetWeightTotal() { + return this._getRingWeightOffset(this.chart.data.datasets.length) || 1; + } +} + +class LineController extends DatasetController { + static id = 'line'; + static defaults = { + datasetElementType: 'line', + dataElementType: 'point', + showLine: true, + spanGaps: false + }; + static overrides = { + scales: { + _index_: { + type: 'category' + }, + _value_: { + type: 'linear' + } + } + }; + initialize() { + this.enableOptionSharing = true; + this.supportsDecimation = true; + super.initialize(); + } + update(mode) { + const meta = this._cachedMeta; + const { dataset: line , data: points = [] , _dataset } = meta; + const animationsDisabled = this.chart._animationsDisabled; + let { start , count } = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled); + this._drawStart = start; + this._drawCount = count; + if (_scaleRangesChanged(meta)) { + start = 0; + count = points.length; + } + line._chart = this.chart; + line._datasetIndex = this.index; + line._decimated = !!_dataset._decimated; + line.points = points; + const options = this.resolveDatasetElementOptions(mode); + if (!this.options.showLine) { + options.borderWidth = 0; + } + options.segment = this.options.segment; + this.updateElement(line, undefined, { + animated: !animationsDisabled, + options + }, mode); + this.updateElements(points, start, count, mode); + } + updateElements(points, start, count, mode) { + const reset = mode === 'reset'; + const { iScale , vScale , _stacked , _dataset } = this._cachedMeta; + const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode); + const iAxis = iScale.axis; + const vAxis = vScale.axis; + const { spanGaps , segment } = this.options; + const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY; + const directUpdate = this.chart._animationsDisabled || reset || mode === 'none'; + const end = start + count; + const pointsCount = points.length; + let prevParsed = start > 0 && this.getParsed(start - 1); + for(let i = 0; i < pointsCount; ++i){ + const point = points[i]; + const properties = directUpdate ? point : {}; + if (i < start || i >= end) { + properties.skip = true; + continue; + } + const parsed = this.getParsed(i); + const nullData = isNullOrUndef(parsed[vAxis]); + const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i); + const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i); + properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData; + properties.stop = i > 0 && Math.abs(parsed[iAxis] - prevParsed[iAxis]) > maxGapLength; + if (segment) { + properties.parsed = parsed; + properties.raw = _dataset.data[i]; + } + if (includeOptions) { + properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode); + } + if (!directUpdate) { + this.updateElement(point, i, properties, mode); + } + prevParsed = parsed; + } + } + getMaxOverflow() { + const meta = this._cachedMeta; + const dataset = meta.dataset; + const border = dataset.options && dataset.options.borderWidth || 0; + const data = meta.data || []; + if (!data.length) { + return border; + } + const firstPoint = data[0].size(this.resolveDataElementOptions(0)); + const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1)); + return Math.max(border, firstPoint, lastPoint) / 2; + } + draw() { + const meta = this._cachedMeta; + meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis); + super.draw(); + } +} + +class PolarAreaController extends DatasetController { + static id = 'polarArea'; + static defaults = { + dataElementType: 'arc', + animation: { + animateRotate: true, + animateScale: true + }, + animations: { + numbers: { + type: 'number', + properties: [ + 'x', + 'y', + 'startAngle', + 'endAngle', + 'innerRadius', + 'outerRadius' + ] + } + }, + indexAxis: 'r', + startAngle: 0 + }; + static overrides = { + aspectRatio: 1, + plugins: { + legend: { + labels: { + generateLabels (chart) { + const data = chart.data; + if (data.labels.length && data.datasets.length) { + const { labels: { pointStyle , color } } = chart.legend.options; + return data.labels.map((label, i)=>{ + const meta = chart.getDatasetMeta(0); + const style = meta.controller.getStyle(i); + return { + text: label, + fillStyle: style.backgroundColor, + strokeStyle: style.borderColor, + fontColor: color, + lineWidth: style.borderWidth, + pointStyle: pointStyle, + hidden: !chart.getDataVisibility(i), + index: i + }; + }); + } + return []; + } + }, + onClick (e, legendItem, legend) { + legend.chart.toggleDataVisibility(legendItem.index); + legend.chart.update(); + } + } + }, + scales: { + r: { + type: 'radialLinear', + angleLines: { + display: false + }, + beginAtZero: true, + grid: { + circular: true + }, + pointLabels: { + display: false + }, + startAngle: 0 + } + } + }; + constructor(chart, datasetIndex){ + super(chart, datasetIndex); + this.innerRadius = undefined; + this.outerRadius = undefined; + } + getLabelAndValue(index) { + const meta = this._cachedMeta; + const chart = this.chart; + const labels = chart.data.labels || []; + const value = formatNumber(meta._parsed[index].r, chart.options.locale); + return { + label: labels[index] || '', + value + }; + } + parseObjectData(meta, data, start, count) { + return _parseObjectDataRadialScale.bind(this)(meta, data, start, count); + } + update(mode) { + const arcs = this._cachedMeta.data; + this._updateRadius(); + this.updateElements(arcs, 0, arcs.length, mode); + } + getMinMax() { + const meta = this._cachedMeta; + const range = { + min: Number.POSITIVE_INFINITY, + max: Number.NEGATIVE_INFINITY + }; + meta.data.forEach((element, index)=>{ + const parsed = this.getParsed(index).r; + if (!isNaN(parsed) && this.chart.getDataVisibility(index)) { + if (parsed < range.min) { + range.min = parsed; + } + if (parsed > range.max) { + range.max = parsed; + } + } + }); + return range; + } + _updateRadius() { + const chart = this.chart; + const chartArea = chart.chartArea; + const opts = chart.options; + const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top); + const outerRadius = Math.max(minSize / 2, 0); + const innerRadius = Math.max(opts.cutoutPercentage ? outerRadius / 100 * opts.cutoutPercentage : 1, 0); + const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount(); + this.outerRadius = outerRadius - radiusLength * this.index; + this.innerRadius = this.outerRadius - radiusLength; + } + updateElements(arcs, start, count, mode) { + const reset = mode === 'reset'; + const chart = this.chart; + const opts = chart.options; + const animationOpts = opts.animation; + const scale = this._cachedMeta.rScale; + const centerX = scale.xCenter; + const centerY = scale.yCenter; + const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI; + let angle = datasetStartAngle; + let i; + const defaultAngle = 360 / this.countVisibleElements(); + for(i = 0; i < start; ++i){ + angle += this._computeAngle(i, mode, defaultAngle); + } + for(i = start; i < start + count; i++){ + const arc = arcs[i]; + let startAngle = angle; + let endAngle = angle + this._computeAngle(i, mode, defaultAngle); + let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(this.getParsed(i).r) : 0; + angle = endAngle; + if (reset) { + if (animationOpts.animateScale) { + outerRadius = 0; + } + if (animationOpts.animateRotate) { + startAngle = endAngle = datasetStartAngle; + } + } + const properties = { + x: centerX, + y: centerY, + innerRadius: 0, + outerRadius, + startAngle, + endAngle, + options: this.resolveDataElementOptions(i, arc.active ? 'active' : mode) + }; + this.updateElement(arc, i, properties, mode); + } + } + countVisibleElements() { + const meta = this._cachedMeta; + let count = 0; + meta.data.forEach((element, index)=>{ + if (!isNaN(this.getParsed(index).r) && this.chart.getDataVisibility(index)) { + count++; + } + }); + return count; + } + _computeAngle(index, mode, defaultAngle) { + return this.chart.getDataVisibility(index) ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle) : 0; + } +} + +class PieController extends DoughnutController { + static id = 'pie'; + static defaults = { + cutout: 0, + rotation: 0, + circumference: 360, + radius: '100%' + }; +} + +class RadarController extends DatasetController { + static id = 'radar'; + static defaults = { + datasetElementType: 'line', + dataElementType: 'point', + indexAxis: 'r', + showLine: true, + elements: { + line: { + fill: 'start' + } + } + }; + static overrides = { + aspectRatio: 1, + scales: { + r: { + type: 'radialLinear' + } + } + }; + getLabelAndValue(index) { + const vScale = this._cachedMeta.vScale; + const parsed = this.getParsed(index); + return { + label: vScale.getLabels()[index], + value: '' + vScale.getLabelForValue(parsed[vScale.axis]) + }; + } + parseObjectData(meta, data, start, count) { + return _parseObjectDataRadialScale.bind(this)(meta, data, start, count); + } + update(mode) { + const meta = this._cachedMeta; + const line = meta.dataset; + const points = meta.data || []; + const labels = meta.iScale.getLabels(); + line.points = points; + if (mode !== 'resize') { + const options = this.resolveDatasetElementOptions(mode); + if (!this.options.showLine) { + options.borderWidth = 0; + } + const properties = { + _loop: true, + _fullLoop: labels.length === points.length, + options + }; + this.updateElement(line, undefined, properties, mode); + } + this.updateElements(points, 0, points.length, mode); + } + updateElements(points, start, count, mode) { + const scale = this._cachedMeta.rScale; + const reset = mode === 'reset'; + for(let i = start; i < start + count; i++){ + const point = points[i]; + const options = this.resolveDataElementOptions(i, point.active ? 'active' : mode); + const pointPosition = scale.getPointPositionForValue(i, this.getParsed(i).r); + const x = reset ? scale.xCenter : pointPosition.x; + const y = reset ? scale.yCenter : pointPosition.y; + const properties = { + x, + y, + angle: pointPosition.angle, + skip: isNaN(x) || isNaN(y), + options + }; + this.updateElement(point, i, properties, mode); + } + } +} + +class ScatterController extends DatasetController { + static id = 'scatter'; + static defaults = { + datasetElementType: false, + dataElementType: 'point', + showLine: false, + fill: false + }; + static overrides = { + interaction: { + mode: 'point' + }, + scales: { + x: { + type: 'linear' + }, + y: { + type: 'linear' + } + } + }; + getLabelAndValue(index) { + const meta = this._cachedMeta; + const labels = this.chart.data.labels || []; + const { xScale , yScale } = meta; + const parsed = this.getParsed(index); + const x = xScale.getLabelForValue(parsed.x); + const y = yScale.getLabelForValue(parsed.y); + return { + label: labels[index] || '', + value: '(' + x + ', ' + y + ')' + }; + } + update(mode) { + const meta = this._cachedMeta; + const { data: points = [] } = meta; + const animationsDisabled = this.chart._animationsDisabled; + let { start , count } = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled); + this._drawStart = start; + this._drawCount = count; + if (_scaleRangesChanged(meta)) { + start = 0; + count = points.length; + } + if (this.options.showLine) { + if (!this.datasetElementType) { + this.addElements(); + } + const { dataset: line , _dataset } = meta; + line._chart = this.chart; + line._datasetIndex = this.index; + line._decimated = !!_dataset._decimated; + line.points = points; + const options = this.resolveDatasetElementOptions(mode); + options.segment = this.options.segment; + this.updateElement(line, undefined, { + animated: !animationsDisabled, + options + }, mode); + } else if (this.datasetElementType) { + delete meta.dataset; + this.datasetElementType = false; + } + this.updateElements(points, start, count, mode); + } + addElements() { + const { showLine } = this.options; + if (!this.datasetElementType && showLine) { + this.datasetElementType = this.chart.registry.getElement('line'); + } + super.addElements(); + } + updateElements(points, start, count, mode) { + const reset = mode === 'reset'; + const { iScale , vScale , _stacked , _dataset } = this._cachedMeta; + const firstOpts = this.resolveDataElementOptions(start, mode); + const sharedOptions = this.getSharedOptions(firstOpts); + const includeOptions = this.includeOptions(mode, sharedOptions); + const iAxis = iScale.axis; + const vAxis = vScale.axis; + const { spanGaps , segment } = this.options; + const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY; + const directUpdate = this.chart._animationsDisabled || reset || mode === 'none'; + let prevParsed = start > 0 && this.getParsed(start - 1); + for(let i = start; i < start + count; ++i){ + const point = points[i]; + const parsed = this.getParsed(i); + const properties = directUpdate ? point : {}; + const nullData = isNullOrUndef(parsed[vAxis]); + const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i); + const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i); + properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData; + properties.stop = i > 0 && Math.abs(parsed[iAxis] - prevParsed[iAxis]) > maxGapLength; + if (segment) { + properties.parsed = parsed; + properties.raw = _dataset.data[i]; + } + if (includeOptions) { + properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode); + } + if (!directUpdate) { + this.updateElement(point, i, properties, mode); + } + prevParsed = parsed; + } + this.updateSharedOptions(sharedOptions, mode, firstOpts); + } + getMaxOverflow() { + const meta = this._cachedMeta; + const data = meta.data || []; + if (!this.options.showLine) { + let max = 0; + for(let i = data.length - 1; i >= 0; --i){ + max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2); + } + return max > 0 && max; + } + const dataset = meta.dataset; + const border = dataset.options && dataset.options.borderWidth || 0; + if (!data.length) { + return border; + } + const firstPoint = data[0].size(this.resolveDataElementOptions(0)); + const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1)); + return Math.max(border, firstPoint, lastPoint) / 2; + } +} + +var controllers = /*#__PURE__*/Object.freeze({ +__proto__: null, +BarController: BarController, +BubbleController: BubbleController, +DoughnutController: DoughnutController, +LineController: LineController, +PieController: PieController, +PolarAreaController: PolarAreaController, +RadarController: RadarController, +ScatterController: ScatterController +}); + +/** + * @namespace Chart._adapters + * @since 2.8.0 + * @private + */ function abstract() { + throw new Error('This method is not implemented: Check that a complete date adapter is provided.'); +} +/** + * Date adapter (current used by the time scale) + * @namespace Chart._adapters._date + * @memberof Chart._adapters + * @private + */ class DateAdapterBase { + /** + * Override default date adapter methods. + * Accepts type parameter to define options type. + * @example + * Chart._adapters._date.override<{myAdapterOption: string}>({ + * init() { + * console.log(this.options.myAdapterOption); + * } + * }) + */ static override(members) { + Object.assign(DateAdapterBase.prototype, members); + } + options; + constructor(options){ + this.options = options || {}; + } + // eslint-disable-next-line @typescript-eslint/no-empty-function + init() {} + formats() { + return abstract(); + } + parse() { + return abstract(); + } + format() { + return abstract(); + } + add() { + return abstract(); + } + diff() { + return abstract(); + } + startOf() { + return abstract(); + } + endOf() { + return abstract(); + } +} +var adapters = { + _date: DateAdapterBase +}; + +function binarySearch(metaset, axis, value, intersect) { + const { controller , data , _sorted } = metaset; + const iScale = controller._cachedMeta.iScale; + const spanGaps = metaset.dataset ? metaset.dataset.options ? metaset.dataset.options.spanGaps : null : null; + if (iScale && axis === iScale.axis && axis !== 'r' && _sorted && data.length) { + const lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey; + if (!intersect) { + const result = lookupMethod(data, axis, value); + if (spanGaps) { + const { vScale } = controller._cachedMeta; + const { _parsed } = metaset; + const distanceToDefinedLo = _parsed.slice(0, result.lo + 1).reverse().findIndex((point)=>!isNullOrUndef(point[vScale.axis])); + result.lo -= Math.max(0, distanceToDefinedLo); + const distanceToDefinedHi = _parsed.slice(result.hi).findIndex((point)=>!isNullOrUndef(point[vScale.axis])); + result.hi += Math.max(0, distanceToDefinedHi); + } + return result; + } else if (controller._sharedOptions) { + const el = data[0]; + const range = typeof el.getRange === 'function' && el.getRange(axis); + if (range) { + const start = lookupMethod(data, axis, value - range); + const end = lookupMethod(data, axis, value + range); + return { + lo: start.lo, + hi: end.hi + }; + } + } + } + return { + lo: 0, + hi: data.length - 1 + }; +} + function evaluateInteractionItems(chart, axis, position, handler, intersect) { + const metasets = chart.getSortedVisibleDatasetMetas(); + const value = position[axis]; + for(let i = 0, ilen = metasets.length; i < ilen; ++i){ + const { index , data } = metasets[i]; + const { lo , hi } = binarySearch(metasets[i], axis, value, intersect); + for(let j = lo; j <= hi; ++j){ + const element = data[j]; + if (!element.skip) { + handler(element, index, j); + } + } + } +} + function getDistanceMetricForAxis(axis) { + const useX = axis.indexOf('x') !== -1; + const useY = axis.indexOf('y') !== -1; + return function(pt1, pt2) { + const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0; + const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0; + return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)); + }; +} + function getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) { + const items = []; + if (!includeInvisible && !chart.isPointInArea(position)) { + return items; + } + const evaluationFunc = function(element, datasetIndex, index) { + if (!includeInvisible && !_isPointInArea(element, chart.chartArea, 0)) { + return; + } + if (element.inRange(position.x, position.y, useFinalPosition)) { + items.push({ + element, + datasetIndex, + index + }); + } + }; + evaluateInteractionItems(chart, axis, position, evaluationFunc, true); + return items; +} + function getNearestRadialItems(chart, position, axis, useFinalPosition) { + let items = []; + function evaluationFunc(element, datasetIndex, index) { + const { startAngle , endAngle } = element.getProps([ + 'startAngle', + 'endAngle' + ], useFinalPosition); + const { angle } = getAngleFromPoint(element, { + x: position.x, + y: position.y + }); + if (_angleBetween(angle, startAngle, endAngle)) { + items.push({ + element, + datasetIndex, + index + }); + } + } + evaluateInteractionItems(chart, axis, position, evaluationFunc); + return items; +} + function getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) { + let items = []; + const distanceMetric = getDistanceMetricForAxis(axis); + let minDistance = Number.POSITIVE_INFINITY; + function evaluationFunc(element, datasetIndex, index) { + const inRange = element.inRange(position.x, position.y, useFinalPosition); + if (intersect && !inRange) { + return; + } + const center = element.getCenterPoint(useFinalPosition); + const pointInArea = !!includeInvisible || chart.isPointInArea(center); + if (!pointInArea && !inRange) { + return; + } + const distance = distanceMetric(position, center); + if (distance < minDistance) { + items = [ + { + element, + datasetIndex, + index + } + ]; + minDistance = distance; + } else if (distance === minDistance) { + items.push({ + element, + datasetIndex, + index + }); + } + } + evaluateInteractionItems(chart, axis, position, evaluationFunc); + return items; +} + function getNearestItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) { + if (!includeInvisible && !chart.isPointInArea(position)) { + return []; + } + return axis === 'r' && !intersect ? getNearestRadialItems(chart, position, axis, useFinalPosition) : getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible); +} + function getAxisItems(chart, position, axis, intersect, useFinalPosition) { + const items = []; + const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange'; + let intersectsItem = false; + evaluateInteractionItems(chart, axis, position, (element, datasetIndex, index)=>{ + if (element[rangeMethod] && element[rangeMethod](position[axis], useFinalPosition)) { + items.push({ + element, + datasetIndex, + index + }); + intersectsItem = intersectsItem || element.inRange(position.x, position.y, useFinalPosition); + } + }); + if (intersect && !intersectsItem) { + return []; + } + return items; +} + var Interaction = { + evaluateInteractionItems, + modes: { + index (chart, e, options, useFinalPosition) { + const position = getRelativePosition(e, chart); + const axis = options.axis || 'x'; + const includeInvisible = options.includeInvisible || false; + const items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible); + const elements = []; + if (!items.length) { + return []; + } + chart.getSortedVisibleDatasetMetas().forEach((meta)=>{ + const index = items[0].index; + const element = meta.data[index]; + if (element && !element.skip) { + elements.push({ + element, + datasetIndex: meta.index, + index + }); + } + }); + return elements; + }, + dataset (chart, e, options, useFinalPosition) { + const position = getRelativePosition(e, chart); + const axis = options.axis || 'xy'; + const includeInvisible = options.includeInvisible || false; + let items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible); + if (items.length > 0) { + const datasetIndex = items[0].datasetIndex; + const data = chart.getDatasetMeta(datasetIndex).data; + items = []; + for(let i = 0; i < data.length; ++i){ + items.push({ + element: data[i], + datasetIndex, + index: i + }); + } + } + return items; + }, + point (chart, e, options, useFinalPosition) { + const position = getRelativePosition(e, chart); + const axis = options.axis || 'xy'; + const includeInvisible = options.includeInvisible || false; + return getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible); + }, + nearest (chart, e, options, useFinalPosition) { + const position = getRelativePosition(e, chart); + const axis = options.axis || 'xy'; + const includeInvisible = options.includeInvisible || false; + return getNearestItems(chart, position, axis, options.intersect, useFinalPosition, includeInvisible); + }, + x (chart, e, options, useFinalPosition) { + const position = getRelativePosition(e, chart); + return getAxisItems(chart, position, 'x', options.intersect, useFinalPosition); + }, + y (chart, e, options, useFinalPosition) { + const position = getRelativePosition(e, chart); + return getAxisItems(chart, position, 'y', options.intersect, useFinalPosition); + } + } +}; + +const STATIC_POSITIONS = [ + 'left', + 'top', + 'right', + 'bottom' +]; +function filterByPosition(array, position) { + return array.filter((v)=>v.pos === position); +} +function filterDynamicPositionByAxis(array, axis) { + return array.filter((v)=>STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis); +} +function sortByWeight(array, reverse) { + return array.sort((a, b)=>{ + const v0 = reverse ? b : a; + const v1 = reverse ? a : b; + return v0.weight === v1.weight ? v0.index - v1.index : v0.weight - v1.weight; + }); +} +function wrapBoxes(boxes) { + const layoutBoxes = []; + let i, ilen, box, pos, stack, stackWeight; + for(i = 0, ilen = (boxes || []).length; i < ilen; ++i){ + box = boxes[i]; + ({ position: pos , options: { stack , stackWeight =1 } } = box); + layoutBoxes.push({ + index: i, + box, + pos, + horizontal: box.isHorizontal(), + weight: box.weight, + stack: stack && pos + stack, + stackWeight + }); + } + return layoutBoxes; +} +function buildStacks(layouts) { + const stacks = {}; + for (const wrap of layouts){ + const { stack , pos , stackWeight } = wrap; + if (!stack || !STATIC_POSITIONS.includes(pos)) { + continue; + } + const _stack = stacks[stack] || (stacks[stack] = { + count: 0, + placed: 0, + weight: 0, + size: 0 + }); + _stack.count++; + _stack.weight += stackWeight; + } + return stacks; +} + function setLayoutDims(layouts, params) { + const stacks = buildStacks(layouts); + const { vBoxMaxWidth , hBoxMaxHeight } = params; + let i, ilen, layout; + for(i = 0, ilen = layouts.length; i < ilen; ++i){ + layout = layouts[i]; + const { fullSize } = layout.box; + const stack = stacks[layout.stack]; + const factor = stack && layout.stackWeight / stack.weight; + if (layout.horizontal) { + layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth; + layout.height = hBoxMaxHeight; + } else { + layout.width = vBoxMaxWidth; + layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight; + } + } + return stacks; +} +function buildLayoutBoxes(boxes) { + const layoutBoxes = wrapBoxes(boxes); + const fullSize = sortByWeight(layoutBoxes.filter((wrap)=>wrap.box.fullSize), true); + const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true); + const right = sortByWeight(filterByPosition(layoutBoxes, 'right')); + const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true); + const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom')); + const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x'); + const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y'); + return { + fullSize, + leftAndTop: left.concat(top), + rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal), + chartArea: filterByPosition(layoutBoxes, 'chartArea'), + vertical: left.concat(right).concat(centerVertical), + horizontal: top.concat(bottom).concat(centerHorizontal) + }; +} +function getCombinedMax(maxPadding, chartArea, a, b) { + return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]); +} +function updateMaxPadding(maxPadding, boxPadding) { + maxPadding.top = Math.max(maxPadding.top, boxPadding.top); + maxPadding.left = Math.max(maxPadding.left, boxPadding.left); + maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom); + maxPadding.right = Math.max(maxPadding.right, boxPadding.right); +} +function updateDims(chartArea, params, layout, stacks) { + const { pos , box } = layout; + const maxPadding = chartArea.maxPadding; + if (!isObject(pos)) { + if (layout.size) { + chartArea[pos] -= layout.size; + } + const stack = stacks[layout.stack] || { + size: 0, + count: 1 + }; + stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width); + layout.size = stack.size / stack.count; + chartArea[pos] += layout.size; + } + if (box.getPadding) { + updateMaxPadding(maxPadding, box.getPadding()); + } + const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right')); + const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom')); + const widthChanged = newWidth !== chartArea.w; + const heightChanged = newHeight !== chartArea.h; + chartArea.w = newWidth; + chartArea.h = newHeight; + return layout.horizontal ? { + same: widthChanged, + other: heightChanged + } : { + same: heightChanged, + other: widthChanged + }; +} +function handleMaxPadding(chartArea) { + const maxPadding = chartArea.maxPadding; + function updatePos(pos) { + const change = Math.max(maxPadding[pos] - chartArea[pos], 0); + chartArea[pos] += change; + return change; + } + chartArea.y += updatePos('top'); + chartArea.x += updatePos('left'); + updatePos('right'); + updatePos('bottom'); +} +function getMargins(horizontal, chartArea) { + const maxPadding = chartArea.maxPadding; + function marginForPositions(positions) { + const margin = { + left: 0, + top: 0, + right: 0, + bottom: 0 + }; + positions.forEach((pos)=>{ + margin[pos] = Math.max(chartArea[pos], maxPadding[pos]); + }); + return margin; + } + return horizontal ? marginForPositions([ + 'left', + 'right' + ]) : marginForPositions([ + 'top', + 'bottom' + ]); +} +function fitBoxes(boxes, chartArea, params, stacks) { + const refitBoxes = []; + let i, ilen, layout, box, refit, changed; + for(i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i){ + layout = boxes[i]; + box = layout.box; + box.update(layout.width || chartArea.w, layout.height || chartArea.h, getMargins(layout.horizontal, chartArea)); + const { same , other } = updateDims(chartArea, params, layout, stacks); + refit |= same && refitBoxes.length; + changed = changed || other; + if (!box.fullSize) { + refitBoxes.push(layout); + } + } + return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed; +} +function setBoxDims(box, left, top, width, height) { + box.top = top; + box.left = left; + box.right = left + width; + box.bottom = top + height; + box.width = width; + box.height = height; +} +function placeBoxes(boxes, chartArea, params, stacks) { + const userPadding = params.padding; + let { x , y } = chartArea; + for (const layout of boxes){ + const box = layout.box; + const stack = stacks[layout.stack] || { + count: 1, + placed: 0, + weight: 1 + }; + const weight = layout.stackWeight / stack.weight || 1; + if (layout.horizontal) { + const width = chartArea.w * weight; + const height = stack.size || box.height; + if (defined(stack.start)) { + y = stack.start; + } + if (box.fullSize) { + setBoxDims(box, userPadding.left, y, params.outerWidth - userPadding.right - userPadding.left, height); + } else { + setBoxDims(box, chartArea.left + stack.placed, y, width, height); + } + stack.start = y; + stack.placed += width; + y = box.bottom; + } else { + const height = chartArea.h * weight; + const width = stack.size || box.width; + if (defined(stack.start)) { + x = stack.start; + } + if (box.fullSize) { + setBoxDims(box, x, userPadding.top, width, params.outerHeight - userPadding.bottom - userPadding.top); + } else { + setBoxDims(box, x, chartArea.top + stack.placed, width, height); + } + stack.start = x; + stack.placed += height; + x = box.right; + } + } + chartArea.x = x; + chartArea.y = y; +} +var layouts = { + addBox (chart, item) { + if (!chart.boxes) { + chart.boxes = []; + } + item.fullSize = item.fullSize || false; + item.position = item.position || 'top'; + item.weight = item.weight || 0; + item._layers = item._layers || function() { + return [ + { + z: 0, + draw (chartArea) { + item.draw(chartArea); + } + } + ]; + }; + chart.boxes.push(item); + }, + removeBox (chart, layoutItem) { + const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1; + if (index !== -1) { + chart.boxes.splice(index, 1); + } + }, + configure (chart, item, options) { + item.fullSize = options.fullSize; + item.position = options.position; + item.weight = options.weight; + }, + update (chart, width, height, minPadding) { + if (!chart) { + return; + } + const padding = toPadding(chart.options.layout.padding); + const availableWidth = Math.max(width - padding.width, 0); + const availableHeight = Math.max(height - padding.height, 0); + const boxes = buildLayoutBoxes(chart.boxes); + const verticalBoxes = boxes.vertical; + const horizontalBoxes = boxes.horizontal; + each(chart.boxes, (box)=>{ + if (typeof box.beforeLayout === 'function') { + box.beforeLayout(); + } + }); + const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap)=>wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1; + const params = Object.freeze({ + outerWidth: width, + outerHeight: height, + padding, + availableWidth, + availableHeight, + vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount, + hBoxMaxHeight: availableHeight / 2 + }); + const maxPadding = Object.assign({}, padding); + updateMaxPadding(maxPadding, toPadding(minPadding)); + const chartArea = Object.assign({ + maxPadding, + w: availableWidth, + h: availableHeight, + x: padding.left, + y: padding.top + }, padding); + const stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params); + fitBoxes(boxes.fullSize, chartArea, params, stacks); + fitBoxes(verticalBoxes, chartArea, params, stacks); + if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) { + fitBoxes(verticalBoxes, chartArea, params, stacks); + } + handleMaxPadding(chartArea); + placeBoxes(boxes.leftAndTop, chartArea, params, stacks); + chartArea.x += chartArea.w; + chartArea.y += chartArea.h; + placeBoxes(boxes.rightAndBottom, chartArea, params, stacks); + chart.chartArea = { + left: chartArea.left, + top: chartArea.top, + right: chartArea.left + chartArea.w, + bottom: chartArea.top + chartArea.h, + height: chartArea.h, + width: chartArea.w + }; + each(boxes.chartArea, (layout)=>{ + const box = layout.box; + Object.assign(box, chart.chartArea); + box.update(chartArea.w, chartArea.h, { + left: 0, + top: 0, + right: 0, + bottom: 0 + }); + }); + } +}; + +class BasePlatform { + acquireContext(canvas, aspectRatio) {} + releaseContext(context) { + return false; + } + addEventListener(chart, type, listener) {} + removeEventListener(chart, type, listener) {} + getDevicePixelRatio() { + return 1; + } + getMaximumSize(element, width, height, aspectRatio) { + width = Math.max(0, width || element.width); + height = height || element.height; + return { + width, + height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height) + }; + } + isAttached(canvas) { + return true; + } + updateConfig(config) { + } +} + +class BasicPlatform extends BasePlatform { + acquireContext(item) { + return item && item.getContext && item.getContext('2d') || null; + } + updateConfig(config) { + config.options.animation = false; + } +} + +const EXPANDO_KEY = '$chartjs'; + const EVENT_TYPES = { + touchstart: 'mousedown', + touchmove: 'mousemove', + touchend: 'mouseup', + pointerenter: 'mouseenter', + pointerdown: 'mousedown', + pointermove: 'mousemove', + pointerup: 'mouseup', + pointerleave: 'mouseout', + pointerout: 'mouseout' +}; +const isNullOrEmpty = (value)=>value === null || value === ''; + function initCanvas(canvas, aspectRatio) { + const style = canvas.style; + const renderHeight = canvas.getAttribute('height'); + const renderWidth = canvas.getAttribute('width'); + canvas[EXPANDO_KEY] = { + initial: { + height: renderHeight, + width: renderWidth, + style: { + display: style.display, + height: style.height, + width: style.width + } + } + }; + style.display = style.display || 'block'; + style.boxSizing = style.boxSizing || 'border-box'; + if (isNullOrEmpty(renderWidth)) { + const displayWidth = readUsedSize(canvas, 'width'); + if (displayWidth !== undefined) { + canvas.width = displayWidth; + } + } + if (isNullOrEmpty(renderHeight)) { + if (canvas.style.height === '') { + canvas.height = canvas.width / (aspectRatio || 2); + } else { + const displayHeight = readUsedSize(canvas, 'height'); + if (displayHeight !== undefined) { + canvas.height = displayHeight; + } + } + } + return canvas; +} +const eventListenerOptions = supportsEventListenerOptions ? { + passive: true +} : false; +function addListener(node, type, listener) { + if (node) { + node.addEventListener(type, listener, eventListenerOptions); + } +} +function removeListener(chart, type, listener) { + if (chart && chart.canvas) { + chart.canvas.removeEventListener(type, listener, eventListenerOptions); + } +} +function fromNativeEvent(event, chart) { + const type = EVENT_TYPES[event.type] || event.type; + const { x , y } = getRelativePosition(event, chart); + return { + type, + chart, + native: event, + x: x !== undefined ? x : null, + y: y !== undefined ? y : null + }; +} +function nodeListContains(nodeList, canvas) { + for (const node of nodeList){ + if (node === canvas || node.contains(canvas)) { + return true; + } + } +} +function createAttachObserver(chart, type, listener) { + const canvas = chart.canvas; + const observer = new MutationObserver((entries)=>{ + let trigger = false; + for (const entry of entries){ + trigger = trigger || nodeListContains(entry.addedNodes, canvas); + trigger = trigger && !nodeListContains(entry.removedNodes, canvas); + } + if (trigger) { + listener(); + } + }); + observer.observe(document, { + childList: true, + subtree: true + }); + return observer; +} +function createDetachObserver(chart, type, listener) { + const canvas = chart.canvas; + const observer = new MutationObserver((entries)=>{ + let trigger = false; + for (const entry of entries){ + trigger = trigger || nodeListContains(entry.removedNodes, canvas); + trigger = trigger && !nodeListContains(entry.addedNodes, canvas); + } + if (trigger) { + listener(); + } + }); + observer.observe(document, { + childList: true, + subtree: true + }); + return observer; +} +const drpListeningCharts = new Map(); +let oldDevicePixelRatio = 0; +function onWindowResize() { + const dpr = window.devicePixelRatio; + if (dpr === oldDevicePixelRatio) { + return; + } + oldDevicePixelRatio = dpr; + drpListeningCharts.forEach((resize, chart)=>{ + if (chart.currentDevicePixelRatio !== dpr) { + resize(); + } + }); +} +function listenDevicePixelRatioChanges(chart, resize) { + if (!drpListeningCharts.size) { + window.addEventListener('resize', onWindowResize); + } + drpListeningCharts.set(chart, resize); +} +function unlistenDevicePixelRatioChanges(chart) { + drpListeningCharts.delete(chart); + if (!drpListeningCharts.size) { + window.removeEventListener('resize', onWindowResize); + } +} +function createResizeObserver(chart, type, listener) { + const canvas = chart.canvas; + const container = canvas && _getParentNode(canvas); + if (!container) { + return; + } + const resize = throttled((width, height)=>{ + const w = container.clientWidth; + listener(width, height); + if (w < container.clientWidth) { + listener(); + } + }, window); + const observer = new ResizeObserver((entries)=>{ + const entry = entries[0]; + const width = entry.contentRect.width; + const height = entry.contentRect.height; + if (width === 0 && height === 0) { + return; + } + resize(width, height); + }); + observer.observe(container); + listenDevicePixelRatioChanges(chart, resize); + return observer; +} +function releaseObserver(chart, type, observer) { + if (observer) { + observer.disconnect(); + } + if (type === 'resize') { + unlistenDevicePixelRatioChanges(chart); + } +} +function createProxyAndListen(chart, type, listener) { + const canvas = chart.canvas; + const proxy = throttled((event)=>{ + if (chart.ctx !== null) { + listener(fromNativeEvent(event, chart)); + } + }, chart); + addListener(canvas, type, proxy); + return proxy; +} + class DomPlatform extends BasePlatform { + acquireContext(canvas, aspectRatio) { + const context = canvas && canvas.getContext && canvas.getContext('2d'); + if (context && context.canvas === canvas) { + initCanvas(canvas, aspectRatio); + return context; + } + return null; + } + releaseContext(context) { + const canvas = context.canvas; + if (!canvas[EXPANDO_KEY]) { + return false; + } + const initial = canvas[EXPANDO_KEY].initial; + [ + 'height', + 'width' + ].forEach((prop)=>{ + const value = initial[prop]; + if (isNullOrUndef(value)) { + canvas.removeAttribute(prop); + } else { + canvas.setAttribute(prop, value); + } + }); + const style = initial.style || {}; + Object.keys(style).forEach((key)=>{ + canvas.style[key] = style[key]; + }); + canvas.width = canvas.width; + delete canvas[EXPANDO_KEY]; + return true; + } + addEventListener(chart, type, listener) { + this.removeEventListener(chart, type); + const proxies = chart.$proxies || (chart.$proxies = {}); + const handlers = { + attach: createAttachObserver, + detach: createDetachObserver, + resize: createResizeObserver + }; + const handler = handlers[type] || createProxyAndListen; + proxies[type] = handler(chart, type, listener); + } + removeEventListener(chart, type) { + const proxies = chart.$proxies || (chart.$proxies = {}); + const proxy = proxies[type]; + if (!proxy) { + return; + } + const handlers = { + attach: releaseObserver, + detach: releaseObserver, + resize: releaseObserver + }; + const handler = handlers[type] || removeListener; + handler(chart, type, proxy); + proxies[type] = undefined; + } + getDevicePixelRatio() { + return window.devicePixelRatio; + } + getMaximumSize(canvas, width, height, aspectRatio) { + return getMaximumSize(canvas, width, height, aspectRatio); + } + isAttached(canvas) { + const container = canvas && _getParentNode(canvas); + return !!(container && container.isConnected); + } +} + +function _detectPlatform(canvas) { + if (!_isDomSupported() || typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas) { + return BasicPlatform; + } + return DomPlatform; +} + +class Element { + static defaults = {}; + static defaultRoutes = undefined; + x; + y; + active = false; + options; + $animations; + tooltipPosition(useFinalPosition) { + const { x , y } = this.getProps([ + 'x', + 'y' + ], useFinalPosition); + return { + x, + y + }; + } + hasValue() { + return isNumber(this.x) && isNumber(this.y); + } + getProps(props, final) { + const anims = this.$animations; + if (!final || !anims) { + // let's not create an object, if not needed + return this; + } + const ret = {}; + props.forEach((prop)=>{ + ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : this[prop]; + }); + return ret; + } +} + +function autoSkip(scale, ticks) { + const tickOpts = scale.options.ticks; + const determinedMaxTicks = determineMaxTicks(scale); + const ticksLimit = Math.min(tickOpts.maxTicksLimit || determinedMaxTicks, determinedMaxTicks); + const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : []; + const numMajorIndices = majorIndices.length; + const first = majorIndices[0]; + const last = majorIndices[numMajorIndices - 1]; + const newTicks = []; + if (numMajorIndices > ticksLimit) { + skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit); + return newTicks; + } + const spacing = calculateSpacing(majorIndices, ticks, ticksLimit); + if (numMajorIndices > 0) { + let i, ilen; + const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null; + skip(ticks, newTicks, spacing, isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first); + for(i = 0, ilen = numMajorIndices - 1; i < ilen; i++){ + skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]); + } + skip(ticks, newTicks, spacing, last, isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing); + return newTicks; + } + skip(ticks, newTicks, spacing); + return newTicks; +} +function determineMaxTicks(scale) { + const offset = scale.options.offset; + const tickLength = scale._tickSize(); + const maxScale = scale._length / tickLength + (offset ? 0 : 1); + const maxChart = scale._maxLength / tickLength; + return Math.floor(Math.min(maxScale, maxChart)); +} + function calculateSpacing(majorIndices, ticks, ticksLimit) { + const evenMajorSpacing = getEvenSpacing(majorIndices); + const spacing = ticks.length / ticksLimit; + if (!evenMajorSpacing) { + return Math.max(spacing, 1); + } + const factors = _factorize(evenMajorSpacing); + for(let i = 0, ilen = factors.length - 1; i < ilen; i++){ + const factor = factors[i]; + if (factor > spacing) { + return factor; + } + } + return Math.max(spacing, 1); +} + function getMajorIndices(ticks) { + const result = []; + let i, ilen; + for(i = 0, ilen = ticks.length; i < ilen; i++){ + if (ticks[i].major) { + result.push(i); + } + } + return result; +} + function skipMajors(ticks, newTicks, majorIndices, spacing) { + let count = 0; + let next = majorIndices[0]; + let i; + spacing = Math.ceil(spacing); + for(i = 0; i < ticks.length; i++){ + if (i === next) { + newTicks.push(ticks[i]); + count++; + next = majorIndices[count * spacing]; + } + } +} + function skip(ticks, newTicks, spacing, majorStart, majorEnd) { + const start = valueOrDefault(majorStart, 0); + const end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length); + let count = 0; + let length, i, next; + spacing = Math.ceil(spacing); + if (majorEnd) { + length = majorEnd - majorStart; + spacing = length / Math.floor(length / spacing); + } + next = start; + while(next < 0){ + count++; + next = Math.round(start + count * spacing); + } + for(i = Math.max(start, 0); i < end; i++){ + if (i === next) { + newTicks.push(ticks[i]); + count++; + next = Math.round(start + count * spacing); + } + } +} + function getEvenSpacing(arr) { + const len = arr.length; + let i, diff; + if (len < 2) { + return false; + } + for(diff = arr[0], i = 1; i < len; ++i){ + if (arr[i] - arr[i - 1] !== diff) { + return false; + } + } + return diff; +} + +const reverseAlign = (align)=>align === 'left' ? 'right' : align === 'right' ? 'left' : align; +const offsetFromEdge = (scale, edge, offset)=>edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset; +const getTicksLimit = (ticksLength, maxTicksLimit)=>Math.min(maxTicksLimit || ticksLength, ticksLength); + function sample(arr, numItems) { + const result = []; + const increment = arr.length / numItems; + const len = arr.length; + let i = 0; + for(; i < len; i += increment){ + result.push(arr[Math.floor(i)]); + } + return result; +} + function getPixelForGridLine(scale, index, offsetGridLines) { + const length = scale.ticks.length; + const validIndex = Math.min(index, length - 1); + const start = scale._startPixel; + const end = scale._endPixel; + const epsilon = 1e-6; + let lineValue = scale.getPixelForTick(validIndex); + let offset; + if (offsetGridLines) { + if (length === 1) { + offset = Math.max(lineValue - start, end - lineValue); + } else if (index === 0) { + offset = (scale.getPixelForTick(1) - lineValue) / 2; + } else { + offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2; + } + lineValue += validIndex < index ? offset : -offset; + if (lineValue < start - epsilon || lineValue > end + epsilon) { + return; + } + } + return lineValue; +} + function garbageCollect(caches, length) { + each(caches, (cache)=>{ + const gc = cache.gc; + const gcLen = gc.length / 2; + let i; + if (gcLen > length) { + for(i = 0; i < gcLen; ++i){ + delete cache.data[gc[i]]; + } + gc.splice(0, gcLen); + } + }); +} + function getTickMarkLength(options) { + return options.drawTicks ? options.tickLength : 0; +} + function getTitleHeight(options, fallback) { + if (!options.display) { + return 0; + } + const font = toFont(options.font, fallback); + const padding = toPadding(options.padding); + const lines = isArray(options.text) ? options.text.length : 1; + return lines * font.lineHeight + padding.height; +} +function createScaleContext(parent, scale) { + return createContext(parent, { + scale, + type: 'scale' + }); +} +function createTickContext(parent, index, tick) { + return createContext(parent, { + tick, + index, + type: 'tick' + }); +} +function titleAlign(align, position, reverse) { + let ret = _toLeftRightCenter(align); + if (reverse && position !== 'right' || !reverse && position === 'right') { + ret = reverseAlign(ret); + } + return ret; +} +function titleArgs(scale, offset, position, align) { + const { top , left , bottom , right , chart } = scale; + const { chartArea , scales } = chart; + let rotation = 0; + let maxWidth, titleX, titleY; + const height = bottom - top; + const width = right - left; + if (scale.isHorizontal()) { + titleX = _alignStartEnd(align, left, right); + if (isObject(position)) { + const positionAxisID = Object.keys(position)[0]; + const value = position[positionAxisID]; + titleY = scales[positionAxisID].getPixelForValue(value) + height - offset; + } else if (position === 'center') { + titleY = (chartArea.bottom + chartArea.top) / 2 + height - offset; + } else { + titleY = offsetFromEdge(scale, position, offset); + } + maxWidth = right - left; + } else { + if (isObject(position)) { + const positionAxisID = Object.keys(position)[0]; + const value = position[positionAxisID]; + titleX = scales[positionAxisID].getPixelForValue(value) - width + offset; + } else if (position === 'center') { + titleX = (chartArea.left + chartArea.right) / 2 - width + offset; + } else { + titleX = offsetFromEdge(scale, position, offset); + } + titleY = _alignStartEnd(align, bottom, top); + rotation = position === 'left' ? -HALF_PI : HALF_PI; + } + return { + titleX, + titleY, + maxWidth, + rotation + }; +} +class Scale extends Element { + constructor(cfg){ + super(); + this.id = cfg.id; + this.type = cfg.type; + this.options = undefined; + this.ctx = cfg.ctx; + this.chart = cfg.chart; + this.top = undefined; + this.bottom = undefined; + this.left = undefined; + this.right = undefined; + this.width = undefined; + this.height = undefined; + this._margins = { + left: 0, + right: 0, + top: 0, + bottom: 0 + }; + this.maxWidth = undefined; + this.maxHeight = undefined; + this.paddingTop = undefined; + this.paddingBottom = undefined; + this.paddingLeft = undefined; + this.paddingRight = undefined; + this.axis = undefined; + this.labelRotation = undefined; + this.min = undefined; + this.max = undefined; + this._range = undefined; + this.ticks = []; + this._gridLineItems = null; + this._labelItems = null; + this._labelSizes = null; + this._length = 0; + this._maxLength = 0; + this._longestTextCache = {}; + this._startPixel = undefined; + this._endPixel = undefined; + this._reversePixels = false; + this._userMax = undefined; + this._userMin = undefined; + this._suggestedMax = undefined; + this._suggestedMin = undefined; + this._ticksLength = 0; + this._borderValue = 0; + this._cache = {}; + this._dataLimitsCached = false; + this.$context = undefined; + } + init(options) { + this.options = options.setContext(this.getContext()); + this.axis = options.axis; + this._userMin = this.parse(options.min); + this._userMax = this.parse(options.max); + this._suggestedMin = this.parse(options.suggestedMin); + this._suggestedMax = this.parse(options.suggestedMax); + } + parse(raw, index) { + return raw; + } + getUserBounds() { + let { _userMin , _userMax , _suggestedMin , _suggestedMax } = this; + _userMin = finiteOrDefault(_userMin, Number.POSITIVE_INFINITY); + _userMax = finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY); + _suggestedMin = finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY); + _suggestedMax = finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY); + return { + min: finiteOrDefault(_userMin, _suggestedMin), + max: finiteOrDefault(_userMax, _suggestedMax), + minDefined: isNumberFinite(_userMin), + maxDefined: isNumberFinite(_userMax) + }; + } + getMinMax(canStack) { + let { min , max , minDefined , maxDefined } = this.getUserBounds(); + let range; + if (minDefined && maxDefined) { + return { + min, + max + }; + } + const metas = this.getMatchingVisibleMetas(); + for(let i = 0, ilen = metas.length; i < ilen; ++i){ + range = metas[i].controller.getMinMax(this, canStack); + if (!minDefined) { + min = Math.min(min, range.min); + } + if (!maxDefined) { + max = Math.max(max, range.max); + } + } + min = maxDefined && min > max ? max : min; + max = minDefined && min > max ? min : max; + return { + min: finiteOrDefault(min, finiteOrDefault(max, min)), + max: finiteOrDefault(max, finiteOrDefault(min, max)) + }; + } + getPadding() { + return { + left: this.paddingLeft || 0, + top: this.paddingTop || 0, + right: this.paddingRight || 0, + bottom: this.paddingBottom || 0 + }; + } + getTicks() { + return this.ticks; + } + getLabels() { + const data = this.chart.data; + return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || []; + } + getLabelItems(chartArea = this.chart.chartArea) { + const items = this._labelItems || (this._labelItems = this._computeLabelItems(chartArea)); + return items; + } + beforeLayout() { + this._cache = {}; + this._dataLimitsCached = false; + } + beforeUpdate() { + callback(this.options.beforeUpdate, [ + this + ]); + } + update(maxWidth, maxHeight, margins) { + const { beginAtZero , grace , ticks: tickOpts } = this.options; + const sampleSize = tickOpts.sampleSize; + this.beforeUpdate(); + this.maxWidth = maxWidth; + this.maxHeight = maxHeight; + this._margins = margins = Object.assign({ + left: 0, + right: 0, + top: 0, + bottom: 0 + }, margins); + this.ticks = null; + this._labelSizes = null; + this._gridLineItems = null; + this._labelItems = null; + this.beforeSetDimensions(); + this.setDimensions(); + this.afterSetDimensions(); + this._maxLength = this.isHorizontal() ? this.width + margins.left + margins.right : this.height + margins.top + margins.bottom; + if (!this._dataLimitsCached) { + this.beforeDataLimits(); + this.determineDataLimits(); + this.afterDataLimits(); + this._range = _addGrace(this, grace, beginAtZero); + this._dataLimitsCached = true; + } + this.beforeBuildTicks(); + this.ticks = this.buildTicks() || []; + this.afterBuildTicks(); + const samplingEnabled = sampleSize < this.ticks.length; + this._convertTicksToLabels(samplingEnabled ? sample(this.ticks, sampleSize) : this.ticks); + this.configure(); + this.beforeCalculateLabelRotation(); + this.calculateLabelRotation(); + this.afterCalculateLabelRotation(); + if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) { + this.ticks = autoSkip(this, this.ticks); + this._labelSizes = null; + this.afterAutoSkip(); + } + if (samplingEnabled) { + this._convertTicksToLabels(this.ticks); + } + this.beforeFit(); + this.fit(); + this.afterFit(); + this.afterUpdate(); + } + configure() { + let reversePixels = this.options.reverse; + let startPixel, endPixel; + if (this.isHorizontal()) { + startPixel = this.left; + endPixel = this.right; + } else { + startPixel = this.top; + endPixel = this.bottom; + reversePixels = !reversePixels; + } + this._startPixel = startPixel; + this._endPixel = endPixel; + this._reversePixels = reversePixels; + this._length = endPixel - startPixel; + this._alignToPixels = this.options.alignToPixels; + } + afterUpdate() { + callback(this.options.afterUpdate, [ + this + ]); + } + beforeSetDimensions() { + callback(this.options.beforeSetDimensions, [ + this + ]); + } + setDimensions() { + if (this.isHorizontal()) { + this.width = this.maxWidth; + this.left = 0; + this.right = this.width; + } else { + this.height = this.maxHeight; + this.top = 0; + this.bottom = this.height; + } + this.paddingLeft = 0; + this.paddingTop = 0; + this.paddingRight = 0; + this.paddingBottom = 0; + } + afterSetDimensions() { + callback(this.options.afterSetDimensions, [ + this + ]); + } + _callHooks(name) { + this.chart.notifyPlugins(name, this.getContext()); + callback(this.options[name], [ + this + ]); + } + beforeDataLimits() { + this._callHooks('beforeDataLimits'); + } + determineDataLimits() {} + afterDataLimits() { + this._callHooks('afterDataLimits'); + } + beforeBuildTicks() { + this._callHooks('beforeBuildTicks'); + } + buildTicks() { + return []; + } + afterBuildTicks() { + this._callHooks('afterBuildTicks'); + } + beforeTickToLabelConversion() { + callback(this.options.beforeTickToLabelConversion, [ + this + ]); + } + generateTickLabels(ticks) { + const tickOpts = this.options.ticks; + let i, ilen, tick; + for(i = 0, ilen = ticks.length; i < ilen; i++){ + tick = ticks[i]; + tick.label = callback(tickOpts.callback, [ + tick.value, + i, + ticks + ], this); + } + } + afterTickToLabelConversion() { + callback(this.options.afterTickToLabelConversion, [ + this + ]); + } + beforeCalculateLabelRotation() { + callback(this.options.beforeCalculateLabelRotation, [ + this + ]); + } + calculateLabelRotation() { + const options = this.options; + const tickOpts = options.ticks; + const numTicks = getTicksLimit(this.ticks.length, options.ticks.maxTicksLimit); + const minRotation = tickOpts.minRotation || 0; + const maxRotation = tickOpts.maxRotation; + let labelRotation = minRotation; + let tickWidth, maxHeight, maxLabelDiagonal; + if (!this._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !this.isHorizontal()) { + this.labelRotation = minRotation; + return; + } + const labelSizes = this._getLabelSizes(); + const maxLabelWidth = labelSizes.widest.width; + const maxLabelHeight = labelSizes.highest.height; + const maxWidth = _limitValue(this.chart.width - maxLabelWidth, 0, this.maxWidth); + tickWidth = options.offset ? this.maxWidth / numTicks : maxWidth / (numTicks - 1); + if (maxLabelWidth + 6 > tickWidth) { + tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1)); + maxHeight = this.maxHeight - getTickMarkLength(options.grid) - tickOpts.padding - getTitleHeight(options.title, this.chart.options.font); + maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight); + labelRotation = toDegrees(Math.min(Math.asin(_limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)), Math.asin(_limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(_limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1)))); + labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation)); + } + this.labelRotation = labelRotation; + } + afterCalculateLabelRotation() { + callback(this.options.afterCalculateLabelRotation, [ + this + ]); + } + afterAutoSkip() {} + beforeFit() { + callback(this.options.beforeFit, [ + this + ]); + } + fit() { + const minSize = { + width: 0, + height: 0 + }; + const { chart , options: { ticks: tickOpts , title: titleOpts , grid: gridOpts } } = this; + const display = this._isVisible(); + const isHorizontal = this.isHorizontal(); + if (display) { + const titleHeight = getTitleHeight(titleOpts, chart.options.font); + if (isHorizontal) { + minSize.width = this.maxWidth; + minSize.height = getTickMarkLength(gridOpts) + titleHeight; + } else { + minSize.height = this.maxHeight; + minSize.width = getTickMarkLength(gridOpts) + titleHeight; + } + if (tickOpts.display && this.ticks.length) { + const { first , last , widest , highest } = this._getLabelSizes(); + const tickPadding = tickOpts.padding * 2; + const angleRadians = toRadians(this.labelRotation); + const cos = Math.cos(angleRadians); + const sin = Math.sin(angleRadians); + if (isHorizontal) { + const labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height; + minSize.height = Math.min(this.maxHeight, minSize.height + labelHeight + tickPadding); + } else { + const labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height; + minSize.width = Math.min(this.maxWidth, minSize.width + labelWidth + tickPadding); + } + this._calculatePadding(first, last, sin, cos); + } + } + this._handleMargins(); + if (isHorizontal) { + this.width = this._length = chart.width - this._margins.left - this._margins.right; + this.height = minSize.height; + } else { + this.width = minSize.width; + this.height = this._length = chart.height - this._margins.top - this._margins.bottom; + } + } + _calculatePadding(first, last, sin, cos) { + const { ticks: { align , padding } , position } = this.options; + const isRotated = this.labelRotation !== 0; + const labelsBelowTicks = position !== 'top' && this.axis === 'x'; + if (this.isHorizontal()) { + const offsetLeft = this.getPixelForTick(0) - this.left; + const offsetRight = this.right - this.getPixelForTick(this.ticks.length - 1); + let paddingLeft = 0; + let paddingRight = 0; + if (isRotated) { + if (labelsBelowTicks) { + paddingLeft = cos * first.width; + paddingRight = sin * last.height; + } else { + paddingLeft = sin * first.height; + paddingRight = cos * last.width; + } + } else if (align === 'start') { + paddingRight = last.width; + } else if (align === 'end') { + paddingLeft = first.width; + } else if (align !== 'inner') { + paddingLeft = first.width / 2; + paddingRight = last.width / 2; + } + this.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * this.width / (this.width - offsetLeft), 0); + this.paddingRight = Math.max((paddingRight - offsetRight + padding) * this.width / (this.width - offsetRight), 0); + } else { + let paddingTop = last.height / 2; + let paddingBottom = first.height / 2; + if (align === 'start') { + paddingTop = 0; + paddingBottom = first.height; + } else if (align === 'end') { + paddingTop = last.height; + paddingBottom = 0; + } + this.paddingTop = paddingTop + padding; + this.paddingBottom = paddingBottom + padding; + } + } + _handleMargins() { + if (this._margins) { + this._margins.left = Math.max(this.paddingLeft, this._margins.left); + this._margins.top = Math.max(this.paddingTop, this._margins.top); + this._margins.right = Math.max(this.paddingRight, this._margins.right); + this._margins.bottom = Math.max(this.paddingBottom, this._margins.bottom); + } + } + afterFit() { + callback(this.options.afterFit, [ + this + ]); + } + isHorizontal() { + const { axis , position } = this.options; + return position === 'top' || position === 'bottom' || axis === 'x'; + } + isFullSize() { + return this.options.fullSize; + } + _convertTicksToLabels(ticks) { + this.beforeTickToLabelConversion(); + this.generateTickLabels(ticks); + let i, ilen; + for(i = 0, ilen = ticks.length; i < ilen; i++){ + if (isNullOrUndef(ticks[i].label)) { + ticks.splice(i, 1); + ilen--; + i--; + } + } + this.afterTickToLabelConversion(); + } + _getLabelSizes() { + let labelSizes = this._labelSizes; + if (!labelSizes) { + const sampleSize = this.options.ticks.sampleSize; + let ticks = this.ticks; + if (sampleSize < ticks.length) { + ticks = sample(ticks, sampleSize); + } + this._labelSizes = labelSizes = this._computeLabelSizes(ticks, ticks.length, this.options.ticks.maxTicksLimit); + } + return labelSizes; + } + _computeLabelSizes(ticks, length, maxTicksLimit) { + const { ctx , _longestTextCache: caches } = this; + const widths = []; + const heights = []; + const increment = Math.floor(length / getTicksLimit(length, maxTicksLimit)); + let widestLabelSize = 0; + let highestLabelSize = 0; + let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel; + for(i = 0; i < length; i += increment){ + label = ticks[i].label; + tickFont = this._resolveTickFontOptions(i); + ctx.font = fontString = tickFont.string; + cache = caches[fontString] = caches[fontString] || { + data: {}, + gc: [] + }; + lineHeight = tickFont.lineHeight; + width = height = 0; + if (!isNullOrUndef(label) && !isArray(label)) { + width = _measureText(ctx, cache.data, cache.gc, width, label); + height = lineHeight; + } else if (isArray(label)) { + for(j = 0, jlen = label.length; j < jlen; ++j){ + nestedLabel = label[j]; + if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) { + width = _measureText(ctx, cache.data, cache.gc, width, nestedLabel); + height += lineHeight; + } + } + } + widths.push(width); + heights.push(height); + widestLabelSize = Math.max(width, widestLabelSize); + highestLabelSize = Math.max(height, highestLabelSize); + } + garbageCollect(caches, length); + const widest = widths.indexOf(widestLabelSize); + const highest = heights.indexOf(highestLabelSize); + const valueAt = (idx)=>({ + width: widths[idx] || 0, + height: heights[idx] || 0 + }); + return { + first: valueAt(0), + last: valueAt(length - 1), + widest: valueAt(widest), + highest: valueAt(highest), + widths, + heights + }; + } + getLabelForValue(value) { + return value; + } + getPixelForValue(value, index) { + return NaN; + } + getValueForPixel(pixel) {} + getPixelForTick(index) { + const ticks = this.ticks; + if (index < 0 || index > ticks.length - 1) { + return null; + } + return this.getPixelForValue(ticks[index].value); + } + getPixelForDecimal(decimal) { + if (this._reversePixels) { + decimal = 1 - decimal; + } + const pixel = this._startPixel + decimal * this._length; + return _int16Range(this._alignToPixels ? _alignPixel(this.chart, pixel, 0) : pixel); + } + getDecimalForPixel(pixel) { + const decimal = (pixel - this._startPixel) / this._length; + return this._reversePixels ? 1 - decimal : decimal; + } + getBasePixel() { + return this.getPixelForValue(this.getBaseValue()); + } + getBaseValue() { + const { min , max } = this; + return min < 0 && max < 0 ? max : min > 0 && max > 0 ? min : 0; + } + getContext(index) { + const ticks = this.ticks || []; + if (index >= 0 && index < ticks.length) { + const tick = ticks[index]; + return tick.$context || (tick.$context = createTickContext(this.getContext(), index, tick)); + } + return this.$context || (this.$context = createScaleContext(this.chart.getContext(), this)); + } + _tickSize() { + const optionTicks = this.options.ticks; + const rot = toRadians(this.labelRotation); + const cos = Math.abs(Math.cos(rot)); + const sin = Math.abs(Math.sin(rot)); + const labelSizes = this._getLabelSizes(); + const padding = optionTicks.autoSkipPadding || 0; + const w = labelSizes ? labelSizes.widest.width + padding : 0; + const h = labelSizes ? labelSizes.highest.height + padding : 0; + return this.isHorizontal() ? h * cos > w * sin ? w / cos : h / sin : h * sin < w * cos ? h / cos : w / sin; + } + _isVisible() { + const display = this.options.display; + if (display !== 'auto') { + return !!display; + } + return this.getMatchingVisibleMetas().length > 0; + } + _computeGridLineItems(chartArea) { + const axis = this.axis; + const chart = this.chart; + const options = this.options; + const { grid , position , border } = options; + const offset = grid.offset; + const isHorizontal = this.isHorizontal(); + const ticks = this.ticks; + const ticksLength = ticks.length + (offset ? 1 : 0); + const tl = getTickMarkLength(grid); + const items = []; + const borderOpts = border.setContext(this.getContext()); + const axisWidth = borderOpts.display ? borderOpts.width : 0; + const axisHalfWidth = axisWidth / 2; + const alignBorderValue = function(pixel) { + return _alignPixel(chart, pixel, axisWidth); + }; + let borderValue, i, lineValue, alignedLineValue; + let tx1, ty1, tx2, ty2, x1, y1, x2, y2; + if (position === 'top') { + borderValue = alignBorderValue(this.bottom); + ty1 = this.bottom - tl; + ty2 = borderValue - axisHalfWidth; + y1 = alignBorderValue(chartArea.top) + axisHalfWidth; + y2 = chartArea.bottom; + } else if (position === 'bottom') { + borderValue = alignBorderValue(this.top); + y1 = chartArea.top; + y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth; + ty1 = borderValue + axisHalfWidth; + ty2 = this.top + tl; + } else if (position === 'left') { + borderValue = alignBorderValue(this.right); + tx1 = this.right - tl; + tx2 = borderValue - axisHalfWidth; + x1 = alignBorderValue(chartArea.left) + axisHalfWidth; + x2 = chartArea.right; + } else if (position === 'right') { + borderValue = alignBorderValue(this.left); + x1 = chartArea.left; + x2 = alignBorderValue(chartArea.right) - axisHalfWidth; + tx1 = borderValue + axisHalfWidth; + tx2 = this.left + tl; + } else if (axis === 'x') { + if (position === 'center') { + borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5); + } else if (isObject(position)) { + const positionAxisID = Object.keys(position)[0]; + const value = position[positionAxisID]; + borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value)); + } + y1 = chartArea.top; + y2 = chartArea.bottom; + ty1 = borderValue + axisHalfWidth; + ty2 = ty1 + tl; + } else if (axis === 'y') { + if (position === 'center') { + borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2); + } else if (isObject(position)) { + const positionAxisID = Object.keys(position)[0]; + const value = position[positionAxisID]; + borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value)); + } + tx1 = borderValue - axisHalfWidth; + tx2 = tx1 - tl; + x1 = chartArea.left; + x2 = chartArea.right; + } + const limit = valueOrDefault(options.ticks.maxTicksLimit, ticksLength); + const step = Math.max(1, Math.ceil(ticksLength / limit)); + for(i = 0; i < ticksLength; i += step){ + const context = this.getContext(i); + const optsAtIndex = grid.setContext(context); + const optsAtIndexBorder = border.setContext(context); + const lineWidth = optsAtIndex.lineWidth; + const lineColor = optsAtIndex.color; + const borderDash = optsAtIndexBorder.dash || []; + const borderDashOffset = optsAtIndexBorder.dashOffset; + const tickWidth = optsAtIndex.tickWidth; + const tickColor = optsAtIndex.tickColor; + const tickBorderDash = optsAtIndex.tickBorderDash || []; + const tickBorderDashOffset = optsAtIndex.tickBorderDashOffset; + lineValue = getPixelForGridLine(this, i, offset); + if (lineValue === undefined) { + continue; + } + alignedLineValue = _alignPixel(chart, lineValue, lineWidth); + if (isHorizontal) { + tx1 = tx2 = x1 = x2 = alignedLineValue; + } else { + ty1 = ty2 = y1 = y2 = alignedLineValue; + } + items.push({ + tx1, + ty1, + tx2, + ty2, + x1, + y1, + x2, + y2, + width: lineWidth, + color: lineColor, + borderDash, + borderDashOffset, + tickWidth, + tickColor, + tickBorderDash, + tickBorderDashOffset + }); + } + this._ticksLength = ticksLength; + this._borderValue = borderValue; + return items; + } + _computeLabelItems(chartArea) { + const axis = this.axis; + const options = this.options; + const { position , ticks: optionTicks } = options; + const isHorizontal = this.isHorizontal(); + const ticks = this.ticks; + const { align , crossAlign , padding , mirror } = optionTicks; + const tl = getTickMarkLength(options.grid); + const tickAndPadding = tl + padding; + const hTickAndPadding = mirror ? -padding : tickAndPadding; + const rotation = -toRadians(this.labelRotation); + const items = []; + let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset; + let textBaseline = 'middle'; + if (position === 'top') { + y = this.bottom - hTickAndPadding; + textAlign = this._getXAxisLabelAlignment(); + } else if (position === 'bottom') { + y = this.top + hTickAndPadding; + textAlign = this._getXAxisLabelAlignment(); + } else if (position === 'left') { + const ret = this._getYAxisLabelAlignment(tl); + textAlign = ret.textAlign; + x = ret.x; + } else if (position === 'right') { + const ret = this._getYAxisLabelAlignment(tl); + textAlign = ret.textAlign; + x = ret.x; + } else if (axis === 'x') { + if (position === 'center') { + y = (chartArea.top + chartArea.bottom) / 2 + tickAndPadding; + } else if (isObject(position)) { + const positionAxisID = Object.keys(position)[0]; + const value = position[positionAxisID]; + y = this.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding; + } + textAlign = this._getXAxisLabelAlignment(); + } else if (axis === 'y') { + if (position === 'center') { + x = (chartArea.left + chartArea.right) / 2 - tickAndPadding; + } else if (isObject(position)) { + const positionAxisID = Object.keys(position)[0]; + const value = position[positionAxisID]; + x = this.chart.scales[positionAxisID].getPixelForValue(value); + } + textAlign = this._getYAxisLabelAlignment(tl).textAlign; + } + if (axis === 'y') { + if (align === 'start') { + textBaseline = 'top'; + } else if (align === 'end') { + textBaseline = 'bottom'; + } + } + const labelSizes = this._getLabelSizes(); + for(i = 0, ilen = ticks.length; i < ilen; ++i){ + tick = ticks[i]; + label = tick.label; + const optsAtIndex = optionTicks.setContext(this.getContext(i)); + pixel = this.getPixelForTick(i) + optionTicks.labelOffset; + font = this._resolveTickFontOptions(i); + lineHeight = font.lineHeight; + lineCount = isArray(label) ? label.length : 1; + const halfCount = lineCount / 2; + const color = optsAtIndex.color; + const strokeColor = optsAtIndex.textStrokeColor; + const strokeWidth = optsAtIndex.textStrokeWidth; + let tickTextAlign = textAlign; + if (isHorizontal) { + x = pixel; + if (textAlign === 'inner') { + if (i === ilen - 1) { + tickTextAlign = !this.options.reverse ? 'right' : 'left'; + } else if (i === 0) { + tickTextAlign = !this.options.reverse ? 'left' : 'right'; + } else { + tickTextAlign = 'center'; + } + } + if (position === 'top') { + if (crossAlign === 'near' || rotation !== 0) { + textOffset = -lineCount * lineHeight + lineHeight / 2; + } else if (crossAlign === 'center') { + textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight; + } else { + textOffset = -labelSizes.highest.height + lineHeight / 2; + } + } else { + if (crossAlign === 'near' || rotation !== 0) { + textOffset = lineHeight / 2; + } else if (crossAlign === 'center') { + textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight; + } else { + textOffset = labelSizes.highest.height - lineCount * lineHeight; + } + } + if (mirror) { + textOffset *= -1; + } + if (rotation !== 0 && !optsAtIndex.showLabelBackdrop) { + x += lineHeight / 2 * Math.sin(rotation); + } + } else { + y = pixel; + textOffset = (1 - lineCount) * lineHeight / 2; + } + let backdrop; + if (optsAtIndex.showLabelBackdrop) { + const labelPadding = toPadding(optsAtIndex.backdropPadding); + const height = labelSizes.heights[i]; + const width = labelSizes.widths[i]; + let top = textOffset - labelPadding.top; + let left = 0 - labelPadding.left; + switch(textBaseline){ + case 'middle': + top -= height / 2; + break; + case 'bottom': + top -= height; + break; + } + switch(textAlign){ + case 'center': + left -= width / 2; + break; + case 'right': + left -= width; + break; + case 'inner': + if (i === ilen - 1) { + left -= width; + } else if (i > 0) { + left -= width / 2; + } + break; + } + backdrop = { + left, + top, + width: width + labelPadding.width, + height: height + labelPadding.height, + color: optsAtIndex.backdropColor + }; + } + items.push({ + label, + font, + textOffset, + options: { + rotation, + color, + strokeColor, + strokeWidth, + textAlign: tickTextAlign, + textBaseline, + translation: [ + x, + y + ], + backdrop + } + }); + } + return items; + } + _getXAxisLabelAlignment() { + const { position , ticks } = this.options; + const rotation = -toRadians(this.labelRotation); + if (rotation) { + return position === 'top' ? 'left' : 'right'; + } + let align = 'center'; + if (ticks.align === 'start') { + align = 'left'; + } else if (ticks.align === 'end') { + align = 'right'; + } else if (ticks.align === 'inner') { + align = 'inner'; + } + return align; + } + _getYAxisLabelAlignment(tl) { + const { position , ticks: { crossAlign , mirror , padding } } = this.options; + const labelSizes = this._getLabelSizes(); + const tickAndPadding = tl + padding; + const widest = labelSizes.widest.width; + let textAlign; + let x; + if (position === 'left') { + if (mirror) { + x = this.right + padding; + if (crossAlign === 'near') { + textAlign = 'left'; + } else if (crossAlign === 'center') { + textAlign = 'center'; + x += widest / 2; + } else { + textAlign = 'right'; + x += widest; + } + } else { + x = this.right - tickAndPadding; + if (crossAlign === 'near') { + textAlign = 'right'; + } else if (crossAlign === 'center') { + textAlign = 'center'; + x -= widest / 2; + } else { + textAlign = 'left'; + x = this.left; + } + } + } else if (position === 'right') { + if (mirror) { + x = this.left + padding; + if (crossAlign === 'near') { + textAlign = 'right'; + } else if (crossAlign === 'center') { + textAlign = 'center'; + x -= widest / 2; + } else { + textAlign = 'left'; + x -= widest; + } + } else { + x = this.left + tickAndPadding; + if (crossAlign === 'near') { + textAlign = 'left'; + } else if (crossAlign === 'center') { + textAlign = 'center'; + x += widest / 2; + } else { + textAlign = 'right'; + x = this.right; + } + } + } else { + textAlign = 'right'; + } + return { + textAlign, + x + }; + } + _computeLabelArea() { + if (this.options.ticks.mirror) { + return; + } + const chart = this.chart; + const position = this.options.position; + if (position === 'left' || position === 'right') { + return { + top: 0, + left: this.left, + bottom: chart.height, + right: this.right + }; + } + if (position === 'top' || position === 'bottom') { + return { + top: this.top, + left: 0, + bottom: this.bottom, + right: chart.width + }; + } + } + drawBackground() { + const { ctx , options: { backgroundColor } , left , top , width , height } = this; + if (backgroundColor) { + ctx.save(); + ctx.fillStyle = backgroundColor; + ctx.fillRect(left, top, width, height); + ctx.restore(); + } + } + getLineWidthForValue(value) { + const grid = this.options.grid; + if (!this._isVisible() || !grid.display) { + return 0; + } + const ticks = this.ticks; + const index = ticks.findIndex((t)=>t.value === value); + if (index >= 0) { + const opts = grid.setContext(this.getContext(index)); + return opts.lineWidth; + } + return 0; + } + drawGrid(chartArea) { + const grid = this.options.grid; + const ctx = this.ctx; + const items = this._gridLineItems || (this._gridLineItems = this._computeGridLineItems(chartArea)); + let i, ilen; + const drawLine = (p1, p2, style)=>{ + if (!style.width || !style.color) { + return; + } + ctx.save(); + ctx.lineWidth = style.width; + ctx.strokeStyle = style.color; + ctx.setLineDash(style.borderDash || []); + ctx.lineDashOffset = style.borderDashOffset; + ctx.beginPath(); + ctx.moveTo(p1.x, p1.y); + ctx.lineTo(p2.x, p2.y); + ctx.stroke(); + ctx.restore(); + }; + if (grid.display) { + for(i = 0, ilen = items.length; i < ilen; ++i){ + const item = items[i]; + if (grid.drawOnChartArea) { + drawLine({ + x: item.x1, + y: item.y1 + }, { + x: item.x2, + y: item.y2 + }, item); + } + if (grid.drawTicks) { + drawLine({ + x: item.tx1, + y: item.ty1 + }, { + x: item.tx2, + y: item.ty2 + }, { + color: item.tickColor, + width: item.tickWidth, + borderDash: item.tickBorderDash, + borderDashOffset: item.tickBorderDashOffset + }); + } + } + } + } + drawBorder() { + const { chart , ctx , options: { border , grid } } = this; + const borderOpts = border.setContext(this.getContext()); + const axisWidth = border.display ? borderOpts.width : 0; + if (!axisWidth) { + return; + } + const lastLineWidth = grid.setContext(this.getContext(0)).lineWidth; + const borderValue = this._borderValue; + let x1, x2, y1, y2; + if (this.isHorizontal()) { + x1 = _alignPixel(chart, this.left, axisWidth) - axisWidth / 2; + x2 = _alignPixel(chart, this.right, lastLineWidth) + lastLineWidth / 2; + y1 = y2 = borderValue; + } else { + y1 = _alignPixel(chart, this.top, axisWidth) - axisWidth / 2; + y2 = _alignPixel(chart, this.bottom, lastLineWidth) + lastLineWidth / 2; + x1 = x2 = borderValue; + } + ctx.save(); + ctx.lineWidth = borderOpts.width; + ctx.strokeStyle = borderOpts.color; + ctx.beginPath(); + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + ctx.stroke(); + ctx.restore(); + } + drawLabels(chartArea) { + const optionTicks = this.options.ticks; + if (!optionTicks.display) { + return; + } + const ctx = this.ctx; + const area = this._computeLabelArea(); + if (area) { + clipArea(ctx, area); + } + const items = this.getLabelItems(chartArea); + for (const item of items){ + const renderTextOptions = item.options; + const tickFont = item.font; + const label = item.label; + const y = item.textOffset; + renderText(ctx, label, 0, y, tickFont, renderTextOptions); + } + if (area) { + unclipArea(ctx); + } + } + drawTitle() { + const { ctx , options: { position , title , reverse } } = this; + if (!title.display) { + return; + } + const font = toFont(title.font); + const padding = toPadding(title.padding); + const align = title.align; + let offset = font.lineHeight / 2; + if (position === 'bottom' || position === 'center' || isObject(position)) { + offset += padding.bottom; + if (isArray(title.text)) { + offset += font.lineHeight * (title.text.length - 1); + } + } else { + offset += padding.top; + } + const { titleX , titleY , maxWidth , rotation } = titleArgs(this, offset, position, align); + renderText(ctx, title.text, 0, 0, font, { + color: title.color, + maxWidth, + rotation, + textAlign: titleAlign(align, position, reverse), + textBaseline: 'middle', + translation: [ + titleX, + titleY + ] + }); + } + draw(chartArea) { + if (!this._isVisible()) { + return; + } + this.drawBackground(); + this.drawGrid(chartArea); + this.drawBorder(); + this.drawTitle(); + this.drawLabels(chartArea); + } + _layers() { + const opts = this.options; + const tz = opts.ticks && opts.ticks.z || 0; + const gz = valueOrDefault(opts.grid && opts.grid.z, -1); + const bz = valueOrDefault(opts.border && opts.border.z, 0); + if (!this._isVisible() || this.draw !== Scale.prototype.draw) { + return [ + { + z: tz, + draw: (chartArea)=>{ + this.draw(chartArea); + } + } + ]; + } + return [ + { + z: gz, + draw: (chartArea)=>{ + this.drawBackground(); + this.drawGrid(chartArea); + this.drawTitle(); + } + }, + { + z: bz, + draw: ()=>{ + this.drawBorder(); + } + }, + { + z: tz, + draw: (chartArea)=>{ + this.drawLabels(chartArea); + } + } + ]; + } + getMatchingVisibleMetas(type) { + const metas = this.chart.getSortedVisibleDatasetMetas(); + const axisID = this.axis + 'AxisID'; + const result = []; + let i, ilen; + for(i = 0, ilen = metas.length; i < ilen; ++i){ + const meta = metas[i]; + if (meta[axisID] === this.id && (!type || meta.type === type)) { + result.push(meta); + } + } + return result; + } + _resolveTickFontOptions(index) { + const opts = this.options.ticks.setContext(this.getContext(index)); + return toFont(opts.font); + } + _maxDigits() { + const fontSize = this._resolveTickFontOptions(0).lineHeight; + return (this.isHorizontal() ? this.width : this.height) / fontSize; + } +} + +class TypedRegistry { + constructor(type, scope, override){ + this.type = type; + this.scope = scope; + this.override = override; + this.items = Object.create(null); + } + isForType(type) { + return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype); + } + register(item) { + const proto = Object.getPrototypeOf(item); + let parentScope; + if (isIChartComponent(proto)) { + parentScope = this.register(proto); + } + const items = this.items; + const id = item.id; + const scope = this.scope + '.' + id; + if (!id) { + throw new Error('class does not have id: ' + item); + } + if (id in items) { + return scope; + } + items[id] = item; + registerDefaults(item, scope, parentScope); + if (this.override) { + defaults.override(item.id, item.overrides); + } + return scope; + } + get(id) { + return this.items[id]; + } + unregister(item) { + const items = this.items; + const id = item.id; + const scope = this.scope; + if (id in items) { + delete items[id]; + } + if (scope && id in defaults[scope]) { + delete defaults[scope][id]; + if (this.override) { + delete overrides[id]; + } + } + } +} +function registerDefaults(item, scope, parentScope) { + const itemDefaults = merge(Object.create(null), [ + parentScope ? defaults.get(parentScope) : {}, + defaults.get(scope), + item.defaults + ]); + defaults.set(scope, itemDefaults); + if (item.defaultRoutes) { + routeDefaults(scope, item.defaultRoutes); + } + if (item.descriptors) { + defaults.describe(scope, item.descriptors); + } +} +function routeDefaults(scope, routes) { + Object.keys(routes).forEach((property)=>{ + const propertyParts = property.split('.'); + const sourceName = propertyParts.pop(); + const sourceScope = [ + scope + ].concat(propertyParts).join('.'); + const parts = routes[property].split('.'); + const targetName = parts.pop(); + const targetScope = parts.join('.'); + defaults.route(sourceScope, sourceName, targetScope, targetName); + }); +} +function isIChartComponent(proto) { + return 'id' in proto && 'defaults' in proto; +} + +class Registry { + constructor(){ + this.controllers = new TypedRegistry(DatasetController, 'datasets', true); + this.elements = new TypedRegistry(Element, 'elements'); + this.plugins = new TypedRegistry(Object, 'plugins'); + this.scales = new TypedRegistry(Scale, 'scales'); + this._typedRegistries = [ + this.controllers, + this.scales, + this.elements + ]; + } + add(...args) { + this._each('register', args); + } + remove(...args) { + this._each('unregister', args); + } + addControllers(...args) { + this._each('register', args, this.controllers); + } + addElements(...args) { + this._each('register', args, this.elements); + } + addPlugins(...args) { + this._each('register', args, this.plugins); + } + addScales(...args) { + this._each('register', args, this.scales); + } + getController(id) { + return this._get(id, this.controllers, 'controller'); + } + getElement(id) { + return this._get(id, this.elements, 'element'); + } + getPlugin(id) { + return this._get(id, this.plugins, 'plugin'); + } + getScale(id) { + return this._get(id, this.scales, 'scale'); + } + removeControllers(...args) { + this._each('unregister', args, this.controllers); + } + removeElements(...args) { + this._each('unregister', args, this.elements); + } + removePlugins(...args) { + this._each('unregister', args, this.plugins); + } + removeScales(...args) { + this._each('unregister', args, this.scales); + } + _each(method, args, typedRegistry) { + [ + ...args + ].forEach((arg)=>{ + const reg = typedRegistry || this._getRegistryForType(arg); + if (typedRegistry || reg.isForType(arg) || reg === this.plugins && arg.id) { + this._exec(method, reg, arg); + } else { + each(arg, (item)=>{ + const itemReg = typedRegistry || this._getRegistryForType(item); + this._exec(method, itemReg, item); + }); + } + }); + } + _exec(method, registry, component) { + const camelMethod = _capitalize(method); + callback(component['before' + camelMethod], [], component); + registry[method](component); + callback(component['after' + camelMethod], [], component); + } + _getRegistryForType(type) { + for(let i = 0; i < this._typedRegistries.length; i++){ + const reg = this._typedRegistries[i]; + if (reg.isForType(type)) { + return reg; + } + } + return this.plugins; + } + _get(id, typedRegistry, type) { + const item = typedRegistry.get(id); + if (item === undefined) { + throw new Error('"' + id + '" is not a registered ' + type + '.'); + } + return item; + } +} +var registry = /* #__PURE__ */ new Registry(); + +class PluginService { + constructor(){ + this._init = []; + } + notify(chart, hook, args, filter) { + if (hook === 'beforeInit') { + this._init = this._createDescriptors(chart, true); + this._notify(this._init, chart, 'install'); + } + const descriptors = filter ? this._descriptors(chart).filter(filter) : this._descriptors(chart); + const result = this._notify(descriptors, chart, hook, args); + if (hook === 'afterDestroy') { + this._notify(descriptors, chart, 'stop'); + this._notify(this._init, chart, 'uninstall'); + } + return result; + } + _notify(descriptors, chart, hook, args) { + args = args || {}; + for (const descriptor of descriptors){ + const plugin = descriptor.plugin; + const method = plugin[hook]; + const params = [ + chart, + args, + descriptor.options + ]; + if (callback(method, params, plugin) === false && args.cancelable) { + return false; + } + } + return true; + } + invalidate() { + if (!isNullOrUndef(this._cache)) { + this._oldCache = this._cache; + this._cache = undefined; + } + } + _descriptors(chart) { + if (this._cache) { + return this._cache; + } + const descriptors = this._cache = this._createDescriptors(chart); + this._notifyStateChanges(chart); + return descriptors; + } + _createDescriptors(chart, all) { + const config = chart && chart.config; + const options = valueOrDefault(config.options && config.options.plugins, {}); + const plugins = allPlugins(config); + return options === false && !all ? [] : createDescriptors(chart, plugins, options, all); + } + _notifyStateChanges(chart) { + const previousDescriptors = this._oldCache || []; + const descriptors = this._cache; + const diff = (a, b)=>a.filter((x)=>!b.some((y)=>x.plugin.id === y.plugin.id)); + this._notify(diff(previousDescriptors, descriptors), chart, 'stop'); + this._notify(diff(descriptors, previousDescriptors), chart, 'start'); + } +} + function allPlugins(config) { + const localIds = {}; + const plugins = []; + const keys = Object.keys(registry.plugins.items); + for(let i = 0; i < keys.length; i++){ + plugins.push(registry.getPlugin(keys[i])); + } + const local = config.plugins || []; + for(let i = 0; i < local.length; i++){ + const plugin = local[i]; + if (plugins.indexOf(plugin) === -1) { + plugins.push(plugin); + localIds[plugin.id] = true; + } + } + return { + plugins, + localIds + }; +} +function getOpts(options, all) { + if (!all && options === false) { + return null; + } + if (options === true) { + return {}; + } + return options; +} +function createDescriptors(chart, { plugins , localIds }, options, all) { + const result = []; + const context = chart.getContext(); + for (const plugin of plugins){ + const id = plugin.id; + const opts = getOpts(options[id], all); + if (opts === null) { + continue; + } + result.push({ + plugin, + options: pluginOpts(chart.config, { + plugin, + local: localIds[id] + }, opts, context) + }); + } + return result; +} +function pluginOpts(config, { plugin , local }, opts, context) { + const keys = config.pluginScopeKeys(plugin); + const scopes = config.getOptionScopes(opts, keys); + if (local && plugin.defaults) { + scopes.push(plugin.defaults); + } + return config.createResolver(scopes, context, [ + '' + ], { + scriptable: false, + indexable: false, + allKeys: true + }); +} + +function getIndexAxis(type, options) { + const datasetDefaults = defaults.datasets[type] || {}; + const datasetOptions = (options.datasets || {})[type] || {}; + return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x'; +} +function getAxisFromDefaultScaleID(id, indexAxis) { + let axis = id; + if (id === '_index_') { + axis = indexAxis; + } else if (id === '_value_') { + axis = indexAxis === 'x' ? 'y' : 'x'; + } + return axis; +} +function getDefaultScaleIDFromAxis(axis, indexAxis) { + return axis === indexAxis ? '_index_' : '_value_'; +} +function idMatchesAxis(id) { + if (id === 'x' || id === 'y' || id === 'r') { + return id; + } +} +function axisFromPosition(position) { + if (position === 'top' || position === 'bottom') { + return 'x'; + } + if (position === 'left' || position === 'right') { + return 'y'; + } +} +function determineAxis(id, ...scaleOptions) { + if (idMatchesAxis(id)) { + return id; + } + for (const opts of scaleOptions){ + const axis = opts.axis || axisFromPosition(opts.position) || id.length > 1 && idMatchesAxis(id[0].toLowerCase()); + if (axis) { + return axis; + } + } + throw new Error(`Cannot determine type of '${id}' axis. Please provide 'axis' or 'position' option.`); +} +function getAxisFromDataset(id, axis, dataset) { + if (dataset[axis + 'AxisID'] === id) { + return { + axis + }; + } +} +function retrieveAxisFromDatasets(id, config) { + if (config.data && config.data.datasets) { + const boundDs = config.data.datasets.filter((d)=>d.xAxisID === id || d.yAxisID === id); + if (boundDs.length) { + return getAxisFromDataset(id, 'x', boundDs[0]) || getAxisFromDataset(id, 'y', boundDs[0]); + } + } + return {}; +} +function mergeScaleConfig(config, options) { + const chartDefaults = overrides[config.type] || { + scales: {} + }; + const configScales = options.scales || {}; + const chartIndexAxis = getIndexAxis(config.type, options); + const scales = Object.create(null); + Object.keys(configScales).forEach((id)=>{ + const scaleConf = configScales[id]; + if (!isObject(scaleConf)) { + return console.error(`Invalid scale configuration for scale: ${id}`); + } + if (scaleConf._proxy) { + return console.warn(`Ignoring resolver passed as options for scale: ${id}`); + } + const axis = determineAxis(id, scaleConf, retrieveAxisFromDatasets(id, config), defaults.scales[scaleConf.type]); + const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis); + const defaultScaleOptions = chartDefaults.scales || {}; + scales[id] = mergeIf(Object.create(null), [ + { + axis + }, + scaleConf, + defaultScaleOptions[axis], + defaultScaleOptions[defaultId] + ]); + }); + config.data.datasets.forEach((dataset)=>{ + const type = dataset.type || config.type; + const indexAxis = dataset.indexAxis || getIndexAxis(type, options); + const datasetDefaults = overrides[type] || {}; + const defaultScaleOptions = datasetDefaults.scales || {}; + Object.keys(defaultScaleOptions).forEach((defaultID)=>{ + const axis = getAxisFromDefaultScaleID(defaultID, indexAxis); + const id = dataset[axis + 'AxisID'] || axis; + scales[id] = scales[id] || Object.create(null); + mergeIf(scales[id], [ + { + axis + }, + configScales[id], + defaultScaleOptions[defaultID] + ]); + }); + }); + Object.keys(scales).forEach((key)=>{ + const scale = scales[key]; + mergeIf(scale, [ + defaults.scales[scale.type], + defaults.scale + ]); + }); + return scales; +} +function initOptions(config) { + const options = config.options || (config.options = {}); + options.plugins = valueOrDefault(options.plugins, {}); + options.scales = mergeScaleConfig(config, options); +} +function initData(data) { + data = data || {}; + data.datasets = data.datasets || []; + data.labels = data.labels || []; + return data; +} +function initConfig(config) { + config = config || {}; + config.data = initData(config.data); + initOptions(config); + return config; +} +const keyCache = new Map(); +const keysCached = new Set(); +function cachedKeys(cacheKey, generate) { + let keys = keyCache.get(cacheKey); + if (!keys) { + keys = generate(); + keyCache.set(cacheKey, keys); + keysCached.add(keys); + } + return keys; +} +const addIfFound = (set, obj, key)=>{ + const opts = resolveObjectKey(obj, key); + if (opts !== undefined) { + set.add(opts); + } +}; +class Config { + constructor(config){ + this._config = initConfig(config); + this._scopeCache = new Map(); + this._resolverCache = new Map(); + } + get platform() { + return this._config.platform; + } + get type() { + return this._config.type; + } + set type(type) { + this._config.type = type; + } + get data() { + return this._config.data; + } + set data(data) { + this._config.data = initData(data); + } + get options() { + return this._config.options; + } + set options(options) { + this._config.options = options; + } + get plugins() { + return this._config.plugins; + } + update() { + const config = this._config; + this.clearCache(); + initOptions(config); + } + clearCache() { + this._scopeCache.clear(); + this._resolverCache.clear(); + } + datasetScopeKeys(datasetType) { + return cachedKeys(datasetType, ()=>[ + [ + `datasets.${datasetType}`, + '' + ] + ]); + } + datasetAnimationScopeKeys(datasetType, transition) { + return cachedKeys(`${datasetType}.transition.${transition}`, ()=>[ + [ + `datasets.${datasetType}.transitions.${transition}`, + `transitions.${transition}` + ], + [ + `datasets.${datasetType}`, + '' + ] + ]); + } + datasetElementScopeKeys(datasetType, elementType) { + return cachedKeys(`${datasetType}-${elementType}`, ()=>[ + [ + `datasets.${datasetType}.elements.${elementType}`, + `datasets.${datasetType}`, + `elements.${elementType}`, + '' + ] + ]); + } + pluginScopeKeys(plugin) { + const id = plugin.id; + const type = this.type; + return cachedKeys(`${type}-plugin-${id}`, ()=>[ + [ + `plugins.${id}`, + ...plugin.additionalOptionScopes || [] + ] + ]); + } + _cachedScopes(mainScope, resetCache) { + const _scopeCache = this._scopeCache; + let cache = _scopeCache.get(mainScope); + if (!cache || resetCache) { + cache = new Map(); + _scopeCache.set(mainScope, cache); + } + return cache; + } + getOptionScopes(mainScope, keyLists, resetCache) { + const { options , type } = this; + const cache = this._cachedScopes(mainScope, resetCache); + const cached = cache.get(keyLists); + if (cached) { + return cached; + } + const scopes = new Set(); + keyLists.forEach((keys)=>{ + if (mainScope) { + scopes.add(mainScope); + keys.forEach((key)=>addIfFound(scopes, mainScope, key)); + } + keys.forEach((key)=>addIfFound(scopes, options, key)); + keys.forEach((key)=>addIfFound(scopes, overrides[type] || {}, key)); + keys.forEach((key)=>addIfFound(scopes, defaults, key)); + keys.forEach((key)=>addIfFound(scopes, descriptors, key)); + }); + const array = Array.from(scopes); + if (array.length === 0) { + array.push(Object.create(null)); + } + if (keysCached.has(keyLists)) { + cache.set(keyLists, array); + } + return array; + } + chartOptionScopes() { + const { options , type } = this; + return [ + options, + overrides[type] || {}, + defaults.datasets[type] || {}, + { + type + }, + defaults, + descriptors + ]; + } + resolveNamedOptions(scopes, names, context, prefixes = [ + '' + ]) { + const result = { + $shared: true + }; + const { resolver , subPrefixes } = getResolver(this._resolverCache, scopes, prefixes); + let options = resolver; + if (needContext(resolver, names)) { + result.$shared = false; + context = isFunction(context) ? context() : context; + const subResolver = this.createResolver(scopes, context, subPrefixes); + options = _attachContext(resolver, context, subResolver); + } + for (const prop of names){ + result[prop] = options[prop]; + } + return result; + } + createResolver(scopes, context, prefixes = [ + '' + ], descriptorDefaults) { + const { resolver } = getResolver(this._resolverCache, scopes, prefixes); + return isObject(context) ? _attachContext(resolver, context, undefined, descriptorDefaults) : resolver; + } +} +function getResolver(resolverCache, scopes, prefixes) { + let cache = resolverCache.get(scopes); + if (!cache) { + cache = new Map(); + resolverCache.set(scopes, cache); + } + const cacheKey = prefixes.join(); + let cached = cache.get(cacheKey); + if (!cached) { + const resolver = _createResolver(scopes, prefixes); + cached = { + resolver, + subPrefixes: prefixes.filter((p)=>!p.toLowerCase().includes('hover')) + }; + cache.set(cacheKey, cached); + } + return cached; +} +const hasFunction = (value)=>isObject(value) && Object.getOwnPropertyNames(value).some((key)=>isFunction(value[key])); +function needContext(proxy, names) { + const { isScriptable , isIndexable } = _descriptors(proxy); + for (const prop of names){ + const scriptable = isScriptable(prop); + const indexable = isIndexable(prop); + const value = (indexable || scriptable) && proxy[prop]; + if (scriptable && (isFunction(value) || hasFunction(value)) || indexable && isArray(value)) { + return true; + } + } + return false; +} + +var version = "4.5.0"; + +const KNOWN_POSITIONS = [ + 'top', + 'bottom', + 'left', + 'right', + 'chartArea' +]; +function positionIsHorizontal(position, axis) { + return position === 'top' || position === 'bottom' || KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x'; +} +function compare2Level(l1, l2) { + return function(a, b) { + return a[l1] === b[l1] ? a[l2] - b[l2] : a[l1] - b[l1]; + }; +} +function onAnimationsComplete(context) { + const chart = context.chart; + const animationOptions = chart.options.animation; + chart.notifyPlugins('afterRender'); + callback(animationOptions && animationOptions.onComplete, [ + context + ], chart); +} +function onAnimationProgress(context) { + const chart = context.chart; + const animationOptions = chart.options.animation; + callback(animationOptions && animationOptions.onProgress, [ + context + ], chart); +} + function getCanvas(item) { + if (_isDomSupported() && typeof item === 'string') { + item = document.getElementById(item); + } else if (item && item.length) { + item = item[0]; + } + if (item && item.canvas) { + item = item.canvas; + } + return item; +} +const instances = {}; +const getChart = (key)=>{ + const canvas = getCanvas(key); + return Object.values(instances).filter((c)=>c.canvas === canvas).pop(); +}; +function moveNumericKeys(obj, start, move) { + const keys = Object.keys(obj); + for (const key of keys){ + const intKey = +key; + if (intKey >= start) { + const value = obj[key]; + delete obj[key]; + if (move > 0 || intKey > start) { + obj[intKey + move] = value; + } + } + } +} + function determineLastEvent(e, lastEvent, inChartArea, isClick) { + if (!inChartArea || e.type === 'mouseout') { + return null; + } + if (isClick) { + return lastEvent; + } + return e; +} +class Chart { + static defaults = defaults; + static instances = instances; + static overrides = overrides; + static registry = registry; + static version = version; + static getChart = getChart; + static register(...items) { + registry.add(...items); + invalidatePlugins(); + } + static unregister(...items) { + registry.remove(...items); + invalidatePlugins(); + } + constructor(item, userConfig){ + const config = this.config = new Config(userConfig); + const initialCanvas = getCanvas(item); + const existingChart = getChart(initialCanvas); + if (existingChart) { + throw new Error('Canvas is already in use. Chart with ID \'' + existingChart.id + '\'' + ' must be destroyed before the canvas with ID \'' + existingChart.canvas.id + '\' can be reused.'); + } + const options = config.createResolver(config.chartOptionScopes(), this.getContext()); + this.platform = new (config.platform || _detectPlatform(initialCanvas))(); + this.platform.updateConfig(config); + const context = this.platform.acquireContext(initialCanvas, options.aspectRatio); + const canvas = context && context.canvas; + const height = canvas && canvas.height; + const width = canvas && canvas.width; + this.id = uid(); + this.ctx = context; + this.canvas = canvas; + this.width = width; + this.height = height; + this._options = options; + this._aspectRatio = this.aspectRatio; + this._layers = []; + this._metasets = []; + this._stacks = undefined; + this.boxes = []; + this.currentDevicePixelRatio = undefined; + this.chartArea = undefined; + this._active = []; + this._lastEvent = undefined; + this._listeners = {}; + this._responsiveListeners = undefined; + this._sortedMetasets = []; + this.scales = {}; + this._plugins = new PluginService(); + this.$proxies = {}; + this._hiddenIndices = {}; + this.attached = false; + this._animationsDisabled = undefined; + this.$context = undefined; + this._doResize = debounce((mode)=>this.update(mode), options.resizeDelay || 0); + this._dataChanges = []; + instances[this.id] = this; + if (!context || !canvas) { + console.error("Failed to create chart: can't acquire context from the given item"); + return; + } + animator.listen(this, 'complete', onAnimationsComplete); + animator.listen(this, 'progress', onAnimationProgress); + this._initialize(); + if (this.attached) { + this.update(); + } + } + get aspectRatio() { + const { options: { aspectRatio , maintainAspectRatio } , width , height , _aspectRatio } = this; + if (!isNullOrUndef(aspectRatio)) { + return aspectRatio; + } + if (maintainAspectRatio && _aspectRatio) { + return _aspectRatio; + } + return height ? width / height : null; + } + get data() { + return this.config.data; + } + set data(data) { + this.config.data = data; + } + get options() { + return this._options; + } + set options(options) { + this.config.options = options; + } + get registry() { + return registry; + } + _initialize() { + this.notifyPlugins('beforeInit'); + if (this.options.responsive) { + this.resize(); + } else { + retinaScale(this, this.options.devicePixelRatio); + } + this.bindEvents(); + this.notifyPlugins('afterInit'); + return this; + } + clear() { + clearCanvas(this.canvas, this.ctx); + return this; + } + stop() { + animator.stop(this); + return this; + } + resize(width, height) { + if (!animator.running(this)) { + this._resize(width, height); + } else { + this._resizeBeforeDraw = { + width, + height + }; + } + } + _resize(width, height) { + const options = this.options; + const canvas = this.canvas; + const aspectRatio = options.maintainAspectRatio && this.aspectRatio; + const newSize = this.platform.getMaximumSize(canvas, width, height, aspectRatio); + const newRatio = options.devicePixelRatio || this.platform.getDevicePixelRatio(); + const mode = this.width ? 'resize' : 'attach'; + this.width = newSize.width; + this.height = newSize.height; + this._aspectRatio = this.aspectRatio; + if (!retinaScale(this, newRatio, true)) { + return; + } + this.notifyPlugins('resize', { + size: newSize + }); + callback(options.onResize, [ + this, + newSize + ], this); + if (this.attached) { + if (this._doResize(mode)) { + this.render(); + } + } + } + ensureScalesHaveIDs() { + const options = this.options; + const scalesOptions = options.scales || {}; + each(scalesOptions, (axisOptions, axisID)=>{ + axisOptions.id = axisID; + }); + } + buildOrUpdateScales() { + const options = this.options; + const scaleOpts = options.scales; + const scales = this.scales; + const updated = Object.keys(scales).reduce((obj, id)=>{ + obj[id] = false; + return obj; + }, {}); + let items = []; + if (scaleOpts) { + items = items.concat(Object.keys(scaleOpts).map((id)=>{ + const scaleOptions = scaleOpts[id]; + const axis = determineAxis(id, scaleOptions); + const isRadial = axis === 'r'; + const isHorizontal = axis === 'x'; + return { + options: scaleOptions, + dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left', + dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear' + }; + })); + } + each(items, (item)=>{ + const scaleOptions = item.options; + const id = scaleOptions.id; + const axis = determineAxis(id, scaleOptions); + const scaleType = valueOrDefault(scaleOptions.type, item.dtype); + if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) { + scaleOptions.position = item.dposition; + } + updated[id] = true; + let scale = null; + if (id in scales && scales[id].type === scaleType) { + scale = scales[id]; + } else { + const scaleClass = registry.getScale(scaleType); + scale = new scaleClass({ + id, + type: scaleType, + ctx: this.ctx, + chart: this + }); + scales[scale.id] = scale; + } + scale.init(scaleOptions, options); + }); + each(updated, (hasUpdated, id)=>{ + if (!hasUpdated) { + delete scales[id]; + } + }); + each(scales, (scale)=>{ + layouts.configure(this, scale, scale.options); + layouts.addBox(this, scale); + }); + } + _updateMetasets() { + const metasets = this._metasets; + const numData = this.data.datasets.length; + const numMeta = metasets.length; + metasets.sort((a, b)=>a.index - b.index); + if (numMeta > numData) { + for(let i = numData; i < numMeta; ++i){ + this._destroyDatasetMeta(i); + } + metasets.splice(numData, numMeta - numData); + } + this._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index')); + } + _removeUnreferencedMetasets() { + const { _metasets: metasets , data: { datasets } } = this; + if (metasets.length > datasets.length) { + delete this._stacks; + } + metasets.forEach((meta, index)=>{ + if (datasets.filter((x)=>x === meta._dataset).length === 0) { + this._destroyDatasetMeta(index); + } + }); + } + buildOrUpdateControllers() { + const newControllers = []; + const datasets = this.data.datasets; + let i, ilen; + this._removeUnreferencedMetasets(); + for(i = 0, ilen = datasets.length; i < ilen; i++){ + const dataset = datasets[i]; + let meta = this.getDatasetMeta(i); + const type = dataset.type || this.config.type; + if (meta.type && meta.type !== type) { + this._destroyDatasetMeta(i); + meta = this.getDatasetMeta(i); + } + meta.type = type; + meta.indexAxis = dataset.indexAxis || getIndexAxis(type, this.options); + meta.order = dataset.order || 0; + meta.index = i; + meta.label = '' + dataset.label; + meta.visible = this.isDatasetVisible(i); + if (meta.controller) { + meta.controller.updateIndex(i); + meta.controller.linkScales(); + } else { + const ControllerClass = registry.getController(type); + const { datasetElementType , dataElementType } = defaults.datasets[type]; + Object.assign(ControllerClass, { + dataElementType: registry.getElement(dataElementType), + datasetElementType: datasetElementType && registry.getElement(datasetElementType) + }); + meta.controller = new ControllerClass(this, i); + newControllers.push(meta.controller); + } + } + this._updateMetasets(); + return newControllers; + } + _resetElements() { + each(this.data.datasets, (dataset, datasetIndex)=>{ + this.getDatasetMeta(datasetIndex).controller.reset(); + }, this); + } + reset() { + this._resetElements(); + this.notifyPlugins('reset'); + } + update(mode) { + const config = this.config; + config.update(); + const options = this._options = config.createResolver(config.chartOptionScopes(), this.getContext()); + const animsDisabled = this._animationsDisabled = !options.animation; + this._updateScales(); + this._checkEventBindings(); + this._updateHiddenIndices(); + this._plugins.invalidate(); + if (this.notifyPlugins('beforeUpdate', { + mode, + cancelable: true + }) === false) { + return; + } + const newControllers = this.buildOrUpdateControllers(); + this.notifyPlugins('beforeElementsUpdate'); + let minPadding = 0; + for(let i = 0, ilen = this.data.datasets.length; i < ilen; i++){ + const { controller } = this.getDatasetMeta(i); + const reset = !animsDisabled && newControllers.indexOf(controller) === -1; + controller.buildOrUpdateElements(reset); + minPadding = Math.max(+controller.getMaxOverflow(), minPadding); + } + minPadding = this._minPadding = options.layout.autoPadding ? minPadding : 0; + this._updateLayout(minPadding); + if (!animsDisabled) { + each(newControllers, (controller)=>{ + controller.reset(); + }); + } + this._updateDatasets(mode); + this.notifyPlugins('afterUpdate', { + mode + }); + this._layers.sort(compare2Level('z', '_idx')); + const { _active , _lastEvent } = this; + if (_lastEvent) { + this._eventHandler(_lastEvent, true); + } else if (_active.length) { + this._updateHoverStyles(_active, _active, true); + } + this.render(); + } + _updateScales() { + each(this.scales, (scale)=>{ + layouts.removeBox(this, scale); + }); + this.ensureScalesHaveIDs(); + this.buildOrUpdateScales(); + } + _checkEventBindings() { + const options = this.options; + const existingEvents = new Set(Object.keys(this._listeners)); + const newEvents = new Set(options.events); + if (!setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== options.responsive) { + this.unbindEvents(); + this.bindEvents(); + } + } + _updateHiddenIndices() { + const { _hiddenIndices } = this; + const changes = this._getUniformDataChanges() || []; + for (const { method , start , count } of changes){ + const move = method === '_removeElements' ? -count : count; + moveNumericKeys(_hiddenIndices, start, move); + } + } + _getUniformDataChanges() { + const _dataChanges = this._dataChanges; + if (!_dataChanges || !_dataChanges.length) { + return; + } + this._dataChanges = []; + const datasetCount = this.data.datasets.length; + const makeSet = (idx)=>new Set(_dataChanges.filter((c)=>c[0] === idx).map((c, i)=>i + ',' + c.splice(1).join(','))); + const changeSet = makeSet(0); + for(let i = 1; i < datasetCount; i++){ + if (!setsEqual(changeSet, makeSet(i))) { + return; + } + } + return Array.from(changeSet).map((c)=>c.split(',')).map((a)=>({ + method: a[1], + start: +a[2], + count: +a[3] + })); + } + _updateLayout(minPadding) { + if (this.notifyPlugins('beforeLayout', { + cancelable: true + }) === false) { + return; + } + layouts.update(this, this.width, this.height, minPadding); + const area = this.chartArea; + const noArea = area.width <= 0 || area.height <= 0; + this._layers = []; + each(this.boxes, (box)=>{ + if (noArea && box.position === 'chartArea') { + return; + } + if (box.configure) { + box.configure(); + } + this._layers.push(...box._layers()); + }, this); + this._layers.forEach((item, index)=>{ + item._idx = index; + }); + this.notifyPlugins('afterLayout'); + } + _updateDatasets(mode) { + if (this.notifyPlugins('beforeDatasetsUpdate', { + mode, + cancelable: true + }) === false) { + return; + } + for(let i = 0, ilen = this.data.datasets.length; i < ilen; ++i){ + this.getDatasetMeta(i).controller.configure(); + } + for(let i = 0, ilen = this.data.datasets.length; i < ilen; ++i){ + this._updateDataset(i, isFunction(mode) ? mode({ + datasetIndex: i + }) : mode); + } + this.notifyPlugins('afterDatasetsUpdate', { + mode + }); + } + _updateDataset(index, mode) { + const meta = this.getDatasetMeta(index); + const args = { + meta, + index, + mode, + cancelable: true + }; + if (this.notifyPlugins('beforeDatasetUpdate', args) === false) { + return; + } + meta.controller._update(mode); + args.cancelable = false; + this.notifyPlugins('afterDatasetUpdate', args); + } + render() { + if (this.notifyPlugins('beforeRender', { + cancelable: true + }) === false) { + return; + } + if (animator.has(this)) { + if (this.attached && !animator.running(this)) { + animator.start(this); + } + } else { + this.draw(); + onAnimationsComplete({ + chart: this + }); + } + } + draw() { + let i; + if (this._resizeBeforeDraw) { + const { width , height } = this._resizeBeforeDraw; + this._resizeBeforeDraw = null; + this._resize(width, height); + } + this.clear(); + if (this.width <= 0 || this.height <= 0) { + return; + } + if (this.notifyPlugins('beforeDraw', { + cancelable: true + }) === false) { + return; + } + const layers = this._layers; + for(i = 0; i < layers.length && layers[i].z <= 0; ++i){ + layers[i].draw(this.chartArea); + } + this._drawDatasets(); + for(; i < layers.length; ++i){ + layers[i].draw(this.chartArea); + } + this.notifyPlugins('afterDraw'); + } + _getSortedDatasetMetas(filterVisible) { + const metasets = this._sortedMetasets; + const result = []; + let i, ilen; + for(i = 0, ilen = metasets.length; i < ilen; ++i){ + const meta = metasets[i]; + if (!filterVisible || meta.visible) { + result.push(meta); + } + } + return result; + } + getSortedVisibleDatasetMetas() { + return this._getSortedDatasetMetas(true); + } + _drawDatasets() { + if (this.notifyPlugins('beforeDatasetsDraw', { + cancelable: true + }) === false) { + return; + } + const metasets = this.getSortedVisibleDatasetMetas(); + for(let i = metasets.length - 1; i >= 0; --i){ + this._drawDataset(metasets[i]); + } + this.notifyPlugins('afterDatasetsDraw'); + } + _drawDataset(meta) { + const ctx = this.ctx; + const args = { + meta, + index: meta.index, + cancelable: true + }; + const clip = getDatasetClipArea(this, meta); + if (this.notifyPlugins('beforeDatasetDraw', args) === false) { + return; + } + if (clip) { + clipArea(ctx, clip); + } + meta.controller.draw(); + if (clip) { + unclipArea(ctx); + } + args.cancelable = false; + this.notifyPlugins('afterDatasetDraw', args); + } + isPointInArea(point) { + return _isPointInArea(point, this.chartArea, this._minPadding); + } + getElementsAtEventForMode(e, mode, options, useFinalPosition) { + const method = Interaction.modes[mode]; + if (typeof method === 'function') { + return method(this, e, options, useFinalPosition); + } + return []; + } + getDatasetMeta(datasetIndex) { + const dataset = this.data.datasets[datasetIndex]; + const metasets = this._metasets; + let meta = metasets.filter((x)=>x && x._dataset === dataset).pop(); + if (!meta) { + meta = { + type: null, + data: [], + dataset: null, + controller: null, + hidden: null, + xAxisID: null, + yAxisID: null, + order: dataset && dataset.order || 0, + index: datasetIndex, + _dataset: dataset, + _parsed: [], + _sorted: false + }; + metasets.push(meta); + } + return meta; + } + getContext() { + return this.$context || (this.$context = createContext(null, { + chart: this, + type: 'chart' + })); + } + getVisibleDatasetCount() { + return this.getSortedVisibleDatasetMetas().length; + } + isDatasetVisible(datasetIndex) { + const dataset = this.data.datasets[datasetIndex]; + if (!dataset) { + return false; + } + const meta = this.getDatasetMeta(datasetIndex); + return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden; + } + setDatasetVisibility(datasetIndex, visible) { + const meta = this.getDatasetMeta(datasetIndex); + meta.hidden = !visible; + } + toggleDataVisibility(index) { + this._hiddenIndices[index] = !this._hiddenIndices[index]; + } + getDataVisibility(index) { + return !this._hiddenIndices[index]; + } + _updateVisibility(datasetIndex, dataIndex, visible) { + const mode = visible ? 'show' : 'hide'; + const meta = this.getDatasetMeta(datasetIndex); + const anims = meta.controller._resolveAnimations(undefined, mode); + if (defined(dataIndex)) { + meta.data[dataIndex].hidden = !visible; + this.update(); + } else { + this.setDatasetVisibility(datasetIndex, visible); + anims.update(meta, { + visible + }); + this.update((ctx)=>ctx.datasetIndex === datasetIndex ? mode : undefined); + } + } + hide(datasetIndex, dataIndex) { + this._updateVisibility(datasetIndex, dataIndex, false); + } + show(datasetIndex, dataIndex) { + this._updateVisibility(datasetIndex, dataIndex, true); + } + _destroyDatasetMeta(datasetIndex) { + const meta = this._metasets[datasetIndex]; + if (meta && meta.controller) { + meta.controller._destroy(); + } + delete this._metasets[datasetIndex]; + } + _stop() { + let i, ilen; + this.stop(); + animator.remove(this); + for(i = 0, ilen = this.data.datasets.length; i < ilen; ++i){ + this._destroyDatasetMeta(i); + } + } + destroy() { + this.notifyPlugins('beforeDestroy'); + const { canvas , ctx } = this; + this._stop(); + this.config.clearCache(); + if (canvas) { + this.unbindEvents(); + clearCanvas(canvas, ctx); + this.platform.releaseContext(ctx); + this.canvas = null; + this.ctx = null; + } + delete instances[this.id]; + this.notifyPlugins('afterDestroy'); + } + toBase64Image(...args) { + return this.canvas.toDataURL(...args); + } + bindEvents() { + this.bindUserEvents(); + if (this.options.responsive) { + this.bindResponsiveEvents(); + } else { + this.attached = true; + } + } + bindUserEvents() { + const listeners = this._listeners; + const platform = this.platform; + const _add = (type, listener)=>{ + platform.addEventListener(this, type, listener); + listeners[type] = listener; + }; + const listener = (e, x, y)=>{ + e.offsetX = x; + e.offsetY = y; + this._eventHandler(e); + }; + each(this.options.events, (type)=>_add(type, listener)); + } + bindResponsiveEvents() { + if (!this._responsiveListeners) { + this._responsiveListeners = {}; + } + const listeners = this._responsiveListeners; + const platform = this.platform; + const _add = (type, listener)=>{ + platform.addEventListener(this, type, listener); + listeners[type] = listener; + }; + const _remove = (type, listener)=>{ + if (listeners[type]) { + platform.removeEventListener(this, type, listener); + delete listeners[type]; + } + }; + const listener = (width, height)=>{ + if (this.canvas) { + this.resize(width, height); + } + }; + let detached; + const attached = ()=>{ + _remove('attach', attached); + this.attached = true; + this.resize(); + _add('resize', listener); + _add('detach', detached); + }; + detached = ()=>{ + this.attached = false; + _remove('resize', listener); + this._stop(); + this._resize(0, 0); + _add('attach', attached); + }; + if (platform.isAttached(this.canvas)) { + attached(); + } else { + detached(); + } + } + unbindEvents() { + each(this._listeners, (listener, type)=>{ + this.platform.removeEventListener(this, type, listener); + }); + this._listeners = {}; + each(this._responsiveListeners, (listener, type)=>{ + this.platform.removeEventListener(this, type, listener); + }); + this._responsiveListeners = undefined; + } + updateHoverStyle(items, mode, enabled) { + const prefix = enabled ? 'set' : 'remove'; + let meta, item, i, ilen; + if (mode === 'dataset') { + meta = this.getDatasetMeta(items[0].datasetIndex); + meta.controller['_' + prefix + 'DatasetHoverStyle'](); + } + for(i = 0, ilen = items.length; i < ilen; ++i){ + item = items[i]; + const controller = item && this.getDatasetMeta(item.datasetIndex).controller; + if (controller) { + controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index); + } + } + } + getActiveElements() { + return this._active || []; + } + setActiveElements(activeElements) { + const lastActive = this._active || []; + const active = activeElements.map(({ datasetIndex , index })=>{ + const meta = this.getDatasetMeta(datasetIndex); + if (!meta) { + throw new Error('No dataset found at index ' + datasetIndex); + } + return { + datasetIndex, + element: meta.data[index], + index + }; + }); + const changed = !_elementsEqual(active, lastActive); + if (changed) { + this._active = active; + this._lastEvent = null; + this._updateHoverStyles(active, lastActive); + } + } + notifyPlugins(hook, args, filter) { + return this._plugins.notify(this, hook, args, filter); + } + isPluginEnabled(pluginId) { + return this._plugins._cache.filter((p)=>p.plugin.id === pluginId).length === 1; + } + _updateHoverStyles(active, lastActive, replay) { + const hoverOptions = this.options.hover; + const diff = (a, b)=>a.filter((x)=>!b.some((y)=>x.datasetIndex === y.datasetIndex && x.index === y.index)); + const deactivated = diff(lastActive, active); + const activated = replay ? active : diff(active, lastActive); + if (deactivated.length) { + this.updateHoverStyle(deactivated, hoverOptions.mode, false); + } + if (activated.length && hoverOptions.mode) { + this.updateHoverStyle(activated, hoverOptions.mode, true); + } + } + _eventHandler(e, replay) { + const args = { + event: e, + replay, + cancelable: true, + inChartArea: this.isPointInArea(e) + }; + const eventFilter = (plugin)=>(plugin.options.events || this.options.events).includes(e.native.type); + if (this.notifyPlugins('beforeEvent', args, eventFilter) === false) { + return; + } + const changed = this._handleEvent(e, replay, args.inChartArea); + args.cancelable = false; + this.notifyPlugins('afterEvent', args, eventFilter); + if (changed || args.changed) { + this.render(); + } + return this; + } + _handleEvent(e, replay, inChartArea) { + const { _active: lastActive = [] , options } = this; + const useFinalPosition = replay; + const active = this._getActiveElements(e, lastActive, inChartArea, useFinalPosition); + const isClick = _isClickEvent(e); + const lastEvent = determineLastEvent(e, this._lastEvent, inChartArea, isClick); + if (inChartArea) { + this._lastEvent = null; + callback(options.onHover, [ + e, + active, + this + ], this); + if (isClick) { + callback(options.onClick, [ + e, + active, + this + ], this); + } + } + const changed = !_elementsEqual(active, lastActive); + if (changed || replay) { + this._active = active; + this._updateHoverStyles(active, lastActive, replay); + } + this._lastEvent = lastEvent; + return changed; + } + _getActiveElements(e, lastActive, inChartArea, useFinalPosition) { + if (e.type === 'mouseout') { + return []; + } + if (!inChartArea) { + return lastActive; + } + const hoverOptions = this.options.hover; + return this.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition); + } +} +function invalidatePlugins() { + return each(Chart.instances, (chart)=>chart._plugins.invalidate()); +} + +function clipSelf(ctx, element, endAngle) { + const { startAngle , x , y , outerRadius , innerRadius , options } = element; + const { borderWidth , borderJoinStyle } = options; + const outerAngleClip = Math.min(borderWidth / outerRadius, _normalizeAngle(startAngle - endAngle)); + ctx.beginPath(); + ctx.arc(x, y, outerRadius - borderWidth / 2, startAngle + outerAngleClip / 2, endAngle - outerAngleClip / 2); + if (innerRadius > 0) { + const innerAngleClip = Math.min(borderWidth / innerRadius, _normalizeAngle(startAngle - endAngle)); + ctx.arc(x, y, innerRadius + borderWidth / 2, endAngle - innerAngleClip / 2, startAngle + innerAngleClip / 2, true); + } else { + const clipWidth = Math.min(borderWidth / 2, outerRadius * _normalizeAngle(startAngle - endAngle)); + if (borderJoinStyle === 'round') { + ctx.arc(x, y, clipWidth, endAngle - PI / 2, startAngle + PI / 2, true); + } else if (borderJoinStyle === 'bevel') { + const r = 2 * clipWidth * clipWidth; + const endX = -r * Math.cos(endAngle + PI / 2) + x; + const endY = -r * Math.sin(endAngle + PI / 2) + y; + const startX = r * Math.cos(startAngle + PI / 2) + x; + const startY = r * Math.sin(startAngle + PI / 2) + y; + ctx.lineTo(endX, endY); + ctx.lineTo(startX, startY); + } + } + ctx.closePath(); + ctx.moveTo(0, 0); + ctx.rect(0, 0, ctx.canvas.width, ctx.canvas.height); + ctx.clip('evenodd'); +} +function clipArc(ctx, element, endAngle) { + const { startAngle , pixelMargin , x , y , outerRadius , innerRadius } = element; + let angleMargin = pixelMargin / outerRadius; + // Draw an inner border by clipping the arc and drawing a double-width border + // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders + ctx.beginPath(); + ctx.arc(x, y, outerRadius, startAngle - angleMargin, endAngle + angleMargin); + if (innerRadius > pixelMargin) { + angleMargin = pixelMargin / innerRadius; + ctx.arc(x, y, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true); + } else { + ctx.arc(x, y, pixelMargin, endAngle + HALF_PI, startAngle - HALF_PI); + } + ctx.closePath(); + ctx.clip(); +} +function toRadiusCorners(value) { + return _readValueToProps(value, [ + 'outerStart', + 'outerEnd', + 'innerStart', + 'innerEnd' + ]); +} +/** + * Parse border radius from the provided options + */ function parseBorderRadius$1(arc, innerRadius, outerRadius, angleDelta) { + const o = toRadiusCorners(arc.options.borderRadius); + const halfThickness = (outerRadius - innerRadius) / 2; + const innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2); + // Outer limits are complicated. We want to compute the available angular distance at + // a radius of outerRadius - borderRadius because for small angular distances, this term limits. + // We compute at r = outerRadius - borderRadius because this circle defines the center of the border corners. + // + // If the borderRadius is large, that value can become negative. + // This causes the outer borders to lose their radius entirely, which is rather unexpected. To solve that, if borderRadius > outerRadius + // we know that the thickness term will dominate and compute the limits at that point + const computeOuterLimit = (val)=>{ + const outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2; + return _limitValue(val, 0, Math.min(halfThickness, outerArcLimit)); + }; + return { + outerStart: computeOuterLimit(o.outerStart), + outerEnd: computeOuterLimit(o.outerEnd), + innerStart: _limitValue(o.innerStart, 0, innerLimit), + innerEnd: _limitValue(o.innerEnd, 0, innerLimit) + }; +} +/** + * Convert (r, 𝜃) to (x, y) + */ function rThetaToXY(r, theta, x, y) { + return { + x: x + r * Math.cos(theta), + y: y + r * Math.sin(theta) + }; +} +/** + * Path the arc, respecting border radius by separating into left and right halves. + * + * Start End + * + * 1--->a--->2 Outer + * / \ + * 8 3 + * | | + * | | + * 7 4 + * \ / + * 6<---b<---5 Inner + */ function pathArc(ctx, element, offset, spacing, end, circular) { + const { x , y , startAngle: start , pixelMargin , innerRadius: innerR } = element; + const outerRadius = Math.max(element.outerRadius + spacing + offset - pixelMargin, 0); + const innerRadius = innerR > 0 ? innerR + spacing + offset + pixelMargin : 0; + let spacingOffset = 0; + const alpha = end - start; + if (spacing) { + // When spacing is present, it is the same for all items + // So we adjust the start and end angle of the arc such that + // the distance is the same as it would be without the spacing + const noSpacingInnerRadius = innerR > 0 ? innerR - spacing : 0; + const noSpacingOuterRadius = outerRadius > 0 ? outerRadius - spacing : 0; + const avNogSpacingRadius = (noSpacingInnerRadius + noSpacingOuterRadius) / 2; + const adjustedAngle = avNogSpacingRadius !== 0 ? alpha * avNogSpacingRadius / (avNogSpacingRadius + spacing) : alpha; + spacingOffset = (alpha - adjustedAngle) / 2; + } + const beta = Math.max(0.001, alpha * outerRadius - offset / PI) / outerRadius; + const angleOffset = (alpha - beta) / 2; + const startAngle = start + angleOffset + spacingOffset; + const endAngle = end - angleOffset - spacingOffset; + const { outerStart , outerEnd , innerStart , innerEnd } = parseBorderRadius$1(element, innerRadius, outerRadius, endAngle - startAngle); + const outerStartAdjustedRadius = outerRadius - outerStart; + const outerEndAdjustedRadius = outerRadius - outerEnd; + const outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius; + const outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius; + const innerStartAdjustedRadius = innerRadius + innerStart; + const innerEndAdjustedRadius = innerRadius + innerEnd; + const innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius; + const innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius; + ctx.beginPath(); + if (circular) { + // The first arc segments from point 1 to point a to point 2 + const outerMidAdjustedAngle = (outerStartAdjustedAngle + outerEndAdjustedAngle) / 2; + ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerMidAdjustedAngle); + ctx.arc(x, y, outerRadius, outerMidAdjustedAngle, outerEndAdjustedAngle); + // The corner segment from point 2 to point 3 + if (outerEnd > 0) { + const pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y); + ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + HALF_PI); + } + // The line from point 3 to point 4 + const p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y); + ctx.lineTo(p4.x, p4.y); + // The corner segment from point 4 to point 5 + if (innerEnd > 0) { + const pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y); + ctx.arc(pCenter.x, pCenter.y, innerEnd, endAngle + HALF_PI, innerEndAdjustedAngle + Math.PI); + } + // The inner arc from point 5 to point b to point 6 + const innerMidAdjustedAngle = (endAngle - innerEnd / innerRadius + (startAngle + innerStart / innerRadius)) / 2; + ctx.arc(x, y, innerRadius, endAngle - innerEnd / innerRadius, innerMidAdjustedAngle, true); + ctx.arc(x, y, innerRadius, innerMidAdjustedAngle, startAngle + innerStart / innerRadius, true); + // The corner segment from point 6 to point 7 + if (innerStart > 0) { + const pCenter = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y); + ctx.arc(pCenter.x, pCenter.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - HALF_PI); + } + // The line from point 7 to point 8 + const p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y); + ctx.lineTo(p8.x, p8.y); + // The corner segment from point 8 to point 1 + if (outerStart > 0) { + const pCenter = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y); + ctx.arc(pCenter.x, pCenter.y, outerStart, startAngle - HALF_PI, outerStartAdjustedAngle); + } + } else { + ctx.moveTo(x, y); + const outerStartX = Math.cos(outerStartAdjustedAngle) * outerRadius + x; + const outerStartY = Math.sin(outerStartAdjustedAngle) * outerRadius + y; + ctx.lineTo(outerStartX, outerStartY); + const outerEndX = Math.cos(outerEndAdjustedAngle) * outerRadius + x; + const outerEndY = Math.sin(outerEndAdjustedAngle) * outerRadius + y; + ctx.lineTo(outerEndX, outerEndY); + } + ctx.closePath(); +} +function drawArc(ctx, element, offset, spacing, circular) { + const { fullCircles , startAngle , circumference } = element; + let endAngle = element.endAngle; + if (fullCircles) { + pathArc(ctx, element, offset, spacing, endAngle, circular); + for(let i = 0; i < fullCircles; ++i){ + ctx.fill(); + } + if (!isNaN(circumference)) { + endAngle = startAngle + (circumference % TAU || TAU); + } + } + pathArc(ctx, element, offset, spacing, endAngle, circular); + ctx.fill(); + return endAngle; +} +function drawBorder(ctx, element, offset, spacing, circular) { + const { fullCircles , startAngle , circumference , options } = element; + const { borderWidth , borderJoinStyle , borderDash , borderDashOffset , borderRadius } = options; + const inner = options.borderAlign === 'inner'; + if (!borderWidth) { + return; + } + ctx.setLineDash(borderDash || []); + ctx.lineDashOffset = borderDashOffset; + if (inner) { + ctx.lineWidth = borderWidth * 2; + ctx.lineJoin = borderJoinStyle || 'round'; + } else { + ctx.lineWidth = borderWidth; + ctx.lineJoin = borderJoinStyle || 'bevel'; + } + let endAngle = element.endAngle; + if (fullCircles) { + pathArc(ctx, element, offset, spacing, endAngle, circular); + for(let i = 0; i < fullCircles; ++i){ + ctx.stroke(); + } + if (!isNaN(circumference)) { + endAngle = startAngle + (circumference % TAU || TAU); + } + } + if (inner) { + clipArc(ctx, element, endAngle); + } + if (options.selfJoin && endAngle - startAngle >= PI && borderRadius === 0 && borderJoinStyle !== 'miter') { + clipSelf(ctx, element, endAngle); + } + if (!fullCircles) { + pathArc(ctx, element, offset, spacing, endAngle, circular); + ctx.stroke(); + } +} +class ArcElement extends Element { + static id = 'arc'; + static defaults = { + borderAlign: 'center', + borderColor: '#fff', + borderDash: [], + borderDashOffset: 0, + borderJoinStyle: undefined, + borderRadius: 0, + borderWidth: 2, + offset: 0, + spacing: 0, + angle: undefined, + circular: true, + selfJoin: false + }; + static defaultRoutes = { + backgroundColor: 'backgroundColor' + }; + static descriptors = { + _scriptable: true, + _indexable: (name)=>name !== 'borderDash' + }; + circumference; + endAngle; + fullCircles; + innerRadius; + outerRadius; + pixelMargin; + startAngle; + constructor(cfg){ + super(); + this.options = undefined; + this.circumference = undefined; + this.startAngle = undefined; + this.endAngle = undefined; + this.innerRadius = undefined; + this.outerRadius = undefined; + this.pixelMargin = 0; + this.fullCircles = 0; + if (cfg) { + Object.assign(this, cfg); + } + } + inRange(chartX, chartY, useFinalPosition) { + const point = this.getProps([ + 'x', + 'y' + ], useFinalPosition); + const { angle , distance } = getAngleFromPoint(point, { + x: chartX, + y: chartY + }); + const { startAngle , endAngle , innerRadius , outerRadius , circumference } = this.getProps([ + 'startAngle', + 'endAngle', + 'innerRadius', + 'outerRadius', + 'circumference' + ], useFinalPosition); + const rAdjust = (this.options.spacing + this.options.borderWidth) / 2; + const _circumference = valueOrDefault(circumference, endAngle - startAngle); + const nonZeroBetween = _angleBetween(angle, startAngle, endAngle) && startAngle !== endAngle; + const betweenAngles = _circumference >= TAU || nonZeroBetween; + const withinRadius = _isBetween(distance, innerRadius + rAdjust, outerRadius + rAdjust); + return betweenAngles && withinRadius; + } + getCenterPoint(useFinalPosition) { + const { x , y , startAngle , endAngle , innerRadius , outerRadius } = this.getProps([ + 'x', + 'y', + 'startAngle', + 'endAngle', + 'innerRadius', + 'outerRadius' + ], useFinalPosition); + const { offset , spacing } = this.options; + const halfAngle = (startAngle + endAngle) / 2; + const halfRadius = (innerRadius + outerRadius + spacing + offset) / 2; + return { + x: x + Math.cos(halfAngle) * halfRadius, + y: y + Math.sin(halfAngle) * halfRadius + }; + } + tooltipPosition(useFinalPosition) { + return this.getCenterPoint(useFinalPosition); + } + draw(ctx) { + const { options , circumference } = this; + const offset = (options.offset || 0) / 4; + const spacing = (options.spacing || 0) / 2; + const circular = options.circular; + this.pixelMargin = options.borderAlign === 'inner' ? 0.33 : 0; + this.fullCircles = circumference > TAU ? Math.floor(circumference / TAU) : 0; + if (circumference === 0 || this.innerRadius < 0 || this.outerRadius < 0) { + return; + } + ctx.save(); + const halfAngle = (this.startAngle + this.endAngle) / 2; + ctx.translate(Math.cos(halfAngle) * offset, Math.sin(halfAngle) * offset); + const fix = 1 - Math.sin(Math.min(PI, circumference || 0)); + const radiusOffset = offset * fix; + ctx.fillStyle = options.backgroundColor; + ctx.strokeStyle = options.borderColor; + drawArc(ctx, this, radiusOffset, spacing, circular); + drawBorder(ctx, this, radiusOffset, spacing, circular); + ctx.restore(); + } +} + +function setStyle(ctx, options, style = options) { + ctx.lineCap = valueOrDefault(style.borderCapStyle, options.borderCapStyle); + ctx.setLineDash(valueOrDefault(style.borderDash, options.borderDash)); + ctx.lineDashOffset = valueOrDefault(style.borderDashOffset, options.borderDashOffset); + ctx.lineJoin = valueOrDefault(style.borderJoinStyle, options.borderJoinStyle); + ctx.lineWidth = valueOrDefault(style.borderWidth, options.borderWidth); + ctx.strokeStyle = valueOrDefault(style.borderColor, options.borderColor); +} +function lineTo(ctx, previous, target) { + ctx.lineTo(target.x, target.y); +} + function getLineMethod(options) { + if (options.stepped) { + return _steppedLineTo; + } + if (options.tension || options.cubicInterpolationMode === 'monotone') { + return _bezierCurveTo; + } + return lineTo; +} +function pathVars(points, segment, params = {}) { + const count = points.length; + const { start: paramsStart = 0 , end: paramsEnd = count - 1 } = params; + const { start: segmentStart , end: segmentEnd } = segment; + const start = Math.max(paramsStart, segmentStart); + const end = Math.min(paramsEnd, segmentEnd); + const outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd; + return { + count, + start, + loop: segment.loop, + ilen: end < start && !outside ? count + end - start : end - start + }; +} + function pathSegment(ctx, line, segment, params) { + const { points , options } = line; + const { count , start , loop , ilen } = pathVars(points, segment, params); + const lineMethod = getLineMethod(options); + let { move =true , reverse } = params || {}; + let i, point, prev; + for(i = 0; i <= ilen; ++i){ + point = points[(start + (reverse ? ilen - i : i)) % count]; + if (point.skip) { + continue; + } else if (move) { + ctx.moveTo(point.x, point.y); + move = false; + } else { + lineMethod(ctx, prev, point, reverse, options.stepped); + } + prev = point; + } + if (loop) { + point = points[(start + (reverse ? ilen : 0)) % count]; + lineMethod(ctx, prev, point, reverse, options.stepped); + } + return !!loop; +} + function fastPathSegment(ctx, line, segment, params) { + const points = line.points; + const { count , start , ilen } = pathVars(points, segment, params); + const { move =true , reverse } = params || {}; + let avgX = 0; + let countX = 0; + let i, point, prevX, minY, maxY, lastY; + const pointIndex = (index)=>(start + (reverse ? ilen - index : index)) % count; + const drawX = ()=>{ + if (minY !== maxY) { + ctx.lineTo(avgX, maxY); + ctx.lineTo(avgX, minY); + ctx.lineTo(avgX, lastY); + } + }; + if (move) { + point = points[pointIndex(0)]; + ctx.moveTo(point.x, point.y); + } + for(i = 0; i <= ilen; ++i){ + point = points[pointIndex(i)]; + if (point.skip) { + continue; + } + const x = point.x; + const y = point.y; + const truncX = x | 0; + if (truncX === prevX) { + if (y < minY) { + minY = y; + } else if (y > maxY) { + maxY = y; + } + avgX = (countX * avgX + x) / ++countX; + } else { + drawX(); + ctx.lineTo(x, y); + prevX = truncX; + countX = 0; + minY = maxY = y; + } + lastY = y; + } + drawX(); +} + function _getSegmentMethod(line) { + const opts = line.options; + const borderDash = opts.borderDash && opts.borderDash.length; + const useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== 'monotone' && !opts.stepped && !borderDash; + return useFastPath ? fastPathSegment : pathSegment; +} + function _getInterpolationMethod(options) { + if (options.stepped) { + return _steppedInterpolation; + } + if (options.tension || options.cubicInterpolationMode === 'monotone') { + return _bezierInterpolation; + } + return _pointInLine; +} +function strokePathWithCache(ctx, line, start, count) { + let path = line._path; + if (!path) { + path = line._path = new Path2D(); + if (line.path(path, start, count)) { + path.closePath(); + } + } + setStyle(ctx, line.options); + ctx.stroke(path); +} +function strokePathDirect(ctx, line, start, count) { + const { segments , options } = line; + const segmentMethod = _getSegmentMethod(line); + for (const segment of segments){ + setStyle(ctx, options, segment.style); + ctx.beginPath(); + if (segmentMethod(ctx, line, segment, { + start, + end: start + count - 1 + })) { + ctx.closePath(); + } + ctx.stroke(); + } +} +const usePath2D = typeof Path2D === 'function'; +function draw(ctx, line, start, count) { + if (usePath2D && !line.options.segment) { + strokePathWithCache(ctx, line, start, count); + } else { + strokePathDirect(ctx, line, start, count); + } +} +class LineElement extends Element { + static id = 'line'; + static defaults = { + borderCapStyle: 'butt', + borderDash: [], + borderDashOffset: 0, + borderJoinStyle: 'miter', + borderWidth: 3, + capBezierPoints: true, + cubicInterpolationMode: 'default', + fill: false, + spanGaps: false, + stepped: false, + tension: 0 + }; + static defaultRoutes = { + backgroundColor: 'backgroundColor', + borderColor: 'borderColor' + }; + static descriptors = { + _scriptable: true, + _indexable: (name)=>name !== 'borderDash' && name !== 'fill' + }; + constructor(cfg){ + super(); + this.animated = true; + this.options = undefined; + this._chart = undefined; + this._loop = undefined; + this._fullLoop = undefined; + this._path = undefined; + this._points = undefined; + this._segments = undefined; + this._decimated = false; + this._pointsUpdated = false; + this._datasetIndex = undefined; + if (cfg) { + Object.assign(this, cfg); + } + } + updateControlPoints(chartArea, indexAxis) { + const options = this.options; + if ((options.tension || options.cubicInterpolationMode === 'monotone') && !options.stepped && !this._pointsUpdated) { + const loop = options.spanGaps ? this._loop : this._fullLoop; + _updateBezierControlPoints(this._points, options, chartArea, loop, indexAxis); + this._pointsUpdated = true; + } + } + set points(points) { + this._points = points; + delete this._segments; + delete this._path; + this._pointsUpdated = false; + } + get points() { + return this._points; + } + get segments() { + return this._segments || (this._segments = _computeSegments(this, this.options.segment)); + } + first() { + const segments = this.segments; + const points = this.points; + return segments.length && points[segments[0].start]; + } + last() { + const segments = this.segments; + const points = this.points; + const count = segments.length; + return count && points[segments[count - 1].end]; + } + interpolate(point, property) { + const options = this.options; + const value = point[property]; + const points = this.points; + const segments = _boundSegments(this, { + property, + start: value, + end: value + }); + if (!segments.length) { + return; + } + const result = []; + const _interpolate = _getInterpolationMethod(options); + let i, ilen; + for(i = 0, ilen = segments.length; i < ilen; ++i){ + const { start , end } = segments[i]; + const p1 = points[start]; + const p2 = points[end]; + if (p1 === p2) { + result.push(p1); + continue; + } + const t = Math.abs((value - p1[property]) / (p2[property] - p1[property])); + const interpolated = _interpolate(p1, p2, t, options.stepped); + interpolated[property] = point[property]; + result.push(interpolated); + } + return result.length === 1 ? result[0] : result; + } + pathSegment(ctx, segment, params) { + const segmentMethod = _getSegmentMethod(this); + return segmentMethod(ctx, this, segment, params); + } + path(ctx, start, count) { + const segments = this.segments; + const segmentMethod = _getSegmentMethod(this); + let loop = this._loop; + start = start || 0; + count = count || this.points.length - start; + for (const segment of segments){ + loop &= segmentMethod(ctx, this, segment, { + start, + end: start + count - 1 + }); + } + return !!loop; + } + draw(ctx, chartArea, start, count) { + const options = this.options || {}; + const points = this.points || []; + if (points.length && options.borderWidth) { + ctx.save(); + draw(ctx, this, start, count); + ctx.restore(); + } + if (this.animated) { + this._pointsUpdated = false; + this._path = undefined; + } + } +} + +function inRange$1(el, pos, axis, useFinalPosition) { + const options = el.options; + const { [axis]: value } = el.getProps([ + axis + ], useFinalPosition); + return Math.abs(pos - value) < options.radius + options.hitRadius; +} +class PointElement extends Element { + static id = 'point'; + parsed; + skip; + stop; + /** + * @type {any} + */ static defaults = { + borderWidth: 1, + hitRadius: 1, + hoverBorderWidth: 1, + hoverRadius: 4, + pointStyle: 'circle', + radius: 3, + rotation: 0 + }; + /** + * @type {any} + */ static defaultRoutes = { + backgroundColor: 'backgroundColor', + borderColor: 'borderColor' + }; + constructor(cfg){ + super(); + this.options = undefined; + this.parsed = undefined; + this.skip = undefined; + this.stop = undefined; + if (cfg) { + Object.assign(this, cfg); + } + } + inRange(mouseX, mouseY, useFinalPosition) { + const options = this.options; + const { x , y } = this.getProps([ + 'x', + 'y' + ], useFinalPosition); + return Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2) < Math.pow(options.hitRadius + options.radius, 2); + } + inXRange(mouseX, useFinalPosition) { + return inRange$1(this, mouseX, 'x', useFinalPosition); + } + inYRange(mouseY, useFinalPosition) { + return inRange$1(this, mouseY, 'y', useFinalPosition); + } + getCenterPoint(useFinalPosition) { + const { x , y } = this.getProps([ + 'x', + 'y' + ], useFinalPosition); + return { + x, + y + }; + } + size(options) { + options = options || this.options || {}; + let radius = options.radius || 0; + radius = Math.max(radius, radius && options.hoverRadius || 0); + const borderWidth = radius && options.borderWidth || 0; + return (radius + borderWidth) * 2; + } + draw(ctx, area) { + const options = this.options; + if (this.skip || options.radius < 0.1 || !_isPointInArea(this, area, this.size(options) / 2)) { + return; + } + ctx.strokeStyle = options.borderColor; + ctx.lineWidth = options.borderWidth; + ctx.fillStyle = options.backgroundColor; + drawPoint(ctx, options, this.x, this.y); + } + getRange() { + const options = this.options || {}; + // @ts-expect-error Fallbacks should never be hit in practice + return options.radius + options.hitRadius; + } +} + +function getBarBounds(bar, useFinalPosition) { + const { x , y , base , width , height } = bar.getProps([ + 'x', + 'y', + 'base', + 'width', + 'height' + ], useFinalPosition); + let left, right, top, bottom, half; + if (bar.horizontal) { + half = height / 2; + left = Math.min(x, base); + right = Math.max(x, base); + top = y - half; + bottom = y + half; + } else { + half = width / 2; + left = x - half; + right = x + half; + top = Math.min(y, base); + bottom = Math.max(y, base); + } + return { + left, + top, + right, + bottom + }; +} +function skipOrLimit(skip, value, min, max) { + return skip ? 0 : _limitValue(value, min, max); +} +function parseBorderWidth(bar, maxW, maxH) { + const value = bar.options.borderWidth; + const skip = bar.borderSkipped; + const o = toTRBL(value); + return { + t: skipOrLimit(skip.top, o.top, 0, maxH), + r: skipOrLimit(skip.right, o.right, 0, maxW), + b: skipOrLimit(skip.bottom, o.bottom, 0, maxH), + l: skipOrLimit(skip.left, o.left, 0, maxW) + }; +} +function parseBorderRadius(bar, maxW, maxH) { + const { enableBorderRadius } = bar.getProps([ + 'enableBorderRadius' + ]); + const value = bar.options.borderRadius; + const o = toTRBLCorners(value); + const maxR = Math.min(maxW, maxH); + const skip = bar.borderSkipped; + const enableBorder = enableBorderRadius || isObject(value); + return { + topLeft: skipOrLimit(!enableBorder || skip.top || skip.left, o.topLeft, 0, maxR), + topRight: skipOrLimit(!enableBorder || skip.top || skip.right, o.topRight, 0, maxR), + bottomLeft: skipOrLimit(!enableBorder || skip.bottom || skip.left, o.bottomLeft, 0, maxR), + bottomRight: skipOrLimit(!enableBorder || skip.bottom || skip.right, o.bottomRight, 0, maxR) + }; +} +function boundingRects(bar) { + const bounds = getBarBounds(bar); + const width = bounds.right - bounds.left; + const height = bounds.bottom - bounds.top; + const border = parseBorderWidth(bar, width / 2, height / 2); + const radius = parseBorderRadius(bar, width / 2, height / 2); + return { + outer: { + x: bounds.left, + y: bounds.top, + w: width, + h: height, + radius + }, + inner: { + x: bounds.left + border.l, + y: bounds.top + border.t, + w: width - border.l - border.r, + h: height - border.t - border.b, + radius: { + topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)), + topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)), + bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)), + bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r)) + } + } + }; +} +function inRange(bar, x, y, useFinalPosition) { + const skipX = x === null; + const skipY = y === null; + const skipBoth = skipX && skipY; + const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition); + return bounds && (skipX || _isBetween(x, bounds.left, bounds.right)) && (skipY || _isBetween(y, bounds.top, bounds.bottom)); +} +function hasRadius(radius) { + return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight; +} + function addNormalRectPath(ctx, rect) { + ctx.rect(rect.x, rect.y, rect.w, rect.h); +} +function inflateRect(rect, amount, refRect = {}) { + const x = rect.x !== refRect.x ? -amount : 0; + const y = rect.y !== refRect.y ? -amount : 0; + const w = (rect.x + rect.w !== refRect.x + refRect.w ? amount : 0) - x; + const h = (rect.y + rect.h !== refRect.y + refRect.h ? amount : 0) - y; + return { + x: rect.x + x, + y: rect.y + y, + w: rect.w + w, + h: rect.h + h, + radius: rect.radius + }; +} +class BarElement extends Element { + static id = 'bar'; + static defaults = { + borderSkipped: 'start', + borderWidth: 0, + borderRadius: 0, + inflateAmount: 'auto', + pointStyle: undefined + }; + static defaultRoutes = { + backgroundColor: 'backgroundColor', + borderColor: 'borderColor' + }; + constructor(cfg){ + super(); + this.options = undefined; + this.horizontal = undefined; + this.base = undefined; + this.width = undefined; + this.height = undefined; + this.inflateAmount = undefined; + if (cfg) { + Object.assign(this, cfg); + } + } + draw(ctx) { + const { inflateAmount , options: { borderColor , backgroundColor } } = this; + const { inner , outer } = boundingRects(this); + const addRectPath = hasRadius(outer.radius) ? addRoundedRectPath : addNormalRectPath; + ctx.save(); + if (outer.w !== inner.w || outer.h !== inner.h) { + ctx.beginPath(); + addRectPath(ctx, inflateRect(outer, inflateAmount, inner)); + ctx.clip(); + addRectPath(ctx, inflateRect(inner, -inflateAmount, outer)); + ctx.fillStyle = borderColor; + ctx.fill('evenodd'); + } + ctx.beginPath(); + addRectPath(ctx, inflateRect(inner, inflateAmount)); + ctx.fillStyle = backgroundColor; + ctx.fill(); + ctx.restore(); + } + inRange(mouseX, mouseY, useFinalPosition) { + return inRange(this, mouseX, mouseY, useFinalPosition); + } + inXRange(mouseX, useFinalPosition) { + return inRange(this, mouseX, null, useFinalPosition); + } + inYRange(mouseY, useFinalPosition) { + return inRange(this, null, mouseY, useFinalPosition); + } + getCenterPoint(useFinalPosition) { + const { x , y , base , horizontal } = this.getProps([ + 'x', + 'y', + 'base', + 'horizontal' + ], useFinalPosition); + return { + x: horizontal ? (x + base) / 2 : x, + y: horizontal ? y : (y + base) / 2 + }; + } + getRange(axis) { + return axis === 'x' ? this.width / 2 : this.height / 2; + } +} + +var elements = /*#__PURE__*/Object.freeze({ +__proto__: null, +ArcElement: ArcElement, +BarElement: BarElement, +LineElement: LineElement, +PointElement: PointElement +}); + +const BORDER_COLORS = [ + 'rgb(54, 162, 235)', + 'rgb(255, 99, 132)', + 'rgb(255, 159, 64)', + 'rgb(255, 205, 86)', + 'rgb(75, 192, 192)', + 'rgb(153, 102, 255)', + 'rgb(201, 203, 207)' // grey +]; +// Border colors with 50% transparency +const BACKGROUND_COLORS = /* #__PURE__ */ BORDER_COLORS.map((color)=>color.replace('rgb(', 'rgba(').replace(')', ', 0.5)')); +function getBorderColor(i) { + return BORDER_COLORS[i % BORDER_COLORS.length]; +} +function getBackgroundColor(i) { + return BACKGROUND_COLORS[i % BACKGROUND_COLORS.length]; +} +function colorizeDefaultDataset(dataset, i) { + dataset.borderColor = getBorderColor(i); + dataset.backgroundColor = getBackgroundColor(i); + return ++i; +} +function colorizeDoughnutDataset(dataset, i) { + dataset.backgroundColor = dataset.data.map(()=>getBorderColor(i++)); + return i; +} +function colorizePolarAreaDataset(dataset, i) { + dataset.backgroundColor = dataset.data.map(()=>getBackgroundColor(i++)); + return i; +} +function getColorizer(chart) { + let i = 0; + return (dataset, datasetIndex)=>{ + const controller = chart.getDatasetMeta(datasetIndex).controller; + if (controller instanceof DoughnutController) { + i = colorizeDoughnutDataset(dataset, i); + } else if (controller instanceof PolarAreaController) { + i = colorizePolarAreaDataset(dataset, i); + } else if (controller) { + i = colorizeDefaultDataset(dataset, i); + } + }; +} +function containsColorsDefinitions(descriptors) { + let k; + for(k in descriptors){ + if (descriptors[k].borderColor || descriptors[k].backgroundColor) { + return true; + } + } + return false; +} +function containsColorsDefinition(descriptor) { + return descriptor && (descriptor.borderColor || descriptor.backgroundColor); +} +function containsDefaultColorsDefenitions() { + return defaults.borderColor !== 'rgba(0,0,0,0.1)' || defaults.backgroundColor !== 'rgba(0,0,0,0.1)'; +} +var plugin_colors = { + id: 'colors', + defaults: { + enabled: true, + forceOverride: false + }, + beforeLayout (chart, _args, options) { + if (!options.enabled) { + return; + } + const { data: { datasets } , options: chartOptions } = chart.config; + const { elements } = chartOptions; + const containsColorDefenition = containsColorsDefinitions(datasets) || containsColorsDefinition(chartOptions) || elements && containsColorsDefinitions(elements) || containsDefaultColorsDefenitions(); + if (!options.forceOverride && containsColorDefenition) { + return; + } + const colorizer = getColorizer(chart); + datasets.forEach(colorizer); + } +}; + +function lttbDecimation(data, start, count, availableWidth, options) { + const samples = options.samples || availableWidth; + if (samples >= count) { + return data.slice(start, start + count); + } + const decimated = []; + const bucketWidth = (count - 2) / (samples - 2); + let sampledIndex = 0; + const endIndex = start + count - 1; + let a = start; + let i, maxAreaPoint, maxArea, area, nextA; + decimated[sampledIndex++] = data[a]; + for(i = 0; i < samples - 2; i++){ + let avgX = 0; + let avgY = 0; + let j; + const avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start; + const avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start; + const avgRangeLength = avgRangeEnd - avgRangeStart; + for(j = avgRangeStart; j < avgRangeEnd; j++){ + avgX += data[j].x; + avgY += data[j].y; + } + avgX /= avgRangeLength; + avgY /= avgRangeLength; + const rangeOffs = Math.floor(i * bucketWidth) + 1 + start; + const rangeTo = Math.min(Math.floor((i + 1) * bucketWidth) + 1, count) + start; + const { x: pointAx , y: pointAy } = data[a]; + maxArea = area = -1; + for(j = rangeOffs; j < rangeTo; j++){ + area = 0.5 * Math.abs((pointAx - avgX) * (data[j].y - pointAy) - (pointAx - data[j].x) * (avgY - pointAy)); + if (area > maxArea) { + maxArea = area; + maxAreaPoint = data[j]; + nextA = j; + } + } + decimated[sampledIndex++] = maxAreaPoint; + a = nextA; + } + decimated[sampledIndex++] = data[endIndex]; + return decimated; +} +function minMaxDecimation(data, start, count, availableWidth) { + let avgX = 0; + let countX = 0; + let i, point, x, y, prevX, minIndex, maxIndex, startIndex, minY, maxY; + const decimated = []; + const endIndex = start + count - 1; + const xMin = data[start].x; + const xMax = data[endIndex].x; + const dx = xMax - xMin; + for(i = start; i < start + count; ++i){ + point = data[i]; + x = (point.x - xMin) / dx * availableWidth; + y = point.y; + const truncX = x | 0; + if (truncX === prevX) { + if (y < minY) { + minY = y; + minIndex = i; + } else if (y > maxY) { + maxY = y; + maxIndex = i; + } + avgX = (countX * avgX + point.x) / ++countX; + } else { + const lastIndex = i - 1; + if (!isNullOrUndef(minIndex) && !isNullOrUndef(maxIndex)) { + const intermediateIndex1 = Math.min(minIndex, maxIndex); + const intermediateIndex2 = Math.max(minIndex, maxIndex); + if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) { + decimated.push({ + ...data[intermediateIndex1], + x: avgX + }); + } + if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) { + decimated.push({ + ...data[intermediateIndex2], + x: avgX + }); + } + } + if (i > 0 && lastIndex !== startIndex) { + decimated.push(data[lastIndex]); + } + decimated.push(point); + prevX = truncX; + countX = 0; + minY = maxY = y; + minIndex = maxIndex = startIndex = i; + } + } + return decimated; +} +function cleanDecimatedDataset(dataset) { + if (dataset._decimated) { + const data = dataset._data; + delete dataset._decimated; + delete dataset._data; + Object.defineProperty(dataset, 'data', { + configurable: true, + enumerable: true, + writable: true, + value: data + }); + } +} +function cleanDecimatedData(chart) { + chart.data.datasets.forEach((dataset)=>{ + cleanDecimatedDataset(dataset); + }); +} +function getStartAndCountOfVisiblePointsSimplified(meta, points) { + const pointCount = points.length; + let start = 0; + let count; + const { iScale } = meta; + const { min , max , minDefined , maxDefined } = iScale.getUserBounds(); + if (minDefined) { + start = _limitValue(_lookupByKey(points, iScale.axis, min).lo, 0, pointCount - 1); + } + if (maxDefined) { + count = _limitValue(_lookupByKey(points, iScale.axis, max).hi + 1, start, pointCount) - start; + } else { + count = pointCount - start; + } + return { + start, + count + }; +} +var plugin_decimation = { + id: 'decimation', + defaults: { + algorithm: 'min-max', + enabled: false + }, + beforeElementsUpdate: (chart, args, options)=>{ + if (!options.enabled) { + cleanDecimatedData(chart); + return; + } + const availableWidth = chart.width; + chart.data.datasets.forEach((dataset, datasetIndex)=>{ + const { _data , indexAxis } = dataset; + const meta = chart.getDatasetMeta(datasetIndex); + const data = _data || dataset.data; + if (resolve([ + indexAxis, + chart.options.indexAxis + ]) === 'y') { + return; + } + if (!meta.controller.supportsDecimation) { + return; + } + const xAxis = chart.scales[meta.xAxisID]; + if (xAxis.type !== 'linear' && xAxis.type !== 'time') { + return; + } + if (chart.options.parsing) { + return; + } + let { start , count } = getStartAndCountOfVisiblePointsSimplified(meta, data); + const threshold = options.threshold || 4 * availableWidth; + if (count <= threshold) { + cleanDecimatedDataset(dataset); + return; + } + if (isNullOrUndef(_data)) { + dataset._data = data; + delete dataset.data; + Object.defineProperty(dataset, 'data', { + configurable: true, + enumerable: true, + get: function() { + return this._decimated; + }, + set: function(d) { + this._data = d; + } + }); + } + let decimated; + switch(options.algorithm){ + case 'lttb': + decimated = lttbDecimation(data, start, count, availableWidth, options); + break; + case 'min-max': + decimated = minMaxDecimation(data, start, count, availableWidth); + break; + default: + throw new Error(`Unsupported decimation algorithm '${options.algorithm}'`); + } + dataset._decimated = decimated; + }); + }, + destroy (chart) { + cleanDecimatedData(chart); + } +}; + +function _segments(line, target, property) { + const segments = line.segments; + const points = line.points; + const tpoints = target.points; + const parts = []; + for (const segment of segments){ + let { start , end } = segment; + end = _findSegmentEnd(start, end, points); + const bounds = _getBounds(property, points[start], points[end], segment.loop); + if (!target.segments) { + parts.push({ + source: segment, + target: bounds, + start: points[start], + end: points[end] + }); + continue; + } + const targetSegments = _boundSegments(target, bounds); + for (const tgt of targetSegments){ + const subBounds = _getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop); + const fillSources = _boundSegment(segment, points, subBounds); + for (const fillSource of fillSources){ + parts.push({ + source: fillSource, + target: tgt, + start: { + [property]: _getEdge(bounds, subBounds, 'start', Math.max) + }, + end: { + [property]: _getEdge(bounds, subBounds, 'end', Math.min) + } + }); + } + } + } + return parts; +} +function _getBounds(property, first, last, loop) { + if (loop) { + return; + } + let start = first[property]; + let end = last[property]; + if (property === 'angle') { + start = _normalizeAngle(start); + end = _normalizeAngle(end); + } + return { + property, + start, + end + }; +} +function _pointsFromSegments(boundary, line) { + const { x =null , y =null } = boundary || {}; + const linePoints = line.points; + const points = []; + line.segments.forEach(({ start , end })=>{ + end = _findSegmentEnd(start, end, linePoints); + const first = linePoints[start]; + const last = linePoints[end]; + if (y !== null) { + points.push({ + x: first.x, + y + }); + points.push({ + x: last.x, + y + }); + } else if (x !== null) { + points.push({ + x, + y: first.y + }); + points.push({ + x, + y: last.y + }); + } + }); + return points; +} +function _findSegmentEnd(start, end, points) { + for(; end > start; end--){ + const point = points[end]; + if (!isNaN(point.x) && !isNaN(point.y)) { + break; + } + } + return end; +} +function _getEdge(a, b, prop, fn) { + if (a && b) { + return fn(a[prop], b[prop]); + } + return a ? a[prop] : b ? b[prop] : 0; +} + +function _createBoundaryLine(boundary, line) { + let points = []; + let _loop = false; + if (isArray(boundary)) { + _loop = true; + points = boundary; + } else { + points = _pointsFromSegments(boundary, line); + } + return points.length ? new LineElement({ + points, + options: { + tension: 0 + }, + _loop, + _fullLoop: _loop + }) : null; +} +function _shouldApplyFill(source) { + return source && source.fill !== false; +} + +function _resolveTarget(sources, index, propagate) { + const source = sources[index]; + let fill = source.fill; + const visited = [ + index + ]; + let target; + if (!propagate) { + return fill; + } + while(fill !== false && visited.indexOf(fill) === -1){ + if (!isNumberFinite(fill)) { + return fill; + } + target = sources[fill]; + if (!target) { + return false; + } + if (target.visible) { + return fill; + } + visited.push(fill); + fill = target.fill; + } + return false; +} + function _decodeFill(line, index, count) { + const fill = parseFillOption(line); + if (isObject(fill)) { + return isNaN(fill.value) ? false : fill; + } + let target = parseFloat(fill); + if (isNumberFinite(target) && Math.floor(target) === target) { + return decodeTargetIndex(fill[0], index, target, count); + } + return [ + 'origin', + 'start', + 'end', + 'stack', + 'shape' + ].indexOf(fill) >= 0 && fill; +} +function decodeTargetIndex(firstCh, index, target, count) { + if (firstCh === '-' || firstCh === '+') { + target = index + target; + } + if (target === index || target < 0 || target >= count) { + return false; + } + return target; +} + function _getTargetPixel(fill, scale) { + let pixel = null; + if (fill === 'start') { + pixel = scale.bottom; + } else if (fill === 'end') { + pixel = scale.top; + } else if (isObject(fill)) { + pixel = scale.getPixelForValue(fill.value); + } else if (scale.getBasePixel) { + pixel = scale.getBasePixel(); + } + return pixel; +} + function _getTargetValue(fill, scale, startValue) { + let value; + if (fill === 'start') { + value = startValue; + } else if (fill === 'end') { + value = scale.options.reverse ? scale.min : scale.max; + } else if (isObject(fill)) { + value = fill.value; + } else { + value = scale.getBaseValue(); + } + return value; +} + function parseFillOption(line) { + const options = line.options; + const fillOption = options.fill; + let fill = valueOrDefault(fillOption && fillOption.target, fillOption); + if (fill === undefined) { + fill = !!options.backgroundColor; + } + if (fill === false || fill === null) { + return false; + } + if (fill === true) { + return 'origin'; + } + return fill; +} + +function _buildStackLine(source) { + const { scale , index , line } = source; + const points = []; + const segments = line.segments; + const sourcePoints = line.points; + const linesBelow = getLinesBelow(scale, index); + linesBelow.push(_createBoundaryLine({ + x: null, + y: scale.bottom + }, line)); + for(let i = 0; i < segments.length; i++){ + const segment = segments[i]; + for(let j = segment.start; j <= segment.end; j++){ + addPointsBelow(points, sourcePoints[j], linesBelow); + } + } + return new LineElement({ + points, + options: {} + }); +} + function getLinesBelow(scale, index) { + const below = []; + const metas = scale.getMatchingVisibleMetas('line'); + for(let i = 0; i < metas.length; i++){ + const meta = metas[i]; + if (meta.index === index) { + break; + } + if (!meta.hidden) { + below.unshift(meta.dataset); + } + } + return below; +} + function addPointsBelow(points, sourcePoint, linesBelow) { + const postponed = []; + for(let j = 0; j < linesBelow.length; j++){ + const line = linesBelow[j]; + const { first , last , point } = findPoint(line, sourcePoint, 'x'); + if (!point || first && last) { + continue; + } + if (first) { + postponed.unshift(point); + } else { + points.push(point); + if (!last) { + break; + } + } + } + points.push(...postponed); +} + function findPoint(line, sourcePoint, property) { + const point = line.interpolate(sourcePoint, property); + if (!point) { + return {}; + } + const pointValue = point[property]; + const segments = line.segments; + const linePoints = line.points; + let first = false; + let last = false; + for(let i = 0; i < segments.length; i++){ + const segment = segments[i]; + const firstValue = linePoints[segment.start][property]; + const lastValue = linePoints[segment.end][property]; + if (_isBetween(pointValue, firstValue, lastValue)) { + first = pointValue === firstValue; + last = pointValue === lastValue; + break; + } + } + return { + first, + last, + point + }; +} + +class simpleArc { + constructor(opts){ + this.x = opts.x; + this.y = opts.y; + this.radius = opts.radius; + } + pathSegment(ctx, bounds, opts) { + const { x , y , radius } = this; + bounds = bounds || { + start: 0, + end: TAU + }; + ctx.arc(x, y, radius, bounds.end, bounds.start, true); + return !opts.bounds; + } + interpolate(point) { + const { x , y , radius } = this; + const angle = point.angle; + return { + x: x + Math.cos(angle) * radius, + y: y + Math.sin(angle) * radius, + angle + }; + } +} + +function _getTarget(source) { + const { chart , fill , line } = source; + if (isNumberFinite(fill)) { + return getLineByIndex(chart, fill); + } + if (fill === 'stack') { + return _buildStackLine(source); + } + if (fill === 'shape') { + return true; + } + const boundary = computeBoundary(source); + if (boundary instanceof simpleArc) { + return boundary; + } + return _createBoundaryLine(boundary, line); +} + function getLineByIndex(chart, index) { + const meta = chart.getDatasetMeta(index); + const visible = meta && chart.isDatasetVisible(index); + return visible ? meta.dataset : null; +} +function computeBoundary(source) { + const scale = source.scale || {}; + if (scale.getPointPositionForValue) { + return computeCircularBoundary(source); + } + return computeLinearBoundary(source); +} +function computeLinearBoundary(source) { + const { scale ={} , fill } = source; + const pixel = _getTargetPixel(fill, scale); + if (isNumberFinite(pixel)) { + const horizontal = scale.isHorizontal(); + return { + x: horizontal ? pixel : null, + y: horizontal ? null : pixel + }; + } + return null; +} +function computeCircularBoundary(source) { + const { scale , fill } = source; + const options = scale.options; + const length = scale.getLabels().length; + const start = options.reverse ? scale.max : scale.min; + const value = _getTargetValue(fill, scale, start); + const target = []; + if (options.grid.circular) { + const center = scale.getPointPositionForValue(0, start); + return new simpleArc({ + x: center.x, + y: center.y, + radius: scale.getDistanceFromCenterForValue(value) + }); + } + for(let i = 0; i < length; ++i){ + target.push(scale.getPointPositionForValue(i, value)); + } + return target; +} + +function _drawfill(ctx, source, area) { + const target = _getTarget(source); + const { chart , index , line , scale , axis } = source; + const lineOpts = line.options; + const fillOption = lineOpts.fill; + const color = lineOpts.backgroundColor; + const { above =color , below =color } = fillOption || {}; + const meta = chart.getDatasetMeta(index); + const clip = getDatasetClipArea(chart, meta); + if (target && line.points.length) { + clipArea(ctx, area); + doFill(ctx, { + line, + target, + above, + below, + area, + scale, + axis, + clip + }); + unclipArea(ctx); + } +} +function doFill(ctx, cfg) { + const { line , target , above , below , area , scale , clip } = cfg; + const property = line._loop ? 'angle' : cfg.axis; + ctx.save(); + let fillColor = below; + if (below !== above) { + if (property === 'x') { + clipVertical(ctx, target, area.top); + fill(ctx, { + line, + target, + color: above, + scale, + property, + clip + }); + ctx.restore(); + ctx.save(); + clipVertical(ctx, target, area.bottom); + } else if (property === 'y') { + clipHorizontal(ctx, target, area.left); + fill(ctx, { + line, + target, + color: below, + scale, + property, + clip + }); + ctx.restore(); + ctx.save(); + clipHorizontal(ctx, target, area.right); + fillColor = above; + } + } + fill(ctx, { + line, + target, + color: fillColor, + scale, + property, + clip + }); + ctx.restore(); +} +function clipVertical(ctx, target, clipY) { + const { segments , points } = target; + let first = true; + let lineLoop = false; + ctx.beginPath(); + for (const segment of segments){ + const { start , end } = segment; + const firstPoint = points[start]; + const lastPoint = points[_findSegmentEnd(start, end, points)]; + if (first) { + ctx.moveTo(firstPoint.x, firstPoint.y); + first = false; + } else { + ctx.lineTo(firstPoint.x, clipY); + ctx.lineTo(firstPoint.x, firstPoint.y); + } + lineLoop = !!target.pathSegment(ctx, segment, { + move: lineLoop + }); + if (lineLoop) { + ctx.closePath(); + } else { + ctx.lineTo(lastPoint.x, clipY); + } + } + ctx.lineTo(target.first().x, clipY); + ctx.closePath(); + ctx.clip(); +} +function clipHorizontal(ctx, target, clipX) { + const { segments , points } = target; + let first = true; + let lineLoop = false; + ctx.beginPath(); + for (const segment of segments){ + const { start , end } = segment; + const firstPoint = points[start]; + const lastPoint = points[_findSegmentEnd(start, end, points)]; + if (first) { + ctx.moveTo(firstPoint.x, firstPoint.y); + first = false; + } else { + ctx.lineTo(clipX, firstPoint.y); + ctx.lineTo(firstPoint.x, firstPoint.y); + } + lineLoop = !!target.pathSegment(ctx, segment, { + move: lineLoop + }); + if (lineLoop) { + ctx.closePath(); + } else { + ctx.lineTo(clipX, lastPoint.y); + } + } + ctx.lineTo(clipX, target.first().y); + ctx.closePath(); + ctx.clip(); +} +function fill(ctx, cfg) { + const { line , target , property , color , scale , clip } = cfg; + const segments = _segments(line, target, property); + for (const { source: src , target: tgt , start , end } of segments){ + const { style: { backgroundColor =color } = {} } = src; + const notShape = target !== true; + ctx.save(); + ctx.fillStyle = backgroundColor; + clipBounds(ctx, scale, clip, notShape && _getBounds(property, start, end)); + ctx.beginPath(); + const lineLoop = !!line.pathSegment(ctx, src); + let loop; + if (notShape) { + if (lineLoop) { + ctx.closePath(); + } else { + interpolatedLineTo(ctx, target, end, property); + } + const targetLoop = !!target.pathSegment(ctx, tgt, { + move: lineLoop, + reverse: true + }); + loop = lineLoop && targetLoop; + if (!loop) { + interpolatedLineTo(ctx, target, start, property); + } + } + ctx.closePath(); + ctx.fill(loop ? 'evenodd' : 'nonzero'); + ctx.restore(); + } +} +function clipBounds(ctx, scale, clip, bounds) { + const chartArea = scale.chart.chartArea; + const { property , start , end } = bounds || {}; + if (property === 'x' || property === 'y') { + let left, top, right, bottom; + if (property === 'x') { + left = start; + top = chartArea.top; + right = end; + bottom = chartArea.bottom; + } else { + left = chartArea.left; + top = start; + right = chartArea.right; + bottom = end; + } + ctx.beginPath(); + if (clip) { + left = Math.max(left, clip.left); + right = Math.min(right, clip.right); + top = Math.max(top, clip.top); + bottom = Math.min(bottom, clip.bottom); + } + ctx.rect(left, top, right - left, bottom - top); + ctx.clip(); + } +} +function interpolatedLineTo(ctx, target, point, property) { + const interpolatedPoint = target.interpolate(point, property); + if (interpolatedPoint) { + ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y); + } +} + +var index = { + id: 'filler', + afterDatasetsUpdate (chart, _args, options) { + const count = (chart.data.datasets || []).length; + const sources = []; + let meta, i, line, source; + for(i = 0; i < count; ++i){ + meta = chart.getDatasetMeta(i); + line = meta.dataset; + source = null; + if (line && line.options && line instanceof LineElement) { + source = { + visible: chart.isDatasetVisible(i), + index: i, + fill: _decodeFill(line, i, count), + chart, + axis: meta.controller.options.indexAxis, + scale: meta.vScale, + line + }; + } + meta.$filler = source; + sources.push(source); + } + for(i = 0; i < count; ++i){ + source = sources[i]; + if (!source || source.fill === false) { + continue; + } + source.fill = _resolveTarget(sources, i, options.propagate); + } + }, + beforeDraw (chart, _args, options) { + const draw = options.drawTime === 'beforeDraw'; + const metasets = chart.getSortedVisibleDatasetMetas(); + const area = chart.chartArea; + for(let i = metasets.length - 1; i >= 0; --i){ + const source = metasets[i].$filler; + if (!source) { + continue; + } + source.line.updateControlPoints(area, source.axis); + if (draw && source.fill) { + _drawfill(chart.ctx, source, area); + } + } + }, + beforeDatasetsDraw (chart, _args, options) { + if (options.drawTime !== 'beforeDatasetsDraw') { + return; + } + const metasets = chart.getSortedVisibleDatasetMetas(); + for(let i = metasets.length - 1; i >= 0; --i){ + const source = metasets[i].$filler; + if (_shouldApplyFill(source)) { + _drawfill(chart.ctx, source, chart.chartArea); + } + } + }, + beforeDatasetDraw (chart, args, options) { + const source = args.meta.$filler; + if (!_shouldApplyFill(source) || options.drawTime !== 'beforeDatasetDraw') { + return; + } + _drawfill(chart.ctx, source, chart.chartArea); + }, + defaults: { + propagate: true, + drawTime: 'beforeDatasetDraw' + } +}; + +const getBoxSize = (labelOpts, fontSize)=>{ + let { boxHeight =fontSize , boxWidth =fontSize } = labelOpts; + if (labelOpts.usePointStyle) { + boxHeight = Math.min(boxHeight, fontSize); + boxWidth = labelOpts.pointStyleWidth || Math.min(boxWidth, fontSize); + } + return { + boxWidth, + boxHeight, + itemHeight: Math.max(fontSize, boxHeight) + }; +}; +const itemsEqual = (a, b)=>a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index; +class Legend extends Element { + constructor(config){ + super(); + this._added = false; + this.legendHitBoxes = []; + this._hoveredItem = null; + this.doughnutMode = false; + this.chart = config.chart; + this.options = config.options; + this.ctx = config.ctx; + this.legendItems = undefined; + this.columnSizes = undefined; + this.lineWidths = undefined; + this.maxHeight = undefined; + this.maxWidth = undefined; + this.top = undefined; + this.bottom = undefined; + this.left = undefined; + this.right = undefined; + this.height = undefined; + this.width = undefined; + this._margins = undefined; + this.position = undefined; + this.weight = undefined; + this.fullSize = undefined; + } + update(maxWidth, maxHeight, margins) { + this.maxWidth = maxWidth; + this.maxHeight = maxHeight; + this._margins = margins; + this.setDimensions(); + this.buildLabels(); + this.fit(); + } + setDimensions() { + if (this.isHorizontal()) { + this.width = this.maxWidth; + this.left = this._margins.left; + this.right = this.width; + } else { + this.height = this.maxHeight; + this.top = this._margins.top; + this.bottom = this.height; + } + } + buildLabels() { + const labelOpts = this.options.labels || {}; + let legendItems = callback(labelOpts.generateLabels, [ + this.chart + ], this) || []; + if (labelOpts.filter) { + legendItems = legendItems.filter((item)=>labelOpts.filter(item, this.chart.data)); + } + if (labelOpts.sort) { + legendItems = legendItems.sort((a, b)=>labelOpts.sort(a, b, this.chart.data)); + } + if (this.options.reverse) { + legendItems.reverse(); + } + this.legendItems = legendItems; + } + fit() { + const { options , ctx } = this; + if (!options.display) { + this.width = this.height = 0; + return; + } + const labelOpts = options.labels; + const labelFont = toFont(labelOpts.font); + const fontSize = labelFont.size; + const titleHeight = this._computeTitleHeight(); + const { boxWidth , itemHeight } = getBoxSize(labelOpts, fontSize); + let width, height; + ctx.font = labelFont.string; + if (this.isHorizontal()) { + width = this.maxWidth; + height = this._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10; + } else { + height = this.maxHeight; + width = this._fitCols(titleHeight, labelFont, boxWidth, itemHeight) + 10; + } + this.width = Math.min(width, options.maxWidth || this.maxWidth); + this.height = Math.min(height, options.maxHeight || this.maxHeight); + } + _fitRows(titleHeight, fontSize, boxWidth, itemHeight) { + const { ctx , maxWidth , options: { labels: { padding } } } = this; + const hitboxes = this.legendHitBoxes = []; + const lineWidths = this.lineWidths = [ + 0 + ]; + const lineHeight = itemHeight + padding; + let totalHeight = titleHeight; + ctx.textAlign = 'left'; + ctx.textBaseline = 'middle'; + let row = -1; + let top = -lineHeight; + this.legendItems.forEach((legendItem, i)=>{ + const itemWidth = boxWidth + fontSize / 2 + ctx.measureText(legendItem.text).width; + if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) { + totalHeight += lineHeight; + lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0; + top += lineHeight; + row++; + } + hitboxes[i] = { + left: 0, + top, + row, + width: itemWidth, + height: itemHeight + }; + lineWidths[lineWidths.length - 1] += itemWidth + padding; + }); + return totalHeight; + } + _fitCols(titleHeight, labelFont, boxWidth, _itemHeight) { + const { ctx , maxHeight , options: { labels: { padding } } } = this; + const hitboxes = this.legendHitBoxes = []; + const columnSizes = this.columnSizes = []; + const heightLimit = maxHeight - titleHeight; + let totalWidth = padding; + let currentColWidth = 0; + let currentColHeight = 0; + let left = 0; + let col = 0; + this.legendItems.forEach((legendItem, i)=>{ + const { itemWidth , itemHeight } = calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight); + if (i > 0 && currentColHeight + itemHeight + 2 * padding > heightLimit) { + totalWidth += currentColWidth + padding; + columnSizes.push({ + width: currentColWidth, + height: currentColHeight + }); + left += currentColWidth + padding; + col++; + currentColWidth = currentColHeight = 0; + } + hitboxes[i] = { + left, + top: currentColHeight, + col, + width: itemWidth, + height: itemHeight + }; + currentColWidth = Math.max(currentColWidth, itemWidth); + currentColHeight += itemHeight + padding; + }); + totalWidth += currentColWidth; + columnSizes.push({ + width: currentColWidth, + height: currentColHeight + }); + return totalWidth; + } + adjustHitBoxes() { + if (!this.options.display) { + return; + } + const titleHeight = this._computeTitleHeight(); + const { legendHitBoxes: hitboxes , options: { align , labels: { padding } , rtl } } = this; + const rtlHelper = getRtlAdapter(rtl, this.left, this.width); + if (this.isHorizontal()) { + let row = 0; + let left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]); + for (const hitbox of hitboxes){ + if (row !== hitbox.row) { + row = hitbox.row; + left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]); + } + hitbox.top += this.top + titleHeight + padding; + hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(left), hitbox.width); + left += hitbox.width + padding; + } + } else { + let col = 0; + let top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height); + for (const hitbox of hitboxes){ + if (hitbox.col !== col) { + col = hitbox.col; + top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height); + } + hitbox.top = top; + hitbox.left += this.left + padding; + hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(hitbox.left), hitbox.width); + top += hitbox.height + padding; + } + } + } + isHorizontal() { + return this.options.position === 'top' || this.options.position === 'bottom'; + } + draw() { + if (this.options.display) { + const ctx = this.ctx; + clipArea(ctx, this); + this._draw(); + unclipArea(ctx); + } + } + _draw() { + const { options: opts , columnSizes , lineWidths , ctx } = this; + const { align , labels: labelOpts } = opts; + const defaultColor = defaults.color; + const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width); + const labelFont = toFont(labelOpts.font); + const { padding } = labelOpts; + const fontSize = labelFont.size; + const halfFontSize = fontSize / 2; + let cursor; + this.drawTitle(); + ctx.textAlign = rtlHelper.textAlign('left'); + ctx.textBaseline = 'middle'; + ctx.lineWidth = 0.5; + ctx.font = labelFont.string; + const { boxWidth , boxHeight , itemHeight } = getBoxSize(labelOpts, fontSize); + const drawLegendBox = function(x, y, legendItem) { + if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) { + return; + } + ctx.save(); + const lineWidth = valueOrDefault(legendItem.lineWidth, 1); + ctx.fillStyle = valueOrDefault(legendItem.fillStyle, defaultColor); + ctx.lineCap = valueOrDefault(legendItem.lineCap, 'butt'); + ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, 0); + ctx.lineJoin = valueOrDefault(legendItem.lineJoin, 'miter'); + ctx.lineWidth = lineWidth; + ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, defaultColor); + ctx.setLineDash(valueOrDefault(legendItem.lineDash, [])); + if (labelOpts.usePointStyle) { + const drawOptions = { + radius: boxHeight * Math.SQRT2 / 2, + pointStyle: legendItem.pointStyle, + rotation: legendItem.rotation, + borderWidth: lineWidth + }; + const centerX = rtlHelper.xPlus(x, boxWidth / 2); + const centerY = y + halfFontSize; + drawPointLegend(ctx, drawOptions, centerX, centerY, labelOpts.pointStyleWidth && boxWidth); + } else { + const yBoxTop = y + Math.max((fontSize - boxHeight) / 2, 0); + const xBoxLeft = rtlHelper.leftForLtr(x, boxWidth); + const borderRadius = toTRBLCorners(legendItem.borderRadius); + ctx.beginPath(); + if (Object.values(borderRadius).some((v)=>v !== 0)) { + addRoundedRectPath(ctx, { + x: xBoxLeft, + y: yBoxTop, + w: boxWidth, + h: boxHeight, + radius: borderRadius + }); + } else { + ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight); + } + ctx.fill(); + if (lineWidth !== 0) { + ctx.stroke(); + } + } + ctx.restore(); + }; + const fillText = function(x, y, legendItem) { + renderText(ctx, legendItem.text, x, y + itemHeight / 2, labelFont, { + strikethrough: legendItem.hidden, + textAlign: rtlHelper.textAlign(legendItem.textAlign) + }); + }; + const isHorizontal = this.isHorizontal(); + const titleHeight = this._computeTitleHeight(); + if (isHorizontal) { + cursor = { + x: _alignStartEnd(align, this.left + padding, this.right - lineWidths[0]), + y: this.top + padding + titleHeight, + line: 0 + }; + } else { + cursor = { + x: this.left + padding, + y: _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[0].height), + line: 0 + }; + } + overrideTextDirection(this.ctx, opts.textDirection); + const lineHeight = itemHeight + padding; + this.legendItems.forEach((legendItem, i)=>{ + ctx.strokeStyle = legendItem.fontColor; + ctx.fillStyle = legendItem.fontColor; + const textWidth = ctx.measureText(legendItem.text).width; + const textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign)); + const width = boxWidth + halfFontSize + textWidth; + let x = cursor.x; + let y = cursor.y; + rtlHelper.setWidth(this.width); + if (isHorizontal) { + if (i > 0 && x + width + padding > this.right) { + y = cursor.y += lineHeight; + cursor.line++; + x = cursor.x = _alignStartEnd(align, this.left + padding, this.right - lineWidths[cursor.line]); + } + } else if (i > 0 && y + lineHeight > this.bottom) { + x = cursor.x = x + columnSizes[cursor.line].width + padding; + cursor.line++; + y = cursor.y = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[cursor.line].height); + } + const realX = rtlHelper.x(x); + drawLegendBox(realX, y, legendItem); + x = _textX(textAlign, x + boxWidth + halfFontSize, isHorizontal ? x + width : this.right, opts.rtl); + fillText(rtlHelper.x(x), y, legendItem); + if (isHorizontal) { + cursor.x += width + padding; + } else if (typeof legendItem.text !== 'string') { + const fontLineHeight = labelFont.lineHeight; + cursor.y += calculateLegendItemHeight(legendItem, fontLineHeight) + padding; + } else { + cursor.y += lineHeight; + } + }); + restoreTextDirection(this.ctx, opts.textDirection); + } + drawTitle() { + const opts = this.options; + const titleOpts = opts.title; + const titleFont = toFont(titleOpts.font); + const titlePadding = toPadding(titleOpts.padding); + if (!titleOpts.display) { + return; + } + const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width); + const ctx = this.ctx; + const position = titleOpts.position; + const halfFontSize = titleFont.size / 2; + const topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize; + let y; + let left = this.left; + let maxWidth = this.width; + if (this.isHorizontal()) { + maxWidth = Math.max(...this.lineWidths); + y = this.top + topPaddingPlusHalfFontSize; + left = _alignStartEnd(opts.align, left, this.right - maxWidth); + } else { + const maxHeight = this.columnSizes.reduce((acc, size)=>Math.max(acc, size.height), 0); + y = topPaddingPlusHalfFontSize + _alignStartEnd(opts.align, this.top, this.bottom - maxHeight - opts.labels.padding - this._computeTitleHeight()); + } + const x = _alignStartEnd(position, left, left + maxWidth); + ctx.textAlign = rtlHelper.textAlign(_toLeftRightCenter(position)); + ctx.textBaseline = 'middle'; + ctx.strokeStyle = titleOpts.color; + ctx.fillStyle = titleOpts.color; + ctx.font = titleFont.string; + renderText(ctx, titleOpts.text, x, y, titleFont); + } + _computeTitleHeight() { + const titleOpts = this.options.title; + const titleFont = toFont(titleOpts.font); + const titlePadding = toPadding(titleOpts.padding); + return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0; + } + _getLegendItemAt(x, y) { + let i, hitBox, lh; + if (_isBetween(x, this.left, this.right) && _isBetween(y, this.top, this.bottom)) { + lh = this.legendHitBoxes; + for(i = 0; i < lh.length; ++i){ + hitBox = lh[i]; + if (_isBetween(x, hitBox.left, hitBox.left + hitBox.width) && _isBetween(y, hitBox.top, hitBox.top + hitBox.height)) { + return this.legendItems[i]; + } + } + } + return null; + } + handleEvent(e) { + const opts = this.options; + if (!isListened(e.type, opts)) { + return; + } + const hoveredItem = this._getLegendItemAt(e.x, e.y); + if (e.type === 'mousemove' || e.type === 'mouseout') { + const previous = this._hoveredItem; + const sameItem = itemsEqual(previous, hoveredItem); + if (previous && !sameItem) { + callback(opts.onLeave, [ + e, + previous, + this + ], this); + } + this._hoveredItem = hoveredItem; + if (hoveredItem && !sameItem) { + callback(opts.onHover, [ + e, + hoveredItem, + this + ], this); + } + } else if (hoveredItem) { + callback(opts.onClick, [ + e, + hoveredItem, + this + ], this); + } + } +} +function calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight) { + const itemWidth = calculateItemWidth(legendItem, boxWidth, labelFont, ctx); + const itemHeight = calculateItemHeight(_itemHeight, legendItem, labelFont.lineHeight); + return { + itemWidth, + itemHeight + }; +} +function calculateItemWidth(legendItem, boxWidth, labelFont, ctx) { + let legendItemText = legendItem.text; + if (legendItemText && typeof legendItemText !== 'string') { + legendItemText = legendItemText.reduce((a, b)=>a.length > b.length ? a : b); + } + return boxWidth + labelFont.size / 2 + ctx.measureText(legendItemText).width; +} +function calculateItemHeight(_itemHeight, legendItem, fontLineHeight) { + let itemHeight = _itemHeight; + if (typeof legendItem.text !== 'string') { + itemHeight = calculateLegendItemHeight(legendItem, fontLineHeight); + } + return itemHeight; +} +function calculateLegendItemHeight(legendItem, fontLineHeight) { + const labelHeight = legendItem.text ? legendItem.text.length : 0; + return fontLineHeight * labelHeight; +} +function isListened(type, opts) { + if ((type === 'mousemove' || type === 'mouseout') && (opts.onHover || opts.onLeave)) { + return true; + } + if (opts.onClick && (type === 'click' || type === 'mouseup')) { + return true; + } + return false; +} +var plugin_legend = { + id: 'legend', + _element: Legend, + start (chart, _args, options) { + const legend = chart.legend = new Legend({ + ctx: chart.ctx, + options, + chart + }); + layouts.configure(chart, legend, options); + layouts.addBox(chart, legend); + }, + stop (chart) { + layouts.removeBox(chart, chart.legend); + delete chart.legend; + }, + beforeUpdate (chart, _args, options) { + const legend = chart.legend; + layouts.configure(chart, legend, options); + legend.options = options; + }, + afterUpdate (chart) { + const legend = chart.legend; + legend.buildLabels(); + legend.adjustHitBoxes(); + }, + afterEvent (chart, args) { + if (!args.replay) { + chart.legend.handleEvent(args.event); + } + }, + defaults: { + display: true, + position: 'top', + align: 'center', + fullSize: true, + reverse: false, + weight: 1000, + onClick (e, legendItem, legend) { + const index = legendItem.datasetIndex; + const ci = legend.chart; + if (ci.isDatasetVisible(index)) { + ci.hide(index); + legendItem.hidden = true; + } else { + ci.show(index); + legendItem.hidden = false; + } + }, + onHover: null, + onLeave: null, + labels: { + color: (ctx)=>ctx.chart.options.color, + boxWidth: 40, + padding: 10, + generateLabels (chart) { + const datasets = chart.data.datasets; + const { labels: { usePointStyle , pointStyle , textAlign , color , useBorderRadius , borderRadius } } = chart.legend.options; + return chart._getSortedDatasetMetas().map((meta)=>{ + const style = meta.controller.getStyle(usePointStyle ? 0 : undefined); + const borderWidth = toPadding(style.borderWidth); + return { + text: datasets[meta.index].label, + fillStyle: style.backgroundColor, + fontColor: color, + hidden: !meta.visible, + lineCap: style.borderCapStyle, + lineDash: style.borderDash, + lineDashOffset: style.borderDashOffset, + lineJoin: style.borderJoinStyle, + lineWidth: (borderWidth.width + borderWidth.height) / 4, + strokeStyle: style.borderColor, + pointStyle: pointStyle || style.pointStyle, + rotation: style.rotation, + textAlign: textAlign || style.textAlign, + borderRadius: useBorderRadius && (borderRadius || style.borderRadius), + datasetIndex: meta.index + }; + }, this); + } + }, + title: { + color: (ctx)=>ctx.chart.options.color, + display: false, + position: 'center', + text: '' + } + }, + descriptors: { + _scriptable: (name)=>!name.startsWith('on'), + labels: { + _scriptable: (name)=>![ + 'generateLabels', + 'filter', + 'sort' + ].includes(name) + } + } +}; + +class Title extends Element { + constructor(config){ + super(); + this.chart = config.chart; + this.options = config.options; + this.ctx = config.ctx; + this._padding = undefined; + this.top = undefined; + this.bottom = undefined; + this.left = undefined; + this.right = undefined; + this.width = undefined; + this.height = undefined; + this.position = undefined; + this.weight = undefined; + this.fullSize = undefined; + } + update(maxWidth, maxHeight) { + const opts = this.options; + this.left = 0; + this.top = 0; + if (!opts.display) { + this.width = this.height = this.right = this.bottom = 0; + return; + } + this.width = this.right = maxWidth; + this.height = this.bottom = maxHeight; + const lineCount = isArray(opts.text) ? opts.text.length : 1; + this._padding = toPadding(opts.padding); + const textSize = lineCount * toFont(opts.font).lineHeight + this._padding.height; + if (this.isHorizontal()) { + this.height = textSize; + } else { + this.width = textSize; + } + } + isHorizontal() { + const pos = this.options.position; + return pos === 'top' || pos === 'bottom'; + } + _drawArgs(offset) { + const { top , left , bottom , right , options } = this; + const align = options.align; + let rotation = 0; + let maxWidth, titleX, titleY; + if (this.isHorizontal()) { + titleX = _alignStartEnd(align, left, right); + titleY = top + offset; + maxWidth = right - left; + } else { + if (options.position === 'left') { + titleX = left + offset; + titleY = _alignStartEnd(align, bottom, top); + rotation = PI * -0.5; + } else { + titleX = right - offset; + titleY = _alignStartEnd(align, top, bottom); + rotation = PI * 0.5; + } + maxWidth = bottom - top; + } + return { + titleX, + titleY, + maxWidth, + rotation + }; + } + draw() { + const ctx = this.ctx; + const opts = this.options; + if (!opts.display) { + return; + } + const fontOpts = toFont(opts.font); + const lineHeight = fontOpts.lineHeight; + const offset = lineHeight / 2 + this._padding.top; + const { titleX , titleY , maxWidth , rotation } = this._drawArgs(offset); + renderText(ctx, opts.text, 0, 0, fontOpts, { + color: opts.color, + maxWidth, + rotation, + textAlign: _toLeftRightCenter(opts.align), + textBaseline: 'middle', + translation: [ + titleX, + titleY + ] + }); + } +} +function createTitle(chart, titleOpts) { + const title = new Title({ + ctx: chart.ctx, + options: titleOpts, + chart + }); + layouts.configure(chart, title, titleOpts); + layouts.addBox(chart, title); + chart.titleBlock = title; +} +var plugin_title = { + id: 'title', + _element: Title, + start (chart, _args, options) { + createTitle(chart, options); + }, + stop (chart) { + const titleBlock = chart.titleBlock; + layouts.removeBox(chart, titleBlock); + delete chart.titleBlock; + }, + beforeUpdate (chart, _args, options) { + const title = chart.titleBlock; + layouts.configure(chart, title, options); + title.options = options; + }, + defaults: { + align: 'center', + display: false, + font: { + weight: 'bold' + }, + fullSize: true, + padding: 10, + position: 'top', + text: '', + weight: 2000 + }, + defaultRoutes: { + color: 'color' + }, + descriptors: { + _scriptable: true, + _indexable: false + } +}; + +const map = new WeakMap(); +var plugin_subtitle = { + id: 'subtitle', + start (chart, _args, options) { + const title = new Title({ + ctx: chart.ctx, + options, + chart + }); + layouts.configure(chart, title, options); + layouts.addBox(chart, title); + map.set(chart, title); + }, + stop (chart) { + layouts.removeBox(chart, map.get(chart)); + map.delete(chart); + }, + beforeUpdate (chart, _args, options) { + const title = map.get(chart); + layouts.configure(chart, title, options); + title.options = options; + }, + defaults: { + align: 'center', + display: false, + font: { + weight: 'normal' + }, + fullSize: true, + padding: 0, + position: 'top', + text: '', + weight: 1500 + }, + defaultRoutes: { + color: 'color' + }, + descriptors: { + _scriptable: true, + _indexable: false + } +}; + +const positioners = { + average (items) { + if (!items.length) { + return false; + } + let i, len; + let xSet = new Set(); + let y = 0; + let count = 0; + for(i = 0, len = items.length; i < len; ++i){ + const el = items[i].element; + if (el && el.hasValue()) { + const pos = el.tooltipPosition(); + xSet.add(pos.x); + y += pos.y; + ++count; + } + } + if (count === 0 || xSet.size === 0) { + return false; + } + const xAverage = [ + ...xSet + ].reduce((a, b)=>a + b) / xSet.size; + return { + x: xAverage, + y: y / count + }; + }, + nearest (items, eventPosition) { + if (!items.length) { + return false; + } + let x = eventPosition.x; + let y = eventPosition.y; + let minDistance = Number.POSITIVE_INFINITY; + let i, len, nearestElement; + for(i = 0, len = items.length; i < len; ++i){ + const el = items[i].element; + if (el && el.hasValue()) { + const center = el.getCenterPoint(); + const d = distanceBetweenPoints(eventPosition, center); + if (d < minDistance) { + minDistance = d; + nearestElement = el; + } + } + } + if (nearestElement) { + const tp = nearestElement.tooltipPosition(); + x = tp.x; + y = tp.y; + } + return { + x, + y + }; + } +}; +function pushOrConcat(base, toPush) { + if (toPush) { + if (isArray(toPush)) { + Array.prototype.push.apply(base, toPush); + } else { + base.push(toPush); + } + } + return base; +} + function splitNewlines(str) { + if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) { + return str.split('\n'); + } + return str; +} + function createTooltipItem(chart, item) { + const { element , datasetIndex , index } = item; + const controller = chart.getDatasetMeta(datasetIndex).controller; + const { label , value } = controller.getLabelAndValue(index); + return { + chart, + label, + parsed: controller.getParsed(index), + raw: chart.data.datasets[datasetIndex].data[index], + formattedValue: value, + dataset: controller.getDataset(), + dataIndex: index, + datasetIndex, + element + }; +} + function getTooltipSize(tooltip, options) { + const ctx = tooltip.chart.ctx; + const { body , footer , title } = tooltip; + const { boxWidth , boxHeight } = options; + const bodyFont = toFont(options.bodyFont); + const titleFont = toFont(options.titleFont); + const footerFont = toFont(options.footerFont); + const titleLineCount = title.length; + const footerLineCount = footer.length; + const bodyLineItemCount = body.length; + const padding = toPadding(options.padding); + let height = padding.height; + let width = 0; + let combinedBodyLength = body.reduce((count, bodyItem)=>count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length, 0); + combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length; + if (titleLineCount) { + height += titleLineCount * titleFont.lineHeight + (titleLineCount - 1) * options.titleSpacing + options.titleMarginBottom; + } + if (combinedBodyLength) { + const bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight; + height += bodyLineItemCount * bodyLineHeight + (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight + (combinedBodyLength - 1) * options.bodySpacing; + } + if (footerLineCount) { + height += options.footerMarginTop + footerLineCount * footerFont.lineHeight + (footerLineCount - 1) * options.footerSpacing; + } + let widthPadding = 0; + const maxLineWidth = function(line) { + width = Math.max(width, ctx.measureText(line).width + widthPadding); + }; + ctx.save(); + ctx.font = titleFont.string; + each(tooltip.title, maxLineWidth); + ctx.font = bodyFont.string; + each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth); + widthPadding = options.displayColors ? boxWidth + 2 + options.boxPadding : 0; + each(body, (bodyItem)=>{ + each(bodyItem.before, maxLineWidth); + each(bodyItem.lines, maxLineWidth); + each(bodyItem.after, maxLineWidth); + }); + widthPadding = 0; + ctx.font = footerFont.string; + each(tooltip.footer, maxLineWidth); + ctx.restore(); + width += padding.width; + return { + width, + height + }; +} +function determineYAlign(chart, size) { + const { y , height } = size; + if (y < height / 2) { + return 'top'; + } else if (y > chart.height - height / 2) { + return 'bottom'; + } + return 'center'; +} +function doesNotFitWithAlign(xAlign, chart, options, size) { + const { x , width } = size; + const caret = options.caretSize + options.caretPadding; + if (xAlign === 'left' && x + width + caret > chart.width) { + return true; + } + if (xAlign === 'right' && x - width - caret < 0) { + return true; + } +} +function determineXAlign(chart, options, size, yAlign) { + const { x , width } = size; + const { width: chartWidth , chartArea: { left , right } } = chart; + let xAlign = 'center'; + if (yAlign === 'center') { + xAlign = x <= (left + right) / 2 ? 'left' : 'right'; + } else if (x <= width / 2) { + xAlign = 'left'; + } else if (x >= chartWidth - width / 2) { + xAlign = 'right'; + } + if (doesNotFitWithAlign(xAlign, chart, options, size)) { + xAlign = 'center'; + } + return xAlign; +} + function determineAlignment(chart, options, size) { + const yAlign = size.yAlign || options.yAlign || determineYAlign(chart, size); + return { + xAlign: size.xAlign || options.xAlign || determineXAlign(chart, options, size, yAlign), + yAlign + }; +} +function alignX(size, xAlign) { + let { x , width } = size; + if (xAlign === 'right') { + x -= width; + } else if (xAlign === 'center') { + x -= width / 2; + } + return x; +} +function alignY(size, yAlign, paddingAndSize) { + let { y , height } = size; + if (yAlign === 'top') { + y += paddingAndSize; + } else if (yAlign === 'bottom') { + y -= height + paddingAndSize; + } else { + y -= height / 2; + } + return y; +} + function getBackgroundPoint(options, size, alignment, chart) { + const { caretSize , caretPadding , cornerRadius } = options; + const { xAlign , yAlign } = alignment; + const paddingAndSize = caretSize + caretPadding; + const { topLeft , topRight , bottomLeft , bottomRight } = toTRBLCorners(cornerRadius); + let x = alignX(size, xAlign); + const y = alignY(size, yAlign, paddingAndSize); + if (yAlign === 'center') { + if (xAlign === 'left') { + x += paddingAndSize; + } else if (xAlign === 'right') { + x -= paddingAndSize; + } + } else if (xAlign === 'left') { + x -= Math.max(topLeft, bottomLeft) + caretSize; + } else if (xAlign === 'right') { + x += Math.max(topRight, bottomRight) + caretSize; + } + return { + x: _limitValue(x, 0, chart.width - size.width), + y: _limitValue(y, 0, chart.height - size.height) + }; +} +function getAlignedX(tooltip, align, options) { + const padding = toPadding(options.padding); + return align === 'center' ? tooltip.x + tooltip.width / 2 : align === 'right' ? tooltip.x + tooltip.width - padding.right : tooltip.x + padding.left; +} + function getBeforeAfterBodyLines(callback) { + return pushOrConcat([], splitNewlines(callback)); +} +function createTooltipContext(parent, tooltip, tooltipItems) { + return createContext(parent, { + tooltip, + tooltipItems, + type: 'tooltip' + }); +} +function overrideCallbacks(callbacks, context) { + const override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks; + return override ? callbacks.override(override) : callbacks; +} +const defaultCallbacks = { + beforeTitle: noop, + title (tooltipItems) { + if (tooltipItems.length > 0) { + const item = tooltipItems[0]; + const labels = item.chart.data.labels; + const labelCount = labels ? labels.length : 0; + if (this && this.options && this.options.mode === 'dataset') { + return item.dataset.label || ''; + } else if (item.label) { + return item.label; + } else if (labelCount > 0 && item.dataIndex < labelCount) { + return labels[item.dataIndex]; + } + } + return ''; + }, + afterTitle: noop, + beforeBody: noop, + beforeLabel: noop, + label (tooltipItem) { + if (this && this.options && this.options.mode === 'dataset') { + return tooltipItem.label + ': ' + tooltipItem.formattedValue || tooltipItem.formattedValue; + } + let label = tooltipItem.dataset.label || ''; + if (label) { + label += ': '; + } + const value = tooltipItem.formattedValue; + if (!isNullOrUndef(value)) { + label += value; + } + return label; + }, + labelColor (tooltipItem) { + const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex); + const options = meta.controller.getStyle(tooltipItem.dataIndex); + return { + borderColor: options.borderColor, + backgroundColor: options.backgroundColor, + borderWidth: options.borderWidth, + borderDash: options.borderDash, + borderDashOffset: options.borderDashOffset, + borderRadius: 0 + }; + }, + labelTextColor () { + return this.options.bodyColor; + }, + labelPointStyle (tooltipItem) { + const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex); + const options = meta.controller.getStyle(tooltipItem.dataIndex); + return { + pointStyle: options.pointStyle, + rotation: options.rotation + }; + }, + afterLabel: noop, + afterBody: noop, + beforeFooter: noop, + footer: noop, + afterFooter: noop +}; + function invokeCallbackWithFallback(callbacks, name, ctx, arg) { + const result = callbacks[name].call(ctx, arg); + if (typeof result === 'undefined') { + return defaultCallbacks[name].call(ctx, arg); + } + return result; +} +class Tooltip extends Element { + static positioners = positioners; + constructor(config){ + super(); + this.opacity = 0; + this._active = []; + this._eventPosition = undefined; + this._size = undefined; + this._cachedAnimations = undefined; + this._tooltipItems = []; + this.$animations = undefined; + this.$context = undefined; + this.chart = config.chart; + this.options = config.options; + this.dataPoints = undefined; + this.title = undefined; + this.beforeBody = undefined; + this.body = undefined; + this.afterBody = undefined; + this.footer = undefined; + this.xAlign = undefined; + this.yAlign = undefined; + this.x = undefined; + this.y = undefined; + this.height = undefined; + this.width = undefined; + this.caretX = undefined; + this.caretY = undefined; + this.labelColors = undefined; + this.labelPointStyles = undefined; + this.labelTextColors = undefined; + } + initialize(options) { + this.options = options; + this._cachedAnimations = undefined; + this.$context = undefined; + } + _resolveAnimations() { + const cached = this._cachedAnimations; + if (cached) { + return cached; + } + const chart = this.chart; + const options = this.options.setContext(this.getContext()); + const opts = options.enabled && chart.options.animation && options.animations; + const animations = new Animations(this.chart, opts); + if (opts._cacheable) { + this._cachedAnimations = Object.freeze(animations); + } + return animations; + } + getContext() { + return this.$context || (this.$context = createTooltipContext(this.chart.getContext(), this, this._tooltipItems)); + } + getTitle(context, options) { + const { callbacks } = options; + const beforeTitle = invokeCallbackWithFallback(callbacks, 'beforeTitle', this, context); + const title = invokeCallbackWithFallback(callbacks, 'title', this, context); + const afterTitle = invokeCallbackWithFallback(callbacks, 'afterTitle', this, context); + let lines = []; + lines = pushOrConcat(lines, splitNewlines(beforeTitle)); + lines = pushOrConcat(lines, splitNewlines(title)); + lines = pushOrConcat(lines, splitNewlines(afterTitle)); + return lines; + } + getBeforeBody(tooltipItems, options) { + return getBeforeAfterBodyLines(invokeCallbackWithFallback(options.callbacks, 'beforeBody', this, tooltipItems)); + } + getBody(tooltipItems, options) { + const { callbacks } = options; + const bodyItems = []; + each(tooltipItems, (context)=>{ + const bodyItem = { + before: [], + lines: [], + after: [] + }; + const scoped = overrideCallbacks(callbacks, context); + pushOrConcat(bodyItem.before, splitNewlines(invokeCallbackWithFallback(scoped, 'beforeLabel', this, context))); + pushOrConcat(bodyItem.lines, invokeCallbackWithFallback(scoped, 'label', this, context)); + pushOrConcat(bodyItem.after, splitNewlines(invokeCallbackWithFallback(scoped, 'afterLabel', this, context))); + bodyItems.push(bodyItem); + }); + return bodyItems; + } + getAfterBody(tooltipItems, options) { + return getBeforeAfterBodyLines(invokeCallbackWithFallback(options.callbacks, 'afterBody', this, tooltipItems)); + } + getFooter(tooltipItems, options) { + const { callbacks } = options; + const beforeFooter = invokeCallbackWithFallback(callbacks, 'beforeFooter', this, tooltipItems); + const footer = invokeCallbackWithFallback(callbacks, 'footer', this, tooltipItems); + const afterFooter = invokeCallbackWithFallback(callbacks, 'afterFooter', this, tooltipItems); + let lines = []; + lines = pushOrConcat(lines, splitNewlines(beforeFooter)); + lines = pushOrConcat(lines, splitNewlines(footer)); + lines = pushOrConcat(lines, splitNewlines(afterFooter)); + return lines; + } + _createItems(options) { + const active = this._active; + const data = this.chart.data; + const labelColors = []; + const labelPointStyles = []; + const labelTextColors = []; + let tooltipItems = []; + let i, len; + for(i = 0, len = active.length; i < len; ++i){ + tooltipItems.push(createTooltipItem(this.chart, active[i])); + } + if (options.filter) { + tooltipItems = tooltipItems.filter((element, index, array)=>options.filter(element, index, array, data)); + } + if (options.itemSort) { + tooltipItems = tooltipItems.sort((a, b)=>options.itemSort(a, b, data)); + } + each(tooltipItems, (context)=>{ + const scoped = overrideCallbacks(options.callbacks, context); + labelColors.push(invokeCallbackWithFallback(scoped, 'labelColor', this, context)); + labelPointStyles.push(invokeCallbackWithFallback(scoped, 'labelPointStyle', this, context)); + labelTextColors.push(invokeCallbackWithFallback(scoped, 'labelTextColor', this, context)); + }); + this.labelColors = labelColors; + this.labelPointStyles = labelPointStyles; + this.labelTextColors = labelTextColors; + this.dataPoints = tooltipItems; + return tooltipItems; + } + update(changed, replay) { + const options = this.options.setContext(this.getContext()); + const active = this._active; + let properties; + let tooltipItems = []; + if (!active.length) { + if (this.opacity !== 0) { + properties = { + opacity: 0 + }; + } + } else { + const position = positioners[options.position].call(this, active, this._eventPosition); + tooltipItems = this._createItems(options); + this.title = this.getTitle(tooltipItems, options); + this.beforeBody = this.getBeforeBody(tooltipItems, options); + this.body = this.getBody(tooltipItems, options); + this.afterBody = this.getAfterBody(tooltipItems, options); + this.footer = this.getFooter(tooltipItems, options); + const size = this._size = getTooltipSize(this, options); + const positionAndSize = Object.assign({}, position, size); + const alignment = determineAlignment(this.chart, options, positionAndSize); + const backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, this.chart); + this.xAlign = alignment.xAlign; + this.yAlign = alignment.yAlign; + properties = { + opacity: 1, + x: backgroundPoint.x, + y: backgroundPoint.y, + width: size.width, + height: size.height, + caretX: position.x, + caretY: position.y + }; + } + this._tooltipItems = tooltipItems; + this.$context = undefined; + if (properties) { + this._resolveAnimations().update(this, properties); + } + if (changed && options.external) { + options.external.call(this, { + chart: this.chart, + tooltip: this, + replay + }); + } + } + drawCaret(tooltipPoint, ctx, size, options) { + const caretPosition = this.getCaretPosition(tooltipPoint, size, options); + ctx.lineTo(caretPosition.x1, caretPosition.y1); + ctx.lineTo(caretPosition.x2, caretPosition.y2); + ctx.lineTo(caretPosition.x3, caretPosition.y3); + } + getCaretPosition(tooltipPoint, size, options) { + const { xAlign , yAlign } = this; + const { caretSize , cornerRadius } = options; + const { topLeft , topRight , bottomLeft , bottomRight } = toTRBLCorners(cornerRadius); + const { x: ptX , y: ptY } = tooltipPoint; + const { width , height } = size; + let x1, x2, x3, y1, y2, y3; + if (yAlign === 'center') { + y2 = ptY + height / 2; + if (xAlign === 'left') { + x1 = ptX; + x2 = x1 - caretSize; + y1 = y2 + caretSize; + y3 = y2 - caretSize; + } else { + x1 = ptX + width; + x2 = x1 + caretSize; + y1 = y2 - caretSize; + y3 = y2 + caretSize; + } + x3 = x1; + } else { + if (xAlign === 'left') { + x2 = ptX + Math.max(topLeft, bottomLeft) + caretSize; + } else if (xAlign === 'right') { + x2 = ptX + width - Math.max(topRight, bottomRight) - caretSize; + } else { + x2 = this.caretX; + } + if (yAlign === 'top') { + y1 = ptY; + y2 = y1 - caretSize; + x1 = x2 - caretSize; + x3 = x2 + caretSize; + } else { + y1 = ptY + height; + y2 = y1 + caretSize; + x1 = x2 + caretSize; + x3 = x2 - caretSize; + } + y3 = y1; + } + return { + x1, + x2, + x3, + y1, + y2, + y3 + }; + } + drawTitle(pt, ctx, options) { + const title = this.title; + const length = title.length; + let titleFont, titleSpacing, i; + if (length) { + const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width); + pt.x = getAlignedX(this, options.titleAlign, options); + ctx.textAlign = rtlHelper.textAlign(options.titleAlign); + ctx.textBaseline = 'middle'; + titleFont = toFont(options.titleFont); + titleSpacing = options.titleSpacing; + ctx.fillStyle = options.titleColor; + ctx.font = titleFont.string; + for(i = 0; i < length; ++i){ + ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFont.lineHeight / 2); + pt.y += titleFont.lineHeight + titleSpacing; + if (i + 1 === length) { + pt.y += options.titleMarginBottom - titleSpacing; + } + } + } + } + _drawColorBox(ctx, pt, i, rtlHelper, options) { + const labelColor = this.labelColors[i]; + const labelPointStyle = this.labelPointStyles[i]; + const { boxHeight , boxWidth } = options; + const bodyFont = toFont(options.bodyFont); + const colorX = getAlignedX(this, 'left', options); + const rtlColorX = rtlHelper.x(colorX); + const yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0; + const colorY = pt.y + yOffSet; + if (options.usePointStyle) { + const drawOptions = { + radius: Math.min(boxWidth, boxHeight) / 2, + pointStyle: labelPointStyle.pointStyle, + rotation: labelPointStyle.rotation, + borderWidth: 1 + }; + const centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2; + const centerY = colorY + boxHeight / 2; + ctx.strokeStyle = options.multiKeyBackground; + ctx.fillStyle = options.multiKeyBackground; + drawPoint(ctx, drawOptions, centerX, centerY); + ctx.strokeStyle = labelColor.borderColor; + ctx.fillStyle = labelColor.backgroundColor; + drawPoint(ctx, drawOptions, centerX, centerY); + } else { + ctx.lineWidth = isObject(labelColor.borderWidth) ? Math.max(...Object.values(labelColor.borderWidth)) : labelColor.borderWidth || 1; + ctx.strokeStyle = labelColor.borderColor; + ctx.setLineDash(labelColor.borderDash || []); + ctx.lineDashOffset = labelColor.borderDashOffset || 0; + const outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth); + const innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - 2); + const borderRadius = toTRBLCorners(labelColor.borderRadius); + if (Object.values(borderRadius).some((v)=>v !== 0)) { + ctx.beginPath(); + ctx.fillStyle = options.multiKeyBackground; + addRoundedRectPath(ctx, { + x: outerX, + y: colorY, + w: boxWidth, + h: boxHeight, + radius: borderRadius + }); + ctx.fill(); + ctx.stroke(); + ctx.fillStyle = labelColor.backgroundColor; + ctx.beginPath(); + addRoundedRectPath(ctx, { + x: innerX, + y: colorY + 1, + w: boxWidth - 2, + h: boxHeight - 2, + radius: borderRadius + }); + ctx.fill(); + } else { + ctx.fillStyle = options.multiKeyBackground; + ctx.fillRect(outerX, colorY, boxWidth, boxHeight); + ctx.strokeRect(outerX, colorY, boxWidth, boxHeight); + ctx.fillStyle = labelColor.backgroundColor; + ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2); + } + } + ctx.fillStyle = this.labelTextColors[i]; + } + drawBody(pt, ctx, options) { + const { body } = this; + const { bodySpacing , bodyAlign , displayColors , boxHeight , boxWidth , boxPadding } = options; + const bodyFont = toFont(options.bodyFont); + let bodyLineHeight = bodyFont.lineHeight; + let xLinePadding = 0; + const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width); + const fillLineOfText = function(line) { + ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyLineHeight / 2); + pt.y += bodyLineHeight + bodySpacing; + }; + const bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign); + let bodyItem, textColor, lines, i, j, ilen, jlen; + ctx.textAlign = bodyAlign; + ctx.textBaseline = 'middle'; + ctx.font = bodyFont.string; + pt.x = getAlignedX(this, bodyAlignForCalculation, options); + ctx.fillStyle = options.bodyColor; + each(this.beforeBody, fillLineOfText); + xLinePadding = displayColors && bodyAlignForCalculation !== 'right' ? bodyAlign === 'center' ? boxWidth / 2 + boxPadding : boxWidth + 2 + boxPadding : 0; + for(i = 0, ilen = body.length; i < ilen; ++i){ + bodyItem = body[i]; + textColor = this.labelTextColors[i]; + ctx.fillStyle = textColor; + each(bodyItem.before, fillLineOfText); + lines = bodyItem.lines; + if (displayColors && lines.length) { + this._drawColorBox(ctx, pt, i, rtlHelper, options); + bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight); + } + for(j = 0, jlen = lines.length; j < jlen; ++j){ + fillLineOfText(lines[j]); + bodyLineHeight = bodyFont.lineHeight; + } + each(bodyItem.after, fillLineOfText); + } + xLinePadding = 0; + bodyLineHeight = bodyFont.lineHeight; + each(this.afterBody, fillLineOfText); + pt.y -= bodySpacing; + } + drawFooter(pt, ctx, options) { + const footer = this.footer; + const length = footer.length; + let footerFont, i; + if (length) { + const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width); + pt.x = getAlignedX(this, options.footerAlign, options); + pt.y += options.footerMarginTop; + ctx.textAlign = rtlHelper.textAlign(options.footerAlign); + ctx.textBaseline = 'middle'; + footerFont = toFont(options.footerFont); + ctx.fillStyle = options.footerColor; + ctx.font = footerFont.string; + for(i = 0; i < length; ++i){ + ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFont.lineHeight / 2); + pt.y += footerFont.lineHeight + options.footerSpacing; + } + } + } + drawBackground(pt, ctx, tooltipSize, options) { + const { xAlign , yAlign } = this; + const { x , y } = pt; + const { width , height } = tooltipSize; + const { topLeft , topRight , bottomLeft , bottomRight } = toTRBLCorners(options.cornerRadius); + ctx.fillStyle = options.backgroundColor; + ctx.strokeStyle = options.borderColor; + ctx.lineWidth = options.borderWidth; + ctx.beginPath(); + ctx.moveTo(x + topLeft, y); + if (yAlign === 'top') { + this.drawCaret(pt, ctx, tooltipSize, options); + } + ctx.lineTo(x + width - topRight, y); + ctx.quadraticCurveTo(x + width, y, x + width, y + topRight); + if (yAlign === 'center' && xAlign === 'right') { + this.drawCaret(pt, ctx, tooltipSize, options); + } + ctx.lineTo(x + width, y + height - bottomRight); + ctx.quadraticCurveTo(x + width, y + height, x + width - bottomRight, y + height); + if (yAlign === 'bottom') { + this.drawCaret(pt, ctx, tooltipSize, options); + } + ctx.lineTo(x + bottomLeft, y + height); + ctx.quadraticCurveTo(x, y + height, x, y + height - bottomLeft); + if (yAlign === 'center' && xAlign === 'left') { + this.drawCaret(pt, ctx, tooltipSize, options); + } + ctx.lineTo(x, y + topLeft); + ctx.quadraticCurveTo(x, y, x + topLeft, y); + ctx.closePath(); + ctx.fill(); + if (options.borderWidth > 0) { + ctx.stroke(); + } + } + _updateAnimationTarget(options) { + const chart = this.chart; + const anims = this.$animations; + const animX = anims && anims.x; + const animY = anims && anims.y; + if (animX || animY) { + const position = positioners[options.position].call(this, this._active, this._eventPosition); + if (!position) { + return; + } + const size = this._size = getTooltipSize(this, options); + const positionAndSize = Object.assign({}, position, this._size); + const alignment = determineAlignment(chart, options, positionAndSize); + const point = getBackgroundPoint(options, positionAndSize, alignment, chart); + if (animX._to !== point.x || animY._to !== point.y) { + this.xAlign = alignment.xAlign; + this.yAlign = alignment.yAlign; + this.width = size.width; + this.height = size.height; + this.caretX = position.x; + this.caretY = position.y; + this._resolveAnimations().update(this, point); + } + } + } + _willRender() { + return !!this.opacity; + } + draw(ctx) { + const options = this.options.setContext(this.getContext()); + let opacity = this.opacity; + if (!opacity) { + return; + } + this._updateAnimationTarget(options); + const tooltipSize = { + width: this.width, + height: this.height + }; + const pt = { + x: this.x, + y: this.y + }; + opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity; + const padding = toPadding(options.padding); + const hasTooltipContent = this.title.length || this.beforeBody.length || this.body.length || this.afterBody.length || this.footer.length; + if (options.enabled && hasTooltipContent) { + ctx.save(); + ctx.globalAlpha = opacity; + this.drawBackground(pt, ctx, tooltipSize, options); + overrideTextDirection(ctx, options.textDirection); + pt.y += padding.top; + this.drawTitle(pt, ctx, options); + this.drawBody(pt, ctx, options); + this.drawFooter(pt, ctx, options); + restoreTextDirection(ctx, options.textDirection); + ctx.restore(); + } + } + getActiveElements() { + return this._active || []; + } + setActiveElements(activeElements, eventPosition) { + const lastActive = this._active; + const active = activeElements.map(({ datasetIndex , index })=>{ + const meta = this.chart.getDatasetMeta(datasetIndex); + if (!meta) { + throw new Error('Cannot find a dataset at index ' + datasetIndex); + } + return { + datasetIndex, + element: meta.data[index], + index + }; + }); + const changed = !_elementsEqual(lastActive, active); + const positionChanged = this._positionChanged(active, eventPosition); + if (changed || positionChanged) { + this._active = active; + this._eventPosition = eventPosition; + this._ignoreReplayEvents = true; + this.update(true); + } + } + handleEvent(e, replay, inChartArea = true) { + if (replay && this._ignoreReplayEvents) { + return false; + } + this._ignoreReplayEvents = false; + const options = this.options; + const lastActive = this._active || []; + const active = this._getActiveElements(e, lastActive, replay, inChartArea); + const positionChanged = this._positionChanged(active, e); + const changed = replay || !_elementsEqual(active, lastActive) || positionChanged; + if (changed) { + this._active = active; + if (options.enabled || options.external) { + this._eventPosition = { + x: e.x, + y: e.y + }; + this.update(true, replay); + } + } + return changed; + } + _getActiveElements(e, lastActive, replay, inChartArea) { + const options = this.options; + if (e.type === 'mouseout') { + return []; + } + if (!inChartArea) { + return lastActive.filter((i)=>this.chart.data.datasets[i.datasetIndex] && this.chart.getDatasetMeta(i.datasetIndex).controller.getParsed(i.index) !== undefined); + } + const active = this.chart.getElementsAtEventForMode(e, options.mode, options, replay); + if (options.reverse) { + active.reverse(); + } + return active; + } + _positionChanged(active, e) { + const { caretX , caretY , options } = this; + const position = positioners[options.position].call(this, active, e); + return position !== false && (caretX !== position.x || caretY !== position.y); + } +} +var plugin_tooltip = { + id: 'tooltip', + _element: Tooltip, + positioners, + afterInit (chart, _args, options) { + if (options) { + chart.tooltip = new Tooltip({ + chart, + options + }); + } + }, + beforeUpdate (chart, _args, options) { + if (chart.tooltip) { + chart.tooltip.initialize(options); + } + }, + reset (chart, _args, options) { + if (chart.tooltip) { + chart.tooltip.initialize(options); + } + }, + afterDraw (chart) { + const tooltip = chart.tooltip; + if (tooltip && tooltip._willRender()) { + const args = { + tooltip + }; + if (chart.notifyPlugins('beforeTooltipDraw', { + ...args, + cancelable: true + }) === false) { + return; + } + tooltip.draw(chart.ctx); + chart.notifyPlugins('afterTooltipDraw', args); + } + }, + afterEvent (chart, args) { + if (chart.tooltip) { + const useFinalPosition = args.replay; + if (chart.tooltip.handleEvent(args.event, useFinalPosition, args.inChartArea)) { + args.changed = true; + } + } + }, + defaults: { + enabled: true, + external: null, + position: 'average', + backgroundColor: 'rgba(0,0,0,0.8)', + titleColor: '#fff', + titleFont: { + weight: 'bold' + }, + titleSpacing: 2, + titleMarginBottom: 6, + titleAlign: 'left', + bodyColor: '#fff', + bodySpacing: 2, + bodyFont: {}, + bodyAlign: 'left', + footerColor: '#fff', + footerSpacing: 2, + footerMarginTop: 6, + footerFont: { + weight: 'bold' + }, + footerAlign: 'left', + padding: 6, + caretPadding: 2, + caretSize: 5, + cornerRadius: 6, + boxHeight: (ctx, opts)=>opts.bodyFont.size, + boxWidth: (ctx, opts)=>opts.bodyFont.size, + multiKeyBackground: '#fff', + displayColors: true, + boxPadding: 0, + borderColor: 'rgba(0,0,0,0)', + borderWidth: 0, + animation: { + duration: 400, + easing: 'easeOutQuart' + }, + animations: { + numbers: { + type: 'number', + properties: [ + 'x', + 'y', + 'width', + 'height', + 'caretX', + 'caretY' + ] + }, + opacity: { + easing: 'linear', + duration: 200 + } + }, + callbacks: defaultCallbacks + }, + defaultRoutes: { + bodyFont: 'font', + footerFont: 'font', + titleFont: 'font' + }, + descriptors: { + _scriptable: (name)=>name !== 'filter' && name !== 'itemSort' && name !== 'external', + _indexable: false, + callbacks: { + _scriptable: false, + _indexable: false + }, + animation: { + _fallback: false + }, + animations: { + _fallback: 'animation' + } + }, + additionalOptionScopes: [ + 'interaction' + ] +}; + +var plugins = /*#__PURE__*/Object.freeze({ +__proto__: null, +Colors: plugin_colors, +Decimation: plugin_decimation, +Filler: index, +Legend: plugin_legend, +SubTitle: plugin_subtitle, +Title: plugin_title, +Tooltip: plugin_tooltip +}); + +const addIfString = (labels, raw, index, addedLabels)=>{ + if (typeof raw === 'string') { + index = labels.push(raw) - 1; + addedLabels.unshift({ + index, + label: raw + }); + } else if (isNaN(raw)) { + index = null; + } + return index; +}; +function findOrAddLabel(labels, raw, index, addedLabels) { + const first = labels.indexOf(raw); + if (first === -1) { + return addIfString(labels, raw, index, addedLabels); + } + const last = labels.lastIndexOf(raw); + return first !== last ? index : first; +} +const validIndex = (index, max)=>index === null ? null : _limitValue(Math.round(index), 0, max); +function _getLabelForValue(value) { + const labels = this.getLabels(); + if (value >= 0 && value < labels.length) { + return labels[value]; + } + return value; +} +class CategoryScale extends Scale { + static id = 'category'; + static defaults = { + ticks: { + callback: _getLabelForValue + } + }; + constructor(cfg){ + super(cfg); + this._startValue = undefined; + this._valueRange = 0; + this._addedLabels = []; + } + init(scaleOptions) { + const added = this._addedLabels; + if (added.length) { + const labels = this.getLabels(); + for (const { index , label } of added){ + if (labels[index] === label) { + labels.splice(index, 1); + } + } + this._addedLabels = []; + } + super.init(scaleOptions); + } + parse(raw, index) { + if (isNullOrUndef(raw)) { + return null; + } + const labels = this.getLabels(); + index = isFinite(index) && labels[index] === raw ? index : findOrAddLabel(labels, raw, valueOrDefault(index, raw), this._addedLabels); + return validIndex(index, labels.length - 1); + } + determineDataLimits() { + const { minDefined , maxDefined } = this.getUserBounds(); + let { min , max } = this.getMinMax(true); + if (this.options.bounds === 'ticks') { + if (!minDefined) { + min = 0; + } + if (!maxDefined) { + max = this.getLabels().length - 1; + } + } + this.min = min; + this.max = max; + } + buildTicks() { + const min = this.min; + const max = this.max; + const offset = this.options.offset; + const ticks = []; + let labels = this.getLabels(); + labels = min === 0 && max === labels.length - 1 ? labels : labels.slice(min, max + 1); + this._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1); + this._startValue = this.min - (offset ? 0.5 : 0); + for(let value = min; value <= max; value++){ + ticks.push({ + value + }); + } + return ticks; + } + getLabelForValue(value) { + return _getLabelForValue.call(this, value); + } + configure() { + super.configure(); + if (!this.isHorizontal()) { + this._reversePixels = !this._reversePixels; + } + } + getPixelForValue(value) { + if (typeof value !== 'number') { + value = this.parse(value); + } + return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange); + } + getPixelForTick(index) { + const ticks = this.ticks; + if (index < 0 || index > ticks.length - 1) { + return null; + } + return this.getPixelForValue(ticks[index].value); + } + getValueForPixel(pixel) { + return Math.round(this._startValue + this.getDecimalForPixel(pixel) * this._valueRange); + } + getBasePixel() { + return this.bottom; + } +} + +function generateTicks$1(generationOptions, dataRange) { + const ticks = []; + const MIN_SPACING = 1e-14; + const { bounds , step , min , max , precision , count , maxTicks , maxDigits , includeBounds } = generationOptions; + const unit = step || 1; + const maxSpaces = maxTicks - 1; + const { min: rmin , max: rmax } = dataRange; + const minDefined = !isNullOrUndef(min); + const maxDefined = !isNullOrUndef(max); + const countDefined = !isNullOrUndef(count); + const minSpacing = (rmax - rmin) / (maxDigits + 1); + let spacing = niceNum((rmax - rmin) / maxSpaces / unit) * unit; + let factor, niceMin, niceMax, numSpaces; + if (spacing < MIN_SPACING && !minDefined && !maxDefined) { + return [ + { + value: rmin + }, + { + value: rmax + } + ]; + } + numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing); + if (numSpaces > maxSpaces) { + spacing = niceNum(numSpaces * spacing / maxSpaces / unit) * unit; + } + if (!isNullOrUndef(precision)) { + factor = Math.pow(10, precision); + spacing = Math.ceil(spacing * factor) / factor; + } + if (bounds === 'ticks') { + niceMin = Math.floor(rmin / spacing) * spacing; + niceMax = Math.ceil(rmax / spacing) * spacing; + } else { + niceMin = rmin; + niceMax = rmax; + } + if (minDefined && maxDefined && step && almostWhole((max - min) / step, spacing / 1000)) { + numSpaces = Math.round(Math.min((max - min) / spacing, maxTicks)); + spacing = (max - min) / numSpaces; + niceMin = min; + niceMax = max; + } else if (countDefined) { + niceMin = minDefined ? min : niceMin; + niceMax = maxDefined ? max : niceMax; + numSpaces = count - 1; + spacing = (niceMax - niceMin) / numSpaces; + } else { + numSpaces = (niceMax - niceMin) / spacing; + if (almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) { + numSpaces = Math.round(numSpaces); + } else { + numSpaces = Math.ceil(numSpaces); + } + } + const decimalPlaces = Math.max(_decimalPlaces(spacing), _decimalPlaces(niceMin)); + factor = Math.pow(10, isNullOrUndef(precision) ? decimalPlaces : precision); + niceMin = Math.round(niceMin * factor) / factor; + niceMax = Math.round(niceMax * factor) / factor; + let j = 0; + if (minDefined) { + if (includeBounds && niceMin !== min) { + ticks.push({ + value: min + }); + if (niceMin < min) { + j++; + } + if (almostEquals(Math.round((niceMin + j * spacing) * factor) / factor, min, relativeLabelSize(min, minSpacing, generationOptions))) { + j++; + } + } else if (niceMin < min) { + j++; + } + } + for(; j < numSpaces; ++j){ + const tickValue = Math.round((niceMin + j * spacing) * factor) / factor; + if (maxDefined && tickValue > max) { + break; + } + ticks.push({ + value: tickValue + }); + } + if (maxDefined && includeBounds && niceMax !== max) { + if (ticks.length && almostEquals(ticks[ticks.length - 1].value, max, relativeLabelSize(max, minSpacing, generationOptions))) { + ticks[ticks.length - 1].value = max; + } else { + ticks.push({ + value: max + }); + } + } else if (!maxDefined || niceMax === max) { + ticks.push({ + value: niceMax + }); + } + return ticks; +} +function relativeLabelSize(value, minSpacing, { horizontal , minRotation }) { + const rad = toRadians(minRotation); + const ratio = (horizontal ? Math.sin(rad) : Math.cos(rad)) || 0.001; + const length = 0.75 * minSpacing * ('' + value).length; + return Math.min(minSpacing / ratio, length); +} +class LinearScaleBase extends Scale { + constructor(cfg){ + super(cfg); + this.start = undefined; + this.end = undefined; + this._startValue = undefined; + this._endValue = undefined; + this._valueRange = 0; + } + parse(raw, index) { + if (isNullOrUndef(raw)) { + return null; + } + if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) { + return null; + } + return +raw; + } + handleTickRangeOptions() { + const { beginAtZero } = this.options; + const { minDefined , maxDefined } = this.getUserBounds(); + let { min , max } = this; + const setMin = (v)=>min = minDefined ? min : v; + const setMax = (v)=>max = maxDefined ? max : v; + if (beginAtZero) { + const minSign = sign(min); + const maxSign = sign(max); + if (minSign < 0 && maxSign < 0) { + setMax(0); + } else if (minSign > 0 && maxSign > 0) { + setMin(0); + } + } + if (min === max) { + let offset = max === 0 ? 1 : Math.abs(max * 0.05); + setMax(max + offset); + if (!beginAtZero) { + setMin(min - offset); + } + } + this.min = min; + this.max = max; + } + getTickLimit() { + const tickOpts = this.options.ticks; + let { maxTicksLimit , stepSize } = tickOpts; + let maxTicks; + if (stepSize) { + maxTicks = Math.ceil(this.max / stepSize) - Math.floor(this.min / stepSize) + 1; + if (maxTicks > 1000) { + console.warn(`scales.${this.id}.ticks.stepSize: ${stepSize} would result generating up to ${maxTicks} ticks. Limiting to 1000.`); + maxTicks = 1000; + } + } else { + maxTicks = this.computeTickLimit(); + maxTicksLimit = maxTicksLimit || 11; + } + if (maxTicksLimit) { + maxTicks = Math.min(maxTicksLimit, maxTicks); + } + return maxTicks; + } + computeTickLimit() { + return Number.POSITIVE_INFINITY; + } + buildTicks() { + const opts = this.options; + const tickOpts = opts.ticks; + let maxTicks = this.getTickLimit(); + maxTicks = Math.max(2, maxTicks); + const numericGeneratorOptions = { + maxTicks, + bounds: opts.bounds, + min: opts.min, + max: opts.max, + precision: tickOpts.precision, + step: tickOpts.stepSize, + count: tickOpts.count, + maxDigits: this._maxDigits(), + horizontal: this.isHorizontal(), + minRotation: tickOpts.minRotation || 0, + includeBounds: tickOpts.includeBounds !== false + }; + const dataRange = this._range || this; + const ticks = generateTicks$1(numericGeneratorOptions, dataRange); + if (opts.bounds === 'ticks') { + _setMinAndMaxByKey(ticks, this, 'value'); + } + if (opts.reverse) { + ticks.reverse(); + this.start = this.max; + this.end = this.min; + } else { + this.start = this.min; + this.end = this.max; + } + return ticks; + } + configure() { + const ticks = this.ticks; + let start = this.min; + let end = this.max; + super.configure(); + if (this.options.offset && ticks.length) { + const offset = (end - start) / Math.max(ticks.length - 1, 1) / 2; + start -= offset; + end += offset; + } + this._startValue = start; + this._endValue = end; + this._valueRange = end - start; + } + getLabelForValue(value) { + return formatNumber(value, this.chart.options.locale, this.options.ticks.format); + } +} + +class LinearScale extends LinearScaleBase { + static id = 'linear'; + static defaults = { + ticks: { + callback: Ticks.formatters.numeric + } + }; + determineDataLimits() { + const { min , max } = this.getMinMax(true); + this.min = isNumberFinite(min) ? min : 0; + this.max = isNumberFinite(max) ? max : 1; + this.handleTickRangeOptions(); + } + computeTickLimit() { + const horizontal = this.isHorizontal(); + const length = horizontal ? this.width : this.height; + const minRotation = toRadians(this.options.ticks.minRotation); + const ratio = (horizontal ? Math.sin(minRotation) : Math.cos(minRotation)) || 0.001; + const tickFont = this._resolveTickFontOptions(0); + return Math.ceil(length / Math.min(40, tickFont.lineHeight / ratio)); + } + getPixelForValue(value) { + return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange); + } + getValueForPixel(pixel) { + return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange; + } +} + +const log10Floor = (v)=>Math.floor(log10(v)); +const changeExponent = (v, m)=>Math.pow(10, log10Floor(v) + m); +function isMajor(tickVal) { + const remain = tickVal / Math.pow(10, log10Floor(tickVal)); + return remain === 1; +} +function steps(min, max, rangeExp) { + const rangeStep = Math.pow(10, rangeExp); + const start = Math.floor(min / rangeStep); + const end = Math.ceil(max / rangeStep); + return end - start; +} +function startExp(min, max) { + const range = max - min; + let rangeExp = log10Floor(range); + while(steps(min, max, rangeExp) > 10){ + rangeExp++; + } + while(steps(min, max, rangeExp) < 10){ + rangeExp--; + } + return Math.min(rangeExp, log10Floor(min)); +} + function generateTicks(generationOptions, { min , max }) { + min = finiteOrDefault(generationOptions.min, min); + const ticks = []; + const minExp = log10Floor(min); + let exp = startExp(min, max); + let precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1; + const stepSize = Math.pow(10, exp); + const base = minExp > exp ? Math.pow(10, minExp) : 0; + const start = Math.round((min - base) * precision) / precision; + const offset = Math.floor((min - base) / stepSize / 10) * stepSize * 10; + let significand = Math.floor((start - offset) / Math.pow(10, exp)); + let value = finiteOrDefault(generationOptions.min, Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision); + while(value < max){ + ticks.push({ + value, + major: isMajor(value), + significand + }); + if (significand >= 10) { + significand = significand < 15 ? 15 : 20; + } else { + significand++; + } + if (significand >= 20) { + exp++; + significand = 2; + precision = exp >= 0 ? 1 : precision; + } + value = Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision; + } + const lastTick = finiteOrDefault(generationOptions.max, value); + ticks.push({ + value: lastTick, + major: isMajor(lastTick), + significand + }); + return ticks; +} +class LogarithmicScale extends Scale { + static id = 'logarithmic'; + static defaults = { + ticks: { + callback: Ticks.formatters.logarithmic, + major: { + enabled: true + } + } + }; + constructor(cfg){ + super(cfg); + this.start = undefined; + this.end = undefined; + this._startValue = undefined; + this._valueRange = 0; + } + parse(raw, index) { + const value = LinearScaleBase.prototype.parse.apply(this, [ + raw, + index + ]); + if (value === 0) { + this._zero = true; + return undefined; + } + return isNumberFinite(value) && value > 0 ? value : null; + } + determineDataLimits() { + const { min , max } = this.getMinMax(true); + this.min = isNumberFinite(min) ? Math.max(0, min) : null; + this.max = isNumberFinite(max) ? Math.max(0, max) : null; + if (this.options.beginAtZero) { + this._zero = true; + } + if (this._zero && this.min !== this._suggestedMin && !isNumberFinite(this._userMin)) { + this.min = min === changeExponent(this.min, 0) ? changeExponent(this.min, -1) : changeExponent(this.min, 0); + } + this.handleTickRangeOptions(); + } + handleTickRangeOptions() { + const { minDefined , maxDefined } = this.getUserBounds(); + let min = this.min; + let max = this.max; + const setMin = (v)=>min = minDefined ? min : v; + const setMax = (v)=>max = maxDefined ? max : v; + if (min === max) { + if (min <= 0) { + setMin(1); + setMax(10); + } else { + setMin(changeExponent(min, -1)); + setMax(changeExponent(max, +1)); + } + } + if (min <= 0) { + setMin(changeExponent(max, -1)); + } + if (max <= 0) { + setMax(changeExponent(min, +1)); + } + this.min = min; + this.max = max; + } + buildTicks() { + const opts = this.options; + const generationOptions = { + min: this._userMin, + max: this._userMax + }; + const ticks = generateTicks(generationOptions, this); + if (opts.bounds === 'ticks') { + _setMinAndMaxByKey(ticks, this, 'value'); + } + if (opts.reverse) { + ticks.reverse(); + this.start = this.max; + this.end = this.min; + } else { + this.start = this.min; + this.end = this.max; + } + return ticks; + } + getLabelForValue(value) { + return value === undefined ? '0' : formatNumber(value, this.chart.options.locale, this.options.ticks.format); + } + configure() { + const start = this.min; + super.configure(); + this._startValue = log10(start); + this._valueRange = log10(this.max) - log10(start); + } + getPixelForValue(value) { + if (value === undefined || value === 0) { + value = this.min; + } + if (value === null || isNaN(value)) { + return NaN; + } + return this.getPixelForDecimal(value === this.min ? 0 : (log10(value) - this._startValue) / this._valueRange); + } + getValueForPixel(pixel) { + const decimal = this.getDecimalForPixel(pixel); + return Math.pow(10, this._startValue + decimal * this._valueRange); + } +} + +function getTickBackdropHeight(opts) { + const tickOpts = opts.ticks; + if (tickOpts.display && opts.display) { + const padding = toPadding(tickOpts.backdropPadding); + return valueOrDefault(tickOpts.font && tickOpts.font.size, defaults.font.size) + padding.height; + } + return 0; +} +function measureLabelSize(ctx, font, label) { + label = isArray(label) ? label : [ + label + ]; + return { + w: _longestText(ctx, font.string, label), + h: label.length * font.lineHeight + }; +} +function determineLimits(angle, pos, size, min, max) { + if (angle === min || angle === max) { + return { + start: pos - size / 2, + end: pos + size / 2 + }; + } else if (angle < min || angle > max) { + return { + start: pos - size, + end: pos + }; + } + return { + start: pos, + end: pos + size + }; +} + function fitWithPointLabels(scale) { + const orig = { + l: scale.left + scale._padding.left, + r: scale.right - scale._padding.right, + t: scale.top + scale._padding.top, + b: scale.bottom - scale._padding.bottom + }; + const limits = Object.assign({}, orig); + const labelSizes = []; + const padding = []; + const valueCount = scale._pointLabels.length; + const pointLabelOpts = scale.options.pointLabels; + const additionalAngle = pointLabelOpts.centerPointLabels ? PI / valueCount : 0; + for(let i = 0; i < valueCount; i++){ + const opts = pointLabelOpts.setContext(scale.getPointLabelContext(i)); + padding[i] = opts.padding; + const pointPosition = scale.getPointPosition(i, scale.drawingArea + padding[i], additionalAngle); + const plFont = toFont(opts.font); + const textSize = measureLabelSize(scale.ctx, plFont, scale._pointLabels[i]); + labelSizes[i] = textSize; + const angleRadians = _normalizeAngle(scale.getIndexAngle(i) + additionalAngle); + const angle = Math.round(toDegrees(angleRadians)); + const hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180); + const vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270); + updateLimits(limits, orig, angleRadians, hLimits, vLimits); + } + scale.setCenterPoint(orig.l - limits.l, limits.r - orig.r, orig.t - limits.t, limits.b - orig.b); + scale._pointLabelItems = buildPointLabelItems(scale, labelSizes, padding); +} +function updateLimits(limits, orig, angle, hLimits, vLimits) { + const sin = Math.abs(Math.sin(angle)); + const cos = Math.abs(Math.cos(angle)); + let x = 0; + let y = 0; + if (hLimits.start < orig.l) { + x = (orig.l - hLimits.start) / sin; + limits.l = Math.min(limits.l, orig.l - x); + } else if (hLimits.end > orig.r) { + x = (hLimits.end - orig.r) / sin; + limits.r = Math.max(limits.r, orig.r + x); + } + if (vLimits.start < orig.t) { + y = (orig.t - vLimits.start) / cos; + limits.t = Math.min(limits.t, orig.t - y); + } else if (vLimits.end > orig.b) { + y = (vLimits.end - orig.b) / cos; + limits.b = Math.max(limits.b, orig.b + y); + } +} +function createPointLabelItem(scale, index, itemOpts) { + const outerDistance = scale.drawingArea; + const { extra , additionalAngle , padding , size } = itemOpts; + const pointLabelPosition = scale.getPointPosition(index, outerDistance + extra + padding, additionalAngle); + const angle = Math.round(toDegrees(_normalizeAngle(pointLabelPosition.angle + HALF_PI))); + const y = yForAngle(pointLabelPosition.y, size.h, angle); + const textAlign = getTextAlignForAngle(angle); + const left = leftForTextAlign(pointLabelPosition.x, size.w, textAlign); + return { + visible: true, + x: pointLabelPosition.x, + y, + textAlign, + left, + top: y, + right: left + size.w, + bottom: y + size.h + }; +} +function isNotOverlapped(item, area) { + if (!area) { + return true; + } + const { left , top , right , bottom } = item; + const apexesInArea = _isPointInArea({ + x: left, + y: top + }, area) || _isPointInArea({ + x: left, + y: bottom + }, area) || _isPointInArea({ + x: right, + y: top + }, area) || _isPointInArea({ + x: right, + y: bottom + }, area); + return !apexesInArea; +} +function buildPointLabelItems(scale, labelSizes, padding) { + const items = []; + const valueCount = scale._pointLabels.length; + const opts = scale.options; + const { centerPointLabels , display } = opts.pointLabels; + const itemOpts = { + extra: getTickBackdropHeight(opts) / 2, + additionalAngle: centerPointLabels ? PI / valueCount : 0 + }; + let area; + for(let i = 0; i < valueCount; i++){ + itemOpts.padding = padding[i]; + itemOpts.size = labelSizes[i]; + const item = createPointLabelItem(scale, i, itemOpts); + items.push(item); + if (display === 'auto') { + item.visible = isNotOverlapped(item, area); + if (item.visible) { + area = item; + } + } + } + return items; +} +function getTextAlignForAngle(angle) { + if (angle === 0 || angle === 180) { + return 'center'; + } else if (angle < 180) { + return 'left'; + } + return 'right'; +} +function leftForTextAlign(x, w, align) { + if (align === 'right') { + x -= w; + } else if (align === 'center') { + x -= w / 2; + } + return x; +} +function yForAngle(y, h, angle) { + if (angle === 90 || angle === 270) { + y -= h / 2; + } else if (angle > 270 || angle < 90) { + y -= h; + } + return y; +} +function drawPointLabelBox(ctx, opts, item) { + const { left , top , right , bottom } = item; + const { backdropColor } = opts; + if (!isNullOrUndef(backdropColor)) { + const borderRadius = toTRBLCorners(opts.borderRadius); + const padding = toPadding(opts.backdropPadding); + ctx.fillStyle = backdropColor; + const backdropLeft = left - padding.left; + const backdropTop = top - padding.top; + const backdropWidth = right - left + padding.width; + const backdropHeight = bottom - top + padding.height; + if (Object.values(borderRadius).some((v)=>v !== 0)) { + ctx.beginPath(); + addRoundedRectPath(ctx, { + x: backdropLeft, + y: backdropTop, + w: backdropWidth, + h: backdropHeight, + radius: borderRadius + }); + ctx.fill(); + } else { + ctx.fillRect(backdropLeft, backdropTop, backdropWidth, backdropHeight); + } + } +} +function drawPointLabels(scale, labelCount) { + const { ctx , options: { pointLabels } } = scale; + for(let i = labelCount - 1; i >= 0; i--){ + const item = scale._pointLabelItems[i]; + if (!item.visible) { + continue; + } + const optsAtIndex = pointLabels.setContext(scale.getPointLabelContext(i)); + drawPointLabelBox(ctx, optsAtIndex, item); + const plFont = toFont(optsAtIndex.font); + const { x , y , textAlign } = item; + renderText(ctx, scale._pointLabels[i], x, y + plFont.lineHeight / 2, plFont, { + color: optsAtIndex.color, + textAlign: textAlign, + textBaseline: 'middle' + }); + } +} +function pathRadiusLine(scale, radius, circular, labelCount) { + const { ctx } = scale; + if (circular) { + ctx.arc(scale.xCenter, scale.yCenter, radius, 0, TAU); + } else { + let pointPosition = scale.getPointPosition(0, radius); + ctx.moveTo(pointPosition.x, pointPosition.y); + for(let i = 1; i < labelCount; i++){ + pointPosition = scale.getPointPosition(i, radius); + ctx.lineTo(pointPosition.x, pointPosition.y); + } + } +} +function drawRadiusLine(scale, gridLineOpts, radius, labelCount, borderOpts) { + const ctx = scale.ctx; + const circular = gridLineOpts.circular; + const { color , lineWidth } = gridLineOpts; + if (!circular && !labelCount || !color || !lineWidth || radius < 0) { + return; + } + ctx.save(); + ctx.strokeStyle = color; + ctx.lineWidth = lineWidth; + ctx.setLineDash(borderOpts.dash || []); + ctx.lineDashOffset = borderOpts.dashOffset; + ctx.beginPath(); + pathRadiusLine(scale, radius, circular, labelCount); + ctx.closePath(); + ctx.stroke(); + ctx.restore(); +} +function createPointLabelContext(parent, index, label) { + return createContext(parent, { + label, + index, + type: 'pointLabel' + }); +} +class RadialLinearScale extends LinearScaleBase { + static id = 'radialLinear'; + static defaults = { + display: true, + animate: true, + position: 'chartArea', + angleLines: { + display: true, + lineWidth: 1, + borderDash: [], + borderDashOffset: 0.0 + }, + grid: { + circular: false + }, + startAngle: 0, + ticks: { + showLabelBackdrop: true, + callback: Ticks.formatters.numeric + }, + pointLabels: { + backdropColor: undefined, + backdropPadding: 2, + display: true, + font: { + size: 10 + }, + callback (label) { + return label; + }, + padding: 5, + centerPointLabels: false + } + }; + static defaultRoutes = { + 'angleLines.color': 'borderColor', + 'pointLabels.color': 'color', + 'ticks.color': 'color' + }; + static descriptors = { + angleLines: { + _fallback: 'grid' + } + }; + constructor(cfg){ + super(cfg); + this.xCenter = undefined; + this.yCenter = undefined; + this.drawingArea = undefined; + this._pointLabels = []; + this._pointLabelItems = []; + } + setDimensions() { + const padding = this._padding = toPadding(getTickBackdropHeight(this.options) / 2); + const w = this.width = this.maxWidth - padding.width; + const h = this.height = this.maxHeight - padding.height; + this.xCenter = Math.floor(this.left + w / 2 + padding.left); + this.yCenter = Math.floor(this.top + h / 2 + padding.top); + this.drawingArea = Math.floor(Math.min(w, h) / 2); + } + determineDataLimits() { + const { min , max } = this.getMinMax(false); + this.min = isNumberFinite(min) && !isNaN(min) ? min : 0; + this.max = isNumberFinite(max) && !isNaN(max) ? max : 0; + this.handleTickRangeOptions(); + } + computeTickLimit() { + return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options)); + } + generateTickLabels(ticks) { + LinearScaleBase.prototype.generateTickLabels.call(this, ticks); + this._pointLabels = this.getLabels().map((value, index)=>{ + const label = callback(this.options.pointLabels.callback, [ + value, + index + ], this); + return label || label === 0 ? label : ''; + }).filter((v, i)=>this.chart.getDataVisibility(i)); + } + fit() { + const opts = this.options; + if (opts.display && opts.pointLabels.display) { + fitWithPointLabels(this); + } else { + this.setCenterPoint(0, 0, 0, 0); + } + } + setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) { + this.xCenter += Math.floor((leftMovement - rightMovement) / 2); + this.yCenter += Math.floor((topMovement - bottomMovement) / 2); + this.drawingArea -= Math.min(this.drawingArea / 2, Math.max(leftMovement, rightMovement, topMovement, bottomMovement)); + } + getIndexAngle(index) { + const angleMultiplier = TAU / (this._pointLabels.length || 1); + const startAngle = this.options.startAngle || 0; + return _normalizeAngle(index * angleMultiplier + toRadians(startAngle)); + } + getDistanceFromCenterForValue(value) { + if (isNullOrUndef(value)) { + return NaN; + } + const scalingFactor = this.drawingArea / (this.max - this.min); + if (this.options.reverse) { + return (this.max - value) * scalingFactor; + } + return (value - this.min) * scalingFactor; + } + getValueForDistanceFromCenter(distance) { + if (isNullOrUndef(distance)) { + return NaN; + } + const scaledDistance = distance / (this.drawingArea / (this.max - this.min)); + return this.options.reverse ? this.max - scaledDistance : this.min + scaledDistance; + } + getPointLabelContext(index) { + const pointLabels = this._pointLabels || []; + if (index >= 0 && index < pointLabels.length) { + const pointLabel = pointLabels[index]; + return createPointLabelContext(this.getContext(), index, pointLabel); + } + } + getPointPosition(index, distanceFromCenter, additionalAngle = 0) { + const angle = this.getIndexAngle(index) - HALF_PI + additionalAngle; + return { + x: Math.cos(angle) * distanceFromCenter + this.xCenter, + y: Math.sin(angle) * distanceFromCenter + this.yCenter, + angle + }; + } + getPointPositionForValue(index, value) { + return this.getPointPosition(index, this.getDistanceFromCenterForValue(value)); + } + getBasePosition(index) { + return this.getPointPositionForValue(index || 0, this.getBaseValue()); + } + getPointLabelPosition(index) { + const { left , top , right , bottom } = this._pointLabelItems[index]; + return { + left, + top, + right, + bottom + }; + } + drawBackground() { + const { backgroundColor , grid: { circular } } = this.options; + if (backgroundColor) { + const ctx = this.ctx; + ctx.save(); + ctx.beginPath(); + pathRadiusLine(this, this.getDistanceFromCenterForValue(this._endValue), circular, this._pointLabels.length); + ctx.closePath(); + ctx.fillStyle = backgroundColor; + ctx.fill(); + ctx.restore(); + } + } + drawGrid() { + const ctx = this.ctx; + const opts = this.options; + const { angleLines , grid , border } = opts; + const labelCount = this._pointLabels.length; + let i, offset, position; + if (opts.pointLabels.display) { + drawPointLabels(this, labelCount); + } + if (grid.display) { + this.ticks.forEach((tick, index)=>{ + if (index !== 0 || index === 0 && this.min < 0) { + offset = this.getDistanceFromCenterForValue(tick.value); + const context = this.getContext(index); + const optsAtIndex = grid.setContext(context); + const optsAtIndexBorder = border.setContext(context); + drawRadiusLine(this, optsAtIndex, offset, labelCount, optsAtIndexBorder); + } + }); + } + if (angleLines.display) { + ctx.save(); + for(i = labelCount - 1; i >= 0; i--){ + const optsAtIndex = angleLines.setContext(this.getPointLabelContext(i)); + const { color , lineWidth } = optsAtIndex; + if (!lineWidth || !color) { + continue; + } + ctx.lineWidth = lineWidth; + ctx.strokeStyle = color; + ctx.setLineDash(optsAtIndex.borderDash); + ctx.lineDashOffset = optsAtIndex.borderDashOffset; + offset = this.getDistanceFromCenterForValue(opts.reverse ? this.min : this.max); + position = this.getPointPosition(i, offset); + ctx.beginPath(); + ctx.moveTo(this.xCenter, this.yCenter); + ctx.lineTo(position.x, position.y); + ctx.stroke(); + } + ctx.restore(); + } + } + drawBorder() {} + drawLabels() { + const ctx = this.ctx; + const opts = this.options; + const tickOpts = opts.ticks; + if (!tickOpts.display) { + return; + } + const startAngle = this.getIndexAngle(0); + let offset, width; + ctx.save(); + ctx.translate(this.xCenter, this.yCenter); + ctx.rotate(startAngle); + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + this.ticks.forEach((tick, index)=>{ + if (index === 0 && this.min >= 0 && !opts.reverse) { + return; + } + const optsAtIndex = tickOpts.setContext(this.getContext(index)); + const tickFont = toFont(optsAtIndex.font); + offset = this.getDistanceFromCenterForValue(this.ticks[index].value); + if (optsAtIndex.showLabelBackdrop) { + ctx.font = tickFont.string; + width = ctx.measureText(tick.label).width; + ctx.fillStyle = optsAtIndex.backdropColor; + const padding = toPadding(optsAtIndex.backdropPadding); + ctx.fillRect(-width / 2 - padding.left, -offset - tickFont.size / 2 - padding.top, width + padding.width, tickFont.size + padding.height); + } + renderText(ctx, tick.label, 0, -offset, tickFont, { + color: optsAtIndex.color, + strokeColor: optsAtIndex.textStrokeColor, + strokeWidth: optsAtIndex.textStrokeWidth + }); + }); + ctx.restore(); + } + drawTitle() {} +} + +const INTERVALS = { + millisecond: { + common: true, + size: 1, + steps: 1000 + }, + second: { + common: true, + size: 1000, + steps: 60 + }, + minute: { + common: true, + size: 60000, + steps: 60 + }, + hour: { + common: true, + size: 3600000, + steps: 24 + }, + day: { + common: true, + size: 86400000, + steps: 30 + }, + week: { + common: false, + size: 604800000, + steps: 4 + }, + month: { + common: true, + size: 2.628e9, + steps: 12 + }, + quarter: { + common: false, + size: 7.884e9, + steps: 4 + }, + year: { + common: true, + size: 3.154e10 + } +}; + const UNITS = /* #__PURE__ */ Object.keys(INTERVALS); + function sorter(a, b) { + return a - b; +} + function parse(scale, input) { + if (isNullOrUndef(input)) { + return null; + } + const adapter = scale._adapter; + const { parser , round , isoWeekday } = scale._parseOpts; + let value = input; + if (typeof parser === 'function') { + value = parser(value); + } + if (!isNumberFinite(value)) { + value = typeof parser === 'string' ? adapter.parse(value, parser) : adapter.parse(value); + } + if (value === null) { + return null; + } + if (round) { + value = round === 'week' && (isNumber(isoWeekday) || isoWeekday === true) ? adapter.startOf(value, 'isoWeek', isoWeekday) : adapter.startOf(value, round); + } + return +value; +} + function determineUnitForAutoTicks(minUnit, min, max, capacity) { + const ilen = UNITS.length; + for(let i = UNITS.indexOf(minUnit); i < ilen - 1; ++i){ + const interval = INTERVALS[UNITS[i]]; + const factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER; + if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) { + return UNITS[i]; + } + } + return UNITS[ilen - 1]; +} + function determineUnitForFormatting(scale, numTicks, minUnit, min, max) { + for(let i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--){ + const unit = UNITS[i]; + if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) { + return unit; + } + } + return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0]; +} + function determineMajorUnit(unit) { + for(let i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i){ + if (INTERVALS[UNITS[i]].common) { + return UNITS[i]; + } + } +} + function addTick(ticks, time, timestamps) { + if (!timestamps) { + ticks[time] = true; + } else if (timestamps.length) { + const { lo , hi } = _lookup(timestamps, time); + const timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi]; + ticks[timestamp] = true; + } +} + function setMajorTicks(scale, ticks, map, majorUnit) { + const adapter = scale._adapter; + const first = +adapter.startOf(ticks[0].value, majorUnit); + const last = ticks[ticks.length - 1].value; + let major, index; + for(major = first; major <= last; major = +adapter.add(major, 1, majorUnit)){ + index = map[major]; + if (index >= 0) { + ticks[index].major = true; + } + } + return ticks; +} + function ticksFromTimestamps(scale, values, majorUnit) { + const ticks = []; + const map = {}; + const ilen = values.length; + let i, value; + for(i = 0; i < ilen; ++i){ + value = values[i]; + map[value] = i; + ticks.push({ + value, + major: false + }); + } + return ilen === 0 || !majorUnit ? ticks : setMajorTicks(scale, ticks, map, majorUnit); +} +class TimeScale extends Scale { + static id = 'time'; + static defaults = { + bounds: 'data', + adapters: {}, + time: { + parser: false, + unit: false, + round: false, + isoWeekday: false, + minUnit: 'millisecond', + displayFormats: {} + }, + ticks: { + source: 'auto', + callback: false, + major: { + enabled: false + } + } + }; + constructor(props){ + super(props); + this._cache = { + data: [], + labels: [], + all: [] + }; + this._unit = 'day'; + this._majorUnit = undefined; + this._offsets = {}; + this._normalized = false; + this._parseOpts = undefined; + } + init(scaleOpts, opts = {}) { + const time = scaleOpts.time || (scaleOpts.time = {}); + const adapter = this._adapter = new adapters._date(scaleOpts.adapters.date); + adapter.init(opts); + mergeIf(time.displayFormats, adapter.formats()); + this._parseOpts = { + parser: time.parser, + round: time.round, + isoWeekday: time.isoWeekday + }; + super.init(scaleOpts); + this._normalized = opts.normalized; + } + parse(raw, index) { + if (raw === undefined) { + return null; + } + return parse(this, raw); + } + beforeLayout() { + super.beforeLayout(); + this._cache = { + data: [], + labels: [], + all: [] + }; + } + determineDataLimits() { + const options = this.options; + const adapter = this._adapter; + const unit = options.time.unit || 'day'; + let { min , max , minDefined , maxDefined } = this.getUserBounds(); + function _applyBounds(bounds) { + if (!minDefined && !isNaN(bounds.min)) { + min = Math.min(min, bounds.min); + } + if (!maxDefined && !isNaN(bounds.max)) { + max = Math.max(max, bounds.max); + } + } + if (!minDefined || !maxDefined) { + _applyBounds(this._getLabelBounds()); + if (options.bounds !== 'ticks' || options.ticks.source !== 'labels') { + _applyBounds(this.getMinMax(false)); + } + } + min = isNumberFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit); + max = isNumberFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1; + this.min = Math.min(min, max - 1); + this.max = Math.max(min + 1, max); + } + _getLabelBounds() { + const arr = this.getLabelTimestamps(); + let min = Number.POSITIVE_INFINITY; + let max = Number.NEGATIVE_INFINITY; + if (arr.length) { + min = arr[0]; + max = arr[arr.length - 1]; + } + return { + min, + max + }; + } + buildTicks() { + const options = this.options; + const timeOpts = options.time; + const tickOpts = options.ticks; + const timestamps = tickOpts.source === 'labels' ? this.getLabelTimestamps() : this._generate(); + if (options.bounds === 'ticks' && timestamps.length) { + this.min = this._userMin || timestamps[0]; + this.max = this._userMax || timestamps[timestamps.length - 1]; + } + const min = this.min; + const max = this.max; + const ticks = _filterBetween(timestamps, min, max); + this._unit = timeOpts.unit || (tickOpts.autoSkip ? determineUnitForAutoTicks(timeOpts.minUnit, this.min, this.max, this._getLabelCapacity(min)) : determineUnitForFormatting(this, ticks.length, timeOpts.minUnit, this.min, this.max)); + this._majorUnit = !tickOpts.major.enabled || this._unit === 'year' ? undefined : determineMajorUnit(this._unit); + this.initOffsets(timestamps); + if (options.reverse) { + ticks.reverse(); + } + return ticksFromTimestamps(this, ticks, this._majorUnit); + } + afterAutoSkip() { + if (this.options.offsetAfterAutoskip) { + this.initOffsets(this.ticks.map((tick)=>+tick.value)); + } + } + initOffsets(timestamps = []) { + let start = 0; + let end = 0; + let first, last; + if (this.options.offset && timestamps.length) { + first = this.getDecimalForValue(timestamps[0]); + if (timestamps.length === 1) { + start = 1 - first; + } else { + start = (this.getDecimalForValue(timestamps[1]) - first) / 2; + } + last = this.getDecimalForValue(timestamps[timestamps.length - 1]); + if (timestamps.length === 1) { + end = last; + } else { + end = (last - this.getDecimalForValue(timestamps[timestamps.length - 2])) / 2; + } + } + const limit = timestamps.length < 3 ? 0.5 : 0.25; + start = _limitValue(start, 0, limit); + end = _limitValue(end, 0, limit); + this._offsets = { + start, + end, + factor: 1 / (start + 1 + end) + }; + } + _generate() { + const adapter = this._adapter; + const min = this.min; + const max = this.max; + const options = this.options; + const timeOpts = options.time; + const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, this._getLabelCapacity(min)); + const stepSize = valueOrDefault(options.ticks.stepSize, 1); + const weekday = minor === 'week' ? timeOpts.isoWeekday : false; + const hasWeekday = isNumber(weekday) || weekday === true; + const ticks = {}; + let first = min; + let time, count; + if (hasWeekday) { + first = +adapter.startOf(first, 'isoWeek', weekday); + } + first = +adapter.startOf(first, hasWeekday ? 'day' : minor); + if (adapter.diff(max, min, minor) > 100000 * stepSize) { + throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor); + } + const timestamps = options.ticks.source === 'data' && this.getDataTimestamps(); + for(time = first, count = 0; time < max; time = +adapter.add(time, stepSize, minor), count++){ + addTick(ticks, time, timestamps); + } + if (time === max || options.bounds === 'ticks' || count === 1) { + addTick(ticks, time, timestamps); + } + return Object.keys(ticks).sort(sorter).map((x)=>+x); + } + getLabelForValue(value) { + const adapter = this._adapter; + const timeOpts = this.options.time; + if (timeOpts.tooltipFormat) { + return adapter.format(value, timeOpts.tooltipFormat); + } + return adapter.format(value, timeOpts.displayFormats.datetime); + } + format(value, format) { + const options = this.options; + const formats = options.time.displayFormats; + const unit = this._unit; + const fmt = format || formats[unit]; + return this._adapter.format(value, fmt); + } + _tickFormatFunction(time, index, ticks, format) { + const options = this.options; + const formatter = options.ticks.callback; + if (formatter) { + return callback(formatter, [ + time, + index, + ticks + ], this); + } + const formats = options.time.displayFormats; + const unit = this._unit; + const majorUnit = this._majorUnit; + const minorFormat = unit && formats[unit]; + const majorFormat = majorUnit && formats[majorUnit]; + const tick = ticks[index]; + const major = majorUnit && majorFormat && tick && tick.major; + return this._adapter.format(time, format || (major ? majorFormat : minorFormat)); + } + generateTickLabels(ticks) { + let i, ilen, tick; + for(i = 0, ilen = ticks.length; i < ilen; ++i){ + tick = ticks[i]; + tick.label = this._tickFormatFunction(tick.value, i, ticks); + } + } + getDecimalForValue(value) { + return value === null ? NaN : (value - this.min) / (this.max - this.min); + } + getPixelForValue(value) { + const offsets = this._offsets; + const pos = this.getDecimalForValue(value); + return this.getPixelForDecimal((offsets.start + pos) * offsets.factor); + } + getValueForPixel(pixel) { + const offsets = this._offsets; + const pos = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end; + return this.min + pos * (this.max - this.min); + } + _getLabelSize(label) { + const ticksOpts = this.options.ticks; + const tickLabelWidth = this.ctx.measureText(label).width; + const angle = toRadians(this.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation); + const cosRotation = Math.cos(angle); + const sinRotation = Math.sin(angle); + const tickFontSize = this._resolveTickFontOptions(0).size; + return { + w: tickLabelWidth * cosRotation + tickFontSize * sinRotation, + h: tickLabelWidth * sinRotation + tickFontSize * cosRotation + }; + } + _getLabelCapacity(exampleTime) { + const timeOpts = this.options.time; + const displayFormats = timeOpts.displayFormats; + const format = displayFormats[timeOpts.unit] || displayFormats.millisecond; + const exampleLabel = this._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(this, [ + exampleTime + ], this._majorUnit), format); + const size = this._getLabelSize(exampleLabel); + const capacity = Math.floor(this.isHorizontal() ? this.width / size.w : this.height / size.h) - 1; + return capacity > 0 ? capacity : 1; + } + getDataTimestamps() { + let timestamps = this._cache.data || []; + let i, ilen; + if (timestamps.length) { + return timestamps; + } + const metas = this.getMatchingVisibleMetas(); + if (this._normalized && metas.length) { + return this._cache.data = metas[0].controller.getAllParsedValues(this); + } + for(i = 0, ilen = metas.length; i < ilen; ++i){ + timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(this)); + } + return this._cache.data = this.normalize(timestamps); + } + getLabelTimestamps() { + const timestamps = this._cache.labels || []; + let i, ilen; + if (timestamps.length) { + return timestamps; + } + const labels = this.getLabels(); + for(i = 0, ilen = labels.length; i < ilen; ++i){ + timestamps.push(parse(this, labels[i])); + } + return this._cache.labels = this._normalized ? timestamps : this.normalize(timestamps); + } + normalize(values) { + return _arrayUnique(values.sort(sorter)); + } +} + +function interpolate(table, val, reverse) { + let lo = 0; + let hi = table.length - 1; + let prevSource, nextSource, prevTarget, nextTarget; + if (reverse) { + if (val >= table[lo].pos && val <= table[hi].pos) { + ({ lo , hi } = _lookupByKey(table, 'pos', val)); + } + ({ pos: prevSource , time: prevTarget } = table[lo]); + ({ pos: nextSource , time: nextTarget } = table[hi]); + } else { + if (val >= table[lo].time && val <= table[hi].time) { + ({ lo , hi } = _lookupByKey(table, 'time', val)); + } + ({ time: prevSource , pos: prevTarget } = table[lo]); + ({ time: nextSource , pos: nextTarget } = table[hi]); + } + const span = nextSource - prevSource; + return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget; +} +class TimeSeriesScale extends TimeScale { + static id = 'timeseries'; + static defaults = TimeScale.defaults; + constructor(props){ + super(props); + this._table = []; + this._minPos = undefined; + this._tableRange = undefined; + } + initOffsets() { + const timestamps = this._getTimestampsForTable(); + const table = this._table = this.buildLookupTable(timestamps); + this._minPos = interpolate(table, this.min); + this._tableRange = interpolate(table, this.max) - this._minPos; + super.initOffsets(timestamps); + } + buildLookupTable(timestamps) { + const { min , max } = this; + const items = []; + const table = []; + let i, ilen, prev, curr, next; + for(i = 0, ilen = timestamps.length; i < ilen; ++i){ + curr = timestamps[i]; + if (curr >= min && curr <= max) { + items.push(curr); + } + } + if (items.length < 2) { + return [ + { + time: min, + pos: 0 + }, + { + time: max, + pos: 1 + } + ]; + } + for(i = 0, ilen = items.length; i < ilen; ++i){ + next = items[i + 1]; + prev = items[i - 1]; + curr = items[i]; + if (Math.round((next + prev) / 2) !== curr) { + table.push({ + time: curr, + pos: i / (ilen - 1) + }); + } + } + return table; + } + _generate() { + const min = this.min; + const max = this.max; + let timestamps = super.getDataTimestamps(); + if (!timestamps.includes(min) || !timestamps.length) { + timestamps.splice(0, 0, min); + } + if (!timestamps.includes(max) || timestamps.length === 1) { + timestamps.push(max); + } + return timestamps.sort((a, b)=>a - b); + } + _getTimestampsForTable() { + let timestamps = this._cache.all || []; + if (timestamps.length) { + return timestamps; + } + const data = this.getDataTimestamps(); + const label = this.getLabelTimestamps(); + if (data.length && label.length) { + timestamps = this.normalize(data.concat(label)); + } else { + timestamps = data.length ? data : label; + } + timestamps = this._cache.all = timestamps; + return timestamps; + } + getDecimalForValue(value) { + return (interpolate(this._table, value) - this._minPos) / this._tableRange; + } + getValueForPixel(pixel) { + const offsets = this._offsets; + const decimal = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end; + return interpolate(this._table, decimal * this._tableRange + this._minPos, true); + } +} + +var scales = /*#__PURE__*/Object.freeze({ +__proto__: null, +CategoryScale: CategoryScale, +LinearScale: LinearScale, +LogarithmicScale: LogarithmicScale, +RadialLinearScale: RadialLinearScale, +TimeScale: TimeScale, +TimeSeriesScale: TimeSeriesScale +}); + +const registerables = [ + controllers, + elements, + plugins, + scales +]; + +export { Animation, Animations, ArcElement, BarController, BarElement, BasePlatform, BasicPlatform, BubbleController, CategoryScale, Chart, plugin_colors as Colors, DatasetController, plugin_decimation as Decimation, DomPlatform, DoughnutController, Element, index as Filler, Interaction, plugin_legend as Legend, LineController, LineElement, LinearScale, LogarithmicScale, PieController, PointElement, PolarAreaController, RadarController, RadialLinearScale, Scale, ScatterController, plugin_subtitle as SubTitle, Ticks, TimeScale, TimeSeriesScale, plugin_title as Title, plugin_tooltip as Tooltip, adapters as _adapters, _detectPlatform, animator, controllers, defaults, elements, layouts, plugins, registerables, registry, scales }; +//# sourceMappingURL=chart.js.map diff --git a/frontend/node_modules/chart.js/dist/chart.js.map b/frontend/node_modules/chart.js/dist/chart.js.map new file mode 100644 index 0000000000000000000000000000000000000000..80b2c674d79b85257dcef168a2d0dacdecfcc168 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/chart.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chart.js","sources":["../src/core/core.animator.js","../src/core/core.animation.js","../src/core/core.animations.js","../src/core/core.datasetController.js","../src/controllers/controller.bar.js","../src/controllers/controller.bubble.js","../src/controllers/controller.doughnut.js","../src/controllers/controller.line.js","../src/controllers/controller.polarArea.js","../src/controllers/controller.pie.js","../src/controllers/controller.radar.js","../src/controllers/controller.scatter.js","../src/core/core.adapters.ts","../src/core/core.interaction.js","../src/core/core.layouts.js","../src/platform/platform.base.js","../src/platform/platform.basic.js","../src/platform/platform.dom.js","../src/platform/index.js","../src/core/core.element.ts","../src/core/core.scale.autoskip.js","../src/core/core.scale.js","../src/core/core.typedRegistry.js","../src/core/core.registry.js","../src/core/core.plugins.js","../src/core/core.config.js","../src/core/core.controller.js","../src/elements/element.arc.ts","../src/elements/element.line.js","../src/elements/element.point.ts","../src/elements/element.bar.js","../src/plugins/plugin.colors.ts","../src/plugins/plugin.decimation.js","../src/plugins/plugin.filler/filler.segment.js","../src/plugins/plugin.filler/filler.helper.js","../src/plugins/plugin.filler/filler.options.js","../src/plugins/plugin.filler/filler.target.stack.js","../src/plugins/plugin.filler/simpleArc.js","../src/plugins/plugin.filler/filler.target.js","../src/plugins/plugin.filler/filler.drawing.js","../src/plugins/plugin.filler/index.js","../src/plugins/plugin.legend.js","../src/plugins/plugin.title.js","../src/plugins/plugin.subtitle.js","../src/plugins/plugin.tooltip.js","../src/scales/scale.category.js","../src/scales/scale.linearbase.js","../src/scales/scale.linear.js","../src/scales/scale.logarithmic.js","../src/scales/scale.radialLinear.js","../src/scales/scale.time.js","../src/scales/scale.timeseries.js","../src/index.ts"],"sourcesContent":["import {requestAnimFrame} from '../helpers/helpers.extras.js';\n\n/**\n * @typedef { import('./core.animation.js').default } Animation\n * @typedef { import('./core.controller.js').default } Chart\n */\n\n/**\n * Please use the module's default export which provides a singleton instance\n * Note: class is export for typedoc\n */\nexport class Animator {\n constructor() {\n this._request = null;\n this._charts = new Map();\n this._running = false;\n this._lastDate = undefined;\n }\n\n /**\n\t * @private\n\t */\n _notify(chart, anims, date, type) {\n const callbacks = anims.listeners[type];\n const numSteps = anims.duration;\n\n callbacks.forEach(fn => fn({\n chart,\n initial: anims.initial,\n numSteps,\n currentStep: Math.min(date - anims.start, numSteps)\n }));\n }\n\n /**\n\t * @private\n\t */\n _refresh() {\n if (this._request) {\n return;\n }\n this._running = true;\n\n this._request = requestAnimFrame.call(window, () => {\n this._update();\n this._request = null;\n\n if (this._running) {\n this._refresh();\n }\n });\n }\n\n /**\n\t * @private\n\t */\n _update(date = Date.now()) {\n let remaining = 0;\n\n this._charts.forEach((anims, chart) => {\n if (!anims.running || !anims.items.length) {\n return;\n }\n const items = anims.items;\n let i = items.length - 1;\n let draw = false;\n let item;\n\n for (; i >= 0; --i) {\n item = items[i];\n\n if (item._active) {\n if (item._total > anims.duration) {\n // if the animation has been updated and its duration prolonged,\n // update to total duration of current animations run (for progress event)\n anims.duration = item._total;\n }\n item.tick(date);\n draw = true;\n } else {\n // Remove the item by replacing it with last item and removing the last\n // A lot faster than splice.\n items[i] = items[items.length - 1];\n items.pop();\n }\n }\n\n if (draw) {\n chart.draw();\n this._notify(chart, anims, date, 'progress');\n }\n\n if (!items.length) {\n anims.running = false;\n this._notify(chart, anims, date, 'complete');\n anims.initial = false;\n }\n\n remaining += items.length;\n });\n\n this._lastDate = date;\n\n if (remaining === 0) {\n this._running = false;\n }\n }\n\n /**\n\t * @private\n\t */\n _getAnims(chart) {\n const charts = this._charts;\n let anims = charts.get(chart);\n if (!anims) {\n anims = {\n running: false,\n initial: true,\n items: [],\n listeners: {\n complete: [],\n progress: []\n }\n };\n charts.set(chart, anims);\n }\n return anims;\n }\n\n /**\n\t * @param {Chart} chart\n\t * @param {string} event - event name\n\t * @param {Function} cb - callback\n\t */\n listen(chart, event, cb) {\n this._getAnims(chart).listeners[event].push(cb);\n }\n\n /**\n\t * Add animations\n\t * @param {Chart} chart\n\t * @param {Animation[]} items - animations\n\t */\n add(chart, items) {\n if (!items || !items.length) {\n return;\n }\n this._getAnims(chart).items.push(...items);\n }\n\n /**\n\t * Counts number of active animations for the chart\n\t * @param {Chart} chart\n\t */\n has(chart) {\n return this._getAnims(chart).items.length > 0;\n }\n\n /**\n\t * Start animating (all charts)\n\t * @param {Chart} chart\n\t */\n start(chart) {\n const anims = this._charts.get(chart);\n if (!anims) {\n return;\n }\n anims.running = true;\n anims.start = Date.now();\n anims.duration = anims.items.reduce((acc, cur) => Math.max(acc, cur._duration), 0);\n this._refresh();\n }\n\n running(chart) {\n if (!this._running) {\n return false;\n }\n const anims = this._charts.get(chart);\n if (!anims || !anims.running || !anims.items.length) {\n return false;\n }\n return true;\n }\n\n /**\n\t * Stop all animations for the chart\n\t * @param {Chart} chart\n\t */\n stop(chart) {\n const anims = this._charts.get(chart);\n if (!anims || !anims.items.length) {\n return;\n }\n const items = anims.items;\n let i = items.length - 1;\n\n for (; i >= 0; --i) {\n items[i].cancel();\n }\n anims.items = [];\n this._notify(chart, anims, Date.now(), 'complete');\n }\n\n /**\n\t * Remove chart from Animator\n\t * @param {Chart} chart\n\t */\n remove(chart) {\n return this._charts.delete(chart);\n }\n}\n\n// singleton instance\nexport default /* #__PURE__ */ new Animator();\n","import effects from '../helpers/helpers.easing.js';\nimport {resolve} from '../helpers/helpers.options.js';\nimport {color as helpersColor} from '../helpers/helpers.color.js';\n\nconst transparent = 'transparent';\nconst interpolators = {\n boolean(from, to, factor) {\n return factor > 0.5 ? to : from;\n },\n /**\n * @param {string} from\n * @param {string} to\n * @param {number} factor\n */\n color(from, to, factor) {\n const c0 = helpersColor(from || transparent);\n const c1 = c0.valid && helpersColor(to || transparent);\n return c1 && c1.valid\n ? c1.mix(c0, factor).hexString()\n : to;\n },\n number(from, to, factor) {\n return from + (to - from) * factor;\n }\n};\n\nexport default class Animation {\n constructor(cfg, target, prop, to) {\n const currentValue = target[prop];\n\n to = resolve([cfg.to, to, currentValue, cfg.from]);\n const from = resolve([cfg.from, currentValue, to]);\n\n this._active = true;\n this._fn = cfg.fn || interpolators[cfg.type || typeof from];\n this._easing = effects[cfg.easing] || effects.linear;\n this._start = Math.floor(Date.now() + (cfg.delay || 0));\n this._duration = this._total = Math.floor(cfg.duration);\n this._loop = !!cfg.loop;\n this._target = target;\n this._prop = prop;\n this._from = from;\n this._to = to;\n this._promises = undefined;\n }\n\n active() {\n return this._active;\n }\n\n update(cfg, to, date) {\n if (this._active) {\n this._notify(false);\n\n const currentValue = this._target[this._prop];\n const elapsed = date - this._start;\n const remain = this._duration - elapsed;\n this._start = date;\n this._duration = Math.floor(Math.max(remain, cfg.duration));\n this._total += elapsed;\n this._loop = !!cfg.loop;\n this._to = resolve([cfg.to, to, currentValue, cfg.from]);\n this._from = resolve([cfg.from, currentValue, to]);\n }\n }\n\n cancel() {\n if (this._active) {\n // update current evaluated value, for smoother animations\n this.tick(Date.now());\n this._active = false;\n this._notify(false);\n }\n }\n\n tick(date) {\n const elapsed = date - this._start;\n const duration = this._duration;\n const prop = this._prop;\n const from = this._from;\n const loop = this._loop;\n const to = this._to;\n let factor;\n\n this._active = from !== to && (loop || (elapsed < duration));\n\n if (!this._active) {\n this._target[prop] = to;\n this._notify(true);\n return;\n }\n\n if (elapsed < 0) {\n this._target[prop] = from;\n return;\n }\n\n factor = (elapsed / duration) % 2;\n factor = loop && factor > 1 ? 2 - factor : factor;\n factor = this._easing(Math.min(1, Math.max(0, factor)));\n\n this._target[prop] = this._fn(from, to, factor);\n }\n\n wait() {\n const promises = this._promises || (this._promises = []);\n return new Promise((res, rej) => {\n promises.push({res, rej});\n });\n }\n\n _notify(resolved) {\n const method = resolved ? 'res' : 'rej';\n const promises = this._promises || [];\n for (let i = 0; i < promises.length; i++) {\n promises[i][method]();\n }\n }\n}\n","import animator from './core.animator.js';\nimport Animation from './core.animation.js';\nimport defaults from './core.defaults.js';\nimport {isArray, isObject} from '../helpers/helpers.core.js';\n\nexport default class Animations {\n constructor(chart, config) {\n this._chart = chart;\n this._properties = new Map();\n this.configure(config);\n }\n\n configure(config) {\n if (!isObject(config)) {\n return;\n }\n\n const animationOptions = Object.keys(defaults.animation);\n const animatedProps = this._properties;\n\n Object.getOwnPropertyNames(config).forEach(key => {\n const cfg = config[key];\n if (!isObject(cfg)) {\n return;\n }\n const resolved = {};\n for (const option of animationOptions) {\n resolved[option] = cfg[option];\n }\n\n (isArray(cfg.properties) && cfg.properties || [key]).forEach((prop) => {\n if (prop === key || !animatedProps.has(prop)) {\n animatedProps.set(prop, resolved);\n }\n });\n });\n }\n\n /**\n\t * Utility to handle animation of `options`.\n\t * @private\n\t */\n _animateOptions(target, values) {\n const newOptions = values.options;\n const options = resolveTargetOptions(target, newOptions);\n if (!options) {\n return [];\n }\n\n const animations = this._createAnimations(options, newOptions);\n if (newOptions.$shared) {\n // Going to shared options:\n // After all animations are done, assign the shared options object to the element\n // So any new updates to the shared options are observed\n awaitAll(target.options.$animations, newOptions).then(() => {\n target.options = newOptions;\n }, () => {\n // rejected, noop\n });\n }\n\n return animations;\n }\n\n /**\n\t * @private\n\t */\n _createAnimations(target, values) {\n const animatedProps = this._properties;\n const animations = [];\n const running = target.$animations || (target.$animations = {});\n const props = Object.keys(values);\n const date = Date.now();\n let i;\n\n for (i = props.length - 1; i >= 0; --i) {\n const prop = props[i];\n if (prop.charAt(0) === '$') {\n continue;\n }\n\n if (prop === 'options') {\n animations.push(...this._animateOptions(target, values));\n continue;\n }\n const value = values[prop];\n let animation = running[prop];\n const cfg = animatedProps.get(prop);\n\n if (animation) {\n if (cfg && animation.active()) {\n // There is an existing active animation, let's update that\n animation.update(cfg, value, date);\n continue;\n } else {\n animation.cancel();\n }\n }\n if (!cfg || !cfg.duration) {\n // not animated, set directly to new value\n target[prop] = value;\n continue;\n }\n\n running[prop] = animation = new Animation(cfg, target, prop, value);\n animations.push(animation);\n }\n return animations;\n }\n\n\n /**\n\t * Update `target` properties to new values, using configured animations\n\t * @param {object} target - object to update\n\t * @param {object} values - new target properties\n\t * @returns {boolean|undefined} - `true` if animations were started\n\t **/\n update(target, values) {\n if (this._properties.size === 0) {\n // Nothing is animated, just apply the new values.\n Object.assign(target, values);\n return;\n }\n\n const animations = this._createAnimations(target, values);\n\n if (animations.length) {\n animator.add(this._chart, animations);\n return true;\n }\n }\n}\n\nfunction awaitAll(animations, properties) {\n const running = [];\n const keys = Object.keys(properties);\n for (let i = 0; i < keys.length; i++) {\n const anim = animations[keys[i]];\n if (anim && anim.active()) {\n running.push(anim.wait());\n }\n }\n // @ts-ignore\n return Promise.all(running);\n}\n\nfunction resolveTargetOptions(target, newOptions) {\n if (!newOptions) {\n return;\n }\n let options = target.options;\n if (!options) {\n target.options = newOptions;\n return;\n }\n if (options.$shared) {\n // Going from shared options to distinct one:\n // Create new options object containing the old shared values and start updating that.\n target.options = options = Object.assign({}, options, {$shared: false, $animations: {}});\n }\n return options;\n}\n","import Animations from './core.animations.js';\nimport defaults from './core.defaults.js';\nimport {isArray, isFinite, isObject, valueOrDefault, resolveObjectKey, defined} from '../helpers/helpers.core.js';\nimport {listenArrayEvents, unlistenArrayEvents} from '../helpers/helpers.collection.js';\nimport {createContext, sign} from '../helpers/index.js';\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n * @typedef { import('./core.scale.js').default } Scale\n */\n\nfunction scaleClip(scale, allowedOverflow) {\n const opts = scale && scale.options || {};\n const reverse = opts.reverse;\n const min = opts.min === undefined ? allowedOverflow : 0;\n const max = opts.max === undefined ? allowedOverflow : 0;\n return {\n start: reverse ? max : min,\n end: reverse ? min : max\n };\n}\n\nfunction defaultClip(xScale, yScale, allowedOverflow) {\n if (allowedOverflow === false) {\n return false;\n }\n const x = scaleClip(xScale, allowedOverflow);\n const y = scaleClip(yScale, allowedOverflow);\n\n return {\n top: y.end,\n right: x.end,\n bottom: y.start,\n left: x.start\n };\n}\n\nfunction toClip(value) {\n let t, r, b, l;\n\n if (isObject(value)) {\n t = value.top;\n r = value.right;\n b = value.bottom;\n l = value.left;\n } else {\n t = r = b = l = value;\n }\n\n return {\n top: t,\n right: r,\n bottom: b,\n left: l,\n disabled: value === false\n };\n}\n\nfunction getSortedDatasetIndices(chart, filterVisible) {\n const keys = [];\n const metasets = chart._getSortedDatasetMetas(filterVisible);\n let i, ilen;\n\n for (i = 0, ilen = metasets.length; i < ilen; ++i) {\n keys.push(metasets[i].index);\n }\n return keys;\n}\n\nfunction applyStack(stack, value, dsIndex, options = {}) {\n const keys = stack.keys;\n const singleMode = options.mode === 'single';\n let i, ilen, datasetIndex, otherValue;\n\n if (value === null) {\n return;\n }\n\n let found = false;\n for (i = 0, ilen = keys.length; i < ilen; ++i) {\n datasetIndex = +keys[i];\n if (datasetIndex === dsIndex) {\n found = true;\n if (options.all) {\n continue;\n }\n break;\n }\n otherValue = stack.values[datasetIndex];\n if (isFinite(otherValue) && (singleMode || (value === 0 || sign(value) === sign(otherValue)))) {\n value += otherValue;\n }\n }\n\n if (!found && !options.all) {\n return 0;\n }\n\n return value;\n}\n\nfunction convertObjectDataToArray(data, meta) {\n const {iScale, vScale} = meta;\n const iAxisKey = iScale.axis === 'x' ? 'x' : 'y';\n const vAxisKey = vScale.axis === 'x' ? 'x' : 'y';\n const keys = Object.keys(data);\n const adata = new Array(keys.length);\n let i, ilen, key;\n for (i = 0, ilen = keys.length; i < ilen; ++i) {\n key = keys[i];\n adata[i] = {\n [iAxisKey]: key,\n [vAxisKey]: data[key]\n };\n }\n return adata;\n}\n\nfunction isStacked(scale, meta) {\n const stacked = scale && scale.options.stacked;\n return stacked || (stacked === undefined && meta.stack !== undefined);\n}\n\nfunction getStackKey(indexScale, valueScale, meta) {\n return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`;\n}\n\nfunction getUserBounds(scale) {\n const {min, max, minDefined, maxDefined} = scale.getUserBounds();\n return {\n min: minDefined ? min : Number.NEGATIVE_INFINITY,\n max: maxDefined ? max : Number.POSITIVE_INFINITY\n };\n}\n\nfunction getOrCreateStack(stacks, stackKey, indexValue) {\n const subStack = stacks[stackKey] || (stacks[stackKey] = {});\n return subStack[indexValue] || (subStack[indexValue] = {});\n}\n\nfunction getLastIndexInStack(stack, vScale, positive, type) {\n for (const meta of vScale.getMatchingVisibleMetas(type).reverse()) {\n const value = stack[meta.index];\n if ((positive && value > 0) || (!positive && value < 0)) {\n return meta.index;\n }\n }\n\n return null;\n}\n\nfunction updateStacks(controller, parsed) {\n const {chart, _cachedMeta: meta} = controller;\n const stacks = chart._stacks || (chart._stacks = {}); // map structure is {stackKey: {datasetIndex: value}}\n const {iScale, vScale, index: datasetIndex} = meta;\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const key = getStackKey(iScale, vScale, meta);\n const ilen = parsed.length;\n let stack;\n\n for (let i = 0; i < ilen; ++i) {\n const item = parsed[i];\n const {[iAxis]: index, [vAxis]: value} = item;\n const itemStacks = item._stacks || (item._stacks = {});\n stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index);\n stack[datasetIndex] = value;\n\n stack._top = getLastIndexInStack(stack, vScale, true, meta.type);\n stack._bottom = getLastIndexInStack(stack, vScale, false, meta.type);\n\n const visualValues = stack._visualValues || (stack._visualValues = {});\n visualValues[datasetIndex] = value;\n }\n}\n\nfunction getFirstScaleId(chart, axis) {\n const scales = chart.scales;\n return Object.keys(scales).filter(key => scales[key].axis === axis).shift();\n}\n\nfunction createDatasetContext(parent, index) {\n return createContext(parent,\n {\n active: false,\n dataset: undefined,\n datasetIndex: index,\n index,\n mode: 'default',\n type: 'dataset'\n }\n );\n}\n\nfunction createDataContext(parent, index, element) {\n return createContext(parent, {\n active: false,\n dataIndex: index,\n parsed: undefined,\n raw: undefined,\n element,\n index,\n mode: 'default',\n type: 'data'\n });\n}\n\nfunction clearStacks(meta, items) {\n // Not using meta.index here, because it might be already updated if the dataset changed location\n const datasetIndex = meta.controller.index;\n const axis = meta.vScale && meta.vScale.axis;\n if (!axis) {\n return;\n }\n\n items = items || meta._parsed;\n for (const parsed of items) {\n const stacks = parsed._stacks;\n if (!stacks || stacks[axis] === undefined || stacks[axis][datasetIndex] === undefined) {\n return;\n }\n delete stacks[axis][datasetIndex];\n if (stacks[axis]._visualValues !== undefined && stacks[axis]._visualValues[datasetIndex] !== undefined) {\n delete stacks[axis]._visualValues[datasetIndex];\n }\n }\n}\n\nconst isDirectUpdateMode = (mode) => mode === 'reset' || mode === 'none';\nconst cloneIfNotShared = (cached, shared) => shared ? cached : Object.assign({}, cached);\nconst createStack = (canStack, meta, chart) => canStack && !meta.hidden && meta._stacked\n && {keys: getSortedDatasetIndices(chart, true), values: null};\n\nexport default class DatasetController {\n\n /**\n * @type {any}\n */\n static defaults = {};\n\n /**\n * Element type used to generate a meta dataset (e.g. Chart.element.LineElement).\n */\n static datasetElementType = null;\n\n /**\n * Element type used to generate a meta data (e.g. Chart.element.PointElement).\n */\n static dataElementType = null;\n\n /**\n\t * @param {Chart} chart\n\t * @param {number} datasetIndex\n\t */\n constructor(chart, datasetIndex) {\n this.chart = chart;\n this._ctx = chart.ctx;\n this.index = datasetIndex;\n this._cachedDataOpts = {};\n this._cachedMeta = this.getMeta();\n this._type = this._cachedMeta.type;\n this.options = undefined;\n /** @type {boolean | object} */\n this._parsing = false;\n this._data = undefined;\n this._objectData = undefined;\n this._sharedOptions = undefined;\n this._drawStart = undefined;\n this._drawCount = undefined;\n this.enableOptionSharing = false;\n this.supportsDecimation = false;\n this.$context = undefined;\n this._syncList = [];\n this.datasetElementType = new.target.datasetElementType;\n this.dataElementType = new.target.dataElementType;\n\n this.initialize();\n }\n\n initialize() {\n const meta = this._cachedMeta;\n this.configure();\n this.linkScales();\n meta._stacked = isStacked(meta.vScale, meta);\n this.addElements();\n\n if (this.options.fill && !this.chart.isPluginEnabled('filler')) {\n console.warn(\"Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options\");\n }\n }\n\n updateIndex(datasetIndex) {\n if (this.index !== datasetIndex) {\n clearStacks(this._cachedMeta);\n }\n this.index = datasetIndex;\n }\n\n linkScales() {\n const chart = this.chart;\n const meta = this._cachedMeta;\n const dataset = this.getDataset();\n\n const chooseId = (axis, x, y, r) => axis === 'x' ? x : axis === 'r' ? r : y;\n\n const xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x'));\n const yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y'));\n const rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r'));\n const indexAxis = meta.indexAxis;\n const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid);\n const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid);\n meta.xScale = this.getScaleForId(xid);\n meta.yScale = this.getScaleForId(yid);\n meta.rScale = this.getScaleForId(rid);\n meta.iScale = this.getScaleForId(iid);\n meta.vScale = this.getScaleForId(vid);\n }\n\n getDataset() {\n return this.chart.data.datasets[this.index];\n }\n\n getMeta() {\n return this.chart.getDatasetMeta(this.index);\n }\n\n /**\n\t * @param {string} scaleID\n\t * @return {Scale}\n\t */\n getScaleForId(scaleID) {\n return this.chart.scales[scaleID];\n }\n\n /**\n\t * @private\n\t */\n _getOtherScale(scale) {\n const meta = this._cachedMeta;\n return scale === meta.iScale\n ? meta.vScale\n : meta.iScale;\n }\n\n reset() {\n this._update('reset');\n }\n\n /**\n\t * @private\n\t */\n _destroy() {\n const meta = this._cachedMeta;\n if (this._data) {\n unlistenArrayEvents(this._data, this);\n }\n if (meta._stacked) {\n clearStacks(meta);\n }\n }\n\n /**\n\t * @private\n\t */\n _dataCheck() {\n const dataset = this.getDataset();\n const data = dataset.data || (dataset.data = []);\n const _data = this._data;\n\n // In order to correctly handle data addition/deletion animation (and thus simulate\n // real-time charts), we need to monitor these data modifications and synchronize\n // the internal metadata accordingly.\n\n if (isObject(data)) {\n const meta = this._cachedMeta;\n this._data = convertObjectDataToArray(data, meta);\n } else if (_data !== data) {\n if (_data) {\n // This case happens when the user replaced the data array instance.\n unlistenArrayEvents(_data, this);\n // Discard old parsed data and stacks\n const meta = this._cachedMeta;\n clearStacks(meta);\n meta._parsed = [];\n }\n if (data && Object.isExtensible(data)) {\n listenArrayEvents(data, this);\n }\n this._syncList = [];\n this._data = data;\n }\n }\n\n addElements() {\n const meta = this._cachedMeta;\n\n this._dataCheck();\n\n if (this.datasetElementType) {\n meta.dataset = new this.datasetElementType();\n }\n }\n\n buildOrUpdateElements(resetNewElements) {\n const meta = this._cachedMeta;\n const dataset = this.getDataset();\n let stackChanged = false;\n\n this._dataCheck();\n\n // make sure cached _stacked status is current\n const oldStacked = meta._stacked;\n meta._stacked = isStacked(meta.vScale, meta);\n\n // detect change in stack option\n if (meta.stack !== dataset.stack) {\n stackChanged = true;\n // remove values from old stack\n clearStacks(meta);\n meta.stack = dataset.stack;\n }\n\n // Re-sync meta data in case the user replaced the data array or if we missed\n // any updates and so make sure that we handle number of datapoints changing.\n this._resyncElements(resetNewElements);\n\n // if stack changed, update stack values for the whole dataset\n if (stackChanged || oldStacked !== meta._stacked) {\n updateStacks(this, meta._parsed);\n meta._stacked = isStacked(meta.vScale, meta);\n }\n }\n\n /**\n\t * Merges user-supplied and default dataset-level options\n\t * @private\n\t */\n configure() {\n const config = this.chart.config;\n const scopeKeys = config.datasetScopeKeys(this._type);\n const scopes = config.getOptionScopes(this.getDataset(), scopeKeys, true);\n this.options = config.createResolver(scopes, this.getContext());\n this._parsing = this.options.parsing;\n this._cachedDataOpts = {};\n }\n\n /**\n\t * @param {number} start\n\t * @param {number} count\n\t */\n parse(start, count) {\n const {_cachedMeta: meta, _data: data} = this;\n const {iScale, _stacked} = meta;\n const iAxis = iScale.axis;\n\n let sorted = start === 0 && count === data.length ? true : meta._sorted;\n let prev = start > 0 && meta._parsed[start - 1];\n let i, cur, parsed;\n\n if (this._parsing === false) {\n meta._parsed = data;\n meta._sorted = true;\n parsed = data;\n } else {\n if (isArray(data[start])) {\n parsed = this.parseArrayData(meta, data, start, count);\n } else if (isObject(data[start])) {\n parsed = this.parseObjectData(meta, data, start, count);\n } else {\n parsed = this.parsePrimitiveData(meta, data, start, count);\n }\n\n const isNotInOrderComparedToPrev = () => cur[iAxis] === null || (prev && cur[iAxis] < prev[iAxis]);\n for (i = 0; i < count; ++i) {\n meta._parsed[i + start] = cur = parsed[i];\n if (sorted) {\n if (isNotInOrderComparedToPrev()) {\n sorted = false;\n }\n prev = cur;\n }\n }\n meta._sorted = sorted;\n }\n\n if (_stacked) {\n updateStacks(this, parsed);\n }\n }\n\n /**\n\t * Parse array of primitive values\n\t * @param {object} meta - dataset meta\n\t * @param {array} data - data array. Example [1,3,4]\n\t * @param {number} start - start index\n\t * @param {number} count - number of items to parse\n\t * @returns {object} parsed item - item containing index and a parsed value\n\t * for each scale id.\n\t * Example: {xScale0: 0, yScale0: 1}\n\t * @protected\n\t */\n parsePrimitiveData(meta, data, start, count) {\n const {iScale, vScale} = meta;\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const labels = iScale.getLabels();\n const singleScale = iScale === vScale;\n const parsed = new Array(count);\n let i, ilen, index;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n parsed[i] = {\n [iAxis]: singleScale || iScale.parse(labels[index], index),\n [vAxis]: vScale.parse(data[index], index)\n };\n }\n return parsed;\n }\n\n /**\n\t * Parse array of arrays\n\t * @param {object} meta - dataset meta\n\t * @param {array} data - data array. Example [[1,2],[3,4]]\n\t * @param {number} start - start index\n\t * @param {number} count - number of items to parse\n\t * @returns {object} parsed item - item containing index and a parsed value\n\t * for each scale id.\n\t * Example: {x: 0, y: 1}\n\t * @protected\n\t */\n parseArrayData(meta, data, start, count) {\n const {xScale, yScale} = meta;\n const parsed = new Array(count);\n let i, ilen, index, item;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n item = data[index];\n parsed[i] = {\n x: xScale.parse(item[0], index),\n y: yScale.parse(item[1], index)\n };\n }\n return parsed;\n }\n\n /**\n\t * Parse array of objects\n\t * @param {object} meta - dataset meta\n\t * @param {array} data - data array. Example [{x:1, y:5}, {x:2, y:10}]\n\t * @param {number} start - start index\n\t * @param {number} count - number of items to parse\n\t * @returns {object} parsed item - item containing index and a parsed value\n\t * for each scale id. _custom is optional\n\t * Example: {xScale0: 0, yScale0: 1, _custom: {r: 10, foo: 'bar'}}\n\t * @protected\n\t */\n parseObjectData(meta, data, start, count) {\n const {xScale, yScale} = meta;\n const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;\n const parsed = new Array(count);\n let i, ilen, index, item;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n item = data[index];\n parsed[i] = {\n x: xScale.parse(resolveObjectKey(item, xAxisKey), index),\n y: yScale.parse(resolveObjectKey(item, yAxisKey), index)\n };\n }\n return parsed;\n }\n\n /**\n\t * @protected\n\t */\n getParsed(index) {\n return this._cachedMeta._parsed[index];\n }\n\n /**\n\t * @protected\n\t */\n getDataElement(index) {\n return this._cachedMeta.data[index];\n }\n\n /**\n\t * @protected\n\t */\n applyStack(scale, parsed, mode) {\n const chart = this.chart;\n const meta = this._cachedMeta;\n const value = parsed[scale.axis];\n const stack = {\n keys: getSortedDatasetIndices(chart, true),\n values: parsed._stacks[scale.axis]._visualValues\n };\n return applyStack(stack, value, meta.index, {mode});\n }\n\n /**\n\t * @protected\n\t */\n updateRangeFromParsed(range, scale, parsed, stack) {\n const parsedValue = parsed[scale.axis];\n let value = parsedValue === null ? NaN : parsedValue;\n const values = stack && parsed._stacks[scale.axis];\n if (stack && values) {\n stack.values = values;\n value = applyStack(stack, parsedValue, this._cachedMeta.index);\n }\n range.min = Math.min(range.min, value);\n range.max = Math.max(range.max, value);\n }\n\n /**\n\t * @protected\n\t */\n getMinMax(scale, canStack) {\n const meta = this._cachedMeta;\n const _parsed = meta._parsed;\n const sorted = meta._sorted && scale === meta.iScale;\n const ilen = _parsed.length;\n const otherScale = this._getOtherScale(scale);\n const stack = createStack(canStack, meta, this.chart);\n const range = {min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY};\n const {min: otherMin, max: otherMax} = getUserBounds(otherScale);\n let i, parsed;\n\n function _skip() {\n parsed = _parsed[i];\n const otherValue = parsed[otherScale.axis];\n return !isFinite(parsed[scale.axis]) || otherMin > otherValue || otherMax < otherValue;\n }\n\n for (i = 0; i < ilen; ++i) {\n if (_skip()) {\n continue;\n }\n this.updateRangeFromParsed(range, scale, parsed, stack);\n if (sorted) {\n // if the data is sorted, we don't need to check further from this end of array\n break;\n }\n }\n if (sorted) {\n // in the sorted case, find first non-skipped value from other end of array\n for (i = ilen - 1; i >= 0; --i) {\n if (_skip()) {\n continue;\n }\n this.updateRangeFromParsed(range, scale, parsed, stack);\n break;\n }\n }\n return range;\n }\n\n getAllParsedValues(scale) {\n const parsed = this._cachedMeta._parsed;\n const values = [];\n let i, ilen, value;\n\n for (i = 0, ilen = parsed.length; i < ilen; ++i) {\n value = parsed[i][scale.axis];\n if (isFinite(value)) {\n values.push(value);\n }\n }\n return values;\n }\n\n /**\n\t * @return {number|boolean}\n\t * @protected\n\t */\n getMaxOverflow() {\n return false;\n }\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const iScale = meta.iScale;\n const vScale = meta.vScale;\n const parsed = this.getParsed(index);\n return {\n label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '',\n value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : ''\n };\n }\n\n /**\n\t * @private\n\t */\n _update(mode) {\n const meta = this._cachedMeta;\n this.update(mode || 'default');\n meta._clip = toClip(valueOrDefault(this.options.clip, defaultClip(meta.xScale, meta.yScale, this.getMaxOverflow())));\n }\n\n /**\n\t * @param {string} mode\n\t */\n update(mode) {} // eslint-disable-line no-unused-vars\n\n draw() {\n const ctx = this._ctx;\n const chart = this.chart;\n const meta = this._cachedMeta;\n const elements = meta.data || [];\n const area = chart.chartArea;\n const active = [];\n const start = this._drawStart || 0;\n const count = this._drawCount || (elements.length - start);\n const drawActiveElementsOnTop = this.options.drawActiveElementsOnTop;\n let i;\n\n if (meta.dataset) {\n meta.dataset.draw(ctx, area, start, count);\n }\n\n for (i = start; i < start + count; ++i) {\n const element = elements[i];\n if (element.hidden) {\n continue;\n }\n if (element.active && drawActiveElementsOnTop) {\n active.push(element);\n } else {\n element.draw(ctx, area);\n }\n }\n\n for (i = 0; i < active.length; ++i) {\n active[i].draw(ctx, area);\n }\n }\n\n /**\n\t * Returns a set of predefined style properties that should be used to represent the dataset\n\t * or the data if the index is specified\n\t * @param {number} index - data index\n\t * @param {boolean} [active] - true if hover\n\t * @return {object} style object\n\t */\n getStyle(index, active) {\n const mode = active ? 'active' : 'default';\n return index === undefined && this._cachedMeta.dataset\n ? this.resolveDatasetElementOptions(mode)\n : this.resolveDataElementOptions(index || 0, mode);\n }\n\n /**\n\t * @protected\n\t */\n getContext(index, active, mode) {\n const dataset = this.getDataset();\n let context;\n if (index >= 0 && index < this._cachedMeta.data.length) {\n const element = this._cachedMeta.data[index];\n context = element.$context ||\n (element.$context = createDataContext(this.getContext(), index, element));\n context.parsed = this.getParsed(index);\n context.raw = dataset.data[index];\n context.index = context.dataIndex = index;\n } else {\n context = this.$context ||\n (this.$context = createDatasetContext(this.chart.getContext(), this.index));\n context.dataset = dataset;\n context.index = context.datasetIndex = this.index;\n }\n\n context.active = !!active;\n context.mode = mode;\n return context;\n }\n\n /**\n\t * @param {string} [mode]\n\t * @protected\n\t */\n resolveDatasetElementOptions(mode) {\n return this._resolveElementOptions(this.datasetElementType.id, mode);\n }\n\n /**\n\t * @param {number} index\n\t * @param {string} [mode]\n\t * @protected\n\t */\n resolveDataElementOptions(index, mode) {\n return this._resolveElementOptions(this.dataElementType.id, mode, index);\n }\n\n /**\n\t * @private\n\t */\n _resolveElementOptions(elementType, mode = 'default', index) {\n const active = mode === 'active';\n const cache = this._cachedDataOpts;\n const cacheKey = elementType + '-' + mode;\n const cached = cache[cacheKey];\n const sharing = this.enableOptionSharing && defined(index);\n if (cached) {\n return cloneIfNotShared(cached, sharing);\n }\n const config = this.chart.config;\n const scopeKeys = config.datasetElementScopeKeys(this._type, elementType);\n const prefixes = active ? [`${elementType}Hover`, 'hover', elementType, ''] : [elementType, ''];\n const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);\n const names = Object.keys(defaults.elements[elementType]);\n // context is provided as a function, and is called only if needed,\n // so we don't create a context for each element if not needed.\n const context = () => this.getContext(index, active, mode);\n const values = config.resolveNamedOptions(scopes, names, context, prefixes);\n\n if (values.$shared) {\n // `$shared` indicates this set of options can be shared between multiple elements.\n // Sharing is used to reduce number of properties to change during animation.\n values.$shared = sharing;\n\n // We cache options by `mode`, which can be 'active' for example. This enables us\n // to have the 'active' element options and 'default' options to switch between\n // when interacting.\n cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing));\n }\n\n return values;\n }\n\n\n /**\n\t * @private\n\t */\n _resolveAnimations(index, transition, active) {\n const chart = this.chart;\n const cache = this._cachedDataOpts;\n const cacheKey = `animation-${transition}`;\n const cached = cache[cacheKey];\n if (cached) {\n return cached;\n }\n let options;\n if (chart.options.animation !== false) {\n const config = this.chart.config;\n const scopeKeys = config.datasetAnimationScopeKeys(this._type, transition);\n const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);\n options = config.createResolver(scopes, this.getContext(index, active, transition));\n }\n const animations = new Animations(chart, options && options.animations);\n if (options && options._cacheable) {\n cache[cacheKey] = Object.freeze(animations);\n }\n return animations;\n }\n\n /**\n\t * Utility for getting the options object shared between elements\n\t * @protected\n\t */\n getSharedOptions(options) {\n if (!options.$shared) {\n return;\n }\n return this._sharedOptions || (this._sharedOptions = Object.assign({}, options));\n }\n\n /**\n\t * Utility for determining if `options` should be included in the updated properties\n\t * @protected\n\t */\n includeOptions(mode, sharedOptions) {\n return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled;\n }\n\n /**\n * @todo v4, rename to getSharedOptions and remove excess functions\n */\n _getSharedOptions(start, mode) {\n const firstOpts = this.resolveDataElementOptions(start, mode);\n const previouslySharedOptions = this._sharedOptions;\n const sharedOptions = this.getSharedOptions(firstOpts);\n const includeOptions = this.includeOptions(mode, sharedOptions) || (sharedOptions !== previouslySharedOptions);\n this.updateSharedOptions(sharedOptions, mode, firstOpts);\n return {sharedOptions, includeOptions};\n }\n\n /**\n\t * Utility for updating an element with new properties, using animations when appropriate.\n\t * @protected\n\t */\n updateElement(element, index, properties, mode) {\n if (isDirectUpdateMode(mode)) {\n Object.assign(element, properties);\n } else {\n this._resolveAnimations(index, mode).update(element, properties);\n }\n }\n\n /**\n\t * Utility to animate the shared options, that are potentially affecting multiple elements.\n\t * @protected\n\t */\n updateSharedOptions(sharedOptions, mode, newOptions) {\n if (sharedOptions && !isDirectUpdateMode(mode)) {\n this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions);\n }\n }\n\n /**\n\t * @private\n\t */\n _setStyle(element, index, mode, active) {\n element.active = active;\n const options = this.getStyle(index, active);\n this._resolveAnimations(index, mode, active).update(element, {\n // When going from active to inactive, we need to update to the shared options.\n // This way the once hovered element will end up with the same original shared options instance, after animation.\n options: (!active && this.getSharedOptions(options)) || options\n });\n }\n\n removeHoverStyle(element, datasetIndex, index) {\n this._setStyle(element, index, 'active', false);\n }\n\n setHoverStyle(element, datasetIndex, index) {\n this._setStyle(element, index, 'active', true);\n }\n\n /**\n\t * @private\n\t */\n _removeDatasetHoverStyle() {\n const element = this._cachedMeta.dataset;\n\n if (element) {\n this._setStyle(element, undefined, 'active', false);\n }\n }\n\n /**\n\t * @private\n\t */\n _setDatasetHoverStyle() {\n const element = this._cachedMeta.dataset;\n\n if (element) {\n this._setStyle(element, undefined, 'active', true);\n }\n }\n\n /**\n\t * @private\n\t */\n _resyncElements(resetNewElements) {\n const data = this._data;\n const elements = this._cachedMeta.data;\n\n // Apply changes detected through array listeners\n for (const [method, arg1, arg2] of this._syncList) {\n this[method](arg1, arg2);\n }\n this._syncList = [];\n\n const numMeta = elements.length;\n const numData = data.length;\n const count = Math.min(numData, numMeta);\n\n if (count) {\n // TODO: It is not optimal to always parse the old data\n // This is done because we are not detecting direct assignments:\n // chart.data.datasets[0].data[5] = 10;\n // chart.data.datasets[0].data[5].y = 10;\n this.parse(0, count);\n }\n\n if (numData > numMeta) {\n this._insertElements(numMeta, numData - numMeta, resetNewElements);\n } else if (numData < numMeta) {\n this._removeElements(numData, numMeta - numData);\n }\n }\n\n /**\n\t * @private\n\t */\n _insertElements(start, count, resetNewElements = true) {\n const meta = this._cachedMeta;\n const data = meta.data;\n const end = start + count;\n let i;\n\n const move = (arr) => {\n arr.length += count;\n for (i = arr.length - 1; i >= end; i--) {\n arr[i] = arr[i - count];\n }\n };\n move(data);\n\n for (i = start; i < end; ++i) {\n data[i] = new this.dataElementType();\n }\n\n if (this._parsing) {\n move(meta._parsed);\n }\n this.parse(start, count);\n\n if (resetNewElements) {\n this.updateElements(data, start, count, 'reset');\n }\n }\n\n updateElements(element, start, count, mode) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * @private\n\t */\n _removeElements(start, count) {\n const meta = this._cachedMeta;\n if (this._parsing) {\n const removed = meta._parsed.splice(start, count);\n if (meta._stacked) {\n clearStacks(meta, removed);\n }\n }\n meta.data.splice(start, count);\n }\n\n /**\n\t * @private\n */\n _sync(args) {\n if (this._parsing) {\n this._syncList.push(args);\n } else {\n const [method, arg1, arg2] = args;\n this[method](arg1, arg2);\n }\n this.chart._dataChanges.push([this.index, ...args]);\n }\n\n _onDataPush() {\n const count = arguments.length;\n this._sync(['_insertElements', this.getDataset().data.length - count, count]);\n }\n\n _onDataPop() {\n this._sync(['_removeElements', this._cachedMeta.data.length - 1, 1]);\n }\n\n _onDataShift() {\n this._sync(['_removeElements', 0, 1]);\n }\n\n _onDataSplice(start, count) {\n if (count) {\n this._sync(['_removeElements', start, count]);\n }\n const newCount = arguments.length - 2;\n if (newCount) {\n this._sync(['_insertElements', start, newCount]);\n }\n }\n\n _onDataUnshift() {\n this._sync(['_insertElements', 0, arguments.length]);\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {\n _arrayUnique, isArray, isNullOrUndef,\n valueOrDefault, resolveObjectKey, sign, defined\n} from '../helpers/index.js';\n\nfunction getAllScaleValues(scale, type) {\n if (!scale._cache.$bar) {\n const visibleMetas = scale.getMatchingVisibleMetas(type);\n let values = [];\n\n for (let i = 0, ilen = visibleMetas.length; i < ilen; i++) {\n values = values.concat(visibleMetas[i].controller.getAllParsedValues(scale));\n }\n scale._cache.$bar = _arrayUnique(values.sort((a, b) => a - b));\n }\n return scale._cache.$bar;\n}\n\n/**\n * Computes the \"optimal\" sample size to maintain bars equally sized while preventing overlap.\n * @private\n */\nfunction computeMinSampleSize(meta) {\n const scale = meta.iScale;\n const values = getAllScaleValues(scale, meta.type);\n let min = scale._length;\n let i, ilen, curr, prev;\n const updateMinAndPrev = () => {\n if (curr === 32767 || curr === -32768) {\n // Ignore truncated pixels\n return;\n }\n if (defined(prev)) {\n // curr - prev === 0 is ignored\n min = Math.min(min, Math.abs(curr - prev) || min);\n }\n prev = curr;\n };\n\n for (i = 0, ilen = values.length; i < ilen; ++i) {\n curr = scale.getPixelForValue(values[i]);\n updateMinAndPrev();\n }\n\n prev = undefined;\n for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) {\n curr = scale.getPixelForTick(i);\n updateMinAndPrev();\n }\n\n return min;\n}\n\n/**\n * Computes an \"ideal\" category based on the absolute bar thickness or, if undefined or null,\n * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This\n * mode currently always generates bars equally sized (until we introduce scriptable options?).\n * @private\n */\nfunction computeFitCategoryTraits(index, ruler, options, stackCount) {\n const thickness = options.barThickness;\n let size, ratio;\n\n if (isNullOrUndef(thickness)) {\n size = ruler.min * options.categoryPercentage;\n ratio = options.barPercentage;\n } else {\n // When bar thickness is enforced, category and bar percentages are ignored.\n // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')\n // and deprecate barPercentage since this value is ignored when thickness is absolute.\n size = thickness * stackCount;\n ratio = 1;\n }\n\n return {\n chunk: size / stackCount,\n ratio,\n start: ruler.pixels[index] - (size / 2)\n };\n}\n\n/**\n * Computes an \"optimal\" category that globally arranges bars side by side (no gap when\n * percentage options are 1), based on the previous and following categories. This mode\n * generates bars with different widths when data are not evenly spaced.\n * @private\n */\nfunction computeFlexCategoryTraits(index, ruler, options, stackCount) {\n const pixels = ruler.pixels;\n const curr = pixels[index];\n let prev = index > 0 ? pixels[index - 1] : null;\n let next = index < pixels.length - 1 ? pixels[index + 1] : null;\n const percent = options.categoryPercentage;\n\n if (prev === null) {\n // first data: its size is double based on the next point or,\n // if it's also the last data, we use the scale size.\n prev = curr - (next === null ? ruler.end - ruler.start : next - curr);\n }\n\n if (next === null) {\n // last data: its size is also double based on the previous point.\n next = curr + curr - prev;\n }\n\n const start = curr - (curr - Math.min(prev, next)) / 2 * percent;\n const size = Math.abs(next - prev) / 2 * percent;\n\n return {\n chunk: size / stackCount,\n ratio: options.barPercentage,\n start\n };\n}\n\nfunction parseFloatBar(entry, item, vScale, i) {\n const startValue = vScale.parse(entry[0], i);\n const endValue = vScale.parse(entry[1], i);\n const min = Math.min(startValue, endValue);\n const max = Math.max(startValue, endValue);\n let barStart = min;\n let barEnd = max;\n\n if (Math.abs(min) > Math.abs(max)) {\n barStart = max;\n barEnd = min;\n }\n\n // Store `barEnd` (furthest away from origin) as parsed value,\n // to make stacking straight forward\n item[vScale.axis] = barEnd;\n\n item._custom = {\n barStart,\n barEnd,\n start: startValue,\n end: endValue,\n min,\n max\n };\n}\n\nfunction parseValue(entry, item, vScale, i) {\n if (isArray(entry)) {\n parseFloatBar(entry, item, vScale, i);\n } else {\n item[vScale.axis] = vScale.parse(entry, i);\n }\n return item;\n}\n\nfunction parseArrayOrPrimitive(meta, data, start, count) {\n const iScale = meta.iScale;\n const vScale = meta.vScale;\n const labels = iScale.getLabels();\n const singleScale = iScale === vScale;\n const parsed = [];\n let i, ilen, item, entry;\n\n for (i = start, ilen = start + count; i < ilen; ++i) {\n entry = data[i];\n item = {};\n item[iScale.axis] = singleScale || iScale.parse(labels[i], i);\n parsed.push(parseValue(entry, item, vScale, i));\n }\n return parsed;\n}\n\nfunction isFloatBar(custom) {\n return custom && custom.barStart !== undefined && custom.barEnd !== undefined;\n}\n\nfunction barSign(size, vScale, actualBase) {\n if (size !== 0) {\n return sign(size);\n }\n return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1);\n}\n\nfunction borderProps(properties) {\n let reverse, start, end, top, bottom;\n if (properties.horizontal) {\n reverse = properties.base > properties.x;\n start = 'left';\n end = 'right';\n } else {\n reverse = properties.base < properties.y;\n start = 'bottom';\n end = 'top';\n }\n if (reverse) {\n top = 'end';\n bottom = 'start';\n } else {\n top = 'start';\n bottom = 'end';\n }\n return {start, end, reverse, top, bottom};\n}\n\nfunction setBorderSkipped(properties, options, stack, index) {\n let edge = options.borderSkipped;\n const res = {};\n\n if (!edge) {\n properties.borderSkipped = res;\n return;\n }\n\n if (edge === true) {\n properties.borderSkipped = {top: true, right: true, bottom: true, left: true};\n return;\n }\n\n const {start, end, reverse, top, bottom} = borderProps(properties);\n\n if (edge === 'middle' && stack) {\n properties.enableBorderRadius = true;\n if ((stack._top || 0) === index) {\n edge = top;\n } else if ((stack._bottom || 0) === index) {\n edge = bottom;\n } else {\n res[parseEdge(bottom, start, end, reverse)] = true;\n edge = top;\n }\n }\n\n res[parseEdge(edge, start, end, reverse)] = true;\n properties.borderSkipped = res;\n}\n\nfunction parseEdge(edge, a, b, reverse) {\n if (reverse) {\n edge = swap(edge, a, b);\n edge = startEnd(edge, b, a);\n } else {\n edge = startEnd(edge, a, b);\n }\n return edge;\n}\n\nfunction swap(orig, v1, v2) {\n return orig === v1 ? v2 : orig === v2 ? v1 : orig;\n}\n\nfunction startEnd(v, start, end) {\n return v === 'start' ? start : v === 'end' ? end : v;\n}\n\nfunction setInflateAmount(properties, {inflateAmount}, ratio) {\n properties.inflateAmount = inflateAmount === 'auto'\n ? ratio === 1 ? 0.33 : 0\n : inflateAmount;\n}\n\nexport default class BarController extends DatasetController {\n\n static id = 'bar';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'bar',\n\n categoryPercentage: 0.8,\n barPercentage: 0.9,\n grouped: true,\n\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'base', 'width', 'height']\n }\n }\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n scales: {\n _index_: {\n type: 'category',\n offset: true,\n grid: {\n offset: true\n }\n },\n _value_: {\n type: 'linear',\n beginAtZero: true,\n }\n }\n };\n\n\n /**\n\t * Overriding primitive data parsing since we support mixed primitive/array\n\t * data for float bars\n\t * @protected\n\t */\n parsePrimitiveData(meta, data, start, count) {\n return parseArrayOrPrimitive(meta, data, start, count);\n }\n\n /**\n\t * Overriding array data parsing since we support mixed primitive/array\n\t * data for float bars\n\t * @protected\n\t */\n parseArrayData(meta, data, start, count) {\n return parseArrayOrPrimitive(meta, data, start, count);\n }\n\n /**\n\t * Overriding object data parsing since we support mixed primitive/array\n\t * value-scale data for float bars\n\t * @protected\n\t */\n parseObjectData(meta, data, start, count) {\n const {iScale, vScale} = meta;\n const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;\n const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey;\n const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey;\n const parsed = [];\n let i, ilen, item, obj;\n for (i = start, ilen = start + count; i < ilen; ++i) {\n obj = data[i];\n item = {};\n item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i);\n parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i));\n }\n return parsed;\n }\n\n /**\n\t * @protected\n\t */\n updateRangeFromParsed(range, scale, parsed, stack) {\n super.updateRangeFromParsed(range, scale, parsed, stack);\n const custom = parsed._custom;\n if (custom && scale === this._cachedMeta.vScale) {\n // float bar: only one end of the bar is considered by `super`\n range.min = Math.min(range.min, custom.min);\n range.max = Math.max(range.max, custom.max);\n }\n }\n\n /**\n\t * @return {number|boolean}\n\t * @protected\n\t */\n getMaxOverflow() {\n return 0;\n }\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const {iScale, vScale} = meta;\n const parsed = this.getParsed(index);\n const custom = parsed._custom;\n const value = isFloatBar(custom)\n ? '[' + custom.start + ', ' + custom.end + ']'\n : '' + vScale.getLabelForValue(parsed[vScale.axis]);\n\n return {\n label: '' + iScale.getLabelForValue(parsed[iScale.axis]),\n value\n };\n }\n\n initialize() {\n this.enableOptionSharing = true;\n\n super.initialize();\n\n const meta = this._cachedMeta;\n meta.stack = this.getDataset().stack;\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n this.updateElements(meta.data, 0, meta.data.length, mode);\n }\n\n updateElements(bars, start, count, mode) {\n const reset = mode === 'reset';\n const {index, _cachedMeta: {vScale}} = this;\n const base = vScale.getBasePixel();\n const horizontal = vScale.isHorizontal();\n const ruler = this._getRuler();\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n\n for (let i = start; i < start + count; i++) {\n const parsed = this.getParsed(i);\n const vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? {base, head: base} : this._calculateBarValuePixels(i);\n const ipixels = this._calculateBarIndexPixels(i, ruler);\n const stack = (parsed._stacks || {})[vScale.axis];\n\n const properties = {\n horizontal,\n base: vpixels.base,\n enableBorderRadius: !stack || isFloatBar(parsed._custom) || (index === stack._top || index === stack._bottom),\n x: horizontal ? vpixels.head : ipixels.center,\n y: horizontal ? ipixels.center : vpixels.head,\n height: horizontal ? ipixels.size : Math.abs(vpixels.size),\n width: horizontal ? Math.abs(vpixels.size) : ipixels.size\n };\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, bars[i].active ? 'active' : mode);\n }\n const options = properties.options || bars[i].options;\n setBorderSkipped(properties, options, stack, index);\n setInflateAmount(properties, options, ruler.ratio);\n this.updateElement(bars[i], i, properties, mode);\n }\n }\n\n /**\n\t * Returns the stacks based on groups and bar visibility.\n\t * @param {number} [last] - The dataset index\n\t * @param {number} [dataIndex] - The data index of the ruler\n\t * @returns {string[]} The list of stack IDs\n\t * @private\n\t */\n _getStacks(last, dataIndex) {\n const {iScale} = this._cachedMeta;\n const metasets = iScale.getMatchingVisibleMetas(this._type)\n .filter(meta => meta.controller.options.grouped);\n const stacked = iScale.options.stacked;\n const stacks = [];\n const currentParsed = this._cachedMeta.controller.getParsed(dataIndex);\n const iScaleValue = currentParsed && currentParsed[iScale.axis];\n\n const skipNull = (meta) => {\n const parsed = meta._parsed.find(item => item[iScale.axis] === iScaleValue);\n const val = parsed && parsed[meta.vScale.axis];\n\n if (isNullOrUndef(val) || isNaN(val)) {\n return true;\n }\n };\n\n for (const meta of metasets) {\n if (dataIndex !== undefined && skipNull(meta)) {\n continue;\n }\n\n // stacked | meta.stack\n // | found | not found | undefined\n // false | x | x | x\n // true | | x |\n // undefined | | x | x\n if (stacked === false || stacks.indexOf(meta.stack) === -1 ||\n\t\t\t\t(stacked === undefined && meta.stack === undefined)) {\n stacks.push(meta.stack);\n }\n if (meta.index === last) {\n break;\n }\n }\n\n // No stacks? that means there is no visible data. Let's still initialize an `undefined`\n // stack where possible invisible bars will be located.\n // https://github.com/chartjs/Chart.js/issues/6368\n if (!stacks.length) {\n stacks.push(undefined);\n }\n\n return stacks;\n }\n\n /**\n\t * Returns the effective number of stacks based on groups and bar visibility.\n\t * @private\n\t */\n _getStackCount(index) {\n return this._getStacks(undefined, index).length;\n }\n\n _getAxisCount() {\n return this._getAxis().length;\n }\n\n getFirstScaleIdForIndexAxis() {\n const scales = this.chart.scales;\n const indexScaleId = this.chart.options.indexAxis;\n return Object.keys(scales).filter(key => scales[key].axis === indexScaleId).shift();\n }\n\n _getAxis() {\n const axis = {};\n const firstScaleAxisId = this.getFirstScaleIdForIndexAxis();\n for (const dataset of this.chart.data.datasets) {\n axis[valueOrDefault(\n this.chart.options.indexAxis === 'x' ? dataset.xAxisID : dataset.yAxisID, firstScaleAxisId\n )] = true;\n }\n return Object.keys(axis);\n }\n\n /**\n\t * Returns the stack index for the given dataset based on groups and bar visibility.\n\t * @param {number} [datasetIndex] - The dataset index\n\t * @param {string} [name] - The stack name to find\n * @param {number} [dataIndex]\n\t * @returns {number} The stack index\n\t * @private\n\t */\n _getStackIndex(datasetIndex, name, dataIndex) {\n const stacks = this._getStacks(datasetIndex, dataIndex);\n const index = (name !== undefined)\n ? stacks.indexOf(name)\n : -1; // indexOf returns -1 if element is not present\n\n return (index === -1)\n ? stacks.length - 1\n : index;\n }\n\n /**\n\t * @private\n\t */\n _getRuler() {\n const opts = this.options;\n const meta = this._cachedMeta;\n const iScale = meta.iScale;\n const pixels = [];\n let i, ilen;\n\n for (i = 0, ilen = meta.data.length; i < ilen; ++i) {\n pixels.push(iScale.getPixelForValue(this.getParsed(i)[iScale.axis], i));\n }\n\n const barThickness = opts.barThickness;\n const min = barThickness || computeMinSampleSize(meta);\n\n return {\n min,\n pixels,\n start: iScale._startPixel,\n end: iScale._endPixel,\n stackCount: this._getStackCount(),\n scale: iScale,\n grouped: opts.grouped,\n // bar thickness ratio used for non-grouped bars\n ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage\n };\n }\n\n /**\n\t * Note: pixel values are not clamped to the scale area.\n\t * @private\n\t */\n _calculateBarValuePixels(index) {\n const {_cachedMeta: {vScale, _stacked, index: datasetIndex}, options: {base: baseValue, minBarLength}} = this;\n const actualBase = baseValue || 0;\n const parsed = this.getParsed(index);\n const custom = parsed._custom;\n const floating = isFloatBar(custom);\n let value = parsed[vScale.axis];\n let start = 0;\n let length = _stacked ? this.applyStack(vScale, parsed, _stacked) : value;\n let head, size;\n\n if (length !== value) {\n start = length - value;\n length = value;\n }\n\n if (floating) {\n value = custom.barStart;\n length = custom.barEnd - custom.barStart;\n // bars crossing origin are not stacked\n if (value !== 0 && sign(value) !== sign(custom.barEnd)) {\n start = 0;\n }\n start += value;\n }\n\n const startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start;\n let base = vScale.getPixelForValue(startValue);\n\n if (this.chart.getDataVisibility(index)) {\n head = vScale.getPixelForValue(start + length);\n } else {\n // When not visible, no height\n head = base;\n }\n\n size = head - base;\n\n if (Math.abs(size) < minBarLength) {\n size = barSign(size, vScale, actualBase) * minBarLength;\n if (value === actualBase) {\n base -= size / 2;\n }\n const startPixel = vScale.getPixelForDecimal(0);\n const endPixel = vScale.getPixelForDecimal(1);\n const min = Math.min(startPixel, endPixel);\n const max = Math.max(startPixel, endPixel);\n base = Math.max(Math.min(base, max), min);\n head = base + size;\n\n if (_stacked && !floating) {\n // visual data coordinates after applying minBarLength\n parsed._stacks[vScale.axis]._visualValues[datasetIndex] = vScale.getValueForPixel(head) - vScale.getValueForPixel(base);\n }\n }\n\n if (base === vScale.getPixelForValue(actualBase)) {\n const halfGrid = sign(size) * vScale.getLineWidthForValue(actualBase) / 2;\n base += halfGrid;\n size -= halfGrid;\n }\n\n return {\n size,\n base,\n head,\n center: head + size / 2\n };\n }\n\n /**\n\t * @private\n\t */\n _calculateBarIndexPixels(index, ruler) {\n const scale = ruler.scale;\n const options = this.options;\n const skipNull = options.skipNull;\n const maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity);\n let center, size;\n const axisCount = this._getAxisCount();\n if (ruler.grouped) {\n const stackCount = skipNull ? this._getStackCount(index) : ruler.stackCount;\n const range = options.barThickness === 'flex'\n ? computeFlexCategoryTraits(index, ruler, options, stackCount * axisCount)\n : computeFitCategoryTraits(index, ruler, options, stackCount * axisCount);\n const axisID = this.chart.options.indexAxis === 'x' ? this.getDataset().xAxisID : this.getDataset().yAxisID;\n const axisNumber = this._getAxis().indexOf(valueOrDefault(axisID, this.getFirstScaleIdForIndexAxis()));\n const stackIndex = this._getStackIndex(this.index, this._cachedMeta.stack, skipNull ? index : undefined) + axisNumber;\n center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);\n size = Math.min(maxBarThickness, range.chunk * range.ratio);\n } else {\n // For non-grouped bar charts, exact pixel values are used\n center = scale.getPixelForValue(this.getParsed(index)[scale.axis], index);\n size = Math.min(maxBarThickness, ruler.min * ruler.ratio);\n }\n\n\n return {\n base: center - size / 2,\n head: center + size / 2,\n center,\n size\n };\n }\n\n draw() {\n const meta = this._cachedMeta;\n const vScale = meta.vScale;\n const rects = meta.data;\n const ilen = rects.length;\n let i = 0;\n\n for (; i < ilen; ++i) {\n if (this.getParsed(i)[vScale.axis] !== null && !rects[i].hidden) {\n rects[i].draw(this._ctx);\n }\n }\n }\n\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {valueOrDefault} from '../helpers/helpers.core.js';\n\nexport default class BubbleController extends DatasetController {\n\n static id = 'bubble';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'point',\n\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'borderWidth', 'radius']\n }\n }\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n scales: {\n x: {\n type: 'linear'\n },\n y: {\n type: 'linear'\n }\n }\n };\n\n initialize() {\n this.enableOptionSharing = true;\n super.initialize();\n }\n\n /**\n\t * Parse array of primitive values\n\t * @protected\n\t */\n parsePrimitiveData(meta, data, start, count) {\n const parsed = super.parsePrimitiveData(meta, data, start, count);\n for (let i = 0; i < parsed.length; i++) {\n parsed[i]._custom = this.resolveDataElementOptions(i + start).radius;\n }\n return parsed;\n }\n\n /**\n\t * Parse array of arrays\n\t * @protected\n\t */\n parseArrayData(meta, data, start, count) {\n const parsed = super.parseArrayData(meta, data, start, count);\n for (let i = 0; i < parsed.length; i++) {\n const item = data[start + i];\n parsed[i]._custom = valueOrDefault(item[2], this.resolveDataElementOptions(i + start).radius);\n }\n return parsed;\n }\n\n /**\n\t * Parse array of objects\n\t * @protected\n\t */\n parseObjectData(meta, data, start, count) {\n const parsed = super.parseObjectData(meta, data, start, count);\n for (let i = 0; i < parsed.length; i++) {\n const item = data[start + i];\n parsed[i]._custom = valueOrDefault(item && item.r && +item.r, this.resolveDataElementOptions(i + start).radius);\n }\n return parsed;\n }\n\n /**\n\t * @protected\n\t */\n getMaxOverflow() {\n const data = this._cachedMeta.data;\n\n let max = 0;\n for (let i = data.length - 1; i >= 0; --i) {\n max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);\n }\n return max > 0 && max;\n }\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const labels = this.chart.data.labels || [];\n const {xScale, yScale} = meta;\n const parsed = this.getParsed(index);\n const x = xScale.getLabelForValue(parsed.x);\n const y = yScale.getLabelForValue(parsed.y);\n const r = parsed._custom;\n\n return {\n label: labels[index] || '',\n value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')'\n };\n }\n\n update(mode) {\n const points = this._cachedMeta.data;\n\n // Update Points\n this.updateElements(points, 0, points.length, mode);\n }\n\n updateElements(points, start, count, mode) {\n const reset = mode === 'reset';\n const {iScale, vScale} = this._cachedMeta;\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n\n for (let i = start; i < start + count; i++) {\n const point = points[i];\n const parsed = !reset && this.getParsed(i);\n const properties = {};\n const iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]);\n const vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]);\n\n properties.skip = isNaN(iPixel) || isNaN(vPixel);\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n\n if (reset) {\n properties.options.radius = 0;\n }\n }\n\n this.updateElement(point, i, properties, mode);\n }\n }\n\n /**\n\t * @param {number} index\n\t * @param {string} [mode]\n\t * @protected\n\t */\n resolveDataElementOptions(index, mode) {\n const parsed = this.getParsed(index);\n let values = super.resolveDataElementOptions(index, mode);\n\n // In case values were cached (and thus frozen), we need to clone the values\n if (values.$shared) {\n values = Object.assign({}, values, {$shared: false});\n }\n\n // Custom radius resolution\n const radius = values.radius;\n if (mode !== 'active') {\n values.radius = 0;\n }\n values.radius += valueOrDefault(parsed && parsed._custom, radius);\n\n return values;\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {isObject, resolveObjectKey, toPercentage, toDimension, valueOrDefault} from '../helpers/helpers.core.js';\nimport {formatNumber} from '../helpers/helpers.intl.js';\nimport {toRadians, PI, TAU, HALF_PI, _angleBetween} from '../helpers/helpers.math.js';\n\n/**\n * @typedef { import('../core/core.controller.js').default } Chart\n */\n\nfunction getRatioAndOffset(rotation, circumference, cutout) {\n let ratioX = 1;\n let ratioY = 1;\n let offsetX = 0;\n let offsetY = 0;\n // If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc\n if (circumference < TAU) {\n const startAngle = rotation;\n const endAngle = startAngle + circumference;\n const startX = Math.cos(startAngle);\n const startY = Math.sin(startAngle);\n const endX = Math.cos(endAngle);\n const endY = Math.sin(endAngle);\n const calcMax = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout);\n const calcMin = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout);\n const maxX = calcMax(0, startX, endX);\n const maxY = calcMax(HALF_PI, startY, endY);\n const minX = calcMin(PI, startX, endX);\n const minY = calcMin(PI + HALF_PI, startY, endY);\n ratioX = (maxX - minX) / 2;\n ratioY = (maxY - minY) / 2;\n offsetX = -(maxX + minX) / 2;\n offsetY = -(maxY + minY) / 2;\n }\n return {ratioX, ratioY, offsetX, offsetY};\n}\n\nexport default class DoughnutController extends DatasetController {\n\n static id = 'doughnut';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'arc',\n animation: {\n // Boolean - Whether we animate the rotation of the Doughnut\n animateRotate: true,\n // Boolean - Whether we animate scaling the Doughnut from the centre\n animateScale: false\n },\n animations: {\n numbers: {\n type: 'number',\n properties: ['circumference', 'endAngle', 'innerRadius', 'outerRadius', 'startAngle', 'x', 'y', 'offset', 'borderWidth', 'spacing']\n },\n },\n // The percentage of the chart that we cut out of the middle.\n cutout: '50%',\n\n // The rotation of the chart, where the first data arc begins.\n rotation: 0,\n\n // The total circumference of the chart.\n circumference: 360,\n\n // The outer radius of the chart\n radius: '100%',\n\n // Spacing between arcs\n spacing: 0,\n\n indexAxis: 'r',\n };\n\n static descriptors = {\n _scriptable: (name) => name !== 'spacing',\n _indexable: (name) => name !== 'spacing' && !name.startsWith('borderDash') && !name.startsWith('hoverBorderDash'),\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n aspectRatio: 1,\n\n // Need to override these to give a nice default\n plugins: {\n legend: {\n labels: {\n generateLabels(chart) {\n const data = chart.data;\n if (data.labels.length && data.datasets.length) {\n const {labels: {pointStyle, color}} = chart.legend.options;\n\n return data.labels.map((label, i) => {\n const meta = chart.getDatasetMeta(0);\n const style = meta.controller.getStyle(i);\n\n return {\n text: label,\n fillStyle: style.backgroundColor,\n strokeStyle: style.borderColor,\n fontColor: color,\n lineWidth: style.borderWidth,\n pointStyle: pointStyle,\n hidden: !chart.getDataVisibility(i),\n\n // Extra data used for toggling the correct item\n index: i\n };\n });\n }\n return [];\n }\n },\n\n onClick(e, legendItem, legend) {\n legend.chart.toggleDataVisibility(legendItem.index);\n legend.chart.update();\n }\n }\n }\n };\n\n constructor(chart, datasetIndex) {\n super(chart, datasetIndex);\n\n this.enableOptionSharing = true;\n this.innerRadius = undefined;\n this.outerRadius = undefined;\n this.offsetX = undefined;\n this.offsetY = undefined;\n }\n\n linkScales() {}\n\n /**\n\t * Override data parsing, since we are not using scales\n\t */\n parse(start, count) {\n const data = this.getDataset().data;\n const meta = this._cachedMeta;\n\n if (this._parsing === false) {\n meta._parsed = data;\n } else {\n let getter = (i) => +data[i];\n\n if (isObject(data[start])) {\n const {key = 'value'} = this._parsing;\n getter = (i) => +resolveObjectKey(data[i], key);\n }\n\n let i, ilen;\n for (i = start, ilen = start + count; i < ilen; ++i) {\n meta._parsed[i] = getter(i);\n }\n }\n }\n\n /**\n\t * @private\n\t */\n _getRotation() {\n return toRadians(this.options.rotation - 90);\n }\n\n /**\n\t * @private\n\t */\n _getCircumference() {\n return toRadians(this.options.circumference);\n }\n\n /**\n\t * Get the maximal rotation & circumference extents\n\t * across all visible datasets.\n\t */\n _getRotationExtents() {\n let min = TAU;\n let max = -TAU;\n\n for (let i = 0; i < this.chart.data.datasets.length; ++i) {\n if (this.chart.isDatasetVisible(i) && this.chart.getDatasetMeta(i).type === this._type) {\n const controller = this.chart.getDatasetMeta(i).controller;\n const rotation = controller._getRotation();\n const circumference = controller._getCircumference();\n\n min = Math.min(min, rotation);\n max = Math.max(max, rotation + circumference);\n }\n }\n\n return {\n rotation: min,\n circumference: max - min,\n };\n }\n\n /**\n\t * @param {string} mode\n\t */\n update(mode) {\n const chart = this.chart;\n const {chartArea} = chart;\n const meta = this._cachedMeta;\n const arcs = meta.data;\n const spacing = this.getMaxBorderWidth() + this.getMaxOffset(arcs) + this.options.spacing;\n const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0);\n const cutout = Math.min(toPercentage(this.options.cutout, maxSize), 1);\n const chartWeight = this._getRingWeight(this.index);\n\n // Compute the maximal rotation & circumference limits.\n // If we only consider our dataset, this can cause problems when two datasets\n // are both less than a circle with different rotations (starting angles)\n const {circumference, rotation} = this._getRotationExtents();\n const {ratioX, ratioY, offsetX, offsetY} = getRatioAndOffset(rotation, circumference, cutout);\n const maxWidth = (chartArea.width - spacing) / ratioX;\n const maxHeight = (chartArea.height - spacing) / ratioY;\n const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);\n const outerRadius = toDimension(this.options.radius, maxRadius);\n const innerRadius = Math.max(outerRadius * cutout, 0);\n const radiusLength = (outerRadius - innerRadius) / this._getVisibleDatasetWeightTotal();\n this.offsetX = offsetX * outerRadius;\n this.offsetY = offsetY * outerRadius;\n\n meta.total = this.calculateTotal();\n\n this.outerRadius = outerRadius - radiusLength * this._getRingWeightOffset(this.index);\n this.innerRadius = Math.max(this.outerRadius - radiusLength * chartWeight, 0);\n\n this.updateElements(arcs, 0, arcs.length, mode);\n }\n\n /**\n * @private\n */\n _circumference(i, reset) {\n const opts = this.options;\n const meta = this._cachedMeta;\n const circumference = this._getCircumference();\n if ((reset && opts.animation.animateRotate) || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) {\n return 0;\n }\n return this.calculateCircumference(meta._parsed[i] * circumference / TAU);\n }\n\n updateElements(arcs, start, count, mode) {\n const reset = mode === 'reset';\n const chart = this.chart;\n const chartArea = chart.chartArea;\n const opts = chart.options;\n const animationOpts = opts.animation;\n const centerX = (chartArea.left + chartArea.right) / 2;\n const centerY = (chartArea.top + chartArea.bottom) / 2;\n const animateScale = reset && animationOpts.animateScale;\n const innerRadius = animateScale ? 0 : this.innerRadius;\n const outerRadius = animateScale ? 0 : this.outerRadius;\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n let startAngle = this._getRotation();\n let i;\n\n for (i = 0; i < start; ++i) {\n startAngle += this._circumference(i, reset);\n }\n\n for (i = start; i < start + count; ++i) {\n const circumference = this._circumference(i, reset);\n const arc = arcs[i];\n const properties = {\n x: centerX + this.offsetX,\n y: centerY + this.offsetY,\n startAngle,\n endAngle: startAngle + circumference,\n circumference,\n outerRadius,\n innerRadius\n };\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, arc.active ? 'active' : mode);\n }\n startAngle += circumference;\n\n this.updateElement(arc, i, properties, mode);\n }\n }\n\n calculateTotal() {\n const meta = this._cachedMeta;\n const metaData = meta.data;\n let total = 0;\n let i;\n\n for (i = 0; i < metaData.length; i++) {\n const value = meta._parsed[i];\n if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) {\n total += Math.abs(value);\n }\n }\n\n return total;\n }\n\n calculateCircumference(value) {\n const total = this._cachedMeta.total;\n if (total > 0 && !isNaN(value)) {\n return TAU * (Math.abs(value) / total);\n }\n return 0;\n }\n\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const chart = this.chart;\n const labels = chart.data.labels || [];\n const value = formatNumber(meta._parsed[index], chart.options.locale);\n\n return {\n label: labels[index] || '',\n value,\n };\n }\n\n getMaxBorderWidth(arcs) {\n let max = 0;\n const chart = this.chart;\n let i, ilen, meta, controller, options;\n\n if (!arcs) {\n // Find the outmost visible dataset\n for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {\n if (chart.isDatasetVisible(i)) {\n meta = chart.getDatasetMeta(i);\n arcs = meta.data;\n controller = meta.controller;\n break;\n }\n }\n }\n\n if (!arcs) {\n return 0;\n }\n\n for (i = 0, ilen = arcs.length; i < ilen; ++i) {\n options = controller.resolveDataElementOptions(i);\n if (options.borderAlign !== 'inner') {\n max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0);\n }\n }\n return max;\n }\n\n getMaxOffset(arcs) {\n let max = 0;\n\n for (let i = 0, ilen = arcs.length; i < ilen; ++i) {\n const options = this.resolveDataElementOptions(i);\n max = Math.max(max, options.offset || 0, options.hoverOffset || 0);\n }\n return max;\n }\n\n /**\n\t * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly\n\t * @private\n\t */\n _getRingWeightOffset(datasetIndex) {\n let ringWeightOffset = 0;\n\n for (let i = 0; i < datasetIndex; ++i) {\n if (this.chart.isDatasetVisible(i)) {\n ringWeightOffset += this._getRingWeight(i);\n }\n }\n\n return ringWeightOffset;\n }\n\n /**\n\t * @private\n\t */\n _getRingWeight(datasetIndex) {\n return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0);\n }\n\n /**\n\t * Returns the sum of all visible data set weights.\n\t * @private\n\t */\n _getVisibleDatasetWeightTotal() {\n return this._getRingWeightOffset(this.chart.data.datasets.length) || 1;\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {isNullOrUndef} from '../helpers/index.js';\nimport {isNumber} from '../helpers/helpers.math.js';\nimport {_getStartAndCountOfVisiblePoints, _scaleRangesChanged} from '../helpers/helpers.extras.js';\n\nexport default class LineController extends DatasetController {\n\n static id = 'line';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: 'line',\n dataElementType: 'point',\n\n showLine: true,\n spanGaps: false,\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n scales: {\n _index_: {\n type: 'category',\n },\n _value_: {\n type: 'linear',\n },\n }\n };\n\n initialize() {\n this.enableOptionSharing = true;\n this.supportsDecimation = true;\n super.initialize();\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n const {dataset: line, data: points = [], _dataset} = meta;\n // @ts-ignore\n const animationsDisabled = this.chart._animationsDisabled;\n let {start, count} = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);\n\n this._drawStart = start;\n this._drawCount = count;\n\n if (_scaleRangesChanged(meta)) {\n start = 0;\n count = points.length;\n }\n\n // Update Line\n line._chart = this.chart;\n line._datasetIndex = this.index;\n line._decimated = !!_dataset._decimated;\n line.points = points;\n\n const options = this.resolveDatasetElementOptions(mode);\n if (!this.options.showLine) {\n options.borderWidth = 0;\n }\n options.segment = this.options.segment;\n this.updateElement(line, undefined, {\n animated: !animationsDisabled,\n options\n }, mode);\n\n // Update Points\n this.updateElements(points, start, count, mode);\n }\n\n updateElements(points, start, count, mode) {\n const reset = mode === 'reset';\n const {iScale, vScale, _stacked, _dataset} = this._cachedMeta;\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const {spanGaps, segment} = this.options;\n const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;\n const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';\n const end = start + count;\n const pointsCount = points.length;\n let prevParsed = start > 0 && this.getParsed(start - 1);\n\n for (let i = 0; i < pointsCount; ++i) {\n const point = points[i];\n const properties = directUpdate ? point : {};\n\n if (i < start || i >= end) {\n properties.skip = true;\n continue;\n }\n\n const parsed = this.getParsed(i);\n const nullData = isNullOrUndef(parsed[vAxis]);\n const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);\n const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);\n\n properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;\n properties.stop = i > 0 && (Math.abs(parsed[iAxis] - prevParsed[iAxis])) > maxGapLength;\n if (segment) {\n properties.parsed = parsed;\n properties.raw = _dataset.data[i];\n }\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n }\n\n if (!directUpdate) {\n this.updateElement(point, i, properties, mode);\n }\n\n prevParsed = parsed;\n }\n }\n\n /**\n\t * @protected\n\t */\n getMaxOverflow() {\n const meta = this._cachedMeta;\n const dataset = meta.dataset;\n const border = dataset.options && dataset.options.borderWidth || 0;\n const data = meta.data || [];\n if (!data.length) {\n return border;\n }\n const firstPoint = data[0].size(this.resolveDataElementOptions(0));\n const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));\n return Math.max(border, firstPoint, lastPoint) / 2;\n }\n\n draw() {\n const meta = this._cachedMeta;\n meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis);\n super.draw();\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {toRadians, PI, formatNumber, _parseObjectDataRadialScale} from '../helpers/index.js';\n\nexport default class PolarAreaController extends DatasetController {\n\n static id = 'polarArea';\n\n /**\n * @type {any}\n */\n static defaults = {\n dataElementType: 'arc',\n animation: {\n animateRotate: true,\n animateScale: true\n },\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'startAngle', 'endAngle', 'innerRadius', 'outerRadius']\n },\n },\n indexAxis: 'r',\n startAngle: 0,\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n aspectRatio: 1,\n\n plugins: {\n legend: {\n labels: {\n generateLabels(chart) {\n const data = chart.data;\n if (data.labels.length && data.datasets.length) {\n const {labels: {pointStyle, color}} = chart.legend.options;\n\n return data.labels.map((label, i) => {\n const meta = chart.getDatasetMeta(0);\n const style = meta.controller.getStyle(i);\n\n return {\n text: label,\n fillStyle: style.backgroundColor,\n strokeStyle: style.borderColor,\n fontColor: color,\n lineWidth: style.borderWidth,\n pointStyle: pointStyle,\n hidden: !chart.getDataVisibility(i),\n\n // Extra data used for toggling the correct item\n index: i\n };\n });\n }\n return [];\n }\n },\n\n onClick(e, legendItem, legend) {\n legend.chart.toggleDataVisibility(legendItem.index);\n legend.chart.update();\n }\n }\n },\n\n scales: {\n r: {\n type: 'radialLinear',\n angleLines: {\n display: false\n },\n beginAtZero: true,\n grid: {\n circular: true\n },\n pointLabels: {\n display: false\n },\n startAngle: 0\n }\n }\n };\n\n constructor(chart, datasetIndex) {\n super(chart, datasetIndex);\n\n this.innerRadius = undefined;\n this.outerRadius = undefined;\n }\n\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const chart = this.chart;\n const labels = chart.data.labels || [];\n const value = formatNumber(meta._parsed[index].r, chart.options.locale);\n\n return {\n label: labels[index] || '',\n value,\n };\n }\n\n parseObjectData(meta, data, start, count) {\n return _parseObjectDataRadialScale.bind(this)(meta, data, start, count);\n }\n\n update(mode) {\n const arcs = this._cachedMeta.data;\n\n this._updateRadius();\n this.updateElements(arcs, 0, arcs.length, mode);\n }\n\n /**\n * @protected\n */\n getMinMax() {\n const meta = this._cachedMeta;\n const range = {min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY};\n\n meta.data.forEach((element, index) => {\n const parsed = this.getParsed(index).r;\n\n if (!isNaN(parsed) && this.chart.getDataVisibility(index)) {\n if (parsed < range.min) {\n range.min = parsed;\n }\n\n if (parsed > range.max) {\n range.max = parsed;\n }\n }\n });\n\n return range;\n }\n\n /**\n\t * @private\n\t */\n _updateRadius() {\n const chart = this.chart;\n const chartArea = chart.chartArea;\n const opts = chart.options;\n const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);\n\n const outerRadius = Math.max(minSize / 2, 0);\n const innerRadius = Math.max(opts.cutoutPercentage ? (outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);\n const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount();\n\n this.outerRadius = outerRadius - (radiusLength * this.index);\n this.innerRadius = this.outerRadius - radiusLength;\n }\n\n updateElements(arcs, start, count, mode) {\n const reset = mode === 'reset';\n const chart = this.chart;\n const opts = chart.options;\n const animationOpts = opts.animation;\n const scale = this._cachedMeta.rScale;\n const centerX = scale.xCenter;\n const centerY = scale.yCenter;\n const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI;\n let angle = datasetStartAngle;\n let i;\n\n const defaultAngle = 360 / this.countVisibleElements();\n\n for (i = 0; i < start; ++i) {\n angle += this._computeAngle(i, mode, defaultAngle);\n }\n for (i = start; i < start + count; i++) {\n const arc = arcs[i];\n let startAngle = angle;\n let endAngle = angle + this._computeAngle(i, mode, defaultAngle);\n let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(this.getParsed(i).r) : 0;\n angle = endAngle;\n\n if (reset) {\n if (animationOpts.animateScale) {\n outerRadius = 0;\n }\n if (animationOpts.animateRotate) {\n startAngle = endAngle = datasetStartAngle;\n }\n }\n\n const properties = {\n x: centerX,\n y: centerY,\n innerRadius: 0,\n outerRadius,\n startAngle,\n endAngle,\n options: this.resolveDataElementOptions(i, arc.active ? 'active' : mode)\n };\n\n this.updateElement(arc, i, properties, mode);\n }\n }\n\n countVisibleElements() {\n const meta = this._cachedMeta;\n let count = 0;\n\n meta.data.forEach((element, index) => {\n if (!isNaN(this.getParsed(index).r) && this.chart.getDataVisibility(index)) {\n count++;\n }\n });\n\n return count;\n }\n\n /**\n\t * @private\n\t */\n _computeAngle(index, mode, defaultAngle) {\n return this.chart.getDataVisibility(index)\n ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle)\n : 0;\n }\n}\n","import DoughnutController from './controller.doughnut.js';\n\n// Pie charts are Doughnut chart with different defaults\nexport default class PieController extends DoughnutController {\n\n static id = 'pie';\n\n /**\n * @type {any}\n */\n static defaults = {\n // The percentage of the chart that we cut out of the middle.\n cutout: 0,\n\n // The rotation of the chart, where the first data arc begins.\n rotation: 0,\n\n // The total circumference of the chart.\n circumference: 360,\n\n // The outer radius of the chart\n radius: '100%'\n };\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {_parseObjectDataRadialScale} from '../helpers/index.js';\n\nexport default class RadarController extends DatasetController {\n\n static id = 'radar';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: 'line',\n dataElementType: 'point',\n indexAxis: 'r',\n showLine: true,\n elements: {\n line: {\n fill: 'start'\n }\n },\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n aspectRatio: 1,\n\n scales: {\n r: {\n type: 'radialLinear',\n }\n }\n };\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const vScale = this._cachedMeta.vScale;\n const parsed = this.getParsed(index);\n\n return {\n label: vScale.getLabels()[index],\n value: '' + vScale.getLabelForValue(parsed[vScale.axis])\n };\n }\n\n parseObjectData(meta, data, start, count) {\n return _parseObjectDataRadialScale.bind(this)(meta, data, start, count);\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n const line = meta.dataset;\n const points = meta.data || [];\n const labels = meta.iScale.getLabels();\n\n // Update Line\n line.points = points;\n // In resize mode only point locations change, so no need to set the points or options.\n if (mode !== 'resize') {\n const options = this.resolveDatasetElementOptions(mode);\n if (!this.options.showLine) {\n options.borderWidth = 0;\n }\n\n const properties = {\n _loop: true,\n _fullLoop: labels.length === points.length,\n options\n };\n\n this.updateElement(line, undefined, properties, mode);\n }\n\n // Update Points\n this.updateElements(points, 0, points.length, mode);\n }\n\n updateElements(points, start, count, mode) {\n const scale = this._cachedMeta.rScale;\n const reset = mode === 'reset';\n\n for (let i = start; i < start + count; i++) {\n const point = points[i];\n const options = this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n const pointPosition = scale.getPointPositionForValue(i, this.getParsed(i).r);\n\n const x = reset ? scale.xCenter : pointPosition.x;\n const y = reset ? scale.yCenter : pointPosition.y;\n\n const properties = {\n x,\n y,\n angle: pointPosition.angle,\n skip: isNaN(x) || isNaN(y),\n options\n };\n\n this.updateElement(point, i, properties, mode);\n }\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {isNullOrUndef} from '../helpers/index.js';\nimport {isNumber} from '../helpers/helpers.math.js';\nimport {_getStartAndCountOfVisiblePoints, _scaleRangesChanged} from '../helpers/helpers.extras.js';\n\nexport default class ScatterController extends DatasetController {\n\n static id = 'scatter';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'point',\n showLine: false,\n fill: false\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n\n interaction: {\n mode: 'point'\n },\n\n scales: {\n x: {\n type: 'linear'\n },\n y: {\n type: 'linear'\n }\n }\n };\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const labels = this.chart.data.labels || [];\n const {xScale, yScale} = meta;\n const parsed = this.getParsed(index);\n const x = xScale.getLabelForValue(parsed.x);\n const y = yScale.getLabelForValue(parsed.y);\n\n return {\n label: labels[index] || '',\n value: '(' + x + ', ' + y + ')'\n };\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n const {data: points = []} = meta;\n // @ts-ignore\n const animationsDisabled = this.chart._animationsDisabled;\n let {start, count} = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);\n\n this._drawStart = start;\n this._drawCount = count;\n\n if (_scaleRangesChanged(meta)) {\n start = 0;\n count = points.length;\n }\n\n if (this.options.showLine) {\n\n // https://github.com/chartjs/Chart.js/issues/11333\n if (!this.datasetElementType) {\n this.addElements();\n }\n const {dataset: line, _dataset} = meta;\n\n // Update Line\n line._chart = this.chart;\n line._datasetIndex = this.index;\n line._decimated = !!_dataset._decimated;\n line.points = points;\n\n const options = this.resolveDatasetElementOptions(mode);\n options.segment = this.options.segment;\n this.updateElement(line, undefined, {\n animated: !animationsDisabled,\n options\n }, mode);\n } else if (this.datasetElementType) {\n // https://github.com/chartjs/Chart.js/issues/11333\n delete meta.dataset;\n this.datasetElementType = false;\n }\n\n // Update Points\n this.updateElements(points, start, count, mode);\n }\n\n addElements() {\n const {showLine} = this.options;\n\n if (!this.datasetElementType && showLine) {\n this.datasetElementType = this.chart.registry.getElement('line');\n }\n\n super.addElements();\n }\n\n updateElements(points, start, count, mode) {\n const reset = mode === 'reset';\n const {iScale, vScale, _stacked, _dataset} = this._cachedMeta;\n const firstOpts = this.resolveDataElementOptions(start, mode);\n const sharedOptions = this.getSharedOptions(firstOpts);\n const includeOptions = this.includeOptions(mode, sharedOptions);\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const {spanGaps, segment} = this.options;\n const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;\n const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';\n let prevParsed = start > 0 && this.getParsed(start - 1);\n\n for (let i = start; i < start + count; ++i) {\n const point = points[i];\n const parsed = this.getParsed(i);\n const properties = directUpdate ? point : {};\n const nullData = isNullOrUndef(parsed[vAxis]);\n const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);\n const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);\n\n properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;\n properties.stop = i > 0 && (Math.abs(parsed[iAxis] - prevParsed[iAxis])) > maxGapLength;\n if (segment) {\n properties.parsed = parsed;\n properties.raw = _dataset.data[i];\n }\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n }\n\n if (!directUpdate) {\n this.updateElement(point, i, properties, mode);\n }\n\n prevParsed = parsed;\n }\n\n this.updateSharedOptions(sharedOptions, mode, firstOpts);\n }\n\n /**\n\t * @protected\n\t */\n getMaxOverflow() {\n const meta = this._cachedMeta;\n const data = meta.data || [];\n\n if (!this.options.showLine) {\n let max = 0;\n for (let i = data.length - 1; i >= 0; --i) {\n max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);\n }\n return max > 0 && max;\n }\n\n const dataset = meta.dataset;\n const border = dataset.options && dataset.options.borderWidth || 0;\n\n if (!data.length) {\n return border;\n }\n\n const firstPoint = data[0].size(this.resolveDataElementOptions(0));\n const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));\n return Math.max(border, firstPoint, lastPoint) / 2;\n }\n}\n","/**\n * @namespace Chart._adapters\n * @since 2.8.0\n * @private\n */\n\nimport type {AnyObject} from '../types/basic.js';\nimport type {ChartOptions} from '../types/index.js';\n\nexport type TimeUnit = 'millisecond' | 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year';\n\nexport interface DateAdapter {\n readonly options: T;\n /**\n * Will called with chart options after adapter creation.\n */\n init(this: DateAdapter, chartOptions: ChartOptions): void;\n /**\n * Returns a map of time formats for the supported formatting units defined\n * in Unit as well as 'datetime' representing a detailed date/time string.\n */\n formats(this: DateAdapter): Record;\n /**\n * Parses the given `value` and return the associated timestamp.\n * @param value - the value to parse (usually comes from the data)\n * @param [format] - the expected data format\n */\n parse(this: DateAdapter, value: unknown, format?: string): number | null;\n /**\n * Returns the formatted date in the specified `format` for a given `timestamp`.\n * @param timestamp - the timestamp to format\n * @param format - the date/time token\n */\n format(this: DateAdapter, timestamp: number, format: string): string;\n /**\n * Adds the specified `amount` of `unit` to the given `timestamp`.\n * @param timestamp - the input timestamp\n * @param amount - the amount to add\n * @param unit - the unit as string\n */\n add(this: DateAdapter, timestamp: number, amount: number, unit: TimeUnit): number;\n /**\n * Returns the number of `unit` between the given timestamps.\n * @param a - the input timestamp (reference)\n * @param b - the timestamp to subtract\n * @param unit - the unit as string\n */\n diff(this: DateAdapter, a: number, b: number, unit: TimeUnit): number;\n /**\n * Returns start of `unit` for the given `timestamp`.\n * @param timestamp - the input timestamp\n * @param unit - the unit as string\n * @param [weekday] - the ISO day of the week with 1 being Monday\n * and 7 being Sunday (only needed if param *unit* is `isoWeek`).\n */\n startOf(this: DateAdapter, timestamp: number, unit: TimeUnit | 'isoWeek', weekday?: number | boolean): number;\n /**\n * Returns end of `unit` for the given `timestamp`.\n * @param timestamp - the input timestamp\n * @param unit - the unit as string\n */\n endOf(this: DateAdapter, timestamp: number, unit: TimeUnit): number;\n}\n\nfunction abstract(): T {\n throw new Error('This method is not implemented: Check that a complete date adapter is provided.');\n}\n\n/**\n * Date adapter (current used by the time scale)\n * @namespace Chart._adapters._date\n * @memberof Chart._adapters\n * @private\n */\nclass DateAdapterBase implements DateAdapter {\n\n /**\n * Override default date adapter methods.\n * Accepts type parameter to define options type.\n * @example\n * Chart._adapters._date.override<{myAdapterOption: string}>({\n * init() {\n * console.log(this.options.myAdapterOption);\n * }\n * })\n */\n static override(\n members: Partial, 'options'>>\n ) {\n Object.assign(DateAdapterBase.prototype, members);\n }\n\n readonly options: AnyObject;\n\n constructor(options?: AnyObject) {\n this.options = options || {};\n }\n\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n init() {}\n\n formats(): Record {\n return abstract();\n }\n\n parse(): number | null {\n return abstract();\n }\n\n format(): string {\n return abstract();\n }\n\n add(): number {\n return abstract();\n }\n\n diff(): number {\n return abstract();\n }\n\n startOf(): number {\n return abstract();\n }\n\n endOf(): number {\n return abstract();\n }\n}\n\nexport default {\n _date: DateAdapterBase as {\n new (options?: AnyObject): DateAdapter;\n override(\n members: Partial, 'options'>>\n ): void;\n }\n};\n","import {_lookupByKey, _rlookupByKey} from '../helpers/helpers.collection.js';\nimport {getRelativePosition} from '../helpers/helpers.dom.js';\nimport {_angleBetween, getAngleFromPoint} from '../helpers/helpers.math.js';\nimport {_isPointInArea, isNullOrUndef} from '../helpers/index.js';\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n * @typedef { import('../types/index.js').ChartEvent } ChartEvent\n * @typedef {{axis?: string, intersect?: boolean, includeInvisible?: boolean}} InteractionOptions\n * @typedef {{datasetIndex: number, index: number, element: import('./core.element.js').default}} InteractionItem\n * @typedef { import('../types/index.js').Point } Point\n */\n\n/**\n * Helper function to do binary search when possible\n * @param {object} metaset - the dataset meta\n * @param {string} axis - the axis mode. x|y|xy|r\n * @param {number} value - the value to find\n * @param {boolean} [intersect] - should the element intersect\n * @returns {{lo:number, hi:number}} indices to search data array between\n */\nfunction binarySearch(metaset, axis, value, intersect) {\n const {controller, data, _sorted} = metaset;\n const iScale = controller._cachedMeta.iScale;\n const spanGaps = metaset.dataset ? metaset.dataset.options ? metaset.dataset.options.spanGaps : null : null;\n\n if (iScale && axis === iScale.axis && axis !== 'r' && _sorted && data.length) {\n const lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey;\n if (!intersect) {\n const result = lookupMethod(data, axis, value);\n if (spanGaps) {\n const {vScale} = controller._cachedMeta;\n const {_parsed} = metaset;\n\n const distanceToDefinedLo = (_parsed\n .slice(0, result.lo + 1)\n .reverse()\n .findIndex(\n point => !isNullOrUndef(point[vScale.axis])));\n result.lo -= Math.max(0, distanceToDefinedLo);\n\n const distanceToDefinedHi = (_parsed\n .slice(result.hi)\n .findIndex(\n point => !isNullOrUndef(point[vScale.axis])));\n result.hi += Math.max(0, distanceToDefinedHi);\n }\n return result;\n } else if (controller._sharedOptions) {\n // _sharedOptions indicates that each element has equal options -> equal proportions\n // So we can do a ranged binary search based on the range of first element and\n // be confident to get the full range of indices that can intersect with the value.\n const el = data[0];\n const range = typeof el.getRange === 'function' && el.getRange(axis);\n if (range) {\n const start = lookupMethod(data, axis, value - range);\n const end = lookupMethod(data, axis, value + range);\n return {lo: start.lo, hi: end.hi};\n }\n }\n }\n // Default to all elements, when binary search can not be used.\n return {lo: 0, hi: data.length - 1};\n}\n\n/**\n * Helper function to select candidate elements for interaction\n * @param {Chart} chart - the chart\n * @param {string} axis - the axis mode. x|y|xy|r\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {function} handler - the callback to execute for each visible item\n * @param {boolean} [intersect] - consider intersecting items\n */\nfunction evaluateInteractionItems(chart, axis, position, handler, intersect) {\n const metasets = chart.getSortedVisibleDatasetMetas();\n const value = position[axis];\n for (let i = 0, ilen = metasets.length; i < ilen; ++i) {\n const {index, data} = metasets[i];\n const {lo, hi} = binarySearch(metasets[i], axis, value, intersect);\n for (let j = lo; j <= hi; ++j) {\n const element = data[j];\n if (!element.skip) {\n handler(element, index, j);\n }\n }\n }\n}\n\n/**\n * Get a distance metric function for two points based on the\n * axis mode setting\n * @param {string} axis - the axis mode. x|y|xy|r\n */\nfunction getDistanceMetricForAxis(axis) {\n const useX = axis.indexOf('x') !== -1;\n const useY = axis.indexOf('y') !== -1;\n\n return function(pt1, pt2) {\n const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;\n const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;\n return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));\n };\n}\n\n/**\n * Helper function to get the items that intersect the event position\n * @param {Chart} chart - the chart\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axis mode. x|y|xy|r\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @param {boolean} [includeInvisible] - include invisible points that are outside of the chart area\n * @return {InteractionItem[]} the nearest items\n */\nfunction getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) {\n const items = [];\n\n if (!includeInvisible && !chart.isPointInArea(position)) {\n return items;\n }\n\n const evaluationFunc = function(element, datasetIndex, index) {\n if (!includeInvisible && !_isPointInArea(element, chart.chartArea, 0)) {\n return;\n }\n if (element.inRange(position.x, position.y, useFinalPosition)) {\n items.push({element, datasetIndex, index});\n }\n };\n\n evaluateInteractionItems(chart, axis, position, evaluationFunc, true);\n return items;\n}\n\n/**\n * Helper function to get the items nearest to the event position for a radial chart\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axes along which to measure distance\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @return {InteractionItem[]} the nearest items\n */\nfunction getNearestRadialItems(chart, position, axis, useFinalPosition) {\n let items = [];\n\n function evaluationFunc(element, datasetIndex, index) {\n const {startAngle, endAngle} = element.getProps(['startAngle', 'endAngle'], useFinalPosition);\n const {angle} = getAngleFromPoint(element, {x: position.x, y: position.y});\n\n if (_angleBetween(angle, startAngle, endAngle)) {\n items.push({element, datasetIndex, index});\n }\n }\n\n evaluateInteractionItems(chart, axis, position, evaluationFunc);\n return items;\n}\n\n/**\n * Helper function to get the items nearest to the event position for a cartesian chart\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axes along which to measure distance\n * @param {boolean} [intersect] - if true, only consider items that intersect the position\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @param {boolean} [includeInvisible] - include invisible points that are outside of the chart area\n * @return {InteractionItem[]} the nearest items\n */\nfunction getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {\n let items = [];\n const distanceMetric = getDistanceMetricForAxis(axis);\n let minDistance = Number.POSITIVE_INFINITY;\n\n function evaluationFunc(element, datasetIndex, index) {\n const inRange = element.inRange(position.x, position.y, useFinalPosition);\n if (intersect && !inRange) {\n return;\n }\n\n const center = element.getCenterPoint(useFinalPosition);\n const pointInArea = !!includeInvisible || chart.isPointInArea(center);\n if (!pointInArea && !inRange) {\n return;\n }\n\n const distance = distanceMetric(position, center);\n if (distance < minDistance) {\n items = [{element, datasetIndex, index}];\n minDistance = distance;\n } else if (distance === minDistance) {\n // Can have multiple items at the same distance in which case we sort by size\n items.push({element, datasetIndex, index});\n }\n }\n\n evaluateInteractionItems(chart, axis, position, evaluationFunc);\n return items;\n}\n\n/**\n * Helper function to get the items nearest to the event position considering all visible items in the chart\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axes along which to measure distance\n * @param {boolean} [intersect] - if true, only consider items that intersect the position\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @param {boolean} [includeInvisible] - include invisible points that are outside of the chart area\n * @return {InteractionItem[]} the nearest items\n */\nfunction getNearestItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {\n if (!includeInvisible && !chart.isPointInArea(position)) {\n return [];\n }\n\n return axis === 'r' && !intersect\n ? getNearestRadialItems(chart, position, axis, useFinalPosition)\n : getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible);\n}\n\n/**\n * Helper function to get the items matching along the given X or Y axis\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axis to match\n * @param {boolean} [intersect] - if true, only consider items that intersect the position\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @return {InteractionItem[]} the nearest items\n */\nfunction getAxisItems(chart, position, axis, intersect, useFinalPosition) {\n const items = [];\n const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange';\n let intersectsItem = false;\n\n evaluateInteractionItems(chart, axis, position, (element, datasetIndex, index) => {\n if (element[rangeMethod] && element[rangeMethod](position[axis], useFinalPosition)) {\n items.push({element, datasetIndex, index});\n intersectsItem = intersectsItem || element.inRange(position.x, position.y, useFinalPosition);\n }\n });\n\n // If we want to trigger on an intersect and we don't have any items\n // that intersect the position, return nothing\n if (intersect && !intersectsItem) {\n return [];\n }\n return items;\n}\n\n/**\n * Contains interaction related functions\n * @namespace Chart.Interaction\n */\nexport default {\n // Part of the public API to facilitate developers creating their own modes\n evaluateInteractionItems,\n\n // Helper function for different modes\n modes: {\n /**\n\t\t * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something\n\t\t * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item\n\t\t * @function Chart.Interaction.modes.index\n\t\t * @since v2.4.0\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n index(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n // Default axis for index mode is 'x' to match old behaviour\n const axis = options.axis || 'x';\n const includeInvisible = options.includeInvisible || false;\n const items = options.intersect\n ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible)\n : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);\n const elements = [];\n\n if (!items.length) {\n return [];\n }\n\n chart.getSortedVisibleDatasetMetas().forEach((meta) => {\n const index = items[0].index;\n const element = meta.data[index];\n\n // don't count items that are skipped (null data)\n if (element && !element.skip) {\n elements.push({element, datasetIndex: meta.index, index});\n }\n });\n\n return elements;\n },\n\n /**\n\t\t * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something\n\t\t * If the options.intersect is false, we find the nearest item and return the items in that dataset\n\t\t * @function Chart.Interaction.modes.dataset\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n dataset(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'xy';\n const includeInvisible = options.includeInvisible || false;\n let items = options.intersect\n ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) :\n getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);\n\n if (items.length > 0) {\n const datasetIndex = items[0].datasetIndex;\n const data = chart.getDatasetMeta(datasetIndex).data;\n items = [];\n for (let i = 0; i < data.length; ++i) {\n items.push({element: data[i], datasetIndex, index: i});\n }\n }\n\n return items;\n },\n\n /**\n\t\t * Point mode returns all elements that hit test based on the event position\n\t\t * of the event\n\t\t * @function Chart.Interaction.modes.intersect\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n point(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'xy';\n const includeInvisible = options.includeInvisible || false;\n return getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible);\n },\n\n /**\n\t\t * nearest mode returns the element closest to the point\n\t\t * @function Chart.Interaction.modes.intersect\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n nearest(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'xy';\n const includeInvisible = options.includeInvisible || false;\n return getNearestItems(chart, position, axis, options.intersect, useFinalPosition, includeInvisible);\n },\n\n /**\n\t\t * x mode returns the elements that hit-test at the current x coordinate\n\t\t * @function Chart.Interaction.modes.x\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n x(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n return getAxisItems(chart, position, 'x', options.intersect, useFinalPosition);\n },\n\n /**\n\t\t * y mode returns the elements that hit-test at the current y coordinate\n\t\t * @function Chart.Interaction.modes.y\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n y(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n return getAxisItems(chart, position, 'y', options.intersect, useFinalPosition);\n }\n }\n};\n","import {defined, each, isObject} from '../helpers/helpers.core.js';\nimport {toPadding} from '../helpers/helpers.options.js';\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n */\n\nconst STATIC_POSITIONS = ['left', 'top', 'right', 'bottom'];\n\nfunction filterByPosition(array, position) {\n return array.filter(v => v.pos === position);\n}\n\nfunction filterDynamicPositionByAxis(array, axis) {\n return array.filter(v => STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis);\n}\n\nfunction sortByWeight(array, reverse) {\n return array.sort((a, b) => {\n const v0 = reverse ? b : a;\n const v1 = reverse ? a : b;\n return v0.weight === v1.weight ?\n v0.index - v1.index :\n v0.weight - v1.weight;\n });\n}\n\nfunction wrapBoxes(boxes) {\n const layoutBoxes = [];\n let i, ilen, box, pos, stack, stackWeight;\n\n for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {\n box = boxes[i];\n ({position: pos, options: {stack, stackWeight = 1}} = box);\n layoutBoxes.push({\n index: i,\n box,\n pos,\n horizontal: box.isHorizontal(),\n weight: box.weight,\n stack: stack && (pos + stack),\n stackWeight\n });\n }\n return layoutBoxes;\n}\n\nfunction buildStacks(layouts) {\n const stacks = {};\n for (const wrap of layouts) {\n const {stack, pos, stackWeight} = wrap;\n if (!stack || !STATIC_POSITIONS.includes(pos)) {\n continue;\n }\n const _stack = stacks[stack] || (stacks[stack] = {count: 0, placed: 0, weight: 0, size: 0});\n _stack.count++;\n _stack.weight += stackWeight;\n }\n return stacks;\n}\n\n/**\n * store dimensions used instead of available chartArea in fitBoxes\n **/\nfunction setLayoutDims(layouts, params) {\n const stacks = buildStacks(layouts);\n const {vBoxMaxWidth, hBoxMaxHeight} = params;\n let i, ilen, layout;\n for (i = 0, ilen = layouts.length; i < ilen; ++i) {\n layout = layouts[i];\n const {fullSize} = layout.box;\n const stack = stacks[layout.stack];\n const factor = stack && layout.stackWeight / stack.weight;\n if (layout.horizontal) {\n layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth;\n layout.height = hBoxMaxHeight;\n } else {\n layout.width = vBoxMaxWidth;\n layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight;\n }\n }\n return stacks;\n}\n\nfunction buildLayoutBoxes(boxes) {\n const layoutBoxes = wrapBoxes(boxes);\n const fullSize = sortByWeight(layoutBoxes.filter(wrap => wrap.box.fullSize), true);\n const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);\n const right = sortByWeight(filterByPosition(layoutBoxes, 'right'));\n const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);\n const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));\n const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x');\n const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y');\n\n return {\n fullSize,\n leftAndTop: left.concat(top),\n rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal),\n chartArea: filterByPosition(layoutBoxes, 'chartArea'),\n vertical: left.concat(right).concat(centerVertical),\n horizontal: top.concat(bottom).concat(centerHorizontal)\n };\n}\n\nfunction getCombinedMax(maxPadding, chartArea, a, b) {\n return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);\n}\n\nfunction updateMaxPadding(maxPadding, boxPadding) {\n maxPadding.top = Math.max(maxPadding.top, boxPadding.top);\n maxPadding.left = Math.max(maxPadding.left, boxPadding.left);\n maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);\n maxPadding.right = Math.max(maxPadding.right, boxPadding.right);\n}\n\nfunction updateDims(chartArea, params, layout, stacks) {\n const {pos, box} = layout;\n const maxPadding = chartArea.maxPadding;\n\n // dynamically placed boxes size is not considered\n if (!isObject(pos)) {\n if (layout.size) {\n // this layout was already counted for, lets first reduce old size\n chartArea[pos] -= layout.size;\n }\n const stack = stacks[layout.stack] || {size: 0, count: 1};\n stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width);\n layout.size = stack.size / stack.count;\n chartArea[pos] += layout.size;\n }\n\n if (box.getPadding) {\n updateMaxPadding(maxPadding, box.getPadding());\n }\n\n const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right'));\n const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom'));\n const widthChanged = newWidth !== chartArea.w;\n const heightChanged = newHeight !== chartArea.h;\n chartArea.w = newWidth;\n chartArea.h = newHeight;\n\n // return booleans on the changes per direction\n return layout.horizontal\n ? {same: widthChanged, other: heightChanged}\n : {same: heightChanged, other: widthChanged};\n}\n\nfunction handleMaxPadding(chartArea) {\n const maxPadding = chartArea.maxPadding;\n\n function updatePos(pos) {\n const change = Math.max(maxPadding[pos] - chartArea[pos], 0);\n chartArea[pos] += change;\n return change;\n }\n chartArea.y += updatePos('top');\n chartArea.x += updatePos('left');\n updatePos('right');\n updatePos('bottom');\n}\n\nfunction getMargins(horizontal, chartArea) {\n const maxPadding = chartArea.maxPadding;\n\n function marginForPositions(positions) {\n const margin = {left: 0, top: 0, right: 0, bottom: 0};\n positions.forEach((pos) => {\n margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);\n });\n return margin;\n }\n\n return horizontal\n ? marginForPositions(['left', 'right'])\n : marginForPositions(['top', 'bottom']);\n}\n\nfunction fitBoxes(boxes, chartArea, params, stacks) {\n const refitBoxes = [];\n let i, ilen, layout, box, refit, changed;\n\n for (i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i) {\n layout = boxes[i];\n box = layout.box;\n\n box.update(\n layout.width || chartArea.w,\n layout.height || chartArea.h,\n getMargins(layout.horizontal, chartArea)\n );\n const {same, other} = updateDims(chartArea, params, layout, stacks);\n\n // Dimensions changed and there were non full width boxes before this\n // -> we have to refit those\n refit |= same && refitBoxes.length;\n\n // Chart area changed in the opposite direction\n changed = changed || other;\n\n if (!box.fullSize) { // fullSize boxes don't need to be re-fitted in any case\n refitBoxes.push(layout);\n }\n }\n\n return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed;\n}\n\nfunction setBoxDims(box, left, top, width, height) {\n box.top = top;\n box.left = left;\n box.right = left + width;\n box.bottom = top + height;\n box.width = width;\n box.height = height;\n}\n\nfunction placeBoxes(boxes, chartArea, params, stacks) {\n const userPadding = params.padding;\n let {x, y} = chartArea;\n\n for (const layout of boxes) {\n const box = layout.box;\n const stack = stacks[layout.stack] || {count: 1, placed: 0, weight: 1};\n const weight = (layout.stackWeight / stack.weight) || 1;\n if (layout.horizontal) {\n const width = chartArea.w * weight;\n const height = stack.size || box.height;\n if (defined(stack.start)) {\n y = stack.start;\n }\n if (box.fullSize) {\n setBoxDims(box, userPadding.left, y, params.outerWidth - userPadding.right - userPadding.left, height);\n } else {\n setBoxDims(box, chartArea.left + stack.placed, y, width, height);\n }\n stack.start = y;\n stack.placed += width;\n y = box.bottom;\n } else {\n const height = chartArea.h * weight;\n const width = stack.size || box.width;\n if (defined(stack.start)) {\n x = stack.start;\n }\n if (box.fullSize) {\n setBoxDims(box, x, userPadding.top, width, params.outerHeight - userPadding.bottom - userPadding.top);\n } else {\n setBoxDims(box, x, chartArea.top + stack.placed, width, height);\n }\n stack.start = x;\n stack.placed += height;\n x = box.right;\n }\n }\n\n chartArea.x = x;\n chartArea.y = y;\n}\n\n/**\n * @interface LayoutItem\n * @typedef {object} LayoutItem\n * @prop {string} position - The position of the item in the chart layout. Possible values are\n * 'left', 'top', 'right', 'bottom', and 'chartArea'\n * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area\n * @prop {boolean} fullSize - if true, and the item is horizontal, then push vertical boxes down\n * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)\n * @prop {function} update - Takes two parameters: width and height. Returns size of item\n * @prop {function} draw - Draws the element\n * @prop {function} [getPadding] - Returns an object with padding on the edges\n * @prop {number} width - Width of item. Must be valid after update()\n * @prop {number} height - Height of item. Must be valid after update()\n * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update\n * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update\n * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update\n * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update\n */\n\n// The layout service is very self explanatory. It's responsible for the layout within a chart.\n// Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need\n// It is this service's responsibility of carrying out that layout.\nexport default {\n\n /**\n\t * Register a box to a chart.\n\t * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.\n\t * @param {Chart} chart - the chart to use\n\t * @param {LayoutItem} item - the item to add to be laid out\n\t */\n addBox(chart, item) {\n if (!chart.boxes) {\n chart.boxes = [];\n }\n\n // initialize item with default values\n item.fullSize = item.fullSize || false;\n item.position = item.position || 'top';\n item.weight = item.weight || 0;\n // @ts-ignore\n item._layers = item._layers || function() {\n return [{\n z: 0,\n draw(chartArea) {\n item.draw(chartArea);\n }\n }];\n };\n\n chart.boxes.push(item);\n },\n\n /**\n\t * Remove a layoutItem from a chart\n\t * @param {Chart} chart - the chart to remove the box from\n\t * @param {LayoutItem} layoutItem - the item to remove from the layout\n\t */\n removeBox(chart, layoutItem) {\n const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;\n if (index !== -1) {\n chart.boxes.splice(index, 1);\n }\n },\n\n /**\n\t * Sets (or updates) options on the given `item`.\n\t * @param {Chart} chart - the chart in which the item lives (or will be added to)\n\t * @param {LayoutItem} item - the item to configure with the given options\n\t * @param {object} options - the new item options.\n\t */\n configure(chart, item, options) {\n item.fullSize = options.fullSize;\n item.position = options.position;\n item.weight = options.weight;\n },\n\n /**\n\t * Fits boxes of the given chart into the given size by having each box measure itself\n\t * then running a fitting algorithm\n\t * @param {Chart} chart - the chart\n\t * @param {number} width - the width to fit into\n\t * @param {number} height - the height to fit into\n * @param {number} minPadding - minimum padding required for each side of chart area\n\t */\n update(chart, width, height, minPadding) {\n if (!chart) {\n return;\n }\n\n const padding = toPadding(chart.options.layout.padding);\n const availableWidth = Math.max(width - padding.width, 0);\n const availableHeight = Math.max(height - padding.height, 0);\n const boxes = buildLayoutBoxes(chart.boxes);\n const verticalBoxes = boxes.vertical;\n const horizontalBoxes = boxes.horizontal;\n\n // Before any changes are made, notify boxes that an update is about to being\n // This is used to clear any cached data (e.g. scale limits)\n each(chart.boxes, box => {\n if (typeof box.beforeLayout === 'function') {\n box.beforeLayout();\n }\n });\n\n // Essentially we now have any number of boxes on each of the 4 sides.\n // Our canvas looks like the following.\n // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and\n // B1 is the bottom axis\n // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays\n // These locations are single-box locations only, when trying to register a chartArea location that is already taken,\n // an error will be thrown.\n //\n // |----------------------------------------------------|\n // | T1 (Full Width) |\n // |----------------------------------------------------|\n // | | | T2 | |\n // | |----|-------------------------------------|----|\n // | | | C1 | | C2 | |\n // | | |----| |----| |\n // | | | | |\n // | L1 | L2 | ChartArea (C0) | R1 |\n // | | | | |\n // | | |----| |----| |\n // | | | C3 | | C4 | |\n // | |----|-------------------------------------|----|\n // | | | B1 | |\n // |----------------------------------------------------|\n // | B2 (Full Width) |\n // |----------------------------------------------------|\n //\n\n const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap) =>\n wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1;\n\n const params = Object.freeze({\n outerWidth: width,\n outerHeight: height,\n padding,\n availableWidth,\n availableHeight,\n vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount,\n hBoxMaxHeight: availableHeight / 2\n });\n const maxPadding = Object.assign({}, padding);\n updateMaxPadding(maxPadding, toPadding(minPadding));\n const chartArea = Object.assign({\n maxPadding,\n w: availableWidth,\n h: availableHeight,\n x: padding.left,\n y: padding.top\n }, padding);\n\n const stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);\n\n // First fit the fullSize boxes, to reduce probability of re-fitting.\n fitBoxes(boxes.fullSize, chartArea, params, stacks);\n\n // Then fit vertical boxes\n fitBoxes(verticalBoxes, chartArea, params, stacks);\n\n // Then fit horizontal boxes\n if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) {\n // if the area changed, re-fit vertical boxes\n fitBoxes(verticalBoxes, chartArea, params, stacks);\n }\n\n handleMaxPadding(chartArea);\n\n // Finally place the boxes to correct coordinates\n placeBoxes(boxes.leftAndTop, chartArea, params, stacks);\n\n // Move to opposite side of chart\n chartArea.x += chartArea.w;\n chartArea.y += chartArea.h;\n\n placeBoxes(boxes.rightAndBottom, chartArea, params, stacks);\n\n chart.chartArea = {\n left: chartArea.left,\n top: chartArea.top,\n right: chartArea.left + chartArea.w,\n bottom: chartArea.top + chartArea.h,\n height: chartArea.h,\n width: chartArea.w,\n };\n\n // Finally update boxes in chartArea (radial scale for example)\n each(boxes.chartArea, (layout) => {\n const box = layout.box;\n Object.assign(box, chart.chartArea);\n box.update(chartArea.w, chartArea.h, {left: 0, top: 0, right: 0, bottom: 0});\n });\n }\n};\n","\n/**\n * @typedef { import('../core/core.controller.js').default } Chart\n */\n\n/**\n * Abstract class that allows abstracting platform dependencies away from the chart.\n */\nexport default class BasePlatform {\n /**\n\t * Called at chart construction time, returns a context2d instance implementing\n\t * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.\n\t * @param {HTMLCanvasElement} canvas - The canvas from which to acquire context (platform specific)\n\t * @param {number} [aspectRatio] - The chart options\n\t */\n acquireContext(canvas, aspectRatio) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * Called at chart destruction time, releases any resources associated to the context\n\t * previously returned by the acquireContext() method.\n\t * @param {CanvasRenderingContext2D} context - The context2d instance\n\t * @returns {boolean} true if the method succeeded, else false\n\t */\n releaseContext(context) { // eslint-disable-line no-unused-vars\n return false;\n }\n\n /**\n\t * Registers the specified listener on the given chart.\n\t * @param {Chart} chart - Chart from which to listen for event\n\t * @param {string} type - The ({@link ChartEvent}) type to listen for\n\t * @param {function} listener - Receives a notification (an object that implements\n\t * the {@link ChartEvent} interface) when an event of the specified type occurs.\n\t */\n addEventListener(chart, type, listener) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * Removes the specified listener previously registered with addEventListener.\n\t * @param {Chart} chart - Chart from which to remove the listener\n\t * @param {string} type - The ({@link ChartEvent}) type to remove\n\t * @param {function} listener - The listener function to remove from the event target.\n\t */\n removeEventListener(chart, type, listener) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * @returns {number} the current devicePixelRatio of the device this platform is connected to.\n\t */\n getDevicePixelRatio() {\n return 1;\n }\n\n /**\n\t * Returns the maximum size in pixels of given canvas element.\n\t * @param {HTMLCanvasElement} element\n\t * @param {number} [width] - content width of parent element\n\t * @param {number} [height] - content height of parent element\n\t * @param {number} [aspectRatio] - aspect ratio to maintain\n\t */\n getMaximumSize(element, width, height, aspectRatio) {\n width = Math.max(0, width || element.width);\n height = height || element.height;\n return {\n width,\n height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height)\n };\n }\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t * @returns {boolean} true if the canvas is attached to the platform, false if not.\n\t */\n isAttached(canvas) { // eslint-disable-line no-unused-vars\n return true;\n }\n\n /**\n * Updates config with platform specific requirements\n * @param {import('../core/core.config.js').default} config\n */\n updateConfig(config) { // eslint-disable-line no-unused-vars\n // no-op\n }\n}\n","/**\n * Platform fallback implementation (minimal).\n * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939\n */\n\nimport BasePlatform from './platform.base.js';\n\n/**\n * Platform class for charts without access to the DOM or to many element properties\n * This platform is used by default for any chart passed an OffscreenCanvas.\n * @extends BasePlatform\n */\nexport default class BasicPlatform extends BasePlatform {\n acquireContext(item) {\n // To prevent canvas fingerprinting, some add-ons undefine the getContext\n // method, for example: https://github.com/kkapsner/CanvasBlocker\n // https://github.com/chartjs/Chart.js/issues/2807\n return item && item.getContext && item.getContext('2d') || null;\n }\n updateConfig(config) {\n config.options.animation = false;\n }\n}\n","/**\n * Chart.Platform implementation for targeting a web browser\n */\n\nimport BasePlatform from './platform.base.js';\nimport {_getParentNode, getRelativePosition, supportsEventListenerOptions, readUsedSize, getMaximumSize} from '../helpers/helpers.dom.js';\nimport {throttled} from '../helpers/helpers.extras.js';\nimport {isNullOrUndef} from '../helpers/helpers.core.js';\n\n/**\n * @typedef { import('../core/core.controller.js').default } Chart\n */\n\nconst EXPANDO_KEY = '$chartjs';\n\n/**\n * DOM event types -> Chart.js event types.\n * Note: only events with different types are mapped.\n * @see https://developer.mozilla.org/en-US/docs/Web/Events\n */\nconst EVENT_TYPES = {\n touchstart: 'mousedown',\n touchmove: 'mousemove',\n touchend: 'mouseup',\n pointerenter: 'mouseenter',\n pointerdown: 'mousedown',\n pointermove: 'mousemove',\n pointerup: 'mouseup',\n pointerleave: 'mouseout',\n pointerout: 'mouseout'\n};\n\nconst isNullOrEmpty = value => value === null || value === '';\n/**\n * Initializes the canvas style and render size without modifying the canvas display size,\n * since responsiveness is handled by the controller.resize() method. The config is used\n * to determine the aspect ratio to apply in case no explicit height has been specified.\n * @param {HTMLCanvasElement} canvas\n * @param {number} [aspectRatio]\n */\nfunction initCanvas(canvas, aspectRatio) {\n const style = canvas.style;\n\n // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it\n // returns null or '' if no explicit value has been set to the canvas attribute.\n const renderHeight = canvas.getAttribute('height');\n const renderWidth = canvas.getAttribute('width');\n\n // Chart.js modifies some canvas values that we want to restore on destroy\n canvas[EXPANDO_KEY] = {\n initial: {\n height: renderHeight,\n width: renderWidth,\n style: {\n display: style.display,\n height: style.height,\n width: style.width\n }\n }\n };\n\n // Force canvas to display as block to avoid extra space caused by inline\n // elements, which would interfere with the responsive resize process.\n // https://github.com/chartjs/Chart.js/issues/2538\n style.display = style.display || 'block';\n // Include possible borders in the size\n style.boxSizing = style.boxSizing || 'border-box';\n\n if (isNullOrEmpty(renderWidth)) {\n const displayWidth = readUsedSize(canvas, 'width');\n if (displayWidth !== undefined) {\n canvas.width = displayWidth;\n }\n }\n\n if (isNullOrEmpty(renderHeight)) {\n if (canvas.style.height === '') {\n // If no explicit render height and style height, let's apply the aspect ratio,\n // which one can be specified by the user but also by charts as default option\n // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.\n canvas.height = canvas.width / (aspectRatio || 2);\n } else {\n const displayHeight = readUsedSize(canvas, 'height');\n if (displayHeight !== undefined) {\n canvas.height = displayHeight;\n }\n }\n }\n\n return canvas;\n}\n\n// Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.\n// https://github.com/chartjs/Chart.js/issues/4287\nconst eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;\n\nfunction addListener(node, type, listener) {\n if (node) {\n node.addEventListener(type, listener, eventListenerOptions);\n }\n}\n\nfunction removeListener(chart, type, listener) {\n if (chart && chart.canvas) {\n chart.canvas.removeEventListener(type, listener, eventListenerOptions);\n }\n}\n\nfunction fromNativeEvent(event, chart) {\n const type = EVENT_TYPES[event.type] || event.type;\n const {x, y} = getRelativePosition(event, chart);\n return {\n type,\n chart,\n native: event,\n x: x !== undefined ? x : null,\n y: y !== undefined ? y : null,\n };\n}\n\nfunction nodeListContains(nodeList, canvas) {\n for (const node of nodeList) {\n if (node === canvas || node.contains(canvas)) {\n return true;\n }\n }\n}\n\nfunction createAttachObserver(chart, type, listener) {\n const canvas = chart.canvas;\n const observer = new MutationObserver(entries => {\n let trigger = false;\n for (const entry of entries) {\n trigger = trigger || nodeListContains(entry.addedNodes, canvas);\n trigger = trigger && !nodeListContains(entry.removedNodes, canvas);\n }\n if (trigger) {\n listener();\n }\n });\n observer.observe(document, {childList: true, subtree: true});\n return observer;\n}\n\nfunction createDetachObserver(chart, type, listener) {\n const canvas = chart.canvas;\n const observer = new MutationObserver(entries => {\n let trigger = false;\n for (const entry of entries) {\n trigger = trigger || nodeListContains(entry.removedNodes, canvas);\n trigger = trigger && !nodeListContains(entry.addedNodes, canvas);\n }\n if (trigger) {\n listener();\n }\n });\n observer.observe(document, {childList: true, subtree: true});\n return observer;\n}\n\nconst drpListeningCharts = new Map();\nlet oldDevicePixelRatio = 0;\n\nfunction onWindowResize() {\n const dpr = window.devicePixelRatio;\n if (dpr === oldDevicePixelRatio) {\n return;\n }\n oldDevicePixelRatio = dpr;\n drpListeningCharts.forEach((resize, chart) => {\n if (chart.currentDevicePixelRatio !== dpr) {\n resize();\n }\n });\n}\n\nfunction listenDevicePixelRatioChanges(chart, resize) {\n if (!drpListeningCharts.size) {\n window.addEventListener('resize', onWindowResize);\n }\n drpListeningCharts.set(chart, resize);\n}\n\nfunction unlistenDevicePixelRatioChanges(chart) {\n drpListeningCharts.delete(chart);\n if (!drpListeningCharts.size) {\n window.removeEventListener('resize', onWindowResize);\n }\n}\n\nfunction createResizeObserver(chart, type, listener) {\n const canvas = chart.canvas;\n const container = canvas && _getParentNode(canvas);\n if (!container) {\n return;\n }\n const resize = throttled((width, height) => {\n const w = container.clientWidth;\n listener(width, height);\n if (w < container.clientWidth) {\n // If the container size shrank during chart resize, let's assume\n // scrollbar appeared. So we resize again with the scrollbar visible -\n // effectively making chart smaller and the scrollbar hidden again.\n // Because we are inside `throttled`, and currently `ticking`, scroll\n // events are ignored during this whole 2 resize process.\n // If we assumed wrong and something else happened, we are resizing\n // twice in a frame (potential performance issue)\n listener();\n }\n }, window);\n\n // @ts-ignore until https://github.com/microsoft/TypeScript/issues/37861 implemented\n const observer = new ResizeObserver(entries => {\n const entry = entries[0];\n const width = entry.contentRect.width;\n const height = entry.contentRect.height;\n // When its container's display is set to 'none' the callback will be called with a\n // size of (0, 0), which will cause the chart to lose its original height, so skip\n // resizing in such case.\n if (width === 0 && height === 0) {\n return;\n }\n resize(width, height);\n });\n observer.observe(container);\n listenDevicePixelRatioChanges(chart, resize);\n\n return observer;\n}\n\nfunction releaseObserver(chart, type, observer) {\n if (observer) {\n observer.disconnect();\n }\n if (type === 'resize') {\n unlistenDevicePixelRatioChanges(chart);\n }\n}\n\nfunction createProxyAndListen(chart, type, listener) {\n const canvas = chart.canvas;\n const proxy = throttled((event) => {\n // This case can occur if the chart is destroyed while waiting\n // for the throttled function to occur. We prevent crashes by checking\n // for a destroyed chart\n if (chart.ctx !== null) {\n listener(fromNativeEvent(event, chart));\n }\n }, chart);\n\n addListener(canvas, type, proxy);\n\n return proxy;\n}\n\n/**\n * Platform class for charts that can access the DOM and global window/document properties\n * @extends BasePlatform\n */\nexport default class DomPlatform extends BasePlatform {\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t * @param {number} [aspectRatio]\n\t * @return {CanvasRenderingContext2D|null}\n\t */\n acquireContext(canvas, aspectRatio) {\n // To prevent canvas fingerprinting, some add-ons undefine the getContext\n // method, for example: https://github.com/kkapsner/CanvasBlocker\n // https://github.com/chartjs/Chart.js/issues/2807\n const context = canvas && canvas.getContext && canvas.getContext('2d');\n\n // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the canvas is\n // inside an iframe or when running in a protected environment. We could guess the\n // types from their toString() value but let's keep things flexible and assume it's\n // a sufficient condition if the canvas has a context2D which has canvas as `canvas`.\n // https://github.com/chartjs/Chart.js/issues/3887\n // https://github.com/chartjs/Chart.js/issues/4102\n // https://github.com/chartjs/Chart.js/issues/4152\n if (context && context.canvas === canvas) {\n // Load platform resources on first chart creation, to make it possible to\n // import the library before setting platform options.\n initCanvas(canvas, aspectRatio);\n return context;\n }\n\n return null;\n }\n\n /**\n\t * @param {CanvasRenderingContext2D} context\n\t */\n releaseContext(context) {\n const canvas = context.canvas;\n if (!canvas[EXPANDO_KEY]) {\n return false;\n }\n\n const initial = canvas[EXPANDO_KEY].initial;\n ['height', 'width'].forEach((prop) => {\n const value = initial[prop];\n if (isNullOrUndef(value)) {\n canvas.removeAttribute(prop);\n } else {\n canvas.setAttribute(prop, value);\n }\n });\n\n const style = initial.style || {};\n Object.keys(style).forEach((key) => {\n canvas.style[key] = style[key];\n });\n\n // The canvas render size might have been changed (and thus the state stack discarded),\n // we can't use save() and restore() to restore the initial state. So make sure that at\n // least the canvas context is reset to the default state by setting the canvas width.\n // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html\n // eslint-disable-next-line no-self-assign\n canvas.width = canvas.width;\n\n delete canvas[EXPANDO_KEY];\n return true;\n }\n\n /**\n\t *\n\t * @param {Chart} chart\n\t * @param {string} type\n\t * @param {function} listener\n\t */\n addEventListener(chart, type, listener) {\n // Can have only one listener per type, so make sure previous is removed\n this.removeEventListener(chart, type);\n\n const proxies = chart.$proxies || (chart.$proxies = {});\n const handlers = {\n attach: createAttachObserver,\n detach: createDetachObserver,\n resize: createResizeObserver\n };\n const handler = handlers[type] || createProxyAndListen;\n proxies[type] = handler(chart, type, listener);\n }\n\n\n /**\n\t * @param {Chart} chart\n\t * @param {string} type\n\t */\n removeEventListener(chart, type) {\n const proxies = chart.$proxies || (chart.$proxies = {});\n const proxy = proxies[type];\n\n if (!proxy) {\n return;\n }\n\n const handlers = {\n attach: releaseObserver,\n detach: releaseObserver,\n resize: releaseObserver\n };\n const handler = handlers[type] || removeListener;\n handler(chart, type, proxy);\n proxies[type] = undefined;\n }\n\n getDevicePixelRatio() {\n return window.devicePixelRatio;\n }\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t * @param {number} [width] - content width of parent element\n\t * @param {number} [height] - content height of parent element\n\t * @param {number} [aspectRatio] - aspect ratio to maintain\n\t */\n getMaximumSize(canvas, width, height, aspectRatio) {\n return getMaximumSize(canvas, width, height, aspectRatio);\n }\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t */\n isAttached(canvas) {\n const container = canvas && _getParentNode(canvas);\n return !!(container && container.isConnected);\n }\n}\n","import {_isDomSupported} from '../helpers/index.js';\nimport BasePlatform from './platform.base.js';\nimport BasicPlatform from './platform.basic.js';\nimport DomPlatform from './platform.dom.js';\n\nexport function _detectPlatform(canvas) {\n if (!_isDomSupported() || (typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas)) {\n return BasicPlatform;\n }\n return DomPlatform;\n}\n\nexport {BasePlatform, BasicPlatform, DomPlatform};\n","import type {AnyObject} from '../types/basic.js';\nimport type {Point} from '../types/geometric.js';\nimport type {Animation} from '../types/animation.js';\nimport {isNumber} from '../helpers/helpers.math.js';\n\nexport default class Element {\n\n static defaults = {};\n static defaultRoutes = undefined;\n\n x: number;\n y: number;\n active = false;\n options: O;\n $animations: Record;\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 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 {each, callback as callCallback, uid, valueOrDefault, _elementsEqual, isNullOrUndef, setsEqual, defined, isFunction, _isClickEvent} from '../helpers/helpers.core.js';\nimport {clearCanvas, clipArea, createContext, unclipArea, _isPointInArea, _isDomSupported, retinaScale, getDatasetClipArea} 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\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 // Unset pending resize request now to avoid possible recursion within _resize\n this._resizeBeforeDraw = null;\n this._resize(width, height);\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 args = {\n meta,\n index: meta.index,\n cancelable: true\n };\n // @ts-expect-error\n const clip = getDatasetClipArea(this, meta);\n\n if (this.notifyPlugins('beforeDatasetDraw', args) === false) {\n return;\n }\n\n if (clip) {\n clipArea(ctx, clip);\n }\n\n meta.controller.draw();\n\n if (clip) {\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 event 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, _angleDiff, _normalizeAngle, _isBetween, _limitValue} from '../helpers/helpers.math.js';\nimport {_readValueToProps} from '../helpers/helpers.options.js';\nimport type {ArcOptions, Point} from '../types/index.js';\n\nfunction clipSelf(ctx: CanvasRenderingContext2D, element: ArcElement, endAngle: number) {\n const {startAngle, x, y, outerRadius, innerRadius, options} = element;\n const {borderWidth, borderJoinStyle} = options;\n const outerAngleClip = Math.min(borderWidth / outerRadius, _normalizeAngle(startAngle - endAngle));\n ctx.beginPath();\n ctx.arc(x, y, outerRadius - borderWidth / 2, startAngle + outerAngleClip / 2, endAngle - outerAngleClip / 2);\n\n if (innerRadius > 0) {\n const innerAngleClip = Math.min(borderWidth / innerRadius, _normalizeAngle(startAngle - endAngle));\n ctx.arc(x, y, innerRadius + borderWidth / 2, endAngle - innerAngleClip / 2, startAngle + innerAngleClip / 2, true);\n } else {\n const clipWidth = Math.min(borderWidth / 2, outerRadius * _normalizeAngle(startAngle - endAngle));\n\n if (borderJoinStyle === 'round') {\n ctx.arc(x, y, clipWidth, endAngle - PI / 2, startAngle + PI / 2, true);\n } else if (borderJoinStyle === 'bevel') {\n const r = 2 * clipWidth * clipWidth;\n const endX = -r * Math.cos(endAngle + PI / 2) + x;\n const endY = -r * Math.sin(endAngle + PI / 2) + y;\n const startX = r * Math.cos(startAngle + PI / 2) + x;\n const startY = r * Math.sin(startAngle + PI / 2) + y;\n ctx.lineTo(endX, endY);\n ctx.lineTo(startX, startY);\n }\n }\n ctx.closePath();\n\n ctx.moveTo(0, 0);\n ctx.rect(0, 0, ctx.canvas.width, ctx.canvas.height);\n\n ctx.clip('evenodd');\n}\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, 𝜃) 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, borderRadius} = 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 (options.selfJoin && endAngle - startAngle >= PI && borderRadius === 0 && borderJoinStyle !== 'miter') {\n clipSelf(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 selfJoin: false,\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 nonZeroBetween = _angleBetween(angle, startAngle, endAngle) && startAngle !== endAngle;\n const betweenAngles = _circumference >= TAU || nonZeroBetween;\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, defaults} 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\nfunction containsDefaultColorsDefenitions() {\n return defaults.borderColor !== 'rgba(0,0,0,0.1)' || defaults.backgroundColor !== 'rgba(0,0,0,0.1)';\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 const containsColorDefenition = (\n containsColorsDefinitions(datasets) ||\n containsColorsDefinition(chartOptions) ||\n (elements && containsColorsDefinitions(elements)) ||\n containsDefaultColorsDefenitions());\n\n if (!options.forceOverride && containsColorDefenition) {\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 a segment -> need to add another point before this,\n postponed.unshift(point);\n } else {\n points.push(point);\n if (!last) {\n // In the middle of a 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, getDatasetClipArea} 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 {chart, index, 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 const meta = chart.getDatasetMeta(index);\n const clip = getDatasetClipArea(chart, meta);\n if (target && line.points.length) {\n clipArea(ctx, area);\n doFill(ctx, {line, target, above, below, area, scale, axis, clip});\n unclipArea(ctx);\n }\n}\n\nfunction doFill(ctx, cfg) {\n const {line, target, above, below, area, scale, clip} = cfg;\n const property = line._loop ? 'angle' : cfg.axis;\n\n ctx.save();\n\n let fillColor = below;\n if (below !== above) {\n if (property === 'x') {\n clipVertical(ctx, target, area.top);\n fill(ctx, {line, target, color: above, scale, property, clip});\n ctx.restore();\n ctx.save();\n clipVertical(ctx, target, area.bottom);\n } else if (property === 'y') {\n clipHorizontal(ctx, target, area.left);\n fill(ctx, {line, target, color: below, scale, property, clip});\n ctx.restore();\n ctx.save();\n clipHorizontal(ctx, target, area.right);\n fillColor = above;\n }\n }\n fill(ctx, {line, target, color: fillColor, scale, property, clip});\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 clipHorizontal(ctx, target, clipX) {\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(clipX, firstPoint.y);\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(clipX, lastPoint.y);\n }\n }\n\n ctx.lineTo(clipX, target.first().y);\n ctx.closePath();\n ctx.clip();\n}\n\nfunction fill(ctx, cfg) {\n const {line, target, property, color, scale, clip} = 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, clip, 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, clip, bounds) {\n const chartArea = scale.chart.chartArea;\n const {property, start, end} = bounds || {};\n\n if (property === 'x' || property === 'y') {\n let left, top, right, bottom;\n\n if (property === 'x') {\n left = start;\n top = chartArea.top;\n right = end;\n bottom = chartArea.bottom;\n } else {\n left = chartArea.left;\n top = start;\n right = chartArea.right;\n bottom = end;\n }\n\n ctx.beginPath();\n\n if (clip) {\n left = Math.max(left, clip.left);\n right = Math.min(right, clip.right);\n top = Math.max(top, clip.top);\n bottom = Math.min(bottom, clip.bottom);\n }\n\n ctx.rect(left, top, right - left, 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 // No visible items where found, return false so we don't have to divide by 0 which reduces in NaN\n if (count === 0 || xSet.size === 0) {\n return false;\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.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, 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"],"names":["Animator","constructor","_request","_charts","Map","_running","_lastDate","undefined","_notify","chart","anims","date","type","callbacks","listeners","numSteps","duration","forEach","fn","initial","currentStep","Math","min","start","_refresh","requestAnimFrame","call","window","_update","Date","now","remaining","running","items","length","i","draw","item","_active","_total","tick","pop","_getAnims","charts","get","complete","progress","set","listen","event","cb","push","add","has","reduce","acc","cur","max","_duration","stop","cancel","remove","delete","transparent","interpolators","boolean","from","to","factor","color","c0","helpersColor","c1","valid","mix","hexString","number","Animation","cfg","target","prop","currentValue","resolve","_fn","_easing","effects","easing","linear","_start","floor","delay","_loop","loop","_target","_prop","_from","_to","_promises","active","update","elapsed","remain","wait","promises","Promise","res","rej","resolved","method","Animations","config","_chart","_properties","configure","isObject","animationOptions","Object","keys","defaults","animation","animatedProps","getOwnPropertyNames","key","option","isArray","properties","_animateOptions","values","newOptions","options","resolveTargetOptions","animations","_createAnimations","$shared","awaitAll","$animations","then","props","charAt","value","size","assign","animator","anim","all","scaleClip","scale","allowedOverflow","opts","reverse","end","defaultClip","xScale","yScale","x","y","top","right","bottom","left","toClip","t","r","b","l","disabled","getSortedDatasetIndices","filterVisible","metasets","_getSortedDatasetMetas","ilen","index","applyStack","stack","dsIndex","singleMode","mode","datasetIndex","otherValue","found","isFinite","sign","convertObjectDataToArray","data","meta","iScale","vScale","iAxisKey","axis","vAxisKey","adata","Array","isStacked","stacked","getStackKey","indexScale","valueScale","id","getUserBounds","minDefined","maxDefined","Number","NEGATIVE_INFINITY","POSITIVE_INFINITY","getOrCreateStack","stacks","stackKey","indexValue","subStack","getLastIndexInStack","positive","getMatchingVisibleMetas","updateStacks","controller","parsed","_cachedMeta","_stacks","iAxis","vAxis","itemStacks","_top","_bottom","visualValues","_visualValues","getFirstScaleId","scales","filter","shift","createDatasetContext","parent","createContext","dataset","createDataContext","element","dataIndex","raw","clearStacks","_parsed","isDirectUpdateMode","cloneIfNotShared","cached","shared","createStack","canStack","hidden","_stacked","DatasetController","datasetElementType","dataElementType","_ctx","ctx","_cachedDataOpts","getMeta","_type","_parsing","_data","_objectData","_sharedOptions","_drawStart","_drawCount","enableOptionSharing","supportsDecimation","$context","_syncList","initialize","linkScales","addElements","fill","isPluginEnabled","console","warn","updateIndex","getDataset","chooseId","xid","xAxisID","valueOrDefault","yid","yAxisID","rid","rAxisID","indexAxis","iid","iAxisID","vid","vAxisID","getScaleForId","rScale","datasets","getDatasetMeta","scaleID","_getOtherScale","reset","_destroy","unlistenArrayEvents","_dataCheck","isExtensible","listenArrayEvents","buildOrUpdateElements","resetNewElements","stackChanged","oldStacked","_resyncElements","scopeKeys","datasetScopeKeys","scopes","getOptionScopes","createResolver","getContext","parsing","parse","count","sorted","_sorted","prev","parseArrayData","parseObjectData","parsePrimitiveData","isNotInOrderComparedToPrev","labels","getLabels","singleScale","xAxisKey","yAxisKey","resolveObjectKey","getParsed","getDataElement","updateRangeFromParsed","range","parsedValue","NaN","getMinMax","otherScale","otherMin","otherMax","_skip","getAllParsedValues","getMaxOverflow","getLabelAndValue","label","getLabelForValue","_clip","clip","elements","area","chartArea","drawActiveElementsOnTop","getStyle","resolveDatasetElementOptions","resolveDataElementOptions","context","_resolveElementOptions","elementType","cache","cacheKey","sharing","defined","datasetElementScopeKeys","prefixes","names","resolveNamedOptions","freeze","_resolveAnimations","transition","datasetAnimationScopeKeys","_cacheable","getSharedOptions","includeOptions","sharedOptions","_animationsDisabled","_getSharedOptions","firstOpts","previouslySharedOptions","updateSharedOptions","updateElement","_setStyle","removeHoverStyle","setHoverStyle","_removeDatasetHoverStyle","_setDatasetHoverStyle","arg1","arg2","numMeta","numData","_insertElements","_removeElements","move","arr","updateElements","removed","splice","_sync","args","_dataChanges","_onDataPush","arguments","_onDataPop","_onDataShift","_onDataSplice","newCount","_onDataUnshift","getAllScaleValues","_cache","$bar","visibleMetas","concat","_arrayUnique","sort","a","computeMinSampleSize","_length","curr","updateMinAndPrev","abs","getPixelForValue","ticks","getPixelForTick","computeFitCategoryTraits","ruler","stackCount","thickness","barThickness","ratio","isNullOrUndef","categoryPercentage","barPercentage","chunk","pixels","computeFlexCategoryTraits","next","percent","parseFloatBar","entry","startValue","endValue","barStart","barEnd","_custom","parseValue","parseArrayOrPrimitive","isFloatBar","custom","barSign","actualBase","isHorizontal","borderProps","horizontal","base","setBorderSkipped","edge","borderSkipped","enableBorderRadius","parseEdge","swap","startEnd","orig","v1","v2","v","setInflateAmount","inflateAmount","BarController","grouped","numbers","overrides","_index_","offset","grid","_value_","beginAtZero","obj","bars","getBasePixel","_getRuler","vpixels","head","_calculateBarValuePixels","ipixels","_calculateBarIndexPixels","center","height","width","_getStacks","last","currentParsed","iScaleValue","skipNull","find","val","isNaN","indexOf","_getStackCount","_getAxisCount","_getAxis","getFirstScaleIdForIndexAxis","indexScaleId","firstScaleAxisId","_getStackIndex","name","_startPixel","_endPixel","baseValue","minBarLength","floating","getDataVisibility","startPixel","getPixelForDecimal","endPixel","getValueForPixel","halfGrid","getLineWidthForValue","maxBarThickness","Infinity","axisCount","axisID","axisNumber","stackIndex","rects","BubbleController","radius","points","point","iPixel","vPixel","skip","getRatioAndOffset","rotation","circumference","cutout","ratioX","ratioY","offsetX","offsetY","TAU","startAngle","endAngle","startX","cos","startY","sin","endX","endY","calcMax","angle","_angleBetween","calcMin","maxX","maxY","HALF_PI","minX","PI","minY","DoughnutController","animateRotate","animateScale","spacing","descriptors","_scriptable","_indexable","startsWith","aspectRatio","plugins","legend","generateLabels","pointStyle","map","style","text","fillStyle","backgroundColor","strokeStyle","borderColor","fontColor","lineWidth","borderWidth","onClick","e","legendItem","toggleDataVisibility","innerRadius","outerRadius","getter","_getRotation","toRadians","_getCircumference","_getRotationExtents","isDatasetVisible","arcs","getMaxBorderWidth","getMaxOffset","maxSize","toPercentage","chartWeight","_getRingWeight","maxWidth","maxHeight","maxRadius","toDimension","radiusLength","_getVisibleDatasetWeightTotal","total","calculateTotal","_getRingWeightOffset","_circumference","calculateCircumference","animationOpts","centerX","centerY","arc","metaData","formatNumber","locale","borderAlign","hoverBorderWidth","hoverOffset","ringWeightOffset","weight","LineController","showLine","spanGaps","line","_dataset","animationsDisabled","_getStartAndCountOfVisiblePoints","_scaleRangesChanged","_datasetIndex","_decimated","segment","animated","maxGapLength","isNumber","directUpdate","pointsCount","prevParsed","nullData","border","firstPoint","lastPoint","updateControlPoints","PolarAreaController","angleLines","display","circular","pointLabels","_parseObjectDataRadialScale","bind","_updateRadius","minSize","cutoutPercentage","getVisibleDatasetCount","xCenter","yCenter","datasetStartAngle","getIndexAngle","defaultAngle","countVisibleElements","_computeAngle","getDistanceFromCenterForValue","PieController","RadarController","_fullLoop","pointPosition","getPointPositionForValue","ScatterController","interaction","registry","getElement","abstract","Error","DateAdapterBase","override","members","prototype","init","formats","format","diff","startOf","endOf","_date","binarySearch","metaset","intersect","lookupMethod","_reversePixels","_rlookupByKey","_lookupByKey","result","distanceToDefinedLo","slice","lo","findIndex","distanceToDefinedHi","hi","el","getRange","evaluateInteractionItems","position","handler","getSortedVisibleDatasetMetas","j","getDistanceMetricForAxis","useX","useY","pt1","pt2","deltaX","deltaY","sqrt","pow","getIntersectItems","useFinalPosition","includeInvisible","isPointInArea","evaluationFunc","_isPointInArea","inRange","getNearestRadialItems","getProps","getAngleFromPoint","getNearestCartesianItems","distanceMetric","minDistance","getCenterPoint","pointInArea","distance","getNearestItems","getAxisItems","rangeMethod","intersectsItem","modes","getRelativePosition","nearest","STATIC_POSITIONS","filterByPosition","array","pos","filterDynamicPositionByAxis","box","sortByWeight","v0","wrapBoxes","boxes","layoutBoxes","stackWeight","buildStacks","layouts","wrap","includes","_stack","placed","setLayoutDims","params","vBoxMaxWidth","hBoxMaxHeight","layout","fullSize","availableWidth","availableHeight","buildLayoutBoxes","centerHorizontal","centerVertical","leftAndTop","rightAndBottom","vertical","getCombinedMax","maxPadding","updateMaxPadding","boxPadding","updateDims","getPadding","newWidth","outerWidth","newHeight","outerHeight","widthChanged","w","heightChanged","h","same","other","handleMaxPadding","updatePos","change","getMargins","marginForPositions","positions","margin","fitBoxes","refitBoxes","refit","changed","setBoxDims","placeBoxes","userPadding","padding","addBox","_layers","z","removeBox","layoutItem","minPadding","toPadding","verticalBoxes","horizontalBoxes","each","beforeLayout","visibleVerticalBoxCount","BasePlatform","acquireContext","canvas","releaseContext","addEventListener","listener","removeEventListener","getDevicePixelRatio","getMaximumSize","isAttached","updateConfig","BasicPlatform","EXPANDO_KEY","EVENT_TYPES","touchstart","touchmove","touchend","pointerenter","pointerdown","pointermove","pointerup","pointerleave","pointerout","isNullOrEmpty","initCanvas","renderHeight","getAttribute","renderWidth","boxSizing","displayWidth","readUsedSize","displayHeight","eventListenerOptions","supportsEventListenerOptions","passive","addListener","node","removeListener","fromNativeEvent","native","nodeListContains","nodeList","contains","createAttachObserver","observer","MutationObserver","entries","trigger","addedNodes","removedNodes","observe","document","childList","subtree","createDetachObserver","drpListeningCharts","oldDevicePixelRatio","onWindowResize","dpr","devicePixelRatio","resize","currentDevicePixelRatio","listenDevicePixelRatioChanges","unlistenDevicePixelRatioChanges","createResizeObserver","container","_getParentNode","throttled","clientWidth","ResizeObserver","contentRect","releaseObserver","disconnect","createProxyAndListen","proxy","DomPlatform","removeAttribute","setAttribute","proxies","$proxies","handlers","attach","detach","isConnected","_detectPlatform","_isDomSupported","OffscreenCanvas","Element","defaultRoutes","tooltipPosition","hasValue","final","ret","autoSkip","tickOpts","determinedMaxTicks","determineMaxTicks","ticksLimit","maxTicksLimit","majorIndices","major","enabled","getMajorIndices","numMajorIndices","first","newTicks","skipMajors","calculateSpacing","avgMajorSpacing","round","tickLength","_tickSize","maxScale","maxChart","_maxLength","evenMajorSpacing","getEvenSpacing","factors","_factorize","ceil","majorStart","majorEnd","len","reverseAlign","align","offsetFromEdge","getTicksLimit","ticksLength","sample","numItems","increment","getPixelForGridLine","offsetGridLines","validIndex","epsilon","lineValue","garbageCollect","caches","gc","gcLen","getTickMarkLength","drawTicks","getTitleHeight","fallback","font","toFont","lines","lineHeight","createScaleContext","createTickContext","titleAlign","_toLeftRightCenter","titleArgs","titleX","titleY","_alignStartEnd","positionAxisID","Scale","_margins","paddingTop","paddingBottom","paddingLeft","paddingRight","labelRotation","_range","_gridLineItems","_labelItems","_labelSizes","_longestTextCache","_userMax","_userMin","_suggestedMax","_suggestedMin","_ticksLength","_borderValue","_dataLimitsCached","setContext","suggestedMin","suggestedMax","finiteOrDefault","metas","getTicks","xLabels","yLabels","getLabelItems","_computeLabelItems","beforeUpdate","margins","grace","sampleSize","beforeSetDimensions","setDimensions","afterSetDimensions","beforeDataLimits","determineDataLimits","afterDataLimits","_addGrace","beforeBuildTicks","buildTicks","afterBuildTicks","samplingEnabled","_convertTicksToLabels","beforeCalculateLabelRotation","calculateLabelRotation","afterCalculateLabelRotation","source","afterAutoSkip","beforeFit","fit","afterFit","afterUpdate","reversePixels","_alignToPixels","alignToPixels","_callHooks","notifyPlugins","beforeTickToLabelConversion","generateTickLabels","callback","afterTickToLabelConversion","numTicks","minRotation","maxRotation","tickWidth","maxLabelDiagonal","_isVisible","labelSizes","_getLabelSizes","maxLabelWidth","widest","maxLabelHeight","highest","_limitValue","title","toDegrees","asin","titleOpts","gridOpts","titleHeight","tickPadding","angleRadians","labelHeight","mirror","labelWidth","_calculatePadding","_handleMargins","isRotated","labelsBelowTicks","offsetLeft","offsetRight","isFullSize","_computeLabelSizes","widths","heights","widestLabelSize","highestLabelSize","jlen","tickFont","fontString","nestedLabel","_resolveTickFontOptions","string","_measureText","valueAt","idx","pixel","decimal","_int16Range","_alignPixel","getDecimalForPixel","getBaseValue","optionTicks","rot","autoSkipPadding","_computeGridLineItems","tl","borderOpts","axisWidth","axisHalfWidth","alignBorderValue","borderValue","alignedLineValue","tx1","ty1","tx2","ty2","x1","y1","x2","y2","limit","step","optsAtIndex","optsAtIndexBorder","lineColor","borderDash","dash","borderDashOffset","dashOffset","tickColor","tickBorderDash","tickBorderDashOffset","crossAlign","tickAndPadding","hTickAndPadding","textAlign","lineCount","textOffset","textBaseline","_getXAxisLabelAlignment","_getYAxisLabelAlignment","labelOffset","halfCount","strokeColor","textStrokeColor","strokeWidth","textStrokeWidth","tickTextAlign","showLabelBackdrop","backdrop","labelPadding","backdropPadding","backdropColor","translation","_computeLabelArea","drawBackground","save","fillRect","restore","drawGrid","drawLine","p1","p2","setLineDash","lineDashOffset","beginPath","moveTo","lineTo","stroke","drawOnChartArea","drawBorder","lastLineWidth","drawLabels","clipArea","renderTextOptions","renderText","unclipArea","drawTitle","tz","gz","bz","_maxDigits","fontSize","TypedRegistry","scope","create","isForType","isPrototypeOf","register","proto","getPrototypeOf","parentScope","isIChartComponent","registerDefaults","unregister","itemDefaults","merge","routeDefaults","describe","routes","property","propertyParts","split","sourceName","sourceScope","join","parts","targetName","targetScope","route","Registry","controllers","_typedRegistries","_each","addControllers","addPlugins","addScales","getController","_get","getPlugin","getScale","removeControllers","removeElements","removePlugins","removeScales","typedRegistry","arg","reg","_getRegistryForType","_exec","itemReg","component","camelMethod","_capitalize","PluginService","_init","notify","hook","_createDescriptors","_descriptors","descriptor","plugin","callCallback","cancelable","invalidate","_oldCache","_notifyStateChanges","allPlugins","createDescriptors","previousDescriptors","some","localIds","local","getOpts","pluginOpts","pluginScopeKeys","scriptable","indexable","allKeys","getIndexAxis","datasetDefaults","datasetOptions","getAxisFromDefaultScaleID","getDefaultScaleIDFromAxis","idMatchesAxis","axisFromPosition","determineAxis","scaleOptions","toLowerCase","getAxisFromDataset","retrieveAxisFromDatasets","boundDs","d","mergeScaleConfig","chartDefaults","configScales","chartIndexAxis","scaleConf","error","_proxy","defaultId","defaultScaleOptions","mergeIf","defaultID","initOptions","initData","initConfig","keyCache","keysCached","Set","cachedKeys","generate","addIfFound","Config","_config","_scopeCache","_resolverCache","platform","clearCache","clear","datasetType","additionalOptionScopes","_cachedScopes","mainScope","resetCache","keyLists","chartOptionScopes","resolver","subPrefixes","getResolver","needContext","isFunction","subResolver","_attachContext","descriptorDefaults","resolverCache","_createResolver","p","hasFunction","isScriptable","isIndexable","KNOWN_POSITIONS","positionIsHorizontal","compare2Level","l1","l2","onAnimationsComplete","onComplete","onAnimationProgress","onProgress","getCanvas","getElementById","instances","getChart","c","moveNumericKeys","intKey","determineLastEvent","lastEvent","inChartArea","isClick","Chart","version","invalidatePlugins","userConfig","initialCanvas","existingChart","uid","_options","_aspectRatio","_metasets","_lastEvent","_listeners","_responsiveListeners","_sortedMetasets","_plugins","_hiddenIndices","attached","_doResize","debounce","resizeDelay","_initialize","maintainAspectRatio","responsive","retinaScale","bindEvents","clearCanvas","_resize","_resizeBeforeDraw","newSize","newRatio","onResize","render","ensureScalesHaveIDs","scalesOptions","axisOptions","buildOrUpdateScales","scaleOpts","updated","isRadial","dposition","dtype","scaleType","scaleClass","hasUpdated","_updateMetasets","_destroyDatasetMeta","_removeUnreferencedMetasets","buildOrUpdateControllers","newControllers","order","visible","ControllerClass","_resetElements","animsDisabled","_updateScales","_checkEventBindings","_updateHiddenIndices","_minPadding","autoPadding","_updateLayout","_updateDatasets","_eventHandler","_updateHoverStyles","existingEvents","newEvents","events","setsEqual","unbindEvents","changes","_getUniformDataChanges","datasetCount","makeSet","changeSet","noArea","_idx","_updateDataset","layers","_drawDatasets","_drawDataset","getDatasetClipArea","getElementsAtEventForMode","Interaction","setDatasetVisibility","_updateVisibility","hide","show","_stop","destroy","toBase64Image","toDataURL","bindUserEvents","bindResponsiveEvents","_add","_remove","detached","updateHoverStyle","prefix","getActiveElements","setActiveElements","activeElements","lastActive","_elementsEqual","pluginId","replay","hoverOptions","hover","deactivated","activated","eventFilter","_handleEvent","_getActiveElements","_isClickEvent","onHover","clipSelf","borderJoinStyle","outerAngleClip","_normalizeAngle","innerAngleClip","clipWidth","closePath","rect","clipArc","pixelMargin","angleMargin","toRadiusCorners","_readValueToProps","parseBorderRadius","angleDelta","o","borderRadius","halfThickness","innerLimit","computeOuterLimit","outerArcLimit","outerStart","outerEnd","innerStart","innerEnd","rThetaToXY","theta","pathArc","innerR","spacingOffset","alpha","noSpacingInnerRadius","noSpacingOuterRadius","avNogSpacingRadius","adjustedAngle","beta","angleOffset","outerStartAdjustedRadius","outerEndAdjustedRadius","outerStartAdjustedAngle","outerEndAdjustedAngle","innerStartAdjustedRadius","innerEndAdjustedRadius","innerStartAdjustedAngle","innerEndAdjustedAngle","outerMidAdjustedAngle","pCenter","p4","innerMidAdjustedAngle","p8","outerStartX","outerStartY","outerEndX","outerEndY","drawArc","fullCircles","inner","lineJoin","selfJoin","ArcElement","chartX","chartY","rAdjust","nonZeroBetween","betweenAngles","withinRadius","_isBetween","halfAngle","halfRadius","translate","fix","radiusOffset","setStyle","lineCap","borderCapStyle","previous","getLineMethod","stepped","_steppedLineTo","tension","cubicInterpolationMode","_bezierCurveTo","pathVars","paramsStart","paramsEnd","segmentStart","segmentEnd","outside","pathSegment","lineMethod","fastPathSegment","avgX","countX","prevX","lastY","pointIndex","drawX","truncX","_getSegmentMethod","useFastPath","_getInterpolationMethod","_steppedInterpolation","_bezierInterpolation","_pointInLine","strokePathWithCache","path","_path","Path2D","strokePathDirect","segments","segmentMethod","usePath2D","LineElement","capBezierPoints","_points","_segments","_pointsUpdated","_updateBezierControlPoints","_computeSegments","interpolate","_boundSegments","_interpolate","interpolated","hitRadius","PointElement","hoverRadius","mouseX","mouseY","inXRange","inYRange","drawPoint","getBarBounds","bar","half","skipOrLimit","parseBorderWidth","maxW","maxH","toTRBL","toTRBLCorners","maxR","enableBorder","topLeft","topRight","bottomLeft","bottomRight","boundingRects","bounds","outer","skipX","skipY","skipBoth","hasRadius","addNormalRectPath","inflateRect","amount","refRect","BarElement","addRectPath","addRoundedRectPath","BORDER_COLORS","BACKGROUND_COLORS","replace","getBorderColor","getBackgroundColor","colorizeDefaultDataset","colorizeDoughnutDataset","colorizePolarAreaDataset","getColorizer","containsColorsDefinitions","k","containsColorsDefinition","containsDefaultColorsDefenitions","forceOverride","_args","chartOptions","containsColorDefenition","colorizer","lttbDecimation","samples","decimated","bucketWidth","sampledIndex","endIndex","maxAreaPoint","maxArea","nextA","avgY","avgRangeStart","avgRangeEnd","avgRangeLength","rangeOffs","rangeTo","pointAx","pointAy","minMaxDecimation","minIndex","maxIndex","startIndex","xMin","xMax","dx","lastIndex","intermediateIndex1","intermediateIndex2","cleanDecimatedDataset","defineProperty","configurable","enumerable","writable","cleanDecimatedData","getStartAndCountOfVisiblePointsSimplified","pointCount","algorithm","beforeElementsUpdate","xAxis","threshold","tpoints","_findSegmentEnd","_getBounds","targetSegments","tgt","subBounds","fillSources","_boundSegment","fillSource","_getEdge","_pointsFromSegments","boundary","linePoints","_createBoundaryLine","_shouldApplyFill","_resolveTarget","sources","propagate","visited","_decodeFill","parseFillOption","parseFloat","decodeTargetIndex","firstCh","_getTargetPixel","_getTargetValue","fillOption","_buildStackLine","sourcePoints","linesBelow","getLinesBelow","addPointsBelow","below","unshift","sourcePoint","postponed","findPoint","pointValue","firstValue","lastValue","simpleArc","_getTarget","getLineByIndex","computeBoundary","computeCircularBoundary","computeLinearBoundary","_drawfill","lineOpts","above","doFill","fillColor","clipVertical","clipHorizontal","clipY","lineLoop","clipX","src","notShape","clipBounds","interpolatedLineTo","targetLoop","interpolatedPoint","afterDatasetsUpdate","$filler","beforeDraw","drawTime","beforeDatasetsDraw","beforeDatasetDraw","getBoxSize","labelOpts","boxHeight","boxWidth","usePointStyle","pointStyleWidth","itemHeight","itemsEqual","Legend","_added","legendHitBoxes","_hoveredItem","doughnutMode","legendItems","columnSizes","lineWidths","buildLabels","labelFont","_computeTitleHeight","_fitRows","_fitCols","hitboxes","totalHeight","row","itemWidth","measureText","_itemHeight","heightLimit","totalWidth","currentColWidth","currentColHeight","col","calculateItemSize","adjustHitBoxes","rtl","rtlHelper","getRtlAdapter","hitbox","leftForLtr","_draw","defaultColor","halfFontSize","cursor","drawLegendBox","lineDash","drawOptions","SQRT2","xPlus","drawPointLegend","yBoxTop","xBoxLeft","fillText","strikethrough","overrideTextDirection","textDirection","textWidth","setWidth","realX","_textX","fontLineHeight","calculateLegendItemHeight","restoreTextDirection","titleFont","titlePadding","topPaddingPlusHalfFontSize","_getLegendItemAt","hitBox","lh","handleEvent","isListened","hoveredItem","sameItem","onLeave","calculateItemWidth","calculateItemHeight","legendItemText","_element","afterEvent","ci","useBorderRadius","Title","_padding","textSize","_drawArgs","fontOpts","createTitle","titleBlock","WeakMap","positioners","average","xSet","xAverage","eventPosition","nearestElement","distanceBetweenPoints","tp","pushOrConcat","toPush","apply","splitNewlines","str","String","createTooltipItem","formattedValue","getTooltipSize","tooltip","body","footer","bodyFont","footerFont","titleLineCount","footerLineCount","bodyLineItemCount","combinedBodyLength","bodyItem","before","after","beforeBody","afterBody","titleSpacing","titleMarginBottom","bodyLineHeight","displayColors","bodySpacing","footerMarginTop","footerSpacing","widthPadding","maxLineWidth","determineYAlign","doesNotFitWithAlign","xAlign","caret","caretSize","caretPadding","determineXAlign","yAlign","chartWidth","determineAlignment","alignX","alignY","paddingAndSize","getBackgroundPoint","alignment","cornerRadius","getAlignedX","getBeforeAfterBodyLines","createTooltipContext","tooltipItems","overrideCallbacks","defaultCallbacks","beforeTitle","noop","labelCount","afterTitle","beforeLabel","tooltipItem","labelColor","labelTextColor","bodyColor","labelPointStyle","afterLabel","beforeFooter","afterFooter","invokeCallbackWithFallback","Tooltip","opacity","_eventPosition","_size","_cachedAnimations","_tooltipItems","dataPoints","caretX","caretY","labelColors","labelPointStyles","labelTextColors","getTitle","getBeforeBody","getBody","bodyItems","scoped","getAfterBody","getFooter","_createItems","itemSort","positionAndSize","backgroundPoint","external","drawCaret","tooltipPoint","caretPosition","getCaretPosition","x3","y3","ptX","ptY","pt","titleColor","_drawColorBox","colorX","rtlColorX","yOffSet","colorY","multiKeyBackground","outerX","innerX","strokeRect","drawBody","bodyAlign","xLinePadding","fillLineOfText","bodyAlignForCalculation","textColor","drawFooter","footerAlign","footerColor","tooltipSize","quadraticCurveTo","_updateAnimationTarget","animX","animY","_willRender","hasTooltipContent","globalAlpha","positionChanged","_positionChanged","_ignoreReplayEvents","afterInit","afterDraw","_fallback","addIfString","addedLabels","findOrAddLabel","lastIndexOf","_getLabelForValue","CategoryScale","_startValue","_valueRange","_addedLabels","added","generateTicks","generationOptions","dataRange","MIN_SPACING","precision","maxTicks","maxDigits","includeBounds","unit","maxSpaces","rmin","rmax","countDefined","minSpacing","niceNum","niceMin","niceMax","numSpaces","almostWhole","almostEquals","decimalPlaces","_decimalPlaces","relativeLabelSize","tickValue","rad","LinearScaleBase","_endValue","handleTickRangeOptions","setMin","setMax","minSign","maxSign","getTickLimit","stepSize","computeTickLimit","numericGeneratorOptions","_setMinAndMaxByKey","LinearScale","Ticks","formatters","numeric","log10Floor","log10","changeExponent","m","isMajor","tickVal","steps","rangeExp","rangeStep","startExp","minExp","exp","significand","lastTick","LogarithmicScale","logarithmic","_zero","getTickBackdropHeight","measureLabelSize","_longestText","determineLimits","fitWithPointLabels","limits","valueCount","_pointLabels","pointLabelOpts","additionalAngle","centerPointLabels","getPointLabelContext","getPointPosition","drawingArea","plFont","hLimits","vLimits","updateLimits","setCenterPoint","_pointLabelItems","buildPointLabelItems","createPointLabelItem","itemOpts","outerDistance","extra","pointLabelPosition","yForAngle","getTextAlignForAngle","leftForTextAlign","isNotOverlapped","apexesInArea","drawPointLabelBox","backdropLeft","backdropTop","backdropWidth","backdropHeight","drawPointLabels","pathRadiusLine","drawRadiusLine","gridLineOpts","createPointLabelContext","RadialLinearScale","animate","leftMovement","rightMovement","topMovement","bottomMovement","angleMultiplier","scalingFactor","getValueForDistanceFromCenter","scaledDistance","pointLabel","distanceFromCenter","getBasePosition","getPointLabelPosition","rotate","INTERVALS","millisecond","common","second","minute","hour","day","week","month","quarter","year","UNITS","sorter","input","adapter","_adapter","parser","isoWeekday","_parseOpts","determineUnitForAutoTicks","minUnit","capacity","interval","MAX_SAFE_INTEGER","determineUnitForFormatting","determineMajorUnit","addTick","time","timestamps","_lookup","timestamp","setMajorTicks","majorUnit","ticksFromTimestamps","TimeScale","adapters","displayFormats","_unit","_majorUnit","_offsets","_normalized","normalized","_applyBounds","_getLabelBounds","getLabelTimestamps","timeOpts","_generate","_filterBetween","_getLabelCapacity","initOffsets","offsetAfterAutoskip","getDecimalForValue","minor","weekday","hasWeekday","getDataTimestamps","tooltipFormat","datetime","fmt","_tickFormatFunction","formatter","minorFormat","majorFormat","offsets","_getLabelSize","ticksOpts","tickLabelWidth","cosRotation","sinRotation","tickFontSize","exampleTime","exampleLabel","normalize","table","prevSource","nextSource","prevTarget","nextTarget","span","TimeSeriesScale","_table","_minPos","_tableRange","_getTimestampsForTable","buildLookupTable","registerables"],"mappings":";;;;;;;;;AAWO,MAAMA,QAAAA,CAAAA;IACXC,WAAc,EAAA;QACZ,IAAI,CAACC,QAAQ,GAAG,IAAI,CAAA;QACpB,IAAI,CAACC,OAAO,GAAG,IAAIC,GAAAA,EAAAA,CAAAA;QACnB,IAAI,CAACC,QAAQ,GAAG,KAAK,CAAA;QACrB,IAAI,CAACC,SAAS,GAAGC,SAAAA,CAAAA;AACnB,KAAA;AAKAC,CAAAA,OAAAA,CAAQC,KAAK,EAAEC,KAAK,EAAEC,IAAI,EAAEC,IAAI,EAAE;AAChC,QAAA,MAAMC,SAAYH,GAAAA,KAAAA,CAAMI,SAAS,CAACF,IAAK,CAAA,CAAA;QACvC,MAAMG,QAAAA,GAAWL,MAAMM,QAAQ,CAAA;AAE/BH,QAAAA,SAAAA,CAAUI,OAAO,CAACC,CAAAA,EAAAA,GAAMA,EAAG,CAAA;AACzBT,gBAAAA,KAAAA;AACAU,gBAAAA,OAAAA,EAAST,MAAMS,OAAO;AACtBJ,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;AACrC,QAAA,IAAI54D,IAAKrJ,CAAAA,MAAM,IAAIiT,KAAAA,CAAMjT,MAAM,EAAE;AAG/BihE,YAAAA,UAAAA,GAAa,IAAI,CAAC4C,SAAS,CAACx6D,IAAAA,CAAK8N,MAAM,CAAClE,KAAAA,CAAAA,CAAAA,CAAAA;SACnC,MAAA;AACLguD,YAAAA,UAAAA,GAAa53D,IAAKrJ,CAAAA,MAAM,GAAGqJ,IAAAA,GAAO4J,KAAK,CAAA;SACxC;AACDguD,QAAAA,UAAAA,GAAa,IAAI,CAACjqD,MAAM,CAAClQ,GAAG,GAAGm6D,UAAAA,CAAAA;QAE/B,OAAOA,UAAAA,CAAAA;AACT,KAAA;AAMAuB,CAAAA,kBAAAA,CAAmB/7D,KAAK,EAAE;AACxB,QAAA,OAAO,CAACo4C,WAAY,CAAA,IAAI,CAACwlB,MAAM,EAAE59D,KAAS,CAAA,GAAA,IAAI,CAAC69D,OAAM,IAAK,IAAI,CAACC,WAAW,CAAA;AAC5E,KAAA;AAMA7mD,CAAAA,gBAAAA,CAAiBqjB,KAAK,EAAE;QACtB,MAAMqiC,OAAAA,GAAU,IAAI,CAACxB,QAAQ,CAAA;QAC7B,MAAM5gC,OAAAA,GAAU,IAAI,CAACG,kBAAkB,CAACJ,SAASqiC,OAAQlhE,CAAAA,MAAM,GAAGkhE,OAAAA,CAAQh8D,GAAG,CAAA;AAC7E,QAAA,OAAOy3C,WAAY,CAAA,IAAI,CAACwlB,MAAM,EAAErjC,OAAU,GAAA,IAAI,CAACujC,WAAW,GAAG,IAAI,CAACD,OAAO,EAAE,IAAI,CAAA,CAAA;AACjF,KAAA;AACF;;;;;;;;;;;;MC3JaI,aAAgB,GAAA;AAC3Bv8B,IAAAA,WAAAA;AACA90B,IAAAA,QAAAA;AACA0N,IAAAA,OAAAA;AACAhV,IAAAA,MAAAA;;;;;"} \ No newline at end of file diff --git a/frontend/node_modules/chart.js/dist/chart.umd.js b/frontend/node_modules/chart.js/dist/chart.umd.js new file mode 100644 index 0000000000000000000000000000000000000000..87bf552abc6a161e0aa10d7fa18dee9211ca3668 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/chart.umd.js @@ -0,0 +1,14 @@ +/*! + * Chart.js v4.5.0 + * https://www.chartjs.org + * (c) 2025 Chart.js Contributors + * Released under the MIT License + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Chart=e()}(this,(function(){"use strict";var t=Object.freeze({__proto__:null,get Colors(){return Jo},get Decimation(){return ta},get Filler(){return ba},get Legend(){return Ma},get SubTitle(){return Pa},get Title(){return ka},get Tooltip(){return Na}});function e(){}const i=(()=>{let t=0;return()=>t++})();function s(t){return null==t}function n(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return"[object"===e.slice(0,7)&&"Array]"===e.slice(-6)}function o(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)}function a(t){return("number"==typeof t||t instanceof Number)&&isFinite(+t)}function r(t,e){return a(t)?t:e}function l(t,e){return void 0===t?e:t}const h=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100:+t/e,c=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100*e:+t;function d(t,e,i){if(t&&"function"==typeof t.call)return t.apply(i,e)}function u(t,e,i,s){let a,r,l;if(n(t))if(r=t.length,s)for(a=r-1;a>=0;a--)e.call(i,t[a],a);else for(a=0;at,x:t=>t.x,y:t=>t.y};function v(t){const e=t.split("."),i=[];let s="";for(const t of e)s+=t,s.endsWith("\\")?s=s.slice(0,-1)+".":(i.push(s),s="");return i}function M(t,e){const i=y[e]||(y[e]=function(t){const e=v(t);return t=>{for(const i of e){if(""===i)break;t=t&&t[i]}return t}}(e));return i(t)}function w(t){return t.charAt(0).toUpperCase()+t.slice(1)}const k=t=>void 0!==t,S=t=>"function"==typeof t,P=(t,e)=>{if(t.size!==e.size)return!1;for(const i of t)if(!e.has(i))return!1;return!0};function D(t){return"mouseup"===t.type||"click"===t.type||"contextmenu"===t.type}const C=Math.PI,O=2*C,A=O+C,T=Number.POSITIVE_INFINITY,L=C/180,E=C/2,R=C/4,I=2*C/3,z=Math.log10,F=Math.sign;function V(t,e,i){return Math.abs(t-e)t-e)).pop(),e}function N(t){return!function(t){return"symbol"==typeof t||"object"==typeof t&&null!==t&&!(Symbol.toPrimitive in t||"toString"in t||"valueOf"in t)}(t)&&!isNaN(parseFloat(t))&&isFinite(t)}function H(t,e){const i=Math.round(t);return i-e<=t&&i+e>=t}function j(t,e,i){let s,n,o;for(s=0,n=t.length;sl&&h=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function et(t,e,i){i=i||(i=>t[i]1;)s=o+n>>1,i(s)?o=s:n=s;return{lo:o,hi:n}}const it=(t,e,i,s)=>et(t,i,s?s=>{const n=t[s][e];return nt[s][e]et(t,i,(s=>t[s][e]>=i));function nt(t,e,i){let s=0,n=t.length;for(;ss&&t[n-1]>i;)n--;return s>0||n{const i="_onData"+w(e),s=t[e];Object.defineProperty(t,e,{configurable:!0,enumerable:!1,value(...e){const n=s.apply(this,e);return t._chartjs.listeners.forEach((t=>{"function"==typeof t[i]&&t[i](...e)})),n}})})))}function rt(t,e){const i=t._chartjs;if(!i)return;const s=i.listeners,n=s.indexOf(e);-1!==n&&s.splice(n,1),s.length>0||(ot.forEach((e=>{delete t[e]})),delete t._chartjs)}function lt(t){const e=new Set(t);return e.size===t.length?t:Array.from(e)}const ht="undefined"==typeof window?function(t){return t()}:window.requestAnimationFrame;function ct(t,e){let i=[],s=!1;return function(...n){i=n,s||(s=!0,ht.call(window,(()=>{s=!1,t.apply(e,i)})))}}function dt(t,e){let i;return function(...s){return e?(clearTimeout(i),i=setTimeout(t,e,s)):t.apply(this,s),e}}const ut=t=>"start"===t?"left":"end"===t?"right":"center",ft=(t,e,i)=>"start"===t?e:"end"===t?i:(e+i)/2,gt=(t,e,i,s)=>t===(s?"left":"right")?i:"center"===t?(e+i)/2:e;function pt(t,e,i){const n=e.length;let o=0,a=n;if(t._sorted){const{iScale:r,vScale:l,_parsed:h}=t,c=t.dataset&&t.dataset.options?t.dataset.options.spanGaps:null,d=r.axis,{min:u,max:f,minDefined:g,maxDefined:p}=r.getUserBounds();if(g){if(o=Math.min(it(h,d,u).lo,i?n:it(e,d,r.getPixelForValue(u)).lo),c){const t=h.slice(0,o+1).reverse().findIndex((t=>!s(t[l.axis])));o-=Math.max(0,t)}o=Z(o,0,n-1)}if(p){let t=Math.max(it(h,r.axis,f,!0).hi+1,i?0:it(e,d,r.getPixelForValue(f),!0).hi+1);if(c){const e=h.slice(t-1).findIndex((t=>!s(t[l.axis])));t+=Math.max(0,e)}a=Z(t,o,n)-o}else a=n-o}return{start:o,count:a}}function mt(t){const{xScale:e,yScale:i,_scaleRanges:s}=t,n={xmin:e.min,xmax:e.max,ymin:i.min,ymax:i.max};if(!s)return t._scaleRanges=n,!0;const o=s.xmin!==e.min||s.xmax!==e.max||s.ymin!==i.min||s.ymax!==i.max;return Object.assign(s,n),o}class xt{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(t,e,i,s){const n=e.listeners[s],o=e.duration;n.forEach((s=>s({chart:t,initial:e.initial,numSteps:o,currentStep:Math.min(i-e.start,o)})))}_refresh(){this._request||(this._running=!0,this._request=ht.call(window,(()=>{this._update(),this._request=null,this._running&&this._refresh()})))}_update(t=Date.now()){let e=0;this._charts.forEach(((i,s)=>{if(!i.running||!i.items.length)return;const n=i.items;let o,a=n.length-1,r=!1;for(;a>=0;--a)o=n[a],o._active?(o._total>i.duration&&(i.duration=o._total),o.tick(t),r=!0):(n[a]=n[n.length-1],n.pop());r&&(s.draw(),this._notify(s,i,t,"progress")),n.length||(i.running=!1,this._notify(s,i,t,"complete"),i.initial=!1),e+=n.length})),this._lastDate=t,0===e&&(this._running=!1)}_getAnims(t){const e=this._charts;let i=e.get(t);return i||(i={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},e.set(t,i)),i}listen(t,e,i){this._getAnims(t).listeners[e].push(i)}add(t,e){e&&e.length&&this._getAnims(t).items.push(...e)}has(t){return this._getAnims(t).items.length>0}start(t){const e=this._charts.get(t);e&&(e.running=!0,e.start=Date.now(),e.duration=e.items.reduce(((t,e)=>Math.max(t,e._duration)),0),this._refresh())}running(t){if(!this._running)return!1;const e=this._charts.get(t);return!!(e&&e.running&&e.items.length)}stop(t){const e=this._charts.get(t);if(!e||!e.items.length)return;const i=e.items;let s=i.length-1;for(;s>=0;--s)i[s].cancel();e.items=[],this._notify(t,e,Date.now(),"complete")}remove(t){return this._charts.delete(t)}}var bt=new xt; +/*! + * @kurkle/color v0.3.2 + * https://github.com/kurkle/color#readme + * (c) 2023 Jukka Kurkela + * Released under the MIT License + */function _t(t){return t+.5|0}const yt=(t,e,i)=>Math.max(Math.min(t,i),e);function vt(t){return yt(_t(2.55*t),0,255)}function Mt(t){return yt(_t(255*t),0,255)}function wt(t){return yt(_t(t/2.55)/100,0,1)}function kt(t){return yt(_t(100*t),0,100)}const St={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},Pt=[..."0123456789ABCDEF"],Dt=t=>Pt[15&t],Ct=t=>Pt[(240&t)>>4]+Pt[15&t],Ot=t=>(240&t)>>4==(15&t);function At(t){var e=(t=>Ot(t.r)&&Ot(t.g)&&Ot(t.b)&&Ot(t.a))(t)?Dt:Ct;return t?"#"+e(t.r)+e(t.g)+e(t.b)+((t,e)=>t<255?e(t):"")(t.a,e):void 0}const Tt=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function Lt(t,e,i){const s=e*Math.min(i,1-i),n=(e,n=(e+t/30)%12)=>i-s*Math.max(Math.min(n-3,9-n,1),-1);return[n(0),n(8),n(4)]}function Et(t,e,i){const s=(s,n=(s+t/60)%6)=>i-i*e*Math.max(Math.min(n,4-n,1),0);return[s(5),s(3),s(1)]}function Rt(t,e,i){const s=Lt(t,1,.5);let n;for(e+i>1&&(n=1/(e+i),e*=n,i*=n),n=0;n<3;n++)s[n]*=1-e-i,s[n]+=e;return s}function It(t){const e=t.r/255,i=t.g/255,s=t.b/255,n=Math.max(e,i,s),o=Math.min(e,i,s),a=(n+o)/2;let r,l,h;return n!==o&&(h=n-o,l=a>.5?h/(2-n-o):h/(n+o),r=function(t,e,i,s,n){return t===n?(e-i)/s+(e>16&255,o>>8&255,255&o]}return t}(),Ht.transparent=[0,0,0,0]);const e=Ht[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:4===e.length?e[3]:255}}const $t=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;const Yt=t=>t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,Ut=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function Xt(t,e,i){if(t){let s=It(t);s[e]=Math.max(0,Math.min(s[e]+s[e]*i,0===e?360:1)),s=Ft(s),t.r=s[0],t.g=s[1],t.b=s[2]}}function qt(t,e){return t?Object.assign(e||{},t):t}function Kt(t){var e={r:0,g:0,b:0,a:255};return Array.isArray(t)?t.length>=3&&(e={r:t[0],g:t[1],b:t[2],a:255},t.length>3&&(e.a=Mt(t[3]))):(e=qt(t,{r:0,g:0,b:0,a:1})).a=Mt(e.a),e}function Gt(t){return"r"===t.charAt(0)?function(t){const e=$t.exec(t);let i,s,n,o=255;if(e){if(e[7]!==i){const t=+e[7];o=e[8]?vt(t):yt(255*t,0,255)}return i=+e[1],s=+e[3],n=+e[5],i=255&(e[2]?vt(i):yt(i,0,255)),s=255&(e[4]?vt(s):yt(s,0,255)),n=255&(e[6]?vt(n):yt(n,0,255)),{r:i,g:s,b:n,a:o}}}(t):Bt(t)}class Jt{constructor(t){if(t instanceof Jt)return t;const e=typeof t;let i;var s,n,o;"object"===e?i=Kt(t):"string"===e&&(o=(s=t).length,"#"===s[0]&&(4===o||5===o?n={r:255&17*St[s[1]],g:255&17*St[s[2]],b:255&17*St[s[3]],a:5===o?17*St[s[4]]:255}:7!==o&&9!==o||(n={r:St[s[1]]<<4|St[s[2]],g:St[s[3]]<<4|St[s[4]],b:St[s[5]]<<4|St[s[6]],a:9===o?St[s[7]]<<4|St[s[8]]:255})),i=n||jt(t)||Gt(t)),this._rgb=i,this._valid=!!i}get valid(){return this._valid}get rgb(){var t=qt(this._rgb);return t&&(t.a=wt(t.a)),t}set rgb(t){this._rgb=Kt(t)}rgbString(){return this._valid?(t=this._rgb)&&(t.a<255?`rgba(${t.r}, ${t.g}, ${t.b}, ${wt(t.a)})`:`rgb(${t.r}, ${t.g}, ${t.b})`):void 0;var t}hexString(){return this._valid?At(this._rgb):void 0}hslString(){return this._valid?function(t){if(!t)return;const e=It(t),i=e[0],s=kt(e[1]),n=kt(e[2]);return t.a<255?`hsla(${i}, ${s}%, ${n}%, ${wt(t.a)})`:`hsl(${i}, ${s}%, ${n}%)`}(this._rgb):void 0}mix(t,e){if(t){const i=this.rgb,s=t.rgb;let n;const o=e===n?.5:e,a=2*o-1,r=i.a-s.a,l=((a*r==-1?a:(a+r)/(1+a*r))+1)/2;n=1-l,i.r=255&l*i.r+n*s.r+.5,i.g=255&l*i.g+n*s.g+.5,i.b=255&l*i.b+n*s.b+.5,i.a=o*i.a+(1-o)*s.a,this.rgb=i}return this}interpolate(t,e){return t&&(this._rgb=function(t,e,i){const s=Ut(wt(t.r)),n=Ut(wt(t.g)),o=Ut(wt(t.b));return{r:Mt(Yt(s+i*(Ut(wt(e.r))-s))),g:Mt(Yt(n+i*(Ut(wt(e.g))-n))),b:Mt(Yt(o+i*(Ut(wt(e.b))-o))),a:t.a+i*(e.a-t.a)}}(this._rgb,t._rgb,e)),this}clone(){return new Jt(this.rgb)}alpha(t){return this._rgb.a=Mt(t),this}clearer(t){return this._rgb.a*=1-t,this}greyscale(){const t=this._rgb,e=_t(.3*t.r+.59*t.g+.11*t.b);return t.r=t.g=t.b=e,this}opaquer(t){return this._rgb.a*=1+t,this}negate(){const t=this._rgb;return t.r=255-t.r,t.g=255-t.g,t.b=255-t.b,this}lighten(t){return Xt(this._rgb,2,t),this}darken(t){return Xt(this._rgb,2,-t),this}saturate(t){return Xt(this._rgb,1,t),this}desaturate(t){return Xt(this._rgb,1,-t),this}rotate(t){return function(t,e){var i=It(t);i[0]=Vt(i[0]+e),i=Ft(i),t.r=i[0],t.g=i[1],t.b=i[2]}(this._rgb,t),this}}function Zt(t){if(t&&"object"==typeof t){const e=t.toString();return"[object CanvasPattern]"===e||"[object CanvasGradient]"===e}return!1}function Qt(t){return Zt(t)?t:new Jt(t)}function te(t){return Zt(t)?t:new Jt(t).saturate(.5).darken(.1).hexString()}const ee=["x","y","borderWidth","radius","tension"],ie=["color","borderColor","backgroundColor"];const se=new Map;function ne(t,e,i){return function(t,e){e=e||{};const i=t+JSON.stringify(e);let s=se.get(i);return s||(s=new Intl.NumberFormat(t,e),se.set(i,s)),s}(e,i).format(t)}const oe={values:t=>n(t)?t:""+t,numeric(t,e,i){if(0===t)return"0";const s=this.chart.options.locale;let n,o=t;if(i.length>1){const e=Math.max(Math.abs(i[0].value),Math.abs(i[i.length-1].value));(e<1e-4||e>1e15)&&(n="scientific"),o=function(t,e){let i=e.length>3?e[2].value-e[1].value:e[1].value-e[0].value;Math.abs(i)>=1&&t!==Math.floor(t)&&(i=t-Math.floor(t));return i}(t,i)}const a=z(Math.abs(o)),r=isNaN(a)?1:Math.max(Math.min(-1*Math.floor(a),20),0),l={notation:n,minimumFractionDigits:r,maximumFractionDigits:r};return Object.assign(l,this.options.ticks.format),ne(t,s,l)},logarithmic(t,e,i){if(0===t)return"0";const s=i[e].significand||t/Math.pow(10,Math.floor(z(t)));return[1,2,3,5,10,15].includes(s)||e>.8*i.length?oe.numeric.call(this,t,e,i):""}};var ae={formatters:oe};const re=Object.create(null),le=Object.create(null);function he(t,e){if(!e)return t;const i=e.split(".");for(let e=0,s=i.length;et.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(t,e)=>te(e.backgroundColor),this.hoverBorderColor=(t,e)=>te(e.borderColor),this.hoverColor=(t,e)=>te(e.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(t),this.apply(e)}set(t,e){return ce(this,t,e)}get(t){return he(this,t)}describe(t,e){return ce(le,t,e)}override(t,e){return ce(re,t,e)}route(t,e,i,s){const n=he(this,t),a=he(this,i),r="_"+e;Object.defineProperties(n,{[r]:{value:n[e],writable:!0},[e]:{enumerable:!0,get(){const t=this[r],e=a[s];return o(t)?Object.assign({},e,t):l(t,e)},set(t){this[r]=t}}})}apply(t){t.forEach((t=>t(this)))}}var ue=new de({_scriptable:t=>!t.startsWith("on"),_indexable:t=>"events"!==t,hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[function(t){t.set("animation",{delay:void 0,duration:1e3,easing:"easeOutQuart",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),t.describe("animation",{_fallback:!1,_indexable:!1,_scriptable:t=>"onProgress"!==t&&"onComplete"!==t&&"fn"!==t}),t.set("animations",{colors:{type:"color",properties:ie},numbers:{type:"number",properties:ee}}),t.describe("animations",{_fallback:"animation"}),t.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:t=>0|t}}}})},function(t){t.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})},function(t){t.set("scale",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:"ticks",clip:!0,grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(t,e)=>e.lineWidth,tickColor:(t,e)=>e.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:ae.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),t.route("scale.ticks","color","","color"),t.route("scale.grid","color","","borderColor"),t.route("scale.border","color","","borderColor"),t.route("scale.title","color","","color"),t.describe("scale",{_fallback:!1,_scriptable:t=>!t.startsWith("before")&&!t.startsWith("after")&&"callback"!==t&&"parser"!==t,_indexable:t=>"borderDash"!==t&&"tickBorderDash"!==t&&"dash"!==t}),t.describe("scales",{_fallback:"scale"}),t.describe("scale.ticks",{_scriptable:t=>"backdropPadding"!==t&&"callback"!==t,_indexable:t=>"backdropPadding"!==t})}]);function fe(){return"undefined"!=typeof window&&"undefined"!=typeof document}function ge(t){let e=t.parentNode;return e&&"[object ShadowRoot]"===e.toString()&&(e=e.host),e}function pe(t,e,i){let s;return"string"==typeof t?(s=parseInt(t,10),-1!==t.indexOf("%")&&(s=s/100*e.parentNode[i])):s=t,s}const me=t=>t.ownerDocument.defaultView.getComputedStyle(t,null);function xe(t,e){return me(t).getPropertyValue(e)}const be=["top","right","bottom","left"];function _e(t,e,i){const s={};i=i?"-"+i:"";for(let n=0;n<4;n++){const o=be[n];s[o]=parseFloat(t[e+"-"+o+i])||0}return s.width=s.left+s.right,s.height=s.top+s.bottom,s}const ye=(t,e,i)=>(t>0||e>0)&&(!i||!i.shadowRoot);function ve(t,e){if("native"in t)return t;const{canvas:i,currentDevicePixelRatio:s}=e,n=me(i),o="border-box"===n.boxSizing,a=_e(n,"padding"),r=_e(n,"border","width"),{x:l,y:h,box:c}=function(t,e){const i=t.touches,s=i&&i.length?i[0]:t,{offsetX:n,offsetY:o}=s;let a,r,l=!1;if(ye(n,o,t.target))a=n,r=o;else{const t=e.getBoundingClientRect();a=s.clientX-t.left,r=s.clientY-t.top,l=!0}return{x:a,y:r,box:l}}(t,i),d=a.left+(c&&r.left),u=a.top+(c&&r.top);let{width:f,height:g}=e;return o&&(f-=a.width+r.width,g-=a.height+r.height),{x:Math.round((l-d)/f*i.width/s),y:Math.round((h-u)/g*i.height/s)}}const Me=t=>Math.round(10*t)/10;function we(t,e,i,s){const n=me(t),o=_e(n,"margin"),a=pe(n.maxWidth,t,"clientWidth")||T,r=pe(n.maxHeight,t,"clientHeight")||T,l=function(t,e,i){let s,n;if(void 0===e||void 0===i){const o=t&&ge(t);if(o){const t=o.getBoundingClientRect(),a=me(o),r=_e(a,"border","width"),l=_e(a,"padding");e=t.width-l.width-r.width,i=t.height-l.height-r.height,s=pe(a.maxWidth,o,"clientWidth"),n=pe(a.maxHeight,o,"clientHeight")}else e=t.clientWidth,i=t.clientHeight}return{width:e,height:i,maxWidth:s||T,maxHeight:n||T}}(t,e,i);let{width:h,height:c}=l;if("content-box"===n.boxSizing){const t=_e(n,"border","width"),e=_e(n,"padding");h-=e.width+t.width,c-=e.height+t.height}h=Math.max(0,h-o.width),c=Math.max(0,s?h/s:c-o.height),h=Me(Math.min(h,a,l.maxWidth)),c=Me(Math.min(c,r,l.maxHeight)),h&&!c&&(c=Me(h/2));return(void 0!==e||void 0!==i)&&s&&l.height&&c>l.height&&(c=l.height,h=Me(Math.floor(c*s))),{width:h,height:c}}function ke(t,e,i){const s=e||1,n=Math.floor(t.height*s),o=Math.floor(t.width*s);t.height=Math.floor(t.height),t.width=Math.floor(t.width);const a=t.canvas;return a.style&&(i||!a.style.height&&!a.style.width)&&(a.style.height=`${t.height}px`,a.style.width=`${t.width}px`),(t.currentDevicePixelRatio!==s||a.height!==n||a.width!==o)&&(t.currentDevicePixelRatio=s,a.height=n,a.width=o,t.ctx.setTransform(s,0,0,s,0,0),!0)}const Se=function(){let t=!1;try{const e={get passive(){return t=!0,!1}};fe()&&(window.addEventListener("test",null,e),window.removeEventListener("test",null,e))}catch(t){}return t}();function Pe(t,e){const i=xe(t,e),s=i&&i.match(/^(\d+)(\.\d+)?px$/);return s?+s[1]:void 0}function De(t){return!t||s(t.size)||s(t.family)?null:(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family}function Ce(t,e,i,s,n){let o=e[n];return o||(o=e[n]=t.measureText(n).width,i.push(n)),o>s&&(s=o),s}function Oe(t,e,i,s){let o=(s=s||{}).data=s.data||{},a=s.garbageCollect=s.garbageCollect||[];s.font!==e&&(o=s.data={},a=s.garbageCollect=[],s.font=e),t.save(),t.font=e;let r=0;const l=i.length;let h,c,d,u,f;for(h=0;hi.length){for(h=0;h0&&t.stroke()}}function Re(t,e,i){return i=i||.5,!e||t&&t.x>e.left-i&&t.xe.top-i&&t.y0&&""!==r.strokeColor;let c,d;for(t.save(),t.font=a.string,function(t,e){e.translation&&t.translate(e.translation[0],e.translation[1]),s(e.rotation)||t.rotate(e.rotation),e.color&&(t.fillStyle=e.color),e.textAlign&&(t.textAlign=e.textAlign),e.textBaseline&&(t.textBaseline=e.textBaseline)}(t,r),c=0;ct[0])){const o=i||t;void 0===s&&(s=ti("_fallback",t));const a={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:t,_rootScopes:o,_fallback:s,_getTarget:n,override:i=>je([i,...t],e,o,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete e._keys,delete t[0][i],!0),get:(i,s)=>qe(i,s,(()=>function(t,e,i,s){let n;for(const o of e)if(n=ti(Ue(o,t),i),void 0!==n)return Xe(t,n)?Ze(i,s,t,n):n}(s,e,t,i))),getOwnPropertyDescriptor:(t,e)=>Reflect.getOwnPropertyDescriptor(t._scopes[0],e),getPrototypeOf:()=>Reflect.getPrototypeOf(t[0]),has:(t,e)=>ei(t).includes(e),ownKeys:t=>ei(t),set(t,e,i){const s=t._storage||(t._storage=n());return t[e]=s[e]=i,delete t._keys,!0}})}function $e(t,e,i,s){const a={_cacheable:!1,_proxy:t,_context:e,_subProxy:i,_stack:new Set,_descriptors:Ye(t,s),setContext:e=>$e(t,e,i,s),override:n=>$e(t.override(n),e,i,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete t[i],!0),get:(t,e,i)=>qe(t,e,(()=>function(t,e,i){const{_proxy:s,_context:a,_subProxy:r,_descriptors:l}=t;let h=s[e];S(h)&&l.isScriptable(e)&&(h=function(t,e,i,s){const{_proxy:n,_context:o,_subProxy:a,_stack:r}=i;if(r.has(t))throw new Error("Recursion detected: "+Array.from(r).join("->")+"->"+t);r.add(t);let l=e(o,a||s);r.delete(t),Xe(t,l)&&(l=Ze(n._scopes,n,t,l));return l}(e,h,t,i));n(h)&&h.length&&(h=function(t,e,i,s){const{_proxy:n,_context:a,_subProxy:r,_descriptors:l}=i;if(void 0!==a.index&&s(t))return e[a.index%e.length];if(o(e[0])){const i=e,s=n._scopes.filter((t=>t!==i));e=[];for(const o of i){const i=Ze(s,n,t,o);e.push($e(i,a,r&&r[t],l))}}return e}(e,h,t,l.isIndexable));Xe(e,h)&&(h=$e(h,a,r&&r[e],l));return h}(t,e,i))),getOwnPropertyDescriptor:(e,i)=>e._descriptors.allKeys?Reflect.has(t,i)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(t,i),getPrototypeOf:()=>Reflect.getPrototypeOf(t),has:(e,i)=>Reflect.has(t,i),ownKeys:()=>Reflect.ownKeys(t),set:(e,i,s)=>(t[i]=s,delete e[i],!0)})}function Ye(t,e={scriptable:!0,indexable:!0}){const{_scriptable:i=e.scriptable,_indexable:s=e.indexable,_allKeys:n=e.allKeys}=t;return{allKeys:n,scriptable:i,indexable:s,isScriptable:S(i)?i:()=>i,isIndexable:S(s)?s:()=>s}}const Ue=(t,e)=>t?t+w(e):e,Xe=(t,e)=>o(e)&&"adapters"!==t&&(null===Object.getPrototypeOf(e)||e.constructor===Object);function qe(t,e,i){if(Object.prototype.hasOwnProperty.call(t,e)||"constructor"===e)return t[e];const s=i();return t[e]=s,s}function Ke(t,e,i){return S(t)?t(e,i):t}const Ge=(t,e)=>!0===t?e:"string"==typeof t?M(e,t):void 0;function Je(t,e,i,s,n){for(const o of e){const e=Ge(i,o);if(e){t.add(e);const o=Ke(e._fallback,i,n);if(void 0!==o&&o!==i&&o!==s)return o}else if(!1===e&&void 0!==s&&i!==s)return null}return!1}function Ze(t,e,i,s){const a=e._rootScopes,r=Ke(e._fallback,i,s),l=[...t,...a],h=new Set;h.add(s);let c=Qe(h,l,i,r||i,s);return null!==c&&((void 0===r||r===i||(c=Qe(h,l,r,c,s),null!==c))&&je(Array.from(h),[""],a,r,(()=>function(t,e,i){const s=t._getTarget();e in s||(s[e]={});const a=s[e];if(n(a)&&o(i))return i;return a||{}}(e,i,s))))}function Qe(t,e,i,s,n){for(;i;)i=Je(t,e,i,s,n);return i}function ti(t,e){for(const i of e){if(!i)continue;const e=i[t];if(void 0!==e)return e}}function ei(t){let e=t._keys;return e||(e=t._keys=function(t){const e=new Set;for(const i of t)for(const t of Object.keys(i).filter((t=>!t.startsWith("_"))))e.add(t);return Array.from(e)}(t._scopes)),e}function ii(t,e,i,s){const{iScale:n}=t,{key:o="r"}=this._parsing,a=new Array(s);let r,l,h,c;for(r=0,l=s;re"x"===t?"y":"x";function ai(t,e,i,s){const n=t.skip?e:t,o=e,a=i.skip?e:i,r=q(o,n),l=q(a,o);let h=r/(r+l),c=l/(r+l);h=isNaN(h)?0:h,c=isNaN(c)?0:c;const d=s*h,u=s*c;return{previous:{x:o.x-d*(a.x-n.x),y:o.y-d*(a.y-n.y)},next:{x:o.x+u*(a.x-n.x),y:o.y+u*(a.y-n.y)}}}function ri(t,e="x"){const i=oi(e),s=t.length,n=Array(s).fill(0),o=Array(s);let a,r,l,h=ni(t,0);for(a=0;a!t.skip))),"monotone"===e.cubicInterpolationMode)ri(t,n);else{let i=s?t[t.length-1]:t[0];for(o=0,a=t.length;o0===t||1===t,di=(t,e,i)=>-Math.pow(2,10*(t-=1))*Math.sin((t-e)*O/i),ui=(t,e,i)=>Math.pow(2,-10*t)*Math.sin((t-e)*O/i)+1,fi={linear:t=>t,easeInQuad:t=>t*t,easeOutQuad:t=>-t*(t-2),easeInOutQuad:t=>(t/=.5)<1?.5*t*t:-.5*(--t*(t-2)-1),easeInCubic:t=>t*t*t,easeOutCubic:t=>(t-=1)*t*t+1,easeInOutCubic:t=>(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2),easeInQuart:t=>t*t*t*t,easeOutQuart:t=>-((t-=1)*t*t*t-1),easeInOutQuart:t=>(t/=.5)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2),easeInQuint:t=>t*t*t*t*t,easeOutQuint:t=>(t-=1)*t*t*t*t+1,easeInOutQuint:t=>(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2),easeInSine:t=>1-Math.cos(t*E),easeOutSine:t=>Math.sin(t*E),easeInOutSine:t=>-.5*(Math.cos(C*t)-1),easeInExpo:t=>0===t?0:Math.pow(2,10*(t-1)),easeOutExpo:t=>1===t?1:1-Math.pow(2,-10*t),easeInOutExpo:t=>ci(t)?t:t<.5?.5*Math.pow(2,10*(2*t-1)):.5*(2-Math.pow(2,-10*(2*t-1))),easeInCirc:t=>t>=1?t:-(Math.sqrt(1-t*t)-1),easeOutCirc:t=>Math.sqrt(1-(t-=1)*t),easeInOutCirc:t=>(t/=.5)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1),easeInElastic:t=>ci(t)?t:di(t,.075,.3),easeOutElastic:t=>ci(t)?t:ui(t,.075,.3),easeInOutElastic(t){const e=.1125;return ci(t)?t:t<.5?.5*di(2*t,e,.45):.5+.5*ui(2*t-1,e,.45)},easeInBack(t){const e=1.70158;return t*t*((e+1)*t-e)},easeOutBack(t){const e=1.70158;return(t-=1)*t*((e+1)*t+e)+1},easeInOutBack(t){let e=1.70158;return(t/=.5)<1?t*t*((1+(e*=1.525))*t-e)*.5:.5*((t-=2)*t*((1+(e*=1.525))*t+e)+2)},easeInBounce:t=>1-fi.easeOutBounce(1-t),easeOutBounce(t){const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375},easeInOutBounce:t=>t<.5?.5*fi.easeInBounce(2*t):.5*fi.easeOutBounce(2*t-1)+.5};function gi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:t.y+i*(e.y-t.y)}}function pi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:"middle"===s?i<.5?t.y:e.y:"after"===s?i<1?t.y:e.y:i>0?e.y:t.y}}function mi(t,e,i,s){const n={x:t.cp2x,y:t.cp2y},o={x:e.cp1x,y:e.cp1y},a=gi(t,n,i),r=gi(n,o,i),l=gi(o,e,i),h=gi(a,r,i),c=gi(r,l,i);return gi(h,c,i)}const xi=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,bi=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;function _i(t,e){const i=(""+t).match(xi);if(!i||"normal"===i[1])return 1.2*e;switch(t=+i[2],i[3]){case"px":return t;case"%":t/=100}return e*t}const yi=t=>+t||0;function vi(t,e){const i={},s=o(e),n=s?Object.keys(e):e,a=o(t)?s?i=>l(t[i],t[e[i]]):e=>t[e]:()=>t;for(const t of n)i[t]=yi(a(t));return i}function Mi(t){return vi(t,{top:"y",right:"x",bottom:"y",left:"x"})}function wi(t){return vi(t,["topLeft","topRight","bottomLeft","bottomRight"])}function ki(t){const e=Mi(t);return e.width=e.left+e.right,e.height=e.top+e.bottom,e}function Si(t,e){t=t||{},e=e||ue.font;let i=l(t.size,e.size);"string"==typeof i&&(i=parseInt(i,10));let s=l(t.style,e.style);s&&!(""+s).match(bi)&&(console.warn('Invalid font style specified: "'+s+'"'),s=void 0);const n={family:l(t.family,e.family),lineHeight:_i(l(t.lineHeight,e.lineHeight),i),size:i,style:s,weight:l(t.weight,e.weight),string:""};return n.string=De(n),n}function Pi(t,e,i,s){let o,a,r,l=!0;for(o=0,a=t.length;oi&&0===t?0:t+e;return{min:a(s,-Math.abs(o)),max:a(n,o)}}function Ci(t,e){return Object.assign(Object.create(t),e)}function Oi(t,e,i){return t?function(t,e){return{x:i=>t+t+e-i,setWidth(t){e=t},textAlign:t=>"center"===t?t:"right"===t?"left":"right",xPlus:(t,e)=>t-e,leftForLtr:(t,e)=>t-e}}(e,i):{x:t=>t,setWidth(t){},textAlign:t=>t,xPlus:(t,e)=>t+e,leftForLtr:(t,e)=>t}}function Ai(t,e){let i,s;"ltr"!==e&&"rtl"!==e||(i=t.canvas.style,s=[i.getPropertyValue("direction"),i.getPropertyPriority("direction")],i.setProperty("direction",e,"important"),t.prevTextDirection=s)}function Ti(t,e){void 0!==e&&(delete t.prevTextDirection,t.canvas.style.setProperty("direction",e[0],e[1]))}function Li(t){return"angle"===t?{between:J,compare:K,normalize:G}:{between:tt,compare:(t,e)=>t-e,normalize:t=>t}}function Ei({start:t,end:e,count:i,loop:s,style:n}){return{start:t%i,end:e%i,loop:s&&(e-t+1)%i==0,style:n}}function Ri(t,e,i){if(!i)return[t];const{property:s,start:n,end:o}=i,a=e.length,{compare:r,between:l,normalize:h}=Li(s),{start:c,end:d,loop:u,style:f}=function(t,e,i){const{property:s,start:n,end:o}=i,{between:a,normalize:r}=Li(s),l=e.length;let h,c,{start:d,end:u,loop:f}=t;if(f){for(d+=l,u+=l,h=0,c=l;hb||l(n,x,p)&&0!==r(n,x),v=()=>!b||0===r(o,p)||l(o,x,p);for(let t=c,i=c;t<=d;++t)m=e[t%a],m.skip||(p=h(m[s]),p!==x&&(b=l(p,n,o),null===_&&y()&&(_=0===r(p,n)?t:i),null!==_&&v()&&(g.push(Ei({start:_,end:t,loop:u,count:a,style:f})),_=null),i=t,x=p));return null!==_&&g.push(Ei({start:_,end:d,loop:u,count:a,style:f})),g}function Ii(t,e){const i=[],s=t.segments;for(let n=0;nn&&t[o%e].skip;)o--;return o%=e,{start:n,end:o}}(i,n,o,s);if(!0===s)return Fi(t,[{start:a,end:r,loop:o}],i,e);return Fi(t,function(t,e,i,s){const n=t.length,o=[];let a,r=e,l=t[e];for(a=e+1;a<=i;++a){const i=t[a%n];i.skip||i.stop?l.skip||(s=!1,o.push({start:e%n,end:(a-1)%n,loop:s}),e=r=i.stop?a:null):(r=a,l.skip&&(e=a)),l=i}return null!==r&&o.push({start:e%n,end:r%n,loop:s}),o}(i,a,r!s(t[e.axis])));n.lo-=Math.max(0,a);const r=i.slice(n.hi).findIndex((t=>!s(t[e.axis])));n.hi+=Math.max(0,r)}return n}if(o._sharedOptions){const t=a[0],s="function"==typeof t.getRange&&t.getRange(e);if(s){const t=r(a,e,i-s),n=r(a,e,i+s);return{lo:t.lo,hi:n.hi}}}}return{lo:0,hi:a.length-1}}function $i(t,e,i,s,n){const o=t.getSortedVisibleDatasetMetas(),a=i[e];for(let t=0,i=o.length;t{t[a]&&t[a](e[i],n)&&(o.push({element:t,datasetIndex:s,index:l}),r=r||t.inRange(e.x,e.y,n))})),s&&!r?[]:o}var Ki={evaluateInteractionItems:$i,modes:{index(t,e,i,s){const n=ve(e,t),o=i.axis||"x",a=i.includeInvisible||!1,r=i.intersect?Yi(t,n,o,s,a):Xi(t,n,o,!1,s,a),l=[];return r.length?(t.getSortedVisibleDatasetMetas().forEach((t=>{const e=r[0].index,i=t.data[e];i&&!i.skip&&l.push({element:i,datasetIndex:t.index,index:e})})),l):[]},dataset(t,e,i,s){const n=ve(e,t),o=i.axis||"xy",a=i.includeInvisible||!1;let r=i.intersect?Yi(t,n,o,s,a):Xi(t,n,o,!1,s,a);if(r.length>0){const e=r[0].datasetIndex,i=t.getDatasetMeta(e).data;r=[];for(let t=0;tYi(t,ve(e,t),i.axis||"xy",s,i.includeInvisible||!1),nearest(t,e,i,s){const n=ve(e,t),o=i.axis||"xy",a=i.includeInvisible||!1;return Xi(t,n,o,i.intersect,s,a)},x:(t,e,i,s)=>qi(t,ve(e,t),"x",i.intersect,s),y:(t,e,i,s)=>qi(t,ve(e,t),"y",i.intersect,s)}};const Gi=["left","top","right","bottom"];function Ji(t,e){return t.filter((t=>t.pos===e))}function Zi(t,e){return t.filter((t=>-1===Gi.indexOf(t.pos)&&t.box.axis===e))}function Qi(t,e){return t.sort(((t,i)=>{const s=e?i:t,n=e?t:i;return s.weight===n.weight?s.index-n.index:s.weight-n.weight}))}function ts(t,e){const i=function(t){const e={};for(const i of t){const{stack:t,pos:s,stackWeight:n}=i;if(!t||!Gi.includes(s))continue;const o=e[t]||(e[t]={count:0,placed:0,weight:0,size:0});o.count++,o.weight+=n}return e}(t),{vBoxMaxWidth:s,hBoxMaxHeight:n}=e;let o,a,r;for(o=0,a=t.length;o{s[t]=Math.max(e[t],i[t])})),s}return s(t?["left","right"]:["top","bottom"])}function os(t,e,i,s){const n=[];let o,a,r,l,h,c;for(o=0,a=t.length,h=0;ot.box.fullSize)),!0),s=Qi(Ji(e,"left"),!0),n=Qi(Ji(e,"right")),o=Qi(Ji(e,"top"),!0),a=Qi(Ji(e,"bottom")),r=Zi(e,"x"),l=Zi(e,"y");return{fullSize:i,leftAndTop:s.concat(o),rightAndBottom:n.concat(l).concat(a).concat(r),chartArea:Ji(e,"chartArea"),vertical:s.concat(n).concat(l),horizontal:o.concat(a).concat(r)}}(t.boxes),l=r.vertical,h=r.horizontal;u(t.boxes,(t=>{"function"==typeof t.beforeLayout&&t.beforeLayout()}));const c=l.reduce(((t,e)=>e.box.options&&!1===e.box.options.display?t:t+1),0)||1,d=Object.freeze({outerWidth:e,outerHeight:i,padding:n,availableWidth:o,availableHeight:a,vBoxMaxWidth:o/2/c,hBoxMaxHeight:a/2}),f=Object.assign({},n);is(f,ki(s));const g=Object.assign({maxPadding:f,w:o,h:a,x:n.left,y:n.top},n),p=ts(l.concat(h),d);os(r.fullSize,g,d,p),os(l,g,d,p),os(h,g,d,p)&&os(l,g,d,p),function(t){const e=t.maxPadding;function i(i){const s=Math.max(e[i]-t[i],0);return t[i]+=s,s}t.y+=i("top"),t.x+=i("left"),i("right"),i("bottom")}(g),rs(r.leftAndTop,g,d,p),g.x+=g.w,g.y+=g.h,rs(r.rightAndBottom,g,d,p),t.chartArea={left:g.left,top:g.top,right:g.left+g.w,bottom:g.top+g.h,height:g.h,width:g.w},u(r.chartArea,(e=>{const i=e.box;Object.assign(i,t.chartArea),i.update(g.w,g.h,{left:0,top:0,right:0,bottom:0})}))}};class hs{acquireContext(t,e){}releaseContext(t){return!1}addEventListener(t,e,i){}removeEventListener(t,e,i){}getDevicePixelRatio(){return 1}getMaximumSize(t,e,i,s){return e=Math.max(0,e||t.width),i=i||t.height,{width:e,height:Math.max(0,s?Math.floor(e/s):i)}}isAttached(t){return!0}updateConfig(t){}}class cs extends hs{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}}const ds="$chartjs",us={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},fs=t=>null===t||""===t;const gs=!!Se&&{passive:!0};function ps(t,e,i){t&&t.canvas&&t.canvas.removeEventListener(e,i,gs)}function ms(t,e){for(const i of t)if(i===e||i.contains(e))return!0}function xs(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||ms(i.addedNodes,s),e=e&&!ms(i.removedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}function bs(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||ms(i.removedNodes,s),e=e&&!ms(i.addedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}const _s=new Map;let ys=0;function vs(){const t=window.devicePixelRatio;t!==ys&&(ys=t,_s.forEach(((e,i)=>{i.currentDevicePixelRatio!==t&&e()})))}function Ms(t,e,i){const s=t.canvas,n=s&&ge(s);if(!n)return;const o=ct(((t,e)=>{const s=n.clientWidth;i(t,e),s{const e=t[0],i=e.contentRect.width,s=e.contentRect.height;0===i&&0===s||o(i,s)}));return a.observe(n),function(t,e){_s.size||window.addEventListener("resize",vs),_s.set(t,e)}(t,o),a}function ws(t,e,i){i&&i.disconnect(),"resize"===e&&function(t){_s.delete(t),_s.size||window.removeEventListener("resize",vs)}(t)}function ks(t,e,i){const s=t.canvas,n=ct((e=>{null!==t.ctx&&i(function(t,e){const i=us[t.type]||t.type,{x:s,y:n}=ve(t,e);return{type:i,chart:e,native:t,x:void 0!==s?s:null,y:void 0!==n?n:null}}(e,t))}),t);return function(t,e,i){t&&t.addEventListener(e,i,gs)}(s,e,n),n}class Ss extends hs{acquireContext(t,e){const i=t&&t.getContext&&t.getContext("2d");return i&&i.canvas===t?(function(t,e){const i=t.style,s=t.getAttribute("height"),n=t.getAttribute("width");if(t[ds]={initial:{height:s,width:n,style:{display:i.display,height:i.height,width:i.width}}},i.display=i.display||"block",i.boxSizing=i.boxSizing||"border-box",fs(n)){const e=Pe(t,"width");void 0!==e&&(t.width=e)}if(fs(s))if(""===t.style.height)t.height=t.width/(e||2);else{const e=Pe(t,"height");void 0!==e&&(t.height=e)}}(t,e),i):null}releaseContext(t){const e=t.canvas;if(!e[ds])return!1;const i=e[ds].initial;["height","width"].forEach((t=>{const n=i[t];s(n)?e.removeAttribute(t):e.setAttribute(t,n)}));const n=i.style||{};return Object.keys(n).forEach((t=>{e.style[t]=n[t]})),e.width=e.width,delete e[ds],!0}addEventListener(t,e,i){this.removeEventListener(t,e);const s=t.$proxies||(t.$proxies={}),n={attach:xs,detach:bs,resize:Ms}[e]||ks;s[e]=n(t,e,i)}removeEventListener(t,e){const i=t.$proxies||(t.$proxies={}),s=i[e];if(!s)return;({attach:ws,detach:ws,resize:ws}[e]||ps)(t,e,s),i[e]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,i,s){return we(t,e,i,s)}isAttached(t){const e=t&&ge(t);return!(!e||!e.isConnected)}}function Ps(t){return!fe()||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas?cs:Ss}var Ds=Object.freeze({__proto__:null,BasePlatform:hs,BasicPlatform:cs,DomPlatform:Ss,_detectPlatform:Ps});const Cs="transparent",Os={boolean:(t,e,i)=>i>.5?e:t,color(t,e,i){const s=Qt(t||Cs),n=s.valid&&Qt(e||Cs);return n&&n.valid?n.mix(s,i).hexString():e},number:(t,e,i)=>t+(e-t)*i};class As{constructor(t,e,i,s){const n=e[i];s=Pi([t.to,s,n,t.from]);const o=Pi([t.from,n,s]);this._active=!0,this._fn=t.fn||Os[t.type||typeof o],this._easing=fi[t.easing]||fi.linear,this._start=Math.floor(Date.now()+(t.delay||0)),this._duration=this._total=Math.floor(t.duration),this._loop=!!t.loop,this._target=e,this._prop=i,this._from=o,this._to=s,this._promises=void 0}active(){return this._active}update(t,e,i){if(this._active){this._notify(!1);const s=this._target[this._prop],n=i-this._start,o=this._duration-n;this._start=i,this._duration=Math.floor(Math.max(o,t.duration)),this._total+=n,this._loop=!!t.loop,this._to=Pi([t.to,e,s,t.from]),this._from=Pi([t.from,s,e])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){const e=t-this._start,i=this._duration,s=this._prop,n=this._from,o=this._loop,a=this._to;let r;if(this._active=n!==a&&(o||e1?2-r:r,r=this._easing(Math.min(1,Math.max(0,r))),this._target[s]=this._fn(n,a,r))}wait(){const t=this._promises||(this._promises=[]);return new Promise(((e,i)=>{t.push({res:e,rej:i})}))}_notify(t){const e=t?"res":"rej",i=this._promises||[];for(let t=0;t{const a=t[s];if(!o(a))return;const r={};for(const t of e)r[t]=a[t];(n(a.properties)&&a.properties||[s]).forEach((t=>{t!==s&&i.has(t)||i.set(t,r)}))}))}_animateOptions(t,e){const i=e.options,s=function(t,e){if(!e)return;let i=t.options;if(!i)return void(t.options=e);i.$shared&&(t.options=i=Object.assign({},i,{$shared:!1,$animations:{}}));return i}(t,i);if(!s)return[];const n=this._createAnimations(s,i);return i.$shared&&function(t,e){const i=[],s=Object.keys(e);for(let e=0;e{t.options=i}),(()=>{})),n}_createAnimations(t,e){const i=this._properties,s=[],n=t.$animations||(t.$animations={}),o=Object.keys(e),a=Date.now();let r;for(r=o.length-1;r>=0;--r){const l=o[r];if("$"===l.charAt(0))continue;if("options"===l){s.push(...this._animateOptions(t,e));continue}const h=e[l];let c=n[l];const d=i.get(l);if(c){if(d&&c.active()){c.update(d,h,a);continue}c.cancel()}d&&d.duration?(n[l]=c=new As(d,t,l,h),s.push(c)):t[l]=h}return s}update(t,e){if(0===this._properties.size)return void Object.assign(t,e);const i=this._createAnimations(t,e);return i.length?(bt.add(this._chart,i),!0):void 0}}function Ls(t,e){const i=t&&t.options||{},s=i.reverse,n=void 0===i.min?e:0,o=void 0===i.max?e:0;return{start:s?o:n,end:s?n:o}}function Es(t,e){const i=[],s=t._getSortedDatasetMetas(e);let n,o;for(n=0,o=s.length;n0||!i&&e<0)return n.index}return null}function Vs(t,e){const{chart:i,_cachedMeta:s}=t,n=i._stacks||(i._stacks={}),{iScale:o,vScale:a,index:r}=s,l=o.axis,h=a.axis,c=function(t,e,i){return`${t.id}.${e.id}.${i.stack||i.type}`}(o,a,s),d=e.length;let u;for(let t=0;ti[t].axis===e)).shift()}function Ws(t,e){const i=t.controller.index,s=t.vScale&&t.vScale.axis;if(s){e=e||t._parsed;for(const t of e){const e=t._stacks;if(!e||void 0===e[s]||void 0===e[s][i])return;delete e[s][i],void 0!==e[s]._visualValues&&void 0!==e[s]._visualValues[i]&&delete e[s]._visualValues[i]}}}const Ns=t=>"reset"===t||"none"===t,Hs=(t,e)=>e?t:Object.assign({},t);class js{static defaults={};static datasetElementType=null;static dataElementType=null;constructor(t,e){this.chart=t,this._ctx=t.ctx,this.index=e,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const t=this._cachedMeta;this.configure(),this.linkScales(),t._stacked=Is(t.vScale,t),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(t){this.index!==t&&Ws(this._cachedMeta),this.index=t}linkScales(){const t=this.chart,e=this._cachedMeta,i=this.getDataset(),s=(t,e,i,s)=>"x"===t?e:"r"===t?s:i,n=e.xAxisID=l(i.xAxisID,Bs(t,"x")),o=e.yAxisID=l(i.yAxisID,Bs(t,"y")),a=e.rAxisID=l(i.rAxisID,Bs(t,"r")),r=e.indexAxis,h=e.iAxisID=s(r,n,o,a),c=e.vAxisID=s(r,o,n,a);e.xScale=this.getScaleForId(n),e.yScale=this.getScaleForId(o),e.rScale=this.getScaleForId(a),e.iScale=this.getScaleForId(h),e.vScale=this.getScaleForId(c)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(t){return this.chart.scales[t]}_getOtherScale(t){const e=this._cachedMeta;return t===e.iScale?e.vScale:e.iScale}reset(){this._update("reset")}_destroy(){const t=this._cachedMeta;this._data&&rt(this._data,this),t._stacked&&Ws(t)}_dataCheck(){const t=this.getDataset(),e=t.data||(t.data=[]),i=this._data;if(o(e)){const t=this._cachedMeta;this._data=function(t,e){const{iScale:i,vScale:s}=e,n="x"===i.axis?"x":"y",o="x"===s.axis?"x":"y",a=Object.keys(t),r=new Array(a.length);let l,h,c;for(l=0,h=a.length;l0&&i._parsed[t-1];if(!1===this._parsing)i._parsed=s,i._sorted=!0,d=s;else{d=n(s[t])?this.parseArrayData(i,s,t,e):o(s[t])?this.parseObjectData(i,s,t,e):this.parsePrimitiveData(i,s,t,e);const a=()=>null===c[l]||f&&c[l]t&&!e.hidden&&e._stacked&&{keys:Es(i,!0),values:null})(e,i,this.chart),h={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:c,max:d}=function(t){const{min:e,max:i,minDefined:s,maxDefined:n}=t.getUserBounds();return{min:s?e:Number.NEGATIVE_INFINITY,max:n?i:Number.POSITIVE_INFINITY}}(r);let u,f;function g(){f=s[u];const e=f[r.axis];return!a(f[t.axis])||c>e||d=0;--u)if(!g()){this.updateRangeFromParsed(h,t,f,l);break}return h}getAllParsedValues(t){const e=this._cachedMeta._parsed,i=[];let s,n,o;for(s=0,n=e.length;s=0&&tthis.getContext(i,s,e)),c);return f.$shared&&(f.$shared=r,n[o]=Object.freeze(Hs(f,r))),f}_resolveAnimations(t,e,i){const s=this.chart,n=this._cachedDataOpts,o=`animation-${e}`,a=n[o];if(a)return a;let r;if(!1!==s.options.animation){const s=this.chart.config,n=s.datasetAnimationScopeKeys(this._type,e),o=s.getOptionScopes(this.getDataset(),n);r=s.createResolver(o,this.getContext(t,i,e))}const l=new Ts(s,r&&r.animations);return r&&r._cacheable&&(n[o]=Object.freeze(l)),l}getSharedOptions(t){if(t.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},t))}includeOptions(t,e){return!e||Ns(t)||this.chart._animationsDisabled}_getSharedOptions(t,e){const i=this.resolveDataElementOptions(t,e),s=this._sharedOptions,n=this.getSharedOptions(i),o=this.includeOptions(e,n)||n!==s;return this.updateSharedOptions(n,e,i),{sharedOptions:n,includeOptions:o}}updateElement(t,e,i,s){Ns(s)?Object.assign(t,i):this._resolveAnimations(e,s).update(t,i)}updateSharedOptions(t,e,i){t&&!Ns(e)&&this._resolveAnimations(void 0,e).update(t,i)}_setStyle(t,e,i,s){t.active=s;const n=this.getStyle(e,s);this._resolveAnimations(e,i,s).update(t,{options:!s&&this.getSharedOptions(n)||n})}removeHoverStyle(t,e,i){this._setStyle(t,i,"active",!1)}setHoverStyle(t,e,i){this._setStyle(t,i,"active",!0)}_removeDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!1)}_setDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!0)}_resyncElements(t){const e=this._data,i=this._cachedMeta.data;for(const[t,e,i]of this._syncList)this[t](e,i);this._syncList=[];const s=i.length,n=e.length,o=Math.min(n,s);o&&this.parse(0,o),n>s?this._insertElements(s,n-s,t):n{for(t.length+=e,a=t.length-1;a>=o;a--)t[a]=t[a-e]};for(r(n),a=t;a{s[t]=i[t]&&i[t].active()?i[t]._to:this[t]})),s}}function Ys(t,e){const i=t.options.ticks,n=function(t){const e=t.options.offset,i=t._tickSize(),s=t._length/i+(e?0:1),n=t._maxLength/i;return Math.floor(Math.min(s,n))}(t),o=Math.min(i.maxTicksLimit||n,n),a=i.major.enabled?function(t){const e=[];let i,s;for(i=0,s=t.length;io)return function(t,e,i,s){let n,o=0,a=i[0];for(s=Math.ceil(s),n=0;nn)return e}return Math.max(n,1)}(a,e,o);if(r>0){let t,i;const n=r>1?Math.round((h-l)/(r-1)):null;for(Us(e,c,d,s(n)?0:l-n,l),t=0,i=r-1;t"top"===e||"left"===e?t[e]+i:t[e]-i,qs=(t,e)=>Math.min(e||t,t);function Ks(t,e){const i=[],s=t.length/e,n=t.length;let o=0;for(;oa+r)))return h}function Js(t){return t.drawTicks?t.tickLength:0}function Zs(t,e){if(!t.display)return 0;const i=Si(t.font,e),s=ki(t.padding);return(n(t.text)?t.text.length:1)*i.lineHeight+s.height}function Qs(t,e,i){let s=ut(t);return(i&&"right"!==e||!i&&"right"===e)&&(s=(t=>"left"===t?"right":"right"===t?"left":t)(s)),s}class tn extends $s{constructor(t){super(),this.id=t.id,this.type=t.type,this.options=void 0,this.ctx=t.ctx,this.chart=t.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(t){this.options=t.setContext(this.getContext()),this.axis=t.axis,this._userMin=this.parse(t.min),this._userMax=this.parse(t.max),this._suggestedMin=this.parse(t.suggestedMin),this._suggestedMax=this.parse(t.suggestedMax)}parse(t,e){return t}getUserBounds(){let{_userMin:t,_userMax:e,_suggestedMin:i,_suggestedMax:s}=this;return t=r(t,Number.POSITIVE_INFINITY),e=r(e,Number.NEGATIVE_INFINITY),i=r(i,Number.POSITIVE_INFINITY),s=r(s,Number.NEGATIVE_INFINITY),{min:r(t,i),max:r(e,s),minDefined:a(t),maxDefined:a(e)}}getMinMax(t){let e,{min:i,max:s,minDefined:n,maxDefined:o}=this.getUserBounds();if(n&&o)return{min:i,max:s};const a=this.getMatchingVisibleMetas();for(let r=0,l=a.length;rs?s:i,s=n&&i>s?i:s,{min:r(i,r(s,i)),max:r(s,r(i,s))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]}getLabelItems(t=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(t))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){d(this.options.beforeUpdate,[this])}update(t,e,i){const{beginAtZero:s,grace:n,ticks:o}=this.options,a=o.sampleSize;this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this._margins=i=Object.assign({left:0,right:0,top:0,bottom:0},i),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+i.left+i.right:this.height+i.top+i.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=Di(this,n,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const r=a=n||i<=1||!this.isHorizontal())return void(this.labelRotation=s);const h=this._getLabelSizes(),c=h.widest.width,d=h.highest.height,u=Z(this.chart.width-c,0,this.maxWidth);o=t.offset?this.maxWidth/i:u/(i-1),c+6>o&&(o=u/(i-(t.offset?.5:1)),a=this.maxHeight-Js(t.grid)-e.padding-Zs(t.title,this.chart.options.font),r=Math.sqrt(c*c+d*d),l=Y(Math.min(Math.asin(Z((h.highest.height+6)/o,-1,1)),Math.asin(Z(a/r,-1,1))-Math.asin(Z(d/r,-1,1)))),l=Math.max(s,Math.min(n,l))),this.labelRotation=l}afterCalculateLabelRotation(){d(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){d(this.options.beforeFit,[this])}fit(){const t={width:0,height:0},{chart:e,options:{ticks:i,title:s,grid:n}}=this,o=this._isVisible(),a=this.isHorizontal();if(o){const o=Zs(s,e.options.font);if(a?(t.width=this.maxWidth,t.height=Js(n)+o):(t.height=this.maxHeight,t.width=Js(n)+o),i.display&&this.ticks.length){const{first:e,last:s,widest:n,highest:o}=this._getLabelSizes(),r=2*i.padding,l=$(this.labelRotation),h=Math.cos(l),c=Math.sin(l);if(a){const e=i.mirror?0:c*n.width+h*o.height;t.height=Math.min(this.maxHeight,t.height+e+r)}else{const e=i.mirror?0:h*n.width+c*o.height;t.width=Math.min(this.maxWidth,t.width+e+r)}this._calculatePadding(e,s,c,h)}}this._handleMargins(),a?(this.width=this._length=e.width-this._margins.left-this._margins.right,this.height=t.height):(this.width=t.width,this.height=this._length=e.height-this._margins.top-this._margins.bottom)}_calculatePadding(t,e,i,s){const{ticks:{align:n,padding:o},position:a}=this.options,r=0!==this.labelRotation,l="top"!==a&&"x"===this.axis;if(this.isHorizontal()){const a=this.getPixelForTick(0)-this.left,h=this.right-this.getPixelForTick(this.ticks.length-1);let c=0,d=0;r?l?(c=s*t.width,d=i*e.height):(c=i*t.height,d=s*e.width):"start"===n?d=e.width:"end"===n?c=t.width:"inner"!==n&&(c=t.width/2,d=e.width/2),this.paddingLeft=Math.max((c-a+o)*this.width/(this.width-a),0),this.paddingRight=Math.max((d-h+o)*this.width/(this.width-h),0)}else{let i=e.height/2,s=t.height/2;"start"===n?(i=0,s=t.height):"end"===n&&(i=e.height,s=0),this.paddingTop=i+o,this.paddingBottom=s+o}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){d(this.options.afterFit,[this])}isHorizontal(){const{axis:t,position:e}=this.options;return"top"===e||"bottom"===e||"x"===t}isFullSize(){return this.options.fullSize}_convertTicksToLabels(t){let e,i;for(this.beforeTickToLabelConversion(),this.generateTickLabels(t),e=0,i=t.length;e{const i=t.gc,s=i.length/2;let n;if(s>e){for(n=0;n({width:r[t]||0,height:l[t]||0});return{first:P(0),last:P(e-1),widest:P(k),highest:P(S),widths:r,heights:l}}getLabelForValue(t){return t}getPixelForValue(t,e){return NaN}getValueForPixel(t){}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getPixelForDecimal(t){this._reversePixels&&(t=1-t);const e=this._startPixel+t*this._length;return Q(this._alignToPixels?Ae(this.chart,e,0):e)}getDecimalForPixel(t){const e=(t-this._startPixel)/this._length;return this._reversePixels?1-e:e}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:t,max:e}=this;return t<0&&e<0?e:t>0&&e>0?t:0}getContext(t){const e=this.ticks||[];if(t>=0&&ta*s?a/i:r/s:r*s0}_computeGridLineItems(t){const e=this.axis,i=this.chart,s=this.options,{grid:n,position:a,border:r}=s,h=n.offset,c=this.isHorizontal(),d=this.ticks.length+(h?1:0),u=Js(n),f=[],g=r.setContext(this.getContext()),p=g.display?g.width:0,m=p/2,x=function(t){return Ae(i,t,p)};let b,_,y,v,M,w,k,S,P,D,C,O;if("top"===a)b=x(this.bottom),w=this.bottom-u,S=b-m,D=x(t.top)+m,O=t.bottom;else if("bottom"===a)b=x(this.top),D=t.top,O=x(t.bottom)-m,w=b+m,S=this.top+u;else if("left"===a)b=x(this.right),M=this.right-u,k=b-m,P=x(t.left)+m,C=t.right;else if("right"===a)b=x(this.left),P=t.left,C=x(t.right)-m,M=b+m,k=this.left+u;else if("x"===e){if("center"===a)b=x((t.top+t.bottom)/2+.5);else if(o(a)){const t=Object.keys(a)[0],e=a[t];b=x(this.chart.scales[t].getPixelForValue(e))}D=t.top,O=t.bottom,w=b+m,S=w+u}else if("y"===e){if("center"===a)b=x((t.left+t.right)/2);else if(o(a)){const t=Object.keys(a)[0],e=a[t];b=x(this.chart.scales[t].getPixelForValue(e))}M=b-m,k=M-u,P=t.left,C=t.right}const A=l(s.ticks.maxTicksLimit,d),T=Math.max(1,Math.ceil(d/A));for(_=0;_0&&(o-=s/2)}d={left:o,top:n,width:s+e.width,height:i+e.height,color:t.backdropColor}}x.push({label:v,font:P,textOffset:O,options:{rotation:m,color:i,strokeColor:o,strokeWidth:h,textAlign:f,textBaseline:A,translation:[M,w],backdrop:d}})}return x}_getXAxisLabelAlignment(){const{position:t,ticks:e}=this.options;if(-$(this.labelRotation))return"top"===t?"left":"right";let i="center";return"start"===e.align?i="left":"end"===e.align?i="right":"inner"===e.align&&(i="inner"),i}_getYAxisLabelAlignment(t){const{position:e,ticks:{crossAlign:i,mirror:s,padding:n}}=this.options,o=t+n,a=this._getLabelSizes().widest.width;let r,l;return"left"===e?s?(l=this.right+n,"near"===i?r="left":"center"===i?(r="center",l+=a/2):(r="right",l+=a)):(l=this.right-o,"near"===i?r="right":"center"===i?(r="center",l-=a/2):(r="left",l=this.left)):"right"===e?s?(l=this.left+n,"near"===i?r="right":"center"===i?(r="center",l-=a/2):(r="left",l-=a)):(l=this.left+o,"near"===i?r="left":"center"===i?(r="center",l+=a/2):(r="right",l=this.right)):r="right",{textAlign:r,x:l}}_computeLabelArea(){if(this.options.ticks.mirror)return;const t=this.chart,e=this.options.position;return"left"===e||"right"===e?{top:0,left:this.left,bottom:t.height,right:this.right}:"top"===e||"bottom"===e?{top:this.top,left:0,bottom:this.bottom,right:t.width}:void 0}drawBackground(){const{ctx:t,options:{backgroundColor:e},left:i,top:s,width:n,height:o}=this;e&&(t.save(),t.fillStyle=e,t.fillRect(i,s,n,o),t.restore())}getLineWidthForValue(t){const e=this.options.grid;if(!this._isVisible()||!e.display)return 0;const i=this.ticks.findIndex((e=>e.value===t));if(i>=0){return e.setContext(this.getContext(i)).lineWidth}return 0}drawGrid(t){const e=this.options.grid,i=this.ctx,s=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t));let n,o;const a=(t,e,s)=>{s.width&&s.color&&(i.save(),i.lineWidth=s.width,i.strokeStyle=s.color,i.setLineDash(s.borderDash||[]),i.lineDashOffset=s.borderDashOffset,i.beginPath(),i.moveTo(t.x,t.y),i.lineTo(e.x,e.y),i.stroke(),i.restore())};if(e.display)for(n=0,o=s.length;n{this.drawBackground(),this.drawGrid(t),this.drawTitle()}},{z:s,draw:()=>{this.drawBorder()}},{z:e,draw:t=>{this.drawLabels(t)}}]:[{z:e,draw:t=>{this.draw(t)}}]}getMatchingVisibleMetas(t){const e=this.chart.getSortedVisibleDatasetMetas(),i=this.axis+"AxisID",s=[];let n,o;for(n=0,o=e.length;n{const s=i.split("."),n=s.pop(),o=[t].concat(s).join("."),a=e[i].split("."),r=a.pop(),l=a.join(".");ue.route(o,n,l,r)}))}(e,t.defaultRoutes);t.descriptors&&ue.describe(e,t.descriptors)}(t,o,i),this.override&&ue.override(t.id,t.overrides)),o}get(t){return this.items[t]}unregister(t){const e=this.items,i=t.id,s=this.scope;i in e&&delete e[i],s&&i in ue[s]&&(delete ue[s][i],this.override&&delete re[i])}}class sn{constructor(){this.controllers=new en(js,"datasets",!0),this.elements=new en($s,"elements"),this.plugins=new en(Object,"plugins"),this.scales=new en(tn,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...t){this._each("register",t)}remove(...t){this._each("unregister",t)}addControllers(...t){this._each("register",t,this.controllers)}addElements(...t){this._each("register",t,this.elements)}addPlugins(...t){this._each("register",t,this.plugins)}addScales(...t){this._each("register",t,this.scales)}getController(t){return this._get(t,this.controllers,"controller")}getElement(t){return this._get(t,this.elements,"element")}getPlugin(t){return this._get(t,this.plugins,"plugin")}getScale(t){return this._get(t,this.scales,"scale")}removeControllers(...t){this._each("unregister",t,this.controllers)}removeElements(...t){this._each("unregister",t,this.elements)}removePlugins(...t){this._each("unregister",t,this.plugins)}removeScales(...t){this._each("unregister",t,this.scales)}_each(t,e,i){[...e].forEach((e=>{const s=i||this._getRegistryForType(e);i||s.isForType(e)||s===this.plugins&&e.id?this._exec(t,s,e):u(e,(e=>{const s=i||this._getRegistryForType(e);this._exec(t,s,e)}))}))}_exec(t,e,i){const s=w(t);d(i["before"+s],[],i),e[t](i),d(i["after"+s],[],i)}_getRegistryForType(t){for(let e=0;et.filter((t=>!e.some((e=>t.plugin.id===e.plugin.id))));this._notify(s(e,i),t,"stop"),this._notify(s(i,e),t,"start")}}function an(t,e){return e||!1!==t?!0===t?{}:t:null}function rn(t,{plugin:e,local:i},s,n){const o=t.pluginScopeKeys(e),a=t.getOptionScopes(s,o);return i&&e.defaults&&a.push(e.defaults),t.createResolver(a,n,[""],{scriptable:!1,indexable:!1,allKeys:!0})}function ln(t,e){const i=ue.datasets[t]||{};return((e.datasets||{})[t]||{}).indexAxis||e.indexAxis||i.indexAxis||"x"}function hn(t){if("x"===t||"y"===t||"r"===t)return t}function cn(t,...e){if(hn(t))return t;for(const s of e){const e=s.axis||("top"===(i=s.position)||"bottom"===i?"x":"left"===i||"right"===i?"y":void 0)||t.length>1&&hn(t[0].toLowerCase());if(e)return e}var i;throw new Error(`Cannot determine type of '${t}' axis. Please provide 'axis' or 'position' option.`)}function dn(t,e,i){if(i[e+"AxisID"]===t)return{axis:e}}function un(t,e){const i=re[t.type]||{scales:{}},s=e.scales||{},n=ln(t.type,e),a=Object.create(null);return Object.keys(s).forEach((e=>{const r=s[e];if(!o(r))return console.error(`Invalid scale configuration for scale: ${e}`);if(r._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${e}`);const l=cn(e,r,function(t,e){if(e.data&&e.data.datasets){const i=e.data.datasets.filter((e=>e.xAxisID===t||e.yAxisID===t));if(i.length)return dn(t,"x",i[0])||dn(t,"y",i[0])}return{}}(e,t),ue.scales[r.type]),h=function(t,e){return t===e?"_index_":"_value_"}(l,n),c=i.scales||{};a[e]=b(Object.create(null),[{axis:l},r,c[l],c[h]])})),t.data.datasets.forEach((i=>{const n=i.type||t.type,o=i.indexAxis||ln(n,e),r=(re[n]||{}).scales||{};Object.keys(r).forEach((t=>{const e=function(t,e){let i=t;return"_index_"===t?i=e:"_value_"===t&&(i="x"===e?"y":"x"),i}(t,o),n=i[e+"AxisID"]||e;a[n]=a[n]||Object.create(null),b(a[n],[{axis:e},s[n],r[t]])}))})),Object.keys(a).forEach((t=>{const e=a[t];b(e,[ue.scales[e.type],ue.scale])})),a}function fn(t){const e=t.options||(t.options={});e.plugins=l(e.plugins,{}),e.scales=un(t,e)}function gn(t){return(t=t||{}).datasets=t.datasets||[],t.labels=t.labels||[],t}const pn=new Map,mn=new Set;function xn(t,e){let i=pn.get(t);return i||(i=e(),pn.set(t,i),mn.add(i)),i}const bn=(t,e,i)=>{const s=M(e,i);void 0!==s&&t.add(s)};class _n{constructor(t){this._config=function(t){return(t=t||{}).data=gn(t.data),fn(t),t}(t),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(t){this._config.type=t}get data(){return this._config.data}set data(t){this._config.data=gn(t)}get options(){return this._config.options}set options(t){this._config.options=t}get plugins(){return this._config.plugins}update(){const t=this._config;this.clearCache(),fn(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return xn(t,(()=>[[`datasets.${t}`,""]]))}datasetAnimationScopeKeys(t,e){return xn(`${t}.transition.${e}`,(()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,""]]))}datasetElementScopeKeys(t,e){return xn(`${t}-${e}`,(()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,""]]))}pluginScopeKeys(t){const e=t.id;return xn(`${this.type}-plugin-${e}`,(()=>[[`plugins.${e}`,...t.additionalOptionScopes||[]]]))}_cachedScopes(t,e){const i=this._scopeCache;let s=i.get(t);return s&&!e||(s=new Map,i.set(t,s)),s}getOptionScopes(t,e,i){const{options:s,type:n}=this,o=this._cachedScopes(t,i),a=o.get(e);if(a)return a;const r=new Set;e.forEach((e=>{t&&(r.add(t),e.forEach((e=>bn(r,t,e)))),e.forEach((t=>bn(r,s,t))),e.forEach((t=>bn(r,re[n]||{},t))),e.forEach((t=>bn(r,ue,t))),e.forEach((t=>bn(r,le,t)))}));const l=Array.from(r);return 0===l.length&&l.push(Object.create(null)),mn.has(e)&&o.set(e,l),l}chartOptionScopes(){const{options:t,type:e}=this;return[t,re[e]||{},ue.datasets[e]||{},{type:e},ue,le]}resolveNamedOptions(t,e,i,s=[""]){const o={$shared:!0},{resolver:a,subPrefixes:r}=yn(this._resolverCache,t,s);let l=a;if(function(t,e){const{isScriptable:i,isIndexable:s}=Ye(t);for(const o of e){const e=i(o),a=s(o),r=(a||e)&&t[o];if(e&&(S(r)||vn(r))||a&&n(r))return!0}return!1}(a,e)){o.$shared=!1;l=$e(a,i=S(i)?i():i,this.createResolver(t,i,r))}for(const t of e)o[t]=l[t];return o}createResolver(t,e,i=[""],s){const{resolver:n}=yn(this._resolverCache,t,i);return o(e)?$e(n,e,void 0,s):n}}function yn(t,e,i){let s=t.get(e);s||(s=new Map,t.set(e,s));const n=i.join();let o=s.get(n);if(!o){o={resolver:je(e,i),subPrefixes:i.filter((t=>!t.toLowerCase().includes("hover")))},s.set(n,o)}return o}const vn=t=>o(t)&&Object.getOwnPropertyNames(t).some((e=>S(t[e])));const Mn=["top","bottom","left","right","chartArea"];function wn(t,e){return"top"===t||"bottom"===t||-1===Mn.indexOf(t)&&"x"===e}function kn(t,e){return function(i,s){return i[t]===s[t]?i[e]-s[e]:i[t]-s[t]}}function Sn(t){const e=t.chart,i=e.options.animation;e.notifyPlugins("afterRender"),d(i&&i.onComplete,[t],e)}function Pn(t){const e=t.chart,i=e.options.animation;d(i&&i.onProgress,[t],e)}function Dn(t){return fe()&&"string"==typeof t?t=document.getElementById(t):t&&t.length&&(t=t[0]),t&&t.canvas&&(t=t.canvas),t}const Cn={},On=t=>{const e=Dn(t);return Object.values(Cn).filter((t=>t.canvas===e)).pop()};function An(t,e,i){const s=Object.keys(t);for(const n of s){const s=+n;if(s>=e){const o=t[n];delete t[n],(i>0||s>e)&&(t[s+i]=o)}}}class Tn{static defaults=ue;static instances=Cn;static overrides=re;static registry=nn;static version="4.5.0";static getChart=On;static register(...t){nn.add(...t),Ln()}static unregister(...t){nn.remove(...t),Ln()}constructor(t,e){const s=this.config=new _n(e),n=Dn(t),o=On(n);if(o)throw new Error("Canvas is already in use. Chart with ID '"+o.id+"' must be destroyed before the canvas with ID '"+o.canvas.id+"' can be reused.");const a=s.createResolver(s.chartOptionScopes(),this.getContext());this.platform=new(s.platform||Ps(n)),this.platform.updateConfig(s);const r=this.platform.acquireContext(n,a.aspectRatio),l=r&&r.canvas,h=l&&l.height,c=l&&l.width;this.id=i(),this.ctx=r,this.canvas=l,this.width=c,this.height=h,this._options=a,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new on,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=dt((t=>this.update(t)),a.resizeDelay||0),this._dataChanges=[],Cn[this.id]=this,r&&l?(bt.listen(this,"complete",Sn),bt.listen(this,"progress",Pn),this._initialize(),this.attached&&this.update()):console.error("Failed to create chart: can't acquire context from the given item")}get aspectRatio(){const{options:{aspectRatio:t,maintainAspectRatio:e},width:i,height:n,_aspectRatio:o}=this;return s(t)?e&&o?o:n?i/n:null:t}get data(){return this.config.data}set data(t){this.config.data=t}get options(){return this._options}set options(t){this.config.options=t}get registry(){return nn}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():ke(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return Te(this.canvas,this.ctx),this}stop(){return bt.stop(this),this}resize(t,e){bt.running(this)?this._resizeBeforeDraw={width:t,height:e}:this._resize(t,e)}_resize(t,e){const i=this.options,s=this.canvas,n=i.maintainAspectRatio&&this.aspectRatio,o=this.platform.getMaximumSize(s,t,e,n),a=i.devicePixelRatio||this.platform.getDevicePixelRatio(),r=this.width?"resize":"attach";this.width=o.width,this.height=o.height,this._aspectRatio=this.aspectRatio,ke(this,a,!0)&&(this.notifyPlugins("resize",{size:o}),d(i.onResize,[this,o],this),this.attached&&this._doResize(r)&&this.render())}ensureScalesHaveIDs(){u(this.options.scales||{},((t,e)=>{t.id=e}))}buildOrUpdateScales(){const t=this.options,e=t.scales,i=this.scales,s=Object.keys(i).reduce(((t,e)=>(t[e]=!1,t)),{});let n=[];e&&(n=n.concat(Object.keys(e).map((t=>{const i=e[t],s=cn(t,i),n="r"===s,o="x"===s;return{options:i,dposition:n?"chartArea":o?"bottom":"left",dtype:n?"radialLinear":o?"category":"linear"}})))),u(n,(e=>{const n=e.options,o=n.id,a=cn(o,n),r=l(n.type,e.dtype);void 0!==n.position&&wn(n.position,a)===wn(e.dposition)||(n.position=e.dposition),s[o]=!0;let h=null;if(o in i&&i[o].type===r)h=i[o];else{h=new(nn.getScale(r))({id:o,type:r,ctx:this.ctx,chart:this}),i[h.id]=h}h.init(n,t)})),u(s,((t,e)=>{t||delete i[e]})),u(i,(t=>{ls.configure(this,t,t.options),ls.addBox(this,t)}))}_updateMetasets(){const t=this._metasets,e=this.data.datasets.length,i=t.length;if(t.sort(((t,e)=>t.index-e.index)),i>e){for(let t=e;te.length&&delete this._stacks,t.forEach(((t,i)=>{0===e.filter((e=>e===t._dataset)).length&&this._destroyDatasetMeta(i)}))}buildOrUpdateControllers(){const t=[],e=this.data.datasets;let i,s;for(this._removeUnreferencedMetasets(),i=0,s=e.length;i{this.getDatasetMeta(e).controller.reset()}),this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(t){const e=this.config;e.update();const i=this._options=e.createResolver(e.chartOptionScopes(),this.getContext()),s=this._animationsDisabled=!i.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),!1===this.notifyPlugins("beforeUpdate",{mode:t,cancelable:!0}))return;const n=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let o=0;for(let t=0,e=this.data.datasets.length;t{t.reset()})),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(kn("z","_idx"));const{_active:a,_lastEvent:r}=this;r?this._eventHandler(r,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){u(this.scales,(t=>{ls.removeBox(this,t)})),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const t=this.options,e=new Set(Object.keys(this._listeners)),i=new Set(t.events);P(e,i)&&!!this._responsiveListeners===t.responsive||(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:t}=this,e=this._getUniformDataChanges()||[];for(const{method:i,start:s,count:n}of e){An(t,s,"_removeElements"===i?-n:n)}}_getUniformDataChanges(){const t=this._dataChanges;if(!t||!t.length)return;this._dataChanges=[];const e=this.data.datasets.length,i=e=>new Set(t.filter((t=>t[0]===e)).map(((t,e)=>e+","+t.splice(1).join(",")))),s=i(0);for(let t=1;tt.split(","))).map((t=>({method:t[1],start:+t[2],count:+t[3]})))}_updateLayout(t){if(!1===this.notifyPlugins("beforeLayout",{cancelable:!0}))return;ls.update(this,this.width,this.height,t);const e=this.chartArea,i=e.width<=0||e.height<=0;this._layers=[],u(this.boxes,(t=>{i&&"chartArea"===t.position||(t.configure&&t.configure(),this._layers.push(...t._layers()))}),this),this._layers.forEach(((t,e)=>{t._idx=e})),this.notifyPlugins("afterLayout")}_updateDatasets(t){if(!1!==this.notifyPlugins("beforeDatasetsUpdate",{mode:t,cancelable:!0})){for(let t=0,e=this.data.datasets.length;t=0;--e)this._drawDataset(t[e]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(t){const e=this.ctx,i={meta:t,index:t.index,cancelable:!0},s=Ni(this,t);!1!==this.notifyPlugins("beforeDatasetDraw",i)&&(s&&Ie(e,s),t.controller.draw(),s&&ze(e),i.cancelable=!1,this.notifyPlugins("afterDatasetDraw",i))}isPointInArea(t){return Re(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,e,i,s){const n=Ki.modes[e];return"function"==typeof n?n(this,t,i,s):[]}getDatasetMeta(t){const e=this.data.datasets[t],i=this._metasets;let s=i.filter((t=>t&&t._dataset===e)).pop();return s||(s={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:e&&e.order||0,index:t,_dataset:e,_parsed:[],_sorted:!1},i.push(s)),s}getContext(){return this.$context||(this.$context=Ci(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){const e=this.data.datasets[t];if(!e)return!1;const i=this.getDatasetMeta(t);return"boolean"==typeof i.hidden?!i.hidden:!e.hidden}setDatasetVisibility(t,e){this.getDatasetMeta(t).hidden=!e}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(t,e,i){const s=i?"show":"hide",n=this.getDatasetMeta(t),o=n.controller._resolveAnimations(void 0,s);k(e)?(n.data[e].hidden=!i,this.update()):(this.setDatasetVisibility(t,i),o.update(n,{visible:i}),this.update((e=>e.datasetIndex===t?s:void 0)))}hide(t,e){this._updateVisibility(t,e,!1)}show(t,e){this._updateVisibility(t,e,!0)}_destroyDatasetMeta(t){const e=this._metasets[t];e&&e.controller&&e.controller._destroy(),delete this._metasets[t]}_stop(){let t,e;for(this.stop(),bt.remove(this),t=0,e=this.data.datasets.length;t{e.addEventListener(this,i,s),t[i]=s},s=(t,e,i)=>{t.offsetX=e,t.offsetY=i,this._eventHandler(t)};u(this.options.events,(t=>i(t,s)))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const t=this._responsiveListeners,e=this.platform,i=(i,s)=>{e.addEventListener(this,i,s),t[i]=s},s=(i,s)=>{t[i]&&(e.removeEventListener(this,i,s),delete t[i])},n=(t,e)=>{this.canvas&&this.resize(t,e)};let o;const a=()=>{s("attach",a),this.attached=!0,this.resize(),i("resize",n),i("detach",o)};o=()=>{this.attached=!1,s("resize",n),this._stop(),this._resize(0,0),i("attach",a)},e.isAttached(this.canvas)?a():o()}unbindEvents(){u(this._listeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._listeners={},u(this._responsiveListeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._responsiveListeners=void 0}updateHoverStyle(t,e,i){const s=i?"set":"remove";let n,o,a,r;for("dataset"===e&&(n=this.getDatasetMeta(t[0].datasetIndex),n.controller["_"+s+"DatasetHoverStyle"]()),a=0,r=t.length;a{const i=this.getDatasetMeta(t);if(!i)throw new Error("No dataset found at index "+t);return{datasetIndex:t,element:i.data[e],index:e}}));!f(i,e)&&(this._active=i,this._lastEvent=null,this._updateHoverStyles(i,e))}notifyPlugins(t,e,i){return this._plugins.notify(this,t,e,i)}isPluginEnabled(t){return 1===this._plugins._cache.filter((e=>e.plugin.id===t)).length}_updateHoverStyles(t,e,i){const s=this.options.hover,n=(t,e)=>t.filter((t=>!e.some((e=>t.datasetIndex===e.datasetIndex&&t.index===e.index)))),o=n(e,t),a=i?t:n(t,e);o.length&&this.updateHoverStyle(o,s.mode,!1),a.length&&s.mode&&this.updateHoverStyle(a,s.mode,!0)}_eventHandler(t,e){const i={event:t,replay:e,cancelable:!0,inChartArea:this.isPointInArea(t)},s=e=>(e.options.events||this.options.events).includes(t.native.type);if(!1===this.notifyPlugins("beforeEvent",i,s))return;const n=this._handleEvent(t,e,i.inChartArea);return i.cancelable=!1,this.notifyPlugins("afterEvent",i,s),(n||i.changed)&&this.render(),this}_handleEvent(t,e,i){const{_active:s=[],options:n}=this,o=e,a=this._getActiveElements(t,s,i,o),r=D(t),l=function(t,e,i,s){return i&&"mouseout"!==t.type?s?e:t:null}(t,this._lastEvent,i,r);i&&(this._lastEvent=null,d(n.onHover,[t,a,this],this),r&&d(n.onClick,[t,a,this],this));const h=!f(a,s);return(h||e)&&(this._active=a,this._updateHoverStyles(a,s,e)),this._lastEvent=l,h}_getActiveElements(t,e,i,s){if("mouseout"===t.type)return[];if(!i)return e;const n=this.options.hover;return this.getElementsAtEventForMode(t,n.mode,n,s)}}function Ln(){return u(Tn.instances,(t=>t._plugins.invalidate()))}function En(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class Rn{static override(t){Object.assign(Rn.prototype,t)}options;constructor(t){this.options=t||{}}init(){}formats(){return En()}parse(){return En()}format(){return En()}add(){return En()}diff(){return En()}startOf(){return En()}endOf(){return En()}}var In={_date:Rn};function zn(t){const e=t.iScale,i=function(t,e){if(!t._cache.$bar){const i=t.getMatchingVisibleMetas(e);let s=[];for(let e=0,n=i.length;et-e)))}return t._cache.$bar}(e,t.type);let s,n,o,a,r=e._length;const l=()=>{32767!==o&&-32768!==o&&(k(a)&&(r=Math.min(r,Math.abs(o-a)||r)),a=o)};for(s=0,n=i.length;sMath.abs(r)&&(l=r,h=a),e[i.axis]=h,e._custom={barStart:l,barEnd:h,start:n,end:o,min:a,max:r}}(t,e,i,s):e[i.axis]=i.parse(t,s),e}function Vn(t,e,i,s){const n=t.iScale,o=t.vScale,a=n.getLabels(),r=n===o,l=[];let h,c,d,u;for(h=i,c=i+s;ht.x,i="left",s="right"):(e=t.base"spacing"!==t,_indexable:t=>"spacing"!==t&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const e=t.data;if(e.labels.length&&e.datasets.length){const{labels:{pointStyle:i,color:s}}=t.legend.options;return e.labels.map(((e,n)=>{const o=t.getDatasetMeta(0).controller.getStyle(n);return{text:e,fillStyle:o.backgroundColor,strokeStyle:o.borderColor,fontColor:s,lineWidth:o.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(n),index:n}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}}};constructor(t,e){super(t,e),this.enableOptionSharing=!0,this.innerRadius=void 0,this.outerRadius=void 0,this.offsetX=void 0,this.offsetY=void 0}linkScales(){}parse(t,e){const i=this.getDataset().data,s=this._cachedMeta;if(!1===this._parsing)s._parsed=i;else{let n,a,r=t=>+i[t];if(o(i[t])){const{key:t="value"}=this._parsing;r=e=>+M(i[e],t)}for(n=t,a=t+e;nJ(t,r,l,!0)?1:Math.max(e,e*i,s,s*i),g=(t,e,s)=>J(t,r,l,!0)?-1:Math.min(e,e*i,s,s*i),p=f(0,h,d),m=f(E,c,u),x=g(C,h,d),b=g(C+E,c,u);s=(p-x)/2,n=(m-b)/2,o=-(p+x)/2,a=-(m+b)/2}return{ratioX:s,ratioY:n,offsetX:o,offsetY:a}}(u,d,r),x=(i.width-o)/f,b=(i.height-o)/g,_=Math.max(Math.min(x,b)/2,0),y=c(this.options.radius,_),v=(y-Math.max(y*r,0))/this._getVisibleDatasetWeightTotal();this.offsetX=p*y,this.offsetY=m*y,s.total=this.calculateTotal(),this.outerRadius=y-v*this._getRingWeightOffset(this.index),this.innerRadius=Math.max(this.outerRadius-v*l,0),this.updateElements(n,0,n.length,t)}_circumference(t,e){const i=this.options,s=this._cachedMeta,n=this._getCircumference();return e&&i.animation.animateRotate||!this.chart.getDataVisibility(t)||null===s._parsed[t]||s.data[t].hidden?0:this.calculateCircumference(s._parsed[t]*n/O)}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.chartArea,r=o.options.animation,l=(a.left+a.right)/2,h=(a.top+a.bottom)/2,c=n&&r.animateScale,d=c?0:this.innerRadius,u=c?0:this.outerRadius,{sharedOptions:f,includeOptions:g}=this._getSharedOptions(e,s);let p,m=this._getRotation();for(p=0;p0&&!isNaN(t)?O*(Math.abs(t)/e):0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t],i.options.locale);return{label:s[t]||"",value:n}}getMaxBorderWidth(t){let e=0;const i=this.chart;let s,n,o,a,r;if(!t)for(s=0,n=i.data.datasets.length;s{const o=t.getDatasetMeta(0).controller.getStyle(n);return{text:e,fillStyle:o.backgroundColor,strokeStyle:o.borderColor,fontColor:s,lineWidth:o.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(n),index:n}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}};constructor(t,e){super(t,e),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t].r,i.options.locale);return{label:s[t]||"",value:n}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta.data;this._updateRadius(),this.updateElements(e,0,e.length,t)}getMinMax(){const t=this._cachedMeta,e={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};return t.data.forEach(((t,i)=>{const s=this.getParsed(i).r;!isNaN(s)&&this.chart.getDataVisibility(i)&&(se.max&&(e.max=s))})),e}_updateRadius(){const t=this.chart,e=t.chartArea,i=t.options,s=Math.min(e.right-e.left,e.bottom-e.top),n=Math.max(s/2,0),o=(n-Math.max(i.cutoutPercentage?n/100*i.cutoutPercentage:1,0))/t.getVisibleDatasetCount();this.outerRadius=n-o*this.index,this.innerRadius=this.outerRadius-o}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.options.animation,r=this._cachedMeta.rScale,l=r.xCenter,h=r.yCenter,c=r.getIndexAngle(0)-.5*C;let d,u=c;const f=360/this.countVisibleElements();for(d=0;d{!isNaN(this.getParsed(i).r)&&this.chart.getDataVisibility(i)&&e++})),e}_computeAngle(t,e,i){return this.chart.getDataVisibility(t)?$(this.resolveDataElementOptions(t,e).angle||i):0}}var Un=Object.freeze({__proto__:null,BarController:class extends js{static id="bar";static defaults={datasetElementType:!1,dataElementType:"bar",categoryPercentage:.8,barPercentage:.9,grouped:!0,animations:{numbers:{type:"number",properties:["x","y","base","width","height"]}}};static overrides={scales:{_index_:{type:"category",offset:!0,grid:{offset:!0}},_value_:{type:"linear",beginAtZero:!0}}};parsePrimitiveData(t,e,i,s){return Vn(t,e,i,s)}parseArrayData(t,e,i,s){return Vn(t,e,i,s)}parseObjectData(t,e,i,s){const{iScale:n,vScale:o}=t,{xAxisKey:a="x",yAxisKey:r="y"}=this._parsing,l="x"===n.axis?a:r,h="x"===o.axis?a:r,c=[];let d,u,f,g;for(d=i,u=i+s;dt.controller.options.grouped)),o=i.options.stacked,a=[],r=this._cachedMeta.controller.getParsed(e),l=r&&r[i.axis],h=t=>{const e=t._parsed.find((t=>t[i.axis]===l)),n=e&&e[t.vScale.axis];if(s(n)||isNaN(n))return!0};for(const i of n)if((void 0===e||!h(i))&&((!1===o||-1===a.indexOf(i.stack)||void 0===o&&void 0===i.stack)&&a.push(i.stack),i.index===t))break;return a.length||a.push(void 0),a}_getStackCount(t){return this._getStacks(void 0,t).length}_getAxisCount(){return this._getAxis().length}getFirstScaleIdForIndexAxis(){const t=this.chart.scales,e=this.chart.options.indexAxis;return Object.keys(t).filter((i=>t[i].axis===e)).shift()}_getAxis(){const t={},e=this.getFirstScaleIdForIndexAxis();for(const i of this.chart.data.datasets)t[l("x"===this.chart.options.indexAxis?i.xAxisID:i.yAxisID,e)]=!0;return Object.keys(t)}_getStackIndex(t,e,i){const s=this._getStacks(t,i),n=void 0!==e?s.indexOf(e):-1;return-1===n?s.length-1:n}_getRuler(){const t=this.options,e=this._cachedMeta,i=e.iScale,s=[];let n,o;for(n=0,o=e.data.length;n=i?1:-1)}(u,e,r)*a,f===r&&(x-=u/2);const t=e.getPixelForDecimal(0),s=e.getPixelForDecimal(1),o=Math.min(t,s),h=Math.max(t,s);x=Math.max(Math.min(x,h),o),d=x+u,i&&!c&&(l._stacks[e.axis]._visualValues[n]=e.getValueForPixel(d)-e.getValueForPixel(x))}if(x===e.getPixelForValue(r)){const t=F(u)*e.getLineWidthForValue(r)/2;x+=t,u-=t}return{size:u,base:x,head:d,center:d+u/2}}_calculateBarIndexPixels(t,e){const i=e.scale,n=this.options,o=n.skipNull,a=l(n.maxBarThickness,1/0);let r,h;const c=this._getAxisCount();if(e.grouped){const i=o?this._getStackCount(t):e.stackCount,d="flex"===n.barThickness?function(t,e,i,s){const n=e.pixels,o=n[t];let a=t>0?n[t-1]:null,r=t=0;--i)e=Math.max(e,t[i].size(this.resolveDataElementOptions(i))/2);return e>0&&e}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart.data.labels||[],{xScale:s,yScale:n}=e,o=this.getParsed(t),a=s.getLabelForValue(o.x),r=n.getLabelForValue(o.y),l=o._custom;return{label:i[t]||"",value:"("+a+", "+r+(l?", "+l:"")+")"}}update(t){const e=this._cachedMeta.data;this.updateElements(e,0,e.length,t)}updateElements(t,e,i,s){const n="reset"===s,{iScale:o,vScale:a}=this._cachedMeta,{sharedOptions:r,includeOptions:l}=this._getSharedOptions(e,s),h=o.axis,c=a.axis;for(let d=e;d0&&this.getParsed(e-1);for(let i=0;i<_;++i){const g=t[i],_=x?g:{};if(i=b){_.skip=!0;continue}const v=this.getParsed(i),M=s(v[f]),w=_[u]=a.getPixelForValue(v[u],i),k=_[f]=o||M?r.getBasePixel():r.getPixelForValue(l?this.applyStack(r,v,l):v[f],i);_.skip=isNaN(w)||isNaN(k)||M,_.stop=i>0&&Math.abs(v[u]-y[u])>m,p&&(_.parsed=v,_.raw=h.data[i]),d&&(_.options=c||this.resolveDataElementOptions(i,g.active?"active":n)),x||this.updateElement(g,i,_,n),y=v}}getMaxOverflow(){const t=this._cachedMeta,e=t.dataset,i=e.options&&e.options.borderWidth||0,s=t.data||[];if(!s.length)return i;const n=s[0].size(this.resolveDataElementOptions(0)),o=s[s.length-1].size(this.resolveDataElementOptions(s.length-1));return Math.max(i,n,o)/2}draw(){const t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}},PieController:class extends $n{static id="pie";static defaults={cutout:0,rotation:0,circumference:360,radius:"100%"}},PolarAreaController:Yn,RadarController:class extends js{static id="radar";static defaults={datasetElementType:"line",dataElementType:"point",indexAxis:"r",showLine:!0,elements:{line:{fill:"start"}}};static overrides={aspectRatio:1,scales:{r:{type:"radialLinear"}}};getLabelAndValue(t){const e=this._cachedMeta.vScale,i=this.getParsed(t);return{label:e.getLabels()[t],value:""+e.getLabelForValue(i[e.axis])}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta,i=e.dataset,s=e.data||[],n=e.iScale.getLabels();if(i.points=s,"resize"!==t){const e=this.resolveDatasetElementOptions(t);this.options.showLine||(e.borderWidth=0);const o={_loop:!0,_fullLoop:n.length===s.length,options:e};this.updateElement(i,void 0,o,t)}this.updateElements(s,0,s.length,t)}updateElements(t,e,i,s){const n=this._cachedMeta.rScale,o="reset"===s;for(let a=e;a0&&this.getParsed(e-1);for(let c=e;c0&&Math.abs(i[f]-_[f])>x,m&&(p.parsed=i,p.raw=h.data[c]),u&&(p.options=d||this.resolveDataElementOptions(c,e.active?"active":n)),b||this.updateElement(e,c,p,n),_=i}this.updateSharedOptions(d,n,c)}getMaxOverflow(){const t=this._cachedMeta,e=t.data||[];if(!this.options.showLine){let t=0;for(let i=e.length-1;i>=0;--i)t=Math.max(t,e[i].size(this.resolveDataElementOptions(i))/2);return t>0&&t}const i=t.dataset,s=i.options&&i.options.borderWidth||0;if(!e.length)return s;const n=e[0].size(this.resolveDataElementOptions(0)),o=e[e.length-1].size(this.resolveDataElementOptions(e.length-1));return Math.max(s,n,o)/2}}});function Xn(t,e,i,s){const n=vi(t.options.borderRadius,["outerStart","outerEnd","innerStart","innerEnd"]);const o=(i-e)/2,a=Math.min(o,s*e/2),r=t=>{const e=(i-Math.min(o,t))*s/2;return Z(t,0,Math.min(o,e))};return{outerStart:r(n.outerStart),outerEnd:r(n.outerEnd),innerStart:Z(n.innerStart,0,a),innerEnd:Z(n.innerEnd,0,a)}}function qn(t,e,i,s){return{x:i+t*Math.cos(e),y:s+t*Math.sin(e)}}function Kn(t,e,i,s,n,o){const{x:a,y:r,startAngle:l,pixelMargin:h,innerRadius:c}=e,d=Math.max(e.outerRadius+s+i-h,0),u=c>0?c+s+i+h:0;let f=0;const g=n-l;if(s){const t=((c>0?c-s:0)+(d>0?d-s:0))/2;f=(g-(0!==t?g*t/(t+s):g))/2}const p=(g-Math.max(.001,g*d-i/C)/d)/2,m=l+p+f,x=n-p-f,{outerStart:b,outerEnd:_,innerStart:y,innerEnd:v}=Xn(e,u,d,x-m),M=d-b,w=d-_,k=m+b/M,S=x-_/w,P=u+y,D=u+v,O=m+y/P,A=x-v/D;if(t.beginPath(),o){const e=(k+S)/2;if(t.arc(a,r,d,k,e),t.arc(a,r,d,e,S),_>0){const e=qn(w,S,a,r);t.arc(e.x,e.y,_,S,x+E)}const i=qn(D,x,a,r);if(t.lineTo(i.x,i.y),v>0){const e=qn(D,A,a,r);t.arc(e.x,e.y,v,x+E,A+Math.PI)}const s=(x-v/u+(m+y/u))/2;if(t.arc(a,r,u,x-v/u,s,!0),t.arc(a,r,u,s,m+y/u,!0),y>0){const e=qn(P,O,a,r);t.arc(e.x,e.y,y,O+Math.PI,m-E)}const n=qn(M,m,a,r);if(t.lineTo(n.x,n.y),b>0){const e=qn(M,k,a,r);t.arc(e.x,e.y,b,m-E,k)}}else{t.moveTo(a,r);const e=Math.cos(k)*d+a,i=Math.sin(k)*d+r;t.lineTo(e,i);const s=Math.cos(S)*d+a,n=Math.sin(S)*d+r;t.lineTo(s,n)}t.closePath()}function Gn(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r,options:l}=e,{borderWidth:h,borderJoinStyle:c,borderDash:d,borderDashOffset:u,borderRadius:f}=l,g="inner"===l.borderAlign;if(!h)return;t.setLineDash(d||[]),t.lineDashOffset=u,g?(t.lineWidth=2*h,t.lineJoin=c||"round"):(t.lineWidth=h,t.lineJoin=c||"bevel");let p=e.endAngle;if(o){Kn(t,e,i,s,p,n);for(let e=0;en?(h=n/l,t.arc(o,a,l,i+h,s-h,!0)):t.arc(o,a,n,i+E,s-E),t.closePath(),t.clip()}(t,e,p),l.selfJoin&&p-a>=C&&0===f&&"miter"!==c&&function(t,e,i){const{startAngle:s,x:n,y:o,outerRadius:a,innerRadius:r,options:l}=e,{borderWidth:h,borderJoinStyle:c}=l,d=Math.min(h/a,G(s-i));if(t.beginPath(),t.arc(n,o,a-h/2,s+d/2,i-d/2),r>0){const e=Math.min(h/r,G(s-i));t.arc(n,o,r+h/2,i-e/2,s+e/2,!0)}else{const e=Math.min(h/2,a*G(s-i));if("round"===c)t.arc(n,o,e,i-C/2,s+C/2,!0);else if("bevel"===c){const a=2*e*e,r=-a*Math.cos(i+C/2)+n,l=-a*Math.sin(i+C/2)+o,h=a*Math.cos(s+C/2)+n,c=a*Math.sin(s+C/2)+o;t.lineTo(r,l),t.lineTo(h,c)}}t.closePath(),t.moveTo(0,0),t.rect(0,0,t.canvas.width,t.canvas.height),t.clip("evenodd")}(t,e,p),o||(Kn(t,e,i,s,p,n),t.stroke())}function Jn(t,e,i=e){t.lineCap=l(i.borderCapStyle,e.borderCapStyle),t.setLineDash(l(i.borderDash,e.borderDash)),t.lineDashOffset=l(i.borderDashOffset,e.borderDashOffset),t.lineJoin=l(i.borderJoinStyle,e.borderJoinStyle),t.lineWidth=l(i.borderWidth,e.borderWidth),t.strokeStyle=l(i.borderColor,e.borderColor)}function Zn(t,e,i){t.lineTo(i.x,i.y)}function Qn(t,e,i={}){const s=t.length,{start:n=0,end:o=s-1}=i,{start:a,end:r}=e,l=Math.max(n,a),h=Math.min(o,r),c=nr&&o>r;return{count:s,start:l,loop:e.loop,ilen:h(a+(h?r-t:t))%o,_=()=>{f!==g&&(t.lineTo(m,g),t.lineTo(m,f),t.lineTo(m,p))};for(l&&(d=n[b(0)],t.moveTo(d.x,d.y)),c=0;c<=r;++c){if(d=n[b(c)],d.skip)continue;const e=d.x,i=d.y,s=0|e;s===u?(ig&&(g=i),m=(x*m+e)/++x):(_(),t.lineTo(e,i),u=s,x=0,f=g=i),p=i}_()}function io(t){const e=t.options,i=e.borderDash&&e.borderDash.length;return!(t._decimated||t._loop||e.tension||"monotone"===e.cubicInterpolationMode||e.stepped||i)?eo:to}const so="function"==typeof Path2D;function no(t,e,i,s){so&&!e.options.segment?function(t,e,i,s){let n=e._path;n||(n=e._path=new Path2D,e.path(n,i,s)&&n.closePath()),Jn(t,e.options),t.stroke(n)}(t,e,i,s):function(t,e,i,s){const{segments:n,options:o}=e,a=io(e);for(const r of n)Jn(t,o,r.style),t.beginPath(),a(t,e,r,{start:i,end:i+s-1})&&t.closePath(),t.stroke()}(t,e,i,s)}class oo extends $s{static id="line";static defaults={borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};static descriptors={_scriptable:!0,_indexable:t=>"borderDash"!==t&&"fill"!==t};constructor(t){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,t&&Object.assign(this,t)}updateControlPoints(t,e){const i=this.options;if((i.tension||"monotone"===i.cubicInterpolationMode)&&!i.stepped&&!this._pointsUpdated){const s=i.spanGaps?this._loop:this._fullLoop;hi(this._points,i,t,s,e),this._pointsUpdated=!0}}set points(t){this._points=t,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=zi(this,this.options.segment))}first(){const t=this.segments,e=this.points;return t.length&&e[t[0].start]}last(){const t=this.segments,e=this.points,i=t.length;return i&&e[t[i-1].end]}interpolate(t,e){const i=this.options,s=t[e],n=this.points,o=Ii(this,{property:e,start:s,end:s});if(!o.length)return;const a=[],r=function(t){return t.stepped?pi:t.tension||"monotone"===t.cubicInterpolationMode?mi:gi}(i);let l,h;for(l=0,h=o.length;l"borderDash"!==t};circumference;endAngle;fullCircles;innerRadius;outerRadius;pixelMargin;startAngle;constructor(t){super(),this.options=void 0,this.circumference=void 0,this.startAngle=void 0,this.endAngle=void 0,this.innerRadius=void 0,this.outerRadius=void 0,this.pixelMargin=0,this.fullCircles=0,t&&Object.assign(this,t)}inRange(t,e,i){const s=this.getProps(["x","y"],i),{angle:n,distance:o}=X(s,{x:t,y:e}),{startAngle:a,endAngle:r,innerRadius:h,outerRadius:c,circumference:d}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],i),u=(this.options.spacing+this.options.borderWidth)/2,f=l(d,r-a),g=J(n,a,r)&&a!==r,p=f>=O||g,m=tt(o,h+u,c+u);return p&&m}getCenterPoint(t){const{x:e,y:i,startAngle:s,endAngle:n,innerRadius:o,outerRadius:a}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],t),{offset:r,spacing:l}=this.options,h=(s+n)/2,c=(o+a+l+r)/2;return{x:e+Math.cos(h)*c,y:i+Math.sin(h)*c}}tooltipPosition(t){return this.getCenterPoint(t)}draw(t){const{options:e,circumference:i}=this,s=(e.offset||0)/4,n=(e.spacing||0)/2,o=e.circular;if(this.pixelMargin="inner"===e.borderAlign?.33:0,this.fullCircles=i>O?Math.floor(i/O):0,0===i||this.innerRadius<0||this.outerRadius<0)return;t.save();const a=(this.startAngle+this.endAngle)/2;t.translate(Math.cos(a)*s,Math.sin(a)*s);const r=s*(1-Math.sin(Math.min(C,i||0)));t.fillStyle=e.backgroundColor,t.strokeStyle=e.borderColor,function(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r}=e;let l=e.endAngle;if(o){Kn(t,e,i,s,l,n);for(let e=0;e("string"==typeof e?(i=t.push(e)-1,s.unshift({index:i,label:e})):isNaN(e)&&(i=null),i))(t,e,i,s);return n!==t.lastIndexOf(e)?i:n}function mo(t){const e=this.getLabels();return t>=0&&ts=e?s:t,a=t=>n=i?n:t;if(t){const t=F(s),e=F(n);t<0&&e<0?a(0):t>0&&e>0&&o(0)}if(s===n){let e=0===n?1:Math.abs(.05*n);a(n+e),t||o(s-e)}this.min=s,this.max=n}getTickLimit(){const t=this.options.ticks;let e,{maxTicksLimit:i,stepSize:s}=t;return s?(e=Math.ceil(this.max/s)-Math.floor(this.min/s)+1,e>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${s} would result generating up to ${e} ticks. Limiting to 1000.`),e=1e3)):(e=this.computeTickLimit(),i=i||11),i&&(e=Math.min(i,e)),e}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const t=this.options,e=t.ticks;let i=this.getTickLimit();i=Math.max(2,i);const n=function(t,e){const i=[],{bounds:n,step:o,min:a,max:r,precision:l,count:h,maxTicks:c,maxDigits:d,includeBounds:u}=t,f=o||1,g=c-1,{min:p,max:m}=e,x=!s(a),b=!s(r),_=!s(h),y=(m-p)/(d+1);let v,M,w,k,S=B((m-p)/g/f)*f;if(S<1e-14&&!x&&!b)return[{value:p},{value:m}];k=Math.ceil(m/S)-Math.floor(p/S),k>g&&(S=B(k*S/g/f)*f),s(l)||(v=Math.pow(10,l),S=Math.ceil(S*v)/v),"ticks"===n?(M=Math.floor(p/S)*S,w=Math.ceil(m/S)*S):(M=p,w=m),x&&b&&o&&H((r-a)/o,S/1e3)?(k=Math.round(Math.min((r-a)/S,c)),S=(r-a)/k,M=a,w=r):_?(M=x?a:M,w=b?r:w,k=h-1,S=(w-M)/k):(k=(w-M)/S,k=V(k,Math.round(k),S/1e3)?Math.round(k):Math.ceil(k));const P=Math.max(U(S),U(M));v=Math.pow(10,s(l)?P:l),M=Math.round(M*v)/v,w=Math.round(w*v)/v;let D=0;for(x&&(u&&M!==a?(i.push({value:a}),Mr)break;i.push({value:t})}return b&&u&&w!==r?i.length&&V(i[i.length-1].value,r,xo(r,y,t))?i[i.length-1].value=r:i.push({value:r}):b&&w!==r||i.push({value:w}),i}({maxTicks:i,bounds:t.bounds,min:t.min,max:t.max,precision:e.precision,step:e.stepSize,count:e.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:e.minRotation||0,includeBounds:!1!==e.includeBounds},this._range||this);return"ticks"===t.bounds&&j(n,this,"value"),t.reverse?(n.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),n}configure(){const t=this.ticks;let e=this.min,i=this.max;if(super.configure(),this.options.offset&&t.length){const s=(i-e)/Math.max(t.length-1,1)/2;e-=s,i+=s}this._startValue=e,this._endValue=i,this._valueRange=i-e}getLabelForValue(t){return ne(t,this.chart.options.locale,this.options.ticks.format)}}class _o extends bo{static id="linear";static defaults={ticks:{callback:ae.formatters.numeric}};determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?t:0,this.max=a(e)?e:1,this.handleTickRangeOptions()}computeTickLimit(){const t=this.isHorizontal(),e=t?this.width:this.height,i=$(this.options.ticks.minRotation),s=(t?Math.sin(i):Math.cos(i))||.001,n=this._resolveTickFontOptions(0);return Math.ceil(e/Math.min(40,n.lineHeight/s))}getPixelForValue(t){return null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getValueForPixel(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange}}const yo=t=>Math.floor(z(t)),vo=(t,e)=>Math.pow(10,yo(t)+e);function Mo(t){return 1===t/Math.pow(10,yo(t))}function wo(t,e,i){const s=Math.pow(10,i),n=Math.floor(t/s);return Math.ceil(e/s)-n}function ko(t,{min:e,max:i}){e=r(t.min,e);const s=[],n=yo(e);let o=function(t,e){let i=yo(e-t);for(;wo(t,e,i)>10;)i++;for(;wo(t,e,i)<10;)i--;return Math.min(i,yo(t))}(e,i),a=o<0?Math.pow(10,Math.abs(o)):1;const l=Math.pow(10,o),h=n>o?Math.pow(10,n):0,c=Math.round((e-h)*a)/a,d=Math.floor((e-h)/l/10)*l*10;let u=Math.floor((c-d)/Math.pow(10,o)),f=r(t.min,Math.round((h+d+u*Math.pow(10,o))*a)/a);for(;f=10?u=u<15?15:20:u++,u>=20&&(o++,u=2,a=o>=0?1:a),f=Math.round((h+d+u*Math.pow(10,o))*a)/a;const g=r(t.max,f);return s.push({value:g,major:Mo(g),significand:u}),s}class So extends tn{static id="logarithmic";static defaults={ticks:{callback:ae.formatters.logarithmic,major:{enabled:!0}}};constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){const i=bo.prototype.parse.apply(this,[t,e]);if(0!==i)return a(i)&&i>0?i:null;this._zero=!0}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?Math.max(0,t):null,this.max=a(e)?Math.max(0,e):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!a(this._userMin)&&(this.min=t===vo(this.min,0)?vo(this.min,-1):vo(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let i=this.min,s=this.max;const n=e=>i=t?i:e,o=t=>s=e?s:t;i===s&&(i<=0?(n(1),o(10)):(n(vo(i,-1)),o(vo(s,1)))),i<=0&&n(vo(s,-1)),s<=0&&o(vo(i,1)),this.min=i,this.max=s}buildTicks(){const t=this.options,e=ko({min:this._userMin,max:this._userMax},this);return"ticks"===t.bounds&&j(e,this,"value"),t.reverse?(e.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),e}getLabelForValue(t){return void 0===t?"0":ne(t,this.chart.options.locale,this.options.ticks.format)}configure(){const t=this.min;super.configure(),this._startValue=z(t),this._valueRange=z(this.max)-z(t)}getPixelForValue(t){return void 0!==t&&0!==t||(t=this.min),null===t||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(z(t)-this._startValue)/this._valueRange)}getValueForPixel(t){const e=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+e*this._valueRange)}}function Po(t){const e=t.ticks;if(e.display&&t.display){const t=ki(e.backdropPadding);return l(e.font&&e.font.size,ue.font.size)+t.height}return 0}function Do(t,e,i,s,n){return t===s||t===n?{start:e-i/2,end:e+i/2}:tn?{start:e-i,end:e}:{start:e,end:e+i}}function Co(t){const e={l:t.left+t._padding.left,r:t.right-t._padding.right,t:t.top+t._padding.top,b:t.bottom-t._padding.bottom},i=Object.assign({},e),s=[],o=[],a=t._pointLabels.length,r=t.options.pointLabels,l=r.centerPointLabels?C/a:0;for(let u=0;ue.r&&(r=(s.end-e.r)/o,t.r=Math.max(t.r,e.r+r)),n.starte.b&&(l=(n.end-e.b)/a,t.b=Math.max(t.b,e.b+l))}function Ao(t,e,i){const s=t.drawingArea,{extra:n,additionalAngle:o,padding:a,size:r}=i,l=t.getPointPosition(e,s+n+a,o),h=Math.round(Y(G(l.angle+E))),c=function(t,e,i){90===i||270===i?t-=e/2:(i>270||i<90)&&(t-=e);return t}(l.y,r.h,h),d=function(t){if(0===t||180===t)return"center";if(t<180)return"left";return"right"}(h),u=function(t,e,i){"right"===i?t-=e:"center"===i&&(t-=e/2);return t}(l.x,r.w,d);return{visible:!0,x:l.x,y:c,textAlign:d,left:u,top:c,right:u+r.w,bottom:c+r.h}}function To(t,e){if(!e)return!0;const{left:i,top:s,right:n,bottom:o}=t;return!(Re({x:i,y:s},e)||Re({x:i,y:o},e)||Re({x:n,y:s},e)||Re({x:n,y:o},e))}function Lo(t,e,i){const{left:n,top:o,right:a,bottom:r}=i,{backdropColor:l}=e;if(!s(l)){const i=wi(e.borderRadius),s=ki(e.backdropPadding);t.fillStyle=l;const h=n-s.left,c=o-s.top,d=a-n+s.width,u=r-o+s.height;Object.values(i).some((t=>0!==t))?(t.beginPath(),He(t,{x:h,y:c,w:d,h:u,radius:i}),t.fill()):t.fillRect(h,c,d,u)}}function Eo(t,e,i,s){const{ctx:n}=t;if(i)n.arc(t.xCenter,t.yCenter,e,0,O);else{let i=t.getPointPosition(0,e);n.moveTo(i.x,i.y);for(let o=1;ot,padding:5,centerPointLabels:!1}};static defaultRoutes={"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"};static descriptors={angleLines:{_fallback:"grid"}};constructor(t){super(t),this.xCenter=void 0,this.yCenter=void 0,this.drawingArea=void 0,this._pointLabels=[],this._pointLabelItems=[]}setDimensions(){const t=this._padding=ki(Po(this.options)/2),e=this.width=this.maxWidth-t.width,i=this.height=this.maxHeight-t.height;this.xCenter=Math.floor(this.left+e/2+t.left),this.yCenter=Math.floor(this.top+i/2+t.top),this.drawingArea=Math.floor(Math.min(e,i)/2)}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!1);this.min=a(t)&&!isNaN(t)?t:0,this.max=a(e)&&!isNaN(e)?e:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/Po(this.options))}generateTickLabels(t){bo.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map(((t,e)=>{const i=d(this.options.pointLabels.callback,[t,e],this);return i||0===i?i:""})).filter(((t,e)=>this.chart.getDataVisibility(e)))}fit(){const t=this.options;t.display&&t.pointLabels.display?Co(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,e,i,s){this.xCenter+=Math.floor((t-e)/2),this.yCenter+=Math.floor((i-s)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,e,i,s))}getIndexAngle(t){return G(t*(O/(this._pointLabels.length||1))+$(this.options.startAngle||0))}getDistanceFromCenterForValue(t){if(s(t))return NaN;const e=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-t)*e:(t-this.min)*e}getValueForDistanceFromCenter(t){if(s(t))return NaN;const e=t/(this.drawingArea/(this.max-this.min));return this.options.reverse?this.max-e:this.min+e}getPointLabelContext(t){const e=this._pointLabels||[];if(t>=0&&t=0;n--){const e=t._pointLabelItems[n];if(!e.visible)continue;const o=s.setContext(t.getPointLabelContext(n));Lo(i,o,e);const a=Si(o.font),{x:r,y:l,textAlign:h}=e;Ne(i,t._pointLabels[n],r,l+a.lineHeight/2,a,{color:o.color,textAlign:h,textBaseline:"middle"})}}(this,o),s.display&&this.ticks.forEach(((t,e)=>{if(0!==e||0===e&&this.min<0){r=this.getDistanceFromCenterForValue(t.value);const i=this.getContext(e),a=s.setContext(i),l=n.setContext(i);!function(t,e,i,s,n){const o=t.ctx,a=e.circular,{color:r,lineWidth:l}=e;!a&&!s||!r||!l||i<0||(o.save(),o.strokeStyle=r,o.lineWidth=l,o.setLineDash(n.dash||[]),o.lineDashOffset=n.dashOffset,o.beginPath(),Eo(t,i,a,s),o.closePath(),o.stroke(),o.restore())}(this,a,r,o,l)}})),i.display){for(t.save(),a=o-1;a>=0;a--){const s=i.setContext(this.getPointLabelContext(a)),{color:n,lineWidth:o}=s;o&&n&&(t.lineWidth=o,t.strokeStyle=n,t.setLineDash(s.borderDash),t.lineDashOffset=s.borderDashOffset,r=this.getDistanceFromCenterForValue(e.reverse?this.min:this.max),l=this.getPointPosition(a,r),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(l.x,l.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){const t=this.ctx,e=this.options,i=e.ticks;if(!i.display)return;const s=this.getIndexAngle(0);let n,o;t.save(),t.translate(this.xCenter,this.yCenter),t.rotate(s),t.textAlign="center",t.textBaseline="middle",this.ticks.forEach(((s,a)=>{if(0===a&&this.min>=0&&!e.reverse)return;const r=i.setContext(this.getContext(a)),l=Si(r.font);if(n=this.getDistanceFromCenterForValue(this.ticks[a].value),r.showLabelBackdrop){t.font=l.string,o=t.measureText(s.label).width,t.fillStyle=r.backdropColor;const e=ki(r.backdropPadding);t.fillRect(-o/2-e.left,-n-l.size/2-e.top,o+e.width,l.size+e.height)}Ne(t,s.label,0,-n,l,{color:r.color,strokeColor:r.textStrokeColor,strokeWidth:r.textStrokeWidth})})),t.restore()}drawTitle(){}}const Io={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},zo=Object.keys(Io);function Fo(t,e){return t-e}function Vo(t,e){if(s(e))return null;const i=t._adapter,{parser:n,round:o,isoWeekday:r}=t._parseOpts;let l=e;return"function"==typeof n&&(l=n(l)),a(l)||(l="string"==typeof n?i.parse(l,n):i.parse(l)),null===l?null:(o&&(l="week"!==o||!N(r)&&!0!==r?i.startOf(l,o):i.startOf(l,"isoWeek",r)),+l)}function Bo(t,e,i,s){const n=zo.length;for(let o=zo.indexOf(t);o=e?i[s]:i[n]]=!0}}else t[e]=!0}function No(t,e,i){const s=[],n={},o=e.length;let a,r;for(a=0;a=0&&(e[l].major=!0);return e}(t,s,n,i):s}class Ho extends tn{static id="time";static defaults={bounds:"data",adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{}},ticks:{source:"auto",callback:!1,major:{enabled:!1}}};constructor(t){super(t),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(t,e={}){const i=t.time||(t.time={}),s=this._adapter=new In._date(t.adapters.date);s.init(e),b(i.displayFormats,s.formats()),this._parseOpts={parser:i.parser,round:i.round,isoWeekday:i.isoWeekday},super.init(t),this._normalized=e.normalized}parse(t,e){return void 0===t?null:Vo(this,t)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){const t=this.options,e=this._adapter,i=t.time.unit||"day";let{min:s,max:n,minDefined:o,maxDefined:r}=this.getUserBounds();function l(t){o||isNaN(t.min)||(s=Math.min(s,t.min)),r||isNaN(t.max)||(n=Math.max(n,t.max))}o&&r||(l(this._getLabelBounds()),"ticks"===t.bounds&&"labels"===t.ticks.source||l(this.getMinMax(!1))),s=a(s)&&!isNaN(s)?s:+e.startOf(Date.now(),i),n=a(n)&&!isNaN(n)?n:+e.endOf(Date.now(),i)+1,this.min=Math.min(s,n-1),this.max=Math.max(s+1,n)}_getLabelBounds(){const t=this.getLabelTimestamps();let e=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;return t.length&&(e=t[0],i=t[t.length-1]),{min:e,max:i}}buildTicks(){const t=this.options,e=t.time,i=t.ticks,s="labels"===i.source?this.getLabelTimestamps():this._generate();"ticks"===t.bounds&&s.length&&(this.min=this._userMin||s[0],this.max=this._userMax||s[s.length-1]);const n=this.min,o=nt(s,n,this.max);return this._unit=e.unit||(i.autoSkip?Bo(e.minUnit,this.min,this.max,this._getLabelCapacity(n)):function(t,e,i,s,n){for(let o=zo.length-1;o>=zo.indexOf(i);o--){const i=zo[o];if(Io[i].common&&t._adapter.diff(n,s,i)>=e-1)return i}return zo[i?zo.indexOf(i):0]}(this,o.length,e.minUnit,this.min,this.max)),this._majorUnit=i.major.enabled&&"year"!==this._unit?function(t){for(let e=zo.indexOf(t)+1,i=zo.length;e+t.value)))}initOffsets(t=[]){let e,i,s=0,n=0;this.options.offset&&t.length&&(e=this.getDecimalForValue(t[0]),s=1===t.length?1-e:(this.getDecimalForValue(t[1])-e)/2,i=this.getDecimalForValue(t[t.length-1]),n=1===t.length?i:(i-this.getDecimalForValue(t[t.length-2]))/2);const o=t.length<3?.5:.25;s=Z(s,0,o),n=Z(n,0,o),this._offsets={start:s,end:n,factor:1/(s+1+n)}}_generate(){const t=this._adapter,e=this.min,i=this.max,s=this.options,n=s.time,o=n.unit||Bo(n.minUnit,e,i,this._getLabelCapacity(e)),a=l(s.ticks.stepSize,1),r="week"===o&&n.isoWeekday,h=N(r)||!0===r,c={};let d,u,f=e;if(h&&(f=+t.startOf(f,"isoWeek",r)),f=+t.startOf(f,h?"day":o),t.diff(i,e,o)>1e5*a)throw new Error(e+" and "+i+" are too far apart with stepSize of "+a+" "+o);const g="data"===s.ticks.source&&this.getDataTimestamps();for(d=f,u=0;d+t))}getLabelForValue(t){const e=this._adapter,i=this.options.time;return i.tooltipFormat?e.format(t,i.tooltipFormat):e.format(t,i.displayFormats.datetime)}format(t,e){const i=this.options.time.displayFormats,s=this._unit,n=e||i[s];return this._adapter.format(t,n)}_tickFormatFunction(t,e,i,s){const n=this.options,o=n.ticks.callback;if(o)return d(o,[t,e,i],this);const a=n.time.displayFormats,r=this._unit,l=this._majorUnit,h=r&&a[r],c=l&&a[l],u=i[e],f=l&&c&&u&&u.major;return this._adapter.format(t,s||(f?c:h))}generateTickLabels(t){let e,i,s;for(e=0,i=t.length;e0?a:1}getDataTimestamps(){let t,e,i=this._cache.data||[];if(i.length)return i;const s=this.getMatchingVisibleMetas();if(this._normalized&&s.length)return this._cache.data=s[0].controller.getAllParsedValues(this);for(t=0,e=s.length;t=t[r].pos&&e<=t[l].pos&&({lo:r,hi:l}=it(t,"pos",e)),({pos:s,time:o}=t[r]),({pos:n,time:a}=t[l])):(e>=t[r].time&&e<=t[l].time&&({lo:r,hi:l}=it(t,"time",e)),({time:s,pos:o}=t[r]),({time:n,pos:a}=t[l]));const h=n-s;return h?o+(a-o)*(e-s)/h:o}var $o=Object.freeze({__proto__:null,CategoryScale:class extends tn{static id="category";static defaults={ticks:{callback:mo}};constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){const e=this._addedLabels;if(e.length){const t=this.getLabels();for(const{index:i,label:s}of e)t[i]===s&&t.splice(i,1);this._addedLabels=[]}super.init(t)}parse(t,e){if(s(t))return null;const i=this.getLabels();return((t,e)=>null===t?null:Z(Math.round(t),0,e))(e=isFinite(e)&&i[e]===t?e:po(i,t,l(e,t),this._addedLabels),i.length-1)}determineDataLimits(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let{min:i,max:s}=this.getMinMax(!0);"ticks"===this.options.bounds&&(t||(i=0),e||(s=this.getLabels().length-1)),this.min=i,this.max=s}buildTicks(){const t=this.min,e=this.max,i=this.options.offset,s=[];let n=this.getLabels();n=0===t&&e===n.length-1?n:n.slice(t,e+1),this._valueRange=Math.max(n.length-(i?0:1),1),this._startValue=this.min-(i?.5:0);for(let i=t;i<=e;i++)s.push({value:i});return s}getLabelForValue(t){return mo.call(this,t)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(t){return"number"!=typeof t&&(t=this.parse(t)),null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getValueForPixel(t){return Math.round(this._startValue+this.getDecimalForPixel(t)*this._valueRange)}getBasePixel(){return this.bottom}},LinearScale:_o,LogarithmicScale:So,RadialLinearScale:Ro,TimeScale:Ho,TimeSeriesScale:class extends Ho{static id="timeseries";static defaults=Ho.defaults;constructor(t){super(t),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const t=this._getTimestampsForTable(),e=this._table=this.buildLookupTable(t);this._minPos=jo(e,this.min),this._tableRange=jo(e,this.max)-this._minPos,super.initOffsets(t)}buildLookupTable(t){const{min:e,max:i}=this,s=[],n=[];let o,a,r,l,h;for(o=0,a=t.length;o=e&&l<=i&&s.push(l);if(s.length<2)return[{time:e,pos:0},{time:i,pos:1}];for(o=0,a=s.length;ot-e))}_getTimestampsForTable(){let t=this._cache.all||[];if(t.length)return t;const e=this.getDataTimestamps(),i=this.getLabelTimestamps();return t=e.length&&i.length?this.normalize(e.concat(i)):e.length?e:i,t=this._cache.all=t,t}getDecimalForValue(t){return(jo(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){const e=this._offsets,i=this.getDecimalForPixel(t)/e.factor-e.end;return jo(this._table,i*this._tableRange+this._minPos,!0)}}});const Yo=["rgb(54, 162, 235)","rgb(255, 99, 132)","rgb(255, 159, 64)","rgb(255, 205, 86)","rgb(75, 192, 192)","rgb(153, 102, 255)","rgb(201, 203, 207)"],Uo=Yo.map((t=>t.replace("rgb(","rgba(").replace(")",", 0.5)")));function Xo(t){return Yo[t%Yo.length]}function qo(t){return Uo[t%Uo.length]}function Ko(t){let e=0;return(i,s)=>{const n=t.getDatasetMeta(s).controller;n instanceof $n?e=function(t,e){return t.backgroundColor=t.data.map((()=>Xo(e++))),e}(i,e):n instanceof Yn?e=function(t,e){return t.backgroundColor=t.data.map((()=>qo(e++))),e}(i,e):n&&(e=function(t,e){return t.borderColor=Xo(e),t.backgroundColor=qo(e),++e}(i,e))}}function Go(t){let e;for(e in t)if(t[e].borderColor||t[e].backgroundColor)return!0;return!1}var Jo={id:"colors",defaults:{enabled:!0,forceOverride:!1},beforeLayout(t,e,i){if(!i.enabled)return;const{data:{datasets:s},options:n}=t.config,{elements:o}=n,a=Go(s)||(r=n)&&(r.borderColor||r.backgroundColor)||o&&Go(o)||"rgba(0,0,0,0.1)"!==ue.borderColor||"rgba(0,0,0,0.1)"!==ue.backgroundColor;var r;if(!i.forceOverride&&a)return;const l=Ko(t);s.forEach(l)}};function Zo(t){if(t._decimated){const e=t._data;delete t._decimated,delete t._data,Object.defineProperty(t,"data",{configurable:!0,enumerable:!0,writable:!0,value:e})}}function Qo(t){t.data.datasets.forEach((t=>{Zo(t)}))}var ta={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(t,e,i)=>{if(!i.enabled)return void Qo(t);const n=t.width;t.data.datasets.forEach(((e,o)=>{const{_data:a,indexAxis:r}=e,l=t.getDatasetMeta(o),h=a||e.data;if("y"===Pi([r,t.options.indexAxis]))return;if(!l.controller.supportsDecimation)return;const c=t.scales[l.xAxisID];if("linear"!==c.type&&"time"!==c.type)return;if(t.options.parsing)return;let{start:d,count:u}=function(t,e){const i=e.length;let s,n=0;const{iScale:o}=t,{min:a,max:r,minDefined:l,maxDefined:h}=o.getUserBounds();return l&&(n=Z(it(e,o.axis,a).lo,0,i-1)),s=h?Z(it(e,o.axis,r).hi+1,n,i)-n:i-n,{start:n,count:s}}(l,h);if(u<=(i.threshold||4*n))return void Zo(e);let f;switch(s(a)&&(e._data=h,delete e.data,Object.defineProperty(e,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(t){this._data=t}})),i.algorithm){case"lttb":f=function(t,e,i,s,n){const o=n.samples||s;if(o>=i)return t.slice(e,e+i);const a=[],r=(i-2)/(o-2);let l=0;const h=e+i-1;let c,d,u,f,g,p=e;for(a[l++]=t[p],c=0;cu&&(u=f,d=t[s],g=s);a[l++]=d,p=g}return a[l++]=t[h],a}(h,d,u,n,i);break;case"min-max":f=function(t,e,i,n){let o,a,r,l,h,c,d,u,f,g,p=0,m=0;const x=[],b=e+i-1,_=t[e].x,y=t[b].x-_;for(o=e;og&&(g=l,d=o),p=(m*p+a.x)/++m;else{const i=o-1;if(!s(c)&&!s(d)){const e=Math.min(c,d),s=Math.max(c,d);e!==u&&e!==i&&x.push({...t[e],x:p}),s!==u&&s!==i&&x.push({...t[s],x:p})}o>0&&i!==u&&x.push(t[i]),x.push(a),h=e,m=0,f=g=l,c=d=u=o}}return x}(h,d,u,n);break;default:throw new Error(`Unsupported decimation algorithm '${i.algorithm}'`)}e._decimated=f}))},destroy(t){Qo(t)}};function ea(t,e,i,s){if(s)return;let n=e[t],o=i[t];return"angle"===t&&(n=G(n),o=G(o)),{property:t,start:n,end:o}}function ia(t,e,i){for(;e>t;e--){const t=i[e];if(!isNaN(t.x)&&!isNaN(t.y))break}return e}function sa(t,e,i,s){return t&&e?s(t[i],e[i]):t?t[i]:e?e[i]:0}function na(t,e){let i=[],s=!1;return n(t)?(s=!0,i=t):i=function(t,e){const{x:i=null,y:s=null}=t||{},n=e.points,o=[];return e.segments.forEach((({start:t,end:e})=>{e=ia(t,e,n);const a=n[t],r=n[e];null!==s?(o.push({x:a.x,y:s}),o.push({x:r.x,y:s})):null!==i&&(o.push({x:i,y:a.y}),o.push({x:i,y:r.y}))})),o}(t,e),i.length?new oo({points:i,options:{tension:0},_loop:s,_fullLoop:s}):null}function oa(t){return t&&!1!==t.fill}function aa(t,e,i){let s=t[e].fill;const n=[e];let o;if(!i)return s;for(;!1!==s&&-1===n.indexOf(s);){if(!a(s))return s;if(o=t[s],!o)return!1;if(o.visible)return s;n.push(s),s=o.fill}return!1}function ra(t,e,i){const s=function(t){const e=t.options,i=e.fill;let s=l(i&&i.target,i);void 0===s&&(s=!!e.backgroundColor);if(!1===s||null===s)return!1;if(!0===s)return"origin";return s}(t);if(o(s))return!isNaN(s.value)&&s;let n=parseFloat(s);return a(n)&&Math.floor(n)===n?function(t,e,i,s){"-"!==t&&"+"!==t||(i=e+i);if(i===e||i<0||i>=s)return!1;return i}(s[0],e,n,i):["origin","start","end","stack","shape"].indexOf(s)>=0&&s}function la(t,e,i){const s=[];for(let n=0;n=0;--e){const i=n[e].$filler;i&&(i.line.updateControlPoints(o,i.axis),s&&i.fill&&ua(t.ctx,i,o))}},beforeDatasetsDraw(t,e,i){if("beforeDatasetsDraw"!==i.drawTime)return;const s=t.getSortedVisibleDatasetMetas();for(let e=s.length-1;e>=0;--e){const i=s[e].$filler;oa(i)&&ua(t.ctx,i,t.chartArea)}},beforeDatasetDraw(t,e,i){const s=e.meta.$filler;oa(s)&&"beforeDatasetDraw"===i.drawTime&&ua(t.ctx,s,t.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}};const _a=(t,e)=>{let{boxHeight:i=e,boxWidth:s=e}=t;return t.usePointStyle&&(i=Math.min(i,e),s=t.pointStyleWidth||Math.min(s,e)),{boxWidth:s,boxHeight:i,itemHeight:Math.max(e,i)}};class ya extends $s{constructor(t){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e,i){this.maxWidth=t,this.maxHeight=e,this._margins=i,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){const t=this.options.labels||{};let e=d(t.generateLabels,[this.chart],this)||[];t.filter&&(e=e.filter((e=>t.filter(e,this.chart.data)))),t.sort&&(e=e.sort(((e,i)=>t.sort(e,i,this.chart.data)))),this.options.reverse&&e.reverse(),this.legendItems=e}fit(){const{options:t,ctx:e}=this;if(!t.display)return void(this.width=this.height=0);const i=t.labels,s=Si(i.font),n=s.size,o=this._computeTitleHeight(),{boxWidth:a,itemHeight:r}=_a(i,n);let l,h;e.font=s.string,this.isHorizontal()?(l=this.maxWidth,h=this._fitRows(o,n,a,r)+10):(h=this.maxHeight,l=this._fitCols(o,s,a,r)+10),this.width=Math.min(l,t.maxWidth||this.maxWidth),this.height=Math.min(h,t.maxHeight||this.maxHeight)}_fitRows(t,e,i,s){const{ctx:n,maxWidth:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.lineWidths=[0],h=s+a;let c=t;n.textAlign="left",n.textBaseline="middle";let d=-1,u=-h;return this.legendItems.forEach(((t,f)=>{const g=i+e/2+n.measureText(t.text).width;(0===f||l[l.length-1]+g+2*a>o)&&(c+=h,l[l.length-(f>0?0:1)]=0,u+=h,d++),r[f]={left:0,top:u,row:d,width:g,height:s},l[l.length-1]+=g+a})),c}_fitCols(t,e,i,s){const{ctx:n,maxHeight:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.columnSizes=[],h=o-t;let c=a,d=0,u=0,f=0,g=0;return this.legendItems.forEach(((t,o)=>{const{itemWidth:p,itemHeight:m}=function(t,e,i,s,n){const o=function(t,e,i,s){let n=t.text;n&&"string"!=typeof n&&(n=n.reduce(((t,e)=>t.length>e.length?t:e)));return e+i.size/2+s.measureText(n).width}(s,t,e,i),a=function(t,e,i){let s=t;"string"!=typeof e.text&&(s=va(e,i));return s}(n,s,e.lineHeight);return{itemWidth:o,itemHeight:a}}(i,e,n,t,s);o>0&&u+m+2*a>h&&(c+=d+a,l.push({width:d,height:u}),f+=d+a,g++,d=u=0),r[o]={left:f,top:u,col:g,width:p,height:m},d=Math.max(d,p),u+=m+a})),c+=d,l.push({width:d,height:u}),c}adjustHitBoxes(){if(!this.options.display)return;const t=this._computeTitleHeight(),{legendHitBoxes:e,options:{align:i,labels:{padding:s},rtl:n}}=this,o=Oi(n,this.left,this.width);if(this.isHorizontal()){let n=0,a=ft(i,this.left+s,this.right-this.lineWidths[n]);for(const r of e)n!==r.row&&(n=r.row,a=ft(i,this.left+s,this.right-this.lineWidths[n])),r.top+=this.top+t+s,r.left=o.leftForLtr(o.x(a),r.width),a+=r.width+s}else{let n=0,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height);for(const r of e)r.col!==n&&(n=r.col,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height)),r.top=a,r.left+=this.left+s,r.left=o.leftForLtr(o.x(r.left),r.width),a+=r.height+s}}isHorizontal(){return"top"===this.options.position||"bottom"===this.options.position}draw(){if(this.options.display){const t=this.ctx;Ie(t,this),this._draw(),ze(t)}}_draw(){const{options:t,columnSizes:e,lineWidths:i,ctx:s}=this,{align:n,labels:o}=t,a=ue.color,r=Oi(t.rtl,this.left,this.width),h=Si(o.font),{padding:c}=o,d=h.size,u=d/2;let f;this.drawTitle(),s.textAlign=r.textAlign("left"),s.textBaseline="middle",s.lineWidth=.5,s.font=h.string;const{boxWidth:g,boxHeight:p,itemHeight:m}=_a(o,d),x=this.isHorizontal(),b=this._computeTitleHeight();f=x?{x:ft(n,this.left+c,this.right-i[0]),y:this.top+c+b,line:0}:{x:this.left+c,y:ft(n,this.top+b+c,this.bottom-e[0].height),line:0},Ai(this.ctx,t.textDirection);const _=m+c;this.legendItems.forEach(((y,v)=>{s.strokeStyle=y.fontColor,s.fillStyle=y.fontColor;const M=s.measureText(y.text).width,w=r.textAlign(y.textAlign||(y.textAlign=o.textAlign)),k=g+u+M;let S=f.x,P=f.y;r.setWidth(this.width),x?v>0&&S+k+c>this.right&&(P=f.y+=_,f.line++,S=f.x=ft(n,this.left+c,this.right-i[f.line])):v>0&&P+_>this.bottom&&(S=f.x=S+e[f.line].width+c,f.line++,P=f.y=ft(n,this.top+b+c,this.bottom-e[f.line].height));if(function(t,e,i){if(isNaN(g)||g<=0||isNaN(p)||p<0)return;s.save();const n=l(i.lineWidth,1);if(s.fillStyle=l(i.fillStyle,a),s.lineCap=l(i.lineCap,"butt"),s.lineDashOffset=l(i.lineDashOffset,0),s.lineJoin=l(i.lineJoin,"miter"),s.lineWidth=n,s.strokeStyle=l(i.strokeStyle,a),s.setLineDash(l(i.lineDash,[])),o.usePointStyle){const a={radius:p*Math.SQRT2/2,pointStyle:i.pointStyle,rotation:i.rotation,borderWidth:n},l=r.xPlus(t,g/2);Ee(s,a,l,e+u,o.pointStyleWidth&&g)}else{const o=e+Math.max((d-p)/2,0),a=r.leftForLtr(t,g),l=wi(i.borderRadius);s.beginPath(),Object.values(l).some((t=>0!==t))?He(s,{x:a,y:o,w:g,h:p,radius:l}):s.rect(a,o,g,p),s.fill(),0!==n&&s.stroke()}s.restore()}(r.x(S),P,y),S=gt(w,S+g+u,x?S+k:this.right,t.rtl),function(t,e,i){Ne(s,i.text,t,e+m/2,h,{strikethrough:i.hidden,textAlign:r.textAlign(i.textAlign)})}(r.x(S),P,y),x)f.x+=k+c;else if("string"!=typeof y.text){const t=h.lineHeight;f.y+=va(y,t)+c}else f.y+=_})),Ti(this.ctx,t.textDirection)}drawTitle(){const t=this.options,e=t.title,i=Si(e.font),s=ki(e.padding);if(!e.display)return;const n=Oi(t.rtl,this.left,this.width),o=this.ctx,a=e.position,r=i.size/2,l=s.top+r;let h,c=this.left,d=this.width;if(this.isHorizontal())d=Math.max(...this.lineWidths),h=this.top+l,c=ft(t.align,c,this.right-d);else{const e=this.columnSizes.reduce(((t,e)=>Math.max(t,e.height)),0);h=l+ft(t.align,this.top,this.bottom-e-t.labels.padding-this._computeTitleHeight())}const u=ft(a,c,c+d);o.textAlign=n.textAlign(ut(a)),o.textBaseline="middle",o.strokeStyle=e.color,o.fillStyle=e.color,o.font=i.string,Ne(o,e.text,u,h,i)}_computeTitleHeight(){const t=this.options.title,e=Si(t.font),i=ki(t.padding);return t.display?e.lineHeight+i.height:0}_getLegendItemAt(t,e){let i,s,n;if(tt(t,this.left,this.right)&&tt(e,this.top,this.bottom))for(n=this.legendHitBoxes,i=0;it.chart.options.color,boxWidth:40,padding:10,generateLabels(t){const e=t.data.datasets,{labels:{usePointStyle:i,pointStyle:s,textAlign:n,color:o,useBorderRadius:a,borderRadius:r}}=t.legend.options;return t._getSortedDatasetMetas().map((t=>{const l=t.controller.getStyle(i?0:void 0),h=ki(l.borderWidth);return{text:e[t.index].label,fillStyle:l.backgroundColor,fontColor:o,hidden:!t.visible,lineCap:l.borderCapStyle,lineDash:l.borderDash,lineDashOffset:l.borderDashOffset,lineJoin:l.borderJoinStyle,lineWidth:(h.width+h.height)/4,strokeStyle:l.borderColor,pointStyle:s||l.pointStyle,rotation:l.rotation,textAlign:n||l.textAlign,borderRadius:a&&(r||l.borderRadius),datasetIndex:t.index}}),this)}},title:{color:t=>t.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:t=>!t.startsWith("on"),labels:{_scriptable:t=>!["generateLabels","filter","sort"].includes(t)}}};class wa extends $s{constructor(t){super(),this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e){const i=this.options;if(this.left=0,this.top=0,!i.display)return void(this.width=this.height=this.right=this.bottom=0);this.width=this.right=t,this.height=this.bottom=e;const s=n(i.text)?i.text.length:1;this._padding=ki(i.padding);const o=s*Si(i.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=o:this.width=o}isHorizontal(){const t=this.options.position;return"top"===t||"bottom"===t}_drawArgs(t){const{top:e,left:i,bottom:s,right:n,options:o}=this,a=o.align;let r,l,h,c=0;return this.isHorizontal()?(l=ft(a,i,n),h=e+t,r=n-i):("left"===o.position?(l=i+t,h=ft(a,s,e),c=-.5*C):(l=n-t,h=ft(a,e,s),c=.5*C),r=s-e),{titleX:l,titleY:h,maxWidth:r,rotation:c}}draw(){const t=this.ctx,e=this.options;if(!e.display)return;const i=Si(e.font),s=i.lineHeight/2+this._padding.top,{titleX:n,titleY:o,maxWidth:a,rotation:r}=this._drawArgs(s);Ne(t,e.text,0,0,i,{color:e.color,maxWidth:a,rotation:r,textAlign:ut(e.align),textBaseline:"middle",translation:[n,o]})}}var ka={id:"title",_element:wa,start(t,e,i){!function(t,e){const i=new wa({ctx:t.ctx,options:e,chart:t});ls.configure(t,i,e),ls.addBox(t,i),t.titleBlock=i}(t,i)},stop(t){const e=t.titleBlock;ls.removeBox(t,e),delete t.titleBlock},beforeUpdate(t,e,i){const s=t.titleBlock;ls.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const Sa=new WeakMap;var Pa={id:"subtitle",start(t,e,i){const s=new wa({ctx:t.ctx,options:i,chart:t});ls.configure(t,s,i),ls.addBox(t,s),Sa.set(t,s)},stop(t){ls.removeBox(t,Sa.get(t)),Sa.delete(t)},beforeUpdate(t,e,i){const s=Sa.get(t);ls.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"normal"},fullSize:!0,padding:0,position:"top",text:"",weight:1500},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const Da={average(t){if(!t.length)return!1;let e,i,s=new Set,n=0,o=0;for(e=0,i=t.length;et+e))/s.size,y:n/o}},nearest(t,e){if(!t.length)return!1;let i,s,n,o=e.x,a=e.y,r=Number.POSITIVE_INFINITY;for(i=0,s=t.length;i-1?t.split("\n"):t}function Aa(t,e){const{element:i,datasetIndex:s,index:n}=e,o=t.getDatasetMeta(s).controller,{label:a,value:r}=o.getLabelAndValue(n);return{chart:t,label:a,parsed:o.getParsed(n),raw:t.data.datasets[s].data[n],formattedValue:r,dataset:o.getDataset(),dataIndex:n,datasetIndex:s,element:i}}function Ta(t,e){const i=t.chart.ctx,{body:s,footer:n,title:o}=t,{boxWidth:a,boxHeight:r}=e,l=Si(e.bodyFont),h=Si(e.titleFont),c=Si(e.footerFont),d=o.length,f=n.length,g=s.length,p=ki(e.padding);let m=p.height,x=0,b=s.reduce(((t,e)=>t+e.before.length+e.lines.length+e.after.length),0);if(b+=t.beforeBody.length+t.afterBody.length,d&&(m+=d*h.lineHeight+(d-1)*e.titleSpacing+e.titleMarginBottom),b){m+=g*(e.displayColors?Math.max(r,l.lineHeight):l.lineHeight)+(b-g)*l.lineHeight+(b-1)*e.bodySpacing}f&&(m+=e.footerMarginTop+f*c.lineHeight+(f-1)*e.footerSpacing);let _=0;const y=function(t){x=Math.max(x,i.measureText(t).width+_)};return i.save(),i.font=h.string,u(t.title,y),i.font=l.string,u(t.beforeBody.concat(t.afterBody),y),_=e.displayColors?a+2+e.boxPadding:0,u(s,(t=>{u(t.before,y),u(t.lines,y),u(t.after,y)})),_=0,i.font=c.string,u(t.footer,y),i.restore(),x+=p.width,{width:x,height:m}}function La(t,e,i,s){const{x:n,width:o}=i,{width:a,chartArea:{left:r,right:l}}=t;let h="center";return"center"===s?h=n<=(r+l)/2?"left":"right":n<=o/2?h="left":n>=a-o/2&&(h="right"),function(t,e,i,s){const{x:n,width:o}=s,a=i.caretSize+i.caretPadding;return"left"===t&&n+o+a>e.width||"right"===t&&n-o-a<0||void 0}(h,t,e,i)&&(h="center"),h}function Ea(t,e,i){const s=i.yAlign||e.yAlign||function(t,e){const{y:i,height:s}=e;return it.height-s/2?"bottom":"center"}(t,i);return{xAlign:i.xAlign||e.xAlign||La(t,e,i,s),yAlign:s}}function Ra(t,e,i,s){const{caretSize:n,caretPadding:o,cornerRadius:a}=t,{xAlign:r,yAlign:l}=i,h=n+o,{topLeft:c,topRight:d,bottomLeft:u,bottomRight:f}=wi(a);let g=function(t,e){let{x:i,width:s}=t;return"right"===e?i-=s:"center"===e&&(i-=s/2),i}(e,r);const p=function(t,e,i){let{y:s,height:n}=t;return"top"===e?s+=i:s-="bottom"===e?n+i:n/2,s}(e,l,h);return"center"===l?"left"===r?g+=h:"right"===r&&(g-=h):"left"===r?g-=Math.max(c,u)+n:"right"===r&&(g+=Math.max(d,f)+n),{x:Z(g,0,s.width-e.width),y:Z(p,0,s.height-e.height)}}function Ia(t,e,i){const s=ki(i.padding);return"center"===e?t.x+t.width/2:"right"===e?t.x+t.width-s.right:t.x+s.left}function za(t){return Ca([],Oa(t))}function Fa(t,e){const i=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return i?t.override(i):t}const Va={beforeTitle:e,title(t){if(t.length>0){const e=t[0],i=e.chart.data.labels,s=i?i.length:0;if(this&&this.options&&"dataset"===this.options.mode)return e.dataset.label||"";if(e.label)return e.label;if(s>0&&e.dataIndex{const e={before:[],lines:[],after:[]},n=Fa(i,t);Ca(e.before,Oa(Ba(n,"beforeLabel",this,t))),Ca(e.lines,Ba(n,"label",this,t)),Ca(e.after,Oa(Ba(n,"afterLabel",this,t))),s.push(e)})),s}getAfterBody(t,e){return za(Ba(e.callbacks,"afterBody",this,t))}getFooter(t,e){const{callbacks:i}=e,s=Ba(i,"beforeFooter",this,t),n=Ba(i,"footer",this,t),o=Ba(i,"afterFooter",this,t);let a=[];return a=Ca(a,Oa(s)),a=Ca(a,Oa(n)),a=Ca(a,Oa(o)),a}_createItems(t){const e=this._active,i=this.chart.data,s=[],n=[],o=[];let a,r,l=[];for(a=0,r=e.length;at.filter(e,s,n,i)))),t.itemSort&&(l=l.sort(((e,s)=>t.itemSort(e,s,i)))),u(l,(e=>{const i=Fa(t.callbacks,e);s.push(Ba(i,"labelColor",this,e)),n.push(Ba(i,"labelPointStyle",this,e)),o.push(Ba(i,"labelTextColor",this,e))})),this.labelColors=s,this.labelPointStyles=n,this.labelTextColors=o,this.dataPoints=l,l}update(t,e){const i=this.options.setContext(this.getContext()),s=this._active;let n,o=[];if(s.length){const t=Da[i.position].call(this,s,this._eventPosition);o=this._createItems(i),this.title=this.getTitle(o,i),this.beforeBody=this.getBeforeBody(o,i),this.body=this.getBody(o,i),this.afterBody=this.getAfterBody(o,i),this.footer=this.getFooter(o,i);const e=this._size=Ta(this,i),a=Object.assign({},t,e),r=Ea(this.chart,i,a),l=Ra(i,a,r,this.chart);this.xAlign=r.xAlign,this.yAlign=r.yAlign,n={opacity:1,x:l.x,y:l.y,width:e.width,height:e.height,caretX:t.x,caretY:t.y}}else 0!==this.opacity&&(n={opacity:0});this._tooltipItems=o,this.$context=void 0,n&&this._resolveAnimations().update(this,n),t&&i.external&&i.external.call(this,{chart:this.chart,tooltip:this,replay:e})}drawCaret(t,e,i,s){const n=this.getCaretPosition(t,i,s);e.lineTo(n.x1,n.y1),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3)}getCaretPosition(t,e,i){const{xAlign:s,yAlign:n}=this,{caretSize:o,cornerRadius:a}=i,{topLeft:r,topRight:l,bottomLeft:h,bottomRight:c}=wi(a),{x:d,y:u}=t,{width:f,height:g}=e;let p,m,x,b,_,y;return"center"===n?(_=u+g/2,"left"===s?(p=d,m=p-o,b=_+o,y=_-o):(p=d+f,m=p+o,b=_-o,y=_+o),x=p):(m="left"===s?d+Math.max(r,h)+o:"right"===s?d+f-Math.max(l,c)-o:this.caretX,"top"===n?(b=u,_=b-o,p=m-o,x=m+o):(b=u+g,_=b+o,p=m+o,x=m-o),y=b),{x1:p,x2:m,x3:x,y1:b,y2:_,y3:y}}drawTitle(t,e,i){const s=this.title,n=s.length;let o,a,r;if(n){const l=Oi(i.rtl,this.x,this.width);for(t.x=Ia(this,i.titleAlign,i),e.textAlign=l.textAlign(i.titleAlign),e.textBaseline="middle",o=Si(i.titleFont),a=i.titleSpacing,e.fillStyle=i.titleColor,e.font=o.string,r=0;r0!==t))?(t.beginPath(),t.fillStyle=n.multiKeyBackground,He(t,{x:e,y:g,w:h,h:l,radius:r}),t.fill(),t.stroke(),t.fillStyle=a.backgroundColor,t.beginPath(),He(t,{x:i,y:g+1,w:h-2,h:l-2,radius:r}),t.fill()):(t.fillStyle=n.multiKeyBackground,t.fillRect(e,g,h,l),t.strokeRect(e,g,h,l),t.fillStyle=a.backgroundColor,t.fillRect(i,g+1,h-2,l-2))}t.fillStyle=this.labelTextColors[i]}drawBody(t,e,i){const{body:s}=this,{bodySpacing:n,bodyAlign:o,displayColors:a,boxHeight:r,boxWidth:l,boxPadding:h}=i,c=Si(i.bodyFont);let d=c.lineHeight,f=0;const g=Oi(i.rtl,this.x,this.width),p=function(i){e.fillText(i,g.x(t.x+f),t.y+d/2),t.y+=d+n},m=g.textAlign(o);let x,b,_,y,v,M,w;for(e.textAlign=o,e.textBaseline="middle",e.font=c.string,t.x=Ia(this,m,i),e.fillStyle=i.bodyColor,u(this.beforeBody,p),f=a&&"right"!==m?"center"===o?l/2+h:l+2+h:0,y=0,M=s.length;y0&&e.stroke()}_updateAnimationTarget(t){const e=this.chart,i=this.$animations,s=i&&i.x,n=i&&i.y;if(s||n){const i=Da[t.position].call(this,this._active,this._eventPosition);if(!i)return;const o=this._size=Ta(this,t),a=Object.assign({},i,this._size),r=Ea(e,t,a),l=Ra(t,a,r,e);s._to===l.x&&n._to===l.y||(this.xAlign=r.xAlign,this.yAlign=r.yAlign,this.width=o.width,this.height=o.height,this.caretX=i.x,this.caretY=i.y,this._resolveAnimations().update(this,l))}}_willRender(){return!!this.opacity}draw(t){const e=this.options.setContext(this.getContext());let i=this.opacity;if(!i)return;this._updateAnimationTarget(e);const s={width:this.width,height:this.height},n={x:this.x,y:this.y};i=Math.abs(i)<.001?0:i;const o=ki(e.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;e.enabled&&a&&(t.save(),t.globalAlpha=i,this.drawBackground(n,t,s,e),Ai(t,e.textDirection),n.y+=o.top,this.drawTitle(n,t,e),this.drawBody(n,t,e),this.drawFooter(n,t,e),Ti(t,e.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,e){const i=this._active,s=t.map((({datasetIndex:t,index:e})=>{const i=this.chart.getDatasetMeta(t);if(!i)throw new Error("Cannot find a dataset at index "+t);return{datasetIndex:t,element:i.data[e],index:e}})),n=!f(i,s),o=this._positionChanged(s,e);(n||o)&&(this._active=s,this._eventPosition=e,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,e,i=!0){if(e&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const s=this.options,n=this._active||[],o=this._getActiveElements(t,n,e,i),a=this._positionChanged(o,t),r=e||!f(o,n)||a;return r&&(this._active=o,(s.enabled||s.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,e))),r}_getActiveElements(t,e,i,s){const n=this.options;if("mouseout"===t.type)return[];if(!s)return e.filter((t=>this.chart.data.datasets[t.datasetIndex]&&void 0!==this.chart.getDatasetMeta(t.datasetIndex).controller.getParsed(t.index)));const o=this.chart.getElementsAtEventForMode(t,n.mode,n,i);return n.reverse&&o.reverse(),o}_positionChanged(t,e){const{caretX:i,caretY:s,options:n}=this,o=Da[n.position].call(this,t,e);return!1!==o&&(i!==o.x||s!==o.y)}}var Na={id:"tooltip",_element:Wa,positioners:Da,afterInit(t,e,i){i&&(t.tooltip=new Wa({chart:t,options:i}))},beforeUpdate(t,e,i){t.tooltip&&t.tooltip.initialize(i)},reset(t,e,i){t.tooltip&&t.tooltip.initialize(i)},afterDraw(t){const e=t.tooltip;if(e&&e._willRender()){const i={tooltip:e};if(!1===t.notifyPlugins("beforeTooltipDraw",{...i,cancelable:!0}))return;e.draw(t.ctx),t.notifyPlugins("afterTooltipDraw",i)}},afterEvent(t,e){if(t.tooltip){const i=e.replay;t.tooltip.handleEvent(e.event,i,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(t,e)=>e.bodyFont.size,boxWidth:(t,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:Va},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:t=>"filter"!==t&&"itemSort"!==t&&"external"!==t,_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]};return Tn.register(Un,$o,go,t),Tn.helpers={...Hi},Tn._adapters=In,Tn.Animation=As,Tn.Animations=Ts,Tn.animator=bt,Tn.controllers=nn.controllers.items,Tn.DatasetController=js,Tn.Element=$s,Tn.elements=go,Tn.Interaction=Ki,Tn.layouts=ls,Tn.platforms=Ds,Tn.Scale=tn,Tn.Ticks=ae,Object.assign(Tn,Un,$o,go,t,Ds),Tn.Chart=Tn,"undefined"!=typeof window&&(window.Chart=Tn),Tn})); +//# sourceMappingURL=chart.umd.js.map diff --git a/frontend/node_modules/chart.js/dist/chart.umd.js.map b/frontend/node_modules/chart.js/dist/chart.umd.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9aa50e31ee7166c497b0c19be3b7a5aaaf8b880f --- /dev/null +++ b/frontend/node_modules/chart.js/dist/chart.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chart.umd.js","sources":["../src/helpers/helpers.core.ts","../src/helpers/helpers.math.ts","../src/helpers/helpers.collection.ts","../src/helpers/helpers.extras.ts","../src/core/core.animator.js","../node_modules/.pnpm/@kurkle+color@0.3.2/node_modules/@kurkle/color/dist/color.esm.js","../src/helpers/helpers.color.ts","../src/core/core.animations.defaults.js","../src/helpers/helpers.intl.ts","../src/core/core.ticks.js","../src/core/core.defaults.js","../src/core/core.layouts.defaults.js","../src/core/core.scale.defaults.js","../src/helpers/helpers.dom.ts","../src/helpers/helpers.canvas.ts","../src/helpers/helpers.config.ts","../src/helpers/helpers.curve.ts","../src/helpers/helpers.easing.ts","../src/helpers/helpers.interpolation.ts","../src/helpers/helpers.options.ts","../src/helpers/helpers.rtl.ts","../src/helpers/helpers.segment.js","../src/helpers/helpers.dataset.ts","../src/core/core.interaction.js","../src/core/core.layouts.js","../src/platform/platform.base.js","../src/platform/platform.basic.js","../src/platform/platform.dom.js","../src/platform/index.js","../src/core/core.animation.js","../src/core/core.animations.js","../src/core/core.datasetController.js","../src/core/core.element.ts","../src/core/core.scale.autoskip.js","../src/core/core.scale.js","../src/core/core.typedRegistry.js","../src/core/core.registry.js","../src/core/core.plugins.js","../src/core/core.config.js","../src/core/core.controller.js","../src/core/core.adapters.ts","../src/controllers/controller.bar.js","../src/controllers/controller.doughnut.js","../src/controllers/controller.polarArea.js","../src/controllers/controller.bubble.js","../src/controllers/controller.line.js","../src/controllers/controller.pie.js","../src/controllers/controller.radar.js","../src/controllers/controller.scatter.js","../src/elements/element.arc.ts","../src/elements/element.line.js","../src/elements/element.point.ts","../src/elements/element.bar.js","../src/scales/scale.category.js","../src/scales/scale.linearbase.js","../src/scales/scale.linear.js","../src/scales/scale.logarithmic.js","../src/scales/scale.radialLinear.js","../src/scales/scale.time.js","../src/scales/scale.timeseries.js","../src/plugins/plugin.colors.ts","../src/plugins/plugin.decimation.js","../src/plugins/plugin.filler/filler.segment.js","../src/plugins/plugin.filler/filler.helper.js","../src/plugins/plugin.filler/filler.options.js","../src/plugins/plugin.filler/filler.target.stack.js","../src/plugins/plugin.filler/simpleArc.js","../src/plugins/plugin.filler/filler.target.js","../src/plugins/plugin.filler/filler.drawing.js","../src/plugins/plugin.filler/index.js","../src/plugins/plugin.legend.js","../src/plugins/plugin.title.js","../src/plugins/plugin.subtitle.js","../src/plugins/plugin.tooltip.js","../src/index.umd.ts"],"sourcesContent":["/**\n * @namespace Chart.helpers\n */\n\nimport type {AnyObject} from '../types/basic.js';\nimport type {ActiveDataPoint, ChartEvent} from '../types/index.js';\n\n/**\n * An empty function that can be used, for example, for optional callback.\n */\nexport function noop() {\n /* noop */\n}\n\n/**\n * Returns a unique id, sequentially generated from a global variable.\n */\nexport const uid = (() => {\n let id = 0;\n return () => id++;\n})();\n\n/**\n * Returns true if `value` is neither null nor undefined, else returns false.\n * @param value - The value to test.\n * @since 2.7.0\n */\nexport function isNullOrUndef(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/**\n * Returns true if `value` is an array (including typed arrays), else returns false.\n * @param value - The value to test.\n * @function\n */\nexport function isArray(value: unknown): value is T[] {\n if (Array.isArray && Array.isArray(value)) {\n return true;\n }\n const type = Object.prototype.toString.call(value);\n if (type.slice(0, 7) === '[object' && type.slice(-6) === 'Array]') {\n return true;\n }\n return false;\n}\n\n/**\n * Returns true if `value` is an object (excluding null), else returns false.\n * @param value - The value to test.\n * @since 2.7.0\n */\nexport function isObject(value: unknown): value is AnyObject {\n return value !== null && Object.prototype.toString.call(value) === '[object Object]';\n}\n\n/**\n * Returns true if `value` is a finite number, else returns false\n * @param value - The value to test.\n */\nfunction isNumberFinite(value: unknown): value is number {\n return (typeof value === 'number' || value instanceof Number) && isFinite(+value);\n}\nexport {\n isNumberFinite as isFinite,\n};\n\n/**\n * Returns `value` if finite, else returns `defaultValue`.\n * @param value - The value to return if defined.\n * @param defaultValue - The value to return if `value` is not finite.\n */\nexport function finiteOrDefault(value: unknown, defaultValue: number) {\n return isNumberFinite(value) ? value : defaultValue;\n}\n\n/**\n * Returns `value` if defined, else returns `defaultValue`.\n * @param value - The value to return if defined.\n * @param defaultValue - The value to return if `value` is undefined.\n */\nexport function valueOrDefault(value: T | undefined, defaultValue: T) {\n return typeof value === 'undefined' ? defaultValue : value;\n}\n\nexport const toPercentage = (value: number | string, dimension: number) =>\n typeof value === 'string' && value.endsWith('%') ?\n parseFloat(value) / 100\n : +value / dimension;\n\nexport const toDimension = (value: number | string, dimension: number) =>\n typeof value === 'string' && value.endsWith('%') ?\n parseFloat(value) / 100 * dimension\n : +value;\n\n/**\n * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the\n * value returned by `fn`. If `fn` is not a function, this method returns undefined.\n * @param fn - The function to call.\n * @param args - The arguments with which `fn` should be called.\n * @param [thisArg] - The value of `this` provided for the call to `fn`.\n */\nexport function callback R, TA, R>(\n fn: T | undefined,\n args: unknown[],\n thisArg?: TA\n): R | undefined {\n if (fn && typeof fn.call === 'function') {\n return fn.apply(thisArg, args);\n }\n}\n\n/**\n * Note(SB) for performance sake, this method should only be used when loopable type\n * is unknown or in none intensive code (not called often and small loopable). Else\n * it's preferable to use a regular for() loop and save extra function calls.\n * @param loopable - The object or array to be iterated.\n * @param fn - The function to call for each item.\n * @param [thisArg] - The value of `this` provided for the call to `fn`.\n * @param [reverse] - If true, iterates backward on the loopable.\n */\nexport function each(\n loopable: Record,\n fn: (this: TA, v: T, i: string) => void,\n thisArg?: TA,\n reverse?: boolean\n): void;\nexport function each(\n loopable: T[],\n fn: (this: TA, v: T, i: number) => void,\n thisArg?: TA,\n reverse?: boolean\n): void;\nexport function each(\n loopable: T[] | Record,\n fn: (this: TA, v: T, i: any) => void,\n thisArg?: TA,\n reverse?: boolean\n) {\n let i: number, len: number, keys: string[];\n if (isArray(loopable)) {\n len = loopable.length;\n if (reverse) {\n for (i = len - 1; i >= 0; i--) {\n fn.call(thisArg, loopable[i], i);\n }\n } else {\n for (i = 0; i < len; i++) {\n fn.call(thisArg, loopable[i], i);\n }\n }\n } else if (isObject(loopable)) {\n keys = Object.keys(loopable);\n len = keys.length;\n for (i = 0; i < len; i++) {\n fn.call(thisArg, loopable[keys[i]], keys[i]);\n }\n }\n}\n\n/**\n * Returns true if the `a0` and `a1` arrays have the same content, else returns false.\n * @param a0 - The array to compare\n * @param a1 - The array to compare\n * @private\n */\nexport function _elementsEqual(a0: ActiveDataPoint[], a1: ActiveDataPoint[]) {\n let i: number, ilen: number, v0: ActiveDataPoint, v1: ActiveDataPoint;\n\n if (!a0 || !a1 || a0.length !== a1.length) {\n return false;\n }\n\n for (i = 0, ilen = a0.length; i < ilen; ++i) {\n v0 = a0[i];\n v1 = a1[i];\n\n if (v0.datasetIndex !== v1.datasetIndex || v0.index !== v1.index) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Returns a deep copy of `source` without keeping references on objects and arrays.\n * @param source - The value to clone.\n */\nexport function clone(source: T): T {\n if (isArray(source)) {\n return source.map(clone) as unknown as T;\n }\n\n if (isObject(source)) {\n const target = Object.create(null);\n const keys = Object.keys(source);\n const klen = keys.length;\n let k = 0;\n\n for (; k < klen; ++k) {\n target[keys[k]] = clone(source[keys[k]]);\n }\n\n return target;\n }\n\n return source;\n}\n\nfunction isValidKey(key: string) {\n return ['__proto__', 'prototype', 'constructor'].indexOf(key) === -1;\n}\n\n/**\n * The default merger when Chart.helpers.merge is called without merger option.\n * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.\n * @private\n */\nexport function _merger(key: string, target: AnyObject, source: AnyObject, options: AnyObject) {\n if (!isValidKey(key)) {\n return;\n }\n\n const tval = target[key];\n const sval = source[key];\n\n if (isObject(tval) && isObject(sval)) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n merge(tval, sval, options);\n } else {\n target[key] = clone(sval);\n }\n}\n\nexport interface MergeOptions {\n merger?: (key: string, target: AnyObject, source: AnyObject, options?: AnyObject) => void;\n}\n\n/**\n * Recursively deep copies `source` properties into `target` with the given `options`.\n * IMPORTANT: `target` is not cloned and will be updated with `source` properties.\n * @param target - The target object in which all sources are merged into.\n * @param source - Object(s) to merge into `target`.\n * @param [options] - Merging options:\n * @param [options.merger] - The merge method (key, target, source, options)\n * @returns The `target` object.\n */\nexport function merge(target: T, source: [], options?: MergeOptions): T;\nexport function merge(target: T, source: S1, options?: MergeOptions): T & S1;\nexport function merge(target: T, source: [S1], options?: MergeOptions): T & S1;\nexport function merge(target: T, source: [S1, S2], options?: MergeOptions): T & S1 & S2;\nexport function merge(target: T, source: [S1, S2, S3], options?: MergeOptions): T & S1 & S2 & S3;\nexport function merge(\n target: T,\n source: [S1, S2, S3, S4],\n options?: MergeOptions\n): T & S1 & S2 & S3 & S4;\nexport function merge(target: T, source: AnyObject[], options?: MergeOptions): AnyObject;\nexport function merge(target: T, source: AnyObject[], options?: MergeOptions): AnyObject {\n const sources = isArray(source) ? source : [source];\n const ilen = sources.length;\n\n if (!isObject(target)) {\n return target as AnyObject;\n }\n\n options = options || {};\n const merger = options.merger || _merger;\n let current: AnyObject;\n\n for (let i = 0; i < ilen; ++i) {\n current = sources[i];\n if (!isObject(current)) {\n continue;\n }\n\n const keys = Object.keys(current);\n for (let k = 0, klen = keys.length; k < klen; ++k) {\n merger(keys[k], target, current, options as AnyObject);\n }\n }\n\n return target;\n}\n\n/**\n * Recursively deep copies `source` properties into `target` *only* if not defined in target.\n * IMPORTANT: `target` is not cloned and will be updated with `source` properties.\n * @param target - The target object in which all sources are merged into.\n * @param source - Object(s) to merge into `target`.\n * @returns The `target` object.\n */\nexport function mergeIf(target: T, source: []): T;\nexport function mergeIf(target: T, source: S1): T & S1;\nexport function mergeIf(target: T, source: [S1]): T & S1;\nexport function mergeIf(target: T, source: [S1, S2]): T & S1 & S2;\nexport function mergeIf(target: T, source: [S1, S2, S3]): T & S1 & S2 & S3;\nexport function mergeIf(target: T, source: [S1, S2, S3, S4]): T & S1 & S2 & S3 & S4;\nexport function mergeIf(target: T, source: AnyObject[]): AnyObject;\nexport function mergeIf(target: T, source: AnyObject[]): AnyObject {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return merge(target, source, {merger: _mergerIf});\n}\n\n/**\n * Merges source[key] in target[key] only if target[key] is undefined.\n * @private\n */\nexport function _mergerIf(key: string, target: AnyObject, source: AnyObject) {\n if (!isValidKey(key)) {\n return;\n }\n\n const tval = target[key];\n const sval = source[key];\n\n if (isObject(tval) && isObject(sval)) {\n mergeIf(tval, sval);\n } else if (!Object.prototype.hasOwnProperty.call(target, key)) {\n target[key] = clone(sval);\n }\n}\n\n/**\n * @private\n */\nexport function _deprecated(scope: string, value: unknown, previous: string, current: string) {\n if (value !== undefined) {\n console.warn(scope + ': \"' + previous +\n '\" is deprecated. Please use \"' + current + '\" instead');\n }\n}\n\n// resolveObjectKey resolver cache\nconst keyResolvers = {\n // Chart.helpers.core resolveObjectKey should resolve empty key to root object\n '': v => v,\n // default resolvers\n x: o => o.x,\n y: o => o.y\n};\n\n/**\n * @private\n */\nexport function _splitKey(key: string) {\n const parts = key.split('.');\n const keys: string[] = [];\n let tmp = '';\n for (const part of parts) {\n tmp += part;\n if (tmp.endsWith('\\\\')) {\n tmp = tmp.slice(0, -1) + '.';\n } else {\n keys.push(tmp);\n tmp = '';\n }\n }\n return keys;\n}\n\nfunction _getKeyResolver(key: string) {\n const keys = _splitKey(key);\n return obj => {\n for (const k of keys) {\n if (k === '') {\n // For backward compatibility:\n // Chart.helpers.core resolveObjectKey should break at empty key\n break;\n }\n obj = obj && obj[k];\n }\n return obj;\n };\n}\n\nexport function resolveObjectKey(obj: AnyObject, key: string): any {\n const resolver = keyResolvers[key] || (keyResolvers[key] = _getKeyResolver(key));\n return resolver(obj);\n}\n\n/**\n * @private\n */\nexport function _capitalize(str: string) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n\nexport const defined = (value: unknown) => typeof value !== 'undefined';\n\nexport const isFunction = (value: unknown): value is (...args: any[]) => any => typeof value === 'function';\n\n// Adapted from https://stackoverflow.com/questions/31128855/comparing-ecma6-sets-for-equality#31129384\nexport const setsEqual = (a: Set, b: Set) => {\n if (a.size !== b.size) {\n return false;\n }\n\n for (const item of a) {\n if (!b.has(item)) {\n return false;\n }\n }\n\n return true;\n};\n\n/**\n * @param e - The event\n * @private\n */\nexport function _isClickEvent(e: ChartEvent) {\n return e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu';\n}\n","import type {Point} from '../types/geometric.js';\nimport {isFinite as isFiniteNumber} from './helpers.core.js';\n\n/**\n * @alias Chart.helpers.math\n * @namespace\n */\n\nexport const PI = Math.PI;\nexport const TAU = 2 * PI;\nexport const PITAU = TAU + PI;\nexport const INFINITY = Number.POSITIVE_INFINITY;\nexport const RAD_PER_DEG = PI / 180;\nexport const HALF_PI = PI / 2;\nexport const QUARTER_PI = PI / 4;\nexport const TWO_THIRDS_PI = PI * 2 / 3;\n\nexport const log10 = Math.log10;\nexport const sign = Math.sign;\n\nexport function almostEquals(x: number, y: number, epsilon: number) {\n return Math.abs(x - y) < epsilon;\n}\n\n/**\n * Implementation of the nice number algorithm used in determining where axis labels will go\n */\nexport function niceNum(range: number) {\n const roundedRange = Math.round(range);\n range = almostEquals(range, roundedRange, range / 1000) ? roundedRange : range;\n const niceRange = Math.pow(10, Math.floor(log10(range)));\n const fraction = range / niceRange;\n const niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10;\n return niceFraction * niceRange;\n}\n\n/**\n * Returns an array of factors sorted from 1 to sqrt(value)\n * @private\n */\nexport function _factorize(value: number) {\n const result: number[] = [];\n const sqrt = Math.sqrt(value);\n let i: number;\n\n for (i = 1; i < sqrt; i++) {\n if (value % i === 0) {\n result.push(i);\n result.push(value / i);\n }\n }\n if (sqrt === (sqrt | 0)) { // if value is a square number\n result.push(sqrt);\n }\n\n result.sort((a, b) => a - b).pop();\n return result;\n}\n\n/**\n * Verifies that attempting to coerce n to string or number won't throw a TypeError.\n */\nfunction isNonPrimitive(n: unknown) {\n return typeof n === 'symbol' || (typeof n === 'object' && n !== null && !(Symbol.toPrimitive in n || 'toString' in n || 'valueOf' in n));\n}\n\nexport function isNumber(n: unknown): n is number {\n return !isNonPrimitive(n) && !isNaN(parseFloat(n as string)) && isFinite(n as number);\n}\n\nexport function almostWhole(x: number, epsilon: number) {\n const rounded = Math.round(x);\n return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);\n}\n\n/**\n * @private\n */\nexport function _setMinAndMaxByKey(\n array: Record[],\n target: { min: number, max: number },\n property: string\n) {\n let i: number, ilen: number, value: number;\n\n for (i = 0, ilen = array.length; i < ilen; i++) {\n value = array[i][property];\n if (!isNaN(value)) {\n target.min = Math.min(target.min, value);\n target.max = Math.max(target.max, value);\n }\n }\n}\n\nexport function toRadians(degrees: number) {\n return degrees * (PI / 180);\n}\n\nexport function toDegrees(radians: number) {\n return radians * (180 / PI);\n}\n\n/**\n * Returns the number of decimal places\n * i.e. the number of digits after the decimal point, of the value of this Number.\n * @param x - A number.\n * @returns The number of decimal places.\n * @private\n */\nexport function _decimalPlaces(x: number) {\n if (!isFiniteNumber(x)) {\n return;\n }\n let e = 1;\n let p = 0;\n while (Math.round(x * e) / e !== x) {\n e *= 10;\n p++;\n }\n return p;\n}\n\n// Gets the angle from vertical upright to the point about a centre.\nexport function getAngleFromPoint(\n centrePoint: Point,\n anglePoint: Point\n) {\n const distanceFromXCenter = anglePoint.x - centrePoint.x;\n const distanceFromYCenter = anglePoint.y - centrePoint.y;\n const radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);\n\n let angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);\n\n if (angle < (-0.5 * PI)) {\n angle += TAU; // make sure the returned angle is in the range of (-PI/2, 3PI/2]\n }\n\n return {\n angle,\n distance: radialDistanceFromCenter\n };\n}\n\nexport function distanceBetweenPoints(pt1: Point, pt2: Point) {\n return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));\n}\n\n/**\n * Shortest distance between angles, in either direction.\n * @private\n */\nexport function _angleDiff(a: number, b: number) {\n return (a - b + PITAU) % TAU - PI;\n}\n\n/**\n * Normalize angle to be between 0 and 2*PI\n * @private\n */\nexport function _normalizeAngle(a: number) {\n return (a % TAU + TAU) % TAU;\n}\n\n/**\n * @private\n */\nexport function _angleBetween(angle: number, start: number, end: number, sameAngleIsFullCircle?: boolean) {\n const a = _normalizeAngle(angle);\n const s = _normalizeAngle(start);\n const e = _normalizeAngle(end);\n const angleToStart = _normalizeAngle(s - a);\n const angleToEnd = _normalizeAngle(e - a);\n const startToAngle = _normalizeAngle(a - s);\n const endToAngle = _normalizeAngle(a - e);\n return a === s || a === e || (sameAngleIsFullCircle && s === e)\n || (angleToStart > angleToEnd && startToAngle < endToAngle);\n}\n\n/**\n * Limit `value` between `min` and `max`\n * @param value\n * @param min\n * @param max\n * @private\n */\nexport function _limitValue(value: number, min: number, max: number) {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * @param {number} value\n * @private\n */\nexport function _int16Range(value: number) {\n return _limitValue(value, -32768, 32767);\n}\n\n/**\n * @param value\n * @param start\n * @param end\n * @param [epsilon]\n * @private\n */\nexport function _isBetween(value: number, start: number, end: number, epsilon = 1e-6) {\n return value >= Math.min(start, end) - epsilon && value <= Math.max(start, end) + epsilon;\n}\n","import {_capitalize} from './helpers.core.js';\n\n/**\n * Binary search\n * @param table - the table search. must be sorted!\n * @param value - value to find\n * @param cmp\n * @private\n */\nexport function _lookup(\n table: number[],\n value: number,\n cmp?: (value: number) => boolean\n): {lo: number, hi: number};\nexport function _lookup(\n table: T[],\n value: number,\n cmp: (value: number) => boolean\n): {lo: number, hi: number};\nexport function _lookup(\n table: unknown[],\n value: number,\n cmp?: (value: number) => boolean\n) {\n cmp = cmp || ((index) => table[index] < value);\n let hi = table.length - 1;\n let lo = 0;\n let mid: number;\n\n while (hi - lo > 1) {\n mid = (lo + hi) >> 1;\n if (cmp(mid)) {\n lo = mid;\n } else {\n hi = mid;\n }\n }\n\n return {lo, hi};\n}\n\n/**\n * Binary search\n * @param table - the table search. must be sorted!\n * @param key - property name for the value in each entry\n * @param value - value to find\n * @param last - lookup last index\n * @private\n */\nexport const _lookupByKey = (\n table: Record[],\n key: string,\n value: number,\n last?: boolean\n) =>\n _lookup(table, value, last\n ? index => {\n const ti = table[index][key];\n return ti < value || ti === value && table[index + 1][key] === value;\n }\n : index => table[index][key] < value);\n\n/**\n * Reverse binary search\n * @param table - the table search. must be sorted!\n * @param key - property name for the value in each entry\n * @param value - value to find\n * @private\n */\nexport const _rlookupByKey = (\n table: Record[],\n key: string,\n value: number\n) =>\n _lookup(table, value, index => table[index][key] >= value);\n\n/**\n * Return subset of `values` between `min` and `max` inclusive.\n * Values are assumed to be in sorted order.\n * @param values - sorted array of values\n * @param min - min value\n * @param max - max value\n */\nexport function _filterBetween(values: number[], min: number, max: number) {\n let start = 0;\n let end = values.length;\n\n while (start < end && values[start] < min) {\n start++;\n }\n while (end > start && values[end - 1] > max) {\n end--;\n }\n\n return start > 0 || end < values.length\n ? values.slice(start, end)\n : values;\n}\n\nconst arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'] as const;\n\nexport interface ArrayListener {\n _onDataPush?(...item: T[]): void;\n _onDataPop?(): void;\n _onDataShift?(): void;\n _onDataSplice?(index: number, deleteCount: number, ...items: T[]): void;\n _onDataUnshift?(...item: T[]): void;\n}\n\n/**\n * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',\n * 'unshift') and notify the listener AFTER the array has been altered. Listeners are\n * called on the '_onData*' callbacks (e.g. _onDataPush, etc.) with same arguments.\n */\nexport function listenArrayEvents(array: T[], listener: ArrayListener): void;\nexport function listenArrayEvents(array, listener) {\n if (array._chartjs) {\n array._chartjs.listeners.push(listener);\n return;\n }\n\n Object.defineProperty(array, '_chartjs', {\n configurable: true,\n enumerable: false,\n value: {\n listeners: [listener]\n }\n });\n\n arrayEvents.forEach((key) => {\n const method = '_onData' + _capitalize(key);\n const base = array[key];\n\n Object.defineProperty(array, key, {\n configurable: true,\n enumerable: false,\n value(...args) {\n const res = base.apply(this, args);\n\n array._chartjs.listeners.forEach((object) => {\n if (typeof object[method] === 'function') {\n object[method](...args);\n }\n });\n\n return res;\n }\n });\n });\n}\n\n\n/**\n * Removes the given array event listener and cleanup extra attached properties (such as\n * the _chartjs stub and overridden methods) if array doesn't have any more listeners.\n */\nexport function unlistenArrayEvents(array: T[], listener: ArrayListener): void;\nexport function unlistenArrayEvents(array, listener) {\n const stub = array._chartjs;\n if (!stub) {\n return;\n }\n\n const listeners = stub.listeners;\n const index = listeners.indexOf(listener);\n if (index !== -1) {\n listeners.splice(index, 1);\n }\n\n if (listeners.length > 0) {\n return;\n }\n\n arrayEvents.forEach((key) => {\n delete array[key];\n });\n\n delete array._chartjs;\n}\n\n/**\n * @param items\n */\nexport function _arrayUnique(items: T[]) {\n const set = new Set(items);\n\n if (set.size === items.length) {\n return items;\n }\n\n return Array.from(set);\n}\n","import type {ChartMeta, PointElement} from '../types/index.js';\n\nimport {_limitValue} from './helpers.math.js';\nimport {_lookupByKey} from './helpers.collection.js';\nimport {isNullOrUndef} from './helpers.core.js';\n\nexport function fontString(pixelSize: number, fontStyle: string, fontFamily: string) {\n return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;\n}\n\n/**\n* Request animation polyfill\n*/\nexport const requestAnimFrame = (function() {\n if (typeof window === 'undefined') {\n return function(callback) {\n return callback();\n };\n }\n return window.requestAnimationFrame;\n}());\n\n/**\n * Throttles calling `fn` once per animation frame\n * Latest arguments are used on the actual call\n */\nexport function throttled>(\n fn: (...args: TArgs) => void,\n thisArg: any,\n) {\n let argsToUse = [] as TArgs;\n let ticking = false;\n\n return function(...args: TArgs) {\n // Save the args for use later\n argsToUse = args;\n if (!ticking) {\n ticking = true;\n requestAnimFrame.call(window, () => {\n ticking = false;\n fn.apply(thisArg, argsToUse);\n });\n }\n };\n}\n\n/**\n * Debounces calling `fn` for `delay` ms\n */\nexport function debounce>(fn: (...args: TArgs) => void, delay: number) {\n let timeout;\n return function(...args: TArgs) {\n if (delay) {\n clearTimeout(timeout);\n timeout = setTimeout(fn, delay, args);\n } else {\n fn.apply(this, args);\n }\n return delay;\n };\n}\n\n/**\n * Converts 'start' to 'left', 'end' to 'right' and others to 'center'\n * @private\n */\nexport const _toLeftRightCenter = (align: 'start' | 'end' | 'center') => align === 'start' ? 'left' : align === 'end' ? 'right' : 'center';\n\n/**\n * Returns `start`, `end` or `(start + end) / 2` depending on `align`. Defaults to `center`\n * @private\n */\nexport const _alignStartEnd = (align: 'start' | 'end' | 'center', start: number, end: number) => align === 'start' ? start : align === 'end' ? end : (start + end) / 2;\n\n/**\n * Returns `left`, `right` or `(left + right) / 2` depending on `align`. Defaults to `left`\n * @private\n */\nexport const _textX = (align: 'left' | 'right' | 'center', left: number, right: number, rtl: boolean) => {\n const check = rtl ? 'left' : 'right';\n return align === check ? right : align === 'center' ? (left + right) / 2 : left;\n};\n\n/**\n * Return start and count of visible points.\n * @private\n */\nexport function _getStartAndCountOfVisiblePoints(meta: ChartMeta<'line' | 'scatter'>, points: PointElement[], animationsDisabled: boolean) {\n const pointCount = points.length;\n\n let start = 0;\n let count = pointCount;\n\n if (meta._sorted) {\n const {iScale, vScale, _parsed} = meta;\n const spanGaps = meta.dataset ? meta.dataset.options ? meta.dataset.options.spanGaps : null : null;\n const axis = iScale.axis;\n const {min, max, minDefined, maxDefined} = iScale.getUserBounds();\n\n if (minDefined) {\n start = Math.min(\n // @ts-expect-error Need to type _parsed\n _lookupByKey(_parsed, axis, min).lo,\n // @ts-expect-error Need to fix types on _lookupByKey\n animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min)).lo);\n if (spanGaps) {\n const distanceToDefinedLo = (_parsed\n .slice(0, start + 1)\n .reverse()\n .findIndex(\n point => !isNullOrUndef(point[vScale.axis])));\n start -= Math.max(0, distanceToDefinedLo);\n }\n start = _limitValue(start, 0, pointCount - 1);\n }\n if (maxDefined) {\n let end = Math.max(\n // @ts-expect-error Need to type _parsed\n _lookupByKey(_parsed, iScale.axis, max, true).hi + 1,\n // @ts-expect-error Need to fix types on _lookupByKey\n animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max), true).hi + 1);\n if (spanGaps) {\n const distanceToDefinedHi = (_parsed\n .slice(end - 1)\n .findIndex(\n point => !isNullOrUndef(point[vScale.axis])));\n end += Math.max(0, distanceToDefinedHi);\n }\n count = _limitValue(end, start, pointCount) - start;\n } else {\n count = pointCount - start;\n }\n }\n\n return {start, count};\n}\n\n/**\n * Checks if the scale ranges have changed.\n * @param {object} meta - dataset meta.\n * @returns {boolean}\n * @private\n */\nexport function _scaleRangesChanged(meta) {\n const {xScale, yScale, _scaleRanges} = meta;\n const newRanges = {\n xmin: xScale.min,\n xmax: xScale.max,\n ymin: yScale.min,\n ymax: yScale.max\n };\n if (!_scaleRanges) {\n meta._scaleRanges = newRanges;\n return true;\n }\n const changed = _scaleRanges.xmin !== xScale.min\n\t\t|| _scaleRanges.xmax !== xScale.max\n\t\t|| _scaleRanges.ymin !== yScale.min\n\t\t|| _scaleRanges.ymax !== yScale.max;\n\n Object.assign(_scaleRanges, newRanges);\n return changed;\n}\n","import {requestAnimFrame} from '../helpers/helpers.extras.js';\n\n/**\n * @typedef { import('./core.animation.js').default } Animation\n * @typedef { import('./core.controller.js').default } Chart\n */\n\n/**\n * Please use the module's default export which provides a singleton instance\n * Note: class is export for typedoc\n */\nexport class Animator {\n constructor() {\n this._request = null;\n this._charts = new Map();\n this._running = false;\n this._lastDate = undefined;\n }\n\n /**\n\t * @private\n\t */\n _notify(chart, anims, date, type) {\n const callbacks = anims.listeners[type];\n const numSteps = anims.duration;\n\n callbacks.forEach(fn => fn({\n chart,\n initial: anims.initial,\n numSteps,\n currentStep: Math.min(date - anims.start, numSteps)\n }));\n }\n\n /**\n\t * @private\n\t */\n _refresh() {\n if (this._request) {\n return;\n }\n this._running = true;\n\n this._request = requestAnimFrame.call(window, () => {\n this._update();\n this._request = null;\n\n if (this._running) {\n this._refresh();\n }\n });\n }\n\n /**\n\t * @private\n\t */\n _update(date = Date.now()) {\n let remaining = 0;\n\n this._charts.forEach((anims, chart) => {\n if (!anims.running || !anims.items.length) {\n return;\n }\n const items = anims.items;\n let i = items.length - 1;\n let draw = false;\n let item;\n\n for (; i >= 0; --i) {\n item = items[i];\n\n if (item._active) {\n if (item._total > anims.duration) {\n // if the animation has been updated and its duration prolonged,\n // update to total duration of current animations run (for progress event)\n anims.duration = item._total;\n }\n item.tick(date);\n draw = true;\n } else {\n // Remove the item by replacing it with last item and removing the last\n // A lot faster than splice.\n items[i] = items[items.length - 1];\n items.pop();\n }\n }\n\n if (draw) {\n chart.draw();\n this._notify(chart, anims, date, 'progress');\n }\n\n if (!items.length) {\n anims.running = false;\n this._notify(chart, anims, date, 'complete');\n anims.initial = false;\n }\n\n remaining += items.length;\n });\n\n this._lastDate = date;\n\n if (remaining === 0) {\n this._running = false;\n }\n }\n\n /**\n\t * @private\n\t */\n _getAnims(chart) {\n const charts = this._charts;\n let anims = charts.get(chart);\n if (!anims) {\n anims = {\n running: false,\n initial: true,\n items: [],\n listeners: {\n complete: [],\n progress: []\n }\n };\n charts.set(chart, anims);\n }\n return anims;\n }\n\n /**\n\t * @param {Chart} chart\n\t * @param {string} event - event name\n\t * @param {Function} cb - callback\n\t */\n listen(chart, event, cb) {\n this._getAnims(chart).listeners[event].push(cb);\n }\n\n /**\n\t * Add animations\n\t * @param {Chart} chart\n\t * @param {Animation[]} items - animations\n\t */\n add(chart, items) {\n if (!items || !items.length) {\n return;\n }\n this._getAnims(chart).items.push(...items);\n }\n\n /**\n\t * Counts number of active animations for the chart\n\t * @param {Chart} chart\n\t */\n has(chart) {\n return this._getAnims(chart).items.length > 0;\n }\n\n /**\n\t * Start animating (all charts)\n\t * @param {Chart} chart\n\t */\n start(chart) {\n const anims = this._charts.get(chart);\n if (!anims) {\n return;\n }\n anims.running = true;\n anims.start = Date.now();\n anims.duration = anims.items.reduce((acc, cur) => Math.max(acc, cur._duration), 0);\n this._refresh();\n }\n\n running(chart) {\n if (!this._running) {\n return false;\n }\n const anims = this._charts.get(chart);\n if (!anims || !anims.running || !anims.items.length) {\n return false;\n }\n return true;\n }\n\n /**\n\t * Stop all animations for the chart\n\t * @param {Chart} chart\n\t */\n stop(chart) {\n const anims = this._charts.get(chart);\n if (!anims || !anims.items.length) {\n return;\n }\n const items = anims.items;\n let i = items.length - 1;\n\n for (; i >= 0; --i) {\n items[i].cancel();\n }\n anims.items = [];\n this._notify(chart, anims, Date.now(), 'complete');\n }\n\n /**\n\t * Remove chart from Animator\n\t * @param {Chart} chart\n\t */\n remove(chart) {\n return this._charts.delete(chart);\n }\n}\n\n// singleton instance\nexport default /* #__PURE__ */ new Animator();\n","/*!\n * @kurkle/color v0.3.2\n * https://github.com/kurkle/color#readme\n * (c) 2023 Jukka Kurkela\n * Released under the MIT License\n */\nfunction round(v) {\n return v + 0.5 | 0;\n}\nconst lim = (v, l, h) => Math.max(Math.min(v, h), l);\nfunction p2b(v) {\n return lim(round(v * 2.55), 0, 255);\n}\nfunction b2p(v) {\n return lim(round(v / 2.55), 0, 100);\n}\nfunction n2b(v) {\n return lim(round(v * 255), 0, 255);\n}\nfunction b2n(v) {\n return lim(round(v / 2.55) / 100, 0, 1);\n}\nfunction n2p(v) {\n return lim(round(v * 100), 0, 100);\n}\n\nconst map$1 = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, A: 10, B: 11, C: 12, D: 13, E: 14, F: 15, a: 10, b: 11, c: 12, d: 13, e: 14, f: 15};\nconst hex = [...'0123456789ABCDEF'];\nconst h1 = b => hex[b & 0xF];\nconst h2 = b => hex[(b & 0xF0) >> 4] + hex[b & 0xF];\nconst eq = b => ((b & 0xF0) >> 4) === (b & 0xF);\nconst isShort = v => eq(v.r) && eq(v.g) && eq(v.b) && eq(v.a);\nfunction hexParse(str) {\n var len = str.length;\n var ret;\n if (str[0] === '#') {\n if (len === 4 || len === 5) {\n ret = {\n r: 255 & map$1[str[1]] * 17,\n g: 255 & map$1[str[2]] * 17,\n b: 255 & map$1[str[3]] * 17,\n a: len === 5 ? map$1[str[4]] * 17 : 255\n };\n } else if (len === 7 || len === 9) {\n ret = {\n r: map$1[str[1]] << 4 | map$1[str[2]],\n g: map$1[str[3]] << 4 | map$1[str[4]],\n b: map$1[str[5]] << 4 | map$1[str[6]],\n a: len === 9 ? (map$1[str[7]] << 4 | map$1[str[8]]) : 255\n };\n }\n }\n return ret;\n}\nconst alpha = (a, f) => a < 255 ? f(a) : '';\nfunction hexString(v) {\n var f = isShort(v) ? h1 : h2;\n return v\n ? '#' + f(v.r) + f(v.g) + f(v.b) + alpha(v.a, f)\n : undefined;\n}\n\nconst HUE_RE = /^(hsla?|hwb|hsv)\\(\\s*([-+.e\\d]+)(?:deg)?[\\s,]+([-+.e\\d]+)%[\\s,]+([-+.e\\d]+)%(?:[\\s,]+([-+.e\\d]+)(%)?)?\\s*\\)$/;\nfunction hsl2rgbn(h, s, l) {\n const a = s * Math.min(l, 1 - l);\n const f = (n, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);\n return [f(0), f(8), f(4)];\n}\nfunction hsv2rgbn(h, s, v) {\n const f = (n, k = (n + h / 60) % 6) => v - v * s * Math.max(Math.min(k, 4 - k, 1), 0);\n return [f(5), f(3), f(1)];\n}\nfunction hwb2rgbn(h, w, b) {\n const rgb = hsl2rgbn(h, 1, 0.5);\n let i;\n if (w + b > 1) {\n i = 1 / (w + b);\n w *= i;\n b *= i;\n }\n for (i = 0; i < 3; i++) {\n rgb[i] *= 1 - w - b;\n rgb[i] += w;\n }\n return rgb;\n}\nfunction hueValue(r, g, b, d, max) {\n if (r === max) {\n return ((g - b) / d) + (g < b ? 6 : 0);\n }\n if (g === max) {\n return (b - r) / d + 2;\n }\n return (r - g) / d + 4;\n}\nfunction rgb2hsl(v) {\n const range = 255;\n const r = v.r / range;\n const g = v.g / range;\n const b = v.b / range;\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const l = (max + min) / 2;\n let h, s, d;\n if (max !== min) {\n d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n h = hueValue(r, g, b, d, max);\n h = h * 60 + 0.5;\n }\n return [h | 0, s || 0, l];\n}\nfunction calln(f, a, b, c) {\n return (\n Array.isArray(a)\n ? f(a[0], a[1], a[2])\n : f(a, b, c)\n ).map(n2b);\n}\nfunction hsl2rgb(h, s, l) {\n return calln(hsl2rgbn, h, s, l);\n}\nfunction hwb2rgb(h, w, b) {\n return calln(hwb2rgbn, h, w, b);\n}\nfunction hsv2rgb(h, s, v) {\n return calln(hsv2rgbn, h, s, v);\n}\nfunction hue(h) {\n return (h % 360 + 360) % 360;\n}\nfunction hueParse(str) {\n const m = HUE_RE.exec(str);\n let a = 255;\n let v;\n if (!m) {\n return;\n }\n if (m[5] !== v) {\n a = m[6] ? p2b(+m[5]) : n2b(+m[5]);\n }\n const h = hue(+m[2]);\n const p1 = +m[3] / 100;\n const p2 = +m[4] / 100;\n if (m[1] === 'hwb') {\n v = hwb2rgb(h, p1, p2);\n } else if (m[1] === 'hsv') {\n v = hsv2rgb(h, p1, p2);\n } else {\n v = hsl2rgb(h, p1, p2);\n }\n return {\n r: v[0],\n g: v[1],\n b: v[2],\n a: a\n };\n}\nfunction rotate(v, deg) {\n var h = rgb2hsl(v);\n h[0] = hue(h[0] + deg);\n h = hsl2rgb(h);\n v.r = h[0];\n v.g = h[1];\n v.b = h[2];\n}\nfunction hslString(v) {\n if (!v) {\n return;\n }\n const a = rgb2hsl(v);\n const h = a[0];\n const s = n2p(a[1]);\n const l = n2p(a[2]);\n return v.a < 255\n ? `hsla(${h}, ${s}%, ${l}%, ${b2n(v.a)})`\n : `hsl(${h}, ${s}%, ${l}%)`;\n}\n\nconst map = {\n x: 'dark',\n Z: 'light',\n Y: 're',\n X: 'blu',\n W: 'gr',\n V: 'medium',\n U: 'slate',\n A: 'ee',\n T: 'ol',\n S: 'or',\n B: 'ra',\n C: 'lateg',\n D: 'ights',\n R: 'in',\n Q: 'turquois',\n E: 'hi',\n P: 'ro',\n O: 'al',\n N: 'le',\n M: 'de',\n L: 'yello',\n F: 'en',\n K: 'ch',\n G: 'arks',\n H: 'ea',\n I: 'ightg',\n J: 'wh'\n};\nconst names$1 = {\n OiceXe: 'f0f8ff',\n antiquewEte: 'faebd7',\n aqua: 'ffff',\n aquamarRe: '7fffd4',\n azuY: 'f0ffff',\n beige: 'f5f5dc',\n bisque: 'ffe4c4',\n black: '0',\n blanKedOmond: 'ffebcd',\n Xe: 'ff',\n XeviTet: '8a2be2',\n bPwn: 'a52a2a',\n burlywood: 'deb887',\n caMtXe: '5f9ea0',\n KartYuse: '7fff00',\n KocTate: 'd2691e',\n cSO: 'ff7f50',\n cSnflowerXe: '6495ed',\n cSnsilk: 'fff8dc',\n crimson: 'dc143c',\n cyan: 'ffff',\n xXe: '8b',\n xcyan: '8b8b',\n xgTMnPd: 'b8860b',\n xWay: 'a9a9a9',\n xgYF: '6400',\n xgYy: 'a9a9a9',\n xkhaki: 'bdb76b',\n xmagFta: '8b008b',\n xTivegYF: '556b2f',\n xSange: 'ff8c00',\n xScEd: '9932cc',\n xYd: '8b0000',\n xsOmon: 'e9967a',\n xsHgYF: '8fbc8f',\n xUXe: '483d8b',\n xUWay: '2f4f4f',\n xUgYy: '2f4f4f',\n xQe: 'ced1',\n xviTet: '9400d3',\n dAppRk: 'ff1493',\n dApskyXe: 'bfff',\n dimWay: '696969',\n dimgYy: '696969',\n dodgerXe: '1e90ff',\n fiYbrick: 'b22222',\n flSOwEte: 'fffaf0',\n foYstWAn: '228b22',\n fuKsia: 'ff00ff',\n gaRsbSo: 'dcdcdc',\n ghostwEte: 'f8f8ff',\n gTd: 'ffd700',\n gTMnPd: 'daa520',\n Way: '808080',\n gYF: '8000',\n gYFLw: 'adff2f',\n gYy: '808080',\n honeyMw: 'f0fff0',\n hotpRk: 'ff69b4',\n RdianYd: 'cd5c5c',\n Rdigo: '4b0082',\n ivSy: 'fffff0',\n khaki: 'f0e68c',\n lavFMr: 'e6e6fa',\n lavFMrXsh: 'fff0f5',\n lawngYF: '7cfc00',\n NmoncEffon: 'fffacd',\n ZXe: 'add8e6',\n ZcSO: 'f08080',\n Zcyan: 'e0ffff',\n ZgTMnPdLw: 'fafad2',\n ZWay: 'd3d3d3',\n ZgYF: '90ee90',\n ZgYy: 'd3d3d3',\n ZpRk: 'ffb6c1',\n ZsOmon: 'ffa07a',\n ZsHgYF: '20b2aa',\n ZskyXe: '87cefa',\n ZUWay: '778899',\n ZUgYy: '778899',\n ZstAlXe: 'b0c4de',\n ZLw: 'ffffe0',\n lime: 'ff00',\n limegYF: '32cd32',\n lRF: 'faf0e6',\n magFta: 'ff00ff',\n maPon: '800000',\n VaquamarRe: '66cdaa',\n VXe: 'cd',\n VScEd: 'ba55d3',\n VpurpN: '9370db',\n VsHgYF: '3cb371',\n VUXe: '7b68ee',\n VsprRggYF: 'fa9a',\n VQe: '48d1cc',\n VviTetYd: 'c71585',\n midnightXe: '191970',\n mRtcYam: 'f5fffa',\n mistyPse: 'ffe4e1',\n moccasR: 'ffe4b5',\n navajowEte: 'ffdead',\n navy: '80',\n Tdlace: 'fdf5e6',\n Tive: '808000',\n TivedBb: '6b8e23',\n Sange: 'ffa500',\n SangeYd: 'ff4500',\n ScEd: 'da70d6',\n pOegTMnPd: 'eee8aa',\n pOegYF: '98fb98',\n pOeQe: 'afeeee',\n pOeviTetYd: 'db7093',\n papayawEp: 'ffefd5',\n pHKpuff: 'ffdab9',\n peru: 'cd853f',\n pRk: 'ffc0cb',\n plum: 'dda0dd',\n powMrXe: 'b0e0e6',\n purpN: '800080',\n YbeccapurpN: '663399',\n Yd: 'ff0000',\n Psybrown: 'bc8f8f',\n PyOXe: '4169e1',\n saddNbPwn: '8b4513',\n sOmon: 'fa8072',\n sandybPwn: 'f4a460',\n sHgYF: '2e8b57',\n sHshell: 'fff5ee',\n siFna: 'a0522d',\n silver: 'c0c0c0',\n skyXe: '87ceeb',\n UXe: '6a5acd',\n UWay: '708090',\n UgYy: '708090',\n snow: 'fffafa',\n sprRggYF: 'ff7f',\n stAlXe: '4682b4',\n tan: 'd2b48c',\n teO: '8080',\n tEstN: 'd8bfd8',\n tomato: 'ff6347',\n Qe: '40e0d0',\n viTet: 'ee82ee',\n JHt: 'f5deb3',\n wEte: 'ffffff',\n wEtesmoke: 'f5f5f5',\n Lw: 'ffff00',\n LwgYF: '9acd32'\n};\nfunction unpack() {\n const unpacked = {};\n const keys = Object.keys(names$1);\n const tkeys = Object.keys(map);\n let i, j, k, ok, nk;\n for (i = 0; i < keys.length; i++) {\n ok = nk = keys[i];\n for (j = 0; j < tkeys.length; j++) {\n k = tkeys[j];\n nk = nk.replace(k, map[k]);\n }\n k = parseInt(names$1[ok], 16);\n unpacked[nk] = [k >> 16 & 0xFF, k >> 8 & 0xFF, k & 0xFF];\n }\n return unpacked;\n}\n\nlet names;\nfunction nameParse(str) {\n if (!names) {\n names = unpack();\n names.transparent = [0, 0, 0, 0];\n }\n const a = names[str.toLowerCase()];\n return a && {\n r: a[0],\n g: a[1],\n b: a[2],\n a: a.length === 4 ? a[3] : 255\n };\n}\n\nconst RGB_RE = /^rgba?\\(\\s*([-+.\\d]+)(%)?[\\s,]+([-+.e\\d]+)(%)?[\\s,]+([-+.e\\d]+)(%)?(?:[\\s,/]+([-+.e\\d]+)(%)?)?\\s*\\)$/;\nfunction rgbParse(str) {\n const m = RGB_RE.exec(str);\n let a = 255;\n let r, g, b;\n if (!m) {\n return;\n }\n if (m[7] !== r) {\n const v = +m[7];\n a = m[8] ? p2b(v) : lim(v * 255, 0, 255);\n }\n r = +m[1];\n g = +m[3];\n b = +m[5];\n r = 255 & (m[2] ? p2b(r) : lim(r, 0, 255));\n g = 255 & (m[4] ? p2b(g) : lim(g, 0, 255));\n b = 255 & (m[6] ? p2b(b) : lim(b, 0, 255));\n return {\n r: r,\n g: g,\n b: b,\n a: a\n };\n}\nfunction rgbString(v) {\n return v && (\n v.a < 255\n ? `rgba(${v.r}, ${v.g}, ${v.b}, ${b2n(v.a)})`\n : `rgb(${v.r}, ${v.g}, ${v.b})`\n );\n}\n\nconst to = v => v <= 0.0031308 ? v * 12.92 : Math.pow(v, 1.0 / 2.4) * 1.055 - 0.055;\nconst from = v => v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);\nfunction interpolate(rgb1, rgb2, t) {\n const r = from(b2n(rgb1.r));\n const g = from(b2n(rgb1.g));\n const b = from(b2n(rgb1.b));\n return {\n r: n2b(to(r + t * (from(b2n(rgb2.r)) - r))),\n g: n2b(to(g + t * (from(b2n(rgb2.g)) - g))),\n b: n2b(to(b + t * (from(b2n(rgb2.b)) - b))),\n a: rgb1.a + t * (rgb2.a - rgb1.a)\n };\n}\n\nfunction modHSL(v, i, ratio) {\n if (v) {\n let tmp = rgb2hsl(v);\n tmp[i] = Math.max(0, Math.min(tmp[i] + tmp[i] * ratio, i === 0 ? 360 : 1));\n tmp = hsl2rgb(tmp);\n v.r = tmp[0];\n v.g = tmp[1];\n v.b = tmp[2];\n }\n}\nfunction clone(v, proto) {\n return v ? Object.assign(proto || {}, v) : v;\n}\nfunction fromObject(input) {\n var v = {r: 0, g: 0, b: 0, a: 255};\n if (Array.isArray(input)) {\n if (input.length >= 3) {\n v = {r: input[0], g: input[1], b: input[2], a: 255};\n if (input.length > 3) {\n v.a = n2b(input[3]);\n }\n }\n } else {\n v = clone(input, {r: 0, g: 0, b: 0, a: 1});\n v.a = n2b(v.a);\n }\n return v;\n}\nfunction functionParse(str) {\n if (str.charAt(0) === 'r') {\n return rgbParse(str);\n }\n return hueParse(str);\n}\nclass Color {\n constructor(input) {\n if (input instanceof Color) {\n return input;\n }\n const type = typeof input;\n let v;\n if (type === 'object') {\n v = fromObject(input);\n } else if (type === 'string') {\n v = hexParse(input) || nameParse(input) || functionParse(input);\n }\n this._rgb = v;\n this._valid = !!v;\n }\n get valid() {\n return this._valid;\n }\n get rgb() {\n var v = clone(this._rgb);\n if (v) {\n v.a = b2n(v.a);\n }\n return v;\n }\n set rgb(obj) {\n this._rgb = fromObject(obj);\n }\n rgbString() {\n return this._valid ? rgbString(this._rgb) : undefined;\n }\n hexString() {\n return this._valid ? hexString(this._rgb) : undefined;\n }\n hslString() {\n return this._valid ? hslString(this._rgb) : undefined;\n }\n mix(color, weight) {\n if (color) {\n const c1 = this.rgb;\n const c2 = color.rgb;\n let w2;\n const p = weight === w2 ? 0.5 : weight;\n const w = 2 * p - 1;\n const a = c1.a - c2.a;\n const w1 = ((w * a === -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0;\n w2 = 1 - w1;\n c1.r = 0xFF & w1 * c1.r + w2 * c2.r + 0.5;\n c1.g = 0xFF & w1 * c1.g + w2 * c2.g + 0.5;\n c1.b = 0xFF & w1 * c1.b + w2 * c2.b + 0.5;\n c1.a = p * c1.a + (1 - p) * c2.a;\n this.rgb = c1;\n }\n return this;\n }\n interpolate(color, t) {\n if (color) {\n this._rgb = interpolate(this._rgb, color._rgb, t);\n }\n return this;\n }\n clone() {\n return new Color(this.rgb);\n }\n alpha(a) {\n this._rgb.a = n2b(a);\n return this;\n }\n clearer(ratio) {\n const rgb = this._rgb;\n rgb.a *= 1 - ratio;\n return this;\n }\n greyscale() {\n const rgb = this._rgb;\n const val = round(rgb.r * 0.3 + rgb.g * 0.59 + rgb.b * 0.11);\n rgb.r = rgb.g = rgb.b = val;\n return this;\n }\n opaquer(ratio) {\n const rgb = this._rgb;\n rgb.a *= 1 + ratio;\n return this;\n }\n negate() {\n const v = this._rgb;\n v.r = 255 - v.r;\n v.g = 255 - v.g;\n v.b = 255 - v.b;\n return this;\n }\n lighten(ratio) {\n modHSL(this._rgb, 2, ratio);\n return this;\n }\n darken(ratio) {\n modHSL(this._rgb, 2, -ratio);\n return this;\n }\n saturate(ratio) {\n modHSL(this._rgb, 1, ratio);\n return this;\n }\n desaturate(ratio) {\n modHSL(this._rgb, 1, -ratio);\n return this;\n }\n rotate(deg) {\n rotate(this._rgb, deg);\n return this;\n }\n}\n\nfunction index_esm(input) {\n return new Color(input);\n}\n\nexport { Color, b2n, b2p, index_esm as default, hexParse, hexString, hsl2rgb, hslString, hsv2rgb, hueParse, hwb2rgb, lim, n2b, n2p, nameParse, p2b, rgb2hsl, rgbParse, rgbString, rotate, round };\n","import {Color} from '@kurkle/color';\n\nexport function isPatternOrGradient(value: unknown): value is CanvasPattern | CanvasGradient {\n if (value && typeof value === 'object') {\n const type = value.toString();\n return type === '[object CanvasPattern]' || type === '[object CanvasGradient]';\n }\n\n return false;\n}\n\nexport function color(value: CanvasGradient): CanvasGradient;\nexport function color(value: CanvasPattern): CanvasPattern;\nexport function color(\n value:\n | string\n | { r: number; g: number; b: number; a: number }\n | [number, number, number]\n | [number, number, number, number]\n): Color;\nexport function color(value) {\n return isPatternOrGradient(value) ? value : new Color(value);\n}\n\nexport function getHoverColor(value: CanvasGradient): CanvasGradient;\nexport function getHoverColor(value: CanvasPattern): CanvasPattern;\nexport function getHoverColor(value: string): string;\nexport function getHoverColor(value) {\n return isPatternOrGradient(value)\n ? value\n : new Color(value).saturate(0.5).darken(0.1).hexString();\n}\n","const numbers = ['x', 'y', 'borderWidth', 'radius', 'tension'];\nconst colors = ['color', 'borderColor', 'backgroundColor'];\n\nexport function applyAnimationsDefaults(defaults) {\n defaults.set('animation', {\n delay: undefined,\n duration: 1000,\n easing: 'easeOutQuart',\n fn: undefined,\n from: undefined,\n loop: undefined,\n to: undefined,\n type: undefined,\n });\n\n defaults.describe('animation', {\n _fallback: false,\n _indexable: false,\n _scriptable: (name) => name !== 'onProgress' && name !== 'onComplete' && name !== 'fn',\n });\n\n defaults.set('animations', {\n colors: {\n type: 'color',\n properties: colors\n },\n numbers: {\n type: 'number',\n properties: numbers\n },\n });\n\n defaults.describe('animations', {\n _fallback: 'animation',\n });\n\n defaults.set('transitions', {\n active: {\n animation: {\n duration: 400\n }\n },\n resize: {\n animation: {\n duration: 0\n }\n },\n show: {\n animations: {\n colors: {\n from: 'transparent'\n },\n visible: {\n type: 'boolean',\n duration: 0 // show immediately\n },\n }\n },\n hide: {\n animations: {\n colors: {\n to: 'transparent'\n },\n visible: {\n type: 'boolean',\n easing: 'linear',\n fn: v => v | 0 // for keeping the dataset visible all the way through the animation\n },\n }\n }\n });\n}\n","\nconst intlCache = new Map();\n\nfunction getNumberFormat(locale: string, options?: Intl.NumberFormatOptions) {\n options = options || {};\n const cacheKey = locale + JSON.stringify(options);\n let formatter = intlCache.get(cacheKey);\n if (!formatter) {\n formatter = new Intl.NumberFormat(locale, options);\n intlCache.set(cacheKey, formatter);\n }\n return formatter;\n}\n\nexport function formatNumber(num: number, locale: string, options?: Intl.NumberFormatOptions) {\n return getNumberFormat(locale, options).format(num);\n}\n","import {isArray} from '../helpers/helpers.core.js';\nimport {formatNumber} from '../helpers/helpers.intl.js';\nimport {log10} from '../helpers/helpers.math.js';\n\n/**\n * Namespace to hold formatters for different types of ticks\n * @namespace Chart.Ticks.formatters\n */\nconst formatters = {\n /**\n * Formatter for value labels\n * @method Chart.Ticks.formatters.values\n * @param value the value to display\n * @return {string|string[]} the label to display\n */\n values(value) {\n return isArray(value) ? /** @type {string[]} */ (value) : '' + value;\n },\n\n /**\n * Formatter for numeric ticks\n * @method Chart.Ticks.formatters.numeric\n * @param tickValue {number} the value to be formatted\n * @param index {number} the position of the tickValue parameter in the ticks array\n * @param ticks {object[]} the list of ticks being converted\n * @return {string} string representation of the tickValue parameter\n */\n numeric(tickValue, index, ticks) {\n if (tickValue === 0) {\n return '0'; // never show decimal places for 0\n }\n\n const locale = this.chart.options.locale;\n let notation;\n let delta = tickValue; // This is used when there are less than 2 ticks as the tick interval.\n\n if (ticks.length > 1) {\n // all ticks are small or there huge numbers; use scientific notation\n const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value));\n if (maxTick < 1e-4 || maxTick > 1e+15) {\n notation = 'scientific';\n }\n\n delta = calculateDelta(tickValue, ticks);\n }\n\n const logDelta = log10(Math.abs(delta));\n\n // When datasets have values approaching Number.MAX_VALUE, the tick calculations might result in\n // infinity and eventually NaN. Passing NaN for minimumFractionDigits or maximumFractionDigits\n // will make the number formatter throw. So instead we check for isNaN and use a fallback value.\n //\n // toFixed has a max of 20 decimal places\n const numDecimal = isNaN(logDelta) ? 1 : Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0);\n\n const options = {notation, minimumFractionDigits: numDecimal, maximumFractionDigits: numDecimal};\n Object.assign(options, this.options.ticks.format);\n\n return formatNumber(tickValue, locale, options);\n },\n\n\n /**\n * Formatter for logarithmic ticks\n * @method Chart.Ticks.formatters.logarithmic\n * @param tickValue {number} the value to be formatted\n * @param index {number} the position of the tickValue parameter in the ticks array\n * @param ticks {object[]} the list of ticks being converted\n * @return {string} string representation of the tickValue parameter\n */\n logarithmic(tickValue, index, ticks) {\n if (tickValue === 0) {\n return '0';\n }\n const remain = ticks[index].significand || (tickValue / (Math.pow(10, Math.floor(log10(tickValue)))));\n if ([1, 2, 3, 5, 10, 15].includes(remain) || index > 0.8 * ticks.length) {\n return formatters.numeric.call(this, tickValue, index, ticks);\n }\n return '';\n }\n\n};\n\n\nfunction calculateDelta(tickValue, ticks) {\n // Figure out how many digits to show\n // The space between the first two ticks might be smaller than normal spacing\n let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value;\n\n // If we have a number like 2.5 as the delta, figure out how many decimal places we need\n if (Math.abs(delta) >= 1 && tickValue !== Math.floor(tickValue)) {\n // not an integer\n delta = tickValue - Math.floor(tickValue);\n }\n return delta;\n}\n\n/**\n * Namespace to hold static tick generation functions\n * @namespace Chart.Ticks\n */\nexport default {formatters};\n","import {getHoverColor} from '../helpers/helpers.color.js';\nimport {isObject, merge, valueOrDefault} from '../helpers/helpers.core.js';\nimport {applyAnimationsDefaults} from './core.animations.defaults.js';\nimport {applyLayoutsDefaults} from './core.layouts.defaults.js';\nimport {applyScaleDefaults} from './core.scale.defaults.js';\n\nexport const overrides = Object.create(null);\nexport const descriptors = Object.create(null);\n\n/**\n * @param {object} node\n * @param {string} key\n * @return {object}\n */\nfunction getScope(node, key) {\n if (!key) {\n return node;\n }\n const keys = key.split('.');\n for (let i = 0, n = keys.length; i < n; ++i) {\n const k = keys[i];\n node = node[k] || (node[k] = Object.create(null));\n }\n return node;\n}\n\nfunction set(root, scope, values) {\n if (typeof scope === 'string') {\n return merge(getScope(root, scope), values);\n }\n return merge(getScope(root, ''), scope);\n}\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 Defaults {\n constructor(_descriptors, _appliers) {\n this.animation = undefined;\n this.backgroundColor = 'rgba(0,0,0,0.1)';\n this.borderColor = 'rgba(0,0,0,0.1)';\n this.color = '#666';\n this.datasets = {};\n this.devicePixelRatio = (context) => context.chart.platform.getDevicePixelRatio();\n this.elements = {};\n this.events = [\n 'mousemove',\n 'mouseout',\n 'click',\n 'touchstart',\n 'touchmove'\n ];\n this.font = {\n family: \"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif\",\n size: 12,\n style: 'normal',\n lineHeight: 1.2,\n weight: null\n };\n this.hover = {};\n this.hoverBackgroundColor = (ctx, options) => getHoverColor(options.backgroundColor);\n this.hoverBorderColor = (ctx, options) => getHoverColor(options.borderColor);\n this.hoverColor = (ctx, options) => getHoverColor(options.color);\n this.indexAxis = 'x';\n this.interaction = {\n mode: 'nearest',\n intersect: true,\n includeInvisible: false\n };\n this.maintainAspectRatio = true;\n this.onHover = null;\n this.onClick = null;\n this.parsing = true;\n this.plugins = {};\n this.responsive = true;\n this.scale = undefined;\n this.scales = {};\n this.showLine = true;\n this.drawActiveElementsOnTop = true;\n\n this.describe(_descriptors);\n this.apply(_appliers);\n }\n\n /**\n\t * @param {string|object} scope\n\t * @param {object} [values]\n\t */\n set(scope, values) {\n return set(this, scope, values);\n }\n\n /**\n\t * @param {string} scope\n\t */\n get(scope) {\n return getScope(this, scope);\n }\n\n /**\n\t * @param {string|object} scope\n\t * @param {object} [values]\n\t */\n describe(scope, values) {\n return set(descriptors, scope, values);\n }\n\n override(scope, values) {\n return set(overrides, scope, values);\n }\n\n /**\n\t * Routes the named defaults to fallback to another scope/name.\n\t * This routing is useful when those target values, like defaults.color, are changed runtime.\n\t * If the values would be copied, the runtime change would not take effect. By routing, the\n\t * fallback is evaluated at each access, so its always up to date.\n\t *\n\t * Example:\n\t *\n\t * \tdefaults.route('elements.arc', 'backgroundColor', '', 'color')\n\t * - reads the backgroundColor from defaults.color when undefined locally\n\t *\n\t * @param {string} scope Scope this route applies to.\n\t * @param {string} name Property name that should be routed to different namespace when not defined here.\n\t * @param {string} targetScope The namespace where those properties should be routed to.\n\t * Empty string ('') is the root of defaults.\n\t * @param {string} targetName The target name in the target scope the property should be routed to.\n\t */\n route(scope, name, targetScope, targetName) {\n const scopeObject = getScope(this, scope);\n const targetScopeObject = getScope(this, targetScope);\n const privateName = '_' + name;\n\n Object.defineProperties(scopeObject, {\n // A private property is defined to hold the actual value, when this property is set in its scope (set in the setter)\n [privateName]: {\n value: scopeObject[name],\n writable: true\n },\n // The actual property is defined as getter/setter so we can do the routing when value is not locally set.\n [name]: {\n enumerable: true,\n get() {\n const local = this[privateName];\n const target = targetScopeObject[targetName];\n if (isObject(local)) {\n return Object.assign({}, target, local);\n }\n return valueOrDefault(local, target);\n },\n set(value) {\n this[privateName] = value;\n }\n }\n });\n }\n\n apply(appliers) {\n appliers.forEach((apply) => apply(this));\n }\n}\n\n// singleton instance\nexport default /* #__PURE__ */ new Defaults({\n _scriptable: (name) => !name.startsWith('on'),\n _indexable: (name) => name !== 'events',\n hover: {\n _fallback: 'interaction'\n },\n interaction: {\n _scriptable: false,\n _indexable: false,\n }\n}, [applyAnimationsDefaults, applyLayoutsDefaults, applyScaleDefaults]);\n","export function applyLayoutsDefaults(defaults) {\n defaults.set('layout', {\n autoPadding: true,\n padding: {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0\n }\n });\n}\n","import Ticks from './core.ticks.js';\n\nexport function applyScaleDefaults(defaults) {\n defaults.set('scale', {\n display: true,\n offset: false,\n reverse: false,\n beginAtZero: false,\n\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 3.0.0\n */\n bounds: 'ticks',\n\n clip: true,\n\n /**\n * Addition grace added to max and reduced from min data value.\n * @since 3.0.0\n */\n grace: 0,\n\n // grid line settings\n grid: {\n display: true,\n lineWidth: 1,\n drawOnChartArea: true,\n drawTicks: true,\n tickLength: 8,\n tickWidth: (_ctx, options) => options.lineWidth,\n tickColor: (_ctx, options) => options.color,\n offset: false,\n },\n\n border: {\n display: true,\n dash: [],\n dashOffset: 0.0,\n width: 1\n },\n\n // scale title\n title: {\n // display property\n display: false,\n\n // actual label\n text: '',\n\n // top/bottom padding\n padding: {\n top: 4,\n bottom: 4\n }\n },\n\n // label settings\n ticks: {\n minRotation: 0,\n maxRotation: 50,\n mirror: false,\n textStrokeWidth: 0,\n textStrokeColor: '',\n padding: 3,\n display: true,\n autoSkip: true,\n autoSkipPadding: 3,\n labelOffset: 0,\n // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.\n callback: Ticks.formatters.values,\n minor: {},\n major: {},\n align: 'center',\n crossAlign: 'near',\n\n showLabelBackdrop: false,\n backdropColor: 'rgba(255, 255, 255, 0.75)',\n backdropPadding: 2,\n }\n });\n\n defaults.route('scale.ticks', 'color', '', 'color');\n defaults.route('scale.grid', 'color', '', 'borderColor');\n defaults.route('scale.border', 'color', '', 'borderColor');\n defaults.route('scale.title', 'color', '', 'color');\n\n defaults.describe('scale', {\n _fallback: false,\n _scriptable: (name) => !name.startsWith('before') && !name.startsWith('after') && name !== 'callback' && name !== 'parser',\n _indexable: (name) => name !== 'borderDash' && name !== 'tickBorderDash' && name !== 'dash',\n });\n\n defaults.describe('scales', {\n _fallback: 'scale',\n });\n\n defaults.describe('scale.ticks', {\n _scriptable: (name) => name !== 'backdropPadding' && name !== 'callback',\n _indexable: (name) => name !== 'backdropPadding',\n });\n}\n","import type {ChartArea, Scale} from '../types/index.js';\nimport type PrivateChart from '../core/core.controller.js';\nimport type {Chart, ChartEvent} from '../types.js';\nimport {INFINITY} from './helpers.math.js';\n\n/**\n * @private\n */\nexport function _isDomSupported(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\n/**\n * @private\n */\nexport function _getParentNode(domNode: HTMLCanvasElement): HTMLCanvasElement {\n let parent = domNode.parentNode;\n if (parent && parent.toString() === '[object ShadowRoot]') {\n parent = (parent as ShadowRoot).host;\n }\n return parent as HTMLCanvasElement;\n}\n\n/**\n * convert max-width/max-height values that may be percentages into a number\n * @private\n */\n\nfunction parseMaxStyle(styleValue: string | number, node: HTMLElement, parentProperty: string) {\n let valueInPixels: number;\n if (typeof styleValue === 'string') {\n valueInPixels = parseInt(styleValue, 10);\n\n if (styleValue.indexOf('%') !== -1) {\n // percentage * size in dimension\n valueInPixels = (valueInPixels / 100) * node.parentNode[parentProperty];\n }\n } else {\n valueInPixels = styleValue;\n }\n\n return valueInPixels;\n}\n\nconst getComputedStyle = (element: HTMLElement): CSSStyleDeclaration =>\n element.ownerDocument.defaultView.getComputedStyle(element, null);\n\nexport function getStyle(el: HTMLElement, property: string): string {\n return getComputedStyle(el).getPropertyValue(property);\n}\n\nconst positions = ['top', 'right', 'bottom', 'left'];\nfunction getPositionedStyle(styles: CSSStyleDeclaration, style: string, suffix?: string): ChartArea {\n const result = {} as ChartArea;\n suffix = suffix ? '-' + suffix : '';\n for (let i = 0; i < 4; i++) {\n const pos = positions[i];\n result[pos] = parseFloat(styles[style + '-' + pos + suffix]) || 0;\n }\n result.width = result.left + result.right;\n result.height = result.top + result.bottom;\n return result;\n}\n\nconst useOffsetPos = (x: number, y: number, target: HTMLElement | EventTarget) =>\n (x > 0 || y > 0) && (!target || !(target as HTMLElement).shadowRoot);\n\n/**\n * @param e\n * @param canvas\n * @returns Canvas position\n */\nfunction getCanvasPosition(\n e: Event | TouchEvent | MouseEvent,\n canvas: HTMLCanvasElement\n): {\n x: number;\n y: number;\n box: boolean;\n } {\n const touches = (e as TouchEvent).touches;\n const source = (touches && touches.length ? touches[0] : e) as MouseEvent;\n const {offsetX, offsetY} = source as MouseEvent;\n let box = false;\n let x, y;\n if (useOffsetPos(offsetX, offsetY, e.target)) {\n x = offsetX;\n y = offsetY;\n } else {\n const rect = canvas.getBoundingClientRect();\n x = source.clientX - rect.left;\n y = source.clientY - rect.top;\n box = true;\n }\n return {x, y, box};\n}\n\n/**\n * Gets an event's x, y coordinates, relative to the chart area\n * @param event\n * @param chart\n * @returns x and y coordinates of the event\n */\n\nexport function getRelativePosition(\n event: Event | ChartEvent | TouchEvent | MouseEvent,\n chart: Chart | PrivateChart\n): { x: number; y: number } {\n if ('native' in event) {\n return event;\n }\n\n const {canvas, currentDevicePixelRatio} = chart;\n const style = getComputedStyle(canvas);\n const borderBox = style.boxSizing === 'border-box';\n const paddings = getPositionedStyle(style, 'padding');\n const borders = getPositionedStyle(style, 'border', 'width');\n const {x, y, box} = getCanvasPosition(event, canvas);\n const xOffset = paddings.left + (box && borders.left);\n const yOffset = paddings.top + (box && borders.top);\n\n let {width, height} = chart;\n if (borderBox) {\n width -= paddings.width + borders.width;\n height -= paddings.height + borders.height;\n }\n return {\n x: Math.round((x - xOffset) / width * canvas.width / currentDevicePixelRatio),\n y: Math.round((y - yOffset) / height * canvas.height / currentDevicePixelRatio)\n };\n}\n\nfunction getContainerSize(canvas: HTMLCanvasElement, width: number, height: number): Partial {\n let maxWidth: number, maxHeight: number;\n\n if (width === undefined || height === undefined) {\n const container = canvas && _getParentNode(canvas);\n if (!container) {\n width = canvas.clientWidth;\n height = canvas.clientHeight;\n } else {\n const rect = container.getBoundingClientRect(); // this is the border box of the container\n const containerStyle = getComputedStyle(container);\n const containerBorder = getPositionedStyle(containerStyle, 'border', 'width');\n const containerPadding = getPositionedStyle(containerStyle, 'padding');\n width = rect.width - containerPadding.width - containerBorder.width;\n height = rect.height - containerPadding.height - containerBorder.height;\n maxWidth = parseMaxStyle(containerStyle.maxWidth, container, 'clientWidth');\n maxHeight = parseMaxStyle(containerStyle.maxHeight, container, 'clientHeight');\n }\n }\n return {\n width,\n height,\n maxWidth: maxWidth || INFINITY,\n maxHeight: maxHeight || INFINITY\n };\n}\n\nconst round1 = (v: number) => Math.round(v * 10) / 10;\n\n// eslint-disable-next-line complexity\nexport function getMaximumSize(\n canvas: HTMLCanvasElement,\n bbWidth?: number,\n bbHeight?: number,\n aspectRatio?: number\n): { width: number; height: number } {\n const style = getComputedStyle(canvas);\n const margins = getPositionedStyle(style, 'margin');\n const maxWidth = parseMaxStyle(style.maxWidth, canvas, 'clientWidth') || INFINITY;\n const maxHeight = parseMaxStyle(style.maxHeight, canvas, 'clientHeight') || INFINITY;\n const containerSize = getContainerSize(canvas, bbWidth, bbHeight);\n let {width, height} = containerSize;\n\n if (style.boxSizing === 'content-box') {\n const borders = getPositionedStyle(style, 'border', 'width');\n const paddings = getPositionedStyle(style, 'padding');\n width -= paddings.width + borders.width;\n height -= paddings.height + borders.height;\n }\n width = Math.max(0, width - margins.width);\n height = Math.max(0, aspectRatio ? width / aspectRatio : height - margins.height);\n width = round1(Math.min(width, maxWidth, containerSize.maxWidth));\n height = round1(Math.min(height, maxHeight, containerSize.maxHeight));\n if (width && !height) {\n // https://github.com/chartjs/Chart.js/issues/4659\n // If the canvas has width, but no height, default to aspectRatio of 2 (canvas default)\n height = round1(width / 2);\n }\n\n const maintainHeight = bbWidth !== undefined || bbHeight !== undefined;\n\n if (maintainHeight && aspectRatio && containerSize.height && height > containerSize.height) {\n height = containerSize.height;\n width = round1(Math.floor(height * aspectRatio));\n }\n\n return {width, height};\n}\n\n/**\n * @param chart\n * @param forceRatio\n * @param forceStyle\n * @returns True if the canvas context size or transformation has changed.\n */\nexport function retinaScale(\n chart: Chart | PrivateChart,\n forceRatio: number,\n forceStyle?: boolean\n): boolean | void {\n const pixelRatio = forceRatio || 1;\n const deviceHeight = Math.floor(chart.height * pixelRatio);\n const deviceWidth = Math.floor(chart.width * pixelRatio);\n\n (chart as PrivateChart).height = Math.floor(chart.height);\n (chart as PrivateChart).width = Math.floor(chart.width);\n\n const canvas = chart.canvas;\n\n // If no style has been set on the canvas, the render size is used as display size,\n // making the chart visually bigger, so let's enforce it to the \"correct\" values.\n // See https://github.com/chartjs/Chart.js/issues/3575\n if (canvas.style && (forceStyle || (!canvas.style.height && !canvas.style.width))) {\n canvas.style.height = `${chart.height}px`;\n canvas.style.width = `${chart.width}px`;\n }\n\n if (chart.currentDevicePixelRatio !== pixelRatio\n || canvas.height !== deviceHeight\n || canvas.width !== deviceWidth) {\n (chart as PrivateChart).currentDevicePixelRatio = pixelRatio;\n canvas.height = deviceHeight;\n canvas.width = deviceWidth;\n chart.ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);\n return true;\n }\n return false;\n}\n\n/**\n * Detects support for options object argument in addEventListener.\n * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support\n * @private\n */\nexport const supportsEventListenerOptions = (function() {\n let passiveSupported = false;\n try {\n const options = {\n get passive() { // This function will be called when the browser attempts to access the passive property.\n passiveSupported = true;\n return false;\n }\n } as EventListenerOptions;\n\n if (_isDomSupported()) {\n window.addEventListener('test', null, options);\n window.removeEventListener('test', null, options);\n }\n } catch (e) {\n // continue regardless of error\n }\n return passiveSupported;\n}());\n\n/**\n * The \"used\" size is the final value of a dimension property after all calculations have\n * been performed. This method uses the computed style of `element` but returns undefined\n * if the computed style is not expressed in pixels. That can happen in some cases where\n * `element` has a size relative to its parent and this last one is not yet displayed,\n * for example because of `display: none` on a parent node.\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value\n * @returns Size in pixels or undefined if unknown.\n */\n\nexport function readUsedSize(\n element: HTMLElement,\n property: 'width' | 'height'\n): number | undefined {\n const value = getStyle(element, property);\n const matches = value && value.match(/^(\\d+)(\\.\\d+)?px$/);\n return matches ? +matches[1] : undefined;\n}\n","import type {\n Chart,\n Point,\n FontSpec,\n CanvasFontSpec,\n PointStyle,\n RenderTextOpts,\n BackdropOptions\n} from '../types/index.js';\nimport type {\n TRBL,\n SplinePoint,\n RoundedRect,\n TRBLCorners\n} from '../types/geometric.js';\nimport {isArray, isNullOrUndef} from './helpers.core.js';\nimport {PI, TAU, HALF_PI, QUARTER_PI, TWO_THIRDS_PI, RAD_PER_DEG} from './helpers.math.js';\n\n/**\n * Converts the given font object into a CSS font string.\n * @param font - A font object.\n * @return The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font\n * @private\n */\nexport function toFontString(font: FontSpec) {\n if (!font || isNullOrUndef(font.size) || isNullOrUndef(font.family)) {\n return null;\n }\n\n return (font.style ? font.style + ' ' : '')\n\t\t+ (font.weight ? font.weight + ' ' : '')\n\t\t+ font.size + 'px '\n\t\t+ font.family;\n}\n\n/**\n * @private\n */\nexport function _measureText(\n ctx: CanvasRenderingContext2D,\n data: Record,\n gc: string[],\n longest: number,\n string: string\n) {\n let textWidth = data[string];\n if (!textWidth) {\n textWidth = data[string] = ctx.measureText(string).width;\n gc.push(string);\n }\n if (textWidth > longest) {\n longest = textWidth;\n }\n return longest;\n}\n\ntype Thing = string | undefined | null\ntype Things = (Thing | Thing[])[]\n\n/**\n * @private\n */\n// eslint-disable-next-line complexity\nexport function _longestText(\n ctx: CanvasRenderingContext2D,\n font: string,\n arrayOfThings: Things,\n cache?: {data?: Record, garbageCollect?: string[], font?: string}\n) {\n cache = cache || {};\n let data = cache.data = cache.data || {};\n let gc = cache.garbageCollect = cache.garbageCollect || [];\n\n if (cache.font !== font) {\n data = cache.data = {};\n gc = cache.garbageCollect = [];\n cache.font = font;\n }\n\n ctx.save();\n\n ctx.font = font;\n let longest = 0;\n const ilen = arrayOfThings.length;\n let i: number, j: number, jlen: number, thing: Thing | Thing[], nestedThing: Thing | Thing[];\n for (i = 0; i < ilen; i++) {\n thing = arrayOfThings[i];\n\n // Undefined strings and arrays should not be measured\n if (thing !== undefined && thing !== null && !isArray(thing)) {\n longest = _measureText(ctx, data, gc, longest, thing);\n } else if (isArray(thing)) {\n // if it is an array lets measure each element\n // to do maybe simplify this function a bit so we can do this more recursively?\n for (j = 0, jlen = thing.length; j < jlen; j++) {\n nestedThing = thing[j];\n // Undefined strings and arrays should not be measured\n if (nestedThing !== undefined && nestedThing !== null && !isArray(nestedThing)) {\n longest = _measureText(ctx, data, gc, longest, nestedThing);\n }\n }\n }\n }\n\n ctx.restore();\n\n const gcLen = gc.length / 2;\n if (gcLen > arrayOfThings.length) {\n for (i = 0; i < gcLen; i++) {\n delete data[gc[i]];\n }\n gc.splice(0, gcLen);\n }\n return longest;\n}\n\n/**\n * Returns the aligned pixel value to avoid anti-aliasing blur\n * @param chart - The chart instance.\n * @param pixel - A pixel value.\n * @param width - The width of the element.\n * @returns The aligned pixel value.\n * @private\n */\nexport function _alignPixel(chart: Chart, pixel: number, width: number) {\n const devicePixelRatio = chart.currentDevicePixelRatio;\n const halfWidth = width !== 0 ? Math.max(width / 2, 0.5) : 0;\n return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;\n}\n\n/**\n * Clears the entire canvas.\n */\nexport function clearCanvas(canvas?: HTMLCanvasElement, ctx?: CanvasRenderingContext2D) {\n if (!ctx && !canvas) {\n return;\n }\n\n ctx = ctx || canvas.getContext('2d');\n\n ctx.save();\n // canvas.width and canvas.height do not consider the canvas transform,\n // while clearRect does\n ctx.resetTransform();\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.restore();\n}\n\nexport interface DrawPointOptions {\n pointStyle: PointStyle;\n rotation?: number;\n radius: number;\n borderWidth: number;\n}\n\nexport function drawPoint(\n ctx: CanvasRenderingContext2D,\n options: DrawPointOptions,\n x: number,\n y: number\n) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n drawPointLegend(ctx, options, x, y, null);\n}\n\n// eslint-disable-next-line complexity\nexport function drawPointLegend(\n ctx: CanvasRenderingContext2D,\n options: DrawPointOptions,\n x: number,\n y: number,\n w: number\n) {\n let type: string, xOffset: number, yOffset: number, size: number, cornerRadius: number, width: number, xOffsetW: number, yOffsetW: number;\n const style = options.pointStyle;\n const rotation = options.rotation;\n const radius = options.radius;\n let rad = (rotation || 0) * RAD_PER_DEG;\n\n if (style && typeof style === 'object') {\n type = style.toString();\n if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {\n ctx.save();\n ctx.translate(x, y);\n ctx.rotate(rad);\n ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);\n ctx.restore();\n return;\n }\n }\n\n if (isNaN(radius) || radius <= 0) {\n return;\n }\n\n ctx.beginPath();\n\n switch (style) {\n // Default includes circle\n default:\n if (w) {\n ctx.ellipse(x, y, w / 2, radius, 0, 0, TAU);\n } else {\n ctx.arc(x, y, radius, 0, TAU);\n }\n ctx.closePath();\n break;\n case 'triangle':\n width = w ? w / 2 : radius;\n ctx.moveTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);\n rad += TWO_THIRDS_PI;\n ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);\n rad += TWO_THIRDS_PI;\n ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);\n ctx.closePath();\n break;\n case 'rectRounded':\n // NOTE: the rounded rect implementation changed to use `arc` instead of\n // `quadraticCurveTo` since it generates better results when rect is\n // almost a circle. 0.516 (instead of 0.5) produces results with visually\n // closer proportion to the previous impl and it is inscribed in the\n // circle with `radius`. For more details, see the following PRs:\n // https://github.com/chartjs/Chart.js/issues/5597\n // https://github.com/chartjs/Chart.js/issues/5858\n cornerRadius = radius * 0.516;\n size = radius - cornerRadius;\n xOffset = Math.cos(rad + QUARTER_PI) * size;\n xOffsetW = Math.cos(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size);\n yOffset = Math.sin(rad + QUARTER_PI) * size;\n yOffsetW = Math.sin(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size);\n ctx.arc(x - xOffsetW, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);\n ctx.arc(x + yOffsetW, y - xOffset, cornerRadius, rad - HALF_PI, rad);\n ctx.arc(x + xOffsetW, y + yOffset, cornerRadius, rad, rad + HALF_PI);\n ctx.arc(x - yOffsetW, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);\n ctx.closePath();\n break;\n case 'rect':\n if (!rotation) {\n size = Math.SQRT1_2 * radius;\n width = w ? w / 2 : size;\n ctx.rect(x - width, y - size, 2 * width, 2 * size);\n break;\n }\n rad += QUARTER_PI;\n /* falls through */\n case 'rectRot':\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n ctx.closePath();\n break;\n case 'crossRot':\n rad += QUARTER_PI;\n /* falls through */\n case 'cross':\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.moveTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n break;\n case 'star':\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.moveTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n rad += QUARTER_PI;\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.moveTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n break;\n case 'line':\n xOffset = w ? w / 2 : Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n ctx.moveTo(x - xOffset, y - yOffset);\n ctx.lineTo(x + xOffset, y + yOffset);\n break;\n case 'dash':\n ctx.moveTo(x, y);\n ctx.lineTo(x + Math.cos(rad) * (w ? w / 2 : radius), y + Math.sin(rad) * radius);\n break;\n case false:\n ctx.closePath();\n break;\n }\n\n ctx.fill();\n if (options.borderWidth > 0) {\n ctx.stroke();\n }\n}\n\n/**\n * Returns true if the point is inside the rectangle\n * @param point - The point to test\n * @param area - The rectangle\n * @param margin - allowed margin\n * @private\n */\nexport function _isPointInArea(\n point: Point,\n area: TRBL,\n margin?: number\n) {\n margin = margin || 0.5; // margin - default is to match rounded decimals\n\n return !area || (point && point.x > area.left - margin && point.x < area.right + margin &&\n\t\tpoint.y > area.top - margin && point.y < area.bottom + margin);\n}\n\nexport function clipArea(ctx: CanvasRenderingContext2D, area: TRBL) {\n ctx.save();\n ctx.beginPath();\n ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);\n ctx.clip();\n}\n\nexport function unclipArea(ctx: CanvasRenderingContext2D) {\n ctx.restore();\n}\n\n/**\n * @private\n */\nexport function _steppedLineTo(\n ctx: CanvasRenderingContext2D,\n previous: Point,\n target: Point,\n flip?: boolean,\n mode?: string\n) {\n if (!previous) {\n return ctx.lineTo(target.x, target.y);\n }\n if (mode === 'middle') {\n const midpoint = (previous.x + target.x) / 2.0;\n ctx.lineTo(midpoint, previous.y);\n ctx.lineTo(midpoint, target.y);\n } else if (mode === 'after' !== !!flip) {\n ctx.lineTo(previous.x, target.y);\n } else {\n ctx.lineTo(target.x, previous.y);\n }\n ctx.lineTo(target.x, target.y);\n}\n\n/**\n * @private\n */\nexport function _bezierCurveTo(\n ctx: CanvasRenderingContext2D,\n previous: SplinePoint,\n target: SplinePoint,\n flip?: boolean\n) {\n if (!previous) {\n return ctx.lineTo(target.x, target.y);\n }\n ctx.bezierCurveTo(\n flip ? previous.cp1x : previous.cp2x,\n flip ? previous.cp1y : previous.cp2y,\n flip ? target.cp2x : target.cp1x,\n flip ? target.cp2y : target.cp1y,\n target.x,\n target.y);\n}\n\nfunction setRenderOpts(ctx: CanvasRenderingContext2D, opts: RenderTextOpts) {\n if (opts.translation) {\n ctx.translate(opts.translation[0], opts.translation[1]);\n }\n\n if (!isNullOrUndef(opts.rotation)) {\n ctx.rotate(opts.rotation);\n }\n\n if (opts.color) {\n ctx.fillStyle = opts.color;\n }\n\n if (opts.textAlign) {\n ctx.textAlign = opts.textAlign;\n }\n\n if (opts.textBaseline) {\n ctx.textBaseline = opts.textBaseline;\n }\n}\n\nfunction decorateText(\n ctx: CanvasRenderingContext2D,\n x: number,\n y: number,\n line: string,\n opts: RenderTextOpts\n) {\n if (opts.strikethrough || opts.underline) {\n /**\n * Now that IE11 support has been dropped, we can use more\n * of the TextMetrics object. The actual bounding boxes\n * are unflagged in Chrome, Firefox, Edge, and Safari so they\n * can be safely used.\n * See https://developer.mozilla.org/en-US/docs/Web/API/TextMetrics#Browser_compatibility\n */\n const metrics = ctx.measureText(line);\n const left = x - metrics.actualBoundingBoxLeft;\n const right = x + metrics.actualBoundingBoxRight;\n const top = y - metrics.actualBoundingBoxAscent;\n const bottom = y + metrics.actualBoundingBoxDescent;\n const yDecoration = opts.strikethrough ? (top + bottom) / 2 : bottom;\n\n ctx.strokeStyle = ctx.fillStyle;\n ctx.beginPath();\n ctx.lineWidth = opts.decorationWidth || 2;\n ctx.moveTo(left, yDecoration);\n ctx.lineTo(right, yDecoration);\n ctx.stroke();\n }\n}\n\nfunction drawBackdrop(ctx: CanvasRenderingContext2D, opts: BackdropOptions) {\n const oldColor = ctx.fillStyle;\n\n ctx.fillStyle = opts.color as string;\n ctx.fillRect(opts.left, opts.top, opts.width, opts.height);\n ctx.fillStyle = oldColor;\n}\n\n/**\n * Render text onto the canvas\n */\nexport function renderText(\n ctx: CanvasRenderingContext2D,\n text: string | string[],\n x: number,\n y: number,\n font: CanvasFontSpec,\n opts: RenderTextOpts = {}\n) {\n const lines = isArray(text) ? text : [text];\n const stroke = opts.strokeWidth > 0 && opts.strokeColor !== '';\n let i: number, line: string;\n\n ctx.save();\n ctx.font = font.string;\n setRenderOpts(ctx, opts);\n\n for (i = 0; i < lines.length; ++i) {\n line = lines[i];\n\n if (opts.backdrop) {\n drawBackdrop(ctx, opts.backdrop);\n }\n\n if (stroke) {\n if (opts.strokeColor) {\n ctx.strokeStyle = opts.strokeColor;\n }\n\n if (!isNullOrUndef(opts.strokeWidth)) {\n ctx.lineWidth = opts.strokeWidth;\n }\n\n ctx.strokeText(line, x, y, opts.maxWidth);\n }\n\n ctx.fillText(line, x, y, opts.maxWidth);\n decorateText(ctx, x, y, line, opts);\n\n y += Number(font.lineHeight);\n }\n\n ctx.restore();\n}\n\n/**\n * Add a path of a rectangle with rounded corners to the current sub-path\n * @param ctx - Context\n * @param rect - Bounding rect\n */\nexport function addRoundedRectPath(\n ctx: CanvasRenderingContext2D,\n rect: RoundedRect & { radius: TRBLCorners }\n) {\n const {x, y, w, h, radius} = rect;\n\n // top left arc\n ctx.arc(x + radius.topLeft, y + radius.topLeft, radius.topLeft, 1.5 * PI, PI, true);\n\n // line from top left to bottom left\n ctx.lineTo(x, y + h - radius.bottomLeft);\n\n // bottom left arc\n ctx.arc(x + radius.bottomLeft, y + h - radius.bottomLeft, radius.bottomLeft, PI, HALF_PI, true);\n\n // line from bottom left to bottom right\n ctx.lineTo(x + w - radius.bottomRight, y + h);\n\n // bottom right arc\n ctx.arc(x + w - radius.bottomRight, y + h - radius.bottomRight, radius.bottomRight, HALF_PI, 0, true);\n\n // line from bottom right to top right\n ctx.lineTo(x + w, y + radius.topRight);\n\n // top right arc\n ctx.arc(x + w - radius.topRight, y + radius.topRight, radius.topRight, 0, -HALF_PI, true);\n\n // line from top right to top left\n ctx.lineTo(x + radius.topLeft, y);\n}\n","/* eslint-disable @typescript-eslint/no-use-before-define */\nimport type {AnyObject} from '../types/basic.js';\nimport type {ChartMeta} from '../types/index.js';\nimport type {\n ResolverObjectKey,\n ResolverCache,\n ResolverProxy,\n DescriptorDefaults,\n Descriptor,\n ContextCache,\n ContextProxy\n} from './helpers.config.types.js';\nimport {isArray, isFunction, isObject, resolveObjectKey, _capitalize} from './helpers.core.js';\n\nexport * from './helpers.config.types.js';\n\n/**\n * Creates a Proxy for resolving raw values for options.\n * @param scopes - The option scopes to look for values, in resolution order\n * @param prefixes - The prefixes for values, in resolution order.\n * @param rootScopes - The root option scopes\n * @param fallback - Parent scopes fallback\n * @param getTarget - callback for getting the target for changed values\n * @returns Proxy\n * @private\n */\nexport function _createResolver<\n T extends AnyObject[] = AnyObject[],\n R extends AnyObject[] = T\n>(\n scopes: T,\n prefixes = [''],\n rootScopes?: R,\n fallback?: ResolverObjectKey,\n getTarget = () => scopes[0]\n) {\n const finalRootScopes = rootScopes || scopes;\n if (typeof fallback === 'undefined') {\n fallback = _resolve('_fallback', scopes);\n }\n const cache: ResolverCache = {\n [Symbol.toStringTag]: 'Object',\n _cacheable: true,\n _scopes: scopes,\n _rootScopes: finalRootScopes,\n _fallback: fallback,\n _getTarget: getTarget,\n override: (scope: AnyObject) => _createResolver([scope, ...scopes], prefixes, finalRootScopes, fallback),\n };\n return new Proxy(cache, {\n /**\n * A trap for the delete operator.\n */\n deleteProperty(target, prop: string) {\n delete target[prop]; // remove from cache\n delete target._keys; // remove cached keys\n delete scopes[0][prop]; // remove from top level scope\n return true;\n },\n\n /**\n * A trap for getting property values.\n */\n get(target, prop: string) {\n return _cached(target, prop,\n () => _resolveWithPrefixes(prop, prefixes, scopes, target));\n },\n\n /**\n * A trap for Object.getOwnPropertyDescriptor.\n * Also used by Object.hasOwnProperty.\n */\n getOwnPropertyDescriptor(target, prop) {\n return Reflect.getOwnPropertyDescriptor(target._scopes[0], prop);\n },\n\n /**\n * A trap for Object.getPrototypeOf.\n */\n getPrototypeOf() {\n return Reflect.getPrototypeOf(scopes[0]);\n },\n\n /**\n * A trap for the in operator.\n */\n has(target, prop: string) {\n return getKeysFromAllScopes(target).includes(prop);\n },\n\n /**\n * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols.\n */\n ownKeys(target) {\n return getKeysFromAllScopes(target);\n },\n\n /**\n * A trap for setting property values.\n */\n set(target, prop: string, value) {\n const storage = target._storage || (target._storage = getTarget());\n target[prop] = storage[prop] = value; // set to top level scope + cache\n delete target._keys; // remove cached keys\n return true;\n }\n }) as ResolverProxy;\n}\n\n/**\n * Returns an Proxy for resolving option values with context.\n * @param proxy - The Proxy returned by `_createResolver`\n * @param context - Context object for scriptable/indexable options\n * @param subProxy - The proxy provided for scriptable options\n * @param descriptorDefaults - Defaults for descriptors\n * @private\n */\nexport function _attachContext<\n T extends AnyObject[] = AnyObject[],\n R extends AnyObject[] = T\n>(\n proxy: ResolverProxy,\n context: AnyObject,\n subProxy?: ResolverProxy,\n descriptorDefaults?: DescriptorDefaults\n) {\n const cache: ContextCache = {\n _cacheable: false,\n _proxy: proxy,\n _context: context,\n _subProxy: subProxy,\n _stack: new Set(),\n _descriptors: _descriptors(proxy, descriptorDefaults),\n setContext: (ctx: AnyObject) => _attachContext(proxy, ctx, subProxy, descriptorDefaults),\n override: (scope: AnyObject) => _attachContext(proxy.override(scope), context, subProxy, descriptorDefaults)\n };\n return new Proxy(cache, {\n /**\n * A trap for the delete operator.\n */\n deleteProperty(target, prop) {\n delete target[prop]; // remove from cache\n delete proxy[prop]; // remove from proxy\n return true;\n },\n\n /**\n * A trap for getting property values.\n */\n get(target, prop: string, receiver) {\n return _cached(target, prop,\n () => _resolveWithContext(target, prop, receiver));\n },\n\n /**\n * A trap for Object.getOwnPropertyDescriptor.\n * Also used by Object.hasOwnProperty.\n */\n getOwnPropertyDescriptor(target, prop) {\n return target._descriptors.allKeys\n ? Reflect.has(proxy, prop) ? {enumerable: true, configurable: true} : undefined\n : Reflect.getOwnPropertyDescriptor(proxy, prop);\n },\n\n /**\n * A trap for Object.getPrototypeOf.\n */\n getPrototypeOf() {\n return Reflect.getPrototypeOf(proxy);\n },\n\n /**\n * A trap for the in operator.\n */\n has(target, prop) {\n return Reflect.has(proxy, prop);\n },\n\n /**\n * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols.\n */\n ownKeys() {\n return Reflect.ownKeys(proxy);\n },\n\n /**\n * A trap for setting property values.\n */\n set(target, prop, value) {\n proxy[prop] = value; // set to proxy\n delete target[prop]; // remove from cache\n return true;\n }\n }) as ContextProxy;\n}\n\n/**\n * @private\n */\nexport function _descriptors(\n proxy: ResolverCache,\n defaults: DescriptorDefaults = {scriptable: true, indexable: true}\n): Descriptor {\n const {_scriptable = defaults.scriptable, _indexable = defaults.indexable, _allKeys = defaults.allKeys} = proxy;\n return {\n allKeys: _allKeys,\n scriptable: _scriptable,\n indexable: _indexable,\n isScriptable: isFunction(_scriptable) ? _scriptable : () => _scriptable,\n isIndexable: isFunction(_indexable) ? _indexable : () => _indexable\n };\n}\n\nconst readKey = (prefix: string, name: string) => prefix ? prefix + _capitalize(name) : name;\nconst needsSubResolver = (prop: string, value: unknown) => isObject(value) && prop !== 'adapters' &&\n (Object.getPrototypeOf(value) === null || value.constructor === Object);\n\nfunction _cached(\n target: AnyObject,\n prop: string,\n resolve: () => unknown\n) {\n if (Object.prototype.hasOwnProperty.call(target, prop) || prop === 'constructor') {\n return target[prop];\n }\n\n const value = resolve();\n // cache the resolved value\n target[prop] = value;\n return value;\n}\n\nfunction _resolveWithContext(\n target: ContextCache,\n prop: string,\n receiver: AnyObject\n) {\n const {_proxy, _context, _subProxy, _descriptors: descriptors} = target;\n let value = _proxy[prop]; // resolve from proxy\n\n // resolve with context\n if (isFunction(value) && descriptors.isScriptable(prop)) {\n value = _resolveScriptable(prop, value, target, receiver);\n }\n if (isArray(value) && value.length) {\n value = _resolveArray(prop, value, target, descriptors.isIndexable);\n }\n if (needsSubResolver(prop, value)) {\n // if the resolved value is an object, create a sub resolver for it\n value = _attachContext(value, _context, _subProxy && _subProxy[prop], descriptors);\n }\n return value;\n}\n\nfunction _resolveScriptable(\n prop: string,\n getValue: (ctx: AnyObject, sub: AnyObject) => unknown,\n target: ContextCache,\n receiver: AnyObject\n) {\n const {_proxy, _context, _subProxy, _stack} = target;\n if (_stack.has(prop)) {\n throw new Error('Recursion detected: ' + Array.from(_stack).join('->') + '->' + prop);\n }\n _stack.add(prop);\n let value = getValue(_context, _subProxy || receiver);\n _stack.delete(prop);\n if (needsSubResolver(prop, value)) {\n // When scriptable option returns an object, create a resolver on that.\n value = createSubResolver(_proxy._scopes, _proxy, prop, value);\n }\n return value;\n}\n\nfunction _resolveArray(\n prop: string,\n value: unknown[],\n target: ContextCache,\n isIndexable: (key: string) => boolean\n) {\n const {_proxy, _context, _subProxy, _descriptors: descriptors} = target;\n\n if (typeof _context.index !== 'undefined' && isIndexable(prop)) {\n return value[_context.index % value.length];\n } else if (isObject(value[0])) {\n // Array of objects, return array or resolvers\n const arr = value;\n const scopes = _proxy._scopes.filter(s => s !== arr);\n value = [];\n for (const item of arr) {\n const resolver = createSubResolver(scopes, _proxy, prop, item);\n value.push(_attachContext(resolver, _context, _subProxy && _subProxy[prop], descriptors));\n }\n }\n return value;\n}\n\nfunction resolveFallback(\n fallback: ResolverObjectKey | ((prop: ResolverObjectKey, value: unknown) => ResolverObjectKey),\n prop: ResolverObjectKey,\n value: unknown\n) {\n return isFunction(fallback) ? fallback(prop, value) : fallback;\n}\n\nconst getScope = (key: ResolverObjectKey, parent: AnyObject) => key === true ? parent\n : typeof key === 'string' ? resolveObjectKey(parent, key) : undefined;\n\nfunction addScopes(\n set: Set,\n parentScopes: AnyObject[],\n key: ResolverObjectKey,\n parentFallback: ResolverObjectKey,\n value: unknown\n) {\n for (const parent of parentScopes) {\n const scope = getScope(key, parent);\n if (scope) {\n set.add(scope);\n const fallback = resolveFallback(scope._fallback, key, value);\n if (typeof fallback !== 'undefined' && fallback !== key && fallback !== parentFallback) {\n // When we reach the descriptor that defines a new _fallback, return that.\n // The fallback will resume to that new scope.\n return fallback;\n }\n } else if (scope === false && typeof parentFallback !== 'undefined' && key !== parentFallback) {\n // Fallback to `false` results to `false`, when falling back to different key.\n // For example `interaction` from `hover` or `plugins.tooltip` and `animation` from `animations`\n return null;\n }\n }\n return false;\n}\n\nfunction createSubResolver(\n parentScopes: AnyObject[],\n resolver: ResolverCache,\n prop: ResolverObjectKey,\n value: unknown\n) {\n const rootScopes = resolver._rootScopes;\n const fallback = resolveFallback(resolver._fallback, prop, value);\n const allScopes = [...parentScopes, ...rootScopes];\n const set = new Set();\n set.add(value);\n let key = addScopesFromKey(set, allScopes, prop, fallback || prop, value);\n if (key === null) {\n return false;\n }\n if (typeof fallback !== 'undefined' && fallback !== prop) {\n key = addScopesFromKey(set, allScopes, fallback, key, value);\n if (key === null) {\n return false;\n }\n }\n return _createResolver(Array.from(set), [''], rootScopes, fallback,\n () => subGetTarget(resolver, prop as string, value));\n}\n\nfunction addScopesFromKey(\n set: Set,\n allScopes: AnyObject[],\n key: ResolverObjectKey,\n fallback: ResolverObjectKey,\n item: unknown\n) {\n while (key) {\n key = addScopes(set, allScopes, key, fallback, item);\n }\n return key;\n}\n\nfunction subGetTarget(\n resolver: ResolverCache,\n prop: string,\n value: unknown\n) {\n const parent = resolver._getTarget();\n if (!(prop in parent)) {\n parent[prop] = {};\n }\n const target = parent[prop];\n if (isArray(target) && isObject(value)) {\n // For array of objects, the object is used to store updated values\n return value;\n }\n return target || {};\n}\n\nfunction _resolveWithPrefixes(\n prop: string,\n prefixes: string[],\n scopes: AnyObject[],\n proxy: ResolverProxy\n) {\n let value: unknown;\n for (const prefix of prefixes) {\n value = _resolve(readKey(prefix, prop), scopes);\n if (typeof value !== 'undefined') {\n return needsSubResolver(prop, value)\n ? createSubResolver(scopes, proxy, prop, value)\n : value;\n }\n }\n}\n\nfunction _resolve(key: string, scopes: AnyObject[]) {\n for (const scope of scopes) {\n if (!scope) {\n continue;\n }\n const value = scope[key];\n if (typeof value !== 'undefined') {\n return value;\n }\n }\n}\n\nfunction getKeysFromAllScopes(target: ResolverCache) {\n let keys = target._keys;\n if (!keys) {\n keys = target._keys = resolveKeysFromAllScopes(target._scopes);\n }\n return keys;\n}\n\nfunction resolveKeysFromAllScopes(scopes: AnyObject[]) {\n const set = new Set();\n for (const scope of scopes) {\n for (const key of Object.keys(scope).filter(k => !k.startsWith('_'))) {\n set.add(key);\n }\n }\n return Array.from(set);\n}\n\nexport function _parseObjectDataRadialScale(\n meta: ChartMeta<'line' | 'scatter'>,\n data: AnyObject[],\n start: number,\n count: number\n) {\n const {iScale} = meta;\n const {key = 'r'} = this._parsing;\n const parsed = new Array<{r: unknown}>(count);\n let i: number, ilen: number, index: number, item: AnyObject;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n item = data[index];\n parsed[i] = {\n r: iScale.parse(resolveObjectKey(item, key), index)\n };\n }\n return parsed;\n}\n","import {almostEquals, distanceBetweenPoints, sign} from './helpers.math.js';\nimport {_isPointInArea} from './helpers.canvas.js';\nimport type {ChartArea} from '../types/index.js';\nimport type {SplinePoint} from '../types/geometric.js';\n\nconst EPSILON = Number.EPSILON || 1e-14;\n\ntype OptionalSplinePoint = SplinePoint | false\nconst getPoint = (points: SplinePoint[], i: number): OptionalSplinePoint => i < points.length && !points[i].skip && points[i];\nconst getValueAxis = (indexAxis: 'x' | 'y') => indexAxis === 'x' ? 'y' : 'x';\n\nexport function splineCurve(\n firstPoint: SplinePoint,\n middlePoint: SplinePoint,\n afterPoint: SplinePoint,\n t: number\n): {\n previous: SplinePoint\n next: SplinePoint\n } {\n // Props to Rob Spencer at scaled innovation for his post on splining between points\n // http://scaledinnovation.com/analytics/splines/aboutSplines.html\n\n // This function must also respect \"skipped\" points\n\n const previous = firstPoint.skip ? middlePoint : firstPoint;\n const current = middlePoint;\n const next = afterPoint.skip ? middlePoint : afterPoint;\n const d01 = distanceBetweenPoints(current, previous);\n const d12 = distanceBetweenPoints(next, current);\n\n let s01 = d01 / (d01 + d12);\n let s12 = d12 / (d01 + d12);\n\n // If all points are the same, s01 & s02 will be inf\n s01 = isNaN(s01) ? 0 : s01;\n s12 = isNaN(s12) ? 0 : s12;\n\n const fa = t * s01; // scaling factor for triangle Ta\n const fb = t * s12;\n\n return {\n previous: {\n x: current.x - fa * (next.x - previous.x),\n y: current.y - fa * (next.y - previous.y)\n },\n next: {\n x: current.x + fb * (next.x - previous.x),\n y: current.y + fb * (next.y - previous.y)\n }\n };\n}\n\n/**\n * Adjust tangents to ensure monotonic properties\n */\nfunction monotoneAdjust(points: SplinePoint[], deltaK: number[], mK: number[]) {\n const pointsLen = points.length;\n\n let alphaK: number, betaK: number, tauK: number, squaredMagnitude: number, pointCurrent: OptionalSplinePoint;\n let pointAfter = getPoint(points, 0);\n for (let i = 0; i < pointsLen - 1; ++i) {\n pointCurrent = pointAfter;\n pointAfter = getPoint(points, i + 1);\n if (!pointCurrent || !pointAfter) {\n continue;\n }\n\n if (almostEquals(deltaK[i], 0, EPSILON)) {\n mK[i] = mK[i + 1] = 0;\n continue;\n }\n\n alphaK = mK[i] / deltaK[i];\n betaK = mK[i + 1] / deltaK[i];\n squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);\n if (squaredMagnitude <= 9) {\n continue;\n }\n\n tauK = 3 / Math.sqrt(squaredMagnitude);\n mK[i] = alphaK * tauK * deltaK[i];\n mK[i + 1] = betaK * tauK * deltaK[i];\n }\n}\n\nfunction monotoneCompute(points: SplinePoint[], mK: number[], indexAxis: 'x' | 'y' = 'x') {\n const valueAxis = getValueAxis(indexAxis);\n const pointsLen = points.length;\n let delta: number, pointBefore: OptionalSplinePoint, pointCurrent: OptionalSplinePoint;\n let pointAfter = getPoint(points, 0);\n\n for (let i = 0; i < pointsLen; ++i) {\n pointBefore = pointCurrent;\n pointCurrent = pointAfter;\n pointAfter = getPoint(points, i + 1);\n if (!pointCurrent) {\n continue;\n }\n\n const iPixel = pointCurrent[indexAxis];\n const vPixel = pointCurrent[valueAxis];\n if (pointBefore) {\n delta = (iPixel - pointBefore[indexAxis]) / 3;\n pointCurrent[`cp1${indexAxis}`] = iPixel - delta;\n pointCurrent[`cp1${valueAxis}`] = vPixel - delta * mK[i];\n }\n if (pointAfter) {\n delta = (pointAfter[indexAxis] - iPixel) / 3;\n pointCurrent[`cp2${indexAxis}`] = iPixel + delta;\n pointCurrent[`cp2${valueAxis}`] = vPixel + delta * mK[i];\n }\n }\n}\n\n/**\n * This function calculates Bézier control points in a similar way than |splineCurve|,\n * but preserves monotonicity of the provided data and ensures no local extremums are added\n * between the dataset discrete points due to the interpolation.\n * See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation\n */\nexport function splineCurveMonotone(points: SplinePoint[], indexAxis: 'x' | 'y' = 'x') {\n const valueAxis = getValueAxis(indexAxis);\n const pointsLen = points.length;\n const deltaK: number[] = Array(pointsLen).fill(0);\n const mK: number[] = Array(pointsLen);\n\n // Calculate slopes (deltaK) and initialize tangents (mK)\n let i, pointBefore: OptionalSplinePoint, pointCurrent: OptionalSplinePoint;\n let pointAfter = getPoint(points, 0);\n\n for (i = 0; i < pointsLen; ++i) {\n pointBefore = pointCurrent;\n pointCurrent = pointAfter;\n pointAfter = getPoint(points, i + 1);\n if (!pointCurrent) {\n continue;\n }\n\n if (pointAfter) {\n const slopeDelta = pointAfter[indexAxis] - pointCurrent[indexAxis];\n\n // In the case of two points that appear at the same x pixel, slopeDeltaX is 0\n deltaK[i] = slopeDelta !== 0 ? (pointAfter[valueAxis] - pointCurrent[valueAxis]) / slopeDelta : 0;\n }\n mK[i] = !pointBefore ? deltaK[i]\n : !pointAfter ? deltaK[i - 1]\n : (sign(deltaK[i - 1]) !== sign(deltaK[i])) ? 0\n : (deltaK[i - 1] + deltaK[i]) / 2;\n }\n\n monotoneAdjust(points, deltaK, mK);\n\n monotoneCompute(points, mK, indexAxis);\n}\n\nfunction capControlPoint(pt: number, min: number, max: number) {\n return Math.max(Math.min(pt, max), min);\n}\n\nfunction capBezierPoints(points: SplinePoint[], area: ChartArea) {\n let i, ilen, point, inArea, inAreaPrev;\n let inAreaNext = _isPointInArea(points[0], area);\n for (i = 0, ilen = points.length; i < ilen; ++i) {\n inAreaPrev = inArea;\n inArea = inAreaNext;\n inAreaNext = i < ilen - 1 && _isPointInArea(points[i + 1], area);\n if (!inArea) {\n continue;\n }\n point = points[i];\n if (inAreaPrev) {\n point.cp1x = capControlPoint(point.cp1x, area.left, area.right);\n point.cp1y = capControlPoint(point.cp1y, area.top, area.bottom);\n }\n if (inAreaNext) {\n point.cp2x = capControlPoint(point.cp2x, area.left, area.right);\n point.cp2y = capControlPoint(point.cp2y, area.top, area.bottom);\n }\n }\n}\n\n/**\n * @private\n */\nexport function _updateBezierControlPoints(\n points: SplinePoint[],\n options,\n area: ChartArea,\n loop: boolean,\n indexAxis: 'x' | 'y'\n) {\n let i: number, ilen: number, point: SplinePoint, controlPoints: ReturnType;\n\n // Only consider points that are drawn in case the spanGaps option is used\n if (options.spanGaps) {\n points = points.filter((pt) => !pt.skip);\n }\n\n if (options.cubicInterpolationMode === 'monotone') {\n splineCurveMonotone(points, indexAxis);\n } else {\n let prev = loop ? points[points.length - 1] : points[0];\n for (i = 0, ilen = points.length; i < ilen; ++i) {\n point = points[i];\n controlPoints = splineCurve(\n prev,\n point,\n points[Math.min(i + 1, ilen - (loop ? 0 : 1)) % ilen],\n options.tension\n );\n point.cp1x = controlPoints.previous.x;\n point.cp1y = controlPoints.previous.y;\n point.cp2x = controlPoints.next.x;\n point.cp2y = controlPoints.next.y;\n prev = point;\n }\n }\n\n if (options.capBezierPoints) {\n capBezierPoints(points, area);\n }\n}\n","import {PI, TAU, HALF_PI} from './helpers.math.js';\n\nconst atEdge = (t: number) => t === 0 || t === 1;\nconst elasticIn = (t: number, s: number, p: number) => -(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * TAU / p));\nconst elasticOut = (t: number, s: number, p: number) => Math.pow(2, -10 * t) * Math.sin((t - s) * TAU / p) + 1;\n\n/**\n * Easing functions adapted from Robert Penner's easing equations.\n * @namespace Chart.helpers.easing.effects\n * @see http://www.robertpenner.com/easing/\n */\nconst effects = {\n linear: (t: number) => t,\n\n easeInQuad: (t: number) => t * t,\n\n easeOutQuad: (t: number) => -t * (t - 2),\n\n easeInOutQuad: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t\n : -0.5 * ((--t) * (t - 2) - 1),\n\n easeInCubic: (t: number) => t * t * t,\n\n easeOutCubic: (t: number) => (t -= 1) * t * t + 1,\n\n easeInOutCubic: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t * t\n : 0.5 * ((t -= 2) * t * t + 2),\n\n easeInQuart: (t: number) => t * t * t * t,\n\n easeOutQuart: (t: number) => -((t -= 1) * t * t * t - 1),\n\n easeInOutQuart: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t * t * t\n : -0.5 * ((t -= 2) * t * t * t - 2),\n\n easeInQuint: (t: number) => t * t * t * t * t,\n\n easeOutQuint: (t: number) => (t -= 1) * t * t * t * t + 1,\n\n easeInOutQuint: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t * t * t * t\n : 0.5 * ((t -= 2) * t * t * t * t + 2),\n\n easeInSine: (t: number) => -Math.cos(t * HALF_PI) + 1,\n\n easeOutSine: (t: number) => Math.sin(t * HALF_PI),\n\n easeInOutSine: (t: number) => -0.5 * (Math.cos(PI * t) - 1),\n\n easeInExpo: (t: number) => (t === 0) ? 0 : Math.pow(2, 10 * (t - 1)),\n\n easeOutExpo: (t: number) => (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1,\n\n easeInOutExpo: (t: number) => atEdge(t) ? t : t < 0.5\n ? 0.5 * Math.pow(2, 10 * (t * 2 - 1))\n : 0.5 * (-Math.pow(2, -10 * (t * 2 - 1)) + 2),\n\n easeInCirc: (t: number) => (t >= 1) ? t : -(Math.sqrt(1 - t * t) - 1),\n\n easeOutCirc: (t: number) => Math.sqrt(1 - (t -= 1) * t),\n\n easeInOutCirc: (t: number) => ((t /= 0.5) < 1)\n ? -0.5 * (Math.sqrt(1 - t * t) - 1)\n : 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1),\n\n easeInElastic: (t: number) => atEdge(t) ? t : elasticIn(t, 0.075, 0.3),\n\n easeOutElastic: (t: number) => atEdge(t) ? t : elasticOut(t, 0.075, 0.3),\n\n easeInOutElastic(t: number) {\n const s = 0.1125;\n const p = 0.45;\n return atEdge(t) ? t :\n t < 0.5\n ? 0.5 * elasticIn(t * 2, s, p)\n : 0.5 + 0.5 * elasticOut(t * 2 - 1, s, p);\n },\n\n easeInBack(t: number) {\n const s = 1.70158;\n return t * t * ((s + 1) * t - s);\n },\n\n easeOutBack(t: number) {\n const s = 1.70158;\n return (t -= 1) * t * ((s + 1) * t + s) + 1;\n },\n\n easeInOutBack(t: number) {\n let s = 1.70158;\n if ((t /= 0.5) < 1) {\n return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));\n }\n return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);\n },\n\n easeInBounce: (t: number) => 1 - effects.easeOutBounce(1 - t),\n\n easeOutBounce(t: number) {\n const m = 7.5625;\n const d = 2.75;\n if (t < (1 / d)) {\n return m * t * t;\n }\n if (t < (2 / d)) {\n return m * (t -= (1.5 / d)) * t + 0.75;\n }\n if (t < (2.5 / d)) {\n return m * (t -= (2.25 / d)) * t + 0.9375;\n }\n return m * (t -= (2.625 / d)) * t + 0.984375;\n },\n\n easeInOutBounce: (t: number) => (t < 0.5)\n ? effects.easeInBounce(t * 2) * 0.5\n : effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5,\n} as const;\n\nexport type EasingFunction = keyof typeof effects\n\nexport default effects;\n","import type {Point, SplinePoint} from '../types/geometric.js';\n\n/**\n * @private\n */\nexport function _pointInLine(p1: Point, p2: Point, t: number, mode?) { // eslint-disable-line @typescript-eslint/no-unused-vars\n return {\n x: p1.x + t * (p2.x - p1.x),\n y: p1.y + t * (p2.y - p1.y)\n };\n}\n\n/**\n * @private\n */\nexport function _steppedInterpolation(\n p1: Point,\n p2: Point,\n t: number, mode: 'middle' | 'after' | unknown\n) {\n return {\n x: p1.x + t * (p2.x - p1.x),\n y: mode === 'middle' ? t < 0.5 ? p1.y : p2.y\n : mode === 'after' ? t < 1 ? p1.y : p2.y\n : t > 0 ? p2.y : p1.y\n };\n}\n\n/**\n * @private\n */\nexport function _bezierInterpolation(p1: SplinePoint, p2: SplinePoint, t: number, mode?) { // eslint-disable-line @typescript-eslint/no-unused-vars\n const cp1 = {x: p1.cp2x, y: p1.cp2y};\n const cp2 = {x: p2.cp1x, y: p2.cp1y};\n const a = _pointInLine(p1, cp1, t);\n const b = _pointInLine(cp1, cp2, t);\n const c = _pointInLine(cp2, p2, t);\n const d = _pointInLine(a, b, t);\n const e = _pointInLine(b, c, t);\n return _pointInLine(d, e, t);\n}\n","import defaults from '../core/core.defaults.js';\nimport {isArray, isObject, toDimension, valueOrDefault} from './helpers.core.js';\nimport {toFontString} from './helpers.canvas.js';\nimport type {ChartArea, FontSpec, Point} from '../types/index.js';\nimport type {TRBL, TRBLCorners} from '../types/geometric.js';\n\nconst LINE_HEIGHT = /^(normal|(\\d+(?:\\.\\d+)?)(px|em|%)?)$/;\nconst FONT_STYLE = /^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;\n\n/**\n * @alias Chart.helpers.options\n * @namespace\n */\n/**\n * Converts the given line height `value` in pixels for a specific font `size`.\n * @param value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').\n * @param size - The font size (in pixels) used to resolve relative `value`.\n * @returns The effective line height in pixels (size * 1.2 if value is invalid).\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height\n * @since 2.7.0\n */\nexport function toLineHeight(value: number | string, size: number): number {\n const matches = ('' + value).match(LINE_HEIGHT);\n if (!matches || matches[1] === 'normal') {\n return size * 1.2;\n }\n\n value = +matches[2];\n\n switch (matches[3]) {\n case 'px':\n return value;\n case '%':\n value /= 100;\n break;\n default:\n break;\n }\n\n return size * value;\n}\n\nconst numberOrZero = (v: unknown) => +v || 0;\n\n/**\n * @param value\n * @param props\n */\nexport function _readValueToProps(value: number | Record, props: K[]): Record;\nexport function _readValueToProps(value: number | Record, props: Record): Record;\nexport function _readValueToProps(value: number | Record, props: string[] | Record) {\n const ret = {};\n const objProps = isObject(props);\n const keys = objProps ? Object.keys(props) : props;\n const read = isObject(value)\n ? objProps\n ? prop => valueOrDefault(value[prop], value[props[prop]])\n : prop => value[prop]\n : () => value;\n\n for (const prop of keys) {\n ret[prop] = numberOrZero(read(prop));\n }\n return ret;\n}\n\n/**\n * Converts the given value into a TRBL object.\n * @param value - If a number, set the value to all TRBL component,\n * else, if an object, use defined properties and sets undefined ones to 0.\n * x / y are shorthands for same value for left/right and top/bottom.\n * @returns The padding values (top, right, bottom, left)\n * @since 3.0.0\n */\nexport function toTRBL(value: number | TRBL | Point) {\n return _readValueToProps(value, {top: 'y', right: 'x', bottom: 'y', left: 'x'});\n}\n\n/**\n * Converts the given value into a TRBL corners object (similar with css border-radius).\n * @param value - If a number, set the value to all TRBL corner components,\n * else, if an object, use defined properties and sets undefined ones to 0.\n * @returns The TRBL corner values (topLeft, topRight, bottomLeft, bottomRight)\n * @since 3.0.0\n */\nexport function toTRBLCorners(value: number | TRBLCorners) {\n return _readValueToProps(value, ['topLeft', 'topRight', 'bottomLeft', 'bottomRight']);\n}\n\n/**\n * Converts the given value into a padding object with pre-computed width/height.\n * @param value - If a number, set the value to all TRBL component,\n * else, if an object, use defined properties and sets undefined ones to 0.\n * x / y are shorthands for same value for left/right and top/bottom.\n * @returns The padding values (top, right, bottom, left, width, height)\n * @since 2.7.0\n */\nexport function toPadding(value?: number | TRBL): ChartArea {\n const obj = toTRBL(value) as ChartArea;\n\n obj.width = obj.left + obj.right;\n obj.height = obj.top + obj.bottom;\n\n return obj;\n}\n\n/**\n * Parses font options and returns the font object.\n * @param options - A object that contains font options to be parsed.\n * @param fallback - A object that contains fallback font options.\n * @return The font object.\n * @private\n */\n\nexport function toFont(options: Partial, fallback?: Partial) {\n options = options || {};\n fallback = fallback || defaults.font as FontSpec;\n\n let size = valueOrDefault(options.size, fallback.size);\n\n if (typeof size === 'string') {\n size = parseInt(size, 10);\n }\n let style = valueOrDefault(options.style, fallback.style);\n if (style && !('' + style).match(FONT_STYLE)) {\n console.warn('Invalid font style specified: \"' + style + '\"');\n style = undefined;\n }\n\n const font = {\n family: valueOrDefault(options.family, fallback.family),\n lineHeight: toLineHeight(valueOrDefault(options.lineHeight, fallback.lineHeight), size),\n size,\n style,\n weight: valueOrDefault(options.weight, fallback.weight),\n string: ''\n };\n\n font.string = toFontString(font);\n return font;\n}\n\n/**\n * Evaluates the given `inputs` sequentially and returns the first defined value.\n * @param inputs - An array of values, falling back to the last value.\n * @param context - If defined and the current value is a function, the value\n * is called with `context` as first argument and the result becomes the new input.\n * @param index - If defined and the current value is an array, the value\n * at `index` become the new input.\n * @param info - object to return information about resolution in\n * @param info.cacheable - Will be set to `false` if option is not cacheable.\n * @since 2.7.0\n */\nexport function resolve(inputs: Array, context?: object, index?: number, info?: { cacheable: boolean }) {\n let cacheable = true;\n let i: number, ilen: number, value: unknown;\n\n for (i = 0, ilen = inputs.length; i < ilen; ++i) {\n value = inputs[i];\n if (value === undefined) {\n continue;\n }\n if (context !== undefined && typeof value === 'function') {\n value = value(context);\n cacheable = false;\n }\n if (index !== undefined && isArray(value)) {\n value = value[index % value.length];\n cacheable = false;\n }\n if (value !== undefined) {\n if (info && !cacheable) {\n info.cacheable = false;\n }\n return value;\n }\n }\n}\n\n/**\n * @param minmax\n * @param grace\n * @param beginAtZero\n * @private\n */\nexport function _addGrace(minmax: { min: number; max: number; }, grace: number | string, beginAtZero: boolean) {\n const {min, max} = minmax;\n const change = toDimension(grace, (max - min) / 2);\n const keepZero = (value: number, add: number) => beginAtZero && value === 0 ? 0 : value + add;\n return {\n min: keepZero(min, -Math.abs(change)),\n max: keepZero(max, change)\n };\n}\n\n/**\n * Create a context inheriting parentContext\n * @param parentContext\n * @param context\n * @returns\n */\nexport function createContext(parentContext: null, context: T): T;\nexport function createContext(parentContext: P, context: T): P & T;\nexport function createContext(parentContext: object, context: object) {\n return Object.assign(Object.create(parentContext), context);\n}\n","export interface RTLAdapter {\n x(x: number): number;\n setWidth(w: number): void;\n textAlign(align: 'center' | 'left' | 'right'): 'center' | 'left' | 'right';\n xPlus(x: number, value: number): number;\n leftForLtr(x: number, itemWidth: number): number;\n}\n\nconst getRightToLeftAdapter = function(rectX: number, width: number): RTLAdapter {\n return {\n x(x) {\n return rectX + rectX + width - x;\n },\n setWidth(w) {\n width = w;\n },\n textAlign(align) {\n if (align === 'center') {\n return align;\n }\n return align === 'right' ? 'left' : 'right';\n },\n xPlus(x, value) {\n return x - value;\n },\n leftForLtr(x, itemWidth) {\n return x - itemWidth;\n },\n };\n};\n\nconst getLeftToRightAdapter = function(): RTLAdapter {\n return {\n x(x) {\n return x;\n },\n setWidth(w) { // eslint-disable-line no-unused-vars\n },\n textAlign(align) {\n return align;\n },\n xPlus(x, value) {\n return x + value;\n },\n leftForLtr(x, _itemWidth) { // eslint-disable-line @typescript-eslint/no-unused-vars\n return x;\n },\n };\n};\n\nexport function getRtlAdapter(rtl: boolean, rectX: number, width: number) {\n return rtl ? getRightToLeftAdapter(rectX, width) : getLeftToRightAdapter();\n}\n\nexport function overrideTextDirection(ctx: CanvasRenderingContext2D, direction: 'ltr' | 'rtl') {\n let style: CSSStyleDeclaration, original: [string, string];\n if (direction === 'ltr' || direction === 'rtl') {\n style = ctx.canvas.style;\n original = [\n style.getPropertyValue('direction'),\n style.getPropertyPriority('direction'),\n ];\n\n style.setProperty('direction', direction, 'important');\n (ctx as { prevTextDirection?: [string, string] }).prevTextDirection = original;\n }\n}\n\nexport function restoreTextDirection(ctx: CanvasRenderingContext2D, original?: [string, string]) {\n if (original !== undefined) {\n delete (ctx as { prevTextDirection?: [string, string] }).prevTextDirection;\n ctx.canvas.style.setProperty('direction', original[0], original[1]);\n }\n}\n","import {_angleBetween, _angleDiff, _isBetween, _normalizeAngle} from './helpers.math.js';\nimport {createContext} from './helpers.options.js';\nimport {isPatternOrGradient} from './helpers.color.js';\n\n/**\n * @typedef { import('../elements/element.line.js').default } LineElement\n * @typedef { import('../elements/element.point.js').default } PointElement\n * @typedef {{start: number, end: number, loop: boolean, style?: any}} Segment\n */\n\nfunction propertyFn(property) {\n if (property === 'angle') {\n return {\n between: _angleBetween,\n compare: _angleDiff,\n normalize: _normalizeAngle,\n };\n }\n return {\n between: _isBetween,\n compare: (a, b) => a - b,\n normalize: x => x\n };\n}\n\nfunction normalizeSegment({start, end, count, loop, style}) {\n return {\n start: start % count,\n end: end % count,\n loop: loop && (end - start + 1) % count === 0,\n style\n };\n}\n\nfunction getSegment(segment, points, bounds) {\n const {property, start: startBound, end: endBound} = bounds;\n const {between, normalize} = propertyFn(property);\n const count = points.length;\n // eslint-disable-next-line prefer-const\n let {start, end, loop} = segment;\n let i, ilen;\n\n if (loop) {\n start += count;\n end += count;\n for (i = 0, ilen = count; i < ilen; ++i) {\n if (!between(normalize(points[start % count][property]), startBound, endBound)) {\n break;\n }\n start--;\n end--;\n }\n start %= count;\n end %= count;\n }\n\n if (end < start) {\n end += count;\n }\n return {start, end, loop, style: segment.style};\n}\n\n/**\n * Returns the sub-segment(s) of a line segment that fall in the given bounds\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} [segment.style] - segment style\n * @param {PointElement[]} points - the points that this segment refers to\n * @param {object} [bounds]\n * @param {string} bounds.property - the property of a `PointElement` we are bounding. `x`, `y` or `angle`.\n * @param {number} bounds.start - start value of the property\n * @param {number} bounds.end - end value of the property\n * @private\n **/\nexport function _boundSegment(segment, points, bounds) {\n if (!bounds) {\n return [segment];\n }\n\n const {property, start: startBound, end: endBound} = bounds;\n const count = points.length;\n const {compare, between, normalize} = propertyFn(property);\n const {start, end, loop, style} = getSegment(segment, points, bounds);\n\n const result = [];\n let inside = false;\n let subStart = null;\n let value, point, prevValue;\n\n const startIsBefore = () => between(startBound, prevValue, value) && compare(startBound, prevValue) !== 0;\n const endIsBefore = () => compare(endBound, value) === 0 || between(endBound, prevValue, value);\n const shouldStart = () => inside || startIsBefore();\n const shouldStop = () => !inside || endIsBefore();\n\n for (let i = start, prev = start; i <= end; ++i) {\n point = points[i % count];\n\n if (point.skip) {\n continue;\n }\n\n value = normalize(point[property]);\n\n if (value === prevValue) {\n continue;\n }\n\n inside = between(value, startBound, endBound);\n\n if (subStart === null && shouldStart()) {\n subStart = compare(value, startBound) === 0 ? i : prev;\n }\n\n if (subStart !== null && shouldStop()) {\n result.push(normalizeSegment({start: subStart, end: i, loop, count, style}));\n subStart = null;\n }\n prev = i;\n prevValue = value;\n }\n\n if (subStart !== null) {\n result.push(normalizeSegment({start: subStart, end, loop, count, style}));\n }\n\n return result;\n}\n\n\n/**\n * Returns the segments of the line that are inside given bounds\n * @param {LineElement} line\n * @param {object} [bounds]\n * @param {string} bounds.property - the property we are bounding with. `x`, `y` or `angle`.\n * @param {number} bounds.start - start value of the `property`\n * @param {number} bounds.end - end value of the `property`\n * @private\n */\nexport function _boundSegments(line, bounds) {\n const result = [];\n const segments = line.segments;\n\n for (let i = 0; i < segments.length; i++) {\n const sub = _boundSegment(segments[i], line.points, bounds);\n if (sub.length) {\n result.push(...sub);\n }\n }\n return result;\n}\n\n/**\n * Find start and end index of a line.\n */\nfunction findStartAndEnd(points, count, loop, spanGaps) {\n let start = 0;\n let end = count - 1;\n\n if (loop && !spanGaps) {\n // loop and not spanning gaps, first find a gap to start from\n while (start < count && !points[start].skip) {\n start++;\n }\n }\n\n // find first non skipped point (after the first gap possibly)\n while (start < count && points[start].skip) {\n start++;\n }\n\n // if we looped to count, start needs to be 0\n start %= count;\n\n if (loop) {\n // loop will go past count, if start > 0\n end += start;\n }\n\n while (end > start && points[end % count].skip) {\n end--;\n }\n\n // end could be more than count, normalize\n end %= count;\n\n return {start, end};\n}\n\n/**\n * Compute solid segments from Points, when spanGaps === false\n * @param {PointElement[]} points - the points\n * @param {number} start - start index\n * @param {number} max - max index (can go past count on a loop)\n * @param {boolean} loop - boolean indicating that this would be a loop if no gaps are found\n */\nfunction solidSegments(points, start, max, loop) {\n const count = points.length;\n const result = [];\n let last = start;\n let prev = points[start];\n let end;\n\n for (end = start + 1; end <= max; ++end) {\n const cur = points[end % count];\n if (cur.skip || cur.stop) {\n if (!prev.skip) {\n loop = false;\n result.push({start: start % count, end: (end - 1) % count, loop});\n // @ts-ignore\n start = last = cur.stop ? end : null;\n }\n } else {\n last = end;\n if (prev.skip) {\n start = end;\n }\n }\n prev = cur;\n }\n\n if (last !== null) {\n result.push({start: start % count, end: last % count, loop});\n }\n\n return result;\n}\n\n/**\n * Compute the continuous segments that define the whole line\n * There can be skipped points within a segment, if spanGaps is true.\n * @param {LineElement} line\n * @param {object} [segmentOptions]\n * @return {Segment[]}\n * @private\n */\nexport function _computeSegments(line, segmentOptions) {\n const points = line.points;\n const spanGaps = line.options.spanGaps;\n const count = points.length;\n\n if (!count) {\n return [];\n }\n\n const loop = !!line._loop;\n const {start, end} = findStartAndEnd(points, count, loop, spanGaps);\n\n if (spanGaps === true) {\n return splitByStyles(line, [{start, end, loop}], points, segmentOptions);\n }\n\n const max = end < start ? end + count : end;\n const completeLoop = !!line._fullLoop && start === 0 && end === count - 1;\n return splitByStyles(line, solidSegments(points, start, max, completeLoop), points, segmentOptions);\n}\n\n/**\n * @param {Segment[]} segments\n * @param {PointElement[]} points\n * @param {object} [segmentOptions]\n * @return {Segment[]}\n */\nfunction splitByStyles(line, segments, points, segmentOptions) {\n if (!segmentOptions || !segmentOptions.setContext || !points) {\n return segments;\n }\n return doSplitByStyles(line, segments, points, segmentOptions);\n}\n\n/**\n * @param {LineElement} line\n * @param {Segment[]} segments\n * @param {PointElement[]} points\n * @param {object} [segmentOptions]\n * @return {Segment[]}\n */\nfunction doSplitByStyles(line, segments, points, segmentOptions) {\n const chartContext = line._chart.getContext();\n const baseStyle = readStyle(line.options);\n const {_datasetIndex: datasetIndex, options: {spanGaps}} = line;\n const count = points.length;\n const result = [];\n let prevStyle = baseStyle;\n let start = segments[0].start;\n let i = start;\n\n function addStyle(s, e, l, st) {\n const dir = spanGaps ? -1 : 1;\n if (s === e) {\n return;\n }\n // Style can not start/end on a skipped point, adjust indices accordingly\n s += count;\n while (points[s % count].skip) {\n s -= dir;\n }\n while (points[e % count].skip) {\n e += dir;\n }\n if (s % count !== e % count) {\n result.push({start: s % count, end: e % count, loop: l, style: st});\n prevStyle = st;\n start = e % count;\n }\n }\n\n for (const segment of segments) {\n start = spanGaps ? start : segment.start;\n let prev = points[start % count];\n let style;\n for (i = start + 1; i <= segment.end; i++) {\n const pt = points[i % count];\n style = readStyle(segmentOptions.setContext(createContext(chartContext, {\n type: 'segment',\n p0: prev,\n p1: pt,\n p0DataIndex: (i - 1) % count,\n p1DataIndex: i % count,\n datasetIndex\n })));\n if (styleChanged(style, prevStyle)) {\n addStyle(start, i - 1, segment.loop, prevStyle);\n }\n prev = pt;\n prevStyle = style;\n }\n if (start < i - 1) {\n addStyle(start, i - 1, segment.loop, prevStyle);\n }\n }\n\n return result;\n}\n\nfunction readStyle(options) {\n return {\n backgroundColor: options.backgroundColor,\n borderCapStyle: options.borderCapStyle,\n borderDash: options.borderDash,\n borderDashOffset: options.borderDashOffset,\n borderJoinStyle: options.borderJoinStyle,\n borderWidth: options.borderWidth,\n borderColor: options.borderColor\n };\n}\n\nfunction styleChanged(style, prevStyle) {\n if (!prevStyle) {\n return false;\n }\n const cache = [];\n const replacer = function(key, value) {\n if (!isPatternOrGradient(value)) {\n return value;\n }\n if (!cache.includes(value)) {\n cache.push(value);\n }\n return cache.indexOf(value);\n };\n return JSON.stringify(style, replacer) !== JSON.stringify(prevStyle, replacer);\n}\n","import type {Chart, ChartArea, ChartMeta, Scale, TRBL} from '../types/index.js';\n\nfunction getSizeForArea(scale: Scale, chartArea: ChartArea, field: keyof ChartArea) {\n return scale.options.clip ? scale[field] : chartArea[field];\n}\n\nfunction getDatasetArea(meta: ChartMeta, chartArea: ChartArea): TRBL {\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\nexport function getDatasetClipArea(chart: Chart, meta: ChartMeta): TRBL | false {\n const clip = meta._clip;\n if (clip.disabled) {\n return false;\n }\n const area = getDatasetArea(meta, chart.chartArea);\n\n return {\n left: clip.left === false ? 0 : area.left - (clip.left === true ? 0 : clip.left),\n right: clip.right === false ? chart.width : area.right + (clip.right === true ? 0 : clip.right),\n top: clip.top === false ? 0 : area.top - (clip.top === true ? 0 : clip.top),\n bottom: clip.bottom === false ? chart.height : area.bottom + (clip.bottom === true ? 0 : clip.bottom)\n };\n}\n","import {_lookupByKey, _rlookupByKey} from '../helpers/helpers.collection.js';\nimport {getRelativePosition} from '../helpers/helpers.dom.js';\nimport {_angleBetween, getAngleFromPoint} from '../helpers/helpers.math.js';\nimport {_isPointInArea, isNullOrUndef} from '../helpers/index.js';\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n * @typedef { import('../types/index.js').ChartEvent } ChartEvent\n * @typedef {{axis?: string, intersect?: boolean, includeInvisible?: boolean}} InteractionOptions\n * @typedef {{datasetIndex: number, index: number, element: import('./core.element.js').default}} InteractionItem\n * @typedef { import('../types/index.js').Point } Point\n */\n\n/**\n * Helper function to do binary search when possible\n * @param {object} metaset - the dataset meta\n * @param {string} axis - the axis mode. x|y|xy|r\n * @param {number} value - the value to find\n * @param {boolean} [intersect] - should the element intersect\n * @returns {{lo:number, hi:number}} indices to search data array between\n */\nfunction binarySearch(metaset, axis, value, intersect) {\n const {controller, data, _sorted} = metaset;\n const iScale = controller._cachedMeta.iScale;\n const spanGaps = metaset.dataset ? metaset.dataset.options ? metaset.dataset.options.spanGaps : null : null;\n\n if (iScale && axis === iScale.axis && axis !== 'r' && _sorted && data.length) {\n const lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey;\n if (!intersect) {\n const result = lookupMethod(data, axis, value);\n if (spanGaps) {\n const {vScale} = controller._cachedMeta;\n const {_parsed} = metaset;\n\n const distanceToDefinedLo = (_parsed\n .slice(0, result.lo + 1)\n .reverse()\n .findIndex(\n point => !isNullOrUndef(point[vScale.axis])));\n result.lo -= Math.max(0, distanceToDefinedLo);\n\n const distanceToDefinedHi = (_parsed\n .slice(result.hi)\n .findIndex(\n point => !isNullOrUndef(point[vScale.axis])));\n result.hi += Math.max(0, distanceToDefinedHi);\n }\n return result;\n } else if (controller._sharedOptions) {\n // _sharedOptions indicates that each element has equal options -> equal proportions\n // So we can do a ranged binary search based on the range of first element and\n // be confident to get the full range of indices that can intersect with the value.\n const el = data[0];\n const range = typeof el.getRange === 'function' && el.getRange(axis);\n if (range) {\n const start = lookupMethod(data, axis, value - range);\n const end = lookupMethod(data, axis, value + range);\n return {lo: start.lo, hi: end.hi};\n }\n }\n }\n // Default to all elements, when binary search can not be used.\n return {lo: 0, hi: data.length - 1};\n}\n\n/**\n * Helper function to select candidate elements for interaction\n * @param {Chart} chart - the chart\n * @param {string} axis - the axis mode. x|y|xy|r\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {function} handler - the callback to execute for each visible item\n * @param {boolean} [intersect] - consider intersecting items\n */\nfunction evaluateInteractionItems(chart, axis, position, handler, intersect) {\n const metasets = chart.getSortedVisibleDatasetMetas();\n const value = position[axis];\n for (let i = 0, ilen = metasets.length; i < ilen; ++i) {\n const {index, data} = metasets[i];\n const {lo, hi} = binarySearch(metasets[i], axis, value, intersect);\n for (let j = lo; j <= hi; ++j) {\n const element = data[j];\n if (!element.skip) {\n handler(element, index, j);\n }\n }\n }\n}\n\n/**\n * Get a distance metric function for two points based on the\n * axis mode setting\n * @param {string} axis - the axis mode. x|y|xy|r\n */\nfunction getDistanceMetricForAxis(axis) {\n const useX = axis.indexOf('x') !== -1;\n const useY = axis.indexOf('y') !== -1;\n\n return function(pt1, pt2) {\n const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;\n const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;\n return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));\n };\n}\n\n/**\n * Helper function to get the items that intersect the event position\n * @param {Chart} chart - the chart\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axis mode. x|y|xy|r\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @param {boolean} [includeInvisible] - include invisible points that are outside of the chart area\n * @return {InteractionItem[]} the nearest items\n */\nfunction getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) {\n const items = [];\n\n if (!includeInvisible && !chart.isPointInArea(position)) {\n return items;\n }\n\n const evaluationFunc = function(element, datasetIndex, index) {\n if (!includeInvisible && !_isPointInArea(element, chart.chartArea, 0)) {\n return;\n }\n if (element.inRange(position.x, position.y, useFinalPosition)) {\n items.push({element, datasetIndex, index});\n }\n };\n\n evaluateInteractionItems(chart, axis, position, evaluationFunc, true);\n return items;\n}\n\n/**\n * Helper function to get the items nearest to the event position for a radial chart\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axes along which to measure distance\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @return {InteractionItem[]} the nearest items\n */\nfunction getNearestRadialItems(chart, position, axis, useFinalPosition) {\n let items = [];\n\n function evaluationFunc(element, datasetIndex, index) {\n const {startAngle, endAngle} = element.getProps(['startAngle', 'endAngle'], useFinalPosition);\n const {angle} = getAngleFromPoint(element, {x: position.x, y: position.y});\n\n if (_angleBetween(angle, startAngle, endAngle)) {\n items.push({element, datasetIndex, index});\n }\n }\n\n evaluateInteractionItems(chart, axis, position, evaluationFunc);\n return items;\n}\n\n/**\n * Helper function to get the items nearest to the event position for a cartesian chart\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axes along which to measure distance\n * @param {boolean} [intersect] - if true, only consider items that intersect the position\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @param {boolean} [includeInvisible] - include invisible points that are outside of the chart area\n * @return {InteractionItem[]} the nearest items\n */\nfunction getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {\n let items = [];\n const distanceMetric = getDistanceMetricForAxis(axis);\n let minDistance = Number.POSITIVE_INFINITY;\n\n function evaluationFunc(element, datasetIndex, index) {\n const inRange = element.inRange(position.x, position.y, useFinalPosition);\n if (intersect && !inRange) {\n return;\n }\n\n const center = element.getCenterPoint(useFinalPosition);\n const pointInArea = !!includeInvisible || chart.isPointInArea(center);\n if (!pointInArea && !inRange) {\n return;\n }\n\n const distance = distanceMetric(position, center);\n if (distance < minDistance) {\n items = [{element, datasetIndex, index}];\n minDistance = distance;\n } else if (distance === minDistance) {\n // Can have multiple items at the same distance in which case we sort by size\n items.push({element, datasetIndex, index});\n }\n }\n\n evaluateInteractionItems(chart, axis, position, evaluationFunc);\n return items;\n}\n\n/**\n * Helper function to get the items nearest to the event position considering all visible items in the chart\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axes along which to measure distance\n * @param {boolean} [intersect] - if true, only consider items that intersect the position\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @param {boolean} [includeInvisible] - include invisible points that are outside of the chart area\n * @return {InteractionItem[]} the nearest items\n */\nfunction getNearestItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {\n if (!includeInvisible && !chart.isPointInArea(position)) {\n return [];\n }\n\n return axis === 'r' && !intersect\n ? getNearestRadialItems(chart, position, axis, useFinalPosition)\n : getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible);\n}\n\n/**\n * Helper function to get the items matching along the given X or Y axis\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axis to match\n * @param {boolean} [intersect] - if true, only consider items that intersect the position\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @return {InteractionItem[]} the nearest items\n */\nfunction getAxisItems(chart, position, axis, intersect, useFinalPosition) {\n const items = [];\n const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange';\n let intersectsItem = false;\n\n evaluateInteractionItems(chart, axis, position, (element, datasetIndex, index) => {\n if (element[rangeMethod] && element[rangeMethod](position[axis], useFinalPosition)) {\n items.push({element, datasetIndex, index});\n intersectsItem = intersectsItem || element.inRange(position.x, position.y, useFinalPosition);\n }\n });\n\n // If we want to trigger on an intersect and we don't have any items\n // that intersect the position, return nothing\n if (intersect && !intersectsItem) {\n return [];\n }\n return items;\n}\n\n/**\n * Contains interaction related functions\n * @namespace Chart.Interaction\n */\nexport default {\n // Part of the public API to facilitate developers creating their own modes\n evaluateInteractionItems,\n\n // Helper function for different modes\n modes: {\n /**\n\t\t * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something\n\t\t * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item\n\t\t * @function Chart.Interaction.modes.index\n\t\t * @since v2.4.0\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n index(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n // Default axis for index mode is 'x' to match old behaviour\n const axis = options.axis || 'x';\n const includeInvisible = options.includeInvisible || false;\n const items = options.intersect\n ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible)\n : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);\n const elements = [];\n\n if (!items.length) {\n return [];\n }\n\n chart.getSortedVisibleDatasetMetas().forEach((meta) => {\n const index = items[0].index;\n const element = meta.data[index];\n\n // don't count items that are skipped (null data)\n if (element && !element.skip) {\n elements.push({element, datasetIndex: meta.index, index});\n }\n });\n\n return elements;\n },\n\n /**\n\t\t * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something\n\t\t * If the options.intersect is false, we find the nearest item and return the items in that dataset\n\t\t * @function Chart.Interaction.modes.dataset\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n dataset(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'xy';\n const includeInvisible = options.includeInvisible || false;\n let items = options.intersect\n ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) :\n getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);\n\n if (items.length > 0) {\n const datasetIndex = items[0].datasetIndex;\n const data = chart.getDatasetMeta(datasetIndex).data;\n items = [];\n for (let i = 0; i < data.length; ++i) {\n items.push({element: data[i], datasetIndex, index: i});\n }\n }\n\n return items;\n },\n\n /**\n\t\t * Point mode returns all elements that hit test based on the event position\n\t\t * of the event\n\t\t * @function Chart.Interaction.modes.intersect\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n point(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'xy';\n const includeInvisible = options.includeInvisible || false;\n return getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible);\n },\n\n /**\n\t\t * nearest mode returns the element closest to the point\n\t\t * @function Chart.Interaction.modes.intersect\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n nearest(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'xy';\n const includeInvisible = options.includeInvisible || false;\n return getNearestItems(chart, position, axis, options.intersect, useFinalPosition, includeInvisible);\n },\n\n /**\n\t\t * x mode returns the elements that hit-test at the current x coordinate\n\t\t * @function Chart.Interaction.modes.x\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n x(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n return getAxisItems(chart, position, 'x', options.intersect, useFinalPosition);\n },\n\n /**\n\t\t * y mode returns the elements that hit-test at the current y coordinate\n\t\t * @function Chart.Interaction.modes.y\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n y(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n return getAxisItems(chart, position, 'y', options.intersect, useFinalPosition);\n }\n }\n};\n","import {defined, each, isObject} from '../helpers/helpers.core.js';\nimport {toPadding} from '../helpers/helpers.options.js';\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n */\n\nconst STATIC_POSITIONS = ['left', 'top', 'right', 'bottom'];\n\nfunction filterByPosition(array, position) {\n return array.filter(v => v.pos === position);\n}\n\nfunction filterDynamicPositionByAxis(array, axis) {\n return array.filter(v => STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis);\n}\n\nfunction sortByWeight(array, reverse) {\n return array.sort((a, b) => {\n const v0 = reverse ? b : a;\n const v1 = reverse ? a : b;\n return v0.weight === v1.weight ?\n v0.index - v1.index :\n v0.weight - v1.weight;\n });\n}\n\nfunction wrapBoxes(boxes) {\n const layoutBoxes = [];\n let i, ilen, box, pos, stack, stackWeight;\n\n for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {\n box = boxes[i];\n ({position: pos, options: {stack, stackWeight = 1}} = box);\n layoutBoxes.push({\n index: i,\n box,\n pos,\n horizontal: box.isHorizontal(),\n weight: box.weight,\n stack: stack && (pos + stack),\n stackWeight\n });\n }\n return layoutBoxes;\n}\n\nfunction buildStacks(layouts) {\n const stacks = {};\n for (const wrap of layouts) {\n const {stack, pos, stackWeight} = wrap;\n if (!stack || !STATIC_POSITIONS.includes(pos)) {\n continue;\n }\n const _stack = stacks[stack] || (stacks[stack] = {count: 0, placed: 0, weight: 0, size: 0});\n _stack.count++;\n _stack.weight += stackWeight;\n }\n return stacks;\n}\n\n/**\n * store dimensions used instead of available chartArea in fitBoxes\n **/\nfunction setLayoutDims(layouts, params) {\n const stacks = buildStacks(layouts);\n const {vBoxMaxWidth, hBoxMaxHeight} = params;\n let i, ilen, layout;\n for (i = 0, ilen = layouts.length; i < ilen; ++i) {\n layout = layouts[i];\n const {fullSize} = layout.box;\n const stack = stacks[layout.stack];\n const factor = stack && layout.stackWeight / stack.weight;\n if (layout.horizontal) {\n layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth;\n layout.height = hBoxMaxHeight;\n } else {\n layout.width = vBoxMaxWidth;\n layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight;\n }\n }\n return stacks;\n}\n\nfunction buildLayoutBoxes(boxes) {\n const layoutBoxes = wrapBoxes(boxes);\n const fullSize = sortByWeight(layoutBoxes.filter(wrap => wrap.box.fullSize), true);\n const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);\n const right = sortByWeight(filterByPosition(layoutBoxes, 'right'));\n const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);\n const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));\n const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x');\n const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y');\n\n return {\n fullSize,\n leftAndTop: left.concat(top),\n rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal),\n chartArea: filterByPosition(layoutBoxes, 'chartArea'),\n vertical: left.concat(right).concat(centerVertical),\n horizontal: top.concat(bottom).concat(centerHorizontal)\n };\n}\n\nfunction getCombinedMax(maxPadding, chartArea, a, b) {\n return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);\n}\n\nfunction updateMaxPadding(maxPadding, boxPadding) {\n maxPadding.top = Math.max(maxPadding.top, boxPadding.top);\n maxPadding.left = Math.max(maxPadding.left, boxPadding.left);\n maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);\n maxPadding.right = Math.max(maxPadding.right, boxPadding.right);\n}\n\nfunction updateDims(chartArea, params, layout, stacks) {\n const {pos, box} = layout;\n const maxPadding = chartArea.maxPadding;\n\n // dynamically placed boxes size is not considered\n if (!isObject(pos)) {\n if (layout.size) {\n // this layout was already counted for, lets first reduce old size\n chartArea[pos] -= layout.size;\n }\n const stack = stacks[layout.stack] || {size: 0, count: 1};\n stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width);\n layout.size = stack.size / stack.count;\n chartArea[pos] += layout.size;\n }\n\n if (box.getPadding) {\n updateMaxPadding(maxPadding, box.getPadding());\n }\n\n const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right'));\n const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom'));\n const widthChanged = newWidth !== chartArea.w;\n const heightChanged = newHeight !== chartArea.h;\n chartArea.w = newWidth;\n chartArea.h = newHeight;\n\n // return booleans on the changes per direction\n return layout.horizontal\n ? {same: widthChanged, other: heightChanged}\n : {same: heightChanged, other: widthChanged};\n}\n\nfunction handleMaxPadding(chartArea) {\n const maxPadding = chartArea.maxPadding;\n\n function updatePos(pos) {\n const change = Math.max(maxPadding[pos] - chartArea[pos], 0);\n chartArea[pos] += change;\n return change;\n }\n chartArea.y += updatePos('top');\n chartArea.x += updatePos('left');\n updatePos('right');\n updatePos('bottom');\n}\n\nfunction getMargins(horizontal, chartArea) {\n const maxPadding = chartArea.maxPadding;\n\n function marginForPositions(positions) {\n const margin = {left: 0, top: 0, right: 0, bottom: 0};\n positions.forEach((pos) => {\n margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);\n });\n return margin;\n }\n\n return horizontal\n ? marginForPositions(['left', 'right'])\n : marginForPositions(['top', 'bottom']);\n}\n\nfunction fitBoxes(boxes, chartArea, params, stacks) {\n const refitBoxes = [];\n let i, ilen, layout, box, refit, changed;\n\n for (i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i) {\n layout = boxes[i];\n box = layout.box;\n\n box.update(\n layout.width || chartArea.w,\n layout.height || chartArea.h,\n getMargins(layout.horizontal, chartArea)\n );\n const {same, other} = updateDims(chartArea, params, layout, stacks);\n\n // Dimensions changed and there were non full width boxes before this\n // -> we have to refit those\n refit |= same && refitBoxes.length;\n\n // Chart area changed in the opposite direction\n changed = changed || other;\n\n if (!box.fullSize) { // fullSize boxes don't need to be re-fitted in any case\n refitBoxes.push(layout);\n }\n }\n\n return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed;\n}\n\nfunction setBoxDims(box, left, top, width, height) {\n box.top = top;\n box.left = left;\n box.right = left + width;\n box.bottom = top + height;\n box.width = width;\n box.height = height;\n}\n\nfunction placeBoxes(boxes, chartArea, params, stacks) {\n const userPadding = params.padding;\n let {x, y} = chartArea;\n\n for (const layout of boxes) {\n const box = layout.box;\n const stack = stacks[layout.stack] || {count: 1, placed: 0, weight: 1};\n const weight = (layout.stackWeight / stack.weight) || 1;\n if (layout.horizontal) {\n const width = chartArea.w * weight;\n const height = stack.size || box.height;\n if (defined(stack.start)) {\n y = stack.start;\n }\n if (box.fullSize) {\n setBoxDims(box, userPadding.left, y, params.outerWidth - userPadding.right - userPadding.left, height);\n } else {\n setBoxDims(box, chartArea.left + stack.placed, y, width, height);\n }\n stack.start = y;\n stack.placed += width;\n y = box.bottom;\n } else {\n const height = chartArea.h * weight;\n const width = stack.size || box.width;\n if (defined(stack.start)) {\n x = stack.start;\n }\n if (box.fullSize) {\n setBoxDims(box, x, userPadding.top, width, params.outerHeight - userPadding.bottom - userPadding.top);\n } else {\n setBoxDims(box, x, chartArea.top + stack.placed, width, height);\n }\n stack.start = x;\n stack.placed += height;\n x = box.right;\n }\n }\n\n chartArea.x = x;\n chartArea.y = y;\n}\n\n/**\n * @interface LayoutItem\n * @typedef {object} LayoutItem\n * @prop {string} position - The position of the item in the chart layout. Possible values are\n * 'left', 'top', 'right', 'bottom', and 'chartArea'\n * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area\n * @prop {boolean} fullSize - if true, and the item is horizontal, then push vertical boxes down\n * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)\n * @prop {function} update - Takes two parameters: width and height. Returns size of item\n * @prop {function} draw - Draws the element\n * @prop {function} [getPadding] - Returns an object with padding on the edges\n * @prop {number} width - Width of item. Must be valid after update()\n * @prop {number} height - Height of item. Must be valid after update()\n * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update\n * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update\n * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update\n * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update\n */\n\n// The layout service is very self explanatory. It's responsible for the layout within a chart.\n// Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need\n// It is this service's responsibility of carrying out that layout.\nexport default {\n\n /**\n\t * Register a box to a chart.\n\t * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.\n\t * @param {Chart} chart - the chart to use\n\t * @param {LayoutItem} item - the item to add to be laid out\n\t */\n addBox(chart, item) {\n if (!chart.boxes) {\n chart.boxes = [];\n }\n\n // initialize item with default values\n item.fullSize = item.fullSize || false;\n item.position = item.position || 'top';\n item.weight = item.weight || 0;\n // @ts-ignore\n item._layers = item._layers || function() {\n return [{\n z: 0,\n draw(chartArea) {\n item.draw(chartArea);\n }\n }];\n };\n\n chart.boxes.push(item);\n },\n\n /**\n\t * Remove a layoutItem from a chart\n\t * @param {Chart} chart - the chart to remove the box from\n\t * @param {LayoutItem} layoutItem - the item to remove from the layout\n\t */\n removeBox(chart, layoutItem) {\n const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;\n if (index !== -1) {\n chart.boxes.splice(index, 1);\n }\n },\n\n /**\n\t * Sets (or updates) options on the given `item`.\n\t * @param {Chart} chart - the chart in which the item lives (or will be added to)\n\t * @param {LayoutItem} item - the item to configure with the given options\n\t * @param {object} options - the new item options.\n\t */\n configure(chart, item, options) {\n item.fullSize = options.fullSize;\n item.position = options.position;\n item.weight = options.weight;\n },\n\n /**\n\t * Fits boxes of the given chart into the given size by having each box measure itself\n\t * then running a fitting algorithm\n\t * @param {Chart} chart - the chart\n\t * @param {number} width - the width to fit into\n\t * @param {number} height - the height to fit into\n * @param {number} minPadding - minimum padding required for each side of chart area\n\t */\n update(chart, width, height, minPadding) {\n if (!chart) {\n return;\n }\n\n const padding = toPadding(chart.options.layout.padding);\n const availableWidth = Math.max(width - padding.width, 0);\n const availableHeight = Math.max(height - padding.height, 0);\n const boxes = buildLayoutBoxes(chart.boxes);\n const verticalBoxes = boxes.vertical;\n const horizontalBoxes = boxes.horizontal;\n\n // Before any changes are made, notify boxes that an update is about to being\n // This is used to clear any cached data (e.g. scale limits)\n each(chart.boxes, box => {\n if (typeof box.beforeLayout === 'function') {\n box.beforeLayout();\n }\n });\n\n // Essentially we now have any number of boxes on each of the 4 sides.\n // Our canvas looks like the following.\n // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and\n // B1 is the bottom axis\n // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays\n // These locations are single-box locations only, when trying to register a chartArea location that is already taken,\n // an error will be thrown.\n //\n // |----------------------------------------------------|\n // | T1 (Full Width) |\n // |----------------------------------------------------|\n // | | | T2 | |\n // | |----|-------------------------------------|----|\n // | | | C1 | | C2 | |\n // | | |----| |----| |\n // | | | | |\n // | L1 | L2 | ChartArea (C0) | R1 |\n // | | | | |\n // | | |----| |----| |\n // | | | C3 | | C4 | |\n // | |----|-------------------------------------|----|\n // | | | B1 | |\n // |----------------------------------------------------|\n // | B2 (Full Width) |\n // |----------------------------------------------------|\n //\n\n const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap) =>\n wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1;\n\n const params = Object.freeze({\n outerWidth: width,\n outerHeight: height,\n padding,\n availableWidth,\n availableHeight,\n vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount,\n hBoxMaxHeight: availableHeight / 2\n });\n const maxPadding = Object.assign({}, padding);\n updateMaxPadding(maxPadding, toPadding(minPadding));\n const chartArea = Object.assign({\n maxPadding,\n w: availableWidth,\n h: availableHeight,\n x: padding.left,\n y: padding.top\n }, padding);\n\n const stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);\n\n // First fit the fullSize boxes, to reduce probability of re-fitting.\n fitBoxes(boxes.fullSize, chartArea, params, stacks);\n\n // Then fit vertical boxes\n fitBoxes(verticalBoxes, chartArea, params, stacks);\n\n // Then fit horizontal boxes\n if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) {\n // if the area changed, re-fit vertical boxes\n fitBoxes(verticalBoxes, chartArea, params, stacks);\n }\n\n handleMaxPadding(chartArea);\n\n // Finally place the boxes to correct coordinates\n placeBoxes(boxes.leftAndTop, chartArea, params, stacks);\n\n // Move to opposite side of chart\n chartArea.x += chartArea.w;\n chartArea.y += chartArea.h;\n\n placeBoxes(boxes.rightAndBottom, chartArea, params, stacks);\n\n chart.chartArea = {\n left: chartArea.left,\n top: chartArea.top,\n right: chartArea.left + chartArea.w,\n bottom: chartArea.top + chartArea.h,\n height: chartArea.h,\n width: chartArea.w,\n };\n\n // Finally update boxes in chartArea (radial scale for example)\n each(boxes.chartArea, (layout) => {\n const box = layout.box;\n Object.assign(box, chart.chartArea);\n box.update(chartArea.w, chartArea.h, {left: 0, top: 0, right: 0, bottom: 0});\n });\n }\n};\n","\n/**\n * @typedef { import('../core/core.controller.js').default } Chart\n */\n\n/**\n * Abstract class that allows abstracting platform dependencies away from the chart.\n */\nexport default class BasePlatform {\n /**\n\t * Called at chart construction time, returns a context2d instance implementing\n\t * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.\n\t * @param {HTMLCanvasElement} canvas - The canvas from which to acquire context (platform specific)\n\t * @param {number} [aspectRatio] - The chart options\n\t */\n acquireContext(canvas, aspectRatio) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * Called at chart destruction time, releases any resources associated to the context\n\t * previously returned by the acquireContext() method.\n\t * @param {CanvasRenderingContext2D} context - The context2d instance\n\t * @returns {boolean} true if the method succeeded, else false\n\t */\n releaseContext(context) { // eslint-disable-line no-unused-vars\n return false;\n }\n\n /**\n\t * Registers the specified listener on the given chart.\n\t * @param {Chart} chart - Chart from which to listen for event\n\t * @param {string} type - The ({@link ChartEvent}) type to listen for\n\t * @param {function} listener - Receives a notification (an object that implements\n\t * the {@link ChartEvent} interface) when an event of the specified type occurs.\n\t */\n addEventListener(chart, type, listener) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * Removes the specified listener previously registered with addEventListener.\n\t * @param {Chart} chart - Chart from which to remove the listener\n\t * @param {string} type - The ({@link ChartEvent}) type to remove\n\t * @param {function} listener - The listener function to remove from the event target.\n\t */\n removeEventListener(chart, type, listener) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * @returns {number} the current devicePixelRatio of the device this platform is connected to.\n\t */\n getDevicePixelRatio() {\n return 1;\n }\n\n /**\n\t * Returns the maximum size in pixels of given canvas element.\n\t * @param {HTMLCanvasElement} element\n\t * @param {number} [width] - content width of parent element\n\t * @param {number} [height] - content height of parent element\n\t * @param {number} [aspectRatio] - aspect ratio to maintain\n\t */\n getMaximumSize(element, width, height, aspectRatio) {\n width = Math.max(0, width || element.width);\n height = height || element.height;\n return {\n width,\n height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height)\n };\n }\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t * @returns {boolean} true if the canvas is attached to the platform, false if not.\n\t */\n isAttached(canvas) { // eslint-disable-line no-unused-vars\n return true;\n }\n\n /**\n * Updates config with platform specific requirements\n * @param {import('../core/core.config.js').default} config\n */\n updateConfig(config) { // eslint-disable-line no-unused-vars\n // no-op\n }\n}\n","/**\n * Platform fallback implementation (minimal).\n * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939\n */\n\nimport BasePlatform from './platform.base.js';\n\n/**\n * Platform class for charts without access to the DOM or to many element properties\n * This platform is used by default for any chart passed an OffscreenCanvas.\n * @extends BasePlatform\n */\nexport default class BasicPlatform extends BasePlatform {\n acquireContext(item) {\n // To prevent canvas fingerprinting, some add-ons undefine the getContext\n // method, for example: https://github.com/kkapsner/CanvasBlocker\n // https://github.com/chartjs/Chart.js/issues/2807\n return item && item.getContext && item.getContext('2d') || null;\n }\n updateConfig(config) {\n config.options.animation = false;\n }\n}\n","/**\n * Chart.Platform implementation for targeting a web browser\n */\n\nimport BasePlatform from './platform.base.js';\nimport {_getParentNode, getRelativePosition, supportsEventListenerOptions, readUsedSize, getMaximumSize} from '../helpers/helpers.dom.js';\nimport {throttled} from '../helpers/helpers.extras.js';\nimport {isNullOrUndef} from '../helpers/helpers.core.js';\n\n/**\n * @typedef { import('../core/core.controller.js').default } Chart\n */\n\nconst EXPANDO_KEY = '$chartjs';\n\n/**\n * DOM event types -> Chart.js event types.\n * Note: only events with different types are mapped.\n * @see https://developer.mozilla.org/en-US/docs/Web/Events\n */\nconst EVENT_TYPES = {\n touchstart: 'mousedown',\n touchmove: 'mousemove',\n touchend: 'mouseup',\n pointerenter: 'mouseenter',\n pointerdown: 'mousedown',\n pointermove: 'mousemove',\n pointerup: 'mouseup',\n pointerleave: 'mouseout',\n pointerout: 'mouseout'\n};\n\nconst isNullOrEmpty = value => value === null || value === '';\n/**\n * Initializes the canvas style and render size without modifying the canvas display size,\n * since responsiveness is handled by the controller.resize() method. The config is used\n * to determine the aspect ratio to apply in case no explicit height has been specified.\n * @param {HTMLCanvasElement} canvas\n * @param {number} [aspectRatio]\n */\nfunction initCanvas(canvas, aspectRatio) {\n const style = canvas.style;\n\n // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it\n // returns null or '' if no explicit value has been set to the canvas attribute.\n const renderHeight = canvas.getAttribute('height');\n const renderWidth = canvas.getAttribute('width');\n\n // Chart.js modifies some canvas values that we want to restore on destroy\n canvas[EXPANDO_KEY] = {\n initial: {\n height: renderHeight,\n width: renderWidth,\n style: {\n display: style.display,\n height: style.height,\n width: style.width\n }\n }\n };\n\n // Force canvas to display as block to avoid extra space caused by inline\n // elements, which would interfere with the responsive resize process.\n // https://github.com/chartjs/Chart.js/issues/2538\n style.display = style.display || 'block';\n // Include possible borders in the size\n style.boxSizing = style.boxSizing || 'border-box';\n\n if (isNullOrEmpty(renderWidth)) {\n const displayWidth = readUsedSize(canvas, 'width');\n if (displayWidth !== undefined) {\n canvas.width = displayWidth;\n }\n }\n\n if (isNullOrEmpty(renderHeight)) {\n if (canvas.style.height === '') {\n // If no explicit render height and style height, let's apply the aspect ratio,\n // which one can be specified by the user but also by charts as default option\n // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.\n canvas.height = canvas.width / (aspectRatio || 2);\n } else {\n const displayHeight = readUsedSize(canvas, 'height');\n if (displayHeight !== undefined) {\n canvas.height = displayHeight;\n }\n }\n }\n\n return canvas;\n}\n\n// Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.\n// https://github.com/chartjs/Chart.js/issues/4287\nconst eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;\n\nfunction addListener(node, type, listener) {\n if (node) {\n node.addEventListener(type, listener, eventListenerOptions);\n }\n}\n\nfunction removeListener(chart, type, listener) {\n if (chart && chart.canvas) {\n chart.canvas.removeEventListener(type, listener, eventListenerOptions);\n }\n}\n\nfunction fromNativeEvent(event, chart) {\n const type = EVENT_TYPES[event.type] || event.type;\n const {x, y} = getRelativePosition(event, chart);\n return {\n type,\n chart,\n native: event,\n x: x !== undefined ? x : null,\n y: y !== undefined ? y : null,\n };\n}\n\nfunction nodeListContains(nodeList, canvas) {\n for (const node of nodeList) {\n if (node === canvas || node.contains(canvas)) {\n return true;\n }\n }\n}\n\nfunction createAttachObserver(chart, type, listener) {\n const canvas = chart.canvas;\n const observer = new MutationObserver(entries => {\n let trigger = false;\n for (const entry of entries) {\n trigger = trigger || nodeListContains(entry.addedNodes, canvas);\n trigger = trigger && !nodeListContains(entry.removedNodes, canvas);\n }\n if (trigger) {\n listener();\n }\n });\n observer.observe(document, {childList: true, subtree: true});\n return observer;\n}\n\nfunction createDetachObserver(chart, type, listener) {\n const canvas = chart.canvas;\n const observer = new MutationObserver(entries => {\n let trigger = false;\n for (const entry of entries) {\n trigger = trigger || nodeListContains(entry.removedNodes, canvas);\n trigger = trigger && !nodeListContains(entry.addedNodes, canvas);\n }\n if (trigger) {\n listener();\n }\n });\n observer.observe(document, {childList: true, subtree: true});\n return observer;\n}\n\nconst drpListeningCharts = new Map();\nlet oldDevicePixelRatio = 0;\n\nfunction onWindowResize() {\n const dpr = window.devicePixelRatio;\n if (dpr === oldDevicePixelRatio) {\n return;\n }\n oldDevicePixelRatio = dpr;\n drpListeningCharts.forEach((resize, chart) => {\n if (chart.currentDevicePixelRatio !== dpr) {\n resize();\n }\n });\n}\n\nfunction listenDevicePixelRatioChanges(chart, resize) {\n if (!drpListeningCharts.size) {\n window.addEventListener('resize', onWindowResize);\n }\n drpListeningCharts.set(chart, resize);\n}\n\nfunction unlistenDevicePixelRatioChanges(chart) {\n drpListeningCharts.delete(chart);\n if (!drpListeningCharts.size) {\n window.removeEventListener('resize', onWindowResize);\n }\n}\n\nfunction createResizeObserver(chart, type, listener) {\n const canvas = chart.canvas;\n const container = canvas && _getParentNode(canvas);\n if (!container) {\n return;\n }\n const resize = throttled((width, height) => {\n const w = container.clientWidth;\n listener(width, height);\n if (w < container.clientWidth) {\n // If the container size shrank during chart resize, let's assume\n // scrollbar appeared. So we resize again with the scrollbar visible -\n // effectively making chart smaller and the scrollbar hidden again.\n // Because we are inside `throttled`, and currently `ticking`, scroll\n // events are ignored during this whole 2 resize process.\n // If we assumed wrong and something else happened, we are resizing\n // twice in a frame (potential performance issue)\n listener();\n }\n }, window);\n\n // @ts-ignore until https://github.com/microsoft/TypeScript/issues/37861 implemented\n const observer = new ResizeObserver(entries => {\n const entry = entries[0];\n const width = entry.contentRect.width;\n const height = entry.contentRect.height;\n // When its container's display is set to 'none' the callback will be called with a\n // size of (0, 0), which will cause the chart to lose its original height, so skip\n // resizing in such case.\n if (width === 0 && height === 0) {\n return;\n }\n resize(width, height);\n });\n observer.observe(container);\n listenDevicePixelRatioChanges(chart, resize);\n\n return observer;\n}\n\nfunction releaseObserver(chart, type, observer) {\n if (observer) {\n observer.disconnect();\n }\n if (type === 'resize') {\n unlistenDevicePixelRatioChanges(chart);\n }\n}\n\nfunction createProxyAndListen(chart, type, listener) {\n const canvas = chart.canvas;\n const proxy = throttled((event) => {\n // This case can occur if the chart is destroyed while waiting\n // for the throttled function to occur. We prevent crashes by checking\n // for a destroyed chart\n if (chart.ctx !== null) {\n listener(fromNativeEvent(event, chart));\n }\n }, chart);\n\n addListener(canvas, type, proxy);\n\n return proxy;\n}\n\n/**\n * Platform class for charts that can access the DOM and global window/document properties\n * @extends BasePlatform\n */\nexport default class DomPlatform extends BasePlatform {\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t * @param {number} [aspectRatio]\n\t * @return {CanvasRenderingContext2D|null}\n\t */\n acquireContext(canvas, aspectRatio) {\n // To prevent canvas fingerprinting, some add-ons undefine the getContext\n // method, for example: https://github.com/kkapsner/CanvasBlocker\n // https://github.com/chartjs/Chart.js/issues/2807\n const context = canvas && canvas.getContext && canvas.getContext('2d');\n\n // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the canvas is\n // inside an iframe or when running in a protected environment. We could guess the\n // types from their toString() value but let's keep things flexible and assume it's\n // a sufficient condition if the canvas has a context2D which has canvas as `canvas`.\n // https://github.com/chartjs/Chart.js/issues/3887\n // https://github.com/chartjs/Chart.js/issues/4102\n // https://github.com/chartjs/Chart.js/issues/4152\n if (context && context.canvas === canvas) {\n // Load platform resources on first chart creation, to make it possible to\n // import the library before setting platform options.\n initCanvas(canvas, aspectRatio);\n return context;\n }\n\n return null;\n }\n\n /**\n\t * @param {CanvasRenderingContext2D} context\n\t */\n releaseContext(context) {\n const canvas = context.canvas;\n if (!canvas[EXPANDO_KEY]) {\n return false;\n }\n\n const initial = canvas[EXPANDO_KEY].initial;\n ['height', 'width'].forEach((prop) => {\n const value = initial[prop];\n if (isNullOrUndef(value)) {\n canvas.removeAttribute(prop);\n } else {\n canvas.setAttribute(prop, value);\n }\n });\n\n const style = initial.style || {};\n Object.keys(style).forEach((key) => {\n canvas.style[key] = style[key];\n });\n\n // The canvas render size might have been changed (and thus the state stack discarded),\n // we can't use save() and restore() to restore the initial state. So make sure that at\n // least the canvas context is reset to the default state by setting the canvas width.\n // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html\n // eslint-disable-next-line no-self-assign\n canvas.width = canvas.width;\n\n delete canvas[EXPANDO_KEY];\n return true;\n }\n\n /**\n\t *\n\t * @param {Chart} chart\n\t * @param {string} type\n\t * @param {function} listener\n\t */\n addEventListener(chart, type, listener) {\n // Can have only one listener per type, so make sure previous is removed\n this.removeEventListener(chart, type);\n\n const proxies = chart.$proxies || (chart.$proxies = {});\n const handlers = {\n attach: createAttachObserver,\n detach: createDetachObserver,\n resize: createResizeObserver\n };\n const handler = handlers[type] || createProxyAndListen;\n proxies[type] = handler(chart, type, listener);\n }\n\n\n /**\n\t * @param {Chart} chart\n\t * @param {string} type\n\t */\n removeEventListener(chart, type) {\n const proxies = chart.$proxies || (chart.$proxies = {});\n const proxy = proxies[type];\n\n if (!proxy) {\n return;\n }\n\n const handlers = {\n attach: releaseObserver,\n detach: releaseObserver,\n resize: releaseObserver\n };\n const handler = handlers[type] || removeListener;\n handler(chart, type, proxy);\n proxies[type] = undefined;\n }\n\n getDevicePixelRatio() {\n return window.devicePixelRatio;\n }\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t * @param {number} [width] - content width of parent element\n\t * @param {number} [height] - content height of parent element\n\t * @param {number} [aspectRatio] - aspect ratio to maintain\n\t */\n getMaximumSize(canvas, width, height, aspectRatio) {\n return getMaximumSize(canvas, width, height, aspectRatio);\n }\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t */\n isAttached(canvas) {\n const container = canvas && _getParentNode(canvas);\n return !!(container && container.isConnected);\n }\n}\n","import {_isDomSupported} from '../helpers/index.js';\nimport BasePlatform from './platform.base.js';\nimport BasicPlatform from './platform.basic.js';\nimport DomPlatform from './platform.dom.js';\n\nexport function _detectPlatform(canvas) {\n if (!_isDomSupported() || (typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas)) {\n return BasicPlatform;\n }\n return DomPlatform;\n}\n\nexport {BasePlatform, BasicPlatform, DomPlatform};\n","import effects from '../helpers/helpers.easing.js';\nimport {resolve} from '../helpers/helpers.options.js';\nimport {color as helpersColor} from '../helpers/helpers.color.js';\n\nconst transparent = 'transparent';\nconst interpolators = {\n boolean(from, to, factor) {\n return factor > 0.5 ? to : from;\n },\n /**\n * @param {string} from\n * @param {string} to\n * @param {number} factor\n */\n color(from, to, factor) {\n const c0 = helpersColor(from || transparent);\n const c1 = c0.valid && helpersColor(to || transparent);\n return c1 && c1.valid\n ? c1.mix(c0, factor).hexString()\n : to;\n },\n number(from, to, factor) {\n return from + (to - from) * factor;\n }\n};\n\nexport default class Animation {\n constructor(cfg, target, prop, to) {\n const currentValue = target[prop];\n\n to = resolve([cfg.to, to, currentValue, cfg.from]);\n const from = resolve([cfg.from, currentValue, to]);\n\n this._active = true;\n this._fn = cfg.fn || interpolators[cfg.type || typeof from];\n this._easing = effects[cfg.easing] || effects.linear;\n this._start = Math.floor(Date.now() + (cfg.delay || 0));\n this._duration = this._total = Math.floor(cfg.duration);\n this._loop = !!cfg.loop;\n this._target = target;\n this._prop = prop;\n this._from = from;\n this._to = to;\n this._promises = undefined;\n }\n\n active() {\n return this._active;\n }\n\n update(cfg, to, date) {\n if (this._active) {\n this._notify(false);\n\n const currentValue = this._target[this._prop];\n const elapsed = date - this._start;\n const remain = this._duration - elapsed;\n this._start = date;\n this._duration = Math.floor(Math.max(remain, cfg.duration));\n this._total += elapsed;\n this._loop = !!cfg.loop;\n this._to = resolve([cfg.to, to, currentValue, cfg.from]);\n this._from = resolve([cfg.from, currentValue, to]);\n }\n }\n\n cancel() {\n if (this._active) {\n // update current evaluated value, for smoother animations\n this.tick(Date.now());\n this._active = false;\n this._notify(false);\n }\n }\n\n tick(date) {\n const elapsed = date - this._start;\n const duration = this._duration;\n const prop = this._prop;\n const from = this._from;\n const loop = this._loop;\n const to = this._to;\n let factor;\n\n this._active = from !== to && (loop || (elapsed < duration));\n\n if (!this._active) {\n this._target[prop] = to;\n this._notify(true);\n return;\n }\n\n if (elapsed < 0) {\n this._target[prop] = from;\n return;\n }\n\n factor = (elapsed / duration) % 2;\n factor = loop && factor > 1 ? 2 - factor : factor;\n factor = this._easing(Math.min(1, Math.max(0, factor)));\n\n this._target[prop] = this._fn(from, to, factor);\n }\n\n wait() {\n const promises = this._promises || (this._promises = []);\n return new Promise((res, rej) => {\n promises.push({res, rej});\n });\n }\n\n _notify(resolved) {\n const method = resolved ? 'res' : 'rej';\n const promises = this._promises || [];\n for (let i = 0; i < promises.length; i++) {\n promises[i][method]();\n }\n }\n}\n","import animator from './core.animator.js';\nimport Animation from './core.animation.js';\nimport defaults from './core.defaults.js';\nimport {isArray, isObject} from '../helpers/helpers.core.js';\n\nexport default class Animations {\n constructor(chart, config) {\n this._chart = chart;\n this._properties = new Map();\n this.configure(config);\n }\n\n configure(config) {\n if (!isObject(config)) {\n return;\n }\n\n const animationOptions = Object.keys(defaults.animation);\n const animatedProps = this._properties;\n\n Object.getOwnPropertyNames(config).forEach(key => {\n const cfg = config[key];\n if (!isObject(cfg)) {\n return;\n }\n const resolved = {};\n for (const option of animationOptions) {\n resolved[option] = cfg[option];\n }\n\n (isArray(cfg.properties) && cfg.properties || [key]).forEach((prop) => {\n if (prop === key || !animatedProps.has(prop)) {\n animatedProps.set(prop, resolved);\n }\n });\n });\n }\n\n /**\n\t * Utility to handle animation of `options`.\n\t * @private\n\t */\n _animateOptions(target, values) {\n const newOptions = values.options;\n const options = resolveTargetOptions(target, newOptions);\n if (!options) {\n return [];\n }\n\n const animations = this._createAnimations(options, newOptions);\n if (newOptions.$shared) {\n // Going to shared options:\n // After all animations are done, assign the shared options object to the element\n // So any new updates to the shared options are observed\n awaitAll(target.options.$animations, newOptions).then(() => {\n target.options = newOptions;\n }, () => {\n // rejected, noop\n });\n }\n\n return animations;\n }\n\n /**\n\t * @private\n\t */\n _createAnimations(target, values) {\n const animatedProps = this._properties;\n const animations = [];\n const running = target.$animations || (target.$animations = {});\n const props = Object.keys(values);\n const date = Date.now();\n let i;\n\n for (i = props.length - 1; i >= 0; --i) {\n const prop = props[i];\n if (prop.charAt(0) === '$') {\n continue;\n }\n\n if (prop === 'options') {\n animations.push(...this._animateOptions(target, values));\n continue;\n }\n const value = values[prop];\n let animation = running[prop];\n const cfg = animatedProps.get(prop);\n\n if (animation) {\n if (cfg && animation.active()) {\n // There is an existing active animation, let's update that\n animation.update(cfg, value, date);\n continue;\n } else {\n animation.cancel();\n }\n }\n if (!cfg || !cfg.duration) {\n // not animated, set directly to new value\n target[prop] = value;\n continue;\n }\n\n running[prop] = animation = new Animation(cfg, target, prop, value);\n animations.push(animation);\n }\n return animations;\n }\n\n\n /**\n\t * Update `target` properties to new values, using configured animations\n\t * @param {object} target - object to update\n\t * @param {object} values - new target properties\n\t * @returns {boolean|undefined} - `true` if animations were started\n\t **/\n update(target, values) {\n if (this._properties.size === 0) {\n // Nothing is animated, just apply the new values.\n Object.assign(target, values);\n return;\n }\n\n const animations = this._createAnimations(target, values);\n\n if (animations.length) {\n animator.add(this._chart, animations);\n return true;\n }\n }\n}\n\nfunction awaitAll(animations, properties) {\n const running = [];\n const keys = Object.keys(properties);\n for (let i = 0; i < keys.length; i++) {\n const anim = animations[keys[i]];\n if (anim && anim.active()) {\n running.push(anim.wait());\n }\n }\n // @ts-ignore\n return Promise.all(running);\n}\n\nfunction resolveTargetOptions(target, newOptions) {\n if (!newOptions) {\n return;\n }\n let options = target.options;\n if (!options) {\n target.options = newOptions;\n return;\n }\n if (options.$shared) {\n // Going from shared options to distinct one:\n // Create new options object containing the old shared values and start updating that.\n target.options = options = Object.assign({}, options, {$shared: false, $animations: {}});\n }\n return options;\n}\n","import Animations from './core.animations.js';\nimport defaults from './core.defaults.js';\nimport {isArray, isFinite, isObject, valueOrDefault, resolveObjectKey, defined} from '../helpers/helpers.core.js';\nimport {listenArrayEvents, unlistenArrayEvents} from '../helpers/helpers.collection.js';\nimport {createContext, sign} from '../helpers/index.js';\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n * @typedef { import('./core.scale.js').default } Scale\n */\n\nfunction scaleClip(scale, allowedOverflow) {\n const opts = scale && scale.options || {};\n const reverse = opts.reverse;\n const min = opts.min === undefined ? allowedOverflow : 0;\n const max = opts.max === undefined ? allowedOverflow : 0;\n return {\n start: reverse ? max : min,\n end: reverse ? min : max\n };\n}\n\nfunction defaultClip(xScale, yScale, allowedOverflow) {\n if (allowedOverflow === false) {\n return false;\n }\n const x = scaleClip(xScale, allowedOverflow);\n const y = scaleClip(yScale, allowedOverflow);\n\n return {\n top: y.end,\n right: x.end,\n bottom: y.start,\n left: x.start\n };\n}\n\nfunction toClip(value) {\n let t, r, b, l;\n\n if (isObject(value)) {\n t = value.top;\n r = value.right;\n b = value.bottom;\n l = value.left;\n } else {\n t = r = b = l = value;\n }\n\n return {\n top: t,\n right: r,\n bottom: b,\n left: l,\n disabled: value === false\n };\n}\n\nfunction getSortedDatasetIndices(chart, filterVisible) {\n const keys = [];\n const metasets = chart._getSortedDatasetMetas(filterVisible);\n let i, ilen;\n\n for (i = 0, ilen = metasets.length; i < ilen; ++i) {\n keys.push(metasets[i].index);\n }\n return keys;\n}\n\nfunction applyStack(stack, value, dsIndex, options = {}) {\n const keys = stack.keys;\n const singleMode = options.mode === 'single';\n let i, ilen, datasetIndex, otherValue;\n\n if (value === null) {\n return;\n }\n\n let found = false;\n for (i = 0, ilen = keys.length; i < ilen; ++i) {\n datasetIndex = +keys[i];\n if (datasetIndex === dsIndex) {\n found = true;\n if (options.all) {\n continue;\n }\n break;\n }\n otherValue = stack.values[datasetIndex];\n if (isFinite(otherValue) && (singleMode || (value === 0 || sign(value) === sign(otherValue)))) {\n value += otherValue;\n }\n }\n\n if (!found && !options.all) {\n return 0;\n }\n\n return value;\n}\n\nfunction convertObjectDataToArray(data, meta) {\n const {iScale, vScale} = meta;\n const iAxisKey = iScale.axis === 'x' ? 'x' : 'y';\n const vAxisKey = vScale.axis === 'x' ? 'x' : 'y';\n const keys = Object.keys(data);\n const adata = new Array(keys.length);\n let i, ilen, key;\n for (i = 0, ilen = keys.length; i < ilen; ++i) {\n key = keys[i];\n adata[i] = {\n [iAxisKey]: key,\n [vAxisKey]: data[key]\n };\n }\n return adata;\n}\n\nfunction isStacked(scale, meta) {\n const stacked = scale && scale.options.stacked;\n return stacked || (stacked === undefined && meta.stack !== undefined);\n}\n\nfunction getStackKey(indexScale, valueScale, meta) {\n return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`;\n}\n\nfunction getUserBounds(scale) {\n const {min, max, minDefined, maxDefined} = scale.getUserBounds();\n return {\n min: minDefined ? min : Number.NEGATIVE_INFINITY,\n max: maxDefined ? max : Number.POSITIVE_INFINITY\n };\n}\n\nfunction getOrCreateStack(stacks, stackKey, indexValue) {\n const subStack = stacks[stackKey] || (stacks[stackKey] = {});\n return subStack[indexValue] || (subStack[indexValue] = {});\n}\n\nfunction getLastIndexInStack(stack, vScale, positive, type) {\n for (const meta of vScale.getMatchingVisibleMetas(type).reverse()) {\n const value = stack[meta.index];\n if ((positive && value > 0) || (!positive && value < 0)) {\n return meta.index;\n }\n }\n\n return null;\n}\n\nfunction updateStacks(controller, parsed) {\n const {chart, _cachedMeta: meta} = controller;\n const stacks = chart._stacks || (chart._stacks = {}); // map structure is {stackKey: {datasetIndex: value}}\n const {iScale, vScale, index: datasetIndex} = meta;\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const key = getStackKey(iScale, vScale, meta);\n const ilen = parsed.length;\n let stack;\n\n for (let i = 0; i < ilen; ++i) {\n const item = parsed[i];\n const {[iAxis]: index, [vAxis]: value} = item;\n const itemStacks = item._stacks || (item._stacks = {});\n stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index);\n stack[datasetIndex] = value;\n\n stack._top = getLastIndexInStack(stack, vScale, true, meta.type);\n stack._bottom = getLastIndexInStack(stack, vScale, false, meta.type);\n\n const visualValues = stack._visualValues || (stack._visualValues = {});\n visualValues[datasetIndex] = value;\n }\n}\n\nfunction getFirstScaleId(chart, axis) {\n const scales = chart.scales;\n return Object.keys(scales).filter(key => scales[key].axis === axis).shift();\n}\n\nfunction createDatasetContext(parent, index) {\n return createContext(parent,\n {\n active: false,\n dataset: undefined,\n datasetIndex: index,\n index,\n mode: 'default',\n type: 'dataset'\n }\n );\n}\n\nfunction createDataContext(parent, index, element) {\n return createContext(parent, {\n active: false,\n dataIndex: index,\n parsed: undefined,\n raw: undefined,\n element,\n index,\n mode: 'default',\n type: 'data'\n });\n}\n\nfunction clearStacks(meta, items) {\n // Not using meta.index here, because it might be already updated if the dataset changed location\n const datasetIndex = meta.controller.index;\n const axis = meta.vScale && meta.vScale.axis;\n if (!axis) {\n return;\n }\n\n items = items || meta._parsed;\n for (const parsed of items) {\n const stacks = parsed._stacks;\n if (!stacks || stacks[axis] === undefined || stacks[axis][datasetIndex] === undefined) {\n return;\n }\n delete stacks[axis][datasetIndex];\n if (stacks[axis]._visualValues !== undefined && stacks[axis]._visualValues[datasetIndex] !== undefined) {\n delete stacks[axis]._visualValues[datasetIndex];\n }\n }\n}\n\nconst isDirectUpdateMode = (mode) => mode === 'reset' || mode === 'none';\nconst cloneIfNotShared = (cached, shared) => shared ? cached : Object.assign({}, cached);\nconst createStack = (canStack, meta, chart) => canStack && !meta.hidden && meta._stacked\n && {keys: getSortedDatasetIndices(chart, true), values: null};\n\nexport default class DatasetController {\n\n /**\n * @type {any}\n */\n static defaults = {};\n\n /**\n * Element type used to generate a meta dataset (e.g. Chart.element.LineElement).\n */\n static datasetElementType = null;\n\n /**\n * Element type used to generate a meta data (e.g. Chart.element.PointElement).\n */\n static dataElementType = null;\n\n /**\n\t * @param {Chart} chart\n\t * @param {number} datasetIndex\n\t */\n constructor(chart, datasetIndex) {\n this.chart = chart;\n this._ctx = chart.ctx;\n this.index = datasetIndex;\n this._cachedDataOpts = {};\n this._cachedMeta = this.getMeta();\n this._type = this._cachedMeta.type;\n this.options = undefined;\n /** @type {boolean | object} */\n this._parsing = false;\n this._data = undefined;\n this._objectData = undefined;\n this._sharedOptions = undefined;\n this._drawStart = undefined;\n this._drawCount = undefined;\n this.enableOptionSharing = false;\n this.supportsDecimation = false;\n this.$context = undefined;\n this._syncList = [];\n this.datasetElementType = new.target.datasetElementType;\n this.dataElementType = new.target.dataElementType;\n\n this.initialize();\n }\n\n initialize() {\n const meta = this._cachedMeta;\n this.configure();\n this.linkScales();\n meta._stacked = isStacked(meta.vScale, meta);\n this.addElements();\n\n if (this.options.fill && !this.chart.isPluginEnabled('filler')) {\n console.warn(\"Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options\");\n }\n }\n\n updateIndex(datasetIndex) {\n if (this.index !== datasetIndex) {\n clearStacks(this._cachedMeta);\n }\n this.index = datasetIndex;\n }\n\n linkScales() {\n const chart = this.chart;\n const meta = this._cachedMeta;\n const dataset = this.getDataset();\n\n const chooseId = (axis, x, y, r) => axis === 'x' ? x : axis === 'r' ? r : y;\n\n const xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x'));\n const yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y'));\n const rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r'));\n const indexAxis = meta.indexAxis;\n const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid);\n const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid);\n meta.xScale = this.getScaleForId(xid);\n meta.yScale = this.getScaleForId(yid);\n meta.rScale = this.getScaleForId(rid);\n meta.iScale = this.getScaleForId(iid);\n meta.vScale = this.getScaleForId(vid);\n }\n\n getDataset() {\n return this.chart.data.datasets[this.index];\n }\n\n getMeta() {\n return this.chart.getDatasetMeta(this.index);\n }\n\n /**\n\t * @param {string} scaleID\n\t * @return {Scale}\n\t */\n getScaleForId(scaleID) {\n return this.chart.scales[scaleID];\n }\n\n /**\n\t * @private\n\t */\n _getOtherScale(scale) {\n const meta = this._cachedMeta;\n return scale === meta.iScale\n ? meta.vScale\n : meta.iScale;\n }\n\n reset() {\n this._update('reset');\n }\n\n /**\n\t * @private\n\t */\n _destroy() {\n const meta = this._cachedMeta;\n if (this._data) {\n unlistenArrayEvents(this._data, this);\n }\n if (meta._stacked) {\n clearStacks(meta);\n }\n }\n\n /**\n\t * @private\n\t */\n _dataCheck() {\n const dataset = this.getDataset();\n const data = dataset.data || (dataset.data = []);\n const _data = this._data;\n\n // In order to correctly handle data addition/deletion animation (and thus simulate\n // real-time charts), we need to monitor these data modifications and synchronize\n // the internal metadata accordingly.\n\n if (isObject(data)) {\n const meta = this._cachedMeta;\n this._data = convertObjectDataToArray(data, meta);\n } else if (_data !== data) {\n if (_data) {\n // This case happens when the user replaced the data array instance.\n unlistenArrayEvents(_data, this);\n // Discard old parsed data and stacks\n const meta = this._cachedMeta;\n clearStacks(meta);\n meta._parsed = [];\n }\n if (data && Object.isExtensible(data)) {\n listenArrayEvents(data, this);\n }\n this._syncList = [];\n this._data = data;\n }\n }\n\n addElements() {\n const meta = this._cachedMeta;\n\n this._dataCheck();\n\n if (this.datasetElementType) {\n meta.dataset = new this.datasetElementType();\n }\n }\n\n buildOrUpdateElements(resetNewElements) {\n const meta = this._cachedMeta;\n const dataset = this.getDataset();\n let stackChanged = false;\n\n this._dataCheck();\n\n // make sure cached _stacked status is current\n const oldStacked = meta._stacked;\n meta._stacked = isStacked(meta.vScale, meta);\n\n // detect change in stack option\n if (meta.stack !== dataset.stack) {\n stackChanged = true;\n // remove values from old stack\n clearStacks(meta);\n meta.stack = dataset.stack;\n }\n\n // Re-sync meta data in case the user replaced the data array or if we missed\n // any updates and so make sure that we handle number of datapoints changing.\n this._resyncElements(resetNewElements);\n\n // if stack changed, update stack values for the whole dataset\n if (stackChanged || oldStacked !== meta._stacked) {\n updateStacks(this, meta._parsed);\n meta._stacked = isStacked(meta.vScale, meta);\n }\n }\n\n /**\n\t * Merges user-supplied and default dataset-level options\n\t * @private\n\t */\n configure() {\n const config = this.chart.config;\n const scopeKeys = config.datasetScopeKeys(this._type);\n const scopes = config.getOptionScopes(this.getDataset(), scopeKeys, true);\n this.options = config.createResolver(scopes, this.getContext());\n this._parsing = this.options.parsing;\n this._cachedDataOpts = {};\n }\n\n /**\n\t * @param {number} start\n\t * @param {number} count\n\t */\n parse(start, count) {\n const {_cachedMeta: meta, _data: data} = this;\n const {iScale, _stacked} = meta;\n const iAxis = iScale.axis;\n\n let sorted = start === 0 && count === data.length ? true : meta._sorted;\n let prev = start > 0 && meta._parsed[start - 1];\n let i, cur, parsed;\n\n if (this._parsing === false) {\n meta._parsed = data;\n meta._sorted = true;\n parsed = data;\n } else {\n if (isArray(data[start])) {\n parsed = this.parseArrayData(meta, data, start, count);\n } else if (isObject(data[start])) {\n parsed = this.parseObjectData(meta, data, start, count);\n } else {\n parsed = this.parsePrimitiveData(meta, data, start, count);\n }\n\n const isNotInOrderComparedToPrev = () => cur[iAxis] === null || (prev && cur[iAxis] < prev[iAxis]);\n for (i = 0; i < count; ++i) {\n meta._parsed[i + start] = cur = parsed[i];\n if (sorted) {\n if (isNotInOrderComparedToPrev()) {\n sorted = false;\n }\n prev = cur;\n }\n }\n meta._sorted = sorted;\n }\n\n if (_stacked) {\n updateStacks(this, parsed);\n }\n }\n\n /**\n\t * Parse array of primitive values\n\t * @param {object} meta - dataset meta\n\t * @param {array} data - data array. Example [1,3,4]\n\t * @param {number} start - start index\n\t * @param {number} count - number of items to parse\n\t * @returns {object} parsed item - item containing index and a parsed value\n\t * for each scale id.\n\t * Example: {xScale0: 0, yScale0: 1}\n\t * @protected\n\t */\n parsePrimitiveData(meta, data, start, count) {\n const {iScale, vScale} = meta;\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const labels = iScale.getLabels();\n const singleScale = iScale === vScale;\n const parsed = new Array(count);\n let i, ilen, index;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n parsed[i] = {\n [iAxis]: singleScale || iScale.parse(labels[index], index),\n [vAxis]: vScale.parse(data[index], index)\n };\n }\n return parsed;\n }\n\n /**\n\t * Parse array of arrays\n\t * @param {object} meta - dataset meta\n\t * @param {array} data - data array. Example [[1,2],[3,4]]\n\t * @param {number} start - start index\n\t * @param {number} count - number of items to parse\n\t * @returns {object} parsed item - item containing index and a parsed value\n\t * for each scale id.\n\t * Example: {x: 0, y: 1}\n\t * @protected\n\t */\n parseArrayData(meta, data, start, count) {\n const {xScale, yScale} = meta;\n const parsed = new Array(count);\n let i, ilen, index, item;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n item = data[index];\n parsed[i] = {\n x: xScale.parse(item[0], index),\n y: yScale.parse(item[1], index)\n };\n }\n return parsed;\n }\n\n /**\n\t * Parse array of objects\n\t * @param {object} meta - dataset meta\n\t * @param {array} data - data array. Example [{x:1, y:5}, {x:2, y:10}]\n\t * @param {number} start - start index\n\t * @param {number} count - number of items to parse\n\t * @returns {object} parsed item - item containing index and a parsed value\n\t * for each scale id. _custom is optional\n\t * Example: {xScale0: 0, yScale0: 1, _custom: {r: 10, foo: 'bar'}}\n\t * @protected\n\t */\n parseObjectData(meta, data, start, count) {\n const {xScale, yScale} = meta;\n const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;\n const parsed = new Array(count);\n let i, ilen, index, item;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n item = data[index];\n parsed[i] = {\n x: xScale.parse(resolveObjectKey(item, xAxisKey), index),\n y: yScale.parse(resolveObjectKey(item, yAxisKey), index)\n };\n }\n return parsed;\n }\n\n /**\n\t * @protected\n\t */\n getParsed(index) {\n return this._cachedMeta._parsed[index];\n }\n\n /**\n\t * @protected\n\t */\n getDataElement(index) {\n return this._cachedMeta.data[index];\n }\n\n /**\n\t * @protected\n\t */\n applyStack(scale, parsed, mode) {\n const chart = this.chart;\n const meta = this._cachedMeta;\n const value = parsed[scale.axis];\n const stack = {\n keys: getSortedDatasetIndices(chart, true),\n values: parsed._stacks[scale.axis]._visualValues\n };\n return applyStack(stack, value, meta.index, {mode});\n }\n\n /**\n\t * @protected\n\t */\n updateRangeFromParsed(range, scale, parsed, stack) {\n const parsedValue = parsed[scale.axis];\n let value = parsedValue === null ? NaN : parsedValue;\n const values = stack && parsed._stacks[scale.axis];\n if (stack && values) {\n stack.values = values;\n value = applyStack(stack, parsedValue, this._cachedMeta.index);\n }\n range.min = Math.min(range.min, value);\n range.max = Math.max(range.max, value);\n }\n\n /**\n\t * @protected\n\t */\n getMinMax(scale, canStack) {\n const meta = this._cachedMeta;\n const _parsed = meta._parsed;\n const sorted = meta._sorted && scale === meta.iScale;\n const ilen = _parsed.length;\n const otherScale = this._getOtherScale(scale);\n const stack = createStack(canStack, meta, this.chart);\n const range = {min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY};\n const {min: otherMin, max: otherMax} = getUserBounds(otherScale);\n let i, parsed;\n\n function _skip() {\n parsed = _parsed[i];\n const otherValue = parsed[otherScale.axis];\n return !isFinite(parsed[scale.axis]) || otherMin > otherValue || otherMax < otherValue;\n }\n\n for (i = 0; i < ilen; ++i) {\n if (_skip()) {\n continue;\n }\n this.updateRangeFromParsed(range, scale, parsed, stack);\n if (sorted) {\n // if the data is sorted, we don't need to check further from this end of array\n break;\n }\n }\n if (sorted) {\n // in the sorted case, find first non-skipped value from other end of array\n for (i = ilen - 1; i >= 0; --i) {\n if (_skip()) {\n continue;\n }\n this.updateRangeFromParsed(range, scale, parsed, stack);\n break;\n }\n }\n return range;\n }\n\n getAllParsedValues(scale) {\n const parsed = this._cachedMeta._parsed;\n const values = [];\n let i, ilen, value;\n\n for (i = 0, ilen = parsed.length; i < ilen; ++i) {\n value = parsed[i][scale.axis];\n if (isFinite(value)) {\n values.push(value);\n }\n }\n return values;\n }\n\n /**\n\t * @return {number|boolean}\n\t * @protected\n\t */\n getMaxOverflow() {\n return false;\n }\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const iScale = meta.iScale;\n const vScale = meta.vScale;\n const parsed = this.getParsed(index);\n return {\n label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '',\n value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : ''\n };\n }\n\n /**\n\t * @private\n\t */\n _update(mode) {\n const meta = this._cachedMeta;\n this.update(mode || 'default');\n meta._clip = toClip(valueOrDefault(this.options.clip, defaultClip(meta.xScale, meta.yScale, this.getMaxOverflow())));\n }\n\n /**\n\t * @param {string} mode\n\t */\n update(mode) {} // eslint-disable-line no-unused-vars\n\n draw() {\n const ctx = this._ctx;\n const chart = this.chart;\n const meta = this._cachedMeta;\n const elements = meta.data || [];\n const area = chart.chartArea;\n const active = [];\n const start = this._drawStart || 0;\n const count = this._drawCount || (elements.length - start);\n const drawActiveElementsOnTop = this.options.drawActiveElementsOnTop;\n let i;\n\n if (meta.dataset) {\n meta.dataset.draw(ctx, area, start, count);\n }\n\n for (i = start; i < start + count; ++i) {\n const element = elements[i];\n if (element.hidden) {\n continue;\n }\n if (element.active && drawActiveElementsOnTop) {\n active.push(element);\n } else {\n element.draw(ctx, area);\n }\n }\n\n for (i = 0; i < active.length; ++i) {\n active[i].draw(ctx, area);\n }\n }\n\n /**\n\t * Returns a set of predefined style properties that should be used to represent the dataset\n\t * or the data if the index is specified\n\t * @param {number} index - data index\n\t * @param {boolean} [active] - true if hover\n\t * @return {object} style object\n\t */\n getStyle(index, active) {\n const mode = active ? 'active' : 'default';\n return index === undefined && this._cachedMeta.dataset\n ? this.resolveDatasetElementOptions(mode)\n : this.resolveDataElementOptions(index || 0, mode);\n }\n\n /**\n\t * @protected\n\t */\n getContext(index, active, mode) {\n const dataset = this.getDataset();\n let context;\n if (index >= 0 && index < this._cachedMeta.data.length) {\n const element = this._cachedMeta.data[index];\n context = element.$context ||\n (element.$context = createDataContext(this.getContext(), index, element));\n context.parsed = this.getParsed(index);\n context.raw = dataset.data[index];\n context.index = context.dataIndex = index;\n } else {\n context = this.$context ||\n (this.$context = createDatasetContext(this.chart.getContext(), this.index));\n context.dataset = dataset;\n context.index = context.datasetIndex = this.index;\n }\n\n context.active = !!active;\n context.mode = mode;\n return context;\n }\n\n /**\n\t * @param {string} [mode]\n\t * @protected\n\t */\n resolveDatasetElementOptions(mode) {\n return this._resolveElementOptions(this.datasetElementType.id, mode);\n }\n\n /**\n\t * @param {number} index\n\t * @param {string} [mode]\n\t * @protected\n\t */\n resolveDataElementOptions(index, mode) {\n return this._resolveElementOptions(this.dataElementType.id, mode, index);\n }\n\n /**\n\t * @private\n\t */\n _resolveElementOptions(elementType, mode = 'default', index) {\n const active = mode === 'active';\n const cache = this._cachedDataOpts;\n const cacheKey = elementType + '-' + mode;\n const cached = cache[cacheKey];\n const sharing = this.enableOptionSharing && defined(index);\n if (cached) {\n return cloneIfNotShared(cached, sharing);\n }\n const config = this.chart.config;\n const scopeKeys = config.datasetElementScopeKeys(this._type, elementType);\n const prefixes = active ? [`${elementType}Hover`, 'hover', elementType, ''] : [elementType, ''];\n const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);\n const names = Object.keys(defaults.elements[elementType]);\n // context is provided as a function, and is called only if needed,\n // so we don't create a context for each element if not needed.\n const context = () => this.getContext(index, active, mode);\n const values = config.resolveNamedOptions(scopes, names, context, prefixes);\n\n if (values.$shared) {\n // `$shared` indicates this set of options can be shared between multiple elements.\n // Sharing is used to reduce number of properties to change during animation.\n values.$shared = sharing;\n\n // We cache options by `mode`, which can be 'active' for example. This enables us\n // to have the 'active' element options and 'default' options to switch between\n // when interacting.\n cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing));\n }\n\n return values;\n }\n\n\n /**\n\t * @private\n\t */\n _resolveAnimations(index, transition, active) {\n const chart = this.chart;\n const cache = this._cachedDataOpts;\n const cacheKey = `animation-${transition}`;\n const cached = cache[cacheKey];\n if (cached) {\n return cached;\n }\n let options;\n if (chart.options.animation !== false) {\n const config = this.chart.config;\n const scopeKeys = config.datasetAnimationScopeKeys(this._type, transition);\n const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);\n options = config.createResolver(scopes, this.getContext(index, active, transition));\n }\n const animations = new Animations(chart, options && options.animations);\n if (options && options._cacheable) {\n cache[cacheKey] = Object.freeze(animations);\n }\n return animations;\n }\n\n /**\n\t * Utility for getting the options object shared between elements\n\t * @protected\n\t */\n getSharedOptions(options) {\n if (!options.$shared) {\n return;\n }\n return this._sharedOptions || (this._sharedOptions = Object.assign({}, options));\n }\n\n /**\n\t * Utility for determining if `options` should be included in the updated properties\n\t * @protected\n\t */\n includeOptions(mode, sharedOptions) {\n return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled;\n }\n\n /**\n * @todo v4, rename to getSharedOptions and remove excess functions\n */\n _getSharedOptions(start, mode) {\n const firstOpts = this.resolveDataElementOptions(start, mode);\n const previouslySharedOptions = this._sharedOptions;\n const sharedOptions = this.getSharedOptions(firstOpts);\n const includeOptions = this.includeOptions(mode, sharedOptions) || (sharedOptions !== previouslySharedOptions);\n this.updateSharedOptions(sharedOptions, mode, firstOpts);\n return {sharedOptions, includeOptions};\n }\n\n /**\n\t * Utility for updating an element with new properties, using animations when appropriate.\n\t * @protected\n\t */\n updateElement(element, index, properties, mode) {\n if (isDirectUpdateMode(mode)) {\n Object.assign(element, properties);\n } else {\n this._resolveAnimations(index, mode).update(element, properties);\n }\n }\n\n /**\n\t * Utility to animate the shared options, that are potentially affecting multiple elements.\n\t * @protected\n\t */\n updateSharedOptions(sharedOptions, mode, newOptions) {\n if (sharedOptions && !isDirectUpdateMode(mode)) {\n this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions);\n }\n }\n\n /**\n\t * @private\n\t */\n _setStyle(element, index, mode, active) {\n element.active = active;\n const options = this.getStyle(index, active);\n this._resolveAnimations(index, mode, active).update(element, {\n // When going from active to inactive, we need to update to the shared options.\n // This way the once hovered element will end up with the same original shared options instance, after animation.\n options: (!active && this.getSharedOptions(options)) || options\n });\n }\n\n removeHoverStyle(element, datasetIndex, index) {\n this._setStyle(element, index, 'active', false);\n }\n\n setHoverStyle(element, datasetIndex, index) {\n this._setStyle(element, index, 'active', true);\n }\n\n /**\n\t * @private\n\t */\n _removeDatasetHoverStyle() {\n const element = this._cachedMeta.dataset;\n\n if (element) {\n this._setStyle(element, undefined, 'active', false);\n }\n }\n\n /**\n\t * @private\n\t */\n _setDatasetHoverStyle() {\n const element = this._cachedMeta.dataset;\n\n if (element) {\n this._setStyle(element, undefined, 'active', true);\n }\n }\n\n /**\n\t * @private\n\t */\n _resyncElements(resetNewElements) {\n const data = this._data;\n const elements = this._cachedMeta.data;\n\n // Apply changes detected through array listeners\n for (const [method, arg1, arg2] of this._syncList) {\n this[method](arg1, arg2);\n }\n this._syncList = [];\n\n const numMeta = elements.length;\n const numData = data.length;\n const count = Math.min(numData, numMeta);\n\n if (count) {\n // TODO: It is not optimal to always parse the old data\n // This is done because we are not detecting direct assignments:\n // chart.data.datasets[0].data[5] = 10;\n // chart.data.datasets[0].data[5].y = 10;\n this.parse(0, count);\n }\n\n if (numData > numMeta) {\n this._insertElements(numMeta, numData - numMeta, resetNewElements);\n } else if (numData < numMeta) {\n this._removeElements(numData, numMeta - numData);\n }\n }\n\n /**\n\t * @private\n\t */\n _insertElements(start, count, resetNewElements = true) {\n const meta = this._cachedMeta;\n const data = meta.data;\n const end = start + count;\n let i;\n\n const move = (arr) => {\n arr.length += count;\n for (i = arr.length - 1; i >= end; i--) {\n arr[i] = arr[i - count];\n }\n };\n move(data);\n\n for (i = start; i < end; ++i) {\n data[i] = new this.dataElementType();\n }\n\n if (this._parsing) {\n move(meta._parsed);\n }\n this.parse(start, count);\n\n if (resetNewElements) {\n this.updateElements(data, start, count, 'reset');\n }\n }\n\n updateElements(element, start, count, mode) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * @private\n\t */\n _removeElements(start, count) {\n const meta = this._cachedMeta;\n if (this._parsing) {\n const removed = meta._parsed.splice(start, count);\n if (meta._stacked) {\n clearStacks(meta, removed);\n }\n }\n meta.data.splice(start, count);\n }\n\n /**\n\t * @private\n */\n _sync(args) {\n if (this._parsing) {\n this._syncList.push(args);\n } else {\n const [method, arg1, arg2] = args;\n this[method](arg1, arg2);\n }\n this.chart._dataChanges.push([this.index, ...args]);\n }\n\n _onDataPush() {\n const count = arguments.length;\n this._sync(['_insertElements', this.getDataset().data.length - count, count]);\n }\n\n _onDataPop() {\n this._sync(['_removeElements', this._cachedMeta.data.length - 1, 1]);\n }\n\n _onDataShift() {\n this._sync(['_removeElements', 0, 1]);\n }\n\n _onDataSplice(start, count) {\n if (count) {\n this._sync(['_removeElements', start, count]);\n }\n const newCount = arguments.length - 2;\n if (newCount) {\n this._sync(['_insertElements', start, newCount]);\n }\n }\n\n _onDataUnshift() {\n this._sync(['_insertElements', 0, arguments.length]);\n }\n}\n","import type {AnyObject} from '../types/basic.js';\nimport type {Point} from '../types/geometric.js';\nimport type {Animation} from '../types/animation.js';\nimport {isNumber} from '../helpers/helpers.math.js';\n\nexport default class Element {\n\n static defaults = {};\n static defaultRoutes = undefined;\n\n x: number;\n y: number;\n active = false;\n options: O;\n $animations: Record;\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 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 {each, callback as callCallback, uid, valueOrDefault, _elementsEqual, isNullOrUndef, setsEqual, defined, isFunction, _isClickEvent} from '../helpers/helpers.core.js';\nimport {clearCanvas, clipArea, createContext, unclipArea, _isPointInArea, _isDomSupported, retinaScale, getDatasetClipArea} 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\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 // Unset pending resize request now to avoid possible recursion within _resize\n this._resizeBeforeDraw = null;\n this._resize(width, height);\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 args = {\n meta,\n index: meta.index,\n cancelable: true\n };\n // @ts-expect-error\n const clip = getDatasetClipArea(this, meta);\n\n if (this.notifyPlugins('beforeDatasetDraw', args) === false) {\n return;\n }\n\n if (clip) {\n clipArea(ctx, clip);\n }\n\n meta.controller.draw();\n\n if (clip) {\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 event 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","/**\n * @namespace Chart._adapters\n * @since 2.8.0\n * @private\n */\n\nimport type {AnyObject} from '../types/basic.js';\nimport type {ChartOptions} from '../types/index.js';\n\nexport type TimeUnit = 'millisecond' | 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year';\n\nexport interface DateAdapter {\n readonly options: T;\n /**\n * Will called with chart options after adapter creation.\n */\n init(this: DateAdapter, chartOptions: ChartOptions): void;\n /**\n * Returns a map of time formats for the supported formatting units defined\n * in Unit as well as 'datetime' representing a detailed date/time string.\n */\n formats(this: DateAdapter): Record;\n /**\n * Parses the given `value` and return the associated timestamp.\n * @param value - the value to parse (usually comes from the data)\n * @param [format] - the expected data format\n */\n parse(this: DateAdapter, value: unknown, format?: string): number | null;\n /**\n * Returns the formatted date in the specified `format` for a given `timestamp`.\n * @param timestamp - the timestamp to format\n * @param format - the date/time token\n */\n format(this: DateAdapter, timestamp: number, format: string): string;\n /**\n * Adds the specified `amount` of `unit` to the given `timestamp`.\n * @param timestamp - the input timestamp\n * @param amount - the amount to add\n * @param unit - the unit as string\n */\n add(this: DateAdapter, timestamp: number, amount: number, unit: TimeUnit): number;\n /**\n * Returns the number of `unit` between the given timestamps.\n * @param a - the input timestamp (reference)\n * @param b - the timestamp to subtract\n * @param unit - the unit as string\n */\n diff(this: DateAdapter, a: number, b: number, unit: TimeUnit): number;\n /**\n * Returns start of `unit` for the given `timestamp`.\n * @param timestamp - the input timestamp\n * @param unit - the unit as string\n * @param [weekday] - the ISO day of the week with 1 being Monday\n * and 7 being Sunday (only needed if param *unit* is `isoWeek`).\n */\n startOf(this: DateAdapter, timestamp: number, unit: TimeUnit | 'isoWeek', weekday?: number | boolean): number;\n /**\n * Returns end of `unit` for the given `timestamp`.\n * @param timestamp - the input timestamp\n * @param unit - the unit as string\n */\n endOf(this: DateAdapter, timestamp: number, unit: TimeUnit): number;\n}\n\nfunction abstract(): T {\n throw new Error('This method is not implemented: Check that a complete date adapter is provided.');\n}\n\n/**\n * Date adapter (current used by the time scale)\n * @namespace Chart._adapters._date\n * @memberof Chart._adapters\n * @private\n */\nclass DateAdapterBase implements DateAdapter {\n\n /**\n * Override default date adapter methods.\n * Accepts type parameter to define options type.\n * @example\n * Chart._adapters._date.override<{myAdapterOption: string}>({\n * init() {\n * console.log(this.options.myAdapterOption);\n * }\n * })\n */\n static override(\n members: Partial, 'options'>>\n ) {\n Object.assign(DateAdapterBase.prototype, members);\n }\n\n readonly options: AnyObject;\n\n constructor(options?: AnyObject) {\n this.options = options || {};\n }\n\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n init() {}\n\n formats(): Record {\n return abstract();\n }\n\n parse(): number | null {\n return abstract();\n }\n\n format(): string {\n return abstract();\n }\n\n add(): number {\n return abstract();\n }\n\n diff(): number {\n return abstract();\n }\n\n startOf(): number {\n return abstract();\n }\n\n endOf(): number {\n return abstract();\n }\n}\n\nexport default {\n _date: DateAdapterBase as {\n new (options?: AnyObject): DateAdapter;\n override(\n members: Partial, 'options'>>\n ): void;\n }\n};\n","import DatasetController from '../core/core.datasetController.js';\nimport {\n _arrayUnique, isArray, isNullOrUndef,\n valueOrDefault, resolveObjectKey, sign, defined\n} from '../helpers/index.js';\n\nfunction getAllScaleValues(scale, type) {\n if (!scale._cache.$bar) {\n const visibleMetas = scale.getMatchingVisibleMetas(type);\n let values = [];\n\n for (let i = 0, ilen = visibleMetas.length; i < ilen; i++) {\n values = values.concat(visibleMetas[i].controller.getAllParsedValues(scale));\n }\n scale._cache.$bar = _arrayUnique(values.sort((a, b) => a - b));\n }\n return scale._cache.$bar;\n}\n\n/**\n * Computes the \"optimal\" sample size to maintain bars equally sized while preventing overlap.\n * @private\n */\nfunction computeMinSampleSize(meta) {\n const scale = meta.iScale;\n const values = getAllScaleValues(scale, meta.type);\n let min = scale._length;\n let i, ilen, curr, prev;\n const updateMinAndPrev = () => {\n if (curr === 32767 || curr === -32768) {\n // Ignore truncated pixels\n return;\n }\n if (defined(prev)) {\n // curr - prev === 0 is ignored\n min = Math.min(min, Math.abs(curr - prev) || min);\n }\n prev = curr;\n };\n\n for (i = 0, ilen = values.length; i < ilen; ++i) {\n curr = scale.getPixelForValue(values[i]);\n updateMinAndPrev();\n }\n\n prev = undefined;\n for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) {\n curr = scale.getPixelForTick(i);\n updateMinAndPrev();\n }\n\n return min;\n}\n\n/**\n * Computes an \"ideal\" category based on the absolute bar thickness or, if undefined or null,\n * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This\n * mode currently always generates bars equally sized (until we introduce scriptable options?).\n * @private\n */\nfunction computeFitCategoryTraits(index, ruler, options, stackCount) {\n const thickness = options.barThickness;\n let size, ratio;\n\n if (isNullOrUndef(thickness)) {\n size = ruler.min * options.categoryPercentage;\n ratio = options.barPercentage;\n } else {\n // When bar thickness is enforced, category and bar percentages are ignored.\n // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')\n // and deprecate barPercentage since this value is ignored when thickness is absolute.\n size = thickness * stackCount;\n ratio = 1;\n }\n\n return {\n chunk: size / stackCount,\n ratio,\n start: ruler.pixels[index] - (size / 2)\n };\n}\n\n/**\n * Computes an \"optimal\" category that globally arranges bars side by side (no gap when\n * percentage options are 1), based on the previous and following categories. This mode\n * generates bars with different widths when data are not evenly spaced.\n * @private\n */\nfunction computeFlexCategoryTraits(index, ruler, options, stackCount) {\n const pixels = ruler.pixels;\n const curr = pixels[index];\n let prev = index > 0 ? pixels[index - 1] : null;\n let next = index < pixels.length - 1 ? pixels[index + 1] : null;\n const percent = options.categoryPercentage;\n\n if (prev === null) {\n // first data: its size is double based on the next point or,\n // if it's also the last data, we use the scale size.\n prev = curr - (next === null ? ruler.end - ruler.start : next - curr);\n }\n\n if (next === null) {\n // last data: its size is also double based on the previous point.\n next = curr + curr - prev;\n }\n\n const start = curr - (curr - Math.min(prev, next)) / 2 * percent;\n const size = Math.abs(next - prev) / 2 * percent;\n\n return {\n chunk: size / stackCount,\n ratio: options.barPercentage,\n start\n };\n}\n\nfunction parseFloatBar(entry, item, vScale, i) {\n const startValue = vScale.parse(entry[0], i);\n const endValue = vScale.parse(entry[1], i);\n const min = Math.min(startValue, endValue);\n const max = Math.max(startValue, endValue);\n let barStart = min;\n let barEnd = max;\n\n if (Math.abs(min) > Math.abs(max)) {\n barStart = max;\n barEnd = min;\n }\n\n // Store `barEnd` (furthest away from origin) as parsed value,\n // to make stacking straight forward\n item[vScale.axis] = barEnd;\n\n item._custom = {\n barStart,\n barEnd,\n start: startValue,\n end: endValue,\n min,\n max\n };\n}\n\nfunction parseValue(entry, item, vScale, i) {\n if (isArray(entry)) {\n parseFloatBar(entry, item, vScale, i);\n } else {\n item[vScale.axis] = vScale.parse(entry, i);\n }\n return item;\n}\n\nfunction parseArrayOrPrimitive(meta, data, start, count) {\n const iScale = meta.iScale;\n const vScale = meta.vScale;\n const labels = iScale.getLabels();\n const singleScale = iScale === vScale;\n const parsed = [];\n let i, ilen, item, entry;\n\n for (i = start, ilen = start + count; i < ilen; ++i) {\n entry = data[i];\n item = {};\n item[iScale.axis] = singleScale || iScale.parse(labels[i], i);\n parsed.push(parseValue(entry, item, vScale, i));\n }\n return parsed;\n}\n\nfunction isFloatBar(custom) {\n return custom && custom.barStart !== undefined && custom.barEnd !== undefined;\n}\n\nfunction barSign(size, vScale, actualBase) {\n if (size !== 0) {\n return sign(size);\n }\n return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1);\n}\n\nfunction borderProps(properties) {\n let reverse, start, end, top, bottom;\n if (properties.horizontal) {\n reverse = properties.base > properties.x;\n start = 'left';\n end = 'right';\n } else {\n reverse = properties.base < properties.y;\n start = 'bottom';\n end = 'top';\n }\n if (reverse) {\n top = 'end';\n bottom = 'start';\n } else {\n top = 'start';\n bottom = 'end';\n }\n return {start, end, reverse, top, bottom};\n}\n\nfunction setBorderSkipped(properties, options, stack, index) {\n let edge = options.borderSkipped;\n const res = {};\n\n if (!edge) {\n properties.borderSkipped = res;\n return;\n }\n\n if (edge === true) {\n properties.borderSkipped = {top: true, right: true, bottom: true, left: true};\n return;\n }\n\n const {start, end, reverse, top, bottom} = borderProps(properties);\n\n if (edge === 'middle' && stack) {\n properties.enableBorderRadius = true;\n if ((stack._top || 0) === index) {\n edge = top;\n } else if ((stack._bottom || 0) === index) {\n edge = bottom;\n } else {\n res[parseEdge(bottom, start, end, reverse)] = true;\n edge = top;\n }\n }\n\n res[parseEdge(edge, start, end, reverse)] = true;\n properties.borderSkipped = res;\n}\n\nfunction parseEdge(edge, a, b, reverse) {\n if (reverse) {\n edge = swap(edge, a, b);\n edge = startEnd(edge, b, a);\n } else {\n edge = startEnd(edge, a, b);\n }\n return edge;\n}\n\nfunction swap(orig, v1, v2) {\n return orig === v1 ? v2 : orig === v2 ? v1 : orig;\n}\n\nfunction startEnd(v, start, end) {\n return v === 'start' ? start : v === 'end' ? end : v;\n}\n\nfunction setInflateAmount(properties, {inflateAmount}, ratio) {\n properties.inflateAmount = inflateAmount === 'auto'\n ? ratio === 1 ? 0.33 : 0\n : inflateAmount;\n}\n\nexport default class BarController extends DatasetController {\n\n static id = 'bar';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'bar',\n\n categoryPercentage: 0.8,\n barPercentage: 0.9,\n grouped: true,\n\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'base', 'width', 'height']\n }\n }\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n scales: {\n _index_: {\n type: 'category',\n offset: true,\n grid: {\n offset: true\n }\n },\n _value_: {\n type: 'linear',\n beginAtZero: true,\n }\n }\n };\n\n\n /**\n\t * Overriding primitive data parsing since we support mixed primitive/array\n\t * data for float bars\n\t * @protected\n\t */\n parsePrimitiveData(meta, data, start, count) {\n return parseArrayOrPrimitive(meta, data, start, count);\n }\n\n /**\n\t * Overriding array data parsing since we support mixed primitive/array\n\t * data for float bars\n\t * @protected\n\t */\n parseArrayData(meta, data, start, count) {\n return parseArrayOrPrimitive(meta, data, start, count);\n }\n\n /**\n\t * Overriding object data parsing since we support mixed primitive/array\n\t * value-scale data for float bars\n\t * @protected\n\t */\n parseObjectData(meta, data, start, count) {\n const {iScale, vScale} = meta;\n const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;\n const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey;\n const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey;\n const parsed = [];\n let i, ilen, item, obj;\n for (i = start, ilen = start + count; i < ilen; ++i) {\n obj = data[i];\n item = {};\n item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i);\n parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i));\n }\n return parsed;\n }\n\n /**\n\t * @protected\n\t */\n updateRangeFromParsed(range, scale, parsed, stack) {\n super.updateRangeFromParsed(range, scale, parsed, stack);\n const custom = parsed._custom;\n if (custom && scale === this._cachedMeta.vScale) {\n // float bar: only one end of the bar is considered by `super`\n range.min = Math.min(range.min, custom.min);\n range.max = Math.max(range.max, custom.max);\n }\n }\n\n /**\n\t * @return {number|boolean}\n\t * @protected\n\t */\n getMaxOverflow() {\n return 0;\n }\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const {iScale, vScale} = meta;\n const parsed = this.getParsed(index);\n const custom = parsed._custom;\n const value = isFloatBar(custom)\n ? '[' + custom.start + ', ' + custom.end + ']'\n : '' + vScale.getLabelForValue(parsed[vScale.axis]);\n\n return {\n label: '' + iScale.getLabelForValue(parsed[iScale.axis]),\n value\n };\n }\n\n initialize() {\n this.enableOptionSharing = true;\n\n super.initialize();\n\n const meta = this._cachedMeta;\n meta.stack = this.getDataset().stack;\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n this.updateElements(meta.data, 0, meta.data.length, mode);\n }\n\n updateElements(bars, start, count, mode) {\n const reset = mode === 'reset';\n const {index, _cachedMeta: {vScale}} = this;\n const base = vScale.getBasePixel();\n const horizontal = vScale.isHorizontal();\n const ruler = this._getRuler();\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n\n for (let i = start; i < start + count; i++) {\n const parsed = this.getParsed(i);\n const vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? {base, head: base} : this._calculateBarValuePixels(i);\n const ipixels = this._calculateBarIndexPixels(i, ruler);\n const stack = (parsed._stacks || {})[vScale.axis];\n\n const properties = {\n horizontal,\n base: vpixels.base,\n enableBorderRadius: !stack || isFloatBar(parsed._custom) || (index === stack._top || index === stack._bottom),\n x: horizontal ? vpixels.head : ipixels.center,\n y: horizontal ? ipixels.center : vpixels.head,\n height: horizontal ? ipixels.size : Math.abs(vpixels.size),\n width: horizontal ? Math.abs(vpixels.size) : ipixels.size\n };\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, bars[i].active ? 'active' : mode);\n }\n const options = properties.options || bars[i].options;\n setBorderSkipped(properties, options, stack, index);\n setInflateAmount(properties, options, ruler.ratio);\n this.updateElement(bars[i], i, properties, mode);\n }\n }\n\n /**\n\t * Returns the stacks based on groups and bar visibility.\n\t * @param {number} [last] - The dataset index\n\t * @param {number} [dataIndex] - The data index of the ruler\n\t * @returns {string[]} The list of stack IDs\n\t * @private\n\t */\n _getStacks(last, dataIndex) {\n const {iScale} = this._cachedMeta;\n const metasets = iScale.getMatchingVisibleMetas(this._type)\n .filter(meta => meta.controller.options.grouped);\n const stacked = iScale.options.stacked;\n const stacks = [];\n const currentParsed = this._cachedMeta.controller.getParsed(dataIndex);\n const iScaleValue = currentParsed && currentParsed[iScale.axis];\n\n const skipNull = (meta) => {\n const parsed = meta._parsed.find(item => item[iScale.axis] === iScaleValue);\n const val = parsed && parsed[meta.vScale.axis];\n\n if (isNullOrUndef(val) || isNaN(val)) {\n return true;\n }\n };\n\n for (const meta of metasets) {\n if (dataIndex !== undefined && skipNull(meta)) {\n continue;\n }\n\n // stacked | meta.stack\n // | found | not found | undefined\n // false | x | x | x\n // true | | x |\n // undefined | | x | x\n if (stacked === false || stacks.indexOf(meta.stack) === -1 ||\n\t\t\t\t(stacked === undefined && meta.stack === undefined)) {\n stacks.push(meta.stack);\n }\n if (meta.index === last) {\n break;\n }\n }\n\n // No stacks? that means there is no visible data. Let's still initialize an `undefined`\n // stack where possible invisible bars will be located.\n // https://github.com/chartjs/Chart.js/issues/6368\n if (!stacks.length) {\n stacks.push(undefined);\n }\n\n return stacks;\n }\n\n /**\n\t * Returns the effective number of stacks based on groups and bar visibility.\n\t * @private\n\t */\n _getStackCount(index) {\n return this._getStacks(undefined, index).length;\n }\n\n _getAxisCount() {\n return this._getAxis().length;\n }\n\n getFirstScaleIdForIndexAxis() {\n const scales = this.chart.scales;\n const indexScaleId = this.chart.options.indexAxis;\n return Object.keys(scales).filter(key => scales[key].axis === indexScaleId).shift();\n }\n\n _getAxis() {\n const axis = {};\n const firstScaleAxisId = this.getFirstScaleIdForIndexAxis();\n for (const dataset of this.chart.data.datasets) {\n axis[valueOrDefault(\n this.chart.options.indexAxis === 'x' ? dataset.xAxisID : dataset.yAxisID, firstScaleAxisId\n )] = true;\n }\n return Object.keys(axis);\n }\n\n /**\n\t * Returns the stack index for the given dataset based on groups and bar visibility.\n\t * @param {number} [datasetIndex] - The dataset index\n\t * @param {string} [name] - The stack name to find\n * @param {number} [dataIndex]\n\t * @returns {number} The stack index\n\t * @private\n\t */\n _getStackIndex(datasetIndex, name, dataIndex) {\n const stacks = this._getStacks(datasetIndex, dataIndex);\n const index = (name !== undefined)\n ? stacks.indexOf(name)\n : -1; // indexOf returns -1 if element is not present\n\n return (index === -1)\n ? stacks.length - 1\n : index;\n }\n\n /**\n\t * @private\n\t */\n _getRuler() {\n const opts = this.options;\n const meta = this._cachedMeta;\n const iScale = meta.iScale;\n const pixels = [];\n let i, ilen;\n\n for (i = 0, ilen = meta.data.length; i < ilen; ++i) {\n pixels.push(iScale.getPixelForValue(this.getParsed(i)[iScale.axis], i));\n }\n\n const barThickness = opts.barThickness;\n const min = barThickness || computeMinSampleSize(meta);\n\n return {\n min,\n pixels,\n start: iScale._startPixel,\n end: iScale._endPixel,\n stackCount: this._getStackCount(),\n scale: iScale,\n grouped: opts.grouped,\n // bar thickness ratio used for non-grouped bars\n ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage\n };\n }\n\n /**\n\t * Note: pixel values are not clamped to the scale area.\n\t * @private\n\t */\n _calculateBarValuePixels(index) {\n const {_cachedMeta: {vScale, _stacked, index: datasetIndex}, options: {base: baseValue, minBarLength}} = this;\n const actualBase = baseValue || 0;\n const parsed = this.getParsed(index);\n const custom = parsed._custom;\n const floating = isFloatBar(custom);\n let value = parsed[vScale.axis];\n let start = 0;\n let length = _stacked ? this.applyStack(vScale, parsed, _stacked) : value;\n let head, size;\n\n if (length !== value) {\n start = length - value;\n length = value;\n }\n\n if (floating) {\n value = custom.barStart;\n length = custom.barEnd - custom.barStart;\n // bars crossing origin are not stacked\n if (value !== 0 && sign(value) !== sign(custom.barEnd)) {\n start = 0;\n }\n start += value;\n }\n\n const startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start;\n let base = vScale.getPixelForValue(startValue);\n\n if (this.chart.getDataVisibility(index)) {\n head = vScale.getPixelForValue(start + length);\n } else {\n // When not visible, no height\n head = base;\n }\n\n size = head - base;\n\n if (Math.abs(size) < minBarLength) {\n size = barSign(size, vScale, actualBase) * minBarLength;\n if (value === actualBase) {\n base -= size / 2;\n }\n const startPixel = vScale.getPixelForDecimal(0);\n const endPixel = vScale.getPixelForDecimal(1);\n const min = Math.min(startPixel, endPixel);\n const max = Math.max(startPixel, endPixel);\n base = Math.max(Math.min(base, max), min);\n head = base + size;\n\n if (_stacked && !floating) {\n // visual data coordinates after applying minBarLength\n parsed._stacks[vScale.axis]._visualValues[datasetIndex] = vScale.getValueForPixel(head) - vScale.getValueForPixel(base);\n }\n }\n\n if (base === vScale.getPixelForValue(actualBase)) {\n const halfGrid = sign(size) * vScale.getLineWidthForValue(actualBase) / 2;\n base += halfGrid;\n size -= halfGrid;\n }\n\n return {\n size,\n base,\n head,\n center: head + size / 2\n };\n }\n\n /**\n\t * @private\n\t */\n _calculateBarIndexPixels(index, ruler) {\n const scale = ruler.scale;\n const options = this.options;\n const skipNull = options.skipNull;\n const maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity);\n let center, size;\n const axisCount = this._getAxisCount();\n if (ruler.grouped) {\n const stackCount = skipNull ? this._getStackCount(index) : ruler.stackCount;\n const range = options.barThickness === 'flex'\n ? computeFlexCategoryTraits(index, ruler, options, stackCount * axisCount)\n : computeFitCategoryTraits(index, ruler, options, stackCount * axisCount);\n const axisID = this.chart.options.indexAxis === 'x' ? this.getDataset().xAxisID : this.getDataset().yAxisID;\n const axisNumber = this._getAxis().indexOf(valueOrDefault(axisID, this.getFirstScaleIdForIndexAxis()));\n const stackIndex = this._getStackIndex(this.index, this._cachedMeta.stack, skipNull ? index : undefined) + axisNumber;\n center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);\n size = Math.min(maxBarThickness, range.chunk * range.ratio);\n } else {\n // For non-grouped bar charts, exact pixel values are used\n center = scale.getPixelForValue(this.getParsed(index)[scale.axis], index);\n size = Math.min(maxBarThickness, ruler.min * ruler.ratio);\n }\n\n\n return {\n base: center - size / 2,\n head: center + size / 2,\n center,\n size\n };\n }\n\n draw() {\n const meta = this._cachedMeta;\n const vScale = meta.vScale;\n const rects = meta.data;\n const ilen = rects.length;\n let i = 0;\n\n for (; i < ilen; ++i) {\n if (this.getParsed(i)[vScale.axis] !== null && !rects[i].hidden) {\n rects[i].draw(this._ctx);\n }\n }\n }\n\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {isObject, resolveObjectKey, toPercentage, toDimension, valueOrDefault} from '../helpers/helpers.core.js';\nimport {formatNumber} from '../helpers/helpers.intl.js';\nimport {toRadians, PI, TAU, HALF_PI, _angleBetween} from '../helpers/helpers.math.js';\n\n/**\n * @typedef { import('../core/core.controller.js').default } Chart\n */\n\nfunction getRatioAndOffset(rotation, circumference, cutout) {\n let ratioX = 1;\n let ratioY = 1;\n let offsetX = 0;\n let offsetY = 0;\n // If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc\n if (circumference < TAU) {\n const startAngle = rotation;\n const endAngle = startAngle + circumference;\n const startX = Math.cos(startAngle);\n const startY = Math.sin(startAngle);\n const endX = Math.cos(endAngle);\n const endY = Math.sin(endAngle);\n const calcMax = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout);\n const calcMin = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout);\n const maxX = calcMax(0, startX, endX);\n const maxY = calcMax(HALF_PI, startY, endY);\n const minX = calcMin(PI, startX, endX);\n const minY = calcMin(PI + HALF_PI, startY, endY);\n ratioX = (maxX - minX) / 2;\n ratioY = (maxY - minY) / 2;\n offsetX = -(maxX + minX) / 2;\n offsetY = -(maxY + minY) / 2;\n }\n return {ratioX, ratioY, offsetX, offsetY};\n}\n\nexport default class DoughnutController extends DatasetController {\n\n static id = 'doughnut';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'arc',\n animation: {\n // Boolean - Whether we animate the rotation of the Doughnut\n animateRotate: true,\n // Boolean - Whether we animate scaling the Doughnut from the centre\n animateScale: false\n },\n animations: {\n numbers: {\n type: 'number',\n properties: ['circumference', 'endAngle', 'innerRadius', 'outerRadius', 'startAngle', 'x', 'y', 'offset', 'borderWidth', 'spacing']\n },\n },\n // The percentage of the chart that we cut out of the middle.\n cutout: '50%',\n\n // The rotation of the chart, where the first data arc begins.\n rotation: 0,\n\n // The total circumference of the chart.\n circumference: 360,\n\n // The outer radius of the chart\n radius: '100%',\n\n // Spacing between arcs\n spacing: 0,\n\n indexAxis: 'r',\n };\n\n static descriptors = {\n _scriptable: (name) => name !== 'spacing',\n _indexable: (name) => name !== 'spacing' && !name.startsWith('borderDash') && !name.startsWith('hoverBorderDash'),\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n aspectRatio: 1,\n\n // Need to override these to give a nice default\n plugins: {\n legend: {\n labels: {\n generateLabels(chart) {\n const data = chart.data;\n if (data.labels.length && data.datasets.length) {\n const {labels: {pointStyle, color}} = chart.legend.options;\n\n return data.labels.map((label, i) => {\n const meta = chart.getDatasetMeta(0);\n const style = meta.controller.getStyle(i);\n\n return {\n text: label,\n fillStyle: style.backgroundColor,\n strokeStyle: style.borderColor,\n fontColor: color,\n lineWidth: style.borderWidth,\n pointStyle: pointStyle,\n hidden: !chart.getDataVisibility(i),\n\n // Extra data used for toggling the correct item\n index: i\n };\n });\n }\n return [];\n }\n },\n\n onClick(e, legendItem, legend) {\n legend.chart.toggleDataVisibility(legendItem.index);\n legend.chart.update();\n }\n }\n }\n };\n\n constructor(chart, datasetIndex) {\n super(chart, datasetIndex);\n\n this.enableOptionSharing = true;\n this.innerRadius = undefined;\n this.outerRadius = undefined;\n this.offsetX = undefined;\n this.offsetY = undefined;\n }\n\n linkScales() {}\n\n /**\n\t * Override data parsing, since we are not using scales\n\t */\n parse(start, count) {\n const data = this.getDataset().data;\n const meta = this._cachedMeta;\n\n if (this._parsing === false) {\n meta._parsed = data;\n } else {\n let getter = (i) => +data[i];\n\n if (isObject(data[start])) {\n const {key = 'value'} = this._parsing;\n getter = (i) => +resolveObjectKey(data[i], key);\n }\n\n let i, ilen;\n for (i = start, ilen = start + count; i < ilen; ++i) {\n meta._parsed[i] = getter(i);\n }\n }\n }\n\n /**\n\t * @private\n\t */\n _getRotation() {\n return toRadians(this.options.rotation - 90);\n }\n\n /**\n\t * @private\n\t */\n _getCircumference() {\n return toRadians(this.options.circumference);\n }\n\n /**\n\t * Get the maximal rotation & circumference extents\n\t * across all visible datasets.\n\t */\n _getRotationExtents() {\n let min = TAU;\n let max = -TAU;\n\n for (let i = 0; i < this.chart.data.datasets.length; ++i) {\n if (this.chart.isDatasetVisible(i) && this.chart.getDatasetMeta(i).type === this._type) {\n const controller = this.chart.getDatasetMeta(i).controller;\n const rotation = controller._getRotation();\n const circumference = controller._getCircumference();\n\n min = Math.min(min, rotation);\n max = Math.max(max, rotation + circumference);\n }\n }\n\n return {\n rotation: min,\n circumference: max - min,\n };\n }\n\n /**\n\t * @param {string} mode\n\t */\n update(mode) {\n const chart = this.chart;\n const {chartArea} = chart;\n const meta = this._cachedMeta;\n const arcs = meta.data;\n const spacing = this.getMaxBorderWidth() + this.getMaxOffset(arcs) + this.options.spacing;\n const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0);\n const cutout = Math.min(toPercentage(this.options.cutout, maxSize), 1);\n const chartWeight = this._getRingWeight(this.index);\n\n // Compute the maximal rotation & circumference limits.\n // If we only consider our dataset, this can cause problems when two datasets\n // are both less than a circle with different rotations (starting angles)\n const {circumference, rotation} = this._getRotationExtents();\n const {ratioX, ratioY, offsetX, offsetY} = getRatioAndOffset(rotation, circumference, cutout);\n const maxWidth = (chartArea.width - spacing) / ratioX;\n const maxHeight = (chartArea.height - spacing) / ratioY;\n const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);\n const outerRadius = toDimension(this.options.radius, maxRadius);\n const innerRadius = Math.max(outerRadius * cutout, 0);\n const radiusLength = (outerRadius - innerRadius) / this._getVisibleDatasetWeightTotal();\n this.offsetX = offsetX * outerRadius;\n this.offsetY = offsetY * outerRadius;\n\n meta.total = this.calculateTotal();\n\n this.outerRadius = outerRadius - radiusLength * this._getRingWeightOffset(this.index);\n this.innerRadius = Math.max(this.outerRadius - radiusLength * chartWeight, 0);\n\n this.updateElements(arcs, 0, arcs.length, mode);\n }\n\n /**\n * @private\n */\n _circumference(i, reset) {\n const opts = this.options;\n const meta = this._cachedMeta;\n const circumference = this._getCircumference();\n if ((reset && opts.animation.animateRotate) || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) {\n return 0;\n }\n return this.calculateCircumference(meta._parsed[i] * circumference / TAU);\n }\n\n updateElements(arcs, start, count, mode) {\n const reset = mode === 'reset';\n const chart = this.chart;\n const chartArea = chart.chartArea;\n const opts = chart.options;\n const animationOpts = opts.animation;\n const centerX = (chartArea.left + chartArea.right) / 2;\n const centerY = (chartArea.top + chartArea.bottom) / 2;\n const animateScale = reset && animationOpts.animateScale;\n const innerRadius = animateScale ? 0 : this.innerRadius;\n const outerRadius = animateScale ? 0 : this.outerRadius;\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n let startAngle = this._getRotation();\n let i;\n\n for (i = 0; i < start; ++i) {\n startAngle += this._circumference(i, reset);\n }\n\n for (i = start; i < start + count; ++i) {\n const circumference = this._circumference(i, reset);\n const arc = arcs[i];\n const properties = {\n x: centerX + this.offsetX,\n y: centerY + this.offsetY,\n startAngle,\n endAngle: startAngle + circumference,\n circumference,\n outerRadius,\n innerRadius\n };\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, arc.active ? 'active' : mode);\n }\n startAngle += circumference;\n\n this.updateElement(arc, i, properties, mode);\n }\n }\n\n calculateTotal() {\n const meta = this._cachedMeta;\n const metaData = meta.data;\n let total = 0;\n let i;\n\n for (i = 0; i < metaData.length; i++) {\n const value = meta._parsed[i];\n if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) {\n total += Math.abs(value);\n }\n }\n\n return total;\n }\n\n calculateCircumference(value) {\n const total = this._cachedMeta.total;\n if (total > 0 && !isNaN(value)) {\n return TAU * (Math.abs(value) / total);\n }\n return 0;\n }\n\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const chart = this.chart;\n const labels = chart.data.labels || [];\n const value = formatNumber(meta._parsed[index], chart.options.locale);\n\n return {\n label: labels[index] || '',\n value,\n };\n }\n\n getMaxBorderWidth(arcs) {\n let max = 0;\n const chart = this.chart;\n let i, ilen, meta, controller, options;\n\n if (!arcs) {\n // Find the outmost visible dataset\n for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {\n if (chart.isDatasetVisible(i)) {\n meta = chart.getDatasetMeta(i);\n arcs = meta.data;\n controller = meta.controller;\n break;\n }\n }\n }\n\n if (!arcs) {\n return 0;\n }\n\n for (i = 0, ilen = arcs.length; i < ilen; ++i) {\n options = controller.resolveDataElementOptions(i);\n if (options.borderAlign !== 'inner') {\n max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0);\n }\n }\n return max;\n }\n\n getMaxOffset(arcs) {\n let max = 0;\n\n for (let i = 0, ilen = arcs.length; i < ilen; ++i) {\n const options = this.resolveDataElementOptions(i);\n max = Math.max(max, options.offset || 0, options.hoverOffset || 0);\n }\n return max;\n }\n\n /**\n\t * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly\n\t * @private\n\t */\n _getRingWeightOffset(datasetIndex) {\n let ringWeightOffset = 0;\n\n for (let i = 0; i < datasetIndex; ++i) {\n if (this.chart.isDatasetVisible(i)) {\n ringWeightOffset += this._getRingWeight(i);\n }\n }\n\n return ringWeightOffset;\n }\n\n /**\n\t * @private\n\t */\n _getRingWeight(datasetIndex) {\n return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0);\n }\n\n /**\n\t * Returns the sum of all visible data set weights.\n\t * @private\n\t */\n _getVisibleDatasetWeightTotal() {\n return this._getRingWeightOffset(this.chart.data.datasets.length) || 1;\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {toRadians, PI, formatNumber, _parseObjectDataRadialScale} from '../helpers/index.js';\n\nexport default class PolarAreaController extends DatasetController {\n\n static id = 'polarArea';\n\n /**\n * @type {any}\n */\n static defaults = {\n dataElementType: 'arc',\n animation: {\n animateRotate: true,\n animateScale: true\n },\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'startAngle', 'endAngle', 'innerRadius', 'outerRadius']\n },\n },\n indexAxis: 'r',\n startAngle: 0,\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n aspectRatio: 1,\n\n plugins: {\n legend: {\n labels: {\n generateLabels(chart) {\n const data = chart.data;\n if (data.labels.length && data.datasets.length) {\n const {labels: {pointStyle, color}} = chart.legend.options;\n\n return data.labels.map((label, i) => {\n const meta = chart.getDatasetMeta(0);\n const style = meta.controller.getStyle(i);\n\n return {\n text: label,\n fillStyle: style.backgroundColor,\n strokeStyle: style.borderColor,\n fontColor: color,\n lineWidth: style.borderWidth,\n pointStyle: pointStyle,\n hidden: !chart.getDataVisibility(i),\n\n // Extra data used for toggling the correct item\n index: i\n };\n });\n }\n return [];\n }\n },\n\n onClick(e, legendItem, legend) {\n legend.chart.toggleDataVisibility(legendItem.index);\n legend.chart.update();\n }\n }\n },\n\n scales: {\n r: {\n type: 'radialLinear',\n angleLines: {\n display: false\n },\n beginAtZero: true,\n grid: {\n circular: true\n },\n pointLabels: {\n display: false\n },\n startAngle: 0\n }\n }\n };\n\n constructor(chart, datasetIndex) {\n super(chart, datasetIndex);\n\n this.innerRadius = undefined;\n this.outerRadius = undefined;\n }\n\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const chart = this.chart;\n const labels = chart.data.labels || [];\n const value = formatNumber(meta._parsed[index].r, chart.options.locale);\n\n return {\n label: labels[index] || '',\n value,\n };\n }\n\n parseObjectData(meta, data, start, count) {\n return _parseObjectDataRadialScale.bind(this)(meta, data, start, count);\n }\n\n update(mode) {\n const arcs = this._cachedMeta.data;\n\n this._updateRadius();\n this.updateElements(arcs, 0, arcs.length, mode);\n }\n\n /**\n * @protected\n */\n getMinMax() {\n const meta = this._cachedMeta;\n const range = {min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY};\n\n meta.data.forEach((element, index) => {\n const parsed = this.getParsed(index).r;\n\n if (!isNaN(parsed) && this.chart.getDataVisibility(index)) {\n if (parsed < range.min) {\n range.min = parsed;\n }\n\n if (parsed > range.max) {\n range.max = parsed;\n }\n }\n });\n\n return range;\n }\n\n /**\n\t * @private\n\t */\n _updateRadius() {\n const chart = this.chart;\n const chartArea = chart.chartArea;\n const opts = chart.options;\n const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);\n\n const outerRadius = Math.max(minSize / 2, 0);\n const innerRadius = Math.max(opts.cutoutPercentage ? (outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);\n const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount();\n\n this.outerRadius = outerRadius - (radiusLength * this.index);\n this.innerRadius = this.outerRadius - radiusLength;\n }\n\n updateElements(arcs, start, count, mode) {\n const reset = mode === 'reset';\n const chart = this.chart;\n const opts = chart.options;\n const animationOpts = opts.animation;\n const scale = this._cachedMeta.rScale;\n const centerX = scale.xCenter;\n const centerY = scale.yCenter;\n const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI;\n let angle = datasetStartAngle;\n let i;\n\n const defaultAngle = 360 / this.countVisibleElements();\n\n for (i = 0; i < start; ++i) {\n angle += this._computeAngle(i, mode, defaultAngle);\n }\n for (i = start; i < start + count; i++) {\n const arc = arcs[i];\n let startAngle = angle;\n let endAngle = angle + this._computeAngle(i, mode, defaultAngle);\n let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(this.getParsed(i).r) : 0;\n angle = endAngle;\n\n if (reset) {\n if (animationOpts.animateScale) {\n outerRadius = 0;\n }\n if (animationOpts.animateRotate) {\n startAngle = endAngle = datasetStartAngle;\n }\n }\n\n const properties = {\n x: centerX,\n y: centerY,\n innerRadius: 0,\n outerRadius,\n startAngle,\n endAngle,\n options: this.resolveDataElementOptions(i, arc.active ? 'active' : mode)\n };\n\n this.updateElement(arc, i, properties, mode);\n }\n }\n\n countVisibleElements() {\n const meta = this._cachedMeta;\n let count = 0;\n\n meta.data.forEach((element, index) => {\n if (!isNaN(this.getParsed(index).r) && this.chart.getDataVisibility(index)) {\n count++;\n }\n });\n\n return count;\n }\n\n /**\n\t * @private\n\t */\n _computeAngle(index, mode, defaultAngle) {\n return this.chart.getDataVisibility(index)\n ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle)\n : 0;\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {valueOrDefault} from '../helpers/helpers.core.js';\n\nexport default class BubbleController extends DatasetController {\n\n static id = 'bubble';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'point',\n\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'borderWidth', 'radius']\n }\n }\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n scales: {\n x: {\n type: 'linear'\n },\n y: {\n type: 'linear'\n }\n }\n };\n\n initialize() {\n this.enableOptionSharing = true;\n super.initialize();\n }\n\n /**\n\t * Parse array of primitive values\n\t * @protected\n\t */\n parsePrimitiveData(meta, data, start, count) {\n const parsed = super.parsePrimitiveData(meta, data, start, count);\n for (let i = 0; i < parsed.length; i++) {\n parsed[i]._custom = this.resolveDataElementOptions(i + start).radius;\n }\n return parsed;\n }\n\n /**\n\t * Parse array of arrays\n\t * @protected\n\t */\n parseArrayData(meta, data, start, count) {\n const parsed = super.parseArrayData(meta, data, start, count);\n for (let i = 0; i < parsed.length; i++) {\n const item = data[start + i];\n parsed[i]._custom = valueOrDefault(item[2], this.resolveDataElementOptions(i + start).radius);\n }\n return parsed;\n }\n\n /**\n\t * Parse array of objects\n\t * @protected\n\t */\n parseObjectData(meta, data, start, count) {\n const parsed = super.parseObjectData(meta, data, start, count);\n for (let i = 0; i < parsed.length; i++) {\n const item = data[start + i];\n parsed[i]._custom = valueOrDefault(item && item.r && +item.r, this.resolveDataElementOptions(i + start).radius);\n }\n return parsed;\n }\n\n /**\n\t * @protected\n\t */\n getMaxOverflow() {\n const data = this._cachedMeta.data;\n\n let max = 0;\n for (let i = data.length - 1; i >= 0; --i) {\n max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);\n }\n return max > 0 && max;\n }\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const labels = this.chart.data.labels || [];\n const {xScale, yScale} = meta;\n const parsed = this.getParsed(index);\n const x = xScale.getLabelForValue(parsed.x);\n const y = yScale.getLabelForValue(parsed.y);\n const r = parsed._custom;\n\n return {\n label: labels[index] || '',\n value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')'\n };\n }\n\n update(mode) {\n const points = this._cachedMeta.data;\n\n // Update Points\n this.updateElements(points, 0, points.length, mode);\n }\n\n updateElements(points, start, count, mode) {\n const reset = mode === 'reset';\n const {iScale, vScale} = this._cachedMeta;\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n\n for (let i = start; i < start + count; i++) {\n const point = points[i];\n const parsed = !reset && this.getParsed(i);\n const properties = {};\n const iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]);\n const vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]);\n\n properties.skip = isNaN(iPixel) || isNaN(vPixel);\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n\n if (reset) {\n properties.options.radius = 0;\n }\n }\n\n this.updateElement(point, i, properties, mode);\n }\n }\n\n /**\n\t * @param {number} index\n\t * @param {string} [mode]\n\t * @protected\n\t */\n resolveDataElementOptions(index, mode) {\n const parsed = this.getParsed(index);\n let values = super.resolveDataElementOptions(index, mode);\n\n // In case values were cached (and thus frozen), we need to clone the values\n if (values.$shared) {\n values = Object.assign({}, values, {$shared: false});\n }\n\n // Custom radius resolution\n const radius = values.radius;\n if (mode !== 'active') {\n values.radius = 0;\n }\n values.radius += valueOrDefault(parsed && parsed._custom, radius);\n\n return values;\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {isNullOrUndef} from '../helpers/index.js';\nimport {isNumber} from '../helpers/helpers.math.js';\nimport {_getStartAndCountOfVisiblePoints, _scaleRangesChanged} from '../helpers/helpers.extras.js';\n\nexport default class LineController extends DatasetController {\n\n static id = 'line';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: 'line',\n dataElementType: 'point',\n\n showLine: true,\n spanGaps: false,\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n scales: {\n _index_: {\n type: 'category',\n },\n _value_: {\n type: 'linear',\n },\n }\n };\n\n initialize() {\n this.enableOptionSharing = true;\n this.supportsDecimation = true;\n super.initialize();\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n const {dataset: line, data: points = [], _dataset} = meta;\n // @ts-ignore\n const animationsDisabled = this.chart._animationsDisabled;\n let {start, count} = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);\n\n this._drawStart = start;\n this._drawCount = count;\n\n if (_scaleRangesChanged(meta)) {\n start = 0;\n count = points.length;\n }\n\n // Update Line\n line._chart = this.chart;\n line._datasetIndex = this.index;\n line._decimated = !!_dataset._decimated;\n line.points = points;\n\n const options = this.resolveDatasetElementOptions(mode);\n if (!this.options.showLine) {\n options.borderWidth = 0;\n }\n options.segment = this.options.segment;\n this.updateElement(line, undefined, {\n animated: !animationsDisabled,\n options\n }, mode);\n\n // Update Points\n this.updateElements(points, start, count, mode);\n }\n\n updateElements(points, start, count, mode) {\n const reset = mode === 'reset';\n const {iScale, vScale, _stacked, _dataset} = this._cachedMeta;\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const {spanGaps, segment} = this.options;\n const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;\n const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';\n const end = start + count;\n const pointsCount = points.length;\n let prevParsed = start > 0 && this.getParsed(start - 1);\n\n for (let i = 0; i < pointsCount; ++i) {\n const point = points[i];\n const properties = directUpdate ? point : {};\n\n if (i < start || i >= end) {\n properties.skip = true;\n continue;\n }\n\n const parsed = this.getParsed(i);\n const nullData = isNullOrUndef(parsed[vAxis]);\n const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);\n const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);\n\n properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;\n properties.stop = i > 0 && (Math.abs(parsed[iAxis] - prevParsed[iAxis])) > maxGapLength;\n if (segment) {\n properties.parsed = parsed;\n properties.raw = _dataset.data[i];\n }\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n }\n\n if (!directUpdate) {\n this.updateElement(point, i, properties, mode);\n }\n\n prevParsed = parsed;\n }\n }\n\n /**\n\t * @protected\n\t */\n getMaxOverflow() {\n const meta = this._cachedMeta;\n const dataset = meta.dataset;\n const border = dataset.options && dataset.options.borderWidth || 0;\n const data = meta.data || [];\n if (!data.length) {\n return border;\n }\n const firstPoint = data[0].size(this.resolveDataElementOptions(0));\n const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));\n return Math.max(border, firstPoint, lastPoint) / 2;\n }\n\n draw() {\n const meta = this._cachedMeta;\n meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis);\n super.draw();\n }\n}\n","import DoughnutController from './controller.doughnut.js';\n\n// Pie charts are Doughnut chart with different defaults\nexport default class PieController extends DoughnutController {\n\n static id = 'pie';\n\n /**\n * @type {any}\n */\n static defaults = {\n // The percentage of the chart that we cut out of the middle.\n cutout: 0,\n\n // The rotation of the chart, where the first data arc begins.\n rotation: 0,\n\n // The total circumference of the chart.\n circumference: 360,\n\n // The outer radius of the chart\n radius: '100%'\n };\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {_parseObjectDataRadialScale} from '../helpers/index.js';\n\nexport default class RadarController extends DatasetController {\n\n static id = 'radar';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: 'line',\n dataElementType: 'point',\n indexAxis: 'r',\n showLine: true,\n elements: {\n line: {\n fill: 'start'\n }\n },\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n aspectRatio: 1,\n\n scales: {\n r: {\n type: 'radialLinear',\n }\n }\n };\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const vScale = this._cachedMeta.vScale;\n const parsed = this.getParsed(index);\n\n return {\n label: vScale.getLabels()[index],\n value: '' + vScale.getLabelForValue(parsed[vScale.axis])\n };\n }\n\n parseObjectData(meta, data, start, count) {\n return _parseObjectDataRadialScale.bind(this)(meta, data, start, count);\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n const line = meta.dataset;\n const points = meta.data || [];\n const labels = meta.iScale.getLabels();\n\n // Update Line\n line.points = points;\n // In resize mode only point locations change, so no need to set the points or options.\n if (mode !== 'resize') {\n const options = this.resolveDatasetElementOptions(mode);\n if (!this.options.showLine) {\n options.borderWidth = 0;\n }\n\n const properties = {\n _loop: true,\n _fullLoop: labels.length === points.length,\n options\n };\n\n this.updateElement(line, undefined, properties, mode);\n }\n\n // Update Points\n this.updateElements(points, 0, points.length, mode);\n }\n\n updateElements(points, start, count, mode) {\n const scale = this._cachedMeta.rScale;\n const reset = mode === 'reset';\n\n for (let i = start; i < start + count; i++) {\n const point = points[i];\n const options = this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n const pointPosition = scale.getPointPositionForValue(i, this.getParsed(i).r);\n\n const x = reset ? scale.xCenter : pointPosition.x;\n const y = reset ? scale.yCenter : pointPosition.y;\n\n const properties = {\n x,\n y,\n angle: pointPosition.angle,\n skip: isNaN(x) || isNaN(y),\n options\n };\n\n this.updateElement(point, i, properties, mode);\n }\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {isNullOrUndef} from '../helpers/index.js';\nimport {isNumber} from '../helpers/helpers.math.js';\nimport {_getStartAndCountOfVisiblePoints, _scaleRangesChanged} from '../helpers/helpers.extras.js';\n\nexport default class ScatterController extends DatasetController {\n\n static id = 'scatter';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'point',\n showLine: false,\n fill: false\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n\n interaction: {\n mode: 'point'\n },\n\n scales: {\n x: {\n type: 'linear'\n },\n y: {\n type: 'linear'\n }\n }\n };\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const labels = this.chart.data.labels || [];\n const {xScale, yScale} = meta;\n const parsed = this.getParsed(index);\n const x = xScale.getLabelForValue(parsed.x);\n const y = yScale.getLabelForValue(parsed.y);\n\n return {\n label: labels[index] || '',\n value: '(' + x + ', ' + y + ')'\n };\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n const {data: points = []} = meta;\n // @ts-ignore\n const animationsDisabled = this.chart._animationsDisabled;\n let {start, count} = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);\n\n this._drawStart = start;\n this._drawCount = count;\n\n if (_scaleRangesChanged(meta)) {\n start = 0;\n count = points.length;\n }\n\n if (this.options.showLine) {\n\n // https://github.com/chartjs/Chart.js/issues/11333\n if (!this.datasetElementType) {\n this.addElements();\n }\n const {dataset: line, _dataset} = meta;\n\n // Update Line\n line._chart = this.chart;\n line._datasetIndex = this.index;\n line._decimated = !!_dataset._decimated;\n line.points = points;\n\n const options = this.resolveDatasetElementOptions(mode);\n options.segment = this.options.segment;\n this.updateElement(line, undefined, {\n animated: !animationsDisabled,\n options\n }, mode);\n } else if (this.datasetElementType) {\n // https://github.com/chartjs/Chart.js/issues/11333\n delete meta.dataset;\n this.datasetElementType = false;\n }\n\n // Update Points\n this.updateElements(points, start, count, mode);\n }\n\n addElements() {\n const {showLine} = this.options;\n\n if (!this.datasetElementType && showLine) {\n this.datasetElementType = this.chart.registry.getElement('line');\n }\n\n super.addElements();\n }\n\n updateElements(points, start, count, mode) {\n const reset = mode === 'reset';\n const {iScale, vScale, _stacked, _dataset} = this._cachedMeta;\n const firstOpts = this.resolveDataElementOptions(start, mode);\n const sharedOptions = this.getSharedOptions(firstOpts);\n const includeOptions = this.includeOptions(mode, sharedOptions);\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const {spanGaps, segment} = this.options;\n const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;\n const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';\n let prevParsed = start > 0 && this.getParsed(start - 1);\n\n for (let i = start; i < start + count; ++i) {\n const point = points[i];\n const parsed = this.getParsed(i);\n const properties = directUpdate ? point : {};\n const nullData = isNullOrUndef(parsed[vAxis]);\n const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);\n const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);\n\n properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;\n properties.stop = i > 0 && (Math.abs(parsed[iAxis] - prevParsed[iAxis])) > maxGapLength;\n if (segment) {\n properties.parsed = parsed;\n properties.raw = _dataset.data[i];\n }\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n }\n\n if (!directUpdate) {\n this.updateElement(point, i, properties, mode);\n }\n\n prevParsed = parsed;\n }\n\n this.updateSharedOptions(sharedOptions, mode, firstOpts);\n }\n\n /**\n\t * @protected\n\t */\n getMaxOverflow() {\n const meta = this._cachedMeta;\n const data = meta.data || [];\n\n if (!this.options.showLine) {\n let max = 0;\n for (let i = data.length - 1; i >= 0; --i) {\n max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);\n }\n return max > 0 && max;\n }\n\n const dataset = meta.dataset;\n const border = dataset.options && dataset.options.borderWidth || 0;\n\n if (!data.length) {\n return border;\n }\n\n const firstPoint = data[0].size(this.resolveDataElementOptions(0));\n const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));\n return Math.max(border, firstPoint, lastPoint) / 2;\n }\n}\n","import Element from '../core/core.element.js';\nimport {_angleBetween, getAngleFromPoint, TAU, HALF_PI, valueOrDefault} from '../helpers/index.js';\nimport {PI, _angleDiff, _normalizeAngle, _isBetween, _limitValue} from '../helpers/helpers.math.js';\nimport {_readValueToProps} from '../helpers/helpers.options.js';\nimport type {ArcOptions, Point} from '../types/index.js';\n\nfunction clipSelf(ctx: CanvasRenderingContext2D, element: ArcElement, endAngle: number) {\n const {startAngle, x, y, outerRadius, innerRadius, options} = element;\n const {borderWidth, borderJoinStyle} = options;\n const outerAngleClip = Math.min(borderWidth / outerRadius, _normalizeAngle(startAngle - endAngle));\n ctx.beginPath();\n ctx.arc(x, y, outerRadius - borderWidth / 2, startAngle + outerAngleClip / 2, endAngle - outerAngleClip / 2);\n\n if (innerRadius > 0) {\n const innerAngleClip = Math.min(borderWidth / innerRadius, _normalizeAngle(startAngle - endAngle));\n ctx.arc(x, y, innerRadius + borderWidth / 2, endAngle - innerAngleClip / 2, startAngle + innerAngleClip / 2, true);\n } else {\n const clipWidth = Math.min(borderWidth / 2, outerRadius * _normalizeAngle(startAngle - endAngle));\n\n if (borderJoinStyle === 'round') {\n ctx.arc(x, y, clipWidth, endAngle - PI / 2, startAngle + PI / 2, true);\n } else if (borderJoinStyle === 'bevel') {\n const r = 2 * clipWidth * clipWidth;\n const endX = -r * Math.cos(endAngle + PI / 2) + x;\n const endY = -r * Math.sin(endAngle + PI / 2) + y;\n const startX = r * Math.cos(startAngle + PI / 2) + x;\n const startY = r * Math.sin(startAngle + PI / 2) + y;\n ctx.lineTo(endX, endY);\n ctx.lineTo(startX, startY);\n }\n }\n ctx.closePath();\n\n ctx.moveTo(0, 0);\n ctx.rect(0, 0, ctx.canvas.width, ctx.canvas.height);\n\n ctx.clip('evenodd');\n}\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, 𝜃) 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, borderRadius} = 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 (options.selfJoin && endAngle - startAngle >= PI && borderRadius === 0 && borderJoinStyle !== 'miter') {\n clipSelf(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 selfJoin: false,\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 nonZeroBetween = _angleBetween(angle, startAngle, endAngle) && startAngle !== endAngle;\n const betweenAngles = _circumference >= TAU || nonZeroBetween;\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 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.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, 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","import {DoughnutController, PolarAreaController, defaults} 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\nfunction containsDefaultColorsDefenitions() {\n return defaults.borderColor !== 'rgba(0,0,0,0.1)' || defaults.backgroundColor !== 'rgba(0,0,0,0.1)';\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 const containsColorDefenition = (\n containsColorsDefinitions(datasets) ||\n containsColorsDefinition(chartOptions) ||\n (elements && containsColorsDefinitions(elements)) ||\n containsDefaultColorsDefenitions());\n\n if (!options.forceOverride && containsColorDefenition) {\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 a segment -> need to add another point before this,\n postponed.unshift(point);\n } else {\n points.push(point);\n if (!last) {\n // In the middle of a 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, getDatasetClipArea} 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 {chart, index, 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 const meta = chart.getDatasetMeta(index);\n const clip = getDatasetClipArea(chart, meta);\n if (target && line.points.length) {\n clipArea(ctx, area);\n doFill(ctx, {line, target, above, below, area, scale, axis, clip});\n unclipArea(ctx);\n }\n}\n\nfunction doFill(ctx, cfg) {\n const {line, target, above, below, area, scale, clip} = cfg;\n const property = line._loop ? 'angle' : cfg.axis;\n\n ctx.save();\n\n let fillColor = below;\n if (below !== above) {\n if (property === 'x') {\n clipVertical(ctx, target, area.top);\n fill(ctx, {line, target, color: above, scale, property, clip});\n ctx.restore();\n ctx.save();\n clipVertical(ctx, target, area.bottom);\n } else if (property === 'y') {\n clipHorizontal(ctx, target, area.left);\n fill(ctx, {line, target, color: below, scale, property, clip});\n ctx.restore();\n ctx.save();\n clipHorizontal(ctx, target, area.right);\n fillColor = above;\n }\n }\n fill(ctx, {line, target, color: fillColor, scale, property, clip});\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 clipHorizontal(ctx, target, clipX) {\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(clipX, firstPoint.y);\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(clipX, lastPoint.y);\n }\n }\n\n ctx.lineTo(clipX, target.first().y);\n ctx.closePath();\n ctx.clip();\n}\n\nfunction fill(ctx, cfg) {\n const {line, target, property, color, scale, clip} = 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, clip, 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, clip, bounds) {\n const chartArea = scale.chart.chartArea;\n const {property, start, end} = bounds || {};\n\n if (property === 'x' || property === 'y') {\n let left, top, right, bottom;\n\n if (property === 'x') {\n left = start;\n top = chartArea.top;\n right = end;\n bottom = chartArea.bottom;\n } else {\n left = chartArea.left;\n top = start;\n right = chartArea.right;\n bottom = end;\n }\n\n ctx.beginPath();\n\n if (clip) {\n left = Math.max(left, clip.left);\n right = Math.min(right, clip.right);\n top = Math.max(top, clip.top);\n bottom = Math.min(bottom, clip.bottom);\n }\n\n ctx.rect(left, top, right - left, 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 // No visible items where found, return false so we don't have to divide by 0 which reduces in NaN\n if (count === 0 || xSet.size === 0) {\n return false;\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","// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-nocheck\n\n/**\n * @namespace Chart\n */\nimport Chart from './core/core.controller.js';\n\nimport * as helpers from './helpers/index.js';\nimport _adapters from './core/core.adapters.js';\nimport Animation from './core/core.animation.js';\nimport animator from './core/core.animator.js';\nimport Animations from './core/core.animations.js';\nimport * as controllers from './controllers/index.js';\nimport DatasetController from './core/core.datasetController.js';\nimport Element from './core/core.element.js';\nimport * as elements from './elements/index.js';\nimport Interaction from './core/core.interaction.js';\nimport layouts from './core/core.layouts.js';\nimport * as platforms from './platform/index.js';\nimport * as plugins from './plugins/index.js';\nimport registry from './core/core.registry.js';\nimport Scale from './core/core.scale.js';\nimport * as scales from './scales/index.js';\nimport Ticks from './core/core.ticks.js';\n\n// Register built-ins\nChart.register(controllers, scales, elements, plugins);\n\nChart.helpers = {...helpers};\nChart._adapters = _adapters;\nChart.Animation = Animation;\nChart.Animations = Animations;\nChart.animator = animator;\nChart.controllers = registry.controllers.items;\nChart.DatasetController = DatasetController;\nChart.Element = Element;\nChart.elements = elements;\nChart.Interaction = Interaction;\nChart.layouts = layouts;\nChart.platforms = platforms;\nChart.Scale = Scale;\nChart.Ticks = Ticks;\n\n// Compatibility with ESM extensions\nObject.assign(Chart, controllers, scales, elements, plugins, platforms);\nChart.Chart = Chart;\n\nif (typeof window !== 'undefined') {\n window.Chart = Chart;\n}\n\nexport default Chart;\n\n"],"names":["noop","uid","id","isNullOrUndef","value","isArray","Array","type","Object","prototype","toString","call","slice","isObject","isNumberFinite","Number","isFinite","finiteOrDefault","defaultValue","valueOrDefault","toPercentage","dimension","endsWith","parseFloat","toDimension","callback","fn","args","thisArg","apply","each","loopable","reverse","i","len","keys","length","_elementsEqual","a0","a1","ilen","v0","v1","datasetIndex","index","clone","source","map","target","create","klen","k","isValidKey","key","indexOf","_merger","options","tval","sval","merge","sources","merger","current","mergeIf","_mergerIf","hasOwnProperty","keyResolvers","v","x","o","y","_splitKey","parts","split","tmp","part","push","resolveObjectKey","obj","resolver","_getKeyResolver","_capitalize","str","charAt","toUpperCase","defined","isFunction","setsEqual","a","b","size","item","has","_isClickEvent","e","PI","Math","TAU","PITAU","INFINITY","POSITIVE_INFINITY","RAD_PER_DEG","HALF_PI","QUARTER_PI","TWO_THIRDS_PI","log10","sign","almostEquals","epsilon","abs","niceNum","range","roundedRange","round","niceRange","pow","floor","fraction","_factorize","result","sqrt","sort","pop","isNumber","n","Symbol","toPrimitive","isNonPrimitive","isNaN","almostWhole","rounded","_setMinAndMaxByKey","array","property","min","max","toRadians","degrees","toDegrees","radians","_decimalPlaces","isFiniteNumber","p","getAngleFromPoint","centrePoint","anglePoint","distanceFromXCenter","distanceFromYCenter","radialDistanceFromCenter","angle","atan2","distance","distanceBetweenPoints","pt1","pt2","_angleDiff","_normalizeAngle","_angleBetween","start","end","sameAngleIsFullCircle","s","angleToStart","angleToEnd","startToAngle","endToAngle","_limitValue","_int16Range","_isBetween","_lookup","table","cmp","mid","hi","lo","_lookupByKey","last","ti","_rlookupByKey","_filterBetween","values","arrayEvents","listenArrayEvents","listener","_chartjs","listeners","defineProperty","configurable","enumerable","forEach","method","base","res","this","object","unlistenArrayEvents","stub","splice","_arrayUnique","items","set","Set","from","requestAnimFrame","window","requestAnimationFrame","throttled","argsToUse","ticking","debounce","delay","timeout","clearTimeout","setTimeout","_toLeftRightCenter","align","_alignStartEnd","_textX","left","right","rtl","_getStartAndCountOfVisiblePoints","meta","points","animationsDisabled","pointCount","count","_sorted","iScale","vScale","_parsed","spanGaps","dataset","axis","minDefined","maxDefined","getUserBounds","getPixelForValue","distanceToDefinedLo","findIndex","point","distanceToDefinedHi","_scaleRangesChanged","xScale","yScale","_scaleRanges","newRanges","xmin","xmax","ymin","ymax","changed","assign","Animator","constructor","_request","_charts","Map","_running","_lastDate","undefined","_notify","chart","anims","date","callbacks","numSteps","duration","initial","currentStep","_refresh","_update","Date","now","remaining","running","draw","_active","_total","tick","_getAnims","charts","get","complete","progress","listen","event","cb","add","reduce","acc","cur","_duration","stop","cancel","remove","delete","animator","lim","l","h","p2b","n2b","b2n","n2p","map$1","A","B","C","D","E","F","c","d","f","hex","h1","h2","eq","hexString","r","g","isShort","alpha","HUE_RE","hsl2rgbn","hsv2rgbn","hwb2rgbn","w","rgb","rgb2hsl","hueValue","calln","hsl2rgb","hue","hueParse","m","exec","p1","p2","hwb2rgb","hsv2rgb","Z","Y","X","W","V","U","T","S","R","Q","P","O","N","M","L","K","G","H","I","J","names$1","OiceXe","antiquewEte","aqua","aquamarRe","azuY","beige","bisque","black","blanKedOmond","Xe","XeviTet","bPwn","burlywood","caMtXe","KartYuse","KocTate","cSO","cSnflowerXe","cSnsilk","crimson","cyan","xXe","xcyan","xgTMnPd","xWay","xgYF","xgYy","xkhaki","xmagFta","xTivegYF","xSange","xScEd","xYd","xsOmon","xsHgYF","xUXe","xUWay","xUgYy","xQe","xviTet","dAppRk","dApskyXe","dimWay","dimgYy","dodgerXe","fiYbrick","flSOwEte","foYstWAn","fuKsia","gaRsbSo","ghostwEte","gTd","gTMnPd","Way","gYF","gYFLw","gYy","honeyMw","hotpRk","RdianYd","Rdigo","ivSy","khaki","lavFMr","lavFMrXsh","lawngYF","NmoncEffon","ZXe","ZcSO","Zcyan","ZgTMnPdLw","ZWay","ZgYF","ZgYy","ZpRk","ZsOmon","ZsHgYF","ZskyXe","ZUWay","ZUgYy","ZstAlXe","ZLw","lime","limegYF","lRF","magFta","maPon","VaquamarRe","VXe","VScEd","VpurpN","VsHgYF","VUXe","VsprRggYF","VQe","VviTetYd","midnightXe","mRtcYam","mistyPse","moccasR","navajowEte","navy","Tdlace","Tive","TivedBb","Sange","SangeYd","ScEd","pOegTMnPd","pOegYF","pOeQe","pOeviTetYd","papayawEp","pHKpuff","peru","pRk","plum","powMrXe","purpN","YbeccapurpN","Yd","Psybrown","PyOXe","saddNbPwn","sOmon","sandybPwn","sHgYF","sHshell","siFna","silver","skyXe","UXe","UWay","UgYy","snow","sprRggYF","stAlXe","tan","teO","tEstN","tomato","Qe","viTet","JHt","wEte","wEtesmoke","Lw","LwgYF","names","nameParse","unpacked","tkeys","j","ok","nk","replace","parseInt","unpack","transparent","toLowerCase","RGB_RE","to","modHSL","ratio","proto","fromObject","input","functionParse","rgbParse","Color","ret","_rgb","_valid","valid","rgbString","hslString","mix","color","weight","c1","c2","w2","w1","interpolate","t","rgb1","rgb2","clearer","greyscale","val","opaquer","negate","lighten","darken","saturate","desaturate","rotate","deg","isPatternOrGradient","getHoverColor","numbers","colors","intlCache","formatNumber","num","locale","cacheKey","JSON","stringify","formatter","Intl","NumberFormat","getNumberFormat","format","formatters","numeric","tickValue","ticks","notation","delta","maxTick","calculateDelta","logDelta","numDecimal","minimumFractionDigits","maximumFractionDigits","logarithmic","remain","significand","includes","Ticks","overrides","descriptors","getScope","node","root","scope","Defaults","_descriptors","_appliers","animation","backgroundColor","borderColor","datasets","devicePixelRatio","context","platform","getDevicePixelRatio","elements","events","font","family","style","lineHeight","hover","hoverBackgroundColor","ctx","hoverBorderColor","hoverColor","indexAxis","interaction","mode","intersect","includeInvisible","maintainAspectRatio","onHover","onClick","parsing","plugins","responsive","scale","scales","showLine","drawActiveElementsOnTop","describe","override","route","name","targetScope","targetName","scopeObject","targetScopeObject","privateName","defineProperties","writable","local","appliers","defaults","_scriptable","startsWith","_indexable","_fallback","easing","loop","properties","active","resize","show","animations","visible","hide","autoPadding","padding","top","bottom","display","offset","beginAtZero","bounds","clip","grace","grid","lineWidth","drawOnChartArea","drawTicks","tickLength","tickWidth","_ctx","tickColor","border","dash","dashOffset","width","title","text","minRotation","maxRotation","mirror","textStrokeWidth","textStrokeColor","autoSkip","autoSkipPadding","labelOffset","minor","major","crossAlign","showLabelBackdrop","backdropColor","backdropPadding","_isDomSupported","document","_getParentNode","domNode","parent","parentNode","host","parseMaxStyle","styleValue","parentProperty","valueInPixels","getComputedStyle","element","ownerDocument","defaultView","getStyle","el","getPropertyValue","positions","getPositionedStyle","styles","suffix","pos","height","useOffsetPos","shadowRoot","getRelativePosition","canvas","currentDevicePixelRatio","borderBox","boxSizing","paddings","borders","box","touches","offsetX","offsetY","rect","getBoundingClientRect","clientX","clientY","getCanvasPosition","xOffset","yOffset","round1","getMaximumSize","bbWidth","bbHeight","aspectRatio","margins","maxWidth","maxHeight","containerSize","container","containerStyle","containerBorder","containerPadding","clientWidth","clientHeight","getContainerSize","retinaScale","forceRatio","forceStyle","pixelRatio","deviceHeight","deviceWidth","setTransform","supportsEventListenerOptions","passiveSupported","passive","addEventListener","removeEventListener","readUsedSize","matches","match","toFontString","_measureText","data","gc","longest","string","textWidth","measureText","_longestText","arrayOfThings","cache","garbageCollect","save","jlen","thing","nestedThing","restore","gcLen","_alignPixel","pixel","halfWidth","clearCanvas","getContext","resetTransform","clearRect","drawPoint","drawPointLegend","cornerRadius","xOffsetW","yOffsetW","pointStyle","rotation","radius","rad","translate","drawImage","beginPath","ellipse","arc","closePath","moveTo","sin","cos","lineTo","SQRT1_2","fill","borderWidth","stroke","_isPointInArea","area","margin","clipArea","unclipArea","_steppedLineTo","previous","flip","midpoint","_bezierCurveTo","bezierCurveTo","cp1x","cp2x","cp1y","cp2y","decorateText","line","opts","strikethrough","underline","metrics","actualBoundingBoxLeft","actualBoundingBoxRight","actualBoundingBoxAscent","actualBoundingBoxDescent","yDecoration","strokeStyle","fillStyle","decorationWidth","drawBackdrop","oldColor","fillRect","renderText","lines","strokeWidth","strokeColor","translation","textAlign","textBaseline","setRenderOpts","backdrop","strokeText","fillText","addRoundedRectPath","topLeft","bottomLeft","bottomRight","topRight","_createResolver","scopes","prefixes","rootScopes","fallback","getTarget","finalRootScopes","_resolve","toStringTag","_cacheable","_scopes","_rootScopes","_getTarget","Proxy","deleteProperty","prop","_keys","_cached","proxy","prefix","readKey","needsSubResolver","createSubResolver","_resolveWithPrefixes","getOwnPropertyDescriptor","Reflect","getPrototypeOf","getKeysFromAllScopes","ownKeys","storage","_storage","_attachContext","subProxy","descriptorDefaults","_proxy","_context","_subProxy","_stack","setContext","receiver","isScriptable","getValue","Error","join","_resolveScriptable","isIndexable","arr","filter","_resolveArray","_resolveWithContext","allKeys","scriptable","indexable","_allKeys","resolve","resolveFallback","addScopes","parentScopes","parentFallback","allScopes","addScopesFromKey","subGetTarget","resolveKeysFromAllScopes","_parseObjectDataRadialScale","_parsing","parsed","parse","EPSILON","getPoint","skip","getValueAxis","splineCurve","firstPoint","middlePoint","afterPoint","next","d01","d12","s01","s12","fa","fb","splineCurveMonotone","valueAxis","pointsLen","deltaK","mK","pointBefore","pointCurrent","pointAfter","slopeDelta","alphaK","betaK","tauK","squaredMagnitude","monotoneAdjust","iPixel","vPixel","monotoneCompute","capControlPoint","pt","_updateBezierControlPoints","controlPoints","cubicInterpolationMode","prev","tension","capBezierPoints","inArea","inAreaPrev","inAreaNext","atEdge","elasticIn","elasticOut","effects","linear","easeInQuad","easeOutQuad","easeInOutQuad","easeInCubic","easeOutCubic","easeInOutCubic","easeInQuart","easeOutQuart","easeInOutQuart","easeInQuint","easeOutQuint","easeInOutQuint","easeInSine","easeOutSine","easeInOutSine","easeInExpo","easeOutExpo","easeInOutExpo","easeInCirc","easeOutCirc","easeInOutCirc","easeInElastic","easeOutElastic","easeInOutElastic","easeInBack","easeOutBack","easeInOutBack","easeInBounce","easeOutBounce","easeInOutBounce","_pointInLine","_steppedInterpolation","_bezierInterpolation","cp1","cp2","LINE_HEIGHT","FONT_STYLE","toLineHeight","numberOrZero","_readValueToProps","props","objProps","read","toTRBL","toTRBLCorners","toPadding","toFont","console","warn","inputs","info","cacheable","_addGrace","minmax","change","keepZero","createContext","parentContext","getRtlAdapter","rectX","setWidth","xPlus","leftForLtr","itemWidth","getRightToLeftAdapter","_itemWidth","overrideTextDirection","direction","original","getPropertyPriority","setProperty","prevTextDirection","restoreTextDirection","propertyFn","between","compare","normalize","normalizeSegment","_boundSegment","segment","startBound","endBound","getSegment","prevValue","inside","subStart","shouldStart","shouldStop","_boundSegments","segments","sub","_computeSegments","segmentOptions","_loop","findStartAndEnd","splitByStyles","solidSegments","_fullLoop","chartContext","_chart","baseStyle","readStyle","_datasetIndex","prevStyle","addStyle","st","dir","p0","p0DataIndex","p1DataIndex","styleChanged","doSplitByStyles","borderCapStyle","borderDash","borderDashOffset","borderJoinStyle","replacer","getSizeForArea","chartArea","field","getDatasetClipArea","_clip","disabled","getDatasetArea","pixelSize","fontStyle","fontFamily","binarySearch","metaset","controller","_cachedMeta","lookupMethod","_reversePixels","_sharedOptions","getRange","evaluateInteractionItems","position","handler","metasets","getSortedVisibleDatasetMetas","getIntersectItems","useFinalPosition","isPointInArea","inRange","getNearestCartesianItems","distanceMetric","useX","useY","deltaX","deltaY","getDistanceMetricForAxis","minDistance","center","getCenterPoint","getNearestItems","startAngle","endAngle","getProps","getNearestRadialItems","getAxisItems","rangeMethod","intersectsItem","Interaction","modes","getDatasetMeta","nearest","STATIC_POSITIONS","filterByPosition","filterDynamicPositionByAxis","sortByWeight","setLayoutDims","layouts","params","stacks","wrap","stack","stackWeight","placed","buildStacks","vBoxMaxWidth","hBoxMaxHeight","layout","fullSize","factor","horizontal","availableWidth","availableHeight","getCombinedMax","maxPadding","updateMaxPadding","boxPadding","updateDims","getPadding","newWidth","outerWidth","newHeight","outerHeight","widthChanged","heightChanged","same","other","getMargins","marginForPositions","fitBoxes","boxes","refitBoxes","refit","update","setBoxDims","placeBoxes","userPadding","addBox","_layers","z","removeBox","layoutItem","configure","minPadding","layoutBoxes","isHorizontal","wrapBoxes","centerHorizontal","centerVertical","leftAndTop","concat","rightAndBottom","vertical","buildLayoutBoxes","verticalBoxes","horizontalBoxes","beforeLayout","visibleVerticalBoxCount","total","freeze","updatePos","handleMaxPadding","BasePlatform","acquireContext","releaseContext","isAttached","updateConfig","config","BasicPlatform","EXPANDO_KEY","EVENT_TYPES","touchstart","touchmove","touchend","pointerenter","pointerdown","pointermove","pointerup","pointerleave","pointerout","isNullOrEmpty","eventListenerOptions","removeListener","nodeListContains","nodeList","contains","createAttachObserver","observer","MutationObserver","entries","trigger","entry","addedNodes","removedNodes","observe","childList","subtree","createDetachObserver","drpListeningCharts","oldDevicePixelRatio","onWindowResize","dpr","createResizeObserver","ResizeObserver","contentRect","listenDevicePixelRatioChanges","releaseObserver","disconnect","unlistenDevicePixelRatioChanges","createProxyAndListen","native","fromNativeEvent","addListener","DomPlatform","renderHeight","getAttribute","renderWidth","displayWidth","displayHeight","initCanvas","removeAttribute","setAttribute","proxies","$proxies","attach","detach","isConnected","_detectPlatform","OffscreenCanvas","interpolators","boolean","c0","helpersColor","number","Animation","cfg","currentValue","_fn","_easing","_start","_target","_prop","_from","_to","_promises","elapsed","wait","promises","Promise","rej","resolved","Animations","_properties","animationOptions","animatedProps","getOwnPropertyNames","option","_animateOptions","newOptions","$shared","$animations","resolveTargetOptions","_createAnimations","anim","all","awaitAll","then","scaleClip","allowedOverflow","getSortedDatasetIndices","filterVisible","_getSortedDatasetMetas","applyStack","dsIndex","singleMode","otherValue","found","isStacked","stacked","getOrCreateStack","stackKey","indexValue","subStack","getLastIndexInStack","positive","getMatchingVisibleMetas","updateStacks","_stacks","iAxis","vAxis","indexScale","valueScale","getStackKey","_top","_bottom","_visualValues","getFirstScaleId","shift","clearStacks","isDirectUpdateMode","cloneIfNotShared","cached","shared","DatasetController","static","_cachedDataOpts","getMeta","_type","_data","_objectData","_drawStart","_drawCount","enableOptionSharing","supportsDecimation","$context","_syncList","datasetElementType","dataElementType","initialize","linkScales","_stacked","addElements","isPluginEnabled","updateIndex","getDataset","chooseId","xid","xAxisID","yid","yAxisID","rid","rAxisID","iid","iAxisID","vid","vAxisID","getScaleForId","rScale","scaleID","_getOtherScale","reset","_destroy","_dataCheck","iAxisKey","vAxisKey","adata","convertObjectDataToArray","isExtensible","buildOrUpdateElements","resetNewElements","stackChanged","oldStacked","_resyncElements","scopeKeys","datasetScopeKeys","getOptionScopes","createResolver","sorted","parseArrayData","parseObjectData","parsePrimitiveData","isNotInOrderComparedToPrev","labels","getLabels","singleScale","xAxisKey","yAxisKey","getParsed","getDataElement","updateRangeFromParsed","parsedValue","NaN","getMinMax","canStack","otherScale","hidden","createStack","NEGATIVE_INFINITY","otherMin","otherMax","_skip","getAllParsedValues","getMaxOverflow","getLabelAndValue","label","getLabelForValue","toClip","defaultClip","resolveDatasetElementOptions","resolveDataElementOptions","dataIndex","raw","createDataContext","createDatasetContext","_resolveElementOptions","elementType","sharing","datasetElementScopeKeys","resolveNamedOptions","_resolveAnimations","transition","datasetAnimationScopeKeys","getSharedOptions","includeOptions","sharedOptions","_animationsDisabled","_getSharedOptions","firstOpts","previouslySharedOptions","updateSharedOptions","updateElement","_setStyle","removeHoverStyle","setHoverStyle","_removeDatasetHoverStyle","_setDatasetHoverStyle","arg1","arg2","numMeta","numData","_insertElements","_removeElements","move","updateElements","removed","_sync","_dataChanges","_onDataPush","arguments","_onDataPop","_onDataShift","_onDataSplice","newCount","_onDataUnshift","Element","tooltipPosition","hasValue","final","tickOpts","determinedMaxTicks","_tickSize","maxScale","_length","maxChart","_maxLength","determineMaxTicks","ticksLimit","maxTicksLimit","majorIndices","enabled","getMajorIndices","numMajorIndices","first","newTicks","spacing","ceil","skipMajors","evenMajorSpacing","diff","getEvenSpacing","factors","calculateSpacing","avgMajorSpacing","majorStart","majorEnd","offsetFromEdge","edge","getTicksLimit","ticksLength","sample","numItems","increment","getPixelForGridLine","offsetGridLines","validIndex","_startPixel","_endPixel","lineValue","getPixelForTick","getTickMarkLength","getTitleHeight","titleAlign","reverseAlign","Scale","super","_margins","paddingTop","paddingBottom","paddingLeft","paddingRight","labelRotation","_range","_gridLineItems","_labelItems","_labelSizes","_longestTextCache","_userMax","_userMin","_suggestedMax","_suggestedMin","_ticksLength","_borderValue","_cache","_dataLimitsCached","init","suggestedMin","suggestedMax","metas","getTicks","xLabels","yLabels","getLabelItems","_computeLabelItems","beforeUpdate","sampleSize","beforeSetDimensions","setDimensions","afterSetDimensions","beforeDataLimits","determineDataLimits","afterDataLimits","beforeBuildTicks","buildTicks","afterBuildTicks","samplingEnabled","_convertTicksToLabels","beforeCalculateLabelRotation","calculateLabelRotation","afterCalculateLabelRotation","afterAutoSkip","beforeFit","fit","afterFit","afterUpdate","startPixel","endPixel","reversePixels","_alignToPixels","alignToPixels","_callHooks","notifyPlugins","beforeTickToLabelConversion","generateTickLabels","afterTickToLabelConversion","numTicks","maxLabelDiagonal","_isVisible","labelSizes","_getLabelSizes","maxLabelWidth","widest","maxLabelHeight","highest","asin","minSize","titleOpts","gridOpts","titleHeight","tickPadding","angleRadians","labelHeight","labelWidth","_calculatePadding","_handleMargins","isRotated","labelsBelowTicks","offsetLeft","offsetRight","isFullSize","_computeLabelSizes","caches","widths","heights","tickFont","fontString","nestedLabel","widestLabelSize","highestLabelSize","_resolveTickFontOptions","valueAt","idx","getValueForPixel","getPixelForDecimal","decimal","getDecimalForPixel","getBasePixel","getBaseValue","createTickContext","optionTicks","rot","_computeGridLineItems","tl","borderOpts","axisWidth","axisHalfWidth","alignBorderValue","borderValue","alignedLineValue","tx1","ty1","tx2","ty2","x1","y1","x2","y2","positionAxisID","limit","step","optsAtIndex","optsAtIndexBorder","lineColor","tickBorderDash","tickBorderDashOffset","tickAndPadding","hTickAndPadding","lineCount","textOffset","_getXAxisLabelAlignment","_getYAxisLabelAlignment","halfCount","tickTextAlign","labelPadding","_computeLabelArea","drawBackground","getLineWidthForValue","drawGrid","drawLine","setLineDash","lineDashOffset","drawBorder","lastLineWidth","drawLabels","renderTextOptions","drawTitle","titleX","titleY","titleArgs","tz","gz","bz","axisID","_maxDigits","fontSize","TypedRegistry","isForType","isPrototypeOf","register","parentScope","isIChartComponent","itemDefaults","defaultRoutes","routes","propertyParts","sourceName","sourceScope","routeDefaults","registerDefaults","unregister","Registry","controllers","_typedRegistries","_each","addControllers","addPlugins","addScales","getController","_get","getElement","getPlugin","getScale","removeControllers","removeElements","removePlugins","removeScales","typedRegistry","arg","reg","_getRegistryForType","_exec","itemReg","registry","component","camelMethod","PluginService","_init","notify","hook","_createDescriptors","descriptor","plugin","callCallback","cancelable","invalidate","_oldCache","_notifyStateChanges","localIds","allPlugins","getOpts","pluginOpts","createDescriptors","previousDescriptors","some","pluginScopeKeys","getIndexAxis","datasetDefaults","idMatchesAxis","determineAxis","scaleOptions","getAxisFromDataset","mergeScaleConfig","chartDefaults","configScales","chartIndexAxis","scaleConf","error","boundDs","retrieveAxisFromDatasets","defaultId","getDefaultScaleIDFromAxis","defaultScaleOptions","defaultID","getAxisFromDefaultScaleID","initOptions","initData","keyCache","keysCached","cachedKeys","generate","addIfFound","Config","_config","initConfig","_scopeCache","_resolverCache","clearCache","clear","datasetType","additionalOptionScopes","_cachedScopes","mainScope","resetCache","keyLists","chartOptionScopes","subPrefixes","getResolver","hasFunction","needContext","resolverCache","KNOWN_POSITIONS","positionIsHorizontal","compare2Level","l1","l2","onAnimationsComplete","onComplete","onAnimationProgress","onProgress","getCanvas","getElementById","instances","getChart","moveNumericKeys","intKey","Chart","invalidatePlugins","userConfig","initialCanvas","existingChart","_options","_aspectRatio","_metasets","_lastEvent","_listeners","_responsiveListeners","_sortedMetasets","_plugins","_hiddenIndices","attached","_doResize","resizeDelay","_initialize","bindEvents","_resizeBeforeDraw","_resize","newSize","newRatio","onResize","render","ensureScalesHaveIDs","axisOptions","buildOrUpdateScales","scaleOpts","updated","isRadial","dposition","dtype","scaleType","hasUpdated","_updateMetasets","_destroyDatasetMeta","_removeUnreferencedMetasets","_dataset","buildOrUpdateControllers","newControllers","order","isDatasetVisible","ControllerClass","_resetElements","animsDisabled","_updateScales","_checkEventBindings","_updateHiddenIndices","_minPadding","_updateLayout","_updateDatasets","_eventHandler","_updateHoverStyles","existingEvents","newEvents","unbindEvents","changes","_getUniformDataChanges","datasetCount","makeSet","changeSet","noArea","_idx","_updateDataset","layers","_drawDatasets","_drawDataset","getElementsAtEventForMode","getVisibleDatasetCount","setDatasetVisibility","toggleDataVisibility","getDataVisibility","_updateVisibility","_stop","destroy","toBase64Image","toDataURL","bindUserEvents","bindResponsiveEvents","_add","_remove","detached","updateHoverStyle","getActiveElements","setActiveElements","activeElements","lastActive","pluginId","replay","hoverOptions","deactivated","activated","inChartArea","eventFilter","_handleEvent","_getActiveElements","isClick","lastEvent","determineLastEvent","abstract","DateAdapterBase","members","formats","startOf","endOf","_adapters","_date","computeMinSampleSize","$bar","visibleMetas","getAllScaleValues","curr","updateMinAndPrev","parseValue","startValue","endValue","barStart","barEnd","_custom","parseFloatBar","parseArrayOrPrimitive","isFloatBar","custom","setBorderSkipped","borderSkipped","borderProps","enableBorderRadius","parseEdge","orig","v2","startEnd","setInflateAmount","inflateAmount","DoughnutController","animateRotate","animateScale","cutout","circumference","legend","generateLabels","fontColor","legendItem","innerRadius","outerRadius","getter","_getRotation","_getCircumference","_getRotationExtents","arcs","getMaxBorderWidth","getMaxOffset","maxSize","chartWeight","_getRingWeight","ratioX","ratioY","startX","startY","endX","endY","calcMax","calcMin","maxX","maxY","minX","minY","getRatioAndOffset","maxRadius","radiusLength","_getVisibleDatasetWeightTotal","calculateTotal","_getRingWeightOffset","_circumference","calculateCircumference","animationOpts","centerX","centerY","metaData","borderAlign","hoverBorderWidth","hoverOffset","ringWeightOffset","PolarAreaController","angleLines","circular","pointLabels","bind","_updateRadius","cutoutPercentage","xCenter","yCenter","datasetStartAngle","getIndexAngle","defaultAngle","countVisibleElements","_computeAngle","getDistanceFromCenterForValue","categoryPercentage","barPercentage","grouped","_index_","_value_","bars","ruler","_getRuler","vpixels","head","_calculateBarValuePixels","ipixels","_calculateBarIndexPixels","_getStacks","currentParsed","iScaleValue","skipNull","find","_getStackCount","_getAxisCount","_getAxis","getFirstScaleIdForIndexAxis","indexScaleId","firstScaleAxisId","_getStackIndex","pixels","barThickness","stackCount","baseValue","minBarLength","actualBase","floating","barSign","halfGrid","maxBarThickness","Infinity","axisCount","percent","chunk","computeFlexCategoryTraits","thickness","computeFitCategoryTraits","axisNumber","stackIndex","rects","_decimated","animated","maxGapLength","directUpdate","pointsCount","prevParsed","nullData","lastPoint","updateControlPoints","pointPosition","getPointPositionForValue","parseBorderRadius","angleDelta","borderRadius","halfThickness","innerLimit","computeOuterLimit","outerArcLimit","outerStart","outerEnd","innerStart","innerEnd","rThetaToXY","theta","pathArc","pixelMargin","innerR","spacingOffset","avNogSpacingRadius","angleOffset","outerStartAdjustedRadius","outerEndAdjustedRadius","outerStartAdjustedAngle","outerEndAdjustedAngle","innerStartAdjustedRadius","innerEndAdjustedRadius","innerStartAdjustedAngle","innerEndAdjustedAngle","outerMidAdjustedAngle","pCenter","p4","innerMidAdjustedAngle","p8","outerStartX","outerStartY","outerEndX","outerEndY","fullCircles","inner","lineJoin","angleMargin","clipArc","selfJoin","outerAngleClip","innerAngleClip","clipWidth","clipSelf","setStyle","lineCap","pathVars","paramsStart","paramsEnd","segmentStart","segmentEnd","outside","pathSegment","lineMethod","stepped","getLineMethod","fastPathSegment","prevX","lastY","avgX","countX","pointIndex","drawX","truncX","_getSegmentMethod","usePath2D","Path2D","path","_path","strokePathWithCache","segmentMethod","strokePathDirect","LineElement","_points","_segments","_pointsUpdated","_interpolate","_getInterpolationMethod","interpolated","hitRadius","getBarBounds","bar","half","skipOrLimit","boundingRects","maxW","maxH","parseBorderWidth","maxR","enableBorder","outer","skipX","skipY","addNormalRectPath","inflateRect","amount","refRect","chartX","chartY","rAdjust","nonZeroBetween","betweenAngles","withinRadius","halfAngle","halfRadius","radiusOffset","drawArc","addRectPath","mouseX","mouseY","inXRange","inYRange","hoverRadius","findOrAddLabel","addedLabels","unshift","addIfString","lastIndexOf","_getLabelForValue","relativeLabelSize","minSpacing","LinearScaleBase","_startValue","_endValue","_valueRange","handleTickRangeOptions","setMin","setMax","minSign","maxSign","getTickLimit","maxTicks","stepSize","computeTickLimit","generationOptions","dataRange","precision","maxDigits","includeBounds","unit","maxSpaces","rmin","rmax","countDefined","niceMin","niceMax","numSpaces","decimalPlaces","generateTicks","LinearScale","log10Floor","changeExponent","isMajor","tickVal","steps","rangeExp","rangeStep","minExp","exp","startExp","lastTick","LogarithmicScale","_zero","getTickBackdropHeight","determineLimits","fitWithPointLabels","_padding","limits","valueCount","_pointLabels","pointLabelOpts","additionalAngle","centerPointLabels","getPointLabelContext","getPointPosition","drawingArea","plFont","textSize","updateLimits","setCenterPoint","_pointLabelItems","itemOpts","extra","createPointLabelItem","isNotOverlapped","buildPointLabelItems","hLimits","vLimits","outerDistance","pointLabelPosition","yForAngle","getTextAlignForAngle","leftForTextAlign","drawPointLabelBox","backdropLeft","backdropTop","backdropWidth","backdropHeight","pathRadiusLine","labelCount","RadialLinearScale","animate","leftMovement","rightMovement","topMovement","bottomMovement","scalingFactor","getValueForDistanceFromCenter","scaledDistance","pointLabel","createPointLabelContext","distanceFromCenter","getBasePosition","getPointLabelPosition","drawPointLabels","gridLineOpts","drawRadiusLine","INTERVALS","millisecond","common","second","minute","hour","day","week","month","quarter","year","UNITS","sorter","adapter","_adapter","parser","isoWeekday","_parseOpts","determineUnitForAutoTicks","minUnit","capacity","interval","MAX_SAFE_INTEGER","addTick","time","timestamps","ticksFromTimestamps","majorUnit","setMajorTicks","TimeScale","adapters","displayFormats","_unit","_majorUnit","_offsets","_normalized","normalized","_applyBounds","_getLabelBounds","getLabelTimestamps","timeOpts","_generate","_getLabelCapacity","determineUnitForFormatting","determineMajorUnit","initOffsets","offsetAfterAutoskip","getDecimalForValue","weekday","hasWeekday","getDataTimestamps","tooltipFormat","datetime","fmt","_tickFormatFunction","minorFormat","majorFormat","offsets","_getLabelSize","ticksOpts","tickLabelWidth","cosRotation","sinRotation","tickFontSize","exampleTime","exampleLabel","prevSource","nextSource","prevTarget","nextTarget","span","_addedLabels","added","_table","_minPos","_tableRange","_getTimestampsForTable","buildLookupTable","BORDER_COLORS","BACKGROUND_COLORS","getBorderColor","getBackgroundColor","getColorizer","colorizeDoughnutDataset","colorizePolarAreaDataset","colorizeDefaultDataset","containsColorsDefinitions","plugin_colors","forceOverride","_args","chartOptions","containsColorDefenition","colorizer","cleanDecimatedDataset","cleanDecimatedData","plugin_decimation","algorithm","beforeElementsUpdate","xAxis","getStartAndCountOfVisiblePointsSimplified","threshold","decimated","samples","bucketWidth","sampledIndex","endIndex","maxAreaPoint","maxArea","nextA","avgY","avgRangeStart","avgRangeEnd","avgRangeLength","rangeOffs","rangeTo","pointAx","pointAy","lttbDecimation","minIndex","maxIndex","startIndex","xMin","dx","lastIndex","intermediateIndex1","intermediateIndex2","minMaxDecimation","_getBounds","_findSegmentEnd","_getEdge","_createBoundaryLine","boundary","linePoints","_pointsFromSegments","_shouldApplyFill","_resolveTarget","propagate","visited","_decodeFill","fillOption","parseFillOption","firstCh","decodeTargetIndex","addPointsBelow","sourcePoint","linesBelow","postponed","findPoint","pointValue","firstValue","lastValue","simpleArc","getLineByIndex","sourcePoints","below","getLinesBelow","_buildStackLine","_getTargetValue","computeCircularBoundary","_getTargetPixel","computeLinearBoundary","computeBoundary","_drawfill","lineOpts","above","fillColor","clipVertical","clipHorizontal","doFill","clipY","lineLoop","clipX","tpoints","targetSegments","tgt","subBounds","fillSources","fillSource","src","notShape","clipBounds","interpolatedLineTo","targetLoop","interpolatedPoint","afterDatasetsUpdate","$filler","beforeDraw","drawTime","beforeDatasetsDraw","beforeDatasetDraw","getBoxSize","labelOpts","boxHeight","boxWidth","usePointStyle","pointStyleWidth","itemHeight","Legend","_added","legendHitBoxes","_hoveredItem","doughnutMode","legendItems","columnSizes","lineWidths","buildLabels","labelFont","_computeTitleHeight","_fitRows","_fitCols","hitboxes","totalHeight","row","_itemHeight","heightLimit","totalWidth","currentColWidth","currentColHeight","col","legendItemText","calculateItemWidth","fontLineHeight","calculateLegendItemHeight","calculateItemHeight","calculateItemSize","adjustHitBoxes","rtlHelper","hitbox","_draw","defaultColor","halfFontSize","cursor","textDirection","lineDash","drawOptions","SQRT2","yBoxTop","xBoxLeft","drawLegendBox","titleFont","titlePadding","topPaddingPlusHalfFontSize","_getLegendItemAt","hitBox","lh","handleEvent","onLeave","isListened","hoveredItem","sameItem","plugin_legend","_element","afterEvent","ci","useBorderRadius","Title","_drawArgs","fontOpts","plugin_title","titleBlock","createTitle","WeakMap","plugin_subtitle","positioners","average","xSet","eventPosition","nearestElement","tp","pushOrConcat","toPush","splitNewlines","String","createTooltipItem","formattedValue","getTooltipSize","tooltip","body","footer","bodyFont","footerFont","titleLineCount","footerLineCount","bodyLineItemCount","combinedBodyLength","bodyItem","before","after","beforeBody","afterBody","titleSpacing","titleMarginBottom","displayColors","bodySpacing","footerMarginTop","footerSpacing","widthPadding","maxLineWidth","determineXAlign","yAlign","chartWidth","xAlign","caret","caretSize","caretPadding","doesNotFitWithAlign","determineAlignment","determineYAlign","getBackgroundPoint","alignment","paddingAndSize","alignX","alignY","getAlignedX","getBeforeAfterBodyLines","overrideCallbacks","defaultCallbacks","beforeTitle","tooltipItems","afterTitle","beforeLabel","tooltipItem","labelColor","labelTextColor","bodyColor","labelPointStyle","afterLabel","beforeFooter","afterFooter","invokeCallbackWithFallback","Tooltip","opacity","_eventPosition","_size","_cachedAnimations","_tooltipItems","dataPoints","caretX","caretY","labelColors","labelPointStyles","labelTextColors","getTitle","getBeforeBody","getBody","bodyItems","scoped","getAfterBody","getFooter","_createItems","itemSort","positionAndSize","backgroundPoint","external","drawCaret","tooltipPoint","caretPosition","getCaretPosition","x3","y3","ptX","ptY","titleColor","_drawColorBox","colorX","rtlColorX","yOffSet","colorY","multiKeyBackground","outerX","innerX","strokeRect","drawBody","bodyAlign","bodyLineHeight","xLinePadding","fillLineOfText","bodyAlignForCalculation","textColor","drawFooter","footerAlign","footerColor","tooltipSize","quadraticCurveTo","_updateAnimationTarget","animX","animY","_willRender","hasTooltipContent","globalAlpha","positionChanged","_positionChanged","_ignoreReplayEvents","plugin_tooltip","afterInit","afterDraw","helpers","platforms"],"mappings":";;;;;;0bAUO,SAASA,IAEf,CAKM,MAAMC,EAAO,MAClB,IAAIC,EAAK,EACT,MAAO,IAAMA,GACf,EAHoB,GAUb,SAASC,EAAcC,GAC5B,OAAOA,OACT,CAOO,SAASC,EAAqBD,GACnC,GAAIE,MAAMD,SAAWC,MAAMD,QAAQD,GACjC,OAAO,EAET,MAAMG,EAAOC,OAAOC,UAAUC,SAASC,KAAKP,GAC5C,MAAyB,YAArBG,EAAKK,MAAM,EAAG,IAAuC,WAAnBL,EAAKK,OAAO,EAIpD,CAOO,SAASC,EAAST,GACvB,OAAiB,OAAVA,GAA4D,oBA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+N,IAASA,EAAKwsD,SAASx7E,KACxCk2E,SAAU,CAACj1D,EAAK+N,IAASA,EAAKwsD,SAASx7E,KACvCihF,mBAAoB,OACpB5E,eAAe,EACfr4C,WAAY,EACZ7jB,YAAa,gBACb0N,YAAa,EACb5N,UAAW,CACThV,SAAU,IACVoY,OAAQ,gBAEVM,WAAY,CACVlG,QAAS,CACP5iB,KAAM,SACN0oB,WAAY,CAAC,IAAK,IAAK,QAAS,SAAU,SAAU,WAEtDq7D,QAAS,CACPv7D,OAAQ,SACRpY,SAAU,MAGdF,UAAW8yE,IAGbt4B,cAAe,CACbi2B,SAAU,OACVC,WAAY,OACZzC,UAAW,QAGbv5D,YAAa,CACXwD,YAAcX,GAAkB,WAATA,GAA8B,aAATA,GAAgC,aAATA,EACnEa,YAAY,EACZpY,UAAW,CACTkY,aAAa,EACbE,YAAY,GAEdlD,UAAW,CACTmD,WAAW,GAEbO,WAAY,CACVP,UAAW,cAKf0nC,uBAAwB,CAAC,uBCzyC3B0B,GAAMrH,SAASa,GAAahkC,GAAQvB,GAAUoB,GAE9C2qC,GAAMq2B,QAAU,IAAIA,IACpBr2B,GAAM0G,UAAYA,GAClB1G,GAAMlhB,UAAYA,GAClBkhB,GAAMjgB,WAAaA,GACnBigB,GAAMz/C,SAAWA,GACjBy/C,GAAMxG,YAAcqB,GAASrB,YAAYn/C,MACzC2lD,GAAM7c,kBAAoBA,GAC1B6c,GAAM1U,QAAUA,GAChB0U,GAAM/rC,SAAWA,GACjB+rC,GAAMpqB,YAAcA,GACpBoqB,GAAM3pB,QAAUA,GAChB2pB,GAAMs2B,UAAYA,GAClBt2B,GAAMzR,MAAQA,GACdyR,GAAMjtC,MAAQA,GAGdzkB,OAAOoP,OAAOsiD,GAAOxG,GAAahkC,GAAQvB,GAAUoB,EAASihE,IAC7Dt2B,GAAMA,MAAQA,GAEQ,oBAAXtlD,SACTA,OAAOslD,MAAQA","x_google_ignoreList":[5]} \ No newline at end of file diff --git a/frontend/node_modules/chart.js/dist/chart.umd.min.js b/frontend/node_modules/chart.js/dist/chart.umd.min.js new file mode 100644 index 0000000000000000000000000000000000000000..7eec4e6d9a40ba3548c11c5a8d576f7195bc0c5f --- /dev/null +++ b/frontend/node_modules/chart.js/dist/chart.umd.min.js @@ -0,0 +1,14 @@ +/*! + * Chart.js v4.5.0 + * https://www.chartjs.org + * (c) 2025 Chart.js Contributors + * Released under the MIT License + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Chart=e()}(this,(function(){"use strict";var t=Object.freeze({__proto__:null,get Colors(){return Jo},get Decimation(){return ta},get Filler(){return ba},get Legend(){return Ma},get SubTitle(){return Pa},get Title(){return ka},get Tooltip(){return Na}});function e(){}const i=(()=>{let t=0;return()=>t++})();function s(t){return null==t}function n(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return"[object"===e.slice(0,7)&&"Array]"===e.slice(-6)}function o(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)}function a(t){return("number"==typeof t||t instanceof Number)&&isFinite(+t)}function r(t,e){return a(t)?t:e}function l(t,e){return void 0===t?e:t}const h=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100:+t/e,c=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100*e:+t;function d(t,e,i){if(t&&"function"==typeof t.call)return t.apply(i,e)}function u(t,e,i,s){let a,r,l;if(n(t))if(r=t.length,s)for(a=r-1;a>=0;a--)e.call(i,t[a],a);else for(a=0;at,x:t=>t.x,y:t=>t.y};function v(t){const e=t.split("."),i=[];let s="";for(const t of e)s+=t,s.endsWith("\\")?s=s.slice(0,-1)+".":(i.push(s),s="");return i}function M(t,e){const i=y[e]||(y[e]=function(t){const e=v(t);return t=>{for(const i of e){if(""===i)break;t=t&&t[i]}return t}}(e));return i(t)}function w(t){return t.charAt(0).toUpperCase()+t.slice(1)}const k=t=>void 0!==t,S=t=>"function"==typeof t,P=(t,e)=>{if(t.size!==e.size)return!1;for(const i of t)if(!e.has(i))return!1;return!0};function D(t){return"mouseup"===t.type||"click"===t.type||"contextmenu"===t.type}const C=Math.PI,O=2*C,A=O+C,T=Number.POSITIVE_INFINITY,L=C/180,E=C/2,R=C/4,I=2*C/3,z=Math.log10,F=Math.sign;function V(t,e,i){return Math.abs(t-e)t-e)).pop(),e}function N(t){return!function(t){return"symbol"==typeof t||"object"==typeof t&&null!==t&&!(Symbol.toPrimitive in t||"toString"in t||"valueOf"in t)}(t)&&!isNaN(parseFloat(t))&&isFinite(t)}function H(t,e){const i=Math.round(t);return i-e<=t&&i+e>=t}function j(t,e,i){let s,n,o;for(s=0,n=t.length;sl&&h=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function et(t,e,i){i=i||(i=>t[i]1;)s=o+n>>1,i(s)?o=s:n=s;return{lo:o,hi:n}}const it=(t,e,i,s)=>et(t,i,s?s=>{const n=t[s][e];return nt[s][e]et(t,i,(s=>t[s][e]>=i));function nt(t,e,i){let s=0,n=t.length;for(;ss&&t[n-1]>i;)n--;return s>0||n{const i="_onData"+w(e),s=t[e];Object.defineProperty(t,e,{configurable:!0,enumerable:!1,value(...e){const n=s.apply(this,e);return t._chartjs.listeners.forEach((t=>{"function"==typeof t[i]&&t[i](...e)})),n}})})))}function rt(t,e){const i=t._chartjs;if(!i)return;const s=i.listeners,n=s.indexOf(e);-1!==n&&s.splice(n,1),s.length>0||(ot.forEach((e=>{delete t[e]})),delete t._chartjs)}function lt(t){const e=new Set(t);return e.size===t.length?t:Array.from(e)}const ht="undefined"==typeof window?function(t){return t()}:window.requestAnimationFrame;function ct(t,e){let i=[],s=!1;return function(...n){i=n,s||(s=!0,ht.call(window,(()=>{s=!1,t.apply(e,i)})))}}function dt(t,e){let i;return function(...s){return e?(clearTimeout(i),i=setTimeout(t,e,s)):t.apply(this,s),e}}const ut=t=>"start"===t?"left":"end"===t?"right":"center",ft=(t,e,i)=>"start"===t?e:"end"===t?i:(e+i)/2,gt=(t,e,i,s)=>t===(s?"left":"right")?i:"center"===t?(e+i)/2:e;function pt(t,e,i){const n=e.length;let o=0,a=n;if(t._sorted){const{iScale:r,vScale:l,_parsed:h}=t,c=t.dataset&&t.dataset.options?t.dataset.options.spanGaps:null,d=r.axis,{min:u,max:f,minDefined:g,maxDefined:p}=r.getUserBounds();if(g){if(o=Math.min(it(h,d,u).lo,i?n:it(e,d,r.getPixelForValue(u)).lo),c){const t=h.slice(0,o+1).reverse().findIndex((t=>!s(t[l.axis])));o-=Math.max(0,t)}o=Z(o,0,n-1)}if(p){let t=Math.max(it(h,r.axis,f,!0).hi+1,i?0:it(e,d,r.getPixelForValue(f),!0).hi+1);if(c){const e=h.slice(t-1).findIndex((t=>!s(t[l.axis])));t+=Math.max(0,e)}a=Z(t,o,n)-o}else a=n-o}return{start:o,count:a}}function mt(t){const{xScale:e,yScale:i,_scaleRanges:s}=t,n={xmin:e.min,xmax:e.max,ymin:i.min,ymax:i.max};if(!s)return t._scaleRanges=n,!0;const o=s.xmin!==e.min||s.xmax!==e.max||s.ymin!==i.min||s.ymax!==i.max;return Object.assign(s,n),o}class xt{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(t,e,i,s){const n=e.listeners[s],o=e.duration;n.forEach((s=>s({chart:t,initial:e.initial,numSteps:o,currentStep:Math.min(i-e.start,o)})))}_refresh(){this._request||(this._running=!0,this._request=ht.call(window,(()=>{this._update(),this._request=null,this._running&&this._refresh()})))}_update(t=Date.now()){let e=0;this._charts.forEach(((i,s)=>{if(!i.running||!i.items.length)return;const n=i.items;let o,a=n.length-1,r=!1;for(;a>=0;--a)o=n[a],o._active?(o._total>i.duration&&(i.duration=o._total),o.tick(t),r=!0):(n[a]=n[n.length-1],n.pop());r&&(s.draw(),this._notify(s,i,t,"progress")),n.length||(i.running=!1,this._notify(s,i,t,"complete"),i.initial=!1),e+=n.length})),this._lastDate=t,0===e&&(this._running=!1)}_getAnims(t){const e=this._charts;let i=e.get(t);return i||(i={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},e.set(t,i)),i}listen(t,e,i){this._getAnims(t).listeners[e].push(i)}add(t,e){e&&e.length&&this._getAnims(t).items.push(...e)}has(t){return this._getAnims(t).items.length>0}start(t){const e=this._charts.get(t);e&&(e.running=!0,e.start=Date.now(),e.duration=e.items.reduce(((t,e)=>Math.max(t,e._duration)),0),this._refresh())}running(t){if(!this._running)return!1;const e=this._charts.get(t);return!!(e&&e.running&&e.items.length)}stop(t){const e=this._charts.get(t);if(!e||!e.items.length)return;const i=e.items;let s=i.length-1;for(;s>=0;--s)i[s].cancel();e.items=[],this._notify(t,e,Date.now(),"complete")}remove(t){return this._charts.delete(t)}}var bt=new xt; +/*! + * @kurkle/color v0.3.2 + * https://github.com/kurkle/color#readme + * (c) 2023 Jukka Kurkela + * Released under the MIT License + */function _t(t){return t+.5|0}const yt=(t,e,i)=>Math.max(Math.min(t,i),e);function vt(t){return yt(_t(2.55*t),0,255)}function Mt(t){return yt(_t(255*t),0,255)}function wt(t){return yt(_t(t/2.55)/100,0,1)}function kt(t){return yt(_t(100*t),0,100)}const St={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},Pt=[..."0123456789ABCDEF"],Dt=t=>Pt[15&t],Ct=t=>Pt[(240&t)>>4]+Pt[15&t],Ot=t=>(240&t)>>4==(15&t);function At(t){var e=(t=>Ot(t.r)&&Ot(t.g)&&Ot(t.b)&&Ot(t.a))(t)?Dt:Ct;return t?"#"+e(t.r)+e(t.g)+e(t.b)+((t,e)=>t<255?e(t):"")(t.a,e):void 0}const Tt=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function Lt(t,e,i){const s=e*Math.min(i,1-i),n=(e,n=(e+t/30)%12)=>i-s*Math.max(Math.min(n-3,9-n,1),-1);return[n(0),n(8),n(4)]}function Et(t,e,i){const s=(s,n=(s+t/60)%6)=>i-i*e*Math.max(Math.min(n,4-n,1),0);return[s(5),s(3),s(1)]}function Rt(t,e,i){const s=Lt(t,1,.5);let n;for(e+i>1&&(n=1/(e+i),e*=n,i*=n),n=0;n<3;n++)s[n]*=1-e-i,s[n]+=e;return s}function It(t){const e=t.r/255,i=t.g/255,s=t.b/255,n=Math.max(e,i,s),o=Math.min(e,i,s),a=(n+o)/2;let r,l,h;return n!==o&&(h=n-o,l=a>.5?h/(2-n-o):h/(n+o),r=function(t,e,i,s,n){return t===n?(e-i)/s+(e>16&255,o>>8&255,255&o]}return t}(),Ht.transparent=[0,0,0,0]);const e=Ht[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:4===e.length?e[3]:255}}const $t=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;const Yt=t=>t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,Ut=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function Xt(t,e,i){if(t){let s=It(t);s[e]=Math.max(0,Math.min(s[e]+s[e]*i,0===e?360:1)),s=Ft(s),t.r=s[0],t.g=s[1],t.b=s[2]}}function qt(t,e){return t?Object.assign(e||{},t):t}function Kt(t){var e={r:0,g:0,b:0,a:255};return Array.isArray(t)?t.length>=3&&(e={r:t[0],g:t[1],b:t[2],a:255},t.length>3&&(e.a=Mt(t[3]))):(e=qt(t,{r:0,g:0,b:0,a:1})).a=Mt(e.a),e}function Gt(t){return"r"===t.charAt(0)?function(t){const e=$t.exec(t);let i,s,n,o=255;if(e){if(e[7]!==i){const t=+e[7];o=e[8]?vt(t):yt(255*t,0,255)}return i=+e[1],s=+e[3],n=+e[5],i=255&(e[2]?vt(i):yt(i,0,255)),s=255&(e[4]?vt(s):yt(s,0,255)),n=255&(e[6]?vt(n):yt(n,0,255)),{r:i,g:s,b:n,a:o}}}(t):Bt(t)}class Jt{constructor(t){if(t instanceof Jt)return t;const e=typeof t;let i;var s,n,o;"object"===e?i=Kt(t):"string"===e&&(o=(s=t).length,"#"===s[0]&&(4===o||5===o?n={r:255&17*St[s[1]],g:255&17*St[s[2]],b:255&17*St[s[3]],a:5===o?17*St[s[4]]:255}:7!==o&&9!==o||(n={r:St[s[1]]<<4|St[s[2]],g:St[s[3]]<<4|St[s[4]],b:St[s[5]]<<4|St[s[6]],a:9===o?St[s[7]]<<4|St[s[8]]:255})),i=n||jt(t)||Gt(t)),this._rgb=i,this._valid=!!i}get valid(){return this._valid}get rgb(){var t=qt(this._rgb);return t&&(t.a=wt(t.a)),t}set rgb(t){this._rgb=Kt(t)}rgbString(){return this._valid?(t=this._rgb)&&(t.a<255?`rgba(${t.r}, ${t.g}, ${t.b}, ${wt(t.a)})`:`rgb(${t.r}, ${t.g}, ${t.b})`):void 0;var t}hexString(){return this._valid?At(this._rgb):void 0}hslString(){return this._valid?function(t){if(!t)return;const e=It(t),i=e[0],s=kt(e[1]),n=kt(e[2]);return t.a<255?`hsla(${i}, ${s}%, ${n}%, ${wt(t.a)})`:`hsl(${i}, ${s}%, ${n}%)`}(this._rgb):void 0}mix(t,e){if(t){const i=this.rgb,s=t.rgb;let n;const o=e===n?.5:e,a=2*o-1,r=i.a-s.a,l=((a*r==-1?a:(a+r)/(1+a*r))+1)/2;n=1-l,i.r=255&l*i.r+n*s.r+.5,i.g=255&l*i.g+n*s.g+.5,i.b=255&l*i.b+n*s.b+.5,i.a=o*i.a+(1-o)*s.a,this.rgb=i}return this}interpolate(t,e){return t&&(this._rgb=function(t,e,i){const s=Ut(wt(t.r)),n=Ut(wt(t.g)),o=Ut(wt(t.b));return{r:Mt(Yt(s+i*(Ut(wt(e.r))-s))),g:Mt(Yt(n+i*(Ut(wt(e.g))-n))),b:Mt(Yt(o+i*(Ut(wt(e.b))-o))),a:t.a+i*(e.a-t.a)}}(this._rgb,t._rgb,e)),this}clone(){return new Jt(this.rgb)}alpha(t){return this._rgb.a=Mt(t),this}clearer(t){return this._rgb.a*=1-t,this}greyscale(){const t=this._rgb,e=_t(.3*t.r+.59*t.g+.11*t.b);return t.r=t.g=t.b=e,this}opaquer(t){return this._rgb.a*=1+t,this}negate(){const t=this._rgb;return t.r=255-t.r,t.g=255-t.g,t.b=255-t.b,this}lighten(t){return Xt(this._rgb,2,t),this}darken(t){return Xt(this._rgb,2,-t),this}saturate(t){return Xt(this._rgb,1,t),this}desaturate(t){return Xt(this._rgb,1,-t),this}rotate(t){return function(t,e){var i=It(t);i[0]=Vt(i[0]+e),i=Ft(i),t.r=i[0],t.g=i[1],t.b=i[2]}(this._rgb,t),this}}function Zt(t){if(t&&"object"==typeof t){const e=t.toString();return"[object CanvasPattern]"===e||"[object CanvasGradient]"===e}return!1}function Qt(t){return Zt(t)?t:new Jt(t)}function te(t){return Zt(t)?t:new Jt(t).saturate(.5).darken(.1).hexString()}const ee=["x","y","borderWidth","radius","tension"],ie=["color","borderColor","backgroundColor"];const se=new Map;function ne(t,e,i){return function(t,e){e=e||{};const i=t+JSON.stringify(e);let s=se.get(i);return s||(s=new Intl.NumberFormat(t,e),se.set(i,s)),s}(e,i).format(t)}const oe={values:t=>n(t)?t:""+t,numeric(t,e,i){if(0===t)return"0";const s=this.chart.options.locale;let n,o=t;if(i.length>1){const e=Math.max(Math.abs(i[0].value),Math.abs(i[i.length-1].value));(e<1e-4||e>1e15)&&(n="scientific"),o=function(t,e){let i=e.length>3?e[2].value-e[1].value:e[1].value-e[0].value;Math.abs(i)>=1&&t!==Math.floor(t)&&(i=t-Math.floor(t));return i}(t,i)}const a=z(Math.abs(o)),r=isNaN(a)?1:Math.max(Math.min(-1*Math.floor(a),20),0),l={notation:n,minimumFractionDigits:r,maximumFractionDigits:r};return Object.assign(l,this.options.ticks.format),ne(t,s,l)},logarithmic(t,e,i){if(0===t)return"0";const s=i[e].significand||t/Math.pow(10,Math.floor(z(t)));return[1,2,3,5,10,15].includes(s)||e>.8*i.length?oe.numeric.call(this,t,e,i):""}};var ae={formatters:oe};const re=Object.create(null),le=Object.create(null);function he(t,e){if(!e)return t;const i=e.split(".");for(let e=0,s=i.length;et.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(t,e)=>te(e.backgroundColor),this.hoverBorderColor=(t,e)=>te(e.borderColor),this.hoverColor=(t,e)=>te(e.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(t),this.apply(e)}set(t,e){return ce(this,t,e)}get(t){return he(this,t)}describe(t,e){return ce(le,t,e)}override(t,e){return ce(re,t,e)}route(t,e,i,s){const n=he(this,t),a=he(this,i),r="_"+e;Object.defineProperties(n,{[r]:{value:n[e],writable:!0},[e]:{enumerable:!0,get(){const t=this[r],e=a[s];return o(t)?Object.assign({},e,t):l(t,e)},set(t){this[r]=t}}})}apply(t){t.forEach((t=>t(this)))}}var ue=new de({_scriptable:t=>!t.startsWith("on"),_indexable:t=>"events"!==t,hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[function(t){t.set("animation",{delay:void 0,duration:1e3,easing:"easeOutQuart",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),t.describe("animation",{_fallback:!1,_indexable:!1,_scriptable:t=>"onProgress"!==t&&"onComplete"!==t&&"fn"!==t}),t.set("animations",{colors:{type:"color",properties:ie},numbers:{type:"number",properties:ee}}),t.describe("animations",{_fallback:"animation"}),t.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:t=>0|t}}}})},function(t){t.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})},function(t){t.set("scale",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:"ticks",clip:!0,grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(t,e)=>e.lineWidth,tickColor:(t,e)=>e.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:ae.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),t.route("scale.ticks","color","","color"),t.route("scale.grid","color","","borderColor"),t.route("scale.border","color","","borderColor"),t.route("scale.title","color","","color"),t.describe("scale",{_fallback:!1,_scriptable:t=>!t.startsWith("before")&&!t.startsWith("after")&&"callback"!==t&&"parser"!==t,_indexable:t=>"borderDash"!==t&&"tickBorderDash"!==t&&"dash"!==t}),t.describe("scales",{_fallback:"scale"}),t.describe("scale.ticks",{_scriptable:t=>"backdropPadding"!==t&&"callback"!==t,_indexable:t=>"backdropPadding"!==t})}]);function fe(){return"undefined"!=typeof window&&"undefined"!=typeof document}function ge(t){let e=t.parentNode;return e&&"[object ShadowRoot]"===e.toString()&&(e=e.host),e}function pe(t,e,i){let s;return"string"==typeof t?(s=parseInt(t,10),-1!==t.indexOf("%")&&(s=s/100*e.parentNode[i])):s=t,s}const me=t=>t.ownerDocument.defaultView.getComputedStyle(t,null);function xe(t,e){return me(t).getPropertyValue(e)}const be=["top","right","bottom","left"];function _e(t,e,i){const s={};i=i?"-"+i:"";for(let n=0;n<4;n++){const o=be[n];s[o]=parseFloat(t[e+"-"+o+i])||0}return s.width=s.left+s.right,s.height=s.top+s.bottom,s}const ye=(t,e,i)=>(t>0||e>0)&&(!i||!i.shadowRoot);function ve(t,e){if("native"in t)return t;const{canvas:i,currentDevicePixelRatio:s}=e,n=me(i),o="border-box"===n.boxSizing,a=_e(n,"padding"),r=_e(n,"border","width"),{x:l,y:h,box:c}=function(t,e){const i=t.touches,s=i&&i.length?i[0]:t,{offsetX:n,offsetY:o}=s;let a,r,l=!1;if(ye(n,o,t.target))a=n,r=o;else{const t=e.getBoundingClientRect();a=s.clientX-t.left,r=s.clientY-t.top,l=!0}return{x:a,y:r,box:l}}(t,i),d=a.left+(c&&r.left),u=a.top+(c&&r.top);let{width:f,height:g}=e;return o&&(f-=a.width+r.width,g-=a.height+r.height),{x:Math.round((l-d)/f*i.width/s),y:Math.round((h-u)/g*i.height/s)}}const Me=t=>Math.round(10*t)/10;function we(t,e,i,s){const n=me(t),o=_e(n,"margin"),a=pe(n.maxWidth,t,"clientWidth")||T,r=pe(n.maxHeight,t,"clientHeight")||T,l=function(t,e,i){let s,n;if(void 0===e||void 0===i){const o=t&&ge(t);if(o){const t=o.getBoundingClientRect(),a=me(o),r=_e(a,"border","width"),l=_e(a,"padding");e=t.width-l.width-r.width,i=t.height-l.height-r.height,s=pe(a.maxWidth,o,"clientWidth"),n=pe(a.maxHeight,o,"clientHeight")}else e=t.clientWidth,i=t.clientHeight}return{width:e,height:i,maxWidth:s||T,maxHeight:n||T}}(t,e,i);let{width:h,height:c}=l;if("content-box"===n.boxSizing){const t=_e(n,"border","width"),e=_e(n,"padding");h-=e.width+t.width,c-=e.height+t.height}h=Math.max(0,h-o.width),c=Math.max(0,s?h/s:c-o.height),h=Me(Math.min(h,a,l.maxWidth)),c=Me(Math.min(c,r,l.maxHeight)),h&&!c&&(c=Me(h/2));return(void 0!==e||void 0!==i)&&s&&l.height&&c>l.height&&(c=l.height,h=Me(Math.floor(c*s))),{width:h,height:c}}function ke(t,e,i){const s=e||1,n=Math.floor(t.height*s),o=Math.floor(t.width*s);t.height=Math.floor(t.height),t.width=Math.floor(t.width);const a=t.canvas;return a.style&&(i||!a.style.height&&!a.style.width)&&(a.style.height=`${t.height}px`,a.style.width=`${t.width}px`),(t.currentDevicePixelRatio!==s||a.height!==n||a.width!==o)&&(t.currentDevicePixelRatio=s,a.height=n,a.width=o,t.ctx.setTransform(s,0,0,s,0,0),!0)}const Se=function(){let t=!1;try{const e={get passive(){return t=!0,!1}};fe()&&(window.addEventListener("test",null,e),window.removeEventListener("test",null,e))}catch(t){}return t}();function Pe(t,e){const i=xe(t,e),s=i&&i.match(/^(\d+)(\.\d+)?px$/);return s?+s[1]:void 0}function De(t){return!t||s(t.size)||s(t.family)?null:(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family}function Ce(t,e,i,s,n){let o=e[n];return o||(o=e[n]=t.measureText(n).width,i.push(n)),o>s&&(s=o),s}function Oe(t,e,i,s){let o=(s=s||{}).data=s.data||{},a=s.garbageCollect=s.garbageCollect||[];s.font!==e&&(o=s.data={},a=s.garbageCollect=[],s.font=e),t.save(),t.font=e;let r=0;const l=i.length;let h,c,d,u,f;for(h=0;hi.length){for(h=0;h0&&t.stroke()}}function Re(t,e,i){return i=i||.5,!e||t&&t.x>e.left-i&&t.xe.top-i&&t.y0&&""!==r.strokeColor;let c,d;for(t.save(),t.font=a.string,function(t,e){e.translation&&t.translate(e.translation[0],e.translation[1]),s(e.rotation)||t.rotate(e.rotation),e.color&&(t.fillStyle=e.color),e.textAlign&&(t.textAlign=e.textAlign),e.textBaseline&&(t.textBaseline=e.textBaseline)}(t,r),c=0;ct[0])){const o=i||t;void 0===s&&(s=ti("_fallback",t));const a={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:t,_rootScopes:o,_fallback:s,_getTarget:n,override:i=>je([i,...t],e,o,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete e._keys,delete t[0][i],!0),get:(i,s)=>qe(i,s,(()=>function(t,e,i,s){let n;for(const o of e)if(n=ti(Ue(o,t),i),void 0!==n)return Xe(t,n)?Ze(i,s,t,n):n}(s,e,t,i))),getOwnPropertyDescriptor:(t,e)=>Reflect.getOwnPropertyDescriptor(t._scopes[0],e),getPrototypeOf:()=>Reflect.getPrototypeOf(t[0]),has:(t,e)=>ei(t).includes(e),ownKeys:t=>ei(t),set(t,e,i){const s=t._storage||(t._storage=n());return t[e]=s[e]=i,delete t._keys,!0}})}function $e(t,e,i,s){const a={_cacheable:!1,_proxy:t,_context:e,_subProxy:i,_stack:new Set,_descriptors:Ye(t,s),setContext:e=>$e(t,e,i,s),override:n=>$e(t.override(n),e,i,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete t[i],!0),get:(t,e,i)=>qe(t,e,(()=>function(t,e,i){const{_proxy:s,_context:a,_subProxy:r,_descriptors:l}=t;let h=s[e];S(h)&&l.isScriptable(e)&&(h=function(t,e,i,s){const{_proxy:n,_context:o,_subProxy:a,_stack:r}=i;if(r.has(t))throw new Error("Recursion detected: "+Array.from(r).join("->")+"->"+t);r.add(t);let l=e(o,a||s);r.delete(t),Xe(t,l)&&(l=Ze(n._scopes,n,t,l));return l}(e,h,t,i));n(h)&&h.length&&(h=function(t,e,i,s){const{_proxy:n,_context:a,_subProxy:r,_descriptors:l}=i;if(void 0!==a.index&&s(t))return e[a.index%e.length];if(o(e[0])){const i=e,s=n._scopes.filter((t=>t!==i));e=[];for(const o of i){const i=Ze(s,n,t,o);e.push($e(i,a,r&&r[t],l))}}return e}(e,h,t,l.isIndexable));Xe(e,h)&&(h=$e(h,a,r&&r[e],l));return h}(t,e,i))),getOwnPropertyDescriptor:(e,i)=>e._descriptors.allKeys?Reflect.has(t,i)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(t,i),getPrototypeOf:()=>Reflect.getPrototypeOf(t),has:(e,i)=>Reflect.has(t,i),ownKeys:()=>Reflect.ownKeys(t),set:(e,i,s)=>(t[i]=s,delete e[i],!0)})}function Ye(t,e={scriptable:!0,indexable:!0}){const{_scriptable:i=e.scriptable,_indexable:s=e.indexable,_allKeys:n=e.allKeys}=t;return{allKeys:n,scriptable:i,indexable:s,isScriptable:S(i)?i:()=>i,isIndexable:S(s)?s:()=>s}}const Ue=(t,e)=>t?t+w(e):e,Xe=(t,e)=>o(e)&&"adapters"!==t&&(null===Object.getPrototypeOf(e)||e.constructor===Object);function qe(t,e,i){if(Object.prototype.hasOwnProperty.call(t,e)||"constructor"===e)return t[e];const s=i();return t[e]=s,s}function Ke(t,e,i){return S(t)?t(e,i):t}const Ge=(t,e)=>!0===t?e:"string"==typeof t?M(e,t):void 0;function Je(t,e,i,s,n){for(const o of e){const e=Ge(i,o);if(e){t.add(e);const o=Ke(e._fallback,i,n);if(void 0!==o&&o!==i&&o!==s)return o}else if(!1===e&&void 0!==s&&i!==s)return null}return!1}function Ze(t,e,i,s){const a=e._rootScopes,r=Ke(e._fallback,i,s),l=[...t,...a],h=new Set;h.add(s);let c=Qe(h,l,i,r||i,s);return null!==c&&((void 0===r||r===i||(c=Qe(h,l,r,c,s),null!==c))&&je(Array.from(h),[""],a,r,(()=>function(t,e,i){const s=t._getTarget();e in s||(s[e]={});const a=s[e];if(n(a)&&o(i))return i;return a||{}}(e,i,s))))}function Qe(t,e,i,s,n){for(;i;)i=Je(t,e,i,s,n);return i}function ti(t,e){for(const i of e){if(!i)continue;const e=i[t];if(void 0!==e)return e}}function ei(t){let e=t._keys;return e||(e=t._keys=function(t){const e=new Set;for(const i of t)for(const t of Object.keys(i).filter((t=>!t.startsWith("_"))))e.add(t);return Array.from(e)}(t._scopes)),e}function ii(t,e,i,s){const{iScale:n}=t,{key:o="r"}=this._parsing,a=new Array(s);let r,l,h,c;for(r=0,l=s;re"x"===t?"y":"x";function ai(t,e,i,s){const n=t.skip?e:t,o=e,a=i.skip?e:i,r=q(o,n),l=q(a,o);let h=r/(r+l),c=l/(r+l);h=isNaN(h)?0:h,c=isNaN(c)?0:c;const d=s*h,u=s*c;return{previous:{x:o.x-d*(a.x-n.x),y:o.y-d*(a.y-n.y)},next:{x:o.x+u*(a.x-n.x),y:o.y+u*(a.y-n.y)}}}function ri(t,e="x"){const i=oi(e),s=t.length,n=Array(s).fill(0),o=Array(s);let a,r,l,h=ni(t,0);for(a=0;a!t.skip))),"monotone"===e.cubicInterpolationMode)ri(t,n);else{let i=s?t[t.length-1]:t[0];for(o=0,a=t.length;o0===t||1===t,di=(t,e,i)=>-Math.pow(2,10*(t-=1))*Math.sin((t-e)*O/i),ui=(t,e,i)=>Math.pow(2,-10*t)*Math.sin((t-e)*O/i)+1,fi={linear:t=>t,easeInQuad:t=>t*t,easeOutQuad:t=>-t*(t-2),easeInOutQuad:t=>(t/=.5)<1?.5*t*t:-.5*(--t*(t-2)-1),easeInCubic:t=>t*t*t,easeOutCubic:t=>(t-=1)*t*t+1,easeInOutCubic:t=>(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2),easeInQuart:t=>t*t*t*t,easeOutQuart:t=>-((t-=1)*t*t*t-1),easeInOutQuart:t=>(t/=.5)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2),easeInQuint:t=>t*t*t*t*t,easeOutQuint:t=>(t-=1)*t*t*t*t+1,easeInOutQuint:t=>(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2),easeInSine:t=>1-Math.cos(t*E),easeOutSine:t=>Math.sin(t*E),easeInOutSine:t=>-.5*(Math.cos(C*t)-1),easeInExpo:t=>0===t?0:Math.pow(2,10*(t-1)),easeOutExpo:t=>1===t?1:1-Math.pow(2,-10*t),easeInOutExpo:t=>ci(t)?t:t<.5?.5*Math.pow(2,10*(2*t-1)):.5*(2-Math.pow(2,-10*(2*t-1))),easeInCirc:t=>t>=1?t:-(Math.sqrt(1-t*t)-1),easeOutCirc:t=>Math.sqrt(1-(t-=1)*t),easeInOutCirc:t=>(t/=.5)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1),easeInElastic:t=>ci(t)?t:di(t,.075,.3),easeOutElastic:t=>ci(t)?t:ui(t,.075,.3),easeInOutElastic(t){const e=.1125;return ci(t)?t:t<.5?.5*di(2*t,e,.45):.5+.5*ui(2*t-1,e,.45)},easeInBack(t){const e=1.70158;return t*t*((e+1)*t-e)},easeOutBack(t){const e=1.70158;return(t-=1)*t*((e+1)*t+e)+1},easeInOutBack(t){let e=1.70158;return(t/=.5)<1?t*t*((1+(e*=1.525))*t-e)*.5:.5*((t-=2)*t*((1+(e*=1.525))*t+e)+2)},easeInBounce:t=>1-fi.easeOutBounce(1-t),easeOutBounce(t){const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375},easeInOutBounce:t=>t<.5?.5*fi.easeInBounce(2*t):.5*fi.easeOutBounce(2*t-1)+.5};function gi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:t.y+i*(e.y-t.y)}}function pi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:"middle"===s?i<.5?t.y:e.y:"after"===s?i<1?t.y:e.y:i>0?e.y:t.y}}function mi(t,e,i,s){const n={x:t.cp2x,y:t.cp2y},o={x:e.cp1x,y:e.cp1y},a=gi(t,n,i),r=gi(n,o,i),l=gi(o,e,i),h=gi(a,r,i),c=gi(r,l,i);return gi(h,c,i)}const xi=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,bi=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;function _i(t,e){const i=(""+t).match(xi);if(!i||"normal"===i[1])return 1.2*e;switch(t=+i[2],i[3]){case"px":return t;case"%":t/=100}return e*t}const yi=t=>+t||0;function vi(t,e){const i={},s=o(e),n=s?Object.keys(e):e,a=o(t)?s?i=>l(t[i],t[e[i]]):e=>t[e]:()=>t;for(const t of n)i[t]=yi(a(t));return i}function Mi(t){return vi(t,{top:"y",right:"x",bottom:"y",left:"x"})}function wi(t){return vi(t,["topLeft","topRight","bottomLeft","bottomRight"])}function ki(t){const e=Mi(t);return e.width=e.left+e.right,e.height=e.top+e.bottom,e}function Si(t,e){t=t||{},e=e||ue.font;let i=l(t.size,e.size);"string"==typeof i&&(i=parseInt(i,10));let s=l(t.style,e.style);s&&!(""+s).match(bi)&&(console.warn('Invalid font style specified: "'+s+'"'),s=void 0);const n={family:l(t.family,e.family),lineHeight:_i(l(t.lineHeight,e.lineHeight),i),size:i,style:s,weight:l(t.weight,e.weight),string:""};return n.string=De(n),n}function Pi(t,e,i,s){let o,a,r,l=!0;for(o=0,a=t.length;oi&&0===t?0:t+e;return{min:a(s,-Math.abs(o)),max:a(n,o)}}function Ci(t,e){return Object.assign(Object.create(t),e)}function Oi(t,e,i){return t?function(t,e){return{x:i=>t+t+e-i,setWidth(t){e=t},textAlign:t=>"center"===t?t:"right"===t?"left":"right",xPlus:(t,e)=>t-e,leftForLtr:(t,e)=>t-e}}(e,i):{x:t=>t,setWidth(t){},textAlign:t=>t,xPlus:(t,e)=>t+e,leftForLtr:(t,e)=>t}}function Ai(t,e){let i,s;"ltr"!==e&&"rtl"!==e||(i=t.canvas.style,s=[i.getPropertyValue("direction"),i.getPropertyPriority("direction")],i.setProperty("direction",e,"important"),t.prevTextDirection=s)}function Ti(t,e){void 0!==e&&(delete t.prevTextDirection,t.canvas.style.setProperty("direction",e[0],e[1]))}function Li(t){return"angle"===t?{between:J,compare:K,normalize:G}:{between:tt,compare:(t,e)=>t-e,normalize:t=>t}}function Ei({start:t,end:e,count:i,loop:s,style:n}){return{start:t%i,end:e%i,loop:s&&(e-t+1)%i==0,style:n}}function Ri(t,e,i){if(!i)return[t];const{property:s,start:n,end:o}=i,a=e.length,{compare:r,between:l,normalize:h}=Li(s),{start:c,end:d,loop:u,style:f}=function(t,e,i){const{property:s,start:n,end:o}=i,{between:a,normalize:r}=Li(s),l=e.length;let h,c,{start:d,end:u,loop:f}=t;if(f){for(d+=l,u+=l,h=0,c=l;hb||l(n,x,p)&&0!==r(n,x),v=()=>!b||0===r(o,p)||l(o,x,p);for(let t=c,i=c;t<=d;++t)m=e[t%a],m.skip||(p=h(m[s]),p!==x&&(b=l(p,n,o),null===_&&y()&&(_=0===r(p,n)?t:i),null!==_&&v()&&(g.push(Ei({start:_,end:t,loop:u,count:a,style:f})),_=null),i=t,x=p));return null!==_&&g.push(Ei({start:_,end:d,loop:u,count:a,style:f})),g}function Ii(t,e){const i=[],s=t.segments;for(let n=0;nn&&t[o%e].skip;)o--;return o%=e,{start:n,end:o}}(i,n,o,s);if(!0===s)return Fi(t,[{start:a,end:r,loop:o}],i,e);return Fi(t,function(t,e,i,s){const n=t.length,o=[];let a,r=e,l=t[e];for(a=e+1;a<=i;++a){const i=t[a%n];i.skip||i.stop?l.skip||(s=!1,o.push({start:e%n,end:(a-1)%n,loop:s}),e=r=i.stop?a:null):(r=a,l.skip&&(e=a)),l=i}return null!==r&&o.push({start:e%n,end:r%n,loop:s}),o}(i,a,r!s(t[e.axis])));n.lo-=Math.max(0,a);const r=i.slice(n.hi).findIndex((t=>!s(t[e.axis])));n.hi+=Math.max(0,r)}return n}if(o._sharedOptions){const t=a[0],s="function"==typeof t.getRange&&t.getRange(e);if(s){const t=r(a,e,i-s),n=r(a,e,i+s);return{lo:t.lo,hi:n.hi}}}}return{lo:0,hi:a.length-1}}function $i(t,e,i,s,n){const o=t.getSortedVisibleDatasetMetas(),a=i[e];for(let t=0,i=o.length;t{t[a]&&t[a](e[i],n)&&(o.push({element:t,datasetIndex:s,index:l}),r=r||t.inRange(e.x,e.y,n))})),s&&!r?[]:o}var Ki={evaluateInteractionItems:$i,modes:{index(t,e,i,s){const n=ve(e,t),o=i.axis||"x",a=i.includeInvisible||!1,r=i.intersect?Yi(t,n,o,s,a):Xi(t,n,o,!1,s,a),l=[];return r.length?(t.getSortedVisibleDatasetMetas().forEach((t=>{const e=r[0].index,i=t.data[e];i&&!i.skip&&l.push({element:i,datasetIndex:t.index,index:e})})),l):[]},dataset(t,e,i,s){const n=ve(e,t),o=i.axis||"xy",a=i.includeInvisible||!1;let r=i.intersect?Yi(t,n,o,s,a):Xi(t,n,o,!1,s,a);if(r.length>0){const e=r[0].datasetIndex,i=t.getDatasetMeta(e).data;r=[];for(let t=0;tYi(t,ve(e,t),i.axis||"xy",s,i.includeInvisible||!1),nearest(t,e,i,s){const n=ve(e,t),o=i.axis||"xy",a=i.includeInvisible||!1;return Xi(t,n,o,i.intersect,s,a)},x:(t,e,i,s)=>qi(t,ve(e,t),"x",i.intersect,s),y:(t,e,i,s)=>qi(t,ve(e,t),"y",i.intersect,s)}};const Gi=["left","top","right","bottom"];function Ji(t,e){return t.filter((t=>t.pos===e))}function Zi(t,e){return t.filter((t=>-1===Gi.indexOf(t.pos)&&t.box.axis===e))}function Qi(t,e){return t.sort(((t,i)=>{const s=e?i:t,n=e?t:i;return s.weight===n.weight?s.index-n.index:s.weight-n.weight}))}function ts(t,e){const i=function(t){const e={};for(const i of t){const{stack:t,pos:s,stackWeight:n}=i;if(!t||!Gi.includes(s))continue;const o=e[t]||(e[t]={count:0,placed:0,weight:0,size:0});o.count++,o.weight+=n}return e}(t),{vBoxMaxWidth:s,hBoxMaxHeight:n}=e;let o,a,r;for(o=0,a=t.length;o{s[t]=Math.max(e[t],i[t])})),s}return s(t?["left","right"]:["top","bottom"])}function os(t,e,i,s){const n=[];let o,a,r,l,h,c;for(o=0,a=t.length,h=0;ot.box.fullSize)),!0),s=Qi(Ji(e,"left"),!0),n=Qi(Ji(e,"right")),o=Qi(Ji(e,"top"),!0),a=Qi(Ji(e,"bottom")),r=Zi(e,"x"),l=Zi(e,"y");return{fullSize:i,leftAndTop:s.concat(o),rightAndBottom:n.concat(l).concat(a).concat(r),chartArea:Ji(e,"chartArea"),vertical:s.concat(n).concat(l),horizontal:o.concat(a).concat(r)}}(t.boxes),l=r.vertical,h=r.horizontal;u(t.boxes,(t=>{"function"==typeof t.beforeLayout&&t.beforeLayout()}));const c=l.reduce(((t,e)=>e.box.options&&!1===e.box.options.display?t:t+1),0)||1,d=Object.freeze({outerWidth:e,outerHeight:i,padding:n,availableWidth:o,availableHeight:a,vBoxMaxWidth:o/2/c,hBoxMaxHeight:a/2}),f=Object.assign({},n);is(f,ki(s));const g=Object.assign({maxPadding:f,w:o,h:a,x:n.left,y:n.top},n),p=ts(l.concat(h),d);os(r.fullSize,g,d,p),os(l,g,d,p),os(h,g,d,p)&&os(l,g,d,p),function(t){const e=t.maxPadding;function i(i){const s=Math.max(e[i]-t[i],0);return t[i]+=s,s}t.y+=i("top"),t.x+=i("left"),i("right"),i("bottom")}(g),rs(r.leftAndTop,g,d,p),g.x+=g.w,g.y+=g.h,rs(r.rightAndBottom,g,d,p),t.chartArea={left:g.left,top:g.top,right:g.left+g.w,bottom:g.top+g.h,height:g.h,width:g.w},u(r.chartArea,(e=>{const i=e.box;Object.assign(i,t.chartArea),i.update(g.w,g.h,{left:0,top:0,right:0,bottom:0})}))}};class hs{acquireContext(t,e){}releaseContext(t){return!1}addEventListener(t,e,i){}removeEventListener(t,e,i){}getDevicePixelRatio(){return 1}getMaximumSize(t,e,i,s){return e=Math.max(0,e||t.width),i=i||t.height,{width:e,height:Math.max(0,s?Math.floor(e/s):i)}}isAttached(t){return!0}updateConfig(t){}}class cs extends hs{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}}const ds="$chartjs",us={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},fs=t=>null===t||""===t;const gs=!!Se&&{passive:!0};function ps(t,e,i){t&&t.canvas&&t.canvas.removeEventListener(e,i,gs)}function ms(t,e){for(const i of t)if(i===e||i.contains(e))return!0}function xs(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||ms(i.addedNodes,s),e=e&&!ms(i.removedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}function bs(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||ms(i.removedNodes,s),e=e&&!ms(i.addedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}const _s=new Map;let ys=0;function vs(){const t=window.devicePixelRatio;t!==ys&&(ys=t,_s.forEach(((e,i)=>{i.currentDevicePixelRatio!==t&&e()})))}function Ms(t,e,i){const s=t.canvas,n=s&&ge(s);if(!n)return;const o=ct(((t,e)=>{const s=n.clientWidth;i(t,e),s{const e=t[0],i=e.contentRect.width,s=e.contentRect.height;0===i&&0===s||o(i,s)}));return a.observe(n),function(t,e){_s.size||window.addEventListener("resize",vs),_s.set(t,e)}(t,o),a}function ws(t,e,i){i&&i.disconnect(),"resize"===e&&function(t){_s.delete(t),_s.size||window.removeEventListener("resize",vs)}(t)}function ks(t,e,i){const s=t.canvas,n=ct((e=>{null!==t.ctx&&i(function(t,e){const i=us[t.type]||t.type,{x:s,y:n}=ve(t,e);return{type:i,chart:e,native:t,x:void 0!==s?s:null,y:void 0!==n?n:null}}(e,t))}),t);return function(t,e,i){t&&t.addEventListener(e,i,gs)}(s,e,n),n}class Ss extends hs{acquireContext(t,e){const i=t&&t.getContext&&t.getContext("2d");return i&&i.canvas===t?(function(t,e){const i=t.style,s=t.getAttribute("height"),n=t.getAttribute("width");if(t[ds]={initial:{height:s,width:n,style:{display:i.display,height:i.height,width:i.width}}},i.display=i.display||"block",i.boxSizing=i.boxSizing||"border-box",fs(n)){const e=Pe(t,"width");void 0!==e&&(t.width=e)}if(fs(s))if(""===t.style.height)t.height=t.width/(e||2);else{const e=Pe(t,"height");void 0!==e&&(t.height=e)}}(t,e),i):null}releaseContext(t){const e=t.canvas;if(!e[ds])return!1;const i=e[ds].initial;["height","width"].forEach((t=>{const n=i[t];s(n)?e.removeAttribute(t):e.setAttribute(t,n)}));const n=i.style||{};return Object.keys(n).forEach((t=>{e.style[t]=n[t]})),e.width=e.width,delete e[ds],!0}addEventListener(t,e,i){this.removeEventListener(t,e);const s=t.$proxies||(t.$proxies={}),n={attach:xs,detach:bs,resize:Ms}[e]||ks;s[e]=n(t,e,i)}removeEventListener(t,e){const i=t.$proxies||(t.$proxies={}),s=i[e];if(!s)return;({attach:ws,detach:ws,resize:ws}[e]||ps)(t,e,s),i[e]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,i,s){return we(t,e,i,s)}isAttached(t){const e=t&&ge(t);return!(!e||!e.isConnected)}}function Ps(t){return!fe()||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas?cs:Ss}var Ds=Object.freeze({__proto__:null,BasePlatform:hs,BasicPlatform:cs,DomPlatform:Ss,_detectPlatform:Ps});const Cs="transparent",Os={boolean:(t,e,i)=>i>.5?e:t,color(t,e,i){const s=Qt(t||Cs),n=s.valid&&Qt(e||Cs);return n&&n.valid?n.mix(s,i).hexString():e},number:(t,e,i)=>t+(e-t)*i};class As{constructor(t,e,i,s){const n=e[i];s=Pi([t.to,s,n,t.from]);const o=Pi([t.from,n,s]);this._active=!0,this._fn=t.fn||Os[t.type||typeof o],this._easing=fi[t.easing]||fi.linear,this._start=Math.floor(Date.now()+(t.delay||0)),this._duration=this._total=Math.floor(t.duration),this._loop=!!t.loop,this._target=e,this._prop=i,this._from=o,this._to=s,this._promises=void 0}active(){return this._active}update(t,e,i){if(this._active){this._notify(!1);const s=this._target[this._prop],n=i-this._start,o=this._duration-n;this._start=i,this._duration=Math.floor(Math.max(o,t.duration)),this._total+=n,this._loop=!!t.loop,this._to=Pi([t.to,e,s,t.from]),this._from=Pi([t.from,s,e])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){const e=t-this._start,i=this._duration,s=this._prop,n=this._from,o=this._loop,a=this._to;let r;if(this._active=n!==a&&(o||e1?2-r:r,r=this._easing(Math.min(1,Math.max(0,r))),this._target[s]=this._fn(n,a,r))}wait(){const t=this._promises||(this._promises=[]);return new Promise(((e,i)=>{t.push({res:e,rej:i})}))}_notify(t){const e=t?"res":"rej",i=this._promises||[];for(let t=0;t{const a=t[s];if(!o(a))return;const r={};for(const t of e)r[t]=a[t];(n(a.properties)&&a.properties||[s]).forEach((t=>{t!==s&&i.has(t)||i.set(t,r)}))}))}_animateOptions(t,e){const i=e.options,s=function(t,e){if(!e)return;let i=t.options;if(!i)return void(t.options=e);i.$shared&&(t.options=i=Object.assign({},i,{$shared:!1,$animations:{}}));return i}(t,i);if(!s)return[];const n=this._createAnimations(s,i);return i.$shared&&function(t,e){const i=[],s=Object.keys(e);for(let e=0;e{t.options=i}),(()=>{})),n}_createAnimations(t,e){const i=this._properties,s=[],n=t.$animations||(t.$animations={}),o=Object.keys(e),a=Date.now();let r;for(r=o.length-1;r>=0;--r){const l=o[r];if("$"===l.charAt(0))continue;if("options"===l){s.push(...this._animateOptions(t,e));continue}const h=e[l];let c=n[l];const d=i.get(l);if(c){if(d&&c.active()){c.update(d,h,a);continue}c.cancel()}d&&d.duration?(n[l]=c=new As(d,t,l,h),s.push(c)):t[l]=h}return s}update(t,e){if(0===this._properties.size)return void Object.assign(t,e);const i=this._createAnimations(t,e);return i.length?(bt.add(this._chart,i),!0):void 0}}function Ls(t,e){const i=t&&t.options||{},s=i.reverse,n=void 0===i.min?e:0,o=void 0===i.max?e:0;return{start:s?o:n,end:s?n:o}}function Es(t,e){const i=[],s=t._getSortedDatasetMetas(e);let n,o;for(n=0,o=s.length;n0||!i&&e<0)return n.index}return null}function Vs(t,e){const{chart:i,_cachedMeta:s}=t,n=i._stacks||(i._stacks={}),{iScale:o,vScale:a,index:r}=s,l=o.axis,h=a.axis,c=function(t,e,i){return`${t.id}.${e.id}.${i.stack||i.type}`}(o,a,s),d=e.length;let u;for(let t=0;ti[t].axis===e)).shift()}function Ws(t,e){const i=t.controller.index,s=t.vScale&&t.vScale.axis;if(s){e=e||t._parsed;for(const t of e){const e=t._stacks;if(!e||void 0===e[s]||void 0===e[s][i])return;delete e[s][i],void 0!==e[s]._visualValues&&void 0!==e[s]._visualValues[i]&&delete e[s]._visualValues[i]}}}const Ns=t=>"reset"===t||"none"===t,Hs=(t,e)=>e?t:Object.assign({},t);class js{static defaults={};static datasetElementType=null;static dataElementType=null;constructor(t,e){this.chart=t,this._ctx=t.ctx,this.index=e,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const t=this._cachedMeta;this.configure(),this.linkScales(),t._stacked=Is(t.vScale,t),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(t){this.index!==t&&Ws(this._cachedMeta),this.index=t}linkScales(){const t=this.chart,e=this._cachedMeta,i=this.getDataset(),s=(t,e,i,s)=>"x"===t?e:"r"===t?s:i,n=e.xAxisID=l(i.xAxisID,Bs(t,"x")),o=e.yAxisID=l(i.yAxisID,Bs(t,"y")),a=e.rAxisID=l(i.rAxisID,Bs(t,"r")),r=e.indexAxis,h=e.iAxisID=s(r,n,o,a),c=e.vAxisID=s(r,o,n,a);e.xScale=this.getScaleForId(n),e.yScale=this.getScaleForId(o),e.rScale=this.getScaleForId(a),e.iScale=this.getScaleForId(h),e.vScale=this.getScaleForId(c)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(t){return this.chart.scales[t]}_getOtherScale(t){const e=this._cachedMeta;return t===e.iScale?e.vScale:e.iScale}reset(){this._update("reset")}_destroy(){const t=this._cachedMeta;this._data&&rt(this._data,this),t._stacked&&Ws(t)}_dataCheck(){const t=this.getDataset(),e=t.data||(t.data=[]),i=this._data;if(o(e)){const t=this._cachedMeta;this._data=function(t,e){const{iScale:i,vScale:s}=e,n="x"===i.axis?"x":"y",o="x"===s.axis?"x":"y",a=Object.keys(t),r=new Array(a.length);let l,h,c;for(l=0,h=a.length;l0&&i._parsed[t-1];if(!1===this._parsing)i._parsed=s,i._sorted=!0,d=s;else{d=n(s[t])?this.parseArrayData(i,s,t,e):o(s[t])?this.parseObjectData(i,s,t,e):this.parsePrimitiveData(i,s,t,e);const a=()=>null===c[l]||f&&c[l]t&&!e.hidden&&e._stacked&&{keys:Es(i,!0),values:null})(e,i,this.chart),h={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:c,max:d}=function(t){const{min:e,max:i,minDefined:s,maxDefined:n}=t.getUserBounds();return{min:s?e:Number.NEGATIVE_INFINITY,max:n?i:Number.POSITIVE_INFINITY}}(r);let u,f;function g(){f=s[u];const e=f[r.axis];return!a(f[t.axis])||c>e||d=0;--u)if(!g()){this.updateRangeFromParsed(h,t,f,l);break}return h}getAllParsedValues(t){const e=this._cachedMeta._parsed,i=[];let s,n,o;for(s=0,n=e.length;s=0&&tthis.getContext(i,s,e)),c);return f.$shared&&(f.$shared=r,n[o]=Object.freeze(Hs(f,r))),f}_resolveAnimations(t,e,i){const s=this.chart,n=this._cachedDataOpts,o=`animation-${e}`,a=n[o];if(a)return a;let r;if(!1!==s.options.animation){const s=this.chart.config,n=s.datasetAnimationScopeKeys(this._type,e),o=s.getOptionScopes(this.getDataset(),n);r=s.createResolver(o,this.getContext(t,i,e))}const l=new Ts(s,r&&r.animations);return r&&r._cacheable&&(n[o]=Object.freeze(l)),l}getSharedOptions(t){if(t.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},t))}includeOptions(t,e){return!e||Ns(t)||this.chart._animationsDisabled}_getSharedOptions(t,e){const i=this.resolveDataElementOptions(t,e),s=this._sharedOptions,n=this.getSharedOptions(i),o=this.includeOptions(e,n)||n!==s;return this.updateSharedOptions(n,e,i),{sharedOptions:n,includeOptions:o}}updateElement(t,e,i,s){Ns(s)?Object.assign(t,i):this._resolveAnimations(e,s).update(t,i)}updateSharedOptions(t,e,i){t&&!Ns(e)&&this._resolveAnimations(void 0,e).update(t,i)}_setStyle(t,e,i,s){t.active=s;const n=this.getStyle(e,s);this._resolveAnimations(e,i,s).update(t,{options:!s&&this.getSharedOptions(n)||n})}removeHoverStyle(t,e,i){this._setStyle(t,i,"active",!1)}setHoverStyle(t,e,i){this._setStyle(t,i,"active",!0)}_removeDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!1)}_setDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!0)}_resyncElements(t){const e=this._data,i=this._cachedMeta.data;for(const[t,e,i]of this._syncList)this[t](e,i);this._syncList=[];const s=i.length,n=e.length,o=Math.min(n,s);o&&this.parse(0,o),n>s?this._insertElements(s,n-s,t):n{for(t.length+=e,a=t.length-1;a>=o;a--)t[a]=t[a-e]};for(r(n),a=t;a{s[t]=i[t]&&i[t].active()?i[t]._to:this[t]})),s}}function Ys(t,e){const i=t.options.ticks,n=function(t){const e=t.options.offset,i=t._tickSize(),s=t._length/i+(e?0:1),n=t._maxLength/i;return Math.floor(Math.min(s,n))}(t),o=Math.min(i.maxTicksLimit||n,n),a=i.major.enabled?function(t){const e=[];let i,s;for(i=0,s=t.length;io)return function(t,e,i,s){let n,o=0,a=i[0];for(s=Math.ceil(s),n=0;nn)return e}return Math.max(n,1)}(a,e,o);if(r>0){let t,i;const n=r>1?Math.round((h-l)/(r-1)):null;for(Us(e,c,d,s(n)?0:l-n,l),t=0,i=r-1;t"top"===e||"left"===e?t[e]+i:t[e]-i,qs=(t,e)=>Math.min(e||t,t);function Ks(t,e){const i=[],s=t.length/e,n=t.length;let o=0;for(;oa+r)))return h}function Js(t){return t.drawTicks?t.tickLength:0}function Zs(t,e){if(!t.display)return 0;const i=Si(t.font,e),s=ki(t.padding);return(n(t.text)?t.text.length:1)*i.lineHeight+s.height}function Qs(t,e,i){let s=ut(t);return(i&&"right"!==e||!i&&"right"===e)&&(s=(t=>"left"===t?"right":"right"===t?"left":t)(s)),s}class tn extends $s{constructor(t){super(),this.id=t.id,this.type=t.type,this.options=void 0,this.ctx=t.ctx,this.chart=t.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(t){this.options=t.setContext(this.getContext()),this.axis=t.axis,this._userMin=this.parse(t.min),this._userMax=this.parse(t.max),this._suggestedMin=this.parse(t.suggestedMin),this._suggestedMax=this.parse(t.suggestedMax)}parse(t,e){return t}getUserBounds(){let{_userMin:t,_userMax:e,_suggestedMin:i,_suggestedMax:s}=this;return t=r(t,Number.POSITIVE_INFINITY),e=r(e,Number.NEGATIVE_INFINITY),i=r(i,Number.POSITIVE_INFINITY),s=r(s,Number.NEGATIVE_INFINITY),{min:r(t,i),max:r(e,s),minDefined:a(t),maxDefined:a(e)}}getMinMax(t){let e,{min:i,max:s,minDefined:n,maxDefined:o}=this.getUserBounds();if(n&&o)return{min:i,max:s};const a=this.getMatchingVisibleMetas();for(let r=0,l=a.length;rs?s:i,s=n&&i>s?i:s,{min:r(i,r(s,i)),max:r(s,r(i,s))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]}getLabelItems(t=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(t))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){d(this.options.beforeUpdate,[this])}update(t,e,i){const{beginAtZero:s,grace:n,ticks:o}=this.options,a=o.sampleSize;this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this._margins=i=Object.assign({left:0,right:0,top:0,bottom:0},i),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+i.left+i.right:this.height+i.top+i.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=Di(this,n,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const r=a=n||i<=1||!this.isHorizontal())return void(this.labelRotation=s);const h=this._getLabelSizes(),c=h.widest.width,d=h.highest.height,u=Z(this.chart.width-c,0,this.maxWidth);o=t.offset?this.maxWidth/i:u/(i-1),c+6>o&&(o=u/(i-(t.offset?.5:1)),a=this.maxHeight-Js(t.grid)-e.padding-Zs(t.title,this.chart.options.font),r=Math.sqrt(c*c+d*d),l=Y(Math.min(Math.asin(Z((h.highest.height+6)/o,-1,1)),Math.asin(Z(a/r,-1,1))-Math.asin(Z(d/r,-1,1)))),l=Math.max(s,Math.min(n,l))),this.labelRotation=l}afterCalculateLabelRotation(){d(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){d(this.options.beforeFit,[this])}fit(){const t={width:0,height:0},{chart:e,options:{ticks:i,title:s,grid:n}}=this,o=this._isVisible(),a=this.isHorizontal();if(o){const o=Zs(s,e.options.font);if(a?(t.width=this.maxWidth,t.height=Js(n)+o):(t.height=this.maxHeight,t.width=Js(n)+o),i.display&&this.ticks.length){const{first:e,last:s,widest:n,highest:o}=this._getLabelSizes(),r=2*i.padding,l=$(this.labelRotation),h=Math.cos(l),c=Math.sin(l);if(a){const e=i.mirror?0:c*n.width+h*o.height;t.height=Math.min(this.maxHeight,t.height+e+r)}else{const e=i.mirror?0:h*n.width+c*o.height;t.width=Math.min(this.maxWidth,t.width+e+r)}this._calculatePadding(e,s,c,h)}}this._handleMargins(),a?(this.width=this._length=e.width-this._margins.left-this._margins.right,this.height=t.height):(this.width=t.width,this.height=this._length=e.height-this._margins.top-this._margins.bottom)}_calculatePadding(t,e,i,s){const{ticks:{align:n,padding:o},position:a}=this.options,r=0!==this.labelRotation,l="top"!==a&&"x"===this.axis;if(this.isHorizontal()){const a=this.getPixelForTick(0)-this.left,h=this.right-this.getPixelForTick(this.ticks.length-1);let c=0,d=0;r?l?(c=s*t.width,d=i*e.height):(c=i*t.height,d=s*e.width):"start"===n?d=e.width:"end"===n?c=t.width:"inner"!==n&&(c=t.width/2,d=e.width/2),this.paddingLeft=Math.max((c-a+o)*this.width/(this.width-a),0),this.paddingRight=Math.max((d-h+o)*this.width/(this.width-h),0)}else{let i=e.height/2,s=t.height/2;"start"===n?(i=0,s=t.height):"end"===n&&(i=e.height,s=0),this.paddingTop=i+o,this.paddingBottom=s+o}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){d(this.options.afterFit,[this])}isHorizontal(){const{axis:t,position:e}=this.options;return"top"===e||"bottom"===e||"x"===t}isFullSize(){return this.options.fullSize}_convertTicksToLabels(t){let e,i;for(this.beforeTickToLabelConversion(),this.generateTickLabels(t),e=0,i=t.length;e{const i=t.gc,s=i.length/2;let n;if(s>e){for(n=0;n({width:r[t]||0,height:l[t]||0});return{first:P(0),last:P(e-1),widest:P(k),highest:P(S),widths:r,heights:l}}getLabelForValue(t){return t}getPixelForValue(t,e){return NaN}getValueForPixel(t){}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getPixelForDecimal(t){this._reversePixels&&(t=1-t);const e=this._startPixel+t*this._length;return Q(this._alignToPixels?Ae(this.chart,e,0):e)}getDecimalForPixel(t){const e=(t-this._startPixel)/this._length;return this._reversePixels?1-e:e}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:t,max:e}=this;return t<0&&e<0?e:t>0&&e>0?t:0}getContext(t){const e=this.ticks||[];if(t>=0&&ta*s?a/i:r/s:r*s0}_computeGridLineItems(t){const e=this.axis,i=this.chart,s=this.options,{grid:n,position:a,border:r}=s,h=n.offset,c=this.isHorizontal(),d=this.ticks.length+(h?1:0),u=Js(n),f=[],g=r.setContext(this.getContext()),p=g.display?g.width:0,m=p/2,x=function(t){return Ae(i,t,p)};let b,_,y,v,M,w,k,S,P,D,C,O;if("top"===a)b=x(this.bottom),w=this.bottom-u,S=b-m,D=x(t.top)+m,O=t.bottom;else if("bottom"===a)b=x(this.top),D=t.top,O=x(t.bottom)-m,w=b+m,S=this.top+u;else if("left"===a)b=x(this.right),M=this.right-u,k=b-m,P=x(t.left)+m,C=t.right;else if("right"===a)b=x(this.left),P=t.left,C=x(t.right)-m,M=b+m,k=this.left+u;else if("x"===e){if("center"===a)b=x((t.top+t.bottom)/2+.5);else if(o(a)){const t=Object.keys(a)[0],e=a[t];b=x(this.chart.scales[t].getPixelForValue(e))}D=t.top,O=t.bottom,w=b+m,S=w+u}else if("y"===e){if("center"===a)b=x((t.left+t.right)/2);else if(o(a)){const t=Object.keys(a)[0],e=a[t];b=x(this.chart.scales[t].getPixelForValue(e))}M=b-m,k=M-u,P=t.left,C=t.right}const A=l(s.ticks.maxTicksLimit,d),T=Math.max(1,Math.ceil(d/A));for(_=0;_0&&(o-=s/2)}d={left:o,top:n,width:s+e.width,height:i+e.height,color:t.backdropColor}}x.push({label:v,font:P,textOffset:O,options:{rotation:m,color:i,strokeColor:o,strokeWidth:h,textAlign:f,textBaseline:A,translation:[M,w],backdrop:d}})}return x}_getXAxisLabelAlignment(){const{position:t,ticks:e}=this.options;if(-$(this.labelRotation))return"top"===t?"left":"right";let i="center";return"start"===e.align?i="left":"end"===e.align?i="right":"inner"===e.align&&(i="inner"),i}_getYAxisLabelAlignment(t){const{position:e,ticks:{crossAlign:i,mirror:s,padding:n}}=this.options,o=t+n,a=this._getLabelSizes().widest.width;let r,l;return"left"===e?s?(l=this.right+n,"near"===i?r="left":"center"===i?(r="center",l+=a/2):(r="right",l+=a)):(l=this.right-o,"near"===i?r="right":"center"===i?(r="center",l-=a/2):(r="left",l=this.left)):"right"===e?s?(l=this.left+n,"near"===i?r="right":"center"===i?(r="center",l-=a/2):(r="left",l-=a)):(l=this.left+o,"near"===i?r="left":"center"===i?(r="center",l+=a/2):(r="right",l=this.right)):r="right",{textAlign:r,x:l}}_computeLabelArea(){if(this.options.ticks.mirror)return;const t=this.chart,e=this.options.position;return"left"===e||"right"===e?{top:0,left:this.left,bottom:t.height,right:this.right}:"top"===e||"bottom"===e?{top:this.top,left:0,bottom:this.bottom,right:t.width}:void 0}drawBackground(){const{ctx:t,options:{backgroundColor:e},left:i,top:s,width:n,height:o}=this;e&&(t.save(),t.fillStyle=e,t.fillRect(i,s,n,o),t.restore())}getLineWidthForValue(t){const e=this.options.grid;if(!this._isVisible()||!e.display)return 0;const i=this.ticks.findIndex((e=>e.value===t));if(i>=0){return e.setContext(this.getContext(i)).lineWidth}return 0}drawGrid(t){const e=this.options.grid,i=this.ctx,s=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t));let n,o;const a=(t,e,s)=>{s.width&&s.color&&(i.save(),i.lineWidth=s.width,i.strokeStyle=s.color,i.setLineDash(s.borderDash||[]),i.lineDashOffset=s.borderDashOffset,i.beginPath(),i.moveTo(t.x,t.y),i.lineTo(e.x,e.y),i.stroke(),i.restore())};if(e.display)for(n=0,o=s.length;n{this.drawBackground(),this.drawGrid(t),this.drawTitle()}},{z:s,draw:()=>{this.drawBorder()}},{z:e,draw:t=>{this.drawLabels(t)}}]:[{z:e,draw:t=>{this.draw(t)}}]}getMatchingVisibleMetas(t){const e=this.chart.getSortedVisibleDatasetMetas(),i=this.axis+"AxisID",s=[];let n,o;for(n=0,o=e.length;n{const s=i.split("."),n=s.pop(),o=[t].concat(s).join("."),a=e[i].split("."),r=a.pop(),l=a.join(".");ue.route(o,n,l,r)}))}(e,t.defaultRoutes);t.descriptors&&ue.describe(e,t.descriptors)}(t,o,i),this.override&&ue.override(t.id,t.overrides)),o}get(t){return this.items[t]}unregister(t){const e=this.items,i=t.id,s=this.scope;i in e&&delete e[i],s&&i in ue[s]&&(delete ue[s][i],this.override&&delete re[i])}}class sn{constructor(){this.controllers=new en(js,"datasets",!0),this.elements=new en($s,"elements"),this.plugins=new en(Object,"plugins"),this.scales=new en(tn,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...t){this._each("register",t)}remove(...t){this._each("unregister",t)}addControllers(...t){this._each("register",t,this.controllers)}addElements(...t){this._each("register",t,this.elements)}addPlugins(...t){this._each("register",t,this.plugins)}addScales(...t){this._each("register",t,this.scales)}getController(t){return this._get(t,this.controllers,"controller")}getElement(t){return this._get(t,this.elements,"element")}getPlugin(t){return this._get(t,this.plugins,"plugin")}getScale(t){return this._get(t,this.scales,"scale")}removeControllers(...t){this._each("unregister",t,this.controllers)}removeElements(...t){this._each("unregister",t,this.elements)}removePlugins(...t){this._each("unregister",t,this.plugins)}removeScales(...t){this._each("unregister",t,this.scales)}_each(t,e,i){[...e].forEach((e=>{const s=i||this._getRegistryForType(e);i||s.isForType(e)||s===this.plugins&&e.id?this._exec(t,s,e):u(e,(e=>{const s=i||this._getRegistryForType(e);this._exec(t,s,e)}))}))}_exec(t,e,i){const s=w(t);d(i["before"+s],[],i),e[t](i),d(i["after"+s],[],i)}_getRegistryForType(t){for(let e=0;et.filter((t=>!e.some((e=>t.plugin.id===e.plugin.id))));this._notify(s(e,i),t,"stop"),this._notify(s(i,e),t,"start")}}function an(t,e){return e||!1!==t?!0===t?{}:t:null}function rn(t,{plugin:e,local:i},s,n){const o=t.pluginScopeKeys(e),a=t.getOptionScopes(s,o);return i&&e.defaults&&a.push(e.defaults),t.createResolver(a,n,[""],{scriptable:!1,indexable:!1,allKeys:!0})}function ln(t,e){const i=ue.datasets[t]||{};return((e.datasets||{})[t]||{}).indexAxis||e.indexAxis||i.indexAxis||"x"}function hn(t){if("x"===t||"y"===t||"r"===t)return t}function cn(t,...e){if(hn(t))return t;for(const s of e){const e=s.axis||("top"===(i=s.position)||"bottom"===i?"x":"left"===i||"right"===i?"y":void 0)||t.length>1&&hn(t[0].toLowerCase());if(e)return e}var i;throw new Error(`Cannot determine type of '${t}' axis. Please provide 'axis' or 'position' option.`)}function dn(t,e,i){if(i[e+"AxisID"]===t)return{axis:e}}function un(t,e){const i=re[t.type]||{scales:{}},s=e.scales||{},n=ln(t.type,e),a=Object.create(null);return Object.keys(s).forEach((e=>{const r=s[e];if(!o(r))return console.error(`Invalid scale configuration for scale: ${e}`);if(r._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${e}`);const l=cn(e,r,function(t,e){if(e.data&&e.data.datasets){const i=e.data.datasets.filter((e=>e.xAxisID===t||e.yAxisID===t));if(i.length)return dn(t,"x",i[0])||dn(t,"y",i[0])}return{}}(e,t),ue.scales[r.type]),h=function(t,e){return t===e?"_index_":"_value_"}(l,n),c=i.scales||{};a[e]=b(Object.create(null),[{axis:l},r,c[l],c[h]])})),t.data.datasets.forEach((i=>{const n=i.type||t.type,o=i.indexAxis||ln(n,e),r=(re[n]||{}).scales||{};Object.keys(r).forEach((t=>{const e=function(t,e){let i=t;return"_index_"===t?i=e:"_value_"===t&&(i="x"===e?"y":"x"),i}(t,o),n=i[e+"AxisID"]||e;a[n]=a[n]||Object.create(null),b(a[n],[{axis:e},s[n],r[t]])}))})),Object.keys(a).forEach((t=>{const e=a[t];b(e,[ue.scales[e.type],ue.scale])})),a}function fn(t){const e=t.options||(t.options={});e.plugins=l(e.plugins,{}),e.scales=un(t,e)}function gn(t){return(t=t||{}).datasets=t.datasets||[],t.labels=t.labels||[],t}const pn=new Map,mn=new Set;function xn(t,e){let i=pn.get(t);return i||(i=e(),pn.set(t,i),mn.add(i)),i}const bn=(t,e,i)=>{const s=M(e,i);void 0!==s&&t.add(s)};class _n{constructor(t){this._config=function(t){return(t=t||{}).data=gn(t.data),fn(t),t}(t),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(t){this._config.type=t}get data(){return this._config.data}set data(t){this._config.data=gn(t)}get options(){return this._config.options}set options(t){this._config.options=t}get plugins(){return this._config.plugins}update(){const t=this._config;this.clearCache(),fn(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return xn(t,(()=>[[`datasets.${t}`,""]]))}datasetAnimationScopeKeys(t,e){return xn(`${t}.transition.${e}`,(()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,""]]))}datasetElementScopeKeys(t,e){return xn(`${t}-${e}`,(()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,""]]))}pluginScopeKeys(t){const e=t.id;return xn(`${this.type}-plugin-${e}`,(()=>[[`plugins.${e}`,...t.additionalOptionScopes||[]]]))}_cachedScopes(t,e){const i=this._scopeCache;let s=i.get(t);return s&&!e||(s=new Map,i.set(t,s)),s}getOptionScopes(t,e,i){const{options:s,type:n}=this,o=this._cachedScopes(t,i),a=o.get(e);if(a)return a;const r=new Set;e.forEach((e=>{t&&(r.add(t),e.forEach((e=>bn(r,t,e)))),e.forEach((t=>bn(r,s,t))),e.forEach((t=>bn(r,re[n]||{},t))),e.forEach((t=>bn(r,ue,t))),e.forEach((t=>bn(r,le,t)))}));const l=Array.from(r);return 0===l.length&&l.push(Object.create(null)),mn.has(e)&&o.set(e,l),l}chartOptionScopes(){const{options:t,type:e}=this;return[t,re[e]||{},ue.datasets[e]||{},{type:e},ue,le]}resolveNamedOptions(t,e,i,s=[""]){const o={$shared:!0},{resolver:a,subPrefixes:r}=yn(this._resolverCache,t,s);let l=a;if(function(t,e){const{isScriptable:i,isIndexable:s}=Ye(t);for(const o of e){const e=i(o),a=s(o),r=(a||e)&&t[o];if(e&&(S(r)||vn(r))||a&&n(r))return!0}return!1}(a,e)){o.$shared=!1;l=$e(a,i=S(i)?i():i,this.createResolver(t,i,r))}for(const t of e)o[t]=l[t];return o}createResolver(t,e,i=[""],s){const{resolver:n}=yn(this._resolverCache,t,i);return o(e)?$e(n,e,void 0,s):n}}function yn(t,e,i){let s=t.get(e);s||(s=new Map,t.set(e,s));const n=i.join();let o=s.get(n);if(!o){o={resolver:je(e,i),subPrefixes:i.filter((t=>!t.toLowerCase().includes("hover")))},s.set(n,o)}return o}const vn=t=>o(t)&&Object.getOwnPropertyNames(t).some((e=>S(t[e])));const Mn=["top","bottom","left","right","chartArea"];function wn(t,e){return"top"===t||"bottom"===t||-1===Mn.indexOf(t)&&"x"===e}function kn(t,e){return function(i,s){return i[t]===s[t]?i[e]-s[e]:i[t]-s[t]}}function Sn(t){const e=t.chart,i=e.options.animation;e.notifyPlugins("afterRender"),d(i&&i.onComplete,[t],e)}function Pn(t){const e=t.chart,i=e.options.animation;d(i&&i.onProgress,[t],e)}function Dn(t){return fe()&&"string"==typeof t?t=document.getElementById(t):t&&t.length&&(t=t[0]),t&&t.canvas&&(t=t.canvas),t}const Cn={},On=t=>{const e=Dn(t);return Object.values(Cn).filter((t=>t.canvas===e)).pop()};function An(t,e,i){const s=Object.keys(t);for(const n of s){const s=+n;if(s>=e){const o=t[n];delete t[n],(i>0||s>e)&&(t[s+i]=o)}}}class Tn{static defaults=ue;static instances=Cn;static overrides=re;static registry=nn;static version="4.5.0";static getChart=On;static register(...t){nn.add(...t),Ln()}static unregister(...t){nn.remove(...t),Ln()}constructor(t,e){const s=this.config=new _n(e),n=Dn(t),o=On(n);if(o)throw new Error("Canvas is already in use. Chart with ID '"+o.id+"' must be destroyed before the canvas with ID '"+o.canvas.id+"' can be reused.");const a=s.createResolver(s.chartOptionScopes(),this.getContext());this.platform=new(s.platform||Ps(n)),this.platform.updateConfig(s);const r=this.platform.acquireContext(n,a.aspectRatio),l=r&&r.canvas,h=l&&l.height,c=l&&l.width;this.id=i(),this.ctx=r,this.canvas=l,this.width=c,this.height=h,this._options=a,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new on,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=dt((t=>this.update(t)),a.resizeDelay||0),this._dataChanges=[],Cn[this.id]=this,r&&l?(bt.listen(this,"complete",Sn),bt.listen(this,"progress",Pn),this._initialize(),this.attached&&this.update()):console.error("Failed to create chart: can't acquire context from the given item")}get aspectRatio(){const{options:{aspectRatio:t,maintainAspectRatio:e},width:i,height:n,_aspectRatio:o}=this;return s(t)?e&&o?o:n?i/n:null:t}get data(){return this.config.data}set data(t){this.config.data=t}get options(){return this._options}set options(t){this.config.options=t}get registry(){return nn}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():ke(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return Te(this.canvas,this.ctx),this}stop(){return bt.stop(this),this}resize(t,e){bt.running(this)?this._resizeBeforeDraw={width:t,height:e}:this._resize(t,e)}_resize(t,e){const i=this.options,s=this.canvas,n=i.maintainAspectRatio&&this.aspectRatio,o=this.platform.getMaximumSize(s,t,e,n),a=i.devicePixelRatio||this.platform.getDevicePixelRatio(),r=this.width?"resize":"attach";this.width=o.width,this.height=o.height,this._aspectRatio=this.aspectRatio,ke(this,a,!0)&&(this.notifyPlugins("resize",{size:o}),d(i.onResize,[this,o],this),this.attached&&this._doResize(r)&&this.render())}ensureScalesHaveIDs(){u(this.options.scales||{},((t,e)=>{t.id=e}))}buildOrUpdateScales(){const t=this.options,e=t.scales,i=this.scales,s=Object.keys(i).reduce(((t,e)=>(t[e]=!1,t)),{});let n=[];e&&(n=n.concat(Object.keys(e).map((t=>{const i=e[t],s=cn(t,i),n="r"===s,o="x"===s;return{options:i,dposition:n?"chartArea":o?"bottom":"left",dtype:n?"radialLinear":o?"category":"linear"}})))),u(n,(e=>{const n=e.options,o=n.id,a=cn(o,n),r=l(n.type,e.dtype);void 0!==n.position&&wn(n.position,a)===wn(e.dposition)||(n.position=e.dposition),s[o]=!0;let h=null;if(o in i&&i[o].type===r)h=i[o];else{h=new(nn.getScale(r))({id:o,type:r,ctx:this.ctx,chart:this}),i[h.id]=h}h.init(n,t)})),u(s,((t,e)=>{t||delete i[e]})),u(i,(t=>{ls.configure(this,t,t.options),ls.addBox(this,t)}))}_updateMetasets(){const t=this._metasets,e=this.data.datasets.length,i=t.length;if(t.sort(((t,e)=>t.index-e.index)),i>e){for(let t=e;te.length&&delete this._stacks,t.forEach(((t,i)=>{0===e.filter((e=>e===t._dataset)).length&&this._destroyDatasetMeta(i)}))}buildOrUpdateControllers(){const t=[],e=this.data.datasets;let i,s;for(this._removeUnreferencedMetasets(),i=0,s=e.length;i{this.getDatasetMeta(e).controller.reset()}),this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(t){const e=this.config;e.update();const i=this._options=e.createResolver(e.chartOptionScopes(),this.getContext()),s=this._animationsDisabled=!i.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),!1===this.notifyPlugins("beforeUpdate",{mode:t,cancelable:!0}))return;const n=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let o=0;for(let t=0,e=this.data.datasets.length;t{t.reset()})),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(kn("z","_idx"));const{_active:a,_lastEvent:r}=this;r?this._eventHandler(r,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){u(this.scales,(t=>{ls.removeBox(this,t)})),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const t=this.options,e=new Set(Object.keys(this._listeners)),i=new Set(t.events);P(e,i)&&!!this._responsiveListeners===t.responsive||(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:t}=this,e=this._getUniformDataChanges()||[];for(const{method:i,start:s,count:n}of e){An(t,s,"_removeElements"===i?-n:n)}}_getUniformDataChanges(){const t=this._dataChanges;if(!t||!t.length)return;this._dataChanges=[];const e=this.data.datasets.length,i=e=>new Set(t.filter((t=>t[0]===e)).map(((t,e)=>e+","+t.splice(1).join(",")))),s=i(0);for(let t=1;tt.split(","))).map((t=>({method:t[1],start:+t[2],count:+t[3]})))}_updateLayout(t){if(!1===this.notifyPlugins("beforeLayout",{cancelable:!0}))return;ls.update(this,this.width,this.height,t);const e=this.chartArea,i=e.width<=0||e.height<=0;this._layers=[],u(this.boxes,(t=>{i&&"chartArea"===t.position||(t.configure&&t.configure(),this._layers.push(...t._layers()))}),this),this._layers.forEach(((t,e)=>{t._idx=e})),this.notifyPlugins("afterLayout")}_updateDatasets(t){if(!1!==this.notifyPlugins("beforeDatasetsUpdate",{mode:t,cancelable:!0})){for(let t=0,e=this.data.datasets.length;t=0;--e)this._drawDataset(t[e]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(t){const e=this.ctx,i={meta:t,index:t.index,cancelable:!0},s=Ni(this,t);!1!==this.notifyPlugins("beforeDatasetDraw",i)&&(s&&Ie(e,s),t.controller.draw(),s&&ze(e),i.cancelable=!1,this.notifyPlugins("afterDatasetDraw",i))}isPointInArea(t){return Re(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,e,i,s){const n=Ki.modes[e];return"function"==typeof n?n(this,t,i,s):[]}getDatasetMeta(t){const e=this.data.datasets[t],i=this._metasets;let s=i.filter((t=>t&&t._dataset===e)).pop();return s||(s={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:e&&e.order||0,index:t,_dataset:e,_parsed:[],_sorted:!1},i.push(s)),s}getContext(){return this.$context||(this.$context=Ci(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){const e=this.data.datasets[t];if(!e)return!1;const i=this.getDatasetMeta(t);return"boolean"==typeof i.hidden?!i.hidden:!e.hidden}setDatasetVisibility(t,e){this.getDatasetMeta(t).hidden=!e}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(t,e,i){const s=i?"show":"hide",n=this.getDatasetMeta(t),o=n.controller._resolveAnimations(void 0,s);k(e)?(n.data[e].hidden=!i,this.update()):(this.setDatasetVisibility(t,i),o.update(n,{visible:i}),this.update((e=>e.datasetIndex===t?s:void 0)))}hide(t,e){this._updateVisibility(t,e,!1)}show(t,e){this._updateVisibility(t,e,!0)}_destroyDatasetMeta(t){const e=this._metasets[t];e&&e.controller&&e.controller._destroy(),delete this._metasets[t]}_stop(){let t,e;for(this.stop(),bt.remove(this),t=0,e=this.data.datasets.length;t{e.addEventListener(this,i,s),t[i]=s},s=(t,e,i)=>{t.offsetX=e,t.offsetY=i,this._eventHandler(t)};u(this.options.events,(t=>i(t,s)))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const t=this._responsiveListeners,e=this.platform,i=(i,s)=>{e.addEventListener(this,i,s),t[i]=s},s=(i,s)=>{t[i]&&(e.removeEventListener(this,i,s),delete t[i])},n=(t,e)=>{this.canvas&&this.resize(t,e)};let o;const a=()=>{s("attach",a),this.attached=!0,this.resize(),i("resize",n),i("detach",o)};o=()=>{this.attached=!1,s("resize",n),this._stop(),this._resize(0,0),i("attach",a)},e.isAttached(this.canvas)?a():o()}unbindEvents(){u(this._listeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._listeners={},u(this._responsiveListeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._responsiveListeners=void 0}updateHoverStyle(t,e,i){const s=i?"set":"remove";let n,o,a,r;for("dataset"===e&&(n=this.getDatasetMeta(t[0].datasetIndex),n.controller["_"+s+"DatasetHoverStyle"]()),a=0,r=t.length;a{const i=this.getDatasetMeta(t);if(!i)throw new Error("No dataset found at index "+t);return{datasetIndex:t,element:i.data[e],index:e}}));!f(i,e)&&(this._active=i,this._lastEvent=null,this._updateHoverStyles(i,e))}notifyPlugins(t,e,i){return this._plugins.notify(this,t,e,i)}isPluginEnabled(t){return 1===this._plugins._cache.filter((e=>e.plugin.id===t)).length}_updateHoverStyles(t,e,i){const s=this.options.hover,n=(t,e)=>t.filter((t=>!e.some((e=>t.datasetIndex===e.datasetIndex&&t.index===e.index)))),o=n(e,t),a=i?t:n(t,e);o.length&&this.updateHoverStyle(o,s.mode,!1),a.length&&s.mode&&this.updateHoverStyle(a,s.mode,!0)}_eventHandler(t,e){const i={event:t,replay:e,cancelable:!0,inChartArea:this.isPointInArea(t)},s=e=>(e.options.events||this.options.events).includes(t.native.type);if(!1===this.notifyPlugins("beforeEvent",i,s))return;const n=this._handleEvent(t,e,i.inChartArea);return i.cancelable=!1,this.notifyPlugins("afterEvent",i,s),(n||i.changed)&&this.render(),this}_handleEvent(t,e,i){const{_active:s=[],options:n}=this,o=e,a=this._getActiveElements(t,s,i,o),r=D(t),l=function(t,e,i,s){return i&&"mouseout"!==t.type?s?e:t:null}(t,this._lastEvent,i,r);i&&(this._lastEvent=null,d(n.onHover,[t,a,this],this),r&&d(n.onClick,[t,a,this],this));const h=!f(a,s);return(h||e)&&(this._active=a,this._updateHoverStyles(a,s,e)),this._lastEvent=l,h}_getActiveElements(t,e,i,s){if("mouseout"===t.type)return[];if(!i)return e;const n=this.options.hover;return this.getElementsAtEventForMode(t,n.mode,n,s)}}function Ln(){return u(Tn.instances,(t=>t._plugins.invalidate()))}function En(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class Rn{static override(t){Object.assign(Rn.prototype,t)}options;constructor(t){this.options=t||{}}init(){}formats(){return En()}parse(){return En()}format(){return En()}add(){return En()}diff(){return En()}startOf(){return En()}endOf(){return En()}}var In={_date:Rn};function zn(t){const e=t.iScale,i=function(t,e){if(!t._cache.$bar){const i=t.getMatchingVisibleMetas(e);let s=[];for(let e=0,n=i.length;et-e)))}return t._cache.$bar}(e,t.type);let s,n,o,a,r=e._length;const l=()=>{32767!==o&&-32768!==o&&(k(a)&&(r=Math.min(r,Math.abs(o-a)||r)),a=o)};for(s=0,n=i.length;sMath.abs(r)&&(l=r,h=a),e[i.axis]=h,e._custom={barStart:l,barEnd:h,start:n,end:o,min:a,max:r}}(t,e,i,s):e[i.axis]=i.parse(t,s),e}function Vn(t,e,i,s){const n=t.iScale,o=t.vScale,a=n.getLabels(),r=n===o,l=[];let h,c,d,u;for(h=i,c=i+s;ht.x,i="left",s="right"):(e=t.base"spacing"!==t,_indexable:t=>"spacing"!==t&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const e=t.data;if(e.labels.length&&e.datasets.length){const{labels:{pointStyle:i,color:s}}=t.legend.options;return e.labels.map(((e,n)=>{const o=t.getDatasetMeta(0).controller.getStyle(n);return{text:e,fillStyle:o.backgroundColor,strokeStyle:o.borderColor,fontColor:s,lineWidth:o.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(n),index:n}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}}};constructor(t,e){super(t,e),this.enableOptionSharing=!0,this.innerRadius=void 0,this.outerRadius=void 0,this.offsetX=void 0,this.offsetY=void 0}linkScales(){}parse(t,e){const i=this.getDataset().data,s=this._cachedMeta;if(!1===this._parsing)s._parsed=i;else{let n,a,r=t=>+i[t];if(o(i[t])){const{key:t="value"}=this._parsing;r=e=>+M(i[e],t)}for(n=t,a=t+e;nJ(t,r,l,!0)?1:Math.max(e,e*i,s,s*i),g=(t,e,s)=>J(t,r,l,!0)?-1:Math.min(e,e*i,s,s*i),p=f(0,h,d),m=f(E,c,u),x=g(C,h,d),b=g(C+E,c,u);s=(p-x)/2,n=(m-b)/2,o=-(p+x)/2,a=-(m+b)/2}return{ratioX:s,ratioY:n,offsetX:o,offsetY:a}}(u,d,r),x=(i.width-o)/f,b=(i.height-o)/g,_=Math.max(Math.min(x,b)/2,0),y=c(this.options.radius,_),v=(y-Math.max(y*r,0))/this._getVisibleDatasetWeightTotal();this.offsetX=p*y,this.offsetY=m*y,s.total=this.calculateTotal(),this.outerRadius=y-v*this._getRingWeightOffset(this.index),this.innerRadius=Math.max(this.outerRadius-v*l,0),this.updateElements(n,0,n.length,t)}_circumference(t,e){const i=this.options,s=this._cachedMeta,n=this._getCircumference();return e&&i.animation.animateRotate||!this.chart.getDataVisibility(t)||null===s._parsed[t]||s.data[t].hidden?0:this.calculateCircumference(s._parsed[t]*n/O)}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.chartArea,r=o.options.animation,l=(a.left+a.right)/2,h=(a.top+a.bottom)/2,c=n&&r.animateScale,d=c?0:this.innerRadius,u=c?0:this.outerRadius,{sharedOptions:f,includeOptions:g}=this._getSharedOptions(e,s);let p,m=this._getRotation();for(p=0;p0&&!isNaN(t)?O*(Math.abs(t)/e):0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t],i.options.locale);return{label:s[t]||"",value:n}}getMaxBorderWidth(t){let e=0;const i=this.chart;let s,n,o,a,r;if(!t)for(s=0,n=i.data.datasets.length;s{const o=t.getDatasetMeta(0).controller.getStyle(n);return{text:e,fillStyle:o.backgroundColor,strokeStyle:o.borderColor,fontColor:s,lineWidth:o.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(n),index:n}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}};constructor(t,e){super(t,e),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t].r,i.options.locale);return{label:s[t]||"",value:n}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta.data;this._updateRadius(),this.updateElements(e,0,e.length,t)}getMinMax(){const t=this._cachedMeta,e={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};return t.data.forEach(((t,i)=>{const s=this.getParsed(i).r;!isNaN(s)&&this.chart.getDataVisibility(i)&&(se.max&&(e.max=s))})),e}_updateRadius(){const t=this.chart,e=t.chartArea,i=t.options,s=Math.min(e.right-e.left,e.bottom-e.top),n=Math.max(s/2,0),o=(n-Math.max(i.cutoutPercentage?n/100*i.cutoutPercentage:1,0))/t.getVisibleDatasetCount();this.outerRadius=n-o*this.index,this.innerRadius=this.outerRadius-o}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.options.animation,r=this._cachedMeta.rScale,l=r.xCenter,h=r.yCenter,c=r.getIndexAngle(0)-.5*C;let d,u=c;const f=360/this.countVisibleElements();for(d=0;d{!isNaN(this.getParsed(i).r)&&this.chart.getDataVisibility(i)&&e++})),e}_computeAngle(t,e,i){return this.chart.getDataVisibility(t)?$(this.resolveDataElementOptions(t,e).angle||i):0}}var Un=Object.freeze({__proto__:null,BarController:class extends js{static id="bar";static defaults={datasetElementType:!1,dataElementType:"bar",categoryPercentage:.8,barPercentage:.9,grouped:!0,animations:{numbers:{type:"number",properties:["x","y","base","width","height"]}}};static overrides={scales:{_index_:{type:"category",offset:!0,grid:{offset:!0}},_value_:{type:"linear",beginAtZero:!0}}};parsePrimitiveData(t,e,i,s){return Vn(t,e,i,s)}parseArrayData(t,e,i,s){return Vn(t,e,i,s)}parseObjectData(t,e,i,s){const{iScale:n,vScale:o}=t,{xAxisKey:a="x",yAxisKey:r="y"}=this._parsing,l="x"===n.axis?a:r,h="x"===o.axis?a:r,c=[];let d,u,f,g;for(d=i,u=i+s;dt.controller.options.grouped)),o=i.options.stacked,a=[],r=this._cachedMeta.controller.getParsed(e),l=r&&r[i.axis],h=t=>{const e=t._parsed.find((t=>t[i.axis]===l)),n=e&&e[t.vScale.axis];if(s(n)||isNaN(n))return!0};for(const i of n)if((void 0===e||!h(i))&&((!1===o||-1===a.indexOf(i.stack)||void 0===o&&void 0===i.stack)&&a.push(i.stack),i.index===t))break;return a.length||a.push(void 0),a}_getStackCount(t){return this._getStacks(void 0,t).length}_getAxisCount(){return this._getAxis().length}getFirstScaleIdForIndexAxis(){const t=this.chart.scales,e=this.chart.options.indexAxis;return Object.keys(t).filter((i=>t[i].axis===e)).shift()}_getAxis(){const t={},e=this.getFirstScaleIdForIndexAxis();for(const i of this.chart.data.datasets)t[l("x"===this.chart.options.indexAxis?i.xAxisID:i.yAxisID,e)]=!0;return Object.keys(t)}_getStackIndex(t,e,i){const s=this._getStacks(t,i),n=void 0!==e?s.indexOf(e):-1;return-1===n?s.length-1:n}_getRuler(){const t=this.options,e=this._cachedMeta,i=e.iScale,s=[];let n,o;for(n=0,o=e.data.length;n=i?1:-1)}(u,e,r)*a,f===r&&(x-=u/2);const t=e.getPixelForDecimal(0),s=e.getPixelForDecimal(1),o=Math.min(t,s),h=Math.max(t,s);x=Math.max(Math.min(x,h),o),d=x+u,i&&!c&&(l._stacks[e.axis]._visualValues[n]=e.getValueForPixel(d)-e.getValueForPixel(x))}if(x===e.getPixelForValue(r)){const t=F(u)*e.getLineWidthForValue(r)/2;x+=t,u-=t}return{size:u,base:x,head:d,center:d+u/2}}_calculateBarIndexPixels(t,e){const i=e.scale,n=this.options,o=n.skipNull,a=l(n.maxBarThickness,1/0);let r,h;const c=this._getAxisCount();if(e.grouped){const i=o?this._getStackCount(t):e.stackCount,d="flex"===n.barThickness?function(t,e,i,s){const n=e.pixels,o=n[t];let a=t>0?n[t-1]:null,r=t=0;--i)e=Math.max(e,t[i].size(this.resolveDataElementOptions(i))/2);return e>0&&e}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart.data.labels||[],{xScale:s,yScale:n}=e,o=this.getParsed(t),a=s.getLabelForValue(o.x),r=n.getLabelForValue(o.y),l=o._custom;return{label:i[t]||"",value:"("+a+", "+r+(l?", "+l:"")+")"}}update(t){const e=this._cachedMeta.data;this.updateElements(e,0,e.length,t)}updateElements(t,e,i,s){const n="reset"===s,{iScale:o,vScale:a}=this._cachedMeta,{sharedOptions:r,includeOptions:l}=this._getSharedOptions(e,s),h=o.axis,c=a.axis;for(let d=e;d0&&this.getParsed(e-1);for(let i=0;i<_;++i){const g=t[i],_=x?g:{};if(i=b){_.skip=!0;continue}const v=this.getParsed(i),M=s(v[f]),w=_[u]=a.getPixelForValue(v[u],i),k=_[f]=o||M?r.getBasePixel():r.getPixelForValue(l?this.applyStack(r,v,l):v[f],i);_.skip=isNaN(w)||isNaN(k)||M,_.stop=i>0&&Math.abs(v[u]-y[u])>m,p&&(_.parsed=v,_.raw=h.data[i]),d&&(_.options=c||this.resolveDataElementOptions(i,g.active?"active":n)),x||this.updateElement(g,i,_,n),y=v}}getMaxOverflow(){const t=this._cachedMeta,e=t.dataset,i=e.options&&e.options.borderWidth||0,s=t.data||[];if(!s.length)return i;const n=s[0].size(this.resolveDataElementOptions(0)),o=s[s.length-1].size(this.resolveDataElementOptions(s.length-1));return Math.max(i,n,o)/2}draw(){const t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}},PieController:class extends $n{static id="pie";static defaults={cutout:0,rotation:0,circumference:360,radius:"100%"}},PolarAreaController:Yn,RadarController:class extends js{static id="radar";static defaults={datasetElementType:"line",dataElementType:"point",indexAxis:"r",showLine:!0,elements:{line:{fill:"start"}}};static overrides={aspectRatio:1,scales:{r:{type:"radialLinear"}}};getLabelAndValue(t){const e=this._cachedMeta.vScale,i=this.getParsed(t);return{label:e.getLabels()[t],value:""+e.getLabelForValue(i[e.axis])}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta,i=e.dataset,s=e.data||[],n=e.iScale.getLabels();if(i.points=s,"resize"!==t){const e=this.resolveDatasetElementOptions(t);this.options.showLine||(e.borderWidth=0);const o={_loop:!0,_fullLoop:n.length===s.length,options:e};this.updateElement(i,void 0,o,t)}this.updateElements(s,0,s.length,t)}updateElements(t,e,i,s){const n=this._cachedMeta.rScale,o="reset"===s;for(let a=e;a0&&this.getParsed(e-1);for(let c=e;c0&&Math.abs(i[f]-_[f])>x,m&&(p.parsed=i,p.raw=h.data[c]),u&&(p.options=d||this.resolveDataElementOptions(c,e.active?"active":n)),b||this.updateElement(e,c,p,n),_=i}this.updateSharedOptions(d,n,c)}getMaxOverflow(){const t=this._cachedMeta,e=t.data||[];if(!this.options.showLine){let t=0;for(let i=e.length-1;i>=0;--i)t=Math.max(t,e[i].size(this.resolveDataElementOptions(i))/2);return t>0&&t}const i=t.dataset,s=i.options&&i.options.borderWidth||0;if(!e.length)return s;const n=e[0].size(this.resolveDataElementOptions(0)),o=e[e.length-1].size(this.resolveDataElementOptions(e.length-1));return Math.max(s,n,o)/2}}});function Xn(t,e,i,s){const n=vi(t.options.borderRadius,["outerStart","outerEnd","innerStart","innerEnd"]);const o=(i-e)/2,a=Math.min(o,s*e/2),r=t=>{const e=(i-Math.min(o,t))*s/2;return Z(t,0,Math.min(o,e))};return{outerStart:r(n.outerStart),outerEnd:r(n.outerEnd),innerStart:Z(n.innerStart,0,a),innerEnd:Z(n.innerEnd,0,a)}}function qn(t,e,i,s){return{x:i+t*Math.cos(e),y:s+t*Math.sin(e)}}function Kn(t,e,i,s,n,o){const{x:a,y:r,startAngle:l,pixelMargin:h,innerRadius:c}=e,d=Math.max(e.outerRadius+s+i-h,0),u=c>0?c+s+i+h:0;let f=0;const g=n-l;if(s){const t=((c>0?c-s:0)+(d>0?d-s:0))/2;f=(g-(0!==t?g*t/(t+s):g))/2}const p=(g-Math.max(.001,g*d-i/C)/d)/2,m=l+p+f,x=n-p-f,{outerStart:b,outerEnd:_,innerStart:y,innerEnd:v}=Xn(e,u,d,x-m),M=d-b,w=d-_,k=m+b/M,S=x-_/w,P=u+y,D=u+v,O=m+y/P,A=x-v/D;if(t.beginPath(),o){const e=(k+S)/2;if(t.arc(a,r,d,k,e),t.arc(a,r,d,e,S),_>0){const e=qn(w,S,a,r);t.arc(e.x,e.y,_,S,x+E)}const i=qn(D,x,a,r);if(t.lineTo(i.x,i.y),v>0){const e=qn(D,A,a,r);t.arc(e.x,e.y,v,x+E,A+Math.PI)}const s=(x-v/u+(m+y/u))/2;if(t.arc(a,r,u,x-v/u,s,!0),t.arc(a,r,u,s,m+y/u,!0),y>0){const e=qn(P,O,a,r);t.arc(e.x,e.y,y,O+Math.PI,m-E)}const n=qn(M,m,a,r);if(t.lineTo(n.x,n.y),b>0){const e=qn(M,k,a,r);t.arc(e.x,e.y,b,m-E,k)}}else{t.moveTo(a,r);const e=Math.cos(k)*d+a,i=Math.sin(k)*d+r;t.lineTo(e,i);const s=Math.cos(S)*d+a,n=Math.sin(S)*d+r;t.lineTo(s,n)}t.closePath()}function Gn(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r,options:l}=e,{borderWidth:h,borderJoinStyle:c,borderDash:d,borderDashOffset:u,borderRadius:f}=l,g="inner"===l.borderAlign;if(!h)return;t.setLineDash(d||[]),t.lineDashOffset=u,g?(t.lineWidth=2*h,t.lineJoin=c||"round"):(t.lineWidth=h,t.lineJoin=c||"bevel");let p=e.endAngle;if(o){Kn(t,e,i,s,p,n);for(let e=0;en?(h=n/l,t.arc(o,a,l,i+h,s-h,!0)):t.arc(o,a,n,i+E,s-E),t.closePath(),t.clip()}(t,e,p),l.selfJoin&&p-a>=C&&0===f&&"miter"!==c&&function(t,e,i){const{startAngle:s,x:n,y:o,outerRadius:a,innerRadius:r,options:l}=e,{borderWidth:h,borderJoinStyle:c}=l,d=Math.min(h/a,G(s-i));if(t.beginPath(),t.arc(n,o,a-h/2,s+d/2,i-d/2),r>0){const e=Math.min(h/r,G(s-i));t.arc(n,o,r+h/2,i-e/2,s+e/2,!0)}else{const e=Math.min(h/2,a*G(s-i));if("round"===c)t.arc(n,o,e,i-C/2,s+C/2,!0);else if("bevel"===c){const a=2*e*e,r=-a*Math.cos(i+C/2)+n,l=-a*Math.sin(i+C/2)+o,h=a*Math.cos(s+C/2)+n,c=a*Math.sin(s+C/2)+o;t.lineTo(r,l),t.lineTo(h,c)}}t.closePath(),t.moveTo(0,0),t.rect(0,0,t.canvas.width,t.canvas.height),t.clip("evenodd")}(t,e,p),o||(Kn(t,e,i,s,p,n),t.stroke())}function Jn(t,e,i=e){t.lineCap=l(i.borderCapStyle,e.borderCapStyle),t.setLineDash(l(i.borderDash,e.borderDash)),t.lineDashOffset=l(i.borderDashOffset,e.borderDashOffset),t.lineJoin=l(i.borderJoinStyle,e.borderJoinStyle),t.lineWidth=l(i.borderWidth,e.borderWidth),t.strokeStyle=l(i.borderColor,e.borderColor)}function Zn(t,e,i){t.lineTo(i.x,i.y)}function Qn(t,e,i={}){const s=t.length,{start:n=0,end:o=s-1}=i,{start:a,end:r}=e,l=Math.max(n,a),h=Math.min(o,r),c=nr&&o>r;return{count:s,start:l,loop:e.loop,ilen:h(a+(h?r-t:t))%o,_=()=>{f!==g&&(t.lineTo(m,g),t.lineTo(m,f),t.lineTo(m,p))};for(l&&(d=n[b(0)],t.moveTo(d.x,d.y)),c=0;c<=r;++c){if(d=n[b(c)],d.skip)continue;const e=d.x,i=d.y,s=0|e;s===u?(ig&&(g=i),m=(x*m+e)/++x):(_(),t.lineTo(e,i),u=s,x=0,f=g=i),p=i}_()}function io(t){const e=t.options,i=e.borderDash&&e.borderDash.length;return!(t._decimated||t._loop||e.tension||"monotone"===e.cubicInterpolationMode||e.stepped||i)?eo:to}const so="function"==typeof Path2D;function no(t,e,i,s){so&&!e.options.segment?function(t,e,i,s){let n=e._path;n||(n=e._path=new Path2D,e.path(n,i,s)&&n.closePath()),Jn(t,e.options),t.stroke(n)}(t,e,i,s):function(t,e,i,s){const{segments:n,options:o}=e,a=io(e);for(const r of n)Jn(t,o,r.style),t.beginPath(),a(t,e,r,{start:i,end:i+s-1})&&t.closePath(),t.stroke()}(t,e,i,s)}class oo extends $s{static id="line";static defaults={borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};static descriptors={_scriptable:!0,_indexable:t=>"borderDash"!==t&&"fill"!==t};constructor(t){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,t&&Object.assign(this,t)}updateControlPoints(t,e){const i=this.options;if((i.tension||"monotone"===i.cubicInterpolationMode)&&!i.stepped&&!this._pointsUpdated){const s=i.spanGaps?this._loop:this._fullLoop;hi(this._points,i,t,s,e),this._pointsUpdated=!0}}set points(t){this._points=t,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=zi(this,this.options.segment))}first(){const t=this.segments,e=this.points;return t.length&&e[t[0].start]}last(){const t=this.segments,e=this.points,i=t.length;return i&&e[t[i-1].end]}interpolate(t,e){const i=this.options,s=t[e],n=this.points,o=Ii(this,{property:e,start:s,end:s});if(!o.length)return;const a=[],r=function(t){return t.stepped?pi:t.tension||"monotone"===t.cubicInterpolationMode?mi:gi}(i);let l,h;for(l=0,h=o.length;l"borderDash"!==t};circumference;endAngle;fullCircles;innerRadius;outerRadius;pixelMargin;startAngle;constructor(t){super(),this.options=void 0,this.circumference=void 0,this.startAngle=void 0,this.endAngle=void 0,this.innerRadius=void 0,this.outerRadius=void 0,this.pixelMargin=0,this.fullCircles=0,t&&Object.assign(this,t)}inRange(t,e,i){const s=this.getProps(["x","y"],i),{angle:n,distance:o}=X(s,{x:t,y:e}),{startAngle:a,endAngle:r,innerRadius:h,outerRadius:c,circumference:d}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],i),u=(this.options.spacing+this.options.borderWidth)/2,f=l(d,r-a),g=J(n,a,r)&&a!==r,p=f>=O||g,m=tt(o,h+u,c+u);return p&&m}getCenterPoint(t){const{x:e,y:i,startAngle:s,endAngle:n,innerRadius:o,outerRadius:a}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],t),{offset:r,spacing:l}=this.options,h=(s+n)/2,c=(o+a+l+r)/2;return{x:e+Math.cos(h)*c,y:i+Math.sin(h)*c}}tooltipPosition(t){return this.getCenterPoint(t)}draw(t){const{options:e,circumference:i}=this,s=(e.offset||0)/4,n=(e.spacing||0)/2,o=e.circular;if(this.pixelMargin="inner"===e.borderAlign?.33:0,this.fullCircles=i>O?Math.floor(i/O):0,0===i||this.innerRadius<0||this.outerRadius<0)return;t.save();const a=(this.startAngle+this.endAngle)/2;t.translate(Math.cos(a)*s,Math.sin(a)*s);const r=s*(1-Math.sin(Math.min(C,i||0)));t.fillStyle=e.backgroundColor,t.strokeStyle=e.borderColor,function(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r}=e;let l=e.endAngle;if(o){Kn(t,e,i,s,l,n);for(let e=0;e("string"==typeof e?(i=t.push(e)-1,s.unshift({index:i,label:e})):isNaN(e)&&(i=null),i))(t,e,i,s);return n!==t.lastIndexOf(e)?i:n}function mo(t){const e=this.getLabels();return t>=0&&ts=e?s:t,a=t=>n=i?n:t;if(t){const t=F(s),e=F(n);t<0&&e<0?a(0):t>0&&e>0&&o(0)}if(s===n){let e=0===n?1:Math.abs(.05*n);a(n+e),t||o(s-e)}this.min=s,this.max=n}getTickLimit(){const t=this.options.ticks;let e,{maxTicksLimit:i,stepSize:s}=t;return s?(e=Math.ceil(this.max/s)-Math.floor(this.min/s)+1,e>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${s} would result generating up to ${e} ticks. Limiting to 1000.`),e=1e3)):(e=this.computeTickLimit(),i=i||11),i&&(e=Math.min(i,e)),e}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const t=this.options,e=t.ticks;let i=this.getTickLimit();i=Math.max(2,i);const n=function(t,e){const i=[],{bounds:n,step:o,min:a,max:r,precision:l,count:h,maxTicks:c,maxDigits:d,includeBounds:u}=t,f=o||1,g=c-1,{min:p,max:m}=e,x=!s(a),b=!s(r),_=!s(h),y=(m-p)/(d+1);let v,M,w,k,S=B((m-p)/g/f)*f;if(S<1e-14&&!x&&!b)return[{value:p},{value:m}];k=Math.ceil(m/S)-Math.floor(p/S),k>g&&(S=B(k*S/g/f)*f),s(l)||(v=Math.pow(10,l),S=Math.ceil(S*v)/v),"ticks"===n?(M=Math.floor(p/S)*S,w=Math.ceil(m/S)*S):(M=p,w=m),x&&b&&o&&H((r-a)/o,S/1e3)?(k=Math.round(Math.min((r-a)/S,c)),S=(r-a)/k,M=a,w=r):_?(M=x?a:M,w=b?r:w,k=h-1,S=(w-M)/k):(k=(w-M)/S,k=V(k,Math.round(k),S/1e3)?Math.round(k):Math.ceil(k));const P=Math.max(U(S),U(M));v=Math.pow(10,s(l)?P:l),M=Math.round(M*v)/v,w=Math.round(w*v)/v;let D=0;for(x&&(u&&M!==a?(i.push({value:a}),Mr)break;i.push({value:t})}return b&&u&&w!==r?i.length&&V(i[i.length-1].value,r,xo(r,y,t))?i[i.length-1].value=r:i.push({value:r}):b&&w!==r||i.push({value:w}),i}({maxTicks:i,bounds:t.bounds,min:t.min,max:t.max,precision:e.precision,step:e.stepSize,count:e.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:e.minRotation||0,includeBounds:!1!==e.includeBounds},this._range||this);return"ticks"===t.bounds&&j(n,this,"value"),t.reverse?(n.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),n}configure(){const t=this.ticks;let e=this.min,i=this.max;if(super.configure(),this.options.offset&&t.length){const s=(i-e)/Math.max(t.length-1,1)/2;e-=s,i+=s}this._startValue=e,this._endValue=i,this._valueRange=i-e}getLabelForValue(t){return ne(t,this.chart.options.locale,this.options.ticks.format)}}class _o extends bo{static id="linear";static defaults={ticks:{callback:ae.formatters.numeric}};determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?t:0,this.max=a(e)?e:1,this.handleTickRangeOptions()}computeTickLimit(){const t=this.isHorizontal(),e=t?this.width:this.height,i=$(this.options.ticks.minRotation),s=(t?Math.sin(i):Math.cos(i))||.001,n=this._resolveTickFontOptions(0);return Math.ceil(e/Math.min(40,n.lineHeight/s))}getPixelForValue(t){return null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getValueForPixel(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange}}const yo=t=>Math.floor(z(t)),vo=(t,e)=>Math.pow(10,yo(t)+e);function Mo(t){return 1===t/Math.pow(10,yo(t))}function wo(t,e,i){const s=Math.pow(10,i),n=Math.floor(t/s);return Math.ceil(e/s)-n}function ko(t,{min:e,max:i}){e=r(t.min,e);const s=[],n=yo(e);let o=function(t,e){let i=yo(e-t);for(;wo(t,e,i)>10;)i++;for(;wo(t,e,i)<10;)i--;return Math.min(i,yo(t))}(e,i),a=o<0?Math.pow(10,Math.abs(o)):1;const l=Math.pow(10,o),h=n>o?Math.pow(10,n):0,c=Math.round((e-h)*a)/a,d=Math.floor((e-h)/l/10)*l*10;let u=Math.floor((c-d)/Math.pow(10,o)),f=r(t.min,Math.round((h+d+u*Math.pow(10,o))*a)/a);for(;f=10?u=u<15?15:20:u++,u>=20&&(o++,u=2,a=o>=0?1:a),f=Math.round((h+d+u*Math.pow(10,o))*a)/a;const g=r(t.max,f);return s.push({value:g,major:Mo(g),significand:u}),s}class So extends tn{static id="logarithmic";static defaults={ticks:{callback:ae.formatters.logarithmic,major:{enabled:!0}}};constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){const i=bo.prototype.parse.apply(this,[t,e]);if(0!==i)return a(i)&&i>0?i:null;this._zero=!0}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?Math.max(0,t):null,this.max=a(e)?Math.max(0,e):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!a(this._userMin)&&(this.min=t===vo(this.min,0)?vo(this.min,-1):vo(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let i=this.min,s=this.max;const n=e=>i=t?i:e,o=t=>s=e?s:t;i===s&&(i<=0?(n(1),o(10)):(n(vo(i,-1)),o(vo(s,1)))),i<=0&&n(vo(s,-1)),s<=0&&o(vo(i,1)),this.min=i,this.max=s}buildTicks(){const t=this.options,e=ko({min:this._userMin,max:this._userMax},this);return"ticks"===t.bounds&&j(e,this,"value"),t.reverse?(e.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),e}getLabelForValue(t){return void 0===t?"0":ne(t,this.chart.options.locale,this.options.ticks.format)}configure(){const t=this.min;super.configure(),this._startValue=z(t),this._valueRange=z(this.max)-z(t)}getPixelForValue(t){return void 0!==t&&0!==t||(t=this.min),null===t||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(z(t)-this._startValue)/this._valueRange)}getValueForPixel(t){const e=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+e*this._valueRange)}}function Po(t){const e=t.ticks;if(e.display&&t.display){const t=ki(e.backdropPadding);return l(e.font&&e.font.size,ue.font.size)+t.height}return 0}function Do(t,e,i,s,n){return t===s||t===n?{start:e-i/2,end:e+i/2}:tn?{start:e-i,end:e}:{start:e,end:e+i}}function Co(t){const e={l:t.left+t._padding.left,r:t.right-t._padding.right,t:t.top+t._padding.top,b:t.bottom-t._padding.bottom},i=Object.assign({},e),s=[],o=[],a=t._pointLabels.length,r=t.options.pointLabels,l=r.centerPointLabels?C/a:0;for(let u=0;ue.r&&(r=(s.end-e.r)/o,t.r=Math.max(t.r,e.r+r)),n.starte.b&&(l=(n.end-e.b)/a,t.b=Math.max(t.b,e.b+l))}function Ao(t,e,i){const s=t.drawingArea,{extra:n,additionalAngle:o,padding:a,size:r}=i,l=t.getPointPosition(e,s+n+a,o),h=Math.round(Y(G(l.angle+E))),c=function(t,e,i){90===i||270===i?t-=e/2:(i>270||i<90)&&(t-=e);return t}(l.y,r.h,h),d=function(t){if(0===t||180===t)return"center";if(t<180)return"left";return"right"}(h),u=function(t,e,i){"right"===i?t-=e:"center"===i&&(t-=e/2);return t}(l.x,r.w,d);return{visible:!0,x:l.x,y:c,textAlign:d,left:u,top:c,right:u+r.w,bottom:c+r.h}}function To(t,e){if(!e)return!0;const{left:i,top:s,right:n,bottom:o}=t;return!(Re({x:i,y:s},e)||Re({x:i,y:o},e)||Re({x:n,y:s},e)||Re({x:n,y:o},e))}function Lo(t,e,i){const{left:n,top:o,right:a,bottom:r}=i,{backdropColor:l}=e;if(!s(l)){const i=wi(e.borderRadius),s=ki(e.backdropPadding);t.fillStyle=l;const h=n-s.left,c=o-s.top,d=a-n+s.width,u=r-o+s.height;Object.values(i).some((t=>0!==t))?(t.beginPath(),He(t,{x:h,y:c,w:d,h:u,radius:i}),t.fill()):t.fillRect(h,c,d,u)}}function Eo(t,e,i,s){const{ctx:n}=t;if(i)n.arc(t.xCenter,t.yCenter,e,0,O);else{let i=t.getPointPosition(0,e);n.moveTo(i.x,i.y);for(let o=1;ot,padding:5,centerPointLabels:!1}};static defaultRoutes={"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"};static descriptors={angleLines:{_fallback:"grid"}};constructor(t){super(t),this.xCenter=void 0,this.yCenter=void 0,this.drawingArea=void 0,this._pointLabels=[],this._pointLabelItems=[]}setDimensions(){const t=this._padding=ki(Po(this.options)/2),e=this.width=this.maxWidth-t.width,i=this.height=this.maxHeight-t.height;this.xCenter=Math.floor(this.left+e/2+t.left),this.yCenter=Math.floor(this.top+i/2+t.top),this.drawingArea=Math.floor(Math.min(e,i)/2)}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!1);this.min=a(t)&&!isNaN(t)?t:0,this.max=a(e)&&!isNaN(e)?e:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/Po(this.options))}generateTickLabels(t){bo.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map(((t,e)=>{const i=d(this.options.pointLabels.callback,[t,e],this);return i||0===i?i:""})).filter(((t,e)=>this.chart.getDataVisibility(e)))}fit(){const t=this.options;t.display&&t.pointLabels.display?Co(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,e,i,s){this.xCenter+=Math.floor((t-e)/2),this.yCenter+=Math.floor((i-s)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,e,i,s))}getIndexAngle(t){return G(t*(O/(this._pointLabels.length||1))+$(this.options.startAngle||0))}getDistanceFromCenterForValue(t){if(s(t))return NaN;const e=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-t)*e:(t-this.min)*e}getValueForDistanceFromCenter(t){if(s(t))return NaN;const e=t/(this.drawingArea/(this.max-this.min));return this.options.reverse?this.max-e:this.min+e}getPointLabelContext(t){const e=this._pointLabels||[];if(t>=0&&t=0;n--){const e=t._pointLabelItems[n];if(!e.visible)continue;const o=s.setContext(t.getPointLabelContext(n));Lo(i,o,e);const a=Si(o.font),{x:r,y:l,textAlign:h}=e;Ne(i,t._pointLabels[n],r,l+a.lineHeight/2,a,{color:o.color,textAlign:h,textBaseline:"middle"})}}(this,o),s.display&&this.ticks.forEach(((t,e)=>{if(0!==e||0===e&&this.min<0){r=this.getDistanceFromCenterForValue(t.value);const i=this.getContext(e),a=s.setContext(i),l=n.setContext(i);!function(t,e,i,s,n){const o=t.ctx,a=e.circular,{color:r,lineWidth:l}=e;!a&&!s||!r||!l||i<0||(o.save(),o.strokeStyle=r,o.lineWidth=l,o.setLineDash(n.dash||[]),o.lineDashOffset=n.dashOffset,o.beginPath(),Eo(t,i,a,s),o.closePath(),o.stroke(),o.restore())}(this,a,r,o,l)}})),i.display){for(t.save(),a=o-1;a>=0;a--){const s=i.setContext(this.getPointLabelContext(a)),{color:n,lineWidth:o}=s;o&&n&&(t.lineWidth=o,t.strokeStyle=n,t.setLineDash(s.borderDash),t.lineDashOffset=s.borderDashOffset,r=this.getDistanceFromCenterForValue(e.reverse?this.min:this.max),l=this.getPointPosition(a,r),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(l.x,l.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){const t=this.ctx,e=this.options,i=e.ticks;if(!i.display)return;const s=this.getIndexAngle(0);let n,o;t.save(),t.translate(this.xCenter,this.yCenter),t.rotate(s),t.textAlign="center",t.textBaseline="middle",this.ticks.forEach(((s,a)=>{if(0===a&&this.min>=0&&!e.reverse)return;const r=i.setContext(this.getContext(a)),l=Si(r.font);if(n=this.getDistanceFromCenterForValue(this.ticks[a].value),r.showLabelBackdrop){t.font=l.string,o=t.measureText(s.label).width,t.fillStyle=r.backdropColor;const e=ki(r.backdropPadding);t.fillRect(-o/2-e.left,-n-l.size/2-e.top,o+e.width,l.size+e.height)}Ne(t,s.label,0,-n,l,{color:r.color,strokeColor:r.textStrokeColor,strokeWidth:r.textStrokeWidth})})),t.restore()}drawTitle(){}}const Io={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},zo=Object.keys(Io);function Fo(t,e){return t-e}function Vo(t,e){if(s(e))return null;const i=t._adapter,{parser:n,round:o,isoWeekday:r}=t._parseOpts;let l=e;return"function"==typeof n&&(l=n(l)),a(l)||(l="string"==typeof n?i.parse(l,n):i.parse(l)),null===l?null:(o&&(l="week"!==o||!N(r)&&!0!==r?i.startOf(l,o):i.startOf(l,"isoWeek",r)),+l)}function Bo(t,e,i,s){const n=zo.length;for(let o=zo.indexOf(t);o=e?i[s]:i[n]]=!0}}else t[e]=!0}function No(t,e,i){const s=[],n={},o=e.length;let a,r;for(a=0;a=0&&(e[l].major=!0);return e}(t,s,n,i):s}class Ho extends tn{static id="time";static defaults={bounds:"data",adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{}},ticks:{source:"auto",callback:!1,major:{enabled:!1}}};constructor(t){super(t),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(t,e={}){const i=t.time||(t.time={}),s=this._adapter=new In._date(t.adapters.date);s.init(e),b(i.displayFormats,s.formats()),this._parseOpts={parser:i.parser,round:i.round,isoWeekday:i.isoWeekday},super.init(t),this._normalized=e.normalized}parse(t,e){return void 0===t?null:Vo(this,t)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){const t=this.options,e=this._adapter,i=t.time.unit||"day";let{min:s,max:n,minDefined:o,maxDefined:r}=this.getUserBounds();function l(t){o||isNaN(t.min)||(s=Math.min(s,t.min)),r||isNaN(t.max)||(n=Math.max(n,t.max))}o&&r||(l(this._getLabelBounds()),"ticks"===t.bounds&&"labels"===t.ticks.source||l(this.getMinMax(!1))),s=a(s)&&!isNaN(s)?s:+e.startOf(Date.now(),i),n=a(n)&&!isNaN(n)?n:+e.endOf(Date.now(),i)+1,this.min=Math.min(s,n-1),this.max=Math.max(s+1,n)}_getLabelBounds(){const t=this.getLabelTimestamps();let e=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;return t.length&&(e=t[0],i=t[t.length-1]),{min:e,max:i}}buildTicks(){const t=this.options,e=t.time,i=t.ticks,s="labels"===i.source?this.getLabelTimestamps():this._generate();"ticks"===t.bounds&&s.length&&(this.min=this._userMin||s[0],this.max=this._userMax||s[s.length-1]);const n=this.min,o=nt(s,n,this.max);return this._unit=e.unit||(i.autoSkip?Bo(e.minUnit,this.min,this.max,this._getLabelCapacity(n)):function(t,e,i,s,n){for(let o=zo.length-1;o>=zo.indexOf(i);o--){const i=zo[o];if(Io[i].common&&t._adapter.diff(n,s,i)>=e-1)return i}return zo[i?zo.indexOf(i):0]}(this,o.length,e.minUnit,this.min,this.max)),this._majorUnit=i.major.enabled&&"year"!==this._unit?function(t){for(let e=zo.indexOf(t)+1,i=zo.length;e+t.value)))}initOffsets(t=[]){let e,i,s=0,n=0;this.options.offset&&t.length&&(e=this.getDecimalForValue(t[0]),s=1===t.length?1-e:(this.getDecimalForValue(t[1])-e)/2,i=this.getDecimalForValue(t[t.length-1]),n=1===t.length?i:(i-this.getDecimalForValue(t[t.length-2]))/2);const o=t.length<3?.5:.25;s=Z(s,0,o),n=Z(n,0,o),this._offsets={start:s,end:n,factor:1/(s+1+n)}}_generate(){const t=this._adapter,e=this.min,i=this.max,s=this.options,n=s.time,o=n.unit||Bo(n.minUnit,e,i,this._getLabelCapacity(e)),a=l(s.ticks.stepSize,1),r="week"===o&&n.isoWeekday,h=N(r)||!0===r,c={};let d,u,f=e;if(h&&(f=+t.startOf(f,"isoWeek",r)),f=+t.startOf(f,h?"day":o),t.diff(i,e,o)>1e5*a)throw new Error(e+" and "+i+" are too far apart with stepSize of "+a+" "+o);const g="data"===s.ticks.source&&this.getDataTimestamps();for(d=f,u=0;d+t))}getLabelForValue(t){const e=this._adapter,i=this.options.time;return i.tooltipFormat?e.format(t,i.tooltipFormat):e.format(t,i.displayFormats.datetime)}format(t,e){const i=this.options.time.displayFormats,s=this._unit,n=e||i[s];return this._adapter.format(t,n)}_tickFormatFunction(t,e,i,s){const n=this.options,o=n.ticks.callback;if(o)return d(o,[t,e,i],this);const a=n.time.displayFormats,r=this._unit,l=this._majorUnit,h=r&&a[r],c=l&&a[l],u=i[e],f=l&&c&&u&&u.major;return this._adapter.format(t,s||(f?c:h))}generateTickLabels(t){let e,i,s;for(e=0,i=t.length;e0?a:1}getDataTimestamps(){let t,e,i=this._cache.data||[];if(i.length)return i;const s=this.getMatchingVisibleMetas();if(this._normalized&&s.length)return this._cache.data=s[0].controller.getAllParsedValues(this);for(t=0,e=s.length;t=t[r].pos&&e<=t[l].pos&&({lo:r,hi:l}=it(t,"pos",e)),({pos:s,time:o}=t[r]),({pos:n,time:a}=t[l])):(e>=t[r].time&&e<=t[l].time&&({lo:r,hi:l}=it(t,"time",e)),({time:s,pos:o}=t[r]),({time:n,pos:a}=t[l]));const h=n-s;return h?o+(a-o)*(e-s)/h:o}var $o=Object.freeze({__proto__:null,CategoryScale:class extends tn{static id="category";static defaults={ticks:{callback:mo}};constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){const e=this._addedLabels;if(e.length){const t=this.getLabels();for(const{index:i,label:s}of e)t[i]===s&&t.splice(i,1);this._addedLabels=[]}super.init(t)}parse(t,e){if(s(t))return null;const i=this.getLabels();return((t,e)=>null===t?null:Z(Math.round(t),0,e))(e=isFinite(e)&&i[e]===t?e:po(i,t,l(e,t),this._addedLabels),i.length-1)}determineDataLimits(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let{min:i,max:s}=this.getMinMax(!0);"ticks"===this.options.bounds&&(t||(i=0),e||(s=this.getLabels().length-1)),this.min=i,this.max=s}buildTicks(){const t=this.min,e=this.max,i=this.options.offset,s=[];let n=this.getLabels();n=0===t&&e===n.length-1?n:n.slice(t,e+1),this._valueRange=Math.max(n.length-(i?0:1),1),this._startValue=this.min-(i?.5:0);for(let i=t;i<=e;i++)s.push({value:i});return s}getLabelForValue(t){return mo.call(this,t)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(t){return"number"!=typeof t&&(t=this.parse(t)),null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getValueForPixel(t){return Math.round(this._startValue+this.getDecimalForPixel(t)*this._valueRange)}getBasePixel(){return this.bottom}},LinearScale:_o,LogarithmicScale:So,RadialLinearScale:Ro,TimeScale:Ho,TimeSeriesScale:class extends Ho{static id="timeseries";static defaults=Ho.defaults;constructor(t){super(t),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const t=this._getTimestampsForTable(),e=this._table=this.buildLookupTable(t);this._minPos=jo(e,this.min),this._tableRange=jo(e,this.max)-this._minPos,super.initOffsets(t)}buildLookupTable(t){const{min:e,max:i}=this,s=[],n=[];let o,a,r,l,h;for(o=0,a=t.length;o=e&&l<=i&&s.push(l);if(s.length<2)return[{time:e,pos:0},{time:i,pos:1}];for(o=0,a=s.length;ot-e))}_getTimestampsForTable(){let t=this._cache.all||[];if(t.length)return t;const e=this.getDataTimestamps(),i=this.getLabelTimestamps();return t=e.length&&i.length?this.normalize(e.concat(i)):e.length?e:i,t=this._cache.all=t,t}getDecimalForValue(t){return(jo(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){const e=this._offsets,i=this.getDecimalForPixel(t)/e.factor-e.end;return jo(this._table,i*this._tableRange+this._minPos,!0)}}});const Yo=["rgb(54, 162, 235)","rgb(255, 99, 132)","rgb(255, 159, 64)","rgb(255, 205, 86)","rgb(75, 192, 192)","rgb(153, 102, 255)","rgb(201, 203, 207)"],Uo=Yo.map((t=>t.replace("rgb(","rgba(").replace(")",", 0.5)")));function Xo(t){return Yo[t%Yo.length]}function qo(t){return Uo[t%Uo.length]}function Ko(t){let e=0;return(i,s)=>{const n=t.getDatasetMeta(s).controller;n instanceof $n?e=function(t,e){return t.backgroundColor=t.data.map((()=>Xo(e++))),e}(i,e):n instanceof Yn?e=function(t,e){return t.backgroundColor=t.data.map((()=>qo(e++))),e}(i,e):n&&(e=function(t,e){return t.borderColor=Xo(e),t.backgroundColor=qo(e),++e}(i,e))}}function Go(t){let e;for(e in t)if(t[e].borderColor||t[e].backgroundColor)return!0;return!1}var Jo={id:"colors",defaults:{enabled:!0,forceOverride:!1},beforeLayout(t,e,i){if(!i.enabled)return;const{data:{datasets:s},options:n}=t.config,{elements:o}=n,a=Go(s)||(r=n)&&(r.borderColor||r.backgroundColor)||o&&Go(o)||"rgba(0,0,0,0.1)"!==ue.borderColor||"rgba(0,0,0,0.1)"!==ue.backgroundColor;var r;if(!i.forceOverride&&a)return;const l=Ko(t);s.forEach(l)}};function Zo(t){if(t._decimated){const e=t._data;delete t._decimated,delete t._data,Object.defineProperty(t,"data",{configurable:!0,enumerable:!0,writable:!0,value:e})}}function Qo(t){t.data.datasets.forEach((t=>{Zo(t)}))}var ta={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(t,e,i)=>{if(!i.enabled)return void Qo(t);const n=t.width;t.data.datasets.forEach(((e,o)=>{const{_data:a,indexAxis:r}=e,l=t.getDatasetMeta(o),h=a||e.data;if("y"===Pi([r,t.options.indexAxis]))return;if(!l.controller.supportsDecimation)return;const c=t.scales[l.xAxisID];if("linear"!==c.type&&"time"!==c.type)return;if(t.options.parsing)return;let{start:d,count:u}=function(t,e){const i=e.length;let s,n=0;const{iScale:o}=t,{min:a,max:r,minDefined:l,maxDefined:h}=o.getUserBounds();return l&&(n=Z(it(e,o.axis,a).lo,0,i-1)),s=h?Z(it(e,o.axis,r).hi+1,n,i)-n:i-n,{start:n,count:s}}(l,h);if(u<=(i.threshold||4*n))return void Zo(e);let f;switch(s(a)&&(e._data=h,delete e.data,Object.defineProperty(e,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(t){this._data=t}})),i.algorithm){case"lttb":f=function(t,e,i,s,n){const o=n.samples||s;if(o>=i)return t.slice(e,e+i);const a=[],r=(i-2)/(o-2);let l=0;const h=e+i-1;let c,d,u,f,g,p=e;for(a[l++]=t[p],c=0;cu&&(u=f,d=t[s],g=s);a[l++]=d,p=g}return a[l++]=t[h],a}(h,d,u,n,i);break;case"min-max":f=function(t,e,i,n){let o,a,r,l,h,c,d,u,f,g,p=0,m=0;const x=[],b=e+i-1,_=t[e].x,y=t[b].x-_;for(o=e;og&&(g=l,d=o),p=(m*p+a.x)/++m;else{const i=o-1;if(!s(c)&&!s(d)){const e=Math.min(c,d),s=Math.max(c,d);e!==u&&e!==i&&x.push({...t[e],x:p}),s!==u&&s!==i&&x.push({...t[s],x:p})}o>0&&i!==u&&x.push(t[i]),x.push(a),h=e,m=0,f=g=l,c=d=u=o}}return x}(h,d,u,n);break;default:throw new Error(`Unsupported decimation algorithm '${i.algorithm}'`)}e._decimated=f}))},destroy(t){Qo(t)}};function ea(t,e,i,s){if(s)return;let n=e[t],o=i[t];return"angle"===t&&(n=G(n),o=G(o)),{property:t,start:n,end:o}}function ia(t,e,i){for(;e>t;e--){const t=i[e];if(!isNaN(t.x)&&!isNaN(t.y))break}return e}function sa(t,e,i,s){return t&&e?s(t[i],e[i]):t?t[i]:e?e[i]:0}function na(t,e){let i=[],s=!1;return n(t)?(s=!0,i=t):i=function(t,e){const{x:i=null,y:s=null}=t||{},n=e.points,o=[];return e.segments.forEach((({start:t,end:e})=>{e=ia(t,e,n);const a=n[t],r=n[e];null!==s?(o.push({x:a.x,y:s}),o.push({x:r.x,y:s})):null!==i&&(o.push({x:i,y:a.y}),o.push({x:i,y:r.y}))})),o}(t,e),i.length?new oo({points:i,options:{tension:0},_loop:s,_fullLoop:s}):null}function oa(t){return t&&!1!==t.fill}function aa(t,e,i){let s=t[e].fill;const n=[e];let o;if(!i)return s;for(;!1!==s&&-1===n.indexOf(s);){if(!a(s))return s;if(o=t[s],!o)return!1;if(o.visible)return s;n.push(s),s=o.fill}return!1}function ra(t,e,i){const s=function(t){const e=t.options,i=e.fill;let s=l(i&&i.target,i);void 0===s&&(s=!!e.backgroundColor);if(!1===s||null===s)return!1;if(!0===s)return"origin";return s}(t);if(o(s))return!isNaN(s.value)&&s;let n=parseFloat(s);return a(n)&&Math.floor(n)===n?function(t,e,i,s){"-"!==t&&"+"!==t||(i=e+i);if(i===e||i<0||i>=s)return!1;return i}(s[0],e,n,i):["origin","start","end","stack","shape"].indexOf(s)>=0&&s}function la(t,e,i){const s=[];for(let n=0;n=0;--e){const i=n[e].$filler;i&&(i.line.updateControlPoints(o,i.axis),s&&i.fill&&ua(t.ctx,i,o))}},beforeDatasetsDraw(t,e,i){if("beforeDatasetsDraw"!==i.drawTime)return;const s=t.getSortedVisibleDatasetMetas();for(let e=s.length-1;e>=0;--e){const i=s[e].$filler;oa(i)&&ua(t.ctx,i,t.chartArea)}},beforeDatasetDraw(t,e,i){const s=e.meta.$filler;oa(s)&&"beforeDatasetDraw"===i.drawTime&&ua(t.ctx,s,t.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}};const _a=(t,e)=>{let{boxHeight:i=e,boxWidth:s=e}=t;return t.usePointStyle&&(i=Math.min(i,e),s=t.pointStyleWidth||Math.min(s,e)),{boxWidth:s,boxHeight:i,itemHeight:Math.max(e,i)}};class ya extends $s{constructor(t){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e,i){this.maxWidth=t,this.maxHeight=e,this._margins=i,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){const t=this.options.labels||{};let e=d(t.generateLabels,[this.chart],this)||[];t.filter&&(e=e.filter((e=>t.filter(e,this.chart.data)))),t.sort&&(e=e.sort(((e,i)=>t.sort(e,i,this.chart.data)))),this.options.reverse&&e.reverse(),this.legendItems=e}fit(){const{options:t,ctx:e}=this;if(!t.display)return void(this.width=this.height=0);const i=t.labels,s=Si(i.font),n=s.size,o=this._computeTitleHeight(),{boxWidth:a,itemHeight:r}=_a(i,n);let l,h;e.font=s.string,this.isHorizontal()?(l=this.maxWidth,h=this._fitRows(o,n,a,r)+10):(h=this.maxHeight,l=this._fitCols(o,s,a,r)+10),this.width=Math.min(l,t.maxWidth||this.maxWidth),this.height=Math.min(h,t.maxHeight||this.maxHeight)}_fitRows(t,e,i,s){const{ctx:n,maxWidth:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.lineWidths=[0],h=s+a;let c=t;n.textAlign="left",n.textBaseline="middle";let d=-1,u=-h;return this.legendItems.forEach(((t,f)=>{const g=i+e/2+n.measureText(t.text).width;(0===f||l[l.length-1]+g+2*a>o)&&(c+=h,l[l.length-(f>0?0:1)]=0,u+=h,d++),r[f]={left:0,top:u,row:d,width:g,height:s},l[l.length-1]+=g+a})),c}_fitCols(t,e,i,s){const{ctx:n,maxHeight:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.columnSizes=[],h=o-t;let c=a,d=0,u=0,f=0,g=0;return this.legendItems.forEach(((t,o)=>{const{itemWidth:p,itemHeight:m}=function(t,e,i,s,n){const o=function(t,e,i,s){let n=t.text;n&&"string"!=typeof n&&(n=n.reduce(((t,e)=>t.length>e.length?t:e)));return e+i.size/2+s.measureText(n).width}(s,t,e,i),a=function(t,e,i){let s=t;"string"!=typeof e.text&&(s=va(e,i));return s}(n,s,e.lineHeight);return{itemWidth:o,itemHeight:a}}(i,e,n,t,s);o>0&&u+m+2*a>h&&(c+=d+a,l.push({width:d,height:u}),f+=d+a,g++,d=u=0),r[o]={left:f,top:u,col:g,width:p,height:m},d=Math.max(d,p),u+=m+a})),c+=d,l.push({width:d,height:u}),c}adjustHitBoxes(){if(!this.options.display)return;const t=this._computeTitleHeight(),{legendHitBoxes:e,options:{align:i,labels:{padding:s},rtl:n}}=this,o=Oi(n,this.left,this.width);if(this.isHorizontal()){let n=0,a=ft(i,this.left+s,this.right-this.lineWidths[n]);for(const r of e)n!==r.row&&(n=r.row,a=ft(i,this.left+s,this.right-this.lineWidths[n])),r.top+=this.top+t+s,r.left=o.leftForLtr(o.x(a),r.width),a+=r.width+s}else{let n=0,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height);for(const r of e)r.col!==n&&(n=r.col,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height)),r.top=a,r.left+=this.left+s,r.left=o.leftForLtr(o.x(r.left),r.width),a+=r.height+s}}isHorizontal(){return"top"===this.options.position||"bottom"===this.options.position}draw(){if(this.options.display){const t=this.ctx;Ie(t,this),this._draw(),ze(t)}}_draw(){const{options:t,columnSizes:e,lineWidths:i,ctx:s}=this,{align:n,labels:o}=t,a=ue.color,r=Oi(t.rtl,this.left,this.width),h=Si(o.font),{padding:c}=o,d=h.size,u=d/2;let f;this.drawTitle(),s.textAlign=r.textAlign("left"),s.textBaseline="middle",s.lineWidth=.5,s.font=h.string;const{boxWidth:g,boxHeight:p,itemHeight:m}=_a(o,d),x=this.isHorizontal(),b=this._computeTitleHeight();f=x?{x:ft(n,this.left+c,this.right-i[0]),y:this.top+c+b,line:0}:{x:this.left+c,y:ft(n,this.top+b+c,this.bottom-e[0].height),line:0},Ai(this.ctx,t.textDirection);const _=m+c;this.legendItems.forEach(((y,v)=>{s.strokeStyle=y.fontColor,s.fillStyle=y.fontColor;const M=s.measureText(y.text).width,w=r.textAlign(y.textAlign||(y.textAlign=o.textAlign)),k=g+u+M;let S=f.x,P=f.y;r.setWidth(this.width),x?v>0&&S+k+c>this.right&&(P=f.y+=_,f.line++,S=f.x=ft(n,this.left+c,this.right-i[f.line])):v>0&&P+_>this.bottom&&(S=f.x=S+e[f.line].width+c,f.line++,P=f.y=ft(n,this.top+b+c,this.bottom-e[f.line].height));if(function(t,e,i){if(isNaN(g)||g<=0||isNaN(p)||p<0)return;s.save();const n=l(i.lineWidth,1);if(s.fillStyle=l(i.fillStyle,a),s.lineCap=l(i.lineCap,"butt"),s.lineDashOffset=l(i.lineDashOffset,0),s.lineJoin=l(i.lineJoin,"miter"),s.lineWidth=n,s.strokeStyle=l(i.strokeStyle,a),s.setLineDash(l(i.lineDash,[])),o.usePointStyle){const a={radius:p*Math.SQRT2/2,pointStyle:i.pointStyle,rotation:i.rotation,borderWidth:n},l=r.xPlus(t,g/2);Ee(s,a,l,e+u,o.pointStyleWidth&&g)}else{const o=e+Math.max((d-p)/2,0),a=r.leftForLtr(t,g),l=wi(i.borderRadius);s.beginPath(),Object.values(l).some((t=>0!==t))?He(s,{x:a,y:o,w:g,h:p,radius:l}):s.rect(a,o,g,p),s.fill(),0!==n&&s.stroke()}s.restore()}(r.x(S),P,y),S=gt(w,S+g+u,x?S+k:this.right,t.rtl),function(t,e,i){Ne(s,i.text,t,e+m/2,h,{strikethrough:i.hidden,textAlign:r.textAlign(i.textAlign)})}(r.x(S),P,y),x)f.x+=k+c;else if("string"!=typeof y.text){const t=h.lineHeight;f.y+=va(y,t)+c}else f.y+=_})),Ti(this.ctx,t.textDirection)}drawTitle(){const t=this.options,e=t.title,i=Si(e.font),s=ki(e.padding);if(!e.display)return;const n=Oi(t.rtl,this.left,this.width),o=this.ctx,a=e.position,r=i.size/2,l=s.top+r;let h,c=this.left,d=this.width;if(this.isHorizontal())d=Math.max(...this.lineWidths),h=this.top+l,c=ft(t.align,c,this.right-d);else{const e=this.columnSizes.reduce(((t,e)=>Math.max(t,e.height)),0);h=l+ft(t.align,this.top,this.bottom-e-t.labels.padding-this._computeTitleHeight())}const u=ft(a,c,c+d);o.textAlign=n.textAlign(ut(a)),o.textBaseline="middle",o.strokeStyle=e.color,o.fillStyle=e.color,o.font=i.string,Ne(o,e.text,u,h,i)}_computeTitleHeight(){const t=this.options.title,e=Si(t.font),i=ki(t.padding);return t.display?e.lineHeight+i.height:0}_getLegendItemAt(t,e){let i,s,n;if(tt(t,this.left,this.right)&&tt(e,this.top,this.bottom))for(n=this.legendHitBoxes,i=0;it.chart.options.color,boxWidth:40,padding:10,generateLabels(t){const e=t.data.datasets,{labels:{usePointStyle:i,pointStyle:s,textAlign:n,color:o,useBorderRadius:a,borderRadius:r}}=t.legend.options;return t._getSortedDatasetMetas().map((t=>{const l=t.controller.getStyle(i?0:void 0),h=ki(l.borderWidth);return{text:e[t.index].label,fillStyle:l.backgroundColor,fontColor:o,hidden:!t.visible,lineCap:l.borderCapStyle,lineDash:l.borderDash,lineDashOffset:l.borderDashOffset,lineJoin:l.borderJoinStyle,lineWidth:(h.width+h.height)/4,strokeStyle:l.borderColor,pointStyle:s||l.pointStyle,rotation:l.rotation,textAlign:n||l.textAlign,borderRadius:a&&(r||l.borderRadius),datasetIndex:t.index}}),this)}},title:{color:t=>t.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:t=>!t.startsWith("on"),labels:{_scriptable:t=>!["generateLabels","filter","sort"].includes(t)}}};class wa extends $s{constructor(t){super(),this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e){const i=this.options;if(this.left=0,this.top=0,!i.display)return void(this.width=this.height=this.right=this.bottom=0);this.width=this.right=t,this.height=this.bottom=e;const s=n(i.text)?i.text.length:1;this._padding=ki(i.padding);const o=s*Si(i.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=o:this.width=o}isHorizontal(){const t=this.options.position;return"top"===t||"bottom"===t}_drawArgs(t){const{top:e,left:i,bottom:s,right:n,options:o}=this,a=o.align;let r,l,h,c=0;return this.isHorizontal()?(l=ft(a,i,n),h=e+t,r=n-i):("left"===o.position?(l=i+t,h=ft(a,s,e),c=-.5*C):(l=n-t,h=ft(a,e,s),c=.5*C),r=s-e),{titleX:l,titleY:h,maxWidth:r,rotation:c}}draw(){const t=this.ctx,e=this.options;if(!e.display)return;const i=Si(e.font),s=i.lineHeight/2+this._padding.top,{titleX:n,titleY:o,maxWidth:a,rotation:r}=this._drawArgs(s);Ne(t,e.text,0,0,i,{color:e.color,maxWidth:a,rotation:r,textAlign:ut(e.align),textBaseline:"middle",translation:[n,o]})}}var ka={id:"title",_element:wa,start(t,e,i){!function(t,e){const i=new wa({ctx:t.ctx,options:e,chart:t});ls.configure(t,i,e),ls.addBox(t,i),t.titleBlock=i}(t,i)},stop(t){const e=t.titleBlock;ls.removeBox(t,e),delete t.titleBlock},beforeUpdate(t,e,i){const s=t.titleBlock;ls.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const Sa=new WeakMap;var Pa={id:"subtitle",start(t,e,i){const s=new wa({ctx:t.ctx,options:i,chart:t});ls.configure(t,s,i),ls.addBox(t,s),Sa.set(t,s)},stop(t){ls.removeBox(t,Sa.get(t)),Sa.delete(t)},beforeUpdate(t,e,i){const s=Sa.get(t);ls.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"normal"},fullSize:!0,padding:0,position:"top",text:"",weight:1500},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const Da={average(t){if(!t.length)return!1;let e,i,s=new Set,n=0,o=0;for(e=0,i=t.length;et+e))/s.size,y:n/o}},nearest(t,e){if(!t.length)return!1;let i,s,n,o=e.x,a=e.y,r=Number.POSITIVE_INFINITY;for(i=0,s=t.length;i-1?t.split("\n"):t}function Aa(t,e){const{element:i,datasetIndex:s,index:n}=e,o=t.getDatasetMeta(s).controller,{label:a,value:r}=o.getLabelAndValue(n);return{chart:t,label:a,parsed:o.getParsed(n),raw:t.data.datasets[s].data[n],formattedValue:r,dataset:o.getDataset(),dataIndex:n,datasetIndex:s,element:i}}function Ta(t,e){const i=t.chart.ctx,{body:s,footer:n,title:o}=t,{boxWidth:a,boxHeight:r}=e,l=Si(e.bodyFont),h=Si(e.titleFont),c=Si(e.footerFont),d=o.length,f=n.length,g=s.length,p=ki(e.padding);let m=p.height,x=0,b=s.reduce(((t,e)=>t+e.before.length+e.lines.length+e.after.length),0);if(b+=t.beforeBody.length+t.afterBody.length,d&&(m+=d*h.lineHeight+(d-1)*e.titleSpacing+e.titleMarginBottom),b){m+=g*(e.displayColors?Math.max(r,l.lineHeight):l.lineHeight)+(b-g)*l.lineHeight+(b-1)*e.bodySpacing}f&&(m+=e.footerMarginTop+f*c.lineHeight+(f-1)*e.footerSpacing);let _=0;const y=function(t){x=Math.max(x,i.measureText(t).width+_)};return i.save(),i.font=h.string,u(t.title,y),i.font=l.string,u(t.beforeBody.concat(t.afterBody),y),_=e.displayColors?a+2+e.boxPadding:0,u(s,(t=>{u(t.before,y),u(t.lines,y),u(t.after,y)})),_=0,i.font=c.string,u(t.footer,y),i.restore(),x+=p.width,{width:x,height:m}}function La(t,e,i,s){const{x:n,width:o}=i,{width:a,chartArea:{left:r,right:l}}=t;let h="center";return"center"===s?h=n<=(r+l)/2?"left":"right":n<=o/2?h="left":n>=a-o/2&&(h="right"),function(t,e,i,s){const{x:n,width:o}=s,a=i.caretSize+i.caretPadding;return"left"===t&&n+o+a>e.width||"right"===t&&n-o-a<0||void 0}(h,t,e,i)&&(h="center"),h}function Ea(t,e,i){const s=i.yAlign||e.yAlign||function(t,e){const{y:i,height:s}=e;return it.height-s/2?"bottom":"center"}(t,i);return{xAlign:i.xAlign||e.xAlign||La(t,e,i,s),yAlign:s}}function Ra(t,e,i,s){const{caretSize:n,caretPadding:o,cornerRadius:a}=t,{xAlign:r,yAlign:l}=i,h=n+o,{topLeft:c,topRight:d,bottomLeft:u,bottomRight:f}=wi(a);let g=function(t,e){let{x:i,width:s}=t;return"right"===e?i-=s:"center"===e&&(i-=s/2),i}(e,r);const p=function(t,e,i){let{y:s,height:n}=t;return"top"===e?s+=i:s-="bottom"===e?n+i:n/2,s}(e,l,h);return"center"===l?"left"===r?g+=h:"right"===r&&(g-=h):"left"===r?g-=Math.max(c,u)+n:"right"===r&&(g+=Math.max(d,f)+n),{x:Z(g,0,s.width-e.width),y:Z(p,0,s.height-e.height)}}function Ia(t,e,i){const s=ki(i.padding);return"center"===e?t.x+t.width/2:"right"===e?t.x+t.width-s.right:t.x+s.left}function za(t){return Ca([],Oa(t))}function Fa(t,e){const i=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return i?t.override(i):t}const Va={beforeTitle:e,title(t){if(t.length>0){const e=t[0],i=e.chart.data.labels,s=i?i.length:0;if(this&&this.options&&"dataset"===this.options.mode)return e.dataset.label||"";if(e.label)return e.label;if(s>0&&e.dataIndex{const e={before:[],lines:[],after:[]},n=Fa(i,t);Ca(e.before,Oa(Ba(n,"beforeLabel",this,t))),Ca(e.lines,Ba(n,"label",this,t)),Ca(e.after,Oa(Ba(n,"afterLabel",this,t))),s.push(e)})),s}getAfterBody(t,e){return za(Ba(e.callbacks,"afterBody",this,t))}getFooter(t,e){const{callbacks:i}=e,s=Ba(i,"beforeFooter",this,t),n=Ba(i,"footer",this,t),o=Ba(i,"afterFooter",this,t);let a=[];return a=Ca(a,Oa(s)),a=Ca(a,Oa(n)),a=Ca(a,Oa(o)),a}_createItems(t){const e=this._active,i=this.chart.data,s=[],n=[],o=[];let a,r,l=[];for(a=0,r=e.length;at.filter(e,s,n,i)))),t.itemSort&&(l=l.sort(((e,s)=>t.itemSort(e,s,i)))),u(l,(e=>{const i=Fa(t.callbacks,e);s.push(Ba(i,"labelColor",this,e)),n.push(Ba(i,"labelPointStyle",this,e)),o.push(Ba(i,"labelTextColor",this,e))})),this.labelColors=s,this.labelPointStyles=n,this.labelTextColors=o,this.dataPoints=l,l}update(t,e){const i=this.options.setContext(this.getContext()),s=this._active;let n,o=[];if(s.length){const t=Da[i.position].call(this,s,this._eventPosition);o=this._createItems(i),this.title=this.getTitle(o,i),this.beforeBody=this.getBeforeBody(o,i),this.body=this.getBody(o,i),this.afterBody=this.getAfterBody(o,i),this.footer=this.getFooter(o,i);const e=this._size=Ta(this,i),a=Object.assign({},t,e),r=Ea(this.chart,i,a),l=Ra(i,a,r,this.chart);this.xAlign=r.xAlign,this.yAlign=r.yAlign,n={opacity:1,x:l.x,y:l.y,width:e.width,height:e.height,caretX:t.x,caretY:t.y}}else 0!==this.opacity&&(n={opacity:0});this._tooltipItems=o,this.$context=void 0,n&&this._resolveAnimations().update(this,n),t&&i.external&&i.external.call(this,{chart:this.chart,tooltip:this,replay:e})}drawCaret(t,e,i,s){const n=this.getCaretPosition(t,i,s);e.lineTo(n.x1,n.y1),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3)}getCaretPosition(t,e,i){const{xAlign:s,yAlign:n}=this,{caretSize:o,cornerRadius:a}=i,{topLeft:r,topRight:l,bottomLeft:h,bottomRight:c}=wi(a),{x:d,y:u}=t,{width:f,height:g}=e;let p,m,x,b,_,y;return"center"===n?(_=u+g/2,"left"===s?(p=d,m=p-o,b=_+o,y=_-o):(p=d+f,m=p+o,b=_-o,y=_+o),x=p):(m="left"===s?d+Math.max(r,h)+o:"right"===s?d+f-Math.max(l,c)-o:this.caretX,"top"===n?(b=u,_=b-o,p=m-o,x=m+o):(b=u+g,_=b+o,p=m+o,x=m-o),y=b),{x1:p,x2:m,x3:x,y1:b,y2:_,y3:y}}drawTitle(t,e,i){const s=this.title,n=s.length;let o,a,r;if(n){const l=Oi(i.rtl,this.x,this.width);for(t.x=Ia(this,i.titleAlign,i),e.textAlign=l.textAlign(i.titleAlign),e.textBaseline="middle",o=Si(i.titleFont),a=i.titleSpacing,e.fillStyle=i.titleColor,e.font=o.string,r=0;r0!==t))?(t.beginPath(),t.fillStyle=n.multiKeyBackground,He(t,{x:e,y:g,w:h,h:l,radius:r}),t.fill(),t.stroke(),t.fillStyle=a.backgroundColor,t.beginPath(),He(t,{x:i,y:g+1,w:h-2,h:l-2,radius:r}),t.fill()):(t.fillStyle=n.multiKeyBackground,t.fillRect(e,g,h,l),t.strokeRect(e,g,h,l),t.fillStyle=a.backgroundColor,t.fillRect(i,g+1,h-2,l-2))}t.fillStyle=this.labelTextColors[i]}drawBody(t,e,i){const{body:s}=this,{bodySpacing:n,bodyAlign:o,displayColors:a,boxHeight:r,boxWidth:l,boxPadding:h}=i,c=Si(i.bodyFont);let d=c.lineHeight,f=0;const g=Oi(i.rtl,this.x,this.width),p=function(i){e.fillText(i,g.x(t.x+f),t.y+d/2),t.y+=d+n},m=g.textAlign(o);let x,b,_,y,v,M,w;for(e.textAlign=o,e.textBaseline="middle",e.font=c.string,t.x=Ia(this,m,i),e.fillStyle=i.bodyColor,u(this.beforeBody,p),f=a&&"right"!==m?"center"===o?l/2+h:l+2+h:0,y=0,M=s.length;y0&&e.stroke()}_updateAnimationTarget(t){const e=this.chart,i=this.$animations,s=i&&i.x,n=i&&i.y;if(s||n){const i=Da[t.position].call(this,this._active,this._eventPosition);if(!i)return;const o=this._size=Ta(this,t),a=Object.assign({},i,this._size),r=Ea(e,t,a),l=Ra(t,a,r,e);s._to===l.x&&n._to===l.y||(this.xAlign=r.xAlign,this.yAlign=r.yAlign,this.width=o.width,this.height=o.height,this.caretX=i.x,this.caretY=i.y,this._resolveAnimations().update(this,l))}}_willRender(){return!!this.opacity}draw(t){const e=this.options.setContext(this.getContext());let i=this.opacity;if(!i)return;this._updateAnimationTarget(e);const s={width:this.width,height:this.height},n={x:this.x,y:this.y};i=Math.abs(i)<.001?0:i;const o=ki(e.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;e.enabled&&a&&(t.save(),t.globalAlpha=i,this.drawBackground(n,t,s,e),Ai(t,e.textDirection),n.y+=o.top,this.drawTitle(n,t,e),this.drawBody(n,t,e),this.drawFooter(n,t,e),Ti(t,e.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,e){const i=this._active,s=t.map((({datasetIndex:t,index:e})=>{const i=this.chart.getDatasetMeta(t);if(!i)throw new Error("Cannot find a dataset at index "+t);return{datasetIndex:t,element:i.data[e],index:e}})),n=!f(i,s),o=this._positionChanged(s,e);(n||o)&&(this._active=s,this._eventPosition=e,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,e,i=!0){if(e&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const s=this.options,n=this._active||[],o=this._getActiveElements(t,n,e,i),a=this._positionChanged(o,t),r=e||!f(o,n)||a;return r&&(this._active=o,(s.enabled||s.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,e))),r}_getActiveElements(t,e,i,s){const n=this.options;if("mouseout"===t.type)return[];if(!s)return e.filter((t=>this.chart.data.datasets[t.datasetIndex]&&void 0!==this.chart.getDatasetMeta(t.datasetIndex).controller.getParsed(t.index)));const o=this.chart.getElementsAtEventForMode(t,n.mode,n,i);return n.reverse&&o.reverse(),o}_positionChanged(t,e){const{caretX:i,caretY:s,options:n}=this,o=Da[n.position].call(this,t,e);return!1!==o&&(i!==o.x||s!==o.y)}}var Na={id:"tooltip",_element:Wa,positioners:Da,afterInit(t,e,i){i&&(t.tooltip=new Wa({chart:t,options:i}))},beforeUpdate(t,e,i){t.tooltip&&t.tooltip.initialize(i)},reset(t,e,i){t.tooltip&&t.tooltip.initialize(i)},afterDraw(t){const e=t.tooltip;if(e&&e._willRender()){const i={tooltip:e};if(!1===t.notifyPlugins("beforeTooltipDraw",{...i,cancelable:!0}))return;e.draw(t.ctx),t.notifyPlugins("afterTooltipDraw",i)}},afterEvent(t,e){if(t.tooltip){const i=e.replay;t.tooltip.handleEvent(e.event,i,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(t,e)=>e.bodyFont.size,boxWidth:(t,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:Va},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:t=>"filter"!==t&&"itemSort"!==t&&"external"!==t,_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]};return Tn.register(Un,$o,go,t),Tn.helpers={...Hi},Tn._adapters=In,Tn.Animation=As,Tn.Animations=Ts,Tn.animator=bt,Tn.controllers=nn.controllers.items,Tn.DatasetController=js,Tn.Element=$s,Tn.elements=go,Tn.Interaction=Ki,Tn.layouts=ls,Tn.platforms=Ds,Tn.Scale=tn,Tn.Ticks=ae,Object.assign(Tn,Un,$o,go,t,Ds),Tn.Chart=Tn,"undefined"!=typeof window&&(window.Chart=Tn),Tn})); +//# sourceMappingURL=chart.umd.min.js.map diff --git a/frontend/node_modules/chart.js/dist/chart.umd.min.js.map b/frontend/node_modules/chart.js/dist/chart.umd.min.js.map new file mode 100644 index 0000000000000000000000000000000000000000..016cbafe4230a4a4c712e8c320b506ba1ea5c2ca --- /dev/null +++ b/frontend/node_modules/chart.js/dist/chart.umd.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chart.umd.min.js","sources":["../src/helpers/helpers.core.ts","../src/helpers/helpers.math.ts","../src/helpers/helpers.collection.ts","../src/helpers/helpers.extras.ts","../src/core/core.animator.js","../node_modules/.pnpm/@kurkle+color@0.3.2/node_modules/@kurkle/color/dist/color.esm.js","../src/helpers/helpers.color.ts","../src/core/core.animations.defaults.js","../src/helpers/helpers.intl.ts","../src/core/core.ticks.js","../src/core/core.defaults.js","../src/core/core.layouts.defaults.js","../src/core/core.scale.defaults.js","../src/helpers/helpers.dom.ts","../src/helpers/helpers.canvas.ts","../src/helpers/helpers.config.ts","../src/helpers/helpers.curve.ts","../src/helpers/helpers.easing.ts","../src/helpers/helpers.interpolation.ts","../src/helpers/helpers.options.ts","../src/helpers/helpers.rtl.ts","../src/helpers/helpers.segment.js","../src/helpers/helpers.dataset.ts","../src/core/core.interaction.js","../src/core/core.layouts.js","../src/platform/platform.base.js","../src/platform/platform.basic.js","../src/platform/platform.dom.js","../src/platform/index.js","../src/core/core.animation.js","../src/core/core.animations.js","../src/core/core.datasetController.js","../src/core/core.element.ts","../src/core/core.scale.autoskip.js","../src/core/core.scale.js","../src/core/core.typedRegistry.js","../src/core/core.registry.js","../src/core/core.plugins.js","../src/core/core.config.js","../src/core/core.controller.js","../src/core/core.adapters.ts","../src/controllers/controller.bar.js","../src/controllers/controller.doughnut.js","../src/controllers/controller.polarArea.js","../src/controllers/controller.bubble.js","../src/controllers/controller.line.js","../src/controllers/controller.pie.js","../src/controllers/controller.radar.js","../src/controllers/controller.scatter.js","../src/elements/element.arc.ts","../src/elements/element.line.js","../src/elements/element.point.ts","../src/elements/element.bar.js","../src/scales/scale.category.js","../src/scales/scale.linearbase.js","../src/scales/scale.linear.js","../src/scales/scale.logarithmic.js","../src/scales/scale.radialLinear.js","../src/scales/scale.time.js","../src/scales/scale.timeseries.js","../src/plugins/plugin.colors.ts","../src/plugins/plugin.decimation.js","../src/plugins/plugin.filler/filler.segment.js","../src/plugins/plugin.filler/filler.helper.js","../src/plugins/plugin.filler/filler.options.js","../src/plugins/plugin.filler/filler.target.stack.js","../src/plugins/plugin.filler/simpleArc.js","../src/plugins/plugin.filler/filler.target.js","../src/plugins/plugin.filler/filler.drawing.js","../src/plugins/plugin.filler/index.js","../src/plugins/plugin.legend.js","../src/plugins/plugin.title.js","../src/plugins/plugin.subtitle.js","../src/plugins/plugin.tooltip.js","../src/index.umd.ts"],"sourcesContent":["/**\n * @namespace Chart.helpers\n */\n\nimport type {AnyObject} from '../types/basic.js';\nimport type {ActiveDataPoint, ChartEvent} from '../types/index.js';\n\n/**\n * An empty function that can be used, for example, for optional callback.\n */\nexport function noop() {\n /* noop */\n}\n\n/**\n * Returns a unique id, sequentially generated from a global variable.\n */\nexport const uid = (() => {\n let id = 0;\n return () => id++;\n})();\n\n/**\n * Returns true if `value` is neither null nor undefined, else returns false.\n * @param value - The value to test.\n * @since 2.7.0\n */\nexport function isNullOrUndef(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/**\n * Returns true if `value` is an array (including typed arrays), else returns false.\n * @param value - The value to test.\n * @function\n */\nexport function isArray(value: unknown): value is T[] {\n if (Array.isArray && Array.isArray(value)) {\n return true;\n }\n const type = Object.prototype.toString.call(value);\n if (type.slice(0, 7) === '[object' && type.slice(-6) === 'Array]') {\n return true;\n }\n return false;\n}\n\n/**\n * Returns true if `value` is an object (excluding null), else returns false.\n * @param value - The value to test.\n * @since 2.7.0\n */\nexport function isObject(value: unknown): value is AnyObject {\n return value !== null && Object.prototype.toString.call(value) === '[object Object]';\n}\n\n/**\n * Returns true if `value` is a finite number, else returns false\n * @param value - The value to test.\n */\nfunction isNumberFinite(value: unknown): value is number {\n return (typeof value === 'number' || value instanceof Number) && isFinite(+value);\n}\nexport {\n isNumberFinite as isFinite,\n};\n\n/**\n * Returns `value` if finite, else returns `defaultValue`.\n * @param value - The value to return if defined.\n * @param defaultValue - The value to return if `value` is not finite.\n */\nexport function finiteOrDefault(value: unknown, defaultValue: number) {\n return isNumberFinite(value) ? value : defaultValue;\n}\n\n/**\n * Returns `value` if defined, else returns `defaultValue`.\n * @param value - The value to return if defined.\n * @param defaultValue - The value to return if `value` is undefined.\n */\nexport function valueOrDefault(value: T | undefined, defaultValue: T) {\n return typeof value === 'undefined' ? defaultValue : value;\n}\n\nexport const toPercentage = (value: number | string, dimension: number) =>\n typeof value === 'string' && value.endsWith('%') ?\n parseFloat(value) / 100\n : +value / dimension;\n\nexport const toDimension = (value: number | string, dimension: number) =>\n typeof value === 'string' && value.endsWith('%') ?\n parseFloat(value) / 100 * dimension\n : +value;\n\n/**\n * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the\n * value returned by `fn`. If `fn` is not a function, this method returns undefined.\n * @param fn - The function to call.\n * @param args - The arguments with which `fn` should be called.\n * @param [thisArg] - The value of `this` provided for the call to `fn`.\n */\nexport function callback R, TA, R>(\n fn: T | undefined,\n args: unknown[],\n thisArg?: TA\n): R | undefined {\n if (fn && typeof fn.call === 'function') {\n return fn.apply(thisArg, args);\n }\n}\n\n/**\n * Note(SB) for performance sake, this method should only be used when loopable type\n * is unknown or in none intensive code (not called often and small loopable). Else\n * it's preferable to use a regular for() loop and save extra function calls.\n * @param loopable - The object or array to be iterated.\n * @param fn - The function to call for each item.\n * @param [thisArg] - The value of `this` provided for the call to `fn`.\n * @param [reverse] - If true, iterates backward on the loopable.\n */\nexport function each(\n loopable: Record,\n fn: (this: TA, v: T, i: string) => void,\n thisArg?: TA,\n reverse?: boolean\n): void;\nexport function each(\n loopable: T[],\n fn: (this: TA, v: T, i: number) => void,\n thisArg?: TA,\n reverse?: boolean\n): void;\nexport function each(\n loopable: T[] | Record,\n fn: (this: TA, v: T, i: any) => void,\n thisArg?: TA,\n reverse?: boolean\n) {\n let i: number, len: number, keys: string[];\n if (isArray(loopable)) {\n len = loopable.length;\n if (reverse) {\n for (i = len - 1; i >= 0; i--) {\n fn.call(thisArg, loopable[i], i);\n }\n } else {\n for (i = 0; i < len; i++) {\n fn.call(thisArg, loopable[i], i);\n }\n }\n } else if (isObject(loopable)) {\n keys = Object.keys(loopable);\n len = keys.length;\n for (i = 0; i < len; i++) {\n fn.call(thisArg, loopable[keys[i]], keys[i]);\n }\n }\n}\n\n/**\n * Returns true if the `a0` and `a1` arrays have the same content, else returns false.\n * @param a0 - The array to compare\n * @param a1 - The array to compare\n * @private\n */\nexport function _elementsEqual(a0: ActiveDataPoint[], a1: ActiveDataPoint[]) {\n let i: number, ilen: number, v0: ActiveDataPoint, v1: ActiveDataPoint;\n\n if (!a0 || !a1 || a0.length !== a1.length) {\n return false;\n }\n\n for (i = 0, ilen = a0.length; i < ilen; ++i) {\n v0 = a0[i];\n v1 = a1[i];\n\n if (v0.datasetIndex !== v1.datasetIndex || v0.index !== v1.index) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Returns a deep copy of `source` without keeping references on objects and arrays.\n * @param source - The value to clone.\n */\nexport function clone(source: T): T {\n if (isArray(source)) {\n return source.map(clone) as unknown as T;\n }\n\n if (isObject(source)) {\n const target = Object.create(null);\n const keys = Object.keys(source);\n const klen = keys.length;\n let k = 0;\n\n for (; k < klen; ++k) {\n target[keys[k]] = clone(source[keys[k]]);\n }\n\n return target;\n }\n\n return source;\n}\n\nfunction isValidKey(key: string) {\n return ['__proto__', 'prototype', 'constructor'].indexOf(key) === -1;\n}\n\n/**\n * The default merger when Chart.helpers.merge is called without merger option.\n * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.\n * @private\n */\nexport function _merger(key: string, target: AnyObject, source: AnyObject, options: AnyObject) {\n if (!isValidKey(key)) {\n return;\n }\n\n const tval = target[key];\n const sval = source[key];\n\n if (isObject(tval) && isObject(sval)) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n merge(tval, sval, options);\n } else {\n target[key] = clone(sval);\n }\n}\n\nexport interface MergeOptions {\n merger?: (key: string, target: AnyObject, source: AnyObject, options?: AnyObject) => void;\n}\n\n/**\n * Recursively deep copies `source` properties into `target` with the given `options`.\n * IMPORTANT: `target` is not cloned and will be updated with `source` properties.\n * @param target - The target object in which all sources are merged into.\n * @param source - Object(s) to merge into `target`.\n * @param [options] - Merging options:\n * @param [options.merger] - The merge method (key, target, source, options)\n * @returns The `target` object.\n */\nexport function merge(target: T, source: [], options?: MergeOptions): T;\nexport function merge(target: T, source: S1, options?: MergeOptions): T & S1;\nexport function merge(target: T, source: [S1], options?: MergeOptions): T & S1;\nexport function merge(target: T, source: [S1, S2], options?: MergeOptions): T & S1 & S2;\nexport function merge(target: T, source: [S1, S2, S3], options?: MergeOptions): T & S1 & S2 & S3;\nexport function merge(\n target: T,\n source: [S1, S2, S3, S4],\n options?: MergeOptions\n): T & S1 & S2 & S3 & S4;\nexport function merge(target: T, source: AnyObject[], options?: MergeOptions): AnyObject;\nexport function merge(target: T, source: AnyObject[], options?: MergeOptions): AnyObject {\n const sources = isArray(source) ? source : [source];\n const ilen = sources.length;\n\n if (!isObject(target)) {\n return target as AnyObject;\n }\n\n options = options || {};\n const merger = options.merger || _merger;\n let current: AnyObject;\n\n for (let i = 0; i < ilen; ++i) {\n current = sources[i];\n if (!isObject(current)) {\n continue;\n }\n\n const keys = Object.keys(current);\n for (let k = 0, klen = keys.length; k < klen; ++k) {\n merger(keys[k], target, current, options as AnyObject);\n }\n }\n\n return target;\n}\n\n/**\n * Recursively deep copies `source` properties into `target` *only* if not defined in target.\n * IMPORTANT: `target` is not cloned and will be updated with `source` properties.\n * @param target - The target object in which all sources are merged into.\n * @param source - Object(s) to merge into `target`.\n * @returns The `target` object.\n */\nexport function mergeIf(target: T, source: []): T;\nexport function mergeIf(target: T, source: S1): T & S1;\nexport function mergeIf(target: T, source: [S1]): T & S1;\nexport function mergeIf(target: T, source: [S1, S2]): T & S1 & S2;\nexport function mergeIf(target: T, source: [S1, S2, S3]): T & S1 & S2 & S3;\nexport function mergeIf(target: T, source: [S1, S2, S3, S4]): T & S1 & S2 & S3 & S4;\nexport function mergeIf(target: T, source: AnyObject[]): AnyObject;\nexport function mergeIf(target: T, source: AnyObject[]): AnyObject {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return merge(target, source, {merger: _mergerIf});\n}\n\n/**\n * Merges source[key] in target[key] only if target[key] is undefined.\n * @private\n */\nexport function _mergerIf(key: string, target: AnyObject, source: AnyObject) {\n if (!isValidKey(key)) {\n return;\n }\n\n const tval = target[key];\n const sval = source[key];\n\n if (isObject(tval) && isObject(sval)) {\n mergeIf(tval, sval);\n } else if (!Object.prototype.hasOwnProperty.call(target, key)) {\n target[key] = clone(sval);\n }\n}\n\n/**\n * @private\n */\nexport function _deprecated(scope: string, value: unknown, previous: string, current: string) {\n if (value !== undefined) {\n console.warn(scope + ': \"' + previous +\n '\" is deprecated. Please use \"' + current + '\" instead');\n }\n}\n\n// resolveObjectKey resolver cache\nconst keyResolvers = {\n // Chart.helpers.core resolveObjectKey should resolve empty key to root object\n '': v => v,\n // default resolvers\n x: o => o.x,\n y: o => o.y\n};\n\n/**\n * @private\n */\nexport function _splitKey(key: string) {\n const parts = key.split('.');\n const keys: string[] = [];\n let tmp = '';\n for (const part of parts) {\n tmp += part;\n if (tmp.endsWith('\\\\')) {\n tmp = tmp.slice(0, -1) + '.';\n } else {\n keys.push(tmp);\n tmp = '';\n }\n }\n return keys;\n}\n\nfunction _getKeyResolver(key: string) {\n const keys = _splitKey(key);\n return obj => {\n for (const k of keys) {\n if (k === '') {\n // For backward compatibility:\n // Chart.helpers.core resolveObjectKey should break at empty key\n break;\n }\n obj = obj && obj[k];\n }\n return obj;\n };\n}\n\nexport function resolveObjectKey(obj: AnyObject, key: string): any {\n const resolver = keyResolvers[key] || (keyResolvers[key] = _getKeyResolver(key));\n return resolver(obj);\n}\n\n/**\n * @private\n */\nexport function _capitalize(str: string) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n\nexport const defined = (value: unknown) => typeof value !== 'undefined';\n\nexport const isFunction = (value: unknown): value is (...args: any[]) => any => typeof value === 'function';\n\n// Adapted from https://stackoverflow.com/questions/31128855/comparing-ecma6-sets-for-equality#31129384\nexport const setsEqual = (a: Set, b: Set) => {\n if (a.size !== b.size) {\n return false;\n }\n\n for (const item of a) {\n if (!b.has(item)) {\n return false;\n }\n }\n\n return true;\n};\n\n/**\n * @param e - The event\n * @private\n */\nexport function _isClickEvent(e: ChartEvent) {\n return e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu';\n}\n","import type {Point} from '../types/geometric.js';\nimport {isFinite as isFiniteNumber} from './helpers.core.js';\n\n/**\n * @alias Chart.helpers.math\n * @namespace\n */\n\nexport const PI = Math.PI;\nexport const TAU = 2 * PI;\nexport const PITAU = TAU + PI;\nexport const INFINITY = Number.POSITIVE_INFINITY;\nexport const RAD_PER_DEG = PI / 180;\nexport const HALF_PI = PI / 2;\nexport const QUARTER_PI = PI / 4;\nexport const TWO_THIRDS_PI = PI * 2 / 3;\n\nexport const log10 = Math.log10;\nexport const sign = Math.sign;\n\nexport function almostEquals(x: number, y: number, epsilon: number) {\n return Math.abs(x - y) < epsilon;\n}\n\n/**\n * Implementation of the nice number algorithm used in determining where axis labels will go\n */\nexport function niceNum(range: number) {\n const roundedRange = Math.round(range);\n range = almostEquals(range, roundedRange, range / 1000) ? roundedRange : range;\n const niceRange = Math.pow(10, Math.floor(log10(range)));\n const fraction = range / niceRange;\n const niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10;\n return niceFraction * niceRange;\n}\n\n/**\n * Returns an array of factors sorted from 1 to sqrt(value)\n * @private\n */\nexport function _factorize(value: number) {\n const result: number[] = [];\n const sqrt = Math.sqrt(value);\n let i: number;\n\n for (i = 1; i < sqrt; i++) {\n if (value % i === 0) {\n result.push(i);\n result.push(value / i);\n }\n }\n if (sqrt === (sqrt | 0)) { // if value is a square number\n result.push(sqrt);\n }\n\n result.sort((a, b) => a - b).pop();\n return result;\n}\n\n/**\n * Verifies that attempting to coerce n to string or number won't throw a TypeError.\n */\nfunction isNonPrimitive(n: unknown) {\n return typeof n === 'symbol' || (typeof n === 'object' && n !== null && !(Symbol.toPrimitive in n || 'toString' in n || 'valueOf' in n));\n}\n\nexport function isNumber(n: unknown): n is number {\n return !isNonPrimitive(n) && !isNaN(parseFloat(n as string)) && isFinite(n as number);\n}\n\nexport function almostWhole(x: number, epsilon: number) {\n const rounded = Math.round(x);\n return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);\n}\n\n/**\n * @private\n */\nexport function _setMinAndMaxByKey(\n array: Record[],\n target: { min: number, max: number },\n property: string\n) {\n let i: number, ilen: number, value: number;\n\n for (i = 0, ilen = array.length; i < ilen; i++) {\n value = array[i][property];\n if (!isNaN(value)) {\n target.min = Math.min(target.min, value);\n target.max = Math.max(target.max, value);\n }\n }\n}\n\nexport function toRadians(degrees: number) {\n return degrees * (PI / 180);\n}\n\nexport function toDegrees(radians: number) {\n return radians * (180 / PI);\n}\n\n/**\n * Returns the number of decimal places\n * i.e. the number of digits after the decimal point, of the value of this Number.\n * @param x - A number.\n * @returns The number of decimal places.\n * @private\n */\nexport function _decimalPlaces(x: number) {\n if (!isFiniteNumber(x)) {\n return;\n }\n let e = 1;\n let p = 0;\n while (Math.round(x * e) / e !== x) {\n e *= 10;\n p++;\n }\n return p;\n}\n\n// Gets the angle from vertical upright to the point about a centre.\nexport function getAngleFromPoint(\n centrePoint: Point,\n anglePoint: Point\n) {\n const distanceFromXCenter = anglePoint.x - centrePoint.x;\n const distanceFromYCenter = anglePoint.y - centrePoint.y;\n const radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);\n\n let angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);\n\n if (angle < (-0.5 * PI)) {\n angle += TAU; // make sure the returned angle is in the range of (-PI/2, 3PI/2]\n }\n\n return {\n angle,\n distance: radialDistanceFromCenter\n };\n}\n\nexport function distanceBetweenPoints(pt1: Point, pt2: Point) {\n return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));\n}\n\n/**\n * Shortest distance between angles, in either direction.\n * @private\n */\nexport function _angleDiff(a: number, b: number) {\n return (a - b + PITAU) % TAU - PI;\n}\n\n/**\n * Normalize angle to be between 0 and 2*PI\n * @private\n */\nexport function _normalizeAngle(a: number) {\n return (a % TAU + TAU) % TAU;\n}\n\n/**\n * @private\n */\nexport function _angleBetween(angle: number, start: number, end: number, sameAngleIsFullCircle?: boolean) {\n const a = _normalizeAngle(angle);\n const s = _normalizeAngle(start);\n const e = _normalizeAngle(end);\n const angleToStart = _normalizeAngle(s - a);\n const angleToEnd = _normalizeAngle(e - a);\n const startToAngle = _normalizeAngle(a - s);\n const endToAngle = _normalizeAngle(a - e);\n return a === s || a === e || (sameAngleIsFullCircle && s === e)\n || (angleToStart > angleToEnd && startToAngle < endToAngle);\n}\n\n/**\n * Limit `value` between `min` and `max`\n * @param value\n * @param min\n * @param max\n * @private\n */\nexport function _limitValue(value: number, min: number, max: number) {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * @param {number} value\n * @private\n */\nexport function _int16Range(value: number) {\n return _limitValue(value, -32768, 32767);\n}\n\n/**\n * @param value\n * @param start\n * @param end\n * @param [epsilon]\n * @private\n */\nexport function _isBetween(value: number, start: number, end: number, epsilon = 1e-6) {\n return value >= Math.min(start, end) - epsilon && value <= Math.max(start, end) + epsilon;\n}\n","import {_capitalize} from './helpers.core.js';\n\n/**\n * Binary search\n * @param table - the table search. must be sorted!\n * @param value - value to find\n * @param cmp\n * @private\n */\nexport function _lookup(\n table: number[],\n value: number,\n cmp?: (value: number) => boolean\n): {lo: number, hi: number};\nexport function _lookup(\n table: T[],\n value: number,\n cmp: (value: number) => boolean\n): {lo: number, hi: number};\nexport function _lookup(\n table: unknown[],\n value: number,\n cmp?: (value: number) => boolean\n) {\n cmp = cmp || ((index) => table[index] < value);\n let hi = table.length - 1;\n let lo = 0;\n let mid: number;\n\n while (hi - lo > 1) {\n mid = (lo + hi) >> 1;\n if (cmp(mid)) {\n lo = mid;\n } else {\n hi = mid;\n }\n }\n\n return {lo, hi};\n}\n\n/**\n * Binary search\n * @param table - the table search. must be sorted!\n * @param key - property name for the value in each entry\n * @param value - value to find\n * @param last - lookup last index\n * @private\n */\nexport const _lookupByKey = (\n table: Record[],\n key: string,\n value: number,\n last?: boolean\n) =>\n _lookup(table, value, last\n ? index => {\n const ti = table[index][key];\n return ti < value || ti === value && table[index + 1][key] === value;\n }\n : index => table[index][key] < value);\n\n/**\n * Reverse binary search\n * @param table - the table search. must be sorted!\n * @param key - property name for the value in each entry\n * @param value - value to find\n * @private\n */\nexport const _rlookupByKey = (\n table: Record[],\n key: string,\n value: number\n) =>\n _lookup(table, value, index => table[index][key] >= value);\n\n/**\n * Return subset of `values` between `min` and `max` inclusive.\n * Values are assumed to be in sorted order.\n * @param values - sorted array of values\n * @param min - min value\n * @param max - max value\n */\nexport function _filterBetween(values: number[], min: number, max: number) {\n let start = 0;\n let end = values.length;\n\n while (start < end && values[start] < min) {\n start++;\n }\n while (end > start && values[end - 1] > max) {\n end--;\n }\n\n return start > 0 || end < values.length\n ? values.slice(start, end)\n : values;\n}\n\nconst arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'] as const;\n\nexport interface ArrayListener {\n _onDataPush?(...item: T[]): void;\n _onDataPop?(): void;\n _onDataShift?(): void;\n _onDataSplice?(index: number, deleteCount: number, ...items: T[]): void;\n _onDataUnshift?(...item: T[]): void;\n}\n\n/**\n * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',\n * 'unshift') and notify the listener AFTER the array has been altered. Listeners are\n * called on the '_onData*' callbacks (e.g. _onDataPush, etc.) with same arguments.\n */\nexport function listenArrayEvents(array: T[], listener: ArrayListener): void;\nexport function listenArrayEvents(array, listener) {\n if (array._chartjs) {\n array._chartjs.listeners.push(listener);\n return;\n }\n\n Object.defineProperty(array, '_chartjs', {\n configurable: true,\n enumerable: false,\n value: {\n listeners: [listener]\n }\n });\n\n arrayEvents.forEach((key) => {\n const method = '_onData' + _capitalize(key);\n const base = array[key];\n\n Object.defineProperty(array, key, {\n configurable: true,\n enumerable: false,\n value(...args) {\n const res = base.apply(this, args);\n\n array._chartjs.listeners.forEach((object) => {\n if (typeof object[method] === 'function') {\n object[method](...args);\n }\n });\n\n return res;\n }\n });\n });\n}\n\n\n/**\n * Removes the given array event listener and cleanup extra attached properties (such as\n * the _chartjs stub and overridden methods) if array doesn't have any more listeners.\n */\nexport function unlistenArrayEvents(array: T[], listener: ArrayListener): void;\nexport function unlistenArrayEvents(array, listener) {\n const stub = array._chartjs;\n if (!stub) {\n return;\n }\n\n const listeners = stub.listeners;\n const index = listeners.indexOf(listener);\n if (index !== -1) {\n listeners.splice(index, 1);\n }\n\n if (listeners.length > 0) {\n return;\n }\n\n arrayEvents.forEach((key) => {\n delete array[key];\n });\n\n delete array._chartjs;\n}\n\n/**\n * @param items\n */\nexport function _arrayUnique(items: T[]) {\n const set = new Set(items);\n\n if (set.size === items.length) {\n return items;\n }\n\n return Array.from(set);\n}\n","import type {ChartMeta, PointElement} from '../types/index.js';\n\nimport {_limitValue} from './helpers.math.js';\nimport {_lookupByKey} from './helpers.collection.js';\nimport {isNullOrUndef} from './helpers.core.js';\n\nexport function fontString(pixelSize: number, fontStyle: string, fontFamily: string) {\n return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;\n}\n\n/**\n* Request animation polyfill\n*/\nexport const requestAnimFrame = (function() {\n if (typeof window === 'undefined') {\n return function(callback) {\n return callback();\n };\n }\n return window.requestAnimationFrame;\n}());\n\n/**\n * Throttles calling `fn` once per animation frame\n * Latest arguments are used on the actual call\n */\nexport function throttled>(\n fn: (...args: TArgs) => void,\n thisArg: any,\n) {\n let argsToUse = [] as TArgs;\n let ticking = false;\n\n return function(...args: TArgs) {\n // Save the args for use later\n argsToUse = args;\n if (!ticking) {\n ticking = true;\n requestAnimFrame.call(window, () => {\n ticking = false;\n fn.apply(thisArg, argsToUse);\n });\n }\n };\n}\n\n/**\n * Debounces calling `fn` for `delay` ms\n */\nexport function debounce>(fn: (...args: TArgs) => void, delay: number) {\n let timeout;\n return function(...args: TArgs) {\n if (delay) {\n clearTimeout(timeout);\n timeout = setTimeout(fn, delay, args);\n } else {\n fn.apply(this, args);\n }\n return delay;\n };\n}\n\n/**\n * Converts 'start' to 'left', 'end' to 'right' and others to 'center'\n * @private\n */\nexport const _toLeftRightCenter = (align: 'start' | 'end' | 'center') => align === 'start' ? 'left' : align === 'end' ? 'right' : 'center';\n\n/**\n * Returns `start`, `end` or `(start + end) / 2` depending on `align`. Defaults to `center`\n * @private\n */\nexport const _alignStartEnd = (align: 'start' | 'end' | 'center', start: number, end: number) => align === 'start' ? start : align === 'end' ? end : (start + end) / 2;\n\n/**\n * Returns `left`, `right` or `(left + right) / 2` depending on `align`. Defaults to `left`\n * @private\n */\nexport const _textX = (align: 'left' | 'right' | 'center', left: number, right: number, rtl: boolean) => {\n const check = rtl ? 'left' : 'right';\n return align === check ? right : align === 'center' ? (left + right) / 2 : left;\n};\n\n/**\n * Return start and count of visible points.\n * @private\n */\nexport function _getStartAndCountOfVisiblePoints(meta: ChartMeta<'line' | 'scatter'>, points: PointElement[], animationsDisabled: boolean) {\n const pointCount = points.length;\n\n let start = 0;\n let count = pointCount;\n\n if (meta._sorted) {\n const {iScale, vScale, _parsed} = meta;\n const spanGaps = meta.dataset ? meta.dataset.options ? meta.dataset.options.spanGaps : null : null;\n const axis = iScale.axis;\n const {min, max, minDefined, maxDefined} = iScale.getUserBounds();\n\n if (minDefined) {\n start = Math.min(\n // @ts-expect-error Need to type _parsed\n _lookupByKey(_parsed, axis, min).lo,\n // @ts-expect-error Need to fix types on _lookupByKey\n animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min)).lo);\n if (spanGaps) {\n const distanceToDefinedLo = (_parsed\n .slice(0, start + 1)\n .reverse()\n .findIndex(\n point => !isNullOrUndef(point[vScale.axis])));\n start -= Math.max(0, distanceToDefinedLo);\n }\n start = _limitValue(start, 0, pointCount - 1);\n }\n if (maxDefined) {\n let end = Math.max(\n // @ts-expect-error Need to type _parsed\n _lookupByKey(_parsed, iScale.axis, max, true).hi + 1,\n // @ts-expect-error Need to fix types on _lookupByKey\n animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max), true).hi + 1);\n if (spanGaps) {\n const distanceToDefinedHi = (_parsed\n .slice(end - 1)\n .findIndex(\n point => !isNullOrUndef(point[vScale.axis])));\n end += Math.max(0, distanceToDefinedHi);\n }\n count = _limitValue(end, start, pointCount) - start;\n } else {\n count = pointCount - start;\n }\n }\n\n return {start, count};\n}\n\n/**\n * Checks if the scale ranges have changed.\n * @param {object} meta - dataset meta.\n * @returns {boolean}\n * @private\n */\nexport function _scaleRangesChanged(meta) {\n const {xScale, yScale, _scaleRanges} = meta;\n const newRanges = {\n xmin: xScale.min,\n xmax: xScale.max,\n ymin: yScale.min,\n ymax: yScale.max\n };\n if (!_scaleRanges) {\n meta._scaleRanges = newRanges;\n return true;\n }\n const changed = _scaleRanges.xmin !== xScale.min\n\t\t|| _scaleRanges.xmax !== xScale.max\n\t\t|| _scaleRanges.ymin !== yScale.min\n\t\t|| _scaleRanges.ymax !== yScale.max;\n\n Object.assign(_scaleRanges, newRanges);\n return changed;\n}\n","import {requestAnimFrame} from '../helpers/helpers.extras.js';\n\n/**\n * @typedef { import('./core.animation.js').default } Animation\n * @typedef { import('./core.controller.js').default } Chart\n */\n\n/**\n * Please use the module's default export which provides a singleton instance\n * Note: class is export for typedoc\n */\nexport class Animator {\n constructor() {\n this._request = null;\n this._charts = new Map();\n this._running = false;\n this._lastDate = undefined;\n }\n\n /**\n\t * @private\n\t */\n _notify(chart, anims, date, type) {\n const callbacks = anims.listeners[type];\n const numSteps = anims.duration;\n\n callbacks.forEach(fn => fn({\n chart,\n initial: anims.initial,\n numSteps,\n currentStep: Math.min(date - anims.start, numSteps)\n }));\n }\n\n /**\n\t * @private\n\t */\n _refresh() {\n if (this._request) {\n return;\n }\n this._running = true;\n\n this._request = requestAnimFrame.call(window, () => {\n this._update();\n this._request = null;\n\n if (this._running) {\n this._refresh();\n }\n });\n }\n\n /**\n\t * @private\n\t */\n _update(date = Date.now()) {\n let remaining = 0;\n\n this._charts.forEach((anims, chart) => {\n if (!anims.running || !anims.items.length) {\n return;\n }\n const items = anims.items;\n let i = items.length - 1;\n let draw = false;\n let item;\n\n for (; i >= 0; --i) {\n item = items[i];\n\n if (item._active) {\n if (item._total > anims.duration) {\n // if the animation has been updated and its duration prolonged,\n // update to total duration of current animations run (for progress event)\n anims.duration = item._total;\n }\n item.tick(date);\n draw = true;\n } else {\n // Remove the item by replacing it with last item and removing the last\n // A lot faster than splice.\n items[i] = items[items.length - 1];\n items.pop();\n }\n }\n\n if (draw) {\n chart.draw();\n this._notify(chart, anims, date, 'progress');\n }\n\n if (!items.length) {\n anims.running = false;\n this._notify(chart, anims, date, 'complete');\n anims.initial = false;\n }\n\n remaining += items.length;\n });\n\n this._lastDate = date;\n\n if (remaining === 0) {\n this._running = false;\n }\n }\n\n /**\n\t * @private\n\t */\n _getAnims(chart) {\n const charts = this._charts;\n let anims = charts.get(chart);\n if (!anims) {\n anims = {\n running: false,\n initial: true,\n items: [],\n listeners: {\n complete: [],\n progress: []\n }\n };\n charts.set(chart, anims);\n }\n return anims;\n }\n\n /**\n\t * @param {Chart} chart\n\t * @param {string} event - event name\n\t * @param {Function} cb - callback\n\t */\n listen(chart, event, cb) {\n this._getAnims(chart).listeners[event].push(cb);\n }\n\n /**\n\t * Add animations\n\t * @param {Chart} chart\n\t * @param {Animation[]} items - animations\n\t */\n add(chart, items) {\n if (!items || !items.length) {\n return;\n }\n this._getAnims(chart).items.push(...items);\n }\n\n /**\n\t * Counts number of active animations for the chart\n\t * @param {Chart} chart\n\t */\n has(chart) {\n return this._getAnims(chart).items.length > 0;\n }\n\n /**\n\t * Start animating (all charts)\n\t * @param {Chart} chart\n\t */\n start(chart) {\n const anims = this._charts.get(chart);\n if (!anims) {\n return;\n }\n anims.running = true;\n anims.start = Date.now();\n anims.duration = anims.items.reduce((acc, cur) => Math.max(acc, cur._duration), 0);\n this._refresh();\n }\n\n running(chart) {\n if (!this._running) {\n return false;\n }\n const anims = this._charts.get(chart);\n if (!anims || !anims.running || !anims.items.length) {\n return false;\n }\n return true;\n }\n\n /**\n\t * Stop all animations for the chart\n\t * @param {Chart} chart\n\t */\n stop(chart) {\n const anims = this._charts.get(chart);\n if (!anims || !anims.items.length) {\n return;\n }\n const items = anims.items;\n let i = items.length - 1;\n\n for (; i >= 0; --i) {\n items[i].cancel();\n }\n anims.items = [];\n this._notify(chart, anims, Date.now(), 'complete');\n }\n\n /**\n\t * Remove chart from Animator\n\t * @param {Chart} chart\n\t */\n remove(chart) {\n return this._charts.delete(chart);\n }\n}\n\n// singleton instance\nexport default /* #__PURE__ */ new Animator();\n","/*!\n * @kurkle/color v0.3.2\n * https://github.com/kurkle/color#readme\n * (c) 2023 Jukka Kurkela\n * Released under the MIT License\n */\nfunction round(v) {\n return v + 0.5 | 0;\n}\nconst lim = (v, l, h) => Math.max(Math.min(v, h), l);\nfunction p2b(v) {\n return lim(round(v * 2.55), 0, 255);\n}\nfunction b2p(v) {\n return lim(round(v / 2.55), 0, 100);\n}\nfunction n2b(v) {\n return lim(round(v * 255), 0, 255);\n}\nfunction b2n(v) {\n return lim(round(v / 2.55) / 100, 0, 1);\n}\nfunction n2p(v) {\n return lim(round(v * 100), 0, 100);\n}\n\nconst map$1 = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, A: 10, B: 11, C: 12, D: 13, E: 14, F: 15, a: 10, b: 11, c: 12, d: 13, e: 14, f: 15};\nconst hex = [...'0123456789ABCDEF'];\nconst h1 = b => hex[b & 0xF];\nconst h2 = b => hex[(b & 0xF0) >> 4] + hex[b & 0xF];\nconst eq = b => ((b & 0xF0) >> 4) === (b & 0xF);\nconst isShort = v => eq(v.r) && eq(v.g) && eq(v.b) && eq(v.a);\nfunction hexParse(str) {\n var len = str.length;\n var ret;\n if (str[0] === '#') {\n if (len === 4 || len === 5) {\n ret = {\n r: 255 & map$1[str[1]] * 17,\n g: 255 & map$1[str[2]] * 17,\n b: 255 & map$1[str[3]] * 17,\n a: len === 5 ? map$1[str[4]] * 17 : 255\n };\n } else if (len === 7 || len === 9) {\n ret = {\n r: map$1[str[1]] << 4 | map$1[str[2]],\n g: map$1[str[3]] << 4 | map$1[str[4]],\n b: map$1[str[5]] << 4 | map$1[str[6]],\n a: len === 9 ? (map$1[str[7]] << 4 | map$1[str[8]]) : 255\n };\n }\n }\n return ret;\n}\nconst alpha = (a, f) => a < 255 ? f(a) : '';\nfunction hexString(v) {\n var f = isShort(v) ? h1 : h2;\n return v\n ? '#' + f(v.r) + f(v.g) + f(v.b) + alpha(v.a, f)\n : undefined;\n}\n\nconst HUE_RE = /^(hsla?|hwb|hsv)\\(\\s*([-+.e\\d]+)(?:deg)?[\\s,]+([-+.e\\d]+)%[\\s,]+([-+.e\\d]+)%(?:[\\s,]+([-+.e\\d]+)(%)?)?\\s*\\)$/;\nfunction hsl2rgbn(h, s, l) {\n const a = s * Math.min(l, 1 - l);\n const f = (n, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);\n return [f(0), f(8), f(4)];\n}\nfunction hsv2rgbn(h, s, v) {\n const f = (n, k = (n + h / 60) % 6) => v - v * s * Math.max(Math.min(k, 4 - k, 1), 0);\n return [f(5), f(3), f(1)];\n}\nfunction hwb2rgbn(h, w, b) {\n const rgb = hsl2rgbn(h, 1, 0.5);\n let i;\n if (w + b > 1) {\n i = 1 / (w + b);\n w *= i;\n b *= i;\n }\n for (i = 0; i < 3; i++) {\n rgb[i] *= 1 - w - b;\n rgb[i] += w;\n }\n return rgb;\n}\nfunction hueValue(r, g, b, d, max) {\n if (r === max) {\n return ((g - b) / d) + (g < b ? 6 : 0);\n }\n if (g === max) {\n return (b - r) / d + 2;\n }\n return (r - g) / d + 4;\n}\nfunction rgb2hsl(v) {\n const range = 255;\n const r = v.r / range;\n const g = v.g / range;\n const b = v.b / range;\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const l = (max + min) / 2;\n let h, s, d;\n if (max !== min) {\n d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n h = hueValue(r, g, b, d, max);\n h = h * 60 + 0.5;\n }\n return [h | 0, s || 0, l];\n}\nfunction calln(f, a, b, c) {\n return (\n Array.isArray(a)\n ? f(a[0], a[1], a[2])\n : f(a, b, c)\n ).map(n2b);\n}\nfunction hsl2rgb(h, s, l) {\n return calln(hsl2rgbn, h, s, l);\n}\nfunction hwb2rgb(h, w, b) {\n return calln(hwb2rgbn, h, w, b);\n}\nfunction hsv2rgb(h, s, v) {\n return calln(hsv2rgbn, h, s, v);\n}\nfunction hue(h) {\n return (h % 360 + 360) % 360;\n}\nfunction hueParse(str) {\n const m = HUE_RE.exec(str);\n let a = 255;\n let v;\n if (!m) {\n return;\n }\n if (m[5] !== v) {\n a = m[6] ? p2b(+m[5]) : n2b(+m[5]);\n }\n const h = hue(+m[2]);\n const p1 = +m[3] / 100;\n const p2 = +m[4] / 100;\n if (m[1] === 'hwb') {\n v = hwb2rgb(h, p1, p2);\n } else if (m[1] === 'hsv') {\n v = hsv2rgb(h, p1, p2);\n } else {\n v = hsl2rgb(h, p1, p2);\n }\n return {\n r: v[0],\n g: v[1],\n b: v[2],\n a: a\n };\n}\nfunction rotate(v, deg) {\n var h = rgb2hsl(v);\n h[0] = hue(h[0] + deg);\n h = hsl2rgb(h);\n v.r = h[0];\n v.g = h[1];\n v.b = h[2];\n}\nfunction hslString(v) {\n if (!v) {\n return;\n }\n const a = rgb2hsl(v);\n const h = a[0];\n const s = n2p(a[1]);\n const l = n2p(a[2]);\n return v.a < 255\n ? `hsla(${h}, ${s}%, ${l}%, ${b2n(v.a)})`\n : `hsl(${h}, ${s}%, ${l}%)`;\n}\n\nconst map = {\n x: 'dark',\n Z: 'light',\n Y: 're',\n X: 'blu',\n W: 'gr',\n V: 'medium',\n U: 'slate',\n A: 'ee',\n T: 'ol',\n S: 'or',\n B: 'ra',\n C: 'lateg',\n D: 'ights',\n R: 'in',\n Q: 'turquois',\n E: 'hi',\n P: 'ro',\n O: 'al',\n N: 'le',\n M: 'de',\n L: 'yello',\n F: 'en',\n K: 'ch',\n G: 'arks',\n H: 'ea',\n I: 'ightg',\n J: 'wh'\n};\nconst names$1 = {\n OiceXe: 'f0f8ff',\n antiquewEte: 'faebd7',\n aqua: 'ffff',\n aquamarRe: '7fffd4',\n azuY: 'f0ffff',\n beige: 'f5f5dc',\n bisque: 'ffe4c4',\n black: '0',\n blanKedOmond: 'ffebcd',\n Xe: 'ff',\n XeviTet: '8a2be2',\n bPwn: 'a52a2a',\n burlywood: 'deb887',\n caMtXe: '5f9ea0',\n KartYuse: '7fff00',\n KocTate: 'd2691e',\n cSO: 'ff7f50',\n cSnflowerXe: '6495ed',\n cSnsilk: 'fff8dc',\n crimson: 'dc143c',\n cyan: 'ffff',\n xXe: '8b',\n xcyan: '8b8b',\n xgTMnPd: 'b8860b',\n xWay: 'a9a9a9',\n xgYF: '6400',\n xgYy: 'a9a9a9',\n xkhaki: 'bdb76b',\n xmagFta: '8b008b',\n xTivegYF: '556b2f',\n xSange: 'ff8c00',\n xScEd: '9932cc',\n xYd: '8b0000',\n xsOmon: 'e9967a',\n xsHgYF: '8fbc8f',\n xUXe: '483d8b',\n xUWay: '2f4f4f',\n xUgYy: '2f4f4f',\n xQe: 'ced1',\n xviTet: '9400d3',\n dAppRk: 'ff1493',\n dApskyXe: 'bfff',\n dimWay: '696969',\n dimgYy: '696969',\n dodgerXe: '1e90ff',\n fiYbrick: 'b22222',\n flSOwEte: 'fffaf0',\n foYstWAn: '228b22',\n fuKsia: 'ff00ff',\n gaRsbSo: 'dcdcdc',\n ghostwEte: 'f8f8ff',\n gTd: 'ffd700',\n gTMnPd: 'daa520',\n Way: '808080',\n gYF: '8000',\n gYFLw: 'adff2f',\n gYy: '808080',\n honeyMw: 'f0fff0',\n hotpRk: 'ff69b4',\n RdianYd: 'cd5c5c',\n Rdigo: '4b0082',\n ivSy: 'fffff0',\n khaki: 'f0e68c',\n lavFMr: 'e6e6fa',\n lavFMrXsh: 'fff0f5',\n lawngYF: '7cfc00',\n NmoncEffon: 'fffacd',\n ZXe: 'add8e6',\n ZcSO: 'f08080',\n Zcyan: 'e0ffff',\n ZgTMnPdLw: 'fafad2',\n ZWay: 'd3d3d3',\n ZgYF: '90ee90',\n ZgYy: 'd3d3d3',\n ZpRk: 'ffb6c1',\n ZsOmon: 'ffa07a',\n ZsHgYF: '20b2aa',\n ZskyXe: '87cefa',\n ZUWay: '778899',\n ZUgYy: '778899',\n ZstAlXe: 'b0c4de',\n ZLw: 'ffffe0',\n lime: 'ff00',\n limegYF: '32cd32',\n lRF: 'faf0e6',\n magFta: 'ff00ff',\n maPon: '800000',\n VaquamarRe: '66cdaa',\n VXe: 'cd',\n VScEd: 'ba55d3',\n VpurpN: '9370db',\n VsHgYF: '3cb371',\n VUXe: '7b68ee',\n VsprRggYF: 'fa9a',\n VQe: '48d1cc',\n VviTetYd: 'c71585',\n midnightXe: '191970',\n mRtcYam: 'f5fffa',\n mistyPse: 'ffe4e1',\n moccasR: 'ffe4b5',\n navajowEte: 'ffdead',\n navy: '80',\n Tdlace: 'fdf5e6',\n Tive: '808000',\n TivedBb: '6b8e23',\n Sange: 'ffa500',\n SangeYd: 'ff4500',\n ScEd: 'da70d6',\n pOegTMnPd: 'eee8aa',\n pOegYF: '98fb98',\n pOeQe: 'afeeee',\n pOeviTetYd: 'db7093',\n papayawEp: 'ffefd5',\n pHKpuff: 'ffdab9',\n peru: 'cd853f',\n pRk: 'ffc0cb',\n plum: 'dda0dd',\n powMrXe: 'b0e0e6',\n purpN: '800080',\n YbeccapurpN: '663399',\n Yd: 'ff0000',\n Psybrown: 'bc8f8f',\n PyOXe: '4169e1',\n saddNbPwn: '8b4513',\n sOmon: 'fa8072',\n sandybPwn: 'f4a460',\n sHgYF: '2e8b57',\n sHshell: 'fff5ee',\n siFna: 'a0522d',\n silver: 'c0c0c0',\n skyXe: '87ceeb',\n UXe: '6a5acd',\n UWay: '708090',\n UgYy: '708090',\n snow: 'fffafa',\n sprRggYF: 'ff7f',\n stAlXe: '4682b4',\n tan: 'd2b48c',\n teO: '8080',\n tEstN: 'd8bfd8',\n tomato: 'ff6347',\n Qe: '40e0d0',\n viTet: 'ee82ee',\n JHt: 'f5deb3',\n wEte: 'ffffff',\n wEtesmoke: 'f5f5f5',\n Lw: 'ffff00',\n LwgYF: '9acd32'\n};\nfunction unpack() {\n const unpacked = {};\n const keys = Object.keys(names$1);\n const tkeys = Object.keys(map);\n let i, j, k, ok, nk;\n for (i = 0; i < keys.length; i++) {\n ok = nk = keys[i];\n for (j = 0; j < tkeys.length; j++) {\n k = tkeys[j];\n nk = nk.replace(k, map[k]);\n }\n k = parseInt(names$1[ok], 16);\n unpacked[nk] = [k >> 16 & 0xFF, k >> 8 & 0xFF, k & 0xFF];\n }\n return unpacked;\n}\n\nlet names;\nfunction nameParse(str) {\n if (!names) {\n names = unpack();\n names.transparent = [0, 0, 0, 0];\n }\n const a = names[str.toLowerCase()];\n return a && {\n r: a[0],\n g: a[1],\n b: a[2],\n a: a.length === 4 ? a[3] : 255\n };\n}\n\nconst RGB_RE = /^rgba?\\(\\s*([-+.\\d]+)(%)?[\\s,]+([-+.e\\d]+)(%)?[\\s,]+([-+.e\\d]+)(%)?(?:[\\s,/]+([-+.e\\d]+)(%)?)?\\s*\\)$/;\nfunction rgbParse(str) {\n const m = RGB_RE.exec(str);\n let a = 255;\n let r, g, b;\n if (!m) {\n return;\n }\n if (m[7] !== r) {\n const v = +m[7];\n a = m[8] ? p2b(v) : lim(v * 255, 0, 255);\n }\n r = +m[1];\n g = +m[3];\n b = +m[5];\n r = 255 & (m[2] ? p2b(r) : lim(r, 0, 255));\n g = 255 & (m[4] ? p2b(g) : lim(g, 0, 255));\n b = 255 & (m[6] ? p2b(b) : lim(b, 0, 255));\n return {\n r: r,\n g: g,\n b: b,\n a: a\n };\n}\nfunction rgbString(v) {\n return v && (\n v.a < 255\n ? `rgba(${v.r}, ${v.g}, ${v.b}, ${b2n(v.a)})`\n : `rgb(${v.r}, ${v.g}, ${v.b})`\n );\n}\n\nconst to = v => v <= 0.0031308 ? v * 12.92 : Math.pow(v, 1.0 / 2.4) * 1.055 - 0.055;\nconst from = v => v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);\nfunction interpolate(rgb1, rgb2, t) {\n const r = from(b2n(rgb1.r));\n const g = from(b2n(rgb1.g));\n const b = from(b2n(rgb1.b));\n return {\n r: n2b(to(r + t * (from(b2n(rgb2.r)) - r))),\n g: n2b(to(g + t * (from(b2n(rgb2.g)) - g))),\n b: n2b(to(b + t * (from(b2n(rgb2.b)) - b))),\n a: rgb1.a + t * (rgb2.a - rgb1.a)\n };\n}\n\nfunction modHSL(v, i, ratio) {\n if (v) {\n let tmp = rgb2hsl(v);\n tmp[i] = Math.max(0, Math.min(tmp[i] + tmp[i] * ratio, i === 0 ? 360 : 1));\n tmp = hsl2rgb(tmp);\n v.r = tmp[0];\n v.g = tmp[1];\n v.b = tmp[2];\n }\n}\nfunction clone(v, proto) {\n return v ? Object.assign(proto || {}, v) : v;\n}\nfunction fromObject(input) {\n var v = {r: 0, g: 0, b: 0, a: 255};\n if (Array.isArray(input)) {\n if (input.length >= 3) {\n v = {r: input[0], g: input[1], b: input[2], a: 255};\n if (input.length > 3) {\n v.a = n2b(input[3]);\n }\n }\n } else {\n v = clone(input, {r: 0, g: 0, b: 0, a: 1});\n v.a = n2b(v.a);\n }\n return v;\n}\nfunction functionParse(str) {\n if (str.charAt(0) === 'r') {\n return rgbParse(str);\n }\n return hueParse(str);\n}\nclass Color {\n constructor(input) {\n if (input instanceof Color) {\n return input;\n }\n const type = typeof input;\n let v;\n if (type === 'object') {\n v = fromObject(input);\n } else if (type === 'string') {\n v = hexParse(input) || nameParse(input) || functionParse(input);\n }\n this._rgb = v;\n this._valid = !!v;\n }\n get valid() {\n return this._valid;\n }\n get rgb() {\n var v = clone(this._rgb);\n if (v) {\n v.a = b2n(v.a);\n }\n return v;\n }\n set rgb(obj) {\n this._rgb = fromObject(obj);\n }\n rgbString() {\n return this._valid ? rgbString(this._rgb) : undefined;\n }\n hexString() {\n return this._valid ? hexString(this._rgb) : undefined;\n }\n hslString() {\n return this._valid ? hslString(this._rgb) : undefined;\n }\n mix(color, weight) {\n if (color) {\n const c1 = this.rgb;\n const c2 = color.rgb;\n let w2;\n const p = weight === w2 ? 0.5 : weight;\n const w = 2 * p - 1;\n const a = c1.a - c2.a;\n const w1 = ((w * a === -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0;\n w2 = 1 - w1;\n c1.r = 0xFF & w1 * c1.r + w2 * c2.r + 0.5;\n c1.g = 0xFF & w1 * c1.g + w2 * c2.g + 0.5;\n c1.b = 0xFF & w1 * c1.b + w2 * c2.b + 0.5;\n c1.a = p * c1.a + (1 - p) * c2.a;\n this.rgb = c1;\n }\n return this;\n }\n interpolate(color, t) {\n if (color) {\n this._rgb = interpolate(this._rgb, color._rgb, t);\n }\n return this;\n }\n clone() {\n return new Color(this.rgb);\n }\n alpha(a) {\n this._rgb.a = n2b(a);\n return this;\n }\n clearer(ratio) {\n const rgb = this._rgb;\n rgb.a *= 1 - ratio;\n return this;\n }\n greyscale() {\n const rgb = this._rgb;\n const val = round(rgb.r * 0.3 + rgb.g * 0.59 + rgb.b * 0.11);\n rgb.r = rgb.g = rgb.b = val;\n return this;\n }\n opaquer(ratio) {\n const rgb = this._rgb;\n rgb.a *= 1 + ratio;\n return this;\n }\n negate() {\n const v = this._rgb;\n v.r = 255 - v.r;\n v.g = 255 - v.g;\n v.b = 255 - v.b;\n return this;\n }\n lighten(ratio) {\n modHSL(this._rgb, 2, ratio);\n return this;\n }\n darken(ratio) {\n modHSL(this._rgb, 2, -ratio);\n return this;\n }\n saturate(ratio) {\n modHSL(this._rgb, 1, ratio);\n return this;\n }\n desaturate(ratio) {\n modHSL(this._rgb, 1, -ratio);\n return this;\n }\n rotate(deg) {\n rotate(this._rgb, deg);\n return this;\n }\n}\n\nfunction index_esm(input) {\n return new Color(input);\n}\n\nexport { Color, b2n, b2p, index_esm as default, hexParse, hexString, hsl2rgb, hslString, hsv2rgb, hueParse, hwb2rgb, lim, n2b, n2p, nameParse, p2b, rgb2hsl, rgbParse, rgbString, rotate, round };\n","import {Color} from '@kurkle/color';\n\nexport function isPatternOrGradient(value: unknown): value is CanvasPattern | CanvasGradient {\n if (value && typeof value === 'object') {\n const type = value.toString();\n return type === '[object CanvasPattern]' || type === '[object CanvasGradient]';\n }\n\n return false;\n}\n\nexport function color(value: CanvasGradient): CanvasGradient;\nexport function color(value: CanvasPattern): CanvasPattern;\nexport function color(\n value:\n | string\n | { r: number; g: number; b: number; a: number }\n | [number, number, number]\n | [number, number, number, number]\n): Color;\nexport function color(value) {\n return isPatternOrGradient(value) ? value : new Color(value);\n}\n\nexport function getHoverColor(value: CanvasGradient): CanvasGradient;\nexport function getHoverColor(value: CanvasPattern): CanvasPattern;\nexport function getHoverColor(value: string): string;\nexport function getHoverColor(value) {\n return isPatternOrGradient(value)\n ? value\n : new Color(value).saturate(0.5).darken(0.1).hexString();\n}\n","const numbers = ['x', 'y', 'borderWidth', 'radius', 'tension'];\nconst colors = ['color', 'borderColor', 'backgroundColor'];\n\nexport function applyAnimationsDefaults(defaults) {\n defaults.set('animation', {\n delay: undefined,\n duration: 1000,\n easing: 'easeOutQuart',\n fn: undefined,\n from: undefined,\n loop: undefined,\n to: undefined,\n type: undefined,\n });\n\n defaults.describe('animation', {\n _fallback: false,\n _indexable: false,\n _scriptable: (name) => name !== 'onProgress' && name !== 'onComplete' && name !== 'fn',\n });\n\n defaults.set('animations', {\n colors: {\n type: 'color',\n properties: colors\n },\n numbers: {\n type: 'number',\n properties: numbers\n },\n });\n\n defaults.describe('animations', {\n _fallback: 'animation',\n });\n\n defaults.set('transitions', {\n active: {\n animation: {\n duration: 400\n }\n },\n resize: {\n animation: {\n duration: 0\n }\n },\n show: {\n animations: {\n colors: {\n from: 'transparent'\n },\n visible: {\n type: 'boolean',\n duration: 0 // show immediately\n },\n }\n },\n hide: {\n animations: {\n colors: {\n to: 'transparent'\n },\n visible: {\n type: 'boolean',\n easing: 'linear',\n fn: v => v | 0 // for keeping the dataset visible all the way through the animation\n },\n }\n }\n });\n}\n","\nconst intlCache = new Map();\n\nfunction getNumberFormat(locale: string, options?: Intl.NumberFormatOptions) {\n options = options || {};\n const cacheKey = locale + JSON.stringify(options);\n let formatter = intlCache.get(cacheKey);\n if (!formatter) {\n formatter = new Intl.NumberFormat(locale, options);\n intlCache.set(cacheKey, formatter);\n }\n return formatter;\n}\n\nexport function formatNumber(num: number, locale: string, options?: Intl.NumberFormatOptions) {\n return getNumberFormat(locale, options).format(num);\n}\n","import {isArray} from '../helpers/helpers.core.js';\nimport {formatNumber} from '../helpers/helpers.intl.js';\nimport {log10} from '../helpers/helpers.math.js';\n\n/**\n * Namespace to hold formatters for different types of ticks\n * @namespace Chart.Ticks.formatters\n */\nconst formatters = {\n /**\n * Formatter for value labels\n * @method Chart.Ticks.formatters.values\n * @param value the value to display\n * @return {string|string[]} the label to display\n */\n values(value) {\n return isArray(value) ? /** @type {string[]} */ (value) : '' + value;\n },\n\n /**\n * Formatter for numeric ticks\n * @method Chart.Ticks.formatters.numeric\n * @param tickValue {number} the value to be formatted\n * @param index {number} the position of the tickValue parameter in the ticks array\n * @param ticks {object[]} the list of ticks being converted\n * @return {string} string representation of the tickValue parameter\n */\n numeric(tickValue, index, ticks) {\n if (tickValue === 0) {\n return '0'; // never show decimal places for 0\n }\n\n const locale = this.chart.options.locale;\n let notation;\n let delta = tickValue; // This is used when there are less than 2 ticks as the tick interval.\n\n if (ticks.length > 1) {\n // all ticks are small or there huge numbers; use scientific notation\n const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value));\n if (maxTick < 1e-4 || maxTick > 1e+15) {\n notation = 'scientific';\n }\n\n delta = calculateDelta(tickValue, ticks);\n }\n\n const logDelta = log10(Math.abs(delta));\n\n // When datasets have values approaching Number.MAX_VALUE, the tick calculations might result in\n // infinity and eventually NaN. Passing NaN for minimumFractionDigits or maximumFractionDigits\n // will make the number formatter throw. So instead we check for isNaN and use a fallback value.\n //\n // toFixed has a max of 20 decimal places\n const numDecimal = isNaN(logDelta) ? 1 : Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0);\n\n const options = {notation, minimumFractionDigits: numDecimal, maximumFractionDigits: numDecimal};\n Object.assign(options, this.options.ticks.format);\n\n return formatNumber(tickValue, locale, options);\n },\n\n\n /**\n * Formatter for logarithmic ticks\n * @method Chart.Ticks.formatters.logarithmic\n * @param tickValue {number} the value to be formatted\n * @param index {number} the position of the tickValue parameter in the ticks array\n * @param ticks {object[]} the list of ticks being converted\n * @return {string} string representation of the tickValue parameter\n */\n logarithmic(tickValue, index, ticks) {\n if (tickValue === 0) {\n return '0';\n }\n const remain = ticks[index].significand || (tickValue / (Math.pow(10, Math.floor(log10(tickValue)))));\n if ([1, 2, 3, 5, 10, 15].includes(remain) || index > 0.8 * ticks.length) {\n return formatters.numeric.call(this, tickValue, index, ticks);\n }\n return '';\n }\n\n};\n\n\nfunction calculateDelta(tickValue, ticks) {\n // Figure out how many digits to show\n // The space between the first two ticks might be smaller than normal spacing\n let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value;\n\n // If we have a number like 2.5 as the delta, figure out how many decimal places we need\n if (Math.abs(delta) >= 1 && tickValue !== Math.floor(tickValue)) {\n // not an integer\n delta = tickValue - Math.floor(tickValue);\n }\n return delta;\n}\n\n/**\n * Namespace to hold static tick generation functions\n * @namespace Chart.Ticks\n */\nexport default {formatters};\n","import {getHoverColor} from '../helpers/helpers.color.js';\nimport {isObject, merge, valueOrDefault} from '../helpers/helpers.core.js';\nimport {applyAnimationsDefaults} from './core.animations.defaults.js';\nimport {applyLayoutsDefaults} from './core.layouts.defaults.js';\nimport {applyScaleDefaults} from './core.scale.defaults.js';\n\nexport const overrides = Object.create(null);\nexport const descriptors = Object.create(null);\n\n/**\n * @param {object} node\n * @param {string} key\n * @return {object}\n */\nfunction getScope(node, key) {\n if (!key) {\n return node;\n }\n const keys = key.split('.');\n for (let i = 0, n = keys.length; i < n; ++i) {\n const k = keys[i];\n node = node[k] || (node[k] = Object.create(null));\n }\n return node;\n}\n\nfunction set(root, scope, values) {\n if (typeof scope === 'string') {\n return merge(getScope(root, scope), values);\n }\n return merge(getScope(root, ''), scope);\n}\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 Defaults {\n constructor(_descriptors, _appliers) {\n this.animation = undefined;\n this.backgroundColor = 'rgba(0,0,0,0.1)';\n this.borderColor = 'rgba(0,0,0,0.1)';\n this.color = '#666';\n this.datasets = {};\n this.devicePixelRatio = (context) => context.chart.platform.getDevicePixelRatio();\n this.elements = {};\n this.events = [\n 'mousemove',\n 'mouseout',\n 'click',\n 'touchstart',\n 'touchmove'\n ];\n this.font = {\n family: \"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif\",\n size: 12,\n style: 'normal',\n lineHeight: 1.2,\n weight: null\n };\n this.hover = {};\n this.hoverBackgroundColor = (ctx, options) => getHoverColor(options.backgroundColor);\n this.hoverBorderColor = (ctx, options) => getHoverColor(options.borderColor);\n this.hoverColor = (ctx, options) => getHoverColor(options.color);\n this.indexAxis = 'x';\n this.interaction = {\n mode: 'nearest',\n intersect: true,\n includeInvisible: false\n };\n this.maintainAspectRatio = true;\n this.onHover = null;\n this.onClick = null;\n this.parsing = true;\n this.plugins = {};\n this.responsive = true;\n this.scale = undefined;\n this.scales = {};\n this.showLine = true;\n this.drawActiveElementsOnTop = true;\n\n this.describe(_descriptors);\n this.apply(_appliers);\n }\n\n /**\n\t * @param {string|object} scope\n\t * @param {object} [values]\n\t */\n set(scope, values) {\n return set(this, scope, values);\n }\n\n /**\n\t * @param {string} scope\n\t */\n get(scope) {\n return getScope(this, scope);\n }\n\n /**\n\t * @param {string|object} scope\n\t * @param {object} [values]\n\t */\n describe(scope, values) {\n return set(descriptors, scope, values);\n }\n\n override(scope, values) {\n return set(overrides, scope, values);\n }\n\n /**\n\t * Routes the named defaults to fallback to another scope/name.\n\t * This routing is useful when those target values, like defaults.color, are changed runtime.\n\t * If the values would be copied, the runtime change would not take effect. By routing, the\n\t * fallback is evaluated at each access, so its always up to date.\n\t *\n\t * Example:\n\t *\n\t * \tdefaults.route('elements.arc', 'backgroundColor', '', 'color')\n\t * - reads the backgroundColor from defaults.color when undefined locally\n\t *\n\t * @param {string} scope Scope this route applies to.\n\t * @param {string} name Property name that should be routed to different namespace when not defined here.\n\t * @param {string} targetScope The namespace where those properties should be routed to.\n\t * Empty string ('') is the root of defaults.\n\t * @param {string} targetName The target name in the target scope the property should be routed to.\n\t */\n route(scope, name, targetScope, targetName) {\n const scopeObject = getScope(this, scope);\n const targetScopeObject = getScope(this, targetScope);\n const privateName = '_' + name;\n\n Object.defineProperties(scopeObject, {\n // A private property is defined to hold the actual value, when this property is set in its scope (set in the setter)\n [privateName]: {\n value: scopeObject[name],\n writable: true\n },\n // The actual property is defined as getter/setter so we can do the routing when value is not locally set.\n [name]: {\n enumerable: true,\n get() {\n const local = this[privateName];\n const target = targetScopeObject[targetName];\n if (isObject(local)) {\n return Object.assign({}, target, local);\n }\n return valueOrDefault(local, target);\n },\n set(value) {\n this[privateName] = value;\n }\n }\n });\n }\n\n apply(appliers) {\n appliers.forEach((apply) => apply(this));\n }\n}\n\n// singleton instance\nexport default /* #__PURE__ */ new Defaults({\n _scriptable: (name) => !name.startsWith('on'),\n _indexable: (name) => name !== 'events',\n hover: {\n _fallback: 'interaction'\n },\n interaction: {\n _scriptable: false,\n _indexable: false,\n }\n}, [applyAnimationsDefaults, applyLayoutsDefaults, applyScaleDefaults]);\n","export function applyLayoutsDefaults(defaults) {\n defaults.set('layout', {\n autoPadding: true,\n padding: {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0\n }\n });\n}\n","import Ticks from './core.ticks.js';\n\nexport function applyScaleDefaults(defaults) {\n defaults.set('scale', {\n display: true,\n offset: false,\n reverse: false,\n beginAtZero: false,\n\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 3.0.0\n */\n bounds: 'ticks',\n\n clip: true,\n\n /**\n * Addition grace added to max and reduced from min data value.\n * @since 3.0.0\n */\n grace: 0,\n\n // grid line settings\n grid: {\n display: true,\n lineWidth: 1,\n drawOnChartArea: true,\n drawTicks: true,\n tickLength: 8,\n tickWidth: (_ctx, options) => options.lineWidth,\n tickColor: (_ctx, options) => options.color,\n offset: false,\n },\n\n border: {\n display: true,\n dash: [],\n dashOffset: 0.0,\n width: 1\n },\n\n // scale title\n title: {\n // display property\n display: false,\n\n // actual label\n text: '',\n\n // top/bottom padding\n padding: {\n top: 4,\n bottom: 4\n }\n },\n\n // label settings\n ticks: {\n minRotation: 0,\n maxRotation: 50,\n mirror: false,\n textStrokeWidth: 0,\n textStrokeColor: '',\n padding: 3,\n display: true,\n autoSkip: true,\n autoSkipPadding: 3,\n labelOffset: 0,\n // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.\n callback: Ticks.formatters.values,\n minor: {},\n major: {},\n align: 'center',\n crossAlign: 'near',\n\n showLabelBackdrop: false,\n backdropColor: 'rgba(255, 255, 255, 0.75)',\n backdropPadding: 2,\n }\n });\n\n defaults.route('scale.ticks', 'color', '', 'color');\n defaults.route('scale.grid', 'color', '', 'borderColor');\n defaults.route('scale.border', 'color', '', 'borderColor');\n defaults.route('scale.title', 'color', '', 'color');\n\n defaults.describe('scale', {\n _fallback: false,\n _scriptable: (name) => !name.startsWith('before') && !name.startsWith('after') && name !== 'callback' && name !== 'parser',\n _indexable: (name) => name !== 'borderDash' && name !== 'tickBorderDash' && name !== 'dash',\n });\n\n defaults.describe('scales', {\n _fallback: 'scale',\n });\n\n defaults.describe('scale.ticks', {\n _scriptable: (name) => name !== 'backdropPadding' && name !== 'callback',\n _indexable: (name) => name !== 'backdropPadding',\n });\n}\n","import type {ChartArea, Scale} from '../types/index.js';\nimport type PrivateChart from '../core/core.controller.js';\nimport type {Chart, ChartEvent} from '../types.js';\nimport {INFINITY} from './helpers.math.js';\n\n/**\n * @private\n */\nexport function _isDomSupported(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\n/**\n * @private\n */\nexport function _getParentNode(domNode: HTMLCanvasElement): HTMLCanvasElement {\n let parent = domNode.parentNode;\n if (parent && parent.toString() === '[object ShadowRoot]') {\n parent = (parent as ShadowRoot).host;\n }\n return parent as HTMLCanvasElement;\n}\n\n/**\n * convert max-width/max-height values that may be percentages into a number\n * @private\n */\n\nfunction parseMaxStyle(styleValue: string | number, node: HTMLElement, parentProperty: string) {\n let valueInPixels: number;\n if (typeof styleValue === 'string') {\n valueInPixels = parseInt(styleValue, 10);\n\n if (styleValue.indexOf('%') !== -1) {\n // percentage * size in dimension\n valueInPixels = (valueInPixels / 100) * node.parentNode[parentProperty];\n }\n } else {\n valueInPixels = styleValue;\n }\n\n return valueInPixels;\n}\n\nconst getComputedStyle = (element: HTMLElement): CSSStyleDeclaration =>\n element.ownerDocument.defaultView.getComputedStyle(element, null);\n\nexport function getStyle(el: HTMLElement, property: string): string {\n return getComputedStyle(el).getPropertyValue(property);\n}\n\nconst positions = ['top', 'right', 'bottom', 'left'];\nfunction getPositionedStyle(styles: CSSStyleDeclaration, style: string, suffix?: string): ChartArea {\n const result = {} as ChartArea;\n suffix = suffix ? '-' + suffix : '';\n for (let i = 0; i < 4; i++) {\n const pos = positions[i];\n result[pos] = parseFloat(styles[style + '-' + pos + suffix]) || 0;\n }\n result.width = result.left + result.right;\n result.height = result.top + result.bottom;\n return result;\n}\n\nconst useOffsetPos = (x: number, y: number, target: HTMLElement | EventTarget) =>\n (x > 0 || y > 0) && (!target || !(target as HTMLElement).shadowRoot);\n\n/**\n * @param e\n * @param canvas\n * @returns Canvas position\n */\nfunction getCanvasPosition(\n e: Event | TouchEvent | MouseEvent,\n canvas: HTMLCanvasElement\n): {\n x: number;\n y: number;\n box: boolean;\n } {\n const touches = (e as TouchEvent).touches;\n const source = (touches && touches.length ? touches[0] : e) as MouseEvent;\n const {offsetX, offsetY} = source as MouseEvent;\n let box = false;\n let x, y;\n if (useOffsetPos(offsetX, offsetY, e.target)) {\n x = offsetX;\n y = offsetY;\n } else {\n const rect = canvas.getBoundingClientRect();\n x = source.clientX - rect.left;\n y = source.clientY - rect.top;\n box = true;\n }\n return {x, y, box};\n}\n\n/**\n * Gets an event's x, y coordinates, relative to the chart area\n * @param event\n * @param chart\n * @returns x and y coordinates of the event\n */\n\nexport function getRelativePosition(\n event: Event | ChartEvent | TouchEvent | MouseEvent,\n chart: Chart | PrivateChart\n): { x: number; y: number } {\n if ('native' in event) {\n return event;\n }\n\n const {canvas, currentDevicePixelRatio} = chart;\n const style = getComputedStyle(canvas);\n const borderBox = style.boxSizing === 'border-box';\n const paddings = getPositionedStyle(style, 'padding');\n const borders = getPositionedStyle(style, 'border', 'width');\n const {x, y, box} = getCanvasPosition(event, canvas);\n const xOffset = paddings.left + (box && borders.left);\n const yOffset = paddings.top + (box && borders.top);\n\n let {width, height} = chart;\n if (borderBox) {\n width -= paddings.width + borders.width;\n height -= paddings.height + borders.height;\n }\n return {\n x: Math.round((x - xOffset) / width * canvas.width / currentDevicePixelRatio),\n y: Math.round((y - yOffset) / height * canvas.height / currentDevicePixelRatio)\n };\n}\n\nfunction getContainerSize(canvas: HTMLCanvasElement, width: number, height: number): Partial {\n let maxWidth: number, maxHeight: number;\n\n if (width === undefined || height === undefined) {\n const container = canvas && _getParentNode(canvas);\n if (!container) {\n width = canvas.clientWidth;\n height = canvas.clientHeight;\n } else {\n const rect = container.getBoundingClientRect(); // this is the border box of the container\n const containerStyle = getComputedStyle(container);\n const containerBorder = getPositionedStyle(containerStyle, 'border', 'width');\n const containerPadding = getPositionedStyle(containerStyle, 'padding');\n width = rect.width - containerPadding.width - containerBorder.width;\n height = rect.height - containerPadding.height - containerBorder.height;\n maxWidth = parseMaxStyle(containerStyle.maxWidth, container, 'clientWidth');\n maxHeight = parseMaxStyle(containerStyle.maxHeight, container, 'clientHeight');\n }\n }\n return {\n width,\n height,\n maxWidth: maxWidth || INFINITY,\n maxHeight: maxHeight || INFINITY\n };\n}\n\nconst round1 = (v: number) => Math.round(v * 10) / 10;\n\n// eslint-disable-next-line complexity\nexport function getMaximumSize(\n canvas: HTMLCanvasElement,\n bbWidth?: number,\n bbHeight?: number,\n aspectRatio?: number\n): { width: number; height: number } {\n const style = getComputedStyle(canvas);\n const margins = getPositionedStyle(style, 'margin');\n const maxWidth = parseMaxStyle(style.maxWidth, canvas, 'clientWidth') || INFINITY;\n const maxHeight = parseMaxStyle(style.maxHeight, canvas, 'clientHeight') || INFINITY;\n const containerSize = getContainerSize(canvas, bbWidth, bbHeight);\n let {width, height} = containerSize;\n\n if (style.boxSizing === 'content-box') {\n const borders = getPositionedStyle(style, 'border', 'width');\n const paddings = getPositionedStyle(style, 'padding');\n width -= paddings.width + borders.width;\n height -= paddings.height + borders.height;\n }\n width = Math.max(0, width - margins.width);\n height = Math.max(0, aspectRatio ? width / aspectRatio : height - margins.height);\n width = round1(Math.min(width, maxWidth, containerSize.maxWidth));\n height = round1(Math.min(height, maxHeight, containerSize.maxHeight));\n if (width && !height) {\n // https://github.com/chartjs/Chart.js/issues/4659\n // If the canvas has width, but no height, default to aspectRatio of 2 (canvas default)\n height = round1(width / 2);\n }\n\n const maintainHeight = bbWidth !== undefined || bbHeight !== undefined;\n\n if (maintainHeight && aspectRatio && containerSize.height && height > containerSize.height) {\n height = containerSize.height;\n width = round1(Math.floor(height * aspectRatio));\n }\n\n return {width, height};\n}\n\n/**\n * @param chart\n * @param forceRatio\n * @param forceStyle\n * @returns True if the canvas context size or transformation has changed.\n */\nexport function retinaScale(\n chart: Chart | PrivateChart,\n forceRatio: number,\n forceStyle?: boolean\n): boolean | void {\n const pixelRatio = forceRatio || 1;\n const deviceHeight = Math.floor(chart.height * pixelRatio);\n const deviceWidth = Math.floor(chart.width * pixelRatio);\n\n (chart as PrivateChart).height = Math.floor(chart.height);\n (chart as PrivateChart).width = Math.floor(chart.width);\n\n const canvas = chart.canvas;\n\n // If no style has been set on the canvas, the render size is used as display size,\n // making the chart visually bigger, so let's enforce it to the \"correct\" values.\n // See https://github.com/chartjs/Chart.js/issues/3575\n if (canvas.style && (forceStyle || (!canvas.style.height && !canvas.style.width))) {\n canvas.style.height = `${chart.height}px`;\n canvas.style.width = `${chart.width}px`;\n }\n\n if (chart.currentDevicePixelRatio !== pixelRatio\n || canvas.height !== deviceHeight\n || canvas.width !== deviceWidth) {\n (chart as PrivateChart).currentDevicePixelRatio = pixelRatio;\n canvas.height = deviceHeight;\n canvas.width = deviceWidth;\n chart.ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);\n return true;\n }\n return false;\n}\n\n/**\n * Detects support for options object argument in addEventListener.\n * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support\n * @private\n */\nexport const supportsEventListenerOptions = (function() {\n let passiveSupported = false;\n try {\n const options = {\n get passive() { // This function will be called when the browser attempts to access the passive property.\n passiveSupported = true;\n return false;\n }\n } as EventListenerOptions;\n\n if (_isDomSupported()) {\n window.addEventListener('test', null, options);\n window.removeEventListener('test', null, options);\n }\n } catch (e) {\n // continue regardless of error\n }\n return passiveSupported;\n}());\n\n/**\n * The \"used\" size is the final value of a dimension property after all calculations have\n * been performed. This method uses the computed style of `element` but returns undefined\n * if the computed style is not expressed in pixels. That can happen in some cases where\n * `element` has a size relative to its parent and this last one is not yet displayed,\n * for example because of `display: none` on a parent node.\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value\n * @returns Size in pixels or undefined if unknown.\n */\n\nexport function readUsedSize(\n element: HTMLElement,\n property: 'width' | 'height'\n): number | undefined {\n const value = getStyle(element, property);\n const matches = value && value.match(/^(\\d+)(\\.\\d+)?px$/);\n return matches ? +matches[1] : undefined;\n}\n","import type {\n Chart,\n Point,\n FontSpec,\n CanvasFontSpec,\n PointStyle,\n RenderTextOpts,\n BackdropOptions\n} from '../types/index.js';\nimport type {\n TRBL,\n SplinePoint,\n RoundedRect,\n TRBLCorners\n} from '../types/geometric.js';\nimport {isArray, isNullOrUndef} from './helpers.core.js';\nimport {PI, TAU, HALF_PI, QUARTER_PI, TWO_THIRDS_PI, RAD_PER_DEG} from './helpers.math.js';\n\n/**\n * Converts the given font object into a CSS font string.\n * @param font - A font object.\n * @return The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font\n * @private\n */\nexport function toFontString(font: FontSpec) {\n if (!font || isNullOrUndef(font.size) || isNullOrUndef(font.family)) {\n return null;\n }\n\n return (font.style ? font.style + ' ' : '')\n\t\t+ (font.weight ? font.weight + ' ' : '')\n\t\t+ font.size + 'px '\n\t\t+ font.family;\n}\n\n/**\n * @private\n */\nexport function _measureText(\n ctx: CanvasRenderingContext2D,\n data: Record,\n gc: string[],\n longest: number,\n string: string\n) {\n let textWidth = data[string];\n if (!textWidth) {\n textWidth = data[string] = ctx.measureText(string).width;\n gc.push(string);\n }\n if (textWidth > longest) {\n longest = textWidth;\n }\n return longest;\n}\n\ntype Thing = string | undefined | null\ntype Things = (Thing | Thing[])[]\n\n/**\n * @private\n */\n// eslint-disable-next-line complexity\nexport function _longestText(\n ctx: CanvasRenderingContext2D,\n font: string,\n arrayOfThings: Things,\n cache?: {data?: Record, garbageCollect?: string[], font?: string}\n) {\n cache = cache || {};\n let data = cache.data = cache.data || {};\n let gc = cache.garbageCollect = cache.garbageCollect || [];\n\n if (cache.font !== font) {\n data = cache.data = {};\n gc = cache.garbageCollect = [];\n cache.font = font;\n }\n\n ctx.save();\n\n ctx.font = font;\n let longest = 0;\n const ilen = arrayOfThings.length;\n let i: number, j: number, jlen: number, thing: Thing | Thing[], nestedThing: Thing | Thing[];\n for (i = 0; i < ilen; i++) {\n thing = arrayOfThings[i];\n\n // Undefined strings and arrays should not be measured\n if (thing !== undefined && thing !== null && !isArray(thing)) {\n longest = _measureText(ctx, data, gc, longest, thing);\n } else if (isArray(thing)) {\n // if it is an array lets measure each element\n // to do maybe simplify this function a bit so we can do this more recursively?\n for (j = 0, jlen = thing.length; j < jlen; j++) {\n nestedThing = thing[j];\n // Undefined strings and arrays should not be measured\n if (nestedThing !== undefined && nestedThing !== null && !isArray(nestedThing)) {\n longest = _measureText(ctx, data, gc, longest, nestedThing);\n }\n }\n }\n }\n\n ctx.restore();\n\n const gcLen = gc.length / 2;\n if (gcLen > arrayOfThings.length) {\n for (i = 0; i < gcLen; i++) {\n delete data[gc[i]];\n }\n gc.splice(0, gcLen);\n }\n return longest;\n}\n\n/**\n * Returns the aligned pixel value to avoid anti-aliasing blur\n * @param chart - The chart instance.\n * @param pixel - A pixel value.\n * @param width - The width of the element.\n * @returns The aligned pixel value.\n * @private\n */\nexport function _alignPixel(chart: Chart, pixel: number, width: number) {\n const devicePixelRatio = chart.currentDevicePixelRatio;\n const halfWidth = width !== 0 ? Math.max(width / 2, 0.5) : 0;\n return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;\n}\n\n/**\n * Clears the entire canvas.\n */\nexport function clearCanvas(canvas?: HTMLCanvasElement, ctx?: CanvasRenderingContext2D) {\n if (!ctx && !canvas) {\n return;\n }\n\n ctx = ctx || canvas.getContext('2d');\n\n ctx.save();\n // canvas.width and canvas.height do not consider the canvas transform,\n // while clearRect does\n ctx.resetTransform();\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.restore();\n}\n\nexport interface DrawPointOptions {\n pointStyle: PointStyle;\n rotation?: number;\n radius: number;\n borderWidth: number;\n}\n\nexport function drawPoint(\n ctx: CanvasRenderingContext2D,\n options: DrawPointOptions,\n x: number,\n y: number\n) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n drawPointLegend(ctx, options, x, y, null);\n}\n\n// eslint-disable-next-line complexity\nexport function drawPointLegend(\n ctx: CanvasRenderingContext2D,\n options: DrawPointOptions,\n x: number,\n y: number,\n w: number\n) {\n let type: string, xOffset: number, yOffset: number, size: number, cornerRadius: number, width: number, xOffsetW: number, yOffsetW: number;\n const style = options.pointStyle;\n const rotation = options.rotation;\n const radius = options.radius;\n let rad = (rotation || 0) * RAD_PER_DEG;\n\n if (style && typeof style === 'object') {\n type = style.toString();\n if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {\n ctx.save();\n ctx.translate(x, y);\n ctx.rotate(rad);\n ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);\n ctx.restore();\n return;\n }\n }\n\n if (isNaN(radius) || radius <= 0) {\n return;\n }\n\n ctx.beginPath();\n\n switch (style) {\n // Default includes circle\n default:\n if (w) {\n ctx.ellipse(x, y, w / 2, radius, 0, 0, TAU);\n } else {\n ctx.arc(x, y, radius, 0, TAU);\n }\n ctx.closePath();\n break;\n case 'triangle':\n width = w ? w / 2 : radius;\n ctx.moveTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);\n rad += TWO_THIRDS_PI;\n ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);\n rad += TWO_THIRDS_PI;\n ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);\n ctx.closePath();\n break;\n case 'rectRounded':\n // NOTE: the rounded rect implementation changed to use `arc` instead of\n // `quadraticCurveTo` since it generates better results when rect is\n // almost a circle. 0.516 (instead of 0.5) produces results with visually\n // closer proportion to the previous impl and it is inscribed in the\n // circle with `radius`. For more details, see the following PRs:\n // https://github.com/chartjs/Chart.js/issues/5597\n // https://github.com/chartjs/Chart.js/issues/5858\n cornerRadius = radius * 0.516;\n size = radius - cornerRadius;\n xOffset = Math.cos(rad + QUARTER_PI) * size;\n xOffsetW = Math.cos(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size);\n yOffset = Math.sin(rad + QUARTER_PI) * size;\n yOffsetW = Math.sin(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size);\n ctx.arc(x - xOffsetW, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);\n ctx.arc(x + yOffsetW, y - xOffset, cornerRadius, rad - HALF_PI, rad);\n ctx.arc(x + xOffsetW, y + yOffset, cornerRadius, rad, rad + HALF_PI);\n ctx.arc(x - yOffsetW, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);\n ctx.closePath();\n break;\n case 'rect':\n if (!rotation) {\n size = Math.SQRT1_2 * radius;\n width = w ? w / 2 : size;\n ctx.rect(x - width, y - size, 2 * width, 2 * size);\n break;\n }\n rad += QUARTER_PI;\n /* falls through */\n case 'rectRot':\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n ctx.closePath();\n break;\n case 'crossRot':\n rad += QUARTER_PI;\n /* falls through */\n case 'cross':\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.moveTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n break;\n case 'star':\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.moveTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n rad += QUARTER_PI;\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.moveTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n break;\n case 'line':\n xOffset = w ? w / 2 : Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n ctx.moveTo(x - xOffset, y - yOffset);\n ctx.lineTo(x + xOffset, y + yOffset);\n break;\n case 'dash':\n ctx.moveTo(x, y);\n ctx.lineTo(x + Math.cos(rad) * (w ? w / 2 : radius), y + Math.sin(rad) * radius);\n break;\n case false:\n ctx.closePath();\n break;\n }\n\n ctx.fill();\n if (options.borderWidth > 0) {\n ctx.stroke();\n }\n}\n\n/**\n * Returns true if the point is inside the rectangle\n * @param point - The point to test\n * @param area - The rectangle\n * @param margin - allowed margin\n * @private\n */\nexport function _isPointInArea(\n point: Point,\n area: TRBL,\n margin?: number\n) {\n margin = margin || 0.5; // margin - default is to match rounded decimals\n\n return !area || (point && point.x > area.left - margin && point.x < area.right + margin &&\n\t\tpoint.y > area.top - margin && point.y < area.bottom + margin);\n}\n\nexport function clipArea(ctx: CanvasRenderingContext2D, area: TRBL) {\n ctx.save();\n ctx.beginPath();\n ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);\n ctx.clip();\n}\n\nexport function unclipArea(ctx: CanvasRenderingContext2D) {\n ctx.restore();\n}\n\n/**\n * @private\n */\nexport function _steppedLineTo(\n ctx: CanvasRenderingContext2D,\n previous: Point,\n target: Point,\n flip?: boolean,\n mode?: string\n) {\n if (!previous) {\n return ctx.lineTo(target.x, target.y);\n }\n if (mode === 'middle') {\n const midpoint = (previous.x + target.x) / 2.0;\n ctx.lineTo(midpoint, previous.y);\n ctx.lineTo(midpoint, target.y);\n } else if (mode === 'after' !== !!flip) {\n ctx.lineTo(previous.x, target.y);\n } else {\n ctx.lineTo(target.x, previous.y);\n }\n ctx.lineTo(target.x, target.y);\n}\n\n/**\n * @private\n */\nexport function _bezierCurveTo(\n ctx: CanvasRenderingContext2D,\n previous: SplinePoint,\n target: SplinePoint,\n flip?: boolean\n) {\n if (!previous) {\n return ctx.lineTo(target.x, target.y);\n }\n ctx.bezierCurveTo(\n flip ? previous.cp1x : previous.cp2x,\n flip ? previous.cp1y : previous.cp2y,\n flip ? target.cp2x : target.cp1x,\n flip ? target.cp2y : target.cp1y,\n target.x,\n target.y);\n}\n\nfunction setRenderOpts(ctx: CanvasRenderingContext2D, opts: RenderTextOpts) {\n if (opts.translation) {\n ctx.translate(opts.translation[0], opts.translation[1]);\n }\n\n if (!isNullOrUndef(opts.rotation)) {\n ctx.rotate(opts.rotation);\n }\n\n if (opts.color) {\n ctx.fillStyle = opts.color;\n }\n\n if (opts.textAlign) {\n ctx.textAlign = opts.textAlign;\n }\n\n if (opts.textBaseline) {\n ctx.textBaseline = opts.textBaseline;\n }\n}\n\nfunction decorateText(\n ctx: CanvasRenderingContext2D,\n x: number,\n y: number,\n line: string,\n opts: RenderTextOpts\n) {\n if (opts.strikethrough || opts.underline) {\n /**\n * Now that IE11 support has been dropped, we can use more\n * of the TextMetrics object. The actual bounding boxes\n * are unflagged in Chrome, Firefox, Edge, and Safari so they\n * can be safely used.\n * See https://developer.mozilla.org/en-US/docs/Web/API/TextMetrics#Browser_compatibility\n */\n const metrics = ctx.measureText(line);\n const left = x - metrics.actualBoundingBoxLeft;\n const right = x + metrics.actualBoundingBoxRight;\n const top = y - metrics.actualBoundingBoxAscent;\n const bottom = y + metrics.actualBoundingBoxDescent;\n const yDecoration = opts.strikethrough ? (top + bottom) / 2 : bottom;\n\n ctx.strokeStyle = ctx.fillStyle;\n ctx.beginPath();\n ctx.lineWidth = opts.decorationWidth || 2;\n ctx.moveTo(left, yDecoration);\n ctx.lineTo(right, yDecoration);\n ctx.stroke();\n }\n}\n\nfunction drawBackdrop(ctx: CanvasRenderingContext2D, opts: BackdropOptions) {\n const oldColor = ctx.fillStyle;\n\n ctx.fillStyle = opts.color as string;\n ctx.fillRect(opts.left, opts.top, opts.width, opts.height);\n ctx.fillStyle = oldColor;\n}\n\n/**\n * Render text onto the canvas\n */\nexport function renderText(\n ctx: CanvasRenderingContext2D,\n text: string | string[],\n x: number,\n y: number,\n font: CanvasFontSpec,\n opts: RenderTextOpts = {}\n) {\n const lines = isArray(text) ? text : [text];\n const stroke = opts.strokeWidth > 0 && opts.strokeColor !== '';\n let i: number, line: string;\n\n ctx.save();\n ctx.font = font.string;\n setRenderOpts(ctx, opts);\n\n for (i = 0; i < lines.length; ++i) {\n line = lines[i];\n\n if (opts.backdrop) {\n drawBackdrop(ctx, opts.backdrop);\n }\n\n if (stroke) {\n if (opts.strokeColor) {\n ctx.strokeStyle = opts.strokeColor;\n }\n\n if (!isNullOrUndef(opts.strokeWidth)) {\n ctx.lineWidth = opts.strokeWidth;\n }\n\n ctx.strokeText(line, x, y, opts.maxWidth);\n }\n\n ctx.fillText(line, x, y, opts.maxWidth);\n decorateText(ctx, x, y, line, opts);\n\n y += Number(font.lineHeight);\n }\n\n ctx.restore();\n}\n\n/**\n * Add a path of a rectangle with rounded corners to the current sub-path\n * @param ctx - Context\n * @param rect - Bounding rect\n */\nexport function addRoundedRectPath(\n ctx: CanvasRenderingContext2D,\n rect: RoundedRect & { radius: TRBLCorners }\n) {\n const {x, y, w, h, radius} = rect;\n\n // top left arc\n ctx.arc(x + radius.topLeft, y + radius.topLeft, radius.topLeft, 1.5 * PI, PI, true);\n\n // line from top left to bottom left\n ctx.lineTo(x, y + h - radius.bottomLeft);\n\n // bottom left arc\n ctx.arc(x + radius.bottomLeft, y + h - radius.bottomLeft, radius.bottomLeft, PI, HALF_PI, true);\n\n // line from bottom left to bottom right\n ctx.lineTo(x + w - radius.bottomRight, y + h);\n\n // bottom right arc\n ctx.arc(x + w - radius.bottomRight, y + h - radius.bottomRight, radius.bottomRight, HALF_PI, 0, true);\n\n // line from bottom right to top right\n ctx.lineTo(x + w, y + radius.topRight);\n\n // top right arc\n ctx.arc(x + w - radius.topRight, y + radius.topRight, radius.topRight, 0, -HALF_PI, true);\n\n // line from top right to top left\n ctx.lineTo(x + radius.topLeft, y);\n}\n","/* eslint-disable @typescript-eslint/no-use-before-define */\nimport type {AnyObject} from '../types/basic.js';\nimport type {ChartMeta} from '../types/index.js';\nimport type {\n ResolverObjectKey,\n ResolverCache,\n ResolverProxy,\n DescriptorDefaults,\n Descriptor,\n ContextCache,\n ContextProxy\n} from './helpers.config.types.js';\nimport {isArray, isFunction, isObject, resolveObjectKey, _capitalize} from './helpers.core.js';\n\nexport * from './helpers.config.types.js';\n\n/**\n * Creates a Proxy for resolving raw values for options.\n * @param scopes - The option scopes to look for values, in resolution order\n * @param prefixes - The prefixes for values, in resolution order.\n * @param rootScopes - The root option scopes\n * @param fallback - Parent scopes fallback\n * @param getTarget - callback for getting the target for changed values\n * @returns Proxy\n * @private\n */\nexport function _createResolver<\n T extends AnyObject[] = AnyObject[],\n R extends AnyObject[] = T\n>(\n scopes: T,\n prefixes = [''],\n rootScopes?: R,\n fallback?: ResolverObjectKey,\n getTarget = () => scopes[0]\n) {\n const finalRootScopes = rootScopes || scopes;\n if (typeof fallback === 'undefined') {\n fallback = _resolve('_fallback', scopes);\n }\n const cache: ResolverCache = {\n [Symbol.toStringTag]: 'Object',\n _cacheable: true,\n _scopes: scopes,\n _rootScopes: finalRootScopes,\n _fallback: fallback,\n _getTarget: getTarget,\n override: (scope: AnyObject) => _createResolver([scope, ...scopes], prefixes, finalRootScopes, fallback),\n };\n return new Proxy(cache, {\n /**\n * A trap for the delete operator.\n */\n deleteProperty(target, prop: string) {\n delete target[prop]; // remove from cache\n delete target._keys; // remove cached keys\n delete scopes[0][prop]; // remove from top level scope\n return true;\n },\n\n /**\n * A trap for getting property values.\n */\n get(target, prop: string) {\n return _cached(target, prop,\n () => _resolveWithPrefixes(prop, prefixes, scopes, target));\n },\n\n /**\n * A trap for Object.getOwnPropertyDescriptor.\n * Also used by Object.hasOwnProperty.\n */\n getOwnPropertyDescriptor(target, prop) {\n return Reflect.getOwnPropertyDescriptor(target._scopes[0], prop);\n },\n\n /**\n * A trap for Object.getPrototypeOf.\n */\n getPrototypeOf() {\n return Reflect.getPrototypeOf(scopes[0]);\n },\n\n /**\n * A trap for the in operator.\n */\n has(target, prop: string) {\n return getKeysFromAllScopes(target).includes(prop);\n },\n\n /**\n * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols.\n */\n ownKeys(target) {\n return getKeysFromAllScopes(target);\n },\n\n /**\n * A trap for setting property values.\n */\n set(target, prop: string, value) {\n const storage = target._storage || (target._storage = getTarget());\n target[prop] = storage[prop] = value; // set to top level scope + cache\n delete target._keys; // remove cached keys\n return true;\n }\n }) as ResolverProxy;\n}\n\n/**\n * Returns an Proxy for resolving option values with context.\n * @param proxy - The Proxy returned by `_createResolver`\n * @param context - Context object for scriptable/indexable options\n * @param subProxy - The proxy provided for scriptable options\n * @param descriptorDefaults - Defaults for descriptors\n * @private\n */\nexport function _attachContext<\n T extends AnyObject[] = AnyObject[],\n R extends AnyObject[] = T\n>(\n proxy: ResolverProxy,\n context: AnyObject,\n subProxy?: ResolverProxy,\n descriptorDefaults?: DescriptorDefaults\n) {\n const cache: ContextCache = {\n _cacheable: false,\n _proxy: proxy,\n _context: context,\n _subProxy: subProxy,\n _stack: new Set(),\n _descriptors: _descriptors(proxy, descriptorDefaults),\n setContext: (ctx: AnyObject) => _attachContext(proxy, ctx, subProxy, descriptorDefaults),\n override: (scope: AnyObject) => _attachContext(proxy.override(scope), context, subProxy, descriptorDefaults)\n };\n return new Proxy(cache, {\n /**\n * A trap for the delete operator.\n */\n deleteProperty(target, prop) {\n delete target[prop]; // remove from cache\n delete proxy[prop]; // remove from proxy\n return true;\n },\n\n /**\n * A trap for getting property values.\n */\n get(target, prop: string, receiver) {\n return _cached(target, prop,\n () => _resolveWithContext(target, prop, receiver));\n },\n\n /**\n * A trap for Object.getOwnPropertyDescriptor.\n * Also used by Object.hasOwnProperty.\n */\n getOwnPropertyDescriptor(target, prop) {\n return target._descriptors.allKeys\n ? Reflect.has(proxy, prop) ? {enumerable: true, configurable: true} : undefined\n : Reflect.getOwnPropertyDescriptor(proxy, prop);\n },\n\n /**\n * A trap for Object.getPrototypeOf.\n */\n getPrototypeOf() {\n return Reflect.getPrototypeOf(proxy);\n },\n\n /**\n * A trap for the in operator.\n */\n has(target, prop) {\n return Reflect.has(proxy, prop);\n },\n\n /**\n * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols.\n */\n ownKeys() {\n return Reflect.ownKeys(proxy);\n },\n\n /**\n * A trap for setting property values.\n */\n set(target, prop, value) {\n proxy[prop] = value; // set to proxy\n delete target[prop]; // remove from cache\n return true;\n }\n }) as ContextProxy;\n}\n\n/**\n * @private\n */\nexport function _descriptors(\n proxy: ResolverCache,\n defaults: DescriptorDefaults = {scriptable: true, indexable: true}\n): Descriptor {\n const {_scriptable = defaults.scriptable, _indexable = defaults.indexable, _allKeys = defaults.allKeys} = proxy;\n return {\n allKeys: _allKeys,\n scriptable: _scriptable,\n indexable: _indexable,\n isScriptable: isFunction(_scriptable) ? _scriptable : () => _scriptable,\n isIndexable: isFunction(_indexable) ? _indexable : () => _indexable\n };\n}\n\nconst readKey = (prefix: string, name: string) => prefix ? prefix + _capitalize(name) : name;\nconst needsSubResolver = (prop: string, value: unknown) => isObject(value) && prop !== 'adapters' &&\n (Object.getPrototypeOf(value) === null || value.constructor === Object);\n\nfunction _cached(\n target: AnyObject,\n prop: string,\n resolve: () => unknown\n) {\n if (Object.prototype.hasOwnProperty.call(target, prop) || prop === 'constructor') {\n return target[prop];\n }\n\n const value = resolve();\n // cache the resolved value\n target[prop] = value;\n return value;\n}\n\nfunction _resolveWithContext(\n target: ContextCache,\n prop: string,\n receiver: AnyObject\n) {\n const {_proxy, _context, _subProxy, _descriptors: descriptors} = target;\n let value = _proxy[prop]; // resolve from proxy\n\n // resolve with context\n if (isFunction(value) && descriptors.isScriptable(prop)) {\n value = _resolveScriptable(prop, value, target, receiver);\n }\n if (isArray(value) && value.length) {\n value = _resolveArray(prop, value, target, descriptors.isIndexable);\n }\n if (needsSubResolver(prop, value)) {\n // if the resolved value is an object, create a sub resolver for it\n value = _attachContext(value, _context, _subProxy && _subProxy[prop], descriptors);\n }\n return value;\n}\n\nfunction _resolveScriptable(\n prop: string,\n getValue: (ctx: AnyObject, sub: AnyObject) => unknown,\n target: ContextCache,\n receiver: AnyObject\n) {\n const {_proxy, _context, _subProxy, _stack} = target;\n if (_stack.has(prop)) {\n throw new Error('Recursion detected: ' + Array.from(_stack).join('->') + '->' + prop);\n }\n _stack.add(prop);\n let value = getValue(_context, _subProxy || receiver);\n _stack.delete(prop);\n if (needsSubResolver(prop, value)) {\n // When scriptable option returns an object, create a resolver on that.\n value = createSubResolver(_proxy._scopes, _proxy, prop, value);\n }\n return value;\n}\n\nfunction _resolveArray(\n prop: string,\n value: unknown[],\n target: ContextCache,\n isIndexable: (key: string) => boolean\n) {\n const {_proxy, _context, _subProxy, _descriptors: descriptors} = target;\n\n if (typeof _context.index !== 'undefined' && isIndexable(prop)) {\n return value[_context.index % value.length];\n } else if (isObject(value[0])) {\n // Array of objects, return array or resolvers\n const arr = value;\n const scopes = _proxy._scopes.filter(s => s !== arr);\n value = [];\n for (const item of arr) {\n const resolver = createSubResolver(scopes, _proxy, prop, item);\n value.push(_attachContext(resolver, _context, _subProxy && _subProxy[prop], descriptors));\n }\n }\n return value;\n}\n\nfunction resolveFallback(\n fallback: ResolverObjectKey | ((prop: ResolverObjectKey, value: unknown) => ResolverObjectKey),\n prop: ResolverObjectKey,\n value: unknown\n) {\n return isFunction(fallback) ? fallback(prop, value) : fallback;\n}\n\nconst getScope = (key: ResolverObjectKey, parent: AnyObject) => key === true ? parent\n : typeof key === 'string' ? resolveObjectKey(parent, key) : undefined;\n\nfunction addScopes(\n set: Set,\n parentScopes: AnyObject[],\n key: ResolverObjectKey,\n parentFallback: ResolverObjectKey,\n value: unknown\n) {\n for (const parent of parentScopes) {\n const scope = getScope(key, parent);\n if (scope) {\n set.add(scope);\n const fallback = resolveFallback(scope._fallback, key, value);\n if (typeof fallback !== 'undefined' && fallback !== key && fallback !== parentFallback) {\n // When we reach the descriptor that defines a new _fallback, return that.\n // The fallback will resume to that new scope.\n return fallback;\n }\n } else if (scope === false && typeof parentFallback !== 'undefined' && key !== parentFallback) {\n // Fallback to `false` results to `false`, when falling back to different key.\n // For example `interaction` from `hover` or `plugins.tooltip` and `animation` from `animations`\n return null;\n }\n }\n return false;\n}\n\nfunction createSubResolver(\n parentScopes: AnyObject[],\n resolver: ResolverCache,\n prop: ResolverObjectKey,\n value: unknown\n) {\n const rootScopes = resolver._rootScopes;\n const fallback = resolveFallback(resolver._fallback, prop, value);\n const allScopes = [...parentScopes, ...rootScopes];\n const set = new Set();\n set.add(value);\n let key = addScopesFromKey(set, allScopes, prop, fallback || prop, value);\n if (key === null) {\n return false;\n }\n if (typeof fallback !== 'undefined' && fallback !== prop) {\n key = addScopesFromKey(set, allScopes, fallback, key, value);\n if (key === null) {\n return false;\n }\n }\n return _createResolver(Array.from(set), [''], rootScopes, fallback,\n () => subGetTarget(resolver, prop as string, value));\n}\n\nfunction addScopesFromKey(\n set: Set,\n allScopes: AnyObject[],\n key: ResolverObjectKey,\n fallback: ResolverObjectKey,\n item: unknown\n) {\n while (key) {\n key = addScopes(set, allScopes, key, fallback, item);\n }\n return key;\n}\n\nfunction subGetTarget(\n resolver: ResolverCache,\n prop: string,\n value: unknown\n) {\n const parent = resolver._getTarget();\n if (!(prop in parent)) {\n parent[prop] = {};\n }\n const target = parent[prop];\n if (isArray(target) && isObject(value)) {\n // For array of objects, the object is used to store updated values\n return value;\n }\n return target || {};\n}\n\nfunction _resolveWithPrefixes(\n prop: string,\n prefixes: string[],\n scopes: AnyObject[],\n proxy: ResolverProxy\n) {\n let value: unknown;\n for (const prefix of prefixes) {\n value = _resolve(readKey(prefix, prop), scopes);\n if (typeof value !== 'undefined') {\n return needsSubResolver(prop, value)\n ? createSubResolver(scopes, proxy, prop, value)\n : value;\n }\n }\n}\n\nfunction _resolve(key: string, scopes: AnyObject[]) {\n for (const scope of scopes) {\n if (!scope) {\n continue;\n }\n const value = scope[key];\n if (typeof value !== 'undefined') {\n return value;\n }\n }\n}\n\nfunction getKeysFromAllScopes(target: ResolverCache) {\n let keys = target._keys;\n if (!keys) {\n keys = target._keys = resolveKeysFromAllScopes(target._scopes);\n }\n return keys;\n}\n\nfunction resolveKeysFromAllScopes(scopes: AnyObject[]) {\n const set = new Set();\n for (const scope of scopes) {\n for (const key of Object.keys(scope).filter(k => !k.startsWith('_'))) {\n set.add(key);\n }\n }\n return Array.from(set);\n}\n\nexport function _parseObjectDataRadialScale(\n meta: ChartMeta<'line' | 'scatter'>,\n data: AnyObject[],\n start: number,\n count: number\n) {\n const {iScale} = meta;\n const {key = 'r'} = this._parsing;\n const parsed = new Array<{r: unknown}>(count);\n let i: number, ilen: number, index: number, item: AnyObject;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n item = data[index];\n parsed[i] = {\n r: iScale.parse(resolveObjectKey(item, key), index)\n };\n }\n return parsed;\n}\n","import {almostEquals, distanceBetweenPoints, sign} from './helpers.math.js';\nimport {_isPointInArea} from './helpers.canvas.js';\nimport type {ChartArea} from '../types/index.js';\nimport type {SplinePoint} from '../types/geometric.js';\n\nconst EPSILON = Number.EPSILON || 1e-14;\n\ntype OptionalSplinePoint = SplinePoint | false\nconst getPoint = (points: SplinePoint[], i: number): OptionalSplinePoint => i < points.length && !points[i].skip && points[i];\nconst getValueAxis = (indexAxis: 'x' | 'y') => indexAxis === 'x' ? 'y' : 'x';\n\nexport function splineCurve(\n firstPoint: SplinePoint,\n middlePoint: SplinePoint,\n afterPoint: SplinePoint,\n t: number\n): {\n previous: SplinePoint\n next: SplinePoint\n } {\n // Props to Rob Spencer at scaled innovation for his post on splining between points\n // http://scaledinnovation.com/analytics/splines/aboutSplines.html\n\n // This function must also respect \"skipped\" points\n\n const previous = firstPoint.skip ? middlePoint : firstPoint;\n const current = middlePoint;\n const next = afterPoint.skip ? middlePoint : afterPoint;\n const d01 = distanceBetweenPoints(current, previous);\n const d12 = distanceBetweenPoints(next, current);\n\n let s01 = d01 / (d01 + d12);\n let s12 = d12 / (d01 + d12);\n\n // If all points are the same, s01 & s02 will be inf\n s01 = isNaN(s01) ? 0 : s01;\n s12 = isNaN(s12) ? 0 : s12;\n\n const fa = t * s01; // scaling factor for triangle Ta\n const fb = t * s12;\n\n return {\n previous: {\n x: current.x - fa * (next.x - previous.x),\n y: current.y - fa * (next.y - previous.y)\n },\n next: {\n x: current.x + fb * (next.x - previous.x),\n y: current.y + fb * (next.y - previous.y)\n }\n };\n}\n\n/**\n * Adjust tangents to ensure monotonic properties\n */\nfunction monotoneAdjust(points: SplinePoint[], deltaK: number[], mK: number[]) {\n const pointsLen = points.length;\n\n let alphaK: number, betaK: number, tauK: number, squaredMagnitude: number, pointCurrent: OptionalSplinePoint;\n let pointAfter = getPoint(points, 0);\n for (let i = 0; i < pointsLen - 1; ++i) {\n pointCurrent = pointAfter;\n pointAfter = getPoint(points, i + 1);\n if (!pointCurrent || !pointAfter) {\n continue;\n }\n\n if (almostEquals(deltaK[i], 0, EPSILON)) {\n mK[i] = mK[i + 1] = 0;\n continue;\n }\n\n alphaK = mK[i] / deltaK[i];\n betaK = mK[i + 1] / deltaK[i];\n squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);\n if (squaredMagnitude <= 9) {\n continue;\n }\n\n tauK = 3 / Math.sqrt(squaredMagnitude);\n mK[i] = alphaK * tauK * deltaK[i];\n mK[i + 1] = betaK * tauK * deltaK[i];\n }\n}\n\nfunction monotoneCompute(points: SplinePoint[], mK: number[], indexAxis: 'x' | 'y' = 'x') {\n const valueAxis = getValueAxis(indexAxis);\n const pointsLen = points.length;\n let delta: number, pointBefore: OptionalSplinePoint, pointCurrent: OptionalSplinePoint;\n let pointAfter = getPoint(points, 0);\n\n for (let i = 0; i < pointsLen; ++i) {\n pointBefore = pointCurrent;\n pointCurrent = pointAfter;\n pointAfter = getPoint(points, i + 1);\n if (!pointCurrent) {\n continue;\n }\n\n const iPixel = pointCurrent[indexAxis];\n const vPixel = pointCurrent[valueAxis];\n if (pointBefore) {\n delta = (iPixel - pointBefore[indexAxis]) / 3;\n pointCurrent[`cp1${indexAxis}`] = iPixel - delta;\n pointCurrent[`cp1${valueAxis}`] = vPixel - delta * mK[i];\n }\n if (pointAfter) {\n delta = (pointAfter[indexAxis] - iPixel) / 3;\n pointCurrent[`cp2${indexAxis}`] = iPixel + delta;\n pointCurrent[`cp2${valueAxis}`] = vPixel + delta * mK[i];\n }\n }\n}\n\n/**\n * This function calculates Bézier control points in a similar way than |splineCurve|,\n * but preserves monotonicity of the provided data and ensures no local extremums are added\n * between the dataset discrete points due to the interpolation.\n * See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation\n */\nexport function splineCurveMonotone(points: SplinePoint[], indexAxis: 'x' | 'y' = 'x') {\n const valueAxis = getValueAxis(indexAxis);\n const pointsLen = points.length;\n const deltaK: number[] = Array(pointsLen).fill(0);\n const mK: number[] = Array(pointsLen);\n\n // Calculate slopes (deltaK) and initialize tangents (mK)\n let i, pointBefore: OptionalSplinePoint, pointCurrent: OptionalSplinePoint;\n let pointAfter = getPoint(points, 0);\n\n for (i = 0; i < pointsLen; ++i) {\n pointBefore = pointCurrent;\n pointCurrent = pointAfter;\n pointAfter = getPoint(points, i + 1);\n if (!pointCurrent) {\n continue;\n }\n\n if (pointAfter) {\n const slopeDelta = pointAfter[indexAxis] - pointCurrent[indexAxis];\n\n // In the case of two points that appear at the same x pixel, slopeDeltaX is 0\n deltaK[i] = slopeDelta !== 0 ? (pointAfter[valueAxis] - pointCurrent[valueAxis]) / slopeDelta : 0;\n }\n mK[i] = !pointBefore ? deltaK[i]\n : !pointAfter ? deltaK[i - 1]\n : (sign(deltaK[i - 1]) !== sign(deltaK[i])) ? 0\n : (deltaK[i - 1] + deltaK[i]) / 2;\n }\n\n monotoneAdjust(points, deltaK, mK);\n\n monotoneCompute(points, mK, indexAxis);\n}\n\nfunction capControlPoint(pt: number, min: number, max: number) {\n return Math.max(Math.min(pt, max), min);\n}\n\nfunction capBezierPoints(points: SplinePoint[], area: ChartArea) {\n let i, ilen, point, inArea, inAreaPrev;\n let inAreaNext = _isPointInArea(points[0], area);\n for (i = 0, ilen = points.length; i < ilen; ++i) {\n inAreaPrev = inArea;\n inArea = inAreaNext;\n inAreaNext = i < ilen - 1 && _isPointInArea(points[i + 1], area);\n if (!inArea) {\n continue;\n }\n point = points[i];\n if (inAreaPrev) {\n point.cp1x = capControlPoint(point.cp1x, area.left, area.right);\n point.cp1y = capControlPoint(point.cp1y, area.top, area.bottom);\n }\n if (inAreaNext) {\n point.cp2x = capControlPoint(point.cp2x, area.left, area.right);\n point.cp2y = capControlPoint(point.cp2y, area.top, area.bottom);\n }\n }\n}\n\n/**\n * @private\n */\nexport function _updateBezierControlPoints(\n points: SplinePoint[],\n options,\n area: ChartArea,\n loop: boolean,\n indexAxis: 'x' | 'y'\n) {\n let i: number, ilen: number, point: SplinePoint, controlPoints: ReturnType;\n\n // Only consider points that are drawn in case the spanGaps option is used\n if (options.spanGaps) {\n points = points.filter((pt) => !pt.skip);\n }\n\n if (options.cubicInterpolationMode === 'monotone') {\n splineCurveMonotone(points, indexAxis);\n } else {\n let prev = loop ? points[points.length - 1] : points[0];\n for (i = 0, ilen = points.length; i < ilen; ++i) {\n point = points[i];\n controlPoints = splineCurve(\n prev,\n point,\n points[Math.min(i + 1, ilen - (loop ? 0 : 1)) % ilen],\n options.tension\n );\n point.cp1x = controlPoints.previous.x;\n point.cp1y = controlPoints.previous.y;\n point.cp2x = controlPoints.next.x;\n point.cp2y = controlPoints.next.y;\n prev = point;\n }\n }\n\n if (options.capBezierPoints) {\n capBezierPoints(points, area);\n }\n}\n","import {PI, TAU, HALF_PI} from './helpers.math.js';\n\nconst atEdge = (t: number) => t === 0 || t === 1;\nconst elasticIn = (t: number, s: number, p: number) => -(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * TAU / p));\nconst elasticOut = (t: number, s: number, p: number) => Math.pow(2, -10 * t) * Math.sin((t - s) * TAU / p) + 1;\n\n/**\n * Easing functions adapted from Robert Penner's easing equations.\n * @namespace Chart.helpers.easing.effects\n * @see http://www.robertpenner.com/easing/\n */\nconst effects = {\n linear: (t: number) => t,\n\n easeInQuad: (t: number) => t * t,\n\n easeOutQuad: (t: number) => -t * (t - 2),\n\n easeInOutQuad: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t\n : -0.5 * ((--t) * (t - 2) - 1),\n\n easeInCubic: (t: number) => t * t * t,\n\n easeOutCubic: (t: number) => (t -= 1) * t * t + 1,\n\n easeInOutCubic: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t * t\n : 0.5 * ((t -= 2) * t * t + 2),\n\n easeInQuart: (t: number) => t * t * t * t,\n\n easeOutQuart: (t: number) => -((t -= 1) * t * t * t - 1),\n\n easeInOutQuart: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t * t * t\n : -0.5 * ((t -= 2) * t * t * t - 2),\n\n easeInQuint: (t: number) => t * t * t * t * t,\n\n easeOutQuint: (t: number) => (t -= 1) * t * t * t * t + 1,\n\n easeInOutQuint: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t * t * t * t\n : 0.5 * ((t -= 2) * t * t * t * t + 2),\n\n easeInSine: (t: number) => -Math.cos(t * HALF_PI) + 1,\n\n easeOutSine: (t: number) => Math.sin(t * HALF_PI),\n\n easeInOutSine: (t: number) => -0.5 * (Math.cos(PI * t) - 1),\n\n easeInExpo: (t: number) => (t === 0) ? 0 : Math.pow(2, 10 * (t - 1)),\n\n easeOutExpo: (t: number) => (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1,\n\n easeInOutExpo: (t: number) => atEdge(t) ? t : t < 0.5\n ? 0.5 * Math.pow(2, 10 * (t * 2 - 1))\n : 0.5 * (-Math.pow(2, -10 * (t * 2 - 1)) + 2),\n\n easeInCirc: (t: number) => (t >= 1) ? t : -(Math.sqrt(1 - t * t) - 1),\n\n easeOutCirc: (t: number) => Math.sqrt(1 - (t -= 1) * t),\n\n easeInOutCirc: (t: number) => ((t /= 0.5) < 1)\n ? -0.5 * (Math.sqrt(1 - t * t) - 1)\n : 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1),\n\n easeInElastic: (t: number) => atEdge(t) ? t : elasticIn(t, 0.075, 0.3),\n\n easeOutElastic: (t: number) => atEdge(t) ? t : elasticOut(t, 0.075, 0.3),\n\n easeInOutElastic(t: number) {\n const s = 0.1125;\n const p = 0.45;\n return atEdge(t) ? t :\n t < 0.5\n ? 0.5 * elasticIn(t * 2, s, p)\n : 0.5 + 0.5 * elasticOut(t * 2 - 1, s, p);\n },\n\n easeInBack(t: number) {\n const s = 1.70158;\n return t * t * ((s + 1) * t - s);\n },\n\n easeOutBack(t: number) {\n const s = 1.70158;\n return (t -= 1) * t * ((s + 1) * t + s) + 1;\n },\n\n easeInOutBack(t: number) {\n let s = 1.70158;\n if ((t /= 0.5) < 1) {\n return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));\n }\n return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);\n },\n\n easeInBounce: (t: number) => 1 - effects.easeOutBounce(1 - t),\n\n easeOutBounce(t: number) {\n const m = 7.5625;\n const d = 2.75;\n if (t < (1 / d)) {\n return m * t * t;\n }\n if (t < (2 / d)) {\n return m * (t -= (1.5 / d)) * t + 0.75;\n }\n if (t < (2.5 / d)) {\n return m * (t -= (2.25 / d)) * t + 0.9375;\n }\n return m * (t -= (2.625 / d)) * t + 0.984375;\n },\n\n easeInOutBounce: (t: number) => (t < 0.5)\n ? effects.easeInBounce(t * 2) * 0.5\n : effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5,\n} as const;\n\nexport type EasingFunction = keyof typeof effects\n\nexport default effects;\n","import type {Point, SplinePoint} from '../types/geometric.js';\n\n/**\n * @private\n */\nexport function _pointInLine(p1: Point, p2: Point, t: number, mode?) { // eslint-disable-line @typescript-eslint/no-unused-vars\n return {\n x: p1.x + t * (p2.x - p1.x),\n y: p1.y + t * (p2.y - p1.y)\n };\n}\n\n/**\n * @private\n */\nexport function _steppedInterpolation(\n p1: Point,\n p2: Point,\n t: number, mode: 'middle' | 'after' | unknown\n) {\n return {\n x: p1.x + t * (p2.x - p1.x),\n y: mode === 'middle' ? t < 0.5 ? p1.y : p2.y\n : mode === 'after' ? t < 1 ? p1.y : p2.y\n : t > 0 ? p2.y : p1.y\n };\n}\n\n/**\n * @private\n */\nexport function _bezierInterpolation(p1: SplinePoint, p2: SplinePoint, t: number, mode?) { // eslint-disable-line @typescript-eslint/no-unused-vars\n const cp1 = {x: p1.cp2x, y: p1.cp2y};\n const cp2 = {x: p2.cp1x, y: p2.cp1y};\n const a = _pointInLine(p1, cp1, t);\n const b = _pointInLine(cp1, cp2, t);\n const c = _pointInLine(cp2, p2, t);\n const d = _pointInLine(a, b, t);\n const e = _pointInLine(b, c, t);\n return _pointInLine(d, e, t);\n}\n","import defaults from '../core/core.defaults.js';\nimport {isArray, isObject, toDimension, valueOrDefault} from './helpers.core.js';\nimport {toFontString} from './helpers.canvas.js';\nimport type {ChartArea, FontSpec, Point} from '../types/index.js';\nimport type {TRBL, TRBLCorners} from '../types/geometric.js';\n\nconst LINE_HEIGHT = /^(normal|(\\d+(?:\\.\\d+)?)(px|em|%)?)$/;\nconst FONT_STYLE = /^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;\n\n/**\n * @alias Chart.helpers.options\n * @namespace\n */\n/**\n * Converts the given line height `value` in pixels for a specific font `size`.\n * @param value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').\n * @param size - The font size (in pixels) used to resolve relative `value`.\n * @returns The effective line height in pixels (size * 1.2 if value is invalid).\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height\n * @since 2.7.0\n */\nexport function toLineHeight(value: number | string, size: number): number {\n const matches = ('' + value).match(LINE_HEIGHT);\n if (!matches || matches[1] === 'normal') {\n return size * 1.2;\n }\n\n value = +matches[2];\n\n switch (matches[3]) {\n case 'px':\n return value;\n case '%':\n value /= 100;\n break;\n default:\n break;\n }\n\n return size * value;\n}\n\nconst numberOrZero = (v: unknown) => +v || 0;\n\n/**\n * @param value\n * @param props\n */\nexport function _readValueToProps(value: number | Record, props: K[]): Record;\nexport function _readValueToProps(value: number | Record, props: Record): Record;\nexport function _readValueToProps(value: number | Record, props: string[] | Record) {\n const ret = {};\n const objProps = isObject(props);\n const keys = objProps ? Object.keys(props) : props;\n const read = isObject(value)\n ? objProps\n ? prop => valueOrDefault(value[prop], value[props[prop]])\n : prop => value[prop]\n : () => value;\n\n for (const prop of keys) {\n ret[prop] = numberOrZero(read(prop));\n }\n return ret;\n}\n\n/**\n * Converts the given value into a TRBL object.\n * @param value - If a number, set the value to all TRBL component,\n * else, if an object, use defined properties and sets undefined ones to 0.\n * x / y are shorthands for same value for left/right and top/bottom.\n * @returns The padding values (top, right, bottom, left)\n * @since 3.0.0\n */\nexport function toTRBL(value: number | TRBL | Point) {\n return _readValueToProps(value, {top: 'y', right: 'x', bottom: 'y', left: 'x'});\n}\n\n/**\n * Converts the given value into a TRBL corners object (similar with css border-radius).\n * @param value - If a number, set the value to all TRBL corner components,\n * else, if an object, use defined properties and sets undefined ones to 0.\n * @returns The TRBL corner values (topLeft, topRight, bottomLeft, bottomRight)\n * @since 3.0.0\n */\nexport function toTRBLCorners(value: number | TRBLCorners) {\n return _readValueToProps(value, ['topLeft', 'topRight', 'bottomLeft', 'bottomRight']);\n}\n\n/**\n * Converts the given value into a padding object with pre-computed width/height.\n * @param value - If a number, set the value to all TRBL component,\n * else, if an object, use defined properties and sets undefined ones to 0.\n * x / y are shorthands for same value for left/right and top/bottom.\n * @returns The padding values (top, right, bottom, left, width, height)\n * @since 2.7.0\n */\nexport function toPadding(value?: number | TRBL): ChartArea {\n const obj = toTRBL(value) as ChartArea;\n\n obj.width = obj.left + obj.right;\n obj.height = obj.top + obj.bottom;\n\n return obj;\n}\n\n/**\n * Parses font options and returns the font object.\n * @param options - A object that contains font options to be parsed.\n * @param fallback - A object that contains fallback font options.\n * @return The font object.\n * @private\n */\n\nexport function toFont(options: Partial, fallback?: Partial) {\n options = options || {};\n fallback = fallback || defaults.font as FontSpec;\n\n let size = valueOrDefault(options.size, fallback.size);\n\n if (typeof size === 'string') {\n size = parseInt(size, 10);\n }\n let style = valueOrDefault(options.style, fallback.style);\n if (style && !('' + style).match(FONT_STYLE)) {\n console.warn('Invalid font style specified: \"' + style + '\"');\n style = undefined;\n }\n\n const font = {\n family: valueOrDefault(options.family, fallback.family),\n lineHeight: toLineHeight(valueOrDefault(options.lineHeight, fallback.lineHeight), size),\n size,\n style,\n weight: valueOrDefault(options.weight, fallback.weight),\n string: ''\n };\n\n font.string = toFontString(font);\n return font;\n}\n\n/**\n * Evaluates the given `inputs` sequentially and returns the first defined value.\n * @param inputs - An array of values, falling back to the last value.\n * @param context - If defined and the current value is a function, the value\n * is called with `context` as first argument and the result becomes the new input.\n * @param index - If defined and the current value is an array, the value\n * at `index` become the new input.\n * @param info - object to return information about resolution in\n * @param info.cacheable - Will be set to `false` if option is not cacheable.\n * @since 2.7.0\n */\nexport function resolve(inputs: Array, context?: object, index?: number, info?: { cacheable: boolean }) {\n let cacheable = true;\n let i: number, ilen: number, value: unknown;\n\n for (i = 0, ilen = inputs.length; i < ilen; ++i) {\n value = inputs[i];\n if (value === undefined) {\n continue;\n }\n if (context !== undefined && typeof value === 'function') {\n value = value(context);\n cacheable = false;\n }\n if (index !== undefined && isArray(value)) {\n value = value[index % value.length];\n cacheable = false;\n }\n if (value !== undefined) {\n if (info && !cacheable) {\n info.cacheable = false;\n }\n return value;\n }\n }\n}\n\n/**\n * @param minmax\n * @param grace\n * @param beginAtZero\n * @private\n */\nexport function _addGrace(minmax: { min: number; max: number; }, grace: number | string, beginAtZero: boolean) {\n const {min, max} = minmax;\n const change = toDimension(grace, (max - min) / 2);\n const keepZero = (value: number, add: number) => beginAtZero && value === 0 ? 0 : value + add;\n return {\n min: keepZero(min, -Math.abs(change)),\n max: keepZero(max, change)\n };\n}\n\n/**\n * Create a context inheriting parentContext\n * @param parentContext\n * @param context\n * @returns\n */\nexport function createContext(parentContext: null, context: T): T;\nexport function createContext(parentContext: P, context: T): P & T;\nexport function createContext(parentContext: object, context: object) {\n return Object.assign(Object.create(parentContext), context);\n}\n","export interface RTLAdapter {\n x(x: number): number;\n setWidth(w: number): void;\n textAlign(align: 'center' | 'left' | 'right'): 'center' | 'left' | 'right';\n xPlus(x: number, value: number): number;\n leftForLtr(x: number, itemWidth: number): number;\n}\n\nconst getRightToLeftAdapter = function(rectX: number, width: number): RTLAdapter {\n return {\n x(x) {\n return rectX + rectX + width - x;\n },\n setWidth(w) {\n width = w;\n },\n textAlign(align) {\n if (align === 'center') {\n return align;\n }\n return align === 'right' ? 'left' : 'right';\n },\n xPlus(x, value) {\n return x - value;\n },\n leftForLtr(x, itemWidth) {\n return x - itemWidth;\n },\n };\n};\n\nconst getLeftToRightAdapter = function(): RTLAdapter {\n return {\n x(x) {\n return x;\n },\n setWidth(w) { // eslint-disable-line no-unused-vars\n },\n textAlign(align) {\n return align;\n },\n xPlus(x, value) {\n return x + value;\n },\n leftForLtr(x, _itemWidth) { // eslint-disable-line @typescript-eslint/no-unused-vars\n return x;\n },\n };\n};\n\nexport function getRtlAdapter(rtl: boolean, rectX: number, width: number) {\n return rtl ? getRightToLeftAdapter(rectX, width) : getLeftToRightAdapter();\n}\n\nexport function overrideTextDirection(ctx: CanvasRenderingContext2D, direction: 'ltr' | 'rtl') {\n let style: CSSStyleDeclaration, original: [string, string];\n if (direction === 'ltr' || direction === 'rtl') {\n style = ctx.canvas.style;\n original = [\n style.getPropertyValue('direction'),\n style.getPropertyPriority('direction'),\n ];\n\n style.setProperty('direction', direction, 'important');\n (ctx as { prevTextDirection?: [string, string] }).prevTextDirection = original;\n }\n}\n\nexport function restoreTextDirection(ctx: CanvasRenderingContext2D, original?: [string, string]) {\n if (original !== undefined) {\n delete (ctx as { prevTextDirection?: [string, string] }).prevTextDirection;\n ctx.canvas.style.setProperty('direction', original[0], original[1]);\n }\n}\n","import {_angleBetween, _angleDiff, _isBetween, _normalizeAngle} from './helpers.math.js';\nimport {createContext} from './helpers.options.js';\nimport {isPatternOrGradient} from './helpers.color.js';\n\n/**\n * @typedef { import('../elements/element.line.js').default } LineElement\n * @typedef { import('../elements/element.point.js').default } PointElement\n * @typedef {{start: number, end: number, loop: boolean, style?: any}} Segment\n */\n\nfunction propertyFn(property) {\n if (property === 'angle') {\n return {\n between: _angleBetween,\n compare: _angleDiff,\n normalize: _normalizeAngle,\n };\n }\n return {\n between: _isBetween,\n compare: (a, b) => a - b,\n normalize: x => x\n };\n}\n\nfunction normalizeSegment({start, end, count, loop, style}) {\n return {\n start: start % count,\n end: end % count,\n loop: loop && (end - start + 1) % count === 0,\n style\n };\n}\n\nfunction getSegment(segment, points, bounds) {\n const {property, start: startBound, end: endBound} = bounds;\n const {between, normalize} = propertyFn(property);\n const count = points.length;\n // eslint-disable-next-line prefer-const\n let {start, end, loop} = segment;\n let i, ilen;\n\n if (loop) {\n start += count;\n end += count;\n for (i = 0, ilen = count; i < ilen; ++i) {\n if (!between(normalize(points[start % count][property]), startBound, endBound)) {\n break;\n }\n start--;\n end--;\n }\n start %= count;\n end %= count;\n }\n\n if (end < start) {\n end += count;\n }\n return {start, end, loop, style: segment.style};\n}\n\n/**\n * Returns the sub-segment(s) of a line segment that fall in the given bounds\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} [segment.style] - segment style\n * @param {PointElement[]} points - the points that this segment refers to\n * @param {object} [bounds]\n * @param {string} bounds.property - the property of a `PointElement` we are bounding. `x`, `y` or `angle`.\n * @param {number} bounds.start - start value of the property\n * @param {number} bounds.end - end value of the property\n * @private\n **/\nexport function _boundSegment(segment, points, bounds) {\n if (!bounds) {\n return [segment];\n }\n\n const {property, start: startBound, end: endBound} = bounds;\n const count = points.length;\n const {compare, between, normalize} = propertyFn(property);\n const {start, end, loop, style} = getSegment(segment, points, bounds);\n\n const result = [];\n let inside = false;\n let subStart = null;\n let value, point, prevValue;\n\n const startIsBefore = () => between(startBound, prevValue, value) && compare(startBound, prevValue) !== 0;\n const endIsBefore = () => compare(endBound, value) === 0 || between(endBound, prevValue, value);\n const shouldStart = () => inside || startIsBefore();\n const shouldStop = () => !inside || endIsBefore();\n\n for (let i = start, prev = start; i <= end; ++i) {\n point = points[i % count];\n\n if (point.skip) {\n continue;\n }\n\n value = normalize(point[property]);\n\n if (value === prevValue) {\n continue;\n }\n\n inside = between(value, startBound, endBound);\n\n if (subStart === null && shouldStart()) {\n subStart = compare(value, startBound) === 0 ? i : prev;\n }\n\n if (subStart !== null && shouldStop()) {\n result.push(normalizeSegment({start: subStart, end: i, loop, count, style}));\n subStart = null;\n }\n prev = i;\n prevValue = value;\n }\n\n if (subStart !== null) {\n result.push(normalizeSegment({start: subStart, end, loop, count, style}));\n }\n\n return result;\n}\n\n\n/**\n * Returns the segments of the line that are inside given bounds\n * @param {LineElement} line\n * @param {object} [bounds]\n * @param {string} bounds.property - the property we are bounding with. `x`, `y` or `angle`.\n * @param {number} bounds.start - start value of the `property`\n * @param {number} bounds.end - end value of the `property`\n * @private\n */\nexport function _boundSegments(line, bounds) {\n const result = [];\n const segments = line.segments;\n\n for (let i = 0; i < segments.length; i++) {\n const sub = _boundSegment(segments[i], line.points, bounds);\n if (sub.length) {\n result.push(...sub);\n }\n }\n return result;\n}\n\n/**\n * Find start and end index of a line.\n */\nfunction findStartAndEnd(points, count, loop, spanGaps) {\n let start = 0;\n let end = count - 1;\n\n if (loop && !spanGaps) {\n // loop and not spanning gaps, first find a gap to start from\n while (start < count && !points[start].skip) {\n start++;\n }\n }\n\n // find first non skipped point (after the first gap possibly)\n while (start < count && points[start].skip) {\n start++;\n }\n\n // if we looped to count, start needs to be 0\n start %= count;\n\n if (loop) {\n // loop will go past count, if start > 0\n end += start;\n }\n\n while (end > start && points[end % count].skip) {\n end--;\n }\n\n // end could be more than count, normalize\n end %= count;\n\n return {start, end};\n}\n\n/**\n * Compute solid segments from Points, when spanGaps === false\n * @param {PointElement[]} points - the points\n * @param {number} start - start index\n * @param {number} max - max index (can go past count on a loop)\n * @param {boolean} loop - boolean indicating that this would be a loop if no gaps are found\n */\nfunction solidSegments(points, start, max, loop) {\n const count = points.length;\n const result = [];\n let last = start;\n let prev = points[start];\n let end;\n\n for (end = start + 1; end <= max; ++end) {\n const cur = points[end % count];\n if (cur.skip || cur.stop) {\n if (!prev.skip) {\n loop = false;\n result.push({start: start % count, end: (end - 1) % count, loop});\n // @ts-ignore\n start = last = cur.stop ? end : null;\n }\n } else {\n last = end;\n if (prev.skip) {\n start = end;\n }\n }\n prev = cur;\n }\n\n if (last !== null) {\n result.push({start: start % count, end: last % count, loop});\n }\n\n return result;\n}\n\n/**\n * Compute the continuous segments that define the whole line\n * There can be skipped points within a segment, if spanGaps is true.\n * @param {LineElement} line\n * @param {object} [segmentOptions]\n * @return {Segment[]}\n * @private\n */\nexport function _computeSegments(line, segmentOptions) {\n const points = line.points;\n const spanGaps = line.options.spanGaps;\n const count = points.length;\n\n if (!count) {\n return [];\n }\n\n const loop = !!line._loop;\n const {start, end} = findStartAndEnd(points, count, loop, spanGaps);\n\n if (spanGaps === true) {\n return splitByStyles(line, [{start, end, loop}], points, segmentOptions);\n }\n\n const max = end < start ? end + count : end;\n const completeLoop = !!line._fullLoop && start === 0 && end === count - 1;\n return splitByStyles(line, solidSegments(points, start, max, completeLoop), points, segmentOptions);\n}\n\n/**\n * @param {Segment[]} segments\n * @param {PointElement[]} points\n * @param {object} [segmentOptions]\n * @return {Segment[]}\n */\nfunction splitByStyles(line, segments, points, segmentOptions) {\n if (!segmentOptions || !segmentOptions.setContext || !points) {\n return segments;\n }\n return doSplitByStyles(line, segments, points, segmentOptions);\n}\n\n/**\n * @param {LineElement} line\n * @param {Segment[]} segments\n * @param {PointElement[]} points\n * @param {object} [segmentOptions]\n * @return {Segment[]}\n */\nfunction doSplitByStyles(line, segments, points, segmentOptions) {\n const chartContext = line._chart.getContext();\n const baseStyle = readStyle(line.options);\n const {_datasetIndex: datasetIndex, options: {spanGaps}} = line;\n const count = points.length;\n const result = [];\n let prevStyle = baseStyle;\n let start = segments[0].start;\n let i = start;\n\n function addStyle(s, e, l, st) {\n const dir = spanGaps ? -1 : 1;\n if (s === e) {\n return;\n }\n // Style can not start/end on a skipped point, adjust indices accordingly\n s += count;\n while (points[s % count].skip) {\n s -= dir;\n }\n while (points[e % count].skip) {\n e += dir;\n }\n if (s % count !== e % count) {\n result.push({start: s % count, end: e % count, loop: l, style: st});\n prevStyle = st;\n start = e % count;\n }\n }\n\n for (const segment of segments) {\n start = spanGaps ? start : segment.start;\n let prev = points[start % count];\n let style;\n for (i = start + 1; i <= segment.end; i++) {\n const pt = points[i % count];\n style = readStyle(segmentOptions.setContext(createContext(chartContext, {\n type: 'segment',\n p0: prev,\n p1: pt,\n p0DataIndex: (i - 1) % count,\n p1DataIndex: i % count,\n datasetIndex\n })));\n if (styleChanged(style, prevStyle)) {\n addStyle(start, i - 1, segment.loop, prevStyle);\n }\n prev = pt;\n prevStyle = style;\n }\n if (start < i - 1) {\n addStyle(start, i - 1, segment.loop, prevStyle);\n }\n }\n\n return result;\n}\n\nfunction readStyle(options) {\n return {\n backgroundColor: options.backgroundColor,\n borderCapStyle: options.borderCapStyle,\n borderDash: options.borderDash,\n borderDashOffset: options.borderDashOffset,\n borderJoinStyle: options.borderJoinStyle,\n borderWidth: options.borderWidth,\n borderColor: options.borderColor\n };\n}\n\nfunction styleChanged(style, prevStyle) {\n if (!prevStyle) {\n return false;\n }\n const cache = [];\n const replacer = function(key, value) {\n if (!isPatternOrGradient(value)) {\n return value;\n }\n if (!cache.includes(value)) {\n cache.push(value);\n }\n return cache.indexOf(value);\n };\n return JSON.stringify(style, replacer) !== JSON.stringify(prevStyle, replacer);\n}\n","import type {Chart, ChartArea, ChartMeta, Scale, TRBL} from '../types/index.js';\n\nfunction getSizeForArea(scale: Scale, chartArea: ChartArea, field: keyof ChartArea) {\n return scale.options.clip ? scale[field] : chartArea[field];\n}\n\nfunction getDatasetArea(meta: ChartMeta, chartArea: ChartArea): TRBL {\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\nexport function getDatasetClipArea(chart: Chart, meta: ChartMeta): TRBL | false {\n const clip = meta._clip;\n if (clip.disabled) {\n return false;\n }\n const area = getDatasetArea(meta, chart.chartArea);\n\n return {\n left: clip.left === false ? 0 : area.left - (clip.left === true ? 0 : clip.left),\n right: clip.right === false ? chart.width : area.right + (clip.right === true ? 0 : clip.right),\n top: clip.top === false ? 0 : area.top - (clip.top === true ? 0 : clip.top),\n bottom: clip.bottom === false ? chart.height : area.bottom + (clip.bottom === true ? 0 : clip.bottom)\n };\n}\n","import {_lookupByKey, _rlookupByKey} from '../helpers/helpers.collection.js';\nimport {getRelativePosition} from '../helpers/helpers.dom.js';\nimport {_angleBetween, getAngleFromPoint} from '../helpers/helpers.math.js';\nimport {_isPointInArea, isNullOrUndef} from '../helpers/index.js';\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n * @typedef { import('../types/index.js').ChartEvent } ChartEvent\n * @typedef {{axis?: string, intersect?: boolean, includeInvisible?: boolean}} InteractionOptions\n * @typedef {{datasetIndex: number, index: number, element: import('./core.element.js').default}} InteractionItem\n * @typedef { import('../types/index.js').Point } Point\n */\n\n/**\n * Helper function to do binary search when possible\n * @param {object} metaset - the dataset meta\n * @param {string} axis - the axis mode. x|y|xy|r\n * @param {number} value - the value to find\n * @param {boolean} [intersect] - should the element intersect\n * @returns {{lo:number, hi:number}} indices to search data array between\n */\nfunction binarySearch(metaset, axis, value, intersect) {\n const {controller, data, _sorted} = metaset;\n const iScale = controller._cachedMeta.iScale;\n const spanGaps = metaset.dataset ? metaset.dataset.options ? metaset.dataset.options.spanGaps : null : null;\n\n if (iScale && axis === iScale.axis && axis !== 'r' && _sorted && data.length) {\n const lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey;\n if (!intersect) {\n const result = lookupMethod(data, axis, value);\n if (spanGaps) {\n const {vScale} = controller._cachedMeta;\n const {_parsed} = metaset;\n\n const distanceToDefinedLo = (_parsed\n .slice(0, result.lo + 1)\n .reverse()\n .findIndex(\n point => !isNullOrUndef(point[vScale.axis])));\n result.lo -= Math.max(0, distanceToDefinedLo);\n\n const distanceToDefinedHi = (_parsed\n .slice(result.hi)\n .findIndex(\n point => !isNullOrUndef(point[vScale.axis])));\n result.hi += Math.max(0, distanceToDefinedHi);\n }\n return result;\n } else if (controller._sharedOptions) {\n // _sharedOptions indicates that each element has equal options -> equal proportions\n // So we can do a ranged binary search based on the range of first element and\n // be confident to get the full range of indices that can intersect with the value.\n const el = data[0];\n const range = typeof el.getRange === 'function' && el.getRange(axis);\n if (range) {\n const start = lookupMethod(data, axis, value - range);\n const end = lookupMethod(data, axis, value + range);\n return {lo: start.lo, hi: end.hi};\n }\n }\n }\n // Default to all elements, when binary search can not be used.\n return {lo: 0, hi: data.length - 1};\n}\n\n/**\n * Helper function to select candidate elements for interaction\n * @param {Chart} chart - the chart\n * @param {string} axis - the axis mode. x|y|xy|r\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {function} handler - the callback to execute for each visible item\n * @param {boolean} [intersect] - consider intersecting items\n */\nfunction evaluateInteractionItems(chart, axis, position, handler, intersect) {\n const metasets = chart.getSortedVisibleDatasetMetas();\n const value = position[axis];\n for (let i = 0, ilen = metasets.length; i < ilen; ++i) {\n const {index, data} = metasets[i];\n const {lo, hi} = binarySearch(metasets[i], axis, value, intersect);\n for (let j = lo; j <= hi; ++j) {\n const element = data[j];\n if (!element.skip) {\n handler(element, index, j);\n }\n }\n }\n}\n\n/**\n * Get a distance metric function for two points based on the\n * axis mode setting\n * @param {string} axis - the axis mode. x|y|xy|r\n */\nfunction getDistanceMetricForAxis(axis) {\n const useX = axis.indexOf('x') !== -1;\n const useY = axis.indexOf('y') !== -1;\n\n return function(pt1, pt2) {\n const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;\n const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;\n return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));\n };\n}\n\n/**\n * Helper function to get the items that intersect the event position\n * @param {Chart} chart - the chart\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axis mode. x|y|xy|r\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @param {boolean} [includeInvisible] - include invisible points that are outside of the chart area\n * @return {InteractionItem[]} the nearest items\n */\nfunction getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) {\n const items = [];\n\n if (!includeInvisible && !chart.isPointInArea(position)) {\n return items;\n }\n\n const evaluationFunc = function(element, datasetIndex, index) {\n if (!includeInvisible && !_isPointInArea(element, chart.chartArea, 0)) {\n return;\n }\n if (element.inRange(position.x, position.y, useFinalPosition)) {\n items.push({element, datasetIndex, index});\n }\n };\n\n evaluateInteractionItems(chart, axis, position, evaluationFunc, true);\n return items;\n}\n\n/**\n * Helper function to get the items nearest to the event position for a radial chart\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axes along which to measure distance\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @return {InteractionItem[]} the nearest items\n */\nfunction getNearestRadialItems(chart, position, axis, useFinalPosition) {\n let items = [];\n\n function evaluationFunc(element, datasetIndex, index) {\n const {startAngle, endAngle} = element.getProps(['startAngle', 'endAngle'], useFinalPosition);\n const {angle} = getAngleFromPoint(element, {x: position.x, y: position.y});\n\n if (_angleBetween(angle, startAngle, endAngle)) {\n items.push({element, datasetIndex, index});\n }\n }\n\n evaluateInteractionItems(chart, axis, position, evaluationFunc);\n return items;\n}\n\n/**\n * Helper function to get the items nearest to the event position for a cartesian chart\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axes along which to measure distance\n * @param {boolean} [intersect] - if true, only consider items that intersect the position\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @param {boolean} [includeInvisible] - include invisible points that are outside of the chart area\n * @return {InteractionItem[]} the nearest items\n */\nfunction getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {\n let items = [];\n const distanceMetric = getDistanceMetricForAxis(axis);\n let minDistance = Number.POSITIVE_INFINITY;\n\n function evaluationFunc(element, datasetIndex, index) {\n const inRange = element.inRange(position.x, position.y, useFinalPosition);\n if (intersect && !inRange) {\n return;\n }\n\n const center = element.getCenterPoint(useFinalPosition);\n const pointInArea = !!includeInvisible || chart.isPointInArea(center);\n if (!pointInArea && !inRange) {\n return;\n }\n\n const distance = distanceMetric(position, center);\n if (distance < minDistance) {\n items = [{element, datasetIndex, index}];\n minDistance = distance;\n } else if (distance === minDistance) {\n // Can have multiple items at the same distance in which case we sort by size\n items.push({element, datasetIndex, index});\n }\n }\n\n evaluateInteractionItems(chart, axis, position, evaluationFunc);\n return items;\n}\n\n/**\n * Helper function to get the items nearest to the event position considering all visible items in the chart\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axes along which to measure distance\n * @param {boolean} [intersect] - if true, only consider items that intersect the position\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @param {boolean} [includeInvisible] - include invisible points that are outside of the chart area\n * @return {InteractionItem[]} the nearest items\n */\nfunction getNearestItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {\n if (!includeInvisible && !chart.isPointInArea(position)) {\n return [];\n }\n\n return axis === 'r' && !intersect\n ? getNearestRadialItems(chart, position, axis, useFinalPosition)\n : getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible);\n}\n\n/**\n * Helper function to get the items matching along the given X or Y axis\n * @param {Chart} chart - the chart to look at elements from\n * @param {Point} position - the point to be nearest to, in relative coordinates\n * @param {string} axis - the axis to match\n * @param {boolean} [intersect] - if true, only consider items that intersect the position\n * @param {boolean} [useFinalPosition] - use the element's animation target instead of current position\n * @return {InteractionItem[]} the nearest items\n */\nfunction getAxisItems(chart, position, axis, intersect, useFinalPosition) {\n const items = [];\n const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange';\n let intersectsItem = false;\n\n evaluateInteractionItems(chart, axis, position, (element, datasetIndex, index) => {\n if (element[rangeMethod] && element[rangeMethod](position[axis], useFinalPosition)) {\n items.push({element, datasetIndex, index});\n intersectsItem = intersectsItem || element.inRange(position.x, position.y, useFinalPosition);\n }\n });\n\n // If we want to trigger on an intersect and we don't have any items\n // that intersect the position, return nothing\n if (intersect && !intersectsItem) {\n return [];\n }\n return items;\n}\n\n/**\n * Contains interaction related functions\n * @namespace Chart.Interaction\n */\nexport default {\n // Part of the public API to facilitate developers creating their own modes\n evaluateInteractionItems,\n\n // Helper function for different modes\n modes: {\n /**\n\t\t * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something\n\t\t * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item\n\t\t * @function Chart.Interaction.modes.index\n\t\t * @since v2.4.0\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n index(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n // Default axis for index mode is 'x' to match old behaviour\n const axis = options.axis || 'x';\n const includeInvisible = options.includeInvisible || false;\n const items = options.intersect\n ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible)\n : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);\n const elements = [];\n\n if (!items.length) {\n return [];\n }\n\n chart.getSortedVisibleDatasetMetas().forEach((meta) => {\n const index = items[0].index;\n const element = meta.data[index];\n\n // don't count items that are skipped (null data)\n if (element && !element.skip) {\n elements.push({element, datasetIndex: meta.index, index});\n }\n });\n\n return elements;\n },\n\n /**\n\t\t * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something\n\t\t * If the options.intersect is false, we find the nearest item and return the items in that dataset\n\t\t * @function Chart.Interaction.modes.dataset\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n dataset(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'xy';\n const includeInvisible = options.includeInvisible || false;\n let items = options.intersect\n ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) :\n getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);\n\n if (items.length > 0) {\n const datasetIndex = items[0].datasetIndex;\n const data = chart.getDatasetMeta(datasetIndex).data;\n items = [];\n for (let i = 0; i < data.length; ++i) {\n items.push({element: data[i], datasetIndex, index: i});\n }\n }\n\n return items;\n },\n\n /**\n\t\t * Point mode returns all elements that hit test based on the event position\n\t\t * of the event\n\t\t * @function Chart.Interaction.modes.intersect\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n point(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'xy';\n const includeInvisible = options.includeInvisible || false;\n return getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible);\n },\n\n /**\n\t\t * nearest mode returns the element closest to the point\n\t\t * @function Chart.Interaction.modes.intersect\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n nearest(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n const axis = options.axis || 'xy';\n const includeInvisible = options.includeInvisible || false;\n return getNearestItems(chart, position, axis, options.intersect, useFinalPosition, includeInvisible);\n },\n\n /**\n\t\t * x mode returns the elements that hit-test at the current x coordinate\n\t\t * @function Chart.Interaction.modes.x\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n x(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n return getAxisItems(chart, position, 'x', options.intersect, useFinalPosition);\n },\n\n /**\n\t\t * y mode returns the elements that hit-test at the current y coordinate\n\t\t * @function Chart.Interaction.modes.y\n\t\t * @param {Chart} chart - the chart we are returning items from\n\t\t * @param {Event} e - the event we are find things at\n\t\t * @param {InteractionOptions} options - options to use\n\t\t * @param {boolean} [useFinalPosition] - use final element position (animation target)\n\t\t * @return {InteractionItem[]} - items that are found\n\t\t */\n y(chart, e, options, useFinalPosition) {\n const position = getRelativePosition(e, chart);\n return getAxisItems(chart, position, 'y', options.intersect, useFinalPosition);\n }\n }\n};\n","import {defined, each, isObject} from '../helpers/helpers.core.js';\nimport {toPadding} from '../helpers/helpers.options.js';\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n */\n\nconst STATIC_POSITIONS = ['left', 'top', 'right', 'bottom'];\n\nfunction filterByPosition(array, position) {\n return array.filter(v => v.pos === position);\n}\n\nfunction filterDynamicPositionByAxis(array, axis) {\n return array.filter(v => STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis);\n}\n\nfunction sortByWeight(array, reverse) {\n return array.sort((a, b) => {\n const v0 = reverse ? b : a;\n const v1 = reverse ? a : b;\n return v0.weight === v1.weight ?\n v0.index - v1.index :\n v0.weight - v1.weight;\n });\n}\n\nfunction wrapBoxes(boxes) {\n const layoutBoxes = [];\n let i, ilen, box, pos, stack, stackWeight;\n\n for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {\n box = boxes[i];\n ({position: pos, options: {stack, stackWeight = 1}} = box);\n layoutBoxes.push({\n index: i,\n box,\n pos,\n horizontal: box.isHorizontal(),\n weight: box.weight,\n stack: stack && (pos + stack),\n stackWeight\n });\n }\n return layoutBoxes;\n}\n\nfunction buildStacks(layouts) {\n const stacks = {};\n for (const wrap of layouts) {\n const {stack, pos, stackWeight} = wrap;\n if (!stack || !STATIC_POSITIONS.includes(pos)) {\n continue;\n }\n const _stack = stacks[stack] || (stacks[stack] = {count: 0, placed: 0, weight: 0, size: 0});\n _stack.count++;\n _stack.weight += stackWeight;\n }\n return stacks;\n}\n\n/**\n * store dimensions used instead of available chartArea in fitBoxes\n **/\nfunction setLayoutDims(layouts, params) {\n const stacks = buildStacks(layouts);\n const {vBoxMaxWidth, hBoxMaxHeight} = params;\n let i, ilen, layout;\n for (i = 0, ilen = layouts.length; i < ilen; ++i) {\n layout = layouts[i];\n const {fullSize} = layout.box;\n const stack = stacks[layout.stack];\n const factor = stack && layout.stackWeight / stack.weight;\n if (layout.horizontal) {\n layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth;\n layout.height = hBoxMaxHeight;\n } else {\n layout.width = vBoxMaxWidth;\n layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight;\n }\n }\n return stacks;\n}\n\nfunction buildLayoutBoxes(boxes) {\n const layoutBoxes = wrapBoxes(boxes);\n const fullSize = sortByWeight(layoutBoxes.filter(wrap => wrap.box.fullSize), true);\n const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);\n const right = sortByWeight(filterByPosition(layoutBoxes, 'right'));\n const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);\n const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));\n const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x');\n const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y');\n\n return {\n fullSize,\n leftAndTop: left.concat(top),\n rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal),\n chartArea: filterByPosition(layoutBoxes, 'chartArea'),\n vertical: left.concat(right).concat(centerVertical),\n horizontal: top.concat(bottom).concat(centerHorizontal)\n };\n}\n\nfunction getCombinedMax(maxPadding, chartArea, a, b) {\n return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);\n}\n\nfunction updateMaxPadding(maxPadding, boxPadding) {\n maxPadding.top = Math.max(maxPadding.top, boxPadding.top);\n maxPadding.left = Math.max(maxPadding.left, boxPadding.left);\n maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);\n maxPadding.right = Math.max(maxPadding.right, boxPadding.right);\n}\n\nfunction updateDims(chartArea, params, layout, stacks) {\n const {pos, box} = layout;\n const maxPadding = chartArea.maxPadding;\n\n // dynamically placed boxes size is not considered\n if (!isObject(pos)) {\n if (layout.size) {\n // this layout was already counted for, lets first reduce old size\n chartArea[pos] -= layout.size;\n }\n const stack = stacks[layout.stack] || {size: 0, count: 1};\n stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width);\n layout.size = stack.size / stack.count;\n chartArea[pos] += layout.size;\n }\n\n if (box.getPadding) {\n updateMaxPadding(maxPadding, box.getPadding());\n }\n\n const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right'));\n const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom'));\n const widthChanged = newWidth !== chartArea.w;\n const heightChanged = newHeight !== chartArea.h;\n chartArea.w = newWidth;\n chartArea.h = newHeight;\n\n // return booleans on the changes per direction\n return layout.horizontal\n ? {same: widthChanged, other: heightChanged}\n : {same: heightChanged, other: widthChanged};\n}\n\nfunction handleMaxPadding(chartArea) {\n const maxPadding = chartArea.maxPadding;\n\n function updatePos(pos) {\n const change = Math.max(maxPadding[pos] - chartArea[pos], 0);\n chartArea[pos] += change;\n return change;\n }\n chartArea.y += updatePos('top');\n chartArea.x += updatePos('left');\n updatePos('right');\n updatePos('bottom');\n}\n\nfunction getMargins(horizontal, chartArea) {\n const maxPadding = chartArea.maxPadding;\n\n function marginForPositions(positions) {\n const margin = {left: 0, top: 0, right: 0, bottom: 0};\n positions.forEach((pos) => {\n margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);\n });\n return margin;\n }\n\n return horizontal\n ? marginForPositions(['left', 'right'])\n : marginForPositions(['top', 'bottom']);\n}\n\nfunction fitBoxes(boxes, chartArea, params, stacks) {\n const refitBoxes = [];\n let i, ilen, layout, box, refit, changed;\n\n for (i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i) {\n layout = boxes[i];\n box = layout.box;\n\n box.update(\n layout.width || chartArea.w,\n layout.height || chartArea.h,\n getMargins(layout.horizontal, chartArea)\n );\n const {same, other} = updateDims(chartArea, params, layout, stacks);\n\n // Dimensions changed and there were non full width boxes before this\n // -> we have to refit those\n refit |= same && refitBoxes.length;\n\n // Chart area changed in the opposite direction\n changed = changed || other;\n\n if (!box.fullSize) { // fullSize boxes don't need to be re-fitted in any case\n refitBoxes.push(layout);\n }\n }\n\n return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed;\n}\n\nfunction setBoxDims(box, left, top, width, height) {\n box.top = top;\n box.left = left;\n box.right = left + width;\n box.bottom = top + height;\n box.width = width;\n box.height = height;\n}\n\nfunction placeBoxes(boxes, chartArea, params, stacks) {\n const userPadding = params.padding;\n let {x, y} = chartArea;\n\n for (const layout of boxes) {\n const box = layout.box;\n const stack = stacks[layout.stack] || {count: 1, placed: 0, weight: 1};\n const weight = (layout.stackWeight / stack.weight) || 1;\n if (layout.horizontal) {\n const width = chartArea.w * weight;\n const height = stack.size || box.height;\n if (defined(stack.start)) {\n y = stack.start;\n }\n if (box.fullSize) {\n setBoxDims(box, userPadding.left, y, params.outerWidth - userPadding.right - userPadding.left, height);\n } else {\n setBoxDims(box, chartArea.left + stack.placed, y, width, height);\n }\n stack.start = y;\n stack.placed += width;\n y = box.bottom;\n } else {\n const height = chartArea.h * weight;\n const width = stack.size || box.width;\n if (defined(stack.start)) {\n x = stack.start;\n }\n if (box.fullSize) {\n setBoxDims(box, x, userPadding.top, width, params.outerHeight - userPadding.bottom - userPadding.top);\n } else {\n setBoxDims(box, x, chartArea.top + stack.placed, width, height);\n }\n stack.start = x;\n stack.placed += height;\n x = box.right;\n }\n }\n\n chartArea.x = x;\n chartArea.y = y;\n}\n\n/**\n * @interface LayoutItem\n * @typedef {object} LayoutItem\n * @prop {string} position - The position of the item in the chart layout. Possible values are\n * 'left', 'top', 'right', 'bottom', and 'chartArea'\n * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area\n * @prop {boolean} fullSize - if true, and the item is horizontal, then push vertical boxes down\n * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)\n * @prop {function} update - Takes two parameters: width and height. Returns size of item\n * @prop {function} draw - Draws the element\n * @prop {function} [getPadding] - Returns an object with padding on the edges\n * @prop {number} width - Width of item. Must be valid after update()\n * @prop {number} height - Height of item. Must be valid after update()\n * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update\n * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update\n * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update\n * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update\n */\n\n// The layout service is very self explanatory. It's responsible for the layout within a chart.\n// Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need\n// It is this service's responsibility of carrying out that layout.\nexport default {\n\n /**\n\t * Register a box to a chart.\n\t * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.\n\t * @param {Chart} chart - the chart to use\n\t * @param {LayoutItem} item - the item to add to be laid out\n\t */\n addBox(chart, item) {\n if (!chart.boxes) {\n chart.boxes = [];\n }\n\n // initialize item with default values\n item.fullSize = item.fullSize || false;\n item.position = item.position || 'top';\n item.weight = item.weight || 0;\n // @ts-ignore\n item._layers = item._layers || function() {\n return [{\n z: 0,\n draw(chartArea) {\n item.draw(chartArea);\n }\n }];\n };\n\n chart.boxes.push(item);\n },\n\n /**\n\t * Remove a layoutItem from a chart\n\t * @param {Chart} chart - the chart to remove the box from\n\t * @param {LayoutItem} layoutItem - the item to remove from the layout\n\t */\n removeBox(chart, layoutItem) {\n const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;\n if (index !== -1) {\n chart.boxes.splice(index, 1);\n }\n },\n\n /**\n\t * Sets (or updates) options on the given `item`.\n\t * @param {Chart} chart - the chart in which the item lives (or will be added to)\n\t * @param {LayoutItem} item - the item to configure with the given options\n\t * @param {object} options - the new item options.\n\t */\n configure(chart, item, options) {\n item.fullSize = options.fullSize;\n item.position = options.position;\n item.weight = options.weight;\n },\n\n /**\n\t * Fits boxes of the given chart into the given size by having each box measure itself\n\t * then running a fitting algorithm\n\t * @param {Chart} chart - the chart\n\t * @param {number} width - the width to fit into\n\t * @param {number} height - the height to fit into\n * @param {number} minPadding - minimum padding required for each side of chart area\n\t */\n update(chart, width, height, minPadding) {\n if (!chart) {\n return;\n }\n\n const padding = toPadding(chart.options.layout.padding);\n const availableWidth = Math.max(width - padding.width, 0);\n const availableHeight = Math.max(height - padding.height, 0);\n const boxes = buildLayoutBoxes(chart.boxes);\n const verticalBoxes = boxes.vertical;\n const horizontalBoxes = boxes.horizontal;\n\n // Before any changes are made, notify boxes that an update is about to being\n // This is used to clear any cached data (e.g. scale limits)\n each(chart.boxes, box => {\n if (typeof box.beforeLayout === 'function') {\n box.beforeLayout();\n }\n });\n\n // Essentially we now have any number of boxes on each of the 4 sides.\n // Our canvas looks like the following.\n // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and\n // B1 is the bottom axis\n // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays\n // These locations are single-box locations only, when trying to register a chartArea location that is already taken,\n // an error will be thrown.\n //\n // |----------------------------------------------------|\n // | T1 (Full Width) |\n // |----------------------------------------------------|\n // | | | T2 | |\n // | |----|-------------------------------------|----|\n // | | | C1 | | C2 | |\n // | | |----| |----| |\n // | | | | |\n // | L1 | L2 | ChartArea (C0) | R1 |\n // | | | | |\n // | | |----| |----| |\n // | | | C3 | | C4 | |\n // | |----|-------------------------------------|----|\n // | | | B1 | |\n // |----------------------------------------------------|\n // | B2 (Full Width) |\n // |----------------------------------------------------|\n //\n\n const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap) =>\n wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1;\n\n const params = Object.freeze({\n outerWidth: width,\n outerHeight: height,\n padding,\n availableWidth,\n availableHeight,\n vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount,\n hBoxMaxHeight: availableHeight / 2\n });\n const maxPadding = Object.assign({}, padding);\n updateMaxPadding(maxPadding, toPadding(minPadding));\n const chartArea = Object.assign({\n maxPadding,\n w: availableWidth,\n h: availableHeight,\n x: padding.left,\n y: padding.top\n }, padding);\n\n const stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);\n\n // First fit the fullSize boxes, to reduce probability of re-fitting.\n fitBoxes(boxes.fullSize, chartArea, params, stacks);\n\n // Then fit vertical boxes\n fitBoxes(verticalBoxes, chartArea, params, stacks);\n\n // Then fit horizontal boxes\n if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) {\n // if the area changed, re-fit vertical boxes\n fitBoxes(verticalBoxes, chartArea, params, stacks);\n }\n\n handleMaxPadding(chartArea);\n\n // Finally place the boxes to correct coordinates\n placeBoxes(boxes.leftAndTop, chartArea, params, stacks);\n\n // Move to opposite side of chart\n chartArea.x += chartArea.w;\n chartArea.y += chartArea.h;\n\n placeBoxes(boxes.rightAndBottom, chartArea, params, stacks);\n\n chart.chartArea = {\n left: chartArea.left,\n top: chartArea.top,\n right: chartArea.left + chartArea.w,\n bottom: chartArea.top + chartArea.h,\n height: chartArea.h,\n width: chartArea.w,\n };\n\n // Finally update boxes in chartArea (radial scale for example)\n each(boxes.chartArea, (layout) => {\n const box = layout.box;\n Object.assign(box, chart.chartArea);\n box.update(chartArea.w, chartArea.h, {left: 0, top: 0, right: 0, bottom: 0});\n });\n }\n};\n","\n/**\n * @typedef { import('../core/core.controller.js').default } Chart\n */\n\n/**\n * Abstract class that allows abstracting platform dependencies away from the chart.\n */\nexport default class BasePlatform {\n /**\n\t * Called at chart construction time, returns a context2d instance implementing\n\t * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.\n\t * @param {HTMLCanvasElement} canvas - The canvas from which to acquire context (platform specific)\n\t * @param {number} [aspectRatio] - The chart options\n\t */\n acquireContext(canvas, aspectRatio) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * Called at chart destruction time, releases any resources associated to the context\n\t * previously returned by the acquireContext() method.\n\t * @param {CanvasRenderingContext2D} context - The context2d instance\n\t * @returns {boolean} true if the method succeeded, else false\n\t */\n releaseContext(context) { // eslint-disable-line no-unused-vars\n return false;\n }\n\n /**\n\t * Registers the specified listener on the given chart.\n\t * @param {Chart} chart - Chart from which to listen for event\n\t * @param {string} type - The ({@link ChartEvent}) type to listen for\n\t * @param {function} listener - Receives a notification (an object that implements\n\t * the {@link ChartEvent} interface) when an event of the specified type occurs.\n\t */\n addEventListener(chart, type, listener) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * Removes the specified listener previously registered with addEventListener.\n\t * @param {Chart} chart - Chart from which to remove the listener\n\t * @param {string} type - The ({@link ChartEvent}) type to remove\n\t * @param {function} listener - The listener function to remove from the event target.\n\t */\n removeEventListener(chart, type, listener) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * @returns {number} the current devicePixelRatio of the device this platform is connected to.\n\t */\n getDevicePixelRatio() {\n return 1;\n }\n\n /**\n\t * Returns the maximum size in pixels of given canvas element.\n\t * @param {HTMLCanvasElement} element\n\t * @param {number} [width] - content width of parent element\n\t * @param {number} [height] - content height of parent element\n\t * @param {number} [aspectRatio] - aspect ratio to maintain\n\t */\n getMaximumSize(element, width, height, aspectRatio) {\n width = Math.max(0, width || element.width);\n height = height || element.height;\n return {\n width,\n height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height)\n };\n }\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t * @returns {boolean} true if the canvas is attached to the platform, false if not.\n\t */\n isAttached(canvas) { // eslint-disable-line no-unused-vars\n return true;\n }\n\n /**\n * Updates config with platform specific requirements\n * @param {import('../core/core.config.js').default} config\n */\n updateConfig(config) { // eslint-disable-line no-unused-vars\n // no-op\n }\n}\n","/**\n * Platform fallback implementation (minimal).\n * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939\n */\n\nimport BasePlatform from './platform.base.js';\n\n/**\n * Platform class for charts without access to the DOM or to many element properties\n * This platform is used by default for any chart passed an OffscreenCanvas.\n * @extends BasePlatform\n */\nexport default class BasicPlatform extends BasePlatform {\n acquireContext(item) {\n // To prevent canvas fingerprinting, some add-ons undefine the getContext\n // method, for example: https://github.com/kkapsner/CanvasBlocker\n // https://github.com/chartjs/Chart.js/issues/2807\n return item && item.getContext && item.getContext('2d') || null;\n }\n updateConfig(config) {\n config.options.animation = false;\n }\n}\n","/**\n * Chart.Platform implementation for targeting a web browser\n */\n\nimport BasePlatform from './platform.base.js';\nimport {_getParentNode, getRelativePosition, supportsEventListenerOptions, readUsedSize, getMaximumSize} from '../helpers/helpers.dom.js';\nimport {throttled} from '../helpers/helpers.extras.js';\nimport {isNullOrUndef} from '../helpers/helpers.core.js';\n\n/**\n * @typedef { import('../core/core.controller.js').default } Chart\n */\n\nconst EXPANDO_KEY = '$chartjs';\n\n/**\n * DOM event types -> Chart.js event types.\n * Note: only events with different types are mapped.\n * @see https://developer.mozilla.org/en-US/docs/Web/Events\n */\nconst EVENT_TYPES = {\n touchstart: 'mousedown',\n touchmove: 'mousemove',\n touchend: 'mouseup',\n pointerenter: 'mouseenter',\n pointerdown: 'mousedown',\n pointermove: 'mousemove',\n pointerup: 'mouseup',\n pointerleave: 'mouseout',\n pointerout: 'mouseout'\n};\n\nconst isNullOrEmpty = value => value === null || value === '';\n/**\n * Initializes the canvas style and render size without modifying the canvas display size,\n * since responsiveness is handled by the controller.resize() method. The config is used\n * to determine the aspect ratio to apply in case no explicit height has been specified.\n * @param {HTMLCanvasElement} canvas\n * @param {number} [aspectRatio]\n */\nfunction initCanvas(canvas, aspectRatio) {\n const style = canvas.style;\n\n // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it\n // returns null or '' if no explicit value has been set to the canvas attribute.\n const renderHeight = canvas.getAttribute('height');\n const renderWidth = canvas.getAttribute('width');\n\n // Chart.js modifies some canvas values that we want to restore on destroy\n canvas[EXPANDO_KEY] = {\n initial: {\n height: renderHeight,\n width: renderWidth,\n style: {\n display: style.display,\n height: style.height,\n width: style.width\n }\n }\n };\n\n // Force canvas to display as block to avoid extra space caused by inline\n // elements, which would interfere with the responsive resize process.\n // https://github.com/chartjs/Chart.js/issues/2538\n style.display = style.display || 'block';\n // Include possible borders in the size\n style.boxSizing = style.boxSizing || 'border-box';\n\n if (isNullOrEmpty(renderWidth)) {\n const displayWidth = readUsedSize(canvas, 'width');\n if (displayWidth !== undefined) {\n canvas.width = displayWidth;\n }\n }\n\n if (isNullOrEmpty(renderHeight)) {\n if (canvas.style.height === '') {\n // If no explicit render height and style height, let's apply the aspect ratio,\n // which one can be specified by the user but also by charts as default option\n // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.\n canvas.height = canvas.width / (aspectRatio || 2);\n } else {\n const displayHeight = readUsedSize(canvas, 'height');\n if (displayHeight !== undefined) {\n canvas.height = displayHeight;\n }\n }\n }\n\n return canvas;\n}\n\n// Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.\n// https://github.com/chartjs/Chart.js/issues/4287\nconst eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;\n\nfunction addListener(node, type, listener) {\n if (node) {\n node.addEventListener(type, listener, eventListenerOptions);\n }\n}\n\nfunction removeListener(chart, type, listener) {\n if (chart && chart.canvas) {\n chart.canvas.removeEventListener(type, listener, eventListenerOptions);\n }\n}\n\nfunction fromNativeEvent(event, chart) {\n const type = EVENT_TYPES[event.type] || event.type;\n const {x, y} = getRelativePosition(event, chart);\n return {\n type,\n chart,\n native: event,\n x: x !== undefined ? x : null,\n y: y !== undefined ? y : null,\n };\n}\n\nfunction nodeListContains(nodeList, canvas) {\n for (const node of nodeList) {\n if (node === canvas || node.contains(canvas)) {\n return true;\n }\n }\n}\n\nfunction createAttachObserver(chart, type, listener) {\n const canvas = chart.canvas;\n const observer = new MutationObserver(entries => {\n let trigger = false;\n for (const entry of entries) {\n trigger = trigger || nodeListContains(entry.addedNodes, canvas);\n trigger = trigger && !nodeListContains(entry.removedNodes, canvas);\n }\n if (trigger) {\n listener();\n }\n });\n observer.observe(document, {childList: true, subtree: true});\n return observer;\n}\n\nfunction createDetachObserver(chart, type, listener) {\n const canvas = chart.canvas;\n const observer = new MutationObserver(entries => {\n let trigger = false;\n for (const entry of entries) {\n trigger = trigger || nodeListContains(entry.removedNodes, canvas);\n trigger = trigger && !nodeListContains(entry.addedNodes, canvas);\n }\n if (trigger) {\n listener();\n }\n });\n observer.observe(document, {childList: true, subtree: true});\n return observer;\n}\n\nconst drpListeningCharts = new Map();\nlet oldDevicePixelRatio = 0;\n\nfunction onWindowResize() {\n const dpr = window.devicePixelRatio;\n if (dpr === oldDevicePixelRatio) {\n return;\n }\n oldDevicePixelRatio = dpr;\n drpListeningCharts.forEach((resize, chart) => {\n if (chart.currentDevicePixelRatio !== dpr) {\n resize();\n }\n });\n}\n\nfunction listenDevicePixelRatioChanges(chart, resize) {\n if (!drpListeningCharts.size) {\n window.addEventListener('resize', onWindowResize);\n }\n drpListeningCharts.set(chart, resize);\n}\n\nfunction unlistenDevicePixelRatioChanges(chart) {\n drpListeningCharts.delete(chart);\n if (!drpListeningCharts.size) {\n window.removeEventListener('resize', onWindowResize);\n }\n}\n\nfunction createResizeObserver(chart, type, listener) {\n const canvas = chart.canvas;\n const container = canvas && _getParentNode(canvas);\n if (!container) {\n return;\n }\n const resize = throttled((width, height) => {\n const w = container.clientWidth;\n listener(width, height);\n if (w < container.clientWidth) {\n // If the container size shrank during chart resize, let's assume\n // scrollbar appeared. So we resize again with the scrollbar visible -\n // effectively making chart smaller and the scrollbar hidden again.\n // Because we are inside `throttled`, and currently `ticking`, scroll\n // events are ignored during this whole 2 resize process.\n // If we assumed wrong and something else happened, we are resizing\n // twice in a frame (potential performance issue)\n listener();\n }\n }, window);\n\n // @ts-ignore until https://github.com/microsoft/TypeScript/issues/37861 implemented\n const observer = new ResizeObserver(entries => {\n const entry = entries[0];\n const width = entry.contentRect.width;\n const height = entry.contentRect.height;\n // When its container's display is set to 'none' the callback will be called with a\n // size of (0, 0), which will cause the chart to lose its original height, so skip\n // resizing in such case.\n if (width === 0 && height === 0) {\n return;\n }\n resize(width, height);\n });\n observer.observe(container);\n listenDevicePixelRatioChanges(chart, resize);\n\n return observer;\n}\n\nfunction releaseObserver(chart, type, observer) {\n if (observer) {\n observer.disconnect();\n }\n if (type === 'resize') {\n unlistenDevicePixelRatioChanges(chart);\n }\n}\n\nfunction createProxyAndListen(chart, type, listener) {\n const canvas = chart.canvas;\n const proxy = throttled((event) => {\n // This case can occur if the chart is destroyed while waiting\n // for the throttled function to occur. We prevent crashes by checking\n // for a destroyed chart\n if (chart.ctx !== null) {\n listener(fromNativeEvent(event, chart));\n }\n }, chart);\n\n addListener(canvas, type, proxy);\n\n return proxy;\n}\n\n/**\n * Platform class for charts that can access the DOM and global window/document properties\n * @extends BasePlatform\n */\nexport default class DomPlatform extends BasePlatform {\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t * @param {number} [aspectRatio]\n\t * @return {CanvasRenderingContext2D|null}\n\t */\n acquireContext(canvas, aspectRatio) {\n // To prevent canvas fingerprinting, some add-ons undefine the getContext\n // method, for example: https://github.com/kkapsner/CanvasBlocker\n // https://github.com/chartjs/Chart.js/issues/2807\n const context = canvas && canvas.getContext && canvas.getContext('2d');\n\n // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the canvas is\n // inside an iframe or when running in a protected environment. We could guess the\n // types from their toString() value but let's keep things flexible and assume it's\n // a sufficient condition if the canvas has a context2D which has canvas as `canvas`.\n // https://github.com/chartjs/Chart.js/issues/3887\n // https://github.com/chartjs/Chart.js/issues/4102\n // https://github.com/chartjs/Chart.js/issues/4152\n if (context && context.canvas === canvas) {\n // Load platform resources on first chart creation, to make it possible to\n // import the library before setting platform options.\n initCanvas(canvas, aspectRatio);\n return context;\n }\n\n return null;\n }\n\n /**\n\t * @param {CanvasRenderingContext2D} context\n\t */\n releaseContext(context) {\n const canvas = context.canvas;\n if (!canvas[EXPANDO_KEY]) {\n return false;\n }\n\n const initial = canvas[EXPANDO_KEY].initial;\n ['height', 'width'].forEach((prop) => {\n const value = initial[prop];\n if (isNullOrUndef(value)) {\n canvas.removeAttribute(prop);\n } else {\n canvas.setAttribute(prop, value);\n }\n });\n\n const style = initial.style || {};\n Object.keys(style).forEach((key) => {\n canvas.style[key] = style[key];\n });\n\n // The canvas render size might have been changed (and thus the state stack discarded),\n // we can't use save() and restore() to restore the initial state. So make sure that at\n // least the canvas context is reset to the default state by setting the canvas width.\n // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html\n // eslint-disable-next-line no-self-assign\n canvas.width = canvas.width;\n\n delete canvas[EXPANDO_KEY];\n return true;\n }\n\n /**\n\t *\n\t * @param {Chart} chart\n\t * @param {string} type\n\t * @param {function} listener\n\t */\n addEventListener(chart, type, listener) {\n // Can have only one listener per type, so make sure previous is removed\n this.removeEventListener(chart, type);\n\n const proxies = chart.$proxies || (chart.$proxies = {});\n const handlers = {\n attach: createAttachObserver,\n detach: createDetachObserver,\n resize: createResizeObserver\n };\n const handler = handlers[type] || createProxyAndListen;\n proxies[type] = handler(chart, type, listener);\n }\n\n\n /**\n\t * @param {Chart} chart\n\t * @param {string} type\n\t */\n removeEventListener(chart, type) {\n const proxies = chart.$proxies || (chart.$proxies = {});\n const proxy = proxies[type];\n\n if (!proxy) {\n return;\n }\n\n const handlers = {\n attach: releaseObserver,\n detach: releaseObserver,\n resize: releaseObserver\n };\n const handler = handlers[type] || removeListener;\n handler(chart, type, proxy);\n proxies[type] = undefined;\n }\n\n getDevicePixelRatio() {\n return window.devicePixelRatio;\n }\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t * @param {number} [width] - content width of parent element\n\t * @param {number} [height] - content height of parent element\n\t * @param {number} [aspectRatio] - aspect ratio to maintain\n\t */\n getMaximumSize(canvas, width, height, aspectRatio) {\n return getMaximumSize(canvas, width, height, aspectRatio);\n }\n\n /**\n\t * @param {HTMLCanvasElement} canvas\n\t */\n isAttached(canvas) {\n const container = canvas && _getParentNode(canvas);\n return !!(container && container.isConnected);\n }\n}\n","import {_isDomSupported} from '../helpers/index.js';\nimport BasePlatform from './platform.base.js';\nimport BasicPlatform from './platform.basic.js';\nimport DomPlatform from './platform.dom.js';\n\nexport function _detectPlatform(canvas) {\n if (!_isDomSupported() || (typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas)) {\n return BasicPlatform;\n }\n return DomPlatform;\n}\n\nexport {BasePlatform, BasicPlatform, DomPlatform};\n","import effects from '../helpers/helpers.easing.js';\nimport {resolve} from '../helpers/helpers.options.js';\nimport {color as helpersColor} from '../helpers/helpers.color.js';\n\nconst transparent = 'transparent';\nconst interpolators = {\n boolean(from, to, factor) {\n return factor > 0.5 ? to : from;\n },\n /**\n * @param {string} from\n * @param {string} to\n * @param {number} factor\n */\n color(from, to, factor) {\n const c0 = helpersColor(from || transparent);\n const c1 = c0.valid && helpersColor(to || transparent);\n return c1 && c1.valid\n ? c1.mix(c0, factor).hexString()\n : to;\n },\n number(from, to, factor) {\n return from + (to - from) * factor;\n }\n};\n\nexport default class Animation {\n constructor(cfg, target, prop, to) {\n const currentValue = target[prop];\n\n to = resolve([cfg.to, to, currentValue, cfg.from]);\n const from = resolve([cfg.from, currentValue, to]);\n\n this._active = true;\n this._fn = cfg.fn || interpolators[cfg.type || typeof from];\n this._easing = effects[cfg.easing] || effects.linear;\n this._start = Math.floor(Date.now() + (cfg.delay || 0));\n this._duration = this._total = Math.floor(cfg.duration);\n this._loop = !!cfg.loop;\n this._target = target;\n this._prop = prop;\n this._from = from;\n this._to = to;\n this._promises = undefined;\n }\n\n active() {\n return this._active;\n }\n\n update(cfg, to, date) {\n if (this._active) {\n this._notify(false);\n\n const currentValue = this._target[this._prop];\n const elapsed = date - this._start;\n const remain = this._duration - elapsed;\n this._start = date;\n this._duration = Math.floor(Math.max(remain, cfg.duration));\n this._total += elapsed;\n this._loop = !!cfg.loop;\n this._to = resolve([cfg.to, to, currentValue, cfg.from]);\n this._from = resolve([cfg.from, currentValue, to]);\n }\n }\n\n cancel() {\n if (this._active) {\n // update current evaluated value, for smoother animations\n this.tick(Date.now());\n this._active = false;\n this._notify(false);\n }\n }\n\n tick(date) {\n const elapsed = date - this._start;\n const duration = this._duration;\n const prop = this._prop;\n const from = this._from;\n const loop = this._loop;\n const to = this._to;\n let factor;\n\n this._active = from !== to && (loop || (elapsed < duration));\n\n if (!this._active) {\n this._target[prop] = to;\n this._notify(true);\n return;\n }\n\n if (elapsed < 0) {\n this._target[prop] = from;\n return;\n }\n\n factor = (elapsed / duration) % 2;\n factor = loop && factor > 1 ? 2 - factor : factor;\n factor = this._easing(Math.min(1, Math.max(0, factor)));\n\n this._target[prop] = this._fn(from, to, factor);\n }\n\n wait() {\n const promises = this._promises || (this._promises = []);\n return new Promise((res, rej) => {\n promises.push({res, rej});\n });\n }\n\n _notify(resolved) {\n const method = resolved ? 'res' : 'rej';\n const promises = this._promises || [];\n for (let i = 0; i < promises.length; i++) {\n promises[i][method]();\n }\n }\n}\n","import animator from './core.animator.js';\nimport Animation from './core.animation.js';\nimport defaults from './core.defaults.js';\nimport {isArray, isObject} from '../helpers/helpers.core.js';\n\nexport default class Animations {\n constructor(chart, config) {\n this._chart = chart;\n this._properties = new Map();\n this.configure(config);\n }\n\n configure(config) {\n if (!isObject(config)) {\n return;\n }\n\n const animationOptions = Object.keys(defaults.animation);\n const animatedProps = this._properties;\n\n Object.getOwnPropertyNames(config).forEach(key => {\n const cfg = config[key];\n if (!isObject(cfg)) {\n return;\n }\n const resolved = {};\n for (const option of animationOptions) {\n resolved[option] = cfg[option];\n }\n\n (isArray(cfg.properties) && cfg.properties || [key]).forEach((prop) => {\n if (prop === key || !animatedProps.has(prop)) {\n animatedProps.set(prop, resolved);\n }\n });\n });\n }\n\n /**\n\t * Utility to handle animation of `options`.\n\t * @private\n\t */\n _animateOptions(target, values) {\n const newOptions = values.options;\n const options = resolveTargetOptions(target, newOptions);\n if (!options) {\n return [];\n }\n\n const animations = this._createAnimations(options, newOptions);\n if (newOptions.$shared) {\n // Going to shared options:\n // After all animations are done, assign the shared options object to the element\n // So any new updates to the shared options are observed\n awaitAll(target.options.$animations, newOptions).then(() => {\n target.options = newOptions;\n }, () => {\n // rejected, noop\n });\n }\n\n return animations;\n }\n\n /**\n\t * @private\n\t */\n _createAnimations(target, values) {\n const animatedProps = this._properties;\n const animations = [];\n const running = target.$animations || (target.$animations = {});\n const props = Object.keys(values);\n const date = Date.now();\n let i;\n\n for (i = props.length - 1; i >= 0; --i) {\n const prop = props[i];\n if (prop.charAt(0) === '$') {\n continue;\n }\n\n if (prop === 'options') {\n animations.push(...this._animateOptions(target, values));\n continue;\n }\n const value = values[prop];\n let animation = running[prop];\n const cfg = animatedProps.get(prop);\n\n if (animation) {\n if (cfg && animation.active()) {\n // There is an existing active animation, let's update that\n animation.update(cfg, value, date);\n continue;\n } else {\n animation.cancel();\n }\n }\n if (!cfg || !cfg.duration) {\n // not animated, set directly to new value\n target[prop] = value;\n continue;\n }\n\n running[prop] = animation = new Animation(cfg, target, prop, value);\n animations.push(animation);\n }\n return animations;\n }\n\n\n /**\n\t * Update `target` properties to new values, using configured animations\n\t * @param {object} target - object to update\n\t * @param {object} values - new target properties\n\t * @returns {boolean|undefined} - `true` if animations were started\n\t **/\n update(target, values) {\n if (this._properties.size === 0) {\n // Nothing is animated, just apply the new values.\n Object.assign(target, values);\n return;\n }\n\n const animations = this._createAnimations(target, values);\n\n if (animations.length) {\n animator.add(this._chart, animations);\n return true;\n }\n }\n}\n\nfunction awaitAll(animations, properties) {\n const running = [];\n const keys = Object.keys(properties);\n for (let i = 0; i < keys.length; i++) {\n const anim = animations[keys[i]];\n if (anim && anim.active()) {\n running.push(anim.wait());\n }\n }\n // @ts-ignore\n return Promise.all(running);\n}\n\nfunction resolveTargetOptions(target, newOptions) {\n if (!newOptions) {\n return;\n }\n let options = target.options;\n if (!options) {\n target.options = newOptions;\n return;\n }\n if (options.$shared) {\n // Going from shared options to distinct one:\n // Create new options object containing the old shared values and start updating that.\n target.options = options = Object.assign({}, options, {$shared: false, $animations: {}});\n }\n return options;\n}\n","import Animations from './core.animations.js';\nimport defaults from './core.defaults.js';\nimport {isArray, isFinite, isObject, valueOrDefault, resolveObjectKey, defined} from '../helpers/helpers.core.js';\nimport {listenArrayEvents, unlistenArrayEvents} from '../helpers/helpers.collection.js';\nimport {createContext, sign} from '../helpers/index.js';\n\n/**\n * @typedef { import('./core.controller.js').default } Chart\n * @typedef { import('./core.scale.js').default } Scale\n */\n\nfunction scaleClip(scale, allowedOverflow) {\n const opts = scale && scale.options || {};\n const reverse = opts.reverse;\n const min = opts.min === undefined ? allowedOverflow : 0;\n const max = opts.max === undefined ? allowedOverflow : 0;\n return {\n start: reverse ? max : min,\n end: reverse ? min : max\n };\n}\n\nfunction defaultClip(xScale, yScale, allowedOverflow) {\n if (allowedOverflow === false) {\n return false;\n }\n const x = scaleClip(xScale, allowedOverflow);\n const y = scaleClip(yScale, allowedOverflow);\n\n return {\n top: y.end,\n right: x.end,\n bottom: y.start,\n left: x.start\n };\n}\n\nfunction toClip(value) {\n let t, r, b, l;\n\n if (isObject(value)) {\n t = value.top;\n r = value.right;\n b = value.bottom;\n l = value.left;\n } else {\n t = r = b = l = value;\n }\n\n return {\n top: t,\n right: r,\n bottom: b,\n left: l,\n disabled: value === false\n };\n}\n\nfunction getSortedDatasetIndices(chart, filterVisible) {\n const keys = [];\n const metasets = chart._getSortedDatasetMetas(filterVisible);\n let i, ilen;\n\n for (i = 0, ilen = metasets.length; i < ilen; ++i) {\n keys.push(metasets[i].index);\n }\n return keys;\n}\n\nfunction applyStack(stack, value, dsIndex, options = {}) {\n const keys = stack.keys;\n const singleMode = options.mode === 'single';\n let i, ilen, datasetIndex, otherValue;\n\n if (value === null) {\n return;\n }\n\n let found = false;\n for (i = 0, ilen = keys.length; i < ilen; ++i) {\n datasetIndex = +keys[i];\n if (datasetIndex === dsIndex) {\n found = true;\n if (options.all) {\n continue;\n }\n break;\n }\n otherValue = stack.values[datasetIndex];\n if (isFinite(otherValue) && (singleMode || (value === 0 || sign(value) === sign(otherValue)))) {\n value += otherValue;\n }\n }\n\n if (!found && !options.all) {\n return 0;\n }\n\n return value;\n}\n\nfunction convertObjectDataToArray(data, meta) {\n const {iScale, vScale} = meta;\n const iAxisKey = iScale.axis === 'x' ? 'x' : 'y';\n const vAxisKey = vScale.axis === 'x' ? 'x' : 'y';\n const keys = Object.keys(data);\n const adata = new Array(keys.length);\n let i, ilen, key;\n for (i = 0, ilen = keys.length; i < ilen; ++i) {\n key = keys[i];\n adata[i] = {\n [iAxisKey]: key,\n [vAxisKey]: data[key]\n };\n }\n return adata;\n}\n\nfunction isStacked(scale, meta) {\n const stacked = scale && scale.options.stacked;\n return stacked || (stacked === undefined && meta.stack !== undefined);\n}\n\nfunction getStackKey(indexScale, valueScale, meta) {\n return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`;\n}\n\nfunction getUserBounds(scale) {\n const {min, max, minDefined, maxDefined} = scale.getUserBounds();\n return {\n min: minDefined ? min : Number.NEGATIVE_INFINITY,\n max: maxDefined ? max : Number.POSITIVE_INFINITY\n };\n}\n\nfunction getOrCreateStack(stacks, stackKey, indexValue) {\n const subStack = stacks[stackKey] || (stacks[stackKey] = {});\n return subStack[indexValue] || (subStack[indexValue] = {});\n}\n\nfunction getLastIndexInStack(stack, vScale, positive, type) {\n for (const meta of vScale.getMatchingVisibleMetas(type).reverse()) {\n const value = stack[meta.index];\n if ((positive && value > 0) || (!positive && value < 0)) {\n return meta.index;\n }\n }\n\n return null;\n}\n\nfunction updateStacks(controller, parsed) {\n const {chart, _cachedMeta: meta} = controller;\n const stacks = chart._stacks || (chart._stacks = {}); // map structure is {stackKey: {datasetIndex: value}}\n const {iScale, vScale, index: datasetIndex} = meta;\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const key = getStackKey(iScale, vScale, meta);\n const ilen = parsed.length;\n let stack;\n\n for (let i = 0; i < ilen; ++i) {\n const item = parsed[i];\n const {[iAxis]: index, [vAxis]: value} = item;\n const itemStacks = item._stacks || (item._stacks = {});\n stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index);\n stack[datasetIndex] = value;\n\n stack._top = getLastIndexInStack(stack, vScale, true, meta.type);\n stack._bottom = getLastIndexInStack(stack, vScale, false, meta.type);\n\n const visualValues = stack._visualValues || (stack._visualValues = {});\n visualValues[datasetIndex] = value;\n }\n}\n\nfunction getFirstScaleId(chart, axis) {\n const scales = chart.scales;\n return Object.keys(scales).filter(key => scales[key].axis === axis).shift();\n}\n\nfunction createDatasetContext(parent, index) {\n return createContext(parent,\n {\n active: false,\n dataset: undefined,\n datasetIndex: index,\n index,\n mode: 'default',\n type: 'dataset'\n }\n );\n}\n\nfunction createDataContext(parent, index, element) {\n return createContext(parent, {\n active: false,\n dataIndex: index,\n parsed: undefined,\n raw: undefined,\n element,\n index,\n mode: 'default',\n type: 'data'\n });\n}\n\nfunction clearStacks(meta, items) {\n // Not using meta.index here, because it might be already updated if the dataset changed location\n const datasetIndex = meta.controller.index;\n const axis = meta.vScale && meta.vScale.axis;\n if (!axis) {\n return;\n }\n\n items = items || meta._parsed;\n for (const parsed of items) {\n const stacks = parsed._stacks;\n if (!stacks || stacks[axis] === undefined || stacks[axis][datasetIndex] === undefined) {\n return;\n }\n delete stacks[axis][datasetIndex];\n if (stacks[axis]._visualValues !== undefined && stacks[axis]._visualValues[datasetIndex] !== undefined) {\n delete stacks[axis]._visualValues[datasetIndex];\n }\n }\n}\n\nconst isDirectUpdateMode = (mode) => mode === 'reset' || mode === 'none';\nconst cloneIfNotShared = (cached, shared) => shared ? cached : Object.assign({}, cached);\nconst createStack = (canStack, meta, chart) => canStack && !meta.hidden && meta._stacked\n && {keys: getSortedDatasetIndices(chart, true), values: null};\n\nexport default class DatasetController {\n\n /**\n * @type {any}\n */\n static defaults = {};\n\n /**\n * Element type used to generate a meta dataset (e.g. Chart.element.LineElement).\n */\n static datasetElementType = null;\n\n /**\n * Element type used to generate a meta data (e.g. Chart.element.PointElement).\n */\n static dataElementType = null;\n\n /**\n\t * @param {Chart} chart\n\t * @param {number} datasetIndex\n\t */\n constructor(chart, datasetIndex) {\n this.chart = chart;\n this._ctx = chart.ctx;\n this.index = datasetIndex;\n this._cachedDataOpts = {};\n this._cachedMeta = this.getMeta();\n this._type = this._cachedMeta.type;\n this.options = undefined;\n /** @type {boolean | object} */\n this._parsing = false;\n this._data = undefined;\n this._objectData = undefined;\n this._sharedOptions = undefined;\n this._drawStart = undefined;\n this._drawCount = undefined;\n this.enableOptionSharing = false;\n this.supportsDecimation = false;\n this.$context = undefined;\n this._syncList = [];\n this.datasetElementType = new.target.datasetElementType;\n this.dataElementType = new.target.dataElementType;\n\n this.initialize();\n }\n\n initialize() {\n const meta = this._cachedMeta;\n this.configure();\n this.linkScales();\n meta._stacked = isStacked(meta.vScale, meta);\n this.addElements();\n\n if (this.options.fill && !this.chart.isPluginEnabled('filler')) {\n console.warn(\"Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options\");\n }\n }\n\n updateIndex(datasetIndex) {\n if (this.index !== datasetIndex) {\n clearStacks(this._cachedMeta);\n }\n this.index = datasetIndex;\n }\n\n linkScales() {\n const chart = this.chart;\n const meta = this._cachedMeta;\n const dataset = this.getDataset();\n\n const chooseId = (axis, x, y, r) => axis === 'x' ? x : axis === 'r' ? r : y;\n\n const xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x'));\n const yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y'));\n const rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r'));\n const indexAxis = meta.indexAxis;\n const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid);\n const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid);\n meta.xScale = this.getScaleForId(xid);\n meta.yScale = this.getScaleForId(yid);\n meta.rScale = this.getScaleForId(rid);\n meta.iScale = this.getScaleForId(iid);\n meta.vScale = this.getScaleForId(vid);\n }\n\n getDataset() {\n return this.chart.data.datasets[this.index];\n }\n\n getMeta() {\n return this.chart.getDatasetMeta(this.index);\n }\n\n /**\n\t * @param {string} scaleID\n\t * @return {Scale}\n\t */\n getScaleForId(scaleID) {\n return this.chart.scales[scaleID];\n }\n\n /**\n\t * @private\n\t */\n _getOtherScale(scale) {\n const meta = this._cachedMeta;\n return scale === meta.iScale\n ? meta.vScale\n : meta.iScale;\n }\n\n reset() {\n this._update('reset');\n }\n\n /**\n\t * @private\n\t */\n _destroy() {\n const meta = this._cachedMeta;\n if (this._data) {\n unlistenArrayEvents(this._data, this);\n }\n if (meta._stacked) {\n clearStacks(meta);\n }\n }\n\n /**\n\t * @private\n\t */\n _dataCheck() {\n const dataset = this.getDataset();\n const data = dataset.data || (dataset.data = []);\n const _data = this._data;\n\n // In order to correctly handle data addition/deletion animation (and thus simulate\n // real-time charts), we need to monitor these data modifications and synchronize\n // the internal metadata accordingly.\n\n if (isObject(data)) {\n const meta = this._cachedMeta;\n this._data = convertObjectDataToArray(data, meta);\n } else if (_data !== data) {\n if (_data) {\n // This case happens when the user replaced the data array instance.\n unlistenArrayEvents(_data, this);\n // Discard old parsed data and stacks\n const meta = this._cachedMeta;\n clearStacks(meta);\n meta._parsed = [];\n }\n if (data && Object.isExtensible(data)) {\n listenArrayEvents(data, this);\n }\n this._syncList = [];\n this._data = data;\n }\n }\n\n addElements() {\n const meta = this._cachedMeta;\n\n this._dataCheck();\n\n if (this.datasetElementType) {\n meta.dataset = new this.datasetElementType();\n }\n }\n\n buildOrUpdateElements(resetNewElements) {\n const meta = this._cachedMeta;\n const dataset = this.getDataset();\n let stackChanged = false;\n\n this._dataCheck();\n\n // make sure cached _stacked status is current\n const oldStacked = meta._stacked;\n meta._stacked = isStacked(meta.vScale, meta);\n\n // detect change in stack option\n if (meta.stack !== dataset.stack) {\n stackChanged = true;\n // remove values from old stack\n clearStacks(meta);\n meta.stack = dataset.stack;\n }\n\n // Re-sync meta data in case the user replaced the data array or if we missed\n // any updates and so make sure that we handle number of datapoints changing.\n this._resyncElements(resetNewElements);\n\n // if stack changed, update stack values for the whole dataset\n if (stackChanged || oldStacked !== meta._stacked) {\n updateStacks(this, meta._parsed);\n meta._stacked = isStacked(meta.vScale, meta);\n }\n }\n\n /**\n\t * Merges user-supplied and default dataset-level options\n\t * @private\n\t */\n configure() {\n const config = this.chart.config;\n const scopeKeys = config.datasetScopeKeys(this._type);\n const scopes = config.getOptionScopes(this.getDataset(), scopeKeys, true);\n this.options = config.createResolver(scopes, this.getContext());\n this._parsing = this.options.parsing;\n this._cachedDataOpts = {};\n }\n\n /**\n\t * @param {number} start\n\t * @param {number} count\n\t */\n parse(start, count) {\n const {_cachedMeta: meta, _data: data} = this;\n const {iScale, _stacked} = meta;\n const iAxis = iScale.axis;\n\n let sorted = start === 0 && count === data.length ? true : meta._sorted;\n let prev = start > 0 && meta._parsed[start - 1];\n let i, cur, parsed;\n\n if (this._parsing === false) {\n meta._parsed = data;\n meta._sorted = true;\n parsed = data;\n } else {\n if (isArray(data[start])) {\n parsed = this.parseArrayData(meta, data, start, count);\n } else if (isObject(data[start])) {\n parsed = this.parseObjectData(meta, data, start, count);\n } else {\n parsed = this.parsePrimitiveData(meta, data, start, count);\n }\n\n const isNotInOrderComparedToPrev = () => cur[iAxis] === null || (prev && cur[iAxis] < prev[iAxis]);\n for (i = 0; i < count; ++i) {\n meta._parsed[i + start] = cur = parsed[i];\n if (sorted) {\n if (isNotInOrderComparedToPrev()) {\n sorted = false;\n }\n prev = cur;\n }\n }\n meta._sorted = sorted;\n }\n\n if (_stacked) {\n updateStacks(this, parsed);\n }\n }\n\n /**\n\t * Parse array of primitive values\n\t * @param {object} meta - dataset meta\n\t * @param {array} data - data array. Example [1,3,4]\n\t * @param {number} start - start index\n\t * @param {number} count - number of items to parse\n\t * @returns {object} parsed item - item containing index and a parsed value\n\t * for each scale id.\n\t * Example: {xScale0: 0, yScale0: 1}\n\t * @protected\n\t */\n parsePrimitiveData(meta, data, start, count) {\n const {iScale, vScale} = meta;\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const labels = iScale.getLabels();\n const singleScale = iScale === vScale;\n const parsed = new Array(count);\n let i, ilen, index;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n parsed[i] = {\n [iAxis]: singleScale || iScale.parse(labels[index], index),\n [vAxis]: vScale.parse(data[index], index)\n };\n }\n return parsed;\n }\n\n /**\n\t * Parse array of arrays\n\t * @param {object} meta - dataset meta\n\t * @param {array} data - data array. Example [[1,2],[3,4]]\n\t * @param {number} start - start index\n\t * @param {number} count - number of items to parse\n\t * @returns {object} parsed item - item containing index and a parsed value\n\t * for each scale id.\n\t * Example: {x: 0, y: 1}\n\t * @protected\n\t */\n parseArrayData(meta, data, start, count) {\n const {xScale, yScale} = meta;\n const parsed = new Array(count);\n let i, ilen, index, item;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n item = data[index];\n parsed[i] = {\n x: xScale.parse(item[0], index),\n y: yScale.parse(item[1], index)\n };\n }\n return parsed;\n }\n\n /**\n\t * Parse array of objects\n\t * @param {object} meta - dataset meta\n\t * @param {array} data - data array. Example [{x:1, y:5}, {x:2, y:10}]\n\t * @param {number} start - start index\n\t * @param {number} count - number of items to parse\n\t * @returns {object} parsed item - item containing index and a parsed value\n\t * for each scale id. _custom is optional\n\t * Example: {xScale0: 0, yScale0: 1, _custom: {r: 10, foo: 'bar'}}\n\t * @protected\n\t */\n parseObjectData(meta, data, start, count) {\n const {xScale, yScale} = meta;\n const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;\n const parsed = new Array(count);\n let i, ilen, index, item;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n item = data[index];\n parsed[i] = {\n x: xScale.parse(resolveObjectKey(item, xAxisKey), index),\n y: yScale.parse(resolveObjectKey(item, yAxisKey), index)\n };\n }\n return parsed;\n }\n\n /**\n\t * @protected\n\t */\n getParsed(index) {\n return this._cachedMeta._parsed[index];\n }\n\n /**\n\t * @protected\n\t */\n getDataElement(index) {\n return this._cachedMeta.data[index];\n }\n\n /**\n\t * @protected\n\t */\n applyStack(scale, parsed, mode) {\n const chart = this.chart;\n const meta = this._cachedMeta;\n const value = parsed[scale.axis];\n const stack = {\n keys: getSortedDatasetIndices(chart, true),\n values: parsed._stacks[scale.axis]._visualValues\n };\n return applyStack(stack, value, meta.index, {mode});\n }\n\n /**\n\t * @protected\n\t */\n updateRangeFromParsed(range, scale, parsed, stack) {\n const parsedValue = parsed[scale.axis];\n let value = parsedValue === null ? NaN : parsedValue;\n const values = stack && parsed._stacks[scale.axis];\n if (stack && values) {\n stack.values = values;\n value = applyStack(stack, parsedValue, this._cachedMeta.index);\n }\n range.min = Math.min(range.min, value);\n range.max = Math.max(range.max, value);\n }\n\n /**\n\t * @protected\n\t */\n getMinMax(scale, canStack) {\n const meta = this._cachedMeta;\n const _parsed = meta._parsed;\n const sorted = meta._sorted && scale === meta.iScale;\n const ilen = _parsed.length;\n const otherScale = this._getOtherScale(scale);\n const stack = createStack(canStack, meta, this.chart);\n const range = {min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY};\n const {min: otherMin, max: otherMax} = getUserBounds(otherScale);\n let i, parsed;\n\n function _skip() {\n parsed = _parsed[i];\n const otherValue = parsed[otherScale.axis];\n return !isFinite(parsed[scale.axis]) || otherMin > otherValue || otherMax < otherValue;\n }\n\n for (i = 0; i < ilen; ++i) {\n if (_skip()) {\n continue;\n }\n this.updateRangeFromParsed(range, scale, parsed, stack);\n if (sorted) {\n // if the data is sorted, we don't need to check further from this end of array\n break;\n }\n }\n if (sorted) {\n // in the sorted case, find first non-skipped value from other end of array\n for (i = ilen - 1; i >= 0; --i) {\n if (_skip()) {\n continue;\n }\n this.updateRangeFromParsed(range, scale, parsed, stack);\n break;\n }\n }\n return range;\n }\n\n getAllParsedValues(scale) {\n const parsed = this._cachedMeta._parsed;\n const values = [];\n let i, ilen, value;\n\n for (i = 0, ilen = parsed.length; i < ilen; ++i) {\n value = parsed[i][scale.axis];\n if (isFinite(value)) {\n values.push(value);\n }\n }\n return values;\n }\n\n /**\n\t * @return {number|boolean}\n\t * @protected\n\t */\n getMaxOverflow() {\n return false;\n }\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const iScale = meta.iScale;\n const vScale = meta.vScale;\n const parsed = this.getParsed(index);\n return {\n label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '',\n value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : ''\n };\n }\n\n /**\n\t * @private\n\t */\n _update(mode) {\n const meta = this._cachedMeta;\n this.update(mode || 'default');\n meta._clip = toClip(valueOrDefault(this.options.clip, defaultClip(meta.xScale, meta.yScale, this.getMaxOverflow())));\n }\n\n /**\n\t * @param {string} mode\n\t */\n update(mode) {} // eslint-disable-line no-unused-vars\n\n draw() {\n const ctx = this._ctx;\n const chart = this.chart;\n const meta = this._cachedMeta;\n const elements = meta.data || [];\n const area = chart.chartArea;\n const active = [];\n const start = this._drawStart || 0;\n const count = this._drawCount || (elements.length - start);\n const drawActiveElementsOnTop = this.options.drawActiveElementsOnTop;\n let i;\n\n if (meta.dataset) {\n meta.dataset.draw(ctx, area, start, count);\n }\n\n for (i = start; i < start + count; ++i) {\n const element = elements[i];\n if (element.hidden) {\n continue;\n }\n if (element.active && drawActiveElementsOnTop) {\n active.push(element);\n } else {\n element.draw(ctx, area);\n }\n }\n\n for (i = 0; i < active.length; ++i) {\n active[i].draw(ctx, area);\n }\n }\n\n /**\n\t * Returns a set of predefined style properties that should be used to represent the dataset\n\t * or the data if the index is specified\n\t * @param {number} index - data index\n\t * @param {boolean} [active] - true if hover\n\t * @return {object} style object\n\t */\n getStyle(index, active) {\n const mode = active ? 'active' : 'default';\n return index === undefined && this._cachedMeta.dataset\n ? this.resolveDatasetElementOptions(mode)\n : this.resolveDataElementOptions(index || 0, mode);\n }\n\n /**\n\t * @protected\n\t */\n getContext(index, active, mode) {\n const dataset = this.getDataset();\n let context;\n if (index >= 0 && index < this._cachedMeta.data.length) {\n const element = this._cachedMeta.data[index];\n context = element.$context ||\n (element.$context = createDataContext(this.getContext(), index, element));\n context.parsed = this.getParsed(index);\n context.raw = dataset.data[index];\n context.index = context.dataIndex = index;\n } else {\n context = this.$context ||\n (this.$context = createDatasetContext(this.chart.getContext(), this.index));\n context.dataset = dataset;\n context.index = context.datasetIndex = this.index;\n }\n\n context.active = !!active;\n context.mode = mode;\n return context;\n }\n\n /**\n\t * @param {string} [mode]\n\t * @protected\n\t */\n resolveDatasetElementOptions(mode) {\n return this._resolveElementOptions(this.datasetElementType.id, mode);\n }\n\n /**\n\t * @param {number} index\n\t * @param {string} [mode]\n\t * @protected\n\t */\n resolveDataElementOptions(index, mode) {\n return this._resolveElementOptions(this.dataElementType.id, mode, index);\n }\n\n /**\n\t * @private\n\t */\n _resolveElementOptions(elementType, mode = 'default', index) {\n const active = mode === 'active';\n const cache = this._cachedDataOpts;\n const cacheKey = elementType + '-' + mode;\n const cached = cache[cacheKey];\n const sharing = this.enableOptionSharing && defined(index);\n if (cached) {\n return cloneIfNotShared(cached, sharing);\n }\n const config = this.chart.config;\n const scopeKeys = config.datasetElementScopeKeys(this._type, elementType);\n const prefixes = active ? [`${elementType}Hover`, 'hover', elementType, ''] : [elementType, ''];\n const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);\n const names = Object.keys(defaults.elements[elementType]);\n // context is provided as a function, and is called only if needed,\n // so we don't create a context for each element if not needed.\n const context = () => this.getContext(index, active, mode);\n const values = config.resolveNamedOptions(scopes, names, context, prefixes);\n\n if (values.$shared) {\n // `$shared` indicates this set of options can be shared between multiple elements.\n // Sharing is used to reduce number of properties to change during animation.\n values.$shared = sharing;\n\n // We cache options by `mode`, which can be 'active' for example. This enables us\n // to have the 'active' element options and 'default' options to switch between\n // when interacting.\n cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing));\n }\n\n return values;\n }\n\n\n /**\n\t * @private\n\t */\n _resolveAnimations(index, transition, active) {\n const chart = this.chart;\n const cache = this._cachedDataOpts;\n const cacheKey = `animation-${transition}`;\n const cached = cache[cacheKey];\n if (cached) {\n return cached;\n }\n let options;\n if (chart.options.animation !== false) {\n const config = this.chart.config;\n const scopeKeys = config.datasetAnimationScopeKeys(this._type, transition);\n const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);\n options = config.createResolver(scopes, this.getContext(index, active, transition));\n }\n const animations = new Animations(chart, options && options.animations);\n if (options && options._cacheable) {\n cache[cacheKey] = Object.freeze(animations);\n }\n return animations;\n }\n\n /**\n\t * Utility for getting the options object shared between elements\n\t * @protected\n\t */\n getSharedOptions(options) {\n if (!options.$shared) {\n return;\n }\n return this._sharedOptions || (this._sharedOptions = Object.assign({}, options));\n }\n\n /**\n\t * Utility for determining if `options` should be included in the updated properties\n\t * @protected\n\t */\n includeOptions(mode, sharedOptions) {\n return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled;\n }\n\n /**\n * @todo v4, rename to getSharedOptions and remove excess functions\n */\n _getSharedOptions(start, mode) {\n const firstOpts = this.resolveDataElementOptions(start, mode);\n const previouslySharedOptions = this._sharedOptions;\n const sharedOptions = this.getSharedOptions(firstOpts);\n const includeOptions = this.includeOptions(mode, sharedOptions) || (sharedOptions !== previouslySharedOptions);\n this.updateSharedOptions(sharedOptions, mode, firstOpts);\n return {sharedOptions, includeOptions};\n }\n\n /**\n\t * Utility for updating an element with new properties, using animations when appropriate.\n\t * @protected\n\t */\n updateElement(element, index, properties, mode) {\n if (isDirectUpdateMode(mode)) {\n Object.assign(element, properties);\n } else {\n this._resolveAnimations(index, mode).update(element, properties);\n }\n }\n\n /**\n\t * Utility to animate the shared options, that are potentially affecting multiple elements.\n\t * @protected\n\t */\n updateSharedOptions(sharedOptions, mode, newOptions) {\n if (sharedOptions && !isDirectUpdateMode(mode)) {\n this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions);\n }\n }\n\n /**\n\t * @private\n\t */\n _setStyle(element, index, mode, active) {\n element.active = active;\n const options = this.getStyle(index, active);\n this._resolveAnimations(index, mode, active).update(element, {\n // When going from active to inactive, we need to update to the shared options.\n // This way the once hovered element will end up with the same original shared options instance, after animation.\n options: (!active && this.getSharedOptions(options)) || options\n });\n }\n\n removeHoverStyle(element, datasetIndex, index) {\n this._setStyle(element, index, 'active', false);\n }\n\n setHoverStyle(element, datasetIndex, index) {\n this._setStyle(element, index, 'active', true);\n }\n\n /**\n\t * @private\n\t */\n _removeDatasetHoverStyle() {\n const element = this._cachedMeta.dataset;\n\n if (element) {\n this._setStyle(element, undefined, 'active', false);\n }\n }\n\n /**\n\t * @private\n\t */\n _setDatasetHoverStyle() {\n const element = this._cachedMeta.dataset;\n\n if (element) {\n this._setStyle(element, undefined, 'active', true);\n }\n }\n\n /**\n\t * @private\n\t */\n _resyncElements(resetNewElements) {\n const data = this._data;\n const elements = this._cachedMeta.data;\n\n // Apply changes detected through array listeners\n for (const [method, arg1, arg2] of this._syncList) {\n this[method](arg1, arg2);\n }\n this._syncList = [];\n\n const numMeta = elements.length;\n const numData = data.length;\n const count = Math.min(numData, numMeta);\n\n if (count) {\n // TODO: It is not optimal to always parse the old data\n // This is done because we are not detecting direct assignments:\n // chart.data.datasets[0].data[5] = 10;\n // chart.data.datasets[0].data[5].y = 10;\n this.parse(0, count);\n }\n\n if (numData > numMeta) {\n this._insertElements(numMeta, numData - numMeta, resetNewElements);\n } else if (numData < numMeta) {\n this._removeElements(numData, numMeta - numData);\n }\n }\n\n /**\n\t * @private\n\t */\n _insertElements(start, count, resetNewElements = true) {\n const meta = this._cachedMeta;\n const data = meta.data;\n const end = start + count;\n let i;\n\n const move = (arr) => {\n arr.length += count;\n for (i = arr.length - 1; i >= end; i--) {\n arr[i] = arr[i - count];\n }\n };\n move(data);\n\n for (i = start; i < end; ++i) {\n data[i] = new this.dataElementType();\n }\n\n if (this._parsing) {\n move(meta._parsed);\n }\n this.parse(start, count);\n\n if (resetNewElements) {\n this.updateElements(data, start, count, 'reset');\n }\n }\n\n updateElements(element, start, count, mode) {} // eslint-disable-line no-unused-vars\n\n /**\n\t * @private\n\t */\n _removeElements(start, count) {\n const meta = this._cachedMeta;\n if (this._parsing) {\n const removed = meta._parsed.splice(start, count);\n if (meta._stacked) {\n clearStacks(meta, removed);\n }\n }\n meta.data.splice(start, count);\n }\n\n /**\n\t * @private\n */\n _sync(args) {\n if (this._parsing) {\n this._syncList.push(args);\n } else {\n const [method, arg1, arg2] = args;\n this[method](arg1, arg2);\n }\n this.chart._dataChanges.push([this.index, ...args]);\n }\n\n _onDataPush() {\n const count = arguments.length;\n this._sync(['_insertElements', this.getDataset().data.length - count, count]);\n }\n\n _onDataPop() {\n this._sync(['_removeElements', this._cachedMeta.data.length - 1, 1]);\n }\n\n _onDataShift() {\n this._sync(['_removeElements', 0, 1]);\n }\n\n _onDataSplice(start, count) {\n if (count) {\n this._sync(['_removeElements', start, count]);\n }\n const newCount = arguments.length - 2;\n if (newCount) {\n this._sync(['_insertElements', start, newCount]);\n }\n }\n\n _onDataUnshift() {\n this._sync(['_insertElements', 0, arguments.length]);\n }\n}\n","import type {AnyObject} from '../types/basic.js';\nimport type {Point} from '../types/geometric.js';\nimport type {Animation} from '../types/animation.js';\nimport {isNumber} from '../helpers/helpers.math.js';\n\nexport default class Element {\n\n static defaults = {};\n static defaultRoutes = undefined;\n\n x: number;\n y: number;\n active = false;\n options: O;\n $animations: Record;\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 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 {each, callback as callCallback, uid, valueOrDefault, _elementsEqual, isNullOrUndef, setsEqual, defined, isFunction, _isClickEvent} from '../helpers/helpers.core.js';\nimport {clearCanvas, clipArea, createContext, unclipArea, _isPointInArea, _isDomSupported, retinaScale, getDatasetClipArea} 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\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 // Unset pending resize request now to avoid possible recursion within _resize\n this._resizeBeforeDraw = null;\n this._resize(width, height);\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 args = {\n meta,\n index: meta.index,\n cancelable: true\n };\n // @ts-expect-error\n const clip = getDatasetClipArea(this, meta);\n\n if (this.notifyPlugins('beforeDatasetDraw', args) === false) {\n return;\n }\n\n if (clip) {\n clipArea(ctx, clip);\n }\n\n meta.controller.draw();\n\n if (clip) {\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 event 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","/**\n * @namespace Chart._adapters\n * @since 2.8.0\n * @private\n */\n\nimport type {AnyObject} from '../types/basic.js';\nimport type {ChartOptions} from '../types/index.js';\n\nexport type TimeUnit = 'millisecond' | 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year';\n\nexport interface DateAdapter {\n readonly options: T;\n /**\n * Will called with chart options after adapter creation.\n */\n init(this: DateAdapter, chartOptions: ChartOptions): void;\n /**\n * Returns a map of time formats for the supported formatting units defined\n * in Unit as well as 'datetime' representing a detailed date/time string.\n */\n formats(this: DateAdapter): Record;\n /**\n * Parses the given `value` and return the associated timestamp.\n * @param value - the value to parse (usually comes from the data)\n * @param [format] - the expected data format\n */\n parse(this: DateAdapter, value: unknown, format?: string): number | null;\n /**\n * Returns the formatted date in the specified `format` for a given `timestamp`.\n * @param timestamp - the timestamp to format\n * @param format - the date/time token\n */\n format(this: DateAdapter, timestamp: number, format: string): string;\n /**\n * Adds the specified `amount` of `unit` to the given `timestamp`.\n * @param timestamp - the input timestamp\n * @param amount - the amount to add\n * @param unit - the unit as string\n */\n add(this: DateAdapter, timestamp: number, amount: number, unit: TimeUnit): number;\n /**\n * Returns the number of `unit` between the given timestamps.\n * @param a - the input timestamp (reference)\n * @param b - the timestamp to subtract\n * @param unit - the unit as string\n */\n diff(this: DateAdapter, a: number, b: number, unit: TimeUnit): number;\n /**\n * Returns start of `unit` for the given `timestamp`.\n * @param timestamp - the input timestamp\n * @param unit - the unit as string\n * @param [weekday] - the ISO day of the week with 1 being Monday\n * and 7 being Sunday (only needed if param *unit* is `isoWeek`).\n */\n startOf(this: DateAdapter, timestamp: number, unit: TimeUnit | 'isoWeek', weekday?: number | boolean): number;\n /**\n * Returns end of `unit` for the given `timestamp`.\n * @param timestamp - the input timestamp\n * @param unit - the unit as string\n */\n endOf(this: DateAdapter, timestamp: number, unit: TimeUnit): number;\n}\n\nfunction abstract(): T {\n throw new Error('This method is not implemented: Check that a complete date adapter is provided.');\n}\n\n/**\n * Date adapter (current used by the time scale)\n * @namespace Chart._adapters._date\n * @memberof Chart._adapters\n * @private\n */\nclass DateAdapterBase implements DateAdapter {\n\n /**\n * Override default date adapter methods.\n * Accepts type parameter to define options type.\n * @example\n * Chart._adapters._date.override<{myAdapterOption: string}>({\n * init() {\n * console.log(this.options.myAdapterOption);\n * }\n * })\n */\n static override(\n members: Partial, 'options'>>\n ) {\n Object.assign(DateAdapterBase.prototype, members);\n }\n\n readonly options: AnyObject;\n\n constructor(options?: AnyObject) {\n this.options = options || {};\n }\n\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n init() {}\n\n formats(): Record {\n return abstract();\n }\n\n parse(): number | null {\n return abstract();\n }\n\n format(): string {\n return abstract();\n }\n\n add(): number {\n return abstract();\n }\n\n diff(): number {\n return abstract();\n }\n\n startOf(): number {\n return abstract();\n }\n\n endOf(): number {\n return abstract();\n }\n}\n\nexport default {\n _date: DateAdapterBase as {\n new (options?: AnyObject): DateAdapter;\n override(\n members: Partial, 'options'>>\n ): void;\n }\n};\n","import DatasetController from '../core/core.datasetController.js';\nimport {\n _arrayUnique, isArray, isNullOrUndef,\n valueOrDefault, resolveObjectKey, sign, defined\n} from '../helpers/index.js';\n\nfunction getAllScaleValues(scale, type) {\n if (!scale._cache.$bar) {\n const visibleMetas = scale.getMatchingVisibleMetas(type);\n let values = [];\n\n for (let i = 0, ilen = visibleMetas.length; i < ilen; i++) {\n values = values.concat(visibleMetas[i].controller.getAllParsedValues(scale));\n }\n scale._cache.$bar = _arrayUnique(values.sort((a, b) => a - b));\n }\n return scale._cache.$bar;\n}\n\n/**\n * Computes the \"optimal\" sample size to maintain bars equally sized while preventing overlap.\n * @private\n */\nfunction computeMinSampleSize(meta) {\n const scale = meta.iScale;\n const values = getAllScaleValues(scale, meta.type);\n let min = scale._length;\n let i, ilen, curr, prev;\n const updateMinAndPrev = () => {\n if (curr === 32767 || curr === -32768) {\n // Ignore truncated pixels\n return;\n }\n if (defined(prev)) {\n // curr - prev === 0 is ignored\n min = Math.min(min, Math.abs(curr - prev) || min);\n }\n prev = curr;\n };\n\n for (i = 0, ilen = values.length; i < ilen; ++i) {\n curr = scale.getPixelForValue(values[i]);\n updateMinAndPrev();\n }\n\n prev = undefined;\n for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) {\n curr = scale.getPixelForTick(i);\n updateMinAndPrev();\n }\n\n return min;\n}\n\n/**\n * Computes an \"ideal\" category based on the absolute bar thickness or, if undefined or null,\n * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This\n * mode currently always generates bars equally sized (until we introduce scriptable options?).\n * @private\n */\nfunction computeFitCategoryTraits(index, ruler, options, stackCount) {\n const thickness = options.barThickness;\n let size, ratio;\n\n if (isNullOrUndef(thickness)) {\n size = ruler.min * options.categoryPercentage;\n ratio = options.barPercentage;\n } else {\n // When bar thickness is enforced, category and bar percentages are ignored.\n // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')\n // and deprecate barPercentage since this value is ignored when thickness is absolute.\n size = thickness * stackCount;\n ratio = 1;\n }\n\n return {\n chunk: size / stackCount,\n ratio,\n start: ruler.pixels[index] - (size / 2)\n };\n}\n\n/**\n * Computes an \"optimal\" category that globally arranges bars side by side (no gap when\n * percentage options are 1), based on the previous and following categories. This mode\n * generates bars with different widths when data are not evenly spaced.\n * @private\n */\nfunction computeFlexCategoryTraits(index, ruler, options, stackCount) {\n const pixels = ruler.pixels;\n const curr = pixels[index];\n let prev = index > 0 ? pixels[index - 1] : null;\n let next = index < pixels.length - 1 ? pixels[index + 1] : null;\n const percent = options.categoryPercentage;\n\n if (prev === null) {\n // first data: its size is double based on the next point or,\n // if it's also the last data, we use the scale size.\n prev = curr - (next === null ? ruler.end - ruler.start : next - curr);\n }\n\n if (next === null) {\n // last data: its size is also double based on the previous point.\n next = curr + curr - prev;\n }\n\n const start = curr - (curr - Math.min(prev, next)) / 2 * percent;\n const size = Math.abs(next - prev) / 2 * percent;\n\n return {\n chunk: size / stackCount,\n ratio: options.barPercentage,\n start\n };\n}\n\nfunction parseFloatBar(entry, item, vScale, i) {\n const startValue = vScale.parse(entry[0], i);\n const endValue = vScale.parse(entry[1], i);\n const min = Math.min(startValue, endValue);\n const max = Math.max(startValue, endValue);\n let barStart = min;\n let barEnd = max;\n\n if (Math.abs(min) > Math.abs(max)) {\n barStart = max;\n barEnd = min;\n }\n\n // Store `barEnd` (furthest away from origin) as parsed value,\n // to make stacking straight forward\n item[vScale.axis] = barEnd;\n\n item._custom = {\n barStart,\n barEnd,\n start: startValue,\n end: endValue,\n min,\n max\n };\n}\n\nfunction parseValue(entry, item, vScale, i) {\n if (isArray(entry)) {\n parseFloatBar(entry, item, vScale, i);\n } else {\n item[vScale.axis] = vScale.parse(entry, i);\n }\n return item;\n}\n\nfunction parseArrayOrPrimitive(meta, data, start, count) {\n const iScale = meta.iScale;\n const vScale = meta.vScale;\n const labels = iScale.getLabels();\n const singleScale = iScale === vScale;\n const parsed = [];\n let i, ilen, item, entry;\n\n for (i = start, ilen = start + count; i < ilen; ++i) {\n entry = data[i];\n item = {};\n item[iScale.axis] = singleScale || iScale.parse(labels[i], i);\n parsed.push(parseValue(entry, item, vScale, i));\n }\n return parsed;\n}\n\nfunction isFloatBar(custom) {\n return custom && custom.barStart !== undefined && custom.barEnd !== undefined;\n}\n\nfunction barSign(size, vScale, actualBase) {\n if (size !== 0) {\n return sign(size);\n }\n return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1);\n}\n\nfunction borderProps(properties) {\n let reverse, start, end, top, bottom;\n if (properties.horizontal) {\n reverse = properties.base > properties.x;\n start = 'left';\n end = 'right';\n } else {\n reverse = properties.base < properties.y;\n start = 'bottom';\n end = 'top';\n }\n if (reverse) {\n top = 'end';\n bottom = 'start';\n } else {\n top = 'start';\n bottom = 'end';\n }\n return {start, end, reverse, top, bottom};\n}\n\nfunction setBorderSkipped(properties, options, stack, index) {\n let edge = options.borderSkipped;\n const res = {};\n\n if (!edge) {\n properties.borderSkipped = res;\n return;\n }\n\n if (edge === true) {\n properties.borderSkipped = {top: true, right: true, bottom: true, left: true};\n return;\n }\n\n const {start, end, reverse, top, bottom} = borderProps(properties);\n\n if (edge === 'middle' && stack) {\n properties.enableBorderRadius = true;\n if ((stack._top || 0) === index) {\n edge = top;\n } else if ((stack._bottom || 0) === index) {\n edge = bottom;\n } else {\n res[parseEdge(bottom, start, end, reverse)] = true;\n edge = top;\n }\n }\n\n res[parseEdge(edge, start, end, reverse)] = true;\n properties.borderSkipped = res;\n}\n\nfunction parseEdge(edge, a, b, reverse) {\n if (reverse) {\n edge = swap(edge, a, b);\n edge = startEnd(edge, b, a);\n } else {\n edge = startEnd(edge, a, b);\n }\n return edge;\n}\n\nfunction swap(orig, v1, v2) {\n return orig === v1 ? v2 : orig === v2 ? v1 : orig;\n}\n\nfunction startEnd(v, start, end) {\n return v === 'start' ? start : v === 'end' ? end : v;\n}\n\nfunction setInflateAmount(properties, {inflateAmount}, ratio) {\n properties.inflateAmount = inflateAmount === 'auto'\n ? ratio === 1 ? 0.33 : 0\n : inflateAmount;\n}\n\nexport default class BarController extends DatasetController {\n\n static id = 'bar';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'bar',\n\n categoryPercentage: 0.8,\n barPercentage: 0.9,\n grouped: true,\n\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'base', 'width', 'height']\n }\n }\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n scales: {\n _index_: {\n type: 'category',\n offset: true,\n grid: {\n offset: true\n }\n },\n _value_: {\n type: 'linear',\n beginAtZero: true,\n }\n }\n };\n\n\n /**\n\t * Overriding primitive data parsing since we support mixed primitive/array\n\t * data for float bars\n\t * @protected\n\t */\n parsePrimitiveData(meta, data, start, count) {\n return parseArrayOrPrimitive(meta, data, start, count);\n }\n\n /**\n\t * Overriding array data parsing since we support mixed primitive/array\n\t * data for float bars\n\t * @protected\n\t */\n parseArrayData(meta, data, start, count) {\n return parseArrayOrPrimitive(meta, data, start, count);\n }\n\n /**\n\t * Overriding object data parsing since we support mixed primitive/array\n\t * value-scale data for float bars\n\t * @protected\n\t */\n parseObjectData(meta, data, start, count) {\n const {iScale, vScale} = meta;\n const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;\n const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey;\n const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey;\n const parsed = [];\n let i, ilen, item, obj;\n for (i = start, ilen = start + count; i < ilen; ++i) {\n obj = data[i];\n item = {};\n item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i);\n parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i));\n }\n return parsed;\n }\n\n /**\n\t * @protected\n\t */\n updateRangeFromParsed(range, scale, parsed, stack) {\n super.updateRangeFromParsed(range, scale, parsed, stack);\n const custom = parsed._custom;\n if (custom && scale === this._cachedMeta.vScale) {\n // float bar: only one end of the bar is considered by `super`\n range.min = Math.min(range.min, custom.min);\n range.max = Math.max(range.max, custom.max);\n }\n }\n\n /**\n\t * @return {number|boolean}\n\t * @protected\n\t */\n getMaxOverflow() {\n return 0;\n }\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const {iScale, vScale} = meta;\n const parsed = this.getParsed(index);\n const custom = parsed._custom;\n const value = isFloatBar(custom)\n ? '[' + custom.start + ', ' + custom.end + ']'\n : '' + vScale.getLabelForValue(parsed[vScale.axis]);\n\n return {\n label: '' + iScale.getLabelForValue(parsed[iScale.axis]),\n value\n };\n }\n\n initialize() {\n this.enableOptionSharing = true;\n\n super.initialize();\n\n const meta = this._cachedMeta;\n meta.stack = this.getDataset().stack;\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n this.updateElements(meta.data, 0, meta.data.length, mode);\n }\n\n updateElements(bars, start, count, mode) {\n const reset = mode === 'reset';\n const {index, _cachedMeta: {vScale}} = this;\n const base = vScale.getBasePixel();\n const horizontal = vScale.isHorizontal();\n const ruler = this._getRuler();\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n\n for (let i = start; i < start + count; i++) {\n const parsed = this.getParsed(i);\n const vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? {base, head: base} : this._calculateBarValuePixels(i);\n const ipixels = this._calculateBarIndexPixels(i, ruler);\n const stack = (parsed._stacks || {})[vScale.axis];\n\n const properties = {\n horizontal,\n base: vpixels.base,\n enableBorderRadius: !stack || isFloatBar(parsed._custom) || (index === stack._top || index === stack._bottom),\n x: horizontal ? vpixels.head : ipixels.center,\n y: horizontal ? ipixels.center : vpixels.head,\n height: horizontal ? ipixels.size : Math.abs(vpixels.size),\n width: horizontal ? Math.abs(vpixels.size) : ipixels.size\n };\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, bars[i].active ? 'active' : mode);\n }\n const options = properties.options || bars[i].options;\n setBorderSkipped(properties, options, stack, index);\n setInflateAmount(properties, options, ruler.ratio);\n this.updateElement(bars[i], i, properties, mode);\n }\n }\n\n /**\n\t * Returns the stacks based on groups and bar visibility.\n\t * @param {number} [last] - The dataset index\n\t * @param {number} [dataIndex] - The data index of the ruler\n\t * @returns {string[]} The list of stack IDs\n\t * @private\n\t */\n _getStacks(last, dataIndex) {\n const {iScale} = this._cachedMeta;\n const metasets = iScale.getMatchingVisibleMetas(this._type)\n .filter(meta => meta.controller.options.grouped);\n const stacked = iScale.options.stacked;\n const stacks = [];\n const currentParsed = this._cachedMeta.controller.getParsed(dataIndex);\n const iScaleValue = currentParsed && currentParsed[iScale.axis];\n\n const skipNull = (meta) => {\n const parsed = meta._parsed.find(item => item[iScale.axis] === iScaleValue);\n const val = parsed && parsed[meta.vScale.axis];\n\n if (isNullOrUndef(val) || isNaN(val)) {\n return true;\n }\n };\n\n for (const meta of metasets) {\n if (dataIndex !== undefined && skipNull(meta)) {\n continue;\n }\n\n // stacked | meta.stack\n // | found | not found | undefined\n // false | x | x | x\n // true | | x |\n // undefined | | x | x\n if (stacked === false || stacks.indexOf(meta.stack) === -1 ||\n\t\t\t\t(stacked === undefined && meta.stack === undefined)) {\n stacks.push(meta.stack);\n }\n if (meta.index === last) {\n break;\n }\n }\n\n // No stacks? that means there is no visible data. Let's still initialize an `undefined`\n // stack where possible invisible bars will be located.\n // https://github.com/chartjs/Chart.js/issues/6368\n if (!stacks.length) {\n stacks.push(undefined);\n }\n\n return stacks;\n }\n\n /**\n\t * Returns the effective number of stacks based on groups and bar visibility.\n\t * @private\n\t */\n _getStackCount(index) {\n return this._getStacks(undefined, index).length;\n }\n\n _getAxisCount() {\n return this._getAxis().length;\n }\n\n getFirstScaleIdForIndexAxis() {\n const scales = this.chart.scales;\n const indexScaleId = this.chart.options.indexAxis;\n return Object.keys(scales).filter(key => scales[key].axis === indexScaleId).shift();\n }\n\n _getAxis() {\n const axis = {};\n const firstScaleAxisId = this.getFirstScaleIdForIndexAxis();\n for (const dataset of this.chart.data.datasets) {\n axis[valueOrDefault(\n this.chart.options.indexAxis === 'x' ? dataset.xAxisID : dataset.yAxisID, firstScaleAxisId\n )] = true;\n }\n return Object.keys(axis);\n }\n\n /**\n\t * Returns the stack index for the given dataset based on groups and bar visibility.\n\t * @param {number} [datasetIndex] - The dataset index\n\t * @param {string} [name] - The stack name to find\n * @param {number} [dataIndex]\n\t * @returns {number} The stack index\n\t * @private\n\t */\n _getStackIndex(datasetIndex, name, dataIndex) {\n const stacks = this._getStacks(datasetIndex, dataIndex);\n const index = (name !== undefined)\n ? stacks.indexOf(name)\n : -1; // indexOf returns -1 if element is not present\n\n return (index === -1)\n ? stacks.length - 1\n : index;\n }\n\n /**\n\t * @private\n\t */\n _getRuler() {\n const opts = this.options;\n const meta = this._cachedMeta;\n const iScale = meta.iScale;\n const pixels = [];\n let i, ilen;\n\n for (i = 0, ilen = meta.data.length; i < ilen; ++i) {\n pixels.push(iScale.getPixelForValue(this.getParsed(i)[iScale.axis], i));\n }\n\n const barThickness = opts.barThickness;\n const min = barThickness || computeMinSampleSize(meta);\n\n return {\n min,\n pixels,\n start: iScale._startPixel,\n end: iScale._endPixel,\n stackCount: this._getStackCount(),\n scale: iScale,\n grouped: opts.grouped,\n // bar thickness ratio used for non-grouped bars\n ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage\n };\n }\n\n /**\n\t * Note: pixel values are not clamped to the scale area.\n\t * @private\n\t */\n _calculateBarValuePixels(index) {\n const {_cachedMeta: {vScale, _stacked, index: datasetIndex}, options: {base: baseValue, minBarLength}} = this;\n const actualBase = baseValue || 0;\n const parsed = this.getParsed(index);\n const custom = parsed._custom;\n const floating = isFloatBar(custom);\n let value = parsed[vScale.axis];\n let start = 0;\n let length = _stacked ? this.applyStack(vScale, parsed, _stacked) : value;\n let head, size;\n\n if (length !== value) {\n start = length - value;\n length = value;\n }\n\n if (floating) {\n value = custom.barStart;\n length = custom.barEnd - custom.barStart;\n // bars crossing origin are not stacked\n if (value !== 0 && sign(value) !== sign(custom.barEnd)) {\n start = 0;\n }\n start += value;\n }\n\n const startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start;\n let base = vScale.getPixelForValue(startValue);\n\n if (this.chart.getDataVisibility(index)) {\n head = vScale.getPixelForValue(start + length);\n } else {\n // When not visible, no height\n head = base;\n }\n\n size = head - base;\n\n if (Math.abs(size) < minBarLength) {\n size = barSign(size, vScale, actualBase) * minBarLength;\n if (value === actualBase) {\n base -= size / 2;\n }\n const startPixel = vScale.getPixelForDecimal(0);\n const endPixel = vScale.getPixelForDecimal(1);\n const min = Math.min(startPixel, endPixel);\n const max = Math.max(startPixel, endPixel);\n base = Math.max(Math.min(base, max), min);\n head = base + size;\n\n if (_stacked && !floating) {\n // visual data coordinates after applying minBarLength\n parsed._stacks[vScale.axis]._visualValues[datasetIndex] = vScale.getValueForPixel(head) - vScale.getValueForPixel(base);\n }\n }\n\n if (base === vScale.getPixelForValue(actualBase)) {\n const halfGrid = sign(size) * vScale.getLineWidthForValue(actualBase) / 2;\n base += halfGrid;\n size -= halfGrid;\n }\n\n return {\n size,\n base,\n head,\n center: head + size / 2\n };\n }\n\n /**\n\t * @private\n\t */\n _calculateBarIndexPixels(index, ruler) {\n const scale = ruler.scale;\n const options = this.options;\n const skipNull = options.skipNull;\n const maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity);\n let center, size;\n const axisCount = this._getAxisCount();\n if (ruler.grouped) {\n const stackCount = skipNull ? this._getStackCount(index) : ruler.stackCount;\n const range = options.barThickness === 'flex'\n ? computeFlexCategoryTraits(index, ruler, options, stackCount * axisCount)\n : computeFitCategoryTraits(index, ruler, options, stackCount * axisCount);\n const axisID = this.chart.options.indexAxis === 'x' ? this.getDataset().xAxisID : this.getDataset().yAxisID;\n const axisNumber = this._getAxis().indexOf(valueOrDefault(axisID, this.getFirstScaleIdForIndexAxis()));\n const stackIndex = this._getStackIndex(this.index, this._cachedMeta.stack, skipNull ? index : undefined) + axisNumber;\n center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);\n size = Math.min(maxBarThickness, range.chunk * range.ratio);\n } else {\n // For non-grouped bar charts, exact pixel values are used\n center = scale.getPixelForValue(this.getParsed(index)[scale.axis], index);\n size = Math.min(maxBarThickness, ruler.min * ruler.ratio);\n }\n\n\n return {\n base: center - size / 2,\n head: center + size / 2,\n center,\n size\n };\n }\n\n draw() {\n const meta = this._cachedMeta;\n const vScale = meta.vScale;\n const rects = meta.data;\n const ilen = rects.length;\n let i = 0;\n\n for (; i < ilen; ++i) {\n if (this.getParsed(i)[vScale.axis] !== null && !rects[i].hidden) {\n rects[i].draw(this._ctx);\n }\n }\n }\n\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {isObject, resolveObjectKey, toPercentage, toDimension, valueOrDefault} from '../helpers/helpers.core.js';\nimport {formatNumber} from '../helpers/helpers.intl.js';\nimport {toRadians, PI, TAU, HALF_PI, _angleBetween} from '../helpers/helpers.math.js';\n\n/**\n * @typedef { import('../core/core.controller.js').default } Chart\n */\n\nfunction getRatioAndOffset(rotation, circumference, cutout) {\n let ratioX = 1;\n let ratioY = 1;\n let offsetX = 0;\n let offsetY = 0;\n // If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc\n if (circumference < TAU) {\n const startAngle = rotation;\n const endAngle = startAngle + circumference;\n const startX = Math.cos(startAngle);\n const startY = Math.sin(startAngle);\n const endX = Math.cos(endAngle);\n const endY = Math.sin(endAngle);\n const calcMax = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout);\n const calcMin = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout);\n const maxX = calcMax(0, startX, endX);\n const maxY = calcMax(HALF_PI, startY, endY);\n const minX = calcMin(PI, startX, endX);\n const minY = calcMin(PI + HALF_PI, startY, endY);\n ratioX = (maxX - minX) / 2;\n ratioY = (maxY - minY) / 2;\n offsetX = -(maxX + minX) / 2;\n offsetY = -(maxY + minY) / 2;\n }\n return {ratioX, ratioY, offsetX, offsetY};\n}\n\nexport default class DoughnutController extends DatasetController {\n\n static id = 'doughnut';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'arc',\n animation: {\n // Boolean - Whether we animate the rotation of the Doughnut\n animateRotate: true,\n // Boolean - Whether we animate scaling the Doughnut from the centre\n animateScale: false\n },\n animations: {\n numbers: {\n type: 'number',\n properties: ['circumference', 'endAngle', 'innerRadius', 'outerRadius', 'startAngle', 'x', 'y', 'offset', 'borderWidth', 'spacing']\n },\n },\n // The percentage of the chart that we cut out of the middle.\n cutout: '50%',\n\n // The rotation of the chart, where the first data arc begins.\n rotation: 0,\n\n // The total circumference of the chart.\n circumference: 360,\n\n // The outer radius of the chart\n radius: '100%',\n\n // Spacing between arcs\n spacing: 0,\n\n indexAxis: 'r',\n };\n\n static descriptors = {\n _scriptable: (name) => name !== 'spacing',\n _indexable: (name) => name !== 'spacing' && !name.startsWith('borderDash') && !name.startsWith('hoverBorderDash'),\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n aspectRatio: 1,\n\n // Need to override these to give a nice default\n plugins: {\n legend: {\n labels: {\n generateLabels(chart) {\n const data = chart.data;\n if (data.labels.length && data.datasets.length) {\n const {labels: {pointStyle, color}} = chart.legend.options;\n\n return data.labels.map((label, i) => {\n const meta = chart.getDatasetMeta(0);\n const style = meta.controller.getStyle(i);\n\n return {\n text: label,\n fillStyle: style.backgroundColor,\n strokeStyle: style.borderColor,\n fontColor: color,\n lineWidth: style.borderWidth,\n pointStyle: pointStyle,\n hidden: !chart.getDataVisibility(i),\n\n // Extra data used for toggling the correct item\n index: i\n };\n });\n }\n return [];\n }\n },\n\n onClick(e, legendItem, legend) {\n legend.chart.toggleDataVisibility(legendItem.index);\n legend.chart.update();\n }\n }\n }\n };\n\n constructor(chart, datasetIndex) {\n super(chart, datasetIndex);\n\n this.enableOptionSharing = true;\n this.innerRadius = undefined;\n this.outerRadius = undefined;\n this.offsetX = undefined;\n this.offsetY = undefined;\n }\n\n linkScales() {}\n\n /**\n\t * Override data parsing, since we are not using scales\n\t */\n parse(start, count) {\n const data = this.getDataset().data;\n const meta = this._cachedMeta;\n\n if (this._parsing === false) {\n meta._parsed = data;\n } else {\n let getter = (i) => +data[i];\n\n if (isObject(data[start])) {\n const {key = 'value'} = this._parsing;\n getter = (i) => +resolveObjectKey(data[i], key);\n }\n\n let i, ilen;\n for (i = start, ilen = start + count; i < ilen; ++i) {\n meta._parsed[i] = getter(i);\n }\n }\n }\n\n /**\n\t * @private\n\t */\n _getRotation() {\n return toRadians(this.options.rotation - 90);\n }\n\n /**\n\t * @private\n\t */\n _getCircumference() {\n return toRadians(this.options.circumference);\n }\n\n /**\n\t * Get the maximal rotation & circumference extents\n\t * across all visible datasets.\n\t */\n _getRotationExtents() {\n let min = TAU;\n let max = -TAU;\n\n for (let i = 0; i < this.chart.data.datasets.length; ++i) {\n if (this.chart.isDatasetVisible(i) && this.chart.getDatasetMeta(i).type === this._type) {\n const controller = this.chart.getDatasetMeta(i).controller;\n const rotation = controller._getRotation();\n const circumference = controller._getCircumference();\n\n min = Math.min(min, rotation);\n max = Math.max(max, rotation + circumference);\n }\n }\n\n return {\n rotation: min,\n circumference: max - min,\n };\n }\n\n /**\n\t * @param {string} mode\n\t */\n update(mode) {\n const chart = this.chart;\n const {chartArea} = chart;\n const meta = this._cachedMeta;\n const arcs = meta.data;\n const spacing = this.getMaxBorderWidth() + this.getMaxOffset(arcs) + this.options.spacing;\n const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0);\n const cutout = Math.min(toPercentage(this.options.cutout, maxSize), 1);\n const chartWeight = this._getRingWeight(this.index);\n\n // Compute the maximal rotation & circumference limits.\n // If we only consider our dataset, this can cause problems when two datasets\n // are both less than a circle with different rotations (starting angles)\n const {circumference, rotation} = this._getRotationExtents();\n const {ratioX, ratioY, offsetX, offsetY} = getRatioAndOffset(rotation, circumference, cutout);\n const maxWidth = (chartArea.width - spacing) / ratioX;\n const maxHeight = (chartArea.height - spacing) / ratioY;\n const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);\n const outerRadius = toDimension(this.options.radius, maxRadius);\n const innerRadius = Math.max(outerRadius * cutout, 0);\n const radiusLength = (outerRadius - innerRadius) / this._getVisibleDatasetWeightTotal();\n this.offsetX = offsetX * outerRadius;\n this.offsetY = offsetY * outerRadius;\n\n meta.total = this.calculateTotal();\n\n this.outerRadius = outerRadius - radiusLength * this._getRingWeightOffset(this.index);\n this.innerRadius = Math.max(this.outerRadius - radiusLength * chartWeight, 0);\n\n this.updateElements(arcs, 0, arcs.length, mode);\n }\n\n /**\n * @private\n */\n _circumference(i, reset) {\n const opts = this.options;\n const meta = this._cachedMeta;\n const circumference = this._getCircumference();\n if ((reset && opts.animation.animateRotate) || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) {\n return 0;\n }\n return this.calculateCircumference(meta._parsed[i] * circumference / TAU);\n }\n\n updateElements(arcs, start, count, mode) {\n const reset = mode === 'reset';\n const chart = this.chart;\n const chartArea = chart.chartArea;\n const opts = chart.options;\n const animationOpts = opts.animation;\n const centerX = (chartArea.left + chartArea.right) / 2;\n const centerY = (chartArea.top + chartArea.bottom) / 2;\n const animateScale = reset && animationOpts.animateScale;\n const innerRadius = animateScale ? 0 : this.innerRadius;\n const outerRadius = animateScale ? 0 : this.outerRadius;\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n let startAngle = this._getRotation();\n let i;\n\n for (i = 0; i < start; ++i) {\n startAngle += this._circumference(i, reset);\n }\n\n for (i = start; i < start + count; ++i) {\n const circumference = this._circumference(i, reset);\n const arc = arcs[i];\n const properties = {\n x: centerX + this.offsetX,\n y: centerY + this.offsetY,\n startAngle,\n endAngle: startAngle + circumference,\n circumference,\n outerRadius,\n innerRadius\n };\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, arc.active ? 'active' : mode);\n }\n startAngle += circumference;\n\n this.updateElement(arc, i, properties, mode);\n }\n }\n\n calculateTotal() {\n const meta = this._cachedMeta;\n const metaData = meta.data;\n let total = 0;\n let i;\n\n for (i = 0; i < metaData.length; i++) {\n const value = meta._parsed[i];\n if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) {\n total += Math.abs(value);\n }\n }\n\n return total;\n }\n\n calculateCircumference(value) {\n const total = this._cachedMeta.total;\n if (total > 0 && !isNaN(value)) {\n return TAU * (Math.abs(value) / total);\n }\n return 0;\n }\n\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const chart = this.chart;\n const labels = chart.data.labels || [];\n const value = formatNumber(meta._parsed[index], chart.options.locale);\n\n return {\n label: labels[index] || '',\n value,\n };\n }\n\n getMaxBorderWidth(arcs) {\n let max = 0;\n const chart = this.chart;\n let i, ilen, meta, controller, options;\n\n if (!arcs) {\n // Find the outmost visible dataset\n for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {\n if (chart.isDatasetVisible(i)) {\n meta = chart.getDatasetMeta(i);\n arcs = meta.data;\n controller = meta.controller;\n break;\n }\n }\n }\n\n if (!arcs) {\n return 0;\n }\n\n for (i = 0, ilen = arcs.length; i < ilen; ++i) {\n options = controller.resolveDataElementOptions(i);\n if (options.borderAlign !== 'inner') {\n max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0);\n }\n }\n return max;\n }\n\n getMaxOffset(arcs) {\n let max = 0;\n\n for (let i = 0, ilen = arcs.length; i < ilen; ++i) {\n const options = this.resolveDataElementOptions(i);\n max = Math.max(max, options.offset || 0, options.hoverOffset || 0);\n }\n return max;\n }\n\n /**\n\t * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly\n\t * @private\n\t */\n _getRingWeightOffset(datasetIndex) {\n let ringWeightOffset = 0;\n\n for (let i = 0; i < datasetIndex; ++i) {\n if (this.chart.isDatasetVisible(i)) {\n ringWeightOffset += this._getRingWeight(i);\n }\n }\n\n return ringWeightOffset;\n }\n\n /**\n\t * @private\n\t */\n _getRingWeight(datasetIndex) {\n return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0);\n }\n\n /**\n\t * Returns the sum of all visible data set weights.\n\t * @private\n\t */\n _getVisibleDatasetWeightTotal() {\n return this._getRingWeightOffset(this.chart.data.datasets.length) || 1;\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {toRadians, PI, formatNumber, _parseObjectDataRadialScale} from '../helpers/index.js';\n\nexport default class PolarAreaController extends DatasetController {\n\n static id = 'polarArea';\n\n /**\n * @type {any}\n */\n static defaults = {\n dataElementType: 'arc',\n animation: {\n animateRotate: true,\n animateScale: true\n },\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'startAngle', 'endAngle', 'innerRadius', 'outerRadius']\n },\n },\n indexAxis: 'r',\n startAngle: 0,\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n aspectRatio: 1,\n\n plugins: {\n legend: {\n labels: {\n generateLabels(chart) {\n const data = chart.data;\n if (data.labels.length && data.datasets.length) {\n const {labels: {pointStyle, color}} = chart.legend.options;\n\n return data.labels.map((label, i) => {\n const meta = chart.getDatasetMeta(0);\n const style = meta.controller.getStyle(i);\n\n return {\n text: label,\n fillStyle: style.backgroundColor,\n strokeStyle: style.borderColor,\n fontColor: color,\n lineWidth: style.borderWidth,\n pointStyle: pointStyle,\n hidden: !chart.getDataVisibility(i),\n\n // Extra data used for toggling the correct item\n index: i\n };\n });\n }\n return [];\n }\n },\n\n onClick(e, legendItem, legend) {\n legend.chart.toggleDataVisibility(legendItem.index);\n legend.chart.update();\n }\n }\n },\n\n scales: {\n r: {\n type: 'radialLinear',\n angleLines: {\n display: false\n },\n beginAtZero: true,\n grid: {\n circular: true\n },\n pointLabels: {\n display: false\n },\n startAngle: 0\n }\n }\n };\n\n constructor(chart, datasetIndex) {\n super(chart, datasetIndex);\n\n this.innerRadius = undefined;\n this.outerRadius = undefined;\n }\n\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const chart = this.chart;\n const labels = chart.data.labels || [];\n const value = formatNumber(meta._parsed[index].r, chart.options.locale);\n\n return {\n label: labels[index] || '',\n value,\n };\n }\n\n parseObjectData(meta, data, start, count) {\n return _parseObjectDataRadialScale.bind(this)(meta, data, start, count);\n }\n\n update(mode) {\n const arcs = this._cachedMeta.data;\n\n this._updateRadius();\n this.updateElements(arcs, 0, arcs.length, mode);\n }\n\n /**\n * @protected\n */\n getMinMax() {\n const meta = this._cachedMeta;\n const range = {min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY};\n\n meta.data.forEach((element, index) => {\n const parsed = this.getParsed(index).r;\n\n if (!isNaN(parsed) && this.chart.getDataVisibility(index)) {\n if (parsed < range.min) {\n range.min = parsed;\n }\n\n if (parsed > range.max) {\n range.max = parsed;\n }\n }\n });\n\n return range;\n }\n\n /**\n\t * @private\n\t */\n _updateRadius() {\n const chart = this.chart;\n const chartArea = chart.chartArea;\n const opts = chart.options;\n const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);\n\n const outerRadius = Math.max(minSize / 2, 0);\n const innerRadius = Math.max(opts.cutoutPercentage ? (outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);\n const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount();\n\n this.outerRadius = outerRadius - (radiusLength * this.index);\n this.innerRadius = this.outerRadius - radiusLength;\n }\n\n updateElements(arcs, start, count, mode) {\n const reset = mode === 'reset';\n const chart = this.chart;\n const opts = chart.options;\n const animationOpts = opts.animation;\n const scale = this._cachedMeta.rScale;\n const centerX = scale.xCenter;\n const centerY = scale.yCenter;\n const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI;\n let angle = datasetStartAngle;\n let i;\n\n const defaultAngle = 360 / this.countVisibleElements();\n\n for (i = 0; i < start; ++i) {\n angle += this._computeAngle(i, mode, defaultAngle);\n }\n for (i = start; i < start + count; i++) {\n const arc = arcs[i];\n let startAngle = angle;\n let endAngle = angle + this._computeAngle(i, mode, defaultAngle);\n let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(this.getParsed(i).r) : 0;\n angle = endAngle;\n\n if (reset) {\n if (animationOpts.animateScale) {\n outerRadius = 0;\n }\n if (animationOpts.animateRotate) {\n startAngle = endAngle = datasetStartAngle;\n }\n }\n\n const properties = {\n x: centerX,\n y: centerY,\n innerRadius: 0,\n outerRadius,\n startAngle,\n endAngle,\n options: this.resolveDataElementOptions(i, arc.active ? 'active' : mode)\n };\n\n this.updateElement(arc, i, properties, mode);\n }\n }\n\n countVisibleElements() {\n const meta = this._cachedMeta;\n let count = 0;\n\n meta.data.forEach((element, index) => {\n if (!isNaN(this.getParsed(index).r) && this.chart.getDataVisibility(index)) {\n count++;\n }\n });\n\n return count;\n }\n\n /**\n\t * @private\n\t */\n _computeAngle(index, mode, defaultAngle) {\n return this.chart.getDataVisibility(index)\n ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle)\n : 0;\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {valueOrDefault} from '../helpers/helpers.core.js';\n\nexport default class BubbleController extends DatasetController {\n\n static id = 'bubble';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'point',\n\n animations: {\n numbers: {\n type: 'number',\n properties: ['x', 'y', 'borderWidth', 'radius']\n }\n }\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n scales: {\n x: {\n type: 'linear'\n },\n y: {\n type: 'linear'\n }\n }\n };\n\n initialize() {\n this.enableOptionSharing = true;\n super.initialize();\n }\n\n /**\n\t * Parse array of primitive values\n\t * @protected\n\t */\n parsePrimitiveData(meta, data, start, count) {\n const parsed = super.parsePrimitiveData(meta, data, start, count);\n for (let i = 0; i < parsed.length; i++) {\n parsed[i]._custom = this.resolveDataElementOptions(i + start).radius;\n }\n return parsed;\n }\n\n /**\n\t * Parse array of arrays\n\t * @protected\n\t */\n parseArrayData(meta, data, start, count) {\n const parsed = super.parseArrayData(meta, data, start, count);\n for (let i = 0; i < parsed.length; i++) {\n const item = data[start + i];\n parsed[i]._custom = valueOrDefault(item[2], this.resolveDataElementOptions(i + start).radius);\n }\n return parsed;\n }\n\n /**\n\t * Parse array of objects\n\t * @protected\n\t */\n parseObjectData(meta, data, start, count) {\n const parsed = super.parseObjectData(meta, data, start, count);\n for (let i = 0; i < parsed.length; i++) {\n const item = data[start + i];\n parsed[i]._custom = valueOrDefault(item && item.r && +item.r, this.resolveDataElementOptions(i + start).radius);\n }\n return parsed;\n }\n\n /**\n\t * @protected\n\t */\n getMaxOverflow() {\n const data = this._cachedMeta.data;\n\n let max = 0;\n for (let i = data.length - 1; i >= 0; --i) {\n max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);\n }\n return max > 0 && max;\n }\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const labels = this.chart.data.labels || [];\n const {xScale, yScale} = meta;\n const parsed = this.getParsed(index);\n const x = xScale.getLabelForValue(parsed.x);\n const y = yScale.getLabelForValue(parsed.y);\n const r = parsed._custom;\n\n return {\n label: labels[index] || '',\n value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')'\n };\n }\n\n update(mode) {\n const points = this._cachedMeta.data;\n\n // Update Points\n this.updateElements(points, 0, points.length, mode);\n }\n\n updateElements(points, start, count, mode) {\n const reset = mode === 'reset';\n const {iScale, vScale} = this._cachedMeta;\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n\n for (let i = start; i < start + count; i++) {\n const point = points[i];\n const parsed = !reset && this.getParsed(i);\n const properties = {};\n const iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]);\n const vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]);\n\n properties.skip = isNaN(iPixel) || isNaN(vPixel);\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n\n if (reset) {\n properties.options.radius = 0;\n }\n }\n\n this.updateElement(point, i, properties, mode);\n }\n }\n\n /**\n\t * @param {number} index\n\t * @param {string} [mode]\n\t * @protected\n\t */\n resolveDataElementOptions(index, mode) {\n const parsed = this.getParsed(index);\n let values = super.resolveDataElementOptions(index, mode);\n\n // In case values were cached (and thus frozen), we need to clone the values\n if (values.$shared) {\n values = Object.assign({}, values, {$shared: false});\n }\n\n // Custom radius resolution\n const radius = values.radius;\n if (mode !== 'active') {\n values.radius = 0;\n }\n values.radius += valueOrDefault(parsed && parsed._custom, radius);\n\n return values;\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {isNullOrUndef} from '../helpers/index.js';\nimport {isNumber} from '../helpers/helpers.math.js';\nimport {_getStartAndCountOfVisiblePoints, _scaleRangesChanged} from '../helpers/helpers.extras.js';\n\nexport default class LineController extends DatasetController {\n\n static id = 'line';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: 'line',\n dataElementType: 'point',\n\n showLine: true,\n spanGaps: false,\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n scales: {\n _index_: {\n type: 'category',\n },\n _value_: {\n type: 'linear',\n },\n }\n };\n\n initialize() {\n this.enableOptionSharing = true;\n this.supportsDecimation = true;\n super.initialize();\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n const {dataset: line, data: points = [], _dataset} = meta;\n // @ts-ignore\n const animationsDisabled = this.chart._animationsDisabled;\n let {start, count} = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);\n\n this._drawStart = start;\n this._drawCount = count;\n\n if (_scaleRangesChanged(meta)) {\n start = 0;\n count = points.length;\n }\n\n // Update Line\n line._chart = this.chart;\n line._datasetIndex = this.index;\n line._decimated = !!_dataset._decimated;\n line.points = points;\n\n const options = this.resolveDatasetElementOptions(mode);\n if (!this.options.showLine) {\n options.borderWidth = 0;\n }\n options.segment = this.options.segment;\n this.updateElement(line, undefined, {\n animated: !animationsDisabled,\n options\n }, mode);\n\n // Update Points\n this.updateElements(points, start, count, mode);\n }\n\n updateElements(points, start, count, mode) {\n const reset = mode === 'reset';\n const {iScale, vScale, _stacked, _dataset} = this._cachedMeta;\n const {sharedOptions, includeOptions} = this._getSharedOptions(start, mode);\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const {spanGaps, segment} = this.options;\n const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;\n const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';\n const end = start + count;\n const pointsCount = points.length;\n let prevParsed = start > 0 && this.getParsed(start - 1);\n\n for (let i = 0; i < pointsCount; ++i) {\n const point = points[i];\n const properties = directUpdate ? point : {};\n\n if (i < start || i >= end) {\n properties.skip = true;\n continue;\n }\n\n const parsed = this.getParsed(i);\n const nullData = isNullOrUndef(parsed[vAxis]);\n const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);\n const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);\n\n properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;\n properties.stop = i > 0 && (Math.abs(parsed[iAxis] - prevParsed[iAxis])) > maxGapLength;\n if (segment) {\n properties.parsed = parsed;\n properties.raw = _dataset.data[i];\n }\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n }\n\n if (!directUpdate) {\n this.updateElement(point, i, properties, mode);\n }\n\n prevParsed = parsed;\n }\n }\n\n /**\n\t * @protected\n\t */\n getMaxOverflow() {\n const meta = this._cachedMeta;\n const dataset = meta.dataset;\n const border = dataset.options && dataset.options.borderWidth || 0;\n const data = meta.data || [];\n if (!data.length) {\n return border;\n }\n const firstPoint = data[0].size(this.resolveDataElementOptions(0));\n const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));\n return Math.max(border, firstPoint, lastPoint) / 2;\n }\n\n draw() {\n const meta = this._cachedMeta;\n meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis);\n super.draw();\n }\n}\n","import DoughnutController from './controller.doughnut.js';\n\n// Pie charts are Doughnut chart with different defaults\nexport default class PieController extends DoughnutController {\n\n static id = 'pie';\n\n /**\n * @type {any}\n */\n static defaults = {\n // The percentage of the chart that we cut out of the middle.\n cutout: 0,\n\n // The rotation of the chart, where the first data arc begins.\n rotation: 0,\n\n // The total circumference of the chart.\n circumference: 360,\n\n // The outer radius of the chart\n radius: '100%'\n };\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {_parseObjectDataRadialScale} from '../helpers/index.js';\n\nexport default class RadarController extends DatasetController {\n\n static id = 'radar';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: 'line',\n dataElementType: 'point',\n indexAxis: 'r',\n showLine: true,\n elements: {\n line: {\n fill: 'start'\n }\n },\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n aspectRatio: 1,\n\n scales: {\n r: {\n type: 'radialLinear',\n }\n }\n };\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const vScale = this._cachedMeta.vScale;\n const parsed = this.getParsed(index);\n\n return {\n label: vScale.getLabels()[index],\n value: '' + vScale.getLabelForValue(parsed[vScale.axis])\n };\n }\n\n parseObjectData(meta, data, start, count) {\n return _parseObjectDataRadialScale.bind(this)(meta, data, start, count);\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n const line = meta.dataset;\n const points = meta.data || [];\n const labels = meta.iScale.getLabels();\n\n // Update Line\n line.points = points;\n // In resize mode only point locations change, so no need to set the points or options.\n if (mode !== 'resize') {\n const options = this.resolveDatasetElementOptions(mode);\n if (!this.options.showLine) {\n options.borderWidth = 0;\n }\n\n const properties = {\n _loop: true,\n _fullLoop: labels.length === points.length,\n options\n };\n\n this.updateElement(line, undefined, properties, mode);\n }\n\n // Update Points\n this.updateElements(points, 0, points.length, mode);\n }\n\n updateElements(points, start, count, mode) {\n const scale = this._cachedMeta.rScale;\n const reset = mode === 'reset';\n\n for (let i = start; i < start + count; i++) {\n const point = points[i];\n const options = this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n const pointPosition = scale.getPointPositionForValue(i, this.getParsed(i).r);\n\n const x = reset ? scale.xCenter : pointPosition.x;\n const y = reset ? scale.yCenter : pointPosition.y;\n\n const properties = {\n x,\n y,\n angle: pointPosition.angle,\n skip: isNaN(x) || isNaN(y),\n options\n };\n\n this.updateElement(point, i, properties, mode);\n }\n }\n}\n","import DatasetController from '../core/core.datasetController.js';\nimport {isNullOrUndef} from '../helpers/index.js';\nimport {isNumber} from '../helpers/helpers.math.js';\nimport {_getStartAndCountOfVisiblePoints, _scaleRangesChanged} from '../helpers/helpers.extras.js';\n\nexport default class ScatterController extends DatasetController {\n\n static id = 'scatter';\n\n /**\n * @type {any}\n */\n static defaults = {\n datasetElementType: false,\n dataElementType: 'point',\n showLine: false,\n fill: false\n };\n\n /**\n * @type {any}\n */\n static overrides = {\n\n interaction: {\n mode: 'point'\n },\n\n scales: {\n x: {\n type: 'linear'\n },\n y: {\n type: 'linear'\n }\n }\n };\n\n /**\n\t * @protected\n\t */\n getLabelAndValue(index) {\n const meta = this._cachedMeta;\n const labels = this.chart.data.labels || [];\n const {xScale, yScale} = meta;\n const parsed = this.getParsed(index);\n const x = xScale.getLabelForValue(parsed.x);\n const y = yScale.getLabelForValue(parsed.y);\n\n return {\n label: labels[index] || '',\n value: '(' + x + ', ' + y + ')'\n };\n }\n\n update(mode) {\n const meta = this._cachedMeta;\n const {data: points = []} = meta;\n // @ts-ignore\n const animationsDisabled = this.chart._animationsDisabled;\n let {start, count} = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);\n\n this._drawStart = start;\n this._drawCount = count;\n\n if (_scaleRangesChanged(meta)) {\n start = 0;\n count = points.length;\n }\n\n if (this.options.showLine) {\n\n // https://github.com/chartjs/Chart.js/issues/11333\n if (!this.datasetElementType) {\n this.addElements();\n }\n const {dataset: line, _dataset} = meta;\n\n // Update Line\n line._chart = this.chart;\n line._datasetIndex = this.index;\n line._decimated = !!_dataset._decimated;\n line.points = points;\n\n const options = this.resolveDatasetElementOptions(mode);\n options.segment = this.options.segment;\n this.updateElement(line, undefined, {\n animated: !animationsDisabled,\n options\n }, mode);\n } else if (this.datasetElementType) {\n // https://github.com/chartjs/Chart.js/issues/11333\n delete meta.dataset;\n this.datasetElementType = false;\n }\n\n // Update Points\n this.updateElements(points, start, count, mode);\n }\n\n addElements() {\n const {showLine} = this.options;\n\n if (!this.datasetElementType && showLine) {\n this.datasetElementType = this.chart.registry.getElement('line');\n }\n\n super.addElements();\n }\n\n updateElements(points, start, count, mode) {\n const reset = mode === 'reset';\n const {iScale, vScale, _stacked, _dataset} = this._cachedMeta;\n const firstOpts = this.resolveDataElementOptions(start, mode);\n const sharedOptions = this.getSharedOptions(firstOpts);\n const includeOptions = this.includeOptions(mode, sharedOptions);\n const iAxis = iScale.axis;\n const vAxis = vScale.axis;\n const {spanGaps, segment} = this.options;\n const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;\n const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';\n let prevParsed = start > 0 && this.getParsed(start - 1);\n\n for (let i = start; i < start + count; ++i) {\n const point = points[i];\n const parsed = this.getParsed(i);\n const properties = directUpdate ? point : {};\n const nullData = isNullOrUndef(parsed[vAxis]);\n const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);\n const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);\n\n properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;\n properties.stop = i > 0 && (Math.abs(parsed[iAxis] - prevParsed[iAxis])) > maxGapLength;\n if (segment) {\n properties.parsed = parsed;\n properties.raw = _dataset.data[i];\n }\n\n if (includeOptions) {\n properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);\n }\n\n if (!directUpdate) {\n this.updateElement(point, i, properties, mode);\n }\n\n prevParsed = parsed;\n }\n\n this.updateSharedOptions(sharedOptions, mode, firstOpts);\n }\n\n /**\n\t * @protected\n\t */\n getMaxOverflow() {\n const meta = this._cachedMeta;\n const data = meta.data || [];\n\n if (!this.options.showLine) {\n let max = 0;\n for (let i = data.length - 1; i >= 0; --i) {\n max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);\n }\n return max > 0 && max;\n }\n\n const dataset = meta.dataset;\n const border = dataset.options && dataset.options.borderWidth || 0;\n\n if (!data.length) {\n return border;\n }\n\n const firstPoint = data[0].size(this.resolveDataElementOptions(0));\n const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));\n return Math.max(border, firstPoint, lastPoint) / 2;\n }\n}\n","import Element from '../core/core.element.js';\nimport {_angleBetween, getAngleFromPoint, TAU, HALF_PI, valueOrDefault} from '../helpers/index.js';\nimport {PI, _angleDiff, _normalizeAngle, _isBetween, _limitValue} from '../helpers/helpers.math.js';\nimport {_readValueToProps} from '../helpers/helpers.options.js';\nimport type {ArcOptions, Point} from '../types/index.js';\n\nfunction clipSelf(ctx: CanvasRenderingContext2D, element: ArcElement, endAngle: number) {\n const {startAngle, x, y, outerRadius, innerRadius, options} = element;\n const {borderWidth, borderJoinStyle} = options;\n const outerAngleClip = Math.min(borderWidth / outerRadius, _normalizeAngle(startAngle - endAngle));\n ctx.beginPath();\n ctx.arc(x, y, outerRadius - borderWidth / 2, startAngle + outerAngleClip / 2, endAngle - outerAngleClip / 2);\n\n if (innerRadius > 0) {\n const innerAngleClip = Math.min(borderWidth / innerRadius, _normalizeAngle(startAngle - endAngle));\n ctx.arc(x, y, innerRadius + borderWidth / 2, endAngle - innerAngleClip / 2, startAngle + innerAngleClip / 2, true);\n } else {\n const clipWidth = Math.min(borderWidth / 2, outerRadius * _normalizeAngle(startAngle - endAngle));\n\n if (borderJoinStyle === 'round') {\n ctx.arc(x, y, clipWidth, endAngle - PI / 2, startAngle + PI / 2, true);\n } else if (borderJoinStyle === 'bevel') {\n const r = 2 * clipWidth * clipWidth;\n const endX = -r * Math.cos(endAngle + PI / 2) + x;\n const endY = -r * Math.sin(endAngle + PI / 2) + y;\n const startX = r * Math.cos(startAngle + PI / 2) + x;\n const startY = r * Math.sin(startAngle + PI / 2) + y;\n ctx.lineTo(endX, endY);\n ctx.lineTo(startX, startY);\n }\n }\n ctx.closePath();\n\n ctx.moveTo(0, 0);\n ctx.rect(0, 0, ctx.canvas.width, ctx.canvas.height);\n\n ctx.clip('evenodd');\n}\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, 𝜃) 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, borderRadius} = 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 (options.selfJoin && endAngle - startAngle >= PI && borderRadius === 0 && borderJoinStyle !== 'miter') {\n clipSelf(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 selfJoin: false,\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 nonZeroBetween = _angleBetween(angle, startAngle, endAngle) && startAngle !== endAngle;\n const betweenAngles = _circumference >= TAU || nonZeroBetween;\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 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.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, 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","import {DoughnutController, PolarAreaController, defaults} 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\nfunction containsDefaultColorsDefenitions() {\n return defaults.borderColor !== 'rgba(0,0,0,0.1)' || defaults.backgroundColor !== 'rgba(0,0,0,0.1)';\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 const containsColorDefenition = (\n containsColorsDefinitions(datasets) ||\n containsColorsDefinition(chartOptions) ||\n (elements && containsColorsDefinitions(elements)) ||\n containsDefaultColorsDefenitions());\n\n if (!options.forceOverride && containsColorDefenition) {\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 a segment -> need to add another point before this,\n postponed.unshift(point);\n } else {\n points.push(point);\n if (!last) {\n // In the middle of a 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, getDatasetClipArea} 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 {chart, index, 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 const meta = chart.getDatasetMeta(index);\n const clip = getDatasetClipArea(chart, meta);\n if (target && line.points.length) {\n clipArea(ctx, area);\n doFill(ctx, {line, target, above, below, area, scale, axis, clip});\n unclipArea(ctx);\n }\n}\n\nfunction doFill(ctx, cfg) {\n const {line, target, above, below, area, scale, clip} = cfg;\n const property = line._loop ? 'angle' : cfg.axis;\n\n ctx.save();\n\n let fillColor = below;\n if (below !== above) {\n if (property === 'x') {\n clipVertical(ctx, target, area.top);\n fill(ctx, {line, target, color: above, scale, property, clip});\n ctx.restore();\n ctx.save();\n clipVertical(ctx, target, area.bottom);\n } else if (property === 'y') {\n clipHorizontal(ctx, target, area.left);\n fill(ctx, {line, target, color: below, scale, property, clip});\n ctx.restore();\n ctx.save();\n clipHorizontal(ctx, target, area.right);\n fillColor = above;\n }\n }\n fill(ctx, {line, target, color: fillColor, scale, property, clip});\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 clipHorizontal(ctx, target, clipX) {\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(clipX, firstPoint.y);\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(clipX, lastPoint.y);\n }\n }\n\n ctx.lineTo(clipX, target.first().y);\n ctx.closePath();\n ctx.clip();\n}\n\nfunction fill(ctx, cfg) {\n const {line, target, property, color, scale, clip} = 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, clip, 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, clip, bounds) {\n const chartArea = scale.chart.chartArea;\n const {property, start, end} = bounds || {};\n\n if (property === 'x' || property === 'y') {\n let left, top, right, bottom;\n\n if (property === 'x') {\n left = start;\n top = chartArea.top;\n right = end;\n bottom = chartArea.bottom;\n } else {\n left = chartArea.left;\n top = start;\n right = chartArea.right;\n bottom = end;\n }\n\n ctx.beginPath();\n\n if (clip) {\n left = Math.max(left, clip.left);\n right = Math.min(right, clip.right);\n top = Math.max(top, clip.top);\n bottom = Math.min(bottom, clip.bottom);\n }\n\n ctx.rect(left, top, right - left, 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 // No visible items where found, return false so we don't have to divide by 0 which reduces in NaN\n if (count === 0 || xSet.size === 0) {\n return false;\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","// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-nocheck\n\n/**\n * @namespace Chart\n */\nimport Chart from './core/core.controller.js';\n\nimport * as helpers from './helpers/index.js';\nimport _adapters from './core/core.adapters.js';\nimport Animation from './core/core.animation.js';\nimport animator from './core/core.animator.js';\nimport Animations from './core/core.animations.js';\nimport * as controllers from './controllers/index.js';\nimport DatasetController from './core/core.datasetController.js';\nimport Element from './core/core.element.js';\nimport * as elements from './elements/index.js';\nimport Interaction from './core/core.interaction.js';\nimport layouts from './core/core.layouts.js';\nimport * as platforms from './platform/index.js';\nimport * as plugins from './plugins/index.js';\nimport registry from './core/core.registry.js';\nimport Scale from './core/core.scale.js';\nimport * as scales from './scales/index.js';\nimport Ticks from './core/core.ticks.js';\n\n// Register built-ins\nChart.register(controllers, scales, elements, plugins);\n\nChart.helpers = {...helpers};\nChart._adapters = _adapters;\nChart.Animation = Animation;\nChart.Animations = Animations;\nChart.animator = animator;\nChart.controllers = registry.controllers.items;\nChart.DatasetController = DatasetController;\nChart.Element = Element;\nChart.elements = elements;\nChart.Interaction = Interaction;\nChart.layouts = layouts;\nChart.platforms = platforms;\nChart.Scale = Scale;\nChart.Ticks = Ticks;\n\n// Compatibility with ESM extensions\nObject.assign(Chart, controllers, scales, elements, plugins, platforms);\nChart.Chart = Chart;\n\nif (typeof window !== 'undefined') {\n window.Chart = Chart;\n}\n\nexport default Chart;\n\n"],"names":["noop","uid","id","isNullOrUndef","value","isArray","Array","type","Object","prototype","toString","call","slice","isObject","isNumberFinite","Number","isFinite","finiteOrDefault","defaultValue","valueOrDefault","toPercentage","dimension","endsWith","parseFloat","toDimension","callback","fn","args","thisArg","apply","each","loopable","reverse","i","len","keys","length","_elementsEqual","a0","a1","ilen","v0","v1","datasetIndex","index","clone","source","map","target","create","klen","k","isValidKey","key","indexOf","_merger","options","tval","sval","merge","sources","merger","current","mergeIf","_mergerIf","hasOwnProperty","keyResolvers","v","x","o","y","_splitKey","parts","split","tmp","part","push","resolveObjectKey","obj","resolver","_getKeyResolver","_capitalize","str","charAt","toUpperCase","defined","isFunction","setsEqual","a","b","size","item","has","_isClickEvent","e","PI","Math","TAU","PITAU","INFINITY","POSITIVE_INFINITY","RAD_PER_DEG","HALF_PI","QUARTER_PI","TWO_THIRDS_PI","log10","sign","almostEquals","epsilon","abs","niceNum","range","roundedRange","round","niceRange","pow","floor","fraction","_factorize","result","sqrt","sort","pop","isNumber","n","Symbol","toPrimitive","isNonPrimitive","isNaN","almostWhole","rounded","_setMinAndMaxByKey","array","property","min","max","toRadians","degrees","toDegrees","radians","_decimalPlaces","isFiniteNumber","p","getAngleFromPoint","centrePoint","anglePoint","distanceFromXCenter","distanceFromYCenter","radialDistanceFromCenter","angle","atan2","distance","distanceBetweenPoints","pt1","pt2","_angleDiff","_normalizeAngle","_angleBetween","start","end","sameAngleIsFullCircle","s","angleToStart","angleToEnd","startToAngle","endToAngle","_limitValue","_int16Range","_isBetween","_lookup","table","cmp","mid","hi","lo","_lookupByKey","last","ti","_rlookupByKey","_filterBetween","values","arrayEvents","listenArrayEvents","listener","_chartjs","listeners","defineProperty","configurable","enumerable","forEach","method","base","res","this","object","unlistenArrayEvents","stub","splice","_arrayUnique","items","set","Set","from","requestAnimFrame","window","requestAnimationFrame","throttled","argsToUse","ticking","debounce","delay","timeout","clearTimeout","setTimeout","_toLeftRightCenter","align","_alignStartEnd","_textX","left","right","rtl","_getStartAndCountOfVisiblePoints","meta","points","animationsDisabled","pointCount","count","_sorted","iScale","vScale","_parsed","spanGaps","dataset","axis","minDefined","maxDefined","getUserBounds","getPixelForValue","distanceToDefinedLo","findIndex","point","distanceToDefinedHi","_scaleRangesChanged","xScale","yScale","_scaleRanges","newRanges","xmin","xmax","ymin","ymax","changed","assign","Animator","constructor","_request","_charts","Map","_running","_lastDate","undefined","_notify","chart","anims","date","callbacks","numSteps","duration","initial","currentStep","_refresh","_update","Date","now","remaining","running","draw","_active","_total","tick","_getAnims","charts","get","complete","progress","listen","event","cb","add","reduce","acc","cur","_duration","stop","cancel","remove","delete","animator","lim","l","h","p2b","n2b","b2n","n2p","map$1","A","B","C","D","E","F","c","d","f","hex","h1","h2","eq","hexString","r","g","isShort","alpha","HUE_RE","hsl2rgbn","hsv2rgbn","hwb2rgbn","w","rgb","rgb2hsl","hueValue","calln","hsl2rgb","hue","hueParse","m","exec","p1","p2","hwb2rgb","hsv2rgb","Z","Y","X","W","V","U","T","S","R","Q","P","O","N","M","L","K","G","H","I","J","names$1","OiceXe","antiquewEte","aqua","aquamarRe","azuY","beige","bisque","black","blanKedOmond","Xe","XeviTet","bPwn","burlywood","caMtXe","KartYuse","KocTate","cSO","cSnflowerXe","cSnsilk","crimson","cyan","xXe","xcyan","xgTMnPd","xWay","xgYF","xgYy","xkhaki","xmagFta","xTivegYF","xSange","xScEd","xYd","xsOmon","xsHgYF","xUXe","xUWay","xUgYy","xQe","xviTet","dAppRk","dApskyXe","dimWay","dimgYy","dodgerXe","fiYbrick","flSOwEte","foYstWAn","fuKsia","gaRsbSo","ghostwEte","gTd","gTMnPd","Way","gYF","gYFLw","gYy","honeyMw","hotpRk","RdianYd","Rdigo","ivSy","khaki","lavFMr","lavFMrXsh","lawngYF","NmoncEffon","ZXe","ZcSO","Zcyan","ZgTMnPdLw","ZWay","ZgYF","ZgYy","ZpRk","ZsOmon","ZsHgYF","ZskyXe","ZUWay","ZUgYy","ZstAlXe","ZLw","lime","limegYF","lRF","magFta","maPon","VaquamarRe","VXe","VScEd","VpurpN","VsHgYF","VUXe","VsprRggYF","VQe","VviTetYd","midnightXe","mRtcYam","mistyPse","moccasR","navajowEte","navy","Tdlace","Tive","TivedBb","Sange","SangeYd","ScEd","pOegTMnPd","pOegYF","pOeQe","pOeviTetYd","papayawEp","pHKpuff","peru","pRk","plum","powMrXe","purpN","YbeccapurpN","Yd","Psybrown","PyOXe","saddNbPwn","sOmon","sandybPwn","sHgYF","sHshell","siFna","silver","skyXe","UXe","UWay","UgYy","snow","sprRggYF","stAlXe","tan","teO","tEstN","tomato","Qe","viTet","JHt","wEte","wEtesmoke","Lw","LwgYF","names","nameParse","unpacked","tkeys","j","ok","nk","replace","parseInt","unpack","transparent","toLowerCase","RGB_RE","to","modHSL","ratio","proto","fromObject","input","functionParse","rgbParse","Color","ret","_rgb","_valid","valid","rgbString","hslString","mix","color","weight","c1","c2","w2","w1","interpolate","t","rgb1","rgb2","clearer","greyscale","val","opaquer","negate","lighten","darken","saturate","desaturate","rotate","deg","isPatternOrGradient","getHoverColor","numbers","colors","intlCache","formatNumber","num","locale","cacheKey","JSON","stringify","formatter","Intl","NumberFormat","getNumberFormat","format","formatters","numeric","tickValue","ticks","notation","delta","maxTick","calculateDelta","logDelta","numDecimal","minimumFractionDigits","maximumFractionDigits","logarithmic","remain","significand","includes","Ticks","overrides","descriptors","getScope","node","root","scope","Defaults","_descriptors","_appliers","animation","backgroundColor","borderColor","datasets","devicePixelRatio","context","platform","getDevicePixelRatio","elements","events","font","family","style","lineHeight","hover","hoverBackgroundColor","ctx","hoverBorderColor","hoverColor","indexAxis","interaction","mode","intersect","includeInvisible","maintainAspectRatio","onHover","onClick","parsing","plugins","responsive","scale","scales","showLine","drawActiveElementsOnTop","describe","override","route","name","targetScope","targetName","scopeObject","targetScopeObject","privateName","defineProperties","writable","local","appliers","defaults","_scriptable","startsWith","_indexable","_fallback","easing","loop","properties","active","resize","show","animations","visible","hide","autoPadding","padding","top","bottom","display","offset","beginAtZero","bounds","clip","grace","grid","lineWidth","drawOnChartArea","drawTicks","tickLength","tickWidth","_ctx","tickColor","border","dash","dashOffset","width","title","text","minRotation","maxRotation","mirror","textStrokeWidth","textStrokeColor","autoSkip","autoSkipPadding","labelOffset","minor","major","crossAlign","showLabelBackdrop","backdropColor","backdropPadding","_isDomSupported","document","_getParentNode","domNode","parent","parentNode","host","parseMaxStyle","styleValue","parentProperty","valueInPixels","getComputedStyle","element","ownerDocument","defaultView","getStyle","el","getPropertyValue","positions","getPositionedStyle","styles","suffix","pos","height","useOffsetPos","shadowRoot","getRelativePosition","canvas","currentDevicePixelRatio","borderBox","boxSizing","paddings","borders","box","touches","offsetX","offsetY","rect","getBoundingClientRect","clientX","clientY","getCanvasPosition","xOffset","yOffset","round1","getMaximumSize","bbWidth","bbHeight","aspectRatio","margins","maxWidth","maxHeight","containerSize","container","containerStyle","containerBorder","containerPadding","clientWidth","clientHeight","getContainerSize","retinaScale","forceRatio","forceStyle","pixelRatio","deviceHeight","deviceWidth","setTransform","supportsEventListenerOptions","passiveSupported","passive","addEventListener","removeEventListener","readUsedSize","matches","match","toFontString","_measureText","data","gc","longest","string","textWidth","measureText","_longestText","arrayOfThings","cache","garbageCollect","save","jlen","thing","nestedThing","restore","gcLen","_alignPixel","pixel","halfWidth","clearCanvas","getContext","resetTransform","clearRect","drawPoint","drawPointLegend","cornerRadius","xOffsetW","yOffsetW","pointStyle","rotation","radius","rad","translate","drawImage","beginPath","ellipse","arc","closePath","moveTo","sin","cos","lineTo","SQRT1_2","fill","borderWidth","stroke","_isPointInArea","area","margin","clipArea","unclipArea","_steppedLineTo","previous","flip","midpoint","_bezierCurveTo","bezierCurveTo","cp1x","cp2x","cp1y","cp2y","decorateText","line","opts","strikethrough","underline","metrics","actualBoundingBoxLeft","actualBoundingBoxRight","actualBoundingBoxAscent","actualBoundingBoxDescent","yDecoration","strokeStyle","fillStyle","decorationWidth","drawBackdrop","oldColor","fillRect","renderText","lines","strokeWidth","strokeColor","translation","textAlign","textBaseline","setRenderOpts","backdrop","strokeText","fillText","addRoundedRectPath","topLeft","bottomLeft","bottomRight","topRight","_createResolver","scopes","prefixes","rootScopes","fallback","getTarget","finalRootScopes","_resolve","toStringTag","_cacheable","_scopes","_rootScopes","_getTarget","Proxy","deleteProperty","prop","_keys","_cached","proxy","prefix","readKey","needsSubResolver","createSubResolver","_resolveWithPrefixes","getOwnPropertyDescriptor","Reflect","getPrototypeOf","getKeysFromAllScopes","ownKeys","storage","_storage","_attachContext","subProxy","descriptorDefaults","_proxy","_context","_subProxy","_stack","setContext","receiver","isScriptable","getValue","Error","join","_resolveScriptable","isIndexable","arr","filter","_resolveArray","_resolveWithContext","allKeys","scriptable","indexable","_allKeys","resolve","resolveFallback","addScopes","parentScopes","parentFallback","allScopes","addScopesFromKey","subGetTarget","resolveKeysFromAllScopes","_parseObjectDataRadialScale","_parsing","parsed","parse","EPSILON","getPoint","skip","getValueAxis","splineCurve","firstPoint","middlePoint","afterPoint","next","d01","d12","s01","s12","fa","fb","splineCurveMonotone","valueAxis","pointsLen","deltaK","mK","pointBefore","pointCurrent","pointAfter","slopeDelta","alphaK","betaK","tauK","squaredMagnitude","monotoneAdjust","iPixel","vPixel","monotoneCompute","capControlPoint","pt","_updateBezierControlPoints","controlPoints","cubicInterpolationMode","prev","tension","capBezierPoints","inArea","inAreaPrev","inAreaNext","atEdge","elasticIn","elasticOut","effects","linear","easeInQuad","easeOutQuad","easeInOutQuad","easeInCubic","easeOutCubic","easeInOutCubic","easeInQuart","easeOutQuart","easeInOutQuart","easeInQuint","easeOutQuint","easeInOutQuint","easeInSine","easeOutSine","easeInOutSine","easeInExpo","easeOutExpo","easeInOutExpo","easeInCirc","easeOutCirc","easeInOutCirc","easeInElastic","easeOutElastic","easeInOutElastic","easeInBack","easeOutBack","easeInOutBack","easeInBounce","easeOutBounce","easeInOutBounce","_pointInLine","_steppedInterpolation","_bezierInterpolation","cp1","cp2","LINE_HEIGHT","FONT_STYLE","toLineHeight","numberOrZero","_readValueToProps","props","objProps","read","toTRBL","toTRBLCorners","toPadding","toFont","console","warn","inputs","info","cacheable","_addGrace","minmax","change","keepZero","createContext","parentContext","getRtlAdapter","rectX","setWidth","xPlus","leftForLtr","itemWidth","getRightToLeftAdapter","_itemWidth","overrideTextDirection","direction","original","getPropertyPriority","setProperty","prevTextDirection","restoreTextDirection","propertyFn","between","compare","normalize","normalizeSegment","_boundSegment","segment","startBound","endBound","getSegment","prevValue","inside","subStart","shouldStart","shouldStop","_boundSegments","segments","sub","_computeSegments","segmentOptions","_loop","findStartAndEnd","splitByStyles","solidSegments","_fullLoop","chartContext","_chart","baseStyle","readStyle","_datasetIndex","prevStyle","addStyle","st","dir","p0","p0DataIndex","p1DataIndex","styleChanged","doSplitByStyles","borderCapStyle","borderDash","borderDashOffset","borderJoinStyle","replacer","getSizeForArea","chartArea","field","getDatasetClipArea","_clip","disabled","getDatasetArea","pixelSize","fontStyle","fontFamily","binarySearch","metaset","controller","_cachedMeta","lookupMethod","_reversePixels","_sharedOptions","getRange","evaluateInteractionItems","position","handler","metasets","getSortedVisibleDatasetMetas","getIntersectItems","useFinalPosition","isPointInArea","inRange","getNearestCartesianItems","distanceMetric","useX","useY","deltaX","deltaY","getDistanceMetricForAxis","minDistance","center","getCenterPoint","getNearestItems","startAngle","endAngle","getProps","getNearestRadialItems","getAxisItems","rangeMethod","intersectsItem","Interaction","modes","getDatasetMeta","nearest","STATIC_POSITIONS","filterByPosition","filterDynamicPositionByAxis","sortByWeight","setLayoutDims","layouts","params","stacks","wrap","stack","stackWeight","placed","buildStacks","vBoxMaxWidth","hBoxMaxHeight","layout","fullSize","factor","horizontal","availableWidth","availableHeight","getCombinedMax","maxPadding","updateMaxPadding","boxPadding","updateDims","getPadding","newWidth","outerWidth","newHeight","outerHeight","widthChanged","heightChanged","same","other","getMargins","marginForPositions","fitBoxes","boxes","refitBoxes","refit","update","setBoxDims","placeBoxes","userPadding","addBox","_layers","z","removeBox","layoutItem","configure","minPadding","layoutBoxes","isHorizontal","wrapBoxes","centerHorizontal","centerVertical","leftAndTop","concat","rightAndBottom","vertical","buildLayoutBoxes","verticalBoxes","horizontalBoxes","beforeLayout","visibleVerticalBoxCount","total","freeze","updatePos","handleMaxPadding","BasePlatform","acquireContext","releaseContext","isAttached","updateConfig","config","BasicPlatform","EXPANDO_KEY","EVENT_TYPES","touchstart","touchmove","touchend","pointerenter","pointerdown","pointermove","pointerup","pointerleave","pointerout","isNullOrEmpty","eventListenerOptions","removeListener","nodeListContains","nodeList","contains","createAttachObserver","observer","MutationObserver","entries","trigger","entry","addedNodes","removedNodes","observe","childList","subtree","createDetachObserver","drpListeningCharts","oldDevicePixelRatio","onWindowResize","dpr","createResizeObserver","ResizeObserver","contentRect","listenDevicePixelRatioChanges","releaseObserver","disconnect","unlistenDevicePixelRatioChanges","createProxyAndListen","native","fromNativeEvent","addListener","DomPlatform","renderHeight","getAttribute","renderWidth","displayWidth","displayHeight","initCanvas","removeAttribute","setAttribute","proxies","$proxies","attach","detach","isConnected","_detectPlatform","OffscreenCanvas","interpolators","boolean","c0","helpersColor","number","Animation","cfg","currentValue","_fn","_easing","_start","_target","_prop","_from","_to","_promises","elapsed","wait","promises","Promise","rej","resolved","Animations","_properties","animationOptions","animatedProps","getOwnPropertyNames","option","_animateOptions","newOptions","$shared","$animations","resolveTargetOptions","_createAnimations","anim","all","awaitAll","then","scaleClip","allowedOverflow","getSortedDatasetIndices","filterVisible","_getSortedDatasetMetas","applyStack","dsIndex","singleMode","otherValue","found","isStacked","stacked","getOrCreateStack","stackKey","indexValue","subStack","getLastIndexInStack","positive","getMatchingVisibleMetas","updateStacks","_stacks","iAxis","vAxis","indexScale","valueScale","getStackKey","_top","_bottom","_visualValues","getFirstScaleId","shift","clearStacks","isDirectUpdateMode","cloneIfNotShared","cached","shared","DatasetController","static","_cachedDataOpts","getMeta","_type","_data","_objectData","_drawStart","_drawCount","enableOptionSharing","supportsDecimation","$context","_syncList","datasetElementType","dataElementType","initialize","linkScales","_stacked","addElements","isPluginEnabled","updateIndex","getDataset","chooseId","xid","xAxisID","yid","yAxisID","rid","rAxisID","iid","iAxisID","vid","vAxisID","getScaleForId","rScale","scaleID","_getOtherScale","reset","_destroy","_dataCheck","iAxisKey","vAxisKey","adata","convertObjectDataToArray","isExtensible","buildOrUpdateElements","resetNewElements","stackChanged","oldStacked","_resyncElements","scopeKeys","datasetScopeKeys","getOptionScopes","createResolver","sorted","parseArrayData","parseObjectData","parsePrimitiveData","isNotInOrderComparedToPrev","labels","getLabels","singleScale","xAxisKey","yAxisKey","getParsed","getDataElement","updateRangeFromParsed","parsedValue","NaN","getMinMax","canStack","otherScale","hidden","createStack","NEGATIVE_INFINITY","otherMin","otherMax","_skip","getAllParsedValues","getMaxOverflow","getLabelAndValue","label","getLabelForValue","toClip","defaultClip","resolveDatasetElementOptions","resolveDataElementOptions","dataIndex","raw","createDataContext","createDatasetContext","_resolveElementOptions","elementType","sharing","datasetElementScopeKeys","resolveNamedOptions","_resolveAnimations","transition","datasetAnimationScopeKeys","getSharedOptions","includeOptions","sharedOptions","_animationsDisabled","_getSharedOptions","firstOpts","previouslySharedOptions","updateSharedOptions","updateElement","_setStyle","removeHoverStyle","setHoverStyle","_removeDatasetHoverStyle","_setDatasetHoverStyle","arg1","arg2","numMeta","numData","_insertElements","_removeElements","move","updateElements","removed","_sync","_dataChanges","_onDataPush","arguments","_onDataPop","_onDataShift","_onDataSplice","newCount","_onDataUnshift","Element","tooltipPosition","hasValue","final","tickOpts","determinedMaxTicks","_tickSize","maxScale","_length","maxChart","_maxLength","determineMaxTicks","ticksLimit","maxTicksLimit","majorIndices","enabled","getMajorIndices","numMajorIndices","first","newTicks","spacing","ceil","skipMajors","evenMajorSpacing","diff","getEvenSpacing","factors","calculateSpacing","avgMajorSpacing","majorStart","majorEnd","offsetFromEdge","edge","getTicksLimit","ticksLength","sample","numItems","increment","getPixelForGridLine","offsetGridLines","validIndex","_startPixel","_endPixel","lineValue","getPixelForTick","getTickMarkLength","getTitleHeight","titleAlign","reverseAlign","Scale","super","_margins","paddingTop","paddingBottom","paddingLeft","paddingRight","labelRotation","_range","_gridLineItems","_labelItems","_labelSizes","_longestTextCache","_userMax","_userMin","_suggestedMax","_suggestedMin","_ticksLength","_borderValue","_cache","_dataLimitsCached","init","suggestedMin","suggestedMax","metas","getTicks","xLabels","yLabels","getLabelItems","_computeLabelItems","beforeUpdate","sampleSize","beforeSetDimensions","setDimensions","afterSetDimensions","beforeDataLimits","determineDataLimits","afterDataLimits","beforeBuildTicks","buildTicks","afterBuildTicks","samplingEnabled","_convertTicksToLabels","beforeCalculateLabelRotation","calculateLabelRotation","afterCalculateLabelRotation","afterAutoSkip","beforeFit","fit","afterFit","afterUpdate","startPixel","endPixel","reversePixels","_alignToPixels","alignToPixels","_callHooks","notifyPlugins","beforeTickToLabelConversion","generateTickLabels","afterTickToLabelConversion","numTicks","maxLabelDiagonal","_isVisible","labelSizes","_getLabelSizes","maxLabelWidth","widest","maxLabelHeight","highest","asin","minSize","titleOpts","gridOpts","titleHeight","tickPadding","angleRadians","labelHeight","labelWidth","_calculatePadding","_handleMargins","isRotated","labelsBelowTicks","offsetLeft","offsetRight","isFullSize","_computeLabelSizes","caches","widths","heights","tickFont","fontString","nestedLabel","widestLabelSize","highestLabelSize","_resolveTickFontOptions","valueAt","idx","getValueForPixel","getPixelForDecimal","decimal","getDecimalForPixel","getBasePixel","getBaseValue","createTickContext","optionTicks","rot","_computeGridLineItems","tl","borderOpts","axisWidth","axisHalfWidth","alignBorderValue","borderValue","alignedLineValue","tx1","ty1","tx2","ty2","x1","y1","x2","y2","positionAxisID","limit","step","optsAtIndex","optsAtIndexBorder","lineColor","tickBorderDash","tickBorderDashOffset","tickAndPadding","hTickAndPadding","lineCount","textOffset","_getXAxisLabelAlignment","_getYAxisLabelAlignment","halfCount","tickTextAlign","labelPadding","_computeLabelArea","drawBackground","getLineWidthForValue","drawGrid","drawLine","setLineDash","lineDashOffset","drawBorder","lastLineWidth","drawLabels","renderTextOptions","drawTitle","titleX","titleY","titleArgs","tz","gz","bz","axisID","_maxDigits","fontSize","TypedRegistry","isForType","isPrototypeOf","register","parentScope","isIChartComponent","itemDefaults","defaultRoutes","routes","propertyParts","sourceName","sourceScope","routeDefaults","registerDefaults","unregister","Registry","controllers","_typedRegistries","_each","addControllers","addPlugins","addScales","getController","_get","getElement","getPlugin","getScale","removeControllers","removeElements","removePlugins","removeScales","typedRegistry","arg","reg","_getRegistryForType","_exec","itemReg","registry","component","camelMethod","PluginService","_init","notify","hook","_createDescriptors","descriptor","plugin","callCallback","cancelable","invalidate","_oldCache","_notifyStateChanges","localIds","allPlugins","getOpts","pluginOpts","createDescriptors","previousDescriptors","some","pluginScopeKeys","getIndexAxis","datasetDefaults","idMatchesAxis","determineAxis","scaleOptions","getAxisFromDataset","mergeScaleConfig","chartDefaults","configScales","chartIndexAxis","scaleConf","error","boundDs","retrieveAxisFromDatasets","defaultId","getDefaultScaleIDFromAxis","defaultScaleOptions","defaultID","getAxisFromDefaultScaleID","initOptions","initData","keyCache","keysCached","cachedKeys","generate","addIfFound","Config","_config","initConfig","_scopeCache","_resolverCache","clearCache","clear","datasetType","additionalOptionScopes","_cachedScopes","mainScope","resetCache","keyLists","chartOptionScopes","subPrefixes","getResolver","hasFunction","needContext","resolverCache","KNOWN_POSITIONS","positionIsHorizontal","compare2Level","l1","l2","onAnimationsComplete","onComplete","onAnimationProgress","onProgress","getCanvas","getElementById","instances","getChart","moveNumericKeys","intKey","Chart","invalidatePlugins","userConfig","initialCanvas","existingChart","_options","_aspectRatio","_metasets","_lastEvent","_listeners","_responsiveListeners","_sortedMetasets","_plugins","_hiddenIndices","attached","_doResize","resizeDelay","_initialize","bindEvents","_resizeBeforeDraw","_resize","newSize","newRatio","onResize","render","ensureScalesHaveIDs","axisOptions","buildOrUpdateScales","scaleOpts","updated","isRadial","dposition","dtype","scaleType","hasUpdated","_updateMetasets","_destroyDatasetMeta","_removeUnreferencedMetasets","_dataset","buildOrUpdateControllers","newControllers","order","isDatasetVisible","ControllerClass","_resetElements","animsDisabled","_updateScales","_checkEventBindings","_updateHiddenIndices","_minPadding","_updateLayout","_updateDatasets","_eventHandler","_updateHoverStyles","existingEvents","newEvents","unbindEvents","changes","_getUniformDataChanges","datasetCount","makeSet","changeSet","noArea","_idx","_updateDataset","layers","_drawDatasets","_drawDataset","getElementsAtEventForMode","getVisibleDatasetCount","setDatasetVisibility","toggleDataVisibility","getDataVisibility","_updateVisibility","_stop","destroy","toBase64Image","toDataURL","bindUserEvents","bindResponsiveEvents","_add","_remove","detached","updateHoverStyle","getActiveElements","setActiveElements","activeElements","lastActive","pluginId","replay","hoverOptions","deactivated","activated","inChartArea","eventFilter","_handleEvent","_getActiveElements","isClick","lastEvent","determineLastEvent","abstract","DateAdapterBase","members","formats","startOf","endOf","_adapters","_date","computeMinSampleSize","$bar","visibleMetas","getAllScaleValues","curr","updateMinAndPrev","parseValue","startValue","endValue","barStart","barEnd","_custom","parseFloatBar","parseArrayOrPrimitive","isFloatBar","custom","setBorderSkipped","borderSkipped","borderProps","enableBorderRadius","parseEdge","orig","v2","startEnd","setInflateAmount","inflateAmount","DoughnutController","animateRotate","animateScale","cutout","circumference","legend","generateLabels","fontColor","legendItem","innerRadius","outerRadius","getter","_getRotation","_getCircumference","_getRotationExtents","arcs","getMaxBorderWidth","getMaxOffset","maxSize","chartWeight","_getRingWeight","ratioX","ratioY","startX","startY","endX","endY","calcMax","calcMin","maxX","maxY","minX","minY","getRatioAndOffset","maxRadius","radiusLength","_getVisibleDatasetWeightTotal","calculateTotal","_getRingWeightOffset","_circumference","calculateCircumference","animationOpts","centerX","centerY","metaData","borderAlign","hoverBorderWidth","hoverOffset","ringWeightOffset","PolarAreaController","angleLines","circular","pointLabels","bind","_updateRadius","cutoutPercentage","xCenter","yCenter","datasetStartAngle","getIndexAngle","defaultAngle","countVisibleElements","_computeAngle","getDistanceFromCenterForValue","categoryPercentage","barPercentage","grouped","_index_","_value_","bars","ruler","_getRuler","vpixels","head","_calculateBarValuePixels","ipixels","_calculateBarIndexPixels","_getStacks","currentParsed","iScaleValue","skipNull","find","_getStackCount","_getAxisCount","_getAxis","getFirstScaleIdForIndexAxis","indexScaleId","firstScaleAxisId","_getStackIndex","pixels","barThickness","stackCount","baseValue","minBarLength","actualBase","floating","barSign","halfGrid","maxBarThickness","Infinity","axisCount","percent","chunk","computeFlexCategoryTraits","thickness","computeFitCategoryTraits","axisNumber","stackIndex","rects","_decimated","animated","maxGapLength","directUpdate","pointsCount","prevParsed","nullData","lastPoint","updateControlPoints","pointPosition","getPointPositionForValue","parseBorderRadius","angleDelta","borderRadius","halfThickness","innerLimit","computeOuterLimit","outerArcLimit","outerStart","outerEnd","innerStart","innerEnd","rThetaToXY","theta","pathArc","pixelMargin","innerR","spacingOffset","avNogSpacingRadius","angleOffset","outerStartAdjustedRadius","outerEndAdjustedRadius","outerStartAdjustedAngle","outerEndAdjustedAngle","innerStartAdjustedRadius","innerEndAdjustedRadius","innerStartAdjustedAngle","innerEndAdjustedAngle","outerMidAdjustedAngle","pCenter","p4","innerMidAdjustedAngle","p8","outerStartX","outerStartY","outerEndX","outerEndY","fullCircles","inner","lineJoin","angleMargin","clipArc","selfJoin","outerAngleClip","innerAngleClip","clipWidth","clipSelf","setStyle","lineCap","pathVars","paramsStart","paramsEnd","segmentStart","segmentEnd","outside","pathSegment","lineMethod","stepped","getLineMethod","fastPathSegment","prevX","lastY","avgX","countX","pointIndex","drawX","truncX","_getSegmentMethod","usePath2D","Path2D","path","_path","strokePathWithCache","segmentMethod","strokePathDirect","LineElement","_points","_segments","_pointsUpdated","_interpolate","_getInterpolationMethod","interpolated","hitRadius","getBarBounds","bar","half","skipOrLimit","boundingRects","maxW","maxH","parseBorderWidth","maxR","enableBorder","outer","skipX","skipY","addNormalRectPath","inflateRect","amount","refRect","chartX","chartY","rAdjust","nonZeroBetween","betweenAngles","withinRadius","halfAngle","halfRadius","radiusOffset","drawArc","addRectPath","mouseX","mouseY","inXRange","inYRange","hoverRadius","findOrAddLabel","addedLabels","unshift","addIfString","lastIndexOf","_getLabelForValue","relativeLabelSize","minSpacing","LinearScaleBase","_startValue","_endValue","_valueRange","handleTickRangeOptions","setMin","setMax","minSign","maxSign","getTickLimit","maxTicks","stepSize","computeTickLimit","generationOptions","dataRange","precision","maxDigits","includeBounds","unit","maxSpaces","rmin","rmax","countDefined","niceMin","niceMax","numSpaces","decimalPlaces","generateTicks","LinearScale","log10Floor","changeExponent","isMajor","tickVal","steps","rangeExp","rangeStep","minExp","exp","startExp","lastTick","LogarithmicScale","_zero","getTickBackdropHeight","determineLimits","fitWithPointLabels","_padding","limits","valueCount","_pointLabels","pointLabelOpts","additionalAngle","centerPointLabels","getPointLabelContext","getPointPosition","drawingArea","plFont","textSize","updateLimits","setCenterPoint","_pointLabelItems","itemOpts","extra","createPointLabelItem","isNotOverlapped","buildPointLabelItems","hLimits","vLimits","outerDistance","pointLabelPosition","yForAngle","getTextAlignForAngle","leftForTextAlign","drawPointLabelBox","backdropLeft","backdropTop","backdropWidth","backdropHeight","pathRadiusLine","labelCount","RadialLinearScale","animate","leftMovement","rightMovement","topMovement","bottomMovement","scalingFactor","getValueForDistanceFromCenter","scaledDistance","pointLabel","createPointLabelContext","distanceFromCenter","getBasePosition","getPointLabelPosition","drawPointLabels","gridLineOpts","drawRadiusLine","INTERVALS","millisecond","common","second","minute","hour","day","week","month","quarter","year","UNITS","sorter","adapter","_adapter","parser","isoWeekday","_parseOpts","determineUnitForAutoTicks","minUnit","capacity","interval","MAX_SAFE_INTEGER","addTick","time","timestamps","ticksFromTimestamps","majorUnit","setMajorTicks","TimeScale","adapters","displayFormats","_unit","_majorUnit","_offsets","_normalized","normalized","_applyBounds","_getLabelBounds","getLabelTimestamps","timeOpts","_generate","_getLabelCapacity","determineUnitForFormatting","determineMajorUnit","initOffsets","offsetAfterAutoskip","getDecimalForValue","weekday","hasWeekday","getDataTimestamps","tooltipFormat","datetime","fmt","_tickFormatFunction","minorFormat","majorFormat","offsets","_getLabelSize","ticksOpts","tickLabelWidth","cosRotation","sinRotation","tickFontSize","exampleTime","exampleLabel","prevSource","nextSource","prevTarget","nextTarget","span","_addedLabels","added","_table","_minPos","_tableRange","_getTimestampsForTable","buildLookupTable","BORDER_COLORS","BACKGROUND_COLORS","getBorderColor","getBackgroundColor","getColorizer","colorizeDoughnutDataset","colorizePolarAreaDataset","colorizeDefaultDataset","containsColorsDefinitions","plugin_colors","forceOverride","_args","chartOptions","containsColorDefenition","colorizer","cleanDecimatedDataset","cleanDecimatedData","plugin_decimation","algorithm","beforeElementsUpdate","xAxis","getStartAndCountOfVisiblePointsSimplified","threshold","decimated","samples","bucketWidth","sampledIndex","endIndex","maxAreaPoint","maxArea","nextA","avgY","avgRangeStart","avgRangeEnd","avgRangeLength","rangeOffs","rangeTo","pointAx","pointAy","lttbDecimation","minIndex","maxIndex","startIndex","xMin","dx","lastIndex","intermediateIndex1","intermediateIndex2","minMaxDecimation","_getBounds","_findSegmentEnd","_getEdge","_createBoundaryLine","boundary","linePoints","_pointsFromSegments","_shouldApplyFill","_resolveTarget","propagate","visited","_decodeFill","fillOption","parseFillOption","firstCh","decodeTargetIndex","addPointsBelow","sourcePoint","linesBelow","postponed","findPoint","pointValue","firstValue","lastValue","simpleArc","getLineByIndex","sourcePoints","below","getLinesBelow","_buildStackLine","_getTargetValue","computeCircularBoundary","_getTargetPixel","computeLinearBoundary","computeBoundary","_drawfill","lineOpts","above","fillColor","clipVertical","clipHorizontal","doFill","clipY","lineLoop","clipX","tpoints","targetSegments","tgt","subBounds","fillSources","fillSource","src","notShape","clipBounds","interpolatedLineTo","targetLoop","interpolatedPoint","afterDatasetsUpdate","$filler","beforeDraw","drawTime","beforeDatasetsDraw","beforeDatasetDraw","getBoxSize","labelOpts","boxHeight","boxWidth","usePointStyle","pointStyleWidth","itemHeight","Legend","_added","legendHitBoxes","_hoveredItem","doughnutMode","legendItems","columnSizes","lineWidths","buildLabels","labelFont","_computeTitleHeight","_fitRows","_fitCols","hitboxes","totalHeight","row","_itemHeight","heightLimit","totalWidth","currentColWidth","currentColHeight","col","legendItemText","calculateItemWidth","fontLineHeight","calculateLegendItemHeight","calculateItemHeight","calculateItemSize","adjustHitBoxes","rtlHelper","hitbox","_draw","defaultColor","halfFontSize","cursor","textDirection","lineDash","drawOptions","SQRT2","yBoxTop","xBoxLeft","drawLegendBox","titleFont","titlePadding","topPaddingPlusHalfFontSize","_getLegendItemAt","hitBox","lh","handleEvent","onLeave","isListened","hoveredItem","sameItem","plugin_legend","_element","afterEvent","ci","useBorderRadius","Title","_drawArgs","fontOpts","plugin_title","titleBlock","createTitle","WeakMap","plugin_subtitle","positioners","average","xSet","eventPosition","nearestElement","tp","pushOrConcat","toPush","splitNewlines","String","createTooltipItem","formattedValue","getTooltipSize","tooltip","body","footer","bodyFont","footerFont","titleLineCount","footerLineCount","bodyLineItemCount","combinedBodyLength","bodyItem","before","after","beforeBody","afterBody","titleSpacing","titleMarginBottom","displayColors","bodySpacing","footerMarginTop","footerSpacing","widthPadding","maxLineWidth","determineXAlign","yAlign","chartWidth","xAlign","caret","caretSize","caretPadding","doesNotFitWithAlign","determineAlignment","determineYAlign","getBackgroundPoint","alignment","paddingAndSize","alignX","alignY","getAlignedX","getBeforeAfterBodyLines","overrideCallbacks","defaultCallbacks","beforeTitle","tooltipItems","afterTitle","beforeLabel","tooltipItem","labelColor","labelTextColor","bodyColor","labelPointStyle","afterLabel","beforeFooter","afterFooter","invokeCallbackWithFallback","Tooltip","opacity","_eventPosition","_size","_cachedAnimations","_tooltipItems","dataPoints","caretX","caretY","labelColors","labelPointStyles","labelTextColors","getTitle","getBeforeBody","getBody","bodyItems","scoped","getAfterBody","getFooter","_createItems","itemSort","positionAndSize","backgroundPoint","external","drawCaret","tooltipPoint","caretPosition","getCaretPosition","x3","y3","ptX","ptY","titleColor","_drawColorBox","colorX","rtlColorX","yOffSet","colorY","multiKeyBackground","outerX","innerX","strokeRect","drawBody","bodyAlign","bodyLineHeight","xLinePadding","fillLineOfText","bodyAlignForCalculation","textColor","drawFooter","footerAlign","footerColor","tooltipSize","quadraticCurveTo","_updateAnimationTarget","animX","animY","_willRender","hasTooltipContent","globalAlpha","positionChanged","_positionChanged","_ignoreReplayEvents","plugin_tooltip","afterInit","afterDraw","helpers","platforms"],"mappings":";;;;;;0bAUO,SAASA,IAEf,CAKM,MAAMC,EAAO,MAClB,IAAIC,EAAK,EACT,MAAO,IAAMA,GACf,EAHoB,GAUb,SAASC,EAAcC,GAC5B,OAAOA,OACT,CAOO,SAASC,EAAqBD,GACnC,GAAIE,MAAMD,SAAWC,MAAMD,QAAQD,GACjC,OAAO,EAET,MAAMG,EAAOC,OAAOC,UAAUC,SAASC,KAAKP,GAC5C,MAAyB,YAArBG,EAAKK,MAAM,EAAG,IAAuC,WAAnBL,EAAKK,OAAO,EAIpD,CAOO,SAASC,EAAST,GACvB,OAAiB,OAAVA,GAA4D,oBAA1CI,OAAOC,UAAUC,SAASC,KAAKP,EAC1D,CAMA,SAASU,EAAeV,GACtB,OAAyB,iBAAVA,GAAsBA,aAAiBW,SAAWC,UAAUZ,EAC7E,CAUO,SAASa,EAAgBb,EAAgBc,GAC9C,OAAOJ,EAAeV,GAASA,EAAQc,CACzC,CAOO,SAASC,EAAkBf,EAAsBc,GACtD,YAAwB,IAAVd,EAAwBc,EAAed,CACvD,CAEO,MAAMgB,EAAe,CAAChB,EAAwBiB,IAClC,iBAAVjB,GAAsBA,EAAMkB,SAAS,KAC1CC,WAAWnB,GAAS,KACjBA,EAAQiB,EAEFG,EAAc,CAACpB,EAAwBiB,IACjC,iBAAVjB,GAAsBA,EAAMkB,SAAS,KAC1CC,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GAA8B,aAATA,GAAgC,aAATA,EACnEa,YAAY,EACZpY,UAAW,CACTkY,aAAa,EACbE,YAAY,GAEdlD,UAAW,CACTmD,WAAW,GAEbO,WAAY,CACVP,UAAW,cAKf0nC,uBAAwB,CAAC,uBCzyC3B0B,GAAMrH,SAASa,GAAahkC,GAAQvB,GAAUoB,GAE9C2qC,GAAMq2B,QAAU,IAAIA,IACpBr2B,GAAM0G,UAAYA,GAClB1G,GAAMlhB,UAAYA,GAClBkhB,GAAMjgB,WAAaA,GACnBigB,GAAMz/C,SAAWA,GACjBy/C,GAAMxG,YAAcqB,GAASrB,YAAYn/C,MACzC2lD,GAAM7c,kBAAoBA,GAC1B6c,GAAM1U,QAAUA,GAChB0U,GAAM/rC,SAAWA,GACjB+rC,GAAMpqB,YAAcA,GACpBoqB,GAAM3pB,QAAUA,GAChB2pB,GAAMs2B,UAAYA,GAClBt2B,GAAMzR,MAAQA,GACdyR,GAAMjtC,MAAQA,GAGdzkB,OAAOoP,OAAOsiD,GAAOxG,GAAahkC,GAAQvB,GAAUoB,EAASihE,IAC7Dt2B,GAAMA,MAAQA,GAEQ,oBAAXtlD,SACTA,OAAOslD,MAAQA","x_google_ignoreList":[5]} \ No newline at end of file diff --git a/frontend/node_modules/chart.js/dist/chunks/helpers.dataset.cjs b/frontend/node_modules/chart.js/dist/chunks/helpers.dataset.cjs new file mode 100644 index 0000000000000000000000000000000000000000..c71d10e3166b4c0c858f4df81e1fb25652d55185 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/chunks/helpers.dataset.cjs @@ -0,0 +1,2915 @@ +/*! + * Chart.js v4.5.0 + * https://www.chartjs.org + * (c) 2025 Chart.js Contributors + * Released under the MIT License + */ +'use strict'; + +var color$1 = require('@kurkle/color'); + +/** + * @namespace Chart.helpers + */ /** + * An empty function that can be used, for example, for optional callback. + */ function noop() { +/* noop */ } +/** + * Returns a unique id, sequentially generated from a global variable. + */ const uid = (()=>{ + let id = 0; + return ()=>id++; +})(); +/** + * Returns true if `value` is neither null nor undefined, else returns false. + * @param value - The value to test. + * @since 2.7.0 + */ function isNullOrUndef(value) { + return value === null || value === undefined; +} +/** + * Returns true if `value` is an array (including typed arrays), else returns false. + * @param value - The value to test. + * @function + */ function isArray(value) { + if (Array.isArray && Array.isArray(value)) { + return true; + } + const type = Object.prototype.toString.call(value); + if (type.slice(0, 7) === '[object' && type.slice(-6) === 'Array]') { + return true; + } + return false; +} +/** + * Returns true if `value` is an object (excluding null), else returns false. + * @param value - The value to test. + * @since 2.7.0 + */ function isObject(value) { + return value !== null && Object.prototype.toString.call(value) === '[object Object]'; +} +/** + * Returns true if `value` is a finite number, else returns false + * @param value - The value to test. + */ function isNumberFinite(value) { + return (typeof value === 'number' || value instanceof Number) && isFinite(+value); +} +/** + * Returns `value` if finite, else returns `defaultValue`. + * @param value - The value to return if defined. + * @param defaultValue - The value to return if `value` is not finite. + */ function finiteOrDefault(value, defaultValue) { + return isNumberFinite(value) ? value : defaultValue; +} +/** + * Returns `value` if defined, else returns `defaultValue`. + * @param value - The value to return if defined. + * @param defaultValue - The value to return if `value` is undefined. + */ function valueOrDefault(value, defaultValue) { + return typeof value === 'undefined' ? defaultValue : value; +} +const toPercentage = (value, dimension)=>typeof value === 'string' && value.endsWith('%') ? parseFloat(value) / 100 : +value / dimension; +const toDimension = (value, dimension)=>typeof value === 'string' && value.endsWith('%') ? parseFloat(value) / 100 * dimension : +value; +/** + * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the + * value returned by `fn`. If `fn` is not a function, this method returns undefined. + * @param fn - The function to call. + * @param args - The arguments with which `fn` should be called. + * @param [thisArg] - The value of `this` provided for the call to `fn`. + */ function callback(fn, args, thisArg) { + if (fn && typeof fn.call === 'function') { + return fn.apply(thisArg, args); + } +} +function each(loopable, fn, thisArg, reverse) { + let i, len, keys; + if (isArray(loopable)) { + len = loopable.length; + if (reverse) { + for(i = len - 1; i >= 0; i--){ + fn.call(thisArg, loopable[i], i); + } + } else { + for(i = 0; i < len; i++){ + fn.call(thisArg, loopable[i], i); + } + } + } else if (isObject(loopable)) { + keys = Object.keys(loopable); + len = keys.length; + for(i = 0; i < len; i++){ + fn.call(thisArg, loopable[keys[i]], keys[i]); + } + } +} +/** + * Returns true if the `a0` and `a1` arrays have the same content, else returns false. + * @param a0 - The array to compare + * @param a1 - The array to compare + * @private + */ function _elementsEqual(a0, a1) { + let i, ilen, v0, v1; + if (!a0 || !a1 || a0.length !== a1.length) { + return false; + } + for(i = 0, ilen = a0.length; i < ilen; ++i){ + v0 = a0[i]; + v1 = a1[i]; + if (v0.datasetIndex !== v1.datasetIndex || v0.index !== v1.index) { + return false; + } + } + return true; +} +/** + * Returns a deep copy of `source` without keeping references on objects and arrays. + * @param source - The value to clone. + */ function clone(source) { + if (isArray(source)) { + return source.map(clone); + } + if (isObject(source)) { + const target = Object.create(null); + const keys = Object.keys(source); + const klen = keys.length; + let k = 0; + for(; k < klen; ++k){ + target[keys[k]] = clone(source[keys[k]]); + } + return target; + } + return source; +} +function isValidKey(key) { + return [ + '__proto__', + 'prototype', + 'constructor' + ].indexOf(key) === -1; +} +/** + * The default merger when Chart.helpers.merge is called without merger option. + * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback. + * @private + */ function _merger(key, target, source, options) { + if (!isValidKey(key)) { + return; + } + const tval = target[key]; + const sval = source[key]; + if (isObject(tval) && isObject(sval)) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + merge(tval, sval, options); + } else { + target[key] = clone(sval); + } +} +function merge(target, source, options) { + const sources = isArray(source) ? source : [ + source + ]; + const ilen = sources.length; + if (!isObject(target)) { + return target; + } + options = options || {}; + const merger = options.merger || _merger; + let current; + for(let i = 0; i < ilen; ++i){ + current = sources[i]; + if (!isObject(current)) { + continue; + } + const keys = Object.keys(current); + for(let k = 0, klen = keys.length; k < klen; ++k){ + merger(keys[k], target, current, options); + } + } + return target; +} +function mergeIf(target, source) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return merge(target, source, { + merger: _mergerIf + }); +} +/** + * Merges source[key] in target[key] only if target[key] is undefined. + * @private + */ function _mergerIf(key, target, source) { + if (!isValidKey(key)) { + return; + } + const tval = target[key]; + const sval = source[key]; + if (isObject(tval) && isObject(sval)) { + mergeIf(tval, sval); + } else if (!Object.prototype.hasOwnProperty.call(target, key)) { + target[key] = clone(sval); + } +} +/** + * @private + */ function _deprecated(scope, value, previous, current) { + if (value !== undefined) { + console.warn(scope + ': "' + previous + '" is deprecated. Please use "' + current + '" instead'); + } +} +// resolveObjectKey resolver cache +const keyResolvers = { + // Chart.helpers.core resolveObjectKey should resolve empty key to root object + '': (v)=>v, + // default resolvers + x: (o)=>o.x, + y: (o)=>o.y +}; +/** + * @private + */ function _splitKey(key) { + const parts = key.split('.'); + const keys = []; + let tmp = ''; + for (const part of parts){ + tmp += part; + if (tmp.endsWith('\\')) { + tmp = tmp.slice(0, -1) + '.'; + } else { + keys.push(tmp); + tmp = ''; + } + } + return keys; +} +function _getKeyResolver(key) { + const keys = _splitKey(key); + return (obj)=>{ + for (const k of keys){ + if (k === '') { + break; + } + obj = obj && obj[k]; + } + return obj; + }; +} +function resolveObjectKey(obj, key) { + const resolver = keyResolvers[key] || (keyResolvers[key] = _getKeyResolver(key)); + return resolver(obj); +} +/** + * @private + */ function _capitalize(str) { + return str.charAt(0).toUpperCase() + str.slice(1); +} +const defined = (value)=>typeof value !== 'undefined'; +const isFunction = (value)=>typeof value === 'function'; +// Adapted from https://stackoverflow.com/questions/31128855/comparing-ecma6-sets-for-equality#31129384 +const setsEqual = (a, b)=>{ + if (a.size !== b.size) { + return false; + } + for (const item of a){ + if (!b.has(item)) { + return false; + } + } + return true; +}; +/** + * @param e - The event + * @private + */ function _isClickEvent(e) { + return e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu'; +} + +/** + * @alias Chart.helpers.math + * @namespace + */ const PI = Math.PI; +const TAU = 2 * PI; +const PITAU = TAU + PI; +const INFINITY = Number.POSITIVE_INFINITY; +const RAD_PER_DEG = PI / 180; +const HALF_PI = PI / 2; +const QUARTER_PI = PI / 4; +const TWO_THIRDS_PI = PI * 2 / 3; +const log10 = Math.log10; +const sign = Math.sign; +function almostEquals(x, y, epsilon) { + return Math.abs(x - y) < epsilon; +} +/** + * Implementation of the nice number algorithm used in determining where axis labels will go + */ function niceNum(range) { + const roundedRange = Math.round(range); + range = almostEquals(range, roundedRange, range / 1000) ? roundedRange : range; + const niceRange = Math.pow(10, Math.floor(log10(range))); + const fraction = range / niceRange; + const niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10; + return niceFraction * niceRange; +} +/** + * Returns an array of factors sorted from 1 to sqrt(value) + * @private + */ function _factorize(value) { + const result = []; + const sqrt = Math.sqrt(value); + let i; + for(i = 1; i < sqrt; i++){ + if (value % i === 0) { + result.push(i); + result.push(value / i); + } + } + if (sqrt === (sqrt | 0)) { + result.push(sqrt); + } + result.sort((a, b)=>a - b).pop(); + return result; +} +/** + * Verifies that attempting to coerce n to string or number won't throw a TypeError. + */ function isNonPrimitive(n) { + return typeof n === 'symbol' || typeof n === 'object' && n !== null && !(Symbol.toPrimitive in n || 'toString' in n || 'valueOf' in n); +} +function isNumber(n) { + return !isNonPrimitive(n) && !isNaN(parseFloat(n)) && isFinite(n); +} +function almostWhole(x, epsilon) { + const rounded = Math.round(x); + return rounded - epsilon <= x && rounded + epsilon >= x; +} +/** + * @private + */ function _setMinAndMaxByKey(array, target, property) { + let i, ilen, value; + for(i = 0, ilen = array.length; i < ilen; i++){ + value = array[i][property]; + if (!isNaN(value)) { + target.min = Math.min(target.min, value); + target.max = Math.max(target.max, value); + } + } +} +function toRadians(degrees) { + return degrees * (PI / 180); +} +function toDegrees(radians) { + return radians * (180 / PI); +} +/** + * Returns the number of decimal places + * i.e. the number of digits after the decimal point, of the value of this Number. + * @param x - A number. + * @returns The number of decimal places. + * @private + */ function _decimalPlaces(x) { + if (!isNumberFinite(x)) { + return; + } + let e = 1; + let p = 0; + while(Math.round(x * e) / e !== x){ + e *= 10; + p++; + } + return p; +} +// Gets the angle from vertical upright to the point about a centre. +function getAngleFromPoint(centrePoint, anglePoint) { + const distanceFromXCenter = anglePoint.x - centrePoint.x; + const distanceFromYCenter = anglePoint.y - centrePoint.y; + const radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter); + let angle = Math.atan2(distanceFromYCenter, distanceFromXCenter); + if (angle < -0.5 * PI) { + angle += TAU; // make sure the returned angle is in the range of (-PI/2, 3PI/2] + } + return { + angle, + distance: radialDistanceFromCenter + }; +} +function distanceBetweenPoints(pt1, pt2) { + return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2)); +} +/** + * Shortest distance between angles, in either direction. + * @private + */ function _angleDiff(a, b) { + return (a - b + PITAU) % TAU - PI; +} +/** + * Normalize angle to be between 0 and 2*PI + * @private + */ function _normalizeAngle(a) { + return (a % TAU + TAU) % TAU; +} +/** + * @private + */ function _angleBetween(angle, start, end, sameAngleIsFullCircle) { + const a = _normalizeAngle(angle); + const s = _normalizeAngle(start); + const e = _normalizeAngle(end); + const angleToStart = _normalizeAngle(s - a); + const angleToEnd = _normalizeAngle(e - a); + const startToAngle = _normalizeAngle(a - s); + const endToAngle = _normalizeAngle(a - e); + return a === s || a === e || sameAngleIsFullCircle && s === e || angleToStart > angleToEnd && startToAngle < endToAngle; +} +/** + * Limit `value` between `min` and `max` + * @param value + * @param min + * @param max + * @private + */ function _limitValue(value, min, max) { + return Math.max(min, Math.min(max, value)); +} +/** + * @param {number} value + * @private + */ function _int16Range(value) { + return _limitValue(value, -32768, 32767); +} +/** + * @param value + * @param start + * @param end + * @param [epsilon] + * @private + */ function _isBetween(value, start, end, epsilon = 1e-6) { + return value >= Math.min(start, end) - epsilon && value <= Math.max(start, end) + epsilon; +} + +function _lookup(table, value, cmp) { + cmp = cmp || ((index)=>table[index] < value); + let hi = table.length - 1; + let lo = 0; + let mid; + while(hi - lo > 1){ + mid = lo + hi >> 1; + if (cmp(mid)) { + lo = mid; + } else { + hi = mid; + } + } + return { + lo, + hi + }; +} +/** + * Binary search + * @param table - the table search. must be sorted! + * @param key - property name for the value in each entry + * @param value - value to find + * @param last - lookup last index + * @private + */ const _lookupByKey = (table, key, value, last)=>_lookup(table, value, last ? (index)=>{ + const ti = table[index][key]; + return ti < value || ti === value && table[index + 1][key] === value; + } : (index)=>table[index][key] < value); +/** + * Reverse binary search + * @param table - the table search. must be sorted! + * @param key - property name for the value in each entry + * @param value - value to find + * @private + */ const _rlookupByKey = (table, key, value)=>_lookup(table, value, (index)=>table[index][key] >= value); +/** + * Return subset of `values` between `min` and `max` inclusive. + * Values are assumed to be in sorted order. + * @param values - sorted array of values + * @param min - min value + * @param max - max value + */ function _filterBetween(values, min, max) { + let start = 0; + let end = values.length; + while(start < end && values[start] < min){ + start++; + } + while(end > start && values[end - 1] > max){ + end--; + } + return start > 0 || end < values.length ? values.slice(start, end) : values; +} +const arrayEvents = [ + 'push', + 'pop', + 'shift', + 'splice', + 'unshift' +]; +function listenArrayEvents(array, listener) { + if (array._chartjs) { + array._chartjs.listeners.push(listener); + return; + } + Object.defineProperty(array, '_chartjs', { + configurable: true, + enumerable: false, + value: { + listeners: [ + listener + ] + } + }); + arrayEvents.forEach((key)=>{ + const method = '_onData' + _capitalize(key); + const base = array[key]; + Object.defineProperty(array, key, { + configurable: true, + enumerable: false, + value (...args) { + const res = base.apply(this, args); + array._chartjs.listeners.forEach((object)=>{ + if (typeof object[method] === 'function') { + object[method](...args); + } + }); + return res; + } + }); + }); +} +function unlistenArrayEvents(array, listener) { + const stub = array._chartjs; + if (!stub) { + return; + } + const listeners = stub.listeners; + const index = listeners.indexOf(listener); + if (index !== -1) { + listeners.splice(index, 1); + } + if (listeners.length > 0) { + return; + } + arrayEvents.forEach((key)=>{ + delete array[key]; + }); + delete array._chartjs; +} +/** + * @param items + */ function _arrayUnique(items) { + const set = new Set(items); + if (set.size === items.length) { + return items; + } + return Array.from(set); +} + +function fontString(pixelSize, fontStyle, fontFamily) { + return fontStyle + ' ' + pixelSize + 'px ' + fontFamily; +} +/** +* Request animation polyfill +*/ const requestAnimFrame = function() { + if (typeof window === 'undefined') { + return function(callback) { + return callback(); + }; + } + return window.requestAnimationFrame; +}(); +/** + * Throttles calling `fn` once per animation frame + * Latest arguments are used on the actual call + */ function throttled(fn, thisArg) { + let argsToUse = []; + let ticking = false; + return function(...args) { + // Save the args for use later + argsToUse = args; + if (!ticking) { + ticking = true; + requestAnimFrame.call(window, ()=>{ + ticking = false; + fn.apply(thisArg, argsToUse); + }); + } + }; +} +/** + * Debounces calling `fn` for `delay` ms + */ function debounce(fn, delay) { + let timeout; + return function(...args) { + if (delay) { + clearTimeout(timeout); + timeout = setTimeout(fn, delay, args); + } else { + fn.apply(this, args); + } + return delay; + }; +} +/** + * Converts 'start' to 'left', 'end' to 'right' and others to 'center' + * @private + */ const _toLeftRightCenter = (align)=>align === 'start' ? 'left' : align === 'end' ? 'right' : 'center'; +/** + * Returns `start`, `end` or `(start + end) / 2` depending on `align`. Defaults to `center` + * @private + */ const _alignStartEnd = (align, start, end)=>align === 'start' ? start : align === 'end' ? end : (start + end) / 2; +/** + * Returns `left`, `right` or `(left + right) / 2` depending on `align`. Defaults to `left` + * @private + */ const _textX = (align, left, right, rtl)=>{ + const check = rtl ? 'left' : 'right'; + return align === check ? right : align === 'center' ? (left + right) / 2 : left; +}; +/** + * Return start and count of visible points. + * @private + */ function _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled) { + const pointCount = points.length; + let start = 0; + let count = pointCount; + if (meta._sorted) { + const { iScale , vScale , _parsed } = meta; + const spanGaps = meta.dataset ? meta.dataset.options ? meta.dataset.options.spanGaps : null : null; + const axis = iScale.axis; + const { min , max , minDefined , maxDefined } = iScale.getUserBounds(); + if (minDefined) { + start = Math.min(// @ts-expect-error Need to type _parsed + _lookupByKey(_parsed, axis, min).lo, // @ts-expect-error Need to fix types on _lookupByKey + animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min)).lo); + if (spanGaps) { + const distanceToDefinedLo = _parsed.slice(0, start + 1).reverse().findIndex((point)=>!isNullOrUndef(point[vScale.axis])); + start -= Math.max(0, distanceToDefinedLo); + } + start = _limitValue(start, 0, pointCount - 1); + } + if (maxDefined) { + let end = Math.max(// @ts-expect-error Need to type _parsed + _lookupByKey(_parsed, iScale.axis, max, true).hi + 1, // @ts-expect-error Need to fix types on _lookupByKey + animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max), true).hi + 1); + if (spanGaps) { + const distanceToDefinedHi = _parsed.slice(end - 1).findIndex((point)=>!isNullOrUndef(point[vScale.axis])); + end += Math.max(0, distanceToDefinedHi); + } + count = _limitValue(end, start, pointCount) - start; + } else { + count = pointCount - start; + } + } + return { + start, + count + }; +} +/** + * Checks if the scale ranges have changed. + * @param {object} meta - dataset meta. + * @returns {boolean} + * @private + */ function _scaleRangesChanged(meta) { + const { xScale , yScale , _scaleRanges } = meta; + const newRanges = { + xmin: xScale.min, + xmax: xScale.max, + ymin: yScale.min, + ymax: yScale.max + }; + if (!_scaleRanges) { + meta._scaleRanges = newRanges; + return true; + } + const changed = _scaleRanges.xmin !== xScale.min || _scaleRanges.xmax !== xScale.max || _scaleRanges.ymin !== yScale.min || _scaleRanges.ymax !== yScale.max; + Object.assign(_scaleRanges, newRanges); + return changed; +} + +const atEdge = (t)=>t === 0 || t === 1; +const elasticIn = (t, s, p)=>-(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * TAU / p)); +const elasticOut = (t, s, p)=>Math.pow(2, -10 * t) * Math.sin((t - s) * TAU / p) + 1; +/** + * Easing functions adapted from Robert Penner's easing equations. + * @namespace Chart.helpers.easing.effects + * @see http://www.robertpenner.com/easing/ + */ const effects = { + linear: (t)=>t, + easeInQuad: (t)=>t * t, + easeOutQuad: (t)=>-t * (t - 2), + easeInOutQuad: (t)=>(t /= 0.5) < 1 ? 0.5 * t * t : -0.5 * (--t * (t - 2) - 1), + easeInCubic: (t)=>t * t * t, + easeOutCubic: (t)=>(t -= 1) * t * t + 1, + easeInOutCubic: (t)=>(t /= 0.5) < 1 ? 0.5 * t * t * t : 0.5 * ((t -= 2) * t * t + 2), + easeInQuart: (t)=>t * t * t * t, + easeOutQuart: (t)=>-((t -= 1) * t * t * t - 1), + easeInOutQuart: (t)=>(t /= 0.5) < 1 ? 0.5 * t * t * t * t : -0.5 * ((t -= 2) * t * t * t - 2), + easeInQuint: (t)=>t * t * t * t * t, + easeOutQuint: (t)=>(t -= 1) * t * t * t * t + 1, + easeInOutQuint: (t)=>(t /= 0.5) < 1 ? 0.5 * t * t * t * t * t : 0.5 * ((t -= 2) * t * t * t * t + 2), + easeInSine: (t)=>-Math.cos(t * HALF_PI) + 1, + easeOutSine: (t)=>Math.sin(t * HALF_PI), + easeInOutSine: (t)=>-0.5 * (Math.cos(PI * t) - 1), + easeInExpo: (t)=>t === 0 ? 0 : Math.pow(2, 10 * (t - 1)), + easeOutExpo: (t)=>t === 1 ? 1 : -Math.pow(2, -10 * t) + 1, + easeInOutExpo: (t)=>atEdge(t) ? t : t < 0.5 ? 0.5 * Math.pow(2, 10 * (t * 2 - 1)) : 0.5 * (-Math.pow(2, -10 * (t * 2 - 1)) + 2), + easeInCirc: (t)=>t >= 1 ? t : -(Math.sqrt(1 - t * t) - 1), + easeOutCirc: (t)=>Math.sqrt(1 - (t -= 1) * t), + easeInOutCirc: (t)=>(t /= 0.5) < 1 ? -0.5 * (Math.sqrt(1 - t * t) - 1) : 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1), + easeInElastic: (t)=>atEdge(t) ? t : elasticIn(t, 0.075, 0.3), + easeOutElastic: (t)=>atEdge(t) ? t : elasticOut(t, 0.075, 0.3), + easeInOutElastic (t) { + const s = 0.1125; + const p = 0.45; + return atEdge(t) ? t : t < 0.5 ? 0.5 * elasticIn(t * 2, s, p) : 0.5 + 0.5 * elasticOut(t * 2 - 1, s, p); + }, + easeInBack (t) { + const s = 1.70158; + return t * t * ((s + 1) * t - s); + }, + easeOutBack (t) { + const s = 1.70158; + return (t -= 1) * t * ((s + 1) * t + s) + 1; + }, + easeInOutBack (t) { + let s = 1.70158; + if ((t /= 0.5) < 1) { + return 0.5 * (t * t * (((s *= 1.525) + 1) * t - s)); + } + return 0.5 * ((t -= 2) * t * (((s *= 1.525) + 1) * t + s) + 2); + }, + easeInBounce: (t)=>1 - effects.easeOutBounce(1 - t), + easeOutBounce (t) { + const m = 7.5625; + const d = 2.75; + if (t < 1 / d) { + return m * t * t; + } + if (t < 2 / d) { + return m * (t -= 1.5 / d) * t + 0.75; + } + if (t < 2.5 / d) { + return m * (t -= 2.25 / d) * t + 0.9375; + } + return m * (t -= 2.625 / d) * t + 0.984375; + }, + easeInOutBounce: (t)=>t < 0.5 ? effects.easeInBounce(t * 2) * 0.5 : effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5 +}; + +function isPatternOrGradient(value) { + if (value && typeof value === 'object') { + const type = value.toString(); + return type === '[object CanvasPattern]' || type === '[object CanvasGradient]'; + } + return false; +} +function color(value) { + return isPatternOrGradient(value) ? value : new color$1.Color(value); +} +function getHoverColor(value) { + return isPatternOrGradient(value) ? value : new color$1.Color(value).saturate(0.5).darken(0.1).hexString(); +} + +const numbers = [ + 'x', + 'y', + 'borderWidth', + 'radius', + 'tension' +]; +const colors = [ + 'color', + 'borderColor', + 'backgroundColor' +]; +function applyAnimationsDefaults(defaults) { + defaults.set('animation', { + delay: undefined, + duration: 1000, + easing: 'easeOutQuart', + fn: undefined, + from: undefined, + loop: undefined, + to: undefined, + type: undefined + }); + defaults.describe('animation', { + _fallback: false, + _indexable: false, + _scriptable: (name)=>name !== 'onProgress' && name !== 'onComplete' && name !== 'fn' + }); + defaults.set('animations', { + colors: { + type: 'color', + properties: colors + }, + numbers: { + type: 'number', + properties: numbers + } + }); + defaults.describe('animations', { + _fallback: 'animation' + }); + defaults.set('transitions', { + active: { + animation: { + duration: 400 + } + }, + resize: { + animation: { + duration: 0 + } + }, + show: { + animations: { + colors: { + from: 'transparent' + }, + visible: { + type: 'boolean', + duration: 0 + } + } + }, + hide: { + animations: { + colors: { + to: 'transparent' + }, + visible: { + type: 'boolean', + easing: 'linear', + fn: (v)=>v | 0 + } + } + } + }); +} + +function applyLayoutsDefaults(defaults) { + defaults.set('layout', { + autoPadding: true, + padding: { + top: 0, + right: 0, + bottom: 0, + left: 0 + } + }); +} + +const intlCache = new Map(); +function getNumberFormat(locale, options) { + options = options || {}; + const cacheKey = locale + JSON.stringify(options); + let formatter = intlCache.get(cacheKey); + if (!formatter) { + formatter = new Intl.NumberFormat(locale, options); + intlCache.set(cacheKey, formatter); + } + return formatter; +} +function formatNumber(num, locale, options) { + return getNumberFormat(locale, options).format(num); +} + +const formatters = { + values (value) { + return isArray(value) ? value : '' + value; + }, + numeric (tickValue, index, ticks) { + if (tickValue === 0) { + return '0'; + } + const locale = this.chart.options.locale; + let notation; + let delta = tickValue; + if (ticks.length > 1) { + const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value)); + if (maxTick < 1e-4 || maxTick > 1e+15) { + notation = 'scientific'; + } + delta = calculateDelta(tickValue, ticks); + } + const logDelta = log10(Math.abs(delta)); + const numDecimal = isNaN(logDelta) ? 1 : Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0); + const options = { + notation, + minimumFractionDigits: numDecimal, + maximumFractionDigits: numDecimal + }; + Object.assign(options, this.options.ticks.format); + return formatNumber(tickValue, locale, options); + }, + logarithmic (tickValue, index, ticks) { + if (tickValue === 0) { + return '0'; + } + const remain = ticks[index].significand || tickValue / Math.pow(10, Math.floor(log10(tickValue))); + if ([ + 1, + 2, + 3, + 5, + 10, + 15 + ].includes(remain) || index > 0.8 * ticks.length) { + return formatters.numeric.call(this, tickValue, index, ticks); + } + return ''; + } +}; +function calculateDelta(tickValue, ticks) { + let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value; + if (Math.abs(delta) >= 1 && tickValue !== Math.floor(tickValue)) { + delta = tickValue - Math.floor(tickValue); + } + return delta; +} + var Ticks = { + formatters +}; + +function applyScaleDefaults(defaults) { + defaults.set('scale', { + display: true, + offset: false, + reverse: false, + beginAtZero: false, + bounds: 'ticks', + clip: true, + grace: 0, + grid: { + display: true, + lineWidth: 1, + drawOnChartArea: true, + drawTicks: true, + tickLength: 8, + tickWidth: (_ctx, options)=>options.lineWidth, + tickColor: (_ctx, options)=>options.color, + offset: false + }, + border: { + display: true, + dash: [], + dashOffset: 0.0, + width: 1 + }, + title: { + display: false, + text: '', + padding: { + top: 4, + bottom: 4 + } + }, + ticks: { + minRotation: 0, + maxRotation: 50, + mirror: false, + textStrokeWidth: 0, + textStrokeColor: '', + padding: 3, + display: true, + autoSkip: true, + autoSkipPadding: 3, + labelOffset: 0, + callback: Ticks.formatters.values, + minor: {}, + major: {}, + align: 'center', + crossAlign: 'near', + showLabelBackdrop: false, + backdropColor: 'rgba(255, 255, 255, 0.75)', + backdropPadding: 2 + } + }); + defaults.route('scale.ticks', 'color', '', 'color'); + defaults.route('scale.grid', 'color', '', 'borderColor'); + defaults.route('scale.border', 'color', '', 'borderColor'); + defaults.route('scale.title', 'color', '', 'color'); + defaults.describe('scale', { + _fallback: false, + _scriptable: (name)=>!name.startsWith('before') && !name.startsWith('after') && name !== 'callback' && name !== 'parser', + _indexable: (name)=>name !== 'borderDash' && name !== 'tickBorderDash' && name !== 'dash' + }); + defaults.describe('scales', { + _fallback: 'scale' + }); + defaults.describe('scale.ticks', { + _scriptable: (name)=>name !== 'backdropPadding' && name !== 'callback', + _indexable: (name)=>name !== 'backdropPadding' + }); +} + +const overrides = Object.create(null); +const descriptors = Object.create(null); + function getScope$1(node, key) { + if (!key) { + return node; + } + const keys = key.split('.'); + for(let i = 0, n = keys.length; i < n; ++i){ + const k = keys[i]; + node = node[k] || (node[k] = Object.create(null)); + } + return node; +} +function set(root, scope, values) { + if (typeof scope === 'string') { + return merge(getScope$1(root, scope), values); + } + return merge(getScope$1(root, ''), scope); +} + class Defaults { + constructor(_descriptors, _appliers){ + this.animation = undefined; + this.backgroundColor = 'rgba(0,0,0,0.1)'; + this.borderColor = 'rgba(0,0,0,0.1)'; + this.color = '#666'; + this.datasets = {}; + this.devicePixelRatio = (context)=>context.chart.platform.getDevicePixelRatio(); + this.elements = {}; + this.events = [ + 'mousemove', + 'mouseout', + 'click', + 'touchstart', + 'touchmove' + ]; + this.font = { + family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", + size: 12, + style: 'normal', + lineHeight: 1.2, + weight: null + }; + this.hover = {}; + this.hoverBackgroundColor = (ctx, options)=>getHoverColor(options.backgroundColor); + this.hoverBorderColor = (ctx, options)=>getHoverColor(options.borderColor); + this.hoverColor = (ctx, options)=>getHoverColor(options.color); + this.indexAxis = 'x'; + this.interaction = { + mode: 'nearest', + intersect: true, + includeInvisible: false + }; + this.maintainAspectRatio = true; + this.onHover = null; + this.onClick = null; + this.parsing = true; + this.plugins = {}; + this.responsive = true; + this.scale = undefined; + this.scales = {}; + this.showLine = true; + this.drawActiveElementsOnTop = true; + this.describe(_descriptors); + this.apply(_appliers); + } + set(scope, values) { + return set(this, scope, values); + } + get(scope) { + return getScope$1(this, scope); + } + describe(scope, values) { + return set(descriptors, scope, values); + } + override(scope, values) { + return set(overrides, scope, values); + } + route(scope, name, targetScope, targetName) { + const scopeObject = getScope$1(this, scope); + const targetScopeObject = getScope$1(this, targetScope); + const privateName = '_' + name; + Object.defineProperties(scopeObject, { + [privateName]: { + value: scopeObject[name], + writable: true + }, + [name]: { + enumerable: true, + get () { + const local = this[privateName]; + const target = targetScopeObject[targetName]; + if (isObject(local)) { + return Object.assign({}, target, local); + } + return valueOrDefault(local, target); + }, + set (value) { + this[privateName] = value; + } + } + }); + } + apply(appliers) { + appliers.forEach((apply)=>apply(this)); + } +} +var defaults = /* #__PURE__ */ new Defaults({ + _scriptable: (name)=>!name.startsWith('on'), + _indexable: (name)=>name !== 'events', + hover: { + _fallback: 'interaction' + }, + interaction: { + _scriptable: false, + _indexable: false + } +}, [ + applyAnimationsDefaults, + applyLayoutsDefaults, + applyScaleDefaults +]); + +/** + * Converts the given font object into a CSS font string. + * @param font - A font object. + * @return The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font + * @private + */ function toFontString(font) { + if (!font || isNullOrUndef(font.size) || isNullOrUndef(font.family)) { + return null; + } + return (font.style ? font.style + ' ' : '') + (font.weight ? font.weight + ' ' : '') + font.size + 'px ' + font.family; +} +/** + * @private + */ function _measureText(ctx, data, gc, longest, string) { + let textWidth = data[string]; + if (!textWidth) { + textWidth = data[string] = ctx.measureText(string).width; + gc.push(string); + } + if (textWidth > longest) { + longest = textWidth; + } + return longest; +} +/** + * @private + */ // eslint-disable-next-line complexity +function _longestText(ctx, font, arrayOfThings, cache) { + cache = cache || {}; + let data = cache.data = cache.data || {}; + let gc = cache.garbageCollect = cache.garbageCollect || []; + if (cache.font !== font) { + data = cache.data = {}; + gc = cache.garbageCollect = []; + cache.font = font; + } + ctx.save(); + ctx.font = font; + let longest = 0; + const ilen = arrayOfThings.length; + let i, j, jlen, thing, nestedThing; + for(i = 0; i < ilen; i++){ + thing = arrayOfThings[i]; + // Undefined strings and arrays should not be measured + if (thing !== undefined && thing !== null && !isArray(thing)) { + longest = _measureText(ctx, data, gc, longest, thing); + } else if (isArray(thing)) { + // if it is an array lets measure each element + // to do maybe simplify this function a bit so we can do this more recursively? + for(j = 0, jlen = thing.length; j < jlen; j++){ + nestedThing = thing[j]; + // Undefined strings and arrays should not be measured + if (nestedThing !== undefined && nestedThing !== null && !isArray(nestedThing)) { + longest = _measureText(ctx, data, gc, longest, nestedThing); + } + } + } + } + ctx.restore(); + const gcLen = gc.length / 2; + if (gcLen > arrayOfThings.length) { + for(i = 0; i < gcLen; i++){ + delete data[gc[i]]; + } + gc.splice(0, gcLen); + } + return longest; +} +/** + * Returns the aligned pixel value to avoid anti-aliasing blur + * @param chart - The chart instance. + * @param pixel - A pixel value. + * @param width - The width of the element. + * @returns The aligned pixel value. + * @private + */ function _alignPixel(chart, pixel, width) { + const devicePixelRatio = chart.currentDevicePixelRatio; + const halfWidth = width !== 0 ? Math.max(width / 2, 0.5) : 0; + return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth; +} +/** + * Clears the entire canvas. + */ function clearCanvas(canvas, ctx) { + if (!ctx && !canvas) { + return; + } + ctx = ctx || canvas.getContext('2d'); + ctx.save(); + // canvas.width and canvas.height do not consider the canvas transform, + // while clearRect does + ctx.resetTransform(); + ctx.clearRect(0, 0, canvas.width, canvas.height); + ctx.restore(); +} +function drawPoint(ctx, options, x, y) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + drawPointLegend(ctx, options, x, y, null); +} +// eslint-disable-next-line complexity +function drawPointLegend(ctx, options, x, y, w) { + let type, xOffset, yOffset, size, cornerRadius, width, xOffsetW, yOffsetW; + const style = options.pointStyle; + const rotation = options.rotation; + const radius = options.radius; + let rad = (rotation || 0) * RAD_PER_DEG; + if (style && typeof style === 'object') { + type = style.toString(); + if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') { + ctx.save(); + ctx.translate(x, y); + ctx.rotate(rad); + ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height); + ctx.restore(); + return; + } + } + if (isNaN(radius) || radius <= 0) { + return; + } + ctx.beginPath(); + switch(style){ + // Default includes circle + default: + if (w) { + ctx.ellipse(x, y, w / 2, radius, 0, 0, TAU); + } else { + ctx.arc(x, y, radius, 0, TAU); + } + ctx.closePath(); + break; + case 'triangle': + width = w ? w / 2 : radius; + ctx.moveTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius); + rad += TWO_THIRDS_PI; + ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius); + rad += TWO_THIRDS_PI; + ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius); + ctx.closePath(); + break; + case 'rectRounded': + // NOTE: the rounded rect implementation changed to use `arc` instead of + // `quadraticCurveTo` since it generates better results when rect is + // almost a circle. 0.516 (instead of 0.5) produces results with visually + // closer proportion to the previous impl and it is inscribed in the + // circle with `radius`. For more details, see the following PRs: + // https://github.com/chartjs/Chart.js/issues/5597 + // https://github.com/chartjs/Chart.js/issues/5858 + cornerRadius = radius * 0.516; + size = radius - cornerRadius; + xOffset = Math.cos(rad + QUARTER_PI) * size; + xOffsetW = Math.cos(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size); + yOffset = Math.sin(rad + QUARTER_PI) * size; + yOffsetW = Math.sin(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size); + ctx.arc(x - xOffsetW, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI); + ctx.arc(x + yOffsetW, y - xOffset, cornerRadius, rad - HALF_PI, rad); + ctx.arc(x + xOffsetW, y + yOffset, cornerRadius, rad, rad + HALF_PI); + ctx.arc(x - yOffsetW, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI); + ctx.closePath(); + break; + case 'rect': + if (!rotation) { + size = Math.SQRT1_2 * radius; + width = w ? w / 2 : size; + ctx.rect(x - width, y - size, 2 * width, 2 * size); + break; + } + rad += QUARTER_PI; + /* falls through */ case 'rectRot': + xOffsetW = Math.cos(rad) * (w ? w / 2 : radius); + xOffset = Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + yOffsetW = Math.sin(rad) * (w ? w / 2 : radius); + ctx.moveTo(x - xOffsetW, y - yOffset); + ctx.lineTo(x + yOffsetW, y - xOffset); + ctx.lineTo(x + xOffsetW, y + yOffset); + ctx.lineTo(x - yOffsetW, y + xOffset); + ctx.closePath(); + break; + case 'crossRot': + rad += QUARTER_PI; + /* falls through */ case 'cross': + xOffsetW = Math.cos(rad) * (w ? w / 2 : radius); + xOffset = Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + yOffsetW = Math.sin(rad) * (w ? w / 2 : radius); + ctx.moveTo(x - xOffsetW, y - yOffset); + ctx.lineTo(x + xOffsetW, y + yOffset); + ctx.moveTo(x + yOffsetW, y - xOffset); + ctx.lineTo(x - yOffsetW, y + xOffset); + break; + case 'star': + xOffsetW = Math.cos(rad) * (w ? w / 2 : radius); + xOffset = Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + yOffsetW = Math.sin(rad) * (w ? w / 2 : radius); + ctx.moveTo(x - xOffsetW, y - yOffset); + ctx.lineTo(x + xOffsetW, y + yOffset); + ctx.moveTo(x + yOffsetW, y - xOffset); + ctx.lineTo(x - yOffsetW, y + xOffset); + rad += QUARTER_PI; + xOffsetW = Math.cos(rad) * (w ? w / 2 : radius); + xOffset = Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + yOffsetW = Math.sin(rad) * (w ? w / 2 : radius); + ctx.moveTo(x - xOffsetW, y - yOffset); + ctx.lineTo(x + xOffsetW, y + yOffset); + ctx.moveTo(x + yOffsetW, y - xOffset); + ctx.lineTo(x - yOffsetW, y + xOffset); + break; + case 'line': + xOffset = w ? w / 2 : Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + ctx.moveTo(x - xOffset, y - yOffset); + ctx.lineTo(x + xOffset, y + yOffset); + break; + case 'dash': + ctx.moveTo(x, y); + ctx.lineTo(x + Math.cos(rad) * (w ? w / 2 : radius), y + Math.sin(rad) * radius); + break; + case false: + ctx.closePath(); + break; + } + ctx.fill(); + if (options.borderWidth > 0) { + ctx.stroke(); + } +} +/** + * Returns true if the point is inside the rectangle + * @param point - The point to test + * @param area - The rectangle + * @param margin - allowed margin + * @private + */ function _isPointInArea(point, area, margin) { + margin = margin || 0.5; // margin - default is to match rounded decimals + return !area || point && point.x > area.left - margin && point.x < area.right + margin && point.y > area.top - margin && point.y < area.bottom + margin; +} +function clipArea(ctx, area) { + ctx.save(); + ctx.beginPath(); + ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top); + ctx.clip(); +} +function unclipArea(ctx) { + ctx.restore(); +} +/** + * @private + */ function _steppedLineTo(ctx, previous, target, flip, mode) { + if (!previous) { + return ctx.lineTo(target.x, target.y); + } + if (mode === 'middle') { + const midpoint = (previous.x + target.x) / 2.0; + ctx.lineTo(midpoint, previous.y); + ctx.lineTo(midpoint, target.y); + } else if (mode === 'after' !== !!flip) { + ctx.lineTo(previous.x, target.y); + } else { + ctx.lineTo(target.x, previous.y); + } + ctx.lineTo(target.x, target.y); +} +/** + * @private + */ function _bezierCurveTo(ctx, previous, target, flip) { + if (!previous) { + return ctx.lineTo(target.x, target.y); + } + ctx.bezierCurveTo(flip ? previous.cp1x : previous.cp2x, flip ? previous.cp1y : previous.cp2y, flip ? target.cp2x : target.cp1x, flip ? target.cp2y : target.cp1y, target.x, target.y); +} +function setRenderOpts(ctx, opts) { + if (opts.translation) { + ctx.translate(opts.translation[0], opts.translation[1]); + } + if (!isNullOrUndef(opts.rotation)) { + ctx.rotate(opts.rotation); + } + if (opts.color) { + ctx.fillStyle = opts.color; + } + if (opts.textAlign) { + ctx.textAlign = opts.textAlign; + } + if (opts.textBaseline) { + ctx.textBaseline = opts.textBaseline; + } +} +function decorateText(ctx, x, y, line, opts) { + if (opts.strikethrough || opts.underline) { + /** + * Now that IE11 support has been dropped, we can use more + * of the TextMetrics object. The actual bounding boxes + * are unflagged in Chrome, Firefox, Edge, and Safari so they + * can be safely used. + * See https://developer.mozilla.org/en-US/docs/Web/API/TextMetrics#Browser_compatibility + */ const metrics = ctx.measureText(line); + const left = x - metrics.actualBoundingBoxLeft; + const right = x + metrics.actualBoundingBoxRight; + const top = y - metrics.actualBoundingBoxAscent; + const bottom = y + metrics.actualBoundingBoxDescent; + const yDecoration = opts.strikethrough ? (top + bottom) / 2 : bottom; + ctx.strokeStyle = ctx.fillStyle; + ctx.beginPath(); + ctx.lineWidth = opts.decorationWidth || 2; + ctx.moveTo(left, yDecoration); + ctx.lineTo(right, yDecoration); + ctx.stroke(); + } +} +function drawBackdrop(ctx, opts) { + const oldColor = ctx.fillStyle; + ctx.fillStyle = opts.color; + ctx.fillRect(opts.left, opts.top, opts.width, opts.height); + ctx.fillStyle = oldColor; +} +/** + * Render text onto the canvas + */ function renderText(ctx, text, x, y, font, opts = {}) { + const lines = isArray(text) ? text : [ + text + ]; + const stroke = opts.strokeWidth > 0 && opts.strokeColor !== ''; + let i, line; + ctx.save(); + ctx.font = font.string; + setRenderOpts(ctx, opts); + for(i = 0; i < lines.length; ++i){ + line = lines[i]; + if (opts.backdrop) { + drawBackdrop(ctx, opts.backdrop); + } + if (stroke) { + if (opts.strokeColor) { + ctx.strokeStyle = opts.strokeColor; + } + if (!isNullOrUndef(opts.strokeWidth)) { + ctx.lineWidth = opts.strokeWidth; + } + ctx.strokeText(line, x, y, opts.maxWidth); + } + ctx.fillText(line, x, y, opts.maxWidth); + decorateText(ctx, x, y, line, opts); + y += Number(font.lineHeight); + } + ctx.restore(); +} +/** + * Add a path of a rectangle with rounded corners to the current sub-path + * @param ctx - Context + * @param rect - Bounding rect + */ function addRoundedRectPath(ctx, rect) { + const { x , y , w , h , radius } = rect; + // top left arc + ctx.arc(x + radius.topLeft, y + radius.topLeft, radius.topLeft, 1.5 * PI, PI, true); + // line from top left to bottom left + ctx.lineTo(x, y + h - radius.bottomLeft); + // bottom left arc + ctx.arc(x + radius.bottomLeft, y + h - radius.bottomLeft, radius.bottomLeft, PI, HALF_PI, true); + // line from bottom left to bottom right + ctx.lineTo(x + w - radius.bottomRight, y + h); + // bottom right arc + ctx.arc(x + w - radius.bottomRight, y + h - radius.bottomRight, radius.bottomRight, HALF_PI, 0, true); + // line from bottom right to top right + ctx.lineTo(x + w, y + radius.topRight); + // top right arc + ctx.arc(x + w - radius.topRight, y + radius.topRight, radius.topRight, 0, -HALF_PI, true); + // line from top right to top left + ctx.lineTo(x + radius.topLeft, y); +} + +const LINE_HEIGHT = /^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/; +const FONT_STYLE = /^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/; +/** + * @alias Chart.helpers.options + * @namespace + */ /** + * Converts the given line height `value` in pixels for a specific font `size`. + * @param value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em'). + * @param size - The font size (in pixels) used to resolve relative `value`. + * @returns The effective line height in pixels (size * 1.2 if value is invalid). + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height + * @since 2.7.0 + */ function toLineHeight(value, size) { + const matches = ('' + value).match(LINE_HEIGHT); + if (!matches || matches[1] === 'normal') { + return size * 1.2; + } + value = +matches[2]; + switch(matches[3]){ + case 'px': + return value; + case '%': + value /= 100; + break; + } + return size * value; +} +const numberOrZero = (v)=>+v || 0; +function _readValueToProps(value, props) { + const ret = {}; + const objProps = isObject(props); + const keys = objProps ? Object.keys(props) : props; + const read = isObject(value) ? objProps ? (prop)=>valueOrDefault(value[prop], value[props[prop]]) : (prop)=>value[prop] : ()=>value; + for (const prop of keys){ + ret[prop] = numberOrZero(read(prop)); + } + return ret; +} +/** + * Converts the given value into a TRBL object. + * @param value - If a number, set the value to all TRBL component, + * else, if an object, use defined properties and sets undefined ones to 0. + * x / y are shorthands for same value for left/right and top/bottom. + * @returns The padding values (top, right, bottom, left) + * @since 3.0.0 + */ function toTRBL(value) { + return _readValueToProps(value, { + top: 'y', + right: 'x', + bottom: 'y', + left: 'x' + }); +} +/** + * Converts the given value into a TRBL corners object (similar with css border-radius). + * @param value - If a number, set the value to all TRBL corner components, + * else, if an object, use defined properties and sets undefined ones to 0. + * @returns The TRBL corner values (topLeft, topRight, bottomLeft, bottomRight) + * @since 3.0.0 + */ function toTRBLCorners(value) { + return _readValueToProps(value, [ + 'topLeft', + 'topRight', + 'bottomLeft', + 'bottomRight' + ]); +} +/** + * Converts the given value into a padding object with pre-computed width/height. + * @param value - If a number, set the value to all TRBL component, + * else, if an object, use defined properties and sets undefined ones to 0. + * x / y are shorthands for same value for left/right and top/bottom. + * @returns The padding values (top, right, bottom, left, width, height) + * @since 2.7.0 + */ function toPadding(value) { + const obj = toTRBL(value); + obj.width = obj.left + obj.right; + obj.height = obj.top + obj.bottom; + return obj; +} +/** + * Parses font options and returns the font object. + * @param options - A object that contains font options to be parsed. + * @param fallback - A object that contains fallback font options. + * @return The font object. + * @private + */ function toFont(options, fallback) { + options = options || {}; + fallback = fallback || defaults.font; + let size = valueOrDefault(options.size, fallback.size); + if (typeof size === 'string') { + size = parseInt(size, 10); + } + let style = valueOrDefault(options.style, fallback.style); + if (style && !('' + style).match(FONT_STYLE)) { + console.warn('Invalid font style specified: "' + style + '"'); + style = undefined; + } + const font = { + family: valueOrDefault(options.family, fallback.family), + lineHeight: toLineHeight(valueOrDefault(options.lineHeight, fallback.lineHeight), size), + size, + style, + weight: valueOrDefault(options.weight, fallback.weight), + string: '' + }; + font.string = toFontString(font); + return font; +} +/** + * Evaluates the given `inputs` sequentially and returns the first defined value. + * @param inputs - An array of values, falling back to the last value. + * @param context - If defined and the current value is a function, the value + * is called with `context` as first argument and the result becomes the new input. + * @param index - If defined and the current value is an array, the value + * at `index` become the new input. + * @param info - object to return information about resolution in + * @param info.cacheable - Will be set to `false` if option is not cacheable. + * @since 2.7.0 + */ function resolve(inputs, context, index, info) { + let cacheable = true; + let i, ilen, value; + for(i = 0, ilen = inputs.length; i < ilen; ++i){ + value = inputs[i]; + if (value === undefined) { + continue; + } + if (context !== undefined && typeof value === 'function') { + value = value(context); + cacheable = false; + } + if (index !== undefined && isArray(value)) { + value = value[index % value.length]; + cacheable = false; + } + if (value !== undefined) { + if (info && !cacheable) { + info.cacheable = false; + } + return value; + } + } +} +/** + * @param minmax + * @param grace + * @param beginAtZero + * @private + */ function _addGrace(minmax, grace, beginAtZero) { + const { min , max } = minmax; + const change = toDimension(grace, (max - min) / 2); + const keepZero = (value, add)=>beginAtZero && value === 0 ? 0 : value + add; + return { + min: keepZero(min, -Math.abs(change)), + max: keepZero(max, change) + }; +} +function createContext(parentContext, context) { + return Object.assign(Object.create(parentContext), context); +} + +/** + * Creates a Proxy for resolving raw values for options. + * @param scopes - The option scopes to look for values, in resolution order + * @param prefixes - The prefixes for values, in resolution order. + * @param rootScopes - The root option scopes + * @param fallback - Parent scopes fallback + * @param getTarget - callback for getting the target for changed values + * @returns Proxy + * @private + */ function _createResolver(scopes, prefixes = [ + '' +], rootScopes, fallback, getTarget = ()=>scopes[0]) { + const finalRootScopes = rootScopes || scopes; + if (typeof fallback === 'undefined') { + fallback = _resolve('_fallback', scopes); + } + const cache = { + [Symbol.toStringTag]: 'Object', + _cacheable: true, + _scopes: scopes, + _rootScopes: finalRootScopes, + _fallback: fallback, + _getTarget: getTarget, + override: (scope)=>_createResolver([ + scope, + ...scopes + ], prefixes, finalRootScopes, fallback) + }; + return new Proxy(cache, { + /** + * A trap for the delete operator. + */ deleteProperty (target, prop) { + delete target[prop]; // remove from cache + delete target._keys; // remove cached keys + delete scopes[0][prop]; // remove from top level scope + return true; + }, + /** + * A trap for getting property values. + */ get (target, prop) { + return _cached(target, prop, ()=>_resolveWithPrefixes(prop, prefixes, scopes, target)); + }, + /** + * A trap for Object.getOwnPropertyDescriptor. + * Also used by Object.hasOwnProperty. + */ getOwnPropertyDescriptor (target, prop) { + return Reflect.getOwnPropertyDescriptor(target._scopes[0], prop); + }, + /** + * A trap for Object.getPrototypeOf. + */ getPrototypeOf () { + return Reflect.getPrototypeOf(scopes[0]); + }, + /** + * A trap for the in operator. + */ has (target, prop) { + return getKeysFromAllScopes(target).includes(prop); + }, + /** + * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols. + */ ownKeys (target) { + return getKeysFromAllScopes(target); + }, + /** + * A trap for setting property values. + */ set (target, prop, value) { + const storage = target._storage || (target._storage = getTarget()); + target[prop] = storage[prop] = value; // set to top level scope + cache + delete target._keys; // remove cached keys + return true; + } + }); +} +/** + * Returns an Proxy for resolving option values with context. + * @param proxy - The Proxy returned by `_createResolver` + * @param context - Context object for scriptable/indexable options + * @param subProxy - The proxy provided for scriptable options + * @param descriptorDefaults - Defaults for descriptors + * @private + */ function _attachContext(proxy, context, subProxy, descriptorDefaults) { + const cache = { + _cacheable: false, + _proxy: proxy, + _context: context, + _subProxy: subProxy, + _stack: new Set(), + _descriptors: _descriptors(proxy, descriptorDefaults), + setContext: (ctx)=>_attachContext(proxy, ctx, subProxy, descriptorDefaults), + override: (scope)=>_attachContext(proxy.override(scope), context, subProxy, descriptorDefaults) + }; + return new Proxy(cache, { + /** + * A trap for the delete operator. + */ deleteProperty (target, prop) { + delete target[prop]; // remove from cache + delete proxy[prop]; // remove from proxy + return true; + }, + /** + * A trap for getting property values. + */ get (target, prop, receiver) { + return _cached(target, prop, ()=>_resolveWithContext(target, prop, receiver)); + }, + /** + * A trap for Object.getOwnPropertyDescriptor. + * Also used by Object.hasOwnProperty. + */ getOwnPropertyDescriptor (target, prop) { + return target._descriptors.allKeys ? Reflect.has(proxy, prop) ? { + enumerable: true, + configurable: true + } : undefined : Reflect.getOwnPropertyDescriptor(proxy, prop); + }, + /** + * A trap for Object.getPrototypeOf. + */ getPrototypeOf () { + return Reflect.getPrototypeOf(proxy); + }, + /** + * A trap for the in operator. + */ has (target, prop) { + return Reflect.has(proxy, prop); + }, + /** + * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols. + */ ownKeys () { + return Reflect.ownKeys(proxy); + }, + /** + * A trap for setting property values. + */ set (target, prop, value) { + proxy[prop] = value; // set to proxy + delete target[prop]; // remove from cache + return true; + } + }); +} +/** + * @private + */ function _descriptors(proxy, defaults = { + scriptable: true, + indexable: true +}) { + const { _scriptable =defaults.scriptable , _indexable =defaults.indexable , _allKeys =defaults.allKeys } = proxy; + return { + allKeys: _allKeys, + scriptable: _scriptable, + indexable: _indexable, + isScriptable: isFunction(_scriptable) ? _scriptable : ()=>_scriptable, + isIndexable: isFunction(_indexable) ? _indexable : ()=>_indexable + }; +} +const readKey = (prefix, name)=>prefix ? prefix + _capitalize(name) : name; +const needsSubResolver = (prop, value)=>isObject(value) && prop !== 'adapters' && (Object.getPrototypeOf(value) === null || value.constructor === Object); +function _cached(target, prop, resolve) { + if (Object.prototype.hasOwnProperty.call(target, prop) || prop === 'constructor') { + return target[prop]; + } + const value = resolve(); + // cache the resolved value + target[prop] = value; + return value; +} +function _resolveWithContext(target, prop, receiver) { + const { _proxy , _context , _subProxy , _descriptors: descriptors } = target; + let value = _proxy[prop]; // resolve from proxy + // resolve with context + if (isFunction(value) && descriptors.isScriptable(prop)) { + value = _resolveScriptable(prop, value, target, receiver); + } + if (isArray(value) && value.length) { + value = _resolveArray(prop, value, target, descriptors.isIndexable); + } + if (needsSubResolver(prop, value)) { + // if the resolved value is an object, create a sub resolver for it + value = _attachContext(value, _context, _subProxy && _subProxy[prop], descriptors); + } + return value; +} +function _resolveScriptable(prop, getValue, target, receiver) { + const { _proxy , _context , _subProxy , _stack } = target; + if (_stack.has(prop)) { + throw new Error('Recursion detected: ' + Array.from(_stack).join('->') + '->' + prop); + } + _stack.add(prop); + let value = getValue(_context, _subProxy || receiver); + _stack.delete(prop); + if (needsSubResolver(prop, value)) { + // When scriptable option returns an object, create a resolver on that. + value = createSubResolver(_proxy._scopes, _proxy, prop, value); + } + return value; +} +function _resolveArray(prop, value, target, isIndexable) { + const { _proxy , _context , _subProxy , _descriptors: descriptors } = target; + if (typeof _context.index !== 'undefined' && isIndexable(prop)) { + return value[_context.index % value.length]; + } else if (isObject(value[0])) { + // Array of objects, return array or resolvers + const arr = value; + const scopes = _proxy._scopes.filter((s)=>s !== arr); + value = []; + for (const item of arr){ + const resolver = createSubResolver(scopes, _proxy, prop, item); + value.push(_attachContext(resolver, _context, _subProxy && _subProxy[prop], descriptors)); + } + } + return value; +} +function resolveFallback(fallback, prop, value) { + return isFunction(fallback) ? fallback(prop, value) : fallback; +} +const getScope = (key, parent)=>key === true ? parent : typeof key === 'string' ? resolveObjectKey(parent, key) : undefined; +function addScopes(set, parentScopes, key, parentFallback, value) { + for (const parent of parentScopes){ + const scope = getScope(key, parent); + if (scope) { + set.add(scope); + const fallback = resolveFallback(scope._fallback, key, value); + if (typeof fallback !== 'undefined' && fallback !== key && fallback !== parentFallback) { + // When we reach the descriptor that defines a new _fallback, return that. + // The fallback will resume to that new scope. + return fallback; + } + } else if (scope === false && typeof parentFallback !== 'undefined' && key !== parentFallback) { + // Fallback to `false` results to `false`, when falling back to different key. + // For example `interaction` from `hover` or `plugins.tooltip` and `animation` from `animations` + return null; + } + } + return false; +} +function createSubResolver(parentScopes, resolver, prop, value) { + const rootScopes = resolver._rootScopes; + const fallback = resolveFallback(resolver._fallback, prop, value); + const allScopes = [ + ...parentScopes, + ...rootScopes + ]; + const set = new Set(); + set.add(value); + let key = addScopesFromKey(set, allScopes, prop, fallback || prop, value); + if (key === null) { + return false; + } + if (typeof fallback !== 'undefined' && fallback !== prop) { + key = addScopesFromKey(set, allScopes, fallback, key, value); + if (key === null) { + return false; + } + } + return _createResolver(Array.from(set), [ + '' + ], rootScopes, fallback, ()=>subGetTarget(resolver, prop, value)); +} +function addScopesFromKey(set, allScopes, key, fallback, item) { + while(key){ + key = addScopes(set, allScopes, key, fallback, item); + } + return key; +} +function subGetTarget(resolver, prop, value) { + const parent = resolver._getTarget(); + if (!(prop in parent)) { + parent[prop] = {}; + } + const target = parent[prop]; + if (isArray(target) && isObject(value)) { + // For array of objects, the object is used to store updated values + return value; + } + return target || {}; +} +function _resolveWithPrefixes(prop, prefixes, scopes, proxy) { + let value; + for (const prefix of prefixes){ + value = _resolve(readKey(prefix, prop), scopes); + if (typeof value !== 'undefined') { + return needsSubResolver(prop, value) ? createSubResolver(scopes, proxy, prop, value) : value; + } + } +} +function _resolve(key, scopes) { + for (const scope of scopes){ + if (!scope) { + continue; + } + const value = scope[key]; + if (typeof value !== 'undefined') { + return value; + } + } +} +function getKeysFromAllScopes(target) { + let keys = target._keys; + if (!keys) { + keys = target._keys = resolveKeysFromAllScopes(target._scopes); + } + return keys; +} +function resolveKeysFromAllScopes(scopes) { + const set = new Set(); + for (const scope of scopes){ + for (const key of Object.keys(scope).filter((k)=>!k.startsWith('_'))){ + set.add(key); + } + } + return Array.from(set); +} +function _parseObjectDataRadialScale(meta, data, start, count) { + const { iScale } = meta; + const { key ='r' } = this._parsing; + const parsed = new Array(count); + let i, ilen, index, item; + for(i = 0, ilen = count; i < ilen; ++i){ + index = i + start; + item = data[index]; + parsed[i] = { + r: iScale.parse(resolveObjectKey(item, key), index) + }; + } + return parsed; +} + +const EPSILON = Number.EPSILON || 1e-14; +const getPoint = (points, i)=>i < points.length && !points[i].skip && points[i]; +const getValueAxis = (indexAxis)=>indexAxis === 'x' ? 'y' : 'x'; +function splineCurve(firstPoint, middlePoint, afterPoint, t) { + // Props to Rob Spencer at scaled innovation for his post on splining between points + // http://scaledinnovation.com/analytics/splines/aboutSplines.html + // This function must also respect "skipped" points + const previous = firstPoint.skip ? middlePoint : firstPoint; + const current = middlePoint; + const next = afterPoint.skip ? middlePoint : afterPoint; + const d01 = distanceBetweenPoints(current, previous); + const d12 = distanceBetweenPoints(next, current); + let s01 = d01 / (d01 + d12); + let s12 = d12 / (d01 + d12); + // If all points are the same, s01 & s02 will be inf + s01 = isNaN(s01) ? 0 : s01; + s12 = isNaN(s12) ? 0 : s12; + const fa = t * s01; // scaling factor for triangle Ta + const fb = t * s12; + return { + previous: { + x: current.x - fa * (next.x - previous.x), + y: current.y - fa * (next.y - previous.y) + }, + next: { + x: current.x + fb * (next.x - previous.x), + y: current.y + fb * (next.y - previous.y) + } + }; +} +/** + * Adjust tangents to ensure monotonic properties + */ function monotoneAdjust(points, deltaK, mK) { + const pointsLen = points.length; + let alphaK, betaK, tauK, squaredMagnitude, pointCurrent; + let pointAfter = getPoint(points, 0); + for(let i = 0; i < pointsLen - 1; ++i){ + pointCurrent = pointAfter; + pointAfter = getPoint(points, i + 1); + if (!pointCurrent || !pointAfter) { + continue; + } + if (almostEquals(deltaK[i], 0, EPSILON)) { + mK[i] = mK[i + 1] = 0; + continue; + } + alphaK = mK[i] / deltaK[i]; + betaK = mK[i + 1] / deltaK[i]; + squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2); + if (squaredMagnitude <= 9) { + continue; + } + tauK = 3 / Math.sqrt(squaredMagnitude); + mK[i] = alphaK * tauK * deltaK[i]; + mK[i + 1] = betaK * tauK * deltaK[i]; + } +} +function monotoneCompute(points, mK, indexAxis = 'x') { + const valueAxis = getValueAxis(indexAxis); + const pointsLen = points.length; + let delta, pointBefore, pointCurrent; + let pointAfter = getPoint(points, 0); + for(let i = 0; i < pointsLen; ++i){ + pointBefore = pointCurrent; + pointCurrent = pointAfter; + pointAfter = getPoint(points, i + 1); + if (!pointCurrent) { + continue; + } + const iPixel = pointCurrent[indexAxis]; + const vPixel = pointCurrent[valueAxis]; + if (pointBefore) { + delta = (iPixel - pointBefore[indexAxis]) / 3; + pointCurrent[`cp1${indexAxis}`] = iPixel - delta; + pointCurrent[`cp1${valueAxis}`] = vPixel - delta * mK[i]; + } + if (pointAfter) { + delta = (pointAfter[indexAxis] - iPixel) / 3; + pointCurrent[`cp2${indexAxis}`] = iPixel + delta; + pointCurrent[`cp2${valueAxis}`] = vPixel + delta * mK[i]; + } + } +} +/** + * This function calculates Bézier control points in a similar way than |splineCurve|, + * but preserves monotonicity of the provided data and ensures no local extremums are added + * between the dataset discrete points due to the interpolation. + * See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation + */ function splineCurveMonotone(points, indexAxis = 'x') { + const valueAxis = getValueAxis(indexAxis); + const pointsLen = points.length; + const deltaK = Array(pointsLen).fill(0); + const mK = Array(pointsLen); + // Calculate slopes (deltaK) and initialize tangents (mK) + let i, pointBefore, pointCurrent; + let pointAfter = getPoint(points, 0); + for(i = 0; i < pointsLen; ++i){ + pointBefore = pointCurrent; + pointCurrent = pointAfter; + pointAfter = getPoint(points, i + 1); + if (!pointCurrent) { + continue; + } + if (pointAfter) { + const slopeDelta = pointAfter[indexAxis] - pointCurrent[indexAxis]; + // In the case of two points that appear at the same x pixel, slopeDeltaX is 0 + deltaK[i] = slopeDelta !== 0 ? (pointAfter[valueAxis] - pointCurrent[valueAxis]) / slopeDelta : 0; + } + mK[i] = !pointBefore ? deltaK[i] : !pointAfter ? deltaK[i - 1] : sign(deltaK[i - 1]) !== sign(deltaK[i]) ? 0 : (deltaK[i - 1] + deltaK[i]) / 2; + } + monotoneAdjust(points, deltaK, mK); + monotoneCompute(points, mK, indexAxis); +} +function capControlPoint(pt, min, max) { + return Math.max(Math.min(pt, max), min); +} +function capBezierPoints(points, area) { + let i, ilen, point, inArea, inAreaPrev; + let inAreaNext = _isPointInArea(points[0], area); + for(i = 0, ilen = points.length; i < ilen; ++i){ + inAreaPrev = inArea; + inArea = inAreaNext; + inAreaNext = i < ilen - 1 && _isPointInArea(points[i + 1], area); + if (!inArea) { + continue; + } + point = points[i]; + if (inAreaPrev) { + point.cp1x = capControlPoint(point.cp1x, area.left, area.right); + point.cp1y = capControlPoint(point.cp1y, area.top, area.bottom); + } + if (inAreaNext) { + point.cp2x = capControlPoint(point.cp2x, area.left, area.right); + point.cp2y = capControlPoint(point.cp2y, area.top, area.bottom); + } + } +} +/** + * @private + */ function _updateBezierControlPoints(points, options, area, loop, indexAxis) { + let i, ilen, point, controlPoints; + // Only consider points that are drawn in case the spanGaps option is used + if (options.spanGaps) { + points = points.filter((pt)=>!pt.skip); + } + if (options.cubicInterpolationMode === 'monotone') { + splineCurveMonotone(points, indexAxis); + } else { + let prev = loop ? points[points.length - 1] : points[0]; + for(i = 0, ilen = points.length; i < ilen; ++i){ + point = points[i]; + controlPoints = splineCurve(prev, point, points[Math.min(i + 1, ilen - (loop ? 0 : 1)) % ilen], options.tension); + point.cp1x = controlPoints.previous.x; + point.cp1y = controlPoints.previous.y; + point.cp2x = controlPoints.next.x; + point.cp2y = controlPoints.next.y; + prev = point; + } + } + if (options.capBezierPoints) { + capBezierPoints(points, area); + } +} + +/** + * @private + */ function _isDomSupported() { + return typeof window !== 'undefined' && typeof document !== 'undefined'; +} +/** + * @private + */ function _getParentNode(domNode) { + let parent = domNode.parentNode; + if (parent && parent.toString() === '[object ShadowRoot]') { + parent = parent.host; + } + return parent; +} +/** + * convert max-width/max-height values that may be percentages into a number + * @private + */ function parseMaxStyle(styleValue, node, parentProperty) { + let valueInPixels; + if (typeof styleValue === 'string') { + valueInPixels = parseInt(styleValue, 10); + if (styleValue.indexOf('%') !== -1) { + // percentage * size in dimension + valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty]; + } + } else { + valueInPixels = styleValue; + } + return valueInPixels; +} +const getComputedStyle = (element)=>element.ownerDocument.defaultView.getComputedStyle(element, null); +function getStyle(el, property) { + return getComputedStyle(el).getPropertyValue(property); +} +const positions = [ + 'top', + 'right', + 'bottom', + 'left' +]; +function getPositionedStyle(styles, style, suffix) { + const result = {}; + suffix = suffix ? '-' + suffix : ''; + for(let i = 0; i < 4; i++){ + const pos = positions[i]; + result[pos] = parseFloat(styles[style + '-' + pos + suffix]) || 0; + } + result.width = result.left + result.right; + result.height = result.top + result.bottom; + return result; +} +const useOffsetPos = (x, y, target)=>(x > 0 || y > 0) && (!target || !target.shadowRoot); +/** + * @param e + * @param canvas + * @returns Canvas position + */ function getCanvasPosition(e, canvas) { + const touches = e.touches; + const source = touches && touches.length ? touches[0] : e; + const { offsetX , offsetY } = source; + let box = false; + let x, y; + if (useOffsetPos(offsetX, offsetY, e.target)) { + x = offsetX; + y = offsetY; + } else { + const rect = canvas.getBoundingClientRect(); + x = source.clientX - rect.left; + y = source.clientY - rect.top; + box = true; + } + return { + x, + y, + box + }; +} +/** + * Gets an event's x, y coordinates, relative to the chart area + * @param event + * @param chart + * @returns x and y coordinates of the event + */ function getRelativePosition(event, chart) { + if ('native' in event) { + return event; + } + const { canvas , currentDevicePixelRatio } = chart; + const style = getComputedStyle(canvas); + const borderBox = style.boxSizing === 'border-box'; + const paddings = getPositionedStyle(style, 'padding'); + const borders = getPositionedStyle(style, 'border', 'width'); + const { x , y , box } = getCanvasPosition(event, canvas); + const xOffset = paddings.left + (box && borders.left); + const yOffset = paddings.top + (box && borders.top); + let { width , height } = chart; + if (borderBox) { + width -= paddings.width + borders.width; + height -= paddings.height + borders.height; + } + return { + x: Math.round((x - xOffset) / width * canvas.width / currentDevicePixelRatio), + y: Math.round((y - yOffset) / height * canvas.height / currentDevicePixelRatio) + }; +} +function getContainerSize(canvas, width, height) { + let maxWidth, maxHeight; + if (width === undefined || height === undefined) { + const container = canvas && _getParentNode(canvas); + if (!container) { + width = canvas.clientWidth; + height = canvas.clientHeight; + } else { + const rect = container.getBoundingClientRect(); // this is the border box of the container + const containerStyle = getComputedStyle(container); + const containerBorder = getPositionedStyle(containerStyle, 'border', 'width'); + const containerPadding = getPositionedStyle(containerStyle, 'padding'); + width = rect.width - containerPadding.width - containerBorder.width; + height = rect.height - containerPadding.height - containerBorder.height; + maxWidth = parseMaxStyle(containerStyle.maxWidth, container, 'clientWidth'); + maxHeight = parseMaxStyle(containerStyle.maxHeight, container, 'clientHeight'); + } + } + return { + width, + height, + maxWidth: maxWidth || INFINITY, + maxHeight: maxHeight || INFINITY + }; +} +const round1 = (v)=>Math.round(v * 10) / 10; +// eslint-disable-next-line complexity +function getMaximumSize(canvas, bbWidth, bbHeight, aspectRatio) { + const style = getComputedStyle(canvas); + const margins = getPositionedStyle(style, 'margin'); + const maxWidth = parseMaxStyle(style.maxWidth, canvas, 'clientWidth') || INFINITY; + const maxHeight = parseMaxStyle(style.maxHeight, canvas, 'clientHeight') || INFINITY; + const containerSize = getContainerSize(canvas, bbWidth, bbHeight); + let { width , height } = containerSize; + if (style.boxSizing === 'content-box') { + const borders = getPositionedStyle(style, 'border', 'width'); + const paddings = getPositionedStyle(style, 'padding'); + width -= paddings.width + borders.width; + height -= paddings.height + borders.height; + } + width = Math.max(0, width - margins.width); + height = Math.max(0, aspectRatio ? width / aspectRatio : height - margins.height); + width = round1(Math.min(width, maxWidth, containerSize.maxWidth)); + height = round1(Math.min(height, maxHeight, containerSize.maxHeight)); + if (width && !height) { + // https://github.com/chartjs/Chart.js/issues/4659 + // If the canvas has width, but no height, default to aspectRatio of 2 (canvas default) + height = round1(width / 2); + } + const maintainHeight = bbWidth !== undefined || bbHeight !== undefined; + if (maintainHeight && aspectRatio && containerSize.height && height > containerSize.height) { + height = containerSize.height; + width = round1(Math.floor(height * aspectRatio)); + } + return { + width, + height + }; +} +/** + * @param chart + * @param forceRatio + * @param forceStyle + * @returns True if the canvas context size or transformation has changed. + */ function retinaScale(chart, forceRatio, forceStyle) { + const pixelRatio = forceRatio || 1; + const deviceHeight = Math.floor(chart.height * pixelRatio); + const deviceWidth = Math.floor(chart.width * pixelRatio); + chart.height = Math.floor(chart.height); + chart.width = Math.floor(chart.width); + const canvas = chart.canvas; + // If no style has been set on the canvas, the render size is used as display size, + // making the chart visually bigger, so let's enforce it to the "correct" values. + // See https://github.com/chartjs/Chart.js/issues/3575 + if (canvas.style && (forceStyle || !canvas.style.height && !canvas.style.width)) { + canvas.style.height = `${chart.height}px`; + canvas.style.width = `${chart.width}px`; + } + if (chart.currentDevicePixelRatio !== pixelRatio || canvas.height !== deviceHeight || canvas.width !== deviceWidth) { + chart.currentDevicePixelRatio = pixelRatio; + canvas.height = deviceHeight; + canvas.width = deviceWidth; + chart.ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); + return true; + } + return false; +} +/** + * Detects support for options object argument in addEventListener. + * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support + * @private + */ const supportsEventListenerOptions = function() { + let passiveSupported = false; + try { + const options = { + get passive () { + passiveSupported = true; + return false; + } + }; + if (_isDomSupported()) { + window.addEventListener('test', null, options); + window.removeEventListener('test', null, options); + } + } catch (e) { + // continue regardless of error + } + return passiveSupported; +}(); +/** + * The "used" size is the final value of a dimension property after all calculations have + * been performed. This method uses the computed style of `element` but returns undefined + * if the computed style is not expressed in pixels. That can happen in some cases where + * `element` has a size relative to its parent and this last one is not yet displayed, + * for example because of `display: none` on a parent node. + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value + * @returns Size in pixels or undefined if unknown. + */ function readUsedSize(element, property) { + const value = getStyle(element, property); + const matches = value && value.match(/^(\d+)(\.\d+)?px$/); + return matches ? +matches[1] : undefined; +} + +/** + * @private + */ function _pointInLine(p1, p2, t, mode) { + return { + x: p1.x + t * (p2.x - p1.x), + y: p1.y + t * (p2.y - p1.y) + }; +} +/** + * @private + */ function _steppedInterpolation(p1, p2, t, mode) { + return { + x: p1.x + t * (p2.x - p1.x), + y: mode === 'middle' ? t < 0.5 ? p1.y : p2.y : mode === 'after' ? t < 1 ? p1.y : p2.y : t > 0 ? p2.y : p1.y + }; +} +/** + * @private + */ function _bezierInterpolation(p1, p2, t, mode) { + const cp1 = { + x: p1.cp2x, + y: p1.cp2y + }; + const cp2 = { + x: p2.cp1x, + y: p2.cp1y + }; + const a = _pointInLine(p1, cp1, t); + const b = _pointInLine(cp1, cp2, t); + const c = _pointInLine(cp2, p2, t); + const d = _pointInLine(a, b, t); + const e = _pointInLine(b, c, t); + return _pointInLine(d, e, t); +} + +const getRightToLeftAdapter = function(rectX, width) { + return { + x (x) { + return rectX + rectX + width - x; + }, + setWidth (w) { + width = w; + }, + textAlign (align) { + if (align === 'center') { + return align; + } + return align === 'right' ? 'left' : 'right'; + }, + xPlus (x, value) { + return x - value; + }, + leftForLtr (x, itemWidth) { + return x - itemWidth; + } + }; +}; +const getLeftToRightAdapter = function() { + return { + x (x) { + return x; + }, + setWidth (w) {}, + textAlign (align) { + return align; + }, + xPlus (x, value) { + return x + value; + }, + leftForLtr (x, _itemWidth) { + return x; + } + }; +}; +function getRtlAdapter(rtl, rectX, width) { + return rtl ? getRightToLeftAdapter(rectX, width) : getLeftToRightAdapter(); +} +function overrideTextDirection(ctx, direction) { + let style, original; + if (direction === 'ltr' || direction === 'rtl') { + style = ctx.canvas.style; + original = [ + style.getPropertyValue('direction'), + style.getPropertyPriority('direction') + ]; + style.setProperty('direction', direction, 'important'); + ctx.prevTextDirection = original; + } +} +function restoreTextDirection(ctx, original) { + if (original !== undefined) { + delete ctx.prevTextDirection; + ctx.canvas.style.setProperty('direction', original[0], original[1]); + } +} + +function propertyFn(property) { + if (property === 'angle') { + return { + between: _angleBetween, + compare: _angleDiff, + normalize: _normalizeAngle + }; + } + return { + between: _isBetween, + compare: (a, b)=>a - b, + normalize: (x)=>x + }; +} +function normalizeSegment({ start , end , count , loop , style }) { + return { + start: start % count, + end: end % count, + loop: loop && (end - start + 1) % count === 0, + style + }; +} +function getSegment(segment, points, bounds) { + const { property , start: startBound , end: endBound } = bounds; + const { between , normalize } = propertyFn(property); + const count = points.length; + let { start , end , loop } = segment; + let i, ilen; + if (loop) { + start += count; + end += count; + for(i = 0, ilen = count; i < ilen; ++i){ + if (!between(normalize(points[start % count][property]), startBound, endBound)) { + break; + } + start--; + end--; + } + start %= count; + end %= count; + } + if (end < start) { + end += count; + } + return { + start, + end, + loop, + style: segment.style + }; +} + function _boundSegment(segment, points, bounds) { + if (!bounds) { + return [ + segment + ]; + } + const { property , start: startBound , end: endBound } = bounds; + const count = points.length; + const { compare , between , normalize } = propertyFn(property); + const { start , end , loop , style } = getSegment(segment, points, bounds); + const result = []; + let inside = false; + let subStart = null; + let value, point, prevValue; + const startIsBefore = ()=>between(startBound, prevValue, value) && compare(startBound, prevValue) !== 0; + const endIsBefore = ()=>compare(endBound, value) === 0 || between(endBound, prevValue, value); + const shouldStart = ()=>inside || startIsBefore(); + const shouldStop = ()=>!inside || endIsBefore(); + for(let i = start, prev = start; i <= end; ++i){ + point = points[i % count]; + if (point.skip) { + continue; + } + value = normalize(point[property]); + if (value === prevValue) { + continue; + } + inside = between(value, startBound, endBound); + if (subStart === null && shouldStart()) { + subStart = compare(value, startBound) === 0 ? i : prev; + } + if (subStart !== null && shouldStop()) { + result.push(normalizeSegment({ + start: subStart, + end: i, + loop, + count, + style + })); + subStart = null; + } + prev = i; + prevValue = value; + } + if (subStart !== null) { + result.push(normalizeSegment({ + start: subStart, + end, + loop, + count, + style + })); + } + return result; +} + function _boundSegments(line, bounds) { + const result = []; + const segments = line.segments; + for(let i = 0; i < segments.length; i++){ + const sub = _boundSegment(segments[i], line.points, bounds); + if (sub.length) { + result.push(...sub); + } + } + return result; +} + function findStartAndEnd(points, count, loop, spanGaps) { + let start = 0; + let end = count - 1; + if (loop && !spanGaps) { + while(start < count && !points[start].skip){ + start++; + } + } + while(start < count && points[start].skip){ + start++; + } + start %= count; + if (loop) { + end += start; + } + while(end > start && points[end % count].skip){ + end--; + } + end %= count; + return { + start, + end + }; +} + function solidSegments(points, start, max, loop) { + const count = points.length; + const result = []; + let last = start; + let prev = points[start]; + let end; + for(end = start + 1; end <= max; ++end){ + const cur = points[end % count]; + if (cur.skip || cur.stop) { + if (!prev.skip) { + loop = false; + result.push({ + start: start % count, + end: (end - 1) % count, + loop + }); + start = last = cur.stop ? end : null; + } + } else { + last = end; + if (prev.skip) { + start = end; + } + } + prev = cur; + } + if (last !== null) { + result.push({ + start: start % count, + end: last % count, + loop + }); + } + return result; +} + function _computeSegments(line, segmentOptions) { + const points = line.points; + const spanGaps = line.options.spanGaps; + const count = points.length; + if (!count) { + return []; + } + const loop = !!line._loop; + const { start , end } = findStartAndEnd(points, count, loop, spanGaps); + if (spanGaps === true) { + return splitByStyles(line, [ + { + start, + end, + loop + } + ], points, segmentOptions); + } + const max = end < start ? end + count : end; + const completeLoop = !!line._fullLoop && start === 0 && end === count - 1; + return splitByStyles(line, solidSegments(points, start, max, completeLoop), points, segmentOptions); +} + function splitByStyles(line, segments, points, segmentOptions) { + if (!segmentOptions || !segmentOptions.setContext || !points) { + return segments; + } + return doSplitByStyles(line, segments, points, segmentOptions); +} + function doSplitByStyles(line, segments, points, segmentOptions) { + const chartContext = line._chart.getContext(); + const baseStyle = readStyle(line.options); + const { _datasetIndex: datasetIndex , options: { spanGaps } } = line; + const count = points.length; + const result = []; + let prevStyle = baseStyle; + let start = segments[0].start; + let i = start; + function addStyle(s, e, l, st) { + const dir = spanGaps ? -1 : 1; + if (s === e) { + return; + } + s += count; + while(points[s % count].skip){ + s -= dir; + } + while(points[e % count].skip){ + e += dir; + } + if (s % count !== e % count) { + result.push({ + start: s % count, + end: e % count, + loop: l, + style: st + }); + prevStyle = st; + start = e % count; + } + } + for (const segment of segments){ + start = spanGaps ? start : segment.start; + let prev = points[start % count]; + let style; + for(i = start + 1; i <= segment.end; i++){ + const pt = points[i % count]; + style = readStyle(segmentOptions.setContext(createContext(chartContext, { + type: 'segment', + p0: prev, + p1: pt, + p0DataIndex: (i - 1) % count, + p1DataIndex: i % count, + datasetIndex + }))); + if (styleChanged(style, prevStyle)) { + addStyle(start, i - 1, segment.loop, prevStyle); + } + prev = pt; + prevStyle = style; + } + if (start < i - 1) { + addStyle(start, i - 1, segment.loop, prevStyle); + } + } + return result; +} +function readStyle(options) { + return { + backgroundColor: options.backgroundColor, + borderCapStyle: options.borderCapStyle, + borderDash: options.borderDash, + borderDashOffset: options.borderDashOffset, + borderJoinStyle: options.borderJoinStyle, + borderWidth: options.borderWidth, + borderColor: options.borderColor + }; +} +function styleChanged(style, prevStyle) { + if (!prevStyle) { + return false; + } + const cache = []; + const replacer = function(key, value) { + if (!isPatternOrGradient(value)) { + return value; + } + if (!cache.includes(value)) { + cache.push(value); + } + return cache.indexOf(value); + }; + return JSON.stringify(style, replacer) !== JSON.stringify(prevStyle, replacer); +} + +function getSizeForArea(scale, chartArea, field) { + return scale.options.clip ? scale[field] : chartArea[field]; +} +function getDatasetArea(meta, chartArea) { + const { xScale , yScale } = meta; + if (xScale && yScale) { + return { + left: getSizeForArea(xScale, chartArea, 'left'), + right: getSizeForArea(xScale, chartArea, 'right'), + top: getSizeForArea(yScale, chartArea, 'top'), + bottom: getSizeForArea(yScale, chartArea, 'bottom') + }; + } + return chartArea; +} +function getDatasetClipArea(chart, meta) { + const clip = meta._clip; + if (clip.disabled) { + return false; + } + const area = getDatasetArea(meta, chart.chartArea); + return { + left: clip.left === false ? 0 : area.left - (clip.left === true ? 0 : clip.left), + right: clip.right === false ? chart.width : area.right + (clip.right === true ? 0 : clip.right), + top: clip.top === false ? 0 : area.top - (clip.top === true ? 0 : clip.top), + bottom: clip.bottom === false ? chart.height : area.bottom + (clip.bottom === true ? 0 : clip.bottom) + }; +} + +exports.HALF_PI = HALF_PI; +exports.INFINITY = INFINITY; +exports.PI = PI; +exports.PITAU = PITAU; +exports.QUARTER_PI = QUARTER_PI; +exports.RAD_PER_DEG = RAD_PER_DEG; +exports.TAU = TAU; +exports.TWO_THIRDS_PI = TWO_THIRDS_PI; +exports.Ticks = Ticks; +exports._addGrace = _addGrace; +exports._alignPixel = _alignPixel; +exports._alignStartEnd = _alignStartEnd; +exports._angleBetween = _angleBetween; +exports._angleDiff = _angleDiff; +exports._arrayUnique = _arrayUnique; +exports._attachContext = _attachContext; +exports._bezierCurveTo = _bezierCurveTo; +exports._bezierInterpolation = _bezierInterpolation; +exports._boundSegment = _boundSegment; +exports._boundSegments = _boundSegments; +exports._capitalize = _capitalize; +exports._computeSegments = _computeSegments; +exports._createResolver = _createResolver; +exports._decimalPlaces = _decimalPlaces; +exports._deprecated = _deprecated; +exports._descriptors = _descriptors; +exports._elementsEqual = _elementsEqual; +exports._factorize = _factorize; +exports._filterBetween = _filterBetween; +exports._getParentNode = _getParentNode; +exports._getStartAndCountOfVisiblePoints = _getStartAndCountOfVisiblePoints; +exports._int16Range = _int16Range; +exports._isBetween = _isBetween; +exports._isClickEvent = _isClickEvent; +exports._isDomSupported = _isDomSupported; +exports._isPointInArea = _isPointInArea; +exports._limitValue = _limitValue; +exports._longestText = _longestText; +exports._lookup = _lookup; +exports._lookupByKey = _lookupByKey; +exports._measureText = _measureText; +exports._merger = _merger; +exports._mergerIf = _mergerIf; +exports._normalizeAngle = _normalizeAngle; +exports._parseObjectDataRadialScale = _parseObjectDataRadialScale; +exports._pointInLine = _pointInLine; +exports._readValueToProps = _readValueToProps; +exports._rlookupByKey = _rlookupByKey; +exports._scaleRangesChanged = _scaleRangesChanged; +exports._setMinAndMaxByKey = _setMinAndMaxByKey; +exports._splitKey = _splitKey; +exports._steppedInterpolation = _steppedInterpolation; +exports._steppedLineTo = _steppedLineTo; +exports._textX = _textX; +exports._toLeftRightCenter = _toLeftRightCenter; +exports._updateBezierControlPoints = _updateBezierControlPoints; +exports.addRoundedRectPath = addRoundedRectPath; +exports.almostEquals = almostEquals; +exports.almostWhole = almostWhole; +exports.callback = callback; +exports.clearCanvas = clearCanvas; +exports.clipArea = clipArea; +exports.clone = clone; +exports.color = color; +exports.createContext = createContext; +exports.debounce = debounce; +exports.defaults = defaults; +exports.defined = defined; +exports.descriptors = descriptors; +exports.distanceBetweenPoints = distanceBetweenPoints; +exports.drawPoint = drawPoint; +exports.drawPointLegend = drawPointLegend; +exports.each = each; +exports.effects = effects; +exports.finiteOrDefault = finiteOrDefault; +exports.fontString = fontString; +exports.formatNumber = formatNumber; +exports.getAngleFromPoint = getAngleFromPoint; +exports.getDatasetClipArea = getDatasetClipArea; +exports.getHoverColor = getHoverColor; +exports.getMaximumSize = getMaximumSize; +exports.getRelativePosition = getRelativePosition; +exports.getRtlAdapter = getRtlAdapter; +exports.getStyle = getStyle; +exports.isArray = isArray; +exports.isFunction = isFunction; +exports.isNullOrUndef = isNullOrUndef; +exports.isNumber = isNumber; +exports.isNumberFinite = isNumberFinite; +exports.isObject = isObject; +exports.isPatternOrGradient = isPatternOrGradient; +exports.listenArrayEvents = listenArrayEvents; +exports.log10 = log10; +exports.merge = merge; +exports.mergeIf = mergeIf; +exports.niceNum = niceNum; +exports.noop = noop; +exports.overrideTextDirection = overrideTextDirection; +exports.overrides = overrides; +exports.readUsedSize = readUsedSize; +exports.renderText = renderText; +exports.requestAnimFrame = requestAnimFrame; +exports.resolve = resolve; +exports.resolveObjectKey = resolveObjectKey; +exports.restoreTextDirection = restoreTextDirection; +exports.retinaScale = retinaScale; +exports.setsEqual = setsEqual; +exports.sign = sign; +exports.splineCurve = splineCurve; +exports.splineCurveMonotone = splineCurveMonotone; +exports.supportsEventListenerOptions = supportsEventListenerOptions; +exports.throttled = throttled; +exports.toDegrees = toDegrees; +exports.toDimension = toDimension; +exports.toFont = toFont; +exports.toFontString = toFontString; +exports.toLineHeight = toLineHeight; +exports.toPadding = toPadding; +exports.toPercentage = toPercentage; +exports.toRadians = toRadians; +exports.toTRBL = toTRBL; +exports.toTRBLCorners = toTRBLCorners; +exports.uid = uid; +exports.unclipArea = unclipArea; +exports.unlistenArrayEvents = unlistenArrayEvents; +exports.valueOrDefault = valueOrDefault; +//# sourceMappingURL=helpers.dataset.cjs.map diff --git a/frontend/node_modules/chart.js/dist/chunks/helpers.dataset.cjs.map b/frontend/node_modules/chart.js/dist/chunks/helpers.dataset.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..6d72dc2e455a85756664a6f659dbc8338f575c64 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/chunks/helpers.dataset.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.dataset.cjs","sources":["../../src/helpers/helpers.core.ts","../../src/helpers/helpers.math.ts","../../src/helpers/helpers.collection.ts","../../src/helpers/helpers.extras.ts","../../src/helpers/helpers.easing.ts","../../src/helpers/helpers.color.ts","../../src/core/core.animations.defaults.js","../../src/core/core.layouts.defaults.js","../../src/helpers/helpers.intl.ts","../../src/core/core.ticks.js","../../src/core/core.scale.defaults.js","../../src/core/core.defaults.js","../../src/helpers/helpers.canvas.ts","../../src/helpers/helpers.options.ts","../../src/helpers/helpers.config.ts","../../src/helpers/helpers.curve.ts","../../src/helpers/helpers.dom.ts","../../src/helpers/helpers.interpolation.ts","../../src/helpers/helpers.rtl.ts","../../src/helpers/helpers.segment.js","../../src/helpers/helpers.dataset.ts"],"sourcesContent":["/**\n * @namespace Chart.helpers\n */\n\nimport type {AnyObject} from '../types/basic.js';\nimport type {ActiveDataPoint, ChartEvent} from '../types/index.js';\n\n/**\n * An empty function that can be used, for example, for optional callback.\n */\nexport function noop() {\n /* noop */\n}\n\n/**\n * Returns a unique id, sequentially generated from a global variable.\n */\nexport const uid = (() => {\n let id = 0;\n return () => id++;\n})();\n\n/**\n * Returns true if `value` is neither null nor undefined, else returns false.\n * @param value - The value to test.\n * @since 2.7.0\n */\nexport function isNullOrUndef(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/**\n * Returns true if `value` is an array (including typed arrays), else returns false.\n * @param value - The value to test.\n * @function\n */\nexport function isArray(value: unknown): value is T[] {\n if (Array.isArray && Array.isArray(value)) {\n return true;\n }\n const type = Object.prototype.toString.call(value);\n if (type.slice(0, 7) === '[object' && type.slice(-6) === 'Array]') {\n return true;\n }\n return false;\n}\n\n/**\n * Returns true if `value` is an object (excluding null), else returns false.\n * @param value - The value to test.\n * @since 2.7.0\n */\nexport function isObject(value: unknown): value is AnyObject {\n return value !== null && Object.prototype.toString.call(value) === '[object Object]';\n}\n\n/**\n * Returns true if `value` is a finite number, else returns false\n * @param value - The value to test.\n */\nfunction isNumberFinite(value: unknown): value is number {\n return (typeof value === 'number' || value instanceof Number) && isFinite(+value);\n}\nexport {\n isNumberFinite as isFinite,\n};\n\n/**\n * Returns `value` if finite, else returns `defaultValue`.\n * @param value - The value to return if defined.\n * @param defaultValue - The value to return if `value` is not finite.\n */\nexport function finiteOrDefault(value: unknown, defaultValue: number) {\n return isNumberFinite(value) ? value : defaultValue;\n}\n\n/**\n * Returns `value` if defined, else returns `defaultValue`.\n * @param value - The value to return if defined.\n * @param defaultValue - The value to return if `value` is undefined.\n */\nexport function valueOrDefault(value: T | undefined, defaultValue: T) {\n return typeof value === 'undefined' ? defaultValue : value;\n}\n\nexport const toPercentage = (value: number | string, dimension: number) =>\n typeof value === 'string' && value.endsWith('%') ?\n parseFloat(value) / 100\n : +value / dimension;\n\nexport const toDimension = (value: number | string, dimension: number) =>\n typeof value === 'string' && value.endsWith('%') ?\n parseFloat(value) / 100 * dimension\n : +value;\n\n/**\n * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the\n * value returned by `fn`. If `fn` is not a function, this method returns undefined.\n * @param fn - The function to call.\n * @param args - The arguments with which `fn` should be called.\n * @param [thisArg] - The value of `this` provided for the call to `fn`.\n */\nexport function callback R, TA, R>(\n fn: T | undefined,\n args: unknown[],\n thisArg?: TA\n): R | undefined {\n if (fn && typeof fn.call === 'function') {\n return fn.apply(thisArg, args);\n }\n}\n\n/**\n * Note(SB) for performance sake, this method should only be used when loopable type\n * is unknown or in none intensive code (not called often and small loopable). Else\n * it's preferable to use a regular for() loop and save extra function calls.\n * @param loopable - The object or array to be iterated.\n * @param fn - The function to call for each item.\n * @param [thisArg] - The value of `this` provided for the call to `fn`.\n * @param [reverse] - If true, iterates backward on the loopable.\n */\nexport function each(\n loopable: Record,\n fn: (this: TA, v: T, i: string) => void,\n thisArg?: TA,\n reverse?: boolean\n): void;\nexport function each(\n loopable: T[],\n fn: (this: TA, v: T, i: number) => void,\n thisArg?: TA,\n reverse?: boolean\n): void;\nexport function each(\n loopable: T[] | Record,\n fn: (this: TA, v: T, i: any) => void,\n thisArg?: TA,\n reverse?: boolean\n) {\n let i: number, len: number, keys: string[];\n if (isArray(loopable)) {\n len = loopable.length;\n if (reverse) {\n for (i = len - 1; i >= 0; i--) {\n fn.call(thisArg, loopable[i], i);\n }\n } else {\n for (i = 0; i < len; i++) {\n fn.call(thisArg, loopable[i], i);\n }\n }\n } else if (isObject(loopable)) {\n keys = Object.keys(loopable);\n len = keys.length;\n for (i = 0; i < len; i++) {\n fn.call(thisArg, loopable[keys[i]], keys[i]);\n }\n }\n}\n\n/**\n * Returns true if the `a0` and `a1` arrays have the same content, else returns false.\n * @param a0 - The array to compare\n * @param a1 - The array to compare\n * @private\n */\nexport function _elementsEqual(a0: ActiveDataPoint[], a1: ActiveDataPoint[]) {\n let i: number, ilen: number, v0: ActiveDataPoint, v1: ActiveDataPoint;\n\n if (!a0 || !a1 || a0.length !== a1.length) {\n return false;\n }\n\n for (i = 0, ilen = a0.length; i < ilen; ++i) {\n v0 = a0[i];\n v1 = a1[i];\n\n if (v0.datasetIndex !== v1.datasetIndex || v0.index !== v1.index) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Returns a deep copy of `source` without keeping references on objects and arrays.\n * @param source - The value to clone.\n */\nexport function clone(source: T): T {\n if (isArray(source)) {\n return source.map(clone) as unknown as T;\n }\n\n if (isObject(source)) {\n const target = Object.create(null);\n const keys = Object.keys(source);\n const klen = keys.length;\n let k = 0;\n\n for (; k < klen; ++k) {\n target[keys[k]] = clone(source[keys[k]]);\n }\n\n return target;\n }\n\n return source;\n}\n\nfunction isValidKey(key: string) {\n return ['__proto__', 'prototype', 'constructor'].indexOf(key) === -1;\n}\n\n/**\n * The default merger when Chart.helpers.merge is called without merger option.\n * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.\n * @private\n */\nexport function _merger(key: string, target: AnyObject, source: AnyObject, options: AnyObject) {\n if (!isValidKey(key)) {\n return;\n }\n\n const tval = target[key];\n const sval = source[key];\n\n if (isObject(tval) && isObject(sval)) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n merge(tval, sval, options);\n } else {\n target[key] = clone(sval);\n }\n}\n\nexport interface MergeOptions {\n merger?: (key: string, target: AnyObject, source: AnyObject, options?: AnyObject) => void;\n}\n\n/**\n * Recursively deep copies `source` properties into `target` with the given `options`.\n * IMPORTANT: `target` is not cloned and will be updated with `source` properties.\n * @param target - The target object in which all sources are merged into.\n * @param source - Object(s) to merge into `target`.\n * @param [options] - Merging options:\n * @param [options.merger] - The merge method (key, target, source, options)\n * @returns The `target` object.\n */\nexport function merge(target: T, source: [], options?: MergeOptions): T;\nexport function merge(target: T, source: S1, options?: MergeOptions): T & S1;\nexport function merge(target: T, source: [S1], options?: MergeOptions): T & S1;\nexport function merge(target: T, source: [S1, S2], options?: MergeOptions): T & S1 & S2;\nexport function merge(target: T, source: [S1, S2, S3], options?: MergeOptions): T & S1 & S2 & S3;\nexport function merge(\n target: T,\n source: [S1, S2, S3, S4],\n options?: MergeOptions\n): T & S1 & S2 & S3 & S4;\nexport function merge(target: T, source: AnyObject[], options?: MergeOptions): AnyObject;\nexport function merge(target: T, source: AnyObject[], options?: MergeOptions): AnyObject {\n const sources = isArray(source) ? source : [source];\n const ilen = sources.length;\n\n if (!isObject(target)) {\n return target as AnyObject;\n }\n\n options = options || {};\n const merger = options.merger || _merger;\n let current: AnyObject;\n\n for (let i = 0; i < ilen; ++i) {\n current = sources[i];\n if (!isObject(current)) {\n continue;\n }\n\n const keys = Object.keys(current);\n for (let k = 0, klen = keys.length; k < klen; ++k) {\n merger(keys[k], target, current, options as AnyObject);\n }\n }\n\n return target;\n}\n\n/**\n * Recursively deep copies `source` properties into `target` *only* if not defined in target.\n * IMPORTANT: `target` is not cloned and will be updated with `source` properties.\n * @param target - The target object in which all sources are merged into.\n * @param source - Object(s) to merge into `target`.\n * @returns The `target` object.\n */\nexport function mergeIf(target: T, source: []): T;\nexport function mergeIf(target: T, source: S1): T & S1;\nexport function mergeIf(target: T, source: [S1]): T & S1;\nexport function mergeIf(target: T, source: [S1, S2]): T & S1 & S2;\nexport function mergeIf(target: T, source: [S1, S2, S3]): T & S1 & S2 & S3;\nexport function mergeIf(target: T, source: [S1, S2, S3, S4]): T & S1 & S2 & S3 & S4;\nexport function mergeIf(target: T, source: AnyObject[]): AnyObject;\nexport function mergeIf(target: T, source: AnyObject[]): AnyObject {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return merge(target, source, {merger: _mergerIf});\n}\n\n/**\n * Merges source[key] in target[key] only if target[key] is undefined.\n * @private\n */\nexport function _mergerIf(key: string, target: AnyObject, source: AnyObject) {\n if (!isValidKey(key)) {\n return;\n }\n\n const tval = target[key];\n const sval = source[key];\n\n if (isObject(tval) && isObject(sval)) {\n mergeIf(tval, sval);\n } else if (!Object.prototype.hasOwnProperty.call(target, key)) {\n target[key] = clone(sval);\n }\n}\n\n/**\n * @private\n */\nexport function _deprecated(scope: string, value: unknown, previous: string, current: string) {\n if (value !== undefined) {\n console.warn(scope + ': \"' + previous +\n '\" is deprecated. Please use \"' + current + '\" instead');\n }\n}\n\n// resolveObjectKey resolver cache\nconst keyResolvers = {\n // Chart.helpers.core resolveObjectKey should resolve empty key to root object\n '': v => v,\n // default resolvers\n x: o => o.x,\n y: o => o.y\n};\n\n/**\n * @private\n */\nexport function _splitKey(key: string) {\n const parts = key.split('.');\n const keys: string[] = [];\n let tmp = '';\n for (const part of parts) {\n tmp += part;\n if (tmp.endsWith('\\\\')) {\n tmp = tmp.slice(0, -1) + '.';\n } else {\n keys.push(tmp);\n tmp = '';\n }\n }\n return keys;\n}\n\nfunction _getKeyResolver(key: string) {\n const keys = _splitKey(key);\n return obj => {\n for (const k of keys) {\n if (k === '') {\n // For backward compatibility:\n // Chart.helpers.core resolveObjectKey should break at empty key\n break;\n }\n obj = obj && obj[k];\n }\n return obj;\n };\n}\n\nexport function resolveObjectKey(obj: AnyObject, key: string): any {\n const resolver = keyResolvers[key] || (keyResolvers[key] = _getKeyResolver(key));\n return resolver(obj);\n}\n\n/**\n * @private\n */\nexport function _capitalize(str: string) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n\nexport const defined = (value: unknown) => typeof value !== 'undefined';\n\nexport const isFunction = (value: unknown): value is (...args: any[]) => any => typeof value === 'function';\n\n// Adapted from https://stackoverflow.com/questions/31128855/comparing-ecma6-sets-for-equality#31129384\nexport const setsEqual = (a: Set, b: Set) => {\n if (a.size !== b.size) {\n return false;\n }\n\n for (const item of a) {\n if (!b.has(item)) {\n return false;\n }\n }\n\n return true;\n};\n\n/**\n * @param e - The event\n * @private\n */\nexport function _isClickEvent(e: ChartEvent) {\n return e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu';\n}\n","import type {Point} from '../types/geometric.js';\nimport {isFinite as isFiniteNumber} from './helpers.core.js';\n\n/**\n * @alias Chart.helpers.math\n * @namespace\n */\n\nexport const PI = Math.PI;\nexport const TAU = 2 * PI;\nexport const PITAU = TAU + PI;\nexport const INFINITY = Number.POSITIVE_INFINITY;\nexport const RAD_PER_DEG = PI / 180;\nexport const HALF_PI = PI / 2;\nexport const QUARTER_PI = PI / 4;\nexport const TWO_THIRDS_PI = PI * 2 / 3;\n\nexport const log10 = Math.log10;\nexport const sign = Math.sign;\n\nexport function almostEquals(x: number, y: number, epsilon: number) {\n return Math.abs(x - y) < epsilon;\n}\n\n/**\n * Implementation of the nice number algorithm used in determining where axis labels will go\n */\nexport function niceNum(range: number) {\n const roundedRange = Math.round(range);\n range = almostEquals(range, roundedRange, range / 1000) ? roundedRange : range;\n const niceRange = Math.pow(10, Math.floor(log10(range)));\n const fraction = range / niceRange;\n const niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10;\n return niceFraction * niceRange;\n}\n\n/**\n * Returns an array of factors sorted from 1 to sqrt(value)\n * @private\n */\nexport function _factorize(value: number) {\n const result: number[] = [];\n const sqrt = Math.sqrt(value);\n let i: number;\n\n for (i = 1; i < sqrt; i++) {\n if (value % i === 0) {\n result.push(i);\n result.push(value / i);\n }\n }\n if (sqrt === (sqrt | 0)) { // if value is a square number\n result.push(sqrt);\n }\n\n result.sort((a, b) => a - b).pop();\n return result;\n}\n\n/**\n * Verifies that attempting to coerce n to string or number won't throw a TypeError.\n */\nfunction isNonPrimitive(n: unknown) {\n return typeof n === 'symbol' || (typeof n === 'object' && n !== null && !(Symbol.toPrimitive in n || 'toString' in n || 'valueOf' in n));\n}\n\nexport function isNumber(n: unknown): n is number {\n return !isNonPrimitive(n) && !isNaN(parseFloat(n as string)) && isFinite(n as number);\n}\n\nexport function almostWhole(x: number, epsilon: number) {\n const rounded = Math.round(x);\n return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);\n}\n\n/**\n * @private\n */\nexport function _setMinAndMaxByKey(\n array: Record[],\n target: { min: number, max: number },\n property: string\n) {\n let i: number, ilen: number, value: number;\n\n for (i = 0, ilen = array.length; i < ilen; i++) {\n value = array[i][property];\n if (!isNaN(value)) {\n target.min = Math.min(target.min, value);\n target.max = Math.max(target.max, value);\n }\n }\n}\n\nexport function toRadians(degrees: number) {\n return degrees * (PI / 180);\n}\n\nexport function toDegrees(radians: number) {\n return radians * (180 / PI);\n}\n\n/**\n * Returns the number of decimal places\n * i.e. the number of digits after the decimal point, of the value of this Number.\n * @param x - A number.\n * @returns The number of decimal places.\n * @private\n */\nexport function _decimalPlaces(x: number) {\n if (!isFiniteNumber(x)) {\n return;\n }\n let e = 1;\n let p = 0;\n while (Math.round(x * e) / e !== x) {\n e *= 10;\n p++;\n }\n return p;\n}\n\n// Gets the angle from vertical upright to the point about a centre.\nexport function getAngleFromPoint(\n centrePoint: Point,\n anglePoint: Point\n) {\n const distanceFromXCenter = anglePoint.x - centrePoint.x;\n const distanceFromYCenter = anglePoint.y - centrePoint.y;\n const radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);\n\n let angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);\n\n if (angle < (-0.5 * PI)) {\n angle += TAU; // make sure the returned angle is in the range of (-PI/2, 3PI/2]\n }\n\n return {\n angle,\n distance: radialDistanceFromCenter\n };\n}\n\nexport function distanceBetweenPoints(pt1: Point, pt2: Point) {\n return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));\n}\n\n/**\n * Shortest distance between angles, in either direction.\n * @private\n */\nexport function _angleDiff(a: number, b: number) {\n return (a - b + PITAU) % TAU - PI;\n}\n\n/**\n * Normalize angle to be between 0 and 2*PI\n * @private\n */\nexport function _normalizeAngle(a: number) {\n return (a % TAU + TAU) % TAU;\n}\n\n/**\n * @private\n */\nexport function _angleBetween(angle: number, start: number, end: number, sameAngleIsFullCircle?: boolean) {\n const a = _normalizeAngle(angle);\n const s = _normalizeAngle(start);\n const e = _normalizeAngle(end);\n const angleToStart = _normalizeAngle(s - a);\n const angleToEnd = _normalizeAngle(e - a);\n const startToAngle = _normalizeAngle(a - s);\n const endToAngle = _normalizeAngle(a - e);\n return a === s || a === e || (sameAngleIsFullCircle && s === e)\n || (angleToStart > angleToEnd && startToAngle < endToAngle);\n}\n\n/**\n * Limit `value` between `min` and `max`\n * @param value\n * @param min\n * @param max\n * @private\n */\nexport function _limitValue(value: number, min: number, max: number) {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * @param {number} value\n * @private\n */\nexport function _int16Range(value: number) {\n return _limitValue(value, -32768, 32767);\n}\n\n/**\n * @param value\n * @param start\n * @param end\n * @param [epsilon]\n * @private\n */\nexport function _isBetween(value: number, start: number, end: number, epsilon = 1e-6) {\n return value >= Math.min(start, end) - epsilon && value <= Math.max(start, end) + epsilon;\n}\n","import {_capitalize} from './helpers.core.js';\n\n/**\n * Binary search\n * @param table - the table search. must be sorted!\n * @param value - value to find\n * @param cmp\n * @private\n */\nexport function _lookup(\n table: number[],\n value: number,\n cmp?: (value: number) => boolean\n): {lo: number, hi: number};\nexport function _lookup(\n table: T[],\n value: number,\n cmp: (value: number) => boolean\n): {lo: number, hi: number};\nexport function _lookup(\n table: unknown[],\n value: number,\n cmp?: (value: number) => boolean\n) {\n cmp = cmp || ((index) => table[index] < value);\n let hi = table.length - 1;\n let lo = 0;\n let mid: number;\n\n while (hi - lo > 1) {\n mid = (lo + hi) >> 1;\n if (cmp(mid)) {\n lo = mid;\n } else {\n hi = mid;\n }\n }\n\n return {lo, hi};\n}\n\n/**\n * Binary search\n * @param table - the table search. must be sorted!\n * @param key - property name for the value in each entry\n * @param value - value to find\n * @param last - lookup last index\n * @private\n */\nexport const _lookupByKey = (\n table: Record[],\n key: string,\n value: number,\n last?: boolean\n) =>\n _lookup(table, value, last\n ? index => {\n const ti = table[index][key];\n return ti < value || ti === value && table[index + 1][key] === value;\n }\n : index => table[index][key] < value);\n\n/**\n * Reverse binary search\n * @param table - the table search. must be sorted!\n * @param key - property name for the value in each entry\n * @param value - value to find\n * @private\n */\nexport const _rlookupByKey = (\n table: Record[],\n key: string,\n value: number\n) =>\n _lookup(table, value, index => table[index][key] >= value);\n\n/**\n * Return subset of `values` between `min` and `max` inclusive.\n * Values are assumed to be in sorted order.\n * @param values - sorted array of values\n * @param min - min value\n * @param max - max value\n */\nexport function _filterBetween(values: number[], min: number, max: number) {\n let start = 0;\n let end = values.length;\n\n while (start < end && values[start] < min) {\n start++;\n }\n while (end > start && values[end - 1] > max) {\n end--;\n }\n\n return start > 0 || end < values.length\n ? values.slice(start, end)\n : values;\n}\n\nconst arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'] as const;\n\nexport interface ArrayListener {\n _onDataPush?(...item: T[]): void;\n _onDataPop?(): void;\n _onDataShift?(): void;\n _onDataSplice?(index: number, deleteCount: number, ...items: T[]): void;\n _onDataUnshift?(...item: T[]): void;\n}\n\n/**\n * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',\n * 'unshift') and notify the listener AFTER the array has been altered. Listeners are\n * called on the '_onData*' callbacks (e.g. _onDataPush, etc.) with same arguments.\n */\nexport function listenArrayEvents(array: T[], listener: ArrayListener): void;\nexport function listenArrayEvents(array, listener) {\n if (array._chartjs) {\n array._chartjs.listeners.push(listener);\n return;\n }\n\n Object.defineProperty(array, '_chartjs', {\n configurable: true,\n enumerable: false,\n value: {\n listeners: [listener]\n }\n });\n\n arrayEvents.forEach((key) => {\n const method = '_onData' + _capitalize(key);\n const base = array[key];\n\n Object.defineProperty(array, key, {\n configurable: true,\n enumerable: false,\n value(...args) {\n const res = base.apply(this, args);\n\n array._chartjs.listeners.forEach((object) => {\n if (typeof object[method] === 'function') {\n object[method](...args);\n }\n });\n\n return res;\n }\n });\n });\n}\n\n\n/**\n * Removes the given array event listener and cleanup extra attached properties (such as\n * the _chartjs stub and overridden methods) if array doesn't have any more listeners.\n */\nexport function unlistenArrayEvents(array: T[], listener: ArrayListener): void;\nexport function unlistenArrayEvents(array, listener) {\n const stub = array._chartjs;\n if (!stub) {\n return;\n }\n\n const listeners = stub.listeners;\n const index = listeners.indexOf(listener);\n if (index !== -1) {\n listeners.splice(index, 1);\n }\n\n if (listeners.length > 0) {\n return;\n }\n\n arrayEvents.forEach((key) => {\n delete array[key];\n });\n\n delete array._chartjs;\n}\n\n/**\n * @param items\n */\nexport function _arrayUnique(items: T[]) {\n const set = new Set(items);\n\n if (set.size === items.length) {\n return items;\n }\n\n return Array.from(set);\n}\n","import type {ChartMeta, PointElement} from '../types/index.js';\n\nimport {_limitValue} from './helpers.math.js';\nimport {_lookupByKey} from './helpers.collection.js';\nimport {isNullOrUndef} from './helpers.core.js';\n\nexport function fontString(pixelSize: number, fontStyle: string, fontFamily: string) {\n return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;\n}\n\n/**\n* Request animation polyfill\n*/\nexport const requestAnimFrame = (function() {\n if (typeof window === 'undefined') {\n return function(callback) {\n return callback();\n };\n }\n return window.requestAnimationFrame;\n}());\n\n/**\n * Throttles calling `fn` once per animation frame\n * Latest arguments are used on the actual call\n */\nexport function throttled>(\n fn: (...args: TArgs) => void,\n thisArg: any,\n) {\n let argsToUse = [] as TArgs;\n let ticking = false;\n\n return function(...args: TArgs) {\n // Save the args for use later\n argsToUse = args;\n if (!ticking) {\n ticking = true;\n requestAnimFrame.call(window, () => {\n ticking = false;\n fn.apply(thisArg, argsToUse);\n });\n }\n };\n}\n\n/**\n * Debounces calling `fn` for `delay` ms\n */\nexport function debounce>(fn: (...args: TArgs) => void, delay: number) {\n let timeout;\n return function(...args: TArgs) {\n if (delay) {\n clearTimeout(timeout);\n timeout = setTimeout(fn, delay, args);\n } else {\n fn.apply(this, args);\n }\n return delay;\n };\n}\n\n/**\n * Converts 'start' to 'left', 'end' to 'right' and others to 'center'\n * @private\n */\nexport const _toLeftRightCenter = (align: 'start' | 'end' | 'center') => align === 'start' ? 'left' : align === 'end' ? 'right' : 'center';\n\n/**\n * Returns `start`, `end` or `(start + end) / 2` depending on `align`. Defaults to `center`\n * @private\n */\nexport const _alignStartEnd = (align: 'start' | 'end' | 'center', start: number, end: number) => align === 'start' ? start : align === 'end' ? end : (start + end) / 2;\n\n/**\n * Returns `left`, `right` or `(left + right) / 2` depending on `align`. Defaults to `left`\n * @private\n */\nexport const _textX = (align: 'left' | 'right' | 'center', left: number, right: number, rtl: boolean) => {\n const check = rtl ? 'left' : 'right';\n return align === check ? right : align === 'center' ? (left + right) / 2 : left;\n};\n\n/**\n * Return start and count of visible points.\n * @private\n */\nexport function _getStartAndCountOfVisiblePoints(meta: ChartMeta<'line' | 'scatter'>, points: PointElement[], animationsDisabled: boolean) {\n const pointCount = points.length;\n\n let start = 0;\n let count = pointCount;\n\n if (meta._sorted) {\n const {iScale, vScale, _parsed} = meta;\n const spanGaps = meta.dataset ? meta.dataset.options ? meta.dataset.options.spanGaps : null : null;\n const axis = iScale.axis;\n const {min, max, minDefined, maxDefined} = iScale.getUserBounds();\n\n if (minDefined) {\n start = Math.min(\n // @ts-expect-error Need to type _parsed\n _lookupByKey(_parsed, axis, min).lo,\n // @ts-expect-error Need to fix types on _lookupByKey\n animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min)).lo);\n if (spanGaps) {\n const distanceToDefinedLo = (_parsed\n .slice(0, start + 1)\n .reverse()\n .findIndex(\n point => !isNullOrUndef(point[vScale.axis])));\n start -= Math.max(0, distanceToDefinedLo);\n }\n start = _limitValue(start, 0, pointCount - 1);\n }\n if (maxDefined) {\n let end = Math.max(\n // @ts-expect-error Need to type _parsed\n _lookupByKey(_parsed, iScale.axis, max, true).hi + 1,\n // @ts-expect-error Need to fix types on _lookupByKey\n animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max), true).hi + 1);\n if (spanGaps) {\n const distanceToDefinedHi = (_parsed\n .slice(end - 1)\n .findIndex(\n point => !isNullOrUndef(point[vScale.axis])));\n end += Math.max(0, distanceToDefinedHi);\n }\n count = _limitValue(end, start, pointCount) - start;\n } else {\n count = pointCount - start;\n }\n }\n\n return {start, count};\n}\n\n/**\n * Checks if the scale ranges have changed.\n * @param {object} meta - dataset meta.\n * @returns {boolean}\n * @private\n */\nexport function _scaleRangesChanged(meta) {\n const {xScale, yScale, _scaleRanges} = meta;\n const newRanges = {\n xmin: xScale.min,\n xmax: xScale.max,\n ymin: yScale.min,\n ymax: yScale.max\n };\n if (!_scaleRanges) {\n meta._scaleRanges = newRanges;\n return true;\n }\n const changed = _scaleRanges.xmin !== xScale.min\n\t\t|| _scaleRanges.xmax !== xScale.max\n\t\t|| _scaleRanges.ymin !== yScale.min\n\t\t|| _scaleRanges.ymax !== yScale.max;\n\n Object.assign(_scaleRanges, newRanges);\n return changed;\n}\n","import {PI, TAU, HALF_PI} from './helpers.math.js';\n\nconst atEdge = (t: number) => t === 0 || t === 1;\nconst elasticIn = (t: number, s: number, p: number) => -(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * TAU / p));\nconst elasticOut = (t: number, s: number, p: number) => Math.pow(2, -10 * t) * Math.sin((t - s) * TAU / p) + 1;\n\n/**\n * Easing functions adapted from Robert Penner's easing equations.\n * @namespace Chart.helpers.easing.effects\n * @see http://www.robertpenner.com/easing/\n */\nconst effects = {\n linear: (t: number) => t,\n\n easeInQuad: (t: number) => t * t,\n\n easeOutQuad: (t: number) => -t * (t - 2),\n\n easeInOutQuad: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t\n : -0.5 * ((--t) * (t - 2) - 1),\n\n easeInCubic: (t: number) => t * t * t,\n\n easeOutCubic: (t: number) => (t -= 1) * t * t + 1,\n\n easeInOutCubic: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t * t\n : 0.5 * ((t -= 2) * t * t + 2),\n\n easeInQuart: (t: number) => t * t * t * t,\n\n easeOutQuart: (t: number) => -((t -= 1) * t * t * t - 1),\n\n easeInOutQuart: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t * t * t\n : -0.5 * ((t -= 2) * t * t * t - 2),\n\n easeInQuint: (t: number) => t * t * t * t * t,\n\n easeOutQuint: (t: number) => (t -= 1) * t * t * t * t + 1,\n\n easeInOutQuint: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t * t * t * t\n : 0.5 * ((t -= 2) * t * t * t * t + 2),\n\n easeInSine: (t: number) => -Math.cos(t * HALF_PI) + 1,\n\n easeOutSine: (t: number) => Math.sin(t * HALF_PI),\n\n easeInOutSine: (t: number) => -0.5 * (Math.cos(PI * t) - 1),\n\n easeInExpo: (t: number) => (t === 0) ? 0 : Math.pow(2, 10 * (t - 1)),\n\n easeOutExpo: (t: number) => (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1,\n\n easeInOutExpo: (t: number) => atEdge(t) ? t : t < 0.5\n ? 0.5 * Math.pow(2, 10 * (t * 2 - 1))\n : 0.5 * (-Math.pow(2, -10 * (t * 2 - 1)) + 2),\n\n easeInCirc: (t: number) => (t >= 1) ? t : -(Math.sqrt(1 - t * t) - 1),\n\n easeOutCirc: (t: number) => Math.sqrt(1 - (t -= 1) * t),\n\n easeInOutCirc: (t: number) => ((t /= 0.5) < 1)\n ? -0.5 * (Math.sqrt(1 - t * t) - 1)\n : 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1),\n\n easeInElastic: (t: number) => atEdge(t) ? t : elasticIn(t, 0.075, 0.3),\n\n easeOutElastic: (t: number) => atEdge(t) ? t : elasticOut(t, 0.075, 0.3),\n\n easeInOutElastic(t: number) {\n const s = 0.1125;\n const p = 0.45;\n return atEdge(t) ? t :\n t < 0.5\n ? 0.5 * elasticIn(t * 2, s, p)\n : 0.5 + 0.5 * elasticOut(t * 2 - 1, s, p);\n },\n\n easeInBack(t: number) {\n const s = 1.70158;\n return t * t * ((s + 1) * t - s);\n },\n\n easeOutBack(t: number) {\n const s = 1.70158;\n return (t -= 1) * t * ((s + 1) * t + s) + 1;\n },\n\n easeInOutBack(t: number) {\n let s = 1.70158;\n if ((t /= 0.5) < 1) {\n return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));\n }\n return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);\n },\n\n easeInBounce: (t: number) => 1 - effects.easeOutBounce(1 - t),\n\n easeOutBounce(t: number) {\n const m = 7.5625;\n const d = 2.75;\n if (t < (1 / d)) {\n return m * t * t;\n }\n if (t < (2 / d)) {\n return m * (t -= (1.5 / d)) * t + 0.75;\n }\n if (t < (2.5 / d)) {\n return m * (t -= (2.25 / d)) * t + 0.9375;\n }\n return m * (t -= (2.625 / d)) * t + 0.984375;\n },\n\n easeInOutBounce: (t: number) => (t < 0.5)\n ? effects.easeInBounce(t * 2) * 0.5\n : effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5,\n} as const;\n\nexport type EasingFunction = keyof typeof effects\n\nexport default effects;\n","import {Color} from '@kurkle/color';\n\nexport function isPatternOrGradient(value: unknown): value is CanvasPattern | CanvasGradient {\n if (value && typeof value === 'object') {\n const type = value.toString();\n return type === '[object CanvasPattern]' || type === '[object CanvasGradient]';\n }\n\n return false;\n}\n\nexport function color(value: CanvasGradient): CanvasGradient;\nexport function color(value: CanvasPattern): CanvasPattern;\nexport function color(\n value:\n | string\n | { r: number; g: number; b: number; a: number }\n | [number, number, number]\n | [number, number, number, number]\n): Color;\nexport function color(value) {\n return isPatternOrGradient(value) ? value : new Color(value);\n}\n\nexport function getHoverColor(value: CanvasGradient): CanvasGradient;\nexport function getHoverColor(value: CanvasPattern): CanvasPattern;\nexport function getHoverColor(value: string): string;\nexport function getHoverColor(value) {\n return isPatternOrGradient(value)\n ? value\n : new Color(value).saturate(0.5).darken(0.1).hexString();\n}\n","const numbers = ['x', 'y', 'borderWidth', 'radius', 'tension'];\nconst colors = ['color', 'borderColor', 'backgroundColor'];\n\nexport function applyAnimationsDefaults(defaults) {\n defaults.set('animation', {\n delay: undefined,\n duration: 1000,\n easing: 'easeOutQuart',\n fn: undefined,\n from: undefined,\n loop: undefined,\n to: undefined,\n type: undefined,\n });\n\n defaults.describe('animation', {\n _fallback: false,\n _indexable: false,\n _scriptable: (name) => name !== 'onProgress' && name !== 'onComplete' && name !== 'fn',\n });\n\n defaults.set('animations', {\n colors: {\n type: 'color',\n properties: colors\n },\n numbers: {\n type: 'number',\n properties: numbers\n },\n });\n\n defaults.describe('animations', {\n _fallback: 'animation',\n });\n\n defaults.set('transitions', {\n active: {\n animation: {\n duration: 400\n }\n },\n resize: {\n animation: {\n duration: 0\n }\n },\n show: {\n animations: {\n colors: {\n from: 'transparent'\n },\n visible: {\n type: 'boolean',\n duration: 0 // show immediately\n },\n }\n },\n hide: {\n animations: {\n colors: {\n to: 'transparent'\n },\n visible: {\n type: 'boolean',\n easing: 'linear',\n fn: v => v | 0 // for keeping the dataset visible all the way through the animation\n },\n }\n }\n });\n}\n","export function applyLayoutsDefaults(defaults) {\n defaults.set('layout', {\n autoPadding: true,\n padding: {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0\n }\n });\n}\n","\nconst intlCache = new Map();\n\nfunction getNumberFormat(locale: string, options?: Intl.NumberFormatOptions) {\n options = options || {};\n const cacheKey = locale + JSON.stringify(options);\n let formatter = intlCache.get(cacheKey);\n if (!formatter) {\n formatter = new Intl.NumberFormat(locale, options);\n intlCache.set(cacheKey, formatter);\n }\n return formatter;\n}\n\nexport function formatNumber(num: number, locale: string, options?: Intl.NumberFormatOptions) {\n return getNumberFormat(locale, options).format(num);\n}\n","import {isArray} from '../helpers/helpers.core.js';\nimport {formatNumber} from '../helpers/helpers.intl.js';\nimport {log10} from '../helpers/helpers.math.js';\n\n/**\n * Namespace to hold formatters for different types of ticks\n * @namespace Chart.Ticks.formatters\n */\nconst formatters = {\n /**\n * Formatter for value labels\n * @method Chart.Ticks.formatters.values\n * @param value the value to display\n * @return {string|string[]} the label to display\n */\n values(value) {\n return isArray(value) ? /** @type {string[]} */ (value) : '' + value;\n },\n\n /**\n * Formatter for numeric ticks\n * @method Chart.Ticks.formatters.numeric\n * @param tickValue {number} the value to be formatted\n * @param index {number} the position of the tickValue parameter in the ticks array\n * @param ticks {object[]} the list of ticks being converted\n * @return {string} string representation of the tickValue parameter\n */\n numeric(tickValue, index, ticks) {\n if (tickValue === 0) {\n return '0'; // never show decimal places for 0\n }\n\n const locale = this.chart.options.locale;\n let notation;\n let delta = tickValue; // This is used when there are less than 2 ticks as the tick interval.\n\n if (ticks.length > 1) {\n // all ticks are small or there huge numbers; use scientific notation\n const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value));\n if (maxTick < 1e-4 || maxTick > 1e+15) {\n notation = 'scientific';\n }\n\n delta = calculateDelta(tickValue, ticks);\n }\n\n const logDelta = log10(Math.abs(delta));\n\n // When datasets have values approaching Number.MAX_VALUE, the tick calculations might result in\n // infinity and eventually NaN. Passing NaN for minimumFractionDigits or maximumFractionDigits\n // will make the number formatter throw. So instead we check for isNaN and use a fallback value.\n //\n // toFixed has a max of 20 decimal places\n const numDecimal = isNaN(logDelta) ? 1 : Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0);\n\n const options = {notation, minimumFractionDigits: numDecimal, maximumFractionDigits: numDecimal};\n Object.assign(options, this.options.ticks.format);\n\n return formatNumber(tickValue, locale, options);\n },\n\n\n /**\n * Formatter for logarithmic ticks\n * @method Chart.Ticks.formatters.logarithmic\n * @param tickValue {number} the value to be formatted\n * @param index {number} the position of the tickValue parameter in the ticks array\n * @param ticks {object[]} the list of ticks being converted\n * @return {string} string representation of the tickValue parameter\n */\n logarithmic(tickValue, index, ticks) {\n if (tickValue === 0) {\n return '0';\n }\n const remain = ticks[index].significand || (tickValue / (Math.pow(10, Math.floor(log10(tickValue)))));\n if ([1, 2, 3, 5, 10, 15].includes(remain) || index > 0.8 * ticks.length) {\n return formatters.numeric.call(this, tickValue, index, ticks);\n }\n return '';\n }\n\n};\n\n\nfunction calculateDelta(tickValue, ticks) {\n // Figure out how many digits to show\n // The space between the first two ticks might be smaller than normal spacing\n let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value;\n\n // If we have a number like 2.5 as the delta, figure out how many decimal places we need\n if (Math.abs(delta) >= 1 && tickValue !== Math.floor(tickValue)) {\n // not an integer\n delta = tickValue - Math.floor(tickValue);\n }\n return delta;\n}\n\n/**\n * Namespace to hold static tick generation functions\n * @namespace Chart.Ticks\n */\nexport default {formatters};\n","import Ticks from './core.ticks.js';\n\nexport function applyScaleDefaults(defaults) {\n defaults.set('scale', {\n display: true,\n offset: false,\n reverse: false,\n beginAtZero: false,\n\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 3.0.0\n */\n bounds: 'ticks',\n\n clip: true,\n\n /**\n * Addition grace added to max and reduced from min data value.\n * @since 3.0.0\n */\n grace: 0,\n\n // grid line settings\n grid: {\n display: true,\n lineWidth: 1,\n drawOnChartArea: true,\n drawTicks: true,\n tickLength: 8,\n tickWidth: (_ctx, options) => options.lineWidth,\n tickColor: (_ctx, options) => options.color,\n offset: false,\n },\n\n border: {\n display: true,\n dash: [],\n dashOffset: 0.0,\n width: 1\n },\n\n // scale title\n title: {\n // display property\n display: false,\n\n // actual label\n text: '',\n\n // top/bottom padding\n padding: {\n top: 4,\n bottom: 4\n }\n },\n\n // label settings\n ticks: {\n minRotation: 0,\n maxRotation: 50,\n mirror: false,\n textStrokeWidth: 0,\n textStrokeColor: '',\n padding: 3,\n display: true,\n autoSkip: true,\n autoSkipPadding: 3,\n labelOffset: 0,\n // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.\n callback: Ticks.formatters.values,\n minor: {},\n major: {},\n align: 'center',\n crossAlign: 'near',\n\n showLabelBackdrop: false,\n backdropColor: 'rgba(255, 255, 255, 0.75)',\n backdropPadding: 2,\n }\n });\n\n defaults.route('scale.ticks', 'color', '', 'color');\n defaults.route('scale.grid', 'color', '', 'borderColor');\n defaults.route('scale.border', 'color', '', 'borderColor');\n defaults.route('scale.title', 'color', '', 'color');\n\n defaults.describe('scale', {\n _fallback: false,\n _scriptable: (name) => !name.startsWith('before') && !name.startsWith('after') && name !== 'callback' && name !== 'parser',\n _indexable: (name) => name !== 'borderDash' && name !== 'tickBorderDash' && name !== 'dash',\n });\n\n defaults.describe('scales', {\n _fallback: 'scale',\n });\n\n defaults.describe('scale.ticks', {\n _scriptable: (name) => name !== 'backdropPadding' && name !== 'callback',\n _indexable: (name) => name !== 'backdropPadding',\n });\n}\n","import {getHoverColor} from '../helpers/helpers.color.js';\nimport {isObject, merge, valueOrDefault} from '../helpers/helpers.core.js';\nimport {applyAnimationsDefaults} from './core.animations.defaults.js';\nimport {applyLayoutsDefaults} from './core.layouts.defaults.js';\nimport {applyScaleDefaults} from './core.scale.defaults.js';\n\nexport const overrides = Object.create(null);\nexport const descriptors = Object.create(null);\n\n/**\n * @param {object} node\n * @param {string} key\n * @return {object}\n */\nfunction getScope(node, key) {\n if (!key) {\n return node;\n }\n const keys = key.split('.');\n for (let i = 0, n = keys.length; i < n; ++i) {\n const k = keys[i];\n node = node[k] || (node[k] = Object.create(null));\n }\n return node;\n}\n\nfunction set(root, scope, values) {\n if (typeof scope === 'string') {\n return merge(getScope(root, scope), values);\n }\n return merge(getScope(root, ''), scope);\n}\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 Defaults {\n constructor(_descriptors, _appliers) {\n this.animation = undefined;\n this.backgroundColor = 'rgba(0,0,0,0.1)';\n this.borderColor = 'rgba(0,0,0,0.1)';\n this.color = '#666';\n this.datasets = {};\n this.devicePixelRatio = (context) => context.chart.platform.getDevicePixelRatio();\n this.elements = {};\n this.events = [\n 'mousemove',\n 'mouseout',\n 'click',\n 'touchstart',\n 'touchmove'\n ];\n this.font = {\n family: \"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif\",\n size: 12,\n style: 'normal',\n lineHeight: 1.2,\n weight: null\n };\n this.hover = {};\n this.hoverBackgroundColor = (ctx, options) => getHoverColor(options.backgroundColor);\n this.hoverBorderColor = (ctx, options) => getHoverColor(options.borderColor);\n this.hoverColor = (ctx, options) => getHoverColor(options.color);\n this.indexAxis = 'x';\n this.interaction = {\n mode: 'nearest',\n intersect: true,\n includeInvisible: false\n };\n this.maintainAspectRatio = true;\n this.onHover = null;\n this.onClick = null;\n this.parsing = true;\n this.plugins = {};\n this.responsive = true;\n this.scale = undefined;\n this.scales = {};\n this.showLine = true;\n this.drawActiveElementsOnTop = true;\n\n this.describe(_descriptors);\n this.apply(_appliers);\n }\n\n /**\n\t * @param {string|object} scope\n\t * @param {object} [values]\n\t */\n set(scope, values) {\n return set(this, scope, values);\n }\n\n /**\n\t * @param {string} scope\n\t */\n get(scope) {\n return getScope(this, scope);\n }\n\n /**\n\t * @param {string|object} scope\n\t * @param {object} [values]\n\t */\n describe(scope, values) {\n return set(descriptors, scope, values);\n }\n\n override(scope, values) {\n return set(overrides, scope, values);\n }\n\n /**\n\t * Routes the named defaults to fallback to another scope/name.\n\t * This routing is useful when those target values, like defaults.color, are changed runtime.\n\t * If the values would be copied, the runtime change would not take effect. By routing, the\n\t * fallback is evaluated at each access, so its always up to date.\n\t *\n\t * Example:\n\t *\n\t * \tdefaults.route('elements.arc', 'backgroundColor', '', 'color')\n\t * - reads the backgroundColor from defaults.color when undefined locally\n\t *\n\t * @param {string} scope Scope this route applies to.\n\t * @param {string} name Property name that should be routed to different namespace when not defined here.\n\t * @param {string} targetScope The namespace where those properties should be routed to.\n\t * Empty string ('') is the root of defaults.\n\t * @param {string} targetName The target name in the target scope the property should be routed to.\n\t */\n route(scope, name, targetScope, targetName) {\n const scopeObject = getScope(this, scope);\n const targetScopeObject = getScope(this, targetScope);\n const privateName = '_' + name;\n\n Object.defineProperties(scopeObject, {\n // A private property is defined to hold the actual value, when this property is set in its scope (set in the setter)\n [privateName]: {\n value: scopeObject[name],\n writable: true\n },\n // The actual property is defined as getter/setter so we can do the routing when value is not locally set.\n [name]: {\n enumerable: true,\n get() {\n const local = this[privateName];\n const target = targetScopeObject[targetName];\n if (isObject(local)) {\n return Object.assign({}, target, local);\n }\n return valueOrDefault(local, target);\n },\n set(value) {\n this[privateName] = value;\n }\n }\n });\n }\n\n apply(appliers) {\n appliers.forEach((apply) => apply(this));\n }\n}\n\n// singleton instance\nexport default /* #__PURE__ */ new Defaults({\n _scriptable: (name) => !name.startsWith('on'),\n _indexable: (name) => name !== 'events',\n hover: {\n _fallback: 'interaction'\n },\n interaction: {\n _scriptable: false,\n _indexable: false,\n }\n}, [applyAnimationsDefaults, applyLayoutsDefaults, applyScaleDefaults]);\n","import type {\n Chart,\n Point,\n FontSpec,\n CanvasFontSpec,\n PointStyle,\n RenderTextOpts,\n BackdropOptions\n} from '../types/index.js';\nimport type {\n TRBL,\n SplinePoint,\n RoundedRect,\n TRBLCorners\n} from '../types/geometric.js';\nimport {isArray, isNullOrUndef} from './helpers.core.js';\nimport {PI, TAU, HALF_PI, QUARTER_PI, TWO_THIRDS_PI, RAD_PER_DEG} from './helpers.math.js';\n\n/**\n * Converts the given font object into a CSS font string.\n * @param font - A font object.\n * @return The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font\n * @private\n */\nexport function toFontString(font: FontSpec) {\n if (!font || isNullOrUndef(font.size) || isNullOrUndef(font.family)) {\n return null;\n }\n\n return (font.style ? font.style + ' ' : '')\n\t\t+ (font.weight ? font.weight + ' ' : '')\n\t\t+ font.size + 'px '\n\t\t+ font.family;\n}\n\n/**\n * @private\n */\nexport function _measureText(\n ctx: CanvasRenderingContext2D,\n data: Record,\n gc: string[],\n longest: number,\n string: string\n) {\n let textWidth = data[string];\n if (!textWidth) {\n textWidth = data[string] = ctx.measureText(string).width;\n gc.push(string);\n }\n if (textWidth > longest) {\n longest = textWidth;\n }\n return longest;\n}\n\ntype Thing = string | undefined | null\ntype Things = (Thing | Thing[])[]\n\n/**\n * @private\n */\n// eslint-disable-next-line complexity\nexport function _longestText(\n ctx: CanvasRenderingContext2D,\n font: string,\n arrayOfThings: Things,\n cache?: {data?: Record, garbageCollect?: string[], font?: string}\n) {\n cache = cache || {};\n let data = cache.data = cache.data || {};\n let gc = cache.garbageCollect = cache.garbageCollect || [];\n\n if (cache.font !== font) {\n data = cache.data = {};\n gc = cache.garbageCollect = [];\n cache.font = font;\n }\n\n ctx.save();\n\n ctx.font = font;\n let longest = 0;\n const ilen = arrayOfThings.length;\n let i: number, j: number, jlen: number, thing: Thing | Thing[], nestedThing: Thing | Thing[];\n for (i = 0; i < ilen; i++) {\n thing = arrayOfThings[i];\n\n // Undefined strings and arrays should not be measured\n if (thing !== undefined && thing !== null && !isArray(thing)) {\n longest = _measureText(ctx, data, gc, longest, thing);\n } else if (isArray(thing)) {\n // if it is an array lets measure each element\n // to do maybe simplify this function a bit so we can do this more recursively?\n for (j = 0, jlen = thing.length; j < jlen; j++) {\n nestedThing = thing[j];\n // Undefined strings and arrays should not be measured\n if (nestedThing !== undefined && nestedThing !== null && !isArray(nestedThing)) {\n longest = _measureText(ctx, data, gc, longest, nestedThing);\n }\n }\n }\n }\n\n ctx.restore();\n\n const gcLen = gc.length / 2;\n if (gcLen > arrayOfThings.length) {\n for (i = 0; i < gcLen; i++) {\n delete data[gc[i]];\n }\n gc.splice(0, gcLen);\n }\n return longest;\n}\n\n/**\n * Returns the aligned pixel value to avoid anti-aliasing blur\n * @param chart - The chart instance.\n * @param pixel - A pixel value.\n * @param width - The width of the element.\n * @returns The aligned pixel value.\n * @private\n */\nexport function _alignPixel(chart: Chart, pixel: number, width: number) {\n const devicePixelRatio = chart.currentDevicePixelRatio;\n const halfWidth = width !== 0 ? Math.max(width / 2, 0.5) : 0;\n return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;\n}\n\n/**\n * Clears the entire canvas.\n */\nexport function clearCanvas(canvas?: HTMLCanvasElement, ctx?: CanvasRenderingContext2D) {\n if (!ctx && !canvas) {\n return;\n }\n\n ctx = ctx || canvas.getContext('2d');\n\n ctx.save();\n // canvas.width and canvas.height do not consider the canvas transform,\n // while clearRect does\n ctx.resetTransform();\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.restore();\n}\n\nexport interface DrawPointOptions {\n pointStyle: PointStyle;\n rotation?: number;\n radius: number;\n borderWidth: number;\n}\n\nexport function drawPoint(\n ctx: CanvasRenderingContext2D,\n options: DrawPointOptions,\n x: number,\n y: number\n) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n drawPointLegend(ctx, options, x, y, null);\n}\n\n// eslint-disable-next-line complexity\nexport function drawPointLegend(\n ctx: CanvasRenderingContext2D,\n options: DrawPointOptions,\n x: number,\n y: number,\n w: number\n) {\n let type: string, xOffset: number, yOffset: number, size: number, cornerRadius: number, width: number, xOffsetW: number, yOffsetW: number;\n const style = options.pointStyle;\n const rotation = options.rotation;\n const radius = options.radius;\n let rad = (rotation || 0) * RAD_PER_DEG;\n\n if (style && typeof style === 'object') {\n type = style.toString();\n if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {\n ctx.save();\n ctx.translate(x, y);\n ctx.rotate(rad);\n ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);\n ctx.restore();\n return;\n }\n }\n\n if (isNaN(radius) || radius <= 0) {\n return;\n }\n\n ctx.beginPath();\n\n switch (style) {\n // Default includes circle\n default:\n if (w) {\n ctx.ellipse(x, y, w / 2, radius, 0, 0, TAU);\n } else {\n ctx.arc(x, y, radius, 0, TAU);\n }\n ctx.closePath();\n break;\n case 'triangle':\n width = w ? w / 2 : radius;\n ctx.moveTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);\n rad += TWO_THIRDS_PI;\n ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);\n rad += TWO_THIRDS_PI;\n ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);\n ctx.closePath();\n break;\n case 'rectRounded':\n // NOTE: the rounded rect implementation changed to use `arc` instead of\n // `quadraticCurveTo` since it generates better results when rect is\n // almost a circle. 0.516 (instead of 0.5) produces results with visually\n // closer proportion to the previous impl and it is inscribed in the\n // circle with `radius`. For more details, see the following PRs:\n // https://github.com/chartjs/Chart.js/issues/5597\n // https://github.com/chartjs/Chart.js/issues/5858\n cornerRadius = radius * 0.516;\n size = radius - cornerRadius;\n xOffset = Math.cos(rad + QUARTER_PI) * size;\n xOffsetW = Math.cos(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size);\n yOffset = Math.sin(rad + QUARTER_PI) * size;\n yOffsetW = Math.sin(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size);\n ctx.arc(x - xOffsetW, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);\n ctx.arc(x + yOffsetW, y - xOffset, cornerRadius, rad - HALF_PI, rad);\n ctx.arc(x + xOffsetW, y + yOffset, cornerRadius, rad, rad + HALF_PI);\n ctx.arc(x - yOffsetW, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);\n ctx.closePath();\n break;\n case 'rect':\n if (!rotation) {\n size = Math.SQRT1_2 * radius;\n width = w ? w / 2 : size;\n ctx.rect(x - width, y - size, 2 * width, 2 * size);\n break;\n }\n rad += QUARTER_PI;\n /* falls through */\n case 'rectRot':\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n ctx.closePath();\n break;\n case 'crossRot':\n rad += QUARTER_PI;\n /* falls through */\n case 'cross':\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.moveTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n break;\n case 'star':\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.moveTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n rad += QUARTER_PI;\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.moveTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n break;\n case 'line':\n xOffset = w ? w / 2 : Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n ctx.moveTo(x - xOffset, y - yOffset);\n ctx.lineTo(x + xOffset, y + yOffset);\n break;\n case 'dash':\n ctx.moveTo(x, y);\n ctx.lineTo(x + Math.cos(rad) * (w ? w / 2 : radius), y + Math.sin(rad) * radius);\n break;\n case false:\n ctx.closePath();\n break;\n }\n\n ctx.fill();\n if (options.borderWidth > 0) {\n ctx.stroke();\n }\n}\n\n/**\n * Returns true if the point is inside the rectangle\n * @param point - The point to test\n * @param area - The rectangle\n * @param margin - allowed margin\n * @private\n */\nexport function _isPointInArea(\n point: Point,\n area: TRBL,\n margin?: number\n) {\n margin = margin || 0.5; // margin - default is to match rounded decimals\n\n return !area || (point && point.x > area.left - margin && point.x < area.right + margin &&\n\t\tpoint.y > area.top - margin && point.y < area.bottom + margin);\n}\n\nexport function clipArea(ctx: CanvasRenderingContext2D, area: TRBL) {\n ctx.save();\n ctx.beginPath();\n ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);\n ctx.clip();\n}\n\nexport function unclipArea(ctx: CanvasRenderingContext2D) {\n ctx.restore();\n}\n\n/**\n * @private\n */\nexport function _steppedLineTo(\n ctx: CanvasRenderingContext2D,\n previous: Point,\n target: Point,\n flip?: boolean,\n mode?: string\n) {\n if (!previous) {\n return ctx.lineTo(target.x, target.y);\n }\n if (mode === 'middle') {\n const midpoint = (previous.x + target.x) / 2.0;\n ctx.lineTo(midpoint, previous.y);\n ctx.lineTo(midpoint, target.y);\n } else if (mode === 'after' !== !!flip) {\n ctx.lineTo(previous.x, target.y);\n } else {\n ctx.lineTo(target.x, previous.y);\n }\n ctx.lineTo(target.x, target.y);\n}\n\n/**\n * @private\n */\nexport function _bezierCurveTo(\n ctx: CanvasRenderingContext2D,\n previous: SplinePoint,\n target: SplinePoint,\n flip?: boolean\n) {\n if (!previous) {\n return ctx.lineTo(target.x, target.y);\n }\n ctx.bezierCurveTo(\n flip ? previous.cp1x : previous.cp2x,\n flip ? previous.cp1y : previous.cp2y,\n flip ? target.cp2x : target.cp1x,\n flip ? target.cp2y : target.cp1y,\n target.x,\n target.y);\n}\n\nfunction setRenderOpts(ctx: CanvasRenderingContext2D, opts: RenderTextOpts) {\n if (opts.translation) {\n ctx.translate(opts.translation[0], opts.translation[1]);\n }\n\n if (!isNullOrUndef(opts.rotation)) {\n ctx.rotate(opts.rotation);\n }\n\n if (opts.color) {\n ctx.fillStyle = opts.color;\n }\n\n if (opts.textAlign) {\n ctx.textAlign = opts.textAlign;\n }\n\n if (opts.textBaseline) {\n ctx.textBaseline = opts.textBaseline;\n }\n}\n\nfunction decorateText(\n ctx: CanvasRenderingContext2D,\n x: number,\n y: number,\n line: string,\n opts: RenderTextOpts\n) {\n if (opts.strikethrough || opts.underline) {\n /**\n * Now that IE11 support has been dropped, we can use more\n * of the TextMetrics object. The actual bounding boxes\n * are unflagged in Chrome, Firefox, Edge, and Safari so they\n * can be safely used.\n * See https://developer.mozilla.org/en-US/docs/Web/API/TextMetrics#Browser_compatibility\n */\n const metrics = ctx.measureText(line);\n const left = x - metrics.actualBoundingBoxLeft;\n const right = x + metrics.actualBoundingBoxRight;\n const top = y - metrics.actualBoundingBoxAscent;\n const bottom = y + metrics.actualBoundingBoxDescent;\n const yDecoration = opts.strikethrough ? (top + bottom) / 2 : bottom;\n\n ctx.strokeStyle = ctx.fillStyle;\n ctx.beginPath();\n ctx.lineWidth = opts.decorationWidth || 2;\n ctx.moveTo(left, yDecoration);\n ctx.lineTo(right, yDecoration);\n ctx.stroke();\n }\n}\n\nfunction drawBackdrop(ctx: CanvasRenderingContext2D, opts: BackdropOptions) {\n const oldColor = ctx.fillStyle;\n\n ctx.fillStyle = opts.color as string;\n ctx.fillRect(opts.left, opts.top, opts.width, opts.height);\n ctx.fillStyle = oldColor;\n}\n\n/**\n * Render text onto the canvas\n */\nexport function renderText(\n ctx: CanvasRenderingContext2D,\n text: string | string[],\n x: number,\n y: number,\n font: CanvasFontSpec,\n opts: RenderTextOpts = {}\n) {\n const lines = isArray(text) ? text : [text];\n const stroke = opts.strokeWidth > 0 && opts.strokeColor !== '';\n let i: number, line: string;\n\n ctx.save();\n ctx.font = font.string;\n setRenderOpts(ctx, opts);\n\n for (i = 0; i < lines.length; ++i) {\n line = lines[i];\n\n if (opts.backdrop) {\n drawBackdrop(ctx, opts.backdrop);\n }\n\n if (stroke) {\n if (opts.strokeColor) {\n ctx.strokeStyle = opts.strokeColor;\n }\n\n if (!isNullOrUndef(opts.strokeWidth)) {\n ctx.lineWidth = opts.strokeWidth;\n }\n\n ctx.strokeText(line, x, y, opts.maxWidth);\n }\n\n ctx.fillText(line, x, y, opts.maxWidth);\n decorateText(ctx, x, y, line, opts);\n\n y += Number(font.lineHeight);\n }\n\n ctx.restore();\n}\n\n/**\n * Add a path of a rectangle with rounded corners to the current sub-path\n * @param ctx - Context\n * @param rect - Bounding rect\n */\nexport function addRoundedRectPath(\n ctx: CanvasRenderingContext2D,\n rect: RoundedRect & { radius: TRBLCorners }\n) {\n const {x, y, w, h, radius} = rect;\n\n // top left arc\n ctx.arc(x + radius.topLeft, y + radius.topLeft, radius.topLeft, 1.5 * PI, PI, true);\n\n // line from top left to bottom left\n ctx.lineTo(x, y + h - radius.bottomLeft);\n\n // bottom left arc\n ctx.arc(x + radius.bottomLeft, y + h - radius.bottomLeft, radius.bottomLeft, PI, HALF_PI, true);\n\n // line from bottom left to bottom right\n ctx.lineTo(x + w - radius.bottomRight, y + h);\n\n // bottom right arc\n ctx.arc(x + w - radius.bottomRight, y + h - radius.bottomRight, radius.bottomRight, HALF_PI, 0, true);\n\n // line from bottom right to top right\n ctx.lineTo(x + w, y + radius.topRight);\n\n // top right arc\n ctx.arc(x + w - radius.topRight, y + radius.topRight, radius.topRight, 0, -HALF_PI, true);\n\n // line from top right to top left\n ctx.lineTo(x + radius.topLeft, y);\n}\n","import defaults from '../core/core.defaults.js';\nimport {isArray, isObject, toDimension, valueOrDefault} from './helpers.core.js';\nimport {toFontString} from './helpers.canvas.js';\nimport type {ChartArea, FontSpec, Point} from '../types/index.js';\nimport type {TRBL, TRBLCorners} from '../types/geometric.js';\n\nconst LINE_HEIGHT = /^(normal|(\\d+(?:\\.\\d+)?)(px|em|%)?)$/;\nconst FONT_STYLE = /^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;\n\n/**\n * @alias Chart.helpers.options\n * @namespace\n */\n/**\n * Converts the given line height `value` in pixels for a specific font `size`.\n * @param value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').\n * @param size - The font size (in pixels) used to resolve relative `value`.\n * @returns The effective line height in pixels (size * 1.2 if value is invalid).\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height\n * @since 2.7.0\n */\nexport function toLineHeight(value: number | string, size: number): number {\n const matches = ('' + value).match(LINE_HEIGHT);\n if (!matches || matches[1] === 'normal') {\n return size * 1.2;\n }\n\n value = +matches[2];\n\n switch (matches[3]) {\n case 'px':\n return value;\n case '%':\n value /= 100;\n break;\n default:\n break;\n }\n\n return size * value;\n}\n\nconst numberOrZero = (v: unknown) => +v || 0;\n\n/**\n * @param value\n * @param props\n */\nexport function _readValueToProps(value: number | Record, props: K[]): Record;\nexport function _readValueToProps(value: number | Record, props: Record): Record;\nexport function _readValueToProps(value: number | Record, props: string[] | Record) {\n const ret = {};\n const objProps = isObject(props);\n const keys = objProps ? Object.keys(props) : props;\n const read = isObject(value)\n ? objProps\n ? prop => valueOrDefault(value[prop], value[props[prop]])\n : prop => value[prop]\n : () => value;\n\n for (const prop of keys) {\n ret[prop] = numberOrZero(read(prop));\n }\n return ret;\n}\n\n/**\n * Converts the given value into a TRBL object.\n * @param value - If a number, set the value to all TRBL component,\n * else, if an object, use defined properties and sets undefined ones to 0.\n * x / y are shorthands for same value for left/right and top/bottom.\n * @returns The padding values (top, right, bottom, left)\n * @since 3.0.0\n */\nexport function toTRBL(value: number | TRBL | Point) {\n return _readValueToProps(value, {top: 'y', right: 'x', bottom: 'y', left: 'x'});\n}\n\n/**\n * Converts the given value into a TRBL corners object (similar with css border-radius).\n * @param value - If a number, set the value to all TRBL corner components,\n * else, if an object, use defined properties and sets undefined ones to 0.\n * @returns The TRBL corner values (topLeft, topRight, bottomLeft, bottomRight)\n * @since 3.0.0\n */\nexport function toTRBLCorners(value: number | TRBLCorners) {\n return _readValueToProps(value, ['topLeft', 'topRight', 'bottomLeft', 'bottomRight']);\n}\n\n/**\n * Converts the given value into a padding object with pre-computed width/height.\n * @param value - If a number, set the value to all TRBL component,\n * else, if an object, use defined properties and sets undefined ones to 0.\n * x / y are shorthands for same value for left/right and top/bottom.\n * @returns The padding values (top, right, bottom, left, width, height)\n * @since 2.7.0\n */\nexport function toPadding(value?: number | TRBL): ChartArea {\n const obj = toTRBL(value) as ChartArea;\n\n obj.width = obj.left + obj.right;\n obj.height = obj.top + obj.bottom;\n\n return obj;\n}\n\n/**\n * Parses font options and returns the font object.\n * @param options - A object that contains font options to be parsed.\n * @param fallback - A object that contains fallback font options.\n * @return The font object.\n * @private\n */\n\nexport function toFont(options: Partial, fallback?: Partial) {\n options = options || {};\n fallback = fallback || defaults.font as FontSpec;\n\n let size = valueOrDefault(options.size, fallback.size);\n\n if (typeof size === 'string') {\n size = parseInt(size, 10);\n }\n let style = valueOrDefault(options.style, fallback.style);\n if (style && !('' + style).match(FONT_STYLE)) {\n console.warn('Invalid font style specified: \"' + style + '\"');\n style = undefined;\n }\n\n const font = {\n family: valueOrDefault(options.family, fallback.family),\n lineHeight: toLineHeight(valueOrDefault(options.lineHeight, fallback.lineHeight), size),\n size,\n style,\n weight: valueOrDefault(options.weight, fallback.weight),\n string: ''\n };\n\n font.string = toFontString(font);\n return font;\n}\n\n/**\n * Evaluates the given `inputs` sequentially and returns the first defined value.\n * @param inputs - An array of values, falling back to the last value.\n * @param context - If defined and the current value is a function, the value\n * is called with `context` as first argument and the result becomes the new input.\n * @param index - If defined and the current value is an array, the value\n * at `index` become the new input.\n * @param info - object to return information about resolution in\n * @param info.cacheable - Will be set to `false` if option is not cacheable.\n * @since 2.7.0\n */\nexport function resolve(inputs: Array, context?: object, index?: number, info?: { cacheable: boolean }) {\n let cacheable = true;\n let i: number, ilen: number, value: unknown;\n\n for (i = 0, ilen = inputs.length; i < ilen; ++i) {\n value = inputs[i];\n if (value === undefined) {\n continue;\n }\n if (context !== undefined && typeof value === 'function') {\n value = value(context);\n cacheable = false;\n }\n if (index !== undefined && isArray(value)) {\n value = value[index % value.length];\n cacheable = false;\n }\n if (value !== undefined) {\n if (info && !cacheable) {\n info.cacheable = false;\n }\n return value;\n }\n }\n}\n\n/**\n * @param minmax\n * @param grace\n * @param beginAtZero\n * @private\n */\nexport function _addGrace(minmax: { min: number; max: number; }, grace: number | string, beginAtZero: boolean) {\n const {min, max} = minmax;\n const change = toDimension(grace, (max - min) / 2);\n const keepZero = (value: number, add: number) => beginAtZero && value === 0 ? 0 : value + add;\n return {\n min: keepZero(min, -Math.abs(change)),\n max: keepZero(max, change)\n };\n}\n\n/**\n * Create a context inheriting parentContext\n * @param parentContext\n * @param context\n * @returns\n */\nexport function createContext(parentContext: null, context: T): T;\nexport function createContext(parentContext: P, context: T): P & T;\nexport function createContext(parentContext: object, context: object) {\n return Object.assign(Object.create(parentContext), context);\n}\n","/* eslint-disable @typescript-eslint/no-use-before-define */\nimport type {AnyObject} from '../types/basic.js';\nimport type {ChartMeta} from '../types/index.js';\nimport type {\n ResolverObjectKey,\n ResolverCache,\n ResolverProxy,\n DescriptorDefaults,\n Descriptor,\n ContextCache,\n ContextProxy\n} from './helpers.config.types.js';\nimport {isArray, isFunction, isObject, resolveObjectKey, _capitalize} from './helpers.core.js';\n\nexport * from './helpers.config.types.js';\n\n/**\n * Creates a Proxy for resolving raw values for options.\n * @param scopes - The option scopes to look for values, in resolution order\n * @param prefixes - The prefixes for values, in resolution order.\n * @param rootScopes - The root option scopes\n * @param fallback - Parent scopes fallback\n * @param getTarget - callback for getting the target for changed values\n * @returns Proxy\n * @private\n */\nexport function _createResolver<\n T extends AnyObject[] = AnyObject[],\n R extends AnyObject[] = T\n>(\n scopes: T,\n prefixes = [''],\n rootScopes?: R,\n fallback?: ResolverObjectKey,\n getTarget = () => scopes[0]\n) {\n const finalRootScopes = rootScopes || scopes;\n if (typeof fallback === 'undefined') {\n fallback = _resolve('_fallback', scopes);\n }\n const cache: ResolverCache = {\n [Symbol.toStringTag]: 'Object',\n _cacheable: true,\n _scopes: scopes,\n _rootScopes: finalRootScopes,\n _fallback: fallback,\n _getTarget: getTarget,\n override: (scope: AnyObject) => _createResolver([scope, ...scopes], prefixes, finalRootScopes, fallback),\n };\n return new Proxy(cache, {\n /**\n * A trap for the delete operator.\n */\n deleteProperty(target, prop: string) {\n delete target[prop]; // remove from cache\n delete target._keys; // remove cached keys\n delete scopes[0][prop]; // remove from top level scope\n return true;\n },\n\n /**\n * A trap for getting property values.\n */\n get(target, prop: string) {\n return _cached(target, prop,\n () => _resolveWithPrefixes(prop, prefixes, scopes, target));\n },\n\n /**\n * A trap for Object.getOwnPropertyDescriptor.\n * Also used by Object.hasOwnProperty.\n */\n getOwnPropertyDescriptor(target, prop) {\n return Reflect.getOwnPropertyDescriptor(target._scopes[0], prop);\n },\n\n /**\n * A trap for Object.getPrototypeOf.\n */\n getPrototypeOf() {\n return Reflect.getPrototypeOf(scopes[0]);\n },\n\n /**\n * A trap for the in operator.\n */\n has(target, prop: string) {\n return getKeysFromAllScopes(target).includes(prop);\n },\n\n /**\n * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols.\n */\n ownKeys(target) {\n return getKeysFromAllScopes(target);\n },\n\n /**\n * A trap for setting property values.\n */\n set(target, prop: string, value) {\n const storage = target._storage || (target._storage = getTarget());\n target[prop] = storage[prop] = value; // set to top level scope + cache\n delete target._keys; // remove cached keys\n return true;\n }\n }) as ResolverProxy;\n}\n\n/**\n * Returns an Proxy for resolving option values with context.\n * @param proxy - The Proxy returned by `_createResolver`\n * @param context - Context object for scriptable/indexable options\n * @param subProxy - The proxy provided for scriptable options\n * @param descriptorDefaults - Defaults for descriptors\n * @private\n */\nexport function _attachContext<\n T extends AnyObject[] = AnyObject[],\n R extends AnyObject[] = T\n>(\n proxy: ResolverProxy,\n context: AnyObject,\n subProxy?: ResolverProxy,\n descriptorDefaults?: DescriptorDefaults\n) {\n const cache: ContextCache = {\n _cacheable: false,\n _proxy: proxy,\n _context: context,\n _subProxy: subProxy,\n _stack: new Set(),\n _descriptors: _descriptors(proxy, descriptorDefaults),\n setContext: (ctx: AnyObject) => _attachContext(proxy, ctx, subProxy, descriptorDefaults),\n override: (scope: AnyObject) => _attachContext(proxy.override(scope), context, subProxy, descriptorDefaults)\n };\n return new Proxy(cache, {\n /**\n * A trap for the delete operator.\n */\n deleteProperty(target, prop) {\n delete target[prop]; // remove from cache\n delete proxy[prop]; // remove from proxy\n return true;\n },\n\n /**\n * A trap for getting property values.\n */\n get(target, prop: string, receiver) {\n return _cached(target, prop,\n () => _resolveWithContext(target, prop, receiver));\n },\n\n /**\n * A trap for Object.getOwnPropertyDescriptor.\n * Also used by Object.hasOwnProperty.\n */\n getOwnPropertyDescriptor(target, prop) {\n return target._descriptors.allKeys\n ? Reflect.has(proxy, prop) ? {enumerable: true, configurable: true} : undefined\n : Reflect.getOwnPropertyDescriptor(proxy, prop);\n },\n\n /**\n * A trap for Object.getPrototypeOf.\n */\n getPrototypeOf() {\n return Reflect.getPrototypeOf(proxy);\n },\n\n /**\n * A trap for the in operator.\n */\n has(target, prop) {\n return Reflect.has(proxy, prop);\n },\n\n /**\n * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols.\n */\n ownKeys() {\n return Reflect.ownKeys(proxy);\n },\n\n /**\n * A trap for setting property values.\n */\n set(target, prop, value) {\n proxy[prop] = value; // set to proxy\n delete target[prop]; // remove from cache\n return true;\n }\n }) as ContextProxy;\n}\n\n/**\n * @private\n */\nexport function _descriptors(\n proxy: ResolverCache,\n defaults: DescriptorDefaults = {scriptable: true, indexable: true}\n): Descriptor {\n const {_scriptable = defaults.scriptable, _indexable = defaults.indexable, _allKeys = defaults.allKeys} = proxy;\n return {\n allKeys: _allKeys,\n scriptable: _scriptable,\n indexable: _indexable,\n isScriptable: isFunction(_scriptable) ? _scriptable : () => _scriptable,\n isIndexable: isFunction(_indexable) ? _indexable : () => _indexable\n };\n}\n\nconst readKey = (prefix: string, name: string) => prefix ? prefix + _capitalize(name) : name;\nconst needsSubResolver = (prop: string, value: unknown) => isObject(value) && prop !== 'adapters' &&\n (Object.getPrototypeOf(value) === null || value.constructor === Object);\n\nfunction _cached(\n target: AnyObject,\n prop: string,\n resolve: () => unknown\n) {\n if (Object.prototype.hasOwnProperty.call(target, prop) || prop === 'constructor') {\n return target[prop];\n }\n\n const value = resolve();\n // cache the resolved value\n target[prop] = value;\n return value;\n}\n\nfunction _resolveWithContext(\n target: ContextCache,\n prop: string,\n receiver: AnyObject\n) {\n const {_proxy, _context, _subProxy, _descriptors: descriptors} = target;\n let value = _proxy[prop]; // resolve from proxy\n\n // resolve with context\n if (isFunction(value) && descriptors.isScriptable(prop)) {\n value = _resolveScriptable(prop, value, target, receiver);\n }\n if (isArray(value) && value.length) {\n value = _resolveArray(prop, value, target, descriptors.isIndexable);\n }\n if (needsSubResolver(prop, value)) {\n // if the resolved value is an object, create a sub resolver for it\n value = _attachContext(value, _context, _subProxy && _subProxy[prop], descriptors);\n }\n return value;\n}\n\nfunction _resolveScriptable(\n prop: string,\n getValue: (ctx: AnyObject, sub: AnyObject) => unknown,\n target: ContextCache,\n receiver: AnyObject\n) {\n const {_proxy, _context, _subProxy, _stack} = target;\n if (_stack.has(prop)) {\n throw new Error('Recursion detected: ' + Array.from(_stack).join('->') + '->' + prop);\n }\n _stack.add(prop);\n let value = getValue(_context, _subProxy || receiver);\n _stack.delete(prop);\n if (needsSubResolver(prop, value)) {\n // When scriptable option returns an object, create a resolver on that.\n value = createSubResolver(_proxy._scopes, _proxy, prop, value);\n }\n return value;\n}\n\nfunction _resolveArray(\n prop: string,\n value: unknown[],\n target: ContextCache,\n isIndexable: (key: string) => boolean\n) {\n const {_proxy, _context, _subProxy, _descriptors: descriptors} = target;\n\n if (typeof _context.index !== 'undefined' && isIndexable(prop)) {\n return value[_context.index % value.length];\n } else if (isObject(value[0])) {\n // Array of objects, return array or resolvers\n const arr = value;\n const scopes = _proxy._scopes.filter(s => s !== arr);\n value = [];\n for (const item of arr) {\n const resolver = createSubResolver(scopes, _proxy, prop, item);\n value.push(_attachContext(resolver, _context, _subProxy && _subProxy[prop], descriptors));\n }\n }\n return value;\n}\n\nfunction resolveFallback(\n fallback: ResolverObjectKey | ((prop: ResolverObjectKey, value: unknown) => ResolverObjectKey),\n prop: ResolverObjectKey,\n value: unknown\n) {\n return isFunction(fallback) ? fallback(prop, value) : fallback;\n}\n\nconst getScope = (key: ResolverObjectKey, parent: AnyObject) => key === true ? parent\n : typeof key === 'string' ? resolveObjectKey(parent, key) : undefined;\n\nfunction addScopes(\n set: Set,\n parentScopes: AnyObject[],\n key: ResolverObjectKey,\n parentFallback: ResolverObjectKey,\n value: unknown\n) {\n for (const parent of parentScopes) {\n const scope = getScope(key, parent);\n if (scope) {\n set.add(scope);\n const fallback = resolveFallback(scope._fallback, key, value);\n if (typeof fallback !== 'undefined' && fallback !== key && fallback !== parentFallback) {\n // When we reach the descriptor that defines a new _fallback, return that.\n // The fallback will resume to that new scope.\n return fallback;\n }\n } else if (scope === false && typeof parentFallback !== 'undefined' && key !== parentFallback) {\n // Fallback to `false` results to `false`, when falling back to different key.\n // For example `interaction` from `hover` or `plugins.tooltip` and `animation` from `animations`\n return null;\n }\n }\n return false;\n}\n\nfunction createSubResolver(\n parentScopes: AnyObject[],\n resolver: ResolverCache,\n prop: ResolverObjectKey,\n value: unknown\n) {\n const rootScopes = resolver._rootScopes;\n const fallback = resolveFallback(resolver._fallback, prop, value);\n const allScopes = [...parentScopes, ...rootScopes];\n const set = new Set();\n set.add(value);\n let key = addScopesFromKey(set, allScopes, prop, fallback || prop, value);\n if (key === null) {\n return false;\n }\n if (typeof fallback !== 'undefined' && fallback !== prop) {\n key = addScopesFromKey(set, allScopes, fallback, key, value);\n if (key === null) {\n return false;\n }\n }\n return _createResolver(Array.from(set), [''], rootScopes, fallback,\n () => subGetTarget(resolver, prop as string, value));\n}\n\nfunction addScopesFromKey(\n set: Set,\n allScopes: AnyObject[],\n key: ResolverObjectKey,\n fallback: ResolverObjectKey,\n item: unknown\n) {\n while (key) {\n key = addScopes(set, allScopes, key, fallback, item);\n }\n return key;\n}\n\nfunction subGetTarget(\n resolver: ResolverCache,\n prop: string,\n value: unknown\n) {\n const parent = resolver._getTarget();\n if (!(prop in parent)) {\n parent[prop] = {};\n }\n const target = parent[prop];\n if (isArray(target) && isObject(value)) {\n // For array of objects, the object is used to store updated values\n return value;\n }\n return target || {};\n}\n\nfunction _resolveWithPrefixes(\n prop: string,\n prefixes: string[],\n scopes: AnyObject[],\n proxy: ResolverProxy\n) {\n let value: unknown;\n for (const prefix of prefixes) {\n value = _resolve(readKey(prefix, prop), scopes);\n if (typeof value !== 'undefined') {\n return needsSubResolver(prop, value)\n ? createSubResolver(scopes, proxy, prop, value)\n : value;\n }\n }\n}\n\nfunction _resolve(key: string, scopes: AnyObject[]) {\n for (const scope of scopes) {\n if (!scope) {\n continue;\n }\n const value = scope[key];\n if (typeof value !== 'undefined') {\n return value;\n }\n }\n}\n\nfunction getKeysFromAllScopes(target: ResolverCache) {\n let keys = target._keys;\n if (!keys) {\n keys = target._keys = resolveKeysFromAllScopes(target._scopes);\n }\n return keys;\n}\n\nfunction resolveKeysFromAllScopes(scopes: AnyObject[]) {\n const set = new Set();\n for (const scope of scopes) {\n for (const key of Object.keys(scope).filter(k => !k.startsWith('_'))) {\n set.add(key);\n }\n }\n return Array.from(set);\n}\n\nexport function _parseObjectDataRadialScale(\n meta: ChartMeta<'line' | 'scatter'>,\n data: AnyObject[],\n start: number,\n count: number\n) {\n const {iScale} = meta;\n const {key = 'r'} = this._parsing;\n const parsed = new Array<{r: unknown}>(count);\n let i: number, ilen: number, index: number, item: AnyObject;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n item = data[index];\n parsed[i] = {\n r: iScale.parse(resolveObjectKey(item, key), index)\n };\n }\n return parsed;\n}\n","import {almostEquals, distanceBetweenPoints, sign} from './helpers.math.js';\nimport {_isPointInArea} from './helpers.canvas.js';\nimport type {ChartArea} from '../types/index.js';\nimport type {SplinePoint} from '../types/geometric.js';\n\nconst EPSILON = Number.EPSILON || 1e-14;\n\ntype OptionalSplinePoint = SplinePoint | false\nconst getPoint = (points: SplinePoint[], i: number): OptionalSplinePoint => i < points.length && !points[i].skip && points[i];\nconst getValueAxis = (indexAxis: 'x' | 'y') => indexAxis === 'x' ? 'y' : 'x';\n\nexport function splineCurve(\n firstPoint: SplinePoint,\n middlePoint: SplinePoint,\n afterPoint: SplinePoint,\n t: number\n): {\n previous: SplinePoint\n next: SplinePoint\n } {\n // Props to Rob Spencer at scaled innovation for his post on splining between points\n // http://scaledinnovation.com/analytics/splines/aboutSplines.html\n\n // This function must also respect \"skipped\" points\n\n const previous = firstPoint.skip ? middlePoint : firstPoint;\n const current = middlePoint;\n const next = afterPoint.skip ? middlePoint : afterPoint;\n const d01 = distanceBetweenPoints(current, previous);\n const d12 = distanceBetweenPoints(next, current);\n\n let s01 = d01 / (d01 + d12);\n let s12 = d12 / (d01 + d12);\n\n // If all points are the same, s01 & s02 will be inf\n s01 = isNaN(s01) ? 0 : s01;\n s12 = isNaN(s12) ? 0 : s12;\n\n const fa = t * s01; // scaling factor for triangle Ta\n const fb = t * s12;\n\n return {\n previous: {\n x: current.x - fa * (next.x - previous.x),\n y: current.y - fa * (next.y - previous.y)\n },\n next: {\n x: current.x + fb * (next.x - previous.x),\n y: current.y + fb * (next.y - previous.y)\n }\n };\n}\n\n/**\n * Adjust tangents to ensure monotonic properties\n */\nfunction monotoneAdjust(points: SplinePoint[], deltaK: number[], mK: number[]) {\n const pointsLen = points.length;\n\n let alphaK: number, betaK: number, tauK: number, squaredMagnitude: number, pointCurrent: OptionalSplinePoint;\n let pointAfter = getPoint(points, 0);\n for (let i = 0; i < pointsLen - 1; ++i) {\n pointCurrent = pointAfter;\n pointAfter = getPoint(points, i + 1);\n if (!pointCurrent || !pointAfter) {\n continue;\n }\n\n if (almostEquals(deltaK[i], 0, EPSILON)) {\n mK[i] = mK[i + 1] = 0;\n continue;\n }\n\n alphaK = mK[i] / deltaK[i];\n betaK = mK[i + 1] / deltaK[i];\n squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);\n if (squaredMagnitude <= 9) {\n continue;\n }\n\n tauK = 3 / Math.sqrt(squaredMagnitude);\n mK[i] = alphaK * tauK * deltaK[i];\n mK[i + 1] = betaK * tauK * deltaK[i];\n }\n}\n\nfunction monotoneCompute(points: SplinePoint[], mK: number[], indexAxis: 'x' | 'y' = 'x') {\n const valueAxis = getValueAxis(indexAxis);\n const pointsLen = points.length;\n let delta: number, pointBefore: OptionalSplinePoint, pointCurrent: OptionalSplinePoint;\n let pointAfter = getPoint(points, 0);\n\n for (let i = 0; i < pointsLen; ++i) {\n pointBefore = pointCurrent;\n pointCurrent = pointAfter;\n pointAfter = getPoint(points, i + 1);\n if (!pointCurrent) {\n continue;\n }\n\n const iPixel = pointCurrent[indexAxis];\n const vPixel = pointCurrent[valueAxis];\n if (pointBefore) {\n delta = (iPixel - pointBefore[indexAxis]) / 3;\n pointCurrent[`cp1${indexAxis}`] = iPixel - delta;\n pointCurrent[`cp1${valueAxis}`] = vPixel - delta * mK[i];\n }\n if (pointAfter) {\n delta = (pointAfter[indexAxis] - iPixel) / 3;\n pointCurrent[`cp2${indexAxis}`] = iPixel + delta;\n pointCurrent[`cp2${valueAxis}`] = vPixel + delta * mK[i];\n }\n }\n}\n\n/**\n * This function calculates Bézier control points in a similar way than |splineCurve|,\n * but preserves monotonicity of the provided data and ensures no local extremums are added\n * between the dataset discrete points due to the interpolation.\n * See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation\n */\nexport function splineCurveMonotone(points: SplinePoint[], indexAxis: 'x' | 'y' = 'x') {\n const valueAxis = getValueAxis(indexAxis);\n const pointsLen = points.length;\n const deltaK: number[] = Array(pointsLen).fill(0);\n const mK: number[] = Array(pointsLen);\n\n // Calculate slopes (deltaK) and initialize tangents (mK)\n let i, pointBefore: OptionalSplinePoint, pointCurrent: OptionalSplinePoint;\n let pointAfter = getPoint(points, 0);\n\n for (i = 0; i < pointsLen; ++i) {\n pointBefore = pointCurrent;\n pointCurrent = pointAfter;\n pointAfter = getPoint(points, i + 1);\n if (!pointCurrent) {\n continue;\n }\n\n if (pointAfter) {\n const slopeDelta = pointAfter[indexAxis] - pointCurrent[indexAxis];\n\n // In the case of two points that appear at the same x pixel, slopeDeltaX is 0\n deltaK[i] = slopeDelta !== 0 ? (pointAfter[valueAxis] - pointCurrent[valueAxis]) / slopeDelta : 0;\n }\n mK[i] = !pointBefore ? deltaK[i]\n : !pointAfter ? deltaK[i - 1]\n : (sign(deltaK[i - 1]) !== sign(deltaK[i])) ? 0\n : (deltaK[i - 1] + deltaK[i]) / 2;\n }\n\n monotoneAdjust(points, deltaK, mK);\n\n monotoneCompute(points, mK, indexAxis);\n}\n\nfunction capControlPoint(pt: number, min: number, max: number) {\n return Math.max(Math.min(pt, max), min);\n}\n\nfunction capBezierPoints(points: SplinePoint[], area: ChartArea) {\n let i, ilen, point, inArea, inAreaPrev;\n let inAreaNext = _isPointInArea(points[0], area);\n for (i = 0, ilen = points.length; i < ilen; ++i) {\n inAreaPrev = inArea;\n inArea = inAreaNext;\n inAreaNext = i < ilen - 1 && _isPointInArea(points[i + 1], area);\n if (!inArea) {\n continue;\n }\n point = points[i];\n if (inAreaPrev) {\n point.cp1x = capControlPoint(point.cp1x, area.left, area.right);\n point.cp1y = capControlPoint(point.cp1y, area.top, area.bottom);\n }\n if (inAreaNext) {\n point.cp2x = capControlPoint(point.cp2x, area.left, area.right);\n point.cp2y = capControlPoint(point.cp2y, area.top, area.bottom);\n }\n }\n}\n\n/**\n * @private\n */\nexport function _updateBezierControlPoints(\n points: SplinePoint[],\n options,\n area: ChartArea,\n loop: boolean,\n indexAxis: 'x' | 'y'\n) {\n let i: number, ilen: number, point: SplinePoint, controlPoints: ReturnType;\n\n // Only consider points that are drawn in case the spanGaps option is used\n if (options.spanGaps) {\n points = points.filter((pt) => !pt.skip);\n }\n\n if (options.cubicInterpolationMode === 'monotone') {\n splineCurveMonotone(points, indexAxis);\n } else {\n let prev = loop ? points[points.length - 1] : points[0];\n for (i = 0, ilen = points.length; i < ilen; ++i) {\n point = points[i];\n controlPoints = splineCurve(\n prev,\n point,\n points[Math.min(i + 1, ilen - (loop ? 0 : 1)) % ilen],\n options.tension\n );\n point.cp1x = controlPoints.previous.x;\n point.cp1y = controlPoints.previous.y;\n point.cp2x = controlPoints.next.x;\n point.cp2y = controlPoints.next.y;\n prev = point;\n }\n }\n\n if (options.capBezierPoints) {\n capBezierPoints(points, area);\n }\n}\n","import type {ChartArea, Scale} from '../types/index.js';\nimport type PrivateChart from '../core/core.controller.js';\nimport type {Chart, ChartEvent} from '../types.js';\nimport {INFINITY} from './helpers.math.js';\n\n/**\n * @private\n */\nexport function _isDomSupported(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\n/**\n * @private\n */\nexport function _getParentNode(domNode: HTMLCanvasElement): HTMLCanvasElement {\n let parent = domNode.parentNode;\n if (parent && parent.toString() === '[object ShadowRoot]') {\n parent = (parent as ShadowRoot).host;\n }\n return parent as HTMLCanvasElement;\n}\n\n/**\n * convert max-width/max-height values that may be percentages into a number\n * @private\n */\n\nfunction parseMaxStyle(styleValue: string | number, node: HTMLElement, parentProperty: string) {\n let valueInPixels: number;\n if (typeof styleValue === 'string') {\n valueInPixels = parseInt(styleValue, 10);\n\n if (styleValue.indexOf('%') !== -1) {\n // percentage * size in dimension\n valueInPixels = (valueInPixels / 100) * node.parentNode[parentProperty];\n }\n } else {\n valueInPixels = styleValue;\n }\n\n return valueInPixels;\n}\n\nconst getComputedStyle = (element: HTMLElement): CSSStyleDeclaration =>\n element.ownerDocument.defaultView.getComputedStyle(element, null);\n\nexport function getStyle(el: HTMLElement, property: string): string {\n return getComputedStyle(el).getPropertyValue(property);\n}\n\nconst positions = ['top', 'right', 'bottom', 'left'];\nfunction getPositionedStyle(styles: CSSStyleDeclaration, style: string, suffix?: string): ChartArea {\n const result = {} as ChartArea;\n suffix = suffix ? '-' + suffix : '';\n for (let i = 0; i < 4; i++) {\n const pos = positions[i];\n result[pos] = parseFloat(styles[style + '-' + pos + suffix]) || 0;\n }\n result.width = result.left + result.right;\n result.height = result.top + result.bottom;\n return result;\n}\n\nconst useOffsetPos = (x: number, y: number, target: HTMLElement | EventTarget) =>\n (x > 0 || y > 0) && (!target || !(target as HTMLElement).shadowRoot);\n\n/**\n * @param e\n * @param canvas\n * @returns Canvas position\n */\nfunction getCanvasPosition(\n e: Event | TouchEvent | MouseEvent,\n canvas: HTMLCanvasElement\n): {\n x: number;\n y: number;\n box: boolean;\n } {\n const touches = (e as TouchEvent).touches;\n const source = (touches && touches.length ? touches[0] : e) as MouseEvent;\n const {offsetX, offsetY} = source as MouseEvent;\n let box = false;\n let x, y;\n if (useOffsetPos(offsetX, offsetY, e.target)) {\n x = offsetX;\n y = offsetY;\n } else {\n const rect = canvas.getBoundingClientRect();\n x = source.clientX - rect.left;\n y = source.clientY - rect.top;\n box = true;\n }\n return {x, y, box};\n}\n\n/**\n * Gets an event's x, y coordinates, relative to the chart area\n * @param event\n * @param chart\n * @returns x and y coordinates of the event\n */\n\nexport function getRelativePosition(\n event: Event | ChartEvent | TouchEvent | MouseEvent,\n chart: Chart | PrivateChart\n): { x: number; y: number } {\n if ('native' in event) {\n return event;\n }\n\n const {canvas, currentDevicePixelRatio} = chart;\n const style = getComputedStyle(canvas);\n const borderBox = style.boxSizing === 'border-box';\n const paddings = getPositionedStyle(style, 'padding');\n const borders = getPositionedStyle(style, 'border', 'width');\n const {x, y, box} = getCanvasPosition(event, canvas);\n const xOffset = paddings.left + (box && borders.left);\n const yOffset = paddings.top + (box && borders.top);\n\n let {width, height} = chart;\n if (borderBox) {\n width -= paddings.width + borders.width;\n height -= paddings.height + borders.height;\n }\n return {\n x: Math.round((x - xOffset) / width * canvas.width / currentDevicePixelRatio),\n y: Math.round((y - yOffset) / height * canvas.height / currentDevicePixelRatio)\n };\n}\n\nfunction getContainerSize(canvas: HTMLCanvasElement, width: number, height: number): Partial {\n let maxWidth: number, maxHeight: number;\n\n if (width === undefined || height === undefined) {\n const container = canvas && _getParentNode(canvas);\n if (!container) {\n width = canvas.clientWidth;\n height = canvas.clientHeight;\n } else {\n const rect = container.getBoundingClientRect(); // this is the border box of the container\n const containerStyle = getComputedStyle(container);\n const containerBorder = getPositionedStyle(containerStyle, 'border', 'width');\n const containerPadding = getPositionedStyle(containerStyle, 'padding');\n width = rect.width - containerPadding.width - containerBorder.width;\n height = rect.height - containerPadding.height - containerBorder.height;\n maxWidth = parseMaxStyle(containerStyle.maxWidth, container, 'clientWidth');\n maxHeight = parseMaxStyle(containerStyle.maxHeight, container, 'clientHeight');\n }\n }\n return {\n width,\n height,\n maxWidth: maxWidth || INFINITY,\n maxHeight: maxHeight || INFINITY\n };\n}\n\nconst round1 = (v: number) => Math.round(v * 10) / 10;\n\n// eslint-disable-next-line complexity\nexport function getMaximumSize(\n canvas: HTMLCanvasElement,\n bbWidth?: number,\n bbHeight?: number,\n aspectRatio?: number\n): { width: number; height: number } {\n const style = getComputedStyle(canvas);\n const margins = getPositionedStyle(style, 'margin');\n const maxWidth = parseMaxStyle(style.maxWidth, canvas, 'clientWidth') || INFINITY;\n const maxHeight = parseMaxStyle(style.maxHeight, canvas, 'clientHeight') || INFINITY;\n const containerSize = getContainerSize(canvas, bbWidth, bbHeight);\n let {width, height} = containerSize;\n\n if (style.boxSizing === 'content-box') {\n const borders = getPositionedStyle(style, 'border', 'width');\n const paddings = getPositionedStyle(style, 'padding');\n width -= paddings.width + borders.width;\n height -= paddings.height + borders.height;\n }\n width = Math.max(0, width - margins.width);\n height = Math.max(0, aspectRatio ? width / aspectRatio : height - margins.height);\n width = round1(Math.min(width, maxWidth, containerSize.maxWidth));\n height = round1(Math.min(height, maxHeight, containerSize.maxHeight));\n if (width && !height) {\n // https://github.com/chartjs/Chart.js/issues/4659\n // If the canvas has width, but no height, default to aspectRatio of 2 (canvas default)\n height = round1(width / 2);\n }\n\n const maintainHeight = bbWidth !== undefined || bbHeight !== undefined;\n\n if (maintainHeight && aspectRatio && containerSize.height && height > containerSize.height) {\n height = containerSize.height;\n width = round1(Math.floor(height * aspectRatio));\n }\n\n return {width, height};\n}\n\n/**\n * @param chart\n * @param forceRatio\n * @param forceStyle\n * @returns True if the canvas context size or transformation has changed.\n */\nexport function retinaScale(\n chart: Chart | PrivateChart,\n forceRatio: number,\n forceStyle?: boolean\n): boolean | void {\n const pixelRatio = forceRatio || 1;\n const deviceHeight = Math.floor(chart.height * pixelRatio);\n const deviceWidth = Math.floor(chart.width * pixelRatio);\n\n (chart as PrivateChart).height = Math.floor(chart.height);\n (chart as PrivateChart).width = Math.floor(chart.width);\n\n const canvas = chart.canvas;\n\n // If no style has been set on the canvas, the render size is used as display size,\n // making the chart visually bigger, so let's enforce it to the \"correct\" values.\n // See https://github.com/chartjs/Chart.js/issues/3575\n if (canvas.style && (forceStyle || (!canvas.style.height && !canvas.style.width))) {\n canvas.style.height = `${chart.height}px`;\n canvas.style.width = `${chart.width}px`;\n }\n\n if (chart.currentDevicePixelRatio !== pixelRatio\n || canvas.height !== deviceHeight\n || canvas.width !== deviceWidth) {\n (chart as PrivateChart).currentDevicePixelRatio = pixelRatio;\n canvas.height = deviceHeight;\n canvas.width = deviceWidth;\n chart.ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);\n return true;\n }\n return false;\n}\n\n/**\n * Detects support for options object argument in addEventListener.\n * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support\n * @private\n */\nexport const supportsEventListenerOptions = (function() {\n let passiveSupported = false;\n try {\n const options = {\n get passive() { // This function will be called when the browser attempts to access the passive property.\n passiveSupported = true;\n return false;\n }\n } as EventListenerOptions;\n\n if (_isDomSupported()) {\n window.addEventListener('test', null, options);\n window.removeEventListener('test', null, options);\n }\n } catch (e) {\n // continue regardless of error\n }\n return passiveSupported;\n}());\n\n/**\n * The \"used\" size is the final value of a dimension property after all calculations have\n * been performed. This method uses the computed style of `element` but returns undefined\n * if the computed style is not expressed in pixels. That can happen in some cases where\n * `element` has a size relative to its parent and this last one is not yet displayed,\n * for example because of `display: none` on a parent node.\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value\n * @returns Size in pixels or undefined if unknown.\n */\n\nexport function readUsedSize(\n element: HTMLElement,\n property: 'width' | 'height'\n): number | undefined {\n const value = getStyle(element, property);\n const matches = value && value.match(/^(\\d+)(\\.\\d+)?px$/);\n return matches ? +matches[1] : undefined;\n}\n","import type {Point, SplinePoint} from '../types/geometric.js';\n\n/**\n * @private\n */\nexport function _pointInLine(p1: Point, p2: Point, t: number, mode?) { // eslint-disable-line @typescript-eslint/no-unused-vars\n return {\n x: p1.x + t * (p2.x - p1.x),\n y: p1.y + t * (p2.y - p1.y)\n };\n}\n\n/**\n * @private\n */\nexport function _steppedInterpolation(\n p1: Point,\n p2: Point,\n t: number, mode: 'middle' | 'after' | unknown\n) {\n return {\n x: p1.x + t * (p2.x - p1.x),\n y: mode === 'middle' ? t < 0.5 ? p1.y : p2.y\n : mode === 'after' ? t < 1 ? p1.y : p2.y\n : t > 0 ? p2.y : p1.y\n };\n}\n\n/**\n * @private\n */\nexport function _bezierInterpolation(p1: SplinePoint, p2: SplinePoint, t: number, mode?) { // eslint-disable-line @typescript-eslint/no-unused-vars\n const cp1 = {x: p1.cp2x, y: p1.cp2y};\n const cp2 = {x: p2.cp1x, y: p2.cp1y};\n const a = _pointInLine(p1, cp1, t);\n const b = _pointInLine(cp1, cp2, t);\n const c = _pointInLine(cp2, p2, t);\n const d = _pointInLine(a, b, t);\n const e = _pointInLine(b, c, t);\n return _pointInLine(d, e, t);\n}\n","export interface RTLAdapter {\n x(x: number): number;\n setWidth(w: number): void;\n textAlign(align: 'center' | 'left' | 'right'): 'center' | 'left' | 'right';\n xPlus(x: number, value: number): number;\n leftForLtr(x: number, itemWidth: number): number;\n}\n\nconst getRightToLeftAdapter = function(rectX: number, width: number): RTLAdapter {\n return {\n x(x) {\n return rectX + rectX + width - x;\n },\n setWidth(w) {\n width = w;\n },\n textAlign(align) {\n if (align === 'center') {\n return align;\n }\n return align === 'right' ? 'left' : 'right';\n },\n xPlus(x, value) {\n return x - value;\n },\n leftForLtr(x, itemWidth) {\n return x - itemWidth;\n },\n };\n};\n\nconst getLeftToRightAdapter = function(): RTLAdapter {\n return {\n x(x) {\n return x;\n },\n setWidth(w) { // eslint-disable-line no-unused-vars\n },\n textAlign(align) {\n return align;\n },\n xPlus(x, value) {\n return x + value;\n },\n leftForLtr(x, _itemWidth) { // eslint-disable-line @typescript-eslint/no-unused-vars\n return x;\n },\n };\n};\n\nexport function getRtlAdapter(rtl: boolean, rectX: number, width: number) {\n return rtl ? getRightToLeftAdapter(rectX, width) : getLeftToRightAdapter();\n}\n\nexport function overrideTextDirection(ctx: CanvasRenderingContext2D, direction: 'ltr' | 'rtl') {\n let style: CSSStyleDeclaration, original: [string, string];\n if (direction === 'ltr' || direction === 'rtl') {\n style = ctx.canvas.style;\n original = [\n style.getPropertyValue('direction'),\n style.getPropertyPriority('direction'),\n ];\n\n style.setProperty('direction', direction, 'important');\n (ctx as { prevTextDirection?: [string, string] }).prevTextDirection = original;\n }\n}\n\nexport function restoreTextDirection(ctx: CanvasRenderingContext2D, original?: [string, string]) {\n if (original !== undefined) {\n delete (ctx as { prevTextDirection?: [string, string] }).prevTextDirection;\n ctx.canvas.style.setProperty('direction', original[0], original[1]);\n }\n}\n","import {_angleBetween, _angleDiff, _isBetween, _normalizeAngle} from './helpers.math.js';\nimport {createContext} from './helpers.options.js';\nimport {isPatternOrGradient} from './helpers.color.js';\n\n/**\n * @typedef { import('../elements/element.line.js').default } LineElement\n * @typedef { import('../elements/element.point.js').default } PointElement\n * @typedef {{start: number, end: number, loop: boolean, style?: any}} Segment\n */\n\nfunction propertyFn(property) {\n if (property === 'angle') {\n return {\n between: _angleBetween,\n compare: _angleDiff,\n normalize: _normalizeAngle,\n };\n }\n return {\n between: _isBetween,\n compare: (a, b) => a - b,\n normalize: x => x\n };\n}\n\nfunction normalizeSegment({start, end, count, loop, style}) {\n return {\n start: start % count,\n end: end % count,\n loop: loop && (end - start + 1) % count === 0,\n style\n };\n}\n\nfunction getSegment(segment, points, bounds) {\n const {property, start: startBound, end: endBound} = bounds;\n const {between, normalize} = propertyFn(property);\n const count = points.length;\n // eslint-disable-next-line prefer-const\n let {start, end, loop} = segment;\n let i, ilen;\n\n if (loop) {\n start += count;\n end += count;\n for (i = 0, ilen = count; i < ilen; ++i) {\n if (!between(normalize(points[start % count][property]), startBound, endBound)) {\n break;\n }\n start--;\n end--;\n }\n start %= count;\n end %= count;\n }\n\n if (end < start) {\n end += count;\n }\n return {start, end, loop, style: segment.style};\n}\n\n/**\n * Returns the sub-segment(s) of a line segment that fall in the given bounds\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} [segment.style] - segment style\n * @param {PointElement[]} points - the points that this segment refers to\n * @param {object} [bounds]\n * @param {string} bounds.property - the property of a `PointElement` we are bounding. `x`, `y` or `angle`.\n * @param {number} bounds.start - start value of the property\n * @param {number} bounds.end - end value of the property\n * @private\n **/\nexport function _boundSegment(segment, points, bounds) {\n if (!bounds) {\n return [segment];\n }\n\n const {property, start: startBound, end: endBound} = bounds;\n const count = points.length;\n const {compare, between, normalize} = propertyFn(property);\n const {start, end, loop, style} = getSegment(segment, points, bounds);\n\n const result = [];\n let inside = false;\n let subStart = null;\n let value, point, prevValue;\n\n const startIsBefore = () => between(startBound, prevValue, value) && compare(startBound, prevValue) !== 0;\n const endIsBefore = () => compare(endBound, value) === 0 || between(endBound, prevValue, value);\n const shouldStart = () => inside || startIsBefore();\n const shouldStop = () => !inside || endIsBefore();\n\n for (let i = start, prev = start; i <= end; ++i) {\n point = points[i % count];\n\n if (point.skip) {\n continue;\n }\n\n value = normalize(point[property]);\n\n if (value === prevValue) {\n continue;\n }\n\n inside = between(value, startBound, endBound);\n\n if (subStart === null && shouldStart()) {\n subStart = compare(value, startBound) === 0 ? i : prev;\n }\n\n if (subStart !== null && shouldStop()) {\n result.push(normalizeSegment({start: subStart, end: i, loop, count, style}));\n subStart = null;\n }\n prev = i;\n prevValue = value;\n }\n\n if (subStart !== null) {\n result.push(normalizeSegment({start: subStart, end, loop, count, style}));\n }\n\n return result;\n}\n\n\n/**\n * Returns the segments of the line that are inside given bounds\n * @param {LineElement} line\n * @param {object} [bounds]\n * @param {string} bounds.property - the property we are bounding with. `x`, `y` or `angle`.\n * @param {number} bounds.start - start value of the `property`\n * @param {number} bounds.end - end value of the `property`\n * @private\n */\nexport function _boundSegments(line, bounds) {\n const result = [];\n const segments = line.segments;\n\n for (let i = 0; i < segments.length; i++) {\n const sub = _boundSegment(segments[i], line.points, bounds);\n if (sub.length) {\n result.push(...sub);\n }\n }\n return result;\n}\n\n/**\n * Find start and end index of a line.\n */\nfunction findStartAndEnd(points, count, loop, spanGaps) {\n let start = 0;\n let end = count - 1;\n\n if (loop && !spanGaps) {\n // loop and not spanning gaps, first find a gap to start from\n while (start < count && !points[start].skip) {\n start++;\n }\n }\n\n // find first non skipped point (after the first gap possibly)\n while (start < count && points[start].skip) {\n start++;\n }\n\n // if we looped to count, start needs to be 0\n start %= count;\n\n if (loop) {\n // loop will go past count, if start > 0\n end += start;\n }\n\n while (end > start && points[end % count].skip) {\n end--;\n }\n\n // end could be more than count, normalize\n end %= count;\n\n return {start, end};\n}\n\n/**\n * Compute solid segments from Points, when spanGaps === false\n * @param {PointElement[]} points - the points\n * @param {number} start - start index\n * @param {number} max - max index (can go past count on a loop)\n * @param {boolean} loop - boolean indicating that this would be a loop if no gaps are found\n */\nfunction solidSegments(points, start, max, loop) {\n const count = points.length;\n const result = [];\n let last = start;\n let prev = points[start];\n let end;\n\n for (end = start + 1; end <= max; ++end) {\n const cur = points[end % count];\n if (cur.skip || cur.stop) {\n if (!prev.skip) {\n loop = false;\n result.push({start: start % count, end: (end - 1) % count, loop});\n // @ts-ignore\n start = last = cur.stop ? end : null;\n }\n } else {\n last = end;\n if (prev.skip) {\n start = end;\n }\n }\n prev = cur;\n }\n\n if (last !== null) {\n result.push({start: start % count, end: last % count, loop});\n }\n\n return result;\n}\n\n/**\n * Compute the continuous segments that define the whole line\n * There can be skipped points within a segment, if spanGaps is true.\n * @param {LineElement} line\n * @param {object} [segmentOptions]\n * @return {Segment[]}\n * @private\n */\nexport function _computeSegments(line, segmentOptions) {\n const points = line.points;\n const spanGaps = line.options.spanGaps;\n const count = points.length;\n\n if (!count) {\n return [];\n }\n\n const loop = !!line._loop;\n const {start, end} = findStartAndEnd(points, count, loop, spanGaps);\n\n if (spanGaps === true) {\n return splitByStyles(line, [{start, end, loop}], points, segmentOptions);\n }\n\n const max = end < start ? end + count : end;\n const completeLoop = !!line._fullLoop && start === 0 && end === count - 1;\n return splitByStyles(line, solidSegments(points, start, max, completeLoop), points, segmentOptions);\n}\n\n/**\n * @param {Segment[]} segments\n * @param {PointElement[]} points\n * @param {object} [segmentOptions]\n * @return {Segment[]}\n */\nfunction splitByStyles(line, segments, points, segmentOptions) {\n if (!segmentOptions || !segmentOptions.setContext || !points) {\n return segments;\n }\n return doSplitByStyles(line, segments, points, segmentOptions);\n}\n\n/**\n * @param {LineElement} line\n * @param {Segment[]} segments\n * @param {PointElement[]} points\n * @param {object} [segmentOptions]\n * @return {Segment[]}\n */\nfunction doSplitByStyles(line, segments, points, segmentOptions) {\n const chartContext = line._chart.getContext();\n const baseStyle = readStyle(line.options);\n const {_datasetIndex: datasetIndex, options: {spanGaps}} = line;\n const count = points.length;\n const result = [];\n let prevStyle = baseStyle;\n let start = segments[0].start;\n let i = start;\n\n function addStyle(s, e, l, st) {\n const dir = spanGaps ? -1 : 1;\n if (s === e) {\n return;\n }\n // Style can not start/end on a skipped point, adjust indices accordingly\n s += count;\n while (points[s % count].skip) {\n s -= dir;\n }\n while (points[e % count].skip) {\n e += dir;\n }\n if (s % count !== e % count) {\n result.push({start: s % count, end: e % count, loop: l, style: st});\n prevStyle = st;\n start = e % count;\n }\n }\n\n for (const segment of segments) {\n start = spanGaps ? start : segment.start;\n let prev = points[start % count];\n let style;\n for (i = start + 1; i <= segment.end; i++) {\n const pt = points[i % count];\n style = readStyle(segmentOptions.setContext(createContext(chartContext, {\n type: 'segment',\n p0: prev,\n p1: pt,\n p0DataIndex: (i - 1) % count,\n p1DataIndex: i % count,\n datasetIndex\n })));\n if (styleChanged(style, prevStyle)) {\n addStyle(start, i - 1, segment.loop, prevStyle);\n }\n prev = pt;\n prevStyle = style;\n }\n if (start < i - 1) {\n addStyle(start, i - 1, segment.loop, prevStyle);\n }\n }\n\n return result;\n}\n\nfunction readStyle(options) {\n return {\n backgroundColor: options.backgroundColor,\n borderCapStyle: options.borderCapStyle,\n borderDash: options.borderDash,\n borderDashOffset: options.borderDashOffset,\n borderJoinStyle: options.borderJoinStyle,\n borderWidth: options.borderWidth,\n borderColor: options.borderColor\n };\n}\n\nfunction styleChanged(style, prevStyle) {\n if (!prevStyle) {\n return false;\n }\n const cache = [];\n const replacer = function(key, value) {\n if (!isPatternOrGradient(value)) {\n return value;\n }\n if (!cache.includes(value)) {\n cache.push(value);\n }\n return cache.indexOf(value);\n };\n return JSON.stringify(style, replacer) !== JSON.stringify(prevStyle, replacer);\n}\n","import type {Chart, ChartArea, ChartMeta, Scale, TRBL} from '../types/index.js';\n\nfunction getSizeForArea(scale: Scale, chartArea: ChartArea, field: keyof ChartArea) {\n return scale.options.clip ? scale[field] : chartArea[field];\n}\n\nfunction getDatasetArea(meta: ChartMeta, chartArea: ChartArea): TRBL {\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\nexport function getDatasetClipArea(chart: Chart, meta: ChartMeta): TRBL | false {\n const clip = meta._clip;\n if (clip.disabled) {\n return false;\n }\n const area = getDatasetArea(meta, chart.chartArea);\n\n return {\n left: clip.left === false ? 0 : area.left - (clip.left === true ? 0 : clip.left),\n right: clip.right === false ? chart.width : area.right + (clip.right === true ? 0 : clip.right),\n top: clip.top === false ? 0 : area.top - (clip.top === true ? 0 : clip.top),\n bottom: clip.bottom === false ? chart.height : area.bottom + (clip.bottom === true ? 0 : clip.bottom)\n };\n}\n"],"names":["noop","uid","id","isNullOrUndef","value","undefined","isArray","Array","type","Object","prototype","toString","call","slice","isObject","isNumberFinite","Number","isFinite","finiteOrDefault","defaultValue","valueOrDefault","toPercentage","dimension","endsWith","parseFloat","toDimension","callback","fn","args","thisArg","apply","each","loopable","reverse","i","len","keys","length","_elementsEqual","a0","a1","ilen","v0","v1","datasetIndex","index","clone","source","map","target","create","klen","k","isValidKey","key","indexOf","_merger","options","tval","sval","merge","sources","merger","current","mergeIf","_mergerIf","hasOwnProperty","_deprecated","scope","previous","console","warn","keyResolvers","v","x","o","y","_splitKey","parts","split","tmp","part","push","_getKeyResolver","obj","resolveObjectKey","resolver","_capitalize","str","charAt","toUpperCase","defined","isFunction","setsEqual","a","b","size","item","has","_isClickEvent","e","PI","Math","TAU","PITAU","INFINITY","POSITIVE_INFINITY","RAD_PER_DEG","HALF_PI","QUARTER_PI","TWO_THIRDS_PI","log10","sign","almostEquals","epsilon","abs","niceNum","range","roundedRange","round","niceRange","pow","floor","fraction","niceFraction","_factorize","result","sqrt","sort","pop","isNonPrimitive","n","Symbol","toPrimitive","isNumber","isNaN","almostWhole","rounded","_setMinAndMaxByKey","array","property","min","max","toRadians","degrees","toDegrees","radians","_decimalPlaces","isFiniteNumber","p","getAngleFromPoint","centrePoint","anglePoint","distanceFromXCenter","distanceFromYCenter","radialDistanceFromCenter","angle","atan2","distance","distanceBetweenPoints","pt1","pt2","_angleDiff","_normalizeAngle","_angleBetween","start","end","sameAngleIsFullCircle","s","angleToStart","angleToEnd","startToAngle","endToAngle","_limitValue","_int16Range","_isBetween","_lookup","table","cmp","hi","lo","mid","_lookupByKey","last","ti","_rlookupByKey","_filterBetween","values","arrayEvents","listenArrayEvents","listener","_chartjs","listeners","defineProperty","configurable","enumerable","forEach","method","base","res","object","unlistenArrayEvents","stub","splice","_arrayUnique","items","set","Set","from","fontString","pixelSize","fontStyle","fontFamily","requestAnimFrame","window","requestAnimationFrame","throttled","argsToUse","ticking","debounce","delay","timeout","clearTimeout","setTimeout","_toLeftRightCenter","align","_alignStartEnd","_textX","left","right","rtl","check","_getStartAndCountOfVisiblePoints","meta","points","animationsDisabled","pointCount","count","_sorted","iScale","vScale","_parsed","spanGaps","dataset","axis","minDefined","maxDefined","getUserBounds","getPixelForValue","distanceToDefinedLo","findIndex","point","distanceToDefinedHi","_scaleRangesChanged","xScale","yScale","_scaleRanges","newRanges","xmin","xmax","ymin","ymax","changed","assign","atEdge","t","elasticIn","sin","elasticOut","effects","linear","easeInQuad","easeOutQuad","easeInOutQuad","easeInCubic","easeOutCubic","easeInOutCubic","easeInQuart","easeOutQuart","easeInOutQuart","easeInQuint","easeOutQuint","easeInOutQuint","easeInSine","cos","easeOutSine","easeInOutSine","easeInExpo","easeOutExpo","easeInOutExpo","easeInCirc","easeOutCirc","easeInOutCirc","easeInElastic","easeOutElastic","easeInOutElastic","easeInBack","easeOutBack","easeInOutBack","easeInBounce","easeOutBounce","m","d","easeInOutBounce","isPatternOrGradient","color","Color","getHoverColor","saturate","darken","hexString","numbers","colors","applyAnimationsDefaults","defaults","duration","easing","loop","to","describe","_fallback","_indexable","_scriptable","name","properties","active","animation","resize","show","animations","visible","hide","applyLayoutsDefaults","autoPadding","padding","top","bottom","intlCache","Map","getNumberFormat","locale","cacheKey","JSON","stringify","formatter","get","Intl","NumberFormat","formatNumber","num","format","formatters","numeric","tickValue","ticks","chart","notation","delta","maxTick","calculateDelta","logDelta","numDecimal","minimumFractionDigits","maximumFractionDigits","logarithmic","remain","significand","includes","applyScaleDefaults","display","offset","beginAtZero","bounds","clip","grace","grid","lineWidth","drawOnChartArea","drawTicks","tickLength","tickWidth","_ctx","tickColor","border","dash","dashOffset","width","title","text","minRotation","maxRotation","mirror","textStrokeWidth","textStrokeColor","autoSkip","autoSkipPadding","labelOffset","Ticks","minor","major","crossAlign","showLabelBackdrop","backdropColor","backdropPadding","route","startsWith","overrides","descriptors","getScope","node","root","Defaults","constructor","_descriptors","_appliers","backgroundColor","borderColor","datasets","devicePixelRatio","context","platform","getDevicePixelRatio","elements","events","font","family","style","lineHeight","weight","hover","hoverBackgroundColor","ctx","hoverBorderColor","hoverColor","indexAxis","interaction","mode","intersect","includeInvisible","maintainAspectRatio","onHover","onClick","parsing","plugins","responsive","scale","scales","showLine","drawActiveElementsOnTop","override","targetScope","targetName","scopeObject","targetScopeObject","privateName","defineProperties","writable","local","appliers","toFontString","_measureText","data","gc","longest","string","textWidth","measureText","_longestText","arrayOfThings","cache","garbageCollect","save","j","jlen","thing","nestedThing","restore","gcLen","_alignPixel","pixel","currentDevicePixelRatio","halfWidth","clearCanvas","canvas","getContext","resetTransform","clearRect","height","drawPoint","drawPointLegend","w","xOffset","yOffset","cornerRadius","xOffsetW","yOffsetW","pointStyle","rotation","radius","rad","translate","rotate","drawImage","beginPath","ellipse","arc","closePath","moveTo","lineTo","SQRT1_2","rect","fill","borderWidth","stroke","_isPointInArea","area","margin","clipArea","unclipArea","_steppedLineTo","flip","midpoint","_bezierCurveTo","bezierCurveTo","cp1x","cp2x","cp1y","cp2y","setRenderOpts","opts","translation","fillStyle","textAlign","textBaseline","decorateText","line","strikethrough","underline","metrics","actualBoundingBoxLeft","actualBoundingBoxRight","actualBoundingBoxAscent","actualBoundingBoxDescent","yDecoration","strokeStyle","decorationWidth","drawBackdrop","oldColor","fillRect","renderText","lines","strokeWidth","strokeColor","backdrop","strokeText","maxWidth","fillText","addRoundedRectPath","h","topLeft","bottomLeft","bottomRight","topRight","LINE_HEIGHT","FONT_STYLE","toLineHeight","matches","match","numberOrZero","_readValueToProps","props","ret","objProps","read","prop","toTRBL","toTRBLCorners","toPadding","toFont","fallback","parseInt","resolve","inputs","info","cacheable","_addGrace","minmax","change","keepZero","add","createContext","parentContext","_createResolver","scopes","prefixes","rootScopes","getTarget","finalRootScopes","_resolve","toStringTag","_cacheable","_scopes","_rootScopes","_getTarget","Proxy","deleteProperty","_keys","_cached","_resolveWithPrefixes","getOwnPropertyDescriptor","Reflect","getPrototypeOf","getKeysFromAllScopes","ownKeys","storage","_storage","_attachContext","proxy","subProxy","descriptorDefaults","_proxy","_context","_subProxy","_stack","setContext","receiver","_resolveWithContext","allKeys","scriptable","indexable","_allKeys","isScriptable","isIndexable","readKey","prefix","needsSubResolver","_resolveScriptable","_resolveArray","getValue","Error","join","delete","createSubResolver","arr","filter","resolveFallback","parent","addScopes","parentScopes","parentFallback","allScopes","addScopesFromKey","subGetTarget","resolveKeysFromAllScopes","_parseObjectDataRadialScale","_parsing","parsed","r","parse","EPSILON","getPoint","skip","getValueAxis","splineCurve","firstPoint","middlePoint","afterPoint","next","d01","d12","s01","s12","fa","fb","monotoneAdjust","deltaK","mK","pointsLen","alphaK","betaK","tauK","squaredMagnitude","pointCurrent","pointAfter","monotoneCompute","valueAxis","pointBefore","iPixel","vPixel","splineCurveMonotone","slopeDelta","capControlPoint","pt","capBezierPoints","inArea","inAreaPrev","inAreaNext","_updateBezierControlPoints","controlPoints","cubicInterpolationMode","prev","tension","_isDomSupported","document","_getParentNode","domNode","parentNode","host","parseMaxStyle","styleValue","parentProperty","valueInPixels","getComputedStyle","element","ownerDocument","defaultView","getStyle","el","getPropertyValue","positions","getPositionedStyle","styles","suffix","pos","useOffsetPos","shadowRoot","getCanvasPosition","touches","offsetX","offsetY","box","getBoundingClientRect","clientX","clientY","getRelativePosition","event","borderBox","boxSizing","paddings","borders","getContainerSize","maxHeight","container","clientWidth","clientHeight","containerStyle","containerBorder","containerPadding","round1","getMaximumSize","bbWidth","bbHeight","aspectRatio","margins","containerSize","maintainHeight","retinaScale","forceRatio","forceStyle","pixelRatio","deviceHeight","deviceWidth","setTransform","supportsEventListenerOptions","passiveSupported","passive","addEventListener","removeEventListener","readUsedSize","_pointInLine","p1","p2","_steppedInterpolation","_bezierInterpolation","cp1","cp2","c","getRightToLeftAdapter","rectX","setWidth","xPlus","leftForLtr","itemWidth","getLeftToRightAdapter","_itemWidth","getRtlAdapter","overrideTextDirection","direction","original","getPropertyPriority","setProperty","prevTextDirection","restoreTextDirection","propertyFn","between","compare","normalize","normalizeSegment","getSegment","segment","startBound","endBound","_boundSegment","inside","subStart","prevValue","startIsBefore","endIsBefore","shouldStart","shouldStop","_boundSegments","segments","sub","findStartAndEnd","solidSegments","cur","stop","_computeSegments","segmentOptions","_loop","splitByStyles","completeLoop","_fullLoop","doSplitByStyles","chartContext","_chart","baseStyle","readStyle","_datasetIndex","prevStyle","addStyle","l","st","dir","p0","p0DataIndex","p1DataIndex","styleChanged","borderCapStyle","borderDash","borderDashOffset","borderJoinStyle","replacer","getSizeForArea","chartArea","field","getDatasetArea","getDatasetClipArea","_clip","disabled"],"mappings":";;;;;;;;;;AAAA;;;;IAUO,SAASA,IAAO,GAAA;AACrB,YACD;AAED;;AAEC,IACM,MAAMC,GAAM,GAAC,CAAA,IAAM;AACxB,IAAA,IAAIC,EAAK,GAAA,CAAA,CAAA;AACT,IAAA,OAAO,IAAMA,EAAAA,EAAAA,CAAAA;AACf,CAAA,IAAK;AAEL;;;;AAIC,IACM,SAASC,aAAcC,CAAAA,KAAc,EAA6B;IACvE,OAAOA,KAAAA,KAAU,IAAI,IAAIA,KAAUC,KAAAA,SAAAA,CAAAA;AACrC,CAAC;AAED;;;;AAIC,IACM,SAASC,OAAqBF,CAAAA,KAAc,EAAgB;AACjE,IAAA,IAAIG,MAAMD,OAAO,IAAIC,KAAMD,CAAAA,OAAO,CAACF,KAAQ,CAAA,EAAA;AACzC,QAAA,OAAO,IAAI,CAAA;KACZ;AACD,IAAA,MAAMI,OAAOC,MAAOC,CAAAA,SAAS,CAACC,QAAQ,CAACC,IAAI,CAACR,KAAAA,CAAAA,CAAAA;IAC5C,IAAII,IAAAA,CAAKK,KAAK,CAAC,CAAG,EAAA,CAAA,CAAA,KAAO,SAAaL,IAAAA,IAAAA,CAAKK,KAAK,CAAC,CAAC,CAAA,CAAA,KAAO,QAAU,EAAA;AACjE,QAAA,OAAO,IAAI,CAAA;KACZ;AACD,IAAA,OAAO,KAAK,CAAA;AACd,CAAC;AAED;;;;AAIC,IACM,SAASC,QAASV,CAAAA,KAAc,EAAsB;IAC3D,OAAOA,KAAAA,KAAU,IAAI,IAAIK,MAAOC,CA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D,IAAA,MAAM9U,IAAO2U,GAAAA,cAAAA,CAAermB,IAAM0H,EAAAA,KAAAA,CAAMye,SAAS,CAAA,CAAA;IAEjD,OAAO;AACLxmB,QAAAA,IAAAA,EAAMiJ,KAAKjJ,IAAI,KAAK,KAAK,GAAG,CAAA,GAAI+R,KAAK/R,IAAI,IAAIiJ,IAAKjJ,CAAAA,IAAI,KAAK,IAAI,GAAG,IAAIiJ,IAAKjJ,CAAAA,IAAI,CAAC;QAChFC,KAAOgJ,EAAAA,IAAAA,CAAKhJ,KAAK,KAAK,KAAK,GAAG8H,KAAM+B,CAAAA,KAAK,GAAGiI,IAAK9R,CAAAA,KAAK,IAAIgJ,IAAAA,CAAKhJ,KAAK,KAAK,IAAI,GAAG,CAAIgJ,GAAAA,IAAAA,CAAKhJ,KAAI,CAAE;AAC/F0G,QAAAA,GAAAA,EAAKsC,KAAKtC,GAAG,KAAK,KAAK,GAAG,CAAA,GAAIoL,KAAKpL,GAAG,IAAIsC,IAAKtC,CAAAA,GAAG,KAAK,IAAI,GAAG,IAAIsC,IAAKtC,CAAAA,GAAG,CAAC;QAC3EC,MAAQqC,EAAAA,IAAAA,CAAKrC,MAAM,KAAK,KAAK,GAAGmB,KAAMoI,CAAAA,MAAM,GAAG4B,IAAKnL,CAAAA,MAAM,IAAIqC,IAAAA,CAAKrC,MAAM,KAAK,IAAI,GAAG,CAAIqC,GAAAA,IAAAA,CAAKrC,MAAK,CAAE;AACvG,KAAA,CAAA;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/frontend/node_modules/chart.js/dist/chunks/helpers.dataset.js b/frontend/node_modules/chart.js/dist/chunks/helpers.dataset.js new file mode 100644 index 0000000000000000000000000000000000000000..aa8a077b8caba6448ce00af7fd3c3743ff0e8ca8 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/chunks/helpers.dataset.js @@ -0,0 +1,2788 @@ +/*! + * Chart.js v4.5.0 + * https://www.chartjs.org + * (c) 2025 Chart.js Contributors + * Released under the MIT License + */ +import { Color } from '@kurkle/color'; + +/** + * @namespace Chart.helpers + */ /** + * An empty function that can be used, for example, for optional callback. + */ function noop() { +/* noop */ } +/** + * Returns a unique id, sequentially generated from a global variable. + */ const uid = (()=>{ + let id = 0; + return ()=>id++; +})(); +/** + * Returns true if `value` is neither null nor undefined, else returns false. + * @param value - The value to test. + * @since 2.7.0 + */ function isNullOrUndef(value) { + return value === null || value === undefined; +} +/** + * Returns true if `value` is an array (including typed arrays), else returns false. + * @param value - The value to test. + * @function + */ function isArray(value) { + if (Array.isArray && Array.isArray(value)) { + return true; + } + const type = Object.prototype.toString.call(value); + if (type.slice(0, 7) === '[object' && type.slice(-6) === 'Array]') { + return true; + } + return false; +} +/** + * Returns true if `value` is an object (excluding null), else returns false. + * @param value - The value to test. + * @since 2.7.0 + */ function isObject(value) { + return value !== null && Object.prototype.toString.call(value) === '[object Object]'; +} +/** + * Returns true if `value` is a finite number, else returns false + * @param value - The value to test. + */ function isNumberFinite(value) { + return (typeof value === 'number' || value instanceof Number) && isFinite(+value); +} +/** + * Returns `value` if finite, else returns `defaultValue`. + * @param value - The value to return if defined. + * @param defaultValue - The value to return if `value` is not finite. + */ function finiteOrDefault(value, defaultValue) { + return isNumberFinite(value) ? value : defaultValue; +} +/** + * Returns `value` if defined, else returns `defaultValue`. + * @param value - The value to return if defined. + * @param defaultValue - The value to return if `value` is undefined. + */ function valueOrDefault(value, defaultValue) { + return typeof value === 'undefined' ? defaultValue : value; +} +const toPercentage = (value, dimension)=>typeof value === 'string' && value.endsWith('%') ? parseFloat(value) / 100 : +value / dimension; +const toDimension = (value, dimension)=>typeof value === 'string' && value.endsWith('%') ? parseFloat(value) / 100 * dimension : +value; +/** + * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the + * value returned by `fn`. If `fn` is not a function, this method returns undefined. + * @param fn - The function to call. + * @param args - The arguments with which `fn` should be called. + * @param [thisArg] - The value of `this` provided for the call to `fn`. + */ function callback(fn, args, thisArg) { + if (fn && typeof fn.call === 'function') { + return fn.apply(thisArg, args); + } +} +function each(loopable, fn, thisArg, reverse) { + let i, len, keys; + if (isArray(loopable)) { + len = loopable.length; + if (reverse) { + for(i = len - 1; i >= 0; i--){ + fn.call(thisArg, loopable[i], i); + } + } else { + for(i = 0; i < len; i++){ + fn.call(thisArg, loopable[i], i); + } + } + } else if (isObject(loopable)) { + keys = Object.keys(loopable); + len = keys.length; + for(i = 0; i < len; i++){ + fn.call(thisArg, loopable[keys[i]], keys[i]); + } + } +} +/** + * Returns true if the `a0` and `a1` arrays have the same content, else returns false. + * @param a0 - The array to compare + * @param a1 - The array to compare + * @private + */ function _elementsEqual(a0, a1) { + let i, ilen, v0, v1; + if (!a0 || !a1 || a0.length !== a1.length) { + return false; + } + for(i = 0, ilen = a0.length; i < ilen; ++i){ + v0 = a0[i]; + v1 = a1[i]; + if (v0.datasetIndex !== v1.datasetIndex || v0.index !== v1.index) { + return false; + } + } + return true; +} +/** + * Returns a deep copy of `source` without keeping references on objects and arrays. + * @param source - The value to clone. + */ function clone(source) { + if (isArray(source)) { + return source.map(clone); + } + if (isObject(source)) { + const target = Object.create(null); + const keys = Object.keys(source); + const klen = keys.length; + let k = 0; + for(; k < klen; ++k){ + target[keys[k]] = clone(source[keys[k]]); + } + return target; + } + return source; +} +function isValidKey(key) { + return [ + '__proto__', + 'prototype', + 'constructor' + ].indexOf(key) === -1; +} +/** + * The default merger when Chart.helpers.merge is called without merger option. + * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback. + * @private + */ function _merger(key, target, source, options) { + if (!isValidKey(key)) { + return; + } + const tval = target[key]; + const sval = source[key]; + if (isObject(tval) && isObject(sval)) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + merge(tval, sval, options); + } else { + target[key] = clone(sval); + } +} +function merge(target, source, options) { + const sources = isArray(source) ? source : [ + source + ]; + const ilen = sources.length; + if (!isObject(target)) { + return target; + } + options = options || {}; + const merger = options.merger || _merger; + let current; + for(let i = 0; i < ilen; ++i){ + current = sources[i]; + if (!isObject(current)) { + continue; + } + const keys = Object.keys(current); + for(let k = 0, klen = keys.length; k < klen; ++k){ + merger(keys[k], target, current, options); + } + } + return target; +} +function mergeIf(target, source) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return merge(target, source, { + merger: _mergerIf + }); +} +/** + * Merges source[key] in target[key] only if target[key] is undefined. + * @private + */ function _mergerIf(key, target, source) { + if (!isValidKey(key)) { + return; + } + const tval = target[key]; + const sval = source[key]; + if (isObject(tval) && isObject(sval)) { + mergeIf(tval, sval); + } else if (!Object.prototype.hasOwnProperty.call(target, key)) { + target[key] = clone(sval); + } +} +/** + * @private + */ function _deprecated(scope, value, previous, current) { + if (value !== undefined) { + console.warn(scope + ': "' + previous + '" is deprecated. Please use "' + current + '" instead'); + } +} +// resolveObjectKey resolver cache +const keyResolvers = { + // Chart.helpers.core resolveObjectKey should resolve empty key to root object + '': (v)=>v, + // default resolvers + x: (o)=>o.x, + y: (o)=>o.y +}; +/** + * @private + */ function _splitKey(key) { + const parts = key.split('.'); + const keys = []; + let tmp = ''; + for (const part of parts){ + tmp += part; + if (tmp.endsWith('\\')) { + tmp = tmp.slice(0, -1) + '.'; + } else { + keys.push(tmp); + tmp = ''; + } + } + return keys; +} +function _getKeyResolver(key) { + const keys = _splitKey(key); + return (obj)=>{ + for (const k of keys){ + if (k === '') { + break; + } + obj = obj && obj[k]; + } + return obj; + }; +} +function resolveObjectKey(obj, key) { + const resolver = keyResolvers[key] || (keyResolvers[key] = _getKeyResolver(key)); + return resolver(obj); +} +/** + * @private + */ function _capitalize(str) { + return str.charAt(0).toUpperCase() + str.slice(1); +} +const defined = (value)=>typeof value !== 'undefined'; +const isFunction = (value)=>typeof value === 'function'; +// Adapted from https://stackoverflow.com/questions/31128855/comparing-ecma6-sets-for-equality#31129384 +const setsEqual = (a, b)=>{ + if (a.size !== b.size) { + return false; + } + for (const item of a){ + if (!b.has(item)) { + return false; + } + } + return true; +}; +/** + * @param e - The event + * @private + */ function _isClickEvent(e) { + return e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu'; +} + +/** + * @alias Chart.helpers.math + * @namespace + */ const PI = Math.PI; +const TAU = 2 * PI; +const PITAU = TAU + PI; +const INFINITY = Number.POSITIVE_INFINITY; +const RAD_PER_DEG = PI / 180; +const HALF_PI = PI / 2; +const QUARTER_PI = PI / 4; +const TWO_THIRDS_PI = PI * 2 / 3; +const log10 = Math.log10; +const sign = Math.sign; +function almostEquals(x, y, epsilon) { + return Math.abs(x - y) < epsilon; +} +/** + * Implementation of the nice number algorithm used in determining where axis labels will go + */ function niceNum(range) { + const roundedRange = Math.round(range); + range = almostEquals(range, roundedRange, range / 1000) ? roundedRange : range; + const niceRange = Math.pow(10, Math.floor(log10(range))); + const fraction = range / niceRange; + const niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10; + return niceFraction * niceRange; +} +/** + * Returns an array of factors sorted from 1 to sqrt(value) + * @private + */ function _factorize(value) { + const result = []; + const sqrt = Math.sqrt(value); + let i; + for(i = 1; i < sqrt; i++){ + if (value % i === 0) { + result.push(i); + result.push(value / i); + } + } + if (sqrt === (sqrt | 0)) { + result.push(sqrt); + } + result.sort((a, b)=>a - b).pop(); + return result; +} +/** + * Verifies that attempting to coerce n to string or number won't throw a TypeError. + */ function isNonPrimitive(n) { + return typeof n === 'symbol' || typeof n === 'object' && n !== null && !(Symbol.toPrimitive in n || 'toString' in n || 'valueOf' in n); +} +function isNumber(n) { + return !isNonPrimitive(n) && !isNaN(parseFloat(n)) && isFinite(n); +} +function almostWhole(x, epsilon) { + const rounded = Math.round(x); + return rounded - epsilon <= x && rounded + epsilon >= x; +} +/** + * @private + */ function _setMinAndMaxByKey(array, target, property) { + let i, ilen, value; + for(i = 0, ilen = array.length; i < ilen; i++){ + value = array[i][property]; + if (!isNaN(value)) { + target.min = Math.min(target.min, value); + target.max = Math.max(target.max, value); + } + } +} +function toRadians(degrees) { + return degrees * (PI / 180); +} +function toDegrees(radians) { + return radians * (180 / PI); +} +/** + * Returns the number of decimal places + * i.e. the number of digits after the decimal point, of the value of this Number. + * @param x - A number. + * @returns The number of decimal places. + * @private + */ function _decimalPlaces(x) { + if (!isNumberFinite(x)) { + return; + } + let e = 1; + let p = 0; + while(Math.round(x * e) / e !== x){ + e *= 10; + p++; + } + return p; +} +// Gets the angle from vertical upright to the point about a centre. +function getAngleFromPoint(centrePoint, anglePoint) { + const distanceFromXCenter = anglePoint.x - centrePoint.x; + const distanceFromYCenter = anglePoint.y - centrePoint.y; + const radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter); + let angle = Math.atan2(distanceFromYCenter, distanceFromXCenter); + if (angle < -0.5 * PI) { + angle += TAU; // make sure the returned angle is in the range of (-PI/2, 3PI/2] + } + return { + angle, + distance: radialDistanceFromCenter + }; +} +function distanceBetweenPoints(pt1, pt2) { + return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2)); +} +/** + * Shortest distance between angles, in either direction. + * @private + */ function _angleDiff(a, b) { + return (a - b + PITAU) % TAU - PI; +} +/** + * Normalize angle to be between 0 and 2*PI + * @private + */ function _normalizeAngle(a) { + return (a % TAU + TAU) % TAU; +} +/** + * @private + */ function _angleBetween(angle, start, end, sameAngleIsFullCircle) { + const a = _normalizeAngle(angle); + const s = _normalizeAngle(start); + const e = _normalizeAngle(end); + const angleToStart = _normalizeAngle(s - a); + const angleToEnd = _normalizeAngle(e - a); + const startToAngle = _normalizeAngle(a - s); + const endToAngle = _normalizeAngle(a - e); + return a === s || a === e || sameAngleIsFullCircle && s === e || angleToStart > angleToEnd && startToAngle < endToAngle; +} +/** + * Limit `value` between `min` and `max` + * @param value + * @param min + * @param max + * @private + */ function _limitValue(value, min, max) { + return Math.max(min, Math.min(max, value)); +} +/** + * @param {number} value + * @private + */ function _int16Range(value) { + return _limitValue(value, -32768, 32767); +} +/** + * @param value + * @param start + * @param end + * @param [epsilon] + * @private + */ function _isBetween(value, start, end, epsilon = 1e-6) { + return value >= Math.min(start, end) - epsilon && value <= Math.max(start, end) + epsilon; +} + +function _lookup(table, value, cmp) { + cmp = cmp || ((index)=>table[index] < value); + let hi = table.length - 1; + let lo = 0; + let mid; + while(hi - lo > 1){ + mid = lo + hi >> 1; + if (cmp(mid)) { + lo = mid; + } else { + hi = mid; + } + } + return { + lo, + hi + }; +} +/** + * Binary search + * @param table - the table search. must be sorted! + * @param key - property name for the value in each entry + * @param value - value to find + * @param last - lookup last index + * @private + */ const _lookupByKey = (table, key, value, last)=>_lookup(table, value, last ? (index)=>{ + const ti = table[index][key]; + return ti < value || ti === value && table[index + 1][key] === value; + } : (index)=>table[index][key] < value); +/** + * Reverse binary search + * @param table - the table search. must be sorted! + * @param key - property name for the value in each entry + * @param value - value to find + * @private + */ const _rlookupByKey = (table, key, value)=>_lookup(table, value, (index)=>table[index][key] >= value); +/** + * Return subset of `values` between `min` and `max` inclusive. + * Values are assumed to be in sorted order. + * @param values - sorted array of values + * @param min - min value + * @param max - max value + */ function _filterBetween(values, min, max) { + let start = 0; + let end = values.length; + while(start < end && values[start] < min){ + start++; + } + while(end > start && values[end - 1] > max){ + end--; + } + return start > 0 || end < values.length ? values.slice(start, end) : values; +} +const arrayEvents = [ + 'push', + 'pop', + 'shift', + 'splice', + 'unshift' +]; +function listenArrayEvents(array, listener) { + if (array._chartjs) { + array._chartjs.listeners.push(listener); + return; + } + Object.defineProperty(array, '_chartjs', { + configurable: true, + enumerable: false, + value: { + listeners: [ + listener + ] + } + }); + arrayEvents.forEach((key)=>{ + const method = '_onData' + _capitalize(key); + const base = array[key]; + Object.defineProperty(array, key, { + configurable: true, + enumerable: false, + value (...args) { + const res = base.apply(this, args); + array._chartjs.listeners.forEach((object)=>{ + if (typeof object[method] === 'function') { + object[method](...args); + } + }); + return res; + } + }); + }); +} +function unlistenArrayEvents(array, listener) { + const stub = array._chartjs; + if (!stub) { + return; + } + const listeners = stub.listeners; + const index = listeners.indexOf(listener); + if (index !== -1) { + listeners.splice(index, 1); + } + if (listeners.length > 0) { + return; + } + arrayEvents.forEach((key)=>{ + delete array[key]; + }); + delete array._chartjs; +} +/** + * @param items + */ function _arrayUnique(items) { + const set = new Set(items); + if (set.size === items.length) { + return items; + } + return Array.from(set); +} + +function fontString(pixelSize, fontStyle, fontFamily) { + return fontStyle + ' ' + pixelSize + 'px ' + fontFamily; +} +/** +* Request animation polyfill +*/ const requestAnimFrame = function() { + if (typeof window === 'undefined') { + return function(callback) { + return callback(); + }; + } + return window.requestAnimationFrame; +}(); +/** + * Throttles calling `fn` once per animation frame + * Latest arguments are used on the actual call + */ function throttled(fn, thisArg) { + let argsToUse = []; + let ticking = false; + return function(...args) { + // Save the args for use later + argsToUse = args; + if (!ticking) { + ticking = true; + requestAnimFrame.call(window, ()=>{ + ticking = false; + fn.apply(thisArg, argsToUse); + }); + } + }; +} +/** + * Debounces calling `fn` for `delay` ms + */ function debounce(fn, delay) { + let timeout; + return function(...args) { + if (delay) { + clearTimeout(timeout); + timeout = setTimeout(fn, delay, args); + } else { + fn.apply(this, args); + } + return delay; + }; +} +/** + * Converts 'start' to 'left', 'end' to 'right' and others to 'center' + * @private + */ const _toLeftRightCenter = (align)=>align === 'start' ? 'left' : align === 'end' ? 'right' : 'center'; +/** + * Returns `start`, `end` or `(start + end) / 2` depending on `align`. Defaults to `center` + * @private + */ const _alignStartEnd = (align, start, end)=>align === 'start' ? start : align === 'end' ? end : (start + end) / 2; +/** + * Returns `left`, `right` or `(left + right) / 2` depending on `align`. Defaults to `left` + * @private + */ const _textX = (align, left, right, rtl)=>{ + const check = rtl ? 'left' : 'right'; + return align === check ? right : align === 'center' ? (left + right) / 2 : left; +}; +/** + * Return start and count of visible points. + * @private + */ function _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled) { + const pointCount = points.length; + let start = 0; + let count = pointCount; + if (meta._sorted) { + const { iScale , vScale , _parsed } = meta; + const spanGaps = meta.dataset ? meta.dataset.options ? meta.dataset.options.spanGaps : null : null; + const axis = iScale.axis; + const { min , max , minDefined , maxDefined } = iScale.getUserBounds(); + if (minDefined) { + start = Math.min(// @ts-expect-error Need to type _parsed + _lookupByKey(_parsed, axis, min).lo, // @ts-expect-error Need to fix types on _lookupByKey + animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min)).lo); + if (spanGaps) { + const distanceToDefinedLo = _parsed.slice(0, start + 1).reverse().findIndex((point)=>!isNullOrUndef(point[vScale.axis])); + start -= Math.max(0, distanceToDefinedLo); + } + start = _limitValue(start, 0, pointCount - 1); + } + if (maxDefined) { + let end = Math.max(// @ts-expect-error Need to type _parsed + _lookupByKey(_parsed, iScale.axis, max, true).hi + 1, // @ts-expect-error Need to fix types on _lookupByKey + animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max), true).hi + 1); + if (spanGaps) { + const distanceToDefinedHi = _parsed.slice(end - 1).findIndex((point)=>!isNullOrUndef(point[vScale.axis])); + end += Math.max(0, distanceToDefinedHi); + } + count = _limitValue(end, start, pointCount) - start; + } else { + count = pointCount - start; + } + } + return { + start, + count + }; +} +/** + * Checks if the scale ranges have changed. + * @param {object} meta - dataset meta. + * @returns {boolean} + * @private + */ function _scaleRangesChanged(meta) { + const { xScale , yScale , _scaleRanges } = meta; + const newRanges = { + xmin: xScale.min, + xmax: xScale.max, + ymin: yScale.min, + ymax: yScale.max + }; + if (!_scaleRanges) { + meta._scaleRanges = newRanges; + return true; + } + const changed = _scaleRanges.xmin !== xScale.min || _scaleRanges.xmax !== xScale.max || _scaleRanges.ymin !== yScale.min || _scaleRanges.ymax !== yScale.max; + Object.assign(_scaleRanges, newRanges); + return changed; +} + +const atEdge = (t)=>t === 0 || t === 1; +const elasticIn = (t, s, p)=>-(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * TAU / p)); +const elasticOut = (t, s, p)=>Math.pow(2, -10 * t) * Math.sin((t - s) * TAU / p) + 1; +/** + * Easing functions adapted from Robert Penner's easing equations. + * @namespace Chart.helpers.easing.effects + * @see http://www.robertpenner.com/easing/ + */ const effects = { + linear: (t)=>t, + easeInQuad: (t)=>t * t, + easeOutQuad: (t)=>-t * (t - 2), + easeInOutQuad: (t)=>(t /= 0.5) < 1 ? 0.5 * t * t : -0.5 * (--t * (t - 2) - 1), + easeInCubic: (t)=>t * t * t, + easeOutCubic: (t)=>(t -= 1) * t * t + 1, + easeInOutCubic: (t)=>(t /= 0.5) < 1 ? 0.5 * t * t * t : 0.5 * ((t -= 2) * t * t + 2), + easeInQuart: (t)=>t * t * t * t, + easeOutQuart: (t)=>-((t -= 1) * t * t * t - 1), + easeInOutQuart: (t)=>(t /= 0.5) < 1 ? 0.5 * t * t * t * t : -0.5 * ((t -= 2) * t * t * t - 2), + easeInQuint: (t)=>t * t * t * t * t, + easeOutQuint: (t)=>(t -= 1) * t * t * t * t + 1, + easeInOutQuint: (t)=>(t /= 0.5) < 1 ? 0.5 * t * t * t * t * t : 0.5 * ((t -= 2) * t * t * t * t + 2), + easeInSine: (t)=>-Math.cos(t * HALF_PI) + 1, + easeOutSine: (t)=>Math.sin(t * HALF_PI), + easeInOutSine: (t)=>-0.5 * (Math.cos(PI * t) - 1), + easeInExpo: (t)=>t === 0 ? 0 : Math.pow(2, 10 * (t - 1)), + easeOutExpo: (t)=>t === 1 ? 1 : -Math.pow(2, -10 * t) + 1, + easeInOutExpo: (t)=>atEdge(t) ? t : t < 0.5 ? 0.5 * Math.pow(2, 10 * (t * 2 - 1)) : 0.5 * (-Math.pow(2, -10 * (t * 2 - 1)) + 2), + easeInCirc: (t)=>t >= 1 ? t : -(Math.sqrt(1 - t * t) - 1), + easeOutCirc: (t)=>Math.sqrt(1 - (t -= 1) * t), + easeInOutCirc: (t)=>(t /= 0.5) < 1 ? -0.5 * (Math.sqrt(1 - t * t) - 1) : 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1), + easeInElastic: (t)=>atEdge(t) ? t : elasticIn(t, 0.075, 0.3), + easeOutElastic: (t)=>atEdge(t) ? t : elasticOut(t, 0.075, 0.3), + easeInOutElastic (t) { + const s = 0.1125; + const p = 0.45; + return atEdge(t) ? t : t < 0.5 ? 0.5 * elasticIn(t * 2, s, p) : 0.5 + 0.5 * elasticOut(t * 2 - 1, s, p); + }, + easeInBack (t) { + const s = 1.70158; + return t * t * ((s + 1) * t - s); + }, + easeOutBack (t) { + const s = 1.70158; + return (t -= 1) * t * ((s + 1) * t + s) + 1; + }, + easeInOutBack (t) { + let s = 1.70158; + if ((t /= 0.5) < 1) { + return 0.5 * (t * t * (((s *= 1.525) + 1) * t - s)); + } + return 0.5 * ((t -= 2) * t * (((s *= 1.525) + 1) * t + s) + 2); + }, + easeInBounce: (t)=>1 - effects.easeOutBounce(1 - t), + easeOutBounce (t) { + const m = 7.5625; + const d = 2.75; + if (t < 1 / d) { + return m * t * t; + } + if (t < 2 / d) { + return m * (t -= 1.5 / d) * t + 0.75; + } + if (t < 2.5 / d) { + return m * (t -= 2.25 / d) * t + 0.9375; + } + return m * (t -= 2.625 / d) * t + 0.984375; + }, + easeInOutBounce: (t)=>t < 0.5 ? effects.easeInBounce(t * 2) * 0.5 : effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5 +}; + +function isPatternOrGradient(value) { + if (value && typeof value === 'object') { + const type = value.toString(); + return type === '[object CanvasPattern]' || type === '[object CanvasGradient]'; + } + return false; +} +function color(value) { + return isPatternOrGradient(value) ? value : new Color(value); +} +function getHoverColor(value) { + return isPatternOrGradient(value) ? value : new Color(value).saturate(0.5).darken(0.1).hexString(); +} + +const numbers = [ + 'x', + 'y', + 'borderWidth', + 'radius', + 'tension' +]; +const colors = [ + 'color', + 'borderColor', + 'backgroundColor' +]; +function applyAnimationsDefaults(defaults) { + defaults.set('animation', { + delay: undefined, + duration: 1000, + easing: 'easeOutQuart', + fn: undefined, + from: undefined, + loop: undefined, + to: undefined, + type: undefined + }); + defaults.describe('animation', { + _fallback: false, + _indexable: false, + _scriptable: (name)=>name !== 'onProgress' && name !== 'onComplete' && name !== 'fn' + }); + defaults.set('animations', { + colors: { + type: 'color', + properties: colors + }, + numbers: { + type: 'number', + properties: numbers + } + }); + defaults.describe('animations', { + _fallback: 'animation' + }); + defaults.set('transitions', { + active: { + animation: { + duration: 400 + } + }, + resize: { + animation: { + duration: 0 + } + }, + show: { + animations: { + colors: { + from: 'transparent' + }, + visible: { + type: 'boolean', + duration: 0 + } + } + }, + hide: { + animations: { + colors: { + to: 'transparent' + }, + visible: { + type: 'boolean', + easing: 'linear', + fn: (v)=>v | 0 + } + } + } + }); +} + +function applyLayoutsDefaults(defaults) { + defaults.set('layout', { + autoPadding: true, + padding: { + top: 0, + right: 0, + bottom: 0, + left: 0 + } + }); +} + +const intlCache = new Map(); +function getNumberFormat(locale, options) { + options = options || {}; + const cacheKey = locale + JSON.stringify(options); + let formatter = intlCache.get(cacheKey); + if (!formatter) { + formatter = new Intl.NumberFormat(locale, options); + intlCache.set(cacheKey, formatter); + } + return formatter; +} +function formatNumber(num, locale, options) { + return getNumberFormat(locale, options).format(num); +} + +const formatters = { + values (value) { + return isArray(value) ? value : '' + value; + }, + numeric (tickValue, index, ticks) { + if (tickValue === 0) { + return '0'; + } + const locale = this.chart.options.locale; + let notation; + let delta = tickValue; + if (ticks.length > 1) { + const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value)); + if (maxTick < 1e-4 || maxTick > 1e+15) { + notation = 'scientific'; + } + delta = calculateDelta(tickValue, ticks); + } + const logDelta = log10(Math.abs(delta)); + const numDecimal = isNaN(logDelta) ? 1 : Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0); + const options = { + notation, + minimumFractionDigits: numDecimal, + maximumFractionDigits: numDecimal + }; + Object.assign(options, this.options.ticks.format); + return formatNumber(tickValue, locale, options); + }, + logarithmic (tickValue, index, ticks) { + if (tickValue === 0) { + return '0'; + } + const remain = ticks[index].significand || tickValue / Math.pow(10, Math.floor(log10(tickValue))); + if ([ + 1, + 2, + 3, + 5, + 10, + 15 + ].includes(remain) || index > 0.8 * ticks.length) { + return formatters.numeric.call(this, tickValue, index, ticks); + } + return ''; + } +}; +function calculateDelta(tickValue, ticks) { + let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value; + if (Math.abs(delta) >= 1 && tickValue !== Math.floor(tickValue)) { + delta = tickValue - Math.floor(tickValue); + } + return delta; +} + var Ticks = { + formatters +}; + +function applyScaleDefaults(defaults) { + defaults.set('scale', { + display: true, + offset: false, + reverse: false, + beginAtZero: false, + bounds: 'ticks', + clip: true, + grace: 0, + grid: { + display: true, + lineWidth: 1, + drawOnChartArea: true, + drawTicks: true, + tickLength: 8, + tickWidth: (_ctx, options)=>options.lineWidth, + tickColor: (_ctx, options)=>options.color, + offset: false + }, + border: { + display: true, + dash: [], + dashOffset: 0.0, + width: 1 + }, + title: { + display: false, + text: '', + padding: { + top: 4, + bottom: 4 + } + }, + ticks: { + minRotation: 0, + maxRotation: 50, + mirror: false, + textStrokeWidth: 0, + textStrokeColor: '', + padding: 3, + display: true, + autoSkip: true, + autoSkipPadding: 3, + labelOffset: 0, + callback: Ticks.formatters.values, + minor: {}, + major: {}, + align: 'center', + crossAlign: 'near', + showLabelBackdrop: false, + backdropColor: 'rgba(255, 255, 255, 0.75)', + backdropPadding: 2 + } + }); + defaults.route('scale.ticks', 'color', '', 'color'); + defaults.route('scale.grid', 'color', '', 'borderColor'); + defaults.route('scale.border', 'color', '', 'borderColor'); + defaults.route('scale.title', 'color', '', 'color'); + defaults.describe('scale', { + _fallback: false, + _scriptable: (name)=>!name.startsWith('before') && !name.startsWith('after') && name !== 'callback' && name !== 'parser', + _indexable: (name)=>name !== 'borderDash' && name !== 'tickBorderDash' && name !== 'dash' + }); + defaults.describe('scales', { + _fallback: 'scale' + }); + defaults.describe('scale.ticks', { + _scriptable: (name)=>name !== 'backdropPadding' && name !== 'callback', + _indexable: (name)=>name !== 'backdropPadding' + }); +} + +const overrides = Object.create(null); +const descriptors = Object.create(null); + function getScope$1(node, key) { + if (!key) { + return node; + } + const keys = key.split('.'); + for(let i = 0, n = keys.length; i < n; ++i){ + const k = keys[i]; + node = node[k] || (node[k] = Object.create(null)); + } + return node; +} +function set(root, scope, values) { + if (typeof scope === 'string') { + return merge(getScope$1(root, scope), values); + } + return merge(getScope$1(root, ''), scope); +} + class Defaults { + constructor(_descriptors, _appliers){ + this.animation = undefined; + this.backgroundColor = 'rgba(0,0,0,0.1)'; + this.borderColor = 'rgba(0,0,0,0.1)'; + this.color = '#666'; + this.datasets = {}; + this.devicePixelRatio = (context)=>context.chart.platform.getDevicePixelRatio(); + this.elements = {}; + this.events = [ + 'mousemove', + 'mouseout', + 'click', + 'touchstart', + 'touchmove' + ]; + this.font = { + family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", + size: 12, + style: 'normal', + lineHeight: 1.2, + weight: null + }; + this.hover = {}; + this.hoverBackgroundColor = (ctx, options)=>getHoverColor(options.backgroundColor); + this.hoverBorderColor = (ctx, options)=>getHoverColor(options.borderColor); + this.hoverColor = (ctx, options)=>getHoverColor(options.color); + this.indexAxis = 'x'; + this.interaction = { + mode: 'nearest', + intersect: true, + includeInvisible: false + }; + this.maintainAspectRatio = true; + this.onHover = null; + this.onClick = null; + this.parsing = true; + this.plugins = {}; + this.responsive = true; + this.scale = undefined; + this.scales = {}; + this.showLine = true; + this.drawActiveElementsOnTop = true; + this.describe(_descriptors); + this.apply(_appliers); + } + set(scope, values) { + return set(this, scope, values); + } + get(scope) { + return getScope$1(this, scope); + } + describe(scope, values) { + return set(descriptors, scope, values); + } + override(scope, values) { + return set(overrides, scope, values); + } + route(scope, name, targetScope, targetName) { + const scopeObject = getScope$1(this, scope); + const targetScopeObject = getScope$1(this, targetScope); + const privateName = '_' + name; + Object.defineProperties(scopeObject, { + [privateName]: { + value: scopeObject[name], + writable: true + }, + [name]: { + enumerable: true, + get () { + const local = this[privateName]; + const target = targetScopeObject[targetName]; + if (isObject(local)) { + return Object.assign({}, target, local); + } + return valueOrDefault(local, target); + }, + set (value) { + this[privateName] = value; + } + } + }); + } + apply(appliers) { + appliers.forEach((apply)=>apply(this)); + } +} +var defaults = /* #__PURE__ */ new Defaults({ + _scriptable: (name)=>!name.startsWith('on'), + _indexable: (name)=>name !== 'events', + hover: { + _fallback: 'interaction' + }, + interaction: { + _scriptable: false, + _indexable: false + } +}, [ + applyAnimationsDefaults, + applyLayoutsDefaults, + applyScaleDefaults +]); + +/** + * Converts the given font object into a CSS font string. + * @param font - A font object. + * @return The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font + * @private + */ function toFontString(font) { + if (!font || isNullOrUndef(font.size) || isNullOrUndef(font.family)) { + return null; + } + return (font.style ? font.style + ' ' : '') + (font.weight ? font.weight + ' ' : '') + font.size + 'px ' + font.family; +} +/** + * @private + */ function _measureText(ctx, data, gc, longest, string) { + let textWidth = data[string]; + if (!textWidth) { + textWidth = data[string] = ctx.measureText(string).width; + gc.push(string); + } + if (textWidth > longest) { + longest = textWidth; + } + return longest; +} +/** + * @private + */ // eslint-disable-next-line complexity +function _longestText(ctx, font, arrayOfThings, cache) { + cache = cache || {}; + let data = cache.data = cache.data || {}; + let gc = cache.garbageCollect = cache.garbageCollect || []; + if (cache.font !== font) { + data = cache.data = {}; + gc = cache.garbageCollect = []; + cache.font = font; + } + ctx.save(); + ctx.font = font; + let longest = 0; + const ilen = arrayOfThings.length; + let i, j, jlen, thing, nestedThing; + for(i = 0; i < ilen; i++){ + thing = arrayOfThings[i]; + // Undefined strings and arrays should not be measured + if (thing !== undefined && thing !== null && !isArray(thing)) { + longest = _measureText(ctx, data, gc, longest, thing); + } else if (isArray(thing)) { + // if it is an array lets measure each element + // to do maybe simplify this function a bit so we can do this more recursively? + for(j = 0, jlen = thing.length; j < jlen; j++){ + nestedThing = thing[j]; + // Undefined strings and arrays should not be measured + if (nestedThing !== undefined && nestedThing !== null && !isArray(nestedThing)) { + longest = _measureText(ctx, data, gc, longest, nestedThing); + } + } + } + } + ctx.restore(); + const gcLen = gc.length / 2; + if (gcLen > arrayOfThings.length) { + for(i = 0; i < gcLen; i++){ + delete data[gc[i]]; + } + gc.splice(0, gcLen); + } + return longest; +} +/** + * Returns the aligned pixel value to avoid anti-aliasing blur + * @param chart - The chart instance. + * @param pixel - A pixel value. + * @param width - The width of the element. + * @returns The aligned pixel value. + * @private + */ function _alignPixel(chart, pixel, width) { + const devicePixelRatio = chart.currentDevicePixelRatio; + const halfWidth = width !== 0 ? Math.max(width / 2, 0.5) : 0; + return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth; +} +/** + * Clears the entire canvas. + */ function clearCanvas(canvas, ctx) { + if (!ctx && !canvas) { + return; + } + ctx = ctx || canvas.getContext('2d'); + ctx.save(); + // canvas.width and canvas.height do not consider the canvas transform, + // while clearRect does + ctx.resetTransform(); + ctx.clearRect(0, 0, canvas.width, canvas.height); + ctx.restore(); +} +function drawPoint(ctx, options, x, y) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + drawPointLegend(ctx, options, x, y, null); +} +// eslint-disable-next-line complexity +function drawPointLegend(ctx, options, x, y, w) { + let type, xOffset, yOffset, size, cornerRadius, width, xOffsetW, yOffsetW; + const style = options.pointStyle; + const rotation = options.rotation; + const radius = options.radius; + let rad = (rotation || 0) * RAD_PER_DEG; + if (style && typeof style === 'object') { + type = style.toString(); + if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') { + ctx.save(); + ctx.translate(x, y); + ctx.rotate(rad); + ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height); + ctx.restore(); + return; + } + } + if (isNaN(radius) || radius <= 0) { + return; + } + ctx.beginPath(); + switch(style){ + // Default includes circle + default: + if (w) { + ctx.ellipse(x, y, w / 2, radius, 0, 0, TAU); + } else { + ctx.arc(x, y, radius, 0, TAU); + } + ctx.closePath(); + break; + case 'triangle': + width = w ? w / 2 : radius; + ctx.moveTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius); + rad += TWO_THIRDS_PI; + ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius); + rad += TWO_THIRDS_PI; + ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius); + ctx.closePath(); + break; + case 'rectRounded': + // NOTE: the rounded rect implementation changed to use `arc` instead of + // `quadraticCurveTo` since it generates better results when rect is + // almost a circle. 0.516 (instead of 0.5) produces results with visually + // closer proportion to the previous impl and it is inscribed in the + // circle with `radius`. For more details, see the following PRs: + // https://github.com/chartjs/Chart.js/issues/5597 + // https://github.com/chartjs/Chart.js/issues/5858 + cornerRadius = radius * 0.516; + size = radius - cornerRadius; + xOffset = Math.cos(rad + QUARTER_PI) * size; + xOffsetW = Math.cos(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size); + yOffset = Math.sin(rad + QUARTER_PI) * size; + yOffsetW = Math.sin(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size); + ctx.arc(x - xOffsetW, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI); + ctx.arc(x + yOffsetW, y - xOffset, cornerRadius, rad - HALF_PI, rad); + ctx.arc(x + xOffsetW, y + yOffset, cornerRadius, rad, rad + HALF_PI); + ctx.arc(x - yOffsetW, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI); + ctx.closePath(); + break; + case 'rect': + if (!rotation) { + size = Math.SQRT1_2 * radius; + width = w ? w / 2 : size; + ctx.rect(x - width, y - size, 2 * width, 2 * size); + break; + } + rad += QUARTER_PI; + /* falls through */ case 'rectRot': + xOffsetW = Math.cos(rad) * (w ? w / 2 : radius); + xOffset = Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + yOffsetW = Math.sin(rad) * (w ? w / 2 : radius); + ctx.moveTo(x - xOffsetW, y - yOffset); + ctx.lineTo(x + yOffsetW, y - xOffset); + ctx.lineTo(x + xOffsetW, y + yOffset); + ctx.lineTo(x - yOffsetW, y + xOffset); + ctx.closePath(); + break; + case 'crossRot': + rad += QUARTER_PI; + /* falls through */ case 'cross': + xOffsetW = Math.cos(rad) * (w ? w / 2 : radius); + xOffset = Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + yOffsetW = Math.sin(rad) * (w ? w / 2 : radius); + ctx.moveTo(x - xOffsetW, y - yOffset); + ctx.lineTo(x + xOffsetW, y + yOffset); + ctx.moveTo(x + yOffsetW, y - xOffset); + ctx.lineTo(x - yOffsetW, y + xOffset); + break; + case 'star': + xOffsetW = Math.cos(rad) * (w ? w / 2 : radius); + xOffset = Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + yOffsetW = Math.sin(rad) * (w ? w / 2 : radius); + ctx.moveTo(x - xOffsetW, y - yOffset); + ctx.lineTo(x + xOffsetW, y + yOffset); + ctx.moveTo(x + yOffsetW, y - xOffset); + ctx.lineTo(x - yOffsetW, y + xOffset); + rad += QUARTER_PI; + xOffsetW = Math.cos(rad) * (w ? w / 2 : radius); + xOffset = Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + yOffsetW = Math.sin(rad) * (w ? w / 2 : radius); + ctx.moveTo(x - xOffsetW, y - yOffset); + ctx.lineTo(x + xOffsetW, y + yOffset); + ctx.moveTo(x + yOffsetW, y - xOffset); + ctx.lineTo(x - yOffsetW, y + xOffset); + break; + case 'line': + xOffset = w ? w / 2 : Math.cos(rad) * radius; + yOffset = Math.sin(rad) * radius; + ctx.moveTo(x - xOffset, y - yOffset); + ctx.lineTo(x + xOffset, y + yOffset); + break; + case 'dash': + ctx.moveTo(x, y); + ctx.lineTo(x + Math.cos(rad) * (w ? w / 2 : radius), y + Math.sin(rad) * radius); + break; + case false: + ctx.closePath(); + break; + } + ctx.fill(); + if (options.borderWidth > 0) { + ctx.stroke(); + } +} +/** + * Returns true if the point is inside the rectangle + * @param point - The point to test + * @param area - The rectangle + * @param margin - allowed margin + * @private + */ function _isPointInArea(point, area, margin) { + margin = margin || 0.5; // margin - default is to match rounded decimals + return !area || point && point.x > area.left - margin && point.x < area.right + margin && point.y > area.top - margin && point.y < area.bottom + margin; +} +function clipArea(ctx, area) { + ctx.save(); + ctx.beginPath(); + ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top); + ctx.clip(); +} +function unclipArea(ctx) { + ctx.restore(); +} +/** + * @private + */ function _steppedLineTo(ctx, previous, target, flip, mode) { + if (!previous) { + return ctx.lineTo(target.x, target.y); + } + if (mode === 'middle') { + const midpoint = (previous.x + target.x) / 2.0; + ctx.lineTo(midpoint, previous.y); + ctx.lineTo(midpoint, target.y); + } else if (mode === 'after' !== !!flip) { + ctx.lineTo(previous.x, target.y); + } else { + ctx.lineTo(target.x, previous.y); + } + ctx.lineTo(target.x, target.y); +} +/** + * @private + */ function _bezierCurveTo(ctx, previous, target, flip) { + if (!previous) { + return ctx.lineTo(target.x, target.y); + } + ctx.bezierCurveTo(flip ? previous.cp1x : previous.cp2x, flip ? previous.cp1y : previous.cp2y, flip ? target.cp2x : target.cp1x, flip ? target.cp2y : target.cp1y, target.x, target.y); +} +function setRenderOpts(ctx, opts) { + if (opts.translation) { + ctx.translate(opts.translation[0], opts.translation[1]); + } + if (!isNullOrUndef(opts.rotation)) { + ctx.rotate(opts.rotation); + } + if (opts.color) { + ctx.fillStyle = opts.color; + } + if (opts.textAlign) { + ctx.textAlign = opts.textAlign; + } + if (opts.textBaseline) { + ctx.textBaseline = opts.textBaseline; + } +} +function decorateText(ctx, x, y, line, opts) { + if (opts.strikethrough || opts.underline) { + /** + * Now that IE11 support has been dropped, we can use more + * of the TextMetrics object. The actual bounding boxes + * are unflagged in Chrome, Firefox, Edge, and Safari so they + * can be safely used. + * See https://developer.mozilla.org/en-US/docs/Web/API/TextMetrics#Browser_compatibility + */ const metrics = ctx.measureText(line); + const left = x - metrics.actualBoundingBoxLeft; + const right = x + metrics.actualBoundingBoxRight; + const top = y - metrics.actualBoundingBoxAscent; + const bottom = y + metrics.actualBoundingBoxDescent; + const yDecoration = opts.strikethrough ? (top + bottom) / 2 : bottom; + ctx.strokeStyle = ctx.fillStyle; + ctx.beginPath(); + ctx.lineWidth = opts.decorationWidth || 2; + ctx.moveTo(left, yDecoration); + ctx.lineTo(right, yDecoration); + ctx.stroke(); + } +} +function drawBackdrop(ctx, opts) { + const oldColor = ctx.fillStyle; + ctx.fillStyle = opts.color; + ctx.fillRect(opts.left, opts.top, opts.width, opts.height); + ctx.fillStyle = oldColor; +} +/** + * Render text onto the canvas + */ function renderText(ctx, text, x, y, font, opts = {}) { + const lines = isArray(text) ? text : [ + text + ]; + const stroke = opts.strokeWidth > 0 && opts.strokeColor !== ''; + let i, line; + ctx.save(); + ctx.font = font.string; + setRenderOpts(ctx, opts); + for(i = 0; i < lines.length; ++i){ + line = lines[i]; + if (opts.backdrop) { + drawBackdrop(ctx, opts.backdrop); + } + if (stroke) { + if (opts.strokeColor) { + ctx.strokeStyle = opts.strokeColor; + } + if (!isNullOrUndef(opts.strokeWidth)) { + ctx.lineWidth = opts.strokeWidth; + } + ctx.strokeText(line, x, y, opts.maxWidth); + } + ctx.fillText(line, x, y, opts.maxWidth); + decorateText(ctx, x, y, line, opts); + y += Number(font.lineHeight); + } + ctx.restore(); +} +/** + * Add a path of a rectangle with rounded corners to the current sub-path + * @param ctx - Context + * @param rect - Bounding rect + */ function addRoundedRectPath(ctx, rect) { + const { x , y , w , h , radius } = rect; + // top left arc + ctx.arc(x + radius.topLeft, y + radius.topLeft, radius.topLeft, 1.5 * PI, PI, true); + // line from top left to bottom left + ctx.lineTo(x, y + h - radius.bottomLeft); + // bottom left arc + ctx.arc(x + radius.bottomLeft, y + h - radius.bottomLeft, radius.bottomLeft, PI, HALF_PI, true); + // line from bottom left to bottom right + ctx.lineTo(x + w - radius.bottomRight, y + h); + // bottom right arc + ctx.arc(x + w - radius.bottomRight, y + h - radius.bottomRight, radius.bottomRight, HALF_PI, 0, true); + // line from bottom right to top right + ctx.lineTo(x + w, y + radius.topRight); + // top right arc + ctx.arc(x + w - radius.topRight, y + radius.topRight, radius.topRight, 0, -HALF_PI, true); + // line from top right to top left + ctx.lineTo(x + radius.topLeft, y); +} + +const LINE_HEIGHT = /^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/; +const FONT_STYLE = /^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/; +/** + * @alias Chart.helpers.options + * @namespace + */ /** + * Converts the given line height `value` in pixels for a specific font `size`. + * @param value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em'). + * @param size - The font size (in pixels) used to resolve relative `value`. + * @returns The effective line height in pixels (size * 1.2 if value is invalid). + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height + * @since 2.7.0 + */ function toLineHeight(value, size) { + const matches = ('' + value).match(LINE_HEIGHT); + if (!matches || matches[1] === 'normal') { + return size * 1.2; + } + value = +matches[2]; + switch(matches[3]){ + case 'px': + return value; + case '%': + value /= 100; + break; + } + return size * value; +} +const numberOrZero = (v)=>+v || 0; +function _readValueToProps(value, props) { + const ret = {}; + const objProps = isObject(props); + const keys = objProps ? Object.keys(props) : props; + const read = isObject(value) ? objProps ? (prop)=>valueOrDefault(value[prop], value[props[prop]]) : (prop)=>value[prop] : ()=>value; + for (const prop of keys){ + ret[prop] = numberOrZero(read(prop)); + } + return ret; +} +/** + * Converts the given value into a TRBL object. + * @param value - If a number, set the value to all TRBL component, + * else, if an object, use defined properties and sets undefined ones to 0. + * x / y are shorthands for same value for left/right and top/bottom. + * @returns The padding values (top, right, bottom, left) + * @since 3.0.0 + */ function toTRBL(value) { + return _readValueToProps(value, { + top: 'y', + right: 'x', + bottom: 'y', + left: 'x' + }); +} +/** + * Converts the given value into a TRBL corners object (similar with css border-radius). + * @param value - If a number, set the value to all TRBL corner components, + * else, if an object, use defined properties and sets undefined ones to 0. + * @returns The TRBL corner values (topLeft, topRight, bottomLeft, bottomRight) + * @since 3.0.0 + */ function toTRBLCorners(value) { + return _readValueToProps(value, [ + 'topLeft', + 'topRight', + 'bottomLeft', + 'bottomRight' + ]); +} +/** + * Converts the given value into a padding object with pre-computed width/height. + * @param value - If a number, set the value to all TRBL component, + * else, if an object, use defined properties and sets undefined ones to 0. + * x / y are shorthands for same value for left/right and top/bottom. + * @returns The padding values (top, right, bottom, left, width, height) + * @since 2.7.0 + */ function toPadding(value) { + const obj = toTRBL(value); + obj.width = obj.left + obj.right; + obj.height = obj.top + obj.bottom; + return obj; +} +/** + * Parses font options and returns the font object. + * @param options - A object that contains font options to be parsed. + * @param fallback - A object that contains fallback font options. + * @return The font object. + * @private + */ function toFont(options, fallback) { + options = options || {}; + fallback = fallback || defaults.font; + let size = valueOrDefault(options.size, fallback.size); + if (typeof size === 'string') { + size = parseInt(size, 10); + } + let style = valueOrDefault(options.style, fallback.style); + if (style && !('' + style).match(FONT_STYLE)) { + console.warn('Invalid font style specified: "' + style + '"'); + style = undefined; + } + const font = { + family: valueOrDefault(options.family, fallback.family), + lineHeight: toLineHeight(valueOrDefault(options.lineHeight, fallback.lineHeight), size), + size, + style, + weight: valueOrDefault(options.weight, fallback.weight), + string: '' + }; + font.string = toFontString(font); + return font; +} +/** + * Evaluates the given `inputs` sequentially and returns the first defined value. + * @param inputs - An array of values, falling back to the last value. + * @param context - If defined and the current value is a function, the value + * is called with `context` as first argument and the result becomes the new input. + * @param index - If defined and the current value is an array, the value + * at `index` become the new input. + * @param info - object to return information about resolution in + * @param info.cacheable - Will be set to `false` if option is not cacheable. + * @since 2.7.0 + */ function resolve(inputs, context, index, info) { + let cacheable = true; + let i, ilen, value; + for(i = 0, ilen = inputs.length; i < ilen; ++i){ + value = inputs[i]; + if (value === undefined) { + continue; + } + if (context !== undefined && typeof value === 'function') { + value = value(context); + cacheable = false; + } + if (index !== undefined && isArray(value)) { + value = value[index % value.length]; + cacheable = false; + } + if (value !== undefined) { + if (info && !cacheable) { + info.cacheable = false; + } + return value; + } + } +} +/** + * @param minmax + * @param grace + * @param beginAtZero + * @private + */ function _addGrace(minmax, grace, beginAtZero) { + const { min , max } = minmax; + const change = toDimension(grace, (max - min) / 2); + const keepZero = (value, add)=>beginAtZero && value === 0 ? 0 : value + add; + return { + min: keepZero(min, -Math.abs(change)), + max: keepZero(max, change) + }; +} +function createContext(parentContext, context) { + return Object.assign(Object.create(parentContext), context); +} + +/** + * Creates a Proxy for resolving raw values for options. + * @param scopes - The option scopes to look for values, in resolution order + * @param prefixes - The prefixes for values, in resolution order. + * @param rootScopes - The root option scopes + * @param fallback - Parent scopes fallback + * @param getTarget - callback for getting the target for changed values + * @returns Proxy + * @private + */ function _createResolver(scopes, prefixes = [ + '' +], rootScopes, fallback, getTarget = ()=>scopes[0]) { + const finalRootScopes = rootScopes || scopes; + if (typeof fallback === 'undefined') { + fallback = _resolve('_fallback', scopes); + } + const cache = { + [Symbol.toStringTag]: 'Object', + _cacheable: true, + _scopes: scopes, + _rootScopes: finalRootScopes, + _fallback: fallback, + _getTarget: getTarget, + override: (scope)=>_createResolver([ + scope, + ...scopes + ], prefixes, finalRootScopes, fallback) + }; + return new Proxy(cache, { + /** + * A trap for the delete operator. + */ deleteProperty (target, prop) { + delete target[prop]; // remove from cache + delete target._keys; // remove cached keys + delete scopes[0][prop]; // remove from top level scope + return true; + }, + /** + * A trap for getting property values. + */ get (target, prop) { + return _cached(target, prop, ()=>_resolveWithPrefixes(prop, prefixes, scopes, target)); + }, + /** + * A trap for Object.getOwnPropertyDescriptor. + * Also used by Object.hasOwnProperty. + */ getOwnPropertyDescriptor (target, prop) { + return Reflect.getOwnPropertyDescriptor(target._scopes[0], prop); + }, + /** + * A trap for Object.getPrototypeOf. + */ getPrototypeOf () { + return Reflect.getPrototypeOf(scopes[0]); + }, + /** + * A trap for the in operator. + */ has (target, prop) { + return getKeysFromAllScopes(target).includes(prop); + }, + /** + * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols. + */ ownKeys (target) { + return getKeysFromAllScopes(target); + }, + /** + * A trap for setting property values. + */ set (target, prop, value) { + const storage = target._storage || (target._storage = getTarget()); + target[prop] = storage[prop] = value; // set to top level scope + cache + delete target._keys; // remove cached keys + return true; + } + }); +} +/** + * Returns an Proxy for resolving option values with context. + * @param proxy - The Proxy returned by `_createResolver` + * @param context - Context object for scriptable/indexable options + * @param subProxy - The proxy provided for scriptable options + * @param descriptorDefaults - Defaults for descriptors + * @private + */ function _attachContext(proxy, context, subProxy, descriptorDefaults) { + const cache = { + _cacheable: false, + _proxy: proxy, + _context: context, + _subProxy: subProxy, + _stack: new Set(), + _descriptors: _descriptors(proxy, descriptorDefaults), + setContext: (ctx)=>_attachContext(proxy, ctx, subProxy, descriptorDefaults), + override: (scope)=>_attachContext(proxy.override(scope), context, subProxy, descriptorDefaults) + }; + return new Proxy(cache, { + /** + * A trap for the delete operator. + */ deleteProperty (target, prop) { + delete target[prop]; // remove from cache + delete proxy[prop]; // remove from proxy + return true; + }, + /** + * A trap for getting property values. + */ get (target, prop, receiver) { + return _cached(target, prop, ()=>_resolveWithContext(target, prop, receiver)); + }, + /** + * A trap for Object.getOwnPropertyDescriptor. + * Also used by Object.hasOwnProperty. + */ getOwnPropertyDescriptor (target, prop) { + return target._descriptors.allKeys ? Reflect.has(proxy, prop) ? { + enumerable: true, + configurable: true + } : undefined : Reflect.getOwnPropertyDescriptor(proxy, prop); + }, + /** + * A trap for Object.getPrototypeOf. + */ getPrototypeOf () { + return Reflect.getPrototypeOf(proxy); + }, + /** + * A trap for the in operator. + */ has (target, prop) { + return Reflect.has(proxy, prop); + }, + /** + * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols. + */ ownKeys () { + return Reflect.ownKeys(proxy); + }, + /** + * A trap for setting property values. + */ set (target, prop, value) { + proxy[prop] = value; // set to proxy + delete target[prop]; // remove from cache + return true; + } + }); +} +/** + * @private + */ function _descriptors(proxy, defaults = { + scriptable: true, + indexable: true +}) { + const { _scriptable =defaults.scriptable , _indexable =defaults.indexable , _allKeys =defaults.allKeys } = proxy; + return { + allKeys: _allKeys, + scriptable: _scriptable, + indexable: _indexable, + isScriptable: isFunction(_scriptable) ? _scriptable : ()=>_scriptable, + isIndexable: isFunction(_indexable) ? _indexable : ()=>_indexable + }; +} +const readKey = (prefix, name)=>prefix ? prefix + _capitalize(name) : name; +const needsSubResolver = (prop, value)=>isObject(value) && prop !== 'adapters' && (Object.getPrototypeOf(value) === null || value.constructor === Object); +function _cached(target, prop, resolve) { + if (Object.prototype.hasOwnProperty.call(target, prop) || prop === 'constructor') { + return target[prop]; + } + const value = resolve(); + // cache the resolved value + target[prop] = value; + return value; +} +function _resolveWithContext(target, prop, receiver) { + const { _proxy , _context , _subProxy , _descriptors: descriptors } = target; + let value = _proxy[prop]; // resolve from proxy + // resolve with context + if (isFunction(value) && descriptors.isScriptable(prop)) { + value = _resolveScriptable(prop, value, target, receiver); + } + if (isArray(value) && value.length) { + value = _resolveArray(prop, value, target, descriptors.isIndexable); + } + if (needsSubResolver(prop, value)) { + // if the resolved value is an object, create a sub resolver for it + value = _attachContext(value, _context, _subProxy && _subProxy[prop], descriptors); + } + return value; +} +function _resolveScriptable(prop, getValue, target, receiver) { + const { _proxy , _context , _subProxy , _stack } = target; + if (_stack.has(prop)) { + throw new Error('Recursion detected: ' + Array.from(_stack).join('->') + '->' + prop); + } + _stack.add(prop); + let value = getValue(_context, _subProxy || receiver); + _stack.delete(prop); + if (needsSubResolver(prop, value)) { + // When scriptable option returns an object, create a resolver on that. + value = createSubResolver(_proxy._scopes, _proxy, prop, value); + } + return value; +} +function _resolveArray(prop, value, target, isIndexable) { + const { _proxy , _context , _subProxy , _descriptors: descriptors } = target; + if (typeof _context.index !== 'undefined' && isIndexable(prop)) { + return value[_context.index % value.length]; + } else if (isObject(value[0])) { + // Array of objects, return array or resolvers + const arr = value; + const scopes = _proxy._scopes.filter((s)=>s !== arr); + value = []; + for (const item of arr){ + const resolver = createSubResolver(scopes, _proxy, prop, item); + value.push(_attachContext(resolver, _context, _subProxy && _subProxy[prop], descriptors)); + } + } + return value; +} +function resolveFallback(fallback, prop, value) { + return isFunction(fallback) ? fallback(prop, value) : fallback; +} +const getScope = (key, parent)=>key === true ? parent : typeof key === 'string' ? resolveObjectKey(parent, key) : undefined; +function addScopes(set, parentScopes, key, parentFallback, value) { + for (const parent of parentScopes){ + const scope = getScope(key, parent); + if (scope) { + set.add(scope); + const fallback = resolveFallback(scope._fallback, key, value); + if (typeof fallback !== 'undefined' && fallback !== key && fallback !== parentFallback) { + // When we reach the descriptor that defines a new _fallback, return that. + // The fallback will resume to that new scope. + return fallback; + } + } else if (scope === false && typeof parentFallback !== 'undefined' && key !== parentFallback) { + // Fallback to `false` results to `false`, when falling back to different key. + // For example `interaction` from `hover` or `plugins.tooltip` and `animation` from `animations` + return null; + } + } + return false; +} +function createSubResolver(parentScopes, resolver, prop, value) { + const rootScopes = resolver._rootScopes; + const fallback = resolveFallback(resolver._fallback, prop, value); + const allScopes = [ + ...parentScopes, + ...rootScopes + ]; + const set = new Set(); + set.add(value); + let key = addScopesFromKey(set, allScopes, prop, fallback || prop, value); + if (key === null) { + return false; + } + if (typeof fallback !== 'undefined' && fallback !== prop) { + key = addScopesFromKey(set, allScopes, fallback, key, value); + if (key === null) { + return false; + } + } + return _createResolver(Array.from(set), [ + '' + ], rootScopes, fallback, ()=>subGetTarget(resolver, prop, value)); +} +function addScopesFromKey(set, allScopes, key, fallback, item) { + while(key){ + key = addScopes(set, allScopes, key, fallback, item); + } + return key; +} +function subGetTarget(resolver, prop, value) { + const parent = resolver._getTarget(); + if (!(prop in parent)) { + parent[prop] = {}; + } + const target = parent[prop]; + if (isArray(target) && isObject(value)) { + // For array of objects, the object is used to store updated values + return value; + } + return target || {}; +} +function _resolveWithPrefixes(prop, prefixes, scopes, proxy) { + let value; + for (const prefix of prefixes){ + value = _resolve(readKey(prefix, prop), scopes); + if (typeof value !== 'undefined') { + return needsSubResolver(prop, value) ? createSubResolver(scopes, proxy, prop, value) : value; + } + } +} +function _resolve(key, scopes) { + for (const scope of scopes){ + if (!scope) { + continue; + } + const value = scope[key]; + if (typeof value !== 'undefined') { + return value; + } + } +} +function getKeysFromAllScopes(target) { + let keys = target._keys; + if (!keys) { + keys = target._keys = resolveKeysFromAllScopes(target._scopes); + } + return keys; +} +function resolveKeysFromAllScopes(scopes) { + const set = new Set(); + for (const scope of scopes){ + for (const key of Object.keys(scope).filter((k)=>!k.startsWith('_'))){ + set.add(key); + } + } + return Array.from(set); +} +function _parseObjectDataRadialScale(meta, data, start, count) { + const { iScale } = meta; + const { key ='r' } = this._parsing; + const parsed = new Array(count); + let i, ilen, index, item; + for(i = 0, ilen = count; i < ilen; ++i){ + index = i + start; + item = data[index]; + parsed[i] = { + r: iScale.parse(resolveObjectKey(item, key), index) + }; + } + return parsed; +} + +const EPSILON = Number.EPSILON || 1e-14; +const getPoint = (points, i)=>i < points.length && !points[i].skip && points[i]; +const getValueAxis = (indexAxis)=>indexAxis === 'x' ? 'y' : 'x'; +function splineCurve(firstPoint, middlePoint, afterPoint, t) { + // Props to Rob Spencer at scaled innovation for his post on splining between points + // http://scaledinnovation.com/analytics/splines/aboutSplines.html + // This function must also respect "skipped" points + const previous = firstPoint.skip ? middlePoint : firstPoint; + const current = middlePoint; + const next = afterPoint.skip ? middlePoint : afterPoint; + const d01 = distanceBetweenPoints(current, previous); + const d12 = distanceBetweenPoints(next, current); + let s01 = d01 / (d01 + d12); + let s12 = d12 / (d01 + d12); + // If all points are the same, s01 & s02 will be inf + s01 = isNaN(s01) ? 0 : s01; + s12 = isNaN(s12) ? 0 : s12; + const fa = t * s01; // scaling factor for triangle Ta + const fb = t * s12; + return { + previous: { + x: current.x - fa * (next.x - previous.x), + y: current.y - fa * (next.y - previous.y) + }, + next: { + x: current.x + fb * (next.x - previous.x), + y: current.y + fb * (next.y - previous.y) + } + }; +} +/** + * Adjust tangents to ensure monotonic properties + */ function monotoneAdjust(points, deltaK, mK) { + const pointsLen = points.length; + let alphaK, betaK, tauK, squaredMagnitude, pointCurrent; + let pointAfter = getPoint(points, 0); + for(let i = 0; i < pointsLen - 1; ++i){ + pointCurrent = pointAfter; + pointAfter = getPoint(points, i + 1); + if (!pointCurrent || !pointAfter) { + continue; + } + if (almostEquals(deltaK[i], 0, EPSILON)) { + mK[i] = mK[i + 1] = 0; + continue; + } + alphaK = mK[i] / deltaK[i]; + betaK = mK[i + 1] / deltaK[i]; + squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2); + if (squaredMagnitude <= 9) { + continue; + } + tauK = 3 / Math.sqrt(squaredMagnitude); + mK[i] = alphaK * tauK * deltaK[i]; + mK[i + 1] = betaK * tauK * deltaK[i]; + } +} +function monotoneCompute(points, mK, indexAxis = 'x') { + const valueAxis = getValueAxis(indexAxis); + const pointsLen = points.length; + let delta, pointBefore, pointCurrent; + let pointAfter = getPoint(points, 0); + for(let i = 0; i < pointsLen; ++i){ + pointBefore = pointCurrent; + pointCurrent = pointAfter; + pointAfter = getPoint(points, i + 1); + if (!pointCurrent) { + continue; + } + const iPixel = pointCurrent[indexAxis]; + const vPixel = pointCurrent[valueAxis]; + if (pointBefore) { + delta = (iPixel - pointBefore[indexAxis]) / 3; + pointCurrent[`cp1${indexAxis}`] = iPixel - delta; + pointCurrent[`cp1${valueAxis}`] = vPixel - delta * mK[i]; + } + if (pointAfter) { + delta = (pointAfter[indexAxis] - iPixel) / 3; + pointCurrent[`cp2${indexAxis}`] = iPixel + delta; + pointCurrent[`cp2${valueAxis}`] = vPixel + delta * mK[i]; + } + } +} +/** + * This function calculates Bézier control points in a similar way than |splineCurve|, + * but preserves monotonicity of the provided data and ensures no local extremums are added + * between the dataset discrete points due to the interpolation. + * See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation + */ function splineCurveMonotone(points, indexAxis = 'x') { + const valueAxis = getValueAxis(indexAxis); + const pointsLen = points.length; + const deltaK = Array(pointsLen).fill(0); + const mK = Array(pointsLen); + // Calculate slopes (deltaK) and initialize tangents (mK) + let i, pointBefore, pointCurrent; + let pointAfter = getPoint(points, 0); + for(i = 0; i < pointsLen; ++i){ + pointBefore = pointCurrent; + pointCurrent = pointAfter; + pointAfter = getPoint(points, i + 1); + if (!pointCurrent) { + continue; + } + if (pointAfter) { + const slopeDelta = pointAfter[indexAxis] - pointCurrent[indexAxis]; + // In the case of two points that appear at the same x pixel, slopeDeltaX is 0 + deltaK[i] = slopeDelta !== 0 ? (pointAfter[valueAxis] - pointCurrent[valueAxis]) / slopeDelta : 0; + } + mK[i] = !pointBefore ? deltaK[i] : !pointAfter ? deltaK[i - 1] : sign(deltaK[i - 1]) !== sign(deltaK[i]) ? 0 : (deltaK[i - 1] + deltaK[i]) / 2; + } + monotoneAdjust(points, deltaK, mK); + monotoneCompute(points, mK, indexAxis); +} +function capControlPoint(pt, min, max) { + return Math.max(Math.min(pt, max), min); +} +function capBezierPoints(points, area) { + let i, ilen, point, inArea, inAreaPrev; + let inAreaNext = _isPointInArea(points[0], area); + for(i = 0, ilen = points.length; i < ilen; ++i){ + inAreaPrev = inArea; + inArea = inAreaNext; + inAreaNext = i < ilen - 1 && _isPointInArea(points[i + 1], area); + if (!inArea) { + continue; + } + point = points[i]; + if (inAreaPrev) { + point.cp1x = capControlPoint(point.cp1x, area.left, area.right); + point.cp1y = capControlPoint(point.cp1y, area.top, area.bottom); + } + if (inAreaNext) { + point.cp2x = capControlPoint(point.cp2x, area.left, area.right); + point.cp2y = capControlPoint(point.cp2y, area.top, area.bottom); + } + } +} +/** + * @private + */ function _updateBezierControlPoints(points, options, area, loop, indexAxis) { + let i, ilen, point, controlPoints; + // Only consider points that are drawn in case the spanGaps option is used + if (options.spanGaps) { + points = points.filter((pt)=>!pt.skip); + } + if (options.cubicInterpolationMode === 'monotone') { + splineCurveMonotone(points, indexAxis); + } else { + let prev = loop ? points[points.length - 1] : points[0]; + for(i = 0, ilen = points.length; i < ilen; ++i){ + point = points[i]; + controlPoints = splineCurve(prev, point, points[Math.min(i + 1, ilen - (loop ? 0 : 1)) % ilen], options.tension); + point.cp1x = controlPoints.previous.x; + point.cp1y = controlPoints.previous.y; + point.cp2x = controlPoints.next.x; + point.cp2y = controlPoints.next.y; + prev = point; + } + } + if (options.capBezierPoints) { + capBezierPoints(points, area); + } +} + +/** + * @private + */ function _isDomSupported() { + return typeof window !== 'undefined' && typeof document !== 'undefined'; +} +/** + * @private + */ function _getParentNode(domNode) { + let parent = domNode.parentNode; + if (parent && parent.toString() === '[object ShadowRoot]') { + parent = parent.host; + } + return parent; +} +/** + * convert max-width/max-height values that may be percentages into a number + * @private + */ function parseMaxStyle(styleValue, node, parentProperty) { + let valueInPixels; + if (typeof styleValue === 'string') { + valueInPixels = parseInt(styleValue, 10); + if (styleValue.indexOf('%') !== -1) { + // percentage * size in dimension + valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty]; + } + } else { + valueInPixels = styleValue; + } + return valueInPixels; +} +const getComputedStyle = (element)=>element.ownerDocument.defaultView.getComputedStyle(element, null); +function getStyle(el, property) { + return getComputedStyle(el).getPropertyValue(property); +} +const positions = [ + 'top', + 'right', + 'bottom', + 'left' +]; +function getPositionedStyle(styles, style, suffix) { + const result = {}; + suffix = suffix ? '-' + suffix : ''; + for(let i = 0; i < 4; i++){ + const pos = positions[i]; + result[pos] = parseFloat(styles[style + '-' + pos + suffix]) || 0; + } + result.width = result.left + result.right; + result.height = result.top + result.bottom; + return result; +} +const useOffsetPos = (x, y, target)=>(x > 0 || y > 0) && (!target || !target.shadowRoot); +/** + * @param e + * @param canvas + * @returns Canvas position + */ function getCanvasPosition(e, canvas) { + const touches = e.touches; + const source = touches && touches.length ? touches[0] : e; + const { offsetX , offsetY } = source; + let box = false; + let x, y; + if (useOffsetPos(offsetX, offsetY, e.target)) { + x = offsetX; + y = offsetY; + } else { + const rect = canvas.getBoundingClientRect(); + x = source.clientX - rect.left; + y = source.clientY - rect.top; + box = true; + } + return { + x, + y, + box + }; +} +/** + * Gets an event's x, y coordinates, relative to the chart area + * @param event + * @param chart + * @returns x and y coordinates of the event + */ function getRelativePosition(event, chart) { + if ('native' in event) { + return event; + } + const { canvas , currentDevicePixelRatio } = chart; + const style = getComputedStyle(canvas); + const borderBox = style.boxSizing === 'border-box'; + const paddings = getPositionedStyle(style, 'padding'); + const borders = getPositionedStyle(style, 'border', 'width'); + const { x , y , box } = getCanvasPosition(event, canvas); + const xOffset = paddings.left + (box && borders.left); + const yOffset = paddings.top + (box && borders.top); + let { width , height } = chart; + if (borderBox) { + width -= paddings.width + borders.width; + height -= paddings.height + borders.height; + } + return { + x: Math.round((x - xOffset) / width * canvas.width / currentDevicePixelRatio), + y: Math.round((y - yOffset) / height * canvas.height / currentDevicePixelRatio) + }; +} +function getContainerSize(canvas, width, height) { + let maxWidth, maxHeight; + if (width === undefined || height === undefined) { + const container = canvas && _getParentNode(canvas); + if (!container) { + width = canvas.clientWidth; + height = canvas.clientHeight; + } else { + const rect = container.getBoundingClientRect(); // this is the border box of the container + const containerStyle = getComputedStyle(container); + const containerBorder = getPositionedStyle(containerStyle, 'border', 'width'); + const containerPadding = getPositionedStyle(containerStyle, 'padding'); + width = rect.width - containerPadding.width - containerBorder.width; + height = rect.height - containerPadding.height - containerBorder.height; + maxWidth = parseMaxStyle(containerStyle.maxWidth, container, 'clientWidth'); + maxHeight = parseMaxStyle(containerStyle.maxHeight, container, 'clientHeight'); + } + } + return { + width, + height, + maxWidth: maxWidth || INFINITY, + maxHeight: maxHeight || INFINITY + }; +} +const round1 = (v)=>Math.round(v * 10) / 10; +// eslint-disable-next-line complexity +function getMaximumSize(canvas, bbWidth, bbHeight, aspectRatio) { + const style = getComputedStyle(canvas); + const margins = getPositionedStyle(style, 'margin'); + const maxWidth = parseMaxStyle(style.maxWidth, canvas, 'clientWidth') || INFINITY; + const maxHeight = parseMaxStyle(style.maxHeight, canvas, 'clientHeight') || INFINITY; + const containerSize = getContainerSize(canvas, bbWidth, bbHeight); + let { width , height } = containerSize; + if (style.boxSizing === 'content-box') { + const borders = getPositionedStyle(style, 'border', 'width'); + const paddings = getPositionedStyle(style, 'padding'); + width -= paddings.width + borders.width; + height -= paddings.height + borders.height; + } + width = Math.max(0, width - margins.width); + height = Math.max(0, aspectRatio ? width / aspectRatio : height - margins.height); + width = round1(Math.min(width, maxWidth, containerSize.maxWidth)); + height = round1(Math.min(height, maxHeight, containerSize.maxHeight)); + if (width && !height) { + // https://github.com/chartjs/Chart.js/issues/4659 + // If the canvas has width, but no height, default to aspectRatio of 2 (canvas default) + height = round1(width / 2); + } + const maintainHeight = bbWidth !== undefined || bbHeight !== undefined; + if (maintainHeight && aspectRatio && containerSize.height && height > containerSize.height) { + height = containerSize.height; + width = round1(Math.floor(height * aspectRatio)); + } + return { + width, + height + }; +} +/** + * @param chart + * @param forceRatio + * @param forceStyle + * @returns True if the canvas context size or transformation has changed. + */ function retinaScale(chart, forceRatio, forceStyle) { + const pixelRatio = forceRatio || 1; + const deviceHeight = Math.floor(chart.height * pixelRatio); + const deviceWidth = Math.floor(chart.width * pixelRatio); + chart.height = Math.floor(chart.height); + chart.width = Math.floor(chart.width); + const canvas = chart.canvas; + // If no style has been set on the canvas, the render size is used as display size, + // making the chart visually bigger, so let's enforce it to the "correct" values. + // See https://github.com/chartjs/Chart.js/issues/3575 + if (canvas.style && (forceStyle || !canvas.style.height && !canvas.style.width)) { + canvas.style.height = `${chart.height}px`; + canvas.style.width = `${chart.width}px`; + } + if (chart.currentDevicePixelRatio !== pixelRatio || canvas.height !== deviceHeight || canvas.width !== deviceWidth) { + chart.currentDevicePixelRatio = pixelRatio; + canvas.height = deviceHeight; + canvas.width = deviceWidth; + chart.ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); + return true; + } + return false; +} +/** + * Detects support for options object argument in addEventListener. + * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support + * @private + */ const supportsEventListenerOptions = function() { + let passiveSupported = false; + try { + const options = { + get passive () { + passiveSupported = true; + return false; + } + }; + if (_isDomSupported()) { + window.addEventListener('test', null, options); + window.removeEventListener('test', null, options); + } + } catch (e) { + // continue regardless of error + } + return passiveSupported; +}(); +/** + * The "used" size is the final value of a dimension property after all calculations have + * been performed. This method uses the computed style of `element` but returns undefined + * if the computed style is not expressed in pixels. That can happen in some cases where + * `element` has a size relative to its parent and this last one is not yet displayed, + * for example because of `display: none` on a parent node. + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value + * @returns Size in pixels or undefined if unknown. + */ function readUsedSize(element, property) { + const value = getStyle(element, property); + const matches = value && value.match(/^(\d+)(\.\d+)?px$/); + return matches ? +matches[1] : undefined; +} + +/** + * @private + */ function _pointInLine(p1, p2, t, mode) { + return { + x: p1.x + t * (p2.x - p1.x), + y: p1.y + t * (p2.y - p1.y) + }; +} +/** + * @private + */ function _steppedInterpolation(p1, p2, t, mode) { + return { + x: p1.x + t * (p2.x - p1.x), + y: mode === 'middle' ? t < 0.5 ? p1.y : p2.y : mode === 'after' ? t < 1 ? p1.y : p2.y : t > 0 ? p2.y : p1.y + }; +} +/** + * @private + */ function _bezierInterpolation(p1, p2, t, mode) { + const cp1 = { + x: p1.cp2x, + y: p1.cp2y + }; + const cp2 = { + x: p2.cp1x, + y: p2.cp1y + }; + const a = _pointInLine(p1, cp1, t); + const b = _pointInLine(cp1, cp2, t); + const c = _pointInLine(cp2, p2, t); + const d = _pointInLine(a, b, t); + const e = _pointInLine(b, c, t); + return _pointInLine(d, e, t); +} + +const getRightToLeftAdapter = function(rectX, width) { + return { + x (x) { + return rectX + rectX + width - x; + }, + setWidth (w) { + width = w; + }, + textAlign (align) { + if (align === 'center') { + return align; + } + return align === 'right' ? 'left' : 'right'; + }, + xPlus (x, value) { + return x - value; + }, + leftForLtr (x, itemWidth) { + return x - itemWidth; + } + }; +}; +const getLeftToRightAdapter = function() { + return { + x (x) { + return x; + }, + setWidth (w) {}, + textAlign (align) { + return align; + }, + xPlus (x, value) { + return x + value; + }, + leftForLtr (x, _itemWidth) { + return x; + } + }; +}; +function getRtlAdapter(rtl, rectX, width) { + return rtl ? getRightToLeftAdapter(rectX, width) : getLeftToRightAdapter(); +} +function overrideTextDirection(ctx, direction) { + let style, original; + if (direction === 'ltr' || direction === 'rtl') { + style = ctx.canvas.style; + original = [ + style.getPropertyValue('direction'), + style.getPropertyPriority('direction') + ]; + style.setProperty('direction', direction, 'important'); + ctx.prevTextDirection = original; + } +} +function restoreTextDirection(ctx, original) { + if (original !== undefined) { + delete ctx.prevTextDirection; + ctx.canvas.style.setProperty('direction', original[0], original[1]); + } +} + +function propertyFn(property) { + if (property === 'angle') { + return { + between: _angleBetween, + compare: _angleDiff, + normalize: _normalizeAngle + }; + } + return { + between: _isBetween, + compare: (a, b)=>a - b, + normalize: (x)=>x + }; +} +function normalizeSegment({ start , end , count , loop , style }) { + return { + start: start % count, + end: end % count, + loop: loop && (end - start + 1) % count === 0, + style + }; +} +function getSegment(segment, points, bounds) { + const { property , start: startBound , end: endBound } = bounds; + const { between , normalize } = propertyFn(property); + const count = points.length; + let { start , end , loop } = segment; + let i, ilen; + if (loop) { + start += count; + end += count; + for(i = 0, ilen = count; i < ilen; ++i){ + if (!between(normalize(points[start % count][property]), startBound, endBound)) { + break; + } + start--; + end--; + } + start %= count; + end %= count; + } + if (end < start) { + end += count; + } + return { + start, + end, + loop, + style: segment.style + }; +} + function _boundSegment(segment, points, bounds) { + if (!bounds) { + return [ + segment + ]; + } + const { property , start: startBound , end: endBound } = bounds; + const count = points.length; + const { compare , between , normalize } = propertyFn(property); + const { start , end , loop , style } = getSegment(segment, points, bounds); + const result = []; + let inside = false; + let subStart = null; + let value, point, prevValue; + const startIsBefore = ()=>between(startBound, prevValue, value) && compare(startBound, prevValue) !== 0; + const endIsBefore = ()=>compare(endBound, value) === 0 || between(endBound, prevValue, value); + const shouldStart = ()=>inside || startIsBefore(); + const shouldStop = ()=>!inside || endIsBefore(); + for(let i = start, prev = start; i <= end; ++i){ + point = points[i % count]; + if (point.skip) { + continue; + } + value = normalize(point[property]); + if (value === prevValue) { + continue; + } + inside = between(value, startBound, endBound); + if (subStart === null && shouldStart()) { + subStart = compare(value, startBound) === 0 ? i : prev; + } + if (subStart !== null && shouldStop()) { + result.push(normalizeSegment({ + start: subStart, + end: i, + loop, + count, + style + })); + subStart = null; + } + prev = i; + prevValue = value; + } + if (subStart !== null) { + result.push(normalizeSegment({ + start: subStart, + end, + loop, + count, + style + })); + } + return result; +} + function _boundSegments(line, bounds) { + const result = []; + const segments = line.segments; + for(let i = 0; i < segments.length; i++){ + const sub = _boundSegment(segments[i], line.points, bounds); + if (sub.length) { + result.push(...sub); + } + } + return result; +} + function findStartAndEnd(points, count, loop, spanGaps) { + let start = 0; + let end = count - 1; + if (loop && !spanGaps) { + while(start < count && !points[start].skip){ + start++; + } + } + while(start < count && points[start].skip){ + start++; + } + start %= count; + if (loop) { + end += start; + } + while(end > start && points[end % count].skip){ + end--; + } + end %= count; + return { + start, + end + }; +} + function solidSegments(points, start, max, loop) { + const count = points.length; + const result = []; + let last = start; + let prev = points[start]; + let end; + for(end = start + 1; end <= max; ++end){ + const cur = points[end % count]; + if (cur.skip || cur.stop) { + if (!prev.skip) { + loop = false; + result.push({ + start: start % count, + end: (end - 1) % count, + loop + }); + start = last = cur.stop ? end : null; + } + } else { + last = end; + if (prev.skip) { + start = end; + } + } + prev = cur; + } + if (last !== null) { + result.push({ + start: start % count, + end: last % count, + loop + }); + } + return result; +} + function _computeSegments(line, segmentOptions) { + const points = line.points; + const spanGaps = line.options.spanGaps; + const count = points.length; + if (!count) { + return []; + } + const loop = !!line._loop; + const { start , end } = findStartAndEnd(points, count, loop, spanGaps); + if (spanGaps === true) { + return splitByStyles(line, [ + { + start, + end, + loop + } + ], points, segmentOptions); + } + const max = end < start ? end + count : end; + const completeLoop = !!line._fullLoop && start === 0 && end === count - 1; + return splitByStyles(line, solidSegments(points, start, max, completeLoop), points, segmentOptions); +} + function splitByStyles(line, segments, points, segmentOptions) { + if (!segmentOptions || !segmentOptions.setContext || !points) { + return segments; + } + return doSplitByStyles(line, segments, points, segmentOptions); +} + function doSplitByStyles(line, segments, points, segmentOptions) { + const chartContext = line._chart.getContext(); + const baseStyle = readStyle(line.options); + const { _datasetIndex: datasetIndex , options: { spanGaps } } = line; + const count = points.length; + const result = []; + let prevStyle = baseStyle; + let start = segments[0].start; + let i = start; + function addStyle(s, e, l, st) { + const dir = spanGaps ? -1 : 1; + if (s === e) { + return; + } + s += count; + while(points[s % count].skip){ + s -= dir; + } + while(points[e % count].skip){ + e += dir; + } + if (s % count !== e % count) { + result.push({ + start: s % count, + end: e % count, + loop: l, + style: st + }); + prevStyle = st; + start = e % count; + } + } + for (const segment of segments){ + start = spanGaps ? start : segment.start; + let prev = points[start % count]; + let style; + for(i = start + 1; i <= segment.end; i++){ + const pt = points[i % count]; + style = readStyle(segmentOptions.setContext(createContext(chartContext, { + type: 'segment', + p0: prev, + p1: pt, + p0DataIndex: (i - 1) % count, + p1DataIndex: i % count, + datasetIndex + }))); + if (styleChanged(style, prevStyle)) { + addStyle(start, i - 1, segment.loop, prevStyle); + } + prev = pt; + prevStyle = style; + } + if (start < i - 1) { + addStyle(start, i - 1, segment.loop, prevStyle); + } + } + return result; +} +function readStyle(options) { + return { + backgroundColor: options.backgroundColor, + borderCapStyle: options.borderCapStyle, + borderDash: options.borderDash, + borderDashOffset: options.borderDashOffset, + borderJoinStyle: options.borderJoinStyle, + borderWidth: options.borderWidth, + borderColor: options.borderColor + }; +} +function styleChanged(style, prevStyle) { + if (!prevStyle) { + return false; + } + const cache = []; + const replacer = function(key, value) { + if (!isPatternOrGradient(value)) { + return value; + } + if (!cache.includes(value)) { + cache.push(value); + } + return cache.indexOf(value); + }; + return JSON.stringify(style, replacer) !== JSON.stringify(prevStyle, replacer); +} + +function getSizeForArea(scale, chartArea, field) { + return scale.options.clip ? scale[field] : chartArea[field]; +} +function getDatasetArea(meta, chartArea) { + const { xScale , yScale } = meta; + if (xScale && yScale) { + return { + left: getSizeForArea(xScale, chartArea, 'left'), + right: getSizeForArea(xScale, chartArea, 'right'), + top: getSizeForArea(yScale, chartArea, 'top'), + bottom: getSizeForArea(yScale, chartArea, 'bottom') + }; + } + return chartArea; +} +function getDatasetClipArea(chart, meta) { + const clip = meta._clip; + if (clip.disabled) { + return false; + } + const area = getDatasetArea(meta, chart.chartArea); + return { + left: clip.left === false ? 0 : area.left - (clip.left === true ? 0 : clip.left), + right: clip.right === false ? chart.width : area.right + (clip.right === true ? 0 : clip.right), + top: clip.top === false ? 0 : area.top - (clip.top === true ? 0 : clip.top), + bottom: clip.bottom === false ? chart.height : area.bottom + (clip.bottom === true ? 0 : clip.bottom) + }; +} + +export { unclipArea as $, _rlookupByKey as A, _lookupByKey as B, _isPointInArea as C, getAngleFromPoint as D, toPadding as E, each as F, getMaximumSize as G, HALF_PI as H, _getParentNode as I, readUsedSize as J, supportsEventListenerOptions as K, throttled as L, _isDomSupported as M, _factorize as N, finiteOrDefault as O, PI as P, callback as Q, _addGrace as R, _limitValue as S, TAU as T, toDegrees as U, _measureText as V, _int16Range as W, _alignPixel as X, clipArea as Y, renderText as Z, _arrayUnique as _, resolve as a, getStyle as a$, toFont as a0, _toLeftRightCenter as a1, _alignStartEnd as a2, overrides as a3, merge as a4, _capitalize as a5, descriptors as a6, isFunction as a7, _attachContext as a8, _createResolver as a9, getRtlAdapter as aA, overrideTextDirection as aB, _textX as aC, restoreTextDirection as aD, drawPointLegend as aE, distanceBetweenPoints as aF, noop as aG, _setMinAndMaxByKey as aH, niceNum as aI, almostWhole as aJ, almostEquals as aK, _decimalPlaces as aL, Ticks as aM, log10 as aN, _longestText as aO, _filterBetween as aP, _lookup as aQ, isPatternOrGradient as aR, getHoverColor as aS, clone as aT, _merger as aU, _mergerIf as aV, _deprecated as aW, _splitKey as aX, toFontString as aY, splineCurve as aZ, splineCurveMonotone as a_, _descriptors as aa, mergeIf as ab, uid as ac, debounce as ad, retinaScale as ae, clearCanvas as af, setsEqual as ag, getDatasetClipArea as ah, _elementsEqual as ai, _isClickEvent as aj, _isBetween as ak, _normalizeAngle as al, _readValueToProps as am, _updateBezierControlPoints as an, _computeSegments as ao, _boundSegments as ap, _steppedInterpolation as aq, _bezierInterpolation as ar, _pointInLine as as, _steppedLineTo as at, _bezierCurveTo as au, drawPoint as av, addRoundedRectPath as aw, toTRBL as ax, toTRBLCorners as ay, _boundSegment as az, isArray as b, fontString as b0, toLineHeight as b1, PITAU as b2, INFINITY as b3, RAD_PER_DEG as b4, QUARTER_PI as b5, TWO_THIRDS_PI as b6, _angleDiff as b7, color as c, defaults as d, effects as e, resolveObjectKey as f, isNumberFinite as g, defined as h, isObject as i, createContext as j, isNullOrUndef as k, listenArrayEvents as l, toPercentage as m, toDimension as n, formatNumber as o, _angleBetween as p, _getStartAndCountOfVisiblePoints as q, requestAnimFrame as r, sign as s, toRadians as t, unlistenArrayEvents as u, valueOrDefault as v, _scaleRangesChanged as w, isNumber as x, _parseObjectDataRadialScale as y, getRelativePosition as z }; +//# sourceMappingURL=helpers.dataset.js.map diff --git a/frontend/node_modules/chart.js/dist/chunks/helpers.dataset.js.map b/frontend/node_modules/chart.js/dist/chunks/helpers.dataset.js.map new file mode 100644 index 0000000000000000000000000000000000000000..54223c145bdb01ae50005bbed68cbd25a41e4beb --- /dev/null +++ b/frontend/node_modules/chart.js/dist/chunks/helpers.dataset.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.dataset.js","sources":["../../src/helpers/helpers.core.ts","../../src/helpers/helpers.math.ts","../../src/helpers/helpers.collection.ts","../../src/helpers/helpers.extras.ts","../../src/helpers/helpers.easing.ts","../../src/helpers/helpers.color.ts","../../src/core/core.animations.defaults.js","../../src/core/core.layouts.defaults.js","../../src/helpers/helpers.intl.ts","../../src/core/core.ticks.js","../../src/core/core.scale.defaults.js","../../src/core/core.defaults.js","../../src/helpers/helpers.canvas.ts","../../src/helpers/helpers.options.ts","../../src/helpers/helpers.config.ts","../../src/helpers/helpers.curve.ts","../../src/helpers/helpers.dom.ts","../../src/helpers/helpers.interpolation.ts","../../src/helpers/helpers.rtl.ts","../../src/helpers/helpers.segment.js","../../src/helpers/helpers.dataset.ts"],"sourcesContent":["/**\n * @namespace Chart.helpers\n */\n\nimport type {AnyObject} from '../types/basic.js';\nimport type {ActiveDataPoint, ChartEvent} from '../types/index.js';\n\n/**\n * An empty function that can be used, for example, for optional callback.\n */\nexport function noop() {\n /* noop */\n}\n\n/**\n * Returns a unique id, sequentially generated from a global variable.\n */\nexport const uid = (() => {\n let id = 0;\n return () => id++;\n})();\n\n/**\n * Returns true if `value` is neither null nor undefined, else returns false.\n * @param value - The value to test.\n * @since 2.7.0\n */\nexport function isNullOrUndef(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/**\n * Returns true if `value` is an array (including typed arrays), else returns false.\n * @param value - The value to test.\n * @function\n */\nexport function isArray(value: unknown): value is T[] {\n if (Array.isArray && Array.isArray(value)) {\n return true;\n }\n const type = Object.prototype.toString.call(value);\n if (type.slice(0, 7) === '[object' && type.slice(-6) === 'Array]') {\n return true;\n }\n return false;\n}\n\n/**\n * Returns true if `value` is an object (excluding null), else returns false.\n * @param value - The value to test.\n * @since 2.7.0\n */\nexport function isObject(value: unknown): value is AnyObject {\n return value !== null && Object.prototype.toString.call(value) === '[object Object]';\n}\n\n/**\n * Returns true if `value` is a finite number, else returns false\n * @param value - The value to test.\n */\nfunction isNumberFinite(value: unknown): value is number {\n return (typeof value === 'number' || value instanceof Number) && isFinite(+value);\n}\nexport {\n isNumberFinite as isFinite,\n};\n\n/**\n * Returns `value` if finite, else returns `defaultValue`.\n * @param value - The value to return if defined.\n * @param defaultValue - The value to return if `value` is not finite.\n */\nexport function finiteOrDefault(value: unknown, defaultValue: number) {\n return isNumberFinite(value) ? value : defaultValue;\n}\n\n/**\n * Returns `value` if defined, else returns `defaultValue`.\n * @param value - The value to return if defined.\n * @param defaultValue - The value to return if `value` is undefined.\n */\nexport function valueOrDefault(value: T | undefined, defaultValue: T) {\n return typeof value === 'undefined' ? defaultValue : value;\n}\n\nexport const toPercentage = (value: number | string, dimension: number) =>\n typeof value === 'string' && value.endsWith('%') ?\n parseFloat(value) / 100\n : +value / dimension;\n\nexport const toDimension = (value: number | string, dimension: number) =>\n typeof value === 'string' && value.endsWith('%') ?\n parseFloat(value) / 100 * dimension\n : +value;\n\n/**\n * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the\n * value returned by `fn`. If `fn` is not a function, this method returns undefined.\n * @param fn - The function to call.\n * @param args - The arguments with which `fn` should be called.\n * @param [thisArg] - The value of `this` provided for the call to `fn`.\n */\nexport function callback R, TA, R>(\n fn: T | undefined,\n args: unknown[],\n thisArg?: TA\n): R | undefined {\n if (fn && typeof fn.call === 'function') {\n return fn.apply(thisArg, args);\n }\n}\n\n/**\n * Note(SB) for performance sake, this method should only be used when loopable type\n * is unknown or in none intensive code (not called often and small loopable). Else\n * it's preferable to use a regular for() loop and save extra function calls.\n * @param loopable - The object or array to be iterated.\n * @param fn - The function to call for each item.\n * @param [thisArg] - The value of `this` provided for the call to `fn`.\n * @param [reverse] - If true, iterates backward on the loopable.\n */\nexport function each(\n loopable: Record,\n fn: (this: TA, v: T, i: string) => void,\n thisArg?: TA,\n reverse?: boolean\n): void;\nexport function each(\n loopable: T[],\n fn: (this: TA, v: T, i: number) => void,\n thisArg?: TA,\n reverse?: boolean\n): void;\nexport function each(\n loopable: T[] | Record,\n fn: (this: TA, v: T, i: any) => void,\n thisArg?: TA,\n reverse?: boolean\n) {\n let i: number, len: number, keys: string[];\n if (isArray(loopable)) {\n len = loopable.length;\n if (reverse) {\n for (i = len - 1; i >= 0; i--) {\n fn.call(thisArg, loopable[i], i);\n }\n } else {\n for (i = 0; i < len; i++) {\n fn.call(thisArg, loopable[i], i);\n }\n }\n } else if (isObject(loopable)) {\n keys = Object.keys(loopable);\n len = keys.length;\n for (i = 0; i < len; i++) {\n fn.call(thisArg, loopable[keys[i]], keys[i]);\n }\n }\n}\n\n/**\n * Returns true if the `a0` and `a1` arrays have the same content, else returns false.\n * @param a0 - The array to compare\n * @param a1 - The array to compare\n * @private\n */\nexport function _elementsEqual(a0: ActiveDataPoint[], a1: ActiveDataPoint[]) {\n let i: number, ilen: number, v0: ActiveDataPoint, v1: ActiveDataPoint;\n\n if (!a0 || !a1 || a0.length !== a1.length) {\n return false;\n }\n\n for (i = 0, ilen = a0.length; i < ilen; ++i) {\n v0 = a0[i];\n v1 = a1[i];\n\n if (v0.datasetIndex !== v1.datasetIndex || v0.index !== v1.index) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Returns a deep copy of `source` without keeping references on objects and arrays.\n * @param source - The value to clone.\n */\nexport function clone(source: T): T {\n if (isArray(source)) {\n return source.map(clone) as unknown as T;\n }\n\n if (isObject(source)) {\n const target = Object.create(null);\n const keys = Object.keys(source);\n const klen = keys.length;\n let k = 0;\n\n for (; k < klen; ++k) {\n target[keys[k]] = clone(source[keys[k]]);\n }\n\n return target;\n }\n\n return source;\n}\n\nfunction isValidKey(key: string) {\n return ['__proto__', 'prototype', 'constructor'].indexOf(key) === -1;\n}\n\n/**\n * The default merger when Chart.helpers.merge is called without merger option.\n * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.\n * @private\n */\nexport function _merger(key: string, target: AnyObject, source: AnyObject, options: AnyObject) {\n if (!isValidKey(key)) {\n return;\n }\n\n const tval = target[key];\n const sval = source[key];\n\n if (isObject(tval) && isObject(sval)) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n merge(tval, sval, options);\n } else {\n target[key] = clone(sval);\n }\n}\n\nexport interface MergeOptions {\n merger?: (key: string, target: AnyObject, source: AnyObject, options?: AnyObject) => void;\n}\n\n/**\n * Recursively deep copies `source` properties into `target` with the given `options`.\n * IMPORTANT: `target` is not cloned and will be updated with `source` properties.\n * @param target - The target object in which all sources are merged into.\n * @param source - Object(s) to merge into `target`.\n * @param [options] - Merging options:\n * @param [options.merger] - The merge method (key, target, source, options)\n * @returns The `target` object.\n */\nexport function merge(target: T, source: [], options?: MergeOptions): T;\nexport function merge(target: T, source: S1, options?: MergeOptions): T & S1;\nexport function merge(target: T, source: [S1], options?: MergeOptions): T & S1;\nexport function merge(target: T, source: [S1, S2], options?: MergeOptions): T & S1 & S2;\nexport function merge(target: T, source: [S1, S2, S3], options?: MergeOptions): T & S1 & S2 & S3;\nexport function merge(\n target: T,\n source: [S1, S2, S3, S4],\n options?: MergeOptions\n): T & S1 & S2 & S3 & S4;\nexport function merge(target: T, source: AnyObject[], options?: MergeOptions): AnyObject;\nexport function merge(target: T, source: AnyObject[], options?: MergeOptions): AnyObject {\n const sources = isArray(source) ? source : [source];\n const ilen = sources.length;\n\n if (!isObject(target)) {\n return target as AnyObject;\n }\n\n options = options || {};\n const merger = options.merger || _merger;\n let current: AnyObject;\n\n for (let i = 0; i < ilen; ++i) {\n current = sources[i];\n if (!isObject(current)) {\n continue;\n }\n\n const keys = Object.keys(current);\n for (let k = 0, klen = keys.length; k < klen; ++k) {\n merger(keys[k], target, current, options as AnyObject);\n }\n }\n\n return target;\n}\n\n/**\n * Recursively deep copies `source` properties into `target` *only* if not defined in target.\n * IMPORTANT: `target` is not cloned and will be updated with `source` properties.\n * @param target - The target object in which all sources are merged into.\n * @param source - Object(s) to merge into `target`.\n * @returns The `target` object.\n */\nexport function mergeIf(target: T, source: []): T;\nexport function mergeIf(target: T, source: S1): T & S1;\nexport function mergeIf(target: T, source: [S1]): T & S1;\nexport function mergeIf(target: T, source: [S1, S2]): T & S1 & S2;\nexport function mergeIf(target: T, source: [S1, S2, S3]): T & S1 & S2 & S3;\nexport function mergeIf(target: T, source: [S1, S2, S3, S4]): T & S1 & S2 & S3 & S4;\nexport function mergeIf(target: T, source: AnyObject[]): AnyObject;\nexport function mergeIf(target: T, source: AnyObject[]): AnyObject {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return merge(target, source, {merger: _mergerIf});\n}\n\n/**\n * Merges source[key] in target[key] only if target[key] is undefined.\n * @private\n */\nexport function _mergerIf(key: string, target: AnyObject, source: AnyObject) {\n if (!isValidKey(key)) {\n return;\n }\n\n const tval = target[key];\n const sval = source[key];\n\n if (isObject(tval) && isObject(sval)) {\n mergeIf(tval, sval);\n } else if (!Object.prototype.hasOwnProperty.call(target, key)) {\n target[key] = clone(sval);\n }\n}\n\n/**\n * @private\n */\nexport function _deprecated(scope: string, value: unknown, previous: string, current: string) {\n if (value !== undefined) {\n console.warn(scope + ': \"' + previous +\n '\" is deprecated. Please use \"' + current + '\" instead');\n }\n}\n\n// resolveObjectKey resolver cache\nconst keyResolvers = {\n // Chart.helpers.core resolveObjectKey should resolve empty key to root object\n '': v => v,\n // default resolvers\n x: o => o.x,\n y: o => o.y\n};\n\n/**\n * @private\n */\nexport function _splitKey(key: string) {\n const parts = key.split('.');\n const keys: string[] = [];\n let tmp = '';\n for (const part of parts) {\n tmp += part;\n if (tmp.endsWith('\\\\')) {\n tmp = tmp.slice(0, -1) + '.';\n } else {\n keys.push(tmp);\n tmp = '';\n }\n }\n return keys;\n}\n\nfunction _getKeyResolver(key: string) {\n const keys = _splitKey(key);\n return obj => {\n for (const k of keys) {\n if (k === '') {\n // For backward compatibility:\n // Chart.helpers.core resolveObjectKey should break at empty key\n break;\n }\n obj = obj && obj[k];\n }\n return obj;\n };\n}\n\nexport function resolveObjectKey(obj: AnyObject, key: string): any {\n const resolver = keyResolvers[key] || (keyResolvers[key] = _getKeyResolver(key));\n return resolver(obj);\n}\n\n/**\n * @private\n */\nexport function _capitalize(str: string) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n\nexport const defined = (value: unknown) => typeof value !== 'undefined';\n\nexport const isFunction = (value: unknown): value is (...args: any[]) => any => typeof value === 'function';\n\n// Adapted from https://stackoverflow.com/questions/31128855/comparing-ecma6-sets-for-equality#31129384\nexport const setsEqual = (a: Set, b: Set) => {\n if (a.size !== b.size) {\n return false;\n }\n\n for (const item of a) {\n if (!b.has(item)) {\n return false;\n }\n }\n\n return true;\n};\n\n/**\n * @param e - The event\n * @private\n */\nexport function _isClickEvent(e: ChartEvent) {\n return e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu';\n}\n","import type {Point} from '../types/geometric.js';\nimport {isFinite as isFiniteNumber} from './helpers.core.js';\n\n/**\n * @alias Chart.helpers.math\n * @namespace\n */\n\nexport const PI = Math.PI;\nexport const TAU = 2 * PI;\nexport const PITAU = TAU + PI;\nexport const INFINITY = Number.POSITIVE_INFINITY;\nexport const RAD_PER_DEG = PI / 180;\nexport const HALF_PI = PI / 2;\nexport const QUARTER_PI = PI / 4;\nexport const TWO_THIRDS_PI = PI * 2 / 3;\n\nexport const log10 = Math.log10;\nexport const sign = Math.sign;\n\nexport function almostEquals(x: number, y: number, epsilon: number) {\n return Math.abs(x - y) < epsilon;\n}\n\n/**\n * Implementation of the nice number algorithm used in determining where axis labels will go\n */\nexport function niceNum(range: number) {\n const roundedRange = Math.round(range);\n range = almostEquals(range, roundedRange, range / 1000) ? roundedRange : range;\n const niceRange = Math.pow(10, Math.floor(log10(range)));\n const fraction = range / niceRange;\n const niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10;\n return niceFraction * niceRange;\n}\n\n/**\n * Returns an array of factors sorted from 1 to sqrt(value)\n * @private\n */\nexport function _factorize(value: number) {\n const result: number[] = [];\n const sqrt = Math.sqrt(value);\n let i: number;\n\n for (i = 1; i < sqrt; i++) {\n if (value % i === 0) {\n result.push(i);\n result.push(value / i);\n }\n }\n if (sqrt === (sqrt | 0)) { // if value is a square number\n result.push(sqrt);\n }\n\n result.sort((a, b) => a - b).pop();\n return result;\n}\n\n/**\n * Verifies that attempting to coerce n to string or number won't throw a TypeError.\n */\nfunction isNonPrimitive(n: unknown) {\n return typeof n === 'symbol' || (typeof n === 'object' && n !== null && !(Symbol.toPrimitive in n || 'toString' in n || 'valueOf' in n));\n}\n\nexport function isNumber(n: unknown): n is number {\n return !isNonPrimitive(n) && !isNaN(parseFloat(n as string)) && isFinite(n as number);\n}\n\nexport function almostWhole(x: number, epsilon: number) {\n const rounded = Math.round(x);\n return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);\n}\n\n/**\n * @private\n */\nexport function _setMinAndMaxByKey(\n array: Record[],\n target: { min: number, max: number },\n property: string\n) {\n let i: number, ilen: number, value: number;\n\n for (i = 0, ilen = array.length; i < ilen; i++) {\n value = array[i][property];\n if (!isNaN(value)) {\n target.min = Math.min(target.min, value);\n target.max = Math.max(target.max, value);\n }\n }\n}\n\nexport function toRadians(degrees: number) {\n return degrees * (PI / 180);\n}\n\nexport function toDegrees(radians: number) {\n return radians * (180 / PI);\n}\n\n/**\n * Returns the number of decimal places\n * i.e. the number of digits after the decimal point, of the value of this Number.\n * @param x - A number.\n * @returns The number of decimal places.\n * @private\n */\nexport function _decimalPlaces(x: number) {\n if (!isFiniteNumber(x)) {\n return;\n }\n let e = 1;\n let p = 0;\n while (Math.round(x * e) / e !== x) {\n e *= 10;\n p++;\n }\n return p;\n}\n\n// Gets the angle from vertical upright to the point about a centre.\nexport function getAngleFromPoint(\n centrePoint: Point,\n anglePoint: Point\n) {\n const distanceFromXCenter = anglePoint.x - centrePoint.x;\n const distanceFromYCenter = anglePoint.y - centrePoint.y;\n const radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);\n\n let angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);\n\n if (angle < (-0.5 * PI)) {\n angle += TAU; // make sure the returned angle is in the range of (-PI/2, 3PI/2]\n }\n\n return {\n angle,\n distance: radialDistanceFromCenter\n };\n}\n\nexport function distanceBetweenPoints(pt1: Point, pt2: Point) {\n return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));\n}\n\n/**\n * Shortest distance between angles, in either direction.\n * @private\n */\nexport function _angleDiff(a: number, b: number) {\n return (a - b + PITAU) % TAU - PI;\n}\n\n/**\n * Normalize angle to be between 0 and 2*PI\n * @private\n */\nexport function _normalizeAngle(a: number) {\n return (a % TAU + TAU) % TAU;\n}\n\n/**\n * @private\n */\nexport function _angleBetween(angle: number, start: number, end: number, sameAngleIsFullCircle?: boolean) {\n const a = _normalizeAngle(angle);\n const s = _normalizeAngle(start);\n const e = _normalizeAngle(end);\n const angleToStart = _normalizeAngle(s - a);\n const angleToEnd = _normalizeAngle(e - a);\n const startToAngle = _normalizeAngle(a - s);\n const endToAngle = _normalizeAngle(a - e);\n return a === s || a === e || (sameAngleIsFullCircle && s === e)\n || (angleToStart > angleToEnd && startToAngle < endToAngle);\n}\n\n/**\n * Limit `value` between `min` and `max`\n * @param value\n * @param min\n * @param max\n * @private\n */\nexport function _limitValue(value: number, min: number, max: number) {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * @param {number} value\n * @private\n */\nexport function _int16Range(value: number) {\n return _limitValue(value, -32768, 32767);\n}\n\n/**\n * @param value\n * @param start\n * @param end\n * @param [epsilon]\n * @private\n */\nexport function _isBetween(value: number, start: number, end: number, epsilon = 1e-6) {\n return value >= Math.min(start, end) - epsilon && value <= Math.max(start, end) + epsilon;\n}\n","import {_capitalize} from './helpers.core.js';\n\n/**\n * Binary search\n * @param table - the table search. must be sorted!\n * @param value - value to find\n * @param cmp\n * @private\n */\nexport function _lookup(\n table: number[],\n value: number,\n cmp?: (value: number) => boolean\n): {lo: number, hi: number};\nexport function _lookup(\n table: T[],\n value: number,\n cmp: (value: number) => boolean\n): {lo: number, hi: number};\nexport function _lookup(\n table: unknown[],\n value: number,\n cmp?: (value: number) => boolean\n) {\n cmp = cmp || ((index) => table[index] < value);\n let hi = table.length - 1;\n let lo = 0;\n let mid: number;\n\n while (hi - lo > 1) {\n mid = (lo + hi) >> 1;\n if (cmp(mid)) {\n lo = mid;\n } else {\n hi = mid;\n }\n }\n\n return {lo, hi};\n}\n\n/**\n * Binary search\n * @param table - the table search. must be sorted!\n * @param key - property name for the value in each entry\n * @param value - value to find\n * @param last - lookup last index\n * @private\n */\nexport const _lookupByKey = (\n table: Record[],\n key: string,\n value: number,\n last?: boolean\n) =>\n _lookup(table, value, last\n ? index => {\n const ti = table[index][key];\n return ti < value || ti === value && table[index + 1][key] === value;\n }\n : index => table[index][key] < value);\n\n/**\n * Reverse binary search\n * @param table - the table search. must be sorted!\n * @param key - property name for the value in each entry\n * @param value - value to find\n * @private\n */\nexport const _rlookupByKey = (\n table: Record[],\n key: string,\n value: number\n) =>\n _lookup(table, value, index => table[index][key] >= value);\n\n/**\n * Return subset of `values` between `min` and `max` inclusive.\n * Values are assumed to be in sorted order.\n * @param values - sorted array of values\n * @param min - min value\n * @param max - max value\n */\nexport function _filterBetween(values: number[], min: number, max: number) {\n let start = 0;\n let end = values.length;\n\n while (start < end && values[start] < min) {\n start++;\n }\n while (end > start && values[end - 1] > max) {\n end--;\n }\n\n return start > 0 || end < values.length\n ? values.slice(start, end)\n : values;\n}\n\nconst arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'] as const;\n\nexport interface ArrayListener {\n _onDataPush?(...item: T[]): void;\n _onDataPop?(): void;\n _onDataShift?(): void;\n _onDataSplice?(index: number, deleteCount: number, ...items: T[]): void;\n _onDataUnshift?(...item: T[]): void;\n}\n\n/**\n * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',\n * 'unshift') and notify the listener AFTER the array has been altered. Listeners are\n * called on the '_onData*' callbacks (e.g. _onDataPush, etc.) with same arguments.\n */\nexport function listenArrayEvents(array: T[], listener: ArrayListener): void;\nexport function listenArrayEvents(array, listener) {\n if (array._chartjs) {\n array._chartjs.listeners.push(listener);\n return;\n }\n\n Object.defineProperty(array, '_chartjs', {\n configurable: true,\n enumerable: false,\n value: {\n listeners: [listener]\n }\n });\n\n arrayEvents.forEach((key) => {\n const method = '_onData' + _capitalize(key);\n const base = array[key];\n\n Object.defineProperty(array, key, {\n configurable: true,\n enumerable: false,\n value(...args) {\n const res = base.apply(this, args);\n\n array._chartjs.listeners.forEach((object) => {\n if (typeof object[method] === 'function') {\n object[method](...args);\n }\n });\n\n return res;\n }\n });\n });\n}\n\n\n/**\n * Removes the given array event listener and cleanup extra attached properties (such as\n * the _chartjs stub and overridden methods) if array doesn't have any more listeners.\n */\nexport function unlistenArrayEvents(array: T[], listener: ArrayListener): void;\nexport function unlistenArrayEvents(array, listener) {\n const stub = array._chartjs;\n if (!stub) {\n return;\n }\n\n const listeners = stub.listeners;\n const index = listeners.indexOf(listener);\n if (index !== -1) {\n listeners.splice(index, 1);\n }\n\n if (listeners.length > 0) {\n return;\n }\n\n arrayEvents.forEach((key) => {\n delete array[key];\n });\n\n delete array._chartjs;\n}\n\n/**\n * @param items\n */\nexport function _arrayUnique(items: T[]) {\n const set = new Set(items);\n\n if (set.size === items.length) {\n return items;\n }\n\n return Array.from(set);\n}\n","import type {ChartMeta, PointElement} from '../types/index.js';\n\nimport {_limitValue} from './helpers.math.js';\nimport {_lookupByKey} from './helpers.collection.js';\nimport {isNullOrUndef} from './helpers.core.js';\n\nexport function fontString(pixelSize: number, fontStyle: string, fontFamily: string) {\n return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;\n}\n\n/**\n* Request animation polyfill\n*/\nexport const requestAnimFrame = (function() {\n if (typeof window === 'undefined') {\n return function(callback) {\n return callback();\n };\n }\n return window.requestAnimationFrame;\n}());\n\n/**\n * Throttles calling `fn` once per animation frame\n * Latest arguments are used on the actual call\n */\nexport function throttled>(\n fn: (...args: TArgs) => void,\n thisArg: any,\n) {\n let argsToUse = [] as TArgs;\n let ticking = false;\n\n return function(...args: TArgs) {\n // Save the args for use later\n argsToUse = args;\n if (!ticking) {\n ticking = true;\n requestAnimFrame.call(window, () => {\n ticking = false;\n fn.apply(thisArg, argsToUse);\n });\n }\n };\n}\n\n/**\n * Debounces calling `fn` for `delay` ms\n */\nexport function debounce>(fn: (...args: TArgs) => void, delay: number) {\n let timeout;\n return function(...args: TArgs) {\n if (delay) {\n clearTimeout(timeout);\n timeout = setTimeout(fn, delay, args);\n } else {\n fn.apply(this, args);\n }\n return delay;\n };\n}\n\n/**\n * Converts 'start' to 'left', 'end' to 'right' and others to 'center'\n * @private\n */\nexport const _toLeftRightCenter = (align: 'start' | 'end' | 'center') => align === 'start' ? 'left' : align === 'end' ? 'right' : 'center';\n\n/**\n * Returns `start`, `end` or `(start + end) / 2` depending on `align`. Defaults to `center`\n * @private\n */\nexport const _alignStartEnd = (align: 'start' | 'end' | 'center', start: number, end: number) => align === 'start' ? start : align === 'end' ? end : (start + end) / 2;\n\n/**\n * Returns `left`, `right` or `(left + right) / 2` depending on `align`. Defaults to `left`\n * @private\n */\nexport const _textX = (align: 'left' | 'right' | 'center', left: number, right: number, rtl: boolean) => {\n const check = rtl ? 'left' : 'right';\n return align === check ? right : align === 'center' ? (left + right) / 2 : left;\n};\n\n/**\n * Return start and count of visible points.\n * @private\n */\nexport function _getStartAndCountOfVisiblePoints(meta: ChartMeta<'line' | 'scatter'>, points: PointElement[], animationsDisabled: boolean) {\n const pointCount = points.length;\n\n let start = 0;\n let count = pointCount;\n\n if (meta._sorted) {\n const {iScale, vScale, _parsed} = meta;\n const spanGaps = meta.dataset ? meta.dataset.options ? meta.dataset.options.spanGaps : null : null;\n const axis = iScale.axis;\n const {min, max, minDefined, maxDefined} = iScale.getUserBounds();\n\n if (minDefined) {\n start = Math.min(\n // @ts-expect-error Need to type _parsed\n _lookupByKey(_parsed, axis, min).lo,\n // @ts-expect-error Need to fix types on _lookupByKey\n animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min)).lo);\n if (spanGaps) {\n const distanceToDefinedLo = (_parsed\n .slice(0, start + 1)\n .reverse()\n .findIndex(\n point => !isNullOrUndef(point[vScale.axis])));\n start -= Math.max(0, distanceToDefinedLo);\n }\n start = _limitValue(start, 0, pointCount - 1);\n }\n if (maxDefined) {\n let end = Math.max(\n // @ts-expect-error Need to type _parsed\n _lookupByKey(_parsed, iScale.axis, max, true).hi + 1,\n // @ts-expect-error Need to fix types on _lookupByKey\n animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max), true).hi + 1);\n if (spanGaps) {\n const distanceToDefinedHi = (_parsed\n .slice(end - 1)\n .findIndex(\n point => !isNullOrUndef(point[vScale.axis])));\n end += Math.max(0, distanceToDefinedHi);\n }\n count = _limitValue(end, start, pointCount) - start;\n } else {\n count = pointCount - start;\n }\n }\n\n return {start, count};\n}\n\n/**\n * Checks if the scale ranges have changed.\n * @param {object} meta - dataset meta.\n * @returns {boolean}\n * @private\n */\nexport function _scaleRangesChanged(meta) {\n const {xScale, yScale, _scaleRanges} = meta;\n const newRanges = {\n xmin: xScale.min,\n xmax: xScale.max,\n ymin: yScale.min,\n ymax: yScale.max\n };\n if (!_scaleRanges) {\n meta._scaleRanges = newRanges;\n return true;\n }\n const changed = _scaleRanges.xmin !== xScale.min\n\t\t|| _scaleRanges.xmax !== xScale.max\n\t\t|| _scaleRanges.ymin !== yScale.min\n\t\t|| _scaleRanges.ymax !== yScale.max;\n\n Object.assign(_scaleRanges, newRanges);\n return changed;\n}\n","import {PI, TAU, HALF_PI} from './helpers.math.js';\n\nconst atEdge = (t: number) => t === 0 || t === 1;\nconst elasticIn = (t: number, s: number, p: number) => -(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * TAU / p));\nconst elasticOut = (t: number, s: number, p: number) => Math.pow(2, -10 * t) * Math.sin((t - s) * TAU / p) + 1;\n\n/**\n * Easing functions adapted from Robert Penner's easing equations.\n * @namespace Chart.helpers.easing.effects\n * @see http://www.robertpenner.com/easing/\n */\nconst effects = {\n linear: (t: number) => t,\n\n easeInQuad: (t: number) => t * t,\n\n easeOutQuad: (t: number) => -t * (t - 2),\n\n easeInOutQuad: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t\n : -0.5 * ((--t) * (t - 2) - 1),\n\n easeInCubic: (t: number) => t * t * t,\n\n easeOutCubic: (t: number) => (t -= 1) * t * t + 1,\n\n easeInOutCubic: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t * t\n : 0.5 * ((t -= 2) * t * t + 2),\n\n easeInQuart: (t: number) => t * t * t * t,\n\n easeOutQuart: (t: number) => -((t -= 1) * t * t * t - 1),\n\n easeInOutQuart: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t * t * t\n : -0.5 * ((t -= 2) * t * t * t - 2),\n\n easeInQuint: (t: number) => t * t * t * t * t,\n\n easeOutQuint: (t: number) => (t -= 1) * t * t * t * t + 1,\n\n easeInOutQuint: (t: number) => ((t /= 0.5) < 1)\n ? 0.5 * t * t * t * t * t\n : 0.5 * ((t -= 2) * t * t * t * t + 2),\n\n easeInSine: (t: number) => -Math.cos(t * HALF_PI) + 1,\n\n easeOutSine: (t: number) => Math.sin(t * HALF_PI),\n\n easeInOutSine: (t: number) => -0.5 * (Math.cos(PI * t) - 1),\n\n easeInExpo: (t: number) => (t === 0) ? 0 : Math.pow(2, 10 * (t - 1)),\n\n easeOutExpo: (t: number) => (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1,\n\n easeInOutExpo: (t: number) => atEdge(t) ? t : t < 0.5\n ? 0.5 * Math.pow(2, 10 * (t * 2 - 1))\n : 0.5 * (-Math.pow(2, -10 * (t * 2 - 1)) + 2),\n\n easeInCirc: (t: number) => (t >= 1) ? t : -(Math.sqrt(1 - t * t) - 1),\n\n easeOutCirc: (t: number) => Math.sqrt(1 - (t -= 1) * t),\n\n easeInOutCirc: (t: number) => ((t /= 0.5) < 1)\n ? -0.5 * (Math.sqrt(1 - t * t) - 1)\n : 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1),\n\n easeInElastic: (t: number) => atEdge(t) ? t : elasticIn(t, 0.075, 0.3),\n\n easeOutElastic: (t: number) => atEdge(t) ? t : elasticOut(t, 0.075, 0.3),\n\n easeInOutElastic(t: number) {\n const s = 0.1125;\n const p = 0.45;\n return atEdge(t) ? t :\n t < 0.5\n ? 0.5 * elasticIn(t * 2, s, p)\n : 0.5 + 0.5 * elasticOut(t * 2 - 1, s, p);\n },\n\n easeInBack(t: number) {\n const s = 1.70158;\n return t * t * ((s + 1) * t - s);\n },\n\n easeOutBack(t: number) {\n const s = 1.70158;\n return (t -= 1) * t * ((s + 1) * t + s) + 1;\n },\n\n easeInOutBack(t: number) {\n let s = 1.70158;\n if ((t /= 0.5) < 1) {\n return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));\n }\n return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);\n },\n\n easeInBounce: (t: number) => 1 - effects.easeOutBounce(1 - t),\n\n easeOutBounce(t: number) {\n const m = 7.5625;\n const d = 2.75;\n if (t < (1 / d)) {\n return m * t * t;\n }\n if (t < (2 / d)) {\n return m * (t -= (1.5 / d)) * t + 0.75;\n }\n if (t < (2.5 / d)) {\n return m * (t -= (2.25 / d)) * t + 0.9375;\n }\n return m * (t -= (2.625 / d)) * t + 0.984375;\n },\n\n easeInOutBounce: (t: number) => (t < 0.5)\n ? effects.easeInBounce(t * 2) * 0.5\n : effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5,\n} as const;\n\nexport type EasingFunction = keyof typeof effects\n\nexport default effects;\n","import {Color} from '@kurkle/color';\n\nexport function isPatternOrGradient(value: unknown): value is CanvasPattern | CanvasGradient {\n if (value && typeof value === 'object') {\n const type = value.toString();\n return type === '[object CanvasPattern]' || type === '[object CanvasGradient]';\n }\n\n return false;\n}\n\nexport function color(value: CanvasGradient): CanvasGradient;\nexport function color(value: CanvasPattern): CanvasPattern;\nexport function color(\n value:\n | string\n | { r: number; g: number; b: number; a: number }\n | [number, number, number]\n | [number, number, number, number]\n): Color;\nexport function color(value) {\n return isPatternOrGradient(value) ? value : new Color(value);\n}\n\nexport function getHoverColor(value: CanvasGradient): CanvasGradient;\nexport function getHoverColor(value: CanvasPattern): CanvasPattern;\nexport function getHoverColor(value: string): string;\nexport function getHoverColor(value) {\n return isPatternOrGradient(value)\n ? value\n : new Color(value).saturate(0.5).darken(0.1).hexString();\n}\n","const numbers = ['x', 'y', 'borderWidth', 'radius', 'tension'];\nconst colors = ['color', 'borderColor', 'backgroundColor'];\n\nexport function applyAnimationsDefaults(defaults) {\n defaults.set('animation', {\n delay: undefined,\n duration: 1000,\n easing: 'easeOutQuart',\n fn: undefined,\n from: undefined,\n loop: undefined,\n to: undefined,\n type: undefined,\n });\n\n defaults.describe('animation', {\n _fallback: false,\n _indexable: false,\n _scriptable: (name) => name !== 'onProgress' && name !== 'onComplete' && name !== 'fn',\n });\n\n defaults.set('animations', {\n colors: {\n type: 'color',\n properties: colors\n },\n numbers: {\n type: 'number',\n properties: numbers\n },\n });\n\n defaults.describe('animations', {\n _fallback: 'animation',\n });\n\n defaults.set('transitions', {\n active: {\n animation: {\n duration: 400\n }\n },\n resize: {\n animation: {\n duration: 0\n }\n },\n show: {\n animations: {\n colors: {\n from: 'transparent'\n },\n visible: {\n type: 'boolean',\n duration: 0 // show immediately\n },\n }\n },\n hide: {\n animations: {\n colors: {\n to: 'transparent'\n },\n visible: {\n type: 'boolean',\n easing: 'linear',\n fn: v => v | 0 // for keeping the dataset visible all the way through the animation\n },\n }\n }\n });\n}\n","export function applyLayoutsDefaults(defaults) {\n defaults.set('layout', {\n autoPadding: true,\n padding: {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0\n }\n });\n}\n","\nconst intlCache = new Map();\n\nfunction getNumberFormat(locale: string, options?: Intl.NumberFormatOptions) {\n options = options || {};\n const cacheKey = locale + JSON.stringify(options);\n let formatter = intlCache.get(cacheKey);\n if (!formatter) {\n formatter = new Intl.NumberFormat(locale, options);\n intlCache.set(cacheKey, formatter);\n }\n return formatter;\n}\n\nexport function formatNumber(num: number, locale: string, options?: Intl.NumberFormatOptions) {\n return getNumberFormat(locale, options).format(num);\n}\n","import {isArray} from '../helpers/helpers.core.js';\nimport {formatNumber} from '../helpers/helpers.intl.js';\nimport {log10} from '../helpers/helpers.math.js';\n\n/**\n * Namespace to hold formatters for different types of ticks\n * @namespace Chart.Ticks.formatters\n */\nconst formatters = {\n /**\n * Formatter for value labels\n * @method Chart.Ticks.formatters.values\n * @param value the value to display\n * @return {string|string[]} the label to display\n */\n values(value) {\n return isArray(value) ? /** @type {string[]} */ (value) : '' + value;\n },\n\n /**\n * Formatter for numeric ticks\n * @method Chart.Ticks.formatters.numeric\n * @param tickValue {number} the value to be formatted\n * @param index {number} the position of the tickValue parameter in the ticks array\n * @param ticks {object[]} the list of ticks being converted\n * @return {string} string representation of the tickValue parameter\n */\n numeric(tickValue, index, ticks) {\n if (tickValue === 0) {\n return '0'; // never show decimal places for 0\n }\n\n const locale = this.chart.options.locale;\n let notation;\n let delta = tickValue; // This is used when there are less than 2 ticks as the tick interval.\n\n if (ticks.length > 1) {\n // all ticks are small or there huge numbers; use scientific notation\n const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value));\n if (maxTick < 1e-4 || maxTick > 1e+15) {\n notation = 'scientific';\n }\n\n delta = calculateDelta(tickValue, ticks);\n }\n\n const logDelta = log10(Math.abs(delta));\n\n // When datasets have values approaching Number.MAX_VALUE, the tick calculations might result in\n // infinity and eventually NaN. Passing NaN for minimumFractionDigits or maximumFractionDigits\n // will make the number formatter throw. So instead we check for isNaN and use a fallback value.\n //\n // toFixed has a max of 20 decimal places\n const numDecimal = isNaN(logDelta) ? 1 : Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0);\n\n const options = {notation, minimumFractionDigits: numDecimal, maximumFractionDigits: numDecimal};\n Object.assign(options, this.options.ticks.format);\n\n return formatNumber(tickValue, locale, options);\n },\n\n\n /**\n * Formatter for logarithmic ticks\n * @method Chart.Ticks.formatters.logarithmic\n * @param tickValue {number} the value to be formatted\n * @param index {number} the position of the tickValue parameter in the ticks array\n * @param ticks {object[]} the list of ticks being converted\n * @return {string} string representation of the tickValue parameter\n */\n logarithmic(tickValue, index, ticks) {\n if (tickValue === 0) {\n return '0';\n }\n const remain = ticks[index].significand || (tickValue / (Math.pow(10, Math.floor(log10(tickValue)))));\n if ([1, 2, 3, 5, 10, 15].includes(remain) || index > 0.8 * ticks.length) {\n return formatters.numeric.call(this, tickValue, index, ticks);\n }\n return '';\n }\n\n};\n\n\nfunction calculateDelta(tickValue, ticks) {\n // Figure out how many digits to show\n // The space between the first two ticks might be smaller than normal spacing\n let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value;\n\n // If we have a number like 2.5 as the delta, figure out how many decimal places we need\n if (Math.abs(delta) >= 1 && tickValue !== Math.floor(tickValue)) {\n // not an integer\n delta = tickValue - Math.floor(tickValue);\n }\n return delta;\n}\n\n/**\n * Namespace to hold static tick generation functions\n * @namespace Chart.Ticks\n */\nexport default {formatters};\n","import Ticks from './core.ticks.js';\n\nexport function applyScaleDefaults(defaults) {\n defaults.set('scale', {\n display: true,\n offset: false,\n reverse: false,\n beginAtZero: false,\n\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 3.0.0\n */\n bounds: 'ticks',\n\n clip: true,\n\n /**\n * Addition grace added to max and reduced from min data value.\n * @since 3.0.0\n */\n grace: 0,\n\n // grid line settings\n grid: {\n display: true,\n lineWidth: 1,\n drawOnChartArea: true,\n drawTicks: true,\n tickLength: 8,\n tickWidth: (_ctx, options) => options.lineWidth,\n tickColor: (_ctx, options) => options.color,\n offset: false,\n },\n\n border: {\n display: true,\n dash: [],\n dashOffset: 0.0,\n width: 1\n },\n\n // scale title\n title: {\n // display property\n display: false,\n\n // actual label\n text: '',\n\n // top/bottom padding\n padding: {\n top: 4,\n bottom: 4\n }\n },\n\n // label settings\n ticks: {\n minRotation: 0,\n maxRotation: 50,\n mirror: false,\n textStrokeWidth: 0,\n textStrokeColor: '',\n padding: 3,\n display: true,\n autoSkip: true,\n autoSkipPadding: 3,\n labelOffset: 0,\n // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.\n callback: Ticks.formatters.values,\n minor: {},\n major: {},\n align: 'center',\n crossAlign: 'near',\n\n showLabelBackdrop: false,\n backdropColor: 'rgba(255, 255, 255, 0.75)',\n backdropPadding: 2,\n }\n });\n\n defaults.route('scale.ticks', 'color', '', 'color');\n defaults.route('scale.grid', 'color', '', 'borderColor');\n defaults.route('scale.border', 'color', '', 'borderColor');\n defaults.route('scale.title', 'color', '', 'color');\n\n defaults.describe('scale', {\n _fallback: false,\n _scriptable: (name) => !name.startsWith('before') && !name.startsWith('after') && name !== 'callback' && name !== 'parser',\n _indexable: (name) => name !== 'borderDash' && name !== 'tickBorderDash' && name !== 'dash',\n });\n\n defaults.describe('scales', {\n _fallback: 'scale',\n });\n\n defaults.describe('scale.ticks', {\n _scriptable: (name) => name !== 'backdropPadding' && name !== 'callback',\n _indexable: (name) => name !== 'backdropPadding',\n });\n}\n","import {getHoverColor} from '../helpers/helpers.color.js';\nimport {isObject, merge, valueOrDefault} from '../helpers/helpers.core.js';\nimport {applyAnimationsDefaults} from './core.animations.defaults.js';\nimport {applyLayoutsDefaults} from './core.layouts.defaults.js';\nimport {applyScaleDefaults} from './core.scale.defaults.js';\n\nexport const overrides = Object.create(null);\nexport const descriptors = Object.create(null);\n\n/**\n * @param {object} node\n * @param {string} key\n * @return {object}\n */\nfunction getScope(node, key) {\n if (!key) {\n return node;\n }\n const keys = key.split('.');\n for (let i = 0, n = keys.length; i < n; ++i) {\n const k = keys[i];\n node = node[k] || (node[k] = Object.create(null));\n }\n return node;\n}\n\nfunction set(root, scope, values) {\n if (typeof scope === 'string') {\n return merge(getScope(root, scope), values);\n }\n return merge(getScope(root, ''), scope);\n}\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 Defaults {\n constructor(_descriptors, _appliers) {\n this.animation = undefined;\n this.backgroundColor = 'rgba(0,0,0,0.1)';\n this.borderColor = 'rgba(0,0,0,0.1)';\n this.color = '#666';\n this.datasets = {};\n this.devicePixelRatio = (context) => context.chart.platform.getDevicePixelRatio();\n this.elements = {};\n this.events = [\n 'mousemove',\n 'mouseout',\n 'click',\n 'touchstart',\n 'touchmove'\n ];\n this.font = {\n family: \"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif\",\n size: 12,\n style: 'normal',\n lineHeight: 1.2,\n weight: null\n };\n this.hover = {};\n this.hoverBackgroundColor = (ctx, options) => getHoverColor(options.backgroundColor);\n this.hoverBorderColor = (ctx, options) => getHoverColor(options.borderColor);\n this.hoverColor = (ctx, options) => getHoverColor(options.color);\n this.indexAxis = 'x';\n this.interaction = {\n mode: 'nearest',\n intersect: true,\n includeInvisible: false\n };\n this.maintainAspectRatio = true;\n this.onHover = null;\n this.onClick = null;\n this.parsing = true;\n this.plugins = {};\n this.responsive = true;\n this.scale = undefined;\n this.scales = {};\n this.showLine = true;\n this.drawActiveElementsOnTop = true;\n\n this.describe(_descriptors);\n this.apply(_appliers);\n }\n\n /**\n\t * @param {string|object} scope\n\t * @param {object} [values]\n\t */\n set(scope, values) {\n return set(this, scope, values);\n }\n\n /**\n\t * @param {string} scope\n\t */\n get(scope) {\n return getScope(this, scope);\n }\n\n /**\n\t * @param {string|object} scope\n\t * @param {object} [values]\n\t */\n describe(scope, values) {\n return set(descriptors, scope, values);\n }\n\n override(scope, values) {\n return set(overrides, scope, values);\n }\n\n /**\n\t * Routes the named defaults to fallback to another scope/name.\n\t * This routing is useful when those target values, like defaults.color, are changed runtime.\n\t * If the values would be copied, the runtime change would not take effect. By routing, the\n\t * fallback is evaluated at each access, so its always up to date.\n\t *\n\t * Example:\n\t *\n\t * \tdefaults.route('elements.arc', 'backgroundColor', '', 'color')\n\t * - reads the backgroundColor from defaults.color when undefined locally\n\t *\n\t * @param {string} scope Scope this route applies to.\n\t * @param {string} name Property name that should be routed to different namespace when not defined here.\n\t * @param {string} targetScope The namespace where those properties should be routed to.\n\t * Empty string ('') is the root of defaults.\n\t * @param {string} targetName The target name in the target scope the property should be routed to.\n\t */\n route(scope, name, targetScope, targetName) {\n const scopeObject = getScope(this, scope);\n const targetScopeObject = getScope(this, targetScope);\n const privateName = '_' + name;\n\n Object.defineProperties(scopeObject, {\n // A private property is defined to hold the actual value, when this property is set in its scope (set in the setter)\n [privateName]: {\n value: scopeObject[name],\n writable: true\n },\n // The actual property is defined as getter/setter so we can do the routing when value is not locally set.\n [name]: {\n enumerable: true,\n get() {\n const local = this[privateName];\n const target = targetScopeObject[targetName];\n if (isObject(local)) {\n return Object.assign({}, target, local);\n }\n return valueOrDefault(local, target);\n },\n set(value) {\n this[privateName] = value;\n }\n }\n });\n }\n\n apply(appliers) {\n appliers.forEach((apply) => apply(this));\n }\n}\n\n// singleton instance\nexport default /* #__PURE__ */ new Defaults({\n _scriptable: (name) => !name.startsWith('on'),\n _indexable: (name) => name !== 'events',\n hover: {\n _fallback: 'interaction'\n },\n interaction: {\n _scriptable: false,\n _indexable: false,\n }\n}, [applyAnimationsDefaults, applyLayoutsDefaults, applyScaleDefaults]);\n","import type {\n Chart,\n Point,\n FontSpec,\n CanvasFontSpec,\n PointStyle,\n RenderTextOpts,\n BackdropOptions\n} from '../types/index.js';\nimport type {\n TRBL,\n SplinePoint,\n RoundedRect,\n TRBLCorners\n} from '../types/geometric.js';\nimport {isArray, isNullOrUndef} from './helpers.core.js';\nimport {PI, TAU, HALF_PI, QUARTER_PI, TWO_THIRDS_PI, RAD_PER_DEG} from './helpers.math.js';\n\n/**\n * Converts the given font object into a CSS font string.\n * @param font - A font object.\n * @return The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font\n * @private\n */\nexport function toFontString(font: FontSpec) {\n if (!font || isNullOrUndef(font.size) || isNullOrUndef(font.family)) {\n return null;\n }\n\n return (font.style ? font.style + ' ' : '')\n\t\t+ (font.weight ? font.weight + ' ' : '')\n\t\t+ font.size + 'px '\n\t\t+ font.family;\n}\n\n/**\n * @private\n */\nexport function _measureText(\n ctx: CanvasRenderingContext2D,\n data: Record,\n gc: string[],\n longest: number,\n string: string\n) {\n let textWidth = data[string];\n if (!textWidth) {\n textWidth = data[string] = ctx.measureText(string).width;\n gc.push(string);\n }\n if (textWidth > longest) {\n longest = textWidth;\n }\n return longest;\n}\n\ntype Thing = string | undefined | null\ntype Things = (Thing | Thing[])[]\n\n/**\n * @private\n */\n// eslint-disable-next-line complexity\nexport function _longestText(\n ctx: CanvasRenderingContext2D,\n font: string,\n arrayOfThings: Things,\n cache?: {data?: Record, garbageCollect?: string[], font?: string}\n) {\n cache = cache || {};\n let data = cache.data = cache.data || {};\n let gc = cache.garbageCollect = cache.garbageCollect || [];\n\n if (cache.font !== font) {\n data = cache.data = {};\n gc = cache.garbageCollect = [];\n cache.font = font;\n }\n\n ctx.save();\n\n ctx.font = font;\n let longest = 0;\n const ilen = arrayOfThings.length;\n let i: number, j: number, jlen: number, thing: Thing | Thing[], nestedThing: Thing | Thing[];\n for (i = 0; i < ilen; i++) {\n thing = arrayOfThings[i];\n\n // Undefined strings and arrays should not be measured\n if (thing !== undefined && thing !== null && !isArray(thing)) {\n longest = _measureText(ctx, data, gc, longest, thing);\n } else if (isArray(thing)) {\n // if it is an array lets measure each element\n // to do maybe simplify this function a bit so we can do this more recursively?\n for (j = 0, jlen = thing.length; j < jlen; j++) {\n nestedThing = thing[j];\n // Undefined strings and arrays should not be measured\n if (nestedThing !== undefined && nestedThing !== null && !isArray(nestedThing)) {\n longest = _measureText(ctx, data, gc, longest, nestedThing);\n }\n }\n }\n }\n\n ctx.restore();\n\n const gcLen = gc.length / 2;\n if (gcLen > arrayOfThings.length) {\n for (i = 0; i < gcLen; i++) {\n delete data[gc[i]];\n }\n gc.splice(0, gcLen);\n }\n return longest;\n}\n\n/**\n * Returns the aligned pixel value to avoid anti-aliasing blur\n * @param chart - The chart instance.\n * @param pixel - A pixel value.\n * @param width - The width of the element.\n * @returns The aligned pixel value.\n * @private\n */\nexport function _alignPixel(chart: Chart, pixel: number, width: number) {\n const devicePixelRatio = chart.currentDevicePixelRatio;\n const halfWidth = width !== 0 ? Math.max(width / 2, 0.5) : 0;\n return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;\n}\n\n/**\n * Clears the entire canvas.\n */\nexport function clearCanvas(canvas?: HTMLCanvasElement, ctx?: CanvasRenderingContext2D) {\n if (!ctx && !canvas) {\n return;\n }\n\n ctx = ctx || canvas.getContext('2d');\n\n ctx.save();\n // canvas.width and canvas.height do not consider the canvas transform,\n // while clearRect does\n ctx.resetTransform();\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.restore();\n}\n\nexport interface DrawPointOptions {\n pointStyle: PointStyle;\n rotation?: number;\n radius: number;\n borderWidth: number;\n}\n\nexport function drawPoint(\n ctx: CanvasRenderingContext2D,\n options: DrawPointOptions,\n x: number,\n y: number\n) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n drawPointLegend(ctx, options, x, y, null);\n}\n\n// eslint-disable-next-line complexity\nexport function drawPointLegend(\n ctx: CanvasRenderingContext2D,\n options: DrawPointOptions,\n x: number,\n y: number,\n w: number\n) {\n let type: string, xOffset: number, yOffset: number, size: number, cornerRadius: number, width: number, xOffsetW: number, yOffsetW: number;\n const style = options.pointStyle;\n const rotation = options.rotation;\n const radius = options.radius;\n let rad = (rotation || 0) * RAD_PER_DEG;\n\n if (style && typeof style === 'object') {\n type = style.toString();\n if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {\n ctx.save();\n ctx.translate(x, y);\n ctx.rotate(rad);\n ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);\n ctx.restore();\n return;\n }\n }\n\n if (isNaN(radius) || radius <= 0) {\n return;\n }\n\n ctx.beginPath();\n\n switch (style) {\n // Default includes circle\n default:\n if (w) {\n ctx.ellipse(x, y, w / 2, radius, 0, 0, TAU);\n } else {\n ctx.arc(x, y, radius, 0, TAU);\n }\n ctx.closePath();\n break;\n case 'triangle':\n width = w ? w / 2 : radius;\n ctx.moveTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);\n rad += TWO_THIRDS_PI;\n ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);\n rad += TWO_THIRDS_PI;\n ctx.lineTo(x + Math.sin(rad) * width, y - Math.cos(rad) * radius);\n ctx.closePath();\n break;\n case 'rectRounded':\n // NOTE: the rounded rect implementation changed to use `arc` instead of\n // `quadraticCurveTo` since it generates better results when rect is\n // almost a circle. 0.516 (instead of 0.5) produces results with visually\n // closer proportion to the previous impl and it is inscribed in the\n // circle with `radius`. For more details, see the following PRs:\n // https://github.com/chartjs/Chart.js/issues/5597\n // https://github.com/chartjs/Chart.js/issues/5858\n cornerRadius = radius * 0.516;\n size = radius - cornerRadius;\n xOffset = Math.cos(rad + QUARTER_PI) * size;\n xOffsetW = Math.cos(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size);\n yOffset = Math.sin(rad + QUARTER_PI) * size;\n yOffsetW = Math.sin(rad + QUARTER_PI) * (w ? w / 2 - cornerRadius : size);\n ctx.arc(x - xOffsetW, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);\n ctx.arc(x + yOffsetW, y - xOffset, cornerRadius, rad - HALF_PI, rad);\n ctx.arc(x + xOffsetW, y + yOffset, cornerRadius, rad, rad + HALF_PI);\n ctx.arc(x - yOffsetW, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);\n ctx.closePath();\n break;\n case 'rect':\n if (!rotation) {\n size = Math.SQRT1_2 * radius;\n width = w ? w / 2 : size;\n ctx.rect(x - width, y - size, 2 * width, 2 * size);\n break;\n }\n rad += QUARTER_PI;\n /* falls through */\n case 'rectRot':\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n ctx.closePath();\n break;\n case 'crossRot':\n rad += QUARTER_PI;\n /* falls through */\n case 'cross':\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.moveTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n break;\n case 'star':\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.moveTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n rad += QUARTER_PI;\n xOffsetW = Math.cos(rad) * (w ? w / 2 : radius);\n xOffset = Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n yOffsetW = Math.sin(rad) * (w ? w / 2 : radius);\n ctx.moveTo(x - xOffsetW, y - yOffset);\n ctx.lineTo(x + xOffsetW, y + yOffset);\n ctx.moveTo(x + yOffsetW, y - xOffset);\n ctx.lineTo(x - yOffsetW, y + xOffset);\n break;\n case 'line':\n xOffset = w ? w / 2 : Math.cos(rad) * radius;\n yOffset = Math.sin(rad) * radius;\n ctx.moveTo(x - xOffset, y - yOffset);\n ctx.lineTo(x + xOffset, y + yOffset);\n break;\n case 'dash':\n ctx.moveTo(x, y);\n ctx.lineTo(x + Math.cos(rad) * (w ? w / 2 : radius), y + Math.sin(rad) * radius);\n break;\n case false:\n ctx.closePath();\n break;\n }\n\n ctx.fill();\n if (options.borderWidth > 0) {\n ctx.stroke();\n }\n}\n\n/**\n * Returns true if the point is inside the rectangle\n * @param point - The point to test\n * @param area - The rectangle\n * @param margin - allowed margin\n * @private\n */\nexport function _isPointInArea(\n point: Point,\n area: TRBL,\n margin?: number\n) {\n margin = margin || 0.5; // margin - default is to match rounded decimals\n\n return !area || (point && point.x > area.left - margin && point.x < area.right + margin &&\n\t\tpoint.y > area.top - margin && point.y < area.bottom + margin);\n}\n\nexport function clipArea(ctx: CanvasRenderingContext2D, area: TRBL) {\n ctx.save();\n ctx.beginPath();\n ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);\n ctx.clip();\n}\n\nexport function unclipArea(ctx: CanvasRenderingContext2D) {\n ctx.restore();\n}\n\n/**\n * @private\n */\nexport function _steppedLineTo(\n ctx: CanvasRenderingContext2D,\n previous: Point,\n target: Point,\n flip?: boolean,\n mode?: string\n) {\n if (!previous) {\n return ctx.lineTo(target.x, target.y);\n }\n if (mode === 'middle') {\n const midpoint = (previous.x + target.x) / 2.0;\n ctx.lineTo(midpoint, previous.y);\n ctx.lineTo(midpoint, target.y);\n } else if (mode === 'after' !== !!flip) {\n ctx.lineTo(previous.x, target.y);\n } else {\n ctx.lineTo(target.x, previous.y);\n }\n ctx.lineTo(target.x, target.y);\n}\n\n/**\n * @private\n */\nexport function _bezierCurveTo(\n ctx: CanvasRenderingContext2D,\n previous: SplinePoint,\n target: SplinePoint,\n flip?: boolean\n) {\n if (!previous) {\n return ctx.lineTo(target.x, target.y);\n }\n ctx.bezierCurveTo(\n flip ? previous.cp1x : previous.cp2x,\n flip ? previous.cp1y : previous.cp2y,\n flip ? target.cp2x : target.cp1x,\n flip ? target.cp2y : target.cp1y,\n target.x,\n target.y);\n}\n\nfunction setRenderOpts(ctx: CanvasRenderingContext2D, opts: RenderTextOpts) {\n if (opts.translation) {\n ctx.translate(opts.translation[0], opts.translation[1]);\n }\n\n if (!isNullOrUndef(opts.rotation)) {\n ctx.rotate(opts.rotation);\n }\n\n if (opts.color) {\n ctx.fillStyle = opts.color;\n }\n\n if (opts.textAlign) {\n ctx.textAlign = opts.textAlign;\n }\n\n if (opts.textBaseline) {\n ctx.textBaseline = opts.textBaseline;\n }\n}\n\nfunction decorateText(\n ctx: CanvasRenderingContext2D,\n x: number,\n y: number,\n line: string,\n opts: RenderTextOpts\n) {\n if (opts.strikethrough || opts.underline) {\n /**\n * Now that IE11 support has been dropped, we can use more\n * of the TextMetrics object. The actual bounding boxes\n * are unflagged in Chrome, Firefox, Edge, and Safari so they\n * can be safely used.\n * See https://developer.mozilla.org/en-US/docs/Web/API/TextMetrics#Browser_compatibility\n */\n const metrics = ctx.measureText(line);\n const left = x - metrics.actualBoundingBoxLeft;\n const right = x + metrics.actualBoundingBoxRight;\n const top = y - metrics.actualBoundingBoxAscent;\n const bottom = y + metrics.actualBoundingBoxDescent;\n const yDecoration = opts.strikethrough ? (top + bottom) / 2 : bottom;\n\n ctx.strokeStyle = ctx.fillStyle;\n ctx.beginPath();\n ctx.lineWidth = opts.decorationWidth || 2;\n ctx.moveTo(left, yDecoration);\n ctx.lineTo(right, yDecoration);\n ctx.stroke();\n }\n}\n\nfunction drawBackdrop(ctx: CanvasRenderingContext2D, opts: BackdropOptions) {\n const oldColor = ctx.fillStyle;\n\n ctx.fillStyle = opts.color as string;\n ctx.fillRect(opts.left, opts.top, opts.width, opts.height);\n ctx.fillStyle = oldColor;\n}\n\n/**\n * Render text onto the canvas\n */\nexport function renderText(\n ctx: CanvasRenderingContext2D,\n text: string | string[],\n x: number,\n y: number,\n font: CanvasFontSpec,\n opts: RenderTextOpts = {}\n) {\n const lines = isArray(text) ? text : [text];\n const stroke = opts.strokeWidth > 0 && opts.strokeColor !== '';\n let i: number, line: string;\n\n ctx.save();\n ctx.font = font.string;\n setRenderOpts(ctx, opts);\n\n for (i = 0; i < lines.length; ++i) {\n line = lines[i];\n\n if (opts.backdrop) {\n drawBackdrop(ctx, opts.backdrop);\n }\n\n if (stroke) {\n if (opts.strokeColor) {\n ctx.strokeStyle = opts.strokeColor;\n }\n\n if (!isNullOrUndef(opts.strokeWidth)) {\n ctx.lineWidth = opts.strokeWidth;\n }\n\n ctx.strokeText(line, x, y, opts.maxWidth);\n }\n\n ctx.fillText(line, x, y, opts.maxWidth);\n decorateText(ctx, x, y, line, opts);\n\n y += Number(font.lineHeight);\n }\n\n ctx.restore();\n}\n\n/**\n * Add a path of a rectangle with rounded corners to the current sub-path\n * @param ctx - Context\n * @param rect - Bounding rect\n */\nexport function addRoundedRectPath(\n ctx: CanvasRenderingContext2D,\n rect: RoundedRect & { radius: TRBLCorners }\n) {\n const {x, y, w, h, radius} = rect;\n\n // top left arc\n ctx.arc(x + radius.topLeft, y + radius.topLeft, radius.topLeft, 1.5 * PI, PI, true);\n\n // line from top left to bottom left\n ctx.lineTo(x, y + h - radius.bottomLeft);\n\n // bottom left arc\n ctx.arc(x + radius.bottomLeft, y + h - radius.bottomLeft, radius.bottomLeft, PI, HALF_PI, true);\n\n // line from bottom left to bottom right\n ctx.lineTo(x + w - radius.bottomRight, y + h);\n\n // bottom right arc\n ctx.arc(x + w - radius.bottomRight, y + h - radius.bottomRight, radius.bottomRight, HALF_PI, 0, true);\n\n // line from bottom right to top right\n ctx.lineTo(x + w, y + radius.topRight);\n\n // top right arc\n ctx.arc(x + w - radius.topRight, y + radius.topRight, radius.topRight, 0, -HALF_PI, true);\n\n // line from top right to top left\n ctx.lineTo(x + radius.topLeft, y);\n}\n","import defaults from '../core/core.defaults.js';\nimport {isArray, isObject, toDimension, valueOrDefault} from './helpers.core.js';\nimport {toFontString} from './helpers.canvas.js';\nimport type {ChartArea, FontSpec, Point} from '../types/index.js';\nimport type {TRBL, TRBLCorners} from '../types/geometric.js';\n\nconst LINE_HEIGHT = /^(normal|(\\d+(?:\\.\\d+)?)(px|em|%)?)$/;\nconst FONT_STYLE = /^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;\n\n/**\n * @alias Chart.helpers.options\n * @namespace\n */\n/**\n * Converts the given line height `value` in pixels for a specific font `size`.\n * @param value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').\n * @param size - The font size (in pixels) used to resolve relative `value`.\n * @returns The effective line height in pixels (size * 1.2 if value is invalid).\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height\n * @since 2.7.0\n */\nexport function toLineHeight(value: number | string, size: number): number {\n const matches = ('' + value).match(LINE_HEIGHT);\n if (!matches || matches[1] === 'normal') {\n return size * 1.2;\n }\n\n value = +matches[2];\n\n switch (matches[3]) {\n case 'px':\n return value;\n case '%':\n value /= 100;\n break;\n default:\n break;\n }\n\n return size * value;\n}\n\nconst numberOrZero = (v: unknown) => +v || 0;\n\n/**\n * @param value\n * @param props\n */\nexport function _readValueToProps(value: number | Record, props: K[]): Record;\nexport function _readValueToProps(value: number | Record, props: Record): Record;\nexport function _readValueToProps(value: number | Record, props: string[] | Record) {\n const ret = {};\n const objProps = isObject(props);\n const keys = objProps ? Object.keys(props) : props;\n const read = isObject(value)\n ? objProps\n ? prop => valueOrDefault(value[prop], value[props[prop]])\n : prop => value[prop]\n : () => value;\n\n for (const prop of keys) {\n ret[prop] = numberOrZero(read(prop));\n }\n return ret;\n}\n\n/**\n * Converts the given value into a TRBL object.\n * @param value - If a number, set the value to all TRBL component,\n * else, if an object, use defined properties and sets undefined ones to 0.\n * x / y are shorthands for same value for left/right and top/bottom.\n * @returns The padding values (top, right, bottom, left)\n * @since 3.0.0\n */\nexport function toTRBL(value: number | TRBL | Point) {\n return _readValueToProps(value, {top: 'y', right: 'x', bottom: 'y', left: 'x'});\n}\n\n/**\n * Converts the given value into a TRBL corners object (similar with css border-radius).\n * @param value - If a number, set the value to all TRBL corner components,\n * else, if an object, use defined properties and sets undefined ones to 0.\n * @returns The TRBL corner values (topLeft, topRight, bottomLeft, bottomRight)\n * @since 3.0.0\n */\nexport function toTRBLCorners(value: number | TRBLCorners) {\n return _readValueToProps(value, ['topLeft', 'topRight', 'bottomLeft', 'bottomRight']);\n}\n\n/**\n * Converts the given value into a padding object with pre-computed width/height.\n * @param value - If a number, set the value to all TRBL component,\n * else, if an object, use defined properties and sets undefined ones to 0.\n * x / y are shorthands for same value for left/right and top/bottom.\n * @returns The padding values (top, right, bottom, left, width, height)\n * @since 2.7.0\n */\nexport function toPadding(value?: number | TRBL): ChartArea {\n const obj = toTRBL(value) as ChartArea;\n\n obj.width = obj.left + obj.right;\n obj.height = obj.top + obj.bottom;\n\n return obj;\n}\n\n/**\n * Parses font options and returns the font object.\n * @param options - A object that contains font options to be parsed.\n * @param fallback - A object that contains fallback font options.\n * @return The font object.\n * @private\n */\n\nexport function toFont(options: Partial, fallback?: Partial) {\n options = options || {};\n fallback = fallback || defaults.font as FontSpec;\n\n let size = valueOrDefault(options.size, fallback.size);\n\n if (typeof size === 'string') {\n size = parseInt(size, 10);\n }\n let style = valueOrDefault(options.style, fallback.style);\n if (style && !('' + style).match(FONT_STYLE)) {\n console.warn('Invalid font style specified: \"' + style + '\"');\n style = undefined;\n }\n\n const font = {\n family: valueOrDefault(options.family, fallback.family),\n lineHeight: toLineHeight(valueOrDefault(options.lineHeight, fallback.lineHeight), size),\n size,\n style,\n weight: valueOrDefault(options.weight, fallback.weight),\n string: ''\n };\n\n font.string = toFontString(font);\n return font;\n}\n\n/**\n * Evaluates the given `inputs` sequentially and returns the first defined value.\n * @param inputs - An array of values, falling back to the last value.\n * @param context - If defined and the current value is a function, the value\n * is called with `context` as first argument and the result becomes the new input.\n * @param index - If defined and the current value is an array, the value\n * at `index` become the new input.\n * @param info - object to return information about resolution in\n * @param info.cacheable - Will be set to `false` if option is not cacheable.\n * @since 2.7.0\n */\nexport function resolve(inputs: Array, context?: object, index?: number, info?: { cacheable: boolean }) {\n let cacheable = true;\n let i: number, ilen: number, value: unknown;\n\n for (i = 0, ilen = inputs.length; i < ilen; ++i) {\n value = inputs[i];\n if (value === undefined) {\n continue;\n }\n if (context !== undefined && typeof value === 'function') {\n value = value(context);\n cacheable = false;\n }\n if (index !== undefined && isArray(value)) {\n value = value[index % value.length];\n cacheable = false;\n }\n if (value !== undefined) {\n if (info && !cacheable) {\n info.cacheable = false;\n }\n return value;\n }\n }\n}\n\n/**\n * @param minmax\n * @param grace\n * @param beginAtZero\n * @private\n */\nexport function _addGrace(minmax: { min: number; max: number; }, grace: number | string, beginAtZero: boolean) {\n const {min, max} = minmax;\n const change = toDimension(grace, (max - min) / 2);\n const keepZero = (value: number, add: number) => beginAtZero && value === 0 ? 0 : value + add;\n return {\n min: keepZero(min, -Math.abs(change)),\n max: keepZero(max, change)\n };\n}\n\n/**\n * Create a context inheriting parentContext\n * @param parentContext\n * @param context\n * @returns\n */\nexport function createContext(parentContext: null, context: T): T;\nexport function createContext(parentContext: P, context: T): P & T;\nexport function createContext(parentContext: object, context: object) {\n return Object.assign(Object.create(parentContext), context);\n}\n","/* eslint-disable @typescript-eslint/no-use-before-define */\nimport type {AnyObject} from '../types/basic.js';\nimport type {ChartMeta} from '../types/index.js';\nimport type {\n ResolverObjectKey,\n ResolverCache,\n ResolverProxy,\n DescriptorDefaults,\n Descriptor,\n ContextCache,\n ContextProxy\n} from './helpers.config.types.js';\nimport {isArray, isFunction, isObject, resolveObjectKey, _capitalize} from './helpers.core.js';\n\nexport * from './helpers.config.types.js';\n\n/**\n * Creates a Proxy for resolving raw values for options.\n * @param scopes - The option scopes to look for values, in resolution order\n * @param prefixes - The prefixes for values, in resolution order.\n * @param rootScopes - The root option scopes\n * @param fallback - Parent scopes fallback\n * @param getTarget - callback for getting the target for changed values\n * @returns Proxy\n * @private\n */\nexport function _createResolver<\n T extends AnyObject[] = AnyObject[],\n R extends AnyObject[] = T\n>(\n scopes: T,\n prefixes = [''],\n rootScopes?: R,\n fallback?: ResolverObjectKey,\n getTarget = () => scopes[0]\n) {\n const finalRootScopes = rootScopes || scopes;\n if (typeof fallback === 'undefined') {\n fallback = _resolve('_fallback', scopes);\n }\n const cache: ResolverCache = {\n [Symbol.toStringTag]: 'Object',\n _cacheable: true,\n _scopes: scopes,\n _rootScopes: finalRootScopes,\n _fallback: fallback,\n _getTarget: getTarget,\n override: (scope: AnyObject) => _createResolver([scope, ...scopes], prefixes, finalRootScopes, fallback),\n };\n return new Proxy(cache, {\n /**\n * A trap for the delete operator.\n */\n deleteProperty(target, prop: string) {\n delete target[prop]; // remove from cache\n delete target._keys; // remove cached keys\n delete scopes[0][prop]; // remove from top level scope\n return true;\n },\n\n /**\n * A trap for getting property values.\n */\n get(target, prop: string) {\n return _cached(target, prop,\n () => _resolveWithPrefixes(prop, prefixes, scopes, target));\n },\n\n /**\n * A trap for Object.getOwnPropertyDescriptor.\n * Also used by Object.hasOwnProperty.\n */\n getOwnPropertyDescriptor(target, prop) {\n return Reflect.getOwnPropertyDescriptor(target._scopes[0], prop);\n },\n\n /**\n * A trap for Object.getPrototypeOf.\n */\n getPrototypeOf() {\n return Reflect.getPrototypeOf(scopes[0]);\n },\n\n /**\n * A trap for the in operator.\n */\n has(target, prop: string) {\n return getKeysFromAllScopes(target).includes(prop);\n },\n\n /**\n * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols.\n */\n ownKeys(target) {\n return getKeysFromAllScopes(target);\n },\n\n /**\n * A trap for setting property values.\n */\n set(target, prop: string, value) {\n const storage = target._storage || (target._storage = getTarget());\n target[prop] = storage[prop] = value; // set to top level scope + cache\n delete target._keys; // remove cached keys\n return true;\n }\n }) as ResolverProxy;\n}\n\n/**\n * Returns an Proxy for resolving option values with context.\n * @param proxy - The Proxy returned by `_createResolver`\n * @param context - Context object for scriptable/indexable options\n * @param subProxy - The proxy provided for scriptable options\n * @param descriptorDefaults - Defaults for descriptors\n * @private\n */\nexport function _attachContext<\n T extends AnyObject[] = AnyObject[],\n R extends AnyObject[] = T\n>(\n proxy: ResolverProxy,\n context: AnyObject,\n subProxy?: ResolverProxy,\n descriptorDefaults?: DescriptorDefaults\n) {\n const cache: ContextCache = {\n _cacheable: false,\n _proxy: proxy,\n _context: context,\n _subProxy: subProxy,\n _stack: new Set(),\n _descriptors: _descriptors(proxy, descriptorDefaults),\n setContext: (ctx: AnyObject) => _attachContext(proxy, ctx, subProxy, descriptorDefaults),\n override: (scope: AnyObject) => _attachContext(proxy.override(scope), context, subProxy, descriptorDefaults)\n };\n return new Proxy(cache, {\n /**\n * A trap for the delete operator.\n */\n deleteProperty(target, prop) {\n delete target[prop]; // remove from cache\n delete proxy[prop]; // remove from proxy\n return true;\n },\n\n /**\n * A trap for getting property values.\n */\n get(target, prop: string, receiver) {\n return _cached(target, prop,\n () => _resolveWithContext(target, prop, receiver));\n },\n\n /**\n * A trap for Object.getOwnPropertyDescriptor.\n * Also used by Object.hasOwnProperty.\n */\n getOwnPropertyDescriptor(target, prop) {\n return target._descriptors.allKeys\n ? Reflect.has(proxy, prop) ? {enumerable: true, configurable: true} : undefined\n : Reflect.getOwnPropertyDescriptor(proxy, prop);\n },\n\n /**\n * A trap for Object.getPrototypeOf.\n */\n getPrototypeOf() {\n return Reflect.getPrototypeOf(proxy);\n },\n\n /**\n * A trap for the in operator.\n */\n has(target, prop) {\n return Reflect.has(proxy, prop);\n },\n\n /**\n * A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols.\n */\n ownKeys() {\n return Reflect.ownKeys(proxy);\n },\n\n /**\n * A trap for setting property values.\n */\n set(target, prop, value) {\n proxy[prop] = value; // set to proxy\n delete target[prop]; // remove from cache\n return true;\n }\n }) as ContextProxy;\n}\n\n/**\n * @private\n */\nexport function _descriptors(\n proxy: ResolverCache,\n defaults: DescriptorDefaults = {scriptable: true, indexable: true}\n): Descriptor {\n const {_scriptable = defaults.scriptable, _indexable = defaults.indexable, _allKeys = defaults.allKeys} = proxy;\n return {\n allKeys: _allKeys,\n scriptable: _scriptable,\n indexable: _indexable,\n isScriptable: isFunction(_scriptable) ? _scriptable : () => _scriptable,\n isIndexable: isFunction(_indexable) ? _indexable : () => _indexable\n };\n}\n\nconst readKey = (prefix: string, name: string) => prefix ? prefix + _capitalize(name) : name;\nconst needsSubResolver = (prop: string, value: unknown) => isObject(value) && prop !== 'adapters' &&\n (Object.getPrototypeOf(value) === null || value.constructor === Object);\n\nfunction _cached(\n target: AnyObject,\n prop: string,\n resolve: () => unknown\n) {\n if (Object.prototype.hasOwnProperty.call(target, prop) || prop === 'constructor') {\n return target[prop];\n }\n\n const value = resolve();\n // cache the resolved value\n target[prop] = value;\n return value;\n}\n\nfunction _resolveWithContext(\n target: ContextCache,\n prop: string,\n receiver: AnyObject\n) {\n const {_proxy, _context, _subProxy, _descriptors: descriptors} = target;\n let value = _proxy[prop]; // resolve from proxy\n\n // resolve with context\n if (isFunction(value) && descriptors.isScriptable(prop)) {\n value = _resolveScriptable(prop, value, target, receiver);\n }\n if (isArray(value) && value.length) {\n value = _resolveArray(prop, value, target, descriptors.isIndexable);\n }\n if (needsSubResolver(prop, value)) {\n // if the resolved value is an object, create a sub resolver for it\n value = _attachContext(value, _context, _subProxy && _subProxy[prop], descriptors);\n }\n return value;\n}\n\nfunction _resolveScriptable(\n prop: string,\n getValue: (ctx: AnyObject, sub: AnyObject) => unknown,\n target: ContextCache,\n receiver: AnyObject\n) {\n const {_proxy, _context, _subProxy, _stack} = target;\n if (_stack.has(prop)) {\n throw new Error('Recursion detected: ' + Array.from(_stack).join('->') + '->' + prop);\n }\n _stack.add(prop);\n let value = getValue(_context, _subProxy || receiver);\n _stack.delete(prop);\n if (needsSubResolver(prop, value)) {\n // When scriptable option returns an object, create a resolver on that.\n value = createSubResolver(_proxy._scopes, _proxy, prop, value);\n }\n return value;\n}\n\nfunction _resolveArray(\n prop: string,\n value: unknown[],\n target: ContextCache,\n isIndexable: (key: string) => boolean\n) {\n const {_proxy, _context, _subProxy, _descriptors: descriptors} = target;\n\n if (typeof _context.index !== 'undefined' && isIndexable(prop)) {\n return value[_context.index % value.length];\n } else if (isObject(value[0])) {\n // Array of objects, return array or resolvers\n const arr = value;\n const scopes = _proxy._scopes.filter(s => s !== arr);\n value = [];\n for (const item of arr) {\n const resolver = createSubResolver(scopes, _proxy, prop, item);\n value.push(_attachContext(resolver, _context, _subProxy && _subProxy[prop], descriptors));\n }\n }\n return value;\n}\n\nfunction resolveFallback(\n fallback: ResolverObjectKey | ((prop: ResolverObjectKey, value: unknown) => ResolverObjectKey),\n prop: ResolverObjectKey,\n value: unknown\n) {\n return isFunction(fallback) ? fallback(prop, value) : fallback;\n}\n\nconst getScope = (key: ResolverObjectKey, parent: AnyObject) => key === true ? parent\n : typeof key === 'string' ? resolveObjectKey(parent, key) : undefined;\n\nfunction addScopes(\n set: Set,\n parentScopes: AnyObject[],\n key: ResolverObjectKey,\n parentFallback: ResolverObjectKey,\n value: unknown\n) {\n for (const parent of parentScopes) {\n const scope = getScope(key, parent);\n if (scope) {\n set.add(scope);\n const fallback = resolveFallback(scope._fallback, key, value);\n if (typeof fallback !== 'undefined' && fallback !== key && fallback !== parentFallback) {\n // When we reach the descriptor that defines a new _fallback, return that.\n // The fallback will resume to that new scope.\n return fallback;\n }\n } else if (scope === false && typeof parentFallback !== 'undefined' && key !== parentFallback) {\n // Fallback to `false` results to `false`, when falling back to different key.\n // For example `interaction` from `hover` or `plugins.tooltip` and `animation` from `animations`\n return null;\n }\n }\n return false;\n}\n\nfunction createSubResolver(\n parentScopes: AnyObject[],\n resolver: ResolverCache,\n prop: ResolverObjectKey,\n value: unknown\n) {\n const rootScopes = resolver._rootScopes;\n const fallback = resolveFallback(resolver._fallback, prop, value);\n const allScopes = [...parentScopes, ...rootScopes];\n const set = new Set();\n set.add(value);\n let key = addScopesFromKey(set, allScopes, prop, fallback || prop, value);\n if (key === null) {\n return false;\n }\n if (typeof fallback !== 'undefined' && fallback !== prop) {\n key = addScopesFromKey(set, allScopes, fallback, key, value);\n if (key === null) {\n return false;\n }\n }\n return _createResolver(Array.from(set), [''], rootScopes, fallback,\n () => subGetTarget(resolver, prop as string, value));\n}\n\nfunction addScopesFromKey(\n set: Set,\n allScopes: AnyObject[],\n key: ResolverObjectKey,\n fallback: ResolverObjectKey,\n item: unknown\n) {\n while (key) {\n key = addScopes(set, allScopes, key, fallback, item);\n }\n return key;\n}\n\nfunction subGetTarget(\n resolver: ResolverCache,\n prop: string,\n value: unknown\n) {\n const parent = resolver._getTarget();\n if (!(prop in parent)) {\n parent[prop] = {};\n }\n const target = parent[prop];\n if (isArray(target) && isObject(value)) {\n // For array of objects, the object is used to store updated values\n return value;\n }\n return target || {};\n}\n\nfunction _resolveWithPrefixes(\n prop: string,\n prefixes: string[],\n scopes: AnyObject[],\n proxy: ResolverProxy\n) {\n let value: unknown;\n for (const prefix of prefixes) {\n value = _resolve(readKey(prefix, prop), scopes);\n if (typeof value !== 'undefined') {\n return needsSubResolver(prop, value)\n ? createSubResolver(scopes, proxy, prop, value)\n : value;\n }\n }\n}\n\nfunction _resolve(key: string, scopes: AnyObject[]) {\n for (const scope of scopes) {\n if (!scope) {\n continue;\n }\n const value = scope[key];\n if (typeof value !== 'undefined') {\n return value;\n }\n }\n}\n\nfunction getKeysFromAllScopes(target: ResolverCache) {\n let keys = target._keys;\n if (!keys) {\n keys = target._keys = resolveKeysFromAllScopes(target._scopes);\n }\n return keys;\n}\n\nfunction resolveKeysFromAllScopes(scopes: AnyObject[]) {\n const set = new Set();\n for (const scope of scopes) {\n for (const key of Object.keys(scope).filter(k => !k.startsWith('_'))) {\n set.add(key);\n }\n }\n return Array.from(set);\n}\n\nexport function _parseObjectDataRadialScale(\n meta: ChartMeta<'line' | 'scatter'>,\n data: AnyObject[],\n start: number,\n count: number\n) {\n const {iScale} = meta;\n const {key = 'r'} = this._parsing;\n const parsed = new Array<{r: unknown}>(count);\n let i: number, ilen: number, index: number, item: AnyObject;\n\n for (i = 0, ilen = count; i < ilen; ++i) {\n index = i + start;\n item = data[index];\n parsed[i] = {\n r: iScale.parse(resolveObjectKey(item, key), index)\n };\n }\n return parsed;\n}\n","import {almostEquals, distanceBetweenPoints, sign} from './helpers.math.js';\nimport {_isPointInArea} from './helpers.canvas.js';\nimport type {ChartArea} from '../types/index.js';\nimport type {SplinePoint} from '../types/geometric.js';\n\nconst EPSILON = Number.EPSILON || 1e-14;\n\ntype OptionalSplinePoint = SplinePoint | false\nconst getPoint = (points: SplinePoint[], i: number): OptionalSplinePoint => i < points.length && !points[i].skip && points[i];\nconst getValueAxis = (indexAxis: 'x' | 'y') => indexAxis === 'x' ? 'y' : 'x';\n\nexport function splineCurve(\n firstPoint: SplinePoint,\n middlePoint: SplinePoint,\n afterPoint: SplinePoint,\n t: number\n): {\n previous: SplinePoint\n next: SplinePoint\n } {\n // Props to Rob Spencer at scaled innovation for his post on splining between points\n // http://scaledinnovation.com/analytics/splines/aboutSplines.html\n\n // This function must also respect \"skipped\" points\n\n const previous = firstPoint.skip ? middlePoint : firstPoint;\n const current = middlePoint;\n const next = afterPoint.skip ? middlePoint : afterPoint;\n const d01 = distanceBetweenPoints(current, previous);\n const d12 = distanceBetweenPoints(next, current);\n\n let s01 = d01 / (d01 + d12);\n let s12 = d12 / (d01 + d12);\n\n // If all points are the same, s01 & s02 will be inf\n s01 = isNaN(s01) ? 0 : s01;\n s12 = isNaN(s12) ? 0 : s12;\n\n const fa = t * s01; // scaling factor for triangle Ta\n const fb = t * s12;\n\n return {\n previous: {\n x: current.x - fa * (next.x - previous.x),\n y: current.y - fa * (next.y - previous.y)\n },\n next: {\n x: current.x + fb * (next.x - previous.x),\n y: current.y + fb * (next.y - previous.y)\n }\n };\n}\n\n/**\n * Adjust tangents to ensure monotonic properties\n */\nfunction monotoneAdjust(points: SplinePoint[], deltaK: number[], mK: number[]) {\n const pointsLen = points.length;\n\n let alphaK: number, betaK: number, tauK: number, squaredMagnitude: number, pointCurrent: OptionalSplinePoint;\n let pointAfter = getPoint(points, 0);\n for (let i = 0; i < pointsLen - 1; ++i) {\n pointCurrent = pointAfter;\n pointAfter = getPoint(points, i + 1);\n if (!pointCurrent || !pointAfter) {\n continue;\n }\n\n if (almostEquals(deltaK[i], 0, EPSILON)) {\n mK[i] = mK[i + 1] = 0;\n continue;\n }\n\n alphaK = mK[i] / deltaK[i];\n betaK = mK[i + 1] / deltaK[i];\n squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);\n if (squaredMagnitude <= 9) {\n continue;\n }\n\n tauK = 3 / Math.sqrt(squaredMagnitude);\n mK[i] = alphaK * tauK * deltaK[i];\n mK[i + 1] = betaK * tauK * deltaK[i];\n }\n}\n\nfunction monotoneCompute(points: SplinePoint[], mK: number[], indexAxis: 'x' | 'y' = 'x') {\n const valueAxis = getValueAxis(indexAxis);\n const pointsLen = points.length;\n let delta: number, pointBefore: OptionalSplinePoint, pointCurrent: OptionalSplinePoint;\n let pointAfter = getPoint(points, 0);\n\n for (let i = 0; i < pointsLen; ++i) {\n pointBefore = pointCurrent;\n pointCurrent = pointAfter;\n pointAfter = getPoint(points, i + 1);\n if (!pointCurrent) {\n continue;\n }\n\n const iPixel = pointCurrent[indexAxis];\n const vPixel = pointCurrent[valueAxis];\n if (pointBefore) {\n delta = (iPixel - pointBefore[indexAxis]) / 3;\n pointCurrent[`cp1${indexAxis}`] = iPixel - delta;\n pointCurrent[`cp1${valueAxis}`] = vPixel - delta * mK[i];\n }\n if (pointAfter) {\n delta = (pointAfter[indexAxis] - iPixel) / 3;\n pointCurrent[`cp2${indexAxis}`] = iPixel + delta;\n pointCurrent[`cp2${valueAxis}`] = vPixel + delta * mK[i];\n }\n }\n}\n\n/**\n * This function calculates Bézier control points in a similar way than |splineCurve|,\n * but preserves monotonicity of the provided data and ensures no local extremums are added\n * between the dataset discrete points due to the interpolation.\n * See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation\n */\nexport function splineCurveMonotone(points: SplinePoint[], indexAxis: 'x' | 'y' = 'x') {\n const valueAxis = getValueAxis(indexAxis);\n const pointsLen = points.length;\n const deltaK: number[] = Array(pointsLen).fill(0);\n const mK: number[] = Array(pointsLen);\n\n // Calculate slopes (deltaK) and initialize tangents (mK)\n let i, pointBefore: OptionalSplinePoint, pointCurrent: OptionalSplinePoint;\n let pointAfter = getPoint(points, 0);\n\n for (i = 0; i < pointsLen; ++i) {\n pointBefore = pointCurrent;\n pointCurrent = pointAfter;\n pointAfter = getPoint(points, i + 1);\n if (!pointCurrent) {\n continue;\n }\n\n if (pointAfter) {\n const slopeDelta = pointAfter[indexAxis] - pointCurrent[indexAxis];\n\n // In the case of two points that appear at the same x pixel, slopeDeltaX is 0\n deltaK[i] = slopeDelta !== 0 ? (pointAfter[valueAxis] - pointCurrent[valueAxis]) / slopeDelta : 0;\n }\n mK[i] = !pointBefore ? deltaK[i]\n : !pointAfter ? deltaK[i - 1]\n : (sign(deltaK[i - 1]) !== sign(deltaK[i])) ? 0\n : (deltaK[i - 1] + deltaK[i]) / 2;\n }\n\n monotoneAdjust(points, deltaK, mK);\n\n monotoneCompute(points, mK, indexAxis);\n}\n\nfunction capControlPoint(pt: number, min: number, max: number) {\n return Math.max(Math.min(pt, max), min);\n}\n\nfunction capBezierPoints(points: SplinePoint[], area: ChartArea) {\n let i, ilen, point, inArea, inAreaPrev;\n let inAreaNext = _isPointInArea(points[0], area);\n for (i = 0, ilen = points.length; i < ilen; ++i) {\n inAreaPrev = inArea;\n inArea = inAreaNext;\n inAreaNext = i < ilen - 1 && _isPointInArea(points[i + 1], area);\n if (!inArea) {\n continue;\n }\n point = points[i];\n if (inAreaPrev) {\n point.cp1x = capControlPoint(point.cp1x, area.left, area.right);\n point.cp1y = capControlPoint(point.cp1y, area.top, area.bottom);\n }\n if (inAreaNext) {\n point.cp2x = capControlPoint(point.cp2x, area.left, area.right);\n point.cp2y = capControlPoint(point.cp2y, area.top, area.bottom);\n }\n }\n}\n\n/**\n * @private\n */\nexport function _updateBezierControlPoints(\n points: SplinePoint[],\n options,\n area: ChartArea,\n loop: boolean,\n indexAxis: 'x' | 'y'\n) {\n let i: number, ilen: number, point: SplinePoint, controlPoints: ReturnType;\n\n // Only consider points that are drawn in case the spanGaps option is used\n if (options.spanGaps) {\n points = points.filter((pt) => !pt.skip);\n }\n\n if (options.cubicInterpolationMode === 'monotone') {\n splineCurveMonotone(points, indexAxis);\n } else {\n let prev = loop ? points[points.length - 1] : points[0];\n for (i = 0, ilen = points.length; i < ilen; ++i) {\n point = points[i];\n controlPoints = splineCurve(\n prev,\n point,\n points[Math.min(i + 1, ilen - (loop ? 0 : 1)) % ilen],\n options.tension\n );\n point.cp1x = controlPoints.previous.x;\n point.cp1y = controlPoints.previous.y;\n point.cp2x = controlPoints.next.x;\n point.cp2y = controlPoints.next.y;\n prev = point;\n }\n }\n\n if (options.capBezierPoints) {\n capBezierPoints(points, area);\n }\n}\n","import type {ChartArea, Scale} from '../types/index.js';\nimport type PrivateChart from '../core/core.controller.js';\nimport type {Chart, ChartEvent} from '../types.js';\nimport {INFINITY} from './helpers.math.js';\n\n/**\n * @private\n */\nexport function _isDomSupported(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\n/**\n * @private\n */\nexport function _getParentNode(domNode: HTMLCanvasElement): HTMLCanvasElement {\n let parent = domNode.parentNode;\n if (parent && parent.toString() === '[object ShadowRoot]') {\n parent = (parent as ShadowRoot).host;\n }\n return parent as HTMLCanvasElement;\n}\n\n/**\n * convert max-width/max-height values that may be percentages into a number\n * @private\n */\n\nfunction parseMaxStyle(styleValue: string | number, node: HTMLElement, parentProperty: string) {\n let valueInPixels: number;\n if (typeof styleValue === 'string') {\n valueInPixels = parseInt(styleValue, 10);\n\n if (styleValue.indexOf('%') !== -1) {\n // percentage * size in dimension\n valueInPixels = (valueInPixels / 100) * node.parentNode[parentProperty];\n }\n } else {\n valueInPixels = styleValue;\n }\n\n return valueInPixels;\n}\n\nconst getComputedStyle = (element: HTMLElement): CSSStyleDeclaration =>\n element.ownerDocument.defaultView.getComputedStyle(element, null);\n\nexport function getStyle(el: HTMLElement, property: string): string {\n return getComputedStyle(el).getPropertyValue(property);\n}\n\nconst positions = ['top', 'right', 'bottom', 'left'];\nfunction getPositionedStyle(styles: CSSStyleDeclaration, style: string, suffix?: string): ChartArea {\n const result = {} as ChartArea;\n suffix = suffix ? '-' + suffix : '';\n for (let i = 0; i < 4; i++) {\n const pos = positions[i];\n result[pos] = parseFloat(styles[style + '-' + pos + suffix]) || 0;\n }\n result.width = result.left + result.right;\n result.height = result.top + result.bottom;\n return result;\n}\n\nconst useOffsetPos = (x: number, y: number, target: HTMLElement | EventTarget) =>\n (x > 0 || y > 0) && (!target || !(target as HTMLElement).shadowRoot);\n\n/**\n * @param e\n * @param canvas\n * @returns Canvas position\n */\nfunction getCanvasPosition(\n e: Event | TouchEvent | MouseEvent,\n canvas: HTMLCanvasElement\n): {\n x: number;\n y: number;\n box: boolean;\n } {\n const touches = (e as TouchEvent).touches;\n const source = (touches && touches.length ? touches[0] : e) as MouseEvent;\n const {offsetX, offsetY} = source as MouseEvent;\n let box = false;\n let x, y;\n if (useOffsetPos(offsetX, offsetY, e.target)) {\n x = offsetX;\n y = offsetY;\n } else {\n const rect = canvas.getBoundingClientRect();\n x = source.clientX - rect.left;\n y = source.clientY - rect.top;\n box = true;\n }\n return {x, y, box};\n}\n\n/**\n * Gets an event's x, y coordinates, relative to the chart area\n * @param event\n * @param chart\n * @returns x and y coordinates of the event\n */\n\nexport function getRelativePosition(\n event: Event | ChartEvent | TouchEvent | MouseEvent,\n chart: Chart | PrivateChart\n): { x: number; y: number } {\n if ('native' in event) {\n return event;\n }\n\n const {canvas, currentDevicePixelRatio} = chart;\n const style = getComputedStyle(canvas);\n const borderBox = style.boxSizing === 'border-box';\n const paddings = getPositionedStyle(style, 'padding');\n const borders = getPositionedStyle(style, 'border', 'width');\n const {x, y, box} = getCanvasPosition(event, canvas);\n const xOffset = paddings.left + (box && borders.left);\n const yOffset = paddings.top + (box && borders.top);\n\n let {width, height} = chart;\n if (borderBox) {\n width -= paddings.width + borders.width;\n height -= paddings.height + borders.height;\n }\n return {\n x: Math.round((x - xOffset) / width * canvas.width / currentDevicePixelRatio),\n y: Math.round((y - yOffset) / height * canvas.height / currentDevicePixelRatio)\n };\n}\n\nfunction getContainerSize(canvas: HTMLCanvasElement, width: number, height: number): Partial {\n let maxWidth: number, maxHeight: number;\n\n if (width === undefined || height === undefined) {\n const container = canvas && _getParentNode(canvas);\n if (!container) {\n width = canvas.clientWidth;\n height = canvas.clientHeight;\n } else {\n const rect = container.getBoundingClientRect(); // this is the border box of the container\n const containerStyle = getComputedStyle(container);\n const containerBorder = getPositionedStyle(containerStyle, 'border', 'width');\n const containerPadding = getPositionedStyle(containerStyle, 'padding');\n width = rect.width - containerPadding.width - containerBorder.width;\n height = rect.height - containerPadding.height - containerBorder.height;\n maxWidth = parseMaxStyle(containerStyle.maxWidth, container, 'clientWidth');\n maxHeight = parseMaxStyle(containerStyle.maxHeight, container, 'clientHeight');\n }\n }\n return {\n width,\n height,\n maxWidth: maxWidth || INFINITY,\n maxHeight: maxHeight || INFINITY\n };\n}\n\nconst round1 = (v: number) => Math.round(v * 10) / 10;\n\n// eslint-disable-next-line complexity\nexport function getMaximumSize(\n canvas: HTMLCanvasElement,\n bbWidth?: number,\n bbHeight?: number,\n aspectRatio?: number\n): { width: number; height: number } {\n const style = getComputedStyle(canvas);\n const margins = getPositionedStyle(style, 'margin');\n const maxWidth = parseMaxStyle(style.maxWidth, canvas, 'clientWidth') || INFINITY;\n const maxHeight = parseMaxStyle(style.maxHeight, canvas, 'clientHeight') || INFINITY;\n const containerSize = getContainerSize(canvas, bbWidth, bbHeight);\n let {width, height} = containerSize;\n\n if (style.boxSizing === 'content-box') {\n const borders = getPositionedStyle(style, 'border', 'width');\n const paddings = getPositionedStyle(style, 'padding');\n width -= paddings.width + borders.width;\n height -= paddings.height + borders.height;\n }\n width = Math.max(0, width - margins.width);\n height = Math.max(0, aspectRatio ? width / aspectRatio : height - margins.height);\n width = round1(Math.min(width, maxWidth, containerSize.maxWidth));\n height = round1(Math.min(height, maxHeight, containerSize.maxHeight));\n if (width && !height) {\n // https://github.com/chartjs/Chart.js/issues/4659\n // If the canvas has width, but no height, default to aspectRatio of 2 (canvas default)\n height = round1(width / 2);\n }\n\n const maintainHeight = bbWidth !== undefined || bbHeight !== undefined;\n\n if (maintainHeight && aspectRatio && containerSize.height && height > containerSize.height) {\n height = containerSize.height;\n width = round1(Math.floor(height * aspectRatio));\n }\n\n return {width, height};\n}\n\n/**\n * @param chart\n * @param forceRatio\n * @param forceStyle\n * @returns True if the canvas context size or transformation has changed.\n */\nexport function retinaScale(\n chart: Chart | PrivateChart,\n forceRatio: number,\n forceStyle?: boolean\n): boolean | void {\n const pixelRatio = forceRatio || 1;\n const deviceHeight = Math.floor(chart.height * pixelRatio);\n const deviceWidth = Math.floor(chart.width * pixelRatio);\n\n (chart as PrivateChart).height = Math.floor(chart.height);\n (chart as PrivateChart).width = Math.floor(chart.width);\n\n const canvas = chart.canvas;\n\n // If no style has been set on the canvas, the render size is used as display size,\n // making the chart visually bigger, so let's enforce it to the \"correct\" values.\n // See https://github.com/chartjs/Chart.js/issues/3575\n if (canvas.style && (forceStyle || (!canvas.style.height && !canvas.style.width))) {\n canvas.style.height = `${chart.height}px`;\n canvas.style.width = `${chart.width}px`;\n }\n\n if (chart.currentDevicePixelRatio !== pixelRatio\n || canvas.height !== deviceHeight\n || canvas.width !== deviceWidth) {\n (chart as PrivateChart).currentDevicePixelRatio = pixelRatio;\n canvas.height = deviceHeight;\n canvas.width = deviceWidth;\n chart.ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);\n return true;\n }\n return false;\n}\n\n/**\n * Detects support for options object argument in addEventListener.\n * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support\n * @private\n */\nexport const supportsEventListenerOptions = (function() {\n let passiveSupported = false;\n try {\n const options = {\n get passive() { // This function will be called when the browser attempts to access the passive property.\n passiveSupported = true;\n return false;\n }\n } as EventListenerOptions;\n\n if (_isDomSupported()) {\n window.addEventListener('test', null, options);\n window.removeEventListener('test', null, options);\n }\n } catch (e) {\n // continue regardless of error\n }\n return passiveSupported;\n}());\n\n/**\n * The \"used\" size is the final value of a dimension property after all calculations have\n * been performed. This method uses the computed style of `element` but returns undefined\n * if the computed style is not expressed in pixels. That can happen in some cases where\n * `element` has a size relative to its parent and this last one is not yet displayed,\n * for example because of `display: none` on a parent node.\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value\n * @returns Size in pixels or undefined if unknown.\n */\n\nexport function readUsedSize(\n element: HTMLElement,\n property: 'width' | 'height'\n): number | undefined {\n const value = getStyle(element, property);\n const matches = value && value.match(/^(\\d+)(\\.\\d+)?px$/);\n return matches ? +matches[1] : undefined;\n}\n","import type {Point, SplinePoint} from '../types/geometric.js';\n\n/**\n * @private\n */\nexport function _pointInLine(p1: Point, p2: Point, t: number, mode?) { // eslint-disable-line @typescript-eslint/no-unused-vars\n return {\n x: p1.x + t * (p2.x - p1.x),\n y: p1.y + t * (p2.y - p1.y)\n };\n}\n\n/**\n * @private\n */\nexport function _steppedInterpolation(\n p1: Point,\n p2: Point,\n t: number, mode: 'middle' | 'after' | unknown\n) {\n return {\n x: p1.x + t * (p2.x - p1.x),\n y: mode === 'middle' ? t < 0.5 ? p1.y : p2.y\n : mode === 'after' ? t < 1 ? p1.y : p2.y\n : t > 0 ? p2.y : p1.y\n };\n}\n\n/**\n * @private\n */\nexport function _bezierInterpolation(p1: SplinePoint, p2: SplinePoint, t: number, mode?) { // eslint-disable-line @typescript-eslint/no-unused-vars\n const cp1 = {x: p1.cp2x, y: p1.cp2y};\n const cp2 = {x: p2.cp1x, y: p2.cp1y};\n const a = _pointInLine(p1, cp1, t);\n const b = _pointInLine(cp1, cp2, t);\n const c = _pointInLine(cp2, p2, t);\n const d = _pointInLine(a, b, t);\n const e = _pointInLine(b, c, t);\n return _pointInLine(d, e, t);\n}\n","export interface RTLAdapter {\n x(x: number): number;\n setWidth(w: number): void;\n textAlign(align: 'center' | 'left' | 'right'): 'center' | 'left' | 'right';\n xPlus(x: number, value: number): number;\n leftForLtr(x: number, itemWidth: number): number;\n}\n\nconst getRightToLeftAdapter = function(rectX: number, width: number): RTLAdapter {\n return {\n x(x) {\n return rectX + rectX + width - x;\n },\n setWidth(w) {\n width = w;\n },\n textAlign(align) {\n if (align === 'center') {\n return align;\n }\n return align === 'right' ? 'left' : 'right';\n },\n xPlus(x, value) {\n return x - value;\n },\n leftForLtr(x, itemWidth) {\n return x - itemWidth;\n },\n };\n};\n\nconst getLeftToRightAdapter = function(): RTLAdapter {\n return {\n x(x) {\n return x;\n },\n setWidth(w) { // eslint-disable-line no-unused-vars\n },\n textAlign(align) {\n return align;\n },\n xPlus(x, value) {\n return x + value;\n },\n leftForLtr(x, _itemWidth) { // eslint-disable-line @typescript-eslint/no-unused-vars\n return x;\n },\n };\n};\n\nexport function getRtlAdapter(rtl: boolean, rectX: number, width: number) {\n return rtl ? getRightToLeftAdapter(rectX, width) : getLeftToRightAdapter();\n}\n\nexport function overrideTextDirection(ctx: CanvasRenderingContext2D, direction: 'ltr' | 'rtl') {\n let style: CSSStyleDeclaration, original: [string, string];\n if (direction === 'ltr' || direction === 'rtl') {\n style = ctx.canvas.style;\n original = [\n style.getPropertyValue('direction'),\n style.getPropertyPriority('direction'),\n ];\n\n style.setProperty('direction', direction, 'important');\n (ctx as { prevTextDirection?: [string, string] }).prevTextDirection = original;\n }\n}\n\nexport function restoreTextDirection(ctx: CanvasRenderingContext2D, original?: [string, string]) {\n if (original !== undefined) {\n delete (ctx as { prevTextDirection?: [string, string] }).prevTextDirection;\n ctx.canvas.style.setProperty('direction', original[0], original[1]);\n }\n}\n","import {_angleBetween, _angleDiff, _isBetween, _normalizeAngle} from './helpers.math.js';\nimport {createContext} from './helpers.options.js';\nimport {isPatternOrGradient} from './helpers.color.js';\n\n/**\n * @typedef { import('../elements/element.line.js').default } LineElement\n * @typedef { import('../elements/element.point.js').default } PointElement\n * @typedef {{start: number, end: number, loop: boolean, style?: any}} Segment\n */\n\nfunction propertyFn(property) {\n if (property === 'angle') {\n return {\n between: _angleBetween,\n compare: _angleDiff,\n normalize: _normalizeAngle,\n };\n }\n return {\n between: _isBetween,\n compare: (a, b) => a - b,\n normalize: x => x\n };\n}\n\nfunction normalizeSegment({start, end, count, loop, style}) {\n return {\n start: start % count,\n end: end % count,\n loop: loop && (end - start + 1) % count === 0,\n style\n };\n}\n\nfunction getSegment(segment, points, bounds) {\n const {property, start: startBound, end: endBound} = bounds;\n const {between, normalize} = propertyFn(property);\n const count = points.length;\n // eslint-disable-next-line prefer-const\n let {start, end, loop} = segment;\n let i, ilen;\n\n if (loop) {\n start += count;\n end += count;\n for (i = 0, ilen = count; i < ilen; ++i) {\n if (!between(normalize(points[start % count][property]), startBound, endBound)) {\n break;\n }\n start--;\n end--;\n }\n start %= count;\n end %= count;\n }\n\n if (end < start) {\n end += count;\n }\n return {start, end, loop, style: segment.style};\n}\n\n/**\n * Returns the sub-segment(s) of a line segment that fall in the given bounds\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} [segment.style] - segment style\n * @param {PointElement[]} points - the points that this segment refers to\n * @param {object} [bounds]\n * @param {string} bounds.property - the property of a `PointElement` we are bounding. `x`, `y` or `angle`.\n * @param {number} bounds.start - start value of the property\n * @param {number} bounds.end - end value of the property\n * @private\n **/\nexport function _boundSegment(segment, points, bounds) {\n if (!bounds) {\n return [segment];\n }\n\n const {property, start: startBound, end: endBound} = bounds;\n const count = points.length;\n const {compare, between, normalize} = propertyFn(property);\n const {start, end, loop, style} = getSegment(segment, points, bounds);\n\n const result = [];\n let inside = false;\n let subStart = null;\n let value, point, prevValue;\n\n const startIsBefore = () => between(startBound, prevValue, value) && compare(startBound, prevValue) !== 0;\n const endIsBefore = () => compare(endBound, value) === 0 || between(endBound, prevValue, value);\n const shouldStart = () => inside || startIsBefore();\n const shouldStop = () => !inside || endIsBefore();\n\n for (let i = start, prev = start; i <= end; ++i) {\n point = points[i % count];\n\n if (point.skip) {\n continue;\n }\n\n value = normalize(point[property]);\n\n if (value === prevValue) {\n continue;\n }\n\n inside = between(value, startBound, endBound);\n\n if (subStart === null && shouldStart()) {\n subStart = compare(value, startBound) === 0 ? i : prev;\n }\n\n if (subStart !== null && shouldStop()) {\n result.push(normalizeSegment({start: subStart, end: i, loop, count, style}));\n subStart = null;\n }\n prev = i;\n prevValue = value;\n }\n\n if (subStart !== null) {\n result.push(normalizeSegment({start: subStart, end, loop, count, style}));\n }\n\n return result;\n}\n\n\n/**\n * Returns the segments of the line that are inside given bounds\n * @param {LineElement} line\n * @param {object} [bounds]\n * @param {string} bounds.property - the property we are bounding with. `x`, `y` or `angle`.\n * @param {number} bounds.start - start value of the `property`\n * @param {number} bounds.end - end value of the `property`\n * @private\n */\nexport function _boundSegments(line, bounds) {\n const result = [];\n const segments = line.segments;\n\n for (let i = 0; i < segments.length; i++) {\n const sub = _boundSegment(segments[i], line.points, bounds);\n if (sub.length) {\n result.push(...sub);\n }\n }\n return result;\n}\n\n/**\n * Find start and end index of a line.\n */\nfunction findStartAndEnd(points, count, loop, spanGaps) {\n let start = 0;\n let end = count - 1;\n\n if (loop && !spanGaps) {\n // loop and not spanning gaps, first find a gap to start from\n while (start < count && !points[start].skip) {\n start++;\n }\n }\n\n // find first non skipped point (after the first gap possibly)\n while (start < count && points[start].skip) {\n start++;\n }\n\n // if we looped to count, start needs to be 0\n start %= count;\n\n if (loop) {\n // loop will go past count, if start > 0\n end += start;\n }\n\n while (end > start && points[end % count].skip) {\n end--;\n }\n\n // end could be more than count, normalize\n end %= count;\n\n return {start, end};\n}\n\n/**\n * Compute solid segments from Points, when spanGaps === false\n * @param {PointElement[]} points - the points\n * @param {number} start - start index\n * @param {number} max - max index (can go past count on a loop)\n * @param {boolean} loop - boolean indicating that this would be a loop if no gaps are found\n */\nfunction solidSegments(points, start, max, loop) {\n const count = points.length;\n const result = [];\n let last = start;\n let prev = points[start];\n let end;\n\n for (end = start + 1; end <= max; ++end) {\n const cur = points[end % count];\n if (cur.skip || cur.stop) {\n if (!prev.skip) {\n loop = false;\n result.push({start: start % count, end: (end - 1) % count, loop});\n // @ts-ignore\n start = last = cur.stop ? end : null;\n }\n } else {\n last = end;\n if (prev.skip) {\n start = end;\n }\n }\n prev = cur;\n }\n\n if (last !== null) {\n result.push({start: start % count, end: last % count, loop});\n }\n\n return result;\n}\n\n/**\n * Compute the continuous segments that define the whole line\n * There can be skipped points within a segment, if spanGaps is true.\n * @param {LineElement} line\n * @param {object} [segmentOptions]\n * @return {Segment[]}\n * @private\n */\nexport function _computeSegments(line, segmentOptions) {\n const points = line.points;\n const spanGaps = line.options.spanGaps;\n const count = points.length;\n\n if (!count) {\n return [];\n }\n\n const loop = !!line._loop;\n const {start, end} = findStartAndEnd(points, count, loop, spanGaps);\n\n if (spanGaps === true) {\n return splitByStyles(line, [{start, end, loop}], points, segmentOptions);\n }\n\n const max = end < start ? end + count : end;\n const completeLoop = !!line._fullLoop && start === 0 && end === count - 1;\n return splitByStyles(line, solidSegments(points, start, max, completeLoop), points, segmentOptions);\n}\n\n/**\n * @param {Segment[]} segments\n * @param {PointElement[]} points\n * @param {object} [segmentOptions]\n * @return {Segment[]}\n */\nfunction splitByStyles(line, segments, points, segmentOptions) {\n if (!segmentOptions || !segmentOptions.setContext || !points) {\n return segments;\n }\n return doSplitByStyles(line, segments, points, segmentOptions);\n}\n\n/**\n * @param {LineElement} line\n * @param {Segment[]} segments\n * @param {PointElement[]} points\n * @param {object} [segmentOptions]\n * @return {Segment[]}\n */\nfunction doSplitByStyles(line, segments, points, segmentOptions) {\n const chartContext = line._chart.getContext();\n const baseStyle = readStyle(line.options);\n const {_datasetIndex: datasetIndex, options: {spanGaps}} = line;\n const count = points.length;\n const result = [];\n let prevStyle = baseStyle;\n let start = segments[0].start;\n let i = start;\n\n function addStyle(s, e, l, st) {\n const dir = spanGaps ? -1 : 1;\n if (s === e) {\n return;\n }\n // Style can not start/end on a skipped point, adjust indices accordingly\n s += count;\n while (points[s % count].skip) {\n s -= dir;\n }\n while (points[e % count].skip) {\n e += dir;\n }\n if (s % count !== e % count) {\n result.push({start: s % count, end: e % count, loop: l, style: st});\n prevStyle = st;\n start = e % count;\n }\n }\n\n for (const segment of segments) {\n start = spanGaps ? start : segment.start;\n let prev = points[start % count];\n let style;\n for (i = start + 1; i <= segment.end; i++) {\n const pt = points[i % count];\n style = readStyle(segmentOptions.setContext(createContext(chartContext, {\n type: 'segment',\n p0: prev,\n p1: pt,\n p0DataIndex: (i - 1) % count,\n p1DataIndex: i % count,\n datasetIndex\n })));\n if (styleChanged(style, prevStyle)) {\n addStyle(start, i - 1, segment.loop, prevStyle);\n }\n prev = pt;\n prevStyle = style;\n }\n if (start < i - 1) {\n addStyle(start, i - 1, segment.loop, prevStyle);\n }\n }\n\n return result;\n}\n\nfunction readStyle(options) {\n return {\n backgroundColor: options.backgroundColor,\n borderCapStyle: options.borderCapStyle,\n borderDash: options.borderDash,\n borderDashOffset: options.borderDashOffset,\n borderJoinStyle: options.borderJoinStyle,\n borderWidth: options.borderWidth,\n borderColor: options.borderColor\n };\n}\n\nfunction styleChanged(style, prevStyle) {\n if (!prevStyle) {\n return false;\n }\n const cache = [];\n const replacer = function(key, value) {\n if (!isPatternOrGradient(value)) {\n return value;\n }\n if (!cache.includes(value)) {\n cache.push(value);\n }\n return cache.indexOf(value);\n };\n return JSON.stringify(style, replacer) !== JSON.stringify(prevStyle, replacer);\n}\n","import type {Chart, ChartArea, ChartMeta, Scale, TRBL} from '../types/index.js';\n\nfunction getSizeForArea(scale: Scale, chartArea: ChartArea, field: keyof ChartArea) {\n return scale.options.clip ? scale[field] : chartArea[field];\n}\n\nfunction getDatasetArea(meta: ChartMeta, chartArea: ChartArea): TRBL {\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\nexport function getDatasetClipArea(chart: Chart, meta: ChartMeta): TRBL | false {\n const clip = meta._clip;\n if (clip.disabled) {\n return false;\n }\n const area = getDatasetArea(meta, chart.chartArea);\n\n return {\n left: clip.left === false ? 0 : area.left - (clip.left === true ? 0 : clip.left),\n right: clip.right === false ? chart.width : area.right + (clip.right === true ? 0 : clip.right),\n top: clip.top === false ? 0 : area.top - (clip.top === true ? 0 : clip.top),\n bottom: clip.bottom === false ? chart.height : area.bottom + (clip.bottom === true ? 0 : clip.bottom)\n };\n}\n"],"names":["noop","uid","id","isNullOrUndef","value","undefined","isArray","Array","type","Object","prototype","toString","call","slice","isObject","isNumberFinite","Number","isFinite","finiteOrDefault","defaultValue","valueOrDefault","toPercentage","dimension","endsWith","parseFloat","toDimension","callback","fn","args","thisArg","apply","each","loopable","reverse","i","len","keys","length","_elementsEqual","a0","a1","ilen","v0","v1","datasetIndex","index","clone","source","map","target","create","klen","k","isValidKey","key","indexOf","_merger","options","tval","sval","merge","sources","merger","current","mergeIf","_mergerIf","hasOwnProperty","_deprecated","scope","previous","console","warn","keyResolvers","v","x","o","y","_splitKey","parts","split","tmp","part","push","_getKeyResolver","obj","resolveObjectKey","resolver","_capitalize","str","charAt","toUpperCase","defined","isFunction","setsEqual","a","b","size","item","has","_isClickEvent","e","PI","Math","TAU","PITAU","INFINITY","POSITIVE_INFINITY","RAD_PER_DEG","HALF_PI","QUARTER_PI","TWO_THIRDS_PI","log10","sign","almostEquals","epsilon","abs","niceNum","range","roundedRange","round","niceRange","pow","floor","fraction","niceFraction","_factorize","result","sqrt","sort","pop","isNonPrimitive","n","Symbol","toPrimitive","isNumber","isNaN","almostWhole","rounded","_setMinAndMaxByKey","array","property","min","max","toRadians","degrees","toDegrees","radians","_decimalPlaces","isFiniteNumber","p","getAngleFromPoint","centrePoint","anglePoint","distanceFromXCenter","distanceFromYCenter","radialDistanceFromCenter","angle","atan2","distance","distanceBetweenPoints","pt1","pt2","_angleDiff","_normalizeAngle","_angleBetween","start","end","sameAngleIsFullCircle","s","angleToStart","angleToEnd","startToAngle","endToAngle","_limitValue","_int16Range","_isBetween","_lookup","table","cmp","hi","lo","mid","_lookupByKey","last","ti","_rlookupByKey","_filterBetween","values","arrayEvents","listenArrayEvents","listener","_chartjs","listeners","defineProperty","configurable","enumerable","forEach","method","base","res","object","unlistenArrayEvents","stub","splice","_arrayUnique","items","set","Set","from","fontString","pixelSize","fontStyle","fontFamily","requestAnimFrame","window","requestAnimationFrame","throttled","argsToUse","ticking","debounce","delay","timeout","clearTimeout","setTimeout","_toLeftRightCenter","align","_alignStartEnd","_textX","left","right","rtl","check","_getStartAndCountOfVisiblePoints","meta","points","animationsDisabled","pointCount","count","_sorted","iScale","vScale","_parsed","spanGaps","dataset","axis","minDefined","maxDefined","getUserBounds","getPixelForValue","distanceToDefinedLo","findIndex","point","distanceToDefinedHi","_scaleRangesChanged","xScale","yScale","_scaleRanges","newRanges","xmin","xmax","ymin","ymax","changed","assign","atEdge","t","elasticIn","sin","elasticOut","effects","linear","easeInQuad","easeOutQuad","easeInOutQuad","easeInCubic","easeOutCubic","easeInOutCubic","easeInQuart","easeOutQuart","easeInOutQuart","easeInQuint","easeOutQuint","easeInOutQuint","easeInSine","cos","easeOutSine","easeInOutSine","easeInExpo","easeOutExpo","easeInOutExpo","easeInCirc","easeOutCirc","easeInOutCirc","easeInElastic","easeOutElastic","easeInOutElastic","easeInBack","easeOutBack","easeInOutBack","easeInBounce","easeOutBounce","m","d","easeInOutBounce","isPatternOrGradient","color","Color","getHoverColor","saturate","darken","hexString","numbers","colors","applyAnimationsDefaults","defaults","duration","easing","loop","to","describe","_fallback","_indexable","_scriptable","name","properties","active","animation","resize","show","animations","visible","hide","applyLayoutsDefaults","autoPadding","padding","top","bottom","intlCache","Map","getNumberFormat","locale","cacheKey","JSON","stringify","formatter","get","Intl","NumberFormat","formatNumber","num","format","formatters","numeric","tickValue","ticks","chart","notation","delta","maxTick","calculateDelta","logDelta","numDecimal","minimumFractionDigits","maximumFractionDigits","logarithmic","remain","significand","includes","applyScaleDefaults","display","offset","beginAtZero","bounds","clip","grace","grid","lineWidth","drawOnChartArea","drawTicks","tickLength","tickWidth","_ctx","tickColor","border","dash","dashOffset","width","title","text","minRotation","maxRotation","mirror","textStrokeWidth","textStrokeColor","autoSkip","autoSkipPadding","labelOffset","Ticks","minor","major","crossAlign","showLabelBackdrop","backdropColor","backdropPadding","route","startsWith","overrides","descriptors","getScope","node","root","Defaults","constructor","_descriptors","_appliers","backgroundColor","borderColor","datasets","devicePixelRatio","context","platform","getDevicePixelRatio","elements","events","font","family","style","lineHeight","weight","hover","hoverBackgroundColor","ctx","hoverBorderColor","hoverColor","indexAxis","interaction","mode","intersect","includeInvisible","maintainAspectRatio","onHover","onClick","parsing","plugins","responsive","scale","scales","showLine","drawActiveElementsOnTop","override","targetScope","targetName","scopeObject","targetScopeObject","privateName","defineProperties","writable","local","appliers","toFontString","_measureText","data","gc","longest","string","textWidth","measureText","_longestText","arrayOfThings","cache","garbageCollect","save","j","jlen","thing","nestedThing","restore","gcLen","_alignPixel","pixel","currentDevicePixelRatio","halfWidth","clearCanvas","canvas","getContext","resetTransform","clearRect","height","drawPoint","drawPointLegend","w","xOffset","yOffset","cornerRadius","xOffsetW","yOffsetW","pointStyle","rotation","radius","rad","translate","rotate","drawImage","beginPath","ellipse","arc","closePath","moveTo","lineTo","SQRT1_2","rect","fill","borderWidth","stroke","_isPointInArea","area","margin","clipArea","unclipArea","_steppedLineTo","flip","midpoint","_bezierCurveTo","bezierCurveTo","cp1x","cp2x","cp1y","cp2y","setRenderOpts","opts","translation","fillStyle","textAlign","textBaseline","decorateText","line","strikethrough","underline","metrics","actualBoundingBoxLeft","actualBoundingBoxRight","actualBoundingBoxAscent","actualBoundingBoxDescent","yDecoration","strokeStyle","decorationWidth","drawBackdrop","oldColor","fillRect","renderText","lines","strokeWidth","strokeColor","backdrop","strokeText","maxWidth","fillText","addRoundedRectPath","h","topLeft","bottomLeft","bottomRight","topRight","LINE_HEIGHT","FONT_STYLE","toLineHeight","matches","match","numberOrZero","_readValueToProps","props","ret","objProps","read","prop","toTRBL","toTRBLCorners","toPadding","toFont","fallback","parseInt","resolve","inputs","info","cacheable","_addGrace","minmax","change","keepZero","add","createContext","parentContext","_createResolver","scopes","prefixes","rootScopes","getTarget","finalRootScopes","_resolve","toStringTag","_cacheable","_scopes","_rootScopes","_getTarget","Proxy","deleteProperty","_keys","_cached","_resolveWithPrefixes","getOwnPropertyDescriptor","Reflect","getPrototypeOf","getKeysFromAllScopes","ownKeys","storage","_storage","_attachContext","proxy","subProxy","descriptorDefaults","_proxy","_context","_subProxy","_stack","setContext","receiver","_resolveWithContext","allKeys","scriptable","indexable","_allKeys","isScriptable","isIndexable","readKey","prefix","needsSubResolver","_resolveScriptable","_resolveArray","getValue","Error","join","delete","createSubResolver","arr","filter","resolveFallback","parent","addScopes","parentScopes","parentFallback","allScopes","addScopesFromKey","subGetTarget","resolveKeysFromAllScopes","_parseObjectDataRadialScale","_parsing","parsed","r","parse","EPSILON","getPoint","skip","getValueAxis","splineCurve","firstPoint","middlePoint","afterPoint","next","d01","d12","s01","s12","fa","fb","monotoneAdjust","deltaK","mK","pointsLen","alphaK","betaK","tauK","squaredMagnitude","pointCurrent","pointAfter","monotoneCompute","valueAxis","pointBefore","iPixel","vPixel","splineCurveMonotone","slopeDelta","capControlPoint","pt","capBezierPoints","inArea","inAreaPrev","inAreaNext","_updateBezierControlPoints","controlPoints","cubicInterpolationMode","prev","tension","_isDomSupported","document","_getParentNode","domNode","parentNode","host","parseMaxStyle","styleValue","parentProperty","valueInPixels","getComputedStyle","element","ownerDocument","defaultView","getStyle","el","getPropertyValue","positions","getPositionedStyle","styles","suffix","pos","useOffsetPos","shadowRoot","getCanvasPosition","touches","offsetX","offsetY","box","getBoundingClientRect","clientX","clientY","getRelativePosition","event","borderBox","boxSizing","paddings","borders","getContainerSize","maxHeight","container","clientWidth","clientHeight","containerStyle","containerBorder","containerPadding","round1","getMaximumSize","bbWidth","bbHeight","aspectRatio","margins","containerSize","maintainHeight","retinaScale","forceRatio","forceStyle","pixelRatio","deviceHeight","deviceWidth","setTransform","supportsEventListenerOptions","passiveSupported","passive","addEventListener","removeEventListener","readUsedSize","_pointInLine","p1","p2","_steppedInterpolation","_bezierInterpolation","cp1","cp2","c","getRightToLeftAdapter","rectX","setWidth","xPlus","leftForLtr","itemWidth","getLeftToRightAdapter","_itemWidth","getRtlAdapter","overrideTextDirection","direction","original","getPropertyPriority","setProperty","prevTextDirection","restoreTextDirection","propertyFn","between","compare","normalize","normalizeSegment","getSegment","segment","startBound","endBound","_boundSegment","inside","subStart","prevValue","startIsBefore","endIsBefore","shouldStart","shouldStop","_boundSegments","segments","sub","findStartAndEnd","solidSegments","cur","stop","_computeSegments","segmentOptions","_loop","splitByStyles","completeLoop","_fullLoop","doSplitByStyles","chartContext","_chart","baseStyle","readStyle","_datasetIndex","prevStyle","addStyle","l","st","dir","p0","p0DataIndex","p1DataIndex","styleChanged","borderCapStyle","borderDash","borderDashOffset","borderJoinStyle","replacer","getSizeForArea","chartArea","field","getDatasetArea","getDatasetClipArea","_clip","disabled"],"mappings":";;;;;;;;AAAA;;;;IAUO,SAASA,IAAO,GAAA;AACrB,YACD;AAED;;AAEC,IACM,MAAMC,GAAM,GAAC,CAAA,IAAM;AACxB,IAAA,IAAIC,EAAK,GAAA,CAAA,CAAA;AACT,IAAA,OAAO,IAAMA,EAAAA,EAAAA,CAAAA;AACf,CAAA,IAAK;AAEL;;;;AAIC,IACM,SAASC,aAAcC,CAAAA,KAAc,EAA6B;IACvE,OAAOA,KAAAA,KAAU,IAAI,IAAIA,KAAUC,KAAAA,SAAAA,CAAAA;AACrC,CAAC;AAED;;;;AAIC,IACM,SAASC,OAAqBF,CAAAA,KAAc,EAAgB;AACjE,IAAA,IAAIG,MAAMD,OAAO,IAAIC,KAAMD,CAAAA,OAAO,CAACF,KAAQ,CAAA,EAAA;AACzC,QAAA,OAAO,IAAI,CAAA;KACZ;AACD,IAAA,MAAMI,OAAOC,MAAOC,CAAAA,SAAS,CAACC,QAAQ,CAACC,IAAI,CAACR,KAAAA,CAAAA,CAA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AA,CAAA;AACF;;;;"} \ No newline at end of file diff --git a/frontend/node_modules/chart.js/dist/controllers/controller.bar.d.ts b/frontend/node_modules/chart.js/dist/controllers/controller.bar.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6cd6db53497c830d266a6ea53f88b09ef5134952 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/controllers/controller.bar.d.ts @@ -0,0 +1,65 @@ +export default class BarController extends DatasetController { + static id: string; + /** + * @type {any} + */ + static overrides: any; + /** + * Overriding primitive data parsing since we support mixed primitive/array + * data for float bars + * @protected + */ + protected parsePrimitiveData(meta: any, data: any, start: any, count: any): any[]; + /** + * Overriding array data parsing since we support mixed primitive/array + * data for float bars + * @protected + */ + protected parseArrayData(meta: any, data: any, start: any, count: any): any[]; + /** + * Overriding object data parsing since we support mixed primitive/array + * value-scale data for float bars + * @protected + */ + protected parseObjectData(meta: any, data: any, start: any, count: any): any[]; + update(mode: any): void; + /** + * Returns the stacks based on groups and bar visibility. + * @param {number} [last] - The dataset index + * @param {number} [dataIndex] - The data index of the ruler + * @returns {string[]} The list of stack IDs + * @private + */ + private _getStacks; + /** + * Returns the effective number of stacks based on groups and bar visibility. + * @private + */ + private _getStackCount; + _getAxisCount(): number; + getFirstScaleIdForIndexAxis(): string; + _getAxis(): string[]; + /** + * Returns the stack index for the given dataset based on groups and bar visibility. + * @param {number} [datasetIndex] - The dataset index + * @param {string} [name] - The stack name to find + * @param {number} [dataIndex] + * @returns {number} The stack index + * @private + */ + private _getStackIndex; + /** + * @private + */ + private _getRuler; + /** + * Note: pixel values are not clamped to the scale area. + * @private + */ + private _calculateBarValuePixels; + /** + * @private + */ + private _calculateBarIndexPixels; +} +import DatasetController from "../core/core.datasetController.js"; diff --git a/frontend/node_modules/chart.js/dist/controllers/controller.bubble.d.ts b/frontend/node_modules/chart.js/dist/controllers/controller.bubble.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fd1c798462ad3cf3efff399254332ceebef0800a --- /dev/null +++ b/frontend/node_modules/chart.js/dist/controllers/controller.bubble.d.ts @@ -0,0 +1,35 @@ +export default class BubbleController extends DatasetController { + static id: string; + /** + * @type {any} + */ + static overrides: any; + /** + * Parse array of primitive values + * @protected + */ + protected parsePrimitiveData(meta: any, data: any, start: any, count: any): any; + /** + * Parse array of arrays + * @protected + */ + protected parseArrayData(meta: any, data: any, start: any, count: any): any; + /** + * Parse array of objects + * @protected + */ + protected parseObjectData(meta: any, data: any, start: any, count: any): any; + /** + * @protected + */ + protected getMaxOverflow(): number; + /** + * @protected + */ + protected getLabelAndValue(index: any): { + label: any; + value: string; + }; + update(mode: any): void; +} +import DatasetController from "../core/core.datasetController.js"; diff --git a/frontend/node_modules/chart.js/dist/controllers/controller.doughnut.d.ts b/frontend/node_modules/chart.js/dist/controllers/controller.doughnut.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8510ed916659f7f9a340f5cd67ab0c6ca7aa225a --- /dev/null +++ b/frontend/node_modules/chart.js/dist/controllers/controller.doughnut.d.ts @@ -0,0 +1,64 @@ +export default class DoughnutController extends DatasetController { + static id: string; + static descriptors: { + _scriptable: (name: any) => boolean; + _indexable: (name: any) => boolean; + }; + /** + * @type {any} + */ + static overrides: any; + constructor(chart: any, datasetIndex: any); + innerRadius: number; + outerRadius: number; + offsetX: number; + offsetY: number; + /** + * Override data parsing, since we are not using scales + */ + parse(start: any, count: any): void; + /** + * @private + */ + private _getRotation; + /** + * @private + */ + private _getCircumference; + /** + * Get the maximal rotation & circumference extents + * across all visible datasets. + */ + _getRotationExtents(): { + rotation: number; + circumference: number; + }; + /** + * @private + */ + private _circumference; + calculateTotal(): number; + calculateCircumference(value: any): number; + getLabelAndValue(index: any): { + label: any; + value: string; + }; + getMaxBorderWidth(arcs: any): number; + getMaxOffset(arcs: any): number; + /** + * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly + * @private + */ + private _getRingWeightOffset; + /** + * @private + */ + private _getRingWeight; + /** + * Returns the sum of all visible data set weights. + * @private + */ + private _getVisibleDatasetWeightTotal; +} +export type Chart = import('../core/core.controller.js').default; +import DatasetController from "../core/core.datasetController.js"; diff --git a/frontend/node_modules/chart.js/dist/controllers/controller.line.d.ts b/frontend/node_modules/chart.js/dist/controllers/controller.line.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..82bc42c57099ef2394c2c5b62c1435b60fcab4ac --- /dev/null +++ b/frontend/node_modules/chart.js/dist/controllers/controller.line.d.ts @@ -0,0 +1,13 @@ +export default class LineController extends DatasetController { + static id: string; + /** + * @type {any} + */ + static overrides: any; + update(mode: any): void; + /** + * @protected + */ + protected getMaxOverflow(): any; +} +import DatasetController from "../core/core.datasetController.js"; diff --git a/frontend/node_modules/chart.js/dist/controllers/controller.pie.d.ts b/frontend/node_modules/chart.js/dist/controllers/controller.pie.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fcb0a24abc862b9e4da6e38cc69f632812a53aa2 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/controllers/controller.pie.d.ts @@ -0,0 +1,3 @@ +export default class PieController extends DoughnutController { +} +import DoughnutController from "./controller.doughnut.js"; diff --git a/frontend/node_modules/chart.js/dist/controllers/controller.polarArea.d.ts b/frontend/node_modules/chart.js/dist/controllers/controller.polarArea.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b27ddf96971869a663a8d6d91f483447c66b1a00 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/controllers/controller.polarArea.d.ts @@ -0,0 +1,35 @@ +export default class PolarAreaController extends DatasetController { + static id: string; + /** + * @type {any} + */ + static overrides: any; + constructor(chart: any, datasetIndex: any); + innerRadius: number; + outerRadius: number; + getLabelAndValue(index: any): { + label: any; + value: string; + }; + parseObjectData(meta: any, data: any, start: any, count: any): { + r: unknown; + }[]; + update(mode: any): void; + /** + * @protected + */ + protected getMinMax(): { + min: number; + max: number; + }; + /** + * @private + */ + private _updateRadius; + countVisibleElements(): number; + /** + * @private + */ + private _computeAngle; +} +import DatasetController from "../core/core.datasetController.js"; diff --git a/frontend/node_modules/chart.js/dist/controllers/controller.radar.d.ts b/frontend/node_modules/chart.js/dist/controllers/controller.radar.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9a06593c06d76b4508ae83437656f1e1f31c0fa4 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/controllers/controller.radar.d.ts @@ -0,0 +1,19 @@ +export default class RadarController extends DatasetController { + static id: string; + /** + * @type {any} + */ + static overrides: any; + /** + * @protected + */ + protected getLabelAndValue(index: any): { + label: any; + value: string; + }; + parseObjectData(meta: any, data: any, start: any, count: any): { + r: unknown; + }[]; + update(mode: any): void; +} +import DatasetController from "../core/core.datasetController.js"; diff --git a/frontend/node_modules/chart.js/dist/controllers/controller.scatter.d.ts b/frontend/node_modules/chart.js/dist/controllers/controller.scatter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf5cde647728d10d9083d6fe7b908a0b52e8fc11 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/controllers/controller.scatter.d.ts @@ -0,0 +1,20 @@ +export default class ScatterController extends DatasetController { + static id: string; + /** + * @type {any} + */ + static overrides: any; + /** + * @protected + */ + protected getLabelAndValue(index: any): { + label: any; + value: string; + }; + update(mode: any): void; + /** + * @protected + */ + protected getMaxOverflow(): any; +} +import DatasetController from "../core/core.datasetController.js"; diff --git a/frontend/node_modules/chart.js/dist/controllers/index.d.ts b/frontend/node_modules/chart.js/dist/controllers/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ff3fdc64c444017f10dfd11b05f4eb31f3cb26c7 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/controllers/index.d.ts @@ -0,0 +1,8 @@ +export { default as BarController } from "./controller.bar.js"; +export { default as BubbleController } from "./controller.bubble.js"; +export { default as DoughnutController } from "./controller.doughnut.js"; +export { default as LineController } from "./controller.line.js"; +export { default as PolarAreaController } from "./controller.polarArea.js"; +export { default as PieController } from "./controller.pie.js"; +export { default as RadarController } from "./controller.radar.js"; +export { default as ScatterController } from "./controller.scatter.js"; diff --git a/frontend/node_modules/chart.js/dist/core/core.adapters.d.ts b/frontend/node_modules/chart.js/dist/core/core.adapters.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..949c393a0f3d364cba4ad514cc96b031d00b7785 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.adapters.d.ts @@ -0,0 +1,67 @@ +/** + * @namespace Chart._adapters + * @since 2.8.0 + * @private + */ +import type { AnyObject } from '../types/basic.js'; +import type { ChartOptions } from '../types/index.js'; +export type TimeUnit = 'millisecond' | 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'; +export interface DateAdapter { + readonly options: T; + /** + * Will called with chart options after adapter creation. + */ + init(this: DateAdapter, chartOptions: ChartOptions): void; + /** + * Returns a map of time formats for the supported formatting units defined + * in Unit as well as 'datetime' representing a detailed date/time string. + */ + formats(this: DateAdapter): Record; + /** + * Parses the given `value` and return the associated timestamp. + * @param value - the value to parse (usually comes from the data) + * @param [format] - the expected data format + */ + parse(this: DateAdapter, value: unknown, format?: string): number | null; + /** + * Returns the formatted date in the specified `format` for a given `timestamp`. + * @param timestamp - the timestamp to format + * @param format - the date/time token + */ + format(this: DateAdapter, timestamp: number, format: string): string; + /** + * Adds the specified `amount` of `unit` to the given `timestamp`. + * @param timestamp - the input timestamp + * @param amount - the amount to add + * @param unit - the unit as string + */ + add(this: DateAdapter, timestamp: number, amount: number, unit: TimeUnit): number; + /** + * Returns the number of `unit` between the given timestamps. + * @param a - the input timestamp (reference) + * @param b - the timestamp to subtract + * @param unit - the unit as string + */ + diff(this: DateAdapter, a: number, b: number, unit: TimeUnit): number; + /** + * Returns start of `unit` for the given `timestamp`. + * @param timestamp - the input timestamp + * @param unit - the unit as string + * @param [weekday] - the ISO day of the week with 1 being Monday + * and 7 being Sunday (only needed if param *unit* is `isoWeek`). + */ + startOf(this: DateAdapter, timestamp: number, unit: TimeUnit | 'isoWeek', weekday?: number | boolean): number; + /** + * Returns end of `unit` for the given `timestamp`. + * @param timestamp - the input timestamp + * @param unit - the unit as string + */ + endOf(this: DateAdapter, timestamp: number, unit: TimeUnit): number; +} +declare const _default: { + _date: { + new (options?: AnyObject): DateAdapter; + override(members: Partial, "options">>): void; + }; +}; +export default _default; diff --git a/frontend/node_modules/chart.js/dist/core/core.animation.d.ts b/frontend/node_modules/chart.js/dist/core/core.animation.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f5a1308941eaba21b09612141b85a8581f7b49f0 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.animation.d.ts @@ -0,0 +1,21 @@ +export default class Animation { + constructor(cfg: any, target: any, prop: any, to: any); + _active: boolean; + _fn: any; + _easing: any; + _start: number; + _duration: number; + _total: number; + _loop: boolean; + _target: any; + _prop: any; + _from: unknown; + _to: any; + _promises: any[]; + active(): boolean; + update(cfg: any, to: any, date: any): void; + cancel(): void; + tick(date: any): void; + wait(): Promise; + _notify(resolved: any): void; +} diff --git a/frontend/node_modules/chart.js/dist/core/core.animations.d.ts b/frontend/node_modules/chart.js/dist/core/core.animations.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..40d11f880740cdaf77b89e7dc5274cd212e10611 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.animations.d.ts @@ -0,0 +1,22 @@ +export default class Animations { + constructor(chart: any, config: any); + _chart: any; + _properties: Map; + configure(config: any): void; + /** + * Utility to handle animation of `options`. + * @private + */ + private _animateOptions; + /** + * @private + */ + private _createAnimations; + /** + * Update `target` properties to new values, using configured animations + * @param {object} target - object to update + * @param {object} values - new target properties + * @returns {boolean|undefined} - `true` if animations were started + **/ + update(target: object, values: object): boolean | undefined; +} diff --git a/frontend/node_modules/chart.js/dist/core/core.animations.defaults.d.ts b/frontend/node_modules/chart.js/dist/core/core.animations.defaults.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..25f588c33f11c871c03f55ac8b49a1599bb10887 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.animations.defaults.d.ts @@ -0,0 +1 @@ +export function applyAnimationsDefaults(defaults: any): void; diff --git a/frontend/node_modules/chart.js/dist/core/core.animator.d.ts b/frontend/node_modules/chart.js/dist/core/core.animator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f0d06503989807d7c928c1d810dc136cfafcd57 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.animator.d.ts @@ -0,0 +1,67 @@ +/** + * @typedef { import('./core.animation.js').default } Animation + * @typedef { import('./core.controller.js').default } Chart + */ +/** + * Please use the module's default export which provides a singleton instance + * Note: class is export for typedoc + */ +export class Animator { + _request: any; + _charts: Map; + _running: boolean; + _lastDate: number; + /** + * @private + */ + private _notify; + /** + * @private + */ + private _refresh; + /** + * @private + */ + private _update; + /** + * @private + */ + private _getAnims; + /** + * @param {Chart} chart + * @param {string} event - event name + * @param {Function} cb - callback + */ + listen(chart: Chart, event: string, cb: Function): void; + /** + * Add animations + * @param {Chart} chart + * @param {Animation[]} items - animations + */ + add(chart: Chart, items: Animation[]): void; + /** + * Counts number of active animations for the chart + * @param {Chart} chart + */ + has(chart: Chart): boolean; + /** + * Start animating (all charts) + * @param {Chart} chart + */ + start(chart: Chart): void; + running(chart: any): boolean; + /** + * Stop all animations for the chart + * @param {Chart} chart + */ + stop(chart: Chart): void; + /** + * Remove chart from Animator + * @param {Chart} chart + */ + remove(chart: Chart): boolean; +} +declare const _default: Animator; +export default _default; +export type Animation = import('./core.animation.js').default; +export type Chart = import('./core.controller.js').default; diff --git a/frontend/node_modules/chart.js/dist/core/core.config.d.ts b/frontend/node_modules/chart.js/dist/core/core.config.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d2631daed2521af678efb8e877197f9cdfd7541 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.config.d.ts @@ -0,0 +1,86 @@ +export function getIndexAxis(type: any, options: any): any; +export function determineAxis(id: any, ...scaleOptions: any[]): any; +export default class Config { + constructor(config: any); + _config: any; + _scopeCache: Map; + _resolverCache: Map; + get platform(): any; + set type(arg: any); + get type(): any; + set data(arg: any); + get data(): any; + set options(arg: any); + get options(): any; + get plugins(): any; + update(): void; + clearCache(): void; + /** + * Returns the option scope keys for resolving dataset options. + * These keys do not include the dataset itself, because it is not under options. + * @param {string} datasetType + * @return {string[][]} + */ + datasetScopeKeys(datasetType: string): string[][]; + /** + * Returns the option scope keys for resolving dataset animation options. + * These keys do not include the dataset itself, because it is not under options. + * @param {string} datasetType + * @param {string} transition + * @return {string[][]} + */ + datasetAnimationScopeKeys(datasetType: string, transition: string): string[][]; + /** + * Returns the options scope keys for resolving element options that belong + * to an dataset. These keys do not include the dataset itself, because it + * is not under options. + * @param {string} datasetType + * @param {string} elementType + * @return {string[][]} + */ + datasetElementScopeKeys(datasetType: string, elementType: string): string[][]; + /** + * Returns the options scope keys for resolving plugin options. + * @param {{id: string, additionalOptionScopes?: string[]}} plugin + * @return {string[][]} + */ + pluginScopeKeys(plugin: { + id: string; + additionalOptionScopes?: string[]; + }): string[][]; + /** + * @private + */ + private _cachedScopes; + /** + * Resolves the objects from options and defaults for option value resolution. + * @param {object} mainScope - The main scope object for options + * @param {string[][]} keyLists - The arrays of keys in resolution order + * @param {boolean} [resetCache] - reset the cache for this mainScope + */ + getOptionScopes(mainScope: object, keyLists: string[][], resetCache?: boolean): any; + /** + * Returns the option scopes for resolving chart options + * @return {object[]} + */ + chartOptionScopes(): object[]; + /** + * @param {object[]} scopes + * @param {string[]} names + * @param {function|object} context + * @param {string[]} [prefixes] + * @return {object} + */ + resolveNamedOptions(scopes: object[], names: string[], context: Function | object, prefixes?: string[]): object; + /** + * @param {object[]} scopes + * @param {object} [context] + * @param {string[]} [prefixes] + * @param {{scriptable: boolean, indexable: boolean, allKeys?: boolean}} [descriptorDefaults] + */ + createResolver(scopes: object[], context?: object, prefixes?: string[], descriptorDefaults?: { + scriptable: boolean; + indexable: boolean; + allKeys?: boolean; + }): any; +} diff --git a/frontend/node_modules/chart.js/dist/core/core.controller.d.ts b/frontend/node_modules/chart.js/dist/core/core.controller.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e64eaf76b006e13b7e35fe11161f7c98510d9df --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.controller.d.ts @@ -0,0 +1,257 @@ +export default Chart; +export type ChartEvent = import('../types/index.js').ChartEvent; +export type Point = import('../types/index.js').Point; +declare class Chart { + static defaults: import("./core.defaults.js").Defaults; + static instances: {}; + static overrides: any; + static registry: import("./core.registry.js").Registry; + static version: string; + static getChart: (key: any) => any; + static register(...items: any[]): void; + static unregister(...items: any[]): void; + constructor(item: any, userConfig: any); + config: Config; + platform: any; + id: number; + ctx: any; + canvas: any; + width: any; + height: any; + _options: any; + _aspectRatio: any; + _layers: any[]; + _metasets: any[]; + _stacks: any; + boxes: any[]; + currentDevicePixelRatio: any; + chartArea: any; + _active: any[]; + _lastEvent: import("../types/index.js").ChartEvent; + _listeners: {}; + /** @type {?{attach?: function, detach?: function, resize?: function}} */ + _responsiveListeners: { + attach?: Function; + detach?: Function; + resize?: Function; + }; + _sortedMetasets: any[]; + scales: {}; + _plugins: PluginService; + $proxies: {}; + _hiddenIndices: {}; + attached: boolean; + _animationsDisabled: boolean; + $context: { + chart: Chart; + type: string; + }; + _doResize: (mode?: any) => number; + _dataChanges: any[]; + get aspectRatio(): any; + set data(arg: any); + get data(): any; + set options(arg: any); + get options(): any; + get registry(): import("./core.registry.js").Registry; + /** + * @private + */ + private _initialize; + clear(): Chart; + stop(): Chart; + /** + * Resize the chart to its container or to explicit dimensions. + * @param {number} [width] + * @param {number} [height] + */ + resize(width?: number, height?: number): void; + _resizeBeforeDraw: { + width: number; + height: number; + }; + _resize(width: any, height: any): void; + ensureScalesHaveIDs(): void; + /** + * Builds a map of scale ID to scale object for future lookup. + */ + buildOrUpdateScales(): void; + /** + * @private + */ + private _updateMetasets; + /** + * @private + */ + private _removeUnreferencedMetasets; + buildOrUpdateControllers(): any[]; + /** + * Reset the elements of all datasets + * @private + */ + private _resetElements; + /** + * Resets the chart back to its state before the initial animation + */ + reset(): void; + update(mode: any): void; + _minPadding: number; + /** + * @private + */ + private _updateScales; + /** + * @private + */ + private _checkEventBindings; + /** + * @private + */ + private _updateHiddenIndices; + /** + * @private + */ + private _getUniformDataChanges; + /** + * Updates the chart layout unless a plugin returns `false` to the `beforeLayout` + * hook, in which case, plugins will not be called on `afterLayout`. + * @private + */ + private _updateLayout; + /** + * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate` + * hook, in which case, plugins will not be called on `afterDatasetsUpdate`. + * @private + */ + private _updateDatasets; + /** + * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate` + * hook, in which case, plugins will not be called on `afterDatasetUpdate`. + * @private + */ + private _updateDataset; + render(): void; + draw(): void; + /** + * @private + */ + private _getSortedDatasetMetas; + /** + * Gets the visible dataset metas in drawing order + * @return {object[]} + */ + getSortedVisibleDatasetMetas(): object[]; + /** + * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw` + * hook, in which case, plugins will not be called on `afterDatasetsDraw`. + * @private + */ + private _drawDatasets; + /** + * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw` + * hook, in which case, plugins will not be called on `afterDatasetDraw`. + * @private + */ + private _drawDataset; + /** + * Checks whether the given point is in the chart area. + * @param {Point} point - in relative coordinates (see, e.g., getRelativePosition) + * @returns {boolean} + */ + isPointInArea(point: Point): boolean; + getElementsAtEventForMode(e: any, mode: any, options: any, useFinalPosition: any): any; + getDatasetMeta(datasetIndex: any): any; + getContext(): { + chart: Chart; + type: string; + }; + getVisibleDatasetCount(): number; + isDatasetVisible(datasetIndex: any): boolean; + setDatasetVisibility(datasetIndex: any, visible: any): void; + toggleDataVisibility(index: any): void; + getDataVisibility(index: any): boolean; + /** + * @private + */ + private _updateVisibility; + hide(datasetIndex: any, dataIndex: any): void; + show(datasetIndex: any, dataIndex: any): void; + /** + * @private + */ + private _destroyDatasetMeta; + _stop(): void; + destroy(): void; + toBase64Image(...args: any[]): any; + /** + * @private + */ + private bindEvents; + /** + * @private + */ + private bindUserEvents; + /** + * @private + */ + private bindResponsiveEvents; + /** + * @private + */ + private unbindEvents; + updateHoverStyle(items: any, mode: any, enabled: any): void; + /** + * Get active (hovered) elements + * @returns array + */ + getActiveElements(): any[]; + /** + * Set active (hovered) elements + * @param {array} activeElements New active data points + */ + setActiveElements(activeElements: any[]): void; + /** + * Calls enabled plugins on the specified hook and with the given args. + * This method immediately returns as soon as a plugin explicitly returns false. The + * returned value can be used, for instance, to interrupt the current action. + * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate'). + * @param {Object} [args] - Extra arguments to apply to the hook call. + * @param {import('./core.plugins.js').filterCallback} [filter] - Filtering function for limiting which plugins are notified + * @returns {boolean} false if any of the plugins return false, else returns true. + */ + notifyPlugins(hook: string, args?: any, filter?: import('./core.plugins.js').filterCallback): boolean; + /** + * Check if a plugin with the specific ID is registered and enabled + * @param {string} pluginId - The ID of the plugin of which to check if it is enabled + * @returns {boolean} + */ + isPluginEnabled(pluginId: string): boolean; + /** + * @private + */ + private _updateHoverStyles; + /** + * @private + */ + private _eventHandler; + /** + * Handle an event + * @param {ChartEvent} e the event to handle + * @param {boolean} [replay] - true if the event was replayed by `update` + * @param {boolean} [inChartArea] - true if the event is inside chartArea + * @return {boolean} true if the chart needs to re-render + * @private + */ + private _handleEvent; + /** + * @param {ChartEvent} e - The event + * @param {import('../types/index.js').ActiveElement[]} lastActive - Previously active elements + * @param {boolean} inChartArea - Is the event inside chartArea + * @param {boolean} useFinalPosition - Should the evaluation be done with current or final (after animation) element positions + * @returns {import('../types/index.js').ActiveElement[]} - The active elements + * @pravate + */ + _getActiveElements(e: ChartEvent, lastActive: import('../types/index.js').ActiveElement[], inChartArea: boolean, useFinalPosition: boolean): import('../types/index.js').ActiveElement[]; +} +import Config from "./core.config.js"; +import PluginService from "./core.plugins.js"; diff --git a/frontend/node_modules/chart.js/dist/core/core.datasetController.d.ts b/frontend/node_modules/chart.js/dist/core/core.datasetController.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..98395e05bd4be3dead3e629d8fde08683676b474 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.datasetController.d.ts @@ -0,0 +1,251 @@ +export default class DatasetController { + /** + * @type {any} + */ + static defaults: any; + /** + * Element type used to generate a meta dataset (e.g. Chart.element.LineElement). + */ + static datasetElementType: any; + /** + * Element type used to generate a meta data (e.g. Chart.element.PointElement). + */ + static dataElementType: any; + /** + * @param {Chart} chart + * @param {number} datasetIndex + */ + constructor(chart: Chart, datasetIndex: number); + chart: import("./core.controller.js").default; + _ctx: any; + index: number; + _cachedDataOpts: {}; + _cachedMeta: any; + _type: any; + options: any; + /** @type {boolean | object} */ + _parsing: boolean | object; + _data: any; + _objectData: any; + _sharedOptions: any; + _drawStart: any; + _drawCount: any; + enableOptionSharing: boolean; + supportsDecimation: boolean; + $context: any; + _syncList: any[]; + datasetElementType: any; + dataElementType: any; + initialize(): void; + updateIndex(datasetIndex: any): void; + linkScales(): void; + getDataset(): any; + getMeta(): any; + /** + * @param {string} scaleID + * @return {Scale} + */ + getScaleForId(scaleID: string): Scale; + /** + * @private + */ + private _getOtherScale; + reset(): void; + /** + * @private + */ + private _destroy; + /** + * @private + */ + private _dataCheck; + addElements(): void; + buildOrUpdateElements(resetNewElements: any): void; + /** + * Merges user-supplied and default dataset-level options + * @private + */ + private configure; + /** + * @param {number} start + * @param {number} count + */ + parse(start: number, count: number): void; + /** + * Parse array of primitive values + * @param {object} meta - dataset meta + * @param {array} data - data array. Example [1,3,4] + * @param {number} start - start index + * @param {number} count - number of items to parse + * @returns {object} parsed item - item containing index and a parsed value + * for each scale id. + * Example: {xScale0: 0, yScale0: 1} + * @protected + */ + protected parsePrimitiveData(meta: object, data: any[], start: number, count: number): object; + /** + * Parse array of arrays + * @param {object} meta - dataset meta + * @param {array} data - data array. Example [[1,2],[3,4]] + * @param {number} start - start index + * @param {number} count - number of items to parse + * @returns {object} parsed item - item containing index and a parsed value + * for each scale id. + * Example: {x: 0, y: 1} + * @protected + */ + protected parseArrayData(meta: object, data: any[], start: number, count: number): object; + /** + * Parse array of objects + * @param {object} meta - dataset meta + * @param {array} data - data array. Example [{x:1, y:5}, {x:2, y:10}] + * @param {number} start - start index + * @param {number} count - number of items to parse + * @returns {object} parsed item - item containing index and a parsed value + * for each scale id. _custom is optional + * Example: {xScale0: 0, yScale0: 1, _custom: {r: 10, foo: 'bar'}} + * @protected + */ + protected parseObjectData(meta: object, data: any[], start: number, count: number): object; + /** + * @protected + */ + protected getParsed(index: any): any; + /** + * @protected + */ + protected getDataElement(index: any): any; + /** + * @protected + */ + protected applyStack(scale: any, parsed: any, mode: any): any; + /** + * @protected + */ + protected updateRangeFromParsed(range: any, scale: any, parsed: any, stack: any): void; + /** + * @protected + */ + protected getMinMax(scale: any, canStack: any): { + min: number; + max: number; + }; + getAllParsedValues(scale: any): number[]; + /** + * @return {number|boolean} + * @protected + */ + protected getMaxOverflow(): number | boolean; + /** + * @protected + */ + protected getLabelAndValue(index: any): { + label: string; + value: string; + }; + /** + * @private + */ + private _update; + /** + * @param {string} mode + */ + update(mode: string): void; + draw(): void; + /** + * Returns a set of predefined style properties that should be used to represent the dataset + * or the data if the index is specified + * @param {number} index - data index + * @param {boolean} [active] - true if hover + * @return {object} style object + */ + getStyle(index: number, active?: boolean): object; + /** + * @protected + */ + protected getContext(index: any, active: any, mode: any): any; + /** + * @param {string} [mode] + * @protected + */ + protected resolveDatasetElementOptions(mode?: string): any; + /** + * @param {number} index + * @param {string} [mode] + * @protected + */ + protected resolveDataElementOptions(index: number, mode?: string): any; + /** + * @private + */ + private _resolveElementOptions; + /** + * @private + */ + private _resolveAnimations; + /** + * Utility for getting the options object shared between elements + * @protected + */ + protected getSharedOptions(options: any): any; + /** + * Utility for determining if `options` should be included in the updated properties + * @protected + */ + protected includeOptions(mode: any, sharedOptions: any): boolean; + /** + * @todo v4, rename to getSharedOptions and remove excess functions + */ + _getSharedOptions(start: any, mode: any): { + sharedOptions: any; + includeOptions: boolean; + }; + /** + * Utility for updating an element with new properties, using animations when appropriate. + * @protected + */ + protected updateElement(element: any, index: any, properties: any, mode: any): void; + /** + * Utility to animate the shared options, that are potentially affecting multiple elements. + * @protected + */ + protected updateSharedOptions(sharedOptions: any, mode: any, newOptions: any): void; + /** + * @private + */ + private _setStyle; + removeHoverStyle(element: any, datasetIndex: any, index: any): void; + setHoverStyle(element: any, datasetIndex: any, index: any): void; + /** + * @private + */ + private _removeDatasetHoverStyle; + /** + * @private + */ + private _setDatasetHoverStyle; + /** + * @private + */ + private _resyncElements; + /** + * @private + */ + private _insertElements; + updateElements(element: any, start: any, count: any, mode: any): void; + /** + * @private + */ + private _removeElements; + /** + * @private + */ + private _sync; + _onDataPush(...args: any[]): void; + _onDataPop(): void; + _onDataShift(): void; + _onDataSplice(start: any, count: any, ...args: any[]): void; + _onDataUnshift(...args: any[]): void; +} +export type Chart = import('./core.controller.js').default; +export type Scale = import('./core.scale.js').default; diff --git a/frontend/node_modules/chart.js/dist/core/core.defaults.d.ts b/frontend/node_modules/chart.js/dist/core/core.defaults.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e6b7cb36f9366899b18a6f59b8bbbcebb43cb931 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.defaults.d.ts @@ -0,0 +1,80 @@ +export const overrides: any; +export const descriptors: any; +/** + * Please use the module's default export which provides a singleton instance + * Note: class is exported for typedoc + */ +export class Defaults { + constructor(_descriptors: any, _appliers: any); + animation: any; + backgroundColor: string; + borderColor: string; + color: string; + datasets: {}; + devicePixelRatio: (context: any) => any; + elements: {}; + events: string[]; + font: { + family: string; + size: number; + style: string; + lineHeight: number; + weight: any; + }; + hover: {}; + hoverBackgroundColor: (ctx: any, options: any) => CanvasGradient; + hoverBorderColor: (ctx: any, options: any) => CanvasGradient; + hoverColor: (ctx: any, options: any) => CanvasGradient; + indexAxis: string; + interaction: { + mode: string; + intersect: boolean; + includeInvisible: boolean; + }; + maintainAspectRatio: boolean; + onHover: any; + onClick: any; + parsing: boolean; + plugins: {}; + responsive: boolean; + scale: any; + scales: {}; + showLine: boolean; + drawActiveElementsOnTop: boolean; + /** + * @param {string|object} scope + * @param {object} [values] + */ + set(scope: string | object, values?: object): any; + /** + * @param {string} scope + */ + get(scope: string): any; + /** + * @param {string|object} scope + * @param {object} [values] + */ + describe(scope: string | object, values?: object): any; + override(scope: any, values: any): any; + /** + * Routes the named defaults to fallback to another scope/name. + * This routing is useful when those target values, like defaults.color, are changed runtime. + * If the values would be copied, the runtime change would not take effect. By routing, the + * fallback is evaluated at each access, so its always up to date. + * + * Example: + * + * defaults.route('elements.arc', 'backgroundColor', '', 'color') + * - reads the backgroundColor from defaults.color when undefined locally + * + * @param {string} scope Scope this route applies to. + * @param {string} name Property name that should be routed to different namespace when not defined here. + * @param {string} targetScope The namespace where those properties should be routed to. + * Empty string ('') is the root of defaults. + * @param {string} targetName The target name in the target scope the property should be routed to. + */ + route(scope: string, name: string, targetScope: string, targetName: string): void; + apply(appliers: any): void; +} +declare const _default: Defaults; +export default _default; diff --git a/frontend/node_modules/chart.js/dist/core/core.element.d.ts b/frontend/node_modules/chart.js/dist/core/core.element.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..25ef0b28975ed05e4cb31268020f4b99fb4faf36 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.element.d.ts @@ -0,0 +1,21 @@ +import type { AnyObject } from '../types/basic.js'; +import type { Point } from '../types/geometric.js'; +import type { Animation } from '../types/animation.js'; +export default class Element { + static defaults: {}; + static defaultRoutes: any; + x: number; + y: number; + active: boolean; + options: O; + $animations: Record; + tooltipPosition(useFinalPosition: boolean): Point; + hasValue(): boolean; + /** + * Gets the current or final value of each prop. Can return extra properties (whole object). + * @param props - properties to get + * @param [final] - get the final value (animation target) + */ + getProps

(props: P, final?: boolean): Pick; + getProps

(props: P[], final?: boolean): Partial>; +} diff --git a/frontend/node_modules/chart.js/dist/core/core.interaction.d.ts b/frontend/node_modules/chart.js/dist/core/core.interaction.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1468fbf8820c4e81a4208dc722d879d325654d28 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.interaction.d.ts @@ -0,0 +1,92 @@ +declare namespace _default { + export { evaluateInteractionItems }; + export namespace modes { + /** + * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something + * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item + * @function Chart.Interaction.modes.index + * @since v2.4.0 + * @param {Chart} chart - the chart we are returning items from + * @param {Event} e - the event we are find things at + * @param {InteractionOptions} options - options to use + * @param {boolean} [useFinalPosition] - use final element position (animation target) + * @return {InteractionItem[]} - items that are found + */ + function index(chart: import("./core.controller.js").default, e: Event, options: InteractionOptions, useFinalPosition?: boolean): InteractionItem[]; + /** + * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something + * If the options.intersect is false, we find the nearest item and return the items in that dataset + * @function Chart.Interaction.modes.dataset + * @param {Chart} chart - the chart we are returning items from + * @param {Event} e - the event we are find things at + * @param {InteractionOptions} options - options to use + * @param {boolean} [useFinalPosition] - use final element position (animation target) + * @return {InteractionItem[]} - items that are found + */ + function dataset(chart: import("./core.controller.js").default, e: Event, options: InteractionOptions, useFinalPosition?: boolean): InteractionItem[]; + /** + * Point mode returns all elements that hit test based on the event position + * of the event + * @function Chart.Interaction.modes.intersect + * @param {Chart} chart - the chart we are returning items from + * @param {Event} e - the event we are find things at + * @param {InteractionOptions} options - options to use + * @param {boolean} [useFinalPosition] - use final element position (animation target) + * @return {InteractionItem[]} - items that are found + */ + function point(chart: import("./core.controller.js").default, e: Event, options: InteractionOptions, useFinalPosition?: boolean): InteractionItem[]; + /** + * nearest mode returns the element closest to the point + * @function Chart.Interaction.modes.intersect + * @param {Chart} chart - the chart we are returning items from + * @param {Event} e - the event we are find things at + * @param {InteractionOptions} options - options to use + * @param {boolean} [useFinalPosition] - use final element position (animation target) + * @return {InteractionItem[]} - items that are found + */ + function nearest(chart: import("./core.controller.js").default, e: Event, options: InteractionOptions, useFinalPosition?: boolean): InteractionItem[]; + /** + * x mode returns the elements that hit-test at the current x coordinate + * @function Chart.Interaction.modes.x + * @param {Chart} chart - the chart we are returning items from + * @param {Event} e - the event we are find things at + * @param {InteractionOptions} options - options to use + * @param {boolean} [useFinalPosition] - use final element position (animation target) + * @return {InteractionItem[]} - items that are found + */ + function x(chart: import("./core.controller.js").default, e: Event, options: InteractionOptions, useFinalPosition?: boolean): InteractionItem[]; + /** + * y mode returns the elements that hit-test at the current y coordinate + * @function Chart.Interaction.modes.y + * @param {Chart} chart - the chart we are returning items from + * @param {Event} e - the event we are find things at + * @param {InteractionOptions} options - options to use + * @param {boolean} [useFinalPosition] - use final element position (animation target) + * @return {InteractionItem[]} - items that are found + */ + function y(chart: import("./core.controller.js").default, e: Event, options: InteractionOptions, useFinalPosition?: boolean): InteractionItem[]; + } +} +export default _default; +export type Chart = import('./core.controller.js').default; +export type ChartEvent = import('../types/index.js').ChartEvent; +export type InteractionOptions = { + axis?: string; + intersect?: boolean; + includeInvisible?: boolean; +}; +export type InteractionItem = { + datasetIndex: number; + index: number; + element: import('./core.element.js').default; +}; +export type Point = import('../types/index.js').Point; +/** + * Helper function to select candidate elements for interaction + * @param {Chart} chart - the chart + * @param {string} axis - the axis mode. x|y|xy|r + * @param {Point} position - the point to be nearest to, in relative coordinates + * @param {function} handler - the callback to execute for each visible item + * @param {boolean} [intersect] - consider intersecting items + */ +declare function evaluateInteractionItems(chart: Chart, axis: string, position: Point, handler: Function, intersect?: boolean): void; diff --git a/frontend/node_modules/chart.js/dist/core/core.layouts.d.ts b/frontend/node_modules/chart.js/dist/core/core.layouts.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f6f6d7d619f30bcdfc83f59fea45fce34bb425ee --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.layouts.d.ts @@ -0,0 +1,88 @@ +declare namespace _default { + /** + * Register a box to a chart. + * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title. + * @param {Chart} chart - the chart to use + * @param {LayoutItem} item - the item to add to be laid out + */ + function addBox(chart: import("./core.controller.js").default, item: LayoutItem): void; + /** + * Remove a layoutItem from a chart + * @param {Chart} chart - the chart to remove the box from + * @param {LayoutItem} layoutItem - the item to remove from the layout + */ + function removeBox(chart: import("./core.controller.js").default, layoutItem: LayoutItem): void; + /** + * Sets (or updates) options on the given `item`. + * @param {Chart} chart - the chart in which the item lives (or will be added to) + * @param {LayoutItem} item - the item to configure with the given options + * @param {object} options - the new item options. + */ + function configure(chart: import("./core.controller.js").default, item: LayoutItem, options: any): void; + /** + * Fits boxes of the given chart into the given size by having each box measure itself + * then running a fitting algorithm + * @param {Chart} chart - the chart + * @param {number} width - the width to fit into + * @param {number} height - the height to fit into + * @param {number} minPadding - minimum padding required for each side of chart area + */ + function update(chart: import("./core.controller.js").default, width: number, height: number, minPadding: number): void; +} +export default _default; +export type Chart = import('./core.controller.js').default; +export type LayoutItem = { + /** + * - The position of the item in the chart layout. Possible values are + * 'left', 'top', 'right', 'bottom', and 'chartArea' + */ + position: string; + /** + * - The weight used to sort the item. Higher weights are further away from the chart area + */ + weight: number; + /** + * - if true, and the item is horizontal, then push vertical boxes down + */ + fullSize: boolean; + /** + * - returns true if the layout item is horizontal (ie. top or bottom) + */ + isHorizontal: Function; + /** + * - Takes two parameters: width and height. Returns size of item + */ + update: Function; + /** + * - Draws the element + */ + draw: Function; + /** + * - Returns an object with padding on the edges + */ + getPadding?: Function; + /** + * - Width of item. Must be valid after update() + */ + width: number; + /** + * - Height of item. Must be valid after update() + */ + height: number; + /** + * - Left edge of the item. Set by layout system and cannot be used in update + */ + left: number; + /** + * - Top edge of the item. Set by layout system and cannot be used in update + */ + top: number; + /** + * - Right edge of the item. Set by layout system and cannot be used in update + */ + right: number; + /** + * - Bottom edge of the item. Set by layout system and cannot be used in update + */ + bottom: number; +}; diff --git a/frontend/node_modules/chart.js/dist/core/core.layouts.defaults.d.ts b/frontend/node_modules/chart.js/dist/core/core.layouts.defaults.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4462f381f8483ef03f540e20398b82d235240f8d --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.layouts.defaults.d.ts @@ -0,0 +1 @@ +export function applyLayoutsDefaults(defaults: any): void; diff --git a/frontend/node_modules/chart.js/dist/core/core.plugins.d.ts b/frontend/node_modules/chart.js/dist/core/core.plugins.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..379153f8a5139fa997c1f583d6d8b80647f21e0b --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.plugins.d.ts @@ -0,0 +1,61 @@ +/** + * @typedef { import('./core.controller.js').default } Chart + * @typedef { import('../types/index.js').ChartEvent } ChartEvent + * @typedef { import('../plugins/plugin.tooltip.js').default } Tooltip + */ +/** + * @callback filterCallback + * @param {{plugin: object, options: object}} value + * @param {number} [index] + * @param {array} [array] + * @param {object} [thisArg] + * @return {boolean} + */ +export default class PluginService { + _init: any[]; + /** + * Calls enabled plugins for `chart` on the specified hook and with the given args. + * This method immediately returns as soon as a plugin explicitly returns false. The + * returned value can be used, for instance, to interrupt the current action. + * @param {Chart} chart - The chart instance for which plugins should be called. + * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate'). + * @param {object} [args] - Extra arguments to apply to the hook call. + * @param {filterCallback} [filter] - Filtering function for limiting which plugins are notified + * @returns {boolean} false if any of the plugins return false, else returns true. + */ + notify(chart: Chart, hook: string, args?: object, filter?: filterCallback): boolean; + /** + * @private + */ + private _notify; + invalidate(): void; + _oldCache: { + plugin: any; + options: any; + }[]; + _cache: { + plugin: any; + options: any; + }[]; + /** + * @param {Chart} chart + * @private + */ + private _descriptors; + _createDescriptors(chart: any, all: any): { + plugin: any; + options: any; + }[]; + /** + * @param {Chart} chart + * @private + */ + private _notifyStateChanges; +} +export type Chart = import('./core.controller.js').default; +export type ChartEvent = import('../types/index.js').ChartEvent; +export type Tooltip = any; +export type filterCallback = (value: { + plugin: object; + options: object; +}, index?: number, array?: any[], thisArg?: object) => boolean; diff --git a/frontend/node_modules/chart.js/dist/core/core.registry.d.ts b/frontend/node_modules/chart.js/dist/core/core.registry.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8452add095b1f61e816dece44f43aa295e92220b --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.registry.d.ts @@ -0,0 +1,90 @@ +/** + * Please use the module's default export which provides a singleton instance + * Note: class is exported for typedoc + */ +export class Registry { + controllers: TypedRegistry; + elements: TypedRegistry; + plugins: TypedRegistry; + scales: TypedRegistry; + _typedRegistries: TypedRegistry[]; + /** + * @param {...any} args + */ + add(...args: any[]): void; + remove(...args: any[]): void; + /** + * @param {...typeof DatasetController} args + */ + addControllers(...args: (typeof DatasetController)[]): void; + /** + * @param {...typeof Element} args + */ + addElements(...args: (typeof Element)[]): void; + /** + * @param {...any} args + */ + addPlugins(...args: any[]): void; + /** + * @param {...typeof Scale} args + */ + addScales(...args: (typeof Scale)[]): void; + /** + * @param {string} id + * @returns {typeof DatasetController} + */ + getController(id: string): typeof DatasetController; + /** + * @param {string} id + * @returns {typeof Element} + */ + getElement(id: string): typeof Element; + /** + * @param {string} id + * @returns {object} + */ + getPlugin(id: string): object; + /** + * @param {string} id + * @returns {typeof Scale} + */ + getScale(id: string): typeof Scale; + /** + * @param {...typeof DatasetController} args + */ + removeControllers(...args: (typeof DatasetController)[]): void; + /** + * @param {...typeof Element} args + */ + removeElements(...args: (typeof Element)[]): void; + /** + * @param {...any} args + */ + removePlugins(...args: any[]): void; + /** + * @param {...typeof Scale} args + */ + removeScales(...args: (typeof Scale)[]): void; + /** + * @private + */ + private _each; + /** + * @private + */ + private _exec; + /** + * @private + */ + private _getRegistryForType; + /** + * @private + */ + private _get; +} +declare const _default: Registry; +export default _default; +import TypedRegistry from "./core.typedRegistry.js"; +import DatasetController from "./core.datasetController.js"; +import Element from "./core.element.js"; +import Scale from "./core.scale.js"; diff --git a/frontend/node_modules/chart.js/dist/core/core.scale.autoskip.d.ts b/frontend/node_modules/chart.js/dist/core/core.scale.autoskip.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..972eaae869149ce9e7f98f5aa6aaaf74d6896dff --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.scale.autoskip.d.ts @@ -0,0 +1,19 @@ +/** + * @typedef { import('./core.controller.js').default } Chart + * @typedef {{value:number | string, label?:string, major?:boolean, $context?:any}} Tick + */ +/** + * Returns a subset of ticks to be plotted to avoid overlapping labels. + * @param {import('./core.scale.js').default} scale + * @param {Tick[]} ticks + * @return {Tick[]} + * @private + */ +export function autoSkip(scale: import('./core.scale.js').default, ticks: Tick[]): Tick[]; +export type Chart = import('./core.controller.js').default; +export type Tick = { + value: number | string; + label?: string; + major?: boolean; + $context?: any; +}; diff --git a/frontend/node_modules/chart.js/dist/core/core.scale.d.ts b/frontend/node_modules/chart.js/dist/core/core.scale.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ca85bba0776fe093a6966e453c1fd8286e544e33 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.scale.d.ts @@ -0,0 +1,343 @@ +export default class Scale extends Element { + constructor(cfg: any); + /** @type {string} */ + id: string; + /** @type {string} */ + type: string; + /** @type {any} */ + options: any; + /** @type {CanvasRenderingContext2D} */ + ctx: CanvasRenderingContext2D; + /** @type {Chart} */ + chart: Chart; + /** @type {number} */ + top: number; + /** @type {number} */ + bottom: number; + /** @type {number} */ + left: number; + /** @type {number} */ + right: number; + /** @type {number} */ + width: number; + /** @type {number} */ + height: number; + _margins: { + left: number; + right: number; + top: number; + bottom: number; + }; + /** @type {number} */ + maxWidth: number; + /** @type {number} */ + maxHeight: number; + /** @type {number} */ + paddingTop: number; + /** @type {number} */ + paddingBottom: number; + /** @type {number} */ + paddingLeft: number; + /** @type {number} */ + paddingRight: number; + /** @type {string=} */ + axis: string | undefined; + /** @type {number=} */ + labelRotation: number | undefined; + min: any; + max: any; + _range: { + min: number; + max: number; + }; + /** @type {Tick[]} */ + ticks: Tick[]; + /** @type {object[]|null} */ + _gridLineItems: object[] | null; + /** @type {object[]|null} */ + _labelItems: object[] | null; + /** @type {object|null} */ + _labelSizes: object | null; + _length: number; + _maxLength: number; + _longestTextCache: {}; + /** @type {number} */ + _startPixel: number; + /** @type {number} */ + _endPixel: number; + _reversePixels: boolean; + _userMax: any; + _userMin: any; + _suggestedMax: any; + _suggestedMin: any; + _ticksLength: number; + _borderValue: number; + _cache: {}; + _dataLimitsCached: boolean; + $context: any; + /** + * @param {any} options + * @since 3.0 + */ + init(options: any): void; + /** + * Parse a supported input value to internal representation. + * @param {*} raw + * @param {number} [index] + * @since 3.0 + */ + parse(raw: any, index?: number): any; + /** + * @return {{min: number, max: number, minDefined: boolean, maxDefined: boolean}} + * @protected + * @since 3.0 + */ + protected getUserBounds(): { + min: number; + max: number; + minDefined: boolean; + maxDefined: boolean; + }; + /** + * @param {boolean} canStack + * @return {{min: number, max: number}} + * @protected + * @since 3.0 + */ + protected getMinMax(canStack: boolean): { + min: number; + max: number; + }; + /** + * Get the padding needed for the scale + * @return {{top: number, left: number, bottom: number, right: number}} the necessary padding + * @private + */ + private getPadding; + /** + * Returns the scale tick objects + * @return {Tick[]} + * @since 2.7 + */ + getTicks(): Tick[]; + /** + * @return {string[]} + */ + getLabels(): string[]; + /** + * @return {import('../types.js').LabelItem[]} + */ + getLabelItems(chartArea?: import("../types.js").ChartArea): import('../types.js').LabelItem[]; + beforeLayout(): void; + beforeUpdate(): void; + /** + * @param {number} maxWidth - the max width in pixels + * @param {number} maxHeight - the max height in pixels + * @param {{top: number, left: number, bottom: number, right: number}} margins - the space between the edge of the other scales and edge of the chart + * This space comes from two sources: + * - padding - space that's required to show the labels at the edges of the scale + * - thickness of scales or legends in another orientation + */ + update(maxWidth: number, maxHeight: number, margins: { + top: number; + left: number; + bottom: number; + right: number; + }): void; + /** + * @protected + */ + protected configure(): void; + _alignToPixels: any; + afterUpdate(): void; + beforeSetDimensions(): void; + setDimensions(): void; + afterSetDimensions(): void; + _callHooks(name: any): void; + beforeDataLimits(): void; + determineDataLimits(): void; + afterDataLimits(): void; + beforeBuildTicks(): void; + /** + * @return {object[]} the ticks + */ + buildTicks(): object[]; + afterBuildTicks(): void; + beforeTickToLabelConversion(): void; + /** + * Convert ticks to label strings + * @param {Tick[]} ticks + */ + generateTickLabels(ticks: Tick[]): void; + afterTickToLabelConversion(): void; + beforeCalculateLabelRotation(): void; + calculateLabelRotation(): void; + afterCalculateLabelRotation(): void; + afterAutoSkip(): void; + beforeFit(): void; + fit(): void; + _calculatePadding(first: any, last: any, sin: any, cos: any): void; + /** + * Handle margins and padding interactions + * @private + */ + private _handleMargins; + afterFit(): void; + /** + * @return {boolean} + */ + isHorizontal(): boolean; + /** + * @return {boolean} + */ + isFullSize(): boolean; + /** + * @param {Tick[]} ticks + * @private + */ + private _convertTicksToLabels; + /** + * @return {{ first: object, last: object, widest: object, highest: object, widths: Array, heights: array }} + * @private + */ + private _getLabelSizes; + /** + * Returns {width, height, offset} objects for the first, last, widest, highest tick + * labels where offset indicates the anchor point offset from the top in pixels. + * @return {{ first: object, last: object, widest: object, highest: object, widths: Array, heights: array }} + * @private + */ + private _computeLabelSizes; + /** + * Used to get the label to display in the tooltip for the given value + * @param {*} value + * @return {string} + */ + getLabelForValue(value: any): string; + /** + * Returns the location of the given data point. Value can either be an index or a numerical value + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @param {*} value + * @param {number} [index] + * @return {number} + */ + getPixelForValue(value: any, index?: number): number; + /** + * Used to get the data value from a given pixel. This is the inverse of getPixelForValue + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @param {number} pixel + * @return {*} + */ + getValueForPixel(pixel: number): any; + /** + * Returns the location of the tick at the given index + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @param {number} index + * @return {number} + */ + getPixelForTick(index: number): number; + /** + * Utility for getting the pixel location of a percentage of scale + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @param {number} decimal + * @return {number} + */ + getPixelForDecimal(decimal: number): number; + /** + * @param {number} pixel + * @return {number} + */ + getDecimalForPixel(pixel: number): number; + /** + * Returns the pixel for the minimum chart value + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @return {number} + */ + getBasePixel(): number; + /** + * @return {number} + */ + getBaseValue(): number; + /** + * @protected + */ + protected getContext(index: any): any; + /** + * @return {number} + * @private + */ + private _tickSize; + /** + * @return {boolean} + * @private + */ + private _isVisible; + /** + * @private + */ + private _computeGridLineItems; + /** + * @private + */ + private _computeLabelItems; + _getXAxisLabelAlignment(): string; + _getYAxisLabelAlignment(tl: any): { + textAlign: string; + x: any; + }; + /** + * @private + */ + private _computeLabelArea; + /** + * @protected + */ + protected drawBackground(): void; + getLineWidthForValue(value: any): any; + /** + * @protected + */ + protected drawGrid(chartArea: any): void; + /** + * @protected + */ + protected drawBorder(): void; + /** + * @protected + */ + protected drawLabels(chartArea: any): void; + /** + * @protected + */ + protected drawTitle(): void; + draw(chartArea: any): void; + /** + * @return {object[]} + * @private + */ + private _layers; + /** + * Returns visible dataset metas that are attached to this scale + * @param {string} [type] - if specified, also filter by dataset type + * @return {object[]} + */ + getMatchingVisibleMetas(type?: string): object[]; + /** + * @param {number} index + * @return {object} + * @protected + */ + protected _resolveTickFontOptions(index: number): object; + /** + * @protected + */ + protected _maxDigits(): number; +} +export type Chart = import('../types/index.js').Chart; +export type Tick = { + value: number | string; + label?: string; + major?: boolean; + $context?: any; +}; +import Element from "./core.element.js"; diff --git a/frontend/node_modules/chart.js/dist/core/core.scale.defaults.d.ts b/frontend/node_modules/chart.js/dist/core/core.scale.defaults.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f747e8b7657eeca681ac8b77f46887456ba62909 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.scale.defaults.d.ts @@ -0,0 +1 @@ +export function applyScaleDefaults(defaults: any): void; diff --git a/frontend/node_modules/chart.js/dist/core/core.ticks.d.ts b/frontend/node_modules/chart.js/dist/core/core.ticks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fc99f1dca1cda4894e87e068233aa56968bcd915 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.ticks.d.ts @@ -0,0 +1,31 @@ +declare namespace _default { + export { formatters }; +} +export default _default; +declare namespace formatters { + /** + * Formatter for value labels + * @method Chart.Ticks.formatters.values + * @param value the value to display + * @return {string|string[]} the label to display + */ + function values(value: any): string | string[]; + /** + * Formatter for numeric ticks + * @method Chart.Ticks.formatters.numeric + * @param tickValue {number} the value to be formatted + * @param index {number} the position of the tickValue parameter in the ticks array + * @param ticks {object[]} the list of ticks being converted + * @return {string} string representation of the tickValue parameter + */ + function numeric(tickValue: number, index: number, ticks: any[]): string; + /** + * Formatter for logarithmic ticks + * @method Chart.Ticks.formatters.logarithmic + * @param tickValue {number} the value to be formatted + * @param index {number} the position of the tickValue parameter in the ticks array + * @param ticks {object[]} the list of ticks being converted + * @return {string} string representation of the tickValue parameter + */ + function logarithmic(tickValue: number, index: number, ticks: any[]): string; +} diff --git a/frontend/node_modules/chart.js/dist/core/core.typedRegistry.d.ts b/frontend/node_modules/chart.js/dist/core/core.typedRegistry.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ac1bf25ce164dee7d8cb864e44e937255f061f20 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/core.typedRegistry.d.ts @@ -0,0 +1,33 @@ +/** + * @typedef {{id: string, defaults: any, overrides?: any, defaultRoutes: any}} IChartComponent + */ +export default class TypedRegistry { + constructor(type: any, scope: any, override: any); + type: any; + scope: any; + override: any; + items: any; + isForType(type: any): boolean; + /** + * @param {IChartComponent} item + * @returns {string} The scope where items defaults were registered to. + */ + register(item: IChartComponent): string; + /** + * @param {string} id + * @returns {object?} + */ + get(id: string): object | null; + /** + * @param {IChartComponent} item + */ + unregister(item: IChartComponent): void; +} +export type IChartComponent = { + id: string; + defaults: any; + overrides?: any; + defaultRoutes: any; +}; +import defaults from "./core.defaults.js"; +import { overrides } from "./core.defaults.js"; diff --git a/frontend/node_modules/chart.js/dist/core/index.d.ts b/frontend/node_modules/chart.js/dist/core/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9b37713e3fb92cd94282de7a51334779a6e3f97 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/core/index.d.ts @@ -0,0 +1,15 @@ +export type { DateAdapter, TimeUnit } from './core.adapters.js'; +export { default as _adapters } from './core.adapters.js'; +export { default as Animation } from './core.animation.js'; +export { default as Animations } from './core.animations.js'; +export { default as animator } from './core.animator.js'; +export { default as Chart } from './core.controller.js'; +export { default as DatasetController } from './core.datasetController.js'; +export { default as defaults } from './core.defaults.js'; +export { default as Element } from './core.element.js'; +export { default as Interaction } from './core.interaction.js'; +export { default as layouts } from './core.layouts.js'; +export { default as plugins } from './core.plugins.js'; +export { default as registry } from './core.registry.js'; +export { default as Scale } from './core.scale.js'; +export { default as Ticks } from './core.ticks.js'; diff --git a/frontend/node_modules/chart.js/dist/elements/element.arc.d.ts b/frontend/node_modules/chart.js/dist/elements/element.arc.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f09fe0e3a01707dd1bda7d7694fc9ff1682d28fc --- /dev/null +++ b/frontend/node_modules/chart.js/dist/elements/element.arc.d.ts @@ -0,0 +1,51 @@ +import Element from '../core/core.element.js'; +import type { ArcOptions, Point } from '../types/index.js'; +export interface ArcProps extends Point { + startAngle: number; + endAngle: number; + innerRadius: number; + outerRadius: number; + circumference: number; +} +export default class ArcElement extends Element { + static id: string; + static defaults: { + borderAlign: string; + borderColor: string; + borderDash: any[]; + borderDashOffset: number; + borderJoinStyle: any; + borderRadius: number; + borderWidth: number; + offset: number; + spacing: number; + angle: any; + circular: boolean; + selfJoin: boolean; + }; + static defaultRoutes: { + backgroundColor: string; + }; + static descriptors: { + _scriptable: boolean; + _indexable: (name: any) => boolean; + }; + circumference: number; + endAngle: number; + fullCircles: number; + innerRadius: number; + outerRadius: number; + pixelMargin: number; + startAngle: number; + constructor(cfg: any); + inRange(chartX: number, chartY: number, useFinalPosition: boolean): boolean; + getCenterPoint(useFinalPosition: boolean): { + x: number; + y: number; + }; + tooltipPosition(useFinalPosition: boolean): { + x: number; + y: number; + }; + draw(ctx: CanvasRenderingContext2D): void; +} diff --git a/frontend/node_modules/chart.js/dist/elements/element.bar.d.ts b/frontend/node_modules/chart.js/dist/elements/element.bar.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f650e324df746aee34a05ffdbafbb980ef0186c4 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/elements/element.bar.d.ts @@ -0,0 +1,32 @@ +export default class BarElement extends Element { + static id: string; + /** + * @type {any} + */ + static defaults: any; + constructor(cfg: any); + options: any; + horizontal: any; + base: any; + width: any; + height: any; + inflateAmount: any; + draw(ctx: any): void; + inRange(mouseX: any, mouseY: any, useFinalPosition: any): boolean; + inXRange(mouseX: any, useFinalPosition: any): boolean; + inYRange(mouseY: any, useFinalPosition: any): boolean; + getCenterPoint(useFinalPosition: any): { + x: number; + y: number; + }; + getRange(axis: any): number; +} +export type BarProps = { + x: number; + y: number; + base: number; + horizontal: boolean; + width: number; + height: number; +}; +import Element from "../core/core.element.js"; diff --git a/frontend/node_modules/chart.js/dist/elements/element.line.d.ts b/frontend/node_modules/chart.js/dist/elements/element.line.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5fe47dfb498fdcfd06eb98f70d9e27559671b70 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/elements/element.line.d.ts @@ -0,0 +1,87 @@ +export default class LineElement extends Element { + static id: string; + /** + * @type {any} + */ + static defaults: any; + static descriptors: { + _scriptable: boolean; + _indexable: (name: any) => boolean; + }; + constructor(cfg: any); + animated: boolean; + options: any; + _chart: any; + _loop: any; + _fullLoop: any; + _path: any; + _points: any; + _segments: import("../helpers/helpers.segment.js").Segment[]; + _decimated: boolean; + _pointsUpdated: boolean; + _datasetIndex: any; + updateControlPoints(chartArea: any, indexAxis: any): void; + set points(arg: any); + get points(): any; + get segments(): import("../helpers/helpers.segment.js").Segment[]; + /** + * First non-skipped point on this line + * @returns {PointElement|undefined} + */ + first(): PointElement | undefined; + /** + * Last non-skipped point on this line + * @returns {PointElement|undefined} + */ + last(): PointElement | undefined; + /** + * Interpolate a point in this line at the same value on `property` as + * the reference `point` provided + * @param {PointElement} point - the reference point + * @param {string} property - the property to match on + * @returns {PointElement|undefined} + */ + interpolate(point: PointElement, property: string): PointElement | undefined; + /** + * Append a segment of this line to current path. + * @param {CanvasRenderingContext2D} ctx + * @param {object} segment + * @param {number} segment.start - start index of the segment, referring the points array + * @param {number} segment.end - end index of the segment, referring the points array + * @param {boolean} segment.loop - indicates that the segment is a loop + * @param {object} params + * @param {boolean} params.move - move to starting point (vs line to it) + * @param {boolean} params.reverse - path the segment from end to start + * @param {number} params.start - limit segment to points starting from `start` index + * @param {number} params.end - limit segment to points ending at `start` + `count` index + * @returns {undefined|boolean} - true if the segment is a full loop (path should be closed) + */ + pathSegment(ctx: CanvasRenderingContext2D, segment: { + start: number; + end: number; + loop: boolean; + }, params: { + move: boolean; + reverse: boolean; + start: number; + end: number; + }): undefined | boolean; + /** + * Append all segments of this line to current path. + * @param {CanvasRenderingContext2D|Path2D} ctx + * @param {number} [start] + * @param {number} [count] + * @returns {undefined|boolean} - true if line is a full loop (path should be closed) + */ + path(ctx: CanvasRenderingContext2D | Path2D, start?: number, count?: number): undefined | boolean; + /** + * Draw + * @param {CanvasRenderingContext2D} ctx + * @param {object} chartArea + * @param {number} [start] + * @param {number} [count] + */ + draw(ctx: CanvasRenderingContext2D, chartArea: object, start?: number, count?: number): void; +} +export type PointElement = import('./element.point.js').default; +import Element from "../core/core.element.js"; diff --git a/frontend/node_modules/chart.js/dist/elements/element.point.d.ts b/frontend/node_modules/chart.js/dist/elements/element.point.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..584b277142f76a1f084e71c6c8f6c2f14c6e91bb --- /dev/null +++ b/frontend/node_modules/chart.js/dist/elements/element.point.d.ts @@ -0,0 +1,39 @@ +import Element from '../core/core.element.js'; +import type { CartesianParsedData, ChartArea, Point, PointHoverOptions, PointOptions } from '../types/index.js'; +export type PointProps = Point; +export default class PointElement extends Element { + static id: string; + parsed: CartesianParsedData; + skip?: boolean; + stop?: boolean; + /** + * @type {any} + */ + static defaults: { + borderWidth: number; + hitRadius: number; + hoverBorderWidth: number; + hoverRadius: number; + pointStyle: string; + radius: number; + rotation: number; + }; + /** + * @type {any} + */ + static defaultRoutes: { + backgroundColor: string; + borderColor: string; + }; + constructor(cfg: any); + inRange(mouseX: number, mouseY: number, useFinalPosition?: boolean): boolean; + inXRange(mouseX: number, useFinalPosition?: boolean): boolean; + inYRange(mouseY: number, useFinalPosition?: boolean): boolean; + getCenterPoint(useFinalPosition?: boolean): { + x: number; + y: number; + }; + size(options?: Partial): number; + draw(ctx: CanvasRenderingContext2D, area: ChartArea): void; + getRange(): any; +} diff --git a/frontend/node_modules/chart.js/dist/elements/index.d.ts b/frontend/node_modules/chart.js/dist/elements/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3db94cc645f34a649727b73a501a6d2d06ef9ab9 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/elements/index.d.ts @@ -0,0 +1,4 @@ +export { default as ArcElement } from "./element.arc.js"; +export { default as LineElement } from "./element.line.js"; +export { default as PointElement } from "./element.point.js"; +export { default as BarElement } from "./element.bar.js"; diff --git a/frontend/node_modules/chart.js/dist/helpers.cjs b/frontend/node_modules/chart.js/dist/helpers.cjs new file mode 100644 index 0000000000000000000000000000000000000000..d502ea55ff3ff4b79a0bab3216e1008faa5cf925 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers.cjs @@ -0,0 +1,136 @@ +/*! + * Chart.js v4.5.0 + * https://www.chartjs.org + * (c) 2025 Chart.js Contributors + * Released under the MIT License + */ +'use strict'; + +var helpers_dataset = require('./chunks/helpers.dataset.cjs'); +require('@kurkle/color'); + + + +exports.HALF_PI = helpers_dataset.HALF_PI; +exports.INFINITY = helpers_dataset.INFINITY; +exports.PI = helpers_dataset.PI; +exports.PITAU = helpers_dataset.PITAU; +exports.QUARTER_PI = helpers_dataset.QUARTER_PI; +exports.RAD_PER_DEG = helpers_dataset.RAD_PER_DEG; +exports.TAU = helpers_dataset.TAU; +exports.TWO_THIRDS_PI = helpers_dataset.TWO_THIRDS_PI; +exports._addGrace = helpers_dataset._addGrace; +exports._alignPixel = helpers_dataset._alignPixel; +exports._alignStartEnd = helpers_dataset._alignStartEnd; +exports._angleBetween = helpers_dataset._angleBetween; +exports._angleDiff = helpers_dataset._angleDiff; +exports._arrayUnique = helpers_dataset._arrayUnique; +exports._attachContext = helpers_dataset._attachContext; +exports._bezierCurveTo = helpers_dataset._bezierCurveTo; +exports._bezierInterpolation = helpers_dataset._bezierInterpolation; +exports._boundSegment = helpers_dataset._boundSegment; +exports._boundSegments = helpers_dataset._boundSegments; +exports._capitalize = helpers_dataset._capitalize; +exports._computeSegments = helpers_dataset._computeSegments; +exports._createResolver = helpers_dataset._createResolver; +exports._decimalPlaces = helpers_dataset._decimalPlaces; +exports._deprecated = helpers_dataset._deprecated; +exports._descriptors = helpers_dataset._descriptors; +exports._elementsEqual = helpers_dataset._elementsEqual; +exports._factorize = helpers_dataset._factorize; +exports._filterBetween = helpers_dataset._filterBetween; +exports._getParentNode = helpers_dataset._getParentNode; +exports._getStartAndCountOfVisiblePoints = helpers_dataset._getStartAndCountOfVisiblePoints; +exports._int16Range = helpers_dataset._int16Range; +exports._isBetween = helpers_dataset._isBetween; +exports._isClickEvent = helpers_dataset._isClickEvent; +exports._isDomSupported = helpers_dataset._isDomSupported; +exports._isPointInArea = helpers_dataset._isPointInArea; +exports._limitValue = helpers_dataset._limitValue; +exports._longestText = helpers_dataset._longestText; +exports._lookup = helpers_dataset._lookup; +exports._lookupByKey = helpers_dataset._lookupByKey; +exports._measureText = helpers_dataset._measureText; +exports._merger = helpers_dataset._merger; +exports._mergerIf = helpers_dataset._mergerIf; +exports._normalizeAngle = helpers_dataset._normalizeAngle; +exports._parseObjectDataRadialScale = helpers_dataset._parseObjectDataRadialScale; +exports._pointInLine = helpers_dataset._pointInLine; +exports._readValueToProps = helpers_dataset._readValueToProps; +exports._rlookupByKey = helpers_dataset._rlookupByKey; +exports._scaleRangesChanged = helpers_dataset._scaleRangesChanged; +exports._setMinAndMaxByKey = helpers_dataset._setMinAndMaxByKey; +exports._splitKey = helpers_dataset._splitKey; +exports._steppedInterpolation = helpers_dataset._steppedInterpolation; +exports._steppedLineTo = helpers_dataset._steppedLineTo; +exports._textX = helpers_dataset._textX; +exports._toLeftRightCenter = helpers_dataset._toLeftRightCenter; +exports._updateBezierControlPoints = helpers_dataset._updateBezierControlPoints; +exports.addRoundedRectPath = helpers_dataset.addRoundedRectPath; +exports.almostEquals = helpers_dataset.almostEquals; +exports.almostWhole = helpers_dataset.almostWhole; +exports.callback = helpers_dataset.callback; +exports.clearCanvas = helpers_dataset.clearCanvas; +exports.clipArea = helpers_dataset.clipArea; +exports.clone = helpers_dataset.clone; +exports.color = helpers_dataset.color; +exports.createContext = helpers_dataset.createContext; +exports.debounce = helpers_dataset.debounce; +exports.defined = helpers_dataset.defined; +exports.distanceBetweenPoints = helpers_dataset.distanceBetweenPoints; +exports.drawPoint = helpers_dataset.drawPoint; +exports.drawPointLegend = helpers_dataset.drawPointLegend; +exports.each = helpers_dataset.each; +exports.easingEffects = helpers_dataset.effects; +exports.finiteOrDefault = helpers_dataset.finiteOrDefault; +exports.fontString = helpers_dataset.fontString; +exports.formatNumber = helpers_dataset.formatNumber; +exports.getAngleFromPoint = helpers_dataset.getAngleFromPoint; +exports.getDatasetClipArea = helpers_dataset.getDatasetClipArea; +exports.getHoverColor = helpers_dataset.getHoverColor; +exports.getMaximumSize = helpers_dataset.getMaximumSize; +exports.getRelativePosition = helpers_dataset.getRelativePosition; +exports.getRtlAdapter = helpers_dataset.getRtlAdapter; +exports.getStyle = helpers_dataset.getStyle; +exports.isArray = helpers_dataset.isArray; +exports.isFinite = helpers_dataset.isNumberFinite; +exports.isFunction = helpers_dataset.isFunction; +exports.isNullOrUndef = helpers_dataset.isNullOrUndef; +exports.isNumber = helpers_dataset.isNumber; +exports.isObject = helpers_dataset.isObject; +exports.isPatternOrGradient = helpers_dataset.isPatternOrGradient; +exports.listenArrayEvents = helpers_dataset.listenArrayEvents; +exports.log10 = helpers_dataset.log10; +exports.merge = helpers_dataset.merge; +exports.mergeIf = helpers_dataset.mergeIf; +exports.niceNum = helpers_dataset.niceNum; +exports.noop = helpers_dataset.noop; +exports.overrideTextDirection = helpers_dataset.overrideTextDirection; +exports.readUsedSize = helpers_dataset.readUsedSize; +exports.renderText = helpers_dataset.renderText; +exports.requestAnimFrame = helpers_dataset.requestAnimFrame; +exports.resolve = helpers_dataset.resolve; +exports.resolveObjectKey = helpers_dataset.resolveObjectKey; +exports.restoreTextDirection = helpers_dataset.restoreTextDirection; +exports.retinaScale = helpers_dataset.retinaScale; +exports.setsEqual = helpers_dataset.setsEqual; +exports.sign = helpers_dataset.sign; +exports.splineCurve = helpers_dataset.splineCurve; +exports.splineCurveMonotone = helpers_dataset.splineCurveMonotone; +exports.supportsEventListenerOptions = helpers_dataset.supportsEventListenerOptions; +exports.throttled = helpers_dataset.throttled; +exports.toDegrees = helpers_dataset.toDegrees; +exports.toDimension = helpers_dataset.toDimension; +exports.toFont = helpers_dataset.toFont; +exports.toFontString = helpers_dataset.toFontString; +exports.toLineHeight = helpers_dataset.toLineHeight; +exports.toPadding = helpers_dataset.toPadding; +exports.toPercentage = helpers_dataset.toPercentage; +exports.toRadians = helpers_dataset.toRadians; +exports.toTRBL = helpers_dataset.toTRBL; +exports.toTRBLCorners = helpers_dataset.toTRBLCorners; +exports.uid = helpers_dataset.uid; +exports.unclipArea = helpers_dataset.unclipArea; +exports.unlistenArrayEvents = helpers_dataset.unlistenArrayEvents; +exports.valueOrDefault = helpers_dataset.valueOrDefault; +//# sourceMappingURL=helpers.cjs.map diff --git a/frontend/node_modules/chart.js/dist/helpers.cjs.map b/frontend/node_modules/chart.js/dist/helpers.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..7b3f0179f89175b8662658c7c5834a16c55777cb --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/frontend/node_modules/chart.js/dist/helpers.js b/frontend/node_modules/chart.js/dist/helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..f354d55090383cdd48c8e80770f14b3da0516e2e --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers.js @@ -0,0 +1,9 @@ +/*! + * Chart.js v4.5.0 + * https://www.chartjs.org + * (c) 2025 Chart.js Contributors + * Released under the MIT License + */ +export { H as HALF_PI, b3 as INFINITY, P as PI, b2 as PITAU, b5 as QUARTER_PI, b4 as RAD_PER_DEG, T as TAU, b6 as TWO_THIRDS_PI, R as _addGrace, X as _alignPixel, a2 as _alignStartEnd, p as _angleBetween, b7 as _angleDiff, _ as _arrayUnique, a8 as _attachContext, au as _bezierCurveTo, ar as _bezierInterpolation, az as _boundSegment, ap as _boundSegments, a5 as _capitalize, ao as _computeSegments, a9 as _createResolver, aL as _decimalPlaces, aW as _deprecated, aa as _descriptors, ai as _elementsEqual, N as _factorize, aP as _filterBetween, I as _getParentNode, q as _getStartAndCountOfVisiblePoints, W as _int16Range, ak as _isBetween, aj as _isClickEvent, M as _isDomSupported, C as _isPointInArea, S as _limitValue, aO as _longestText, aQ as _lookup, B as _lookupByKey, V as _measureText, aU as _merger, aV as _mergerIf, al as _normalizeAngle, y as _parseObjectDataRadialScale, as as _pointInLine, am as _readValueToProps, A as _rlookupByKey, w as _scaleRangesChanged, aH as _setMinAndMaxByKey, aX as _splitKey, aq as _steppedInterpolation, at as _steppedLineTo, aC as _textX, a1 as _toLeftRightCenter, an as _updateBezierControlPoints, aw as addRoundedRectPath, aK as almostEquals, aJ as almostWhole, Q as callback, af as clearCanvas, Y as clipArea, aT as clone, c as color, j as createContext, ad as debounce, h as defined, aF as distanceBetweenPoints, av as drawPoint, aE as drawPointLegend, F as each, e as easingEffects, O as finiteOrDefault, b0 as fontString, o as formatNumber, D as getAngleFromPoint, ah as getDatasetClipArea, aS as getHoverColor, G as getMaximumSize, z as getRelativePosition, aA as getRtlAdapter, a$ as getStyle, b as isArray, g as isFinite, a7 as isFunction, k as isNullOrUndef, x as isNumber, i as isObject, aR as isPatternOrGradient, l as listenArrayEvents, aN as log10, a4 as merge, ab as mergeIf, aI as niceNum, aG as noop, aB as overrideTextDirection, J as readUsedSize, Z as renderText, r as requestAnimFrame, a as resolve, f as resolveObjectKey, aD as restoreTextDirection, ae as retinaScale, ag as setsEqual, s as sign, aZ as splineCurve, a_ as splineCurveMonotone, K as supportsEventListenerOptions, L as throttled, U as toDegrees, n as toDimension, a0 as toFont, aY as toFontString, b1 as toLineHeight, E as toPadding, m as toPercentage, t as toRadians, ax as toTRBL, ay as toTRBLCorners, ac as uid, $ as unclipArea, u as unlistenArrayEvents, v as valueOrDefault } from './chunks/helpers.dataset.js'; +import '@kurkle/color'; +//# sourceMappingURL=helpers.js.map diff --git a/frontend/node_modules/chart.js/dist/helpers.js.map b/frontend/node_modules/chart.js/dist/helpers.js.map new file mode 100644 index 0000000000000000000000000000000000000000..de14c42666f16ef394575d0b9ee9bf7e0ff7986a --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;"} \ No newline at end of file diff --git a/frontend/node_modules/chart.js/dist/helpers/helpers.canvas.d.ts b/frontend/node_modules/chart.js/dist/helpers/helpers.canvas.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ff83b2820b6f1276c925c3aa1b5bc83aeb46415d --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers/helpers.canvas.d.ts @@ -0,0 +1,75 @@ +import type { Chart, Point, FontSpec, CanvasFontSpec, PointStyle, RenderTextOpts } from '../types/index.js'; +import type { TRBL, SplinePoint, RoundedRect, TRBLCorners } from '../types/geometric.js'; +/** + * Converts the given font object into a CSS font string. + * @param font - A font object. + * @return The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font + * @private + */ +export declare function toFontString(font: FontSpec): string; +/** + * @private + */ +export declare function _measureText(ctx: CanvasRenderingContext2D, data: Record, gc: string[], longest: number, string: string): number; +type Thing = string | undefined | null; +type Things = (Thing | Thing[])[]; +/** + * @private + */ +export declare function _longestText(ctx: CanvasRenderingContext2D, font: string, arrayOfThings: Things, cache?: { + data?: Record; + garbageCollect?: string[]; + font?: string; +}): number; +/** + * Returns the aligned pixel value to avoid anti-aliasing blur + * @param chart - The chart instance. + * @param pixel - A pixel value. + * @param width - The width of the element. + * @returns The aligned pixel value. + * @private + */ +export declare function _alignPixel(chart: Chart, pixel: number, width: number): number; +/** + * Clears the entire canvas. + */ +export declare function clearCanvas(canvas?: HTMLCanvasElement, ctx?: CanvasRenderingContext2D): void; +export interface DrawPointOptions { + pointStyle: PointStyle; + rotation?: number; + radius: number; + borderWidth: number; +} +export declare function drawPoint(ctx: CanvasRenderingContext2D, options: DrawPointOptions, x: number, y: number): void; +export declare function drawPointLegend(ctx: CanvasRenderingContext2D, options: DrawPointOptions, x: number, y: number, w: number): void; +/** + * Returns true if the point is inside the rectangle + * @param point - The point to test + * @param area - The rectangle + * @param margin - allowed margin + * @private + */ +export declare function _isPointInArea(point: Point, area: TRBL, margin?: number): boolean; +export declare function clipArea(ctx: CanvasRenderingContext2D, area: TRBL): void; +export declare function unclipArea(ctx: CanvasRenderingContext2D): void; +/** + * @private + */ +export declare function _steppedLineTo(ctx: CanvasRenderingContext2D, previous: Point, target: Point, flip?: boolean, mode?: string): void; +/** + * @private + */ +export declare function _bezierCurveTo(ctx: CanvasRenderingContext2D, previous: SplinePoint, target: SplinePoint, flip?: boolean): void; +/** + * Render text onto the canvas + */ +export declare function renderText(ctx: CanvasRenderingContext2D, text: string | string[], x: number, y: number, font: CanvasFontSpec, opts?: RenderTextOpts): void; +/** + * Add a path of a rectangle with rounded corners to the current sub-path + * @param ctx - Context + * @param rect - Bounding rect + */ +export declare function addRoundedRectPath(ctx: CanvasRenderingContext2D, rect: RoundedRect & { + radius: TRBLCorners; +}): void; +export {}; diff --git a/frontend/node_modules/chart.js/dist/helpers/helpers.collection.d.ts b/frontend/node_modules/chart.js/dist/helpers/helpers.collection.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..94d15893d3e7973c9b32921bd6610359885e3de3 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers/helpers.collection.d.ts @@ -0,0 +1,68 @@ +/** + * Binary search + * @param table - the table search. must be sorted! + * @param value - value to find + * @param cmp + * @private + */ +export declare function _lookup(table: number[], value: number, cmp?: (value: number) => boolean): { + lo: number; + hi: number; +}; +export declare function _lookup(table: T[], value: number, cmp: (value: number) => boolean): { + lo: number; + hi: number; +}; +/** + * Binary search + * @param table - the table search. must be sorted! + * @param key - property name for the value in each entry + * @param value - value to find + * @param last - lookup last index + * @private + */ +export declare const _lookupByKey: (table: Record[], key: string, value: number, last?: boolean) => { + lo: number; + hi: number; +}; +/** + * Reverse binary search + * @param table - the table search. must be sorted! + * @param key - property name for the value in each entry + * @param value - value to find + * @private + */ +export declare const _rlookupByKey: (table: Record[], key: string, value: number) => { + lo: number; + hi: number; +}; +/** + * Return subset of `values` between `min` and `max` inclusive. + * Values are assumed to be in sorted order. + * @param values - sorted array of values + * @param min - min value + * @param max - max value + */ +export declare function _filterBetween(values: number[], min: number, max: number): number[]; +export interface ArrayListener { + _onDataPush?(...item: T[]): void; + _onDataPop?(): void; + _onDataShift?(): void; + _onDataSplice?(index: number, deleteCount: number, ...items: T[]): void; + _onDataUnshift?(...item: T[]): void; +} +/** + * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice', + * 'unshift') and notify the listener AFTER the array has been altered. Listeners are + * called on the '_onData*' callbacks (e.g. _onDataPush, etc.) with same arguments. + */ +export declare function listenArrayEvents(array: T[], listener: ArrayListener): void; +/** + * Removes the given array event listener and cleanup extra attached properties (such as + * the _chartjs stub and overridden methods) if array doesn't have any more listeners. + */ +export declare function unlistenArrayEvents(array: T[], listener: ArrayListener): void; +/** + * @param items + */ +export declare function _arrayUnique(items: T[]): T[]; diff --git a/frontend/node_modules/chart.js/dist/helpers/helpers.color.d.ts b/frontend/node_modules/chart.js/dist/helpers/helpers.color.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b4d7c70721ad7ca3d50a4707acaa4f0f2c84ef86 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers/helpers.color.d.ts @@ -0,0 +1,13 @@ +import { Color } from '@kurkle/color'; +export declare function isPatternOrGradient(value: unknown): value is CanvasPattern | CanvasGradient; +export declare function color(value: CanvasGradient): CanvasGradient; +export declare function color(value: CanvasPattern): CanvasPattern; +export declare function color(value: string | { + r: number; + g: number; + b: number; + a: number; +} | [number, number, number] | [number, number, number, number]): Color; +export declare function getHoverColor(value: CanvasGradient): CanvasGradient; +export declare function getHoverColor(value: CanvasPattern): CanvasPattern; +export declare function getHoverColor(value: string): string; diff --git a/frontend/node_modules/chart.js/dist/helpers/helpers.config.d.ts b/frontend/node_modules/chart.js/dist/helpers/helpers.config.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..daaf4a017d5b5ba4904abe1bbf5819048fa02cb2 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers/helpers.config.d.ts @@ -0,0 +1,31 @@ +import type { AnyObject } from '../types/basic.js'; +import type { ChartMeta } from '../types/index.js'; +import type { ResolverObjectKey, ResolverCache, ResolverProxy, DescriptorDefaults, Descriptor, ContextProxy } from './helpers.config.types.js'; +export * from './helpers.config.types.js'; +/** + * Creates a Proxy for resolving raw values for options. + * @param scopes - The option scopes to look for values, in resolution order + * @param prefixes - The prefixes for values, in resolution order. + * @param rootScopes - The root option scopes + * @param fallback - Parent scopes fallback + * @param getTarget - callback for getting the target for changed values + * @returns Proxy + * @private + */ +export declare function _createResolver(scopes: T, prefixes?: string[], rootScopes?: R, fallback?: ResolverObjectKey, getTarget?: () => AnyObject): any; +/** + * Returns an Proxy for resolving option values with context. + * @param proxy - The Proxy returned by `_createResolver` + * @param context - Context object for scriptable/indexable options + * @param subProxy - The proxy provided for scriptable options + * @param descriptorDefaults - Defaults for descriptors + * @private + */ +export declare function _attachContext(proxy: ResolverProxy, context: AnyObject, subProxy?: ResolverProxy, descriptorDefaults?: DescriptorDefaults): ContextProxy; +/** + * @private + */ +export declare function _descriptors(proxy: ResolverCache, defaults?: DescriptorDefaults): Descriptor; +export declare function _parseObjectDataRadialScale(meta: ChartMeta<'line' | 'scatter'>, data: AnyObject[], start: number, count: number): { + r: unknown; +}[]; diff --git a/frontend/node_modules/chart.js/dist/helpers/helpers.config.types.d.ts b/frontend/node_modules/chart.js/dist/helpers/helpers.config.types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..328ae73c2acf014c2a4febb44b733f84adcac64a --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers/helpers.config.types.d.ts @@ -0,0 +1,41 @@ +import type { AnyObject } from '../types/basic.js'; +import type { Merge } from '../types/utils.js'; +export type ResolverObjectKey = string | boolean; +export interface ResolverCache { + [Symbol.toStringTag]: 'Object'; + _cacheable: boolean; + _scopes: T; + _rootScopes: T | R; + _fallback: ResolverObjectKey; + _keys?: string[]; + _scriptable?: boolean; + _indexable?: boolean; + _allKeys?: boolean; + _storage?: T[number]; + _getTarget(): T[number]; + override(scope: S): ResolverProxy<(T[number] | S)[], T | R>; +} +export type ResolverProxy = Merge & ResolverCache; +export interface DescriptorDefaults { + scriptable: boolean; + indexable: boolean; + allKeys?: boolean; +} +export interface Descriptor { + allKeys: boolean; + scriptable: boolean; + indexable: boolean; + isScriptable(key: string): boolean; + isIndexable(key: string): boolean; +} +export interface ContextCache { + _cacheable: boolean; + _proxy: ResolverProxy; + _context: AnyObject; + _subProxy: ResolverProxy; + _stack: Set; + _descriptors: Descriptor; + setContext(ctx: AnyObject): ContextProxy; + override(scope: S): ContextProxy<(T[number] | S)[], T | R>; +} +export type ContextProxy = Merge & ContextCache; diff --git a/frontend/node_modules/chart.js/dist/helpers/helpers.core.d.ts b/frontend/node_modules/chart.js/dist/helpers/helpers.core.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..448f178aabb1cf8b56d321f407b5f49f34880706 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers/helpers.core.d.ts @@ -0,0 +1,147 @@ +/** + * @namespace Chart.helpers + */ +import type { AnyObject } from '../types/basic.js'; +import type { ActiveDataPoint, ChartEvent } from '../types/index.js'; +/** + * An empty function that can be used, for example, for optional callback. + */ +export declare function noop(): void; +/** + * Returns a unique id, sequentially generated from a global variable. + */ +export declare const uid: () => number; +/** + * Returns true if `value` is neither null nor undefined, else returns false. + * @param value - The value to test. + * @since 2.7.0 + */ +export declare function isNullOrUndef(value: unknown): value is null | undefined; +/** + * Returns true if `value` is an array (including typed arrays), else returns false. + * @param value - The value to test. + * @function + */ +export declare function isArray(value: unknown): value is T[]; +/** + * Returns true if `value` is an object (excluding null), else returns false. + * @param value - The value to test. + * @since 2.7.0 + */ +export declare function isObject(value: unknown): value is AnyObject; +/** + * Returns true if `value` is a finite number, else returns false + * @param value - The value to test. + */ +declare function isNumberFinite(value: unknown): value is number; +export { isNumberFinite as isFinite, }; +/** + * Returns `value` if finite, else returns `defaultValue`. + * @param value - The value to return if defined. + * @param defaultValue - The value to return if `value` is not finite. + */ +export declare function finiteOrDefault(value: unknown, defaultValue: number): number; +/** + * Returns `value` if defined, else returns `defaultValue`. + * @param value - The value to return if defined. + * @param defaultValue - The value to return if `value` is undefined. + */ +export declare function valueOrDefault(value: T | undefined, defaultValue: T): T; +export declare const toPercentage: (value: number | string, dimension: number) => number; +export declare const toDimension: (value: number | string, dimension: number) => number; +/** + * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the + * value returned by `fn`. If `fn` is not a function, this method returns undefined. + * @param fn - The function to call. + * @param args - The arguments with which `fn` should be called. + * @param [thisArg] - The value of `this` provided for the call to `fn`. + */ +export declare function callback R, TA, R>(fn: T | undefined, args: unknown[], thisArg?: TA): R | undefined; +/** + * Note(SB) for performance sake, this method should only be used when loopable type + * is unknown or in none intensive code (not called often and small loopable). Else + * it's preferable to use a regular for() loop and save extra function calls. + * @param loopable - The object or array to be iterated. + * @param fn - The function to call for each item. + * @param [thisArg] - The value of `this` provided for the call to `fn`. + * @param [reverse] - If true, iterates backward on the loopable. + */ +export declare function each(loopable: Record, fn: (this: TA, v: T, i: string) => void, thisArg?: TA, reverse?: boolean): void; +export declare function each(loopable: T[], fn: (this: TA, v: T, i: number) => void, thisArg?: TA, reverse?: boolean): void; +/** + * Returns true if the `a0` and `a1` arrays have the same content, else returns false. + * @param a0 - The array to compare + * @param a1 - The array to compare + * @private + */ +export declare function _elementsEqual(a0: ActiveDataPoint[], a1: ActiveDataPoint[]): boolean; +/** + * Returns a deep copy of `source` without keeping references on objects and arrays. + * @param source - The value to clone. + */ +export declare function clone(source: T): T; +/** + * The default merger when Chart.helpers.merge is called without merger option. + * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback. + * @private + */ +export declare function _merger(key: string, target: AnyObject, source: AnyObject, options: AnyObject): void; +export interface MergeOptions { + merger?: (key: string, target: AnyObject, source: AnyObject, options?: AnyObject) => void; +} +/** + * Recursively deep copies `source` properties into `target` with the given `options`. + * IMPORTANT: `target` is not cloned and will be updated with `source` properties. + * @param target - The target object in which all sources are merged into. + * @param source - Object(s) to merge into `target`. + * @param [options] - Merging options: + * @param [options.merger] - The merge method (key, target, source, options) + * @returns The `target` object. + */ +export declare function merge(target: T, source: [], options?: MergeOptions): T; +export declare function merge(target: T, source: S1, options?: MergeOptions): T & S1; +export declare function merge(target: T, source: [S1], options?: MergeOptions): T & S1; +export declare function merge(target: T, source: [S1, S2], options?: MergeOptions): T & S1 & S2; +export declare function merge(target: T, source: [S1, S2, S3], options?: MergeOptions): T & S1 & S2 & S3; +export declare function merge(target: T, source: [S1, S2, S3, S4], options?: MergeOptions): T & S1 & S2 & S3 & S4; +export declare function merge(target: T, source: AnyObject[], options?: MergeOptions): AnyObject; +/** + * Recursively deep copies `source` properties into `target` *only* if not defined in target. + * IMPORTANT: `target` is not cloned and will be updated with `source` properties. + * @param target - The target object in which all sources are merged into. + * @param source - Object(s) to merge into `target`. + * @returns The `target` object. + */ +export declare function mergeIf(target: T, source: []): T; +export declare function mergeIf(target: T, source: S1): T & S1; +export declare function mergeIf(target: T, source: [S1]): T & S1; +export declare function mergeIf(target: T, source: [S1, S2]): T & S1 & S2; +export declare function mergeIf(target: T, source: [S1, S2, S3]): T & S1 & S2 & S3; +export declare function mergeIf(target: T, source: [S1, S2, S3, S4]): T & S1 & S2 & S3 & S4; +export declare function mergeIf(target: T, source: AnyObject[]): AnyObject; +/** + * Merges source[key] in target[key] only if target[key] is undefined. + * @private + */ +export declare function _mergerIf(key: string, target: AnyObject, source: AnyObject): void; +/** + * @private + */ +export declare function _deprecated(scope: string, value: unknown, previous: string, current: string): void; +/** + * @private + */ +export declare function _splitKey(key: string): string[]; +export declare function resolveObjectKey(obj: AnyObject, key: string): any; +/** + * @private + */ +export declare function _capitalize(str: string): string; +export declare const defined: (value: unknown) => boolean; +export declare const isFunction: (value: unknown) => value is (...args: any[]) => any; +export declare const setsEqual: (a: Set, b: Set) => boolean; +/** + * @param e - The event + * @private + */ +export declare function _isClickEvent(e: ChartEvent): boolean; diff --git a/frontend/node_modules/chart.js/dist/helpers/helpers.curve.d.ts b/frontend/node_modules/chart.js/dist/helpers/helpers.curve.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e6357cb263725aee776e8a953f5a388e6365c7be --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers/helpers.curve.d.ts @@ -0,0 +1,17 @@ +import type { ChartArea } from '../types/index.js'; +import type { SplinePoint } from '../types/geometric.js'; +export declare function splineCurve(firstPoint: SplinePoint, middlePoint: SplinePoint, afterPoint: SplinePoint, t: number): { + previous: SplinePoint; + next: SplinePoint; +}; +/** + * This function calculates Bézier control points in a similar way than |splineCurve|, + * but preserves monotonicity of the provided data and ensures no local extremums are added + * between the dataset discrete points due to the interpolation. + * See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation + */ +export declare function splineCurveMonotone(points: SplinePoint[], indexAxis?: 'x' | 'y'): void; +/** + * @private + */ +export declare function _updateBezierControlPoints(points: SplinePoint[], options: any, area: ChartArea, loop: boolean, indexAxis: 'x' | 'y'): void; diff --git a/frontend/node_modules/chart.js/dist/helpers/helpers.dataset.d.ts b/frontend/node_modules/chart.js/dist/helpers/helpers.dataset.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..389c79993d8a6f22ab00658edb42a43562d96467 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers/helpers.dataset.d.ts @@ -0,0 +1,2 @@ +import type { Chart, ChartMeta, TRBL } from '../types/index.js'; +export declare function getDatasetClipArea(chart: Chart, meta: ChartMeta): TRBL | false; diff --git a/frontend/node_modules/chart.js/dist/helpers/helpers.dom.d.ts b/frontend/node_modules/chart.js/dist/helpers/helpers.dom.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e83132dade73dec55c3fdb04baff29c42f88e74 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers/helpers.dom.d.ts @@ -0,0 +1,48 @@ +import type PrivateChart from '../core/core.controller.js'; +import type { Chart, ChartEvent } from '../types.js'; +/** + * @private + */ +export declare function _isDomSupported(): boolean; +/** + * @private + */ +export declare function _getParentNode(domNode: HTMLCanvasElement): HTMLCanvasElement; +export declare function getStyle(el: HTMLElement, property: string): string; +/** + * Gets an event's x, y coordinates, relative to the chart area + * @param event + * @param chart + * @returns x and y coordinates of the event + */ +export declare function getRelativePosition(event: Event | ChartEvent | TouchEvent | MouseEvent, chart: Chart | PrivateChart): { + x: number; + y: number; +}; +export declare function getMaximumSize(canvas: HTMLCanvasElement, bbWidth?: number, bbHeight?: number, aspectRatio?: number): { + width: number; + height: number; +}; +/** + * @param chart + * @param forceRatio + * @param forceStyle + * @returns True if the canvas context size or transformation has changed. + */ +export declare function retinaScale(chart: Chart | PrivateChart, forceRatio: number, forceStyle?: boolean): boolean | void; +/** + * Detects support for options object argument in addEventListener. + * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support + * @private + */ +export declare const supportsEventListenerOptions: boolean; +/** + * The "used" size is the final value of a dimension property after all calculations have + * been performed. This method uses the computed style of `element` but returns undefined + * if the computed style is not expressed in pixels. That can happen in some cases where + * `element` has a size relative to its parent and this last one is not yet displayed, + * for example because of `display: none` on a parent node. + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value + * @returns Size in pixels or undefined if unknown. + */ +export declare function readUsedSize(element: HTMLElement, property: 'width' | 'height'): number | undefined; diff --git a/frontend/node_modules/chart.js/dist/helpers/helpers.easing.d.ts b/frontend/node_modules/chart.js/dist/helpers/helpers.easing.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b9f55900076b1d49439dac2f2bc446f5b6a1def --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers/helpers.easing.d.ts @@ -0,0 +1,40 @@ +/** + * Easing functions adapted from Robert Penner's easing equations. + * @namespace Chart.helpers.easing.effects + * @see http://www.robertpenner.com/easing/ + */ +declare const effects: { + readonly linear: (t: number) => number; + readonly easeInQuad: (t: number) => number; + readonly easeOutQuad: (t: number) => number; + readonly easeInOutQuad: (t: number) => number; + readonly easeInCubic: (t: number) => number; + readonly easeOutCubic: (t: number) => number; + readonly easeInOutCubic: (t: number) => number; + readonly easeInQuart: (t: number) => number; + readonly easeOutQuart: (t: number) => number; + readonly easeInOutQuart: (t: number) => number; + readonly easeInQuint: (t: number) => number; + readonly easeOutQuint: (t: number) => number; + readonly easeInOutQuint: (t: number) => number; + readonly easeInSine: (t: number) => number; + readonly easeOutSine: (t: number) => number; + readonly easeInOutSine: (t: number) => number; + readonly easeInExpo: (t: number) => number; + readonly easeOutExpo: (t: number) => number; + readonly easeInOutExpo: (t: number) => number; + readonly easeInCirc: (t: number) => number; + readonly easeOutCirc: (t: number) => number; + readonly easeInOutCirc: (t: number) => number; + readonly easeInElastic: (t: number) => number; + readonly easeOutElastic: (t: number) => number; + readonly easeInOutElastic: (t: number) => number; + readonly easeInBack: (t: number) => number; + readonly easeOutBack: (t: number) => number; + readonly easeInOutBack: (t: number) => number; + readonly easeInBounce: (t: number) => number; + readonly easeOutBounce: (t: number) => number; + readonly easeInOutBounce: (t: number) => number; +}; +export type EasingFunction = keyof typeof effects; +export default effects; diff --git a/frontend/node_modules/chart.js/dist/helpers/helpers.extras.d.ts b/frontend/node_modules/chart.js/dist/helpers/helpers.extras.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fc958952fe09aeb8a07cbd507eb329fb125714e9 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers/helpers.extras.d.ts @@ -0,0 +1,45 @@ +import type { ChartMeta, PointElement } from '../types/index.js'; +export declare function fontString(pixelSize: number, fontStyle: string, fontFamily: string): string; +/** +* Request animation polyfill +*/ +export declare const requestAnimFrame: (((callback: FrameRequestCallback) => number) & typeof requestAnimationFrame) | ((callback: any) => any); +/** + * Throttles calling `fn` once per animation frame + * Latest arguments are used on the actual call + */ +export declare function throttled>(fn: (...args: TArgs) => void, thisArg: any): (...args: TArgs) => void; +/** + * Debounces calling `fn` for `delay` ms + */ +export declare function debounce>(fn: (...args: TArgs) => void, delay: number): (...args: TArgs) => number; +/** + * Converts 'start' to 'left', 'end' to 'right' and others to 'center' + * @private + */ +export declare const _toLeftRightCenter: (align: 'start' | 'end' | 'center') => "center" | "left" | "right"; +/** + * Returns `start`, `end` or `(start + end) / 2` depending on `align`. Defaults to `center` + * @private + */ +export declare const _alignStartEnd: (align: 'start' | 'end' | 'center', start: number, end: number) => number; +/** + * Returns `left`, `right` or `(left + right) / 2` depending on `align`. Defaults to `left` + * @private + */ +export declare const _textX: (align: 'left' | 'right' | 'center', left: number, right: number, rtl: boolean) => number; +/** + * Return start and count of visible points. + * @private + */ +export declare function _getStartAndCountOfVisiblePoints(meta: ChartMeta<'line' | 'scatter'>, points: PointElement[], animationsDisabled: boolean): { + start: number; + count: number; +}; +/** + * Checks if the scale ranges have changed. + * @param {object} meta - dataset meta. + * @returns {boolean} + * @private + */ +export declare function _scaleRangesChanged(meta: any): boolean; diff --git a/frontend/node_modules/chart.js/dist/helpers/helpers.interpolation.d.ts b/frontend/node_modules/chart.js/dist/helpers/helpers.interpolation.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d0b6d9b704ab456f5035b3f89adf41441dc84899 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers/helpers.interpolation.d.ts @@ -0,0 +1,22 @@ +import type { Point, SplinePoint } from '../types/geometric.js'; +/** + * @private + */ +export declare function _pointInLine(p1: Point, p2: Point, t: number, mode?: any): { + x: number; + y: number; +}; +/** + * @private + */ +export declare function _steppedInterpolation(p1: Point, p2: Point, t: number, mode: 'middle' | 'after' | unknown): { + x: number; + y: number; +}; +/** + * @private + */ +export declare function _bezierInterpolation(p1: SplinePoint, p2: SplinePoint, t: number, mode?: any): { + x: number; + y: number; +}; diff --git a/frontend/node_modules/chart.js/dist/helpers/helpers.intl.d.ts b/frontend/node_modules/chart.js/dist/helpers/helpers.intl.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..288f8cf78737c8456a700a5d591dd3f6d9b8a0d9 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers/helpers.intl.d.ts @@ -0,0 +1 @@ +export declare function formatNumber(num: number, locale: string, options?: Intl.NumberFormatOptions): string; diff --git a/frontend/node_modules/chart.js/dist/helpers/helpers.math.d.ts b/frontend/node_modules/chart.js/dist/helpers/helpers.math.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c7b5549aaae6a22a86e28c6e4779efc420f1ea43 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers/helpers.math.d.ts @@ -0,0 +1,84 @@ +import type { Point } from '../types/geometric.js'; +/** + * @alias Chart.helpers.math + * @namespace + */ +export declare const PI: number; +export declare const TAU: number; +export declare const PITAU: number; +export declare const INFINITY: number; +export declare const RAD_PER_DEG: number; +export declare const HALF_PI: number; +export declare const QUARTER_PI: number; +export declare const TWO_THIRDS_PI: number; +export declare const log10: (x: number) => number; +export declare const sign: (x: number) => number; +export declare function almostEquals(x: number, y: number, epsilon: number): boolean; +/** + * Implementation of the nice number algorithm used in determining where axis labels will go + */ +export declare function niceNum(range: number): number; +/** + * Returns an array of factors sorted from 1 to sqrt(value) + * @private + */ +export declare function _factorize(value: number): number[]; +export declare function isNumber(n: unknown): n is number; +export declare function almostWhole(x: number, epsilon: number): boolean; +/** + * @private + */ +export declare function _setMinAndMaxByKey(array: Record[], target: { + min: number; + max: number; +}, property: string): void; +export declare function toRadians(degrees: number): number; +export declare function toDegrees(radians: number): number; +/** + * Returns the number of decimal places + * i.e. the number of digits after the decimal point, of the value of this Number. + * @param x - A number. + * @returns The number of decimal places. + * @private + */ +export declare function _decimalPlaces(x: number): number; +export declare function getAngleFromPoint(centrePoint: Point, anglePoint: Point): { + angle: number; + distance: number; +}; +export declare function distanceBetweenPoints(pt1: Point, pt2: Point): number; +/** + * Shortest distance between angles, in either direction. + * @private + */ +export declare function _angleDiff(a: number, b: number): number; +/** + * Normalize angle to be between 0 and 2*PI + * @private + */ +export declare function _normalizeAngle(a: number): number; +/** + * @private + */ +export declare function _angleBetween(angle: number, start: number, end: number, sameAngleIsFullCircle?: boolean): boolean; +/** + * Limit `value` between `min` and `max` + * @param value + * @param min + * @param max + * @private + */ +export declare function _limitValue(value: number, min: number, max: number): number; +/** + * @param {number} value + * @private + */ +export declare function _int16Range(value: number): number; +/** + * @param value + * @param start + * @param end + * @param [epsilon] + * @private + */ +export declare function _isBetween(value: number, start: number, end: number, epsilon?: number): boolean; diff --git a/frontend/node_modules/chart.js/dist/helpers/helpers.options.d.ts b/frontend/node_modules/chart.js/dist/helpers/helpers.options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0aae90a0f5da1c404b4a22ef46c73139f4545ef0 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers/helpers.options.d.ts @@ -0,0 +1,97 @@ +import type { ChartArea, FontSpec, Point } from '../types/index.js'; +import type { TRBL, TRBLCorners } from '../types/geometric.js'; +/** + * @alias Chart.helpers.options + * @namespace + */ +/** + * Converts the given line height `value` in pixels for a specific font `size`. + * @param value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em'). + * @param size - The font size (in pixels) used to resolve relative `value`. + * @returns The effective line height in pixels (size * 1.2 if value is invalid). + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height + * @since 2.7.0 + */ +export declare function toLineHeight(value: number | string, size: number): number; +/** + * @param value + * @param props + */ +export declare function _readValueToProps(value: number | Record, props: K[]): Record; +export declare function _readValueToProps(value: number | Record, props: Record): Record; +/** + * Converts the given value into a TRBL object. + * @param value - If a number, set the value to all TRBL component, + * else, if an object, use defined properties and sets undefined ones to 0. + * x / y are shorthands for same value for left/right and top/bottom. + * @returns The padding values (top, right, bottom, left) + * @since 3.0.0 + */ +export declare function toTRBL(value: number | TRBL | Point): Record<"left" | "top" | "bottom" | "right", number>; +/** + * Converts the given value into a TRBL corners object (similar with css border-radius). + * @param value - If a number, set the value to all TRBL corner components, + * else, if an object, use defined properties and sets undefined ones to 0. + * @returns The TRBL corner values (topLeft, topRight, bottomLeft, bottomRight) + * @since 3.0.0 + */ +export declare function toTRBLCorners(value: number | TRBLCorners): Record<"topLeft" | "topRight" | "bottomLeft" | "bottomRight", number>; +/** + * Converts the given value into a padding object with pre-computed width/height. + * @param value - If a number, set the value to all TRBL component, + * else, if an object, use defined properties and sets undefined ones to 0. + * x / y are shorthands for same value for left/right and top/bottom. + * @returns The padding values (top, right, bottom, left, width, height) + * @since 2.7.0 + */ +export declare function toPadding(value?: number | TRBL): ChartArea; +/** + * Parses font options and returns the font object. + * @param options - A object that contains font options to be parsed. + * @param fallback - A object that contains fallback font options. + * @return The font object. + * @private + */ +export declare function toFont(options: Partial, fallback?: Partial): { + family: string; + lineHeight: number; + size: number; + style: "normal" | "inherit" | "italic" | "oblique" | "initial"; + weight: number | "bold" | "normal" | "lighter" | "bolder"; + string: string; +}; +/** + * Evaluates the given `inputs` sequentially and returns the first defined value. + * @param inputs - An array of values, falling back to the last value. + * @param context - If defined and the current value is a function, the value + * is called with `context` as first argument and the result becomes the new input. + * @param index - If defined and the current value is an array, the value + * at `index` become the new input. + * @param info - object to return information about resolution in + * @param info.cacheable - Will be set to `false` if option is not cacheable. + * @since 2.7.0 + */ +export declare function resolve(inputs: Array, context?: object, index?: number, info?: { + cacheable: boolean; +}): unknown; +/** + * @param minmax + * @param grace + * @param beginAtZero + * @private + */ +export declare function _addGrace(minmax: { + min: number; + max: number; +}, grace: number | string, beginAtZero: boolean): { + min: number; + max: number; +}; +/** + * Create a context inheriting parentContext + * @param parentContext + * @param context + * @returns + */ +export declare function createContext(parentContext: null, context: T): T; +export declare function createContext(parentContext: P, context: T): P & T; diff --git a/frontend/node_modules/chart.js/dist/helpers/helpers.rtl.d.ts b/frontend/node_modules/chart.js/dist/helpers/helpers.rtl.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..93ceb1c6a52eff0a1763d6a83ebc313995942752 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers/helpers.rtl.d.ts @@ -0,0 +1,10 @@ +export interface RTLAdapter { + x(x: number): number; + setWidth(w: number): void; + textAlign(align: 'center' | 'left' | 'right'): 'center' | 'left' | 'right'; + xPlus(x: number, value: number): number; + leftForLtr(x: number, itemWidth: number): number; +} +export declare function getRtlAdapter(rtl: boolean, rectX: number, width: number): RTLAdapter; +export declare function overrideTextDirection(ctx: CanvasRenderingContext2D, direction: 'ltr' | 'rtl'): void; +export declare function restoreTextDirection(ctx: CanvasRenderingContext2D, original?: [string, string]): void; diff --git a/frontend/node_modules/chart.js/dist/helpers/helpers.segment.d.ts b/frontend/node_modules/chart.js/dist/helpers/helpers.segment.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..20f19c4828509540a0fa707f91c1d1cc10892c2e --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers/helpers.segment.d.ts @@ -0,0 +1,65 @@ +/** + * Returns the sub-segment(s) of a line segment that fall in the given bounds + * @param {object} segment + * @param {number} segment.start - start index of the segment, referring the points array + * @param {number} segment.end - end index of the segment, referring the points array + * @param {boolean} segment.loop - indicates that the segment is a loop + * @param {object} [segment.style] - segment style + * @param {PointElement[]} points - the points that this segment refers to + * @param {object} [bounds] + * @param {string} bounds.property - the property of a `PointElement` we are bounding. `x`, `y` or `angle`. + * @param {number} bounds.start - start value of the property + * @param {number} bounds.end - end value of the property + * @private + **/ +export function _boundSegment(segment: { + start: number; + end: number; + loop: boolean; + style?: object; +}, points: PointElement[], bounds?: { + property: string; + start: number; + end: number; +}): { + start: number; + end: number; + loop: boolean; + style?: object; +}[]; +/** + * Returns the segments of the line that are inside given bounds + * @param {LineElement} line + * @param {object} [bounds] + * @param {string} bounds.property - the property we are bounding with. `x`, `y` or `angle`. + * @param {number} bounds.start - start value of the `property` + * @param {number} bounds.end - end value of the `property` + * @private + */ +export function _boundSegments(line: LineElement, bounds?: { + property: string; + start: number; + end: number; +}): { + start: number; + end: number; + loop: boolean; + style?: object; +}[]; +/** + * Compute the continuous segments that define the whole line + * There can be skipped points within a segment, if spanGaps is true. + * @param {LineElement} line + * @param {object} [segmentOptions] + * @return {Segment[]} + * @private + */ +export function _computeSegments(line: LineElement, segmentOptions?: object): Segment[]; +export type LineElement = import('../elements/element.line.js').default; +export type PointElement = import('../elements/element.point.js').default; +export type Segment = { + start: number; + end: number; + loop: boolean; + style?: any; +}; diff --git a/frontend/node_modules/chart.js/dist/helpers/index.d.ts b/frontend/node_modules/chart.js/dist/helpers/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b1784d2aac2294e3f33369ae20550335a0a345c --- /dev/null +++ b/frontend/node_modules/chart.js/dist/helpers/index.d.ts @@ -0,0 +1,16 @@ +export * from './helpers.color.js'; +export * from './helpers.core.js'; +export * from './helpers.canvas.js'; +export * from './helpers.collection.js'; +export * from './helpers.config.js'; +export * from './helpers.curve.js'; +export * from './helpers.dom.js'; +export { default as easingEffects } from './helpers.easing.js'; +export * from './helpers.extras.js'; +export * from './helpers.interpolation.js'; +export * from './helpers.intl.js'; +export * from './helpers.options.js'; +export * from './helpers.math.js'; +export * from './helpers.rtl.js'; +export * from './helpers.segment.js'; +export * from './helpers.dataset.js'; diff --git a/frontend/node_modules/chart.js/dist/index.d.ts b/frontend/node_modules/chart.js/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc748023c139c3a8a4c89e71cabea86a15433cf6 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/index.d.ts @@ -0,0 +1,12 @@ +export * from './controllers/index.js'; +export * from './core/index.js'; +export * from './elements/index.js'; +export * from './platform/index.js'; +export * from './plugins/index.js'; +export * from './scales/index.js'; +import * as controllers from './controllers/index.js'; +import * as elements from './elements/index.js'; +import * as plugins from './plugins/index.js'; +import * as scales from './scales/index.js'; +export { controllers, elements, plugins, scales, }; +export declare const registerables: (typeof controllers | typeof elements | typeof plugins | typeof scales)[]; diff --git a/frontend/node_modules/chart.js/dist/index.umd.d.ts b/frontend/node_modules/chart.js/dist/index.umd.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..58e390f6d7e1fb4bfa55c188e4951f6743a35114 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/index.umd.d.ts @@ -0,0 +1,5 @@ +/** + * @namespace Chart + */ +import Chart from './core/core.controller.js'; +export default Chart; diff --git a/frontend/node_modules/chart.js/dist/platform/index.d.ts b/frontend/node_modules/chart.js/dist/platform/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ad12831d36c9183de18b2ff047d4536de681c53 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/platform/index.d.ts @@ -0,0 +1,5 @@ +export function _detectPlatform(canvas: any): typeof BasicPlatform | typeof DomPlatform; +import BasicPlatform from "./platform.basic.js"; +import DomPlatform from "./platform.dom.js"; +import BasePlatform from "./platform.base.js"; +export { BasePlatform, BasicPlatform, DomPlatform }; diff --git a/frontend/node_modules/chart.js/dist/platform/platform.base.d.ts b/frontend/node_modules/chart.js/dist/platform/platform.base.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..34bc9aec7b8f2ab8aba494b665209399efcdd84f --- /dev/null +++ b/frontend/node_modules/chart.js/dist/platform/platform.base.d.ts @@ -0,0 +1,63 @@ +/** + * @typedef { import('../core/core.controller.js').default } Chart + */ +/** + * Abstract class that allows abstracting platform dependencies away from the chart. + */ +export default class BasePlatform { + /** + * Called at chart construction time, returns a context2d instance implementing + * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}. + * @param {HTMLCanvasElement} canvas - The canvas from which to acquire context (platform specific) + * @param {number} [aspectRatio] - The chart options + */ + acquireContext(canvas: HTMLCanvasElement, aspectRatio?: number): void; + /** + * Called at chart destruction time, releases any resources associated to the context + * previously returned by the acquireContext() method. + * @param {CanvasRenderingContext2D} context - The context2d instance + * @returns {boolean} true if the method succeeded, else false + */ + releaseContext(context: CanvasRenderingContext2D): boolean; + /** + * Registers the specified listener on the given chart. + * @param {Chart} chart - Chart from which to listen for event + * @param {string} type - The ({@link ChartEvent}) type to listen for + * @param {function} listener - Receives a notification (an object that implements + * the {@link ChartEvent} interface) when an event of the specified type occurs. + */ + addEventListener(chart: Chart, type: string, listener: Function): void; + /** + * Removes the specified listener previously registered with addEventListener. + * @param {Chart} chart - Chart from which to remove the listener + * @param {string} type - The ({@link ChartEvent}) type to remove + * @param {function} listener - The listener function to remove from the event target. + */ + removeEventListener(chart: Chart, type: string, listener: Function): void; + /** + * @returns {number} the current devicePixelRatio of the device this platform is connected to. + */ + getDevicePixelRatio(): number; + /** + * Returns the maximum size in pixels of given canvas element. + * @param {HTMLCanvasElement} element + * @param {number} [width] - content width of parent element + * @param {number} [height] - content height of parent element + * @param {number} [aspectRatio] - aspect ratio to maintain + */ + getMaximumSize(element: HTMLCanvasElement, width?: number, height?: number, aspectRatio?: number): { + width: number; + height: number; + }; + /** + * @param {HTMLCanvasElement} canvas + * @returns {boolean} true if the canvas is attached to the platform, false if not. + */ + isAttached(canvas: HTMLCanvasElement): boolean; + /** + * Updates config with platform specific requirements + * @param {import('../core/core.config.js').default} config + */ + updateConfig(config: import('../core/core.config.js').default): void; +} +export type Chart = import('../core/core.controller.js').default; diff --git a/frontend/node_modules/chart.js/dist/platform/platform.basic.d.ts b/frontend/node_modules/chart.js/dist/platform/platform.basic.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..929c3736ca7aa99469bbe7abad73b02e1ccecca9 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/platform/platform.basic.d.ts @@ -0,0 +1,10 @@ +/** + * Platform class for charts without access to the DOM or to many element properties + * This platform is used by default for any chart passed an OffscreenCanvas. + * @extends BasePlatform + */ +export default class BasicPlatform extends BasePlatform { + acquireContext(item: any): any; + updateConfig(config: any): void; +} +import BasePlatform from "./platform.base.js"; diff --git a/frontend/node_modules/chart.js/dist/platform/platform.dom.d.ts b/frontend/node_modules/chart.js/dist/platform/platform.dom.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c82f4ed2394351809c59abd6d3a92dbfbc1cda34 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/platform/platform.dom.d.ts @@ -0,0 +1,19 @@ +/** + * Platform class for charts that can access the DOM and global window/document properties + * @extends BasePlatform + */ +export default class DomPlatform extends BasePlatform { + /** + * @param {HTMLCanvasElement} canvas + * @param {number} [aspectRatio] + * @return {CanvasRenderingContext2D|null} + */ + acquireContext(canvas: HTMLCanvasElement, aspectRatio?: number): CanvasRenderingContext2D | null; + /** + * @param {Chart} chart + * @param {string} type + */ + removeEventListener(chart: Chart, type: string): void; +} +export type Chart = import('../core/core.controller.js').default; +import BasePlatform from "./platform.base.js"; diff --git a/frontend/node_modules/chart.js/dist/plugins/index.d.ts b/frontend/node_modules/chart.js/dist/plugins/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..39043cf2a4cba674e0ac08ae67bc9c956332ea29 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/plugins/index.d.ts @@ -0,0 +1,7 @@ +export { default as Colors } from "./plugin.colors.js"; +export { default as Decimation } from "./plugin.decimation.js"; +export { default as Filler } from "./plugin.filler/index.js"; +export { default as Legend } from "./plugin.legend.js"; +export { default as SubTitle } from "./plugin.subtitle.js"; +export { default as Title } from "./plugin.title.js"; +export { default as Tooltip } from "./plugin.tooltip.js"; diff --git a/frontend/node_modules/chart.js/dist/plugins/plugin.colors.d.ts b/frontend/node_modules/chart.js/dist/plugins/plugin.colors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d445b8a120f88431255373bc604e28e3a9aff89b --- /dev/null +++ b/frontend/node_modules/chart.js/dist/plugins/plugin.colors.d.ts @@ -0,0 +1,11 @@ +import type { Chart } from '../types.js'; +export interface ColorsPluginOptions { + enabled?: boolean; + forceOverride?: boolean; +} +declare const _default: { + id: string; + defaults: ColorsPluginOptions; + beforeLayout(chart: Chart, _args: any, options: ColorsPluginOptions): void; +}; +export default _default; diff --git a/frontend/node_modules/chart.js/dist/plugins/plugin.decimation.d.ts b/frontend/node_modules/chart.js/dist/plugins/plugin.decimation.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d94db92202b3b158dc17736d9f009cffcd871e4 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/plugins/plugin.decimation.d.ts @@ -0,0 +1,10 @@ +declare namespace _default { + const id: string; + namespace defaults { + const algorithm: string; + const enabled: boolean; + } + function beforeElementsUpdate(chart: any, args: any, options: any): void; + function destroy(chart: any): void; +} +export default _default; diff --git a/frontend/node_modules/chart.js/dist/plugins/plugin.filler/filler.drawing.d.ts b/frontend/node_modules/chart.js/dist/plugins/plugin.filler/filler.drawing.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a89b48e95dce0c6436fdc8fc026fb6900cd9983b --- /dev/null +++ b/frontend/node_modules/chart.js/dist/plugins/plugin.filler/filler.drawing.d.ts @@ -0,0 +1 @@ +export function _drawfill(ctx: any, source: any, area: any): void; diff --git a/frontend/node_modules/chart.js/dist/plugins/plugin.filler/filler.helper.d.ts b/frontend/node_modules/chart.js/dist/plugins/plugin.filler/filler.helper.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fbccfa7f1e3f55cd4dd6b959b7a7df89cd14a853 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/plugins/plugin.filler/filler.helper.d.ts @@ -0,0 +1,14 @@ +/** + * @param {PointElement[] | { x: number; y: number; }} boundary + * @param {LineElement} line + * @return {LineElement?} + */ +export function _createBoundaryLine(boundary: PointElement[] | { + x: number; + y: number; +}, line: LineElement): LineElement | null; +export function _shouldApplyFill(source: any): boolean; +export type Chart = import('../../core/core.controller.js').default; +export type Scale = import('../../core/core.scale.js').default; +export type PointElement = import('../../elements/element.point.js').default; +import { LineElement } from "../../elements/index.js"; diff --git a/frontend/node_modules/chart.js/dist/plugins/plugin.filler/filler.options.d.ts b/frontend/node_modules/chart.js/dist/plugins/plugin.filler/filler.options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f3d218b4ea67207f08535e7988b8245e145295a1 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/plugins/plugin.filler/filler.options.d.ts @@ -0,0 +1,30 @@ +/** + * @typedef { import('../../core/core.scale.js').default } Scale + * @typedef { import('../../elements/element.line.js').default } LineElement + * @typedef { import('../../types/index.js').FillTarget } FillTarget + * @typedef { import('../../types/index.js').ComplexFillTarget } ComplexFillTarget + */ +export function _resolveTarget(sources: any, index: any, propagate: any): any; +/** + * @param {LineElement} line + * @param {number} index + * @param {number} count + */ +export function _decodeFill(line: LineElement, index: number, count: number): any; +/** + * @param {FillTarget | ComplexFillTarget} fill + * @param {Scale} scale + * @returns {number | null} + */ +export function _getTargetPixel(fill: FillTarget | ComplexFillTarget, scale: Scale): number | null; +/** + * @param {FillTarget | ComplexFillTarget} fill + * @param {Scale} scale + * @param {number} startValue + * @returns {number | undefined} + */ +export function _getTargetValue(fill: FillTarget | ComplexFillTarget, scale: Scale, startValue: number): number | undefined; +export type Scale = import('../../core/core.scale.js').default; +export type LineElement = import('../../elements/element.line.js').default; +export type FillTarget = import('../../types/index.js').FillTarget; +export type ComplexFillTarget = import('../../types/index.js').ComplexFillTarget; diff --git a/frontend/node_modules/chart.js/dist/plugins/plugin.filler/filler.segment.d.ts b/frontend/node_modules/chart.js/dist/plugins/plugin.filler/filler.segment.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..41552ecd60131408346cf7d3245e9c3c7dd7eb3d --- /dev/null +++ b/frontend/node_modules/chart.js/dist/plugins/plugin.filler/filler.segment.d.ts @@ -0,0 +1,36 @@ +export function _segments(line: any, target: any, property: any): ({ + source: any; + target: { + property: any; + start: any; + end: any; + }; + start: any; + end: any; +} | { + source: { + start: number; + end: number; + loop: boolean; + style?: any; + }; + target: { + start: number; + end: number; + loop: boolean; + style?: any; + }; + start: { + [x: number]: any; + }; + end: { + [x: number]: any; + }; +})[]; +export function _getBounds(property: any, first: any, last: any, loop: any): { + property: any; + start: any; + end: any; +}; +export function _pointsFromSegments(boundary: any, line: any): any[]; +export function _findSegmentEnd(start: any, end: any, points: any): any; diff --git a/frontend/node_modules/chart.js/dist/plugins/plugin.filler/filler.target.d.ts b/frontend/node_modules/chart.js/dist/plugins/plugin.filler/filler.target.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..90656c9ddff72b0e7e5af6c540139c1edf0bfc91 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/plugins/plugin.filler/filler.target.d.ts @@ -0,0 +1,9 @@ +/** + * @typedef { import('../../core/core.controller.js').default } Chart + * @typedef { import('../../core/core.scale.js').default } Scale + * @typedef { import('../../elements/element.point.js').default } PointElement + */ +export function _getTarget(source: any): any; +export type Chart = import('../../core/core.controller.js').default; +export type Scale = import('../../core/core.scale.js').default; +export type PointElement = import('../../elements/element.point.js').default; diff --git a/frontend/node_modules/chart.js/dist/plugins/plugin.filler/filler.target.stack.d.ts b/frontend/node_modules/chart.js/dist/plugins/plugin.filler/filler.target.stack.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..be2625f1b4f47f2bcd4f7129b236c19642a12c2e --- /dev/null +++ b/frontend/node_modules/chart.js/dist/plugins/plugin.filler/filler.target.stack.d.ts @@ -0,0 +1,14 @@ +/** + * @param {{ chart: Chart; scale: Scale; index: number; line: LineElement; }} source + * @return {LineElement} + */ +export function _buildStackLine(source: { + chart: Chart; + scale: Scale; + index: number; + line: LineElement; +}): LineElement; +export type Chart = import('../../core/core.controller.js').default; +export type Scale = import('../../core/core.scale.js').default; +export type PointElement = import('../../elements/element.point.js').default; +import { LineElement } from "../../elements/index.js"; diff --git a/frontend/node_modules/chart.js/dist/plugins/plugin.filler/index.d.ts b/frontend/node_modules/chart.js/dist/plugins/plugin.filler/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3c8e36ac964975b8c1c470eeed52ade12bd06341 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/plugins/plugin.filler/index.d.ts @@ -0,0 +1,12 @@ +declare namespace _default { + const id: string; + function afterDatasetsUpdate(chart: any, _args: any, options: any): void; + function beforeDraw(chart: any, _args: any, options: any): void; + function beforeDatasetsDraw(chart: any, _args: any, options: any): void; + function beforeDatasetDraw(chart: any, args: any, options: any): void; + namespace defaults { + const propagate: boolean; + const drawTime: string; + } +} +export default _default; diff --git a/frontend/node_modules/chart.js/dist/plugins/plugin.filler/simpleArc.d.ts b/frontend/node_modules/chart.js/dist/plugins/plugin.filler/simpleArc.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..91f9d7d163aacc9493634fab046c989a06bbc980 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/plugins/plugin.filler/simpleArc.d.ts @@ -0,0 +1,12 @@ +export class simpleArc { + constructor(opts: any); + x: any; + y: any; + radius: any; + pathSegment(ctx: any, bounds: any, opts: any): boolean; + interpolate(point: any): { + x: any; + y: any; + angle: any; + }; +} diff --git a/frontend/node_modules/chart.js/dist/plugins/plugin.legend.d.ts b/frontend/node_modules/chart.js/dist/plugins/plugin.legend.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a9827ceebdf3a170c3415146e2890bd3ce0d8b0a --- /dev/null +++ b/frontend/node_modules/chart.js/dist/plugins/plugin.legend.d.ts @@ -0,0 +1,114 @@ +export class Legend extends Element { + /** + * @param {{ ctx: any; options: any; chart: any; }} config + */ + constructor(config: { + ctx: any; + options: any; + chart: any; + }); + _added: boolean; + legendHitBoxes: any[]; + /** + * @private + */ + private _hoveredItem; + doughnutMode: boolean; + chart: any; + options: any; + ctx: any; + legendItems: any; + columnSizes: any[]; + lineWidths: number[]; + maxHeight: any; + maxWidth: any; + top: any; + bottom: any; + left: any; + right: any; + height: any; + width: any; + _margins: any; + position: any; + weight: any; + fullSize: any; + update(maxWidth: any, maxHeight: any, margins: any): void; + setDimensions(): void; + buildLabels(): void; + fit(): void; + /** + * @private + */ + private _fitRows; + _fitCols(titleHeight: any, labelFont: any, boxWidth: any, _itemHeight: any): any; + adjustHitBoxes(): void; + isHorizontal(): boolean; + draw(): void; + /** + * @private + */ + private _draw; + /** + * @protected + */ + protected drawTitle(): void; + /** + * @private + */ + private _computeTitleHeight; + /** + * @private + */ + private _getLegendItemAt; + /** + * Handle an event + * @param {ChartEvent} e - The event to handle + */ + handleEvent(e: ChartEvent): void; +} +declare namespace _default { + export const id: string; + export { Legend as _element }; + export function start(chart: any, _args: any, options: any): void; + export function stop(chart: any): void; + export function beforeUpdate(chart: any, _args: any, options: any): void; + export function afterUpdate(chart: any): void; + export function afterEvent(chart: any, args: any): void; + export namespace defaults { + const display: boolean; + const position: string; + const align: string; + const fullSize: boolean; + const reverse: boolean; + const weight: number; + function onClick(e: any, legendItem: any, legend: any): void; + const onHover: any; + const onLeave: any; + namespace labels { + function color(ctx: any): any; + const boxWidth: number; + const padding: number; + function generateLabels(chart: any): any; + } + namespace title { + export function color_1(ctx: any): any; + export { color_1 as color }; + const display_1: boolean; + export { display_1 as display }; + const position_1: string; + export { position_1 as position }; + export const text: string; + } + } + export namespace descriptors { + export function _scriptable(name: any): boolean; + export namespace labels_1 { + export function _scriptable_1(name: any): boolean; + export { _scriptable_1 as _scriptable }; + } + export { labels_1 as labels }; + } +} +export default _default; +export type ChartEvent = import('../types/index.js').ChartEvent; +import Element from "../core/core.element.js"; diff --git a/frontend/node_modules/chart.js/dist/plugins/plugin.subtitle.d.ts b/frontend/node_modules/chart.js/dist/plugins/plugin.subtitle.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a9490547af67bd25115d0a8ca2118bc6526d577 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/plugins/plugin.subtitle.d.ts @@ -0,0 +1,27 @@ +declare namespace _default { + const id: string; + function start(chart: any, _args: any, options: any): void; + function stop(chart: any): void; + function beforeUpdate(chart: any, _args: any, options: any): void; + namespace defaults { + export const align: string; + export const display: boolean; + export namespace font { + const weight: string; + } + export const fullSize: boolean; + export const padding: number; + export const position: string; + export const text: string; + const weight_1: number; + export { weight_1 as weight }; + } + namespace defaultRoutes { + const color: string; + } + namespace descriptors { + const _scriptable: boolean; + const _indexable: boolean; + } +} +export default _default; diff --git a/frontend/node_modules/chart.js/dist/plugins/plugin.title.d.ts b/frontend/node_modules/chart.js/dist/plugins/plugin.title.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c2e73bc344e681bfa785388a5e71308dbac26cf4 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/plugins/plugin.title.d.ts @@ -0,0 +1,61 @@ +export class Title extends Element { + /** + * @param {{ ctx: any; options: any; chart: any; }} config + */ + constructor(config: { + ctx: any; + options: any; + chart: any; + }); + chart: any; + options: any; + ctx: any; + _padding: import("../types.js").ChartArea; + top: number; + bottom: any; + left: number; + right: any; + width: any; + height: any; + position: any; + weight: any; + fullSize: any; + update(maxWidth: any, maxHeight: any): void; + isHorizontal(): boolean; + _drawArgs(offset: any): { + titleX: any; + titleY: any; + maxWidth: number; + rotation: number; + }; + draw(): void; +} +declare namespace _default { + export const id: string; + export { Title as _element }; + export function start(chart: any, _args: any, options: any): void; + export function stop(chart: any): void; + export function beforeUpdate(chart: any, _args: any, options: any): void; + export namespace defaults { + export const align: string; + export const display: boolean; + export namespace font { + const weight: string; + } + export const fullSize: boolean; + export const padding: number; + export const position: string; + export const text: string; + const weight_1: number; + export { weight_1 as weight }; + } + export namespace defaultRoutes { + const color: string; + } + export namespace descriptors { + const _scriptable: boolean; + const _indexable: boolean; + } +} +export default _default; +import Element from "../core/core.element.js"; diff --git a/frontend/node_modules/chart.js/dist/plugins/plugin.tooltip.d.ts b/frontend/node_modules/chart.js/dist/plugins/plugin.tooltip.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..77315038e56fd37086b13f6a414885773fbdc328 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/plugins/plugin.tooltip.d.ts @@ -0,0 +1,288 @@ +export class Tooltip extends Element { + /** + * @namespace Chart.Tooltip.positioners + */ + static positioners: { + /** + * Average mode places the tooltip at the average position of the elements shown + */ + average(items: any): false | { + x: number; + y: number; + }; + /** + * Gets the tooltip position nearest of the item nearest to the event position + */ + nearest(items: any, eventPosition: any): false | { + x: any; + y: any; + }; + }; + constructor(config: any); + opacity: number; + _active: any[]; + _eventPosition: any; + _size: { + width: number; + height: number; + }; + _cachedAnimations: Readonly; + _tooltipItems: any[]; + $animations: any; + $context: any; + chart: any; + options: any; + dataPoints: { + chart: import("../core/core.controller.js").default; + label: any; + parsed: any; + raw: any; + formattedValue: any; + dataset: any; + dataIndex: number; + datasetIndex: number; + element: Element; + }[]; + title: any; + beforeBody: any; + body: any[]; + afterBody: any; + footer: any; + xAlign: any; + yAlign: any; + x: any; + y: any; + height: number; + width: number; + caretX: any; + caretY: any; + labelColors: any[]; + labelPointStyles: any[]; + labelTextColors: any[]; + initialize(options: any): void; + /** + * @private + */ + private _resolveAnimations; + /** + * @protected + */ + protected getContext(): any; + getTitle(context: any, options: any): any; + getBeforeBody(tooltipItems: any, options: any): any; + getBody(tooltipItems: any, options: any): any[]; + getAfterBody(tooltipItems: any, options: any): any; + getFooter(tooltipItems: any, options: any): any; + /** + * @private + */ + private _createItems; + update(changed: any, replay: any): void; + drawCaret(tooltipPoint: any, ctx: any, size: any, options: any): void; + getCaretPosition(tooltipPoint: any, size: any, options: any): { + x1: any; + x2: any; + x3: any; + y1: any; + y2: any; + y3: any; + }; + drawTitle(pt: any, ctx: any, options: any): void; + /** + * @private + */ + private _drawColorBox; + drawBody(pt: any, ctx: any, options: any): void; + drawFooter(pt: any, ctx: any, options: any): void; + drawBackground(pt: any, ctx: any, tooltipSize: any, options: any): void; + /** + * Update x/y animation targets when _active elements are animating too + * @private + */ + private _updateAnimationTarget; + /** + * Determine if the tooltip will draw anything + * @returns {boolean} True if the tooltip will render + */ + _willRender(): boolean; + draw(ctx: any): void; + /** + * Get active elements in the tooltip + * @returns {Array} Array of elements that are active in the tooltip + */ + getActiveElements(): any[]; + /** + * Set active elements in the tooltip + * @param {array} activeElements Array of active datasetIndex/index pairs. + * @param {object} eventPosition Synthetic event position used in positioning + */ + setActiveElements(activeElements: any[], eventPosition: object): void; + _ignoreReplayEvents: boolean; + /** + * Handle an event + * @param {ChartEvent} e - The event to handle + * @param {boolean} [replay] - This is a replayed event (from update) + * @param {boolean} [inChartArea] - The event is inside chartArea + * @returns {boolean} true if the tooltip changed + */ + handleEvent(e: ChartEvent, replay?: boolean, inChartArea?: boolean): boolean; + /** + * Helper for determining the active elements for event + * @param {ChartEvent} e - The event to handle + * @param {InteractionItem[]} lastActive - Previously active elements + * @param {boolean} [replay] - This is a replayed event (from update) + * @param {boolean} [inChartArea] - The event is inside chartArea + * @returns {InteractionItem[]} - Active elements + * @private + */ + private _getActiveElements; + /** + * Determine if the active elements + event combination changes the + * tooltip position + * @param {array} active - Active elements + * @param {ChartEvent} e - Event that triggered the position change + * @returns {boolean} True if the position has changed + */ + _positionChanged(active: any[], e: ChartEvent): boolean; +} +declare namespace _default { + export const id: string; + export { Tooltip as _element }; + export { positioners }; + export function afterInit(chart: any, _args: any, options: any): void; + export function beforeUpdate(chart: any, _args: any, options: any): void; + export function reset(chart: any, _args: any, options: any): void; + export function afterDraw(chart: any): void; + export function afterEvent(chart: any, args: any): void; + export namespace defaults { + export const enabled: boolean; + export const external: any; + export const position: string; + export const backgroundColor: string; + export const titleColor: string; + export namespace titleFont { + const weight: string; + } + export const titleSpacing: number; + export const titleMarginBottom: number; + export const titleAlign: string; + export const bodyColor: string; + export const bodySpacing: number; + export const bodyFont: {}; + export const bodyAlign: string; + export const footerColor: string; + export const footerSpacing: number; + export const footerMarginTop: number; + export namespace footerFont { + const weight_1: string; + export { weight_1 as weight }; + } + export const footerAlign: string; + export const padding: number; + export const caretPadding: number; + export const caretSize: number; + export const cornerRadius: number; + export function boxHeight(ctx: any, opts: any): any; + export function boxWidth(ctx: any, opts: any): any; + export const multiKeyBackground: string; + export const displayColors: boolean; + export const boxPadding: number; + export const borderColor: string; + export const borderWidth: number; + export namespace animation { + const duration: number; + const easing: string; + } + export namespace animations { + namespace numbers { + const type: string; + const properties: string[]; + } + namespace opacity { + const easing_1: string; + export { easing_1 as easing }; + const duration_1: number; + export { duration_1 as duration }; + } + } + export { defaultCallbacks as callbacks }; + } + export namespace defaultRoutes { + const bodyFont_1: string; + export { bodyFont_1 as bodyFont }; + const footerFont_1: string; + export { footerFont_1 as footerFont }; + const titleFont_1: string; + export { titleFont_1 as titleFont }; + } + export namespace descriptors { + export function _scriptable(name: any): boolean; + export const _indexable: boolean; + export namespace callbacks { + const _scriptable_1: boolean; + export { _scriptable_1 as _scriptable }; + const _indexable_1: boolean; + export { _indexable_1 as _indexable }; + } + export namespace animation_1 { + const _fallback: boolean; + } + export { animation_1 as animation }; + export namespace animations_1 { + const _fallback_1: string; + export { _fallback_1 as _fallback }; + } + export { animations_1 as animations }; + } + export const additionalOptionScopes: string[]; +} +export default _default; +export type Chart = import('../platform/platform.base.js').Chart; +export type ChartEvent = import('../types/index.js').ChartEvent; +export type ActiveElement = import('../types/index.js').ActiveElement; +export type InteractionItem = import('../core/core.interaction.js').InteractionItem; +import Element from "../core/core.element.js"; +import Animations from "../core/core.animations.js"; +declare namespace positioners { + /** + * Average mode places the tooltip at the average position of the elements shown + */ + function average(items: any): false | { + x: number; + y: number; + }; + /** + * Gets the tooltip position nearest of the item nearest to the event position + */ + function nearest(items: any, eventPosition: any): false | { + x: any; + y: any; + }; +} +declare namespace defaultCallbacks { + export { noop as beforeTitle }; + export function title(tooltipItems: any): any; + export { noop as afterTitle }; + export { noop as beforeBody }; + export { noop as beforeLabel }; + export function label(tooltipItem: any): any; + export function labelColor(tooltipItem: any): { + borderColor: any; + backgroundColor: any; + borderWidth: any; + borderDash: any; + borderDashOffset: any; + borderRadius: number; + }; + export function labelTextColor(): any; + export function labelPointStyle(tooltipItem: any): { + pointStyle: any; + rotation: any; + }; + export { noop as afterLabel }; + export { noop as afterBody }; + export { noop as beforeFooter }; + export { noop as footer }; + export { noop as afterFooter }; +} +import { noop } from "../helpers/helpers.core.js"; diff --git a/frontend/node_modules/chart.js/dist/scales/index.d.ts b/frontend/node_modules/chart.js/dist/scales/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a6b28f93c52d76723c47a9c4c1d9552656676713 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/scales/index.d.ts @@ -0,0 +1,6 @@ +export { default as CategoryScale } from "./scale.category.js"; +export { default as LinearScale } from "./scale.linear.js"; +export { default as LogarithmicScale } from "./scale.logarithmic.js"; +export { default as RadialLinearScale } from "./scale.radialLinear.js"; +export { default as TimeScale } from "./scale.time.js"; +export { default as TimeSeriesScale } from "./scale.timeseries.js"; diff --git a/frontend/node_modules/chart.js/dist/scales/scale.category.d.ts b/frontend/node_modules/chart.js/dist/scales/scale.category.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..85af4c56f33d2622eb02c4c2fe964d91f2eafcdd --- /dev/null +++ b/frontend/node_modules/chart.js/dist/scales/scale.category.d.ts @@ -0,0 +1,21 @@ +export default class CategoryScale extends Scale { + static id: string; + /** + * @type {any} + */ + static defaults: any; + /** @type {number} */ + _startValue: number; + _valueRange: number; + _addedLabels: any[]; + init(scaleOptions: any): void; + parse(raw: any, index: any): number; + buildTicks(): { + value: any; + }[]; + getLabelForValue(value: any): any; + getPixelForValue(value: any): number; + getPixelForTick(index: any): number; + getValueForPixel(pixel: any): number; +} +import Scale from "../core/core.scale.js"; diff --git a/frontend/node_modules/chart.js/dist/scales/scale.linear.d.ts b/frontend/node_modules/chart.js/dist/scales/scale.linear.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3a7174415701fbd5a1d743293331c7b5139cdc22 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/scales/scale.linear.d.ts @@ -0,0 +1,10 @@ +export default class LinearScale extends LinearScaleBase { + static id: string; + /** + * @type {any} + */ + static defaults: any; + getPixelForValue(value: any): number; + getValueForPixel(pixel: any): number; +} +import LinearScaleBase from "./scale.linearbase.js"; diff --git a/frontend/node_modules/chart.js/dist/scales/scale.linearbase.d.ts b/frontend/node_modules/chart.js/dist/scales/scale.linearbase.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..39f264b75079a9ba8143f03a81a152f5f03edd73 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/scales/scale.linearbase.d.ts @@ -0,0 +1,20 @@ +export default class LinearScaleBase extends Scale { + /** @type {number} */ + start: number; + /** @type {number} */ + end: number; + /** @type {number} */ + _startValue: number; + /** @type {number} */ + _endValue: number; + _valueRange: number; + parse(raw: any, index: any): number; + handleTickRangeOptions(): void; + getTickLimit(): number; + /** + * @protected + */ + protected computeTickLimit(): number; + getLabelForValue(value: any): string; +} +import Scale from "../core/core.scale.js"; diff --git a/frontend/node_modules/chart.js/dist/scales/scale.logarithmic.d.ts b/frontend/node_modules/chart.js/dist/scales/scale.logarithmic.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..32ce9c6b5f9969a68b6366bbd4b74281d9941380 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/scales/scale.logarithmic.d.ts @@ -0,0 +1,25 @@ +export default class LogarithmicScale extends Scale { + static id: string; + /** + * @type {any} + */ + static defaults: any; + /** @type {number} */ + start: number; + /** @type {number} */ + end: number; + /** @type {number} */ + _startValue: number; + _valueRange: number; + parse(raw: any, index: any): number; + _zero: boolean; + handleTickRangeOptions(): void; + /** + * @param {number} value + * @return {string} + */ + getLabelForValue(value: number): string; + getPixelForValue(value: any): number; + getValueForPixel(pixel: any): number; +} +import Scale from "../core/core.scale.js"; diff --git a/frontend/node_modules/chart.js/dist/scales/scale.radialLinear.d.ts b/frontend/node_modules/chart.js/dist/scales/scale.radialLinear.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a34fa8f3e556c5d4baf8ff416d6ca2b4f3470728 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/scales/scale.radialLinear.d.ts @@ -0,0 +1,63 @@ +export default class RadialLinearScale extends LinearScaleBase { + static id: string; + /** + * @type {any} + */ + static defaults: any; + static defaultRoutes: { + 'angleLines.color': string; + 'pointLabels.color': string; + 'ticks.color': string; + }; + static descriptors: { + angleLines: { + _fallback: string; + }; + }; + /** @type {number} */ + xCenter: number; + /** @type {number} */ + yCenter: number; + /** @type {number} */ + drawingArea: number; + /** @type {string[]} */ + _pointLabels: string[]; + _pointLabelItems: any[]; + _padding: import("../types.js").ChartArea; + generateTickLabels(ticks: any): void; + setCenterPoint(leftMovement: any, rightMovement: any, topMovement: any, bottomMovement: any): void; + getIndexAngle(index: any): number; + getDistanceFromCenterForValue(value: any): number; + getValueForDistanceFromCenter(distance: any): any; + getPointLabelContext(index: any): any; + getPointPosition(index: any, distanceFromCenter: any, additionalAngle?: number): { + x: number; + y: number; + angle: number; + }; + getPointPositionForValue(index: any, value: any): { + x: number; + y: number; + angle: number; + }; + getBasePosition(index: any): { + x: number; + y: number; + angle: number; + }; + getPointLabelPosition(index: any): { + left: any; + top: any; + right: any; + bottom: any; + }; + /** + * @protected + */ + protected drawGrid(): void; + /** + * @protected + */ + protected drawLabels(): void; +} +import LinearScaleBase from "./scale.linearbase.js"; diff --git a/frontend/node_modules/chart.js/dist/scales/scale.time.d.ts b/frontend/node_modules/chart.js/dist/scales/scale.time.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6bdaeeb51bba48af277b4e49a8a82c50277d15be --- /dev/null +++ b/frontend/node_modules/chart.js/dist/scales/scale.time.d.ts @@ -0,0 +1,130 @@ +export default class TimeScale extends Scale { + static id: string; + /** + * @type {any} + */ + static defaults: any; + /** + * @param {object} props + */ + constructor(props: object); + /** @type {{data: number[], labels: number[], all: number[]}} */ + _cache: { + data: number[]; + labels: number[]; + all: number[]; + }; + /** @type {Unit} */ + _unit: Unit; + /** @type {Unit=} */ + _majorUnit: Unit | undefined; + _offsets: {}; + _normalized: boolean; + _parseOpts: { + parser: any; + round: any; + isoWeekday: any; + }; + init(scaleOpts: any, opts?: {}): void; + _adapter: DateAdapter; + /** + * @param {*} raw + * @param {number?} [index] + * @return {number} + */ + parse(raw: any, index?: number | null): number; + /** + * @private + */ + private _getLabelBounds; + /** + * Returns the start and end offsets from edges in the form of {start, end} + * where each value is a relative width to the scale and ranges between 0 and 1. + * They add extra margins on the both sides by scaling down the original scale. + * Offsets are added when the `offset` option is true. + * @param {number[]} timestamps + * @protected + */ + protected initOffsets(timestamps?: number[]): void; + /** + * Generates a maximum of `capacity` timestamps between min and max, rounded to the + * `minor` unit using the given scale time `options`. + * Important: this method can return ticks outside the min and max range, it's the + * responsibility of the calling code to clamp values if needed. + * @protected + */ + protected _generate(): number[]; + /** + * @param {number} value + * @return {string} + */ + getLabelForValue(value: number): string; + /** + * @param {number} value + * @param {string|undefined} format + * @return {string} + */ + format(value: number, format: string | undefined): string; + /** + * Function to format an individual tick mark + * @param {number} time + * @param {number} index + * @param {object[]} ticks + * @param {string|undefined} [format] + * @return {string} + * @private + */ + private _tickFormatFunction; + /** + * @param {object[]} ticks + */ + generateTickLabels(ticks: object[]): void; + /** + * @param {number} value - Milliseconds since epoch (1 January 1970 00:00:00 UTC) + * @return {number} + */ + getDecimalForValue(value: number): number; + /** + * @param {number} value - Milliseconds since epoch (1 January 1970 00:00:00 UTC) + * @return {number} + */ + getPixelForValue(value: number): number; + /** + * @param {number} pixel + * @return {number} + */ + getValueForPixel(pixel: number): number; + /** + * @param {string} label + * @return {{w:number, h:number}} + * @private + */ + private _getLabelSize; + /** + * @param {number} exampleTime + * @return {number} + * @private + */ + private _getLabelCapacity; + /** + * @protected + */ + protected getDataTimestamps(): any; + /** + * @protected + */ + protected getLabelTimestamps(): number[]; + /** + * @param {number[]} values + * @protected + */ + protected normalize(values: number[]): number[]; +} +export type Unit = import('../core/core.adapters.js').TimeUnit; +export type Interval = { + common: boolean; + size: number; + steps?: number; +}; +export type DateAdapter = import('../core/core.adapters.js').DateAdapter; +import Scale from "../core/core.scale.js"; diff --git a/frontend/node_modules/chart.js/dist/scales/scale.timeseries.d.ts b/frontend/node_modules/chart.js/dist/scales/scale.timeseries.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0afa0611818b48a8b859695abdde00dd1c45c629 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/scales/scale.timeseries.d.ts @@ -0,0 +1,39 @@ +export default TimeSeriesScale; +declare class TimeSeriesScale extends TimeScale { + /** @type {object[]} */ + _table: object[]; + /** @type {number} */ + _minPos: number; + /** @type {number} */ + _tableRange: number; + /** + * @protected + */ + protected initOffsets(): void; + /** + * Returns an array of {time, pos} objects used to interpolate a specific `time` or position + * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is + * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other + * extremity (left + width or top + height). Note that it would be more optimized to directly + * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need + * to create the lookup table. The table ALWAYS contains at least two items: min and max. + * @param {number[]} timestamps + * @return {object[]} + * @protected + */ + protected buildLookupTable(timestamps: number[]): object[]; + /** + * Generates all timestamps defined in the data. + * Important: this method can return ticks outside the min and max range, it's the + * responsibility of the calling code to clamp values if needed. + * @protected + */ + protected _generate(): any; + /** + * Returns all timestamps + * @return {number[]} + * @private + */ + private _getTimestampsForTable; +} +import TimeScale from "./scale.time.js"; diff --git a/frontend/node_modules/chart.js/dist/types.d.ts b/frontend/node_modules/chart.js/dist/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f3d839218f765ee2569dca83acc51526b0b1b427 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/types.d.ts @@ -0,0 +1,10 @@ +/** + * Temporary entry point of the types at the time of the transition. + * After transition done need to remove it in favor of index.ts + */ +export * from './index.js'; +/** + * Explicitly re-exporting to resolve the ambiguity. + */ +export { BarController, BubbleController, DoughnutController, LineController, PieController, PolarAreaController, RadarController, ScatterController, Animation, Animations, Chart, DatasetController, Interaction, Scale, Ticks, defaults, layouts, registry, ArcElement, BarElement, LineElement, PointElement, BasePlatform, BasicPlatform, DomPlatform, Decimation, Filler, Legend, SubTitle, Title, Tooltip, CategoryScale, LinearScale, LogarithmicScale, RadialLinearScale, TimeScale, TimeSeriesScale, PluginOptionsByType, ElementOptionsByType, ChartDatasetProperties, UpdateModeEnum, registerables } from './types/index.js'; +export * from './types/index.js'; diff --git a/frontend/node_modules/chart.js/dist/types/animation.d.ts b/frontend/node_modules/chart.js/dist/types/animation.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..41895125e991d0e269961e5b5258de6f46714b00 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/types/animation.d.ts @@ -0,0 +1,34 @@ +import {Chart} from './index.js'; +import {AnyObject} from './basic.js'; + +export declare class Animation { + constructor(cfg: AnyObject, target: AnyObject, prop: string, to?: unknown); + active(): boolean; + update(cfg: AnyObject, to: unknown, date: number): void; + cancel(): void; + tick(date: number): void; + readonly _to: unknown; +} + +export interface AnimationEvent { + chart: Chart; + numSteps: number; + initial: boolean; + currentStep: number; +} + +export declare class Animator { + listen(chart: Chart, event: 'complete' | 'progress', cb: (event: AnimationEvent) => void): void; + add(chart: Chart, items: readonly Animation[]): void; + has(chart: Chart): boolean; + start(chart: Chart): void; + running(chart: Chart): boolean; + stop(chart: Chart): void; + remove(chart: Chart): boolean; +} + +export declare class Animations { + constructor(chart: Chart, animations: AnyObject); + configure(animations: AnyObject): void; + update(target: AnyObject, values: AnyObject): undefined | boolean; +} diff --git a/frontend/node_modules/chart.js/dist/types/basic.d.ts b/frontend/node_modules/chart.js/dist/types/basic.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f48ee23dcbafbd094f962b4b112548317e1b45e --- /dev/null +++ b/frontend/node_modules/chart.js/dist/types/basic.d.ts @@ -0,0 +1,3 @@ + +export type AnyObject = Record; +export type EmptyObject = Record; diff --git a/frontend/node_modules/chart.js/dist/types/color.d.ts b/frontend/node_modules/chart.js/dist/types/color.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a68f98bbd67f92d7bb81ee6e824bbff49c18f38 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/types/color.d.ts @@ -0,0 +1 @@ +export type Color = string | CanvasGradient | CanvasPattern; diff --git a/frontend/node_modules/chart.js/dist/types/geometric.d.ts b/frontend/node_modules/chart.js/dist/types/geometric.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9df01f16487a88a021b789cf932eee4b67e41e38 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/types/geometric.d.ts @@ -0,0 +1,52 @@ +export interface ChartArea { + top: number; + left: number; + right: number; + bottom: number; + width: number; + height: number; +} + +export interface Point { + x: number; + y: number; +} + +export type TRBL = { + top: number; + right: number; + bottom: number; + left: number; +} + +export type TRBLCorners = { + topLeft: number; + topRight: number; + bottomLeft: number; + bottomRight: number; +}; + +export type CornerRadius = number | Partial; + +export type RoundedRect = { + x: number; + y: number; + w: number; + h: number; + radius?: CornerRadius +} + +export type Padding = Partial | number | Point; + +export interface SplinePoint { + x: number; + y: number; + skip?: boolean; + + // Both Bezier and monotone interpolations have these fields + // but they are added in different spots + cp1x?: number; + cp1y?: number; + cp2x?: number; + cp2y?: number; +} diff --git a/frontend/node_modules/chart.js/dist/types/index.d.ts b/frontend/node_modules/chart.js/dist/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..69a4cfccbc51fdebd485bd24e270c49556525525 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/types/index.d.ts @@ -0,0 +1,3859 @@ +/* eslint-disable @typescript-eslint/ban-types */ +import {DeepPartial, DistributiveArray, UnionToIntersection} from './utils.js'; + +import {TimeUnit} from '../core/core.adapters.js'; +import PointElement from '../elements/element.point.js'; +import {EasingFunction} from '../helpers/helpers.easing.js'; +import {AnimationEvent} from './animation.js'; +import {AnyObject, EmptyObject} from './basic.js'; +import {Color} from './color.js'; +import Element from '../core/core.element.js'; +import {ChartArea, Padding, Point} from './geometric.js'; +import {LayoutItem, LayoutPosition} from './layout.js'; +import {ColorsPluginOptions} from '../plugins/plugin.colors.js'; + +export {EasingFunction} from '../helpers/helpers.easing.js'; +export {default as ArcElement, ArcProps} from '../elements/element.arc.js'; +export {default as PointElement, PointProps} from '../elements/element.point.js'; +export {Animation, Animations, Animator, AnimationEvent} from './animation.js'; +export {Color} from './color.js'; +export {ChartArea, Point, TRBL} from './geometric.js'; +export {LayoutItem, LayoutPosition} from './layout.js'; + +export interface ScriptableContext { + active: boolean; + chart: Chart; + dataIndex: number; + dataset: UnionToIntersection>; + datasetIndex: number; + type: string; + mode: string; + parsed: UnionToIntersection>; + raw: unknown; +} + +export interface ScriptableLineSegmentContext { + type: 'segment', + p0: PointElement, + p1: PointElement, + p0DataIndex: number, + p1DataIndex: number, + datasetIndex: number +} + +export type Scriptable = T | ((ctx: TContext, options: AnyObject) => T | undefined); +export type ScriptableOptions = { [P in keyof T]: Scriptable }; +export type ScriptableAndScriptableOptions = Scriptable | ScriptableOptions; +export type ScriptableAndArray = readonly T[] | Scriptable; +export type ScriptableAndArrayOptions = { [P in keyof T]: ScriptableAndArray }; + +export interface ParsingOptions { + /** + * How to parse the dataset. The parsing can be disabled by specifying parsing: false at chart options or dataset. If parsing is disabled, data must be sorted and in the formats the associated chart type and scales use internally. + */ + parsing: + { + [key: string]: string; + } + | false; + + /** + * Chart.js is fastest if you provide data with indices that are unique, sorted, and consistent across datasets and provide the normalized: true option to let Chart.js know that you have done so. + */ + normalized: boolean; +} + +export interface ControllerDatasetOptions extends ParsingOptions { + /** + * The base axis of the chart. 'x' for vertical charts and 'y' for horizontal charts. + * @default 'x' + */ + indexAxis: 'x' | 'y'; + /** + * How to clip relative to chartArea. Positive value allows overflow, negative value clips that many pixels inside chartArea. 0 = clip at chartArea. Clipping can also be configured per side: `clip: {left: 5, top: false, right: -2, bottom: 0}` + */ + clip: number | ChartArea | false; + /** + * The label for the dataset which appears in the legend and tooltips. + */ + label: string; + /** + * The drawing order of dataset. Also affects order for stacking, tooltip and legend. + */ + order: number; + + /** + * The ID of the group to which this dataset belongs to (when stacked, each group will be a separate stack). + */ + stack: string; + /** + * Configures the visibility state of the dataset. Set it to true, to hide the dataset from the chart. + * @default false + */ + hidden: boolean; +} + +export interface BarControllerDatasetOptions + extends ControllerDatasetOptions, + ScriptableAndArrayOptions>, + ScriptableAndArrayOptions>, + AnimationOptions<'bar'> { + /** + * The ID of the x axis to plot this dataset on. + */ + xAxisID: string; + /** + * The ID of the y axis to plot this dataset on. + */ + yAxisID: string; + + /** + * Percent (0-1) of the available width each bar should be within the category width. 1.0 will take the whole category width and put the bars right next to each other. + * @default 0.9 + */ + barPercentage: number; + /** + * Percent (0-1) of the available width each category should be within the sample width. + * @default 0.8 + */ + categoryPercentage: number; + + /** + * Manually set width of each bar in pixels. If set to 'flex', it computes "optimal" sample widths that globally arrange bars side by side. If not set (default), bars are equally sized based on the smallest interval. + */ + barThickness: number | 'flex'; + + /** + * Set this to ensure that bars are not sized thicker than this. + */ + maxBarThickness: number; + + /** + * Set this to ensure that bars have a minimum length in pixels. + */ + minBarLength: number; + + /** + * Point style for the legend + * @default 'circle; + */ + pointStyle: PointStyle; + + /** + * Should the bars be grouped on index axis + * @default true + */ + grouped: boolean; +} + +export interface BarControllerChartOptions { + /** + * Should null or undefined values be omitted from drawing + */ + skipNull?: boolean; +} + +export type BarController = DatasetController +export declare const BarController: ChartComponent & { + prototype: BarController; + new (chart: Chart, datasetIndex: number): BarController; +}; + +export interface BubbleControllerDatasetOptions + extends ControllerDatasetOptions, + ScriptableAndArrayOptions>, + ScriptableAndArrayOptions> { + /** + * The ID of the x axis to plot this dataset on. + */ + xAxisID: string; + /** + * The ID of the y axis to plot this dataset on. + */ + yAxisID: string; +} + +export interface BubbleDataPoint extends Point { + /** + * Bubble radius in pixels (not scaled). + */ + r?: number; +} + +export type BubbleController = DatasetController +export declare const BubbleController: ChartComponent & { + prototype: BubbleController; + new (chart: Chart, datasetIndex: number): BubbleController; +}; + +export interface LineControllerDatasetOptions + extends ControllerDatasetOptions, + ScriptableAndArrayOptions>, + ScriptableAndArrayOptions>, + ScriptableOptions, ScriptableContext<'line'>>, + ScriptableAndArrayOptions>, + ScriptableOptions, ScriptableContext<'line'>>, + ScriptableAndArrayOptions>, + AnimationOptions<'line'> { + /** + * The ID of the x axis to plot this dataset on. + */ + xAxisID: string; + /** + * The ID of the y axis to plot this dataset on. + */ + yAxisID: string; + + /** + * If true, lines will be drawn between points with no or null data. If false, points with NaN data will create a break in the line. Can also be a number specifying the maximum gap length to span. The unit of the value depends on the scale used. + * @default false + */ + spanGaps: boolean | number; + + showLine: boolean; +} + +export interface LineControllerChartOptions { + /** + * If true, lines will be drawn between points with no or null data. If false, points with NaN data will create a break in the line. Can also be a number specifying the maximum gap length to span. The unit of the value depends on the scale used. + * @default false + */ + spanGaps: boolean | number; + /** + * If false, the lines between points are not drawn. + * @default true + */ + showLine: boolean; +} + +export type LineController = DatasetController +export declare const LineController: ChartComponent & { + prototype: LineController; + new (chart: Chart, datasetIndex: number): LineController; +}; + +export type ScatterControllerDatasetOptions = LineControllerDatasetOptions; + +export type ScatterDataPoint = Point + +export type ScatterControllerChartOptions = LineControllerChartOptions; + +export type ScatterController = LineController +export declare const ScatterController: ChartComponent & { + prototype: ScatterController; + new (chart: Chart, datasetIndex: number): ScatterController; +}; + +export interface DoughnutControllerDatasetOptions + extends ControllerDatasetOptions, + ScriptableAndArrayOptions>, + ScriptableAndArrayOptions>, + AnimationOptions<'doughnut'> { + + /** + * Sweep to allow arcs to cover. + * @default 360 + */ + circumference: number; + + /** + * Arc offset (in pixels). + */ + offset: number | number[]; + + /** + * Starting angle to draw this dataset from. + * @default 0 + */ + rotation: number; + + /** + * The relative thickness of the dataset. Providing a value for weight will cause the pie or doughnut dataset to be drawn with a thickness relative to the sum of all the dataset weight values. + * @default 1 + */ + weight: number; + + /** + * Similar to the `offset` option, but applies to all arcs. This can be used to to add spaces + * between arcs + * @default 0 + */ + spacing: number; +} + +export interface DoughnutAnimationOptions extends AnimationSpec<'doughnut'> { + /** + * If true, the chart will animate in with a rotation animation. This property is in the options.animation object. + * @default true + */ + animateRotate: boolean; + + /** + * If true, will animate scaling the chart from the center outwards. + * @default false + */ + animateScale: boolean; +} + +export interface DoughnutControllerChartOptions { + /** + * Sweep to allow arcs to cover. + * @default 360 + */ + circumference: number; + + /** + * The portion of the chart that is cut out of the middle. ('50%' - for doughnut, 0 - for pie) + * String ending with '%' means percentage, number means pixels. + * @default 50 + */ + cutout: Scriptable>; + + /** + * Arc offset (in pixels). + */ + offset: number | number[]; + + /** + * The outer radius of the chart. String ending with '%' means percentage of maximum radius, number means pixels. + * @default '100%' + */ + radius: Scriptable>; + + /** + * Starting angle to draw arcs from. + * @default 0 + */ + rotation: number; + + /** + * Spacing between the arcs + * @default 0 + */ + spacing: number; + + animation: false | DoughnutAnimationOptions; +} + +export type DoughnutDataPoint = number; + +export interface DoughnutController extends DatasetController { + readonly innerRadius: number; + readonly outerRadius: number; + readonly offsetX: number; + readonly offsetY: number; + + calculateTotal(): number; + calculateCircumference(value: number): number; +} + +export declare const DoughnutController: ChartComponent & { + prototype: DoughnutController; + new (chart: Chart, datasetIndex: number): DoughnutController; +}; + +export interface DoughnutMetaExtensions { + total: number; +} + +export type PieControllerDatasetOptions = DoughnutControllerDatasetOptions; +export type PieControllerChartOptions = DoughnutControllerChartOptions; +export type PieAnimationOptions = DoughnutAnimationOptions; + +export type PieDataPoint = DoughnutDataPoint; +export type PieMetaExtensions = DoughnutMetaExtensions; + +export type PieController = DoughnutController +export declare const PieController: ChartComponent & { + prototype: PieController; + new (chart: Chart, datasetIndex: number): PieController; +}; + +export interface PolarAreaControllerDatasetOptions extends DoughnutControllerDatasetOptions { + /** + * Arc angle to cover. - for polar only + * @default circumference / (arc count) + */ + angle: number; +} + +export type PolarAreaAnimationOptions = DoughnutAnimationOptions; + +export interface PolarAreaControllerChartOptions { + /** + * Starting angle to draw arcs for the first item in a dataset. In degrees, 0 is at top. + * @default 0 + */ + startAngle: number; + + animation: false | PolarAreaAnimationOptions; +} + +export interface PolarAreaController extends DoughnutController { + countVisibleElements(): number; +} +export declare const PolarAreaController: ChartComponent & { + prototype: PolarAreaController; + new (chart: Chart, datasetIndex: number): PolarAreaController; +}; + +export interface RadarControllerDatasetOptions + extends ControllerDatasetOptions, + ScriptableAndArrayOptions>, + ScriptableAndArrayOptions>, + AnimationOptions<'radar'> { + /** + * The ID of the x axis to plot this dataset on. + */ + xAxisID: string; + /** + * The ID of the y axis to plot this dataset on. + */ + yAxisID: string; + + /** + * If true, lines will be drawn between points with no or null data. If false, points with NaN data will create a break in the line. Can also be a number specifying the maximum gap length to span. The unit of the value depends on the scale used. + */ + spanGaps: boolean | number; + + /** + * If false, the line is not drawn for this dataset. + */ + showLine: boolean; +} + +export type RadarControllerChartOptions = LineControllerChartOptions; + +export type RadarController = DatasetController +export declare const RadarController: ChartComponent & { + prototype: RadarController; + new (chart: Chart, datasetIndex: number): RadarController; +}; + +interface ChartMetaClip { + left: number | boolean; + top: number | boolean; + right: number | boolean; + bottom: number | boolean; + disabled: boolean; +} + +interface ChartMetaCommon { + type: string; + controller: DatasetController; + order: number; + + label: string; + index: number; + visible: boolean; + + stack: number; + + indexAxis: 'x' | 'y'; + + data: TElement[]; + dataset?: TDatasetElement; + + hidden: boolean; + + xAxisID?: string; + yAxisID?: string; + rAxisID?: string; + iAxisID: string; + vAxisID: string; + + xScale?: Scale; + yScale?: Scale; + rScale?: Scale; + iScale?: Scale; + vScale?: Scale; + + _sorted: boolean; + _stacked: boolean | 'single'; + _parsed: unknown[]; + _clip: ChartMetaClip; +} + +export type ChartMeta< + TType extends ChartType = ChartType, + TElement extends Element = Element, + TDatasetElement extends Element = Element, +> = DeepPartial< +{ [key in ChartType]: ChartTypeRegistry[key]['metaExtensions'] }[TType] +> & ChartMetaCommon; + +export interface ActiveDataPoint { + datasetIndex: number; + index: number; +} + +export interface ActiveElement extends ActiveDataPoint { + element: Element; +} + +export declare class Chart< + TType extends ChartType = ChartType, + TData = DefaultDataPoint, + TLabel = unknown +> { + readonly platform: BasePlatform; + readonly id: string; + readonly canvas: HTMLCanvasElement; + readonly ctx: CanvasRenderingContext2D; + readonly config: ChartConfiguration | ChartConfigurationCustomTypesPerDataset; + readonly width: number; + readonly height: number; + readonly aspectRatio: number; + readonly boxes: LayoutItem[]; + readonly currentDevicePixelRatio: number; + readonly chartArea: ChartArea; + readonly scales: { [key: string]: Scale }; + readonly attached: boolean; + + readonly legend?: LegendElement; // Only available if legend plugin is registered and enabled + readonly tooltip?: TooltipModel; // Only available if tooltip plugin is registered and enabled + + data: ChartData; + options: ChartOptions; + + constructor(item: ChartItem, config: ChartConfiguration | ChartConfigurationCustomTypesPerDataset); + + clear(): this; + stop(): this; + + resize(width?: number, height?: number): void; + ensureScalesHaveIDs(): void; + buildOrUpdateScales(): void; + buildOrUpdateControllers(): void; + reset(): void; + update(mode?: UpdateMode | ((ctx: { datasetIndex: number }) => UpdateMode)): void; + render(): void; + draw(): void; + + isPointInArea(point: Point): boolean; + getElementsAtEventForMode(e: Event, mode: string, options: InteractionOptions, useFinalPosition: boolean): InteractionItem[]; + + getSortedVisibleDatasetMetas(): ChartMeta[]; + getDatasetMeta(datasetIndex: number): ChartMeta; + getVisibleDatasetCount(): number; + isDatasetVisible(datasetIndex: number): boolean; + setDatasetVisibility(datasetIndex: number, visible: boolean): void; + toggleDataVisibility(index: number): void; + getDataVisibility(index: number): boolean; + hide(datasetIndex: number, dataIndex?: number): void; + show(datasetIndex: number, dataIndex?: number): void; + + getActiveElements(): ActiveElement[]; + setActiveElements(active: ActiveDataPoint[]): void; + + destroy(): void; + toBase64Image(type?: string, quality?: unknown): string; + bindEvents(): void; + unbindEvents(): void; + updateHoverStyle(items: InteractionItem[], mode: 'dataset', enabled: boolean): void; + + notifyPlugins(hook: string, args?: AnyObject): boolean | void; + + isPluginEnabled(pluginId: string): boolean; + + getContext(): { chart: Chart, type: string }; + + static readonly defaults: Defaults; + static readonly overrides: Overrides; + static readonly version: string; + static readonly instances: { [key: string]: Chart }; + static readonly registry: Registry; + static getChart(key: string | CanvasRenderingContext2D | HTMLCanvasElement): Chart | undefined; + static register(...items: ChartComponentLike[]): void; + static unregister(...items: ChartComponentLike[]): void; +} + +export declare const registerables: readonly ChartComponentLike[]; + +export declare type ChartItem = + | string + | CanvasRenderingContext2D + | HTMLCanvasElement + | { canvas: HTMLCanvasElement } + | ArrayLike; + +export declare enum UpdateModeEnum { + resize = 'resize', + reset = 'reset', + none = 'none', + hide = 'hide', + show = 'show', + default = 'default', + active = 'active' +} + +export type UpdateMode = keyof typeof UpdateModeEnum; + +export declare class DatasetController< + TType extends ChartType = ChartType, + TElement extends Element = Element, + TDatasetElement extends Element = Element, + TParsedData = ParsedDataType, +> { + constructor(chart: Chart, datasetIndex: number); + + readonly chart: Chart; + readonly index: number; + readonly _cachedMeta: ChartMeta; + enableOptionSharing: boolean; + // If true, the controller supports the decimation + // plugin. Defaults to `false` for all controllers + // except the LineController + supportsDecimation: boolean; + + linkScales(): void; + getAllParsedValues(scale: Scale): number[]; + protected getLabelAndValue(index: number): { label: string; value: string }; + updateElements(elements: TElement[], start: number, count: number, mode: UpdateMode): void; + update(mode: UpdateMode): void; + updateIndex(datasetIndex: number): void; + protected getMaxOverflow(): boolean | number; + draw(): void; + reset(): void; + getDataset(): ChartDataset; + getMeta(): ChartMeta; + getScaleForId(scaleID: string): Scale | undefined; + configure(): void; + initialize(): void; + addElements(): void; + buildOrUpdateElements(resetNewElements?: boolean): void; + + getStyle(index: number, active: boolean): AnyObject; + protected resolveDatasetElementOptions(mode: UpdateMode): AnyObject; + protected resolveDataElementOptions(index: number, mode: UpdateMode): AnyObject; + /** + * Utility for checking if the options are shared and should be animated separately. + * @protected + */ + protected getSharedOptions(options: AnyObject): undefined | AnyObject; + /** + * Utility for determining if `options` should be included in the updated properties + * @protected + */ + protected includeOptions(mode: UpdateMode, sharedOptions: AnyObject): boolean; + /** + * Utility for updating an element with new properties, using animations when appropriate. + * @protected + */ + + protected updateElement(element: TElement | TDatasetElement, index: number | undefined, properties: AnyObject, mode: UpdateMode): void; + /** + * Utility to animate the shared options, that are potentially affecting multiple elements. + * @protected + */ + + protected updateSharedOptions(sharedOptions: AnyObject, mode: UpdateMode, newOptions: AnyObject): void; + removeHoverStyle(element: TElement, datasetIndex: number, index: number): void; + setHoverStyle(element: TElement, datasetIndex: number, index: number): void; + + parse(start: number, count: number): void; + protected parsePrimitiveData(meta: ChartMeta, data: AnyObject[], start: number, count: number): AnyObject[]; + protected parseArrayData(meta: ChartMeta, data: AnyObject[], start: number, count: number): AnyObject[]; + protected parseObjectData(meta: ChartMeta, data: AnyObject[], start: number, count: number): AnyObject[]; + protected getParsed(index: number): TParsedData; + protected applyStack(scale: Scale, parsed: unknown[]): number; + protected updateRangeFromParsed( + range: { min: number; max: number }, + scale: Scale, + parsed: unknown[], + stack: boolean | string + ): void; + protected getMinMax(scale: Scale, canStack?: boolean): { min: number; max: number }; +} + +export interface DatasetControllerChartComponent extends ChartComponent { + defaults: { + datasetElementType?: string | null | false; + dataElementType?: string | null | false; + }; +} + +export interface Defaults extends CoreChartOptions, ElementChartOptions, PluginChartOptions { + + scale: ScaleOptionsByType; + scales: { + [key in ScaleType]: ScaleOptionsByType; + }; + + set(values: AnyObject): AnyObject; + set(scope: string, values: AnyObject): AnyObject; + get(scope: string): AnyObject; + + describe(scope: string, values: AnyObject): AnyObject; + override(scope: string, values: AnyObject): AnyObject; + + /** + * Routes the named defaults to fallback to another scope/name. + * This routing is useful when those target values, like defaults.color, are changed runtime. + * If the values would be copied, the runtime change would not take effect. By routing, the + * fallback is evaluated at each access, so its always up to date. + * + * Example: + * + * defaults.route('elements.arc', 'backgroundColor', '', 'color') + * - reads the backgroundColor from defaults.color when undefined locally + * + * @param scope Scope this route applies to. + * @param name Property name that should be routed to different namespace when not defined here. + * @param targetScope The namespace where those properties should be routed to. + * Empty string ('') is the root of defaults. + * @param targetName The target name in the target scope the property should be routed to. + */ + route(scope: string, name: string, targetScope: string, targetName: string): void; +} + +export type Overrides = { + [key in ChartType]: + CoreChartOptions & + ElementChartOptions & + PluginChartOptions & + DatasetChartOptions & + ScaleChartOptions & + ChartTypeRegistry[key]['chartOptions']; +} + +export declare const defaults: Defaults; +export interface InteractionOptions { + axis?: string; + intersect?: boolean; + includeInvisible?: boolean; +} + +export interface InteractionItem { + element: Element; + datasetIndex: number; + index: number; +} + +export type InteractionModeFunction = ( + chart: Chart, + e: ChartEvent, + options: InteractionOptions, + useFinalPosition?: boolean +) => InteractionItem[]; + +export interface InteractionModeMap { + /** + * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something + * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item + */ + index: InteractionModeFunction; + + /** + * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something + * If the options.intersect is false, we find the nearest item and return the items in that dataset + */ + dataset: InteractionModeFunction; + /** + * Point mode returns all elements that hit test based on the event position + * of the event + */ + point: InteractionModeFunction; + /** + * nearest mode returns the element closest to the point + */ + nearest: InteractionModeFunction; + /** + * x mode returns the elements that hit-test at the current x coordinate + */ + x: InteractionModeFunction; + /** + * y mode returns the elements that hit-test at the current y coordinate + */ + y: InteractionModeFunction; +} + +export type InteractionMode = keyof InteractionModeMap; + +export declare const Interaction: { + modes: InteractionModeMap; + + /** + * Helper function to select candidate elements for interaction + */ + evaluateInteractionItems( + chart: Chart, + axis: InteractionAxis, + position: Point, + handler: (element: Element & VisualElement, datasetIndex: number, index: number) => void, + intersect?: boolean + ): InteractionItem[]; +}; + +export declare const layouts: { + /** + * Register a box to a chart. + * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title. + * @param {Chart} chart - the chart to use + * @param {LayoutItem} item - the item to add to be laid out + */ + addBox(chart: Chart, item: LayoutItem): void; + + /** + * Remove a layoutItem from a chart + * @param {Chart} chart - the chart to remove the box from + * @param {LayoutItem} layoutItem - the item to remove from the layout + */ + removeBox(chart: Chart, layoutItem: LayoutItem): void; + + /** + * Sets (or updates) options on the given `item`. + * @param {Chart} chart - the chart in which the item lives (or will be added to) + * @param {LayoutItem} item - the item to configure with the given options + * @param options - the new item options. + */ + configure( + chart: Chart, + item: LayoutItem, + options: { fullSize?: number; position?: LayoutPosition; weight?: number } + ): void; + + /** + * Fits boxes of the given chart into the given size by having each box measure itself + * then running a fitting algorithm + * @param {Chart} chart - the chart + * @param {number} width - the width to fit into + * @param {number} height - the height to fit into + */ + update(chart: Chart, width: number, height: number): void; +}; + +export interface Plugin extends ExtendedPlugin { + id: string; + + /** + * The events option defines the browser events that the plugin should listen. + * @default ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'] + */ + events?: (keyof HTMLElementEventMap)[] + + /** + * @desc Called when plugin is installed for this chart instance. This hook is also invoked for disabled plugins (options === false). + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + * @since 3.0.0 + */ + install?(chart: Chart, args: EmptyObject, options: O): void; + /** + * @desc Called when a plugin is starting. This happens when chart is created or plugin is enabled. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + * @since 3.0.0 + */ + start?(chart: Chart, args: EmptyObject, options: O): void; + /** + * @desc Called when a plugin stopping. This happens when chart is destroyed or plugin is disabled. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + * @since 3.0.0 + */ + stop?(chart: Chart, args: EmptyObject, options: O): void; + /** + * @desc Called before initializing `chart`. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + */ + beforeInit?(chart: Chart, args: EmptyObject, options: O): void; + /** + * @desc Called after `chart` has been initialized and before the first update. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + */ + afterInit?(chart: Chart, args: EmptyObject, options: O): void; + /** + * @desc Called before updating `chart`. If any plugin returns `false`, the update + * is cancelled (and thus subsequent render(s)) until another `update` is triggered. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {UpdateMode} args.mode - The update mode + * @param {object} options - The plugin options. + * @returns {boolean} `false` to cancel the chart update. + */ + beforeUpdate?(chart: Chart, args: { mode: UpdateMode, cancelable: true }, options: O): boolean | void; + /** + * @desc Called after `chart` has been updated and before rendering. Note that this + * hook will not be called if the chart update has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {UpdateMode} args.mode - The update mode + * @param {object} options - The plugin options. + */ + afterUpdate?(chart: Chart, args: { mode: UpdateMode }, options: O): void; + /** + * @desc Called during the update process, before any chart elements have been created. + * This can be used for data decimation by changing the data array inside a dataset. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + */ + beforeElementsUpdate?(chart: Chart, args: EmptyObject, options: O): void; + /** + * @desc Called during chart reset + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + * @since version 3.0.0 + */ + reset?(chart: Chart, args: EmptyObject, options: O): void; + /** + * @desc Called before updating the `chart` datasets. If any plugin returns `false`, + * the datasets update is cancelled until another `update` is triggered. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {UpdateMode} args.mode - The update mode. + * @param {object} options - The plugin options. + * @returns {boolean} false to cancel the datasets update. + * @since version 2.1.5 + */ + beforeDatasetsUpdate?(chart: Chart, args: { mode: UpdateMode }, options: O): boolean | void; + /** + * @desc Called after the `chart` datasets have been updated. Note that this hook + * will not be called if the datasets update has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {UpdateMode} args.mode - The update mode. + * @param {object} options - The plugin options. + * @since version 2.1.5 + */ + afterDatasetsUpdate?(chart: Chart, args: { mode: UpdateMode, cancelable: true }, options: O): void; + /** + * @desc Called before updating the `chart` dataset at the given `args.index`. If any plugin + * returns `false`, the datasets update is cancelled until another `update` is triggered. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {number} args.index - The dataset index. + * @param {object} args.meta - The dataset metadata. + * @param {UpdateMode} args.mode - The update mode. + * @param {object} options - The plugin options. + * @returns {boolean} `false` to cancel the chart datasets drawing. + */ + beforeDatasetUpdate?(chart: Chart, args: { index: number; meta: ChartMeta, mode: UpdateMode, cancelable: true }, options: O): boolean | void; + /** + * @desc Called after the `chart` datasets at the given `args.index` has been updated. Note + * that this hook will not be called if the datasets update has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {number} args.index - The dataset index. + * @param {object} args.meta - The dataset metadata. + * @param {UpdateMode} args.mode - The update mode. + * @param {object} options - The plugin options. + */ + afterDatasetUpdate?(chart: Chart, args: { index: number; meta: ChartMeta, mode: UpdateMode, cancelable: false }, options: O): void; + /** + * @desc Called before laying out `chart`. If any plugin returns `false`, + * the layout update is cancelled until another `update` is triggered. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + * @returns {boolean} `false` to cancel the chart layout. + */ + beforeLayout?(chart: Chart, args: { cancelable: true }, options: O): boolean | void; + /** + * @desc Called before scale data limits are calculated. This hook is called separately for each scale in the chart. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {Scale} args.scale - The scale. + * @param {object} options - The plugin options. + */ + beforeDataLimits?(chart: Chart, args: { scale: Scale }, options: O): void; + /** + * @desc Called after scale data limits are calculated. This hook is called separately for each scale in the chart. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {Scale} args.scale - The scale. + * @param {object} options - The plugin options. + */ + afterDataLimits?(chart: Chart, args: { scale: Scale }, options: O): void; + /** + * @desc Called before scale builds its ticks. This hook is called separately for each scale in the chart. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {Scale} args.scale - The scale. + * @param {object} options - The plugin options. + */ + beforeBuildTicks?(chart: Chart, args: { scale: Scale }, options: O): void; + /** + * @desc Called after scale has build its ticks. This hook is called separately for each scale in the chart. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {Scale} args.scale - The scale. + * @param {object} options - The plugin options. + */ + afterBuildTicks?(chart: Chart, args: { scale: Scale }, options: O): void; + /** + * @desc Called after the `chart` has been laid out. Note that this hook will not + * be called if the layout update has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + */ + afterLayout?(chart: Chart, args: EmptyObject, options: O): void; + /** + * @desc Called before rendering `chart`. If any plugin returns `false`, + * the rendering is cancelled until another `render` is triggered. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + * @returns {boolean} `false` to cancel the chart rendering. + */ + beforeRender?(chart: Chart, args: { cancelable: true }, options: O): boolean | void; + /** + * @desc Called after the `chart` has been fully rendered (and animation completed). Note + * that this hook will not be called if the rendering has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + */ + afterRender?(chart: Chart, args: EmptyObject, options: O): void; + /** + * @desc Called before drawing `chart` at every animation frame. If any plugin returns `false`, + * the frame drawing is cancelled untilanother `render` is triggered. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + * @returns {boolean} `false` to cancel the chart drawing. + */ + beforeDraw?(chart: Chart, args: { cancelable: true }, options: O): boolean | void; + /** + * @desc Called after the `chart` has been drawn. Note that this hook will not be called + * if the drawing has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + */ + afterDraw?(chart: Chart, args: EmptyObject, options: O): void; + /** + * @desc Called before drawing the `chart` datasets. If any plugin returns `false`, + * the datasets drawing is cancelled until another `render` is triggered. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + * @returns {boolean} `false` to cancel the chart datasets drawing. + */ + beforeDatasetsDraw?(chart: Chart, args: { cancelable: true }, options: O): boolean | void; + /** + * @desc Called after the `chart` datasets have been drawn. Note that this hook + * will not be called if the datasets drawing has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + */ + afterDatasetsDraw?(chart: Chart, args: EmptyObject, options: O, cancelable: false): void; + /** + * @desc Called before drawing the `chart` dataset at the given `args.index` (datasets + * are drawn in the reverse order). If any plugin returns `false`, the datasets drawing + * is cancelled until another `render` is triggered. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {number} args.index - The dataset index. + * @param {object} args.meta - The dataset metadata. + * @param {object} options - The plugin options. + * @returns {boolean} `false` to cancel the chart datasets drawing. + */ + beforeDatasetDraw?(chart: Chart, args: { index: number; meta: ChartMeta }, options: O): boolean | void; + /** + * @desc Called after the `chart` datasets at the given `args.index` have been drawn + * (datasets are drawn in the reverse order). Note that this hook will not be called + * if the datasets drawing has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {number} args.index - The dataset index. + * @param {object} args.meta - The dataset metadata. + * @param {object} options - The plugin options. + */ + afterDatasetDraw?(chart: Chart, args: { index: number; meta: ChartMeta }, options: O): void; + /** + * @desc Called before processing the specified `event`. If any plugin returns `false`, + * the event will be discarded. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {ChartEvent} args.event - The event object. + * @param {boolean} args.replay - True if this event is replayed from `Chart.update` + * @param {boolean} args.inChartArea - The event position is inside chartArea + * @param {boolean} [args.changed] - Set to true if the plugin needs a render. Should only be changed to true, because this args object is passed through all plugins. + * @param {object} options - The plugin options. + */ + beforeEvent?(chart: Chart, args: { event: ChartEvent, replay: boolean, changed?: boolean; cancelable: true, inChartArea: boolean }, options: O): boolean | void; + /** + * @desc Called after the `event` has been consumed. Note that this hook + * will not be called if the `event` has been previously discarded. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {ChartEvent} args.event - The event object. + * @param {boolean} args.replay - True if this event is replayed from `Chart.update` + * @param {boolean} args.inChartArea - The event position is inside chartArea + * @param {boolean} [args.changed] - Set to true if the plugin needs a render. Should only be changed to true, because this args object is passed through all plugins. + * @param {object} options - The plugin options. + */ + afterEvent?(chart: Chart, args: { event: ChartEvent, replay: boolean, changed?: boolean, cancelable: false, inChartArea: boolean }, options: O): void; + /** + * @desc Called after the chart as been resized. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {number} args.size - The new canvas display size (eq. canvas.style width & height). + * @param {object} options - The plugin options. + */ + resize?(chart: Chart, args: { size: { width: number, height: number } }, options: O): void; + /** + * Called before the chart is being destroyed. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + */ + beforeDestroy?(chart: Chart, args: EmptyObject, options: O): void; + /** + * Called after the chart has been destroyed. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + */ + afterDestroy?(chart: Chart, args: EmptyObject, options: O): void; + /** + * Called after chart is destroyed on all plugins that were installed for that chart. This hook is also invoked for disabled plugins (options === false). + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {object} options - The plugin options. + * @since 3.0.0 + */ + uninstall?(chart: Chart, args: EmptyObject, options: O): void; + + /** + * Default options used in the plugin + */ + defaults?: Partial; +} + +export declare type ChartComponentLike = ChartComponent | ChartComponent[] | { [key: string]: ChartComponent } | Plugin | Plugin[]; + +/** + * Please use the module's default export which provides a singleton instance + * Note: class is exported for typedoc + */ +export interface Registry { + readonly controllers: TypedRegistry; + readonly elements: TypedRegistry; + readonly plugins: TypedRegistry; + readonly scales: TypedRegistry; + + add(...args: ChartComponentLike[]): void; + remove(...args: ChartComponentLike[]): void; + + addControllers(...args: ChartComponentLike[]): void; + addElements(...args: ChartComponentLike[]): void; + addPlugins(...args: ChartComponentLike[]): void; + addScales(...args: ChartComponentLike[]): void; + + getController(id: string): DatasetController | undefined; + getElement(id: string): Element | undefined; + getPlugin(id: string): Plugin | undefined; + getScale(id: string): Scale | undefined; +} + +export declare const registry: Registry; + +export interface Tick { + value: number; + label?: string | string[]; + major?: boolean; +} + +export interface CoreScaleOptions { + /** + * Controls the axis global visibility (visible when true, hidden when false). When display: 'auto', the axis is visible only if at least one associated dataset is visible. + * @default true + */ + display: boolean | 'auto'; + /** + * Align pixel values to device pixels + */ + alignToPixels: boolean; + /** + * Background color of the scale area. + */ + backgroundColor: Color; + /** + * Reverse the scale. + * @default false + */ + reverse: boolean; + /** + * Clip the dataset drawing against the size of the scale instead of chart area. + * @default true + */ + clip: boolean; + /** + * The weight used to sort the axis. Higher weights are further away from the chart area. + * @default true + */ + weight: number; + /** + * User defined minimum value for the scale, overrides minimum value from data. + */ + min: unknown; + /** + * User defined maximum value for the scale, overrides maximum value from data. + */ + max: unknown; + /** + * Adjustment used when calculating the maximum data value. + */ + suggestedMin: unknown; + /** + * Adjustment used when calculating the minimum data value. + */ + suggestedMax: unknown; + /** + * Callback called before the update process starts. + */ + beforeUpdate(axis: Scale): void; + /** + * Callback that runs before dimensions are set. + */ + beforeSetDimensions(axis: Scale): void; + /** + * Callback that runs after dimensions are set. + */ + afterSetDimensions(axis: Scale): void; + /** + * Callback that runs before data limits are determined. + */ + beforeDataLimits(axis: Scale): void; + /** + * Callback that runs after data limits are determined. + */ + afterDataLimits(axis: Scale): void; + /** + * Callback that runs before ticks are created. + */ + beforeBuildTicks(axis: Scale): void; + /** + * Callback that runs after ticks are created. Useful for filtering ticks. + */ + afterBuildTicks(axis: Scale): void; + /** + * Callback that runs before ticks are converted into strings. + */ + beforeTickToLabelConversion(axis: Scale): void; + /** + * Callback that runs after ticks are converted into strings. + */ + afterTickToLabelConversion(axis: Scale): void; + /** + * Callback that runs before tick rotation is determined. + */ + beforeCalculateLabelRotation(axis: Scale): void; + /** + * Callback that runs after tick rotation is determined. + */ + afterCalculateLabelRotation(axis: Scale): void; + /** + * Callback that runs before the scale fits to the canvas. + */ + beforeFit(axis: Scale): void; + /** + * Callback that runs after the scale fits to the canvas. + */ + afterFit(axis: Scale): void; + /** + * Callback that runs at the end of the update process. + */ + afterUpdate(axis: Scale): void; +} + +export interface Scale extends Element, LayoutItem { + readonly id: string; + readonly type: string; + readonly ctx: CanvasRenderingContext2D; + readonly chart: Chart; + + maxWidth: number; + maxHeight: number; + + paddingTop: number; + paddingBottom: number; + paddingLeft: number; + paddingRight: number; + + axis: string; + labelRotation: number; + min: number; + max: number; + ticks: Tick[]; + getMatchingVisibleMetas(type?: string): ChartMeta[]; + + drawTitle(chartArea: ChartArea): void; + drawLabels(chartArea: ChartArea): void; + drawGrid(chartArea: ChartArea): void; + + /** + * @param {number} pixel + * @return {number} + */ + getDecimalForPixel(pixel: number): number; + /** + * Utility for getting the pixel location of a percentage of scale + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @param {number} decimal + * @return {number} + */ + getPixelForDecimal(decimal: number): number; + /** + * Returns the location of the tick at the given index + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @param {number} index + * @return {number} + */ + getPixelForTick(index: number): number; + /** + * Used to get the label to display in the tooltip for the given value + * @param {*} value + * @return {string} + */ + getLabelForValue(value: number): string; + + /** + * Returns the grid line width at given value + */ + getLineWidthForValue(value: number): number; + + /** + * Returns the location of the given data point. Value can either be an index or a numerical value + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @param {*} value + * @param {number} [index] + * @return {number} + */ + getPixelForValue(value: number, index?: number): number; + + /** + * Used to get the data value from a given pixel. This is the inverse of getPixelForValue + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @param {number} pixel + * @return {*} + */ + getValueForPixel(pixel: number): number | undefined; + + getBaseValue(): number; + /** + * Returns the pixel for the minimum chart value + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @return {number} + */ + getBasePixel(): number; + + init(options: O): void; + parse(raw: unknown, index?: number): unknown; + getUserBounds(): { min: number; max: number; minDefined: boolean; maxDefined: boolean }; + getMinMax(canStack: boolean): { min: number; max: number }; + getTicks(): Tick[]; + getLabels(): string[]; + getLabelItems(chartArea?: ChartArea): LabelItem[]; + beforeUpdate(): void; + configure(): void; + afterUpdate(): void; + beforeSetDimensions(): void; + setDimensions(): void; + afterSetDimensions(): void; + beforeDataLimits(): void; + determineDataLimits(): void; + afterDataLimits(): void; + beforeBuildTicks(): void; + buildTicks(): Tick[]; + afterBuildTicks(): void; + beforeTickToLabelConversion(): void; + generateTickLabels(ticks: Tick[]): void; + afterTickToLabelConversion(): void; + beforeCalculateLabelRotation(): void; + calculateLabelRotation(): void; + afterCalculateLabelRotation(): void; + beforeFit(): void; + fit(): void; + afterFit(): void; + + isFullSize(): boolean; +} +export declare class Scale { + constructor(cfg: {id: string, type: string, ctx: CanvasRenderingContext2D, chart: Chart}); +} + +export interface ScriptableScaleContext { + chart: Chart; + scale: Scale; + index: number; + tick: Tick; +} + +export interface ScriptableScalePointLabelContext { + chart: Chart; + scale: Scale; + index: number; + label: string; + type: string; +} + +export interface RenderTextOpts { + /** + * The fill color of the text. If unset, the existing + * fillStyle property of the canvas is unchanged. + */ + color?: Color; + + /** + * The width of the strikethrough / underline + * @default 2 + */ + decorationWidth?: number; + + /** + * The max width of the text in pixels + */ + maxWidth?: number; + + /** + * A rotation to be applied to the canvas + * This is applied after the translation is applied + */ + rotation?: number; + + /** + * Apply a strikethrough effect to the text + */ + strikethrough?: boolean; + + /** + * The color of the text stroke. If unset, the existing + * strokeStyle property of the context is unchanged + */ + strokeColor?: Color; + + /** + * The text stroke width. If unset, the existing + * lineWidth property of the context is unchanged + */ + strokeWidth?: number; + + /** + * The text alignment to use. If unset, the existing + * textAlign property of the context is unchanged + */ + textAlign?: CanvasTextAlign; + + /** + * The text baseline to use. If unset, the existing + * textBaseline property of the context is unchanged + */ + textBaseline?: CanvasTextBaseline; + + /** + * If specified, a translation to apply to the context + */ + translation?: [number, number]; + + /** + * Underline the text + */ + underline?: boolean; + + /** + * Dimensions for drawing the label backdrop + */ + backdrop?: BackdropOptions; +} + +export interface BackdropOptions { + /** + * Left position of backdrop as pixel + */ + left: number; + + /** + * Top position of backdrop as pixel + */ + top: number; + + /** + * Width of backdrop in pixels + */ + width: number; + + /** + * Height of backdrop in pixels + */ + height: number; + + /** + * Color of label backdrops. + */ + color: Scriptable; +} + +export interface LabelItem { + label: string | string[]; + font: CanvasFontSpec; + textOffset: number; + options: RenderTextOpts; +} + +export declare const Ticks: { + formatters: { + /** + * Formatter for value labels + * @param value the value to display + * @return {string|string[]} the label to display + */ + values(value: unknown): string | string[]; + /** + * Formatter for numeric ticks + * @param tickValue the value to be formatted + * @param index the position of the tickValue parameter in the ticks array + * @param ticks the list of ticks being converted + * @return string representation of the tickValue parameter + */ + numeric(this: Scale, tickValue: number, index: number, ticks: { value: number }[]): string; + /** + * Formatter for logarithmic ticks + * @param tickValue the value to be formatted + * @param index the position of the tickValue parameter in the ticks array + * @param ticks the list of ticks being converted + * @return string representation of the tickValue parameter + */ + logarithmic(this: Scale, tickValue: number, index: number, ticks: { value: number }[]): string; + }; +}; + +export interface TypedRegistry { + /** + * @param {ChartComponent} item + * @returns {string} The scope where items defaults were registered to. + */ + register(item: ChartComponent): string; + get(id: string): T | undefined; + unregister(item: ChartComponent): void; +} + +export interface ChartEvent { + type: + | 'contextmenu' + | 'mouseenter' + | 'mousedown' + | 'mousemove' + | 'mouseup' + | 'mouseout' + | 'click' + | 'dblclick' + | 'keydown' + | 'keypress' + | 'keyup' + | 'resize'; + native: Event | null; + x: number | null; + y: number | null; +} +export interface ChartComponent { + id: string; + defaults?: AnyObject; + defaultRoutes?: { [property: string]: string }; + + beforeRegister?(): void; + afterRegister?(): void; + beforeUnregister?(): void; + afterUnregister?(): void; +} + +export type InteractionAxis = 'x' | 'y' | 'xy' | 'r'; + +export interface CoreInteractionOptions { + /** + * Sets which elements appear in the tooltip. See Interaction Modes for details. + * @default 'nearest' + */ + mode: InteractionMode; + /** + * if true, the hover mode only applies when the mouse position intersects an item on the chart. + * @default true + */ + intersect: boolean; + + /** + * Defines which directions are used in calculating distances. Defaults to 'x' for 'index' mode and 'xy' in dataset and 'nearest' modes. + */ + axis: InteractionAxis; + + /** + * if true, the invisible points that are outside of the chart area will also be included when evaluating interactions. + * @default false + */ + includeInvisible: boolean; +} + +export interface CoreChartOptions extends ParsingOptions, AnimationOptions { + + datasets: { + [key in ChartType]: ChartTypeRegistry[key]['datasetOptions'] + } + + /** + * The base axis of the chart. 'x' for vertical charts and 'y' for horizontal charts. + * @default 'x' + */ + indexAxis: 'x' | 'y'; + + /** + * How to clip relative to chartArea. Positive value allows overflow, negative value clips that many pixels inside chartArea. 0 = clip at chartArea. Clipping can also be configured per side: `clip: {left: 5, top: false, right: -2, bottom: 0}` + */ + clip: number | ChartArea | false; + + /** + * base color + * @see Defaults.color + */ + color: Scriptable>; + /** + * base background color + * @see Defaults.backgroundColor + */ + backgroundColor: ScriptableAndArray>; + /** + * base hover background color + * @see Defaults.hoverBackgroundColor + */ + hoverBackgroundColor: ScriptableAndArray>; + /** + * base border color + * @see Defaults.borderColor + */ + borderColor: ScriptableAndArray>; + /** + * base hover border color + * @see Defaults.hoverBorderColor + */ + hoverBorderColor: ScriptableAndArray>; + /** + * base font + * @see Defaults.font + */ + font: Partial; + /** + * Resizes the chart canvas when its container does (important note...). + * @default true + */ + responsive: boolean; + /** + * Maintain the original canvas aspect ratio (width / height) when resizing. For this option to work properly the chart must be in its own dedicated container. + * @default true + */ + maintainAspectRatio: boolean; + /** + * Delay the resize update by give amount of milliseconds. This can ease the resize process by debouncing update of the elements. + * @default 0 + */ + resizeDelay: number; + + /** + * Canvas aspect ratio (i.e. width / height, a value of 1 representing a square canvas). Note that this option is ignored if the height is explicitly defined either as attribute or via the style. + * @default 2 + */ + aspectRatio: number; + + /** + * Locale used for number formatting (using `Intl.NumberFormat`). + * @default user's browser setting + */ + locale: string; + + /** + * Called when a resize occurs. Gets passed two arguments: the chart instance and the new size. + */ + onResize(chart: Chart, size: { width: number; height: number }): void; + + /** + * Override the window's default devicePixelRatio. + * @default window.devicePixelRatio + */ + devicePixelRatio: number; + + interaction: CoreInteractionOptions; + + hover: CoreInteractionOptions; + + /** + * The events option defines the browser events that the chart should listen to for tooltips and hovering. + * @default ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'] + */ + events: (keyof HTMLElementEventMap)[] + + /** + * Called when any of the events fire. Passed the event, an array of active elements (bars, points, etc), and the chart. + */ + onHover(event: ChartEvent, elements: ActiveElement[], chart: Chart): void; + + /** + * Called if the event is of type 'mouseup' or 'click'. Passed the event, an array of active elements, and the chart. + */ + onClick(event: ChartEvent, elements: ActiveElement[], chart: Chart): void; + + layout: Partial<{ + autoPadding: boolean; + padding: Scriptable>; + }>; +} + +export type AnimationSpec = { + /** + * The number of milliseconds an animation takes. + * @default 1000 + */ + duration?: Scriptable>; + /** + * Easing function to use + * @default 'easeOutQuart' + */ + easing?: Scriptable>; + + /** + * Delay before starting the animations. + * @default 0 + */ + delay?: Scriptable>; + + /** + * If set to true, the animations loop endlessly. + * @default false + */ + loop?: Scriptable>; +} + +export type AnimationsSpec = { + [name: string]: false | AnimationSpec & { + properties: string[]; + + /** + * Type of property, determines the interpolator used. Possible values: 'number', 'color' and 'boolean'. Only really needed for 'color', because typeof does not get that right. + */ + type: 'color' | 'number' | 'boolean'; + + fn: (from: T, to: T, factor: number) => T; + + /** + * Start value for the animation. Current value is used when undefined + */ + from: Scriptable>; + /** + * + */ + to: Scriptable>; + } +} + +export type TransitionSpec = { + animation: AnimationSpec; + animations: AnimationsSpec; +} + +export type TransitionsSpec = { + [mode: string]: TransitionSpec +} + +export type AnimationOptions = { + animation: false | AnimationSpec & { + /** + * Callback called on each step of an animation. + */ + onProgress?: (this: Chart, event: AnimationEvent) => void; + /** + * Callback called when all animations are completed. + */ + onComplete?: (this: Chart, event: AnimationEvent) => void; + }; + animations: AnimationsSpec; + transitions: TransitionsSpec; +}; + +export interface FontSpec { + /** + * Default font family for all text, follows CSS font-family options. + * @default "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif" + */ + family: string; + /** + * Default font size (in px) for text. Does not apply to radialLinear scale point labels. + * @default 12 + */ + size: number; + /** + * Default font style. Does not apply to tooltip title or footer. Does not apply to chart title. Follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit) + * @default 'normal' + */ + style: 'normal' | 'italic' | 'oblique' | 'initial' | 'inherit'; + /** + * Default font weight (boldness). (see MDN). + */ + weight: 'normal' | 'bold' | 'lighter' | 'bolder' | number | null; + /** + * Height of an individual line of text (see MDN). + * @default 1.2 + */ + lineHeight: number | string; +} + +export interface CanvasFontSpec extends FontSpec { + string: string; +} + +export type TextAlign = 'left' | 'center' | 'right'; +export type Align = 'start' | 'center' | 'end'; + +export interface VisualElement { + draw(ctx: CanvasRenderingContext2D, area?: ChartArea): void; + inRange(mouseX: number, mouseY: number, useFinalPosition?: boolean): boolean; + inXRange(mouseX: number, useFinalPosition?: boolean): boolean; + inYRange(mouseY: number, useFinalPosition?: boolean): boolean; + getCenterPoint(useFinalPosition?: boolean): Point; + getRange?(axis: 'x' | 'y'): number; +} + +export interface CommonElementOptions { + borderWidth: number; + borderColor: Color; + backgroundColor: Color; +} + +export interface CommonHoverOptions { + hoverBorderWidth: number; + hoverBorderColor: Color; + hoverBackgroundColor: Color; +} + +export interface Segment { + start: number; + end: number; + loop: boolean; +} + +export interface ArcBorderRadius { + outerStart: number; + outerEnd: number; + innerStart: number; + innerEnd: number; +} + +export interface ArcOptions extends CommonElementOptions { + /** + * If true, Arc can take up 100% of a circular graph without any visual split or cut. This option doesn't support borderRadius and borderJoinStyle miter + * @default true + */ + selfJoin: boolean; + + /** + * Arc stroke alignment. + */ + borderAlign: 'center' | 'inner'; + /** + * Line dash. See MDN. + * @default [] + */ + borderDash: number[]; + /** + * Line dash offset. See MDN. + * @default 0.0 + */ + borderDashOffset: number; + /** + * Line join style. See MDN. Default is 'round' when `borderAlign` is 'inner', else 'bevel'. + */ + borderJoinStyle: CanvasLineJoin; + + /** + * Sets the border radius for arcs + * @default 0 + */ + borderRadius: number | ArcBorderRadius; + + /** + * Arc offset (in pixels). + */ + offset: number; + + /** + * If false, Arc will be flat. + * @default true + */ + circular: boolean; + + /** + * Spacing between arcs + */ + spacing: number +} + +export interface ArcHoverOptions extends CommonHoverOptions { + hoverBorderDash: number[]; + hoverBorderDashOffset: number; + hoverOffset: number; +} + +export interface LineProps { + points: Point[] +} + +export interface LineOptions extends CommonElementOptions { + /** + * Line cap style. See MDN. + * @default 'butt' + */ + borderCapStyle: CanvasLineCap; + /** + * Line dash. See MDN. + * @default [] + */ + borderDash: number[]; + /** + * Line dash offset. See MDN. + * @default 0.0 + */ + borderDashOffset: number; + /** + * Line join style. See MDN. + * @default 'miter' + */ + borderJoinStyle: CanvasLineJoin; + /** + * true to keep Bézier control inside the chart, false for no restriction. + * @default true + */ + capBezierPoints: boolean; + /** + * Interpolation mode to apply. + * @default 'default' + */ + cubicInterpolationMode: 'default' | 'monotone'; + /** + * Bézier curve tension (0 for no Bézier curves). + * @default 0 + */ + tension: number; + /** + * true to show the line as a stepped line (tension will be ignored). + * @default false + */ + stepped: 'before' | 'after' | 'middle' | boolean; + /** + * Both line and radar charts support a fill option on the dataset object which can be used to create area between two datasets or a dataset and a boundary, i.e. the scale origin, start or end + */ + fill: FillTarget | ComplexFillTarget; + /** + * If true, lines will be drawn between points with no or null data. If false, points with NaN data will create a break in the line. Can also be a number specifying the maximum gap length to span. The unit of the value depends on the scale used. + */ + spanGaps: boolean | number; + + segment: { + backgroundColor: Scriptable, + borderColor: Scriptable, + borderCapStyle: Scriptable; + borderDash: Scriptable; + borderDashOffset: Scriptable; + borderJoinStyle: Scriptable; + borderWidth: Scriptable; + }; +} + +export interface LineHoverOptions extends CommonHoverOptions { + hoverBorderCapStyle: CanvasLineCap; + hoverBorderDash: number[]; + hoverBorderDashOffset: number; + hoverBorderJoinStyle: CanvasLineJoin; +} + +export interface LineElement + extends Element, + VisualElement { + updateControlPoints(chartArea: ChartArea, indexAxis?: 'x' | 'y'): void; + points: Point[]; + readonly segments: Segment[]; + first(): Point | false; + last(): Point | false; + interpolate(point: Point, property: 'x' | 'y'): undefined | Point | Point[]; + pathSegment(ctx: CanvasRenderingContext2D, segment: Segment, params: AnyObject): undefined | boolean; + path(ctx: CanvasRenderingContext2D): boolean; +} + +export declare const LineElement: ChartComponent & { + prototype: LineElement; + new (cfg: AnyObject): LineElement; +}; + +export type PointStyle = + | 'circle' + | 'cross' + | 'crossRot' + | 'dash' + | 'line' + | 'rect' + | 'rectRounded' + | 'rectRot' + | 'star' + | 'triangle' + | false + | HTMLImageElement + | HTMLCanvasElement; + +export interface PointOptions extends CommonElementOptions { + /** + * Point radius + * @default 3 + */ + radius: number; + /** + * Extra radius added to point radius for hit detection. + * @default 1 + */ + hitRadius: number; + /** + * Point style + * @default 'circle; + */ + pointStyle: PointStyle; + /** + * Point rotation (in degrees). + * @default 0 + */ + rotation: number; + /** + * Draw the active elements over the other elements of the dataset, + * @default true + */ + drawActiveElementsOnTop: boolean; +} + +export interface PointHoverOptions extends CommonHoverOptions { + /** + * Point radius when hovered. + * @default 4 + */ + hoverRadius: number; +} + +export interface PointPrefixedOptions { + /** + * The fill color for points. + */ + pointBackgroundColor: Color; + /** + * The border color for points. + */ + pointBorderColor: Color; + /** + * The width of the point border in pixels. + */ + pointBorderWidth: number; + /** + * The pixel size of the non-displayed point that reacts to mouse events. + */ + pointHitRadius: number; + /** + * The radius of the point shape. If set to 0, the point is not rendered. + */ + pointRadius: number; + /** + * The rotation of the point in degrees. + */ + pointRotation: number; + /** + * Style of the point. + */ + pointStyle: PointStyle; +} + +export interface PointPrefixedHoverOptions { + /** + * Point background color when hovered. + */ + pointHoverBackgroundColor: Color; + /** + * Point border color when hovered. + */ + pointHoverBorderColor: Color; + /** + * Border width of point when hovered. + */ + pointHoverBorderWidth: number; + /** + * The radius of the point when hovered. + */ + pointHoverRadius: number; +} + +export interface BarProps extends Point { + base: number; + horizontal: boolean; + width: number; + height: number; +} + +export interface BarOptions extends Omit { + /** + * The base value for the bar in data units along the value axis. + */ + base: number; + + /** + * Skipped (excluded) border: 'start', 'end', 'left', 'right', 'bottom', 'top', 'middle', false (none) or true (all). + * @default 'start' + */ + borderSkipped: 'start' | 'end' | 'left' | 'right' | 'bottom' | 'top' | 'middle' | boolean; + + /** + * Border radius + * @default 0 + */ + borderRadius: number | BorderRadius; + + /** + * Amount to inflate the rectangle(s). This can be used to hide artifacts between bars. + * Unit is pixels. 'auto' translates to 0.33 pixels when barPercentage * categoryPercentage is 1, else 0. + * @default 'auto' + */ + inflateAmount: number | 'auto'; + + /** + * Width of the border, number for all sides, object to specify width for each side specifically + * @default 0 + */ + borderWidth: number | { top?: number, right?: number, bottom?: number, left?: number }; +} + +export interface BorderRadius { + topLeft: number; + topRight: number; + bottomLeft: number; + bottomRight: number; +} + +export interface BarHoverOptions extends CommonHoverOptions { + hoverBorderRadius: number | BorderRadius; +} + +export interface BarElement< + T extends BarProps = BarProps, + O extends BarOptions = BarOptions +> extends Element, VisualElement {} + +export declare const BarElement: ChartComponent & { + prototype: BarElement; + new (cfg: AnyObject): BarElement; +}; + +export interface ElementOptionsByType { + arc: ScriptableAndArrayOptions>; + bar: ScriptableAndArrayOptions>; + line: ScriptableAndArrayOptions>; + point: ScriptableAndArrayOptions>; +} + +export type ElementChartOptions = { + elements: ElementOptionsByType +}; + +export declare class BasePlatform { + /** + * Called at chart construction time, returns a context2d instance implementing + * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}. + * @param {HTMLCanvasElement} canvas - The canvas from which to acquire context (platform specific) + * @param options - The chart options + */ + acquireContext( + canvas: HTMLCanvasElement, + options?: CanvasRenderingContext2DSettings + ): CanvasRenderingContext2D | null; + /** + * Called at chart destruction time, releases any resources associated to the context + * previously returned by the acquireContext() method. + * @param {CanvasRenderingContext2D} context - The context2d instance + * @returns {boolean} true if the method succeeded, else false + */ + releaseContext(context: CanvasRenderingContext2D): boolean; + /** + * Registers the specified listener on the given chart. + * @param {Chart} chart - Chart from which to listen for event + * @param {string} type - The ({@link ChartEvent}) type to listen for + * @param listener - Receives a notification (an object that implements + * the {@link ChartEvent} interface) when an event of the specified type occurs. + */ + addEventListener(chart: Chart, type: string, listener: (e: ChartEvent) => void): void; + /** + * Removes the specified listener previously registered with addEventListener. + * @param {Chart} chart - Chart from which to remove the listener + * @param {string} type - The ({@link ChartEvent}) type to remove + * @param listener - The listener function to remove from the event target. + */ + removeEventListener(chart: Chart, type: string, listener: (e: ChartEvent) => void): void; + /** + * @returns {number} the current devicePixelRatio of the device this platform is connected to. + */ + getDevicePixelRatio(): number; + /** + * @param {HTMLCanvasElement} canvas - The canvas for which to calculate the maximum size + * @param {number} [width] - Parent element's content width + * @param {number} [height] - Parent element's content height + * @param {number} [aspectRatio] - The aspect ratio to maintain + * @returns { width: number, height: number } the maximum size available. + */ + getMaximumSize(canvas: HTMLCanvasElement, width?: number, height?: number, aspectRatio?: number): { width: number, height: number }; + /** + * @param {HTMLCanvasElement} canvas + * @returns {boolean} true if the canvas is attached to the platform, false if not. + */ + isAttached(canvas: HTMLCanvasElement): boolean; + /** + * Updates config with platform specific requirements + * @param {ChartConfiguration | ChartConfigurationCustomTypes} config + */ + updateConfig(config: ChartConfiguration | ChartConfigurationCustomTypesPerDataset): void; +} + +export declare class BasicPlatform extends BasePlatform {} +export declare class DomPlatform extends BasePlatform {} + +export declare const Decimation: Plugin; + +export declare const enum DecimationAlgorithm { + lttb = 'lttb', + minmax = 'min-max', +} +interface BaseDecimationOptions { + enabled: boolean; + threshold?: number; +} + +interface LttbDecimationOptions extends BaseDecimationOptions { + algorithm: DecimationAlgorithm.lttb | 'lttb'; + samples?: number; +} + +interface MinMaxDecimationOptions extends BaseDecimationOptions { + algorithm: DecimationAlgorithm.minmax | 'min-max'; +} + +export type DecimationOptions = LttbDecimationOptions | MinMaxDecimationOptions; + +export declare const Filler: Plugin; +export interface FillerOptions { + drawTime: 'beforeDraw' | 'beforeDatasetDraw' | 'beforeDatasetsDraw'; + propagate: boolean; +} + +export type FillTarget = number | string | { value: number } | 'start' | 'end' | 'origin' | 'stack' | 'shape' | boolean; + +export interface ComplexFillTarget { + /** + * The accepted values are the same as the filling mode values, so you may use absolute and relative dataset indexes and/or boundaries. + */ + target: FillTarget; + /** + * If no color is set, the default color will be the background color of the chart. + */ + above: Color; + /** + * Same as the above. + */ + below: Color; +} + +export interface FillerControllerDatasetOptions { + /** + * Both line and radar charts support a fill option on the dataset object which can be used to create area between two datasets or a dataset and a boundary, i.e. the scale origin, start or end + */ + fill: FillTarget | ComplexFillTarget; +} + +export declare const Legend: Plugin; + +export interface LegendItem { + /** + * Label that will be displayed + */ + text: string; + + /** + * Border radius of the legend box + * @since 3.1.0 + */ + borderRadius?: number | BorderRadius; + + /** + * Index of the associated dataset + */ + datasetIndex?: number; + + /** + * Index the associated label in the labels array + */ + index?: number + + /** + * Fill style of the legend box + */ + fillStyle?: Color; + + /** + * Font color for the text + * Defaults to LegendOptions.labels.color + */ + fontColor?: Color; + + /** + * If true, this item represents a hidden dataset. Label will be rendered with a strike-through effect + */ + hidden?: boolean; + + /** + * For box border. + * @see https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/lineCap + */ + lineCap?: CanvasLineCap; + + /** + * For box border. + * @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash + */ + lineDash?: number[]; + + /** + * For box border. + * @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset + */ + lineDashOffset?: number; + + /** + * For box border. + * @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin + */ + lineJoin?: CanvasLineJoin; + + /** + * Width of box border + */ + lineWidth?: number; + + /** + * Stroke style of the legend box + */ + strokeStyle?: Color; + + /** + * Point style of the legend box (only used if usePointStyle is true) + */ + pointStyle?: PointStyle; + + /** + * Rotation of the point in degrees (only used if usePointStyle is true) + */ + rotation?: number; + + /** + * Text alignment + */ + textAlign?: TextAlign; +} + +export interface LegendElement extends Element>, LayoutItem { + chart: Chart; + ctx: CanvasRenderingContext2D; + legendItems?: LegendItem[]; + options: LegendOptions; + fit(): void; +} + +export interface LegendOptions { + /** + * Is the legend shown? + * @default true + */ + display: boolean; + /** + * Position of the legend. + * @default 'top' + */ + position: LayoutPosition; + /** + * Alignment of the legend. + * @default 'center' + */ + align: Align; + /** + * Maximum height of the legend, in pixels + */ + maxHeight: number; + /** + * Maximum width of the legend, in pixels + */ + maxWidth: number; + /** + * Marks that this box should take the full width/height of the canvas (moving other boxes). This is unlikely to need to be changed in day-to-day use. + * @default true + */ + fullSize: boolean; + /** + * Legend will show datasets in reverse order. + * @default false + */ + reverse: boolean; + /** + * A callback that is called when a click event is registered on a label item. + */ + onClick(this: LegendElement, e: ChartEvent, legendItem: LegendItem, legend: LegendElement): void; + /** + * A callback that is called when a 'mousemove' event is registered on top of a label item + */ + onHover(this: LegendElement, e: ChartEvent, legendItem: LegendItem, legend: LegendElement): void; + /** + * A callback that is called when a 'mousemove' event is registered outside of a previously hovered label item. + */ + onLeave(this: LegendElement, e: ChartEvent, legendItem: LegendItem, legend: LegendElement): void; + + labels: { + /** + * Width of colored box. + * @default 40 + */ + boxWidth: number; + /** + * Height of the coloured box. + * @default fontSize + */ + boxHeight: number; + /** + * Color of label + * @see Defaults.color + */ + color: Color; + /** + * Font of label + * @see Defaults.font + */ + font: ScriptableAndScriptableOptions, ScriptableChartContext>; + /** + * Padding between rows of colored boxes. + * @default 10 + */ + padding: number; + /** + * If usePointStyle is true, the width of the point style used for the legend. + */ + pointStyleWidth: number; + /** + * Generates legend items for each thing in the legend. Default implementation returns the text + styling for the color box. See Legend Item for details. + */ + generateLabels(chart: Chart): LegendItem[]; + + /** + * Filters legend items out of the legend. Receives 2 parameters, a Legend Item and the chart data + */ + filter(item: LegendItem, data: ChartData): boolean; + + /** + * Sorts the legend items + */ + sort(a: LegendItem, b: LegendItem, data: ChartData): number; + + /** + * Override point style for the legend. Only applies if usePointStyle is true + */ + pointStyle: PointStyle; + + /** + * Text alignment + */ + textAlign?: TextAlign; + + /** + * Label style will match corresponding point style (size is based on the minimum value between boxWidth and font.size). + * @default false + */ + usePointStyle: boolean; + + /** + * Label borderRadius will match corresponding borderRadius. + * @default false + */ + useBorderRadius: boolean; + + /** + * Override the borderRadius to use. + * @default undefined + */ + borderRadius: number; + }; + /** + * true for rendering the legends from right to left. + */ + rtl: boolean; + /** + * This will force the text direction 'rtl' or 'ltr' on the canvas for rendering the legend, regardless of the css specified on the canvas + * @default canvas's default + */ + textDirection: string; + + title: { + /** + * Is the legend title displayed. + * @default false + */ + display: boolean; + /** + * Color of title + * @see Defaults.color + */ + color: Color; + /** + * see Fonts + */ + font: ScriptableAndScriptableOptions, ScriptableChartContext>; + position: 'center' | 'start' | 'end'; + padding?: number | ChartArea; + /** + * The string title. + */ + text: string; + }; +} + +export declare const SubTitle: Plugin; +export declare const Title: Plugin; + +export interface TitleOptions { + /** + * Alignment of the title. + * @default 'center' + */ + align: Align; + /** + * Is the title shown? + * @default false + */ + display: boolean; + /** + * Position of title + * @default 'top' + */ + position: 'top' | 'left' | 'bottom' | 'right'; + /** + * Color of text + * @see Defaults.color + */ + color: Color; + font: ScriptableAndScriptableOptions, ScriptableChartContext>; + + /** + * Marks that this box should take the full width/height of the canvas (moving other boxes). If set to `false`, places the box above/beside the + * chart area + * @default true + */ + fullSize: boolean; + /** + * Adds padding above and below the title text if a single number is specified. It is also possible to change top and bottom padding separately. + */ + padding: number | { top: number; bottom: number }; + /** + * Title text to display. If specified as an array, text is rendered on multiple lines. + */ + text: string | string[]; +} + +export type TooltipXAlignment = 'left' | 'center' | 'right'; +export type TooltipYAlignment = 'top' | 'center' | 'bottom'; +export interface TooltipLabelStyle { + borderColor: Color; + backgroundColor: Color; + + /** + * Width of border line + * @since 3.1.0 + */ + borderWidth?: number; + + /** + * Border dash + * @since 3.1.0 + */ + borderDash?: [number, number]; + + /** + * Border dash offset + * @since 3.1.0 + */ + borderDashOffset?: number; + + /** + * borderRadius + * @since 3.1.0 + */ + borderRadius?: number | BorderRadius; +} +export interface TooltipModel extends Element> { + readonly chart: Chart; + + // The items that we are rendering in the tooltip. See Tooltip Item Interface section + dataPoints: TooltipItem[]; + + // Positioning + xAlign: TooltipXAlignment; + yAlign: TooltipYAlignment; + + // X and Y properties are the top left of the tooltip + x: number; + y: number; + width: number; + height: number; + // Where the tooltip points to + caretX: number; + caretY: number; + + // Body + // The body lines that need to be rendered + // Each object contains 3 parameters + // before: string[] // lines of text before the line with the color square + // lines: string[]; // lines of text to render as the main item with color square + // after: string[]; // lines of text to render after the main lines + body: { before: string[]; lines: string[]; after: string[] }[]; + // lines of text that appear after the title but before the body + beforeBody: string[]; + // line of text that appear after the body and before the footer + afterBody: string[]; + + // Title + // lines of text that form the title + title: string[]; + + // Footer + // lines of text that form the footer + footer: string[]; + + // Styles to render for each item in body[]. This is the styling of the squares in the tooltip + labelColors: TooltipLabelStyle[]; + labelTextColors: Color[]; + labelPointStyles: { pointStyle: PointStyle; rotation: number }[]; + + // 0 opacity is a hidden tooltip + opacity: number; + + // tooltip options + options: TooltipOptions; + + getActiveElements(): ActiveElement[]; + setActiveElements(active: ActiveDataPoint[], eventPosition: Point): void; +} + +export interface TooltipPosition extends Point { + xAlign?: TooltipXAlignment; + yAlign?: TooltipYAlignment; +} + +export type TooltipPositionerFunction = ( + this: TooltipModel, + items: readonly ActiveElement[], + eventPosition: Point +) => TooltipPosition | false; + +export interface TooltipPositionerMap { + average: TooltipPositionerFunction; + nearest: TooltipPositionerFunction; +} + +export type TooltipPositioner = keyof TooltipPositionerMap; + +export interface Tooltip extends Plugin { + readonly positioners: TooltipPositionerMap; +} + +export declare const Tooltip: Tooltip; + +export interface TooltipCallbacks< + TType extends ChartType, + Model = TooltipModel, + Item = TooltipItem> { + + beforeTitle(this: Model, tooltipItems: Item[]): string | string[] | void; + title(this: Model, tooltipItems: Item[]): string | string[] | void; + afterTitle(this: Model, tooltipItems: Item[]): string | string[] | void; + + beforeBody(this: Model, tooltipItems: Item[]): string | string[] | void; + afterBody(this: Model, tooltipItems: Item[]): string | string[] | void; + + beforeLabel(this: Model, tooltipItem: Item): string | string[] | void; + label(this: Model, tooltipItem: Item): string | string[] | void; + afterLabel(this: Model, tooltipItem: Item): string | string[] | void; + + labelColor(this: Model, tooltipItem: Item): TooltipLabelStyle | void; + labelTextColor(this: Model, tooltipItem: Item): Color | void; + labelPointStyle(this: Model, tooltipItem: Item): { pointStyle: PointStyle; rotation: number } | void; + + beforeFooter(this: Model, tooltipItems: Item[]): string | string[] | void; + footer(this: Model, tooltipItems: Item[]): string | string[] | void; + afterFooter(this: Model, tooltipItems: Item[]): string | string[] | void; +} + +export interface ExtendedPlugin< + TType extends ChartType, + O = AnyObject, + Model = TooltipModel> { + /** + * @desc Called before drawing the `tooltip`. If any plugin returns `false`, + * the tooltip drawing is cancelled until another `render` is triggered. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {Tooltip} args.tooltip - The tooltip. + * @param {object} options - The plugin options. + * @returns {boolean} `false` to cancel the chart tooltip drawing. + */ + beforeTooltipDraw?(chart: Chart, args: { tooltip: Model, cancelable: true }, options: O): boolean | void; + /** + * @desc Called after drawing the `tooltip`. Note that this hook will not + * be called if the tooltip drawing has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {object} args - The call arguments. + * @param {Tooltip} args.tooltip - The tooltip. + * @param {object} options - The plugin options. + */ + afterTooltipDraw?(chart: Chart, args: { tooltip: Model }, options: O): void; +} + +export interface ScriptableTooltipContext { + chart: UnionToIntersection>; + tooltip: UnionToIntersection>; + tooltipItems: TooltipItem[]; +} + +export interface TooltipOptions extends CoreInteractionOptions { + /** + * Are on-canvas tooltips enabled? + * @default true + */ + enabled: Scriptable>; + /** + * See external tooltip section. + */ + external(this: TooltipModel, args: { chart: Chart; tooltip: TooltipModel }): void; + /** + * The mode for positioning the tooltip + */ + position: Scriptable> + + /** + * Override the tooltip alignment calculations + */ + xAlign: Scriptable>; + yAlign: Scriptable>; + + /** + * Sort tooltip items. + */ + itemSort: (a: TooltipItem, b: TooltipItem, data: ChartData) => number; + + filter: (e: TooltipItem, index: number, array: TooltipItem[], data: ChartData) => boolean; + + /** + * Background color of the tooltip. + * @default 'rgba(0, 0, 0, 0.8)' + */ + backgroundColor: Scriptable>; + /** + * Padding between the color box and the text. + * @default 1 + */ + boxPadding: number; + /** + * Color of title + * @default '#fff' + */ + titleColor: Scriptable>; + /** + * See Fonts + * @default {weight: 'bold'} + */ + titleFont: ScriptableAndScriptableOptions, ScriptableTooltipContext>; + /** + * Spacing to add to top and bottom of each title line. + * @default 2 + */ + titleSpacing: Scriptable>; + /** + * Margin to add on bottom of title section. + * @default 6 + */ + titleMarginBottom: Scriptable>; + /** + * Horizontal alignment of the title text lines. + * @default 'left' + */ + titleAlign: Scriptable>; + /** + * Spacing to add to top and bottom of each tooltip item. + * @default 2 + */ + bodySpacing: Scriptable>; + /** + * Color of body + * @default '#fff' + */ + bodyColor: Scriptable>; + /** + * See Fonts. + * @default {} + */ + bodyFont: ScriptableAndScriptableOptions, ScriptableTooltipContext>; + /** + * Horizontal alignment of the body text lines. + * @default 'left' + */ + bodyAlign: Scriptable>; + /** + * Spacing to add to top and bottom of each footer line. + * @default 2 + */ + footerSpacing: Scriptable>; + /** + * Margin to add before drawing the footer. + * @default 6 + */ + footerMarginTop: Scriptable>; + /** + * Color of footer + * @default '#fff' + */ + footerColor: Scriptable>; + /** + * See Fonts + * @default {weight: 'bold'} + */ + footerFont: ScriptableAndScriptableOptions, ScriptableTooltipContext>; + /** + * Horizontal alignment of the footer text lines. + * @default 'left' + */ + footerAlign: Scriptable>; + /** + * Padding to add to the tooltip + * @default 6 + */ + padding: Scriptable>; + /** + * Extra distance to move the end of the tooltip arrow away from the tooltip point. + * @default 2 + */ + caretPadding: Scriptable>; + /** + * Size, in px, of the tooltip arrow. + * @default 5 + */ + caretSize: Scriptable>; + /** + * Radius of tooltip corner curves. + * @default 6 + */ + cornerRadius: Scriptable>; + /** + * Color to draw behind the colored boxes when multiple items are in the tooltip. + * @default '#fff' + */ + multiKeyBackground: Scriptable>; + /** + * If true, color boxes are shown in the tooltip. + * @default true + */ + displayColors: Scriptable>; + /** + * Width of the color box if displayColors is true. + * @default bodyFont.size + */ + boxWidth: Scriptable>; + /** + * Height of the color box if displayColors is true. + * @default bodyFont.size + */ + boxHeight: Scriptable>; + /** + * Use the corresponding point style (from dataset options) instead of color boxes, ex: star, triangle etc. (size is based on the minimum value between boxWidth and boxHeight) + * @default false + */ + usePointStyle: Scriptable>; + /** + * Color of the border. + * @default 'rgba(0, 0, 0, 0)' + */ + borderColor: Scriptable>; + /** + * Size of the border. + * @default 0 + */ + borderWidth: Scriptable>; + /** + * true for rendering the legends from right to left. + */ + rtl: Scriptable>; + + /** + * This will force the text direction 'rtl' or 'ltr on the canvas for rendering the tooltips, regardless of the css specified on the canvas + * @default canvas's default + */ + textDirection: Scriptable>; + + animation: AnimationSpec | false; + animations: AnimationsSpec | false; + callbacks: TooltipCallbacks; +} + +export interface TooltipItem { + /** + * The chart the tooltip is being shown on + */ + chart: Chart; + + /** + * Label for the tooltip + */ + label: string; + + /** + * Parsed data values for the given `dataIndex` and `datasetIndex` + */ + parsed: UnionToIntersection>; + + /** + * Raw data values for the given `dataIndex` and `datasetIndex` + */ + raw: unknown; + + /** + * Formatted value for the tooltip + */ + formattedValue: string; + + /** + * The dataset the item comes from + */ + dataset: UnionToIntersection>; + + /** + * Index of the dataset the item comes from + */ + datasetIndex: number; + + /** + * Index of this data item in the dataset + */ + dataIndex: number; + + /** + * The chart element (point, arc, bar, etc.) for this tooltip item + */ + element: Element; +} + +export interface PluginOptionsByType { + colors: ColorsPluginOptions; + decimation: DecimationOptions; + filler: FillerOptions; + legend: LegendOptions; + subtitle: TitleOptions; + title: TitleOptions; + tooltip: TooltipOptions; +} +export interface PluginChartOptions { + plugins: PluginOptionsByType; +} + +export interface BorderOptions { + /** + * @default true + */ + display: boolean + /** + * @default [] + */ + dash: Scriptable; + /** + * @default 0 + */ + dashOffset: Scriptable; + color: Color; + width: number; + z: number; +} + +export interface GridLineOptions { + /** + * @default true + */ + display: boolean; + /** + * @default false + */ + circular: boolean; + /** + * @default 'rgba(0, 0, 0, 0.1)' + */ + color: ScriptableAndArray; + /** + * @default 1 + */ + lineWidth: ScriptableAndArray; + /** + * @default true + */ + drawOnChartArea: boolean; + /** + * @default true + */ + drawTicks: boolean; + /** + * @default [] + */ + tickBorderDash: Scriptable; + /** + * @default 0 + */ + tickBorderDashOffset: Scriptable; + /** + * @default 'rgba(0, 0, 0, 0.1)' + */ + tickColor: ScriptableAndArray; + /** + * @default 10 + */ + tickLength: number; + /** + * @default 1 + */ + tickWidth: number; + /** + * @default false + */ + offset: boolean; + /** + * @default 0 + */ + z: number; +} + +export interface TickOptions { + /** + * Color of label backdrops. + * @default 'rgba(255, 255, 255, 0.75)' + */ + backdropColor: Scriptable; + /** + * Padding of tick backdrop. + * @default 2 + */ + backdropPadding: number | ChartArea; + + /** + * Returns the string representation of the tick value as it should be displayed on the chart. See callback. + */ + callback: (this: Scale, tickValue: number | string, index: number, ticks: Tick[]) => string | string[] | number | number[] | null | undefined; + /** + * If true, show tick labels. + * @default true + */ + display: boolean; + /** + * Color of tick + * @see Defaults.color + */ + color: ScriptableAndArray; + /** + * see Fonts + */ + font: ScriptableAndScriptableOptions, ScriptableScaleContext>; + /** + * Sets the offset of the tick labels from the axis + */ + padding: number; + /** + * If true, draw a background behind the tick labels. + * @default false + */ + showLabelBackdrop: Scriptable; + /** + * The color of the stroke around the text. + * @default undefined + */ + textStrokeColor: Scriptable; + /** + * Stroke width around the text. + * @default 0 + */ + textStrokeWidth: Scriptable; + /** + * z-index of tick layer. Useful when ticks are drawn on chart area. Values <= 0 are drawn under datasets, > 0 on top. + * @default 0 + */ + z: number; + + major: { + /** + * If true, major ticks are generated. A major tick will affect autoskipping and major will be defined on ticks in the scriptable options context. + * @default false + */ + enabled: boolean; + }; +} + +export type CartesianTickOptions = TickOptions & { + /** + * The number of ticks to examine when deciding how many labels will fit. Setting a smaller value will be faster, but may be less accurate when there is large variability in label length. + * @default ticks.length + */ + sampleSize: number; + /** + * The label alignment + * @default 'center' + */ + align: Align | 'inner'; + /** + * If true, automatically calculates how many labels can be shown and hides labels accordingly. Labels will be rotated up to maxRotation before skipping any. Turn autoSkip off to show all labels no matter what. + * @default true + */ + autoSkip: boolean; + /** + * Padding between the ticks on the horizontal axis when autoSkip is enabled. + * @default 0 + */ + autoSkipPadding: number; + + /** + * How is the label positioned perpendicular to the axis direction. + * This only applies when the rotation is 0 and the axis position is one of "top", "left", "right", or "bottom" + * @default 'near' + */ + crossAlign: 'near' | 'center' | 'far'; + + /** + * Should the defined `min` and `max` values be presented as ticks even if they are not "nice". + * @default: true + */ + includeBounds: boolean; + + /** + * Distance in pixels to offset the label from the centre point of the tick (in the x direction for the x axis, and the y direction for the y axis). Note: this can cause labels at the edges to be cropped by the edge of the canvas + * @default 0 + */ + labelOffset: number; + + /** + * Minimum rotation for tick labels. Note: Only applicable to horizontal scales. + * @default 0 + */ + minRotation: number; + /** + * Maximum rotation for tick labels when rotating to condense labels. Note: Rotation doesn't occur until necessary. Note: Only applicable to horizontal scales. + * @default 50 + */ + maxRotation: number; + /** + * Flips tick labels around axis, displaying the labels inside the chart instead of outside. Note: Only applicable to vertical scales. + * @default false + */ + mirror: boolean; + /** + * Padding between the tick label and the axis. When set on a vertical axis, this applies in the horizontal (X) direction. When set on a horizontal axis, this applies in the vertical (Y) direction. + * @default 0 + */ + padding: number; + /** + * Maximum number of ticks and gridlines to show. + * @default 11 + */ + maxTicksLimit: number; +} + +export interface ScriptableCartesianScaleContext { + scale: keyof CartesianScaleTypeRegistry; + type: string; +} + +export interface ScriptableChartContext { + chart: Chart; + type: string; +} + +export interface CartesianScaleOptions extends CoreScaleOptions { + /** + * Scale boundary strategy (bypassed by min/max time options) + * - `data`: make sure data are fully visible, ticks outside are removed + * - `ticks`: make sure ticks are fully visible, data outside are truncated + * @since 2.7.0 + * @default 'ticks' + */ + bounds: 'ticks' | 'data'; + + /** + * Position of the axis. + */ + position: 'left' | 'top' | 'right' | 'bottom' | 'center' | { [scale: string]: number }; + + /** + * Stack group. Axes at the same `position` with same `stack` are stacked. + */ + stack?: string; + + /** + * Weight of the scale in stack group. Used to determine the amount of allocated space for the scale within the group. + * @default 1 + */ + stackWeight?: number; + + /** + * Which type of axis this is. Possible values are: 'x', 'y', 'r'. If not set, this is inferred from the first character of the ID which should be 'x', 'y' or 'r'. + */ + axis: 'x' | 'y' | 'r'; + + /** + * User defined minimum value for the scale, overrides minimum value from data. + */ + min: number; + + /** + * User defined maximum value for the scale, overrides maximum value from data. + */ + max: number; + + /** + * If true, extra space is added to the both edges and the axis is scaled to fit into the chart area. This is set to true for a bar chart by default. + * @default false + */ + offset: boolean; + + grid: Partial; + + border: BorderOptions; + + /** Options for the scale title. */ + title: { + /** If true, displays the axis title. */ + display: boolean; + /** Alignment of the axis title. */ + align: Align; + /** The text for the title, e.g. "# of People" or "Response Choices". */ + text: string | string[]; + /** Color of the axis label. */ + color: Color; + /** Information about the axis title font. */ + font: ScriptableAndScriptableOptions, ScriptableCartesianScaleContext>; + /** Padding to apply around scale labels. */ + padding: number | { + /** Padding on the (relative) top side of this axis label. */ + top: number; + /** Padding on the (relative) bottom side of this axis label. */ + bottom: number; + /** This is a shorthand for defining top/bottom to the same values. */ + y: number; + }; + }; + + /** + * If true, data will be comprised between datasets of data + * @default false + */ + stacked?: boolean | 'single'; + + ticks: CartesianTickOptions; +} + +export type CategoryScaleOptions = Omit & { + min: string | number; + max: string | number; + labels: string[] | string[][]; +}; + +export type CategoryScale = Scale +export declare const CategoryScale: ChartComponent & { + prototype: CategoryScale; + new (cfg: AnyObject): CategoryScale; +}; + +export type LinearScaleOptions = CartesianScaleOptions & { + + /** + * if true, scale will include 0 if it is not already included. + * @default true + */ + beginAtZero: boolean; + /** + * Adjustment used when calculating the minimum data value. + */ + suggestedMin?: number; + /** + * Adjustment used when calculating the maximum data value. + */ + suggestedMax?: number; + /** + * Percentage (string ending with %) or amount (number) for added room in the scale range above and below data. + */ + grace?: string | number; + + ticks: { + /** + * The Intl.NumberFormat options used by the default label formatter + */ + format: Intl.NumberFormatOptions; + + /** + * if defined and stepSize is not specified, the step size will be rounded to this many decimal places. + */ + precision: number; + + /** + * User defined fixed step size for the scale + */ + stepSize: number; + + /** + * User defined count of ticks + */ + count: number; + }; +}; + +export type LinearScale = Scale +export declare const LinearScale: ChartComponent & { + prototype: LinearScale; + new (cfg: AnyObject): LinearScale; +}; + +export type LogarithmicScaleOptions = CartesianScaleOptions & { + /** + * Adjustment used when calculating the maximum data value. + */ + suggestedMin?: number; + /** + * Adjustment used when calculating the minimum data value. + */ + suggestedMax?: number; + + ticks: { + /** + * The Intl.NumberFormat options used by the default label formatter + */ + format: Intl.NumberFormatOptions; + }; +}; + +export type LogarithmicScale = Scale +export declare const LogarithmicScale: ChartComponent & { + prototype: LogarithmicScale; + new (cfg: AnyObject): LogarithmicScale; +}; + +export type TimeScaleTimeOptions = { + /** + * Custom parser for dates. + */ + parser: string | ((v: unknown) => number); + /** + * If defined, dates will be rounded to the start of this unit. See Time Units below for the allowed units. + */ + round: false | TimeUnit; + /** + * If boolean and true and the unit is set to 'week', then the first day of the week will be Monday. Otherwise, it will be Sunday. + * If `number`, the index of the first day of the week (0 - Sunday, 6 - Saturday). + * @default false + */ + isoWeekday: boolean | number; + /** + * Sets how different time units are displayed. + */ + displayFormats: { + [key: string]: string; + }; + /** + * The format string to use for the tooltip. + */ + tooltipFormat: string; + /** + * If defined, will force the unit to be a certain type. See Time Units section below for details. + * @default false + */ + unit: false | TimeUnit; + /** + * The minimum display format to be used for a time unit. + * @default 'millisecond' + */ + minUnit: TimeUnit; +}; + +export type TimeScaleTickOptions = { + /** + * Ticks generation input values: + * - 'auto': generates "optimal" ticks based on scale size and time options. + * - 'data': generates ticks from data (including labels from data `{t|x|y}` objects). + * - 'labels': generates ticks from user given `data.labels` values ONLY. + * @see https://github.com/chartjs/Chart.js/pull/4507 + * @since 2.7.0 + * @default 'auto' + */ + source: 'labels' | 'auto' | 'data'; + /** + * The number of units between grid lines. + * @default 1 + */ + stepSize: number; +}; + +export type TimeScaleOptions = Omit & { + min: string | number; + max: string | number; + suggestedMin: string | number; + suggestedMax: string | number; + /** + * Scale boundary strategy (bypassed by min/max time options) + * - `data`: make sure data are fully visible, ticks outside are removed + * - `ticks`: make sure ticks are fully visible, data outside are truncated + * @since 2.7.0 + * @default 'data' + */ + bounds: 'ticks' | 'data'; + + /** + * If true, bar chart offsets are computed with skipped tick sizes + * @since 3.8.0 + * @default false + */ + offsetAfterAutoskip: boolean; + + /** + * options for creating a new adapter instance + */ + adapters: { + date: unknown; + }; + + time: TimeScaleTimeOptions; + + ticks: TimeScaleTickOptions; +}; + +export interface TimeScale extends Scale { + format(value: number, format?: string): string; + getDataTimestamps(): number[]; + getLabelTimestamps(): string[]; + normalize(values: number[]): number[]; +} + +export declare const TimeScale: ChartComponent & { + prototype: TimeScale; + new (cfg: AnyObject): TimeScale; +}; + +export type TimeSeriesScale = TimeScale +export declare const TimeSeriesScale: ChartComponent & { + prototype: TimeSeriesScale; + new (cfg: AnyObject): TimeSeriesScale; +}; + +export type RadialTickOptions = TickOptions & { + /** + * The Intl.NumberFormat options used by the default label formatter + */ + format: Intl.NumberFormatOptions; + + /** + * Maximum number of ticks and gridlines to show. + * @default 11 + */ + maxTicksLimit: number; + + /** + * if defined and stepSize is not specified, the step size will be rounded to this many decimal places. + */ + precision: number; + + /** + * User defined fixed step size for the scale. + */ + stepSize: number; + + /** + * User defined number of ticks + */ + count: number; +} + +export type RadialLinearScaleOptions = CoreScaleOptions & { + animate: boolean; + + startAngle: number; + + angleLines: { + /** + * if true, angle lines are shown. + * @default true + */ + display: boolean; + /** + * Color of angled lines. + * @default 'rgba(0, 0, 0, 0.1)' + */ + color: Scriptable; + /** + * Width of angled lines. + * @default 1 + */ + lineWidth: Scriptable; + /** + * Length and spacing of dashes on angled lines. See MDN. + * @default [] + */ + borderDash: Scriptable; + /** + * Offset for line dashes. See MDN. + * @default 0 + */ + borderDashOffset: Scriptable; + }; + + /** + * if true, scale will include 0 if it is not already included. + * @default false + */ + beginAtZero: boolean; + + grid: Partial; + + /** + * User defined minimum number for the scale, overrides minimum value from data. + */ + min: number; + /** + * User defined maximum number for the scale, overrides maximum value from data. + */ + max: number; + + pointLabels: { + /** + * Background color of the point label. + * @default undefined + */ + backdropColor: Scriptable; + /** + * Padding of label backdrop. + * @default 2 + */ + backdropPadding: Scriptable; + + /** + * Border radius + * @default 0 + * @since 3.8.0 + */ + borderRadius: Scriptable; + + /** + * if true, point labels are shown. When `display: 'auto'`, the label is hidden if it overlaps with another label. + * @default true + */ + display: boolean | 'auto'; + /** + * Color of label + * @see Defaults.color + */ + color: Scriptable; + /** + */ + font: ScriptableAndScriptableOptions, ScriptableScalePointLabelContext>; + + /** + * Callback function to transform data labels to point labels. The default implementation simply returns the current string. + */ + callback: (label: string, index: number) => string | string[] | number | number[]; + + /** + * Padding around the pointLabels + * @default 5 + */ + padding: Scriptable; + + /** + * if true, point labels are centered. + * @default false + */ + centerPointLabels: boolean; + }; + + /** + * Adjustment used when calculating the maximum data value. + */ + suggestedMax: number; + /** + * Adjustment used when calculating the minimum data value. + */ + suggestedMin: number; + + ticks: RadialTickOptions; +}; + +export interface RadialLinearScale extends Scale { + xCenter: number; + yCenter: number; + setCenterPoint(leftMovement: number, rightMovement: number, topMovement: number, bottomMovement: number): void; + getIndexAngle(index: number): number; + getDistanceFromCenterForValue(value: number): number; + getValueForDistanceFromCenter(distance: number): number; + getPointPosition(index: number, distanceFromCenter: number): { x: number; y: number; angle: number }; + getPointPositionForValue(index: number, value: number): { x: number; y: number; angle: number }; + getPointLabelPosition(index: number): ChartArea; + getBasePosition(index: number): { x: number; y: number; angle: number }; +} +export declare const RadialLinearScale: ChartComponent & { + prototype: RadialLinearScale; + new (cfg: AnyObject): RadialLinearScale; +}; + +export interface CartesianScaleTypeRegistry { + linear: { + options: LinearScaleOptions; + }; + logarithmic: { + options: LogarithmicScaleOptions; + }; + category: { + options: CategoryScaleOptions; + }; + time: { + options: TimeScaleOptions; + }; + timeseries: { + options: TimeScaleOptions; + }; +} + +export interface RadialScaleTypeRegistry { + radialLinear: { + options: RadialLinearScaleOptions; + }; +} + +export interface ScaleTypeRegistry extends CartesianScaleTypeRegistry, RadialScaleTypeRegistry { +} + +export type ScaleType = keyof ScaleTypeRegistry; + +export interface CartesianParsedData extends Point { + // Only specified when stacked bars are enabled + _stacks?: { + // Key is the stack ID which is generally the axis ID + [key: string]: { + // Inner key is the datasetIndex + [key: number]: number; + } + } +} + +export interface BarParsedData extends CartesianParsedData { + // Only specified if floating bars are show + _custom?: { + barStart: number; + barEnd: number; + start: number; + end: number; + min: number; + max: number; + } +} + +export interface BubbleParsedData extends CartesianParsedData { + // The bubble radius value + _custom: number; +} + +export interface RadialParsedData { + r: number; +} + +export interface ChartTypeRegistry { + bar: { + chartOptions: BarControllerChartOptions; + datasetOptions: BarControllerDatasetOptions; + defaultDataPoint: number | [number, number] | null; + metaExtensions: {}; + parsedDataType: BarParsedData, + scales: keyof CartesianScaleTypeRegistry; + }; + line: { + chartOptions: LineControllerChartOptions; + datasetOptions: LineControllerDatasetOptions & FillerControllerDatasetOptions; + defaultDataPoint: ScatterDataPoint | number | null; + metaExtensions: {}; + parsedDataType: CartesianParsedData; + scales: keyof CartesianScaleTypeRegistry; + }; + scatter: { + chartOptions: ScatterControllerChartOptions; + datasetOptions: ScatterControllerDatasetOptions; + defaultDataPoint: ScatterDataPoint | number | null; + metaExtensions: {}; + parsedDataType: CartesianParsedData; + scales: keyof CartesianScaleTypeRegistry; + }; + bubble: { + chartOptions: unknown; + datasetOptions: BubbleControllerDatasetOptions; + defaultDataPoint: BubbleDataPoint; + metaExtensions: {}; + parsedDataType: BubbleParsedData; + scales: keyof CartesianScaleTypeRegistry; + }; + pie: { + chartOptions: PieControllerChartOptions; + datasetOptions: PieControllerDatasetOptions; + defaultDataPoint: PieDataPoint; + metaExtensions: PieMetaExtensions; + parsedDataType: number; + scales: keyof CartesianScaleTypeRegistry; + }; + doughnut: { + chartOptions: DoughnutControllerChartOptions; + datasetOptions: DoughnutControllerDatasetOptions; + defaultDataPoint: DoughnutDataPoint; + metaExtensions: DoughnutMetaExtensions; + parsedDataType: number; + scales: keyof CartesianScaleTypeRegistry; + }; + polarArea: { + chartOptions: PolarAreaControllerChartOptions; + datasetOptions: PolarAreaControllerDatasetOptions; + defaultDataPoint: number; + metaExtensions: {}; + parsedDataType: RadialParsedData; + scales: keyof RadialScaleTypeRegistry; + }; + radar: { + chartOptions: RadarControllerChartOptions; + datasetOptions: RadarControllerDatasetOptions & FillerControllerDatasetOptions; + defaultDataPoint: number | null; + metaExtensions: {}; + parsedDataType: RadialParsedData; + scales: keyof RadialScaleTypeRegistry; + }; +} + +export type ChartType = keyof ChartTypeRegistry; + +export type ScaleOptionsByType = + { [key in ScaleType]: { type: key } & ScaleTypeRegistry[key]['options'] }[TScale] +; + +// Convenience alias for creating and manipulating scale options in user code +export type ScaleOptions = DeepPartial>; + +export type DatasetChartOptions = { + [key in TType]: { + datasets: ChartTypeRegistry[key]['datasetOptions']; + }; +}; + +export type ScaleChartOptions = { + scales: { + [key: string]: ScaleOptionsByType; + }; +}; + +export type ChartOptions = Exclude< +DeepPartial< +CoreChartOptions & +ElementChartOptions & +PluginChartOptions & +DatasetChartOptions & +ScaleChartOptions & +ChartTypeRegistry[TType]['chartOptions'] +>, +DeepPartial +>; + +export type DefaultDataPoint = DistributiveArray; + +export type ParsedDataType = ChartTypeRegistry[TType]['parsedDataType']; + +export interface ChartDatasetProperties { + type?: TType; + data: TData; +} + +export interface ChartDatasetPropertiesCustomTypesPerDataset { + type: TType; + data: TData; +} + +export type ChartDataset< + TType extends ChartType = ChartType, + TData = DefaultDataPoint +> = DeepPartial< +{ [key in ChartType]: { type: key } & ChartTypeRegistry[key]['datasetOptions'] }[TType] +> & ChartDatasetProperties; + +export type ChartDatasetCustomTypesPerDataset< + TType extends ChartType = ChartType, + TData = DefaultDataPoint +> = DeepPartial< +{ [key in ChartType]: { type: key } & ChartTypeRegistry[key]['datasetOptions'] }[TType] +> & ChartDatasetPropertiesCustomTypesPerDataset; + +/** + * TData represents the data point type. If unspecified, a default is provided + * based on the chart type. + * TLabel represents the label type + */ +export interface ChartData< + TType extends ChartType = ChartType, + TData = DefaultDataPoint, + TLabel = unknown +> { + labels?: TLabel[]; + xLabels?: TLabel[]; + yLabels?: TLabel[]; + datasets: ChartDataset[]; +} + +export interface ChartDataCustomTypesPerDataset< + TType extends ChartType = ChartType, + TData = DefaultDataPoint, + TLabel = unknown +> { + labels?: TLabel[]; + xLabels?: TLabel[]; + yLabels?: TLabel[]; + datasets: ChartDatasetCustomTypesPerDataset[]; +} + +export interface ChartConfiguration< + TType extends ChartType = ChartType, + TData = DefaultDataPoint, + TLabel = unknown +> { + type: TType; + data: ChartData; + options?: ChartOptions | undefined; + plugins?: Plugin[]; + platform?: typeof BasePlatform; +} + +export interface ChartConfigurationCustomTypesPerDataset< + TType extends ChartType = ChartType, + TData = DefaultDataPoint, + TLabel = unknown +> { + data: ChartDataCustomTypesPerDataset; + options?: ChartOptions | undefined; + plugins?: Plugin[]; +} diff --git a/frontend/node_modules/chart.js/dist/types/layout.d.ts b/frontend/node_modules/chart.js/dist/types/layout.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..39ddc1394b7889c137d24305d72cfcc88a7adc30 --- /dev/null +++ b/frontend/node_modules/chart.js/dist/types/layout.d.ts @@ -0,0 +1,65 @@ +import {ChartArea} from './geometric.js'; + +export type LayoutPosition = 'left' | 'top' | 'right' | 'bottom' | 'center' | 'chartArea' | {[scaleId: string]: number}; + +export interface LayoutItem { + /** + * The position of the item in the chart layout. Possible values are + */ + position: LayoutPosition; + /** + * The weight used to sort the item. Higher weights are further away from the chart area + */ + weight: number; + /** + * if true, and the item is horizontal, then push vertical boxes down + */ + fullSize: boolean; + /** + * Width of item. Must be valid after update() + */ + width: number; + /** + * Height of item. Must be valid after update() + */ + height: number; + /** + * Left edge of the item. Set by layout system and cannot be used in update + */ + left: number; + /** + * Top edge of the item. Set by layout system and cannot be used in update + */ + top: number; + /** + * Right edge of the item. Set by layout system and cannot be used in update + */ + right: number; + /** + * Bottom edge of the item. Set by layout system and cannot be used in update + */ + bottom: number; + + /** + * Called before the layout process starts + */ + beforeLayout?(): void; + /** + * Draws the element + */ + draw(chartArea: ChartArea): void; + /** + * Returns an object with padding on the edges + */ + getPadding?(): ChartArea; + /** + * returns true if the layout item is horizontal (ie. top or bottom) + */ + isHorizontal(): boolean; + /** + * Takes two parameters: width and height. + * @param width + * @param height + */ + update(width: number, height: number, margins?: ChartArea): void; +} diff --git a/frontend/node_modules/chart.js/dist/types/utils.d.ts b/frontend/node_modules/chart.js/dist/types/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..17b1cbd9f77fbffbca43fc9dc67b25ad34a06e0b --- /dev/null +++ b/frontend/node_modules/chart.js/dist/types/utils.d.ts @@ -0,0 +1,30 @@ +/* eslint-disable @typescript-eslint/ban-types */ + +// DeepPartial implementation taken from the utility-types NPM package, which is +// Copyright (c) 2016 Piotr Witek (http://piotrwitek.github.io) +// and used under the terms of the MIT license +export type DeepPartial = T extends Function + ? T + : T extends Array + ? _DeepPartialArray + : T extends object + ? _DeepPartialObject + : T | undefined; + +type _DeepPartialArray = Array> +type _DeepPartialObject = { [P in keyof T]?: DeepPartial }; + +export type DistributiveArray = [T] extends [unknown] ? Array : never + +// https://stackoverflow.com/a/50375286 +export type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never; + +export type AllKeys = T extends any ? keyof T : never; + +export type PickType> = T extends { [k in K]?: any } + ? T[K] + : undefined; + +export type Merge = { + [k in AllKeys]: PickType; +}; diff --git a/frontend/node_modules/chart.js/helpers/helpers.cjs b/frontend/node_modules/chart.js/helpers/helpers.cjs new file mode 100644 index 0000000000000000000000000000000000000000..d476848184aaeb7815ec5d2c8dd32595abe35c3f --- /dev/null +++ b/frontend/node_modules/chart.js/helpers/helpers.cjs @@ -0,0 +1 @@ +module.exports = require('../dist/helpers.cjs'); diff --git a/frontend/node_modules/chart.js/helpers/helpers.d.ts b/frontend/node_modules/chart.js/helpers/helpers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3870461f29b8a13061107100f4ccd295298437d2 --- /dev/null +++ b/frontend/node_modules/chart.js/helpers/helpers.d.ts @@ -0,0 +1 @@ +export * from '../dist/helpers/index.js'; diff --git a/frontend/node_modules/chart.js/helpers/helpers.js b/frontend/node_modules/chart.js/helpers/helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..451fa58f7396f4777c448905884eff155cc84c96 --- /dev/null +++ b/frontend/node_modules/chart.js/helpers/helpers.js @@ -0,0 +1 @@ +export * from '../dist/helpers.js'; diff --git a/frontend/node_modules/chart.js/helpers/package.json b/frontend/node_modules/chart.js/helpers/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b856155d4095b4ef805450fcb3258f0c3a097792 --- /dev/null +++ b/frontend/node_modules/chart.js/helpers/package.json @@ -0,0 +1,14 @@ +{ + "name": "chart.js-helpers", + "private": true, + "description": "Helpers package. Exists to support bundlers without exports support such as webpack 4.", + "type": "module", + "main": "./helpers.cjs", + "module": "./helpers.js", + "exports": { + "types": "./helpers.d.ts", + "import": "./helpers.js", + "require": "./helpers.cjs" + }, + "types": "./helpers.d.ts" +} diff --git a/frontend/node_modules/chart.js/package.json b/frontend/node_modules/chart.js/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7cb3b7e36c9049414bfbe645eb7a33a9d90d1a54 --- /dev/null +++ b/frontend/node_modules/chart.js/package.json @@ -0,0 +1,139 @@ +{ + "name": "chart.js", + "homepage": "https://www.chartjs.org", + "description": "Simple HTML5 charts using the canvas element.", + "version": "4.5.0", + "license": "MIT", + "type": "module", + "sideEffects": [ + "./auto/auto.js", + "./auto/auto.cjs", + "./dist/chart.umd.min.js", + "./dist/chart.umd.js" + ], + "jsdelivr": "./dist/chart.umd.min.js", + "unpkg": "./dist/chart.umd.min.js", + "main": "./dist/chart.cjs", + "module": "./dist/chart.js", + "exports": { + ".": { + "types": "./dist/types.d.ts", + "import": "./dist/chart.js", + "require": "./dist/chart.cjs" + }, + "./auto": { + "types": "./auto/auto.d.ts", + "import": "./auto/auto.js", + "require": "./auto/auto.cjs" + }, + "./helpers": { + "types": "./helpers/helpers.d.ts", + "import": "./helpers/helpers.js", + "require": "./helpers/helpers.cjs" + } + }, + "types": "./dist/types.d.ts", + "keywords": [ + "canvas", + "charts", + "data", + "graphs", + "html5", + "responsive" + ], + "repository": { + "type": "git", + "url": "https://github.com/chartjs/Chart.js.git" + }, + "bugs": { + "url": "https://github.com/chartjs/Chart.js/issues" + }, + "files": [ + "auto/**", + "dist/**", + "!dist/docs/**", + "helpers/**" + ], + "scripts": { + "autobuild": "rollup -c -w", + "copyDeclarations": "node -e \"fs.cpSync('./src/types/', './dist/types/', {recursive:true})\"", + "emitDeclarations": "tsc --emitDeclarationOnly && pnpm copyDeclarations", + "build": "rollup -c && pnpm emitDeclarations", + "dev": "karma start ./karma.conf.cjs --auto-watch --no-single-run --browsers chrome --grep", + "dev:ff": "karma start ./karma.conf.cjs --auto-watch --no-single-run --browsers firefox --grep", + "docs": "pnpm run build && pnpm --filter \"./docs/**\" build", + "docs:dev": "pnpm run build && pnpm --filter \"./docs/**\" dev", + "lint-js": "eslint \"src/**/*.{js,ts}\" \"test/**/*.js\" \"docs/**/*.js\" --cache", + "lint-md": "eslint \"**/*.md\" --cache", + "lint-types": "pnpm build && node test/types/autogen.js && tsc -p test/types", + "lint": "concurrently \"pnpm:lint-*\"", + "test": "pnpm lint && pnpm test-ci", + "test-ci": "concurrently \"pnpm:test-ci-*\"", + "test-ci-karma": "cross-env NODE_ENV=test karma start ./karma.conf.cjs --auto-watch --single-run --coverage --grep", + "test-ci-integration": "pnpm --filter \"./test/integration/**\" test" + }, + "dependencies": { + "@kurkle/color": "^0.3.0" + }, + "devDependencies": { + "@rollup/plugin-commonjs": "^23.0.2", + "@rollup/plugin-inject": "^5.0.2", + "@rollup/plugin-json": "^5.0.1", + "@rollup/plugin-node-resolve": "^15.0.1", + "@swc/core": "^1.3.18", + "@types/estree": "^1.0.0", + "@types/offscreencanvas": "^2019.7.0", + "@typescript-eslint/eslint-plugin": "^5.32.0", + "@typescript-eslint/parser": "^5.32.0", + "chartjs-adapter-luxon": "^1.2.0", + "chartjs-adapter-moment": "^1.0.0", + "chartjs-test-utils": "^0.4.0", + "concurrently": "^7.3.0", + "coveralls": "^3.1.1", + "cross-env": "^7.0.3", + "eslint": "^8.21.0", + "eslint-config-chartjs": "^0.3.0", + "eslint-plugin-es": "^4.1.0", + "eslint-plugin-html": "^7.1.0", + "eslint-plugin-markdown": "^3.0.0", + "esm": "^3.2.25", + "glob": "^8.0.3", + "jasmine": "^3.7.0", + "jasmine-core": "^3.7.1", + "karma": "^6.3.2", + "karma-chrome-launcher": "^3.1.0", + "karma-coverage": "^2.0.3", + "karma-edge-launcher": "^0.4.2", + "karma-firefox-launcher": "^2.1.0", + "karma-jasmine": "^4.0.1", + "karma-jasmine-html-reporter": "^1.5.4", + "karma-rollup-preprocessor": "7.0.7", + "karma-safari-private-launcher": "^1.0.0", + "karma-spec-reporter": "0.0.32", + "luxon": "^3.0.1", + "moment": "^2.29.4", + "moment-timezone": "^0.5.34", + "pixelmatch": "^5.3.0", + "rollup": "^3.3.0", + "rollup-plugin-cleanup": "^3.2.1", + "rollup-plugin-istanbul": "^4.0.0", + "rollup-plugin-swc3": "^0.7.0", + "rollup-plugin-terser": "^7.0.2", + "typescript": "^4.7.4", + "yargs": "^17.5.1" + }, + "engines": { + "pnpm": ">=8" + }, + "packageManager": "pnpm@8.13.0", + "pnpm": { + "overrides": { + "html-entities": "1.4.0" + }, + "peerDependencyRules": { + "ignoreMissing": [ + "chart.js" + ] + } + } +} diff --git a/frontend/node_modules/framer-motion/LICENSE.md b/frontend/node_modules/framer-motion/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..b5b8d6a89fe510535a09e575ddbf6fa112456174 --- /dev/null +++ b/frontend/node_modules/framer-motion/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018 Framer B.V. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/frontend/node_modules/framer-motion/README.md b/frontend/node_modules/framer-motion/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e3cc1c456f6eff27dfa37a5b5bfa5134e09496f3 --- /dev/null +++ b/frontend/node_modules/framer-motion/README.md @@ -0,0 +1,151 @@ + +

Motion logo
Motion for React

+

+ An open source animation library
for React +

+ +

+ npm version + npm downloads per month + jsDelivr hits (npm) + NPM License +

+ + +```bash +npm install motion +``` + +## Table of Contents + +1. [Why Motion?](#why-motion) +2. [🍦 Flavours](#-flavours) +3. [🎓 Examples](#-examples) +4. [🎨 Studio](#-studio) +5. [⚡️ Motion+](#-motion) +6. [👩🏻‍⚖️ License](#-license) +7. [💎 Contribute](#-contribute) +8. [✨ Sponsors](#-sponsors) + +## Why Motion? + +Motion is an animation library for making beautiful animations. + +* The **only** library with first‑class APIs for React, JavaScript, **and** Vue. +* Powered by a **hybrid engine** that blends JavaScript flexibility with native browser APIs for **120fps GPU‑accelerated** motion. +* Tiny footprint, tree‑shakable, and fully TypeScript‑typed. + +## 🍦 Flavours + +Motion is available for [React](https://motion.dev/docs/react), [JavaScript](https://motion.dev/docs/quick-start) and [Vue](https://motion.dev/docs/vue). + +
+React ⬇ + +```jsx +import { motion } from "motion/react" + +function Component() { + return +} +``` + +Get started with [Motion for React](https://motion.dev/docs/react). + +
+ +
+JavaScript ⬇ + +```javascript +import { animate } from "motion" + +animate("#box", { x: 100 }) +``` + +Get started with [JavaScript](https://motion.dev/docs/quick-start). + +
+ +
+Vue ⬇ + +```html + + + +``` + +Get started with [Motion for Vue](https://motion.dev/docs/vue). + +
+ +## 🎓 Examples + +[Motion Examples](https://motion.dev/examples) offers 100s of free and Motion+ examples for beginners and advanced users alike. Easy copy/paste code to kick‑start your next project. + +## ⚡️ Motion+ + +Learn, Design, Build. [Motion+](https://motion.dev/plus) is a one-time fee, lifetime update membership that provides: +- 160+ premium Motion Examples +- Motion UI features like Cursor and Ticker +- Motion Studio animation editing for VS Code `alpha` +- Early access content +- Private Discord + +[Get Motion+](https://motion.dev/plus) + +## 🎨 Studio + +![Video of bezier curve editing](https://framerusercontent.com/images/KO5dnHOUSNGb9S73p1J7nLhoFI.gif) + +Motion Studio is a versatile suite of developer tools allowing you to: + +- Visually edit CSS and Motion easing curves in VS Code +- Generate CSS springs with LLMs +- Load Motion docs into your LLM + +Get started with [Motion Studio](https://motion.dev/docs/tools-quick-start). + +## 👩🏻‍⚖️ License + +- Motion is MIT licensed. + +## 💎 Contribute + +- Want to contribute to Motion? Our [contributing guide](https://github.com/motiondivision/motion/blob/master/CONTRIBUTING.md) has you covered. + +## ✨ Sponsors + +Motion is sustainable thanks to the kind support of its sponsors. + +### Partners + +#### Framer + +Motion powers Framer animations, the web builder for creative pros. Design and ship your dream site. Zero code, maximum speed. + + + Framer + + +### Platinum + +Tailwind Linear + +### Gold + +Vercel Liveblocks Luma Emil Kowalski + +### Silver + +Frontend.fyi Firecrawl Puzzmo + +### Personal + +- [OlegWock](https://sinja.io) +- [Lambert Weller](https://github.com/l-mbert) +- [Jake LeBoeuf](https://jklb.wf) +- [Han Lee](https://github.com/hahnlee) diff --git a/frontend/node_modules/framer-motion/client/README.md b/frontend/node_modules/framer-motion/client/README.md new file mode 100644 index 0000000000000000000000000000000000000000..00af8b44d80bd72d6ad33a6d4650810d6d1f351d --- /dev/null +++ b/frontend/node_modules/framer-motion/client/README.md @@ -0,0 +1 @@ +This directory is a fallback for `exports["./client"]` in the root `framer-motion` `package.json`. diff --git a/frontend/node_modules/framer-motion/client/package.json b/frontend/node_modules/framer-motion/client/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ed702d3c3ff64cec12c6f78630aca8c2c5f5517b --- /dev/null +++ b/frontend/node_modules/framer-motion/client/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "types": "../dist/types/client.d.ts", + "main": "../dist/cjs/client.js", + "module": "../dist/es/client.mjs" +} diff --git a/frontend/node_modules/framer-motion/dist/cjs/client.js b/frontend/node_modules/framer-motion/dist/cjs/client.js new file mode 100644 index 0000000000000000000000000000000000000000..c124b90a005e40c88eac02807437cc15606c0298 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/cjs/client.js @@ -0,0 +1,369 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var featureBundle = require('./feature-bundle-PNQ-8QDo.js'); +require('react'); +require('motion-dom'); +require('motion-utils'); +require('react/jsx-runtime'); + +function createMotionComponentWithFeatures(Component, options) { + return featureBundle.createMotionComponent(Component, options, featureBundle.featureBundle, featureBundle.createDomVisualElement); +} + +/** + * HTML components + */ +const MotionA = /*@__PURE__*/ createMotionComponentWithFeatures("a"); +const MotionAbbr = /*@__PURE__*/ createMotionComponentWithFeatures("abbr"); +const MotionAddress = /*@__PURE__*/ createMotionComponentWithFeatures("address"); +const MotionArea = /*@__PURE__*/ createMotionComponentWithFeatures("area"); +const MotionArticle = /*@__PURE__*/ createMotionComponentWithFeatures("article"); +const MotionAside = /*@__PURE__*/ createMotionComponentWithFeatures("aside"); +const MotionAudio = /*@__PURE__*/ createMotionComponentWithFeatures("audio"); +const MotionB = /*@__PURE__*/ createMotionComponentWithFeatures("b"); +const MotionBase = /*@__PURE__*/ createMotionComponentWithFeatures("base"); +const MotionBdi = /*@__PURE__*/ createMotionComponentWithFeatures("bdi"); +const MotionBdo = /*@__PURE__*/ createMotionComponentWithFeatures("bdo"); +const MotionBig = /*@__PURE__*/ createMotionComponentWithFeatures("big"); +const MotionBlockquote = +/*@__PURE__*/ createMotionComponentWithFeatures("blockquote"); +const MotionBody = /*@__PURE__*/ createMotionComponentWithFeatures("body"); +const MotionButton = /*@__PURE__*/ createMotionComponentWithFeatures("button"); +const MotionCanvas = /*@__PURE__*/ createMotionComponentWithFeatures("canvas"); +const MotionCaption = /*@__PURE__*/ createMotionComponentWithFeatures("caption"); +const MotionCite = /*@__PURE__*/ createMotionComponentWithFeatures("cite"); +const MotionCode = /*@__PURE__*/ createMotionComponentWithFeatures("code"); +const MotionCol = /*@__PURE__*/ createMotionComponentWithFeatures("col"); +const MotionColgroup = /*@__PURE__*/ createMotionComponentWithFeatures("colgroup"); +const MotionData = /*@__PURE__*/ createMotionComponentWithFeatures("data"); +const MotionDatalist = /*@__PURE__*/ createMotionComponentWithFeatures("datalist"); +const MotionDd = /*@__PURE__*/ createMotionComponentWithFeatures("dd"); +const MotionDel = /*@__PURE__*/ createMotionComponentWithFeatures("del"); +const MotionDetails = /*@__PURE__*/ createMotionComponentWithFeatures("details"); +const MotionDfn = /*@__PURE__*/ createMotionComponentWithFeatures("dfn"); +const MotionDialog = /*@__PURE__*/ createMotionComponentWithFeatures("dialog"); +const MotionDiv = /*@__PURE__*/ createMotionComponentWithFeatures("div"); +const MotionDl = /*@__PURE__*/ createMotionComponentWithFeatures("dl"); +const MotionDt = /*@__PURE__*/ createMotionComponentWithFeatures("dt"); +const MotionEm = /*@__PURE__*/ createMotionComponentWithFeatures("em"); +const MotionEmbed = /*@__PURE__*/ createMotionComponentWithFeatures("embed"); +const MotionFieldset = /*@__PURE__*/ createMotionComponentWithFeatures("fieldset"); +const MotionFigcaption = +/*@__PURE__*/ createMotionComponentWithFeatures("figcaption"); +const MotionFigure = /*@__PURE__*/ createMotionComponentWithFeatures("figure"); +const MotionFooter = /*@__PURE__*/ createMotionComponentWithFeatures("footer"); +const MotionForm = /*@__PURE__*/ createMotionComponentWithFeatures("form"); +const MotionH1 = /*@__PURE__*/ createMotionComponentWithFeatures("h1"); +const MotionH2 = /*@__PURE__*/ createMotionComponentWithFeatures("h2"); +const MotionH3 = /*@__PURE__*/ createMotionComponentWithFeatures("h3"); +const MotionH4 = /*@__PURE__*/ createMotionComponentWithFeatures("h4"); +const MotionH5 = /*@__PURE__*/ createMotionComponentWithFeatures("h5"); +const MotionH6 = /*@__PURE__*/ createMotionComponentWithFeatures("h6"); +const MotionHead = /*@__PURE__*/ createMotionComponentWithFeatures("head"); +const MotionHeader = /*@__PURE__*/ createMotionComponentWithFeatures("header"); +const MotionHgroup = /*@__PURE__*/ createMotionComponentWithFeatures("hgroup"); +const MotionHr = /*@__PURE__*/ createMotionComponentWithFeatures("hr"); +const MotionHtml = /*@__PURE__*/ createMotionComponentWithFeatures("html"); +const MotionI = /*@__PURE__*/ createMotionComponentWithFeatures("i"); +const MotionIframe = /*@__PURE__*/ createMotionComponentWithFeatures("iframe"); +const MotionImg = /*@__PURE__*/ createMotionComponentWithFeatures("img"); +const MotionInput = /*@__PURE__*/ createMotionComponentWithFeatures("input"); +const MotionIns = /*@__PURE__*/ createMotionComponentWithFeatures("ins"); +const MotionKbd = /*@__PURE__*/ createMotionComponentWithFeatures("kbd"); +const MotionKeygen = /*@__PURE__*/ createMotionComponentWithFeatures("keygen"); +const MotionLabel = /*@__PURE__*/ createMotionComponentWithFeatures("label"); +const MotionLegend = /*@__PURE__*/ createMotionComponentWithFeatures("legend"); +const MotionLi = /*@__PURE__*/ createMotionComponentWithFeatures("li"); +const MotionLink = /*@__PURE__*/ createMotionComponentWithFeatures("link"); +const MotionMain = /*@__PURE__*/ createMotionComponentWithFeatures("main"); +const MotionMap = /*@__PURE__*/ createMotionComponentWithFeatures("map"); +const MotionMark = /*@__PURE__*/ createMotionComponentWithFeatures("mark"); +const MotionMenu = /*@__PURE__*/ createMotionComponentWithFeatures("menu"); +const MotionMenuitem = /*@__PURE__*/ createMotionComponentWithFeatures("menuitem"); +const MotionMeter = /*@__PURE__*/ createMotionComponentWithFeatures("meter"); +const MotionNav = /*@__PURE__*/ createMotionComponentWithFeatures("nav"); +const MotionObject = /*@__PURE__*/ createMotionComponentWithFeatures("object"); +const MotionOl = /*@__PURE__*/ createMotionComponentWithFeatures("ol"); +const MotionOptgroup = /*@__PURE__*/ createMotionComponentWithFeatures("optgroup"); +const MotionOption = /*@__PURE__*/ createMotionComponentWithFeatures("option"); +const MotionOutput = /*@__PURE__*/ createMotionComponentWithFeatures("output"); +const MotionP = /*@__PURE__*/ createMotionComponentWithFeatures("p"); +const MotionParam = /*@__PURE__*/ createMotionComponentWithFeatures("param"); +const MotionPicture = /*@__PURE__*/ createMotionComponentWithFeatures("picture"); +const MotionPre = /*@__PURE__*/ createMotionComponentWithFeatures("pre"); +const MotionProgress = /*@__PURE__*/ createMotionComponentWithFeatures("progress"); +const MotionQ = /*@__PURE__*/ createMotionComponentWithFeatures("q"); +const MotionRp = /*@__PURE__*/ createMotionComponentWithFeatures("rp"); +const MotionRt = /*@__PURE__*/ createMotionComponentWithFeatures("rt"); +const MotionRuby = /*@__PURE__*/ createMotionComponentWithFeatures("ruby"); +const MotionS = /*@__PURE__*/ createMotionComponentWithFeatures("s"); +const MotionSamp = /*@__PURE__*/ createMotionComponentWithFeatures("samp"); +const MotionScript = /*@__PURE__*/ createMotionComponentWithFeatures("script"); +const MotionSection = /*@__PURE__*/ createMotionComponentWithFeatures("section"); +const MotionSelect = /*@__PURE__*/ createMotionComponentWithFeatures("select"); +const MotionSmall = /*@__PURE__*/ createMotionComponentWithFeatures("small"); +const MotionSource = /*@__PURE__*/ createMotionComponentWithFeatures("source"); +const MotionSpan = /*@__PURE__*/ createMotionComponentWithFeatures("span"); +const MotionStrong = /*@__PURE__*/ createMotionComponentWithFeatures("strong"); +const MotionStyle = /*@__PURE__*/ createMotionComponentWithFeatures("style"); +const MotionSub = /*@__PURE__*/ createMotionComponentWithFeatures("sub"); +const MotionSummary = /*@__PURE__*/ createMotionComponentWithFeatures("summary"); +const MotionSup = /*@__PURE__*/ createMotionComponentWithFeatures("sup"); +const MotionTable = /*@__PURE__*/ createMotionComponentWithFeatures("table"); +const MotionTbody = /*@__PURE__*/ createMotionComponentWithFeatures("tbody"); +const MotionTd = /*@__PURE__*/ createMotionComponentWithFeatures("td"); +const MotionTextarea = /*@__PURE__*/ createMotionComponentWithFeatures("textarea"); +const MotionTfoot = /*@__PURE__*/ createMotionComponentWithFeatures("tfoot"); +const MotionTh = /*@__PURE__*/ createMotionComponentWithFeatures("th"); +const MotionThead = /*@__PURE__*/ createMotionComponentWithFeatures("thead"); +const MotionTime = /*@__PURE__*/ createMotionComponentWithFeatures("time"); +const MotionTitle = /*@__PURE__*/ createMotionComponentWithFeatures("title"); +const MotionTr = /*@__PURE__*/ createMotionComponentWithFeatures("tr"); +const MotionTrack = /*@__PURE__*/ createMotionComponentWithFeatures("track"); +const MotionU = /*@__PURE__*/ createMotionComponentWithFeatures("u"); +const MotionUl = /*@__PURE__*/ createMotionComponentWithFeatures("ul"); +const MotionVideo = /*@__PURE__*/ createMotionComponentWithFeatures("video"); +const MotionWbr = /*@__PURE__*/ createMotionComponentWithFeatures("wbr"); +const MotionWebview = /*@__PURE__*/ createMotionComponentWithFeatures("webview"); +/** + * SVG components + */ +const MotionAnimate = /*@__PURE__*/ createMotionComponentWithFeatures("animate"); +const MotionCircle = /*@__PURE__*/ createMotionComponentWithFeatures("circle"); +const MotionDefs = /*@__PURE__*/ createMotionComponentWithFeatures("defs"); +const MotionDesc = /*@__PURE__*/ createMotionComponentWithFeatures("desc"); +const MotionEllipse = /*@__PURE__*/ createMotionComponentWithFeatures("ellipse"); +const MotionG = /*@__PURE__*/ createMotionComponentWithFeatures("g"); +const MotionImage = /*@__PURE__*/ createMotionComponentWithFeatures("image"); +const MotionLine = /*@__PURE__*/ createMotionComponentWithFeatures("line"); +const MotionFilter = /*@__PURE__*/ createMotionComponentWithFeatures("filter"); +const MotionMarker = /*@__PURE__*/ createMotionComponentWithFeatures("marker"); +const MotionMask = /*@__PURE__*/ createMotionComponentWithFeatures("mask"); +const MotionMetadata = /*@__PURE__*/ createMotionComponentWithFeatures("metadata"); +const MotionPath = /*@__PURE__*/ createMotionComponentWithFeatures("path"); +const MotionPattern = /*@__PURE__*/ createMotionComponentWithFeatures("pattern"); +const MotionPolygon = /*@__PURE__*/ createMotionComponentWithFeatures("polygon"); +const MotionPolyline = /*@__PURE__*/ createMotionComponentWithFeatures("polyline"); +const MotionRect = /*@__PURE__*/ createMotionComponentWithFeatures("rect"); +const MotionStop = /*@__PURE__*/ createMotionComponentWithFeatures("stop"); +const MotionSvg = /*@__PURE__*/ createMotionComponentWithFeatures("svg"); +const MotionSymbol = /*@__PURE__*/ createMotionComponentWithFeatures("symbol"); +const MotionText = /*@__PURE__*/ createMotionComponentWithFeatures("text"); +const MotionTspan = /*@__PURE__*/ createMotionComponentWithFeatures("tspan"); +const MotionUse = /*@__PURE__*/ createMotionComponentWithFeatures("use"); +const MotionView = /*@__PURE__*/ createMotionComponentWithFeatures("view"); +const MotionClipPath = /*@__PURE__*/ createMotionComponentWithFeatures("clipPath"); +const MotionFeBlend = /*@__PURE__*/ createMotionComponentWithFeatures("feBlend"); +const MotionFeColorMatrix = +/*@__PURE__*/ createMotionComponentWithFeatures("feColorMatrix"); +const MotionFeComponentTransfer = /*@__PURE__*/ createMotionComponentWithFeatures("feComponentTransfer"); +const MotionFeComposite = +/*@__PURE__*/ createMotionComponentWithFeatures("feComposite"); +const MotionFeConvolveMatrix = +/*@__PURE__*/ createMotionComponentWithFeatures("feConvolveMatrix"); +const MotionFeDiffuseLighting = +/*@__PURE__*/ createMotionComponentWithFeatures("feDiffuseLighting"); +const MotionFeDisplacementMap = +/*@__PURE__*/ createMotionComponentWithFeatures("feDisplacementMap"); +const MotionFeDistantLight = +/*@__PURE__*/ createMotionComponentWithFeatures("feDistantLight"); +const MotionFeDropShadow = +/*@__PURE__*/ createMotionComponentWithFeatures("feDropShadow"); +const MotionFeFlood = /*@__PURE__*/ createMotionComponentWithFeatures("feFlood"); +const MotionFeFuncA = /*@__PURE__*/ createMotionComponentWithFeatures("feFuncA"); +const MotionFeFuncB = /*@__PURE__*/ createMotionComponentWithFeatures("feFuncB"); +const MotionFeFuncG = /*@__PURE__*/ createMotionComponentWithFeatures("feFuncG"); +const MotionFeFuncR = /*@__PURE__*/ createMotionComponentWithFeatures("feFuncR"); +const MotionFeGaussianBlur = +/*@__PURE__*/ createMotionComponentWithFeatures("feGaussianBlur"); +const MotionFeImage = /*@__PURE__*/ createMotionComponentWithFeatures("feImage"); +const MotionFeMerge = /*@__PURE__*/ createMotionComponentWithFeatures("feMerge"); +const MotionFeMergeNode = +/*@__PURE__*/ createMotionComponentWithFeatures("feMergeNode"); +const MotionFeMorphology = +/*@__PURE__*/ createMotionComponentWithFeatures("feMorphology"); +const MotionFeOffset = /*@__PURE__*/ createMotionComponentWithFeatures("feOffset"); +const MotionFePointLight = +/*@__PURE__*/ createMotionComponentWithFeatures("fePointLight"); +const MotionFeSpecularLighting = +/*@__PURE__*/ createMotionComponentWithFeatures("feSpecularLighting"); +const MotionFeSpotLight = +/*@__PURE__*/ createMotionComponentWithFeatures("feSpotLight"); +const MotionFeTile = /*@__PURE__*/ createMotionComponentWithFeatures("feTile"); +const MotionFeTurbulence = +/*@__PURE__*/ createMotionComponentWithFeatures("feTurbulence"); +const MotionForeignObject = +/*@__PURE__*/ createMotionComponentWithFeatures("foreignObject"); +const MotionLinearGradient = +/*@__PURE__*/ createMotionComponentWithFeatures("linearGradient"); +const MotionRadialGradient = +/*@__PURE__*/ createMotionComponentWithFeatures("radialGradient"); +const MotionTextPath = /*@__PURE__*/ createMotionComponentWithFeatures("textPath"); + +exports.create = featureBundle.createMotionComponent; +exports.a = MotionA; +exports.abbr = MotionAbbr; +exports.address = MotionAddress; +exports.animate = MotionAnimate; +exports.area = MotionArea; +exports.article = MotionArticle; +exports.aside = MotionAside; +exports.audio = MotionAudio; +exports.b = MotionB; +exports.base = MotionBase; +exports.bdi = MotionBdi; +exports.bdo = MotionBdo; +exports.big = MotionBig; +exports.blockquote = MotionBlockquote; +exports.body = MotionBody; +exports.button = MotionButton; +exports.canvas = MotionCanvas; +exports.caption = MotionCaption; +exports.circle = MotionCircle; +exports.cite = MotionCite; +exports.clipPath = MotionClipPath; +exports.code = MotionCode; +exports.col = MotionCol; +exports.colgroup = MotionColgroup; +exports.data = MotionData; +exports.datalist = MotionDatalist; +exports.dd = MotionDd; +exports.defs = MotionDefs; +exports.del = MotionDel; +exports.desc = MotionDesc; +exports.details = MotionDetails; +exports.dfn = MotionDfn; +exports.dialog = MotionDialog; +exports.div = MotionDiv; +exports.dl = MotionDl; +exports.dt = MotionDt; +exports.ellipse = MotionEllipse; +exports.em = MotionEm; +exports.embed = MotionEmbed; +exports.feBlend = MotionFeBlend; +exports.feColorMatrix = MotionFeColorMatrix; +exports.feComponentTransfer = MotionFeComponentTransfer; +exports.feComposite = MotionFeComposite; +exports.feConvolveMatrix = MotionFeConvolveMatrix; +exports.feDiffuseLighting = MotionFeDiffuseLighting; +exports.feDisplacementMap = MotionFeDisplacementMap; +exports.feDistantLight = MotionFeDistantLight; +exports.feDropShadow = MotionFeDropShadow; +exports.feFlood = MotionFeFlood; +exports.feFuncA = MotionFeFuncA; +exports.feFuncB = MotionFeFuncB; +exports.feFuncG = MotionFeFuncG; +exports.feFuncR = MotionFeFuncR; +exports.feGaussianBlur = MotionFeGaussianBlur; +exports.feImage = MotionFeImage; +exports.feMerge = MotionFeMerge; +exports.feMergeNode = MotionFeMergeNode; +exports.feMorphology = MotionFeMorphology; +exports.feOffset = MotionFeOffset; +exports.fePointLight = MotionFePointLight; +exports.feSpecularLighting = MotionFeSpecularLighting; +exports.feSpotLight = MotionFeSpotLight; +exports.feTile = MotionFeTile; +exports.feTurbulence = MotionFeTurbulence; +exports.fieldset = MotionFieldset; +exports.figcaption = MotionFigcaption; +exports.figure = MotionFigure; +exports.filter = MotionFilter; +exports.footer = MotionFooter; +exports.foreignObject = MotionForeignObject; +exports.form = MotionForm; +exports.g = MotionG; +exports.h1 = MotionH1; +exports.h2 = MotionH2; +exports.h3 = MotionH3; +exports.h4 = MotionH4; +exports.h5 = MotionH5; +exports.h6 = MotionH6; +exports.head = MotionHead; +exports.header = MotionHeader; +exports.hgroup = MotionHgroup; +exports.hr = MotionHr; +exports.html = MotionHtml; +exports.i = MotionI; +exports.iframe = MotionIframe; +exports.image = MotionImage; +exports.img = MotionImg; +exports.input = MotionInput; +exports.ins = MotionIns; +exports.kbd = MotionKbd; +exports.keygen = MotionKeygen; +exports.label = MotionLabel; +exports.legend = MotionLegend; +exports.li = MotionLi; +exports.line = MotionLine; +exports.linearGradient = MotionLinearGradient; +exports.link = MotionLink; +exports.main = MotionMain; +exports.map = MotionMap; +exports.mark = MotionMark; +exports.marker = MotionMarker; +exports.mask = MotionMask; +exports.menu = MotionMenu; +exports.menuitem = MotionMenuitem; +exports.metadata = MotionMetadata; +exports.meter = MotionMeter; +exports.nav = MotionNav; +exports.object = MotionObject; +exports.ol = MotionOl; +exports.optgroup = MotionOptgroup; +exports.option = MotionOption; +exports.output = MotionOutput; +exports.p = MotionP; +exports.param = MotionParam; +exports.path = MotionPath; +exports.pattern = MotionPattern; +exports.picture = MotionPicture; +exports.polygon = MotionPolygon; +exports.polyline = MotionPolyline; +exports.pre = MotionPre; +exports.progress = MotionProgress; +exports.q = MotionQ; +exports.radialGradient = MotionRadialGradient; +exports.rect = MotionRect; +exports.rp = MotionRp; +exports.rt = MotionRt; +exports.ruby = MotionRuby; +exports.s = MotionS; +exports.samp = MotionSamp; +exports.script = MotionScript; +exports.section = MotionSection; +exports.select = MotionSelect; +exports.small = MotionSmall; +exports.source = MotionSource; +exports.span = MotionSpan; +exports.stop = MotionStop; +exports.strong = MotionStrong; +exports.style = MotionStyle; +exports.sub = MotionSub; +exports.summary = MotionSummary; +exports.sup = MotionSup; +exports.svg = MotionSvg; +exports.symbol = MotionSymbol; +exports.table = MotionTable; +exports.tbody = MotionTbody; +exports.td = MotionTd; +exports.text = MotionText; +exports.textPath = MotionTextPath; +exports.textarea = MotionTextarea; +exports.tfoot = MotionTfoot; +exports.th = MotionTh; +exports.thead = MotionThead; +exports.time = MotionTime; +exports.title = MotionTitle; +exports.tr = MotionTr; +exports.track = MotionTrack; +exports.tspan = MotionTspan; +exports.u = MotionU; +exports.ul = MotionUl; +exports.use = MotionUse; +exports.video = MotionVideo; +exports.view = MotionView; +exports.wbr = MotionWbr; +exports.webview = MotionWebview; diff --git a/frontend/node_modules/framer-motion/dist/cjs/debug.js b/frontend/node_modules/framer-motion/dist/cjs/debug.js new file mode 100644 index 0000000000000000000000000000000000000000..b8eba96bcd0cdb210880f16c64b0afa12ed86ff8 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/cjs/debug.js @@ -0,0 +1,12 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var motionDom = require('motion-dom'); + + + +Object.defineProperty(exports, "recordStats", { + enumerable: true, + get: function () { return motionDom.recordStats; } +}); diff --git a/frontend/node_modules/framer-motion/dist/cjs/dom-mini.js b/frontend/node_modules/framer-motion/dist/cjs/dom-mini.js new file mode 100644 index 0000000000000000000000000000000000000000..28c57844660479d533259c2284e2e4fcf270444a --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/cjs/dom-mini.js @@ -0,0 +1,461 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var motionDom = require('motion-dom'); +var motionUtils = require('motion-utils'); + +function isDOMKeyframes(keyframes) { + return typeof keyframes === "object" && !Array.isArray(keyframes); +} + +function resolveSubjects(subject, keyframes, scope, selectorCache) { + if (typeof subject === "string" && isDOMKeyframes(keyframes)) { + return motionDom.resolveElements(subject, scope, selectorCache); + } + else if (subject instanceof NodeList) { + return Array.from(subject); + } + else if (Array.isArray(subject)) { + return subject; + } + else { + return [subject]; + } +} + +function calculateRepeatDuration(duration, repeat, _repeatDelay) { + return duration * (repeat + 1); +} + +/** + * Given a absolute or relative time definition and current/prev time state of the sequence, + * calculate an absolute time for the next keyframes. + */ +function calcNextTime(current, next, prev, labels) { + if (typeof next === "number") { + return next; + } + else if (next.startsWith("-") || next.startsWith("+")) { + return Math.max(0, current + parseFloat(next)); + } + else if (next === "<") { + return prev; + } + else if (next.startsWith("<")) { + return Math.max(0, prev + parseFloat(next.slice(1))); + } + else { + return labels.get(next) ?? current; + } +} + +function eraseKeyframes(sequence, startTime, endTime) { + for (let i = 0; i < sequence.length; i++) { + const keyframe = sequence[i]; + if (keyframe.at > startTime && keyframe.at < endTime) { + motionUtils.removeItem(sequence, keyframe); + // If we remove this item we have to push the pointer back one + i--; + } + } +} +function addKeyframes(sequence, keyframes, easing, offset, startTime, endTime) { + /** + * Erase every existing value between currentTime and targetTime, + * this will essentially splice this timeline into any currently + * defined ones. + */ + eraseKeyframes(sequence, startTime, endTime); + for (let i = 0; i < keyframes.length; i++) { + sequence.push({ + value: keyframes[i], + at: motionDom.mixNumber(startTime, endTime, offset[i]), + easing: motionUtils.getEasingForSegment(easing, i), + }); + } +} + +/** + * Take an array of times that represent repeated keyframes. For instance + * if we have original times of [0, 0.5, 1] then our repeated times will + * be [0, 0.5, 1, 1, 1.5, 2]. Loop over the times and scale them back + * down to a 0-1 scale. + */ +function normalizeTimes(times, repeat) { + for (let i = 0; i < times.length; i++) { + times[i] = times[i] / (repeat + 1); + } +} + +function compareByTime(a, b) { + if (a.at === b.at) { + if (a.value === null) + return 1; + if (b.value === null) + return -1; + return 0; + } + else { + return a.at - b.at; + } +} + +const defaultSegmentEasing = "easeInOut"; +const MAX_REPEAT = 20; +function createAnimationsFromSequence(sequence, { defaultTransition = {}, ...sequenceTransition } = {}, scope, generators) { + const defaultDuration = defaultTransition.duration || 0.3; + const animationDefinitions = new Map(); + const sequences = new Map(); + const elementCache = {}; + const timeLabels = new Map(); + let prevTime = 0; + let currentTime = 0; + let totalDuration = 0; + /** + * Build the timeline by mapping over the sequence array and converting + * the definitions into keyframes and offsets with absolute time values. + * These will later get converted into relative offsets in a second pass. + */ + for (let i = 0; i < sequence.length; i++) { + const segment = sequence[i]; + /** + * If this is a timeline label, mark it and skip the rest of this iteration. + */ + if (typeof segment === "string") { + timeLabels.set(segment, currentTime); + continue; + } + else if (!Array.isArray(segment)) { + timeLabels.set(segment.name, calcNextTime(currentTime, segment.at, prevTime, timeLabels)); + continue; + } + let [subject, keyframes, transition = {}] = segment; + /** + * If a relative or absolute time value has been specified we need to resolve + * it in relation to the currentTime. + */ + if (transition.at !== undefined) { + currentTime = calcNextTime(currentTime, transition.at, prevTime, timeLabels); + } + /** + * Keep track of the maximum duration in this definition. This will be + * applied to currentTime once the definition has been parsed. + */ + let maxDuration = 0; + const resolveValueSequence = (valueKeyframes, valueTransition, valueSequence, elementIndex = 0, numSubjects = 0) => { + const valueKeyframesAsList = keyframesAsList(valueKeyframes); + const { delay = 0, times = motionDom.defaultOffset(valueKeyframesAsList), type = "keyframes", repeat, repeatType, repeatDelay = 0, ...remainingTransition } = valueTransition; + let { ease = defaultTransition.ease || "easeOut", duration } = valueTransition; + /** + * Resolve stagger() if defined. + */ + const calculatedDelay = typeof delay === "function" + ? delay(elementIndex, numSubjects) + : delay; + /** + * If this animation should and can use a spring, generate a spring easing function. + */ + const numKeyframes = valueKeyframesAsList.length; + const createGenerator = motionDom.isGenerator(type) + ? type + : generators?.[type || "keyframes"]; + if (numKeyframes <= 2 && createGenerator) { + /** + * As we're creating an easing function from a spring, + * ideally we want to generate it using the real distance + * between the two keyframes. However this isn't always + * possible - in these situations we use 0-100. + */ + let absoluteDelta = 100; + if (numKeyframes === 2 && + isNumberKeyframesArray(valueKeyframesAsList)) { + const delta = valueKeyframesAsList[1] - valueKeyframesAsList[0]; + absoluteDelta = Math.abs(delta); + } + const springTransition = { ...remainingTransition }; + if (duration !== undefined) { + springTransition.duration = motionUtils.secondsToMilliseconds(duration); + } + const springEasing = motionDom.createGeneratorEasing(springTransition, absoluteDelta, createGenerator); + ease = springEasing.ease; + duration = springEasing.duration; + } + duration ?? (duration = defaultDuration); + const startTime = currentTime + calculatedDelay; + /** + * If there's only one time offset of 0, fill in a second with length 1 + */ + if (times.length === 1 && times[0] === 0) { + times[1] = 1; + } + /** + * Fill out if offset if fewer offsets than keyframes + */ + const remainder = times.length - valueKeyframesAsList.length; + remainder > 0 && motionDom.fillOffset(times, remainder); + /** + * If only one value has been set, ie [1], push a null to the start of + * the keyframe array. This will let us mark a keyframe at this point + * that will later be hydrated with the previous value. + */ + valueKeyframesAsList.length === 1 && + valueKeyframesAsList.unshift(null); + /** + * Handle repeat options + */ + if (repeat) { + motionUtils.invariant(repeat < MAX_REPEAT, "Repeat count too high, must be less than 20", "repeat-count-high"); + duration = calculateRepeatDuration(duration, repeat); + const originalKeyframes = [...valueKeyframesAsList]; + const originalTimes = [...times]; + ease = Array.isArray(ease) ? [...ease] : [ease]; + const originalEase = [...ease]; + for (let repeatIndex = 0; repeatIndex < repeat; repeatIndex++) { + valueKeyframesAsList.push(...originalKeyframes); + for (let keyframeIndex = 0; keyframeIndex < originalKeyframes.length; keyframeIndex++) { + times.push(originalTimes[keyframeIndex] + (repeatIndex + 1)); + ease.push(keyframeIndex === 0 + ? "linear" + : motionUtils.getEasingForSegment(originalEase, keyframeIndex - 1)); + } + } + normalizeTimes(times, repeat); + } + const targetTime = startTime + duration; + /** + * Add keyframes, mapping offsets to absolute time. + */ + addKeyframes(valueSequence, valueKeyframesAsList, ease, times, startTime, targetTime); + maxDuration = Math.max(calculatedDelay + duration, maxDuration); + totalDuration = Math.max(targetTime, totalDuration); + }; + if (motionDom.isMotionValue(subject)) { + const subjectSequence = getSubjectSequence(subject, sequences); + resolveValueSequence(keyframes, transition, getValueSequence("default", subjectSequence)); + } + else { + const subjects = resolveSubjects(subject, keyframes, scope, elementCache); + const numSubjects = subjects.length; + /** + * For every element in this segment, process the defined values. + */ + for (let subjectIndex = 0; subjectIndex < numSubjects; subjectIndex++) { + /** + * Cast necessary, but we know these are of this type + */ + keyframes = keyframes; + transition = transition; + const thisSubject = subjects[subjectIndex]; + const subjectSequence = getSubjectSequence(thisSubject, sequences); + for (const key in keyframes) { + resolveValueSequence(keyframes[key], getValueTransition(transition, key), getValueSequence(key, subjectSequence), subjectIndex, numSubjects); + } + } + } + prevTime = currentTime; + currentTime += maxDuration; + } + /** + * For every element and value combination create a new animation. + */ + sequences.forEach((valueSequences, element) => { + for (const key in valueSequences) { + const valueSequence = valueSequences[key]; + /** + * Arrange all the keyframes in ascending time order. + */ + valueSequence.sort(compareByTime); + const keyframes = []; + const valueOffset = []; + const valueEasing = []; + /** + * For each keyframe, translate absolute times into + * relative offsets based on the total duration of the timeline. + */ + for (let i = 0; i < valueSequence.length; i++) { + const { at, value, easing } = valueSequence[i]; + keyframes.push(value); + valueOffset.push(motionUtils.progress(0, totalDuration, at)); + valueEasing.push(easing || "easeOut"); + } + /** + * If the first keyframe doesn't land on offset: 0 + * provide one by duplicating the initial keyframe. This ensures + * it snaps to the first keyframe when the animation starts. + */ + if (valueOffset[0] !== 0) { + valueOffset.unshift(0); + keyframes.unshift(keyframes[0]); + valueEasing.unshift(defaultSegmentEasing); + } + /** + * If the last keyframe doesn't land on offset: 1 + * provide one with a null wildcard value. This will ensure it + * stays static until the end of the animation. + */ + if (valueOffset[valueOffset.length - 1] !== 1) { + valueOffset.push(1); + keyframes.push(null); + } + if (!animationDefinitions.has(element)) { + animationDefinitions.set(element, { + keyframes: {}, + transition: {}, + }); + } + const definition = animationDefinitions.get(element); + definition.keyframes[key] = keyframes; + definition.transition[key] = { + ...defaultTransition, + duration: totalDuration, + ease: valueEasing, + times: valueOffset, + ...sequenceTransition, + }; + } + }); + return animationDefinitions; +} +function getSubjectSequence(subject, sequences) { + !sequences.has(subject) && sequences.set(subject, {}); + return sequences.get(subject); +} +function getValueSequence(name, sequences) { + if (!sequences[name]) + sequences[name] = []; + return sequences[name]; +} +function keyframesAsList(keyframes) { + return Array.isArray(keyframes) ? keyframes : [keyframes]; +} +function getValueTransition(transition, key) { + return transition && transition[key] + ? { + ...transition, + ...transition[key], + } + : { ...transition }; +} +const isNumber = (keyframe) => typeof keyframe === "number"; +const isNumberKeyframesArray = (keyframes) => keyframes.every(isNumber); + +function animateElements(elementOrSelector, keyframes, options, scope) { + const elements = motionDom.resolveElements(elementOrSelector, scope); + const numElements = elements.length; + motionUtils.invariant(Boolean(numElements), "No valid elements provided.", "no-valid-elements"); + /** + * WAAPI doesn't support interrupting animations. + * + * Therefore, starting animations requires a three-step process: + * 1. Stop existing animations (write styles to DOM) + * 2. Resolve keyframes (read styles from DOM) + * 3. Create new animations (write styles to DOM) + * + * The hybrid `animate()` function uses AsyncAnimation to resolve + * keyframes before creating new animations, which removes style + * thrashing. Here, we have much stricter filesize constraints. + * Therefore we do this in a synchronous way that ensures that + * at least within `animate()` calls there is no style thrashing. + * + * In the motion-native-animate-mini-interrupt benchmark this + * was 80% faster than a single loop. + */ + const animationDefinitions = []; + /** + * Step 1: Build options and stop existing animations (write) + */ + for (let i = 0; i < numElements; i++) { + const element = elements[i]; + const elementTransition = { ...options }; + /** + * Resolve stagger function if provided. + */ + if (typeof elementTransition.delay === "function") { + elementTransition.delay = elementTransition.delay(i, numElements); + } + for (const valueName in keyframes) { + let valueKeyframes = keyframes[valueName]; + if (!Array.isArray(valueKeyframes)) { + valueKeyframes = [valueKeyframes]; + } + const valueOptions = { + ...motionDom.getValueTransition(elementTransition, valueName), + }; + valueOptions.duration && (valueOptions.duration = motionUtils.secondsToMilliseconds(valueOptions.duration)); + valueOptions.delay && (valueOptions.delay = motionUtils.secondsToMilliseconds(valueOptions.delay)); + /** + * If there's an existing animation playing on this element then stop it + * before creating a new one. + */ + const map = motionDom.getAnimationMap(element); + const key = motionDom.animationMapKey(valueName, valueOptions.pseudoElement || ""); + const currentAnimation = map.get(key); + currentAnimation && currentAnimation.stop(); + animationDefinitions.push({ + map, + key, + unresolvedKeyframes: valueKeyframes, + options: { + ...valueOptions, + element, + name: valueName, + allowFlatten: !elementTransition.type && !elementTransition.ease, + }, + }); + } + } + /** + * Step 2: Resolve keyframes (read) + */ + for (let i = 0; i < animationDefinitions.length; i++) { + const { unresolvedKeyframes, options: animationOptions } = animationDefinitions[i]; + const { element, name, pseudoElement } = animationOptions; + if (!pseudoElement && unresolvedKeyframes[0] === null) { + unresolvedKeyframes[0] = motionDom.getComputedStyle(element, name); + } + motionDom.fillWildcards(unresolvedKeyframes); + motionDom.applyPxDefaults(unresolvedKeyframes, name); + /** + * If we only have one keyframe, explicitly read the initial keyframe + * from the computed style. This is to ensure consistency with WAAPI behaviour + * for restarting animations, for instance .play() after finish, when it + * has one vs two keyframes. + */ + if (!pseudoElement && unresolvedKeyframes.length < 2) { + unresolvedKeyframes.unshift(motionDom.getComputedStyle(element, name)); + } + animationOptions.keyframes = unresolvedKeyframes; + } + /** + * Step 3: Create new animations (write) + */ + const animations = []; + for (let i = 0; i < animationDefinitions.length; i++) { + const { map, key, options: animationOptions } = animationDefinitions[i]; + const animation = new motionDom.NativeAnimation(animationOptions); + map.set(key, animation); + animation.finished.finally(() => map.delete(key)); + animations.push(animation); + } + return animations; +} + +function animateSequence(definition, options) { + const animations = []; + createAnimationsFromSequence(definition, options).forEach(({ keyframes, transition }, element) => { + animations.push(...animateElements(element, keyframes, transition)); + }); + return new motionDom.GroupAnimationWithThen(animations); +} + +const createScopedWaapiAnimate = (scope) => { + function scopedAnimate(elementOrSelector, keyframes, options) { + return new motionDom.GroupAnimationWithThen(animateElements(elementOrSelector, keyframes, options, scope)); + } + return scopedAnimate; +}; +const animateMini = /*@__PURE__*/ createScopedWaapiAnimate(); + +exports.animate = animateMini; +exports.animateSequence = animateSequence; diff --git a/frontend/node_modules/framer-motion/dist/cjs/dom.js b/frontend/node_modules/framer-motion/dist/cjs/dom.js new file mode 100644 index 0000000000000000000000000000000000000000..6d83538628cf88ddaa4479e0977e1565e74ec13a --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/cjs/dom.js @@ -0,0 +1,2482 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var motionDom = require('motion-dom'); +var motionUtils = require('motion-utils'); + +function isDOMKeyframes(keyframes) { + return typeof keyframes === "object" && !Array.isArray(keyframes); +} + +function resolveSubjects(subject, keyframes, scope, selectorCache) { + if (typeof subject === "string" && isDOMKeyframes(keyframes)) { + return motionDom.resolveElements(subject, scope, selectorCache); + } + else if (subject instanceof NodeList) { + return Array.from(subject); + } + else if (Array.isArray(subject)) { + return subject; + } + else { + return [subject]; + } +} + +function calculateRepeatDuration(duration, repeat, _repeatDelay) { + return duration * (repeat + 1); +} + +/** + * Given a absolute or relative time definition and current/prev time state of the sequence, + * calculate an absolute time for the next keyframes. + */ +function calcNextTime(current, next, prev, labels) { + if (typeof next === "number") { + return next; + } + else if (next.startsWith("-") || next.startsWith("+")) { + return Math.max(0, current + parseFloat(next)); + } + else if (next === "<") { + return prev; + } + else if (next.startsWith("<")) { + return Math.max(0, prev + parseFloat(next.slice(1))); + } + else { + return labels.get(next) ?? current; + } +} + +function eraseKeyframes(sequence, startTime, endTime) { + for (let i = 0; i < sequence.length; i++) { + const keyframe = sequence[i]; + if (keyframe.at > startTime && keyframe.at < endTime) { + motionUtils.removeItem(sequence, keyframe); + // If we remove this item we have to push the pointer back one + i--; + } + } +} +function addKeyframes(sequence, keyframes, easing, offset, startTime, endTime) { + /** + * Erase every existing value between currentTime and targetTime, + * this will essentially splice this timeline into any currently + * defined ones. + */ + eraseKeyframes(sequence, startTime, endTime); + for (let i = 0; i < keyframes.length; i++) { + sequence.push({ + value: keyframes[i], + at: motionDom.mixNumber(startTime, endTime, offset[i]), + easing: motionUtils.getEasingForSegment(easing, i), + }); + } +} + +/** + * Take an array of times that represent repeated keyframes. For instance + * if we have original times of [0, 0.5, 1] then our repeated times will + * be [0, 0.5, 1, 1, 1.5, 2]. Loop over the times and scale them back + * down to a 0-1 scale. + */ +function normalizeTimes(times, repeat) { + for (let i = 0; i < times.length; i++) { + times[i] = times[i] / (repeat + 1); + } +} + +function compareByTime(a, b) { + if (a.at === b.at) { + if (a.value === null) + return 1; + if (b.value === null) + return -1; + return 0; + } + else { + return a.at - b.at; + } +} + +const defaultSegmentEasing = "easeInOut"; +const MAX_REPEAT = 20; +function createAnimationsFromSequence(sequence, { defaultTransition = {}, ...sequenceTransition } = {}, scope, generators) { + const defaultDuration = defaultTransition.duration || 0.3; + const animationDefinitions = new Map(); + const sequences = new Map(); + const elementCache = {}; + const timeLabels = new Map(); + let prevTime = 0; + let currentTime = 0; + let totalDuration = 0; + /** + * Build the timeline by mapping over the sequence array and converting + * the definitions into keyframes and offsets with absolute time values. + * These will later get converted into relative offsets in a second pass. + */ + for (let i = 0; i < sequence.length; i++) { + const segment = sequence[i]; + /** + * If this is a timeline label, mark it and skip the rest of this iteration. + */ + if (typeof segment === "string") { + timeLabels.set(segment, currentTime); + continue; + } + else if (!Array.isArray(segment)) { + timeLabels.set(segment.name, calcNextTime(currentTime, segment.at, prevTime, timeLabels)); + continue; + } + let [subject, keyframes, transition = {}] = segment; + /** + * If a relative or absolute time value has been specified we need to resolve + * it in relation to the currentTime. + */ + if (transition.at !== undefined) { + currentTime = calcNextTime(currentTime, transition.at, prevTime, timeLabels); + } + /** + * Keep track of the maximum duration in this definition. This will be + * applied to currentTime once the definition has been parsed. + */ + let maxDuration = 0; + const resolveValueSequence = (valueKeyframes, valueTransition, valueSequence, elementIndex = 0, numSubjects = 0) => { + const valueKeyframesAsList = keyframesAsList(valueKeyframes); + const { delay = 0, times = motionDom.defaultOffset(valueKeyframesAsList), type = "keyframes", repeat, repeatType, repeatDelay = 0, ...remainingTransition } = valueTransition; + let { ease = defaultTransition.ease || "easeOut", duration } = valueTransition; + /** + * Resolve stagger() if defined. + */ + const calculatedDelay = typeof delay === "function" + ? delay(elementIndex, numSubjects) + : delay; + /** + * If this animation should and can use a spring, generate a spring easing function. + */ + const numKeyframes = valueKeyframesAsList.length; + const createGenerator = motionDom.isGenerator(type) + ? type + : generators?.[type || "keyframes"]; + if (numKeyframes <= 2 && createGenerator) { + /** + * As we're creating an easing function from a spring, + * ideally we want to generate it using the real distance + * between the two keyframes. However this isn't always + * possible - in these situations we use 0-100. + */ + let absoluteDelta = 100; + if (numKeyframes === 2 && + isNumberKeyframesArray(valueKeyframesAsList)) { + const delta = valueKeyframesAsList[1] - valueKeyframesAsList[0]; + absoluteDelta = Math.abs(delta); + } + const springTransition = { ...remainingTransition }; + if (duration !== undefined) { + springTransition.duration = motionUtils.secondsToMilliseconds(duration); + } + const springEasing = motionDom.createGeneratorEasing(springTransition, absoluteDelta, createGenerator); + ease = springEasing.ease; + duration = springEasing.duration; + } + duration ?? (duration = defaultDuration); + const startTime = currentTime + calculatedDelay; + /** + * If there's only one time offset of 0, fill in a second with length 1 + */ + if (times.length === 1 && times[0] === 0) { + times[1] = 1; + } + /** + * Fill out if offset if fewer offsets than keyframes + */ + const remainder = times.length - valueKeyframesAsList.length; + remainder > 0 && motionDom.fillOffset(times, remainder); + /** + * If only one value has been set, ie [1], push a null to the start of + * the keyframe array. This will let us mark a keyframe at this point + * that will later be hydrated with the previous value. + */ + valueKeyframesAsList.length === 1 && + valueKeyframesAsList.unshift(null); + /** + * Handle repeat options + */ + if (repeat) { + motionUtils.invariant(repeat < MAX_REPEAT, "Repeat count too high, must be less than 20", "repeat-count-high"); + duration = calculateRepeatDuration(duration, repeat); + const originalKeyframes = [...valueKeyframesAsList]; + const originalTimes = [...times]; + ease = Array.isArray(ease) ? [...ease] : [ease]; + const originalEase = [...ease]; + for (let repeatIndex = 0; repeatIndex < repeat; repeatIndex++) { + valueKeyframesAsList.push(...originalKeyframes); + for (let keyframeIndex = 0; keyframeIndex < originalKeyframes.length; keyframeIndex++) { + times.push(originalTimes[keyframeIndex] + (repeatIndex + 1)); + ease.push(keyframeIndex === 0 + ? "linear" + : motionUtils.getEasingForSegment(originalEase, keyframeIndex - 1)); + } + } + normalizeTimes(times, repeat); + } + const targetTime = startTime + duration; + /** + * Add keyframes, mapping offsets to absolute time. + */ + addKeyframes(valueSequence, valueKeyframesAsList, ease, times, startTime, targetTime); + maxDuration = Math.max(calculatedDelay + duration, maxDuration); + totalDuration = Math.max(targetTime, totalDuration); + }; + if (motionDom.isMotionValue(subject)) { + const subjectSequence = getSubjectSequence(subject, sequences); + resolveValueSequence(keyframes, transition, getValueSequence("default", subjectSequence)); + } + else { + const subjects = resolveSubjects(subject, keyframes, scope, elementCache); + const numSubjects = subjects.length; + /** + * For every element in this segment, process the defined values. + */ + for (let subjectIndex = 0; subjectIndex < numSubjects; subjectIndex++) { + /** + * Cast necessary, but we know these are of this type + */ + keyframes = keyframes; + transition = transition; + const thisSubject = subjects[subjectIndex]; + const subjectSequence = getSubjectSequence(thisSubject, sequences); + for (const key in keyframes) { + resolveValueSequence(keyframes[key], getValueTransition(transition, key), getValueSequence(key, subjectSequence), subjectIndex, numSubjects); + } + } + } + prevTime = currentTime; + currentTime += maxDuration; + } + /** + * For every element and value combination create a new animation. + */ + sequences.forEach((valueSequences, element) => { + for (const key in valueSequences) { + const valueSequence = valueSequences[key]; + /** + * Arrange all the keyframes in ascending time order. + */ + valueSequence.sort(compareByTime); + const keyframes = []; + const valueOffset = []; + const valueEasing = []; + /** + * For each keyframe, translate absolute times into + * relative offsets based on the total duration of the timeline. + */ + for (let i = 0; i < valueSequence.length; i++) { + const { at, value, easing } = valueSequence[i]; + keyframes.push(value); + valueOffset.push(motionUtils.progress(0, totalDuration, at)); + valueEasing.push(easing || "easeOut"); + } + /** + * If the first keyframe doesn't land on offset: 0 + * provide one by duplicating the initial keyframe. This ensures + * it snaps to the first keyframe when the animation starts. + */ + if (valueOffset[0] !== 0) { + valueOffset.unshift(0); + keyframes.unshift(keyframes[0]); + valueEasing.unshift(defaultSegmentEasing); + } + /** + * If the last keyframe doesn't land on offset: 1 + * provide one with a null wildcard value. This will ensure it + * stays static until the end of the animation. + */ + if (valueOffset[valueOffset.length - 1] !== 1) { + valueOffset.push(1); + keyframes.push(null); + } + if (!animationDefinitions.has(element)) { + animationDefinitions.set(element, { + keyframes: {}, + transition: {}, + }); + } + const definition = animationDefinitions.get(element); + definition.keyframes[key] = keyframes; + definition.transition[key] = { + ...defaultTransition, + duration: totalDuration, + ease: valueEasing, + times: valueOffset, + ...sequenceTransition, + }; + } + }); + return animationDefinitions; +} +function getSubjectSequence(subject, sequences) { + !sequences.has(subject) && sequences.set(subject, {}); + return sequences.get(subject); +} +function getValueSequence(name, sequences) { + if (!sequences[name]) + sequences[name] = []; + return sequences[name]; +} +function keyframesAsList(keyframes) { + return Array.isArray(keyframes) ? keyframes : [keyframes]; +} +function getValueTransition(transition, key) { + return transition && transition[key] + ? { + ...transition, + ...transition[key], + } + : { ...transition }; +} +const isNumber = (keyframe) => typeof keyframe === "number"; +const isNumberKeyframesArray = (keyframes) => keyframes.every(isNumber); + +const visualElementStore = new WeakMap(); + +const isKeyframesTarget = (v) => { + return Array.isArray(v); +}; + +function getValueState(visualElement) { + const state = [{}, {}]; + visualElement?.values.forEach((value, key) => { + state[0][key] = value.get(); + state[1][key] = value.getVelocity(); + }); + return state; +} +function resolveVariantFromProps(props, definition, custom, visualElement) { + /** + * If the variant definition is a function, resolve. + */ + if (typeof definition === "function") { + const [current, velocity] = getValueState(visualElement); + definition = definition(custom !== undefined ? custom : props.custom, current, velocity); + } + /** + * If the variant definition is a variant label, or + * the function returned a variant label, resolve. + */ + if (typeof definition === "string") { + definition = props.variants && props.variants[definition]; + } + /** + * At this point we've resolved both functions and variant labels, + * but the resolved variant label might itself have been a function. + * If so, resolve. This can only have returned a valid target object. + */ + if (typeof definition === "function") { + const [current, velocity] = getValueState(visualElement); + definition = definition(custom !== undefined ? custom : props.custom, current, velocity); + } + return definition; +} + +function resolveVariant(visualElement, definition, custom) { + const props = visualElement.getProps(); + return resolveVariantFromProps(props, definition, custom !== undefined ? custom : props.custom, visualElement); +} + +/** + * Set VisualElement's MotionValue, creating a new MotionValue for it if + * it doesn't exist. + */ +function setMotionValue(visualElement, key, value) { + if (visualElement.hasValue(key)) { + visualElement.getValue(key).set(value); + } + else { + visualElement.addValue(key, motionDom.motionValue(value)); + } +} +function resolveFinalValueInKeyframes(v) { + // TODO maybe throw if v.length - 1 is placeholder token? + return isKeyframesTarget(v) ? v[v.length - 1] || 0 : v; +} +function setTarget(visualElement, definition) { + const resolved = resolveVariant(visualElement, definition); + let { transitionEnd = {}, transition = {}, ...target } = resolved || {}; + target = { ...target, ...transitionEnd }; + for (const key in target) { + const value = resolveFinalValueInKeyframes(target[key]); + setMotionValue(visualElement, key, value); + } +} + +function isWillChangeMotionValue(value) { + return Boolean(motionDom.isMotionValue(value) && value.add); +} + +function addValueToWillChange(visualElement, key) { + const willChange = visualElement.getValue("willChange"); + /** + * It could be that a user has set willChange to a regular MotionValue, + * in which case we can't add the value to it. + */ + if (isWillChangeMotionValue(willChange)) { + return willChange.add(key); + } + else if (!willChange && motionUtils.MotionGlobalConfig.WillChange) { + const newWillChange = new motionUtils.MotionGlobalConfig.WillChange("auto"); + visualElement.addValue("willChange", newWillChange); + newWillChange.add(key); + } +} + +/** + * Convert camelCase to dash-case properties. + */ +const camelToDash = (str) => str.replace(/([a-z])([A-Z])/gu, "$1-$2").toLowerCase(); + +const optimizedAppearDataId = "framerAppearId"; +const optimizedAppearDataAttribute = "data-" + camelToDash(optimizedAppearDataId); + +function getOptimisedAppearId(visualElement) { + return visualElement.props[optimizedAppearDataAttribute]; +} + +const isNotNull = (value) => value !== null; +function getFinalKeyframe(keyframes, { repeat, repeatType = "loop" }, finalKeyframe) { + const resolvedKeyframes = keyframes.filter(isNotNull); + const index = repeat && repeatType !== "loop" && repeat % 2 === 1 + ? 0 + : resolvedKeyframes.length - 1; + return !index || finalKeyframe === undefined + ? resolvedKeyframes[index] + : finalKeyframe; +} + +const underDampedSpring = { + type: "spring", + stiffness: 500, + damping: 25, + restSpeed: 10, +}; +const criticallyDampedSpring = (target) => ({ + type: "spring", + stiffness: 550, + damping: target === 0 ? 2 * Math.sqrt(550) : 30, + restSpeed: 10, +}); +const keyframesTransition = { + type: "keyframes", + duration: 0.8, +}; +/** + * Default easing curve is a slightly shallower version of + * the default browser easing curve. + */ +const ease = { + type: "keyframes", + ease: [0.25, 0.1, 0.35, 1], + duration: 0.3, +}; +const getDefaultTransition = (valueKey, { keyframes }) => { + if (keyframes.length > 2) { + return keyframesTransition; + } + else if (motionDom.transformProps.has(valueKey)) { + return valueKey.startsWith("scale") + ? criticallyDampedSpring(keyframes[1]) + : underDampedSpring; + } + return ease; +}; + +/** + * Decide whether a transition is defined on a given Transition. + * This filters out orchestration options and returns true + * if any options are left. + */ +function isTransitionDefined({ when, delay: _delay, delayChildren, staggerChildren, staggerDirection, repeat, repeatType, repeatDelay, from, elapsed, ...transition }) { + return !!Object.keys(transition).length; +} + +const animateMotionValue = (name, value, target, transition = {}, element, isHandoff) => (onComplete) => { + const valueTransition = motionDom.getValueTransition(transition, name) || {}; + /** + * Most transition values are currently completely overwritten by value-specific + * transitions. In the future it'd be nicer to blend these transitions. But for now + * delay actually does inherit from the root transition if not value-specific. + */ + const delay = valueTransition.delay || transition.delay || 0; + /** + * Elapsed isn't a public transition option but can be passed through from + * optimized appear effects in milliseconds. + */ + let { elapsed = 0 } = transition; + elapsed = elapsed - motionUtils.secondsToMilliseconds(delay); + const options = { + keyframes: Array.isArray(target) ? target : [null, target], + ease: "easeOut", + velocity: value.getVelocity(), + ...valueTransition, + delay: -elapsed, + onUpdate: (v) => { + value.set(v); + valueTransition.onUpdate && valueTransition.onUpdate(v); + }, + onComplete: () => { + onComplete(); + valueTransition.onComplete && valueTransition.onComplete(); + }, + name, + motionValue: value, + element: isHandoff ? undefined : element, + }; + /** + * If there's no transition defined for this value, we can generate + * unique transition settings for this value. + */ + if (!isTransitionDefined(valueTransition)) { + Object.assign(options, getDefaultTransition(name, options)); + } + /** + * Both WAAPI and our internal animation functions use durations + * as defined by milliseconds, while our external API defines them + * as seconds. + */ + options.duration && (options.duration = motionUtils.secondsToMilliseconds(options.duration)); + options.repeatDelay && (options.repeatDelay = motionUtils.secondsToMilliseconds(options.repeatDelay)); + /** + * Support deprecated way to set initial value. Prefer keyframe syntax. + */ + if (options.from !== undefined) { + options.keyframes[0] = options.from; + } + let shouldSkip = false; + if (options.type === false || + (options.duration === 0 && !options.repeatDelay)) { + motionDom.makeAnimationInstant(options); + if (options.delay === 0) { + shouldSkip = true; + } + } + if (motionUtils.MotionGlobalConfig.instantAnimations || + motionUtils.MotionGlobalConfig.skipAnimations) { + shouldSkip = true; + motionDom.makeAnimationInstant(options); + options.delay = 0; + } + /** + * If the transition type or easing has been explicitly set by the user + * then we don't want to allow flattening the animation. + */ + options.allowFlatten = !valueTransition.type && !valueTransition.ease; + /** + * If we can or must skip creating the animation, and apply only + * the final keyframe, do so. We also check once keyframes are resolved but + * this early check prevents the need to create an animation at all. + */ + if (shouldSkip && !isHandoff && value.get() !== undefined) { + const finalKeyframe = getFinalKeyframe(options.keyframes, valueTransition); + if (finalKeyframe !== undefined) { + motionDom.frame.update(() => { + options.onUpdate(finalKeyframe); + options.onComplete(); + }); + return; + } + } + return valueTransition.isSync + ? new motionDom.JSAnimation(options) + : new motionDom.AsyncMotionValueAnimation(options); +}; + +/** + * Decide whether we should block this animation. Previously, we achieved this + * just by checking whether the key was listed in protectedKeys, but this + * posed problems if an animation was triggered by afterChildren and protectedKeys + * had been set to true in the meantime. + */ +function shouldBlockAnimation({ protectedKeys, needsAnimating }, key) { + const shouldBlock = protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true; + needsAnimating[key] = false; + return shouldBlock; +} +function animateTarget(visualElement, targetAndTransition, { delay = 0, transitionOverride, type } = {}) { + let { transition = visualElement.getDefaultTransition(), transitionEnd, ...target } = targetAndTransition; + if (transitionOverride) + transition = transitionOverride; + const animations = []; + const animationTypeState = type && + visualElement.animationState && + visualElement.animationState.getState()[type]; + for (const key in target) { + const value = visualElement.getValue(key, visualElement.latestValues[key] ?? null); + const valueTarget = target[key]; + if (valueTarget === undefined || + (animationTypeState && + shouldBlockAnimation(animationTypeState, key))) { + continue; + } + const valueTransition = { + delay, + ...motionDom.getValueTransition(transition || {}, key), + }; + /** + * If the value is already at the defined target, skip the animation. + */ + const currentValue = value.get(); + if (currentValue !== undefined && + !value.isAnimating && + !Array.isArray(valueTarget) && + valueTarget === currentValue && + !valueTransition.velocity) { + continue; + } + /** + * If this is the first time a value is being animated, check + * to see if we're handling off from an existing animation. + */ + let isHandoff = false; + if (window.MotionHandoffAnimation) { + const appearId = getOptimisedAppearId(visualElement); + if (appearId) { + const startTime = window.MotionHandoffAnimation(appearId, key, motionDom.frame); + if (startTime !== null) { + valueTransition.startTime = startTime; + isHandoff = true; + } + } + } + addValueToWillChange(visualElement, key); + value.start(animateMotionValue(key, value, valueTarget, visualElement.shouldReduceMotion && motionDom.positionalKeys.has(key) + ? { type: false } + : valueTransition, visualElement, isHandoff)); + const animation = value.animation; + if (animation) { + animations.push(animation); + } + } + if (transitionEnd) { + Promise.all(animations).then(() => { + motionDom.frame.update(() => { + transitionEnd && setTarget(visualElement, transitionEnd); + }); + }); + } + return animations; +} + +/** + * Bounding boxes tend to be defined as top, left, right, bottom. For various operations + * it's easier to consider each axis individually. This function returns a bounding box + * as a map of single-axis min/max values. + */ +function convertBoundingBoxToBox({ top, left, right, bottom, }) { + return { + x: { min: left, max: right }, + y: { min: top, max: bottom }, + }; +} +/** + * Applies a TransformPoint function to a bounding box. TransformPoint is usually a function + * provided by Framer to allow measured points to be corrected for device scaling. This is used + * when measuring DOM elements and DOM event points. + */ +function transformBoxPoints(point, transformPoint) { + if (!transformPoint) + return point; + const topLeft = transformPoint({ x: point.left, y: point.top }); + const bottomRight = transformPoint({ x: point.right, y: point.bottom }); + return { + top: topLeft.y, + left: topLeft.x, + bottom: bottomRight.y, + right: bottomRight.x, + }; +} + +function measureViewportBox(instance, transformPoint) { + return convertBoundingBoxToBox(transformBoxPoints(instance.getBoundingClientRect(), transformPoint)); +} + +const featureProps = { + animation: [ + "animate", + "variants", + "whileHover", + "whileTap", + "exit", + "whileInView", + "whileFocus", + "whileDrag", + ], + exit: ["exit"], + drag: ["drag", "dragControls"], + focus: ["whileFocus"], + hover: ["whileHover", "onHoverStart", "onHoverEnd"], + tap: ["whileTap", "onTap", "onTapStart", "onTapCancel"], + pan: ["onPan", "onPanStart", "onPanSessionStart", "onPanEnd"], + inView: ["whileInView", "onViewportEnter", "onViewportLeave"], + layout: ["layout", "layoutId"], +}; +const featureDefinitions = {}; +for (const key in featureProps) { + featureDefinitions[key] = { + isEnabled: (props) => featureProps[key].some((name) => !!props[name]), + }; +} + +const createAxis = () => ({ min: 0, max: 0 }); +const createBox = () => ({ + x: createAxis(), + y: createAxis(), +}); + +const isBrowser = typeof window !== "undefined"; + +// Does this device prefer reduced motion? Returns `null` server-side. +const prefersReducedMotion = { current: null }; +const hasReducedMotionListener = { current: false }; + +function initPrefersReducedMotion() { + hasReducedMotionListener.current = true; + if (!isBrowser) + return; + if (window.matchMedia) { + const motionMediaQuery = window.matchMedia("(prefers-reduced-motion)"); + const setReducedMotionPreferences = () => (prefersReducedMotion.current = motionMediaQuery.matches); + motionMediaQuery.addEventListener("change", setReducedMotionPreferences); + setReducedMotionPreferences(); + } + else { + prefersReducedMotion.current = false; + } +} + +function isAnimationControls(v) { + return (v !== null && + typeof v === "object" && + typeof v.start === "function"); +} + +/** + * Decides if the supplied variable is variant label + */ +function isVariantLabel(v) { + return typeof v === "string" || Array.isArray(v); +} + +const variantPriorityOrder = [ + "animate", + "whileInView", + "whileFocus", + "whileHover", + "whileTap", + "whileDrag", + "exit", +]; +const variantProps = ["initial", ...variantPriorityOrder]; + +function isControllingVariants(props) { + return (isAnimationControls(props.animate) || + variantProps.some((name) => isVariantLabel(props[name]))); +} +function isVariantNode(props) { + return Boolean(isControllingVariants(props) || props.variants); +} + +function updateMotionValuesFromProps(element, next, prev) { + for (const key in next) { + const nextValue = next[key]; + const prevValue = prev[key]; + if (motionDom.isMotionValue(nextValue)) { + /** + * If this is a motion value found in props or style, we want to add it + * to our visual element's motion value map. + */ + element.addValue(key, nextValue); + } + else if (motionDom.isMotionValue(prevValue)) { + /** + * If we're swapping from a motion value to a static value, + * create a new motion value from that + */ + element.addValue(key, motionDom.motionValue(nextValue, { owner: element })); + } + else if (prevValue !== nextValue) { + /** + * If this is a flat value that has changed, update the motion value + * or create one if it doesn't exist. We only want to do this if we're + * not handling the value with our animation state. + */ + if (element.hasValue(key)) { + const existingValue = element.getValue(key); + if (existingValue.liveStyle === true) { + existingValue.jump(nextValue); + } + else if (!existingValue.hasAnimated) { + existingValue.set(nextValue); + } + } + else { + const latestValue = element.getStaticValue(key); + element.addValue(key, motionDom.motionValue(latestValue !== undefined ? latestValue : nextValue, { owner: element })); + } + } + } + // Handle removed values + for (const key in prev) { + if (next[key] === undefined) + element.removeValue(key); + } + return next; +} + +const propEventHandlers = [ + "AnimationStart", + "AnimationComplete", + "Update", + "BeforeLayoutMeasure", + "LayoutMeasure", + "LayoutAnimationStart", + "LayoutAnimationComplete", +]; +/** + * A VisualElement is an imperative abstraction around UI elements such as + * HTMLElement, SVGElement, Three.Object3D etc. + */ +class VisualElement { + /** + * This method takes React props and returns found MotionValues. For example, HTML + * MotionValues will be found within the style prop, whereas for Three.js within attribute arrays. + * + * This isn't an abstract method as it needs calling in the constructor, but it is + * intended to be one. + */ + scrapeMotionValuesFromProps(_props, _prevProps, _visualElement) { + return {}; + } + constructor({ parent, props, presenceContext, reducedMotionConfig, blockInitialAnimation, visualState, }, options = {}) { + /** + * A reference to the current underlying Instance, e.g. a HTMLElement + * or Three.Mesh etc. + */ + this.current = null; + /** + * A set containing references to this VisualElement's children. + */ + this.children = new Set(); + /** + * Determine what role this visual element should take in the variant tree. + */ + this.isVariantNode = false; + this.isControllingVariants = false; + /** + * Decides whether this VisualElement should animate in reduced motion + * mode. + * + * TODO: This is currently set on every individual VisualElement but feels + * like it could be set globally. + */ + this.shouldReduceMotion = null; + /** + * A map of all motion values attached to this visual element. Motion + * values are source of truth for any given animated value. A motion + * value might be provided externally by the component via props. + */ + this.values = new Map(); + this.KeyframeResolver = motionDom.KeyframeResolver; + /** + * Cleanup functions for active features (hover/tap/exit etc) + */ + this.features = {}; + /** + * A map of every subscription that binds the provided or generated + * motion values onChange listeners to this visual element. + */ + this.valueSubscriptions = new Map(); + /** + * A reference to the previously-provided motion values as returned + * from scrapeMotionValuesFromProps. We use the keys in here to determine + * if any motion values need to be removed after props are updated. + */ + this.prevMotionValues = {}; + /** + * An object containing a SubscriptionManager for each active event. + */ + this.events = {}; + /** + * An object containing an unsubscribe function for each prop event subscription. + * For example, every "Update" event can have multiple subscribers via + * VisualElement.on(), but only one of those can be defined via the onUpdate prop. + */ + this.propEventSubscriptions = {}; + this.notifyUpdate = () => this.notify("Update", this.latestValues); + this.render = () => { + if (!this.current) + return; + this.triggerBuild(); + this.renderInstance(this.current, this.renderState, this.props.style, this.projection); + }; + this.renderScheduledAt = 0.0; + this.scheduleRender = () => { + const now = motionDom.time.now(); + if (this.renderScheduledAt < now) { + this.renderScheduledAt = now; + motionDom.frame.render(this.render, false, true); + } + }; + const { latestValues, renderState } = visualState; + this.latestValues = latestValues; + this.baseTarget = { ...latestValues }; + this.initialValues = props.initial ? { ...latestValues } : {}; + this.renderState = renderState; + this.parent = parent; + this.props = props; + this.presenceContext = presenceContext; + this.depth = parent ? parent.depth + 1 : 0; + this.reducedMotionConfig = reducedMotionConfig; + this.options = options; + this.blockInitialAnimation = Boolean(blockInitialAnimation); + this.isControllingVariants = isControllingVariants(props); + this.isVariantNode = isVariantNode(props); + if (this.isVariantNode) { + this.variantChildren = new Set(); + } + this.manuallyAnimateOnMount = Boolean(parent && parent.current); + /** + * Any motion values that are provided to the element when created + * aren't yet bound to the element, as this would technically be impure. + * However, we iterate through the motion values and set them to the + * initial values for this component. + * + * TODO: This is impure and we should look at changing this to run on mount. + * Doing so will break some tests but this isn't necessarily a breaking change, + * more a reflection of the test. + */ + const { willChange, ...initialMotionValues } = this.scrapeMotionValuesFromProps(props, {}, this); + for (const key in initialMotionValues) { + const value = initialMotionValues[key]; + if (latestValues[key] !== undefined && motionDom.isMotionValue(value)) { + value.set(latestValues[key]); + } + } + } + mount(instance) { + this.current = instance; + visualElementStore.set(instance, this); + if (this.projection && !this.projection.instance) { + this.projection.mount(instance); + } + if (this.parent && this.isVariantNode && !this.isControllingVariants) { + this.removeFromVariantTree = this.parent.addVariantChild(this); + } + this.values.forEach((value, key) => this.bindToMotionValue(key, value)); + if (!hasReducedMotionListener.current) { + initPrefersReducedMotion(); + } + this.shouldReduceMotion = + this.reducedMotionConfig === "never" + ? false + : this.reducedMotionConfig === "always" + ? true + : prefersReducedMotion.current; + if (process.env.NODE_ENV !== "production") { + motionUtils.warnOnce(this.shouldReduceMotion !== true, "You have Reduced Motion enabled on your device. Animations may not appear as expected.", "reduced-motion-disabled"); + } + this.parent?.addChild(this); + this.update(this.props, this.presenceContext); + } + unmount() { + this.projection && this.projection.unmount(); + motionDom.cancelFrame(this.notifyUpdate); + motionDom.cancelFrame(this.render); + this.valueSubscriptions.forEach((remove) => remove()); + this.valueSubscriptions.clear(); + this.removeFromVariantTree && this.removeFromVariantTree(); + this.parent?.removeChild(this); + for (const key in this.events) { + this.events[key].clear(); + } + for (const key in this.features) { + const feature = this.features[key]; + if (feature) { + feature.unmount(); + feature.isMounted = false; + } + } + this.current = null; + } + addChild(child) { + this.children.add(child); + this.enteringChildren ?? (this.enteringChildren = new Set()); + this.enteringChildren.add(child); + } + removeChild(child) { + this.children.delete(child); + this.enteringChildren && this.enteringChildren.delete(child); + } + bindToMotionValue(key, value) { + if (this.valueSubscriptions.has(key)) { + this.valueSubscriptions.get(key)(); + } + const valueIsTransform = motionDom.transformProps.has(key); + if (valueIsTransform && this.onBindTransform) { + this.onBindTransform(); + } + const removeOnChange = value.on("change", (latestValue) => { + this.latestValues[key] = latestValue; + this.props.onUpdate && motionDom.frame.preRender(this.notifyUpdate); + if (valueIsTransform && this.projection) { + this.projection.isTransformDirty = true; + } + this.scheduleRender(); + }); + let removeSyncCheck; + if (window.MotionCheckAppearSync) { + removeSyncCheck = window.MotionCheckAppearSync(this, key, value); + } + this.valueSubscriptions.set(key, () => { + removeOnChange(); + if (removeSyncCheck) + removeSyncCheck(); + if (value.owner) + value.stop(); + }); + } + sortNodePosition(other) { + /** + * If these nodes aren't even of the same type we can't compare their depth. + */ + if (!this.current || + !this.sortInstanceNodePosition || + this.type !== other.type) { + return 0; + } + return this.sortInstanceNodePosition(this.current, other.current); + } + updateFeatures() { + let key = "animation"; + for (key in featureDefinitions) { + const featureDefinition = featureDefinitions[key]; + if (!featureDefinition) + continue; + const { isEnabled, Feature: FeatureConstructor } = featureDefinition; + /** + * If this feature is enabled but not active, make a new instance. + */ + if (!this.features[key] && + FeatureConstructor && + isEnabled(this.props)) { + this.features[key] = new FeatureConstructor(this); + } + /** + * If we have a feature, mount or update it. + */ + if (this.features[key]) { + const feature = this.features[key]; + if (feature.isMounted) { + feature.update(); + } + else { + feature.mount(); + feature.isMounted = true; + } + } + } + } + triggerBuild() { + this.build(this.renderState, this.latestValues, this.props); + } + /** + * Measure the current viewport box with or without transforms. + * Only measures axis-aligned boxes, rotate and skew must be manually + * removed with a re-render to work. + */ + measureViewportBox() { + return this.current + ? this.measureInstanceViewportBox(this.current, this.props) + : createBox(); + } + getStaticValue(key) { + return this.latestValues[key]; + } + setStaticValue(key, value) { + this.latestValues[key] = value; + } + /** + * Update the provided props. Ensure any newly-added motion values are + * added to our map, old ones removed, and listeners updated. + */ + update(props, presenceContext) { + if (props.transformTemplate || this.props.transformTemplate) { + this.scheduleRender(); + } + this.prevProps = this.props; + this.props = props; + this.prevPresenceContext = this.presenceContext; + this.presenceContext = presenceContext; + /** + * Update prop event handlers ie onAnimationStart, onAnimationComplete + */ + for (let i = 0; i < propEventHandlers.length; i++) { + const key = propEventHandlers[i]; + if (this.propEventSubscriptions[key]) { + this.propEventSubscriptions[key](); + delete this.propEventSubscriptions[key]; + } + const listenerName = ("on" + key); + const listener = props[listenerName]; + if (listener) { + this.propEventSubscriptions[key] = this.on(key, listener); + } + } + this.prevMotionValues = updateMotionValuesFromProps(this, this.scrapeMotionValuesFromProps(props, this.prevProps, this), this.prevMotionValues); + if (this.handleChildMotionValue) { + this.handleChildMotionValue(); + } + } + getProps() { + return this.props; + } + /** + * Returns the variant definition with a given name. + */ + getVariant(name) { + return this.props.variants ? this.props.variants[name] : undefined; + } + /** + * Returns the defined default transition on this component. + */ + getDefaultTransition() { + return this.props.transition; + } + getTransformPagePoint() { + return this.props.transformPagePoint; + } + getClosestVariantNode() { + return this.isVariantNode + ? this + : this.parent + ? this.parent.getClosestVariantNode() + : undefined; + } + /** + * Add a child visual element to our set of children. + */ + addVariantChild(child) { + const closestVariantNode = this.getClosestVariantNode(); + if (closestVariantNode) { + closestVariantNode.variantChildren && + closestVariantNode.variantChildren.add(child); + return () => closestVariantNode.variantChildren.delete(child); + } + } + /** + * Add a motion value and bind it to this visual element. + */ + addValue(key, value) { + // Remove existing value if it exists + const existingValue = this.values.get(key); + if (value !== existingValue) { + if (existingValue) + this.removeValue(key); + this.bindToMotionValue(key, value); + this.values.set(key, value); + this.latestValues[key] = value.get(); + } + } + /** + * Remove a motion value and unbind any active subscriptions. + */ + removeValue(key) { + this.values.delete(key); + const unsubscribe = this.valueSubscriptions.get(key); + if (unsubscribe) { + unsubscribe(); + this.valueSubscriptions.delete(key); + } + delete this.latestValues[key]; + this.removeValueFromRenderState(key, this.renderState); + } + /** + * Check whether we have a motion value for this key + */ + hasValue(key) { + return this.values.has(key); + } + getValue(key, defaultValue) { + if (this.props.values && this.props.values[key]) { + return this.props.values[key]; + } + let value = this.values.get(key); + if (value === undefined && defaultValue !== undefined) { + value = motionDom.motionValue(defaultValue === null ? undefined : defaultValue, { owner: this }); + this.addValue(key, value); + } + return value; + } + /** + * If we're trying to animate to a previously unencountered value, + * we need to check for it in our state and as a last resort read it + * directly from the instance (which might have performance implications). + */ + readValue(key, target) { + let value = this.latestValues[key] !== undefined || !this.current + ? this.latestValues[key] + : this.getBaseTargetFromProps(this.props, key) ?? + this.readValueFromInstance(this.current, key, this.options); + if (value !== undefined && value !== null) { + if (typeof value === "string" && + (motionUtils.isNumericalString(value) || motionUtils.isZeroValueString(value))) { + // If this is a number read as a string, ie "0" or "200", convert it to a number + value = parseFloat(value); + } + else if (!motionDom.findValueType(value) && motionDom.complex.test(target)) { + value = motionDom.getAnimatableNone(key, target); + } + this.setBaseTarget(key, motionDom.isMotionValue(value) ? value.get() : value); + } + return motionDom.isMotionValue(value) ? value.get() : value; + } + /** + * Set the base target to later animate back to. This is currently + * only hydrated on creation and when we first read a value. + */ + setBaseTarget(key, value) { + this.baseTarget[key] = value; + } + /** + * Find the base target for a value thats been removed from all animation + * props. + */ + getBaseTarget(key) { + const { initial } = this.props; + let valueFromInitial; + if (typeof initial === "string" || typeof initial === "object") { + const variant = resolveVariantFromProps(this.props, initial, this.presenceContext?.custom); + if (variant) { + valueFromInitial = variant[key]; + } + } + /** + * If this value still exists in the current initial variant, read that. + */ + if (initial && valueFromInitial !== undefined) { + return valueFromInitial; + } + /** + * Alternatively, if this VisualElement config has defined a getBaseTarget + * so we can read the value from an alternative source, try that. + */ + const target = this.getBaseTargetFromProps(this.props, key); + if (target !== undefined && !motionDom.isMotionValue(target)) + return target; + /** + * If the value was initially defined on initial, but it doesn't any more, + * return undefined. Otherwise return the value as initially read from the DOM. + */ + return this.initialValues[key] !== undefined && + valueFromInitial === undefined + ? undefined + : this.baseTarget[key]; + } + on(eventName, callback) { + if (!this.events[eventName]) { + this.events[eventName] = new motionUtils.SubscriptionManager(); + } + return this.events[eventName].add(callback); + } + notify(eventName, ...args) { + if (this.events[eventName]) { + this.events[eventName].notify(...args); + } + } + scheduleRenderMicrotask() { + motionDom.microtask.render(this.render); + } +} + +class DOMVisualElement extends VisualElement { + constructor() { + super(...arguments); + this.KeyframeResolver = motionDom.DOMKeyframesResolver; + } + sortInstanceNodePosition(a, b) { + /** + * compareDocumentPosition returns a bitmask, by using the bitwise & + * we're returning true if 2 in that bitmask is set to true. 2 is set + * to true if b preceeds a. + */ + return a.compareDocumentPosition(b) & 2 ? 1 : -1; + } + getBaseTargetFromProps(props, key) { + return props.style + ? props.style[key] + : undefined; + } + removeValueFromRenderState(key, { vars, style }) { + delete vars[key]; + delete style[key]; + } + handleChildMotionValue() { + if (this.childSubscription) { + this.childSubscription(); + delete this.childSubscription; + } + const { children } = this.props; + if (motionDom.isMotionValue(children)) { + this.childSubscription = children.on("change", (latest) => { + if (this.current) { + this.current.textContent = `${latest}`; + } + }); + } + } +} + +const translateAlias = { + x: "translateX", + y: "translateY", + z: "translateZ", + transformPerspective: "perspective", +}; +const numTransforms = motionDom.transformPropOrder.length; +/** + * Build a CSS transform style from individual x/y/scale etc properties. + * + * This outputs with a default order of transforms/scales/rotations, this can be customised by + * providing a transformTemplate function. + */ +function buildTransform(latestValues, transform, transformTemplate) { + // The transform string we're going to build into. + let transformString = ""; + let transformIsDefault = true; + /** + * Loop over all possible transforms in order, adding the ones that + * are present to the transform string. + */ + for (let i = 0; i < numTransforms; i++) { + const key = motionDom.transformPropOrder[i]; + const value = latestValues[key]; + if (value === undefined) + continue; + let valueIsDefault = true; + if (typeof value === "number") { + valueIsDefault = value === (key.startsWith("scale") ? 1 : 0); + } + else { + valueIsDefault = parseFloat(value) === 0; + } + if (!valueIsDefault || transformTemplate) { + const valueAsType = motionDom.getValueAsType(value, motionDom.numberValueTypes[key]); + if (!valueIsDefault) { + transformIsDefault = false; + const transformName = translateAlias[key] || key; + transformString += `${transformName}(${valueAsType}) `; + } + if (transformTemplate) { + transform[key] = valueAsType; + } + } + } + transformString = transformString.trim(); + // If we have a custom `transform` template, pass our transform values and + // generated transformString to that before returning + if (transformTemplate) { + transformString = transformTemplate(transform, transformIsDefault ? "" : transformString); + } + else if (transformIsDefault) { + transformString = "none"; + } + return transformString; +} + +function buildHTMLStyles(state, latestValues, transformTemplate) { + const { style, vars, transformOrigin } = state; + // Track whether we encounter any transform or transformOrigin values. + let hasTransform = false; + let hasTransformOrigin = false; + /** + * Loop over all our latest animated values and decide whether to handle them + * as a style or CSS variable. + * + * Transforms and transform origins are kept separately for further processing. + */ + for (const key in latestValues) { + const value = latestValues[key]; + if (motionDom.transformProps.has(key)) { + // If this is a transform, flag to enable further transform processing + hasTransform = true; + continue; + } + else if (motionDom.isCSSVariableName(key)) { + vars[key] = value; + continue; + } + else { + // Convert the value to its default value type, ie 0 -> "0px" + const valueAsType = motionDom.getValueAsType(value, motionDom.numberValueTypes[key]); + if (key.startsWith("origin")) { + // If this is a transform origin, flag and enable further transform-origin processing + hasTransformOrigin = true; + transformOrigin[key] = + valueAsType; + } + else { + style[key] = valueAsType; + } + } + } + if (!latestValues.transform) { + if (hasTransform || transformTemplate) { + style.transform = buildTransform(latestValues, state.transform, transformTemplate); + } + else if (style.transform) { + /** + * If we have previously created a transform but currently don't have any, + * reset transform style to none. + */ + style.transform = "none"; + } + } + /** + * Build a transformOrigin style. Uses the same defaults as the browser for + * undefined origins. + */ + if (hasTransformOrigin) { + const { originX = "50%", originY = "50%", originZ = 0, } = transformOrigin; + style.transformOrigin = `${originX} ${originY} ${originZ}`; + } +} + +function renderHTML(element, { style, vars }, styleProp, projection) { + const elementStyle = element.style; + let key; + for (key in style) { + // CSSStyleDeclaration has [index: number]: string; in the types, so we use that as key type. + elementStyle[key] = style[key]; + } + // Write projection styles directly to element style + projection?.applyProjectionStyles(elementStyle, styleProp); + for (key in vars) { + // Loop over any CSS variables and assign those. + // They can only be assigned using `setProperty`. + elementStyle.setProperty(key, vars[key]); + } +} + +const scaleCorrectors = {}; + +function isForcedMotionValue(key, { layout, layoutId }) { + return (motionDom.transformProps.has(key) || + key.startsWith("origin") || + ((layout || layoutId !== undefined) && + (!!scaleCorrectors[key] || key === "opacity"))); +} + +function scrapeMotionValuesFromProps$1(props, prevProps, visualElement) { + const { style } = props; + const newValues = {}; + for (const key in style) { + if (motionDom.isMotionValue(style[key]) || + (prevProps.style && + motionDom.isMotionValue(prevProps.style[key])) || + isForcedMotionValue(key, props) || + visualElement?.getValue(key)?.liveStyle !== undefined) { + newValues[key] = style[key]; + } + } + return newValues; +} + +function getComputedStyle$1(element) { + return window.getComputedStyle(element); +} +class HTMLVisualElement extends DOMVisualElement { + constructor() { + super(...arguments); + this.type = "html"; + this.renderInstance = renderHTML; + } + readValueFromInstance(instance, key) { + if (motionDom.transformProps.has(key)) { + return this.projection?.isProjecting + ? motionDom.defaultTransformValue(key) + : motionDom.readTransformValue(instance, key); + } + else { + const computedStyle = getComputedStyle$1(instance); + const value = (motionDom.isCSSVariableName(key) + ? computedStyle.getPropertyValue(key) + : computedStyle[key]) || 0; + return typeof value === "string" ? value.trim() : value; + } + } + measureInstanceViewportBox(instance, { transformPagePoint }) { + return measureViewportBox(instance, transformPagePoint); + } + build(renderState, latestValues, props) { + buildHTMLStyles(renderState, latestValues, props.transformTemplate); + } + scrapeMotionValuesFromProps(props, prevProps, visualElement) { + return scrapeMotionValuesFromProps$1(props, prevProps, visualElement); + } +} + +function isObjectKey(key, object) { + return key in object; +} +class ObjectVisualElement extends VisualElement { + constructor() { + super(...arguments); + this.type = "object"; + } + readValueFromInstance(instance, key) { + if (isObjectKey(key, instance)) { + const value = instance[key]; + if (typeof value === "string" || typeof value === "number") { + return value; + } + } + return undefined; + } + getBaseTargetFromProps() { + return undefined; + } + removeValueFromRenderState(key, renderState) { + delete renderState.output[key]; + } + measureInstanceViewportBox() { + return createBox(); + } + build(renderState, latestValues) { + Object.assign(renderState.output, latestValues); + } + renderInstance(instance, { output }) { + Object.assign(instance, output); + } + sortInstanceNodePosition() { + return 0; + } +} + +const dashKeys = { + offset: "stroke-dashoffset", + array: "stroke-dasharray", +}; +const camelKeys = { + offset: "strokeDashoffset", + array: "strokeDasharray", +}; +/** + * Build SVG path properties. Uses the path's measured length to convert + * our custom pathLength, pathSpacing and pathOffset into stroke-dashoffset + * and stroke-dasharray attributes. + * + * This function is mutative to reduce per-frame GC. + */ +function buildSVGPath(attrs, length, spacing = 1, offset = 0, useDashCase = true) { + // Normalise path length by setting SVG attribute pathLength to 1 + attrs.pathLength = 1; + // We use dash case when setting attributes directly to the DOM node and camel case + // when defining props on a React component. + const keys = useDashCase ? dashKeys : camelKeys; + // Build the dash offset + attrs[keys.offset] = motionDom.px.transform(-offset); + // Build the dash array + const pathLength = motionDom.px.transform(length); + const pathSpacing = motionDom.px.transform(spacing); + attrs[keys.array] = `${pathLength} ${pathSpacing}`; +} + +/** + * Build SVG visual attributes, like cx and style.transform + */ +function buildSVGAttrs(state, { attrX, attrY, attrScale, pathLength, pathSpacing = 1, pathOffset = 0, +// This is object creation, which we try to avoid per-frame. +...latest }, isSVGTag, transformTemplate, styleProp) { + buildHTMLStyles(state, latest, transformTemplate); + /** + * For svg tags we just want to make sure viewBox is animatable and treat all the styles + * as normal HTML tags. + */ + if (isSVGTag) { + if (state.style.viewBox) { + state.attrs.viewBox = state.style.viewBox; + } + return; + } + state.attrs = state.style; + state.style = {}; + const { attrs, style } = state; + /** + * However, we apply transforms as CSS transforms. + * So if we detect a transform, transformOrigin we take it from attrs and copy it into style. + */ + if (attrs.transform) { + style.transform = attrs.transform; + delete attrs.transform; + } + if (style.transform || attrs.transformOrigin) { + style.transformOrigin = attrs.transformOrigin ?? "50% 50%"; + delete attrs.transformOrigin; + } + if (style.transform) { + /** + * SVG's element transform-origin uses its own median as a reference. + * Therefore, transformBox becomes a fill-box + */ + style.transformBox = styleProp?.transformBox ?? "fill-box"; + delete attrs.transformBox; + } + // Render attrX/attrY/attrScale as attributes + if (attrX !== undefined) + attrs.x = attrX; + if (attrY !== undefined) + attrs.y = attrY; + if (attrScale !== undefined) + attrs.scale = attrScale; + // Build SVG path if one has been defined + if (pathLength !== undefined) { + buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false); + } +} + +/** + * A set of attribute names that are always read/written as camel case. + */ +const camelCaseAttributes = new Set([ + "baseFrequency", + "diffuseConstant", + "kernelMatrix", + "kernelUnitLength", + "keySplines", + "keyTimes", + "limitingConeAngle", + "markerHeight", + "markerWidth", + "numOctaves", + "targetX", + "targetY", + "surfaceScale", + "specularConstant", + "specularExponent", + "stdDeviation", + "tableValues", + "viewBox", + "gradientTransform", + "pathLength", + "startOffset", + "textLength", + "lengthAdjust", +]); + +const isSVGTag = (tag) => typeof tag === "string" && tag.toLowerCase() === "svg"; + +function renderSVG(element, renderState, _styleProp, projection) { + renderHTML(element, renderState, undefined, projection); + for (const key in renderState.attrs) { + element.setAttribute(!camelCaseAttributes.has(key) ? camelToDash(key) : key, renderState.attrs[key]); + } +} + +function scrapeMotionValuesFromProps(props, prevProps, visualElement) { + const newValues = scrapeMotionValuesFromProps$1(props, prevProps, visualElement); + for (const key in props) { + if (motionDom.isMotionValue(props[key]) || + motionDom.isMotionValue(prevProps[key])) { + const targetKey = motionDom.transformPropOrder.indexOf(key) !== -1 + ? "attr" + key.charAt(0).toUpperCase() + key.substring(1) + : key; + newValues[targetKey] = props[key]; + } + } + return newValues; +} + +class SVGVisualElement extends DOMVisualElement { + constructor() { + super(...arguments); + this.type = "svg"; + this.isSVGTag = false; + this.measureInstanceViewportBox = createBox; + } + getBaseTargetFromProps(props, key) { + return props[key]; + } + readValueFromInstance(instance, key) { + if (motionDom.transformProps.has(key)) { + const defaultType = motionDom.getDefaultValueType(key); + return defaultType ? defaultType.default || 0 : 0; + } + key = !camelCaseAttributes.has(key) ? camelToDash(key) : key; + return instance.getAttribute(key); + } + scrapeMotionValuesFromProps(props, prevProps, visualElement) { + return scrapeMotionValuesFromProps(props, prevProps, visualElement); + } + build(renderState, latestValues, props) { + buildSVGAttrs(renderState, latestValues, this.isSVGTag, props.transformTemplate, props.style); + } + renderInstance(instance, renderState, styleProp, projection) { + renderSVG(instance, renderState, styleProp, projection); + } + mount(instance) { + this.isSVGTag = isSVGTag(instance.tagName); + super.mount(instance); + } +} + +function createDOMVisualElement(element) { + const options = { + presenceContext: null, + props: {}, + visualState: { + renderState: { + transform: {}, + transformOrigin: {}, + style: {}, + vars: {}, + attrs: {}, + }, + latestValues: {}, + }, + }; + const node = motionDom.isSVGElement(element) && !motionDom.isSVGSVGElement(element) + ? new SVGVisualElement(options) + : new HTMLVisualElement(options); + node.mount(element); + visualElementStore.set(element, node); +} +function createObjectVisualElement(subject) { + const options = { + presenceContext: null, + props: {}, + visualState: { + renderState: { + output: {}, + }, + latestValues: {}, + }, + }; + const node = new ObjectVisualElement(options); + node.mount(subject); + visualElementStore.set(subject, node); +} + +function animateSingleValue(value, keyframes, options) { + const motionValue = motionDom.isMotionValue(value) ? value : motionDom.motionValue(value); + motionValue.start(animateMotionValue("", motionValue, keyframes, options)); + return motionValue.animation; +} + +function isSingleValue(subject, keyframes) { + return (motionDom.isMotionValue(subject) || + typeof subject === "number" || + (typeof subject === "string" && !isDOMKeyframes(keyframes))); +} +/** + * Implementation + */ +function animateSubject(subject, keyframes, options, scope) { + const animations = []; + if (isSingleValue(subject, keyframes)) { + animations.push(animateSingleValue(subject, isDOMKeyframes(keyframes) + ? keyframes.default || keyframes + : keyframes, options ? options.default || options : options)); + } + else { + const subjects = resolveSubjects(subject, keyframes, scope); + const numSubjects = subjects.length; + motionUtils.invariant(Boolean(numSubjects), "No valid elements provided.", "no-valid-elements"); + for (let i = 0; i < numSubjects; i++) { + const thisSubject = subjects[i]; + motionUtils.invariant(thisSubject !== null, "You're trying to perform an animation on null. Ensure that selectors are correctly finding elements and refs are correctly hydrated.", "animate-null"); + const createVisualElement = thisSubject instanceof Element + ? createDOMVisualElement + : createObjectVisualElement; + if (!visualElementStore.has(thisSubject)) { + createVisualElement(thisSubject); + } + const visualElement = visualElementStore.get(thisSubject); + const transition = { ...options }; + /** + * Resolve stagger function if provided. + */ + if ("delay" in transition && + typeof transition.delay === "function") { + transition.delay = transition.delay(i, numSubjects); + } + animations.push(...animateTarget(visualElement, { ...keyframes, transition }, {})); + } + } + return animations; +} + +function animateSequence(sequence, options, scope) { + const animations = []; + const animationDefinitions = createAnimationsFromSequence(sequence, options, scope, { spring: motionDom.spring }); + animationDefinitions.forEach(({ keyframes, transition }, subject) => { + animations.push(...animateSubject(subject, keyframes, transition)); + }); + return animations; +} + +function isSequence(value) { + return Array.isArray(value) && value.some(Array.isArray); +} +/** + * Creates an animation function that is optionally scoped + * to a specific element. + */ +function createScopedAnimate(scope) { + /** + * Implementation + */ + function scopedAnimate(subjectOrSequence, optionsOrKeyframes, options) { + let animations = []; + if (isSequence(subjectOrSequence)) { + animations = animateSequence(subjectOrSequence, optionsOrKeyframes, scope); + } + else { + animations = animateSubject(subjectOrSequence, optionsOrKeyframes, options, scope); + } + const animation = new motionDom.GroupAnimationWithThen(animations); + if (scope) { + scope.animations.push(animation); + animation.finished.then(() => { + motionUtils.removeItem(scope.animations, animation); + }); + } + return animation; + } + return scopedAnimate; +} +const animate = createScopedAnimate(); + +function animateElements(elementOrSelector, keyframes, options, scope) { + const elements = motionDom.resolveElements(elementOrSelector, scope); + const numElements = elements.length; + motionUtils.invariant(Boolean(numElements), "No valid elements provided.", "no-valid-elements"); + /** + * WAAPI doesn't support interrupting animations. + * + * Therefore, starting animations requires a three-step process: + * 1. Stop existing animations (write styles to DOM) + * 2. Resolve keyframes (read styles from DOM) + * 3. Create new animations (write styles to DOM) + * + * The hybrid `animate()` function uses AsyncAnimation to resolve + * keyframes before creating new animations, which removes style + * thrashing. Here, we have much stricter filesize constraints. + * Therefore we do this in a synchronous way that ensures that + * at least within `animate()` calls there is no style thrashing. + * + * In the motion-native-animate-mini-interrupt benchmark this + * was 80% faster than a single loop. + */ + const animationDefinitions = []; + /** + * Step 1: Build options and stop existing animations (write) + */ + for (let i = 0; i < numElements; i++) { + const element = elements[i]; + const elementTransition = { ...options }; + /** + * Resolve stagger function if provided. + */ + if (typeof elementTransition.delay === "function") { + elementTransition.delay = elementTransition.delay(i, numElements); + } + for (const valueName in keyframes) { + let valueKeyframes = keyframes[valueName]; + if (!Array.isArray(valueKeyframes)) { + valueKeyframes = [valueKeyframes]; + } + const valueOptions = { + ...motionDom.getValueTransition(elementTransition, valueName), + }; + valueOptions.duration && (valueOptions.duration = motionUtils.secondsToMilliseconds(valueOptions.duration)); + valueOptions.delay && (valueOptions.delay = motionUtils.secondsToMilliseconds(valueOptions.delay)); + /** + * If there's an existing animation playing on this element then stop it + * before creating a new one. + */ + const map = motionDom.getAnimationMap(element); + const key = motionDom.animationMapKey(valueName, valueOptions.pseudoElement || ""); + const currentAnimation = map.get(key); + currentAnimation && currentAnimation.stop(); + animationDefinitions.push({ + map, + key, + unresolvedKeyframes: valueKeyframes, + options: { + ...valueOptions, + element, + name: valueName, + allowFlatten: !elementTransition.type && !elementTransition.ease, + }, + }); + } + } + /** + * Step 2: Resolve keyframes (read) + */ + for (let i = 0; i < animationDefinitions.length; i++) { + const { unresolvedKeyframes, options: animationOptions } = animationDefinitions[i]; + const { element, name, pseudoElement } = animationOptions; + if (!pseudoElement && unresolvedKeyframes[0] === null) { + unresolvedKeyframes[0] = motionDom.getComputedStyle(element, name); + } + motionDom.fillWildcards(unresolvedKeyframes); + motionDom.applyPxDefaults(unresolvedKeyframes, name); + /** + * If we only have one keyframe, explicitly read the initial keyframe + * from the computed style. This is to ensure consistency with WAAPI behaviour + * for restarting animations, for instance .play() after finish, when it + * has one vs two keyframes. + */ + if (!pseudoElement && unresolvedKeyframes.length < 2) { + unresolvedKeyframes.unshift(motionDom.getComputedStyle(element, name)); + } + animationOptions.keyframes = unresolvedKeyframes; + } + /** + * Step 3: Create new animations (write) + */ + const animations = []; + for (let i = 0; i < animationDefinitions.length; i++) { + const { map, key, options: animationOptions } = animationDefinitions[i]; + const animation = new motionDom.NativeAnimation(animationOptions); + map.set(key, animation); + animation.finished.finally(() => map.delete(key)); + animations.push(animation); + } + return animations; +} + +const createScopedWaapiAnimate = (scope) => { + function scopedAnimate(elementOrSelector, keyframes, options) { + return new motionDom.GroupAnimationWithThen(animateElements(elementOrSelector, keyframes, options, scope)); + } + return scopedAnimate; +}; +const animateMini = /*@__PURE__*/ createScopedWaapiAnimate(); + +/** + * A time in milliseconds, beyond which we consider the scroll velocity to be 0. + */ +const maxElapsed = 50; +const createAxisInfo = () => ({ + current: 0, + offset: [], + progress: 0, + scrollLength: 0, + targetOffset: 0, + targetLength: 0, + containerLength: 0, + velocity: 0, +}); +const createScrollInfo = () => ({ + time: 0, + x: createAxisInfo(), + y: createAxisInfo(), +}); +const keys = { + x: { + length: "Width", + position: "Left", + }, + y: { + length: "Height", + position: "Top", + }, +}; +function updateAxisInfo(element, axisName, info, time) { + const axis = info[axisName]; + const { length, position } = keys[axisName]; + const prev = axis.current; + const prevTime = info.time; + axis.current = element[`scroll${position}`]; + axis.scrollLength = element[`scroll${length}`] - element[`client${length}`]; + axis.offset.length = 0; + axis.offset[0] = 0; + axis.offset[1] = axis.scrollLength; + axis.progress = motionUtils.progress(0, axis.scrollLength, axis.current); + const elapsed = time - prevTime; + axis.velocity = + elapsed > maxElapsed + ? 0 + : motionUtils.velocityPerSecond(axis.current - prev, elapsed); +} +function updateScrollInfo(element, info, time) { + updateAxisInfo(element, "x", info, time); + updateAxisInfo(element, "y", info, time); + info.time = time; +} + +function calcInset(element, container) { + const inset = { x: 0, y: 0 }; + let current = element; + while (current && current !== container) { + if (motionDom.isHTMLElement(current)) { + inset.x += current.offsetLeft; + inset.y += current.offsetTop; + current = current.offsetParent; + } + else if (current.tagName === "svg") { + /** + * This isn't an ideal approach to measuring the offset of tags. + * It would be preferable, given they behave like HTMLElements in most ways + * to use offsetLeft/Top. But these don't exist on . Likewise we + * can't use .getBBox() like most SVG elements as these provide the offset + * relative to the SVG itself, which for is usually 0x0. + */ + const svgBoundingBox = current.getBoundingClientRect(); + current = current.parentElement; + const parentBoundingBox = current.getBoundingClientRect(); + inset.x += svgBoundingBox.left - parentBoundingBox.left; + inset.y += svgBoundingBox.top - parentBoundingBox.top; + } + else if (current instanceof SVGGraphicsElement) { + const { x, y } = current.getBBox(); + inset.x += x; + inset.y += y; + let svg = null; + let parent = current.parentNode; + while (!svg) { + if (parent.tagName === "svg") { + svg = parent; + } + parent = current.parentNode; + } + current = svg; + } + else { + break; + } + } + return inset; +} + +const namedEdges = { + start: 0, + center: 0.5, + end: 1, +}; +function resolveEdge(edge, length, inset = 0) { + let delta = 0; + /** + * If we have this edge defined as a preset, replace the definition + * with the numerical value. + */ + if (edge in namedEdges) { + edge = namedEdges[edge]; + } + /** + * Handle unit values + */ + if (typeof edge === "string") { + const asNumber = parseFloat(edge); + if (edge.endsWith("px")) { + delta = asNumber; + } + else if (edge.endsWith("%")) { + edge = asNumber / 100; + } + else if (edge.endsWith("vw")) { + delta = (asNumber / 100) * document.documentElement.clientWidth; + } + else if (edge.endsWith("vh")) { + delta = (asNumber / 100) * document.documentElement.clientHeight; + } + else { + edge = asNumber; + } + } + /** + * If the edge is defined as a number, handle as a progress value. + */ + if (typeof edge === "number") { + delta = length * edge; + } + return inset + delta; +} + +const defaultOffset = [0, 0]; +function resolveOffset(offset, containerLength, targetLength, targetInset) { + let offsetDefinition = Array.isArray(offset) ? offset : defaultOffset; + let targetPoint = 0; + let containerPoint = 0; + if (typeof offset === "number") { + /** + * If we're provided offset: [0, 0.5, 1] then each number x should become + * [x, x], so we default to the behaviour of mapping 0 => 0 of both target + * and container etc. + */ + offsetDefinition = [offset, offset]; + } + else if (typeof offset === "string") { + offset = offset.trim(); + if (offset.includes(" ")) { + offsetDefinition = offset.split(" "); + } + else { + /** + * If we're provided a definition like "100px" then we want to apply + * that only to the top of the target point, leaving the container at 0. + * Whereas a named offset like "end" should be applied to both. + */ + offsetDefinition = [offset, namedEdges[offset] ? offset : `0`]; + } + } + targetPoint = resolveEdge(offsetDefinition[0], targetLength, targetInset); + containerPoint = resolveEdge(offsetDefinition[1], containerLength); + return targetPoint - containerPoint; +} + +const ScrollOffset = { + Enter: [ + [0, 1], + [1, 1], + ], + Exit: [ + [0, 0], + [1, 0], + ], + Any: [ + [1, 0], + [0, 1], + ], + All: [ + [0, 0], + [1, 1], + ], +}; + +const point = { x: 0, y: 0 }; +function getTargetSize(target) { + return "getBBox" in target && target.tagName !== "svg" + ? target.getBBox() + : { width: target.clientWidth, height: target.clientHeight }; +} +function resolveOffsets(container, info, options) { + const { offset: offsetDefinition = ScrollOffset.All } = options; + const { target = container, axis = "y" } = options; + const lengthLabel = axis === "y" ? "height" : "width"; + const inset = target !== container ? calcInset(target, container) : point; + /** + * Measure the target and container. If they're the same thing then we + * use the container's scrollWidth/Height as the target, from there + * all other calculations can remain the same. + */ + const targetSize = target === container + ? { width: container.scrollWidth, height: container.scrollHeight } + : getTargetSize(target); + const containerSize = { + width: container.clientWidth, + height: container.clientHeight, + }; + /** + * Reset the length of the resolved offset array rather than creating a new one. + * TODO: More reusable data structures for targetSize/containerSize would also be good. + */ + info[axis].offset.length = 0; + /** + * Populate the offset array by resolving the user's offset definition into + * a list of pixel scroll offets. + */ + let hasChanged = !info[axis].interpolate; + const numOffsets = offsetDefinition.length; + for (let i = 0; i < numOffsets; i++) { + const offset = resolveOffset(offsetDefinition[i], containerSize[lengthLabel], targetSize[lengthLabel], inset[axis]); + if (!hasChanged && offset !== info[axis].interpolatorOffsets[i]) { + hasChanged = true; + } + info[axis].offset[i] = offset; + } + /** + * If the pixel scroll offsets have changed, create a new interpolator function + * to map scroll value into a progress. + */ + if (hasChanged) { + info[axis].interpolate = motionDom.interpolate(info[axis].offset, motionDom.defaultOffset(offsetDefinition), { clamp: false }); + info[axis].interpolatorOffsets = [...info[axis].offset]; + } + info[axis].progress = motionUtils.clamp(0, 1, info[axis].interpolate(info[axis].current)); +} + +function measure(container, target = container, info) { + /** + * Find inset of target within scrollable container + */ + info.x.targetOffset = 0; + info.y.targetOffset = 0; + if (target !== container) { + let node = target; + while (node && node !== container) { + info.x.targetOffset += node.offsetLeft; + info.y.targetOffset += node.offsetTop; + node = node.offsetParent; + } + } + info.x.targetLength = + target === container ? target.scrollWidth : target.clientWidth; + info.y.targetLength = + target === container ? target.scrollHeight : target.clientHeight; + info.x.containerLength = container.clientWidth; + info.y.containerLength = container.clientHeight; + /** + * In development mode ensure scroll containers aren't position: static as this makes + * it difficult to measure their relative positions. + */ + if (process.env.NODE_ENV !== "production") { + if (container && target && target !== container) { + motionUtils.warnOnce(getComputedStyle(container).position !== "static", "Please ensure that the container has a non-static position, like 'relative', 'fixed', or 'absolute' to ensure scroll offset is calculated correctly."); + } + } +} +function createOnScrollHandler(element, onScroll, info, options = {}) { + return { + measure: (time) => { + measure(element, options.target, info); + updateScrollInfo(element, info, time); + if (options.offset || options.target) { + resolveOffsets(element, info, options); + } + }, + notify: () => onScroll(info), + }; +} + +const scrollListeners = new WeakMap(); +const resizeListeners = new WeakMap(); +const onScrollHandlers = new WeakMap(); +const getEventTarget = (element) => element === document.scrollingElement ? window : element; +function scrollInfo(onScroll, { container = document.scrollingElement, ...options } = {}) { + if (!container) + return motionUtils.noop; + let containerHandlers = onScrollHandlers.get(container); + /** + * Get the onScroll handlers for this container. + * If one isn't found, create a new one. + */ + if (!containerHandlers) { + containerHandlers = new Set(); + onScrollHandlers.set(container, containerHandlers); + } + /** + * Create a new onScroll handler for the provided callback. + */ + const info = createScrollInfo(); + const containerHandler = createOnScrollHandler(container, onScroll, info, options); + containerHandlers.add(containerHandler); + /** + * Check if there's a scroll event listener for this container. + * If not, create one. + */ + if (!scrollListeners.has(container)) { + const measureAll = () => { + for (const handler of containerHandlers) { + handler.measure(motionDom.frameData.timestamp); + } + motionDom.frame.preUpdate(notifyAll); + }; + const notifyAll = () => { + for (const handler of containerHandlers) { + handler.notify(); + } + }; + const listener = () => motionDom.frame.read(measureAll); + scrollListeners.set(container, listener); + const target = getEventTarget(container); + window.addEventListener("resize", listener, { passive: true }); + if (container !== document.documentElement) { + resizeListeners.set(container, motionDom.resize(container, listener)); + } + target.addEventListener("scroll", listener, { passive: true }); + listener(); + } + const listener = scrollListeners.get(container); + motionDom.frame.read(listener, false, true); + return () => { + motionDom.cancelFrame(listener); + /** + * Check if we even have any handlers for this container. + */ + const currentHandlers = onScrollHandlers.get(container); + if (!currentHandlers) + return; + currentHandlers.delete(containerHandler); + if (currentHandlers.size) + return; + /** + * If no more handlers, remove the scroll listener too. + */ + const scrollListener = scrollListeners.get(container); + scrollListeners.delete(container); + if (scrollListener) { + getEventTarget(container).removeEventListener("scroll", scrollListener); + resizeListeners.get(container)?.(); + window.removeEventListener("resize", scrollListener); + } + }; +} + +const timelineCache = new Map(); +function scrollTimelineFallback(options) { + const currentTime = { value: 0 }; + const cancel = scrollInfo((info) => { + currentTime.value = info[options.axis].progress * 100; + }, options); + return { currentTime, cancel }; +} +function getTimeline({ source, container, ...options }) { + const { axis } = options; + if (source) + container = source; + const containerCache = timelineCache.get(container) ?? new Map(); + timelineCache.set(container, containerCache); + const targetKey = options.target ?? "self"; + const targetCache = containerCache.get(targetKey) ?? {}; + const axisKey = axis + (options.offset ?? []).join(","); + if (!targetCache[axisKey]) { + targetCache[axisKey] = + !options.target && motionDom.supportsScrollTimeline() + ? new ScrollTimeline({ source: container, axis }) + : scrollTimelineFallback({ container, ...options }); + } + return targetCache[axisKey]; +} + +function attachToAnimation(animation, options) { + const timeline = getTimeline(options); + return animation.attachTimeline({ + timeline: options.target ? undefined : timeline, + observe: (valueAnimation) => { + valueAnimation.pause(); + return motionDom.observeTimeline((progress) => { + valueAnimation.time = valueAnimation.duration * progress; + }, timeline); + }, + }); +} + +/** + * If the onScroll function has two arguments, it's expecting + * more specific information about the scroll from scrollInfo. + */ +function isOnScrollWithInfo(onScroll) { + return onScroll.length === 2; +} +function attachToFunction(onScroll, options) { + if (isOnScrollWithInfo(onScroll)) { + return scrollInfo((info) => { + onScroll(info[options.axis].progress, info); + }, options); + } + else { + return motionDom.observeTimeline(onScroll, getTimeline(options)); + } +} + +function scroll(onScroll, { axis = "y", container = document.scrollingElement, ...options } = {}) { + if (!container) + return motionUtils.noop; + const optionsWithDefaults = { axis, container, ...options }; + return typeof onScroll === "function" + ? attachToFunction(onScroll, optionsWithDefaults) + : attachToAnimation(onScroll, optionsWithDefaults); +} + +const thresholds = { + some: 0, + all: 1, +}; +function inView(elementOrSelector, onStart, { root, margin: rootMargin, amount = "some" } = {}) { + const elements = motionDom.resolveElements(elementOrSelector); + const activeIntersections = new WeakMap(); + const onIntersectionChange = (entries) => { + entries.forEach((entry) => { + const onEnd = activeIntersections.get(entry.target); + /** + * If there's no change to the intersection, we don't need to + * do anything here. + */ + if (entry.isIntersecting === Boolean(onEnd)) + return; + if (entry.isIntersecting) { + const newOnEnd = onStart(entry.target, entry); + if (typeof newOnEnd === "function") { + activeIntersections.set(entry.target, newOnEnd); + } + else { + observer.unobserve(entry.target); + } + } + else if (typeof onEnd === "function") { + onEnd(entry); + activeIntersections.delete(entry.target); + } + }); + }; + const observer = new IntersectionObserver(onIntersectionChange, { + root, + rootMargin, + threshold: typeof amount === "number" ? amount : thresholds[amount], + }); + elements.forEach((element) => observer.observe(element)); + return () => observer.disconnect(); +} + +/** + * Timeout defined in ms + */ +function delay(callback, timeout) { + const start = motionDom.time.now(); + const checkElapsed = ({ timestamp }) => { + const elapsed = timestamp - start; + if (elapsed >= timeout) { + motionDom.cancelFrame(checkElapsed); + callback(elapsed - timeout); + } + }; + motionDom.frame.setup(checkElapsed, true); + return () => motionDom.cancelFrame(checkElapsed); +} +function delayInSeconds(callback, timeout) { + return delay(callback, motionUtils.secondsToMilliseconds(timeout)); +} + +const distance = (a, b) => Math.abs(a - b); +function distance2D(a, b) { + // Multi-dimensional + const xDelta = distance(a.x, b.x); + const yDelta = distance(a.y, b.y); + return Math.sqrt(xDelta ** 2 + yDelta ** 2); +} + +exports.animate = animate; +exports.animateMini = animateMini; +exports.createScopedAnimate = createScopedAnimate; +exports.delay = delayInSeconds; +exports.distance = distance; +exports.distance2D = distance2D; +exports.inView = inView; +exports.scroll = scroll; +exports.scrollInfo = scrollInfo; +Object.keys(motionDom).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return motionDom[k]; } + }); +}); +Object.keys(motionUtils).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return motionUtils[k]; } + }); +}); diff --git a/frontend/node_modules/framer-motion/dist/cjs/feature-bundle-PNQ-8QDo.js b/frontend/node_modules/framer-motion/dist/cjs/feature-bundle-PNQ-8QDo.js new file mode 100644 index 0000000000000000000000000000000000000000..ec42af912f267e070bc62e8baadc84143227a5e5 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/cjs/feature-bundle-PNQ-8QDo.js @@ -0,0 +1,6280 @@ +'use strict'; + +var React = require('react'); +var motionDom = require('motion-dom'); +var motionUtils = require('motion-utils'); +var jsxRuntime = require('react/jsx-runtime'); + +const LayoutGroupContext = React.createContext({}); + +/** + * Creates a constant value over the lifecycle of a component. + * + * Even if `useMemo` is provided an empty array as its final argument, it doesn't offer + * a guarantee that it won't re-run for performance reasons later on. By using `useConstant` + * you can ensure that initialisers don't execute twice or more. + */ +function useConstant(init) { + const ref = React.useRef(null); + if (ref.current === null) { + ref.current = init(); + } + return ref.current; +} + +const isBrowser = typeof window !== "undefined"; + +const useIsomorphicLayoutEffect = isBrowser ? React.useLayoutEffect : React.useEffect; + +/** + * @public + */ +const PresenceContext = +/* @__PURE__ */ React.createContext(null); + +/** + * @public + */ +const MotionConfigContext = React.createContext({ + transformPagePoint: (p) => p, + isStatic: false, + reducedMotion: "never", +}); + +/** + * When a component is the child of `AnimatePresence`, it can use `usePresence` + * to access information about whether it's still present in the React tree. + * + * ```jsx + * import { usePresence } from "framer-motion" + * + * export const Component = () => { + * const [isPresent, safeToRemove] = usePresence() + * + * useEffect(() => { + * !isPresent && setTimeout(safeToRemove, 1000) + * }, [isPresent]) + * + * return
+ * } + * ``` + * + * If `isPresent` is `false`, it means that a component has been removed the tree, but + * `AnimatePresence` won't really remove it until `safeToRemove` has been called. + * + * @public + */ +function usePresence(subscribe = true) { + const context = React.useContext(PresenceContext); + if (context === null) + return [true, null]; + const { isPresent, onExitComplete, register } = context; + // It's safe to call the following hooks conditionally (after an early return) because the context will always + // either be null or non-null for the lifespan of the component. + const id = React.useId(); + React.useEffect(() => { + if (subscribe) { + return register(id); + } + }, [subscribe]); + const safeToRemove = React.useCallback(() => subscribe && onExitComplete && onExitComplete(id), [id, onExitComplete, subscribe]); + return !isPresent && onExitComplete ? [false, safeToRemove] : [true]; +} +/** + * Similar to `usePresence`, except `useIsPresent` simply returns whether or not the component is present. + * There is no `safeToRemove` function. + * + * ```jsx + * import { useIsPresent } from "framer-motion" + * + * export const Component = () => { + * const isPresent = useIsPresent() + * + * useEffect(() => { + * !isPresent && console.log("I've been removed!") + * }, [isPresent]) + * + * return
+ * } + * ``` + * + * @public + */ +function useIsPresent() { + return isPresent(React.useContext(PresenceContext)); +} +function isPresent(context) { + return context === null ? true : context.isPresent; +} + +const SCALE_PRECISION = 0.0001; +const SCALE_MIN = 1 - SCALE_PRECISION; +const SCALE_MAX = 1 + SCALE_PRECISION; +const TRANSLATE_PRECISION = 0.01; +const TRANSLATE_MIN = 0 - TRANSLATE_PRECISION; +const TRANSLATE_MAX = 0 + TRANSLATE_PRECISION; +function calcLength(axis) { + return axis.max - axis.min; +} +function isNear(value, target, maxDistance) { + return Math.abs(value - target) <= maxDistance; +} +function calcAxisDelta(delta, source, target, origin = 0.5) { + delta.origin = origin; + delta.originPoint = motionDom.mixNumber(source.min, source.max, delta.origin); + delta.scale = calcLength(target) / calcLength(source); + delta.translate = + motionDom.mixNumber(target.min, target.max, delta.origin) - delta.originPoint; + if ((delta.scale >= SCALE_MIN && delta.scale <= SCALE_MAX) || + isNaN(delta.scale)) { + delta.scale = 1.0; + } + if ((delta.translate >= TRANSLATE_MIN && + delta.translate <= TRANSLATE_MAX) || + isNaN(delta.translate)) { + delta.translate = 0.0; + } +} +function calcBoxDelta(delta, source, target, origin) { + calcAxisDelta(delta.x, source.x, target.x, origin ? origin.originX : undefined); + calcAxisDelta(delta.y, source.y, target.y, origin ? origin.originY : undefined); +} +function calcRelativeAxis(target, relative, parent) { + target.min = parent.min + relative.min; + target.max = target.min + calcLength(relative); +} +function calcRelativeBox(target, relative, parent) { + calcRelativeAxis(target.x, relative.x, parent.x); + calcRelativeAxis(target.y, relative.y, parent.y); +} +function calcRelativeAxisPosition(target, layout, parent) { + target.min = layout.min - parent.min; + target.max = target.min + calcLength(layout); +} +function calcRelativePosition(target, layout, parent) { + calcRelativeAxisPosition(target.x, layout.x, parent.x); + calcRelativeAxisPosition(target.y, layout.y, parent.y); +} + +const isNotNull = (value) => value !== null; +function getFinalKeyframe(keyframes, { repeat, repeatType = "loop" }, finalKeyframe) { + const resolvedKeyframes = keyframes.filter(isNotNull); + const index = repeat && repeatType !== "loop" && repeat % 2 === 1 + ? 0 + : resolvedKeyframes.length - 1; + return !index || finalKeyframe === undefined + ? resolvedKeyframes[index] + : finalKeyframe; +} + +const underDampedSpring = { + type: "spring", + stiffness: 500, + damping: 25, + restSpeed: 10, +}; +const criticallyDampedSpring = (target) => ({ + type: "spring", + stiffness: 550, + damping: target === 0 ? 2 * Math.sqrt(550) : 30, + restSpeed: 10, +}); +const keyframesTransition = { + type: "keyframes", + duration: 0.8, +}; +/** + * Default easing curve is a slightly shallower version of + * the default browser easing curve. + */ +const ease = { + type: "keyframes", + ease: [0.25, 0.1, 0.35, 1], + duration: 0.3, +}; +const getDefaultTransition = (valueKey, { keyframes }) => { + if (keyframes.length > 2) { + return keyframesTransition; + } + else if (motionDom.transformProps.has(valueKey)) { + return valueKey.startsWith("scale") + ? criticallyDampedSpring(keyframes[1]) + : underDampedSpring; + } + return ease; +}; + +/** + * Decide whether a transition is defined on a given Transition. + * This filters out orchestration options and returns true + * if any options are left. + */ +function isTransitionDefined({ when, delay: _delay, delayChildren, staggerChildren, staggerDirection, repeat, repeatType, repeatDelay, from, elapsed, ...transition }) { + return !!Object.keys(transition).length; +} + +const animateMotionValue = (name, value, target, transition = {}, element, isHandoff) => (onComplete) => { + const valueTransition = motionDom.getValueTransition(transition, name) || {}; + /** + * Most transition values are currently completely overwritten by value-specific + * transitions. In the future it'd be nicer to blend these transitions. But for now + * delay actually does inherit from the root transition if not value-specific. + */ + const delay = valueTransition.delay || transition.delay || 0; + /** + * Elapsed isn't a public transition option but can be passed through from + * optimized appear effects in milliseconds. + */ + let { elapsed = 0 } = transition; + elapsed = elapsed - motionUtils.secondsToMilliseconds(delay); + const options = { + keyframes: Array.isArray(target) ? target : [null, target], + ease: "easeOut", + velocity: value.getVelocity(), + ...valueTransition, + delay: -elapsed, + onUpdate: (v) => { + value.set(v); + valueTransition.onUpdate && valueTransition.onUpdate(v); + }, + onComplete: () => { + onComplete(); + valueTransition.onComplete && valueTransition.onComplete(); + }, + name, + motionValue: value, + element: isHandoff ? undefined : element, + }; + /** + * If there's no transition defined for this value, we can generate + * unique transition settings for this value. + */ + if (!isTransitionDefined(valueTransition)) { + Object.assign(options, getDefaultTransition(name, options)); + } + /** + * Both WAAPI and our internal animation functions use durations + * as defined by milliseconds, while our external API defines them + * as seconds. + */ + options.duration && (options.duration = motionUtils.secondsToMilliseconds(options.duration)); + options.repeatDelay && (options.repeatDelay = motionUtils.secondsToMilliseconds(options.repeatDelay)); + /** + * Support deprecated way to set initial value. Prefer keyframe syntax. + */ + if (options.from !== undefined) { + options.keyframes[0] = options.from; + } + let shouldSkip = false; + if (options.type === false || + (options.duration === 0 && !options.repeatDelay)) { + motionDom.makeAnimationInstant(options); + if (options.delay === 0) { + shouldSkip = true; + } + } + if (motionUtils.MotionGlobalConfig.instantAnimations || + motionUtils.MotionGlobalConfig.skipAnimations) { + shouldSkip = true; + motionDom.makeAnimationInstant(options); + options.delay = 0; + } + /** + * If the transition type or easing has been explicitly set by the user + * then we don't want to allow flattening the animation. + */ + options.allowFlatten = !valueTransition.type && !valueTransition.ease; + /** + * If we can or must skip creating the animation, and apply only + * the final keyframe, do so. We also check once keyframes are resolved but + * this early check prevents the need to create an animation at all. + */ + if (shouldSkip && !isHandoff && value.get() !== undefined) { + const finalKeyframe = getFinalKeyframe(options.keyframes, valueTransition); + if (finalKeyframe !== undefined) { + motionDom.frame.update(() => { + options.onUpdate(finalKeyframe); + options.onComplete(); + }); + return; + } + } + return valueTransition.isSync + ? new motionDom.JSAnimation(options) + : new motionDom.AsyncMotionValueAnimation(options); +}; + +function animateSingleValue(value, keyframes, options) { + const motionValue = motionDom.isMotionValue(value) ? value : motionDom.motionValue(value); + motionValue.start(animateMotionValue("", motionValue, keyframes, options)); + return motionValue.animation; +} + +/** + * Convert camelCase to dash-case properties. + */ +const camelToDash = (str) => str.replace(/([a-z])([A-Z])/gu, "$1-$2").toLowerCase(); + +const optimizedAppearDataId = "framerAppearId"; +const optimizedAppearDataAttribute = "data-" + camelToDash(optimizedAppearDataId); + +function getOptimisedAppearId(visualElement) { + return visualElement.props[optimizedAppearDataAttribute]; +} + +const compareByDepth = (a, b) => a.depth - b.depth; + +class FlatTree { + constructor() { + this.children = []; + this.isDirty = false; + } + add(child) { + motionUtils.addUniqueItem(this.children, child); + this.isDirty = true; + } + remove(child) { + motionUtils.removeItem(this.children, child); + this.isDirty = true; + } + forEach(callback) { + this.isDirty && this.children.sort(compareByDepth); + this.isDirty = false; + this.children.forEach(callback); + } +} + +/** + * Timeout defined in ms + */ +function delay(callback, timeout) { + const start = motionDom.time.now(); + const checkElapsed = ({ timestamp }) => { + const elapsed = timestamp - start; + if (elapsed >= timeout) { + motionDom.cancelFrame(checkElapsed); + callback(elapsed - timeout); + } + }; + motionDom.frame.setup(checkElapsed, true); + return () => motionDom.cancelFrame(checkElapsed); +} + +/** + * If the provided value is a MotionValue, this returns the actual value, otherwise just the value itself + * + * TODO: Remove and move to library + */ +function resolveMotionValue(value) { + return motionDom.isMotionValue(value) ? value.get() : value; +} + +const borders = ["TopLeft", "TopRight", "BottomLeft", "BottomRight"]; +const numBorders = borders.length; +const asNumber = (value) => typeof value === "string" ? parseFloat(value) : value; +const isPx = (value) => typeof value === "number" || motionDom.px.test(value); +function mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnlyMember) { + if (shouldCrossfadeOpacity) { + target.opacity = motionDom.mixNumber(0, lead.opacity ?? 1, easeCrossfadeIn(progress)); + target.opacityExit = motionDom.mixNumber(follow.opacity ?? 1, 0, easeCrossfadeOut(progress)); + } + else if (isOnlyMember) { + target.opacity = motionDom.mixNumber(follow.opacity ?? 1, lead.opacity ?? 1, progress); + } + /** + * Mix border radius + */ + for (let i = 0; i < numBorders; i++) { + const borderLabel = `border${borders[i]}Radius`; + let followRadius = getRadius(follow, borderLabel); + let leadRadius = getRadius(lead, borderLabel); + if (followRadius === undefined && leadRadius === undefined) + continue; + followRadius || (followRadius = 0); + leadRadius || (leadRadius = 0); + const canMix = followRadius === 0 || + leadRadius === 0 || + isPx(followRadius) === isPx(leadRadius); + if (canMix) { + target[borderLabel] = Math.max(motionDom.mixNumber(asNumber(followRadius), asNumber(leadRadius), progress), 0); + if (motionDom.percent.test(leadRadius) || motionDom.percent.test(followRadius)) { + target[borderLabel] += "%"; + } + } + else { + target[borderLabel] = leadRadius; + } + } + /** + * Mix rotation + */ + if (follow.rotate || lead.rotate) { + target.rotate = motionDom.mixNumber(follow.rotate || 0, lead.rotate || 0, progress); + } +} +function getRadius(values, radiusName) { + return values[radiusName] !== undefined + ? values[radiusName] + : values.borderRadius; +} +// /** +// * We only want to mix the background color if there's a follow element +// * that we're not crossfading opacity between. For instance with switch +// * AnimateSharedLayout animations, this helps the illusion of a continuous +// * element being animated but also cuts down on the number of paints triggered +// * for elements where opacity is doing that work for us. +// */ +// if ( +// !hasFollowElement && +// latestLeadValues.backgroundColor && +// latestFollowValues.backgroundColor +// ) { +// /** +// * This isn't ideal performance-wise as mixColor is creating a new function every frame. +// * We could probably create a mixer that runs at the start of the animation but +// * the idea behind the crossfader is that it runs dynamically between two potentially +// * changing targets (ie opacity or borderRadius may be animating independently via variants) +// */ +// leadState.backgroundColor = followState.backgroundColor = mixColor( +// latestFollowValues.backgroundColor as string, +// latestLeadValues.backgroundColor as string +// )(p) +// } +const easeCrossfadeIn = /*@__PURE__*/ compress(0, 0.5, motionUtils.circOut); +const easeCrossfadeOut = /*@__PURE__*/ compress(0.5, 0.95, motionUtils.noop); +function compress(min, max, easing) { + return (p) => { + // Could replace ifs with clamp + if (p < min) + return 0; + if (p > max) + return 1; + return easing(motionUtils.progress(min, max, p)); + }; +} + +/** + * Reset an axis to the provided origin box. + * + * This is a mutative operation. + */ +function copyAxisInto(axis, originAxis) { + axis.min = originAxis.min; + axis.max = originAxis.max; +} +/** + * Reset a box to the provided origin box. + * + * This is a mutative operation. + */ +function copyBoxInto(box, originBox) { + copyAxisInto(box.x, originBox.x); + copyAxisInto(box.y, originBox.y); +} +/** + * Reset a delta to the provided origin box. + * + * This is a mutative operation. + */ +function copyAxisDeltaInto(delta, originDelta) { + delta.translate = originDelta.translate; + delta.scale = originDelta.scale; + delta.originPoint = originDelta.originPoint; + delta.origin = originDelta.origin; +} + +function isIdentityScale(scale) { + return scale === undefined || scale === 1; +} +function hasScale({ scale, scaleX, scaleY }) { + return (!isIdentityScale(scale) || + !isIdentityScale(scaleX) || + !isIdentityScale(scaleY)); +} +function hasTransform(values) { + return (hasScale(values) || + has2DTranslate(values) || + values.z || + values.rotate || + values.rotateX || + values.rotateY || + values.skewX || + values.skewY); +} +function has2DTranslate(values) { + return is2DTranslate(values.x) || is2DTranslate(values.y); +} +function is2DTranslate(value) { + return value && value !== "0%"; +} + +/** + * Scales a point based on a factor and an originPoint + */ +function scalePoint(point, scale, originPoint) { + const distanceFromOrigin = point - originPoint; + const scaled = scale * distanceFromOrigin; + return originPoint + scaled; +} +/** + * Applies a translate/scale delta to a point + */ +function applyPointDelta(point, translate, scale, originPoint, boxScale) { + if (boxScale !== undefined) { + point = scalePoint(point, boxScale, originPoint); + } + return scalePoint(point, scale, originPoint) + translate; +} +/** + * Applies a translate/scale delta to an axis + */ +function applyAxisDelta(axis, translate = 0, scale = 1, originPoint, boxScale) { + axis.min = applyPointDelta(axis.min, translate, scale, originPoint, boxScale); + axis.max = applyPointDelta(axis.max, translate, scale, originPoint, boxScale); +} +/** + * Applies a translate/scale delta to a box + */ +function applyBoxDelta(box, { x, y }) { + applyAxisDelta(box.x, x.translate, x.scale, x.originPoint); + applyAxisDelta(box.y, y.translate, y.scale, y.originPoint); +} +const TREE_SCALE_SNAP_MIN = 0.999999999999; +const TREE_SCALE_SNAP_MAX = 1.0000000000001; +/** + * Apply a tree of deltas to a box. We do this to calculate the effect of all the transforms + * in a tree upon our box before then calculating how to project it into our desired viewport-relative box + * + * This is the final nested loop within updateLayoutDelta for future refactoring + */ +function applyTreeDeltas(box, treeScale, treePath, isSharedTransition = false) { + const treeLength = treePath.length; + if (!treeLength) + return; + // Reset the treeScale + treeScale.x = treeScale.y = 1; + let node; + let delta; + for (let i = 0; i < treeLength; i++) { + node = treePath[i]; + delta = node.projectionDelta; + /** + * TODO: Prefer to remove this, but currently we have motion components with + * display: contents in Framer. + */ + const { visualElement } = node.options; + if (visualElement && + visualElement.props.style && + visualElement.props.style.display === "contents") { + continue; + } + if (isSharedTransition && + node.options.layoutScroll && + node.scroll && + node !== node.root) { + transformBox(box, { + x: -node.scroll.offset.x, + y: -node.scroll.offset.y, + }); + } + if (delta) { + // Incoporate each ancestor's scale into a culmulative treeScale for this component + treeScale.x *= delta.x.scale; + treeScale.y *= delta.y.scale; + // Apply each ancestor's calculated delta into this component's recorded layout box + applyBoxDelta(box, delta); + } + if (isSharedTransition && hasTransform(node.latestValues)) { + transformBox(box, node.latestValues); + } + } + /** + * Snap tree scale back to 1 if it's within a non-perceivable threshold. + * This will help reduce useless scales getting rendered. + */ + if (treeScale.x < TREE_SCALE_SNAP_MAX && + treeScale.x > TREE_SCALE_SNAP_MIN) { + treeScale.x = 1.0; + } + if (treeScale.y < TREE_SCALE_SNAP_MAX && + treeScale.y > TREE_SCALE_SNAP_MIN) { + treeScale.y = 1.0; + } +} +function translateAxis(axis, distance) { + axis.min = axis.min + distance; + axis.max = axis.max + distance; +} +/** + * Apply a transform to an axis from the latest resolved motion values. + * This function basically acts as a bridge between a flat motion value map + * and applyAxisDelta + */ +function transformAxis(axis, axisTranslate, axisScale, boxScale, axisOrigin = 0.5) { + const originPoint = motionDom.mixNumber(axis.min, axis.max, axisOrigin); + // Apply the axis delta to the final axis + applyAxisDelta(axis, axisTranslate, axisScale, originPoint, boxScale); +} +/** + * Apply a transform to a box from the latest resolved motion values. + */ +function transformBox(box, transform) { + transformAxis(box.x, transform.x, transform.scaleX, transform.scale, transform.originX); + transformAxis(box.y, transform.y, transform.scaleY, transform.scale, transform.originY); +} + +/** + * Remove a delta from a point. This is essentially the steps of applyPointDelta in reverse + */ +function removePointDelta(point, translate, scale, originPoint, boxScale) { + point -= translate; + point = scalePoint(point, 1 / scale, originPoint); + if (boxScale !== undefined) { + point = scalePoint(point, 1 / boxScale, originPoint); + } + return point; +} +/** + * Remove a delta from an axis. This is essentially the steps of applyAxisDelta in reverse + */ +function removeAxisDelta(axis, translate = 0, scale = 1, origin = 0.5, boxScale, originAxis = axis, sourceAxis = axis) { + if (motionDom.percent.test(translate)) { + translate = parseFloat(translate); + const relativeProgress = motionDom.mixNumber(sourceAxis.min, sourceAxis.max, translate / 100); + translate = relativeProgress - sourceAxis.min; + } + if (typeof translate !== "number") + return; + let originPoint = motionDom.mixNumber(originAxis.min, originAxis.max, origin); + if (axis === originAxis) + originPoint -= translate; + axis.min = removePointDelta(axis.min, translate, scale, originPoint, boxScale); + axis.max = removePointDelta(axis.max, translate, scale, originPoint, boxScale); +} +/** + * Remove a transforms from an axis. This is essentially the steps of applyAxisTransforms in reverse + * and acts as a bridge between motion values and removeAxisDelta + */ +function removeAxisTransforms(axis, transforms, [key, scaleKey, originKey], origin, sourceAxis) { + removeAxisDelta(axis, transforms[key], transforms[scaleKey], transforms[originKey], transforms.scale, origin, sourceAxis); +} +/** + * The names of the motion values we want to apply as translation, scale and origin. + */ +const xKeys = ["x", "scaleX", "originX"]; +const yKeys = ["y", "scaleY", "originY"]; +/** + * Remove a transforms from an box. This is essentially the steps of applyAxisBox in reverse + * and acts as a bridge between motion values and removeAxisDelta + */ +function removeBoxTransforms(box, transforms, originBox, sourceBox) { + removeAxisTransforms(box.x, transforms, xKeys, originBox ? originBox.x : undefined, sourceBox ? sourceBox.x : undefined); + removeAxisTransforms(box.y, transforms, yKeys, originBox ? originBox.y : undefined, sourceBox ? sourceBox.y : undefined); +} + +const createAxisDelta = () => ({ + translate: 0, + scale: 1, + origin: 0, + originPoint: 0, +}); +const createDelta = () => ({ + x: createAxisDelta(), + y: createAxisDelta(), +}); +const createAxis = () => ({ min: 0, max: 0 }); +const createBox = () => ({ + x: createAxis(), + y: createAxis(), +}); + +function isAxisDeltaZero(delta) { + return delta.translate === 0 && delta.scale === 1; +} +function isDeltaZero(delta) { + return isAxisDeltaZero(delta.x) && isAxisDeltaZero(delta.y); +} +function axisEquals(a, b) { + return a.min === b.min && a.max === b.max; +} +function boxEquals(a, b) { + return axisEquals(a.x, b.x) && axisEquals(a.y, b.y); +} +function axisEqualsRounded(a, b) { + return (Math.round(a.min) === Math.round(b.min) && + Math.round(a.max) === Math.round(b.max)); +} +function boxEqualsRounded(a, b) { + return axisEqualsRounded(a.x, b.x) && axisEqualsRounded(a.y, b.y); +} +function aspectRatio(box) { + return calcLength(box.x) / calcLength(box.y); +} +function axisDeltaEquals(a, b) { + return (a.translate === b.translate && + a.scale === b.scale && + a.originPoint === b.originPoint); +} + +class NodeStack { + constructor() { + this.members = []; + } + add(node) { + motionUtils.addUniqueItem(this.members, node); + node.scheduleRender(); + } + remove(node) { + motionUtils.removeItem(this.members, node); + if (node === this.prevLead) { + this.prevLead = undefined; + } + if (node === this.lead) { + const prevLead = this.members[this.members.length - 1]; + if (prevLead) { + this.promote(prevLead); + } + } + } + relegate(node) { + const indexOfNode = this.members.findIndex((member) => node === member); + if (indexOfNode === 0) + return false; + /** + * Find the next projection node that is present + */ + let prevLead; + for (let i = indexOfNode; i >= 0; i--) { + const member = this.members[i]; + if (member.isPresent !== false) { + prevLead = member; + break; + } + } + if (prevLead) { + this.promote(prevLead); + return true; + } + else { + return false; + } + } + promote(node, preserveFollowOpacity) { + const prevLead = this.lead; + if (node === prevLead) + return; + this.prevLead = prevLead; + this.lead = node; + node.show(); + if (prevLead) { + prevLead.instance && prevLead.scheduleRender(); + node.scheduleRender(); + node.resumeFrom = prevLead; + if (preserveFollowOpacity) { + node.resumeFrom.preserveOpacity = true; + } + if (prevLead.snapshot) { + node.snapshot = prevLead.snapshot; + node.snapshot.latestValues = + prevLead.animationValues || prevLead.latestValues; + } + if (node.root && node.root.isUpdating) { + node.isLayoutDirty = true; + } + const { crossfade } = node.options; + if (crossfade === false) { + prevLead.hide(); + } + /** + * TODO: + * - Test border radius when previous node was deleted + * - boxShadow mixing + * - Shared between element A in scrolled container and element B (scroll stays the same or changes) + * - Shared between element A in transformed container and element B (transform stays the same or changes) + * - Shared between element A in scrolled page and element B (scroll stays the same or changes) + * --- + * - Crossfade opacity of root nodes + * - layoutId changes after animation + * - layoutId changes mid animation + */ + } + } + exitAnimationComplete() { + this.members.forEach((node) => { + const { options, resumingFrom } = node; + options.onExitComplete && options.onExitComplete(); + if (resumingFrom) { + resumingFrom.options.onExitComplete && + resumingFrom.options.onExitComplete(); + } + }); + } + scheduleRender() { + this.members.forEach((node) => { + node.instance && node.scheduleRender(false); + }); + } + /** + * Clear any leads that have been removed this render to prevent them from being + * used in future animations and to prevent memory leaks + */ + removeLeadSnapshot() { + if (this.lead && this.lead.snapshot) { + this.lead.snapshot = undefined; + } + } +} + +const scaleCorrectors = {}; +function addScaleCorrector(correctors) { + for (const key in correctors) { + scaleCorrectors[key] = correctors[key]; + if (motionDom.isCSSVariableName(key)) { + scaleCorrectors[key].isCSSVariable = true; + } + } +} + +function buildProjectionTransform(delta, treeScale, latestTransform) { + let transform = ""; + /** + * The translations we use to calculate are always relative to the viewport coordinate space. + * But when we apply scales, we also scale the coordinate space of an element and its children. + * For instance if we have a treeScale (the culmination of all parent scales) of 0.5 and we need + * to move an element 100 pixels, we actually need to move it 200 in within that scaled space. + */ + const xTranslate = delta.x.translate / treeScale.x; + const yTranslate = delta.y.translate / treeScale.y; + const zTranslate = latestTransform?.z || 0; + if (xTranslate || yTranslate || zTranslate) { + transform = `translate3d(${xTranslate}px, ${yTranslate}px, ${zTranslate}px) `; + } + /** + * Apply scale correction for the tree transform. + * This will apply scale to the screen-orientated axes. + */ + if (treeScale.x !== 1 || treeScale.y !== 1) { + transform += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `; + } + if (latestTransform) { + const { transformPerspective, rotate, rotateX, rotateY, skewX, skewY } = latestTransform; + if (transformPerspective) + transform = `perspective(${transformPerspective}px) ${transform}`; + if (rotate) + transform += `rotate(${rotate}deg) `; + if (rotateX) + transform += `rotateX(${rotateX}deg) `; + if (rotateY) + transform += `rotateY(${rotateY}deg) `; + if (skewX) + transform += `skewX(${skewX}deg) `; + if (skewY) + transform += `skewY(${skewY}deg) `; + } + /** + * Apply scale to match the size of the element to the size we want it. + * This will apply scale to the element-orientated axes. + */ + const elementScaleX = delta.x.scale * treeScale.x; + const elementScaleY = delta.y.scale * treeScale.y; + if (elementScaleX !== 1 || elementScaleY !== 1) { + transform += `scale(${elementScaleX}, ${elementScaleY})`; + } + return transform || "none"; +} + +function eachAxis(callback) { + return [callback("x"), callback("y")]; +} + +/** + * This should only ever be modified on the client otherwise it'll + * persist through server requests. If we need instanced states we + * could lazy-init via root. + */ +const globalProjectionState = { + /** + * Global flag as to whether the tree has animated since the last time + * we resized the window + */ + hasAnimatedSinceResize: true, + /** + * We set this to true once, on the first update. Any nodes added to the tree beyond that + * update will be given a `data-projection-id` attribute. + */ + hasEverUpdated: false, +}; + +const metrics = { + nodes: 0, + calculatedTargetDeltas: 0, + calculatedProjections: 0, +}; +const transformAxes = ["", "X", "Y", "Z"]; +/** + * We use 1000 as the animation target as 0-1000 maps better to pixels than 0-1 + * which has a noticeable difference in spring animations + */ +const animationTarget = 1000; +let id$1 = 0; +function resetDistortingTransform(key, visualElement, values, sharedAnimationValues) { + const { latestValues } = visualElement; + // Record the distorting transform and then temporarily set it to 0 + if (latestValues[key]) { + values[key] = latestValues[key]; + visualElement.setStaticValue(key, 0); + if (sharedAnimationValues) { + sharedAnimationValues[key] = 0; + } + } +} +function cancelTreeOptimisedTransformAnimations(projectionNode) { + projectionNode.hasCheckedOptimisedAppear = true; + if (projectionNode.root === projectionNode) + return; + const { visualElement } = projectionNode.options; + if (!visualElement) + return; + const appearId = getOptimisedAppearId(visualElement); + if (window.MotionHasOptimisedAnimation(appearId, "transform")) { + const { layout, layoutId } = projectionNode.options; + window.MotionCancelOptimisedAnimation(appearId, "transform", motionDom.frame, !(layout || layoutId)); + } + const { parent } = projectionNode; + if (parent && !parent.hasCheckedOptimisedAppear) { + cancelTreeOptimisedTransformAnimations(parent); + } +} +function createProjectionNode$1({ attachResizeListener, defaultParent, measureScroll, checkIsScrollRoot, resetTransform, }) { + return class ProjectionNode { + constructor(latestValues = {}, parent = defaultParent?.()) { + /** + * A unique ID generated for every projection node. + */ + this.id = id$1++; + /** + * An id that represents a unique session instigated by startUpdate. + */ + this.animationId = 0; + this.animationCommitId = 0; + /** + * A Set containing all this component's children. This is used to iterate + * through the children. + * + * TODO: This could be faster to iterate as a flat array stored on the root node. + */ + this.children = new Set(); + /** + * Options for the node. We use this to configure what kind of layout animations + * we should perform (if any). + */ + this.options = {}; + /** + * We use this to detect when its safe to shut down part of a projection tree. + * We have to keep projecting children for scale correction and relative projection + * until all their parents stop performing layout animations. + */ + this.isTreeAnimating = false; + this.isAnimationBlocked = false; + /** + * Flag to true if we think this layout has been changed. We can't always know this, + * currently we set it to true every time a component renders, or if it has a layoutDependency + * if that has changed between renders. Additionally, components can be grouped by LayoutGroup + * and if one node is dirtied, they all are. + */ + this.isLayoutDirty = false; + /** + * Flag to true if we think the projection calculations for this node needs + * recalculating as a result of an updated transform or layout animation. + */ + this.isProjectionDirty = false; + /** + * Flag to true if the layout *or* transform has changed. This then gets propagated + * throughout the projection tree, forcing any element below to recalculate on the next frame. + */ + this.isSharedProjectionDirty = false; + /** + * Flag transform dirty. This gets propagated throughout the whole tree but is only + * respected by shared nodes. + */ + this.isTransformDirty = false; + /** + * Block layout updates for instant layout transitions throughout the tree. + */ + this.updateManuallyBlocked = false; + this.updateBlockedByResize = false; + /** + * Set to true between the start of the first `willUpdate` call and the end of the `didUpdate` + * call. + */ + this.isUpdating = false; + /** + * If this is an SVG element we currently disable projection transforms + */ + this.isSVG = false; + /** + * Flag to true (during promotion) if a node doing an instant layout transition needs to reset + * its projection styles. + */ + this.needsReset = false; + /** + * Flags whether this node should have its transform reset prior to measuring. + */ + this.shouldResetTransform = false; + /** + * Store whether this node has been checked for optimised appear animations. As + * effects fire bottom-up, and we want to look up the tree for appear animations, + * this makes sure we only check each path once, stopping at nodes that + * have already been checked. + */ + this.hasCheckedOptimisedAppear = false; + /** + * An object representing the calculated contextual/accumulated/tree scale. + * This will be used to scale calculcated projection transforms, as these are + * calculated in screen-space but need to be scaled for elements to layoutly + * make it to their calculated destinations. + * + * TODO: Lazy-init + */ + this.treeScale = { x: 1, y: 1 }; + /** + * + */ + this.eventHandlers = new Map(); + this.hasTreeAnimated = false; + // Note: Currently only running on root node + this.updateScheduled = false; + this.scheduleUpdate = () => this.update(); + this.projectionUpdateScheduled = false; + this.checkUpdateFailed = () => { + if (this.isUpdating) { + this.isUpdating = false; + this.clearAllSnapshots(); + } + }; + /** + * This is a multi-step process as shared nodes might be of different depths. Nodes + * are sorted by depth order, so we need to resolve the entire tree before moving to + * the next step. + */ + this.updateProjection = () => { + this.projectionUpdateScheduled = false; + /** + * Reset debug counts. Manually resetting rather than creating a new + * object each frame. + */ + if (motionDom.statsBuffer.value) { + metrics.nodes = + metrics.calculatedTargetDeltas = + metrics.calculatedProjections = + 0; + } + this.nodes.forEach(propagateDirtyNodes); + this.nodes.forEach(resolveTargetDelta); + this.nodes.forEach(calcProjection); + this.nodes.forEach(cleanDirtyNodes); + if (motionDom.statsBuffer.addProjectionMetrics) { + motionDom.statsBuffer.addProjectionMetrics(metrics); + } + }; + /** + * Frame calculations + */ + this.resolvedRelativeTargetAt = 0.0; + this.hasProjected = false; + this.isVisible = true; + this.animationProgress = 0; + /** + * Shared layout + */ + // TODO Only running on root node + this.sharedNodes = new Map(); + this.latestValues = latestValues; + this.root = parent ? parent.root || parent : this; + this.path = parent ? [...parent.path, parent] : []; + this.parent = parent; + this.depth = parent ? parent.depth + 1 : 0; + for (let i = 0; i < this.path.length; i++) { + this.path[i].shouldResetTransform = true; + } + if (this.root === this) + this.nodes = new FlatTree(); + } + addEventListener(name, handler) { + if (!this.eventHandlers.has(name)) { + this.eventHandlers.set(name, new motionUtils.SubscriptionManager()); + } + return this.eventHandlers.get(name).add(handler); + } + notifyListeners(name, ...args) { + const subscriptionManager = this.eventHandlers.get(name); + subscriptionManager && subscriptionManager.notify(...args); + } + hasListeners(name) { + return this.eventHandlers.has(name); + } + /** + * Lifecycles + */ + mount(instance) { + if (this.instance) + return; + this.isSVG = motionDom.isSVGElement(instance) && !motionDom.isSVGSVGElement(instance); + this.instance = instance; + const { layoutId, layout, visualElement } = this.options; + if (visualElement && !visualElement.current) { + visualElement.mount(instance); + } + this.root.nodes.add(this); + this.parent && this.parent.children.add(this); + if (this.root.hasTreeAnimated && (layout || layoutId)) { + this.isLayoutDirty = true; + } + if (attachResizeListener) { + let cancelDelay; + let innerWidth = 0; + const resizeUnblockUpdate = () => (this.root.updateBlockedByResize = false); + // Set initial innerWidth in a frame.read callback to batch the read + motionDom.frame.read(() => { + innerWidth = window.innerWidth; + }); + attachResizeListener(instance, () => { + const newInnerWidth = window.innerWidth; + if (newInnerWidth === innerWidth) + return; + innerWidth = newInnerWidth; + this.root.updateBlockedByResize = true; + cancelDelay && cancelDelay(); + cancelDelay = delay(resizeUnblockUpdate, 250); + if (globalProjectionState.hasAnimatedSinceResize) { + globalProjectionState.hasAnimatedSinceResize = false; + this.nodes.forEach(finishAnimation); + } + }); + } + if (layoutId) { + this.root.registerSharedNode(layoutId, this); + } + // Only register the handler if it requires layout animation + if (this.options.animate !== false && + visualElement && + (layoutId || layout)) { + this.addEventListener("didUpdate", ({ delta, hasLayoutChanged, hasRelativeLayoutChanged, layout: newLayout, }) => { + if (this.isTreeAnimationBlocked()) { + this.target = undefined; + this.relativeTarget = undefined; + return; + } + // TODO: Check here if an animation exists + const layoutTransition = this.options.transition || + visualElement.getDefaultTransition() || + defaultLayoutTransition; + const { onLayoutAnimationStart, onLayoutAnimationComplete, } = visualElement.getProps(); + /** + * The target layout of the element might stay the same, + * but its position relative to its parent has changed. + */ + const hasTargetChanged = !this.targetLayout || + !boxEqualsRounded(this.targetLayout, newLayout); + /* + * Note: Disabled to fix relative animations always triggering new + * layout animations. If this causes further issues, we can try + * a different approach to detecting relative target changes. + */ + // || hasRelativeLayoutChanged + /** + * If the layout hasn't seemed to have changed, it might be that the + * element is visually in the same place in the document but its position + * relative to its parent has indeed changed. So here we check for that. + */ + const hasOnlyRelativeTargetChanged = !hasLayoutChanged && hasRelativeLayoutChanged; + if (this.options.layoutRoot || + this.resumeFrom || + hasOnlyRelativeTargetChanged || + (hasLayoutChanged && + (hasTargetChanged || !this.currentAnimation))) { + if (this.resumeFrom) { + this.resumingFrom = this.resumeFrom; + this.resumingFrom.resumingFrom = undefined; + } + const animationOptions = { + ...motionDom.getValueTransition(layoutTransition, "layout"), + onPlay: onLayoutAnimationStart, + onComplete: onLayoutAnimationComplete, + }; + if (visualElement.shouldReduceMotion || + this.options.layoutRoot) { + animationOptions.delay = 0; + animationOptions.type = false; + } + this.startAnimation(animationOptions); + /** + * Set animation origin after starting animation to avoid layout jump + * caused by stopping previous layout animation + */ + this.setAnimationOrigin(delta, hasOnlyRelativeTargetChanged); + } + else { + /** + * If the layout hasn't changed and we have an animation that hasn't started yet, + * finish it immediately. Otherwise it will be animating from a location + * that was probably never commited to screen and look like a jumpy box. + */ + if (!hasLayoutChanged) { + finishAnimation(this); + } + if (this.isLead() && this.options.onExitComplete) { + this.options.onExitComplete(); + } + } + this.targetLayout = newLayout; + }); + } + } + unmount() { + this.options.layoutId && this.willUpdate(); + this.root.nodes.remove(this); + const stack = this.getStack(); + stack && stack.remove(this); + this.parent && this.parent.children.delete(this); + this.instance = undefined; + this.eventHandlers.clear(); + motionDom.cancelFrame(this.updateProjection); + } + // only on the root + blockUpdate() { + this.updateManuallyBlocked = true; + } + unblockUpdate() { + this.updateManuallyBlocked = false; + } + isUpdateBlocked() { + return this.updateManuallyBlocked || this.updateBlockedByResize; + } + isTreeAnimationBlocked() { + return (this.isAnimationBlocked || + (this.parent && this.parent.isTreeAnimationBlocked()) || + false); + } + // Note: currently only running on root node + startUpdate() { + if (this.isUpdateBlocked()) + return; + this.isUpdating = true; + this.nodes && this.nodes.forEach(resetSkewAndRotation); + this.animationId++; + } + getTransformTemplate() { + const { visualElement } = this.options; + return visualElement && visualElement.getProps().transformTemplate; + } + willUpdate(shouldNotifyListeners = true) { + this.root.hasTreeAnimated = true; + if (this.root.isUpdateBlocked()) { + this.options.onExitComplete && this.options.onExitComplete(); + return; + } + /** + * If we're running optimised appear animations then these must be + * cancelled before measuring the DOM. This is so we can measure + * the true layout of the element rather than the WAAPI animation + * which will be unaffected by the resetSkewAndRotate step. + * + * Note: This is a DOM write. Worst case scenario is this is sandwiched + * between other snapshot reads which will cause unnecessary style recalculations. + * This has to happen here though, as we don't yet know which nodes will need + * snapshots in startUpdate(), but we only want to cancel optimised animations + * if a layout animation measurement is actually going to be affected by them. + */ + if (window.MotionCancelOptimisedAnimation && + !this.hasCheckedOptimisedAppear) { + cancelTreeOptimisedTransformAnimations(this); + } + !this.root.isUpdating && this.root.startUpdate(); + if (this.isLayoutDirty) + return; + this.isLayoutDirty = true; + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + node.shouldResetTransform = true; + node.updateScroll("snapshot"); + if (node.options.layoutRoot) { + node.willUpdate(false); + } + } + const { layoutId, layout } = this.options; + if (layoutId === undefined && !layout) + return; + const transformTemplate = this.getTransformTemplate(); + this.prevTransformTemplateValue = transformTemplate + ? transformTemplate(this.latestValues, "") + : undefined; + this.updateSnapshot(); + shouldNotifyListeners && this.notifyListeners("willUpdate"); + } + update() { + this.updateScheduled = false; + const updateWasBlocked = this.isUpdateBlocked(); + // When doing an instant transition, we skip the layout update, + // but should still clean up the measurements so that the next + // snapshot could be taken correctly. + if (updateWasBlocked) { + this.unblockUpdate(); + this.clearAllSnapshots(); + this.nodes.forEach(clearMeasurements); + return; + } + /** + * If this is a repeat of didUpdate then ignore the animation. + */ + if (this.animationId <= this.animationCommitId) { + this.nodes.forEach(clearIsLayoutDirty); + return; + } + this.animationCommitId = this.animationId; + if (!this.isUpdating) { + this.nodes.forEach(clearIsLayoutDirty); + } + else { + this.isUpdating = false; + /** + * Write + */ + this.nodes.forEach(resetTransformStyle); + /** + * Read ================== + */ + // Update layout measurements of updated children + this.nodes.forEach(updateLayout); + /** + * Write + */ + // Notify listeners that the layout is updated + this.nodes.forEach(notifyLayoutUpdate); + } + this.clearAllSnapshots(); + /** + * Manually flush any pending updates. Ideally + * we could leave this to the following requestAnimationFrame but this seems + * to leave a flash of incorrectly styled content. + */ + const now = motionDom.time.now(); + motionDom.frameData.delta = motionUtils.clamp(0, 1000 / 60, now - motionDom.frameData.timestamp); + motionDom.frameData.timestamp = now; + motionDom.frameData.isProcessing = true; + motionDom.frameSteps.update.process(motionDom.frameData); + motionDom.frameSteps.preRender.process(motionDom.frameData); + motionDom.frameSteps.render.process(motionDom.frameData); + motionDom.frameData.isProcessing = false; + } + didUpdate() { + if (!this.updateScheduled) { + this.updateScheduled = true; + motionDom.microtask.read(this.scheduleUpdate); + } + } + clearAllSnapshots() { + this.nodes.forEach(clearSnapshot); + this.sharedNodes.forEach(removeLeadSnapshots); + } + scheduleUpdateProjection() { + if (!this.projectionUpdateScheduled) { + this.projectionUpdateScheduled = true; + motionDom.frame.preRender(this.updateProjection, false, true); + } + } + scheduleCheckAfterUnmount() { + /** + * If the unmounting node is in a layoutGroup and did trigger a willUpdate, + * we manually call didUpdate to give a chance to the siblings to animate. + * Otherwise, cleanup all snapshots to prevents future nodes from reusing them. + */ + motionDom.frame.postRender(() => { + if (this.isLayoutDirty) { + this.root.didUpdate(); + } + else { + this.root.checkUpdateFailed(); + } + }); + } + /** + * Update measurements + */ + updateSnapshot() { + if (this.snapshot || !this.instance) + return; + this.snapshot = this.measure(); + if (this.snapshot && + !calcLength(this.snapshot.measuredBox.x) && + !calcLength(this.snapshot.measuredBox.y)) { + this.snapshot = undefined; + } + } + updateLayout() { + if (!this.instance) + return; + this.updateScroll(); + if (!(this.options.alwaysMeasureLayout && this.isLead()) && + !this.isLayoutDirty) { + return; + } + /** + * When a node is mounted, it simply resumes from the prevLead's + * snapshot instead of taking a new one, but the ancestors scroll + * might have updated while the prevLead is unmounted. We need to + * update the scroll again to make sure the layout we measure is + * up to date. + */ + if (this.resumeFrom && !this.resumeFrom.instance) { + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + node.updateScroll(); + } + } + const prevLayout = this.layout; + this.layout = this.measure(false); + this.layoutCorrected = createBox(); + this.isLayoutDirty = false; + this.projectionDelta = undefined; + this.notifyListeners("measure", this.layout.layoutBox); + const { visualElement } = this.options; + visualElement && + visualElement.notify("LayoutMeasure", this.layout.layoutBox, prevLayout ? prevLayout.layoutBox : undefined); + } + updateScroll(phase = "measure") { + let needsMeasurement = Boolean(this.options.layoutScroll && this.instance); + if (this.scroll && + this.scroll.animationId === this.root.animationId && + this.scroll.phase === phase) { + needsMeasurement = false; + } + if (needsMeasurement && this.instance) { + const isRoot = checkIsScrollRoot(this.instance); + this.scroll = { + animationId: this.root.animationId, + phase, + isRoot, + offset: measureScroll(this.instance), + wasRoot: this.scroll ? this.scroll.isRoot : isRoot, + }; + } + } + resetTransform() { + if (!resetTransform) + return; + const isResetRequested = this.isLayoutDirty || + this.shouldResetTransform || + this.options.alwaysMeasureLayout; + const hasProjection = this.projectionDelta && !isDeltaZero(this.projectionDelta); + const transformTemplate = this.getTransformTemplate(); + const transformTemplateValue = transformTemplate + ? transformTemplate(this.latestValues, "") + : undefined; + const transformTemplateHasChanged = transformTemplateValue !== this.prevTransformTemplateValue; + if (isResetRequested && + this.instance && + (hasProjection || + hasTransform(this.latestValues) || + transformTemplateHasChanged)) { + resetTransform(this.instance, transformTemplateValue); + this.shouldResetTransform = false; + this.scheduleRender(); + } + } + measure(removeTransform = true) { + const pageBox = this.measurePageBox(); + let layoutBox = this.removeElementScroll(pageBox); + /** + * Measurements taken during the pre-render stage + * still have transforms applied so we remove them + * via calculation. + */ + if (removeTransform) { + layoutBox = this.removeTransform(layoutBox); + } + roundBox(layoutBox); + return { + animationId: this.root.animationId, + measuredBox: pageBox, + layoutBox, + latestValues: {}, + source: this.id, + }; + } + measurePageBox() { + const { visualElement } = this.options; + if (!visualElement) + return createBox(); + const box = visualElement.measureViewportBox(); + const wasInScrollRoot = this.scroll?.wasRoot || this.path.some(checkNodeWasScrollRoot); + if (!wasInScrollRoot) { + // Remove viewport scroll to give page-relative coordinates + const { scroll } = this.root; + if (scroll) { + translateAxis(box.x, scroll.offset.x); + translateAxis(box.y, scroll.offset.y); + } + } + return box; + } + removeElementScroll(box) { + const boxWithoutScroll = createBox(); + copyBoxInto(boxWithoutScroll, box); + if (this.scroll?.wasRoot) { + return boxWithoutScroll; + } + /** + * Performance TODO: Keep a cumulative scroll offset down the tree + * rather than loop back up the path. + */ + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + const { scroll, options } = node; + if (node !== this.root && scroll && options.layoutScroll) { + /** + * If this is a new scroll root, we want to remove all previous scrolls + * from the viewport box. + */ + if (scroll.wasRoot) { + copyBoxInto(boxWithoutScroll, box); + } + translateAxis(boxWithoutScroll.x, scroll.offset.x); + translateAxis(boxWithoutScroll.y, scroll.offset.y); + } + } + return boxWithoutScroll; + } + applyTransform(box, transformOnly = false) { + const withTransforms = createBox(); + copyBoxInto(withTransforms, box); + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + if (!transformOnly && + node.options.layoutScroll && + node.scroll && + node !== node.root) { + transformBox(withTransforms, { + x: -node.scroll.offset.x, + y: -node.scroll.offset.y, + }); + } + if (!hasTransform(node.latestValues)) + continue; + transformBox(withTransforms, node.latestValues); + } + if (hasTransform(this.latestValues)) { + transformBox(withTransforms, this.latestValues); + } + return withTransforms; + } + removeTransform(box) { + const boxWithoutTransform = createBox(); + copyBoxInto(boxWithoutTransform, box); + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + if (!node.instance) + continue; + if (!hasTransform(node.latestValues)) + continue; + hasScale(node.latestValues) && node.updateSnapshot(); + const sourceBox = createBox(); + const nodeBox = node.measurePageBox(); + copyBoxInto(sourceBox, nodeBox); + removeBoxTransforms(boxWithoutTransform, node.latestValues, node.snapshot ? node.snapshot.layoutBox : undefined, sourceBox); + } + if (hasTransform(this.latestValues)) { + removeBoxTransforms(boxWithoutTransform, this.latestValues); + } + return boxWithoutTransform; + } + setTargetDelta(delta) { + this.targetDelta = delta; + this.root.scheduleUpdateProjection(); + this.isProjectionDirty = true; + } + setOptions(options) { + this.options = { + ...this.options, + ...options, + crossfade: options.crossfade !== undefined ? options.crossfade : true, + }; + } + clearMeasurements() { + this.scroll = undefined; + this.layout = undefined; + this.snapshot = undefined; + this.prevTransformTemplateValue = undefined; + this.targetDelta = undefined; + this.target = undefined; + this.isLayoutDirty = false; + } + forceRelativeParentToResolveTarget() { + if (!this.relativeParent) + return; + /** + * If the parent target isn't up-to-date, force it to update. + * This is an unfortunate de-optimisation as it means any updating relative + * projection will cause all the relative parents to recalculate back + * up the tree. + */ + if (this.relativeParent.resolvedRelativeTargetAt !== + motionDom.frameData.timestamp) { + this.relativeParent.resolveTargetDelta(true); + } + } + resolveTargetDelta(forceRecalculation = false) { + /** + * Once the dirty status of nodes has been spread through the tree, we also + * need to check if we have a shared node of a different depth that has itself + * been dirtied. + */ + const lead = this.getLead(); + this.isProjectionDirty || (this.isProjectionDirty = lead.isProjectionDirty); + this.isTransformDirty || (this.isTransformDirty = lead.isTransformDirty); + this.isSharedProjectionDirty || (this.isSharedProjectionDirty = lead.isSharedProjectionDirty); + const isShared = Boolean(this.resumingFrom) || this !== lead; + /** + * We don't use transform for this step of processing so we don't + * need to check whether any nodes have changed transform. + */ + const canSkip = !(forceRecalculation || + (isShared && this.isSharedProjectionDirty) || + this.isProjectionDirty || + this.parent?.isProjectionDirty || + this.attemptToResolveRelativeTarget || + this.root.updateBlockedByResize); + if (canSkip) + return; + const { layout, layoutId } = this.options; + /** + * If we have no layout, we can't perform projection, so early return + */ + if (!this.layout || !(layout || layoutId)) + return; + this.resolvedRelativeTargetAt = motionDom.frameData.timestamp; + /** + * If we don't have a targetDelta but do have a layout, we can attempt to resolve + * a relativeParent. This will allow a component to perform scale correction + * even if no animation has started. + */ + if (!this.targetDelta && !this.relativeTarget) { + const relativeParent = this.getClosestProjectingParent(); + if (relativeParent && + relativeParent.layout && + this.animationProgress !== 1) { + this.relativeParent = relativeParent; + this.forceRelativeParentToResolveTarget(); + this.relativeTarget = createBox(); + this.relativeTargetOrigin = createBox(); + calcRelativePosition(this.relativeTargetOrigin, this.layout.layoutBox, relativeParent.layout.layoutBox); + copyBoxInto(this.relativeTarget, this.relativeTargetOrigin); + } + else { + this.relativeParent = this.relativeTarget = undefined; + } + } + /** + * If we have no relative target or no target delta our target isn't valid + * for this frame. + */ + if (!this.relativeTarget && !this.targetDelta) + return; + /** + * Lazy-init target data structure + */ + if (!this.target) { + this.target = createBox(); + this.targetWithTransforms = createBox(); + } + /** + * If we've got a relative box for this component, resolve it into a target relative to the parent. + */ + if (this.relativeTarget && + this.relativeTargetOrigin && + this.relativeParent && + this.relativeParent.target) { + this.forceRelativeParentToResolveTarget(); + calcRelativeBox(this.target, this.relativeTarget, this.relativeParent.target); + /** + * If we've only got a targetDelta, resolve it into a target + */ + } + else if (this.targetDelta) { + if (Boolean(this.resumingFrom)) { + // TODO: This is creating a new object every frame + this.target = this.applyTransform(this.layout.layoutBox); + } + else { + copyBoxInto(this.target, this.layout.layoutBox); + } + applyBoxDelta(this.target, this.targetDelta); + } + else { + /** + * If no target, use own layout as target + */ + copyBoxInto(this.target, this.layout.layoutBox); + } + /** + * If we've been told to attempt to resolve a relative target, do so. + */ + if (this.attemptToResolveRelativeTarget) { + this.attemptToResolveRelativeTarget = false; + const relativeParent = this.getClosestProjectingParent(); + if (relativeParent && + Boolean(relativeParent.resumingFrom) === + Boolean(this.resumingFrom) && + !relativeParent.options.layoutScroll && + relativeParent.target && + this.animationProgress !== 1) { + this.relativeParent = relativeParent; + this.forceRelativeParentToResolveTarget(); + this.relativeTarget = createBox(); + this.relativeTargetOrigin = createBox(); + calcRelativePosition(this.relativeTargetOrigin, this.target, relativeParent.target); + copyBoxInto(this.relativeTarget, this.relativeTargetOrigin); + } + else { + this.relativeParent = this.relativeTarget = undefined; + } + } + /** + * Increase debug counter for resolved target deltas + */ + if (motionDom.statsBuffer.value) { + metrics.calculatedTargetDeltas++; + } + } + getClosestProjectingParent() { + if (!this.parent || + hasScale(this.parent.latestValues) || + has2DTranslate(this.parent.latestValues)) { + return undefined; + } + if (this.parent.isProjecting()) { + return this.parent; + } + else { + return this.parent.getClosestProjectingParent(); + } + } + isProjecting() { + return Boolean((this.relativeTarget || + this.targetDelta || + this.options.layoutRoot) && + this.layout); + } + calcProjection() { + const lead = this.getLead(); + const isShared = Boolean(this.resumingFrom) || this !== lead; + let canSkip = true; + /** + * If this is a normal layout animation and neither this node nor its nearest projecting + * is dirty then we can't skip. + */ + if (this.isProjectionDirty || this.parent?.isProjectionDirty) { + canSkip = false; + } + /** + * If this is a shared layout animation and this node's shared projection is dirty then + * we can't skip. + */ + if (isShared && + (this.isSharedProjectionDirty || this.isTransformDirty)) { + canSkip = false; + } + /** + * If we have resolved the target this frame we must recalculate the + * projection to ensure it visually represents the internal calculations. + */ + if (this.resolvedRelativeTargetAt === motionDom.frameData.timestamp) { + canSkip = false; + } + if (canSkip) + return; + const { layout, layoutId } = this.options; + /** + * If this section of the tree isn't animating we can + * delete our target sources for the following frame. + */ + this.isTreeAnimating = Boolean((this.parent && this.parent.isTreeAnimating) || + this.currentAnimation || + this.pendingAnimation); + if (!this.isTreeAnimating) { + this.targetDelta = this.relativeTarget = undefined; + } + if (!this.layout || !(layout || layoutId)) + return; + /** + * Reset the corrected box with the latest values from box, as we're then going + * to perform mutative operations on it. + */ + copyBoxInto(this.layoutCorrected, this.layout.layoutBox); + /** + * Record previous tree scales before updating. + */ + const prevTreeScaleX = this.treeScale.x; + const prevTreeScaleY = this.treeScale.y; + /** + * Apply all the parent deltas to this box to produce the corrected box. This + * is the layout box, as it will appear on screen as a result of the transforms of its parents. + */ + applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, isShared); + /** + * If this layer needs to perform scale correction but doesn't have a target, + * use the layout as the target. + */ + if (lead.layout && + !lead.target && + (this.treeScale.x !== 1 || this.treeScale.y !== 1)) { + lead.target = lead.layout.layoutBox; + lead.targetWithTransforms = createBox(); + } + const { target } = lead; + if (!target) { + /** + * If we don't have a target to project into, but we were previously + * projecting, we want to remove the stored transform and schedule + * a render to ensure the elements reflect the removed transform. + */ + if (this.prevProjectionDelta) { + this.createProjectionDeltas(); + this.scheduleRender(); + } + return; + } + if (!this.projectionDelta || !this.prevProjectionDelta) { + this.createProjectionDeltas(); + } + else { + copyAxisDeltaInto(this.prevProjectionDelta.x, this.projectionDelta.x); + copyAxisDeltaInto(this.prevProjectionDelta.y, this.projectionDelta.y); + } + /** + * Update the delta between the corrected box and the target box before user-set transforms were applied. + * This will allow us to calculate the corrected borderRadius and boxShadow to compensate + * for our layout reprojection, but still allow them to be scaled correctly by the user. + * It might be that to simplify this we may want to accept that user-set scale is also corrected + * and we wouldn't have to keep and calc both deltas, OR we could support a user setting + * to allow people to choose whether these styles are corrected based on just the + * layout reprojection or the final bounding box. + */ + calcBoxDelta(this.projectionDelta, this.layoutCorrected, target, this.latestValues); + if (this.treeScale.x !== prevTreeScaleX || + this.treeScale.y !== prevTreeScaleY || + !axisDeltaEquals(this.projectionDelta.x, this.prevProjectionDelta.x) || + !axisDeltaEquals(this.projectionDelta.y, this.prevProjectionDelta.y)) { + this.hasProjected = true; + this.scheduleRender(); + this.notifyListeners("projectionUpdate", target); + } + /** + * Increase debug counter for recalculated projections + */ + if (motionDom.statsBuffer.value) { + metrics.calculatedProjections++; + } + } + hide() { + this.isVisible = false; + // TODO: Schedule render + } + show() { + this.isVisible = true; + // TODO: Schedule render + } + scheduleRender(notifyAll = true) { + this.options.visualElement?.scheduleRender(); + if (notifyAll) { + const stack = this.getStack(); + stack && stack.scheduleRender(); + } + if (this.resumingFrom && !this.resumingFrom.instance) { + this.resumingFrom = undefined; + } + } + createProjectionDeltas() { + this.prevProjectionDelta = createDelta(); + this.projectionDelta = createDelta(); + this.projectionDeltaWithTransform = createDelta(); + } + setAnimationOrigin(delta, hasOnlyRelativeTargetChanged = false) { + const snapshot = this.snapshot; + const snapshotLatestValues = snapshot ? snapshot.latestValues : {}; + const mixedValues = { ...this.latestValues }; + const targetDelta = createDelta(); + if (!this.relativeParent || + !this.relativeParent.options.layoutRoot) { + this.relativeTarget = this.relativeTargetOrigin = undefined; + } + this.attemptToResolveRelativeTarget = !hasOnlyRelativeTargetChanged; + const relativeLayout = createBox(); + const snapshotSource = snapshot ? snapshot.source : undefined; + const layoutSource = this.layout ? this.layout.source : undefined; + const isSharedLayoutAnimation = snapshotSource !== layoutSource; + const stack = this.getStack(); + const isOnlyMember = !stack || stack.members.length <= 1; + const shouldCrossfadeOpacity = Boolean(isSharedLayoutAnimation && + !isOnlyMember && + this.options.crossfade === true && + !this.path.some(hasOpacityCrossfade)); + this.animationProgress = 0; + let prevRelativeTarget; + this.mixTargetDelta = (latest) => { + const progress = latest / 1000; + mixAxisDelta(targetDelta.x, delta.x, progress); + mixAxisDelta(targetDelta.y, delta.y, progress); + this.setTargetDelta(targetDelta); + if (this.relativeTarget && + this.relativeTargetOrigin && + this.layout && + this.relativeParent && + this.relativeParent.layout) { + calcRelativePosition(relativeLayout, this.layout.layoutBox, this.relativeParent.layout.layoutBox); + mixBox(this.relativeTarget, this.relativeTargetOrigin, relativeLayout, progress); + /** + * If this is an unchanged relative target we can consider the + * projection not dirty. + */ + if (prevRelativeTarget && + boxEquals(this.relativeTarget, prevRelativeTarget)) { + this.isProjectionDirty = false; + } + if (!prevRelativeTarget) + prevRelativeTarget = createBox(); + copyBoxInto(prevRelativeTarget, this.relativeTarget); + } + if (isSharedLayoutAnimation) { + this.animationValues = mixedValues; + mixValues(mixedValues, snapshotLatestValues, this.latestValues, progress, shouldCrossfadeOpacity, isOnlyMember); + } + this.root.scheduleUpdateProjection(); + this.scheduleRender(); + this.animationProgress = progress; + }; + this.mixTargetDelta(this.options.layoutRoot ? 1000 : 0); + } + startAnimation(options) { + this.notifyListeners("animationStart"); + this.currentAnimation?.stop(); + this.resumingFrom?.currentAnimation?.stop(); + if (this.pendingAnimation) { + motionDom.cancelFrame(this.pendingAnimation); + this.pendingAnimation = undefined; + } + /** + * Start the animation in the next frame to have a frame with progress 0, + * where the target is the same as when the animation started, so we can + * calculate the relative positions correctly for instant transitions. + */ + this.pendingAnimation = motionDom.frame.update(() => { + globalProjectionState.hasAnimatedSinceResize = true; + motionDom.activeAnimations.layout++; + this.motionValue || (this.motionValue = motionDom.motionValue(0)); + this.currentAnimation = animateSingleValue(this.motionValue, [0, 1000], { + ...options, + velocity: 0, + isSync: true, + onUpdate: (latest) => { + this.mixTargetDelta(latest); + options.onUpdate && options.onUpdate(latest); + }, + onStop: () => { + motionDom.activeAnimations.layout--; + }, + onComplete: () => { + motionDom.activeAnimations.layout--; + options.onComplete && options.onComplete(); + this.completeAnimation(); + }, + }); + if (this.resumingFrom) { + this.resumingFrom.currentAnimation = this.currentAnimation; + } + this.pendingAnimation = undefined; + }); + } + completeAnimation() { + if (this.resumingFrom) { + this.resumingFrom.currentAnimation = undefined; + this.resumingFrom.preserveOpacity = undefined; + } + const stack = this.getStack(); + stack && stack.exitAnimationComplete(); + this.resumingFrom = + this.currentAnimation = + this.animationValues = + undefined; + this.notifyListeners("animationComplete"); + } + finishAnimation() { + if (this.currentAnimation) { + this.mixTargetDelta && this.mixTargetDelta(animationTarget); + this.currentAnimation.stop(); + } + this.completeAnimation(); + } + applyTransformsToTarget() { + const lead = this.getLead(); + let { targetWithTransforms, target, layout, latestValues } = lead; + if (!targetWithTransforms || !target || !layout) + return; + /** + * If we're only animating position, and this element isn't the lead element, + * then instead of projecting into the lead box we instead want to calculate + * a new target that aligns the two boxes but maintains the layout shape. + */ + if (this !== lead && + this.layout && + layout && + shouldAnimatePositionOnly(this.options.animationType, this.layout.layoutBox, layout.layoutBox)) { + target = this.target || createBox(); + const xLength = calcLength(this.layout.layoutBox.x); + target.x.min = lead.target.x.min; + target.x.max = target.x.min + xLength; + const yLength = calcLength(this.layout.layoutBox.y); + target.y.min = lead.target.y.min; + target.y.max = target.y.min + yLength; + } + copyBoxInto(targetWithTransforms, target); + /** + * Apply the latest user-set transforms to the targetBox to produce the targetBoxFinal. + * This is the final box that we will then project into by calculating a transform delta and + * applying it to the corrected box. + */ + transformBox(targetWithTransforms, latestValues); + /** + * Update the delta between the corrected box and the final target box, after + * user-set transforms are applied to it. This will be used by the renderer to + * create a transform style that will reproject the element from its layout layout + * into the desired bounding box. + */ + calcBoxDelta(this.projectionDeltaWithTransform, this.layoutCorrected, targetWithTransforms, latestValues); + } + registerSharedNode(layoutId, node) { + if (!this.sharedNodes.has(layoutId)) { + this.sharedNodes.set(layoutId, new NodeStack()); + } + const stack = this.sharedNodes.get(layoutId); + stack.add(node); + const config = node.options.initialPromotionConfig; + node.promote({ + transition: config ? config.transition : undefined, + preserveFollowOpacity: config && config.shouldPreserveFollowOpacity + ? config.shouldPreserveFollowOpacity(node) + : undefined, + }); + } + isLead() { + const stack = this.getStack(); + return stack ? stack.lead === this : true; + } + getLead() { + const { layoutId } = this.options; + return layoutId ? this.getStack()?.lead || this : this; + } + getPrevLead() { + const { layoutId } = this.options; + return layoutId ? this.getStack()?.prevLead : undefined; + } + getStack() { + const { layoutId } = this.options; + if (layoutId) + return this.root.sharedNodes.get(layoutId); + } + promote({ needsReset, transition, preserveFollowOpacity, } = {}) { + const stack = this.getStack(); + if (stack) + stack.promote(this, preserveFollowOpacity); + if (needsReset) { + this.projectionDelta = undefined; + this.needsReset = true; + } + if (transition) + this.setOptions({ transition }); + } + relegate() { + const stack = this.getStack(); + if (stack) { + return stack.relegate(this); + } + else { + return false; + } + } + resetSkewAndRotation() { + const { visualElement } = this.options; + if (!visualElement) + return; + // If there's no detected skew or rotation values, we can early return without a forced render. + let hasDistortingTransform = false; + /** + * An unrolled check for rotation values. Most elements don't have any rotation and + * skipping the nested loop and new object creation is 50% faster. + */ + const { latestValues } = visualElement; + if (latestValues.z || + latestValues.rotate || + latestValues.rotateX || + latestValues.rotateY || + latestValues.rotateZ || + latestValues.skewX || + latestValues.skewY) { + hasDistortingTransform = true; + } + // If there's no distorting values, we don't need to do any more. + if (!hasDistortingTransform) + return; + const resetValues = {}; + if (latestValues.z) { + resetDistortingTransform("z", visualElement, resetValues, this.animationValues); + } + // Check the skew and rotate value of all axes and reset to 0 + for (let i = 0; i < transformAxes.length; i++) { + resetDistortingTransform(`rotate${transformAxes[i]}`, visualElement, resetValues, this.animationValues); + resetDistortingTransform(`skew${transformAxes[i]}`, visualElement, resetValues, this.animationValues); + } + // Force a render of this element to apply the transform with all skews and rotations + // set to 0. + visualElement.render(); + // Put back all the values we reset + for (const key in resetValues) { + visualElement.setStaticValue(key, resetValues[key]); + if (this.animationValues) { + this.animationValues[key] = resetValues[key]; + } + } + // Schedule a render for the next frame. This ensures we won't visually + // see the element with the reset rotate value applied. + visualElement.scheduleRender(); + } + applyProjectionStyles(targetStyle, // CSSStyleDeclaration - doesn't allow numbers to be assigned to properties + styleProp) { + if (!this.instance || this.isSVG) + return; + if (!this.isVisible) { + targetStyle.visibility = "hidden"; + return; + } + const transformTemplate = this.getTransformTemplate(); + if (this.needsReset) { + this.needsReset = false; + targetStyle.visibility = ""; + targetStyle.opacity = ""; + targetStyle.pointerEvents = + resolveMotionValue(styleProp?.pointerEvents) || ""; + targetStyle.transform = transformTemplate + ? transformTemplate(this.latestValues, "") + : "none"; + return; + } + const lead = this.getLead(); + if (!this.projectionDelta || !this.layout || !lead.target) { + if (this.options.layoutId) { + targetStyle.opacity = + this.latestValues.opacity !== undefined + ? this.latestValues.opacity + : 1; + targetStyle.pointerEvents = + resolveMotionValue(styleProp?.pointerEvents) || ""; + } + if (this.hasProjected && !hasTransform(this.latestValues)) { + targetStyle.transform = transformTemplate + ? transformTemplate({}, "") + : "none"; + this.hasProjected = false; + } + return; + } + targetStyle.visibility = ""; + const valuesToRender = lead.animationValues || lead.latestValues; + this.applyTransformsToTarget(); + let transform = buildProjectionTransform(this.projectionDeltaWithTransform, this.treeScale, valuesToRender); + if (transformTemplate) { + transform = transformTemplate(valuesToRender, transform); + } + targetStyle.transform = transform; + const { x, y } = this.projectionDelta; + targetStyle.transformOrigin = `${x.origin * 100}% ${y.origin * 100}% 0`; + if (lead.animationValues) { + /** + * If the lead component is animating, assign this either the entering/leaving + * opacity + */ + targetStyle.opacity = + lead === this + ? valuesToRender.opacity ?? + this.latestValues.opacity ?? + 1 + : this.preserveOpacity + ? this.latestValues.opacity + : valuesToRender.opacityExit; + } + else { + /** + * Or we're not animating at all, set the lead component to its layout + * opacity and other components to hidden. + */ + targetStyle.opacity = + lead === this + ? valuesToRender.opacity !== undefined + ? valuesToRender.opacity + : "" + : valuesToRender.opacityExit !== undefined + ? valuesToRender.opacityExit + : 0; + } + /** + * Apply scale correction + */ + for (const key in scaleCorrectors) { + if (valuesToRender[key] === undefined) + continue; + const { correct, applyTo, isCSSVariable } = scaleCorrectors[key]; + /** + * Only apply scale correction to the value if we have an + * active projection transform. Otherwise these values become + * vulnerable to distortion if the element changes size without + * a corresponding layout animation. + */ + const corrected = transform === "none" + ? valuesToRender[key] + : correct(valuesToRender[key], lead); + if (applyTo) { + const num = applyTo.length; + for (let i = 0; i < num; i++) { + targetStyle[applyTo[i]] = corrected; + } + } + else { + // If this is a CSS variable, set it directly on the instance. + // Replacing this function from creating styles to setting them + // would be a good place to remove per frame object creation + if (isCSSVariable) { + this.options.visualElement.renderState.vars[key] = corrected; + } + else { + targetStyle[key] = corrected; + } + } + } + /** + * Disable pointer events on follow components. This is to ensure + * that if a follow component covers a lead component it doesn't block + * pointer events on the lead. + */ + if (this.options.layoutId) { + targetStyle.pointerEvents = + lead === this + ? resolveMotionValue(styleProp?.pointerEvents) || "" + : "none"; + } + } + clearSnapshot() { + this.resumeFrom = this.snapshot = undefined; + } + // Only run on root + resetTree() { + this.root.nodes.forEach((node) => node.currentAnimation?.stop()); + this.root.nodes.forEach(clearMeasurements); + this.root.sharedNodes.clear(); + } + }; +} +function updateLayout(node) { + node.updateLayout(); +} +function notifyLayoutUpdate(node) { + const snapshot = node.resumeFrom?.snapshot || node.snapshot; + if (node.isLead() && + node.layout && + snapshot && + node.hasListeners("didUpdate")) { + const { layoutBox: layout, measuredBox: measuredLayout } = node.layout; + const { animationType } = node.options; + const isShared = snapshot.source !== node.layout.source; + // TODO Maybe we want to also resize the layout snapshot so we don't trigger + // animations for instance if layout="size" and an element has only changed position + if (animationType === "size") { + eachAxis((axis) => { + const axisSnapshot = isShared + ? snapshot.measuredBox[axis] + : snapshot.layoutBox[axis]; + const length = calcLength(axisSnapshot); + axisSnapshot.min = layout[axis].min; + axisSnapshot.max = axisSnapshot.min + length; + }); + } + else if (shouldAnimatePositionOnly(animationType, snapshot.layoutBox, layout)) { + eachAxis((axis) => { + const axisSnapshot = isShared + ? snapshot.measuredBox[axis] + : snapshot.layoutBox[axis]; + const length = calcLength(layout[axis]); + axisSnapshot.max = axisSnapshot.min + length; + /** + * Ensure relative target gets resized and rerendererd + */ + if (node.relativeTarget && !node.currentAnimation) { + node.isProjectionDirty = true; + node.relativeTarget[axis].max = + node.relativeTarget[axis].min + length; + } + }); + } + const layoutDelta = createDelta(); + calcBoxDelta(layoutDelta, layout, snapshot.layoutBox); + const visualDelta = createDelta(); + if (isShared) { + calcBoxDelta(visualDelta, node.applyTransform(measuredLayout, true), snapshot.measuredBox); + } + else { + calcBoxDelta(visualDelta, layout, snapshot.layoutBox); + } + const hasLayoutChanged = !isDeltaZero(layoutDelta); + let hasRelativeLayoutChanged = false; + if (!node.resumeFrom) { + const relativeParent = node.getClosestProjectingParent(); + /** + * If the relativeParent is itself resuming from a different element then + * the relative snapshot is not relavent + */ + if (relativeParent && !relativeParent.resumeFrom) { + const { snapshot: parentSnapshot, layout: parentLayout } = relativeParent; + if (parentSnapshot && parentLayout) { + const relativeSnapshot = createBox(); + calcRelativePosition(relativeSnapshot, snapshot.layoutBox, parentSnapshot.layoutBox); + const relativeLayout = createBox(); + calcRelativePosition(relativeLayout, layout, parentLayout.layoutBox); + if (!boxEqualsRounded(relativeSnapshot, relativeLayout)) { + hasRelativeLayoutChanged = true; + } + if (relativeParent.options.layoutRoot) { + node.relativeTarget = relativeLayout; + node.relativeTargetOrigin = relativeSnapshot; + node.relativeParent = relativeParent; + } + } + } + } + node.notifyListeners("didUpdate", { + layout, + snapshot, + delta: visualDelta, + layoutDelta, + hasLayoutChanged, + hasRelativeLayoutChanged, + }); + } + else if (node.isLead()) { + const { onExitComplete } = node.options; + onExitComplete && onExitComplete(); + } + /** + * Clearing transition + * TODO: Investigate why this transition is being passed in as {type: false } from Framer + * and why we need it at all + */ + node.options.transition = undefined; +} +function propagateDirtyNodes(node) { + /** + * Increase debug counter for nodes encountered this frame + */ + if (motionDom.statsBuffer.value) { + metrics.nodes++; + } + if (!node.parent) + return; + /** + * If this node isn't projecting, propagate isProjectionDirty. It will have + * no performance impact but it will allow the next child that *is* projecting + * but *isn't* dirty to just check its parent to see if *any* ancestor needs + * correcting. + */ + if (!node.isProjecting()) { + node.isProjectionDirty = node.parent.isProjectionDirty; + } + /** + * Propagate isSharedProjectionDirty and isTransformDirty + * throughout the whole tree. A future revision can take another look at + * this but for safety we still recalcualte shared nodes. + */ + node.isSharedProjectionDirty || (node.isSharedProjectionDirty = Boolean(node.isProjectionDirty || + node.parent.isProjectionDirty || + node.parent.isSharedProjectionDirty)); + node.isTransformDirty || (node.isTransformDirty = node.parent.isTransformDirty); +} +function cleanDirtyNodes(node) { + node.isProjectionDirty = + node.isSharedProjectionDirty = + node.isTransformDirty = + false; +} +function clearSnapshot(node) { + node.clearSnapshot(); +} +function clearMeasurements(node) { + node.clearMeasurements(); +} +function clearIsLayoutDirty(node) { + node.isLayoutDirty = false; +} +function resetTransformStyle(node) { + const { visualElement } = node.options; + if (visualElement && visualElement.getProps().onBeforeLayoutMeasure) { + visualElement.notify("BeforeLayoutMeasure"); + } + node.resetTransform(); +} +function finishAnimation(node) { + node.finishAnimation(); + node.targetDelta = node.relativeTarget = node.target = undefined; + node.isProjectionDirty = true; +} +function resolveTargetDelta(node) { + node.resolveTargetDelta(); +} +function calcProjection(node) { + node.calcProjection(); +} +function resetSkewAndRotation(node) { + node.resetSkewAndRotation(); +} +function removeLeadSnapshots(stack) { + stack.removeLeadSnapshot(); +} +function mixAxisDelta(output, delta, p) { + output.translate = motionDom.mixNumber(delta.translate, 0, p); + output.scale = motionDom.mixNumber(delta.scale, 1, p); + output.origin = delta.origin; + output.originPoint = delta.originPoint; +} +function mixAxis(output, from, to, p) { + output.min = motionDom.mixNumber(from.min, to.min, p); + output.max = motionDom.mixNumber(from.max, to.max, p); +} +function mixBox(output, from, to, p) { + mixAxis(output.x, from.x, to.x, p); + mixAxis(output.y, from.y, to.y, p); +} +function hasOpacityCrossfade(node) { + return (node.animationValues && node.animationValues.opacityExit !== undefined); +} +const defaultLayoutTransition = { + duration: 0.45, + ease: [0.4, 0, 0.1, 1], +}; +const userAgentContains = (string) => typeof navigator !== "undefined" && + navigator.userAgent && + navigator.userAgent.toLowerCase().includes(string); +/** + * Measured bounding boxes must be rounded in Safari and + * left untouched in Chrome, otherwise non-integer layouts within scaled-up elements + * can appear to jump. + */ +const roundPoint = userAgentContains("applewebkit/") && !userAgentContains("chrome/") + ? Math.round + : motionUtils.noop; +function roundAxis(axis) { + // Round to the nearest .5 pixels to support subpixel layouts + axis.min = roundPoint(axis.min); + axis.max = roundPoint(axis.max); +} +function roundBox(box) { + roundAxis(box.x); + roundAxis(box.y); +} +function shouldAnimatePositionOnly(animationType, snapshot, layout) { + return (animationType === "position" || + (animationType === "preserve-aspect" && + !isNear(aspectRatio(snapshot), aspectRatio(layout), 0.2))); +} +function checkNodeWasScrollRoot(node) { + return node !== node.root && node.scroll?.wasRoot; +} + +function addDomEvent(target, eventName, handler, options = { passive: true }) { + target.addEventListener(eventName, handler, options); + return () => target.removeEventListener(eventName, handler); +} + +const DocumentProjectionNode = createProjectionNode$1({ + attachResizeListener: (ref, notify) => addDomEvent(ref, "resize", notify), + measureScroll: () => ({ + x: document.documentElement.scrollLeft || document.body.scrollLeft, + y: document.documentElement.scrollTop || document.body.scrollTop, + }), + checkIsScrollRoot: () => true, +}); + +const rootProjectionNode = { + current: undefined, +}; +const HTMLProjectionNode = createProjectionNode$1({ + measureScroll: (instance) => ({ + x: instance.scrollLeft, + y: instance.scrollTop, + }), + defaultParent: () => { + if (!rootProjectionNode.current) { + const documentNode = new DocumentProjectionNode({}); + documentNode.mount(window); + documentNode.setOptions({ layoutScroll: true }); + rootProjectionNode.current = documentNode; + } + return rootProjectionNode.current; + }, + resetTransform: (instance, value) => { + instance.style.transform = value !== undefined ? value : "none"; + }, + checkIsScrollRoot: (instance) => Boolean(window.getComputedStyle(instance).position === "fixed"), +}); + +function pixelsToPercent(pixels, axis) { + if (axis.max === axis.min) + return 0; + return (pixels / (axis.max - axis.min)) * 100; +} +/** + * We always correct borderRadius as a percentage rather than pixels to reduce paints. + * For example, if you are projecting a box that is 100px wide with a 10px borderRadius + * into a box that is 200px wide with a 20px borderRadius, that is actually a 10% + * borderRadius in both states. If we animate between the two in pixels that will trigger + * a paint each time. If we animate between the two in percentage we'll avoid a paint. + */ +const correctBorderRadius = { + correct: (latest, node) => { + if (!node.target) + return latest; + /** + * If latest is a string, if it's a percentage we can return immediately as it's + * going to be stretched appropriately. Otherwise, if it's a pixel, convert it to a number. + */ + if (typeof latest === "string") { + if (motionDom.px.test(latest)) { + latest = parseFloat(latest); + } + else { + return latest; + } + } + /** + * If latest is a number, it's a pixel value. We use the current viewportBox to calculate that + * pixel value as a percentage of each axis + */ + const x = pixelsToPercent(latest, node.target.x); + const y = pixelsToPercent(latest, node.target.y); + return `${x}% ${y}%`; + }, +}; + +const correctBoxShadow = { + correct: (latest, { treeScale, projectionDelta }) => { + const original = latest; + const shadow = motionDom.complex.parse(latest); + // TODO: Doesn't support multiple shadows + if (shadow.length > 5) + return original; + const template = motionDom.complex.createTransformer(latest); + const offset = typeof shadow[0] !== "number" ? 1 : 0; + // Calculate the overall context scale + const xScale = projectionDelta.x.scale * treeScale.x; + const yScale = projectionDelta.y.scale * treeScale.y; + shadow[0 + offset] /= xScale; + shadow[1 + offset] /= yScale; + /** + * Ideally we'd correct x and y scales individually, but because blur and + * spread apply to both we have to take a scale average and apply that instead. + * We could potentially improve the outcome of this by incorporating the ratio between + * the two scales. + */ + const averageScale = motionDom.mixNumber(xScale, yScale, 0.5); + // Blur + if (typeof shadow[2 + offset] === "number") + shadow[2 + offset] /= averageScale; + // Spread + if (typeof shadow[3 + offset] === "number") + shadow[3 + offset] /= averageScale; + return template(shadow); + }, +}; + +/** + * Bounding boxes tend to be defined as top, left, right, bottom. For various operations + * it's easier to consider each axis individually. This function returns a bounding box + * as a map of single-axis min/max values. + */ +function convertBoundingBoxToBox({ top, left, right, bottom, }) { + return { + x: { min: left, max: right }, + y: { min: top, max: bottom }, + }; +} +function convertBoxToBoundingBox({ x, y }) { + return { top: y.min, right: x.max, bottom: y.max, left: x.min }; +} +/** + * Applies a TransformPoint function to a bounding box. TransformPoint is usually a function + * provided by Framer to allow measured points to be corrected for device scaling. This is used + * when measuring DOM elements and DOM event points. + */ +function transformBoxPoints(point, transformPoint) { + if (!transformPoint) + return point; + const topLeft = transformPoint({ x: point.left, y: point.top }); + const bottomRight = transformPoint({ x: point.right, y: point.bottom }); + return { + top: topLeft.y, + left: topLeft.x, + bottom: bottomRight.y, + right: bottomRight.x, + }; +} + +function measureViewportBox(instance, transformPoint) { + return convertBoundingBoxToBox(transformBoxPoints(instance.getBoundingClientRect(), transformPoint)); +} +function measurePageBox(element, rootProjectionNode, transformPagePoint) { + const viewportBox = measureViewportBox(element, transformPagePoint); + const { scroll } = rootProjectionNode; + if (scroll) { + translateAxis(viewportBox.x, scroll.offset.x); + translateAxis(viewportBox.y, scroll.offset.y); + } + return viewportBox; +} + +const featureProps = { + animation: [ + "animate", + "variants", + "whileHover", + "whileTap", + "exit", + "whileInView", + "whileFocus", + "whileDrag", + ], + exit: ["exit"], + drag: ["drag", "dragControls"], + focus: ["whileFocus"], + hover: ["whileHover", "onHoverStart", "onHoverEnd"], + tap: ["whileTap", "onTap", "onTapStart", "onTapCancel"], + pan: ["onPan", "onPanStart", "onPanSessionStart", "onPanEnd"], + inView: ["whileInView", "onViewportEnter", "onViewportLeave"], + layout: ["layout", "layoutId"], +}; +const featureDefinitions = {}; +for (const key in featureProps) { + featureDefinitions[key] = { + isEnabled: (props) => featureProps[key].some((name) => !!props[name]), + }; +} + +// Does this device prefer reduced motion? Returns `null` server-side. +const prefersReducedMotion = { current: null }; +const hasReducedMotionListener = { current: false }; + +function initPrefersReducedMotion() { + hasReducedMotionListener.current = true; + if (!isBrowser) + return; + if (window.matchMedia) { + const motionMediaQuery = window.matchMedia("(prefers-reduced-motion)"); + const setReducedMotionPreferences = () => (prefersReducedMotion.current = motionMediaQuery.matches); + motionMediaQuery.addEventListener("change", setReducedMotionPreferences); + setReducedMotionPreferences(); + } + else { + prefersReducedMotion.current = false; + } +} + +const visualElementStore = new WeakMap(); + +function isAnimationControls(v) { + return (v !== null && + typeof v === "object" && + typeof v.start === "function"); +} + +/** + * Decides if the supplied variable is variant label + */ +function isVariantLabel(v) { + return typeof v === "string" || Array.isArray(v); +} + +const variantPriorityOrder = [ + "animate", + "whileInView", + "whileFocus", + "whileHover", + "whileTap", + "whileDrag", + "exit", +]; +const variantProps = ["initial", ...variantPriorityOrder]; + +function isControllingVariants(props) { + return (isAnimationControls(props.animate) || + variantProps.some((name) => isVariantLabel(props[name]))); +} +function isVariantNode(props) { + return Boolean(isControllingVariants(props) || props.variants); +} + +function updateMotionValuesFromProps(element, next, prev) { + for (const key in next) { + const nextValue = next[key]; + const prevValue = prev[key]; + if (motionDom.isMotionValue(nextValue)) { + /** + * If this is a motion value found in props or style, we want to add it + * to our visual element's motion value map. + */ + element.addValue(key, nextValue); + } + else if (motionDom.isMotionValue(prevValue)) { + /** + * If we're swapping from a motion value to a static value, + * create a new motion value from that + */ + element.addValue(key, motionDom.motionValue(nextValue, { owner: element })); + } + else if (prevValue !== nextValue) { + /** + * If this is a flat value that has changed, update the motion value + * or create one if it doesn't exist. We only want to do this if we're + * not handling the value with our animation state. + */ + if (element.hasValue(key)) { + const existingValue = element.getValue(key); + if (existingValue.liveStyle === true) { + existingValue.jump(nextValue); + } + else if (!existingValue.hasAnimated) { + existingValue.set(nextValue); + } + } + else { + const latestValue = element.getStaticValue(key); + element.addValue(key, motionDom.motionValue(latestValue !== undefined ? latestValue : nextValue, { owner: element })); + } + } + } + // Handle removed values + for (const key in prev) { + if (next[key] === undefined) + element.removeValue(key); + } + return next; +} + +function getValueState(visualElement) { + const state = [{}, {}]; + visualElement?.values.forEach((value, key) => { + state[0][key] = value.get(); + state[1][key] = value.getVelocity(); + }); + return state; +} +function resolveVariantFromProps(props, definition, custom, visualElement) { + /** + * If the variant definition is a function, resolve. + */ + if (typeof definition === "function") { + const [current, velocity] = getValueState(visualElement); + definition = definition(custom !== undefined ? custom : props.custom, current, velocity); + } + /** + * If the variant definition is a variant label, or + * the function returned a variant label, resolve. + */ + if (typeof definition === "string") { + definition = props.variants && props.variants[definition]; + } + /** + * At this point we've resolved both functions and variant labels, + * but the resolved variant label might itself have been a function. + * If so, resolve. This can only have returned a valid target object. + */ + if (typeof definition === "function") { + const [current, velocity] = getValueState(visualElement); + definition = definition(custom !== undefined ? custom : props.custom, current, velocity); + } + return definition; +} + +const propEventHandlers = [ + "AnimationStart", + "AnimationComplete", + "Update", + "BeforeLayoutMeasure", + "LayoutMeasure", + "LayoutAnimationStart", + "LayoutAnimationComplete", +]; +/** + * A VisualElement is an imperative abstraction around UI elements such as + * HTMLElement, SVGElement, Three.Object3D etc. + */ +class VisualElement { + /** + * This method takes React props and returns found MotionValues. For example, HTML + * MotionValues will be found within the style prop, whereas for Three.js within attribute arrays. + * + * This isn't an abstract method as it needs calling in the constructor, but it is + * intended to be one. + */ + scrapeMotionValuesFromProps(_props, _prevProps, _visualElement) { + return {}; + } + constructor({ parent, props, presenceContext, reducedMotionConfig, blockInitialAnimation, visualState, }, options = {}) { + /** + * A reference to the current underlying Instance, e.g. a HTMLElement + * or Three.Mesh etc. + */ + this.current = null; + /** + * A set containing references to this VisualElement's children. + */ + this.children = new Set(); + /** + * Determine what role this visual element should take in the variant tree. + */ + this.isVariantNode = false; + this.isControllingVariants = false; + /** + * Decides whether this VisualElement should animate in reduced motion + * mode. + * + * TODO: This is currently set on every individual VisualElement but feels + * like it could be set globally. + */ + this.shouldReduceMotion = null; + /** + * A map of all motion values attached to this visual element. Motion + * values are source of truth for any given animated value. A motion + * value might be provided externally by the component via props. + */ + this.values = new Map(); + this.KeyframeResolver = motionDom.KeyframeResolver; + /** + * Cleanup functions for active features (hover/tap/exit etc) + */ + this.features = {}; + /** + * A map of every subscription that binds the provided or generated + * motion values onChange listeners to this visual element. + */ + this.valueSubscriptions = new Map(); + /** + * A reference to the previously-provided motion values as returned + * from scrapeMotionValuesFromProps. We use the keys in here to determine + * if any motion values need to be removed after props are updated. + */ + this.prevMotionValues = {}; + /** + * An object containing a SubscriptionManager for each active event. + */ + this.events = {}; + /** + * An object containing an unsubscribe function for each prop event subscription. + * For example, every "Update" event can have multiple subscribers via + * VisualElement.on(), but only one of those can be defined via the onUpdate prop. + */ + this.propEventSubscriptions = {}; + this.notifyUpdate = () => this.notify("Update", this.latestValues); + this.render = () => { + if (!this.current) + return; + this.triggerBuild(); + this.renderInstance(this.current, this.renderState, this.props.style, this.projection); + }; + this.renderScheduledAt = 0.0; + this.scheduleRender = () => { + const now = motionDom.time.now(); + if (this.renderScheduledAt < now) { + this.renderScheduledAt = now; + motionDom.frame.render(this.render, false, true); + } + }; + const { latestValues, renderState } = visualState; + this.latestValues = latestValues; + this.baseTarget = { ...latestValues }; + this.initialValues = props.initial ? { ...latestValues } : {}; + this.renderState = renderState; + this.parent = parent; + this.props = props; + this.presenceContext = presenceContext; + this.depth = parent ? parent.depth + 1 : 0; + this.reducedMotionConfig = reducedMotionConfig; + this.options = options; + this.blockInitialAnimation = Boolean(blockInitialAnimation); + this.isControllingVariants = isControllingVariants(props); + this.isVariantNode = isVariantNode(props); + if (this.isVariantNode) { + this.variantChildren = new Set(); + } + this.manuallyAnimateOnMount = Boolean(parent && parent.current); + /** + * Any motion values that are provided to the element when created + * aren't yet bound to the element, as this would technically be impure. + * However, we iterate through the motion values and set them to the + * initial values for this component. + * + * TODO: This is impure and we should look at changing this to run on mount. + * Doing so will break some tests but this isn't necessarily a breaking change, + * more a reflection of the test. + */ + const { willChange, ...initialMotionValues } = this.scrapeMotionValuesFromProps(props, {}, this); + for (const key in initialMotionValues) { + const value = initialMotionValues[key]; + if (latestValues[key] !== undefined && motionDom.isMotionValue(value)) { + value.set(latestValues[key]); + } + } + } + mount(instance) { + this.current = instance; + visualElementStore.set(instance, this); + if (this.projection && !this.projection.instance) { + this.projection.mount(instance); + } + if (this.parent && this.isVariantNode && !this.isControllingVariants) { + this.removeFromVariantTree = this.parent.addVariantChild(this); + } + this.values.forEach((value, key) => this.bindToMotionValue(key, value)); + if (!hasReducedMotionListener.current) { + initPrefersReducedMotion(); + } + this.shouldReduceMotion = + this.reducedMotionConfig === "never" + ? false + : this.reducedMotionConfig === "always" + ? true + : prefersReducedMotion.current; + if (process.env.NODE_ENV !== "production") { + motionUtils.warnOnce(this.shouldReduceMotion !== true, "You have Reduced Motion enabled on your device. Animations may not appear as expected.", "reduced-motion-disabled"); + } + this.parent?.addChild(this); + this.update(this.props, this.presenceContext); + } + unmount() { + this.projection && this.projection.unmount(); + motionDom.cancelFrame(this.notifyUpdate); + motionDom.cancelFrame(this.render); + this.valueSubscriptions.forEach((remove) => remove()); + this.valueSubscriptions.clear(); + this.removeFromVariantTree && this.removeFromVariantTree(); + this.parent?.removeChild(this); + for (const key in this.events) { + this.events[key].clear(); + } + for (const key in this.features) { + const feature = this.features[key]; + if (feature) { + feature.unmount(); + feature.isMounted = false; + } + } + this.current = null; + } + addChild(child) { + this.children.add(child); + this.enteringChildren ?? (this.enteringChildren = new Set()); + this.enteringChildren.add(child); + } + removeChild(child) { + this.children.delete(child); + this.enteringChildren && this.enteringChildren.delete(child); + } + bindToMotionValue(key, value) { + if (this.valueSubscriptions.has(key)) { + this.valueSubscriptions.get(key)(); + } + const valueIsTransform = motionDom.transformProps.has(key); + if (valueIsTransform && this.onBindTransform) { + this.onBindTransform(); + } + const removeOnChange = value.on("change", (latestValue) => { + this.latestValues[key] = latestValue; + this.props.onUpdate && motionDom.frame.preRender(this.notifyUpdate); + if (valueIsTransform && this.projection) { + this.projection.isTransformDirty = true; + } + this.scheduleRender(); + }); + let removeSyncCheck; + if (window.MotionCheckAppearSync) { + removeSyncCheck = window.MotionCheckAppearSync(this, key, value); + } + this.valueSubscriptions.set(key, () => { + removeOnChange(); + if (removeSyncCheck) + removeSyncCheck(); + if (value.owner) + value.stop(); + }); + } + sortNodePosition(other) { + /** + * If these nodes aren't even of the same type we can't compare their depth. + */ + if (!this.current || + !this.sortInstanceNodePosition || + this.type !== other.type) { + return 0; + } + return this.sortInstanceNodePosition(this.current, other.current); + } + updateFeatures() { + let key = "animation"; + for (key in featureDefinitions) { + const featureDefinition = featureDefinitions[key]; + if (!featureDefinition) + continue; + const { isEnabled, Feature: FeatureConstructor } = featureDefinition; + /** + * If this feature is enabled but not active, make a new instance. + */ + if (!this.features[key] && + FeatureConstructor && + isEnabled(this.props)) { + this.features[key] = new FeatureConstructor(this); + } + /** + * If we have a feature, mount or update it. + */ + if (this.features[key]) { + const feature = this.features[key]; + if (feature.isMounted) { + feature.update(); + } + else { + feature.mount(); + feature.isMounted = true; + } + } + } + } + triggerBuild() { + this.build(this.renderState, this.latestValues, this.props); + } + /** + * Measure the current viewport box with or without transforms. + * Only measures axis-aligned boxes, rotate and skew must be manually + * removed with a re-render to work. + */ + measureViewportBox() { + return this.current + ? this.measureInstanceViewportBox(this.current, this.props) + : createBox(); + } + getStaticValue(key) { + return this.latestValues[key]; + } + setStaticValue(key, value) { + this.latestValues[key] = value; + } + /** + * Update the provided props. Ensure any newly-added motion values are + * added to our map, old ones removed, and listeners updated. + */ + update(props, presenceContext) { + if (props.transformTemplate || this.props.transformTemplate) { + this.scheduleRender(); + } + this.prevProps = this.props; + this.props = props; + this.prevPresenceContext = this.presenceContext; + this.presenceContext = presenceContext; + /** + * Update prop event handlers ie onAnimationStart, onAnimationComplete + */ + for (let i = 0; i < propEventHandlers.length; i++) { + const key = propEventHandlers[i]; + if (this.propEventSubscriptions[key]) { + this.propEventSubscriptions[key](); + delete this.propEventSubscriptions[key]; + } + const listenerName = ("on" + key); + const listener = props[listenerName]; + if (listener) { + this.propEventSubscriptions[key] = this.on(key, listener); + } + } + this.prevMotionValues = updateMotionValuesFromProps(this, this.scrapeMotionValuesFromProps(props, this.prevProps, this), this.prevMotionValues); + if (this.handleChildMotionValue) { + this.handleChildMotionValue(); + } + } + getProps() { + return this.props; + } + /** + * Returns the variant definition with a given name. + */ + getVariant(name) { + return this.props.variants ? this.props.variants[name] : undefined; + } + /** + * Returns the defined default transition on this component. + */ + getDefaultTransition() { + return this.props.transition; + } + getTransformPagePoint() { + return this.props.transformPagePoint; + } + getClosestVariantNode() { + return this.isVariantNode + ? this + : this.parent + ? this.parent.getClosestVariantNode() + : undefined; + } + /** + * Add a child visual element to our set of children. + */ + addVariantChild(child) { + const closestVariantNode = this.getClosestVariantNode(); + if (closestVariantNode) { + closestVariantNode.variantChildren && + closestVariantNode.variantChildren.add(child); + return () => closestVariantNode.variantChildren.delete(child); + } + } + /** + * Add a motion value and bind it to this visual element. + */ + addValue(key, value) { + // Remove existing value if it exists + const existingValue = this.values.get(key); + if (value !== existingValue) { + if (existingValue) + this.removeValue(key); + this.bindToMotionValue(key, value); + this.values.set(key, value); + this.latestValues[key] = value.get(); + } + } + /** + * Remove a motion value and unbind any active subscriptions. + */ + removeValue(key) { + this.values.delete(key); + const unsubscribe = this.valueSubscriptions.get(key); + if (unsubscribe) { + unsubscribe(); + this.valueSubscriptions.delete(key); + } + delete this.latestValues[key]; + this.removeValueFromRenderState(key, this.renderState); + } + /** + * Check whether we have a motion value for this key + */ + hasValue(key) { + return this.values.has(key); + } + getValue(key, defaultValue) { + if (this.props.values && this.props.values[key]) { + return this.props.values[key]; + } + let value = this.values.get(key); + if (value === undefined && defaultValue !== undefined) { + value = motionDom.motionValue(defaultValue === null ? undefined : defaultValue, { owner: this }); + this.addValue(key, value); + } + return value; + } + /** + * If we're trying to animate to a previously unencountered value, + * we need to check for it in our state and as a last resort read it + * directly from the instance (which might have performance implications). + */ + readValue(key, target) { + let value = this.latestValues[key] !== undefined || !this.current + ? this.latestValues[key] + : this.getBaseTargetFromProps(this.props, key) ?? + this.readValueFromInstance(this.current, key, this.options); + if (value !== undefined && value !== null) { + if (typeof value === "string" && + (motionUtils.isNumericalString(value) || motionUtils.isZeroValueString(value))) { + // If this is a number read as a string, ie "0" or "200", convert it to a number + value = parseFloat(value); + } + else if (!motionDom.findValueType(value) && motionDom.complex.test(target)) { + value = motionDom.getAnimatableNone(key, target); + } + this.setBaseTarget(key, motionDom.isMotionValue(value) ? value.get() : value); + } + return motionDom.isMotionValue(value) ? value.get() : value; + } + /** + * Set the base target to later animate back to. This is currently + * only hydrated on creation and when we first read a value. + */ + setBaseTarget(key, value) { + this.baseTarget[key] = value; + } + /** + * Find the base target for a value thats been removed from all animation + * props. + */ + getBaseTarget(key) { + const { initial } = this.props; + let valueFromInitial; + if (typeof initial === "string" || typeof initial === "object") { + const variant = resolveVariantFromProps(this.props, initial, this.presenceContext?.custom); + if (variant) { + valueFromInitial = variant[key]; + } + } + /** + * If this value still exists in the current initial variant, read that. + */ + if (initial && valueFromInitial !== undefined) { + return valueFromInitial; + } + /** + * Alternatively, if this VisualElement config has defined a getBaseTarget + * so we can read the value from an alternative source, try that. + */ + const target = this.getBaseTargetFromProps(this.props, key); + if (target !== undefined && !motionDom.isMotionValue(target)) + return target; + /** + * If the value was initially defined on initial, but it doesn't any more, + * return undefined. Otherwise return the value as initially read from the DOM. + */ + return this.initialValues[key] !== undefined && + valueFromInitial === undefined + ? undefined + : this.baseTarget[key]; + } + on(eventName, callback) { + if (!this.events[eventName]) { + this.events[eventName] = new motionUtils.SubscriptionManager(); + } + return this.events[eventName].add(callback); + } + notify(eventName, ...args) { + if (this.events[eventName]) { + this.events[eventName].notify(...args); + } + } + scheduleRenderMicrotask() { + motionDom.microtask.render(this.render); + } +} + +class DOMVisualElement extends VisualElement { + constructor() { + super(...arguments); + this.KeyframeResolver = motionDom.DOMKeyframesResolver; + } + sortInstanceNodePosition(a, b) { + /** + * compareDocumentPosition returns a bitmask, by using the bitwise & + * we're returning true if 2 in that bitmask is set to true. 2 is set + * to true if b preceeds a. + */ + return a.compareDocumentPosition(b) & 2 ? 1 : -1; + } + getBaseTargetFromProps(props, key) { + return props.style + ? props.style[key] + : undefined; + } + removeValueFromRenderState(key, { vars, style }) { + delete vars[key]; + delete style[key]; + } + handleChildMotionValue() { + if (this.childSubscription) { + this.childSubscription(); + delete this.childSubscription; + } + const { children } = this.props; + if (motionDom.isMotionValue(children)) { + this.childSubscription = children.on("change", (latest) => { + if (this.current) { + this.current.textContent = `${latest}`; + } + }); + } + } +} + +const translateAlias = { + x: "translateX", + y: "translateY", + z: "translateZ", + transformPerspective: "perspective", +}; +const numTransforms = motionDom.transformPropOrder.length; +/** + * Build a CSS transform style from individual x/y/scale etc properties. + * + * This outputs with a default order of transforms/scales/rotations, this can be customised by + * providing a transformTemplate function. + */ +function buildTransform(latestValues, transform, transformTemplate) { + // The transform string we're going to build into. + let transformString = ""; + let transformIsDefault = true; + /** + * Loop over all possible transforms in order, adding the ones that + * are present to the transform string. + */ + for (let i = 0; i < numTransforms; i++) { + const key = motionDom.transformPropOrder[i]; + const value = latestValues[key]; + if (value === undefined) + continue; + let valueIsDefault = true; + if (typeof value === "number") { + valueIsDefault = value === (key.startsWith("scale") ? 1 : 0); + } + else { + valueIsDefault = parseFloat(value) === 0; + } + if (!valueIsDefault || transformTemplate) { + const valueAsType = motionDom.getValueAsType(value, motionDom.numberValueTypes[key]); + if (!valueIsDefault) { + transformIsDefault = false; + const transformName = translateAlias[key] || key; + transformString += `${transformName}(${valueAsType}) `; + } + if (transformTemplate) { + transform[key] = valueAsType; + } + } + } + transformString = transformString.trim(); + // If we have a custom `transform` template, pass our transform values and + // generated transformString to that before returning + if (transformTemplate) { + transformString = transformTemplate(transform, transformIsDefault ? "" : transformString); + } + else if (transformIsDefault) { + transformString = "none"; + } + return transformString; +} + +function buildHTMLStyles(state, latestValues, transformTemplate) { + const { style, vars, transformOrigin } = state; + // Track whether we encounter any transform or transformOrigin values. + let hasTransform = false; + let hasTransformOrigin = false; + /** + * Loop over all our latest animated values and decide whether to handle them + * as a style or CSS variable. + * + * Transforms and transform origins are kept separately for further processing. + */ + for (const key in latestValues) { + const value = latestValues[key]; + if (motionDom.transformProps.has(key)) { + // If this is a transform, flag to enable further transform processing + hasTransform = true; + continue; + } + else if (motionDom.isCSSVariableName(key)) { + vars[key] = value; + continue; + } + else { + // Convert the value to its default value type, ie 0 -> "0px" + const valueAsType = motionDom.getValueAsType(value, motionDom.numberValueTypes[key]); + if (key.startsWith("origin")) { + // If this is a transform origin, flag and enable further transform-origin processing + hasTransformOrigin = true; + transformOrigin[key] = + valueAsType; + } + else { + style[key] = valueAsType; + } + } + } + if (!latestValues.transform) { + if (hasTransform || transformTemplate) { + style.transform = buildTransform(latestValues, state.transform, transformTemplate); + } + else if (style.transform) { + /** + * If we have previously created a transform but currently don't have any, + * reset transform style to none. + */ + style.transform = "none"; + } + } + /** + * Build a transformOrigin style. Uses the same defaults as the browser for + * undefined origins. + */ + if (hasTransformOrigin) { + const { originX = "50%", originY = "50%", originZ = 0, } = transformOrigin; + style.transformOrigin = `${originX} ${originY} ${originZ}`; + } +} + +function renderHTML(element, { style, vars }, styleProp, projection) { + const elementStyle = element.style; + let key; + for (key in style) { + // CSSStyleDeclaration has [index: number]: string; in the types, so we use that as key type. + elementStyle[key] = style[key]; + } + // Write projection styles directly to element style + projection?.applyProjectionStyles(elementStyle, styleProp); + for (key in vars) { + // Loop over any CSS variables and assign those. + // They can only be assigned using `setProperty`. + elementStyle.setProperty(key, vars[key]); + } +} + +function isForcedMotionValue(key, { layout, layoutId }) { + return (motionDom.transformProps.has(key) || + key.startsWith("origin") || + ((layout || layoutId !== undefined) && + (!!scaleCorrectors[key] || key === "opacity"))); +} + +function scrapeMotionValuesFromProps$1(props, prevProps, visualElement) { + const { style } = props; + const newValues = {}; + for (const key in style) { + if (motionDom.isMotionValue(style[key]) || + (prevProps.style && + motionDom.isMotionValue(prevProps.style[key])) || + isForcedMotionValue(key, props) || + visualElement?.getValue(key)?.liveStyle !== undefined) { + newValues[key] = style[key]; + } + } + return newValues; +} + +function getComputedStyle(element) { + return window.getComputedStyle(element); +} +class HTMLVisualElement extends DOMVisualElement { + constructor() { + super(...arguments); + this.type = "html"; + this.renderInstance = renderHTML; + } + readValueFromInstance(instance, key) { + if (motionDom.transformProps.has(key)) { + return this.projection?.isProjecting + ? motionDom.defaultTransformValue(key) + : motionDom.readTransformValue(instance, key); + } + else { + const computedStyle = getComputedStyle(instance); + const value = (motionDom.isCSSVariableName(key) + ? computedStyle.getPropertyValue(key) + : computedStyle[key]) || 0; + return typeof value === "string" ? value.trim() : value; + } + } + measureInstanceViewportBox(instance, { transformPagePoint }) { + return measureViewportBox(instance, transformPagePoint); + } + build(renderState, latestValues, props) { + buildHTMLStyles(renderState, latestValues, props.transformTemplate); + } + scrapeMotionValuesFromProps(props, prevProps, visualElement) { + return scrapeMotionValuesFromProps$1(props, prevProps, visualElement); + } +} + +const LazyContext = React.createContext({ strict: false }); + +function loadFeatures(features) { + for (const key in features) { + featureDefinitions[key] = { + ...featureDefinitions[key], + ...features[key], + }; + } +} + +/** + * A list of all valid MotionProps. + * + * @privateRemarks + * This doesn't throw if a `MotionProp` name is missing - it should. + */ +const validMotionProps = new Set([ + "animate", + "exit", + "variants", + "initial", + "style", + "values", + "variants", + "transition", + "transformTemplate", + "custom", + "inherit", + "onBeforeLayoutMeasure", + "onAnimationStart", + "onAnimationComplete", + "onUpdate", + "onDragStart", + "onDrag", + "onDragEnd", + "onMeasureDragConstraints", + "onDirectionLock", + "onDragTransitionEnd", + "_dragX", + "_dragY", + "onHoverStart", + "onHoverEnd", + "onViewportEnter", + "onViewportLeave", + "globalTapTarget", + "ignoreStrict", + "viewport", +]); +/** + * Check whether a prop name is a valid `MotionProp` key. + * + * @param key - Name of the property to check + * @returns `true` is key is a valid `MotionProp`. + * + * @public + */ +function isValidMotionProp(key) { + return (key.startsWith("while") || + (key.startsWith("drag") && key !== "draggable") || + key.startsWith("layout") || + key.startsWith("onTap") || + key.startsWith("onPan") || + key.startsWith("onLayout") || + validMotionProps.has(key)); +} + +let shouldForward = (key) => !isValidMotionProp(key); +function loadExternalIsValidProp(isValidProp) { + if (typeof isValidProp !== "function") + return; + // Explicitly filter our events + shouldForward = (key) => key.startsWith("on") ? !isValidMotionProp(key) : isValidProp(key); +} +/** + * Emotion and Styled Components both allow users to pass through arbitrary props to their components + * to dynamically generate CSS. They both use the `@emotion/is-prop-valid` package to determine which + * of these should be passed to the underlying DOM node. + * + * However, when styling a Motion component `styled(motion.div)`, both packages pass through *all* props + * as it's seen as an arbitrary component rather than a DOM node. Motion only allows arbitrary props + * passed through the `custom` prop so it doesn't *need* the payload or computational overhead of + * `@emotion/is-prop-valid`, however to fix this problem we need to use it. + * + * By making it an optionalDependency we can offer this functionality only in the situations where it's + * actually required. + */ +try { + /** + * We attempt to import this package but require won't be defined in esm environments, in that case + * isPropValid will have to be provided via `MotionContext`. In a 6.0.0 this should probably be removed + * in favour of explicit injection. + */ + loadExternalIsValidProp(require("@emotion/is-prop-valid").default); +} +catch { + // We don't need to actually do anything here - the fallback is the existing `isPropValid`. +} +function filterProps(props, isDom, forwardMotionProps) { + const filteredProps = {}; + for (const key in props) { + /** + * values is considered a valid prop by Emotion, so if it's present + * this will be rendered out to the DOM unless explicitly filtered. + * + * We check the type as it could be used with the `feColorMatrix` + * element, which we support. + */ + if (key === "values" && typeof props.values === "object") + continue; + if (shouldForward(key) || + (forwardMotionProps === true && isValidMotionProp(key)) || + (!isDom && !isValidMotionProp(key)) || + // If trying to use native HTML drag events, forward drag listeners + (props["draggable"] && + key.startsWith("onDrag"))) { + filteredProps[key] = + props[key]; + } + } + return filteredProps; +} + +const dashKeys = { + offset: "stroke-dashoffset", + array: "stroke-dasharray", +}; +const camelKeys = { + offset: "strokeDashoffset", + array: "strokeDasharray", +}; +/** + * Build SVG path properties. Uses the path's measured length to convert + * our custom pathLength, pathSpacing and pathOffset into stroke-dashoffset + * and stroke-dasharray attributes. + * + * This function is mutative to reduce per-frame GC. + */ +function buildSVGPath(attrs, length, spacing = 1, offset = 0, useDashCase = true) { + // Normalise path length by setting SVG attribute pathLength to 1 + attrs.pathLength = 1; + // We use dash case when setting attributes directly to the DOM node and camel case + // when defining props on a React component. + const keys = useDashCase ? dashKeys : camelKeys; + // Build the dash offset + attrs[keys.offset] = motionDom.px.transform(-offset); + // Build the dash array + const pathLength = motionDom.px.transform(length); + const pathSpacing = motionDom.px.transform(spacing); + attrs[keys.array] = `${pathLength} ${pathSpacing}`; +} + +/** + * Build SVG visual attributes, like cx and style.transform + */ +function buildSVGAttrs(state, { attrX, attrY, attrScale, pathLength, pathSpacing = 1, pathOffset = 0, +// This is object creation, which we try to avoid per-frame. +...latest }, isSVGTag, transformTemplate, styleProp) { + buildHTMLStyles(state, latest, transformTemplate); + /** + * For svg tags we just want to make sure viewBox is animatable and treat all the styles + * as normal HTML tags. + */ + if (isSVGTag) { + if (state.style.viewBox) { + state.attrs.viewBox = state.style.viewBox; + } + return; + } + state.attrs = state.style; + state.style = {}; + const { attrs, style } = state; + /** + * However, we apply transforms as CSS transforms. + * So if we detect a transform, transformOrigin we take it from attrs and copy it into style. + */ + if (attrs.transform) { + style.transform = attrs.transform; + delete attrs.transform; + } + if (style.transform || attrs.transformOrigin) { + style.transformOrigin = attrs.transformOrigin ?? "50% 50%"; + delete attrs.transformOrigin; + } + if (style.transform) { + /** + * SVG's element transform-origin uses its own median as a reference. + * Therefore, transformBox becomes a fill-box + */ + style.transformBox = styleProp?.transformBox ?? "fill-box"; + delete attrs.transformBox; + } + // Render attrX/attrY/attrScale as attributes + if (attrX !== undefined) + attrs.x = attrX; + if (attrY !== undefined) + attrs.y = attrY; + if (attrScale !== undefined) + attrs.scale = attrScale; + // Build SVG path if one has been defined + if (pathLength !== undefined) { + buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false); + } +} + +/** + * A set of attribute names that are always read/written as camel case. + */ +const camelCaseAttributes = new Set([ + "baseFrequency", + "diffuseConstant", + "kernelMatrix", + "kernelUnitLength", + "keySplines", + "keyTimes", + "limitingConeAngle", + "markerHeight", + "markerWidth", + "numOctaves", + "targetX", + "targetY", + "surfaceScale", + "specularConstant", + "specularExponent", + "stdDeviation", + "tableValues", + "viewBox", + "gradientTransform", + "pathLength", + "startOffset", + "textLength", + "lengthAdjust", +]); + +const isSVGTag = (tag) => typeof tag === "string" && tag.toLowerCase() === "svg"; + +function renderSVG(element, renderState, _styleProp, projection) { + renderHTML(element, renderState, undefined, projection); + for (const key in renderState.attrs) { + element.setAttribute(!camelCaseAttributes.has(key) ? camelToDash(key) : key, renderState.attrs[key]); + } +} + +function scrapeMotionValuesFromProps(props, prevProps, visualElement) { + const newValues = scrapeMotionValuesFromProps$1(props, prevProps, visualElement); + for (const key in props) { + if (motionDom.isMotionValue(props[key]) || + motionDom.isMotionValue(prevProps[key])) { + const targetKey = motionDom.transformPropOrder.indexOf(key) !== -1 + ? "attr" + key.charAt(0).toUpperCase() + key.substring(1) + : key; + newValues[targetKey] = props[key]; + } + } + return newValues; +} + +class SVGVisualElement extends DOMVisualElement { + constructor() { + super(...arguments); + this.type = "svg"; + this.isSVGTag = false; + this.measureInstanceViewportBox = createBox; + } + getBaseTargetFromProps(props, key) { + return props[key]; + } + readValueFromInstance(instance, key) { + if (motionDom.transformProps.has(key)) { + const defaultType = motionDom.getDefaultValueType(key); + return defaultType ? defaultType.default || 0 : 0; + } + key = !camelCaseAttributes.has(key) ? camelToDash(key) : key; + return instance.getAttribute(key); + } + scrapeMotionValuesFromProps(props, prevProps, visualElement) { + return scrapeMotionValuesFromProps(props, prevProps, visualElement); + } + build(renderState, latestValues, props) { + buildSVGAttrs(renderState, latestValues, this.isSVGTag, props.transformTemplate, props.style); + } + renderInstance(instance, renderState, styleProp, projection) { + renderSVG(instance, renderState, styleProp, projection); + } + mount(instance) { + this.isSVGTag = isSVGTag(instance.tagName); + super.mount(instance); + } +} + +/** + * We keep these listed separately as we use the lowercase tag names as part + * of the runtime bundle to detect SVG components + */ +const lowercaseSVGElements = [ + "animate", + "circle", + "defs", + "desc", + "ellipse", + "g", + "image", + "line", + "filter", + "marker", + "mask", + "metadata", + "path", + "pattern", + "polygon", + "polyline", + "rect", + "stop", + "switch", + "symbol", + "svg", + "text", + "tspan", + "use", + "view", +]; + +function isSVGComponent(Component) { + if ( + /** + * If it's not a string, it's a custom React component. Currently we only support + * HTML custom React components. + */ + typeof Component !== "string" || + /** + * If it contains a dash, the element is a custom HTML webcomponent. + */ + Component.includes("-")) { + return false; + } + else if ( + /** + * If it's in our list of lowercase SVG tags, it's an SVG component + */ + lowercaseSVGElements.indexOf(Component) > -1 || + /** + * If it contains a capital letter, it's an SVG component + */ + /[A-Z]/u.test(Component)) { + return true; + } + return false; +} + +const createDomVisualElement = (Component, options) => { + return isSVGComponent(Component) + ? new SVGVisualElement(options) + : new HTMLVisualElement(options, { + allowProjection: Component !== React.Fragment, + }); +}; + +const MotionContext = /* @__PURE__ */ React.createContext({}); + +function getCurrentTreeVariants(props, context) { + if (isControllingVariants(props)) { + const { initial, animate } = props; + return { + initial: initial === false || isVariantLabel(initial) + ? initial + : undefined, + animate: isVariantLabel(animate) ? animate : undefined, + }; + } + return props.inherit !== false ? context : {}; +} + +function useCreateMotionContext(props) { + const { initial, animate } = getCurrentTreeVariants(props, React.useContext(MotionContext)); + return React.useMemo(() => ({ initial, animate }), [variantLabelsAsDependency(initial), variantLabelsAsDependency(animate)]); +} +function variantLabelsAsDependency(prop) { + return Array.isArray(prop) ? prop.join(" ") : prop; +} + +const createHtmlRenderState = () => ({ + style: {}, + transform: {}, + transformOrigin: {}, + vars: {}, +}); + +function copyRawValuesOnly(target, source, props) { + for (const key in source) { + if (!motionDom.isMotionValue(source[key]) && !isForcedMotionValue(key, props)) { + target[key] = source[key]; + } + } +} +function useInitialMotionValues({ transformTemplate }, visualState) { + return React.useMemo(() => { + const state = createHtmlRenderState(); + buildHTMLStyles(state, visualState, transformTemplate); + return Object.assign({}, state.vars, state.style); + }, [visualState]); +} +function useStyle(props, visualState) { + const styleProp = props.style || {}; + const style = {}; + /** + * Copy non-Motion Values straight into style + */ + copyRawValuesOnly(style, styleProp, props); + Object.assign(style, useInitialMotionValues(props, visualState)); + return style; +} +function useHTMLProps(props, visualState) { + // The `any` isn't ideal but it is the type of createElement props argument + const htmlProps = {}; + const style = useStyle(props, visualState); + if (props.drag && props.dragListener !== false) { + // Disable the ghost element when a user drags + htmlProps.draggable = false; + // Disable text selection + style.userSelect = + style.WebkitUserSelect = + style.WebkitTouchCallout = + "none"; + // Disable scrolling on the draggable direction + style.touchAction = + props.drag === true + ? "none" + : `pan-${props.drag === "x" ? "y" : "x"}`; + } + if (props.tabIndex === undefined && + (props.onTap || props.onTapStart || props.whileTap)) { + htmlProps.tabIndex = 0; + } + htmlProps.style = style; + return htmlProps; +} + +const createSvgRenderState = () => ({ + ...createHtmlRenderState(), + attrs: {}, +}); + +function useSVGProps(props, visualState, _isStatic, Component) { + const visualProps = React.useMemo(() => { + const state = createSvgRenderState(); + buildSVGAttrs(state, visualState, isSVGTag(Component), props.transformTemplate, props.style); + return { + ...state.attrs, + style: { ...state.style }, + }; + }, [visualState]); + if (props.style) { + const rawStyles = {}; + copyRawValuesOnly(rawStyles, props.style, props); + visualProps.style = { ...rawStyles, ...visualProps.style }; + } + return visualProps; +} + +function useRender(Component, props, ref, { latestValues, }, isStatic, forwardMotionProps = false) { + const useVisualProps = isSVGComponent(Component) + ? useSVGProps + : useHTMLProps; + const visualProps = useVisualProps(props, latestValues, isStatic, Component); + const filteredProps = filterProps(props, typeof Component === "string", forwardMotionProps); + const elementProps = Component !== React.Fragment ? { ...filteredProps, ...visualProps, ref } : {}; + /** + * If component has been handed a motion value as its child, + * memoise its initial value and render that. Subsequent updates + * will be handled by the onChange handler + */ + const { children } = props; + const renderedChildren = React.useMemo(() => (motionDom.isMotionValue(children) ? children.get() : children), [children]); + return React.createElement(Component, { + ...elementProps, + children: renderedChildren, + }); +} + +function makeState({ scrapeMotionValuesFromProps, createRenderState, }, props, context, presenceContext) { + const state = { + latestValues: makeLatestValues(props, context, presenceContext, scrapeMotionValuesFromProps), + renderState: createRenderState(), + }; + return state; +} +function makeLatestValues(props, context, presenceContext, scrapeMotionValues) { + const values = {}; + const motionValues = scrapeMotionValues(props, {}); + for (const key in motionValues) { + values[key] = resolveMotionValue(motionValues[key]); + } + let { initial, animate } = props; + const isControllingVariants$1 = isControllingVariants(props); + const isVariantNode$1 = isVariantNode(props); + if (context && + isVariantNode$1 && + !isControllingVariants$1 && + props.inherit !== false) { + if (initial === undefined) + initial = context.initial; + if (animate === undefined) + animate = context.animate; + } + let isInitialAnimationBlocked = presenceContext + ? presenceContext.initial === false + : false; + isInitialAnimationBlocked = isInitialAnimationBlocked || initial === false; + const variantToSet = isInitialAnimationBlocked ? animate : initial; + if (variantToSet && + typeof variantToSet !== "boolean" && + !isAnimationControls(variantToSet)) { + const list = Array.isArray(variantToSet) ? variantToSet : [variantToSet]; + for (let i = 0; i < list.length; i++) { + const resolved = resolveVariantFromProps(props, list[i]); + if (resolved) { + const { transitionEnd, transition, ...target } = resolved; + for (const key in target) { + let valueTarget = target[key]; + if (Array.isArray(valueTarget)) { + /** + * Take final keyframe if the initial animation is blocked because + * we want to initialise at the end of that blocked animation. + */ + const index = isInitialAnimationBlocked + ? valueTarget.length - 1 + : 0; + valueTarget = valueTarget[index]; + } + if (valueTarget !== null) { + values[key] = valueTarget; + } + } + for (const key in transitionEnd) { + values[key] = transitionEnd[key]; + } + } + } + } + return values; +} +const makeUseVisualState = (config) => (props, isStatic) => { + const context = React.useContext(MotionContext); + const presenceContext = React.useContext(PresenceContext); + const make = () => makeState(config, props, context, presenceContext); + return isStatic ? make() : useConstant(make); +}; + +const useHTMLVisualState = /*@__PURE__*/ makeUseVisualState({ + scrapeMotionValuesFromProps: scrapeMotionValuesFromProps$1, + createRenderState: createHtmlRenderState, +}); + +const useSVGVisualState = /*@__PURE__*/ makeUseVisualState({ + scrapeMotionValuesFromProps: scrapeMotionValuesFromProps, + createRenderState: createSvgRenderState, +}); + +const motionComponentSymbol = Symbol.for("motionComponentSymbol"); + +function isRefObject(ref) { + return (ref && + typeof ref === "object" && + Object.prototype.hasOwnProperty.call(ref, "current")); +} + +/** + * Creates a ref function that, when called, hydrates the provided + * external ref and VisualElement. + */ +function useMotionRef(visualState, visualElement, externalRef) { + return React.useCallback((instance) => { + if (instance) { + visualState.onMount && visualState.onMount(instance); + } + if (visualElement) { + if (instance) { + visualElement.mount(instance); + } + else { + visualElement.unmount(); + } + } + if (externalRef) { + if (typeof externalRef === "function") { + externalRef(instance); + } + else if (isRefObject(externalRef)) { + externalRef.current = instance; + } + } + }, + /** + * Only pass a new ref callback to React if we've received a visual element + * factory. Otherwise we'll be mounting/remounting every time externalRef + * or other dependencies change. + */ + [visualElement]); +} + +/** + * Internal, exported only for usage in Framer + */ +const SwitchLayoutGroupContext = React.createContext({}); + +function useVisualElement(Component, visualState, props, createVisualElement, ProjectionNodeConstructor) { + const { visualElement: parent } = React.useContext(MotionContext); + const lazyContext = React.useContext(LazyContext); + const presenceContext = React.useContext(PresenceContext); + const reducedMotionConfig = React.useContext(MotionConfigContext).reducedMotion; + const visualElementRef = React.useRef(null); + /** + * If we haven't preloaded a renderer, check to see if we have one lazy-loaded + */ + createVisualElement = + createVisualElement || + lazyContext.renderer; + if (!visualElementRef.current && createVisualElement) { + visualElementRef.current = createVisualElement(Component, { + visualState, + parent, + props, + presenceContext, + blockInitialAnimation: presenceContext + ? presenceContext.initial === false + : false, + reducedMotionConfig, + }); + } + const visualElement = visualElementRef.current; + /** + * Load Motion gesture and animation features. These are rendered as renderless + * components so each feature can optionally make use of React lifecycle methods. + */ + const initialLayoutGroupConfig = React.useContext(SwitchLayoutGroupContext); + if (visualElement && + !visualElement.projection && + ProjectionNodeConstructor && + (visualElement.type === "html" || visualElement.type === "svg")) { + createProjectionNode(visualElementRef.current, props, ProjectionNodeConstructor, initialLayoutGroupConfig); + } + const isMounted = React.useRef(false); + React.useInsertionEffect(() => { + /** + * Check the component has already mounted before calling + * `update` unnecessarily. This ensures we skip the initial update. + */ + if (visualElement && isMounted.current) { + visualElement.update(props, presenceContext); + } + }); + /** + * Cache this value as we want to know whether HandoffAppearAnimations + * was present on initial render - it will be deleted after this. + */ + const optimisedAppearId = props[optimizedAppearDataAttribute]; + const wantsHandoff = React.useRef(Boolean(optimisedAppearId) && + !window.MotionHandoffIsComplete?.(optimisedAppearId) && + window.MotionHasOptimisedAnimation?.(optimisedAppearId)); + useIsomorphicLayoutEffect(() => { + if (!visualElement) + return; + isMounted.current = true; + window.MotionIsMounted = true; + visualElement.updateFeatures(); + visualElement.scheduleRenderMicrotask(); + /** + * Ideally this function would always run in a useEffect. + * + * However, if we have optimised appear animations to handoff from, + * it needs to happen synchronously to ensure there's no flash of + * incorrect styles in the event of a hydration error. + * + * So if we detect a situtation where optimised appear animations + * are running, we use useLayoutEffect to trigger animations. + */ + if (wantsHandoff.current && visualElement.animationState) { + visualElement.animationState.animateChanges(); + } + }); + React.useEffect(() => { + if (!visualElement) + return; + if (!wantsHandoff.current && visualElement.animationState) { + visualElement.animationState.animateChanges(); + } + if (wantsHandoff.current) { + // This ensures all future calls to animateChanges() in this component will run in useEffect + queueMicrotask(() => { + window.MotionHandoffMarkAsComplete?.(optimisedAppearId); + }); + wantsHandoff.current = false; + } + /** + * Now we've finished triggering animations for this element we + * can wipe the enteringChildren set for the next render. + */ + visualElement.enteringChildren = undefined; + }); + return visualElement; +} +function createProjectionNode(visualElement, props, ProjectionNodeConstructor, initialPromotionConfig) { + const { layoutId, layout, drag, dragConstraints, layoutScroll, layoutRoot, layoutCrossfade, } = props; + visualElement.projection = new ProjectionNodeConstructor(visualElement.latestValues, props["data-framer-portal-id"] + ? undefined + : getClosestProjectingNode(visualElement.parent)); + visualElement.projection.setOptions({ + layoutId, + layout, + alwaysMeasureLayout: Boolean(drag) || (dragConstraints && isRefObject(dragConstraints)), + visualElement, + /** + * TODO: Update options in an effect. This could be tricky as it'll be too late + * to update by the time layout animations run. + * We also need to fix this safeToRemove by linking it up to the one returned by usePresence, + * ensuring it gets called if there's no potential layout animations. + * + */ + animationType: typeof layout === "string" ? layout : "both", + initialPromotionConfig, + crossfade: layoutCrossfade, + layoutScroll, + layoutRoot, + }); +} +function getClosestProjectingNode(visualElement) { + if (!visualElement) + return undefined; + return visualElement.options.allowProjection !== false + ? visualElement.projection + : getClosestProjectingNode(visualElement.parent); +} + +/** + * Create a `motion` component. + * + * This function accepts a Component argument, which can be either a string (ie "div" + * for `motion.div`), or an actual React component. + * + * Alongside this is a config option which provides a way of rendering the provided + * component "offline", or outside the React render cycle. + */ +function createMotionComponent(Component, { forwardMotionProps = false } = {}, preloadedFeatures, createVisualElement) { + preloadedFeatures && loadFeatures(preloadedFeatures); + const useVisualState = isSVGComponent(Component) + ? useSVGVisualState + : useHTMLVisualState; + function MotionDOMComponent(props, externalRef) { + /** + * If we need to measure the element we load this functionality in a + * separate class component in order to gain access to getSnapshotBeforeUpdate. + */ + let MeasureLayout; + const configAndProps = { + ...React.useContext(MotionConfigContext), + ...props, + layoutId: useLayoutId(props), + }; + const { isStatic } = configAndProps; + const context = useCreateMotionContext(props); + const visualState = useVisualState(props, isStatic); + if (!isStatic && isBrowser) { + useStrictMode(configAndProps, preloadedFeatures); + const layoutProjection = getProjectionFunctionality(configAndProps); + MeasureLayout = layoutProjection.MeasureLayout; + /** + * Create a VisualElement for this component. A VisualElement provides a common + * interface to renderer-specific APIs (ie DOM/Three.js etc) as well as + * providing a way of rendering to these APIs outside of the React render loop + * for more performant animations and interactions + */ + context.visualElement = useVisualElement(Component, visualState, configAndProps, createVisualElement, layoutProjection.ProjectionNode); + } + /** + * The mount order and hierarchy is specific to ensure our element ref + * is hydrated by the time features fire their effects. + */ + return (jsxRuntime.jsxs(MotionContext.Provider, { value: context, children: [MeasureLayout && context.visualElement ? (jsxRuntime.jsx(MeasureLayout, { visualElement: context.visualElement, ...configAndProps })) : null, useRender(Component, props, useMotionRef(visualState, context.visualElement, externalRef), visualState, isStatic, forwardMotionProps)] })); + } + MotionDOMComponent.displayName = `motion.${typeof Component === "string" + ? Component + : `create(${Component.displayName ?? Component.name ?? ""})`}`; + const ForwardRefMotionComponent = React.forwardRef(MotionDOMComponent); + ForwardRefMotionComponent[motionComponentSymbol] = Component; + return ForwardRefMotionComponent; +} +function useLayoutId({ layoutId }) { + const layoutGroupId = React.useContext(LayoutGroupContext).id; + return layoutGroupId && layoutId !== undefined + ? layoutGroupId + "-" + layoutId + : layoutId; +} +function useStrictMode(configAndProps, preloadedFeatures) { + const isStrict = React.useContext(LazyContext).strict; + /** + * If we're in development mode, check to make sure we're not rendering a motion component + * as a child of LazyMotion, as this will break the file-size benefits of using it. + */ + if (process.env.NODE_ENV !== "production" && + preloadedFeatures && + isStrict) { + const strictMessage = "You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead."; + configAndProps.ignoreStrict + ? motionUtils.warning(false, strictMessage, "lazy-strict-mode") + : motionUtils.invariant(false, strictMessage, "lazy-strict-mode"); + } +} +function getProjectionFunctionality(props) { + const { drag, layout } = featureDefinitions; + if (!drag && !layout) + return {}; + const combined = { ...drag, ...layout }; + return { + MeasureLayout: drag?.isEnabled(props) || layout?.isEnabled(props) + ? combined.MeasureLayout + : undefined, + ProjectionNode: combined.ProjectionNode, + }; +} + +function resolveVariant(visualElement, definition, custom) { + const props = visualElement.getProps(); + return resolveVariantFromProps(props, definition, custom !== undefined ? custom : props.custom, visualElement); +} + +const isKeyframesTarget = (v) => { + return Array.isArray(v); +}; + +/** + * Set VisualElement's MotionValue, creating a new MotionValue for it if + * it doesn't exist. + */ +function setMotionValue(visualElement, key, value) { + if (visualElement.hasValue(key)) { + visualElement.getValue(key).set(value); + } + else { + visualElement.addValue(key, motionDom.motionValue(value)); + } +} +function resolveFinalValueInKeyframes(v) { + // TODO maybe throw if v.length - 1 is placeholder token? + return isKeyframesTarget(v) ? v[v.length - 1] || 0 : v; +} +function setTarget(visualElement, definition) { + const resolved = resolveVariant(visualElement, definition); + let { transitionEnd = {}, transition = {}, ...target } = resolved || {}; + target = { ...target, ...transitionEnd }; + for (const key in target) { + const value = resolveFinalValueInKeyframes(target[key]); + setMotionValue(visualElement, key, value); + } +} + +function isWillChangeMotionValue(value) { + return Boolean(motionDom.isMotionValue(value) && value.add); +} + +function addValueToWillChange(visualElement, key) { + const willChange = visualElement.getValue("willChange"); + /** + * It could be that a user has set willChange to a regular MotionValue, + * in which case we can't add the value to it. + */ + if (isWillChangeMotionValue(willChange)) { + return willChange.add(key); + } + else if (!willChange && motionUtils.MotionGlobalConfig.WillChange) { + const newWillChange = new motionUtils.MotionGlobalConfig.WillChange("auto"); + visualElement.addValue("willChange", newWillChange); + newWillChange.add(key); + } +} + +/** + * Decide whether we should block this animation. Previously, we achieved this + * just by checking whether the key was listed in protectedKeys, but this + * posed problems if an animation was triggered by afterChildren and protectedKeys + * had been set to true in the meantime. + */ +function shouldBlockAnimation({ protectedKeys, needsAnimating }, key) { + const shouldBlock = protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true; + needsAnimating[key] = false; + return shouldBlock; +} +function animateTarget(visualElement, targetAndTransition, { delay = 0, transitionOverride, type } = {}) { + let { transition = visualElement.getDefaultTransition(), transitionEnd, ...target } = targetAndTransition; + if (transitionOverride) + transition = transitionOverride; + const animations = []; + const animationTypeState = type && + visualElement.animationState && + visualElement.animationState.getState()[type]; + for (const key in target) { + const value = visualElement.getValue(key, visualElement.latestValues[key] ?? null); + const valueTarget = target[key]; + if (valueTarget === undefined || + (animationTypeState && + shouldBlockAnimation(animationTypeState, key))) { + continue; + } + const valueTransition = { + delay, + ...motionDom.getValueTransition(transition || {}, key), + }; + /** + * If the value is already at the defined target, skip the animation. + */ + const currentValue = value.get(); + if (currentValue !== undefined && + !value.isAnimating && + !Array.isArray(valueTarget) && + valueTarget === currentValue && + !valueTransition.velocity) { + continue; + } + /** + * If this is the first time a value is being animated, check + * to see if we're handling off from an existing animation. + */ + let isHandoff = false; + if (window.MotionHandoffAnimation) { + const appearId = getOptimisedAppearId(visualElement); + if (appearId) { + const startTime = window.MotionHandoffAnimation(appearId, key, motionDom.frame); + if (startTime !== null) { + valueTransition.startTime = startTime; + isHandoff = true; + } + } + } + addValueToWillChange(visualElement, key); + value.start(animateMotionValue(key, value, valueTarget, visualElement.shouldReduceMotion && motionDom.positionalKeys.has(key) + ? { type: false } + : valueTransition, visualElement, isHandoff)); + const animation = value.animation; + if (animation) { + animations.push(animation); + } + } + if (transitionEnd) { + Promise.all(animations).then(() => { + motionDom.frame.update(() => { + transitionEnd && setTarget(visualElement, transitionEnd); + }); + }); + } + return animations; +} + +function calcChildStagger(children, child, delayChildren, staggerChildren = 0, staggerDirection = 1) { + const index = Array.from(children) + .sort((a, b) => a.sortNodePosition(b)) + .indexOf(child); + const numChildren = children.size; + const maxStaggerDuration = (numChildren - 1) * staggerChildren; + const delayIsFunction = typeof delayChildren === "function"; + return delayIsFunction + ? delayChildren(index, numChildren) + : staggerDirection === 1 + ? index * staggerChildren + : maxStaggerDuration - index * staggerChildren; +} + +function animateVariant(visualElement, variant, options = {}) { + const resolved = resolveVariant(visualElement, variant, options.type === "exit" + ? visualElement.presenceContext?.custom + : undefined); + let { transition = visualElement.getDefaultTransition() || {} } = resolved || {}; + if (options.transitionOverride) { + transition = options.transitionOverride; + } + /** + * If we have a variant, create a callback that runs it as an animation. + * Otherwise, we resolve a Promise immediately for a composable no-op. + */ + const getAnimation = resolved + ? () => Promise.all(animateTarget(visualElement, resolved, options)) + : () => Promise.resolve(); + /** + * If we have children, create a callback that runs all their animations. + * Otherwise, we resolve a Promise immediately for a composable no-op. + */ + const getChildAnimations = visualElement.variantChildren && visualElement.variantChildren.size + ? (forwardDelay = 0) => { + const { delayChildren = 0, staggerChildren, staggerDirection, } = transition; + return animateChildren(visualElement, variant, forwardDelay, delayChildren, staggerChildren, staggerDirection, options); + } + : () => Promise.resolve(); + /** + * If the transition explicitly defines a "when" option, we need to resolve either + * this animation or all children animations before playing the other. + */ + const { when } = transition; + if (when) { + const [first, last] = when === "beforeChildren" + ? [getAnimation, getChildAnimations] + : [getChildAnimations, getAnimation]; + return first().then(() => last()); + } + else { + return Promise.all([getAnimation(), getChildAnimations(options.delay)]); + } +} +function animateChildren(visualElement, variant, delay = 0, delayChildren = 0, staggerChildren = 0, staggerDirection = 1, options) { + const animations = []; + for (const child of visualElement.variantChildren) { + child.notify("AnimationStart", variant); + animations.push(animateVariant(child, variant, { + ...options, + delay: delay + + (typeof delayChildren === "function" ? 0 : delayChildren) + + calcChildStagger(visualElement.variantChildren, child, delayChildren, staggerChildren, staggerDirection), + }).then(() => child.notify("AnimationComplete", variant))); + } + return Promise.all(animations); +} + +function animateVisualElement(visualElement, definition, options = {}) { + visualElement.notify("AnimationStart", definition); + let animation; + if (Array.isArray(definition)) { + const animations = definition.map((variant) => animateVariant(visualElement, variant, options)); + animation = Promise.all(animations); + } + else if (typeof definition === "string") { + animation = animateVariant(visualElement, definition, options); + } + else { + const resolvedDefinition = typeof definition === "function" + ? resolveVariant(visualElement, definition, options.custom) + : definition; + animation = Promise.all(animateTarget(visualElement, resolvedDefinition, options)); + } + return animation.then(() => { + visualElement.notify("AnimationComplete", definition); + }); +} + +function shallowCompare(next, prev) { + if (!Array.isArray(prev)) + return false; + const prevLength = prev.length; + if (prevLength !== next.length) + return false; + for (let i = 0; i < prevLength; i++) { + if (prev[i] !== next[i]) + return false; + } + return true; +} + +const numVariantProps = variantProps.length; +function getVariantContext(visualElement) { + if (!visualElement) + return undefined; + if (!visualElement.isControllingVariants) { + const context = visualElement.parent + ? getVariantContext(visualElement.parent) || {} + : {}; + if (visualElement.props.initial !== undefined) { + context.initial = visualElement.props.initial; + } + return context; + } + const context = {}; + for (let i = 0; i < numVariantProps; i++) { + const name = variantProps[i]; + const prop = visualElement.props[name]; + if (isVariantLabel(prop) || prop === false) { + context[name] = prop; + } + } + return context; +} + +const reversePriorityOrder = [...variantPriorityOrder].reverse(); +const numAnimationTypes = variantPriorityOrder.length; +function animateList(visualElement) { + return (animations) => Promise.all(animations.map(({ animation, options }) => animateVisualElement(visualElement, animation, options))); +} +function createAnimationState(visualElement) { + let animate = animateList(visualElement); + let state = createState(); + let isInitialRender = true; + /** + * This function will be used to reduce the animation definitions for + * each active animation type into an object of resolved values for it. + */ + const buildResolvedTypeValues = (type) => (acc, definition) => { + const resolved = resolveVariant(visualElement, definition, type === "exit" + ? visualElement.presenceContext?.custom + : undefined); + if (resolved) { + const { transition, transitionEnd, ...target } = resolved; + acc = { ...acc, ...target, ...transitionEnd }; + } + return acc; + }; + /** + * This just allows us to inject mocked animation functions + * @internal + */ + function setAnimateFunction(makeAnimator) { + animate = makeAnimator(visualElement); + } + /** + * When we receive new props, we need to: + * 1. Create a list of protected keys for each type. This is a directory of + * value keys that are currently being "handled" by types of a higher priority + * so that whenever an animation is played of a given type, these values are + * protected from being animated. + * 2. Determine if an animation type needs animating. + * 3. Determine if any values have been removed from a type and figure out + * what to animate those to. + */ + function animateChanges(changedActiveType) { + const { props } = visualElement; + const context = getVariantContext(visualElement.parent) || {}; + /** + * A list of animations that we'll build into as we iterate through the animation + * types. This will get executed at the end of the function. + */ + const animations = []; + /** + * Keep track of which values have been removed. Then, as we hit lower priority + * animation types, we can check if they contain removed values and animate to that. + */ + const removedKeys = new Set(); + /** + * A dictionary of all encountered keys. This is an object to let us build into and + * copy it without iteration. Each time we hit an animation type we set its protected + * keys - the keys its not allowed to animate - to the latest version of this object. + */ + let encounteredKeys = {}; + /** + * If a variant has been removed at a given index, and this component is controlling + * variant animations, we want to ensure lower-priority variants are forced to animate. + */ + let removedVariantIndex = Infinity; + /** + * Iterate through all animation types in reverse priority order. For each, we want to + * detect which values it's handling and whether or not they've changed (and therefore + * need to be animated). If any values have been removed, we want to detect those in + * lower priority props and flag for animation. + */ + for (let i = 0; i < numAnimationTypes; i++) { + const type = reversePriorityOrder[i]; + const typeState = state[type]; + const prop = props[type] !== undefined + ? props[type] + : context[type]; + const propIsVariant = isVariantLabel(prop); + /** + * If this type has *just* changed isActive status, set activeDelta + * to that status. Otherwise set to null. + */ + const activeDelta = type === changedActiveType ? typeState.isActive : null; + if (activeDelta === false) + removedVariantIndex = i; + /** + * If this prop is an inherited variant, rather than been set directly on the + * component itself, we want to make sure we allow the parent to trigger animations. + * + * TODO: Can probably change this to a !isControllingVariants check + */ + let isInherited = prop === context[type] && + prop !== props[type] && + propIsVariant; + if (isInherited && + isInitialRender && + visualElement.manuallyAnimateOnMount) { + isInherited = false; + } + /** + * Set all encountered keys so far as the protected keys for this type. This will + * be any key that has been animated or otherwise handled by active, higher-priortiy types. + */ + typeState.protectedKeys = { ...encounteredKeys }; + // Check if we can skip analysing this prop early + if ( + // If it isn't active and hasn't *just* been set as inactive + (!typeState.isActive && activeDelta === null) || + // If we didn't and don't have any defined prop for this animation type + (!prop && !typeState.prevProp) || + // Or if the prop doesn't define an animation + isAnimationControls(prop) || + typeof prop === "boolean") { + continue; + } + /** + * As we go look through the values defined on this type, if we detect + * a changed value or a value that was removed in a higher priority, we set + * this to true and add this prop to the animation list. + */ + const variantDidChange = checkVariantsDidChange(typeState.prevProp, prop); + let shouldAnimateType = variantDidChange || + // If we're making this variant active, we want to always make it active + (type === changedActiveType && + typeState.isActive && + !isInherited && + propIsVariant) || + // If we removed a higher-priority variant (i is in reverse order) + (i > removedVariantIndex && propIsVariant); + let handledRemovedValues = false; + /** + * As animations can be set as variant lists, variants or target objects, we + * coerce everything to an array if it isn't one already + */ + const definitionList = Array.isArray(prop) ? prop : [prop]; + /** + * Build an object of all the resolved values. We'll use this in the subsequent + * animateChanges calls to determine whether a value has changed. + */ + let resolvedValues = definitionList.reduce(buildResolvedTypeValues(type), {}); + if (activeDelta === false) + resolvedValues = {}; + /** + * Now we need to loop through all the keys in the prev prop and this prop, + * and decide: + * 1. If the value has changed, and needs animating + * 2. If it has been removed, and needs adding to the removedKeys set + * 3. If it has been removed in a higher priority type and needs animating + * 4. If it hasn't been removed in a higher priority but hasn't changed, and + * needs adding to the type's protectedKeys list. + */ + const { prevResolvedValues = {} } = typeState; + const allKeys = { + ...prevResolvedValues, + ...resolvedValues, + }; + const markToAnimate = (key) => { + shouldAnimateType = true; + if (removedKeys.has(key)) { + handledRemovedValues = true; + removedKeys.delete(key); + } + typeState.needsAnimating[key] = true; + const motionValue = visualElement.getValue(key); + if (motionValue) + motionValue.liveStyle = false; + }; + for (const key in allKeys) { + const next = resolvedValues[key]; + const prev = prevResolvedValues[key]; + // If we've already handled this we can just skip ahead + if (encounteredKeys.hasOwnProperty(key)) + continue; + /** + * If the value has changed, we probably want to animate it. + */ + let valueHasChanged = false; + if (isKeyframesTarget(next) && isKeyframesTarget(prev)) { + valueHasChanged = !shallowCompare(next, prev); + } + else { + valueHasChanged = next !== prev; + } + if (valueHasChanged) { + if (next !== undefined && next !== null) { + // If next is defined and doesn't equal prev, it needs animating + markToAnimate(key); + } + else { + // If it's undefined, it's been removed. + removedKeys.add(key); + } + } + else if (next !== undefined && removedKeys.has(key)) { + /** + * If next hasn't changed and it isn't undefined, we want to check if it's + * been removed by a higher priority + */ + markToAnimate(key); + } + else { + /** + * If it hasn't changed, we add it to the list of protected values + * to ensure it doesn't get animated. + */ + typeState.protectedKeys[key] = true; + } + } + /** + * Update the typeState so next time animateChanges is called we can compare the + * latest prop and resolvedValues to these. + */ + typeState.prevProp = prop; + typeState.prevResolvedValues = resolvedValues; + if (typeState.isActive) { + encounteredKeys = { ...encounteredKeys, ...resolvedValues }; + } + if (isInitialRender && visualElement.blockInitialAnimation) { + shouldAnimateType = false; + } + /** + * If this is an inherited prop we want to skip this animation + * unless the inherited variants haven't changed on this render. + */ + const willAnimateViaParent = isInherited && variantDidChange; + const needsAnimating = !willAnimateViaParent || handledRemovedValues; + if (shouldAnimateType && needsAnimating) { + animations.push(...definitionList.map((animation) => { + const options = { type }; + /** + * If we're performing the initial animation, but we're not + * rendering at the same time as the variant-controlling parent, + * we want to use the parent's transition to calculate the stagger. + */ + if (typeof animation === "string" && + isInitialRender && + !willAnimateViaParent && + visualElement.manuallyAnimateOnMount && + visualElement.parent) { + const { parent } = visualElement; + const parentVariant = resolveVariant(parent, animation); + if (parent.enteringChildren && parentVariant) { + const { delayChildren } = parentVariant.transition || {}; + options.delay = calcChildStagger(parent.enteringChildren, visualElement, delayChildren); + } + } + return { + animation: animation, + options, + }; + })); + } + } + /** + * If there are some removed value that haven't been dealt with, + * we need to create a new animation that falls back either to the value + * defined in the style prop, or the last read value. + */ + if (removedKeys.size) { + const fallbackAnimation = {}; + /** + * If the initial prop contains a transition we can use that, otherwise + * allow the animation function to use the visual element's default. + */ + if (typeof props.initial !== "boolean") { + const initialTransition = resolveVariant(visualElement, Array.isArray(props.initial) + ? props.initial[0] + : props.initial); + if (initialTransition && initialTransition.transition) { + fallbackAnimation.transition = initialTransition.transition; + } + } + removedKeys.forEach((key) => { + const fallbackTarget = visualElement.getBaseTarget(key); + const motionValue = visualElement.getValue(key); + if (motionValue) + motionValue.liveStyle = true; + // @ts-expect-error - @mattgperry to figure if we should do something here + fallbackAnimation[key] = fallbackTarget ?? null; + }); + animations.push({ animation: fallbackAnimation }); + } + let shouldAnimate = Boolean(animations.length); + if (isInitialRender && + (props.initial === false || props.initial === props.animate) && + !visualElement.manuallyAnimateOnMount) { + shouldAnimate = false; + } + isInitialRender = false; + return shouldAnimate ? animate(animations) : Promise.resolve(); + } + /** + * Change whether a certain animation type is active. + */ + function setActive(type, isActive) { + // If the active state hasn't changed, we can safely do nothing here + if (state[type].isActive === isActive) + return Promise.resolve(); + // Propagate active change to children + visualElement.variantChildren?.forEach((child) => child.animationState?.setActive(type, isActive)); + state[type].isActive = isActive; + const animations = animateChanges(type); + for (const key in state) { + state[key].protectedKeys = {}; + } + return animations; + } + return { + animateChanges, + setActive, + setAnimateFunction, + getState: () => state, + reset: () => { + state = createState(); + isInitialRender = true; + }, + }; +} +function checkVariantsDidChange(prev, next) { + if (typeof next === "string") { + return next !== prev; + } + else if (Array.isArray(next)) { + return !shallowCompare(next, prev); + } + return false; +} +function createTypeState(isActive = false) { + return { + isActive, + protectedKeys: {}, + needsAnimating: {}, + prevResolvedValues: {}, + }; +} +function createState() { + return { + animate: createTypeState(true), + whileInView: createTypeState(), + whileHover: createTypeState(), + whileTap: createTypeState(), + whileDrag: createTypeState(), + whileFocus: createTypeState(), + exit: createTypeState(), + }; +} + +class Feature { + constructor(node) { + this.isMounted = false; + this.node = node; + } + update() { } +} + +class AnimationFeature extends Feature { + /** + * We dynamically generate the AnimationState manager as it contains a reference + * to the underlying animation library. We only want to load that if we load this, + * so people can optionally code split it out using the `m` component. + */ + constructor(node) { + super(node); + node.animationState || (node.animationState = createAnimationState(node)); + } + updateAnimationControlsSubscription() { + const { animate } = this.node.getProps(); + if (isAnimationControls(animate)) { + this.unmountControls = animate.subscribe(this.node); + } + } + /** + * Subscribe any provided AnimationControls to the component's VisualElement + */ + mount() { + this.updateAnimationControlsSubscription(); + } + update() { + const { animate } = this.node.getProps(); + const { animate: prevAnimate } = this.node.prevProps || {}; + if (animate !== prevAnimate) { + this.updateAnimationControlsSubscription(); + } + } + unmount() { + this.node.animationState.reset(); + this.unmountControls?.(); + } +} + +let id = 0; +class ExitAnimationFeature extends Feature { + constructor() { + super(...arguments); + this.id = id++; + } + update() { + if (!this.node.presenceContext) + return; + const { isPresent, onExitComplete } = this.node.presenceContext; + const { isPresent: prevIsPresent } = this.node.prevPresenceContext || {}; + if (!this.node.animationState || isPresent === prevIsPresent) { + return; + } + const exitAnimation = this.node.animationState.setActive("exit", !isPresent); + if (onExitComplete && !isPresent) { + exitAnimation.then(() => { + onExitComplete(this.id); + }); + } + } + mount() { + const { register, onExitComplete } = this.node.presenceContext || {}; + if (onExitComplete) { + onExitComplete(this.id); + } + if (register) { + this.unmount = register(this.id); + } + } + unmount() { } +} + +const animations = { + animation: { + Feature: AnimationFeature, + }, + exit: { + Feature: ExitAnimationFeature, + }, +}; + +function extractEventInfo(event) { + return { + point: { + x: event.pageX, + y: event.pageY, + }, + }; +} +const addPointerInfo = (handler) => { + return (event) => motionDom.isPrimaryPointer(event) && handler(event, extractEventInfo(event)); +}; + +function addPointerEvent(target, eventName, handler, options) { + return addDomEvent(target, eventName, addPointerInfo(handler), options); +} + +// Fixes https://github.com/motiondivision/motion/issues/2270 +const getContextWindow = ({ current }) => { + return current ? current.ownerDocument.defaultView : null; +}; + +const distance = (a, b) => Math.abs(a - b); +function distance2D(a, b) { + // Multi-dimensional + const xDelta = distance(a.x, b.x); + const yDelta = distance(a.y, b.y); + return Math.sqrt(xDelta ** 2 + yDelta ** 2); +} + +/** + * @internal + */ +class PanSession { + constructor(event, handlers, { transformPagePoint, contextWindow = window, dragSnapToOrigin = false, distanceThreshold = 3, } = {}) { + /** + * @internal + */ + this.startEvent = null; + /** + * @internal + */ + this.lastMoveEvent = null; + /** + * @internal + */ + this.lastMoveEventInfo = null; + /** + * @internal + */ + this.handlers = {}; + /** + * @internal + */ + this.contextWindow = window; + this.updatePoint = () => { + if (!(this.lastMoveEvent && this.lastMoveEventInfo)) + return; + const info = getPanInfo(this.lastMoveEventInfo, this.history); + const isPanStarted = this.startEvent !== null; + // Only start panning if the offset is larger than 3 pixels. If we make it + // any larger than this we'll want to reset the pointer history + // on the first update to avoid visual snapping to the cursor. + const isDistancePastThreshold = distance2D(info.offset, { x: 0, y: 0 }) >= this.distanceThreshold; + if (!isPanStarted && !isDistancePastThreshold) + return; + const { point } = info; + const { timestamp } = motionDom.frameData; + this.history.push({ ...point, timestamp }); + const { onStart, onMove } = this.handlers; + if (!isPanStarted) { + onStart && onStart(this.lastMoveEvent, info); + this.startEvent = this.lastMoveEvent; + } + onMove && onMove(this.lastMoveEvent, info); + }; + this.handlePointerMove = (event, info) => { + this.lastMoveEvent = event; + this.lastMoveEventInfo = transformPoint(info, this.transformPagePoint); + // Throttle mouse move event to once per frame + motionDom.frame.update(this.updatePoint, true); + }; + this.handlePointerUp = (event, info) => { + this.end(); + const { onEnd, onSessionEnd, resumeAnimation } = this.handlers; + if (this.dragSnapToOrigin) + resumeAnimation && resumeAnimation(); + if (!(this.lastMoveEvent && this.lastMoveEventInfo)) + return; + const panInfo = getPanInfo(event.type === "pointercancel" + ? this.lastMoveEventInfo + : transformPoint(info, this.transformPagePoint), this.history); + if (this.startEvent && onEnd) { + onEnd(event, panInfo); + } + onSessionEnd && onSessionEnd(event, panInfo); + }; + // If we have more than one touch, don't start detecting this gesture + if (!motionDom.isPrimaryPointer(event)) + return; + this.dragSnapToOrigin = dragSnapToOrigin; + this.handlers = handlers; + this.transformPagePoint = transformPagePoint; + this.distanceThreshold = distanceThreshold; + this.contextWindow = contextWindow || window; + const info = extractEventInfo(event); + const initialInfo = transformPoint(info, this.transformPagePoint); + const { point } = initialInfo; + const { timestamp } = motionDom.frameData; + this.history = [{ ...point, timestamp }]; + const { onSessionStart } = handlers; + onSessionStart && + onSessionStart(event, getPanInfo(initialInfo, this.history)); + this.removeListeners = motionUtils.pipe(addPointerEvent(this.contextWindow, "pointermove", this.handlePointerMove), addPointerEvent(this.contextWindow, "pointerup", this.handlePointerUp), addPointerEvent(this.contextWindow, "pointercancel", this.handlePointerUp)); + } + updateHandlers(handlers) { + this.handlers = handlers; + } + end() { + this.removeListeners && this.removeListeners(); + motionDom.cancelFrame(this.updatePoint); + } +} +function transformPoint(info, transformPagePoint) { + return transformPagePoint ? { point: transformPagePoint(info.point) } : info; +} +function subtractPoint(a, b) { + return { x: a.x - b.x, y: a.y - b.y }; +} +function getPanInfo({ point }, history) { + return { + point, + delta: subtractPoint(point, lastDevicePoint(history)), + offset: subtractPoint(point, startDevicePoint(history)), + velocity: getVelocity(history, 0.1), + }; +} +function startDevicePoint(history) { + return history[0]; +} +function lastDevicePoint(history) { + return history[history.length - 1]; +} +function getVelocity(history, timeDelta) { + if (history.length < 2) { + return { x: 0, y: 0 }; + } + let i = history.length - 1; + let timestampedPoint = null; + const lastPoint = lastDevicePoint(history); + while (i >= 0) { + timestampedPoint = history[i]; + if (lastPoint.timestamp - timestampedPoint.timestamp > + motionUtils.secondsToMilliseconds(timeDelta)) { + break; + } + i--; + } + if (!timestampedPoint) { + return { x: 0, y: 0 }; + } + const time = motionUtils.millisecondsToSeconds(lastPoint.timestamp - timestampedPoint.timestamp); + if (time === 0) { + return { x: 0, y: 0 }; + } + const currentVelocity = { + x: (lastPoint.x - timestampedPoint.x) / time, + y: (lastPoint.y - timestampedPoint.y) / time, + }; + if (currentVelocity.x === Infinity) { + currentVelocity.x = 0; + } + if (currentVelocity.y === Infinity) { + currentVelocity.y = 0; + } + return currentVelocity; +} + +/** + * Apply constraints to a point. These constraints are both physical along an + * axis, and an elastic factor that determines how much to constrain the point + * by if it does lie outside the defined parameters. + */ +function applyConstraints(point, { min, max }, elastic) { + if (min !== undefined && point < min) { + // If we have a min point defined, and this is outside of that, constrain + point = elastic + ? motionDom.mixNumber(min, point, elastic.min) + : Math.max(point, min); + } + else if (max !== undefined && point > max) { + // If we have a max point defined, and this is outside of that, constrain + point = elastic + ? motionDom.mixNumber(max, point, elastic.max) + : Math.min(point, max); + } + return point; +} +/** + * Calculate constraints in terms of the viewport when defined relatively to the + * measured axis. This is measured from the nearest edge, so a max constraint of 200 + * on an axis with a max value of 300 would return a constraint of 500 - axis length + */ +function calcRelativeAxisConstraints(axis, min, max) { + return { + min: min !== undefined ? axis.min + min : undefined, + max: max !== undefined + ? axis.max + max - (axis.max - axis.min) + : undefined, + }; +} +/** + * Calculate constraints in terms of the viewport when + * defined relatively to the measured bounding box. + */ +function calcRelativeConstraints(layoutBox, { top, left, bottom, right }) { + return { + x: calcRelativeAxisConstraints(layoutBox.x, left, right), + y: calcRelativeAxisConstraints(layoutBox.y, top, bottom), + }; +} +/** + * Calculate viewport constraints when defined as another viewport-relative axis + */ +function calcViewportAxisConstraints(layoutAxis, constraintsAxis) { + let min = constraintsAxis.min - layoutAxis.min; + let max = constraintsAxis.max - layoutAxis.max; + // If the constraints axis is actually smaller than the layout axis then we can + // flip the constraints + if (constraintsAxis.max - constraintsAxis.min < + layoutAxis.max - layoutAxis.min) { + [min, max] = [max, min]; + } + return { min, max }; +} +/** + * Calculate viewport constraints when defined as another viewport-relative box + */ +function calcViewportConstraints(layoutBox, constraintsBox) { + return { + x: calcViewportAxisConstraints(layoutBox.x, constraintsBox.x), + y: calcViewportAxisConstraints(layoutBox.y, constraintsBox.y), + }; +} +/** + * Calculate a transform origin relative to the source axis, between 0-1, that results + * in an asthetically pleasing scale/transform needed to project from source to target. + */ +function calcOrigin(source, target) { + let origin = 0.5; + const sourceLength = calcLength(source); + const targetLength = calcLength(target); + if (targetLength > sourceLength) { + origin = motionUtils.progress(target.min, target.max - sourceLength, source.min); + } + else if (sourceLength > targetLength) { + origin = motionUtils.progress(source.min, source.max - targetLength, target.min); + } + return motionUtils.clamp(0, 1, origin); +} +/** + * Rebase the calculated viewport constraints relative to the layout.min point. + */ +function rebaseAxisConstraints(layout, constraints) { + const relativeConstraints = {}; + if (constraints.min !== undefined) { + relativeConstraints.min = constraints.min - layout.min; + } + if (constraints.max !== undefined) { + relativeConstraints.max = constraints.max - layout.min; + } + return relativeConstraints; +} +const defaultElastic = 0.35; +/** + * Accepts a dragElastic prop and returns resolved elastic values for each axis. + */ +function resolveDragElastic(dragElastic = defaultElastic) { + if (dragElastic === false) { + dragElastic = 0; + } + else if (dragElastic === true) { + dragElastic = defaultElastic; + } + return { + x: resolveAxisElastic(dragElastic, "left", "right"), + y: resolveAxisElastic(dragElastic, "top", "bottom"), + }; +} +function resolveAxisElastic(dragElastic, minLabel, maxLabel) { + return { + min: resolvePointElastic(dragElastic, minLabel), + max: resolvePointElastic(dragElastic, maxLabel), + }; +} +function resolvePointElastic(dragElastic, label) { + return typeof dragElastic === "number" + ? dragElastic + : dragElastic[label] || 0; +} + +const elementDragControls = new WeakMap(); +class VisualElementDragControls { + constructor(visualElement) { + this.openDragLock = null; + this.isDragging = false; + this.currentDirection = null; + this.originPoint = { x: 0, y: 0 }; + /** + * The permitted boundaries of travel, in pixels. + */ + this.constraints = false; + this.hasMutatedConstraints = false; + /** + * The per-axis resolved elastic values. + */ + this.elastic = createBox(); + /** + * The latest pointer event. Used as fallback when the `cancel` and `stop` functions are called without arguments. + */ + this.latestPointerEvent = null; + /** + * The latest pan info. Used as fallback when the `cancel` and `stop` functions are called without arguments. + */ + this.latestPanInfo = null; + this.visualElement = visualElement; + } + start(originEvent, { snapToCursor = false, distanceThreshold } = {}) { + /** + * Don't start dragging if this component is exiting + */ + const { presenceContext } = this.visualElement; + if (presenceContext && presenceContext.isPresent === false) + return; + const onSessionStart = (event) => { + const { dragSnapToOrigin } = this.getProps(); + // Stop or pause any animations on both axis values immediately. This allows the user to throw and catch + // the component. + dragSnapToOrigin ? this.pauseAnimation() : this.stopAnimation(); + if (snapToCursor) { + this.snapToCursor(extractEventInfo(event).point); + } + }; + const onStart = (event, info) => { + // Attempt to grab the global drag gesture lock - maybe make this part of PanSession + const { drag, dragPropagation, onDragStart } = this.getProps(); + if (drag && !dragPropagation) { + if (this.openDragLock) + this.openDragLock(); + this.openDragLock = motionDom.setDragLock(drag); + // If we don 't have the lock, don't start dragging + if (!this.openDragLock) + return; + } + this.latestPointerEvent = event; + this.latestPanInfo = info; + this.isDragging = true; + this.currentDirection = null; + this.resolveConstraints(); + if (this.visualElement.projection) { + this.visualElement.projection.isAnimationBlocked = true; + this.visualElement.projection.target = undefined; + } + /** + * Record gesture origin + */ + eachAxis((axis) => { + let current = this.getAxisMotionValue(axis).get() || 0; + /** + * If the MotionValue is a percentage value convert to px + */ + if (motionDom.percent.test(current)) { + const { projection } = this.visualElement; + if (projection && projection.layout) { + const measuredAxis = projection.layout.layoutBox[axis]; + if (measuredAxis) { + const length = calcLength(measuredAxis); + current = length * (parseFloat(current) / 100); + } + } + } + this.originPoint[axis] = current; + }); + // Fire onDragStart event + if (onDragStart) { + motionDom.frame.postRender(() => onDragStart(event, info)); + } + addValueToWillChange(this.visualElement, "transform"); + const { animationState } = this.visualElement; + animationState && animationState.setActive("whileDrag", true); + }; + const onMove = (event, info) => { + this.latestPointerEvent = event; + this.latestPanInfo = info; + const { dragPropagation, dragDirectionLock, onDirectionLock, onDrag, } = this.getProps(); + // If we didn't successfully receive the gesture lock, early return. + if (!dragPropagation && !this.openDragLock) + return; + const { offset } = info; + // Attempt to detect drag direction if directionLock is true + if (dragDirectionLock && this.currentDirection === null) { + this.currentDirection = getCurrentDirection(offset); + // If we've successfully set a direction, notify listener + if (this.currentDirection !== null) { + onDirectionLock && onDirectionLock(this.currentDirection); + } + return; + } + // Update each point with the latest position + this.updateAxis("x", info.point, offset); + this.updateAxis("y", info.point, offset); + /** + * Ideally we would leave the renderer to fire naturally at the end of + * this frame but if the element is about to change layout as the result + * of a re-render we want to ensure the browser can read the latest + * bounding box to ensure the pointer and element don't fall out of sync. + */ + this.visualElement.render(); + /** + * This must fire after the render call as it might trigger a state + * change which itself might trigger a layout update. + */ + onDrag && onDrag(event, info); + }; + const onSessionEnd = (event, info) => { + this.latestPointerEvent = event; + this.latestPanInfo = info; + this.stop(event, info); + this.latestPointerEvent = null; + this.latestPanInfo = null; + }; + const resumeAnimation = () => eachAxis((axis) => this.getAnimationState(axis) === "paused" && + this.getAxisMotionValue(axis).animation?.play()); + const { dragSnapToOrigin } = this.getProps(); + this.panSession = new PanSession(originEvent, { + onSessionStart, + onStart, + onMove, + onSessionEnd, + resumeAnimation, + }, { + transformPagePoint: this.visualElement.getTransformPagePoint(), + dragSnapToOrigin, + distanceThreshold, + contextWindow: getContextWindow(this.visualElement), + }); + } + /** + * @internal + */ + stop(event, panInfo) { + const finalEvent = event || this.latestPointerEvent; + const finalPanInfo = panInfo || this.latestPanInfo; + const isDragging = this.isDragging; + this.cancel(); + if (!isDragging || !finalPanInfo || !finalEvent) + return; + const { velocity } = finalPanInfo; + this.startAnimation(velocity); + const { onDragEnd } = this.getProps(); + if (onDragEnd) { + motionDom.frame.postRender(() => onDragEnd(finalEvent, finalPanInfo)); + } + } + /** + * @internal + */ + cancel() { + this.isDragging = false; + const { projection, animationState } = this.visualElement; + if (projection) { + projection.isAnimationBlocked = false; + } + this.panSession && this.panSession.end(); + this.panSession = undefined; + const { dragPropagation } = this.getProps(); + if (!dragPropagation && this.openDragLock) { + this.openDragLock(); + this.openDragLock = null; + } + animationState && animationState.setActive("whileDrag", false); + } + updateAxis(axis, _point, offset) { + const { drag } = this.getProps(); + // If we're not dragging this axis, do an early return. + if (!offset || !shouldDrag(axis, drag, this.currentDirection)) + return; + const axisValue = this.getAxisMotionValue(axis); + let next = this.originPoint[axis] + offset[axis]; + // Apply constraints + if (this.constraints && this.constraints[axis]) { + next = applyConstraints(next, this.constraints[axis], this.elastic[axis]); + } + axisValue.set(next); + } + resolveConstraints() { + const { dragConstraints, dragElastic } = this.getProps(); + const layout = this.visualElement.projection && + !this.visualElement.projection.layout + ? this.visualElement.projection.measure(false) + : this.visualElement.projection?.layout; + const prevConstraints = this.constraints; + if (dragConstraints && isRefObject(dragConstraints)) { + if (!this.constraints) { + this.constraints = this.resolveRefConstraints(); + } + } + else { + if (dragConstraints && layout) { + this.constraints = calcRelativeConstraints(layout.layoutBox, dragConstraints); + } + else { + this.constraints = false; + } + } + this.elastic = resolveDragElastic(dragElastic); + /** + * If we're outputting to external MotionValues, we want to rebase the measured constraints + * from viewport-relative to component-relative. + */ + if (prevConstraints !== this.constraints && + layout && + this.constraints && + !this.hasMutatedConstraints) { + eachAxis((axis) => { + if (this.constraints !== false && + this.getAxisMotionValue(axis)) { + this.constraints[axis] = rebaseAxisConstraints(layout.layoutBox[axis], this.constraints[axis]); + } + }); + } + } + resolveRefConstraints() { + const { dragConstraints: constraints, onMeasureDragConstraints } = this.getProps(); + if (!constraints || !isRefObject(constraints)) + return false; + const constraintsElement = constraints.current; + motionUtils.invariant(constraintsElement !== null, "If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.", "drag-constraints-ref"); + const { projection } = this.visualElement; + // TODO + if (!projection || !projection.layout) + return false; + const constraintsBox = measurePageBox(constraintsElement, projection.root, this.visualElement.getTransformPagePoint()); + let measuredConstraints = calcViewportConstraints(projection.layout.layoutBox, constraintsBox); + /** + * If there's an onMeasureDragConstraints listener we call it and + * if different constraints are returned, set constraints to that + */ + if (onMeasureDragConstraints) { + const userConstraints = onMeasureDragConstraints(convertBoxToBoundingBox(measuredConstraints)); + this.hasMutatedConstraints = !!userConstraints; + if (userConstraints) { + measuredConstraints = convertBoundingBoxToBox(userConstraints); + } + } + return measuredConstraints; + } + startAnimation(velocity) { + const { drag, dragMomentum, dragElastic, dragTransition, dragSnapToOrigin, onDragTransitionEnd, } = this.getProps(); + const constraints = this.constraints || {}; + const momentumAnimations = eachAxis((axis) => { + if (!shouldDrag(axis, drag, this.currentDirection)) { + return; + } + let transition = (constraints && constraints[axis]) || {}; + if (dragSnapToOrigin) + transition = { min: 0, max: 0 }; + /** + * Overdamp the boundary spring if `dragElastic` is disabled. There's still a frame + * of spring animations so we should look into adding a disable spring option to `inertia`. + * We could do something here where we affect the `bounceStiffness` and `bounceDamping` + * using the value of `dragElastic`. + */ + const bounceStiffness = dragElastic ? 200 : 1000000; + const bounceDamping = dragElastic ? 40 : 10000000; + const inertia = { + type: "inertia", + velocity: dragMomentum ? velocity[axis] : 0, + bounceStiffness, + bounceDamping, + timeConstant: 750, + restDelta: 1, + restSpeed: 10, + ...dragTransition, + ...transition, + }; + // If we're not animating on an externally-provided `MotionValue` we can use the + // component's animation controls which will handle interactions with whileHover (etc), + // otherwise we just have to animate the `MotionValue` itself. + return this.startAxisValueAnimation(axis, inertia); + }); + // Run all animations and then resolve the new drag constraints. + return Promise.all(momentumAnimations).then(onDragTransitionEnd); + } + startAxisValueAnimation(axis, transition) { + const axisValue = this.getAxisMotionValue(axis); + addValueToWillChange(this.visualElement, axis); + return axisValue.start(animateMotionValue(axis, axisValue, 0, transition, this.visualElement, false)); + } + stopAnimation() { + eachAxis((axis) => this.getAxisMotionValue(axis).stop()); + } + pauseAnimation() { + eachAxis((axis) => this.getAxisMotionValue(axis).animation?.pause()); + } + getAnimationState(axis) { + return this.getAxisMotionValue(axis).animation?.state; + } + /** + * Drag works differently depending on which props are provided. + * + * - If _dragX and _dragY are provided, we output the gesture delta directly to those motion values. + * - Otherwise, we apply the delta to the x/y motion values. + */ + getAxisMotionValue(axis) { + const dragKey = `_drag${axis.toUpperCase()}`; + const props = this.visualElement.getProps(); + const externalMotionValue = props[dragKey]; + return externalMotionValue + ? externalMotionValue + : this.visualElement.getValue(axis, (props.initial + ? props.initial[axis] + : undefined) || 0); + } + snapToCursor(point) { + eachAxis((axis) => { + const { drag } = this.getProps(); + // If we're not dragging this axis, do an early return. + if (!shouldDrag(axis, drag, this.currentDirection)) + return; + const { projection } = this.visualElement; + const axisValue = this.getAxisMotionValue(axis); + if (projection && projection.layout) { + const { min, max } = projection.layout.layoutBox[axis]; + axisValue.set(point[axis] - motionDom.mixNumber(min, max, 0.5)); + } + }); + } + /** + * When the viewport resizes we want to check if the measured constraints + * have changed and, if so, reposition the element within those new constraints + * relative to where it was before the resize. + */ + scalePositionWithinConstraints() { + if (!this.visualElement.current) + return; + const { drag, dragConstraints } = this.getProps(); + const { projection } = this.visualElement; + if (!isRefObject(dragConstraints) || !projection || !this.constraints) + return; + /** + * Stop current animations as there can be visual glitching if we try to do + * this mid-animation + */ + this.stopAnimation(); + /** + * Record the relative position of the dragged element relative to the + * constraints box and save as a progress value. + */ + const boxProgress = { x: 0, y: 0 }; + eachAxis((axis) => { + const axisValue = this.getAxisMotionValue(axis); + if (axisValue && this.constraints !== false) { + const latest = axisValue.get(); + boxProgress[axis] = calcOrigin({ min: latest, max: latest }, this.constraints[axis]); + } + }); + /** + * Update the layout of this element and resolve the latest drag constraints + */ + const { transformTemplate } = this.visualElement.getProps(); + this.visualElement.current.style.transform = transformTemplate + ? transformTemplate({}, "") + : "none"; + projection.root && projection.root.updateScroll(); + projection.updateLayout(); + this.resolveConstraints(); + /** + * For each axis, calculate the current progress of the layout axis + * within the new constraints. + */ + eachAxis((axis) => { + if (!shouldDrag(axis, drag, null)) + return; + /** + * Calculate a new transform based on the previous box progress + */ + const axisValue = this.getAxisMotionValue(axis); + const { min, max } = this.constraints[axis]; + axisValue.set(motionDom.mixNumber(min, max, boxProgress[axis])); + }); + } + addListeners() { + if (!this.visualElement.current) + return; + elementDragControls.set(this.visualElement, this); + const element = this.visualElement.current; + /** + * Attach a pointerdown event listener on this DOM element to initiate drag tracking. + */ + const stopPointerListener = addPointerEvent(element, "pointerdown", (event) => { + const { drag, dragListener = true } = this.getProps(); + drag && dragListener && this.start(event); + }); + const measureDragConstraints = () => { + const { dragConstraints } = this.getProps(); + if (isRefObject(dragConstraints) && dragConstraints.current) { + this.constraints = this.resolveRefConstraints(); + } + }; + const { projection } = this.visualElement; + const stopMeasureLayoutListener = projection.addEventListener("measure", measureDragConstraints); + if (projection && !projection.layout) { + projection.root && projection.root.updateScroll(); + projection.updateLayout(); + } + motionDom.frame.read(measureDragConstraints); + /** + * Attach a window resize listener to scale the draggable target within its defined + * constraints as the window resizes. + */ + const stopResizeListener = addDomEvent(window, "resize", () => this.scalePositionWithinConstraints()); + /** + * If the element's layout changes, calculate the delta and apply that to + * the drag gesture's origin point. + */ + const stopLayoutUpdateListener = projection.addEventListener("didUpdate", (({ delta, hasLayoutChanged }) => { + if (this.isDragging && hasLayoutChanged) { + eachAxis((axis) => { + const motionValue = this.getAxisMotionValue(axis); + if (!motionValue) + return; + this.originPoint[axis] += delta[axis].translate; + motionValue.set(motionValue.get() + delta[axis].translate); + }); + this.visualElement.render(); + } + })); + return () => { + stopResizeListener(); + stopPointerListener(); + stopMeasureLayoutListener(); + stopLayoutUpdateListener && stopLayoutUpdateListener(); + }; + } + getProps() { + const props = this.visualElement.getProps(); + const { drag = false, dragDirectionLock = false, dragPropagation = false, dragConstraints = false, dragElastic = defaultElastic, dragMomentum = true, } = props; + return { + ...props, + drag, + dragDirectionLock, + dragPropagation, + dragConstraints, + dragElastic, + dragMomentum, + }; + } +} +function shouldDrag(direction, drag, currentDirection) { + return ((drag === true || drag === direction) && + (currentDirection === null || currentDirection === direction)); +} +/** + * Based on an x/y offset determine the current drag direction. If both axis' offsets are lower + * than the provided threshold, return `null`. + * + * @param offset - The x/y offset from origin. + * @param lockThreshold - (Optional) - the minimum absolute offset before we can determine a drag direction. + */ +function getCurrentDirection(offset, lockThreshold = 10) { + let direction = null; + if (Math.abs(offset.y) > lockThreshold) { + direction = "y"; + } + else if (Math.abs(offset.x) > lockThreshold) { + direction = "x"; + } + return direction; +} + +class DragGesture extends Feature { + constructor(node) { + super(node); + this.removeGroupControls = motionUtils.noop; + this.removeListeners = motionUtils.noop; + this.controls = new VisualElementDragControls(node); + } + mount() { + // If we've been provided a DragControls for manual control over the drag gesture, + // subscribe this component to it on mount. + const { dragControls } = this.node.getProps(); + if (dragControls) { + this.removeGroupControls = dragControls.subscribe(this.controls); + } + this.removeListeners = this.controls.addListeners() || motionUtils.noop; + } + unmount() { + this.removeGroupControls(); + this.removeListeners(); + } +} + +const asyncHandler = (handler) => (event, info) => { + if (handler) { + motionDom.frame.postRender(() => handler(event, info)); + } +}; +class PanGesture extends Feature { + constructor() { + super(...arguments); + this.removePointerDownListener = motionUtils.noop; + } + onPointerDown(pointerDownEvent) { + this.session = new PanSession(pointerDownEvent, this.createPanHandlers(), { + transformPagePoint: this.node.getTransformPagePoint(), + contextWindow: getContextWindow(this.node), + }); + } + createPanHandlers() { + const { onPanSessionStart, onPanStart, onPan, onPanEnd } = this.node.getProps(); + return { + onSessionStart: asyncHandler(onPanSessionStart), + onStart: asyncHandler(onPanStart), + onMove: onPan, + onEnd: (event, info) => { + delete this.session; + if (onPanEnd) { + motionDom.frame.postRender(() => onPanEnd(event, info)); + } + }, + }; + } + mount() { + this.removePointerDownListener = addPointerEvent(this.node.current, "pointerdown", (event) => this.onPointerDown(event)); + } + update() { + this.session && this.session.updateHandlers(this.createPanHandlers()); + } + unmount() { + this.removePointerDownListener(); + this.session && this.session.end(); + } +} + +/** + * Track whether we've taken any snapshots yet. If not, + * we can safely skip notification of didUpdate. + * + * Difficult to capture in a test but to prevent flickering + * we must set this to true either on update or unmount. + * Running `next-env/layout-id` in Safari will show this behaviour if broken. + */ +let hasTakenAnySnapshot = false; +class MeasureLayoutWithContext extends React.Component { + /** + * This only mounts projection nodes for components that + * need measuring, we might want to do it for all components + * in order to incorporate transforms + */ + componentDidMount() { + const { visualElement, layoutGroup, switchLayoutGroup, layoutId } = this.props; + const { projection } = visualElement; + addScaleCorrector(defaultScaleCorrectors); + if (projection) { + if (layoutGroup.group) + layoutGroup.group.add(projection); + if (switchLayoutGroup && switchLayoutGroup.register && layoutId) { + switchLayoutGroup.register(projection); + } + if (hasTakenAnySnapshot) { + projection.root.didUpdate(); + } + projection.addEventListener("animationComplete", () => { + this.safeToRemove(); + }); + projection.setOptions({ + ...projection.options, + onExitComplete: () => this.safeToRemove(), + }); + } + globalProjectionState.hasEverUpdated = true; + } + getSnapshotBeforeUpdate(prevProps) { + const { layoutDependency, visualElement, drag, isPresent } = this.props; + const { projection } = visualElement; + if (!projection) + return null; + /** + * TODO: We use this data in relegate to determine whether to + * promote a previous element. There's no guarantee its presence data + * will have updated by this point - if a bug like this arises it will + * have to be that we markForRelegation and then find a new lead some other way, + * perhaps in didUpdate + */ + projection.isPresent = isPresent; + hasTakenAnySnapshot = true; + if (drag || + prevProps.layoutDependency !== layoutDependency || + layoutDependency === undefined || + prevProps.isPresent !== isPresent) { + projection.willUpdate(); + } + else { + this.safeToRemove(); + } + if (prevProps.isPresent !== isPresent) { + if (isPresent) { + projection.promote(); + } + else if (!projection.relegate()) { + /** + * If there's another stack member taking over from this one, + * it's in charge of the exit animation and therefore should + * be in charge of the safe to remove. Otherwise we call it here. + */ + motionDom.frame.postRender(() => { + const stack = projection.getStack(); + if (!stack || !stack.members.length) { + this.safeToRemove(); + } + }); + } + } + return null; + } + componentDidUpdate() { + const { projection } = this.props.visualElement; + if (projection) { + projection.root.didUpdate(); + motionDom.microtask.postRender(() => { + if (!projection.currentAnimation && projection.isLead()) { + this.safeToRemove(); + } + }); + } + } + componentWillUnmount() { + const { visualElement, layoutGroup, switchLayoutGroup: promoteContext, } = this.props; + const { projection } = visualElement; + hasTakenAnySnapshot = true; + if (projection) { + projection.scheduleCheckAfterUnmount(); + if (layoutGroup && layoutGroup.group) + layoutGroup.group.remove(projection); + if (promoteContext && promoteContext.deregister) + promoteContext.deregister(projection); + } + } + safeToRemove() { + const { safeToRemove } = this.props; + safeToRemove && safeToRemove(); + } + render() { + return null; + } +} +function MeasureLayout(props) { + const [isPresent, safeToRemove] = usePresence(); + const layoutGroup = React.useContext(LayoutGroupContext); + return (jsxRuntime.jsx(MeasureLayoutWithContext, { ...props, layoutGroup: layoutGroup, switchLayoutGroup: React.useContext(SwitchLayoutGroupContext), isPresent: isPresent, safeToRemove: safeToRemove })); +} +const defaultScaleCorrectors = { + borderRadius: { + ...correctBorderRadius, + applyTo: [ + "borderTopLeftRadius", + "borderTopRightRadius", + "borderBottomLeftRadius", + "borderBottomRightRadius", + ], + }, + borderTopLeftRadius: correctBorderRadius, + borderTopRightRadius: correctBorderRadius, + borderBottomLeftRadius: correctBorderRadius, + borderBottomRightRadius: correctBorderRadius, + boxShadow: correctBoxShadow, +}; + +const drag = { + pan: { + Feature: PanGesture, + }, + drag: { + Feature: DragGesture, + ProjectionNode: HTMLProjectionNode, + MeasureLayout, + }, +}; + +function handleHoverEvent(node, event, lifecycle) { + const { props } = node; + if (node.animationState && props.whileHover) { + node.animationState.setActive("whileHover", lifecycle === "Start"); + } + const eventName = ("onHover" + lifecycle); + const callback = props[eventName]; + if (callback) { + motionDom.frame.postRender(() => callback(event, extractEventInfo(event))); + } +} +class HoverGesture extends Feature { + mount() { + const { current } = this.node; + if (!current) + return; + this.unmount = motionDom.hover(current, (_element, startEvent) => { + handleHoverEvent(this.node, startEvent, "Start"); + return (endEvent) => handleHoverEvent(this.node, endEvent, "End"); + }); + } + unmount() { } +} + +class FocusGesture extends Feature { + constructor() { + super(...arguments); + this.isActive = false; + } + onFocus() { + let isFocusVisible = false; + /** + * If this element doesn't match focus-visible then don't + * apply whileHover. But, if matches throws that focus-visible + * is not a valid selector then in that browser outline styles will be applied + * to the element by default and we want to match that behaviour with whileFocus. + */ + try { + isFocusVisible = this.node.current.matches(":focus-visible"); + } + catch (e) { + isFocusVisible = true; + } + if (!isFocusVisible || !this.node.animationState) + return; + this.node.animationState.setActive("whileFocus", true); + this.isActive = true; + } + onBlur() { + if (!this.isActive || !this.node.animationState) + return; + this.node.animationState.setActive("whileFocus", false); + this.isActive = false; + } + mount() { + this.unmount = motionUtils.pipe(addDomEvent(this.node.current, "focus", () => this.onFocus()), addDomEvent(this.node.current, "blur", () => this.onBlur())); + } + unmount() { } +} + +function handlePressEvent(node, event, lifecycle) { + const { props } = node; + if (node.current instanceof HTMLButtonElement && node.current.disabled) { + return; + } + if (node.animationState && props.whileTap) { + node.animationState.setActive("whileTap", lifecycle === "Start"); + } + const eventName = ("onTap" + (lifecycle === "End" ? "" : lifecycle)); + const callback = props[eventName]; + if (callback) { + motionDom.frame.postRender(() => callback(event, extractEventInfo(event))); + } +} +class PressGesture extends Feature { + mount() { + const { current } = this.node; + if (!current) + return; + this.unmount = motionDom.press(current, (_element, startEvent) => { + handlePressEvent(this.node, startEvent, "Start"); + return (endEvent, { success }) => handlePressEvent(this.node, endEvent, success ? "End" : "Cancel"); + }, { useGlobalTarget: this.node.props.globalTapTarget }); + } + unmount() { } +} + +/** + * Map an IntersectionHandler callback to an element. We only ever make one handler for one + * element, so even though these handlers might all be triggered by different + * observers, we can keep them in the same map. + */ +const observerCallbacks = new WeakMap(); +/** + * Multiple observers can be created for multiple element/document roots. Each with + * different settings. So here we store dictionaries of observers to each root, + * using serialised settings (threshold/margin) as lookup keys. + */ +const observers = new WeakMap(); +const fireObserverCallback = (entry) => { + const callback = observerCallbacks.get(entry.target); + callback && callback(entry); +}; +const fireAllObserverCallbacks = (entries) => { + entries.forEach(fireObserverCallback); +}; +function initIntersectionObserver({ root, ...options }) { + const lookupRoot = root || document; + /** + * If we don't have an observer lookup map for this root, create one. + */ + if (!observers.has(lookupRoot)) { + observers.set(lookupRoot, {}); + } + const rootObservers = observers.get(lookupRoot); + const key = JSON.stringify(options); + /** + * If we don't have an observer for this combination of root and settings, + * create one. + */ + if (!rootObservers[key]) { + rootObservers[key] = new IntersectionObserver(fireAllObserverCallbacks, { root, ...options }); + } + return rootObservers[key]; +} +function observeIntersection(element, options, callback) { + const rootInteresectionObserver = initIntersectionObserver(options); + observerCallbacks.set(element, callback); + rootInteresectionObserver.observe(element); + return () => { + observerCallbacks.delete(element); + rootInteresectionObserver.unobserve(element); + }; +} + +const thresholdNames = { + some: 0, + all: 1, +}; +class InViewFeature extends Feature { + constructor() { + super(...arguments); + this.hasEnteredView = false; + this.isInView = false; + } + startObserver() { + this.unmount(); + const { viewport = {} } = this.node.getProps(); + const { root, margin: rootMargin, amount = "some", once } = viewport; + const options = { + root: root ? root.current : undefined, + rootMargin, + threshold: typeof amount === "number" ? amount : thresholdNames[amount], + }; + const onIntersectionUpdate = (entry) => { + const { isIntersecting } = entry; + /** + * If there's been no change in the viewport state, early return. + */ + if (this.isInView === isIntersecting) + return; + this.isInView = isIntersecting; + /** + * Handle hasEnteredView. If this is only meant to run once, and + * element isn't visible, early return. Otherwise set hasEnteredView to true. + */ + if (once && !isIntersecting && this.hasEnteredView) { + return; + } + else if (isIntersecting) { + this.hasEnteredView = true; + } + if (this.node.animationState) { + this.node.animationState.setActive("whileInView", isIntersecting); + } + /** + * Use the latest committed props rather than the ones in scope + * when this observer is created + */ + const { onViewportEnter, onViewportLeave } = this.node.getProps(); + const callback = isIntersecting ? onViewportEnter : onViewportLeave; + callback && callback(entry); + }; + return observeIntersection(this.node.current, options, onIntersectionUpdate); + } + mount() { + this.startObserver(); + } + update() { + if (typeof IntersectionObserver === "undefined") + return; + const { props, prevProps } = this.node; + const hasOptionsChanged = ["amount", "margin", "root"].some(hasViewportOptionChanged(props, prevProps)); + if (hasOptionsChanged) { + this.startObserver(); + } + } + unmount() { } +} +function hasViewportOptionChanged({ viewport = {} }, { viewport: prevViewport = {} } = {}) { + return (name) => viewport[name] !== prevViewport[name]; +} + +const gestureAnimations = { + inView: { + Feature: InViewFeature, + }, + tap: { + Feature: PressGesture, + }, + focus: { + Feature: FocusGesture, + }, + hover: { + Feature: HoverGesture, + }, +}; + +const layout = { + layout: { + ProjectionNode: HTMLProjectionNode, + MeasureLayout, + }, +}; + +const featureBundle = { + ...animations, + ...gestureAnimations, + ...drag, + ...layout, +}; + +exports.FlatTree = FlatTree; +exports.HTMLVisualElement = HTMLVisualElement; +exports.LayoutGroupContext = LayoutGroupContext; +exports.LazyContext = LazyContext; +exports.MotionConfigContext = MotionConfigContext; +exports.MotionContext = MotionContext; +exports.PresenceContext = PresenceContext; +exports.SVGVisualElement = SVGVisualElement; +exports.SwitchLayoutGroupContext = SwitchLayoutGroupContext; +exports.VisualElement = VisualElement; +exports.addDomEvent = addDomEvent; +exports.addPointerEvent = addPointerEvent; +exports.addPointerInfo = addPointerInfo; +exports.addScaleCorrector = addScaleCorrector; +exports.animateSingleValue = animateSingleValue; +exports.animateTarget = animateTarget; +exports.animateVisualElement = animateVisualElement; +exports.animations = animations; +exports.buildTransform = buildTransform; +exports.calcLength = calcLength; +exports.createBox = createBox; +exports.createDomVisualElement = createDomVisualElement; +exports.createMotionComponent = createMotionComponent; +exports.delay = delay; +exports.distance = distance; +exports.distance2D = distance2D; +exports.drag = drag; +exports.featureBundle = featureBundle; +exports.filterProps = filterProps; +exports.gestureAnimations = gestureAnimations; +exports.getOptimisedAppearId = getOptimisedAppearId; +exports.hasReducedMotionListener = hasReducedMotionListener; +exports.initPrefersReducedMotion = initPrefersReducedMotion; +exports.isBrowser = isBrowser; +exports.isValidMotionProp = isValidMotionProp; +exports.layout = layout; +exports.loadExternalIsValidProp = loadExternalIsValidProp; +exports.loadFeatures = loadFeatures; +exports.makeUseVisualState = makeUseVisualState; +exports.motionComponentSymbol = motionComponentSymbol; +exports.optimizedAppearDataAttribute = optimizedAppearDataAttribute; +exports.optimizedAppearDataId = optimizedAppearDataId; +exports.prefersReducedMotion = prefersReducedMotion; +exports.resolveMotionValue = resolveMotionValue; +exports.rootProjectionNode = rootProjectionNode; +exports.setTarget = setTarget; +exports.useConstant = useConstant; +exports.useIsPresent = useIsPresent; +exports.useIsomorphicLayoutEffect = useIsomorphicLayoutEffect; +exports.usePresence = usePresence; +exports.visualElementStore = visualElementStore; diff --git a/frontend/node_modules/framer-motion/dist/cjs/index.js b/frontend/node_modules/framer-motion/dist/cjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..88ba9e1062afe80cb5e22f62bd2185164d62215a --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/cjs/index.js @@ -0,0 +1,2963 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var jsxRuntime = require('react/jsx-runtime'); +var React = require('react'); +var featureBundle = require('./feature-bundle-PNQ-8QDo.js'); +var motionDom = require('motion-dom'); +var motionUtils = require('motion-utils'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React); + +/** + * Measurement functionality has to be within a separate component + * to leverage snapshot lifecycle. + */ +class PopChildMeasure extends React__namespace.Component { + getSnapshotBeforeUpdate(prevProps) { + const element = this.props.childRef.current; + if (element && prevProps.isPresent && !this.props.isPresent) { + const parent = element.offsetParent; + const parentWidth = motionDom.isHTMLElement(parent) + ? parent.offsetWidth || 0 + : 0; + const size = this.props.sizeRef.current; + size.height = element.offsetHeight || 0; + size.width = element.offsetWidth || 0; + size.top = element.offsetTop; + size.left = element.offsetLeft; + size.right = parentWidth - size.width - size.left; + } + return null; + } + /** + * Required with getSnapshotBeforeUpdate to stop React complaining. + */ + componentDidUpdate() { } + render() { + return this.props.children; + } +} +function PopChild({ children, isPresent, anchorX, root }) { + const id = React.useId(); + const ref = React.useRef(null); + const size = React.useRef({ + width: 0, + height: 0, + top: 0, + left: 0, + right: 0, + }); + const { nonce } = React.useContext(featureBundle.MotionConfigContext); + /** + * We create and inject a style block so we can apply this explicit + * sizing in a non-destructive manner by just deleting the style block. + * + * We can't apply size via render as the measurement happens + * in getSnapshotBeforeUpdate (post-render), likewise if we apply the + * styles directly on the DOM node, we might be overwriting + * styles set via the style prop. + */ + React.useInsertionEffect(() => { + const { width, height, top, left, right } = size.current; + if (isPresent || !ref.current || !width || !height) + return; + const x = anchorX === "left" ? `left: ${left}` : `right: ${right}`; + ref.current.dataset.motionPopId = id; + const style = document.createElement("style"); + if (nonce) + style.nonce = nonce; + const parent = root ?? document.head; + parent.appendChild(style); + if (style.sheet) { + style.sheet.insertRule(` + [data-motion-pop-id="${id}"] { + position: absolute !important; + width: ${width}px !important; + height: ${height}px !important; + ${x}px !important; + top: ${top}px !important; + } + `); + } + return () => { + if (parent.contains(style)) { + parent.removeChild(style); + } + }; + }, [isPresent]); + return (jsxRuntime.jsx(PopChildMeasure, { isPresent: isPresent, childRef: ref, sizeRef: size, children: React__namespace.cloneElement(children, { ref }) })); +} + +const PresenceChild = ({ children, initial, isPresent, onExitComplete, custom, presenceAffectsLayout, mode, anchorX, root }) => { + const presenceChildren = featureBundle.useConstant(newChildrenMap); + const id = React.useId(); + let isReusedContext = true; + let context = React.useMemo(() => { + isReusedContext = false; + return { + id, + initial, + isPresent, + custom, + onExitComplete: (childId) => { + presenceChildren.set(childId, true); + for (const isComplete of presenceChildren.values()) { + if (!isComplete) + return; // can stop searching when any is incomplete + } + onExitComplete && onExitComplete(); + }, + register: (childId) => { + presenceChildren.set(childId, false); + return () => presenceChildren.delete(childId); + }, + }; + }, [isPresent, presenceChildren, onExitComplete]); + /** + * If the presence of a child affects the layout of the components around it, + * we want to make a new context value to ensure they get re-rendered + * so they can detect that layout change. + */ + if (presenceAffectsLayout && isReusedContext) { + context = { ...context }; + } + React.useMemo(() => { + presenceChildren.forEach((_, key) => presenceChildren.set(key, false)); + }, [isPresent]); + /** + * If there's no `motion` components to fire exit animations, we want to remove this + * component immediately. + */ + React__namespace.useEffect(() => { + !isPresent && + !presenceChildren.size && + onExitComplete && + onExitComplete(); + }, [isPresent]); + if (mode === "popLayout") { + children = (jsxRuntime.jsx(PopChild, { isPresent: isPresent, anchorX: anchorX, root: root, children: children })); + } + return (jsxRuntime.jsx(featureBundle.PresenceContext.Provider, { value: context, children: children })); +}; +function newChildrenMap() { + return new Map(); +} + +const getChildKey = (child) => child.key || ""; +function onlyElements(children) { + const filtered = []; + // We use forEach here instead of map as map mutates the component key by preprending `.$` + React.Children.forEach(children, (child) => { + if (React.isValidElement(child)) + filtered.push(child); + }); + return filtered; +} + +/** + * `AnimatePresence` enables the animation of components that have been removed from the tree. + * + * When adding/removing more than a single child, every child **must** be given a unique `key` prop. + * + * Any `motion` components that have an `exit` property defined will animate out when removed from + * the tree. + * + * ```jsx + * import { motion, AnimatePresence } from 'framer-motion' + * + * export const Items = ({ items }) => ( + * + * {items.map(item => ( + * + * ))} + * + * ) + * ``` + * + * You can sequence exit animations throughout a tree using variants. + * + * If a child contains multiple `motion` components with `exit` props, it will only unmount the child + * once all `motion` components have finished animating out. Likewise, any components using + * `usePresence` all need to call `safeToRemove`. + * + * @public + */ +const AnimatePresence = ({ children, custom, initial = true, onExitComplete, presenceAffectsLayout = true, mode = "sync", propagate = false, anchorX = "left", root }) => { + const [isParentPresent, safeToRemove] = featureBundle.usePresence(propagate); + /** + * Filter any children that aren't ReactElements. We can only track components + * between renders with a props.key. + */ + const presentChildren = React.useMemo(() => onlyElements(children), [children]); + /** + * Track the keys of the currently rendered children. This is used to + * determine which children are exiting. + */ + const presentKeys = propagate && !isParentPresent ? [] : presentChildren.map(getChildKey); + /** + * If `initial={false}` we only want to pass this to components in the first render. + */ + const isInitialRender = React.useRef(true); + /** + * A ref containing the currently present children. When all exit animations + * are complete, we use this to re-render the component with the latest children + * *committed* rather than the latest children *rendered*. + */ + const pendingPresentChildren = React.useRef(presentChildren); + /** + * Track which exiting children have finished animating out. + */ + const exitComplete = featureBundle.useConstant(() => new Map()); + /** + * Save children to render as React state. To ensure this component is concurrent-safe, + * we check for exiting children via an effect. + */ + const [diffedChildren, setDiffedChildren] = React.useState(presentChildren); + const [renderedChildren, setRenderedChildren] = React.useState(presentChildren); + featureBundle.useIsomorphicLayoutEffect(() => { + isInitialRender.current = false; + pendingPresentChildren.current = presentChildren; + /** + * Update complete status of exiting children. + */ + for (let i = 0; i < renderedChildren.length; i++) { + const key = getChildKey(renderedChildren[i]); + if (!presentKeys.includes(key)) { + if (exitComplete.get(key) !== true) { + exitComplete.set(key, false); + } + } + else { + exitComplete.delete(key); + } + } + }, [renderedChildren, presentKeys.length, presentKeys.join("-")]); + const exitingChildren = []; + if (presentChildren !== diffedChildren) { + let nextChildren = [...presentChildren]; + /** + * Loop through all the currently rendered components and decide which + * are exiting. + */ + for (let i = 0; i < renderedChildren.length; i++) { + const child = renderedChildren[i]; + const key = getChildKey(child); + if (!presentKeys.includes(key)) { + nextChildren.splice(i, 0, child); + exitingChildren.push(child); + } + } + /** + * If we're in "wait" mode, and we have exiting children, we want to + * only render these until they've all exited. + */ + if (mode === "wait" && exitingChildren.length) { + nextChildren = exitingChildren; + } + setRenderedChildren(onlyElements(nextChildren)); + setDiffedChildren(presentChildren); + /** + * Early return to ensure once we've set state with the latest diffed + * children, we can immediately re-render. + */ + return null; + } + if (process.env.NODE_ENV !== "production" && + mode === "wait" && + renderedChildren.length > 1) { + console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`); + } + /** + * If we've been provided a forceRender function by the LayoutGroupContext, + * we can use it to force a re-render amongst all surrounding components once + * all components have finished animating out. + */ + const { forceRender } = React.useContext(featureBundle.LayoutGroupContext); + return (jsxRuntime.jsx(jsxRuntime.Fragment, { children: renderedChildren.map((child) => { + const key = getChildKey(child); + const isPresent = propagate && !isParentPresent + ? false + : presentChildren === renderedChildren || + presentKeys.includes(key); + const onExit = () => { + if (exitComplete.has(key)) { + exitComplete.set(key, true); + } + else { + return; + } + let isEveryExitComplete = true; + exitComplete.forEach((isExitComplete) => { + if (!isExitComplete) + isEveryExitComplete = false; + }); + if (isEveryExitComplete) { + forceRender?.(); + setRenderedChildren(pendingPresentChildren.current); + propagate && safeToRemove?.(); + onExitComplete && onExitComplete(); + } + }; + return (jsxRuntime.jsx(PresenceChild, { isPresent: isPresent, initial: !isInitialRender.current || initial + ? undefined + : false, custom: custom, presenceAffectsLayout: presenceAffectsLayout, mode: mode, root: root, onExitComplete: isPresent ? undefined : onExit, anchorX: anchorX, children: child }, key)); + }) })); +}; + +/** + * Note: Still used by components generated by old versions of Framer + * + * @deprecated + */ +const DeprecatedLayoutGroupContext = React.createContext(null); + +const notify = (node) => !node.isLayoutDirty && node.willUpdate(false); +function nodeGroup() { + const nodes = new Set(); + const subscriptions = new WeakMap(); + const dirtyAll = () => nodes.forEach(notify); + return { + add: (node) => { + nodes.add(node); + subscriptions.set(node, node.addEventListener("willUpdate", dirtyAll)); + }, + remove: (node) => { + nodes.delete(node); + const unsubscribe = subscriptions.get(node); + if (unsubscribe) { + unsubscribe(); + subscriptions.delete(node); + } + dirtyAll(); + }, + dirty: dirtyAll, + }; +} + +function useIsMounted() { + const isMounted = React.useRef(false); + featureBundle.useIsomorphicLayoutEffect(() => { + isMounted.current = true; + return () => { + isMounted.current = false; + }; + }, []); + return isMounted; +} + +function useForceUpdate() { + const isMounted = useIsMounted(); + const [forcedRenderCount, setForcedRenderCount] = React.useState(0); + const forceRender = React.useCallback(() => { + isMounted.current && setForcedRenderCount(forcedRenderCount + 1); + }, [forcedRenderCount]); + /** + * Defer this to the end of the next animation frame in case there are multiple + * synchronous calls. + */ + const deferredForceRender = React.useCallback(() => motionDom.frame.postRender(forceRender), [forceRender]); + return [deferredForceRender, forcedRenderCount]; +} + +const shouldInheritGroup = (inherit) => inherit === true; +const shouldInheritId = (inherit) => shouldInheritGroup(inherit === true) || inherit === "id"; +const LayoutGroup = ({ children, id, inherit = true }) => { + const layoutGroupContext = React.useContext(featureBundle.LayoutGroupContext); + const deprecatedLayoutGroupContext = React.useContext(DeprecatedLayoutGroupContext); + const [forceRender, key] = useForceUpdate(); + const context = React.useRef(null); + const upstreamId = layoutGroupContext.id || deprecatedLayoutGroupContext; + if (context.current === null) { + if (shouldInheritId(inherit) && upstreamId) { + id = id ? upstreamId + "-" + id : upstreamId; + } + context.current = { + id, + group: shouldInheritGroup(inherit) + ? layoutGroupContext.group || nodeGroup() + : nodeGroup(), + }; + } + const memoizedContext = React.useMemo(() => ({ ...context.current, forceRender }), [key]); + return (jsxRuntime.jsx(featureBundle.LayoutGroupContext.Provider, { value: memoizedContext, children: children })); +}; + +/** + * Used in conjunction with the `m` component to reduce bundle size. + * + * `m` is a version of the `motion` component that only loads functionality + * critical for the initial render. + * + * `LazyMotion` can then be used to either synchronously or asynchronously + * load animation and gesture support. + * + * ```jsx + * // Synchronous loading + * import { LazyMotion, m, domAnimation } from "framer-motion" + * + * function App() { + * return ( + * + * + * + * ) + * } + * + * // Asynchronous loading + * import { LazyMotion, m } from "framer-motion" + * + * function App() { + * return ( + * import('./path/to/domAnimation')}> + * + * + * ) + * } + * ``` + * + * @public + */ +function LazyMotion({ children, features, strict = false }) { + const [, setIsLoaded] = React.useState(!isLazyBundle(features)); + const loadedRenderer = React.useRef(undefined); + /** + * If this is a synchronous load, load features immediately + */ + if (!isLazyBundle(features)) { + const { renderer, ...loadedFeatures } = features; + loadedRenderer.current = renderer; + featureBundle.loadFeatures(loadedFeatures); + } + React.useEffect(() => { + if (isLazyBundle(features)) { + features().then(({ renderer, ...loadedFeatures }) => { + featureBundle.loadFeatures(loadedFeatures); + loadedRenderer.current = renderer; + setIsLoaded(true); + }); + } + }, []); + return (jsxRuntime.jsx(featureBundle.LazyContext.Provider, { value: { renderer: loadedRenderer.current, strict }, children: children })); +} +function isLazyBundle(features) { + return typeof features === "function"; +} + +/** + * `MotionConfig` is used to set configuration options for all children `motion` components. + * + * ```jsx + * import { motion, MotionConfig } from "framer-motion" + * + * export function App() { + * return ( + * + * + * + * ) + * } + * ``` + * + * @public + */ +function MotionConfig({ children, isValidProp, ...config }) { + isValidProp && featureBundle.loadExternalIsValidProp(isValidProp); + /** + * Inherit props from any parent MotionConfig components + */ + config = { ...React.useContext(featureBundle.MotionConfigContext), ...config }; + /** + * Don't allow isStatic to change between renders as it affects how many hooks + * motion components fire. + */ + config.isStatic = featureBundle.useConstant(() => config.isStatic); + /** + * Creating a new config context object will re-render every `motion` component + * every time it renders. So we only want to create a new one sparingly. + */ + const context = React.useMemo(() => config, [ + JSON.stringify(config.transition), + config.transformPagePoint, + config.reducedMotion, + ]); + return (jsxRuntime.jsx(featureBundle.MotionConfigContext.Provider, { value: context, children: children })); +} + +const ReorderContext = React.createContext(null); + +function createMotionProxy(preloadedFeatures, createVisualElement) { + if (typeof Proxy === "undefined") { + return featureBundle.createMotionComponent; + } + /** + * A cache of generated `motion` components, e.g `motion.div`, `motion.input` etc. + * Rather than generating them anew every render. + */ + const componentCache = new Map(); + const factory = (Component, options) => { + return featureBundle.createMotionComponent(Component, options, preloadedFeatures, createVisualElement); + }; + /** + * Support for deprecated`motion(Component)` pattern + */ + const deprecatedFactoryFunction = (Component, options) => { + if (process.env.NODE_ENV !== "production") { + motionUtils.warnOnce(false, "motion() is deprecated. Use motion.create() instead."); + } + return factory(Component, options); + }; + return new Proxy(deprecatedFactoryFunction, { + /** + * Called when `motion` is referenced with a prop: `motion.div`, `motion.input` etc. + * The prop name is passed through as `key` and we can use that to generate a `motion` + * DOM component with that name. + */ + get: (_target, key) => { + if (key === "create") + return factory; + /** + * If this element doesn't exist in the component cache, create it and cache. + */ + if (!componentCache.has(key)) { + componentCache.set(key, featureBundle.createMotionComponent(key, undefined, preloadedFeatures, createVisualElement)); + } + return componentCache.get(key); + }, + }); +} + +const motion = /*@__PURE__*/ createMotionProxy(featureBundle.featureBundle, featureBundle.createDomVisualElement); + +function checkReorder(order, value, offset, velocity) { + if (!velocity) + return order; + const index = order.findIndex((item) => item.value === value); + if (index === -1) + return order; + const nextOffset = velocity > 0 ? 1 : -1; + const nextItem = order[index + nextOffset]; + if (!nextItem) + return order; + const item = order[index]; + const nextLayout = nextItem.layout; + const nextItemCenter = motionDom.mixNumber(nextLayout.min, nextLayout.max, 0.5); + if ((nextOffset === 1 && item.layout.max + offset > nextItemCenter) || + (nextOffset === -1 && item.layout.min + offset < nextItemCenter)) { + return motionUtils.moveItem(order, index, index + nextOffset); + } + return order; +} + +function ReorderGroupComponent({ children, as = "ul", axis = "y", onReorder, values, ...props }, externalRef) { + const Component = featureBundle.useConstant(() => motion[as]); + const order = []; + const isReordering = React.useRef(false); + motionUtils.invariant(Boolean(values), "Reorder.Group must be provided a values prop", "reorder-values"); + const context = { + axis, + registerItem: (value, layout) => { + // If the entry was already added, update it rather than adding it again + const idx = order.findIndex((entry) => value === entry.value); + if (idx !== -1) { + order[idx].layout = layout[axis]; + } + else { + order.push({ value: value, layout: layout[axis] }); + } + order.sort(compareMin); + }, + updateOrder: (item, offset, velocity) => { + if (isReordering.current) + return; + const newOrder = checkReorder(order, item, offset, velocity); + if (order !== newOrder) { + isReordering.current = true; + onReorder(newOrder + .map(getValue) + .filter((value) => values.indexOf(value) !== -1)); + } + }, + }; + React.useEffect(() => { + isReordering.current = false; + }); + return (jsxRuntime.jsx(Component, { ...props, ref: externalRef, ignoreStrict: true, children: jsxRuntime.jsx(ReorderContext.Provider, { value: context, children: children }) })); +} +const ReorderGroup = /*@__PURE__*/ React.forwardRef(ReorderGroupComponent); +function getValue(item) { + return item.value; +} +function compareMin(a, b) { + return a.layout.min - b.layout.min; +} + +/** + * Creates a `MotionValue` to track the state and velocity of a value. + * + * Usually, these are created automatically. For advanced use-cases, like use with `useTransform`, you can create `MotionValue`s externally and pass them into the animated component via the `style` prop. + * + * ```jsx + * export const MyComponent = () => { + * const scale = useMotionValue(1) + * + * return + * } + * ``` + * + * @param initial - The initial state. + * + * @public + */ +function useMotionValue(initial) { + const value = featureBundle.useConstant(() => motionDom.motionValue(initial)); + /** + * If this motion value is being used in static mode, like on + * the Framer canvas, force components to rerender when the motion + * value is updated. + */ + const { isStatic } = React.useContext(featureBundle.MotionConfigContext); + if (isStatic) { + const [, setLatest] = React.useState(initial); + React.useEffect(() => value.on("change", setLatest), []); + } + return value; +} + +function useCombineMotionValues(values, combineValues) { + /** + * Initialise the returned motion value. This remains the same between renders. + */ + const value = useMotionValue(combineValues()); + /** + * Create a function that will update the template motion value with the latest values. + * This is pre-bound so whenever a motion value updates it can schedule its + * execution in Framesync. If it's already been scheduled it won't be fired twice + * in a single frame. + */ + const updateValue = () => value.set(combineValues()); + /** + * Synchronously update the motion value with the latest values during the render. + * This ensures that within a React render, the styles applied to the DOM are up-to-date. + */ + updateValue(); + /** + * Subscribe to all motion values found within the template. Whenever any of them change, + * schedule an update. + */ + featureBundle.useIsomorphicLayoutEffect(() => { + const scheduleUpdate = () => motionDom.frame.preRender(updateValue, false, true); + const subscriptions = values.map((v) => v.on("change", scheduleUpdate)); + return () => { + subscriptions.forEach((unsubscribe) => unsubscribe()); + motionDom.cancelFrame(updateValue); + }; + }); + return value; +} + +function useComputed(compute) { + /** + * Open session of collectMotionValues. Any MotionValue that calls get() + * will be saved into this array. + */ + motionDom.collectMotionValues.current = []; + compute(); + const value = useCombineMotionValues(motionDom.collectMotionValues.current, compute); + /** + * Synchronously close session of collectMotionValues. + */ + motionDom.collectMotionValues.current = undefined; + return value; +} + +function useTransform(input, inputRangeOrTransformer, outputRange, options) { + if (typeof input === "function") { + return useComputed(input); + } + const transformer = typeof inputRangeOrTransformer === "function" + ? inputRangeOrTransformer + : motionDom.transform(inputRangeOrTransformer, outputRange, options); + return Array.isArray(input) + ? useListTransform(input, transformer) + : useListTransform([input], ([latest]) => transformer(latest)); +} +function useListTransform(values, transformer) { + const latest = featureBundle.useConstant(() => []); + return useCombineMotionValues(values, () => { + latest.length = 0; + const numValues = values.length; + for (let i = 0; i < numValues; i++) { + latest[i] = values[i].get(); + } + return transformer(latest); + }); +} + +function useDefaultMotionValue(value, defaultValue = 0) { + return motionDom.isMotionValue(value) ? value : useMotionValue(defaultValue); +} +function ReorderItemComponent({ children, style = {}, value, as = "li", onDrag, layout = true, ...props }, externalRef) { + const Component = featureBundle.useConstant(() => motion[as]); + const context = React.useContext(ReorderContext); + const point = { + x: useDefaultMotionValue(style.x), + y: useDefaultMotionValue(style.y), + }; + const zIndex = useTransform([point.x, point.y], ([latestX, latestY]) => latestX || latestY ? 1 : "unset"); + motionUtils.invariant(Boolean(context), "Reorder.Item must be a child of Reorder.Group", "reorder-item-child"); + const { axis, registerItem, updateOrder } = context; + return (jsxRuntime.jsx(Component, { drag: axis, ...props, dragSnapToOrigin: true, style: { ...style, x: point.x, y: point.y, zIndex }, layout: layout, onDrag: (event, gesturePoint) => { + const { velocity } = gesturePoint; + velocity[axis] && + updateOrder(value, point[axis].get(), velocity[axis]); + onDrag && onDrag(event, gesturePoint); + }, onLayoutMeasure: (measured) => registerItem(value, measured), ref: externalRef, ignoreStrict: true, children: children })); +} +const ReorderItem = /*@__PURE__*/ React.forwardRef(ReorderItemComponent); + +var namespace = /*#__PURE__*/Object.freeze({ + __proto__: null, + Group: ReorderGroup, + Item: ReorderItem +}); + +function isDOMKeyframes(keyframes) { + return typeof keyframes === "object" && !Array.isArray(keyframes); +} + +function resolveSubjects(subject, keyframes, scope, selectorCache) { + if (typeof subject === "string" && isDOMKeyframes(keyframes)) { + return motionDom.resolveElements(subject, scope, selectorCache); + } + else if (subject instanceof NodeList) { + return Array.from(subject); + } + else if (Array.isArray(subject)) { + return subject; + } + else { + return [subject]; + } +} + +function calculateRepeatDuration(duration, repeat, _repeatDelay) { + return duration * (repeat + 1); +} + +/** + * Given a absolute or relative time definition and current/prev time state of the sequence, + * calculate an absolute time for the next keyframes. + */ +function calcNextTime(current, next, prev, labels) { + if (typeof next === "number") { + return next; + } + else if (next.startsWith("-") || next.startsWith("+")) { + return Math.max(0, current + parseFloat(next)); + } + else if (next === "<") { + return prev; + } + else if (next.startsWith("<")) { + return Math.max(0, prev + parseFloat(next.slice(1))); + } + else { + return labels.get(next) ?? current; + } +} + +function eraseKeyframes(sequence, startTime, endTime) { + for (let i = 0; i < sequence.length; i++) { + const keyframe = sequence[i]; + if (keyframe.at > startTime && keyframe.at < endTime) { + motionUtils.removeItem(sequence, keyframe); + // If we remove this item we have to push the pointer back one + i--; + } + } +} +function addKeyframes(sequence, keyframes, easing, offset, startTime, endTime) { + /** + * Erase every existing value between currentTime and targetTime, + * this will essentially splice this timeline into any currently + * defined ones. + */ + eraseKeyframes(sequence, startTime, endTime); + for (let i = 0; i < keyframes.length; i++) { + sequence.push({ + value: keyframes[i], + at: motionDom.mixNumber(startTime, endTime, offset[i]), + easing: motionUtils.getEasingForSegment(easing, i), + }); + } +} + +/** + * Take an array of times that represent repeated keyframes. For instance + * if we have original times of [0, 0.5, 1] then our repeated times will + * be [0, 0.5, 1, 1, 1.5, 2]. Loop over the times and scale them back + * down to a 0-1 scale. + */ +function normalizeTimes(times, repeat) { + for (let i = 0; i < times.length; i++) { + times[i] = times[i] / (repeat + 1); + } +} + +function compareByTime(a, b) { + if (a.at === b.at) { + if (a.value === null) + return 1; + if (b.value === null) + return -1; + return 0; + } + else { + return a.at - b.at; + } +} + +const defaultSegmentEasing = "easeInOut"; +const MAX_REPEAT = 20; +function createAnimationsFromSequence(sequence, { defaultTransition = {}, ...sequenceTransition } = {}, scope, generators) { + const defaultDuration = defaultTransition.duration || 0.3; + const animationDefinitions = new Map(); + const sequences = new Map(); + const elementCache = {}; + const timeLabels = new Map(); + let prevTime = 0; + let currentTime = 0; + let totalDuration = 0; + /** + * Build the timeline by mapping over the sequence array and converting + * the definitions into keyframes and offsets with absolute time values. + * These will later get converted into relative offsets in a second pass. + */ + for (let i = 0; i < sequence.length; i++) { + const segment = sequence[i]; + /** + * If this is a timeline label, mark it and skip the rest of this iteration. + */ + if (typeof segment === "string") { + timeLabels.set(segment, currentTime); + continue; + } + else if (!Array.isArray(segment)) { + timeLabels.set(segment.name, calcNextTime(currentTime, segment.at, prevTime, timeLabels)); + continue; + } + let [subject, keyframes, transition = {}] = segment; + /** + * If a relative or absolute time value has been specified we need to resolve + * it in relation to the currentTime. + */ + if (transition.at !== undefined) { + currentTime = calcNextTime(currentTime, transition.at, prevTime, timeLabels); + } + /** + * Keep track of the maximum duration in this definition. This will be + * applied to currentTime once the definition has been parsed. + */ + let maxDuration = 0; + const resolveValueSequence = (valueKeyframes, valueTransition, valueSequence, elementIndex = 0, numSubjects = 0) => { + const valueKeyframesAsList = keyframesAsList(valueKeyframes); + const { delay = 0, times = motionDom.defaultOffset(valueKeyframesAsList), type = "keyframes", repeat, repeatType, repeatDelay = 0, ...remainingTransition } = valueTransition; + let { ease = defaultTransition.ease || "easeOut", duration } = valueTransition; + /** + * Resolve stagger() if defined. + */ + const calculatedDelay = typeof delay === "function" + ? delay(elementIndex, numSubjects) + : delay; + /** + * If this animation should and can use a spring, generate a spring easing function. + */ + const numKeyframes = valueKeyframesAsList.length; + const createGenerator = motionDom.isGenerator(type) + ? type + : generators?.[type || "keyframes"]; + if (numKeyframes <= 2 && createGenerator) { + /** + * As we're creating an easing function from a spring, + * ideally we want to generate it using the real distance + * between the two keyframes. However this isn't always + * possible - in these situations we use 0-100. + */ + let absoluteDelta = 100; + if (numKeyframes === 2 && + isNumberKeyframesArray(valueKeyframesAsList)) { + const delta = valueKeyframesAsList[1] - valueKeyframesAsList[0]; + absoluteDelta = Math.abs(delta); + } + const springTransition = { ...remainingTransition }; + if (duration !== undefined) { + springTransition.duration = motionUtils.secondsToMilliseconds(duration); + } + const springEasing = motionDom.createGeneratorEasing(springTransition, absoluteDelta, createGenerator); + ease = springEasing.ease; + duration = springEasing.duration; + } + duration ?? (duration = defaultDuration); + const startTime = currentTime + calculatedDelay; + /** + * If there's only one time offset of 0, fill in a second with length 1 + */ + if (times.length === 1 && times[0] === 0) { + times[1] = 1; + } + /** + * Fill out if offset if fewer offsets than keyframes + */ + const remainder = times.length - valueKeyframesAsList.length; + remainder > 0 && motionDom.fillOffset(times, remainder); + /** + * If only one value has been set, ie [1], push a null to the start of + * the keyframe array. This will let us mark a keyframe at this point + * that will later be hydrated with the previous value. + */ + valueKeyframesAsList.length === 1 && + valueKeyframesAsList.unshift(null); + /** + * Handle repeat options + */ + if (repeat) { + motionUtils.invariant(repeat < MAX_REPEAT, "Repeat count too high, must be less than 20", "repeat-count-high"); + duration = calculateRepeatDuration(duration, repeat); + const originalKeyframes = [...valueKeyframesAsList]; + const originalTimes = [...times]; + ease = Array.isArray(ease) ? [...ease] : [ease]; + const originalEase = [...ease]; + for (let repeatIndex = 0; repeatIndex < repeat; repeatIndex++) { + valueKeyframesAsList.push(...originalKeyframes); + for (let keyframeIndex = 0; keyframeIndex < originalKeyframes.length; keyframeIndex++) { + times.push(originalTimes[keyframeIndex] + (repeatIndex + 1)); + ease.push(keyframeIndex === 0 + ? "linear" + : motionUtils.getEasingForSegment(originalEase, keyframeIndex - 1)); + } + } + normalizeTimes(times, repeat); + } + const targetTime = startTime + duration; + /** + * Add keyframes, mapping offsets to absolute time. + */ + addKeyframes(valueSequence, valueKeyframesAsList, ease, times, startTime, targetTime); + maxDuration = Math.max(calculatedDelay + duration, maxDuration); + totalDuration = Math.max(targetTime, totalDuration); + }; + if (motionDom.isMotionValue(subject)) { + const subjectSequence = getSubjectSequence(subject, sequences); + resolveValueSequence(keyframes, transition, getValueSequence("default", subjectSequence)); + } + else { + const subjects = resolveSubjects(subject, keyframes, scope, elementCache); + const numSubjects = subjects.length; + /** + * For every element in this segment, process the defined values. + */ + for (let subjectIndex = 0; subjectIndex < numSubjects; subjectIndex++) { + /** + * Cast necessary, but we know these are of this type + */ + keyframes = keyframes; + transition = transition; + const thisSubject = subjects[subjectIndex]; + const subjectSequence = getSubjectSequence(thisSubject, sequences); + for (const key in keyframes) { + resolveValueSequence(keyframes[key], getValueTransition(transition, key), getValueSequence(key, subjectSequence), subjectIndex, numSubjects); + } + } + } + prevTime = currentTime; + currentTime += maxDuration; + } + /** + * For every element and value combination create a new animation. + */ + sequences.forEach((valueSequences, element) => { + for (const key in valueSequences) { + const valueSequence = valueSequences[key]; + /** + * Arrange all the keyframes in ascending time order. + */ + valueSequence.sort(compareByTime); + const keyframes = []; + const valueOffset = []; + const valueEasing = []; + /** + * For each keyframe, translate absolute times into + * relative offsets based on the total duration of the timeline. + */ + for (let i = 0; i < valueSequence.length; i++) { + const { at, value, easing } = valueSequence[i]; + keyframes.push(value); + valueOffset.push(motionUtils.progress(0, totalDuration, at)); + valueEasing.push(easing || "easeOut"); + } + /** + * If the first keyframe doesn't land on offset: 0 + * provide one by duplicating the initial keyframe. This ensures + * it snaps to the first keyframe when the animation starts. + */ + if (valueOffset[0] !== 0) { + valueOffset.unshift(0); + keyframes.unshift(keyframes[0]); + valueEasing.unshift(defaultSegmentEasing); + } + /** + * If the last keyframe doesn't land on offset: 1 + * provide one with a null wildcard value. This will ensure it + * stays static until the end of the animation. + */ + if (valueOffset[valueOffset.length - 1] !== 1) { + valueOffset.push(1); + keyframes.push(null); + } + if (!animationDefinitions.has(element)) { + animationDefinitions.set(element, { + keyframes: {}, + transition: {}, + }); + } + const definition = animationDefinitions.get(element); + definition.keyframes[key] = keyframes; + definition.transition[key] = { + ...defaultTransition, + duration: totalDuration, + ease: valueEasing, + times: valueOffset, + ...sequenceTransition, + }; + } + }); + return animationDefinitions; +} +function getSubjectSequence(subject, sequences) { + !sequences.has(subject) && sequences.set(subject, {}); + return sequences.get(subject); +} +function getValueSequence(name, sequences) { + if (!sequences[name]) + sequences[name] = []; + return sequences[name]; +} +function keyframesAsList(keyframes) { + return Array.isArray(keyframes) ? keyframes : [keyframes]; +} +function getValueTransition(transition, key) { + return transition && transition[key] + ? { + ...transition, + ...transition[key], + } + : { ...transition }; +} +const isNumber = (keyframe) => typeof keyframe === "number"; +const isNumberKeyframesArray = (keyframes) => keyframes.every(isNumber); + +function isObjectKey(key, object) { + return key in object; +} +class ObjectVisualElement extends featureBundle.VisualElement { + constructor() { + super(...arguments); + this.type = "object"; + } + readValueFromInstance(instance, key) { + if (isObjectKey(key, instance)) { + const value = instance[key]; + if (typeof value === "string" || typeof value === "number") { + return value; + } + } + return undefined; + } + getBaseTargetFromProps() { + return undefined; + } + removeValueFromRenderState(key, renderState) { + delete renderState.output[key]; + } + measureInstanceViewportBox() { + return featureBundle.createBox(); + } + build(renderState, latestValues) { + Object.assign(renderState.output, latestValues); + } + renderInstance(instance, { output }) { + Object.assign(instance, output); + } + sortInstanceNodePosition() { + return 0; + } +} + +function createDOMVisualElement(element) { + const options = { + presenceContext: null, + props: {}, + visualState: { + renderState: { + transform: {}, + transformOrigin: {}, + style: {}, + vars: {}, + attrs: {}, + }, + latestValues: {}, + }, + }; + const node = motionDom.isSVGElement(element) && !motionDom.isSVGSVGElement(element) + ? new featureBundle.SVGVisualElement(options) + : new featureBundle.HTMLVisualElement(options); + node.mount(element); + featureBundle.visualElementStore.set(element, node); +} +function createObjectVisualElement(subject) { + const options = { + presenceContext: null, + props: {}, + visualState: { + renderState: { + output: {}, + }, + latestValues: {}, + }, + }; + const node = new ObjectVisualElement(options); + node.mount(subject); + featureBundle.visualElementStore.set(subject, node); +} + +function isSingleValue(subject, keyframes) { + return (motionDom.isMotionValue(subject) || + typeof subject === "number" || + (typeof subject === "string" && !isDOMKeyframes(keyframes))); +} +/** + * Implementation + */ +function animateSubject(subject, keyframes, options, scope) { + const animations = []; + if (isSingleValue(subject, keyframes)) { + animations.push(featureBundle.animateSingleValue(subject, isDOMKeyframes(keyframes) + ? keyframes.default || keyframes + : keyframes, options ? options.default || options : options)); + } + else { + const subjects = resolveSubjects(subject, keyframes, scope); + const numSubjects = subjects.length; + motionUtils.invariant(Boolean(numSubjects), "No valid elements provided.", "no-valid-elements"); + for (let i = 0; i < numSubjects; i++) { + const thisSubject = subjects[i]; + motionUtils.invariant(thisSubject !== null, "You're trying to perform an animation on null. Ensure that selectors are correctly finding elements and refs are correctly hydrated.", "animate-null"); + const createVisualElement = thisSubject instanceof Element + ? createDOMVisualElement + : createObjectVisualElement; + if (!featureBundle.visualElementStore.has(thisSubject)) { + createVisualElement(thisSubject); + } + const visualElement = featureBundle.visualElementStore.get(thisSubject); + const transition = { ...options }; + /** + * Resolve stagger function if provided. + */ + if ("delay" in transition && + typeof transition.delay === "function") { + transition.delay = transition.delay(i, numSubjects); + } + animations.push(...featureBundle.animateTarget(visualElement, { ...keyframes, transition }, {})); + } + } + return animations; +} + +function animateSequence(sequence, options, scope) { + const animations = []; + const animationDefinitions = createAnimationsFromSequence(sequence, options, scope, { spring: motionDom.spring }); + animationDefinitions.forEach(({ keyframes, transition }, subject) => { + animations.push(...animateSubject(subject, keyframes, transition)); + }); + return animations; +} + +function isSequence(value) { + return Array.isArray(value) && value.some(Array.isArray); +} +/** + * Creates an animation function that is optionally scoped + * to a specific element. + */ +function createScopedAnimate(scope) { + /** + * Implementation + */ + function scopedAnimate(subjectOrSequence, optionsOrKeyframes, options) { + let animations = []; + if (isSequence(subjectOrSequence)) { + animations = animateSequence(subjectOrSequence, optionsOrKeyframes, scope); + } + else { + animations = animateSubject(subjectOrSequence, optionsOrKeyframes, options, scope); + } + const animation = new motionDom.GroupAnimationWithThen(animations); + if (scope) { + scope.animations.push(animation); + animation.finished.then(() => { + motionUtils.removeItem(scope.animations, animation); + }); + } + return animation; + } + return scopedAnimate; +} +const animate = createScopedAnimate(); + +function animateElements(elementOrSelector, keyframes, options, scope) { + const elements = motionDom.resolveElements(elementOrSelector, scope); + const numElements = elements.length; + motionUtils.invariant(Boolean(numElements), "No valid elements provided.", "no-valid-elements"); + /** + * WAAPI doesn't support interrupting animations. + * + * Therefore, starting animations requires a three-step process: + * 1. Stop existing animations (write styles to DOM) + * 2. Resolve keyframes (read styles from DOM) + * 3. Create new animations (write styles to DOM) + * + * The hybrid `animate()` function uses AsyncAnimation to resolve + * keyframes before creating new animations, which removes style + * thrashing. Here, we have much stricter filesize constraints. + * Therefore we do this in a synchronous way that ensures that + * at least within `animate()` calls there is no style thrashing. + * + * In the motion-native-animate-mini-interrupt benchmark this + * was 80% faster than a single loop. + */ + const animationDefinitions = []; + /** + * Step 1: Build options and stop existing animations (write) + */ + for (let i = 0; i < numElements; i++) { + const element = elements[i]; + const elementTransition = { ...options }; + /** + * Resolve stagger function if provided. + */ + if (typeof elementTransition.delay === "function") { + elementTransition.delay = elementTransition.delay(i, numElements); + } + for (const valueName in keyframes) { + let valueKeyframes = keyframes[valueName]; + if (!Array.isArray(valueKeyframes)) { + valueKeyframes = [valueKeyframes]; + } + const valueOptions = { + ...motionDom.getValueTransition(elementTransition, valueName), + }; + valueOptions.duration && (valueOptions.duration = motionUtils.secondsToMilliseconds(valueOptions.duration)); + valueOptions.delay && (valueOptions.delay = motionUtils.secondsToMilliseconds(valueOptions.delay)); + /** + * If there's an existing animation playing on this element then stop it + * before creating a new one. + */ + const map = motionDom.getAnimationMap(element); + const key = motionDom.animationMapKey(valueName, valueOptions.pseudoElement || ""); + const currentAnimation = map.get(key); + currentAnimation && currentAnimation.stop(); + animationDefinitions.push({ + map, + key, + unresolvedKeyframes: valueKeyframes, + options: { + ...valueOptions, + element, + name: valueName, + allowFlatten: !elementTransition.type && !elementTransition.ease, + }, + }); + } + } + /** + * Step 2: Resolve keyframes (read) + */ + for (let i = 0; i < animationDefinitions.length; i++) { + const { unresolvedKeyframes, options: animationOptions } = animationDefinitions[i]; + const { element, name, pseudoElement } = animationOptions; + if (!pseudoElement && unresolvedKeyframes[0] === null) { + unresolvedKeyframes[0] = motionDom.getComputedStyle(element, name); + } + motionDom.fillWildcards(unresolvedKeyframes); + motionDom.applyPxDefaults(unresolvedKeyframes, name); + /** + * If we only have one keyframe, explicitly read the initial keyframe + * from the computed style. This is to ensure consistency with WAAPI behaviour + * for restarting animations, for instance .play() after finish, when it + * has one vs two keyframes. + */ + if (!pseudoElement && unresolvedKeyframes.length < 2) { + unresolvedKeyframes.unshift(motionDom.getComputedStyle(element, name)); + } + animationOptions.keyframes = unresolvedKeyframes; + } + /** + * Step 3: Create new animations (write) + */ + const animations = []; + for (let i = 0; i < animationDefinitions.length; i++) { + const { map, key, options: animationOptions } = animationDefinitions[i]; + const animation = new motionDom.NativeAnimation(animationOptions); + map.set(key, animation); + animation.finished.finally(() => map.delete(key)); + animations.push(animation); + } + return animations; +} + +const createScopedWaapiAnimate = (scope) => { + function scopedAnimate(elementOrSelector, keyframes, options) { + return new motionDom.GroupAnimationWithThen(animateElements(elementOrSelector, keyframes, options, scope)); + } + return scopedAnimate; +}; +const animateMini = /*@__PURE__*/ createScopedWaapiAnimate(); + +/** + * A time in milliseconds, beyond which we consider the scroll velocity to be 0. + */ +const maxElapsed = 50; +const createAxisInfo = () => ({ + current: 0, + offset: [], + progress: 0, + scrollLength: 0, + targetOffset: 0, + targetLength: 0, + containerLength: 0, + velocity: 0, +}); +const createScrollInfo = () => ({ + time: 0, + x: createAxisInfo(), + y: createAxisInfo(), +}); +const keys = { + x: { + length: "Width", + position: "Left", + }, + y: { + length: "Height", + position: "Top", + }, +}; +function updateAxisInfo(element, axisName, info, time) { + const axis = info[axisName]; + const { length, position } = keys[axisName]; + const prev = axis.current; + const prevTime = info.time; + axis.current = element[`scroll${position}`]; + axis.scrollLength = element[`scroll${length}`] - element[`client${length}`]; + axis.offset.length = 0; + axis.offset[0] = 0; + axis.offset[1] = axis.scrollLength; + axis.progress = motionUtils.progress(0, axis.scrollLength, axis.current); + const elapsed = time - prevTime; + axis.velocity = + elapsed > maxElapsed + ? 0 + : motionUtils.velocityPerSecond(axis.current - prev, elapsed); +} +function updateScrollInfo(element, info, time) { + updateAxisInfo(element, "x", info, time); + updateAxisInfo(element, "y", info, time); + info.time = time; +} + +function calcInset(element, container) { + const inset = { x: 0, y: 0 }; + let current = element; + while (current && current !== container) { + if (motionDom.isHTMLElement(current)) { + inset.x += current.offsetLeft; + inset.y += current.offsetTop; + current = current.offsetParent; + } + else if (current.tagName === "svg") { + /** + * This isn't an ideal approach to measuring the offset of tags. + * It would be preferable, given they behave like HTMLElements in most ways + * to use offsetLeft/Top. But these don't exist on . Likewise we + * can't use .getBBox() like most SVG elements as these provide the offset + * relative to the SVG itself, which for is usually 0x0. + */ + const svgBoundingBox = current.getBoundingClientRect(); + current = current.parentElement; + const parentBoundingBox = current.getBoundingClientRect(); + inset.x += svgBoundingBox.left - parentBoundingBox.left; + inset.y += svgBoundingBox.top - parentBoundingBox.top; + } + else if (current instanceof SVGGraphicsElement) { + const { x, y } = current.getBBox(); + inset.x += x; + inset.y += y; + let svg = null; + let parent = current.parentNode; + while (!svg) { + if (parent.tagName === "svg") { + svg = parent; + } + parent = current.parentNode; + } + current = svg; + } + else { + break; + } + } + return inset; +} + +const namedEdges = { + start: 0, + center: 0.5, + end: 1, +}; +function resolveEdge(edge, length, inset = 0) { + let delta = 0; + /** + * If we have this edge defined as a preset, replace the definition + * with the numerical value. + */ + if (edge in namedEdges) { + edge = namedEdges[edge]; + } + /** + * Handle unit values + */ + if (typeof edge === "string") { + const asNumber = parseFloat(edge); + if (edge.endsWith("px")) { + delta = asNumber; + } + else if (edge.endsWith("%")) { + edge = asNumber / 100; + } + else if (edge.endsWith("vw")) { + delta = (asNumber / 100) * document.documentElement.clientWidth; + } + else if (edge.endsWith("vh")) { + delta = (asNumber / 100) * document.documentElement.clientHeight; + } + else { + edge = asNumber; + } + } + /** + * If the edge is defined as a number, handle as a progress value. + */ + if (typeof edge === "number") { + delta = length * edge; + } + return inset + delta; +} + +const defaultOffset = [0, 0]; +function resolveOffset(offset, containerLength, targetLength, targetInset) { + let offsetDefinition = Array.isArray(offset) ? offset : defaultOffset; + let targetPoint = 0; + let containerPoint = 0; + if (typeof offset === "number") { + /** + * If we're provided offset: [0, 0.5, 1] then each number x should become + * [x, x], so we default to the behaviour of mapping 0 => 0 of both target + * and container etc. + */ + offsetDefinition = [offset, offset]; + } + else if (typeof offset === "string") { + offset = offset.trim(); + if (offset.includes(" ")) { + offsetDefinition = offset.split(" "); + } + else { + /** + * If we're provided a definition like "100px" then we want to apply + * that only to the top of the target point, leaving the container at 0. + * Whereas a named offset like "end" should be applied to both. + */ + offsetDefinition = [offset, namedEdges[offset] ? offset : `0`]; + } + } + targetPoint = resolveEdge(offsetDefinition[0], targetLength, targetInset); + containerPoint = resolveEdge(offsetDefinition[1], containerLength); + return targetPoint - containerPoint; +} + +const ScrollOffset = { + Enter: [ + [0, 1], + [1, 1], + ], + Exit: [ + [0, 0], + [1, 0], + ], + Any: [ + [1, 0], + [0, 1], + ], + All: [ + [0, 0], + [1, 1], + ], +}; + +const point = { x: 0, y: 0 }; +function getTargetSize(target) { + return "getBBox" in target && target.tagName !== "svg" + ? target.getBBox() + : { width: target.clientWidth, height: target.clientHeight }; +} +function resolveOffsets(container, info, options) { + const { offset: offsetDefinition = ScrollOffset.All } = options; + const { target = container, axis = "y" } = options; + const lengthLabel = axis === "y" ? "height" : "width"; + const inset = target !== container ? calcInset(target, container) : point; + /** + * Measure the target and container. If they're the same thing then we + * use the container's scrollWidth/Height as the target, from there + * all other calculations can remain the same. + */ + const targetSize = target === container + ? { width: container.scrollWidth, height: container.scrollHeight } + : getTargetSize(target); + const containerSize = { + width: container.clientWidth, + height: container.clientHeight, + }; + /** + * Reset the length of the resolved offset array rather than creating a new one. + * TODO: More reusable data structures for targetSize/containerSize would also be good. + */ + info[axis].offset.length = 0; + /** + * Populate the offset array by resolving the user's offset definition into + * a list of pixel scroll offets. + */ + let hasChanged = !info[axis].interpolate; + const numOffsets = offsetDefinition.length; + for (let i = 0; i < numOffsets; i++) { + const offset = resolveOffset(offsetDefinition[i], containerSize[lengthLabel], targetSize[lengthLabel], inset[axis]); + if (!hasChanged && offset !== info[axis].interpolatorOffsets[i]) { + hasChanged = true; + } + info[axis].offset[i] = offset; + } + /** + * If the pixel scroll offsets have changed, create a new interpolator function + * to map scroll value into a progress. + */ + if (hasChanged) { + info[axis].interpolate = motionDom.interpolate(info[axis].offset, motionDom.defaultOffset(offsetDefinition), { clamp: false }); + info[axis].interpolatorOffsets = [...info[axis].offset]; + } + info[axis].progress = motionUtils.clamp(0, 1, info[axis].interpolate(info[axis].current)); +} + +function measure(container, target = container, info) { + /** + * Find inset of target within scrollable container + */ + info.x.targetOffset = 0; + info.y.targetOffset = 0; + if (target !== container) { + let node = target; + while (node && node !== container) { + info.x.targetOffset += node.offsetLeft; + info.y.targetOffset += node.offsetTop; + node = node.offsetParent; + } + } + info.x.targetLength = + target === container ? target.scrollWidth : target.clientWidth; + info.y.targetLength = + target === container ? target.scrollHeight : target.clientHeight; + info.x.containerLength = container.clientWidth; + info.y.containerLength = container.clientHeight; + /** + * In development mode ensure scroll containers aren't position: static as this makes + * it difficult to measure their relative positions. + */ + if (process.env.NODE_ENV !== "production") { + if (container && target && target !== container) { + motionUtils.warnOnce(getComputedStyle(container).position !== "static", "Please ensure that the container has a non-static position, like 'relative', 'fixed', or 'absolute' to ensure scroll offset is calculated correctly."); + } + } +} +function createOnScrollHandler(element, onScroll, info, options = {}) { + return { + measure: (time) => { + measure(element, options.target, info); + updateScrollInfo(element, info, time); + if (options.offset || options.target) { + resolveOffsets(element, info, options); + } + }, + notify: () => onScroll(info), + }; +} + +const scrollListeners = new WeakMap(); +const resizeListeners = new WeakMap(); +const onScrollHandlers = new WeakMap(); +const getEventTarget = (element) => element === document.scrollingElement ? window : element; +function scrollInfo(onScroll, { container = document.scrollingElement, ...options } = {}) { + if (!container) + return motionUtils.noop; + let containerHandlers = onScrollHandlers.get(container); + /** + * Get the onScroll handlers for this container. + * If one isn't found, create a new one. + */ + if (!containerHandlers) { + containerHandlers = new Set(); + onScrollHandlers.set(container, containerHandlers); + } + /** + * Create a new onScroll handler for the provided callback. + */ + const info = createScrollInfo(); + const containerHandler = createOnScrollHandler(container, onScroll, info, options); + containerHandlers.add(containerHandler); + /** + * Check if there's a scroll event listener for this container. + * If not, create one. + */ + if (!scrollListeners.has(container)) { + const measureAll = () => { + for (const handler of containerHandlers) { + handler.measure(motionDom.frameData.timestamp); + } + motionDom.frame.preUpdate(notifyAll); + }; + const notifyAll = () => { + for (const handler of containerHandlers) { + handler.notify(); + } + }; + const listener = () => motionDom.frame.read(measureAll); + scrollListeners.set(container, listener); + const target = getEventTarget(container); + window.addEventListener("resize", listener, { passive: true }); + if (container !== document.documentElement) { + resizeListeners.set(container, motionDom.resize(container, listener)); + } + target.addEventListener("scroll", listener, { passive: true }); + listener(); + } + const listener = scrollListeners.get(container); + motionDom.frame.read(listener, false, true); + return () => { + motionDom.cancelFrame(listener); + /** + * Check if we even have any handlers for this container. + */ + const currentHandlers = onScrollHandlers.get(container); + if (!currentHandlers) + return; + currentHandlers.delete(containerHandler); + if (currentHandlers.size) + return; + /** + * If no more handlers, remove the scroll listener too. + */ + const scrollListener = scrollListeners.get(container); + scrollListeners.delete(container); + if (scrollListener) { + getEventTarget(container).removeEventListener("scroll", scrollListener); + resizeListeners.get(container)?.(); + window.removeEventListener("resize", scrollListener); + } + }; +} + +const timelineCache = new Map(); +function scrollTimelineFallback(options) { + const currentTime = { value: 0 }; + const cancel = scrollInfo((info) => { + currentTime.value = info[options.axis].progress * 100; + }, options); + return { currentTime, cancel }; +} +function getTimeline({ source, container, ...options }) { + const { axis } = options; + if (source) + container = source; + const containerCache = timelineCache.get(container) ?? new Map(); + timelineCache.set(container, containerCache); + const targetKey = options.target ?? "self"; + const targetCache = containerCache.get(targetKey) ?? {}; + const axisKey = axis + (options.offset ?? []).join(","); + if (!targetCache[axisKey]) { + targetCache[axisKey] = + !options.target && motionDom.supportsScrollTimeline() + ? new ScrollTimeline({ source: container, axis }) + : scrollTimelineFallback({ container, ...options }); + } + return targetCache[axisKey]; +} + +function attachToAnimation(animation, options) { + const timeline = getTimeline(options); + return animation.attachTimeline({ + timeline: options.target ? undefined : timeline, + observe: (valueAnimation) => { + valueAnimation.pause(); + return motionDom.observeTimeline((progress) => { + valueAnimation.time = valueAnimation.duration * progress; + }, timeline); + }, + }); +} + +/** + * If the onScroll function has two arguments, it's expecting + * more specific information about the scroll from scrollInfo. + */ +function isOnScrollWithInfo(onScroll) { + return onScroll.length === 2; +} +function attachToFunction(onScroll, options) { + if (isOnScrollWithInfo(onScroll)) { + return scrollInfo((info) => { + onScroll(info[options.axis].progress, info); + }, options); + } + else { + return motionDom.observeTimeline(onScroll, getTimeline(options)); + } +} + +function scroll(onScroll, { axis = "y", container = document.scrollingElement, ...options } = {}) { + if (!container) + return motionUtils.noop; + const optionsWithDefaults = { axis, container, ...options }; + return typeof onScroll === "function" + ? attachToFunction(onScroll, optionsWithDefaults) + : attachToAnimation(onScroll, optionsWithDefaults); +} + +const thresholds = { + some: 0, + all: 1, +}; +function inView(elementOrSelector, onStart, { root, margin: rootMargin, amount = "some" } = {}) { + const elements = motionDom.resolveElements(elementOrSelector); + const activeIntersections = new WeakMap(); + const onIntersectionChange = (entries) => { + entries.forEach((entry) => { + const onEnd = activeIntersections.get(entry.target); + /** + * If there's no change to the intersection, we don't need to + * do anything here. + */ + if (entry.isIntersecting === Boolean(onEnd)) + return; + if (entry.isIntersecting) { + const newOnEnd = onStart(entry.target, entry); + if (typeof newOnEnd === "function") { + activeIntersections.set(entry.target, newOnEnd); + } + else { + observer.unobserve(entry.target); + } + } + else if (typeof onEnd === "function") { + onEnd(entry); + activeIntersections.delete(entry.target); + } + }); + }; + const observer = new IntersectionObserver(onIntersectionChange, { + root, + rootMargin, + threshold: typeof amount === "number" ? amount : thresholds[amount], + }); + elements.forEach((element) => observer.observe(element)); + return () => observer.disconnect(); +} + +const m = /*@__PURE__*/ createMotionProxy(); + +function useUnmountEffect(callback) { + return React.useEffect(() => () => callback(), []); +} + +/** + * @public + */ +const domAnimation = { + renderer: featureBundle.createDomVisualElement, + ...featureBundle.animations, + ...featureBundle.gestureAnimations, +}; + +/** + * @public + */ +const domMax = { + ...domAnimation, + ...featureBundle.drag, + ...featureBundle.layout, +}; + +/** + * @public + */ +const domMin = { + renderer: featureBundle.createDomVisualElement, + ...featureBundle.animations, +}; + +function useMotionValueEvent(value, event, callback) { + /** + * useInsertionEffect will create subscriptions before any other + * effects will run. Effects run upwards through the tree so it + * can be that binding a useLayoutEffect higher up the tree can + * miss changes from lower down the tree. + */ + React.useInsertionEffect(() => value.on(event, callback), [value, event, callback]); +} + +const createScrollMotionValues = () => ({ + scrollX: motionDom.motionValue(0), + scrollY: motionDom.motionValue(0), + scrollXProgress: motionDom.motionValue(0), + scrollYProgress: motionDom.motionValue(0), +}); +const isRefPending = (ref) => { + if (!ref) + return false; + return !ref.current; +}; +function useScroll({ container, target, ...options } = {}) { + const values = featureBundle.useConstant(createScrollMotionValues); + const scrollAnimation = React.useRef(null); + const needsStart = React.useRef(false); + const start = React.useCallback(() => { + scrollAnimation.current = scroll((_progress, { x, y, }) => { + values.scrollX.set(x.current); + values.scrollXProgress.set(x.progress); + values.scrollY.set(y.current); + values.scrollYProgress.set(y.progress); + }, { + ...options, + container: container?.current || undefined, + target: target?.current || undefined, + }); + return () => { + scrollAnimation.current?.(); + }; + }, [container, target, JSON.stringify(options.offset)]); + featureBundle.useIsomorphicLayoutEffect(() => { + needsStart.current = false; + if (isRefPending(container) || isRefPending(target)) { + needsStart.current = true; + return; + } + else { + return start(); + } + }, [start]); + React.useEffect(() => { + if (needsStart.current) { + motionUtils.invariant(!isRefPending(container), "Container ref is defined but not hydrated", "use-scroll-ref"); + motionUtils.invariant(!isRefPending(target), "Target ref is defined but not hydrated", "use-scroll-ref"); + return start(); + } + else { + return; + } + }, [start]); + return values; +} + +/** + * @deprecated useElementScroll is deprecated. Convert to useScroll({ container: ref }) + */ +function useElementScroll(ref) { + if (process.env.NODE_ENV === "development") { + motionUtils.warnOnce(false, "useElementScroll is deprecated. Convert to useScroll({ container: ref })."); + } + return useScroll({ container: ref }); +} + +/** + * @deprecated useViewportScroll is deprecated. Convert to useScroll() + */ +function useViewportScroll() { + if (process.env.NODE_ENV !== "production") { + motionUtils.warnOnce(false, "useViewportScroll is deprecated. Convert to useScroll()."); + } + return useScroll(); +} + +/** + * Combine multiple motion values into a new one using a string template literal. + * + * ```jsx + * import { + * motion, + * useSpring, + * useMotionValue, + * useMotionTemplate + * } from "framer-motion" + * + * function Component() { + * const shadowX = useSpring(0) + * const shadowY = useMotionValue(0) + * const shadow = useMotionTemplate`drop-shadow(${shadowX}px ${shadowY}px 20px rgba(0,0,0,0.3))` + * + * return + * } + * ``` + * + * @public + */ +function useMotionTemplate(fragments, ...values) { + /** + * Create a function that will build a string from the latest motion values. + */ + const numFragments = fragments.length; + function buildValue() { + let output = ``; + for (let i = 0; i < numFragments; i++) { + output += fragments[i]; + const value = values[i]; + if (value) { + output += motionDom.isMotionValue(value) ? value.get() : value; + } + } + return output; + } + return useCombineMotionValues(values.filter(motionDom.isMotionValue), buildValue); +} + +function useSpring(source, options = {}) { + const { isStatic } = React.useContext(featureBundle.MotionConfigContext); + const getFromSource = () => (motionDom.isMotionValue(source) ? source.get() : source); + // isStatic will never change, allowing early hooks return + if (isStatic) { + return useTransform(getFromSource); + } + const value = useMotionValue(getFromSource()); + React.useInsertionEffect(() => { + return motionDom.attachSpring(value, source, options); + }, [value, JSON.stringify(options)]); + return value; +} + +function useAnimationFrame(callback) { + const initialTimestamp = React.useRef(0); + const { isStatic } = React.useContext(featureBundle.MotionConfigContext); + React.useEffect(() => { + if (isStatic) + return; + const provideTimeSinceStart = ({ timestamp, delta }) => { + if (!initialTimestamp.current) + initialTimestamp.current = timestamp; + callback(timestamp - initialTimestamp.current, delta); + }; + motionDom.frame.update(provideTimeSinceStart, true); + return () => motionDom.cancelFrame(provideTimeSinceStart); + }, [callback]); +} + +function useTime() { + const time = useMotionValue(0); + useAnimationFrame((t) => time.set(t)); + return time; +} + +/** + * Creates a `MotionValue` that updates when the velocity of the provided `MotionValue` changes. + * + * ```javascript + * const x = useMotionValue(0) + * const xVelocity = useVelocity(x) + * const xAcceleration = useVelocity(xVelocity) + * ``` + * + * @public + */ +function useVelocity(value) { + const velocity = useMotionValue(value.getVelocity()); + const updateVelocity = () => { + const latest = value.getVelocity(); + velocity.set(latest); + /** + * If we still have velocity, schedule an update for the next frame + * to keep checking until it is zero. + */ + if (latest) + motionDom.frame.update(updateVelocity); + }; + useMotionValueEvent(value, "change", () => { + // Schedule an update to this value at the end of the current frame. + motionDom.frame.update(updateVelocity, false, true); + }); + return velocity; +} + +class WillChangeMotionValue extends motionDom.MotionValue { + constructor() { + super(...arguments); + this.isEnabled = false; + } + add(name) { + if (motionDom.transformProps.has(name) || motionDom.acceleratedValues.has(name)) { + this.isEnabled = true; + this.update(); + } + } + update() { + this.set(this.isEnabled ? "transform" : "auto"); + } +} + +function useWillChange() { + return featureBundle.useConstant(() => new WillChangeMotionValue("auto")); +} + +/** + * A hook that returns `true` if we should be using reduced motion based on the current device's Reduced Motion setting. + * + * This can be used to implement changes to your UI based on Reduced Motion. For instance, replacing motion-sickness inducing + * `x`/`y` animations with `opacity`, disabling the autoplay of background videos, or turning off parallax motion. + * + * It will actively respond to changes and re-render your components with the latest setting. + * + * ```jsx + * export function Sidebar({ isOpen }) { + * const shouldReduceMotion = useReducedMotion() + * const closedX = shouldReduceMotion ? 0 : "-100%" + * + * return ( + * + * ) + * } + * ``` + * + * @return boolean + * + * @public + */ +function useReducedMotion() { + /** + * Lazy initialisation of prefersReducedMotion + */ + !featureBundle.hasReducedMotionListener.current && featureBundle.initPrefersReducedMotion(); + const [shouldReduceMotion] = React.useState(featureBundle.prefersReducedMotion.current); + if (process.env.NODE_ENV !== "production") { + motionUtils.warnOnce(shouldReduceMotion !== true, "You have Reduced Motion enabled on your device. Animations may not appear as expected.", "reduced-motion-disabled"); + } + /** + * TODO See if people miss automatically updating shouldReduceMotion setting + */ + return shouldReduceMotion; +} + +function useReducedMotionConfig() { + const reducedMotionPreference = useReducedMotion(); + const { reducedMotion } = React.useContext(featureBundle.MotionConfigContext); + if (reducedMotion === "never") { + return false; + } + else if (reducedMotion === "always") { + return true; + } + else { + return reducedMotionPreference; + } +} + +function stopAnimation(visualElement) { + visualElement.values.forEach((value) => value.stop()); +} +function setVariants(visualElement, variantLabels) { + const reversedLabels = [...variantLabels].reverse(); + reversedLabels.forEach((key) => { + const variant = visualElement.getVariant(key); + variant && featureBundle.setTarget(visualElement, variant); + if (visualElement.variantChildren) { + visualElement.variantChildren.forEach((child) => { + setVariants(child, variantLabels); + }); + } + }); +} +function setValues(visualElement, definition) { + if (Array.isArray(definition)) { + return setVariants(visualElement, definition); + } + else if (typeof definition === "string") { + return setVariants(visualElement, [definition]); + } + else { + featureBundle.setTarget(visualElement, definition); + } +} +/** + * @public + */ +function animationControls() { + /** + * Track whether the host component has mounted. + */ + let hasMounted = false; + /** + * A collection of linked component animation controls. + */ + const subscribers = new Set(); + const controls = { + subscribe(visualElement) { + subscribers.add(visualElement); + return () => void subscribers.delete(visualElement); + }, + start(definition, transitionOverride) { + motionUtils.invariant(hasMounted, "controls.start() should only be called after a component has mounted. Consider calling within a useEffect hook."); + const animations = []; + subscribers.forEach((visualElement) => { + animations.push(featureBundle.animateVisualElement(visualElement, definition, { + transitionOverride, + })); + }); + return Promise.all(animations); + }, + set(definition) { + motionUtils.invariant(hasMounted, "controls.set() should only be called after a component has mounted. Consider calling within a useEffect hook."); + return subscribers.forEach((visualElement) => { + setValues(visualElement, definition); + }); + }, + stop() { + subscribers.forEach((visualElement) => { + stopAnimation(visualElement); + }); + }, + mount() { + hasMounted = true; + return () => { + hasMounted = false; + controls.stop(); + }; + }, + }; + return controls; +} + +function useAnimate() { + const scope = featureBundle.useConstant(() => ({ + current: null, // Will be hydrated by React + animations: [], + })); + const animate = featureBundle.useConstant(() => createScopedAnimate(scope)); + useUnmountEffect(() => { + scope.animations.forEach((animation) => animation.stop()); + scope.animations.length = 0; + }); + return [scope, animate]; +} + +function useAnimateMini() { + const scope = featureBundle.useConstant(() => ({ + current: null, // Will be hydrated by React + animations: [], + })); + const animate = featureBundle.useConstant(() => createScopedWaapiAnimate(scope)); + useUnmountEffect(() => { + scope.animations.forEach((animation) => animation.stop()); + }); + return [scope, animate]; +} + +/** + * Creates `LegacyAnimationControls`, which can be used to manually start, stop + * and sequence animations on one or more components. + * + * The returned `LegacyAnimationControls` should be passed to the `animate` property + * of the components you want to animate. + * + * These components can then be animated with the `start` method. + * + * ```jsx + * import * as React from 'react' + * import { motion, useAnimation } from 'framer-motion' + * + * export function MyComponent(props) { + * const controls = useAnimation() + * + * controls.start({ + * x: 100, + * transition: { duration: 0.5 }, + * }) + * + * return + * } + * ``` + * + * @returns Animation controller with `start` and `stop` methods + * + * @public + */ +function useAnimationControls() { + const controls = featureBundle.useConstant(animationControls); + featureBundle.useIsomorphicLayoutEffect(controls.mount, []); + return controls; +} +const useAnimation = useAnimationControls; + +function usePresenceData() { + const context = React.useContext(featureBundle.PresenceContext); + return context ? context.custom : undefined; +} + +/** + * Attaches an event listener directly to the provided DOM element. + * + * Bypassing React's event system can be desirable, for instance when attaching non-passive + * event handlers. + * + * ```jsx + * const ref = useRef(null) + * + * useDomEvent(ref, 'wheel', onWheel, { passive: false }) + * + * return
+ * ``` + * + * @param ref - React.RefObject that's been provided to the element you want to bind the listener to. + * @param eventName - Name of the event you want listen for. + * @param handler - Function to fire when receiving the event. + * @param options - Options to pass to `Event.addEventListener`. + * + * @public + */ +function useDomEvent(ref, eventName, handler, options) { + React.useEffect(() => { + const element = ref.current; + if (handler && element) { + return featureBundle.addDomEvent(element, eventName, handler, options); + } + }, [ref, eventName, handler, options]); +} + +/** + * Can manually trigger a drag gesture on one or more `drag`-enabled `motion` components. + * + * ```jsx + * const dragControls = useDragControls() + * + * function startDrag(event) { + * dragControls.start(event, { snapToCursor: true }) + * } + * + * return ( + * <> + *
+ * + * + * ) + * ``` + * + * @public + */ +class DragControls { + constructor() { + this.componentControls = new Set(); + } + /** + * Subscribe a component's internal `VisualElementDragControls` to the user-facing API. + * + * @internal + */ + subscribe(controls) { + this.componentControls.add(controls); + return () => this.componentControls.delete(controls); + } + /** + * Start a drag gesture on every `motion` component that has this set of drag controls + * passed into it via the `dragControls` prop. + * + * ```jsx + * dragControls.start(e, { + * snapToCursor: true + * }) + * ``` + * + * @param event - PointerEvent + * @param options - Options + * + * @public + */ + start(event, options) { + this.componentControls.forEach((controls) => { + controls.start(event.nativeEvent || event, options); + }); + } + /** + * Cancels a drag gesture. + * + * ```jsx + * dragControls.cancel() + * ``` + * + * @public + */ + cancel() { + this.componentControls.forEach((controls) => { + controls.cancel(); + }); + } + /** + * Stops a drag gesture. + * + * ```jsx + * dragControls.stop() + * ``` + * + * @public + */ + stop() { + this.componentControls.forEach((controls) => { + controls.stop(); + }); + } +} +const createDragControls = () => new DragControls(); +/** + * Usually, dragging is initiated by pressing down on a `motion` component with a `drag` prop + * and moving it. For some use-cases, for instance clicking at an arbitrary point on a video scrubber, we + * might want to initiate that dragging from a different component than the draggable one. + * + * By creating a `dragControls` using the `useDragControls` hook, we can pass this into + * the draggable component's `dragControls` prop. It exposes a `start` method + * that can start dragging from pointer events on other components. + * + * ```jsx + * const dragControls = useDragControls() + * + * function startDrag(event) { + * dragControls.start(event, { snapToCursor: true }) + * } + * + * return ( + * <> + *
+ * + * + * ) + * ``` + * + * @public + */ +function useDragControls() { + return featureBundle.useConstant(createDragControls); +} + +/** + * Checks if a component is a `motion` component. + */ +function isMotionComponent(component) { + return (component !== null && + typeof component === "object" && + featureBundle.motionComponentSymbol in component); +} + +/** + * Unwraps a `motion` component and returns either a string for `motion.div` or + * the React component for `motion(Component)`. + * + * If the component is not a `motion` component it returns undefined. + */ +function unwrapMotionComponent(component) { + if (isMotionComponent(component)) { + return component[featureBundle.motionComponentSymbol]; + } + return undefined; +} + +function useInstantLayoutTransition() { + return startTransition; +} +function startTransition(callback) { + if (!featureBundle.rootProjectionNode.current) + return; + featureBundle.rootProjectionNode.current.isUpdating = false; + featureBundle.rootProjectionNode.current.blockUpdate(); + callback && callback(); +} + +function useResetProjection() { + const reset = React.useCallback(() => { + const root = featureBundle.rootProjectionNode.current; + if (!root) + return; + root.resetTree(); + }, []); + return reset; +} + +/** + * Cycles through a series of visual properties. Can be used to toggle between or cycle through animations. It works similar to `useState` in React. It is provided an initial array of possible states, and returns an array of two arguments. + * + * An index value can be passed to the returned `cycle` function to cycle to a specific index. + * + * ```jsx + * import * as React from "react" + * import { motion, useCycle } from "framer-motion" + * + * export const MyComponent = () => { + * const [x, cycleX] = useCycle(0, 50, 100) + * + * return ( + * cycleX()} + * /> + * ) + * } + * ``` + * + * @param items - items to cycle through + * @returns [currentState, cycleState] + * + * @public + */ +function useCycle(...items) { + const index = React.useRef(0); + const [item, setItem] = React.useState(items[index.current]); + const runCycle = React.useCallback((next) => { + index.current = + typeof next !== "number" + ? motionUtils.wrap(0, items.length, index.current + 1) + : next; + setItem(items[index.current]); + }, + // The array will change on each call, but by putting items.length at + // the front of this array, we guarantee the dependency comparison will match up + // eslint-disable-next-line react-hooks/exhaustive-deps + [items.length, ...items]); + return [item, runCycle]; +} + +function useInView(ref, { root, margin, amount, once = false, initial = false, } = {}) { + const [isInView, setInView] = React.useState(initial); + React.useEffect(() => { + if (!ref.current || (once && isInView)) + return; + const onEnter = () => { + setInView(true); + return once ? undefined : () => setInView(false); + }; + const options = { + root: (root && root.current) || undefined, + margin, + amount, + }; + return inView(ref.current, onEnter, options); + }, [root, ref, margin, once, amount]); + return isInView; +} + +function useInstantTransition() { + const [forceUpdate, forcedRenderCount] = useForceUpdate(); + const startInstantLayoutTransition = useInstantLayoutTransition(); + const unlockOnFrameRef = React.useRef(-1); + React.useEffect(() => { + /** + * Unblock after two animation frames, otherwise this will unblock too soon. + */ + motionDom.frame.postRender(() => motionDom.frame.postRender(() => { + /** + * If the callback has been called again after the effect + * triggered this 2 frame delay, don't unblock animations. This + * prevents the previous effect from unblocking the current + * instant transition too soon. This becomes more likely when + * used in conjunction with React.startTransition(). + */ + if (forcedRenderCount !== unlockOnFrameRef.current) + return; + motionUtils.MotionGlobalConfig.instantAnimations = false; + })); + }, [forcedRenderCount]); + return (callback) => { + startInstantLayoutTransition(() => { + motionUtils.MotionGlobalConfig.instantAnimations = true; + forceUpdate(); + callback(); + unlockOnFrameRef.current = forcedRenderCount + 1; + }); + }; +} +function disableInstantTransitions() { + motionUtils.MotionGlobalConfig.instantAnimations = false; +} + +function usePageInView() { + const [isInView, setIsInView] = React.useState(true); + React.useEffect(() => { + const handleVisibilityChange = () => setIsInView(!document.hidden); + if (document.hidden) { + handleVisibilityChange(); + } + document.addEventListener("visibilitychange", handleVisibilityChange); + return () => { + document.removeEventListener("visibilitychange", handleVisibilityChange); + }; + }, []); + return isInView; +} + +const appearAnimationStore = new Map(); +const appearComplete = new Map(); + +const appearStoreId = (elementId, valueName) => { + const key = motionDom.transformProps.has(valueName) ? "transform" : valueName; + return `${elementId}: ${key}`; +}; + +function handoffOptimizedAppearAnimation(elementId, valueName, frame) { + const storeId = appearStoreId(elementId, valueName); + const optimisedAnimation = appearAnimationStore.get(storeId); + if (!optimisedAnimation) { + return null; + } + const { animation, startTime } = optimisedAnimation; + function cancelAnimation() { + window.MotionCancelOptimisedAnimation?.(elementId, valueName, frame); + } + /** + * We can cancel the animation once it's finished now that we've synced + * with Motion. + * + * Prefer onfinish over finished as onfinish is backwards compatible with + * older browsers. + */ + animation.onfinish = cancelAnimation; + if (startTime === null || window.MotionHandoffIsComplete?.(elementId)) { + /** + * If the startTime is null, this animation is the Paint Ready detection animation + * and we can cancel it immediately without handoff. + * + * Or if we've already handed off the animation then we're now interrupting it. + * In which case we need to cancel it. + */ + cancelAnimation(); + return null; + } + else { + return startTime; + } +} + +/** + * A single time to use across all animations to manually set startTime + * and ensure they're all in sync. + */ +let startFrameTime; +/** + * A dummy animation to detect when Chrome is ready to start + * painting the page and hold off from triggering the real animation + * until then. We only need one animation to detect paint ready. + * + * https://bugs.chromium.org/p/chromium/issues/detail?id=1406850 + */ +let readyAnimation; +/** + * Keep track of animations that were suspended vs cancelled so we + * can easily resume them when we're done measuring layout. + */ +const suspendedAnimations = new Set(); +function resumeSuspendedAnimations() { + suspendedAnimations.forEach((data) => { + data.animation.play(); + data.animation.startTime = data.startTime; + }); + suspendedAnimations.clear(); +} +function startOptimizedAppearAnimation(element, name, keyframes, options, onReady) { + // Prevent optimised appear animations if Motion has already started animating. + if (window.MotionIsMounted) { + return; + } + const id = element.dataset[featureBundle.optimizedAppearDataId]; + if (!id) + return; + window.MotionHandoffAnimation = handoffOptimizedAppearAnimation; + const storeId = appearStoreId(id, name); + if (!readyAnimation) { + readyAnimation = motionDom.startWaapiAnimation(element, name, [keyframes[0], keyframes[0]], + /** + * 10 secs is basically just a super-safe duration to give Chrome + * long enough to get the animation ready. + */ + { duration: 10000, ease: "linear" }); + appearAnimationStore.set(storeId, { + animation: readyAnimation, + startTime: null, + }); + /** + * If there's no readyAnimation then there's been no instantiation + * of handoff animations. + */ + window.MotionHandoffAnimation = handoffOptimizedAppearAnimation; + window.MotionHasOptimisedAnimation = (elementId, valueName) => { + if (!elementId) + return false; + /** + * Keep a map of elementIds that have started animating. We check + * via ID instead of Element because of hydration errors and + * pre-hydration checks. We also actively record IDs as they start + * animating rather than simply checking for data-appear-id as + * this attrbute might be present but not lead to an animation, for + * instance if the element's appear animation is on a different + * breakpoint. + */ + if (!valueName) { + return appearComplete.has(elementId); + } + const animationId = appearStoreId(elementId, valueName); + return Boolean(appearAnimationStore.get(animationId)); + }; + window.MotionHandoffMarkAsComplete = (elementId) => { + if (appearComplete.has(elementId)) { + appearComplete.set(elementId, true); + } + }; + window.MotionHandoffIsComplete = (elementId) => { + return appearComplete.get(elementId) === true; + }; + /** + * We only need to cancel transform animations as + * they're the ones that will interfere with the + * layout animation measurements. + */ + window.MotionCancelOptimisedAnimation = (elementId, valueName, frame, canResume) => { + const animationId = appearStoreId(elementId, valueName); + const data = appearAnimationStore.get(animationId); + if (!data) + return; + if (frame && canResume === undefined) { + /** + * Wait until the end of the subsequent frame to cancel the animation + * to ensure we don't remove the animation before the main thread has + * had a chance to resolve keyframes and render. + */ + frame.postRender(() => { + frame.postRender(() => { + data.animation.cancel(); + }); + }); + } + else { + data.animation.cancel(); + } + if (frame && canResume) { + suspendedAnimations.add(data); + frame.render(resumeSuspendedAnimations); + } + else { + appearAnimationStore.delete(animationId); + /** + * If there are no more animations left, we can remove the cancel function. + * This will let us know when we can stop checking for conflicting layout animations. + */ + if (!appearAnimationStore.size) { + window.MotionCancelOptimisedAnimation = undefined; + } + } + }; + window.MotionCheckAppearSync = (visualElement, valueName, value) => { + const appearId = featureBundle.getOptimisedAppearId(visualElement); + if (!appearId) + return; + const valueIsOptimised = window.MotionHasOptimisedAnimation?.(appearId, valueName); + const externalAnimationValue = visualElement.props.values?.[valueName]; + if (!valueIsOptimised || !externalAnimationValue) + return; + const removeSyncCheck = value.on("change", (latestValue) => { + if (externalAnimationValue.get() !== latestValue) { + window.MotionCancelOptimisedAnimation?.(appearId, valueName); + removeSyncCheck(); + } + }); + return removeSyncCheck; + }; + } + const startAnimation = () => { + readyAnimation.cancel(); + const appearAnimation = motionDom.startWaapiAnimation(element, name, keyframes, options); + /** + * Record the time of the first started animation. We call performance.now() once + * here and once in handoff to ensure we're getting + * close to a frame-locked time. This keeps all animations in sync. + */ + if (startFrameTime === undefined) { + startFrameTime = performance.now(); + } + appearAnimation.startTime = startFrameTime; + appearAnimationStore.set(storeId, { + animation: appearAnimation, + startTime: startFrameTime, + }); + if (onReady) + onReady(appearAnimation); + }; + appearComplete.set(id, false); + if (readyAnimation.ready) { + readyAnimation.ready.then(startAnimation).catch(motionUtils.noop); + } + else { + startAnimation(); + } +} + +const createObject = () => ({}); +class StateVisualElement extends featureBundle.VisualElement { + constructor() { + super(...arguments); + this.measureInstanceViewportBox = featureBundle.createBox; + } + build() { } + resetTransform() { } + restoreTransform() { } + removeValueFromRenderState() { } + renderInstance() { } + scrapeMotionValuesFromProps() { + return createObject(); + } + getBaseTargetFromProps() { + return undefined; + } + readValueFromInstance(_state, key, options) { + return options.initialState[key] || 0; + } + sortInstanceNodePosition() { + return 0; + } +} +const useVisualState = featureBundle.makeUseVisualState({ + scrapeMotionValuesFromProps: createObject, + createRenderState: createObject, +}); +/** + * This is not an officially supported API and may be removed + * on any version. + */ +function useAnimatedState(initialState) { + const [animationState, setAnimationState] = React.useState(initialState); + const visualState = useVisualState({}, false); + const element = featureBundle.useConstant(() => { + return new StateVisualElement({ + props: { + onUpdate: (v) => { + setAnimationState({ ...v }); + }, + }, + visualState, + presenceContext: null, + }, { initialState }); + }); + React.useLayoutEffect(() => { + element.mount({}); + return () => element.unmount(); + }, [element]); + const startAnimation = featureBundle.useConstant(() => (animationDefinition) => { + return featureBundle.animateVisualElement(element, animationDefinition); + }); + return [animationState, startAnimation]; +} + +let id = 0; +const AnimateSharedLayout = ({ children }) => { + React__namespace.useEffect(() => { + motionUtils.invariant(false, "AnimateSharedLayout is deprecated: https://www.framer.com/docs/guide-upgrade/##shared-layout-animations"); + }, []); + return (jsxRuntime.jsx(LayoutGroup, { id: featureBundle.useConstant(() => `asl-${id++}`), children: children })); +}; + +// Keep things reasonable and avoid scale: Infinity. In practise we might need +// to add another value, opacity, that could interpolate scaleX/Y [0,0.01] => [0,1] +// to simply hide content at unreasonable scales. +const maxScale = 100000; +const invertScale = (scale) => scale > 0.001 ? 1 / scale : maxScale; +let hasWarned = false; +/** + * Returns a `MotionValue` each for `scaleX` and `scaleY` that update with the inverse + * of their respective parent scales. + * + * This is useful for undoing the distortion of content when scaling a parent component. + * + * By default, `useInvertedScale` will automatically fetch `scaleX` and `scaleY` from the nearest parent. + * By passing other `MotionValue`s in as `useInvertedScale({ scaleX, scaleY })`, it will invert the output + * of those instead. + * + * ```jsx + * const MyComponent = () => { + * const { scaleX, scaleY } = useInvertedScale() + * return + * } + * ``` + * + * @deprecated + */ +function useInvertedScale(scale) { + let parentScaleX = useMotionValue(1); + let parentScaleY = useMotionValue(1); + const { visualElement } = React.useContext(featureBundle.MotionContext); + motionUtils.invariant(!!(scale || visualElement), "If no scale values are provided, useInvertedScale must be used within a child of another motion component."); + motionUtils.warning(hasWarned, "useInvertedScale is deprecated and will be removed in 3.0. Use the layout prop instead."); + hasWarned = true; + if (scale) { + parentScaleX = scale.scaleX || parentScaleX; + parentScaleY = scale.scaleY || parentScaleY; + } + else if (visualElement) { + parentScaleX = visualElement.getValue("scaleX", 1); + parentScaleY = visualElement.getValue("scaleY", 1); + } + const scaleX = useTransform(parentScaleX, invertScale); + const scaleY = useTransform(parentScaleY, invertScale); + return { scaleX, scaleY }; +} + +exports.FlatTree = featureBundle.FlatTree; +exports.LayoutGroupContext = featureBundle.LayoutGroupContext; +exports.MotionConfigContext = featureBundle.MotionConfigContext; +exports.MotionContext = featureBundle.MotionContext; +exports.PresenceContext = featureBundle.PresenceContext; +exports.SwitchLayoutGroupContext = featureBundle.SwitchLayoutGroupContext; +exports.VisualElement = featureBundle.VisualElement; +exports.addPointerEvent = featureBundle.addPointerEvent; +exports.addPointerInfo = featureBundle.addPointerInfo; +exports.addScaleCorrector = featureBundle.addScaleCorrector; +exports.animateVisualElement = featureBundle.animateVisualElement; +exports.animations = featureBundle.animations; +exports.buildTransform = featureBundle.buildTransform; +exports.calcLength = featureBundle.calcLength; +exports.createBox = featureBundle.createBox; +exports.delay = featureBundle.delay; +exports.distance = featureBundle.distance; +exports.distance2D = featureBundle.distance2D; +exports.filterProps = featureBundle.filterProps; +exports.isBrowser = featureBundle.isBrowser; +exports.isValidMotionProp = featureBundle.isValidMotionProp; +exports.makeUseVisualState = featureBundle.makeUseVisualState; +exports.optimizedAppearDataAttribute = featureBundle.optimizedAppearDataAttribute; +exports.resolveMotionValue = featureBundle.resolveMotionValue; +exports.useIsPresent = featureBundle.useIsPresent; +exports.useIsomorphicLayoutEffect = featureBundle.useIsomorphicLayoutEffect; +exports.usePresence = featureBundle.usePresence; +exports.visualElementStore = featureBundle.visualElementStore; +Object.defineProperty(exports, "MotionGlobalConfig", { + enumerable: true, + get: function () { return motionUtils.MotionGlobalConfig; } +}); +exports.AnimatePresence = AnimatePresence; +exports.AnimateSharedLayout = AnimateSharedLayout; +exports.DeprecatedLayoutGroupContext = DeprecatedLayoutGroupContext; +exports.DragControls = DragControls; +exports.LayoutGroup = LayoutGroup; +exports.LazyMotion = LazyMotion; +exports.MotionConfig = MotionConfig; +exports.Reorder = namespace; +exports.WillChangeMotionValue = WillChangeMotionValue; +exports.animate = animate; +exports.animateMini = animateMini; +exports.animationControls = animationControls; +exports.createScopedAnimate = createScopedAnimate; +exports.disableInstantTransitions = disableInstantTransitions; +exports.domAnimation = domAnimation; +exports.domMax = domMax; +exports.domMin = domMin; +exports.inView = inView; +exports.isMotionComponent = isMotionComponent; +exports.m = m; +exports.motion = motion; +exports.scroll = scroll; +exports.scrollInfo = scrollInfo; +exports.startOptimizedAppearAnimation = startOptimizedAppearAnimation; +exports.unwrapMotionComponent = unwrapMotionComponent; +exports.useAnimate = useAnimate; +exports.useAnimateMini = useAnimateMini; +exports.useAnimation = useAnimation; +exports.useAnimationControls = useAnimationControls; +exports.useAnimationFrame = useAnimationFrame; +exports.useCycle = useCycle; +exports.useDeprecatedAnimatedState = useAnimatedState; +exports.useDeprecatedInvertedScale = useInvertedScale; +exports.useDomEvent = useDomEvent; +exports.useDragControls = useDragControls; +exports.useElementScroll = useElementScroll; +exports.useForceUpdate = useForceUpdate; +exports.useInView = useInView; +exports.useInstantLayoutTransition = useInstantLayoutTransition; +exports.useInstantTransition = useInstantTransition; +exports.useMotionTemplate = useMotionTemplate; +exports.useMotionValue = useMotionValue; +exports.useMotionValueEvent = useMotionValueEvent; +exports.usePageInView = usePageInView; +exports.usePresenceData = usePresenceData; +exports.useReducedMotion = useReducedMotion; +exports.useReducedMotionConfig = useReducedMotionConfig; +exports.useResetProjection = useResetProjection; +exports.useScroll = useScroll; +exports.useSpring = useSpring; +exports.useTime = useTime; +exports.useTransform = useTransform; +exports.useUnmountEffect = useUnmountEffect; +exports.useVelocity = useVelocity; +exports.useViewportScroll = useViewportScroll; +exports.useWillChange = useWillChange; +Object.keys(motionDom).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return motionDom[k]; } + }); +}); +Object.keys(motionUtils).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return motionUtils[k]; } + }); +}); diff --git a/frontend/node_modules/framer-motion/dist/cjs/m.js b/frontend/node_modules/framer-motion/dist/cjs/m.js new file mode 100644 index 0000000000000000000000000000000000000000..19779d14a536ea1e638ea698035f3c51aa9626b9 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/cjs/m.js @@ -0,0 +1,1430 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var jsxRuntime = require('react/jsx-runtime'); +var motionUtils = require('motion-utils'); +var react = require('react'); +var motionDom = require('motion-dom'); + +const LayoutGroupContext = react.createContext({}); + +const LazyContext = react.createContext({ strict: false }); + +/** + * @public + */ +const MotionConfigContext = react.createContext({ + transformPagePoint: (p) => p, + isStatic: false, + reducedMotion: "never", +}); + +const MotionContext = /* @__PURE__ */ react.createContext({}); + +function isAnimationControls(v) { + return (v !== null && + typeof v === "object" && + typeof v.start === "function"); +} + +/** + * Decides if the supplied variable is variant label + */ +function isVariantLabel(v) { + return typeof v === "string" || Array.isArray(v); +} + +const variantPriorityOrder = [ + "animate", + "whileInView", + "whileFocus", + "whileHover", + "whileTap", + "whileDrag", + "exit", +]; +const variantProps = ["initial", ...variantPriorityOrder]; + +function isControllingVariants(props) { + return (isAnimationControls(props.animate) || + variantProps.some((name) => isVariantLabel(props[name]))); +} +function isVariantNode(props) { + return Boolean(isControllingVariants(props) || props.variants); +} + +function getCurrentTreeVariants(props, context) { + if (isControllingVariants(props)) { + const { initial, animate } = props; + return { + initial: initial === false || isVariantLabel(initial) + ? initial + : undefined, + animate: isVariantLabel(animate) ? animate : undefined, + }; + } + return props.inherit !== false ? context : {}; +} + +function useCreateMotionContext(props) { + const { initial, animate } = getCurrentTreeVariants(props, react.useContext(MotionContext)); + return react.useMemo(() => ({ initial, animate }), [variantLabelsAsDependency(initial), variantLabelsAsDependency(animate)]); +} +function variantLabelsAsDependency(prop) { + return Array.isArray(prop) ? prop.join(" ") : prop; +} + +const scaleCorrectors = {}; + +function isForcedMotionValue(key, { layout, layoutId }) { + return (motionDom.transformProps.has(key) || + key.startsWith("origin") || + ((layout || layoutId !== undefined) && + (!!scaleCorrectors[key] || key === "opacity"))); +} + +const translateAlias = { + x: "translateX", + y: "translateY", + z: "translateZ", + transformPerspective: "perspective", +}; +const numTransforms = motionDom.transformPropOrder.length; +/** + * Build a CSS transform style from individual x/y/scale etc properties. + * + * This outputs with a default order of transforms/scales/rotations, this can be customised by + * providing a transformTemplate function. + */ +function buildTransform(latestValues, transform, transformTemplate) { + // The transform string we're going to build into. + let transformString = ""; + let transformIsDefault = true; + /** + * Loop over all possible transforms in order, adding the ones that + * are present to the transform string. + */ + for (let i = 0; i < numTransforms; i++) { + const key = motionDom.transformPropOrder[i]; + const value = latestValues[key]; + if (value === undefined) + continue; + let valueIsDefault = true; + if (typeof value === "number") { + valueIsDefault = value === (key.startsWith("scale") ? 1 : 0); + } + else { + valueIsDefault = parseFloat(value) === 0; + } + if (!valueIsDefault || transformTemplate) { + const valueAsType = motionDom.getValueAsType(value, motionDom.numberValueTypes[key]); + if (!valueIsDefault) { + transformIsDefault = false; + const transformName = translateAlias[key] || key; + transformString += `${transformName}(${valueAsType}) `; + } + if (transformTemplate) { + transform[key] = valueAsType; + } + } + } + transformString = transformString.trim(); + // If we have a custom `transform` template, pass our transform values and + // generated transformString to that before returning + if (transformTemplate) { + transformString = transformTemplate(transform, transformIsDefault ? "" : transformString); + } + else if (transformIsDefault) { + transformString = "none"; + } + return transformString; +} + +function buildHTMLStyles(state, latestValues, transformTemplate) { + const { style, vars, transformOrigin } = state; + // Track whether we encounter any transform or transformOrigin values. + let hasTransform = false; + let hasTransformOrigin = false; + /** + * Loop over all our latest animated values and decide whether to handle them + * as a style or CSS variable. + * + * Transforms and transform origins are kept separately for further processing. + */ + for (const key in latestValues) { + const value = latestValues[key]; + if (motionDom.transformProps.has(key)) { + // If this is a transform, flag to enable further transform processing + hasTransform = true; + continue; + } + else if (motionDom.isCSSVariableName(key)) { + vars[key] = value; + continue; + } + else { + // Convert the value to its default value type, ie 0 -> "0px" + const valueAsType = motionDom.getValueAsType(value, motionDom.numberValueTypes[key]); + if (key.startsWith("origin")) { + // If this is a transform origin, flag and enable further transform-origin processing + hasTransformOrigin = true; + transformOrigin[key] = + valueAsType; + } + else { + style[key] = valueAsType; + } + } + } + if (!latestValues.transform) { + if (hasTransform || transformTemplate) { + style.transform = buildTransform(latestValues, state.transform, transformTemplate); + } + else if (style.transform) { + /** + * If we have previously created a transform but currently don't have any, + * reset transform style to none. + */ + style.transform = "none"; + } + } + /** + * Build a transformOrigin style. Uses the same defaults as the browser for + * undefined origins. + */ + if (hasTransformOrigin) { + const { originX = "50%", originY = "50%", originZ = 0, } = transformOrigin; + style.transformOrigin = `${originX} ${originY} ${originZ}`; + } +} + +const createHtmlRenderState = () => ({ + style: {}, + transform: {}, + transformOrigin: {}, + vars: {}, +}); + +function copyRawValuesOnly(target, source, props) { + for (const key in source) { + if (!motionDom.isMotionValue(source[key]) && !isForcedMotionValue(key, props)) { + target[key] = source[key]; + } + } +} +function useInitialMotionValues({ transformTemplate }, visualState) { + return react.useMemo(() => { + const state = createHtmlRenderState(); + buildHTMLStyles(state, visualState, transformTemplate); + return Object.assign({}, state.vars, state.style); + }, [visualState]); +} +function useStyle(props, visualState) { + const styleProp = props.style || {}; + const style = {}; + /** + * Copy non-Motion Values straight into style + */ + copyRawValuesOnly(style, styleProp, props); + Object.assign(style, useInitialMotionValues(props, visualState)); + return style; +} +function useHTMLProps(props, visualState) { + // The `any` isn't ideal but it is the type of createElement props argument + const htmlProps = {}; + const style = useStyle(props, visualState); + if (props.drag && props.dragListener !== false) { + // Disable the ghost element when a user drags + htmlProps.draggable = false; + // Disable text selection + style.userSelect = + style.WebkitUserSelect = + style.WebkitTouchCallout = + "none"; + // Disable scrolling on the draggable direction + style.touchAction = + props.drag === true + ? "none" + : `pan-${props.drag === "x" ? "y" : "x"}`; + } + if (props.tabIndex === undefined && + (props.onTap || props.onTapStart || props.whileTap)) { + htmlProps.tabIndex = 0; + } + htmlProps.style = style; + return htmlProps; +} + +const dashKeys = { + offset: "stroke-dashoffset", + array: "stroke-dasharray", +}; +const camelKeys = { + offset: "strokeDashoffset", + array: "strokeDasharray", +}; +/** + * Build SVG path properties. Uses the path's measured length to convert + * our custom pathLength, pathSpacing and pathOffset into stroke-dashoffset + * and stroke-dasharray attributes. + * + * This function is mutative to reduce per-frame GC. + */ +function buildSVGPath(attrs, length, spacing = 1, offset = 0, useDashCase = true) { + // Normalise path length by setting SVG attribute pathLength to 1 + attrs.pathLength = 1; + // We use dash case when setting attributes directly to the DOM node and camel case + // when defining props on a React component. + const keys = useDashCase ? dashKeys : camelKeys; + // Build the dash offset + attrs[keys.offset] = motionDom.px.transform(-offset); + // Build the dash array + const pathLength = motionDom.px.transform(length); + const pathSpacing = motionDom.px.transform(spacing); + attrs[keys.array] = `${pathLength} ${pathSpacing}`; +} + +/** + * Build SVG visual attributes, like cx and style.transform + */ +function buildSVGAttrs(state, { attrX, attrY, attrScale, pathLength, pathSpacing = 1, pathOffset = 0, +// This is object creation, which we try to avoid per-frame. +...latest }, isSVGTag, transformTemplate, styleProp) { + buildHTMLStyles(state, latest, transformTemplate); + /** + * For svg tags we just want to make sure viewBox is animatable and treat all the styles + * as normal HTML tags. + */ + if (isSVGTag) { + if (state.style.viewBox) { + state.attrs.viewBox = state.style.viewBox; + } + return; + } + state.attrs = state.style; + state.style = {}; + const { attrs, style } = state; + /** + * However, we apply transforms as CSS transforms. + * So if we detect a transform, transformOrigin we take it from attrs and copy it into style. + */ + if (attrs.transform) { + style.transform = attrs.transform; + delete attrs.transform; + } + if (style.transform || attrs.transformOrigin) { + style.transformOrigin = attrs.transformOrigin ?? "50% 50%"; + delete attrs.transformOrigin; + } + if (style.transform) { + /** + * SVG's element transform-origin uses its own median as a reference. + * Therefore, transformBox becomes a fill-box + */ + style.transformBox = styleProp?.transformBox ?? "fill-box"; + delete attrs.transformBox; + } + // Render attrX/attrY/attrScale as attributes + if (attrX !== undefined) + attrs.x = attrX; + if (attrY !== undefined) + attrs.y = attrY; + if (attrScale !== undefined) + attrs.scale = attrScale; + // Build SVG path if one has been defined + if (pathLength !== undefined) { + buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false); + } +} + +const createSvgRenderState = () => ({ + ...createHtmlRenderState(), + attrs: {}, +}); + +const isSVGTag = (tag) => typeof tag === "string" && tag.toLowerCase() === "svg"; + +function useSVGProps(props, visualState, _isStatic, Component) { + const visualProps = react.useMemo(() => { + const state = createSvgRenderState(); + buildSVGAttrs(state, visualState, isSVGTag(Component), props.transformTemplate, props.style); + return { + ...state.attrs, + style: { ...state.style }, + }; + }, [visualState]); + if (props.style) { + const rawStyles = {}; + copyRawValuesOnly(rawStyles, props.style, props); + visualProps.style = { ...rawStyles, ...visualProps.style }; + } + return visualProps; +} + +/** + * A list of all valid MotionProps. + * + * @privateRemarks + * This doesn't throw if a `MotionProp` name is missing - it should. + */ +const validMotionProps = new Set([ + "animate", + "exit", + "variants", + "initial", + "style", + "values", + "variants", + "transition", + "transformTemplate", + "custom", + "inherit", + "onBeforeLayoutMeasure", + "onAnimationStart", + "onAnimationComplete", + "onUpdate", + "onDragStart", + "onDrag", + "onDragEnd", + "onMeasureDragConstraints", + "onDirectionLock", + "onDragTransitionEnd", + "_dragX", + "_dragY", + "onHoverStart", + "onHoverEnd", + "onViewportEnter", + "onViewportLeave", + "globalTapTarget", + "ignoreStrict", + "viewport", +]); +/** + * Check whether a prop name is a valid `MotionProp` key. + * + * @param key - Name of the property to check + * @returns `true` is key is a valid `MotionProp`. + * + * @public + */ +function isValidMotionProp(key) { + return (key.startsWith("while") || + (key.startsWith("drag") && key !== "draggable") || + key.startsWith("layout") || + key.startsWith("onTap") || + key.startsWith("onPan") || + key.startsWith("onLayout") || + validMotionProps.has(key)); +} + +let shouldForward = (key) => !isValidMotionProp(key); +function loadExternalIsValidProp(isValidProp) { + if (typeof isValidProp !== "function") + return; + // Explicitly filter our events + shouldForward = (key) => key.startsWith("on") ? !isValidMotionProp(key) : isValidProp(key); +} +/** + * Emotion and Styled Components both allow users to pass through arbitrary props to their components + * to dynamically generate CSS. They both use the `@emotion/is-prop-valid` package to determine which + * of these should be passed to the underlying DOM node. + * + * However, when styling a Motion component `styled(motion.div)`, both packages pass through *all* props + * as it's seen as an arbitrary component rather than a DOM node. Motion only allows arbitrary props + * passed through the `custom` prop so it doesn't *need* the payload or computational overhead of + * `@emotion/is-prop-valid`, however to fix this problem we need to use it. + * + * By making it an optionalDependency we can offer this functionality only in the situations where it's + * actually required. + */ +try { + /** + * We attempt to import this package but require won't be defined in esm environments, in that case + * isPropValid will have to be provided via `MotionContext`. In a 6.0.0 this should probably be removed + * in favour of explicit injection. + */ + loadExternalIsValidProp(require("@emotion/is-prop-valid").default); +} +catch { + // We don't need to actually do anything here - the fallback is the existing `isPropValid`. +} +function filterProps(props, isDom, forwardMotionProps) { + const filteredProps = {}; + for (const key in props) { + /** + * values is considered a valid prop by Emotion, so if it's present + * this will be rendered out to the DOM unless explicitly filtered. + * + * We check the type as it could be used with the `feColorMatrix` + * element, which we support. + */ + if (key === "values" && typeof props.values === "object") + continue; + if (shouldForward(key) || + (forwardMotionProps === true && isValidMotionProp(key)) || + (!isDom && !isValidMotionProp(key)) || + // If trying to use native HTML drag events, forward drag listeners + (props["draggable"] && + key.startsWith("onDrag"))) { + filteredProps[key] = + props[key]; + } + } + return filteredProps; +} + +/** + * We keep these listed separately as we use the lowercase tag names as part + * of the runtime bundle to detect SVG components + */ +const lowercaseSVGElements = [ + "animate", + "circle", + "defs", + "desc", + "ellipse", + "g", + "image", + "line", + "filter", + "marker", + "mask", + "metadata", + "path", + "pattern", + "polygon", + "polyline", + "rect", + "stop", + "switch", + "symbol", + "svg", + "text", + "tspan", + "use", + "view", +]; + +function isSVGComponent(Component) { + if ( + /** + * If it's not a string, it's a custom React component. Currently we only support + * HTML custom React components. + */ + typeof Component !== "string" || + /** + * If it contains a dash, the element is a custom HTML webcomponent. + */ + Component.includes("-")) { + return false; + } + else if ( + /** + * If it's in our list of lowercase SVG tags, it's an SVG component + */ + lowercaseSVGElements.indexOf(Component) > -1 || + /** + * If it contains a capital letter, it's an SVG component + */ + /[A-Z]/u.test(Component)) { + return true; + } + return false; +} + +function useRender(Component, props, ref, { latestValues, }, isStatic, forwardMotionProps = false) { + const useVisualProps = isSVGComponent(Component) + ? useSVGProps + : useHTMLProps; + const visualProps = useVisualProps(props, latestValues, isStatic, Component); + const filteredProps = filterProps(props, typeof Component === "string", forwardMotionProps); + const elementProps = Component !== react.Fragment ? { ...filteredProps, ...visualProps, ref } : {}; + /** + * If component has been handed a motion value as its child, + * memoise its initial value and render that. Subsequent updates + * will be handled by the onChange handler + */ + const { children } = props; + const renderedChildren = react.useMemo(() => (motionDom.isMotionValue(children) ? children.get() : children), [children]); + return react.createElement(Component, { + ...elementProps, + children: renderedChildren, + }); +} + +/** + * @public + */ +const PresenceContext = +/* @__PURE__ */ react.createContext(null); + +function getValueState(visualElement) { + const state = [{}, {}]; + visualElement?.values.forEach((value, key) => { + state[0][key] = value.get(); + state[1][key] = value.getVelocity(); + }); + return state; +} +function resolveVariantFromProps(props, definition, custom, visualElement) { + /** + * If the variant definition is a function, resolve. + */ + if (typeof definition === "function") { + const [current, velocity] = getValueState(visualElement); + definition = definition(custom !== undefined ? custom : props.custom, current, velocity); + } + /** + * If the variant definition is a variant label, or + * the function returned a variant label, resolve. + */ + if (typeof definition === "string") { + definition = props.variants && props.variants[definition]; + } + /** + * At this point we've resolved both functions and variant labels, + * but the resolved variant label might itself have been a function. + * If so, resolve. This can only have returned a valid target object. + */ + if (typeof definition === "function") { + const [current, velocity] = getValueState(visualElement); + definition = definition(custom !== undefined ? custom : props.custom, current, velocity); + } + return definition; +} + +/** + * Creates a constant value over the lifecycle of a component. + * + * Even if `useMemo` is provided an empty array as its final argument, it doesn't offer + * a guarantee that it won't re-run for performance reasons later on. By using `useConstant` + * you can ensure that initialisers don't execute twice or more. + */ +function useConstant(init) { + const ref = react.useRef(null); + if (ref.current === null) { + ref.current = init(); + } + return ref.current; +} + +/** + * If the provided value is a MotionValue, this returns the actual value, otherwise just the value itself + * + * TODO: Remove and move to library + */ +function resolveMotionValue(value) { + return motionDom.isMotionValue(value) ? value.get() : value; +} + +function makeState({ scrapeMotionValuesFromProps, createRenderState, }, props, context, presenceContext) { + const state = { + latestValues: makeLatestValues(props, context, presenceContext, scrapeMotionValuesFromProps), + renderState: createRenderState(), + }; + return state; +} +function makeLatestValues(props, context, presenceContext, scrapeMotionValues) { + const values = {}; + const motionValues = scrapeMotionValues(props, {}); + for (const key in motionValues) { + values[key] = resolveMotionValue(motionValues[key]); + } + let { initial, animate } = props; + const isControllingVariants$1 = isControllingVariants(props); + const isVariantNode$1 = isVariantNode(props); + if (context && + isVariantNode$1 && + !isControllingVariants$1 && + props.inherit !== false) { + if (initial === undefined) + initial = context.initial; + if (animate === undefined) + animate = context.animate; + } + let isInitialAnimationBlocked = presenceContext + ? presenceContext.initial === false + : false; + isInitialAnimationBlocked = isInitialAnimationBlocked || initial === false; + const variantToSet = isInitialAnimationBlocked ? animate : initial; + if (variantToSet && + typeof variantToSet !== "boolean" && + !isAnimationControls(variantToSet)) { + const list = Array.isArray(variantToSet) ? variantToSet : [variantToSet]; + for (let i = 0; i < list.length; i++) { + const resolved = resolveVariantFromProps(props, list[i]); + if (resolved) { + const { transitionEnd, transition, ...target } = resolved; + for (const key in target) { + let valueTarget = target[key]; + if (Array.isArray(valueTarget)) { + /** + * Take final keyframe if the initial animation is blocked because + * we want to initialise at the end of that blocked animation. + */ + const index = isInitialAnimationBlocked + ? valueTarget.length - 1 + : 0; + valueTarget = valueTarget[index]; + } + if (valueTarget !== null) { + values[key] = valueTarget; + } + } + for (const key in transitionEnd) { + values[key] = transitionEnd[key]; + } + } + } + } + return values; +} +const makeUseVisualState = (config) => (props, isStatic) => { + const context = react.useContext(MotionContext); + const presenceContext = react.useContext(PresenceContext); + const make = () => makeState(config, props, context, presenceContext); + return isStatic ? make() : useConstant(make); +}; + +function scrapeMotionValuesFromProps$1(props, prevProps, visualElement) { + const { style } = props; + const newValues = {}; + for (const key in style) { + if (motionDom.isMotionValue(style[key]) || + (prevProps.style && + motionDom.isMotionValue(prevProps.style[key])) || + isForcedMotionValue(key, props) || + visualElement?.getValue(key)?.liveStyle !== undefined) { + newValues[key] = style[key]; + } + } + return newValues; +} + +const useHTMLVisualState = /*@__PURE__*/ makeUseVisualState({ + scrapeMotionValuesFromProps: scrapeMotionValuesFromProps$1, + createRenderState: createHtmlRenderState, +}); + +function scrapeMotionValuesFromProps(props, prevProps, visualElement) { + const newValues = scrapeMotionValuesFromProps$1(props, prevProps, visualElement); + for (const key in props) { + if (motionDom.isMotionValue(props[key]) || + motionDom.isMotionValue(prevProps[key])) { + const targetKey = motionDom.transformPropOrder.indexOf(key) !== -1 + ? "attr" + key.charAt(0).toUpperCase() + key.substring(1) + : key; + newValues[targetKey] = props[key]; + } + } + return newValues; +} + +const useSVGVisualState = /*@__PURE__*/ makeUseVisualState({ + scrapeMotionValuesFromProps: scrapeMotionValuesFromProps, + createRenderState: createSvgRenderState, +}); + +const isBrowser = typeof window !== "undefined"; + +const featureProps = { + animation: [ + "animate", + "variants", + "whileHover", + "whileTap", + "exit", + "whileInView", + "whileFocus", + "whileDrag", + ], + exit: ["exit"], + drag: ["drag", "dragControls"], + focus: ["whileFocus"], + hover: ["whileHover", "onHoverStart", "onHoverEnd"], + tap: ["whileTap", "onTap", "onTapStart", "onTapCancel"], + pan: ["onPan", "onPanStart", "onPanSessionStart", "onPanEnd"], + inView: ["whileInView", "onViewportEnter", "onViewportLeave"], + layout: ["layout", "layoutId"], +}; +const featureDefinitions = {}; +for (const key in featureProps) { + featureDefinitions[key] = { + isEnabled: (props) => featureProps[key].some((name) => !!props[name]), + }; +} + +function loadFeatures(features) { + for (const key in features) { + featureDefinitions[key] = { + ...featureDefinitions[key], + ...features[key], + }; + } +} + +const motionComponentSymbol = Symbol.for("motionComponentSymbol"); + +function isRefObject(ref) { + return (ref && + typeof ref === "object" && + Object.prototype.hasOwnProperty.call(ref, "current")); +} + +/** + * Creates a ref function that, when called, hydrates the provided + * external ref and VisualElement. + */ +function useMotionRef(visualState, visualElement, externalRef) { + return react.useCallback((instance) => { + if (instance) { + visualState.onMount && visualState.onMount(instance); + } + if (visualElement) { + if (instance) { + visualElement.mount(instance); + } + else { + visualElement.unmount(); + } + } + if (externalRef) { + if (typeof externalRef === "function") { + externalRef(instance); + } + else if (isRefObject(externalRef)) { + externalRef.current = instance; + } + } + }, + /** + * Only pass a new ref callback to React if we've received a visual element + * factory. Otherwise we'll be mounting/remounting every time externalRef + * or other dependencies change. + */ + [visualElement]); +} + +/** + * Convert camelCase to dash-case properties. + */ +const camelToDash = (str) => str.replace(/([a-z])([A-Z])/gu, "$1-$2").toLowerCase(); + +const optimizedAppearDataId = "framerAppearId"; +const optimizedAppearDataAttribute = "data-" + camelToDash(optimizedAppearDataId); + +/** + * Internal, exported only for usage in Framer + */ +const SwitchLayoutGroupContext = react.createContext({}); + +const useIsomorphicLayoutEffect = isBrowser ? react.useLayoutEffect : react.useEffect; + +function useVisualElement(Component, visualState, props, createVisualElement, ProjectionNodeConstructor) { + const { visualElement: parent } = react.useContext(MotionContext); + const lazyContext = react.useContext(LazyContext); + const presenceContext = react.useContext(PresenceContext); + const reducedMotionConfig = react.useContext(MotionConfigContext).reducedMotion; + const visualElementRef = react.useRef(null); + /** + * If we haven't preloaded a renderer, check to see if we have one lazy-loaded + */ + createVisualElement = + createVisualElement || + lazyContext.renderer; + if (!visualElementRef.current && createVisualElement) { + visualElementRef.current = createVisualElement(Component, { + visualState, + parent, + props, + presenceContext, + blockInitialAnimation: presenceContext + ? presenceContext.initial === false + : false, + reducedMotionConfig, + }); + } + const visualElement = visualElementRef.current; + /** + * Load Motion gesture and animation features. These are rendered as renderless + * components so each feature can optionally make use of React lifecycle methods. + */ + const initialLayoutGroupConfig = react.useContext(SwitchLayoutGroupContext); + if (visualElement && + !visualElement.projection && + ProjectionNodeConstructor && + (visualElement.type === "html" || visualElement.type === "svg")) { + createProjectionNode(visualElementRef.current, props, ProjectionNodeConstructor, initialLayoutGroupConfig); + } + const isMounted = react.useRef(false); + react.useInsertionEffect(() => { + /** + * Check the component has already mounted before calling + * `update` unnecessarily. This ensures we skip the initial update. + */ + if (visualElement && isMounted.current) { + visualElement.update(props, presenceContext); + } + }); + /** + * Cache this value as we want to know whether HandoffAppearAnimations + * was present on initial render - it will be deleted after this. + */ + const optimisedAppearId = props[optimizedAppearDataAttribute]; + const wantsHandoff = react.useRef(Boolean(optimisedAppearId) && + !window.MotionHandoffIsComplete?.(optimisedAppearId) && + window.MotionHasOptimisedAnimation?.(optimisedAppearId)); + useIsomorphicLayoutEffect(() => { + if (!visualElement) + return; + isMounted.current = true; + window.MotionIsMounted = true; + visualElement.updateFeatures(); + visualElement.scheduleRenderMicrotask(); + /** + * Ideally this function would always run in a useEffect. + * + * However, if we have optimised appear animations to handoff from, + * it needs to happen synchronously to ensure there's no flash of + * incorrect styles in the event of a hydration error. + * + * So if we detect a situtation where optimised appear animations + * are running, we use useLayoutEffect to trigger animations. + */ + if (wantsHandoff.current && visualElement.animationState) { + visualElement.animationState.animateChanges(); + } + }); + react.useEffect(() => { + if (!visualElement) + return; + if (!wantsHandoff.current && visualElement.animationState) { + visualElement.animationState.animateChanges(); + } + if (wantsHandoff.current) { + // This ensures all future calls to animateChanges() in this component will run in useEffect + queueMicrotask(() => { + window.MotionHandoffMarkAsComplete?.(optimisedAppearId); + }); + wantsHandoff.current = false; + } + /** + * Now we've finished triggering animations for this element we + * can wipe the enteringChildren set for the next render. + */ + visualElement.enteringChildren = undefined; + }); + return visualElement; +} +function createProjectionNode(visualElement, props, ProjectionNodeConstructor, initialPromotionConfig) { + const { layoutId, layout, drag, dragConstraints, layoutScroll, layoutRoot, layoutCrossfade, } = props; + visualElement.projection = new ProjectionNodeConstructor(visualElement.latestValues, props["data-framer-portal-id"] + ? undefined + : getClosestProjectingNode(visualElement.parent)); + visualElement.projection.setOptions({ + layoutId, + layout, + alwaysMeasureLayout: Boolean(drag) || (dragConstraints && isRefObject(dragConstraints)), + visualElement, + /** + * TODO: Update options in an effect. This could be tricky as it'll be too late + * to update by the time layout animations run. + * We also need to fix this safeToRemove by linking it up to the one returned by usePresence, + * ensuring it gets called if there's no potential layout animations. + * + */ + animationType: typeof layout === "string" ? layout : "both", + initialPromotionConfig, + crossfade: layoutCrossfade, + layoutScroll, + layoutRoot, + }); +} +function getClosestProjectingNode(visualElement) { + if (!visualElement) + return undefined; + return visualElement.options.allowProjection !== false + ? visualElement.projection + : getClosestProjectingNode(visualElement.parent); +} + +/** + * Create a `motion` component. + * + * This function accepts a Component argument, which can be either a string (ie "div" + * for `motion.div`), or an actual React component. + * + * Alongside this is a config option which provides a way of rendering the provided + * component "offline", or outside the React render cycle. + */ +function createMotionComponent(Component, { forwardMotionProps = false } = {}, preloadedFeatures, createVisualElement) { + preloadedFeatures && loadFeatures(preloadedFeatures); + const useVisualState = isSVGComponent(Component) + ? useSVGVisualState + : useHTMLVisualState; + function MotionDOMComponent(props, externalRef) { + /** + * If we need to measure the element we load this functionality in a + * separate class component in order to gain access to getSnapshotBeforeUpdate. + */ + let MeasureLayout; + const configAndProps = { + ...react.useContext(MotionConfigContext), + ...props, + layoutId: useLayoutId(props), + }; + const { isStatic } = configAndProps; + const context = useCreateMotionContext(props); + const visualState = useVisualState(props, isStatic); + if (!isStatic && isBrowser) { + useStrictMode(configAndProps, preloadedFeatures); + const layoutProjection = getProjectionFunctionality(configAndProps); + MeasureLayout = layoutProjection.MeasureLayout; + /** + * Create a VisualElement for this component. A VisualElement provides a common + * interface to renderer-specific APIs (ie DOM/Three.js etc) as well as + * providing a way of rendering to these APIs outside of the React render loop + * for more performant animations and interactions + */ + context.visualElement = useVisualElement(Component, visualState, configAndProps, createVisualElement, layoutProjection.ProjectionNode); + } + /** + * The mount order and hierarchy is specific to ensure our element ref + * is hydrated by the time features fire their effects. + */ + return (jsxRuntime.jsxs(MotionContext.Provider, { value: context, children: [MeasureLayout && context.visualElement ? (jsxRuntime.jsx(MeasureLayout, { visualElement: context.visualElement, ...configAndProps })) : null, useRender(Component, props, useMotionRef(visualState, context.visualElement, externalRef), visualState, isStatic, forwardMotionProps)] })); + } + MotionDOMComponent.displayName = `motion.${typeof Component === "string" + ? Component + : `create(${Component.displayName ?? Component.name ?? ""})`}`; + const ForwardRefMotionComponent = react.forwardRef(MotionDOMComponent); + ForwardRefMotionComponent[motionComponentSymbol] = Component; + return ForwardRefMotionComponent; +} +function useLayoutId({ layoutId }) { + const layoutGroupId = react.useContext(LayoutGroupContext).id; + return layoutGroupId && layoutId !== undefined + ? layoutGroupId + "-" + layoutId + : layoutId; +} +function useStrictMode(configAndProps, preloadedFeatures) { + const isStrict = react.useContext(LazyContext).strict; + /** + * If we're in development mode, check to make sure we're not rendering a motion component + * as a child of LazyMotion, as this will break the file-size benefits of using it. + */ + if (process.env.NODE_ENV !== "production" && + preloadedFeatures && + isStrict) { + const strictMessage = "You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead."; + configAndProps.ignoreStrict + ? motionUtils.warning(false, strictMessage, "lazy-strict-mode") + : motionUtils.invariant(false, strictMessage, "lazy-strict-mode"); + } +} +function getProjectionFunctionality(props) { + const { drag, layout } = featureDefinitions; + if (!drag && !layout) + return {}; + const combined = { ...drag, ...layout }; + return { + MeasureLayout: drag?.isEnabled(props) || layout?.isEnabled(props) + ? combined.MeasureLayout + : undefined, + ProjectionNode: combined.ProjectionNode, + }; +} + +function createMinimalMotionComponent(Component, options) { + return createMotionComponent(Component, options); +} + +/** + * HTML components + */ +const MotionA = /*@__PURE__*/ createMinimalMotionComponent("a"); +const MotionAbbr = /*@__PURE__*/ createMinimalMotionComponent("abbr"); +const MotionAddress = +/*@__PURE__*/ createMinimalMotionComponent("address"); +const MotionArea = /*@__PURE__*/ createMinimalMotionComponent("area"); +const MotionArticle = +/*@__PURE__*/ createMinimalMotionComponent("article"); +const MotionAside = /*@__PURE__*/ createMinimalMotionComponent("aside"); +const MotionAudio = /*@__PURE__*/ createMinimalMotionComponent("audio"); +const MotionB = /*@__PURE__*/ createMinimalMotionComponent("b"); +const MotionBase = /*@__PURE__*/ createMinimalMotionComponent("base"); +const MotionBdi = /*@__PURE__*/ createMinimalMotionComponent("bdi"); +const MotionBdo = /*@__PURE__*/ createMinimalMotionComponent("bdo"); +const MotionBig = /*@__PURE__*/ createMinimalMotionComponent("big"); +const MotionBlockquote = +/*@__PURE__*/ createMinimalMotionComponent("blockquote"); +const MotionBody = /*@__PURE__*/ createMinimalMotionComponent("body"); +const MotionButton = /*@__PURE__*/ createMinimalMotionComponent("button"); +const MotionCanvas = /*@__PURE__*/ createMinimalMotionComponent("canvas"); +const MotionCaption = +/*@__PURE__*/ createMinimalMotionComponent("caption"); +const MotionCite = /*@__PURE__*/ createMinimalMotionComponent("cite"); +const MotionCode = /*@__PURE__*/ createMinimalMotionComponent("code"); +const MotionCol = /*@__PURE__*/ createMinimalMotionComponent("col"); +const MotionColgroup = +/*@__PURE__*/ createMinimalMotionComponent("colgroup"); +const MotionData = /*@__PURE__*/ createMinimalMotionComponent("data"); +const MotionDatalist = +/*@__PURE__*/ createMinimalMotionComponent("datalist"); +const MotionDd = /*@__PURE__*/ createMinimalMotionComponent("dd"); +const MotionDel = /*@__PURE__*/ createMinimalMotionComponent("del"); +const MotionDetails = +/*@__PURE__*/ createMinimalMotionComponent("details"); +const MotionDfn = /*@__PURE__*/ createMinimalMotionComponent("dfn"); +const MotionDialog = /*@__PURE__*/ createMinimalMotionComponent("dialog"); +const MotionDiv = /*@__PURE__*/ createMinimalMotionComponent("div"); +const MotionDl = /*@__PURE__*/ createMinimalMotionComponent("dl"); +const MotionDt = /*@__PURE__*/ createMinimalMotionComponent("dt"); +const MotionEm = /*@__PURE__*/ createMinimalMotionComponent("em"); +const MotionEmbed = /*@__PURE__*/ createMinimalMotionComponent("embed"); +const MotionFieldset = +/*@__PURE__*/ createMinimalMotionComponent("fieldset"); +const MotionFigcaption = +/*@__PURE__*/ createMinimalMotionComponent("figcaption"); +const MotionFigure = /*@__PURE__*/ createMinimalMotionComponent("figure"); +const MotionFooter = /*@__PURE__*/ createMinimalMotionComponent("footer"); +const MotionForm = /*@__PURE__*/ createMinimalMotionComponent("form"); +const MotionH1 = /*@__PURE__*/ createMinimalMotionComponent("h1"); +const MotionH2 = /*@__PURE__*/ createMinimalMotionComponent("h2"); +const MotionH3 = /*@__PURE__*/ createMinimalMotionComponent("h3"); +const MotionH4 = /*@__PURE__*/ createMinimalMotionComponent("h4"); +const MotionH5 = /*@__PURE__*/ createMinimalMotionComponent("h5"); +const MotionH6 = /*@__PURE__*/ createMinimalMotionComponent("h6"); +const MotionHead = /*@__PURE__*/ createMinimalMotionComponent("head"); +const MotionHeader = /*@__PURE__*/ createMinimalMotionComponent("header"); +const MotionHgroup = /*@__PURE__*/ createMinimalMotionComponent("hgroup"); +const MotionHr = /*@__PURE__*/ createMinimalMotionComponent("hr"); +const MotionHtml = /*@__PURE__*/ createMinimalMotionComponent("html"); +const MotionI = /*@__PURE__*/ createMinimalMotionComponent("i"); +const MotionIframe = /*@__PURE__*/ createMinimalMotionComponent("iframe"); +const MotionImg = /*@__PURE__*/ createMinimalMotionComponent("img"); +const MotionInput = /*@__PURE__*/ createMinimalMotionComponent("input"); +const MotionIns = /*@__PURE__*/ createMinimalMotionComponent("ins"); +const MotionKbd = /*@__PURE__*/ createMinimalMotionComponent("kbd"); +const MotionKeygen = /*@__PURE__*/ createMinimalMotionComponent("keygen"); +const MotionLabel = /*@__PURE__*/ createMinimalMotionComponent("label"); +const MotionLegend = /*@__PURE__*/ createMinimalMotionComponent("legend"); +const MotionLi = /*@__PURE__*/ createMinimalMotionComponent("li"); +const MotionLink = /*@__PURE__*/ createMinimalMotionComponent("link"); +const MotionMain = /*@__PURE__*/ createMinimalMotionComponent("main"); +const MotionMap = /*@__PURE__*/ createMinimalMotionComponent("map"); +const MotionMark = /*@__PURE__*/ createMinimalMotionComponent("mark"); +const MotionMenu = /*@__PURE__*/ createMinimalMotionComponent("menu"); +const MotionMenuitem = +/*@__PURE__*/ createMinimalMotionComponent("menuitem"); +const MotionMeter = /*@__PURE__*/ createMinimalMotionComponent("meter"); +const MotionNav = /*@__PURE__*/ createMinimalMotionComponent("nav"); +const MotionObject = /*@__PURE__*/ createMinimalMotionComponent("object"); +const MotionOl = /*@__PURE__*/ createMinimalMotionComponent("ol"); +const MotionOptgroup = +/*@__PURE__*/ createMinimalMotionComponent("optgroup"); +const MotionOption = /*@__PURE__*/ createMinimalMotionComponent("option"); +const MotionOutput = /*@__PURE__*/ createMinimalMotionComponent("output"); +const MotionP = /*@__PURE__*/ createMinimalMotionComponent("p"); +const MotionParam = /*@__PURE__*/ createMinimalMotionComponent("param"); +const MotionPicture = +/*@__PURE__*/ createMinimalMotionComponent("picture"); +const MotionPre = /*@__PURE__*/ createMinimalMotionComponent("pre"); +const MotionProgress = +/*@__PURE__*/ createMinimalMotionComponent("progress"); +const MotionQ = /*@__PURE__*/ createMinimalMotionComponent("q"); +const MotionRp = /*@__PURE__*/ createMinimalMotionComponent("rp"); +const MotionRt = /*@__PURE__*/ createMinimalMotionComponent("rt"); +const MotionRuby = /*@__PURE__*/ createMinimalMotionComponent("ruby"); +const MotionS = /*@__PURE__*/ createMinimalMotionComponent("s"); +const MotionSamp = /*@__PURE__*/ createMinimalMotionComponent("samp"); +const MotionScript = /*@__PURE__*/ createMinimalMotionComponent("script"); +const MotionSection = +/*@__PURE__*/ createMinimalMotionComponent("section"); +const MotionSelect = /*@__PURE__*/ createMinimalMotionComponent("select"); +const MotionSmall = /*@__PURE__*/ createMinimalMotionComponent("small"); +const MotionSource = /*@__PURE__*/ createMinimalMotionComponent("source"); +const MotionSpan = /*@__PURE__*/ createMinimalMotionComponent("span"); +const MotionStrong = /*@__PURE__*/ createMinimalMotionComponent("strong"); +const MotionStyle = /*@__PURE__*/ createMinimalMotionComponent("style"); +const MotionSub = /*@__PURE__*/ createMinimalMotionComponent("sub"); +const MotionSummary = +/*@__PURE__*/ createMinimalMotionComponent("summary"); +const MotionSup = /*@__PURE__*/ createMinimalMotionComponent("sup"); +const MotionTable = /*@__PURE__*/ createMinimalMotionComponent("table"); +const MotionTbody = /*@__PURE__*/ createMinimalMotionComponent("tbody"); +const MotionTd = /*@__PURE__*/ createMinimalMotionComponent("td"); +const MotionTextarea = +/*@__PURE__*/ createMinimalMotionComponent("textarea"); +const MotionTfoot = /*@__PURE__*/ createMinimalMotionComponent("tfoot"); +const MotionTh = /*@__PURE__*/ createMinimalMotionComponent("th"); +const MotionThead = /*@__PURE__*/ createMinimalMotionComponent("thead"); +const MotionTime = /*@__PURE__*/ createMinimalMotionComponent("time"); +const MotionTitle = /*@__PURE__*/ createMinimalMotionComponent("title"); +const MotionTr = /*@__PURE__*/ createMinimalMotionComponent("tr"); +const MotionTrack = /*@__PURE__*/ createMinimalMotionComponent("track"); +const MotionU = /*@__PURE__*/ createMinimalMotionComponent("u"); +const MotionUl = /*@__PURE__*/ createMinimalMotionComponent("ul"); +const MotionVideo = /*@__PURE__*/ createMinimalMotionComponent("video"); +const MotionWbr = /*@__PURE__*/ createMinimalMotionComponent("wbr"); +const MotionWebview = +/*@__PURE__*/ createMinimalMotionComponent("webview"); +/** + * SVG components + */ +const MotionAnimate = +/*@__PURE__*/ createMinimalMotionComponent("animate"); +const MotionCircle = /*@__PURE__*/ createMinimalMotionComponent("circle"); +const MotionDefs = /*@__PURE__*/ createMinimalMotionComponent("defs"); +const MotionDesc = /*@__PURE__*/ createMinimalMotionComponent("desc"); +const MotionEllipse = +/*@__PURE__*/ createMinimalMotionComponent("ellipse"); +const MotionG = /*@__PURE__*/ createMinimalMotionComponent("g"); +const MotionImage = /*@__PURE__*/ createMinimalMotionComponent("image"); +const MotionLine = /*@__PURE__*/ createMinimalMotionComponent("line"); +const MotionFilter = /*@__PURE__*/ createMinimalMotionComponent("filter"); +const MotionMarker = /*@__PURE__*/ createMinimalMotionComponent("marker"); +const MotionMask = /*@__PURE__*/ createMinimalMotionComponent("mask"); +const MotionMetadata = +/*@__PURE__*/ createMinimalMotionComponent("metadata"); +const MotionPath = /*@__PURE__*/ createMinimalMotionComponent("path"); +const MotionPattern = +/*@__PURE__*/ createMinimalMotionComponent("pattern"); +const MotionPolygon = +/*@__PURE__*/ createMinimalMotionComponent("polygon"); +const MotionPolyline = +/*@__PURE__*/ createMinimalMotionComponent("polyline"); +const MotionRect = /*@__PURE__*/ createMinimalMotionComponent("rect"); +const MotionStop = /*@__PURE__*/ createMinimalMotionComponent("stop"); +const MotionSvg = /*@__PURE__*/ createMinimalMotionComponent("svg"); +const MotionSymbol = /*@__PURE__*/ createMinimalMotionComponent("symbol"); +const MotionText = /*@__PURE__*/ createMinimalMotionComponent("text"); +const MotionTspan = /*@__PURE__*/ createMinimalMotionComponent("tspan"); +const MotionUse = /*@__PURE__*/ createMinimalMotionComponent("use"); +const MotionView = /*@__PURE__*/ createMinimalMotionComponent("view"); +const MotionClipPath = +/*@__PURE__*/ createMinimalMotionComponent("clipPath"); +const MotionFeBlend = +/*@__PURE__*/ createMinimalMotionComponent("feBlend"); +const MotionFeColorMatrix = +/*@__PURE__*/ createMinimalMotionComponent("feColorMatrix"); +const MotionFeComponentTransfer = +/*@__PURE__*/ createMinimalMotionComponent("feComponentTransfer"); +const MotionFeComposite = +/*@__PURE__*/ createMinimalMotionComponent("feComposite"); +const MotionFeConvolveMatrix = +/*@__PURE__*/ createMinimalMotionComponent("feConvolveMatrix"); +const MotionFeDiffuseLighting = +/*@__PURE__*/ createMinimalMotionComponent("feDiffuseLighting"); +const MotionFeDisplacementMap = +/*@__PURE__*/ createMinimalMotionComponent("feDisplacementMap"); +const MotionFeDistantLight = +/*@__PURE__*/ createMinimalMotionComponent("feDistantLight"); +const MotionFeDropShadow = +/*@__PURE__*/ createMinimalMotionComponent("feDropShadow"); +const MotionFeFlood = +/*@__PURE__*/ createMinimalMotionComponent("feFlood"); +const MotionFeFuncA = +/*@__PURE__*/ createMinimalMotionComponent("feFuncA"); +const MotionFeFuncB = +/*@__PURE__*/ createMinimalMotionComponent("feFuncB"); +const MotionFeFuncG = +/*@__PURE__*/ createMinimalMotionComponent("feFuncG"); +const MotionFeFuncR = +/*@__PURE__*/ createMinimalMotionComponent("feFuncR"); +const MotionFeGaussianBlur = +/*@__PURE__*/ createMinimalMotionComponent("feGaussianBlur"); +const MotionFeImage = +/*@__PURE__*/ createMinimalMotionComponent("feImage"); +const MotionFeMerge = +/*@__PURE__*/ createMinimalMotionComponent("feMerge"); +const MotionFeMergeNode = +/*@__PURE__*/ createMinimalMotionComponent("feMergeNode"); +const MotionFeMorphology = +/*@__PURE__*/ createMinimalMotionComponent("feMorphology"); +const MotionFeOffset = +/*@__PURE__*/ createMinimalMotionComponent("feOffset"); +const MotionFePointLight = +/*@__PURE__*/ createMinimalMotionComponent("fePointLight"); +const MotionFeSpecularLighting = +/*@__PURE__*/ createMinimalMotionComponent("feSpecularLighting"); +const MotionFeSpotLight = +/*@__PURE__*/ createMinimalMotionComponent("feSpotLight"); +const MotionFeTile = /*@__PURE__*/ createMinimalMotionComponent("feTile"); +const MotionFeTurbulence = +/*@__PURE__*/ createMinimalMotionComponent("feTurbulence"); +const MotionForeignObject = +/*@__PURE__*/ createMinimalMotionComponent("foreignObject"); +const MotionLinearGradient = +/*@__PURE__*/ createMinimalMotionComponent("linearGradient"); +const MotionRadialGradient = +/*@__PURE__*/ createMinimalMotionComponent("radialGradient"); +const MotionTextPath = +/*@__PURE__*/ createMinimalMotionComponent("textPath"); + +exports.a = MotionA; +exports.abbr = MotionAbbr; +exports.address = MotionAddress; +exports.animate = MotionAnimate; +exports.area = MotionArea; +exports.article = MotionArticle; +exports.aside = MotionAside; +exports.audio = MotionAudio; +exports.b = MotionB; +exports.base = MotionBase; +exports.bdi = MotionBdi; +exports.bdo = MotionBdo; +exports.big = MotionBig; +exports.blockquote = MotionBlockquote; +exports.body = MotionBody; +exports.button = MotionButton; +exports.canvas = MotionCanvas; +exports.caption = MotionCaption; +exports.circle = MotionCircle; +exports.cite = MotionCite; +exports.clipPath = MotionClipPath; +exports.code = MotionCode; +exports.col = MotionCol; +exports.colgroup = MotionColgroup; +exports.create = createMinimalMotionComponent; +exports.data = MotionData; +exports.datalist = MotionDatalist; +exports.dd = MotionDd; +exports.defs = MotionDefs; +exports.del = MotionDel; +exports.desc = MotionDesc; +exports.details = MotionDetails; +exports.dfn = MotionDfn; +exports.dialog = MotionDialog; +exports.div = MotionDiv; +exports.dl = MotionDl; +exports.dt = MotionDt; +exports.ellipse = MotionEllipse; +exports.em = MotionEm; +exports.embed = MotionEmbed; +exports.feBlend = MotionFeBlend; +exports.feColorMatrix = MotionFeColorMatrix; +exports.feComponentTransfer = MotionFeComponentTransfer; +exports.feComposite = MotionFeComposite; +exports.feConvolveMatrix = MotionFeConvolveMatrix; +exports.feDiffuseLighting = MotionFeDiffuseLighting; +exports.feDisplacementMap = MotionFeDisplacementMap; +exports.feDistantLight = MotionFeDistantLight; +exports.feDropShadow = MotionFeDropShadow; +exports.feFlood = MotionFeFlood; +exports.feFuncA = MotionFeFuncA; +exports.feFuncB = MotionFeFuncB; +exports.feFuncG = MotionFeFuncG; +exports.feFuncR = MotionFeFuncR; +exports.feGaussianBlur = MotionFeGaussianBlur; +exports.feImage = MotionFeImage; +exports.feMerge = MotionFeMerge; +exports.feMergeNode = MotionFeMergeNode; +exports.feMorphology = MotionFeMorphology; +exports.feOffset = MotionFeOffset; +exports.fePointLight = MotionFePointLight; +exports.feSpecularLighting = MotionFeSpecularLighting; +exports.feSpotLight = MotionFeSpotLight; +exports.feTile = MotionFeTile; +exports.feTurbulence = MotionFeTurbulence; +exports.fieldset = MotionFieldset; +exports.figcaption = MotionFigcaption; +exports.figure = MotionFigure; +exports.filter = MotionFilter; +exports.footer = MotionFooter; +exports.foreignObject = MotionForeignObject; +exports.form = MotionForm; +exports.g = MotionG; +exports.h1 = MotionH1; +exports.h2 = MotionH2; +exports.h3 = MotionH3; +exports.h4 = MotionH4; +exports.h5 = MotionH5; +exports.h6 = MotionH6; +exports.head = MotionHead; +exports.header = MotionHeader; +exports.hgroup = MotionHgroup; +exports.hr = MotionHr; +exports.html = MotionHtml; +exports.i = MotionI; +exports.iframe = MotionIframe; +exports.image = MotionImage; +exports.img = MotionImg; +exports.input = MotionInput; +exports.ins = MotionIns; +exports.kbd = MotionKbd; +exports.keygen = MotionKeygen; +exports.label = MotionLabel; +exports.legend = MotionLegend; +exports.li = MotionLi; +exports.line = MotionLine; +exports.linearGradient = MotionLinearGradient; +exports.link = MotionLink; +exports.main = MotionMain; +exports.map = MotionMap; +exports.mark = MotionMark; +exports.marker = MotionMarker; +exports.mask = MotionMask; +exports.menu = MotionMenu; +exports.menuitem = MotionMenuitem; +exports.metadata = MotionMetadata; +exports.meter = MotionMeter; +exports.nav = MotionNav; +exports.object = MotionObject; +exports.ol = MotionOl; +exports.optgroup = MotionOptgroup; +exports.option = MotionOption; +exports.output = MotionOutput; +exports.p = MotionP; +exports.param = MotionParam; +exports.path = MotionPath; +exports.pattern = MotionPattern; +exports.picture = MotionPicture; +exports.polygon = MotionPolygon; +exports.polyline = MotionPolyline; +exports.pre = MotionPre; +exports.progress = MotionProgress; +exports.q = MotionQ; +exports.radialGradient = MotionRadialGradient; +exports.rect = MotionRect; +exports.rp = MotionRp; +exports.rt = MotionRt; +exports.ruby = MotionRuby; +exports.s = MotionS; +exports.samp = MotionSamp; +exports.script = MotionScript; +exports.section = MotionSection; +exports.select = MotionSelect; +exports.small = MotionSmall; +exports.source = MotionSource; +exports.span = MotionSpan; +exports.stop = MotionStop; +exports.strong = MotionStrong; +exports.style = MotionStyle; +exports.sub = MotionSub; +exports.summary = MotionSummary; +exports.sup = MotionSup; +exports.svg = MotionSvg; +exports.symbol = MotionSymbol; +exports.table = MotionTable; +exports.tbody = MotionTbody; +exports.td = MotionTd; +exports.text = MotionText; +exports.textPath = MotionTextPath; +exports.textarea = MotionTextarea; +exports.tfoot = MotionTfoot; +exports.th = MotionTh; +exports.thead = MotionThead; +exports.time = MotionTime; +exports.title = MotionTitle; +exports.tr = MotionTr; +exports.track = MotionTrack; +exports.tspan = MotionTspan; +exports.u = MotionU; +exports.ul = MotionUl; +exports.use = MotionUse; +exports.video = MotionVideo; +exports.view = MotionView; +exports.wbr = MotionWbr; +exports.webview = MotionWebview; diff --git a/frontend/node_modules/framer-motion/dist/cjs/mini.js b/frontend/node_modules/framer-motion/dist/cjs/mini.js new file mode 100644 index 0000000000000000000000000000000000000000..535407a010881145e224381df845a2bba23c19ff --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/cjs/mini.js @@ -0,0 +1,148 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var react = require('react'); +var motionDom = require('motion-dom'); +var motionUtils = require('motion-utils'); + +/** + * Creates a constant value over the lifecycle of a component. + * + * Even if `useMemo` is provided an empty array as its final argument, it doesn't offer + * a guarantee that it won't re-run for performance reasons later on. By using `useConstant` + * you can ensure that initialisers don't execute twice or more. + */ +function useConstant(init) { + const ref = react.useRef(null); + if (ref.current === null) { + ref.current = init(); + } + return ref.current; +} + +function useUnmountEffect(callback) { + return react.useEffect(() => () => callback(), []); +} + +function animateElements(elementOrSelector, keyframes, options, scope) { + const elements = motionDom.resolveElements(elementOrSelector, scope); + const numElements = elements.length; + motionUtils.invariant(Boolean(numElements), "No valid elements provided.", "no-valid-elements"); + /** + * WAAPI doesn't support interrupting animations. + * + * Therefore, starting animations requires a three-step process: + * 1. Stop existing animations (write styles to DOM) + * 2. Resolve keyframes (read styles from DOM) + * 3. Create new animations (write styles to DOM) + * + * The hybrid `animate()` function uses AsyncAnimation to resolve + * keyframes before creating new animations, which removes style + * thrashing. Here, we have much stricter filesize constraints. + * Therefore we do this in a synchronous way that ensures that + * at least within `animate()` calls there is no style thrashing. + * + * In the motion-native-animate-mini-interrupt benchmark this + * was 80% faster than a single loop. + */ + const animationDefinitions = []; + /** + * Step 1: Build options and stop existing animations (write) + */ + for (let i = 0; i < numElements; i++) { + const element = elements[i]; + const elementTransition = { ...options }; + /** + * Resolve stagger function if provided. + */ + if (typeof elementTransition.delay === "function") { + elementTransition.delay = elementTransition.delay(i, numElements); + } + for (const valueName in keyframes) { + let valueKeyframes = keyframes[valueName]; + if (!Array.isArray(valueKeyframes)) { + valueKeyframes = [valueKeyframes]; + } + const valueOptions = { + ...motionDom.getValueTransition(elementTransition, valueName), + }; + valueOptions.duration && (valueOptions.duration = motionUtils.secondsToMilliseconds(valueOptions.duration)); + valueOptions.delay && (valueOptions.delay = motionUtils.secondsToMilliseconds(valueOptions.delay)); + /** + * If there's an existing animation playing on this element then stop it + * before creating a new one. + */ + const map = motionDom.getAnimationMap(element); + const key = motionDom.animationMapKey(valueName, valueOptions.pseudoElement || ""); + const currentAnimation = map.get(key); + currentAnimation && currentAnimation.stop(); + animationDefinitions.push({ + map, + key, + unresolvedKeyframes: valueKeyframes, + options: { + ...valueOptions, + element, + name: valueName, + allowFlatten: !elementTransition.type && !elementTransition.ease, + }, + }); + } + } + /** + * Step 2: Resolve keyframes (read) + */ + for (let i = 0; i < animationDefinitions.length; i++) { + const { unresolvedKeyframes, options: animationOptions } = animationDefinitions[i]; + const { element, name, pseudoElement } = animationOptions; + if (!pseudoElement && unresolvedKeyframes[0] === null) { + unresolvedKeyframes[0] = motionDom.getComputedStyle(element, name); + } + motionDom.fillWildcards(unresolvedKeyframes); + motionDom.applyPxDefaults(unresolvedKeyframes, name); + /** + * If we only have one keyframe, explicitly read the initial keyframe + * from the computed style. This is to ensure consistency with WAAPI behaviour + * for restarting animations, for instance .play() after finish, when it + * has one vs two keyframes. + */ + if (!pseudoElement && unresolvedKeyframes.length < 2) { + unresolvedKeyframes.unshift(motionDom.getComputedStyle(element, name)); + } + animationOptions.keyframes = unresolvedKeyframes; + } + /** + * Step 3: Create new animations (write) + */ + const animations = []; + for (let i = 0; i < animationDefinitions.length; i++) { + const { map, key, options: animationOptions } = animationDefinitions[i]; + const animation = new motionDom.NativeAnimation(animationOptions); + map.set(key, animation); + animation.finished.finally(() => map.delete(key)); + animations.push(animation); + } + return animations; +} + +const createScopedWaapiAnimate = (scope) => { + function scopedAnimate(elementOrSelector, keyframes, options) { + return new motionDom.GroupAnimationWithThen(animateElements(elementOrSelector, keyframes, options, scope)); + } + return scopedAnimate; +}; + +function useAnimateMini() { + const scope = useConstant(() => ({ + current: null, // Will be hydrated by React + animations: [], + })); + const animate = useConstant(() => createScopedWaapiAnimate(scope)); + useUnmountEffect(() => { + scope.animations.forEach((animation) => animation.stop()); + }); + return [scope, animate]; +} + +exports.useAnimate = useAnimateMini; diff --git a/frontend/node_modules/framer-motion/dist/debug.d.ts b/frontend/node_modules/framer-motion/dist/debug.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a4901bc1d9ae46df00600151db584a77dc31f285 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/debug.d.ts @@ -0,0 +1,2 @@ +export * from 'motion-dom'; +export { recordStats } from 'motion-dom'; diff --git a/frontend/node_modules/framer-motion/dist/dom-mini.d.ts b/frontend/node_modules/framer-motion/dist/dom-mini.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a2aa22c25cd74ebfb7c304a72358a3fa44e010b0 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/dom-mini.d.ts @@ -0,0 +1,48 @@ +import { AnimationPlaybackOptions, Transition, MotionValue, UnresolvedValueKeyframe, ElementOrSelector, DOMKeyframesDefinition, AnimationOptions, GroupAnimationWithThen, AnimationPlaybackControlsWithThen } from 'motion-dom'; + +type ObjectTarget = { + [K in keyof O]?: O[K] | UnresolvedValueKeyframe[]; +}; +type SequenceTime = number | "<" | `+${number}` | `-${number}` | `${string}`; +type SequenceLabel = string; +interface SequenceLabelWithTime { + name: SequenceLabel; + at: SequenceTime; +} +interface At { + at?: SequenceTime; +} +type MotionValueSegment = [ + MotionValue, + UnresolvedValueKeyframe | UnresolvedValueKeyframe[] +]; +type MotionValueSegmentWithTransition = [ + MotionValue, + UnresolvedValueKeyframe | UnresolvedValueKeyframe[], + Transition & At +]; +type DOMSegment = [ElementOrSelector, DOMKeyframesDefinition]; +type DOMSegmentWithTransition = [ + ElementOrSelector, + DOMKeyframesDefinition, + AnimationOptions & At +]; +type ObjectSegment = [O, ObjectTarget]; +type ObjectSegmentWithTransition = [ + O, + ObjectTarget, + AnimationOptions & At +]; +type Segment = ObjectSegment | ObjectSegmentWithTransition | SequenceLabel | SequenceLabelWithTime | MotionValueSegment | MotionValueSegmentWithTransition | DOMSegment | DOMSegmentWithTransition; +type AnimationSequence = Segment[]; +interface SequenceOptions extends AnimationPlaybackOptions { + delay?: number; + duration?: number; + defaultTransition?: Transition; +} + +declare function animateSequence(definition: AnimationSequence, options?: SequenceOptions): GroupAnimationWithThen; + +declare const animateMini: (elementOrSelector: ElementOrSelector, keyframes: DOMKeyframesDefinition, options?: AnimationOptions) => AnimationPlaybackControlsWithThen; + +export { animateMini as animate, animateSequence }; diff --git a/frontend/node_modules/framer-motion/dist/dom-mini.js b/frontend/node_modules/framer-motion/dist/dom-mini.js new file mode 100644 index 0000000000000000000000000000000000000000..517a6590d33e24aa20a2c9671e8656acad760097 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/dom-mini.js @@ -0,0 +1 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).Motion={})}(this,function(t){"use strict";function e(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}function n(t){let e;return()=>(void 0===e&&(e=t()),e)}const i=t=>t,s=(t,e,n)=>{const i=e-t;return 0===i?1:(n-t)/i},o=t=>1e3*t,a=t=>t/1e3;function r(t,e){return n=t,Array.isArray(n)&&"number"!=typeof n[0]?t[((t,e,n)=>{const i=e-t;return((n-t)%i+i)%i+t})(0,t.length,e)]:t;var n}const l=(t,e,n)=>t+(e-t)*n,u=2e4;function h(t,e=100,n){const i=n({...t,keyframes:[0,e]}),s=Math.min(function(t){let e=0,n=t.next(e);for(;!n.done&&e=u?1/0:e}(i),u);return{type:"keyframes",ease:t=>i.next(s*t).value/e,duration:a(s)}}function c(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const o=s(0,e,i);t.push(l(n,1,o))}}function f(t){const e=[0];return c(e,t.length-1),e}const m=t=>null!==t;class d{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,e){return this.finished.then(t,e)}}function p(t){for(let e=1;et.startsWith("--");const g=n(()=>void 0!==window.ScrollTimeline),A={};function b(t,e){const i=n(t);return()=>A[e]??i()}const T=b(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch(t){return!1}return!0},"linearEasing"),v=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,M={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:v([0,.65,.55,1]),circOut:v([.55,0,1,.45]),backIn:v([.31,.01,.66,-.59]),backOut:v([.33,1.53,.69,.99])};function w(t,e){return t?"function"==typeof t?T()?((t,e,n=10)=>{let i="";const s=Math.max(Math.round(e/n),2);for(let e=0;eArray.isArray(t)&&"number"==typeof t[0])(t)?v(t):Array.isArray(t)?t.map(t=>w(t,e)||M.easeOut):M[t]:void 0}function k(t){return"function"==typeof t&&"applyToOptions"in t}class x extends d{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:e,name:n,keyframes:i,pseudoElement:s,allowFlatten:o=!1,finalKeyframe:a,onComplete:r}=t;this.isPseudoElement=Boolean(s),this.allowFlatten=o,this.options=t,t.type;const l=function({type:t,...e}){return k(t)&&T()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}(t);this.animation=function(t,e,n,{delay:i=0,duration:s=300,repeat:o=0,repeatType:a="loop",ease:r="easeOut",times:l}={},u){const h={[e]:n};l&&(h.offset=l);const c=w(r,s);Array.isArray(c)&&(h.easing=c);const f={delay:i,duration:s,easing:Array.isArray(c)?"linear":c,fill:"both",iterations:o+1,direction:"reverse"===a?"alternate":"normal"};return u&&(f.pseudoElement=u),t.animate(h,f)}(e,n,i,l,s),!1===l.autoplay&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!s){const t=function(t,{repeat:e,repeatType:n="loop"},i,s=1){const o=t.filter(m),a=s<0||e&&"loop"!==n&&e%2==1?0:o.length-1;return a&&void 0!==i?i:o[a]}(i,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(t):function(t,e,n){y(e)?t.style.setProperty(e,n):t.style[e]=n}(e,n,t),this.animation.cancel()}r?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),"finished"===this.state&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch(t){}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;"idle"!==t&&"finished"!==t&&(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming?.().duration||0;return a(Number(t))}get time(){return a(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=o(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return null!==this.finishedTime?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:e}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&g()?(this.animation.timeline=t,i):e(this)}}class E{constructor(t){this.stop=()=>this.runAll("stop"),this.animations=t.filter(Boolean)}get finished(){return Promise.all(this.animations.map(t=>t.finished))}getAll(t){return this.animations[0][t]}setAll(t,e){for(let n=0;ne.attachTimeline(t));return()=>{e.forEach((t,e)=>{t&&t(),this.animations[e].stop()})}}get time(){return this.getAll("time")}set time(t){this.setAll("time",t)}get speed(){return this.getAll("speed")}set speed(t){this.setAll("speed",t)}get state(){return this.getAll("state")}get startTime(){return this.getAll("startTime")}get duration(){let t=0;for(let e=0;ee[t]())}play(){this.runAll("play")}pause(){this.runAll("pause")}cancel(){this.runAll("cancel")}complete(){this.runAll("complete")}}class O extends E{then(t,e){return this.finished.finally(t).then(()=>{})}}const S=new WeakMap,R=(t,e="")=>`${t}:${e}`;function F(t){const e=S.get(t)||new Map;return S.set(t,e),e}function W(t,e){return t?.[e]??t?.default??t}const P=new Set(["borderWidth","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderRadius","radius","borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius","width","maxWidth","height","maxHeight","top","right","bottom","left","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","margin","marginTop","marginRight","marginBottom","marginLeft","backgroundPositionX","backgroundPositionY"]);function B(t,e){for(let n=0;nBoolean(t&&t.getVelocity);function I(t,e,n,i){return"string"==typeof t&&function(t){return"object"==typeof t&&!Array.isArray(t)}(e)?$(t,n,i):t instanceof NodeList?Array.from(t):Array.isArray(t)?t:[t]}function N(t,e,n){return t*(e+1)}function C(t,e,n,i){return"number"==typeof e?e:e.startsWith("-")||e.startsWith("+")?Math.max(0,t+parseFloat(e)):"<"===e?n:e.startsWith("<")?Math.max(0,n+parseFloat(e.slice(1))):i.get(e)??t}function K(t,n,i,s,o,a){!function(t,n,i){for(let s=0;sn&&o.at"number"==typeof t,Y=t=>t.every(X);function G(t,e,n,i){const s=$(t,i),a=s.length,r=[];for(let t=0;te.delete(n)),l.push(s)}return l}const J=(t=>function(e,n,i){return new O(G(e,n,i,t))})();t.animate=J,t.animateSequence=function(t,e){const n=[];return function(t,{defaultTransition:e={},...n}={},i,a){const l=e.duration||.3,u=new Map,m=new Map,d={},p=new Map;let y=0,g=0,A=0;for(let n=0;n{const m=D(t),{delay:d=0,times:p=f(m),type:y="keyframes",repeat:b,repeatType:T,repeatDelay:M=0,...w}=n;let{ease:x=e.ease||"easeOut",duration:E}=n;const O="function"==typeof d?d(s,u):d,S=m.length,R=k(y)?y:a?.[y||"keyframes"];if(S<=2&&R){let t=100;if(2===S&&Y(m)){const e=m[1]-m[0];t=Math.abs(e)}const e={...w};void 0!==E&&(e.duration=o(E));const n=h(e,t,R);x=n.ease,E=n.duration}E??(E=l);const F=g+O;1===p.length&&0===p[0]&&(p[1]=1);const W=p.length-m.length;if(W>0&&c(p,W),1===m.length&&m.unshift(null),b){E=N(E,b);const t=[...m],e=[...p];x=Array.isArray(x)?[...x]:[x];const n=[...x];for(let i=0;i{for(const o in t){const a=t[o];a.sort(q);const r=[],l=[],h=[];for(let t=0;t{n.push(...G(i,t,e))}),new O(n)}}); diff --git a/frontend/node_modules/framer-motion/dist/dom.d.ts b/frontend/node_modules/framer-motion/dist/dom.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6625ba5c0f6f0333f6f128f97cae52e24cfc1c18 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/dom.d.ts @@ -0,0 +1,151 @@ +import { UnresolvedValueKeyframe, MotionValue, Transition, ElementOrSelector, DOMKeyframesDefinition, AnimationOptions, AnimationPlaybackOptions, AnyResolvedKeyframe, AnimationScope, AnimationPlaybackControlsWithThen, ValueAnimationTransition, AnimationPlaybackControls } from 'motion-dom'; +export * from 'motion-dom'; +import { Easing, EasingFunction, Point } from 'motion-utils'; +export * from 'motion-utils'; + +type ObjectTarget = { + [K in keyof O]?: O[K] | UnresolvedValueKeyframe[]; +}; +type SequenceTime = number | "<" | `+${number}` | `-${number}` | `${string}`; +type SequenceLabel = string; +interface SequenceLabelWithTime { + name: SequenceLabel; + at: SequenceTime; +} +interface At { + at?: SequenceTime; +} +type MotionValueSegment = [ + MotionValue, + UnresolvedValueKeyframe | UnresolvedValueKeyframe[] +]; +type MotionValueSegmentWithTransition = [ + MotionValue, + UnresolvedValueKeyframe | UnresolvedValueKeyframe[], + Transition & At +]; +type DOMSegment = [ElementOrSelector, DOMKeyframesDefinition]; +type DOMSegmentWithTransition = [ + ElementOrSelector, + DOMKeyframesDefinition, + AnimationOptions & At +]; +type ObjectSegment = [O, ObjectTarget]; +type ObjectSegmentWithTransition = [ + O, + ObjectTarget, + AnimationOptions & At +]; +type Segment = ObjectSegment | ObjectSegmentWithTransition | SequenceLabel | SequenceLabelWithTime | MotionValueSegment | MotionValueSegmentWithTransition | DOMSegment | DOMSegmentWithTransition; +type AnimationSequence = Segment[]; +interface SequenceOptions extends AnimationPlaybackOptions { + delay?: number; + duration?: number; + defaultTransition?: Transition; +} +interface AbsoluteKeyframe { + value: AnyResolvedKeyframe | null; + at: number; + easing?: Easing; +} +type ValueSequence = AbsoluteKeyframe[]; +interface SequenceMap { + [key: string]: ValueSequence; +} +type ResolvedAnimationDefinition = { + keyframes: { + [key: string]: UnresolvedValueKeyframe[]; + }; + transition: { + [key: string]: Transition; + }; +}; +type ResolvedAnimationDefinitions = Map; + +/** + * Creates an animation function that is optionally scoped + * to a specific element. + */ +declare function createScopedAnimate(scope?: AnimationScope): { + (sequence: AnimationSequence, options?: SequenceOptions): AnimationPlaybackControlsWithThen; + (value: string | MotionValue, keyframes: string | UnresolvedValueKeyframe[], options?: ValueAnimationTransition): AnimationPlaybackControlsWithThen; + (value: number | MotionValue, keyframes: number | UnresolvedValueKeyframe[], options?: ValueAnimationTransition): AnimationPlaybackControlsWithThen; + (value: V | MotionValue, keyframes: V | UnresolvedValueKeyframe[], options?: ValueAnimationTransition): AnimationPlaybackControlsWithThen; + (element: ElementOrSelector, keyframes: DOMKeyframesDefinition, options?: AnimationOptions): AnimationPlaybackControlsWithThen; + (object: O | O[], keyframes: ObjectTarget, options?: AnimationOptions): AnimationPlaybackControlsWithThen; +}; +declare const animate: { + (sequence: AnimationSequence, options?: SequenceOptions): AnimationPlaybackControlsWithThen; + (value: string | MotionValue, keyframes: string | UnresolvedValueKeyframe[], options?: ValueAnimationTransition): AnimationPlaybackControlsWithThen; + (value: number | MotionValue, keyframes: number | UnresolvedValueKeyframe[], options?: ValueAnimationTransition): AnimationPlaybackControlsWithThen; + (value: V | MotionValue, keyframes: V | UnresolvedValueKeyframe[], options?: ValueAnimationTransition): AnimationPlaybackControlsWithThen; + (element: ElementOrSelector, keyframes: DOMKeyframesDefinition, options?: AnimationOptions): AnimationPlaybackControlsWithThen; + (object: O | O[], keyframes: ObjectTarget, options?: AnimationOptions): AnimationPlaybackControlsWithThen; +}; + +declare const animateMini: (elementOrSelector: ElementOrSelector, keyframes: DOMKeyframesDefinition, options?: AnimationOptions) => AnimationPlaybackControlsWithThen; + +interface ScrollOptions { + source?: HTMLElement; + container?: Element; + target?: Element; + axis?: "x" | "y"; + offset?: ScrollOffset; +} +type OnScrollProgress = (progress: number) => void; +type OnScrollWithInfo = (progress: number, info: ScrollInfo) => void; +type OnScroll = OnScrollProgress | OnScrollWithInfo; +interface AxisScrollInfo { + current: number; + offset: number[]; + progress: number; + scrollLength: number; + velocity: number; + targetOffset: number; + targetLength: number; + containerLength: number; + interpolatorOffsets?: number[]; + interpolate?: EasingFunction; +} +interface ScrollInfo { + time: number; + x: AxisScrollInfo; + y: AxisScrollInfo; +} +type OnScrollInfo = (info: ScrollInfo) => void; +type SupportedEdgeUnit = "px" | "vw" | "vh" | "%"; +type EdgeUnit = `${number}${SupportedEdgeUnit}`; +type NamedEdges = "start" | "end" | "center"; +type EdgeString = NamedEdges | EdgeUnit | `${number}`; +type Edge = EdgeString | number; +type ProgressIntersection = [number, number]; +type Intersection = `${Edge} ${Edge}`; +type ScrollOffset = Array; +interface ScrollInfoOptions { + container?: Element; + target?: Element; + axis?: "x" | "y"; + offset?: ScrollOffset; +} + +declare function scroll(onScroll: OnScroll | AnimationPlaybackControls, { axis, container, ...options }?: ScrollOptions): VoidFunction; + +declare function scrollInfo(onScroll: OnScrollInfo, { container, ...options }?: ScrollInfoOptions): VoidFunction; + +type ViewChangeHandler = (entry: IntersectionObserverEntry) => void; +type MarginValue = `${number}${"px" | "%"}`; +type MarginType = MarginValue | `${MarginValue} ${MarginValue}` | `${MarginValue} ${MarginValue} ${MarginValue}` | `${MarginValue} ${MarginValue} ${MarginValue} ${MarginValue}`; +interface InViewOptions { + root?: Element | Document; + margin?: MarginType; + amount?: "some" | "all" | number; +} +declare function inView(elementOrSelector: ElementOrSelector, onStart: (element: Element, entry: IntersectionObserverEntry) => void | ViewChangeHandler, { root, margin: rootMargin, amount }?: InViewOptions): VoidFunction; + +type DelayedFunction = (overshoot: number) => void; +declare function delayInSeconds(callback: DelayedFunction, timeout: number): () => void; + +declare const distance: (a: number, b: number) => number; +declare function distance2D(a: Point, b: Point): number; + +export { type AbsoluteKeyframe, type AnimationSequence, type At, type DOMSegment, type DOMSegmentWithTransition, type DelayedFunction, type MotionValueSegment, type MotionValueSegmentWithTransition, type ObjectSegment, type ObjectSegmentWithTransition, type ObjectTarget, type ResolvedAnimationDefinition, type ResolvedAnimationDefinitions, type Segment, type SequenceLabel, type SequenceLabelWithTime, type SequenceMap, type SequenceOptions, type SequenceTime, type ValueSequence, animate, animateMini, createScopedAnimate, delayInSeconds as delay, distance, distance2D, inView, scroll, scrollInfo }; diff --git a/frontend/node_modules/framer-motion/dist/dom.js b/frontend/node_modules/framer-motion/dist/dom.js new file mode 100644 index 0000000000000000000000000000000000000000..7358c6df2a8454d105d0e6d598cfc45fc72de785 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/dom.js @@ -0,0 +1 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).Motion={})}(this,function(t){"use strict";function e(t,e){-1===t.indexOf(e)&&t.push(e)}function n(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const s=(t,e,n)=>n>e?e:n{};const r={},o=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function a(t){return"object"==typeof t&&null!==t}const l=t=>/^0[^.\s]+$/u.test(t);function u(t){let e;return()=>(void 0===e&&(e=t()),e)}const c=t=>t,h=(t,e)=>n=>e(t(n)),d=(...t)=>t.reduce(h),p=(t,e,n)=>{const s=e-t;return 0===s?1:(n-t)/s};class f{constructor(){this.subscriptions=[]}add(t){return e(this.subscriptions,t),()=>n(this.subscriptions,t)}notify(t,e,n){const s=this.subscriptions.length;if(s)if(1===s)this.subscriptions[0](t,e,n);else for(let i=0;i1e3*t,g=t=>t/1e3;function y(t,e){return e?t*(1e3/e):0}const v=new Set;const w=(t,e,n)=>{const s=e-t;return((n-t)%s+s)%s+t},b=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t;function T(t,e,n,s){if(t===e&&n===s)return c;const i=e=>function(t,e,n,s,i){let r,o,a=0;do{o=e+(n-e)/2,r=b(o,s,i)-t,r>0?n=o:e=o}while(Math.abs(r)>1e-7&&++a<12);return o}(e,0,1,t,n);return t=>0===t||1===t?t:b(i(t),e,s)}const x=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,V=t=>e=>1-t(1-e),M=T(.33,1.53,.69,.99),S=V(M),A=x(S),k=t=>(t*=2)<1?.5*S(t):.5*(2-Math.pow(2,-10*(t-1))),E=t=>1-Math.sin(Math.acos(t)),P=V(E),C=x(E),O=T(.42,0,1,1),F=T(0,0,.58,1),R=T(.42,0,.58,1);const B=t=>Array.isArray(t)&&"number"!=typeof t[0];function L(t,e){return B(t)?t[w(0,t.length,e)]:t}const D=t=>Array.isArray(t)&&"number"==typeof t[0],I={linear:c,easeIn:O,easeInOut:R,easeOut:F,circIn:E,circInOut:C,circOut:P,backIn:S,backInOut:A,backOut:M,anticipate:k},W=t=>{if(D(t)){t.length;const[e,n,s,i]=t;return T(e,n,s,i)}return"string"==typeof t?I[t]:t},j=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],N={value:null,addProjectionMetrics:null};function K(t,e){let n=!1,s=!0;const i={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,a=j.reduce((t,n)=>(t[n]=function(t,e){let n=new Set,s=new Set,i=!1,r=!1;const o=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},l=0;function u(e){o.has(e)&&(c.schedule(e),t()),l++,e(a)}const c={schedule:(t,e=!1,r=!1)=>{const a=r&&i?n:s;return e&&o.add(t),a.has(t)||a.add(t),t},cancel:t=>{s.delete(t),o.delete(t)},process:t=>{a=t,i?r=!0:(i=!0,[n,s]=[s,n],n.forEach(u),e&&N.value&&N.value.frameloop[e].push(l),l=0,n.clear(),i=!1,r&&(r=!1,c.process(t)))}};return c}(o,e?n:void 0),t),{}),{setup:l,read:u,resolveKeyframes:c,preUpdate:h,update:d,preRender:p,render:f,postRender:m}=a,g=()=>{const o=r.useManualTiming?i.timestamp:performance.now();n=!1,r.useManualTiming||(i.delta=s?1e3/60:Math.max(Math.min(o-i.timestamp,40),1)),i.timestamp=o,i.isProcessing=!0,l.process(i),u.process(i),c.process(i),h.process(i),d.process(i),p.process(i),f.process(i),m.process(i),i.isProcessing=!1,n&&e&&(s=!1,t(g))};return{schedule:j.reduce((e,r)=>{const o=a[r];return e[r]=(e,r=!1,a=!1)=>(n||(n=!0,s=!0,i.isProcessing||t(g)),o.schedule(e,r,a)),e},{}),cancel:t=>{for(let e=0;e(void 0===X&&G.set(Y.isProcessing||r.useManualTiming?Y.timestamp:performance.now()),X),set:t=>{X=t,queueMicrotask(H)}},Z={layout:0,mainThread:0,waapi:0},q=t=>e=>"string"==typeof e&&e.startsWith(t),_=q("--"),J=q("var(--"),Q=t=>!!J(t)&&tt.test(t.split("/*")[0].trim()),tt=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,et={test:t=>"number"==typeof t,parse:parseFloat,transform:t=>t},nt={...et,transform:t=>s(0,1,t)},st={...et,default:1},it=t=>Math.round(1e5*t)/1e5,rt=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;const ot=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,at=(t,e)=>n=>Boolean("string"==typeof n&&ot.test(n)&&n.startsWith(t)||e&&!function(t){return null==t}(n)&&Object.prototype.hasOwnProperty.call(n,e)),lt=(t,e,n)=>s=>{if("string"!=typeof s)return s;const[i,r,o,a]=s.match(rt);return{[t]:parseFloat(i),[e]:parseFloat(r),[n]:parseFloat(o),alpha:void 0!==a?parseFloat(a):1}},ut={...et,transform:t=>Math.round((t=>s(0,255,t))(t))},ct={test:at("rgb","red"),parse:lt("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:s=1})=>"rgba("+ut.transform(t)+", "+ut.transform(e)+", "+ut.transform(n)+", "+it(nt.transform(s))+")"};const ht={test:at("#"),parse:function(t){let e="",n="",s="",i="";return t.length>5?(e=t.substring(1,3),n=t.substring(3,5),s=t.substring(5,7),i=t.substring(7,9)):(e=t.substring(1,2),n=t.substring(2,3),s=t.substring(3,4),i=t.substring(4,5),e+=e,n+=n,s+=s,i+=i),{red:parseInt(e,16),green:parseInt(n,16),blue:parseInt(s,16),alpha:i?parseInt(i,16)/255:1}},transform:ct.transform},dt=t=>({test:e=>"string"==typeof e&&e.endsWith(t)&&1===e.split(" ").length,parse:parseFloat,transform:e=>`${e}${t}`}),pt=dt("deg"),ft=dt("%"),mt=dt("px"),gt=dt("vh"),yt=dt("vw"),vt=(()=>({...ft,parse:t=>ft.parse(t)/100,transform:t=>ft.transform(100*t)}))(),wt={test:at("hsl","hue"),parse:lt("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:s=1})=>"hsla("+Math.round(t)+", "+ft.transform(it(e))+", "+ft.transform(it(n))+", "+it(nt.transform(s))+")"},bt={test:t=>ct.test(t)||ht.test(t)||wt.test(t),parse:t=>ct.test(t)?ct.parse(t):wt.test(t)?wt.parse(t):ht.parse(t),transform:t=>"string"==typeof t?t:t.hasOwnProperty("red")?ct.transform(t):wt.transform(t),getAnimatableNone:t=>{const e=bt.parse(t);return e.alpha=0,bt.transform(e)}},Tt=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;const xt="number",Vt="color",Mt=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function St(t){const e=t.toString(),n=[],s={color:[],number:[],var:[]},i=[];let r=0;const o=e.replace(Mt,t=>(bt.test(t)?(s.color.push(r),i.push(Vt),n.push(bt.parse(t))):t.startsWith("var(")?(s.var.push(r),i.push("var"),n.push(t)):(s.number.push(r),i.push(xt),n.push(parseFloat(t))),++r,"${}")).split("${}");return{values:n,split:o,indexes:s,types:i}}function At(t){return St(t).values}function kt(t){const{split:e,types:n}=St(t),s=e.length;return t=>{let i="";for(let r=0;r"number"==typeof t?0:bt.test(t)?bt.getAnimatableNone(t):t;const Pt={test:function(t){return isNaN(t)&&"string"==typeof t&&(t.match(rt)?.length||0)+(t.match(Tt)?.length||0)>0},parse:At,createTransformer:kt,getAnimatableNone:function(t){const e=At(t);return kt(t)(e.map(Et))}};function Ct(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<.5?e:n<2/3?t+(e-t)*(2/3-n)*6:t}function Ot({hue:t,saturation:e,lightness:n,alpha:s}){t/=360,n/=100;let i=0,r=0,o=0;if(e/=100){const s=n<.5?n*(1+e):n+e-n*e,a=2*n-s;i=Ct(a,s,t+1/3),r=Ct(a,s,t),o=Ct(a,s,t-1/3)}else i=r=o=n;return{red:Math.round(255*i),green:Math.round(255*r),blue:Math.round(255*o),alpha:s}}function Ft(t,e){return n=>n>0?e:t}const Rt=(t,e,n)=>t+(e-t)*n,Bt=(t,e,n)=>{const s=t*t,i=n*(e*e-s)+s;return i<0?0:Math.sqrt(i)},Lt=[ht,ct,wt];function Dt(t){const e=(n=t,Lt.find(t=>t.test(n)));var n;if(!Boolean(e))return!1;let s=e.parse(t);return e===wt&&(s=Ot(s)),s}const It=(t,e)=>{const n=Dt(t),s=Dt(e);if(!n||!s)return Ft(t,e);const i={...n};return t=>(i.red=Bt(n.red,s.red,t),i.green=Bt(n.green,s.green,t),i.blue=Bt(n.blue,s.blue,t),i.alpha=Rt(n.alpha,s.alpha,t),ct.transform(i))},Wt=new Set(["none","hidden"]);function jt(t,e){return Wt.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function Nt(t,e){return n=>Rt(t,e,n)}function Kt(t){return"number"==typeof t?Nt:"string"==typeof t?Q(t)?Ft:bt.test(t)?It:Yt:Array.isArray(t)?$t:"object"==typeof t?bt.test(t)?It:Ut:Ft}function $t(t,e){const n=[...t],s=n.length,i=t.map((t,n)=>Kt(t)(t,e[n]));return t=>{for(let e=0;e{for(const e in s)n[e]=s[e](t);return n}}const Yt=(t,e)=>{const n=Pt.createTransformer(e),s=St(t),i=St(e);return s.indexes.var.length===i.indexes.var.length&&s.indexes.color.length===i.indexes.color.length&&s.indexes.number.length>=i.indexes.number.length?Wt.has(t)&&!i.values.length||Wt.has(e)&&!s.values.length?jt(t,e):d($t(function(t,e){const n=[],s={color:0,var:0,number:0};for(let i=0;i{const e=({timestamp:e})=>t(e);return{start:(t=!0)=>$.update(e,t),stop:()=>U(e),now:()=>Y.isProcessing?Y.timestamp:G.now()}},Ht=(t,e,n=10)=>{let s="";const i=Math.max(Math.round(e/n),2);for(let e=0;e=Gt?1/0:e}function qt(t,e=100,n){const s=n({...t,keyframes:[0,e]}),i=Math.min(Zt(s),Gt);return{type:"keyframes",ease:t=>s.next(i*t).value/e,duration:g(i)}}function _t(t,e,n){const s=Math.max(e-5,0);return y(n-t(s),e-s)}const Jt=100,Qt=10,te=1,ee=0,ne=800,se=.3,ie=.3,re={granular:.01,default:2},oe={granular:.005,default:.5},ae=.01,le=10,ue=.05,ce=1,he=.001;function de({duration:t=ne,bounce:e=se,velocity:n=ee,mass:i=te}){let r,o,a=1-e;a=s(ue,ce,a),t=s(ae,le,g(t)),a<1?(r=e=>{const s=e*a,i=s*t,r=s-n,o=fe(e,a),l=Math.exp(-i);return he-r/o*l},o=e=>{const s=e*a*t,i=s*n+n,o=Math.pow(a,2)*Math.pow(e,2)*t,l=Math.exp(-s),u=fe(Math.pow(e,2),a);return(-r(e)+he>0?-1:1)*((i-o)*l)/u}):(r=e=>Math.exp(-e*t)*((e-n)*t+1)-.001,o=e=>Math.exp(-e*t)*(t*t*(n-e)));const l=function(t,e,n){let s=n;for(let n=1;nvoid 0!==t[e])}function ve(t=ie,e=se){const n="object"!=typeof t?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:i,restDelta:r}=n;const o=n.keyframes[0],a=n.keyframes[n.keyframes.length-1],l={done:!1,value:o},{stiffness:u,damping:c,mass:h,duration:d,velocity:p,isResolvedFromDuration:f}=function(t){let e={velocity:ee,stiffness:Jt,damping:Qt,mass:te,isResolvedFromDuration:!1,...t};if(!ye(t,ge)&&ye(t,me))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(1.2*n),r=i*i,o=2*s(.05,1,1-(t.bounce||0))*Math.sqrt(r);e={...e,mass:te,stiffness:r,damping:o}}else{const n=de(t);e={...e,...n,mass:te},e.isResolvedFromDuration=!0}return e}({...n,velocity:-g(n.velocity||0)}),y=p||0,v=c/(2*Math.sqrt(u*h)),w=a-o,b=g(Math.sqrt(u/h)),T=Math.abs(w)<5;let x;if(i||(i=T?re.granular:re.default),r||(r=T?oe.granular:oe.default),v<1){const t=fe(b,v);x=e=>{const n=Math.exp(-v*b*e);return a-n*((y+v*b*w)/t*Math.sin(t*e)+w*Math.cos(t*e))}}else if(1===v)x=t=>a-Math.exp(-b*t)*(w+(y+b*w)*t);else{const t=b*Math.sqrt(v*v-1);x=e=>{const n=Math.exp(-v*b*e),s=Math.min(t*e,300);return a-n*((y+v*b*w)*Math.sinh(s)+t*w*Math.cosh(s))/t}}const V={calculatedDuration:f&&d||null,next:t=>{const e=x(t);if(f)l.done=t>=d;else{let n=0===t?y:0;v<1&&(n=0===t?m(y):_t(x,t,e));const s=Math.abs(n)<=i,o=Math.abs(a-e)<=r;l.done=s&&o}return l.value=l.done?a:e,l},toString:()=>{const t=Math.min(Zt(V),Gt),e=Ht(e=>V.next(t*e).value,t,30);return t+"ms "+e},toTransition:()=>{}};return V}function we({keyframes:t,velocity:e=0,power:n=.8,timeConstant:s=325,bounceDamping:i=10,bounceStiffness:r=500,modifyTarget:o,min:a,max:l,restDelta:u=.5,restSpeed:c}){const h=t[0],d={done:!1,value:h},p=t=>void 0===a?l:void 0===l||Math.abs(a-t)-f*Math.exp(-t/s),v=t=>g+y(t),w=t=>{const e=y(t),n=v(t);d.done=Math.abs(e)<=u,d.value=d.done?g:n};let b,T;const x=t=>{var e;(e=d.value,void 0!==a&&el)&&(b=t,T=ve({keyframes:[d.value,p(d.value)],velocity:_t(v,t,d.value),damping:i,stiffness:r,restDelta:u,restSpeed:c}))};return x(0),{calculatedDuration:null,next:t=>{let e=!1;return T||void 0!==b||(e=!0,w(t),x(t)),void 0!==b&&t>=b?T.next(t-b):(!e&&w(t),d)}}}function be(t,e,{clamp:n=!0,ease:i,mixer:o}={}){const a=t.length;if(e.length,1===a)return()=>e[0];if(2===a&&e[0]===e[1])return()=>e[1];const l=t[0]===t[1];t[0]>t[a-1]&&(t=[...t].reverse(),e=[...e].reverse());const u=function(t,e,n){const s=[],i=n||r.mix||zt,o=t.length-1;for(let n=0;n{if(l&&n1)for(;sf(s(t[0],t[a-1],e)):f}function Te(t,e){const n=t[t.length-1];for(let s=1;s<=e;s++){const i=p(0,e,s);t.push(Rt(n,1,i))}}function xe(t){const e=[0];return Te(e,t.length-1),e}function Ve(t,e){return t.map(t=>t*e)}function Me(t,e){return t.map(()=>e||R).splice(0,t.length-1)}function Se({duration:t=300,keyframes:e,times:n,ease:s="easeInOut"}){const i=B(s)?s.map(W):W(s),r={done:!1,value:e[0]},o=be(Ve(n&&n.length===e.length?n:xe(e),t),e,{ease:Array.isArray(i)?i:Me(e,i)});return{calculatedDuration:t,next:e=>(r.value=o(e),r.done=e>=t,r)}}ve.applyToOptions=t=>{const e=qt(t,100,ve);return t.ease=e.ease,t.duration=m(e.duration),t.type="keyframes",t};const Ae=t=>null!==t;function ke(t,{repeat:e,repeatType:n="loop"},s,i=1){const r=t.filter(Ae),o=i<0||e&&"loop"!==n&&e%2==1?0:r.length-1;return o&&void 0!==s?s:r[o]}const Ee={decay:we,inertia:we,tween:Se,keyframes:Se,spring:ve};function Pe(t){"string"==typeof t.type&&(t.type=Ee[t.type])}class Ce{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,e){return this.finished.then(t,e)}}const Oe=t=>t/100;class Fe extends Ce{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:t}=this.options;t&&t.updatedAt!==G.now()&&this.tick(G.now()),this.isStopped=!0,"idle"!==this.state&&(this.teardown(),this.options.onStop?.())},Z.mainThread++,this.options=t,this.initAnimation(),this.play(),!1===t.autoplay&&this.pause()}initAnimation(){const{options:t}=this;Pe(t);const{type:e=Se,repeat:n=0,repeatDelay:s=0,repeatType:i,velocity:r=0}=t;let{keyframes:o}=t;const a=e||Se;a!==Se&&"number"!=typeof o[0]&&(this.mixKeyframes=d(Oe,zt(o[0],o[1])),o=[0,100]);const l=a({...t,keyframes:o});"mirror"===i&&(this.mirroredGenerator=a({...t,keyframes:[...o].reverse(),velocity:-r})),null===l.calculatedDuration&&(l.calculatedDuration=Zt(l));const{calculatedDuration:u}=l;this.calculatedDuration=u,this.resolvedDuration=u+s,this.totalDuration=this.resolvedDuration*(n+1)-s,this.generator=l}updateTime(t){const e=Math.round(t-this.startTime)*this.playbackSpeed;null!==this.holdTime?this.currentTime=this.holdTime:this.currentTime=e}tick(t,e=!1){const{generator:n,totalDuration:i,mixKeyframes:r,mirroredGenerator:o,resolvedDuration:a,calculatedDuration:l}=this;if(null===this.startTime)return n.next(0);const{delay:u=0,keyframes:c,repeat:h,repeatType:d,repeatDelay:p,type:f,onUpdate:m,finalKeyframe:g}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-i/this.speed,this.startTime)),e?this.currentTime=t:this.updateTime(t);const y=this.currentTime-u*(this.playbackSpeed>=0?1:-1),v=this.playbackSpeed>=0?y<0:y>i;this.currentTime=Math.max(y,0),"finished"===this.state&&null===this.holdTime&&(this.currentTime=i);let w=this.currentTime,b=n;if(h){const t=Math.min(this.currentTime,i)/a;let e=Math.floor(t),n=t%1;!n&&t>=1&&(n=1),1===n&&e--,e=Math.min(e,h+1);Boolean(e%2)&&("reverse"===d?(n=1-n,p&&(n-=p/a)):"mirror"===d&&(b=o)),w=s(0,1,n)*a}const T=v?{done:!1,value:c[0]}:b.next(w);r&&(T.value=r(T.value));let{done:x}=T;v||null===l||(x=this.playbackSpeed>=0?this.currentTime>=i:this.currentTime<=0);const V=null===this.holdTime&&("finished"===this.state||"running"===this.state&&x);return V&&f!==we&&(T.value=ke(c,this.options,g,this.speed)),m&&m(T.value),V&&this.finish(),T}then(t,e){return this.finished.then(t,e)}get duration(){return g(this.calculatedDuration)}get time(){return g(this.currentTime)}set time(t){t=m(t),this.currentTime=t,null===this.startTime||null!==this.holdTime||0===this.playbackSpeed?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime(G.now());const e=this.playbackSpeed!==t;this.playbackSpeed=t,e&&(this.time=g(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=Xt,startTime:e}=this.options;this.driver||(this.driver=t(t=>this.tick(t))),this.options.onPlay?.();const n=this.driver.now();"finished"===this.state?(this.updateFinished(),this.startTime=n):null!==this.holdTime?this.startTime=n-this.holdTime:this.startTime||(this.startTime=e??n),"finished"===this.state&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(G.now()),this.holdTime=this.currentTime}complete(){"running"!==this.state&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null,Z.mainThread--}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),t.observe(this)}}function Re(t){for(let e=1;e180*t/Math.PI,Le=t=>{const e=Be(Math.atan2(t[1],t[0]));return Ie(e)},De={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Le,rotateZ:Le,skewX:t=>Be(Math.atan(t[1])),skewY:t=>Be(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Ie=t=>((t%=360)<0&&(t+=360),t),We=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),je=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Ne={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:We,scaleY:je,scale:t=>(We(t)+je(t))/2,rotateX:t=>Ie(Be(Math.atan2(t[6],t[5]))),rotateY:t=>Ie(Be(Math.atan2(-t[2],t[0]))),rotateZ:Le,rotate:Le,skewX:t=>Be(Math.atan(t[4])),skewY:t=>Be(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Ke(t){return t.includes("scale")?1:0}function $e(t,e){if(!t||"none"===t)return Ke(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,i;if(n)s=Ne,i=n;else{const e=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=De,i=e}if(!i)return Ke(e);const r=s[e],o=i[1].split(",").map(Ye);return"function"==typeof r?r(o):o[r]}const Ue=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return $e(n,e)};function Ye(t){return parseFloat(t.trim())}const ze=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Xe=(()=>new Set(ze))(),He=t=>t===et||t===mt,Ge=new Set(["x","y","z"]),Ze=ze.filter(t=>!Ge.has(t));const qe={width:({x:t},{paddingLeft:e="0",paddingRight:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),height:({y:t},{paddingTop:e="0",paddingBottom:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>$e(e,"x"),y:(t,{transform:e})=>$e(e,"y")};qe.translateX=qe.x,qe.translateY=qe.y;const _e=new Set;let Je=!1,Qe=!1,tn=!1;function en(){if(Qe){const t=Array.from(_e).filter(t=>t.needsMeasurement),e=new Set(t.map(t=>t.element)),n=new Map;e.forEach(t=>{const e=function(t){const e=[];return Ze.forEach(n=>{const s=t.getValue(n);void 0!==s&&(e.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),e}(t);e.length&&(n.set(t,e),t.render())}),t.forEach(t=>t.measureInitialState()),e.forEach(t=>{t.render();const e=n.get(t);e&&e.forEach(([e,n])=>{t.getValue(e)?.set(n)})}),t.forEach(t=>t.measureEndState()),t.forEach(t=>{void 0!==t.suspendedScrollY&&window.scrollTo(0,t.suspendedScrollY)})}Qe=!1,Je=!1,_e.forEach(t=>t.complete(tn)),_e.clear()}function nn(){_e.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Qe=!0)})}function sn(){tn=!0,nn(),en(),tn=!1}class rn{constructor(t,e,n,s,i,r=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=e,this.name=n,this.motionValue=s,this.element=i,this.isAsync=r}scheduleResolve(){this.state="scheduled",this.isAsync?(_e.add(this),Je||(Je=!0,$.read(nn),$.resolveKeyframes(en))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:e,element:n,motionValue:s}=this;if(null===t[0]){const i=s?.get(),r=t[t.length-1];if(void 0!==i)t[0]=i;else if(n&&e){const s=n.readValue(e,r);null!=s&&(t[0]=s)}void 0===t[0]&&(t[0]=r),s&&void 0===i&&s.set(t[0])}Re(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),_e.delete(this)}cancel(){"scheduled"===this.state&&(_e.delete(this),this.state="pending")}resume(){"pending"===this.state&&this.scheduleResolve()}}const on=t=>t.startsWith("--");function an(t,e,n){on(e)?t.style.setProperty(e,n):t.style[e]=n}const ln=u(()=>void 0!==window.ScrollTimeline),un={};function cn(t,e){const n=u(t);return()=>un[e]??n()}const hn=cn(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch(t){return!1}return!0},"linearEasing"),dn=([t,e,n,s])=>`cubic-bezier(${t}, ${e}, ${n}, ${s})`,pn={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:dn([0,.65,.55,1]),circOut:dn([.55,0,1,.45]),backIn:dn([.31,.01,.66,-.59]),backOut:dn([.33,1.53,.69,.99])};function fn(t,e){return t?"function"==typeof t?hn()?Ht(t,e):"ease-out":D(t)?dn(t):Array.isArray(t)?t.map(t=>fn(t,e)||pn.easeOut):pn[t]:void 0}function mn(t,e,n,{delay:s=0,duration:i=300,repeat:r=0,repeatType:o="loop",ease:a="easeOut",times:l}={},u=void 0){const c={[e]:n};l&&(c.offset=l);const h=fn(a,i);Array.isArray(h)&&(c.easing=h),N.value&&Z.waapi++;const d={delay:s,duration:i,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:r+1,direction:"reverse"===o?"alternate":"normal"};u&&(d.pseudoElement=u);const p=t.animate(c,d);return N.value&&p.finished.finally(()=>{Z.waapi--}),p}function gn(t){return"function"==typeof t&&"applyToOptions"in t}function yn({type:t,...e}){return gn(t)&&hn()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class vn extends Ce{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:e,name:n,keyframes:s,pseudoElement:i,allowFlatten:r=!1,finalKeyframe:o,onComplete:a}=t;this.isPseudoElement=Boolean(i),this.allowFlatten=r,this.options=t,t.type;const l=yn(t);this.animation=mn(e,n,s,l,i),!1===l.autoplay&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const t=ke(s,this.options,o,this.speed);this.updateMotionValue?this.updateMotionValue(t):an(e,n,t),this.animation.cancel()}a?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),"finished"===this.state&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch(t){}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;"idle"!==t&&"finished"!==t&&(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming?.().duration||0;return g(Number(t))}get time(){return g(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=m(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return null!==this.finishedTime?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:e}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&ln()?(this.animation.timeline=t,c):e(this)}}const wn={anticipate:k,backInOut:A,circInOut:C};function bn(t){"string"==typeof t.ease&&t.ease in wn&&(t.ease=wn[t.ease])}class Tn extends vn{constructor(t){bn(t),Pe(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:e,onUpdate:n,onComplete:s,element:i,...r}=this.options;if(!e)return;if(void 0!==t)return void e.set(t);const o=new Fe({...r,autoplay:!1}),a=m(this.finishedTime??this.time);e.setWithVelocity(o.sample(a-10).value,o.sample(a).value,10),o.stop()}}const xn=(t,e)=>"zIndex"!==e&&(!("number"!=typeof t&&!Array.isArray(t))||!("string"!=typeof t||!Pt.test(t)&&"0"!==t||t.startsWith("url(")));function Vn(t){t.duration=0,t.type}const Mn=new Set(["opacity","clipPath","filter","transform"]),Sn=u(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function An(t){const{motionValue:e,name:n,repeatDelay:s,repeatType:i,damping:r,type:o}=t,a=e?.owner?.current;if(!(a instanceof HTMLElement))return!1;const{onUpdate:l,transformTemplate:u}=e.owner.getProps();return Sn()&&n&&Mn.has(n)&&("transform"!==n||!u)&&!l&&!s&&"mirror"!==i&&0!==r&&"inertia"!==o}class kn extends Ce{constructor({autoplay:t=!0,delay:e=0,type:n="keyframes",repeat:s=0,repeatDelay:i=0,repeatType:r="loop",keyframes:o,name:a,motionValue:l,element:u,...c}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=G.now();const h={autoplay:t,delay:e,type:n,repeat:s,repeatDelay:i,repeatType:r,name:a,motionValue:l,element:u,...c},d=u?.KeyframeResolver||rn;this.keyframeResolver=new d(o,(t,e,n)=>this.onKeyframesResolved(t,e,h,!n),a,l,u),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,e,n,s){this.keyframeResolver=void 0;const{name:i,type:o,velocity:a,delay:l,isHandoff:u,onUpdate:h}=n;this.resolvedAt=G.now(),function(t,e,n,s){const i=t[0];if(null===i)return!1;if("display"===e||"visibility"===e)return!0;const r=t[t.length-1],o=xn(i,e),a=xn(r,e);return!(!o||!a)&&(function(t){const e=t[0];if(1===t.length)return!0;for(let n=0;n40?this.resolvedAt:this.createdAt:void 0,finalKeyframe:e,...n,keyframes:t},p=!u&&An(d)?new Tn({...d,element:d.motionValue.owner.current}):new Fe(d);p.finished.then(()=>this.notifyFinished()).catch(c),this.pendingTimeline&&(this.stopTimeline=p.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=p}get finished(){return this._animation?this.animation.finished:this._finished}then(t,e){return this.finished.finally(t).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),sn()),this._animation}get duration(){return this.animation.duration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}class En{constructor(t){this.stop=()=>this.runAll("stop"),this.animations=t.filter(Boolean)}get finished(){return Promise.all(this.animations.map(t=>t.finished))}getAll(t){return this.animations[0][t]}setAll(t,e){for(let n=0;ne.attachTimeline(t));return()=>{e.forEach((t,e)=>{t&&t(),this.animations[e].stop()})}}get time(){return this.getAll("time")}set time(t){this.setAll("time",t)}get speed(){return this.getAll("speed")}set speed(t){this.setAll("speed",t)}get state(){return this.getAll("state")}get startTime(){return this.getAll("startTime")}get duration(){let t=0;for(let e=0;ee[t]())}play(){this.runAll("play")}pause(){this.runAll("pause")}cancel(){this.runAll("cancel")}complete(){this.runAll("complete")}}class Pn extends En{then(t,e){return this.finished.finally(t).then(()=>{})}}class Cn extends vn{constructor(t){super(),this.animation=t,t.onfinish=()=>{this.finishedTime=this.time,this.notifyFinished()}}}const On=new WeakMap,Fn=(t,e="")=>`${t}:${e}`;function Rn(t){const e=On.get(t)||new Map;return On.set(t,e),e}const Bn=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Ln(t){const e=Bn.exec(t);if(!e)return[,];const[,n,s,i]=e;return[`--${n??s}`,i]}function Dn(t,e,n=1){const[s,i]=Ln(t);if(!s)return;const r=window.getComputedStyle(e).getPropertyValue(s);if(r){const t=r.trim();return o(t)?parseFloat(t):t}return Q(i)?Dn(i,e,n+1):i}function In(t,e){return t?.[e]??t?.default??t}const Wn=new Set(["width","height","top","left","right","bottom",...ze]),jn=t=>e=>e.test(t),Nn=[et,mt,ft,pt,yt,gt,{test:t=>"auto"===t,parse:t=>t}],Kn=t=>Nn.find(jn(t));function $n(t){return"number"==typeof t?0===t:null===t||("none"===t||"0"===t||l(t))}const Un=new Set(["brightness","contrast","saturate","opacity"]);function Yn(t){const[e,n]=t.slice(0,-1).split("(");if("drop-shadow"===e)return t;const[s]=n.match(rt)||[];if(!s)return t;const i=n.replace(s,"");let r=Un.has(e)?1:0;return s!==n&&(r*=100),e+"("+r+i+")"}const zn=/\b([a-z-]*)\(.*?\)/gu,Xn={...Pt,getAnimatableNone:t=>{const e=t.match(zn);return e?e.map(Yn).join(" "):t}},Hn={...et,transform:Math.round},Gn={rotate:pt,rotateX:pt,rotateY:pt,rotateZ:pt,scale:st,scaleX:st,scaleY:st,scaleZ:st,skew:pt,skewX:pt,skewY:pt,distance:mt,translateX:mt,translateY:mt,translateZ:mt,x:mt,y:mt,z:mt,perspective:mt,transformPerspective:mt,opacity:nt,originX:vt,originY:vt,originZ:mt},Zn={borderWidth:mt,borderTopWidth:mt,borderRightWidth:mt,borderBottomWidth:mt,borderLeftWidth:mt,borderRadius:mt,radius:mt,borderTopLeftRadius:mt,borderTopRightRadius:mt,borderBottomRightRadius:mt,borderBottomLeftRadius:mt,width:mt,maxWidth:mt,height:mt,maxHeight:mt,top:mt,right:mt,bottom:mt,left:mt,padding:mt,paddingTop:mt,paddingRight:mt,paddingBottom:mt,paddingLeft:mt,margin:mt,marginTop:mt,marginRight:mt,marginBottom:mt,marginLeft:mt,backgroundPositionX:mt,backgroundPositionY:mt,...Gn,zIndex:Hn,fillOpacity:nt,strokeOpacity:nt,numOctaves:Hn},qn={...Zn,color:bt,backgroundColor:bt,outlineColor:bt,fill:bt,stroke:bt,borderColor:bt,borderTopColor:bt,borderRightColor:bt,borderBottomColor:bt,borderLeftColor:bt,filter:Xn,WebkitFilter:Xn},_n=t=>qn[t];function Jn(t,e){let n=_n(t);return n!==Xn&&(n=Pt),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const Qn=new Set(["auto","none","0"]);class ts extends rn{constructor(t,e,n,s,i){super(t,e,n,s,i,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:e,name:n}=this;if(!e||!e.current)return;super.readKeyframes();for(let n=0;n{t.getValue(e).set(n)}),this.resolveNoneKeyframes()}}const es=new Set(["borderWidth","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderRadius","radius","borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius","width","maxWidth","height","maxHeight","top","right","bottom","left","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","margin","marginTop","marginRight","marginBottom","marginLeft","backgroundPositionX","backgroundPositionY"]);function ns(t,e){for(let n=0;n{try{document.createElement("div").animate({opacity:[1]})}catch(t){return!1}return!0}),is=new Set(["opacity","clipPath","filter","transform"]);function rs(t,e,n){if(t instanceof EventTarget)return[t];if("string"==typeof t){let s=document;e&&(s=e.current);const i=n?.[t]??s.querySelectorAll(t);return i?Array.from(i):[]}return Array.from(t)}function os(t){return(e,n)=>{const s=rs(e),i=[];for(const e of s){const s=t(e,n);i.push(s)}return()=>{for(const t of i)t()}}}const as=(t,e)=>e&&"number"==typeof t?e.transform(t):t;class ls{constructor(){this.latest={},this.values=new Map}set(t,e,n,s,i=!0){const r=this.values.get(t);r&&r.onRemove();const o=()=>{const s=e.get();this.latest[t]=i?as(s,Zn[t]):s,n&&$.render(n)};o();const a=e.on("change",o);s&&e.addDependent(s);const l=()=>{a(),n&&U(n),this.values.delete(t),s&&e.removeDependent(s)};return this.values.set(t,{value:e,onRemove:l}),l}get(t){return this.values.get(t)?.value}destroy(){for(const t of this.values.values())t.onRemove()}}function us(t){const e=new WeakMap,n=[];return(s,i)=>{const r=e.get(s)??new ls;e.set(s,r);for(const e in i){const o=i[e],a=t(s,r,e,o);n.push(a)}return()=>{for(const t of n)t()}}}const cs=(t,e,n,s)=>{const i=function(t,e){if(!(e in t))return!1;const n=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(t),e)||Object.getOwnPropertyDescriptor(t,e);return n&&"function"==typeof n.set}(t,n),r=i?n:n.startsWith("data")||n.startsWith("aria")?n.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`):n;const o=i?()=>{t[r]=e.latest[n]}:()=>{const s=e.latest[n];null==s?t.removeAttribute(r):t.setAttribute(r,String(s))};return e.set(n,s,o)},hs=os(us(cs)),ds=us((t,e,n,s)=>e.set(n,s,()=>{t[n]=e.latest[n]},void 0,!1));function ps(t){return a(t)&&"offsetHeight"in t}const fs={current:void 0};class ms{constructor(t,e={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=t=>{const e=G.now();if(this.updatedAt!==e&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(t),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const t of this.dependents)t.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=e.owner}setCurrent(t){var e;this.current=t,this.updatedAt=G.now(),null===this.canTrackVelocity&&void 0!==t&&(this.canTrackVelocity=(e=this.current,!isNaN(parseFloat(e))))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return this.on("change",t)}on(t,e){this.events[t]||(this.events[t]=new f);const n=this.events[t].add(e);return"change"===t?()=>{n(),$.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,e){this.passiveEffect=t,this.stopPassiveEffect=e}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,e,n){this.set(e),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-n}jump(t,e=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,e&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return fs.current&&fs.current.push(this),this.current}getPrevious(){return this.prev}getVelocity(){const t=G.now();if(!this.canTrackVelocity||void 0===this.prevFrameValue||t-this.updatedAt>30)return 0;const e=Math.min(this.updatedAt-this.prevUpdatedAt,30);return y(parseFloat(this.current)-parseFloat(this.prevFrameValue),e)}start(t){return this.stop(),new Promise(e=>{this.hasAnimated=!0,this.animation=t(e),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function gs(t,e){return new ms(t,e)}const ys={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"};const vs=new Set(["originX","originY","originZ"]),ws=(t,e,n,s)=>{let i,r;return Xe.has(n)?(e.get("transform")||(ps(t)||e.get("transformBox")||ws(t,e,"transformBox",new ms("fill-box")),e.set("transform",new ms("none"),()=>{t.style.transform=function(t){let e="",n=!0;for(let s=0;s{const n=e.latest.originX??"50%",s=e.latest.originY??"50%",i=e.latest.originZ??0;t.style.transformOrigin=`${n} ${s} ${i}`}),r=e.get("transformOrigin")):i=on(n)?()=>{t.style.setProperty(n,e.latest[n])}:()=>{t.style[n]=e.latest[n]},e.set(n,s,i,r)},bs=os(us(ws)),Ts=mt.transform;const xs=os(us((t,e,n,s)=>{if(n.startsWith("path"))return function(t,e,n,s){return $.render(()=>t.setAttribute("pathLength","1")),"pathOffset"===n?e.set(n,s,()=>t.setAttribute("stroke-dashoffset",Ts(-e.latest[n]))):(e.get("stroke-dasharray")||e.set("stroke-dasharray",new ms("1 1"),()=>{const{pathLength:n=1,pathSpacing:s}=e.latest;t.setAttribute("stroke-dasharray",`${Ts(n)} ${Ts(s??1-Number(n))}`)}),e.set(n,s,void 0,e.get("stroke-dasharray")))}(t,e,n,s);if(n.startsWith("attr"))return cs(t,e,function(t){return t.replace(/^attr([A-Z])/,(t,e)=>e.toLowerCase())}(n),s);return(n in t.style?ws:cs)(t,e,n,s)}));const{schedule:Vs,cancel:Ms}=K(queueMicrotask,!1),Ss={x:!1,y:!1};function As(){return Ss.x||Ss.y}function ks(t,e){const n=rs(t),s=new AbortController;return[n,{passive:!0,...e,signal:s.signal},()=>s.abort()]}function Es(t){return!("touch"===t.pointerType||As())}const Ps=(t,e)=>!!e&&(t===e||Ps(t,e.parentElement)),Cs=t=>"mouse"===t.pointerType?"number"!=typeof t.button||t.button<=0:!1!==t.isPrimary,Os=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);const Fs=new WeakSet;function Rs(t){return e=>{"Enter"===e.key&&t(e)}}function Bs(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}function Ls(t){return Cs(t)&&!As()}function Ds(t,e){const n=window.getComputedStyle(t);return on(e)?n.getPropertyValue(e):n[e]}function Is(t){return a(t)&&"ownerSVGElement"in t}const Ws=new WeakMap;let js;const Ns=(t,e,n)=>(s,i)=>i&&i[0]?i[0][t+"Size"]:Is(s)&&"getBBox"in s?s.getBBox()[e]:s[n],Ks=Ns("inline","width","offsetWidth"),$s=Ns("block","height","offsetHeight");function Us({target:t,borderBoxSize:e}){Ws.get(t)?.forEach(n=>{n(t,{get width(){return Ks(t,e)},get height(){return $s(t,e)}})})}function Ys(t){t.forEach(Us)}function zs(t,e){js||"undefined"!=typeof ResizeObserver&&(js=new ResizeObserver(Ys));const n=rs(t);return n.forEach(t=>{let n=Ws.get(t);n||(n=new Set,Ws.set(t,n)),n.add(e),js?.observe(t)}),()=>{n.forEach(t=>{const n=Ws.get(t);n?.delete(e),n?.size||js?.unobserve(t)})}}const Xs=new Set;let Hs;function Gs(t){return Xs.add(t),Hs||(Hs=()=>{const t={get width(){return window.innerWidth},get height(){return window.innerHeight}};Xs.forEach(e=>e(t))},window.addEventListener("resize",Hs)),()=>{Xs.delete(t),Xs.size||"function"!=typeof Hs||(window.removeEventListener("resize",Hs),Hs=void 0)}}function Zs(t,e){return"function"==typeof t?Gs(t):zs(t,e)}function qs(t,e){let n;const s=()=>{const{currentTime:s}=e,i=(null===s?0:s.value)/100;n!==i&&t(i),n=i};return $.preUpdate(s,!0),()=>U(s)}function _s(){const{value:t}=N;null!==t?(t.frameloop.rate.push(Y.delta),t.animations.mainThread.push(Z.mainThread),t.animations.waapi.push(Z.waapi),t.animations.layout.push(Z.layout)):U(_s)}function Js(t){return t.reduce((t,e)=>t+e,0)/t.length}function Qs(t,e=Js){return 0===t.length?{min:0,max:0,avg:0}:{min:Math.min(...t),max:Math.max(...t),avg:e(t)}}const ti=t=>Math.round(1e3/t);function ei(){N.value=null,N.addProjectionMetrics=null}function ni(){const{value:t}=N;if(!t)throw new Error("Stats are not being measured");ei(),U(_s);const e={frameloop:{setup:Qs(t.frameloop.setup),rate:Qs(t.frameloop.rate),read:Qs(t.frameloop.read),resolveKeyframes:Qs(t.frameloop.resolveKeyframes),preUpdate:Qs(t.frameloop.preUpdate),update:Qs(t.frameloop.update),preRender:Qs(t.frameloop.preRender),render:Qs(t.frameloop.render),postRender:Qs(t.frameloop.postRender)},animations:{mainThread:Qs(t.animations.mainThread),waapi:Qs(t.animations.waapi),layout:Qs(t.animations.layout)},layoutProjection:{nodes:Qs(t.layoutProjection.nodes),calculatedTargetDeltas:Qs(t.layoutProjection.calculatedTargetDeltas),calculatedProjections:Qs(t.layoutProjection.calculatedProjections)}},{rate:n}=e.frameloop;return n.min=ti(n.min),n.max=ti(n.max),n.avg=ti(n.avg),[n.min,n.max]=[n.max,n.min],e}function si(t){return Is(t)&&"svg"===t.tagName}function ii(t,e){if("first"===t)return 0;{const n=e-1;return"last"===t?n:n/2}}function ri(...t){const e=!Array.isArray(t[0]),n=e?0:-1,s=t[0+n],i=be(t[1+n],t[2+n],t[3+n]);return e?i(s):i}function oi(t){const e=[];fs.current=e;const n=t();fs.current=void 0;const s=gs(n);return function(t,e,n){const s=()=>e.set(n()),i=()=>$.preRender(s,!1,!0),r=t.map(t=>t.on("change",i));e.on("destroy",()=>{r.forEach(t=>t()),U(s)})}(e,s,t),s}const ai=t=>Boolean(t&&t.getVelocity);function li(t,e,n){const s=t.get();let i,r=null,o=s;const a="string"==typeof s?s.replace(/[\d.-]/g,""):void 0,l=()=>{r&&(r.stop(),r=null)},u=()=>{l(),r=new Fe({keyframes:[ci(t.get()),ci(o)],velocity:t.getVelocity(),type:"spring",restDelta:.001,restSpeed:.01,...n,onUpdate:i})};if(t.attach((e,n)=>(o=e,i=t=>n(ui(t,a)),$.postRender(u),t.get()),l),ai(e)){const n=e.on("change",e=>t.set(ui(e,a))),s=t.on("destroy",n);return()=>{n(),s()}}return l}function ui(t,e){return e?t+e:t}function ci(t){return"number"==typeof t?t:parseFloat(t)}const hi=[...Nn,bt,Pt],di=t=>hi.find(jn(t));function pi(t){return"layout"===t?"group":"enter"===t||"new"===t?"new":"exit"===t||"old"===t?"old":"group"}let fi={},mi=null;const gi=(t,e)=>{fi[t]=e},yi=()=>{mi||(mi=document.createElement("style"),mi.id="motion-view");let t="";for(const e in fi){const n=fi[e];t+=`${e} {\n`;for(const[e,s]of Object.entries(n))t+=` ${e}: ${s};\n`;t+="}\n"}mi.textContent=t,document.head.appendChild(mi),fi={}},vi=()=>{mi&&mi.parentElement&&mi.parentElement.removeChild(mi)};function wi(t){const e=t.match(/::view-transition-(old|new|group|image-pair)\((.*?)\)/);return e?{layer:e[2],type:e[1]}:null}function bi(t){const{effect:e}=t;return!!e&&(e.target===document.documentElement&&e.pseudoElement?.startsWith("::view-transition"))}function Ti(){return document.getAnimations().filter(bi)}const xi=["layout","enter","exit","new","old"];function Vi(t){const{update:e,targets:n,options:s}=t;if(!document.startViewTransition)return new Promise(async t=>{await e(),t(new En([]))});(function(t,e){return e.has(t)&&Object.keys(e.get(t)).length>0})("root",n)||gi(":root",{"view-transition-name":"none"}),gi("::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*)",{"animation-timing-function":"linear !important"}),yi();const i=document.startViewTransition(async()=>{await e()});return i.finished.finally(()=>{vi()}),new Promise(t=>{i.ready.then(()=>{const e=Ti(),i=[];n.forEach((t,e)=>{for(const n of xi){if(!t[n])continue;const{keyframes:r,options:o}=t[n];for(let[t,a]of Object.entries(r)){if(!a)continue;const r={...In(s,t),...In(o,t)},l=pi(n);if("opacity"===t&&!Array.isArray(a)){a=["new"===l?0:1,a]}"function"==typeof r.delay&&(r.delay=r.delay(0,1)),r.duration&&(r.duration=m(r.duration)),r.delay&&(r.delay=m(r.delay));const u=new vn({...r,element:document.documentElement,name:t,pseudoElement:`::view-transition-${l}(${e})`,keyframes:a});i.push(u)}}});for(const t of e){if("finished"===t.playState)continue;const{effect:e}=t;if(!(e&&e instanceof KeyframeEffect))continue;const{pseudoElement:r}=e;if(!r)continue;const o=wi(r);if(!o)continue;const a=n.get(o.layer);if(a)Mi(a,"enter")&&Mi(a,"exit")&&e.getKeyframes().some(t=>t.mixBlendMode)?i.push(new Cn(t)):t.cancel();else{const n="group"===o.type?"layout":"";let r={...In(s,n)};r.duration&&(r.duration=m(r.duration)),r=yn(r);const a=fn(r.ease,r.duration);e.updateTiming({delay:m(r.delay??0),duration:r.duration,easing:a}),i.push(new Cn(t))}}t(new En(i))})})}function Mi(t,e){return t?.[e]?.keyframes.opacity}let Si=[],Ai=null;function ki(){Ai=null;const[t]=Si;var e;t&&(n(Si,e=t),Ai=e,Vi(e).then(t=>{e.notifyReady(t),t.finished.finally(ki)}))}function Ei(){for(let t=Si.length-1;t>=0;t--){const e=Si[t],{interrupt:n}=e.options;if("immediate"===n){const n=Si.slice(0,t+1).map(t=>t.update),s=Si.slice(t+1);e.update=()=>{n.forEach(t=>t())},Si=[e,...s];break}}Ai&&"immediate"!==Si[0]?.options.interrupt||ki()}class Pi{constructor(t,e={}){var n;this.currentSubject="root",this.targets=new Map,this.notifyReady=c,this.readyPromise=new Promise(t=>{this.notifyReady=t}),this.update=t,this.options={interrupt:"wait",...e},n=this,Si.push(n),Vs.render(Ei)}get(t){return this.currentSubject=t,this}layout(t,e){return this.updateTarget("layout",t,e),this}new(t,e){return this.updateTarget("new",t,e),this}old(t,e){return this.updateTarget("old",t,e),this}enter(t,e){return this.updateTarget("enter",t,e),this}exit(t,e){return this.updateTarget("exit",t,e),this}crossfade(t){return this.updateTarget("enter",{opacity:1},t),this.updateTarget("exit",{opacity:0},t),this}updateTarget(t,e,n={}){const{currentSubject:s,targets:i}=this;i.has(s)||i.set(s,{});i.get(s)[t]={keyframes:e,options:n}}then(t,e){return this.readyPromise.then(t,e)}}const Ci=$,Oi=j.reduce((t,e)=>(t[e]=t=>U(t),t),{});function Fi(t){return"object"==typeof t&&!Array.isArray(t)}function Ri(t,e,n,s){return"string"==typeof t&&Fi(e)?rs(t,n,s):t instanceof NodeList?Array.from(t):Array.isArray(t)?t:[t]}function Bi(t,e,n){return t*(e+1)}function Li(t,e,n,s){return"number"==typeof e?e:e.startsWith("-")||e.startsWith("+")?Math.max(0,t+parseFloat(e)):"<"===e?n:e.startsWith("<")?Math.max(0,n+parseFloat(e.slice(1))):s.get(e)??t}function Di(t,e,s,i,r,o){!function(t,e,s){for(let i=0;ie&&r.at"number"==typeof t,Yi=t=>t.every(Ui),zi=new WeakMap;function Xi(t){const e=[{},{}];return t?.values.forEach((t,n)=>{e[0][n]=t.get(),e[1][n]=t.getVelocity()}),e}function Hi(t,e,n,s){if("function"==typeof e){const[i,r]=Xi(s);e=e(void 0!==n?n:t.custom,i,r)}if("string"==typeof e&&(e=t.variants&&t.variants[e]),"function"==typeof e){const[i,r]=Xi(s);e=e(void 0!==n?n:t.custom,i,r)}return e}function Gi(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,gs(n))}function Zi(t){return(t=>Array.isArray(t))(t)?t[t.length-1]||0:t}function qi(t,e){const n=function(t,e,n){const s=t.getProps();return Hi(s,e,void 0!==n?n:s.custom,t)}(t,e);let{transitionEnd:s={},transition:i={},...r}=n||{};r={...r,...s};for(const e in r){Gi(t,e,Zi(r[e]))}}function _i(t,e){const n=t.getValue("willChange");if(s=n,Boolean(ai(s)&&s.add))return n.add(e);if(!n&&r.WillChange){const n=new r.WillChange("auto");t.addValue("willChange",n),n.add(e)}var s}const Ji=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Qi="data-"+Ji("framerAppearId");function tr(t){return t.props[Qi]}const er=t=>null!==t;const nr={type:"spring",stiffness:500,damping:25,restSpeed:10},sr={type:"keyframes",duration:.8},ir={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},rr=(t,{keyframes:e})=>e.length>2?sr:Xe.has(t)?t.startsWith("scale")?{type:"spring",stiffness:550,damping:0===e[1]?2*Math.sqrt(550):30,restSpeed:10}:nr:ir;const or=(t,e,n,s={},i,o)=>a=>{const l=In(s,t)||{},u=l.delay||s.delay||0;let{elapsed:c=0}=s;c-=m(u);const h={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...l,delay:-c,onUpdate:t=>{e.set(t),l.onUpdate&&l.onUpdate(t)},onComplete:()=>{a(),l.onComplete&&l.onComplete()},name:t,motionValue:e,element:o?void 0:i};(function({when:t,delay:e,delayChildren:n,staggerChildren:s,staggerDirection:i,repeat:r,repeatType:o,repeatDelay:a,from:l,elapsed:u,...c}){return!!Object.keys(c).length})(l)||Object.assign(h,rr(t,h)),h.duration&&(h.duration=m(h.duration)),h.repeatDelay&&(h.repeatDelay=m(h.repeatDelay)),void 0!==h.from&&(h.keyframes[0]=h.from);let d=!1;if((!1===h.type||0===h.duration&&!h.repeatDelay)&&(Vn(h),0===h.delay&&(d=!0)),(r.instantAnimations||r.skipAnimations)&&(d=!0,Vn(h),h.delay=0),h.allowFlatten=!l.type&&!l.ease,d&&!o&&void 0!==e.get()){const t=function(t,{repeat:e,repeatType:n="loop"},s){const i=t.filter(er),r=e&&"loop"!==n&&e%2==1?0:i.length-1;return r&&void 0!==s?s:i[r]}(h.keyframes,l);if(void 0!==t)return void $.update(()=>{h.onUpdate(t),h.onComplete()})}return l.isSync?new Fe(h):new kn(h)};function ar({protectedKeys:t,needsAnimating:e},n){const s=t.hasOwnProperty(n)&&!0!==e[n];return e[n]=!1,s}function lr(t,e,{delay:n=0,transitionOverride:s,type:i}={}){let{transition:r=t.getDefaultTransition(),transitionEnd:o,...a}=e;s&&(r=s);const l=[],u=i&&t.animationState&&t.animationState.getState()[i];for(const e in a){const s=t.getValue(e,t.latestValues[e]??null),i=a[e];if(void 0===i||u&&ar(u,e))continue;const o={delay:n,...In(r||{},e)},c=s.get();if(void 0!==c&&!s.isAnimating&&!Array.isArray(i)&&i===c&&!o.velocity)continue;let h=!1;if(window.MotionHandoffAnimation){const n=tr(t);if(n){const t=window.MotionHandoffAnimation(n,e,$);null!==t&&(o.startTime=t,h=!0)}}_i(t,e),s.start(or(e,s,i,t.shouldReduceMotion&&Wn.has(e)?{type:!1}:o,t,h));const d=s.animation;d&&l.push(d)}return o&&Promise.all(l).then(()=>{$.update(()=>{o&&qi(t,o)})}),l}const ur={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},cr={};for(const t in ur)cr[t]={isEnabled:e=>ur[t].some(t=>!!e[t])};const hr=()=>({x:{min:0,max:0},y:{min:0,max:0}}),dr="undefined"!=typeof window,pr={current:null},fr={current:!1};const mr=["initial","animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"];function gr(t){return null!==(e=t.animate)&&"object"==typeof e&&"function"==typeof e.start||mr.some(e=>function(t){return"string"==typeof t||Array.isArray(t)}(t[e]));var e}const yr=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class vr{scrapeMotionValuesFromProps(t,e,n){return{}}constructor({parent:t,props:e,presenceContext:n,reducedMotionConfig:s,blockInitialAnimation:i,visualState:r},o={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=rn,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const t=G.now();this.renderScheduledAtthis.bindToMotionValue(e,t)),fr.current||function(){if(fr.current=!0,dr)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>pr.current=t.matches;t.addEventListener("change",e),e()}else pr.current=!1}(),this.shouldReduceMotion="never"!==this.reducedMotionConfig&&("always"===this.reducedMotionConfig||pr.current),this.parent?.addChild(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),U(this.notifyUpdate),U(this.render),this.valueSubscriptions.forEach(t=>t()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const t in this.events)this.events[t].clear();for(const t in this.features){const e=this.features[t];e&&(e.unmount(),e.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,e){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const n=Xe.has(t);n&&this.onBindTransform&&this.onBindTransform();const s=e.on("change",e=>{this.latestValues[t]=e,this.props.onUpdate&&$.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let i;window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,t,e)),this.valueSubscriptions.set(t,()=>{s(),i&&i(),e.owner&&e.stop()})}sortNodePosition(t){return this.current&&this.sortInstanceNodePosition&&this.type===t.type?this.sortInstanceNodePosition(this.current,t.current):0}updateFeatures(){let t="animation";for(t in cr){const e=cr[t];if(!e)continue;const{isEnabled:n,Feature:s}=e;if(!this.features[t]&&s&&n(this.props)&&(this.features[t]=new s(this)),this.features[t]){const e=this.features[t];e.isMounted?e.update():(e.mount(),e.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):{x:{min:0,max:0},y:{min:0,max:0}}}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,e){this.latestValues[t]=e}update(t,e){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=e;for(let e=0;ee.variantChildren.delete(t)}addValue(t,e){const n=this.values.get(t);e!==n&&(n&&this.removeValue(t),this.bindToMotionValue(t,e),this.values.set(t,e),this.latestValues[t]=e.get())}removeValue(t){this.values.delete(t);const e=this.valueSubscriptions.get(t);e&&(e(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,e){if(this.props.values&&this.props.values[t])return this.props.values[t];let n=this.values.get(t);return void 0===n&&void 0!==e&&(n=gs(null===e?void 0:e,{owner:this}),this.addValue(t,n)),n}readValue(t,e){let n=void 0===this.latestValues[t]&&this.current?this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options):this.latestValues[t];return null!=n&&("string"==typeof n&&(o(n)||l(n))?n=parseFloat(n):!di(n)&&Pt.test(e)&&(n=Jn(t,e)),this.setBaseTarget(t,ai(n)?n.get():n)),ai(n)?n.get():n}setBaseTarget(t,e){this.baseTarget[t]=e}getBaseTarget(t){const{initial:e}=this.props;let n;if("string"==typeof e||"object"==typeof e){const s=Hi(this.props,e,this.presenceContext?.custom);s&&(n=s[t])}if(e&&void 0!==n)return n;const s=this.getBaseTargetFromProps(this.props,t);return void 0===s||ai(s)?void 0!==this.initialValues[t]&&void 0===n?void 0:this.baseTarget[t]:s}on(t,e){return this.events[t]||(this.events[t]=new f),this.events[t].add(e)}notify(t,...e){this.events[t]&&this.events[t].notify(...e)}scheduleRenderMicrotask(){Vs.render(this.render)}}class wr extends vr{constructor(){super(...arguments),this.KeyframeResolver=ts}sortInstanceNodePosition(t,e){return 2&t.compareDocumentPosition(e)?1:-1}getBaseTargetFromProps(t,e){return t.style?t.style[e]:void 0}removeValueFromRenderState(t,{vars:e,style:n}){delete e[t],delete n[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;ai(t)&&(this.childSubscription=t.on("change",t=>{this.current&&(this.current.textContent=`${t}`)}))}}const br={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Tr=ze.length;function xr(t,e,n){const{style:s,vars:i,transformOrigin:r}=t;let o=!1,a=!1;for(const t in e){const n=e[t];if(Xe.has(t))o=!0;else if(_(t))i[t]=n;else{const e=as(n,Zn[t]);t.startsWith("origin")?(a=!0,r[t]=e):s[t]=e}}if(e.transform||(o||n?s.transform=function(t,e,n){let s="",i=!0;for(let r=0;r{const l=Ki(t),{delay:u=0,times:c=xe(l),type:p="keyframes",repeat:f,repeatType:g,repeatDelay:v=0,...w}=n;let{ease:b=e.ease||"easeOut",duration:T}=n;const x="function"==typeof u?u(o,a):u,V=l.length,M=gn(p)?p:i?.[p||"keyframes"];if(V<=2&&M){let t=100;if(2===V&&Yi(l)){const e=l[1]-l[0];t=Math.abs(e)}const e={...w};void 0!==T&&(e.duration=m(T));const n=qt(e,t,M);b=n.ease,T=n.duration}T??(T=r);const S=h+x;1===c.length&&0===c[0]&&(c[1]=1);const A=c.length-l.length;if(A>0&&Te(c,A),1===l.length&&l.unshift(null),f){T=Bi(T,f);const t=[...l],e=[...c];b=Array.isArray(b)?[...b]:[b];const n=[...b];for(let s=0;s{for(const i in t){const r=t[i];r.sort(Wi);const a=[],l=[],u=[];for(let t=0;t{s.push(...Dr(n,t,e))}),s}function Wr(t){return function(e,s,i){let r=[];var o;o=e,r=Array.isArray(o)&&o.some(Array.isArray)?Ir(e,s,t):Dr(e,s,i,t);const a=new Pn(r);return t&&(t.animations.push(a),a.finished.then(()=>{n(t.animations,a)})),a}}const jr=Wr();const Nr=t=>function(e,n,s){return new Pn(function(t,e,n,s){const i=rs(t,s),r=i.length,o=[];for(let t=0;te.delete(n)),a.push(i)}return a}(e,n,s,t))},Kr=Nr(),$r={x:{length:"Width",position:"Left"},y:{length:"Height",position:"Top"}};function Ur(t,e,n,s){const i=n[e],{length:r,position:o}=$r[e],a=i.current,l=n.time;i.current=t[`scroll${o}`],i.scrollLength=t[`scroll${r}`]-t[`client${r}`],i.offset.length=0,i.offset[0]=0,i.offset[1]=i.scrollLength,i.progress=p(0,i.scrollLength,i.current);const u=s-l;i.velocity=u>50?0:y(i.current-a,u)}const Yr={start:0,center:.5,end:1};function zr(t,e,n=0){let s=0;if(t in Yr&&(t=Yr[t]),"string"==typeof t){const e=parseFloat(t);t.endsWith("px")?s=e:t.endsWith("%")?t=e/100:t.endsWith("vw")?s=e/100*document.documentElement.clientWidth:t.endsWith("vh")?s=e/100*document.documentElement.clientHeight:t=e}return"number"==typeof t&&(s=e*t),n+s}const Xr=[0,0];function Hr(t,e,n,s){let i=Array.isArray(t)?t:Xr,r=0,o=0;return"number"==typeof t?i=[t,t]:"string"==typeof t&&(i=(t=t.trim()).includes(" ")?t.split(" "):[t,Yr[t]?t:"0"]),r=zr(i[0],n,s),o=zr(i[1],e),r-o}const Gr={Enter:[[0,1],[1,1]],Exit:[[0,0],[1,0]],Any:[[1,0],[0,1]],All:[[0,0],[1,1]]},Zr={x:0,y:0};function qr(t,e,n){const{offset:i=Gr.All}=n,{target:r=t,axis:o="y"}=n,a="y"===o?"height":"width",l=r!==t?function(t,e){const n={x:0,y:0};let s=t;for(;s&&s!==e;)if(ps(s))n.x+=s.offsetLeft,n.y+=s.offsetTop,s=s.offsetParent;else if("svg"===s.tagName){const t=s.getBoundingClientRect();s=s.parentElement;const e=s.getBoundingClientRect();n.x+=t.left-e.left,n.y+=t.top-e.top}else{if(!(s instanceof SVGGraphicsElement))break;{const{x:t,y:e}=s.getBBox();n.x+=t,n.y+=e;let i=null,r=s.parentNode;for(;!i;)"svg"===r.tagName&&(i=r),r=s.parentNode;s=i}}return n}(r,t):Zr,u=r===t?{width:t.scrollWidth,height:t.scrollHeight}:function(t){return"getBBox"in t&&"svg"!==t.tagName?t.getBBox():{width:t.clientWidth,height:t.clientHeight}}(r),c={width:t.clientWidth,height:t.clientHeight};e[o].offset.length=0;let h=!e[o].interpolate;const d=i.length;for(let t=0;t{!function(t,e=t,n){if(n.x.targetOffset=0,n.y.targetOffset=0,e!==t){let s=e;for(;s&&s!==t;)n.x.targetOffset+=s.offsetLeft,n.y.targetOffset+=s.offsetTop,s=s.offsetParent}n.x.targetLength=e===t?e.scrollWidth:e.clientWidth,n.y.targetLength=e===t?e.scrollHeight:e.clientHeight,n.x.containerLength=t.clientWidth,n.y.containerLength=t.clientHeight}(t,s.target,n),function(t,e,n){Ur(t,"x",e,n),Ur(t,"y",e,n),e.time=n}(t,n,e),(s.offset||s.target)&&qr(t,n,s)},notify:()=>e(n)}}const Jr=new WeakMap,Qr=new WeakMap,to=new WeakMap,eo=t=>t===document.scrollingElement?window:t;function no(t,{container:e=document.scrollingElement,...n}={}){if(!e)return c;let s=to.get(e);s||(s=new Set,to.set(e,s));const i=_r(e,t,{time:0,x:{current:0,offset:[],progress:0,scrollLength:0,targetOffset:0,targetLength:0,containerLength:0,velocity:0},y:{current:0,offset:[],progress:0,scrollLength:0,targetOffset:0,targetLength:0,containerLength:0,velocity:0}},n);if(s.add(i),!Jr.has(e)){const t=()=>{for(const t of s)t.measure(Y.timestamp);$.preUpdate(n)},n=()=>{for(const t of s)t.notify()},i=()=>$.read(t);Jr.set(e,i);const r=eo(e);window.addEventListener("resize",i,{passive:!0}),e!==document.documentElement&&Qr.set(e,Zs(e,i)),r.addEventListener("scroll",i,{passive:!0}),i()}const r=Jr.get(e);return $.read(r,!1,!0),()=>{U(r);const t=to.get(e);if(!t)return;if(t.delete(i),t.size)return;const n=Jr.get(e);Jr.delete(e),n&&(eo(e).removeEventListener("scroll",n),Qr.get(e)?.(),window.removeEventListener("resize",n))}}const so=new Map;function io({source:t,container:e,...n}){const{axis:s}=n;t&&(e=t);const i=so.get(e)??new Map;so.set(e,i);const r=n.target??"self",o=i.get(r)??{},a=s+(n.offset??[]).join(",");return o[a]||(o[a]=!n.target&&ln()?new ScrollTimeline({source:e,axis:s}):function(t){const e={value:0},n=no(n=>{e.value=100*n[t.axis].progress},t);return{currentTime:e,cancel:n}}({container:e,...n})),o[a]}const ro={some:0,all:1};const oo=(t,e)=>Math.abs(t-e);t.AsyncMotionValueAnimation=kn,t.DOMKeyframesResolver=ts,t.GroupAnimation=En,t.GroupAnimationWithThen=Pn,t.JSAnimation=Fe,t.KeyframeResolver=rn,t.MotionGlobalConfig=r,t.MotionValue=ms,t.NativeAnimation=vn,t.NativeAnimationExtended=Tn,t.NativeAnimationWrapper=Cn,t.SubscriptionManager=f,t.ViewTransitionBuilder=Pi,t.acceleratedValues=is,t.activeAnimations=Z,t.addAttrValue=cs,t.addStyleValue=ws,t.addUniqueItem=e,t.alpha=nt,t.analyseComplexValue=St,t.animate=jr,t.animateMini=Kr,t.animateValue=function(t){return new Fe(t)},t.animateView=function(t,e={}){return new Pi(t,e)},t.animationMapKey=Fn,t.anticipate=k,t.applyGeneratorOptions=yn,t.applyPxDefaults=ns,t.attachSpring=li,t.attrEffect=hs,t.backIn=S,t.backInOut=A,t.backOut=M,t.calcGeneratorDuration=Zt,t.cancelFrame=U,t.cancelMicrotask=Ms,t.cancelSync=Oi,t.circIn=E,t.circInOut=C,t.circOut=P,t.clamp=s,t.collectMotionValues=fs,t.color=bt,t.complex=Pt,t.convertOffsetToTimes=Ve,t.createGeneratorEasing=qt,t.createRenderBatcher=K,t.createScopedAnimate=Wr,t.cubicBezier=T,t.cubicBezierAsString=dn,t.defaultEasing=Me,t.defaultOffset=xe,t.defaultTransformValue=Ke,t.defaultValueTypes=qn,t.degrees=pt,t.delay=function(t,e){return function(t,e){const n=G.now(),s=({timestamp:i})=>{const r=i-n;r>=e&&(U(s),t(r-e))};return $.setup(s,!0),()=>U(s)}(t,m(e))},t.dimensionValueTypes=Nn,t.distance=oo,t.distance2D=function(t,e){const n=oo(t.x,e.x),s=oo(t.y,e.y);return Math.sqrt(n**2+s**2)},t.easeIn=O,t.easeInOut=R,t.easeOut=F,t.easingDefinitionToFunction=W,t.fillOffset=Te,t.fillWildcards=Re,t.findDimensionValueType=Kn,t.findValueType=di,t.flushKeyframeResolvers=sn,t.frame=$,t.frameData=Y,t.frameSteps=z,t.generateLinearEasing=Ht,t.getAnimatableNone=Jn,t.getAnimationMap=Rn,t.getComputedStyle=Ds,t.getDefaultValueType=_n,t.getEasingForSegment=L,t.getMixer=Kt,t.getOriginIndex=ii,t.getValueAsType=as,t.getValueTransition=In,t.getVariableValue=Dn,t.getViewAnimationLayerInfo=wi,t.getViewAnimations=Ti,t.hasWarned=function(t){return v.has(t)},t.hex=ht,t.hover=function(t,e,n={}){const[s,i,r]=ks(t,n),o=t=>{if(!Es(t))return;const{target:n}=t,s=e(n,t);if("function"!=typeof s||!n)return;const r=t=>{Es(t)&&(s(t),n.removeEventListener("pointerleave",r))};n.addEventListener("pointerleave",r,i)};return s.forEach(t=>{t.addEventListener("pointerenter",o,i)}),r},t.hsla=wt,t.hslaToRgba=Ot,t.inView=function(t,e,{root:n,margin:s,amount:i="some"}={}){const r=rs(t),o=new WeakMap,a=new IntersectionObserver(t=>{t.forEach(t=>{const n=o.get(t.target);if(t.isIntersecting!==Boolean(n))if(t.isIntersecting){const n=e(t.target,t);"function"==typeof n?o.set(t.target,n):a.unobserve(t.target)}else"function"==typeof n&&(n(t),o.delete(t.target))})},{root:n,rootMargin:s,threshold:"number"==typeof i?i:ro[i]});return r.forEach(t=>a.observe(t)),()=>a.disconnect()},t.inertia=we,t.interpolate=be,t.invariant=i,t.invisibleValues=Wt,t.isBezierDefinition=D,t.isCSSVariableName=_,t.isCSSVariableToken=Q,t.isDragActive=As,t.isDragging=Ss,t.isEasingArray=B,t.isGenerator=gn,t.isHTMLElement=ps,t.isMotionValue=ai,t.isNodeOrChild=Ps,t.isNumericalString=o,t.isObject=a,t.isPrimaryPointer=Cs,t.isSVGElement=Is,t.isSVGSVGElement=si,t.isWaapiSupportedEasing=function t(e){return Boolean("function"==typeof e&&hn()||!e||"string"==typeof e&&(e in pn||hn())||D(e)||Array.isArray(e)&&e.every(t))},t.isZeroValueString=l,t.keyframes=Se,t.makeAnimationInstant=Vn,t.mapEasingToNativeEasing=fn,t.mapValue=function(t,e,n,s){const i=ri(e,n,s);return oi(()=>i(t.get()))},t.maxGeneratorDuration=Gt,t.memo=u,t.microtask=Vs,t.millisecondsToSeconds=g,t.mirrorEasing=x,t.mix=zt,t.mixArray=$t,t.mixColor=It,t.mixComplex=Yt,t.mixImmediate=Ft,t.mixLinearColor=Bt,t.mixNumber=Rt,t.mixObject=Ut,t.mixVisibility=jt,t.motionValue=gs,t.moveItem=function([...t],e,n){const s=e<0?t.length+e:e;if(s>=0&&s{const s=t.currentTarget;if(!Ls(t))return;Fs.add(s);const r=e(s,t),o=(t,e)=>{window.removeEventListener("pointerup",a),window.removeEventListener("pointercancel",l),Fs.has(s)&&Fs.delete(s),Ls(t)&&"function"==typeof r&&r(t,{success:e})},a=t=>{o(t,s===window||s===document||n.useGlobalTarget||Ps(s,t.target))},l=t=>{o(t,!1)};window.addEventListener("pointerup",a,i),window.addEventListener("pointercancel",l,i)};return s.forEach(t=>{var e;(n.useGlobalTarget?window:t).addEventListener("pointerdown",o,i),ps(t)&&(t.addEventListener("focus",t=>((t,e)=>{const n=t.currentTarget;if(!n)return;const s=Rs(()=>{if(Fs.has(n))return;Bs(n,"down");const t=Rs(()=>{Bs(n,"up")});n.addEventListener("keyup",t,e),n.addEventListener("blur",()=>Bs(n,"cancel"),e)});n.addEventListener("keydown",s,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",s),e)})(t,i)),e=t,Os.has(e.tagName)||-1!==e.tabIndex||t.hasAttribute("tabindex")||(t.tabIndex=0))}),r},t.progress=p,t.progressPercentage=vt,t.propEffect=ds,t.px=mt,t.readTransformValue=Ue,t.recordStats=function(){if(N.value)throw ei(),new Error("Stats are already being measured");const t=N;return t.value={frameloop:{setup:[],rate:[],read:[],resolveKeyframes:[],preUpdate:[],update:[],preRender:[],render:[],postRender:[]},animations:{mainThread:[],waapi:[],layout:[]},layoutProjection:{nodes:[],calculatedTargetDeltas:[],calculatedProjections:[]}},t.addProjectionMetrics=e=>{const{layoutProjection:n}=t.value;n.nodes.push(e.nodes),n.calculatedTargetDeltas.push(e.calculatedTargetDeltas),n.calculatedProjections.push(e.calculatedProjections)},$.postRender(_s,!0),ni},t.removeItem=n,t.resize=Zs,t.resolveElements=rs,t.reverseEasing=V,t.rgbUnit=ut,t.rgba=ct,t.scale=st,t.scroll=function(t,{axis:e="y",container:n=document.scrollingElement,...s}={}){if(!n)return c;const i={axis:e,container:n,...s};return"function"==typeof t?function(t,e){return function(t){return 2===t.length}(t)?no(n=>{t(n[e.axis].progress,n)},e):qs(t,io(e))}(t,i):function(t,e){const n=io(e);return t.attachTimeline({timeline:e.target?void 0:n,observe:t=>(t.pause(),qs(e=>{t.time=t.duration*e},n))})}(t,i)},t.scrollInfo=no,t.secondsToMilliseconds=m,t.setDragLock=function(t){return"x"===t||"y"===t?Ss[t]?null:(Ss[t]=!0,()=>{Ss[t]=!1}):Ss.x||Ss.y?null:(Ss.x=Ss.y=!0,()=>{Ss.x=Ss.y=!1})},t.setStyle=an,t.spring=ve,t.springValue=function(t,e){const n=gs(ai(t)?t.get():t);return li(n,t,e),n},t.stagger=function(t=.1,{startDelay:e=0,from:n=0,ease:s}={}){return(i,r)=>{const o="number"==typeof n?n:ii(n,r),a=Math.abs(o-i);let l=t*a;if(s){const e=r*t;l=W(s)(l/e)*e}return e+l}},t.startWaapiAnimation=mn,t.statsBuffer=N,t.steps=function(t,e="end"){return n=>{const i=(n="end"===e?Math.min(n,.999):Math.max(n,.001))*t,r="end"===e?Math.floor(i):Math.ceil(i);return s(0,1,r/t)}},t.styleEffect=bs,t.supportedWaapiEasing=pn,t.supportsBrowserAnimation=An,t.supportsFlags=un,t.supportsLinearEasing=hn,t.supportsPartialKeyframes=ss,t.supportsScrollTimeline=ln,t.svgEffect=xs,t.sync=Ci,t.testValueType=jn,t.time=G,t.transform=ri,t.transformPropOrder=ze,t.transformProps=Xe,t.transformValue=oi,t.transformValueTypes=Gn,t.velocityPerSecond=y,t.vh=gt,t.vw=yt,t.warnOnce=function(t,e,n){t||v.has(e)||(console.warn(function(t,e){return e?`${t}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${e}`:t}(e,n)),v.add(e))},t.warning=()=>{},t.wrap=w}); diff --git a/frontend/node_modules/framer-motion/dist/es/animation/animate/index.mjs b/frontend/node_modules/framer-motion/dist/es/animation/animate/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1171458f6de7393f4a75f47c7997717b585efe3f --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/animate/index.mjs @@ -0,0 +1,38 @@ +import { GroupAnimationWithThen } from 'motion-dom'; +import { removeItem } from 'motion-utils'; +import { animateSequence } from './sequence.mjs'; +import { animateSubject } from './subject.mjs'; + +function isSequence(value) { + return Array.isArray(value) && value.some(Array.isArray); +} +/** + * Creates an animation function that is optionally scoped + * to a specific element. + */ +function createScopedAnimate(scope) { + /** + * Implementation + */ + function scopedAnimate(subjectOrSequence, optionsOrKeyframes, options) { + let animations = []; + if (isSequence(subjectOrSequence)) { + animations = animateSequence(subjectOrSequence, optionsOrKeyframes, scope); + } + else { + animations = animateSubject(subjectOrSequence, optionsOrKeyframes, options, scope); + } + const animation = new GroupAnimationWithThen(animations); + if (scope) { + scope.animations.push(animation); + animation.finished.then(() => { + removeItem(scope.animations, animation); + }); + } + return animation; + } + return scopedAnimate; +} +const animate = createScopedAnimate(); + +export { animate, createScopedAnimate }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/animate/resolve-subjects.mjs b/frontend/node_modules/framer-motion/dist/es/animation/animate/resolve-subjects.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cb9c63d6558cb8c58f5a532d1bc5279d6ca89571 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/animate/resolve-subjects.mjs @@ -0,0 +1,19 @@ +import { resolveElements } from 'motion-dom'; +import { isDOMKeyframes } from '../utils/is-dom-keyframes.mjs'; + +function resolveSubjects(subject, keyframes, scope, selectorCache) { + if (typeof subject === "string" && isDOMKeyframes(keyframes)) { + return resolveElements(subject, scope, selectorCache); + } + else if (subject instanceof NodeList) { + return Array.from(subject); + } + else if (Array.isArray(subject)) { + return subject; + } + else { + return [subject]; + } +} + +export { resolveSubjects }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/animate/sequence.mjs b/frontend/node_modules/framer-motion/dist/es/animation/animate/sequence.mjs new file mode 100644 index 0000000000000000000000000000000000000000..52a1f920a421c03eafd3b1d205275ac6adcd588a --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/animate/sequence.mjs @@ -0,0 +1,14 @@ +import { spring } from 'motion-dom'; +import { createAnimationsFromSequence } from '../sequence/create.mjs'; +import { animateSubject } from './subject.mjs'; + +function animateSequence(sequence, options, scope) { + const animations = []; + const animationDefinitions = createAnimationsFromSequence(sequence, options, scope, { spring }); + animationDefinitions.forEach(({ keyframes, transition }, subject) => { + animations.push(...animateSubject(subject, keyframes, transition)); + }); + return animations; +} + +export { animateSequence }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/animate/single-value.mjs b/frontend/node_modules/framer-motion/dist/es/animation/animate/single-value.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b92156c454f5b470aeee27fcfbe5891eef6a8db2 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/animate/single-value.mjs @@ -0,0 +1,10 @@ +import { isMotionValue, motionValue } from 'motion-dom'; +import { animateMotionValue } from '../interfaces/motion-value.mjs'; + +function animateSingleValue(value, keyframes, options) { + const motionValue$1 = isMotionValue(value) ? value : motionValue(value); + motionValue$1.start(animateMotionValue("", motionValue$1, keyframes, options)); + return motionValue$1.animation; +} + +export { animateSingleValue }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/animate/subject.mjs b/frontend/node_modules/framer-motion/dist/es/animation/animate/subject.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4c80ed5bb7dc75f848cb6b8eee53c7a7c88ab7fb --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/animate/subject.mjs @@ -0,0 +1,53 @@ +import { isMotionValue } from 'motion-dom'; +import { invariant } from 'motion-utils'; +import { visualElementStore } from '../../render/store.mjs'; +import { animateTarget } from '../interfaces/visual-element-target.mjs'; +import { createDOMVisualElement, createObjectVisualElement } from '../utils/create-visual-element.mjs'; +import { isDOMKeyframes } from '../utils/is-dom-keyframes.mjs'; +import { resolveSubjects } from './resolve-subjects.mjs'; +import { animateSingleValue } from './single-value.mjs'; + +function isSingleValue(subject, keyframes) { + return (isMotionValue(subject) || + typeof subject === "number" || + (typeof subject === "string" && !isDOMKeyframes(keyframes))); +} +/** + * Implementation + */ +function animateSubject(subject, keyframes, options, scope) { + const animations = []; + if (isSingleValue(subject, keyframes)) { + animations.push(animateSingleValue(subject, isDOMKeyframes(keyframes) + ? keyframes.default || keyframes + : keyframes, options ? options.default || options : options)); + } + else { + const subjects = resolveSubjects(subject, keyframes, scope); + const numSubjects = subjects.length; + invariant(Boolean(numSubjects), "No valid elements provided.", "no-valid-elements"); + for (let i = 0; i < numSubjects; i++) { + const thisSubject = subjects[i]; + invariant(thisSubject !== null, "You're trying to perform an animation on null. Ensure that selectors are correctly finding elements and refs are correctly hydrated.", "animate-null"); + const createVisualElement = thisSubject instanceof Element + ? createDOMVisualElement + : createObjectVisualElement; + if (!visualElementStore.has(thisSubject)) { + createVisualElement(thisSubject); + } + const visualElement = visualElementStore.get(thisSubject); + const transition = { ...options }; + /** + * Resolve stagger function if provided. + */ + if ("delay" in transition && + typeof transition.delay === "function") { + transition.delay = transition.delay(i, numSubjects); + } + animations.push(...animateTarget(visualElement, { ...keyframes, transition }, {})); + } + } + return animations; +} + +export { animateSubject }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/animators/waapi/animate-elements.mjs b/frontend/node_modules/framer-motion/dist/es/animation/animators/waapi/animate-elements.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6c5125be6a2ad3474bff927d56bae7f253aaceed --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/animators/waapi/animate-elements.mjs @@ -0,0 +1,105 @@ +import { resolveElements, getValueTransition, getAnimationMap, animationMapKey, getComputedStyle, fillWildcards, applyPxDefaults, NativeAnimation } from 'motion-dom'; +import { invariant, secondsToMilliseconds } from 'motion-utils'; + +function animateElements(elementOrSelector, keyframes, options, scope) { + const elements = resolveElements(elementOrSelector, scope); + const numElements = elements.length; + invariant(Boolean(numElements), "No valid elements provided.", "no-valid-elements"); + /** + * WAAPI doesn't support interrupting animations. + * + * Therefore, starting animations requires a three-step process: + * 1. Stop existing animations (write styles to DOM) + * 2. Resolve keyframes (read styles from DOM) + * 3. Create new animations (write styles to DOM) + * + * The hybrid `animate()` function uses AsyncAnimation to resolve + * keyframes before creating new animations, which removes style + * thrashing. Here, we have much stricter filesize constraints. + * Therefore we do this in a synchronous way that ensures that + * at least within `animate()` calls there is no style thrashing. + * + * In the motion-native-animate-mini-interrupt benchmark this + * was 80% faster than a single loop. + */ + const animationDefinitions = []; + /** + * Step 1: Build options and stop existing animations (write) + */ + for (let i = 0; i < numElements; i++) { + const element = elements[i]; + const elementTransition = { ...options }; + /** + * Resolve stagger function if provided. + */ + if (typeof elementTransition.delay === "function") { + elementTransition.delay = elementTransition.delay(i, numElements); + } + for (const valueName in keyframes) { + let valueKeyframes = keyframes[valueName]; + if (!Array.isArray(valueKeyframes)) { + valueKeyframes = [valueKeyframes]; + } + const valueOptions = { + ...getValueTransition(elementTransition, valueName), + }; + valueOptions.duration && (valueOptions.duration = secondsToMilliseconds(valueOptions.duration)); + valueOptions.delay && (valueOptions.delay = secondsToMilliseconds(valueOptions.delay)); + /** + * If there's an existing animation playing on this element then stop it + * before creating a new one. + */ + const map = getAnimationMap(element); + const key = animationMapKey(valueName, valueOptions.pseudoElement || ""); + const currentAnimation = map.get(key); + currentAnimation && currentAnimation.stop(); + animationDefinitions.push({ + map, + key, + unresolvedKeyframes: valueKeyframes, + options: { + ...valueOptions, + element, + name: valueName, + allowFlatten: !elementTransition.type && !elementTransition.ease, + }, + }); + } + } + /** + * Step 2: Resolve keyframes (read) + */ + for (let i = 0; i < animationDefinitions.length; i++) { + const { unresolvedKeyframes, options: animationOptions } = animationDefinitions[i]; + const { element, name, pseudoElement } = animationOptions; + if (!pseudoElement && unresolvedKeyframes[0] === null) { + unresolvedKeyframes[0] = getComputedStyle(element, name); + } + fillWildcards(unresolvedKeyframes); + applyPxDefaults(unresolvedKeyframes, name); + /** + * If we only have one keyframe, explicitly read the initial keyframe + * from the computed style. This is to ensure consistency with WAAPI behaviour + * for restarting animations, for instance .play() after finish, when it + * has one vs two keyframes. + */ + if (!pseudoElement && unresolvedKeyframes.length < 2) { + unresolvedKeyframes.unshift(getComputedStyle(element, name)); + } + animationOptions.keyframes = unresolvedKeyframes; + } + /** + * Step 3: Create new animations (write) + */ + const animations = []; + for (let i = 0; i < animationDefinitions.length; i++) { + const { map, key, options: animationOptions } = animationDefinitions[i]; + const animation = new NativeAnimation(animationOptions); + map.set(key, animation); + animation.finished.finally(() => map.delete(key)); + animations.push(animation); + } + return animations; +} + +export { animateElements }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/animators/waapi/animate-sequence.mjs b/frontend/node_modules/framer-motion/dist/es/animation/animators/waapi/animate-sequence.mjs new file mode 100644 index 0000000000000000000000000000000000000000..43f1075b889ab38bc9305335b8eda60b8382751d --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/animators/waapi/animate-sequence.mjs @@ -0,0 +1,13 @@ +import { GroupAnimationWithThen } from 'motion-dom'; +import { createAnimationsFromSequence } from '../../sequence/create.mjs'; +import { animateElements } from './animate-elements.mjs'; + +function animateSequence(definition, options) { + const animations = []; + createAnimationsFromSequence(definition, options).forEach(({ keyframes, transition }, element) => { + animations.push(...animateElements(element, keyframes, transition)); + }); + return new GroupAnimationWithThen(animations); +} + +export { animateSequence }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/animators/waapi/animate-style.mjs b/frontend/node_modules/framer-motion/dist/es/animation/animators/waapi/animate-style.mjs new file mode 100644 index 0000000000000000000000000000000000000000..72a7b2ceaa2f66ddb20d30850f0be79957981352 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/animators/waapi/animate-style.mjs @@ -0,0 +1,12 @@ +import { GroupAnimationWithThen } from 'motion-dom'; +import { animateElements } from './animate-elements.mjs'; + +const createScopedWaapiAnimate = (scope) => { + function scopedAnimate(elementOrSelector, keyframes, options) { + return new GroupAnimationWithThen(animateElements(elementOrSelector, keyframes, options, scope)); + } + return scopedAnimate; +}; +const animateMini = /*@__PURE__*/ createScopedWaapiAnimate(); + +export { animateMini, createScopedWaapiAnimate }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/animators/waapi/utils/get-final-keyframe.mjs b/frontend/node_modules/framer-motion/dist/es/animation/animators/waapi/utils/get-final-keyframe.mjs new file mode 100644 index 0000000000000000000000000000000000000000..508516101bb0ed7286e23a1bc7e730edc8891d00 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/animators/waapi/utils/get-final-keyframe.mjs @@ -0,0 +1,12 @@ +const isNotNull = (value) => value !== null; +function getFinalKeyframe(keyframes, { repeat, repeatType = "loop" }, finalKeyframe) { + const resolvedKeyframes = keyframes.filter(isNotNull); + const index = repeat && repeatType !== "loop" && repeat % 2 === 1 + ? 0 + : resolvedKeyframes.length - 1; + return !index || finalKeyframe === undefined + ? resolvedKeyframes[index] + : finalKeyframe; +} + +export { getFinalKeyframe }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/hooks/animation-controls.mjs b/frontend/node_modules/framer-motion/dist/es/animation/hooks/animation-controls.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7edc5e211301dcdfb83a4cd7cd784cf4b659fdf1 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/hooks/animation-controls.mjs @@ -0,0 +1,80 @@ +import { invariant } from 'motion-utils'; +import { setTarget } from '../../render/utils/setters.mjs'; +import { animateVisualElement } from '../interfaces/visual-element.mjs'; + +function stopAnimation(visualElement) { + visualElement.values.forEach((value) => value.stop()); +} +function setVariants(visualElement, variantLabels) { + const reversedLabels = [...variantLabels].reverse(); + reversedLabels.forEach((key) => { + const variant = visualElement.getVariant(key); + variant && setTarget(visualElement, variant); + if (visualElement.variantChildren) { + visualElement.variantChildren.forEach((child) => { + setVariants(child, variantLabels); + }); + } + }); +} +function setValues(visualElement, definition) { + if (Array.isArray(definition)) { + return setVariants(visualElement, definition); + } + else if (typeof definition === "string") { + return setVariants(visualElement, [definition]); + } + else { + setTarget(visualElement, definition); + } +} +/** + * @public + */ +function animationControls() { + /** + * Track whether the host component has mounted. + */ + let hasMounted = false; + /** + * A collection of linked component animation controls. + */ + const subscribers = new Set(); + const controls = { + subscribe(visualElement) { + subscribers.add(visualElement); + return () => void subscribers.delete(visualElement); + }, + start(definition, transitionOverride) { + invariant(hasMounted, "controls.start() should only be called after a component has mounted. Consider calling within a useEffect hook."); + const animations = []; + subscribers.forEach((visualElement) => { + animations.push(animateVisualElement(visualElement, definition, { + transitionOverride, + })); + }); + return Promise.all(animations); + }, + set(definition) { + invariant(hasMounted, "controls.set() should only be called after a component has mounted. Consider calling within a useEffect hook."); + return subscribers.forEach((visualElement) => { + setValues(visualElement, definition); + }); + }, + stop() { + subscribers.forEach((visualElement) => { + stopAnimation(visualElement); + }); + }, + mount() { + hasMounted = true; + return () => { + hasMounted = false; + controls.stop(); + }; + }, + }; + return controls; +} + +export { animationControls, setValues }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/hooks/use-animate-style.mjs b/frontend/node_modules/framer-motion/dist/es/animation/hooks/use-animate-style.mjs new file mode 100644 index 0000000000000000000000000000000000000000..173d266eb53a762f1680bdbcae66560dc09a78f8 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/hooks/use-animate-style.mjs @@ -0,0 +1,17 @@ +import { useConstant } from '../../utils/use-constant.mjs'; +import { useUnmountEffect } from '../../utils/use-unmount-effect.mjs'; +import { createScopedWaapiAnimate } from '../animators/waapi/animate-style.mjs'; + +function useAnimateMini() { + const scope = useConstant(() => ({ + current: null, // Will be hydrated by React + animations: [], + })); + const animate = useConstant(() => createScopedWaapiAnimate(scope)); + useUnmountEffect(() => { + scope.animations.forEach((animation) => animation.stop()); + }); + return [scope, animate]; +} + +export { useAnimateMini }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/hooks/use-animate.mjs b/frontend/node_modules/framer-motion/dist/es/animation/hooks/use-animate.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9963520df24248313d9bd54017d21fad25d8daa8 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/hooks/use-animate.mjs @@ -0,0 +1,18 @@ +import { useConstant } from '../../utils/use-constant.mjs'; +import { useUnmountEffect } from '../../utils/use-unmount-effect.mjs'; +import { createScopedAnimate } from '../animate/index.mjs'; + +function useAnimate() { + const scope = useConstant(() => ({ + current: null, // Will be hydrated by React + animations: [], + })); + const animate = useConstant(() => createScopedAnimate(scope)); + useUnmountEffect(() => { + scope.animations.forEach((animation) => animation.stop()); + scope.animations.length = 0; + }); + return [scope, animate]; +} + +export { useAnimate }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/hooks/use-animated-state.mjs b/frontend/node_modules/framer-motion/dist/es/animation/hooks/use-animated-state.mjs new file mode 100644 index 0000000000000000000000000000000000000000..425186fc59d754e8634a883535c49d7354d5ec25 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/hooks/use-animated-state.mjs @@ -0,0 +1,64 @@ +import { useState, useLayoutEffect } from 'react'; +import { makeUseVisualState } from '../../motion/utils/use-visual-state.mjs'; +import { createBox } from '../../projection/geometry/models.mjs'; +import { VisualElement } from '../../render/VisualElement.mjs'; +import { useConstant } from '../../utils/use-constant.mjs'; +import { animateVisualElement } from '../interfaces/visual-element.mjs'; + +const createObject = () => ({}); +class StateVisualElement extends VisualElement { + constructor() { + super(...arguments); + this.measureInstanceViewportBox = createBox; + } + build() { } + resetTransform() { } + restoreTransform() { } + removeValueFromRenderState() { } + renderInstance() { } + scrapeMotionValuesFromProps() { + return createObject(); + } + getBaseTargetFromProps() { + return undefined; + } + readValueFromInstance(_state, key, options) { + return options.initialState[key] || 0; + } + sortInstanceNodePosition() { + return 0; + } +} +const useVisualState = makeUseVisualState({ + scrapeMotionValuesFromProps: createObject, + createRenderState: createObject, +}); +/** + * This is not an officially supported API and may be removed + * on any version. + */ +function useAnimatedState(initialState) { + const [animationState, setAnimationState] = useState(initialState); + const visualState = useVisualState({}, false); + const element = useConstant(() => { + return new StateVisualElement({ + props: { + onUpdate: (v) => { + setAnimationState({ ...v }); + }, + }, + visualState, + presenceContext: null, + }, { initialState }); + }); + useLayoutEffect(() => { + element.mount({}); + return () => element.unmount(); + }, [element]); + const startAnimation = useConstant(() => (animationDefinition) => { + return animateVisualElement(element, animationDefinition); + }); + return [animationState, startAnimation]; +} + +export { useAnimatedState }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/hooks/use-animation.mjs b/frontend/node_modules/framer-motion/dist/es/animation/hooks/use-animation.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a2716876746145fb35444ba94b65668780a5f9e4 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/hooks/use-animation.mjs @@ -0,0 +1,41 @@ +import { useConstant } from '../../utils/use-constant.mjs'; +import { useIsomorphicLayoutEffect } from '../../utils/use-isomorphic-effect.mjs'; +import { animationControls } from './animation-controls.mjs'; + +/** + * Creates `LegacyAnimationControls`, which can be used to manually start, stop + * and sequence animations on one or more components. + * + * The returned `LegacyAnimationControls` should be passed to the `animate` property + * of the components you want to animate. + * + * These components can then be animated with the `start` method. + * + * ```jsx + * import * as React from 'react' + * import { motion, useAnimation } from 'framer-motion' + * + * export function MyComponent(props) { + * const controls = useAnimation() + * + * controls.start({ + * x: 100, + * transition: { duration: 0.5 }, + * }) + * + * return + * } + * ``` + * + * @returns Animation controller with `start` and `stop` methods + * + * @public + */ +function useAnimationControls() { + const controls = useConstant(animationControls); + useIsomorphicLayoutEffect(controls.mount, []); + return controls; +} +const useAnimation = useAnimationControls; + +export { useAnimation, useAnimationControls }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/interfaces/motion-value.mjs b/frontend/node_modules/framer-motion/dist/es/animation/interfaces/motion-value.mjs new file mode 100644 index 0000000000000000000000000000000000000000..be13d4f5fc38b39218c86af788a966efb4a19a35 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/interfaces/motion-value.mjs @@ -0,0 +1,98 @@ +import { getValueTransition, makeAnimationInstant, frame, JSAnimation, AsyncMotionValueAnimation } from 'motion-dom'; +import { secondsToMilliseconds, MotionGlobalConfig } from 'motion-utils'; +import { getFinalKeyframe } from '../animators/waapi/utils/get-final-keyframe.mjs'; +import { getDefaultTransition } from '../utils/default-transitions.mjs'; +import { isTransitionDefined } from '../utils/is-transition-defined.mjs'; + +const animateMotionValue = (name, value, target, transition = {}, element, isHandoff) => (onComplete) => { + const valueTransition = getValueTransition(transition, name) || {}; + /** + * Most transition values are currently completely overwritten by value-specific + * transitions. In the future it'd be nicer to blend these transitions. But for now + * delay actually does inherit from the root transition if not value-specific. + */ + const delay = valueTransition.delay || transition.delay || 0; + /** + * Elapsed isn't a public transition option but can be passed through from + * optimized appear effects in milliseconds. + */ + let { elapsed = 0 } = transition; + elapsed = elapsed - secondsToMilliseconds(delay); + const options = { + keyframes: Array.isArray(target) ? target : [null, target], + ease: "easeOut", + velocity: value.getVelocity(), + ...valueTransition, + delay: -elapsed, + onUpdate: (v) => { + value.set(v); + valueTransition.onUpdate && valueTransition.onUpdate(v); + }, + onComplete: () => { + onComplete(); + valueTransition.onComplete && valueTransition.onComplete(); + }, + name, + motionValue: value, + element: isHandoff ? undefined : element, + }; + /** + * If there's no transition defined for this value, we can generate + * unique transition settings for this value. + */ + if (!isTransitionDefined(valueTransition)) { + Object.assign(options, getDefaultTransition(name, options)); + } + /** + * Both WAAPI and our internal animation functions use durations + * as defined by milliseconds, while our external API defines them + * as seconds. + */ + options.duration && (options.duration = secondsToMilliseconds(options.duration)); + options.repeatDelay && (options.repeatDelay = secondsToMilliseconds(options.repeatDelay)); + /** + * Support deprecated way to set initial value. Prefer keyframe syntax. + */ + if (options.from !== undefined) { + options.keyframes[0] = options.from; + } + let shouldSkip = false; + if (options.type === false || + (options.duration === 0 && !options.repeatDelay)) { + makeAnimationInstant(options); + if (options.delay === 0) { + shouldSkip = true; + } + } + if (MotionGlobalConfig.instantAnimations || + MotionGlobalConfig.skipAnimations) { + shouldSkip = true; + makeAnimationInstant(options); + options.delay = 0; + } + /** + * If the transition type or easing has been explicitly set by the user + * then we don't want to allow flattening the animation. + */ + options.allowFlatten = !valueTransition.type && !valueTransition.ease; + /** + * If we can or must skip creating the animation, and apply only + * the final keyframe, do so. We also check once keyframes are resolved but + * this early check prevents the need to create an animation at all. + */ + if (shouldSkip && !isHandoff && value.get() !== undefined) { + const finalKeyframe = getFinalKeyframe(options.keyframes, valueTransition); + if (finalKeyframe !== undefined) { + frame.update(() => { + options.onUpdate(finalKeyframe); + options.onComplete(); + }); + return; + } + } + return valueTransition.isSync + ? new JSAnimation(options) + : new AsyncMotionValueAnimation(options); +}; + +export { animateMotionValue }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/interfaces/visual-element-target.mjs b/frontend/node_modules/framer-motion/dist/es/animation/interfaces/visual-element-target.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fc5ac6cbccf1d03c5a129861a459845a263409bb --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/interfaces/visual-element-target.mjs @@ -0,0 +1,83 @@ +import { getValueTransition, frame, positionalKeys } from 'motion-dom'; +import { setTarget } from '../../render/utils/setters.mjs'; +import { addValueToWillChange } from '../../value/use-will-change/add-will-change.mjs'; +import { getOptimisedAppearId } from '../optimized-appear/get-appear-id.mjs'; +import { animateMotionValue } from './motion-value.mjs'; + +/** + * Decide whether we should block this animation. Previously, we achieved this + * just by checking whether the key was listed in protectedKeys, but this + * posed problems if an animation was triggered by afterChildren and protectedKeys + * had been set to true in the meantime. + */ +function shouldBlockAnimation({ protectedKeys, needsAnimating }, key) { + const shouldBlock = protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true; + needsAnimating[key] = false; + return shouldBlock; +} +function animateTarget(visualElement, targetAndTransition, { delay = 0, transitionOverride, type } = {}) { + let { transition = visualElement.getDefaultTransition(), transitionEnd, ...target } = targetAndTransition; + if (transitionOverride) + transition = transitionOverride; + const animations = []; + const animationTypeState = type && + visualElement.animationState && + visualElement.animationState.getState()[type]; + for (const key in target) { + const value = visualElement.getValue(key, visualElement.latestValues[key] ?? null); + const valueTarget = target[key]; + if (valueTarget === undefined || + (animationTypeState && + shouldBlockAnimation(animationTypeState, key))) { + continue; + } + const valueTransition = { + delay, + ...getValueTransition(transition || {}, key), + }; + /** + * If the value is already at the defined target, skip the animation. + */ + const currentValue = value.get(); + if (currentValue !== undefined && + !value.isAnimating && + !Array.isArray(valueTarget) && + valueTarget === currentValue && + !valueTransition.velocity) { + continue; + } + /** + * If this is the first time a value is being animated, check + * to see if we're handling off from an existing animation. + */ + let isHandoff = false; + if (window.MotionHandoffAnimation) { + const appearId = getOptimisedAppearId(visualElement); + if (appearId) { + const startTime = window.MotionHandoffAnimation(appearId, key, frame); + if (startTime !== null) { + valueTransition.startTime = startTime; + isHandoff = true; + } + } + } + addValueToWillChange(visualElement, key); + value.start(animateMotionValue(key, value, valueTarget, visualElement.shouldReduceMotion && positionalKeys.has(key) + ? { type: false } + : valueTransition, visualElement, isHandoff)); + const animation = value.animation; + if (animation) { + animations.push(animation); + } + } + if (transitionEnd) { + Promise.all(animations).then(() => { + frame.update(() => { + transitionEnd && setTarget(visualElement, transitionEnd); + }); + }); + } + return animations; +} + +export { animateTarget }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/interfaces/visual-element-variant.mjs b/frontend/node_modules/framer-motion/dist/es/animation/interfaces/visual-element-variant.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4402ebd75e3f032b1aa287eb4642309475933ca7 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/interfaces/visual-element-variant.mjs @@ -0,0 +1,59 @@ +import { resolveVariant } from '../../render/utils/resolve-dynamic-variants.mjs'; +import { calcChildStagger } from '../utils/calc-child-stagger.mjs'; +import { animateTarget } from './visual-element-target.mjs'; + +function animateVariant(visualElement, variant, options = {}) { + const resolved = resolveVariant(visualElement, variant, options.type === "exit" + ? visualElement.presenceContext?.custom + : undefined); + let { transition = visualElement.getDefaultTransition() || {} } = resolved || {}; + if (options.transitionOverride) { + transition = options.transitionOverride; + } + /** + * If we have a variant, create a callback that runs it as an animation. + * Otherwise, we resolve a Promise immediately for a composable no-op. + */ + const getAnimation = resolved + ? () => Promise.all(animateTarget(visualElement, resolved, options)) + : () => Promise.resolve(); + /** + * If we have children, create a callback that runs all their animations. + * Otherwise, we resolve a Promise immediately for a composable no-op. + */ + const getChildAnimations = visualElement.variantChildren && visualElement.variantChildren.size + ? (forwardDelay = 0) => { + const { delayChildren = 0, staggerChildren, staggerDirection, } = transition; + return animateChildren(visualElement, variant, forwardDelay, delayChildren, staggerChildren, staggerDirection, options); + } + : () => Promise.resolve(); + /** + * If the transition explicitly defines a "when" option, we need to resolve either + * this animation or all children animations before playing the other. + */ + const { when } = transition; + if (when) { + const [first, last] = when === "beforeChildren" + ? [getAnimation, getChildAnimations] + : [getChildAnimations, getAnimation]; + return first().then(() => last()); + } + else { + return Promise.all([getAnimation(), getChildAnimations(options.delay)]); + } +} +function animateChildren(visualElement, variant, delay = 0, delayChildren = 0, staggerChildren = 0, staggerDirection = 1, options) { + const animations = []; + for (const child of visualElement.variantChildren) { + child.notify("AnimationStart", variant); + animations.push(animateVariant(child, variant, { + ...options, + delay: delay + + (typeof delayChildren === "function" ? 0 : delayChildren) + + calcChildStagger(visualElement.variantChildren, child, delayChildren, staggerChildren, staggerDirection), + }).then(() => child.notify("AnimationComplete", variant))); + } + return Promise.all(animations); +} + +export { animateVariant }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/interfaces/visual-element.mjs b/frontend/node_modules/framer-motion/dist/es/animation/interfaces/visual-element.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c9f57d1ba3913e27bbe52849b145fe3538c0d091 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/interfaces/visual-element.mjs @@ -0,0 +1,26 @@ +import { resolveVariant } from '../../render/utils/resolve-dynamic-variants.mjs'; +import { animateTarget } from './visual-element-target.mjs'; +import { animateVariant } from './visual-element-variant.mjs'; + +function animateVisualElement(visualElement, definition, options = {}) { + visualElement.notify("AnimationStart", definition); + let animation; + if (Array.isArray(definition)) { + const animations = definition.map((variant) => animateVariant(visualElement, variant, options)); + animation = Promise.all(animations); + } + else if (typeof definition === "string") { + animation = animateVariant(visualElement, definition, options); + } + else { + const resolvedDefinition = typeof definition === "function" + ? resolveVariant(visualElement, definition, options.custom) + : definition; + animation = Promise.all(animateTarget(visualElement, resolvedDefinition, options)); + } + return animation.then(() => { + visualElement.notify("AnimationComplete", definition); + }); +} + +export { animateVisualElement }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/optimized-appear/data-id.mjs b/frontend/node_modules/framer-motion/dist/es/animation/optimized-appear/data-id.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1714fddbc9df672d73e8053f993f75bd50997402 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/optimized-appear/data-id.mjs @@ -0,0 +1,6 @@ +import { camelToDash } from '../../render/dom/utils/camel-to-dash.mjs'; + +const optimizedAppearDataId = "framerAppearId"; +const optimizedAppearDataAttribute = "data-" + camelToDash(optimizedAppearDataId); + +export { optimizedAppearDataAttribute, optimizedAppearDataId }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/optimized-appear/get-appear-id.mjs b/frontend/node_modules/framer-motion/dist/es/animation/optimized-appear/get-appear-id.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0080730743694a5bbc195b6afe8e2d70f07ed735 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/optimized-appear/get-appear-id.mjs @@ -0,0 +1,7 @@ +import { optimizedAppearDataAttribute } from './data-id.mjs'; + +function getOptimisedAppearId(visualElement) { + return visualElement.props[optimizedAppearDataAttribute]; +} + +export { getOptimisedAppearId }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/optimized-appear/handoff.mjs b/frontend/node_modules/framer-motion/dist/es/animation/optimized-appear/handoff.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4d3fecb6b077c6e8b09f578ccec773483eb76790 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/optimized-appear/handoff.mjs @@ -0,0 +1,38 @@ +import { appearAnimationStore } from './store.mjs'; +import { appearStoreId } from './store-id.mjs'; + +function handoffOptimizedAppearAnimation(elementId, valueName, frame) { + const storeId = appearStoreId(elementId, valueName); + const optimisedAnimation = appearAnimationStore.get(storeId); + if (!optimisedAnimation) { + return null; + } + const { animation, startTime } = optimisedAnimation; + function cancelAnimation() { + window.MotionCancelOptimisedAnimation?.(elementId, valueName, frame); + } + /** + * We can cancel the animation once it's finished now that we've synced + * with Motion. + * + * Prefer onfinish over finished as onfinish is backwards compatible with + * older browsers. + */ + animation.onfinish = cancelAnimation; + if (startTime === null || window.MotionHandoffIsComplete?.(elementId)) { + /** + * If the startTime is null, this animation is the Paint Ready detection animation + * and we can cancel it immediately without handoff. + * + * Or if we've already handed off the animation then we're now interrupting it. + * In which case we need to cancel it. + */ + cancelAnimation(); + return null; + } + else { + return startTime; + } +} + +export { handoffOptimizedAppearAnimation }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/optimized-appear/start.mjs b/frontend/node_modules/framer-motion/dist/es/animation/optimized-appear/start.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1a99e514728c9a6ed84bb76549ee9d2672390a01 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/optimized-appear/start.mjs @@ -0,0 +1,171 @@ +import { startWaapiAnimation } from 'motion-dom'; +import { noop } from 'motion-utils'; +import { optimizedAppearDataId } from './data-id.mjs'; +import { getOptimisedAppearId } from './get-appear-id.mjs'; +import { handoffOptimizedAppearAnimation } from './handoff.mjs'; +import { appearAnimationStore, appearComplete } from './store.mjs'; +import { appearStoreId } from './store-id.mjs'; + +/** + * A single time to use across all animations to manually set startTime + * and ensure they're all in sync. + */ +let startFrameTime; +/** + * A dummy animation to detect when Chrome is ready to start + * painting the page and hold off from triggering the real animation + * until then. We only need one animation to detect paint ready. + * + * https://bugs.chromium.org/p/chromium/issues/detail?id=1406850 + */ +let readyAnimation; +/** + * Keep track of animations that were suspended vs cancelled so we + * can easily resume them when we're done measuring layout. + */ +const suspendedAnimations = new Set(); +function resumeSuspendedAnimations() { + suspendedAnimations.forEach((data) => { + data.animation.play(); + data.animation.startTime = data.startTime; + }); + suspendedAnimations.clear(); +} +function startOptimizedAppearAnimation(element, name, keyframes, options, onReady) { + // Prevent optimised appear animations if Motion has already started animating. + if (window.MotionIsMounted) { + return; + } + const id = element.dataset[optimizedAppearDataId]; + if (!id) + return; + window.MotionHandoffAnimation = handoffOptimizedAppearAnimation; + const storeId = appearStoreId(id, name); + if (!readyAnimation) { + readyAnimation = startWaapiAnimation(element, name, [keyframes[0], keyframes[0]], + /** + * 10 secs is basically just a super-safe duration to give Chrome + * long enough to get the animation ready. + */ + { duration: 10000, ease: "linear" }); + appearAnimationStore.set(storeId, { + animation: readyAnimation, + startTime: null, + }); + /** + * If there's no readyAnimation then there's been no instantiation + * of handoff animations. + */ + window.MotionHandoffAnimation = handoffOptimizedAppearAnimation; + window.MotionHasOptimisedAnimation = (elementId, valueName) => { + if (!elementId) + return false; + /** + * Keep a map of elementIds that have started animating. We check + * via ID instead of Element because of hydration errors and + * pre-hydration checks. We also actively record IDs as they start + * animating rather than simply checking for data-appear-id as + * this attrbute might be present but not lead to an animation, for + * instance if the element's appear animation is on a different + * breakpoint. + */ + if (!valueName) { + return appearComplete.has(elementId); + } + const animationId = appearStoreId(elementId, valueName); + return Boolean(appearAnimationStore.get(animationId)); + }; + window.MotionHandoffMarkAsComplete = (elementId) => { + if (appearComplete.has(elementId)) { + appearComplete.set(elementId, true); + } + }; + window.MotionHandoffIsComplete = (elementId) => { + return appearComplete.get(elementId) === true; + }; + /** + * We only need to cancel transform animations as + * they're the ones that will interfere with the + * layout animation measurements. + */ + window.MotionCancelOptimisedAnimation = (elementId, valueName, frame, canResume) => { + const animationId = appearStoreId(elementId, valueName); + const data = appearAnimationStore.get(animationId); + if (!data) + return; + if (frame && canResume === undefined) { + /** + * Wait until the end of the subsequent frame to cancel the animation + * to ensure we don't remove the animation before the main thread has + * had a chance to resolve keyframes and render. + */ + frame.postRender(() => { + frame.postRender(() => { + data.animation.cancel(); + }); + }); + } + else { + data.animation.cancel(); + } + if (frame && canResume) { + suspendedAnimations.add(data); + frame.render(resumeSuspendedAnimations); + } + else { + appearAnimationStore.delete(animationId); + /** + * If there are no more animations left, we can remove the cancel function. + * This will let us know when we can stop checking for conflicting layout animations. + */ + if (!appearAnimationStore.size) { + window.MotionCancelOptimisedAnimation = undefined; + } + } + }; + window.MotionCheckAppearSync = (visualElement, valueName, value) => { + const appearId = getOptimisedAppearId(visualElement); + if (!appearId) + return; + const valueIsOptimised = window.MotionHasOptimisedAnimation?.(appearId, valueName); + const externalAnimationValue = visualElement.props.values?.[valueName]; + if (!valueIsOptimised || !externalAnimationValue) + return; + const removeSyncCheck = value.on("change", (latestValue) => { + if (externalAnimationValue.get() !== latestValue) { + window.MotionCancelOptimisedAnimation?.(appearId, valueName); + removeSyncCheck(); + } + }); + return removeSyncCheck; + }; + } + const startAnimation = () => { + readyAnimation.cancel(); + const appearAnimation = startWaapiAnimation(element, name, keyframes, options); + /** + * Record the time of the first started animation. We call performance.now() once + * here and once in handoff to ensure we're getting + * close to a frame-locked time. This keeps all animations in sync. + */ + if (startFrameTime === undefined) { + startFrameTime = performance.now(); + } + appearAnimation.startTime = startFrameTime; + appearAnimationStore.set(storeId, { + animation: appearAnimation, + startTime: startFrameTime, + }); + if (onReady) + onReady(appearAnimation); + }; + appearComplete.set(id, false); + if (readyAnimation.ready) { + readyAnimation.ready.then(startAnimation).catch(noop); + } + else { + startAnimation(); + } +} + +export { startOptimizedAppearAnimation }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/optimized-appear/store-id.mjs b/frontend/node_modules/framer-motion/dist/es/animation/optimized-appear/store-id.mjs new file mode 100644 index 0000000000000000000000000000000000000000..86e1e1f1029a0b0ed71efea21c461e6edfca0ead --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/optimized-appear/store-id.mjs @@ -0,0 +1,8 @@ +import { transformProps } from 'motion-dom'; + +const appearStoreId = (elementId, valueName) => { + const key = transformProps.has(valueName) ? "transform" : valueName; + return `${elementId}: ${key}`; +}; + +export { appearStoreId }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/optimized-appear/store.mjs b/frontend/node_modules/framer-motion/dist/es/animation/optimized-appear/store.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5b0d9e8dcd582c413a35ec62eb84e3a11a589b90 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/optimized-appear/store.mjs @@ -0,0 +1,4 @@ +const appearAnimationStore = new Map(); +const appearComplete = new Map(); + +export { appearAnimationStore, appearComplete }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/sequence/create.mjs b/frontend/node_modules/framer-motion/dist/es/animation/sequence/create.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1012cf1b2ba78af961300631c03bc2bd7fc32f7b --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/sequence/create.mjs @@ -0,0 +1,249 @@ +import { isMotionValue, defaultOffset, isGenerator, createGeneratorEasing, fillOffset } from 'motion-dom'; +import { progress, secondsToMilliseconds, invariant, getEasingForSegment } from 'motion-utils'; +import { resolveSubjects } from '../animate/resolve-subjects.mjs'; +import { calculateRepeatDuration } from './utils/calc-repeat-duration.mjs'; +import { calcNextTime } from './utils/calc-time.mjs'; +import { addKeyframes } from './utils/edit.mjs'; +import { normalizeTimes } from './utils/normalize-times.mjs'; +import { compareByTime } from './utils/sort.mjs'; + +const defaultSegmentEasing = "easeInOut"; +const MAX_REPEAT = 20; +function createAnimationsFromSequence(sequence, { defaultTransition = {}, ...sequenceTransition } = {}, scope, generators) { + const defaultDuration = defaultTransition.duration || 0.3; + const animationDefinitions = new Map(); + const sequences = new Map(); + const elementCache = {}; + const timeLabels = new Map(); + let prevTime = 0; + let currentTime = 0; + let totalDuration = 0; + /** + * Build the timeline by mapping over the sequence array and converting + * the definitions into keyframes and offsets with absolute time values. + * These will later get converted into relative offsets in a second pass. + */ + for (let i = 0; i < sequence.length; i++) { + const segment = sequence[i]; + /** + * If this is a timeline label, mark it and skip the rest of this iteration. + */ + if (typeof segment === "string") { + timeLabels.set(segment, currentTime); + continue; + } + else if (!Array.isArray(segment)) { + timeLabels.set(segment.name, calcNextTime(currentTime, segment.at, prevTime, timeLabels)); + continue; + } + let [subject, keyframes, transition = {}] = segment; + /** + * If a relative or absolute time value has been specified we need to resolve + * it in relation to the currentTime. + */ + if (transition.at !== undefined) { + currentTime = calcNextTime(currentTime, transition.at, prevTime, timeLabels); + } + /** + * Keep track of the maximum duration in this definition. This will be + * applied to currentTime once the definition has been parsed. + */ + let maxDuration = 0; + const resolveValueSequence = (valueKeyframes, valueTransition, valueSequence, elementIndex = 0, numSubjects = 0) => { + const valueKeyframesAsList = keyframesAsList(valueKeyframes); + const { delay = 0, times = defaultOffset(valueKeyframesAsList), type = "keyframes", repeat, repeatType, repeatDelay = 0, ...remainingTransition } = valueTransition; + let { ease = defaultTransition.ease || "easeOut", duration } = valueTransition; + /** + * Resolve stagger() if defined. + */ + const calculatedDelay = typeof delay === "function" + ? delay(elementIndex, numSubjects) + : delay; + /** + * If this animation should and can use a spring, generate a spring easing function. + */ + const numKeyframes = valueKeyframesAsList.length; + const createGenerator = isGenerator(type) + ? type + : generators?.[type || "keyframes"]; + if (numKeyframes <= 2 && createGenerator) { + /** + * As we're creating an easing function from a spring, + * ideally we want to generate it using the real distance + * between the two keyframes. However this isn't always + * possible - in these situations we use 0-100. + */ + let absoluteDelta = 100; + if (numKeyframes === 2 && + isNumberKeyframesArray(valueKeyframesAsList)) { + const delta = valueKeyframesAsList[1] - valueKeyframesAsList[0]; + absoluteDelta = Math.abs(delta); + } + const springTransition = { ...remainingTransition }; + if (duration !== undefined) { + springTransition.duration = secondsToMilliseconds(duration); + } + const springEasing = createGeneratorEasing(springTransition, absoluteDelta, createGenerator); + ease = springEasing.ease; + duration = springEasing.duration; + } + duration ?? (duration = defaultDuration); + const startTime = currentTime + calculatedDelay; + /** + * If there's only one time offset of 0, fill in a second with length 1 + */ + if (times.length === 1 && times[0] === 0) { + times[1] = 1; + } + /** + * Fill out if offset if fewer offsets than keyframes + */ + const remainder = times.length - valueKeyframesAsList.length; + remainder > 0 && fillOffset(times, remainder); + /** + * If only one value has been set, ie [1], push a null to the start of + * the keyframe array. This will let us mark a keyframe at this point + * that will later be hydrated with the previous value. + */ + valueKeyframesAsList.length === 1 && + valueKeyframesAsList.unshift(null); + /** + * Handle repeat options + */ + if (repeat) { + invariant(repeat < MAX_REPEAT, "Repeat count too high, must be less than 20", "repeat-count-high"); + duration = calculateRepeatDuration(duration, repeat); + const originalKeyframes = [...valueKeyframesAsList]; + const originalTimes = [...times]; + ease = Array.isArray(ease) ? [...ease] : [ease]; + const originalEase = [...ease]; + for (let repeatIndex = 0; repeatIndex < repeat; repeatIndex++) { + valueKeyframesAsList.push(...originalKeyframes); + for (let keyframeIndex = 0; keyframeIndex < originalKeyframes.length; keyframeIndex++) { + times.push(originalTimes[keyframeIndex] + (repeatIndex + 1)); + ease.push(keyframeIndex === 0 + ? "linear" + : getEasingForSegment(originalEase, keyframeIndex - 1)); + } + } + normalizeTimes(times, repeat); + } + const targetTime = startTime + duration; + /** + * Add keyframes, mapping offsets to absolute time. + */ + addKeyframes(valueSequence, valueKeyframesAsList, ease, times, startTime, targetTime); + maxDuration = Math.max(calculatedDelay + duration, maxDuration); + totalDuration = Math.max(targetTime, totalDuration); + }; + if (isMotionValue(subject)) { + const subjectSequence = getSubjectSequence(subject, sequences); + resolveValueSequence(keyframes, transition, getValueSequence("default", subjectSequence)); + } + else { + const subjects = resolveSubjects(subject, keyframes, scope, elementCache); + const numSubjects = subjects.length; + /** + * For every element in this segment, process the defined values. + */ + for (let subjectIndex = 0; subjectIndex < numSubjects; subjectIndex++) { + /** + * Cast necessary, but we know these are of this type + */ + keyframes = keyframes; + transition = transition; + const thisSubject = subjects[subjectIndex]; + const subjectSequence = getSubjectSequence(thisSubject, sequences); + for (const key in keyframes) { + resolveValueSequence(keyframes[key], getValueTransition(transition, key), getValueSequence(key, subjectSequence), subjectIndex, numSubjects); + } + } + } + prevTime = currentTime; + currentTime += maxDuration; + } + /** + * For every element and value combination create a new animation. + */ + sequences.forEach((valueSequences, element) => { + for (const key in valueSequences) { + const valueSequence = valueSequences[key]; + /** + * Arrange all the keyframes in ascending time order. + */ + valueSequence.sort(compareByTime); + const keyframes = []; + const valueOffset = []; + const valueEasing = []; + /** + * For each keyframe, translate absolute times into + * relative offsets based on the total duration of the timeline. + */ + for (let i = 0; i < valueSequence.length; i++) { + const { at, value, easing } = valueSequence[i]; + keyframes.push(value); + valueOffset.push(progress(0, totalDuration, at)); + valueEasing.push(easing || "easeOut"); + } + /** + * If the first keyframe doesn't land on offset: 0 + * provide one by duplicating the initial keyframe. This ensures + * it snaps to the first keyframe when the animation starts. + */ + if (valueOffset[0] !== 0) { + valueOffset.unshift(0); + keyframes.unshift(keyframes[0]); + valueEasing.unshift(defaultSegmentEasing); + } + /** + * If the last keyframe doesn't land on offset: 1 + * provide one with a null wildcard value. This will ensure it + * stays static until the end of the animation. + */ + if (valueOffset[valueOffset.length - 1] !== 1) { + valueOffset.push(1); + keyframes.push(null); + } + if (!animationDefinitions.has(element)) { + animationDefinitions.set(element, { + keyframes: {}, + transition: {}, + }); + } + const definition = animationDefinitions.get(element); + definition.keyframes[key] = keyframes; + definition.transition[key] = { + ...defaultTransition, + duration: totalDuration, + ease: valueEasing, + times: valueOffset, + ...sequenceTransition, + }; + } + }); + return animationDefinitions; +} +function getSubjectSequence(subject, sequences) { + !sequences.has(subject) && sequences.set(subject, {}); + return sequences.get(subject); +} +function getValueSequence(name, sequences) { + if (!sequences[name]) + sequences[name] = []; + return sequences[name]; +} +function keyframesAsList(keyframes) { + return Array.isArray(keyframes) ? keyframes : [keyframes]; +} +function getValueTransition(transition, key) { + return transition && transition[key] + ? { + ...transition, + ...transition[key], + } + : { ...transition }; +} +const isNumber = (keyframe) => typeof keyframe === "number"; +const isNumberKeyframesArray = (keyframes) => keyframes.every(isNumber); + +export { createAnimationsFromSequence, getValueTransition }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/sequence/utils/calc-repeat-duration.mjs b/frontend/node_modules/framer-motion/dist/es/animation/sequence/utils/calc-repeat-duration.mjs new file mode 100644 index 0000000000000000000000000000000000000000..93372213c0410e3f123f5540cb7e0f43e44ad5e7 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/sequence/utils/calc-repeat-duration.mjs @@ -0,0 +1,5 @@ +function calculateRepeatDuration(duration, repeat, _repeatDelay) { + return duration * (repeat + 1); +} + +export { calculateRepeatDuration }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/sequence/utils/calc-time.mjs b/frontend/node_modules/framer-motion/dist/es/animation/sequence/utils/calc-time.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b558a5ba48d8972c186e050286ad4493efe14a13 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/sequence/utils/calc-time.mjs @@ -0,0 +1,23 @@ +/** + * Given a absolute or relative time definition and current/prev time state of the sequence, + * calculate an absolute time for the next keyframes. + */ +function calcNextTime(current, next, prev, labels) { + if (typeof next === "number") { + return next; + } + else if (next.startsWith("-") || next.startsWith("+")) { + return Math.max(0, current + parseFloat(next)); + } + else if (next === "<") { + return prev; + } + else if (next.startsWith("<")) { + return Math.max(0, prev + parseFloat(next.slice(1))); + } + else { + return labels.get(next) ?? current; + } +} + +export { calcNextTime }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/sequence/utils/edit.mjs b/frontend/node_modules/framer-motion/dist/es/animation/sequence/utils/edit.mjs new file mode 100644 index 0000000000000000000000000000000000000000..aa00b8ed427ac17de781f1ae8abca368b90271ff --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/sequence/utils/edit.mjs @@ -0,0 +1,30 @@ +import { mixNumber } from 'motion-dom'; +import { getEasingForSegment, removeItem } from 'motion-utils'; + +function eraseKeyframes(sequence, startTime, endTime) { + for (let i = 0; i < sequence.length; i++) { + const keyframe = sequence[i]; + if (keyframe.at > startTime && keyframe.at < endTime) { + removeItem(sequence, keyframe); + // If we remove this item we have to push the pointer back one + i--; + } + } +} +function addKeyframes(sequence, keyframes, easing, offset, startTime, endTime) { + /** + * Erase every existing value between currentTime and targetTime, + * this will essentially splice this timeline into any currently + * defined ones. + */ + eraseKeyframes(sequence, startTime, endTime); + for (let i = 0; i < keyframes.length; i++) { + sequence.push({ + value: keyframes[i], + at: mixNumber(startTime, endTime, offset[i]), + easing: getEasingForSegment(easing, i), + }); + } +} + +export { addKeyframes, eraseKeyframes }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/sequence/utils/normalize-times.mjs b/frontend/node_modules/framer-motion/dist/es/animation/sequence/utils/normalize-times.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ad36448ba63d92135597fd029d10d9b1490594de --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/sequence/utils/normalize-times.mjs @@ -0,0 +1,13 @@ +/** + * Take an array of times that represent repeated keyframes. For instance + * if we have original times of [0, 0.5, 1] then our repeated times will + * be [0, 0.5, 1, 1, 1.5, 2]. Loop over the times and scale them back + * down to a 0-1 scale. + */ +function normalizeTimes(times, repeat) { + for (let i = 0; i < times.length; i++) { + times[i] = times[i] / (repeat + 1); + } +} + +export { normalizeTimes }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/sequence/utils/sort.mjs b/frontend/node_modules/framer-motion/dist/es/animation/sequence/utils/sort.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6b1ea690fe8484f9660286cb6941067444b9dda1 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/sequence/utils/sort.mjs @@ -0,0 +1,14 @@ +function compareByTime(a, b) { + if (a.at === b.at) { + if (a.value === null) + return 1; + if (b.value === null) + return -1; + return 0; + } + else { + return a.at - b.at; + } +} + +export { compareByTime }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/utils/calc-child-stagger.mjs b/frontend/node_modules/framer-motion/dist/es/animation/utils/calc-child-stagger.mjs new file mode 100644 index 0000000000000000000000000000000000000000..20bc3dca1aad820ed8ec7fe2aa4400dbbec3ad08 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/utils/calc-child-stagger.mjs @@ -0,0 +1,15 @@ +function calcChildStagger(children, child, delayChildren, staggerChildren = 0, staggerDirection = 1) { + const index = Array.from(children) + .sort((a, b) => a.sortNodePosition(b)) + .indexOf(child); + const numChildren = children.size; + const maxStaggerDuration = (numChildren - 1) * staggerChildren; + const delayIsFunction = typeof delayChildren === "function"; + return delayIsFunction + ? delayChildren(index, numChildren) + : staggerDirection === 1 + ? index * staggerChildren + : maxStaggerDuration - index * staggerChildren; +} + +export { calcChildStagger }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/utils/create-visual-element.mjs b/frontend/node_modules/framer-motion/dist/es/animation/utils/create-visual-element.mjs new file mode 100644 index 0000000000000000000000000000000000000000..60995cd98002eec23a44f1652dab3b21668cb4d3 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/utils/create-visual-element.mjs @@ -0,0 +1,44 @@ +import { isSVGElement, isSVGSVGElement } from 'motion-dom'; +import { HTMLVisualElement } from '../../render/html/HTMLVisualElement.mjs'; +import { ObjectVisualElement } from '../../render/object/ObjectVisualElement.mjs'; +import { visualElementStore } from '../../render/store.mjs'; +import { SVGVisualElement } from '../../render/svg/SVGVisualElement.mjs'; + +function createDOMVisualElement(element) { + const options = { + presenceContext: null, + props: {}, + visualState: { + renderState: { + transform: {}, + transformOrigin: {}, + style: {}, + vars: {}, + attrs: {}, + }, + latestValues: {}, + }, + }; + const node = isSVGElement(element) && !isSVGSVGElement(element) + ? new SVGVisualElement(options) + : new HTMLVisualElement(options); + node.mount(element); + visualElementStore.set(element, node); +} +function createObjectVisualElement(subject) { + const options = { + presenceContext: null, + props: {}, + visualState: { + renderState: { + output: {}, + }, + latestValues: {}, + }, + }; + const node = new ObjectVisualElement(options); + node.mount(subject); + visualElementStore.set(subject, node); +} + +export { createDOMVisualElement, createObjectVisualElement }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/utils/default-transitions.mjs b/frontend/node_modules/framer-motion/dist/es/animation/utils/default-transitions.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7cadb0f536cd9588fb24334f06e9075f2b8aa4f9 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/utils/default-transitions.mjs @@ -0,0 +1,40 @@ +import { transformProps } from 'motion-dom'; + +const underDampedSpring = { + type: "spring", + stiffness: 500, + damping: 25, + restSpeed: 10, +}; +const criticallyDampedSpring = (target) => ({ + type: "spring", + stiffness: 550, + damping: target === 0 ? 2 * Math.sqrt(550) : 30, + restSpeed: 10, +}); +const keyframesTransition = { + type: "keyframes", + duration: 0.8, +}; +/** + * Default easing curve is a slightly shallower version of + * the default browser easing curve. + */ +const ease = { + type: "keyframes", + ease: [0.25, 0.1, 0.35, 1], + duration: 0.3, +}; +const getDefaultTransition = (valueKey, { keyframes }) => { + if (keyframes.length > 2) { + return keyframesTransition; + } + else if (transformProps.has(valueKey)) { + return valueKey.startsWith("scale") + ? criticallyDampedSpring(keyframes[1]) + : underDampedSpring; + } + return ease; +}; + +export { getDefaultTransition }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/utils/is-animation-controls.mjs b/frontend/node_modules/framer-motion/dist/es/animation/utils/is-animation-controls.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a59e87eb00810f3c6906d68a085c2ed99107a476 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/utils/is-animation-controls.mjs @@ -0,0 +1,7 @@ +function isAnimationControls(v) { + return (v !== null && + typeof v === "object" && + typeof v.start === "function"); +} + +export { isAnimationControls }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/utils/is-dom-keyframes.mjs b/frontend/node_modules/framer-motion/dist/es/animation/utils/is-dom-keyframes.mjs new file mode 100644 index 0000000000000000000000000000000000000000..86dbef7b9a904172b97e05a647f10ef2c808a459 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/utils/is-dom-keyframes.mjs @@ -0,0 +1,5 @@ +function isDOMKeyframes(keyframes) { + return typeof keyframes === "object" && !Array.isArray(keyframes); +} + +export { isDOMKeyframes }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/utils/is-keyframes-target.mjs b/frontend/node_modules/framer-motion/dist/es/animation/utils/is-keyframes-target.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3c637bf23608cc0529374296b4a02640074dec4c --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/utils/is-keyframes-target.mjs @@ -0,0 +1,5 @@ +const isKeyframesTarget = (v) => { + return Array.isArray(v); +}; + +export { isKeyframesTarget }; diff --git a/frontend/node_modules/framer-motion/dist/es/animation/utils/is-transition-defined.mjs b/frontend/node_modules/framer-motion/dist/es/animation/utils/is-transition-defined.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0fdcfd514ece4cab4537e54502ca9a10c2c8e06d --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/animation/utils/is-transition-defined.mjs @@ -0,0 +1,10 @@ +/** + * Decide whether a transition is defined on a given Transition. + * This filters out orchestration options and returns true + * if any options are left. + */ +function isTransitionDefined({ when, delay: _delay, delayChildren, staggerChildren, staggerDirection, repeat, repeatType, repeatDelay, from, elapsed, ...transition }) { + return !!Object.keys(transition).length; +} + +export { isTransitionDefined }; diff --git a/frontend/node_modules/framer-motion/dist/es/client.mjs b/frontend/node_modules/framer-motion/dist/es/client.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6340be3e7d01146a6000a2de90f883e0f7ee6153 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/client.mjs @@ -0,0 +1,3 @@ +"use client"; +export { MotionA as a, MotionAbbr as abbr, MotionAddress as address, MotionAnimate as animate, MotionArea as area, MotionArticle as article, MotionAside as aside, MotionAudio as audio, MotionB as b, MotionBase as base, MotionBdi as bdi, MotionBdo as bdo, MotionBig as big, MotionBlockquote as blockquote, MotionBody as body, MotionButton as button, MotionCanvas as canvas, MotionCaption as caption, MotionCircle as circle, MotionCite as cite, MotionClipPath as clipPath, MotionCode as code, MotionCol as col, MotionColgroup as colgroup, MotionData as data, MotionDatalist as datalist, MotionDd as dd, MotionDefs as defs, MotionDel as del, MotionDesc as desc, MotionDetails as details, MotionDfn as dfn, MotionDialog as dialog, MotionDiv as div, MotionDl as dl, MotionDt as dt, MotionEllipse as ellipse, MotionEm as em, MotionEmbed as embed, MotionFeBlend as feBlend, MotionFeColorMatrix as feColorMatrix, MotionFeComponentTransfer as feComponentTransfer, MotionFeComposite as feComposite, MotionFeConvolveMatrix as feConvolveMatrix, MotionFeDiffuseLighting as feDiffuseLighting, MotionFeDisplacementMap as feDisplacementMap, MotionFeDistantLight as feDistantLight, MotionFeDropShadow as feDropShadow, MotionFeFlood as feFlood, MotionFeFuncA as feFuncA, MotionFeFuncB as feFuncB, MotionFeFuncG as feFuncG, MotionFeFuncR as feFuncR, MotionFeGaussianBlur as feGaussianBlur, MotionFeImage as feImage, MotionFeMerge as feMerge, MotionFeMergeNode as feMergeNode, MotionFeMorphology as feMorphology, MotionFeOffset as feOffset, MotionFePointLight as fePointLight, MotionFeSpecularLighting as feSpecularLighting, MotionFeSpotLight as feSpotLight, MotionFeTile as feTile, MotionFeTurbulence as feTurbulence, MotionFieldset as fieldset, MotionFigcaption as figcaption, MotionFigure as figure, MotionFilter as filter, MotionFooter as footer, MotionForeignObject as foreignObject, MotionForm as form, MotionG as g, MotionH1 as h1, MotionH2 as h2, MotionH3 as h3, MotionH4 as h4, MotionH5 as h5, MotionH6 as h6, MotionHead as head, MotionHeader as header, MotionHgroup as hgroup, MotionHr as hr, MotionHtml as html, MotionI as i, MotionIframe as iframe, MotionImage as image, MotionImg as img, MotionInput as input, MotionIns as ins, MotionKbd as kbd, MotionKeygen as keygen, MotionLabel as label, MotionLegend as legend, MotionLi as li, MotionLine as line, MotionLinearGradient as linearGradient, MotionLink as link, MotionMain as main, MotionMap as map, MotionMark as mark, MotionMarker as marker, MotionMask as mask, MotionMenu as menu, MotionMenuitem as menuitem, MotionMetadata as metadata, MotionMeter as meter, MotionNav as nav, MotionObject as object, MotionOl as ol, MotionOptgroup as optgroup, MotionOption as option, MotionOutput as output, MotionP as p, MotionParam as param, MotionPath as path, MotionPattern as pattern, MotionPicture as picture, MotionPolygon as polygon, MotionPolyline as polyline, MotionPre as pre, MotionProgress as progress, MotionQ as q, MotionRadialGradient as radialGradient, MotionRect as rect, MotionRp as rp, MotionRt as rt, MotionRuby as ruby, MotionS as s, MotionSamp as samp, MotionScript as script, MotionSection as section, MotionSelect as select, MotionSmall as small, MotionSource as source, MotionSpan as span, MotionStop as stop, MotionStrong as strong, MotionStyle as style, MotionSub as sub, MotionSummary as summary, MotionSup as sup, MotionSvg as svg, MotionSymbol as symbol, MotionTable as table, MotionTbody as tbody, MotionTd as td, MotionText as text, MotionTextPath as textPath, MotionTextarea as textarea, MotionTfoot as tfoot, MotionTh as th, MotionThead as thead, MotionTime as time, MotionTitle as title, MotionTr as tr, MotionTrack as track, MotionTspan as tspan, MotionU as u, MotionUl as ul, MotionUse as use, MotionVideo as video, MotionView as view, MotionWbr as wbr, MotionWebview as webview } from './render/components/motion/elements.mjs'; +export { createMotionComponent as create } from './motion/index.mjs'; diff --git a/frontend/node_modules/framer-motion/dist/es/components/AnimatePresence/PopChild.mjs b/frontend/node_modules/framer-motion/dist/es/components/AnimatePresence/PopChild.mjs new file mode 100644 index 0000000000000000000000000000000000000000..73dc8fb1a0a6ffc490f3c72d1fdc997c46930b15 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/components/AnimatePresence/PopChild.mjs @@ -0,0 +1,88 @@ +"use client"; +import { jsx } from 'react/jsx-runtime'; +import { isHTMLElement } from 'motion-dom'; +import * as React from 'react'; +import { useId, useRef, useContext, useInsertionEffect } from 'react'; +import { MotionConfigContext } from '../../context/MotionConfigContext.mjs'; + +/** + * Measurement functionality has to be within a separate component + * to leverage snapshot lifecycle. + */ +class PopChildMeasure extends React.Component { + getSnapshotBeforeUpdate(prevProps) { + const element = this.props.childRef.current; + if (element && prevProps.isPresent && !this.props.isPresent) { + const parent = element.offsetParent; + const parentWidth = isHTMLElement(parent) + ? parent.offsetWidth || 0 + : 0; + const size = this.props.sizeRef.current; + size.height = element.offsetHeight || 0; + size.width = element.offsetWidth || 0; + size.top = element.offsetTop; + size.left = element.offsetLeft; + size.right = parentWidth - size.width - size.left; + } + return null; + } + /** + * Required with getSnapshotBeforeUpdate to stop React complaining. + */ + componentDidUpdate() { } + render() { + return this.props.children; + } +} +function PopChild({ children, isPresent, anchorX, root }) { + const id = useId(); + const ref = useRef(null); + const size = useRef({ + width: 0, + height: 0, + top: 0, + left: 0, + right: 0, + }); + const { nonce } = useContext(MotionConfigContext); + /** + * We create and inject a style block so we can apply this explicit + * sizing in a non-destructive manner by just deleting the style block. + * + * We can't apply size via render as the measurement happens + * in getSnapshotBeforeUpdate (post-render), likewise if we apply the + * styles directly on the DOM node, we might be overwriting + * styles set via the style prop. + */ + useInsertionEffect(() => { + const { width, height, top, left, right } = size.current; + if (isPresent || !ref.current || !width || !height) + return; + const x = anchorX === "left" ? `left: ${left}` : `right: ${right}`; + ref.current.dataset.motionPopId = id; + const style = document.createElement("style"); + if (nonce) + style.nonce = nonce; + const parent = root ?? document.head; + parent.appendChild(style); + if (style.sheet) { + style.sheet.insertRule(` + [data-motion-pop-id="${id}"] { + position: absolute !important; + width: ${width}px !important; + height: ${height}px !important; + ${x}px !important; + top: ${top}px !important; + } + `); + } + return () => { + if (parent.contains(style)) { + parent.removeChild(style); + } + }; + }, [isPresent]); + return (jsx(PopChildMeasure, { isPresent: isPresent, childRef: ref, sizeRef: size, children: React.cloneElement(children, { ref }) })); +} + +export { PopChild }; diff --git a/frontend/node_modules/framer-motion/dist/es/components/AnimatePresence/PresenceChild.mjs b/frontend/node_modules/framer-motion/dist/es/components/AnimatePresence/PresenceChild.mjs new file mode 100644 index 0000000000000000000000000000000000000000..938ab9c74044c347b3d8280542c789e9398be87b --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/components/AnimatePresence/PresenceChild.mjs @@ -0,0 +1,64 @@ +"use client"; +import { jsx } from 'react/jsx-runtime'; +import * as React from 'react'; +import { useId, useMemo } from 'react'; +import { PresenceContext } from '../../context/PresenceContext.mjs'; +import { useConstant } from '../../utils/use-constant.mjs'; +import { PopChild } from './PopChild.mjs'; + +const PresenceChild = ({ children, initial, isPresent, onExitComplete, custom, presenceAffectsLayout, mode, anchorX, root }) => { + const presenceChildren = useConstant(newChildrenMap); + const id = useId(); + let isReusedContext = true; + let context = useMemo(() => { + isReusedContext = false; + return { + id, + initial, + isPresent, + custom, + onExitComplete: (childId) => { + presenceChildren.set(childId, true); + for (const isComplete of presenceChildren.values()) { + if (!isComplete) + return; // can stop searching when any is incomplete + } + onExitComplete && onExitComplete(); + }, + register: (childId) => { + presenceChildren.set(childId, false); + return () => presenceChildren.delete(childId); + }, + }; + }, [isPresent, presenceChildren, onExitComplete]); + /** + * If the presence of a child affects the layout of the components around it, + * we want to make a new context value to ensure they get re-rendered + * so they can detect that layout change. + */ + if (presenceAffectsLayout && isReusedContext) { + context = { ...context }; + } + useMemo(() => { + presenceChildren.forEach((_, key) => presenceChildren.set(key, false)); + }, [isPresent]); + /** + * If there's no `motion` components to fire exit animations, we want to remove this + * component immediately. + */ + React.useEffect(() => { + !isPresent && + !presenceChildren.size && + onExitComplete && + onExitComplete(); + }, [isPresent]); + if (mode === "popLayout") { + children = (jsx(PopChild, { isPresent: isPresent, anchorX: anchorX, root: root, children: children })); + } + return (jsx(PresenceContext.Provider, { value: context, children: children })); +}; +function newChildrenMap() { + return new Map(); +} + +export { PresenceChild }; diff --git a/frontend/node_modules/framer-motion/dist/es/components/AnimatePresence/index.mjs b/frontend/node_modules/framer-motion/dist/es/components/AnimatePresence/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2704002398f57b9898fe896c05eb74b457db8a2c --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/components/AnimatePresence/index.mjs @@ -0,0 +1,166 @@ +"use client"; +import { jsx, Fragment } from 'react/jsx-runtime'; +import { useMemo, useRef, useState, useContext } from 'react'; +import { LayoutGroupContext } from '../../context/LayoutGroupContext.mjs'; +import { useConstant } from '../../utils/use-constant.mjs'; +import { useIsomorphicLayoutEffect } from '../../utils/use-isomorphic-effect.mjs'; +import { PresenceChild } from './PresenceChild.mjs'; +import { usePresence } from './use-presence.mjs'; +import { onlyElements, getChildKey } from './utils.mjs'; + +/** + * `AnimatePresence` enables the animation of components that have been removed from the tree. + * + * When adding/removing more than a single child, every child **must** be given a unique `key` prop. + * + * Any `motion` components that have an `exit` property defined will animate out when removed from + * the tree. + * + * ```jsx + * import { motion, AnimatePresence } from 'framer-motion' + * + * export const Items = ({ items }) => ( + * + * {items.map(item => ( + * + * ))} + * + * ) + * ``` + * + * You can sequence exit animations throughout a tree using variants. + * + * If a child contains multiple `motion` components with `exit` props, it will only unmount the child + * once all `motion` components have finished animating out. Likewise, any components using + * `usePresence` all need to call `safeToRemove`. + * + * @public + */ +const AnimatePresence = ({ children, custom, initial = true, onExitComplete, presenceAffectsLayout = true, mode = "sync", propagate = false, anchorX = "left", root }) => { + const [isParentPresent, safeToRemove] = usePresence(propagate); + /** + * Filter any children that aren't ReactElements. We can only track components + * between renders with a props.key. + */ + const presentChildren = useMemo(() => onlyElements(children), [children]); + /** + * Track the keys of the currently rendered children. This is used to + * determine which children are exiting. + */ + const presentKeys = propagate && !isParentPresent ? [] : presentChildren.map(getChildKey); + /** + * If `initial={false}` we only want to pass this to components in the first render. + */ + const isInitialRender = useRef(true); + /** + * A ref containing the currently present children. When all exit animations + * are complete, we use this to re-render the component with the latest children + * *committed* rather than the latest children *rendered*. + */ + const pendingPresentChildren = useRef(presentChildren); + /** + * Track which exiting children have finished animating out. + */ + const exitComplete = useConstant(() => new Map()); + /** + * Save children to render as React state. To ensure this component is concurrent-safe, + * we check for exiting children via an effect. + */ + const [diffedChildren, setDiffedChildren] = useState(presentChildren); + const [renderedChildren, setRenderedChildren] = useState(presentChildren); + useIsomorphicLayoutEffect(() => { + isInitialRender.current = false; + pendingPresentChildren.current = presentChildren; + /** + * Update complete status of exiting children. + */ + for (let i = 0; i < renderedChildren.length; i++) { + const key = getChildKey(renderedChildren[i]); + if (!presentKeys.includes(key)) { + if (exitComplete.get(key) !== true) { + exitComplete.set(key, false); + } + } + else { + exitComplete.delete(key); + } + } + }, [renderedChildren, presentKeys.length, presentKeys.join("-")]); + const exitingChildren = []; + if (presentChildren !== diffedChildren) { + let nextChildren = [...presentChildren]; + /** + * Loop through all the currently rendered components and decide which + * are exiting. + */ + for (let i = 0; i < renderedChildren.length; i++) { + const child = renderedChildren[i]; + const key = getChildKey(child); + if (!presentKeys.includes(key)) { + nextChildren.splice(i, 0, child); + exitingChildren.push(child); + } + } + /** + * If we're in "wait" mode, and we have exiting children, we want to + * only render these until they've all exited. + */ + if (mode === "wait" && exitingChildren.length) { + nextChildren = exitingChildren; + } + setRenderedChildren(onlyElements(nextChildren)); + setDiffedChildren(presentChildren); + /** + * Early return to ensure once we've set state with the latest diffed + * children, we can immediately re-render. + */ + return null; + } + if (process.env.NODE_ENV !== "production" && + mode === "wait" && + renderedChildren.length > 1) { + console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`); + } + /** + * If we've been provided a forceRender function by the LayoutGroupContext, + * we can use it to force a re-render amongst all surrounding components once + * all components have finished animating out. + */ + const { forceRender } = useContext(LayoutGroupContext); + return (jsx(Fragment, { children: renderedChildren.map((child) => { + const key = getChildKey(child); + const isPresent = propagate && !isParentPresent + ? false + : presentChildren === renderedChildren || + presentKeys.includes(key); + const onExit = () => { + if (exitComplete.has(key)) { + exitComplete.set(key, true); + } + else { + return; + } + let isEveryExitComplete = true; + exitComplete.forEach((isExitComplete) => { + if (!isExitComplete) + isEveryExitComplete = false; + }); + if (isEveryExitComplete) { + forceRender?.(); + setRenderedChildren(pendingPresentChildren.current); + propagate && safeToRemove?.(); + onExitComplete && onExitComplete(); + } + }; + return (jsx(PresenceChild, { isPresent: isPresent, initial: !isInitialRender.current || initial + ? undefined + : false, custom: custom, presenceAffectsLayout: presenceAffectsLayout, mode: mode, root: root, onExitComplete: isPresent ? undefined : onExit, anchorX: anchorX, children: child }, key)); + }) })); +}; + +export { AnimatePresence }; diff --git a/frontend/node_modules/framer-motion/dist/es/components/AnimatePresence/use-presence-data.mjs b/frontend/node_modules/framer-motion/dist/es/components/AnimatePresence/use-presence-data.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a8a091f0fcd2b55ef76f2a1cd8dba6919d48b210 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/components/AnimatePresence/use-presence-data.mjs @@ -0,0 +1,9 @@ +import { useContext } from 'react'; +import { PresenceContext } from '../../context/PresenceContext.mjs'; + +function usePresenceData() { + const context = useContext(PresenceContext); + return context ? context.custom : undefined; +} + +export { usePresenceData }; diff --git a/frontend/node_modules/framer-motion/dist/es/components/AnimatePresence/use-presence.mjs b/frontend/node_modules/framer-motion/dist/es/components/AnimatePresence/use-presence.mjs new file mode 100644 index 0000000000000000000000000000000000000000..569930a779fbca42fdf3996c70e1bb21cc73582b --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/components/AnimatePresence/use-presence.mjs @@ -0,0 +1,70 @@ +import { useContext, useId, useEffect, useCallback } from 'react'; +import { PresenceContext } from '../../context/PresenceContext.mjs'; + +/** + * When a component is the child of `AnimatePresence`, it can use `usePresence` + * to access information about whether it's still present in the React tree. + * + * ```jsx + * import { usePresence } from "framer-motion" + * + * export const Component = () => { + * const [isPresent, safeToRemove] = usePresence() + * + * useEffect(() => { + * !isPresent && setTimeout(safeToRemove, 1000) + * }, [isPresent]) + * + * return
+ * } + * ``` + * + * If `isPresent` is `false`, it means that a component has been removed the tree, but + * `AnimatePresence` won't really remove it until `safeToRemove` has been called. + * + * @public + */ +function usePresence(subscribe = true) { + const context = useContext(PresenceContext); + if (context === null) + return [true, null]; + const { isPresent, onExitComplete, register } = context; + // It's safe to call the following hooks conditionally (after an early return) because the context will always + // either be null or non-null for the lifespan of the component. + const id = useId(); + useEffect(() => { + if (subscribe) { + return register(id); + } + }, [subscribe]); + const safeToRemove = useCallback(() => subscribe && onExitComplete && onExitComplete(id), [id, onExitComplete, subscribe]); + return !isPresent && onExitComplete ? [false, safeToRemove] : [true]; +} +/** + * Similar to `usePresence`, except `useIsPresent` simply returns whether or not the component is present. + * There is no `safeToRemove` function. + * + * ```jsx + * import { useIsPresent } from "framer-motion" + * + * export const Component = () => { + * const isPresent = useIsPresent() + * + * useEffect(() => { + * !isPresent && console.log("I've been removed!") + * }, [isPresent]) + * + * return
+ * } + * ``` + * + * @public + */ +function useIsPresent() { + return isPresent(useContext(PresenceContext)); +} +function isPresent(context) { + return context === null ? true : context.isPresent; +} + +export { isPresent, useIsPresent, usePresence }; diff --git a/frontend/node_modules/framer-motion/dist/es/components/AnimatePresence/utils.mjs b/frontend/node_modules/framer-motion/dist/es/components/AnimatePresence/utils.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6819aba4fe4890bee76b5dd057da8cd116d72bcc --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/components/AnimatePresence/utils.mjs @@ -0,0 +1,14 @@ +import { Children, isValidElement } from 'react'; + +const getChildKey = (child) => child.key || ""; +function onlyElements(children) { + const filtered = []; + // We use forEach here instead of map as map mutates the component key by preprending `.$` + Children.forEach(children, (child) => { + if (isValidElement(child)) + filtered.push(child); + }); + return filtered; +} + +export { getChildKey, onlyElements }; diff --git a/frontend/node_modules/framer-motion/dist/es/components/AnimateSharedLayout.mjs b/frontend/node_modules/framer-motion/dist/es/components/AnimateSharedLayout.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d8a1e31a36e58345520fd37cb1fd834dbccd2b47 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/components/AnimateSharedLayout.mjs @@ -0,0 +1,15 @@ +import { jsx } from 'react/jsx-runtime'; +import { invariant } from 'motion-utils'; +import * as React from 'react'; +import { useConstant } from '../utils/use-constant.mjs'; +import { LayoutGroup } from './LayoutGroup/index.mjs'; + +let id = 0; +const AnimateSharedLayout = ({ children }) => { + React.useEffect(() => { + invariant(false, "AnimateSharedLayout is deprecated: https://www.framer.com/docs/guide-upgrade/##shared-layout-animations"); + }, []); + return (jsx(LayoutGroup, { id: useConstant(() => `asl-${id++}`), children: children })); +}; + +export { AnimateSharedLayout }; diff --git a/frontend/node_modules/framer-motion/dist/es/components/LayoutGroup/index.mjs b/frontend/node_modules/framer-motion/dist/es/components/LayoutGroup/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ccd17d7676536320638dd2c9314525bbf6b6488d --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/components/LayoutGroup/index.mjs @@ -0,0 +1,32 @@ +"use client"; +import { jsx } from 'react/jsx-runtime'; +import { useContext, useRef, useMemo } from 'react'; +import { LayoutGroupContext } from '../../context/LayoutGroupContext.mjs'; +import { DeprecatedLayoutGroupContext } from '../../context/DeprecatedLayoutGroupContext.mjs'; +import { useForceUpdate } from '../../utils/use-force-update.mjs'; +import { nodeGroup } from '../../projection/node/group.mjs'; + +const shouldInheritGroup = (inherit) => inherit === true; +const shouldInheritId = (inherit) => shouldInheritGroup(inherit === true) || inherit === "id"; +const LayoutGroup = ({ children, id, inherit = true }) => { + const layoutGroupContext = useContext(LayoutGroupContext); + const deprecatedLayoutGroupContext = useContext(DeprecatedLayoutGroupContext); + const [forceRender, key] = useForceUpdate(); + const context = useRef(null); + const upstreamId = layoutGroupContext.id || deprecatedLayoutGroupContext; + if (context.current === null) { + if (shouldInheritId(inherit) && upstreamId) { + id = id ? upstreamId + "-" + id : upstreamId; + } + context.current = { + id, + group: shouldInheritGroup(inherit) + ? layoutGroupContext.group || nodeGroup() + : nodeGroup(), + }; + } + const memoizedContext = useMemo(() => ({ ...context.current, forceRender }), [key]); + return (jsx(LayoutGroupContext.Provider, { value: memoizedContext, children: children })); +}; + +export { LayoutGroup }; diff --git a/frontend/node_modules/framer-motion/dist/es/components/LazyMotion/index.mjs b/frontend/node_modules/framer-motion/dist/es/components/LazyMotion/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..499b7a5ad7bdcf36026dbb994599b5a1f8d788dd --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/components/LazyMotion/index.mjs @@ -0,0 +1,68 @@ +"use client"; +import { jsx } from 'react/jsx-runtime'; +import { useState, useRef, useEffect } from 'react'; +import { LazyContext } from '../../context/LazyContext.mjs'; +import { loadFeatures } from '../../motion/features/load-features.mjs'; + +/** + * Used in conjunction with the `m` component to reduce bundle size. + * + * `m` is a version of the `motion` component that only loads functionality + * critical for the initial render. + * + * `LazyMotion` can then be used to either synchronously or asynchronously + * load animation and gesture support. + * + * ```jsx + * // Synchronous loading + * import { LazyMotion, m, domAnimation } from "framer-motion" + * + * function App() { + * return ( + * + * + * + * ) + * } + * + * // Asynchronous loading + * import { LazyMotion, m } from "framer-motion" + * + * function App() { + * return ( + * import('./path/to/domAnimation')}> + * + * + * ) + * } + * ``` + * + * @public + */ +function LazyMotion({ children, features, strict = false }) { + const [, setIsLoaded] = useState(!isLazyBundle(features)); + const loadedRenderer = useRef(undefined); + /** + * If this is a synchronous load, load features immediately + */ + if (!isLazyBundle(features)) { + const { renderer, ...loadedFeatures } = features; + loadedRenderer.current = renderer; + loadFeatures(loadedFeatures); + } + useEffect(() => { + if (isLazyBundle(features)) { + features().then(({ renderer, ...loadedFeatures }) => { + loadFeatures(loadedFeatures); + loadedRenderer.current = renderer; + setIsLoaded(true); + }); + } + }, []); + return (jsx(LazyContext.Provider, { value: { renderer: loadedRenderer.current, strict }, children: children })); +} +function isLazyBundle(features) { + return typeof features === "function"; +} + +export { LazyMotion }; diff --git a/frontend/node_modules/framer-motion/dist/es/components/MotionConfig/index.mjs b/frontend/node_modules/framer-motion/dist/es/components/MotionConfig/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8947fa26b979d9f35b005408051a04237b7a4ab9 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/components/MotionConfig/index.mjs @@ -0,0 +1,48 @@ +"use client"; +import { jsx } from 'react/jsx-runtime'; +import { useContext, useMemo } from 'react'; +import { MotionConfigContext } from '../../context/MotionConfigContext.mjs'; +import { loadExternalIsValidProp } from '../../render/dom/utils/filter-props.mjs'; +import { useConstant } from '../../utils/use-constant.mjs'; + +/** + * `MotionConfig` is used to set configuration options for all children `motion` components. + * + * ```jsx + * import { motion, MotionConfig } from "framer-motion" + * + * export function App() { + * return ( + * + * + * + * ) + * } + * ``` + * + * @public + */ +function MotionConfig({ children, isValidProp, ...config }) { + isValidProp && loadExternalIsValidProp(isValidProp); + /** + * Inherit props from any parent MotionConfig components + */ + config = { ...useContext(MotionConfigContext), ...config }; + /** + * Don't allow isStatic to change between renders as it affects how many hooks + * motion components fire. + */ + config.isStatic = useConstant(() => config.isStatic); + /** + * Creating a new config context object will re-render every `motion` component + * every time it renders. So we only want to create a new one sparingly. + */ + const context = useMemo(() => config, [ + JSON.stringify(config.transition), + config.transformPagePoint, + config.reducedMotion, + ]); + return (jsx(MotionConfigContext.Provider, { value: context, children: children })); +} + +export { MotionConfig }; diff --git a/frontend/node_modules/framer-motion/dist/es/components/Reorder/Group.mjs b/frontend/node_modules/framer-motion/dist/es/components/Reorder/Group.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8ef5e1cbe0af64882d5a73012c87098e76c74f50 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/components/Reorder/Group.mjs @@ -0,0 +1,53 @@ +"use client"; +import { jsx } from 'react/jsx-runtime'; +import { invariant } from 'motion-utils'; +import { forwardRef, useRef, useEffect } from 'react'; +import { ReorderContext } from '../../context/ReorderContext.mjs'; +import { motion } from '../../render/components/motion/proxy.mjs'; +import { useConstant } from '../../utils/use-constant.mjs'; +import { checkReorder } from './utils/check-reorder.mjs'; + +function ReorderGroupComponent({ children, as = "ul", axis = "y", onReorder, values, ...props }, externalRef) { + const Component = useConstant(() => motion[as]); + const order = []; + const isReordering = useRef(false); + invariant(Boolean(values), "Reorder.Group must be provided a values prop", "reorder-values"); + const context = { + axis, + registerItem: (value, layout) => { + // If the entry was already added, update it rather than adding it again + const idx = order.findIndex((entry) => value === entry.value); + if (idx !== -1) { + order[idx].layout = layout[axis]; + } + else { + order.push({ value: value, layout: layout[axis] }); + } + order.sort(compareMin); + }, + updateOrder: (item, offset, velocity) => { + if (isReordering.current) + return; + const newOrder = checkReorder(order, item, offset, velocity); + if (order !== newOrder) { + isReordering.current = true; + onReorder(newOrder + .map(getValue) + .filter((value) => values.indexOf(value) !== -1)); + } + }, + }; + useEffect(() => { + isReordering.current = false; + }); + return (jsx(Component, { ...props, ref: externalRef, ignoreStrict: true, children: jsx(ReorderContext.Provider, { value: context, children: children }) })); +} +const ReorderGroup = /*@__PURE__*/ forwardRef(ReorderGroupComponent); +function getValue(item) { + return item.value; +} +function compareMin(a, b) { + return a.layout.min - b.layout.min; +} + +export { ReorderGroup, ReorderGroupComponent }; diff --git a/frontend/node_modules/framer-motion/dist/es/components/Reorder/Item.mjs b/frontend/node_modules/framer-motion/dist/es/components/Reorder/Item.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8e347495b32bba42e16d93e2fee79309358da300 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/components/Reorder/Item.mjs @@ -0,0 +1,34 @@ +"use client"; +import { jsx } from 'react/jsx-runtime'; +import { isMotionValue } from 'motion-dom'; +import { invariant } from 'motion-utils'; +import { forwardRef, useContext } from 'react'; +import { ReorderContext } from '../../context/ReorderContext.mjs'; +import { motion } from '../../render/components/motion/proxy.mjs'; +import { useConstant } from '../../utils/use-constant.mjs'; +import { useMotionValue } from '../../value/use-motion-value.mjs'; +import { useTransform } from '../../value/use-transform.mjs'; + +function useDefaultMotionValue(value, defaultValue = 0) { + return isMotionValue(value) ? value : useMotionValue(defaultValue); +} +function ReorderItemComponent({ children, style = {}, value, as = "li", onDrag, layout = true, ...props }, externalRef) { + const Component = useConstant(() => motion[as]); + const context = useContext(ReorderContext); + const point = { + x: useDefaultMotionValue(style.x), + y: useDefaultMotionValue(style.y), + }; + const zIndex = useTransform([point.x, point.y], ([latestX, latestY]) => latestX || latestY ? 1 : "unset"); + invariant(Boolean(context), "Reorder.Item must be a child of Reorder.Group", "reorder-item-child"); + const { axis, registerItem, updateOrder } = context; + return (jsx(Component, { drag: axis, ...props, dragSnapToOrigin: true, style: { ...style, x: point.x, y: point.y, zIndex }, layout: layout, onDrag: (event, gesturePoint) => { + const { velocity } = gesturePoint; + velocity[axis] && + updateOrder(value, point[axis].get(), velocity[axis]); + onDrag && onDrag(event, gesturePoint); + }, onLayoutMeasure: (measured) => registerItem(value, measured), ref: externalRef, ignoreStrict: true, children: children })); +} +const ReorderItem = /*@__PURE__*/ forwardRef(ReorderItemComponent); + +export { ReorderItem, ReorderItemComponent }; diff --git a/frontend/node_modules/framer-motion/dist/es/components/Reorder/namespace.mjs b/frontend/node_modules/framer-motion/dist/es/components/Reorder/namespace.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c0ce0f00928afc081506341986a7145fab114ab9 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/components/Reorder/namespace.mjs @@ -0,0 +1,2 @@ +export { ReorderGroup as Group } from './Group.mjs'; +export { ReorderItem as Item } from './Item.mjs'; diff --git a/frontend/node_modules/framer-motion/dist/es/components/Reorder/utils/check-reorder.mjs b/frontend/node_modules/framer-motion/dist/es/components/Reorder/utils/check-reorder.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d6ba9671038b73734f8e873ebe39fe2ed2589421 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/components/Reorder/utils/check-reorder.mjs @@ -0,0 +1,24 @@ +import { mixNumber } from 'motion-dom'; +import { moveItem } from 'motion-utils'; + +function checkReorder(order, value, offset, velocity) { + if (!velocity) + return order; + const index = order.findIndex((item) => item.value === value); + if (index === -1) + return order; + const nextOffset = velocity > 0 ? 1 : -1; + const nextItem = order[index + nextOffset]; + if (!nextItem) + return order; + const item = order[index]; + const nextLayout = nextItem.layout; + const nextItemCenter = mixNumber(nextLayout.min, nextLayout.max, 0.5); + if ((nextOffset === 1 && item.layout.max + offset > nextItemCenter) || + (nextOffset === -1 && item.layout.min + offset < nextItemCenter)) { + return moveItem(order, index, index + nextOffset); + } + return order; +} + +export { checkReorder }; diff --git a/frontend/node_modules/framer-motion/dist/es/context/DeprecatedLayoutGroupContext.mjs b/frontend/node_modules/framer-motion/dist/es/context/DeprecatedLayoutGroupContext.mjs new file mode 100644 index 0000000000000000000000000000000000000000..16f8bed047899fcc7a22f042faca41143b0489d4 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/context/DeprecatedLayoutGroupContext.mjs @@ -0,0 +1,10 @@ +import { createContext } from 'react'; + +/** + * Note: Still used by components generated by old versions of Framer + * + * @deprecated + */ +const DeprecatedLayoutGroupContext = createContext(null); + +export { DeprecatedLayoutGroupContext }; diff --git a/frontend/node_modules/framer-motion/dist/es/context/LayoutGroupContext.mjs b/frontend/node_modules/framer-motion/dist/es/context/LayoutGroupContext.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0148bacc5bfc783ee34363a5d332d640aa41907e --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/context/LayoutGroupContext.mjs @@ -0,0 +1,6 @@ +"use client"; +import { createContext } from 'react'; + +const LayoutGroupContext = createContext({}); + +export { LayoutGroupContext }; diff --git a/frontend/node_modules/framer-motion/dist/es/context/LazyContext.mjs b/frontend/node_modules/framer-motion/dist/es/context/LazyContext.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9b04f565b3c386c12890c963e05790008c0d9f61 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/context/LazyContext.mjs @@ -0,0 +1,6 @@ +"use client"; +import { createContext } from 'react'; + +const LazyContext = createContext({ strict: false }); + +export { LazyContext }; diff --git a/frontend/node_modules/framer-motion/dist/es/context/MotionConfigContext.mjs b/frontend/node_modules/framer-motion/dist/es/context/MotionConfigContext.mjs new file mode 100644 index 0000000000000000000000000000000000000000..55f28a0915b90211929d451c96cd6130d20924f9 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/context/MotionConfigContext.mjs @@ -0,0 +1,13 @@ +"use client"; +import { createContext } from 'react'; + +/** + * @public + */ +const MotionConfigContext = createContext({ + transformPagePoint: (p) => p, + isStatic: false, + reducedMotion: "never", +}); + +export { MotionConfigContext }; diff --git a/frontend/node_modules/framer-motion/dist/es/context/MotionContext/create.mjs b/frontend/node_modules/framer-motion/dist/es/context/MotionContext/create.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e8fa5734fdc2be1e0c08814c87b88814efdc4b04 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/context/MotionContext/create.mjs @@ -0,0 +1,13 @@ +import { useContext, useMemo } from 'react'; +import { MotionContext } from './index.mjs'; +import { getCurrentTreeVariants } from './utils.mjs'; + +function useCreateMotionContext(props) { + const { initial, animate } = getCurrentTreeVariants(props, useContext(MotionContext)); + return useMemo(() => ({ initial, animate }), [variantLabelsAsDependency(initial), variantLabelsAsDependency(animate)]); +} +function variantLabelsAsDependency(prop) { + return Array.isArray(prop) ? prop.join(" ") : prop; +} + +export { useCreateMotionContext }; diff --git a/frontend/node_modules/framer-motion/dist/es/context/MotionContext/index.mjs b/frontend/node_modules/framer-motion/dist/es/context/MotionContext/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cfdec2d741de3943a647b5df1b4ff8f62d8eb843 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/context/MotionContext/index.mjs @@ -0,0 +1,6 @@ +"use client"; +import { createContext } from 'react'; + +const MotionContext = /* @__PURE__ */ createContext({}); + +export { MotionContext }; diff --git a/frontend/node_modules/framer-motion/dist/es/context/MotionContext/utils.mjs b/frontend/node_modules/framer-motion/dist/es/context/MotionContext/utils.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3ec9c8ec9a8decf3a3c2e37de46581a05b358efc --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/context/MotionContext/utils.mjs @@ -0,0 +1,17 @@ +import { isControllingVariants } from '../../render/utils/is-controlling-variants.mjs'; +import { isVariantLabel } from '../../render/utils/is-variant-label.mjs'; + +function getCurrentTreeVariants(props, context) { + if (isControllingVariants(props)) { + const { initial, animate } = props; + return { + initial: initial === false || isVariantLabel(initial) + ? initial + : undefined, + animate: isVariantLabel(animate) ? animate : undefined, + }; + } + return props.inherit !== false ? context : {}; +} + +export { getCurrentTreeVariants }; diff --git a/frontend/node_modules/framer-motion/dist/es/context/PresenceContext.mjs b/frontend/node_modules/framer-motion/dist/es/context/PresenceContext.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6b00c1e5cb205b47bccf86148f8c2c228501e247 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/context/PresenceContext.mjs @@ -0,0 +1,10 @@ +"use client"; +import { createContext } from 'react'; + +/** + * @public + */ +const PresenceContext = +/* @__PURE__ */ createContext(null); + +export { PresenceContext }; diff --git a/frontend/node_modules/framer-motion/dist/es/context/ReorderContext.mjs b/frontend/node_modules/framer-motion/dist/es/context/ReorderContext.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5bc3a57e6f316ce26ced30971eeb2a449f411f1f --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/context/ReorderContext.mjs @@ -0,0 +1,6 @@ +"use client"; +import { createContext } from 'react'; + +const ReorderContext = createContext(null); + +export { ReorderContext }; diff --git a/frontend/node_modules/framer-motion/dist/es/context/SwitchLayoutGroupContext.mjs b/frontend/node_modules/framer-motion/dist/es/context/SwitchLayoutGroupContext.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f2062513c1aa1077d9f4155a30672cea1049f4b8 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/context/SwitchLayoutGroupContext.mjs @@ -0,0 +1,9 @@ +"use client"; +import { createContext } from 'react'; + +/** + * Internal, exported only for usage in Framer + */ +const SwitchLayoutGroupContext = createContext({}); + +export { SwitchLayoutGroupContext }; diff --git a/frontend/node_modules/framer-motion/dist/es/debug.mjs b/frontend/node_modules/framer-motion/dist/es/debug.mjs new file mode 100644 index 0000000000000000000000000000000000000000..75f15e3bd06dc61cce5ea8147180afa31311d56b --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/debug.mjs @@ -0,0 +1 @@ +export { recordStats } from 'motion-dom'; diff --git a/frontend/node_modules/framer-motion/dist/es/dom-mini.mjs b/frontend/node_modules/framer-motion/dist/es/dom-mini.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bcc1915a863ce60ec7f988ed164f9ee2d7aad758 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/dom-mini.mjs @@ -0,0 +1,2 @@ +export { animateSequence } from './animation/animators/waapi/animate-sequence.mjs'; +export { animateMini as animate } from './animation/animators/waapi/animate-style.mjs'; diff --git a/frontend/node_modules/framer-motion/dist/es/dom.mjs b/frontend/node_modules/framer-motion/dist/es/dom.mjs new file mode 100644 index 0000000000000000000000000000000000000000..998703f9af8e096c0140af0bd3c1b1c45f13c409 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/dom.mjs @@ -0,0 +1,9 @@ +export * from 'motion-dom'; +export * from 'motion-utils'; +export { animate, createScopedAnimate } from './animation/animate/index.mjs'; +export { animateMini } from './animation/animators/waapi/animate-style.mjs'; +export { scroll } from './render/dom/scroll/index.mjs'; +export { scrollInfo } from './render/dom/scroll/track.mjs'; +export { inView } from './render/dom/viewport/index.mjs'; +export { delayInSeconds as delay } from './utils/delay.mjs'; +export { distance, distance2D } from './utils/distance.mjs'; diff --git a/frontend/node_modules/framer-motion/dist/es/events/add-dom-event.mjs b/frontend/node_modules/framer-motion/dist/es/events/add-dom-event.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5f0a2fd853f14ef443b01d605d9b621a94b615d3 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/events/add-dom-event.mjs @@ -0,0 +1,6 @@ +function addDomEvent(target, eventName, handler, options = { passive: true }) { + target.addEventListener(eventName, handler, options); + return () => target.removeEventListener(eventName, handler); +} + +export { addDomEvent }; diff --git a/frontend/node_modules/framer-motion/dist/es/events/add-pointer-event.mjs b/frontend/node_modules/framer-motion/dist/es/events/add-pointer-event.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7ebf1ff5130b1b97bdf343034f5d7ef4cc6e498d --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/events/add-pointer-event.mjs @@ -0,0 +1,8 @@ +import { addDomEvent } from './add-dom-event.mjs'; +import { addPointerInfo } from './event-info.mjs'; + +function addPointerEvent(target, eventName, handler, options) { + return addDomEvent(target, eventName, addPointerInfo(handler), options); +} + +export { addPointerEvent }; diff --git a/frontend/node_modules/framer-motion/dist/es/events/event-info.mjs b/frontend/node_modules/framer-motion/dist/es/events/event-info.mjs new file mode 100644 index 0000000000000000000000000000000000000000..91e60b533ebeb8d3389459652089ed4faff5ed0f --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/events/event-info.mjs @@ -0,0 +1,15 @@ +import { isPrimaryPointer } from 'motion-dom'; + +function extractEventInfo(event) { + return { + point: { + x: event.pageX, + y: event.pageY, + }, + }; +} +const addPointerInfo = (handler) => { + return (event) => isPrimaryPointer(event) && handler(event, extractEventInfo(event)); +}; + +export { addPointerInfo, extractEventInfo }; diff --git a/frontend/node_modules/framer-motion/dist/es/events/use-dom-event.mjs b/frontend/node_modules/framer-motion/dist/es/events/use-dom-event.mjs new file mode 100644 index 0000000000000000000000000000000000000000..809d497bf82e405a30104a19facdb2a6acaf6631 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/events/use-dom-event.mjs @@ -0,0 +1,34 @@ +import { useEffect } from 'react'; +import { addDomEvent } from './add-dom-event.mjs'; + +/** + * Attaches an event listener directly to the provided DOM element. + * + * Bypassing React's event system can be desirable, for instance when attaching non-passive + * event handlers. + * + * ```jsx + * const ref = useRef(null) + * + * useDomEvent(ref, 'wheel', onWheel, { passive: false }) + * + * return
+ * ``` + * + * @param ref - React.RefObject that's been provided to the element you want to bind the listener to. + * @param eventName - Name of the event you want listen for. + * @param handler - Function to fire when receiving the event. + * @param options - Options to pass to `Event.addEventListener`. + * + * @public + */ +function useDomEvent(ref, eventName, handler, options) { + useEffect(() => { + const element = ref.current; + if (handler && element) { + return addDomEvent(element, eventName, handler, options); + } + }, [ref, eventName, handler, options]); +} + +export { useDomEvent }; diff --git a/frontend/node_modules/framer-motion/dist/es/gestures/drag/VisualElementDragControls.mjs b/frontend/node_modules/framer-motion/dist/es/gestures/drag/VisualElementDragControls.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8fd50b735cf3522a643d526e592e4e286b9488c9 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/gestures/drag/VisualElementDragControls.mjs @@ -0,0 +1,498 @@ +import { frame, mixNumber, setDragLock, percent } from 'motion-dom'; +import { invariant } from 'motion-utils'; +import { animateMotionValue } from '../../animation/interfaces/motion-value.mjs'; +import { addDomEvent } from '../../events/add-dom-event.mjs'; +import { addPointerEvent } from '../../events/add-pointer-event.mjs'; +import { extractEventInfo } from '../../events/event-info.mjs'; +import { convertBoxToBoundingBox, convertBoundingBoxToBox } from '../../projection/geometry/conversion.mjs'; +import { calcLength } from '../../projection/geometry/delta-calc.mjs'; +import { createBox } from '../../projection/geometry/models.mjs'; +import { eachAxis } from '../../projection/utils/each-axis.mjs'; +import { measurePageBox } from '../../projection/utils/measure.mjs'; +import { getContextWindow } from '../../utils/get-context-window.mjs'; +import { isRefObject } from '../../utils/is-ref-object.mjs'; +import { addValueToWillChange } from '../../value/use-will-change/add-will-change.mjs'; +import { PanSession } from '../pan/PanSession.mjs'; +import { applyConstraints, calcRelativeConstraints, resolveDragElastic, rebaseAxisConstraints, calcViewportConstraints, calcOrigin, defaultElastic } from './utils/constraints.mjs'; + +const elementDragControls = new WeakMap(); +class VisualElementDragControls { + constructor(visualElement) { + this.openDragLock = null; + this.isDragging = false; + this.currentDirection = null; + this.originPoint = { x: 0, y: 0 }; + /** + * The permitted boundaries of travel, in pixels. + */ + this.constraints = false; + this.hasMutatedConstraints = false; + /** + * The per-axis resolved elastic values. + */ + this.elastic = createBox(); + /** + * The latest pointer event. Used as fallback when the `cancel` and `stop` functions are called without arguments. + */ + this.latestPointerEvent = null; + /** + * The latest pan info. Used as fallback when the `cancel` and `stop` functions are called without arguments. + */ + this.latestPanInfo = null; + this.visualElement = visualElement; + } + start(originEvent, { snapToCursor = false, distanceThreshold } = {}) { + /** + * Don't start dragging if this component is exiting + */ + const { presenceContext } = this.visualElement; + if (presenceContext && presenceContext.isPresent === false) + return; + const onSessionStart = (event) => { + const { dragSnapToOrigin } = this.getProps(); + // Stop or pause any animations on both axis values immediately. This allows the user to throw and catch + // the component. + dragSnapToOrigin ? this.pauseAnimation() : this.stopAnimation(); + if (snapToCursor) { + this.snapToCursor(extractEventInfo(event).point); + } + }; + const onStart = (event, info) => { + // Attempt to grab the global drag gesture lock - maybe make this part of PanSession + const { drag, dragPropagation, onDragStart } = this.getProps(); + if (drag && !dragPropagation) { + if (this.openDragLock) + this.openDragLock(); + this.openDragLock = setDragLock(drag); + // If we don 't have the lock, don't start dragging + if (!this.openDragLock) + return; + } + this.latestPointerEvent = event; + this.latestPanInfo = info; + this.isDragging = true; + this.currentDirection = null; + this.resolveConstraints(); + if (this.visualElement.projection) { + this.visualElement.projection.isAnimationBlocked = true; + this.visualElement.projection.target = undefined; + } + /** + * Record gesture origin + */ + eachAxis((axis) => { + let current = this.getAxisMotionValue(axis).get() || 0; + /** + * If the MotionValue is a percentage value convert to px + */ + if (percent.test(current)) { + const { projection } = this.visualElement; + if (projection && projection.layout) { + const measuredAxis = projection.layout.layoutBox[axis]; + if (measuredAxis) { + const length = calcLength(measuredAxis); + current = length * (parseFloat(current) / 100); + } + } + } + this.originPoint[axis] = current; + }); + // Fire onDragStart event + if (onDragStart) { + frame.postRender(() => onDragStart(event, info)); + } + addValueToWillChange(this.visualElement, "transform"); + const { animationState } = this.visualElement; + animationState && animationState.setActive("whileDrag", true); + }; + const onMove = (event, info) => { + this.latestPointerEvent = event; + this.latestPanInfo = info; + const { dragPropagation, dragDirectionLock, onDirectionLock, onDrag, } = this.getProps(); + // If we didn't successfully receive the gesture lock, early return. + if (!dragPropagation && !this.openDragLock) + return; + const { offset } = info; + // Attempt to detect drag direction if directionLock is true + if (dragDirectionLock && this.currentDirection === null) { + this.currentDirection = getCurrentDirection(offset); + // If we've successfully set a direction, notify listener + if (this.currentDirection !== null) { + onDirectionLock && onDirectionLock(this.currentDirection); + } + return; + } + // Update each point with the latest position + this.updateAxis("x", info.point, offset); + this.updateAxis("y", info.point, offset); + /** + * Ideally we would leave the renderer to fire naturally at the end of + * this frame but if the element is about to change layout as the result + * of a re-render we want to ensure the browser can read the latest + * bounding box to ensure the pointer and element don't fall out of sync. + */ + this.visualElement.render(); + /** + * This must fire after the render call as it might trigger a state + * change which itself might trigger a layout update. + */ + onDrag && onDrag(event, info); + }; + const onSessionEnd = (event, info) => { + this.latestPointerEvent = event; + this.latestPanInfo = info; + this.stop(event, info); + this.latestPointerEvent = null; + this.latestPanInfo = null; + }; + const resumeAnimation = () => eachAxis((axis) => this.getAnimationState(axis) === "paused" && + this.getAxisMotionValue(axis).animation?.play()); + const { dragSnapToOrigin } = this.getProps(); + this.panSession = new PanSession(originEvent, { + onSessionStart, + onStart, + onMove, + onSessionEnd, + resumeAnimation, + }, { + transformPagePoint: this.visualElement.getTransformPagePoint(), + dragSnapToOrigin, + distanceThreshold, + contextWindow: getContextWindow(this.visualElement), + }); + } + /** + * @internal + */ + stop(event, panInfo) { + const finalEvent = event || this.latestPointerEvent; + const finalPanInfo = panInfo || this.latestPanInfo; + const isDragging = this.isDragging; + this.cancel(); + if (!isDragging || !finalPanInfo || !finalEvent) + return; + const { velocity } = finalPanInfo; + this.startAnimation(velocity); + const { onDragEnd } = this.getProps(); + if (onDragEnd) { + frame.postRender(() => onDragEnd(finalEvent, finalPanInfo)); + } + } + /** + * @internal + */ + cancel() { + this.isDragging = false; + const { projection, animationState } = this.visualElement; + if (projection) { + projection.isAnimationBlocked = false; + } + this.panSession && this.panSession.end(); + this.panSession = undefined; + const { dragPropagation } = this.getProps(); + if (!dragPropagation && this.openDragLock) { + this.openDragLock(); + this.openDragLock = null; + } + animationState && animationState.setActive("whileDrag", false); + } + updateAxis(axis, _point, offset) { + const { drag } = this.getProps(); + // If we're not dragging this axis, do an early return. + if (!offset || !shouldDrag(axis, drag, this.currentDirection)) + return; + const axisValue = this.getAxisMotionValue(axis); + let next = this.originPoint[axis] + offset[axis]; + // Apply constraints + if (this.constraints && this.constraints[axis]) { + next = applyConstraints(next, this.constraints[axis], this.elastic[axis]); + } + axisValue.set(next); + } + resolveConstraints() { + const { dragConstraints, dragElastic } = this.getProps(); + const layout = this.visualElement.projection && + !this.visualElement.projection.layout + ? this.visualElement.projection.measure(false) + : this.visualElement.projection?.layout; + const prevConstraints = this.constraints; + if (dragConstraints && isRefObject(dragConstraints)) { + if (!this.constraints) { + this.constraints = this.resolveRefConstraints(); + } + } + else { + if (dragConstraints && layout) { + this.constraints = calcRelativeConstraints(layout.layoutBox, dragConstraints); + } + else { + this.constraints = false; + } + } + this.elastic = resolveDragElastic(dragElastic); + /** + * If we're outputting to external MotionValues, we want to rebase the measured constraints + * from viewport-relative to component-relative. + */ + if (prevConstraints !== this.constraints && + layout && + this.constraints && + !this.hasMutatedConstraints) { + eachAxis((axis) => { + if (this.constraints !== false && + this.getAxisMotionValue(axis)) { + this.constraints[axis] = rebaseAxisConstraints(layout.layoutBox[axis], this.constraints[axis]); + } + }); + } + } + resolveRefConstraints() { + const { dragConstraints: constraints, onMeasureDragConstraints } = this.getProps(); + if (!constraints || !isRefObject(constraints)) + return false; + const constraintsElement = constraints.current; + invariant(constraintsElement !== null, "If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.", "drag-constraints-ref"); + const { projection } = this.visualElement; + // TODO + if (!projection || !projection.layout) + return false; + const constraintsBox = measurePageBox(constraintsElement, projection.root, this.visualElement.getTransformPagePoint()); + let measuredConstraints = calcViewportConstraints(projection.layout.layoutBox, constraintsBox); + /** + * If there's an onMeasureDragConstraints listener we call it and + * if different constraints are returned, set constraints to that + */ + if (onMeasureDragConstraints) { + const userConstraints = onMeasureDragConstraints(convertBoxToBoundingBox(measuredConstraints)); + this.hasMutatedConstraints = !!userConstraints; + if (userConstraints) { + measuredConstraints = convertBoundingBoxToBox(userConstraints); + } + } + return measuredConstraints; + } + startAnimation(velocity) { + const { drag, dragMomentum, dragElastic, dragTransition, dragSnapToOrigin, onDragTransitionEnd, } = this.getProps(); + const constraints = this.constraints || {}; + const momentumAnimations = eachAxis((axis) => { + if (!shouldDrag(axis, drag, this.currentDirection)) { + return; + } + let transition = (constraints && constraints[axis]) || {}; + if (dragSnapToOrigin) + transition = { min: 0, max: 0 }; + /** + * Overdamp the boundary spring if `dragElastic` is disabled. There's still a frame + * of spring animations so we should look into adding a disable spring option to `inertia`. + * We could do something here where we affect the `bounceStiffness` and `bounceDamping` + * using the value of `dragElastic`. + */ + const bounceStiffness = dragElastic ? 200 : 1000000; + const bounceDamping = dragElastic ? 40 : 10000000; + const inertia = { + type: "inertia", + velocity: dragMomentum ? velocity[axis] : 0, + bounceStiffness, + bounceDamping, + timeConstant: 750, + restDelta: 1, + restSpeed: 10, + ...dragTransition, + ...transition, + }; + // If we're not animating on an externally-provided `MotionValue` we can use the + // component's animation controls which will handle interactions with whileHover (etc), + // otherwise we just have to animate the `MotionValue` itself. + return this.startAxisValueAnimation(axis, inertia); + }); + // Run all animations and then resolve the new drag constraints. + return Promise.all(momentumAnimations).then(onDragTransitionEnd); + } + startAxisValueAnimation(axis, transition) { + const axisValue = this.getAxisMotionValue(axis); + addValueToWillChange(this.visualElement, axis); + return axisValue.start(animateMotionValue(axis, axisValue, 0, transition, this.visualElement, false)); + } + stopAnimation() { + eachAxis((axis) => this.getAxisMotionValue(axis).stop()); + } + pauseAnimation() { + eachAxis((axis) => this.getAxisMotionValue(axis).animation?.pause()); + } + getAnimationState(axis) { + return this.getAxisMotionValue(axis).animation?.state; + } + /** + * Drag works differently depending on which props are provided. + * + * - If _dragX and _dragY are provided, we output the gesture delta directly to those motion values. + * - Otherwise, we apply the delta to the x/y motion values. + */ + getAxisMotionValue(axis) { + const dragKey = `_drag${axis.toUpperCase()}`; + const props = this.visualElement.getProps(); + const externalMotionValue = props[dragKey]; + return externalMotionValue + ? externalMotionValue + : this.visualElement.getValue(axis, (props.initial + ? props.initial[axis] + : undefined) || 0); + } + snapToCursor(point) { + eachAxis((axis) => { + const { drag } = this.getProps(); + // If we're not dragging this axis, do an early return. + if (!shouldDrag(axis, drag, this.currentDirection)) + return; + const { projection } = this.visualElement; + const axisValue = this.getAxisMotionValue(axis); + if (projection && projection.layout) { + const { min, max } = projection.layout.layoutBox[axis]; + axisValue.set(point[axis] - mixNumber(min, max, 0.5)); + } + }); + } + /** + * When the viewport resizes we want to check if the measured constraints + * have changed and, if so, reposition the element within those new constraints + * relative to where it was before the resize. + */ + scalePositionWithinConstraints() { + if (!this.visualElement.current) + return; + const { drag, dragConstraints } = this.getProps(); + const { projection } = this.visualElement; + if (!isRefObject(dragConstraints) || !projection || !this.constraints) + return; + /** + * Stop current animations as there can be visual glitching if we try to do + * this mid-animation + */ + this.stopAnimation(); + /** + * Record the relative position of the dragged element relative to the + * constraints box and save as a progress value. + */ + const boxProgress = { x: 0, y: 0 }; + eachAxis((axis) => { + const axisValue = this.getAxisMotionValue(axis); + if (axisValue && this.constraints !== false) { + const latest = axisValue.get(); + boxProgress[axis] = calcOrigin({ min: latest, max: latest }, this.constraints[axis]); + } + }); + /** + * Update the layout of this element and resolve the latest drag constraints + */ + const { transformTemplate } = this.visualElement.getProps(); + this.visualElement.current.style.transform = transformTemplate + ? transformTemplate({}, "") + : "none"; + projection.root && projection.root.updateScroll(); + projection.updateLayout(); + this.resolveConstraints(); + /** + * For each axis, calculate the current progress of the layout axis + * within the new constraints. + */ + eachAxis((axis) => { + if (!shouldDrag(axis, drag, null)) + return; + /** + * Calculate a new transform based on the previous box progress + */ + const axisValue = this.getAxisMotionValue(axis); + const { min, max } = this.constraints[axis]; + axisValue.set(mixNumber(min, max, boxProgress[axis])); + }); + } + addListeners() { + if (!this.visualElement.current) + return; + elementDragControls.set(this.visualElement, this); + const element = this.visualElement.current; + /** + * Attach a pointerdown event listener on this DOM element to initiate drag tracking. + */ + const stopPointerListener = addPointerEvent(element, "pointerdown", (event) => { + const { drag, dragListener = true } = this.getProps(); + drag && dragListener && this.start(event); + }); + const measureDragConstraints = () => { + const { dragConstraints } = this.getProps(); + if (isRefObject(dragConstraints) && dragConstraints.current) { + this.constraints = this.resolveRefConstraints(); + } + }; + const { projection } = this.visualElement; + const stopMeasureLayoutListener = projection.addEventListener("measure", measureDragConstraints); + if (projection && !projection.layout) { + projection.root && projection.root.updateScroll(); + projection.updateLayout(); + } + frame.read(measureDragConstraints); + /** + * Attach a window resize listener to scale the draggable target within its defined + * constraints as the window resizes. + */ + const stopResizeListener = addDomEvent(window, "resize", () => this.scalePositionWithinConstraints()); + /** + * If the element's layout changes, calculate the delta and apply that to + * the drag gesture's origin point. + */ + const stopLayoutUpdateListener = projection.addEventListener("didUpdate", (({ delta, hasLayoutChanged }) => { + if (this.isDragging && hasLayoutChanged) { + eachAxis((axis) => { + const motionValue = this.getAxisMotionValue(axis); + if (!motionValue) + return; + this.originPoint[axis] += delta[axis].translate; + motionValue.set(motionValue.get() + delta[axis].translate); + }); + this.visualElement.render(); + } + })); + return () => { + stopResizeListener(); + stopPointerListener(); + stopMeasureLayoutListener(); + stopLayoutUpdateListener && stopLayoutUpdateListener(); + }; + } + getProps() { + const props = this.visualElement.getProps(); + const { drag = false, dragDirectionLock = false, dragPropagation = false, dragConstraints = false, dragElastic = defaultElastic, dragMomentum = true, } = props; + return { + ...props, + drag, + dragDirectionLock, + dragPropagation, + dragConstraints, + dragElastic, + dragMomentum, + }; + } +} +function shouldDrag(direction, drag, currentDirection) { + return ((drag === true || drag === direction) && + (currentDirection === null || currentDirection === direction)); +} +/** + * Based on an x/y offset determine the current drag direction. If both axis' offsets are lower + * than the provided threshold, return `null`. + * + * @param offset - The x/y offset from origin. + * @param lockThreshold - (Optional) - the minimum absolute offset before we can determine a drag direction. + */ +function getCurrentDirection(offset, lockThreshold = 10) { + let direction = null; + if (Math.abs(offset.y) > lockThreshold) { + direction = "y"; + } + else if (Math.abs(offset.x) > lockThreshold) { + direction = "x"; + } + return direction; +} + +export { VisualElementDragControls, elementDragControls }; diff --git a/frontend/node_modules/framer-motion/dist/es/gestures/drag/index.mjs b/frontend/node_modules/framer-motion/dist/es/gestures/drag/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5d968ae7ff3f15126d3110ddc908cf6bc1bd3ad5 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/gestures/drag/index.mjs @@ -0,0 +1,27 @@ +import { Feature } from '../../motion/features/Feature.mjs'; +import { noop } from 'motion-utils'; +import { VisualElementDragControls } from './VisualElementDragControls.mjs'; + +class DragGesture extends Feature { + constructor(node) { + super(node); + this.removeGroupControls = noop; + this.removeListeners = noop; + this.controls = new VisualElementDragControls(node); + } + mount() { + // If we've been provided a DragControls for manual control over the drag gesture, + // subscribe this component to it on mount. + const { dragControls } = this.node.getProps(); + if (dragControls) { + this.removeGroupControls = dragControls.subscribe(this.controls); + } + this.removeListeners = this.controls.addListeners() || noop; + } + unmount() { + this.removeGroupControls(); + this.removeListeners(); + } +} + +export { DragGesture }; diff --git a/frontend/node_modules/framer-motion/dist/es/gestures/drag/use-drag-controls.mjs b/frontend/node_modules/framer-motion/dist/es/gestures/drag/use-drag-controls.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5c2b45cb430134340c29c4fbf8ac17ba7319c8e6 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/gestures/drag/use-drag-controls.mjs @@ -0,0 +1,116 @@ +import { useConstant } from '../../utils/use-constant.mjs'; + +/** + * Can manually trigger a drag gesture on one or more `drag`-enabled `motion` components. + * + * ```jsx + * const dragControls = useDragControls() + * + * function startDrag(event) { + * dragControls.start(event, { snapToCursor: true }) + * } + * + * return ( + * <> + *
+ * + * + * ) + * ``` + * + * @public + */ +class DragControls { + constructor() { + this.componentControls = new Set(); + } + /** + * Subscribe a component's internal `VisualElementDragControls` to the user-facing API. + * + * @internal + */ + subscribe(controls) { + this.componentControls.add(controls); + return () => this.componentControls.delete(controls); + } + /** + * Start a drag gesture on every `motion` component that has this set of drag controls + * passed into it via the `dragControls` prop. + * + * ```jsx + * dragControls.start(e, { + * snapToCursor: true + * }) + * ``` + * + * @param event - PointerEvent + * @param options - Options + * + * @public + */ + start(event, options) { + this.componentControls.forEach((controls) => { + controls.start(event.nativeEvent || event, options); + }); + } + /** + * Cancels a drag gesture. + * + * ```jsx + * dragControls.cancel() + * ``` + * + * @public + */ + cancel() { + this.componentControls.forEach((controls) => { + controls.cancel(); + }); + } + /** + * Stops a drag gesture. + * + * ```jsx + * dragControls.stop() + * ``` + * + * @public + */ + stop() { + this.componentControls.forEach((controls) => { + controls.stop(); + }); + } +} +const createDragControls = () => new DragControls(); +/** + * Usually, dragging is initiated by pressing down on a `motion` component with a `drag` prop + * and moving it. For some use-cases, for instance clicking at an arbitrary point on a video scrubber, we + * might want to initiate that dragging from a different component than the draggable one. + * + * By creating a `dragControls` using the `useDragControls` hook, we can pass this into + * the draggable component's `dragControls` prop. It exposes a `start` method + * that can start dragging from pointer events on other components. + * + * ```jsx + * const dragControls = useDragControls() + * + * function startDrag(event) { + * dragControls.start(event, { snapToCursor: true }) + * } + * + * return ( + * <> + *
+ * + * + * ) + * ``` + * + * @public + */ +function useDragControls() { + return useConstant(createDragControls); +} + +export { DragControls, useDragControls }; diff --git a/frontend/node_modules/framer-motion/dist/es/gestures/drag/utils/constraints.mjs b/frontend/node_modules/framer-motion/dist/es/gestures/drag/utils/constraints.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5a39d8d6cdc39eb6078887e63b13f4168e3c680c --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/gestures/drag/utils/constraints.mjs @@ -0,0 +1,128 @@ +import { mixNumber } from 'motion-dom'; +import { progress, clamp } from 'motion-utils'; +import { calcLength } from '../../../projection/geometry/delta-calc.mjs'; + +/** + * Apply constraints to a point. These constraints are both physical along an + * axis, and an elastic factor that determines how much to constrain the point + * by if it does lie outside the defined parameters. + */ +function applyConstraints(point, { min, max }, elastic) { + if (min !== undefined && point < min) { + // If we have a min point defined, and this is outside of that, constrain + point = elastic + ? mixNumber(min, point, elastic.min) + : Math.max(point, min); + } + else if (max !== undefined && point > max) { + // If we have a max point defined, and this is outside of that, constrain + point = elastic + ? mixNumber(max, point, elastic.max) + : Math.min(point, max); + } + return point; +} +/** + * Calculate constraints in terms of the viewport when defined relatively to the + * measured axis. This is measured from the nearest edge, so a max constraint of 200 + * on an axis with a max value of 300 would return a constraint of 500 - axis length + */ +function calcRelativeAxisConstraints(axis, min, max) { + return { + min: min !== undefined ? axis.min + min : undefined, + max: max !== undefined + ? axis.max + max - (axis.max - axis.min) + : undefined, + }; +} +/** + * Calculate constraints in terms of the viewport when + * defined relatively to the measured bounding box. + */ +function calcRelativeConstraints(layoutBox, { top, left, bottom, right }) { + return { + x: calcRelativeAxisConstraints(layoutBox.x, left, right), + y: calcRelativeAxisConstraints(layoutBox.y, top, bottom), + }; +} +/** + * Calculate viewport constraints when defined as another viewport-relative axis + */ +function calcViewportAxisConstraints(layoutAxis, constraintsAxis) { + let min = constraintsAxis.min - layoutAxis.min; + let max = constraintsAxis.max - layoutAxis.max; + // If the constraints axis is actually smaller than the layout axis then we can + // flip the constraints + if (constraintsAxis.max - constraintsAxis.min < + layoutAxis.max - layoutAxis.min) { + [min, max] = [max, min]; + } + return { min, max }; +} +/** + * Calculate viewport constraints when defined as another viewport-relative box + */ +function calcViewportConstraints(layoutBox, constraintsBox) { + return { + x: calcViewportAxisConstraints(layoutBox.x, constraintsBox.x), + y: calcViewportAxisConstraints(layoutBox.y, constraintsBox.y), + }; +} +/** + * Calculate a transform origin relative to the source axis, between 0-1, that results + * in an asthetically pleasing scale/transform needed to project from source to target. + */ +function calcOrigin(source, target) { + let origin = 0.5; + const sourceLength = calcLength(source); + const targetLength = calcLength(target); + if (targetLength > sourceLength) { + origin = progress(target.min, target.max - sourceLength, source.min); + } + else if (sourceLength > targetLength) { + origin = progress(source.min, source.max - targetLength, target.min); + } + return clamp(0, 1, origin); +} +/** + * Rebase the calculated viewport constraints relative to the layout.min point. + */ +function rebaseAxisConstraints(layout, constraints) { + const relativeConstraints = {}; + if (constraints.min !== undefined) { + relativeConstraints.min = constraints.min - layout.min; + } + if (constraints.max !== undefined) { + relativeConstraints.max = constraints.max - layout.min; + } + return relativeConstraints; +} +const defaultElastic = 0.35; +/** + * Accepts a dragElastic prop and returns resolved elastic values for each axis. + */ +function resolveDragElastic(dragElastic = defaultElastic) { + if (dragElastic === false) { + dragElastic = 0; + } + else if (dragElastic === true) { + dragElastic = defaultElastic; + } + return { + x: resolveAxisElastic(dragElastic, "left", "right"), + y: resolveAxisElastic(dragElastic, "top", "bottom"), + }; +} +function resolveAxisElastic(dragElastic, minLabel, maxLabel) { + return { + min: resolvePointElastic(dragElastic, minLabel), + max: resolvePointElastic(dragElastic, maxLabel), + }; +} +function resolvePointElastic(dragElastic, label) { + return typeof dragElastic === "number" + ? dragElastic + : dragElastic[label] || 0; +} + +export { applyConstraints, calcOrigin, calcRelativeAxisConstraints, calcRelativeConstraints, calcViewportAxisConstraints, calcViewportConstraints, defaultElastic, rebaseAxisConstraints, resolveAxisElastic, resolveDragElastic, resolvePointElastic }; diff --git a/frontend/node_modules/framer-motion/dist/es/gestures/focus.mjs b/frontend/node_modules/framer-motion/dist/es/gestures/focus.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4ad76bf5af44e8439ee6d51f7e2c09971955bd6f --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/gestures/focus.mjs @@ -0,0 +1,41 @@ +import { pipe } from 'motion-utils'; +import { addDomEvent } from '../events/add-dom-event.mjs'; +import { Feature } from '../motion/features/Feature.mjs'; + +class FocusGesture extends Feature { + constructor() { + super(...arguments); + this.isActive = false; + } + onFocus() { + let isFocusVisible = false; + /** + * If this element doesn't match focus-visible then don't + * apply whileHover. But, if matches throws that focus-visible + * is not a valid selector then in that browser outline styles will be applied + * to the element by default and we want to match that behaviour with whileFocus. + */ + try { + isFocusVisible = this.node.current.matches(":focus-visible"); + } + catch (e) { + isFocusVisible = true; + } + if (!isFocusVisible || !this.node.animationState) + return; + this.node.animationState.setActive("whileFocus", true); + this.isActive = true; + } + onBlur() { + if (!this.isActive || !this.node.animationState) + return; + this.node.animationState.setActive("whileFocus", false); + this.isActive = false; + } + mount() { + this.unmount = pipe(addDomEvent(this.node.current, "focus", () => this.onFocus()), addDomEvent(this.node.current, "blur", () => this.onBlur())); + } + unmount() { } +} + +export { FocusGesture }; diff --git a/frontend/node_modules/framer-motion/dist/es/gestures/hover.mjs b/frontend/node_modules/framer-motion/dist/es/gestures/hover.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8a86a72b7c563c93694bad734b5856b2a4d1f7be --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/gestures/hover.mjs @@ -0,0 +1,29 @@ +import { hover, frame } from 'motion-dom'; +import { extractEventInfo } from '../events/event-info.mjs'; +import { Feature } from '../motion/features/Feature.mjs'; + +function handleHoverEvent(node, event, lifecycle) { + const { props } = node; + if (node.animationState && props.whileHover) { + node.animationState.setActive("whileHover", lifecycle === "Start"); + } + const eventName = ("onHover" + lifecycle); + const callback = props[eventName]; + if (callback) { + frame.postRender(() => callback(event, extractEventInfo(event))); + } +} +class HoverGesture extends Feature { + mount() { + const { current } = this.node; + if (!current) + return; + this.unmount = hover(current, (_element, startEvent) => { + handleHoverEvent(this.node, startEvent, "Start"); + return (endEvent) => handleHoverEvent(this.node, endEvent, "End"); + }); + } + unmount() { } +} + +export { HoverGesture }; diff --git a/frontend/node_modules/framer-motion/dist/es/gestures/pan/PanSession.mjs b/frontend/node_modules/framer-motion/dist/es/gestures/pan/PanSession.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a690c2703e51b9f3caf9984cead5dc19d090a22a --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/gestures/pan/PanSession.mjs @@ -0,0 +1,155 @@ +import { frame, isPrimaryPointer, cancelFrame, frameData } from 'motion-dom'; +import { pipe, secondsToMilliseconds, millisecondsToSeconds } from 'motion-utils'; +import { addPointerEvent } from '../../events/add-pointer-event.mjs'; +import { extractEventInfo } from '../../events/event-info.mjs'; +import { distance2D } from '../../utils/distance.mjs'; + +/** + * @internal + */ +class PanSession { + constructor(event, handlers, { transformPagePoint, contextWindow = window, dragSnapToOrigin = false, distanceThreshold = 3, } = {}) { + /** + * @internal + */ + this.startEvent = null; + /** + * @internal + */ + this.lastMoveEvent = null; + /** + * @internal + */ + this.lastMoveEventInfo = null; + /** + * @internal + */ + this.handlers = {}; + /** + * @internal + */ + this.contextWindow = window; + this.updatePoint = () => { + if (!(this.lastMoveEvent && this.lastMoveEventInfo)) + return; + const info = getPanInfo(this.lastMoveEventInfo, this.history); + const isPanStarted = this.startEvent !== null; + // Only start panning if the offset is larger than 3 pixels. If we make it + // any larger than this we'll want to reset the pointer history + // on the first update to avoid visual snapping to the cursor. + const isDistancePastThreshold = distance2D(info.offset, { x: 0, y: 0 }) >= this.distanceThreshold; + if (!isPanStarted && !isDistancePastThreshold) + return; + const { point } = info; + const { timestamp } = frameData; + this.history.push({ ...point, timestamp }); + const { onStart, onMove } = this.handlers; + if (!isPanStarted) { + onStart && onStart(this.lastMoveEvent, info); + this.startEvent = this.lastMoveEvent; + } + onMove && onMove(this.lastMoveEvent, info); + }; + this.handlePointerMove = (event, info) => { + this.lastMoveEvent = event; + this.lastMoveEventInfo = transformPoint(info, this.transformPagePoint); + // Throttle mouse move event to once per frame + frame.update(this.updatePoint, true); + }; + this.handlePointerUp = (event, info) => { + this.end(); + const { onEnd, onSessionEnd, resumeAnimation } = this.handlers; + if (this.dragSnapToOrigin) + resumeAnimation && resumeAnimation(); + if (!(this.lastMoveEvent && this.lastMoveEventInfo)) + return; + const panInfo = getPanInfo(event.type === "pointercancel" + ? this.lastMoveEventInfo + : transformPoint(info, this.transformPagePoint), this.history); + if (this.startEvent && onEnd) { + onEnd(event, panInfo); + } + onSessionEnd && onSessionEnd(event, panInfo); + }; + // If we have more than one touch, don't start detecting this gesture + if (!isPrimaryPointer(event)) + return; + this.dragSnapToOrigin = dragSnapToOrigin; + this.handlers = handlers; + this.transformPagePoint = transformPagePoint; + this.distanceThreshold = distanceThreshold; + this.contextWindow = contextWindow || window; + const info = extractEventInfo(event); + const initialInfo = transformPoint(info, this.transformPagePoint); + const { point } = initialInfo; + const { timestamp } = frameData; + this.history = [{ ...point, timestamp }]; + const { onSessionStart } = handlers; + onSessionStart && + onSessionStart(event, getPanInfo(initialInfo, this.history)); + this.removeListeners = pipe(addPointerEvent(this.contextWindow, "pointermove", this.handlePointerMove), addPointerEvent(this.contextWindow, "pointerup", this.handlePointerUp), addPointerEvent(this.contextWindow, "pointercancel", this.handlePointerUp)); + } + updateHandlers(handlers) { + this.handlers = handlers; + } + end() { + this.removeListeners && this.removeListeners(); + cancelFrame(this.updatePoint); + } +} +function transformPoint(info, transformPagePoint) { + return transformPagePoint ? { point: transformPagePoint(info.point) } : info; +} +function subtractPoint(a, b) { + return { x: a.x - b.x, y: a.y - b.y }; +} +function getPanInfo({ point }, history) { + return { + point, + delta: subtractPoint(point, lastDevicePoint(history)), + offset: subtractPoint(point, startDevicePoint(history)), + velocity: getVelocity(history, 0.1), + }; +} +function startDevicePoint(history) { + return history[0]; +} +function lastDevicePoint(history) { + return history[history.length - 1]; +} +function getVelocity(history, timeDelta) { + if (history.length < 2) { + return { x: 0, y: 0 }; + } + let i = history.length - 1; + let timestampedPoint = null; + const lastPoint = lastDevicePoint(history); + while (i >= 0) { + timestampedPoint = history[i]; + if (lastPoint.timestamp - timestampedPoint.timestamp > + secondsToMilliseconds(timeDelta)) { + break; + } + i--; + } + if (!timestampedPoint) { + return { x: 0, y: 0 }; + } + const time = millisecondsToSeconds(lastPoint.timestamp - timestampedPoint.timestamp); + if (time === 0) { + return { x: 0, y: 0 }; + } + const currentVelocity = { + x: (lastPoint.x - timestampedPoint.x) / time, + y: (lastPoint.y - timestampedPoint.y) / time, + }; + if (currentVelocity.x === Infinity) { + currentVelocity.x = 0; + } + if (currentVelocity.y === Infinity) { + currentVelocity.y = 0; + } + return currentVelocity; +} + +export { PanSession }; diff --git a/frontend/node_modules/framer-motion/dist/es/gestures/pan/index.mjs b/frontend/node_modules/framer-motion/dist/es/gestures/pan/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a6d64feb5075c86940673a68e49443230b1f68a2 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/gestures/pan/index.mjs @@ -0,0 +1,50 @@ +import { frame } from 'motion-dom'; +import { noop } from 'motion-utils'; +import { addPointerEvent } from '../../events/add-pointer-event.mjs'; +import { Feature } from '../../motion/features/Feature.mjs'; +import { getContextWindow } from '../../utils/get-context-window.mjs'; +import { PanSession } from './PanSession.mjs'; + +const asyncHandler = (handler) => (event, info) => { + if (handler) { + frame.postRender(() => handler(event, info)); + } +}; +class PanGesture extends Feature { + constructor() { + super(...arguments); + this.removePointerDownListener = noop; + } + onPointerDown(pointerDownEvent) { + this.session = new PanSession(pointerDownEvent, this.createPanHandlers(), { + transformPagePoint: this.node.getTransformPagePoint(), + contextWindow: getContextWindow(this.node), + }); + } + createPanHandlers() { + const { onPanSessionStart, onPanStart, onPan, onPanEnd } = this.node.getProps(); + return { + onSessionStart: asyncHandler(onPanSessionStart), + onStart: asyncHandler(onPanStart), + onMove: onPan, + onEnd: (event, info) => { + delete this.session; + if (onPanEnd) { + frame.postRender(() => onPanEnd(event, info)); + } + }, + }; + } + mount() { + this.removePointerDownListener = addPointerEvent(this.node.current, "pointerdown", (event) => this.onPointerDown(event)); + } + update() { + this.session && this.session.updateHandlers(this.createPanHandlers()); + } + unmount() { + this.removePointerDownListener(); + this.session && this.session.end(); + } +} + +export { PanGesture }; diff --git a/frontend/node_modules/framer-motion/dist/es/gestures/press.mjs b/frontend/node_modules/framer-motion/dist/es/gestures/press.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2c749381ea8cdd9dc5e40cfff0060b9c58660eab --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/gestures/press.mjs @@ -0,0 +1,32 @@ +import { press, frame } from 'motion-dom'; +import { extractEventInfo } from '../events/event-info.mjs'; +import { Feature } from '../motion/features/Feature.mjs'; + +function handlePressEvent(node, event, lifecycle) { + const { props } = node; + if (node.current instanceof HTMLButtonElement && node.current.disabled) { + return; + } + if (node.animationState && props.whileTap) { + node.animationState.setActive("whileTap", lifecycle === "Start"); + } + const eventName = ("onTap" + (lifecycle === "End" ? "" : lifecycle)); + const callback = props[eventName]; + if (callback) { + frame.postRender(() => callback(event, extractEventInfo(event))); + } +} +class PressGesture extends Feature { + mount() { + const { current } = this.node; + if (!current) + return; + this.unmount = press(current, (_element, startEvent) => { + handlePressEvent(this.node, startEvent, "Start"); + return (endEvent, { success }) => handlePressEvent(this.node, endEvent, success ? "End" : "Cancel"); + }, { useGlobalTarget: this.node.props.globalTapTarget }); + } + unmount() { } +} + +export { PressGesture }; diff --git a/frontend/node_modules/framer-motion/dist/es/index.mjs b/frontend/node_modules/framer-motion/dist/es/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ad3d12ca58bb70b8aafff8dd1173a9f50032aef4 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/index.mjs @@ -0,0 +1,83 @@ +"use client"; +export { AnimatePresence } from './components/AnimatePresence/index.mjs'; +export { LayoutGroup } from './components/LayoutGroup/index.mjs'; +export { LazyMotion } from './components/LazyMotion/index.mjs'; +export { MotionConfig } from './components/MotionConfig/index.mjs'; +export { m } from './render/components/m/proxy.mjs'; +export { motion } from './render/components/motion/proxy.mjs'; +export { addPointerEvent } from './events/add-pointer-event.mjs'; +export { addPointerInfo } from './events/event-info.mjs'; +export { animations } from './motion/features/animations.mjs'; +export { makeUseVisualState } from './motion/utils/use-visual-state.mjs'; +export { calcLength } from './projection/geometry/delta-calc.mjs'; +export { createBox } from './projection/geometry/models.mjs'; +export { filterProps } from './render/dom/utils/filter-props.mjs'; +export { isBrowser } from './utils/is-browser.mjs'; +export { useForceUpdate } from './utils/use-force-update.mjs'; +export { useIsomorphicLayoutEffect } from './utils/use-isomorphic-effect.mjs'; +export { useUnmountEffect } from './utils/use-unmount-effect.mjs'; +export { domAnimation } from './render/dom/features-animation.mjs'; +export { domMax } from './render/dom/features-max.mjs'; +export { domMin } from './render/dom/features-min.mjs'; +export { useMotionValueEvent } from './utils/use-motion-value-event.mjs'; +export { useElementScroll } from './value/scroll/use-element-scroll.mjs'; +export { useViewportScroll } from './value/scroll/use-viewport-scroll.mjs'; +export { useMotionTemplate } from './value/use-motion-template.mjs'; +export { useMotionValue } from './value/use-motion-value.mjs'; +export { useScroll } from './value/use-scroll.mjs'; +export { useSpring } from './value/use-spring.mjs'; +export { useTime } from './value/use-time.mjs'; +export { useTransform } from './value/use-transform.mjs'; +export { useVelocity } from './value/use-velocity.mjs'; +export { useWillChange } from './value/use-will-change/index.mjs'; +export { WillChangeMotionValue } from './value/use-will-change/WillChangeMotionValue.mjs'; +export { resolveMotionValue } from './value/utils/resolve-motion-value.mjs'; +export { useReducedMotion } from './utils/reduced-motion/use-reduced-motion.mjs'; +export { useReducedMotionConfig } from './utils/reduced-motion/use-reduced-motion-config.mjs'; +export * from 'motion-utils'; +export { MotionGlobalConfig } from 'motion-utils'; +export { animationControls } from './animation/hooks/animation-controls.mjs'; +export { useAnimate } from './animation/hooks/use-animate.mjs'; +export { useAnimateMini } from './animation/hooks/use-animate-style.mjs'; +export { useAnimation, useAnimationControls } from './animation/hooks/use-animation.mjs'; +export { animateVisualElement } from './animation/interfaces/visual-element.mjs'; +export { useIsPresent, usePresence } from './components/AnimatePresence/use-presence.mjs'; +export { usePresenceData } from './components/AnimatePresence/use-presence-data.mjs'; +export { useDomEvent } from './events/use-dom-event.mjs'; +export { DragControls, useDragControls } from './gestures/drag/use-drag-controls.mjs'; +export { isMotionComponent } from './motion/utils/is-motion-component.mjs'; +export { unwrapMotionComponent } from './motion/utils/unwrap-motion-component.mjs'; +export { isValidMotionProp } from './motion/utils/valid-prop.mjs'; +export { addScaleCorrector } from './projection/styles/scale-correction.mjs'; +export { useInstantLayoutTransition } from './projection/use-instant-layout-transition.mjs'; +export { useResetProjection } from './projection/use-reset-projection.mjs'; +export { buildTransform } from './render/html/utils/build-transform.mjs'; +export { visualElementStore } from './render/store.mjs'; +export { VisualElement } from './render/VisualElement.mjs'; +export { useAnimationFrame } from './utils/use-animation-frame.mjs'; +export { useCycle } from './utils/use-cycle.mjs'; +export { useInView } from './utils/use-in-view.mjs'; +export { disableInstantTransitions, useInstantTransition } from './utils/use-instant-transition.mjs'; +export { usePageInView } from './utils/use-page-in-view.mjs'; +export { optimizedAppearDataAttribute } from './animation/optimized-appear/data-id.mjs'; +export { startOptimizedAppearAnimation } from './animation/optimized-appear/start.mjs'; +export { LayoutGroupContext } from './context/LayoutGroupContext.mjs'; +export { MotionConfigContext } from './context/MotionConfigContext.mjs'; +export { MotionContext } from './context/MotionContext/index.mjs'; +export { PresenceContext } from './context/PresenceContext.mjs'; +export { SwitchLayoutGroupContext } from './context/SwitchLayoutGroupContext.mjs'; +export { FlatTree } from './render/utils/flat-tree.mjs'; +export { useAnimatedState as useDeprecatedAnimatedState } from './animation/hooks/use-animated-state.mjs'; +export { AnimateSharedLayout } from './components/AnimateSharedLayout.mjs'; +export { DeprecatedLayoutGroupContext } from './context/DeprecatedLayoutGroupContext.mjs'; +export { useInvertedScale as useDeprecatedInvertedScale } from './value/use-inverted-scale.mjs'; +export { delay } from './utils/delay.mjs'; +import * as namespace from './components/Reorder/namespace.mjs'; +export { namespace as Reorder }; +export { animate, createScopedAnimate } from './animation/animate/index.mjs'; +export { animateMini } from './animation/animators/waapi/animate-style.mjs'; +export { scroll } from './render/dom/scroll/index.mjs'; +export { scrollInfo } from './render/dom/scroll/track.mjs'; +export { inView } from './render/dom/viewport/index.mjs'; +export { distance, distance2D } from './utils/distance.mjs'; +export * from 'motion-dom'; diff --git a/frontend/node_modules/framer-motion/dist/es/m.mjs b/frontend/node_modules/framer-motion/dist/es/m.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5db207de3ef856cea7628b4760a4a49e7e2ea86c --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/m.mjs @@ -0,0 +1,3 @@ +"use client"; +export { createMinimalMotionComponent as create } from './render/components/m/create.mjs'; +export { MotionA as a, MotionAbbr as abbr, MotionAddress as address, MotionAnimate as animate, MotionArea as area, MotionArticle as article, MotionAside as aside, MotionAudio as audio, MotionB as b, MotionBase as base, MotionBdi as bdi, MotionBdo as bdo, MotionBig as big, MotionBlockquote as blockquote, MotionBody as body, MotionButton as button, MotionCanvas as canvas, MotionCaption as caption, MotionCircle as circle, MotionCite as cite, MotionClipPath as clipPath, MotionCode as code, MotionCol as col, MotionColgroup as colgroup, MotionData as data, MotionDatalist as datalist, MotionDd as dd, MotionDefs as defs, MotionDel as del, MotionDesc as desc, MotionDetails as details, MotionDfn as dfn, MotionDialog as dialog, MotionDiv as div, MotionDl as dl, MotionDt as dt, MotionEllipse as ellipse, MotionEm as em, MotionEmbed as embed, MotionFeBlend as feBlend, MotionFeColorMatrix as feColorMatrix, MotionFeComponentTransfer as feComponentTransfer, MotionFeComposite as feComposite, MotionFeConvolveMatrix as feConvolveMatrix, MotionFeDiffuseLighting as feDiffuseLighting, MotionFeDisplacementMap as feDisplacementMap, MotionFeDistantLight as feDistantLight, MotionFeDropShadow as feDropShadow, MotionFeFlood as feFlood, MotionFeFuncA as feFuncA, MotionFeFuncB as feFuncB, MotionFeFuncG as feFuncG, MotionFeFuncR as feFuncR, MotionFeGaussianBlur as feGaussianBlur, MotionFeImage as feImage, MotionFeMerge as feMerge, MotionFeMergeNode as feMergeNode, MotionFeMorphology as feMorphology, MotionFeOffset as feOffset, MotionFePointLight as fePointLight, MotionFeSpecularLighting as feSpecularLighting, MotionFeSpotLight as feSpotLight, MotionFeTile as feTile, MotionFeTurbulence as feTurbulence, MotionFieldset as fieldset, MotionFigcaption as figcaption, MotionFigure as figure, MotionFilter as filter, MotionFooter as footer, MotionForeignObject as foreignObject, MotionForm as form, MotionG as g, MotionH1 as h1, MotionH2 as h2, MotionH3 as h3, MotionH4 as h4, MotionH5 as h5, MotionH6 as h6, MotionHead as head, MotionHeader as header, MotionHgroup as hgroup, MotionHr as hr, MotionHtml as html, MotionI as i, MotionIframe as iframe, MotionImage as image, MotionImg as img, MotionInput as input, MotionIns as ins, MotionKbd as kbd, MotionKeygen as keygen, MotionLabel as label, MotionLegend as legend, MotionLi as li, MotionLine as line, MotionLinearGradient as linearGradient, MotionLink as link, MotionMain as main, MotionMap as map, MotionMark as mark, MotionMarker as marker, MotionMask as mask, MotionMenu as menu, MotionMenuitem as menuitem, MotionMetadata as metadata, MotionMeter as meter, MotionNav as nav, MotionObject as object, MotionOl as ol, MotionOptgroup as optgroup, MotionOption as option, MotionOutput as output, MotionP as p, MotionParam as param, MotionPath as path, MotionPattern as pattern, MotionPicture as picture, MotionPolygon as polygon, MotionPolyline as polyline, MotionPre as pre, MotionProgress as progress, MotionQ as q, MotionRadialGradient as radialGradient, MotionRect as rect, MotionRp as rp, MotionRt as rt, MotionRuby as ruby, MotionS as s, MotionSamp as samp, MotionScript as script, MotionSection as section, MotionSelect as select, MotionSmall as small, MotionSource as source, MotionSpan as span, MotionStop as stop, MotionStrong as strong, MotionStyle as style, MotionSub as sub, MotionSummary as summary, MotionSup as sup, MotionSvg as svg, MotionSymbol as symbol, MotionTable as table, MotionTbody as tbody, MotionTd as td, MotionText as text, MotionTextPath as textPath, MotionTextarea as textarea, MotionTfoot as tfoot, MotionTh as th, MotionThead as thead, MotionTime as time, MotionTitle as title, MotionTr as tr, MotionTrack as track, MotionTspan as tspan, MotionU as u, MotionUl as ul, MotionUse as use, MotionVideo as video, MotionView as view, MotionWbr as wbr, MotionWebview as webview } from './render/components/m/elements.mjs'; diff --git a/frontend/node_modules/framer-motion/dist/es/mini.mjs b/frontend/node_modules/framer-motion/dist/es/mini.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e255297644f007a2a06bd0294ec0969b44d8511f --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/mini.mjs @@ -0,0 +1 @@ +export { useAnimateMini as useAnimate } from './animation/hooks/use-animate-style.mjs'; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/features/Feature.mjs b/frontend/node_modules/framer-motion/dist/es/motion/features/Feature.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1c70050ed6cba35f80e1557e89103c7d360ccc49 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/features/Feature.mjs @@ -0,0 +1,9 @@ +class Feature { + constructor(node) { + this.isMounted = false; + this.node = node; + } + update() { } +} + +export { Feature }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/features/animation/exit.mjs b/frontend/node_modules/framer-motion/dist/es/motion/features/animation/exit.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4c1a92bea4ee5576cf424a9ece2cc54ac248ccd1 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/features/animation/exit.mjs @@ -0,0 +1,36 @@ +import { Feature } from '../Feature.mjs'; + +let id = 0; +class ExitAnimationFeature extends Feature { + constructor() { + super(...arguments); + this.id = id++; + } + update() { + if (!this.node.presenceContext) + return; + const { isPresent, onExitComplete } = this.node.presenceContext; + const { isPresent: prevIsPresent } = this.node.prevPresenceContext || {}; + if (!this.node.animationState || isPresent === prevIsPresent) { + return; + } + const exitAnimation = this.node.animationState.setActive("exit", !isPresent); + if (onExitComplete && !isPresent) { + exitAnimation.then(() => { + onExitComplete(this.id); + }); + } + } + mount() { + const { register, onExitComplete } = this.node.presenceContext || {}; + if (onExitComplete) { + onExitComplete(this.id); + } + if (register) { + this.unmount = register(this.id); + } + } + unmount() { } +} + +export { ExitAnimationFeature }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/features/animation/index.mjs b/frontend/node_modules/framer-motion/dist/es/motion/features/animation/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5a1eae94aa6502cbb652a64bb4a4990185dfaa69 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/features/animation/index.mjs @@ -0,0 +1,40 @@ +import { isAnimationControls } from '../../../animation/utils/is-animation-controls.mjs'; +import { createAnimationState } from '../../../render/utils/animation-state.mjs'; +import { Feature } from '../Feature.mjs'; + +class AnimationFeature extends Feature { + /** + * We dynamically generate the AnimationState manager as it contains a reference + * to the underlying animation library. We only want to load that if we load this, + * so people can optionally code split it out using the `m` component. + */ + constructor(node) { + super(node); + node.animationState || (node.animationState = createAnimationState(node)); + } + updateAnimationControlsSubscription() { + const { animate } = this.node.getProps(); + if (isAnimationControls(animate)) { + this.unmountControls = animate.subscribe(this.node); + } + } + /** + * Subscribe any provided AnimationControls to the component's VisualElement + */ + mount() { + this.updateAnimationControlsSubscription(); + } + update() { + const { animate } = this.node.getProps(); + const { animate: prevAnimate } = this.node.prevProps || {}; + if (animate !== prevAnimate) { + this.updateAnimationControlsSubscription(); + } + } + unmount() { + this.node.animationState.reset(); + this.unmountControls?.(); + } +} + +export { AnimationFeature }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/features/animations.mjs b/frontend/node_modules/framer-motion/dist/es/motion/features/animations.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bd67eb40b602e3c4a18bc5f48e3c60cccf65f272 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/features/animations.mjs @@ -0,0 +1,13 @@ +import { AnimationFeature } from './animation/index.mjs'; +import { ExitAnimationFeature } from './animation/exit.mjs'; + +const animations = { + animation: { + Feature: AnimationFeature, + }, + exit: { + Feature: ExitAnimationFeature, + }, +}; + +export { animations }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/features/definitions.mjs b/frontend/node_modules/framer-motion/dist/es/motion/features/definitions.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5a774ad5fdb5d10244a273d6dbd88d130e1a898f --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/features/definitions.mjs @@ -0,0 +1,28 @@ +const featureProps = { + animation: [ + "animate", + "variants", + "whileHover", + "whileTap", + "exit", + "whileInView", + "whileFocus", + "whileDrag", + ], + exit: ["exit"], + drag: ["drag", "dragControls"], + focus: ["whileFocus"], + hover: ["whileHover", "onHoverStart", "onHoverEnd"], + tap: ["whileTap", "onTap", "onTapStart", "onTapCancel"], + pan: ["onPan", "onPanStart", "onPanSessionStart", "onPanEnd"], + inView: ["whileInView", "onViewportEnter", "onViewportLeave"], + layout: ["layout", "layoutId"], +}; +const featureDefinitions = {}; +for (const key in featureProps) { + featureDefinitions[key] = { + isEnabled: (props) => featureProps[key].some((name) => !!props[name]), + }; +} + +export { featureDefinitions }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/features/drag.mjs b/frontend/node_modules/framer-motion/dist/es/motion/features/drag.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ecac2141b02c7fa6cdac0a7e6bc2fbb876bb450f --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/features/drag.mjs @@ -0,0 +1,17 @@ +import { DragGesture } from '../../gestures/drag/index.mjs'; +import { PanGesture } from '../../gestures/pan/index.mjs'; +import { MeasureLayout } from './layout/MeasureLayout.mjs'; +import { HTMLProjectionNode } from '../../projection/node/HTMLProjectionNode.mjs'; + +const drag = { + pan: { + Feature: PanGesture, + }, + drag: { + Feature: DragGesture, + ProjectionNode: HTMLProjectionNode, + MeasureLayout, + }, +}; + +export { drag }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/features/gestures.mjs b/frontend/node_modules/framer-motion/dist/es/motion/features/gestures.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a9a9cf670a0f3681d44ed474ca81cc7449509cfd --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/features/gestures.mjs @@ -0,0 +1,21 @@ +import { HoverGesture } from '../../gestures/hover.mjs'; +import { FocusGesture } from '../../gestures/focus.mjs'; +import { PressGesture } from '../../gestures/press.mjs'; +import { InViewFeature } from './viewport/index.mjs'; + +const gestureAnimations = { + inView: { + Feature: InViewFeature, + }, + tap: { + Feature: PressGesture, + }, + focus: { + Feature: FocusGesture, + }, + hover: { + Feature: HoverGesture, + }, +}; + +export { gestureAnimations }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/features/layout.mjs b/frontend/node_modules/framer-motion/dist/es/motion/features/layout.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e473842ef8f075cfa2c74acfa2cd304da54c033b --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/features/layout.mjs @@ -0,0 +1,11 @@ +import { HTMLProjectionNode } from '../../projection/node/HTMLProjectionNode.mjs'; +import { MeasureLayout } from './layout/MeasureLayout.mjs'; + +const layout = { + layout: { + ProjectionNode: HTMLProjectionNode, + MeasureLayout, + }, +}; + +export { layout }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/features/layout/MeasureLayout.mjs b/frontend/node_modules/framer-motion/dist/es/motion/features/layout/MeasureLayout.mjs new file mode 100644 index 0000000000000000000000000000000000000000..adb964d541e99834a220147deb09e26145c39190 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/features/layout/MeasureLayout.mjs @@ -0,0 +1,147 @@ +"use client"; +import { jsx } from 'react/jsx-runtime'; +import { frame, microtask } from 'motion-dom'; +import { useContext, Component } from 'react'; +import { usePresence } from '../../../components/AnimatePresence/use-presence.mjs'; +import { LayoutGroupContext } from '../../../context/LayoutGroupContext.mjs'; +import { SwitchLayoutGroupContext } from '../../../context/SwitchLayoutGroupContext.mjs'; +import { globalProjectionState } from '../../../projection/node/state.mjs'; +import { correctBorderRadius } from '../../../projection/styles/scale-border-radius.mjs'; +import { correctBoxShadow } from '../../../projection/styles/scale-box-shadow.mjs'; +import { addScaleCorrector } from '../../../projection/styles/scale-correction.mjs'; + +/** + * Track whether we've taken any snapshots yet. If not, + * we can safely skip notification of didUpdate. + * + * Difficult to capture in a test but to prevent flickering + * we must set this to true either on update or unmount. + * Running `next-env/layout-id` in Safari will show this behaviour if broken. + */ +let hasTakenAnySnapshot = false; +class MeasureLayoutWithContext extends Component { + /** + * This only mounts projection nodes for components that + * need measuring, we might want to do it for all components + * in order to incorporate transforms + */ + componentDidMount() { + const { visualElement, layoutGroup, switchLayoutGroup, layoutId } = this.props; + const { projection } = visualElement; + addScaleCorrector(defaultScaleCorrectors); + if (projection) { + if (layoutGroup.group) + layoutGroup.group.add(projection); + if (switchLayoutGroup && switchLayoutGroup.register && layoutId) { + switchLayoutGroup.register(projection); + } + if (hasTakenAnySnapshot) { + projection.root.didUpdate(); + } + projection.addEventListener("animationComplete", () => { + this.safeToRemove(); + }); + projection.setOptions({ + ...projection.options, + onExitComplete: () => this.safeToRemove(), + }); + } + globalProjectionState.hasEverUpdated = true; + } + getSnapshotBeforeUpdate(prevProps) { + const { layoutDependency, visualElement, drag, isPresent } = this.props; + const { projection } = visualElement; + if (!projection) + return null; + /** + * TODO: We use this data in relegate to determine whether to + * promote a previous element. There's no guarantee its presence data + * will have updated by this point - if a bug like this arises it will + * have to be that we markForRelegation and then find a new lead some other way, + * perhaps in didUpdate + */ + projection.isPresent = isPresent; + hasTakenAnySnapshot = true; + if (drag || + prevProps.layoutDependency !== layoutDependency || + layoutDependency === undefined || + prevProps.isPresent !== isPresent) { + projection.willUpdate(); + } + else { + this.safeToRemove(); + } + if (prevProps.isPresent !== isPresent) { + if (isPresent) { + projection.promote(); + } + else if (!projection.relegate()) { + /** + * If there's another stack member taking over from this one, + * it's in charge of the exit animation and therefore should + * be in charge of the safe to remove. Otherwise we call it here. + */ + frame.postRender(() => { + const stack = projection.getStack(); + if (!stack || !stack.members.length) { + this.safeToRemove(); + } + }); + } + } + return null; + } + componentDidUpdate() { + const { projection } = this.props.visualElement; + if (projection) { + projection.root.didUpdate(); + microtask.postRender(() => { + if (!projection.currentAnimation && projection.isLead()) { + this.safeToRemove(); + } + }); + } + } + componentWillUnmount() { + const { visualElement, layoutGroup, switchLayoutGroup: promoteContext, } = this.props; + const { projection } = visualElement; + hasTakenAnySnapshot = true; + if (projection) { + projection.scheduleCheckAfterUnmount(); + if (layoutGroup && layoutGroup.group) + layoutGroup.group.remove(projection); + if (promoteContext && promoteContext.deregister) + promoteContext.deregister(projection); + } + } + safeToRemove() { + const { safeToRemove } = this.props; + safeToRemove && safeToRemove(); + } + render() { + return null; + } +} +function MeasureLayout(props) { + const [isPresent, safeToRemove] = usePresence(); + const layoutGroup = useContext(LayoutGroupContext); + return (jsx(MeasureLayoutWithContext, { ...props, layoutGroup: layoutGroup, switchLayoutGroup: useContext(SwitchLayoutGroupContext), isPresent: isPresent, safeToRemove: safeToRemove })); +} +const defaultScaleCorrectors = { + borderRadius: { + ...correctBorderRadius, + applyTo: [ + "borderTopLeftRadius", + "borderTopRightRadius", + "borderBottomLeftRadius", + "borderBottomRightRadius", + ], + }, + borderTopLeftRadius: correctBorderRadius, + borderTopRightRadius: correctBorderRadius, + borderBottomLeftRadius: correctBorderRadius, + borderBottomRightRadius: correctBorderRadius, + boxShadow: correctBoxShadow, +}; + +export { MeasureLayout }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/features/load-features.mjs b/frontend/node_modules/framer-motion/dist/es/motion/features/load-features.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9211bba8a0373dd39264eb3b842cb75deb48e30c --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/features/load-features.mjs @@ -0,0 +1,12 @@ +import { featureDefinitions } from './definitions.mjs'; + +function loadFeatures(features) { + for (const key in features) { + featureDefinitions[key] = { + ...featureDefinitions[key], + ...features[key], + }; + } +} + +export { loadFeatures }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/features/viewport/index.mjs b/frontend/node_modules/framer-motion/dist/es/motion/features/viewport/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..29198b49677e53f40aea64a80565c7a8113b61ba --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/features/viewport/index.mjs @@ -0,0 +1,72 @@ +import { Feature } from '../Feature.mjs'; +import { observeIntersection } from './observers.mjs'; + +const thresholdNames = { + some: 0, + all: 1, +}; +class InViewFeature extends Feature { + constructor() { + super(...arguments); + this.hasEnteredView = false; + this.isInView = false; + } + startObserver() { + this.unmount(); + const { viewport = {} } = this.node.getProps(); + const { root, margin: rootMargin, amount = "some", once } = viewport; + const options = { + root: root ? root.current : undefined, + rootMargin, + threshold: typeof amount === "number" ? amount : thresholdNames[amount], + }; + const onIntersectionUpdate = (entry) => { + const { isIntersecting } = entry; + /** + * If there's been no change in the viewport state, early return. + */ + if (this.isInView === isIntersecting) + return; + this.isInView = isIntersecting; + /** + * Handle hasEnteredView. If this is only meant to run once, and + * element isn't visible, early return. Otherwise set hasEnteredView to true. + */ + if (once && !isIntersecting && this.hasEnteredView) { + return; + } + else if (isIntersecting) { + this.hasEnteredView = true; + } + if (this.node.animationState) { + this.node.animationState.setActive("whileInView", isIntersecting); + } + /** + * Use the latest committed props rather than the ones in scope + * when this observer is created + */ + const { onViewportEnter, onViewportLeave } = this.node.getProps(); + const callback = isIntersecting ? onViewportEnter : onViewportLeave; + callback && callback(entry); + }; + return observeIntersection(this.node.current, options, onIntersectionUpdate); + } + mount() { + this.startObserver(); + } + update() { + if (typeof IntersectionObserver === "undefined") + return; + const { props, prevProps } = this.node; + const hasOptionsChanged = ["amount", "margin", "root"].some(hasViewportOptionChanged(props, prevProps)); + if (hasOptionsChanged) { + this.startObserver(); + } + } + unmount() { } +} +function hasViewportOptionChanged({ viewport = {} }, { viewport: prevViewport = {} } = {}) { + return (name) => viewport[name] !== prevViewport[name]; +} + +export { InViewFeature }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/features/viewport/observers.mjs b/frontend/node_modules/framer-motion/dist/es/motion/features/viewport/observers.mjs new file mode 100644 index 0000000000000000000000000000000000000000..36106045f93f8f42bc156c22fa497665e0092b85 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/features/viewport/observers.mjs @@ -0,0 +1,49 @@ +/** + * Map an IntersectionHandler callback to an element. We only ever make one handler for one + * element, so even though these handlers might all be triggered by different + * observers, we can keep them in the same map. + */ +const observerCallbacks = new WeakMap(); +/** + * Multiple observers can be created for multiple element/document roots. Each with + * different settings. So here we store dictionaries of observers to each root, + * using serialised settings (threshold/margin) as lookup keys. + */ +const observers = new WeakMap(); +const fireObserverCallback = (entry) => { + const callback = observerCallbacks.get(entry.target); + callback && callback(entry); +}; +const fireAllObserverCallbacks = (entries) => { + entries.forEach(fireObserverCallback); +}; +function initIntersectionObserver({ root, ...options }) { + const lookupRoot = root || document; + /** + * If we don't have an observer lookup map for this root, create one. + */ + if (!observers.has(lookupRoot)) { + observers.set(lookupRoot, {}); + } + const rootObservers = observers.get(lookupRoot); + const key = JSON.stringify(options); + /** + * If we don't have an observer for this combination of root and settings, + * create one. + */ + if (!rootObservers[key]) { + rootObservers[key] = new IntersectionObserver(fireAllObserverCallbacks, { root, ...options }); + } + return rootObservers[key]; +} +function observeIntersection(element, options, callback) { + const rootInteresectionObserver = initIntersectionObserver(options); + observerCallbacks.set(element, callback); + rootInteresectionObserver.observe(element); + return () => { + observerCallbacks.delete(element); + rootInteresectionObserver.unobserve(element); + }; +} + +export { observeIntersection }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/index.mjs b/frontend/node_modules/framer-motion/dist/es/motion/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..577714e1a9bee793f0b429c547857a9f694a54c2 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/index.mjs @@ -0,0 +1,108 @@ +"use client"; +import { jsxs, jsx } from 'react/jsx-runtime'; +import { warning, invariant } from 'motion-utils'; +import { forwardRef, useContext } from 'react'; +import { LayoutGroupContext } from '../context/LayoutGroupContext.mjs'; +import { LazyContext } from '../context/LazyContext.mjs'; +import { MotionConfigContext } from '../context/MotionConfigContext.mjs'; +import { MotionContext } from '../context/MotionContext/index.mjs'; +import { useCreateMotionContext } from '../context/MotionContext/create.mjs'; +import { useRender } from '../render/dom/use-render.mjs'; +import { isSVGComponent } from '../render/dom/utils/is-svg-component.mjs'; +import { useHTMLVisualState } from '../render/html/use-html-visual-state.mjs'; +import { useSVGVisualState } from '../render/svg/use-svg-visual-state.mjs'; +import { isBrowser } from '../utils/is-browser.mjs'; +import { featureDefinitions } from './features/definitions.mjs'; +import { loadFeatures } from './features/load-features.mjs'; +import { motionComponentSymbol } from './utils/symbol.mjs'; +import { useMotionRef } from './utils/use-motion-ref.mjs'; +import { useVisualElement } from './utils/use-visual-element.mjs'; + +/** + * Create a `motion` component. + * + * This function accepts a Component argument, which can be either a string (ie "div" + * for `motion.div`), or an actual React component. + * + * Alongside this is a config option which provides a way of rendering the provided + * component "offline", or outside the React render cycle. + */ +function createMotionComponent(Component, { forwardMotionProps = false } = {}, preloadedFeatures, createVisualElement) { + preloadedFeatures && loadFeatures(preloadedFeatures); + const useVisualState = isSVGComponent(Component) + ? useSVGVisualState + : useHTMLVisualState; + function MotionDOMComponent(props, externalRef) { + /** + * If we need to measure the element we load this functionality in a + * separate class component in order to gain access to getSnapshotBeforeUpdate. + */ + let MeasureLayout; + const configAndProps = { + ...useContext(MotionConfigContext), + ...props, + layoutId: useLayoutId(props), + }; + const { isStatic } = configAndProps; + const context = useCreateMotionContext(props); + const visualState = useVisualState(props, isStatic); + if (!isStatic && isBrowser) { + useStrictMode(configAndProps, preloadedFeatures); + const layoutProjection = getProjectionFunctionality(configAndProps); + MeasureLayout = layoutProjection.MeasureLayout; + /** + * Create a VisualElement for this component. A VisualElement provides a common + * interface to renderer-specific APIs (ie DOM/Three.js etc) as well as + * providing a way of rendering to these APIs outside of the React render loop + * for more performant animations and interactions + */ + context.visualElement = useVisualElement(Component, visualState, configAndProps, createVisualElement, layoutProjection.ProjectionNode); + } + /** + * The mount order and hierarchy is specific to ensure our element ref + * is hydrated by the time features fire their effects. + */ + return (jsxs(MotionContext.Provider, { value: context, children: [MeasureLayout && context.visualElement ? (jsx(MeasureLayout, { visualElement: context.visualElement, ...configAndProps })) : null, useRender(Component, props, useMotionRef(visualState, context.visualElement, externalRef), visualState, isStatic, forwardMotionProps)] })); + } + MotionDOMComponent.displayName = `motion.${typeof Component === "string" + ? Component + : `create(${Component.displayName ?? Component.name ?? ""})`}`; + const ForwardRefMotionComponent = forwardRef(MotionDOMComponent); + ForwardRefMotionComponent[motionComponentSymbol] = Component; + return ForwardRefMotionComponent; +} +function useLayoutId({ layoutId }) { + const layoutGroupId = useContext(LayoutGroupContext).id; + return layoutGroupId && layoutId !== undefined + ? layoutGroupId + "-" + layoutId + : layoutId; +} +function useStrictMode(configAndProps, preloadedFeatures) { + const isStrict = useContext(LazyContext).strict; + /** + * If we're in development mode, check to make sure we're not rendering a motion component + * as a child of LazyMotion, as this will break the file-size benefits of using it. + */ + if (process.env.NODE_ENV !== "production" && + preloadedFeatures && + isStrict) { + const strictMessage = "You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead."; + configAndProps.ignoreStrict + ? warning(false, strictMessage, "lazy-strict-mode") + : invariant(false, strictMessage, "lazy-strict-mode"); + } +} +function getProjectionFunctionality(props) { + const { drag, layout } = featureDefinitions; + if (!drag && !layout) + return {}; + const combined = { ...drag, ...layout }; + return { + MeasureLayout: drag?.isEnabled(props) || layout?.isEnabled(props) + ? combined.MeasureLayout + : undefined, + ProjectionNode: combined.ProjectionNode, + }; +} + +export { createMotionComponent }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/utils/is-forced-motion-value.mjs b/frontend/node_modules/framer-motion/dist/es/motion/utils/is-forced-motion-value.mjs new file mode 100644 index 0000000000000000000000000000000000000000..59d74f3cfa21c380a379d87598e4c625853f6604 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/utils/is-forced-motion-value.mjs @@ -0,0 +1,11 @@ +import { transformProps } from 'motion-dom'; +import { scaleCorrectors } from '../../projection/styles/scale-correction.mjs'; + +function isForcedMotionValue(key, { layout, layoutId }) { + return (transformProps.has(key) || + key.startsWith("origin") || + ((layout || layoutId !== undefined) && + (!!scaleCorrectors[key] || key === "opacity"))); +} + +export { isForcedMotionValue }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/utils/is-motion-component.mjs b/frontend/node_modules/framer-motion/dist/es/motion/utils/is-motion-component.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6ddb65cd870ef45081146410789b5b339df13dd5 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/utils/is-motion-component.mjs @@ -0,0 +1,12 @@ +import { motionComponentSymbol } from './symbol.mjs'; + +/** + * Checks if a component is a `motion` component. + */ +function isMotionComponent(component) { + return (component !== null && + typeof component === "object" && + motionComponentSymbol in component); +} + +export { isMotionComponent }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/utils/symbol.mjs b/frontend/node_modules/framer-motion/dist/es/motion/utils/symbol.mjs new file mode 100644 index 0000000000000000000000000000000000000000..376932c97a22a52ce72be8f704f17c597004704d --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/utils/symbol.mjs @@ -0,0 +1,3 @@ +const motionComponentSymbol = Symbol.for("motionComponentSymbol"); + +export { motionComponentSymbol }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/utils/unwrap-motion-component.mjs b/frontend/node_modules/framer-motion/dist/es/motion/utils/unwrap-motion-component.mjs new file mode 100644 index 0000000000000000000000000000000000000000..204db9b4360946e5fcdcabcd4c98d358215fdf31 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/utils/unwrap-motion-component.mjs @@ -0,0 +1,17 @@ +import { isMotionComponent } from './is-motion-component.mjs'; +import { motionComponentSymbol } from './symbol.mjs'; + +/** + * Unwraps a `motion` component and returns either a string for `motion.div` or + * the React component for `motion(Component)`. + * + * If the component is not a `motion` component it returns undefined. + */ +function unwrapMotionComponent(component) { + if (isMotionComponent(component)) { + return component[motionComponentSymbol]; + } + return undefined; +} + +export { unwrapMotionComponent }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/utils/use-motion-ref.mjs b/frontend/node_modules/framer-motion/dist/es/motion/utils/use-motion-ref.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6c2807fe0840c284aac877e0039230b30fc44a08 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/utils/use-motion-ref.mjs @@ -0,0 +1,38 @@ +import { useCallback } from 'react'; +import { isRefObject } from '../../utils/is-ref-object.mjs'; + +/** + * Creates a ref function that, when called, hydrates the provided + * external ref and VisualElement. + */ +function useMotionRef(visualState, visualElement, externalRef) { + return useCallback((instance) => { + if (instance) { + visualState.onMount && visualState.onMount(instance); + } + if (visualElement) { + if (instance) { + visualElement.mount(instance); + } + else { + visualElement.unmount(); + } + } + if (externalRef) { + if (typeof externalRef === "function") { + externalRef(instance); + } + else if (isRefObject(externalRef)) { + externalRef.current = instance; + } + } + }, + /** + * Only pass a new ref callback to React if we've received a visual element + * factory. Otherwise we'll be mounting/remounting every time externalRef + * or other dependencies change. + */ + [visualElement]); +} + +export { useMotionRef }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/utils/use-visual-element.mjs b/frontend/node_modules/framer-motion/dist/es/motion/utils/use-visual-element.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2f36882405f011300c40cf52425e124ad553f778 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/utils/use-visual-element.mjs @@ -0,0 +1,139 @@ +import { useContext, useRef, useInsertionEffect, useEffect } from 'react'; +import { optimizedAppearDataAttribute } from '../../animation/optimized-appear/data-id.mjs'; +import { LazyContext } from '../../context/LazyContext.mjs'; +import { MotionConfigContext } from '../../context/MotionConfigContext.mjs'; +import { MotionContext } from '../../context/MotionContext/index.mjs'; +import { PresenceContext } from '../../context/PresenceContext.mjs'; +import { SwitchLayoutGroupContext } from '../../context/SwitchLayoutGroupContext.mjs'; +import { isRefObject } from '../../utils/is-ref-object.mjs'; +import { useIsomorphicLayoutEffect } from '../../utils/use-isomorphic-effect.mjs'; + +function useVisualElement(Component, visualState, props, createVisualElement, ProjectionNodeConstructor) { + const { visualElement: parent } = useContext(MotionContext); + const lazyContext = useContext(LazyContext); + const presenceContext = useContext(PresenceContext); + const reducedMotionConfig = useContext(MotionConfigContext).reducedMotion; + const visualElementRef = useRef(null); + /** + * If we haven't preloaded a renderer, check to see if we have one lazy-loaded + */ + createVisualElement = + createVisualElement || + lazyContext.renderer; + if (!visualElementRef.current && createVisualElement) { + visualElementRef.current = createVisualElement(Component, { + visualState, + parent, + props, + presenceContext, + blockInitialAnimation: presenceContext + ? presenceContext.initial === false + : false, + reducedMotionConfig, + }); + } + const visualElement = visualElementRef.current; + /** + * Load Motion gesture and animation features. These are rendered as renderless + * components so each feature can optionally make use of React lifecycle methods. + */ + const initialLayoutGroupConfig = useContext(SwitchLayoutGroupContext); + if (visualElement && + !visualElement.projection && + ProjectionNodeConstructor && + (visualElement.type === "html" || visualElement.type === "svg")) { + createProjectionNode(visualElementRef.current, props, ProjectionNodeConstructor, initialLayoutGroupConfig); + } + const isMounted = useRef(false); + useInsertionEffect(() => { + /** + * Check the component has already mounted before calling + * `update` unnecessarily. This ensures we skip the initial update. + */ + if (visualElement && isMounted.current) { + visualElement.update(props, presenceContext); + } + }); + /** + * Cache this value as we want to know whether HandoffAppearAnimations + * was present on initial render - it will be deleted after this. + */ + const optimisedAppearId = props[optimizedAppearDataAttribute]; + const wantsHandoff = useRef(Boolean(optimisedAppearId) && + !window.MotionHandoffIsComplete?.(optimisedAppearId) && + window.MotionHasOptimisedAnimation?.(optimisedAppearId)); + useIsomorphicLayoutEffect(() => { + if (!visualElement) + return; + isMounted.current = true; + window.MotionIsMounted = true; + visualElement.updateFeatures(); + visualElement.scheduleRenderMicrotask(); + /** + * Ideally this function would always run in a useEffect. + * + * However, if we have optimised appear animations to handoff from, + * it needs to happen synchronously to ensure there's no flash of + * incorrect styles in the event of a hydration error. + * + * So if we detect a situtation where optimised appear animations + * are running, we use useLayoutEffect to trigger animations. + */ + if (wantsHandoff.current && visualElement.animationState) { + visualElement.animationState.animateChanges(); + } + }); + useEffect(() => { + if (!visualElement) + return; + if (!wantsHandoff.current && visualElement.animationState) { + visualElement.animationState.animateChanges(); + } + if (wantsHandoff.current) { + // This ensures all future calls to animateChanges() in this component will run in useEffect + queueMicrotask(() => { + window.MotionHandoffMarkAsComplete?.(optimisedAppearId); + }); + wantsHandoff.current = false; + } + /** + * Now we've finished triggering animations for this element we + * can wipe the enteringChildren set for the next render. + */ + visualElement.enteringChildren = undefined; + }); + return visualElement; +} +function createProjectionNode(visualElement, props, ProjectionNodeConstructor, initialPromotionConfig) { + const { layoutId, layout, drag, dragConstraints, layoutScroll, layoutRoot, layoutCrossfade, } = props; + visualElement.projection = new ProjectionNodeConstructor(visualElement.latestValues, props["data-framer-portal-id"] + ? undefined + : getClosestProjectingNode(visualElement.parent)); + visualElement.projection.setOptions({ + layoutId, + layout, + alwaysMeasureLayout: Boolean(drag) || (dragConstraints && isRefObject(dragConstraints)), + visualElement, + /** + * TODO: Update options in an effect. This could be tricky as it'll be too late + * to update by the time layout animations run. + * We also need to fix this safeToRemove by linking it up to the one returned by usePresence, + * ensuring it gets called if there's no potential layout animations. + * + */ + animationType: typeof layout === "string" ? layout : "both", + initialPromotionConfig, + crossfade: layoutCrossfade, + layoutScroll, + layoutRoot, + }); +} +function getClosestProjectingNode(visualElement) { + if (!visualElement) + return undefined; + return visualElement.options.allowProjection !== false + ? visualElement.projection + : getClosestProjectingNode(visualElement.parent); +} + +export { useVisualElement }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/utils/use-visual-state.mjs b/frontend/node_modules/framer-motion/dist/es/motion/utils/use-visual-state.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f2403ccbc9186d8f1897bc92e8ec63fcb25bb7c6 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/utils/use-visual-state.mjs @@ -0,0 +1,79 @@ +import { useContext } from 'react'; +import { isAnimationControls } from '../../animation/utils/is-animation-controls.mjs'; +import { MotionContext } from '../../context/MotionContext/index.mjs'; +import { PresenceContext } from '../../context/PresenceContext.mjs'; +import { isControllingVariants, isVariantNode } from '../../render/utils/is-controlling-variants.mjs'; +import { resolveVariantFromProps } from '../../render/utils/resolve-variants.mjs'; +import { useConstant } from '../../utils/use-constant.mjs'; +import { resolveMotionValue } from '../../value/utils/resolve-motion-value.mjs'; + +function makeState({ scrapeMotionValuesFromProps, createRenderState, }, props, context, presenceContext) { + const state = { + latestValues: makeLatestValues(props, context, presenceContext, scrapeMotionValuesFromProps), + renderState: createRenderState(), + }; + return state; +} +function makeLatestValues(props, context, presenceContext, scrapeMotionValues) { + const values = {}; + const motionValues = scrapeMotionValues(props, {}); + for (const key in motionValues) { + values[key] = resolveMotionValue(motionValues[key]); + } + let { initial, animate } = props; + const isControllingVariants$1 = isControllingVariants(props); + const isVariantNode$1 = isVariantNode(props); + if (context && + isVariantNode$1 && + !isControllingVariants$1 && + props.inherit !== false) { + if (initial === undefined) + initial = context.initial; + if (animate === undefined) + animate = context.animate; + } + let isInitialAnimationBlocked = presenceContext + ? presenceContext.initial === false + : false; + isInitialAnimationBlocked = isInitialAnimationBlocked || initial === false; + const variantToSet = isInitialAnimationBlocked ? animate : initial; + if (variantToSet && + typeof variantToSet !== "boolean" && + !isAnimationControls(variantToSet)) { + const list = Array.isArray(variantToSet) ? variantToSet : [variantToSet]; + for (let i = 0; i < list.length; i++) { + const resolved = resolveVariantFromProps(props, list[i]); + if (resolved) { + const { transitionEnd, transition, ...target } = resolved; + for (const key in target) { + let valueTarget = target[key]; + if (Array.isArray(valueTarget)) { + /** + * Take final keyframe if the initial animation is blocked because + * we want to initialise at the end of that blocked animation. + */ + const index = isInitialAnimationBlocked + ? valueTarget.length - 1 + : 0; + valueTarget = valueTarget[index]; + } + if (valueTarget !== null) { + values[key] = valueTarget; + } + } + for (const key in transitionEnd) { + values[key] = transitionEnd[key]; + } + } + } + } + return values; +} +const makeUseVisualState = (config) => (props, isStatic) => { + const context = useContext(MotionContext); + const presenceContext = useContext(PresenceContext); + const make = () => makeState(config, props, context, presenceContext); + return isStatic ? make() : useConstant(make); +}; + +export { makeUseVisualState }; diff --git a/frontend/node_modules/framer-motion/dist/es/motion/utils/valid-prop.mjs b/frontend/node_modules/framer-motion/dist/es/motion/utils/valid-prop.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d6587abe88c2d5a40f16583fbd06482a1803edec --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/motion/utils/valid-prop.mjs @@ -0,0 +1,57 @@ +/** + * A list of all valid MotionProps. + * + * @privateRemarks + * This doesn't throw if a `MotionProp` name is missing - it should. + */ +const validMotionProps = new Set([ + "animate", + "exit", + "variants", + "initial", + "style", + "values", + "variants", + "transition", + "transformTemplate", + "custom", + "inherit", + "onBeforeLayoutMeasure", + "onAnimationStart", + "onAnimationComplete", + "onUpdate", + "onDragStart", + "onDrag", + "onDragEnd", + "onMeasureDragConstraints", + "onDirectionLock", + "onDragTransitionEnd", + "_dragX", + "_dragY", + "onHoverStart", + "onHoverEnd", + "onViewportEnter", + "onViewportLeave", + "globalTapTarget", + "ignoreStrict", + "viewport", +]); +/** + * Check whether a prop name is a valid `MotionProp` key. + * + * @param key - Name of the property to check + * @returns `true` is key is a valid `MotionProp`. + * + * @public + */ +function isValidMotionProp(key) { + return (key.startsWith("while") || + (key.startsWith("drag") && key !== "draggable") || + key.startsWith("layout") || + key.startsWith("onTap") || + key.startsWith("onPan") || + key.startsWith("onLayout") || + validMotionProps.has(key)); +} + +export { isValidMotionProp }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection.mjs b/frontend/node_modules/framer-motion/dist/es/projection.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1ad606fcee1bf5f1ebcc2f0985fb6bcfba1171e7 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection.mjs @@ -0,0 +1,9 @@ +export { frame, frameData, mix, recordStats, statsBuffer } from 'motion-dom'; +export { calcBoxDelta } from './projection/geometry/delta-calc.mjs'; +export { nodeGroup } from './projection/node/group.mjs'; +export { HTMLProjectionNode } from './projection/node/HTMLProjectionNode.mjs'; +export { correctBorderRadius } from './projection/styles/scale-border-radius.mjs'; +export { correctBoxShadow } from './projection/styles/scale-box-shadow.mjs'; +export { addScaleCorrector } from './projection/styles/scale-correction.mjs'; +export { HTMLVisualElement } from './render/html/HTMLVisualElement.mjs'; +export { buildTransform } from './render/html/utils/build-transform.mjs'; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/animation/mix-values.mjs b/frontend/node_modules/framer-motion/dist/es/projection/animation/mix-values.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a3f4db763aaaec15047b619036978ed12698635f --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/animation/mix-values.mjs @@ -0,0 +1,88 @@ +import { mixNumber, percent, px } from 'motion-dom'; +import { progress, circOut, noop } from 'motion-utils'; + +const borders = ["TopLeft", "TopRight", "BottomLeft", "BottomRight"]; +const numBorders = borders.length; +const asNumber = (value) => typeof value === "string" ? parseFloat(value) : value; +const isPx = (value) => typeof value === "number" || px.test(value); +function mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnlyMember) { + if (shouldCrossfadeOpacity) { + target.opacity = mixNumber(0, lead.opacity ?? 1, easeCrossfadeIn(progress)); + target.opacityExit = mixNumber(follow.opacity ?? 1, 0, easeCrossfadeOut(progress)); + } + else if (isOnlyMember) { + target.opacity = mixNumber(follow.opacity ?? 1, lead.opacity ?? 1, progress); + } + /** + * Mix border radius + */ + for (let i = 0; i < numBorders; i++) { + const borderLabel = `border${borders[i]}Radius`; + let followRadius = getRadius(follow, borderLabel); + let leadRadius = getRadius(lead, borderLabel); + if (followRadius === undefined && leadRadius === undefined) + continue; + followRadius || (followRadius = 0); + leadRadius || (leadRadius = 0); + const canMix = followRadius === 0 || + leadRadius === 0 || + isPx(followRadius) === isPx(leadRadius); + if (canMix) { + target[borderLabel] = Math.max(mixNumber(asNumber(followRadius), asNumber(leadRadius), progress), 0); + if (percent.test(leadRadius) || percent.test(followRadius)) { + target[borderLabel] += "%"; + } + } + else { + target[borderLabel] = leadRadius; + } + } + /** + * Mix rotation + */ + if (follow.rotate || lead.rotate) { + target.rotate = mixNumber(follow.rotate || 0, lead.rotate || 0, progress); + } +} +function getRadius(values, radiusName) { + return values[radiusName] !== undefined + ? values[radiusName] + : values.borderRadius; +} +// /** +// * We only want to mix the background color if there's a follow element +// * that we're not crossfading opacity between. For instance with switch +// * AnimateSharedLayout animations, this helps the illusion of a continuous +// * element being animated but also cuts down on the number of paints triggered +// * for elements where opacity is doing that work for us. +// */ +// if ( +// !hasFollowElement && +// latestLeadValues.backgroundColor && +// latestFollowValues.backgroundColor +// ) { +// /** +// * This isn't ideal performance-wise as mixColor is creating a new function every frame. +// * We could probably create a mixer that runs at the start of the animation but +// * the idea behind the crossfader is that it runs dynamically between two potentially +// * changing targets (ie opacity or borderRadius may be animating independently via variants) +// */ +// leadState.backgroundColor = followState.backgroundColor = mixColor( +// latestFollowValues.backgroundColor as string, +// latestLeadValues.backgroundColor as string +// )(p) +// } +const easeCrossfadeIn = /*@__PURE__*/ compress(0, 0.5, circOut); +const easeCrossfadeOut = /*@__PURE__*/ compress(0.5, 0.95, noop); +function compress(min, max, easing) { + return (p) => { + // Could replace ifs with clamp + if (p < min) + return 0; + if (p > max) + return 1; + return easing(progress(min, max, p)); + }; +} + +export { mixValues }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/geometry/conversion.mjs b/frontend/node_modules/framer-motion/dist/es/projection/geometry/conversion.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2188851c025d1d50877e11f3fa78a02902bb7d89 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/geometry/conversion.mjs @@ -0,0 +1,33 @@ +/** + * Bounding boxes tend to be defined as top, left, right, bottom. For various operations + * it's easier to consider each axis individually. This function returns a bounding box + * as a map of single-axis min/max values. + */ +function convertBoundingBoxToBox({ top, left, right, bottom, }) { + return { + x: { min: left, max: right }, + y: { min: top, max: bottom }, + }; +} +function convertBoxToBoundingBox({ x, y }) { + return { top: y.min, right: x.max, bottom: y.max, left: x.min }; +} +/** + * Applies a TransformPoint function to a bounding box. TransformPoint is usually a function + * provided by Framer to allow measured points to be corrected for device scaling. This is used + * when measuring DOM elements and DOM event points. + */ +function transformBoxPoints(point, transformPoint) { + if (!transformPoint) + return point; + const topLeft = transformPoint({ x: point.left, y: point.top }); + const bottomRight = transformPoint({ x: point.right, y: point.bottom }); + return { + top: topLeft.y, + left: topLeft.x, + bottom: bottomRight.y, + right: bottomRight.x, + }; +} + +export { convertBoundingBoxToBox, convertBoxToBoundingBox, transformBoxPoints }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/geometry/copy.mjs b/frontend/node_modules/framer-motion/dist/es/projection/geometry/copy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..210a880a6c0d642c6c6d50fa56f1543f8f6a539a --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/geometry/copy.mjs @@ -0,0 +1,31 @@ +/** + * Reset an axis to the provided origin box. + * + * This is a mutative operation. + */ +function copyAxisInto(axis, originAxis) { + axis.min = originAxis.min; + axis.max = originAxis.max; +} +/** + * Reset a box to the provided origin box. + * + * This is a mutative operation. + */ +function copyBoxInto(box, originBox) { + copyAxisInto(box.x, originBox.x); + copyAxisInto(box.y, originBox.y); +} +/** + * Reset a delta to the provided origin box. + * + * This is a mutative operation. + */ +function copyAxisDeltaInto(delta, originDelta) { + delta.translate = originDelta.translate; + delta.scale = originDelta.scale; + delta.originPoint = originDelta.originPoint; + delta.origin = originDelta.origin; +} + +export { copyAxisDeltaInto, copyAxisInto, copyBoxInto }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/geometry/delta-apply.mjs b/frontend/node_modules/framer-motion/dist/es/projection/geometry/delta-apply.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5e88625b4b9818f91e9805748cb3f94ef1378619 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/geometry/delta-apply.mjs @@ -0,0 +1,119 @@ +import { mixNumber } from 'motion-dom'; +import { hasTransform } from '../utils/has-transform.mjs'; + +/** + * Scales a point based on a factor and an originPoint + */ +function scalePoint(point, scale, originPoint) { + const distanceFromOrigin = point - originPoint; + const scaled = scale * distanceFromOrigin; + return originPoint + scaled; +} +/** + * Applies a translate/scale delta to a point + */ +function applyPointDelta(point, translate, scale, originPoint, boxScale) { + if (boxScale !== undefined) { + point = scalePoint(point, boxScale, originPoint); + } + return scalePoint(point, scale, originPoint) + translate; +} +/** + * Applies a translate/scale delta to an axis + */ +function applyAxisDelta(axis, translate = 0, scale = 1, originPoint, boxScale) { + axis.min = applyPointDelta(axis.min, translate, scale, originPoint, boxScale); + axis.max = applyPointDelta(axis.max, translate, scale, originPoint, boxScale); +} +/** + * Applies a translate/scale delta to a box + */ +function applyBoxDelta(box, { x, y }) { + applyAxisDelta(box.x, x.translate, x.scale, x.originPoint); + applyAxisDelta(box.y, y.translate, y.scale, y.originPoint); +} +const TREE_SCALE_SNAP_MIN = 0.999999999999; +const TREE_SCALE_SNAP_MAX = 1.0000000000001; +/** + * Apply a tree of deltas to a box. We do this to calculate the effect of all the transforms + * in a tree upon our box before then calculating how to project it into our desired viewport-relative box + * + * This is the final nested loop within updateLayoutDelta for future refactoring + */ +function applyTreeDeltas(box, treeScale, treePath, isSharedTransition = false) { + const treeLength = treePath.length; + if (!treeLength) + return; + // Reset the treeScale + treeScale.x = treeScale.y = 1; + let node; + let delta; + for (let i = 0; i < treeLength; i++) { + node = treePath[i]; + delta = node.projectionDelta; + /** + * TODO: Prefer to remove this, but currently we have motion components with + * display: contents in Framer. + */ + const { visualElement } = node.options; + if (visualElement && + visualElement.props.style && + visualElement.props.style.display === "contents") { + continue; + } + if (isSharedTransition && + node.options.layoutScroll && + node.scroll && + node !== node.root) { + transformBox(box, { + x: -node.scroll.offset.x, + y: -node.scroll.offset.y, + }); + } + if (delta) { + // Incoporate each ancestor's scale into a culmulative treeScale for this component + treeScale.x *= delta.x.scale; + treeScale.y *= delta.y.scale; + // Apply each ancestor's calculated delta into this component's recorded layout box + applyBoxDelta(box, delta); + } + if (isSharedTransition && hasTransform(node.latestValues)) { + transformBox(box, node.latestValues); + } + } + /** + * Snap tree scale back to 1 if it's within a non-perceivable threshold. + * This will help reduce useless scales getting rendered. + */ + if (treeScale.x < TREE_SCALE_SNAP_MAX && + treeScale.x > TREE_SCALE_SNAP_MIN) { + treeScale.x = 1.0; + } + if (treeScale.y < TREE_SCALE_SNAP_MAX && + treeScale.y > TREE_SCALE_SNAP_MIN) { + treeScale.y = 1.0; + } +} +function translateAxis(axis, distance) { + axis.min = axis.min + distance; + axis.max = axis.max + distance; +} +/** + * Apply a transform to an axis from the latest resolved motion values. + * This function basically acts as a bridge between a flat motion value map + * and applyAxisDelta + */ +function transformAxis(axis, axisTranslate, axisScale, boxScale, axisOrigin = 0.5) { + const originPoint = mixNumber(axis.min, axis.max, axisOrigin); + // Apply the axis delta to the final axis + applyAxisDelta(axis, axisTranslate, axisScale, originPoint, boxScale); +} +/** + * Apply a transform to a box from the latest resolved motion values. + */ +function transformBox(box, transform) { + transformAxis(box.x, transform.x, transform.scaleX, transform.scale, transform.originX); + transformAxis(box.y, transform.y, transform.scaleY, transform.scale, transform.originY); +} + +export { applyAxisDelta, applyBoxDelta, applyPointDelta, applyTreeDeltas, scalePoint, transformAxis, transformBox, translateAxis }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/geometry/delta-calc.mjs b/frontend/node_modules/framer-motion/dist/es/projection/geometry/delta-calc.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c0c1979cc2f190e62b3e4d2da2ebd4c859816aa0 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/geometry/delta-calc.mjs @@ -0,0 +1,52 @@ +import { mixNumber } from 'motion-dom'; + +const SCALE_PRECISION = 0.0001; +const SCALE_MIN = 1 - SCALE_PRECISION; +const SCALE_MAX = 1 + SCALE_PRECISION; +const TRANSLATE_PRECISION = 0.01; +const TRANSLATE_MIN = 0 - TRANSLATE_PRECISION; +const TRANSLATE_MAX = 0 + TRANSLATE_PRECISION; +function calcLength(axis) { + return axis.max - axis.min; +} +function isNear(value, target, maxDistance) { + return Math.abs(value - target) <= maxDistance; +} +function calcAxisDelta(delta, source, target, origin = 0.5) { + delta.origin = origin; + delta.originPoint = mixNumber(source.min, source.max, delta.origin); + delta.scale = calcLength(target) / calcLength(source); + delta.translate = + mixNumber(target.min, target.max, delta.origin) - delta.originPoint; + if ((delta.scale >= SCALE_MIN && delta.scale <= SCALE_MAX) || + isNaN(delta.scale)) { + delta.scale = 1.0; + } + if ((delta.translate >= TRANSLATE_MIN && + delta.translate <= TRANSLATE_MAX) || + isNaN(delta.translate)) { + delta.translate = 0.0; + } +} +function calcBoxDelta(delta, source, target, origin) { + calcAxisDelta(delta.x, source.x, target.x, origin ? origin.originX : undefined); + calcAxisDelta(delta.y, source.y, target.y, origin ? origin.originY : undefined); +} +function calcRelativeAxis(target, relative, parent) { + target.min = parent.min + relative.min; + target.max = target.min + calcLength(relative); +} +function calcRelativeBox(target, relative, parent) { + calcRelativeAxis(target.x, relative.x, parent.x); + calcRelativeAxis(target.y, relative.y, parent.y); +} +function calcRelativeAxisPosition(target, layout, parent) { + target.min = layout.min - parent.min; + target.max = target.min + calcLength(layout); +} +function calcRelativePosition(target, layout, parent) { + calcRelativeAxisPosition(target.x, layout.x, parent.x); + calcRelativeAxisPosition(target.y, layout.y, parent.y); +} + +export { calcAxisDelta, calcBoxDelta, calcLength, calcRelativeAxis, calcRelativeAxisPosition, calcRelativeBox, calcRelativePosition, isNear }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/geometry/delta-remove.mjs b/frontend/node_modules/framer-motion/dist/es/projection/geometry/delta-remove.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7d2ad58f35d60317e32626886ab7a7adf25dbba9 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/geometry/delta-remove.mjs @@ -0,0 +1,53 @@ +import { percent, mixNumber } from 'motion-dom'; +import { scalePoint } from './delta-apply.mjs'; + +/** + * Remove a delta from a point. This is essentially the steps of applyPointDelta in reverse + */ +function removePointDelta(point, translate, scale, originPoint, boxScale) { + point -= translate; + point = scalePoint(point, 1 / scale, originPoint); + if (boxScale !== undefined) { + point = scalePoint(point, 1 / boxScale, originPoint); + } + return point; +} +/** + * Remove a delta from an axis. This is essentially the steps of applyAxisDelta in reverse + */ +function removeAxisDelta(axis, translate = 0, scale = 1, origin = 0.5, boxScale, originAxis = axis, sourceAxis = axis) { + if (percent.test(translate)) { + translate = parseFloat(translate); + const relativeProgress = mixNumber(sourceAxis.min, sourceAxis.max, translate / 100); + translate = relativeProgress - sourceAxis.min; + } + if (typeof translate !== "number") + return; + let originPoint = mixNumber(originAxis.min, originAxis.max, origin); + if (axis === originAxis) + originPoint -= translate; + axis.min = removePointDelta(axis.min, translate, scale, originPoint, boxScale); + axis.max = removePointDelta(axis.max, translate, scale, originPoint, boxScale); +} +/** + * Remove a transforms from an axis. This is essentially the steps of applyAxisTransforms in reverse + * and acts as a bridge between motion values and removeAxisDelta + */ +function removeAxisTransforms(axis, transforms, [key, scaleKey, originKey], origin, sourceAxis) { + removeAxisDelta(axis, transforms[key], transforms[scaleKey], transforms[originKey], transforms.scale, origin, sourceAxis); +} +/** + * The names of the motion values we want to apply as translation, scale and origin. + */ +const xKeys = ["x", "scaleX", "originX"]; +const yKeys = ["y", "scaleY", "originY"]; +/** + * Remove a transforms from an box. This is essentially the steps of applyAxisBox in reverse + * and acts as a bridge between motion values and removeAxisDelta + */ +function removeBoxTransforms(box, transforms, originBox, sourceBox) { + removeAxisTransforms(box.x, transforms, xKeys, originBox ? originBox.x : undefined, sourceBox ? sourceBox.x : undefined); + removeAxisTransforms(box.y, transforms, yKeys, originBox ? originBox.y : undefined, sourceBox ? sourceBox.y : undefined); +} + +export { removeAxisDelta, removeAxisTransforms, removeBoxTransforms, removePointDelta }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/geometry/models.mjs b/frontend/node_modules/framer-motion/dist/es/projection/geometry/models.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5e01de0a02d6ed5263ad25019047cd4375e461f0 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/geometry/models.mjs @@ -0,0 +1,17 @@ +const createAxisDelta = () => ({ + translate: 0, + scale: 1, + origin: 0, + originPoint: 0, +}); +const createDelta = () => ({ + x: createAxisDelta(), + y: createAxisDelta(), +}); +const createAxis = () => ({ min: 0, max: 0 }); +const createBox = () => ({ + x: createAxis(), + y: createAxis(), +}); + +export { createAxis, createAxisDelta, createBox, createDelta }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/geometry/utils.mjs b/frontend/node_modules/framer-motion/dist/es/projection/geometry/utils.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d2a78edf7046899203f38f2f37bffcd37c1083b2 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/geometry/utils.mjs @@ -0,0 +1,31 @@ +import { calcLength } from './delta-calc.mjs'; + +function isAxisDeltaZero(delta) { + return delta.translate === 0 && delta.scale === 1; +} +function isDeltaZero(delta) { + return isAxisDeltaZero(delta.x) && isAxisDeltaZero(delta.y); +} +function axisEquals(a, b) { + return a.min === b.min && a.max === b.max; +} +function boxEquals(a, b) { + return axisEquals(a.x, b.x) && axisEquals(a.y, b.y); +} +function axisEqualsRounded(a, b) { + return (Math.round(a.min) === Math.round(b.min) && + Math.round(a.max) === Math.round(b.max)); +} +function boxEqualsRounded(a, b) { + return axisEqualsRounded(a.x, b.x) && axisEqualsRounded(a.y, b.y); +} +function aspectRatio(box) { + return calcLength(box.x) / calcLength(box.y); +} +function axisDeltaEquals(a, b) { + return (a.translate === b.translate && + a.scale === b.scale && + a.originPoint === b.originPoint); +} + +export { aspectRatio, axisDeltaEquals, axisEquals, axisEqualsRounded, boxEquals, boxEqualsRounded, isDeltaZero }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/node/DocumentProjectionNode.mjs b/frontend/node_modules/framer-motion/dist/es/projection/node/DocumentProjectionNode.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7f1a4234341f05f9bfba4a4f4006010cf9e6bd92 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/node/DocumentProjectionNode.mjs @@ -0,0 +1,13 @@ +import { addDomEvent } from '../../events/add-dom-event.mjs'; +import { createProjectionNode } from './create-projection-node.mjs'; + +const DocumentProjectionNode = createProjectionNode({ + attachResizeListener: (ref, notify) => addDomEvent(ref, "resize", notify), + measureScroll: () => ({ + x: document.documentElement.scrollLeft || document.body.scrollLeft, + y: document.documentElement.scrollTop || document.body.scrollTop, + }), + checkIsScrollRoot: () => true, +}); + +export { DocumentProjectionNode }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/node/HTMLProjectionNode.mjs b/frontend/node_modules/framer-motion/dist/es/projection/node/HTMLProjectionNode.mjs new file mode 100644 index 0000000000000000000000000000000000000000..95f86466947289042e651a04843a019d5d87bcc5 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/node/HTMLProjectionNode.mjs @@ -0,0 +1,27 @@ +import { createProjectionNode } from './create-projection-node.mjs'; +import { DocumentProjectionNode } from './DocumentProjectionNode.mjs'; + +const rootProjectionNode = { + current: undefined, +}; +const HTMLProjectionNode = createProjectionNode({ + measureScroll: (instance) => ({ + x: instance.scrollLeft, + y: instance.scrollTop, + }), + defaultParent: () => { + if (!rootProjectionNode.current) { + const documentNode = new DocumentProjectionNode({}); + documentNode.mount(window); + documentNode.setOptions({ layoutScroll: true }); + rootProjectionNode.current = documentNode; + } + return rootProjectionNode.current; + }, + resetTransform: (instance, value) => { + instance.style.transform = value !== undefined ? value : "none"; + }, + checkIsScrollRoot: (instance) => Boolean(window.getComputedStyle(instance).position === "fixed"), +}); + +export { HTMLProjectionNode, rootProjectionNode }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/node/create-projection-node.mjs b/frontend/node_modules/framer-motion/dist/es/projection/node/create-projection-node.mjs new file mode 100644 index 0000000000000000000000000000000000000000..50a7dabdb659df15e23ed3d75741fc6ffed3c6ab --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/node/create-projection-node.mjs @@ -0,0 +1,1612 @@ +import { statsBuffer, isSVGElement, isSVGSVGElement, frame, getValueTransition, cancelFrame, time, frameData, frameSteps, microtask, activeAnimations, motionValue, mixNumber } from 'motion-dom'; +import { SubscriptionManager, clamp, noop } from 'motion-utils'; +import { animateSingleValue } from '../../animation/animate/single-value.mjs'; +import { getOptimisedAppearId } from '../../animation/optimized-appear/get-appear-id.mjs'; +import { FlatTree } from '../../render/utils/flat-tree.mjs'; +import { delay } from '../../utils/delay.mjs'; +import { resolveMotionValue } from '../../value/utils/resolve-motion-value.mjs'; +import { mixValues } from '../animation/mix-values.mjs'; +import { copyBoxInto, copyAxisDeltaInto } from '../geometry/copy.mjs'; +import { translateAxis, transformBox, applyBoxDelta, applyTreeDeltas } from '../geometry/delta-apply.mjs'; +import { calcLength, calcRelativePosition, calcRelativeBox, calcBoxDelta, isNear } from '../geometry/delta-calc.mjs'; +import { removeBoxTransforms } from '../geometry/delta-remove.mjs'; +import { createBox, createDelta } from '../geometry/models.mjs'; +import { boxEqualsRounded, isDeltaZero, axisDeltaEquals, aspectRatio, boxEquals } from '../geometry/utils.mjs'; +import { NodeStack } from '../shared/stack.mjs'; +import { scaleCorrectors } from '../styles/scale-correction.mjs'; +import { buildProjectionTransform } from '../styles/transform.mjs'; +import { eachAxis } from '../utils/each-axis.mjs'; +import { hasTransform, hasScale, has2DTranslate } from '../utils/has-transform.mjs'; +import { globalProjectionState } from './state.mjs'; + +const metrics = { + nodes: 0, + calculatedTargetDeltas: 0, + calculatedProjections: 0, +}; +const transformAxes = ["", "X", "Y", "Z"]; +/** + * We use 1000 as the animation target as 0-1000 maps better to pixels than 0-1 + * which has a noticeable difference in spring animations + */ +const animationTarget = 1000; +let id = 0; +function resetDistortingTransform(key, visualElement, values, sharedAnimationValues) { + const { latestValues } = visualElement; + // Record the distorting transform and then temporarily set it to 0 + if (latestValues[key]) { + values[key] = latestValues[key]; + visualElement.setStaticValue(key, 0); + if (sharedAnimationValues) { + sharedAnimationValues[key] = 0; + } + } +} +function cancelTreeOptimisedTransformAnimations(projectionNode) { + projectionNode.hasCheckedOptimisedAppear = true; + if (projectionNode.root === projectionNode) + return; + const { visualElement } = projectionNode.options; + if (!visualElement) + return; + const appearId = getOptimisedAppearId(visualElement); + if (window.MotionHasOptimisedAnimation(appearId, "transform")) { + const { layout, layoutId } = projectionNode.options; + window.MotionCancelOptimisedAnimation(appearId, "transform", frame, !(layout || layoutId)); + } + const { parent } = projectionNode; + if (parent && !parent.hasCheckedOptimisedAppear) { + cancelTreeOptimisedTransformAnimations(parent); + } +} +function createProjectionNode({ attachResizeListener, defaultParent, measureScroll, checkIsScrollRoot, resetTransform, }) { + return class ProjectionNode { + constructor(latestValues = {}, parent = defaultParent?.()) { + /** + * A unique ID generated for every projection node. + */ + this.id = id++; + /** + * An id that represents a unique session instigated by startUpdate. + */ + this.animationId = 0; + this.animationCommitId = 0; + /** + * A Set containing all this component's children. This is used to iterate + * through the children. + * + * TODO: This could be faster to iterate as a flat array stored on the root node. + */ + this.children = new Set(); + /** + * Options for the node. We use this to configure what kind of layout animations + * we should perform (if any). + */ + this.options = {}; + /** + * We use this to detect when its safe to shut down part of a projection tree. + * We have to keep projecting children for scale correction and relative projection + * until all their parents stop performing layout animations. + */ + this.isTreeAnimating = false; + this.isAnimationBlocked = false; + /** + * Flag to true if we think this layout has been changed. We can't always know this, + * currently we set it to true every time a component renders, or if it has a layoutDependency + * if that has changed between renders. Additionally, components can be grouped by LayoutGroup + * and if one node is dirtied, they all are. + */ + this.isLayoutDirty = false; + /** + * Flag to true if we think the projection calculations for this node needs + * recalculating as a result of an updated transform or layout animation. + */ + this.isProjectionDirty = false; + /** + * Flag to true if the layout *or* transform has changed. This then gets propagated + * throughout the projection tree, forcing any element below to recalculate on the next frame. + */ + this.isSharedProjectionDirty = false; + /** + * Flag transform dirty. This gets propagated throughout the whole tree but is only + * respected by shared nodes. + */ + this.isTransformDirty = false; + /** + * Block layout updates for instant layout transitions throughout the tree. + */ + this.updateManuallyBlocked = false; + this.updateBlockedByResize = false; + /** + * Set to true between the start of the first `willUpdate` call and the end of the `didUpdate` + * call. + */ + this.isUpdating = false; + /** + * If this is an SVG element we currently disable projection transforms + */ + this.isSVG = false; + /** + * Flag to true (during promotion) if a node doing an instant layout transition needs to reset + * its projection styles. + */ + this.needsReset = false; + /** + * Flags whether this node should have its transform reset prior to measuring. + */ + this.shouldResetTransform = false; + /** + * Store whether this node has been checked for optimised appear animations. As + * effects fire bottom-up, and we want to look up the tree for appear animations, + * this makes sure we only check each path once, stopping at nodes that + * have already been checked. + */ + this.hasCheckedOptimisedAppear = false; + /** + * An object representing the calculated contextual/accumulated/tree scale. + * This will be used to scale calculcated projection transforms, as these are + * calculated in screen-space but need to be scaled for elements to layoutly + * make it to their calculated destinations. + * + * TODO: Lazy-init + */ + this.treeScale = { x: 1, y: 1 }; + /** + * + */ + this.eventHandlers = new Map(); + this.hasTreeAnimated = false; + // Note: Currently only running on root node + this.updateScheduled = false; + this.scheduleUpdate = () => this.update(); + this.projectionUpdateScheduled = false; + this.checkUpdateFailed = () => { + if (this.isUpdating) { + this.isUpdating = false; + this.clearAllSnapshots(); + } + }; + /** + * This is a multi-step process as shared nodes might be of different depths. Nodes + * are sorted by depth order, so we need to resolve the entire tree before moving to + * the next step. + */ + this.updateProjection = () => { + this.projectionUpdateScheduled = false; + /** + * Reset debug counts. Manually resetting rather than creating a new + * object each frame. + */ + if (statsBuffer.value) { + metrics.nodes = + metrics.calculatedTargetDeltas = + metrics.calculatedProjections = + 0; + } + this.nodes.forEach(propagateDirtyNodes); + this.nodes.forEach(resolveTargetDelta); + this.nodes.forEach(calcProjection); + this.nodes.forEach(cleanDirtyNodes); + if (statsBuffer.addProjectionMetrics) { + statsBuffer.addProjectionMetrics(metrics); + } + }; + /** + * Frame calculations + */ + this.resolvedRelativeTargetAt = 0.0; + this.hasProjected = false; + this.isVisible = true; + this.animationProgress = 0; + /** + * Shared layout + */ + // TODO Only running on root node + this.sharedNodes = new Map(); + this.latestValues = latestValues; + this.root = parent ? parent.root || parent : this; + this.path = parent ? [...parent.path, parent] : []; + this.parent = parent; + this.depth = parent ? parent.depth + 1 : 0; + for (let i = 0; i < this.path.length; i++) { + this.path[i].shouldResetTransform = true; + } + if (this.root === this) + this.nodes = new FlatTree(); + } + addEventListener(name, handler) { + if (!this.eventHandlers.has(name)) { + this.eventHandlers.set(name, new SubscriptionManager()); + } + return this.eventHandlers.get(name).add(handler); + } + notifyListeners(name, ...args) { + const subscriptionManager = this.eventHandlers.get(name); + subscriptionManager && subscriptionManager.notify(...args); + } + hasListeners(name) { + return this.eventHandlers.has(name); + } + /** + * Lifecycles + */ + mount(instance) { + if (this.instance) + return; + this.isSVG = isSVGElement(instance) && !isSVGSVGElement(instance); + this.instance = instance; + const { layoutId, layout, visualElement } = this.options; + if (visualElement && !visualElement.current) { + visualElement.mount(instance); + } + this.root.nodes.add(this); + this.parent && this.parent.children.add(this); + if (this.root.hasTreeAnimated && (layout || layoutId)) { + this.isLayoutDirty = true; + } + if (attachResizeListener) { + let cancelDelay; + let innerWidth = 0; + const resizeUnblockUpdate = () => (this.root.updateBlockedByResize = false); + // Set initial innerWidth in a frame.read callback to batch the read + frame.read(() => { + innerWidth = window.innerWidth; + }); + attachResizeListener(instance, () => { + const newInnerWidth = window.innerWidth; + if (newInnerWidth === innerWidth) + return; + innerWidth = newInnerWidth; + this.root.updateBlockedByResize = true; + cancelDelay && cancelDelay(); + cancelDelay = delay(resizeUnblockUpdate, 250); + if (globalProjectionState.hasAnimatedSinceResize) { + globalProjectionState.hasAnimatedSinceResize = false; + this.nodes.forEach(finishAnimation); + } + }); + } + if (layoutId) { + this.root.registerSharedNode(layoutId, this); + } + // Only register the handler if it requires layout animation + if (this.options.animate !== false && + visualElement && + (layoutId || layout)) { + this.addEventListener("didUpdate", ({ delta, hasLayoutChanged, hasRelativeLayoutChanged, layout: newLayout, }) => { + if (this.isTreeAnimationBlocked()) { + this.target = undefined; + this.relativeTarget = undefined; + return; + } + // TODO: Check here if an animation exists + const layoutTransition = this.options.transition || + visualElement.getDefaultTransition() || + defaultLayoutTransition; + const { onLayoutAnimationStart, onLayoutAnimationComplete, } = visualElement.getProps(); + /** + * The target layout of the element might stay the same, + * but its position relative to its parent has changed. + */ + const hasTargetChanged = !this.targetLayout || + !boxEqualsRounded(this.targetLayout, newLayout); + /* + * Note: Disabled to fix relative animations always triggering new + * layout animations. If this causes further issues, we can try + * a different approach to detecting relative target changes. + */ + // || hasRelativeLayoutChanged + /** + * If the layout hasn't seemed to have changed, it might be that the + * element is visually in the same place in the document but its position + * relative to its parent has indeed changed. So here we check for that. + */ + const hasOnlyRelativeTargetChanged = !hasLayoutChanged && hasRelativeLayoutChanged; + if (this.options.layoutRoot || + this.resumeFrom || + hasOnlyRelativeTargetChanged || + (hasLayoutChanged && + (hasTargetChanged || !this.currentAnimation))) { + if (this.resumeFrom) { + this.resumingFrom = this.resumeFrom; + this.resumingFrom.resumingFrom = undefined; + } + const animationOptions = { + ...getValueTransition(layoutTransition, "layout"), + onPlay: onLayoutAnimationStart, + onComplete: onLayoutAnimationComplete, + }; + if (visualElement.shouldReduceMotion || + this.options.layoutRoot) { + animationOptions.delay = 0; + animationOptions.type = false; + } + this.startAnimation(animationOptions); + /** + * Set animation origin after starting animation to avoid layout jump + * caused by stopping previous layout animation + */ + this.setAnimationOrigin(delta, hasOnlyRelativeTargetChanged); + } + else { + /** + * If the layout hasn't changed and we have an animation that hasn't started yet, + * finish it immediately. Otherwise it will be animating from a location + * that was probably never commited to screen and look like a jumpy box. + */ + if (!hasLayoutChanged) { + finishAnimation(this); + } + if (this.isLead() && this.options.onExitComplete) { + this.options.onExitComplete(); + } + } + this.targetLayout = newLayout; + }); + } + } + unmount() { + this.options.layoutId && this.willUpdate(); + this.root.nodes.remove(this); + const stack = this.getStack(); + stack && stack.remove(this); + this.parent && this.parent.children.delete(this); + this.instance = undefined; + this.eventHandlers.clear(); + cancelFrame(this.updateProjection); + } + // only on the root + blockUpdate() { + this.updateManuallyBlocked = true; + } + unblockUpdate() { + this.updateManuallyBlocked = false; + } + isUpdateBlocked() { + return this.updateManuallyBlocked || this.updateBlockedByResize; + } + isTreeAnimationBlocked() { + return (this.isAnimationBlocked || + (this.parent && this.parent.isTreeAnimationBlocked()) || + false); + } + // Note: currently only running on root node + startUpdate() { + if (this.isUpdateBlocked()) + return; + this.isUpdating = true; + this.nodes && this.nodes.forEach(resetSkewAndRotation); + this.animationId++; + } + getTransformTemplate() { + const { visualElement } = this.options; + return visualElement && visualElement.getProps().transformTemplate; + } + willUpdate(shouldNotifyListeners = true) { + this.root.hasTreeAnimated = true; + if (this.root.isUpdateBlocked()) { + this.options.onExitComplete && this.options.onExitComplete(); + return; + } + /** + * If we're running optimised appear animations then these must be + * cancelled before measuring the DOM. This is so we can measure + * the true layout of the element rather than the WAAPI animation + * which will be unaffected by the resetSkewAndRotate step. + * + * Note: This is a DOM write. Worst case scenario is this is sandwiched + * between other snapshot reads which will cause unnecessary style recalculations. + * This has to happen here though, as we don't yet know which nodes will need + * snapshots in startUpdate(), but we only want to cancel optimised animations + * if a layout animation measurement is actually going to be affected by them. + */ + if (window.MotionCancelOptimisedAnimation && + !this.hasCheckedOptimisedAppear) { + cancelTreeOptimisedTransformAnimations(this); + } + !this.root.isUpdating && this.root.startUpdate(); + if (this.isLayoutDirty) + return; + this.isLayoutDirty = true; + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + node.shouldResetTransform = true; + node.updateScroll("snapshot"); + if (node.options.layoutRoot) { + node.willUpdate(false); + } + } + const { layoutId, layout } = this.options; + if (layoutId === undefined && !layout) + return; + const transformTemplate = this.getTransformTemplate(); + this.prevTransformTemplateValue = transformTemplate + ? transformTemplate(this.latestValues, "") + : undefined; + this.updateSnapshot(); + shouldNotifyListeners && this.notifyListeners("willUpdate"); + } + update() { + this.updateScheduled = false; + const updateWasBlocked = this.isUpdateBlocked(); + // When doing an instant transition, we skip the layout update, + // but should still clean up the measurements so that the next + // snapshot could be taken correctly. + if (updateWasBlocked) { + this.unblockUpdate(); + this.clearAllSnapshots(); + this.nodes.forEach(clearMeasurements); + return; + } + /** + * If this is a repeat of didUpdate then ignore the animation. + */ + if (this.animationId <= this.animationCommitId) { + this.nodes.forEach(clearIsLayoutDirty); + return; + } + this.animationCommitId = this.animationId; + if (!this.isUpdating) { + this.nodes.forEach(clearIsLayoutDirty); + } + else { + this.isUpdating = false; + /** + * Write + */ + this.nodes.forEach(resetTransformStyle); + /** + * Read ================== + */ + // Update layout measurements of updated children + this.nodes.forEach(updateLayout); + /** + * Write + */ + // Notify listeners that the layout is updated + this.nodes.forEach(notifyLayoutUpdate); + } + this.clearAllSnapshots(); + /** + * Manually flush any pending updates. Ideally + * we could leave this to the following requestAnimationFrame but this seems + * to leave a flash of incorrectly styled content. + */ + const now = time.now(); + frameData.delta = clamp(0, 1000 / 60, now - frameData.timestamp); + frameData.timestamp = now; + frameData.isProcessing = true; + frameSteps.update.process(frameData); + frameSteps.preRender.process(frameData); + frameSteps.render.process(frameData); + frameData.isProcessing = false; + } + didUpdate() { + if (!this.updateScheduled) { + this.updateScheduled = true; + microtask.read(this.scheduleUpdate); + } + } + clearAllSnapshots() { + this.nodes.forEach(clearSnapshot); + this.sharedNodes.forEach(removeLeadSnapshots); + } + scheduleUpdateProjection() { + if (!this.projectionUpdateScheduled) { + this.projectionUpdateScheduled = true; + frame.preRender(this.updateProjection, false, true); + } + } + scheduleCheckAfterUnmount() { + /** + * If the unmounting node is in a layoutGroup and did trigger a willUpdate, + * we manually call didUpdate to give a chance to the siblings to animate. + * Otherwise, cleanup all snapshots to prevents future nodes from reusing them. + */ + frame.postRender(() => { + if (this.isLayoutDirty) { + this.root.didUpdate(); + } + else { + this.root.checkUpdateFailed(); + } + }); + } + /** + * Update measurements + */ + updateSnapshot() { + if (this.snapshot || !this.instance) + return; + this.snapshot = this.measure(); + if (this.snapshot && + !calcLength(this.snapshot.measuredBox.x) && + !calcLength(this.snapshot.measuredBox.y)) { + this.snapshot = undefined; + } + } + updateLayout() { + if (!this.instance) + return; + this.updateScroll(); + if (!(this.options.alwaysMeasureLayout && this.isLead()) && + !this.isLayoutDirty) { + return; + } + /** + * When a node is mounted, it simply resumes from the prevLead's + * snapshot instead of taking a new one, but the ancestors scroll + * might have updated while the prevLead is unmounted. We need to + * update the scroll again to make sure the layout we measure is + * up to date. + */ + if (this.resumeFrom && !this.resumeFrom.instance) { + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + node.updateScroll(); + } + } + const prevLayout = this.layout; + this.layout = this.measure(false); + this.layoutCorrected = createBox(); + this.isLayoutDirty = false; + this.projectionDelta = undefined; + this.notifyListeners("measure", this.layout.layoutBox); + const { visualElement } = this.options; + visualElement && + visualElement.notify("LayoutMeasure", this.layout.layoutBox, prevLayout ? prevLayout.layoutBox : undefined); + } + updateScroll(phase = "measure") { + let needsMeasurement = Boolean(this.options.layoutScroll && this.instance); + if (this.scroll && + this.scroll.animationId === this.root.animationId && + this.scroll.phase === phase) { + needsMeasurement = false; + } + if (needsMeasurement && this.instance) { + const isRoot = checkIsScrollRoot(this.instance); + this.scroll = { + animationId: this.root.animationId, + phase, + isRoot, + offset: measureScroll(this.instance), + wasRoot: this.scroll ? this.scroll.isRoot : isRoot, + }; + } + } + resetTransform() { + if (!resetTransform) + return; + const isResetRequested = this.isLayoutDirty || + this.shouldResetTransform || + this.options.alwaysMeasureLayout; + const hasProjection = this.projectionDelta && !isDeltaZero(this.projectionDelta); + const transformTemplate = this.getTransformTemplate(); + const transformTemplateValue = transformTemplate + ? transformTemplate(this.latestValues, "") + : undefined; + const transformTemplateHasChanged = transformTemplateValue !== this.prevTransformTemplateValue; + if (isResetRequested && + this.instance && + (hasProjection || + hasTransform(this.latestValues) || + transformTemplateHasChanged)) { + resetTransform(this.instance, transformTemplateValue); + this.shouldResetTransform = false; + this.scheduleRender(); + } + } + measure(removeTransform = true) { + const pageBox = this.measurePageBox(); + let layoutBox = this.removeElementScroll(pageBox); + /** + * Measurements taken during the pre-render stage + * still have transforms applied so we remove them + * via calculation. + */ + if (removeTransform) { + layoutBox = this.removeTransform(layoutBox); + } + roundBox(layoutBox); + return { + animationId: this.root.animationId, + measuredBox: pageBox, + layoutBox, + latestValues: {}, + source: this.id, + }; + } + measurePageBox() { + const { visualElement } = this.options; + if (!visualElement) + return createBox(); + const box = visualElement.measureViewportBox(); + const wasInScrollRoot = this.scroll?.wasRoot || this.path.some(checkNodeWasScrollRoot); + if (!wasInScrollRoot) { + // Remove viewport scroll to give page-relative coordinates + const { scroll } = this.root; + if (scroll) { + translateAxis(box.x, scroll.offset.x); + translateAxis(box.y, scroll.offset.y); + } + } + return box; + } + removeElementScroll(box) { + const boxWithoutScroll = createBox(); + copyBoxInto(boxWithoutScroll, box); + if (this.scroll?.wasRoot) { + return boxWithoutScroll; + } + /** + * Performance TODO: Keep a cumulative scroll offset down the tree + * rather than loop back up the path. + */ + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + const { scroll, options } = node; + if (node !== this.root && scroll && options.layoutScroll) { + /** + * If this is a new scroll root, we want to remove all previous scrolls + * from the viewport box. + */ + if (scroll.wasRoot) { + copyBoxInto(boxWithoutScroll, box); + } + translateAxis(boxWithoutScroll.x, scroll.offset.x); + translateAxis(boxWithoutScroll.y, scroll.offset.y); + } + } + return boxWithoutScroll; + } + applyTransform(box, transformOnly = false) { + const withTransforms = createBox(); + copyBoxInto(withTransforms, box); + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + if (!transformOnly && + node.options.layoutScroll && + node.scroll && + node !== node.root) { + transformBox(withTransforms, { + x: -node.scroll.offset.x, + y: -node.scroll.offset.y, + }); + } + if (!hasTransform(node.latestValues)) + continue; + transformBox(withTransforms, node.latestValues); + } + if (hasTransform(this.latestValues)) { + transformBox(withTransforms, this.latestValues); + } + return withTransforms; + } + removeTransform(box) { + const boxWithoutTransform = createBox(); + copyBoxInto(boxWithoutTransform, box); + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + if (!node.instance) + continue; + if (!hasTransform(node.latestValues)) + continue; + hasScale(node.latestValues) && node.updateSnapshot(); + const sourceBox = createBox(); + const nodeBox = node.measurePageBox(); + copyBoxInto(sourceBox, nodeBox); + removeBoxTransforms(boxWithoutTransform, node.latestValues, node.snapshot ? node.snapshot.layoutBox : undefined, sourceBox); + } + if (hasTransform(this.latestValues)) { + removeBoxTransforms(boxWithoutTransform, this.latestValues); + } + return boxWithoutTransform; + } + setTargetDelta(delta) { + this.targetDelta = delta; + this.root.scheduleUpdateProjection(); + this.isProjectionDirty = true; + } + setOptions(options) { + this.options = { + ...this.options, + ...options, + crossfade: options.crossfade !== undefined ? options.crossfade : true, + }; + } + clearMeasurements() { + this.scroll = undefined; + this.layout = undefined; + this.snapshot = undefined; + this.prevTransformTemplateValue = undefined; + this.targetDelta = undefined; + this.target = undefined; + this.isLayoutDirty = false; + } + forceRelativeParentToResolveTarget() { + if (!this.relativeParent) + return; + /** + * If the parent target isn't up-to-date, force it to update. + * This is an unfortunate de-optimisation as it means any updating relative + * projection will cause all the relative parents to recalculate back + * up the tree. + */ + if (this.relativeParent.resolvedRelativeTargetAt !== + frameData.timestamp) { + this.relativeParent.resolveTargetDelta(true); + } + } + resolveTargetDelta(forceRecalculation = false) { + /** + * Once the dirty status of nodes has been spread through the tree, we also + * need to check if we have a shared node of a different depth that has itself + * been dirtied. + */ + const lead = this.getLead(); + this.isProjectionDirty || (this.isProjectionDirty = lead.isProjectionDirty); + this.isTransformDirty || (this.isTransformDirty = lead.isTransformDirty); + this.isSharedProjectionDirty || (this.isSharedProjectionDirty = lead.isSharedProjectionDirty); + const isShared = Boolean(this.resumingFrom) || this !== lead; + /** + * We don't use transform for this step of processing so we don't + * need to check whether any nodes have changed transform. + */ + const canSkip = !(forceRecalculation || + (isShared && this.isSharedProjectionDirty) || + this.isProjectionDirty || + this.parent?.isProjectionDirty || + this.attemptToResolveRelativeTarget || + this.root.updateBlockedByResize); + if (canSkip) + return; + const { layout, layoutId } = this.options; + /** + * If we have no layout, we can't perform projection, so early return + */ + if (!this.layout || !(layout || layoutId)) + return; + this.resolvedRelativeTargetAt = frameData.timestamp; + /** + * If we don't have a targetDelta but do have a layout, we can attempt to resolve + * a relativeParent. This will allow a component to perform scale correction + * even if no animation has started. + */ + if (!this.targetDelta && !this.relativeTarget) { + const relativeParent = this.getClosestProjectingParent(); + if (relativeParent && + relativeParent.layout && + this.animationProgress !== 1) { + this.relativeParent = relativeParent; + this.forceRelativeParentToResolveTarget(); + this.relativeTarget = createBox(); + this.relativeTargetOrigin = createBox(); + calcRelativePosition(this.relativeTargetOrigin, this.layout.layoutBox, relativeParent.layout.layoutBox); + copyBoxInto(this.relativeTarget, this.relativeTargetOrigin); + } + else { + this.relativeParent = this.relativeTarget = undefined; + } + } + /** + * If we have no relative target or no target delta our target isn't valid + * for this frame. + */ + if (!this.relativeTarget && !this.targetDelta) + return; + /** + * Lazy-init target data structure + */ + if (!this.target) { + this.target = createBox(); + this.targetWithTransforms = createBox(); + } + /** + * If we've got a relative box for this component, resolve it into a target relative to the parent. + */ + if (this.relativeTarget && + this.relativeTargetOrigin && + this.relativeParent && + this.relativeParent.target) { + this.forceRelativeParentToResolveTarget(); + calcRelativeBox(this.target, this.relativeTarget, this.relativeParent.target); + /** + * If we've only got a targetDelta, resolve it into a target + */ + } + else if (this.targetDelta) { + if (Boolean(this.resumingFrom)) { + // TODO: This is creating a new object every frame + this.target = this.applyTransform(this.layout.layoutBox); + } + else { + copyBoxInto(this.target, this.layout.layoutBox); + } + applyBoxDelta(this.target, this.targetDelta); + } + else { + /** + * If no target, use own layout as target + */ + copyBoxInto(this.target, this.layout.layoutBox); + } + /** + * If we've been told to attempt to resolve a relative target, do so. + */ + if (this.attemptToResolveRelativeTarget) { + this.attemptToResolveRelativeTarget = false; + const relativeParent = this.getClosestProjectingParent(); + if (relativeParent && + Boolean(relativeParent.resumingFrom) === + Boolean(this.resumingFrom) && + !relativeParent.options.layoutScroll && + relativeParent.target && + this.animationProgress !== 1) { + this.relativeParent = relativeParent; + this.forceRelativeParentToResolveTarget(); + this.relativeTarget = createBox(); + this.relativeTargetOrigin = createBox(); + calcRelativePosition(this.relativeTargetOrigin, this.target, relativeParent.target); + copyBoxInto(this.relativeTarget, this.relativeTargetOrigin); + } + else { + this.relativeParent = this.relativeTarget = undefined; + } + } + /** + * Increase debug counter for resolved target deltas + */ + if (statsBuffer.value) { + metrics.calculatedTargetDeltas++; + } + } + getClosestProjectingParent() { + if (!this.parent || + hasScale(this.parent.latestValues) || + has2DTranslate(this.parent.latestValues)) { + return undefined; + } + if (this.parent.isProjecting()) { + return this.parent; + } + else { + return this.parent.getClosestProjectingParent(); + } + } + isProjecting() { + return Boolean((this.relativeTarget || + this.targetDelta || + this.options.layoutRoot) && + this.layout); + } + calcProjection() { + const lead = this.getLead(); + const isShared = Boolean(this.resumingFrom) || this !== lead; + let canSkip = true; + /** + * If this is a normal layout animation and neither this node nor its nearest projecting + * is dirty then we can't skip. + */ + if (this.isProjectionDirty || this.parent?.isProjectionDirty) { + canSkip = false; + } + /** + * If this is a shared layout animation and this node's shared projection is dirty then + * we can't skip. + */ + if (isShared && + (this.isSharedProjectionDirty || this.isTransformDirty)) { + canSkip = false; + } + /** + * If we have resolved the target this frame we must recalculate the + * projection to ensure it visually represents the internal calculations. + */ + if (this.resolvedRelativeTargetAt === frameData.timestamp) { + canSkip = false; + } + if (canSkip) + return; + const { layout, layoutId } = this.options; + /** + * If this section of the tree isn't animating we can + * delete our target sources for the following frame. + */ + this.isTreeAnimating = Boolean((this.parent && this.parent.isTreeAnimating) || + this.currentAnimation || + this.pendingAnimation); + if (!this.isTreeAnimating) { + this.targetDelta = this.relativeTarget = undefined; + } + if (!this.layout || !(layout || layoutId)) + return; + /** + * Reset the corrected box with the latest values from box, as we're then going + * to perform mutative operations on it. + */ + copyBoxInto(this.layoutCorrected, this.layout.layoutBox); + /** + * Record previous tree scales before updating. + */ + const prevTreeScaleX = this.treeScale.x; + const prevTreeScaleY = this.treeScale.y; + /** + * Apply all the parent deltas to this box to produce the corrected box. This + * is the layout box, as it will appear on screen as a result of the transforms of its parents. + */ + applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, isShared); + /** + * If this layer needs to perform scale correction but doesn't have a target, + * use the layout as the target. + */ + if (lead.layout && + !lead.target && + (this.treeScale.x !== 1 || this.treeScale.y !== 1)) { + lead.target = lead.layout.layoutBox; + lead.targetWithTransforms = createBox(); + } + const { target } = lead; + if (!target) { + /** + * If we don't have a target to project into, but we were previously + * projecting, we want to remove the stored transform and schedule + * a render to ensure the elements reflect the removed transform. + */ + if (this.prevProjectionDelta) { + this.createProjectionDeltas(); + this.scheduleRender(); + } + return; + } + if (!this.projectionDelta || !this.prevProjectionDelta) { + this.createProjectionDeltas(); + } + else { + copyAxisDeltaInto(this.prevProjectionDelta.x, this.projectionDelta.x); + copyAxisDeltaInto(this.prevProjectionDelta.y, this.projectionDelta.y); + } + /** + * Update the delta between the corrected box and the target box before user-set transforms were applied. + * This will allow us to calculate the corrected borderRadius and boxShadow to compensate + * for our layout reprojection, but still allow them to be scaled correctly by the user. + * It might be that to simplify this we may want to accept that user-set scale is also corrected + * and we wouldn't have to keep and calc both deltas, OR we could support a user setting + * to allow people to choose whether these styles are corrected based on just the + * layout reprojection or the final bounding box. + */ + calcBoxDelta(this.projectionDelta, this.layoutCorrected, target, this.latestValues); + if (this.treeScale.x !== prevTreeScaleX || + this.treeScale.y !== prevTreeScaleY || + !axisDeltaEquals(this.projectionDelta.x, this.prevProjectionDelta.x) || + !axisDeltaEquals(this.projectionDelta.y, this.prevProjectionDelta.y)) { + this.hasProjected = true; + this.scheduleRender(); + this.notifyListeners("projectionUpdate", target); + } + /** + * Increase debug counter for recalculated projections + */ + if (statsBuffer.value) { + metrics.calculatedProjections++; + } + } + hide() { + this.isVisible = false; + // TODO: Schedule render + } + show() { + this.isVisible = true; + // TODO: Schedule render + } + scheduleRender(notifyAll = true) { + this.options.visualElement?.scheduleRender(); + if (notifyAll) { + const stack = this.getStack(); + stack && stack.scheduleRender(); + } + if (this.resumingFrom && !this.resumingFrom.instance) { + this.resumingFrom = undefined; + } + } + createProjectionDeltas() { + this.prevProjectionDelta = createDelta(); + this.projectionDelta = createDelta(); + this.projectionDeltaWithTransform = createDelta(); + } + setAnimationOrigin(delta, hasOnlyRelativeTargetChanged = false) { + const snapshot = this.snapshot; + const snapshotLatestValues = snapshot ? snapshot.latestValues : {}; + const mixedValues = { ...this.latestValues }; + const targetDelta = createDelta(); + if (!this.relativeParent || + !this.relativeParent.options.layoutRoot) { + this.relativeTarget = this.relativeTargetOrigin = undefined; + } + this.attemptToResolveRelativeTarget = !hasOnlyRelativeTargetChanged; + const relativeLayout = createBox(); + const snapshotSource = snapshot ? snapshot.source : undefined; + const layoutSource = this.layout ? this.layout.source : undefined; + const isSharedLayoutAnimation = snapshotSource !== layoutSource; + const stack = this.getStack(); + const isOnlyMember = !stack || stack.members.length <= 1; + const shouldCrossfadeOpacity = Boolean(isSharedLayoutAnimation && + !isOnlyMember && + this.options.crossfade === true && + !this.path.some(hasOpacityCrossfade)); + this.animationProgress = 0; + let prevRelativeTarget; + this.mixTargetDelta = (latest) => { + const progress = latest / 1000; + mixAxisDelta(targetDelta.x, delta.x, progress); + mixAxisDelta(targetDelta.y, delta.y, progress); + this.setTargetDelta(targetDelta); + if (this.relativeTarget && + this.relativeTargetOrigin && + this.layout && + this.relativeParent && + this.relativeParent.layout) { + calcRelativePosition(relativeLayout, this.layout.layoutBox, this.relativeParent.layout.layoutBox); + mixBox(this.relativeTarget, this.relativeTargetOrigin, relativeLayout, progress); + /** + * If this is an unchanged relative target we can consider the + * projection not dirty. + */ + if (prevRelativeTarget && + boxEquals(this.relativeTarget, prevRelativeTarget)) { + this.isProjectionDirty = false; + } + if (!prevRelativeTarget) + prevRelativeTarget = createBox(); + copyBoxInto(prevRelativeTarget, this.relativeTarget); + } + if (isSharedLayoutAnimation) { + this.animationValues = mixedValues; + mixValues(mixedValues, snapshotLatestValues, this.latestValues, progress, shouldCrossfadeOpacity, isOnlyMember); + } + this.root.scheduleUpdateProjection(); + this.scheduleRender(); + this.animationProgress = progress; + }; + this.mixTargetDelta(this.options.layoutRoot ? 1000 : 0); + } + startAnimation(options) { + this.notifyListeners("animationStart"); + this.currentAnimation?.stop(); + this.resumingFrom?.currentAnimation?.stop(); + if (this.pendingAnimation) { + cancelFrame(this.pendingAnimation); + this.pendingAnimation = undefined; + } + /** + * Start the animation in the next frame to have a frame with progress 0, + * where the target is the same as when the animation started, so we can + * calculate the relative positions correctly for instant transitions. + */ + this.pendingAnimation = frame.update(() => { + globalProjectionState.hasAnimatedSinceResize = true; + activeAnimations.layout++; + this.motionValue || (this.motionValue = motionValue(0)); + this.currentAnimation = animateSingleValue(this.motionValue, [0, 1000], { + ...options, + velocity: 0, + isSync: true, + onUpdate: (latest) => { + this.mixTargetDelta(latest); + options.onUpdate && options.onUpdate(latest); + }, + onStop: () => { + activeAnimations.layout--; + }, + onComplete: () => { + activeAnimations.layout--; + options.onComplete && options.onComplete(); + this.completeAnimation(); + }, + }); + if (this.resumingFrom) { + this.resumingFrom.currentAnimation = this.currentAnimation; + } + this.pendingAnimation = undefined; + }); + } + completeAnimation() { + if (this.resumingFrom) { + this.resumingFrom.currentAnimation = undefined; + this.resumingFrom.preserveOpacity = undefined; + } + const stack = this.getStack(); + stack && stack.exitAnimationComplete(); + this.resumingFrom = + this.currentAnimation = + this.animationValues = + undefined; + this.notifyListeners("animationComplete"); + } + finishAnimation() { + if (this.currentAnimation) { + this.mixTargetDelta && this.mixTargetDelta(animationTarget); + this.currentAnimation.stop(); + } + this.completeAnimation(); + } + applyTransformsToTarget() { + const lead = this.getLead(); + let { targetWithTransforms, target, layout, latestValues } = lead; + if (!targetWithTransforms || !target || !layout) + return; + /** + * If we're only animating position, and this element isn't the lead element, + * then instead of projecting into the lead box we instead want to calculate + * a new target that aligns the two boxes but maintains the layout shape. + */ + if (this !== lead && + this.layout && + layout && + shouldAnimatePositionOnly(this.options.animationType, this.layout.layoutBox, layout.layoutBox)) { + target = this.target || createBox(); + const xLength = calcLength(this.layout.layoutBox.x); + target.x.min = lead.target.x.min; + target.x.max = target.x.min + xLength; + const yLength = calcLength(this.layout.layoutBox.y); + target.y.min = lead.target.y.min; + target.y.max = target.y.min + yLength; + } + copyBoxInto(targetWithTransforms, target); + /** + * Apply the latest user-set transforms to the targetBox to produce the targetBoxFinal. + * This is the final box that we will then project into by calculating a transform delta and + * applying it to the corrected box. + */ + transformBox(targetWithTransforms, latestValues); + /** + * Update the delta between the corrected box and the final target box, after + * user-set transforms are applied to it. This will be used by the renderer to + * create a transform style that will reproject the element from its layout layout + * into the desired bounding box. + */ + calcBoxDelta(this.projectionDeltaWithTransform, this.layoutCorrected, targetWithTransforms, latestValues); + } + registerSharedNode(layoutId, node) { + if (!this.sharedNodes.has(layoutId)) { + this.sharedNodes.set(layoutId, new NodeStack()); + } + const stack = this.sharedNodes.get(layoutId); + stack.add(node); + const config = node.options.initialPromotionConfig; + node.promote({ + transition: config ? config.transition : undefined, + preserveFollowOpacity: config && config.shouldPreserveFollowOpacity + ? config.shouldPreserveFollowOpacity(node) + : undefined, + }); + } + isLead() { + const stack = this.getStack(); + return stack ? stack.lead === this : true; + } + getLead() { + const { layoutId } = this.options; + return layoutId ? this.getStack()?.lead || this : this; + } + getPrevLead() { + const { layoutId } = this.options; + return layoutId ? this.getStack()?.prevLead : undefined; + } + getStack() { + const { layoutId } = this.options; + if (layoutId) + return this.root.sharedNodes.get(layoutId); + } + promote({ needsReset, transition, preserveFollowOpacity, } = {}) { + const stack = this.getStack(); + if (stack) + stack.promote(this, preserveFollowOpacity); + if (needsReset) { + this.projectionDelta = undefined; + this.needsReset = true; + } + if (transition) + this.setOptions({ transition }); + } + relegate() { + const stack = this.getStack(); + if (stack) { + return stack.relegate(this); + } + else { + return false; + } + } + resetSkewAndRotation() { + const { visualElement } = this.options; + if (!visualElement) + return; + // If there's no detected skew or rotation values, we can early return without a forced render. + let hasDistortingTransform = false; + /** + * An unrolled check for rotation values. Most elements don't have any rotation and + * skipping the nested loop and new object creation is 50% faster. + */ + const { latestValues } = visualElement; + if (latestValues.z || + latestValues.rotate || + latestValues.rotateX || + latestValues.rotateY || + latestValues.rotateZ || + latestValues.skewX || + latestValues.skewY) { + hasDistortingTransform = true; + } + // If there's no distorting values, we don't need to do any more. + if (!hasDistortingTransform) + return; + const resetValues = {}; + if (latestValues.z) { + resetDistortingTransform("z", visualElement, resetValues, this.animationValues); + } + // Check the skew and rotate value of all axes and reset to 0 + for (let i = 0; i < transformAxes.length; i++) { + resetDistortingTransform(`rotate${transformAxes[i]}`, visualElement, resetValues, this.animationValues); + resetDistortingTransform(`skew${transformAxes[i]}`, visualElement, resetValues, this.animationValues); + } + // Force a render of this element to apply the transform with all skews and rotations + // set to 0. + visualElement.render(); + // Put back all the values we reset + for (const key in resetValues) { + visualElement.setStaticValue(key, resetValues[key]); + if (this.animationValues) { + this.animationValues[key] = resetValues[key]; + } + } + // Schedule a render for the next frame. This ensures we won't visually + // see the element with the reset rotate value applied. + visualElement.scheduleRender(); + } + applyProjectionStyles(targetStyle, // CSSStyleDeclaration - doesn't allow numbers to be assigned to properties + styleProp) { + if (!this.instance || this.isSVG) + return; + if (!this.isVisible) { + targetStyle.visibility = "hidden"; + return; + } + const transformTemplate = this.getTransformTemplate(); + if (this.needsReset) { + this.needsReset = false; + targetStyle.visibility = ""; + targetStyle.opacity = ""; + targetStyle.pointerEvents = + resolveMotionValue(styleProp?.pointerEvents) || ""; + targetStyle.transform = transformTemplate + ? transformTemplate(this.latestValues, "") + : "none"; + return; + } + const lead = this.getLead(); + if (!this.projectionDelta || !this.layout || !lead.target) { + if (this.options.layoutId) { + targetStyle.opacity = + this.latestValues.opacity !== undefined + ? this.latestValues.opacity + : 1; + targetStyle.pointerEvents = + resolveMotionValue(styleProp?.pointerEvents) || ""; + } + if (this.hasProjected && !hasTransform(this.latestValues)) { + targetStyle.transform = transformTemplate + ? transformTemplate({}, "") + : "none"; + this.hasProjected = false; + } + return; + } + targetStyle.visibility = ""; + const valuesToRender = lead.animationValues || lead.latestValues; + this.applyTransformsToTarget(); + let transform = buildProjectionTransform(this.projectionDeltaWithTransform, this.treeScale, valuesToRender); + if (transformTemplate) { + transform = transformTemplate(valuesToRender, transform); + } + targetStyle.transform = transform; + const { x, y } = this.projectionDelta; + targetStyle.transformOrigin = `${x.origin * 100}% ${y.origin * 100}% 0`; + if (lead.animationValues) { + /** + * If the lead component is animating, assign this either the entering/leaving + * opacity + */ + targetStyle.opacity = + lead === this + ? valuesToRender.opacity ?? + this.latestValues.opacity ?? + 1 + : this.preserveOpacity + ? this.latestValues.opacity + : valuesToRender.opacityExit; + } + else { + /** + * Or we're not animating at all, set the lead component to its layout + * opacity and other components to hidden. + */ + targetStyle.opacity = + lead === this + ? valuesToRender.opacity !== undefined + ? valuesToRender.opacity + : "" + : valuesToRender.opacityExit !== undefined + ? valuesToRender.opacityExit + : 0; + } + /** + * Apply scale correction + */ + for (const key in scaleCorrectors) { + if (valuesToRender[key] === undefined) + continue; + const { correct, applyTo, isCSSVariable } = scaleCorrectors[key]; + /** + * Only apply scale correction to the value if we have an + * active projection transform. Otherwise these values become + * vulnerable to distortion if the element changes size without + * a corresponding layout animation. + */ + const corrected = transform === "none" + ? valuesToRender[key] + : correct(valuesToRender[key], lead); + if (applyTo) { + const num = applyTo.length; + for (let i = 0; i < num; i++) { + targetStyle[applyTo[i]] = corrected; + } + } + else { + // If this is a CSS variable, set it directly on the instance. + // Replacing this function from creating styles to setting them + // would be a good place to remove per frame object creation + if (isCSSVariable) { + this.options.visualElement.renderState.vars[key] = corrected; + } + else { + targetStyle[key] = corrected; + } + } + } + /** + * Disable pointer events on follow components. This is to ensure + * that if a follow component covers a lead component it doesn't block + * pointer events on the lead. + */ + if (this.options.layoutId) { + targetStyle.pointerEvents = + lead === this + ? resolveMotionValue(styleProp?.pointerEvents) || "" + : "none"; + } + } + clearSnapshot() { + this.resumeFrom = this.snapshot = undefined; + } + // Only run on root + resetTree() { + this.root.nodes.forEach((node) => node.currentAnimation?.stop()); + this.root.nodes.forEach(clearMeasurements); + this.root.sharedNodes.clear(); + } + }; +} +function updateLayout(node) { + node.updateLayout(); +} +function notifyLayoutUpdate(node) { + const snapshot = node.resumeFrom?.snapshot || node.snapshot; + if (node.isLead() && + node.layout && + snapshot && + node.hasListeners("didUpdate")) { + const { layoutBox: layout, measuredBox: measuredLayout } = node.layout; + const { animationType } = node.options; + const isShared = snapshot.source !== node.layout.source; + // TODO Maybe we want to also resize the layout snapshot so we don't trigger + // animations for instance if layout="size" and an element has only changed position + if (animationType === "size") { + eachAxis((axis) => { + const axisSnapshot = isShared + ? snapshot.measuredBox[axis] + : snapshot.layoutBox[axis]; + const length = calcLength(axisSnapshot); + axisSnapshot.min = layout[axis].min; + axisSnapshot.max = axisSnapshot.min + length; + }); + } + else if (shouldAnimatePositionOnly(animationType, snapshot.layoutBox, layout)) { + eachAxis((axis) => { + const axisSnapshot = isShared + ? snapshot.measuredBox[axis] + : snapshot.layoutBox[axis]; + const length = calcLength(layout[axis]); + axisSnapshot.max = axisSnapshot.min + length; + /** + * Ensure relative target gets resized and rerendererd + */ + if (node.relativeTarget && !node.currentAnimation) { + node.isProjectionDirty = true; + node.relativeTarget[axis].max = + node.relativeTarget[axis].min + length; + } + }); + } + const layoutDelta = createDelta(); + calcBoxDelta(layoutDelta, layout, snapshot.layoutBox); + const visualDelta = createDelta(); + if (isShared) { + calcBoxDelta(visualDelta, node.applyTransform(measuredLayout, true), snapshot.measuredBox); + } + else { + calcBoxDelta(visualDelta, layout, snapshot.layoutBox); + } + const hasLayoutChanged = !isDeltaZero(layoutDelta); + let hasRelativeLayoutChanged = false; + if (!node.resumeFrom) { + const relativeParent = node.getClosestProjectingParent(); + /** + * If the relativeParent is itself resuming from a different element then + * the relative snapshot is not relavent + */ + if (relativeParent && !relativeParent.resumeFrom) { + const { snapshot: parentSnapshot, layout: parentLayout } = relativeParent; + if (parentSnapshot && parentLayout) { + const relativeSnapshot = createBox(); + calcRelativePosition(relativeSnapshot, snapshot.layoutBox, parentSnapshot.layoutBox); + const relativeLayout = createBox(); + calcRelativePosition(relativeLayout, layout, parentLayout.layoutBox); + if (!boxEqualsRounded(relativeSnapshot, relativeLayout)) { + hasRelativeLayoutChanged = true; + } + if (relativeParent.options.layoutRoot) { + node.relativeTarget = relativeLayout; + node.relativeTargetOrigin = relativeSnapshot; + node.relativeParent = relativeParent; + } + } + } + } + node.notifyListeners("didUpdate", { + layout, + snapshot, + delta: visualDelta, + layoutDelta, + hasLayoutChanged, + hasRelativeLayoutChanged, + }); + } + else if (node.isLead()) { + const { onExitComplete } = node.options; + onExitComplete && onExitComplete(); + } + /** + * Clearing transition + * TODO: Investigate why this transition is being passed in as {type: false } from Framer + * and why we need it at all + */ + node.options.transition = undefined; +} +function propagateDirtyNodes(node) { + /** + * Increase debug counter for nodes encountered this frame + */ + if (statsBuffer.value) { + metrics.nodes++; + } + if (!node.parent) + return; + /** + * If this node isn't projecting, propagate isProjectionDirty. It will have + * no performance impact but it will allow the next child that *is* projecting + * but *isn't* dirty to just check its parent to see if *any* ancestor needs + * correcting. + */ + if (!node.isProjecting()) { + node.isProjectionDirty = node.parent.isProjectionDirty; + } + /** + * Propagate isSharedProjectionDirty and isTransformDirty + * throughout the whole tree. A future revision can take another look at + * this but for safety we still recalcualte shared nodes. + */ + node.isSharedProjectionDirty || (node.isSharedProjectionDirty = Boolean(node.isProjectionDirty || + node.parent.isProjectionDirty || + node.parent.isSharedProjectionDirty)); + node.isTransformDirty || (node.isTransformDirty = node.parent.isTransformDirty); +} +function cleanDirtyNodes(node) { + node.isProjectionDirty = + node.isSharedProjectionDirty = + node.isTransformDirty = + false; +} +function clearSnapshot(node) { + node.clearSnapshot(); +} +function clearMeasurements(node) { + node.clearMeasurements(); +} +function clearIsLayoutDirty(node) { + node.isLayoutDirty = false; +} +function resetTransformStyle(node) { + const { visualElement } = node.options; + if (visualElement && visualElement.getProps().onBeforeLayoutMeasure) { + visualElement.notify("BeforeLayoutMeasure"); + } + node.resetTransform(); +} +function finishAnimation(node) { + node.finishAnimation(); + node.targetDelta = node.relativeTarget = node.target = undefined; + node.isProjectionDirty = true; +} +function resolveTargetDelta(node) { + node.resolveTargetDelta(); +} +function calcProjection(node) { + node.calcProjection(); +} +function resetSkewAndRotation(node) { + node.resetSkewAndRotation(); +} +function removeLeadSnapshots(stack) { + stack.removeLeadSnapshot(); +} +function mixAxisDelta(output, delta, p) { + output.translate = mixNumber(delta.translate, 0, p); + output.scale = mixNumber(delta.scale, 1, p); + output.origin = delta.origin; + output.originPoint = delta.originPoint; +} +function mixAxis(output, from, to, p) { + output.min = mixNumber(from.min, to.min, p); + output.max = mixNumber(from.max, to.max, p); +} +function mixBox(output, from, to, p) { + mixAxis(output.x, from.x, to.x, p); + mixAxis(output.y, from.y, to.y, p); +} +function hasOpacityCrossfade(node) { + return (node.animationValues && node.animationValues.opacityExit !== undefined); +} +const defaultLayoutTransition = { + duration: 0.45, + ease: [0.4, 0, 0.1, 1], +}; +const userAgentContains = (string) => typeof navigator !== "undefined" && + navigator.userAgent && + navigator.userAgent.toLowerCase().includes(string); +/** + * Measured bounding boxes must be rounded in Safari and + * left untouched in Chrome, otherwise non-integer layouts within scaled-up elements + * can appear to jump. + */ +const roundPoint = userAgentContains("applewebkit/") && !userAgentContains("chrome/") + ? Math.round + : noop; +function roundAxis(axis) { + // Round to the nearest .5 pixels to support subpixel layouts + axis.min = roundPoint(axis.min); + axis.max = roundPoint(axis.max); +} +function roundBox(box) { + roundAxis(box.x); + roundAxis(box.y); +} +function shouldAnimatePositionOnly(animationType, snapshot, layout) { + return (animationType === "position" || + (animationType === "preserve-aspect" && + !isNear(aspectRatio(snapshot), aspectRatio(layout), 0.2))); +} +function checkNodeWasScrollRoot(node) { + return node !== node.root && node.scroll?.wasRoot; +} + +export { cleanDirtyNodes, createProjectionNode, mixAxis, mixAxisDelta, mixBox, propagateDirtyNodes }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/node/group.mjs b/frontend/node_modules/framer-motion/dist/es/projection/node/group.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0dd1fd8f84b61365688af12a202bc3455c617ab8 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/node/group.mjs @@ -0,0 +1,24 @@ +const notify = (node) => !node.isLayoutDirty && node.willUpdate(false); +function nodeGroup() { + const nodes = new Set(); + const subscriptions = new WeakMap(); + const dirtyAll = () => nodes.forEach(notify); + return { + add: (node) => { + nodes.add(node); + subscriptions.set(node, node.addEventListener("willUpdate", dirtyAll)); + }, + remove: (node) => { + nodes.delete(node); + const unsubscribe = subscriptions.get(node); + if (unsubscribe) { + unsubscribe(); + subscriptions.delete(node); + } + dirtyAll(); + }, + dirty: dirtyAll, + }; +} + +export { nodeGroup }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/node/state.mjs b/frontend/node_modules/framer-motion/dist/es/projection/node/state.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e516e6104a19d1a8d04098ad14a1c33a921c367c --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/node/state.mjs @@ -0,0 +1,19 @@ +/** + * This should only ever be modified on the client otherwise it'll + * persist through server requests. If we need instanced states we + * could lazy-init via root. + */ +const globalProjectionState = { + /** + * Global flag as to whether the tree has animated since the last time + * we resized the window + */ + hasAnimatedSinceResize: true, + /** + * We set this to true once, on the first update. Any nodes added to the tree beyond that + * update will be given a `data-projection-id` attribute. + */ + hasEverUpdated: false, +}; + +export { globalProjectionState }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/shared/stack.mjs b/frontend/node_modules/framer-motion/dist/es/projection/shared/stack.mjs new file mode 100644 index 0000000000000000000000000000000000000000..da4af5a8119a84312f4fd188090e743521b73fd9 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/shared/stack.mjs @@ -0,0 +1,112 @@ +import { addUniqueItem, removeItem } from 'motion-utils'; + +class NodeStack { + constructor() { + this.members = []; + } + add(node) { + addUniqueItem(this.members, node); + node.scheduleRender(); + } + remove(node) { + removeItem(this.members, node); + if (node === this.prevLead) { + this.prevLead = undefined; + } + if (node === this.lead) { + const prevLead = this.members[this.members.length - 1]; + if (prevLead) { + this.promote(prevLead); + } + } + } + relegate(node) { + const indexOfNode = this.members.findIndex((member) => node === member); + if (indexOfNode === 0) + return false; + /** + * Find the next projection node that is present + */ + let prevLead; + for (let i = indexOfNode; i >= 0; i--) { + const member = this.members[i]; + if (member.isPresent !== false) { + prevLead = member; + break; + } + } + if (prevLead) { + this.promote(prevLead); + return true; + } + else { + return false; + } + } + promote(node, preserveFollowOpacity) { + const prevLead = this.lead; + if (node === prevLead) + return; + this.prevLead = prevLead; + this.lead = node; + node.show(); + if (prevLead) { + prevLead.instance && prevLead.scheduleRender(); + node.scheduleRender(); + node.resumeFrom = prevLead; + if (preserveFollowOpacity) { + node.resumeFrom.preserveOpacity = true; + } + if (prevLead.snapshot) { + node.snapshot = prevLead.snapshot; + node.snapshot.latestValues = + prevLead.animationValues || prevLead.latestValues; + } + if (node.root && node.root.isUpdating) { + node.isLayoutDirty = true; + } + const { crossfade } = node.options; + if (crossfade === false) { + prevLead.hide(); + } + /** + * TODO: + * - Test border radius when previous node was deleted + * - boxShadow mixing + * - Shared between element A in scrolled container and element B (scroll stays the same or changes) + * - Shared between element A in transformed container and element B (transform stays the same or changes) + * - Shared between element A in scrolled page and element B (scroll stays the same or changes) + * --- + * - Crossfade opacity of root nodes + * - layoutId changes after animation + * - layoutId changes mid animation + */ + } + } + exitAnimationComplete() { + this.members.forEach((node) => { + const { options, resumingFrom } = node; + options.onExitComplete && options.onExitComplete(); + if (resumingFrom) { + resumingFrom.options.onExitComplete && + resumingFrom.options.onExitComplete(); + } + }); + } + scheduleRender() { + this.members.forEach((node) => { + node.instance && node.scheduleRender(false); + }); + } + /** + * Clear any leads that have been removed this render to prevent them from being + * used in future animations and to prevent memory leaks + */ + removeLeadSnapshot() { + if (this.lead && this.lead.snapshot) { + this.lead.snapshot = undefined; + } + } +} + +export { NodeStack }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/styles/scale-border-radius.mjs b/frontend/node_modules/framer-motion/dist/es/projection/styles/scale-border-radius.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b827baaf7c89afaf7f31eb6e76640b62a3008ba4 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/styles/scale-border-radius.mjs @@ -0,0 +1,41 @@ +import { px } from 'motion-dom'; + +function pixelsToPercent(pixels, axis) { + if (axis.max === axis.min) + return 0; + return (pixels / (axis.max - axis.min)) * 100; +} +/** + * We always correct borderRadius as a percentage rather than pixels to reduce paints. + * For example, if you are projecting a box that is 100px wide with a 10px borderRadius + * into a box that is 200px wide with a 20px borderRadius, that is actually a 10% + * borderRadius in both states. If we animate between the two in pixels that will trigger + * a paint each time. If we animate between the two in percentage we'll avoid a paint. + */ +const correctBorderRadius = { + correct: (latest, node) => { + if (!node.target) + return latest; + /** + * If latest is a string, if it's a percentage we can return immediately as it's + * going to be stretched appropriately. Otherwise, if it's a pixel, convert it to a number. + */ + if (typeof latest === "string") { + if (px.test(latest)) { + latest = parseFloat(latest); + } + else { + return latest; + } + } + /** + * If latest is a number, it's a pixel value. We use the current viewportBox to calculate that + * pixel value as a percentage of each axis + */ + const x = pixelsToPercent(latest, node.target.x); + const y = pixelsToPercent(latest, node.target.y); + return `${x}% ${y}%`; + }, +}; + +export { correctBorderRadius, pixelsToPercent }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/styles/scale-box-shadow.mjs b/frontend/node_modules/framer-motion/dist/es/projection/styles/scale-box-shadow.mjs new file mode 100644 index 0000000000000000000000000000000000000000..eddf7a52931d5472327fd7794396dbb693d6b862 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/styles/scale-box-shadow.mjs @@ -0,0 +1,34 @@ +import { complex, mixNumber } from 'motion-dom'; + +const correctBoxShadow = { + correct: (latest, { treeScale, projectionDelta }) => { + const original = latest; + const shadow = complex.parse(latest); + // TODO: Doesn't support multiple shadows + if (shadow.length > 5) + return original; + const template = complex.createTransformer(latest); + const offset = typeof shadow[0] !== "number" ? 1 : 0; + // Calculate the overall context scale + const xScale = projectionDelta.x.scale * treeScale.x; + const yScale = projectionDelta.y.scale * treeScale.y; + shadow[0 + offset] /= xScale; + shadow[1 + offset] /= yScale; + /** + * Ideally we'd correct x and y scales individually, but because blur and + * spread apply to both we have to take a scale average and apply that instead. + * We could potentially improve the outcome of this by incorporating the ratio between + * the two scales. + */ + const averageScale = mixNumber(xScale, yScale, 0.5); + // Blur + if (typeof shadow[2 + offset] === "number") + shadow[2 + offset] /= averageScale; + // Spread + if (typeof shadow[3 + offset] === "number") + shadow[3 + offset] /= averageScale; + return template(shadow); + }, +}; + +export { correctBoxShadow }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/styles/scale-correction.mjs b/frontend/node_modules/framer-motion/dist/es/projection/styles/scale-correction.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c3dff7f76bd457f41816d354ce8aba151aabbe24 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/styles/scale-correction.mjs @@ -0,0 +1,13 @@ +import { isCSSVariableName } from 'motion-dom'; + +const scaleCorrectors = {}; +function addScaleCorrector(correctors) { + for (const key in correctors) { + scaleCorrectors[key] = correctors[key]; + if (isCSSVariableName(key)) { + scaleCorrectors[key].isCSSVariable = true; + } + } +} + +export { addScaleCorrector, scaleCorrectors }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/styles/transform.mjs b/frontend/node_modules/framer-motion/dist/es/projection/styles/transform.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1f5b56153caf69008e73238ea9d9f8fdb840c77a --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/styles/transform.mjs @@ -0,0 +1,49 @@ +function buildProjectionTransform(delta, treeScale, latestTransform) { + let transform = ""; + /** + * The translations we use to calculate are always relative to the viewport coordinate space. + * But when we apply scales, we also scale the coordinate space of an element and its children. + * For instance if we have a treeScale (the culmination of all parent scales) of 0.5 and we need + * to move an element 100 pixels, we actually need to move it 200 in within that scaled space. + */ + const xTranslate = delta.x.translate / treeScale.x; + const yTranslate = delta.y.translate / treeScale.y; + const zTranslate = latestTransform?.z || 0; + if (xTranslate || yTranslate || zTranslate) { + transform = `translate3d(${xTranslate}px, ${yTranslate}px, ${zTranslate}px) `; + } + /** + * Apply scale correction for the tree transform. + * This will apply scale to the screen-orientated axes. + */ + if (treeScale.x !== 1 || treeScale.y !== 1) { + transform += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `; + } + if (latestTransform) { + const { transformPerspective, rotate, rotateX, rotateY, skewX, skewY } = latestTransform; + if (transformPerspective) + transform = `perspective(${transformPerspective}px) ${transform}`; + if (rotate) + transform += `rotate(${rotate}deg) `; + if (rotateX) + transform += `rotateX(${rotateX}deg) `; + if (rotateY) + transform += `rotateY(${rotateY}deg) `; + if (skewX) + transform += `skewX(${skewX}deg) `; + if (skewY) + transform += `skewY(${skewY}deg) `; + } + /** + * Apply scale to match the size of the element to the size we want it. + * This will apply scale to the element-orientated axes. + */ + const elementScaleX = delta.x.scale * treeScale.x; + const elementScaleY = delta.y.scale * treeScale.y; + if (elementScaleX !== 1 || elementScaleY !== 1) { + transform += `scale(${elementScaleX}, ${elementScaleY})`; + } + return transform || "none"; +} + +export { buildProjectionTransform }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/use-instant-layout-transition.mjs b/frontend/node_modules/framer-motion/dist/es/projection/use-instant-layout-transition.mjs new file mode 100644 index 0000000000000000000000000000000000000000..51a8297da9195995cb9ed5b34aafba463cfea5fe --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/use-instant-layout-transition.mjs @@ -0,0 +1,14 @@ +import { rootProjectionNode } from './node/HTMLProjectionNode.mjs'; + +function useInstantLayoutTransition() { + return startTransition; +} +function startTransition(callback) { + if (!rootProjectionNode.current) + return; + rootProjectionNode.current.isUpdating = false; + rootProjectionNode.current.blockUpdate(); + callback && callback(); +} + +export { useInstantLayoutTransition }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/use-reset-projection.mjs b/frontend/node_modules/framer-motion/dist/es/projection/use-reset-projection.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5fa993265cb06016639c6ffa5da7f1070d7b2ba8 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/use-reset-projection.mjs @@ -0,0 +1,14 @@ +import { useCallback } from 'react'; +import { rootProjectionNode } from './node/HTMLProjectionNode.mjs'; + +function useResetProjection() { + const reset = useCallback(() => { + const root = rootProjectionNode.current; + if (!root) + return; + root.resetTree(); + }, []); + return reset; +} + +export { useResetProjection }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/utils/each-axis.mjs b/frontend/node_modules/framer-motion/dist/es/projection/utils/each-axis.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e9434c72ea2e1d57335b7bb951feb30aa40239cc --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/utils/each-axis.mjs @@ -0,0 +1,5 @@ +function eachAxis(callback) { + return [callback("x"), callback("y")]; +} + +export { eachAxis }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/utils/has-transform.mjs b/frontend/node_modules/framer-motion/dist/es/projection/utils/has-transform.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d99d6e83870131f949a5e56bc423256e37d26ecd --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/utils/has-transform.mjs @@ -0,0 +1,26 @@ +function isIdentityScale(scale) { + return scale === undefined || scale === 1; +} +function hasScale({ scale, scaleX, scaleY }) { + return (!isIdentityScale(scale) || + !isIdentityScale(scaleX) || + !isIdentityScale(scaleY)); +} +function hasTransform(values) { + return (hasScale(values) || + has2DTranslate(values) || + values.z || + values.rotate || + values.rotateX || + values.rotateY || + values.skewX || + values.skewY); +} +function has2DTranslate(values) { + return is2DTranslate(values.x) || is2DTranslate(values.y); +} +function is2DTranslate(value) { + return value && value !== "0%"; +} + +export { has2DTranslate, hasScale, hasTransform }; diff --git a/frontend/node_modules/framer-motion/dist/es/projection/utils/measure.mjs b/frontend/node_modules/framer-motion/dist/es/projection/utils/measure.mjs new file mode 100644 index 0000000000000000000000000000000000000000..adcb380882f82793b9d7a8cf8568d0eb666a2953 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/projection/utils/measure.mjs @@ -0,0 +1,17 @@ +import { convertBoundingBoxToBox, transformBoxPoints } from '../geometry/conversion.mjs'; +import { translateAxis } from '../geometry/delta-apply.mjs'; + +function measureViewportBox(instance, transformPoint) { + return convertBoundingBoxToBox(transformBoxPoints(instance.getBoundingClientRect(), transformPoint)); +} +function measurePageBox(element, rootProjectionNode, transformPagePoint) { + const viewportBox = measureViewportBox(element, transformPagePoint); + const { scroll } = rootProjectionNode; + if (scroll) { + translateAxis(viewportBox.x, scroll.offset.x); + translateAxis(viewportBox.y, scroll.offset.y); + } + return viewportBox; +} + +export { measurePageBox, measureViewportBox }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/VisualElement.mjs b/frontend/node_modules/framer-motion/dist/es/render/VisualElement.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e6e9ed0206c01e0072319b212f89d54ecb289286 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/VisualElement.mjs @@ -0,0 +1,477 @@ +import { KeyframeResolver, time, frame, isMotionValue, cancelFrame, transformProps, motionValue, findValueType, complex, getAnimatableNone, microtask } from 'motion-dom'; +import { warnOnce, isNumericalString, isZeroValueString, SubscriptionManager } from 'motion-utils'; +import { featureDefinitions } from '../motion/features/definitions.mjs'; +import { createBox } from '../projection/geometry/models.mjs'; +import { initPrefersReducedMotion } from '../utils/reduced-motion/index.mjs'; +import { hasReducedMotionListener, prefersReducedMotion } from '../utils/reduced-motion/state.mjs'; +import { visualElementStore } from './store.mjs'; +import { isControllingVariants, isVariantNode } from './utils/is-controlling-variants.mjs'; +import { updateMotionValuesFromProps } from './utils/motion-values.mjs'; +import { resolveVariantFromProps } from './utils/resolve-variants.mjs'; + +const propEventHandlers = [ + "AnimationStart", + "AnimationComplete", + "Update", + "BeforeLayoutMeasure", + "LayoutMeasure", + "LayoutAnimationStart", + "LayoutAnimationComplete", +]; +/** + * A VisualElement is an imperative abstraction around UI elements such as + * HTMLElement, SVGElement, Three.Object3D etc. + */ +class VisualElement { + /** + * This method takes React props and returns found MotionValues. For example, HTML + * MotionValues will be found within the style prop, whereas for Three.js within attribute arrays. + * + * This isn't an abstract method as it needs calling in the constructor, but it is + * intended to be one. + */ + scrapeMotionValuesFromProps(_props, _prevProps, _visualElement) { + return {}; + } + constructor({ parent, props, presenceContext, reducedMotionConfig, blockInitialAnimation, visualState, }, options = {}) { + /** + * A reference to the current underlying Instance, e.g. a HTMLElement + * or Three.Mesh etc. + */ + this.current = null; + /** + * A set containing references to this VisualElement's children. + */ + this.children = new Set(); + /** + * Determine what role this visual element should take in the variant tree. + */ + this.isVariantNode = false; + this.isControllingVariants = false; + /** + * Decides whether this VisualElement should animate in reduced motion + * mode. + * + * TODO: This is currently set on every individual VisualElement but feels + * like it could be set globally. + */ + this.shouldReduceMotion = null; + /** + * A map of all motion values attached to this visual element. Motion + * values are source of truth for any given animated value. A motion + * value might be provided externally by the component via props. + */ + this.values = new Map(); + this.KeyframeResolver = KeyframeResolver; + /** + * Cleanup functions for active features (hover/tap/exit etc) + */ + this.features = {}; + /** + * A map of every subscription that binds the provided or generated + * motion values onChange listeners to this visual element. + */ + this.valueSubscriptions = new Map(); + /** + * A reference to the previously-provided motion values as returned + * from scrapeMotionValuesFromProps. We use the keys in here to determine + * if any motion values need to be removed after props are updated. + */ + this.prevMotionValues = {}; + /** + * An object containing a SubscriptionManager for each active event. + */ + this.events = {}; + /** + * An object containing an unsubscribe function for each prop event subscription. + * For example, every "Update" event can have multiple subscribers via + * VisualElement.on(), but only one of those can be defined via the onUpdate prop. + */ + this.propEventSubscriptions = {}; + this.notifyUpdate = () => this.notify("Update", this.latestValues); + this.render = () => { + if (!this.current) + return; + this.triggerBuild(); + this.renderInstance(this.current, this.renderState, this.props.style, this.projection); + }; + this.renderScheduledAt = 0.0; + this.scheduleRender = () => { + const now = time.now(); + if (this.renderScheduledAt < now) { + this.renderScheduledAt = now; + frame.render(this.render, false, true); + } + }; + const { latestValues, renderState } = visualState; + this.latestValues = latestValues; + this.baseTarget = { ...latestValues }; + this.initialValues = props.initial ? { ...latestValues } : {}; + this.renderState = renderState; + this.parent = parent; + this.props = props; + this.presenceContext = presenceContext; + this.depth = parent ? parent.depth + 1 : 0; + this.reducedMotionConfig = reducedMotionConfig; + this.options = options; + this.blockInitialAnimation = Boolean(blockInitialAnimation); + this.isControllingVariants = isControllingVariants(props); + this.isVariantNode = isVariantNode(props); + if (this.isVariantNode) { + this.variantChildren = new Set(); + } + this.manuallyAnimateOnMount = Boolean(parent && parent.current); + /** + * Any motion values that are provided to the element when created + * aren't yet bound to the element, as this would technically be impure. + * However, we iterate through the motion values and set them to the + * initial values for this component. + * + * TODO: This is impure and we should look at changing this to run on mount. + * Doing so will break some tests but this isn't necessarily a breaking change, + * more a reflection of the test. + */ + const { willChange, ...initialMotionValues } = this.scrapeMotionValuesFromProps(props, {}, this); + for (const key in initialMotionValues) { + const value = initialMotionValues[key]; + if (latestValues[key] !== undefined && isMotionValue(value)) { + value.set(latestValues[key]); + } + } + } + mount(instance) { + this.current = instance; + visualElementStore.set(instance, this); + if (this.projection && !this.projection.instance) { + this.projection.mount(instance); + } + if (this.parent && this.isVariantNode && !this.isControllingVariants) { + this.removeFromVariantTree = this.parent.addVariantChild(this); + } + this.values.forEach((value, key) => this.bindToMotionValue(key, value)); + if (!hasReducedMotionListener.current) { + initPrefersReducedMotion(); + } + this.shouldReduceMotion = + this.reducedMotionConfig === "never" + ? false + : this.reducedMotionConfig === "always" + ? true + : prefersReducedMotion.current; + if (process.env.NODE_ENV !== "production") { + warnOnce(this.shouldReduceMotion !== true, "You have Reduced Motion enabled on your device. Animations may not appear as expected.", "reduced-motion-disabled"); + } + this.parent?.addChild(this); + this.update(this.props, this.presenceContext); + } + unmount() { + this.projection && this.projection.unmount(); + cancelFrame(this.notifyUpdate); + cancelFrame(this.render); + this.valueSubscriptions.forEach((remove) => remove()); + this.valueSubscriptions.clear(); + this.removeFromVariantTree && this.removeFromVariantTree(); + this.parent?.removeChild(this); + for (const key in this.events) { + this.events[key].clear(); + } + for (const key in this.features) { + const feature = this.features[key]; + if (feature) { + feature.unmount(); + feature.isMounted = false; + } + } + this.current = null; + } + addChild(child) { + this.children.add(child); + this.enteringChildren ?? (this.enteringChildren = new Set()); + this.enteringChildren.add(child); + } + removeChild(child) { + this.children.delete(child); + this.enteringChildren && this.enteringChildren.delete(child); + } + bindToMotionValue(key, value) { + if (this.valueSubscriptions.has(key)) { + this.valueSubscriptions.get(key)(); + } + const valueIsTransform = transformProps.has(key); + if (valueIsTransform && this.onBindTransform) { + this.onBindTransform(); + } + const removeOnChange = value.on("change", (latestValue) => { + this.latestValues[key] = latestValue; + this.props.onUpdate && frame.preRender(this.notifyUpdate); + if (valueIsTransform && this.projection) { + this.projection.isTransformDirty = true; + } + this.scheduleRender(); + }); + let removeSyncCheck; + if (window.MotionCheckAppearSync) { + removeSyncCheck = window.MotionCheckAppearSync(this, key, value); + } + this.valueSubscriptions.set(key, () => { + removeOnChange(); + if (removeSyncCheck) + removeSyncCheck(); + if (value.owner) + value.stop(); + }); + } + sortNodePosition(other) { + /** + * If these nodes aren't even of the same type we can't compare their depth. + */ + if (!this.current || + !this.sortInstanceNodePosition || + this.type !== other.type) { + return 0; + } + return this.sortInstanceNodePosition(this.current, other.current); + } + updateFeatures() { + let key = "animation"; + for (key in featureDefinitions) { + const featureDefinition = featureDefinitions[key]; + if (!featureDefinition) + continue; + const { isEnabled, Feature: FeatureConstructor } = featureDefinition; + /** + * If this feature is enabled but not active, make a new instance. + */ + if (!this.features[key] && + FeatureConstructor && + isEnabled(this.props)) { + this.features[key] = new FeatureConstructor(this); + } + /** + * If we have a feature, mount or update it. + */ + if (this.features[key]) { + const feature = this.features[key]; + if (feature.isMounted) { + feature.update(); + } + else { + feature.mount(); + feature.isMounted = true; + } + } + } + } + triggerBuild() { + this.build(this.renderState, this.latestValues, this.props); + } + /** + * Measure the current viewport box with or without transforms. + * Only measures axis-aligned boxes, rotate and skew must be manually + * removed with a re-render to work. + */ + measureViewportBox() { + return this.current + ? this.measureInstanceViewportBox(this.current, this.props) + : createBox(); + } + getStaticValue(key) { + return this.latestValues[key]; + } + setStaticValue(key, value) { + this.latestValues[key] = value; + } + /** + * Update the provided props. Ensure any newly-added motion values are + * added to our map, old ones removed, and listeners updated. + */ + update(props, presenceContext) { + if (props.transformTemplate || this.props.transformTemplate) { + this.scheduleRender(); + } + this.prevProps = this.props; + this.props = props; + this.prevPresenceContext = this.presenceContext; + this.presenceContext = presenceContext; + /** + * Update prop event handlers ie onAnimationStart, onAnimationComplete + */ + for (let i = 0; i < propEventHandlers.length; i++) { + const key = propEventHandlers[i]; + if (this.propEventSubscriptions[key]) { + this.propEventSubscriptions[key](); + delete this.propEventSubscriptions[key]; + } + const listenerName = ("on" + key); + const listener = props[listenerName]; + if (listener) { + this.propEventSubscriptions[key] = this.on(key, listener); + } + } + this.prevMotionValues = updateMotionValuesFromProps(this, this.scrapeMotionValuesFromProps(props, this.prevProps, this), this.prevMotionValues); + if (this.handleChildMotionValue) { + this.handleChildMotionValue(); + } + } + getProps() { + return this.props; + } + /** + * Returns the variant definition with a given name. + */ + getVariant(name) { + return this.props.variants ? this.props.variants[name] : undefined; + } + /** + * Returns the defined default transition on this component. + */ + getDefaultTransition() { + return this.props.transition; + } + getTransformPagePoint() { + return this.props.transformPagePoint; + } + getClosestVariantNode() { + return this.isVariantNode + ? this + : this.parent + ? this.parent.getClosestVariantNode() + : undefined; + } + /** + * Add a child visual element to our set of children. + */ + addVariantChild(child) { + const closestVariantNode = this.getClosestVariantNode(); + if (closestVariantNode) { + closestVariantNode.variantChildren && + closestVariantNode.variantChildren.add(child); + return () => closestVariantNode.variantChildren.delete(child); + } + } + /** + * Add a motion value and bind it to this visual element. + */ + addValue(key, value) { + // Remove existing value if it exists + const existingValue = this.values.get(key); + if (value !== existingValue) { + if (existingValue) + this.removeValue(key); + this.bindToMotionValue(key, value); + this.values.set(key, value); + this.latestValues[key] = value.get(); + } + } + /** + * Remove a motion value and unbind any active subscriptions. + */ + removeValue(key) { + this.values.delete(key); + const unsubscribe = this.valueSubscriptions.get(key); + if (unsubscribe) { + unsubscribe(); + this.valueSubscriptions.delete(key); + } + delete this.latestValues[key]; + this.removeValueFromRenderState(key, this.renderState); + } + /** + * Check whether we have a motion value for this key + */ + hasValue(key) { + return this.values.has(key); + } + getValue(key, defaultValue) { + if (this.props.values && this.props.values[key]) { + return this.props.values[key]; + } + let value = this.values.get(key); + if (value === undefined && defaultValue !== undefined) { + value = motionValue(defaultValue === null ? undefined : defaultValue, { owner: this }); + this.addValue(key, value); + } + return value; + } + /** + * If we're trying to animate to a previously unencountered value, + * we need to check for it in our state and as a last resort read it + * directly from the instance (which might have performance implications). + */ + readValue(key, target) { + let value = this.latestValues[key] !== undefined || !this.current + ? this.latestValues[key] + : this.getBaseTargetFromProps(this.props, key) ?? + this.readValueFromInstance(this.current, key, this.options); + if (value !== undefined && value !== null) { + if (typeof value === "string" && + (isNumericalString(value) || isZeroValueString(value))) { + // If this is a number read as a string, ie "0" or "200", convert it to a number + value = parseFloat(value); + } + else if (!findValueType(value) && complex.test(target)) { + value = getAnimatableNone(key, target); + } + this.setBaseTarget(key, isMotionValue(value) ? value.get() : value); + } + return isMotionValue(value) ? value.get() : value; + } + /** + * Set the base target to later animate back to. This is currently + * only hydrated on creation and when we first read a value. + */ + setBaseTarget(key, value) { + this.baseTarget[key] = value; + } + /** + * Find the base target for a value thats been removed from all animation + * props. + */ + getBaseTarget(key) { + const { initial } = this.props; + let valueFromInitial; + if (typeof initial === "string" || typeof initial === "object") { + const variant = resolveVariantFromProps(this.props, initial, this.presenceContext?.custom); + if (variant) { + valueFromInitial = variant[key]; + } + } + /** + * If this value still exists in the current initial variant, read that. + */ + if (initial && valueFromInitial !== undefined) { + return valueFromInitial; + } + /** + * Alternatively, if this VisualElement config has defined a getBaseTarget + * so we can read the value from an alternative source, try that. + */ + const target = this.getBaseTargetFromProps(this.props, key); + if (target !== undefined && !isMotionValue(target)) + return target; + /** + * If the value was initially defined on initial, but it doesn't any more, + * return undefined. Otherwise return the value as initially read from the DOM. + */ + return this.initialValues[key] !== undefined && + valueFromInitial === undefined + ? undefined + : this.baseTarget[key]; + } + on(eventName, callback) { + if (!this.events[eventName]) { + this.events[eventName] = new SubscriptionManager(); + } + return this.events[eventName].add(callback); + } + notify(eventName, ...args) { + if (this.events[eventName]) { + this.events[eventName].notify(...args); + } + } + scheduleRenderMicrotask() { + microtask.render(this.render); + } +} + +export { VisualElement }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/components/create-proxy.mjs b/frontend/node_modules/framer-motion/dist/es/render/components/create-proxy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ae24ac396e7ea2bdc5bc9144948efffff6bc69d9 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/components/create-proxy.mjs @@ -0,0 +1,45 @@ +import { warnOnce } from 'motion-utils'; +import { createMotionComponent } from '../../motion/index.mjs'; + +function createMotionProxy(preloadedFeatures, createVisualElement) { + if (typeof Proxy === "undefined") { + return createMotionComponent; + } + /** + * A cache of generated `motion` components, e.g `motion.div`, `motion.input` etc. + * Rather than generating them anew every render. + */ + const componentCache = new Map(); + const factory = (Component, options) => { + return createMotionComponent(Component, options, preloadedFeatures, createVisualElement); + }; + /** + * Support for deprecated`motion(Component)` pattern + */ + const deprecatedFactoryFunction = (Component, options) => { + if (process.env.NODE_ENV !== "production") { + warnOnce(false, "motion() is deprecated. Use motion.create() instead."); + } + return factory(Component, options); + }; + return new Proxy(deprecatedFactoryFunction, { + /** + * Called when `motion` is referenced with a prop: `motion.div`, `motion.input` etc. + * The prop name is passed through as `key` and we can use that to generate a `motion` + * DOM component with that name. + */ + get: (_target, key) => { + if (key === "create") + return factory; + /** + * If this element doesn't exist in the component cache, create it and cache. + */ + if (!componentCache.has(key)) { + componentCache.set(key, createMotionComponent(key, undefined, preloadedFeatures, createVisualElement)); + } + return componentCache.get(key); + }, + }); +} + +export { createMotionProxy }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/components/m/create.mjs b/frontend/node_modules/framer-motion/dist/es/render/components/m/create.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8a66f0afb744a11193f182cb196e0428379eb677 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/components/m/create.mjs @@ -0,0 +1,7 @@ +import { createMotionComponent } from '../../../motion/index.mjs'; + +function createMinimalMotionComponent(Component, options) { + return createMotionComponent(Component, options); +} + +export { createMinimalMotionComponent }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/components/m/elements.mjs b/frontend/node_modules/framer-motion/dist/es/render/components/m/elements.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ac516d337e9de063d80749ac67a3c7243150795f --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/components/m/elements.mjs @@ -0,0 +1,227 @@ +"use client"; +import { createMinimalMotionComponent } from './create.mjs'; + +/** + * HTML components + */ +const MotionA = /*@__PURE__*/ createMinimalMotionComponent("a"); +const MotionAbbr = /*@__PURE__*/ createMinimalMotionComponent("abbr"); +const MotionAddress = +/*@__PURE__*/ createMinimalMotionComponent("address"); +const MotionArea = /*@__PURE__*/ createMinimalMotionComponent("area"); +const MotionArticle = +/*@__PURE__*/ createMinimalMotionComponent("article"); +const MotionAside = /*@__PURE__*/ createMinimalMotionComponent("aside"); +const MotionAudio = /*@__PURE__*/ createMinimalMotionComponent("audio"); +const MotionB = /*@__PURE__*/ createMinimalMotionComponent("b"); +const MotionBase = /*@__PURE__*/ createMinimalMotionComponent("base"); +const MotionBdi = /*@__PURE__*/ createMinimalMotionComponent("bdi"); +const MotionBdo = /*@__PURE__*/ createMinimalMotionComponent("bdo"); +const MotionBig = /*@__PURE__*/ createMinimalMotionComponent("big"); +const MotionBlockquote = +/*@__PURE__*/ createMinimalMotionComponent("blockquote"); +const MotionBody = /*@__PURE__*/ createMinimalMotionComponent("body"); +const MotionButton = /*@__PURE__*/ createMinimalMotionComponent("button"); +const MotionCanvas = /*@__PURE__*/ createMinimalMotionComponent("canvas"); +const MotionCaption = +/*@__PURE__*/ createMinimalMotionComponent("caption"); +const MotionCite = /*@__PURE__*/ createMinimalMotionComponent("cite"); +const MotionCode = /*@__PURE__*/ createMinimalMotionComponent("code"); +const MotionCol = /*@__PURE__*/ createMinimalMotionComponent("col"); +const MotionColgroup = +/*@__PURE__*/ createMinimalMotionComponent("colgroup"); +const MotionData = /*@__PURE__*/ createMinimalMotionComponent("data"); +const MotionDatalist = +/*@__PURE__*/ createMinimalMotionComponent("datalist"); +const MotionDd = /*@__PURE__*/ createMinimalMotionComponent("dd"); +const MotionDel = /*@__PURE__*/ createMinimalMotionComponent("del"); +const MotionDetails = +/*@__PURE__*/ createMinimalMotionComponent("details"); +const MotionDfn = /*@__PURE__*/ createMinimalMotionComponent("dfn"); +const MotionDialog = /*@__PURE__*/ createMinimalMotionComponent("dialog"); +const MotionDiv = /*@__PURE__*/ createMinimalMotionComponent("div"); +const MotionDl = /*@__PURE__*/ createMinimalMotionComponent("dl"); +const MotionDt = /*@__PURE__*/ createMinimalMotionComponent("dt"); +const MotionEm = /*@__PURE__*/ createMinimalMotionComponent("em"); +const MotionEmbed = /*@__PURE__*/ createMinimalMotionComponent("embed"); +const MotionFieldset = +/*@__PURE__*/ createMinimalMotionComponent("fieldset"); +const MotionFigcaption = +/*@__PURE__*/ createMinimalMotionComponent("figcaption"); +const MotionFigure = /*@__PURE__*/ createMinimalMotionComponent("figure"); +const MotionFooter = /*@__PURE__*/ createMinimalMotionComponent("footer"); +const MotionForm = /*@__PURE__*/ createMinimalMotionComponent("form"); +const MotionH1 = /*@__PURE__*/ createMinimalMotionComponent("h1"); +const MotionH2 = /*@__PURE__*/ createMinimalMotionComponent("h2"); +const MotionH3 = /*@__PURE__*/ createMinimalMotionComponent("h3"); +const MotionH4 = /*@__PURE__*/ createMinimalMotionComponent("h4"); +const MotionH5 = /*@__PURE__*/ createMinimalMotionComponent("h5"); +const MotionH6 = /*@__PURE__*/ createMinimalMotionComponent("h6"); +const MotionHead = /*@__PURE__*/ createMinimalMotionComponent("head"); +const MotionHeader = /*@__PURE__*/ createMinimalMotionComponent("header"); +const MotionHgroup = /*@__PURE__*/ createMinimalMotionComponent("hgroup"); +const MotionHr = /*@__PURE__*/ createMinimalMotionComponent("hr"); +const MotionHtml = /*@__PURE__*/ createMinimalMotionComponent("html"); +const MotionI = /*@__PURE__*/ createMinimalMotionComponent("i"); +const MotionIframe = /*@__PURE__*/ createMinimalMotionComponent("iframe"); +const MotionImg = /*@__PURE__*/ createMinimalMotionComponent("img"); +const MotionInput = /*@__PURE__*/ createMinimalMotionComponent("input"); +const MotionIns = /*@__PURE__*/ createMinimalMotionComponent("ins"); +const MotionKbd = /*@__PURE__*/ createMinimalMotionComponent("kbd"); +const MotionKeygen = /*@__PURE__*/ createMinimalMotionComponent("keygen"); +const MotionLabel = /*@__PURE__*/ createMinimalMotionComponent("label"); +const MotionLegend = /*@__PURE__*/ createMinimalMotionComponent("legend"); +const MotionLi = /*@__PURE__*/ createMinimalMotionComponent("li"); +const MotionLink = /*@__PURE__*/ createMinimalMotionComponent("link"); +const MotionMain = /*@__PURE__*/ createMinimalMotionComponent("main"); +const MotionMap = /*@__PURE__*/ createMinimalMotionComponent("map"); +const MotionMark = /*@__PURE__*/ createMinimalMotionComponent("mark"); +const MotionMenu = /*@__PURE__*/ createMinimalMotionComponent("menu"); +const MotionMenuitem = +/*@__PURE__*/ createMinimalMotionComponent("menuitem"); +const MotionMeter = /*@__PURE__*/ createMinimalMotionComponent("meter"); +const MotionNav = /*@__PURE__*/ createMinimalMotionComponent("nav"); +const MotionObject = /*@__PURE__*/ createMinimalMotionComponent("object"); +const MotionOl = /*@__PURE__*/ createMinimalMotionComponent("ol"); +const MotionOptgroup = +/*@__PURE__*/ createMinimalMotionComponent("optgroup"); +const MotionOption = /*@__PURE__*/ createMinimalMotionComponent("option"); +const MotionOutput = /*@__PURE__*/ createMinimalMotionComponent("output"); +const MotionP = /*@__PURE__*/ createMinimalMotionComponent("p"); +const MotionParam = /*@__PURE__*/ createMinimalMotionComponent("param"); +const MotionPicture = +/*@__PURE__*/ createMinimalMotionComponent("picture"); +const MotionPre = /*@__PURE__*/ createMinimalMotionComponent("pre"); +const MotionProgress = +/*@__PURE__*/ createMinimalMotionComponent("progress"); +const MotionQ = /*@__PURE__*/ createMinimalMotionComponent("q"); +const MotionRp = /*@__PURE__*/ createMinimalMotionComponent("rp"); +const MotionRt = /*@__PURE__*/ createMinimalMotionComponent("rt"); +const MotionRuby = /*@__PURE__*/ createMinimalMotionComponent("ruby"); +const MotionS = /*@__PURE__*/ createMinimalMotionComponent("s"); +const MotionSamp = /*@__PURE__*/ createMinimalMotionComponent("samp"); +const MotionScript = /*@__PURE__*/ createMinimalMotionComponent("script"); +const MotionSection = +/*@__PURE__*/ createMinimalMotionComponent("section"); +const MotionSelect = /*@__PURE__*/ createMinimalMotionComponent("select"); +const MotionSmall = /*@__PURE__*/ createMinimalMotionComponent("small"); +const MotionSource = /*@__PURE__*/ createMinimalMotionComponent("source"); +const MotionSpan = /*@__PURE__*/ createMinimalMotionComponent("span"); +const MotionStrong = /*@__PURE__*/ createMinimalMotionComponent("strong"); +const MotionStyle = /*@__PURE__*/ createMinimalMotionComponent("style"); +const MotionSub = /*@__PURE__*/ createMinimalMotionComponent("sub"); +const MotionSummary = +/*@__PURE__*/ createMinimalMotionComponent("summary"); +const MotionSup = /*@__PURE__*/ createMinimalMotionComponent("sup"); +const MotionTable = /*@__PURE__*/ createMinimalMotionComponent("table"); +const MotionTbody = /*@__PURE__*/ createMinimalMotionComponent("tbody"); +const MotionTd = /*@__PURE__*/ createMinimalMotionComponent("td"); +const MotionTextarea = +/*@__PURE__*/ createMinimalMotionComponent("textarea"); +const MotionTfoot = /*@__PURE__*/ createMinimalMotionComponent("tfoot"); +const MotionTh = /*@__PURE__*/ createMinimalMotionComponent("th"); +const MotionThead = /*@__PURE__*/ createMinimalMotionComponent("thead"); +const MotionTime = /*@__PURE__*/ createMinimalMotionComponent("time"); +const MotionTitle = /*@__PURE__*/ createMinimalMotionComponent("title"); +const MotionTr = /*@__PURE__*/ createMinimalMotionComponent("tr"); +const MotionTrack = /*@__PURE__*/ createMinimalMotionComponent("track"); +const MotionU = /*@__PURE__*/ createMinimalMotionComponent("u"); +const MotionUl = /*@__PURE__*/ createMinimalMotionComponent("ul"); +const MotionVideo = /*@__PURE__*/ createMinimalMotionComponent("video"); +const MotionWbr = /*@__PURE__*/ createMinimalMotionComponent("wbr"); +const MotionWebview = +/*@__PURE__*/ createMinimalMotionComponent("webview"); +/** + * SVG components + */ +const MotionAnimate = +/*@__PURE__*/ createMinimalMotionComponent("animate"); +const MotionCircle = /*@__PURE__*/ createMinimalMotionComponent("circle"); +const MotionDefs = /*@__PURE__*/ createMinimalMotionComponent("defs"); +const MotionDesc = /*@__PURE__*/ createMinimalMotionComponent("desc"); +const MotionEllipse = +/*@__PURE__*/ createMinimalMotionComponent("ellipse"); +const MotionG = /*@__PURE__*/ createMinimalMotionComponent("g"); +const MotionImage = /*@__PURE__*/ createMinimalMotionComponent("image"); +const MotionLine = /*@__PURE__*/ createMinimalMotionComponent("line"); +const MotionFilter = /*@__PURE__*/ createMinimalMotionComponent("filter"); +const MotionMarker = /*@__PURE__*/ createMinimalMotionComponent("marker"); +const MotionMask = /*@__PURE__*/ createMinimalMotionComponent("mask"); +const MotionMetadata = +/*@__PURE__*/ createMinimalMotionComponent("metadata"); +const MotionPath = /*@__PURE__*/ createMinimalMotionComponent("path"); +const MotionPattern = +/*@__PURE__*/ createMinimalMotionComponent("pattern"); +const MotionPolygon = +/*@__PURE__*/ createMinimalMotionComponent("polygon"); +const MotionPolyline = +/*@__PURE__*/ createMinimalMotionComponent("polyline"); +const MotionRect = /*@__PURE__*/ createMinimalMotionComponent("rect"); +const MotionStop = /*@__PURE__*/ createMinimalMotionComponent("stop"); +const MotionSvg = /*@__PURE__*/ createMinimalMotionComponent("svg"); +const MotionSymbol = /*@__PURE__*/ createMinimalMotionComponent("symbol"); +const MotionText = /*@__PURE__*/ createMinimalMotionComponent("text"); +const MotionTspan = /*@__PURE__*/ createMinimalMotionComponent("tspan"); +const MotionUse = /*@__PURE__*/ createMinimalMotionComponent("use"); +const MotionView = /*@__PURE__*/ createMinimalMotionComponent("view"); +const MotionClipPath = +/*@__PURE__*/ createMinimalMotionComponent("clipPath"); +const MotionFeBlend = +/*@__PURE__*/ createMinimalMotionComponent("feBlend"); +const MotionFeColorMatrix = +/*@__PURE__*/ createMinimalMotionComponent("feColorMatrix"); +const MotionFeComponentTransfer = +/*@__PURE__*/ createMinimalMotionComponent("feComponentTransfer"); +const MotionFeComposite = +/*@__PURE__*/ createMinimalMotionComponent("feComposite"); +const MotionFeConvolveMatrix = +/*@__PURE__*/ createMinimalMotionComponent("feConvolveMatrix"); +const MotionFeDiffuseLighting = +/*@__PURE__*/ createMinimalMotionComponent("feDiffuseLighting"); +const MotionFeDisplacementMap = +/*@__PURE__*/ createMinimalMotionComponent("feDisplacementMap"); +const MotionFeDistantLight = +/*@__PURE__*/ createMinimalMotionComponent("feDistantLight"); +const MotionFeDropShadow = +/*@__PURE__*/ createMinimalMotionComponent("feDropShadow"); +const MotionFeFlood = +/*@__PURE__*/ createMinimalMotionComponent("feFlood"); +const MotionFeFuncA = +/*@__PURE__*/ createMinimalMotionComponent("feFuncA"); +const MotionFeFuncB = +/*@__PURE__*/ createMinimalMotionComponent("feFuncB"); +const MotionFeFuncG = +/*@__PURE__*/ createMinimalMotionComponent("feFuncG"); +const MotionFeFuncR = +/*@__PURE__*/ createMinimalMotionComponent("feFuncR"); +const MotionFeGaussianBlur = +/*@__PURE__*/ createMinimalMotionComponent("feGaussianBlur"); +const MotionFeImage = +/*@__PURE__*/ createMinimalMotionComponent("feImage"); +const MotionFeMerge = +/*@__PURE__*/ createMinimalMotionComponent("feMerge"); +const MotionFeMergeNode = +/*@__PURE__*/ createMinimalMotionComponent("feMergeNode"); +const MotionFeMorphology = +/*@__PURE__*/ createMinimalMotionComponent("feMorphology"); +const MotionFeOffset = +/*@__PURE__*/ createMinimalMotionComponent("feOffset"); +const MotionFePointLight = +/*@__PURE__*/ createMinimalMotionComponent("fePointLight"); +const MotionFeSpecularLighting = +/*@__PURE__*/ createMinimalMotionComponent("feSpecularLighting"); +const MotionFeSpotLight = +/*@__PURE__*/ createMinimalMotionComponent("feSpotLight"); +const MotionFeTile = /*@__PURE__*/ createMinimalMotionComponent("feTile"); +const MotionFeTurbulence = +/*@__PURE__*/ createMinimalMotionComponent("feTurbulence"); +const MotionForeignObject = +/*@__PURE__*/ createMinimalMotionComponent("foreignObject"); +const MotionLinearGradient = +/*@__PURE__*/ createMinimalMotionComponent("linearGradient"); +const MotionRadialGradient = +/*@__PURE__*/ createMinimalMotionComponent("radialGradient"); +const MotionTextPath = +/*@__PURE__*/ createMinimalMotionComponent("textPath"); + +export { MotionA, MotionAbbr, MotionAddress, MotionAnimate, MotionArea, MotionArticle, MotionAside, MotionAudio, MotionB, MotionBase, MotionBdi, MotionBdo, MotionBig, MotionBlockquote, MotionBody, MotionButton, MotionCanvas, MotionCaption, MotionCircle, MotionCite, MotionClipPath, MotionCode, MotionCol, MotionColgroup, MotionData, MotionDatalist, MotionDd, MotionDefs, MotionDel, MotionDesc, MotionDetails, MotionDfn, MotionDialog, MotionDiv, MotionDl, MotionDt, MotionEllipse, MotionEm, MotionEmbed, MotionFeBlend, MotionFeColorMatrix, MotionFeComponentTransfer, MotionFeComposite, MotionFeConvolveMatrix, MotionFeDiffuseLighting, MotionFeDisplacementMap, MotionFeDistantLight, MotionFeDropShadow, MotionFeFlood, MotionFeFuncA, MotionFeFuncB, MotionFeFuncG, MotionFeFuncR, MotionFeGaussianBlur, MotionFeImage, MotionFeMerge, MotionFeMergeNode, MotionFeMorphology, MotionFeOffset, MotionFePointLight, MotionFeSpecularLighting, MotionFeSpotLight, MotionFeTile, MotionFeTurbulence, MotionFieldset, MotionFigcaption, MotionFigure, MotionFilter, MotionFooter, MotionForeignObject, MotionForm, MotionG, MotionH1, MotionH2, MotionH3, MotionH4, MotionH5, MotionH6, MotionHead, MotionHeader, MotionHgroup, MotionHr, MotionHtml, MotionI, MotionIframe, MotionImage, MotionImg, MotionInput, MotionIns, MotionKbd, MotionKeygen, MotionLabel, MotionLegend, MotionLi, MotionLine, MotionLinearGradient, MotionLink, MotionMain, MotionMap, MotionMark, MotionMarker, MotionMask, MotionMenu, MotionMenuitem, MotionMetadata, MotionMeter, MotionNav, MotionObject, MotionOl, MotionOptgroup, MotionOption, MotionOutput, MotionP, MotionParam, MotionPath, MotionPattern, MotionPicture, MotionPolygon, MotionPolyline, MotionPre, MotionProgress, MotionQ, MotionRadialGradient, MotionRect, MotionRp, MotionRt, MotionRuby, MotionS, MotionSamp, MotionScript, MotionSection, MotionSelect, MotionSmall, MotionSource, MotionSpan, MotionStop, MotionStrong, MotionStyle, MotionSub, MotionSummary, MotionSup, MotionSvg, MotionSymbol, MotionTable, MotionTbody, MotionTd, MotionText, MotionTextPath, MotionTextarea, MotionTfoot, MotionTh, MotionThead, MotionTime, MotionTitle, MotionTr, MotionTrack, MotionTspan, MotionU, MotionUl, MotionUse, MotionVideo, MotionView, MotionWbr, MotionWebview }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/components/m/proxy.mjs b/frontend/node_modules/framer-motion/dist/es/render/components/m/proxy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..21f42d0d583bc1f05e18b5a892f4e120ead69f15 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/components/m/proxy.mjs @@ -0,0 +1,5 @@ +import { createMotionProxy } from '../create-proxy.mjs'; + +const m = /*@__PURE__*/ createMotionProxy(); + +export { m }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/components/motion/create.mjs b/frontend/node_modules/framer-motion/dist/es/render/components/motion/create.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6453670da06bc2ad737c48545557e97204e877c7 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/components/motion/create.mjs @@ -0,0 +1,9 @@ +import { createMotionComponent } from '../../../motion/index.mjs'; +import { createDomVisualElement } from '../../dom/create-visual-element.mjs'; +import { featureBundle } from './feature-bundle.mjs'; + +function createMotionComponentWithFeatures(Component, options) { + return createMotionComponent(Component, options, featureBundle, createDomVisualElement); +} + +export { createMotionComponentWithFeatures }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/components/motion/elements.mjs b/frontend/node_modules/framer-motion/dist/es/render/components/motion/elements.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f183920a172e9b6d699b708e86d191d3e048cb3d --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/components/motion/elements.mjs @@ -0,0 +1,194 @@ +"use client"; +import { createMotionComponentWithFeatures } from './create.mjs'; + +/** + * HTML components + */ +const MotionA = /*@__PURE__*/ createMotionComponentWithFeatures("a"); +const MotionAbbr = /*@__PURE__*/ createMotionComponentWithFeatures("abbr"); +const MotionAddress = /*@__PURE__*/ createMotionComponentWithFeatures("address"); +const MotionArea = /*@__PURE__*/ createMotionComponentWithFeatures("area"); +const MotionArticle = /*@__PURE__*/ createMotionComponentWithFeatures("article"); +const MotionAside = /*@__PURE__*/ createMotionComponentWithFeatures("aside"); +const MotionAudio = /*@__PURE__*/ createMotionComponentWithFeatures("audio"); +const MotionB = /*@__PURE__*/ createMotionComponentWithFeatures("b"); +const MotionBase = /*@__PURE__*/ createMotionComponentWithFeatures("base"); +const MotionBdi = /*@__PURE__*/ createMotionComponentWithFeatures("bdi"); +const MotionBdo = /*@__PURE__*/ createMotionComponentWithFeatures("bdo"); +const MotionBig = /*@__PURE__*/ createMotionComponentWithFeatures("big"); +const MotionBlockquote = +/*@__PURE__*/ createMotionComponentWithFeatures("blockquote"); +const MotionBody = /*@__PURE__*/ createMotionComponentWithFeatures("body"); +const MotionButton = /*@__PURE__*/ createMotionComponentWithFeatures("button"); +const MotionCanvas = /*@__PURE__*/ createMotionComponentWithFeatures("canvas"); +const MotionCaption = /*@__PURE__*/ createMotionComponentWithFeatures("caption"); +const MotionCite = /*@__PURE__*/ createMotionComponentWithFeatures("cite"); +const MotionCode = /*@__PURE__*/ createMotionComponentWithFeatures("code"); +const MotionCol = /*@__PURE__*/ createMotionComponentWithFeatures("col"); +const MotionColgroup = /*@__PURE__*/ createMotionComponentWithFeatures("colgroup"); +const MotionData = /*@__PURE__*/ createMotionComponentWithFeatures("data"); +const MotionDatalist = /*@__PURE__*/ createMotionComponentWithFeatures("datalist"); +const MotionDd = /*@__PURE__*/ createMotionComponentWithFeatures("dd"); +const MotionDel = /*@__PURE__*/ createMotionComponentWithFeatures("del"); +const MotionDetails = /*@__PURE__*/ createMotionComponentWithFeatures("details"); +const MotionDfn = /*@__PURE__*/ createMotionComponentWithFeatures("dfn"); +const MotionDialog = /*@__PURE__*/ createMotionComponentWithFeatures("dialog"); +const MotionDiv = /*@__PURE__*/ createMotionComponentWithFeatures("div"); +const MotionDl = /*@__PURE__*/ createMotionComponentWithFeatures("dl"); +const MotionDt = /*@__PURE__*/ createMotionComponentWithFeatures("dt"); +const MotionEm = /*@__PURE__*/ createMotionComponentWithFeatures("em"); +const MotionEmbed = /*@__PURE__*/ createMotionComponentWithFeatures("embed"); +const MotionFieldset = /*@__PURE__*/ createMotionComponentWithFeatures("fieldset"); +const MotionFigcaption = +/*@__PURE__*/ createMotionComponentWithFeatures("figcaption"); +const MotionFigure = /*@__PURE__*/ createMotionComponentWithFeatures("figure"); +const MotionFooter = /*@__PURE__*/ createMotionComponentWithFeatures("footer"); +const MotionForm = /*@__PURE__*/ createMotionComponentWithFeatures("form"); +const MotionH1 = /*@__PURE__*/ createMotionComponentWithFeatures("h1"); +const MotionH2 = /*@__PURE__*/ createMotionComponentWithFeatures("h2"); +const MotionH3 = /*@__PURE__*/ createMotionComponentWithFeatures("h3"); +const MotionH4 = /*@__PURE__*/ createMotionComponentWithFeatures("h4"); +const MotionH5 = /*@__PURE__*/ createMotionComponentWithFeatures("h5"); +const MotionH6 = /*@__PURE__*/ createMotionComponentWithFeatures("h6"); +const MotionHead = /*@__PURE__*/ createMotionComponentWithFeatures("head"); +const MotionHeader = /*@__PURE__*/ createMotionComponentWithFeatures("header"); +const MotionHgroup = /*@__PURE__*/ createMotionComponentWithFeatures("hgroup"); +const MotionHr = /*@__PURE__*/ createMotionComponentWithFeatures("hr"); +const MotionHtml = /*@__PURE__*/ createMotionComponentWithFeatures("html"); +const MotionI = /*@__PURE__*/ createMotionComponentWithFeatures("i"); +const MotionIframe = /*@__PURE__*/ createMotionComponentWithFeatures("iframe"); +const MotionImg = /*@__PURE__*/ createMotionComponentWithFeatures("img"); +const MotionInput = /*@__PURE__*/ createMotionComponentWithFeatures("input"); +const MotionIns = /*@__PURE__*/ createMotionComponentWithFeatures("ins"); +const MotionKbd = /*@__PURE__*/ createMotionComponentWithFeatures("kbd"); +const MotionKeygen = /*@__PURE__*/ createMotionComponentWithFeatures("keygen"); +const MotionLabel = /*@__PURE__*/ createMotionComponentWithFeatures("label"); +const MotionLegend = /*@__PURE__*/ createMotionComponentWithFeatures("legend"); +const MotionLi = /*@__PURE__*/ createMotionComponentWithFeatures("li"); +const MotionLink = /*@__PURE__*/ createMotionComponentWithFeatures("link"); +const MotionMain = /*@__PURE__*/ createMotionComponentWithFeatures("main"); +const MotionMap = /*@__PURE__*/ createMotionComponentWithFeatures("map"); +const MotionMark = /*@__PURE__*/ createMotionComponentWithFeatures("mark"); +const MotionMenu = /*@__PURE__*/ createMotionComponentWithFeatures("menu"); +const MotionMenuitem = /*@__PURE__*/ createMotionComponentWithFeatures("menuitem"); +const MotionMeter = /*@__PURE__*/ createMotionComponentWithFeatures("meter"); +const MotionNav = /*@__PURE__*/ createMotionComponentWithFeatures("nav"); +const MotionObject = /*@__PURE__*/ createMotionComponentWithFeatures("object"); +const MotionOl = /*@__PURE__*/ createMotionComponentWithFeatures("ol"); +const MotionOptgroup = /*@__PURE__*/ createMotionComponentWithFeatures("optgroup"); +const MotionOption = /*@__PURE__*/ createMotionComponentWithFeatures("option"); +const MotionOutput = /*@__PURE__*/ createMotionComponentWithFeatures("output"); +const MotionP = /*@__PURE__*/ createMotionComponentWithFeatures("p"); +const MotionParam = /*@__PURE__*/ createMotionComponentWithFeatures("param"); +const MotionPicture = /*@__PURE__*/ createMotionComponentWithFeatures("picture"); +const MotionPre = /*@__PURE__*/ createMotionComponentWithFeatures("pre"); +const MotionProgress = /*@__PURE__*/ createMotionComponentWithFeatures("progress"); +const MotionQ = /*@__PURE__*/ createMotionComponentWithFeatures("q"); +const MotionRp = /*@__PURE__*/ createMotionComponentWithFeatures("rp"); +const MotionRt = /*@__PURE__*/ createMotionComponentWithFeatures("rt"); +const MotionRuby = /*@__PURE__*/ createMotionComponentWithFeatures("ruby"); +const MotionS = /*@__PURE__*/ createMotionComponentWithFeatures("s"); +const MotionSamp = /*@__PURE__*/ createMotionComponentWithFeatures("samp"); +const MotionScript = /*@__PURE__*/ createMotionComponentWithFeatures("script"); +const MotionSection = /*@__PURE__*/ createMotionComponentWithFeatures("section"); +const MotionSelect = /*@__PURE__*/ createMotionComponentWithFeatures("select"); +const MotionSmall = /*@__PURE__*/ createMotionComponentWithFeatures("small"); +const MotionSource = /*@__PURE__*/ createMotionComponentWithFeatures("source"); +const MotionSpan = /*@__PURE__*/ createMotionComponentWithFeatures("span"); +const MotionStrong = /*@__PURE__*/ createMotionComponentWithFeatures("strong"); +const MotionStyle = /*@__PURE__*/ createMotionComponentWithFeatures("style"); +const MotionSub = /*@__PURE__*/ createMotionComponentWithFeatures("sub"); +const MotionSummary = /*@__PURE__*/ createMotionComponentWithFeatures("summary"); +const MotionSup = /*@__PURE__*/ createMotionComponentWithFeatures("sup"); +const MotionTable = /*@__PURE__*/ createMotionComponentWithFeatures("table"); +const MotionTbody = /*@__PURE__*/ createMotionComponentWithFeatures("tbody"); +const MotionTd = /*@__PURE__*/ createMotionComponentWithFeatures("td"); +const MotionTextarea = /*@__PURE__*/ createMotionComponentWithFeatures("textarea"); +const MotionTfoot = /*@__PURE__*/ createMotionComponentWithFeatures("tfoot"); +const MotionTh = /*@__PURE__*/ createMotionComponentWithFeatures("th"); +const MotionThead = /*@__PURE__*/ createMotionComponentWithFeatures("thead"); +const MotionTime = /*@__PURE__*/ createMotionComponentWithFeatures("time"); +const MotionTitle = /*@__PURE__*/ createMotionComponentWithFeatures("title"); +const MotionTr = /*@__PURE__*/ createMotionComponentWithFeatures("tr"); +const MotionTrack = /*@__PURE__*/ createMotionComponentWithFeatures("track"); +const MotionU = /*@__PURE__*/ createMotionComponentWithFeatures("u"); +const MotionUl = /*@__PURE__*/ createMotionComponentWithFeatures("ul"); +const MotionVideo = /*@__PURE__*/ createMotionComponentWithFeatures("video"); +const MotionWbr = /*@__PURE__*/ createMotionComponentWithFeatures("wbr"); +const MotionWebview = /*@__PURE__*/ createMotionComponentWithFeatures("webview"); +/** + * SVG components + */ +const MotionAnimate = /*@__PURE__*/ createMotionComponentWithFeatures("animate"); +const MotionCircle = /*@__PURE__*/ createMotionComponentWithFeatures("circle"); +const MotionDefs = /*@__PURE__*/ createMotionComponentWithFeatures("defs"); +const MotionDesc = /*@__PURE__*/ createMotionComponentWithFeatures("desc"); +const MotionEllipse = /*@__PURE__*/ createMotionComponentWithFeatures("ellipse"); +const MotionG = /*@__PURE__*/ createMotionComponentWithFeatures("g"); +const MotionImage = /*@__PURE__*/ createMotionComponentWithFeatures("image"); +const MotionLine = /*@__PURE__*/ createMotionComponentWithFeatures("line"); +const MotionFilter = /*@__PURE__*/ createMotionComponentWithFeatures("filter"); +const MotionMarker = /*@__PURE__*/ createMotionComponentWithFeatures("marker"); +const MotionMask = /*@__PURE__*/ createMotionComponentWithFeatures("mask"); +const MotionMetadata = /*@__PURE__*/ createMotionComponentWithFeatures("metadata"); +const MotionPath = /*@__PURE__*/ createMotionComponentWithFeatures("path"); +const MotionPattern = /*@__PURE__*/ createMotionComponentWithFeatures("pattern"); +const MotionPolygon = /*@__PURE__*/ createMotionComponentWithFeatures("polygon"); +const MotionPolyline = /*@__PURE__*/ createMotionComponentWithFeatures("polyline"); +const MotionRect = /*@__PURE__*/ createMotionComponentWithFeatures("rect"); +const MotionStop = /*@__PURE__*/ createMotionComponentWithFeatures("stop"); +const MotionSvg = /*@__PURE__*/ createMotionComponentWithFeatures("svg"); +const MotionSymbol = /*@__PURE__*/ createMotionComponentWithFeatures("symbol"); +const MotionText = /*@__PURE__*/ createMotionComponentWithFeatures("text"); +const MotionTspan = /*@__PURE__*/ createMotionComponentWithFeatures("tspan"); +const MotionUse = /*@__PURE__*/ createMotionComponentWithFeatures("use"); +const MotionView = /*@__PURE__*/ createMotionComponentWithFeatures("view"); +const MotionClipPath = /*@__PURE__*/ createMotionComponentWithFeatures("clipPath"); +const MotionFeBlend = /*@__PURE__*/ createMotionComponentWithFeatures("feBlend"); +const MotionFeColorMatrix = +/*@__PURE__*/ createMotionComponentWithFeatures("feColorMatrix"); +const MotionFeComponentTransfer = /*@__PURE__*/ createMotionComponentWithFeatures("feComponentTransfer"); +const MotionFeComposite = +/*@__PURE__*/ createMotionComponentWithFeatures("feComposite"); +const MotionFeConvolveMatrix = +/*@__PURE__*/ createMotionComponentWithFeatures("feConvolveMatrix"); +const MotionFeDiffuseLighting = +/*@__PURE__*/ createMotionComponentWithFeatures("feDiffuseLighting"); +const MotionFeDisplacementMap = +/*@__PURE__*/ createMotionComponentWithFeatures("feDisplacementMap"); +const MotionFeDistantLight = +/*@__PURE__*/ createMotionComponentWithFeatures("feDistantLight"); +const MotionFeDropShadow = +/*@__PURE__*/ createMotionComponentWithFeatures("feDropShadow"); +const MotionFeFlood = /*@__PURE__*/ createMotionComponentWithFeatures("feFlood"); +const MotionFeFuncA = /*@__PURE__*/ createMotionComponentWithFeatures("feFuncA"); +const MotionFeFuncB = /*@__PURE__*/ createMotionComponentWithFeatures("feFuncB"); +const MotionFeFuncG = /*@__PURE__*/ createMotionComponentWithFeatures("feFuncG"); +const MotionFeFuncR = /*@__PURE__*/ createMotionComponentWithFeatures("feFuncR"); +const MotionFeGaussianBlur = +/*@__PURE__*/ createMotionComponentWithFeatures("feGaussianBlur"); +const MotionFeImage = /*@__PURE__*/ createMotionComponentWithFeatures("feImage"); +const MotionFeMerge = /*@__PURE__*/ createMotionComponentWithFeatures("feMerge"); +const MotionFeMergeNode = +/*@__PURE__*/ createMotionComponentWithFeatures("feMergeNode"); +const MotionFeMorphology = +/*@__PURE__*/ createMotionComponentWithFeatures("feMorphology"); +const MotionFeOffset = /*@__PURE__*/ createMotionComponentWithFeatures("feOffset"); +const MotionFePointLight = +/*@__PURE__*/ createMotionComponentWithFeatures("fePointLight"); +const MotionFeSpecularLighting = +/*@__PURE__*/ createMotionComponentWithFeatures("feSpecularLighting"); +const MotionFeSpotLight = +/*@__PURE__*/ createMotionComponentWithFeatures("feSpotLight"); +const MotionFeTile = /*@__PURE__*/ createMotionComponentWithFeatures("feTile"); +const MotionFeTurbulence = +/*@__PURE__*/ createMotionComponentWithFeatures("feTurbulence"); +const MotionForeignObject = +/*@__PURE__*/ createMotionComponentWithFeatures("foreignObject"); +const MotionLinearGradient = +/*@__PURE__*/ createMotionComponentWithFeatures("linearGradient"); +const MotionRadialGradient = +/*@__PURE__*/ createMotionComponentWithFeatures("radialGradient"); +const MotionTextPath = /*@__PURE__*/ createMotionComponentWithFeatures("textPath"); + +export { MotionA, MotionAbbr, MotionAddress, MotionAnimate, MotionArea, MotionArticle, MotionAside, MotionAudio, MotionB, MotionBase, MotionBdi, MotionBdo, MotionBig, MotionBlockquote, MotionBody, MotionButton, MotionCanvas, MotionCaption, MotionCircle, MotionCite, MotionClipPath, MotionCode, MotionCol, MotionColgroup, MotionData, MotionDatalist, MotionDd, MotionDefs, MotionDel, MotionDesc, MotionDetails, MotionDfn, MotionDialog, MotionDiv, MotionDl, MotionDt, MotionEllipse, MotionEm, MotionEmbed, MotionFeBlend, MotionFeColorMatrix, MotionFeComponentTransfer, MotionFeComposite, MotionFeConvolveMatrix, MotionFeDiffuseLighting, MotionFeDisplacementMap, MotionFeDistantLight, MotionFeDropShadow, MotionFeFlood, MotionFeFuncA, MotionFeFuncB, MotionFeFuncG, MotionFeFuncR, MotionFeGaussianBlur, MotionFeImage, MotionFeMerge, MotionFeMergeNode, MotionFeMorphology, MotionFeOffset, MotionFePointLight, MotionFeSpecularLighting, MotionFeSpotLight, MotionFeTile, MotionFeTurbulence, MotionFieldset, MotionFigcaption, MotionFigure, MotionFilter, MotionFooter, MotionForeignObject, MotionForm, MotionG, MotionH1, MotionH2, MotionH3, MotionH4, MotionH5, MotionH6, MotionHead, MotionHeader, MotionHgroup, MotionHr, MotionHtml, MotionI, MotionIframe, MotionImage, MotionImg, MotionInput, MotionIns, MotionKbd, MotionKeygen, MotionLabel, MotionLegend, MotionLi, MotionLine, MotionLinearGradient, MotionLink, MotionMain, MotionMap, MotionMark, MotionMarker, MotionMask, MotionMenu, MotionMenuitem, MotionMetadata, MotionMeter, MotionNav, MotionObject, MotionOl, MotionOptgroup, MotionOption, MotionOutput, MotionP, MotionParam, MotionPath, MotionPattern, MotionPicture, MotionPolygon, MotionPolyline, MotionPre, MotionProgress, MotionQ, MotionRadialGradient, MotionRect, MotionRp, MotionRt, MotionRuby, MotionS, MotionSamp, MotionScript, MotionSection, MotionSelect, MotionSmall, MotionSource, MotionSpan, MotionStop, MotionStrong, MotionStyle, MotionSub, MotionSummary, MotionSup, MotionSvg, MotionSymbol, MotionTable, MotionTbody, MotionTd, MotionText, MotionTextPath, MotionTextarea, MotionTfoot, MotionTh, MotionThead, MotionTime, MotionTitle, MotionTr, MotionTrack, MotionTspan, MotionU, MotionUl, MotionUse, MotionVideo, MotionView, MotionWbr, MotionWebview }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/components/motion/feature-bundle.mjs b/frontend/node_modules/framer-motion/dist/es/render/components/motion/feature-bundle.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4a576ac8af1a977125230166bc6691db9bf5dcf1 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/components/motion/feature-bundle.mjs @@ -0,0 +1,13 @@ +import { animations } from '../../../motion/features/animations.mjs'; +import { drag } from '../../../motion/features/drag.mjs'; +import { gestureAnimations } from '../../../motion/features/gestures.mjs'; +import { layout } from '../../../motion/features/layout.mjs'; + +const featureBundle = { + ...animations, + ...gestureAnimations, + ...drag, + ...layout, +}; + +export { featureBundle }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/components/motion/proxy.mjs b/frontend/node_modules/framer-motion/dist/es/render/components/motion/proxy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..698e783929dabe4b8fb79c4a22b86435198943dd --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/components/motion/proxy.mjs @@ -0,0 +1,7 @@ +import { createDomVisualElement } from '../../dom/create-visual-element.mjs'; +import { createMotionProxy } from '../create-proxy.mjs'; +import { featureBundle } from './feature-bundle.mjs'; + +const motion = /*@__PURE__*/ createMotionProxy(featureBundle, createDomVisualElement); + +export { motion }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/DOMVisualElement.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/DOMVisualElement.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b7f9d0dea88e7a87bd432b78e0605a03607fa82f --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/DOMVisualElement.mjs @@ -0,0 +1,42 @@ +import { DOMKeyframesResolver, isMotionValue } from 'motion-dom'; +import { VisualElement } from '../VisualElement.mjs'; + +class DOMVisualElement extends VisualElement { + constructor() { + super(...arguments); + this.KeyframeResolver = DOMKeyframesResolver; + } + sortInstanceNodePosition(a, b) { + /** + * compareDocumentPosition returns a bitmask, by using the bitwise & + * we're returning true if 2 in that bitmask is set to true. 2 is set + * to true if b preceeds a. + */ + return a.compareDocumentPosition(b) & 2 ? 1 : -1; + } + getBaseTargetFromProps(props, key) { + return props.style + ? props.style[key] + : undefined; + } + removeValueFromRenderState(key, { vars, style }) { + delete vars[key]; + delete style[key]; + } + handleChildMotionValue() { + if (this.childSubscription) { + this.childSubscription(); + delete this.childSubscription; + } + const { children } = this.props; + if (isMotionValue(children)) { + this.childSubscription = children.on("change", (latest) => { + if (this.current) { + this.current.textContent = `${latest}`; + } + }); + } + } +} + +export { DOMVisualElement }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/create-visual-element.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/create-visual-element.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4bc45bf2c505b42b52f367ecf0d49021cf6c859d --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/create-visual-element.mjs @@ -0,0 +1,14 @@ +import { Fragment } from 'react'; +import { HTMLVisualElement } from '../html/HTMLVisualElement.mjs'; +import { SVGVisualElement } from '../svg/SVGVisualElement.mjs'; +import { isSVGComponent } from './utils/is-svg-component.mjs'; + +const createDomVisualElement = (Component, options) => { + return isSVGComponent(Component) + ? new SVGVisualElement(options) + : new HTMLVisualElement(options, { + allowProjection: Component !== Fragment, + }); +}; + +export { createDomVisualElement }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/features-animation.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/features-animation.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3d1377db73c644b7f1d16a44c9abd553bae60766 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/features-animation.mjs @@ -0,0 +1,14 @@ +import { animations } from '../../motion/features/animations.mjs'; +import { gestureAnimations } from '../../motion/features/gestures.mjs'; +import { createDomVisualElement } from './create-visual-element.mjs'; + +/** + * @public + */ +const domAnimation = { + renderer: createDomVisualElement, + ...animations, + ...gestureAnimations, +}; + +export { domAnimation }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/features-max.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/features-max.mjs new file mode 100644 index 0000000000000000000000000000000000000000..46d792df5c75ef54ea7f43b234a2a4658ca70fcf --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/features-max.mjs @@ -0,0 +1,14 @@ +import { drag } from '../../motion/features/drag.mjs'; +import { layout } from '../../motion/features/layout.mjs'; +import { domAnimation } from './features-animation.mjs'; + +/** + * @public + */ +const domMax = { + ...domAnimation, + ...drag, + ...layout, +}; + +export { domMax }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/features-min.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/features-min.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c72a12ddd9a90635185569af408091771a8a794c --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/features-min.mjs @@ -0,0 +1,12 @@ +import { animations } from '../../motion/features/animations.mjs'; +import { createDomVisualElement } from './create-visual-element.mjs'; + +/** + * @public + */ +const domMin = { + renderer: createDomVisualElement, + ...animations, +}; + +export { domMin }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/attach-animation.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/attach-animation.mjs new file mode 100644 index 0000000000000000000000000000000000000000..87071605d064314cf3cb11a7cba9c89d34d7adde --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/attach-animation.mjs @@ -0,0 +1,17 @@ +import { observeTimeline } from 'motion-dom'; +import { getTimeline } from './utils/get-timeline.mjs'; + +function attachToAnimation(animation, options) { + const timeline = getTimeline(options); + return animation.attachTimeline({ + timeline: options.target ? undefined : timeline, + observe: (valueAnimation) => { + valueAnimation.pause(); + return observeTimeline((progress) => { + valueAnimation.time = valueAnimation.duration * progress; + }, timeline); + }, + }); +} + +export { attachToAnimation }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/attach-function.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/attach-function.mjs new file mode 100644 index 0000000000000000000000000000000000000000..698e9548d0a61698116fbeaa54b18d39f32d4f1e --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/attach-function.mjs @@ -0,0 +1,23 @@ +import { observeTimeline } from 'motion-dom'; +import { scrollInfo } from './track.mjs'; +import { getTimeline } from './utils/get-timeline.mjs'; + +/** + * If the onScroll function has two arguments, it's expecting + * more specific information about the scroll from scrollInfo. + */ +function isOnScrollWithInfo(onScroll) { + return onScroll.length === 2; +} +function attachToFunction(onScroll, options) { + if (isOnScrollWithInfo(onScroll)) { + return scrollInfo((info) => { + onScroll(info[options.axis].progress, info); + }, options); + } + else { + return observeTimeline(onScroll, getTimeline(options)); + } +} + +export { attachToFunction }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/index.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..008d6cd357d5776308229de955c98515fb59ac07 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/index.mjs @@ -0,0 +1,14 @@ +import { noop } from 'motion-utils'; +import { attachToAnimation } from './attach-animation.mjs'; +import { attachToFunction } from './attach-function.mjs'; + +function scroll(onScroll, { axis = "y", container = document.scrollingElement, ...options } = {}) { + if (!container) + return noop; + const optionsWithDefaults = { axis, container, ...options }; + return typeof onScroll === "function" + ? attachToFunction(onScroll, optionsWithDefaults) + : attachToAnimation(onScroll, optionsWithDefaults); +} + +export { scroll }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/info.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/info.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d199dbc7dec05278ae8624f70d4cf968486712c4 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/info.mjs @@ -0,0 +1,55 @@ +import { progress, velocityPerSecond } from 'motion-utils'; + +/** + * A time in milliseconds, beyond which we consider the scroll velocity to be 0. + */ +const maxElapsed = 50; +const createAxisInfo = () => ({ + current: 0, + offset: [], + progress: 0, + scrollLength: 0, + targetOffset: 0, + targetLength: 0, + containerLength: 0, + velocity: 0, +}); +const createScrollInfo = () => ({ + time: 0, + x: createAxisInfo(), + y: createAxisInfo(), +}); +const keys = { + x: { + length: "Width", + position: "Left", + }, + y: { + length: "Height", + position: "Top", + }, +}; +function updateAxisInfo(element, axisName, info, time) { + const axis = info[axisName]; + const { length, position } = keys[axisName]; + const prev = axis.current; + const prevTime = info.time; + axis.current = element[`scroll${position}`]; + axis.scrollLength = element[`scroll${length}`] - element[`client${length}`]; + axis.offset.length = 0; + axis.offset[0] = 0; + axis.offset[1] = axis.scrollLength; + axis.progress = progress(0, axis.scrollLength, axis.current); + const elapsed = time - prevTime; + axis.velocity = + elapsed > maxElapsed + ? 0 + : velocityPerSecond(axis.current - prev, elapsed); +} +function updateScrollInfo(element, info, time) { + updateAxisInfo(element, "x", info, time); + updateAxisInfo(element, "y", info, time); + info.time = time; +} + +export { createScrollInfo, updateScrollInfo }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/offsets/edge.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/offsets/edge.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9ac6bb2c1491ae6dea3a905555d2ce8d54567346 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/offsets/edge.mjs @@ -0,0 +1,45 @@ +const namedEdges = { + start: 0, + center: 0.5, + end: 1, +}; +function resolveEdge(edge, length, inset = 0) { + let delta = 0; + /** + * If we have this edge defined as a preset, replace the definition + * with the numerical value. + */ + if (edge in namedEdges) { + edge = namedEdges[edge]; + } + /** + * Handle unit values + */ + if (typeof edge === "string") { + const asNumber = parseFloat(edge); + if (edge.endsWith("px")) { + delta = asNumber; + } + else if (edge.endsWith("%")) { + edge = asNumber / 100; + } + else if (edge.endsWith("vw")) { + delta = (asNumber / 100) * document.documentElement.clientWidth; + } + else if (edge.endsWith("vh")) { + delta = (asNumber / 100) * document.documentElement.clientHeight; + } + else { + edge = asNumber; + } + } + /** + * If the edge is defined as a number, handle as a progress value. + */ + if (typeof edge === "number") { + delta = length * edge; + } + return inset + delta; +} + +export { namedEdges, resolveEdge }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/offsets/index.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/offsets/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9576fa09fd36abfc88be2cb4dfe6c5322094baec --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/offsets/index.mjs @@ -0,0 +1,59 @@ +import { interpolate, defaultOffset } from 'motion-dom'; +import { clamp } from 'motion-utils'; +import { calcInset } from './inset.mjs'; +import { resolveOffset } from './offset.mjs'; +import { ScrollOffset } from './presets.mjs'; + +const point = { x: 0, y: 0 }; +function getTargetSize(target) { + return "getBBox" in target && target.tagName !== "svg" + ? target.getBBox() + : { width: target.clientWidth, height: target.clientHeight }; +} +function resolveOffsets(container, info, options) { + const { offset: offsetDefinition = ScrollOffset.All } = options; + const { target = container, axis = "y" } = options; + const lengthLabel = axis === "y" ? "height" : "width"; + const inset = target !== container ? calcInset(target, container) : point; + /** + * Measure the target and container. If they're the same thing then we + * use the container's scrollWidth/Height as the target, from there + * all other calculations can remain the same. + */ + const targetSize = target === container + ? { width: container.scrollWidth, height: container.scrollHeight } + : getTargetSize(target); + const containerSize = { + width: container.clientWidth, + height: container.clientHeight, + }; + /** + * Reset the length of the resolved offset array rather than creating a new one. + * TODO: More reusable data structures for targetSize/containerSize would also be good. + */ + info[axis].offset.length = 0; + /** + * Populate the offset array by resolving the user's offset definition into + * a list of pixel scroll offets. + */ + let hasChanged = !info[axis].interpolate; + const numOffsets = offsetDefinition.length; + for (let i = 0; i < numOffsets; i++) { + const offset = resolveOffset(offsetDefinition[i], containerSize[lengthLabel], targetSize[lengthLabel], inset[axis]); + if (!hasChanged && offset !== info[axis].interpolatorOffsets[i]) { + hasChanged = true; + } + info[axis].offset[i] = offset; + } + /** + * If the pixel scroll offsets have changed, create a new interpolator function + * to map scroll value into a progress. + */ + if (hasChanged) { + info[axis].interpolate = interpolate(info[axis].offset, defaultOffset(offsetDefinition), { clamp: false }); + info[axis].interpolatorOffsets = [...info[axis].offset]; + } + info[axis].progress = clamp(0, 1, info[axis].interpolate(info[axis].current)); +} + +export { resolveOffsets }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/offsets/inset.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/offsets/inset.mjs new file mode 100644 index 0000000000000000000000000000000000000000..70e8315b85cc7285df513eb18971da4d64eb6fa8 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/offsets/inset.mjs @@ -0,0 +1,47 @@ +import { isHTMLElement } from 'motion-dom'; + +function calcInset(element, container) { + const inset = { x: 0, y: 0 }; + let current = element; + while (current && current !== container) { + if (isHTMLElement(current)) { + inset.x += current.offsetLeft; + inset.y += current.offsetTop; + current = current.offsetParent; + } + else if (current.tagName === "svg") { + /** + * This isn't an ideal approach to measuring the offset of tags. + * It would be preferable, given they behave like HTMLElements in most ways + * to use offsetLeft/Top. But these don't exist on . Likewise we + * can't use .getBBox() like most SVG elements as these provide the offset + * relative to the SVG itself, which for is usually 0x0. + */ + const svgBoundingBox = current.getBoundingClientRect(); + current = current.parentElement; + const parentBoundingBox = current.getBoundingClientRect(); + inset.x += svgBoundingBox.left - parentBoundingBox.left; + inset.y += svgBoundingBox.top - parentBoundingBox.top; + } + else if (current instanceof SVGGraphicsElement) { + const { x, y } = current.getBBox(); + inset.x += x; + inset.y += y; + let svg = null; + let parent = current.parentNode; + while (!svg) { + if (parent.tagName === "svg") { + svg = parent; + } + parent = current.parentNode; + } + current = svg; + } + else { + break; + } + } + return inset; +} + +export { calcInset }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/offsets/offset.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/offsets/offset.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3d4256f69444be74ba5c89b561d6d662e31baeff --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/offsets/offset.mjs @@ -0,0 +1,35 @@ +import { resolveEdge, namedEdges } from './edge.mjs'; + +const defaultOffset = [0, 0]; +function resolveOffset(offset, containerLength, targetLength, targetInset) { + let offsetDefinition = Array.isArray(offset) ? offset : defaultOffset; + let targetPoint = 0; + let containerPoint = 0; + if (typeof offset === "number") { + /** + * If we're provided offset: [0, 0.5, 1] then each number x should become + * [x, x], so we default to the behaviour of mapping 0 => 0 of both target + * and container etc. + */ + offsetDefinition = [offset, offset]; + } + else if (typeof offset === "string") { + offset = offset.trim(); + if (offset.includes(" ")) { + offsetDefinition = offset.split(" "); + } + else { + /** + * If we're provided a definition like "100px" then we want to apply + * that only to the top of the target point, leaving the container at 0. + * Whereas a named offset like "end" should be applied to both. + */ + offsetDefinition = [offset, namedEdges[offset] ? offset : `0`]; + } + } + targetPoint = resolveEdge(offsetDefinition[0], targetLength, targetInset); + containerPoint = resolveEdge(offsetDefinition[1], containerLength); + return targetPoint - containerPoint; +} + +export { resolveOffset }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/offsets/presets.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/offsets/presets.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6759ebba299e5889e9ed433a630aa15a84b87ef6 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/offsets/presets.mjs @@ -0,0 +1,20 @@ +const ScrollOffset = { + Enter: [ + [0, 1], + [1, 1], + ], + Exit: [ + [0, 0], + [1, 0], + ], + Any: [ + [1, 0], + [0, 1], + ], + All: [ + [0, 0], + [1, 1], + ], +}; + +export { ScrollOffset }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/on-scroll-handler.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/on-scroll-handler.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6053f1a0463bf99d5636643bab53fbd3a83c3973 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/on-scroll-handler.mjs @@ -0,0 +1,48 @@ +import { warnOnce } from 'motion-utils'; +import { updateScrollInfo } from './info.mjs'; +import { resolveOffsets } from './offsets/index.mjs'; + +function measure(container, target = container, info) { + /** + * Find inset of target within scrollable container + */ + info.x.targetOffset = 0; + info.y.targetOffset = 0; + if (target !== container) { + let node = target; + while (node && node !== container) { + info.x.targetOffset += node.offsetLeft; + info.y.targetOffset += node.offsetTop; + node = node.offsetParent; + } + } + info.x.targetLength = + target === container ? target.scrollWidth : target.clientWidth; + info.y.targetLength = + target === container ? target.scrollHeight : target.clientHeight; + info.x.containerLength = container.clientWidth; + info.y.containerLength = container.clientHeight; + /** + * In development mode ensure scroll containers aren't position: static as this makes + * it difficult to measure their relative positions. + */ + if (process.env.NODE_ENV !== "production") { + if (container && target && target !== container) { + warnOnce(getComputedStyle(container).position !== "static", "Please ensure that the container has a non-static position, like 'relative', 'fixed', or 'absolute' to ensure scroll offset is calculated correctly."); + } + } +} +function createOnScrollHandler(element, onScroll, info, options = {}) { + return { + measure: (time) => { + measure(element, options.target, info); + updateScrollInfo(element, info, time); + if (options.offset || options.target) { + resolveOffsets(element, info, options); + } + }, + notify: () => onScroll(info), + }; +} + +export { createOnScrollHandler }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/track.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/track.mjs new file mode 100644 index 0000000000000000000000000000000000000000..be20ac63bdbf28c54bec5bec4f151e2872b501a5 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/track.mjs @@ -0,0 +1,80 @@ +import { resize, frame, cancelFrame, frameData } from 'motion-dom'; +import { noop } from 'motion-utils'; +import { createScrollInfo } from './info.mjs'; +import { createOnScrollHandler } from './on-scroll-handler.mjs'; + +const scrollListeners = new WeakMap(); +const resizeListeners = new WeakMap(); +const onScrollHandlers = new WeakMap(); +const getEventTarget = (element) => element === document.scrollingElement ? window : element; +function scrollInfo(onScroll, { container = document.scrollingElement, ...options } = {}) { + if (!container) + return noop; + let containerHandlers = onScrollHandlers.get(container); + /** + * Get the onScroll handlers for this container. + * If one isn't found, create a new one. + */ + if (!containerHandlers) { + containerHandlers = new Set(); + onScrollHandlers.set(container, containerHandlers); + } + /** + * Create a new onScroll handler for the provided callback. + */ + const info = createScrollInfo(); + const containerHandler = createOnScrollHandler(container, onScroll, info, options); + containerHandlers.add(containerHandler); + /** + * Check if there's a scroll event listener for this container. + * If not, create one. + */ + if (!scrollListeners.has(container)) { + const measureAll = () => { + for (const handler of containerHandlers) { + handler.measure(frameData.timestamp); + } + frame.preUpdate(notifyAll); + }; + const notifyAll = () => { + for (const handler of containerHandlers) { + handler.notify(); + } + }; + const listener = () => frame.read(measureAll); + scrollListeners.set(container, listener); + const target = getEventTarget(container); + window.addEventListener("resize", listener, { passive: true }); + if (container !== document.documentElement) { + resizeListeners.set(container, resize(container, listener)); + } + target.addEventListener("scroll", listener, { passive: true }); + listener(); + } + const listener = scrollListeners.get(container); + frame.read(listener, false, true); + return () => { + cancelFrame(listener); + /** + * Check if we even have any handlers for this container. + */ + const currentHandlers = onScrollHandlers.get(container); + if (!currentHandlers) + return; + currentHandlers.delete(containerHandler); + if (currentHandlers.size) + return; + /** + * If no more handlers, remove the scroll listener too. + */ + const scrollListener = scrollListeners.get(container); + scrollListeners.delete(container); + if (scrollListener) { + getEventTarget(container).removeEventListener("scroll", scrollListener); + resizeListeners.get(container)?.(); + window.removeEventListener("resize", scrollListener); + } + }; +} + +export { scrollInfo }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/utils/get-timeline.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/utils/get-timeline.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b7702124328796ba69eb59d6946f0d1d759c400d --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/scroll/utils/get-timeline.mjs @@ -0,0 +1,30 @@ +import { supportsScrollTimeline } from 'motion-dom'; +import { scrollInfo } from '../track.mjs'; + +const timelineCache = new Map(); +function scrollTimelineFallback(options) { + const currentTime = { value: 0 }; + const cancel = scrollInfo((info) => { + currentTime.value = info[options.axis].progress * 100; + }, options); + return { currentTime, cancel }; +} +function getTimeline({ source, container, ...options }) { + const { axis } = options; + if (source) + container = source; + const containerCache = timelineCache.get(container) ?? new Map(); + timelineCache.set(container, containerCache); + const targetKey = options.target ?? "self"; + const targetCache = containerCache.get(targetKey) ?? {}; + const axisKey = axis + (options.offset ?? []).join(","); + if (!targetCache[axisKey]) { + targetCache[axisKey] = + !options.target && supportsScrollTimeline() + ? new ScrollTimeline({ source: container, axis }) + : scrollTimelineFallback({ container, ...options }); + } + return targetCache[axisKey]; +} + +export { getTimeline }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/use-render.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/use-render.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5ff1030ef3fa6e073fdaf9a77175d0e106a6bd48 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/use-render.mjs @@ -0,0 +1,28 @@ +import { isMotionValue } from 'motion-dom'; +import { Fragment, useMemo, createElement } from 'react'; +import { useHTMLProps } from '../html/use-props.mjs'; +import { useSVGProps } from '../svg/use-props.mjs'; +import { filterProps } from './utils/filter-props.mjs'; +import { isSVGComponent } from './utils/is-svg-component.mjs'; + +function useRender(Component, props, ref, { latestValues, }, isStatic, forwardMotionProps = false) { + const useVisualProps = isSVGComponent(Component) + ? useSVGProps + : useHTMLProps; + const visualProps = useVisualProps(props, latestValues, isStatic, Component); + const filteredProps = filterProps(props, typeof Component === "string", forwardMotionProps); + const elementProps = Component !== Fragment ? { ...filteredProps, ...visualProps, ref } : {}; + /** + * If component has been handed a motion value as its child, + * memoise its initial value and render that. Subsequent updates + * will be handled by the onChange handler + */ + const { children } = props; + const renderedChildren = useMemo(() => (isMotionValue(children) ? children.get() : children), [children]); + return createElement(Component, { + ...elementProps, + children: renderedChildren, + }); +} + +export { useRender }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/utils/camel-to-dash.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/utils/camel-to-dash.mjs new file mode 100644 index 0000000000000000000000000000000000000000..436d5ab5ffaeceec80017c3d479d3abdbffda721 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/utils/camel-to-dash.mjs @@ -0,0 +1,6 @@ +/** + * Convert camelCase to dash-case properties. + */ +const camelToDash = (str) => str.replace(/([a-z])([A-Z])/gu, "$1-$2").toLowerCase(); + +export { camelToDash }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/utils/filter-props.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/utils/filter-props.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d9f461fa89730fa00d799333bb3ff4dcb7f59cd9 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/utils/filter-props.mjs @@ -0,0 +1,59 @@ +import { isValidMotionProp } from '../../../motion/utils/valid-prop.mjs'; + +let shouldForward = (key) => !isValidMotionProp(key); +function loadExternalIsValidProp(isValidProp) { + if (typeof isValidProp !== "function") + return; + // Explicitly filter our events + shouldForward = (key) => key.startsWith("on") ? !isValidMotionProp(key) : isValidProp(key); +} +/** + * Emotion and Styled Components both allow users to pass through arbitrary props to their components + * to dynamically generate CSS. They both use the `@emotion/is-prop-valid` package to determine which + * of these should be passed to the underlying DOM node. + * + * However, when styling a Motion component `styled(motion.div)`, both packages pass through *all* props + * as it's seen as an arbitrary component rather than a DOM node. Motion only allows arbitrary props + * passed through the `custom` prop so it doesn't *need* the payload or computational overhead of + * `@emotion/is-prop-valid`, however to fix this problem we need to use it. + * + * By making it an optionalDependency we can offer this functionality only in the situations where it's + * actually required. + */ +try { + /** + * We attempt to import this package but require won't be defined in esm environments, in that case + * isPropValid will have to be provided via `MotionContext`. In a 6.0.0 this should probably be removed + * in favour of explicit injection. + */ + loadExternalIsValidProp(require("@emotion/is-prop-valid").default); +} +catch { + // We don't need to actually do anything here - the fallback is the existing `isPropValid`. +} +function filterProps(props, isDom, forwardMotionProps) { + const filteredProps = {}; + for (const key in props) { + /** + * values is considered a valid prop by Emotion, so if it's present + * this will be rendered out to the DOM unless explicitly filtered. + * + * We check the type as it could be used with the `feColorMatrix` + * element, which we support. + */ + if (key === "values" && typeof props.values === "object") + continue; + if (shouldForward(key) || + (forwardMotionProps === true && isValidMotionProp(key)) || + (!isDom && !isValidMotionProp(key)) || + // If trying to use native HTML drag events, forward drag listeners + (props["draggable"] && + key.startsWith("onDrag"))) { + filteredProps[key] = + props[key]; + } + } + return filteredProps; +} + +export { filterProps, loadExternalIsValidProp }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/utils/is-svg-component.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/utils/is-svg-component.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3ed31f3cc98c77a4e7a949dc4e0be62d8b5c5653 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/utils/is-svg-component.mjs @@ -0,0 +1,30 @@ +import { lowercaseSVGElements } from '../../svg/lowercase-elements.mjs'; + +function isSVGComponent(Component) { + if ( + /** + * If it's not a string, it's a custom React component. Currently we only support + * HTML custom React components. + */ + typeof Component !== "string" || + /** + * If it contains a dash, the element is a custom HTML webcomponent. + */ + Component.includes("-")) { + return false; + } + else if ( + /** + * If it's in our list of lowercase SVG tags, it's an SVG component + */ + lowercaseSVGElements.indexOf(Component) > -1 || + /** + * If it contains a capital letter, it's an SVG component + */ + /[A-Z]/u.test(Component)) { + return true; + } + return false; +} + +export { isSVGComponent }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/dom/viewport/index.mjs b/frontend/node_modules/framer-motion/dist/es/render/dom/viewport/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ca226c14977caf75dbb60de859c1fa5fb2d46eb9 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/dom/viewport/index.mjs @@ -0,0 +1,43 @@ +import { resolveElements } from 'motion-dom'; + +const thresholds = { + some: 0, + all: 1, +}; +function inView(elementOrSelector, onStart, { root, margin: rootMargin, amount = "some" } = {}) { + const elements = resolveElements(elementOrSelector); + const activeIntersections = new WeakMap(); + const onIntersectionChange = (entries) => { + entries.forEach((entry) => { + const onEnd = activeIntersections.get(entry.target); + /** + * If there's no change to the intersection, we don't need to + * do anything here. + */ + if (entry.isIntersecting === Boolean(onEnd)) + return; + if (entry.isIntersecting) { + const newOnEnd = onStart(entry.target, entry); + if (typeof newOnEnd === "function") { + activeIntersections.set(entry.target, newOnEnd); + } + else { + observer.unobserve(entry.target); + } + } + else if (typeof onEnd === "function") { + onEnd(entry); + activeIntersections.delete(entry.target); + } + }); + }; + const observer = new IntersectionObserver(onIntersectionChange, { + root, + rootMargin, + threshold: typeof amount === "number" ? amount : thresholds[amount], + }); + elements.forEach((element) => observer.observe(element)); + return () => observer.disconnect(); +} + +export { inView }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/html/HTMLVisualElement.mjs b/frontend/node_modules/framer-motion/dist/es/render/html/HTMLVisualElement.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4720f231a725c552c6f73c185a66c8eb0c3d0cb1 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/html/HTMLVisualElement.mjs @@ -0,0 +1,42 @@ +import { transformProps, defaultTransformValue, readTransformValue, isCSSVariableName } from 'motion-dom'; +import { measureViewportBox } from '../../projection/utils/measure.mjs'; +import { DOMVisualElement } from '../dom/DOMVisualElement.mjs'; +import { buildHTMLStyles } from './utils/build-styles.mjs'; +import { renderHTML } from './utils/render.mjs'; +import { scrapeMotionValuesFromProps } from './utils/scrape-motion-values.mjs'; + +function getComputedStyle(element) { + return window.getComputedStyle(element); +} +class HTMLVisualElement extends DOMVisualElement { + constructor() { + super(...arguments); + this.type = "html"; + this.renderInstance = renderHTML; + } + readValueFromInstance(instance, key) { + if (transformProps.has(key)) { + return this.projection?.isProjecting + ? defaultTransformValue(key) + : readTransformValue(instance, key); + } + else { + const computedStyle = getComputedStyle(instance); + const value = (isCSSVariableName(key) + ? computedStyle.getPropertyValue(key) + : computedStyle[key]) || 0; + return typeof value === "string" ? value.trim() : value; + } + } + measureInstanceViewportBox(instance, { transformPagePoint }) { + return measureViewportBox(instance, transformPagePoint); + } + build(renderState, latestValues, props) { + buildHTMLStyles(renderState, latestValues, props.transformTemplate); + } + scrapeMotionValuesFromProps(props, prevProps, visualElement) { + return scrapeMotionValuesFromProps(props, prevProps, visualElement); + } +} + +export { HTMLVisualElement, getComputedStyle }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/html/use-html-visual-state.mjs b/frontend/node_modules/framer-motion/dist/es/render/html/use-html-visual-state.mjs new file mode 100644 index 0000000000000000000000000000000000000000..74fbb2541e5e54f7d521eaf022f51c022461dacb --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/html/use-html-visual-state.mjs @@ -0,0 +1,10 @@ +import { makeUseVisualState } from '../../motion/utils/use-visual-state.mjs'; +import { createHtmlRenderState } from './utils/create-render-state.mjs'; +import { scrapeMotionValuesFromProps } from './utils/scrape-motion-values.mjs'; + +const useHTMLVisualState = /*@__PURE__*/ makeUseVisualState({ + scrapeMotionValuesFromProps, + createRenderState: createHtmlRenderState, +}); + +export { useHTMLVisualState }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/html/use-props.mjs b/frontend/node_modules/framer-motion/dist/es/render/html/use-props.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3ddafbe6a4478e47de61bdcf89aa896365a7ddaf --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/html/use-props.mjs @@ -0,0 +1,57 @@ +import { isMotionValue } from 'motion-dom'; +import { useMemo } from 'react'; +import { isForcedMotionValue } from '../../motion/utils/is-forced-motion-value.mjs'; +import { buildHTMLStyles } from './utils/build-styles.mjs'; +import { createHtmlRenderState } from './utils/create-render-state.mjs'; + +function copyRawValuesOnly(target, source, props) { + for (const key in source) { + if (!isMotionValue(source[key]) && !isForcedMotionValue(key, props)) { + target[key] = source[key]; + } + } +} +function useInitialMotionValues({ transformTemplate }, visualState) { + return useMemo(() => { + const state = createHtmlRenderState(); + buildHTMLStyles(state, visualState, transformTemplate); + return Object.assign({}, state.vars, state.style); + }, [visualState]); +} +function useStyle(props, visualState) { + const styleProp = props.style || {}; + const style = {}; + /** + * Copy non-Motion Values straight into style + */ + copyRawValuesOnly(style, styleProp, props); + Object.assign(style, useInitialMotionValues(props, visualState)); + return style; +} +function useHTMLProps(props, visualState) { + // The `any` isn't ideal but it is the type of createElement props argument + const htmlProps = {}; + const style = useStyle(props, visualState); + if (props.drag && props.dragListener !== false) { + // Disable the ghost element when a user drags + htmlProps.draggable = false; + // Disable text selection + style.userSelect = + style.WebkitUserSelect = + style.WebkitTouchCallout = + "none"; + // Disable scrolling on the draggable direction + style.touchAction = + props.drag === true + ? "none" + : `pan-${props.drag === "x" ? "y" : "x"}`; + } + if (props.tabIndex === undefined && + (props.onTap || props.onTapStart || props.whileTap)) { + htmlProps.tabIndex = 0; + } + htmlProps.style = style; + return htmlProps; +} + +export { copyRawValuesOnly, useHTMLProps }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/html/utils/build-styles.mjs b/frontend/node_modules/framer-motion/dist/es/render/html/utils/build-styles.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6537d619b86ae5428888597875fc6dfdb31a4195 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/html/utils/build-styles.mjs @@ -0,0 +1,62 @@ +import { transformProps, isCSSVariableName, getValueAsType, numberValueTypes } from 'motion-dom'; +import { buildTransform } from './build-transform.mjs'; + +function buildHTMLStyles(state, latestValues, transformTemplate) { + const { style, vars, transformOrigin } = state; + // Track whether we encounter any transform or transformOrigin values. + let hasTransform = false; + let hasTransformOrigin = false; + /** + * Loop over all our latest animated values and decide whether to handle them + * as a style or CSS variable. + * + * Transforms and transform origins are kept separately for further processing. + */ + for (const key in latestValues) { + const value = latestValues[key]; + if (transformProps.has(key)) { + // If this is a transform, flag to enable further transform processing + hasTransform = true; + continue; + } + else if (isCSSVariableName(key)) { + vars[key] = value; + continue; + } + else { + // Convert the value to its default value type, ie 0 -> "0px" + const valueAsType = getValueAsType(value, numberValueTypes[key]); + if (key.startsWith("origin")) { + // If this is a transform origin, flag and enable further transform-origin processing + hasTransformOrigin = true; + transformOrigin[key] = + valueAsType; + } + else { + style[key] = valueAsType; + } + } + } + if (!latestValues.transform) { + if (hasTransform || transformTemplate) { + style.transform = buildTransform(latestValues, state.transform, transformTemplate); + } + else if (style.transform) { + /** + * If we have previously created a transform but currently don't have any, + * reset transform style to none. + */ + style.transform = "none"; + } + } + /** + * Build a transformOrigin style. Uses the same defaults as the browser for + * undefined origins. + */ + if (hasTransformOrigin) { + const { originX = "50%", originY = "50%", originZ = 0, } = transformOrigin; + style.transformOrigin = `${originX} ${originY} ${originZ}`; + } +} + +export { buildHTMLStyles }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/html/utils/build-transform.mjs b/frontend/node_modules/framer-motion/dist/es/render/html/utils/build-transform.mjs new file mode 100644 index 0000000000000000000000000000000000000000..508b9a4cb72a6fdfd9bce6f7254b0080226f08ec --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/html/utils/build-transform.mjs @@ -0,0 +1,60 @@ +import { transformPropOrder, getValueAsType, numberValueTypes } from 'motion-dom'; + +const translateAlias = { + x: "translateX", + y: "translateY", + z: "translateZ", + transformPerspective: "perspective", +}; +const numTransforms = transformPropOrder.length; +/** + * Build a CSS transform style from individual x/y/scale etc properties. + * + * This outputs with a default order of transforms/scales/rotations, this can be customised by + * providing a transformTemplate function. + */ +function buildTransform(latestValues, transform, transformTemplate) { + // The transform string we're going to build into. + let transformString = ""; + let transformIsDefault = true; + /** + * Loop over all possible transforms in order, adding the ones that + * are present to the transform string. + */ + for (let i = 0; i < numTransforms; i++) { + const key = transformPropOrder[i]; + const value = latestValues[key]; + if (value === undefined) + continue; + let valueIsDefault = true; + if (typeof value === "number") { + valueIsDefault = value === (key.startsWith("scale") ? 1 : 0); + } + else { + valueIsDefault = parseFloat(value) === 0; + } + if (!valueIsDefault || transformTemplate) { + const valueAsType = getValueAsType(value, numberValueTypes[key]); + if (!valueIsDefault) { + transformIsDefault = false; + const transformName = translateAlias[key] || key; + transformString += `${transformName}(${valueAsType}) `; + } + if (transformTemplate) { + transform[key] = valueAsType; + } + } + } + transformString = transformString.trim(); + // If we have a custom `transform` template, pass our transform values and + // generated transformString to that before returning + if (transformTemplate) { + transformString = transformTemplate(transform, transformIsDefault ? "" : transformString); + } + else if (transformIsDefault) { + transformString = "none"; + } + return transformString; +} + +export { buildTransform }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/html/utils/create-render-state.mjs b/frontend/node_modules/framer-motion/dist/es/render/html/utils/create-render-state.mjs new file mode 100644 index 0000000000000000000000000000000000000000..39441be6ca66255ed03c17022a660d2ed1a87f22 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/html/utils/create-render-state.mjs @@ -0,0 +1,8 @@ +const createHtmlRenderState = () => ({ + style: {}, + transform: {}, + transformOrigin: {}, + vars: {}, +}); + +export { createHtmlRenderState }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/html/utils/render.mjs b/frontend/node_modules/framer-motion/dist/es/render/html/utils/render.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0fe5d8082819360608ca015b8076bb118482e92e --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/html/utils/render.mjs @@ -0,0 +1,17 @@ +function renderHTML(element, { style, vars }, styleProp, projection) { + const elementStyle = element.style; + let key; + for (key in style) { + // CSSStyleDeclaration has [index: number]: string; in the types, so we use that as key type. + elementStyle[key] = style[key]; + } + // Write projection styles directly to element style + projection?.applyProjectionStyles(elementStyle, styleProp); + for (key in vars) { + // Loop over any CSS variables and assign those. + // They can only be assigned using `setProperty`. + elementStyle.setProperty(key, vars[key]); + } +} + +export { renderHTML }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/html/utils/scrape-motion-values.mjs b/frontend/node_modules/framer-motion/dist/es/render/html/utils/scrape-motion-values.mjs new file mode 100644 index 0000000000000000000000000000000000000000..447dea1e346a497a38987224a6cee55683f8ebe2 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/html/utils/scrape-motion-values.mjs @@ -0,0 +1,19 @@ +import { isMotionValue } from 'motion-dom'; +import { isForcedMotionValue } from '../../../motion/utils/is-forced-motion-value.mjs'; + +function scrapeMotionValuesFromProps(props, prevProps, visualElement) { + const { style } = props; + const newValues = {}; + for (const key in style) { + if (isMotionValue(style[key]) || + (prevProps.style && + isMotionValue(prevProps.style[key])) || + isForcedMotionValue(key, props) || + visualElement?.getValue(key)?.liveStyle !== undefined) { + newValues[key] = style[key]; + } + } + return newValues; +} + +export { scrapeMotionValuesFromProps }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/object/ObjectVisualElement.mjs b/frontend/node_modules/framer-motion/dist/es/render/object/ObjectVisualElement.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bf46724813ab179003a4e1841b915403e55674a6 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/object/ObjectVisualElement.mjs @@ -0,0 +1,41 @@ +import { createBox } from '../../projection/geometry/models.mjs'; +import { VisualElement } from '../VisualElement.mjs'; + +function isObjectKey(key, object) { + return key in object; +} +class ObjectVisualElement extends VisualElement { + constructor() { + super(...arguments); + this.type = "object"; + } + readValueFromInstance(instance, key) { + if (isObjectKey(key, instance)) { + const value = instance[key]; + if (typeof value === "string" || typeof value === "number") { + return value; + } + } + return undefined; + } + getBaseTargetFromProps() { + return undefined; + } + removeValueFromRenderState(key, renderState) { + delete renderState.output[key]; + } + measureInstanceViewportBox() { + return createBox(); + } + build(renderState, latestValues) { + Object.assign(renderState.output, latestValues); + } + renderInstance(instance, { output }) { + Object.assign(instance, output); + } + sortInstanceNodePosition() { + return 0; + } +} + +export { ObjectVisualElement }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/store.mjs b/frontend/node_modules/framer-motion/dist/es/render/store.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c94c04b3fba24bfd111be6680f8f0f185d32f68e --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/store.mjs @@ -0,0 +1,3 @@ +const visualElementStore = new WeakMap(); + +export { visualElementStore }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/svg/SVGVisualElement.mjs b/frontend/node_modules/framer-motion/dist/es/render/svg/SVGVisualElement.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f7d24e9d4d4b7bd3d32fc77a63e9748cd0160c09 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/svg/SVGVisualElement.mjs @@ -0,0 +1,44 @@ +import { transformProps, getDefaultValueType } from 'motion-dom'; +import { createBox } from '../../projection/geometry/models.mjs'; +import { DOMVisualElement } from '../dom/DOMVisualElement.mjs'; +import { camelToDash } from '../dom/utils/camel-to-dash.mjs'; +import { buildSVGAttrs } from './utils/build-attrs.mjs'; +import { camelCaseAttributes } from './utils/camel-case-attrs.mjs'; +import { isSVGTag } from './utils/is-svg-tag.mjs'; +import { renderSVG } from './utils/render.mjs'; +import { scrapeMotionValuesFromProps } from './utils/scrape-motion-values.mjs'; + +class SVGVisualElement extends DOMVisualElement { + constructor() { + super(...arguments); + this.type = "svg"; + this.isSVGTag = false; + this.measureInstanceViewportBox = createBox; + } + getBaseTargetFromProps(props, key) { + return props[key]; + } + readValueFromInstance(instance, key) { + if (transformProps.has(key)) { + const defaultType = getDefaultValueType(key); + return defaultType ? defaultType.default || 0 : 0; + } + key = !camelCaseAttributes.has(key) ? camelToDash(key) : key; + return instance.getAttribute(key); + } + scrapeMotionValuesFromProps(props, prevProps, visualElement) { + return scrapeMotionValuesFromProps(props, prevProps, visualElement); + } + build(renderState, latestValues, props) { + buildSVGAttrs(renderState, latestValues, this.isSVGTag, props.transformTemplate, props.style); + } + renderInstance(instance, renderState, styleProp, projection) { + renderSVG(instance, renderState, styleProp, projection); + } + mount(instance) { + this.isSVGTag = isSVGTag(instance.tagName); + super.mount(instance); + } +} + +export { SVGVisualElement }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/svg/lowercase-elements.mjs b/frontend/node_modules/framer-motion/dist/es/render/svg/lowercase-elements.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5435c644f96988eaffa3442ad9a905456d3cb288 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/svg/lowercase-elements.mjs @@ -0,0 +1,33 @@ +/** + * We keep these listed separately as we use the lowercase tag names as part + * of the runtime bundle to detect SVG components + */ +const lowercaseSVGElements = [ + "animate", + "circle", + "defs", + "desc", + "ellipse", + "g", + "image", + "line", + "filter", + "marker", + "mask", + "metadata", + "path", + "pattern", + "polygon", + "polyline", + "rect", + "stop", + "switch", + "symbol", + "svg", + "text", + "tspan", + "use", + "view", +]; + +export { lowercaseSVGElements }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/svg/use-props.mjs b/frontend/node_modules/framer-motion/dist/es/render/svg/use-props.mjs new file mode 100644 index 0000000000000000000000000000000000000000..669baf9159eebe891bdad6da81a494bf328f5ad8 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/svg/use-props.mjs @@ -0,0 +1,24 @@ +import { useMemo } from 'react'; +import { copyRawValuesOnly } from '../html/use-props.mjs'; +import { buildSVGAttrs } from './utils/build-attrs.mjs'; +import { createSvgRenderState } from './utils/create-render-state.mjs'; +import { isSVGTag } from './utils/is-svg-tag.mjs'; + +function useSVGProps(props, visualState, _isStatic, Component) { + const visualProps = useMemo(() => { + const state = createSvgRenderState(); + buildSVGAttrs(state, visualState, isSVGTag(Component), props.transformTemplate, props.style); + return { + ...state.attrs, + style: { ...state.style }, + }; + }, [visualState]); + if (props.style) { + const rawStyles = {}; + copyRawValuesOnly(rawStyles, props.style, props); + visualProps.style = { ...rawStyles, ...visualProps.style }; + } + return visualProps; +} + +export { useSVGProps }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/svg/use-svg-visual-state.mjs b/frontend/node_modules/framer-motion/dist/es/render/svg/use-svg-visual-state.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d272aaf13450961311edf5d58529898c79f7414d --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/svg/use-svg-visual-state.mjs @@ -0,0 +1,10 @@ +import { makeUseVisualState } from '../../motion/utils/use-visual-state.mjs'; +import { createSvgRenderState } from './utils/create-render-state.mjs'; +import { scrapeMotionValuesFromProps } from './utils/scrape-motion-values.mjs'; + +const useSVGVisualState = /*@__PURE__*/ makeUseVisualState({ + scrapeMotionValuesFromProps: scrapeMotionValuesFromProps, + createRenderState: createSvgRenderState, +}); + +export { useSVGVisualState }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/svg/utils/build-attrs.mjs b/frontend/node_modules/framer-motion/dist/es/render/svg/utils/build-attrs.mjs new file mode 100644 index 0000000000000000000000000000000000000000..91c98b0dc12577740315df9c59cc0cd500be8119 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/svg/utils/build-attrs.mjs @@ -0,0 +1,57 @@ +import { buildHTMLStyles } from '../../html/utils/build-styles.mjs'; +import { buildSVGPath } from './path.mjs'; + +/** + * Build SVG visual attributes, like cx and style.transform + */ +function buildSVGAttrs(state, { attrX, attrY, attrScale, pathLength, pathSpacing = 1, pathOffset = 0, +// This is object creation, which we try to avoid per-frame. +...latest }, isSVGTag, transformTemplate, styleProp) { + buildHTMLStyles(state, latest, transformTemplate); + /** + * For svg tags we just want to make sure viewBox is animatable and treat all the styles + * as normal HTML tags. + */ + if (isSVGTag) { + if (state.style.viewBox) { + state.attrs.viewBox = state.style.viewBox; + } + return; + } + state.attrs = state.style; + state.style = {}; + const { attrs, style } = state; + /** + * However, we apply transforms as CSS transforms. + * So if we detect a transform, transformOrigin we take it from attrs and copy it into style. + */ + if (attrs.transform) { + style.transform = attrs.transform; + delete attrs.transform; + } + if (style.transform || attrs.transformOrigin) { + style.transformOrigin = attrs.transformOrigin ?? "50% 50%"; + delete attrs.transformOrigin; + } + if (style.transform) { + /** + * SVG's element transform-origin uses its own median as a reference. + * Therefore, transformBox becomes a fill-box + */ + style.transformBox = styleProp?.transformBox ?? "fill-box"; + delete attrs.transformBox; + } + // Render attrX/attrY/attrScale as attributes + if (attrX !== undefined) + attrs.x = attrX; + if (attrY !== undefined) + attrs.y = attrY; + if (attrScale !== undefined) + attrs.scale = attrScale; + // Build SVG path if one has been defined + if (pathLength !== undefined) { + buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false); + } +} + +export { buildSVGAttrs }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/svg/utils/camel-case-attrs.mjs b/frontend/node_modules/framer-motion/dist/es/render/svg/utils/camel-case-attrs.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4158b5350044a33362edf7c436e4a769ac468a78 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/svg/utils/camel-case-attrs.mjs @@ -0,0 +1,30 @@ +/** + * A set of attribute names that are always read/written as camel case. + */ +const camelCaseAttributes = new Set([ + "baseFrequency", + "diffuseConstant", + "kernelMatrix", + "kernelUnitLength", + "keySplines", + "keyTimes", + "limitingConeAngle", + "markerHeight", + "markerWidth", + "numOctaves", + "targetX", + "targetY", + "surfaceScale", + "specularConstant", + "specularExponent", + "stdDeviation", + "tableValues", + "viewBox", + "gradientTransform", + "pathLength", + "startOffset", + "textLength", + "lengthAdjust", +]); + +export { camelCaseAttributes }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/svg/utils/create-render-state.mjs b/frontend/node_modules/framer-motion/dist/es/render/svg/utils/create-render-state.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7eb583e3f79e6b5fd20fa765a1c215659b6aa4a1 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/svg/utils/create-render-state.mjs @@ -0,0 +1,8 @@ +import { createHtmlRenderState } from '../../html/utils/create-render-state.mjs'; + +const createSvgRenderState = () => ({ + ...createHtmlRenderState(), + attrs: {}, +}); + +export { createSvgRenderState }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/svg/utils/is-svg-tag.mjs b/frontend/node_modules/framer-motion/dist/es/render/svg/utils/is-svg-tag.mjs new file mode 100644 index 0000000000000000000000000000000000000000..091789648494a2036229f4a7f57eb3003fafff6f --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/svg/utils/is-svg-tag.mjs @@ -0,0 +1,3 @@ +const isSVGTag = (tag) => typeof tag === "string" && tag.toLowerCase() === "svg"; + +export { isSVGTag }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/svg/utils/path.mjs b/frontend/node_modules/framer-motion/dist/es/render/svg/utils/path.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fc0a43bda54137ef810527ec520386f93bc4ee69 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/svg/utils/path.mjs @@ -0,0 +1,32 @@ +import { px } from 'motion-dom'; + +const dashKeys = { + offset: "stroke-dashoffset", + array: "stroke-dasharray", +}; +const camelKeys = { + offset: "strokeDashoffset", + array: "strokeDasharray", +}; +/** + * Build SVG path properties. Uses the path's measured length to convert + * our custom pathLength, pathSpacing and pathOffset into stroke-dashoffset + * and stroke-dasharray attributes. + * + * This function is mutative to reduce per-frame GC. + */ +function buildSVGPath(attrs, length, spacing = 1, offset = 0, useDashCase = true) { + // Normalise path length by setting SVG attribute pathLength to 1 + attrs.pathLength = 1; + // We use dash case when setting attributes directly to the DOM node and camel case + // when defining props on a React component. + const keys = useDashCase ? dashKeys : camelKeys; + // Build the dash offset + attrs[keys.offset] = px.transform(-offset); + // Build the dash array + const pathLength = px.transform(length); + const pathSpacing = px.transform(spacing); + attrs[keys.array] = `${pathLength} ${pathSpacing}`; +} + +export { buildSVGPath }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/svg/utils/render.mjs b/frontend/node_modules/framer-motion/dist/es/render/svg/utils/render.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bfd65f3d70bdb59e8f7ae1017310e939e693aa75 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/svg/utils/render.mjs @@ -0,0 +1,12 @@ +import { camelToDash } from '../../dom/utils/camel-to-dash.mjs'; +import { renderHTML } from '../../html/utils/render.mjs'; +import { camelCaseAttributes } from './camel-case-attrs.mjs'; + +function renderSVG(element, renderState, _styleProp, projection) { + renderHTML(element, renderState, undefined, projection); + for (const key in renderState.attrs) { + element.setAttribute(!camelCaseAttributes.has(key) ? camelToDash(key) : key, renderState.attrs[key]); + } +} + +export { renderSVG }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/svg/utils/scrape-motion-values.mjs b/frontend/node_modules/framer-motion/dist/es/render/svg/utils/scrape-motion-values.mjs new file mode 100644 index 0000000000000000000000000000000000000000..532dc4601d49fa63824e50c5736ca72fbc974f7e --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/svg/utils/scrape-motion-values.mjs @@ -0,0 +1,18 @@ +import { isMotionValue, transformPropOrder } from 'motion-dom'; +import { scrapeMotionValuesFromProps as scrapeMotionValuesFromProps$1 } from '../../html/utils/scrape-motion-values.mjs'; + +function scrapeMotionValuesFromProps(props, prevProps, visualElement) { + const newValues = scrapeMotionValuesFromProps$1(props, prevProps, visualElement); + for (const key in props) { + if (isMotionValue(props[key]) || + isMotionValue(prevProps[key])) { + const targetKey = transformPropOrder.indexOf(key) !== -1 + ? "attr" + key.charAt(0).toUpperCase() + key.substring(1) + : key; + newValues[targetKey] = props[key]; + } + } + return newValues; +} + +export { scrapeMotionValuesFromProps }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/utils/animation-state.mjs b/frontend/node_modules/framer-motion/dist/es/render/utils/animation-state.mjs new file mode 100644 index 0000000000000000000000000000000000000000..db5e3c35e032f37fab21f65299b7003943b172a0 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/utils/animation-state.mjs @@ -0,0 +1,357 @@ +import { animateVisualElement } from '../../animation/interfaces/visual-element.mjs'; +import { calcChildStagger } from '../../animation/utils/calc-child-stagger.mjs'; +import { isAnimationControls } from '../../animation/utils/is-animation-controls.mjs'; +import { isKeyframesTarget } from '../../animation/utils/is-keyframes-target.mjs'; +import { shallowCompare } from '../../utils/shallow-compare.mjs'; +import { getVariantContext } from './get-variant-context.mjs'; +import { isVariantLabel } from './is-variant-label.mjs'; +import { resolveVariant } from './resolve-dynamic-variants.mjs'; +import { variantPriorityOrder } from './variant-props.mjs'; + +const reversePriorityOrder = [...variantPriorityOrder].reverse(); +const numAnimationTypes = variantPriorityOrder.length; +function animateList(visualElement) { + return (animations) => Promise.all(animations.map(({ animation, options }) => animateVisualElement(visualElement, animation, options))); +} +function createAnimationState(visualElement) { + let animate = animateList(visualElement); + let state = createState(); + let isInitialRender = true; + /** + * This function will be used to reduce the animation definitions for + * each active animation type into an object of resolved values for it. + */ + const buildResolvedTypeValues = (type) => (acc, definition) => { + const resolved = resolveVariant(visualElement, definition, type === "exit" + ? visualElement.presenceContext?.custom + : undefined); + if (resolved) { + const { transition, transitionEnd, ...target } = resolved; + acc = { ...acc, ...target, ...transitionEnd }; + } + return acc; + }; + /** + * This just allows us to inject mocked animation functions + * @internal + */ + function setAnimateFunction(makeAnimator) { + animate = makeAnimator(visualElement); + } + /** + * When we receive new props, we need to: + * 1. Create a list of protected keys for each type. This is a directory of + * value keys that are currently being "handled" by types of a higher priority + * so that whenever an animation is played of a given type, these values are + * protected from being animated. + * 2. Determine if an animation type needs animating. + * 3. Determine if any values have been removed from a type and figure out + * what to animate those to. + */ + function animateChanges(changedActiveType) { + const { props } = visualElement; + const context = getVariantContext(visualElement.parent) || {}; + /** + * A list of animations that we'll build into as we iterate through the animation + * types. This will get executed at the end of the function. + */ + const animations = []; + /** + * Keep track of which values have been removed. Then, as we hit lower priority + * animation types, we can check if they contain removed values and animate to that. + */ + const removedKeys = new Set(); + /** + * A dictionary of all encountered keys. This is an object to let us build into and + * copy it without iteration. Each time we hit an animation type we set its protected + * keys - the keys its not allowed to animate - to the latest version of this object. + */ + let encounteredKeys = {}; + /** + * If a variant has been removed at a given index, and this component is controlling + * variant animations, we want to ensure lower-priority variants are forced to animate. + */ + let removedVariantIndex = Infinity; + /** + * Iterate through all animation types in reverse priority order. For each, we want to + * detect which values it's handling and whether or not they've changed (and therefore + * need to be animated). If any values have been removed, we want to detect those in + * lower priority props and flag for animation. + */ + for (let i = 0; i < numAnimationTypes; i++) { + const type = reversePriorityOrder[i]; + const typeState = state[type]; + const prop = props[type] !== undefined + ? props[type] + : context[type]; + const propIsVariant = isVariantLabel(prop); + /** + * If this type has *just* changed isActive status, set activeDelta + * to that status. Otherwise set to null. + */ + const activeDelta = type === changedActiveType ? typeState.isActive : null; + if (activeDelta === false) + removedVariantIndex = i; + /** + * If this prop is an inherited variant, rather than been set directly on the + * component itself, we want to make sure we allow the parent to trigger animations. + * + * TODO: Can probably change this to a !isControllingVariants check + */ + let isInherited = prop === context[type] && + prop !== props[type] && + propIsVariant; + if (isInherited && + isInitialRender && + visualElement.manuallyAnimateOnMount) { + isInherited = false; + } + /** + * Set all encountered keys so far as the protected keys for this type. This will + * be any key that has been animated or otherwise handled by active, higher-priortiy types. + */ + typeState.protectedKeys = { ...encounteredKeys }; + // Check if we can skip analysing this prop early + if ( + // If it isn't active and hasn't *just* been set as inactive + (!typeState.isActive && activeDelta === null) || + // If we didn't and don't have any defined prop for this animation type + (!prop && !typeState.prevProp) || + // Or if the prop doesn't define an animation + isAnimationControls(prop) || + typeof prop === "boolean") { + continue; + } + /** + * As we go look through the values defined on this type, if we detect + * a changed value or a value that was removed in a higher priority, we set + * this to true and add this prop to the animation list. + */ + const variantDidChange = checkVariantsDidChange(typeState.prevProp, prop); + let shouldAnimateType = variantDidChange || + // If we're making this variant active, we want to always make it active + (type === changedActiveType && + typeState.isActive && + !isInherited && + propIsVariant) || + // If we removed a higher-priority variant (i is in reverse order) + (i > removedVariantIndex && propIsVariant); + let handledRemovedValues = false; + /** + * As animations can be set as variant lists, variants or target objects, we + * coerce everything to an array if it isn't one already + */ + const definitionList = Array.isArray(prop) ? prop : [prop]; + /** + * Build an object of all the resolved values. We'll use this in the subsequent + * animateChanges calls to determine whether a value has changed. + */ + let resolvedValues = definitionList.reduce(buildResolvedTypeValues(type), {}); + if (activeDelta === false) + resolvedValues = {}; + /** + * Now we need to loop through all the keys in the prev prop and this prop, + * and decide: + * 1. If the value has changed, and needs animating + * 2. If it has been removed, and needs adding to the removedKeys set + * 3. If it has been removed in a higher priority type and needs animating + * 4. If it hasn't been removed in a higher priority but hasn't changed, and + * needs adding to the type's protectedKeys list. + */ + const { prevResolvedValues = {} } = typeState; + const allKeys = { + ...prevResolvedValues, + ...resolvedValues, + }; + const markToAnimate = (key) => { + shouldAnimateType = true; + if (removedKeys.has(key)) { + handledRemovedValues = true; + removedKeys.delete(key); + } + typeState.needsAnimating[key] = true; + const motionValue = visualElement.getValue(key); + if (motionValue) + motionValue.liveStyle = false; + }; + for (const key in allKeys) { + const next = resolvedValues[key]; + const prev = prevResolvedValues[key]; + // If we've already handled this we can just skip ahead + if (encounteredKeys.hasOwnProperty(key)) + continue; + /** + * If the value has changed, we probably want to animate it. + */ + let valueHasChanged = false; + if (isKeyframesTarget(next) && isKeyframesTarget(prev)) { + valueHasChanged = !shallowCompare(next, prev); + } + else { + valueHasChanged = next !== prev; + } + if (valueHasChanged) { + if (next !== undefined && next !== null) { + // If next is defined and doesn't equal prev, it needs animating + markToAnimate(key); + } + else { + // If it's undefined, it's been removed. + removedKeys.add(key); + } + } + else if (next !== undefined && removedKeys.has(key)) { + /** + * If next hasn't changed and it isn't undefined, we want to check if it's + * been removed by a higher priority + */ + markToAnimate(key); + } + else { + /** + * If it hasn't changed, we add it to the list of protected values + * to ensure it doesn't get animated. + */ + typeState.protectedKeys[key] = true; + } + } + /** + * Update the typeState so next time animateChanges is called we can compare the + * latest prop and resolvedValues to these. + */ + typeState.prevProp = prop; + typeState.prevResolvedValues = resolvedValues; + if (typeState.isActive) { + encounteredKeys = { ...encounteredKeys, ...resolvedValues }; + } + if (isInitialRender && visualElement.blockInitialAnimation) { + shouldAnimateType = false; + } + /** + * If this is an inherited prop we want to skip this animation + * unless the inherited variants haven't changed on this render. + */ + const willAnimateViaParent = isInherited && variantDidChange; + const needsAnimating = !willAnimateViaParent || handledRemovedValues; + if (shouldAnimateType && needsAnimating) { + animations.push(...definitionList.map((animation) => { + const options = { type }; + /** + * If we're performing the initial animation, but we're not + * rendering at the same time as the variant-controlling parent, + * we want to use the parent's transition to calculate the stagger. + */ + if (typeof animation === "string" && + isInitialRender && + !willAnimateViaParent && + visualElement.manuallyAnimateOnMount && + visualElement.parent) { + const { parent } = visualElement; + const parentVariant = resolveVariant(parent, animation); + if (parent.enteringChildren && parentVariant) { + const { delayChildren } = parentVariant.transition || {}; + options.delay = calcChildStagger(parent.enteringChildren, visualElement, delayChildren); + } + } + return { + animation: animation, + options, + }; + })); + } + } + /** + * If there are some removed value that haven't been dealt with, + * we need to create a new animation that falls back either to the value + * defined in the style prop, or the last read value. + */ + if (removedKeys.size) { + const fallbackAnimation = {}; + /** + * If the initial prop contains a transition we can use that, otherwise + * allow the animation function to use the visual element's default. + */ + if (typeof props.initial !== "boolean") { + const initialTransition = resolveVariant(visualElement, Array.isArray(props.initial) + ? props.initial[0] + : props.initial); + if (initialTransition && initialTransition.transition) { + fallbackAnimation.transition = initialTransition.transition; + } + } + removedKeys.forEach((key) => { + const fallbackTarget = visualElement.getBaseTarget(key); + const motionValue = visualElement.getValue(key); + if (motionValue) + motionValue.liveStyle = true; + // @ts-expect-error - @mattgperry to figure if we should do something here + fallbackAnimation[key] = fallbackTarget ?? null; + }); + animations.push({ animation: fallbackAnimation }); + } + let shouldAnimate = Boolean(animations.length); + if (isInitialRender && + (props.initial === false || props.initial === props.animate) && + !visualElement.manuallyAnimateOnMount) { + shouldAnimate = false; + } + isInitialRender = false; + return shouldAnimate ? animate(animations) : Promise.resolve(); + } + /** + * Change whether a certain animation type is active. + */ + function setActive(type, isActive) { + // If the active state hasn't changed, we can safely do nothing here + if (state[type].isActive === isActive) + return Promise.resolve(); + // Propagate active change to children + visualElement.variantChildren?.forEach((child) => child.animationState?.setActive(type, isActive)); + state[type].isActive = isActive; + const animations = animateChanges(type); + for (const key in state) { + state[key].protectedKeys = {}; + } + return animations; + } + return { + animateChanges, + setActive, + setAnimateFunction, + getState: () => state, + reset: () => { + state = createState(); + isInitialRender = true; + }, + }; +} +function checkVariantsDidChange(prev, next) { + if (typeof next === "string") { + return next !== prev; + } + else if (Array.isArray(next)) { + return !shallowCompare(next, prev); + } + return false; +} +function createTypeState(isActive = false) { + return { + isActive, + protectedKeys: {}, + needsAnimating: {}, + prevResolvedValues: {}, + }; +} +function createState() { + return { + animate: createTypeState(true), + whileInView: createTypeState(), + whileHover: createTypeState(), + whileTap: createTypeState(), + whileDrag: createTypeState(), + whileFocus: createTypeState(), + exit: createTypeState(), + }; +} + +export { checkVariantsDidChange, createAnimationState }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/utils/compare-by-depth.mjs b/frontend/node_modules/framer-motion/dist/es/render/utils/compare-by-depth.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c34dd7453f0cb860f5674fe0b3ec3dd22a98a4d5 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/utils/compare-by-depth.mjs @@ -0,0 +1,3 @@ +const compareByDepth = (a, b) => a.depth - b.depth; + +export { compareByDepth }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/utils/flat-tree.mjs b/frontend/node_modules/framer-motion/dist/es/render/utils/flat-tree.mjs new file mode 100644 index 0000000000000000000000000000000000000000..75d8f88c8bbab7faf34085c12846232fecb0e02e --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/utils/flat-tree.mjs @@ -0,0 +1,24 @@ +import { addUniqueItem, removeItem } from 'motion-utils'; +import { compareByDepth } from './compare-by-depth.mjs'; + +class FlatTree { + constructor() { + this.children = []; + this.isDirty = false; + } + add(child) { + addUniqueItem(this.children, child); + this.isDirty = true; + } + remove(child) { + removeItem(this.children, child); + this.isDirty = true; + } + forEach(callback) { + this.isDirty && this.children.sort(compareByDepth); + this.isDirty = false; + this.children.forEach(callback); + } +} + +export { FlatTree }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/utils/get-variant-context.mjs b/frontend/node_modules/framer-motion/dist/es/render/utils/get-variant-context.mjs new file mode 100644 index 0000000000000000000000000000000000000000..15e579882d6461e204e7b407118715a16fb596fb --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/utils/get-variant-context.mjs @@ -0,0 +1,28 @@ +import { isVariantLabel } from './is-variant-label.mjs'; +import { variantProps } from './variant-props.mjs'; + +const numVariantProps = variantProps.length; +function getVariantContext(visualElement) { + if (!visualElement) + return undefined; + if (!visualElement.isControllingVariants) { + const context = visualElement.parent + ? getVariantContext(visualElement.parent) || {} + : {}; + if (visualElement.props.initial !== undefined) { + context.initial = visualElement.props.initial; + } + return context; + } + const context = {}; + for (let i = 0; i < numVariantProps; i++) { + const name = variantProps[i]; + const prop = visualElement.props[name]; + if (isVariantLabel(prop) || prop === false) { + context[name] = prop; + } + } + return context; +} + +export { getVariantContext }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/utils/is-controlling-variants.mjs b/frontend/node_modules/framer-motion/dist/es/render/utils/is-controlling-variants.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3b24d8b157f04d192a355930bec2fe11bf4d858e --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/utils/is-controlling-variants.mjs @@ -0,0 +1,13 @@ +import { isAnimationControls } from '../../animation/utils/is-animation-controls.mjs'; +import { isVariantLabel } from './is-variant-label.mjs'; +import { variantProps } from './variant-props.mjs'; + +function isControllingVariants(props) { + return (isAnimationControls(props.animate) || + variantProps.some((name) => isVariantLabel(props[name]))); +} +function isVariantNode(props) { + return Boolean(isControllingVariants(props) || props.variants); +} + +export { isControllingVariants, isVariantNode }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/utils/is-variant-label.mjs b/frontend/node_modules/framer-motion/dist/es/render/utils/is-variant-label.mjs new file mode 100644 index 0000000000000000000000000000000000000000..db4ab5c4ad28c3472f12c2beaa59ac8e1d1c46f0 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/utils/is-variant-label.mjs @@ -0,0 +1,8 @@ +/** + * Decides if the supplied variable is variant label + */ +function isVariantLabel(v) { + return typeof v === "string" || Array.isArray(v); +} + +export { isVariantLabel }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/utils/motion-values.mjs b/frontend/node_modules/framer-motion/dist/es/render/utils/motion-values.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1db628a3d18892b5ac5eb0e7a7f895de9086bcf5 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/utils/motion-values.mjs @@ -0,0 +1,50 @@ +import { isMotionValue, motionValue } from 'motion-dom'; + +function updateMotionValuesFromProps(element, next, prev) { + for (const key in next) { + const nextValue = next[key]; + const prevValue = prev[key]; + if (isMotionValue(nextValue)) { + /** + * If this is a motion value found in props or style, we want to add it + * to our visual element's motion value map. + */ + element.addValue(key, nextValue); + } + else if (isMotionValue(prevValue)) { + /** + * If we're swapping from a motion value to a static value, + * create a new motion value from that + */ + element.addValue(key, motionValue(nextValue, { owner: element })); + } + else if (prevValue !== nextValue) { + /** + * If this is a flat value that has changed, update the motion value + * or create one if it doesn't exist. We only want to do this if we're + * not handling the value with our animation state. + */ + if (element.hasValue(key)) { + const existingValue = element.getValue(key); + if (existingValue.liveStyle === true) { + existingValue.jump(nextValue); + } + else if (!existingValue.hasAnimated) { + existingValue.set(nextValue); + } + } + else { + const latestValue = element.getStaticValue(key); + element.addValue(key, motionValue(latestValue !== undefined ? latestValue : nextValue, { owner: element })); + } + } + } + // Handle removed values + for (const key in prev) { + if (next[key] === undefined) + element.removeValue(key); + } + return next; +} + +export { updateMotionValuesFromProps }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/utils/resolve-dynamic-variants.mjs b/frontend/node_modules/framer-motion/dist/es/render/utils/resolve-dynamic-variants.mjs new file mode 100644 index 0000000000000000000000000000000000000000..57b1cea55655c8c9da8aa22bcd27518e60ded142 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/utils/resolve-dynamic-variants.mjs @@ -0,0 +1,8 @@ +import { resolveVariantFromProps } from './resolve-variants.mjs'; + +function resolveVariant(visualElement, definition, custom) { + const props = visualElement.getProps(); + return resolveVariantFromProps(props, definition, custom !== undefined ? custom : props.custom, visualElement); +} + +export { resolveVariant }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/utils/resolve-variants.mjs b/frontend/node_modules/framer-motion/dist/es/render/utils/resolve-variants.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ba65fc29c5858e0c2c1f2646582b9e3fc930506c --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/utils/resolve-variants.mjs @@ -0,0 +1,36 @@ +function getValueState(visualElement) { + const state = [{}, {}]; + visualElement?.values.forEach((value, key) => { + state[0][key] = value.get(); + state[1][key] = value.getVelocity(); + }); + return state; +} +function resolveVariantFromProps(props, definition, custom, visualElement) { + /** + * If the variant definition is a function, resolve. + */ + if (typeof definition === "function") { + const [current, velocity] = getValueState(visualElement); + definition = definition(custom !== undefined ? custom : props.custom, current, velocity); + } + /** + * If the variant definition is a variant label, or + * the function returned a variant label, resolve. + */ + if (typeof definition === "string") { + definition = props.variants && props.variants[definition]; + } + /** + * At this point we've resolved both functions and variant labels, + * but the resolved variant label might itself have been a function. + * If so, resolve. This can only have returned a valid target object. + */ + if (typeof definition === "function") { + const [current, velocity] = getValueState(visualElement); + definition = definition(custom !== undefined ? custom : props.custom, current, velocity); + } + return definition; +} + +export { resolveVariantFromProps }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/utils/setters.mjs b/frontend/node_modules/framer-motion/dist/es/render/utils/setters.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6ea78049bba52d38d29fb81c5863ed29abd5f08b --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/utils/setters.mjs @@ -0,0 +1,31 @@ +import { motionValue } from 'motion-dom'; +import { isKeyframesTarget } from '../../animation/utils/is-keyframes-target.mjs'; +import { resolveVariant } from './resolve-dynamic-variants.mjs'; + +/** + * Set VisualElement's MotionValue, creating a new MotionValue for it if + * it doesn't exist. + */ +function setMotionValue(visualElement, key, value) { + if (visualElement.hasValue(key)) { + visualElement.getValue(key).set(value); + } + else { + visualElement.addValue(key, motionValue(value)); + } +} +function resolveFinalValueInKeyframes(v) { + // TODO maybe throw if v.length - 1 is placeholder token? + return isKeyframesTarget(v) ? v[v.length - 1] || 0 : v; +} +function setTarget(visualElement, definition) { + const resolved = resolveVariant(visualElement, definition); + let { transitionEnd = {}, transition = {}, ...target } = resolved || {}; + target = { ...target, ...transitionEnd }; + for (const key in target) { + const value = resolveFinalValueInKeyframes(target[key]); + setMotionValue(visualElement, key, value); + } +} + +export { setTarget }; diff --git a/frontend/node_modules/framer-motion/dist/es/render/utils/variant-props.mjs b/frontend/node_modules/framer-motion/dist/es/render/utils/variant-props.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f4d0a9111642a5c359d360c09bffeaff1f3a1532 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/render/utils/variant-props.mjs @@ -0,0 +1,12 @@ +const variantPriorityOrder = [ + "animate", + "whileInView", + "whileFocus", + "whileHover", + "whileTap", + "whileDrag", + "exit", +]; +const variantProps = ["initial", ...variantPriorityOrder]; + +export { variantPriorityOrder, variantProps }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/delay.mjs b/frontend/node_modules/framer-motion/dist/es/utils/delay.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6dceb872483c94b762ce15ac5fcac12865afe73f --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/delay.mjs @@ -0,0 +1,23 @@ +import { time, frame, cancelFrame } from 'motion-dom'; +import { secondsToMilliseconds } from 'motion-utils'; + +/** + * Timeout defined in ms + */ +function delay(callback, timeout) { + const start = time.now(); + const checkElapsed = ({ timestamp }) => { + const elapsed = timestamp - start; + if (elapsed >= timeout) { + cancelFrame(checkElapsed); + callback(elapsed - timeout); + } + }; + frame.setup(checkElapsed, true); + return () => cancelFrame(checkElapsed); +} +function delayInSeconds(callback, timeout) { + return delay(callback, secondsToMilliseconds(timeout)); +} + +export { delay, delayInSeconds }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/distance.mjs b/frontend/node_modules/framer-motion/dist/es/utils/distance.mjs new file mode 100644 index 0000000000000000000000000000000000000000..dfcc107784456760b651f63408a072e5c52b2644 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/distance.mjs @@ -0,0 +1,9 @@ +const distance = (a, b) => Math.abs(a - b); +function distance2D(a, b) { + // Multi-dimensional + const xDelta = distance(a.x, b.x); + const yDelta = distance(a.y, b.y); + return Math.sqrt(xDelta ** 2 + yDelta ** 2); +} + +export { distance, distance2D }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/get-context-window.mjs b/frontend/node_modules/framer-motion/dist/es/utils/get-context-window.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5e38905003718657cac3320963bbd5c1409d92ad --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/get-context-window.mjs @@ -0,0 +1,6 @@ +// Fixes https://github.com/motiondivision/motion/issues/2270 +const getContextWindow = ({ current }) => { + return current ? current.ownerDocument.defaultView : null; +}; + +export { getContextWindow }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/is-browser.mjs b/frontend/node_modules/framer-motion/dist/es/utils/is-browser.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bd45170d6d1dda2f9fd3a2ccc87314cbc31c079e --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/is-browser.mjs @@ -0,0 +1,3 @@ +const isBrowser = typeof window !== "undefined"; + +export { isBrowser }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/is-ref-object.mjs b/frontend/node_modules/framer-motion/dist/es/utils/is-ref-object.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1244527fe5f60a790e8892bf8ecf3fad0df95626 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/is-ref-object.mjs @@ -0,0 +1,7 @@ +function isRefObject(ref) { + return (ref && + typeof ref === "object" && + Object.prototype.hasOwnProperty.call(ref, "current")); +} + +export { isRefObject }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/reduced-motion/index.mjs b/frontend/node_modules/framer-motion/dist/es/utils/reduced-motion/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a2d76e8fa7805548a7c7976181e116c289de6a74 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/reduced-motion/index.mjs @@ -0,0 +1,19 @@ +import { isBrowser } from '../is-browser.mjs'; +import { hasReducedMotionListener, prefersReducedMotion } from './state.mjs'; + +function initPrefersReducedMotion() { + hasReducedMotionListener.current = true; + if (!isBrowser) + return; + if (window.matchMedia) { + const motionMediaQuery = window.matchMedia("(prefers-reduced-motion)"); + const setReducedMotionPreferences = () => (prefersReducedMotion.current = motionMediaQuery.matches); + motionMediaQuery.addEventListener("change", setReducedMotionPreferences); + setReducedMotionPreferences(); + } + else { + prefersReducedMotion.current = false; + } +} + +export { initPrefersReducedMotion }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/reduced-motion/state.mjs b/frontend/node_modules/framer-motion/dist/es/utils/reduced-motion/state.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6cea55708a2203b80739a18604305f47b5fc0486 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/reduced-motion/state.mjs @@ -0,0 +1,5 @@ +// Does this device prefer reduced motion? Returns `null` server-side. +const prefersReducedMotion = { current: null }; +const hasReducedMotionListener = { current: false }; + +export { hasReducedMotionListener, prefersReducedMotion }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/reduced-motion/use-reduced-motion-config.mjs b/frontend/node_modules/framer-motion/dist/es/utils/reduced-motion/use-reduced-motion-config.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bec54ebe6e5e6b6e5e8a00cd8451bb44126a7395 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/reduced-motion/use-reduced-motion-config.mjs @@ -0,0 +1,19 @@ +import { useContext } from 'react'; +import { MotionConfigContext } from '../../context/MotionConfigContext.mjs'; +import { useReducedMotion } from './use-reduced-motion.mjs'; + +function useReducedMotionConfig() { + const reducedMotionPreference = useReducedMotion(); + const { reducedMotion } = useContext(MotionConfigContext); + if (reducedMotion === "never") { + return false; + } + else if (reducedMotion === "always") { + return true; + } + else { + return reducedMotionPreference; + } +} + +export { useReducedMotionConfig }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/reduced-motion/use-reduced-motion.mjs b/frontend/node_modules/framer-motion/dist/es/utils/reduced-motion/use-reduced-motion.mjs new file mode 100644 index 0000000000000000000000000000000000000000..83ebc5b925f6fd602badef27c6ae086f751ca24f --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/reduced-motion/use-reduced-motion.mjs @@ -0,0 +1,47 @@ +import { warnOnce } from 'motion-utils'; +import { useState } from 'react'; +import { initPrefersReducedMotion } from './index.mjs'; +import { hasReducedMotionListener, prefersReducedMotion } from './state.mjs'; + +/** + * A hook that returns `true` if we should be using reduced motion based on the current device's Reduced Motion setting. + * + * This can be used to implement changes to your UI based on Reduced Motion. For instance, replacing motion-sickness inducing + * `x`/`y` animations with `opacity`, disabling the autoplay of background videos, or turning off parallax motion. + * + * It will actively respond to changes and re-render your components with the latest setting. + * + * ```jsx + * export function Sidebar({ isOpen }) { + * const shouldReduceMotion = useReducedMotion() + * const closedX = shouldReduceMotion ? 0 : "-100%" + * + * return ( + * + * ) + * } + * ``` + * + * @return boolean + * + * @public + */ +function useReducedMotion() { + /** + * Lazy initialisation of prefersReducedMotion + */ + !hasReducedMotionListener.current && initPrefersReducedMotion(); + const [shouldReduceMotion] = useState(prefersReducedMotion.current); + if (process.env.NODE_ENV !== "production") { + warnOnce(shouldReduceMotion !== true, "You have Reduced Motion enabled on your device. Animations may not appear as expected.", "reduced-motion-disabled"); + } + /** + * TODO See if people miss automatically updating shouldReduceMotion setting + */ + return shouldReduceMotion; +} + +export { useReducedMotion }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/shallow-compare.mjs b/frontend/node_modules/framer-motion/dist/es/utils/shallow-compare.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6b9861aacb60362a0e1c76366b2f7c03a87778af --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/shallow-compare.mjs @@ -0,0 +1,14 @@ +function shallowCompare(next, prev) { + if (!Array.isArray(prev)) + return false; + const prevLength = prev.length; + if (prevLength !== next.length) + return false; + for (let i = 0; i < prevLength; i++) { + if (prev[i] !== next[i]) + return false; + } + return true; +} + +export { shallowCompare }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/use-animation-frame.mjs b/frontend/node_modules/framer-motion/dist/es/utils/use-animation-frame.mjs new file mode 100644 index 0000000000000000000000000000000000000000..72e895fc2e5ac2ca06a89ddbd4f8d241705db560 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/use-animation-frame.mjs @@ -0,0 +1,21 @@ +import { frame, cancelFrame } from 'motion-dom'; +import { useRef, useContext, useEffect } from 'react'; +import { MotionConfigContext } from '../context/MotionConfigContext.mjs'; + +function useAnimationFrame(callback) { + const initialTimestamp = useRef(0); + const { isStatic } = useContext(MotionConfigContext); + useEffect(() => { + if (isStatic) + return; + const provideTimeSinceStart = ({ timestamp, delta }) => { + if (!initialTimestamp.current) + initialTimestamp.current = timestamp; + callback(timestamp - initialTimestamp.current, delta); + }; + frame.update(provideTimeSinceStart, true); + return () => cancelFrame(provideTimeSinceStart); + }, [callback]); +} + +export { useAnimationFrame }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/use-constant.mjs b/frontend/node_modules/framer-motion/dist/es/utils/use-constant.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7b271abcd059a38fcb67b7e80593f96eed8c48fb --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/use-constant.mjs @@ -0,0 +1,18 @@ +import { useRef } from 'react'; + +/** + * Creates a constant value over the lifecycle of a component. + * + * Even if `useMemo` is provided an empty array as its final argument, it doesn't offer + * a guarantee that it won't re-run for performance reasons later on. By using `useConstant` + * you can ensure that initialisers don't execute twice or more. + */ +function useConstant(init) { + const ref = useRef(null); + if (ref.current === null) { + ref.current = init(); + } + return ref.current; +} + +export { useConstant }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/use-cycle.mjs b/frontend/node_modules/framer-motion/dist/es/utils/use-cycle.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4cca7d2936307d3d1d498b54d112d9a4f4e2fbdd --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/use-cycle.mjs @@ -0,0 +1,47 @@ +import { wrap } from 'motion-utils'; +import { useRef, useState, useCallback } from 'react'; + +/** + * Cycles through a series of visual properties. Can be used to toggle between or cycle through animations. It works similar to `useState` in React. It is provided an initial array of possible states, and returns an array of two arguments. + * + * An index value can be passed to the returned `cycle` function to cycle to a specific index. + * + * ```jsx + * import * as React from "react" + * import { motion, useCycle } from "framer-motion" + * + * export const MyComponent = () => { + * const [x, cycleX] = useCycle(0, 50, 100) + * + * return ( + * cycleX()} + * /> + * ) + * } + * ``` + * + * @param items - items to cycle through + * @returns [currentState, cycleState] + * + * @public + */ +function useCycle(...items) { + const index = useRef(0); + const [item, setItem] = useState(items[index.current]); + const runCycle = useCallback((next) => { + index.current = + typeof next !== "number" + ? wrap(0, items.length, index.current + 1) + : next; + setItem(items[index.current]); + }, + // The array will change on each call, but by putting items.length at + // the front of this array, we guarantee the dependency comparison will match up + // eslint-disable-next-line react-hooks/exhaustive-deps + [items.length, ...items]); + return [item, runCycle]; +} + +export { useCycle }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/use-force-update.mjs b/frontend/node_modules/framer-motion/dist/es/utils/use-force-update.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7b968b9f2398b4911de796ec98ab711ae6e48c39 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/use-force-update.mjs @@ -0,0 +1,19 @@ +import { frame } from 'motion-dom'; +import { useState, useCallback } from 'react'; +import { useIsMounted } from './use-is-mounted.mjs'; + +function useForceUpdate() { + const isMounted = useIsMounted(); + const [forcedRenderCount, setForcedRenderCount] = useState(0); + const forceRender = useCallback(() => { + isMounted.current && setForcedRenderCount(forcedRenderCount + 1); + }, [forcedRenderCount]); + /** + * Defer this to the end of the next animation frame in case there are multiple + * synchronous calls. + */ + const deferredForceRender = useCallback(() => frame.postRender(forceRender), [forceRender]); + return [deferredForceRender, forcedRenderCount]; +} + +export { useForceUpdate }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/use-in-view.mjs b/frontend/node_modules/framer-motion/dist/es/utils/use-in-view.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3361429a0a7a648c2163ddbe4d9d2dc26f7f19d2 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/use-in-view.mjs @@ -0,0 +1,23 @@ +import { useState, useEffect } from 'react'; +import { inView } from '../render/dom/viewport/index.mjs'; + +function useInView(ref, { root, margin, amount, once = false, initial = false, } = {}) { + const [isInView, setInView] = useState(initial); + useEffect(() => { + if (!ref.current || (once && isInView)) + return; + const onEnter = () => { + setInView(true); + return once ? undefined : () => setInView(false); + }; + const options = { + root: (root && root.current) || undefined, + margin, + amount, + }; + return inView(ref.current, onEnter, options); + }, [root, ref, margin, once, amount]); + return isInView; +} + +export { useInView }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/use-instant-transition.mjs b/frontend/node_modules/framer-motion/dist/es/utils/use-instant-transition.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b9d5415773c177296d4c9ebf74ceda2154aa495f --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/use-instant-transition.mjs @@ -0,0 +1,41 @@ +import { frame } from 'motion-dom'; +import { MotionGlobalConfig } from 'motion-utils'; +import { useRef, useEffect } from 'react'; +import { useInstantLayoutTransition } from '../projection/use-instant-layout-transition.mjs'; +import { useForceUpdate } from './use-force-update.mjs'; + +function useInstantTransition() { + const [forceUpdate, forcedRenderCount] = useForceUpdate(); + const startInstantLayoutTransition = useInstantLayoutTransition(); + const unlockOnFrameRef = useRef(-1); + useEffect(() => { + /** + * Unblock after two animation frames, otherwise this will unblock too soon. + */ + frame.postRender(() => frame.postRender(() => { + /** + * If the callback has been called again after the effect + * triggered this 2 frame delay, don't unblock animations. This + * prevents the previous effect from unblocking the current + * instant transition too soon. This becomes more likely when + * used in conjunction with React.startTransition(). + */ + if (forcedRenderCount !== unlockOnFrameRef.current) + return; + MotionGlobalConfig.instantAnimations = false; + })); + }, [forcedRenderCount]); + return (callback) => { + startInstantLayoutTransition(() => { + MotionGlobalConfig.instantAnimations = true; + forceUpdate(); + callback(); + unlockOnFrameRef.current = forcedRenderCount + 1; + }); + }; +} +function disableInstantTransitions() { + MotionGlobalConfig.instantAnimations = false; +} + +export { disableInstantTransitions, useInstantTransition }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/use-is-mounted.mjs b/frontend/node_modules/framer-motion/dist/es/utils/use-is-mounted.mjs new file mode 100644 index 0000000000000000000000000000000000000000..63528baf7a7d53471ce844fbeac08b6ce0855852 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/use-is-mounted.mjs @@ -0,0 +1,15 @@ +import { useRef } from 'react'; +import { useIsomorphicLayoutEffect } from './use-isomorphic-effect.mjs'; + +function useIsMounted() { + const isMounted = useRef(false); + useIsomorphicLayoutEffect(() => { + isMounted.current = true; + return () => { + isMounted.current = false; + }; + }, []); + return isMounted; +} + +export { useIsMounted }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/use-isomorphic-effect.mjs b/frontend/node_modules/framer-motion/dist/es/utils/use-isomorphic-effect.mjs new file mode 100644 index 0000000000000000000000000000000000000000..024536c760993bcab772d5ccce92a1e817ba132f --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/use-isomorphic-effect.mjs @@ -0,0 +1,6 @@ +import { useLayoutEffect, useEffect } from 'react'; +import { isBrowser } from './is-browser.mjs'; + +const useIsomorphicLayoutEffect = isBrowser ? useLayoutEffect : useEffect; + +export { useIsomorphicLayoutEffect }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/use-motion-value-event.mjs b/frontend/node_modules/framer-motion/dist/es/utils/use-motion-value-event.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d4488b64f883cda9405811d6de032f5d50797898 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/use-motion-value-event.mjs @@ -0,0 +1,13 @@ +import { useInsertionEffect } from 'react'; + +function useMotionValueEvent(value, event, callback) { + /** + * useInsertionEffect will create subscriptions before any other + * effects will run. Effects run upwards through the tree so it + * can be that binding a useLayoutEffect higher up the tree can + * miss changes from lower down the tree. + */ + useInsertionEffect(() => value.on(event, callback), [value, event, callback]); +} + +export { useMotionValueEvent }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/use-page-in-view.mjs b/frontend/node_modules/framer-motion/dist/es/utils/use-page-in-view.mjs new file mode 100644 index 0000000000000000000000000000000000000000..aa55bbee2d4d852bd7bada45113a26aecfdb8448 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/use-page-in-view.mjs @@ -0,0 +1,18 @@ +import { useState, useEffect } from 'react'; + +function usePageInView() { + const [isInView, setIsInView] = useState(true); + useEffect(() => { + const handleVisibilityChange = () => setIsInView(!document.hidden); + if (document.hidden) { + handleVisibilityChange(); + } + document.addEventListener("visibilitychange", handleVisibilityChange); + return () => { + document.removeEventListener("visibilitychange", handleVisibilityChange); + }; + }, []); + return isInView; +} + +export { usePageInView }; diff --git a/frontend/node_modules/framer-motion/dist/es/utils/use-unmount-effect.mjs b/frontend/node_modules/framer-motion/dist/es/utils/use-unmount-effect.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6c955cfb93d1f0240798aec3cd9109e2419a22d2 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/utils/use-unmount-effect.mjs @@ -0,0 +1,7 @@ +import { useEffect } from 'react'; + +function useUnmountEffect(callback) { + return useEffect(() => () => callback(), []); +} + +export { useUnmountEffect }; diff --git a/frontend/node_modules/framer-motion/dist/es/value/scroll/use-element-scroll.mjs b/frontend/node_modules/framer-motion/dist/es/value/scroll/use-element-scroll.mjs new file mode 100644 index 0000000000000000000000000000000000000000..83f5732455f0ded1824b995be7bb43123e2746aa --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/value/scroll/use-element-scroll.mjs @@ -0,0 +1,14 @@ +import { warnOnce } from 'motion-utils'; +import { useScroll } from '../use-scroll.mjs'; + +/** + * @deprecated useElementScroll is deprecated. Convert to useScroll({ container: ref }) + */ +function useElementScroll(ref) { + if (process.env.NODE_ENV === "development") { + warnOnce(false, "useElementScroll is deprecated. Convert to useScroll({ container: ref })."); + } + return useScroll({ container: ref }); +} + +export { useElementScroll }; diff --git a/frontend/node_modules/framer-motion/dist/es/value/scroll/use-viewport-scroll.mjs b/frontend/node_modules/framer-motion/dist/es/value/scroll/use-viewport-scroll.mjs new file mode 100644 index 0000000000000000000000000000000000000000..84be0f10c812f79fd11b03b63d0fe6688f31b9ed --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/value/scroll/use-viewport-scroll.mjs @@ -0,0 +1,14 @@ +import { warnOnce } from 'motion-utils'; +import { useScroll } from '../use-scroll.mjs'; + +/** + * @deprecated useViewportScroll is deprecated. Convert to useScroll() + */ +function useViewportScroll() { + if (process.env.NODE_ENV !== "production") { + warnOnce(false, "useViewportScroll is deprecated. Convert to useScroll()."); + } + return useScroll(); +} + +export { useViewportScroll }; diff --git a/frontend/node_modules/framer-motion/dist/es/value/use-combine-values.mjs b/frontend/node_modules/framer-motion/dist/es/value/use-combine-values.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b79d3b8602b0e8fccef2f7ac04825a4fad2ca19b --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/value/use-combine-values.mjs @@ -0,0 +1,37 @@ +import { cancelFrame, frame } from 'motion-dom'; +import { useIsomorphicLayoutEffect } from '../utils/use-isomorphic-effect.mjs'; +import { useMotionValue } from './use-motion-value.mjs'; + +function useCombineMotionValues(values, combineValues) { + /** + * Initialise the returned motion value. This remains the same between renders. + */ + const value = useMotionValue(combineValues()); + /** + * Create a function that will update the template motion value with the latest values. + * This is pre-bound so whenever a motion value updates it can schedule its + * execution in Framesync. If it's already been scheduled it won't be fired twice + * in a single frame. + */ + const updateValue = () => value.set(combineValues()); + /** + * Synchronously update the motion value with the latest values during the render. + * This ensures that within a React render, the styles applied to the DOM are up-to-date. + */ + updateValue(); + /** + * Subscribe to all motion values found within the template. Whenever any of them change, + * schedule an update. + */ + useIsomorphicLayoutEffect(() => { + const scheduleUpdate = () => frame.preRender(updateValue, false, true); + const subscriptions = values.map((v) => v.on("change", scheduleUpdate)); + return () => { + subscriptions.forEach((unsubscribe) => unsubscribe()); + cancelFrame(updateValue); + }; + }); + return value; +} + +export { useCombineMotionValues }; diff --git a/frontend/node_modules/framer-motion/dist/es/value/use-computed.mjs b/frontend/node_modules/framer-motion/dist/es/value/use-computed.mjs new file mode 100644 index 0000000000000000000000000000000000000000..70827c97cb7aaddf65a2e3cbe700f99e0be160d3 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/value/use-computed.mjs @@ -0,0 +1,19 @@ +import { collectMotionValues } from 'motion-dom'; +import { useCombineMotionValues } from './use-combine-values.mjs'; + +function useComputed(compute) { + /** + * Open session of collectMotionValues. Any MotionValue that calls get() + * will be saved into this array. + */ + collectMotionValues.current = []; + compute(); + const value = useCombineMotionValues(collectMotionValues.current, compute); + /** + * Synchronously close session of collectMotionValues. + */ + collectMotionValues.current = undefined; + return value; +} + +export { useComputed }; diff --git a/frontend/node_modules/framer-motion/dist/es/value/use-inverted-scale.mjs b/frontend/node_modules/framer-motion/dist/es/value/use-inverted-scale.mjs new file mode 100644 index 0000000000000000000000000000000000000000..31f15ee6a07b3b4a924dd24e33a8b0b0f6d4bd1f --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/value/use-inverted-scale.mjs @@ -0,0 +1,52 @@ +import { invariant, warning } from 'motion-utils'; +import { useContext } from 'react'; +import { MotionContext } from '../context/MotionContext/index.mjs'; +import { useMotionValue } from './use-motion-value.mjs'; +import { useTransform } from './use-transform.mjs'; + +// Keep things reasonable and avoid scale: Infinity. In practise we might need +// to add another value, opacity, that could interpolate scaleX/Y [0,0.01] => [0,1] +// to simply hide content at unreasonable scales. +const maxScale = 100000; +const invertScale = (scale) => scale > 0.001 ? 1 / scale : maxScale; +let hasWarned = false; +/** + * Returns a `MotionValue` each for `scaleX` and `scaleY` that update with the inverse + * of their respective parent scales. + * + * This is useful for undoing the distortion of content when scaling a parent component. + * + * By default, `useInvertedScale` will automatically fetch `scaleX` and `scaleY` from the nearest parent. + * By passing other `MotionValue`s in as `useInvertedScale({ scaleX, scaleY })`, it will invert the output + * of those instead. + * + * ```jsx + * const MyComponent = () => { + * const { scaleX, scaleY } = useInvertedScale() + * return + * } + * ``` + * + * @deprecated + */ +function useInvertedScale(scale) { + let parentScaleX = useMotionValue(1); + let parentScaleY = useMotionValue(1); + const { visualElement } = useContext(MotionContext); + invariant(!!(scale || visualElement), "If no scale values are provided, useInvertedScale must be used within a child of another motion component."); + warning(hasWarned, "useInvertedScale is deprecated and will be removed in 3.0. Use the layout prop instead."); + hasWarned = true; + if (scale) { + parentScaleX = scale.scaleX || parentScaleX; + parentScaleY = scale.scaleY || parentScaleY; + } + else if (visualElement) { + parentScaleX = visualElement.getValue("scaleX", 1); + parentScaleY = visualElement.getValue("scaleY", 1); + } + const scaleX = useTransform(parentScaleX, invertScale); + const scaleY = useTransform(parentScaleY, invertScale); + return { scaleX, scaleY }; +} + +export { invertScale, useInvertedScale }; diff --git a/frontend/node_modules/framer-motion/dist/es/value/use-motion-template.mjs b/frontend/node_modules/framer-motion/dist/es/value/use-motion-template.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3c41024a9002234395f58037b319c037a2ef6e92 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/value/use-motion-template.mjs @@ -0,0 +1,45 @@ +import { isMotionValue } from 'motion-dom'; +import { useCombineMotionValues } from './use-combine-values.mjs'; + +/** + * Combine multiple motion values into a new one using a string template literal. + * + * ```jsx + * import { + * motion, + * useSpring, + * useMotionValue, + * useMotionTemplate + * } from "framer-motion" + * + * function Component() { + * const shadowX = useSpring(0) + * const shadowY = useMotionValue(0) + * const shadow = useMotionTemplate`drop-shadow(${shadowX}px ${shadowY}px 20px rgba(0,0,0,0.3))` + * + * return + * } + * ``` + * + * @public + */ +function useMotionTemplate(fragments, ...values) { + /** + * Create a function that will build a string from the latest motion values. + */ + const numFragments = fragments.length; + function buildValue() { + let output = ``; + for (let i = 0; i < numFragments; i++) { + output += fragments[i]; + const value = values[i]; + if (value) { + output += isMotionValue(value) ? value.get() : value; + } + } + return output; + } + return useCombineMotionValues(values.filter(isMotionValue), buildValue); +} + +export { useMotionTemplate }; diff --git a/frontend/node_modules/framer-motion/dist/es/value/use-motion-value.mjs b/frontend/node_modules/framer-motion/dist/es/value/use-motion-value.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3a8a6627813c6dd36f63648b64f344beb27973b4 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/value/use-motion-value.mjs @@ -0,0 +1,38 @@ +import { motionValue } from 'motion-dom'; +import { useContext, useState, useEffect } from 'react'; +import { MotionConfigContext } from '../context/MotionConfigContext.mjs'; +import { useConstant } from '../utils/use-constant.mjs'; + +/** + * Creates a `MotionValue` to track the state and velocity of a value. + * + * Usually, these are created automatically. For advanced use-cases, like use with `useTransform`, you can create `MotionValue`s externally and pass them into the animated component via the `style` prop. + * + * ```jsx + * export const MyComponent = () => { + * const scale = useMotionValue(1) + * + * return + * } + * ``` + * + * @param initial - The initial state. + * + * @public + */ +function useMotionValue(initial) { + const value = useConstant(() => motionValue(initial)); + /** + * If this motion value is being used in static mode, like on + * the Framer canvas, force components to rerender when the motion + * value is updated. + */ + const { isStatic } = useContext(MotionConfigContext); + if (isStatic) { + const [, setLatest] = useState(initial); + useEffect(() => value.on("change", setLatest), []); + } + return value; +} + +export { useMotionValue }; diff --git a/frontend/node_modules/framer-motion/dist/es/value/use-scroll.mjs b/frontend/node_modules/framer-motion/dist/es/value/use-scroll.mjs new file mode 100644 index 0000000000000000000000000000000000000000..484e6a46b48b2998e2651b0b5676bcf604225ce7 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/value/use-scroll.mjs @@ -0,0 +1,61 @@ +import { motionValue } from 'motion-dom'; +import { invariant } from 'motion-utils'; +import { useRef, useCallback, useEffect } from 'react'; +import { scroll } from '../render/dom/scroll/index.mjs'; +import { useConstant } from '../utils/use-constant.mjs'; +import { useIsomorphicLayoutEffect } from '../utils/use-isomorphic-effect.mjs'; + +const createScrollMotionValues = () => ({ + scrollX: motionValue(0), + scrollY: motionValue(0), + scrollXProgress: motionValue(0), + scrollYProgress: motionValue(0), +}); +const isRefPending = (ref) => { + if (!ref) + return false; + return !ref.current; +}; +function useScroll({ container, target, ...options } = {}) { + const values = useConstant(createScrollMotionValues); + const scrollAnimation = useRef(null); + const needsStart = useRef(false); + const start = useCallback(() => { + scrollAnimation.current = scroll((_progress, { x, y, }) => { + values.scrollX.set(x.current); + values.scrollXProgress.set(x.progress); + values.scrollY.set(y.current); + values.scrollYProgress.set(y.progress); + }, { + ...options, + container: container?.current || undefined, + target: target?.current || undefined, + }); + return () => { + scrollAnimation.current?.(); + }; + }, [container, target, JSON.stringify(options.offset)]); + useIsomorphicLayoutEffect(() => { + needsStart.current = false; + if (isRefPending(container) || isRefPending(target)) { + needsStart.current = true; + return; + } + else { + return start(); + } + }, [start]); + useEffect(() => { + if (needsStart.current) { + invariant(!isRefPending(container), "Container ref is defined but not hydrated", "use-scroll-ref"); + invariant(!isRefPending(target), "Target ref is defined but not hydrated", "use-scroll-ref"); + return start(); + } + else { + return; + } + }, [start]); + return values; +} + +export { useScroll }; diff --git a/frontend/node_modules/framer-motion/dist/es/value/use-spring.mjs b/frontend/node_modules/framer-motion/dist/es/value/use-spring.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1daac6e2a7c7278b4c112aab6d96651f61950663 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/value/use-spring.mjs @@ -0,0 +1,21 @@ +import { attachSpring, isMotionValue } from 'motion-dom'; +import { useContext, useInsertionEffect } from 'react'; +import { MotionConfigContext } from '../context/MotionConfigContext.mjs'; +import { useMotionValue } from './use-motion-value.mjs'; +import { useTransform } from './use-transform.mjs'; + +function useSpring(source, options = {}) { + const { isStatic } = useContext(MotionConfigContext); + const getFromSource = () => (isMotionValue(source) ? source.get() : source); + // isStatic will never change, allowing early hooks return + if (isStatic) { + return useTransform(getFromSource); + } + const value = useMotionValue(getFromSource()); + useInsertionEffect(() => { + return attachSpring(value, source, options); + }, [value, JSON.stringify(options)]); + return value; +} + +export { useSpring }; diff --git a/frontend/node_modules/framer-motion/dist/es/value/use-time.mjs b/frontend/node_modules/framer-motion/dist/es/value/use-time.mjs new file mode 100644 index 0000000000000000000000000000000000000000..390a5e460ebb8a79d6623ce150fc4f11cfa132d0 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/value/use-time.mjs @@ -0,0 +1,10 @@ +import { useAnimationFrame } from '../utils/use-animation-frame.mjs'; +import { useMotionValue } from './use-motion-value.mjs'; + +function useTime() { + const time = useMotionValue(0); + useAnimationFrame((t) => time.set(t)); + return time; +} + +export { useTime }; diff --git a/frontend/node_modules/framer-motion/dist/es/value/use-transform.mjs b/frontend/node_modules/framer-motion/dist/es/value/use-transform.mjs new file mode 100644 index 0000000000000000000000000000000000000000..eef2c2fe14b19785d209853dc78bddecbb15ac5d --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/value/use-transform.mjs @@ -0,0 +1,29 @@ +import { transform } from 'motion-dom'; +import { useConstant } from '../utils/use-constant.mjs'; +import { useCombineMotionValues } from './use-combine-values.mjs'; +import { useComputed } from './use-computed.mjs'; + +function useTransform(input, inputRangeOrTransformer, outputRange, options) { + if (typeof input === "function") { + return useComputed(input); + } + const transformer = typeof inputRangeOrTransformer === "function" + ? inputRangeOrTransformer + : transform(inputRangeOrTransformer, outputRange, options); + return Array.isArray(input) + ? useListTransform(input, transformer) + : useListTransform([input], ([latest]) => transformer(latest)); +} +function useListTransform(values, transformer) { + const latest = useConstant(() => []); + return useCombineMotionValues(values, () => { + latest.length = 0; + const numValues = values.length; + for (let i = 0; i < numValues; i++) { + latest[i] = values[i].get(); + } + return transformer(latest); + }); +} + +export { useTransform }; diff --git a/frontend/node_modules/framer-motion/dist/es/value/use-velocity.mjs b/frontend/node_modules/framer-motion/dist/es/value/use-velocity.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fd665f5669060cac388807e0f94f881f3bf1a360 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/value/use-velocity.mjs @@ -0,0 +1,35 @@ +import { frame } from 'motion-dom'; +import { useMotionValueEvent } from '../utils/use-motion-value-event.mjs'; +import { useMotionValue } from './use-motion-value.mjs'; + +/** + * Creates a `MotionValue` that updates when the velocity of the provided `MotionValue` changes. + * + * ```javascript + * const x = useMotionValue(0) + * const xVelocity = useVelocity(x) + * const xAcceleration = useVelocity(xVelocity) + * ``` + * + * @public + */ +function useVelocity(value) { + const velocity = useMotionValue(value.getVelocity()); + const updateVelocity = () => { + const latest = value.getVelocity(); + velocity.set(latest); + /** + * If we still have velocity, schedule an update for the next frame + * to keep checking until it is zero. + */ + if (latest) + frame.update(updateVelocity); + }; + useMotionValueEvent(value, "change", () => { + // Schedule an update to this value at the end of the current frame. + frame.update(updateVelocity, false, true); + }); + return velocity; +} + +export { useVelocity }; diff --git a/frontend/node_modules/framer-motion/dist/es/value/use-will-change/WillChangeMotionValue.mjs b/frontend/node_modules/framer-motion/dist/es/value/use-will-change/WillChangeMotionValue.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3e49bbd36a1e99e2a9ca484ad683d33abdf56e83 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/value/use-will-change/WillChangeMotionValue.mjs @@ -0,0 +1,19 @@ +import { MotionValue, transformProps, acceleratedValues } from 'motion-dom'; + +class WillChangeMotionValue extends MotionValue { + constructor() { + super(...arguments); + this.isEnabled = false; + } + add(name) { + if (transformProps.has(name) || acceleratedValues.has(name)) { + this.isEnabled = true; + this.update(); + } + } + update() { + this.set(this.isEnabled ? "transform" : "auto"); + } +} + +export { WillChangeMotionValue }; diff --git a/frontend/node_modules/framer-motion/dist/es/value/use-will-change/add-will-change.mjs b/frontend/node_modules/framer-motion/dist/es/value/use-will-change/add-will-change.mjs new file mode 100644 index 0000000000000000000000000000000000000000..001d97014c458dbdd3f45b78069e94a747a8fb38 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/value/use-will-change/add-will-change.mjs @@ -0,0 +1,20 @@ +import { MotionGlobalConfig } from 'motion-utils'; +import { isWillChangeMotionValue } from './is.mjs'; + +function addValueToWillChange(visualElement, key) { + const willChange = visualElement.getValue("willChange"); + /** + * It could be that a user has set willChange to a regular MotionValue, + * in which case we can't add the value to it. + */ + if (isWillChangeMotionValue(willChange)) { + return willChange.add(key); + } + else if (!willChange && MotionGlobalConfig.WillChange) { + const newWillChange = new MotionGlobalConfig.WillChange("auto"); + visualElement.addValue("willChange", newWillChange); + newWillChange.add(key); + } +} + +export { addValueToWillChange }; diff --git a/frontend/node_modules/framer-motion/dist/es/value/use-will-change/index.mjs b/frontend/node_modules/framer-motion/dist/es/value/use-will-change/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..356a94d682bf9e5be3050343e911e9aa52d31045 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/value/use-will-change/index.mjs @@ -0,0 +1,8 @@ +import { useConstant } from '../../utils/use-constant.mjs'; +import { WillChangeMotionValue } from './WillChangeMotionValue.mjs'; + +function useWillChange() { + return useConstant(() => new WillChangeMotionValue("auto")); +} + +export { useWillChange }; diff --git a/frontend/node_modules/framer-motion/dist/es/value/use-will-change/is.mjs b/frontend/node_modules/framer-motion/dist/es/value/use-will-change/is.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a5502f9a1b29ef1fbf0e710d9f75e985c4b08311 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/value/use-will-change/is.mjs @@ -0,0 +1,7 @@ +import { isMotionValue } from 'motion-dom'; + +function isWillChangeMotionValue(value) { + return Boolean(isMotionValue(value) && value.add); +} + +export { isWillChangeMotionValue }; diff --git a/frontend/node_modules/framer-motion/dist/es/value/utils/resolve-motion-value.mjs b/frontend/node_modules/framer-motion/dist/es/value/utils/resolve-motion-value.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8cdd4b2e861521d8bb7ec6a30288b27411c923fd --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/es/value/utils/resolve-motion-value.mjs @@ -0,0 +1,12 @@ +import { isMotionValue } from 'motion-dom'; + +/** + * If the provided value is a MotionValue, this returns the actual value, otherwise just the value itself + * + * TODO: Remove and move to library + */ +function resolveMotionValue(value) { + return isMotionValue(value) ? value.get() : value; +} + +export { resolveMotionValue }; diff --git a/frontend/node_modules/framer-motion/dist/framer-motion.dev.js b/frontend/node_modules/framer-motion/dist/framer-motion.dev.js new file mode 100644 index 0000000000000000000000000000000000000000..fe59edf24b5d026987a1c6b678f8d28274255230 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/framer-motion.dev.js @@ -0,0 +1,14319 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : + typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Motion = {}, global.React)); +})(this, (function (exports, React$1) { 'use strict'; + + function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); + } + + var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React$1); + + // source: react/cjs/react-jsx-runtime.production.min.js + /** + * @license React + * react-jsx-runtime.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + var f = React, + k = Symbol.for("react.element"), + l = Symbol.for("react.fragment"), + m$1 = Object.prototype.hasOwnProperty, + n = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, + p = { key: !0, ref: !0, __self: !0, __source: !0 }; + function q(c, a, g) { + var b, + d = {}, + e = null, + h = null; + void 0 !== g && (e = "" + g); + void 0 !== a.key && (e = "" + a.key); + void 0 !== a.ref && (h = a.ref); + for (b in a) m$1.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]); + if (c && c.defaultProps) + for (b in ((a = c.defaultProps), a)) void 0 === d[b] && (d[b] = a[b]); + return { $$typeof: k, type: c, key: e, ref: h, props: d, _owner: n.current } + } + const Fragment = l; + const jsx = q; + const jsxs = q; + + const LayoutGroupContext = React$1.createContext({}); + + /** + * Creates a constant value over the lifecycle of a component. + * + * Even if `useMemo` is provided an empty array as its final argument, it doesn't offer + * a guarantee that it won't re-run for performance reasons later on. By using `useConstant` + * you can ensure that initialisers don't execute twice or more. + */ + function useConstant(init) { + const ref = React$1.useRef(null); + if (ref.current === null) { + ref.current = init(); + } + return ref.current; + } + + const isBrowser = typeof window !== "undefined"; + + const useIsomorphicLayoutEffect = isBrowser ? React$1.useLayoutEffect : React$1.useEffect; + + /** + * @public + */ + const PresenceContext = + /* @__PURE__ */ React$1.createContext(null); + + function addUniqueItem(arr, item) { + if (arr.indexOf(item) === -1) + arr.push(item); + } + function removeItem(arr, item) { + const index = arr.indexOf(item); + if (index > -1) + arr.splice(index, 1); + } + // Adapted from array-move + function moveItem([...arr], fromIndex, toIndex) { + const startIndex = fromIndex < 0 ? arr.length + fromIndex : fromIndex; + if (startIndex >= 0 && startIndex < arr.length) { + const endIndex = toIndex < 0 ? arr.length + toIndex : toIndex; + const [item] = arr.splice(fromIndex, 1); + arr.splice(endIndex, 0, item); + } + return arr; + } + + const clamp = (min, max, v) => { + if (v > max) + return max; + if (v < min) + return min; + return v; + }; + + function formatErrorMessage(message, errorCode) { + return errorCode + ? `${message}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${errorCode}` + : message; + } + + exports.warning = () => { }; + exports.invariant = () => { }; + { + exports.warning = (check, message, errorCode) => { + if (!check && typeof console !== "undefined") { + console.warn(formatErrorMessage(message, errorCode)); + } + }; + exports.invariant = (check, message, errorCode) => { + if (!check) { + throw new Error(formatErrorMessage(message, errorCode)); + } + }; + } + + const MotionGlobalConfig = {}; + + /** + * Check if value is a numerical string, ie a string that is purely a number eg "100" or "-100.1" + */ + const isNumericalString = (v) => /^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(v); + + function isObject(value) { + return typeof value === "object" && value !== null; + } + + /** + * Check if the value is a zero value string like "0px" or "0%" + */ + const isZeroValueString = (v) => /^0[^.\s]+$/u.test(v); + + /*#__NO_SIDE_EFFECTS__*/ + function memo(callback) { + let result; + return () => { + if (result === undefined) + result = callback(); + return result; + }; + } + + /*#__NO_SIDE_EFFECTS__*/ + const noop = (any) => any; + + /** + * Pipe + * Compose other transformers to run linearily + * pipe(min(20), max(40)) + * @param {...functions} transformers + * @return {function} + */ + const combineFunctions = (a, b) => (v) => b(a(v)); + const pipe = (...transformers) => transformers.reduce(combineFunctions); + + /* + Progress within given range + + Given a lower limit and an upper limit, we return the progress + (expressed as a number 0-1) represented by the given value, and + limit that progress to within 0-1. + + @param [number]: Lower limit + @param [number]: Upper limit + @param [number]: Value to find progress within given range + @return [number]: Progress of value within range as expressed 0-1 + */ + /*#__NO_SIDE_EFFECTS__*/ + const progress = (from, to, value) => { + const toFromDifference = to - from; + return toFromDifference === 0 ? 1 : (value - from) / toFromDifference; + }; + + class SubscriptionManager { + constructor() { + this.subscriptions = []; + } + add(handler) { + addUniqueItem(this.subscriptions, handler); + return () => removeItem(this.subscriptions, handler); + } + notify(a, b, c) { + const numSubscriptions = this.subscriptions.length; + if (!numSubscriptions) + return; + if (numSubscriptions === 1) { + /** + * If there's only a single handler we can just call it without invoking a loop. + */ + this.subscriptions[0](a, b, c); + } + else { + for (let i = 0; i < numSubscriptions; i++) { + /** + * Check whether the handler exists before firing as it's possible + * the subscriptions were modified during this loop running. + */ + const handler = this.subscriptions[i]; + handler && handler(a, b, c); + } + } + } + getSize() { + return this.subscriptions.length; + } + clear() { + this.subscriptions.length = 0; + } + } + + /** + * Converts seconds to milliseconds + * + * @param seconds - Time in seconds. + * @return milliseconds - Converted time in milliseconds. + */ + /*#__NO_SIDE_EFFECTS__*/ + const secondsToMilliseconds = (seconds) => seconds * 1000; + /*#__NO_SIDE_EFFECTS__*/ + const millisecondsToSeconds = (milliseconds) => milliseconds / 1000; + + /* + Convert velocity into velocity per second + + @param [number]: Unit per frame + @param [number]: Frame duration in ms + */ + function velocityPerSecond(velocity, frameDuration) { + return frameDuration ? velocity * (1000 / frameDuration) : 0; + } + + const warned = new Set(); + function hasWarned$1(message) { + return warned.has(message); + } + function warnOnce(condition, message, errorCode) { + if (condition || warned.has(message)) + return; + console.warn(formatErrorMessage(message, errorCode)); + warned.add(message); + } + + const wrap = (min, max, v) => { + const rangeSize = max - min; + return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min; + }; + + /* + Bezier function generator + This has been modified from Gaëtan Renaudeau's BezierEasing + https://github.com/gre/bezier-easing/blob/master/src/index.js + https://github.com/gre/bezier-easing/blob/master/LICENSE + + I've removed the newtonRaphsonIterate algo because in benchmarking it + wasn't noticeably faster than binarySubdivision, indeed removing it + usually improved times, depending on the curve. + I also removed the lookup table, as for the added bundle size and loop we're + only cutting ~4 or so subdivision iterations. I bumped the max iterations up + to 12 to compensate and this still tended to be faster for no perceivable + loss in accuracy. + Usage + const easeOut = cubicBezier(.17,.67,.83,.67); + const x = easeOut(0.5); // returns 0.627... + */ + // Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2. + const calcBezier = (t, a1, a2) => (((1.0 - 3.0 * a2 + 3.0 * a1) * t + (3.0 * a2 - 6.0 * a1)) * t + 3.0 * a1) * + t; + const subdivisionPrecision = 0.0000001; + const subdivisionMaxIterations = 12; + function binarySubdivide(x, lowerBound, upperBound, mX1, mX2) { + let currentX; + let currentT; + let i = 0; + do { + currentT = lowerBound + (upperBound - lowerBound) / 2.0; + currentX = calcBezier(currentT, mX1, mX2) - x; + if (currentX > 0.0) { + upperBound = currentT; + } + else { + lowerBound = currentT; + } + } while (Math.abs(currentX) > subdivisionPrecision && + ++i < subdivisionMaxIterations); + return currentT; + } + function cubicBezier(mX1, mY1, mX2, mY2) { + // If this is a linear gradient, return linear easing + if (mX1 === mY1 && mX2 === mY2) + return noop; + const getTForX = (aX) => binarySubdivide(aX, 0, 1, mX1, mX2); + // If animation is at start/end, return t without easing + return (t) => t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2); + } + + // Accepts an easing function and returns a new one that outputs mirrored values for + // the second half of the animation. Turns easeIn into easeInOut. + const mirrorEasing = (easing) => (p) => p <= 0.5 ? easing(2 * p) / 2 : (2 - easing(2 * (1 - p))) / 2; + + // Accepts an easing function and returns a new one that outputs reversed values. + // Turns easeIn into easeOut. + const reverseEasing = (easing) => (p) => 1 - easing(1 - p); + + const backOut = /*@__PURE__*/ cubicBezier(0.33, 1.53, 0.69, 0.99); + const backIn = /*@__PURE__*/ reverseEasing(backOut); + const backInOut = /*@__PURE__*/ mirrorEasing(backIn); + + const anticipate = (p) => (p *= 2) < 1 ? 0.5 * backIn(p) : 0.5 * (2 - Math.pow(2, -10 * (p - 1))); + + const circIn = (p) => 1 - Math.sin(Math.acos(p)); + const circOut = reverseEasing(circIn); + const circInOut = mirrorEasing(circIn); + + const easeIn = /*@__PURE__*/ cubicBezier(0.42, 0, 1, 1); + const easeOut = /*@__PURE__*/ cubicBezier(0, 0, 0.58, 1); + const easeInOut = /*@__PURE__*/ cubicBezier(0.42, 0, 0.58, 1); + + function steps(numSteps, direction = "end") { + return (progress) => { + progress = + direction === "end" + ? Math.min(progress, 0.999) + : Math.max(progress, 0.001); + const expanded = progress * numSteps; + const rounded = direction === "end" ? Math.floor(expanded) : Math.ceil(expanded); + return clamp(0, 1, rounded / numSteps); + }; + } + + const isEasingArray = (ease) => { + return Array.isArray(ease) && typeof ease[0] !== "number"; + }; + + function getEasingForSegment(easing, i) { + return isEasingArray(easing) ? easing[wrap(0, easing.length, i)] : easing; + } + + const isBezierDefinition = (easing) => Array.isArray(easing) && typeof easing[0] === "number"; + + const easingLookup = { + linear: noop, + easeIn, + easeInOut, + easeOut, + circIn, + circInOut, + circOut, + backIn, + backInOut, + backOut, + anticipate, + }; + const isValidEasing = (easing) => { + return typeof easing === "string"; + }; + const easingDefinitionToFunction = (definition) => { + if (isBezierDefinition(definition)) { + // If cubic bezier definition, create bezier curve + exports.invariant(definition.length === 4, `Cubic bezier arrays must contain four numerical values.`, "cubic-bezier-length"); + const [x1, y1, x2, y2] = definition; + return cubicBezier(x1, y1, x2, y2); + } + else if (isValidEasing(definition)) { + // Else lookup from table + exports.invariant(easingLookup[definition] !== undefined, `Invalid easing type '${definition}'`, "invalid-easing-type"); + return easingLookup[definition]; + } + return definition; + }; + + const stepsOrder = [ + "setup", // Compute + "read", // Read + "resolveKeyframes", // Write/Read/Write/Read + "preUpdate", // Compute + "update", // Compute + "preRender", // Compute + "render", // Write + "postRender", // Compute + ]; + + const statsBuffer = { + value: null, + addProjectionMetrics: null, + }; + + function createRenderStep(runNextFrame, stepName) { + /** + * We create and reuse two queues, one to queue jobs for the current frame + * and one for the next. We reuse to avoid triggering GC after x frames. + */ + let thisFrame = new Set(); + let nextFrame = new Set(); + /** + * Track whether we're currently processing jobs in this step. This way + * we can decide whether to schedule new jobs for this frame or next. + */ + let isProcessing = false; + let flushNextFrame = false; + /** + * A set of processes which were marked keepAlive when scheduled. + */ + const toKeepAlive = new WeakSet(); + let latestFrameData = { + delta: 0.0, + timestamp: 0.0, + isProcessing: false, + }; + let numCalls = 0; + function triggerCallback(callback) { + if (toKeepAlive.has(callback)) { + step.schedule(callback); + runNextFrame(); + } + numCalls++; + callback(latestFrameData); + } + const step = { + /** + * Schedule a process to run on the next frame. + */ + schedule: (callback, keepAlive = false, immediate = false) => { + const addToCurrentFrame = immediate && isProcessing; + const queue = addToCurrentFrame ? thisFrame : nextFrame; + if (keepAlive) + toKeepAlive.add(callback); + if (!queue.has(callback)) + queue.add(callback); + return callback; + }, + /** + * Cancel the provided callback from running on the next frame. + */ + cancel: (callback) => { + nextFrame.delete(callback); + toKeepAlive.delete(callback); + }, + /** + * Execute all schedule callbacks. + */ + process: (frameData) => { + latestFrameData = frameData; + /** + * If we're already processing we've probably been triggered by a flushSync + * inside an existing process. Instead of executing, mark flushNextFrame + * as true and ensure we flush the following frame at the end of this one. + */ + if (isProcessing) { + flushNextFrame = true; + return; + } + isProcessing = true; + [thisFrame, nextFrame] = [nextFrame, thisFrame]; + // Execute this frame + thisFrame.forEach(triggerCallback); + /** + * If we're recording stats then + */ + if (stepName && statsBuffer.value) { + statsBuffer.value.frameloop[stepName].push(numCalls); + } + numCalls = 0; + // Clear the frame so no callbacks remain. This is to avoid + // memory leaks should this render step not run for a while. + thisFrame.clear(); + isProcessing = false; + if (flushNextFrame) { + flushNextFrame = false; + step.process(frameData); + } + }, + }; + return step; + } + + const maxElapsed$1 = 40; + function createRenderBatcher(scheduleNextBatch, allowKeepAlive) { + let runNextFrame = false; + let useDefaultElapsed = true; + const state = { + delta: 0.0, + timestamp: 0.0, + isProcessing: false, + }; + const flagRunNextFrame = () => (runNextFrame = true); + const steps = stepsOrder.reduce((acc, key) => { + acc[key] = createRenderStep(flagRunNextFrame, allowKeepAlive ? key : undefined); + return acc; + }, {}); + const { setup, read, resolveKeyframes, preUpdate, update, preRender, render, postRender, } = steps; + const processBatch = () => { + const timestamp = MotionGlobalConfig.useManualTiming + ? state.timestamp + : performance.now(); + runNextFrame = false; + if (!MotionGlobalConfig.useManualTiming) { + state.delta = useDefaultElapsed + ? 1000 / 60 + : Math.max(Math.min(timestamp - state.timestamp, maxElapsed$1), 1); + } + state.timestamp = timestamp; + state.isProcessing = true; + // Unrolled render loop for better per-frame performance + setup.process(state); + read.process(state); + resolveKeyframes.process(state); + preUpdate.process(state); + update.process(state); + preRender.process(state); + render.process(state); + postRender.process(state); + state.isProcessing = false; + if (runNextFrame && allowKeepAlive) { + useDefaultElapsed = false; + scheduleNextBatch(processBatch); + } + }; + const wake = () => { + runNextFrame = true; + useDefaultElapsed = true; + if (!state.isProcessing) { + scheduleNextBatch(processBatch); + } + }; + const schedule = stepsOrder.reduce((acc, key) => { + const step = steps[key]; + acc[key] = (process, keepAlive = false, immediate = false) => { + if (!runNextFrame) + wake(); + return step.schedule(process, keepAlive, immediate); + }; + return acc; + }, {}); + const cancel = (process) => { + for (let i = 0; i < stepsOrder.length; i++) { + steps[stepsOrder[i]].cancel(process); + } + }; + return { schedule, cancel, state, steps }; + } + + const { schedule: frame, cancel: cancelFrame, state: frameData, steps: frameSteps, } = /* @__PURE__ */ createRenderBatcher(typeof requestAnimationFrame !== "undefined" ? requestAnimationFrame : noop, true); + + let now; + function clearTime() { + now = undefined; + } + /** + * An eventloop-synchronous alternative to performance.now(). + * + * Ensures that time measurements remain consistent within a synchronous context. + * Usually calling performance.now() twice within the same synchronous context + * will return different values which isn't useful for animations when we're usually + * trying to sync animations to the same frame. + */ + const time = { + now: () => { + if (now === undefined) { + time.set(frameData.isProcessing || MotionGlobalConfig.useManualTiming + ? frameData.timestamp + : performance.now()); + } + return now; + }, + set: (newTime) => { + now = newTime; + queueMicrotask(clearTime); + }, + }; + + const activeAnimations = { + layout: 0, + mainThread: 0, + waapi: 0, + }; + + const checkStringStartsWith = (token) => (key) => typeof key === "string" && key.startsWith(token); + const isCSSVariableName = + /*@__PURE__*/ checkStringStartsWith("--"); + const startsAsVariableToken = + /*@__PURE__*/ checkStringStartsWith("var(--"); + const isCSSVariableToken = (value) => { + const startsWithToken = startsAsVariableToken(value); + if (!startsWithToken) + return false; + // Ensure any comments are stripped from the value as this can harm performance of the regex. + return singleCssVariableRegex.test(value.split("/*")[0].trim()); + }; + const singleCssVariableRegex = /var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu; + + const number = { + test: (v) => typeof v === "number", + parse: parseFloat, + transform: (v) => v, + }; + const alpha = { + ...number, + transform: (v) => clamp(0, 1, v), + }; + const scale = { + ...number, + default: 1, + }; + + // If this number is a decimal, make it just five decimal places + // to avoid exponents + const sanitize = (v) => Math.round(v * 100000) / 100000; + + const floatRegex = /-?(?:\d+(?:\.\d+)?|\.\d+)/gu; + + function isNullish(v) { + return v == null; + } + + const singleColorRegex = /^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu; + + /** + * Returns true if the provided string is a color, ie rgba(0,0,0,0) or #000, + * but false if a number or multiple colors + */ + const isColorString = (type, testProp) => (v) => { + return Boolean((typeof v === "string" && + singleColorRegex.test(v) && + v.startsWith(type)) || + (testProp && + !isNullish(v) && + Object.prototype.hasOwnProperty.call(v, testProp))); + }; + const splitColor = (aName, bName, cName) => (v) => { + if (typeof v !== "string") + return v; + const [a, b, c, alpha] = v.match(floatRegex); + return { + [aName]: parseFloat(a), + [bName]: parseFloat(b), + [cName]: parseFloat(c), + alpha: alpha !== undefined ? parseFloat(alpha) : 1, + }; + }; + + const clampRgbUnit = (v) => clamp(0, 255, v); + const rgbUnit = { + ...number, + transform: (v) => Math.round(clampRgbUnit(v)), + }; + const rgba = { + test: /*@__PURE__*/ isColorString("rgb", "red"), + parse: /*@__PURE__*/ splitColor("red", "green", "blue"), + transform: ({ red, green, blue, alpha: alpha$1 = 1 }) => "rgba(" + + rgbUnit.transform(red) + + ", " + + rgbUnit.transform(green) + + ", " + + rgbUnit.transform(blue) + + ", " + + sanitize(alpha.transform(alpha$1)) + + ")", + }; + + function parseHex(v) { + let r = ""; + let g = ""; + let b = ""; + let a = ""; + // If we have 6 characters, ie #FF0000 + if (v.length > 5) { + r = v.substring(1, 3); + g = v.substring(3, 5); + b = v.substring(5, 7); + a = v.substring(7, 9); + // Or we have 3 characters, ie #F00 + } + else { + r = v.substring(1, 2); + g = v.substring(2, 3); + b = v.substring(3, 4); + a = v.substring(4, 5); + r += r; + g += g; + b += b; + a += a; + } + return { + red: parseInt(r, 16), + green: parseInt(g, 16), + blue: parseInt(b, 16), + alpha: a ? parseInt(a, 16) / 255 : 1, + }; + } + const hex = { + test: /*@__PURE__*/ isColorString("#"), + parse: parseHex, + transform: rgba.transform, + }; + + /*#__NO_SIDE_EFFECTS__*/ + const createUnitType = (unit) => ({ + test: (v) => typeof v === "string" && v.endsWith(unit) && v.split(" ").length === 1, + parse: parseFloat, + transform: (v) => `${v}${unit}`, + }); + const degrees = /*@__PURE__*/ createUnitType("deg"); + const percent = /*@__PURE__*/ createUnitType("%"); + const px = /*@__PURE__*/ createUnitType("px"); + const vh = /*@__PURE__*/ createUnitType("vh"); + const vw = /*@__PURE__*/ createUnitType("vw"); + const progressPercentage = /*@__PURE__*/ (() => ({ + ...percent, + parse: (v) => percent.parse(v) / 100, + transform: (v) => percent.transform(v * 100), + }))(); + + const hsla = { + test: /*@__PURE__*/ isColorString("hsl", "hue"), + parse: /*@__PURE__*/ splitColor("hue", "saturation", "lightness"), + transform: ({ hue, saturation, lightness, alpha: alpha$1 = 1 }) => { + return ("hsla(" + + Math.round(hue) + + ", " + + percent.transform(sanitize(saturation)) + + ", " + + percent.transform(sanitize(lightness)) + + ", " + + sanitize(alpha.transform(alpha$1)) + + ")"); + }, + }; + + const color = { + test: (v) => rgba.test(v) || hex.test(v) || hsla.test(v), + parse: (v) => { + if (rgba.test(v)) { + return rgba.parse(v); + } + else if (hsla.test(v)) { + return hsla.parse(v); + } + else { + return hex.parse(v); + } + }, + transform: (v) => { + return typeof v === "string" + ? v + : v.hasOwnProperty("red") + ? rgba.transform(v) + : hsla.transform(v); + }, + getAnimatableNone: (v) => { + const parsed = color.parse(v); + parsed.alpha = 0; + return color.transform(parsed); + }, + }; + + const colorRegex = /(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu; + + function test(v) { + return (isNaN(v) && + typeof v === "string" && + (v.match(floatRegex)?.length || 0) + + (v.match(colorRegex)?.length || 0) > + 0); + } + const NUMBER_TOKEN = "number"; + const COLOR_TOKEN = "color"; + const VAR_TOKEN = "var"; + const VAR_FUNCTION_TOKEN = "var("; + const SPLIT_TOKEN = "${}"; + // this regex consists of the `singleCssVariableRegex|rgbHSLValueRegex|digitRegex` + const complexRegex = /var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu; + function analyseComplexValue(value) { + const originalValue = value.toString(); + const values = []; + const indexes = { + color: [], + number: [], + var: [], + }; + const types = []; + let i = 0; + const tokenised = originalValue.replace(complexRegex, (parsedValue) => { + if (color.test(parsedValue)) { + indexes.color.push(i); + types.push(COLOR_TOKEN); + values.push(color.parse(parsedValue)); + } + else if (parsedValue.startsWith(VAR_FUNCTION_TOKEN)) { + indexes.var.push(i); + types.push(VAR_TOKEN); + values.push(parsedValue); + } + else { + indexes.number.push(i); + types.push(NUMBER_TOKEN); + values.push(parseFloat(parsedValue)); + } + ++i; + return SPLIT_TOKEN; + }); + const split = tokenised.split(SPLIT_TOKEN); + return { values, split, indexes, types }; + } + function parseComplexValue(v) { + return analyseComplexValue(v).values; + } + function createTransformer(source) { + const { split, types } = analyseComplexValue(source); + const numSections = split.length; + return (v) => { + let output = ""; + for (let i = 0; i < numSections; i++) { + output += split[i]; + if (v[i] !== undefined) { + const type = types[i]; + if (type === NUMBER_TOKEN) { + output += sanitize(v[i]); + } + else if (type === COLOR_TOKEN) { + output += color.transform(v[i]); + } + else { + output += v[i]; + } + } + } + return output; + }; + } + const convertNumbersToZero = (v) => typeof v === "number" ? 0 : color.test(v) ? color.getAnimatableNone(v) : v; + function getAnimatableNone$1(v) { + const parsed = parseComplexValue(v); + const transformer = createTransformer(v); + return transformer(parsed.map(convertNumbersToZero)); + } + const complex = { + test, + parse: parseComplexValue, + createTransformer, + getAnimatableNone: getAnimatableNone$1, + }; + + // Adapted from https://gist.github.com/mjackson/5311256 + function hueToRgb(p, q, t) { + if (t < 0) + t += 1; + if (t > 1) + t -= 1; + if (t < 1 / 6) + return p + (q - p) * 6 * t; + if (t < 1 / 2) + return q; + if (t < 2 / 3) + return p + (q - p) * (2 / 3 - t) * 6; + return p; + } + function hslaToRgba({ hue, saturation, lightness, alpha }) { + hue /= 360; + saturation /= 100; + lightness /= 100; + let red = 0; + let green = 0; + let blue = 0; + if (!saturation) { + red = green = blue = lightness; + } + else { + const q = lightness < 0.5 + ? lightness * (1 + saturation) + : lightness + saturation - lightness * saturation; + const p = 2 * lightness - q; + red = hueToRgb(p, q, hue + 1 / 3); + green = hueToRgb(p, q, hue); + blue = hueToRgb(p, q, hue - 1 / 3); + } + return { + red: Math.round(red * 255), + green: Math.round(green * 255), + blue: Math.round(blue * 255), + alpha, + }; + } + + function mixImmediate(a, b) { + return (p) => (p > 0 ? b : a); + } + + /* + Value in range from progress + + Given a lower limit and an upper limit, we return the value within + that range as expressed by progress (usually a number from 0 to 1) + + So progress = 0.5 would change + + from -------- to + + to + + from ---- to + + E.g. from = 10, to = 20, progress = 0.5 => 15 + + @param [number]: Lower limit of range + @param [number]: Upper limit of range + @param [number]: The progress between lower and upper limits expressed 0-1 + @return [number]: Value as calculated from progress within range (not limited within range) + */ + const mixNumber$1 = (from, to, progress) => { + return from + (to - from) * progress; + }; + + // Linear color space blending + // Explained https://www.youtube.com/watch?v=LKnqECcg6Gw + // Demonstrated http://codepen.io/osublake/pen/xGVVaN + const mixLinearColor = (from, to, v) => { + const fromExpo = from * from; + const expo = v * (to * to - fromExpo) + fromExpo; + return expo < 0 ? 0 : Math.sqrt(expo); + }; + const colorTypes = [hex, rgba, hsla]; + const getColorType = (v) => colorTypes.find((type) => type.test(v)); + function asRGBA(color) { + const type = getColorType(color); + exports.warning(Boolean(type), `'${color}' is not an animatable color. Use the equivalent color code instead.`, "color-not-animatable"); + if (!Boolean(type)) + return false; + let model = type.parse(color); + if (type === hsla) { + // TODO Remove this cast - needed since Motion's stricter typing + model = hslaToRgba(model); + } + return model; + } + const mixColor = (from, to) => { + const fromRGBA = asRGBA(from); + const toRGBA = asRGBA(to); + if (!fromRGBA || !toRGBA) { + return mixImmediate(from, to); + } + const blended = { ...fromRGBA }; + return (v) => { + blended.red = mixLinearColor(fromRGBA.red, toRGBA.red, v); + blended.green = mixLinearColor(fromRGBA.green, toRGBA.green, v); + blended.blue = mixLinearColor(fromRGBA.blue, toRGBA.blue, v); + blended.alpha = mixNumber$1(fromRGBA.alpha, toRGBA.alpha, v); + return rgba.transform(blended); + }; + }; + + const invisibleValues = new Set(["none", "hidden"]); + /** + * Returns a function that, when provided a progress value between 0 and 1, + * will return the "none" or "hidden" string only when the progress is that of + * the origin or target. + */ + function mixVisibility(origin, target) { + if (invisibleValues.has(origin)) { + return (p) => (p <= 0 ? origin : target); + } + else { + return (p) => (p >= 1 ? target : origin); + } + } + + function mixNumber(a, b) { + return (p) => mixNumber$1(a, b, p); + } + function getMixer(a) { + if (typeof a === "number") { + return mixNumber; + } + else if (typeof a === "string") { + return isCSSVariableToken(a) + ? mixImmediate + : color.test(a) + ? mixColor + : mixComplex; + } + else if (Array.isArray(a)) { + return mixArray; + } + else if (typeof a === "object") { + return color.test(a) ? mixColor : mixObject; + } + return mixImmediate; + } + function mixArray(a, b) { + const output = [...a]; + const numValues = output.length; + const blendValue = a.map((v, i) => getMixer(v)(v, b[i])); + return (p) => { + for (let i = 0; i < numValues; i++) { + output[i] = blendValue[i](p); + } + return output; + }; + } + function mixObject(a, b) { + const output = { ...a, ...b }; + const blendValue = {}; + for (const key in output) { + if (a[key] !== undefined && b[key] !== undefined) { + blendValue[key] = getMixer(a[key])(a[key], b[key]); + } + } + return (v) => { + for (const key in blendValue) { + output[key] = blendValue[key](v); + } + return output; + }; + } + function matchOrder(origin, target) { + const orderedOrigin = []; + const pointers = { color: 0, var: 0, number: 0 }; + for (let i = 0; i < target.values.length; i++) { + const type = target.types[i]; + const originIndex = origin.indexes[type][pointers[type]]; + const originValue = origin.values[originIndex] ?? 0; + orderedOrigin[i] = originValue; + pointers[type]++; + } + return orderedOrigin; + } + const mixComplex = (origin, target) => { + const template = complex.createTransformer(target); + const originStats = analyseComplexValue(origin); + const targetStats = analyseComplexValue(target); + const canInterpolate = originStats.indexes.var.length === targetStats.indexes.var.length && + originStats.indexes.color.length === targetStats.indexes.color.length && + originStats.indexes.number.length >= targetStats.indexes.number.length; + if (canInterpolate) { + if ((invisibleValues.has(origin) && + !targetStats.values.length) || + (invisibleValues.has(target) && + !originStats.values.length)) { + return mixVisibility(origin, target); + } + return pipe(mixArray(matchOrder(originStats, targetStats), targetStats.values), template); + } + else { + exports.warning(true, `Complex values '${origin}' and '${target}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`, "complex-values-different"); + return mixImmediate(origin, target); + } + }; + + function mix(from, to, p) { + if (typeof from === "number" && + typeof to === "number" && + typeof p === "number") { + return mixNumber$1(from, to, p); + } + const mixer = getMixer(from); + return mixer(from, to); + } + + const frameloopDriver = (update) => { + const passTimestamp = ({ timestamp }) => update(timestamp); + return { + start: (keepAlive = true) => frame.update(passTimestamp, keepAlive), + stop: () => cancelFrame(passTimestamp), + /** + * If we're processing this frame we can use the + * framelocked timestamp to keep things in sync. + */ + now: () => (frameData.isProcessing ? frameData.timestamp : time.now()), + }; + }; + + const generateLinearEasing = (easing, duration, // as milliseconds + resolution = 10 // as milliseconds + ) => { + let points = ""; + const numPoints = Math.max(Math.round(duration / resolution), 2); + for (let i = 0; i < numPoints; i++) { + points += Math.round(easing(i / (numPoints - 1)) * 10000) / 10000 + ", "; + } + return `linear(${points.substring(0, points.length - 2)})`; + }; + + /** + * Implement a practical max duration for keyframe generation + * to prevent infinite loops + */ + const maxGeneratorDuration = 20000; + function calcGeneratorDuration(generator) { + let duration = 0; + const timeStep = 50; + let state = generator.next(duration); + while (!state.done && duration < maxGeneratorDuration) { + duration += timeStep; + state = generator.next(duration); + } + return duration >= maxGeneratorDuration ? Infinity : duration; + } + + /** + * Create a progress => progress easing function from a generator. + */ + function createGeneratorEasing(options, scale = 100, createGenerator) { + const generator = createGenerator({ ...options, keyframes: [0, scale] }); + const duration = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration); + return { + type: "keyframes", + ease: (progress) => { + return generator.next(duration * progress).value / scale; + }, + duration: millisecondsToSeconds(duration), + }; + } + + const velocitySampleDuration = 5; // ms + function calcGeneratorVelocity(resolveValue, t, current) { + const prevT = Math.max(t - velocitySampleDuration, 0); + return velocityPerSecond(current - resolveValue(prevT), t - prevT); + } + + const springDefaults = { + // Default spring physics + stiffness: 100, + damping: 10, + mass: 1.0, + velocity: 0.0, + // Default duration/bounce-based options + duration: 800, // in ms + bounce: 0.3, + visualDuration: 0.3, // in seconds + // Rest thresholds + restSpeed: { + granular: 0.01, + default: 2, + }, + restDelta: { + granular: 0.005, + default: 0.5, + }, + // Limits + minDuration: 0.01, // in seconds + maxDuration: 10.0, // in seconds + minDamping: 0.05, + maxDamping: 1, + }; + + const safeMin = 0.001; + function findSpring({ duration = springDefaults.duration, bounce = springDefaults.bounce, velocity = springDefaults.velocity, mass = springDefaults.mass, }) { + let envelope; + let derivative; + exports.warning(duration <= secondsToMilliseconds(springDefaults.maxDuration), "Spring duration must be 10 seconds or less", "spring-duration-limit"); + let dampingRatio = 1 - bounce; + /** + * Restrict dampingRatio and duration to within acceptable ranges. + */ + dampingRatio = clamp(springDefaults.minDamping, springDefaults.maxDamping, dampingRatio); + duration = clamp(springDefaults.minDuration, springDefaults.maxDuration, millisecondsToSeconds(duration)); + if (dampingRatio < 1) { + /** + * Underdamped spring + */ + envelope = (undampedFreq) => { + const exponentialDecay = undampedFreq * dampingRatio; + const delta = exponentialDecay * duration; + const a = exponentialDecay - velocity; + const b = calcAngularFreq(undampedFreq, dampingRatio); + const c = Math.exp(-delta); + return safeMin - (a / b) * c; + }; + derivative = (undampedFreq) => { + const exponentialDecay = undampedFreq * dampingRatio; + const delta = exponentialDecay * duration; + const d = delta * velocity + velocity; + const e = Math.pow(dampingRatio, 2) * Math.pow(undampedFreq, 2) * duration; + const f = Math.exp(-delta); + const g = calcAngularFreq(Math.pow(undampedFreq, 2), dampingRatio); + const factor = -envelope(undampedFreq) + safeMin > 0 ? -1 : 1; + return (factor * ((d - e) * f)) / g; + }; + } + else { + /** + * Critically-damped spring + */ + envelope = (undampedFreq) => { + const a = Math.exp(-undampedFreq * duration); + const b = (undampedFreq - velocity) * duration + 1; + return -safeMin + a * b; + }; + derivative = (undampedFreq) => { + const a = Math.exp(-undampedFreq * duration); + const b = (velocity - undampedFreq) * (duration * duration); + return a * b; + }; + } + const initialGuess = 5 / duration; + const undampedFreq = approximateRoot(envelope, derivative, initialGuess); + duration = secondsToMilliseconds(duration); + if (isNaN(undampedFreq)) { + return { + stiffness: springDefaults.stiffness, + damping: springDefaults.damping, + duration, + }; + } + else { + const stiffness = Math.pow(undampedFreq, 2) * mass; + return { + stiffness, + damping: dampingRatio * 2 * Math.sqrt(mass * stiffness), + duration, + }; + } + } + const rootIterations = 12; + function approximateRoot(envelope, derivative, initialGuess) { + let result = initialGuess; + for (let i = 1; i < rootIterations; i++) { + result = result - envelope(result) / derivative(result); + } + return result; + } + function calcAngularFreq(undampedFreq, dampingRatio) { + return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio); + } + + const durationKeys = ["duration", "bounce"]; + const physicsKeys = ["stiffness", "damping", "mass"]; + function isSpringType(options, keys) { + return keys.some((key) => options[key] !== undefined); + } + function getSpringOptions(options) { + let springOptions = { + velocity: springDefaults.velocity, + stiffness: springDefaults.stiffness, + damping: springDefaults.damping, + mass: springDefaults.mass, + isResolvedFromDuration: false, + ...options, + }; + // stiffness/damping/mass overrides duration/bounce + if (!isSpringType(options, physicsKeys) && + isSpringType(options, durationKeys)) { + if (options.visualDuration) { + const visualDuration = options.visualDuration; + const root = (2 * Math.PI) / (visualDuration * 1.2); + const stiffness = root * root; + const damping = 2 * + clamp(0.05, 1, 1 - (options.bounce || 0)) * + Math.sqrt(stiffness); + springOptions = { + ...springOptions, + mass: springDefaults.mass, + stiffness, + damping, + }; + } + else { + const derived = findSpring(options); + springOptions = { + ...springOptions, + ...derived, + mass: springDefaults.mass, + }; + springOptions.isResolvedFromDuration = true; + } + } + return springOptions; + } + function spring(optionsOrVisualDuration = springDefaults.visualDuration, bounce = springDefaults.bounce) { + const options = typeof optionsOrVisualDuration !== "object" + ? { + visualDuration: optionsOrVisualDuration, + keyframes: [0, 1], + bounce, + } + : optionsOrVisualDuration; + let { restSpeed, restDelta } = options; + const origin = options.keyframes[0]; + const target = options.keyframes[options.keyframes.length - 1]; + /** + * This is the Iterator-spec return value. We ensure it's mutable rather than using a generator + * to reduce GC during animation. + */ + const state = { done: false, value: origin }; + const { stiffness, damping, mass, duration, velocity, isResolvedFromDuration, } = getSpringOptions({ + ...options, + velocity: -millisecondsToSeconds(options.velocity || 0), + }); + const initialVelocity = velocity || 0.0; + const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass)); + const initialDelta = target - origin; + const undampedAngularFreq = millisecondsToSeconds(Math.sqrt(stiffness / mass)); + /** + * If we're working on a granular scale, use smaller defaults for determining + * when the spring is finished. + * + * These defaults have been selected emprically based on what strikes a good + * ratio between feeling good and finishing as soon as changes are imperceptible. + */ + const isGranularScale = Math.abs(initialDelta) < 5; + restSpeed || (restSpeed = isGranularScale + ? springDefaults.restSpeed.granular + : springDefaults.restSpeed.default); + restDelta || (restDelta = isGranularScale + ? springDefaults.restDelta.granular + : springDefaults.restDelta.default); + let resolveSpring; + if (dampingRatio < 1) { + const angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio); + // Underdamped spring + resolveSpring = (t) => { + const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); + return (target - + envelope * + (((initialVelocity + + dampingRatio * undampedAngularFreq * initialDelta) / + angularFreq) * + Math.sin(angularFreq * t) + + initialDelta * Math.cos(angularFreq * t))); + }; + } + else if (dampingRatio === 1) { + // Critically damped spring + resolveSpring = (t) => target - + Math.exp(-undampedAngularFreq * t) * + (initialDelta + + (initialVelocity + undampedAngularFreq * initialDelta) * t); + } + else { + // Overdamped spring + const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1); + resolveSpring = (t) => { + const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); + // When performing sinh or cosh values can hit Infinity so we cap them here + const freqForT = Math.min(dampedAngularFreq * t, 300); + return (target - + (envelope * + ((initialVelocity + + dampingRatio * undampedAngularFreq * initialDelta) * + Math.sinh(freqForT) + + dampedAngularFreq * + initialDelta * + Math.cosh(freqForT))) / + dampedAngularFreq); + }; + } + const generator = { + calculatedDuration: isResolvedFromDuration ? duration || null : null, + next: (t) => { + const current = resolveSpring(t); + if (!isResolvedFromDuration) { + let currentVelocity = t === 0 ? initialVelocity : 0.0; + /** + * We only need to calculate velocity for under-damped springs + * as over- and critically-damped springs can't overshoot, so + * checking only for displacement is enough. + */ + if (dampingRatio < 1) { + currentVelocity = + t === 0 + ? secondsToMilliseconds(initialVelocity) + : calcGeneratorVelocity(resolveSpring, t, current); + } + const isBelowVelocityThreshold = Math.abs(currentVelocity) <= restSpeed; + const isBelowDisplacementThreshold = Math.abs(target - current) <= restDelta; + state.done = + isBelowVelocityThreshold && isBelowDisplacementThreshold; + } + else { + state.done = t >= duration; + } + state.value = state.done ? target : current; + return state; + }, + toString: () => { + const calculatedDuration = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration); + const easing = generateLinearEasing((progress) => generator.next(calculatedDuration * progress).value, calculatedDuration, 30); + return calculatedDuration + "ms " + easing; + }, + toTransition: () => { }, + }; + return generator; + } + spring.applyToOptions = (options) => { + const generatorOptions = createGeneratorEasing(options, 100, spring); + options.ease = generatorOptions.ease; + options.duration = secondsToMilliseconds(generatorOptions.duration); + options.type = "keyframes"; + return options; + }; + + function inertia({ keyframes, velocity = 0.0, power = 0.8, timeConstant = 325, bounceDamping = 10, bounceStiffness = 500, modifyTarget, min, max, restDelta = 0.5, restSpeed, }) { + const origin = keyframes[0]; + const state = { + done: false, + value: origin, + }; + const isOutOfBounds = (v) => (min !== undefined && v < min) || (max !== undefined && v > max); + const nearestBoundary = (v) => { + if (min === undefined) + return max; + if (max === undefined) + return min; + return Math.abs(min - v) < Math.abs(max - v) ? min : max; + }; + let amplitude = power * velocity; + const ideal = origin + amplitude; + const target = modifyTarget === undefined ? ideal : modifyTarget(ideal); + /** + * If the target has changed we need to re-calculate the amplitude, otherwise + * the animation will start from the wrong position. + */ + if (target !== ideal) + amplitude = target - origin; + const calcDelta = (t) => -amplitude * Math.exp(-t / timeConstant); + const calcLatest = (t) => target + calcDelta(t); + const applyFriction = (t) => { + const delta = calcDelta(t); + const latest = calcLatest(t); + state.done = Math.abs(delta) <= restDelta; + state.value = state.done ? target : latest; + }; + /** + * Ideally this would resolve for t in a stateless way, we could + * do that by always precalculating the animation but as we know + * this will be done anyway we can assume that spring will + * be discovered during that. + */ + let timeReachedBoundary; + let spring$1; + const checkCatchBoundary = (t) => { + if (!isOutOfBounds(state.value)) + return; + timeReachedBoundary = t; + spring$1 = spring({ + keyframes: [state.value, nearestBoundary(state.value)], + velocity: calcGeneratorVelocity(calcLatest, t, state.value), // TODO: This should be passing * 1000 + damping: bounceDamping, + stiffness: bounceStiffness, + restDelta, + restSpeed, + }); + }; + checkCatchBoundary(0); + return { + calculatedDuration: null, + next: (t) => { + /** + * We need to resolve the friction to figure out if we need a + * spring but we don't want to do this twice per frame. So here + * we flag if we updated for this frame and later if we did + * we can skip doing it again. + */ + let hasUpdatedFrame = false; + if (!spring$1 && timeReachedBoundary === undefined) { + hasUpdatedFrame = true; + applyFriction(t); + checkCatchBoundary(t); + } + /** + * If we have a spring and the provided t is beyond the moment the friction + * animation crossed the min/max boundary, use the spring. + */ + if (timeReachedBoundary !== undefined && t >= timeReachedBoundary) { + return spring$1.next(t - timeReachedBoundary); + } + else { + !hasUpdatedFrame && applyFriction(t); + return state; + } + }, + }; + } + + function createMixers(output, ease, customMixer) { + const mixers = []; + const mixerFactory = customMixer || MotionGlobalConfig.mix || mix; + const numMixers = output.length - 1; + for (let i = 0; i < numMixers; i++) { + let mixer = mixerFactory(output[i], output[i + 1]); + if (ease) { + const easingFunction = Array.isArray(ease) ? ease[i] || noop : ease; + mixer = pipe(easingFunction, mixer); + } + mixers.push(mixer); + } + return mixers; + } + /** + * Create a function that maps from a numerical input array to a generic output array. + * + * Accepts: + * - Numbers + * - Colors (hex, hsl, hsla, rgb, rgba) + * - Complex (combinations of one or more numbers or strings) + * + * ```jsx + * const mixColor = interpolate([0, 1], ['#fff', '#000']) + * + * mixColor(0.5) // 'rgba(128, 128, 128, 1)' + * ``` + * + * TODO Revisit this approach once we've moved to data models for values, + * probably not needed to pregenerate mixer functions. + * + * @public + */ + function interpolate(input, output, { clamp: isClamp = true, ease, mixer } = {}) { + const inputLength = input.length; + exports.invariant(inputLength === output.length, "Both input and output ranges must be the same length", "range-length"); + /** + * If we're only provided a single input, we can just make a function + * that returns the output. + */ + if (inputLength === 1) + return () => output[0]; + if (inputLength === 2 && output[0] === output[1]) + return () => output[1]; + const isZeroDeltaRange = input[0] === input[1]; + // If input runs highest -> lowest, reverse both arrays + if (input[0] > input[inputLength - 1]) { + input = [...input].reverse(); + output = [...output].reverse(); + } + const mixers = createMixers(output, ease, mixer); + const numMixers = mixers.length; + const interpolator = (v) => { + if (isZeroDeltaRange && v < input[0]) + return output[0]; + let i = 0; + if (numMixers > 1) { + for (; i < input.length - 2; i++) { + if (v < input[i + 1]) + break; + } + } + const progressInRange = progress(input[i], input[i + 1], v); + return mixers[i](progressInRange); + }; + return isClamp + ? (v) => interpolator(clamp(input[0], input[inputLength - 1], v)) + : interpolator; + } + + function fillOffset(offset, remaining) { + const min = offset[offset.length - 1]; + for (let i = 1; i <= remaining; i++) { + const offsetProgress = progress(0, remaining, i); + offset.push(mixNumber$1(min, 1, offsetProgress)); + } + } + + function defaultOffset$1(arr) { + const offset = [0]; + fillOffset(offset, arr.length - 1); + return offset; + } + + function convertOffsetToTimes(offset, duration) { + return offset.map((o) => o * duration); + } + + function defaultEasing(values, easing) { + return values.map(() => easing || easeInOut).splice(0, values.length - 1); + } + function keyframes({ duration = 300, keyframes: keyframeValues, times, ease = "easeInOut", }) { + /** + * Easing functions can be externally defined as strings. Here we convert them + * into actual functions. + */ + const easingFunctions = isEasingArray(ease) + ? ease.map(easingDefinitionToFunction) + : easingDefinitionToFunction(ease); + /** + * This is the Iterator-spec return value. We ensure it's mutable rather than using a generator + * to reduce GC during animation. + */ + const state = { + done: false, + value: keyframeValues[0], + }; + /** + * Create a times array based on the provided 0-1 offsets + */ + const absoluteTimes = convertOffsetToTimes( + // Only use the provided offsets if they're the correct length + // TODO Maybe we should warn here if there's a length mismatch + times && times.length === keyframeValues.length + ? times + : defaultOffset$1(keyframeValues), duration); + const mapTimeToKeyframe = interpolate(absoluteTimes, keyframeValues, { + ease: Array.isArray(easingFunctions) + ? easingFunctions + : defaultEasing(keyframeValues, easingFunctions), + }); + return { + calculatedDuration: duration, + next: (t) => { + state.value = mapTimeToKeyframe(t); + state.done = t >= duration; + return state; + }, + }; + } + + const isNotNull$1 = (value) => value !== null; + function getFinalKeyframe$1(keyframes, { repeat, repeatType = "loop" }, finalKeyframe, speed = 1) { + const resolvedKeyframes = keyframes.filter(isNotNull$1); + const useFirstKeyframe = speed < 0 || (repeat && repeatType !== "loop" && repeat % 2 === 1); + const index = useFirstKeyframe ? 0 : resolvedKeyframes.length - 1; + return !index || finalKeyframe === undefined + ? resolvedKeyframes[index] + : finalKeyframe; + } + + const transitionTypeMap = { + decay: inertia, + inertia, + tween: keyframes, + keyframes: keyframes, + spring, + }; + function replaceTransitionType(transition) { + if (typeof transition.type === "string") { + transition.type = transitionTypeMap[transition.type]; + } + } + + class WithPromise { + constructor() { + this.updateFinished(); + } + get finished() { + return this._finished; + } + updateFinished() { + this._finished = new Promise((resolve) => { + this.resolve = resolve; + }); + } + notifyFinished() { + this.resolve(); + } + /** + * Allows the animation to be awaited. + * + * @deprecated Use `finished` instead. + */ + then(onResolve, onReject) { + return this.finished.then(onResolve, onReject); + } + } + + const percentToProgress = (percent) => percent / 100; + class JSAnimation extends WithPromise { + constructor(options) { + super(); + this.state = "idle"; + this.startTime = null; + this.isStopped = false; + /** + * The current time of the animation. + */ + this.currentTime = 0; + /** + * The time at which the animation was paused. + */ + this.holdTime = null; + /** + * Playback speed as a factor. 0 would be stopped, -1 reverse and 2 double speed. + */ + this.playbackSpeed = 1; + /** + * This method is bound to the instance to fix a pattern where + * animation.stop is returned as a reference from a useEffect. + */ + this.stop = () => { + const { motionValue } = this.options; + if (motionValue && motionValue.updatedAt !== time.now()) { + this.tick(time.now()); + } + this.isStopped = true; + if (this.state === "idle") + return; + this.teardown(); + this.options.onStop?.(); + }; + activeAnimations.mainThread++; + this.options = options; + this.initAnimation(); + this.play(); + if (options.autoplay === false) + this.pause(); + } + initAnimation() { + const { options } = this; + replaceTransitionType(options); + const { type = keyframes, repeat = 0, repeatDelay = 0, repeatType, velocity = 0, } = options; + let { keyframes: keyframes$1 } = options; + const generatorFactory = type || keyframes; + if (generatorFactory !== keyframes) { + exports.invariant(keyframes$1.length <= 2, `Only two keyframes currently supported with spring and inertia animations. Trying to animate ${keyframes$1}`, "spring-two-frames"); + } + if (generatorFactory !== keyframes && + typeof keyframes$1[0] !== "number") { + this.mixKeyframes = pipe(percentToProgress, mix(keyframes$1[0], keyframes$1[1])); + keyframes$1 = [0, 100]; + } + const generator = generatorFactory({ ...options, keyframes: keyframes$1 }); + /** + * If we have a mirror repeat type we need to create a second generator that outputs the + * mirrored (not reversed) animation and later ping pong between the two generators. + */ + if (repeatType === "mirror") { + this.mirroredGenerator = generatorFactory({ + ...options, + keyframes: [...keyframes$1].reverse(), + velocity: -velocity, + }); + } + /** + * If duration is undefined and we have repeat options, + * we need to calculate a duration from the generator. + * + * We set it to the generator itself to cache the duration. + * Any timeline resolver will need to have already precalculated + * the duration by this step. + */ + if (generator.calculatedDuration === null) { + generator.calculatedDuration = calcGeneratorDuration(generator); + } + const { calculatedDuration } = generator; + this.calculatedDuration = calculatedDuration; + this.resolvedDuration = calculatedDuration + repeatDelay; + this.totalDuration = this.resolvedDuration * (repeat + 1) - repeatDelay; + this.generator = generator; + } + updateTime(timestamp) { + const animationTime = Math.round(timestamp - this.startTime) * this.playbackSpeed; + // Update currentTime + if (this.holdTime !== null) { + this.currentTime = this.holdTime; + } + else { + // Rounding the time because floating point arithmetic is not always accurate, e.g. 3000.367 - 1000.367 = + // 2000.0000000000002. This is a problem when we are comparing the currentTime with the duration, for + // example. + this.currentTime = animationTime; + } + } + tick(timestamp, sample = false) { + const { generator, totalDuration, mixKeyframes, mirroredGenerator, resolvedDuration, calculatedDuration, } = this; + if (this.startTime === null) + return generator.next(0); + const { delay = 0, keyframes, repeat, repeatType, repeatDelay, type, onUpdate, finalKeyframe, } = this.options; + /** + * requestAnimationFrame timestamps can come through as lower than + * the startTime as set by performance.now(). Here we prevent this, + * though in the future it could be possible to make setting startTime + * a pending operation that gets resolved here. + */ + if (this.speed > 0) { + this.startTime = Math.min(this.startTime, timestamp); + } + else if (this.speed < 0) { + this.startTime = Math.min(timestamp - totalDuration / this.speed, this.startTime); + } + if (sample) { + this.currentTime = timestamp; + } + else { + this.updateTime(timestamp); + } + // Rebase on delay + const timeWithoutDelay = this.currentTime - delay * (this.playbackSpeed >= 0 ? 1 : -1); + const isInDelayPhase = this.playbackSpeed >= 0 + ? timeWithoutDelay < 0 + : timeWithoutDelay > totalDuration; + this.currentTime = Math.max(timeWithoutDelay, 0); + // If this animation has finished, set the current time to the total duration. + if (this.state === "finished" && this.holdTime === null) { + this.currentTime = totalDuration; + } + let elapsed = this.currentTime; + let frameGenerator = generator; + if (repeat) { + /** + * Get the current progress (0-1) of the animation. If t is > + * than duration we'll get values like 2.5 (midway through the + * third iteration) + */ + const progress = Math.min(this.currentTime, totalDuration) / resolvedDuration; + /** + * Get the current iteration (0 indexed). For instance the floor of + * 2.5 is 2. + */ + let currentIteration = Math.floor(progress); + /** + * Get the current progress of the iteration by taking the remainder + * so 2.5 is 0.5 through iteration 2 + */ + let iterationProgress = progress % 1.0; + /** + * If iteration progress is 1 we count that as the end + * of the previous iteration. + */ + if (!iterationProgress && progress >= 1) { + iterationProgress = 1; + } + iterationProgress === 1 && currentIteration--; + currentIteration = Math.min(currentIteration, repeat + 1); + /** + * Reverse progress if we're not running in "normal" direction + */ + const isOddIteration = Boolean(currentIteration % 2); + if (isOddIteration) { + if (repeatType === "reverse") { + iterationProgress = 1 - iterationProgress; + if (repeatDelay) { + iterationProgress -= repeatDelay / resolvedDuration; + } + } + else if (repeatType === "mirror") { + frameGenerator = mirroredGenerator; + } + } + elapsed = clamp(0, 1, iterationProgress) * resolvedDuration; + } + /** + * If we're in negative time, set state as the initial keyframe. + * This prevents delay: x, duration: 0 animations from finishing + * instantly. + */ + const state = isInDelayPhase + ? { done: false, value: keyframes[0] } + : frameGenerator.next(elapsed); + if (mixKeyframes) { + state.value = mixKeyframes(state.value); + } + let { done } = state; + if (!isInDelayPhase && calculatedDuration !== null) { + done = + this.playbackSpeed >= 0 + ? this.currentTime >= totalDuration + : this.currentTime <= 0; + } + const isAnimationFinished = this.holdTime === null && + (this.state === "finished" || (this.state === "running" && done)); + // TODO: The exception for inertia could be cleaner here + if (isAnimationFinished && type !== inertia) { + state.value = getFinalKeyframe$1(keyframes, this.options, finalKeyframe, this.speed); + } + if (onUpdate) { + onUpdate(state.value); + } + if (isAnimationFinished) { + this.finish(); + } + return state; + } + /** + * Allows the returned animation to be awaited or promise-chained. Currently + * resolves when the animation finishes at all but in a future update could/should + * reject if its cancels. + */ + then(resolve, reject) { + return this.finished.then(resolve, reject); + } + get duration() { + return millisecondsToSeconds(this.calculatedDuration); + } + get time() { + return millisecondsToSeconds(this.currentTime); + } + set time(newTime) { + newTime = secondsToMilliseconds(newTime); + this.currentTime = newTime; + if (this.startTime === null || + this.holdTime !== null || + this.playbackSpeed === 0) { + this.holdTime = newTime; + } + else if (this.driver) { + this.startTime = this.driver.now() - newTime / this.playbackSpeed; + } + this.driver?.start(false); + } + get speed() { + return this.playbackSpeed; + } + set speed(newSpeed) { + this.updateTime(time.now()); + const hasChanged = this.playbackSpeed !== newSpeed; + this.playbackSpeed = newSpeed; + if (hasChanged) { + this.time = millisecondsToSeconds(this.currentTime); + } + } + play() { + if (this.isStopped) + return; + const { driver = frameloopDriver, startTime } = this.options; + if (!this.driver) { + this.driver = driver((timestamp) => this.tick(timestamp)); + } + this.options.onPlay?.(); + const now = this.driver.now(); + if (this.state === "finished") { + this.updateFinished(); + this.startTime = now; + } + else if (this.holdTime !== null) { + this.startTime = now - this.holdTime; + } + else if (!this.startTime) { + this.startTime = startTime ?? now; + } + if (this.state === "finished" && this.speed < 0) { + this.startTime += this.calculatedDuration; + } + this.holdTime = null; + /** + * Set playState to running only after we've used it in + * the previous logic. + */ + this.state = "running"; + this.driver.start(); + } + pause() { + this.state = "paused"; + this.updateTime(time.now()); + this.holdTime = this.currentTime; + } + complete() { + if (this.state !== "running") { + this.play(); + } + this.state = "finished"; + this.holdTime = null; + } + finish() { + this.notifyFinished(); + this.teardown(); + this.state = "finished"; + this.options.onComplete?.(); + } + cancel() { + this.holdTime = null; + this.startTime = 0; + this.tick(0); + this.teardown(); + this.options.onCancel?.(); + } + teardown() { + this.state = "idle"; + this.stopDriver(); + this.startTime = this.holdTime = null; + activeAnimations.mainThread--; + } + stopDriver() { + if (!this.driver) + return; + this.driver.stop(); + this.driver = undefined; + } + sample(sampleTime) { + this.startTime = 0; + return this.tick(sampleTime, true); + } + attachTimeline(timeline) { + if (this.options.allowFlatten) { + this.options.type = "keyframes"; + this.options.ease = "linear"; + this.initAnimation(); + } + this.driver?.stop(); + return timeline.observe(this); + } + } + // Legacy function support + function animateValue(options) { + return new JSAnimation(options); + } + + function fillWildcards(keyframes) { + for (let i = 1; i < keyframes.length; i++) { + keyframes[i] ?? (keyframes[i] = keyframes[i - 1]); + } + } + + const radToDeg = (rad) => (rad * 180) / Math.PI; + const rotate = (v) => { + const angle = radToDeg(Math.atan2(v[1], v[0])); + return rebaseAngle(angle); + }; + const matrix2dParsers = { + x: 4, + y: 5, + translateX: 4, + translateY: 5, + scaleX: 0, + scaleY: 3, + scale: (v) => (Math.abs(v[0]) + Math.abs(v[3])) / 2, + rotate, + rotateZ: rotate, + skewX: (v) => radToDeg(Math.atan(v[1])), + skewY: (v) => radToDeg(Math.atan(v[2])), + skew: (v) => (Math.abs(v[1]) + Math.abs(v[2])) / 2, + }; + const rebaseAngle = (angle) => { + angle = angle % 360; + if (angle < 0) + angle += 360; + return angle; + }; + const rotateZ = rotate; + const scaleX = (v) => Math.sqrt(v[0] * v[0] + v[1] * v[1]); + const scaleY = (v) => Math.sqrt(v[4] * v[4] + v[5] * v[5]); + const matrix3dParsers = { + x: 12, + y: 13, + z: 14, + translateX: 12, + translateY: 13, + translateZ: 14, + scaleX, + scaleY, + scale: (v) => (scaleX(v) + scaleY(v)) / 2, + rotateX: (v) => rebaseAngle(radToDeg(Math.atan2(v[6], v[5]))), + rotateY: (v) => rebaseAngle(radToDeg(Math.atan2(-v[2], v[0]))), + rotateZ, + rotate: rotateZ, + skewX: (v) => radToDeg(Math.atan(v[4])), + skewY: (v) => radToDeg(Math.atan(v[1])), + skew: (v) => (Math.abs(v[1]) + Math.abs(v[4])) / 2, + }; + function defaultTransformValue(name) { + return name.includes("scale") ? 1 : 0; + } + function parseValueFromTransform(transform, name) { + if (!transform || transform === "none") { + return defaultTransformValue(name); + } + const matrix3dMatch = transform.match(/^matrix3d\(([-\d.e\s,]+)\)$/u); + let parsers; + let match; + if (matrix3dMatch) { + parsers = matrix3dParsers; + match = matrix3dMatch; + } + else { + const matrix2dMatch = transform.match(/^matrix\(([-\d.e\s,]+)\)$/u); + parsers = matrix2dParsers; + match = matrix2dMatch; + } + if (!match) { + return defaultTransformValue(name); + } + const valueParser = parsers[name]; + const values = match[1].split(",").map(convertTransformToNumber); + return typeof valueParser === "function" + ? valueParser(values) + : values[valueParser]; + } + const readTransformValue = (instance, name) => { + const { transform = "none" } = getComputedStyle(instance); + return parseValueFromTransform(transform, name); + }; + function convertTransformToNumber(value) { + return parseFloat(value.trim()); + } + + /** + * Generate a list of every possible transform key. + */ + const transformPropOrder = [ + "transformPerspective", + "x", + "y", + "z", + "translateX", + "translateY", + "translateZ", + "scale", + "scaleX", + "scaleY", + "rotate", + "rotateX", + "rotateY", + "rotateZ", + "skew", + "skewX", + "skewY", + ]; + /** + * A quick lookup for transform props. + */ + const transformProps = /*@__PURE__*/ (() => new Set(transformPropOrder))(); + + const isNumOrPxType = (v) => v === number || v === px; + const transformKeys = new Set(["x", "y", "z"]); + const nonTranslationalTransformKeys = transformPropOrder.filter((key) => !transformKeys.has(key)); + function removeNonTranslationalTransform(visualElement) { + const removedTransforms = []; + nonTranslationalTransformKeys.forEach((key) => { + const value = visualElement.getValue(key); + if (value !== undefined) { + removedTransforms.push([key, value.get()]); + value.set(key.startsWith("scale") ? 1 : 0); + } + }); + return removedTransforms; + } + const positionalValues = { + // Dimensions + width: ({ x }, { paddingLeft = "0", paddingRight = "0" }) => x.max - x.min - parseFloat(paddingLeft) - parseFloat(paddingRight), + height: ({ y }, { paddingTop = "0", paddingBottom = "0" }) => y.max - y.min - parseFloat(paddingTop) - parseFloat(paddingBottom), + top: (_bbox, { top }) => parseFloat(top), + left: (_bbox, { left }) => parseFloat(left), + bottom: ({ y }, { top }) => parseFloat(top) + (y.max - y.min), + right: ({ x }, { left }) => parseFloat(left) + (x.max - x.min), + // Transform + x: (_bbox, { transform }) => parseValueFromTransform(transform, "x"), + y: (_bbox, { transform }) => parseValueFromTransform(transform, "y"), + }; + // Alias translate longform names + positionalValues.translateX = positionalValues.x; + positionalValues.translateY = positionalValues.y; + + const toResolve = new Set(); + let isScheduled = false; + let anyNeedsMeasurement = false; + let isForced = false; + function measureAllKeyframes() { + if (anyNeedsMeasurement) { + const resolversToMeasure = Array.from(toResolve).filter((resolver) => resolver.needsMeasurement); + const elementsToMeasure = new Set(resolversToMeasure.map((resolver) => resolver.element)); + const transformsToRestore = new Map(); + /** + * Write pass + * If we're measuring elements we want to remove bounding box-changing transforms. + */ + elementsToMeasure.forEach((element) => { + const removedTransforms = removeNonTranslationalTransform(element); + if (!removedTransforms.length) + return; + transformsToRestore.set(element, removedTransforms); + element.render(); + }); + // Read + resolversToMeasure.forEach((resolver) => resolver.measureInitialState()); + // Write + elementsToMeasure.forEach((element) => { + element.render(); + const restore = transformsToRestore.get(element); + if (restore) { + restore.forEach(([key, value]) => { + element.getValue(key)?.set(value); + }); + } + }); + // Read + resolversToMeasure.forEach((resolver) => resolver.measureEndState()); + // Write + resolversToMeasure.forEach((resolver) => { + if (resolver.suspendedScrollY !== undefined) { + window.scrollTo(0, resolver.suspendedScrollY); + } + }); + } + anyNeedsMeasurement = false; + isScheduled = false; + toResolve.forEach((resolver) => resolver.complete(isForced)); + toResolve.clear(); + } + function readAllKeyframes() { + toResolve.forEach((resolver) => { + resolver.readKeyframes(); + if (resolver.needsMeasurement) { + anyNeedsMeasurement = true; + } + }); + } + function flushKeyframeResolvers() { + isForced = true; + readAllKeyframes(); + measureAllKeyframes(); + isForced = false; + } + class KeyframeResolver { + constructor(unresolvedKeyframes, onComplete, name, motionValue, element, isAsync = false) { + this.state = "pending"; + /** + * Track whether this resolver is async. If it is, it'll be added to the + * resolver queue and flushed in the next frame. Resolvers that aren't going + * to trigger read/write thrashing don't need to be async. + */ + this.isAsync = false; + /** + * Track whether this resolver needs to perform a measurement + * to resolve its keyframes. + */ + this.needsMeasurement = false; + this.unresolvedKeyframes = [...unresolvedKeyframes]; + this.onComplete = onComplete; + this.name = name; + this.motionValue = motionValue; + this.element = element; + this.isAsync = isAsync; + } + scheduleResolve() { + this.state = "scheduled"; + if (this.isAsync) { + toResolve.add(this); + if (!isScheduled) { + isScheduled = true; + frame.read(readAllKeyframes); + frame.resolveKeyframes(measureAllKeyframes); + } + } + else { + this.readKeyframes(); + this.complete(); + } + } + readKeyframes() { + const { unresolvedKeyframes, name, element, motionValue } = this; + // If initial keyframe is null we need to read it from the DOM + if (unresolvedKeyframes[0] === null) { + const currentValue = motionValue?.get(); + // TODO: This doesn't work if the final keyframe is a wildcard + const finalKeyframe = unresolvedKeyframes[unresolvedKeyframes.length - 1]; + if (currentValue !== undefined) { + unresolvedKeyframes[0] = currentValue; + } + else if (element && name) { + const valueAsRead = element.readValue(name, finalKeyframe); + if (valueAsRead !== undefined && valueAsRead !== null) { + unresolvedKeyframes[0] = valueAsRead; + } + } + if (unresolvedKeyframes[0] === undefined) { + unresolvedKeyframes[0] = finalKeyframe; + } + if (motionValue && currentValue === undefined) { + motionValue.set(unresolvedKeyframes[0]); + } + } + fillWildcards(unresolvedKeyframes); + } + setFinalKeyframe() { } + measureInitialState() { } + renderEndStyles() { } + measureEndState() { } + complete(isForcedComplete = false) { + this.state = "complete"; + this.onComplete(this.unresolvedKeyframes, this.finalKeyframe, isForcedComplete); + toResolve.delete(this); + } + cancel() { + if (this.state === "scheduled") { + toResolve.delete(this); + this.state = "pending"; + } + } + resume() { + if (this.state === "pending") + this.scheduleResolve(); + } + } + + const isCSSVar = (name) => name.startsWith("--"); + + function setStyle(element, name, value) { + isCSSVar(name) + ? element.style.setProperty(name, value) + : (element.style[name] = value); + } + + const supportsScrollTimeline = /* @__PURE__ */ memo(() => window.ScrollTimeline !== undefined); + + /** + * Add the ability for test suites to manually set support flags + * to better test more environments. + */ + const supportsFlags = {}; + + function memoSupports(callback, supportsFlag) { + const memoized = memo(callback); + return () => supportsFlags[supportsFlag] ?? memoized(); + } + + const supportsLinearEasing = /*@__PURE__*/ memoSupports(() => { + try { + document + .createElement("div") + .animate({ opacity: 0 }, { easing: "linear(0, 1)" }); + } + catch (e) { + return false; + } + return true; + }, "linearEasing"); + + const cubicBezierAsString = ([a, b, c, d]) => `cubic-bezier(${a}, ${b}, ${c}, ${d})`; + + const supportedWaapiEasing = { + linear: "linear", + ease: "ease", + easeIn: "ease-in", + easeOut: "ease-out", + easeInOut: "ease-in-out", + circIn: /*@__PURE__*/ cubicBezierAsString([0, 0.65, 0.55, 1]), + circOut: /*@__PURE__*/ cubicBezierAsString([0.55, 0, 1, 0.45]), + backIn: /*@__PURE__*/ cubicBezierAsString([0.31, 0.01, 0.66, -0.59]), + backOut: /*@__PURE__*/ cubicBezierAsString([0.33, 1.53, 0.69, 0.99]), + }; + + function mapEasingToNativeEasing(easing, duration) { + if (!easing) { + return undefined; + } + else if (typeof easing === "function") { + return supportsLinearEasing() + ? generateLinearEasing(easing, duration) + : "ease-out"; + } + else if (isBezierDefinition(easing)) { + return cubicBezierAsString(easing); + } + else if (Array.isArray(easing)) { + return easing.map((segmentEasing) => mapEasingToNativeEasing(segmentEasing, duration) || + supportedWaapiEasing.easeOut); + } + else { + return supportedWaapiEasing[easing]; + } + } + + function startWaapiAnimation(element, valueName, keyframes, { delay = 0, duration = 300, repeat = 0, repeatType = "loop", ease = "easeOut", times, } = {}, pseudoElement = undefined) { + const keyframeOptions = { + [valueName]: keyframes, + }; + if (times) + keyframeOptions.offset = times; + const easing = mapEasingToNativeEasing(ease, duration); + /** + * If this is an easing array, apply to keyframes, not animation as a whole + */ + if (Array.isArray(easing)) + keyframeOptions.easing = easing; + if (statsBuffer.value) { + activeAnimations.waapi++; + } + const options = { + delay, + duration, + easing: !Array.isArray(easing) ? easing : "linear", + fill: "both", + iterations: repeat + 1, + direction: repeatType === "reverse" ? "alternate" : "normal", + }; + if (pseudoElement) + options.pseudoElement = pseudoElement; + const animation = element.animate(keyframeOptions, options); + if (statsBuffer.value) { + animation.finished.finally(() => { + activeAnimations.waapi--; + }); + } + return animation; + } + + function isGenerator(type) { + return typeof type === "function" && "applyToOptions" in type; + } + + function applyGeneratorOptions({ type, ...options }) { + if (isGenerator(type) && supportsLinearEasing()) { + return type.applyToOptions(options); + } + else { + options.duration ?? (options.duration = 300); + options.ease ?? (options.ease = "easeOut"); + } + return options; + } + + /** + * NativeAnimation implements AnimationPlaybackControls for the browser's Web Animations API. + */ + class NativeAnimation extends WithPromise { + constructor(options) { + super(); + this.finishedTime = null; + this.isStopped = false; + if (!options) + return; + const { element, name, keyframes, pseudoElement, allowFlatten = false, finalKeyframe, onComplete, } = options; + this.isPseudoElement = Boolean(pseudoElement); + this.allowFlatten = allowFlatten; + this.options = options; + exports.invariant(typeof options.type !== "string", `Mini animate() doesn't support "type" as a string.`, "mini-spring"); + const transition = applyGeneratorOptions(options); + this.animation = startWaapiAnimation(element, name, keyframes, transition, pseudoElement); + if (transition.autoplay === false) { + this.animation.pause(); + } + this.animation.onfinish = () => { + this.finishedTime = this.time; + if (!pseudoElement) { + const keyframe = getFinalKeyframe$1(keyframes, this.options, finalKeyframe, this.speed); + if (this.updateMotionValue) { + this.updateMotionValue(keyframe); + } + else { + /** + * If we can, we want to commit the final style as set by the user, + * rather than the computed keyframe value supplied by the animation. + */ + setStyle(element, name, keyframe); + } + this.animation.cancel(); + } + onComplete?.(); + this.notifyFinished(); + }; + } + play() { + if (this.isStopped) + return; + this.animation.play(); + if (this.state === "finished") { + this.updateFinished(); + } + } + pause() { + this.animation.pause(); + } + complete() { + this.animation.finish?.(); + } + cancel() { + try { + this.animation.cancel(); + } + catch (e) { } + } + stop() { + if (this.isStopped) + return; + this.isStopped = true; + const { state } = this; + if (state === "idle" || state === "finished") { + return; + } + if (this.updateMotionValue) { + this.updateMotionValue(); + } + else { + this.commitStyles(); + } + if (!this.isPseudoElement) + this.cancel(); + } + /** + * WAAPI doesn't natively have any interruption capabilities. + * + * In this method, we commit styles back to the DOM before cancelling + * the animation. + * + * This is designed to be overridden by NativeAnimationExtended, which + * will create a renderless JS animation and sample it twice to calculate + * its current value, "previous" value, and therefore allow + * Motion to also correctly calculate velocity for any subsequent animation + * while deferring the commit until the next animation frame. + */ + commitStyles() { + if (!this.isPseudoElement) { + this.animation.commitStyles?.(); + } + } + get duration() { + const duration = this.animation.effect?.getComputedTiming?.().duration || 0; + return millisecondsToSeconds(Number(duration)); + } + get time() { + return millisecondsToSeconds(Number(this.animation.currentTime) || 0); + } + set time(newTime) { + this.finishedTime = null; + this.animation.currentTime = secondsToMilliseconds(newTime); + } + /** + * The playback speed of the animation. + * 1 = normal speed, 2 = double speed, 0.5 = half speed. + */ + get speed() { + return this.animation.playbackRate; + } + set speed(newSpeed) { + // Allow backwards playback after finishing + if (newSpeed < 0) + this.finishedTime = null; + this.animation.playbackRate = newSpeed; + } + get state() { + return this.finishedTime !== null + ? "finished" + : this.animation.playState; + } + get startTime() { + return Number(this.animation.startTime); + } + set startTime(newStartTime) { + this.animation.startTime = newStartTime; + } + /** + * Attaches a timeline to the animation, for instance the `ScrollTimeline`. + */ + attachTimeline({ timeline, observe }) { + if (this.allowFlatten) { + this.animation.effect?.updateTiming({ easing: "linear" }); + } + this.animation.onfinish = null; + if (timeline && supportsScrollTimeline()) { + this.animation.timeline = timeline; + return noop; + } + else { + return observe(this); + } + } + } + + const unsupportedEasingFunctions = { + anticipate, + backInOut, + circInOut, + }; + function isUnsupportedEase(key) { + return key in unsupportedEasingFunctions; + } + function replaceStringEasing(transition) { + if (typeof transition.ease === "string" && + isUnsupportedEase(transition.ease)) { + transition.ease = unsupportedEasingFunctions[transition.ease]; + } + } + + /** + * 10ms is chosen here as it strikes a balance between smooth + * results (more than one keyframe per frame at 60fps) and + * keyframe quantity. + */ + const sampleDelta = 10; //ms + class NativeAnimationExtended extends NativeAnimation { + constructor(options) { + /** + * The base NativeAnimation function only supports a subset + * of Motion easings, and WAAPI also only supports some + * easing functions via string/cubic-bezier definitions. + * + * This function replaces those unsupported easing functions + * with a JS easing function. This will later get compiled + * to a linear() easing function. + */ + replaceStringEasing(options); + /** + * Ensure we replace the transition type with a generator function + * before passing to WAAPI. + * + * TODO: Does this have a better home? It could be shared with + * JSAnimation. + */ + replaceTransitionType(options); + super(options); + if (options.startTime) { + this.startTime = options.startTime; + } + this.options = options; + } + /** + * WAAPI doesn't natively have any interruption capabilities. + * + * Rather than read commited styles back out of the DOM, we can + * create a renderless JS animation and sample it twice to calculate + * its current value, "previous" value, and therefore allow + * Motion to calculate velocity for any subsequent animation. + */ + updateMotionValue(value) { + const { motionValue, onUpdate, onComplete, element, ...options } = this.options; + if (!motionValue) + return; + if (value !== undefined) { + motionValue.set(value); + return; + } + const sampleAnimation = new JSAnimation({ + ...options, + autoplay: false, + }); + const sampleTime = secondsToMilliseconds(this.finishedTime ?? this.time); + motionValue.setWithVelocity(sampleAnimation.sample(sampleTime - sampleDelta).value, sampleAnimation.sample(sampleTime).value, sampleDelta); + sampleAnimation.stop(); + } + } + + /** + * Check if a value is animatable. Examples: + * + * ✅: 100, "100px", "#fff" + * ❌: "block", "url(2.jpg)" + * @param value + * + * @internal + */ + const isAnimatable = (value, name) => { + // If the list of keys that might be non-animatable grows, replace with Set + if (name === "zIndex") + return false; + // If it's a number or a keyframes array, we can animate it. We might at some point + // need to do a deep isAnimatable check of keyframes, or let Popmotion handle this, + // but for now lets leave it like this for performance reasons + if (typeof value === "number" || Array.isArray(value)) + return true; + if (typeof value === "string" && // It's animatable if we have a string + (complex.test(value) || value === "0") && // And it contains numbers and/or colors + !value.startsWith("url(") // Unless it starts with "url(" + ) { + return true; + } + return false; + }; + + function hasKeyframesChanged(keyframes) { + const current = keyframes[0]; + if (keyframes.length === 1) + return true; + for (let i = 0; i < keyframes.length; i++) { + if (keyframes[i] !== current) + return true; + } + } + function canAnimate(keyframes, name, type, velocity) { + /** + * Check if we're able to animate between the start and end keyframes, + * and throw a warning if we're attempting to animate between one that's + * animatable and another that isn't. + */ + const originKeyframe = keyframes[0]; + if (originKeyframe === null) + return false; + /** + * These aren't traditionally animatable but we do support them. + * In future we could look into making this more generic or replacing + * this function with mix() === mixImmediate + */ + if (name === "display" || name === "visibility") + return true; + const targetKeyframe = keyframes[keyframes.length - 1]; + const isOriginAnimatable = isAnimatable(originKeyframe, name); + const isTargetAnimatable = isAnimatable(targetKeyframe, name); + exports.warning(isOriginAnimatable === isTargetAnimatable, `You are trying to animate ${name} from "${originKeyframe}" to "${targetKeyframe}". "${isOriginAnimatable ? targetKeyframe : originKeyframe}" is not an animatable value.`, "value-not-animatable"); + // Always skip if any of these are true + if (!isOriginAnimatable || !isTargetAnimatable) { + return false; + } + return (hasKeyframesChanged(keyframes) || + ((type === "spring" || isGenerator(type)) && velocity)); + } + + function makeAnimationInstant(options) { + options.duration = 0; + options.type === "keyframes"; + } + + /** + * A list of values that can be hardware-accelerated. + */ + const acceleratedValues$1 = new Set([ + "opacity", + "clipPath", + "filter", + "transform", + // TODO: Could be re-enabled now we have support for linear() easing + // "background-color" + ]); + const supportsWaapi = /*@__PURE__*/ memo(() => Object.hasOwnProperty.call(Element.prototype, "animate")); + function supportsBrowserAnimation(options) { + const { motionValue, name, repeatDelay, repeatType, damping, type } = options; + const subject = motionValue?.owner?.current; + /** + * We use this check instead of isHTMLElement() because we explicitly + * **don't** want elements in different timing contexts (i.e. popups) + * to be accelerated, as it's not possible to sync these animations + * properly with those driven from the main window frameloop. + */ + if (!(subject instanceof HTMLElement)) { + return false; + } + const { onUpdate, transformTemplate } = motionValue.owner.getProps(); + return (supportsWaapi() && + name && + acceleratedValues$1.has(name) && + (name !== "transform" || !transformTemplate) && + /** + * If we're outputting values to onUpdate then we can't use WAAPI as there's + * no way to read the value from WAAPI every frame. + */ + !onUpdate && + !repeatDelay && + repeatType !== "mirror" && + damping !== 0 && + type !== "inertia"); + } + + /** + * Maximum time allowed between an animation being created and it being + * resolved for us to use the latter as the start time. + * + * This is to ensure that while we prefer to "start" an animation as soon + * as it's triggered, we also want to avoid a visual jump if there's a big delay + * between these two moments. + */ + const MAX_RESOLVE_DELAY = 40; + class AsyncMotionValueAnimation extends WithPromise { + constructor({ autoplay = true, delay = 0, type = "keyframes", repeat = 0, repeatDelay = 0, repeatType = "loop", keyframes, name, motionValue, element, ...options }) { + super(); + /** + * Bound to support return animation.stop pattern + */ + this.stop = () => { + if (this._animation) { + this._animation.stop(); + this.stopTimeline?.(); + } + this.keyframeResolver?.cancel(); + }; + this.createdAt = time.now(); + const optionsWithDefaults = { + autoplay, + delay, + type, + repeat, + repeatDelay, + repeatType, + name, + motionValue, + element, + ...options, + }; + const KeyframeResolver$1 = element?.KeyframeResolver || KeyframeResolver; + this.keyframeResolver = new KeyframeResolver$1(keyframes, (resolvedKeyframes, finalKeyframe, forced) => this.onKeyframesResolved(resolvedKeyframes, finalKeyframe, optionsWithDefaults, !forced), name, motionValue, element); + this.keyframeResolver?.scheduleResolve(); + } + onKeyframesResolved(keyframes, finalKeyframe, options, sync) { + this.keyframeResolver = undefined; + const { name, type, velocity, delay, isHandoff, onUpdate } = options; + this.resolvedAt = time.now(); + /** + * If we can't animate this value with the resolved keyframes + * then we should complete it immediately. + */ + if (!canAnimate(keyframes, name, type, velocity)) { + if (MotionGlobalConfig.instantAnimations || !delay) { + onUpdate?.(getFinalKeyframe$1(keyframes, options, finalKeyframe)); + } + keyframes[0] = keyframes[keyframes.length - 1]; + makeAnimationInstant(options); + options.repeat = 0; + } + /** + * Resolve startTime for the animation. + * + * This method uses the createdAt and resolvedAt to calculate the + * animation startTime. *Ideally*, we would use the createdAt time as t=0 + * as the following frame would then be the first frame of the animation in + * progress, which would feel snappier. + * + * However, if there's a delay (main thread work) between the creation of + * the animation and the first commited frame, we prefer to use resolvedAt + * to avoid a sudden jump into the animation. + */ + const startTime = sync + ? !this.resolvedAt + ? this.createdAt + : this.resolvedAt - this.createdAt > MAX_RESOLVE_DELAY + ? this.resolvedAt + : this.createdAt + : undefined; + const resolvedOptions = { + startTime, + finalKeyframe, + ...options, + keyframes, + }; + /** + * Animate via WAAPI if possible. If this is a handoff animation, the optimised animation will be running via + * WAAPI. Therefore, this animation must be JS to ensure it runs "under" the + * optimised animation. + */ + const animation = !isHandoff && supportsBrowserAnimation(resolvedOptions) + ? new NativeAnimationExtended({ + ...resolvedOptions, + element: resolvedOptions.motionValue.owner.current, + }) + : new JSAnimation(resolvedOptions); + animation.finished.then(() => this.notifyFinished()).catch(noop); + if (this.pendingTimeline) { + this.stopTimeline = animation.attachTimeline(this.pendingTimeline); + this.pendingTimeline = undefined; + } + this._animation = animation; + } + get finished() { + if (!this._animation) { + return this._finished; + } + else { + return this.animation.finished; + } + } + then(onResolve, _onReject) { + return this.finished.finally(onResolve).then(() => { }); + } + get animation() { + if (!this._animation) { + this.keyframeResolver?.resume(); + flushKeyframeResolvers(); + } + return this._animation; + } + get duration() { + return this.animation.duration; + } + get time() { + return this.animation.time; + } + set time(newTime) { + this.animation.time = newTime; + } + get speed() { + return this.animation.speed; + } + get state() { + return this.animation.state; + } + set speed(newSpeed) { + this.animation.speed = newSpeed; + } + get startTime() { + return this.animation.startTime; + } + attachTimeline(timeline) { + if (this._animation) { + this.stopTimeline = this.animation.attachTimeline(timeline); + } + else { + this.pendingTimeline = timeline; + } + return () => this.stop(); + } + play() { + this.animation.play(); + } + pause() { + this.animation.pause(); + } + complete() { + this.animation.complete(); + } + cancel() { + if (this._animation) { + this.animation.cancel(); + } + this.keyframeResolver?.cancel(); + } + } + + class GroupAnimation { + constructor(animations) { + // Bound to accomadate common `return animation.stop` pattern + this.stop = () => this.runAll("stop"); + this.animations = animations.filter(Boolean); + } + get finished() { + return Promise.all(this.animations.map((animation) => animation.finished)); + } + /** + * TODO: Filter out cancelled or stopped animations before returning + */ + getAll(propName) { + return this.animations[0][propName]; + } + setAll(propName, newValue) { + for (let i = 0; i < this.animations.length; i++) { + this.animations[i][propName] = newValue; + } + } + attachTimeline(timeline) { + const subscriptions = this.animations.map((animation) => animation.attachTimeline(timeline)); + return () => { + subscriptions.forEach((cancel, i) => { + cancel && cancel(); + this.animations[i].stop(); + }); + }; + } + get time() { + return this.getAll("time"); + } + set time(time) { + this.setAll("time", time); + } + get speed() { + return this.getAll("speed"); + } + set speed(speed) { + this.setAll("speed", speed); + } + get state() { + return this.getAll("state"); + } + get startTime() { + return this.getAll("startTime"); + } + get duration() { + let max = 0; + for (let i = 0; i < this.animations.length; i++) { + max = Math.max(max, this.animations[i].duration); + } + return max; + } + runAll(methodName) { + this.animations.forEach((controls) => controls[methodName]()); + } + play() { + this.runAll("play"); + } + pause() { + this.runAll("pause"); + } + cancel() { + this.runAll("cancel"); + } + complete() { + this.runAll("complete"); + } + } + + class GroupAnimationWithThen extends GroupAnimation { + then(onResolve, _onReject) { + return this.finished.finally(onResolve).then(() => { }); + } + } + + class NativeAnimationWrapper extends NativeAnimation { + constructor(animation) { + super(); + this.animation = animation; + animation.onfinish = () => { + this.finishedTime = this.time; + this.notifyFinished(); + }; + } + } + + const animationMaps = new WeakMap(); + const animationMapKey = (name, pseudoElement = "") => `${name}:${pseudoElement}`; + function getAnimationMap(element) { + const map = animationMaps.get(element) || new Map(); + animationMaps.set(element, map); + return map; + } + + /** + * Parse Framer's special CSS variable format into a CSS token and a fallback. + * + * ``` + * `var(--foo, #fff)` => [`--foo`, '#fff'] + * ``` + * + * @param current + */ + const splitCSSVariableRegex = + // eslint-disable-next-line redos-detector/no-unsafe-regex -- false positive, as it can match a lot of words + /^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u; + function parseCSSVariable(current) { + const match = splitCSSVariableRegex.exec(current); + if (!match) + return [,]; + const [, token1, token2, fallback] = match; + return [`--${token1 ?? token2}`, fallback]; + } + const maxDepth = 4; + function getVariableValue(current, element, depth = 1) { + exports.invariant(depth <= maxDepth, `Max CSS variable fallback depth detected in property "${current}". This may indicate a circular fallback dependency.`, "max-css-var-depth"); + const [token, fallback] = parseCSSVariable(current); + // No CSS variable detected + if (!token) + return; + // Attempt to read this CSS variable off the element + const resolved = window.getComputedStyle(element).getPropertyValue(token); + if (resolved) { + const trimmed = resolved.trim(); + return isNumericalString(trimmed) ? parseFloat(trimmed) : trimmed; + } + return isCSSVariableToken(fallback) + ? getVariableValue(fallback, element, depth + 1) + : fallback; + } + + function getValueTransition$1(transition, key) { + return (transition?.[key] ?? + transition?.["default"] ?? + transition); + } + + const positionalKeys = new Set([ + "width", + "height", + "top", + "left", + "right", + "bottom", + ...transformPropOrder, + ]); + + /** + * ValueType for "auto" + */ + const auto = { + test: (v) => v === "auto", + parse: (v) => v, + }; + + /** + * Tests a provided value against a ValueType + */ + const testValueType = (v) => (type) => type.test(v); + + /** + * A list of value types commonly used for dimensions + */ + const dimensionValueTypes = [number, px, percent, degrees, vw, vh, auto]; + /** + * Tests a dimensional value against the list of dimension ValueTypes + */ + const findDimensionValueType = (v) => dimensionValueTypes.find(testValueType(v)); + + function isNone(value) { + if (typeof value === "number") { + return value === 0; + } + else if (value !== null) { + return value === "none" || value === "0" || isZeroValueString(value); + } + else { + return true; + } + } + + /** + * Properties that should default to 1 or 100% + */ + const maxDefaults = new Set(["brightness", "contrast", "saturate", "opacity"]); + function applyDefaultFilter(v) { + const [name, value] = v.slice(0, -1).split("("); + if (name === "drop-shadow") + return v; + const [number] = value.match(floatRegex) || []; + if (!number) + return v; + const unit = value.replace(number, ""); + let defaultValue = maxDefaults.has(name) ? 1 : 0; + if (number !== value) + defaultValue *= 100; + return name + "(" + defaultValue + unit + ")"; + } + const functionRegex = /\b([a-z-]*)\(.*?\)/gu; + const filter = { + ...complex, + getAnimatableNone: (v) => { + const functions = v.match(functionRegex); + return functions ? functions.map(applyDefaultFilter).join(" ") : v; + }, + }; + + const int = { + ...number, + transform: Math.round, + }; + + const transformValueTypes = { + rotate: degrees, + rotateX: degrees, + rotateY: degrees, + rotateZ: degrees, + scale, + scaleX: scale, + scaleY: scale, + scaleZ: scale, + skew: degrees, + skewX: degrees, + skewY: degrees, + distance: px, + translateX: px, + translateY: px, + translateZ: px, + x: px, + y: px, + z: px, + perspective: px, + transformPerspective: px, + opacity: alpha, + originX: progressPercentage, + originY: progressPercentage, + originZ: px, + }; + + const numberValueTypes = { + // Border props + borderWidth: px, + borderTopWidth: px, + borderRightWidth: px, + borderBottomWidth: px, + borderLeftWidth: px, + borderRadius: px, + radius: px, + borderTopLeftRadius: px, + borderTopRightRadius: px, + borderBottomRightRadius: px, + borderBottomLeftRadius: px, + // Positioning props + width: px, + maxWidth: px, + height: px, + maxHeight: px, + top: px, + right: px, + bottom: px, + left: px, + // Spacing props + padding: px, + paddingTop: px, + paddingRight: px, + paddingBottom: px, + paddingLeft: px, + margin: px, + marginTop: px, + marginRight: px, + marginBottom: px, + marginLeft: px, + // Misc + backgroundPositionX: px, + backgroundPositionY: px, + ...transformValueTypes, + zIndex: int, + // SVG + fillOpacity: alpha, + strokeOpacity: alpha, + numOctaves: int, + }; + + /** + * A map of default value types for common values + */ + const defaultValueTypes = { + ...numberValueTypes, + // Color props + color, + backgroundColor: color, + outlineColor: color, + fill: color, + stroke: color, + // Border props + borderColor: color, + borderTopColor: color, + borderRightColor: color, + borderBottomColor: color, + borderLeftColor: color, + filter, + WebkitFilter: filter, + }; + /** + * Gets the default ValueType for the provided value key + */ + const getDefaultValueType = (key) => defaultValueTypes[key]; + + function getAnimatableNone(key, value) { + let defaultValueType = getDefaultValueType(key); + if (defaultValueType !== filter) + defaultValueType = complex; + // If value is not recognised as animatable, ie "none", create an animatable version origin based on the target + return defaultValueType.getAnimatableNone + ? defaultValueType.getAnimatableNone(value) + : undefined; + } + + /** + * If we encounter keyframes like "none" or "0" and we also have keyframes like + * "#fff" or "200px 200px" we want to find a keyframe to serve as a template for + * the "none" keyframes. In this case "#fff" or "200px 200px" - then these get turned into + * zero equivalents, i.e. "#fff0" or "0px 0px". + */ + const invalidTemplates = new Set(["auto", "none", "0"]); + function makeNoneKeyframesAnimatable(unresolvedKeyframes, noneKeyframeIndexes, name) { + let i = 0; + let animatableTemplate = undefined; + while (i < unresolvedKeyframes.length && !animatableTemplate) { + const keyframe = unresolvedKeyframes[i]; + if (typeof keyframe === "string" && + !invalidTemplates.has(keyframe) && + analyseComplexValue(keyframe).values.length) { + animatableTemplate = unresolvedKeyframes[i]; + } + i++; + } + if (animatableTemplate && name) { + for (const noneIndex of noneKeyframeIndexes) { + unresolvedKeyframes[noneIndex] = getAnimatableNone(name, animatableTemplate); + } + } + } + + class DOMKeyframesResolver extends KeyframeResolver { + constructor(unresolvedKeyframes, onComplete, name, motionValue, element) { + super(unresolvedKeyframes, onComplete, name, motionValue, element, true); + } + readKeyframes() { + const { unresolvedKeyframes, element, name } = this; + if (!element || !element.current) + return; + super.readKeyframes(); + /** + * If any keyframe is a CSS variable, we need to find its value by sampling the element + */ + for (let i = 0; i < unresolvedKeyframes.length; i++) { + let keyframe = unresolvedKeyframes[i]; + if (typeof keyframe === "string") { + keyframe = keyframe.trim(); + if (isCSSVariableToken(keyframe)) { + const resolved = getVariableValue(keyframe, element.current); + if (resolved !== undefined) { + unresolvedKeyframes[i] = resolved; + } + if (i === unresolvedKeyframes.length - 1) { + this.finalKeyframe = keyframe; + } + } + } + } + /** + * Resolve "none" values. We do this potentially twice - once before and once after measuring keyframes. + * This could be seen as inefficient but it's a trade-off to avoid measurements in more situations, which + * have a far bigger performance impact. + */ + this.resolveNoneKeyframes(); + /** + * Check to see if unit type has changed. If so schedule jobs that will + * temporarily set styles to the destination keyframes. + * Skip if we have more than two keyframes or this isn't a positional value. + * TODO: We can throw if there are multiple keyframes and the value type changes. + */ + if (!positionalKeys.has(name) || unresolvedKeyframes.length !== 2) { + return; + } + const [origin, target] = unresolvedKeyframes; + const originType = findDimensionValueType(origin); + const targetType = findDimensionValueType(target); + /** + * Either we don't recognise these value types or we can animate between them. + */ + if (originType === targetType) + return; + /** + * If both values are numbers or pixels, we can animate between them by + * converting them to numbers. + */ + if (isNumOrPxType(originType) && isNumOrPxType(targetType)) { + for (let i = 0; i < unresolvedKeyframes.length; i++) { + const value = unresolvedKeyframes[i]; + if (typeof value === "string") { + unresolvedKeyframes[i] = parseFloat(value); + } + } + } + else if (positionalValues[name]) { + /** + * Else, the only way to resolve this is by measuring the element. + */ + this.needsMeasurement = true; + } + } + resolveNoneKeyframes() { + const { unresolvedKeyframes, name } = this; + const noneKeyframeIndexes = []; + for (let i = 0; i < unresolvedKeyframes.length; i++) { + if (unresolvedKeyframes[i] === null || + isNone(unresolvedKeyframes[i])) { + noneKeyframeIndexes.push(i); + } + } + if (noneKeyframeIndexes.length) { + makeNoneKeyframesAnimatable(unresolvedKeyframes, noneKeyframeIndexes, name); + } + } + measureInitialState() { + const { element, unresolvedKeyframes, name } = this; + if (!element || !element.current) + return; + if (name === "height") { + this.suspendedScrollY = window.pageYOffset; + } + this.measuredOrigin = positionalValues[name](element.measureViewportBox(), window.getComputedStyle(element.current)); + unresolvedKeyframes[0] = this.measuredOrigin; + // Set final key frame to measure after next render + const measureKeyframe = unresolvedKeyframes[unresolvedKeyframes.length - 1]; + if (measureKeyframe !== undefined) { + element.getValue(name, measureKeyframe).jump(measureKeyframe, false); + } + } + measureEndState() { + const { element, name, unresolvedKeyframes } = this; + if (!element || !element.current) + return; + const value = element.getValue(name); + value && value.jump(this.measuredOrigin, false); + const finalKeyframeIndex = unresolvedKeyframes.length - 1; + const finalKeyframe = unresolvedKeyframes[finalKeyframeIndex]; + unresolvedKeyframes[finalKeyframeIndex] = positionalValues[name](element.measureViewportBox(), window.getComputedStyle(element.current)); + if (finalKeyframe !== null && this.finalKeyframe === undefined) { + this.finalKeyframe = finalKeyframe; + } + // If we removed transform values, reapply them before the next render + if (this.removedTransforms?.length) { + this.removedTransforms.forEach(([unsetTransformName, unsetTransformValue]) => { + element + .getValue(unsetTransformName) + .set(unsetTransformValue); + }); + } + this.resolveNoneKeyframes(); + } + } + + const pxValues = new Set([ + // Border props + "borderWidth", + "borderTopWidth", + "borderRightWidth", + "borderBottomWidth", + "borderLeftWidth", + "borderRadius", + "radius", + "borderTopLeftRadius", + "borderTopRightRadius", + "borderBottomRightRadius", + "borderBottomLeftRadius", + // Positioning props + "width", + "maxWidth", + "height", + "maxHeight", + "top", + "right", + "bottom", + "left", + // Spacing props + "padding", + "paddingTop", + "paddingRight", + "paddingBottom", + "paddingLeft", + "margin", + "marginTop", + "marginRight", + "marginBottom", + "marginLeft", + // Misc + "backgroundPositionX", + "backgroundPositionY", + ]); + + function applyPxDefaults(keyframes, name) { + for (let i = 0; i < keyframes.length; i++) { + if (typeof keyframes[i] === "number" && pxValues.has(name)) { + keyframes[i] = keyframes[i] + "px"; + } + } + } + + function isWaapiSupportedEasing(easing) { + return Boolean((typeof easing === "function" && supportsLinearEasing()) || + !easing || + (typeof easing === "string" && + (easing in supportedWaapiEasing || supportsLinearEasing())) || + isBezierDefinition(easing) || + (Array.isArray(easing) && easing.every(isWaapiSupportedEasing))); + } + + const supportsPartialKeyframes = /*@__PURE__*/ memo(() => { + try { + document.createElement("div").animate({ opacity: [1] }); + } + catch (e) { + return false; + } + return true; + }); + + /** + * A list of values that can be hardware-accelerated. + */ + const acceleratedValues = new Set([ + "opacity", + "clipPath", + "filter", + "transform", + // TODO: Can be accelerated but currently disabled until https://issues.chromium.org/issues/41491098 is resolved + // or until we implement support for linear() easing. + // "background-color" + ]); + + function camelToDash$1(str) { + return str.replace(/([A-Z])/g, (match) => `-${match.toLowerCase()}`); + } + + function resolveElements(elementOrSelector, scope, selectorCache) { + if (elementOrSelector instanceof EventTarget) { + return [elementOrSelector]; + } + else if (typeof elementOrSelector === "string") { + let root = document; + if (scope) { + root = scope.current; + } + const elements = selectorCache?.[elementOrSelector] ?? + root.querySelectorAll(elementOrSelector); + return elements ? Array.from(elements) : []; + } + return Array.from(elementOrSelector); + } + + function createSelectorEffect(subjectEffect) { + return (subject, values) => { + const elements = resolveElements(subject); + const subscriptions = []; + for (const element of elements) { + const remove = subjectEffect(element, values); + subscriptions.push(remove); + } + return () => { + for (const remove of subscriptions) + remove(); + }; + }; + } + + /** + * Provided a value and a ValueType, returns the value as that value type. + */ + const getValueAsType = (value, type) => { + return type && typeof value === "number" + ? type.transform(value) + : value; + }; + + class MotionValueState { + constructor() { + this.latest = {}; + this.values = new Map(); + } + set(name, value, render, computed, useDefaultValueType = true) { + const existingValue = this.values.get(name); + if (existingValue) { + existingValue.onRemove(); + } + const onChange = () => { + const v = value.get(); + if (useDefaultValueType) { + this.latest[name] = getValueAsType(v, numberValueTypes[name]); + } + else { + this.latest[name] = v; + } + render && frame.render(render); + }; + onChange(); + const cancelOnChange = value.on("change", onChange); + computed && value.addDependent(computed); + const remove = () => { + cancelOnChange(); + render && cancelFrame(render); + this.values.delete(name); + computed && value.removeDependent(computed); + }; + this.values.set(name, { value, onRemove: remove }); + return remove; + } + get(name) { + return this.values.get(name)?.value; + } + destroy() { + for (const value of this.values.values()) { + value.onRemove(); + } + } + } + + function createEffect(addValue) { + const stateCache = new WeakMap(); + const subscriptions = []; + return (subject, values) => { + const state = stateCache.get(subject) ?? new MotionValueState(); + stateCache.set(subject, state); + for (const key in values) { + const value = values[key]; + const remove = addValue(subject, state, key, value); + subscriptions.push(remove); + } + return () => { + for (const cancel of subscriptions) + cancel(); + }; + }; + } + + function canSetAsProperty(element, name) { + if (!(name in element)) + return false; + const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(element), name) || + Object.getOwnPropertyDescriptor(element, name); + // Check if it has a setter + return descriptor && typeof descriptor.set === "function"; + } + const addAttrValue = (element, state, key, value) => { + const isProp = canSetAsProperty(element, key); + const name = isProp + ? key + : key.startsWith("data") || key.startsWith("aria") + ? camelToDash$1(key) + : key; + /** + * Set attribute directly via property if available + */ + const render = isProp + ? () => { + element[name] = state.latest[key]; + } + : () => { + const v = state.latest[key]; + if (v === null || v === undefined) { + element.removeAttribute(name); + } + else { + element.setAttribute(name, String(v)); + } + }; + return state.set(key, value, render); + }; + const attrEffect = /*@__PURE__*/ createSelectorEffect( + /*@__PURE__*/ createEffect(addAttrValue)); + + const propEffect = /*@__PURE__*/ createEffect((subject, state, key, value) => { + return state.set(key, value, () => { + subject[key] = state.latest[key]; + }, undefined, false); + }); + + /** + * Checks if an element is an HTML element in a way + * that works across iframes + */ + function isHTMLElement(element) { + return isObject(element) && "offsetHeight" in element; + } + + /** + * Maximum time between the value of two frames, beyond which we + * assume the velocity has since been 0. + */ + const MAX_VELOCITY_DELTA = 30; + const isFloat = (value) => { + return !isNaN(parseFloat(value)); + }; + const collectMotionValues = { + current: undefined, + }; + /** + * `MotionValue` is used to track the state and velocity of motion values. + * + * @public + */ + class MotionValue { + /** + * @param init - The initiating value + * @param config - Optional configuration options + * + * - `transformer`: A function to transform incoming values with. + */ + constructor(init, options = {}) { + /** + * Tracks whether this value can output a velocity. Currently this is only true + * if the value is numerical, but we might be able to widen the scope here and support + * other value types. + * + * @internal + */ + this.canTrackVelocity = null; + /** + * An object containing a SubscriptionManager for each active event. + */ + this.events = {}; + this.updateAndNotify = (v) => { + const currentTime = time.now(); + /** + * If we're updating the value during another frame or eventloop + * than the previous frame, then the we set the previous frame value + * to current. + */ + if (this.updatedAt !== currentTime) { + this.setPrevFrameValue(); + } + this.prev = this.current; + this.setCurrent(v); + // Update update subscribers + if (this.current !== this.prev) { + this.events.change?.notify(this.current); + if (this.dependents) { + for (const dependent of this.dependents) { + dependent.dirty(); + } + } + } + }; + this.hasAnimated = false; + this.setCurrent(init); + this.owner = options.owner; + } + setCurrent(current) { + this.current = current; + this.updatedAt = time.now(); + if (this.canTrackVelocity === null && current !== undefined) { + this.canTrackVelocity = isFloat(this.current); + } + } + setPrevFrameValue(prevFrameValue = this.current) { + this.prevFrameValue = prevFrameValue; + this.prevUpdatedAt = this.updatedAt; + } + /** + * Adds a function that will be notified when the `MotionValue` is updated. + * + * It returns a function that, when called, will cancel the subscription. + * + * When calling `onChange` inside a React component, it should be wrapped with the + * `useEffect` hook. As it returns an unsubscribe function, this should be returned + * from the `useEffect` function to ensure you don't add duplicate subscribers.. + * + * ```jsx + * export const MyComponent = () => { + * const x = useMotionValue(0) + * const y = useMotionValue(0) + * const opacity = useMotionValue(1) + * + * useEffect(() => { + * function updateOpacity() { + * const maxXY = Math.max(x.get(), y.get()) + * const newOpacity = transform(maxXY, [0, 100], [1, 0]) + * opacity.set(newOpacity) + * } + * + * const unsubscribeX = x.on("change", updateOpacity) + * const unsubscribeY = y.on("change", updateOpacity) + * + * return () => { + * unsubscribeX() + * unsubscribeY() + * } + * }, []) + * + * return + * } + * ``` + * + * @param subscriber - A function that receives the latest value. + * @returns A function that, when called, will cancel this subscription. + * + * @deprecated + */ + onChange(subscription) { + { + warnOnce(false, `value.onChange(callback) is deprecated. Switch to value.on("change", callback).`); + } + return this.on("change", subscription); + } + on(eventName, callback) { + if (!this.events[eventName]) { + this.events[eventName] = new SubscriptionManager(); + } + const unsubscribe = this.events[eventName].add(callback); + if (eventName === "change") { + return () => { + unsubscribe(); + /** + * If we have no more change listeners by the start + * of the next frame, stop active animations. + */ + frame.read(() => { + if (!this.events.change.getSize()) { + this.stop(); + } + }); + }; + } + return unsubscribe; + } + clearListeners() { + for (const eventManagers in this.events) { + this.events[eventManagers].clear(); + } + } + /** + * Attaches a passive effect to the `MotionValue`. + */ + attach(passiveEffect, stopPassiveEffect) { + this.passiveEffect = passiveEffect; + this.stopPassiveEffect = stopPassiveEffect; + } + /** + * Sets the state of the `MotionValue`. + * + * @remarks + * + * ```jsx + * const x = useMotionValue(0) + * x.set(10) + * ``` + * + * @param latest - Latest value to set. + * @param render - Whether to notify render subscribers. Defaults to `true` + * + * @public + */ + set(v) { + if (!this.passiveEffect) { + this.updateAndNotify(v); + } + else { + this.passiveEffect(v, this.updateAndNotify); + } + } + setWithVelocity(prev, current, delta) { + this.set(current); + this.prev = undefined; + this.prevFrameValue = prev; + this.prevUpdatedAt = this.updatedAt - delta; + } + /** + * Set the state of the `MotionValue`, stopping any active animations, + * effects, and resets velocity to `0`. + */ + jump(v, endAnimation = true) { + this.updateAndNotify(v); + this.prev = v; + this.prevUpdatedAt = this.prevFrameValue = undefined; + endAnimation && this.stop(); + if (this.stopPassiveEffect) + this.stopPassiveEffect(); + } + dirty() { + this.events.change?.notify(this.current); + } + addDependent(dependent) { + if (!this.dependents) { + this.dependents = new Set(); + } + this.dependents.add(dependent); + } + removeDependent(dependent) { + if (this.dependents) { + this.dependents.delete(dependent); + } + } + /** + * Returns the latest state of `MotionValue` + * + * @returns - The latest state of `MotionValue` + * + * @public + */ + get() { + if (collectMotionValues.current) { + collectMotionValues.current.push(this); + } + return this.current; + } + /** + * @public + */ + getPrevious() { + return this.prev; + } + /** + * Returns the latest velocity of `MotionValue` + * + * @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical. + * + * @public + */ + getVelocity() { + const currentTime = time.now(); + if (!this.canTrackVelocity || + this.prevFrameValue === undefined || + currentTime - this.updatedAt > MAX_VELOCITY_DELTA) { + return 0; + } + const delta = Math.min(this.updatedAt - this.prevUpdatedAt, MAX_VELOCITY_DELTA); + // Casts because of parseFloat's poor typing + return velocityPerSecond(parseFloat(this.current) - + parseFloat(this.prevFrameValue), delta); + } + /** + * Registers a new animation to control this `MotionValue`. Only one + * animation can drive a `MotionValue` at one time. + * + * ```jsx + * value.start() + * ``` + * + * @param animation - A function that starts the provided animation + */ + start(startAnimation) { + this.stop(); + return new Promise((resolve) => { + this.hasAnimated = true; + this.animation = startAnimation(resolve); + if (this.events.animationStart) { + this.events.animationStart.notify(); + } + }).then(() => { + if (this.events.animationComplete) { + this.events.animationComplete.notify(); + } + this.clearAnimation(); + }); + } + /** + * Stop the currently active animation. + * + * @public + */ + stop() { + if (this.animation) { + this.animation.stop(); + if (this.events.animationCancel) { + this.events.animationCancel.notify(); + } + } + this.clearAnimation(); + } + /** + * Returns `true` if this value is currently animating. + * + * @public + */ + isAnimating() { + return !!this.animation; + } + clearAnimation() { + delete this.animation; + } + /** + * Destroy and clean up subscribers to this `MotionValue`. + * + * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically + * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually + * created a `MotionValue` via the `motionValue` function. + * + * @public + */ + destroy() { + this.dependents?.clear(); + this.events.destroy?.notify(); + this.clearListeners(); + this.stop(); + if (this.stopPassiveEffect) { + this.stopPassiveEffect(); + } + } + } + function motionValue(init, options) { + return new MotionValue(init, options); + } + + const translateAlias$1 = { + x: "translateX", + y: "translateY", + z: "translateZ", + transformPerspective: "perspective", + }; + function buildTransform$1(state) { + let transform = ""; + let transformIsDefault = true; + /** + * Loop over all possible transforms in order, adding the ones that + * are present to the transform string. + */ + for (let i = 0; i < transformPropOrder.length; i++) { + const key = transformPropOrder[i]; + const value = state.latest[key]; + if (value === undefined) + continue; + let valueIsDefault = true; + if (typeof value === "number") { + valueIsDefault = value === (key.startsWith("scale") ? 1 : 0); + } + else { + valueIsDefault = parseFloat(value) === 0; + } + if (!valueIsDefault) { + transformIsDefault = false; + const transformName = translateAlias$1[key] || key; + const valueToRender = state.latest[key]; + transform += `${transformName}(${valueToRender}) `; + } + } + return transformIsDefault ? "none" : transform.trim(); + } + + const originProps = new Set(["originX", "originY", "originZ"]); + const addStyleValue = (element, state, key, value) => { + let render = undefined; + let computed = undefined; + if (transformProps.has(key)) { + if (!state.get("transform")) { + // If this is an HTML element, we need to set the transform-box to fill-box + // to normalise the transform relative to the element's bounding box + if (!isHTMLElement(element) && !state.get("transformBox")) { + addStyleValue(element, state, "transformBox", new MotionValue("fill-box")); + } + state.set("transform", new MotionValue("none"), () => { + element.style.transform = buildTransform$1(state); + }); + } + computed = state.get("transform"); + } + else if (originProps.has(key)) { + if (!state.get("transformOrigin")) { + state.set("transformOrigin", new MotionValue(""), () => { + const originX = state.latest.originX ?? "50%"; + const originY = state.latest.originY ?? "50%"; + const originZ = state.latest.originZ ?? 0; + element.style.transformOrigin = `${originX} ${originY} ${originZ}`; + }); + } + computed = state.get("transformOrigin"); + } + else if (isCSSVar(key)) { + render = () => { + element.style.setProperty(key, state.latest[key]); + }; + } + else { + render = () => { + element.style[key] = state.latest[key]; + }; + } + return state.set(key, value, render, computed); + }; + const styleEffect = /*@__PURE__*/ createSelectorEffect( + /*@__PURE__*/ createEffect(addStyleValue)); + + const toPx = px.transform; + function addSVGPathValue(element, state, key, value) { + frame.render(() => element.setAttribute("pathLength", "1")); + if (key === "pathOffset") { + return state.set(key, value, () => element.setAttribute("stroke-dashoffset", toPx(-state.latest[key]))); + } + else { + if (!state.get("stroke-dasharray")) { + state.set("stroke-dasharray", new MotionValue("1 1"), () => { + const { pathLength = 1, pathSpacing } = state.latest; + element.setAttribute("stroke-dasharray", `${toPx(pathLength)} ${toPx(pathSpacing ?? 1 - Number(pathLength))}`); + }); + } + return state.set(key, value, undefined, state.get("stroke-dasharray")); + } + } + const addSVGValue = (element, state, key, value) => { + if (key.startsWith("path")) { + return addSVGPathValue(element, state, key, value); + } + else if (key.startsWith("attr")) { + return addAttrValue(element, state, convertAttrKey(key), value); + } + const handler = key in element.style ? addStyleValue : addAttrValue; + return handler(element, state, key, value); + }; + const svgEffect = /*@__PURE__*/ createSelectorEffect( + /*@__PURE__*/ createEffect(addSVGValue)); + function convertAttrKey(key) { + return key.replace(/^attr([A-Z])/, (_, firstChar) => firstChar.toLowerCase()); + } + + const { schedule: microtask, cancel: cancelMicrotask } = + /* @__PURE__ */ createRenderBatcher(queueMicrotask, false); + + const isDragging = { + x: false, + y: false, + }; + function isDragActive() { + return isDragging.x || isDragging.y; + } + + function setDragLock(axis) { + if (axis === "x" || axis === "y") { + if (isDragging[axis]) { + return null; + } + else { + isDragging[axis] = true; + return () => { + isDragging[axis] = false; + }; + } + } + else { + if (isDragging.x || isDragging.y) { + return null; + } + else { + isDragging.x = isDragging.y = true; + return () => { + isDragging.x = isDragging.y = false; + }; + } + } + } + + function setupGesture(elementOrSelector, options) { + const elements = resolveElements(elementOrSelector); + const gestureAbortController = new AbortController(); + const eventOptions = { + passive: true, + ...options, + signal: gestureAbortController.signal, + }; + const cancel = () => gestureAbortController.abort(); + return [elements, eventOptions, cancel]; + } + + function isValidHover(event) { + return !(event.pointerType === "touch" || isDragActive()); + } + /** + * Create a hover gesture. hover() is different to .addEventListener("pointerenter") + * in that it has an easier syntax, filters out polyfilled touch events, interoperates + * with drag gestures, and automatically removes the "pointerennd" event listener when the hover ends. + * + * @public + */ + function hover(elementOrSelector, onHoverStart, options = {}) { + const [elements, eventOptions, cancel] = setupGesture(elementOrSelector, options); + const onPointerEnter = (enterEvent) => { + if (!isValidHover(enterEvent)) + return; + const { target } = enterEvent; + const onHoverEnd = onHoverStart(target, enterEvent); + if (typeof onHoverEnd !== "function" || !target) + return; + const onPointerLeave = (leaveEvent) => { + if (!isValidHover(leaveEvent)) + return; + onHoverEnd(leaveEvent); + target.removeEventListener("pointerleave", onPointerLeave); + }; + target.addEventListener("pointerleave", onPointerLeave, eventOptions); + }; + elements.forEach((element) => { + element.addEventListener("pointerenter", onPointerEnter, eventOptions); + }); + return cancel; + } + + /** + * Recursively traverse up the tree to check whether the provided child node + * is the parent or a descendant of it. + * + * @param parent - Element to find + * @param child - Element to test against parent + */ + const isNodeOrChild = (parent, child) => { + if (!child) { + return false; + } + else if (parent === child) { + return true; + } + else { + return isNodeOrChild(parent, child.parentElement); + } + }; + + const isPrimaryPointer = (event) => { + if (event.pointerType === "mouse") { + return typeof event.button !== "number" || event.button <= 0; + } + else { + /** + * isPrimary is true for all mice buttons, whereas every touch point + * is regarded as its own input. So subsequent concurrent touch points + * will be false. + * + * Specifically match against false here as incomplete versions of + * PointerEvents in very old browser might have it set as undefined. + */ + return event.isPrimary !== false; + } + }; + + const focusableElements = new Set([ + "BUTTON", + "INPUT", + "SELECT", + "TEXTAREA", + "A", + ]); + function isElementKeyboardAccessible(element) { + return (focusableElements.has(element.tagName) || + element.tabIndex !== -1); + } + + const isPressing = new WeakSet(); + + /** + * Filter out events that are not "Enter" keys. + */ + function filterEvents(callback) { + return (event) => { + if (event.key !== "Enter") + return; + callback(event); + }; + } + function firePointerEvent(target, type) { + target.dispatchEvent(new PointerEvent("pointer" + type, { isPrimary: true, bubbles: true })); + } + const enableKeyboardPress = (focusEvent, eventOptions) => { + const element = focusEvent.currentTarget; + if (!element) + return; + const handleKeydown = filterEvents(() => { + if (isPressing.has(element)) + return; + firePointerEvent(element, "down"); + const handleKeyup = filterEvents(() => { + firePointerEvent(element, "up"); + }); + const handleBlur = () => firePointerEvent(element, "cancel"); + element.addEventListener("keyup", handleKeyup, eventOptions); + element.addEventListener("blur", handleBlur, eventOptions); + }); + element.addEventListener("keydown", handleKeydown, eventOptions); + /** + * Add an event listener that fires on blur to remove the keydown events. + */ + element.addEventListener("blur", () => element.removeEventListener("keydown", handleKeydown), eventOptions); + }; + + /** + * Filter out events that are not primary pointer events, or are triggering + * while a Motion gesture is active. + */ + function isValidPressEvent(event) { + return isPrimaryPointer(event) && !isDragActive(); + } + /** + * Create a press gesture. + * + * Press is different to `"pointerdown"`, `"pointerup"` in that it + * automatically filters out secondary pointer events like right + * click and multitouch. + * + * It also adds accessibility support for keyboards, where + * an element with a press gesture will receive focus and + * trigger on Enter `"keydown"` and `"keyup"` events. + * + * This is different to a browser's `"click"` event, which does + * respond to keyboards but only for the `"click"` itself, rather + * than the press start and end/cancel. The element also needs + * to be focusable for this to work, whereas a press gesture will + * make an element focusable by default. + * + * @public + */ + function press(targetOrSelector, onPressStart, options = {}) { + const [targets, eventOptions, cancelEvents] = setupGesture(targetOrSelector, options); + const startPress = (startEvent) => { + const target = startEvent.currentTarget; + if (!isValidPressEvent(startEvent)) + return; + isPressing.add(target); + const onPressEnd = onPressStart(target, startEvent); + const onPointerEnd = (endEvent, success) => { + window.removeEventListener("pointerup", onPointerUp); + window.removeEventListener("pointercancel", onPointerCancel); + if (isPressing.has(target)) { + isPressing.delete(target); + } + if (!isValidPressEvent(endEvent)) { + return; + } + if (typeof onPressEnd === "function") { + onPressEnd(endEvent, { success }); + } + }; + const onPointerUp = (upEvent) => { + onPointerEnd(upEvent, target === window || + target === document || + options.useGlobalTarget || + isNodeOrChild(target, upEvent.target)); + }; + const onPointerCancel = (cancelEvent) => { + onPointerEnd(cancelEvent, false); + }; + window.addEventListener("pointerup", onPointerUp, eventOptions); + window.addEventListener("pointercancel", onPointerCancel, eventOptions); + }; + targets.forEach((target) => { + const pointerDownTarget = options.useGlobalTarget ? window : target; + pointerDownTarget.addEventListener("pointerdown", startPress, eventOptions); + if (isHTMLElement(target)) { + target.addEventListener("focus", (event) => enableKeyboardPress(event, eventOptions)); + if (!isElementKeyboardAccessible(target) && + !target.hasAttribute("tabindex")) { + target.tabIndex = 0; + } + } + }); + return cancelEvents; + } + + function getComputedStyle$2(element, name) { + const computedStyle = window.getComputedStyle(element); + return isCSSVar(name) + ? computedStyle.getPropertyValue(name) + : computedStyle[name]; + } + + /** + * Checks if an element is an SVG element in a way + * that works across iframes + */ + function isSVGElement(element) { + return isObject(element) && "ownerSVGElement" in element; + } + + const resizeHandlers = new WeakMap(); + let observer; + const getSize = (borderBoxAxis, svgAxis, htmlAxis) => (target, borderBoxSize) => { + if (borderBoxSize && borderBoxSize[0]) { + return borderBoxSize[0][(borderBoxAxis + "Size")]; + } + else if (isSVGElement(target) && "getBBox" in target) { + return target.getBBox()[svgAxis]; + } + else { + return target[htmlAxis]; + } + }; + const getWidth = /*@__PURE__*/ getSize("inline", "width", "offsetWidth"); + const getHeight = /*@__PURE__*/ getSize("block", "height", "offsetHeight"); + function notifyTarget({ target, borderBoxSize }) { + resizeHandlers.get(target)?.forEach((handler) => { + handler(target, { + get width() { + return getWidth(target, borderBoxSize); + }, + get height() { + return getHeight(target, borderBoxSize); + }, + }); + }); + } + function notifyAll(entries) { + entries.forEach(notifyTarget); + } + function createResizeObserver() { + if (typeof ResizeObserver === "undefined") + return; + observer = new ResizeObserver(notifyAll); + } + function resizeElement(target, handler) { + if (!observer) + createResizeObserver(); + const elements = resolveElements(target); + elements.forEach((element) => { + let elementHandlers = resizeHandlers.get(element); + if (!elementHandlers) { + elementHandlers = new Set(); + resizeHandlers.set(element, elementHandlers); + } + elementHandlers.add(handler); + observer?.observe(element); + }); + return () => { + elements.forEach((element) => { + const elementHandlers = resizeHandlers.get(element); + elementHandlers?.delete(handler); + if (!elementHandlers?.size) { + observer?.unobserve(element); + } + }); + }; + } + + const windowCallbacks = new Set(); + let windowResizeHandler; + function createWindowResizeHandler() { + windowResizeHandler = () => { + const info = { + get width() { + return window.innerWidth; + }, + get height() { + return window.innerHeight; + }, + }; + windowCallbacks.forEach((callback) => callback(info)); + }; + window.addEventListener("resize", windowResizeHandler); + } + function resizeWindow(callback) { + windowCallbacks.add(callback); + if (!windowResizeHandler) + createWindowResizeHandler(); + return () => { + windowCallbacks.delete(callback); + if (!windowCallbacks.size && + typeof windowResizeHandler === "function") { + window.removeEventListener("resize", windowResizeHandler); + windowResizeHandler = undefined; + } + }; + } + + function resize(a, b) { + return typeof a === "function" ? resizeWindow(a) : resizeElement(a, b); + } + + function observeTimeline(update, timeline) { + let prevProgress; + const onFrame = () => { + const { currentTime } = timeline; + const percentage = currentTime === null ? 0 : currentTime.value; + const progress = percentage / 100; + if (prevProgress !== progress) { + update(progress); + } + prevProgress = progress; + }; + frame.preUpdate(onFrame, true); + return () => cancelFrame(onFrame); + } + + function record() { + const { value } = statsBuffer; + if (value === null) { + cancelFrame(record); + return; + } + value.frameloop.rate.push(frameData.delta); + value.animations.mainThread.push(activeAnimations.mainThread); + value.animations.waapi.push(activeAnimations.waapi); + value.animations.layout.push(activeAnimations.layout); + } + function mean(values) { + return values.reduce((acc, value) => acc + value, 0) / values.length; + } + function summarise(values, calcAverage = mean) { + if (values.length === 0) { + return { + min: 0, + max: 0, + avg: 0, + }; + } + return { + min: Math.min(...values), + max: Math.max(...values), + avg: calcAverage(values), + }; + } + const msToFps = (ms) => Math.round(1000 / ms); + function clearStatsBuffer() { + statsBuffer.value = null; + statsBuffer.addProjectionMetrics = null; + } + function reportStats() { + const { value } = statsBuffer; + if (!value) { + throw new Error("Stats are not being measured"); + } + clearStatsBuffer(); + cancelFrame(record); + const summary = { + frameloop: { + setup: summarise(value.frameloop.setup), + rate: summarise(value.frameloop.rate), + read: summarise(value.frameloop.read), + resolveKeyframes: summarise(value.frameloop.resolveKeyframes), + preUpdate: summarise(value.frameloop.preUpdate), + update: summarise(value.frameloop.update), + preRender: summarise(value.frameloop.preRender), + render: summarise(value.frameloop.render), + postRender: summarise(value.frameloop.postRender), + }, + animations: { + mainThread: summarise(value.animations.mainThread), + waapi: summarise(value.animations.waapi), + layout: summarise(value.animations.layout), + }, + layoutProjection: { + nodes: summarise(value.layoutProjection.nodes), + calculatedTargetDeltas: summarise(value.layoutProjection.calculatedTargetDeltas), + calculatedProjections: summarise(value.layoutProjection.calculatedProjections), + }, + }; + /** + * Convert the rate to FPS + */ + const { rate } = summary.frameloop; + rate.min = msToFps(rate.min); + rate.max = msToFps(rate.max); + rate.avg = msToFps(rate.avg); + [rate.min, rate.max] = [rate.max, rate.min]; + return summary; + } + function recordStats() { + if (statsBuffer.value) { + clearStatsBuffer(); + throw new Error("Stats are already being measured"); + } + const newStatsBuffer = statsBuffer; + newStatsBuffer.value = { + frameloop: { + setup: [], + rate: [], + read: [], + resolveKeyframes: [], + preUpdate: [], + update: [], + preRender: [], + render: [], + postRender: [], + }, + animations: { + mainThread: [], + waapi: [], + layout: [], + }, + layoutProjection: { + nodes: [], + calculatedTargetDeltas: [], + calculatedProjections: [], + }, + }; + newStatsBuffer.addProjectionMetrics = (metrics) => { + const { layoutProjection } = newStatsBuffer.value; + layoutProjection.nodes.push(metrics.nodes); + layoutProjection.calculatedTargetDeltas.push(metrics.calculatedTargetDeltas); + layoutProjection.calculatedProjections.push(metrics.calculatedProjections); + }; + frame.postRender(record, true); + return reportStats; + } + + /** + * Checks if an element is specifically an SVGSVGElement (the root SVG element) + * in a way that works across iframes + */ + function isSVGSVGElement(element) { + return isSVGElement(element) && element.tagName === "svg"; + } + + function getOriginIndex(from, total) { + if (from === "first") { + return 0; + } + else { + const lastIndex = total - 1; + return from === "last" ? lastIndex : lastIndex / 2; + } + } + function stagger(duration = 0.1, { startDelay = 0, from = 0, ease } = {}) { + return (i, total) => { + const fromIndex = typeof from === "number" ? from : getOriginIndex(from, total); + const distance = Math.abs(fromIndex - i); + let delay = duration * distance; + if (ease) { + const maxDelay = total * duration; + const easingFunction = easingDefinitionToFunction(ease); + delay = easingFunction(delay / maxDelay) * maxDelay; + } + return startDelay + delay; + }; + } + + function transform(...args) { + const useImmediate = !Array.isArray(args[0]); + const argOffset = useImmediate ? 0 : -1; + const inputValue = args[0 + argOffset]; + const inputRange = args[1 + argOffset]; + const outputRange = args[2 + argOffset]; + const options = args[3 + argOffset]; + const interpolator = interpolate(inputRange, outputRange, options); + return useImmediate ? interpolator(inputValue) : interpolator; + } + + function subscribeValue(inputValues, outputValue, getLatest) { + const update = () => outputValue.set(getLatest()); + const scheduleUpdate = () => frame.preRender(update, false, true); + const subscriptions = inputValues.map((v) => v.on("change", scheduleUpdate)); + outputValue.on("destroy", () => { + subscriptions.forEach((unsubscribe) => unsubscribe()); + cancelFrame(update); + }); + } + + /** + * Create a `MotionValue` that transforms the output of other `MotionValue`s by + * passing their latest values through a transform function. + * + * Whenever a `MotionValue` referred to in the provided function is updated, + * it will be re-evaluated. + * + * ```jsx + * const x = motionValue(0) + * const y = transformValue(() => x.get() * 2) // double x + * ``` + * + * @param transformer - A transform function. This function must be pure with no side-effects or conditional statements. + * @returns `MotionValue` + * + * @public + */ + function transformValue(transform) { + const collectedValues = []; + /** + * Open session of collectMotionValues. Any MotionValue that calls get() + * inside transform will be saved into this array. + */ + collectMotionValues.current = collectedValues; + const initialValue = transform(); + collectMotionValues.current = undefined; + const value = motionValue(initialValue); + subscribeValue(collectedValues, value, transform); + return value; + } + + /** + * Create a `MotionValue` that maps the output of another `MotionValue` by + * mapping it from one range of values into another. + * + * @remarks + * + * Given an input range of `[-200, -100, 100, 200]` and an output range of + * `[0, 1, 1, 0]`, the returned `MotionValue` will: + * + * - When provided a value between `-200` and `-100`, will return a value between `0` and `1`. + * - When provided a value between `-100` and `100`, will return `1`. + * - When provided a value between `100` and `200`, will return a value between `1` and `0` + * + * The input range must be a linear series of numbers. The output range + * can be any value type supported by Motion: numbers, colors, shadows, etc. + * + * Every value in the output range must be of the same type and in the same format. + * + * ```jsx + * const x = motionValue(0) + * const xRange = [-200, -100, 100, 200] + * const opacityRange = [0, 1, 1, 0] + * const opacity = mapValue(x, xRange, opacityRange) + * ``` + * + * @param inputValue - `MotionValue` + * @param inputRange - A linear series of numbers (either all increasing or decreasing) + * @param outputRange - A series of numbers, colors or strings. Must be the same length as `inputRange`. + * @param options - + * + * - clamp: boolean. Clamp values to within the given range. Defaults to `true` + * - ease: EasingFunction[]. Easing functions to use on the interpolations between each value in the input and output ranges. If provided as an array, the array must be one item shorter than the input and output ranges, as the easings apply to the transition between each. + * + * @returns `MotionValue` + * + * @public + */ + function mapValue(inputValue, inputRange, outputRange, options) { + const map = transform(inputRange, outputRange, options); + return transformValue(() => map(inputValue.get())); + } + + const isMotionValue = (value) => Boolean(value && value.getVelocity); + + /** + * Create a `MotionValue` that animates to its latest value using a spring. + * Can either be a value or track another `MotionValue`. + * + * ```jsx + * const x = motionValue(0) + * const y = transformValue(() => x.get() * 2) // double x + * ``` + * + * @param transformer - A transform function. This function must be pure with no side-effects or conditional statements. + * @returns `MotionValue` + * + * @public + */ + function springValue(source, options) { + const initialValue = isMotionValue(source) ? source.get() : source; + const value = motionValue(initialValue); + attachSpring(value, source, options); + return value; + } + function attachSpring(value, source, options) { + const initialValue = value.get(); + let activeAnimation = null; + let latestValue = initialValue; + let latestSetter; + const unit = typeof initialValue === "string" + ? initialValue.replace(/[\d.-]/g, "") + : undefined; + const stopAnimation = () => { + if (activeAnimation) { + activeAnimation.stop(); + activeAnimation = null; + } + }; + const startAnimation = () => { + stopAnimation(); + activeAnimation = new JSAnimation({ + keyframes: [asNumber$1(value.get()), asNumber$1(latestValue)], + velocity: value.getVelocity(), + type: "spring", + restDelta: 0.001, + restSpeed: 0.01, + ...options, + onUpdate: latestSetter, + }); + }; + value.attach((v, set) => { + latestValue = v; + latestSetter = (latest) => set(parseValue(latest, unit)); + frame.postRender(startAnimation); + return value.get(); + }, stopAnimation); + if (isMotionValue(source)) { + const removeSourceOnChange = source.on("change", (v) => value.set(parseValue(v, unit))); + const removeValueOnDestroy = value.on("destroy", removeSourceOnChange); + return () => { + removeSourceOnChange(); + removeValueOnDestroy(); + }; + } + return stopAnimation; + } + function parseValue(v, unit) { + return unit ? v + unit : v; + } + function asNumber$1(v) { + return typeof v === "number" ? v : parseFloat(v); + } + + /** + * A list of all ValueTypes + */ + const valueTypes = [...dimensionValueTypes, color, complex]; + /** + * Tests a value against the list of ValueTypes + */ + const findValueType = (v) => valueTypes.find(testValueType(v)); + + function chooseLayerType(valueName) { + if (valueName === "layout") + return "group"; + if (valueName === "enter" || valueName === "new") + return "new"; + if (valueName === "exit" || valueName === "old") + return "old"; + return "group"; + } + + let pendingRules = {}; + let style = null; + const css = { + set: (selector, values) => { + pendingRules[selector] = values; + }, + commit: () => { + if (!style) { + style = document.createElement("style"); + style.id = "motion-view"; + } + let cssText = ""; + for (const selector in pendingRules) { + const rule = pendingRules[selector]; + cssText += `${selector} {\n`; + for (const [property, value] of Object.entries(rule)) { + cssText += ` ${property}: ${value};\n`; + } + cssText += "}\n"; + } + style.textContent = cssText; + document.head.appendChild(style); + pendingRules = {}; + }, + remove: () => { + if (style && style.parentElement) { + style.parentElement.removeChild(style); + } + }, + }; + + function getViewAnimationLayerInfo(pseudoElement) { + const match = pseudoElement.match(/::view-transition-(old|new|group|image-pair)\((.*?)\)/); + if (!match) + return null; + return { layer: match[2], type: match[1] }; + } + + function filterViewAnimations(animation) { + const { effect } = animation; + if (!effect) + return false; + return (effect.target === document.documentElement && + effect.pseudoElement?.startsWith("::view-transition")); + } + function getViewAnimations() { + return document.getAnimations().filter(filterViewAnimations); + } + + function hasTarget(target, targets) { + return targets.has(target) && Object.keys(targets.get(target)).length > 0; + } + + const definitionNames = ["layout", "enter", "exit", "new", "old"]; + function startViewAnimation(builder) { + const { update, targets, options: defaultOptions } = builder; + if (!document.startViewTransition) { + return new Promise(async (resolve) => { + await update(); + resolve(new GroupAnimation([])); + }); + } + // TODO: Go over existing targets and ensure they all have ids + /** + * If we don't have any animations defined for the root target, + * remove it from being captured. + */ + if (!hasTarget("root", targets)) { + css.set(":root", { + "view-transition-name": "none", + }); + } + /** + * Set the timing curve to linear for all view transition layers. + * This gets baked into the keyframes, which can't be changed + * without breaking the generated animation. + * + * This allows us to set easing via updateTiming - which can be changed. + */ + css.set("::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*)", { "animation-timing-function": "linear !important" }); + css.commit(); // Write + const transition = document.startViewTransition(async () => { + await update(); + // TODO: Go over new targets and ensure they all have ids + }); + transition.finished.finally(() => { + css.remove(); // Write + }); + return new Promise((resolve) => { + transition.ready.then(() => { + const generatedViewAnimations = getViewAnimations(); + const animations = []; + /** + * Create animations for each of our explicitly-defined subjects. + */ + targets.forEach((definition, target) => { + // TODO: If target is not "root", resolve elements + // and iterate over each + for (const key of definitionNames) { + if (!definition[key]) + continue; + const { keyframes, options } = definition[key]; + for (let [valueName, valueKeyframes] of Object.entries(keyframes)) { + if (!valueKeyframes) + continue; + const valueOptions = { + ...getValueTransition$1(defaultOptions, valueName), + ...getValueTransition$1(options, valueName), + }; + const type = chooseLayerType(key); + /** + * If this is an opacity animation, and keyframes are not an array, + * we need to convert them into an array and set an initial value. + */ + if (valueName === "opacity" && + !Array.isArray(valueKeyframes)) { + const initialValue = type === "new" ? 0 : 1; + valueKeyframes = [initialValue, valueKeyframes]; + } + /** + * Resolve stagger function if provided. + */ + if (typeof valueOptions.delay === "function") { + valueOptions.delay = valueOptions.delay(0, 1); + } + valueOptions.duration && (valueOptions.duration = secondsToMilliseconds(valueOptions.duration)); + valueOptions.delay && (valueOptions.delay = secondsToMilliseconds(valueOptions.delay)); + const animation = new NativeAnimation({ + ...valueOptions, + element: document.documentElement, + name: valueName, + pseudoElement: `::view-transition-${type}(${target})`, + keyframes: valueKeyframes, + }); + animations.push(animation); + } + } + }); + /** + * Handle browser generated animations + */ + for (const animation of generatedViewAnimations) { + if (animation.playState === "finished") + continue; + const { effect } = animation; + if (!effect || !(effect instanceof KeyframeEffect)) + continue; + const { pseudoElement } = effect; + if (!pseudoElement) + continue; + const name = getViewAnimationLayerInfo(pseudoElement); + if (!name) + continue; + const targetDefinition = targets.get(name.layer); + if (!targetDefinition) { + /** + * If transition name is group then update the timing of the animation + * whereas if it's old or new then we could possibly replace it using + * the above method. + */ + const transitionName = name.type === "group" ? "layout" : ""; + let animationTransition = { + ...getValueTransition$1(defaultOptions, transitionName), + }; + animationTransition.duration && (animationTransition.duration = secondsToMilliseconds(animationTransition.duration)); + animationTransition = + applyGeneratorOptions(animationTransition); + const easing = mapEasingToNativeEasing(animationTransition.ease, animationTransition.duration); + effect.updateTiming({ + delay: secondsToMilliseconds(animationTransition.delay ?? 0), + duration: animationTransition.duration, + easing, + }); + animations.push(new NativeAnimationWrapper(animation)); + } + else if (hasOpacity(targetDefinition, "enter") && + hasOpacity(targetDefinition, "exit") && + effect + .getKeyframes() + .some((keyframe) => keyframe.mixBlendMode)) { + animations.push(new NativeAnimationWrapper(animation)); + } + else { + animation.cancel(); + } + } + resolve(new GroupAnimation(animations)); + }); + }); + } + function hasOpacity(target, key) { + return target?.[key]?.keyframes.opacity; + } + + let builders = []; + let current = null; + function next() { + current = null; + const [nextBuilder] = builders; + if (nextBuilder) + start(nextBuilder); + } + function start(builder) { + removeItem(builders, builder); + current = builder; + startViewAnimation(builder).then((animation) => { + builder.notifyReady(animation); + animation.finished.finally(next); + }); + } + function processQueue() { + /** + * Iterate backwards over the builders array. We can ignore the + * "wait" animations. If we have an interrupting animation in the + * queue then we need to batch all preceeding animations into it. + * Currently this only batches the update functions but will also + * need to batch the targets. + */ + for (let i = builders.length - 1; i >= 0; i--) { + const builder = builders[i]; + const { interrupt } = builder.options; + if (interrupt === "immediate") { + const batchedUpdates = builders.slice(0, i + 1).map((b) => b.update); + const remaining = builders.slice(i + 1); + builder.update = () => { + batchedUpdates.forEach((update) => update()); + }; + // Put the current builder at the front, followed by any "wait" builders + builders = [builder, ...remaining]; + break; + } + } + if (!current || builders[0]?.options.interrupt === "immediate") { + next(); + } + } + function addToQueue(builder) { + builders.push(builder); + microtask.render(processQueue); + } + + class ViewTransitionBuilder { + constructor(update, options = {}) { + this.currentSubject = "root"; + this.targets = new Map(); + this.notifyReady = noop; + this.readyPromise = new Promise((resolve) => { + this.notifyReady = resolve; + }); + this.update = update; + this.options = { + interrupt: "wait", + ...options, + }; + addToQueue(this); + } + get(subject) { + this.currentSubject = subject; + return this; + } + layout(keyframes, options) { + this.updateTarget("layout", keyframes, options); + return this; + } + new(keyframes, options) { + this.updateTarget("new", keyframes, options); + return this; + } + old(keyframes, options) { + this.updateTarget("old", keyframes, options); + return this; + } + enter(keyframes, options) { + this.updateTarget("enter", keyframes, options); + return this; + } + exit(keyframes, options) { + this.updateTarget("exit", keyframes, options); + return this; + } + crossfade(options) { + this.updateTarget("enter", { opacity: 1 }, options); + this.updateTarget("exit", { opacity: 0 }, options); + return this; + } + updateTarget(target, keyframes, options = {}) { + const { currentSubject, targets } = this; + if (!targets.has(currentSubject)) { + targets.set(currentSubject, {}); + } + const targetData = targets.get(currentSubject); + targetData[target] = { keyframes, options }; + } + then(resolve, reject) { + return this.readyPromise.then(resolve, reject); + } + } + function animateView(update, defaultOptions = {}) { + return new ViewTransitionBuilder(update, defaultOptions); + } + + /** + * @deprecated + * + * Import as `frame` instead. + */ + const sync = frame; + /** + * @deprecated + * + * Use cancelFrame(callback) instead. + */ + const cancelSync = stepsOrder.reduce((acc, key) => { + acc[key] = (process) => cancelFrame(process); + return acc; + }, {}); + + /** + * @public + */ + const MotionConfigContext = React$1.createContext({ + transformPagePoint: (p) => p, + isStatic: false, + reducedMotion: "never", + }); + + /** + * Measurement functionality has to be within a separate component + * to leverage snapshot lifecycle. + */ + class PopChildMeasure extends React__namespace.Component { + getSnapshotBeforeUpdate(prevProps) { + const element = this.props.childRef.current; + if (element && prevProps.isPresent && !this.props.isPresent) { + const parent = element.offsetParent; + const parentWidth = isHTMLElement(parent) + ? parent.offsetWidth || 0 + : 0; + const size = this.props.sizeRef.current; + size.height = element.offsetHeight || 0; + size.width = element.offsetWidth || 0; + size.top = element.offsetTop; + size.left = element.offsetLeft; + size.right = parentWidth - size.width - size.left; + } + return null; + } + /** + * Required with getSnapshotBeforeUpdate to stop React complaining. + */ + componentDidUpdate() { } + render() { + return this.props.children; + } + } + function PopChild({ children, isPresent, anchorX, root }) { + const id = React$1.useId(); + const ref = React$1.useRef(null); + const size = React$1.useRef({ + width: 0, + height: 0, + top: 0, + left: 0, + right: 0, + }); + const { nonce } = React$1.useContext(MotionConfigContext); + /** + * We create and inject a style block so we can apply this explicit + * sizing in a non-destructive manner by just deleting the style block. + * + * We can't apply size via render as the measurement happens + * in getSnapshotBeforeUpdate (post-render), likewise if we apply the + * styles directly on the DOM node, we might be overwriting + * styles set via the style prop. + */ + React$1.useInsertionEffect(() => { + const { width, height, top, left, right } = size.current; + if (isPresent || !ref.current || !width || !height) + return; + const x = anchorX === "left" ? `left: ${left}` : `right: ${right}`; + ref.current.dataset.motionPopId = id; + const style = document.createElement("style"); + if (nonce) + style.nonce = nonce; + const parent = root ?? document.head; + parent.appendChild(style); + if (style.sheet) { + style.sheet.insertRule(` + [data-motion-pop-id="${id}"] { + position: absolute !important; + width: ${width}px !important; + height: ${height}px !important; + ${x}px !important; + top: ${top}px !important; + } + `); + } + return () => { + if (parent.contains(style)) { + parent.removeChild(style); + } + }; + }, [isPresent]); + return (jsx(PopChildMeasure, { isPresent: isPresent, childRef: ref, sizeRef: size, children: React__namespace.cloneElement(children, { ref }) })); + } + + const PresenceChild = ({ children, initial, isPresent, onExitComplete, custom, presenceAffectsLayout, mode, anchorX, root }) => { + const presenceChildren = useConstant(newChildrenMap); + const id = React$1.useId(); + let isReusedContext = true; + let context = React$1.useMemo(() => { + isReusedContext = false; + return { + id, + initial, + isPresent, + custom, + onExitComplete: (childId) => { + presenceChildren.set(childId, true); + for (const isComplete of presenceChildren.values()) { + if (!isComplete) + return; // can stop searching when any is incomplete + } + onExitComplete && onExitComplete(); + }, + register: (childId) => { + presenceChildren.set(childId, false); + return () => presenceChildren.delete(childId); + }, + }; + }, [isPresent, presenceChildren, onExitComplete]); + /** + * If the presence of a child affects the layout of the components around it, + * we want to make a new context value to ensure they get re-rendered + * so they can detect that layout change. + */ + if (presenceAffectsLayout && isReusedContext) { + context = { ...context }; + } + React$1.useMemo(() => { + presenceChildren.forEach((_, key) => presenceChildren.set(key, false)); + }, [isPresent]); + /** + * If there's no `motion` components to fire exit animations, we want to remove this + * component immediately. + */ + React__namespace.useEffect(() => { + !isPresent && + !presenceChildren.size && + onExitComplete && + onExitComplete(); + }, [isPresent]); + if (mode === "popLayout") { + children = (jsx(PopChild, { isPresent: isPresent, anchorX: anchorX, root: root, children: children })); + } + return (jsx(PresenceContext.Provider, { value: context, children: children })); + }; + function newChildrenMap() { + return new Map(); + } + + /** + * When a component is the child of `AnimatePresence`, it can use `usePresence` + * to access information about whether it's still present in the React tree. + * + * ```jsx + * import { usePresence } from "framer-motion" + * + * export const Component = () => { + * const [isPresent, safeToRemove] = usePresence() + * + * useEffect(() => { + * !isPresent && setTimeout(safeToRemove, 1000) + * }, [isPresent]) + * + * return
+ * } + * ``` + * + * If `isPresent` is `false`, it means that a component has been removed the tree, but + * `AnimatePresence` won't really remove it until `safeToRemove` has been called. + * + * @public + */ + function usePresence(subscribe = true) { + const context = React$1.useContext(PresenceContext); + if (context === null) + return [true, null]; + const { isPresent, onExitComplete, register } = context; + // It's safe to call the following hooks conditionally (after an early return) because the context will always + // either be null or non-null for the lifespan of the component. + const id = React$1.useId(); + React$1.useEffect(() => { + if (subscribe) { + return register(id); + } + }, [subscribe]); + const safeToRemove = React$1.useCallback(() => subscribe && onExitComplete && onExitComplete(id), [id, onExitComplete, subscribe]); + return !isPresent && onExitComplete ? [false, safeToRemove] : [true]; + } + /** + * Similar to `usePresence`, except `useIsPresent` simply returns whether or not the component is present. + * There is no `safeToRemove` function. + * + * ```jsx + * import { useIsPresent } from "framer-motion" + * + * export const Component = () => { + * const isPresent = useIsPresent() + * + * useEffect(() => { + * !isPresent && console.log("I've been removed!") + * }, [isPresent]) + * + * return
+ * } + * ``` + * + * @public + */ + function useIsPresent() { + return isPresent(React$1.useContext(PresenceContext)); + } + function isPresent(context) { + return context === null ? true : context.isPresent; + } + + const getChildKey = (child) => child.key || ""; + function onlyElements(children) { + const filtered = []; + // We use forEach here instead of map as map mutates the component key by preprending `.$` + React$1.Children.forEach(children, (child) => { + if (React$1.isValidElement(child)) + filtered.push(child); + }); + return filtered; + } + + /** + * `AnimatePresence` enables the animation of components that have been removed from the tree. + * + * When adding/removing more than a single child, every child **must** be given a unique `key` prop. + * + * Any `motion` components that have an `exit` property defined will animate out when removed from + * the tree. + * + * ```jsx + * import { motion, AnimatePresence } from 'framer-motion' + * + * export const Items = ({ items }) => ( + * + * {items.map(item => ( + * + * ))} + * + * ) + * ``` + * + * You can sequence exit animations throughout a tree using variants. + * + * If a child contains multiple `motion` components with `exit` props, it will only unmount the child + * once all `motion` components have finished animating out. Likewise, any components using + * `usePresence` all need to call `safeToRemove`. + * + * @public + */ + const AnimatePresence = ({ children, custom, initial = true, onExitComplete, presenceAffectsLayout = true, mode = "sync", propagate = false, anchorX = "left", root }) => { + const [isParentPresent, safeToRemove] = usePresence(propagate); + /** + * Filter any children that aren't ReactElements. We can only track components + * between renders with a props.key. + */ + const presentChildren = React$1.useMemo(() => onlyElements(children), [children]); + /** + * Track the keys of the currently rendered children. This is used to + * determine which children are exiting. + */ + const presentKeys = propagate && !isParentPresent ? [] : presentChildren.map(getChildKey); + /** + * If `initial={false}` we only want to pass this to components in the first render. + */ + const isInitialRender = React$1.useRef(true); + /** + * A ref containing the currently present children. When all exit animations + * are complete, we use this to re-render the component with the latest children + * *committed* rather than the latest children *rendered*. + */ + const pendingPresentChildren = React$1.useRef(presentChildren); + /** + * Track which exiting children have finished animating out. + */ + const exitComplete = useConstant(() => new Map()); + /** + * Save children to render as React state. To ensure this component is concurrent-safe, + * we check for exiting children via an effect. + */ + const [diffedChildren, setDiffedChildren] = React$1.useState(presentChildren); + const [renderedChildren, setRenderedChildren] = React$1.useState(presentChildren); + useIsomorphicLayoutEffect(() => { + isInitialRender.current = false; + pendingPresentChildren.current = presentChildren; + /** + * Update complete status of exiting children. + */ + for (let i = 0; i < renderedChildren.length; i++) { + const key = getChildKey(renderedChildren[i]); + if (!presentKeys.includes(key)) { + if (exitComplete.get(key) !== true) { + exitComplete.set(key, false); + } + } + else { + exitComplete.delete(key); + } + } + }, [renderedChildren, presentKeys.length, presentKeys.join("-")]); + const exitingChildren = []; + if (presentChildren !== diffedChildren) { + let nextChildren = [...presentChildren]; + /** + * Loop through all the currently rendered components and decide which + * are exiting. + */ + for (let i = 0; i < renderedChildren.length; i++) { + const child = renderedChildren[i]; + const key = getChildKey(child); + if (!presentKeys.includes(key)) { + nextChildren.splice(i, 0, child); + exitingChildren.push(child); + } + } + /** + * If we're in "wait" mode, and we have exiting children, we want to + * only render these until they've all exited. + */ + if (mode === "wait" && exitingChildren.length) { + nextChildren = exitingChildren; + } + setRenderedChildren(onlyElements(nextChildren)); + setDiffedChildren(presentChildren); + /** + * Early return to ensure once we've set state with the latest diffed + * children, we can immediately re-render. + */ + return null; + } + if (mode === "wait" && + renderedChildren.length > 1) { + console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`); + } + /** + * If we've been provided a forceRender function by the LayoutGroupContext, + * we can use it to force a re-render amongst all surrounding components once + * all components have finished animating out. + */ + const { forceRender } = React$1.useContext(LayoutGroupContext); + return (jsx(Fragment, { children: renderedChildren.map((child) => { + const key = getChildKey(child); + const isPresent = propagate && !isParentPresent + ? false + : presentChildren === renderedChildren || + presentKeys.includes(key); + const onExit = () => { + if (exitComplete.has(key)) { + exitComplete.set(key, true); + } + else { + return; + } + let isEveryExitComplete = true; + exitComplete.forEach((isExitComplete) => { + if (!isExitComplete) + isEveryExitComplete = false; + }); + if (isEveryExitComplete) { + forceRender?.(); + setRenderedChildren(pendingPresentChildren.current); + propagate && safeToRemove?.(); + onExitComplete && onExitComplete(); + } + }; + return (jsx(PresenceChild, { isPresent: isPresent, initial: !isInitialRender.current || initial + ? undefined + : false, custom: custom, presenceAffectsLayout: presenceAffectsLayout, mode: mode, root: root, onExitComplete: isPresent ? undefined : onExit, anchorX: anchorX, children: child }, key)); + }) })); + }; + + /** + * Note: Still used by components generated by old versions of Framer + * + * @deprecated + */ + const DeprecatedLayoutGroupContext = React$1.createContext(null); + + const SCALE_PRECISION = 0.0001; + const SCALE_MIN = 1 - SCALE_PRECISION; + const SCALE_MAX = 1 + SCALE_PRECISION; + const TRANSLATE_PRECISION = 0.01; + const TRANSLATE_MIN = 0 - TRANSLATE_PRECISION; + const TRANSLATE_MAX = 0 + TRANSLATE_PRECISION; + function calcLength(axis) { + return axis.max - axis.min; + } + function isNear(value, target, maxDistance) { + return Math.abs(value - target) <= maxDistance; + } + function calcAxisDelta(delta, source, target, origin = 0.5) { + delta.origin = origin; + delta.originPoint = mixNumber$1(source.min, source.max, delta.origin); + delta.scale = calcLength(target) / calcLength(source); + delta.translate = + mixNumber$1(target.min, target.max, delta.origin) - delta.originPoint; + if ((delta.scale >= SCALE_MIN && delta.scale <= SCALE_MAX) || + isNaN(delta.scale)) { + delta.scale = 1.0; + } + if ((delta.translate >= TRANSLATE_MIN && + delta.translate <= TRANSLATE_MAX) || + isNaN(delta.translate)) { + delta.translate = 0.0; + } + } + function calcBoxDelta(delta, source, target, origin) { + calcAxisDelta(delta.x, source.x, target.x, origin ? origin.originX : undefined); + calcAxisDelta(delta.y, source.y, target.y, origin ? origin.originY : undefined); + } + function calcRelativeAxis(target, relative, parent) { + target.min = parent.min + relative.min; + target.max = target.min + calcLength(relative); + } + function calcRelativeBox(target, relative, parent) { + calcRelativeAxis(target.x, relative.x, parent.x); + calcRelativeAxis(target.y, relative.y, parent.y); + } + function calcRelativeAxisPosition(target, layout, parent) { + target.min = layout.min - parent.min; + target.max = target.min + calcLength(layout); + } + function calcRelativePosition(target, layout, parent) { + calcRelativeAxisPosition(target.x, layout.x, parent.x); + calcRelativeAxisPosition(target.y, layout.y, parent.y); + } + + const notify = (node) => !node.isLayoutDirty && node.willUpdate(false); + function nodeGroup() { + const nodes = new Set(); + const subscriptions = new WeakMap(); + const dirtyAll = () => nodes.forEach(notify); + return { + add: (node) => { + nodes.add(node); + subscriptions.set(node, node.addEventListener("willUpdate", dirtyAll)); + }, + remove: (node) => { + nodes.delete(node); + const unsubscribe = subscriptions.get(node); + if (unsubscribe) { + unsubscribe(); + subscriptions.delete(node); + } + dirtyAll(); + }, + dirty: dirtyAll, + }; + } + + const isNotNull = (value) => value !== null; + function getFinalKeyframe(keyframes, { repeat, repeatType = "loop" }, finalKeyframe) { + const resolvedKeyframes = keyframes.filter(isNotNull); + const index = repeat && repeatType !== "loop" && repeat % 2 === 1 + ? 0 + : resolvedKeyframes.length - 1; + return !index || finalKeyframe === undefined + ? resolvedKeyframes[index] + : finalKeyframe; + } + + const underDampedSpring = { + type: "spring", + stiffness: 500, + damping: 25, + restSpeed: 10, + }; + const criticallyDampedSpring = (target) => ({ + type: "spring", + stiffness: 550, + damping: target === 0 ? 2 * Math.sqrt(550) : 30, + restSpeed: 10, + }); + const keyframesTransition = { + type: "keyframes", + duration: 0.8, + }; + /** + * Default easing curve is a slightly shallower version of + * the default browser easing curve. + */ + const ease = { + type: "keyframes", + ease: [0.25, 0.1, 0.35, 1], + duration: 0.3, + }; + const getDefaultTransition = (valueKey, { keyframes }) => { + if (keyframes.length > 2) { + return keyframesTransition; + } + else if (transformProps.has(valueKey)) { + return valueKey.startsWith("scale") + ? criticallyDampedSpring(keyframes[1]) + : underDampedSpring; + } + return ease; + }; + + /** + * Decide whether a transition is defined on a given Transition. + * This filters out orchestration options and returns true + * if any options are left. + */ + function isTransitionDefined({ when, delay: _delay, delayChildren, staggerChildren, staggerDirection, repeat, repeatType, repeatDelay, from, elapsed, ...transition }) { + return !!Object.keys(transition).length; + } + + const animateMotionValue = (name, value, target, transition = {}, element, isHandoff) => (onComplete) => { + const valueTransition = getValueTransition$1(transition, name) || {}; + /** + * Most transition values are currently completely overwritten by value-specific + * transitions. In the future it'd be nicer to blend these transitions. But for now + * delay actually does inherit from the root transition if not value-specific. + */ + const delay = valueTransition.delay || transition.delay || 0; + /** + * Elapsed isn't a public transition option but can be passed through from + * optimized appear effects in milliseconds. + */ + let { elapsed = 0 } = transition; + elapsed = elapsed - secondsToMilliseconds(delay); + const options = { + keyframes: Array.isArray(target) ? target : [null, target], + ease: "easeOut", + velocity: value.getVelocity(), + ...valueTransition, + delay: -elapsed, + onUpdate: (v) => { + value.set(v); + valueTransition.onUpdate && valueTransition.onUpdate(v); + }, + onComplete: () => { + onComplete(); + valueTransition.onComplete && valueTransition.onComplete(); + }, + name, + motionValue: value, + element: isHandoff ? undefined : element, + }; + /** + * If there's no transition defined for this value, we can generate + * unique transition settings for this value. + */ + if (!isTransitionDefined(valueTransition)) { + Object.assign(options, getDefaultTransition(name, options)); + } + /** + * Both WAAPI and our internal animation functions use durations + * as defined by milliseconds, while our external API defines them + * as seconds. + */ + options.duration && (options.duration = secondsToMilliseconds(options.duration)); + options.repeatDelay && (options.repeatDelay = secondsToMilliseconds(options.repeatDelay)); + /** + * Support deprecated way to set initial value. Prefer keyframe syntax. + */ + if (options.from !== undefined) { + options.keyframes[0] = options.from; + } + let shouldSkip = false; + if (options.type === false || + (options.duration === 0 && !options.repeatDelay)) { + makeAnimationInstant(options); + if (options.delay === 0) { + shouldSkip = true; + } + } + if (MotionGlobalConfig.instantAnimations || + MotionGlobalConfig.skipAnimations) { + shouldSkip = true; + makeAnimationInstant(options); + options.delay = 0; + } + /** + * If the transition type or easing has been explicitly set by the user + * then we don't want to allow flattening the animation. + */ + options.allowFlatten = !valueTransition.type && !valueTransition.ease; + /** + * If we can or must skip creating the animation, and apply only + * the final keyframe, do so. We also check once keyframes are resolved but + * this early check prevents the need to create an animation at all. + */ + if (shouldSkip && !isHandoff && value.get() !== undefined) { + const finalKeyframe = getFinalKeyframe(options.keyframes, valueTransition); + if (finalKeyframe !== undefined) { + frame.update(() => { + options.onUpdate(finalKeyframe); + options.onComplete(); + }); + return; + } + } + return valueTransition.isSync + ? new JSAnimation(options) + : new AsyncMotionValueAnimation(options); + }; + + function animateSingleValue(value, keyframes, options) { + const motionValue$1 = isMotionValue(value) ? value : motionValue(value); + motionValue$1.start(animateMotionValue("", motionValue$1, keyframes, options)); + return motionValue$1.animation; + } + + /** + * Convert camelCase to dash-case properties. + */ + const camelToDash = (str) => str.replace(/([a-z])([A-Z])/gu, "$1-$2").toLowerCase(); + + const optimizedAppearDataId = "framerAppearId"; + const optimizedAppearDataAttribute = "data-" + camelToDash(optimizedAppearDataId); + + function getOptimisedAppearId(visualElement) { + return visualElement.props[optimizedAppearDataAttribute]; + } + + const compareByDepth = (a, b) => a.depth - b.depth; + + class FlatTree { + constructor() { + this.children = []; + this.isDirty = false; + } + add(child) { + addUniqueItem(this.children, child); + this.isDirty = true; + } + remove(child) { + removeItem(this.children, child); + this.isDirty = true; + } + forEach(callback) { + this.isDirty && this.children.sort(compareByDepth); + this.isDirty = false; + this.children.forEach(callback); + } + } + + /** + * Timeout defined in ms + */ + function delay(callback, timeout) { + const start = time.now(); + const checkElapsed = ({ timestamp }) => { + const elapsed = timestamp - start; + if (elapsed >= timeout) { + cancelFrame(checkElapsed); + callback(elapsed - timeout); + } + }; + frame.setup(checkElapsed, true); + return () => cancelFrame(checkElapsed); + } + + /** + * If the provided value is a MotionValue, this returns the actual value, otherwise just the value itself + * + * TODO: Remove and move to library + */ + function resolveMotionValue(value) { + return isMotionValue(value) ? value.get() : value; + } + + const borders = ["TopLeft", "TopRight", "BottomLeft", "BottomRight"]; + const numBorders = borders.length; + const asNumber = (value) => typeof value === "string" ? parseFloat(value) : value; + const isPx = (value) => typeof value === "number" || px.test(value); + function mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnlyMember) { + if (shouldCrossfadeOpacity) { + target.opacity = mixNumber$1(0, lead.opacity ?? 1, easeCrossfadeIn(progress)); + target.opacityExit = mixNumber$1(follow.opacity ?? 1, 0, easeCrossfadeOut(progress)); + } + else if (isOnlyMember) { + target.opacity = mixNumber$1(follow.opacity ?? 1, lead.opacity ?? 1, progress); + } + /** + * Mix border radius + */ + for (let i = 0; i < numBorders; i++) { + const borderLabel = `border${borders[i]}Radius`; + let followRadius = getRadius(follow, borderLabel); + let leadRadius = getRadius(lead, borderLabel); + if (followRadius === undefined && leadRadius === undefined) + continue; + followRadius || (followRadius = 0); + leadRadius || (leadRadius = 0); + const canMix = followRadius === 0 || + leadRadius === 0 || + isPx(followRadius) === isPx(leadRadius); + if (canMix) { + target[borderLabel] = Math.max(mixNumber$1(asNumber(followRadius), asNumber(leadRadius), progress), 0); + if (percent.test(leadRadius) || percent.test(followRadius)) { + target[borderLabel] += "%"; + } + } + else { + target[borderLabel] = leadRadius; + } + } + /** + * Mix rotation + */ + if (follow.rotate || lead.rotate) { + target.rotate = mixNumber$1(follow.rotate || 0, lead.rotate || 0, progress); + } + } + function getRadius(values, radiusName) { + return values[radiusName] !== undefined + ? values[radiusName] + : values.borderRadius; + } + // /** + // * We only want to mix the background color if there's a follow element + // * that we're not crossfading opacity between. For instance with switch + // * AnimateSharedLayout animations, this helps the illusion of a continuous + // * element being animated but also cuts down on the number of paints triggered + // * for elements where opacity is doing that work for us. + // */ + // if ( + // !hasFollowElement && + // latestLeadValues.backgroundColor && + // latestFollowValues.backgroundColor + // ) { + // /** + // * This isn't ideal performance-wise as mixColor is creating a new function every frame. + // * We could probably create a mixer that runs at the start of the animation but + // * the idea behind the crossfader is that it runs dynamically between two potentially + // * changing targets (ie opacity or borderRadius may be animating independently via variants) + // */ + // leadState.backgroundColor = followState.backgroundColor = mixColor( + // latestFollowValues.backgroundColor as string, + // latestLeadValues.backgroundColor as string + // )(p) + // } + const easeCrossfadeIn = /*@__PURE__*/ compress(0, 0.5, circOut); + const easeCrossfadeOut = /*@__PURE__*/ compress(0.5, 0.95, noop); + function compress(min, max, easing) { + return (p) => { + // Could replace ifs with clamp + if (p < min) + return 0; + if (p > max) + return 1; + return easing(progress(min, max, p)); + }; + } + + /** + * Reset an axis to the provided origin box. + * + * This is a mutative operation. + */ + function copyAxisInto(axis, originAxis) { + axis.min = originAxis.min; + axis.max = originAxis.max; + } + /** + * Reset a box to the provided origin box. + * + * This is a mutative operation. + */ + function copyBoxInto(box, originBox) { + copyAxisInto(box.x, originBox.x); + copyAxisInto(box.y, originBox.y); + } + /** + * Reset a delta to the provided origin box. + * + * This is a mutative operation. + */ + function copyAxisDeltaInto(delta, originDelta) { + delta.translate = originDelta.translate; + delta.scale = originDelta.scale; + delta.originPoint = originDelta.originPoint; + delta.origin = originDelta.origin; + } + + function isIdentityScale(scale) { + return scale === undefined || scale === 1; + } + function hasScale({ scale, scaleX, scaleY }) { + return (!isIdentityScale(scale) || + !isIdentityScale(scaleX) || + !isIdentityScale(scaleY)); + } + function hasTransform(values) { + return (hasScale(values) || + has2DTranslate(values) || + values.z || + values.rotate || + values.rotateX || + values.rotateY || + values.skewX || + values.skewY); + } + function has2DTranslate(values) { + return is2DTranslate(values.x) || is2DTranslate(values.y); + } + function is2DTranslate(value) { + return value && value !== "0%"; + } + + /** + * Scales a point based on a factor and an originPoint + */ + function scalePoint(point, scale, originPoint) { + const distanceFromOrigin = point - originPoint; + const scaled = scale * distanceFromOrigin; + return originPoint + scaled; + } + /** + * Applies a translate/scale delta to a point + */ + function applyPointDelta(point, translate, scale, originPoint, boxScale) { + if (boxScale !== undefined) { + point = scalePoint(point, boxScale, originPoint); + } + return scalePoint(point, scale, originPoint) + translate; + } + /** + * Applies a translate/scale delta to an axis + */ + function applyAxisDelta(axis, translate = 0, scale = 1, originPoint, boxScale) { + axis.min = applyPointDelta(axis.min, translate, scale, originPoint, boxScale); + axis.max = applyPointDelta(axis.max, translate, scale, originPoint, boxScale); + } + /** + * Applies a translate/scale delta to a box + */ + function applyBoxDelta(box, { x, y }) { + applyAxisDelta(box.x, x.translate, x.scale, x.originPoint); + applyAxisDelta(box.y, y.translate, y.scale, y.originPoint); + } + const TREE_SCALE_SNAP_MIN = 0.999999999999; + const TREE_SCALE_SNAP_MAX = 1.0000000000001; + /** + * Apply a tree of deltas to a box. We do this to calculate the effect of all the transforms + * in a tree upon our box before then calculating how to project it into our desired viewport-relative box + * + * This is the final nested loop within updateLayoutDelta for future refactoring + */ + function applyTreeDeltas(box, treeScale, treePath, isSharedTransition = false) { + const treeLength = treePath.length; + if (!treeLength) + return; + // Reset the treeScale + treeScale.x = treeScale.y = 1; + let node; + let delta; + for (let i = 0; i < treeLength; i++) { + node = treePath[i]; + delta = node.projectionDelta; + /** + * TODO: Prefer to remove this, but currently we have motion components with + * display: contents in Framer. + */ + const { visualElement } = node.options; + if (visualElement && + visualElement.props.style && + visualElement.props.style.display === "contents") { + continue; + } + if (isSharedTransition && + node.options.layoutScroll && + node.scroll && + node !== node.root) { + transformBox(box, { + x: -node.scroll.offset.x, + y: -node.scroll.offset.y, + }); + } + if (delta) { + // Incoporate each ancestor's scale into a culmulative treeScale for this component + treeScale.x *= delta.x.scale; + treeScale.y *= delta.y.scale; + // Apply each ancestor's calculated delta into this component's recorded layout box + applyBoxDelta(box, delta); + } + if (isSharedTransition && hasTransform(node.latestValues)) { + transformBox(box, node.latestValues); + } + } + /** + * Snap tree scale back to 1 if it's within a non-perceivable threshold. + * This will help reduce useless scales getting rendered. + */ + if (treeScale.x < TREE_SCALE_SNAP_MAX && + treeScale.x > TREE_SCALE_SNAP_MIN) { + treeScale.x = 1.0; + } + if (treeScale.y < TREE_SCALE_SNAP_MAX && + treeScale.y > TREE_SCALE_SNAP_MIN) { + treeScale.y = 1.0; + } + } + function translateAxis(axis, distance) { + axis.min = axis.min + distance; + axis.max = axis.max + distance; + } + /** + * Apply a transform to an axis from the latest resolved motion values. + * This function basically acts as a bridge between a flat motion value map + * and applyAxisDelta + */ + function transformAxis(axis, axisTranslate, axisScale, boxScale, axisOrigin = 0.5) { + const originPoint = mixNumber$1(axis.min, axis.max, axisOrigin); + // Apply the axis delta to the final axis + applyAxisDelta(axis, axisTranslate, axisScale, originPoint, boxScale); + } + /** + * Apply a transform to a box from the latest resolved motion values. + */ + function transformBox(box, transform) { + transformAxis(box.x, transform.x, transform.scaleX, transform.scale, transform.originX); + transformAxis(box.y, transform.y, transform.scaleY, transform.scale, transform.originY); + } + + /** + * Remove a delta from a point. This is essentially the steps of applyPointDelta in reverse + */ + function removePointDelta(point, translate, scale, originPoint, boxScale) { + point -= translate; + point = scalePoint(point, 1 / scale, originPoint); + if (boxScale !== undefined) { + point = scalePoint(point, 1 / boxScale, originPoint); + } + return point; + } + /** + * Remove a delta from an axis. This is essentially the steps of applyAxisDelta in reverse + */ + function removeAxisDelta(axis, translate = 0, scale = 1, origin = 0.5, boxScale, originAxis = axis, sourceAxis = axis) { + if (percent.test(translate)) { + translate = parseFloat(translate); + const relativeProgress = mixNumber$1(sourceAxis.min, sourceAxis.max, translate / 100); + translate = relativeProgress - sourceAxis.min; + } + if (typeof translate !== "number") + return; + let originPoint = mixNumber$1(originAxis.min, originAxis.max, origin); + if (axis === originAxis) + originPoint -= translate; + axis.min = removePointDelta(axis.min, translate, scale, originPoint, boxScale); + axis.max = removePointDelta(axis.max, translate, scale, originPoint, boxScale); + } + /** + * Remove a transforms from an axis. This is essentially the steps of applyAxisTransforms in reverse + * and acts as a bridge between motion values and removeAxisDelta + */ + function removeAxisTransforms(axis, transforms, [key, scaleKey, originKey], origin, sourceAxis) { + removeAxisDelta(axis, transforms[key], transforms[scaleKey], transforms[originKey], transforms.scale, origin, sourceAxis); + } + /** + * The names of the motion values we want to apply as translation, scale and origin. + */ + const xKeys = ["x", "scaleX", "originX"]; + const yKeys = ["y", "scaleY", "originY"]; + /** + * Remove a transforms from an box. This is essentially the steps of applyAxisBox in reverse + * and acts as a bridge between motion values and removeAxisDelta + */ + function removeBoxTransforms(box, transforms, originBox, sourceBox) { + removeAxisTransforms(box.x, transforms, xKeys, originBox ? originBox.x : undefined, sourceBox ? sourceBox.x : undefined); + removeAxisTransforms(box.y, transforms, yKeys, originBox ? originBox.y : undefined, sourceBox ? sourceBox.y : undefined); + } + + const createAxisDelta = () => ({ + translate: 0, + scale: 1, + origin: 0, + originPoint: 0, + }); + const createDelta = () => ({ + x: createAxisDelta(), + y: createAxisDelta(), + }); + const createAxis = () => ({ min: 0, max: 0 }); + const createBox = () => ({ + x: createAxis(), + y: createAxis(), + }); + + function isAxisDeltaZero(delta) { + return delta.translate === 0 && delta.scale === 1; + } + function isDeltaZero(delta) { + return isAxisDeltaZero(delta.x) && isAxisDeltaZero(delta.y); + } + function axisEquals(a, b) { + return a.min === b.min && a.max === b.max; + } + function boxEquals(a, b) { + return axisEquals(a.x, b.x) && axisEquals(a.y, b.y); + } + function axisEqualsRounded(a, b) { + return (Math.round(a.min) === Math.round(b.min) && + Math.round(a.max) === Math.round(b.max)); + } + function boxEqualsRounded(a, b) { + return axisEqualsRounded(a.x, b.x) && axisEqualsRounded(a.y, b.y); + } + function aspectRatio(box) { + return calcLength(box.x) / calcLength(box.y); + } + function axisDeltaEquals(a, b) { + return (a.translate === b.translate && + a.scale === b.scale && + a.originPoint === b.originPoint); + } + + class NodeStack { + constructor() { + this.members = []; + } + add(node) { + addUniqueItem(this.members, node); + node.scheduleRender(); + } + remove(node) { + removeItem(this.members, node); + if (node === this.prevLead) { + this.prevLead = undefined; + } + if (node === this.lead) { + const prevLead = this.members[this.members.length - 1]; + if (prevLead) { + this.promote(prevLead); + } + } + } + relegate(node) { + const indexOfNode = this.members.findIndex((member) => node === member); + if (indexOfNode === 0) + return false; + /** + * Find the next projection node that is present + */ + let prevLead; + for (let i = indexOfNode; i >= 0; i--) { + const member = this.members[i]; + if (member.isPresent !== false) { + prevLead = member; + break; + } + } + if (prevLead) { + this.promote(prevLead); + return true; + } + else { + return false; + } + } + promote(node, preserveFollowOpacity) { + const prevLead = this.lead; + if (node === prevLead) + return; + this.prevLead = prevLead; + this.lead = node; + node.show(); + if (prevLead) { + prevLead.instance && prevLead.scheduleRender(); + node.scheduleRender(); + node.resumeFrom = prevLead; + if (preserveFollowOpacity) { + node.resumeFrom.preserveOpacity = true; + } + if (prevLead.snapshot) { + node.snapshot = prevLead.snapshot; + node.snapshot.latestValues = + prevLead.animationValues || prevLead.latestValues; + } + if (node.root && node.root.isUpdating) { + node.isLayoutDirty = true; + } + const { crossfade } = node.options; + if (crossfade === false) { + prevLead.hide(); + } + /** + * TODO: + * - Test border radius when previous node was deleted + * - boxShadow mixing + * - Shared between element A in scrolled container and element B (scroll stays the same or changes) + * - Shared between element A in transformed container and element B (transform stays the same or changes) + * - Shared between element A in scrolled page and element B (scroll stays the same or changes) + * --- + * - Crossfade opacity of root nodes + * - layoutId changes after animation + * - layoutId changes mid animation + */ + } + } + exitAnimationComplete() { + this.members.forEach((node) => { + const { options, resumingFrom } = node; + options.onExitComplete && options.onExitComplete(); + if (resumingFrom) { + resumingFrom.options.onExitComplete && + resumingFrom.options.onExitComplete(); + } + }); + } + scheduleRender() { + this.members.forEach((node) => { + node.instance && node.scheduleRender(false); + }); + } + /** + * Clear any leads that have been removed this render to prevent them from being + * used in future animations and to prevent memory leaks + */ + removeLeadSnapshot() { + if (this.lead && this.lead.snapshot) { + this.lead.snapshot = undefined; + } + } + } + + const scaleCorrectors = {}; + function addScaleCorrector(correctors) { + for (const key in correctors) { + scaleCorrectors[key] = correctors[key]; + if (isCSSVariableName(key)) { + scaleCorrectors[key].isCSSVariable = true; + } + } + } + + function buildProjectionTransform(delta, treeScale, latestTransform) { + let transform = ""; + /** + * The translations we use to calculate are always relative to the viewport coordinate space. + * But when we apply scales, we also scale the coordinate space of an element and its children. + * For instance if we have a treeScale (the culmination of all parent scales) of 0.5 and we need + * to move an element 100 pixels, we actually need to move it 200 in within that scaled space. + */ + const xTranslate = delta.x.translate / treeScale.x; + const yTranslate = delta.y.translate / treeScale.y; + const zTranslate = latestTransform?.z || 0; + if (xTranslate || yTranslate || zTranslate) { + transform = `translate3d(${xTranslate}px, ${yTranslate}px, ${zTranslate}px) `; + } + /** + * Apply scale correction for the tree transform. + * This will apply scale to the screen-orientated axes. + */ + if (treeScale.x !== 1 || treeScale.y !== 1) { + transform += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `; + } + if (latestTransform) { + const { transformPerspective, rotate, rotateX, rotateY, skewX, skewY } = latestTransform; + if (transformPerspective) + transform = `perspective(${transformPerspective}px) ${transform}`; + if (rotate) + transform += `rotate(${rotate}deg) `; + if (rotateX) + transform += `rotateX(${rotateX}deg) `; + if (rotateY) + transform += `rotateY(${rotateY}deg) `; + if (skewX) + transform += `skewX(${skewX}deg) `; + if (skewY) + transform += `skewY(${skewY}deg) `; + } + /** + * Apply scale to match the size of the element to the size we want it. + * This will apply scale to the element-orientated axes. + */ + const elementScaleX = delta.x.scale * treeScale.x; + const elementScaleY = delta.y.scale * treeScale.y; + if (elementScaleX !== 1 || elementScaleY !== 1) { + transform += `scale(${elementScaleX}, ${elementScaleY})`; + } + return transform || "none"; + } + + function eachAxis(callback) { + return [callback("x"), callback("y")]; + } + + /** + * This should only ever be modified on the client otherwise it'll + * persist through server requests. If we need instanced states we + * could lazy-init via root. + */ + const globalProjectionState = { + /** + * Global flag as to whether the tree has animated since the last time + * we resized the window + */ + hasAnimatedSinceResize: true, + /** + * We set this to true once, on the first update. Any nodes added to the tree beyond that + * update will be given a `data-projection-id` attribute. + */ + hasEverUpdated: false, + }; + + const metrics = { + nodes: 0, + calculatedTargetDeltas: 0, + calculatedProjections: 0, + }; + const transformAxes = ["", "X", "Y", "Z"]; + /** + * We use 1000 as the animation target as 0-1000 maps better to pixels than 0-1 + * which has a noticeable difference in spring animations + */ + const animationTarget = 1000; + let id$2 = 0; + function resetDistortingTransform(key, visualElement, values, sharedAnimationValues) { + const { latestValues } = visualElement; + // Record the distorting transform and then temporarily set it to 0 + if (latestValues[key]) { + values[key] = latestValues[key]; + visualElement.setStaticValue(key, 0); + if (sharedAnimationValues) { + sharedAnimationValues[key] = 0; + } + } + } + function cancelTreeOptimisedTransformAnimations(projectionNode) { + projectionNode.hasCheckedOptimisedAppear = true; + if (projectionNode.root === projectionNode) + return; + const { visualElement } = projectionNode.options; + if (!visualElement) + return; + const appearId = getOptimisedAppearId(visualElement); + if (window.MotionHasOptimisedAnimation(appearId, "transform")) { + const { layout, layoutId } = projectionNode.options; + window.MotionCancelOptimisedAnimation(appearId, "transform", frame, !(layout || layoutId)); + } + const { parent } = projectionNode; + if (parent && !parent.hasCheckedOptimisedAppear) { + cancelTreeOptimisedTransformAnimations(parent); + } + } + function createProjectionNode$1({ attachResizeListener, defaultParent, measureScroll, checkIsScrollRoot, resetTransform, }) { + return class ProjectionNode { + constructor(latestValues = {}, parent = defaultParent?.()) { + /** + * A unique ID generated for every projection node. + */ + this.id = id$2++; + /** + * An id that represents a unique session instigated by startUpdate. + */ + this.animationId = 0; + this.animationCommitId = 0; + /** + * A Set containing all this component's children. This is used to iterate + * through the children. + * + * TODO: This could be faster to iterate as a flat array stored on the root node. + */ + this.children = new Set(); + /** + * Options for the node. We use this to configure what kind of layout animations + * we should perform (if any). + */ + this.options = {}; + /** + * We use this to detect when its safe to shut down part of a projection tree. + * We have to keep projecting children for scale correction and relative projection + * until all their parents stop performing layout animations. + */ + this.isTreeAnimating = false; + this.isAnimationBlocked = false; + /** + * Flag to true if we think this layout has been changed. We can't always know this, + * currently we set it to true every time a component renders, or if it has a layoutDependency + * if that has changed between renders. Additionally, components can be grouped by LayoutGroup + * and if one node is dirtied, they all are. + */ + this.isLayoutDirty = false; + /** + * Flag to true if we think the projection calculations for this node needs + * recalculating as a result of an updated transform or layout animation. + */ + this.isProjectionDirty = false; + /** + * Flag to true if the layout *or* transform has changed. This then gets propagated + * throughout the projection tree, forcing any element below to recalculate on the next frame. + */ + this.isSharedProjectionDirty = false; + /** + * Flag transform dirty. This gets propagated throughout the whole tree but is only + * respected by shared nodes. + */ + this.isTransformDirty = false; + /** + * Block layout updates for instant layout transitions throughout the tree. + */ + this.updateManuallyBlocked = false; + this.updateBlockedByResize = false; + /** + * Set to true between the start of the first `willUpdate` call and the end of the `didUpdate` + * call. + */ + this.isUpdating = false; + /** + * If this is an SVG element we currently disable projection transforms + */ + this.isSVG = false; + /** + * Flag to true (during promotion) if a node doing an instant layout transition needs to reset + * its projection styles. + */ + this.needsReset = false; + /** + * Flags whether this node should have its transform reset prior to measuring. + */ + this.shouldResetTransform = false; + /** + * Store whether this node has been checked for optimised appear animations. As + * effects fire bottom-up, and we want to look up the tree for appear animations, + * this makes sure we only check each path once, stopping at nodes that + * have already been checked. + */ + this.hasCheckedOptimisedAppear = false; + /** + * An object representing the calculated contextual/accumulated/tree scale. + * This will be used to scale calculcated projection transforms, as these are + * calculated in screen-space but need to be scaled for elements to layoutly + * make it to their calculated destinations. + * + * TODO: Lazy-init + */ + this.treeScale = { x: 1, y: 1 }; + /** + * + */ + this.eventHandlers = new Map(); + this.hasTreeAnimated = false; + // Note: Currently only running on root node + this.updateScheduled = false; + this.scheduleUpdate = () => this.update(); + this.projectionUpdateScheduled = false; + this.checkUpdateFailed = () => { + if (this.isUpdating) { + this.isUpdating = false; + this.clearAllSnapshots(); + } + }; + /** + * This is a multi-step process as shared nodes might be of different depths. Nodes + * are sorted by depth order, so we need to resolve the entire tree before moving to + * the next step. + */ + this.updateProjection = () => { + this.projectionUpdateScheduled = false; + /** + * Reset debug counts. Manually resetting rather than creating a new + * object each frame. + */ + if (statsBuffer.value) { + metrics.nodes = + metrics.calculatedTargetDeltas = + metrics.calculatedProjections = + 0; + } + this.nodes.forEach(propagateDirtyNodes); + this.nodes.forEach(resolveTargetDelta); + this.nodes.forEach(calcProjection); + this.nodes.forEach(cleanDirtyNodes); + if (statsBuffer.addProjectionMetrics) { + statsBuffer.addProjectionMetrics(metrics); + } + }; + /** + * Frame calculations + */ + this.resolvedRelativeTargetAt = 0.0; + this.hasProjected = false; + this.isVisible = true; + this.animationProgress = 0; + /** + * Shared layout + */ + // TODO Only running on root node + this.sharedNodes = new Map(); + this.latestValues = latestValues; + this.root = parent ? parent.root || parent : this; + this.path = parent ? [...parent.path, parent] : []; + this.parent = parent; + this.depth = parent ? parent.depth + 1 : 0; + for (let i = 0; i < this.path.length; i++) { + this.path[i].shouldResetTransform = true; + } + if (this.root === this) + this.nodes = new FlatTree(); + } + addEventListener(name, handler) { + if (!this.eventHandlers.has(name)) { + this.eventHandlers.set(name, new SubscriptionManager()); + } + return this.eventHandlers.get(name).add(handler); + } + notifyListeners(name, ...args) { + const subscriptionManager = this.eventHandlers.get(name); + subscriptionManager && subscriptionManager.notify(...args); + } + hasListeners(name) { + return this.eventHandlers.has(name); + } + /** + * Lifecycles + */ + mount(instance) { + if (this.instance) + return; + this.isSVG = isSVGElement(instance) && !isSVGSVGElement(instance); + this.instance = instance; + const { layoutId, layout, visualElement } = this.options; + if (visualElement && !visualElement.current) { + visualElement.mount(instance); + } + this.root.nodes.add(this); + this.parent && this.parent.children.add(this); + if (this.root.hasTreeAnimated && (layout || layoutId)) { + this.isLayoutDirty = true; + } + if (attachResizeListener) { + let cancelDelay; + let innerWidth = 0; + const resizeUnblockUpdate = () => (this.root.updateBlockedByResize = false); + // Set initial innerWidth in a frame.read callback to batch the read + frame.read(() => { + innerWidth = window.innerWidth; + }); + attachResizeListener(instance, () => { + const newInnerWidth = window.innerWidth; + if (newInnerWidth === innerWidth) + return; + innerWidth = newInnerWidth; + this.root.updateBlockedByResize = true; + cancelDelay && cancelDelay(); + cancelDelay = delay(resizeUnblockUpdate, 250); + if (globalProjectionState.hasAnimatedSinceResize) { + globalProjectionState.hasAnimatedSinceResize = false; + this.nodes.forEach(finishAnimation); + } + }); + } + if (layoutId) { + this.root.registerSharedNode(layoutId, this); + } + // Only register the handler if it requires layout animation + if (this.options.animate !== false && + visualElement && + (layoutId || layout)) { + this.addEventListener("didUpdate", ({ delta, hasLayoutChanged, hasRelativeLayoutChanged, layout: newLayout, }) => { + if (this.isTreeAnimationBlocked()) { + this.target = undefined; + this.relativeTarget = undefined; + return; + } + // TODO: Check here if an animation exists + const layoutTransition = this.options.transition || + visualElement.getDefaultTransition() || + defaultLayoutTransition; + const { onLayoutAnimationStart, onLayoutAnimationComplete, } = visualElement.getProps(); + /** + * The target layout of the element might stay the same, + * but its position relative to its parent has changed. + */ + const hasTargetChanged = !this.targetLayout || + !boxEqualsRounded(this.targetLayout, newLayout); + /* + * Note: Disabled to fix relative animations always triggering new + * layout animations. If this causes further issues, we can try + * a different approach to detecting relative target changes. + */ + // || hasRelativeLayoutChanged + /** + * If the layout hasn't seemed to have changed, it might be that the + * element is visually in the same place in the document but its position + * relative to its parent has indeed changed. So here we check for that. + */ + const hasOnlyRelativeTargetChanged = !hasLayoutChanged && hasRelativeLayoutChanged; + if (this.options.layoutRoot || + this.resumeFrom || + hasOnlyRelativeTargetChanged || + (hasLayoutChanged && + (hasTargetChanged || !this.currentAnimation))) { + if (this.resumeFrom) { + this.resumingFrom = this.resumeFrom; + this.resumingFrom.resumingFrom = undefined; + } + const animationOptions = { + ...getValueTransition$1(layoutTransition, "layout"), + onPlay: onLayoutAnimationStart, + onComplete: onLayoutAnimationComplete, + }; + if (visualElement.shouldReduceMotion || + this.options.layoutRoot) { + animationOptions.delay = 0; + animationOptions.type = false; + } + this.startAnimation(animationOptions); + /** + * Set animation origin after starting animation to avoid layout jump + * caused by stopping previous layout animation + */ + this.setAnimationOrigin(delta, hasOnlyRelativeTargetChanged); + } + else { + /** + * If the layout hasn't changed and we have an animation that hasn't started yet, + * finish it immediately. Otherwise it will be animating from a location + * that was probably never commited to screen and look like a jumpy box. + */ + if (!hasLayoutChanged) { + finishAnimation(this); + } + if (this.isLead() && this.options.onExitComplete) { + this.options.onExitComplete(); + } + } + this.targetLayout = newLayout; + }); + } + } + unmount() { + this.options.layoutId && this.willUpdate(); + this.root.nodes.remove(this); + const stack = this.getStack(); + stack && stack.remove(this); + this.parent && this.parent.children.delete(this); + this.instance = undefined; + this.eventHandlers.clear(); + cancelFrame(this.updateProjection); + } + // only on the root + blockUpdate() { + this.updateManuallyBlocked = true; + } + unblockUpdate() { + this.updateManuallyBlocked = false; + } + isUpdateBlocked() { + return this.updateManuallyBlocked || this.updateBlockedByResize; + } + isTreeAnimationBlocked() { + return (this.isAnimationBlocked || + (this.parent && this.parent.isTreeAnimationBlocked()) || + false); + } + // Note: currently only running on root node + startUpdate() { + if (this.isUpdateBlocked()) + return; + this.isUpdating = true; + this.nodes && this.nodes.forEach(resetSkewAndRotation); + this.animationId++; + } + getTransformTemplate() { + const { visualElement } = this.options; + return visualElement && visualElement.getProps().transformTemplate; + } + willUpdate(shouldNotifyListeners = true) { + this.root.hasTreeAnimated = true; + if (this.root.isUpdateBlocked()) { + this.options.onExitComplete && this.options.onExitComplete(); + return; + } + /** + * If we're running optimised appear animations then these must be + * cancelled before measuring the DOM. This is so we can measure + * the true layout of the element rather than the WAAPI animation + * which will be unaffected by the resetSkewAndRotate step. + * + * Note: This is a DOM write. Worst case scenario is this is sandwiched + * between other snapshot reads which will cause unnecessary style recalculations. + * This has to happen here though, as we don't yet know which nodes will need + * snapshots in startUpdate(), but we only want to cancel optimised animations + * if a layout animation measurement is actually going to be affected by them. + */ + if (window.MotionCancelOptimisedAnimation && + !this.hasCheckedOptimisedAppear) { + cancelTreeOptimisedTransformAnimations(this); + } + !this.root.isUpdating && this.root.startUpdate(); + if (this.isLayoutDirty) + return; + this.isLayoutDirty = true; + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + node.shouldResetTransform = true; + node.updateScroll("snapshot"); + if (node.options.layoutRoot) { + node.willUpdate(false); + } + } + const { layoutId, layout } = this.options; + if (layoutId === undefined && !layout) + return; + const transformTemplate = this.getTransformTemplate(); + this.prevTransformTemplateValue = transformTemplate + ? transformTemplate(this.latestValues, "") + : undefined; + this.updateSnapshot(); + shouldNotifyListeners && this.notifyListeners("willUpdate"); + } + update() { + this.updateScheduled = false; + const updateWasBlocked = this.isUpdateBlocked(); + // When doing an instant transition, we skip the layout update, + // but should still clean up the measurements so that the next + // snapshot could be taken correctly. + if (updateWasBlocked) { + this.unblockUpdate(); + this.clearAllSnapshots(); + this.nodes.forEach(clearMeasurements); + return; + } + /** + * If this is a repeat of didUpdate then ignore the animation. + */ + if (this.animationId <= this.animationCommitId) { + this.nodes.forEach(clearIsLayoutDirty); + return; + } + this.animationCommitId = this.animationId; + if (!this.isUpdating) { + this.nodes.forEach(clearIsLayoutDirty); + } + else { + this.isUpdating = false; + /** + * Write + */ + this.nodes.forEach(resetTransformStyle); + /** + * Read ================== + */ + // Update layout measurements of updated children + this.nodes.forEach(updateLayout); + /** + * Write + */ + // Notify listeners that the layout is updated + this.nodes.forEach(notifyLayoutUpdate); + } + this.clearAllSnapshots(); + /** + * Manually flush any pending updates. Ideally + * we could leave this to the following requestAnimationFrame but this seems + * to leave a flash of incorrectly styled content. + */ + const now = time.now(); + frameData.delta = clamp(0, 1000 / 60, now - frameData.timestamp); + frameData.timestamp = now; + frameData.isProcessing = true; + frameSteps.update.process(frameData); + frameSteps.preRender.process(frameData); + frameSteps.render.process(frameData); + frameData.isProcessing = false; + } + didUpdate() { + if (!this.updateScheduled) { + this.updateScheduled = true; + microtask.read(this.scheduleUpdate); + } + } + clearAllSnapshots() { + this.nodes.forEach(clearSnapshot); + this.sharedNodes.forEach(removeLeadSnapshots); + } + scheduleUpdateProjection() { + if (!this.projectionUpdateScheduled) { + this.projectionUpdateScheduled = true; + frame.preRender(this.updateProjection, false, true); + } + } + scheduleCheckAfterUnmount() { + /** + * If the unmounting node is in a layoutGroup and did trigger a willUpdate, + * we manually call didUpdate to give a chance to the siblings to animate. + * Otherwise, cleanup all snapshots to prevents future nodes from reusing them. + */ + frame.postRender(() => { + if (this.isLayoutDirty) { + this.root.didUpdate(); + } + else { + this.root.checkUpdateFailed(); + } + }); + } + /** + * Update measurements + */ + updateSnapshot() { + if (this.snapshot || !this.instance) + return; + this.snapshot = this.measure(); + if (this.snapshot && + !calcLength(this.snapshot.measuredBox.x) && + !calcLength(this.snapshot.measuredBox.y)) { + this.snapshot = undefined; + } + } + updateLayout() { + if (!this.instance) + return; + this.updateScroll(); + if (!(this.options.alwaysMeasureLayout && this.isLead()) && + !this.isLayoutDirty) { + return; + } + /** + * When a node is mounted, it simply resumes from the prevLead's + * snapshot instead of taking a new one, but the ancestors scroll + * might have updated while the prevLead is unmounted. We need to + * update the scroll again to make sure the layout we measure is + * up to date. + */ + if (this.resumeFrom && !this.resumeFrom.instance) { + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + node.updateScroll(); + } + } + const prevLayout = this.layout; + this.layout = this.measure(false); + this.layoutCorrected = createBox(); + this.isLayoutDirty = false; + this.projectionDelta = undefined; + this.notifyListeners("measure", this.layout.layoutBox); + const { visualElement } = this.options; + visualElement && + visualElement.notify("LayoutMeasure", this.layout.layoutBox, prevLayout ? prevLayout.layoutBox : undefined); + } + updateScroll(phase = "measure") { + let needsMeasurement = Boolean(this.options.layoutScroll && this.instance); + if (this.scroll && + this.scroll.animationId === this.root.animationId && + this.scroll.phase === phase) { + needsMeasurement = false; + } + if (needsMeasurement && this.instance) { + const isRoot = checkIsScrollRoot(this.instance); + this.scroll = { + animationId: this.root.animationId, + phase, + isRoot, + offset: measureScroll(this.instance), + wasRoot: this.scroll ? this.scroll.isRoot : isRoot, + }; + } + } + resetTransform() { + if (!resetTransform) + return; + const isResetRequested = this.isLayoutDirty || + this.shouldResetTransform || + this.options.alwaysMeasureLayout; + const hasProjection = this.projectionDelta && !isDeltaZero(this.projectionDelta); + const transformTemplate = this.getTransformTemplate(); + const transformTemplateValue = transformTemplate + ? transformTemplate(this.latestValues, "") + : undefined; + const transformTemplateHasChanged = transformTemplateValue !== this.prevTransformTemplateValue; + if (isResetRequested && + this.instance && + (hasProjection || + hasTransform(this.latestValues) || + transformTemplateHasChanged)) { + resetTransform(this.instance, transformTemplateValue); + this.shouldResetTransform = false; + this.scheduleRender(); + } + } + measure(removeTransform = true) { + const pageBox = this.measurePageBox(); + let layoutBox = this.removeElementScroll(pageBox); + /** + * Measurements taken during the pre-render stage + * still have transforms applied so we remove them + * via calculation. + */ + if (removeTransform) { + layoutBox = this.removeTransform(layoutBox); + } + roundBox(layoutBox); + return { + animationId: this.root.animationId, + measuredBox: pageBox, + layoutBox, + latestValues: {}, + source: this.id, + }; + } + measurePageBox() { + const { visualElement } = this.options; + if (!visualElement) + return createBox(); + const box = visualElement.measureViewportBox(); + const wasInScrollRoot = this.scroll?.wasRoot || this.path.some(checkNodeWasScrollRoot); + if (!wasInScrollRoot) { + // Remove viewport scroll to give page-relative coordinates + const { scroll } = this.root; + if (scroll) { + translateAxis(box.x, scroll.offset.x); + translateAxis(box.y, scroll.offset.y); + } + } + return box; + } + removeElementScroll(box) { + const boxWithoutScroll = createBox(); + copyBoxInto(boxWithoutScroll, box); + if (this.scroll?.wasRoot) { + return boxWithoutScroll; + } + /** + * Performance TODO: Keep a cumulative scroll offset down the tree + * rather than loop back up the path. + */ + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + const { scroll, options } = node; + if (node !== this.root && scroll && options.layoutScroll) { + /** + * If this is a new scroll root, we want to remove all previous scrolls + * from the viewport box. + */ + if (scroll.wasRoot) { + copyBoxInto(boxWithoutScroll, box); + } + translateAxis(boxWithoutScroll.x, scroll.offset.x); + translateAxis(boxWithoutScroll.y, scroll.offset.y); + } + } + return boxWithoutScroll; + } + applyTransform(box, transformOnly = false) { + const withTransforms = createBox(); + copyBoxInto(withTransforms, box); + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + if (!transformOnly && + node.options.layoutScroll && + node.scroll && + node !== node.root) { + transformBox(withTransforms, { + x: -node.scroll.offset.x, + y: -node.scroll.offset.y, + }); + } + if (!hasTransform(node.latestValues)) + continue; + transformBox(withTransforms, node.latestValues); + } + if (hasTransform(this.latestValues)) { + transformBox(withTransforms, this.latestValues); + } + return withTransforms; + } + removeTransform(box) { + const boxWithoutTransform = createBox(); + copyBoxInto(boxWithoutTransform, box); + for (let i = 0; i < this.path.length; i++) { + const node = this.path[i]; + if (!node.instance) + continue; + if (!hasTransform(node.latestValues)) + continue; + hasScale(node.latestValues) && node.updateSnapshot(); + const sourceBox = createBox(); + const nodeBox = node.measurePageBox(); + copyBoxInto(sourceBox, nodeBox); + removeBoxTransforms(boxWithoutTransform, node.latestValues, node.snapshot ? node.snapshot.layoutBox : undefined, sourceBox); + } + if (hasTransform(this.latestValues)) { + removeBoxTransforms(boxWithoutTransform, this.latestValues); + } + return boxWithoutTransform; + } + setTargetDelta(delta) { + this.targetDelta = delta; + this.root.scheduleUpdateProjection(); + this.isProjectionDirty = true; + } + setOptions(options) { + this.options = { + ...this.options, + ...options, + crossfade: options.crossfade !== undefined ? options.crossfade : true, + }; + } + clearMeasurements() { + this.scroll = undefined; + this.layout = undefined; + this.snapshot = undefined; + this.prevTransformTemplateValue = undefined; + this.targetDelta = undefined; + this.target = undefined; + this.isLayoutDirty = false; + } + forceRelativeParentToResolveTarget() { + if (!this.relativeParent) + return; + /** + * If the parent target isn't up-to-date, force it to update. + * This is an unfortunate de-optimisation as it means any updating relative + * projection will cause all the relative parents to recalculate back + * up the tree. + */ + if (this.relativeParent.resolvedRelativeTargetAt !== + frameData.timestamp) { + this.relativeParent.resolveTargetDelta(true); + } + } + resolveTargetDelta(forceRecalculation = false) { + /** + * Once the dirty status of nodes has been spread through the tree, we also + * need to check if we have a shared node of a different depth that has itself + * been dirtied. + */ + const lead = this.getLead(); + this.isProjectionDirty || (this.isProjectionDirty = lead.isProjectionDirty); + this.isTransformDirty || (this.isTransformDirty = lead.isTransformDirty); + this.isSharedProjectionDirty || (this.isSharedProjectionDirty = lead.isSharedProjectionDirty); + const isShared = Boolean(this.resumingFrom) || this !== lead; + /** + * We don't use transform for this step of processing so we don't + * need to check whether any nodes have changed transform. + */ + const canSkip = !(forceRecalculation || + (isShared && this.isSharedProjectionDirty) || + this.isProjectionDirty || + this.parent?.isProjectionDirty || + this.attemptToResolveRelativeTarget || + this.root.updateBlockedByResize); + if (canSkip) + return; + const { layout, layoutId } = this.options; + /** + * If we have no layout, we can't perform projection, so early return + */ + if (!this.layout || !(layout || layoutId)) + return; + this.resolvedRelativeTargetAt = frameData.timestamp; + /** + * If we don't have a targetDelta but do have a layout, we can attempt to resolve + * a relativeParent. This will allow a component to perform scale correction + * even if no animation has started. + */ + if (!this.targetDelta && !this.relativeTarget) { + const relativeParent = this.getClosestProjectingParent(); + if (relativeParent && + relativeParent.layout && + this.animationProgress !== 1) { + this.relativeParent = relativeParent; + this.forceRelativeParentToResolveTarget(); + this.relativeTarget = createBox(); + this.relativeTargetOrigin = createBox(); + calcRelativePosition(this.relativeTargetOrigin, this.layout.layoutBox, relativeParent.layout.layoutBox); + copyBoxInto(this.relativeTarget, this.relativeTargetOrigin); + } + else { + this.relativeParent = this.relativeTarget = undefined; + } + } + /** + * If we have no relative target or no target delta our target isn't valid + * for this frame. + */ + if (!this.relativeTarget && !this.targetDelta) + return; + /** + * Lazy-init target data structure + */ + if (!this.target) { + this.target = createBox(); + this.targetWithTransforms = createBox(); + } + /** + * If we've got a relative box for this component, resolve it into a target relative to the parent. + */ + if (this.relativeTarget && + this.relativeTargetOrigin && + this.relativeParent && + this.relativeParent.target) { + this.forceRelativeParentToResolveTarget(); + calcRelativeBox(this.target, this.relativeTarget, this.relativeParent.target); + /** + * If we've only got a targetDelta, resolve it into a target + */ + } + else if (this.targetDelta) { + if (Boolean(this.resumingFrom)) { + // TODO: This is creating a new object every frame + this.target = this.applyTransform(this.layout.layoutBox); + } + else { + copyBoxInto(this.target, this.layout.layoutBox); + } + applyBoxDelta(this.target, this.targetDelta); + } + else { + /** + * If no target, use own layout as target + */ + copyBoxInto(this.target, this.layout.layoutBox); + } + /** + * If we've been told to attempt to resolve a relative target, do so. + */ + if (this.attemptToResolveRelativeTarget) { + this.attemptToResolveRelativeTarget = false; + const relativeParent = this.getClosestProjectingParent(); + if (relativeParent && + Boolean(relativeParent.resumingFrom) === + Boolean(this.resumingFrom) && + !relativeParent.options.layoutScroll && + relativeParent.target && + this.animationProgress !== 1) { + this.relativeParent = relativeParent; + this.forceRelativeParentToResolveTarget(); + this.relativeTarget = createBox(); + this.relativeTargetOrigin = createBox(); + calcRelativePosition(this.relativeTargetOrigin, this.target, relativeParent.target); + copyBoxInto(this.relativeTarget, this.relativeTargetOrigin); + } + else { + this.relativeParent = this.relativeTarget = undefined; + } + } + /** + * Increase debug counter for resolved target deltas + */ + if (statsBuffer.value) { + metrics.calculatedTargetDeltas++; + } + } + getClosestProjectingParent() { + if (!this.parent || + hasScale(this.parent.latestValues) || + has2DTranslate(this.parent.latestValues)) { + return undefined; + } + if (this.parent.isProjecting()) { + return this.parent; + } + else { + return this.parent.getClosestProjectingParent(); + } + } + isProjecting() { + return Boolean((this.relativeTarget || + this.targetDelta || + this.options.layoutRoot) && + this.layout); + } + calcProjection() { + const lead = this.getLead(); + const isShared = Boolean(this.resumingFrom) || this !== lead; + let canSkip = true; + /** + * If this is a normal layout animation and neither this node nor its nearest projecting + * is dirty then we can't skip. + */ + if (this.isProjectionDirty || this.parent?.isProjectionDirty) { + canSkip = false; + } + /** + * If this is a shared layout animation and this node's shared projection is dirty then + * we can't skip. + */ + if (isShared && + (this.isSharedProjectionDirty || this.isTransformDirty)) { + canSkip = false; + } + /** + * If we have resolved the target this frame we must recalculate the + * projection to ensure it visually represents the internal calculations. + */ + if (this.resolvedRelativeTargetAt === frameData.timestamp) { + canSkip = false; + } + if (canSkip) + return; + const { layout, layoutId } = this.options; + /** + * If this section of the tree isn't animating we can + * delete our target sources for the following frame. + */ + this.isTreeAnimating = Boolean((this.parent && this.parent.isTreeAnimating) || + this.currentAnimation || + this.pendingAnimation); + if (!this.isTreeAnimating) { + this.targetDelta = this.relativeTarget = undefined; + } + if (!this.layout || !(layout || layoutId)) + return; + /** + * Reset the corrected box with the latest values from box, as we're then going + * to perform mutative operations on it. + */ + copyBoxInto(this.layoutCorrected, this.layout.layoutBox); + /** + * Record previous tree scales before updating. + */ + const prevTreeScaleX = this.treeScale.x; + const prevTreeScaleY = this.treeScale.y; + /** + * Apply all the parent deltas to this box to produce the corrected box. This + * is the layout box, as it will appear on screen as a result of the transforms of its parents. + */ + applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, isShared); + /** + * If this layer needs to perform scale correction but doesn't have a target, + * use the layout as the target. + */ + if (lead.layout && + !lead.target && + (this.treeScale.x !== 1 || this.treeScale.y !== 1)) { + lead.target = lead.layout.layoutBox; + lead.targetWithTransforms = createBox(); + } + const { target } = lead; + if (!target) { + /** + * If we don't have a target to project into, but we were previously + * projecting, we want to remove the stored transform and schedule + * a render to ensure the elements reflect the removed transform. + */ + if (this.prevProjectionDelta) { + this.createProjectionDeltas(); + this.scheduleRender(); + } + return; + } + if (!this.projectionDelta || !this.prevProjectionDelta) { + this.createProjectionDeltas(); + } + else { + copyAxisDeltaInto(this.prevProjectionDelta.x, this.projectionDelta.x); + copyAxisDeltaInto(this.prevProjectionDelta.y, this.projectionDelta.y); + } + /** + * Update the delta between the corrected box and the target box before user-set transforms were applied. + * This will allow us to calculate the corrected borderRadius and boxShadow to compensate + * for our layout reprojection, but still allow them to be scaled correctly by the user. + * It might be that to simplify this we may want to accept that user-set scale is also corrected + * and we wouldn't have to keep and calc both deltas, OR we could support a user setting + * to allow people to choose whether these styles are corrected based on just the + * layout reprojection or the final bounding box. + */ + calcBoxDelta(this.projectionDelta, this.layoutCorrected, target, this.latestValues); + if (this.treeScale.x !== prevTreeScaleX || + this.treeScale.y !== prevTreeScaleY || + !axisDeltaEquals(this.projectionDelta.x, this.prevProjectionDelta.x) || + !axisDeltaEquals(this.projectionDelta.y, this.prevProjectionDelta.y)) { + this.hasProjected = true; + this.scheduleRender(); + this.notifyListeners("projectionUpdate", target); + } + /** + * Increase debug counter for recalculated projections + */ + if (statsBuffer.value) { + metrics.calculatedProjections++; + } + } + hide() { + this.isVisible = false; + // TODO: Schedule render + } + show() { + this.isVisible = true; + // TODO: Schedule render + } + scheduleRender(notifyAll = true) { + this.options.visualElement?.scheduleRender(); + if (notifyAll) { + const stack = this.getStack(); + stack && stack.scheduleRender(); + } + if (this.resumingFrom && !this.resumingFrom.instance) { + this.resumingFrom = undefined; + } + } + createProjectionDeltas() { + this.prevProjectionDelta = createDelta(); + this.projectionDelta = createDelta(); + this.projectionDeltaWithTransform = createDelta(); + } + setAnimationOrigin(delta, hasOnlyRelativeTargetChanged = false) { + const snapshot = this.snapshot; + const snapshotLatestValues = snapshot ? snapshot.latestValues : {}; + const mixedValues = { ...this.latestValues }; + const targetDelta = createDelta(); + if (!this.relativeParent || + !this.relativeParent.options.layoutRoot) { + this.relativeTarget = this.relativeTargetOrigin = undefined; + } + this.attemptToResolveRelativeTarget = !hasOnlyRelativeTargetChanged; + const relativeLayout = createBox(); + const snapshotSource = snapshot ? snapshot.source : undefined; + const layoutSource = this.layout ? this.layout.source : undefined; + const isSharedLayoutAnimation = snapshotSource !== layoutSource; + const stack = this.getStack(); + const isOnlyMember = !stack || stack.members.length <= 1; + const shouldCrossfadeOpacity = Boolean(isSharedLayoutAnimation && + !isOnlyMember && + this.options.crossfade === true && + !this.path.some(hasOpacityCrossfade)); + this.animationProgress = 0; + let prevRelativeTarget; + this.mixTargetDelta = (latest) => { + const progress = latest / 1000; + mixAxisDelta(targetDelta.x, delta.x, progress); + mixAxisDelta(targetDelta.y, delta.y, progress); + this.setTargetDelta(targetDelta); + if (this.relativeTarget && + this.relativeTargetOrigin && + this.layout && + this.relativeParent && + this.relativeParent.layout) { + calcRelativePosition(relativeLayout, this.layout.layoutBox, this.relativeParent.layout.layoutBox); + mixBox(this.relativeTarget, this.relativeTargetOrigin, relativeLayout, progress); + /** + * If this is an unchanged relative target we can consider the + * projection not dirty. + */ + if (prevRelativeTarget && + boxEquals(this.relativeTarget, prevRelativeTarget)) { + this.isProjectionDirty = false; + } + if (!prevRelativeTarget) + prevRelativeTarget = createBox(); + copyBoxInto(prevRelativeTarget, this.relativeTarget); + } + if (isSharedLayoutAnimation) { + this.animationValues = mixedValues; + mixValues(mixedValues, snapshotLatestValues, this.latestValues, progress, shouldCrossfadeOpacity, isOnlyMember); + } + this.root.scheduleUpdateProjection(); + this.scheduleRender(); + this.animationProgress = progress; + }; + this.mixTargetDelta(this.options.layoutRoot ? 1000 : 0); + } + startAnimation(options) { + this.notifyListeners("animationStart"); + this.currentAnimation?.stop(); + this.resumingFrom?.currentAnimation?.stop(); + if (this.pendingAnimation) { + cancelFrame(this.pendingAnimation); + this.pendingAnimation = undefined; + } + /** + * Start the animation in the next frame to have a frame with progress 0, + * where the target is the same as when the animation started, so we can + * calculate the relative positions correctly for instant transitions. + */ + this.pendingAnimation = frame.update(() => { + globalProjectionState.hasAnimatedSinceResize = true; + activeAnimations.layout++; + this.motionValue || (this.motionValue = motionValue(0)); + this.currentAnimation = animateSingleValue(this.motionValue, [0, 1000], { + ...options, + velocity: 0, + isSync: true, + onUpdate: (latest) => { + this.mixTargetDelta(latest); + options.onUpdate && options.onUpdate(latest); + }, + onStop: () => { + activeAnimations.layout--; + }, + onComplete: () => { + activeAnimations.layout--; + options.onComplete && options.onComplete(); + this.completeAnimation(); + }, + }); + if (this.resumingFrom) { + this.resumingFrom.currentAnimation = this.currentAnimation; + } + this.pendingAnimation = undefined; + }); + } + completeAnimation() { + if (this.resumingFrom) { + this.resumingFrom.currentAnimation = undefined; + this.resumingFrom.preserveOpacity = undefined; + } + const stack = this.getStack(); + stack && stack.exitAnimationComplete(); + this.resumingFrom = + this.currentAnimation = + this.animationValues = + undefined; + this.notifyListeners("animationComplete"); + } + finishAnimation() { + if (this.currentAnimation) { + this.mixTargetDelta && this.mixTargetDelta(animationTarget); + this.currentAnimation.stop(); + } + this.completeAnimation(); + } + applyTransformsToTarget() { + const lead = this.getLead(); + let { targetWithTransforms, target, layout, latestValues } = lead; + if (!targetWithTransforms || !target || !layout) + return; + /** + * If we're only animating position, and this element isn't the lead element, + * then instead of projecting into the lead box we instead want to calculate + * a new target that aligns the two boxes but maintains the layout shape. + */ + if (this !== lead && + this.layout && + layout && + shouldAnimatePositionOnly(this.options.animationType, this.layout.layoutBox, layout.layoutBox)) { + target = this.target || createBox(); + const xLength = calcLength(this.layout.layoutBox.x); + target.x.min = lead.target.x.min; + target.x.max = target.x.min + xLength; + const yLength = calcLength(this.layout.layoutBox.y); + target.y.min = lead.target.y.min; + target.y.max = target.y.min + yLength; + } + copyBoxInto(targetWithTransforms, target); + /** + * Apply the latest user-set transforms to the targetBox to produce the targetBoxFinal. + * This is the final box that we will then project into by calculating a transform delta and + * applying it to the corrected box. + */ + transformBox(targetWithTransforms, latestValues); + /** + * Update the delta between the corrected box and the final target box, after + * user-set transforms are applied to it. This will be used by the renderer to + * create a transform style that will reproject the element from its layout layout + * into the desired bounding box. + */ + calcBoxDelta(this.projectionDeltaWithTransform, this.layoutCorrected, targetWithTransforms, latestValues); + } + registerSharedNode(layoutId, node) { + if (!this.sharedNodes.has(layoutId)) { + this.sharedNodes.set(layoutId, new NodeStack()); + } + const stack = this.sharedNodes.get(layoutId); + stack.add(node); + const config = node.options.initialPromotionConfig; + node.promote({ + transition: config ? config.transition : undefined, + preserveFollowOpacity: config && config.shouldPreserveFollowOpacity + ? config.shouldPreserveFollowOpacity(node) + : undefined, + }); + } + isLead() { + const stack = this.getStack(); + return stack ? stack.lead === this : true; + } + getLead() { + const { layoutId } = this.options; + return layoutId ? this.getStack()?.lead || this : this; + } + getPrevLead() { + const { layoutId } = this.options; + return layoutId ? this.getStack()?.prevLead : undefined; + } + getStack() { + const { layoutId } = this.options; + if (layoutId) + return this.root.sharedNodes.get(layoutId); + } + promote({ needsReset, transition, preserveFollowOpacity, } = {}) { + const stack = this.getStack(); + if (stack) + stack.promote(this, preserveFollowOpacity); + if (needsReset) { + this.projectionDelta = undefined; + this.needsReset = true; + } + if (transition) + this.setOptions({ transition }); + } + relegate() { + const stack = this.getStack(); + if (stack) { + return stack.relegate(this); + } + else { + return false; + } + } + resetSkewAndRotation() { + const { visualElement } = this.options; + if (!visualElement) + return; + // If there's no detected skew or rotation values, we can early return without a forced render. + let hasDistortingTransform = false; + /** + * An unrolled check for rotation values. Most elements don't have any rotation and + * skipping the nested loop and new object creation is 50% faster. + */ + const { latestValues } = visualElement; + if (latestValues.z || + latestValues.rotate || + latestValues.rotateX || + latestValues.rotateY || + latestValues.rotateZ || + latestValues.skewX || + latestValues.skewY) { + hasDistortingTransform = true; + } + // If there's no distorting values, we don't need to do any more. + if (!hasDistortingTransform) + return; + const resetValues = {}; + if (latestValues.z) { + resetDistortingTransform("z", visualElement, resetValues, this.animationValues); + } + // Check the skew and rotate value of all axes and reset to 0 + for (let i = 0; i < transformAxes.length; i++) { + resetDistortingTransform(`rotate${transformAxes[i]}`, visualElement, resetValues, this.animationValues); + resetDistortingTransform(`skew${transformAxes[i]}`, visualElement, resetValues, this.animationValues); + } + // Force a render of this element to apply the transform with all skews and rotations + // set to 0. + visualElement.render(); + // Put back all the values we reset + for (const key in resetValues) { + visualElement.setStaticValue(key, resetValues[key]); + if (this.animationValues) { + this.animationValues[key] = resetValues[key]; + } + } + // Schedule a render for the next frame. This ensures we won't visually + // see the element with the reset rotate value applied. + visualElement.scheduleRender(); + } + applyProjectionStyles(targetStyle, // CSSStyleDeclaration - doesn't allow numbers to be assigned to properties + styleProp) { + if (!this.instance || this.isSVG) + return; + if (!this.isVisible) { + targetStyle.visibility = "hidden"; + return; + } + const transformTemplate = this.getTransformTemplate(); + if (this.needsReset) { + this.needsReset = false; + targetStyle.visibility = ""; + targetStyle.opacity = ""; + targetStyle.pointerEvents = + resolveMotionValue(styleProp?.pointerEvents) || ""; + targetStyle.transform = transformTemplate + ? transformTemplate(this.latestValues, "") + : "none"; + return; + } + const lead = this.getLead(); + if (!this.projectionDelta || !this.layout || !lead.target) { + if (this.options.layoutId) { + targetStyle.opacity = + this.latestValues.opacity !== undefined + ? this.latestValues.opacity + : 1; + targetStyle.pointerEvents = + resolveMotionValue(styleProp?.pointerEvents) || ""; + } + if (this.hasProjected && !hasTransform(this.latestValues)) { + targetStyle.transform = transformTemplate + ? transformTemplate({}, "") + : "none"; + this.hasProjected = false; + } + return; + } + targetStyle.visibility = ""; + const valuesToRender = lead.animationValues || lead.latestValues; + this.applyTransformsToTarget(); + let transform = buildProjectionTransform(this.projectionDeltaWithTransform, this.treeScale, valuesToRender); + if (transformTemplate) { + transform = transformTemplate(valuesToRender, transform); + } + targetStyle.transform = transform; + const { x, y } = this.projectionDelta; + targetStyle.transformOrigin = `${x.origin * 100}% ${y.origin * 100}% 0`; + if (lead.animationValues) { + /** + * If the lead component is animating, assign this either the entering/leaving + * opacity + */ + targetStyle.opacity = + lead === this + ? valuesToRender.opacity ?? + this.latestValues.opacity ?? + 1 + : this.preserveOpacity + ? this.latestValues.opacity + : valuesToRender.opacityExit; + } + else { + /** + * Or we're not animating at all, set the lead component to its layout + * opacity and other components to hidden. + */ + targetStyle.opacity = + lead === this + ? valuesToRender.opacity !== undefined + ? valuesToRender.opacity + : "" + : valuesToRender.opacityExit !== undefined + ? valuesToRender.opacityExit + : 0; + } + /** + * Apply scale correction + */ + for (const key in scaleCorrectors) { + if (valuesToRender[key] === undefined) + continue; + const { correct, applyTo, isCSSVariable } = scaleCorrectors[key]; + /** + * Only apply scale correction to the value if we have an + * active projection transform. Otherwise these values become + * vulnerable to distortion if the element changes size without + * a corresponding layout animation. + */ + const corrected = transform === "none" + ? valuesToRender[key] + : correct(valuesToRender[key], lead); + if (applyTo) { + const num = applyTo.length; + for (let i = 0; i < num; i++) { + targetStyle[applyTo[i]] = corrected; + } + } + else { + // If this is a CSS variable, set it directly on the instance. + // Replacing this function from creating styles to setting them + // would be a good place to remove per frame object creation + if (isCSSVariable) { + this.options.visualElement.renderState.vars[key] = corrected; + } + else { + targetStyle[key] = corrected; + } + } + } + /** + * Disable pointer events on follow components. This is to ensure + * that if a follow component covers a lead component it doesn't block + * pointer events on the lead. + */ + if (this.options.layoutId) { + targetStyle.pointerEvents = + lead === this + ? resolveMotionValue(styleProp?.pointerEvents) || "" + : "none"; + } + } + clearSnapshot() { + this.resumeFrom = this.snapshot = undefined; + } + // Only run on root + resetTree() { + this.root.nodes.forEach((node) => node.currentAnimation?.stop()); + this.root.nodes.forEach(clearMeasurements); + this.root.sharedNodes.clear(); + } + }; + } + function updateLayout(node) { + node.updateLayout(); + } + function notifyLayoutUpdate(node) { + const snapshot = node.resumeFrom?.snapshot || node.snapshot; + if (node.isLead() && + node.layout && + snapshot && + node.hasListeners("didUpdate")) { + const { layoutBox: layout, measuredBox: measuredLayout } = node.layout; + const { animationType } = node.options; + const isShared = snapshot.source !== node.layout.source; + // TODO Maybe we want to also resize the layout snapshot so we don't trigger + // animations for instance if layout="size" and an element has only changed position + if (animationType === "size") { + eachAxis((axis) => { + const axisSnapshot = isShared + ? snapshot.measuredBox[axis] + : snapshot.layoutBox[axis]; + const length = calcLength(axisSnapshot); + axisSnapshot.min = layout[axis].min; + axisSnapshot.max = axisSnapshot.min + length; + }); + } + else if (shouldAnimatePositionOnly(animationType, snapshot.layoutBox, layout)) { + eachAxis((axis) => { + const axisSnapshot = isShared + ? snapshot.measuredBox[axis] + : snapshot.layoutBox[axis]; + const length = calcLength(layout[axis]); + axisSnapshot.max = axisSnapshot.min + length; + /** + * Ensure relative target gets resized and rerendererd + */ + if (node.relativeTarget && !node.currentAnimation) { + node.isProjectionDirty = true; + node.relativeTarget[axis].max = + node.relativeTarget[axis].min + length; + } + }); + } + const layoutDelta = createDelta(); + calcBoxDelta(layoutDelta, layout, snapshot.layoutBox); + const visualDelta = createDelta(); + if (isShared) { + calcBoxDelta(visualDelta, node.applyTransform(measuredLayout, true), snapshot.measuredBox); + } + else { + calcBoxDelta(visualDelta, layout, snapshot.layoutBox); + } + const hasLayoutChanged = !isDeltaZero(layoutDelta); + let hasRelativeLayoutChanged = false; + if (!node.resumeFrom) { + const relativeParent = node.getClosestProjectingParent(); + /** + * If the relativeParent is itself resuming from a different element then + * the relative snapshot is not relavent + */ + if (relativeParent && !relativeParent.resumeFrom) { + const { snapshot: parentSnapshot, layout: parentLayout } = relativeParent; + if (parentSnapshot && parentLayout) { + const relativeSnapshot = createBox(); + calcRelativePosition(relativeSnapshot, snapshot.layoutBox, parentSnapshot.layoutBox); + const relativeLayout = createBox(); + calcRelativePosition(relativeLayout, layout, parentLayout.layoutBox); + if (!boxEqualsRounded(relativeSnapshot, relativeLayout)) { + hasRelativeLayoutChanged = true; + } + if (relativeParent.options.layoutRoot) { + node.relativeTarget = relativeLayout; + node.relativeTargetOrigin = relativeSnapshot; + node.relativeParent = relativeParent; + } + } + } + } + node.notifyListeners("didUpdate", { + layout, + snapshot, + delta: visualDelta, + layoutDelta, + hasLayoutChanged, + hasRelativeLayoutChanged, + }); + } + else if (node.isLead()) { + const { onExitComplete } = node.options; + onExitComplete && onExitComplete(); + } + /** + * Clearing transition + * TODO: Investigate why this transition is being passed in as {type: false } from Framer + * and why we need it at all + */ + node.options.transition = undefined; + } + function propagateDirtyNodes(node) { + /** + * Increase debug counter for nodes encountered this frame + */ + if (statsBuffer.value) { + metrics.nodes++; + } + if (!node.parent) + return; + /** + * If this node isn't projecting, propagate isProjectionDirty. It will have + * no performance impact but it will allow the next child that *is* projecting + * but *isn't* dirty to just check its parent to see if *any* ancestor needs + * correcting. + */ + if (!node.isProjecting()) { + node.isProjectionDirty = node.parent.isProjectionDirty; + } + /** + * Propagate isSharedProjectionDirty and isTransformDirty + * throughout the whole tree. A future revision can take another look at + * this but for safety we still recalcualte shared nodes. + */ + node.isSharedProjectionDirty || (node.isSharedProjectionDirty = Boolean(node.isProjectionDirty || + node.parent.isProjectionDirty || + node.parent.isSharedProjectionDirty)); + node.isTransformDirty || (node.isTransformDirty = node.parent.isTransformDirty); + } + function cleanDirtyNodes(node) { + node.isProjectionDirty = + node.isSharedProjectionDirty = + node.isTransformDirty = + false; + } + function clearSnapshot(node) { + node.clearSnapshot(); + } + function clearMeasurements(node) { + node.clearMeasurements(); + } + function clearIsLayoutDirty(node) { + node.isLayoutDirty = false; + } + function resetTransformStyle(node) { + const { visualElement } = node.options; + if (visualElement && visualElement.getProps().onBeforeLayoutMeasure) { + visualElement.notify("BeforeLayoutMeasure"); + } + node.resetTransform(); + } + function finishAnimation(node) { + node.finishAnimation(); + node.targetDelta = node.relativeTarget = node.target = undefined; + node.isProjectionDirty = true; + } + function resolveTargetDelta(node) { + node.resolveTargetDelta(); + } + function calcProjection(node) { + node.calcProjection(); + } + function resetSkewAndRotation(node) { + node.resetSkewAndRotation(); + } + function removeLeadSnapshots(stack) { + stack.removeLeadSnapshot(); + } + function mixAxisDelta(output, delta, p) { + output.translate = mixNumber$1(delta.translate, 0, p); + output.scale = mixNumber$1(delta.scale, 1, p); + output.origin = delta.origin; + output.originPoint = delta.originPoint; + } + function mixAxis(output, from, to, p) { + output.min = mixNumber$1(from.min, to.min, p); + output.max = mixNumber$1(from.max, to.max, p); + } + function mixBox(output, from, to, p) { + mixAxis(output.x, from.x, to.x, p); + mixAxis(output.y, from.y, to.y, p); + } + function hasOpacityCrossfade(node) { + return (node.animationValues && node.animationValues.opacityExit !== undefined); + } + const defaultLayoutTransition = { + duration: 0.45, + ease: [0.4, 0, 0.1, 1], + }; + const userAgentContains = (string) => typeof navigator !== "undefined" && + navigator.userAgent && + navigator.userAgent.toLowerCase().includes(string); + /** + * Measured bounding boxes must be rounded in Safari and + * left untouched in Chrome, otherwise non-integer layouts within scaled-up elements + * can appear to jump. + */ + const roundPoint = userAgentContains("applewebkit/") && !userAgentContains("chrome/") + ? Math.round + : noop; + function roundAxis(axis) { + // Round to the nearest .5 pixels to support subpixel layouts + axis.min = roundPoint(axis.min); + axis.max = roundPoint(axis.max); + } + function roundBox(box) { + roundAxis(box.x); + roundAxis(box.y); + } + function shouldAnimatePositionOnly(animationType, snapshot, layout) { + return (animationType === "position" || + (animationType === "preserve-aspect" && + !isNear(aspectRatio(snapshot), aspectRatio(layout), 0.2))); + } + function checkNodeWasScrollRoot(node) { + return node !== node.root && node.scroll?.wasRoot; + } + + function addDomEvent(target, eventName, handler, options = { passive: true }) { + target.addEventListener(eventName, handler, options); + return () => target.removeEventListener(eventName, handler); + } + + const DocumentProjectionNode = createProjectionNode$1({ + attachResizeListener: (ref, notify) => addDomEvent(ref, "resize", notify), + measureScroll: () => ({ + x: document.documentElement.scrollLeft || document.body.scrollLeft, + y: document.documentElement.scrollTop || document.body.scrollTop, + }), + checkIsScrollRoot: () => true, + }); + + const rootProjectionNode = { + current: undefined, + }; + const HTMLProjectionNode = createProjectionNode$1({ + measureScroll: (instance) => ({ + x: instance.scrollLeft, + y: instance.scrollTop, + }), + defaultParent: () => { + if (!rootProjectionNode.current) { + const documentNode = new DocumentProjectionNode({}); + documentNode.mount(window); + documentNode.setOptions({ layoutScroll: true }); + rootProjectionNode.current = documentNode; + } + return rootProjectionNode.current; + }, + resetTransform: (instance, value) => { + instance.style.transform = value !== undefined ? value : "none"; + }, + checkIsScrollRoot: (instance) => Boolean(window.getComputedStyle(instance).position === "fixed"), + }); + + function pixelsToPercent(pixels, axis) { + if (axis.max === axis.min) + return 0; + return (pixels / (axis.max - axis.min)) * 100; + } + /** + * We always correct borderRadius as a percentage rather than pixels to reduce paints. + * For example, if you are projecting a box that is 100px wide with a 10px borderRadius + * into a box that is 200px wide with a 20px borderRadius, that is actually a 10% + * borderRadius in both states. If we animate between the two in pixels that will trigger + * a paint each time. If we animate between the two in percentage we'll avoid a paint. + */ + const correctBorderRadius = { + correct: (latest, node) => { + if (!node.target) + return latest; + /** + * If latest is a string, if it's a percentage we can return immediately as it's + * going to be stretched appropriately. Otherwise, if it's a pixel, convert it to a number. + */ + if (typeof latest === "string") { + if (px.test(latest)) { + latest = parseFloat(latest); + } + else { + return latest; + } + } + /** + * If latest is a number, it's a pixel value. We use the current viewportBox to calculate that + * pixel value as a percentage of each axis + */ + const x = pixelsToPercent(latest, node.target.x); + const y = pixelsToPercent(latest, node.target.y); + return `${x}% ${y}%`; + }, + }; + + const correctBoxShadow = { + correct: (latest, { treeScale, projectionDelta }) => { + const original = latest; + const shadow = complex.parse(latest); + // TODO: Doesn't support multiple shadows + if (shadow.length > 5) + return original; + const template = complex.createTransformer(latest); + const offset = typeof shadow[0] !== "number" ? 1 : 0; + // Calculate the overall context scale + const xScale = projectionDelta.x.scale * treeScale.x; + const yScale = projectionDelta.y.scale * treeScale.y; + shadow[0 + offset] /= xScale; + shadow[1 + offset] /= yScale; + /** + * Ideally we'd correct x and y scales individually, but because blur and + * spread apply to both we have to take a scale average and apply that instead. + * We could potentially improve the outcome of this by incorporating the ratio between + * the two scales. + */ + const averageScale = mixNumber$1(xScale, yScale, 0.5); + // Blur + if (typeof shadow[2 + offset] === "number") + shadow[2 + offset] /= averageScale; + // Spread + if (typeof shadow[3 + offset] === "number") + shadow[3 + offset] /= averageScale; + return template(shadow); + }, + }; + + /** + * Bounding boxes tend to be defined as top, left, right, bottom. For various operations + * it's easier to consider each axis individually. This function returns a bounding box + * as a map of single-axis min/max values. + */ + function convertBoundingBoxToBox({ top, left, right, bottom, }) { + return { + x: { min: left, max: right }, + y: { min: top, max: bottom }, + }; + } + function convertBoxToBoundingBox({ x, y }) { + return { top: y.min, right: x.max, bottom: y.max, left: x.min }; + } + /** + * Applies a TransformPoint function to a bounding box. TransformPoint is usually a function + * provided by Framer to allow measured points to be corrected for device scaling. This is used + * when measuring DOM elements and DOM event points. + */ + function transformBoxPoints(point, transformPoint) { + if (!transformPoint) + return point; + const topLeft = transformPoint({ x: point.left, y: point.top }); + const bottomRight = transformPoint({ x: point.right, y: point.bottom }); + return { + top: topLeft.y, + left: topLeft.x, + bottom: bottomRight.y, + right: bottomRight.x, + }; + } + + function measureViewportBox(instance, transformPoint) { + return convertBoundingBoxToBox(transformBoxPoints(instance.getBoundingClientRect(), transformPoint)); + } + function measurePageBox(element, rootProjectionNode, transformPagePoint) { + const viewportBox = measureViewportBox(element, transformPagePoint); + const { scroll } = rootProjectionNode; + if (scroll) { + translateAxis(viewportBox.x, scroll.offset.x); + translateAxis(viewportBox.y, scroll.offset.y); + } + return viewportBox; + } + + const featureProps = { + animation: [ + "animate", + "variants", + "whileHover", + "whileTap", + "exit", + "whileInView", + "whileFocus", + "whileDrag", + ], + exit: ["exit"], + drag: ["drag", "dragControls"], + focus: ["whileFocus"], + hover: ["whileHover", "onHoverStart", "onHoverEnd"], + tap: ["whileTap", "onTap", "onTapStart", "onTapCancel"], + pan: ["onPan", "onPanStart", "onPanSessionStart", "onPanEnd"], + inView: ["whileInView", "onViewportEnter", "onViewportLeave"], + layout: ["layout", "layoutId"], + }; + const featureDefinitions = {}; + for (const key in featureProps) { + featureDefinitions[key] = { + isEnabled: (props) => featureProps[key].some((name) => !!props[name]), + }; + } + + // Does this device prefer reduced motion? Returns `null` server-side. + const prefersReducedMotion = { current: null }; + const hasReducedMotionListener = { current: false }; + + function initPrefersReducedMotion() { + hasReducedMotionListener.current = true; + if (!isBrowser) + return; + if (window.matchMedia) { + const motionMediaQuery = window.matchMedia("(prefers-reduced-motion)"); + const setReducedMotionPreferences = () => (prefersReducedMotion.current = motionMediaQuery.matches); + motionMediaQuery.addEventListener("change", setReducedMotionPreferences); + setReducedMotionPreferences(); + } + else { + prefersReducedMotion.current = false; + } + } + + const visualElementStore = new WeakMap(); + + function isAnimationControls(v) { + return (v !== null && + typeof v === "object" && + typeof v.start === "function"); + } + + /** + * Decides if the supplied variable is variant label + */ + function isVariantLabel(v) { + return typeof v === "string" || Array.isArray(v); + } + + const variantPriorityOrder = [ + "animate", + "whileInView", + "whileFocus", + "whileHover", + "whileTap", + "whileDrag", + "exit", + ]; + const variantProps = ["initial", ...variantPriorityOrder]; + + function isControllingVariants(props) { + return (isAnimationControls(props.animate) || + variantProps.some((name) => isVariantLabel(props[name]))); + } + function isVariantNode(props) { + return Boolean(isControllingVariants(props) || props.variants); + } + + function updateMotionValuesFromProps(element, next, prev) { + for (const key in next) { + const nextValue = next[key]; + const prevValue = prev[key]; + if (isMotionValue(nextValue)) { + /** + * If this is a motion value found in props or style, we want to add it + * to our visual element's motion value map. + */ + element.addValue(key, nextValue); + } + else if (isMotionValue(prevValue)) { + /** + * If we're swapping from a motion value to a static value, + * create a new motion value from that + */ + element.addValue(key, motionValue(nextValue, { owner: element })); + } + else if (prevValue !== nextValue) { + /** + * If this is a flat value that has changed, update the motion value + * or create one if it doesn't exist. We only want to do this if we're + * not handling the value with our animation state. + */ + if (element.hasValue(key)) { + const existingValue = element.getValue(key); + if (existingValue.liveStyle === true) { + existingValue.jump(nextValue); + } + else if (!existingValue.hasAnimated) { + existingValue.set(nextValue); + } + } + else { + const latestValue = element.getStaticValue(key); + element.addValue(key, motionValue(latestValue !== undefined ? latestValue : nextValue, { owner: element })); + } + } + } + // Handle removed values + for (const key in prev) { + if (next[key] === undefined) + element.removeValue(key); + } + return next; + } + + function getValueState(visualElement) { + const state = [{}, {}]; + visualElement?.values.forEach((value, key) => { + state[0][key] = value.get(); + state[1][key] = value.getVelocity(); + }); + return state; + } + function resolveVariantFromProps(props, definition, custom, visualElement) { + /** + * If the variant definition is a function, resolve. + */ + if (typeof definition === "function") { + const [current, velocity] = getValueState(visualElement); + definition = definition(custom !== undefined ? custom : props.custom, current, velocity); + } + /** + * If the variant definition is a variant label, or + * the function returned a variant label, resolve. + */ + if (typeof definition === "string") { + definition = props.variants && props.variants[definition]; + } + /** + * At this point we've resolved both functions and variant labels, + * but the resolved variant label might itself have been a function. + * If so, resolve. This can only have returned a valid target object. + */ + if (typeof definition === "function") { + const [current, velocity] = getValueState(visualElement); + definition = definition(custom !== undefined ? custom : props.custom, current, velocity); + } + return definition; + } + + const propEventHandlers = [ + "AnimationStart", + "AnimationComplete", + "Update", + "BeforeLayoutMeasure", + "LayoutMeasure", + "LayoutAnimationStart", + "LayoutAnimationComplete", + ]; + /** + * A VisualElement is an imperative abstraction around UI elements such as + * HTMLElement, SVGElement, Three.Object3D etc. + */ + class VisualElement { + /** + * This method takes React props and returns found MotionValues. For example, HTML + * MotionValues will be found within the style prop, whereas for Three.js within attribute arrays. + * + * This isn't an abstract method as it needs calling in the constructor, but it is + * intended to be one. + */ + scrapeMotionValuesFromProps(_props, _prevProps, _visualElement) { + return {}; + } + constructor({ parent, props, presenceContext, reducedMotionConfig, blockInitialAnimation, visualState, }, options = {}) { + /** + * A reference to the current underlying Instance, e.g. a HTMLElement + * or Three.Mesh etc. + */ + this.current = null; + /** + * A set containing references to this VisualElement's children. + */ + this.children = new Set(); + /** + * Determine what role this visual element should take in the variant tree. + */ + this.isVariantNode = false; + this.isControllingVariants = false; + /** + * Decides whether this VisualElement should animate in reduced motion + * mode. + * + * TODO: This is currently set on every individual VisualElement but feels + * like it could be set globally. + */ + this.shouldReduceMotion = null; + /** + * A map of all motion values attached to this visual element. Motion + * values are source of truth for any given animated value. A motion + * value might be provided externally by the component via props. + */ + this.values = new Map(); + this.KeyframeResolver = KeyframeResolver; + /** + * Cleanup functions for active features (hover/tap/exit etc) + */ + this.features = {}; + /** + * A map of every subscription that binds the provided or generated + * motion values onChange listeners to this visual element. + */ + this.valueSubscriptions = new Map(); + /** + * A reference to the previously-provided motion values as returned + * from scrapeMotionValuesFromProps. We use the keys in here to determine + * if any motion values need to be removed after props are updated. + */ + this.prevMotionValues = {}; + /** + * An object containing a SubscriptionManager for each active event. + */ + this.events = {}; + /** + * An object containing an unsubscribe function for each prop event subscription. + * For example, every "Update" event can have multiple subscribers via + * VisualElement.on(), but only one of those can be defined via the onUpdate prop. + */ + this.propEventSubscriptions = {}; + this.notifyUpdate = () => this.notify("Update", this.latestValues); + this.render = () => { + if (!this.current) + return; + this.triggerBuild(); + this.renderInstance(this.current, this.renderState, this.props.style, this.projection); + }; + this.renderScheduledAt = 0.0; + this.scheduleRender = () => { + const now = time.now(); + if (this.renderScheduledAt < now) { + this.renderScheduledAt = now; + frame.render(this.render, false, true); + } + }; + const { latestValues, renderState } = visualState; + this.latestValues = latestValues; + this.baseTarget = { ...latestValues }; + this.initialValues = props.initial ? { ...latestValues } : {}; + this.renderState = renderState; + this.parent = parent; + this.props = props; + this.presenceContext = presenceContext; + this.depth = parent ? parent.depth + 1 : 0; + this.reducedMotionConfig = reducedMotionConfig; + this.options = options; + this.blockInitialAnimation = Boolean(blockInitialAnimation); + this.isControllingVariants = isControllingVariants(props); + this.isVariantNode = isVariantNode(props); + if (this.isVariantNode) { + this.variantChildren = new Set(); + } + this.manuallyAnimateOnMount = Boolean(parent && parent.current); + /** + * Any motion values that are provided to the element when created + * aren't yet bound to the element, as this would technically be impure. + * However, we iterate through the motion values and set them to the + * initial values for this component. + * + * TODO: This is impure and we should look at changing this to run on mount. + * Doing so will break some tests but this isn't necessarily a breaking change, + * more a reflection of the test. + */ + const { willChange, ...initialMotionValues } = this.scrapeMotionValuesFromProps(props, {}, this); + for (const key in initialMotionValues) { + const value = initialMotionValues[key]; + if (latestValues[key] !== undefined && isMotionValue(value)) { + value.set(latestValues[key]); + } + } + } + mount(instance) { + this.current = instance; + visualElementStore.set(instance, this); + if (this.projection && !this.projection.instance) { + this.projection.mount(instance); + } + if (this.parent && this.isVariantNode && !this.isControllingVariants) { + this.removeFromVariantTree = this.parent.addVariantChild(this); + } + this.values.forEach((value, key) => this.bindToMotionValue(key, value)); + if (!hasReducedMotionListener.current) { + initPrefersReducedMotion(); + } + this.shouldReduceMotion = + this.reducedMotionConfig === "never" + ? false + : this.reducedMotionConfig === "always" + ? true + : prefersReducedMotion.current; + { + warnOnce(this.shouldReduceMotion !== true, "You have Reduced Motion enabled on your device. Animations may not appear as expected.", "reduced-motion-disabled"); + } + this.parent?.addChild(this); + this.update(this.props, this.presenceContext); + } + unmount() { + this.projection && this.projection.unmount(); + cancelFrame(this.notifyUpdate); + cancelFrame(this.render); + this.valueSubscriptions.forEach((remove) => remove()); + this.valueSubscriptions.clear(); + this.removeFromVariantTree && this.removeFromVariantTree(); + this.parent?.removeChild(this); + for (const key in this.events) { + this.events[key].clear(); + } + for (const key in this.features) { + const feature = this.features[key]; + if (feature) { + feature.unmount(); + feature.isMounted = false; + } + } + this.current = null; + } + addChild(child) { + this.children.add(child); + this.enteringChildren ?? (this.enteringChildren = new Set()); + this.enteringChildren.add(child); + } + removeChild(child) { + this.children.delete(child); + this.enteringChildren && this.enteringChildren.delete(child); + } + bindToMotionValue(key, value) { + if (this.valueSubscriptions.has(key)) { + this.valueSubscriptions.get(key)(); + } + const valueIsTransform = transformProps.has(key); + if (valueIsTransform && this.onBindTransform) { + this.onBindTransform(); + } + const removeOnChange = value.on("change", (latestValue) => { + this.latestValues[key] = latestValue; + this.props.onUpdate && frame.preRender(this.notifyUpdate); + if (valueIsTransform && this.projection) { + this.projection.isTransformDirty = true; + } + this.scheduleRender(); + }); + let removeSyncCheck; + if (window.MotionCheckAppearSync) { + removeSyncCheck = window.MotionCheckAppearSync(this, key, value); + } + this.valueSubscriptions.set(key, () => { + removeOnChange(); + if (removeSyncCheck) + removeSyncCheck(); + if (value.owner) + value.stop(); + }); + } + sortNodePosition(other) { + /** + * If these nodes aren't even of the same type we can't compare their depth. + */ + if (!this.current || + !this.sortInstanceNodePosition || + this.type !== other.type) { + return 0; + } + return this.sortInstanceNodePosition(this.current, other.current); + } + updateFeatures() { + let key = "animation"; + for (key in featureDefinitions) { + const featureDefinition = featureDefinitions[key]; + if (!featureDefinition) + continue; + const { isEnabled, Feature: FeatureConstructor } = featureDefinition; + /** + * If this feature is enabled but not active, make a new instance. + */ + if (!this.features[key] && + FeatureConstructor && + isEnabled(this.props)) { + this.features[key] = new FeatureConstructor(this); + } + /** + * If we have a feature, mount or update it. + */ + if (this.features[key]) { + const feature = this.features[key]; + if (feature.isMounted) { + feature.update(); + } + else { + feature.mount(); + feature.isMounted = true; + } + } + } + } + triggerBuild() { + this.build(this.renderState, this.latestValues, this.props); + } + /** + * Measure the current viewport box with or without transforms. + * Only measures axis-aligned boxes, rotate and skew must be manually + * removed with a re-render to work. + */ + measureViewportBox() { + return this.current + ? this.measureInstanceViewportBox(this.current, this.props) + : createBox(); + } + getStaticValue(key) { + return this.latestValues[key]; + } + setStaticValue(key, value) { + this.latestValues[key] = value; + } + /** + * Update the provided props. Ensure any newly-added motion values are + * added to our map, old ones removed, and listeners updated. + */ + update(props, presenceContext) { + if (props.transformTemplate || this.props.transformTemplate) { + this.scheduleRender(); + } + this.prevProps = this.props; + this.props = props; + this.prevPresenceContext = this.presenceContext; + this.presenceContext = presenceContext; + /** + * Update prop event handlers ie onAnimationStart, onAnimationComplete + */ + for (let i = 0; i < propEventHandlers.length; i++) { + const key = propEventHandlers[i]; + if (this.propEventSubscriptions[key]) { + this.propEventSubscriptions[key](); + delete this.propEventSubscriptions[key]; + } + const listenerName = ("on" + key); + const listener = props[listenerName]; + if (listener) { + this.propEventSubscriptions[key] = this.on(key, listener); + } + } + this.prevMotionValues = updateMotionValuesFromProps(this, this.scrapeMotionValuesFromProps(props, this.prevProps, this), this.prevMotionValues); + if (this.handleChildMotionValue) { + this.handleChildMotionValue(); + } + } + getProps() { + return this.props; + } + /** + * Returns the variant definition with a given name. + */ + getVariant(name) { + return this.props.variants ? this.props.variants[name] : undefined; + } + /** + * Returns the defined default transition on this component. + */ + getDefaultTransition() { + return this.props.transition; + } + getTransformPagePoint() { + return this.props.transformPagePoint; + } + getClosestVariantNode() { + return this.isVariantNode + ? this + : this.parent + ? this.parent.getClosestVariantNode() + : undefined; + } + /** + * Add a child visual element to our set of children. + */ + addVariantChild(child) { + const closestVariantNode = this.getClosestVariantNode(); + if (closestVariantNode) { + closestVariantNode.variantChildren && + closestVariantNode.variantChildren.add(child); + return () => closestVariantNode.variantChildren.delete(child); + } + } + /** + * Add a motion value and bind it to this visual element. + */ + addValue(key, value) { + // Remove existing value if it exists + const existingValue = this.values.get(key); + if (value !== existingValue) { + if (existingValue) + this.removeValue(key); + this.bindToMotionValue(key, value); + this.values.set(key, value); + this.latestValues[key] = value.get(); + } + } + /** + * Remove a motion value and unbind any active subscriptions. + */ + removeValue(key) { + this.values.delete(key); + const unsubscribe = this.valueSubscriptions.get(key); + if (unsubscribe) { + unsubscribe(); + this.valueSubscriptions.delete(key); + } + delete this.latestValues[key]; + this.removeValueFromRenderState(key, this.renderState); + } + /** + * Check whether we have a motion value for this key + */ + hasValue(key) { + return this.values.has(key); + } + getValue(key, defaultValue) { + if (this.props.values && this.props.values[key]) { + return this.props.values[key]; + } + let value = this.values.get(key); + if (value === undefined && defaultValue !== undefined) { + value = motionValue(defaultValue === null ? undefined : defaultValue, { owner: this }); + this.addValue(key, value); + } + return value; + } + /** + * If we're trying to animate to a previously unencountered value, + * we need to check for it in our state and as a last resort read it + * directly from the instance (which might have performance implications). + */ + readValue(key, target) { + let value = this.latestValues[key] !== undefined || !this.current + ? this.latestValues[key] + : this.getBaseTargetFromProps(this.props, key) ?? + this.readValueFromInstance(this.current, key, this.options); + if (value !== undefined && value !== null) { + if (typeof value === "string" && + (isNumericalString(value) || isZeroValueString(value))) { + // If this is a number read as a string, ie "0" or "200", convert it to a number + value = parseFloat(value); + } + else if (!findValueType(value) && complex.test(target)) { + value = getAnimatableNone(key, target); + } + this.setBaseTarget(key, isMotionValue(value) ? value.get() : value); + } + return isMotionValue(value) ? value.get() : value; + } + /** + * Set the base target to later animate back to. This is currently + * only hydrated on creation and when we first read a value. + */ + setBaseTarget(key, value) { + this.baseTarget[key] = value; + } + /** + * Find the base target for a value thats been removed from all animation + * props. + */ + getBaseTarget(key) { + const { initial } = this.props; + let valueFromInitial; + if (typeof initial === "string" || typeof initial === "object") { + const variant = resolveVariantFromProps(this.props, initial, this.presenceContext?.custom); + if (variant) { + valueFromInitial = variant[key]; + } + } + /** + * If this value still exists in the current initial variant, read that. + */ + if (initial && valueFromInitial !== undefined) { + return valueFromInitial; + } + /** + * Alternatively, if this VisualElement config has defined a getBaseTarget + * so we can read the value from an alternative source, try that. + */ + const target = this.getBaseTargetFromProps(this.props, key); + if (target !== undefined && !isMotionValue(target)) + return target; + /** + * If the value was initially defined on initial, but it doesn't any more, + * return undefined. Otherwise return the value as initially read from the DOM. + */ + return this.initialValues[key] !== undefined && + valueFromInitial === undefined + ? undefined + : this.baseTarget[key]; + } + on(eventName, callback) { + if (!this.events[eventName]) { + this.events[eventName] = new SubscriptionManager(); + } + return this.events[eventName].add(callback); + } + notify(eventName, ...args) { + if (this.events[eventName]) { + this.events[eventName].notify(...args); + } + } + scheduleRenderMicrotask() { + microtask.render(this.render); + } + } + + class DOMVisualElement extends VisualElement { + constructor() { + super(...arguments); + this.KeyframeResolver = DOMKeyframesResolver; + } + sortInstanceNodePosition(a, b) { + /** + * compareDocumentPosition returns a bitmask, by using the bitwise & + * we're returning true if 2 in that bitmask is set to true. 2 is set + * to true if b preceeds a. + */ + return a.compareDocumentPosition(b) & 2 ? 1 : -1; + } + getBaseTargetFromProps(props, key) { + return props.style + ? props.style[key] + : undefined; + } + removeValueFromRenderState(key, { vars, style }) { + delete vars[key]; + delete style[key]; + } + handleChildMotionValue() { + if (this.childSubscription) { + this.childSubscription(); + delete this.childSubscription; + } + const { children } = this.props; + if (isMotionValue(children)) { + this.childSubscription = children.on("change", (latest) => { + if (this.current) { + this.current.textContent = `${latest}`; + } + }); + } + } + } + + const translateAlias = { + x: "translateX", + y: "translateY", + z: "translateZ", + transformPerspective: "perspective", + }; + const numTransforms = transformPropOrder.length; + /** + * Build a CSS transform style from individual x/y/scale etc properties. + * + * This outputs with a default order of transforms/scales/rotations, this can be customised by + * providing a transformTemplate function. + */ + function buildTransform(latestValues, transform, transformTemplate) { + // The transform string we're going to build into. + let transformString = ""; + let transformIsDefault = true; + /** + * Loop over all possible transforms in order, adding the ones that + * are present to the transform string. + */ + for (let i = 0; i < numTransforms; i++) { + const key = transformPropOrder[i]; + const value = latestValues[key]; + if (value === undefined) + continue; + let valueIsDefault = true; + if (typeof value === "number") { + valueIsDefault = value === (key.startsWith("scale") ? 1 : 0); + } + else { + valueIsDefault = parseFloat(value) === 0; + } + if (!valueIsDefault || transformTemplate) { + const valueAsType = getValueAsType(value, numberValueTypes[key]); + if (!valueIsDefault) { + transformIsDefault = false; + const transformName = translateAlias[key] || key; + transformString += `${transformName}(${valueAsType}) `; + } + if (transformTemplate) { + transform[key] = valueAsType; + } + } + } + transformString = transformString.trim(); + // If we have a custom `transform` template, pass our transform values and + // generated transformString to that before returning + if (transformTemplate) { + transformString = transformTemplate(transform, transformIsDefault ? "" : transformString); + } + else if (transformIsDefault) { + transformString = "none"; + } + return transformString; + } + + function buildHTMLStyles(state, latestValues, transformTemplate) { + const { style, vars, transformOrigin } = state; + // Track whether we encounter any transform or transformOrigin values. + let hasTransform = false; + let hasTransformOrigin = false; + /** + * Loop over all our latest animated values and decide whether to handle them + * as a style or CSS variable. + * + * Transforms and transform origins are kept separately for further processing. + */ + for (const key in latestValues) { + const value = latestValues[key]; + if (transformProps.has(key)) { + // If this is a transform, flag to enable further transform processing + hasTransform = true; + continue; + } + else if (isCSSVariableName(key)) { + vars[key] = value; + continue; + } + else { + // Convert the value to its default value type, ie 0 -> "0px" + const valueAsType = getValueAsType(value, numberValueTypes[key]); + if (key.startsWith("origin")) { + // If this is a transform origin, flag and enable further transform-origin processing + hasTransformOrigin = true; + transformOrigin[key] = + valueAsType; + } + else { + style[key] = valueAsType; + } + } + } + if (!latestValues.transform) { + if (hasTransform || transformTemplate) { + style.transform = buildTransform(latestValues, state.transform, transformTemplate); + } + else if (style.transform) { + /** + * If we have previously created a transform but currently don't have any, + * reset transform style to none. + */ + style.transform = "none"; + } + } + /** + * Build a transformOrigin style. Uses the same defaults as the browser for + * undefined origins. + */ + if (hasTransformOrigin) { + const { originX = "50%", originY = "50%", originZ = 0, } = transformOrigin; + style.transformOrigin = `${originX} ${originY} ${originZ}`; + } + } + + function renderHTML(element, { style, vars }, styleProp, projection) { + const elementStyle = element.style; + let key; + for (key in style) { + // CSSStyleDeclaration has [index: number]: string; in the types, so we use that as key type. + elementStyle[key] = style[key]; + } + // Write projection styles directly to element style + projection?.applyProjectionStyles(elementStyle, styleProp); + for (key in vars) { + // Loop over any CSS variables and assign those. + // They can only be assigned using `setProperty`. + elementStyle.setProperty(key, vars[key]); + } + } + + function isForcedMotionValue(key, { layout, layoutId }) { + return (transformProps.has(key) || + key.startsWith("origin") || + ((layout || layoutId !== undefined) && + (!!scaleCorrectors[key] || key === "opacity"))); + } + + function scrapeMotionValuesFromProps$1(props, prevProps, visualElement) { + const { style } = props; + const newValues = {}; + for (const key in style) { + if (isMotionValue(style[key]) || + (prevProps.style && + isMotionValue(prevProps.style[key])) || + isForcedMotionValue(key, props) || + visualElement?.getValue(key)?.liveStyle !== undefined) { + newValues[key] = style[key]; + } + } + return newValues; + } + + function getComputedStyle$1(element) { + return window.getComputedStyle(element); + } + class HTMLVisualElement extends DOMVisualElement { + constructor() { + super(...arguments); + this.type = "html"; + this.renderInstance = renderHTML; + } + readValueFromInstance(instance, key) { + if (transformProps.has(key)) { + return this.projection?.isProjecting + ? defaultTransformValue(key) + : readTransformValue(instance, key); + } + else { + const computedStyle = getComputedStyle$1(instance); + const value = (isCSSVariableName(key) + ? computedStyle.getPropertyValue(key) + : computedStyle[key]) || 0; + return typeof value === "string" ? value.trim() : value; + } + } + measureInstanceViewportBox(instance, { transformPagePoint }) { + return measureViewportBox(instance, transformPagePoint); + } + build(renderState, latestValues, props) { + buildHTMLStyles(renderState, latestValues, props.transformTemplate); + } + scrapeMotionValuesFromProps(props, prevProps, visualElement) { + return scrapeMotionValuesFromProps$1(props, prevProps, visualElement); + } + } + + function useIsMounted() { + const isMounted = React$1.useRef(false); + useIsomorphicLayoutEffect(() => { + isMounted.current = true; + return () => { + isMounted.current = false; + }; + }, []); + return isMounted; + } + + function useForceUpdate() { + const isMounted = useIsMounted(); + const [forcedRenderCount, setForcedRenderCount] = React$1.useState(0); + const forceRender = React$1.useCallback(() => { + isMounted.current && setForcedRenderCount(forcedRenderCount + 1); + }, [forcedRenderCount]); + /** + * Defer this to the end of the next animation frame in case there are multiple + * synchronous calls. + */ + const deferredForceRender = React$1.useCallback(() => frame.postRender(forceRender), [forceRender]); + return [deferredForceRender, forcedRenderCount]; + } + + const shouldInheritGroup = (inherit) => inherit === true; + const shouldInheritId = (inherit) => shouldInheritGroup(inherit === true) || inherit === "id"; + const LayoutGroup = ({ children, id, inherit = true }) => { + const layoutGroupContext = React$1.useContext(LayoutGroupContext); + const deprecatedLayoutGroupContext = React$1.useContext(DeprecatedLayoutGroupContext); + const [forceRender, key] = useForceUpdate(); + const context = React$1.useRef(null); + const upstreamId = layoutGroupContext.id || deprecatedLayoutGroupContext; + if (context.current === null) { + if (shouldInheritId(inherit) && upstreamId) { + id = id ? upstreamId + "-" + id : upstreamId; + } + context.current = { + id, + group: shouldInheritGroup(inherit) + ? layoutGroupContext.group || nodeGroup() + : nodeGroup(), + }; + } + const memoizedContext = React$1.useMemo(() => ({ ...context.current, forceRender }), [key]); + return (jsx(LayoutGroupContext.Provider, { value: memoizedContext, children: children })); + }; + + const LazyContext = React$1.createContext({ strict: false }); + + function loadFeatures(features) { + for (const key in features) { + featureDefinitions[key] = { + ...featureDefinitions[key], + ...features[key], + }; + } + } + + /** + * Used in conjunction with the `m` component to reduce bundle size. + * + * `m` is a version of the `motion` component that only loads functionality + * critical for the initial render. + * + * `LazyMotion` can then be used to either synchronously or asynchronously + * load animation and gesture support. + * + * ```jsx + * // Synchronous loading + * import { LazyMotion, m, domAnimation } from "framer-motion" + * + * function App() { + * return ( + * + * + * + * ) + * } + * + * // Asynchronous loading + * import { LazyMotion, m } from "framer-motion" + * + * function App() { + * return ( + * import('./path/to/domAnimation')}> + * + * + * ) + * } + * ``` + * + * @public + */ + function LazyMotion({ children, features, strict = false }) { + const [, setIsLoaded] = React$1.useState(!isLazyBundle(features)); + const loadedRenderer = React$1.useRef(undefined); + /** + * If this is a synchronous load, load features immediately + */ + if (!isLazyBundle(features)) { + const { renderer, ...loadedFeatures } = features; + loadedRenderer.current = renderer; + loadFeatures(loadedFeatures); + } + React$1.useEffect(() => { + if (isLazyBundle(features)) { + features().then(({ renderer, ...loadedFeatures }) => { + loadFeatures(loadedFeatures); + loadedRenderer.current = renderer; + setIsLoaded(true); + }); + } + }, []); + return (jsx(LazyContext.Provider, { value: { renderer: loadedRenderer.current, strict }, children: children })); + } + function isLazyBundle(features) { + return typeof features === "function"; + } + + /** + * A list of all valid MotionProps. + * + * @privateRemarks + * This doesn't throw if a `MotionProp` name is missing - it should. + */ + const validMotionProps = new Set([ + "animate", + "exit", + "variants", + "initial", + "style", + "values", + "variants", + "transition", + "transformTemplate", + "custom", + "inherit", + "onBeforeLayoutMeasure", + "onAnimationStart", + "onAnimationComplete", + "onUpdate", + "onDragStart", + "onDrag", + "onDragEnd", + "onMeasureDragConstraints", + "onDirectionLock", + "onDragTransitionEnd", + "_dragX", + "_dragY", + "onHoverStart", + "onHoverEnd", + "onViewportEnter", + "onViewportLeave", + "globalTapTarget", + "ignoreStrict", + "viewport", + ]); + /** + * Check whether a prop name is a valid `MotionProp` key. + * + * @param key - Name of the property to check + * @returns `true` is key is a valid `MotionProp`. + * + * @public + */ + function isValidMotionProp(key) { + return (key.startsWith("while") || + (key.startsWith("drag") && key !== "draggable") || + key.startsWith("layout") || + key.startsWith("onTap") || + key.startsWith("onPan") || + key.startsWith("onLayout") || + validMotionProps.has(key)); + } + + let shouldForward = (key) => !isValidMotionProp(key); + function loadExternalIsValidProp(isValidProp) { + if (typeof isValidProp !== "function") + return; + // Explicitly filter our events + shouldForward = (key) => key.startsWith("on") ? !isValidMotionProp(key) : isValidProp(key); + } + /** + * Emotion and Styled Components both allow users to pass through arbitrary props to their components + * to dynamically generate CSS. They both use the `@emotion/is-prop-valid` package to determine which + * of these should be passed to the underlying DOM node. + * + * However, when styling a Motion component `styled(motion.div)`, both packages pass through *all* props + * as it's seen as an arbitrary component rather than a DOM node. Motion only allows arbitrary props + * passed through the `custom` prop so it doesn't *need* the payload or computational overhead of + * `@emotion/is-prop-valid`, however to fix this problem we need to use it. + * + * By making it an optionalDependency we can offer this functionality only in the situations where it's + * actually required. + */ + try { + /** + * We attempt to import this package but require won't be defined in esm environments, in that case + * isPropValid will have to be provided via `MotionContext`. In a 6.0.0 this should probably be removed + * in favour of explicit injection. + */ + loadExternalIsValidProp(require("@emotion/is-prop-valid").default); + } + catch { + // We don't need to actually do anything here - the fallback is the existing `isPropValid`. + } + function filterProps(props, isDom, forwardMotionProps) { + const filteredProps = {}; + for (const key in props) { + /** + * values is considered a valid prop by Emotion, so if it's present + * this will be rendered out to the DOM unless explicitly filtered. + * + * We check the type as it could be used with the `feColorMatrix` + * element, which we support. + */ + if (key === "values" && typeof props.values === "object") + continue; + if (shouldForward(key) || + (forwardMotionProps === true && isValidMotionProp(key)) || + (!isDom && !isValidMotionProp(key)) || + // If trying to use native HTML drag events, forward drag listeners + (props["draggable"] && + key.startsWith("onDrag"))) { + filteredProps[key] = + props[key]; + } + } + return filteredProps; + } + + /** + * `MotionConfig` is used to set configuration options for all children `motion` components. + * + * ```jsx + * import { motion, MotionConfig } from "framer-motion" + * + * export function App() { + * return ( + * + * + * + * ) + * } + * ``` + * + * @public + */ + function MotionConfig({ children, isValidProp, ...config }) { + isValidProp && loadExternalIsValidProp(isValidProp); + /** + * Inherit props from any parent MotionConfig components + */ + config = { ...React$1.useContext(MotionConfigContext), ...config }; + /** + * Don't allow isStatic to change between renders as it affects how many hooks + * motion components fire. + */ + config.isStatic = useConstant(() => config.isStatic); + /** + * Creating a new config context object will re-render every `motion` component + * every time it renders. So we only want to create a new one sparingly. + */ + const context = React$1.useMemo(() => config, [ + JSON.stringify(config.transition), + config.transformPagePoint, + config.reducedMotion, + ]); + return (jsx(MotionConfigContext.Provider, { value: context, children: children })); + } + + const ReorderContext = React$1.createContext(null); + + const dashKeys = { + offset: "stroke-dashoffset", + array: "stroke-dasharray", + }; + const camelKeys = { + offset: "strokeDashoffset", + array: "strokeDasharray", + }; + /** + * Build SVG path properties. Uses the path's measured length to convert + * our custom pathLength, pathSpacing and pathOffset into stroke-dashoffset + * and stroke-dasharray attributes. + * + * This function is mutative to reduce per-frame GC. + */ + function buildSVGPath(attrs, length, spacing = 1, offset = 0, useDashCase = true) { + // Normalise path length by setting SVG attribute pathLength to 1 + attrs.pathLength = 1; + // We use dash case when setting attributes directly to the DOM node and camel case + // when defining props on a React component. + const keys = useDashCase ? dashKeys : camelKeys; + // Build the dash offset + attrs[keys.offset] = px.transform(-offset); + // Build the dash array + const pathLength = px.transform(length); + const pathSpacing = px.transform(spacing); + attrs[keys.array] = `${pathLength} ${pathSpacing}`; + } + + /** + * Build SVG visual attributes, like cx and style.transform + */ + function buildSVGAttrs(state, { attrX, attrY, attrScale, pathLength, pathSpacing = 1, pathOffset = 0, + // This is object creation, which we try to avoid per-frame. + ...latest }, isSVGTag, transformTemplate, styleProp) { + buildHTMLStyles(state, latest, transformTemplate); + /** + * For svg tags we just want to make sure viewBox is animatable and treat all the styles + * as normal HTML tags. + */ + if (isSVGTag) { + if (state.style.viewBox) { + state.attrs.viewBox = state.style.viewBox; + } + return; + } + state.attrs = state.style; + state.style = {}; + const { attrs, style } = state; + /** + * However, we apply transforms as CSS transforms. + * So if we detect a transform, transformOrigin we take it from attrs and copy it into style. + */ + if (attrs.transform) { + style.transform = attrs.transform; + delete attrs.transform; + } + if (style.transform || attrs.transformOrigin) { + style.transformOrigin = attrs.transformOrigin ?? "50% 50%"; + delete attrs.transformOrigin; + } + if (style.transform) { + /** + * SVG's element transform-origin uses its own median as a reference. + * Therefore, transformBox becomes a fill-box + */ + style.transformBox = styleProp?.transformBox ?? "fill-box"; + delete attrs.transformBox; + } + // Render attrX/attrY/attrScale as attributes + if (attrX !== undefined) + attrs.x = attrX; + if (attrY !== undefined) + attrs.y = attrY; + if (attrScale !== undefined) + attrs.scale = attrScale; + // Build SVG path if one has been defined + if (pathLength !== undefined) { + buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false); + } + } + + /** + * A set of attribute names that are always read/written as camel case. + */ + const camelCaseAttributes = new Set([ + "baseFrequency", + "diffuseConstant", + "kernelMatrix", + "kernelUnitLength", + "keySplines", + "keyTimes", + "limitingConeAngle", + "markerHeight", + "markerWidth", + "numOctaves", + "targetX", + "targetY", + "surfaceScale", + "specularConstant", + "specularExponent", + "stdDeviation", + "tableValues", + "viewBox", + "gradientTransform", + "pathLength", + "startOffset", + "textLength", + "lengthAdjust", + ]); + + const isSVGTag = (tag) => typeof tag === "string" && tag.toLowerCase() === "svg"; + + function renderSVG(element, renderState, _styleProp, projection) { + renderHTML(element, renderState, undefined, projection); + for (const key in renderState.attrs) { + element.setAttribute(!camelCaseAttributes.has(key) ? camelToDash(key) : key, renderState.attrs[key]); + } + } + + function scrapeMotionValuesFromProps(props, prevProps, visualElement) { + const newValues = scrapeMotionValuesFromProps$1(props, prevProps, visualElement); + for (const key in props) { + if (isMotionValue(props[key]) || + isMotionValue(prevProps[key])) { + const targetKey = transformPropOrder.indexOf(key) !== -1 + ? "attr" + key.charAt(0).toUpperCase() + key.substring(1) + : key; + newValues[targetKey] = props[key]; + } + } + return newValues; + } + + class SVGVisualElement extends DOMVisualElement { + constructor() { + super(...arguments); + this.type = "svg"; + this.isSVGTag = false; + this.measureInstanceViewportBox = createBox; + } + getBaseTargetFromProps(props, key) { + return props[key]; + } + readValueFromInstance(instance, key) { + if (transformProps.has(key)) { + const defaultType = getDefaultValueType(key); + return defaultType ? defaultType.default || 0 : 0; + } + key = !camelCaseAttributes.has(key) ? camelToDash(key) : key; + return instance.getAttribute(key); + } + scrapeMotionValuesFromProps(props, prevProps, visualElement) { + return scrapeMotionValuesFromProps(props, prevProps, visualElement); + } + build(renderState, latestValues, props) { + buildSVGAttrs(renderState, latestValues, this.isSVGTag, props.transformTemplate, props.style); + } + renderInstance(instance, renderState, styleProp, projection) { + renderSVG(instance, renderState, styleProp, projection); + } + mount(instance) { + this.isSVGTag = isSVGTag(instance.tagName); + super.mount(instance); + } + } + + /** + * We keep these listed separately as we use the lowercase tag names as part + * of the runtime bundle to detect SVG components + */ + const lowercaseSVGElements = [ + "animate", + "circle", + "defs", + "desc", + "ellipse", + "g", + "image", + "line", + "filter", + "marker", + "mask", + "metadata", + "path", + "pattern", + "polygon", + "polyline", + "rect", + "stop", + "switch", + "symbol", + "svg", + "text", + "tspan", + "use", + "view", + ]; + + function isSVGComponent(Component) { + if ( + /** + * If it's not a string, it's a custom React component. Currently we only support + * HTML custom React components. + */ + typeof Component !== "string" || + /** + * If it contains a dash, the element is a custom HTML webcomponent. + */ + Component.includes("-")) { + return false; + } + else if ( + /** + * If it's in our list of lowercase SVG tags, it's an SVG component + */ + lowercaseSVGElements.indexOf(Component) > -1 || + /** + * If it contains a capital letter, it's an SVG component + */ + /[A-Z]/u.test(Component)) { + return true; + } + return false; + } + + const createDomVisualElement = (Component, options) => { + return isSVGComponent(Component) + ? new SVGVisualElement(options) + : new HTMLVisualElement(options, { + allowProjection: Component !== React$1.Fragment, + }); + }; + + const MotionContext = /* @__PURE__ */ React$1.createContext({}); + + function getCurrentTreeVariants(props, context) { + if (isControllingVariants(props)) { + const { initial, animate } = props; + return { + initial: initial === false || isVariantLabel(initial) + ? initial + : undefined, + animate: isVariantLabel(animate) ? animate : undefined, + }; + } + return props.inherit !== false ? context : {}; + } + + function useCreateMotionContext(props) { + const { initial, animate } = getCurrentTreeVariants(props, React$1.useContext(MotionContext)); + return React$1.useMemo(() => ({ initial, animate }), [variantLabelsAsDependency(initial), variantLabelsAsDependency(animate)]); + } + function variantLabelsAsDependency(prop) { + return Array.isArray(prop) ? prop.join(" ") : prop; + } + + const createHtmlRenderState = () => ({ + style: {}, + transform: {}, + transformOrigin: {}, + vars: {}, + }); + + function copyRawValuesOnly(target, source, props) { + for (const key in source) { + if (!isMotionValue(source[key]) && !isForcedMotionValue(key, props)) { + target[key] = source[key]; + } + } + } + function useInitialMotionValues({ transformTemplate }, visualState) { + return React$1.useMemo(() => { + const state = createHtmlRenderState(); + buildHTMLStyles(state, visualState, transformTemplate); + return Object.assign({}, state.vars, state.style); + }, [visualState]); + } + function useStyle(props, visualState) { + const styleProp = props.style || {}; + const style = {}; + /** + * Copy non-Motion Values straight into style + */ + copyRawValuesOnly(style, styleProp, props); + Object.assign(style, useInitialMotionValues(props, visualState)); + return style; + } + function useHTMLProps(props, visualState) { + // The `any` isn't ideal but it is the type of createElement props argument + const htmlProps = {}; + const style = useStyle(props, visualState); + if (props.drag && props.dragListener !== false) { + // Disable the ghost element when a user drags + htmlProps.draggable = false; + // Disable text selection + style.userSelect = + style.WebkitUserSelect = + style.WebkitTouchCallout = + "none"; + // Disable scrolling on the draggable direction + style.touchAction = + props.drag === true + ? "none" + : `pan-${props.drag === "x" ? "y" : "x"}`; + } + if (props.tabIndex === undefined && + (props.onTap || props.onTapStart || props.whileTap)) { + htmlProps.tabIndex = 0; + } + htmlProps.style = style; + return htmlProps; + } + + const createSvgRenderState = () => ({ + ...createHtmlRenderState(), + attrs: {}, + }); + + function useSVGProps(props, visualState, _isStatic, Component) { + const visualProps = React$1.useMemo(() => { + const state = createSvgRenderState(); + buildSVGAttrs(state, visualState, isSVGTag(Component), props.transformTemplate, props.style); + return { + ...state.attrs, + style: { ...state.style }, + }; + }, [visualState]); + if (props.style) { + const rawStyles = {}; + copyRawValuesOnly(rawStyles, props.style, props); + visualProps.style = { ...rawStyles, ...visualProps.style }; + } + return visualProps; + } + + function useRender(Component, props, ref, { latestValues, }, isStatic, forwardMotionProps = false) { + const useVisualProps = isSVGComponent(Component) + ? useSVGProps + : useHTMLProps; + const visualProps = useVisualProps(props, latestValues, isStatic, Component); + const filteredProps = filterProps(props, typeof Component === "string", forwardMotionProps); + const elementProps = Component !== React$1.Fragment ? { ...filteredProps, ...visualProps, ref } : {}; + /** + * If component has been handed a motion value as its child, + * memoise its initial value and render that. Subsequent updates + * will be handled by the onChange handler + */ + const { children } = props; + const renderedChildren = React$1.useMemo(() => (isMotionValue(children) ? children.get() : children), [children]); + return React$1.createElement(Component, { + ...elementProps, + children: renderedChildren, + }); + } + + function makeState({ scrapeMotionValuesFromProps, createRenderState, }, props, context, presenceContext) { + const state = { + latestValues: makeLatestValues(props, context, presenceContext, scrapeMotionValuesFromProps), + renderState: createRenderState(), + }; + return state; + } + function makeLatestValues(props, context, presenceContext, scrapeMotionValues) { + const values = {}; + const motionValues = scrapeMotionValues(props, {}); + for (const key in motionValues) { + values[key] = resolveMotionValue(motionValues[key]); + } + let { initial, animate } = props; + const isControllingVariants$1 = isControllingVariants(props); + const isVariantNode$1 = isVariantNode(props); + if (context && + isVariantNode$1 && + !isControllingVariants$1 && + props.inherit !== false) { + if (initial === undefined) + initial = context.initial; + if (animate === undefined) + animate = context.animate; + } + let isInitialAnimationBlocked = presenceContext + ? presenceContext.initial === false + : false; + isInitialAnimationBlocked = isInitialAnimationBlocked || initial === false; + const variantToSet = isInitialAnimationBlocked ? animate : initial; + if (variantToSet && + typeof variantToSet !== "boolean" && + !isAnimationControls(variantToSet)) { + const list = Array.isArray(variantToSet) ? variantToSet : [variantToSet]; + for (let i = 0; i < list.length; i++) { + const resolved = resolveVariantFromProps(props, list[i]); + if (resolved) { + const { transitionEnd, transition, ...target } = resolved; + for (const key in target) { + let valueTarget = target[key]; + if (Array.isArray(valueTarget)) { + /** + * Take final keyframe if the initial animation is blocked because + * we want to initialise at the end of that blocked animation. + */ + const index = isInitialAnimationBlocked + ? valueTarget.length - 1 + : 0; + valueTarget = valueTarget[index]; + } + if (valueTarget !== null) { + values[key] = valueTarget; + } + } + for (const key in transitionEnd) { + values[key] = transitionEnd[key]; + } + } + } + } + return values; + } + const makeUseVisualState = (config) => (props, isStatic) => { + const context = React$1.useContext(MotionContext); + const presenceContext = React$1.useContext(PresenceContext); + const make = () => makeState(config, props, context, presenceContext); + return isStatic ? make() : useConstant(make); + }; + + const useHTMLVisualState = /*@__PURE__*/ makeUseVisualState({ + scrapeMotionValuesFromProps: scrapeMotionValuesFromProps$1, + createRenderState: createHtmlRenderState, + }); + + const useSVGVisualState = /*@__PURE__*/ makeUseVisualState({ + scrapeMotionValuesFromProps: scrapeMotionValuesFromProps, + createRenderState: createSvgRenderState, + }); + + const motionComponentSymbol = Symbol.for("motionComponentSymbol"); + + function isRefObject(ref) { + return (ref && + typeof ref === "object" && + Object.prototype.hasOwnProperty.call(ref, "current")); + } + + /** + * Creates a ref function that, when called, hydrates the provided + * external ref and VisualElement. + */ + function useMotionRef(visualState, visualElement, externalRef) { + return React$1.useCallback((instance) => { + if (instance) { + visualState.onMount && visualState.onMount(instance); + } + if (visualElement) { + if (instance) { + visualElement.mount(instance); + } + else { + visualElement.unmount(); + } + } + if (externalRef) { + if (typeof externalRef === "function") { + externalRef(instance); + } + else if (isRefObject(externalRef)) { + externalRef.current = instance; + } + } + }, + /** + * Only pass a new ref callback to React if we've received a visual element + * factory. Otherwise we'll be mounting/remounting every time externalRef + * or other dependencies change. + */ + [visualElement]); + } + + /** + * Internal, exported only for usage in Framer + */ + const SwitchLayoutGroupContext = React$1.createContext({}); + + function useVisualElement(Component, visualState, props, createVisualElement, ProjectionNodeConstructor) { + const { visualElement: parent } = React$1.useContext(MotionContext); + const lazyContext = React$1.useContext(LazyContext); + const presenceContext = React$1.useContext(PresenceContext); + const reducedMotionConfig = React$1.useContext(MotionConfigContext).reducedMotion; + const visualElementRef = React$1.useRef(null); + /** + * If we haven't preloaded a renderer, check to see if we have one lazy-loaded + */ + createVisualElement = + createVisualElement || + lazyContext.renderer; + if (!visualElementRef.current && createVisualElement) { + visualElementRef.current = createVisualElement(Component, { + visualState, + parent, + props, + presenceContext, + blockInitialAnimation: presenceContext + ? presenceContext.initial === false + : false, + reducedMotionConfig, + }); + } + const visualElement = visualElementRef.current; + /** + * Load Motion gesture and animation features. These are rendered as renderless + * components so each feature can optionally make use of React lifecycle methods. + */ + const initialLayoutGroupConfig = React$1.useContext(SwitchLayoutGroupContext); + if (visualElement && + !visualElement.projection && + ProjectionNodeConstructor && + (visualElement.type === "html" || visualElement.type === "svg")) { + createProjectionNode(visualElementRef.current, props, ProjectionNodeConstructor, initialLayoutGroupConfig); + } + const isMounted = React$1.useRef(false); + React$1.useInsertionEffect(() => { + /** + * Check the component has already mounted before calling + * `update` unnecessarily. This ensures we skip the initial update. + */ + if (visualElement && isMounted.current) { + visualElement.update(props, presenceContext); + } + }); + /** + * Cache this value as we want to know whether HandoffAppearAnimations + * was present on initial render - it will be deleted after this. + */ + const optimisedAppearId = props[optimizedAppearDataAttribute]; + const wantsHandoff = React$1.useRef(Boolean(optimisedAppearId) && + !window.MotionHandoffIsComplete?.(optimisedAppearId) && + window.MotionHasOptimisedAnimation?.(optimisedAppearId)); + useIsomorphicLayoutEffect(() => { + if (!visualElement) + return; + isMounted.current = true; + window.MotionIsMounted = true; + visualElement.updateFeatures(); + visualElement.scheduleRenderMicrotask(); + /** + * Ideally this function would always run in a useEffect. + * + * However, if we have optimised appear animations to handoff from, + * it needs to happen synchronously to ensure there's no flash of + * incorrect styles in the event of a hydration error. + * + * So if we detect a situtation where optimised appear animations + * are running, we use useLayoutEffect to trigger animations. + */ + if (wantsHandoff.current && visualElement.animationState) { + visualElement.animationState.animateChanges(); + } + }); + React$1.useEffect(() => { + if (!visualElement) + return; + if (!wantsHandoff.current && visualElement.animationState) { + visualElement.animationState.animateChanges(); + } + if (wantsHandoff.current) { + // This ensures all future calls to animateChanges() in this component will run in useEffect + queueMicrotask(() => { + window.MotionHandoffMarkAsComplete?.(optimisedAppearId); + }); + wantsHandoff.current = false; + } + /** + * Now we've finished triggering animations for this element we + * can wipe the enteringChildren set for the next render. + */ + visualElement.enteringChildren = undefined; + }); + return visualElement; + } + function createProjectionNode(visualElement, props, ProjectionNodeConstructor, initialPromotionConfig) { + const { layoutId, layout, drag, dragConstraints, layoutScroll, layoutRoot, layoutCrossfade, } = props; + visualElement.projection = new ProjectionNodeConstructor(visualElement.latestValues, props["data-framer-portal-id"] + ? undefined + : getClosestProjectingNode(visualElement.parent)); + visualElement.projection.setOptions({ + layoutId, + layout, + alwaysMeasureLayout: Boolean(drag) || (dragConstraints && isRefObject(dragConstraints)), + visualElement, + /** + * TODO: Update options in an effect. This could be tricky as it'll be too late + * to update by the time layout animations run. + * We also need to fix this safeToRemove by linking it up to the one returned by usePresence, + * ensuring it gets called if there's no potential layout animations. + * + */ + animationType: typeof layout === "string" ? layout : "both", + initialPromotionConfig, + crossfade: layoutCrossfade, + layoutScroll, + layoutRoot, + }); + } + function getClosestProjectingNode(visualElement) { + if (!visualElement) + return undefined; + return visualElement.options.allowProjection !== false + ? visualElement.projection + : getClosestProjectingNode(visualElement.parent); + } + + /** + * Create a `motion` component. + * + * This function accepts a Component argument, which can be either a string (ie "div" + * for `motion.div`), or an actual React component. + * + * Alongside this is a config option which provides a way of rendering the provided + * component "offline", or outside the React render cycle. + */ + function createMotionComponent(Component, { forwardMotionProps = false } = {}, preloadedFeatures, createVisualElement) { + preloadedFeatures && loadFeatures(preloadedFeatures); + const useVisualState = isSVGComponent(Component) + ? useSVGVisualState + : useHTMLVisualState; + function MotionDOMComponent(props, externalRef) { + /** + * If we need to measure the element we load this functionality in a + * separate class component in order to gain access to getSnapshotBeforeUpdate. + */ + let MeasureLayout; + const configAndProps = { + ...React$1.useContext(MotionConfigContext), + ...props, + layoutId: useLayoutId(props), + }; + const { isStatic } = configAndProps; + const context = useCreateMotionContext(props); + const visualState = useVisualState(props, isStatic); + if (!isStatic && isBrowser) { + useStrictMode(configAndProps, preloadedFeatures); + const layoutProjection = getProjectionFunctionality(configAndProps); + MeasureLayout = layoutProjection.MeasureLayout; + /** + * Create a VisualElement for this component. A VisualElement provides a common + * interface to renderer-specific APIs (ie DOM/Three.js etc) as well as + * providing a way of rendering to these APIs outside of the React render loop + * for more performant animations and interactions + */ + context.visualElement = useVisualElement(Component, visualState, configAndProps, createVisualElement, layoutProjection.ProjectionNode); + } + /** + * The mount order and hierarchy is specific to ensure our element ref + * is hydrated by the time features fire their effects. + */ + return (jsxs(MotionContext.Provider, { value: context, children: [MeasureLayout && context.visualElement ? (jsx(MeasureLayout, { visualElement: context.visualElement, ...configAndProps })) : null, useRender(Component, props, useMotionRef(visualState, context.visualElement, externalRef), visualState, isStatic, forwardMotionProps)] })); + } + MotionDOMComponent.displayName = `motion.${typeof Component === "string" + ? Component + : `create(${Component.displayName ?? Component.name ?? ""})`}`; + const ForwardRefMotionComponent = React$1.forwardRef(MotionDOMComponent); + ForwardRefMotionComponent[motionComponentSymbol] = Component; + return ForwardRefMotionComponent; + } + function useLayoutId({ layoutId }) { + const layoutGroupId = React$1.useContext(LayoutGroupContext).id; + return layoutGroupId && layoutId !== undefined + ? layoutGroupId + "-" + layoutId + : layoutId; + } + function useStrictMode(configAndProps, preloadedFeatures) { + const isStrict = React$1.useContext(LazyContext).strict; + /** + * If we're in development mode, check to make sure we're not rendering a motion component + * as a child of LazyMotion, as this will break the file-size benefits of using it. + */ + if (preloadedFeatures && + isStrict) { + const strictMessage = "You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead."; + configAndProps.ignoreStrict + ? exports.warning(false, strictMessage, "lazy-strict-mode") + : exports.invariant(false, strictMessage, "lazy-strict-mode"); + } + } + function getProjectionFunctionality(props) { + const { drag, layout } = featureDefinitions; + if (!drag && !layout) + return {}; + const combined = { ...drag, ...layout }; + return { + MeasureLayout: drag?.isEnabled(props) || layout?.isEnabled(props) + ? combined.MeasureLayout + : undefined, + ProjectionNode: combined.ProjectionNode, + }; + } + + function createMotionProxy(preloadedFeatures, createVisualElement) { + if (typeof Proxy === "undefined") { + return createMotionComponent; + } + /** + * A cache of generated `motion` components, e.g `motion.div`, `motion.input` etc. + * Rather than generating them anew every render. + */ + const componentCache = new Map(); + const factory = (Component, options) => { + return createMotionComponent(Component, options, preloadedFeatures, createVisualElement); + }; + /** + * Support for deprecated`motion(Component)` pattern + */ + const deprecatedFactoryFunction = (Component, options) => { + { + warnOnce(false, "motion() is deprecated. Use motion.create() instead."); + } + return factory(Component, options); + }; + return new Proxy(deprecatedFactoryFunction, { + /** + * Called when `motion` is referenced with a prop: `motion.div`, `motion.input` etc. + * The prop name is passed through as `key` and we can use that to generate a `motion` + * DOM component with that name. + */ + get: (_target, key) => { + if (key === "create") + return factory; + /** + * If this element doesn't exist in the component cache, create it and cache. + */ + if (!componentCache.has(key)) { + componentCache.set(key, createMotionComponent(key, undefined, preloadedFeatures, createVisualElement)); + } + return componentCache.get(key); + }, + }); + } + + function resolveVariant(visualElement, definition, custom) { + const props = visualElement.getProps(); + return resolveVariantFromProps(props, definition, custom !== undefined ? custom : props.custom, visualElement); + } + + const isKeyframesTarget = (v) => { + return Array.isArray(v); + }; + + /** + * Set VisualElement's MotionValue, creating a new MotionValue for it if + * it doesn't exist. + */ + function setMotionValue(visualElement, key, value) { + if (visualElement.hasValue(key)) { + visualElement.getValue(key).set(value); + } + else { + visualElement.addValue(key, motionValue(value)); + } + } + function resolveFinalValueInKeyframes(v) { + // TODO maybe throw if v.length - 1 is placeholder token? + return isKeyframesTarget(v) ? v[v.length - 1] || 0 : v; + } + function setTarget(visualElement, definition) { + const resolved = resolveVariant(visualElement, definition); + let { transitionEnd = {}, transition = {}, ...target } = resolved || {}; + target = { ...target, ...transitionEnd }; + for (const key in target) { + const value = resolveFinalValueInKeyframes(target[key]); + setMotionValue(visualElement, key, value); + } + } + + function isWillChangeMotionValue(value) { + return Boolean(isMotionValue(value) && value.add); + } + + function addValueToWillChange(visualElement, key) { + const willChange = visualElement.getValue("willChange"); + /** + * It could be that a user has set willChange to a regular MotionValue, + * in which case we can't add the value to it. + */ + if (isWillChangeMotionValue(willChange)) { + return willChange.add(key); + } + else if (!willChange && MotionGlobalConfig.WillChange) { + const newWillChange = new MotionGlobalConfig.WillChange("auto"); + visualElement.addValue("willChange", newWillChange); + newWillChange.add(key); + } + } + + /** + * Decide whether we should block this animation. Previously, we achieved this + * just by checking whether the key was listed in protectedKeys, but this + * posed problems if an animation was triggered by afterChildren and protectedKeys + * had been set to true in the meantime. + */ + function shouldBlockAnimation({ protectedKeys, needsAnimating }, key) { + const shouldBlock = protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true; + needsAnimating[key] = false; + return shouldBlock; + } + function animateTarget(visualElement, targetAndTransition, { delay = 0, transitionOverride, type } = {}) { + let { transition = visualElement.getDefaultTransition(), transitionEnd, ...target } = targetAndTransition; + if (transitionOverride) + transition = transitionOverride; + const animations = []; + const animationTypeState = type && + visualElement.animationState && + visualElement.animationState.getState()[type]; + for (const key in target) { + const value = visualElement.getValue(key, visualElement.latestValues[key] ?? null); + const valueTarget = target[key]; + if (valueTarget === undefined || + (animationTypeState && + shouldBlockAnimation(animationTypeState, key))) { + continue; + } + const valueTransition = { + delay, + ...getValueTransition$1(transition || {}, key), + }; + /** + * If the value is already at the defined target, skip the animation. + */ + const currentValue = value.get(); + if (currentValue !== undefined && + !value.isAnimating && + !Array.isArray(valueTarget) && + valueTarget === currentValue && + !valueTransition.velocity) { + continue; + } + /** + * If this is the first time a value is being animated, check + * to see if we're handling off from an existing animation. + */ + let isHandoff = false; + if (window.MotionHandoffAnimation) { + const appearId = getOptimisedAppearId(visualElement); + if (appearId) { + const startTime = window.MotionHandoffAnimation(appearId, key, frame); + if (startTime !== null) { + valueTransition.startTime = startTime; + isHandoff = true; + } + } + } + addValueToWillChange(visualElement, key); + value.start(animateMotionValue(key, value, valueTarget, visualElement.shouldReduceMotion && positionalKeys.has(key) + ? { type: false } + : valueTransition, visualElement, isHandoff)); + const animation = value.animation; + if (animation) { + animations.push(animation); + } + } + if (transitionEnd) { + Promise.all(animations).then(() => { + frame.update(() => { + transitionEnd && setTarget(visualElement, transitionEnd); + }); + }); + } + return animations; + } + + function calcChildStagger(children, child, delayChildren, staggerChildren = 0, staggerDirection = 1) { + const index = Array.from(children) + .sort((a, b) => a.sortNodePosition(b)) + .indexOf(child); + const numChildren = children.size; + const maxStaggerDuration = (numChildren - 1) * staggerChildren; + const delayIsFunction = typeof delayChildren === "function"; + return delayIsFunction + ? delayChildren(index, numChildren) + : staggerDirection === 1 + ? index * staggerChildren + : maxStaggerDuration - index * staggerChildren; + } + + function animateVariant(visualElement, variant, options = {}) { + const resolved = resolveVariant(visualElement, variant, options.type === "exit" + ? visualElement.presenceContext?.custom + : undefined); + let { transition = visualElement.getDefaultTransition() || {} } = resolved || {}; + if (options.transitionOverride) { + transition = options.transitionOverride; + } + /** + * If we have a variant, create a callback that runs it as an animation. + * Otherwise, we resolve a Promise immediately for a composable no-op. + */ + const getAnimation = resolved + ? () => Promise.all(animateTarget(visualElement, resolved, options)) + : () => Promise.resolve(); + /** + * If we have children, create a callback that runs all their animations. + * Otherwise, we resolve a Promise immediately for a composable no-op. + */ + const getChildAnimations = visualElement.variantChildren && visualElement.variantChildren.size + ? (forwardDelay = 0) => { + const { delayChildren = 0, staggerChildren, staggerDirection, } = transition; + return animateChildren(visualElement, variant, forwardDelay, delayChildren, staggerChildren, staggerDirection, options); + } + : () => Promise.resolve(); + /** + * If the transition explicitly defines a "when" option, we need to resolve either + * this animation or all children animations before playing the other. + */ + const { when } = transition; + if (when) { + const [first, last] = when === "beforeChildren" + ? [getAnimation, getChildAnimations] + : [getChildAnimations, getAnimation]; + return first().then(() => last()); + } + else { + return Promise.all([getAnimation(), getChildAnimations(options.delay)]); + } + } + function animateChildren(visualElement, variant, delay = 0, delayChildren = 0, staggerChildren = 0, staggerDirection = 1, options) { + const animations = []; + for (const child of visualElement.variantChildren) { + child.notify("AnimationStart", variant); + animations.push(animateVariant(child, variant, { + ...options, + delay: delay + + (typeof delayChildren === "function" ? 0 : delayChildren) + + calcChildStagger(visualElement.variantChildren, child, delayChildren, staggerChildren, staggerDirection), + }).then(() => child.notify("AnimationComplete", variant))); + } + return Promise.all(animations); + } + + function animateVisualElement(visualElement, definition, options = {}) { + visualElement.notify("AnimationStart", definition); + let animation; + if (Array.isArray(definition)) { + const animations = definition.map((variant) => animateVariant(visualElement, variant, options)); + animation = Promise.all(animations); + } + else if (typeof definition === "string") { + animation = animateVariant(visualElement, definition, options); + } + else { + const resolvedDefinition = typeof definition === "function" + ? resolveVariant(visualElement, definition, options.custom) + : definition; + animation = Promise.all(animateTarget(visualElement, resolvedDefinition, options)); + } + return animation.then(() => { + visualElement.notify("AnimationComplete", definition); + }); + } + + function shallowCompare(next, prev) { + if (!Array.isArray(prev)) + return false; + const prevLength = prev.length; + if (prevLength !== next.length) + return false; + for (let i = 0; i < prevLength; i++) { + if (prev[i] !== next[i]) + return false; + } + return true; + } + + const numVariantProps = variantProps.length; + function getVariantContext(visualElement) { + if (!visualElement) + return undefined; + if (!visualElement.isControllingVariants) { + const context = visualElement.parent + ? getVariantContext(visualElement.parent) || {} + : {}; + if (visualElement.props.initial !== undefined) { + context.initial = visualElement.props.initial; + } + return context; + } + const context = {}; + for (let i = 0; i < numVariantProps; i++) { + const name = variantProps[i]; + const prop = visualElement.props[name]; + if (isVariantLabel(prop) || prop === false) { + context[name] = prop; + } + } + return context; + } + + const reversePriorityOrder = [...variantPriorityOrder].reverse(); + const numAnimationTypes = variantPriorityOrder.length; + function animateList(visualElement) { + return (animations) => Promise.all(animations.map(({ animation, options }) => animateVisualElement(visualElement, animation, options))); + } + function createAnimationState(visualElement) { + let animate = animateList(visualElement); + let state = createState(); + let isInitialRender = true; + /** + * This function will be used to reduce the animation definitions for + * each active animation type into an object of resolved values for it. + */ + const buildResolvedTypeValues = (type) => (acc, definition) => { + const resolved = resolveVariant(visualElement, definition, type === "exit" + ? visualElement.presenceContext?.custom + : undefined); + if (resolved) { + const { transition, transitionEnd, ...target } = resolved; + acc = { ...acc, ...target, ...transitionEnd }; + } + return acc; + }; + /** + * This just allows us to inject mocked animation functions + * @internal + */ + function setAnimateFunction(makeAnimator) { + animate = makeAnimator(visualElement); + } + /** + * When we receive new props, we need to: + * 1. Create a list of protected keys for each type. This is a directory of + * value keys that are currently being "handled" by types of a higher priority + * so that whenever an animation is played of a given type, these values are + * protected from being animated. + * 2. Determine if an animation type needs animating. + * 3. Determine if any values have been removed from a type and figure out + * what to animate those to. + */ + function animateChanges(changedActiveType) { + const { props } = visualElement; + const context = getVariantContext(visualElement.parent) || {}; + /** + * A list of animations that we'll build into as we iterate through the animation + * types. This will get executed at the end of the function. + */ + const animations = []; + /** + * Keep track of which values have been removed. Then, as we hit lower priority + * animation types, we can check if they contain removed values and animate to that. + */ + const removedKeys = new Set(); + /** + * A dictionary of all encountered keys. This is an object to let us build into and + * copy it without iteration. Each time we hit an animation type we set its protected + * keys - the keys its not allowed to animate - to the latest version of this object. + */ + let encounteredKeys = {}; + /** + * If a variant has been removed at a given index, and this component is controlling + * variant animations, we want to ensure lower-priority variants are forced to animate. + */ + let removedVariantIndex = Infinity; + /** + * Iterate through all animation types in reverse priority order. For each, we want to + * detect which values it's handling and whether or not they've changed (and therefore + * need to be animated). If any values have been removed, we want to detect those in + * lower priority props and flag for animation. + */ + for (let i = 0; i < numAnimationTypes; i++) { + const type = reversePriorityOrder[i]; + const typeState = state[type]; + const prop = props[type] !== undefined + ? props[type] + : context[type]; + const propIsVariant = isVariantLabel(prop); + /** + * If this type has *just* changed isActive status, set activeDelta + * to that status. Otherwise set to null. + */ + const activeDelta = type === changedActiveType ? typeState.isActive : null; + if (activeDelta === false) + removedVariantIndex = i; + /** + * If this prop is an inherited variant, rather than been set directly on the + * component itself, we want to make sure we allow the parent to trigger animations. + * + * TODO: Can probably change this to a !isControllingVariants check + */ + let isInherited = prop === context[type] && + prop !== props[type] && + propIsVariant; + if (isInherited && + isInitialRender && + visualElement.manuallyAnimateOnMount) { + isInherited = false; + } + /** + * Set all encountered keys so far as the protected keys for this type. This will + * be any key that has been animated or otherwise handled by active, higher-priortiy types. + */ + typeState.protectedKeys = { ...encounteredKeys }; + // Check if we can skip analysing this prop early + if ( + // If it isn't active and hasn't *just* been set as inactive + (!typeState.isActive && activeDelta === null) || + // If we didn't and don't have any defined prop for this animation type + (!prop && !typeState.prevProp) || + // Or if the prop doesn't define an animation + isAnimationControls(prop) || + typeof prop === "boolean") { + continue; + } + /** + * As we go look through the values defined on this type, if we detect + * a changed value or a value that was removed in a higher priority, we set + * this to true and add this prop to the animation list. + */ + const variantDidChange = checkVariantsDidChange(typeState.prevProp, prop); + let shouldAnimateType = variantDidChange || + // If we're making this variant active, we want to always make it active + (type === changedActiveType && + typeState.isActive && + !isInherited && + propIsVariant) || + // If we removed a higher-priority variant (i is in reverse order) + (i > removedVariantIndex && propIsVariant); + let handledRemovedValues = false; + /** + * As animations can be set as variant lists, variants or target objects, we + * coerce everything to an array if it isn't one already + */ + const definitionList = Array.isArray(prop) ? prop : [prop]; + /** + * Build an object of all the resolved values. We'll use this in the subsequent + * animateChanges calls to determine whether a value has changed. + */ + let resolvedValues = definitionList.reduce(buildResolvedTypeValues(type), {}); + if (activeDelta === false) + resolvedValues = {}; + /** + * Now we need to loop through all the keys in the prev prop and this prop, + * and decide: + * 1. If the value has changed, and needs animating + * 2. If it has been removed, and needs adding to the removedKeys set + * 3. If it has been removed in a higher priority type and needs animating + * 4. If it hasn't been removed in a higher priority but hasn't changed, and + * needs adding to the type's protectedKeys list. + */ + const { prevResolvedValues = {} } = typeState; + const allKeys = { + ...prevResolvedValues, + ...resolvedValues, + }; + const markToAnimate = (key) => { + shouldAnimateType = true; + if (removedKeys.has(key)) { + handledRemovedValues = true; + removedKeys.delete(key); + } + typeState.needsAnimating[key] = true; + const motionValue = visualElement.getValue(key); + if (motionValue) + motionValue.liveStyle = false; + }; + for (const key in allKeys) { + const next = resolvedValues[key]; + const prev = prevResolvedValues[key]; + // If we've already handled this we can just skip ahead + if (encounteredKeys.hasOwnProperty(key)) + continue; + /** + * If the value has changed, we probably want to animate it. + */ + let valueHasChanged = false; + if (isKeyframesTarget(next) && isKeyframesTarget(prev)) { + valueHasChanged = !shallowCompare(next, prev); + } + else { + valueHasChanged = next !== prev; + } + if (valueHasChanged) { + if (next !== undefined && next !== null) { + // If next is defined and doesn't equal prev, it needs animating + markToAnimate(key); + } + else { + // If it's undefined, it's been removed. + removedKeys.add(key); + } + } + else if (next !== undefined && removedKeys.has(key)) { + /** + * If next hasn't changed and it isn't undefined, we want to check if it's + * been removed by a higher priority + */ + markToAnimate(key); + } + else { + /** + * If it hasn't changed, we add it to the list of protected values + * to ensure it doesn't get animated. + */ + typeState.protectedKeys[key] = true; + } + } + /** + * Update the typeState so next time animateChanges is called we can compare the + * latest prop and resolvedValues to these. + */ + typeState.prevProp = prop; + typeState.prevResolvedValues = resolvedValues; + if (typeState.isActive) { + encounteredKeys = { ...encounteredKeys, ...resolvedValues }; + } + if (isInitialRender && visualElement.blockInitialAnimation) { + shouldAnimateType = false; + } + /** + * If this is an inherited prop we want to skip this animation + * unless the inherited variants haven't changed on this render. + */ + const willAnimateViaParent = isInherited && variantDidChange; + const needsAnimating = !willAnimateViaParent || handledRemovedValues; + if (shouldAnimateType && needsAnimating) { + animations.push(...definitionList.map((animation) => { + const options = { type }; + /** + * If we're performing the initial animation, but we're not + * rendering at the same time as the variant-controlling parent, + * we want to use the parent's transition to calculate the stagger. + */ + if (typeof animation === "string" && + isInitialRender && + !willAnimateViaParent && + visualElement.manuallyAnimateOnMount && + visualElement.parent) { + const { parent } = visualElement; + const parentVariant = resolveVariant(parent, animation); + if (parent.enteringChildren && parentVariant) { + const { delayChildren } = parentVariant.transition || {}; + options.delay = calcChildStagger(parent.enteringChildren, visualElement, delayChildren); + } + } + return { + animation: animation, + options, + }; + })); + } + } + /** + * If there are some removed value that haven't been dealt with, + * we need to create a new animation that falls back either to the value + * defined in the style prop, or the last read value. + */ + if (removedKeys.size) { + const fallbackAnimation = {}; + /** + * If the initial prop contains a transition we can use that, otherwise + * allow the animation function to use the visual element's default. + */ + if (typeof props.initial !== "boolean") { + const initialTransition = resolveVariant(visualElement, Array.isArray(props.initial) + ? props.initial[0] + : props.initial); + if (initialTransition && initialTransition.transition) { + fallbackAnimation.transition = initialTransition.transition; + } + } + removedKeys.forEach((key) => { + const fallbackTarget = visualElement.getBaseTarget(key); + const motionValue = visualElement.getValue(key); + if (motionValue) + motionValue.liveStyle = true; + // @ts-expect-error - @mattgperry to figure if we should do something here + fallbackAnimation[key] = fallbackTarget ?? null; + }); + animations.push({ animation: fallbackAnimation }); + } + let shouldAnimate = Boolean(animations.length); + if (isInitialRender && + (props.initial === false || props.initial === props.animate) && + !visualElement.manuallyAnimateOnMount) { + shouldAnimate = false; + } + isInitialRender = false; + return shouldAnimate ? animate(animations) : Promise.resolve(); + } + /** + * Change whether a certain animation type is active. + */ + function setActive(type, isActive) { + // If the active state hasn't changed, we can safely do nothing here + if (state[type].isActive === isActive) + return Promise.resolve(); + // Propagate active change to children + visualElement.variantChildren?.forEach((child) => child.animationState?.setActive(type, isActive)); + state[type].isActive = isActive; + const animations = animateChanges(type); + for (const key in state) { + state[key].protectedKeys = {}; + } + return animations; + } + return { + animateChanges, + setActive, + setAnimateFunction, + getState: () => state, + reset: () => { + state = createState(); + isInitialRender = true; + }, + }; + } + function checkVariantsDidChange(prev, next) { + if (typeof next === "string") { + return next !== prev; + } + else if (Array.isArray(next)) { + return !shallowCompare(next, prev); + } + return false; + } + function createTypeState(isActive = false) { + return { + isActive, + protectedKeys: {}, + needsAnimating: {}, + prevResolvedValues: {}, + }; + } + function createState() { + return { + animate: createTypeState(true), + whileInView: createTypeState(), + whileHover: createTypeState(), + whileTap: createTypeState(), + whileDrag: createTypeState(), + whileFocus: createTypeState(), + exit: createTypeState(), + }; + } + + class Feature { + constructor(node) { + this.isMounted = false; + this.node = node; + } + update() { } + } + + class AnimationFeature extends Feature { + /** + * We dynamically generate the AnimationState manager as it contains a reference + * to the underlying animation library. We only want to load that if we load this, + * so people can optionally code split it out using the `m` component. + */ + constructor(node) { + super(node); + node.animationState || (node.animationState = createAnimationState(node)); + } + updateAnimationControlsSubscription() { + const { animate } = this.node.getProps(); + if (isAnimationControls(animate)) { + this.unmountControls = animate.subscribe(this.node); + } + } + /** + * Subscribe any provided AnimationControls to the component's VisualElement + */ + mount() { + this.updateAnimationControlsSubscription(); + } + update() { + const { animate } = this.node.getProps(); + const { animate: prevAnimate } = this.node.prevProps || {}; + if (animate !== prevAnimate) { + this.updateAnimationControlsSubscription(); + } + } + unmount() { + this.node.animationState.reset(); + this.unmountControls?.(); + } + } + + let id$1 = 0; + class ExitAnimationFeature extends Feature { + constructor() { + super(...arguments); + this.id = id$1++; + } + update() { + if (!this.node.presenceContext) + return; + const { isPresent, onExitComplete } = this.node.presenceContext; + const { isPresent: prevIsPresent } = this.node.prevPresenceContext || {}; + if (!this.node.animationState || isPresent === prevIsPresent) { + return; + } + const exitAnimation = this.node.animationState.setActive("exit", !isPresent); + if (onExitComplete && !isPresent) { + exitAnimation.then(() => { + onExitComplete(this.id); + }); + } + } + mount() { + const { register, onExitComplete } = this.node.presenceContext || {}; + if (onExitComplete) { + onExitComplete(this.id); + } + if (register) { + this.unmount = register(this.id); + } + } + unmount() { } + } + + const animations = { + animation: { + Feature: AnimationFeature, + }, + exit: { + Feature: ExitAnimationFeature, + }, + }; + + function extractEventInfo(event) { + return { + point: { + x: event.pageX, + y: event.pageY, + }, + }; + } + const addPointerInfo = (handler) => { + return (event) => isPrimaryPointer(event) && handler(event, extractEventInfo(event)); + }; + + function addPointerEvent(target, eventName, handler, options) { + return addDomEvent(target, eventName, addPointerInfo(handler), options); + } + + // Fixes https://github.com/motiondivision/motion/issues/2270 + const getContextWindow = ({ current }) => { + return current ? current.ownerDocument.defaultView : null; + }; + + const distance = (a, b) => Math.abs(a - b); + function distance2D(a, b) { + // Multi-dimensional + const xDelta = distance(a.x, b.x); + const yDelta = distance(a.y, b.y); + return Math.sqrt(xDelta ** 2 + yDelta ** 2); + } + + /** + * @internal + */ + class PanSession { + constructor(event, handlers, { transformPagePoint, contextWindow = window, dragSnapToOrigin = false, distanceThreshold = 3, } = {}) { + /** + * @internal + */ + this.startEvent = null; + /** + * @internal + */ + this.lastMoveEvent = null; + /** + * @internal + */ + this.lastMoveEventInfo = null; + /** + * @internal + */ + this.handlers = {}; + /** + * @internal + */ + this.contextWindow = window; + this.updatePoint = () => { + if (!(this.lastMoveEvent && this.lastMoveEventInfo)) + return; + const info = getPanInfo(this.lastMoveEventInfo, this.history); + const isPanStarted = this.startEvent !== null; + // Only start panning if the offset is larger than 3 pixels. If we make it + // any larger than this we'll want to reset the pointer history + // on the first update to avoid visual snapping to the cursor. + const isDistancePastThreshold = distance2D(info.offset, { x: 0, y: 0 }) >= this.distanceThreshold; + if (!isPanStarted && !isDistancePastThreshold) + return; + const { point } = info; + const { timestamp } = frameData; + this.history.push({ ...point, timestamp }); + const { onStart, onMove } = this.handlers; + if (!isPanStarted) { + onStart && onStart(this.lastMoveEvent, info); + this.startEvent = this.lastMoveEvent; + } + onMove && onMove(this.lastMoveEvent, info); + }; + this.handlePointerMove = (event, info) => { + this.lastMoveEvent = event; + this.lastMoveEventInfo = transformPoint(info, this.transformPagePoint); + // Throttle mouse move event to once per frame + frame.update(this.updatePoint, true); + }; + this.handlePointerUp = (event, info) => { + this.end(); + const { onEnd, onSessionEnd, resumeAnimation } = this.handlers; + if (this.dragSnapToOrigin) + resumeAnimation && resumeAnimation(); + if (!(this.lastMoveEvent && this.lastMoveEventInfo)) + return; + const panInfo = getPanInfo(event.type === "pointercancel" + ? this.lastMoveEventInfo + : transformPoint(info, this.transformPagePoint), this.history); + if (this.startEvent && onEnd) { + onEnd(event, panInfo); + } + onSessionEnd && onSessionEnd(event, panInfo); + }; + // If we have more than one touch, don't start detecting this gesture + if (!isPrimaryPointer(event)) + return; + this.dragSnapToOrigin = dragSnapToOrigin; + this.handlers = handlers; + this.transformPagePoint = transformPagePoint; + this.distanceThreshold = distanceThreshold; + this.contextWindow = contextWindow || window; + const info = extractEventInfo(event); + const initialInfo = transformPoint(info, this.transformPagePoint); + const { point } = initialInfo; + const { timestamp } = frameData; + this.history = [{ ...point, timestamp }]; + const { onSessionStart } = handlers; + onSessionStart && + onSessionStart(event, getPanInfo(initialInfo, this.history)); + this.removeListeners = pipe(addPointerEvent(this.contextWindow, "pointermove", this.handlePointerMove), addPointerEvent(this.contextWindow, "pointerup", this.handlePointerUp), addPointerEvent(this.contextWindow, "pointercancel", this.handlePointerUp)); + } + updateHandlers(handlers) { + this.handlers = handlers; + } + end() { + this.removeListeners && this.removeListeners(); + cancelFrame(this.updatePoint); + } + } + function transformPoint(info, transformPagePoint) { + return transformPagePoint ? { point: transformPagePoint(info.point) } : info; + } + function subtractPoint(a, b) { + return { x: a.x - b.x, y: a.y - b.y }; + } + function getPanInfo({ point }, history) { + return { + point, + delta: subtractPoint(point, lastDevicePoint(history)), + offset: subtractPoint(point, startDevicePoint(history)), + velocity: getVelocity(history, 0.1), + }; + } + function startDevicePoint(history) { + return history[0]; + } + function lastDevicePoint(history) { + return history[history.length - 1]; + } + function getVelocity(history, timeDelta) { + if (history.length < 2) { + return { x: 0, y: 0 }; + } + let i = history.length - 1; + let timestampedPoint = null; + const lastPoint = lastDevicePoint(history); + while (i >= 0) { + timestampedPoint = history[i]; + if (lastPoint.timestamp - timestampedPoint.timestamp > + secondsToMilliseconds(timeDelta)) { + break; + } + i--; + } + if (!timestampedPoint) { + return { x: 0, y: 0 }; + } + const time = millisecondsToSeconds(lastPoint.timestamp - timestampedPoint.timestamp); + if (time === 0) { + return { x: 0, y: 0 }; + } + const currentVelocity = { + x: (lastPoint.x - timestampedPoint.x) / time, + y: (lastPoint.y - timestampedPoint.y) / time, + }; + if (currentVelocity.x === Infinity) { + currentVelocity.x = 0; + } + if (currentVelocity.y === Infinity) { + currentVelocity.y = 0; + } + return currentVelocity; + } + + /** + * Apply constraints to a point. These constraints are both physical along an + * axis, and an elastic factor that determines how much to constrain the point + * by if it does lie outside the defined parameters. + */ + function applyConstraints(point, { min, max }, elastic) { + if (min !== undefined && point < min) { + // If we have a min point defined, and this is outside of that, constrain + point = elastic + ? mixNumber$1(min, point, elastic.min) + : Math.max(point, min); + } + else if (max !== undefined && point > max) { + // If we have a max point defined, and this is outside of that, constrain + point = elastic + ? mixNumber$1(max, point, elastic.max) + : Math.min(point, max); + } + return point; + } + /** + * Calculate constraints in terms of the viewport when defined relatively to the + * measured axis. This is measured from the nearest edge, so a max constraint of 200 + * on an axis with a max value of 300 would return a constraint of 500 - axis length + */ + function calcRelativeAxisConstraints(axis, min, max) { + return { + min: min !== undefined ? axis.min + min : undefined, + max: max !== undefined + ? axis.max + max - (axis.max - axis.min) + : undefined, + }; + } + /** + * Calculate constraints in terms of the viewport when + * defined relatively to the measured bounding box. + */ + function calcRelativeConstraints(layoutBox, { top, left, bottom, right }) { + return { + x: calcRelativeAxisConstraints(layoutBox.x, left, right), + y: calcRelativeAxisConstraints(layoutBox.y, top, bottom), + }; + } + /** + * Calculate viewport constraints when defined as another viewport-relative axis + */ + function calcViewportAxisConstraints(layoutAxis, constraintsAxis) { + let min = constraintsAxis.min - layoutAxis.min; + let max = constraintsAxis.max - layoutAxis.max; + // If the constraints axis is actually smaller than the layout axis then we can + // flip the constraints + if (constraintsAxis.max - constraintsAxis.min < + layoutAxis.max - layoutAxis.min) { + [min, max] = [max, min]; + } + return { min, max }; + } + /** + * Calculate viewport constraints when defined as another viewport-relative box + */ + function calcViewportConstraints(layoutBox, constraintsBox) { + return { + x: calcViewportAxisConstraints(layoutBox.x, constraintsBox.x), + y: calcViewportAxisConstraints(layoutBox.y, constraintsBox.y), + }; + } + /** + * Calculate a transform origin relative to the source axis, between 0-1, that results + * in an asthetically pleasing scale/transform needed to project from source to target. + */ + function calcOrigin(source, target) { + let origin = 0.5; + const sourceLength = calcLength(source); + const targetLength = calcLength(target); + if (targetLength > sourceLength) { + origin = progress(target.min, target.max - sourceLength, source.min); + } + else if (sourceLength > targetLength) { + origin = progress(source.min, source.max - targetLength, target.min); + } + return clamp(0, 1, origin); + } + /** + * Rebase the calculated viewport constraints relative to the layout.min point. + */ + function rebaseAxisConstraints(layout, constraints) { + const relativeConstraints = {}; + if (constraints.min !== undefined) { + relativeConstraints.min = constraints.min - layout.min; + } + if (constraints.max !== undefined) { + relativeConstraints.max = constraints.max - layout.min; + } + return relativeConstraints; + } + const defaultElastic = 0.35; + /** + * Accepts a dragElastic prop and returns resolved elastic values for each axis. + */ + function resolveDragElastic(dragElastic = defaultElastic) { + if (dragElastic === false) { + dragElastic = 0; + } + else if (dragElastic === true) { + dragElastic = defaultElastic; + } + return { + x: resolveAxisElastic(dragElastic, "left", "right"), + y: resolveAxisElastic(dragElastic, "top", "bottom"), + }; + } + function resolveAxisElastic(dragElastic, minLabel, maxLabel) { + return { + min: resolvePointElastic(dragElastic, minLabel), + max: resolvePointElastic(dragElastic, maxLabel), + }; + } + function resolvePointElastic(dragElastic, label) { + return typeof dragElastic === "number" + ? dragElastic + : dragElastic[label] || 0; + } + + const elementDragControls = new WeakMap(); + class VisualElementDragControls { + constructor(visualElement) { + this.openDragLock = null; + this.isDragging = false; + this.currentDirection = null; + this.originPoint = { x: 0, y: 0 }; + /** + * The permitted boundaries of travel, in pixels. + */ + this.constraints = false; + this.hasMutatedConstraints = false; + /** + * The per-axis resolved elastic values. + */ + this.elastic = createBox(); + /** + * The latest pointer event. Used as fallback when the `cancel` and `stop` functions are called without arguments. + */ + this.latestPointerEvent = null; + /** + * The latest pan info. Used as fallback when the `cancel` and `stop` functions are called without arguments. + */ + this.latestPanInfo = null; + this.visualElement = visualElement; + } + start(originEvent, { snapToCursor = false, distanceThreshold } = {}) { + /** + * Don't start dragging if this component is exiting + */ + const { presenceContext } = this.visualElement; + if (presenceContext && presenceContext.isPresent === false) + return; + const onSessionStart = (event) => { + const { dragSnapToOrigin } = this.getProps(); + // Stop or pause any animations on both axis values immediately. This allows the user to throw and catch + // the component. + dragSnapToOrigin ? this.pauseAnimation() : this.stopAnimation(); + if (snapToCursor) { + this.snapToCursor(extractEventInfo(event).point); + } + }; + const onStart = (event, info) => { + // Attempt to grab the global drag gesture lock - maybe make this part of PanSession + const { drag, dragPropagation, onDragStart } = this.getProps(); + if (drag && !dragPropagation) { + if (this.openDragLock) + this.openDragLock(); + this.openDragLock = setDragLock(drag); + // If we don 't have the lock, don't start dragging + if (!this.openDragLock) + return; + } + this.latestPointerEvent = event; + this.latestPanInfo = info; + this.isDragging = true; + this.currentDirection = null; + this.resolveConstraints(); + if (this.visualElement.projection) { + this.visualElement.projection.isAnimationBlocked = true; + this.visualElement.projection.target = undefined; + } + /** + * Record gesture origin + */ + eachAxis((axis) => { + let current = this.getAxisMotionValue(axis).get() || 0; + /** + * If the MotionValue is a percentage value convert to px + */ + if (percent.test(current)) { + const { projection } = this.visualElement; + if (projection && projection.layout) { + const measuredAxis = projection.layout.layoutBox[axis]; + if (measuredAxis) { + const length = calcLength(measuredAxis); + current = length * (parseFloat(current) / 100); + } + } + } + this.originPoint[axis] = current; + }); + // Fire onDragStart event + if (onDragStart) { + frame.postRender(() => onDragStart(event, info)); + } + addValueToWillChange(this.visualElement, "transform"); + const { animationState } = this.visualElement; + animationState && animationState.setActive("whileDrag", true); + }; + const onMove = (event, info) => { + this.latestPointerEvent = event; + this.latestPanInfo = info; + const { dragPropagation, dragDirectionLock, onDirectionLock, onDrag, } = this.getProps(); + // If we didn't successfully receive the gesture lock, early return. + if (!dragPropagation && !this.openDragLock) + return; + const { offset } = info; + // Attempt to detect drag direction if directionLock is true + if (dragDirectionLock && this.currentDirection === null) { + this.currentDirection = getCurrentDirection(offset); + // If we've successfully set a direction, notify listener + if (this.currentDirection !== null) { + onDirectionLock && onDirectionLock(this.currentDirection); + } + return; + } + // Update each point with the latest position + this.updateAxis("x", info.point, offset); + this.updateAxis("y", info.point, offset); + /** + * Ideally we would leave the renderer to fire naturally at the end of + * this frame but if the element is about to change layout as the result + * of a re-render we want to ensure the browser can read the latest + * bounding box to ensure the pointer and element don't fall out of sync. + */ + this.visualElement.render(); + /** + * This must fire after the render call as it might trigger a state + * change which itself might trigger a layout update. + */ + onDrag && onDrag(event, info); + }; + const onSessionEnd = (event, info) => { + this.latestPointerEvent = event; + this.latestPanInfo = info; + this.stop(event, info); + this.latestPointerEvent = null; + this.latestPanInfo = null; + }; + const resumeAnimation = () => eachAxis((axis) => this.getAnimationState(axis) === "paused" && + this.getAxisMotionValue(axis).animation?.play()); + const { dragSnapToOrigin } = this.getProps(); + this.panSession = new PanSession(originEvent, { + onSessionStart, + onStart, + onMove, + onSessionEnd, + resumeAnimation, + }, { + transformPagePoint: this.visualElement.getTransformPagePoint(), + dragSnapToOrigin, + distanceThreshold, + contextWindow: getContextWindow(this.visualElement), + }); + } + /** + * @internal + */ + stop(event, panInfo) { + const finalEvent = event || this.latestPointerEvent; + const finalPanInfo = panInfo || this.latestPanInfo; + const isDragging = this.isDragging; + this.cancel(); + if (!isDragging || !finalPanInfo || !finalEvent) + return; + const { velocity } = finalPanInfo; + this.startAnimation(velocity); + const { onDragEnd } = this.getProps(); + if (onDragEnd) { + frame.postRender(() => onDragEnd(finalEvent, finalPanInfo)); + } + } + /** + * @internal + */ + cancel() { + this.isDragging = false; + const { projection, animationState } = this.visualElement; + if (projection) { + projection.isAnimationBlocked = false; + } + this.panSession && this.panSession.end(); + this.panSession = undefined; + const { dragPropagation } = this.getProps(); + if (!dragPropagation && this.openDragLock) { + this.openDragLock(); + this.openDragLock = null; + } + animationState && animationState.setActive("whileDrag", false); + } + updateAxis(axis, _point, offset) { + const { drag } = this.getProps(); + // If we're not dragging this axis, do an early return. + if (!offset || !shouldDrag(axis, drag, this.currentDirection)) + return; + const axisValue = this.getAxisMotionValue(axis); + let next = this.originPoint[axis] + offset[axis]; + // Apply constraints + if (this.constraints && this.constraints[axis]) { + next = applyConstraints(next, this.constraints[axis], this.elastic[axis]); + } + axisValue.set(next); + } + resolveConstraints() { + const { dragConstraints, dragElastic } = this.getProps(); + const layout = this.visualElement.projection && + !this.visualElement.projection.layout + ? this.visualElement.projection.measure(false) + : this.visualElement.projection?.layout; + const prevConstraints = this.constraints; + if (dragConstraints && isRefObject(dragConstraints)) { + if (!this.constraints) { + this.constraints = this.resolveRefConstraints(); + } + } + else { + if (dragConstraints && layout) { + this.constraints = calcRelativeConstraints(layout.layoutBox, dragConstraints); + } + else { + this.constraints = false; + } + } + this.elastic = resolveDragElastic(dragElastic); + /** + * If we're outputting to external MotionValues, we want to rebase the measured constraints + * from viewport-relative to component-relative. + */ + if (prevConstraints !== this.constraints && + layout && + this.constraints && + !this.hasMutatedConstraints) { + eachAxis((axis) => { + if (this.constraints !== false && + this.getAxisMotionValue(axis)) { + this.constraints[axis] = rebaseAxisConstraints(layout.layoutBox[axis], this.constraints[axis]); + } + }); + } + } + resolveRefConstraints() { + const { dragConstraints: constraints, onMeasureDragConstraints } = this.getProps(); + if (!constraints || !isRefObject(constraints)) + return false; + const constraintsElement = constraints.current; + exports.invariant(constraintsElement !== null, "If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.", "drag-constraints-ref"); + const { projection } = this.visualElement; + // TODO + if (!projection || !projection.layout) + return false; + const constraintsBox = measurePageBox(constraintsElement, projection.root, this.visualElement.getTransformPagePoint()); + let measuredConstraints = calcViewportConstraints(projection.layout.layoutBox, constraintsBox); + /** + * If there's an onMeasureDragConstraints listener we call it and + * if different constraints are returned, set constraints to that + */ + if (onMeasureDragConstraints) { + const userConstraints = onMeasureDragConstraints(convertBoxToBoundingBox(measuredConstraints)); + this.hasMutatedConstraints = !!userConstraints; + if (userConstraints) { + measuredConstraints = convertBoundingBoxToBox(userConstraints); + } + } + return measuredConstraints; + } + startAnimation(velocity) { + const { drag, dragMomentum, dragElastic, dragTransition, dragSnapToOrigin, onDragTransitionEnd, } = this.getProps(); + const constraints = this.constraints || {}; + const momentumAnimations = eachAxis((axis) => { + if (!shouldDrag(axis, drag, this.currentDirection)) { + return; + } + let transition = (constraints && constraints[axis]) || {}; + if (dragSnapToOrigin) + transition = { min: 0, max: 0 }; + /** + * Overdamp the boundary spring if `dragElastic` is disabled. There's still a frame + * of spring animations so we should look into adding a disable spring option to `inertia`. + * We could do something here where we affect the `bounceStiffness` and `bounceDamping` + * using the value of `dragElastic`. + */ + const bounceStiffness = dragElastic ? 200 : 1000000; + const bounceDamping = dragElastic ? 40 : 10000000; + const inertia = { + type: "inertia", + velocity: dragMomentum ? velocity[axis] : 0, + bounceStiffness, + bounceDamping, + timeConstant: 750, + restDelta: 1, + restSpeed: 10, + ...dragTransition, + ...transition, + }; + // If we're not animating on an externally-provided `MotionValue` we can use the + // component's animation controls which will handle interactions with whileHover (etc), + // otherwise we just have to animate the `MotionValue` itself. + return this.startAxisValueAnimation(axis, inertia); + }); + // Run all animations and then resolve the new drag constraints. + return Promise.all(momentumAnimations).then(onDragTransitionEnd); + } + startAxisValueAnimation(axis, transition) { + const axisValue = this.getAxisMotionValue(axis); + addValueToWillChange(this.visualElement, axis); + return axisValue.start(animateMotionValue(axis, axisValue, 0, transition, this.visualElement, false)); + } + stopAnimation() { + eachAxis((axis) => this.getAxisMotionValue(axis).stop()); + } + pauseAnimation() { + eachAxis((axis) => this.getAxisMotionValue(axis).animation?.pause()); + } + getAnimationState(axis) { + return this.getAxisMotionValue(axis).animation?.state; + } + /** + * Drag works differently depending on which props are provided. + * + * - If _dragX and _dragY are provided, we output the gesture delta directly to those motion values. + * - Otherwise, we apply the delta to the x/y motion values. + */ + getAxisMotionValue(axis) { + const dragKey = `_drag${axis.toUpperCase()}`; + const props = this.visualElement.getProps(); + const externalMotionValue = props[dragKey]; + return externalMotionValue + ? externalMotionValue + : this.visualElement.getValue(axis, (props.initial + ? props.initial[axis] + : undefined) || 0); + } + snapToCursor(point) { + eachAxis((axis) => { + const { drag } = this.getProps(); + // If we're not dragging this axis, do an early return. + if (!shouldDrag(axis, drag, this.currentDirection)) + return; + const { projection } = this.visualElement; + const axisValue = this.getAxisMotionValue(axis); + if (projection && projection.layout) { + const { min, max } = projection.layout.layoutBox[axis]; + axisValue.set(point[axis] - mixNumber$1(min, max, 0.5)); + } + }); + } + /** + * When the viewport resizes we want to check if the measured constraints + * have changed and, if so, reposition the element within those new constraints + * relative to where it was before the resize. + */ + scalePositionWithinConstraints() { + if (!this.visualElement.current) + return; + const { drag, dragConstraints } = this.getProps(); + const { projection } = this.visualElement; + if (!isRefObject(dragConstraints) || !projection || !this.constraints) + return; + /** + * Stop current animations as there can be visual glitching if we try to do + * this mid-animation + */ + this.stopAnimation(); + /** + * Record the relative position of the dragged element relative to the + * constraints box and save as a progress value. + */ + const boxProgress = { x: 0, y: 0 }; + eachAxis((axis) => { + const axisValue = this.getAxisMotionValue(axis); + if (axisValue && this.constraints !== false) { + const latest = axisValue.get(); + boxProgress[axis] = calcOrigin({ min: latest, max: latest }, this.constraints[axis]); + } + }); + /** + * Update the layout of this element and resolve the latest drag constraints + */ + const { transformTemplate } = this.visualElement.getProps(); + this.visualElement.current.style.transform = transformTemplate + ? transformTemplate({}, "") + : "none"; + projection.root && projection.root.updateScroll(); + projection.updateLayout(); + this.resolveConstraints(); + /** + * For each axis, calculate the current progress of the layout axis + * within the new constraints. + */ + eachAxis((axis) => { + if (!shouldDrag(axis, drag, null)) + return; + /** + * Calculate a new transform based on the previous box progress + */ + const axisValue = this.getAxisMotionValue(axis); + const { min, max } = this.constraints[axis]; + axisValue.set(mixNumber$1(min, max, boxProgress[axis])); + }); + } + addListeners() { + if (!this.visualElement.current) + return; + elementDragControls.set(this.visualElement, this); + const element = this.visualElement.current; + /** + * Attach a pointerdown event listener on this DOM element to initiate drag tracking. + */ + const stopPointerListener = addPointerEvent(element, "pointerdown", (event) => { + const { drag, dragListener = true } = this.getProps(); + drag && dragListener && this.start(event); + }); + const measureDragConstraints = () => { + const { dragConstraints } = this.getProps(); + if (isRefObject(dragConstraints) && dragConstraints.current) { + this.constraints = this.resolveRefConstraints(); + } + }; + const { projection } = this.visualElement; + const stopMeasureLayoutListener = projection.addEventListener("measure", measureDragConstraints); + if (projection && !projection.layout) { + projection.root && projection.root.updateScroll(); + projection.updateLayout(); + } + frame.read(measureDragConstraints); + /** + * Attach a window resize listener to scale the draggable target within its defined + * constraints as the window resizes. + */ + const stopResizeListener = addDomEvent(window, "resize", () => this.scalePositionWithinConstraints()); + /** + * If the element's layout changes, calculate the delta and apply that to + * the drag gesture's origin point. + */ + const stopLayoutUpdateListener = projection.addEventListener("didUpdate", (({ delta, hasLayoutChanged }) => { + if (this.isDragging && hasLayoutChanged) { + eachAxis((axis) => { + const motionValue = this.getAxisMotionValue(axis); + if (!motionValue) + return; + this.originPoint[axis] += delta[axis].translate; + motionValue.set(motionValue.get() + delta[axis].translate); + }); + this.visualElement.render(); + } + })); + return () => { + stopResizeListener(); + stopPointerListener(); + stopMeasureLayoutListener(); + stopLayoutUpdateListener && stopLayoutUpdateListener(); + }; + } + getProps() { + const props = this.visualElement.getProps(); + const { drag = false, dragDirectionLock = false, dragPropagation = false, dragConstraints = false, dragElastic = defaultElastic, dragMomentum = true, } = props; + return { + ...props, + drag, + dragDirectionLock, + dragPropagation, + dragConstraints, + dragElastic, + dragMomentum, + }; + } + } + function shouldDrag(direction, drag, currentDirection) { + return ((drag === true || drag === direction) && + (currentDirection === null || currentDirection === direction)); + } + /** + * Based on an x/y offset determine the current drag direction. If both axis' offsets are lower + * than the provided threshold, return `null`. + * + * @param offset - The x/y offset from origin. + * @param lockThreshold - (Optional) - the minimum absolute offset before we can determine a drag direction. + */ + function getCurrentDirection(offset, lockThreshold = 10) { + let direction = null; + if (Math.abs(offset.y) > lockThreshold) { + direction = "y"; + } + else if (Math.abs(offset.x) > lockThreshold) { + direction = "x"; + } + return direction; + } + + class DragGesture extends Feature { + constructor(node) { + super(node); + this.removeGroupControls = noop; + this.removeListeners = noop; + this.controls = new VisualElementDragControls(node); + } + mount() { + // If we've been provided a DragControls for manual control over the drag gesture, + // subscribe this component to it on mount. + const { dragControls } = this.node.getProps(); + if (dragControls) { + this.removeGroupControls = dragControls.subscribe(this.controls); + } + this.removeListeners = this.controls.addListeners() || noop; + } + unmount() { + this.removeGroupControls(); + this.removeListeners(); + } + } + + const asyncHandler = (handler) => (event, info) => { + if (handler) { + frame.postRender(() => handler(event, info)); + } + }; + class PanGesture extends Feature { + constructor() { + super(...arguments); + this.removePointerDownListener = noop; + } + onPointerDown(pointerDownEvent) { + this.session = new PanSession(pointerDownEvent, this.createPanHandlers(), { + transformPagePoint: this.node.getTransformPagePoint(), + contextWindow: getContextWindow(this.node), + }); + } + createPanHandlers() { + const { onPanSessionStart, onPanStart, onPan, onPanEnd } = this.node.getProps(); + return { + onSessionStart: asyncHandler(onPanSessionStart), + onStart: asyncHandler(onPanStart), + onMove: onPan, + onEnd: (event, info) => { + delete this.session; + if (onPanEnd) { + frame.postRender(() => onPanEnd(event, info)); + } + }, + }; + } + mount() { + this.removePointerDownListener = addPointerEvent(this.node.current, "pointerdown", (event) => this.onPointerDown(event)); + } + update() { + this.session && this.session.updateHandlers(this.createPanHandlers()); + } + unmount() { + this.removePointerDownListener(); + this.session && this.session.end(); + } + } + + /** + * Track whether we've taken any snapshots yet. If not, + * we can safely skip notification of didUpdate. + * + * Difficult to capture in a test but to prevent flickering + * we must set this to true either on update or unmount. + * Running `next-env/layout-id` in Safari will show this behaviour if broken. + */ + let hasTakenAnySnapshot = false; + class MeasureLayoutWithContext extends React$1.Component { + /** + * This only mounts projection nodes for components that + * need measuring, we might want to do it for all components + * in order to incorporate transforms + */ + componentDidMount() { + const { visualElement, layoutGroup, switchLayoutGroup, layoutId } = this.props; + const { projection } = visualElement; + addScaleCorrector(defaultScaleCorrectors); + if (projection) { + if (layoutGroup.group) + layoutGroup.group.add(projection); + if (switchLayoutGroup && switchLayoutGroup.register && layoutId) { + switchLayoutGroup.register(projection); + } + if (hasTakenAnySnapshot) { + projection.root.didUpdate(); + } + projection.addEventListener("animationComplete", () => { + this.safeToRemove(); + }); + projection.setOptions({ + ...projection.options, + onExitComplete: () => this.safeToRemove(), + }); + } + globalProjectionState.hasEverUpdated = true; + } + getSnapshotBeforeUpdate(prevProps) { + const { layoutDependency, visualElement, drag, isPresent } = this.props; + const { projection } = visualElement; + if (!projection) + return null; + /** + * TODO: We use this data in relegate to determine whether to + * promote a previous element. There's no guarantee its presence data + * will have updated by this point - if a bug like this arises it will + * have to be that we markForRelegation and then find a new lead some other way, + * perhaps in didUpdate + */ + projection.isPresent = isPresent; + hasTakenAnySnapshot = true; + if (drag || + prevProps.layoutDependency !== layoutDependency || + layoutDependency === undefined || + prevProps.isPresent !== isPresent) { + projection.willUpdate(); + } + else { + this.safeToRemove(); + } + if (prevProps.isPresent !== isPresent) { + if (isPresent) { + projection.promote(); + } + else if (!projection.relegate()) { + /** + * If there's another stack member taking over from this one, + * it's in charge of the exit animation and therefore should + * be in charge of the safe to remove. Otherwise we call it here. + */ + frame.postRender(() => { + const stack = projection.getStack(); + if (!stack || !stack.members.length) { + this.safeToRemove(); + } + }); + } + } + return null; + } + componentDidUpdate() { + const { projection } = this.props.visualElement; + if (projection) { + projection.root.didUpdate(); + microtask.postRender(() => { + if (!projection.currentAnimation && projection.isLead()) { + this.safeToRemove(); + } + }); + } + } + componentWillUnmount() { + const { visualElement, layoutGroup, switchLayoutGroup: promoteContext, } = this.props; + const { projection } = visualElement; + hasTakenAnySnapshot = true; + if (projection) { + projection.scheduleCheckAfterUnmount(); + if (layoutGroup && layoutGroup.group) + layoutGroup.group.remove(projection); + if (promoteContext && promoteContext.deregister) + promoteContext.deregister(projection); + } + } + safeToRemove() { + const { safeToRemove } = this.props; + safeToRemove && safeToRemove(); + } + render() { + return null; + } + } + function MeasureLayout(props) { + const [isPresent, safeToRemove] = usePresence(); + const layoutGroup = React$1.useContext(LayoutGroupContext); + return (jsx(MeasureLayoutWithContext, { ...props, layoutGroup: layoutGroup, switchLayoutGroup: React$1.useContext(SwitchLayoutGroupContext), isPresent: isPresent, safeToRemove: safeToRemove })); + } + const defaultScaleCorrectors = { + borderRadius: { + ...correctBorderRadius, + applyTo: [ + "borderTopLeftRadius", + "borderTopRightRadius", + "borderBottomLeftRadius", + "borderBottomRightRadius", + ], + }, + borderTopLeftRadius: correctBorderRadius, + borderTopRightRadius: correctBorderRadius, + borderBottomLeftRadius: correctBorderRadius, + borderBottomRightRadius: correctBorderRadius, + boxShadow: correctBoxShadow, + }; + + const drag = { + pan: { + Feature: PanGesture, + }, + drag: { + Feature: DragGesture, + ProjectionNode: HTMLProjectionNode, + MeasureLayout, + }, + }; + + function handleHoverEvent(node, event, lifecycle) { + const { props } = node; + if (node.animationState && props.whileHover) { + node.animationState.setActive("whileHover", lifecycle === "Start"); + } + const eventName = ("onHover" + lifecycle); + const callback = props[eventName]; + if (callback) { + frame.postRender(() => callback(event, extractEventInfo(event))); + } + } + class HoverGesture extends Feature { + mount() { + const { current } = this.node; + if (!current) + return; + this.unmount = hover(current, (_element, startEvent) => { + handleHoverEvent(this.node, startEvent, "Start"); + return (endEvent) => handleHoverEvent(this.node, endEvent, "End"); + }); + } + unmount() { } + } + + class FocusGesture extends Feature { + constructor() { + super(...arguments); + this.isActive = false; + } + onFocus() { + let isFocusVisible = false; + /** + * If this element doesn't match focus-visible then don't + * apply whileHover. But, if matches throws that focus-visible + * is not a valid selector then in that browser outline styles will be applied + * to the element by default and we want to match that behaviour with whileFocus. + */ + try { + isFocusVisible = this.node.current.matches(":focus-visible"); + } + catch (e) { + isFocusVisible = true; + } + if (!isFocusVisible || !this.node.animationState) + return; + this.node.animationState.setActive("whileFocus", true); + this.isActive = true; + } + onBlur() { + if (!this.isActive || !this.node.animationState) + return; + this.node.animationState.setActive("whileFocus", false); + this.isActive = false; + } + mount() { + this.unmount = pipe(addDomEvent(this.node.current, "focus", () => this.onFocus()), addDomEvent(this.node.current, "blur", () => this.onBlur())); + } + unmount() { } + } + + function handlePressEvent(node, event, lifecycle) { + const { props } = node; + if (node.current instanceof HTMLButtonElement && node.current.disabled) { + return; + } + if (node.animationState && props.whileTap) { + node.animationState.setActive("whileTap", lifecycle === "Start"); + } + const eventName = ("onTap" + (lifecycle === "End" ? "" : lifecycle)); + const callback = props[eventName]; + if (callback) { + frame.postRender(() => callback(event, extractEventInfo(event))); + } + } + class PressGesture extends Feature { + mount() { + const { current } = this.node; + if (!current) + return; + this.unmount = press(current, (_element, startEvent) => { + handlePressEvent(this.node, startEvent, "Start"); + return (endEvent, { success }) => handlePressEvent(this.node, endEvent, success ? "End" : "Cancel"); + }, { useGlobalTarget: this.node.props.globalTapTarget }); + } + unmount() { } + } + + /** + * Map an IntersectionHandler callback to an element. We only ever make one handler for one + * element, so even though these handlers might all be triggered by different + * observers, we can keep them in the same map. + */ + const observerCallbacks = new WeakMap(); + /** + * Multiple observers can be created for multiple element/document roots. Each with + * different settings. So here we store dictionaries of observers to each root, + * using serialised settings (threshold/margin) as lookup keys. + */ + const observers = new WeakMap(); + const fireObserverCallback = (entry) => { + const callback = observerCallbacks.get(entry.target); + callback && callback(entry); + }; + const fireAllObserverCallbacks = (entries) => { + entries.forEach(fireObserverCallback); + }; + function initIntersectionObserver({ root, ...options }) { + const lookupRoot = root || document; + /** + * If we don't have an observer lookup map for this root, create one. + */ + if (!observers.has(lookupRoot)) { + observers.set(lookupRoot, {}); + } + const rootObservers = observers.get(lookupRoot); + const key = JSON.stringify(options); + /** + * If we don't have an observer for this combination of root and settings, + * create one. + */ + if (!rootObservers[key]) { + rootObservers[key] = new IntersectionObserver(fireAllObserverCallbacks, { root, ...options }); + } + return rootObservers[key]; + } + function observeIntersection(element, options, callback) { + const rootInteresectionObserver = initIntersectionObserver(options); + observerCallbacks.set(element, callback); + rootInteresectionObserver.observe(element); + return () => { + observerCallbacks.delete(element); + rootInteresectionObserver.unobserve(element); + }; + } + + const thresholdNames = { + some: 0, + all: 1, + }; + class InViewFeature extends Feature { + constructor() { + super(...arguments); + this.hasEnteredView = false; + this.isInView = false; + } + startObserver() { + this.unmount(); + const { viewport = {} } = this.node.getProps(); + const { root, margin: rootMargin, amount = "some", once } = viewport; + const options = { + root: root ? root.current : undefined, + rootMargin, + threshold: typeof amount === "number" ? amount : thresholdNames[amount], + }; + const onIntersectionUpdate = (entry) => { + const { isIntersecting } = entry; + /** + * If there's been no change in the viewport state, early return. + */ + if (this.isInView === isIntersecting) + return; + this.isInView = isIntersecting; + /** + * Handle hasEnteredView. If this is only meant to run once, and + * element isn't visible, early return. Otherwise set hasEnteredView to true. + */ + if (once && !isIntersecting && this.hasEnteredView) { + return; + } + else if (isIntersecting) { + this.hasEnteredView = true; + } + if (this.node.animationState) { + this.node.animationState.setActive("whileInView", isIntersecting); + } + /** + * Use the latest committed props rather than the ones in scope + * when this observer is created + */ + const { onViewportEnter, onViewportLeave } = this.node.getProps(); + const callback = isIntersecting ? onViewportEnter : onViewportLeave; + callback && callback(entry); + }; + return observeIntersection(this.node.current, options, onIntersectionUpdate); + } + mount() { + this.startObserver(); + } + update() { + if (typeof IntersectionObserver === "undefined") + return; + const { props, prevProps } = this.node; + const hasOptionsChanged = ["amount", "margin", "root"].some(hasViewportOptionChanged(props, prevProps)); + if (hasOptionsChanged) { + this.startObserver(); + } + } + unmount() { } + } + function hasViewportOptionChanged({ viewport = {} }, { viewport: prevViewport = {} } = {}) { + return (name) => viewport[name] !== prevViewport[name]; + } + + const gestureAnimations = { + inView: { + Feature: InViewFeature, + }, + tap: { + Feature: PressGesture, + }, + focus: { + Feature: FocusGesture, + }, + hover: { + Feature: HoverGesture, + }, + }; + + const layout = { + layout: { + ProjectionNode: HTMLProjectionNode, + MeasureLayout, + }, + }; + + const featureBundle = { + ...animations, + ...gestureAnimations, + ...drag, + ...layout, + }; + + const motion = /*@__PURE__*/ createMotionProxy(featureBundle, createDomVisualElement); + + function checkReorder(order, value, offset, velocity) { + if (!velocity) + return order; + const index = order.findIndex((item) => item.value === value); + if (index === -1) + return order; + const nextOffset = velocity > 0 ? 1 : -1; + const nextItem = order[index + nextOffset]; + if (!nextItem) + return order; + const item = order[index]; + const nextLayout = nextItem.layout; + const nextItemCenter = mixNumber$1(nextLayout.min, nextLayout.max, 0.5); + if ((nextOffset === 1 && item.layout.max + offset > nextItemCenter) || + (nextOffset === -1 && item.layout.min + offset < nextItemCenter)) { + return moveItem(order, index, index + nextOffset); + } + return order; + } + + function ReorderGroupComponent({ children, as = "ul", axis = "y", onReorder, values, ...props }, externalRef) { + const Component = useConstant(() => motion[as]); + const order = []; + const isReordering = React$1.useRef(false); + exports.invariant(Boolean(values), "Reorder.Group must be provided a values prop", "reorder-values"); + const context = { + axis, + registerItem: (value, layout) => { + // If the entry was already added, update it rather than adding it again + const idx = order.findIndex((entry) => value === entry.value); + if (idx !== -1) { + order[idx].layout = layout[axis]; + } + else { + order.push({ value: value, layout: layout[axis] }); + } + order.sort(compareMin); + }, + updateOrder: (item, offset, velocity) => { + if (isReordering.current) + return; + const newOrder = checkReorder(order, item, offset, velocity); + if (order !== newOrder) { + isReordering.current = true; + onReorder(newOrder + .map(getValue) + .filter((value) => values.indexOf(value) !== -1)); + } + }, + }; + React$1.useEffect(() => { + isReordering.current = false; + }); + return (jsx(Component, { ...props, ref: externalRef, ignoreStrict: true, children: jsx(ReorderContext.Provider, { value: context, children: children }) })); + } + const ReorderGroup = /*@__PURE__*/ React$1.forwardRef(ReorderGroupComponent); + function getValue(item) { + return item.value; + } + function compareMin(a, b) { + return a.layout.min - b.layout.min; + } + + /** + * Creates a `MotionValue` to track the state and velocity of a value. + * + * Usually, these are created automatically. For advanced use-cases, like use with `useTransform`, you can create `MotionValue`s externally and pass them into the animated component via the `style` prop. + * + * ```jsx + * export const MyComponent = () => { + * const scale = useMotionValue(1) + * + * return + * } + * ``` + * + * @param initial - The initial state. + * + * @public + */ + function useMotionValue(initial) { + const value = useConstant(() => motionValue(initial)); + /** + * If this motion value is being used in static mode, like on + * the Framer canvas, force components to rerender when the motion + * value is updated. + */ + const { isStatic } = React$1.useContext(MotionConfigContext); + if (isStatic) { + const [, setLatest] = React$1.useState(initial); + React$1.useEffect(() => value.on("change", setLatest), []); + } + return value; + } + + function useCombineMotionValues(values, combineValues) { + /** + * Initialise the returned motion value. This remains the same between renders. + */ + const value = useMotionValue(combineValues()); + /** + * Create a function that will update the template motion value with the latest values. + * This is pre-bound so whenever a motion value updates it can schedule its + * execution in Framesync. If it's already been scheduled it won't be fired twice + * in a single frame. + */ + const updateValue = () => value.set(combineValues()); + /** + * Synchronously update the motion value with the latest values during the render. + * This ensures that within a React render, the styles applied to the DOM are up-to-date. + */ + updateValue(); + /** + * Subscribe to all motion values found within the template. Whenever any of them change, + * schedule an update. + */ + useIsomorphicLayoutEffect(() => { + const scheduleUpdate = () => frame.preRender(updateValue, false, true); + const subscriptions = values.map((v) => v.on("change", scheduleUpdate)); + return () => { + subscriptions.forEach((unsubscribe) => unsubscribe()); + cancelFrame(updateValue); + }; + }); + return value; + } + + function useComputed(compute) { + /** + * Open session of collectMotionValues. Any MotionValue that calls get() + * will be saved into this array. + */ + collectMotionValues.current = []; + compute(); + const value = useCombineMotionValues(collectMotionValues.current, compute); + /** + * Synchronously close session of collectMotionValues. + */ + collectMotionValues.current = undefined; + return value; + } + + function useTransform(input, inputRangeOrTransformer, outputRange, options) { + if (typeof input === "function") { + return useComputed(input); + } + const transformer = typeof inputRangeOrTransformer === "function" + ? inputRangeOrTransformer + : transform(inputRangeOrTransformer, outputRange, options); + return Array.isArray(input) + ? useListTransform(input, transformer) + : useListTransform([input], ([latest]) => transformer(latest)); + } + function useListTransform(values, transformer) { + const latest = useConstant(() => []); + return useCombineMotionValues(values, () => { + latest.length = 0; + const numValues = values.length; + for (let i = 0; i < numValues; i++) { + latest[i] = values[i].get(); + } + return transformer(latest); + }); + } + + function useDefaultMotionValue(value, defaultValue = 0) { + return isMotionValue(value) ? value : useMotionValue(defaultValue); + } + function ReorderItemComponent({ children, style = {}, value, as = "li", onDrag, layout = true, ...props }, externalRef) { + const Component = useConstant(() => motion[as]); + const context = React$1.useContext(ReorderContext); + const point = { + x: useDefaultMotionValue(style.x), + y: useDefaultMotionValue(style.y), + }; + const zIndex = useTransform([point.x, point.y], ([latestX, latestY]) => latestX || latestY ? 1 : "unset"); + exports.invariant(Boolean(context), "Reorder.Item must be a child of Reorder.Group", "reorder-item-child"); + const { axis, registerItem, updateOrder } = context; + return (jsx(Component, { drag: axis, ...props, dragSnapToOrigin: true, style: { ...style, x: point.x, y: point.y, zIndex }, layout: layout, onDrag: (event, gesturePoint) => { + const { velocity } = gesturePoint; + velocity[axis] && + updateOrder(value, point[axis].get(), velocity[axis]); + onDrag && onDrag(event, gesturePoint); + }, onLayoutMeasure: (measured) => registerItem(value, measured), ref: externalRef, ignoreStrict: true, children: children })); + } + const ReorderItem = /*@__PURE__*/ React$1.forwardRef(ReorderItemComponent); + + var namespace = /*#__PURE__*/Object.freeze({ + __proto__: null, + Group: ReorderGroup, + Item: ReorderItem + }); + + function isDOMKeyframes(keyframes) { + return typeof keyframes === "object" && !Array.isArray(keyframes); + } + + function resolveSubjects(subject, keyframes, scope, selectorCache) { + if (typeof subject === "string" && isDOMKeyframes(keyframes)) { + return resolveElements(subject, scope, selectorCache); + } + else if (subject instanceof NodeList) { + return Array.from(subject); + } + else if (Array.isArray(subject)) { + return subject; + } + else { + return [subject]; + } + } + + function calculateRepeatDuration(duration, repeat, _repeatDelay) { + return duration * (repeat + 1); + } + + /** + * Given a absolute or relative time definition and current/prev time state of the sequence, + * calculate an absolute time for the next keyframes. + */ + function calcNextTime(current, next, prev, labels) { + if (typeof next === "number") { + return next; + } + else if (next.startsWith("-") || next.startsWith("+")) { + return Math.max(0, current + parseFloat(next)); + } + else if (next === "<") { + return prev; + } + else if (next.startsWith("<")) { + return Math.max(0, prev + parseFloat(next.slice(1))); + } + else { + return labels.get(next) ?? current; + } + } + + function eraseKeyframes(sequence, startTime, endTime) { + for (let i = 0; i < sequence.length; i++) { + const keyframe = sequence[i]; + if (keyframe.at > startTime && keyframe.at < endTime) { + removeItem(sequence, keyframe); + // If we remove this item we have to push the pointer back one + i--; + } + } + } + function addKeyframes(sequence, keyframes, easing, offset, startTime, endTime) { + /** + * Erase every existing value between currentTime and targetTime, + * this will essentially splice this timeline into any currently + * defined ones. + */ + eraseKeyframes(sequence, startTime, endTime); + for (let i = 0; i < keyframes.length; i++) { + sequence.push({ + value: keyframes[i], + at: mixNumber$1(startTime, endTime, offset[i]), + easing: getEasingForSegment(easing, i), + }); + } + } + + /** + * Take an array of times that represent repeated keyframes. For instance + * if we have original times of [0, 0.5, 1] then our repeated times will + * be [0, 0.5, 1, 1, 1.5, 2]. Loop over the times and scale them back + * down to a 0-1 scale. + */ + function normalizeTimes(times, repeat) { + for (let i = 0; i < times.length; i++) { + times[i] = times[i] / (repeat + 1); + } + } + + function compareByTime(a, b) { + if (a.at === b.at) { + if (a.value === null) + return 1; + if (b.value === null) + return -1; + return 0; + } + else { + return a.at - b.at; + } + } + + const defaultSegmentEasing = "easeInOut"; + const MAX_REPEAT = 20; + function createAnimationsFromSequence(sequence, { defaultTransition = {}, ...sequenceTransition } = {}, scope, generators) { + const defaultDuration = defaultTransition.duration || 0.3; + const animationDefinitions = new Map(); + const sequences = new Map(); + const elementCache = {}; + const timeLabels = new Map(); + let prevTime = 0; + let currentTime = 0; + let totalDuration = 0; + /** + * Build the timeline by mapping over the sequence array and converting + * the definitions into keyframes and offsets with absolute time values. + * These will later get converted into relative offsets in a second pass. + */ + for (let i = 0; i < sequence.length; i++) { + const segment = sequence[i]; + /** + * If this is a timeline label, mark it and skip the rest of this iteration. + */ + if (typeof segment === "string") { + timeLabels.set(segment, currentTime); + continue; + } + else if (!Array.isArray(segment)) { + timeLabels.set(segment.name, calcNextTime(currentTime, segment.at, prevTime, timeLabels)); + continue; + } + let [subject, keyframes, transition = {}] = segment; + /** + * If a relative or absolute time value has been specified we need to resolve + * it in relation to the currentTime. + */ + if (transition.at !== undefined) { + currentTime = calcNextTime(currentTime, transition.at, prevTime, timeLabels); + } + /** + * Keep track of the maximum duration in this definition. This will be + * applied to currentTime once the definition has been parsed. + */ + let maxDuration = 0; + const resolveValueSequence = (valueKeyframes, valueTransition, valueSequence, elementIndex = 0, numSubjects = 0) => { + const valueKeyframesAsList = keyframesAsList(valueKeyframes); + const { delay = 0, times = defaultOffset$1(valueKeyframesAsList), type = "keyframes", repeat, repeatType, repeatDelay = 0, ...remainingTransition } = valueTransition; + let { ease = defaultTransition.ease || "easeOut", duration } = valueTransition; + /** + * Resolve stagger() if defined. + */ + const calculatedDelay = typeof delay === "function" + ? delay(elementIndex, numSubjects) + : delay; + /** + * If this animation should and can use a spring, generate a spring easing function. + */ + const numKeyframes = valueKeyframesAsList.length; + const createGenerator = isGenerator(type) + ? type + : generators?.[type || "keyframes"]; + if (numKeyframes <= 2 && createGenerator) { + /** + * As we're creating an easing function from a spring, + * ideally we want to generate it using the real distance + * between the two keyframes. However this isn't always + * possible - in these situations we use 0-100. + */ + let absoluteDelta = 100; + if (numKeyframes === 2 && + isNumberKeyframesArray(valueKeyframesAsList)) { + const delta = valueKeyframesAsList[1] - valueKeyframesAsList[0]; + absoluteDelta = Math.abs(delta); + } + const springTransition = { ...remainingTransition }; + if (duration !== undefined) { + springTransition.duration = secondsToMilliseconds(duration); + } + const springEasing = createGeneratorEasing(springTransition, absoluteDelta, createGenerator); + ease = springEasing.ease; + duration = springEasing.duration; + } + duration ?? (duration = defaultDuration); + const startTime = currentTime + calculatedDelay; + /** + * If there's only one time offset of 0, fill in a second with length 1 + */ + if (times.length === 1 && times[0] === 0) { + times[1] = 1; + } + /** + * Fill out if offset if fewer offsets than keyframes + */ + const remainder = times.length - valueKeyframesAsList.length; + remainder > 0 && fillOffset(times, remainder); + /** + * If only one value has been set, ie [1], push a null to the start of + * the keyframe array. This will let us mark a keyframe at this point + * that will later be hydrated with the previous value. + */ + valueKeyframesAsList.length === 1 && + valueKeyframesAsList.unshift(null); + /** + * Handle repeat options + */ + if (repeat) { + exports.invariant(repeat < MAX_REPEAT, "Repeat count too high, must be less than 20", "repeat-count-high"); + duration = calculateRepeatDuration(duration, repeat); + const originalKeyframes = [...valueKeyframesAsList]; + const originalTimes = [...times]; + ease = Array.isArray(ease) ? [...ease] : [ease]; + const originalEase = [...ease]; + for (let repeatIndex = 0; repeatIndex < repeat; repeatIndex++) { + valueKeyframesAsList.push(...originalKeyframes); + for (let keyframeIndex = 0; keyframeIndex < originalKeyframes.length; keyframeIndex++) { + times.push(originalTimes[keyframeIndex] + (repeatIndex + 1)); + ease.push(keyframeIndex === 0 + ? "linear" + : getEasingForSegment(originalEase, keyframeIndex - 1)); + } + } + normalizeTimes(times, repeat); + } + const targetTime = startTime + duration; + /** + * Add keyframes, mapping offsets to absolute time. + */ + addKeyframes(valueSequence, valueKeyframesAsList, ease, times, startTime, targetTime); + maxDuration = Math.max(calculatedDelay + duration, maxDuration); + totalDuration = Math.max(targetTime, totalDuration); + }; + if (isMotionValue(subject)) { + const subjectSequence = getSubjectSequence(subject, sequences); + resolveValueSequence(keyframes, transition, getValueSequence("default", subjectSequence)); + } + else { + const subjects = resolveSubjects(subject, keyframes, scope, elementCache); + const numSubjects = subjects.length; + /** + * For every element in this segment, process the defined values. + */ + for (let subjectIndex = 0; subjectIndex < numSubjects; subjectIndex++) { + /** + * Cast necessary, but we know these are of this type + */ + keyframes = keyframes; + transition = transition; + const thisSubject = subjects[subjectIndex]; + const subjectSequence = getSubjectSequence(thisSubject, sequences); + for (const key in keyframes) { + resolveValueSequence(keyframes[key], getValueTransition(transition, key), getValueSequence(key, subjectSequence), subjectIndex, numSubjects); + } + } + } + prevTime = currentTime; + currentTime += maxDuration; + } + /** + * For every element and value combination create a new animation. + */ + sequences.forEach((valueSequences, element) => { + for (const key in valueSequences) { + const valueSequence = valueSequences[key]; + /** + * Arrange all the keyframes in ascending time order. + */ + valueSequence.sort(compareByTime); + const keyframes = []; + const valueOffset = []; + const valueEasing = []; + /** + * For each keyframe, translate absolute times into + * relative offsets based on the total duration of the timeline. + */ + for (let i = 0; i < valueSequence.length; i++) { + const { at, value, easing } = valueSequence[i]; + keyframes.push(value); + valueOffset.push(progress(0, totalDuration, at)); + valueEasing.push(easing || "easeOut"); + } + /** + * If the first keyframe doesn't land on offset: 0 + * provide one by duplicating the initial keyframe. This ensures + * it snaps to the first keyframe when the animation starts. + */ + if (valueOffset[0] !== 0) { + valueOffset.unshift(0); + keyframes.unshift(keyframes[0]); + valueEasing.unshift(defaultSegmentEasing); + } + /** + * If the last keyframe doesn't land on offset: 1 + * provide one with a null wildcard value. This will ensure it + * stays static until the end of the animation. + */ + if (valueOffset[valueOffset.length - 1] !== 1) { + valueOffset.push(1); + keyframes.push(null); + } + if (!animationDefinitions.has(element)) { + animationDefinitions.set(element, { + keyframes: {}, + transition: {}, + }); + } + const definition = animationDefinitions.get(element); + definition.keyframes[key] = keyframes; + definition.transition[key] = { + ...defaultTransition, + duration: totalDuration, + ease: valueEasing, + times: valueOffset, + ...sequenceTransition, + }; + } + }); + return animationDefinitions; + } + function getSubjectSequence(subject, sequences) { + !sequences.has(subject) && sequences.set(subject, {}); + return sequences.get(subject); + } + function getValueSequence(name, sequences) { + if (!sequences[name]) + sequences[name] = []; + return sequences[name]; + } + function keyframesAsList(keyframes) { + return Array.isArray(keyframes) ? keyframes : [keyframes]; + } + function getValueTransition(transition, key) { + return transition && transition[key] + ? { + ...transition, + ...transition[key], + } + : { ...transition }; + } + const isNumber = (keyframe) => typeof keyframe === "number"; + const isNumberKeyframesArray = (keyframes) => keyframes.every(isNumber); + + function isObjectKey(key, object) { + return key in object; + } + class ObjectVisualElement extends VisualElement { + constructor() { + super(...arguments); + this.type = "object"; + } + readValueFromInstance(instance, key) { + if (isObjectKey(key, instance)) { + const value = instance[key]; + if (typeof value === "string" || typeof value === "number") { + return value; + } + } + return undefined; + } + getBaseTargetFromProps() { + return undefined; + } + removeValueFromRenderState(key, renderState) { + delete renderState.output[key]; + } + measureInstanceViewportBox() { + return createBox(); + } + build(renderState, latestValues) { + Object.assign(renderState.output, latestValues); + } + renderInstance(instance, { output }) { + Object.assign(instance, output); + } + sortInstanceNodePosition() { + return 0; + } + } + + function createDOMVisualElement(element) { + const options = { + presenceContext: null, + props: {}, + visualState: { + renderState: { + transform: {}, + transformOrigin: {}, + style: {}, + vars: {}, + attrs: {}, + }, + latestValues: {}, + }, + }; + const node = isSVGElement(element) && !isSVGSVGElement(element) + ? new SVGVisualElement(options) + : new HTMLVisualElement(options); + node.mount(element); + visualElementStore.set(element, node); + } + function createObjectVisualElement(subject) { + const options = { + presenceContext: null, + props: {}, + visualState: { + renderState: { + output: {}, + }, + latestValues: {}, + }, + }; + const node = new ObjectVisualElement(options); + node.mount(subject); + visualElementStore.set(subject, node); + } + + function isSingleValue(subject, keyframes) { + return (isMotionValue(subject) || + typeof subject === "number" || + (typeof subject === "string" && !isDOMKeyframes(keyframes))); + } + /** + * Implementation + */ + function animateSubject(subject, keyframes, options, scope) { + const animations = []; + if (isSingleValue(subject, keyframes)) { + animations.push(animateSingleValue(subject, isDOMKeyframes(keyframes) + ? keyframes.default || keyframes + : keyframes, options ? options.default || options : options)); + } + else { + const subjects = resolveSubjects(subject, keyframes, scope); + const numSubjects = subjects.length; + exports.invariant(Boolean(numSubjects), "No valid elements provided.", "no-valid-elements"); + for (let i = 0; i < numSubjects; i++) { + const thisSubject = subjects[i]; + exports.invariant(thisSubject !== null, "You're trying to perform an animation on null. Ensure that selectors are correctly finding elements and refs are correctly hydrated.", "animate-null"); + const createVisualElement = thisSubject instanceof Element + ? createDOMVisualElement + : createObjectVisualElement; + if (!visualElementStore.has(thisSubject)) { + createVisualElement(thisSubject); + } + const visualElement = visualElementStore.get(thisSubject); + const transition = { ...options }; + /** + * Resolve stagger function if provided. + */ + if ("delay" in transition && + typeof transition.delay === "function") { + transition.delay = transition.delay(i, numSubjects); + } + animations.push(...animateTarget(visualElement, { ...keyframes, transition }, {})); + } + } + return animations; + } + + function animateSequence(sequence, options, scope) { + const animations = []; + const animationDefinitions = createAnimationsFromSequence(sequence, options, scope, { spring }); + animationDefinitions.forEach(({ keyframes, transition }, subject) => { + animations.push(...animateSubject(subject, keyframes, transition)); + }); + return animations; + } + + function isSequence(value) { + return Array.isArray(value) && value.some(Array.isArray); + } + /** + * Creates an animation function that is optionally scoped + * to a specific element. + */ + function createScopedAnimate(scope) { + /** + * Implementation + */ + function scopedAnimate(subjectOrSequence, optionsOrKeyframes, options) { + let animations = []; + if (isSequence(subjectOrSequence)) { + animations = animateSequence(subjectOrSequence, optionsOrKeyframes, scope); + } + else { + animations = animateSubject(subjectOrSequence, optionsOrKeyframes, options, scope); + } + const animation = new GroupAnimationWithThen(animations); + if (scope) { + scope.animations.push(animation); + animation.finished.then(() => { + removeItem(scope.animations, animation); + }); + } + return animation; + } + return scopedAnimate; + } + const animate = createScopedAnimate(); + + function animateElements(elementOrSelector, keyframes, options, scope) { + const elements = resolveElements(elementOrSelector, scope); + const numElements = elements.length; + exports.invariant(Boolean(numElements), "No valid elements provided.", "no-valid-elements"); + /** + * WAAPI doesn't support interrupting animations. + * + * Therefore, starting animations requires a three-step process: + * 1. Stop existing animations (write styles to DOM) + * 2. Resolve keyframes (read styles from DOM) + * 3. Create new animations (write styles to DOM) + * + * The hybrid `animate()` function uses AsyncAnimation to resolve + * keyframes before creating new animations, which removes style + * thrashing. Here, we have much stricter filesize constraints. + * Therefore we do this in a synchronous way that ensures that + * at least within `animate()` calls there is no style thrashing. + * + * In the motion-native-animate-mini-interrupt benchmark this + * was 80% faster than a single loop. + */ + const animationDefinitions = []; + /** + * Step 1: Build options and stop existing animations (write) + */ + for (let i = 0; i < numElements; i++) { + const element = elements[i]; + const elementTransition = { ...options }; + /** + * Resolve stagger function if provided. + */ + if (typeof elementTransition.delay === "function") { + elementTransition.delay = elementTransition.delay(i, numElements); + } + for (const valueName in keyframes) { + let valueKeyframes = keyframes[valueName]; + if (!Array.isArray(valueKeyframes)) { + valueKeyframes = [valueKeyframes]; + } + const valueOptions = { + ...getValueTransition$1(elementTransition, valueName), + }; + valueOptions.duration && (valueOptions.duration = secondsToMilliseconds(valueOptions.duration)); + valueOptions.delay && (valueOptions.delay = secondsToMilliseconds(valueOptions.delay)); + /** + * If there's an existing animation playing on this element then stop it + * before creating a new one. + */ + const map = getAnimationMap(element); + const key = animationMapKey(valueName, valueOptions.pseudoElement || ""); + const currentAnimation = map.get(key); + currentAnimation && currentAnimation.stop(); + animationDefinitions.push({ + map, + key, + unresolvedKeyframes: valueKeyframes, + options: { + ...valueOptions, + element, + name: valueName, + allowFlatten: !elementTransition.type && !elementTransition.ease, + }, + }); + } + } + /** + * Step 2: Resolve keyframes (read) + */ + for (let i = 0; i < animationDefinitions.length; i++) { + const { unresolvedKeyframes, options: animationOptions } = animationDefinitions[i]; + const { element, name, pseudoElement } = animationOptions; + if (!pseudoElement && unresolvedKeyframes[0] === null) { + unresolvedKeyframes[0] = getComputedStyle$2(element, name); + } + fillWildcards(unresolvedKeyframes); + applyPxDefaults(unresolvedKeyframes, name); + /** + * If we only have one keyframe, explicitly read the initial keyframe + * from the computed style. This is to ensure consistency with WAAPI behaviour + * for restarting animations, for instance .play() after finish, when it + * has one vs two keyframes. + */ + if (!pseudoElement && unresolvedKeyframes.length < 2) { + unresolvedKeyframes.unshift(getComputedStyle$2(element, name)); + } + animationOptions.keyframes = unresolvedKeyframes; + } + /** + * Step 3: Create new animations (write) + */ + const animations = []; + for (let i = 0; i < animationDefinitions.length; i++) { + const { map, key, options: animationOptions } = animationDefinitions[i]; + const animation = new NativeAnimation(animationOptions); + map.set(key, animation); + animation.finished.finally(() => map.delete(key)); + animations.push(animation); + } + return animations; + } + + const createScopedWaapiAnimate = (scope) => { + function scopedAnimate(elementOrSelector, keyframes, options) { + return new GroupAnimationWithThen(animateElements(elementOrSelector, keyframes, options, scope)); + } + return scopedAnimate; + }; + const animateMini = /*@__PURE__*/ createScopedWaapiAnimate(); + + /** + * A time in milliseconds, beyond which we consider the scroll velocity to be 0. + */ + const maxElapsed = 50; + const createAxisInfo = () => ({ + current: 0, + offset: [], + progress: 0, + scrollLength: 0, + targetOffset: 0, + targetLength: 0, + containerLength: 0, + velocity: 0, + }); + const createScrollInfo = () => ({ + time: 0, + x: createAxisInfo(), + y: createAxisInfo(), + }); + const keys = { + x: { + length: "Width", + position: "Left", + }, + y: { + length: "Height", + position: "Top", + }, + }; + function updateAxisInfo(element, axisName, info, time) { + const axis = info[axisName]; + const { length, position } = keys[axisName]; + const prev = axis.current; + const prevTime = info.time; + axis.current = element[`scroll${position}`]; + axis.scrollLength = element[`scroll${length}`] - element[`client${length}`]; + axis.offset.length = 0; + axis.offset[0] = 0; + axis.offset[1] = axis.scrollLength; + axis.progress = progress(0, axis.scrollLength, axis.current); + const elapsed = time - prevTime; + axis.velocity = + elapsed > maxElapsed + ? 0 + : velocityPerSecond(axis.current - prev, elapsed); + } + function updateScrollInfo(element, info, time) { + updateAxisInfo(element, "x", info, time); + updateAxisInfo(element, "y", info, time); + info.time = time; + } + + function calcInset(element, container) { + const inset = { x: 0, y: 0 }; + let current = element; + while (current && current !== container) { + if (isHTMLElement(current)) { + inset.x += current.offsetLeft; + inset.y += current.offsetTop; + current = current.offsetParent; + } + else if (current.tagName === "svg") { + /** + * This isn't an ideal approach to measuring the offset of tags. + * It would be preferable, given they behave like HTMLElements in most ways + * to use offsetLeft/Top. But these don't exist on . Likewise we + * can't use .getBBox() like most SVG elements as these provide the offset + * relative to the SVG itself, which for is usually 0x0. + */ + const svgBoundingBox = current.getBoundingClientRect(); + current = current.parentElement; + const parentBoundingBox = current.getBoundingClientRect(); + inset.x += svgBoundingBox.left - parentBoundingBox.left; + inset.y += svgBoundingBox.top - parentBoundingBox.top; + } + else if (current instanceof SVGGraphicsElement) { + const { x, y } = current.getBBox(); + inset.x += x; + inset.y += y; + let svg = null; + let parent = current.parentNode; + while (!svg) { + if (parent.tagName === "svg") { + svg = parent; + } + parent = current.parentNode; + } + current = svg; + } + else { + break; + } + } + return inset; + } + + const namedEdges = { + start: 0, + center: 0.5, + end: 1, + }; + function resolveEdge(edge, length, inset = 0) { + let delta = 0; + /** + * If we have this edge defined as a preset, replace the definition + * with the numerical value. + */ + if (edge in namedEdges) { + edge = namedEdges[edge]; + } + /** + * Handle unit values + */ + if (typeof edge === "string") { + const asNumber = parseFloat(edge); + if (edge.endsWith("px")) { + delta = asNumber; + } + else if (edge.endsWith("%")) { + edge = asNumber / 100; + } + else if (edge.endsWith("vw")) { + delta = (asNumber / 100) * document.documentElement.clientWidth; + } + else if (edge.endsWith("vh")) { + delta = (asNumber / 100) * document.documentElement.clientHeight; + } + else { + edge = asNumber; + } + } + /** + * If the edge is defined as a number, handle as a progress value. + */ + if (typeof edge === "number") { + delta = length * edge; + } + return inset + delta; + } + + const defaultOffset = [0, 0]; + function resolveOffset(offset, containerLength, targetLength, targetInset) { + let offsetDefinition = Array.isArray(offset) ? offset : defaultOffset; + let targetPoint = 0; + let containerPoint = 0; + if (typeof offset === "number") { + /** + * If we're provided offset: [0, 0.5, 1] then each number x should become + * [x, x], so we default to the behaviour of mapping 0 => 0 of both target + * and container etc. + */ + offsetDefinition = [offset, offset]; + } + else if (typeof offset === "string") { + offset = offset.trim(); + if (offset.includes(" ")) { + offsetDefinition = offset.split(" "); + } + else { + /** + * If we're provided a definition like "100px" then we want to apply + * that only to the top of the target point, leaving the container at 0. + * Whereas a named offset like "end" should be applied to both. + */ + offsetDefinition = [offset, namedEdges[offset] ? offset : `0`]; + } + } + targetPoint = resolveEdge(offsetDefinition[0], targetLength, targetInset); + containerPoint = resolveEdge(offsetDefinition[1], containerLength); + return targetPoint - containerPoint; + } + + const ScrollOffset = { + Enter: [ + [0, 1], + [1, 1], + ], + Exit: [ + [0, 0], + [1, 0], + ], + Any: [ + [1, 0], + [0, 1], + ], + All: [ + [0, 0], + [1, 1], + ], + }; + + const point = { x: 0, y: 0 }; + function getTargetSize(target) { + return "getBBox" in target && target.tagName !== "svg" + ? target.getBBox() + : { width: target.clientWidth, height: target.clientHeight }; + } + function resolveOffsets(container, info, options) { + const { offset: offsetDefinition = ScrollOffset.All } = options; + const { target = container, axis = "y" } = options; + const lengthLabel = axis === "y" ? "height" : "width"; + const inset = target !== container ? calcInset(target, container) : point; + /** + * Measure the target and container. If they're the same thing then we + * use the container's scrollWidth/Height as the target, from there + * all other calculations can remain the same. + */ + const targetSize = target === container + ? { width: container.scrollWidth, height: container.scrollHeight } + : getTargetSize(target); + const containerSize = { + width: container.clientWidth, + height: container.clientHeight, + }; + /** + * Reset the length of the resolved offset array rather than creating a new one. + * TODO: More reusable data structures for targetSize/containerSize would also be good. + */ + info[axis].offset.length = 0; + /** + * Populate the offset array by resolving the user's offset definition into + * a list of pixel scroll offets. + */ + let hasChanged = !info[axis].interpolate; + const numOffsets = offsetDefinition.length; + for (let i = 0; i < numOffsets; i++) { + const offset = resolveOffset(offsetDefinition[i], containerSize[lengthLabel], targetSize[lengthLabel], inset[axis]); + if (!hasChanged && offset !== info[axis].interpolatorOffsets[i]) { + hasChanged = true; + } + info[axis].offset[i] = offset; + } + /** + * If the pixel scroll offsets have changed, create a new interpolator function + * to map scroll value into a progress. + */ + if (hasChanged) { + info[axis].interpolate = interpolate(info[axis].offset, defaultOffset$1(offsetDefinition), { clamp: false }); + info[axis].interpolatorOffsets = [...info[axis].offset]; + } + info[axis].progress = clamp(0, 1, info[axis].interpolate(info[axis].current)); + } + + function measure(container, target = container, info) { + /** + * Find inset of target within scrollable container + */ + info.x.targetOffset = 0; + info.y.targetOffset = 0; + if (target !== container) { + let node = target; + while (node && node !== container) { + info.x.targetOffset += node.offsetLeft; + info.y.targetOffset += node.offsetTop; + node = node.offsetParent; + } + } + info.x.targetLength = + target === container ? target.scrollWidth : target.clientWidth; + info.y.targetLength = + target === container ? target.scrollHeight : target.clientHeight; + info.x.containerLength = container.clientWidth; + info.y.containerLength = container.clientHeight; + /** + * In development mode ensure scroll containers aren't position: static as this makes + * it difficult to measure their relative positions. + */ + { + if (container && target && target !== container) { + warnOnce(getComputedStyle(container).position !== "static", "Please ensure that the container has a non-static position, like 'relative', 'fixed', or 'absolute' to ensure scroll offset is calculated correctly."); + } + } + } + function createOnScrollHandler(element, onScroll, info, options = {}) { + return { + measure: (time) => { + measure(element, options.target, info); + updateScrollInfo(element, info, time); + if (options.offset || options.target) { + resolveOffsets(element, info, options); + } + }, + notify: () => onScroll(info), + }; + } + + const scrollListeners = new WeakMap(); + const resizeListeners = new WeakMap(); + const onScrollHandlers = new WeakMap(); + const getEventTarget = (element) => element === document.scrollingElement ? window : element; + function scrollInfo(onScroll, { container = document.scrollingElement, ...options } = {}) { + if (!container) + return noop; + let containerHandlers = onScrollHandlers.get(container); + /** + * Get the onScroll handlers for this container. + * If one isn't found, create a new one. + */ + if (!containerHandlers) { + containerHandlers = new Set(); + onScrollHandlers.set(container, containerHandlers); + } + /** + * Create a new onScroll handler for the provided callback. + */ + const info = createScrollInfo(); + const containerHandler = createOnScrollHandler(container, onScroll, info, options); + containerHandlers.add(containerHandler); + /** + * Check if there's a scroll event listener for this container. + * If not, create one. + */ + if (!scrollListeners.has(container)) { + const measureAll = () => { + for (const handler of containerHandlers) { + handler.measure(frameData.timestamp); + } + frame.preUpdate(notifyAll); + }; + const notifyAll = () => { + for (const handler of containerHandlers) { + handler.notify(); + } + }; + const listener = () => frame.read(measureAll); + scrollListeners.set(container, listener); + const target = getEventTarget(container); + window.addEventListener("resize", listener, { passive: true }); + if (container !== document.documentElement) { + resizeListeners.set(container, resize(container, listener)); + } + target.addEventListener("scroll", listener, { passive: true }); + listener(); + } + const listener = scrollListeners.get(container); + frame.read(listener, false, true); + return () => { + cancelFrame(listener); + /** + * Check if we even have any handlers for this container. + */ + const currentHandlers = onScrollHandlers.get(container); + if (!currentHandlers) + return; + currentHandlers.delete(containerHandler); + if (currentHandlers.size) + return; + /** + * If no more handlers, remove the scroll listener too. + */ + const scrollListener = scrollListeners.get(container); + scrollListeners.delete(container); + if (scrollListener) { + getEventTarget(container).removeEventListener("scroll", scrollListener); + resizeListeners.get(container)?.(); + window.removeEventListener("resize", scrollListener); + } + }; + } + + const timelineCache = new Map(); + function scrollTimelineFallback(options) { + const currentTime = { value: 0 }; + const cancel = scrollInfo((info) => { + currentTime.value = info[options.axis].progress * 100; + }, options); + return { currentTime, cancel }; + } + function getTimeline({ source, container, ...options }) { + const { axis } = options; + if (source) + container = source; + const containerCache = timelineCache.get(container) ?? new Map(); + timelineCache.set(container, containerCache); + const targetKey = options.target ?? "self"; + const targetCache = containerCache.get(targetKey) ?? {}; + const axisKey = axis + (options.offset ?? []).join(","); + if (!targetCache[axisKey]) { + targetCache[axisKey] = + !options.target && supportsScrollTimeline() + ? new ScrollTimeline({ source: container, axis }) + : scrollTimelineFallback({ container, ...options }); + } + return targetCache[axisKey]; + } + + function attachToAnimation(animation, options) { + const timeline = getTimeline(options); + return animation.attachTimeline({ + timeline: options.target ? undefined : timeline, + observe: (valueAnimation) => { + valueAnimation.pause(); + return observeTimeline((progress) => { + valueAnimation.time = valueAnimation.duration * progress; + }, timeline); + }, + }); + } + + /** + * If the onScroll function has two arguments, it's expecting + * more specific information about the scroll from scrollInfo. + */ + function isOnScrollWithInfo(onScroll) { + return onScroll.length === 2; + } + function attachToFunction(onScroll, options) { + if (isOnScrollWithInfo(onScroll)) { + return scrollInfo((info) => { + onScroll(info[options.axis].progress, info); + }, options); + } + else { + return observeTimeline(onScroll, getTimeline(options)); + } + } + + function scroll(onScroll, { axis = "y", container = document.scrollingElement, ...options } = {}) { + if (!container) + return noop; + const optionsWithDefaults = { axis, container, ...options }; + return typeof onScroll === "function" + ? attachToFunction(onScroll, optionsWithDefaults) + : attachToAnimation(onScroll, optionsWithDefaults); + } + + const thresholds = { + some: 0, + all: 1, + }; + function inView(elementOrSelector, onStart, { root, margin: rootMargin, amount = "some" } = {}) { + const elements = resolveElements(elementOrSelector); + const activeIntersections = new WeakMap(); + const onIntersectionChange = (entries) => { + entries.forEach((entry) => { + const onEnd = activeIntersections.get(entry.target); + /** + * If there's no change to the intersection, we don't need to + * do anything here. + */ + if (entry.isIntersecting === Boolean(onEnd)) + return; + if (entry.isIntersecting) { + const newOnEnd = onStart(entry.target, entry); + if (typeof newOnEnd === "function") { + activeIntersections.set(entry.target, newOnEnd); + } + else { + observer.unobserve(entry.target); + } + } + else if (typeof onEnd === "function") { + onEnd(entry); + activeIntersections.delete(entry.target); + } + }); + }; + const observer = new IntersectionObserver(onIntersectionChange, { + root, + rootMargin, + threshold: typeof amount === "number" ? amount : thresholds[amount], + }); + elements.forEach((element) => observer.observe(element)); + return () => observer.disconnect(); + } + + const m = /*@__PURE__*/ createMotionProxy(); + + function useUnmountEffect(callback) { + return React$1.useEffect(() => () => callback(), []); + } + + /** + * @public + */ + const domAnimation = { + renderer: createDomVisualElement, + ...animations, + ...gestureAnimations, + }; + + /** + * @public + */ + const domMax = { + ...domAnimation, + ...drag, + ...layout, + }; + + /** + * @public + */ + const domMin = { + renderer: createDomVisualElement, + ...animations, + }; + + function useMotionValueEvent(value, event, callback) { + /** + * useInsertionEffect will create subscriptions before any other + * effects will run. Effects run upwards through the tree so it + * can be that binding a useLayoutEffect higher up the tree can + * miss changes from lower down the tree. + */ + React$1.useInsertionEffect(() => value.on(event, callback), [value, event, callback]); + } + + const createScrollMotionValues = () => ({ + scrollX: motionValue(0), + scrollY: motionValue(0), + scrollXProgress: motionValue(0), + scrollYProgress: motionValue(0), + }); + const isRefPending = (ref) => { + if (!ref) + return false; + return !ref.current; + }; + function useScroll({ container, target, ...options } = {}) { + const values = useConstant(createScrollMotionValues); + const scrollAnimation = React$1.useRef(null); + const needsStart = React$1.useRef(false); + const start = React$1.useCallback(() => { + scrollAnimation.current = scroll((_progress, { x, y, }) => { + values.scrollX.set(x.current); + values.scrollXProgress.set(x.progress); + values.scrollY.set(y.current); + values.scrollYProgress.set(y.progress); + }, { + ...options, + container: container?.current || undefined, + target: target?.current || undefined, + }); + return () => { + scrollAnimation.current?.(); + }; + }, [container, target, JSON.stringify(options.offset)]); + useIsomorphicLayoutEffect(() => { + needsStart.current = false; + if (isRefPending(container) || isRefPending(target)) { + needsStart.current = true; + return; + } + else { + return start(); + } + }, [start]); + React$1.useEffect(() => { + if (needsStart.current) { + exports.invariant(!isRefPending(container), "Container ref is defined but not hydrated", "use-scroll-ref"); + exports.invariant(!isRefPending(target), "Target ref is defined but not hydrated", "use-scroll-ref"); + return start(); + } + else { + return; + } + }, [start]); + return values; + } + + /** + * @deprecated useElementScroll is deprecated. Convert to useScroll({ container: ref }) + */ + function useElementScroll(ref) { + { + warnOnce(false, "useElementScroll is deprecated. Convert to useScroll({ container: ref })."); + } + return useScroll({ container: ref }); + } + + /** + * @deprecated useViewportScroll is deprecated. Convert to useScroll() + */ + function useViewportScroll() { + { + warnOnce(false, "useViewportScroll is deprecated. Convert to useScroll()."); + } + return useScroll(); + } + + /** + * Combine multiple motion values into a new one using a string template literal. + * + * ```jsx + * import { + * motion, + * useSpring, + * useMotionValue, + * useMotionTemplate + * } from "framer-motion" + * + * function Component() { + * const shadowX = useSpring(0) + * const shadowY = useMotionValue(0) + * const shadow = useMotionTemplate`drop-shadow(${shadowX}px ${shadowY}px 20px rgba(0,0,0,0.3))` + * + * return + * } + * ``` + * + * @public + */ + function useMotionTemplate(fragments, ...values) { + /** + * Create a function that will build a string from the latest motion values. + */ + const numFragments = fragments.length; + function buildValue() { + let output = ``; + for (let i = 0; i < numFragments; i++) { + output += fragments[i]; + const value = values[i]; + if (value) { + output += isMotionValue(value) ? value.get() : value; + } + } + return output; + } + return useCombineMotionValues(values.filter(isMotionValue), buildValue); + } + + function useSpring(source, options = {}) { + const { isStatic } = React$1.useContext(MotionConfigContext); + const getFromSource = () => (isMotionValue(source) ? source.get() : source); + // isStatic will never change, allowing early hooks return + if (isStatic) { + return useTransform(getFromSource); + } + const value = useMotionValue(getFromSource()); + React$1.useInsertionEffect(() => { + return attachSpring(value, source, options); + }, [value, JSON.stringify(options)]); + return value; + } + + function useAnimationFrame(callback) { + const initialTimestamp = React$1.useRef(0); + const { isStatic } = React$1.useContext(MotionConfigContext); + React$1.useEffect(() => { + if (isStatic) + return; + const provideTimeSinceStart = ({ timestamp, delta }) => { + if (!initialTimestamp.current) + initialTimestamp.current = timestamp; + callback(timestamp - initialTimestamp.current, delta); + }; + frame.update(provideTimeSinceStart, true); + return () => cancelFrame(provideTimeSinceStart); + }, [callback]); + } + + function useTime() { + const time = useMotionValue(0); + useAnimationFrame((t) => time.set(t)); + return time; + } + + /** + * Creates a `MotionValue` that updates when the velocity of the provided `MotionValue` changes. + * + * ```javascript + * const x = useMotionValue(0) + * const xVelocity = useVelocity(x) + * const xAcceleration = useVelocity(xVelocity) + * ``` + * + * @public + */ + function useVelocity(value) { + const velocity = useMotionValue(value.getVelocity()); + const updateVelocity = () => { + const latest = value.getVelocity(); + velocity.set(latest); + /** + * If we still have velocity, schedule an update for the next frame + * to keep checking until it is zero. + */ + if (latest) + frame.update(updateVelocity); + }; + useMotionValueEvent(value, "change", () => { + // Schedule an update to this value at the end of the current frame. + frame.update(updateVelocity, false, true); + }); + return velocity; + } + + class WillChangeMotionValue extends MotionValue { + constructor() { + super(...arguments); + this.isEnabled = false; + } + add(name) { + if (transformProps.has(name) || acceleratedValues.has(name)) { + this.isEnabled = true; + this.update(); + } + } + update() { + this.set(this.isEnabled ? "transform" : "auto"); + } + } + + function useWillChange() { + return useConstant(() => new WillChangeMotionValue("auto")); + } + + /** + * A hook that returns `true` if we should be using reduced motion based on the current device's Reduced Motion setting. + * + * This can be used to implement changes to your UI based on Reduced Motion. For instance, replacing motion-sickness inducing + * `x`/`y` animations with `opacity`, disabling the autoplay of background videos, or turning off parallax motion. + * + * It will actively respond to changes and re-render your components with the latest setting. + * + * ```jsx + * export function Sidebar({ isOpen }) { + * const shouldReduceMotion = useReducedMotion() + * const closedX = shouldReduceMotion ? 0 : "-100%" + * + * return ( + * + * ) + * } + * ``` + * + * @return boolean + * + * @public + */ + function useReducedMotion() { + /** + * Lazy initialisation of prefersReducedMotion + */ + !hasReducedMotionListener.current && initPrefersReducedMotion(); + const [shouldReduceMotion] = React$1.useState(prefersReducedMotion.current); + { + warnOnce(shouldReduceMotion !== true, "You have Reduced Motion enabled on your device. Animations may not appear as expected.", "reduced-motion-disabled"); + } + /** + * TODO See if people miss automatically updating shouldReduceMotion setting + */ + return shouldReduceMotion; + } + + function useReducedMotionConfig() { + const reducedMotionPreference = useReducedMotion(); + const { reducedMotion } = React$1.useContext(MotionConfigContext); + if (reducedMotion === "never") { + return false; + } + else if (reducedMotion === "always") { + return true; + } + else { + return reducedMotionPreference; + } + } + + function stopAnimation(visualElement) { + visualElement.values.forEach((value) => value.stop()); + } + function setVariants(visualElement, variantLabels) { + const reversedLabels = [...variantLabels].reverse(); + reversedLabels.forEach((key) => { + const variant = visualElement.getVariant(key); + variant && setTarget(visualElement, variant); + if (visualElement.variantChildren) { + visualElement.variantChildren.forEach((child) => { + setVariants(child, variantLabels); + }); + } + }); + } + function setValues(visualElement, definition) { + if (Array.isArray(definition)) { + return setVariants(visualElement, definition); + } + else if (typeof definition === "string") { + return setVariants(visualElement, [definition]); + } + else { + setTarget(visualElement, definition); + } + } + /** + * @public + */ + function animationControls() { + /** + * Track whether the host component has mounted. + */ + let hasMounted = false; + /** + * A collection of linked component animation controls. + */ + const subscribers = new Set(); + const controls = { + subscribe(visualElement) { + subscribers.add(visualElement); + return () => void subscribers.delete(visualElement); + }, + start(definition, transitionOverride) { + exports.invariant(hasMounted, "controls.start() should only be called after a component has mounted. Consider calling within a useEffect hook."); + const animations = []; + subscribers.forEach((visualElement) => { + animations.push(animateVisualElement(visualElement, definition, { + transitionOverride, + })); + }); + return Promise.all(animations); + }, + set(definition) { + exports.invariant(hasMounted, "controls.set() should only be called after a component has mounted. Consider calling within a useEffect hook."); + return subscribers.forEach((visualElement) => { + setValues(visualElement, definition); + }); + }, + stop() { + subscribers.forEach((visualElement) => { + stopAnimation(visualElement); + }); + }, + mount() { + hasMounted = true; + return () => { + hasMounted = false; + controls.stop(); + }; + }, + }; + return controls; + } + + function useAnimate() { + const scope = useConstant(() => ({ + current: null, // Will be hydrated by React + animations: [], + })); + const animate = useConstant(() => createScopedAnimate(scope)); + useUnmountEffect(() => { + scope.animations.forEach((animation) => animation.stop()); + scope.animations.length = 0; + }); + return [scope, animate]; + } + + function useAnimateMini() { + const scope = useConstant(() => ({ + current: null, // Will be hydrated by React + animations: [], + })); + const animate = useConstant(() => createScopedWaapiAnimate(scope)); + useUnmountEffect(() => { + scope.animations.forEach((animation) => animation.stop()); + }); + return [scope, animate]; + } + + /** + * Creates `LegacyAnimationControls`, which can be used to manually start, stop + * and sequence animations on one or more components. + * + * The returned `LegacyAnimationControls` should be passed to the `animate` property + * of the components you want to animate. + * + * These components can then be animated with the `start` method. + * + * ```jsx + * import * as React from 'react' + * import { motion, useAnimation } from 'framer-motion' + * + * export function MyComponent(props) { + * const controls = useAnimation() + * + * controls.start({ + * x: 100, + * transition: { duration: 0.5 }, + * }) + * + * return + * } + * ``` + * + * @returns Animation controller with `start` and `stop` methods + * + * @public + */ + function useAnimationControls() { + const controls = useConstant(animationControls); + useIsomorphicLayoutEffect(controls.mount, []); + return controls; + } + const useAnimation = useAnimationControls; + + function usePresenceData() { + const context = React$1.useContext(PresenceContext); + return context ? context.custom : undefined; + } + + /** + * Attaches an event listener directly to the provided DOM element. + * + * Bypassing React's event system can be desirable, for instance when attaching non-passive + * event handlers. + * + * ```jsx + * const ref = useRef(null) + * + * useDomEvent(ref, 'wheel', onWheel, { passive: false }) + * + * return
+ * ``` + * + * @param ref - React.RefObject that's been provided to the element you want to bind the listener to. + * @param eventName - Name of the event you want listen for. + * @param handler - Function to fire when receiving the event. + * @param options - Options to pass to `Event.addEventListener`. + * + * @public + */ + function useDomEvent(ref, eventName, handler, options) { + React$1.useEffect(() => { + const element = ref.current; + if (handler && element) { + return addDomEvent(element, eventName, handler, options); + } + }, [ref, eventName, handler, options]); + } + + /** + * Can manually trigger a drag gesture on one or more `drag`-enabled `motion` components. + * + * ```jsx + * const dragControls = useDragControls() + * + * function startDrag(event) { + * dragControls.start(event, { snapToCursor: true }) + * } + * + * return ( + * <> + *
+ * + * + * ) + * ``` + * + * @public + */ + class DragControls { + constructor() { + this.componentControls = new Set(); + } + /** + * Subscribe a component's internal `VisualElementDragControls` to the user-facing API. + * + * @internal + */ + subscribe(controls) { + this.componentControls.add(controls); + return () => this.componentControls.delete(controls); + } + /** + * Start a drag gesture on every `motion` component that has this set of drag controls + * passed into it via the `dragControls` prop. + * + * ```jsx + * dragControls.start(e, { + * snapToCursor: true + * }) + * ``` + * + * @param event - PointerEvent + * @param options - Options + * + * @public + */ + start(event, options) { + this.componentControls.forEach((controls) => { + controls.start(event.nativeEvent || event, options); + }); + } + /** + * Cancels a drag gesture. + * + * ```jsx + * dragControls.cancel() + * ``` + * + * @public + */ + cancel() { + this.componentControls.forEach((controls) => { + controls.cancel(); + }); + } + /** + * Stops a drag gesture. + * + * ```jsx + * dragControls.stop() + * ``` + * + * @public + */ + stop() { + this.componentControls.forEach((controls) => { + controls.stop(); + }); + } + } + const createDragControls = () => new DragControls(); + /** + * Usually, dragging is initiated by pressing down on a `motion` component with a `drag` prop + * and moving it. For some use-cases, for instance clicking at an arbitrary point on a video scrubber, we + * might want to initiate that dragging from a different component than the draggable one. + * + * By creating a `dragControls` using the `useDragControls` hook, we can pass this into + * the draggable component's `dragControls` prop. It exposes a `start` method + * that can start dragging from pointer events on other components. + * + * ```jsx + * const dragControls = useDragControls() + * + * function startDrag(event) { + * dragControls.start(event, { snapToCursor: true }) + * } + * + * return ( + * <> + *
+ * + * + * ) + * ``` + * + * @public + */ + function useDragControls() { + return useConstant(createDragControls); + } + + /** + * Checks if a component is a `motion` component. + */ + function isMotionComponent(component) { + return (component !== null && + typeof component === "object" && + motionComponentSymbol in component); + } + + /** + * Unwraps a `motion` component and returns either a string for `motion.div` or + * the React component for `motion(Component)`. + * + * If the component is not a `motion` component it returns undefined. + */ + function unwrapMotionComponent(component) { + if (isMotionComponent(component)) { + return component[motionComponentSymbol]; + } + return undefined; + } + + function useInstantLayoutTransition() { + return startTransition; + } + function startTransition(callback) { + if (!rootProjectionNode.current) + return; + rootProjectionNode.current.isUpdating = false; + rootProjectionNode.current.blockUpdate(); + callback && callback(); + } + + function useResetProjection() { + const reset = React$1.useCallback(() => { + const root = rootProjectionNode.current; + if (!root) + return; + root.resetTree(); + }, []); + return reset; + } + + /** + * Cycles through a series of visual properties. Can be used to toggle between or cycle through animations. It works similar to `useState` in React. It is provided an initial array of possible states, and returns an array of two arguments. + * + * An index value can be passed to the returned `cycle` function to cycle to a specific index. + * + * ```jsx + * import * as React from "react" + * import { motion, useCycle } from "framer-motion" + * + * export const MyComponent = () => { + * const [x, cycleX] = useCycle(0, 50, 100) + * + * return ( + * cycleX()} + * /> + * ) + * } + * ``` + * + * @param items - items to cycle through + * @returns [currentState, cycleState] + * + * @public + */ + function useCycle(...items) { + const index = React$1.useRef(0); + const [item, setItem] = React$1.useState(items[index.current]); + const runCycle = React$1.useCallback((next) => { + index.current = + typeof next !== "number" + ? wrap(0, items.length, index.current + 1) + : next; + setItem(items[index.current]); + }, + // The array will change on each call, but by putting items.length at + // the front of this array, we guarantee the dependency comparison will match up + // eslint-disable-next-line react-hooks/exhaustive-deps + [items.length, ...items]); + return [item, runCycle]; + } + + function useInView(ref, { root, margin, amount, once = false, initial = false, } = {}) { + const [isInView, setInView] = React$1.useState(initial); + React$1.useEffect(() => { + if (!ref.current || (once && isInView)) + return; + const onEnter = () => { + setInView(true); + return once ? undefined : () => setInView(false); + }; + const options = { + root: (root && root.current) || undefined, + margin, + amount, + }; + return inView(ref.current, onEnter, options); + }, [root, ref, margin, once, amount]); + return isInView; + } + + function useInstantTransition() { + const [forceUpdate, forcedRenderCount] = useForceUpdate(); + const startInstantLayoutTransition = useInstantLayoutTransition(); + const unlockOnFrameRef = React$1.useRef(-1); + React$1.useEffect(() => { + /** + * Unblock after two animation frames, otherwise this will unblock too soon. + */ + frame.postRender(() => frame.postRender(() => { + /** + * If the callback has been called again after the effect + * triggered this 2 frame delay, don't unblock animations. This + * prevents the previous effect from unblocking the current + * instant transition too soon. This becomes more likely when + * used in conjunction with React.startTransition(). + */ + if (forcedRenderCount !== unlockOnFrameRef.current) + return; + MotionGlobalConfig.instantAnimations = false; + })); + }, [forcedRenderCount]); + return (callback) => { + startInstantLayoutTransition(() => { + MotionGlobalConfig.instantAnimations = true; + forceUpdate(); + callback(); + unlockOnFrameRef.current = forcedRenderCount + 1; + }); + }; + } + function disableInstantTransitions() { + MotionGlobalConfig.instantAnimations = false; + } + + function usePageInView() { + const [isInView, setIsInView] = React$1.useState(true); + React$1.useEffect(() => { + const handleVisibilityChange = () => setIsInView(!document.hidden); + if (document.hidden) { + handleVisibilityChange(); + } + document.addEventListener("visibilitychange", handleVisibilityChange); + return () => { + document.removeEventListener("visibilitychange", handleVisibilityChange); + }; + }, []); + return isInView; + } + + const appearAnimationStore = new Map(); + const appearComplete = new Map(); + + const appearStoreId = (elementId, valueName) => { + const key = transformProps.has(valueName) ? "transform" : valueName; + return `${elementId}: ${key}`; + }; + + function handoffOptimizedAppearAnimation(elementId, valueName, frame) { + const storeId = appearStoreId(elementId, valueName); + const optimisedAnimation = appearAnimationStore.get(storeId); + if (!optimisedAnimation) { + return null; + } + const { animation, startTime } = optimisedAnimation; + function cancelAnimation() { + window.MotionCancelOptimisedAnimation?.(elementId, valueName, frame); + } + /** + * We can cancel the animation once it's finished now that we've synced + * with Motion. + * + * Prefer onfinish over finished as onfinish is backwards compatible with + * older browsers. + */ + animation.onfinish = cancelAnimation; + if (startTime === null || window.MotionHandoffIsComplete?.(elementId)) { + /** + * If the startTime is null, this animation is the Paint Ready detection animation + * and we can cancel it immediately without handoff. + * + * Or if we've already handed off the animation then we're now interrupting it. + * In which case we need to cancel it. + */ + cancelAnimation(); + return null; + } + else { + return startTime; + } + } + + /** + * A single time to use across all animations to manually set startTime + * and ensure they're all in sync. + */ + let startFrameTime; + /** + * A dummy animation to detect when Chrome is ready to start + * painting the page and hold off from triggering the real animation + * until then. We only need one animation to detect paint ready. + * + * https://bugs.chromium.org/p/chromium/issues/detail?id=1406850 + */ + let readyAnimation; + /** + * Keep track of animations that were suspended vs cancelled so we + * can easily resume them when we're done measuring layout. + */ + const suspendedAnimations = new Set(); + function resumeSuspendedAnimations() { + suspendedAnimations.forEach((data) => { + data.animation.play(); + data.animation.startTime = data.startTime; + }); + suspendedAnimations.clear(); + } + function startOptimizedAppearAnimation(element, name, keyframes, options, onReady) { + // Prevent optimised appear animations if Motion has already started animating. + if (window.MotionIsMounted) { + return; + } + const id = element.dataset[optimizedAppearDataId]; + if (!id) + return; + window.MotionHandoffAnimation = handoffOptimizedAppearAnimation; + const storeId = appearStoreId(id, name); + if (!readyAnimation) { + readyAnimation = startWaapiAnimation(element, name, [keyframes[0], keyframes[0]], + /** + * 10 secs is basically just a super-safe duration to give Chrome + * long enough to get the animation ready. + */ + { duration: 10000, ease: "linear" }); + appearAnimationStore.set(storeId, { + animation: readyAnimation, + startTime: null, + }); + /** + * If there's no readyAnimation then there's been no instantiation + * of handoff animations. + */ + window.MotionHandoffAnimation = handoffOptimizedAppearAnimation; + window.MotionHasOptimisedAnimation = (elementId, valueName) => { + if (!elementId) + return false; + /** + * Keep a map of elementIds that have started animating. We check + * via ID instead of Element because of hydration errors and + * pre-hydration checks. We also actively record IDs as they start + * animating rather than simply checking for data-appear-id as + * this attrbute might be present but not lead to an animation, for + * instance if the element's appear animation is on a different + * breakpoint. + */ + if (!valueName) { + return appearComplete.has(elementId); + } + const animationId = appearStoreId(elementId, valueName); + return Boolean(appearAnimationStore.get(animationId)); + }; + window.MotionHandoffMarkAsComplete = (elementId) => { + if (appearComplete.has(elementId)) { + appearComplete.set(elementId, true); + } + }; + window.MotionHandoffIsComplete = (elementId) => { + return appearComplete.get(elementId) === true; + }; + /** + * We only need to cancel transform animations as + * they're the ones that will interfere with the + * layout animation measurements. + */ + window.MotionCancelOptimisedAnimation = (elementId, valueName, frame, canResume) => { + const animationId = appearStoreId(elementId, valueName); + const data = appearAnimationStore.get(animationId); + if (!data) + return; + if (frame && canResume === undefined) { + /** + * Wait until the end of the subsequent frame to cancel the animation + * to ensure we don't remove the animation before the main thread has + * had a chance to resolve keyframes and render. + */ + frame.postRender(() => { + frame.postRender(() => { + data.animation.cancel(); + }); + }); + } + else { + data.animation.cancel(); + } + if (frame && canResume) { + suspendedAnimations.add(data); + frame.render(resumeSuspendedAnimations); + } + else { + appearAnimationStore.delete(animationId); + /** + * If there are no more animations left, we can remove the cancel function. + * This will let us know when we can stop checking for conflicting layout animations. + */ + if (!appearAnimationStore.size) { + window.MotionCancelOptimisedAnimation = undefined; + } + } + }; + window.MotionCheckAppearSync = (visualElement, valueName, value) => { + const appearId = getOptimisedAppearId(visualElement); + if (!appearId) + return; + const valueIsOptimised = window.MotionHasOptimisedAnimation?.(appearId, valueName); + const externalAnimationValue = visualElement.props.values?.[valueName]; + if (!valueIsOptimised || !externalAnimationValue) + return; + const removeSyncCheck = value.on("change", (latestValue) => { + if (externalAnimationValue.get() !== latestValue) { + window.MotionCancelOptimisedAnimation?.(appearId, valueName); + removeSyncCheck(); + } + }); + return removeSyncCheck; + }; + } + const startAnimation = () => { + readyAnimation.cancel(); + const appearAnimation = startWaapiAnimation(element, name, keyframes, options); + /** + * Record the time of the first started animation. We call performance.now() once + * here and once in handoff to ensure we're getting + * close to a frame-locked time. This keeps all animations in sync. + */ + if (startFrameTime === undefined) { + startFrameTime = performance.now(); + } + appearAnimation.startTime = startFrameTime; + appearAnimationStore.set(storeId, { + animation: appearAnimation, + startTime: startFrameTime, + }); + if (onReady) + onReady(appearAnimation); + }; + appearComplete.set(id, false); + if (readyAnimation.ready) { + readyAnimation.ready.then(startAnimation).catch(noop); + } + else { + startAnimation(); + } + } + + const createObject = () => ({}); + class StateVisualElement extends VisualElement { + constructor() { + super(...arguments); + this.measureInstanceViewportBox = createBox; + } + build() { } + resetTransform() { } + restoreTransform() { } + removeValueFromRenderState() { } + renderInstance() { } + scrapeMotionValuesFromProps() { + return createObject(); + } + getBaseTargetFromProps() { + return undefined; + } + readValueFromInstance(_state, key, options) { + return options.initialState[key] || 0; + } + sortInstanceNodePosition() { + return 0; + } + } + const useVisualState = makeUseVisualState({ + scrapeMotionValuesFromProps: createObject, + createRenderState: createObject, + }); + /** + * This is not an officially supported API and may be removed + * on any version. + */ + function useAnimatedState(initialState) { + const [animationState, setAnimationState] = React$1.useState(initialState); + const visualState = useVisualState({}, false); + const element = useConstant(() => { + return new StateVisualElement({ + props: { + onUpdate: (v) => { + setAnimationState({ ...v }); + }, + }, + visualState, + presenceContext: null, + }, { initialState }); + }); + React$1.useLayoutEffect(() => { + element.mount({}); + return () => element.unmount(); + }, [element]); + const startAnimation = useConstant(() => (animationDefinition) => { + return animateVisualElement(element, animationDefinition); + }); + return [animationState, startAnimation]; + } + + let id = 0; + const AnimateSharedLayout = ({ children }) => { + React__namespace.useEffect(() => { + exports.invariant(false, "AnimateSharedLayout is deprecated: https://www.framer.com/docs/guide-upgrade/##shared-layout-animations"); + }, []); + return (jsx(LayoutGroup, { id: useConstant(() => `asl-${id++}`), children: children })); + }; + + // Keep things reasonable and avoid scale: Infinity. In practise we might need + // to add another value, opacity, that could interpolate scaleX/Y [0,0.01] => [0,1] + // to simply hide content at unreasonable scales. + const maxScale = 100000; + const invertScale = (scale) => scale > 0.001 ? 1 / scale : maxScale; + let hasWarned = false; + /** + * Returns a `MotionValue` each for `scaleX` and `scaleY` that update with the inverse + * of their respective parent scales. + * + * This is useful for undoing the distortion of content when scaling a parent component. + * + * By default, `useInvertedScale` will automatically fetch `scaleX` and `scaleY` from the nearest parent. + * By passing other `MotionValue`s in as `useInvertedScale({ scaleX, scaleY })`, it will invert the output + * of those instead. + * + * ```jsx + * const MyComponent = () => { + * const { scaleX, scaleY } = useInvertedScale() + * return + * } + * ``` + * + * @deprecated + */ + function useInvertedScale(scale) { + let parentScaleX = useMotionValue(1); + let parentScaleY = useMotionValue(1); + const { visualElement } = React$1.useContext(MotionContext); + exports.invariant(!!(scale || visualElement), "If no scale values are provided, useInvertedScale must be used within a child of another motion component."); + exports.warning(hasWarned, "useInvertedScale is deprecated and will be removed in 3.0. Use the layout prop instead."); + hasWarned = true; + if (scale) { + parentScaleX = scale.scaleX || parentScaleX; + parentScaleY = scale.scaleY || parentScaleY; + } + else if (visualElement) { + parentScaleX = visualElement.getValue("scaleX", 1); + parentScaleY = visualElement.getValue("scaleY", 1); + } + const scaleX = useTransform(parentScaleX, invertScale); + const scaleY = useTransform(parentScaleY, invertScale); + return { scaleX, scaleY }; + } + + exports.AnimatePresence = AnimatePresence; + exports.AnimateSharedLayout = AnimateSharedLayout; + exports.AsyncMotionValueAnimation = AsyncMotionValueAnimation; + exports.DOMKeyframesResolver = DOMKeyframesResolver; + exports.DeprecatedLayoutGroupContext = DeprecatedLayoutGroupContext; + exports.DragControls = DragControls; + exports.FlatTree = FlatTree; + exports.GroupAnimation = GroupAnimation; + exports.GroupAnimationWithThen = GroupAnimationWithThen; + exports.JSAnimation = JSAnimation; + exports.KeyframeResolver = KeyframeResolver; + exports.LayoutGroup = LayoutGroup; + exports.LayoutGroupContext = LayoutGroupContext; + exports.LazyMotion = LazyMotion; + exports.MotionConfig = MotionConfig; + exports.MotionConfigContext = MotionConfigContext; + exports.MotionContext = MotionContext; + exports.MotionGlobalConfig = MotionGlobalConfig; + exports.MotionValue = MotionValue; + exports.NativeAnimation = NativeAnimation; + exports.NativeAnimationExtended = NativeAnimationExtended; + exports.NativeAnimationWrapper = NativeAnimationWrapper; + exports.PresenceContext = PresenceContext; + exports.Reorder = namespace; + exports.SubscriptionManager = SubscriptionManager; + exports.SwitchLayoutGroupContext = SwitchLayoutGroupContext; + exports.ViewTransitionBuilder = ViewTransitionBuilder; + exports.VisualElement = VisualElement; + exports.WillChangeMotionValue = WillChangeMotionValue; + exports.acceleratedValues = acceleratedValues; + exports.activeAnimations = activeAnimations; + exports.addAttrValue = addAttrValue; + exports.addPointerEvent = addPointerEvent; + exports.addPointerInfo = addPointerInfo; + exports.addScaleCorrector = addScaleCorrector; + exports.addStyleValue = addStyleValue; + exports.addUniqueItem = addUniqueItem; + exports.alpha = alpha; + exports.analyseComplexValue = analyseComplexValue; + exports.animate = animate; + exports.animateMini = animateMini; + exports.animateValue = animateValue; + exports.animateView = animateView; + exports.animateVisualElement = animateVisualElement; + exports.animationControls = animationControls; + exports.animationMapKey = animationMapKey; + exports.animations = animations; + exports.anticipate = anticipate; + exports.applyGeneratorOptions = applyGeneratorOptions; + exports.applyPxDefaults = applyPxDefaults; + exports.attachSpring = attachSpring; + exports.attrEffect = attrEffect; + exports.backIn = backIn; + exports.backInOut = backInOut; + exports.backOut = backOut; + exports.buildTransform = buildTransform; + exports.calcGeneratorDuration = calcGeneratorDuration; + exports.calcLength = calcLength; + exports.cancelFrame = cancelFrame; + exports.cancelMicrotask = cancelMicrotask; + exports.cancelSync = cancelSync; + exports.circIn = circIn; + exports.circInOut = circInOut; + exports.circOut = circOut; + exports.clamp = clamp; + exports.collectMotionValues = collectMotionValues; + exports.color = color; + exports.complex = complex; + exports.convertOffsetToTimes = convertOffsetToTimes; + exports.createBox = createBox; + exports.createGeneratorEasing = createGeneratorEasing; + exports.createRenderBatcher = createRenderBatcher; + exports.createScopedAnimate = createScopedAnimate; + exports.cubicBezier = cubicBezier; + exports.cubicBezierAsString = cubicBezierAsString; + exports.defaultEasing = defaultEasing; + exports.defaultOffset = defaultOffset$1; + exports.defaultTransformValue = defaultTransformValue; + exports.defaultValueTypes = defaultValueTypes; + exports.degrees = degrees; + exports.delay = delay; + exports.dimensionValueTypes = dimensionValueTypes; + exports.disableInstantTransitions = disableInstantTransitions; + exports.distance = distance; + exports.distance2D = distance2D; + exports.domAnimation = domAnimation; + exports.domMax = domMax; + exports.domMin = domMin; + exports.easeIn = easeIn; + exports.easeInOut = easeInOut; + exports.easeOut = easeOut; + exports.easingDefinitionToFunction = easingDefinitionToFunction; + exports.fillOffset = fillOffset; + exports.fillWildcards = fillWildcards; + exports.filterProps = filterProps; + exports.findDimensionValueType = findDimensionValueType; + exports.findValueType = findValueType; + exports.flushKeyframeResolvers = flushKeyframeResolvers; + exports.frame = frame; + exports.frameData = frameData; + exports.frameSteps = frameSteps; + exports.generateLinearEasing = generateLinearEasing; + exports.getAnimatableNone = getAnimatableNone; + exports.getAnimationMap = getAnimationMap; + exports.getComputedStyle = getComputedStyle$2; + exports.getDefaultValueType = getDefaultValueType; + exports.getEasingForSegment = getEasingForSegment; + exports.getMixer = getMixer; + exports.getOriginIndex = getOriginIndex; + exports.getValueAsType = getValueAsType; + exports.getValueTransition = getValueTransition$1; + exports.getVariableValue = getVariableValue; + exports.getViewAnimationLayerInfo = getViewAnimationLayerInfo; + exports.getViewAnimations = getViewAnimations; + exports.hasWarned = hasWarned$1; + exports.hex = hex; + exports.hover = hover; + exports.hsla = hsla; + exports.hslaToRgba = hslaToRgba; + exports.inView = inView; + exports.inertia = inertia; + exports.interpolate = interpolate; + exports.invisibleValues = invisibleValues; + exports.isBezierDefinition = isBezierDefinition; + exports.isBrowser = isBrowser; + exports.isCSSVariableName = isCSSVariableName; + exports.isCSSVariableToken = isCSSVariableToken; + exports.isDragActive = isDragActive; + exports.isDragging = isDragging; + exports.isEasingArray = isEasingArray; + exports.isGenerator = isGenerator; + exports.isHTMLElement = isHTMLElement; + exports.isMotionComponent = isMotionComponent; + exports.isMotionValue = isMotionValue; + exports.isNodeOrChild = isNodeOrChild; + exports.isNumericalString = isNumericalString; + exports.isObject = isObject; + exports.isPrimaryPointer = isPrimaryPointer; + exports.isSVGElement = isSVGElement; + exports.isSVGSVGElement = isSVGSVGElement; + exports.isValidMotionProp = isValidMotionProp; + exports.isWaapiSupportedEasing = isWaapiSupportedEasing; + exports.isZeroValueString = isZeroValueString; + exports.keyframes = keyframes; + exports.m = m; + exports.makeAnimationInstant = makeAnimationInstant; + exports.makeUseVisualState = makeUseVisualState; + exports.mapEasingToNativeEasing = mapEasingToNativeEasing; + exports.mapValue = mapValue; + exports.maxGeneratorDuration = maxGeneratorDuration; + exports.memo = memo; + exports.microtask = microtask; + exports.millisecondsToSeconds = millisecondsToSeconds; + exports.mirrorEasing = mirrorEasing; + exports.mix = mix; + exports.mixArray = mixArray; + exports.mixColor = mixColor; + exports.mixComplex = mixComplex; + exports.mixImmediate = mixImmediate; + exports.mixLinearColor = mixLinearColor; + exports.mixNumber = mixNumber$1; + exports.mixObject = mixObject; + exports.mixVisibility = mixVisibility; + exports.motion = motion; + exports.motionValue = motionValue; + exports.moveItem = moveItem; + exports.noop = noop; + exports.number = number; + exports.numberValueTypes = numberValueTypes; + exports.observeTimeline = observeTimeline; + exports.optimizedAppearDataAttribute = optimizedAppearDataAttribute; + exports.parseCSSVariable = parseCSSVariable; + exports.parseValueFromTransform = parseValueFromTransform; + exports.percent = percent; + exports.pipe = pipe; + exports.positionalKeys = positionalKeys; + exports.press = press; + exports.progress = progress; + exports.progressPercentage = progressPercentage; + exports.propEffect = propEffect; + exports.px = px; + exports.readTransformValue = readTransformValue; + exports.recordStats = recordStats; + exports.removeItem = removeItem; + exports.resize = resize; + exports.resolveElements = resolveElements; + exports.resolveMotionValue = resolveMotionValue; + exports.reverseEasing = reverseEasing; + exports.rgbUnit = rgbUnit; + exports.rgba = rgba; + exports.scale = scale; + exports.scroll = scroll; + exports.scrollInfo = scrollInfo; + exports.secondsToMilliseconds = secondsToMilliseconds; + exports.setDragLock = setDragLock; + exports.setStyle = setStyle; + exports.spring = spring; + exports.springValue = springValue; + exports.stagger = stagger; + exports.startOptimizedAppearAnimation = startOptimizedAppearAnimation; + exports.startWaapiAnimation = startWaapiAnimation; + exports.statsBuffer = statsBuffer; + exports.steps = steps; + exports.styleEffect = styleEffect; + exports.supportedWaapiEasing = supportedWaapiEasing; + exports.supportsBrowserAnimation = supportsBrowserAnimation; + exports.supportsFlags = supportsFlags; + exports.supportsLinearEasing = supportsLinearEasing; + exports.supportsPartialKeyframes = supportsPartialKeyframes; + exports.supportsScrollTimeline = supportsScrollTimeline; + exports.svgEffect = svgEffect; + exports.sync = sync; + exports.testValueType = testValueType; + exports.time = time; + exports.transform = transform; + exports.transformPropOrder = transformPropOrder; + exports.transformProps = transformProps; + exports.transformValue = transformValue; + exports.transformValueTypes = transformValueTypes; + exports.unwrapMotionComponent = unwrapMotionComponent; + exports.useAnimate = useAnimate; + exports.useAnimateMini = useAnimateMini; + exports.useAnimation = useAnimation; + exports.useAnimationControls = useAnimationControls; + exports.useAnimationFrame = useAnimationFrame; + exports.useCycle = useCycle; + exports.useDeprecatedAnimatedState = useAnimatedState; + exports.useDeprecatedInvertedScale = useInvertedScale; + exports.useDomEvent = useDomEvent; + exports.useDragControls = useDragControls; + exports.useElementScroll = useElementScroll; + exports.useForceUpdate = useForceUpdate; + exports.useInView = useInView; + exports.useInstantLayoutTransition = useInstantLayoutTransition; + exports.useInstantTransition = useInstantTransition; + exports.useIsPresent = useIsPresent; + exports.useIsomorphicLayoutEffect = useIsomorphicLayoutEffect; + exports.useMotionTemplate = useMotionTemplate; + exports.useMotionValue = useMotionValue; + exports.useMotionValueEvent = useMotionValueEvent; + exports.usePageInView = usePageInView; + exports.usePresence = usePresence; + exports.usePresenceData = usePresenceData; + exports.useReducedMotion = useReducedMotion; + exports.useReducedMotionConfig = useReducedMotionConfig; + exports.useResetProjection = useResetProjection; + exports.useScroll = useScroll; + exports.useSpring = useSpring; + exports.useTime = useTime; + exports.useTransform = useTransform; + exports.useUnmountEffect = useUnmountEffect; + exports.useVelocity = useVelocity; + exports.useViewportScroll = useViewportScroll; + exports.useWillChange = useWillChange; + exports.velocityPerSecond = velocityPerSecond; + exports.vh = vh; + exports.visualElementStore = visualElementStore; + exports.vw = vw; + exports.warnOnce = warnOnce; + exports.wrap = wrap; + +})); diff --git a/frontend/node_modules/framer-motion/dist/framer-motion.js b/frontend/node_modules/framer-motion/dist/framer-motion.js new file mode 100644 index 0000000000000000000000000000000000000000..47dbeb4db8c632ec06d836e2d0f374a6e818a07d --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/framer-motion.js @@ -0,0 +1 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).Motion={},t.React)}(this,function(t,e){"use strict";function n(t){var e=Object.create(null);return t&&Object.keys(t).forEach(function(n){if("default"!==n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}}),e.default=t,Object.freeze(e)}var i=n(e),s=React,o=Symbol.for("react.element"),r=Symbol.for("react.fragment"),a=Object.prototype.hasOwnProperty,l=s.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,u={key:!0,ref:!0,__self:!0,__source:!0};function c(t,e,n){var i,s={},r=null,c=null;for(i in void 0!==n&&(r=""+n),void 0!==e.key&&(r=""+e.key),void 0!==e.ref&&(c=e.ref),e)a.call(e,i)&&!u.hasOwnProperty(i)&&(s[i]=e[i]);if(t&&t.defaultProps)for(i in e=t.defaultProps)void 0===s[i]&&(s[i]=e[i]);return{$$typeof:o,type:t,key:r,ref:c,props:s,_owner:l.current}}const h=r,d=c,p=c,m=e.createContext({});function f(t){const n=e.useRef(null);return null===n.current&&(n.current=t()),n.current}const g="undefined"!=typeof window,y=g?e.useLayoutEffect:e.useEffect,v=e.createContext(null);function x(t,e){-1===t.indexOf(e)&&t.push(e)}function w(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}function T([...t],e,n){const i=e<0?t.length+e:e;if(i>=0&&in>e?e:n{};const S={},E=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function A(t){return"object"==typeof t&&null!==t}const M=t=>/^0[^.\s]+$/u.test(t);function C(t){let e;return()=>(void 0===e&&(e=t()),e)}const V=t=>t,R=(t,e)=>n=>e(t(n)),D=(...t)=>t.reduce(R),k=(t,e,n)=>{const i=e-t;return 0===i?1:(n-t)/i};class L{constructor(){this.subscriptions=[]}add(t){return x(this.subscriptions,t),()=>w(this.subscriptions,t)}notify(t,e,n){const i=this.subscriptions.length;if(i)if(1===i)this.subscriptions[0](t,e,n);else for(let s=0;s1e3*t,j=t=>t/1e3;function B(t,e){return e?t*(1e3/e):0}const I=new Set;const F=(t,e,n)=>{const i=e-t;return((n-t)%i+i)%i+t},W=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t;function U(t,e,n,i){if(t===e&&n===i)return V;const s=e=>function(t,e,n,i,s){let o,r,a=0;do{r=e+(n-e)/2,o=W(r,i,s)-t,o>0?n=r:e=r}while(Math.abs(o)>1e-7&&++a<12);return r}(e,0,1,t,n);return t=>0===t||1===t?t:W(s(t),e,i)}const N=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,$=t=>e=>1-t(1-e),z=U(.33,1.53,.69,.99),X=$(z),H=N(X),Y=t=>(t*=2)<1?.5*X(t):.5*(2-Math.pow(2,-10*(t-1))),K=t=>1-Math.sin(Math.acos(t)),G=$(K),_=N(K),Z=U(.42,0,1,1),q=U(0,0,.58,1),J=U(.42,0,.58,1);const Q=t=>Array.isArray(t)&&"number"!=typeof t[0];function tt(t,e){return Q(t)?t[F(0,t.length,e)]:t}const et=t=>Array.isArray(t)&&"number"==typeof t[0],nt={linear:V,easeIn:Z,easeInOut:J,easeOut:q,circIn:K,circInOut:_,circOut:G,backIn:X,backInOut:H,backOut:z,anticipate:Y},it=t=>{if(et(t)){t.length;const[e,n,i,s]=t;return U(e,n,i,s)}return"string"==typeof t?nt[t]:t},st=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],ot={value:null,addProjectionMetrics:null};function rt(t,e){let n=!1,i=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,r=st.reduce((t,n)=>(t[n]=function(t,e){let n=new Set,i=new Set,s=!1,o=!1;const r=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},l=0;function u(e){r.has(e)&&(c.schedule(e),t()),l++,e(a)}const c={schedule:(t,e=!1,o=!1)=>{const a=o&&s?n:i;return e&&r.add(t),a.has(t)||a.add(t),t},cancel:t=>{i.delete(t),r.delete(t)},process:t=>{a=t,s?o=!0:(s=!0,[n,i]=[i,n],n.forEach(u),e&&ot.value&&ot.value.frameloop[e].push(l),l=0,n.clear(),s=!1,o&&(o=!1,c.process(t)))}};return c}(o,e?n:void 0),t),{}),{setup:a,read:l,resolveKeyframes:u,preUpdate:c,update:h,preRender:d,render:p,postRender:m}=r,f=()=>{const o=S.useManualTiming?s.timestamp:performance.now();n=!1,S.useManualTiming||(s.delta=i?1e3/60:Math.max(Math.min(o-s.timestamp,40),1)),s.timestamp=o,s.isProcessing=!0,a.process(s),l.process(s),u.process(s),c.process(s),h.process(s),d.process(s),p.process(s),m.process(s),s.isProcessing=!1,n&&e&&(i=!1,t(f))};return{schedule:st.reduce((e,o)=>{const a=r[o];return e[o]=(e,o=!1,r=!1)=>(n||(n=!0,i=!0,s.isProcessing||t(f)),a.schedule(e,o,r)),e},{}),cancel:t=>{for(let e=0;e(void 0===ht&&pt.set(ut.isProcessing||S.useManualTiming?ut.timestamp:performance.now()),ht),set:t=>{ht=t,queueMicrotask(dt)}},mt={layout:0,mainThread:0,waapi:0},ft=t=>e=>"string"==typeof e&&e.startsWith(t),gt=ft("--"),yt=ft("var(--"),vt=t=>!!yt(t)&&xt.test(t.split("/*")[0].trim()),xt=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,wt={test:t=>"number"==typeof t,parse:parseFloat,transform:t=>t},Tt={...wt,transform:t=>P(0,1,t)},Pt={...wt,default:1},bt=t=>Math.round(1e5*t)/1e5,St=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;const Et=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,At=(t,e)=>n=>Boolean("string"==typeof n&&Et.test(n)&&n.startsWith(t)||e&&!function(t){return null==t}(n)&&Object.prototype.hasOwnProperty.call(n,e)),Mt=(t,e,n)=>i=>{if("string"!=typeof i)return i;const[s,o,r,a]=i.match(St);return{[t]:parseFloat(s),[e]:parseFloat(o),[n]:parseFloat(r),alpha:void 0!==a?parseFloat(a):1}},Ct={...wt,transform:t=>Math.round((t=>P(0,255,t))(t))},Vt={test:At("rgb","red"),parse:Mt("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+Ct.transform(t)+", "+Ct.transform(e)+", "+Ct.transform(n)+", "+bt(Tt.transform(i))+")"};const Rt={test:At("#"),parse:function(t){let e="",n="",i="",s="";return t.length>5?(e=t.substring(1,3),n=t.substring(3,5),i=t.substring(5,7),s=t.substring(7,9)):(e=t.substring(1,2),n=t.substring(2,3),i=t.substring(3,4),s=t.substring(4,5),e+=e,n+=n,i+=i,s+=s),{red:parseInt(e,16),green:parseInt(n,16),blue:parseInt(i,16),alpha:s?parseInt(s,16)/255:1}},transform:Vt.transform},Dt=t=>({test:e=>"string"==typeof e&&e.endsWith(t)&&1===e.split(" ").length,parse:parseFloat,transform:e=>`${e}${t}`}),kt=Dt("deg"),Lt=Dt("%"),Ot=Dt("px"),jt=Dt("vh"),Bt=Dt("vw"),It=(()=>({...Lt,parse:t=>Lt.parse(t)/100,transform:t=>Lt.transform(100*t)}))(),Ft={test:At("hsl","hue"),parse:Mt("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+Lt.transform(bt(e))+", "+Lt.transform(bt(n))+", "+bt(Tt.transform(i))+")"},Wt={test:t=>Vt.test(t)||Rt.test(t)||Ft.test(t),parse:t=>Vt.test(t)?Vt.parse(t):Ft.test(t)?Ft.parse(t):Rt.parse(t),transform:t=>"string"==typeof t?t:t.hasOwnProperty("red")?Vt.transform(t):Ft.transform(t),getAnimatableNone:t=>{const e=Wt.parse(t);return e.alpha=0,Wt.transform(e)}},Ut=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;const Nt="number",$t="color",zt=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function Xt(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},s=[];let o=0;const r=e.replace(zt,t=>(Wt.test(t)?(i.color.push(o),s.push($t),n.push(Wt.parse(t))):t.startsWith("var(")?(i.var.push(o),s.push("var"),n.push(t)):(i.number.push(o),s.push(Nt),n.push(parseFloat(t))),++o,"${}")).split("${}");return{values:n,split:r,indexes:i,types:s}}function Ht(t){return Xt(t).values}function Yt(t){const{split:e,types:n}=Xt(t),i=e.length;return t=>{let s="";for(let o=0;o"number"==typeof t?0:Wt.test(t)?Wt.getAnimatableNone(t):t;const Gt={test:function(t){return isNaN(t)&&"string"==typeof t&&(t.match(St)?.length||0)+(t.match(Ut)?.length||0)>0},parse:Ht,createTransformer:Yt,getAnimatableNone:function(t){const e=Ht(t);return Yt(t)(e.map(Kt))}};function _t(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<.5?e:n<2/3?t+(e-t)*(2/3-n)*6:t}function Zt({hue:t,saturation:e,lightness:n,alpha:i}){t/=360,n/=100;let s=0,o=0,r=0;if(e/=100){const i=n<.5?n*(1+e):n+e-n*e,a=2*n-i;s=_t(a,i,t+1/3),o=_t(a,i,t),r=_t(a,i,t-1/3)}else s=o=r=n;return{red:Math.round(255*s),green:Math.round(255*o),blue:Math.round(255*r),alpha:i}}function qt(t,e){return n=>n>0?e:t}const Jt=(t,e,n)=>t+(e-t)*n,Qt=(t,e,n)=>{const i=t*t,s=n*(e*e-i)+i;return s<0?0:Math.sqrt(s)},te=[Rt,Vt,Ft];function ee(t){const e=(n=t,te.find(t=>t.test(n)));var n;if(!Boolean(e))return!1;let i=e.parse(t);return e===Ft&&(i=Zt(i)),i}const ne=(t,e)=>{const n=ee(t),i=ee(e);if(!n||!i)return qt(t,e);const s={...n};return t=>(s.red=Qt(n.red,i.red,t),s.green=Qt(n.green,i.green,t),s.blue=Qt(n.blue,i.blue,t),s.alpha=Jt(n.alpha,i.alpha,t),Vt.transform(s))},ie=new Set(["none","hidden"]);function se(t,e){return ie.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function oe(t,e){return n=>Jt(t,e,n)}function re(t){return"number"==typeof t?oe:"string"==typeof t?vt(t)?qt:Wt.test(t)?ne:ue:Array.isArray(t)?ae:"object"==typeof t?Wt.test(t)?ne:le:qt}function ae(t,e){const n=[...t],i=n.length,s=t.map((t,n)=>re(t)(t,e[n]));return t=>{for(let e=0;e{for(const e in i)n[e]=i[e](t);return n}}const ue=(t,e)=>{const n=Gt.createTransformer(e),i=Xt(t),s=Xt(e);return i.indexes.var.length===s.indexes.var.length&&i.indexes.color.length===s.indexes.color.length&&i.indexes.number.length>=s.indexes.number.length?ie.has(t)&&!s.values.length||ie.has(e)&&!i.values.length?se(t,e):D(ae(function(t,e){const n=[],i={color:0,var:0,number:0};for(let s=0;s{const e=({timestamp:e})=>t(e);return{start:(t=!0)=>at.update(e,t),stop:()=>lt(e),now:()=>ut.isProcessing?ut.timestamp:pt.now()}},de=(t,e,n=10)=>{let i="";const s=Math.max(Math.round(e/n),2);for(let e=0;e=pe?1/0:e}function fe(t,e=100,n){const i=n({...t,keyframes:[0,e]}),s=Math.min(me(i),pe);return{type:"keyframes",ease:t=>i.next(s*t).value/e,duration:j(s)}}function ge(t,e,n){const i=Math.max(e-5,0);return B(n-t(i),e-i)}const ye=100,ve=10,xe=1,we=0,Te=800,Pe=.3,be=.3,Se={granular:.01,default:2},Ee={granular:.005,default:.5},Ae=.01,Me=10,Ce=.05,Ve=1,Re=.001;function De({duration:t=Te,bounce:e=Pe,velocity:n=we,mass:i=xe}){let s,o,r=1-e;r=P(Ce,Ve,r),t=P(Ae,Me,j(t)),r<1?(s=e=>{const i=e*r,s=i*t,o=i-n,a=Le(e,r),l=Math.exp(-s);return Re-o/a*l},o=e=>{const i=e*r*t,o=i*n+n,a=Math.pow(r,2)*Math.pow(e,2)*t,l=Math.exp(-i),u=Le(Math.pow(e,2),r);return(-s(e)+Re>0?-1:1)*((o-a)*l)/u}):(s=e=>Math.exp(-e*t)*((e-n)*t+1)-.001,o=e=>Math.exp(-e*t)*(t*t*(n-e)));const a=function(t,e,n){let i=n;for(let n=1;nvoid 0!==t[e])}function Ie(t=be,e=Pe){const n="object"!=typeof t?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:i,restDelta:s}=n;const o=n.keyframes[0],r=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:l,damping:u,mass:c,duration:h,velocity:d,isResolvedFromDuration:p}=function(t){let e={velocity:we,stiffness:ye,damping:ve,mass:xe,isResolvedFromDuration:!1,...t};if(!Be(t,je)&&Be(t,Oe))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(1.2*n),s=i*i,o=2*P(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:xe,stiffness:s,damping:o}}else{const n=De(t);e={...e,...n,mass:xe},e.isResolvedFromDuration=!0}return e}({...n,velocity:-j(n.velocity||0)}),m=d||0,f=u/(2*Math.sqrt(l*c)),g=r-o,y=j(Math.sqrt(l/c)),v=Math.abs(g)<5;let x;if(i||(i=v?Se.granular:Se.default),s||(s=v?Ee.granular:Ee.default),f<1){const t=Le(y,f);x=e=>{const n=Math.exp(-f*y*e);return r-n*((m+f*y*g)/t*Math.sin(t*e)+g*Math.cos(t*e))}}else if(1===f)x=t=>r-Math.exp(-y*t)*(g+(m+y*g)*t);else{const t=y*Math.sqrt(f*f-1);x=e=>{const n=Math.exp(-f*y*e),i=Math.min(t*e,300);return r-n*((m+f*y*g)*Math.sinh(i)+t*g*Math.cosh(i))/t}}const w={calculatedDuration:p&&h||null,next:t=>{const e=x(t);if(p)a.done=t>=h;else{let n=0===t?m:0;f<1&&(n=0===t?O(m):ge(x,t,e));const o=Math.abs(n)<=i,l=Math.abs(r-e)<=s;a.done=o&&l}return a.value=a.done?r:e,a},toString:()=>{const t=Math.min(me(w),pe),e=de(e=>w.next(t*e).value,t,30);return t+"ms "+e},toTransition:()=>{}};return w}function Fe({keyframes:t,velocity:e=0,power:n=.8,timeConstant:i=325,bounceDamping:s=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:l,restDelta:u=.5,restSpeed:c}){const h=t[0],d={done:!1,value:h},p=t=>void 0===a?l:void 0===l||Math.abs(a-t)-m*Math.exp(-t/i),v=t=>g+y(t),x=t=>{const e=y(t),n=v(t);d.done=Math.abs(e)<=u,d.value=d.done?g:n};let w,T;const P=t=>{var e;(e=d.value,void 0!==a&&el)&&(w=t,T=Ie({keyframes:[d.value,p(d.value)],velocity:ge(v,t,d.value),damping:s,stiffness:o,restDelta:u,restSpeed:c}))};return P(0),{calculatedDuration:null,next:t=>{let e=!1;return T||void 0!==w||(e=!0,x(t),P(t)),void 0!==w&&t>=w?T.next(t-w):(!e&&x(t),d)}}}function We(t,e,{clamp:n=!0,ease:i,mixer:s}={}){const o=t.length;if(e.length,1===o)return()=>e[0];if(2===o&&e[0]===e[1])return()=>e[1];const r=t[0]===t[1];t[0]>t[o-1]&&(t=[...t].reverse(),e=[...e].reverse());const a=function(t,e,n){const i=[],s=n||S.mix||ce,o=t.length-1;for(let n=0;n{if(r&&n1)for(;iu(P(t[0],t[o-1],e)):u}function Ue(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const s=k(0,e,i);t.push(Jt(n,1,s))}}function Ne(t){const e=[0];return Ue(e,t.length-1),e}function $e(t,e){return t.map(t=>t*e)}function ze(t,e){return t.map(()=>e||J).splice(0,t.length-1)}function Xe({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const s=Q(i)?i.map(it):it(i),o={done:!1,value:e[0]},r=We($e(n&&n.length===e.length?n:Ne(e),t),e,{ease:Array.isArray(s)?s:ze(e,s)});return{calculatedDuration:t,next:e=>(o.value=r(e),o.done=e>=t,o)}}Ie.applyToOptions=t=>{const e=fe(t,100,Ie);return t.ease=e.ease,t.duration=O(e.duration),t.type="keyframes",t};const He=t=>null!==t;function Ye(t,{repeat:e,repeatType:n="loop"},i,s=1){const o=t.filter(He),r=s<0||e&&"loop"!==n&&e%2==1?0:o.length-1;return r&&void 0!==i?i:o[r]}const Ke={decay:Fe,inertia:Fe,tween:Xe,keyframes:Xe,spring:Ie};function Ge(t){"string"==typeof t.type&&(t.type=Ke[t.type])}class _e{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,e){return this.finished.then(t,e)}}const Ze=t=>t/100;class qe extends _e{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:t}=this.options;t&&t.updatedAt!==pt.now()&&this.tick(pt.now()),this.isStopped=!0,"idle"!==this.state&&(this.teardown(),this.options.onStop?.())},mt.mainThread++,this.options=t,this.initAnimation(),this.play(),!1===t.autoplay&&this.pause()}initAnimation(){const{options:t}=this;Ge(t);const{type:e=Xe,repeat:n=0,repeatDelay:i=0,repeatType:s,velocity:o=0}=t;let{keyframes:r}=t;const a=e||Xe;a!==Xe&&"number"!=typeof r[0]&&(this.mixKeyframes=D(Ze,ce(r[0],r[1])),r=[0,100]);const l=a({...t,keyframes:r});"mirror"===s&&(this.mirroredGenerator=a({...t,keyframes:[...r].reverse(),velocity:-o})),null===l.calculatedDuration&&(l.calculatedDuration=me(l));const{calculatedDuration:u}=l;this.calculatedDuration=u,this.resolvedDuration=u+i,this.totalDuration=this.resolvedDuration*(n+1)-i,this.generator=l}updateTime(t){const e=Math.round(t-this.startTime)*this.playbackSpeed;null!==this.holdTime?this.currentTime=this.holdTime:this.currentTime=e}tick(t,e=!1){const{generator:n,totalDuration:i,mixKeyframes:s,mirroredGenerator:o,resolvedDuration:r,calculatedDuration:a}=this;if(null===this.startTime)return n.next(0);const{delay:l=0,keyframes:u,repeat:c,repeatType:h,repeatDelay:d,type:p,onUpdate:m,finalKeyframe:f}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-i/this.speed,this.startTime)),e?this.currentTime=t:this.updateTime(t);const g=this.currentTime-l*(this.playbackSpeed>=0?1:-1),y=this.playbackSpeed>=0?g<0:g>i;this.currentTime=Math.max(g,0),"finished"===this.state&&null===this.holdTime&&(this.currentTime=i);let v=this.currentTime,x=n;if(c){const t=Math.min(this.currentTime,i)/r;let e=Math.floor(t),n=t%1;!n&&t>=1&&(n=1),1===n&&e--,e=Math.min(e,c+1);Boolean(e%2)&&("reverse"===h?(n=1-n,d&&(n-=d/r)):"mirror"===h&&(x=o)),v=P(0,1,n)*r}const w=y?{done:!1,value:u[0]}:x.next(v);s&&(w.value=s(w.value));let{done:T}=w;y||null===a||(T=this.playbackSpeed>=0?this.currentTime>=i:this.currentTime<=0);const b=null===this.holdTime&&("finished"===this.state||"running"===this.state&&T);return b&&p!==Fe&&(w.value=Ye(u,this.options,f,this.speed)),m&&m(w.value),b&&this.finish(),w}then(t,e){return this.finished.then(t,e)}get duration(){return j(this.calculatedDuration)}get time(){return j(this.currentTime)}set time(t){t=O(t),this.currentTime=t,null===this.startTime||null!==this.holdTime||0===this.playbackSpeed?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime(pt.now());const e=this.playbackSpeed!==t;this.playbackSpeed=t,e&&(this.time=j(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=he,startTime:e}=this.options;this.driver||(this.driver=t(t=>this.tick(t))),this.options.onPlay?.();const n=this.driver.now();"finished"===this.state?(this.updateFinished(),this.startTime=n):null!==this.holdTime?this.startTime=n-this.holdTime:this.startTime||(this.startTime=e??n),"finished"===this.state&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(pt.now()),this.holdTime=this.currentTime}complete(){"running"!==this.state&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null,mt.mainThread--}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),t.observe(this)}}function Je(t){for(let e=1;e180*t/Math.PI,tn=t=>{const e=Qe(Math.atan2(t[1],t[0]));return nn(e)},en={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:tn,rotateZ:tn,skewX:t=>Qe(Math.atan(t[1])),skewY:t=>Qe(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},nn=t=>((t%=360)<0&&(t+=360),t),sn=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),on=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),rn={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:sn,scaleY:on,scale:t=>(sn(t)+on(t))/2,rotateX:t=>nn(Qe(Math.atan2(t[6],t[5]))),rotateY:t=>nn(Qe(Math.atan2(-t[2],t[0]))),rotateZ:tn,rotate:tn,skewX:t=>Qe(Math.atan(t[4])),skewY:t=>Qe(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function an(t){return t.includes("scale")?1:0}function ln(t,e){if(!t||"none"===t)return an(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,s;if(n)i=rn,s=n;else{const e=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=en,s=e}if(!s)return an(e);const o=i[e],r=s[1].split(",").map(cn);return"function"==typeof o?o(r):r[o]}const un=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return ln(n,e)};function cn(t){return parseFloat(t.trim())}const hn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],dn=(()=>new Set(hn))(),pn=t=>t===wt||t===Ot,mn=new Set(["x","y","z"]),fn=hn.filter(t=>!mn.has(t));const gn={width:({x:t},{paddingLeft:e="0",paddingRight:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),height:({y:t},{paddingTop:e="0",paddingBottom:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>ln(e,"x"),y:(t,{transform:e})=>ln(e,"y")};gn.translateX=gn.x,gn.translateY=gn.y;const yn=new Set;let vn=!1,xn=!1,wn=!1;function Tn(){if(xn){const t=Array.from(yn).filter(t=>t.needsMeasurement),e=new Set(t.map(t=>t.element)),n=new Map;e.forEach(t=>{const e=function(t){const e=[];return fn.forEach(n=>{const i=t.getValue(n);void 0!==i&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}(t);e.length&&(n.set(t,e),t.render())}),t.forEach(t=>t.measureInitialState()),e.forEach(t=>{t.render();const e=n.get(t);e&&e.forEach(([e,n])=>{t.getValue(e)?.set(n)})}),t.forEach(t=>t.measureEndState()),t.forEach(t=>{void 0!==t.suspendedScrollY&&window.scrollTo(0,t.suspendedScrollY)})}xn=!1,vn=!1,yn.forEach(t=>t.complete(wn)),yn.clear()}function Pn(){yn.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(xn=!0)})}function bn(){wn=!0,Pn(),Tn(),wn=!1}class Sn{constructor(t,e,n,i,s,o=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=e,this.name=n,this.motionValue=i,this.element=s,this.isAsync=o}scheduleResolve(){this.state="scheduled",this.isAsync?(yn.add(this),vn||(vn=!0,at.read(Pn),at.resolveKeyframes(Tn))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:e,element:n,motionValue:i}=this;if(null===t[0]){const s=i?.get(),o=t[t.length-1];if(void 0!==s)t[0]=s;else if(n&&e){const i=n.readValue(e,o);null!=i&&(t[0]=i)}void 0===t[0]&&(t[0]=o),i&&void 0===s&&i.set(t[0])}Je(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),yn.delete(this)}cancel(){"scheduled"===this.state&&(yn.delete(this),this.state="pending")}resume(){"pending"===this.state&&this.scheduleResolve()}}const En=t=>t.startsWith("--");function An(t,e,n){En(e)?t.style.setProperty(e,n):t.style[e]=n}const Mn=C(()=>void 0!==window.ScrollTimeline),Cn={};function Vn(t,e){const n=C(t);return()=>Cn[e]??n()}const Rn=Vn(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch(t){return!1}return!0},"linearEasing"),Dn=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,kn={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Dn([0,.65,.55,1]),circOut:Dn([.55,0,1,.45]),backIn:Dn([.31,.01,.66,-.59]),backOut:Dn([.33,1.53,.69,.99])};function Ln(t,e){return t?"function"==typeof t?Rn()?de(t,e):"ease-out":et(t)?Dn(t):Array.isArray(t)?t.map(t=>Ln(t,e)||kn.easeOut):kn[t]:void 0}function On(t,e,n,{delay:i=0,duration:s=300,repeat:o=0,repeatType:r="loop",ease:a="easeOut",times:l}={},u=void 0){const c={[e]:n};l&&(c.offset=l);const h=Ln(a,s);Array.isArray(h)&&(c.easing=h),ot.value&&mt.waapi++;const d={delay:i,duration:s,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:o+1,direction:"reverse"===r?"alternate":"normal"};u&&(d.pseudoElement=u);const p=t.animate(c,d);return ot.value&&p.finished.finally(()=>{mt.waapi--}),p}function jn(t){return"function"==typeof t&&"applyToOptions"in t}function Bn({type:t,...e}){return jn(t)&&Rn()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class In extends _e{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:e,name:n,keyframes:i,pseudoElement:s,allowFlatten:o=!1,finalKeyframe:r,onComplete:a}=t;this.isPseudoElement=Boolean(s),this.allowFlatten=o,this.options=t,t.type;const l=Bn(t);this.animation=On(e,n,i,l,s),!1===l.autoplay&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!s){const t=Ye(i,this.options,r,this.speed);this.updateMotionValue?this.updateMotionValue(t):An(e,n,t),this.animation.cancel()}a?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),"finished"===this.state&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch(t){}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;"idle"!==t&&"finished"!==t&&(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming?.().duration||0;return j(Number(t))}get time(){return j(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=O(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return null!==this.finishedTime?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:e}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&Mn()?(this.animation.timeline=t,V):e(this)}}const Fn={anticipate:Y,backInOut:H,circInOut:_};function Wn(t){"string"==typeof t.ease&&t.ease in Fn&&(t.ease=Fn[t.ease])}class Un extends In{constructor(t){Wn(t),Ge(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:e,onUpdate:n,onComplete:i,element:s,...o}=this.options;if(!e)return;if(void 0!==t)return void e.set(t);const r=new qe({...o,autoplay:!1}),a=O(this.finishedTime??this.time);e.setWithVelocity(r.sample(a-10).value,r.sample(a).value,10),r.stop()}}const Nn=(t,e)=>"zIndex"!==e&&(!("number"!=typeof t&&!Array.isArray(t))||!("string"!=typeof t||!Gt.test(t)&&"0"!==t||t.startsWith("url(")));function $n(t){t.duration=0,t.type}const zn=new Set(["opacity","clipPath","filter","transform"]),Xn=C(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Hn(t){const{motionValue:e,name:n,repeatDelay:i,repeatType:s,damping:o,type:r}=t,a=e?.owner?.current;if(!(a instanceof HTMLElement))return!1;const{onUpdate:l,transformTemplate:u}=e.owner.getProps();return Xn()&&n&&zn.has(n)&&("transform"!==n||!u)&&!l&&!i&&"mirror"!==s&&0!==o&&"inertia"!==r}class Yn extends _e{constructor({autoplay:t=!0,delay:e=0,type:n="keyframes",repeat:i=0,repeatDelay:s=0,repeatType:o="loop",keyframes:r,name:a,motionValue:l,element:u,...c}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=pt.now();const h={autoplay:t,delay:e,type:n,repeat:i,repeatDelay:s,repeatType:o,name:a,motionValue:l,element:u,...c},d=u?.KeyframeResolver||Sn;this.keyframeResolver=new d(r,(t,e,n)=>this.onKeyframesResolved(t,e,h,!n),a,l,u),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,e,n,i){this.keyframeResolver=void 0;const{name:s,type:o,velocity:r,delay:a,isHandoff:l,onUpdate:u}=n;this.resolvedAt=pt.now(),function(t,e,n,i){const s=t[0];if(null===s)return!1;if("display"===e||"visibility"===e)return!0;const o=t[t.length-1],r=Nn(s,e),a=Nn(o,e);return!(!r||!a)&&(function(t){const e=t[0];if(1===t.length)return!0;for(let n=0;n40?this.resolvedAt:this.createdAt:void 0,finalKeyframe:e,...n,keyframes:t},h=!l&&Hn(c)?new Un({...c,element:c.motionValue.owner.current}):new qe(c);h.finished.then(()=>this.notifyFinished()).catch(V),this.pendingTimeline&&(this.stopTimeline=h.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=h}get finished(){return this._animation?this.animation.finished:this._finished}then(t,e){return this.finished.finally(t).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),bn()),this._animation}get duration(){return this.animation.duration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}class Kn{constructor(t){this.stop=()=>this.runAll("stop"),this.animations=t.filter(Boolean)}get finished(){return Promise.all(this.animations.map(t=>t.finished))}getAll(t){return this.animations[0][t]}setAll(t,e){for(let n=0;ne.attachTimeline(t));return()=>{e.forEach((t,e)=>{t&&t(),this.animations[e].stop()})}}get time(){return this.getAll("time")}set time(t){this.setAll("time",t)}get speed(){return this.getAll("speed")}set speed(t){this.setAll("speed",t)}get state(){return this.getAll("state")}get startTime(){return this.getAll("startTime")}get duration(){let t=0;for(let e=0;ee[t]())}play(){this.runAll("play")}pause(){this.runAll("pause")}cancel(){this.runAll("cancel")}complete(){this.runAll("complete")}}class Gn extends Kn{then(t,e){return this.finished.finally(t).then(()=>{})}}class _n extends In{constructor(t){super(),this.animation=t,t.onfinish=()=>{this.finishedTime=this.time,this.notifyFinished()}}}const Zn=new WeakMap,qn=(t,e="")=>`${t}:${e}`;function Jn(t){const e=Zn.get(t)||new Map;return Zn.set(t,e),e}const Qn=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function ti(t){const e=Qn.exec(t);if(!e)return[,];const[,n,i,s]=e;return[`--${n??i}`,s]}function ei(t,e,n=1){const[i,s]=ti(t);if(!i)return;const o=window.getComputedStyle(e).getPropertyValue(i);if(o){const t=o.trim();return E(t)?parseFloat(t):t}return vt(s)?ei(s,e,n+1):s}function ni(t,e){return t?.[e]??t?.default??t}const ii=new Set(["width","height","top","left","right","bottom",...hn]),si=t=>e=>e.test(t),oi=[wt,Ot,Lt,kt,Bt,jt,{test:t=>"auto"===t,parse:t=>t}],ri=t=>oi.find(si(t));function ai(t){return"number"==typeof t?0===t:null===t||("none"===t||"0"===t||M(t))}const li=new Set(["brightness","contrast","saturate","opacity"]);function ui(t){const[e,n]=t.slice(0,-1).split("(");if("drop-shadow"===e)return t;const[i]=n.match(St)||[];if(!i)return t;const s=n.replace(i,"");let o=li.has(e)?1:0;return i!==n&&(o*=100),e+"("+o+s+")"}const ci=/\b([a-z-]*)\(.*?\)/gu,hi={...Gt,getAnimatableNone:t=>{const e=t.match(ci);return e?e.map(ui).join(" "):t}},di={...wt,transform:Math.round},pi={rotate:kt,rotateX:kt,rotateY:kt,rotateZ:kt,scale:Pt,scaleX:Pt,scaleY:Pt,scaleZ:Pt,skew:kt,skewX:kt,skewY:kt,distance:Ot,translateX:Ot,translateY:Ot,translateZ:Ot,x:Ot,y:Ot,z:Ot,perspective:Ot,transformPerspective:Ot,opacity:Tt,originX:It,originY:It,originZ:Ot},mi={borderWidth:Ot,borderTopWidth:Ot,borderRightWidth:Ot,borderBottomWidth:Ot,borderLeftWidth:Ot,borderRadius:Ot,radius:Ot,borderTopLeftRadius:Ot,borderTopRightRadius:Ot,borderBottomRightRadius:Ot,borderBottomLeftRadius:Ot,width:Ot,maxWidth:Ot,height:Ot,maxHeight:Ot,top:Ot,right:Ot,bottom:Ot,left:Ot,padding:Ot,paddingTop:Ot,paddingRight:Ot,paddingBottom:Ot,paddingLeft:Ot,margin:Ot,marginTop:Ot,marginRight:Ot,marginBottom:Ot,marginLeft:Ot,backgroundPositionX:Ot,backgroundPositionY:Ot,...pi,zIndex:di,fillOpacity:Tt,strokeOpacity:Tt,numOctaves:di},fi={...mi,color:Wt,backgroundColor:Wt,outlineColor:Wt,fill:Wt,stroke:Wt,borderColor:Wt,borderTopColor:Wt,borderRightColor:Wt,borderBottomColor:Wt,borderLeftColor:Wt,filter:hi,WebkitFilter:hi},gi=t=>fi[t];function yi(t,e){let n=gi(t);return n!==hi&&(n=Gt),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const vi=new Set(["auto","none","0"]);class xi extends Sn{constructor(t,e,n,i,s){super(t,e,n,i,s,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:e,name:n}=this;if(!e||!e.current)return;super.readKeyframes();for(let n=0;n{t.getValue(e).set(n)}),this.resolveNoneKeyframes()}}const wi=new Set(["borderWidth","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderRadius","radius","borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius","width","maxWidth","height","maxHeight","top","right","bottom","left","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","margin","marginTop","marginRight","marginBottom","marginLeft","backgroundPositionX","backgroundPositionY"]);function Ti(t,e){for(let n=0;n{try{document.createElement("div").animate({opacity:[1]})}catch(t){return!1}return!0}),bi=new Set(["opacity","clipPath","filter","transform"]);function Si(t,e,n){if(t instanceof EventTarget)return[t];if("string"==typeof t){let i=document;e&&(i=e.current);const s=n?.[t]??i.querySelectorAll(t);return s?Array.from(s):[]}return Array.from(t)}function Ei(t){return(e,n)=>{const i=Si(e),s=[];for(const e of i){const i=t(e,n);s.push(i)}return()=>{for(const t of s)t()}}}const Ai=(t,e)=>e&&"number"==typeof t?e.transform(t):t;class Mi{constructor(){this.latest={},this.values=new Map}set(t,e,n,i,s=!0){const o=this.values.get(t);o&&o.onRemove();const r=()=>{const i=e.get();this.latest[t]=s?Ai(i,mi[t]):i,n&&at.render(n)};r();const a=e.on("change",r);i&&e.addDependent(i);const l=()=>{a(),n&<(n),this.values.delete(t),i&&e.removeDependent(i)};return this.values.set(t,{value:e,onRemove:l}),l}get(t){return this.values.get(t)?.value}destroy(){for(const t of this.values.values())t.onRemove()}}function Ci(t){const e=new WeakMap,n=[];return(i,s)=>{const o=e.get(i)??new Mi;e.set(i,o);for(const e in s){const r=s[e],a=t(i,o,e,r);n.push(a)}return()=>{for(const t of n)t()}}}const Vi=(t,e,n,i)=>{const s=function(t,e){if(!(e in t))return!1;const n=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(t),e)||Object.getOwnPropertyDescriptor(t,e);return n&&"function"==typeof n.set}(t,n),o=s?n:n.startsWith("data")||n.startsWith("aria")?n.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`):n;const r=s?()=>{t[o]=e.latest[n]}:()=>{const i=e.latest[n];null==i?t.removeAttribute(o):t.setAttribute(o,String(i))};return e.set(n,i,r)},Ri=Ei(Ci(Vi)),Di=Ci((t,e,n,i)=>e.set(n,i,()=>{t[n]=e.latest[n]},void 0,!1));function ki(t){return A(t)&&"offsetHeight"in t}const Li={current:void 0};class Oi{constructor(t,e={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=t=>{const e=pt.now();if(this.updatedAt!==e&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(t),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const t of this.dependents)t.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=e.owner}setCurrent(t){var e;this.current=t,this.updatedAt=pt.now(),null===this.canTrackVelocity&&void 0!==t&&(this.canTrackVelocity=(e=this.current,!isNaN(parseFloat(e))))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return this.on("change",t)}on(t,e){this.events[t]||(this.events[t]=new L);const n=this.events[t].add(e);return"change"===t?()=>{n(),at.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,e){this.passiveEffect=t,this.stopPassiveEffect=e}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,e,n){this.set(e),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-n}jump(t,e=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,e&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return Li.current&&Li.current.push(this),this.current}getPrevious(){return this.prev}getVelocity(){const t=pt.now();if(!this.canTrackVelocity||void 0===this.prevFrameValue||t-this.updatedAt>30)return 0;const e=Math.min(this.updatedAt-this.prevUpdatedAt,30);return B(parseFloat(this.current)-parseFloat(this.prevFrameValue),e)}start(t){return this.stop(),new Promise(e=>{this.hasAnimated=!0,this.animation=t(e),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function ji(t,e){return new Oi(t,e)}const Bi={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"};const Ii=new Set(["originX","originY","originZ"]),Fi=(t,e,n,i)=>{let s,o;return dn.has(n)?(e.get("transform")||(ki(t)||e.get("transformBox")||Fi(t,e,"transformBox",new Oi("fill-box")),e.set("transform",new Oi("none"),()=>{t.style.transform=function(t){let e="",n=!0;for(let i=0;i{const n=e.latest.originX??"50%",i=e.latest.originY??"50%",s=e.latest.originZ??0;t.style.transformOrigin=`${n} ${i} ${s}`}),o=e.get("transformOrigin")):s=En(n)?()=>{t.style.setProperty(n,e.latest[n])}:()=>{t.style[n]=e.latest[n]},e.set(n,i,s,o)},Wi=Ei(Ci(Fi)),Ui=Ot.transform;const Ni=Ei(Ci((t,e,n,i)=>{if(n.startsWith("path"))return function(t,e,n,i){return at.render(()=>t.setAttribute("pathLength","1")),"pathOffset"===n?e.set(n,i,()=>t.setAttribute("stroke-dashoffset",Ui(-e.latest[n]))):(e.get("stroke-dasharray")||e.set("stroke-dasharray",new Oi("1 1"),()=>{const{pathLength:n=1,pathSpacing:i}=e.latest;t.setAttribute("stroke-dasharray",`${Ui(n)} ${Ui(i??1-Number(n))}`)}),e.set(n,i,void 0,e.get("stroke-dasharray")))}(t,e,n,i);if(n.startsWith("attr"))return Vi(t,e,function(t){return t.replace(/^attr([A-Z])/,(t,e)=>e.toLowerCase())}(n),i);return(n in t.style?Fi:Vi)(t,e,n,i)}));const{schedule:$i,cancel:zi}=rt(queueMicrotask,!1),Xi={x:!1,y:!1};function Hi(){return Xi.x||Xi.y}function Yi(t){return"x"===t||"y"===t?Xi[t]?null:(Xi[t]=!0,()=>{Xi[t]=!1}):Xi.x||Xi.y?null:(Xi.x=Xi.y=!0,()=>{Xi.x=Xi.y=!1})}function Ki(t,e){const n=Si(t),i=new AbortController;return[n,{passive:!0,...e,signal:i.signal},()=>i.abort()]}function Gi(t){return!("touch"===t.pointerType||Hi())}function _i(t,e,n={}){const[i,s,o]=Ki(t,n),r=t=>{if(!Gi(t))return;const{target:n}=t,i=e(n,t);if("function"!=typeof i||!n)return;const o=t=>{Gi(t)&&(i(t),n.removeEventListener("pointerleave",o))};n.addEventListener("pointerleave",o,s)};return i.forEach(t=>{t.addEventListener("pointerenter",r,s)}),o}const Zi=(t,e)=>!!e&&(t===e||Zi(t,e.parentElement)),qi=t=>"mouse"===t.pointerType?"number"!=typeof t.button||t.button<=0:!1!==t.isPrimary,Ji=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);const Qi=new WeakSet;function ts(t){return e=>{"Enter"===e.key&&t(e)}}function es(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}function ns(t){return qi(t)&&!Hi()}function is(t,e,n={}){const[i,s,o]=Ki(t,n),r=t=>{const i=t.currentTarget;if(!ns(t))return;Qi.add(i);const o=e(i,t),r=(t,e)=>{window.removeEventListener("pointerup",a),window.removeEventListener("pointercancel",l),Qi.has(i)&&Qi.delete(i),ns(t)&&"function"==typeof o&&o(t,{success:e})},a=t=>{r(t,i===window||i===document||n.useGlobalTarget||Zi(i,t.target))},l=t=>{r(t,!1)};window.addEventListener("pointerup",a,s),window.addEventListener("pointercancel",l,s)};return i.forEach(t=>{var e;(n.useGlobalTarget?window:t).addEventListener("pointerdown",r,s),ki(t)&&(t.addEventListener("focus",t=>((t,e)=>{const n=t.currentTarget;if(!n)return;const i=ts(()=>{if(Qi.has(n))return;es(n,"down");const t=ts(()=>{es(n,"up")});n.addEventListener("keyup",t,e),n.addEventListener("blur",()=>es(n,"cancel"),e)});n.addEventListener("keydown",i,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",i),e)})(t,s)),e=t,Ji.has(e.tagName)||-1!==e.tabIndex||t.hasAttribute("tabindex")||(t.tabIndex=0))}),o}function ss(t,e){const n=window.getComputedStyle(t);return En(e)?n.getPropertyValue(e):n[e]}function os(t){return A(t)&&"ownerSVGElement"in t}const rs=new WeakMap;let as;const ls=(t,e,n)=>(i,s)=>s&&s[0]?s[0][t+"Size"]:os(i)&&"getBBox"in i?i.getBBox()[e]:i[n],us=ls("inline","width","offsetWidth"),cs=ls("block","height","offsetHeight");function hs({target:t,borderBoxSize:e}){rs.get(t)?.forEach(n=>{n(t,{get width(){return us(t,e)},get height(){return cs(t,e)}})})}function ds(t){t.forEach(hs)}function ps(t,e){as||"undefined"!=typeof ResizeObserver&&(as=new ResizeObserver(ds));const n=Si(t);return n.forEach(t=>{let n=rs.get(t);n||(n=new Set,rs.set(t,n)),n.add(e),as?.observe(t)}),()=>{n.forEach(t=>{const n=rs.get(t);n?.delete(e),n?.size||as?.unobserve(t)})}}const ms=new Set;let fs;function gs(t){return ms.add(t),fs||(fs=()=>{const t={get width(){return window.innerWidth},get height(){return window.innerHeight}};ms.forEach(e=>e(t))},window.addEventListener("resize",fs)),()=>{ms.delete(t),ms.size||"function"!=typeof fs||(window.removeEventListener("resize",fs),fs=void 0)}}function ys(t,e){return"function"==typeof t?gs(t):ps(t,e)}function vs(t,e){let n;const i=()=>{const{currentTime:i}=e,s=(null===i?0:i.value)/100;n!==s&&t(s),n=s};return at.preUpdate(i,!0),()=>lt(i)}function xs(){const{value:t}=ot;null!==t?(t.frameloop.rate.push(ut.delta),t.animations.mainThread.push(mt.mainThread),t.animations.waapi.push(mt.waapi),t.animations.layout.push(mt.layout)):lt(xs)}function ws(t){return t.reduce((t,e)=>t+e,0)/t.length}function Ts(t,e=ws){return 0===t.length?{min:0,max:0,avg:0}:{min:Math.min(...t),max:Math.max(...t),avg:e(t)}}const Ps=t=>Math.round(1e3/t);function bs(){ot.value=null,ot.addProjectionMetrics=null}function Ss(){const{value:t}=ot;if(!t)throw new Error("Stats are not being measured");bs(),lt(xs);const e={frameloop:{setup:Ts(t.frameloop.setup),rate:Ts(t.frameloop.rate),read:Ts(t.frameloop.read),resolveKeyframes:Ts(t.frameloop.resolveKeyframes),preUpdate:Ts(t.frameloop.preUpdate),update:Ts(t.frameloop.update),preRender:Ts(t.frameloop.preRender),render:Ts(t.frameloop.render),postRender:Ts(t.frameloop.postRender)},animations:{mainThread:Ts(t.animations.mainThread),waapi:Ts(t.animations.waapi),layout:Ts(t.animations.layout)},layoutProjection:{nodes:Ts(t.layoutProjection.nodes),calculatedTargetDeltas:Ts(t.layoutProjection.calculatedTargetDeltas),calculatedProjections:Ts(t.layoutProjection.calculatedProjections)}},{rate:n}=e.frameloop;return n.min=Ps(n.min),n.max=Ps(n.max),n.avg=Ps(n.avg),[n.min,n.max]=[n.max,n.min],e}function Es(t){return os(t)&&"svg"===t.tagName}function As(t,e){if("first"===t)return 0;{const n=e-1;return"last"===t?n:n/2}}function Ms(...t){const e=!Array.isArray(t[0]),n=e?0:-1,i=t[0+n],s=We(t[1+n],t[2+n],t[3+n]);return e?s(i):s}function Cs(t){const e=[];Li.current=e;const n=t();Li.current=void 0;const i=ji(n);return function(t,e,n){const i=()=>e.set(n()),s=()=>at.preRender(i,!1,!0),o=t.map(t=>t.on("change",s));e.on("destroy",()=>{o.forEach(t=>t()),lt(i)})}(e,i,t),i}const Vs=t=>Boolean(t&&t.getVelocity);function Rs(t,e,n){const i=t.get();let s,o=null,r=i;const a="string"==typeof i?i.replace(/[\d.-]/g,""):void 0,l=()=>{o&&(o.stop(),o=null)},u=()=>{l(),o=new qe({keyframes:[ks(t.get()),ks(r)],velocity:t.getVelocity(),type:"spring",restDelta:.001,restSpeed:.01,...n,onUpdate:s})};if(t.attach((e,n)=>(r=e,s=t=>n(Ds(t,a)),at.postRender(u),t.get()),l),Vs(e)){const n=e.on("change",e=>t.set(Ds(e,a))),i=t.on("destroy",n);return()=>{n(),i()}}return l}function Ds(t,e){return e?t+e:t}function ks(t){return"number"==typeof t?t:parseFloat(t)}const Ls=[...oi,Wt,Gt],Os=t=>Ls.find(si(t));function js(t){return"layout"===t?"group":"enter"===t||"new"===t?"new":"exit"===t||"old"===t?"old":"group"}let Bs={},Is=null;const Fs=(t,e)=>{Bs[t]=e},Ws=()=>{Is||(Is=document.createElement("style"),Is.id="motion-view");let t="";for(const e in Bs){const n=Bs[e];t+=`${e} {\n`;for(const[e,i]of Object.entries(n))t+=` ${e}: ${i};\n`;t+="}\n"}Is.textContent=t,document.head.appendChild(Is),Bs={}},Us=()=>{Is&&Is.parentElement&&Is.parentElement.removeChild(Is)};function Ns(t){const e=t.match(/::view-transition-(old|new|group|image-pair)\((.*?)\)/);return e?{layer:e[2],type:e[1]}:null}function $s(t){const{effect:e}=t;return!!e&&(e.target===document.documentElement&&e.pseudoElement?.startsWith("::view-transition"))}function zs(){return document.getAnimations().filter($s)}const Xs=["layout","enter","exit","new","old"];function Hs(t){const{update:e,targets:n,options:i}=t;if(!document.startViewTransition)return new Promise(async t=>{await e(),t(new Kn([]))});(function(t,e){return e.has(t)&&Object.keys(e.get(t)).length>0})("root",n)||Fs(":root",{"view-transition-name":"none"}),Fs("::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*)",{"animation-timing-function":"linear !important"}),Ws();const s=document.startViewTransition(async()=>{await e()});return s.finished.finally(()=>{Us()}),new Promise(t=>{s.ready.then(()=>{const e=zs(),s=[];n.forEach((t,e)=>{for(const n of Xs){if(!t[n])continue;const{keyframes:o,options:r}=t[n];for(let[t,a]of Object.entries(o)){if(!a)continue;const o={...ni(i,t),...ni(r,t)},l=js(n);if("opacity"===t&&!Array.isArray(a)){a=["new"===l?0:1,a]}"function"==typeof o.delay&&(o.delay=o.delay(0,1)),o.duration&&(o.duration=O(o.duration)),o.delay&&(o.delay=O(o.delay));const u=new In({...o,element:document.documentElement,name:t,pseudoElement:`::view-transition-${l}(${e})`,keyframes:a});s.push(u)}}});for(const t of e){if("finished"===t.playState)continue;const{effect:e}=t;if(!(e&&e instanceof KeyframeEffect))continue;const{pseudoElement:o}=e;if(!o)continue;const r=Ns(o);if(!r)continue;const a=n.get(r.layer);if(a)Ys(a,"enter")&&Ys(a,"exit")&&e.getKeyframes().some(t=>t.mixBlendMode)?s.push(new _n(t)):t.cancel();else{const n="group"===r.type?"layout":"";let o={...ni(i,n)};o.duration&&(o.duration=O(o.duration)),o=Bn(o);const a=Ln(o.ease,o.duration);e.updateTiming({delay:O(o.delay??0),duration:o.duration,easing:a}),s.push(new _n(t))}}t(new Kn(s))})})}function Ys(t,e){return t?.[e]?.keyframes.opacity}let Ks=[],Gs=null;function _s(){Gs=null;const[t]=Ks;var e;t&&(w(Ks,e=t),Gs=e,Hs(e).then(t=>{e.notifyReady(t),t.finished.finally(_s)}))}function Zs(){for(let t=Ks.length-1;t>=0;t--){const e=Ks[t],{interrupt:n}=e.options;if("immediate"===n){const n=Ks.slice(0,t+1).map(t=>t.update),i=Ks.slice(t+1);e.update=()=>{n.forEach(t=>t())},Ks=[e,...i];break}}Gs&&"immediate"!==Ks[0]?.options.interrupt||_s()}class qs{constructor(t,e={}){var n;this.currentSubject="root",this.targets=new Map,this.notifyReady=V,this.readyPromise=new Promise(t=>{this.notifyReady=t}),this.update=t,this.options={interrupt:"wait",...e},n=this,Ks.push(n),$i.render(Zs)}get(t){return this.currentSubject=t,this}layout(t,e){return this.updateTarget("layout",t,e),this}new(t,e){return this.updateTarget("new",t,e),this}old(t,e){return this.updateTarget("old",t,e),this}enter(t,e){return this.updateTarget("enter",t,e),this}exit(t,e){return this.updateTarget("exit",t,e),this}crossfade(t){return this.updateTarget("enter",{opacity:1},t),this.updateTarget("exit",{opacity:0},t),this}updateTarget(t,e,n={}){const{currentSubject:i,targets:s}=this;s.has(i)||s.set(i,{});s.get(i)[t]={keyframes:e,options:n}}then(t,e){return this.readyPromise.then(t,e)}}const Js=at,Qs=st.reduce((t,e)=>(t[e]=t=>lt(t),t),{}),to=e.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class eo extends i.Component{getSnapshotBeforeUpdate(t){const e=this.props.childRef.current;if(e&&t.isPresent&&!this.props.isPresent){const t=e.offsetParent,n=ki(t)&&t.offsetWidth||0,i=this.props.sizeRef.current;i.height=e.offsetHeight||0,i.width=e.offsetWidth||0,i.top=e.offsetTop,i.left=e.offsetLeft,i.right=n-i.width-i.left}return null}componentDidUpdate(){}render(){return this.props.children}}function no({children:t,isPresent:n,anchorX:s,root:o}){const r=e.useId(),a=e.useRef(null),l=e.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:u}=e.useContext(to);return e.useInsertionEffect(()=>{const{width:t,height:e,top:i,left:c,right:h}=l.current;if(n||!a.current||!t||!e)return;const d="left"===s?`left: ${c}`:`right: ${h}`;a.current.dataset.motionPopId=r;const p=document.createElement("style");u&&(p.nonce=u);const m=o??document.head;return m.appendChild(p),p.sheet&&p.sheet.insertRule(`\n [data-motion-pop-id="${r}"] {\n position: absolute !important;\n width: ${t}px !important;\n height: ${e}px !important;\n ${d}px !important;\n top: ${i}px !important;\n }\n `),()=>{m.contains(p)&&m.removeChild(p)}},[n]),d(eo,{isPresent:n,childRef:a,sizeRef:l,children:i.cloneElement(t,{ref:a})})}const io=({children:t,initial:n,isPresent:s,onExitComplete:o,custom:r,presenceAffectsLayout:a,mode:l,anchorX:u,root:c})=>{const h=f(so),p=e.useId();let m=!0,g=e.useMemo(()=>(m=!1,{id:p,initial:n,isPresent:s,custom:r,onExitComplete:t=>{h.set(t,!0);for(const t of h.values())if(!t)return;o&&o()},register:t=>(h.set(t,!1),()=>h.delete(t))}),[s,h,o]);return a&&m&&(g={...g}),e.useMemo(()=>{h.forEach((t,e)=>h.set(e,!1))},[s]),i.useEffect(()=>{!s&&!h.size&&o&&o()},[s]),"popLayout"===l&&(t=d(no,{isPresent:s,anchorX:u,root:c,children:t})),d(v.Provider,{value:g,children:t})};function so(){return new Map}function oo(t=!0){const n=e.useContext(v);if(null===n)return[!0,null];const{isPresent:i,onExitComplete:s,register:o}=n,r=e.useId();e.useEffect(()=>{if(t)return o(r)},[t]);const a=e.useCallback(()=>t&&s&&s(r),[r,s,t]);return!i&&s?[!1,a]:[!0]}const ro=t=>t.key||"";function ao(t){const n=[];return e.Children.forEach(t,t=>{e.isValidElement(t)&&n.push(t)}),n}const lo=e.createContext(null);function uo(t){return t.max-t.min}function co(t,e,n,i=.5){t.origin=i,t.originPoint=Jt(e.min,e.max,t.origin),t.scale=uo(n)/uo(e),t.translate=Jt(n.min,n.max,t.origin)-t.originPoint,(t.scale>=.9999&&t.scale<=1.0001||isNaN(t.scale))&&(t.scale=1),(t.translate>=-.01&&t.translate<=.01||isNaN(t.translate))&&(t.translate=0)}function ho(t,e,n,i){co(t.x,e.x,n.x,i?i.originX:void 0),co(t.y,e.y,n.y,i?i.originY:void 0)}function po(t,e,n){t.min=n.min+e.min,t.max=t.min+uo(e)}function mo(t,e,n){t.min=e.min-n.min,t.max=t.min+uo(e)}function fo(t,e,n){mo(t.x,e.x,n.x),mo(t.y,e.y,n.y)}const go=t=>!t.isLayoutDirty&&t.willUpdate(!1);function yo(){const t=new Set,e=new WeakMap,n=()=>t.forEach(go);return{add:i=>{t.add(i),e.set(i,i.addEventListener("willUpdate",n))},remove:i=>{t.delete(i);const s=e.get(i);s&&(s(),e.delete(i)),n()},dirty:n}}const vo=t=>null!==t;const xo={type:"spring",stiffness:500,damping:25,restSpeed:10},wo={type:"keyframes",duration:.8},To={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Po=(t,{keyframes:e})=>e.length>2?wo:dn.has(t)?t.startsWith("scale")?{type:"spring",stiffness:550,damping:0===e[1]?2*Math.sqrt(550):30,restSpeed:10}:xo:To;const bo=(t,e,n,i={},s,o)=>r=>{const a=ni(i,t)||{},l=a.delay||i.delay||0;let{elapsed:u=0}=i;u-=O(l);const c={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-u,onUpdate:t=>{e.set(t),a.onUpdate&&a.onUpdate(t)},onComplete:()=>{r(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:s};(function({when:t,delay:e,delayChildren:n,staggerChildren:i,staggerDirection:s,repeat:o,repeatType:r,repeatDelay:a,from:l,elapsed:u,...c}){return!!Object.keys(c).length})(a)||Object.assign(c,Po(t,c)),c.duration&&(c.duration=O(c.duration)),c.repeatDelay&&(c.repeatDelay=O(c.repeatDelay)),void 0!==c.from&&(c.keyframes[0]=c.from);let h=!1;if((!1===c.type||0===c.duration&&!c.repeatDelay)&&($n(c),0===c.delay&&(h=!0)),(S.instantAnimations||S.skipAnimations)&&(h=!0,$n(c),c.delay=0),c.allowFlatten=!a.type&&!a.ease,h&&!o&&void 0!==e.get()){const t=function(t,{repeat:e,repeatType:n="loop"},i){const s=t.filter(vo),o=e&&"loop"!==n&&e%2==1?0:s.length-1;return o&&void 0!==i?i:s[o]}(c.keyframes,a);if(void 0!==t)return void at.update(()=>{c.onUpdate(t),c.onComplete()})}return a.isSync?new qe(c):new Yn(c)};function So(t,e,n){const i=Vs(t)?t:ji(t);return i.start(bo("",i,e,n)),i.animation}const Eo=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Ao="framerAppearId",Mo="data-"+Eo(Ao);function Co(t){return t.props[Mo]}const Vo=(t,e)=>t.depth-e.depth;class Ro{constructor(){this.children=[],this.isDirty=!1}add(t){x(this.children,t),this.isDirty=!0}remove(t){w(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(Vo),this.isDirty=!1,this.children.forEach(t)}}function Do(t,e){const n=pt.now(),i=({timestamp:s})=>{const o=s-n;o>=e&&(lt(i),t(o-e))};return at.setup(i,!0),()=>lt(i)}function ko(t){return Vs(t)?t.get():t}const Lo=["TopLeft","TopRight","BottomLeft","BottomRight"],Oo=Lo.length,jo=t=>"string"==typeof t?parseFloat(t):t,Bo=t=>"number"==typeof t||Ot.test(t);function Io(t,e){return void 0!==t[e]?t[e]:t.borderRadius}const Fo=Uo(0,.5,G),Wo=Uo(.5,.95,V);function Uo(t,e,n){return i=>ie?1:n(k(t,e,i))}function No(t,e){t.min=e.min,t.max=e.max}function $o(t,e){No(t.x,e.x),No(t.y,e.y)}function zo(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Xo(t){return void 0===t||1===t}function Ho({scale:t,scaleX:e,scaleY:n}){return!Xo(t)||!Xo(e)||!Xo(n)}function Yo(t){return Ho(t)||Ko(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Ko(t){return Go(t.x)||Go(t.y)}function Go(t){return t&&"0%"!==t}function _o(t,e,n){return n+e*(t-n)}function Zo(t,e,n,i,s){return void 0!==s&&(t=_o(t,s,i)),_o(t,n,i)+e}function qo(t,e=0,n=1,i,s){t.min=Zo(t.min,e,n,i,s),t.max=Zo(t.max,e,n,i,s)}function Jo(t,{x:e,y:n}){qo(t.x,e.translate,e.scale,e.originPoint),qo(t.y,n.translate,n.scale,n.originPoint)}const Qo=.999999999999,tr=1.0000000000001;function er(t,e){t.min=t.min+e,t.max=t.max+e}function nr(t,e,n,i,s=.5){qo(t,e,n,Jt(t.min,t.max,s),i)}function ir(t,e){nr(t.x,e.x,e.scaleX,e.scale,e.originX),nr(t.y,e.y,e.scaleY,e.scale,e.originY)}function sr(t,e,n,i,s){return t=_o(t-=e,1/n,i),void 0!==s&&(t=_o(t,1/s,i)),t}function or(t,e,[n,i,s],o,r){!function(t,e=0,n=1,i=.5,s,o=t,r=t){Lt.test(e)&&(e=parseFloat(e),e=Jt(r.min,r.max,e/100)-r.min);if("number"!=typeof e)return;let a=Jt(o.min,o.max,i);t===o&&(a-=e),t.min=sr(t.min,e,n,a,s),t.max=sr(t.max,e,n,a,s)}(t,e[n],e[i],e[s],e.scale,o,r)}const rr=["x","scaleX","originX"],ar=["y","scaleY","originY"];function lr(t,e,n,i){or(t.x,e,rr,n?n.x:void 0,i?i.x:void 0),or(t.y,e,ar,n?n.y:void 0,i?i.y:void 0)}const ur=()=>({x:{min:0,max:0},y:{min:0,max:0}});function cr(t){return 0===t.translate&&1===t.scale}function hr(t){return cr(t.x)&&cr(t.y)}function dr(t,e){return t.min===e.min&&t.max===e.max}function pr(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function mr(t,e){return pr(t.x,e.x)&&pr(t.y,e.y)}function fr(t){return uo(t.x)/uo(t.y)}function gr(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class yr{constructor(){this.members=[]}add(t){x(this.members,t),t.scheduleRender()}remove(t){if(w(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const t=this.members[this.members.length-1];t&&this.promote(t)}}relegate(t){const e=this.members.findIndex(e=>t===e);if(0===e)return!1;let n;for(let t=e;t>=0;t--){const e=this.members[t];if(!1!==e.isPresent){n=e;break}}return!!n&&(this.promote(n),!0)}promote(t,e){const n=this.lead;if(t!==n&&(this.prevLead=n,this.lead=t,t.show(),n)){n.instance&&n.scheduleRender(),t.scheduleRender(),t.resumeFrom=n,e&&(t.resumeFrom.preserveOpacity=!0),n.snapshot&&(t.snapshot=n.snapshot,t.snapshot.latestValues=n.animationValues||n.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:i}=t.options;!1===i&&n.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:e,resumingFrom:n}=t;e.onExitComplete&&e.onExitComplete(),n&&n.options.onExitComplete&&n.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}const vr={};function xr(t){for(const e in t)vr[e]=t[e],gt(e)&&(vr[e].isCSSVariable=!0)}function wr(t){return[t("x"),t("y")]}const Tr={hasAnimatedSinceResize:!0,hasEverUpdated:!1},Pr={nodes:0,calculatedTargetDeltas:0,calculatedProjections:0},br=["","X","Y","Z"];let Sr=0;function Er(t,e,n,i){const{latestValues:s}=e;s[t]&&(n[t]=s[t],e.setStaticValue(t,0),i&&(i[t]=0))}function Ar(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=Co(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:e,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",at,!(e||i))}const{parent:i}=t;i&&!i.hasCheckedOptimisedAppear&&Ar(i)}function Mr({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:i,resetTransform:s}){return class{constructor(t={},n=e?.()){this.id=Sr++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,ot.value&&(Pr.nodes=Pr.calculatedTargetDeltas=Pr.calculatedProjections=0),this.nodes.forEach(Rr),this.nodes.forEach(Ir),this.nodes.forEach(Fr),this.nodes.forEach(Dr),ot.addProjectionMetrics&&ot.addProjectionMetrics(Pr)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=t,this.root=n?n.root||n:this,this.path=n?[...n.path,n]:[],this.parent=n,this.depth=n?n.depth+1:0;for(let t=0;tthis.root.updateBlockedByResize=!1;at.read(()=>{i=window.innerWidth}),t(e,()=>{const t=window.innerWidth;t!==i&&(i=t,this.root.updateBlockedByResize=!0,n&&n(),n=Do(s,250),Tr.hasAnimatedSinceResize&&(Tr.hasAnimatedSinceResize=!1,this.nodes.forEach(Br)))})}n&&this.root.registerSharedNode(n,this),!1!==this.options.animate&&s&&(n||i)&&this.addEventListener("didUpdate",({delta:t,hasLayoutChanged:e,hasRelativeLayoutChanged:n,layout:i})=>{if(this.isTreeAnimationBlocked())return this.target=void 0,void(this.relativeTarget=void 0);const o=this.options.transition||s.getDefaultTransition()||Xr,{onLayoutAnimationStart:r,onLayoutAnimationComplete:a}=s.getProps(),l=!this.targetLayout||!mr(this.targetLayout,i),u=!e&&n;if(this.options.layoutRoot||this.resumeFrom||u||e&&(l||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const e={...ni(o,"layout"),onPlay:r,onComplete:a};(s.shouldReduceMotion||this.options.layoutRoot)&&(e.delay=0,e.type=!1),this.startAnimation(e),this.setAnimationOrigin(t,u)}else e||Br(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=i})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const t=this.getStack();t&&t.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),lt(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(Wr),this.animationId++)}getTransformTemplate(){const{visualElement:t}=this.options;return t&&t.getProps().transformTemplate}willUpdate(t=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked())return void(this.options.onExitComplete&&this.options.onExitComplete());if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Ar(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let t=0;t{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){!this.snapshot&&this.instance&&(this.snapshot=this.measure(),!this.snapshot||uo(this.snapshot.measuredBox.x)||uo(this.snapshot.measuredBox.y)||(this.snapshot=void 0))}updateLayout(){if(!this.instance)return;if(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead()||this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let t=0;tQo&&(e.x=1),e.yQo&&(e.y=1)}(this.layoutCorrected,this.treeScale,this.path,e),!t.layout||t.target||1===this.treeScale.x&&1===this.treeScale.y||(t.target=t.layout.layoutBox,t.targetWithTransforms={x:{min:0,max:0},y:{min:0,max:0}});const{target:a}=t;a?(this.projectionDelta&&this.prevProjectionDelta?(zo(this.prevProjectionDelta.x,this.projectionDelta.x),zo(this.prevProjectionDelta.y,this.projectionDelta.y)):this.createProjectionDeltas(),ho(this.projectionDelta,this.layoutCorrected,a,this.latestValues),this.treeScale.x===o&&this.treeScale.y===r&&gr(this.projectionDelta.x,this.prevProjectionDelta.x)&&gr(this.projectionDelta.y,this.prevProjectionDelta.y)||(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",a)),ot.value&&Pr.calculatedProjections++):this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender())}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(t=!0){if(this.options.visualElement?.scheduleRender(),t){const t=this.getStack();t&&t.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}},this.projectionDelta={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}},this.projectionDeltaWithTransform={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}}}setAnimationOrigin(t,e=!1){const n=this.snapshot,i=n?n.latestValues:{},s={...this.latestValues},o={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}};this.relativeParent&&this.relativeParent.options.layoutRoot||(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!e;const r={x:{min:0,max:0},y:{min:0,max:0}},a=(n?n.source:void 0)!==(this.layout?this.layout.source:void 0),l=this.getStack(),u=!l||l.members.length<=1,c=Boolean(a&&!u&&!0===this.options.crossfade&&!this.path.some(zr));let h;this.animationProgress=0,this.mixTargetDelta=e=>{const n=e/1e3;var l,d;Nr(o.x,t.x,n),Nr(o.y,t.y,n),this.setTargetDelta(o),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(fo(r,this.layout.layoutBox,this.relativeParent.layout.layoutBox),function(t,e,n,i){$r(t.x,e.x,n.x,i),$r(t.y,e.y,n.y,i)}(this.relativeTarget,this.relativeTargetOrigin,r,n),h&&(l=this.relativeTarget,d=h,dr(l.x,d.x)&&dr(l.y,d.y))&&(this.isProjectionDirty=!1),h||(h={x:{min:0,max:0},y:{min:0,max:0}}),$o(h,this.relativeTarget)),a&&(this.animationValues=s,function(t,e,n,i,s,o){s?(t.opacity=Jt(0,n.opacity??1,Fo(i)),t.opacityExit=Jt(e.opacity??1,0,Wo(i))):o&&(t.opacity=Jt(e.opacity??1,n.opacity??1,i));for(let s=0;s{Tr.hasAnimatedSinceResize=!0,mt.layout++,this.motionValue||(this.motionValue=ji(0)),this.currentAnimation=So(this.motionValue,[0,1e3],{...t,velocity:0,isSync:!0,onUpdate:e=>{this.mixTargetDelta(e),t.onUpdate&&t.onUpdate(e)},onStop:()=>{mt.layout--},onComplete:()=>{mt.layout--,t.onComplete&&t.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const t=this.getStack();t&&t.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(1e3),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const t=this.getLead();let{targetWithTransforms:e,target:n,layout:i,latestValues:s}=t;if(e&&n&&i){if(this!==t&&this.layout&&i&&Gr(this.options.animationType,this.layout.layoutBox,i.layoutBox)){n=this.target||{x:{min:0,max:0},y:{min:0,max:0}};const e=uo(this.layout.layoutBox.x);n.x.min=t.target.x.min,n.x.max=n.x.min+e;const i=uo(this.layout.layoutBox.y);n.y.min=t.target.y.min,n.y.max=n.y.min+i}$o(e,n),ir(e,s),ho(this.projectionDeltaWithTransform,this.layoutCorrected,e,s)}}registerSharedNode(t,e){this.sharedNodes.has(t)||this.sharedNodes.set(t,new yr);this.sharedNodes.get(t).add(e);const n=e.options.initialPromotionConfig;e.promote({transition:n?n.transition:void 0,preserveFollowOpacity:n&&n.shouldPreserveFollowOpacity?n.shouldPreserveFollowOpacity(e):void 0})}isLead(){const t=this.getStack();return!t||t.lead===this}getLead(){const{layoutId:t}=this.options;return t&&this.getStack()?.lead||this}getPrevLead(){const{layoutId:t}=this.options;return t?this.getStack()?.prevLead:void 0}getStack(){const{layoutId:t}=this.options;if(t)return this.root.sharedNodes.get(t)}promote({needsReset:t,transition:e,preserveFollowOpacity:n}={}){const i=this.getStack();i&&i.promote(this,n),t&&(this.projectionDelta=void 0,this.needsReset=!0),e&&this.setOptions({transition:e})}relegate(){const t=this.getStack();return!!t&&t.relegate(this)}resetSkewAndRotation(){const{visualElement:t}=this.options;if(!t)return;let e=!1;const{latestValues:n}=t;if((n.z||n.rotate||n.rotateX||n.rotateY||n.rotateZ||n.skewX||n.skewY)&&(e=!0),!e)return;const i={};n.z&&Er("z",t,i,this.animationValues);for(let e=0;et.currentAnimation?.stop()),this.root.nodes.forEach(Lr),this.root.sharedNodes.clear()}}}function Cr(t){t.updateLayout()}function Vr(t){const e=t.resumeFrom?.snapshot||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:i}=t.layout,{animationType:s}=t.options,o=e.source!==t.layout.source;"size"===s?wr(t=>{const i=o?e.measuredBox[t]:e.layoutBox[t],s=uo(i);i.min=n[t].min,i.max=i.min+s}):Gr(s,e.layoutBox,n)&&wr(i=>{const s=o?e.measuredBox[i]:e.layoutBox[i],r=uo(n[i]);s.max=s.min+r,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[i].max=t.relativeTarget[i].min+r)});const r={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}};ho(r,n,e.layoutBox);const a={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}};o?ho(a,t.applyTransform(i,!0),e.measuredBox):ho(a,n,e.layoutBox);const l=!hr(r);let u=!1;if(!t.resumeFrom){const i=t.getClosestProjectingParent();if(i&&!i.resumeFrom){const{snapshot:s,layout:o}=i;if(s&&o){const r={x:{min:0,max:0},y:{min:0,max:0}};fo(r,e.layoutBox,s.layoutBox);const a={x:{min:0,max:0},y:{min:0,max:0}};fo(a,n,o.layoutBox),mr(r,a)||(u=!0),i.options.layoutRoot&&(t.relativeTarget=a,t.relativeTargetOrigin=r,t.relativeParent=i)}}}t.notifyListeners("didUpdate",{layout:n,snapshot:e,delta:a,layoutDelta:r,hasLayoutChanged:l,hasRelativeLayoutChanged:u})}else if(t.isLead()){const{onExitComplete:e}=t.options;e&&e()}t.options.transition=void 0}function Rr(t){ot.value&&Pr.nodes++,t.parent&&(t.isProjecting()||(t.isProjectionDirty=t.parent.isProjectionDirty),t.isSharedProjectionDirty||(t.isSharedProjectionDirty=Boolean(t.isProjectionDirty||t.parent.isProjectionDirty||t.parent.isSharedProjectionDirty)),t.isTransformDirty||(t.isTransformDirty=t.parent.isTransformDirty))}function Dr(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function kr(t){t.clearSnapshot()}function Lr(t){t.clearMeasurements()}function Or(t){t.isLayoutDirty=!1}function jr(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Br(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function Ir(t){t.resolveTargetDelta()}function Fr(t){t.calcProjection()}function Wr(t){t.resetSkewAndRotation()}function Ur(t){t.removeLeadSnapshot()}function Nr(t,e,n){t.translate=Jt(e.translate,0,n),t.scale=Jt(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function $r(t,e,n,i){t.min=Jt(e.min,n.min,i),t.max=Jt(e.max,n.max,i)}function zr(t){return t.animationValues&&void 0!==t.animationValues.opacityExit}const Xr={duration:.45,ease:[.4,0,.1,1]},Hr=t=>"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Yr=Hr("applewebkit/")&&!Hr("chrome/")?Math.round:V;function Kr(t){t.min=Yr(t.min),t.max=Yr(t.max)}function Gr(t,e,n){return"position"===t||"preserve-aspect"===t&&(i=fr(e),s=fr(n),o=.2,!(Math.abs(i-s)<=o));var i,s,o}function _r(t){return t!==t.root&&t.scroll?.wasRoot}function Zr(t,e,n,i={passive:!0}){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n)}const qr=Mr({attachResizeListener:(t,e)=>Zr(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Jr={current:void 0},Qr=Mr({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Jr.current){const t=new qr({});t.mount(window),t.setOptions({layoutScroll:!0}),Jr.current=t}return Jr.current},resetTransform:(t,e)=>{t.style.transform=void 0!==e?e:"none"},checkIsScrollRoot:t=>Boolean("fixed"===window.getComputedStyle(t).position)});function ta(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const ea={correct:(t,e)=>{if(!e.target)return t;if("string"==typeof t){if(!Ot.test(t))return t;t=parseFloat(t)}return`${ta(t,e.target.x)}% ${ta(t,e.target.y)}%`}},na={correct:(t,{treeScale:e,projectionDelta:n})=>{const i=t,s=Gt.parse(t);if(s.length>5)return i;const o=Gt.createTransformer(t),r="number"!=typeof s[0]?1:0,a=n.x.scale*e.x,l=n.y.scale*e.y;s[0+r]/=a,s[1+r]/=l;const u=Jt(a,l,.5);return"number"==typeof s[2+r]&&(s[2+r]/=u),"number"==typeof s[3+r]&&(s[3+r]/=u),o(s)}};function ia({top:t,left:e,right:n,bottom:i}){return{x:{min:e,max:n},y:{min:t,max:i}}}function sa(t,e){return ia(function(t,e){if(!e)return t;const n=e({x:t.left,y:t.top}),i=e({x:t.right,y:t.bottom});return{top:n.y,left:n.x,bottom:i.y,right:i.x}}(t.getBoundingClientRect(),e))}const oa={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},ra={};for(const t in oa)ra[t]={isEnabled:e=>oa[t].some(t=>!!e[t])};const aa={current:null},la={current:!1};function ua(){if(la.current=!0,g)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>aa.current=t.matches;t.addEventListener("change",e),e()}else aa.current=!1}const ca=new WeakMap;function ha(t){return null!==t&&"object"==typeof t&&"function"==typeof t.start}function da(t){return"string"==typeof t||Array.isArray(t)}const pa=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],ma=["initial",...pa];function fa(t){return ha(t.animate)||ma.some(e=>da(t[e]))}function ga(t){return Boolean(fa(t)||t.variants)}function ya(t){const e=[{},{}];return t?.values.forEach((t,n)=>{e[0][n]=t.get(),e[1][n]=t.getVelocity()}),e}function va(t,e,n,i){if("function"==typeof e){const[s,o]=ya(i);e=e(void 0!==n?n:t.custom,s,o)}if("string"==typeof e&&(e=t.variants&&t.variants[e]),"function"==typeof e){const[s,o]=ya(i);e=e(void 0!==n?n:t.custom,s,o)}return e}const xa=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class wa{scrapeMotionValuesFromProps(t,e,n){return{}}constructor({parent:t,props:e,presenceContext:n,reducedMotionConfig:i,blockInitialAnimation:s,visualState:o},r={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Sn,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const t=pt.now();this.renderScheduledAtthis.bindToMotionValue(e,t)),la.current||ua(),this.shouldReduceMotion="never"!==this.reducedMotionConfig&&("always"===this.reducedMotionConfig||aa.current),this.parent?.addChild(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),lt(this.notifyUpdate),lt(this.render),this.valueSubscriptions.forEach(t=>t()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const t in this.events)this.events[t].clear();for(const t in this.features){const e=this.features[t];e&&(e.unmount(),e.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,e){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const n=dn.has(t);n&&this.onBindTransform&&this.onBindTransform();const i=e.on("change",e=>{this.latestValues[t]=e,this.props.onUpdate&&at.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let s;window.MotionCheckAppearSync&&(s=window.MotionCheckAppearSync(this,t,e)),this.valueSubscriptions.set(t,()=>{i(),s&&s(),e.owner&&e.stop()})}sortNodePosition(t){return this.current&&this.sortInstanceNodePosition&&this.type===t.type?this.sortInstanceNodePosition(this.current,t.current):0}updateFeatures(){let t="animation";for(t in ra){const e=ra[t];if(!e)continue;const{isEnabled:n,Feature:i}=e;if(!this.features[t]&&i&&n(this.props)&&(this.features[t]=new i(this)),this.features[t]){const e=this.features[t];e.isMounted?e.update():(e.mount(),e.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):{x:{min:0,max:0},y:{min:0,max:0}}}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,e){this.latestValues[t]=e}update(t,e){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=e;for(let e=0;ee.variantChildren.delete(t)}addValue(t,e){const n=this.values.get(t);e!==n&&(n&&this.removeValue(t),this.bindToMotionValue(t,e),this.values.set(t,e),this.latestValues[t]=e.get())}removeValue(t){this.values.delete(t);const e=this.valueSubscriptions.get(t);e&&(e(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,e){if(this.props.values&&this.props.values[t])return this.props.values[t];let n=this.values.get(t);return void 0===n&&void 0!==e&&(n=ji(null===e?void 0:e,{owner:this}),this.addValue(t,n)),n}readValue(t,e){let n=void 0===this.latestValues[t]&&this.current?this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options):this.latestValues[t];return null!=n&&("string"==typeof n&&(E(n)||M(n))?n=parseFloat(n):!Os(n)&&Gt.test(e)&&(n=yi(t,e)),this.setBaseTarget(t,Vs(n)?n.get():n)),Vs(n)?n.get():n}setBaseTarget(t,e){this.baseTarget[t]=e}getBaseTarget(t){const{initial:e}=this.props;let n;if("string"==typeof e||"object"==typeof e){const i=va(this.props,e,this.presenceContext?.custom);i&&(n=i[t])}if(e&&void 0!==n)return n;const i=this.getBaseTargetFromProps(this.props,t);return void 0===i||Vs(i)?void 0!==this.initialValues[t]&&void 0===n?void 0:this.baseTarget[t]:i}on(t,e){return this.events[t]||(this.events[t]=new L),this.events[t].add(e)}notify(t,...e){this.events[t]&&this.events[t].notify(...e)}scheduleRenderMicrotask(){$i.render(this.render)}}class Ta extends wa{constructor(){super(...arguments),this.KeyframeResolver=xi}sortInstanceNodePosition(t,e){return 2&t.compareDocumentPosition(e)?1:-1}getBaseTargetFromProps(t,e){return t.style?t.style[e]:void 0}removeValueFromRenderState(t,{vars:e,style:n}){delete e[t],delete n[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;Vs(t)&&(this.childSubscription=t.on("change",t=>{this.current&&(this.current.textContent=`${t}`)}))}}const Pa={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},ba=hn.length;function Sa(t,e,n){let i="",s=!0;for(let o=0;o(t.current=!0,()=>{t.current=!1}),[]),t}(),[n,i]=e.useState(0),s=e.useCallback(()=>{t.current&&i(n+1)},[n]);return[e.useCallback(()=>at.postRender(s),[s]),n]}const Da=t=>!0===t,ka=({children:t,id:n,inherit:i=!0})=>{const s=e.useContext(m),o=e.useContext(lo),[r,a]=Ra(),l=e.useRef(null),u=s.id||o;null===l.current&&((t=>Da(!0===t)||"id"===t)(i)&&u&&(n=n?u+"-"+n:u),l.current={id:n,group:Da(i)&&s.group||yo()});const c=e.useMemo(()=>({...l.current,forceRender:r}),[a]);return d(m.Provider,{value:c,children:t})},La=e.createContext({strict:!1});function Oa(t){for(const e in t)ra[e]={...ra[e],...t[e]}}function ja(t){return"function"==typeof t}const Ba=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function Ia(t){return t.startsWith("while")||t.startsWith("drag")&&"draggable"!==t||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||Ba.has(t)}let Fa=t=>!Ia(t);function Wa(t){"function"==typeof t&&(Fa=e=>e.startsWith("on")?!Ia(e):t(e))}try{Wa(require("@emotion/is-prop-valid").default)}catch{}function Ua(t,e,n){const i={};for(const s in t)"values"===s&&"object"==typeof t.values||(Fa(s)||!0===n&&Ia(s)||!e&&!Ia(s)||t.draggable&&s.startsWith("onDrag"))&&(i[s]=t[s]);return i}const Na=e.createContext(null),$a={offset:"stroke-dashoffset",array:"stroke-dasharray"},za={offset:"strokeDashoffset",array:"strokeDasharray"};function Xa(t,{attrX:e,attrY:n,attrScale:i,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,u,c){if(Ea(t,a,u),l)return void(t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox));t.attrs=t.style,t.style={};const{attrs:h,style:d}=t;h.transform&&(d.transform=h.transform,delete h.transform),(d.transform||h.transformOrigin)&&(d.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),d.transform&&(d.transformBox=c?.transformBox??"fill-box",delete h.transformBox),void 0!==e&&(h.x=e),void 0!==n&&(h.y=n),void 0!==i&&(h.scale=i),void 0!==s&&function(t,e,n=1,i=0,s=!0){t.pathLength=1;const o=s?$a:za;t[o.offset]=Ot.transform(-i);const r=Ot.transform(e),a=Ot.transform(n);t[o.array]=`${r} ${a}`}(h,s,o,r,!1)}const Ha=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]),Ya=t=>"string"==typeof t&&"svg"===t.toLowerCase();function Ka(t,e,n){const i=Ca(t,e,n);for(const n in t)if(Vs(t[n])||Vs(e[n])){i[-1!==hn.indexOf(n)?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n]=t[n]}return i}class Ga extends Ta{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ur}getBaseTargetFromProps(t,e){return t[e]}readValueFromInstance(t,e){if(dn.has(e)){const t=gi(e);return t&&t.default||0}return e=Ha.has(e)?e:Eo(e),t.getAttribute(e)}scrapeMotionValuesFromProps(t,e,n){return Ka(t,e,n)}build(t,e,n){Xa(t,e,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(t,e,n,i){!function(t,e,n,i){Aa(t,e,void 0,i);for(const n in e.attrs)t.setAttribute(Ha.has(n)?n:Eo(n),e.attrs[n])}(t,e,0,i)}mount(t){this.isSVGTag=Ya(t.tagName),super.mount(t)}}const _a=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function Za(t){return"string"==typeof t&&!t.includes("-")&&!!(_a.indexOf(t)>-1||/[A-Z]/u.test(t))}const qa=(t,n)=>Za(t)?new Ga(n):new Va(n,{allowProjection:t!==e.Fragment}),Ja=e.createContext({});function Qa(t){const{initial:n,animate:i}=function(t,e){if(fa(t)){const{initial:e,animate:n}=t;return{initial:!1===e||da(e)?e:void 0,animate:da(n)?n:void 0}}return!1!==t.inherit?e:{}}(t,e.useContext(Ja));return e.useMemo(()=>({initial:n,animate:i}),[tl(n),tl(i)])}function tl(t){return Array.isArray(t)?t.join(" "):t}const el=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function nl(t,e,n){for(const i in e)Vs(e[i])||Ma(i,n)||(t[i]=e[i])}function il(t,n){const i={};return nl(i,t.style||{},t),Object.assign(i,function({transformTemplate:t},n){return e.useMemo(()=>{const e={style:{},transform:{},transformOrigin:{},vars:{}};return Ea(e,n,t),Object.assign({},e.vars,e.style)},[n])}(t,n)),i}function sl(t,e){const n={},i=il(t,e);return t.drag&&!1!==t.dragListener&&(n.draggable=!1,i.userSelect=i.WebkitUserSelect=i.WebkitTouchCallout="none",i.touchAction=!0===t.drag?"none":"pan-"+("x"===t.drag?"y":"x")),void 0===t.tabIndex&&(t.onTap||t.onTapStart||t.whileTap)&&(n.tabIndex=0),n.style=i,n}const ol=()=>({style:{},transform:{},transformOrigin:{},vars:{},attrs:{}});function rl(t,n,i,s){const o=e.useMemo(()=>{const e={style:{},transform:{},transformOrigin:{},vars:{},attrs:{}};return Xa(e,n,Ya(s),t.transformTemplate,t.style),{...e.attrs,style:{...e.style}}},[n]);if(t.style){const e={};nl(e,t.style,t),o.style={...e,...o.style}}return o}function al(t,n,i,{latestValues:s},o,r=!1){const a=(Za(t)?rl:sl)(n,s,o,t),l=Ua(n,"string"==typeof t,r),u=t!==e.Fragment?{...l,...a,ref:i}:{},{children:c}=n,h=e.useMemo(()=>Vs(c)?c.get():c,[c]);return e.createElement(t,{...u,children:h})}function ll(t,e,n,i){const s={},o=i(t,{});for(const t in o)s[t]=ko(o[t]);let{initial:r,animate:a}=t;const l=fa(t),u=ga(t);e&&u&&!l&&!1!==t.inherit&&(void 0===r&&(r=e.initial),void 0===a&&(a=e.animate));let c=!!n&&!1===n.initial;c=c||!1===r;const h=c?a:r;if(h&&"boolean"!=typeof h&&!ha(h)){const e=Array.isArray(h)?h:[h];for(let n=0;n(n,i)=>{const s=e.useContext(Ja),o=e.useContext(v),r=()=>function({scrapeMotionValuesFromProps:t,createRenderState:e},n,i,s){return{latestValues:ll(n,i,s,t),renderState:e()}}(t,n,s,o);return i?r():f(r)},cl=ul({scrapeMotionValuesFromProps:Ca,createRenderState:el}),hl=ul({scrapeMotionValuesFromProps:Ka,createRenderState:ol}),dl=Symbol.for("motionComponentSymbol");function pl(t){return t&&"object"==typeof t&&Object.prototype.hasOwnProperty.call(t,"current")}function ml(t,n,i){return e.useCallback(e=>{e&&t.onMount&&t.onMount(e),n&&(e?n.mount(e):n.unmount()),i&&("function"==typeof i?i(e):pl(i)&&(i.current=e))},[n])}const fl=e.createContext({});function gl(t,n,i,s,o){const{visualElement:r}=e.useContext(Ja),a=e.useContext(La),l=e.useContext(v),u=e.useContext(to).reducedMotion,c=e.useRef(null);s=s||a.renderer,!c.current&&s&&(c.current=s(t,{visualState:n,parent:r,props:i,presenceContext:l,blockInitialAnimation:!!l&&!1===l.initial,reducedMotionConfig:u}));const h=c.current,d=e.useContext(fl);!h||h.projection||!o||"html"!==h.type&&"svg"!==h.type||function(t,e,n,i){const{layoutId:s,layout:o,drag:r,dragConstraints:a,layoutScroll:l,layoutRoot:u,layoutCrossfade:c}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:yl(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:Boolean(r)||a&&pl(a),visualElement:t,animationType:"string"==typeof o?o:"both",initialPromotionConfig:i,crossfade:c,layoutScroll:l,layoutRoot:u})}(c.current,i,o,d);const p=e.useRef(!1);e.useInsertionEffect(()=>{h&&p.current&&h.update(i,l)});const m=i[Mo],f=e.useRef(Boolean(m)&&!window.MotionHandoffIsComplete?.(m)&&window.MotionHasOptimisedAnimation?.(m));return y(()=>{h&&(p.current=!0,window.MotionIsMounted=!0,h.updateFeatures(),h.scheduleRenderMicrotask(),f.current&&h.animationState&&h.animationState.animateChanges())}),e.useEffect(()=>{h&&(!f.current&&h.animationState&&h.animationState.animateChanges(),f.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(m)}),f.current=!1),h.enteringChildren=void 0)}),h}function yl(t){if(t)return!1!==t.options.allowProjection?t.projection:yl(t.parent)}function vl(t,{forwardMotionProps:n=!1}={},i,s){i&&Oa(i);const o=Za(t)?hl:cl;function r(i,r){let a;const l={...e.useContext(to),...i,layoutId:xl(i)},{isStatic:u}=l,c=Qa(i),h=o(i,u);if(!u&&g){e.useContext(La).strict;const n=function(t){const{drag:e,layout:n}=ra;if(!e&&!n)return{};const i={...e,...n};return{MeasureLayout:e?.isEnabled(t)||n?.isEnabled(t)?i.MeasureLayout:void 0,ProjectionNode:i.ProjectionNode}}(l);a=n.MeasureLayout,c.visualElement=gl(t,h,l,s,n.ProjectionNode)}return p(Ja.Provider,{value:c,children:[a&&c.visualElement?d(a,{visualElement:c.visualElement,...l}):null,al(t,i,ml(h,c.visualElement,r),h,u,n)]})}r.displayName=`motion.${"string"==typeof t?t:`create(${t.displayName??t.name??""})`}`;const a=e.forwardRef(r);return a[dl]=t,a}function xl({layoutId:t}){const n=e.useContext(m).id;return n&&void 0!==t?n+"-"+t:t}function wl(t,e){if("undefined"==typeof Proxy)return vl;const n=new Map,i=(n,i)=>vl(n,i,t,e);return new Proxy((t,e)=>i(t,e),{get:(s,o)=>"create"===o?i:(n.has(o)||n.set(o,vl(o,void 0,t,e)),n.get(o))})}function Tl(t,e,n){const i=t.getProps();return va(i,e,void 0!==n?n:i.custom,t)}const Pl=t=>Array.isArray(t);function bl(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,ji(n))}function Sl(t){return Pl(t)?t[t.length-1]||0:t}function El(t,e){const n=Tl(t,e);let{transitionEnd:i={},transition:s={},...o}=n||{};o={...o,...i};for(const e in o){bl(t,e,Sl(o[e]))}}function Al(t,e){const n=t.getValue("willChange");if(i=n,Boolean(Vs(i)&&i.add))return n.add(e);if(!n&&S.WillChange){const n=new S.WillChange("auto");t.addValue("willChange",n),n.add(e)}var i}function Ml({protectedKeys:t,needsAnimating:e},n){const i=t.hasOwnProperty(n)&&!0!==e[n];return e[n]=!1,i}function Cl(t,e,{delay:n=0,transitionOverride:i,type:s}={}){let{transition:o=t.getDefaultTransition(),transitionEnd:r,...a}=e;i&&(o=i);const l=[],u=s&&t.animationState&&t.animationState.getState()[s];for(const e in a){const i=t.getValue(e,t.latestValues[e]??null),s=a[e];if(void 0===s||u&&Ml(u,e))continue;const r={delay:n,...ni(o||{},e)},c=i.get();if(void 0!==c&&!i.isAnimating&&!Array.isArray(s)&&s===c&&!r.velocity)continue;let h=!1;if(window.MotionHandoffAnimation){const n=Co(t);if(n){const t=window.MotionHandoffAnimation(n,e,at);null!==t&&(r.startTime=t,h=!0)}}Al(t,e),i.start(bo(e,i,s,t.shouldReduceMotion&&ii.has(e)?{type:!1}:r,t,h));const d=i.animation;d&&l.push(d)}return r&&Promise.all(l).then(()=>{at.update(()=>{r&&El(t,r)})}),l}function Vl(t,e,n,i=0,s=1){const o=Array.from(t).sort((t,e)=>t.sortNodePosition(e)).indexOf(e),r=t.size,a=(r-1)*i;return"function"==typeof n?n(o,r):1===s?o*i:a-o*i}function Rl(t,e,n={}){const i=Tl(t,e,"exit"===n.type?t.presenceContext?.custom:void 0);let{transition:s=t.getDefaultTransition()||{}}=i||{};n.transitionOverride&&(s=n.transitionOverride);const o=i?()=>Promise.all(Cl(t,i,n)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(i=0)=>{const{delayChildren:o=0,staggerChildren:r,staggerDirection:a}=s;return function(t,e,n=0,i=0,s=0,o=1,r){const a=[];for(const l of t.variantChildren)l.notify("AnimationStart",e),a.push(Rl(l,e,{...r,delay:n+("function"==typeof i?0:i)+Vl(t.variantChildren,l,i,s,o)}).then(()=>l.notify("AnimationComplete",e)));return Promise.all(a)}(t,e,i,o,r,a,n)}:()=>Promise.resolve(),{when:a}=s;if(a){const[t,e]="beforeChildren"===a?[o,r]:[r,o];return t().then(()=>e())}return Promise.all([o(),r(n.delay)])}function Dl(t,e,n={}){let i;if(t.notify("AnimationStart",e),Array.isArray(e)){const s=e.map(e=>Rl(t,e,n));i=Promise.all(s)}else if("string"==typeof e)i=Rl(t,e,n);else{const s="function"==typeof e?Tl(t,e,n.custom):e;i=Promise.all(Cl(t,s,n))}return i.then(()=>{t.notify("AnimationComplete",e)})}function kl(t,e){if(!Array.isArray(e))return!1;const n=e.length;if(n!==t.length)return!1;for(let i=0;iPromise.all(e.map(({animation:e,options:n})=>Dl(t,e,n)))}(t),n=Ul(),i=!0;const s=e=>(n,i)=>{const s=Tl(t,i,"exit"===e?t.presenceContext?.custom:void 0);if(s){const{transition:t,transitionEnd:e,...i}=s;n={...n,...i,...e}}return n};function o(o){const{props:r}=t,a=Ol(t.parent)||{},l=[],u=new Set;let c={},h=1/0;for(let e=0;eh&&f,w=!1;const T=Array.isArray(m)?m:[m];let P=T.reduce(s(d),{});!1===g&&(P={});const{prevResolvedValues:b={}}=p,S={...b,...P},E=e=>{x=!0,u.has(e)&&(w=!0,u.delete(e)),p.needsAnimating[e]=!0;const n=t.getValue(e);n&&(n.liveStyle=!1)};for(const t in S){const e=P[t],n=b[t];if(c.hasOwnProperty(t))continue;let i=!1;i=Pl(e)&&Pl(n)?!kl(e,n):e!==n,i?null!=e?E(t):u.add(t):void 0!==e&&u.has(t)?E(t):p.protectedKeys[t]=!0}p.prevProp=m,p.prevResolvedValues=P,p.isActive&&(c={...c,...P}),i&&t.blockInitialAnimation&&(x=!1);const A=y&&v;x&&(!A||w)&&l.push(...T.map(e=>{const n={type:d};if("string"==typeof e&&i&&!A&&t.manuallyAnimateOnMount&&t.parent){const{parent:i}=t,s=Tl(i,e);if(i.enteringChildren&&s){const{delayChildren:e}=s.transition||{};n.delay=Vl(i.enteringChildren,t,e)}}return{animation:e,options:n}}))}if(u.size){const e={};if("boolean"!=typeof r.initial){const n=Tl(t,Array.isArray(r.initial)?r.initial[0]:r.initial);n&&n.transition&&(e.transition=n.transition)}u.forEach(n=>{const i=t.getBaseTarget(n),s=t.getValue(n);s&&(s.liveStyle=!0),e[n]=i??null}),l.push({animation:e})}let d=Boolean(l.length);return!i||!1!==r.initial&&r.initial!==r.animate||t.manuallyAnimateOnMount||(d=!1),i=!1,d?e(l):Promise.resolve()}return{animateChanges:o,setActive:function(e,i){if(n[e].isActive===i)return Promise.resolve();t.variantChildren?.forEach(t=>t.animationState?.setActive(e,i)),n[e].isActive=i;const s=o(e);for(const t in n)n[t].protectedKeys={};return s},setAnimateFunction:function(n){e=n(t)},getState:()=>n,reset:()=>{n=Ul(),i=!0}}}function Fl(t,e){return"string"==typeof e?e!==t:!!Array.isArray(e)&&!kl(e,t)}function Wl(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Ul(){return{animate:Wl(!0),whileInView:Wl(),whileHover:Wl(),whileTap:Wl(),whileDrag:Wl(),whileFocus:Wl(),exit:Wl()}}class Nl{constructor(t){this.isMounted=!1,this.node=t}update(){}}let $l=0;const zl={animation:{Feature:class extends Nl{constructor(t){super(t),t.animationState||(t.animationState=Il(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();ha(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:e}=this.node.prevProps||{};t!==e&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}},exit:{Feature:class extends Nl{constructor(){super(...arguments),this.id=$l++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:e}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===n)return;const i=this.node.animationState.setActive("exit",!t);e&&!t&&i.then(()=>{e(this.id)})}mount(){const{register:t,onExitComplete:e}=this.node.presenceContext||{};e&&e(this.id),t&&(this.unmount=t(this.id))}unmount(){}}}};function Xl(t){return{point:{x:t.pageX,y:t.pageY}}}const Hl=t=>e=>qi(e)&&t(e,Xl(e));function Yl(t,e,n,i){return Zr(t,e,Hl(n),i)}const Kl=({current:t})=>t?t.ownerDocument.defaultView:null,Gl=(t,e)=>Math.abs(t-e);function _l(t,e){const n=Gl(t.x,e.x),i=Gl(t.y,e.y);return Math.sqrt(n**2+i**2)}class Zl{constructor(t,e,{transformPagePoint:n,contextWindow:i=window,dragSnapToOrigin:s=!1,distanceThreshold:o=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!this.lastMoveEvent||!this.lastMoveEventInfo)return;const t=Ql(this.lastMoveEventInfo,this.history),e=null!==this.startEvent,n=_l(t.offset,{x:0,y:0})>=this.distanceThreshold;if(!e&&!n)return;const{point:i}=t,{timestamp:s}=ut;this.history.push({...i,timestamp:s});const{onStart:o,onMove:r}=this.handlers;e||(o&&o(this.lastMoveEvent,t),this.startEvent=this.lastMoveEvent),r&&r(this.lastMoveEvent,t)},this.handlePointerMove=(t,e)=>{this.lastMoveEvent=t,this.lastMoveEventInfo=ql(e,this.transformPagePoint),at.update(this.updatePoint,!0)},this.handlePointerUp=(t,e)=>{this.end();const{onEnd:n,onSessionEnd:i,resumeAnimation:s}=this.handlers;if(this.dragSnapToOrigin&&s&&s(),!this.lastMoveEvent||!this.lastMoveEventInfo)return;const o=Ql("pointercancel"===t.type?this.lastMoveEventInfo:ql(e,this.transformPagePoint),this.history);this.startEvent&&n&&n(t,o),i&&i(t,o)},!qi(t))return;this.dragSnapToOrigin=s,this.handlers=e,this.transformPagePoint=n,this.distanceThreshold=o,this.contextWindow=i||window;const r=ql(Xl(t),this.transformPagePoint),{point:a}=r,{timestamp:l}=ut;this.history=[{...a,timestamp:l}];const{onSessionStart:u}=e;u&&u(t,Ql(r,this.history)),this.removeListeners=D(Yl(this.contextWindow,"pointermove",this.handlePointerMove),Yl(this.contextWindow,"pointerup",this.handlePointerUp),Yl(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),lt(this.updatePoint)}}function ql(t,e){return e?{point:e(t.point)}:t}function Jl(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Ql({point:t},e){return{point:t,delta:Jl(t,eu(e)),offset:Jl(t,tu(e)),velocity:nu(e,.1)}}function tu(t){return t[0]}function eu(t){return t[t.length-1]}function nu(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,i=null;const s=eu(t);for(;n>=0&&(i=t[n],!(s.timestamp-i.timestamp>O(e)));)n--;if(!i)return{x:0,y:0};const o=j(s.timestamp-i.timestamp);if(0===o)return{x:0,y:0};const r={x:(s.x-i.x)/o,y:(s.y-i.y)/o};return r.x===1/0&&(r.x=0),r.y===1/0&&(r.y=0),r}function iu(t,e,n){return{min:void 0!==e?t.min+e:void 0,max:void 0!==n?t.max+n-(t.max-t.min):void 0}}function su(t,e){let n=e.min-t.min,i=e.max-t.max;return e.max-e.min{const{dragSnapToOrigin:n}=this.getProps();n?this.pauseAnimation():this.stopAnimation(),e&&this.snapToCursor(Xl(t).point)},onStart:(t,e)=>{const{drag:n,dragPropagation:i,onDragStart:s}=this.getProps();if(n&&!i&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Yi(n),!this.openDragLock))return;this.latestPointerEvent=t,this.latestPanInfo=e,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),wr(t=>{let e=this.getAxisMotionValue(t).get()||0;if(Lt.test(e)){const{projection:n}=this.visualElement;if(n&&n.layout){const i=n.layout.layoutBox[t];if(i){e=uo(i)*(parseFloat(e)/100)}}}this.originPoint[t]=e}),s&&at.postRender(()=>s(t,e)),Al(this.visualElement,"transform");const{animationState:o}=this.visualElement;o&&o.setActive("whileDrag",!0)},onMove:(t,e)=>{this.latestPointerEvent=t,this.latestPanInfo=e;const{dragPropagation:n,dragDirectionLock:i,onDirectionLock:s,onDrag:o}=this.getProps();if(!n&&!this.openDragLock)return;const{offset:r}=e;if(i&&null===this.currentDirection)return this.currentDirection=function(t,e=10){let n=null;Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x");return n}(r),void(null!==this.currentDirection&&s&&s(this.currentDirection));this.updateAxis("x",e.point,r),this.updateAxis("y",e.point,r),this.visualElement.render(),o&&o(t,e)},onSessionEnd:(t,e)=>{this.latestPointerEvent=t,this.latestPanInfo=e,this.stop(t,e),this.latestPointerEvent=null,this.latestPanInfo=null},resumeAnimation:()=>wr(t=>"paused"===this.getAnimationState(t)&&this.getAxisMotionValue(t).animation?.play())},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:s,distanceThreshold:n,contextWindow:Kl(this.visualElement)})}stop(t,e){const n=t||this.latestPointerEvent,i=e||this.latestPanInfo,s=this.isDragging;if(this.cancel(),!s||!i||!n)return;const{velocity:o}=i;this.startAnimation(o);const{onDragEnd:r}=this.getProps();r&&at.postRender(()=>r(n,i))}cancel(){this.isDragging=!1;const{projection:t,animationState:e}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),e&&e.setActive("whileDrag",!1)}updateAxis(t,e,n){const{drag:i}=this.getProps();if(!n||!cu(t,i,this.currentDirection))return;const s=this.getAxisMotionValue(t);let o=this.originPoint[t]+n[t];this.constraints&&this.constraints[t]&&(o=function(t,{min:e,max:n},i){return void 0!==e&&tn&&(t=i?Jt(n,t,i.max):Math.min(t,n)),t}(o,this.constraints[t],this.elastic[t])),s.set(o)}resolveConstraints(){const{dragConstraints:t,dragElastic:e}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,i=this.constraints;t&&pl(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):this.constraints=!(!t||!n)&&function(t,{top:e,left:n,bottom:i,right:s}){return{x:iu(t.x,n,s),y:iu(t.y,e,i)}}(n.layoutBox,t),this.elastic=function(t=ou){return!1===t?t=0:!0===t&&(t=ou),{x:ru(t,"left","right"),y:ru(t,"top","bottom")}}(e),i!==this.constraints&&n&&this.constraints&&!this.hasMutatedConstraints&&wr(t=>{!1!==this.constraints&&this.getAxisMotionValue(t)&&(this.constraints[t]=function(t,e){const n={};return void 0!==e.min&&(n.min=e.min-t.min),void 0!==e.max&&(n.max=e.max-t.min),n}(n.layoutBox[t],this.constraints[t]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:e}=this.getProps();if(!t||!pl(t))return!1;const n=t.current,{projection:i}=this.visualElement;if(!i||!i.layout)return!1;const s=function(t,e,n){const i=sa(t,n),{scroll:s}=e;return s&&(er(i.x,s.offset.x),er(i.y,s.offset.y)),i}(n,i.root,this.visualElement.getTransformPagePoint());let o=function(t,e){return{x:su(t.x,e.x),y:su(t.y,e.y)}}(i.layout.layoutBox,s);if(e){const t=e(function({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}(o));this.hasMutatedConstraints=!!t,t&&(o=ia(t))}return o}startAnimation(t){const{drag:e,dragMomentum:n,dragElastic:i,dragTransition:s,dragSnapToOrigin:o,onDragTransitionEnd:r}=this.getProps(),a=this.constraints||{},l=wr(r=>{if(!cu(r,e,this.currentDirection))return;let l=a&&a[r]||{};o&&(l={min:0,max:0});const u=i?200:1e6,c=i?40:1e7,h={type:"inertia",velocity:n?t[r]:0,bounceStiffness:u,bounceDamping:c,timeConstant:750,restDelta:1,restSpeed:10,...s,...l};return this.startAxisValueAnimation(r,h)});return Promise.all(l).then(r)}startAxisValueAnimation(t,e){const n=this.getAxisMotionValue(t);return Al(this.visualElement,t),n.start(bo(t,n,0,e,this.visualElement,!1))}stopAnimation(){wr(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){wr(t=>this.getAxisMotionValue(t).animation?.pause())}getAnimationState(t){return this.getAxisMotionValue(t).animation?.state}getAxisMotionValue(t){const e=`_drag${t.toUpperCase()}`,n=this.visualElement.getProps(),i=n[e];return i||this.visualElement.getValue(t,(n.initial?n.initial[t]:void 0)||0)}snapToCursor(t){wr(e=>{const{drag:n}=this.getProps();if(!cu(e,n,this.currentDirection))return;const{projection:i}=this.visualElement,s=this.getAxisMotionValue(e);if(i&&i.layout){const{min:n,max:o}=i.layout.layoutBox[e];s.set(t[e]-Jt(n,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:e}=this.getProps(),{projection:n}=this.visualElement;if(!pl(e)||!n||!this.constraints)return;this.stopAnimation();const i={x:0,y:0};wr(t=>{const e=this.getAxisMotionValue(t);if(e&&!1!==this.constraints){const n=e.get();i[t]=function(t,e){let n=.5;const i=uo(t),s=uo(e);return s>i?n=k(e.min,e.max-i,t.min):i>s&&(n=k(t.min,t.max-s,e.min)),P(0,1,n)}({min:n,max:n},this.constraints[t])}});const{transformTemplate:s}=this.visualElement.getProps();this.visualElement.current.style.transform=s?s({},""):"none",n.root&&n.root.updateScroll(),n.updateLayout(),this.resolveConstraints(),wr(e=>{if(!cu(e,t,null))return;const n=this.getAxisMotionValue(e),{min:s,max:o}=this.constraints[e];n.set(Jt(s,o,i[e]))})}addListeners(){if(!this.visualElement.current)return;lu.set(this.visualElement,this);const t=Yl(this.visualElement.current,"pointerdown",t=>{const{drag:e,dragListener:n=!0}=this.getProps();e&&n&&this.start(t)}),e=()=>{const{dragConstraints:t}=this.getProps();pl(t)&&t.current&&(this.constraints=this.resolveRefConstraints())},{projection:n}=this.visualElement,i=n.addEventListener("measure",e);n&&!n.layout&&(n.root&&n.root.updateScroll(),n.updateLayout()),at.read(e);const s=Zr(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:t,hasLayoutChanged:e})=>{this.isDragging&&e&&(wr(e=>{const n=this.getAxisMotionValue(e);n&&(this.originPoint[e]+=t[e].translate,n.set(n.get()+t[e].translate))}),this.visualElement.render())});return()=>{s(),t(),i(),o&&o()}}getProps(){const t=this.visualElement.getProps(),{drag:e=!1,dragDirectionLock:n=!1,dragPropagation:i=!1,dragConstraints:s=!1,dragElastic:o=ou,dragMomentum:r=!0}=t;return{...t,drag:e,dragDirectionLock:n,dragPropagation:i,dragConstraints:s,dragElastic:o,dragMomentum:r}}}function cu(t,e,n){return!(!0!==e&&e!==t||null!==n&&n!==t)}const hu=t=>(e,n)=>{t&&at.postRender(()=>t(e,n))};let du=!1;class pu extends e.Component{componentDidMount(){const{visualElement:t,layoutGroup:e,switchLayoutGroup:n,layoutId:i}=this.props,{projection:s}=t;xr(fu),s&&(e.group&&e.group.add(s),n&&n.register&&i&&n.register(s),du&&s.root.didUpdate(),s.addEventListener("animationComplete",()=>{this.safeToRemove()}),s.setOptions({...s.options,onExitComplete:()=>this.safeToRemove()})),Tr.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:e,visualElement:n,drag:i,isPresent:s}=this.props,{projection:o}=n;return o?(o.isPresent=s,du=!0,i||t.layoutDependency!==e||void 0===e||t.isPresent!==s?o.willUpdate():this.safeToRemove(),t.isPresent!==s&&(s?o.promote():o.relegate()||at.postRender(()=>{const t=o.getStack();t&&t.members.length||this.safeToRemove()})),null):null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),$i.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:e,switchLayoutGroup:n}=this.props,{projection:i}=t;du=!0,i&&(i.scheduleCheckAfterUnmount(),e&&e.group&&e.group.remove(i),n&&n.deregister&&n.deregister(i))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function mu(t){const[n,i]=oo(),s=e.useContext(m);return d(pu,{...t,layoutGroup:s,switchLayoutGroup:e.useContext(fl),isPresent:n,safeToRemove:i})}const fu={borderRadius:{...ea,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:ea,borderTopRightRadius:ea,borderBottomLeftRadius:ea,borderBottomRightRadius:ea,boxShadow:na},gu={pan:{Feature:class extends Nl{constructor(){super(...arguments),this.removePointerDownListener=V}onPointerDown(t){this.session=new Zl(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Kl(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:e,onPan:n,onPanEnd:i}=this.node.getProps();return{onSessionStart:hu(t),onStart:hu(e),onMove:n,onEnd:(t,e)=>{delete this.session,i&&at.postRender(()=>i(t,e))}}}mount(){this.removePointerDownListener=Yl(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}},drag:{Feature:class extends Nl{constructor(t){super(t),this.removeGroupControls=V,this.removeListeners=V,this.controls=new uu(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||V}unmount(){this.removeGroupControls(),this.removeListeners()}},ProjectionNode:Qr,MeasureLayout:mu}};function yu(t,e,n){const{props:i}=t;t.animationState&&i.whileHover&&t.animationState.setActive("whileHover","Start"===n);const s=i["onHover"+n];s&&at.postRender(()=>s(e,Xl(e)))}function vu(t,e,n){const{props:i}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&i.whileTap&&t.animationState.setActive("whileTap","Start"===n);const s=i["onTap"+("End"===n?"":n)];s&&at.postRender(()=>s(e,Xl(e)))}const xu=new WeakMap,wu=new WeakMap,Tu=t=>{const e=xu.get(t.target);e&&e(t)},Pu=t=>{t.forEach(Tu)};function bu(t,e,n){const i=function({root:t,...e}){const n=t||document;wu.has(n)||wu.set(n,{});const i=wu.get(n),s=JSON.stringify(e);return i[s]||(i[s]=new IntersectionObserver(Pu,{root:t,...e})),i[s]}(e);return xu.set(t,n),i.observe(t),()=>{xu.delete(t),i.unobserve(t)}}const Su={some:0,all:1};const Eu={inView:{Feature:class extends Nl{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:e,margin:n,amount:i="some",once:s}=t,o={root:e?e.current:void 0,rootMargin:n,threshold:"number"==typeof i?i:Su[i]};return bu(this.node.current,o,t=>{const{isIntersecting:e}=t;if(this.isInView===e)return;if(this.isInView=e,s&&!e&&this.hasEnteredView)return;e&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",e);const{onViewportEnter:n,onViewportLeave:i}=this.node.getProps(),o=e?n:i;o&&o(t)})}mount(){this.startObserver()}update(){if("undefined"==typeof IntersectionObserver)return;const{props:t,prevProps:e}=this.node;["amount","margin","root"].some(function({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}(t,e))&&this.startObserver()}unmount(){}}},tap:{Feature:class extends Nl{mount(){const{current:t}=this.node;t&&(this.unmount=is(t,(t,e)=>(vu(this.node,e,"Start"),(t,{success:e})=>vu(this.node,t,e?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}},focus:{Feature:class extends Nl{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch(e){t=!0}t&&this.node.animationState&&(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){this.isActive&&this.node.animationState&&(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=D(Zr(this.node.current,"focus",()=>this.onFocus()),Zr(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}},hover:{Feature:class extends Nl{mount(){const{current:t}=this.node;t&&(this.unmount=_i(t,(t,e)=>(yu(this.node,e,"Start"),t=>yu(this.node,t,"End"))))}unmount(){}}}},Au={layout:{ProjectionNode:Qr,MeasureLayout:mu}},Mu=wl({...zl,...Eu,...gu,...Au},qa);function Cu({children:t,as:n="ul",axis:i="y",onReorder:s,values:o,...r},a){const l=f(()=>Mu[n]),u=[],c=e.useRef(!1),h={axis:i,registerItem:(t,e)=>{const n=u.findIndex(e=>t===e.value);-1!==n?u[n].layout=e[i]:u.push({value:t,layout:e[i]}),u.sort(Du)},updateOrder:(t,e,n)=>{if(c.current)return;const i=function(t,e,n,i){if(!i)return t;const s=t.findIndex(t=>t.value===e);if(-1===s)return t;const o=i>0?1:-1,r=t[s+o];if(!r)return t;const a=t[s],l=r.layout,u=Jt(l.min,l.max,.5);return 1===o&&a.layout.max+n>u||-1===o&&a.layout.min+n-1!==o.indexOf(t))))}};return e.useEffect(()=>{c.current=!1}),d(l,{...r,ref:a,ignoreStrict:!0,children:d(Na.Provider,{value:h,children:t})})}const Vu=e.forwardRef(Cu);function Ru(t){return t.value}function Du(t,e){return t.layout.min-e.layout.min}function ku(t){const n=f(()=>ji(t)),{isStatic:i}=e.useContext(to);if(i){const[,i]=e.useState(t);e.useEffect(()=>n.on("change",i),[])}return n}function Lu(t,e){const n=ku(e()),i=()=>n.set(e());return i(),y(()=>{const e=()=>at.preRender(i,!1,!0),n=t.map(t=>t.on("change",e));return()=>{n.forEach(t=>t()),lt(i)}}),n}function Ou(t,e,n,i){if("function"==typeof t)return function(t){Li.current=[],t();const e=Lu(Li.current,t);return Li.current=void 0,e}(t);const s="function"==typeof e?e:Ms(e,n,i);return Array.isArray(t)?ju(t,s):ju([t],([t])=>s(t))}function ju(t,e){const n=f(()=>[]);return Lu(t,()=>{n.length=0;const i=t.length;for(let e=0;eMu[s]),c=e.useContext(Na),h={x:Bu(n.x),y:Bu(n.y)},p=Ou([h.x,h.y],([t,e])=>t||e?1:"unset"),{axis:m,registerItem:g,updateOrder:y}=c;return d(u,{drag:m,...a,dragSnapToOrigin:!0,style:{...n,x:h.x,y:h.y,zIndex:p},layout:r,onDrag:(t,e)=>{const{velocity:n}=e;n[m]&&y(i,h[m].get(),n[m]),o&&o(t,e)},onLayoutMeasure:t=>g(i,t),ref:l,ignoreStrict:!0,children:t})}const Fu=e.forwardRef(Iu);var Wu=Object.freeze({__proto__:null,Group:Vu,Item:Fu});function Uu(t){return"object"==typeof t&&!Array.isArray(t)}function Nu(t,e,n,i){return"string"==typeof t&&Uu(e)?Si(t,n,i):t instanceof NodeList?Array.from(t):Array.isArray(t)?t:[t]}function $u(t,e,n){return t*(e+1)}function zu(t,e,n,i){return"number"==typeof e?e:e.startsWith("-")||e.startsWith("+")?Math.max(0,t+parseFloat(e)):"<"===e?n:e.startsWith("<")?Math.max(0,n+parseFloat(e.slice(1))):i.get(e)??t}function Xu(t,e,n,i,s,o){!function(t,e,n){for(let i=0;ie&&s.at"number"==typeof t,Ju=t=>t.every(qu);class Qu extends wa{constructor(){super(...arguments),this.type="object"}readValueFromInstance(t,e){if(function(t,e){return t in e}(e,t)){const n=t[e];if("string"==typeof n||"number"==typeof n)return n}}getBaseTargetFromProps(){}removeValueFromRenderState(t,e){delete e.output[t]}measureInstanceViewportBox(){return{x:{min:0,max:0},y:{min:0,max:0}}}build(t,e){Object.assign(t.output,e)}renderInstance(t,{output:e}){Object.assign(t,e)}sortInstanceNodePosition(){return 0}}function tc(t){const e={presenceContext:null,props:{},visualState:{renderState:{transform:{},transformOrigin:{},style:{},vars:{},attrs:{}},latestValues:{}}},n=os(t)&&!Es(t)?new Ga(e):new Va(e);n.mount(t),ca.set(t,n)}function ec(t){const e=new Qu({presenceContext:null,props:{},visualState:{renderState:{output:{}},latestValues:{}}});e.mount(t),ca.set(t,e)}function nc(t,e,n,i){const s=[];if(function(t,e){return Vs(t)||"number"==typeof t||"string"==typeof t&&!Uu(e)}(t,e))s.push(So(t,Uu(e)&&e.default||e,n&&n.default||n));else{const o=Nu(t,e,i),r=o.length;for(let t=0;t{const l=_u(t),{delay:u=0,times:c=Ne(l),type:p="keyframes",repeat:m,repeatType:f,repeatDelay:y=0,...v}=n;let{ease:x=e.ease||"easeOut",duration:w}=n;const T="function"==typeof u?u(r,a):u,P=l.length,b=jn(p)?p:s?.[p||"keyframes"];if(P<=2&&b){let t=100;if(2===P&&Ju(l)){const e=l[1]-l[0];t=Math.abs(e)}const e={...v};void 0!==w&&(e.duration=O(w));const n=fe(e,t,b);x=n.ease,w=n.duration}w??(w=o);const S=h+T;1===c.length&&0===c[0]&&(c[1]=1);const E=c.length-l.length;if(E>0&&Ue(c,E),1===l.length&&l.unshift(null),m){w=$u(w,m);const t=[...l],e=[...c];x=Array.isArray(x)?[...x]:[x];const n=[...x];for(let i=0;i{for(const s in t){const o=t[s];o.sort(Yu);const a=[],l=[],u=[];for(let t=0;t{i.push(...nc(n,t,e))}),i}function sc(t){return function(e,n,i){let s=[];var o;o=e,s=Array.isArray(o)&&o.some(Array.isArray)?ic(e,n,t):nc(e,n,i,t);const r=new Gn(s);return t&&(t.animations.push(r),r.finished.then(()=>{w(t.animations,r)})),r}}const oc=sc();const rc=t=>function(e,n,i){return new Gn(function(t,e,n,i){const s=Si(t,i),o=s.length,r=[];for(let t=0;te.delete(n)),a.push(s)}return a}(e,n,i,t))},ac=rc(),lc={x:{length:"Width",position:"Left"},y:{length:"Height",position:"Top"}};function uc(t,e,n,i){const s=n[e],{length:o,position:r}=lc[e],a=s.current,l=n.time;s.current=t[`scroll${r}`],s.scrollLength=t[`scroll${o}`]-t[`client${o}`],s.offset.length=0,s.offset[0]=0,s.offset[1]=s.scrollLength,s.progress=k(0,s.scrollLength,s.current);const u=i-l;s.velocity=u>50?0:B(s.current-a,u)}const cc={start:0,center:.5,end:1};function hc(t,e,n=0){let i=0;if(t in cc&&(t=cc[t]),"string"==typeof t){const e=parseFloat(t);t.endsWith("px")?i=e:t.endsWith("%")?t=e/100:t.endsWith("vw")?i=e/100*document.documentElement.clientWidth:t.endsWith("vh")?i=e/100*document.documentElement.clientHeight:t=e}return"number"==typeof t&&(i=e*t),n+i}const dc=[0,0];function pc(t,e,n,i){let s=Array.isArray(t)?t:dc,o=0,r=0;return"number"==typeof t?s=[t,t]:"string"==typeof t&&(s=(t=t.trim()).includes(" ")?t.split(" "):[t,cc[t]?t:"0"]),o=hc(s[0],n,i),r=hc(s[1],e),o-r}const mc={Enter:[[0,1],[1,1]],Exit:[[0,0],[1,0]],Any:[[1,0],[0,1]],All:[[0,0],[1,1]]},fc={x:0,y:0};function gc(t,e,n){const{offset:i=mc.All}=n,{target:s=t,axis:o="y"}=n,r="y"===o?"height":"width",a=s!==t?function(t,e){const n={x:0,y:0};let i=t;for(;i&&i!==e;)if(ki(i))n.x+=i.offsetLeft,n.y+=i.offsetTop,i=i.offsetParent;else if("svg"===i.tagName){const t=i.getBoundingClientRect();i=i.parentElement;const e=i.getBoundingClientRect();n.x+=t.left-e.left,n.y+=t.top-e.top}else{if(!(i instanceof SVGGraphicsElement))break;{const{x:t,y:e}=i.getBBox();n.x+=t,n.y+=e;let s=null,o=i.parentNode;for(;!s;)"svg"===o.tagName&&(s=o),o=i.parentNode;i=s}}return n}(s,t):fc,l=s===t?{width:t.scrollWidth,height:t.scrollHeight}:function(t){return"getBBox"in t&&"svg"!==t.tagName?t.getBBox():{width:t.clientWidth,height:t.clientHeight}}(s),u={width:t.clientWidth,height:t.clientHeight};e[o].offset.length=0;let c=!e[o].interpolate;const h=i.length;for(let t=0;t{!function(t,e=t,n){if(n.x.targetOffset=0,n.y.targetOffset=0,e!==t){let i=e;for(;i&&i!==t;)n.x.targetOffset+=i.offsetLeft,n.y.targetOffset+=i.offsetTop,i=i.offsetParent}n.x.targetLength=e===t?e.scrollWidth:e.clientWidth,n.y.targetLength=e===t?e.scrollHeight:e.clientHeight,n.x.containerLength=t.clientWidth,n.y.containerLength=t.clientHeight}(t,i.target,n),function(t,e,n){uc(t,"x",e,n),uc(t,"y",e,n),e.time=n}(t,n,e),(i.offset||i.target)&&gc(t,n,i)},notify:()=>e(n)}}const vc=new WeakMap,xc=new WeakMap,wc=new WeakMap,Tc=t=>t===document.scrollingElement?window:t;function Pc(t,{container:e=document.scrollingElement,...n}={}){if(!e)return V;let i=wc.get(e);i||(i=new Set,wc.set(e,i));const s=yc(e,t,{time:0,x:{current:0,offset:[],progress:0,scrollLength:0,targetOffset:0,targetLength:0,containerLength:0,velocity:0},y:{current:0,offset:[],progress:0,scrollLength:0,targetOffset:0,targetLength:0,containerLength:0,velocity:0}},n);if(i.add(s),!vc.has(e)){const t=()=>{for(const t of i)t.measure(ut.timestamp);at.preUpdate(n)},n=()=>{for(const t of i)t.notify()},s=()=>at.read(t);vc.set(e,s);const o=Tc(e);window.addEventListener("resize",s,{passive:!0}),e!==document.documentElement&&xc.set(e,ys(e,s)),o.addEventListener("scroll",s,{passive:!0}),s()}const o=vc.get(e);return at.read(o,!1,!0),()=>{lt(o);const t=wc.get(e);if(!t)return;if(t.delete(s),t.size)return;const n=vc.get(e);vc.delete(e),n&&(Tc(e).removeEventListener("scroll",n),xc.get(e)?.(),window.removeEventListener("resize",n))}}const bc=new Map;function Sc({source:t,container:e,...n}){const{axis:i}=n;t&&(e=t);const s=bc.get(e)??new Map;bc.set(e,s);const o=n.target??"self",r=s.get(o)??{},a=i+(n.offset??[]).join(",");return r[a]||(r[a]=!n.target&&Mn()?new ScrollTimeline({source:e,axis:i}):function(t){const e={value:0},n=Pc(n=>{e.value=100*n[t.axis].progress},t);return{currentTime:e,cancel:n}}({container:e,...n})),r[a]}function Ec(t,{axis:e="y",container:n=document.scrollingElement,...i}={}){if(!n)return V;const s={axis:e,container:n,...i};return"function"==typeof t?function(t,e){return function(t){return 2===t.length}(t)?Pc(n=>{t(n[e.axis].progress,n)},e):vs(t,Sc(e))}(t,s):function(t,e){const n=Sc(e);return t.attachTimeline({timeline:e.target?void 0:n,observe:t=>(t.pause(),vs(e=>{t.time=t.duration*e},n))})}(t,s)}const Ac={some:0,all:1};function Mc(t,e,{root:n,margin:i,amount:s="some"}={}){const o=Si(t),r=new WeakMap,a=new IntersectionObserver(t=>{t.forEach(t=>{const n=r.get(t.target);if(t.isIntersecting!==Boolean(n))if(t.isIntersecting){const n=e(t.target,t);"function"==typeof n?r.set(t.target,n):a.unobserve(t.target)}else"function"==typeof n&&(n(t),r.delete(t.target))})},{root:n,rootMargin:i,threshold:"number"==typeof s?s:Ac[s]});return o.forEach(t=>a.observe(t)),()=>a.disconnect()}const Cc=wl();function Vc(t){return e.useEffect(()=>()=>t(),[])}const Rc={renderer:qa,...zl,...Eu},Dc={...Rc,...gu,...Au},kc={renderer:qa,...zl};function Lc(t,n,i){e.useInsertionEffect(()=>t.on(n,i),[t,n,i])}const Oc=()=>({scrollX:ji(0),scrollY:ji(0),scrollXProgress:ji(0),scrollYProgress:ji(0)}),jc=t=>!!t&&!t.current;function Bc({container:t,target:n,...i}={}){const s=f(Oc),o=e.useRef(null),r=e.useRef(!1),a=e.useCallback(()=>(o.current=Ec((t,{x:e,y:n})=>{s.scrollX.set(e.current),s.scrollXProgress.set(e.progress),s.scrollY.set(n.current),s.scrollYProgress.set(n.progress)},{...i,container:t?.current||void 0,target:n?.current||void 0}),()=>{o.current?.()}),[t,n,JSON.stringify(i.offset)]);return y(()=>(r.current=!1,jc(t)||jc(n)?void(r.current=!0):a()),[a]),e.useEffect(()=>r.current?(jc(t),jc(n),a()):void 0,[a]),s}function Ic(t){const n=e.useRef(0),{isStatic:i}=e.useContext(to);e.useEffect(()=>{if(i)return;const e=({timestamp:e,delta:i})=>{n.current||(n.current=e),t(e-n.current,i)};return at.update(e,!0),()=>lt(e)},[t])}class Fc extends Oi{constructor(){super(...arguments),this.isEnabled=!1}add(t){(dn.has(t)||bi.has(t))&&(this.isEnabled=!0,this.update())}update(){this.set(this.isEnabled?"transform":"auto")}}function Wc(){!la.current&&ua();const[t]=e.useState(aa.current);return t}function Uc(t,e){[...e].reverse().forEach(n=>{const i=t.getVariant(n);i&&El(t,i),t.variantChildren&&t.variantChildren.forEach(t=>{Uc(t,e)})})}function Nc(){const t=new Set,e={subscribe:e=>(t.add(e),()=>{t.delete(e)}),start(e,n){const i=[];return t.forEach(t=>{i.push(Dl(t,e,{transitionOverride:n}))}),Promise.all(i)},set:e=>t.forEach(t=>{!function(t,e){Array.isArray(e)?Uc(t,e):"string"==typeof e?Uc(t,[e]):El(t,e)}(t,e)}),stop(){t.forEach(t=>{!function(t){t.values.forEach(t=>t.stop())}(t)})},mount:()=>()=>{e.stop()}};return e}function $c(){const t=f(Nc);return y(t.mount,[]),t}const zc=$c;class Xc{constructor(){this.componentControls=new Set}subscribe(t){return this.componentControls.add(t),()=>this.componentControls.delete(t)}start(t,e){this.componentControls.forEach(n=>{n.start(t.nativeEvent||t,e)})}cancel(){this.componentControls.forEach(t=>{t.cancel()})}stop(){this.componentControls.forEach(t=>{t.stop()})}}const Hc=()=>new Xc;function Yc(t){return null!==t&&"object"==typeof t&&dl in t}function Kc(){return Gc}function Gc(t){Jr.current&&(Jr.current.isUpdating=!1,Jr.current.blockUpdate(),t&&t())}const _c=new Map,Zc=new Map,qc=(t,e)=>`${t}: ${dn.has(e)?"transform":e}`;function Jc(t,e,n){const i=qc(t,e),s=_c.get(i);if(!s)return null;const{animation:o,startTime:r}=s;function a(){window.MotionCancelOptimisedAnimation?.(t,e,n)}return o.onfinish=a,null===r||window.MotionHandoffIsComplete?.(t)?(a(),null):r}let Qc,th;const eh=new Set;function nh(){eh.forEach(t=>{t.animation.play(),t.animation.startTime=t.startTime}),eh.clear()}const ih=()=>({});class sh extends wa{constructor(){super(...arguments),this.measureInstanceViewportBox=ur}build(){}resetTransform(){}restoreTransform(){}removeValueFromRenderState(){}renderInstance(){}scrapeMotionValuesFromProps(){return{}}getBaseTargetFromProps(){}readValueFromInstance(t,e,n){return n.initialState[e]||0}sortInstanceNodePosition(){return 0}}const oh=ul({scrapeMotionValuesFromProps:ih,createRenderState:ih});let rh=0;const ah=t=>t>.001?1/t:1e5;t.AnimatePresence=({children:t,custom:n,initial:i=!0,onExitComplete:s,presenceAffectsLayout:o=!0,mode:r="sync",propagate:a=!1,anchorX:l="left",root:u})=>{const[c,p]=oo(a),g=e.useMemo(()=>ao(t),[t]),v=a&&!c?[]:g.map(ro),x=e.useRef(!0),w=e.useRef(g),T=f(()=>new Map),[P,b]=e.useState(g),[S,E]=e.useState(g);y(()=>{x.current=!1,w.current=g;for(let t=0;t{const e=ro(t),h=!(a&&!c)&&(g===S||v.includes(e));return d(io,{isPresent:h,initial:!(x.current&&!i)&&void 0,custom:n,presenceAffectsLayout:o,mode:r,root:u,onExitComplete:h?void 0:()=>{if(!T.has(e))return;T.set(e,!0);let t=!0;T.forEach(e=>{e||(t=!1)}),t&&(M?.(),E(w.current),a&&p?.(),s&&s())},anchorX:l,children:t},e)})})},t.AnimateSharedLayout=({children:t})=>(i.useEffect(()=>{},[]),d(ka,{id:f(()=>"asl-"+rh++),children:t})),t.AsyncMotionValueAnimation=Yn,t.DOMKeyframesResolver=xi,t.DeprecatedLayoutGroupContext=lo,t.DragControls=Xc,t.FlatTree=Ro,t.GroupAnimation=Kn,t.GroupAnimationWithThen=Gn,t.JSAnimation=qe,t.KeyframeResolver=Sn,t.LayoutGroup=ka,t.LayoutGroupContext=m,t.LazyMotion=function({children:t,features:n,strict:i=!1}){const[,s]=e.useState(!ja(n)),o=e.useRef(void 0);if(!ja(n)){const{renderer:t,...e}=n;o.current=t,Oa(e)}return e.useEffect(()=>{ja(n)&&n().then(({renderer:t,...e})=>{Oa(e),o.current=t,s(!0)})},[]),d(La.Provider,{value:{renderer:o.current,strict:i},children:t})},t.MotionConfig=function({children:t,isValidProp:n,...i}){n&&Wa(n),(i={...e.useContext(to),...i}).isStatic=f(()=>i.isStatic);const s=e.useMemo(()=>i,[JSON.stringify(i.transition),i.transformPagePoint,i.reducedMotion]);return d(to.Provider,{value:s,children:t})},t.MotionConfigContext=to,t.MotionContext=Ja,t.MotionGlobalConfig=S,t.MotionValue=Oi,t.NativeAnimation=In,t.NativeAnimationExtended=Un,t.NativeAnimationWrapper=_n,t.PresenceContext=v,t.Reorder=Wu,t.SubscriptionManager=L,t.SwitchLayoutGroupContext=fl,t.ViewTransitionBuilder=qs,t.VisualElement=wa,t.WillChangeMotionValue=Fc,t.acceleratedValues=bi,t.activeAnimations=mt,t.addAttrValue=Vi,t.addPointerEvent=Yl,t.addPointerInfo=Hl,t.addScaleCorrector=xr,t.addStyleValue=Fi,t.addUniqueItem=x,t.alpha=Tt,t.analyseComplexValue=Xt,t.animate=oc,t.animateMini=ac,t.animateValue=function(t){return new qe(t)},t.animateView=function(t,e={}){return new qs(t,e)},t.animateVisualElement=Dl,t.animationControls=Nc,t.animationMapKey=qn,t.animations=zl,t.anticipate=Y,t.applyGeneratorOptions=Bn,t.applyPxDefaults=Ti,t.attachSpring=Rs,t.attrEffect=Ri,t.backIn=X,t.backInOut=H,t.backOut=z,t.buildTransform=Sa,t.calcGeneratorDuration=me,t.calcLength=uo,t.cancelFrame=lt,t.cancelMicrotask=zi,t.cancelSync=Qs,t.circIn=K,t.circInOut=_,t.circOut=G,t.clamp=P,t.collectMotionValues=Li,t.color=Wt,t.complex=Gt,t.convertOffsetToTimes=$e,t.createBox=ur,t.createGeneratorEasing=fe,t.createRenderBatcher=rt,t.createScopedAnimate=sc,t.cubicBezier=U,t.cubicBezierAsString=Dn,t.defaultEasing=ze,t.defaultOffset=Ne,t.defaultTransformValue=an,t.defaultValueTypes=fi,t.degrees=kt,t.delay=Do,t.dimensionValueTypes=oi,t.disableInstantTransitions=function(){S.instantAnimations=!1},t.distance=Gl,t.distance2D=_l,t.domAnimation=Rc,t.domMax=Dc,t.domMin=kc,t.easeIn=Z,t.easeInOut=J,t.easeOut=q,t.easingDefinitionToFunction=it,t.fillOffset=Ue,t.fillWildcards=Je,t.filterProps=Ua,t.findDimensionValueType=ri,t.findValueType=Os,t.flushKeyframeResolvers=bn,t.frame=at,t.frameData=ut,t.frameSteps=ct,t.generateLinearEasing=de,t.getAnimatableNone=yi,t.getAnimationMap=Jn,t.getComputedStyle=ss,t.getDefaultValueType=gi,t.getEasingForSegment=tt,t.getMixer=re,t.getOriginIndex=As,t.getValueAsType=Ai,t.getValueTransition=ni,t.getVariableValue=ei,t.getViewAnimationLayerInfo=Ns,t.getViewAnimations=zs,t.hasWarned=function(t){return I.has(t)},t.hex=Rt,t.hover=_i,t.hsla=Ft,t.hslaToRgba=Zt,t.inView=Mc,t.inertia=Fe,t.interpolate=We,t.invariant=b,t.invisibleValues=ie,t.isBezierDefinition=et,t.isBrowser=g,t.isCSSVariableName=gt,t.isCSSVariableToken=vt,t.isDragActive=Hi,t.isDragging=Xi,t.isEasingArray=Q,t.isGenerator=jn,t.isHTMLElement=ki,t.isMotionComponent=Yc,t.isMotionValue=Vs,t.isNodeOrChild=Zi,t.isNumericalString=E,t.isObject=A,t.isPrimaryPointer=qi,t.isSVGElement=os,t.isSVGSVGElement=Es,t.isValidMotionProp=Ia,t.isWaapiSupportedEasing=function t(e){return Boolean("function"==typeof e&&Rn()||!e||"string"==typeof e&&(e in kn||Rn())||et(e)||Array.isArray(e)&&e.every(t))},t.isZeroValueString=M,t.keyframes=Xe,t.m=Cc,t.makeAnimationInstant=$n,t.makeUseVisualState=ul,t.mapEasingToNativeEasing=Ln,t.mapValue=function(t,e,n,i){const s=Ms(e,n,i);return Cs(()=>s(t.get()))},t.maxGeneratorDuration=pe,t.memo=C,t.microtask=$i,t.millisecondsToSeconds=j,t.mirrorEasing=N,t.mix=ce,t.mixArray=ae,t.mixColor=ne,t.mixComplex=ue,t.mixImmediate=qt,t.mixLinearColor=Qt,t.mixNumber=Jt,t.mixObject=le,t.mixVisibility=se,t.motion=Mu,t.motionValue=ji,t.moveItem=T,t.noop=V,t.number=wt,t.numberValueTypes=mi,t.observeTimeline=vs,t.optimizedAppearDataAttribute=Mo,t.parseCSSVariable=ti,t.parseValueFromTransform=ln,t.percent=Lt,t.pipe=D,t.positionalKeys=ii,t.press=is,t.progress=k,t.progressPercentage=It,t.propEffect=Di,t.px=Ot,t.readTransformValue=un,t.recordStats=function(){if(ot.value)throw bs(),new Error("Stats are already being measured");const t=ot;return t.value={frameloop:{setup:[],rate:[],read:[],resolveKeyframes:[],preUpdate:[],update:[],preRender:[],render:[],postRender:[]},animations:{mainThread:[],waapi:[],layout:[]},layoutProjection:{nodes:[],calculatedTargetDeltas:[],calculatedProjections:[]}},t.addProjectionMetrics=e=>{const{layoutProjection:n}=t.value;n.nodes.push(e.nodes),n.calculatedTargetDeltas.push(e.calculatedTargetDeltas),n.calculatedProjections.push(e.calculatedProjections)},at.postRender(xs,!0),Ss},t.removeItem=w,t.resize=ys,t.resolveElements=Si,t.resolveMotionValue=ko,t.reverseEasing=$,t.rgbUnit=Ct,t.rgba=Vt,t.scale=Pt,t.scroll=Ec,t.scrollInfo=Pc,t.secondsToMilliseconds=O,t.setDragLock=Yi,t.setStyle=An,t.spring=Ie,t.springValue=function(t,e){const n=ji(Vs(t)?t.get():t);return Rs(n,t,e),n},t.stagger=function(t=.1,{startDelay:e=0,from:n=0,ease:i}={}){return(s,o)=>{const r="number"==typeof n?n:As(n,o),a=Math.abs(r-s);let l=t*a;if(i){const e=o*t;l=it(i)(l/e)*e}return e+l}},t.startOptimizedAppearAnimation=function(t,e,n,i,s){if(window.MotionIsMounted)return;const o=t.dataset[Ao];if(!o)return;window.MotionHandoffAnimation=Jc;const r=qc(o,e);th||(th=On(t,e,[n[0],n[0]],{duration:1e4,ease:"linear"}),_c.set(r,{animation:th,startTime:null}),window.MotionHandoffAnimation=Jc,window.MotionHasOptimisedAnimation=(t,e)=>{if(!t)return!1;if(!e)return Zc.has(t);const n=qc(t,e);return Boolean(_c.get(n))},window.MotionHandoffMarkAsComplete=t=>{Zc.has(t)&&Zc.set(t,!0)},window.MotionHandoffIsComplete=t=>!0===Zc.get(t),window.MotionCancelOptimisedAnimation=(t,e,n,i)=>{const s=qc(t,e),o=_c.get(s);o&&(n&&void 0===i?n.postRender(()=>{n.postRender(()=>{o.animation.cancel()})}):o.animation.cancel(),n&&i?(eh.add(o),n.render(nh)):(_c.delete(s),_c.size||(window.MotionCancelOptimisedAnimation=void 0)))},window.MotionCheckAppearSync=(t,e,n)=>{const i=Co(t);if(!i)return;const s=window.MotionHasOptimisedAnimation?.(i,e),o=t.props.values?.[e];if(!s||!o)return;const r=n.on("change",t=>{o.get()!==t&&(window.MotionCancelOptimisedAnimation?.(i,e),r())});return r});const a=()=>{th.cancel();const o=On(t,e,n,i);void 0===Qc&&(Qc=performance.now()),o.startTime=Qc,_c.set(r,{animation:o,startTime:Qc}),s&&s(o)};Zc.set(o,!1),th.ready?th.ready.then(a).catch(V):a()},t.startWaapiAnimation=On,t.statsBuffer=ot,t.steps=function(t,e="end"){return n=>{const i=(n="end"===e?Math.min(n,.999):Math.max(n,.001))*t,s="end"===e?Math.floor(i):Math.ceil(i);return P(0,1,s/t)}},t.styleEffect=Wi,t.supportedWaapiEasing=kn,t.supportsBrowserAnimation=Hn,t.supportsFlags=Cn,t.supportsLinearEasing=Rn,t.supportsPartialKeyframes=Pi,t.supportsScrollTimeline=Mn,t.svgEffect=Ni,t.sync=Js,t.testValueType=si,t.time=pt,t.transform=Ms,t.transformPropOrder=hn,t.transformProps=dn,t.transformValue=Cs,t.transformValueTypes=pi,t.unwrapMotionComponent=function(t){if(Yc(t))return t[dl]},t.useAnimate=function(){const t=f(()=>({current:null,animations:[]})),e=f(()=>sc(t));return Vc(()=>{t.animations.forEach(t=>t.stop()),t.animations.length=0}),[t,e]},t.useAnimateMini=function(){const t=f(()=>({current:null,animations:[]})),e=f(()=>rc(t));return Vc(()=>{t.animations.forEach(t=>t.stop())}),[t,e]},t.useAnimation=zc,t.useAnimationControls=$c,t.useAnimationFrame=Ic,t.useCycle=function(...t){const n=e.useRef(0),[i,s]=e.useState(t[n.current]),o=e.useCallback(e=>{n.current="number"!=typeof e?F(0,t.length,n.current+1):e,s(t[n.current])},[t.length,...t]);return[i,o]},t.useDeprecatedAnimatedState=function(t){const[n,i]=e.useState(t),s=oh({},!1),o=f(()=>new sh({props:{onUpdate:t=>{i({...t})}},visualState:s,presenceContext:null},{initialState:t}));return e.useLayoutEffect(()=>(o.mount({}),()=>o.unmount()),[o]),[n,f(()=>t=>Dl(o,t))]},t.useDeprecatedInvertedScale=function(t){let n=ku(1),i=ku(1);const{visualElement:s}=e.useContext(Ja);return t?(n=t.scaleX||n,i=t.scaleY||i):s&&(n=s.getValue("scaleX",1),i=s.getValue("scaleY",1)),{scaleX:Ou(n,ah),scaleY:Ou(i,ah)}},t.useDomEvent=function(t,n,i,s){e.useEffect(()=>{const e=t.current;if(i&&e)return Zr(e,n,i,s)},[t,n,i,s])},t.useDragControls=function(){return f(Hc)},t.useElementScroll=function(t){return Bc({container:t})},t.useForceUpdate=Ra,t.useInView=function(t,{root:n,margin:i,amount:s,once:o=!1,initial:r=!1}={}){const[a,l]=e.useState(r);return e.useEffect(()=>{if(!t.current||o&&a)return;const e={root:n&&n.current||void 0,margin:i,amount:s};return Mc(t.current,()=>(l(!0),o?void 0:()=>l(!1)),e)},[n,t,i,o,s]),a},t.useInstantLayoutTransition=Kc,t.useInstantTransition=function(){const[t,n]=Ra(),i=Kc(),s=e.useRef(-1);return e.useEffect(()=>{at.postRender(()=>at.postRender(()=>{n===s.current&&(S.instantAnimations=!1)}))},[n]),e=>{i(()=>{S.instantAnimations=!0,t(),e(),s.current=n+1})}},t.useIsPresent=function(){return null===(t=e.useContext(v))||t.isPresent;var t},t.useIsomorphicLayoutEffect=y,t.useMotionTemplate=function(t,...e){const n=t.length;return Lu(e.filter(Vs),function(){let i="";for(let s=0;s{const t=()=>n(!document.hidden);return document.hidden&&t(),document.addEventListener("visibilitychange",t),()=>{document.removeEventListener("visibilitychange",t)}},[]),t},t.usePresence=oo,t.usePresenceData=function(){const t=e.useContext(v);return t?t.custom:void 0},t.useReducedMotion=Wc,t.useReducedMotionConfig=function(){const t=Wc(),{reducedMotion:n}=e.useContext(to);return"never"!==n&&("always"===n||t)},t.useResetProjection=function(){return e.useCallback(()=>{const t=Jr.current;t&&t.resetTree()},[])},t.useScroll=Bc,t.useSpring=function(t,n={}){const{isStatic:i}=e.useContext(to),s=()=>Vs(t)?t.get():t;if(i)return Ou(s);const o=ku(s());return e.useInsertionEffect(()=>Rs(o,t,n),[o,JSON.stringify(n)]),o},t.useTime=function(){const t=ku(0);return Ic(e=>t.set(e)),t},t.useTransform=Ou,t.useUnmountEffect=Vc,t.useVelocity=function(t){const e=ku(t.getVelocity()),n=()=>{const i=t.getVelocity();e.set(i),i&&at.update(n)};return Lc(t,"change",()=>{at.update(n,!1,!0)}),e},t.useViewportScroll=function(){return Bc()},t.useWillChange=function(){return f(()=>new Fc("auto"))},t.velocityPerSecond=B,t.vh=jt,t.visualElementStore=ca,t.vw=Bt,t.warnOnce=function(t,e,n){t||I.has(e)||(console.warn(function(t,e){return e?`${t}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${e}`:t}(e,n)),I.add(e))},t.warning=()=>{},t.wrap=F}); diff --git a/frontend/node_modules/framer-motion/dist/m.d.ts b/frontend/node_modules/framer-motion/dist/m.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ffaa88db813fcd75c233689cdb6804984ca09aa4 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/m.d.ts @@ -0,0 +1,435 @@ +/// +import * as React$1 from 'react'; +import { CSSProperties, PropsWithoutRef, RefAttributes, JSX, SVGAttributes } from 'react'; +import { MotionNodeOptions, MotionValue, TransformProperties, SVGPathProperties, Batcher } from 'motion-dom'; + +type MotionValueString = MotionValue; +type MotionValueNumber = MotionValue; +type MotionValueAny = MotionValue; +type AnyMotionValue = MotionValueNumber | MotionValueString | MotionValueAny; +type MotionValueHelper = T | AnyMotionValue; +type MakeMotionHelper = { + [K in keyof T]: MotionValueHelper; +}; +type MakeCustomValueTypeHelper = MakeMotionHelper; +type MakeMotion = MakeCustomValueTypeHelper; +type MotionCSS = MakeMotion>; +/** + * @public + */ +type MotionTransform = MakeMotion; +type MotionSVGProps = MakeMotion; +/** + * @public + */ +interface MotionStyle$1 extends MotionCSS, MotionTransform, MotionSVGProps { +} +/** + * Props for `motion` components. + * + * @public + */ +interface MotionProps extends MotionNodeOptions { + /** + * + * The React DOM `style` prop, enhanced with support for `MotionValue`s and separate `transform` values. + * + * ```jsx + * export const MyComponent = () => { + * const x = useMotionValue(0) + * + * return + * } + * ``` + */ + style?: MotionStyle$1; + children?: React.ReactNode | MotionValueNumber | MotionValueString; +} + +interface HTMLElements { + a: HTMLAnchorElement; + abbr: HTMLElement; + address: HTMLElement; + area: HTMLAreaElement; + article: HTMLElement; + aside: HTMLElement; + audio: HTMLAudioElement; + b: HTMLElement; + base: HTMLBaseElement; + bdi: HTMLElement; + bdo: HTMLElement; + big: HTMLElement; + blockquote: HTMLQuoteElement; + body: HTMLBodyElement; + br: HTMLBRElement; + button: HTMLButtonElement; + canvas: HTMLCanvasElement; + caption: HTMLElement; + center: HTMLElement; + cite: HTMLElement; + code: HTMLElement; + col: HTMLTableColElement; + colgroup: HTMLTableColElement; + data: HTMLDataElement; + datalist: HTMLDataListElement; + dd: HTMLElement; + del: HTMLModElement; + details: HTMLDetailsElement; + dfn: HTMLElement; + dialog: HTMLDialogElement; + div: HTMLDivElement; + dl: HTMLDListElement; + dt: HTMLElement; + em: HTMLElement; + embed: HTMLEmbedElement; + fieldset: HTMLFieldSetElement; + figcaption: HTMLElement; + figure: HTMLElement; + footer: HTMLElement; + form: HTMLFormElement; + h1: HTMLHeadingElement; + h2: HTMLHeadingElement; + h3: HTMLHeadingElement; + h4: HTMLHeadingElement; + h5: HTMLHeadingElement; + h6: HTMLHeadingElement; + head: HTMLHeadElement; + header: HTMLElement; + hgroup: HTMLElement; + hr: HTMLHRElement; + html: HTMLHtmlElement; + i: HTMLElement; + iframe: HTMLIFrameElement; + img: HTMLImageElement; + input: HTMLInputElement; + ins: HTMLModElement; + kbd: HTMLElement; + keygen: HTMLElement; + label: HTMLLabelElement; + legend: HTMLLegendElement; + li: HTMLLIElement; + link: HTMLLinkElement; + main: HTMLElement; + map: HTMLMapElement; + mark: HTMLElement; + menu: HTMLElement; + menuitem: HTMLElement; + meta: HTMLMetaElement; + meter: HTMLMeterElement; + nav: HTMLElement; + noindex: HTMLElement; + noscript: HTMLElement; + object: HTMLObjectElement; + ol: HTMLOListElement; + optgroup: HTMLOptGroupElement; + option: HTMLOptionElement; + output: HTMLOutputElement; + p: HTMLParagraphElement; + param: HTMLParamElement; + picture: HTMLElement; + pre: HTMLPreElement; + progress: HTMLProgressElement; + q: HTMLQuoteElement; + rp: HTMLElement; + rt: HTMLElement; + ruby: HTMLElement; + s: HTMLElement; + samp: HTMLElement; + search: HTMLElement; + slot: HTMLSlotElement; + script: HTMLScriptElement; + section: HTMLElement; + select: HTMLSelectElement; + small: HTMLElement; + source: HTMLSourceElement; + span: HTMLSpanElement; + strong: HTMLElement; + style: HTMLStyleElement; + sub: HTMLElement; + summary: HTMLElement; + sup: HTMLElement; + table: HTMLTableElement; + template: HTMLTemplateElement; + tbody: HTMLTableSectionElement; + td: HTMLTableDataCellElement; + textarea: HTMLTextAreaElement; + tfoot: HTMLTableSectionElement; + th: HTMLTableHeaderCellElement; + thead: HTMLTableSectionElement; + time: HTMLTimeElement; + title: HTMLTitleElement; + tr: HTMLTableRowElement; + track: HTMLTrackElement; + u: HTMLElement; + ul: HTMLUListElement; + var: HTMLElement; + video: HTMLVideoElement; + wbr: HTMLElement; + webview: HTMLWebViewElement; +} + +/** + * @public + */ +type ForwardRefComponent = { + readonly $$typeof: symbol; +} & ((props: PropsWithoutRef

& RefAttributes) => JSX.Element); +type AttributesWithoutMotionProps = { + [K in Exclude]?: Attributes[K]; +}; +/** + * @public + */ +type HTMLMotionProps = AttributesWithoutMotionProps & MotionProps; +/** + * Motion-optimised versions of React's HTML components. + * + * @public + */ +type HTMLMotionComponents = { + [K in keyof HTMLElements]: ForwardRefComponent>; +}; + +type UnionStringArray> = T[number]; +declare const svgElements: readonly ["animate", "circle", "defs", "desc", "ellipse", "g", "image", "line", "filter", "marker", "mask", "metadata", "path", "pattern", "polygon", "polyline", "rect", "stop", "svg", "switch", "symbol", "text", "tspan", "use", "view", "clipPath", "feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feDropShadow", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence", "foreignObject", "linearGradient", "radialGradient", "textPath"]; +type SVGElements = UnionStringArray; + +interface SVGAttributesWithoutMotionProps extends Pick, Exclude, keyof MotionProps>> { +} +/** + * Blanket-accept any SVG attribute as a `MotionValue` + * @public + */ +type SVGAttributesAsMotionValues = MakeMotion>; +type UnwrapSVGFactoryElement = F extends React.SVGProps ? P : never; +/** + * @public + */ +interface SVGMotionProps extends SVGAttributesAsMotionValues, MotionProps { +} +/** + * Motion-optimised versions of React's SVG components. + * + * @public + */ +type SVGMotionComponents = { + [K in SVGElements]: ForwardRefComponent, SVGMotionProps>>; +}; + +type DOMMotionComponents = HTMLMotionComponents & SVGMotionComponents; + +type MotionComponentProps = { + [K in Exclude]?: Props[K]; +} & MotionProps; +type MotionComponent = T extends keyof DOMMotionComponents ? DOMMotionComponents[T] : React$1.ComponentType, "children"> & { + children?: "children" extends keyof P ? P["children"] | MotionComponentProps

["children"] : MotionComponentProps

["children"]; +}>; +interface MotionComponentOptions { + forwardMotionProps?: boolean; +} + +declare function createMinimalMotionComponent(Component: TagName | string | React.ComponentType, options?: MotionComponentOptions): MotionComponent; + +declare const optimizedAppearDataAttribute: "data-framer-appear-id"; + +/** + * Expose only the needed part of the VisualElement interface to + * ensure React types don't end up in the generic DOM bundle. + */ +interface WithAppearProps { + props: { + [optimizedAppearDataAttribute]?: string; + values?: { + [key: string]: MotionValue | MotionValue; + }; + }; +} +type HandoffFunction = (storeId: string, valueName: string, frame: Batcher) => number | null; +/** + * The window global object acts as a bridge between our inline script + * triggering the optimized appear animations, and Motion. + */ +declare global { + interface Window { + MotionHandoffAnimation?: HandoffFunction; + MotionHandoffMarkAsComplete?: (elementId: string) => void; + MotionHandoffIsComplete?: (elementId: string) => boolean; + MotionHasOptimisedAnimation?: (elementId?: string, valueName?: string) => boolean; + MotionCancelOptimisedAnimation?: (elementId?: string, valueName?: string, frame?: Batcher, canResume?: boolean) => void; + MotionCheckAppearSync?: (visualElement: WithAppearProps, valueName: string, value: MotionValue) => VoidFunction | void; + MotionIsMounted?: boolean; + } +} + +/** + * HTML components + */ +declare const MotionA: ForwardRefComponent>; +declare const MotionAbbr: ForwardRefComponent>; +declare const MotionAddress: ForwardRefComponent>; +declare const MotionArea: ForwardRefComponent>; +declare const MotionArticle: ForwardRefComponent>; +declare const MotionAside: ForwardRefComponent>; +declare const MotionAudio: ForwardRefComponent>; +declare const MotionB: ForwardRefComponent>; +declare const MotionBase: ForwardRefComponent>; +declare const MotionBdi: ForwardRefComponent>; +declare const MotionBdo: ForwardRefComponent>; +declare const MotionBig: ForwardRefComponent>; +declare const MotionBlockquote: ForwardRefComponent>; +declare const MotionBody: ForwardRefComponent>; +declare const MotionButton: ForwardRefComponent>; +declare const MotionCanvas: ForwardRefComponent>; +declare const MotionCaption: ForwardRefComponent>; +declare const MotionCite: ForwardRefComponent>; +declare const MotionCode: ForwardRefComponent>; +declare const MotionCol: ForwardRefComponent>; +declare const MotionColgroup: ForwardRefComponent>; +declare const MotionData: ForwardRefComponent>; +declare const MotionDatalist: ForwardRefComponent>; +declare const MotionDd: ForwardRefComponent>; +declare const MotionDel: ForwardRefComponent>; +declare const MotionDetails: ForwardRefComponent>; +declare const MotionDfn: ForwardRefComponent>; +declare const MotionDialog: ForwardRefComponent>; +declare const MotionDiv: ForwardRefComponent>; +declare const MotionDl: ForwardRefComponent>; +declare const MotionDt: ForwardRefComponent>; +declare const MotionEm: ForwardRefComponent>; +declare const MotionEmbed: ForwardRefComponent>; +declare const MotionFieldset: ForwardRefComponent>; +declare const MotionFigcaption: ForwardRefComponent>; +declare const MotionFigure: ForwardRefComponent>; +declare const MotionFooter: ForwardRefComponent>; +declare const MotionForm: ForwardRefComponent>; +declare const MotionH1: ForwardRefComponent>; +declare const MotionH2: ForwardRefComponent>; +declare const MotionH3: ForwardRefComponent>; +declare const MotionH4: ForwardRefComponent>; +declare const MotionH5: ForwardRefComponent>; +declare const MotionH6: ForwardRefComponent>; +declare const MotionHead: ForwardRefComponent>; +declare const MotionHeader: ForwardRefComponent>; +declare const MotionHgroup: ForwardRefComponent>; +declare const MotionHr: ForwardRefComponent>; +declare const MotionHtml: ForwardRefComponent>; +declare const MotionI: ForwardRefComponent>; +declare const MotionIframe: ForwardRefComponent>; +declare const MotionImg: ForwardRefComponent>; +declare const MotionInput: ForwardRefComponent>; +declare const MotionIns: ForwardRefComponent>; +declare const MotionKbd: ForwardRefComponent>; +declare const MotionKeygen: ForwardRefComponent>; +declare const MotionLabel: ForwardRefComponent>; +declare const MotionLegend: ForwardRefComponent>; +declare const MotionLi: ForwardRefComponent>; +declare const MotionLink: ForwardRefComponent>; +declare const MotionMain: ForwardRefComponent>; +declare const MotionMap: ForwardRefComponent>; +declare const MotionMark: ForwardRefComponent>; +declare const MotionMenu: ForwardRefComponent>; +declare const MotionMenuitem: ForwardRefComponent>; +declare const MotionMeter: ForwardRefComponent>; +declare const MotionNav: ForwardRefComponent>; +declare const MotionObject: ForwardRefComponent>; +declare const MotionOl: ForwardRefComponent>; +declare const MotionOptgroup: ForwardRefComponent>; +declare const MotionOption: ForwardRefComponent>; +declare const MotionOutput: ForwardRefComponent>; +declare const MotionP: ForwardRefComponent>; +declare const MotionParam: ForwardRefComponent>; +declare const MotionPicture: ForwardRefComponent>; +declare const MotionPre: ForwardRefComponent>; +declare const MotionProgress: ForwardRefComponent>; +declare const MotionQ: ForwardRefComponent>; +declare const MotionRp: ForwardRefComponent>; +declare const MotionRt: ForwardRefComponent>; +declare const MotionRuby: ForwardRefComponent>; +declare const MotionS: ForwardRefComponent>; +declare const MotionSamp: ForwardRefComponent>; +declare const MotionScript: ForwardRefComponent>; +declare const MotionSection: ForwardRefComponent>; +declare const MotionSelect: ForwardRefComponent>; +declare const MotionSmall: ForwardRefComponent>; +declare const MotionSource: ForwardRefComponent>; +declare const MotionSpan: ForwardRefComponent>; +declare const MotionStrong: ForwardRefComponent>; +declare const MotionStyle: ForwardRefComponent>; +declare const MotionSub: ForwardRefComponent>; +declare const MotionSummary: ForwardRefComponent>; +declare const MotionSup: ForwardRefComponent>; +declare const MotionTable: ForwardRefComponent>; +declare const MotionTbody: ForwardRefComponent>; +declare const MotionTd: ForwardRefComponent>; +declare const MotionTextarea: ForwardRefComponent>; +declare const MotionTfoot: ForwardRefComponent>; +declare const MotionTh: ForwardRefComponent>; +declare const MotionThead: ForwardRefComponent>; +declare const MotionTime: ForwardRefComponent>; +declare const MotionTitle: ForwardRefComponent>; +declare const MotionTr: ForwardRefComponent>; +declare const MotionTrack: ForwardRefComponent>; +declare const MotionU: ForwardRefComponent>; +declare const MotionUl: ForwardRefComponent>; +declare const MotionVideo: ForwardRefComponent>; +declare const MotionWbr: ForwardRefComponent>; +declare const MotionWebview: ForwardRefComponent>; +/** + * SVG components + */ +declare const MotionAnimate: ForwardRefComponent>; +declare const MotionCircle: ForwardRefComponent>; +declare const MotionDefs: ForwardRefComponent>; +declare const MotionDesc: ForwardRefComponent>; +declare const MotionEllipse: ForwardRefComponent>; +declare const MotionG: ForwardRefComponent>; +declare const MotionImage: ForwardRefComponent>; +declare const MotionLine: ForwardRefComponent>; +declare const MotionFilter: ForwardRefComponent>; +declare const MotionMarker: ForwardRefComponent>; +declare const MotionMask: ForwardRefComponent>; +declare const MotionMetadata: ForwardRefComponent>; +declare const MotionPath: ForwardRefComponent>; +declare const MotionPattern: ForwardRefComponent>; +declare const MotionPolygon: ForwardRefComponent>; +declare const MotionPolyline: ForwardRefComponent>; +declare const MotionRect: ForwardRefComponent>; +declare const MotionStop: ForwardRefComponent>; +declare const MotionSvg: ForwardRefComponent>; +declare const MotionSymbol: ForwardRefComponent>; +declare const MotionText: ForwardRefComponent>; +declare const MotionTspan: ForwardRefComponent>; +declare const MotionUse: ForwardRefComponent>; +declare const MotionView: ForwardRefComponent>; +declare const MotionClipPath: ForwardRefComponent>; +declare const MotionFeBlend: ForwardRefComponent>; +declare const MotionFeColorMatrix: ForwardRefComponent>; +declare const MotionFeComponentTransfer: ForwardRefComponent>; +declare const MotionFeComposite: ForwardRefComponent>; +declare const MotionFeConvolveMatrix: ForwardRefComponent>; +declare const MotionFeDiffuseLighting: ForwardRefComponent>; +declare const MotionFeDisplacementMap: ForwardRefComponent>; +declare const MotionFeDistantLight: ForwardRefComponent>; +declare const MotionFeDropShadow: ForwardRefComponent>; +declare const MotionFeFlood: ForwardRefComponent>; +declare const MotionFeFuncA: ForwardRefComponent>; +declare const MotionFeFuncB: ForwardRefComponent>; +declare const MotionFeFuncG: ForwardRefComponent>; +declare const MotionFeFuncR: ForwardRefComponent>; +declare const MotionFeGaussianBlur: ForwardRefComponent>; +declare const MotionFeImage: ForwardRefComponent>; +declare const MotionFeMerge: ForwardRefComponent>; +declare const MotionFeMergeNode: ForwardRefComponent>; +declare const MotionFeMorphology: ForwardRefComponent>; +declare const MotionFeOffset: ForwardRefComponent>; +declare const MotionFePointLight: ForwardRefComponent>; +declare const MotionFeSpecularLighting: ForwardRefComponent>; +declare const MotionFeSpotLight: ForwardRefComponent>; +declare const MotionFeTile: ForwardRefComponent>; +declare const MotionFeTurbulence: ForwardRefComponent>; +declare const MotionForeignObject: ForwardRefComponent>; +declare const MotionLinearGradient: ForwardRefComponent>; +declare const MotionRadialGradient: ForwardRefComponent>; +declare const MotionTextPath: ForwardRefComponent>; + +export { MotionA as a, MotionAbbr as abbr, MotionAddress as address, MotionAnimate as animate, MotionArea as area, MotionArticle as article, MotionAside as aside, MotionAudio as audio, MotionB as b, MotionBase as base, MotionBdi as bdi, MotionBdo as bdo, MotionBig as big, MotionBlockquote as blockquote, MotionBody as body, MotionButton as button, MotionCanvas as canvas, MotionCaption as caption, MotionCircle as circle, MotionCite as cite, MotionClipPath as clipPath, MotionCode as code, MotionCol as col, MotionColgroup as colgroup, createMinimalMotionComponent as create, MotionData as data, MotionDatalist as datalist, MotionDd as dd, MotionDefs as defs, MotionDel as del, MotionDesc as desc, MotionDetails as details, MotionDfn as dfn, MotionDialog as dialog, MotionDiv as div, MotionDl as dl, MotionDt as dt, MotionEllipse as ellipse, MotionEm as em, MotionEmbed as embed, MotionFeBlend as feBlend, MotionFeColorMatrix as feColorMatrix, MotionFeComponentTransfer as feComponentTransfer, MotionFeComposite as feComposite, MotionFeConvolveMatrix as feConvolveMatrix, MotionFeDiffuseLighting as feDiffuseLighting, MotionFeDisplacementMap as feDisplacementMap, MotionFeDistantLight as feDistantLight, MotionFeDropShadow as feDropShadow, MotionFeFlood as feFlood, MotionFeFuncA as feFuncA, MotionFeFuncB as feFuncB, MotionFeFuncG as feFuncG, MotionFeFuncR as feFuncR, MotionFeGaussianBlur as feGaussianBlur, MotionFeImage as feImage, MotionFeMerge as feMerge, MotionFeMergeNode as feMergeNode, MotionFeMorphology as feMorphology, MotionFeOffset as feOffset, MotionFePointLight as fePointLight, MotionFeSpecularLighting as feSpecularLighting, MotionFeSpotLight as feSpotLight, MotionFeTile as feTile, MotionFeTurbulence as feTurbulence, MotionFieldset as fieldset, MotionFigcaption as figcaption, MotionFigure as figure, MotionFilter as filter, MotionFooter as footer, MotionForeignObject as foreignObject, MotionForm as form, MotionG as g, MotionH1 as h1, MotionH2 as h2, MotionH3 as h3, MotionH4 as h4, MotionH5 as h5, MotionH6 as h6, MotionHead as head, MotionHeader as header, MotionHgroup as hgroup, MotionHr as hr, MotionHtml as html, MotionI as i, MotionIframe as iframe, MotionImage as image, MotionImg as img, MotionInput as input, MotionIns as ins, MotionKbd as kbd, MotionKeygen as keygen, MotionLabel as label, MotionLegend as legend, MotionLi as li, MotionLine as line, MotionLinearGradient as linearGradient, MotionLink as link, MotionMain as main, MotionMap as map, MotionMark as mark, MotionMarker as marker, MotionMask as mask, MotionMenu as menu, MotionMenuitem as menuitem, MotionMetadata as metadata, MotionMeter as meter, MotionNav as nav, MotionObject as object, MotionOl as ol, MotionOptgroup as optgroup, MotionOption as option, MotionOutput as output, MotionP as p, MotionParam as param, MotionPath as path, MotionPattern as pattern, MotionPicture as picture, MotionPolygon as polygon, MotionPolyline as polyline, MotionPre as pre, MotionProgress as progress, MotionQ as q, MotionRadialGradient as radialGradient, MotionRect as rect, MotionRp as rp, MotionRt as rt, MotionRuby as ruby, MotionS as s, MotionSamp as samp, MotionScript as script, MotionSection as section, MotionSelect as select, MotionSmall as small, MotionSource as source, MotionSpan as span, MotionStop as stop, MotionStrong as strong, MotionStyle as style, MotionSub as sub, MotionSummary as summary, MotionSup as sup, MotionSvg as svg, MotionSymbol as symbol, MotionTable as table, MotionTbody as tbody, MotionTd as td, MotionText as text, MotionTextPath as textPath, MotionTextarea as textarea, MotionTfoot as tfoot, MotionTh as th, MotionThead as thead, MotionTime as time, MotionTitle as title, MotionTr as tr, MotionTrack as track, MotionTspan as tspan, MotionU as u, MotionUl as ul, MotionUse as use, MotionVideo as video, MotionView as view, MotionWbr as wbr, MotionWebview as webview }; diff --git a/frontend/node_modules/framer-motion/dist/mini.d.ts b/frontend/node_modules/framer-motion/dist/mini.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c2d756c565e64689ea9b00e098086b415023065 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/mini.d.ts @@ -0,0 +1,6 @@ +import * as motion_dom from 'motion-dom'; +import { AnimationScope } from 'motion-dom'; + +declare function useAnimateMini(): [AnimationScope, (elementOrSelector: motion_dom.ElementOrSelector, keyframes: motion_dom.DOMKeyframesDefinition, options?: motion_dom.AnimationOptions | undefined) => motion_dom.AnimationPlaybackControlsWithThen]; + +export { useAnimateMini as useAnimate }; diff --git a/frontend/node_modules/framer-motion/dist/mini.js b/frontend/node_modules/framer-motion/dist/mini.js new file mode 100644 index 0000000000000000000000000000000000000000..8f02b5016a496fcae5358844af9488030323321e --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/mini.js @@ -0,0 +1 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).Motion={},t.React)}(this,function(t,e){"use strict";function i(t){const i=e.useRef(null);return null===i.current&&(i.current=t()),i.current}function n(t){let e;return()=>(void 0===e&&(e=t()),e)}const s=t=>t,a=t=>1e3*t,o=t=>t/1e3,r=t=>null!==t;class l{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,e){return this.finished.then(t,e)}}function u(t){for(let e=1;et.startsWith("--");const d=n(()=>void 0!==window.ScrollTimeline),m={};function c(t,e){const i=n(t);return()=>m[e]??i()}const p=c(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch(t){return!1}return!0},"linearEasing"),f=([t,e,i,n])=>`cubic-bezier(${t}, ${e}, ${i}, ${n})`,y={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:f([0,.65,.55,1]),circOut:f([.55,0,1,.45]),backIn:f([.31,.01,.66,-.59]),backOut:f([.33,1.53,.69,.99])};function g(t,e){return t?"function"==typeof t?p()?((t,e,i=10)=>{let n="";const s=Math.max(Math.round(e/i),2);for(let e=0;eArray.isArray(t)&&"number"==typeof t[0])(t)?f(t):Array.isArray(t)?t.map(t=>g(t,e)||y.easeOut):y[t]:void 0}class T extends l{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:e,name:i,keyframes:n,pseudoElement:s,allowFlatten:a=!1,finalKeyframe:o,onComplete:l}=t;this.isPseudoElement=Boolean(s),this.allowFlatten=a,this.options=t,t.type;const u=function({type:t,...e}){return function(t){return"function"==typeof t&&"applyToOptions"in t}(t)&&p()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}(t);this.animation=function(t,e,i,{delay:n=0,duration:s=300,repeat:a=0,repeatType:o="loop",ease:r="easeOut",times:l}={},u){const h={[e]:i};l&&(h.offset=l);const d=g(r,s);Array.isArray(d)&&(h.easing=d);const m={delay:n,duration:s,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:a+1,direction:"reverse"===o?"alternate":"normal"};return u&&(m.pseudoElement=u),t.animate(h,m)}(e,i,n,u,s),!1===u.autoplay&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!s){const t=function(t,{repeat:e,repeatType:i="loop"},n,s=1){const a=t.filter(r),o=s<0||e&&"loop"!==i&&e%2==1?0:a.length-1;return o&&void 0!==n?n:a[o]}(n,this.options,o,this.speed);this.updateMotionValue?this.updateMotionValue(t):function(t,e,i){h(e)?t.style.setProperty(e,i):t.style[e]=i}(e,i,t),this.animation.cancel()}l?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),"finished"===this.state&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch(t){}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;"idle"!==t&&"finished"!==t&&(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming?.().duration||0;return o(Number(t))}get time(){return o(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=a(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return null!==this.finishedTime?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:e}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&d()?(this.animation.timeline=t,s):e(this)}}class b{constructor(t){this.stop=()=>this.runAll("stop"),this.animations=t.filter(Boolean)}get finished(){return Promise.all(this.animations.map(t=>t.finished))}getAll(t){return this.animations[0][t]}setAll(t,e){for(let i=0;ie.attachTimeline(t));return()=>{e.forEach((t,e)=>{t&&t(),this.animations[e].stop()})}}get time(){return this.getAll("time")}set time(t){this.setAll("time",t)}get speed(){return this.getAll("speed")}set speed(t){this.setAll("speed",t)}get state(){return this.getAll("state")}get startTime(){return this.getAll("startTime")}get duration(){let t=0;for(let e=0;ee[t]())}play(){this.runAll("play")}pause(){this.runAll("pause")}cancel(){this.runAll("cancel")}complete(){this.runAll("complete")}}class A extends b{then(t,e){return this.finished.finally(t).then(()=>{})}}const w=new WeakMap,E=(t,e="")=>`${t}:${e}`;function R(t){const e=w.get(t)||new Map;return w.set(t,e),e}function v(t,e){return t?.[e]??t?.default??t}const S=new Set(["borderWidth","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderRadius","radius","borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius","width","maxWidth","height","maxHeight","top","right","bottom","left","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","margin","marginTop","marginRight","marginBottom","marginLeft","backgroundPositionX","backgroundPositionY"]);function k(t,e){for(let i=0;ie.delete(i)),l.push(s)}return l}t.useAnimate=function(){const t=i(()=>({current:null,animations:[]})),n=i(()=>(t=>function(e,i,n){return new A(x(e,i,n,t))})(t));var s;return s=()=>{t.animations.forEach(t=>t.stop())},e.useEffect(()=>()=>s(),[]),[t,n]}}); diff --git a/frontend/node_modules/framer-motion/dist/size-rollup-animate.js b/frontend/node_modules/framer-motion/dist/size-rollup-animate.js new file mode 100644 index 0000000000000000000000000000000000000000..e637733fb92be30c753c338a948dc43a922addeb --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/size-rollup-animate.js @@ -0,0 +1 @@ +function t(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const e=(t,e,n)=>n>e?e:n/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);const i=t=>/^0[^.\s]+$/u.test(t);function r(t){let e;return()=>(void 0===e&&(e=t()),e)}const a=t=>t,o=(t,e)=>n=>e(t(n)),l=(...t)=>t.reduce(o),u=(t,e,n)=>{const s=e-t;return 0===s?1:(n-t)/s};class h{constructor(){this.subscriptions=[]}add(e){var n,s;return n=this.subscriptions,s=e,-1===n.indexOf(s)&&n.push(s),()=>t(this.subscriptions,e)}notify(t,e,n){const s=this.subscriptions.length;if(s)if(1===s)this.subscriptions[0](t,e,n);else for(let i=0;i1e3*t,d=t=>t/1e3;function p(t,e){return e?t*(1e3/e):0}const m=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t;function f(t,e,n,s){if(t===e&&n===s)return a;const i=e=>function(t,e,n,s,i){let r,a,o=0;do{a=e+(n-e)/2,r=m(a,s,i)-t,r>0?n=a:e=a}while(Math.abs(r)>1e-7&&++o<12);return a}(e,0,1,t,n);return t=>0===t||1===t?t:m(i(t),e,s)}const y=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,g=t=>e=>1-t(1-e),v=f(.33,1.53,.69,.99),b=g(v),w=y(b),T=t=>(t*=2)<1?.5*b(t):.5*(2-Math.pow(2,-10*(t-1))),M=t=>1-Math.sin(Math.acos(t)),V=g(M),A=y(M),S=f(.42,0,1,1),x=f(0,0,.58,1),k=f(.42,0,.58,1),C=t=>Array.isArray(t)&&"number"!=typeof t[0];function F(t,e){return C(t)?t[((t,e,n)=>{const s=e-t;return((n-t)%s+s)%s+t})(0,t.length,e)]:t}const P=t=>Array.isArray(t)&&"number"==typeof t[0],E={linear:a,easeIn:S,easeInOut:k,easeOut:x,circIn:M,circInOut:A,circOut:V,backIn:b,backInOut:w,backOut:v,anticipate:T},O=t=>{if(P(t)){t.length;const[e,n,s,i]=t;return f(e,n,s,i)}return"string"==typeof t?E[t]:t},D=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],I={value:null,addProjectionMetrics:null};function R(t,e){let s=!1,i=!0;const r={delta:0,timestamp:0,isProcessing:!1},a=()=>s=!0,o=D.reduce((t,n)=>(t[n]=function(t,e){let n=new Set,s=new Set,i=!1,r=!1;const a=new WeakSet;let o={delta:0,timestamp:0,isProcessing:!1},l=0;function u(e){a.has(e)&&(h.schedule(e),t()),l++,e(o)}const h={schedule:(t,e=!1,r=!1)=>{const o=r&&i?n:s;return e&&a.add(t),o.has(t)||o.add(t),t},cancel:t=>{s.delete(t),a.delete(t)},process:t=>{o=t,i?r=!0:(i=!0,[n,s]=[s,n],n.forEach(u),e&&I.value&&I.value.frameloop[e].push(l),l=0,n.clear(),i=!1,r&&(r=!1,h.process(t)))}};return h}(a,e?n:void 0),t),{}),{setup:l,read:u,resolveKeyframes:h,preUpdate:c,update:d,preRender:p,render:m,postRender:f}=o,y=()=>{const a=n.useManualTiming?r.timestamp:performance.now();s=!1,n.useManualTiming||(r.delta=i?1e3/60:Math.max(Math.min(a-r.timestamp,40),1)),r.timestamp=a,r.isProcessing=!0,l.process(r),u.process(r),h.process(r),c.process(r),d.process(r),p.process(r),m.process(r),f.process(r),r.isProcessing=!1,s&&e&&(i=!1,t(y))};return{schedule:D.reduce((e,n)=>{const a=o[n];return e[n]=(e,n=!1,o=!1)=>(s||(s=!0,i=!0,r.isProcessing||t(y)),a.schedule(e,n,o)),e},{}),cancel:t=>{for(let e=0;e(void 0===W&&$.set(K.isProcessing||n.useManualTiming?K.timestamp:performance.now()),W),set:t=>{W=t,queueMicrotask(Y)}},L=t=>e=>"string"==typeof e&&e.startsWith(t),U=L("--"),X=L("var(--"),q=t=>!!X(t)&&z.test(t.split("/*")[0].trim()),z=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Z={test:t=>"number"==typeof t,parse:parseFloat,transform:t=>t},H={...Z,transform:t=>e(0,1,t)},_={...Z,default:1},G=t=>Math.round(1e5*t)/1e5,J=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;const Q=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,tt=(t,e)=>n=>Boolean("string"==typeof n&&Q.test(n)&&n.startsWith(t)||e&&!function(t){return null==t}(n)&&Object.prototype.hasOwnProperty.call(n,e)),et=(t,e,n)=>s=>{if("string"!=typeof s)return s;const[i,r,a,o]=s.match(J);return{[t]:parseFloat(i),[e]:parseFloat(r),[n]:parseFloat(a),alpha:void 0!==o?parseFloat(o):1}},nt={...Z,transform:t=>Math.round((t=>e(0,255,t))(t))},st={test:tt("rgb","red"),parse:et("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:s=1})=>"rgba("+nt.transform(t)+", "+nt.transform(e)+", "+nt.transform(n)+", "+G(H.transform(s))+")"};const it={test:tt("#"),parse:function(t){let e="",n="",s="",i="";return t.length>5?(e=t.substring(1,3),n=t.substring(3,5),s=t.substring(5,7),i=t.substring(7,9)):(e=t.substring(1,2),n=t.substring(2,3),s=t.substring(3,4),i=t.substring(4,5),e+=e,n+=n,s+=s,i+=i),{red:parseInt(e,16),green:parseInt(n,16),blue:parseInt(s,16),alpha:i?parseInt(i,16)/255:1}},transform:st.transform},rt=t=>({test:e=>"string"==typeof e&&e.endsWith(t)&&1===e.split(" ").length,parse:parseFloat,transform:e=>`${e}${t}`}),at=rt("deg"),ot=rt("%"),lt=rt("px"),ut=rt("vh"),ht=rt("vw"),ct=(()=>({...ot,parse:t=>ot.parse(t)/100,transform:t=>ot.transform(100*t)}))(),dt={test:tt("hsl","hue"),parse:et("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:s=1})=>"hsla("+Math.round(t)+", "+ot.transform(G(e))+", "+ot.transform(G(n))+", "+G(H.transform(s))+")"},pt={test:t=>st.test(t)||it.test(t)||dt.test(t),parse:t=>st.test(t)?st.parse(t):dt.test(t)?dt.parse(t):it.parse(t),transform:t=>"string"==typeof t?t:t.hasOwnProperty("red")?st.transform(t):dt.transform(t),getAnimatableNone:t=>{const e=pt.parse(t);return e.alpha=0,pt.transform(e)}},mt=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;const ft="number",yt="color",gt=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function vt(t){const e=t.toString(),n=[],s={color:[],number:[],var:[]},i=[];let r=0;const a=e.replace(gt,t=>(pt.test(t)?(s.color.push(r),i.push(yt),n.push(pt.parse(t))):t.startsWith("var(")?(s.var.push(r),i.push("var"),n.push(t)):(s.number.push(r),i.push(ft),n.push(parseFloat(t))),++r,"${}")).split("${}");return{values:n,split:a,indexes:s,types:i}}function bt(t){return vt(t).values}function wt(t){const{split:e,types:n}=vt(t),s=e.length;return t=>{let i="";for(let r=0;r"number"==typeof t?0:pt.test(t)?pt.getAnimatableNone(t):t;const Mt={test:function(t){return isNaN(t)&&"string"==typeof t&&(t.match(J)?.length||0)+(t.match(mt)?.length||0)>0},parse:bt,createTransformer:wt,getAnimatableNone:function(t){const e=bt(t);return wt(t)(e.map(Tt))}};function Vt(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<.5?e:n<2/3?t+(e-t)*(2/3-n)*6:t}function At(t,e){return n=>n>0?e:t}const St=(t,e,n)=>t+(e-t)*n,xt=(t,e,n)=>{const s=t*t,i=n*(e*e-s)+s;return i<0?0:Math.sqrt(i)},kt=[it,st,dt];function Ct(t){const e=(n=t,kt.find(t=>t.test(n)));var n;if(!Boolean(e))return!1;let s=e.parse(t);return e===dt&&(s=function({hue:t,saturation:e,lightness:n,alpha:s}){t/=360,n/=100;let i=0,r=0,a=0;if(e/=100){const s=n<.5?n*(1+e):n+e-n*e,o=2*n-s;i=Vt(o,s,t+1/3),r=Vt(o,s,t),a=Vt(o,s,t-1/3)}else i=r=a=n;return{red:Math.round(255*i),green:Math.round(255*r),blue:Math.round(255*a),alpha:s}}(s)),s}const Ft=(t,e)=>{const n=Ct(t),s=Ct(e);if(!n||!s)return At(t,e);const i={...n};return t=>(i.red=xt(n.red,s.red,t),i.green=xt(n.green,s.green,t),i.blue=xt(n.blue,s.blue,t),i.alpha=St(n.alpha,s.alpha,t),st.transform(i))},Pt=new Set(["none","hidden"]);function Et(t,e){return n=>St(t,e,n)}function Ot(t){return"number"==typeof t?Et:"string"==typeof t?q(t)?At:pt.test(t)?Ft:Rt:Array.isArray(t)?Dt:"object"==typeof t?pt.test(t)?Ft:It:At}function Dt(t,e){const n=[...t],s=n.length,i=t.map((t,n)=>Ot(t)(t,e[n]));return t=>{for(let e=0;e{for(const e in s)n[e]=s[e](t);return n}}const Rt=(t,e)=>{const n=Mt.createTransformer(e),s=vt(t),i=vt(e);return s.indexes.var.length===i.indexes.var.length&&s.indexes.color.length===i.indexes.color.length&&s.indexes.number.length>=i.indexes.number.length?Pt.has(t)&&!i.values.length||Pt.has(e)&&!s.values.length?function(t,e){return Pt.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}(t,e):l(Dt(function(t,e){const n=[],s={color:0,var:0,number:0};for(let i=0;i{const e=({timestamp:e})=>t(e);return{start:(t=!0)=>B.update(e,t),stop:()=>N(e),now:()=>K.isProcessing?K.timestamp:$.now()}},Kt=(t,e,n=10)=>{let s="";const i=Math.max(Math.round(e/n),2);for(let e=0;e=jt?1/0:e}function Yt(t,e=100,n){const s=n({...t,keyframes:[0,e]}),i=Math.min(Wt(s),jt);return{type:"keyframes",ease:t=>s.next(i*t).value/e,duration:d(i)}}function $t(t,e,n){const s=Math.max(e-5,0);return p(n-t(s),e-s)}const Lt=100,Ut=10,Xt=1,qt=0,zt=800,Zt=.3,Ht=.3,_t={granular:.01,default:2},Gt={granular:.005,default:.5},Jt=.01,Qt=10,te=.05,ee=1,ne=.001;function se({duration:t=zt,bounce:n=Zt,velocity:s=qt,mass:i=Xt}){let r,a,o=1-n;o=e(te,ee,o),t=e(Jt,Qt,d(t)),o<1?(r=e=>{const n=e*o,i=n*t,r=n-s,a=re(e,o),l=Math.exp(-i);return ne-r/a*l},a=e=>{const n=e*o*t,i=n*s+s,a=Math.pow(o,2)*Math.pow(e,2)*t,l=Math.exp(-n),u=re(Math.pow(e,2),o);return(-r(e)+ne>0?-1:1)*((i-a)*l)/u}):(r=e=>Math.exp(-e*t)*((e-s)*t+1)-.001,a=e=>Math.exp(-e*t)*(t*t*(s-e)));const l=function(t,e,n){let s=n;for(let n=1;nvoid 0!==t[e])}function ue(t=Ht,n=Zt){const s="object"!=typeof t?{visualDuration:t,keyframes:[0,1],bounce:n}:t;let{restSpeed:i,restDelta:r}=s;const a=s.keyframes[0],o=s.keyframes[s.keyframes.length-1],l={done:!1,value:a},{stiffness:u,damping:h,mass:p,duration:m,velocity:f,isResolvedFromDuration:y}=function(t){let n={velocity:qt,stiffness:Lt,damping:Ut,mass:Xt,isResolvedFromDuration:!1,...t};if(!le(t,oe)&&le(t,ae))if(t.visualDuration){const s=t.visualDuration,i=2*Math.PI/(1.2*s),r=i*i,a=2*e(.05,1,1-(t.bounce||0))*Math.sqrt(r);n={...n,mass:Xt,stiffness:r,damping:a}}else{const e=se(t);n={...n,...e,mass:Xt},n.isResolvedFromDuration=!0}return n}({...s,velocity:-d(s.velocity||0)}),g=f||0,v=h/(2*Math.sqrt(u*p)),b=o-a,w=d(Math.sqrt(u/p)),T=Math.abs(b)<5;let M;if(i||(i=T?_t.granular:_t.default),r||(r=T?Gt.granular:Gt.default),v<1){const t=re(w,v);M=e=>{const n=Math.exp(-v*w*e);return o-n*((g+v*w*b)/t*Math.sin(t*e)+b*Math.cos(t*e))}}else if(1===v)M=t=>o-Math.exp(-w*t)*(b+(g+w*b)*t);else{const t=w*Math.sqrt(v*v-1);M=e=>{const n=Math.exp(-v*w*e),s=Math.min(t*e,300);return o-n*((g+v*w*b)*Math.sinh(s)+t*b*Math.cosh(s))/t}}const V={calculatedDuration:y&&m||null,next:t=>{const e=M(t);if(y)l.done=t>=m;else{let n=0===t?g:0;v<1&&(n=0===t?c(g):$t(M,t,e));const s=Math.abs(n)<=i,a=Math.abs(o-e)<=r;l.done=s&&a}return l.value=l.done?o:e,l},toString:()=>{const t=Math.min(Wt(V),jt),e=Kt(e=>V.next(t*e).value,t,30);return t+"ms "+e},toTransition:()=>{}};return V}function he({keyframes:t,velocity:e=0,power:n=.8,timeConstant:s=325,bounceDamping:i=10,bounceStiffness:r=500,modifyTarget:a,min:o,max:l,restDelta:u=.5,restSpeed:h}){const c=t[0],d={done:!1,value:c},p=t=>void 0===o?l:void 0===l||Math.abs(o-t)-m*Math.exp(-t/s),v=t=>y+g(t),b=t=>{const e=g(t),n=v(t);d.done=Math.abs(e)<=u,d.value=d.done?y:n};let w,T;const M=t=>{var e;(e=d.value,void 0!==o&&el)&&(w=t,T=ue({keyframes:[d.value,p(d.value)],velocity:$t(v,t,d.value),damping:i,stiffness:r,restDelta:u,restSpeed:h}))};return M(0),{calculatedDuration:null,next:t=>{let e=!1;return T||void 0!==w||(e=!0,b(t),M(t)),void 0!==w&&t>=w?T.next(t-w):(!e&&b(t),d)}}}function ce(t,s,{clamp:i=!0,ease:r,mixer:o}={}){const h=t.length;if(s.length,1===h)return()=>s[0];if(2===h&&s[0]===s[1])return()=>s[1];const c=t[0]===t[1];t[0]>t[h-1]&&(t=[...t].reverse(),s=[...s].reverse());const d=function(t,e,s){const i=[],r=s||n.mix||Bt,o=t.length-1;for(let n=0;n{if(c&&e1)for(;nm(e(t[0],t[h-1],n)):m}function de(t,e){const n=t[t.length-1];for(let s=1;s<=e;s++){const i=u(0,e,s);t.push(St(n,1,i))}}function pe(t){const e=[0];return de(e,t.length-1),e}function me({duration:t=300,keyframes:e,times:n,ease:s="easeInOut"}){const i=C(s)?s.map(O):O(s),r={done:!1,value:e[0]},a=function(t,e){return t.map(t=>t*e)}(n&&n.length===e.length?n:pe(e),t),o=ce(a,e,{ease:Array.isArray(i)?i:(l=e,u=i,l.map(()=>u||k).splice(0,l.length-1))});var l,u;return{calculatedDuration:t,next:e=>(r.value=o(e),r.done=e>=t,r)}}ue.applyToOptions=t=>{const e=Yt(t,100,ue);return t.ease=e.ease,t.duration=c(e.duration),t.type="keyframes",t};const fe=t=>null!==t;function ye(t,{repeat:e,repeatType:n="loop"},s,i=1){const r=t.filter(fe),a=i<0||e&&"loop"!==n&&e%2==1?0:r.length-1;return a&&void 0!==s?s:r[a]}const ge={decay:he,inertia:he,tween:me,keyframes:me,spring:ue};function ve(t){"string"==typeof t.type&&(t.type=ge[t.type])}class be{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,e){return this.finished.then(t,e)}}const we=t=>t/100;class Te extends be{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:t}=this.options;t&&t.updatedAt!==$.now()&&this.tick($.now()),this.isStopped=!0,"idle"!==this.state&&(this.teardown(),this.options.onStop?.())},this.options=t,this.initAnimation(),this.play(),!1===t.autoplay&&this.pause()}initAnimation(){const{options:t}=this;ve(t);const{type:e=me,repeat:n=0,repeatDelay:s=0,repeatType:i,velocity:r=0}=t;let{keyframes:a}=t;const o=e||me;o!==me&&"number"!=typeof a[0]&&(this.mixKeyframes=l(we,Bt(a[0],a[1])),a=[0,100]);const u=o({...t,keyframes:a});"mirror"===i&&(this.mirroredGenerator=o({...t,keyframes:[...a].reverse(),velocity:-r})),null===u.calculatedDuration&&(u.calculatedDuration=Wt(u));const{calculatedDuration:h}=u;this.calculatedDuration=h,this.resolvedDuration=h+s,this.totalDuration=this.resolvedDuration*(n+1)-s,this.generator=u}updateTime(t){const e=Math.round(t-this.startTime)*this.playbackSpeed;null!==this.holdTime?this.currentTime=this.holdTime:this.currentTime=e}tick(t,n=!1){const{generator:s,totalDuration:i,mixKeyframes:r,mirroredGenerator:a,resolvedDuration:o,calculatedDuration:l}=this;if(null===this.startTime)return s.next(0);const{delay:u=0,keyframes:h,repeat:c,repeatType:d,repeatDelay:p,type:m,onUpdate:f,finalKeyframe:y}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-i/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const g=this.currentTime-u*(this.playbackSpeed>=0?1:-1),v=this.playbackSpeed>=0?g<0:g>i;this.currentTime=Math.max(g,0),"finished"===this.state&&null===this.holdTime&&(this.currentTime=i);let b=this.currentTime,w=s;if(c){const t=Math.min(this.currentTime,i)/o;let n=Math.floor(t),s=t%1;!s&&t>=1&&(s=1),1===s&&n--,n=Math.min(n,c+1);Boolean(n%2)&&("reverse"===d?(s=1-s,p&&(s-=p/o)):"mirror"===d&&(w=a)),b=e(0,1,s)*o}const T=v?{done:!1,value:h[0]}:w.next(b);r&&(T.value=r(T.value));let{done:M}=T;v||null===l||(M=this.playbackSpeed>=0?this.currentTime>=i:this.currentTime<=0);const V=null===this.holdTime&&("finished"===this.state||"running"===this.state&&M);return V&&m!==he&&(T.value=ye(h,this.options,y,this.speed)),f&&f(T.value),V&&this.finish(),T}then(t,e){return this.finished.then(t,e)}get duration(){return d(this.calculatedDuration)}get time(){return d(this.currentTime)}set time(t){t=c(t),this.currentTime=t,null===this.startTime||null!==this.holdTime||0===this.playbackSpeed?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime($.now());const e=this.playbackSpeed!==t;this.playbackSpeed=t,e&&(this.time=d(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=Nt,startTime:e}=this.options;this.driver||(this.driver=t(t=>this.tick(t))),this.options.onPlay?.();const n=this.driver.now();"finished"===this.state?(this.updateFinished(),this.startTime=n):null!==this.holdTime?this.startTime=n-this.holdTime:this.startTime||(this.startTime=e??n),"finished"===this.state&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime($.now()),this.holdTime=this.currentTime}complete(){"running"!==this.state&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),t.observe(this)}}const Me=t=>180*t/Math.PI,Ve=t=>{const e=Me(Math.atan2(t[1],t[0]));return Se(e)},Ae={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Ve,rotateZ:Ve,skewX:t=>Me(Math.atan(t[1])),skewY:t=>Me(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Se=t=>((t%=360)<0&&(t+=360),t),xe=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),ke=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Ce={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:xe,scaleY:ke,scale:t=>(xe(t)+ke(t))/2,rotateX:t=>Se(Me(Math.atan2(t[6],t[5]))),rotateY:t=>Se(Me(Math.atan2(-t[2],t[0]))),rotateZ:Ve,rotate:Ve,skewX:t=>Me(Math.atan(t[4])),skewY:t=>Me(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Fe(t){return t.includes("scale")?1:0}function Pe(t,e){if(!t||"none"===t)return Fe(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,i;if(n)s=Ce,i=n;else{const e=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=Ae,i=e}if(!i)return Fe(e);const r=s[e],a=i[1].split(",").map(Ee);return"function"==typeof r?r(a):a[r]}function Ee(t){return parseFloat(t.trim())}const Oe=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],De=(()=>new Set(Oe))(),Ie=t=>t===Z||t===lt,Re=new Set(["x","y","z"]),Be=Oe.filter(t=>!Re.has(t));const Ne={width:({x:t},{paddingLeft:e="0",paddingRight:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),height:({y:t},{paddingTop:e="0",paddingBottom:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>Pe(e,"x"),y:(t,{transform:e})=>Pe(e,"y")};Ne.translateX=Ne.x,Ne.translateY=Ne.y;const Ke=new Set;let je=!1,We=!1,Ye=!1;function $e(){if(We){const t=Array.from(Ke).filter(t=>t.needsMeasurement),e=new Set(t.map(t=>t.element)),n=new Map;e.forEach(t=>{const e=function(t){const e=[];return Be.forEach(n=>{const s=t.getValue(n);void 0!==s&&(e.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),e}(t);e.length&&(n.set(t,e),t.render())}),t.forEach(t=>t.measureInitialState()),e.forEach(t=>{t.render();const e=n.get(t);e&&e.forEach(([e,n])=>{t.getValue(e)?.set(n)})}),t.forEach(t=>t.measureEndState()),t.forEach(t=>{void 0!==t.suspendedScrollY&&window.scrollTo(0,t.suspendedScrollY)})}We=!1,je=!1,Ke.forEach(t=>t.complete(Ye)),Ke.clear()}function Le(){Ke.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(We=!0)})}class Ue{constructor(t,e,n,s,i,r=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=e,this.name=n,this.motionValue=s,this.element=i,this.isAsync=r}scheduleResolve(){this.state="scheduled",this.isAsync?(Ke.add(this),je||(je=!0,B.read(Le),B.resolveKeyframes($e))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:e,element:n,motionValue:s}=this;if(null===t[0]){const i=s?.get(),r=t[t.length-1];if(void 0!==i)t[0]=i;else if(n&&e){const s=n.readValue(e,r);null!=s&&(t[0]=s)}void 0===t[0]&&(t[0]=r),s&&void 0===i&&s.set(t[0])}!function(t){for(let e=1;evoid 0!==window.ScrollTimeline),qe={};function ze(t,e){const n=r(t);return()=>qe[e]??n()}const Ze=ze(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch(t){return!1}return!0},"linearEasing"),He=([t,e,n,s])=>`cubic-bezier(${t}, ${e}, ${n}, ${s})`,_e={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:He([0,.65,.55,1]),circOut:He([.55,0,1,.45]),backIn:He([.31,.01,.66,-.59]),backOut:He([.33,1.53,.69,.99])};function Ge(t,e){return t?"function"==typeof t?Ze()?Kt(t,e):"ease-out":P(t)?He(t):Array.isArray(t)?t.map(t=>Ge(t,e)||_e.easeOut):_e[t]:void 0}function Je(t,e,n,{delay:s=0,duration:i=300,repeat:r=0,repeatType:a="loop",ease:o="easeOut",times:l}={},u=void 0){const h={[e]:n};l&&(h.offset=l);const c=Ge(o,i);Array.isArray(c)&&(h.easing=c);const d={delay:s,duration:i,easing:Array.isArray(c)?"linear":c,fill:"both",iterations:r+1,direction:"reverse"===a?"alternate":"normal"};u&&(d.pseudoElement=u);return t.animate(h,d)}function Qe(t){return"function"==typeof t&&"applyToOptions"in t}class tn extends be{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:e,name:n,keyframes:s,pseudoElement:i,allowFlatten:r=!1,finalKeyframe:a,onComplete:o}=t;this.isPseudoElement=Boolean(i),this.allowFlatten=r,this.options=t,t.type;const l=function({type:t,...e}){return Qe(t)&&Ze()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}(t);this.animation=Je(e,n,s,l,i),!1===l.autoplay&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const t=ye(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(t):function(t,e,n){(t=>t.startsWith("--"))(e)?t.style.setProperty(e,n):t.style[e]=n}(e,n,t),this.animation.cancel()}o?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),"finished"===this.state&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch(t){}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;"idle"!==t&&"finished"!==t&&(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming?.().duration||0;return d(Number(t))}get time(){return d(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=c(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return null!==this.finishedTime?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:e}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&Xe()?(this.animation.timeline=t,a):e(this)}}const en={anticipate:T,backInOut:w,circInOut:A};function nn(t){"string"==typeof t.ease&&t.ease in en&&(t.ease=en[t.ease])}class sn extends tn{constructor(t){nn(t),ve(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:e,onUpdate:n,onComplete:s,element:i,...r}=this.options;if(!e)return;if(void 0!==t)return void e.set(t);const a=new Te({...r,autoplay:!1}),o=c(this.finishedTime??this.time);e.setWithVelocity(a.sample(o-10).value,a.sample(o).value,10),a.stop()}}const rn=(t,e)=>"zIndex"!==e&&(!("number"!=typeof t&&!Array.isArray(t))||!("string"!=typeof t||!Mt.test(t)&&"0"!==t||t.startsWith("url(")));function an(t){t.duration=0,t.type}const on=new Set(["opacity","clipPath","filter","transform"]),ln=r(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));class un extends be{constructor({autoplay:t=!0,delay:e=0,type:n="keyframes",repeat:s=0,repeatDelay:i=0,repeatType:r="loop",keyframes:a,name:o,motionValue:l,element:u,...h}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=$.now();const c={autoplay:t,delay:e,type:n,repeat:s,repeatDelay:i,repeatType:r,name:o,motionValue:l,element:u,...h},d=u?.KeyframeResolver||Ue;this.keyframeResolver=new d(a,(t,e,n)=>this.onKeyframesResolved(t,e,c,!n),o,l,u),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,e,s,i){this.keyframeResolver=void 0;const{name:r,type:o,velocity:l,delay:u,isHandoff:h,onUpdate:c}=s;this.resolvedAt=$.now(),function(t,e,n,s){const i=t[0];if(null===i)return!1;if("display"===e||"visibility"===e)return!0;const r=t[t.length-1],a=rn(i,e),o=rn(r,e);return!(!a||!o)&&(function(t){const e=t[0];if(1===t.length)return!0;for(let n=0;n40?this.resolvedAt:this.createdAt:void 0,finalKeyframe:e,...s,keyframes:t},p=!h&&function(t){const{motionValue:e,name:n,repeatDelay:s,repeatType:i,damping:r,type:a}=t,o=e?.owner?.current;if(!(o instanceof HTMLElement))return!1;const{onUpdate:l,transformTemplate:u}=e.owner.getProps();return ln()&&n&&on.has(n)&&("transform"!==n||!u)&&!l&&!s&&"mirror"!==i&&0!==r&&"inertia"!==a}(d)?new sn({...d,element:d.motionValue.owner.current}):new Te(d);p.finished.then(()=>this.notifyFinished()).catch(a),this.pendingTimeline&&(this.stopTimeline=p.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=p}get finished(){return this._animation?this.animation.finished:this._finished}then(t,e){return this.finished.finally(t).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),Ye=!0,Le(),$e(),Ye=!1),this._animation}get duration(){return this.animation.duration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}class hn{constructor(t){this.stop=()=>this.runAll("stop"),this.animations=t.filter(Boolean)}get finished(){return Promise.all(this.animations.map(t=>t.finished))}getAll(t){return this.animations[0][t]}setAll(t,e){for(let n=0;ne.attachTimeline(t));return()=>{e.forEach((t,e)=>{t&&t(),this.animations[e].stop()})}}get time(){return this.getAll("time")}set time(t){this.setAll("time",t)}get speed(){return this.getAll("speed")}set speed(t){this.setAll("speed",t)}get state(){return this.getAll("state")}get startTime(){return this.getAll("startTime")}get duration(){let t=0;for(let e=0;ee[t]())}play(){this.runAll("play")}pause(){this.runAll("pause")}cancel(){this.runAll("cancel")}complete(){this.runAll("complete")}}class cn extends hn{then(t,e){return this.finished.finally(t).then(()=>{})}}const dn=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function pn(t,e,n=1){const[i,r]=function(t){const e=dn.exec(t);if(!e)return[,];const[,n,s,i]=e;return[`--${n??s}`,i]}(t);if(!i)return;const a=window.getComputedStyle(e).getPropertyValue(i);if(a){const t=a.trim();return s(t)?parseFloat(t):t}return q(r)?pn(r,e,n+1):r}function mn(t,e){return t?.[e]??t?.default??t}const fn=new Set(["width","height","top","left","right","bottom",...Oe]),yn=t=>e=>e.test(t),gn=[Z,lt,ot,at,ht,ut,{test:t=>"auto"===t,parse:t=>t}],vn=t=>gn.find(yn(t));function bn(t){return"number"==typeof t?0===t:null===t||("none"===t||"0"===t||i(t))}const wn=new Set(["brightness","contrast","saturate","opacity"]);function Tn(t){const[e,n]=t.slice(0,-1).split("(");if("drop-shadow"===e)return t;const[s]=n.match(J)||[];if(!s)return t;const i=n.replace(s,"");let r=wn.has(e)?1:0;return s!==n&&(r*=100),e+"("+r+i+")"}const Mn=/\b([a-z-]*)\(.*?\)/gu,Vn={...Mt,getAnimatableNone:t=>{const e=t.match(Mn);return e?e.map(Tn).join(" "):t}},An={...Z,transform:Math.round},Sn={borderWidth:lt,borderTopWidth:lt,borderRightWidth:lt,borderBottomWidth:lt,borderLeftWidth:lt,borderRadius:lt,radius:lt,borderTopLeftRadius:lt,borderTopRightRadius:lt,borderBottomRightRadius:lt,borderBottomLeftRadius:lt,width:lt,maxWidth:lt,height:lt,maxHeight:lt,top:lt,right:lt,bottom:lt,left:lt,padding:lt,paddingTop:lt,paddingRight:lt,paddingBottom:lt,paddingLeft:lt,margin:lt,marginTop:lt,marginRight:lt,marginBottom:lt,marginLeft:lt,backgroundPositionX:lt,backgroundPositionY:lt,...{rotate:at,rotateX:at,rotateY:at,rotateZ:at,scale:_,scaleX:_,scaleY:_,scaleZ:_,skew:at,skewX:at,skewY:at,distance:lt,translateX:lt,translateY:lt,translateZ:lt,x:lt,y:lt,z:lt,perspective:lt,transformPerspective:lt,opacity:H,originX:ct,originY:ct,originZ:lt},zIndex:An,fillOpacity:H,strokeOpacity:H,numOctaves:An},xn={...Sn,color:pt,backgroundColor:pt,outlineColor:pt,fill:pt,stroke:pt,borderColor:pt,borderTopColor:pt,borderRightColor:pt,borderBottomColor:pt,borderLeftColor:pt,filter:Vn,WebkitFilter:Vn},kn=t=>xn[t];function Cn(t,e){let n=kn(t);return n!==Vn&&(n=Mt),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const Fn=new Set(["auto","none","0"]);class Pn extends Ue{constructor(t,e,n,s,i){super(t,e,n,s,i,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:e,name:n}=this;if(!e||!e.current)return;super.readKeyframes();for(let n=0;n{t.getValue(e).set(n)}),this.resolveNoneKeyframes()}}const En=(t,e)=>e&&"number"==typeof t?e.transform(t):t;class On{constructor(t,e={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=t=>{const e=$.now();if(this.updatedAt!==e&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(t),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const t of this.dependents)t.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=e.owner}setCurrent(t){var e;this.current=t,this.updatedAt=$.now(),null===this.canTrackVelocity&&void 0!==t&&(this.canTrackVelocity=(e=this.current,!isNaN(parseFloat(e))))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return this.on("change",t)}on(t,e){this.events[t]||(this.events[t]=new h);const n=this.events[t].add(e);return"change"===t?()=>{n(),B.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,e){this.passiveEffect=t,this.stopPassiveEffect=e}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,e,n){this.set(e),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-n}jump(t,e=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,e&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=$.now();if(!this.canTrackVelocity||void 0===this.prevFrameValue||t-this.updatedAt>30)return 0;const e=Math.min(this.updatedAt-this.prevUpdatedAt,30);return p(parseFloat(this.current)-parseFloat(this.prevFrameValue),e)}start(t){return this.stop(),new Promise(e=>{this.hasAnimated=!0,this.animation=t(e),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function Dn(t,e){return new On(t,e)}const{schedule:In,cancel:Rn}=R(queueMicrotask,!1);function Bn(t){return"object"==typeof(e=t)&&null!==e&&"ownerSVGElement"in t;var e}const Nn=t=>Boolean(t&&t.getVelocity),Kn=[...gn,pt,Mt];function jn(t){return"object"==typeof t&&!Array.isArray(t)}function Wn(t,e,n,s){return"string"==typeof t&&jn(e)?function(t,e,n){if(t instanceof EventTarget)return[t];if("string"==typeof t){let s=document;e&&(s=e.current);const i=n?.[t]??s.querySelectorAll(t);return i?Array.from(i):[]}return Array.from(t)}(t,n,s):t instanceof NodeList?Array.from(t):Array.isArray(t)?t:[t]}function Yn(t,e,n){return t*(e+1)}function $n(t,e,n,s){return"number"==typeof e?e:e.startsWith("-")||e.startsWith("+")?Math.max(0,t+parseFloat(e)):"<"===e?n:e.startsWith("<")?Math.max(0,n+parseFloat(e.slice(1))):s.get(e)??t}function Ln(e,n,s,i,r,a){!function(e,n,s){for(let i=0;in&&r.at"number"==typeof t,Gn=t=>t.every(_n),Jn=new WeakMap;function Qn(t){const e=[{},{}];return t?.values.forEach((t,n)=>{e[0][n]=t.get(),e[1][n]=t.getVelocity()}),e}function ts(t,e,n,s){if("function"==typeof e){const[i,r]=Qn(s);e=e(void 0!==n?n:t.custom,i,r)}if("string"==typeof e&&(e=t.variants&&t.variants[e]),"function"==typeof e){const[i,r]=Qn(s);e=e(void 0!==n?n:t.custom,i,r)}return e}function es(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,Dn(n))}function ns(t){return(t=>Array.isArray(t))(t)?t[t.length-1]||0:t}function ss(t,e){const n=function(t,e,n){const s=t.getProps();return ts(s,e,void 0!==n?n:s.custom,t)}(t,e);let{transitionEnd:s={},transition:i={},...r}=n||{};r={...r,...s};for(const e in r){es(t,e,ns(r[e]))}}function is(t,e){const s=t.getValue("willChange");if(i=s,Boolean(Nn(i)&&i.add))return s.add(e);if(!s&&n.WillChange){const s=new n.WillChange("auto");t.addValue("willChange",s),s.add(e)}var i}const rs=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),as="data-"+rs("framerAppearId");function os(t){return t.props[as]}const ls=t=>null!==t;const us={type:"spring",stiffness:500,damping:25,restSpeed:10},hs={type:"keyframes",duration:.8},cs={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},ds=(t,{keyframes:e})=>e.length>2?hs:De.has(t)?t.startsWith("scale")?{type:"spring",stiffness:550,damping:0===e[1]?2*Math.sqrt(550):30,restSpeed:10}:us:cs;const ps=(t,e,s,i={},r,a)=>o=>{const l=mn(i,t)||{},u=l.delay||i.delay||0;let{elapsed:h=0}=i;h-=c(u);const d={keyframes:Array.isArray(s)?s:[null,s],ease:"easeOut",velocity:e.getVelocity(),...l,delay:-h,onUpdate:t=>{e.set(t),l.onUpdate&&l.onUpdate(t)},onComplete:()=>{o(),l.onComplete&&l.onComplete()},name:t,motionValue:e,element:a?void 0:r};(function({when:t,delay:e,delayChildren:n,staggerChildren:s,staggerDirection:i,repeat:r,repeatType:a,repeatDelay:o,from:l,elapsed:u,...h}){return!!Object.keys(h).length})(l)||Object.assign(d,ds(t,d)),d.duration&&(d.duration=c(d.duration)),d.repeatDelay&&(d.repeatDelay=c(d.repeatDelay)),void 0!==d.from&&(d.keyframes[0]=d.from);let p=!1;if((!1===d.type||0===d.duration&&!d.repeatDelay)&&(an(d),0===d.delay&&(p=!0)),(n.instantAnimations||n.skipAnimations)&&(p=!0,an(d),d.delay=0),d.allowFlatten=!l.type&&!l.ease,p&&!a&&void 0!==e.get()){const t=function(t,{repeat:e,repeatType:n="loop"},s){const i=t.filter(ls),r=e&&"loop"!==n&&e%2==1?0:i.length-1;return r&&void 0!==s?s:i[r]}(d.keyframes,l);if(void 0!==t)return void B.update(()=>{d.onUpdate(t),d.onComplete()})}return l.isSync?new Te(d):new un(d)};function ms({protectedKeys:t,needsAnimating:e},n){const s=t.hasOwnProperty(n)&&!0!==e[n];return e[n]=!1,s}function fs(t,e,{delay:n=0,transitionOverride:s,type:i}={}){let{transition:r=t.getDefaultTransition(),transitionEnd:a,...o}=e;s&&(r=s);const l=[],u=i&&t.animationState&&t.animationState.getState()[i];for(const e in o){const s=t.getValue(e,t.latestValues[e]??null),i=o[e];if(void 0===i||u&&ms(u,e))continue;const a={delay:n,...mn(r||{},e)},h=s.get();if(void 0!==h&&!s.isAnimating&&!Array.isArray(i)&&i===h&&!a.velocity)continue;let c=!1;if(window.MotionHandoffAnimation){const n=os(t);if(n){const t=window.MotionHandoffAnimation(n,e,B);null!==t&&(a.startTime=t,c=!0)}}is(t,e),s.start(ps(e,s,i,t.shouldReduceMotion&&fn.has(e)?{type:!1}:a,t,c));const d=s.animation;d&&l.push(d)}return a&&Promise.all(l).then(()=>{B.update(()=>{a&&ss(t,a)})}),l}const ys={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},gs={};for(const t in ys)gs[t]={isEnabled:e=>ys[t].some(t=>!!e[t])};const vs=()=>({x:{min:0,max:0},y:{min:0,max:0}}),bs="undefined"!=typeof window,ws={current:null},Ts={current:!1};const Ms=["initial","animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"];function Vs(t){return null!==(e=t.animate)&&"object"==typeof e&&"function"==typeof e.start||Ms.some(e=>function(t){return"string"==typeof t||Array.isArray(t)}(t[e]));var e}const As=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Ss{scrapeMotionValuesFromProps(t,e,n){return{}}constructor({parent:t,props:e,presenceContext:n,reducedMotionConfig:s,blockInitialAnimation:i,visualState:r},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Ue,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const t=$.now();this.renderScheduledAtthis.bindToMotionValue(e,t)),Ts.current||function(){if(Ts.current=!0,bs)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>ws.current=t.matches;t.addEventListener("change",e),e()}else ws.current=!1}(),this.shouldReduceMotion="never"!==this.reducedMotionConfig&&("always"===this.reducedMotionConfig||ws.current),this.parent?.addChild(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),N(this.notifyUpdate),N(this.render),this.valueSubscriptions.forEach(t=>t()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const t in this.events)this.events[t].clear();for(const t in this.features){const e=this.features[t];e&&(e.unmount(),e.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,e){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const n=De.has(t);n&&this.onBindTransform&&this.onBindTransform();const s=e.on("change",e=>{this.latestValues[t]=e,this.props.onUpdate&&B.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let i;window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,t,e)),this.valueSubscriptions.set(t,()=>{s(),i&&i(),e.owner&&e.stop()})}sortNodePosition(t){return this.current&&this.sortInstanceNodePosition&&this.type===t.type?this.sortInstanceNodePosition(this.current,t.current):0}updateFeatures(){let t="animation";for(t in gs){const e=gs[t];if(!e)continue;const{isEnabled:n,Feature:s}=e;if(!this.features[t]&&s&&n(this.props)&&(this.features[t]=new s(this)),this.features[t]){const e=this.features[t];e.isMounted?e.update():(e.mount(),e.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):{x:{min:0,max:0},y:{min:0,max:0}}}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,e){this.latestValues[t]=e}update(t,e){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=e;for(let e=0;ee.variantChildren.delete(t)}addValue(t,e){const n=this.values.get(t);e!==n&&(n&&this.removeValue(t),this.bindToMotionValue(t,e),this.values.set(t,e),this.latestValues[t]=e.get())}removeValue(t){this.values.delete(t);const e=this.valueSubscriptions.get(t);e&&(e(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,e){if(this.props.values&&this.props.values[t])return this.props.values[t];let n=this.values.get(t);return void 0===n&&void 0!==e&&(n=Dn(null===e?void 0:e,{owner:this}),this.addValue(t,n)),n}readValue(t,e){let n=void 0===this.latestValues[t]&&this.current?this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options):this.latestValues[t];var r;return null!=n&&("string"==typeof n&&(s(n)||i(n))?n=parseFloat(n):(r=n,!Kn.find(yn(r))&&Mt.test(e)&&(n=Cn(t,e))),this.setBaseTarget(t,Nn(n)?n.get():n)),Nn(n)?n.get():n}setBaseTarget(t,e){this.baseTarget[t]=e}getBaseTarget(t){const{initial:e}=this.props;let n;if("string"==typeof e||"object"==typeof e){const s=ts(this.props,e,this.presenceContext?.custom);s&&(n=s[t])}if(e&&void 0!==n)return n;const s=this.getBaseTargetFromProps(this.props,t);return void 0===s||Nn(s)?void 0!==this.initialValues[t]&&void 0===n?void 0:this.baseTarget[t]:s}on(t,e){return this.events[t]||(this.events[t]=new h),this.events[t].add(e)}notify(t,...e){this.events[t]&&this.events[t].notify(...e)}scheduleRenderMicrotask(){In.render(this.render)}}class xs extends Ss{constructor(){super(...arguments),this.KeyframeResolver=Pn}sortInstanceNodePosition(t,e){return 2&t.compareDocumentPosition(e)?1:-1}getBaseTargetFromProps(t,e){return t.style?t.style[e]:void 0}removeValueFromRenderState(t,{vars:e,style:n}){delete e[t],delete n[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;Nn(t)&&(this.childSubscription=t.on("change",t=>{this.current&&(this.current.textContent=`${t}`)}))}}const ks={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Cs=Oe.length;function Fs(t,e,n){const{style:s,vars:i,transformOrigin:r}=t;let a=!1,o=!1;for(const t in e){const n=e[t];if(De.has(t))a=!0;else if(U(t))i[t]=n;else{const e=En(n,Sn[t]);t.startsWith("origin")?(o=!0,r[t]=e):s[t]=e}}if(e.transform||(a||n?s.transform=function(t,e,n){let s="",i=!0;for(let r=0;r{const{transform:n="none"}=getComputedStyle(t);return Pe(n,e)})(t,e);{const s=(n=t,window.getComputedStyle(n)),i=(U(e)?s.getPropertyValue(e):s[e])||0;return"string"==typeof i?i.trim():i}var n}measureInstanceViewportBox(t,{transformPagePoint:e}){return function(t,e){return function({top:t,left:e,right:n,bottom:s}){return{x:{min:e,max:n},y:{min:t,max:s}}}(function(t,e){if(!e)return t;const n=e({x:t.left,y:t.top}),s=e({x:t.right,y:t.bottom});return{top:n.y,left:n.x,bottom:s.y,right:s.x}}(t.getBoundingClientRect(),e))}(t,e)}build(t,e,n){Fs(t,e,n.transformTemplate)}scrapeMotionValuesFromProps(t,e,n){return Ds(t,e,n)}}class Rs extends Ss{constructor(){super(...arguments),this.type="object"}readValueFromInstance(t,e){if(function(t,e){return t in e}(e,t)){const n=t[e];if("string"==typeof n||"number"==typeof n)return n}}getBaseTargetFromProps(){}removeValueFromRenderState(t,e){delete e.output[t]}measureInstanceViewportBox(){return{x:{min:0,max:0},y:{min:0,max:0}}}build(t,e){Object.assign(t.output,e)}renderInstance(t,{output:e}){Object.assign(t,e)}sortInstanceNodePosition(){return 0}}const Bs={offset:"stroke-dashoffset",array:"stroke-dasharray"},Ns={offset:"strokeDashoffset",array:"strokeDasharray"};function Ks(t,{attrX:e,attrY:n,attrScale:s,pathLength:i,pathSpacing:r=1,pathOffset:a=0,...o},l,u,h){if(Fs(t,o,u),l)return void(t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox));t.attrs=t.style,t.style={};const{attrs:c,style:d}=t;c.transform&&(d.transform=c.transform,delete c.transform),(d.transform||c.transformOrigin)&&(d.transformOrigin=c.transformOrigin??"50% 50%",delete c.transformOrigin),d.transform&&(d.transformBox=h?.transformBox??"fill-box",delete c.transformBox),void 0!==e&&(c.x=e),void 0!==n&&(c.y=n),void 0!==s&&(c.scale=s),void 0!==i&&function(t,e,n=1,s=0,i=!0){t.pathLength=1;const r=i?Bs:Ns;t[r.offset]=lt.transform(-s);const a=lt.transform(e),o=lt.transform(n);t[r.array]=`${a} ${o}`}(c,i,r,a,!1)}const js=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);class Ws extends xs{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=vs}getBaseTargetFromProps(t,e){return t[e]}readValueFromInstance(t,e){if(De.has(e)){const t=kn(e);return t&&t.default||0}return e=js.has(e)?e:rs(e),t.getAttribute(e)}scrapeMotionValuesFromProps(t,e,n){return function(t,e,n){const s=Ds(t,e,n);for(const n in t)(Nn(t[n])||Nn(e[n]))&&(s[-1!==Oe.indexOf(n)?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n]=t[n]);return s}(t,e,n)}build(t,e,n){Ks(t,e,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(t,e,n,s){!function(t,e,n,s){Ps(t,e,void 0,s);for(const n in e.attrs)t.setAttribute(js.has(n)?n:rs(n),e.attrs[n])}(t,e,0,s)}mount(t){var e;this.isSVGTag="string"==typeof(e=t.tagName)&&"svg"===e.toLowerCase(),super.mount(t)}}function Ys(t){const e={presenceContext:null,props:{},visualState:{renderState:{transform:{},transformOrigin:{},style:{},vars:{},attrs:{}},latestValues:{}}},n=Bn(t)&&!function(t){return Bn(t)&&"svg"===t.tagName}(t)?new Ws(e):new Is(e);n.mount(t),Jn.set(t,n)}function $s(t){const e=new Rs({presenceContext:null,props:{},visualState:{renderState:{output:{}},latestValues:{}}});e.mount(t),Jn.set(t,e)}function Ls(t,e,n,s){const i=[];if(function(t,e){return Nn(t)||"number"==typeof t||"string"==typeof t&&!jn(e)}(t,e))i.push(function(t,e,n){const s=Nn(t)?t:Dn(t);return s.start(ps("",s,e,n)),s.animation}(t,jn(e)&&e.default||e,n&&n.default||n));else{const r=Wn(t,e,s),a=r.length;for(let t=0;t{const l=Zn(t),{delay:u=0,times:h=pe(l),type:d="keyframes",repeat:f,repeatType:y,repeatDelay:v=0,...b}=n;let{ease:w=e.ease||"easeOut",duration:T}=n;const M="function"==typeof u?u(a,o):u,V=l.length,A=Qe(d)?d:i?.[d||"keyframes"];if(V<=2&&A){let t=100;if(2===V&&Gn(l)){const e=l[1]-l[0];t=Math.abs(e)}const e={...b};void 0!==T&&(e.duration=c(T));const n=Yt(e,t,A);w=n.ease,T=n.duration}T??(T=r);const S=p+M;1===h.length&&0===h[0]&&(h[1]=1);const x=h.length-l.length;if(x>0&&de(h,x),1===l.length&&l.unshift(null),f){T=Yn(T,f);const t=[...l],e=[...h];w=Array.isArray(w)?[...w]:[w];const n=[...w];for(let s=0;s{for(const i in t){const r=t[i];r.sort(Xn);const o=[],l=[],h=[];for(let t=0;t{s.push(...Ls(n,t,e))}),s}function Xs(e){return function(n,s,i){let r=[];var a;a=n,r=Array.isArray(a)&&a.some(Array.isArray)?Us(n,s,e):Ls(n,s,i,e);const o=new cn(r);return e&&(e.animations.push(o),o.finished.then(()=>{t(e.animations,o)})),o}}const qs=Xs();export{qs as animate,Xs as createScopedAnimate}; diff --git a/frontend/node_modules/framer-motion/dist/size-rollup-dom-animation-assets.js b/frontend/node_modules/framer-motion/dist/size-rollup-dom-animation-assets.js new file mode 100644 index 0000000000000000000000000000000000000000..a6d762bb7df170efe9d86d695c27702149659367 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/size-rollup-dom-animation-assets.js @@ -0,0 +1 @@ +const t=(t,r,a)=>a>r?r:aa(t[r]))}function n(t){return Boolean(s(t)||t.variants)}const i=t=>r=>"string"==typeof r&&r.startsWith(t),f=i("--"),l=i("var(--"),c=t=>!!l(t)&&d.test(t.split("/*")[0].trim()),d=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,p={test:t=>"number"==typeof t,parse:parseFloat,transform:t=>t},m={...p,transform:r=>t(0,1,r)},u={...p,default:1},g=t=>({test:r=>"string"==typeof r&&r.endsWith(t)&&1===r.split(" ").length,parse:parseFloat,transform:r=>`${r}${t}`}),h=g("deg"),y=g("%"),v=g("px"),w=g("vh"),x=g("vw"),b=(()=>({...y,parse:t=>y.parse(t)/100,transform:t=>y.transform(100*t)}))(),k=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],B=(()=>new Set(k))(),X={...p,transform:Math.round},Y={borderWidth:v,borderTopWidth:v,borderRightWidth:v,borderBottomWidth:v,borderLeftWidth:v,borderRadius:v,radius:v,borderTopLeftRadius:v,borderTopRightRadius:v,borderBottomRightRadius:v,borderBottomLeftRadius:v,width:v,maxWidth:v,height:v,maxHeight:v,top:v,right:v,bottom:v,left:v,padding:v,paddingTop:v,paddingRight:v,paddingBottom:v,paddingLeft:v,margin:v,marginTop:v,marginRight:v,marginBottom:v,marginLeft:v,backgroundPositionX:v,backgroundPositionY:v,...{rotate:h,rotateX:h,rotateY:h,rotateZ:h,scale:u,scaleX:u,scaleY:u,scaleZ:u,skew:h,skewX:h,skewY:h,distance:v,translateX:v,translateY:v,translateZ:v,x:v,y:v,z:v,perspective:v,transformPerspective:v,opacity:m,originX:b,originY:b,originZ:v},zIndex:X,fillOpacity:m,strokeOpacity:m,numOctaves:X},O=(t,r)=>r&&"number"==typeof t?r.transform(t):t,$=t=>Boolean(t&&t.getVelocity),T={};function W(t,{layout:r,layoutId:a}){return B.has(t)||t.startsWith("origin")||(r||void 0!==a)&&(!!T[t]||"opacity"===t)}const L={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},R=k.length;function Z(t,r,a){const{style:e,vars:o,transformOrigin:s}=t;let n=!1,i=!1;for(const t in r){const a=r[t];if(B.has(t))n=!0;else if(f(t))o[t]=a;else{const r=O(a,Y[t]);t.startsWith("origin")?(i=!0,s[t]=r):e[t]=r}}if(r.transform||(n||a?e.transform=function(t,r,a){let e="",o=!0;for(let s=0;s"string"==typeof t&&"svg"===t.toLowerCase(),F=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function I(t){return"string"==typeof t&&!t.includes("-")&&!!(F.indexOf(t)>-1||/[A-Z]/u.test(t))}function z(t){const r=[{},{}];return t?.values.forEach((t,a)=>{r[0][a]=t.get(),r[1][a]=t.getVelocity()}),r}function C(t,r,a,e){if("function"==typeof r){const[o,s]=z(e);r=r(void 0!==a?a:t.custom,o,s)}if("string"==typeof r&&(r=t.variants&&t.variants[r]),"function"==typeof r){const[o,s]=z(e);r=r(void 0!==a?a:t.custom,o,s)}return r}function E(t,r,a){const{style:e}=t,o={};for(const s in e)($(e[s])||r.style&&$(r.style[s])||W(s,t)||void 0!==a?.getValue(s)?.liveStyle)&&(o[s]=e[s]);return o}function H(t,r,a){const e=E(t,r,a);for(const a in t)if($(t[a])||$(r[a])){e[-1!==k.indexOf(a)?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a]=t[a]}return e}const D="undefined"!=typeof window,j={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},q={};for(const t in j)q[t]={isEnabled:r=>j[t].some(t=>!!r[t])};const M=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),U="data-"+M("framerAppearId");export{Y as A,B,o as C,e as D,f as E,M as F,a,$ as b,W as c,Z as d,V as e,A as f,I as g,n as h,s as i,r as j,H as k,q as l,D as m,p as n,U as o,m as p,t as q,C as r,E as s,y as t,c as u,v,k as w,h as x,x as y,w as z}; diff --git a/frontend/node_modules/framer-motion/dist/size-rollup-dom-animation-m.js b/frontend/node_modules/framer-motion/dist/size-rollup-dom-animation-m.js new file mode 100644 index 0000000000000000000000000000000000000000..4ab8cc16937bce7e79f7d7eb6ca73888646ea1b2 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/size-rollup-dom-animation-m.js @@ -0,0 +1 @@ +import{jsxs as t,jsx as n}from"react/jsx-runtime";import{createContext as o,useContext as r,useMemo as e,Fragment as a,createElement as i,useRef as s,useCallback as u,useLayoutEffect as c,useEffect as l,useInsertionEffect as d,forwardRef as f}from"react";import{i as m,a as p,b as y,c as g,d as v,e as h,f as S,g as M,P as b,r as w,h as j,j as C,k as E,s as P,l as A,m as T,n as L,o as W,S as x,p as I,L as k}from"./size-rollup-dom-max-assets.js";const O=o({strict:!1}),V=o({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"}),D=o({});function R(t){const{initial:n,animate:o}=function(t,n){if(m(t)){const{initial:n,animate:o}=t;return{initial:!1===n||p(n)?n:void 0,animate:p(o)?o:void 0}}return!1!==t.inherit?n:{}}(t,r(D));return e(()=>({initial:n,animate:o}),[H(n),H(o)])}function H(t){return Array.isArray(t)?t.join(" "):t}const N=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function F(t,n,o){for(const r in n)y(n[r])||g(r,o)||(t[r]=n[r])}function B(t,n){const o={};return F(o,t.style||{},t),Object.assign(o,function({transformTemplate:t},n){return e(()=>{const o={style:{},transform:{},transformOrigin:{},vars:{}};return v(o,n,t),Object.assign({},o.vars,o.style)},[n])}(t,n)),o}function q(t,n){const o={},r=B(t,n);return t.drag&&!1!==t.dragListener&&(o.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout="none",r.touchAction=!0===t.drag?"none":"pan-"+("x"===t.drag?"y":"x")),void 0===t.tabIndex&&(t.onTap||t.onTapStart||t.whileTap)&&(o.tabIndex=0),o.style=r,o}const U=()=>({style:{},transform:{},transformOrigin:{},vars:{},attrs:{}});function $(t,n,o,r){const a=e(()=>{const o={style:{},transform:{},transformOrigin:{},vars:{},attrs:{}};return h(o,n,S(r),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[n]);if(t.style){const n={};F(n,t.style,t),a.style={...n,...a.style}}return a}const _=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function z(t){return t.startsWith("while")||t.startsWith("drag")&&"draggable"!==t||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||_.has(t)}let X=t=>!z(t);try{"function"==typeof(Y=require("@emotion/is-prop-valid").default)&&(X=t=>t.startsWith("on")?!z(t):Y(t))}catch{}var Y;function G(t,n,o,{latestValues:r},s,u=!1){const c=(M(t)?$:q)(n,r,s,t),l=function(t,n,o){const r={};for(const e in t)"values"===e&&"object"==typeof t.values||(X(e)||!0===o&&z(e)||!n&&!z(e)||t.draggable&&e.startsWith("onDrag"))&&(r[e]=t[e]);return r}(n,"string"==typeof t,u),d=t!==a?{...l,...c,ref:o}:{},{children:f}=n,m=e(()=>y(f)?f.get():f,[f]);return i(t,{...d,children:m})}function J(t,n,o,r){const e={},a=r(t,{});for(const t in a)e[t]=w(a[t]);let{initial:i,animate:s}=t;const u=m(t),c=j(t);n&&c&&!u&&!1!==t.inherit&&(void 0===i&&(i=n.initial),void 0===s&&(s=n.animate));let l=!!o&&!1===o.initial;l=l||!1===i;const d=l?s:i;if(d&&"boolean"!=typeof d&&!C(d)){const n=Array.isArray(d)?d:[d];for(let o=0;o(n,o)=>{const e=r(D),a=r(b),i=()=>function({scrapeMotionValuesFromProps:t,createRenderState:n},o,r,e){return{latestValues:J(o,r,e,t),renderState:n()}}(t,n,e,a);return o?i():function(t){const n=s(null);return null===n.current&&(n.current=t()),n.current}(i)},Q=K({scrapeMotionValuesFromProps:P,createRenderState:N}),Z=K({scrapeMotionValuesFromProps:A,createRenderState:U});const tt=Symbol.for("motionComponentSymbol");function nt(t,n,o){return u(r=>{r&&t.onMount&&t.onMount(r),n&&(r?n.mount(r):n.unmount()),o&&("function"==typeof o?o(r):L(o)&&(o.current=r))},[n])}const ot=W?c:l;function rt(t,n,o,e,a){const{visualElement:i}=r(D),u=r(O),c=r(b),f=r(V).reducedMotion,m=s(null);e=e||u.renderer,!m.current&&e&&(m.current=e(t,{visualState:n,parent:i,props:o,presenceContext:c,blockInitialAnimation:!!c&&!1===c.initial,reducedMotionConfig:f}));const p=m.current,y=r(x);!p||p.projection||!a||"html"!==p.type&&"svg"!==p.type||function(t,n,o,r){const{layoutId:e,layout:a,drag:i,dragConstraints:s,layoutScroll:u,layoutRoot:c,layoutCrossfade:l}=n;t.projection=new o(t.latestValues,n["data-framer-portal-id"]?void 0:et(t.parent)),t.projection.setOptions({layoutId:e,layout:a,alwaysMeasureLayout:Boolean(i)||s&&L(s),visualElement:t,animationType:"string"==typeof a?a:"both",initialPromotionConfig:r,crossfade:l,layoutScroll:u,layoutRoot:c})}(m.current,o,a,y);const g=s(!1);d(()=>{p&&g.current&&p.update(o,c)});const v=o[I],h=s(Boolean(v)&&!window.MotionHandoffIsComplete?.(v)&&window.MotionHasOptimisedAnimation?.(v));return ot(()=>{p&&(g.current=!0,window.MotionIsMounted=!0,p.updateFeatures(),p.scheduleRenderMicrotask(),h.current&&p.animationState&&p.animationState.animateChanges())}),l(()=>{p&&(!h.current&&p.animationState&&p.animationState.animateChanges(),h.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(v)}),h.current=!1),p.enteringChildren=void 0)}),p}function et(t){if(t)return!1!==t.options.allowProjection?t.projection:et(t.parent)}function at(o,{forwardMotionProps:e=!1}={},a,i){a&&function(t){for(const n in t)T[n]={...T[n],...t[n]}}(a);const s=M(o)?Z:Q;function u(a,u){let c;const l={...r(V),...a,layoutId:it(a)},{isStatic:d}=l,f=R(a),m=s(a,d);if(!d&&W){r(O).strict;const t=function(t){const{drag:n,layout:o}=T;if(!n&&!o)return{};const r={...n,...o};return{MeasureLayout:n?.isEnabled(t)||o?.isEnabled(t)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}(l);c=t.MeasureLayout,f.visualElement=rt(o,m,l,i,t.ProjectionNode)}return t(D.Provider,{value:f,children:[c&&f.visualElement?n(c,{visualElement:f.visualElement,...l}):null,G(o,a,nt(m,f.visualElement,u),m,d,e)]})}u.displayName=`motion.${"string"==typeof o?o:`create(${o.displayName??o.name??""})`}`;const c=f(u);return c[tt]=o,c}function it({layoutId:t}){const n=r(k).id;return n&&void 0!==t?n+"-"+t:t}function st(t,n){return at(t,n)}const ut=st("div");export{ut as MotionDiv}; diff --git a/frontend/node_modules/framer-motion/dist/size-rollup-dom-animation.js b/frontend/node_modules/framer-motion/dist/size-rollup-dom-animation.js new file mode 100644 index 0000000000000000000000000000000000000000..6c6318bc8d39fd55ba4b59d30c1695a405fb3b60 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/size-rollup-dom-animation.js @@ -0,0 +1 @@ +import{n as t,p as e,q as n,t as s,u as i,v as r,w as o,x as a,y as u,z as l,A as h,r as c,b as d,o as p,B as m,a as f,C as y,j as v,D as g,m as b,i as w,h as T,l as S,E as A,d as M,s as V,F as x,k as C,e as k,f as P,g as E}from"./size-rollup-dom-animation-assets.js";import{Fragment as F}from"react";const O={},D=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);const I=t=>/^0[^.\s]+$/u.test(t);function R(t){let e;return()=>(void 0===e&&(e=t()),e)}const N=t=>t,K=(t,e)=>n=>e(t(n)),B=(...t)=>t.reduce(K),L=(t,e,n)=>{const s=e-t;return 0===s?1:(n-t)/s};class j{constructor(){this.subscriptions=[]}add(t){var e,n;return e=this.subscriptions,n=t,-1===e.indexOf(n)&&e.push(n),()=>function(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}(this.subscriptions,t)}notify(t,e,n){const s=this.subscriptions.length;if(s)if(1===s)this.subscriptions[0](t,e,n);else for(let i=0;i1e3*t,q=t=>t/1e3;function W(t,e){return e?t*(1e3/e):0}const Y=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t;function $(t,e,n,s){if(t===e&&n===s)return N;const i=e=>function(t,e,n,s,i){let r,o,a=0;do{o=e+(n-e)/2,r=Y(o,s,i)-t,r>0?n=o:e=o}while(Math.abs(r)>1e-7&&++a<12);return o}(e,0,1,t,n);return t=>0===t||1===t?t:Y(i(t),e,s)}const z=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,H=t=>e=>1-t(1-e),X=$(.33,1.53,.69,.99),_=H(X),G=z(_),Z=t=>(t*=2)<1?.5*_(t):.5*(2-Math.pow(2,-10*(t-1))),J=t=>1-Math.sin(Math.acos(t)),Q=H(J),tt=z(J),et=$(.42,0,1,1),nt=$(0,0,.58,1),st=$(.42,0,.58,1),it=t=>Array.isArray(t)&&"number"==typeof t[0],rt={linear:N,easeIn:et,easeInOut:st,easeOut:nt,circIn:J,circInOut:tt,circOut:Q,backIn:_,backInOut:G,backOut:X,anticipate:Z},ot=t=>{if(it(t)){t.length;const[e,n,s,i]=t;return $(e,n,s,i)}return"string"==typeof t?rt[t]:t},at=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],ut={value:null,addProjectionMetrics:null};function lt(t,e){let n=!1,s=!0;const i={delta:0,timestamp:0,isProcessing:!1},r=()=>n=!0,o=at.reduce((t,n)=>(t[n]=function(t,e){let n=new Set,s=new Set,i=!1,r=!1;const o=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},u=0;function l(e){o.has(e)&&(h.schedule(e),t()),u++,e(a)}const h={schedule:(t,e=!1,r=!1)=>{const a=r&&i?n:s;return e&&o.add(t),a.has(t)||a.add(t),t},cancel:t=>{s.delete(t),o.delete(t)},process:t=>{a=t,i?r=!0:(i=!0,[n,s]=[s,n],n.forEach(l),e&&ut.value&&ut.value.frameloop[e].push(u),u=0,n.clear(),i=!1,r&&(r=!1,h.process(t)))}};return h}(r,e?n:void 0),t),{}),{setup:a,read:u,resolveKeyframes:l,preUpdate:h,update:c,preRender:d,render:p,postRender:m}=o,f=()=>{const r=O.useManualTiming?i.timestamp:performance.now();n=!1,O.useManualTiming||(i.delta=s?1e3/60:Math.max(Math.min(r-i.timestamp,40),1)),i.timestamp=r,i.isProcessing=!0,a.process(i),u.process(i),l.process(i),h.process(i),c.process(i),d.process(i),p.process(i),m.process(i),i.isProcessing=!1,n&&e&&(s=!1,t(f))};return{schedule:at.reduce((e,r)=>{const a=o[r];return e[r]=(e,r=!1,o=!1)=>(n||(n=!0,s=!0,i.isProcessing||t(f)),a.schedule(e,r,o)),e},{}),cancel:t=>{for(let e=0;e(void 0===mt&&yt.set(dt.isProcessing||O.useManualTiming?dt.timestamp:performance.now()),mt),set:t=>{mt=t,queueMicrotask(ft)}},vt=t=>Math.round(1e5*t)/1e5,gt=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;const bt=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,wt=(t,e)=>n=>Boolean("string"==typeof n&&bt.test(n)&&n.startsWith(t)||e&&!function(t){return null==t}(n)&&Object.prototype.hasOwnProperty.call(n,e)),Tt=(t,e,n)=>s=>{if("string"!=typeof s)return s;const[i,r,o,a]=s.match(gt);return{[t]:parseFloat(i),[e]:parseFloat(r),[n]:parseFloat(o),alpha:void 0!==a?parseFloat(a):1}},St={...t,transform:t=>Math.round((t=>n(0,255,t))(t))},At={test:wt("rgb","red"),parse:Tt("red","green","blue"),transform:({red:t,green:n,blue:s,alpha:i=1})=>"rgba("+St.transform(t)+", "+St.transform(n)+", "+St.transform(s)+", "+vt(e.transform(i))+")"};const Mt={test:wt("#"),parse:function(t){let e="",n="",s="",i="";return t.length>5?(e=t.substring(1,3),n=t.substring(3,5),s=t.substring(5,7),i=t.substring(7,9)):(e=t.substring(1,2),n=t.substring(2,3),s=t.substring(3,4),i=t.substring(4,5),e+=e,n+=n,s+=s,i+=i),{red:parseInt(e,16),green:parseInt(n,16),blue:parseInt(s,16),alpha:i?parseInt(i,16)/255:1}},transform:At.transform},Vt={test:wt("hsl","hue"),parse:Tt("hue","saturation","lightness"),transform:({hue:t,saturation:n,lightness:i,alpha:r=1})=>"hsla("+Math.round(t)+", "+s.transform(vt(n))+", "+s.transform(vt(i))+", "+vt(e.transform(r))+")"},xt={test:t=>At.test(t)||Mt.test(t)||Vt.test(t),parse:t=>At.test(t)?At.parse(t):Vt.test(t)?Vt.parse(t):Mt.parse(t),transform:t=>"string"==typeof t?t:t.hasOwnProperty("red")?At.transform(t):Vt.transform(t),getAnimatableNone:t=>{const e=xt.parse(t);return e.alpha=0,xt.transform(e)}},Ct=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;const kt="number",Pt="color",Et=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function Ft(t){const e=t.toString(),n=[],s={color:[],number:[],var:[]},i=[];let r=0;const o=e.replace(Et,t=>(xt.test(t)?(s.color.push(r),i.push(Pt),n.push(xt.parse(t))):t.startsWith("var(")?(s.var.push(r),i.push("var"),n.push(t)):(s.number.push(r),i.push(kt),n.push(parseFloat(t))),++r,"${}")).split("${}");return{values:n,split:o,indexes:s,types:i}}function Ot(t){return Ft(t).values}function Dt(t){const{split:e,types:n}=Ft(t),s=e.length;return t=>{let i="";for(let r=0;r"number"==typeof t?0:xt.test(t)?xt.getAnimatableNone(t):t;const Rt={test:function(t){return isNaN(t)&&"string"==typeof t&&(t.match(gt)?.length||0)+(t.match(Ct)?.length||0)>0},parse:Ot,createTransformer:Dt,getAnimatableNone:function(t){const e=Ot(t);return Dt(t)(e.map(It))}};function Nt(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<.5?e:n<2/3?t+(e-t)*(2/3-n)*6:t}function Kt(t,e){return n=>n>0?e:t}const Bt=(t,e,n)=>t+(e-t)*n,Lt=(t,e,n)=>{const s=t*t,i=n*(e*e-s)+s;return i<0?0:Math.sqrt(i)},jt=[Mt,At,Vt];function Ut(t){const e=(n=t,jt.find(t=>t.test(n)));var n;if(!Boolean(e))return!1;let s=e.parse(t);return e===Vt&&(s=function({hue:t,saturation:e,lightness:n,alpha:s}){t/=360,n/=100;let i=0,r=0,o=0;if(e/=100){const s=n<.5?n*(1+e):n+e-n*e,a=2*n-s;i=Nt(a,s,t+1/3),r=Nt(a,s,t),o=Nt(a,s,t-1/3)}else i=r=o=n;return{red:Math.round(255*i),green:Math.round(255*r),blue:Math.round(255*o),alpha:s}}(s)),s}const qt=(t,e)=>{const n=Ut(t),s=Ut(e);if(!n||!s)return Kt(t,e);const i={...n};return t=>(i.red=Lt(n.red,s.red,t),i.green=Lt(n.green,s.green,t),i.blue=Lt(n.blue,s.blue,t),i.alpha=Bt(n.alpha,s.alpha,t),At.transform(i))},Wt=new Set(["none","hidden"]);function Yt(t,e){return n=>Bt(t,e,n)}function $t(t){return"number"==typeof t?Yt:"string"==typeof t?i(t)?Kt:xt.test(t)?qt:Xt:Array.isArray(t)?zt:"object"==typeof t?xt.test(t)?qt:Ht:Kt}function zt(t,e){const n=[...t],s=n.length,i=t.map((t,n)=>$t(t)(t,e[n]));return t=>{for(let e=0;e{for(const e in s)n[e]=s[e](t);return n}}const Xt=(t,e)=>{const n=Rt.createTransformer(e),s=Ft(t),i=Ft(e);return s.indexes.var.length===i.indexes.var.length&&s.indexes.color.length===i.indexes.color.length&&s.indexes.number.length>=i.indexes.number.length?Wt.has(t)&&!i.values.length||Wt.has(e)&&!s.values.length?function(t,e){return Wt.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}(t,e):B(zt(function(t,e){const n=[],s={color:0,var:0,number:0};for(let i=0;i{const e=({timestamp:e})=>t(e);return{start:(t=!0)=>ht.update(e,t),stop:()=>ct(e),now:()=>dt.isProcessing?dt.timestamp:yt.now()}},Zt=(t,e,n=10)=>{let s="";const i=Math.max(Math.round(e/n),2);for(let e=0;e=Jt?1/0:e}function te(t,e,n){const s=Math.max(e-5,0);return W(n-t(s),e-s)}const ee=100,ne=10,se=1,ie=0,re=800,oe=.3,ae=.3,ue={granular:.01,default:2},le={granular:.005,default:.5},he=.01,ce=10,de=.05,pe=1,me=.001;function fe({duration:t=re,bounce:e=oe,velocity:s=ie,mass:i=se}){let r,o,a=1-e;a=n(de,pe,a),t=n(he,ce,q(t)),a<1?(r=e=>{const n=e*a,i=n*t,r=n-s,o=ve(e,a),u=Math.exp(-i);return me-r/o*u},o=e=>{const n=e*a*t,i=n*s+s,o=Math.pow(a,2)*Math.pow(e,2)*t,u=Math.exp(-n),l=ve(Math.pow(e,2),a);return(-r(e)+me>0?-1:1)*((i-o)*u)/l}):(r=e=>Math.exp(-e*t)*((e-s)*t+1)-.001,o=e=>Math.exp(-e*t)*(t*t*(s-e)));const u=function(t,e,n){let s=n;for(let n=1;nvoid 0!==t[e])}function Te(t=ae,e=oe){const s="object"!=typeof t?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:i,restDelta:r}=s;const o=s.keyframes[0],a=s.keyframes[s.keyframes.length-1],u={done:!1,value:o},{stiffness:l,damping:h,mass:c,duration:d,velocity:p,isResolvedFromDuration:m}=function(t){let e={velocity:ie,stiffness:ee,damping:ne,mass:se,isResolvedFromDuration:!1,...t};if(!we(t,be)&&we(t,ge))if(t.visualDuration){const s=t.visualDuration,i=2*Math.PI/(1.2*s),r=i*i,o=2*n(.05,1,1-(t.bounce||0))*Math.sqrt(r);e={...e,mass:se,stiffness:r,damping:o}}else{const n=fe(t);e={...e,...n,mass:se},e.isResolvedFromDuration=!0}return e}({...s,velocity:-q(s.velocity||0)}),f=p||0,y=h/(2*Math.sqrt(l*c)),v=a-o,g=q(Math.sqrt(l/c)),b=Math.abs(v)<5;let w;if(i||(i=b?ue.granular:ue.default),r||(r=b?le.granular:le.default),y<1){const t=ve(g,y);w=e=>{const n=Math.exp(-y*g*e);return a-n*((f+y*g*v)/t*Math.sin(t*e)+v*Math.cos(t*e))}}else if(1===y)w=t=>a-Math.exp(-g*t)*(v+(f+g*v)*t);else{const t=g*Math.sqrt(y*y-1);w=e=>{const n=Math.exp(-y*g*e),s=Math.min(t*e,300);return a-n*((f+y*g*v)*Math.sinh(s)+t*v*Math.cosh(s))/t}}const T={calculatedDuration:m&&d||null,next:t=>{const e=w(t);if(m)u.done=t>=d;else{let n=0===t?f:0;y<1&&(n=0===t?U(f):te(w,t,e));const s=Math.abs(n)<=i,o=Math.abs(a-e)<=r;u.done=s&&o}return u.value=u.done?a:e,u},toString:()=>{const t=Math.min(Qt(T),Jt),e=Zt(e=>T.next(t*e).value,t,30);return t+"ms "+e},toTransition:()=>{}};return T}function Se({keyframes:t,velocity:e=0,power:n=.8,timeConstant:s=325,bounceDamping:i=10,bounceStiffness:r=500,modifyTarget:o,min:a,max:u,restDelta:l=.5,restSpeed:h}){const c=t[0],d={done:!1,value:c},p=t=>void 0===a?u:void 0===u||Math.abs(a-t)-m*Math.exp(-t/s),g=t=>y+v(t),b=t=>{const e=v(t),n=g(t);d.done=Math.abs(e)<=l,d.value=d.done?y:n};let w,T;const S=t=>{var e;(e=d.value,void 0!==a&&eu)&&(w=t,T=Te({keyframes:[d.value,p(d.value)],velocity:te(g,t,d.value),damping:i,stiffness:r,restDelta:l,restSpeed:h}))};return S(0),{calculatedDuration:null,next:t=>{let e=!1;return T||void 0!==w||(e=!0,b(t),S(t)),void 0!==w&&t>=w?T.next(t-w):(!e&&b(t),d)}}}function Ae(t,e,{clamp:s=!0,ease:i,mixer:r}={}){const o=t.length;if(e.length,1===o)return()=>e[0];if(2===o&&e[0]===e[1])return()=>e[1];const a=t[0]===t[1];t[0]>t[o-1]&&(t=[...t].reverse(),e=[...e].reverse());const u=function(t,e,n){const s=[],i=n||O.mix||_t,r=t.length-1;for(let n=0;n{if(a&&n1)for(;sh(n(t[0],t[o-1],e)):h}function Me(t){const e=[0];return function(t,e){const n=t[t.length-1];for(let s=1;s<=e;s++){const i=L(0,e,s);t.push(Bt(n,1,i))}}(e,t.length-1),e}function Ve({duration:t=300,keyframes:e,times:n,ease:s="easeInOut"}){const i=(t=>Array.isArray(t)&&"number"!=typeof t[0])(s)?s.map(ot):ot(s),r={done:!1,value:e[0]},o=function(t,e){return t.map(t=>t*e)}(n&&n.length===e.length?n:Me(e),t),a=Ae(o,e,{ease:Array.isArray(i)?i:(u=e,l=i,u.map(()=>l||st).splice(0,u.length-1))});var u,l;return{calculatedDuration:t,next:e=>(r.value=a(e),r.done=e>=t,r)}}Te.applyToOptions=t=>{const e=function(t,e=100,n){const s=n({...t,keyframes:[0,e]}),i=Math.min(Qt(s),Jt);return{type:"keyframes",ease:t=>s.next(i*t).value/e,duration:q(i)}}(t,100,Te);return t.ease=e.ease,t.duration=U(e.duration),t.type="keyframes",t};const xe=t=>null!==t;function Ce(t,{repeat:e,repeatType:n="loop"},s,i=1){const r=t.filter(xe),o=i<0||e&&"loop"!==n&&e%2==1?0:r.length-1;return o&&void 0!==s?s:r[o]}const ke={decay:Se,inertia:Se,tween:Ve,keyframes:Ve,spring:Te};function Pe(t){"string"==typeof t.type&&(t.type=ke[t.type])}class Ee{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,e){return this.finished.then(t,e)}}const Fe=t=>t/100;class Oe extends Ee{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:t}=this.options;t&&t.updatedAt!==yt.now()&&this.tick(yt.now()),this.isStopped=!0,"idle"!==this.state&&(this.teardown(),this.options.onStop?.())},this.options=t,this.initAnimation(),this.play(),!1===t.autoplay&&this.pause()}initAnimation(){const{options:t}=this;Pe(t);const{type:e=Ve,repeat:n=0,repeatDelay:s=0,repeatType:i,velocity:r=0}=t;let{keyframes:o}=t;const a=e||Ve;a!==Ve&&"number"!=typeof o[0]&&(this.mixKeyframes=B(Fe,_t(o[0],o[1])),o=[0,100]);const u=a({...t,keyframes:o});"mirror"===i&&(this.mirroredGenerator=a({...t,keyframes:[...o].reverse(),velocity:-r})),null===u.calculatedDuration&&(u.calculatedDuration=Qt(u));const{calculatedDuration:l}=u;this.calculatedDuration=l,this.resolvedDuration=l+s,this.totalDuration=this.resolvedDuration*(n+1)-s,this.generator=u}updateTime(t){const e=Math.round(t-this.startTime)*this.playbackSpeed;null!==this.holdTime?this.currentTime=this.holdTime:this.currentTime=e}tick(t,e=!1){const{generator:s,totalDuration:i,mixKeyframes:r,mirroredGenerator:o,resolvedDuration:a,calculatedDuration:u}=this;if(null===this.startTime)return s.next(0);const{delay:l=0,keyframes:h,repeat:c,repeatType:d,repeatDelay:p,type:m,onUpdate:f,finalKeyframe:y}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-i/this.speed,this.startTime)),e?this.currentTime=t:this.updateTime(t);const v=this.currentTime-l*(this.playbackSpeed>=0?1:-1),g=this.playbackSpeed>=0?v<0:v>i;this.currentTime=Math.max(v,0),"finished"===this.state&&null===this.holdTime&&(this.currentTime=i);let b=this.currentTime,w=s;if(c){const t=Math.min(this.currentTime,i)/a;let e=Math.floor(t),s=t%1;!s&&t>=1&&(s=1),1===s&&e--,e=Math.min(e,c+1);Boolean(e%2)&&("reverse"===d?(s=1-s,p&&(s-=p/a)):"mirror"===d&&(w=o)),b=n(0,1,s)*a}const T=g?{done:!1,value:h[0]}:w.next(b);r&&(T.value=r(T.value));let{done:S}=T;g||null===u||(S=this.playbackSpeed>=0?this.currentTime>=i:this.currentTime<=0);const A=null===this.holdTime&&("finished"===this.state||"running"===this.state&&S);return A&&m!==Se&&(T.value=Ce(h,this.options,y,this.speed)),f&&f(T.value),A&&this.finish(),T}then(t,e){return this.finished.then(t,e)}get duration(){return q(this.calculatedDuration)}get time(){return q(this.currentTime)}set time(t){t=U(t),this.currentTime=t,null===this.startTime||null!==this.holdTime||0===this.playbackSpeed?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime(yt.now());const e=this.playbackSpeed!==t;this.playbackSpeed=t,e&&(this.time=q(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=Gt,startTime:e}=this.options;this.driver||(this.driver=t(t=>this.tick(t))),this.options.onPlay?.();const n=this.driver.now();"finished"===this.state?(this.updateFinished(),this.startTime=n):null!==this.holdTime?this.startTime=n-this.holdTime:this.startTime||(this.startTime=e??n),"finished"===this.state&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(yt.now()),this.holdTime=this.currentTime}complete(){"running"!==this.state&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),t.observe(this)}}const De=t=>180*t/Math.PI,Ie=t=>{const e=De(Math.atan2(t[1],t[0]));return Ne(e)},Re={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Ie,rotateZ:Ie,skewX:t=>De(Math.atan(t[1])),skewY:t=>De(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Ne=t=>((t%=360)<0&&(t+=360),t),Ke=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Be=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Le={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Ke,scaleY:Be,scale:t=>(Ke(t)+Be(t))/2,rotateX:t=>Ne(De(Math.atan2(t[6],t[5]))),rotateY:t=>Ne(De(Math.atan2(-t[2],t[0]))),rotateZ:Ie,rotate:Ie,skewX:t=>De(Math.atan(t[4])),skewY:t=>De(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function je(t){return t.includes("scale")?1:0}function Ue(t,e){if(!t||"none"===t)return je(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,i;if(n)s=Le,i=n;else{const e=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=Re,i=e}if(!i)return je(e);const r=s[e],o=i[1].split(",").map(qe);return"function"==typeof r?r(o):o[r]}function qe(t){return parseFloat(t.trim())}const We=e=>e===t||e===r,Ye=new Set(["x","y","z"]),$e=o.filter(t=>!Ye.has(t));const ze={width:({x:t},{paddingLeft:e="0",paddingRight:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),height:({y:t},{paddingTop:e="0",paddingBottom:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>Ue(e,"x"),y:(t,{transform:e})=>Ue(e,"y")};ze.translateX=ze.x,ze.translateY=ze.y;const He=new Set;let Xe=!1,_e=!1,Ge=!1;function Ze(){if(_e){const t=Array.from(He).filter(t=>t.needsMeasurement),e=new Set(t.map(t=>t.element)),n=new Map;e.forEach(t=>{const e=function(t){const e=[];return $e.forEach(n=>{const s=t.getValue(n);void 0!==s&&(e.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),e}(t);e.length&&(n.set(t,e),t.render())}),t.forEach(t=>t.measureInitialState()),e.forEach(t=>{t.render();const e=n.get(t);e&&e.forEach(([e,n])=>{t.getValue(e)?.set(n)})}),t.forEach(t=>t.measureEndState()),t.forEach(t=>{void 0!==t.suspendedScrollY&&window.scrollTo(0,t.suspendedScrollY)})}_e=!1,Xe=!1,He.forEach(t=>t.complete(Ge)),He.clear()}function Je(){He.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(_e=!0)})}class Qe{constructor(t,e,n,s,i,r=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=e,this.name=n,this.motionValue=s,this.element=i,this.isAsync=r}scheduleResolve(){this.state="scheduled",this.isAsync?(He.add(this),Xe||(Xe=!0,ht.read(Je),ht.resolveKeyframes(Ze))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:e,element:n,motionValue:s}=this;if(null===t[0]){const i=s?.get(),r=t[t.length-1];if(void 0!==i)t[0]=i;else if(n&&e){const s=n.readValue(e,r);null!=s&&(t[0]=s)}void 0===t[0]&&(t[0]=r),s&&void 0===i&&s.set(t[0])}!function(t){for(let e=1;evoid 0!==window.ScrollTimeline),en={};function nn(t,e){const n=R(t);return()=>en[e]??n()}const sn=nn(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch(t){return!1}return!0},"linearEasing"),rn=([t,e,n,s])=>`cubic-bezier(${t}, ${e}, ${n}, ${s})`,on={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:rn([0,.65,.55,1]),circOut:rn([.55,0,1,.45]),backIn:rn([.31,.01,.66,-.59]),backOut:rn([.33,1.53,.69,.99])};function an(t,e){return t?"function"==typeof t?sn()?Zt(t,e):"ease-out":it(t)?rn(t):Array.isArray(t)?t.map(t=>an(t,e)||on.easeOut):on[t]:void 0}function un(t,e,n,{delay:s=0,duration:i=300,repeat:r=0,repeatType:o="loop",ease:a="easeOut",times:u}={},l=void 0){const h={[e]:n};u&&(h.offset=u);const c=an(a,i);Array.isArray(c)&&(h.easing=c);const d={delay:s,duration:i,easing:Array.isArray(c)?"linear":c,fill:"both",iterations:r+1,direction:"reverse"===o?"alternate":"normal"};l&&(d.pseudoElement=l);return t.animate(h,d)}function ln(t){return"function"==typeof t&&"applyToOptions"in t}class hn extends Ee{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:e,name:n,keyframes:s,pseudoElement:i,allowFlatten:r=!1,finalKeyframe:o,onComplete:a}=t;this.isPseudoElement=Boolean(i),this.allowFlatten=r,this.options=t,t.type;const u=function({type:t,...e}){return ln(t)&&sn()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}(t);this.animation=un(e,n,s,u,i),!1===u.autoplay&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const t=Ce(s,this.options,o,this.speed);this.updateMotionValue?this.updateMotionValue(t):function(t,e,n){(t=>t.startsWith("--"))(e)?t.style.setProperty(e,n):t.style[e]=n}(e,n,t),this.animation.cancel()}a?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),"finished"===this.state&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch(t){}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;"idle"!==t&&"finished"!==t&&(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming?.().duration||0;return q(Number(t))}get time(){return q(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=U(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return null!==this.finishedTime?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:e}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&tn()?(this.animation.timeline=t,N):e(this)}}const cn={anticipate:Z,backInOut:G,circInOut:tt};function dn(t){"string"==typeof t.ease&&t.ease in cn&&(t.ease=cn[t.ease])}class pn extends hn{constructor(t){dn(t),Pe(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:e,onUpdate:n,onComplete:s,element:i,...r}=this.options;if(!e)return;if(void 0!==t)return void e.set(t);const o=new Oe({...r,autoplay:!1}),a=U(this.finishedTime??this.time);e.setWithVelocity(o.sample(a-10).value,o.sample(a).value,10),o.stop()}}const mn=(t,e)=>"zIndex"!==e&&(!("number"!=typeof t&&!Array.isArray(t))||!("string"!=typeof t||!Rt.test(t)&&"0"!==t||t.startsWith("url(")));function fn(t){t.duration=0,t.type}const yn=new Set(["opacity","clipPath","filter","transform"]),vn=R(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));class gn extends Ee{constructor({autoplay:t=!0,delay:e=0,type:n="keyframes",repeat:s=0,repeatDelay:i=0,repeatType:r="loop",keyframes:o,name:a,motionValue:u,element:l,...h}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=yt.now();const c={autoplay:t,delay:e,type:n,repeat:s,repeatDelay:i,repeatType:r,name:a,motionValue:u,element:l,...h},d=l?.KeyframeResolver||Qe;this.keyframeResolver=new d(o,(t,e,n)=>this.onKeyframesResolved(t,e,c,!n),a,u,l),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,e,n,s){this.keyframeResolver=void 0;const{name:i,type:r,velocity:o,delay:a,isHandoff:u,onUpdate:l}=n;this.resolvedAt=yt.now(),function(t,e,n,s){const i=t[0];if(null===i)return!1;if("display"===e||"visibility"===e)return!0;const r=t[t.length-1],o=mn(i,e),a=mn(r,e);return!(!o||!a)&&(function(t){const e=t[0];if(1===t.length)return!0;for(let n=0;n40?this.resolvedAt:this.createdAt:void 0,finalKeyframe:e,...n,keyframes:t},c=!u&&function(t){const{motionValue:e,name:n,repeatDelay:s,repeatType:i,damping:r,type:o}=t,a=e?.owner?.current;if(!(a instanceof HTMLElement))return!1;const{onUpdate:u,transformTemplate:l}=e.owner.getProps();return vn()&&n&&yn.has(n)&&("transform"!==n||!l)&&!u&&!s&&"mirror"!==i&&0!==r&&"inertia"!==o}(h)?new pn({...h,element:h.motionValue.owner.current}):new Oe(h);c.finished.then(()=>this.notifyFinished()).catch(N),this.pendingTimeline&&(this.stopTimeline=c.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=c}get finished(){return this._animation?this.animation.finished:this._finished}then(t,e){return this.finished.finally(t).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),Ge=!0,Je(),Ze(),Ge=!1),this._animation}get duration(){return this.animation.duration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}const bn=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function wn(t,e,n=1){const[s,r]=function(t){const e=bn.exec(t);if(!e)return[,];const[,n,s,i]=e;return[`--${n??s}`,i]}(t);if(!s)return;const o=window.getComputedStyle(e).getPropertyValue(s);if(o){const t=o.trim();return D(t)?parseFloat(t):t}return i(r)?wn(r,e,n+1):r}function Tn(t,e){return t?.[e]??t?.default??t}const Sn=new Set(["width","height","top","left","right","bottom",...o]),An=t=>e=>e.test(t),Mn=[t,r,s,a,u,l,{test:t=>"auto"===t,parse:t=>t}],Vn=t=>Mn.find(An(t));function xn(t){return"number"==typeof t?0===t:null===t||("none"===t||"0"===t||I(t))}const Cn=new Set(["brightness","contrast","saturate","opacity"]);function kn(t){const[e,n]=t.slice(0,-1).split("(");if("drop-shadow"===e)return t;const[s]=n.match(gt)||[];if(!s)return t;const i=n.replace(s,"");let r=Cn.has(e)?1:0;return s!==n&&(r*=100),e+"("+r+i+")"}const Pn=/\b([a-z-]*)\(.*?\)/gu,En={...Rt,getAnimatableNone:t=>{const e=t.match(Pn);return e?e.map(kn).join(" "):t}},Fn={...h,color:xt,backgroundColor:xt,outlineColor:xt,fill:xt,stroke:xt,borderColor:xt,borderTopColor:xt,borderRightColor:xt,borderBottomColor:xt,borderLeftColor:xt,filter:En,WebkitFilter:En},On=t=>Fn[t];function Dn(t,e){let n=On(t);return n!==En&&(n=Rt),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const In=new Set(["auto","none","0"]);class Rn extends Qe{constructor(t,e,n,s,i){super(t,e,n,s,i,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:e,name:n}=this;if(!e||!e.current)return;super.readKeyframes();for(let n=0;n{t.getValue(e).set(n)}),this.resolveNoneKeyframes()}}class Nn{constructor(t,e={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=t=>{const e=yt.now();if(this.updatedAt!==e&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(t),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const t of this.dependents)t.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=e.owner}setCurrent(t){var e;this.current=t,this.updatedAt=yt.now(),null===this.canTrackVelocity&&void 0!==t&&(this.canTrackVelocity=(e=this.current,!isNaN(parseFloat(e))))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return this.on("change",t)}on(t,e){this.events[t]||(this.events[t]=new j);const n=this.events[t].add(e);return"change"===t?()=>{n(),ht.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,e){this.passiveEffect=t,this.stopPassiveEffect=e}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,e,n){this.set(e),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-n}jump(t,e=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,e&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=yt.now();if(!this.canTrackVelocity||void 0===this.prevFrameValue||t-this.updatedAt>30)return 0;const e=Math.min(this.updatedAt-this.prevUpdatedAt,30);return W(parseFloat(this.current)-parseFloat(this.prevFrameValue),e)}start(t){return this.stop(),new Promise(e=>{this.hasAnimated=!0,this.animation=t(e),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function Kn(t,e){return new Nn(t,e)}const{schedule:Bn,cancel:Ln}=lt(queueMicrotask,!1),jn=!1;function Un(){return jn}function qn(t,e){const n=function(t,e,n){if(t instanceof EventTarget)return[t];if("string"==typeof t){let s=document;e&&(s=e.current);const i=n?.[t]??s.querySelectorAll(t);return i?Array.from(i):[]}return Array.from(t)}(t),s=new AbortController;return[n,{passive:!0,...e,signal:s.signal},()=>s.abort()]}function Wn(t){return!("touch"===t.pointerType||Un())}const Yn=(t,e)=>!!e&&(t===e||Yn(t,e.parentElement)),$n=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);const zn=new WeakSet;function Hn(t){return e=>{"Enter"===e.key&&t(e)}}function Xn(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}function _n(t){return(t=>"mouse"===t.pointerType?"number"!=typeof t.button||t.button<=0:!1!==t.isPrimary)(t)&&!Un()}function Gn(t,e,n={}){const[s,i,r]=qn(t,n),o=t=>{const s=t.currentTarget;if(!_n(t))return;zn.add(s);const r=e(s,t),o=(t,e)=>{window.removeEventListener("pointerup",a),window.removeEventListener("pointercancel",u),zn.has(s)&&zn.delete(s),_n(t)&&"function"==typeof r&&r(t,{success:e})},a=t=>{o(t,s===window||s===document||n.useGlobalTarget||Yn(s,t.target))},u=t=>{o(t,!1)};window.addEventListener("pointerup",a,i),window.addEventListener("pointercancel",u,i)};return s.forEach(t=>{var e,s;(n.useGlobalTarget?window:t).addEventListener("pointerdown",o,i),"object"==typeof(s=e=t)&&null!==s&&"offsetHeight"in e&&(t.addEventListener("focus",t=>((t,e)=>{const n=t.currentTarget;if(!n)return;const s=Hn(()=>{if(zn.has(n))return;Xn(n,"down");const t=Hn(()=>{Xn(n,"up")});n.addEventListener("keyup",t,e),n.addEventListener("blur",()=>Xn(n,"cancel"),e)});n.addEventListener("keydown",s,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",s),e)})(t,i)),function(t){return $n.has(t.tagName)||-1!==t.tabIndex}(t)||t.hasAttribute("tabindex")||(t.tabIndex=0))}),r}const Zn=[...Mn,xt,Rt];function Jn(t,e,n){const s=t.getProps();return c(s,e,void 0!==n?n:s.custom,t)}const Qn=t=>Array.isArray(t);function ts(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,Kn(n))}function es(t){return Qn(t)?t[t.length-1]||0:t}function ns(t,e){const n=t.getValue("willChange");if(s=n,Boolean(d(s)&&s.add))return n.add(e);if(!n&&O.WillChange){const n=new O.WillChange("auto");t.addValue("willChange",n),n.add(e)}var s}function ss(t){return t.props[p]}const is=t=>null!==t;const rs={type:"spring",stiffness:500,damping:25,restSpeed:10},os={type:"keyframes",duration:.8},as={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},us=(t,{keyframes:e})=>e.length>2?os:m.has(t)?t.startsWith("scale")?{type:"spring",stiffness:550,damping:0===e[1]?2*Math.sqrt(550):30,restSpeed:10}:rs:as;const ls=(t,e,n,s={},i,r)=>o=>{const a=Tn(s,t)||{},u=a.delay||s.delay||0;let{elapsed:l=0}=s;l-=U(u);const h={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-l,onUpdate:t=>{e.set(t),a.onUpdate&&a.onUpdate(t)},onComplete:()=>{o(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:r?void 0:i};(function({when:t,delay:e,delayChildren:n,staggerChildren:s,staggerDirection:i,repeat:r,repeatType:o,repeatDelay:a,from:u,elapsed:l,...h}){return!!Object.keys(h).length})(a)||Object.assign(h,us(t,h)),h.duration&&(h.duration=U(h.duration)),h.repeatDelay&&(h.repeatDelay=U(h.repeatDelay)),void 0!==h.from&&(h.keyframes[0]=h.from);let c=!1;if((!1===h.type||0===h.duration&&!h.repeatDelay)&&(fn(h),0===h.delay&&(c=!0)),(O.instantAnimations||O.skipAnimations)&&(c=!0,fn(h),h.delay=0),h.allowFlatten=!a.type&&!a.ease,c&&!r&&void 0!==e.get()){const t=function(t,{repeat:e,repeatType:n="loop"},s){const i=t.filter(is),r=e&&"loop"!==n&&e%2==1?0:i.length-1;return r&&void 0!==s?s:i[r]}(h.keyframes,a);if(void 0!==t)return void ht.update(()=>{h.onUpdate(t),h.onComplete()})}return a.isSync?new Oe(h):new gn(h)};function hs({protectedKeys:t,needsAnimating:e},n){const s=t.hasOwnProperty(n)&&!0!==e[n];return e[n]=!1,s}function cs(t,e,{delay:n=0,transitionOverride:s,type:i}={}){let{transition:r=t.getDefaultTransition(),transitionEnd:o,...a}=e;s&&(r=s);const u=[],l=i&&t.animationState&&t.animationState.getState()[i];for(const e in a){const s=t.getValue(e,t.latestValues[e]??null),i=a[e];if(void 0===i||l&&hs(l,e))continue;const o={delay:n,...Tn(r||{},e)},h=s.get();if(void 0!==h&&!s.isAnimating&&!Array.isArray(i)&&i===h&&!o.velocity)continue;let c=!1;if(window.MotionHandoffAnimation){const n=ss(t);if(n){const t=window.MotionHandoffAnimation(n,e,ht);null!==t&&(o.startTime=t,c=!0)}}ns(t,e),s.start(ls(e,s,i,t.shouldReduceMotion&&Sn.has(e)?{type:!1}:o,t,c));const d=s.animation;d&&u.push(d)}return o&&Promise.all(u).then(()=>{ht.update(()=>{o&&function(t,e){const n=Jn(t,e);let{transitionEnd:s={},transition:i={},...r}=n||{};r={...r,...s};for(const e in r)ts(t,e,es(r[e]))}(t,o)})}),u}function ds(t,e,n,s=0,i=1){const r=Array.from(t).sort((t,e)=>t.sortNodePosition(e)).indexOf(e),o=t.size,a=(o-1)*s;return"function"==typeof n?n(r,o):1===i?r*s:a-r*s}function ps(t,e,n={}){const s=Jn(t,e,"exit"===n.type?t.presenceContext?.custom:void 0);let{transition:i=t.getDefaultTransition()||{}}=s||{};n.transitionOverride&&(i=n.transitionOverride);const r=s?()=>Promise.all(cs(t,s,n)):()=>Promise.resolve(),o=t.variantChildren&&t.variantChildren.size?(s=0)=>{const{delayChildren:r=0,staggerChildren:o,staggerDirection:a}=i;return function(t,e,n=0,s=0,i=0,r=1,o){const a=[];for(const u of t.variantChildren)u.notify("AnimationStart",e),a.push(ps(u,e,{...o,delay:n+("function"==typeof s?0:s)+ds(t.variantChildren,u,s,i,r)}).then(()=>u.notify("AnimationComplete",e)));return Promise.all(a)}(t,e,s,r,o,a,n)}:()=>Promise.resolve(),{when:a}=i;if(a){const[t,e]="beforeChildren"===a?[r,o]:[o,r];return t().then(()=>e())}return Promise.all([r(),o(n.delay)])}function ms(t,e){if(!Array.isArray(e))return!1;const n=e.length;if(n!==t.length)return!1;for(let s=0;sPromise.all(e.map(({animation:e,options:n})=>function(t,e,n={}){let s;if(t.notify("AnimationStart",e),Array.isArray(e)){const i=e.map(e=>ps(t,e,n));s=Promise.all(i)}else if("string"==typeof e)s=ps(t,e,n);else{const i="function"==typeof e?Jn(t,e,n.custom):e;s=Promise.all(cs(t,i,n))}return s.then(()=>{t.notify("AnimationComplete",e)})}(t,e,n)))}function ws(t){let e=bs(t),n=As(),s=!0;const i=e=>(n,s)=>{const i=Jn(t,s,"exit"===e?t.presenceContext?.custom:void 0);if(i){const{transition:t,transitionEnd:e,...s}=i;n={...n,...s,...e}}return n};function r(r){const{props:o}=t,a=ys(t.parent)||{},u=[],l=new Set;let h={},c=1/0;for(let e=0;ec&&y,S=!1;const A=Array.isArray(m)?m:[m];let M=A.reduce(i(d),{});!1===g&&(M={});const{prevResolvedValues:V={}}=p,x={...V,...M},C=e=>{T=!0,l.has(e)&&(S=!0,l.delete(e)),p.needsAnimating[e]=!0;const n=t.getValue(e);n&&(n.liveStyle=!1)};for(const t in x){const e=M[t],n=V[t];if(h.hasOwnProperty(t))continue;let s=!1;s=Qn(e)&&Qn(n)?!ms(e,n):e!==n,s?null!=e?C(t):l.add(t):void 0!==e&&l.has(t)?C(t):p.protectedKeys[t]=!0}p.prevProp=m,p.prevResolvedValues=M,p.isActive&&(h={...h,...M}),s&&t.blockInitialAnimation&&(T=!1);const k=b&&w;T&&(!k||S)&&u.push(...A.map(e=>{const n={type:d};if("string"==typeof e&&s&&!k&&t.manuallyAnimateOnMount&&t.parent){const{parent:s}=t,i=Jn(s,e);if(s.enteringChildren&&i){const{delayChildren:e}=i.transition||{};n.delay=ds(s.enteringChildren,t,e)}}return{animation:e,options:n}}))}if(l.size){const e={};if("boolean"!=typeof o.initial){const n=Jn(t,Array.isArray(o.initial)?o.initial[0]:o.initial);n&&n.transition&&(e.transition=n.transition)}l.forEach(n=>{const s=t.getBaseTarget(n),i=t.getValue(n);i&&(i.liveStyle=!0),e[n]=s??null}),u.push({animation:e})}let d=Boolean(u.length);return!s||!1!==o.initial&&o.initial!==o.animate||t.manuallyAnimateOnMount||(d=!1),s=!1,d?e(u):Promise.resolve()}return{animateChanges:r,setActive:function(e,s){if(n[e].isActive===s)return Promise.resolve();t.variantChildren?.forEach(t=>t.animationState?.setActive(e,s)),n[e].isActive=s;const i=r(e);for(const t in n)n[t].protectedKeys={};return i},setAnimateFunction:function(n){e=n(t)},getState:()=>n,reset:()=>{n=As(),s=!0}}}function Ts(t,e){return"string"==typeof e?e!==t:!!Array.isArray(e)&&!ms(e,t)}function Ss(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function As(){return{animate:Ss(!0),whileInView:Ss(),whileHover:Ss(),whileTap:Ss(),whileDrag:Ss(),whileFocus:Ss(),exit:Ss()}}class Ms{constructor(t){this.isMounted=!1,this.node=t}update(){}}let Vs=0;const xs={animation:{Feature:class extends Ms{constructor(t){super(t),t.animationState||(t.animationState=ws(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();v(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:e}=this.node.prevProps||{};t!==e&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}},exit:{Feature:class extends Ms{constructor(){super(...arguments),this.id=Vs++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:e}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===n)return;const s=this.node.animationState.setActive("exit",!t);e&&!t&&s.then(()=>{e(this.id)})}mount(){const{register:t,onExitComplete:e}=this.node.presenceContext||{};e&&e(this.id),t&&(this.unmount=t(this.id))}unmount(){}}}};function Cs(t){return{point:{x:t.pageX,y:t.pageY}}}function ks(t,e,n){const{props:s}=t;t.animationState&&s.whileHover&&t.animationState.setActive("whileHover","Start"===n);const i=s["onHover"+n];i&&ht.postRender(()=>i(e,Cs(e)))}function Ps(t,e,n,s={passive:!0}){return t.addEventListener(e,n,s),()=>t.removeEventListener(e,n)}function Es(t,e,n){const{props:s}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&s.whileTap&&t.animationState.setActive("whileTap","Start"===n);const i=s["onTap"+("End"===n?"":n)];i&&ht.postRender(()=>i(e,Cs(e)))}const Fs=new WeakMap,Os=new WeakMap,Ds=t=>{const e=Fs.get(t.target);e&&e(t)},Is=t=>{t.forEach(Ds)};function Rs(t,e,n){const s=function({root:t,...e}){const n=t||document;Os.has(n)||Os.set(n,{});const s=Os.get(n),i=JSON.stringify(e);return s[i]||(s[i]=new IntersectionObserver(Is,{root:t,...e})),s[i]}(e);return Fs.set(t,n),s.observe(t),()=>{Fs.delete(t),s.unobserve(t)}}const Ns={some:0,all:1};const Ks={inView:{Feature:class extends Ms{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:e,margin:n,amount:s="some",once:i}=t,r={root:e?e.current:void 0,rootMargin:n,threshold:"number"==typeof s?s:Ns[s]};return Rs(this.node.current,r,t=>{const{isIntersecting:e}=t;if(this.isInView===e)return;if(this.isInView=e,i&&!e&&this.hasEnteredView)return;e&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",e);const{onViewportEnter:n,onViewportLeave:s}=this.node.getProps(),r=e?n:s;r&&r(t)})}mount(){this.startObserver()}update(){if("undefined"==typeof IntersectionObserver)return;const{props:t,prevProps:e}=this.node;["amount","margin","root"].some(function({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}(t,e))&&this.startObserver()}unmount(){}}},tap:{Feature:class extends Ms{mount(){const{current:t}=this.node;t&&(this.unmount=Gn(t,(t,e)=>(Es(this.node,e,"Start"),(t,{success:e})=>Es(this.node,t,e?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}},focus:{Feature:class extends Ms{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch(e){t=!0}t&&this.node.animationState&&(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){this.isActive&&this.node.animationState&&(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=B(Ps(this.node.current,"focus",()=>this.onFocus()),Ps(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}},hover:{Feature:class extends Ms{mount(){const{current:t}=this.node;t&&(this.unmount=function(t,e,n={}){const[s,i,r]=qn(t,n),o=t=>{if(!Wn(t))return;const{target:n}=t,s=e(n,t);if("function"!=typeof s||!n)return;const r=t=>{Wn(t)&&(s(t),n.removeEventListener("pointerleave",r))};n.addEventListener("pointerleave",r,i)};return s.forEach(t=>{t.addEventListener("pointerenter",o,i)}),r}(t,(t,e)=>(ks(this.node,e,"Start"),t=>ks(this.node,t,"End"))))}unmount(){}}}};const Bs=()=>({x:{min:0,max:0},y:{min:0,max:0}}),Ls={current:null},js={current:!1};const Us=new WeakMap;const qs=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Ws{scrapeMotionValuesFromProps(t,e,n){return{}}constructor({parent:t,props:e,presenceContext:n,reducedMotionConfig:s,blockInitialAnimation:i,visualState:r},o={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Qe,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const t=yt.now();this.renderScheduledAtthis.bindToMotionValue(e,t)),js.current||function(){if(js.current=!0,b)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Ls.current=t.matches;t.addEventListener("change",e),e()}else Ls.current=!1}(),this.shouldReduceMotion="never"!==this.reducedMotionConfig&&("always"===this.reducedMotionConfig||Ls.current),this.parent?.addChild(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),ct(this.notifyUpdate),ct(this.render),this.valueSubscriptions.forEach(t=>t()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const t in this.events)this.events[t].clear();for(const t in this.features){const e=this.features[t];e&&(e.unmount(),e.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,e){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const n=m.has(t);n&&this.onBindTransform&&this.onBindTransform();const s=e.on("change",e=>{this.latestValues[t]=e,this.props.onUpdate&&ht.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let i;window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,t,e)),this.valueSubscriptions.set(t,()=>{s(),i&&i(),e.owner&&e.stop()})}sortNodePosition(t){return this.current&&this.sortInstanceNodePosition&&this.type===t.type?this.sortInstanceNodePosition(this.current,t.current):0}updateFeatures(){let t="animation";for(t in S){const e=S[t];if(!e)continue;const{isEnabled:n,Feature:s}=e;if(!this.features[t]&&s&&n(this.props)&&(this.features[t]=new s(this)),this.features[t]){const e=this.features[t];e.isMounted?e.update():(e.mount(),e.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):{x:{min:0,max:0},y:{min:0,max:0}}}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,e){this.latestValues[t]=e}update(t,e){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=e;for(let e=0;ee.variantChildren.delete(t)}addValue(t,e){const n=this.values.get(t);e!==n&&(n&&this.removeValue(t),this.bindToMotionValue(t,e),this.values.set(t,e),this.latestValues[t]=e.get())}removeValue(t){this.values.delete(t);const e=this.valueSubscriptions.get(t);e&&(e(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,e){if(this.props.values&&this.props.values[t])return this.props.values[t];let n=this.values.get(t);return void 0===n&&void 0!==e&&(n=Kn(null===e?void 0:e,{owner:this}),this.addValue(t,n)),n}readValue(t,e){let n=void 0===this.latestValues[t]&&this.current?this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options):this.latestValues[t];var s;return null!=n&&("string"==typeof n&&(D(n)||I(n))?n=parseFloat(n):(s=n,!Zn.find(An(s))&&Rt.test(e)&&(n=Dn(t,e))),this.setBaseTarget(t,d(n)?n.get():n)),d(n)?n.get():n}setBaseTarget(t,e){this.baseTarget[t]=e}getBaseTarget(t){const{initial:e}=this.props;let n;if("string"==typeof e||"object"==typeof e){const s=c(this.props,e,this.presenceContext?.custom);s&&(n=s[t])}if(e&&void 0!==n)return n;const s=this.getBaseTargetFromProps(this.props,t);return void 0===s||d(s)?void 0!==this.initialValues[t]&&void 0===n?void 0:this.baseTarget[t]:s}on(t,e){return this.events[t]||(this.events[t]=new j),this.events[t].add(e)}notify(t,...e){this.events[t]&&this.events[t].notify(...e)}scheduleRenderMicrotask(){Bn.render(this.render)}}class Ys extends Ws{constructor(){super(...arguments),this.KeyframeResolver=Rn}sortInstanceNodePosition(t,e){return 2&t.compareDocumentPosition(e)?1:-1}getBaseTargetFromProps(t,e){return t.style?t.style[e]:void 0}removeValueFromRenderState(t,{vars:e,style:n}){delete e[t],delete n[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;d(t)&&(this.childSubscription=t.on("change",t=>{this.current&&(this.current.textContent=`${t}`)}))}}function $s(t,{style:e,vars:n},s,i){const r=t.style;let o;for(o in e)r[o]=e[o];for(o in i?.applyProjectionStyles(r,s),n)r.setProperty(o,n[o])}class zs extends Ys{constructor(){super(...arguments),this.type="html",this.renderInstance=$s}readValueFromInstance(t,e){if(m.has(e))return this.projection?.isProjecting?je(e):((t,e)=>{const{transform:n="none"}=getComputedStyle(t);return Ue(n,e)})(t,e);{const s=(n=t,window.getComputedStyle(n)),i=(A(e)?s.getPropertyValue(e):s[e])||0;return"string"==typeof i?i.trim():i}var n}measureInstanceViewportBox(t,{transformPagePoint:e}){return function(t,e){return function({top:t,left:e,right:n,bottom:s}){return{x:{min:e,max:n},y:{min:t,max:s}}}(function(t,e){if(!e)return t;const n=e({x:t.left,y:t.top}),s=e({x:t.right,y:t.bottom});return{top:n.y,left:n.x,bottom:s.y,right:s.x}}(t.getBoundingClientRect(),e))}(t,e)}build(t,e,n){M(t,e,n.transformTemplate)}scrapeMotionValuesFromProps(t,e,n){return V(t,e,n)}}const Hs=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);class Xs extends Ys{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Bs}getBaseTargetFromProps(t,e){return t[e]}readValueFromInstance(t,e){if(m.has(e)){const t=On(e);return t&&t.default||0}return e=Hs.has(e)?e:x(e),t.getAttribute(e)}scrapeMotionValuesFromProps(t,e,n){return C(t,e,n)}build(t,e,n){k(t,e,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(t,e,n,s){!function(t,e,n,s){$s(t,e,void 0,s);for(const n in e.attrs)t.setAttribute(Hs.has(n)?n:x(n),e.attrs[n])}(t,e,0,s)}mount(t){this.isSVGTag=P(t.tagName),super.mount(t)}}const _s={renderer:(t,e)=>E(t)?new Xs(e):new zs(e,{allowProjection:t!==F}),...xs,...Ks};export{_s as domAnimation}; diff --git a/frontend/node_modules/framer-motion/dist/size-rollup-dom-max-assets.js b/frontend/node_modules/framer-motion/dist/size-rollup-dom-max-assets.js new file mode 100644 index 0000000000000000000000000000000000000000..d1b3b022ae1224d0a641183929682ee347e4cd1d --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/size-rollup-dom-max-assets.js @@ -0,0 +1 @@ +import{createContext as t}from"react";const r=(t,r,a)=>a>r?r:ao(t[r]))}function f(t){return Boolean(i(t)||t.variants)}const l=t=>r=>"string"==typeof r&&r.startsWith(t),c=l("--"),p=l("var(--"),d=t=>!!p(t)&&u.test(t.split("/*")[0].trim()),u=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,m={test:t=>"number"==typeof t,parse:parseFloat,transform:t=>t},g={...m,transform:t=>r(0,1,t)},h={...m,default:1},y=t=>({test:r=>"string"==typeof r&&r.endsWith(t)&&1===r.split(" ").length,parse:parseFloat,transform:r=>`${r}${t}`}),w=y("deg"),v=y("%"),b=y("px"),x=y("vh"),k=y("vw"),B=(()=>({...v,parse:t=>v.parse(t)/100,transform:t=>v.transform(100*t)}))(),O=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],X=(()=>new Set(O))(),Y={...m,transform:Math.round},S={borderWidth:b,borderTopWidth:b,borderRightWidth:b,borderBottomWidth:b,borderLeftWidth:b,borderRadius:b,radius:b,borderTopLeftRadius:b,borderTopRightRadius:b,borderBottomRightRadius:b,borderBottomLeftRadius:b,width:b,maxWidth:b,height:b,maxHeight:b,top:b,right:b,bottom:b,left:b,padding:b,paddingTop:b,paddingRight:b,paddingBottom:b,paddingLeft:b,margin:b,marginTop:b,marginRight:b,marginBottom:b,marginLeft:b,backgroundPositionX:b,backgroundPositionY:b,...{rotate:w,rotateX:w,rotateY:w,rotateZ:w,scale:h,scaleX:h,scaleY:h,scaleZ:h,skew:w,skewX:w,skewY:w,distance:b,translateX:b,translateY:b,translateZ:b,x:b,y:b,z:b,perspective:b,transformPerspective:b,opacity:g,originX:B,originY:B,originZ:b},zIndex:Y,fillOpacity:g,strokeOpacity:g,numOctaves:Y},$=(t,r)=>r&&"number"==typeof t?r.transform(t):t,L=t=>Boolean(t&&t.getVelocity),P={};function T(t){for(const r in t)P[r]=t[r],c(r)&&(P[r].isCSSVariable=!0)}function W(t,{layout:r,layoutId:a}){return X.has(t)||t.startsWith("origin")||(r||void 0!==a)&&(!!P[t]||"opacity"===t)}const R={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},V=O.length;function Z(t,r,a){const{style:e,vars:o,transformOrigin:s}=t;let n=!1,i=!1;for(const t in r){const a=r[t];if(X.has(t))n=!0;else if(c(t))o[t]=a;else{const r=$(a,S[t]);t.startsWith("origin")?(i=!0,s[t]=r):e[t]=r}}if(r.transform||(n||a?e.transform=function(t,r,a){let e="",o=!0;for(let s=0;s"string"==typeof t&&"svg"===t.toLowerCase(),H=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function z(t){return"string"==typeof t&&!t.includes("-")&&!!(H.indexOf(t)>-1||/[A-Z]/u.test(t))}const E=t(null);function D(t){const r=[{},{}];return t?.values.forEach((t,a)=>{r[0][a]=t.get(),r[1][a]=t.getVelocity()}),r}function j(t,r,a,e){if("function"==typeof r){const[o,s]=D(e);r=r(void 0!==a?a:t.custom,o,s)}if("string"==typeof r&&(r=t.variants&&t.variants[r]),"function"==typeof r){const[o,s]=D(e);r=r(void 0!==a?a:t.custom,o,s)}return r}function q(t){return L(t)?t.get():t}function G(t,r,a){const{style:e}=t,o={};for(const s in e)(L(e[s])||r.style&&L(r.style[s])||W(s,t)||void 0!==a?.getValue(s)?.liveStyle)&&(o[s]=e[s]);return o}function J(t,r,a){const e=G(t,r,a);for(const a in t)if(L(t[a])||L(r[a])){e[-1!==O.indexOf(a)?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a]=t[a]}return e}const M="undefined"!=typeof window,U={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},K={};for(const t in U)K[t]={isEnabled:r=>U[t].some(t=>!!r[t])};function N(t){return t&&"object"==typeof t&&Object.prototype.hasOwnProperty.call(t,"current")}const Q=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),_="data-"+Q("framerAppearId"),tt=t({});export{k as A,x as B,S as C,X as D,P as E,c as F,T as G,n as H,s as I,Q as J,a as L,E as P,tt as S,o as a,L as b,W as c,Z as d,C as e,F as f,z as g,f as h,i,e as j,j as k,J as l,K as m,N as n,M as o,_ as p,m as q,q as r,G as s,g as t,r as u,v,d as w,b as x,O as y,w as z}; diff --git a/frontend/node_modules/framer-motion/dist/size-rollup-dom-max.js b/frontend/node_modules/framer-motion/dist/size-rollup-dom-max.js new file mode 100644 index 0000000000000000000000000000000000000000..970c382c59cc16b13d1a8242128f1d1b96e5780a --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/size-rollup-dom-max.js @@ -0,0 +1 @@ +import{q as t,t as e,u as i,v as s,w as n,x as o,y as r,z as a,A as l,B as h,C as u,D as c,b as d,n as p,p as m,r as f,E as y,o as g,i as v,h as x,m as T,k as P,F as w,d as S,s as A,P as b,L as E,S as V,G as M,a as D,H as C,j as k,I as R,J as L,l as j,e as B,f as F,g as I}from"./size-rollup-dom-max-assets.js";import{jsx as O}from"react/jsx-runtime";import{useContext as U,useId as N,useEffect as K,useCallback as W,Component as $,Fragment as z}from"react";function Y(t,e){-1===t.indexOf(e)&&t.push(e)}function X(t,e){const i=t.indexOf(e);i>-1&&t.splice(i,1)}const H={},G=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function q(t){return"object"==typeof t&&null!==t}const _=t=>/^0[^.\s]+$/u.test(t);function Z(t){let e;return()=>(void 0===e&&(e=t()),e)}const J=t=>t,Q=(t,e)=>i=>e(t(i)),tt=(...t)=>t.reduce(Q),et=(t,e,i)=>{const s=e-t;return 0===s?1:(i-t)/s};class it{constructor(){this.subscriptions=[]}add(t){return Y(this.subscriptions,t),()=>X(this.subscriptions,t)}notify(t,e,i){const s=this.subscriptions.length;if(s)if(1===s)this.subscriptions[0](t,e,i);else for(let n=0;n1e3*t,nt=t=>t/1e3;function ot(t,e){return e?t*(1e3/e):0}const rt=(t,e,i)=>(((1-3*i+3*e)*t+(3*i-6*e))*t+3*e)*t;function at(t,e,i,s){if(t===e&&i===s)return J;const n=e=>function(t,e,i,s,n){let o,r,a=0;do{r=e+(i-e)/2,o=rt(r,s,n)-t,o>0?i=r:e=r}while(Math.abs(o)>1e-7&&++a<12);return r}(e,0,1,t,i);return t=>0===t||1===t?t:rt(n(t),e,s)}const lt=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,ht=t=>e=>1-t(1-e),ut=at(.33,1.53,.69,.99),ct=ht(ut),dt=lt(ct),pt=t=>(t*=2)<1?.5*ct(t):.5*(2-Math.pow(2,-10*(t-1))),mt=t=>1-Math.sin(Math.acos(t)),ft=ht(mt),yt=lt(mt),gt=at(.42,0,1,1),vt=at(0,0,.58,1),xt=at(.42,0,.58,1),Tt=t=>Array.isArray(t)&&"number"==typeof t[0],Pt={linear:J,easeIn:gt,easeInOut:xt,easeOut:vt,circIn:mt,circInOut:yt,circOut:ft,backIn:ct,backInOut:dt,backOut:ut,anticipate:pt},wt=t=>{if(Tt(t)){t.length;const[e,i,s,n]=t;return at(e,i,s,n)}return"string"==typeof t?Pt[t]:t},St=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],At={value:null,addProjectionMetrics:null};function bt(t,e){let i=!1,s=!0;const n={delta:0,timestamp:0,isProcessing:!1},o=()=>i=!0,r=St.reduce((t,i)=>(t[i]=function(t,e){let i=new Set,s=new Set,n=!1,o=!1;const r=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},l=0;function h(e){r.has(e)&&(u.schedule(e),t()),l++,e(a)}const u={schedule:(t,e=!1,o=!1)=>{const a=o&&n?i:s;return e&&r.add(t),a.has(t)||a.add(t),t},cancel:t=>{s.delete(t),r.delete(t)},process:t=>{a=t,n?o=!0:(n=!0,[i,s]=[s,i],i.forEach(h),e&&At.value&&At.value.frameloop[e].push(l),l=0,i.clear(),n=!1,o&&(o=!1,u.process(t)))}};return u}(o,e?i:void 0),t),{}),{setup:a,read:l,resolveKeyframes:h,preUpdate:u,update:c,preRender:d,render:p,postRender:m}=r,f=()=>{const o=H.useManualTiming?n.timestamp:performance.now();i=!1,H.useManualTiming||(n.delta=s?1e3/60:Math.max(Math.min(o-n.timestamp,40),1)),n.timestamp=o,n.isProcessing=!0,a.process(n),l.process(n),h.process(n),u.process(n),c.process(n),d.process(n),p.process(n),m.process(n),n.isProcessing=!1,i&&e&&(s=!1,t(f))};return{schedule:St.reduce((e,o)=>{const a=r[o];return e[o]=(e,o=!1,r=!1)=>(i||(i=!0,s=!0,n.isProcessing||t(f)),a.schedule(e,o,r)),e},{}),cancel:t=>{for(let e=0;e(void 0===Ct&&Rt.set(Mt.isProcessing||H.useManualTiming?Mt.timestamp:performance.now()),Ct),set:t=>{Ct=t,queueMicrotask(kt)}},Lt=t=>Math.round(1e5*t)/1e5,jt=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;const Bt=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Ft=(t,e)=>i=>Boolean("string"==typeof i&&Bt.test(i)&&i.startsWith(t)||e&&!function(t){return null==t}(i)&&Object.prototype.hasOwnProperty.call(i,e)),It=(t,e,i)=>s=>{if("string"!=typeof s)return s;const[n,o,r,a]=s.match(jt);return{[t]:parseFloat(n),[e]:parseFloat(o),[i]:parseFloat(r),alpha:void 0!==a?parseFloat(a):1}},Ot={...t,transform:t=>Math.round((t=>i(0,255,t))(t))},Ut={test:Ft("rgb","red"),parse:It("red","green","blue"),transform:({red:t,green:i,blue:s,alpha:n=1})=>"rgba("+Ot.transform(t)+", "+Ot.transform(i)+", "+Ot.transform(s)+", "+Lt(e.transform(n))+")"};const Nt={test:Ft("#"),parse:function(t){let e="",i="",s="",n="";return t.length>5?(e=t.substring(1,3),i=t.substring(3,5),s=t.substring(5,7),n=t.substring(7,9)):(e=t.substring(1,2),i=t.substring(2,3),s=t.substring(3,4),n=t.substring(4,5),e+=e,i+=i,s+=s,n+=n),{red:parseInt(e,16),green:parseInt(i,16),blue:parseInt(s,16),alpha:n?parseInt(n,16)/255:1}},transform:Ut.transform},Kt={test:Ft("hsl","hue"),parse:It("hue","saturation","lightness"),transform:({hue:t,saturation:i,lightness:n,alpha:o=1})=>"hsla("+Math.round(t)+", "+s.transform(Lt(i))+", "+s.transform(Lt(n))+", "+Lt(e.transform(o))+")"},Wt={test:t=>Ut.test(t)||Nt.test(t)||Kt.test(t),parse:t=>Ut.test(t)?Ut.parse(t):Kt.test(t)?Kt.parse(t):Nt.parse(t),transform:t=>"string"==typeof t?t:t.hasOwnProperty("red")?Ut.transform(t):Kt.transform(t),getAnimatableNone:t=>{const e=Wt.parse(t);return e.alpha=0,Wt.transform(e)}},$t=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;const zt="number",Yt="color",Xt=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function Ht(t){const e=t.toString(),i=[],s={color:[],number:[],var:[]},n=[];let o=0;const r=e.replace(Xt,t=>(Wt.test(t)?(s.color.push(o),n.push(Yt),i.push(Wt.parse(t))):t.startsWith("var(")?(s.var.push(o),n.push("var"),i.push(t)):(s.number.push(o),n.push(zt),i.push(parseFloat(t))),++o,"${}")).split("${}");return{values:i,split:r,indexes:s,types:n}}function Gt(t){return Ht(t).values}function qt(t){const{split:e,types:i}=Ht(t),s=e.length;return t=>{let n="";for(let o=0;o"number"==typeof t?0:Wt.test(t)?Wt.getAnimatableNone(t):t;const Zt={test:function(t){return isNaN(t)&&"string"==typeof t&&(t.match(jt)?.length||0)+(t.match($t)?.length||0)>0},parse:Gt,createTransformer:qt,getAnimatableNone:function(t){const e=Gt(t);return qt(t)(e.map(_t))}};function Jt(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}function Qt(t,e){return i=>i>0?e:t}const te=(t,e,i)=>t+(e-t)*i,ee=(t,e,i)=>{const s=t*t,n=i*(e*e-s)+s;return n<0?0:Math.sqrt(n)},ie=[Nt,Ut,Kt];function se(t){const e=(i=t,ie.find(t=>t.test(i)));var i;if(!Boolean(e))return!1;let s=e.parse(t);return e===Kt&&(s=function({hue:t,saturation:e,lightness:i,alpha:s}){t/=360,i/=100;let n=0,o=0,r=0;if(e/=100){const s=i<.5?i*(1+e):i+e-i*e,a=2*i-s;n=Jt(a,s,t+1/3),o=Jt(a,s,t),r=Jt(a,s,t-1/3)}else n=o=r=i;return{red:Math.round(255*n),green:Math.round(255*o),blue:Math.round(255*r),alpha:s}}(s)),s}const ne=(t,e)=>{const i=se(t),s=se(e);if(!i||!s)return Qt(t,e);const n={...i};return t=>(n.red=ee(i.red,s.red,t),n.green=ee(i.green,s.green,t),n.blue=ee(i.blue,s.blue,t),n.alpha=te(i.alpha,s.alpha,t),Ut.transform(n))},oe=new Set(["none","hidden"]);function re(t,e){return i=>te(t,e,i)}function ae(t){return"number"==typeof t?re:"string"==typeof t?n(t)?Qt:Wt.test(t)?ne:ue:Array.isArray(t)?le:"object"==typeof t?Wt.test(t)?ne:he:Qt}function le(t,e){const i=[...t],s=i.length,n=t.map((t,i)=>ae(t)(t,e[i]));return t=>{for(let e=0;e{for(const e in s)i[e]=s[e](t);return i}}const ue=(t,e)=>{const i=Zt.createTransformer(e),s=Ht(t),n=Ht(e);return s.indexes.var.length===n.indexes.var.length&&s.indexes.color.length===n.indexes.color.length&&s.indexes.number.length>=n.indexes.number.length?oe.has(t)&&!n.values.length||oe.has(e)&&!s.values.length?function(t,e){return oe.has(t)?i=>i<=0?t:e:i=>i>=1?e:t}(t,e):tt(le(function(t,e){const i=[],s={color:0,var:0,number:0};for(let n=0;n{const e=({timestamp:e})=>t(e);return{start:(t=!0)=>Et.update(e,t),stop:()=>Vt(e),now:()=>Mt.isProcessing?Mt.timestamp:Rt.now()}},pe=(t,e,i=10)=>{let s="";const n=Math.max(Math.round(e/i),2);for(let e=0;e=me?1/0:e}function ye(t,e,i){const s=Math.max(e-5,0);return ot(i-t(s),e-s)}const ge=100,ve=10,xe=1,Te=0,Pe=800,we=.3,Se=.3,Ae={granular:.01,default:2},be={granular:.005,default:.5},Ee=.01,Ve=10,Me=.05,De=1,Ce=.001;function ke({duration:t=Pe,bounce:e=we,velocity:s=Te,mass:n=xe}){let o,r,a=1-e;a=i(Me,De,a),t=i(Ee,Ve,nt(t)),a<1?(o=e=>{const i=e*a,n=i*t,o=i-s,r=Le(e,a),l=Math.exp(-n);return Ce-o/r*l},r=e=>{const i=e*a*t,n=i*s+s,r=Math.pow(a,2)*Math.pow(e,2)*t,l=Math.exp(-i),h=Le(Math.pow(e,2),a);return(-o(e)+Ce>0?-1:1)*((n-r)*l)/h}):(o=e=>Math.exp(-e*t)*((e-s)*t+1)-.001,r=e=>Math.exp(-e*t)*(t*t*(s-e)));const l=function(t,e,i){let s=i;for(let i=1;ivoid 0!==t[e])}function Ie(t=Se,e=we){const s="object"!=typeof t?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:n,restDelta:o}=s;const r=s.keyframes[0],a=s.keyframes[s.keyframes.length-1],l={done:!1,value:r},{stiffness:h,damping:u,mass:c,duration:d,velocity:p,isResolvedFromDuration:m}=function(t){let e={velocity:Te,stiffness:ge,damping:ve,mass:xe,isResolvedFromDuration:!1,...t};if(!Fe(t,Be)&&Fe(t,je))if(t.visualDuration){const s=t.visualDuration,n=2*Math.PI/(1.2*s),o=n*n,r=2*i(.05,1,1-(t.bounce||0))*Math.sqrt(o);e={...e,mass:xe,stiffness:o,damping:r}}else{const i=ke(t);e={...e,...i,mass:xe},e.isResolvedFromDuration=!0}return e}({...s,velocity:-nt(s.velocity||0)}),f=p||0,y=u/(2*Math.sqrt(h*c)),g=a-r,v=nt(Math.sqrt(h/c)),x=Math.abs(g)<5;let T;if(n||(n=x?Ae.granular:Ae.default),o||(o=x?be.granular:be.default),y<1){const t=Le(v,y);T=e=>{const i=Math.exp(-y*v*e);return a-i*((f+y*v*g)/t*Math.sin(t*e)+g*Math.cos(t*e))}}else if(1===y)T=t=>a-Math.exp(-v*t)*(g+(f+v*g)*t);else{const t=v*Math.sqrt(y*y-1);T=e=>{const i=Math.exp(-y*v*e),s=Math.min(t*e,300);return a-i*((f+y*v*g)*Math.sinh(s)+t*g*Math.cosh(s))/t}}const P={calculatedDuration:m&&d||null,next:t=>{const e=T(t);if(m)l.done=t>=d;else{let i=0===t?f:0;y<1&&(i=0===t?st(f):ye(T,t,e));const s=Math.abs(i)<=n,r=Math.abs(a-e)<=o;l.done=s&&r}return l.value=l.done?a:e,l},toString:()=>{const t=Math.min(fe(P),me),e=pe(e=>P.next(t*e).value,t,30);return t+"ms "+e},toTransition:()=>{}};return P}function Oe({keyframes:t,velocity:e=0,power:i=.8,timeConstant:s=325,bounceDamping:n=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:l,restDelta:h=.5,restSpeed:u}){const c=t[0],d={done:!1,value:c},p=t=>void 0===a?l:void 0===l||Math.abs(a-t)-m*Math.exp(-t/s),v=t=>y+g(t),x=t=>{const e=g(t),i=v(t);d.done=Math.abs(e)<=h,d.value=d.done?y:i};let T,P;const w=t=>{var e;(e=d.value,void 0!==a&&el)&&(T=t,P=Ie({keyframes:[d.value,p(d.value)],velocity:ye(v,t,d.value),damping:n,stiffness:o,restDelta:h,restSpeed:u}))};return w(0),{calculatedDuration:null,next:t=>{let e=!1;return P||void 0!==T||(e=!0,x(t),w(t)),void 0!==T&&t>=T?P.next(t-T):(!e&&x(t),d)}}}function Ue(t,e,{clamp:s=!0,ease:n,mixer:o}={}){const r=t.length;if(e.length,1===r)return()=>e[0];if(2===r&&e[0]===e[1])return()=>e[1];const a=t[0]===t[1];t[0]>t[r-1]&&(t=[...t].reverse(),e=[...e].reverse());const l=function(t,e,i){const s=[],n=i||H.mix||ce,o=t.length-1;for(let i=0;i{if(a&&i1)for(;su(i(t[0],t[r-1],e)):u}function Ne(t){const e=[0];return function(t,e){const i=t[t.length-1];for(let s=1;s<=e;s++){const n=et(0,e,s);t.push(te(i,1,n))}}(e,t.length-1),e}function Ke({duration:t=300,keyframes:e,times:i,ease:s="easeInOut"}){const n=(t=>Array.isArray(t)&&"number"!=typeof t[0])(s)?s.map(wt):wt(s),o={done:!1,value:e[0]},r=function(t,e){return t.map(t=>t*e)}(i&&i.length===e.length?i:Ne(e),t),a=Ue(r,e,{ease:Array.isArray(n)?n:(l=e,h=n,l.map(()=>h||xt).splice(0,l.length-1))});var l,h;return{calculatedDuration:t,next:e=>(o.value=a(e),o.done=e>=t,o)}}Ie.applyToOptions=t=>{const e=function(t,e=100,i){const s=i({...t,keyframes:[0,e]}),n=Math.min(fe(s),me);return{type:"keyframes",ease:t=>s.next(n*t).value/e,duration:nt(n)}}(t,100,Ie);return t.ease=e.ease,t.duration=st(e.duration),t.type="keyframes",t};const We=t=>null!==t;function $e(t,{repeat:e,repeatType:i="loop"},s,n=1){const o=t.filter(We),r=n<0||e&&"loop"!==i&&e%2==1?0:o.length-1;return r&&void 0!==s?s:o[r]}const ze={decay:Oe,inertia:Oe,tween:Ke,keyframes:Ke,spring:Ie};function Ye(t){"string"==typeof t.type&&(t.type=ze[t.type])}class Xe{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,e){return this.finished.then(t,e)}}const He=t=>t/100;class Ge extends Xe{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:t}=this.options;t&&t.updatedAt!==Rt.now()&&this.tick(Rt.now()),this.isStopped=!0,"idle"!==this.state&&(this.teardown(),this.options.onStop?.())},this.options=t,this.initAnimation(),this.play(),!1===t.autoplay&&this.pause()}initAnimation(){const{options:t}=this;Ye(t);const{type:e=Ke,repeat:i=0,repeatDelay:s=0,repeatType:n,velocity:o=0}=t;let{keyframes:r}=t;const a=e||Ke;a!==Ke&&"number"!=typeof r[0]&&(this.mixKeyframes=tt(He,ce(r[0],r[1])),r=[0,100]);const l=a({...t,keyframes:r});"mirror"===n&&(this.mirroredGenerator=a({...t,keyframes:[...r].reverse(),velocity:-o})),null===l.calculatedDuration&&(l.calculatedDuration=fe(l));const{calculatedDuration:h}=l;this.calculatedDuration=h,this.resolvedDuration=h+s,this.totalDuration=this.resolvedDuration*(i+1)-s,this.generator=l}updateTime(t){const e=Math.round(t-this.startTime)*this.playbackSpeed;null!==this.holdTime?this.currentTime=this.holdTime:this.currentTime=e}tick(t,e=!1){const{generator:s,totalDuration:n,mixKeyframes:o,mirroredGenerator:r,resolvedDuration:a,calculatedDuration:l}=this;if(null===this.startTime)return s.next(0);const{delay:h=0,keyframes:u,repeat:c,repeatType:d,repeatDelay:p,type:m,onUpdate:f,finalKeyframe:y}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-n/this.speed,this.startTime)),e?this.currentTime=t:this.updateTime(t);const g=this.currentTime-h*(this.playbackSpeed>=0?1:-1),v=this.playbackSpeed>=0?g<0:g>n;this.currentTime=Math.max(g,0),"finished"===this.state&&null===this.holdTime&&(this.currentTime=n);let x=this.currentTime,T=s;if(c){const t=Math.min(this.currentTime,n)/a;let e=Math.floor(t),s=t%1;!s&&t>=1&&(s=1),1===s&&e--,e=Math.min(e,c+1);Boolean(e%2)&&("reverse"===d?(s=1-s,p&&(s-=p/a)):"mirror"===d&&(T=r)),x=i(0,1,s)*a}const P=v?{done:!1,value:u[0]}:T.next(x);o&&(P.value=o(P.value));let{done:w}=P;v||null===l||(w=this.playbackSpeed>=0?this.currentTime>=n:this.currentTime<=0);const S=null===this.holdTime&&("finished"===this.state||"running"===this.state&&w);return S&&m!==Oe&&(P.value=$e(u,this.options,y,this.speed)),f&&f(P.value),S&&this.finish(),P}then(t,e){return this.finished.then(t,e)}get duration(){return nt(this.calculatedDuration)}get time(){return nt(this.currentTime)}set time(t){t=st(t),this.currentTime=t,null===this.startTime||null!==this.holdTime||0===this.playbackSpeed?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime(Rt.now());const e=this.playbackSpeed!==t;this.playbackSpeed=t,e&&(this.time=nt(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=de,startTime:e}=this.options;this.driver||(this.driver=t(t=>this.tick(t))),this.options.onPlay?.();const i=this.driver.now();"finished"===this.state?(this.updateFinished(),this.startTime=i):null!==this.holdTime?this.startTime=i-this.holdTime:this.startTime||(this.startTime=e??i),"finished"===this.state&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(Rt.now()),this.holdTime=this.currentTime}complete(){"running"!==this.state&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),t.observe(this)}}const qe=t=>180*t/Math.PI,_e=t=>{const e=qe(Math.atan2(t[1],t[0]));return Je(e)},Ze={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:_e,rotateZ:_e,skewX:t=>qe(Math.atan(t[1])),skewY:t=>qe(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Je=t=>((t%=360)<0&&(t+=360),t),Qe=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),ti=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),ei={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Qe,scaleY:ti,scale:t=>(Qe(t)+ti(t))/2,rotateX:t=>Je(qe(Math.atan2(t[6],t[5]))),rotateY:t=>Je(qe(Math.atan2(-t[2],t[0]))),rotateZ:_e,rotate:_e,skewX:t=>qe(Math.atan(t[4])),skewY:t=>qe(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function ii(t){return t.includes("scale")?1:0}function si(t,e){if(!t||"none"===t)return ii(e);const i=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,n;if(i)s=ei,n=i;else{const e=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=Ze,n=e}if(!n)return ii(e);const o=s[e],r=n[1].split(",").map(ni);return"function"==typeof o?o(r):r[o]}function ni(t){return parseFloat(t.trim())}const oi=e=>e===t||e===o,ri=new Set(["x","y","z"]),ai=r.filter(t=>!ri.has(t));const li={width:({x:t},{paddingLeft:e="0",paddingRight:i="0"})=>t.max-t.min-parseFloat(e)-parseFloat(i),height:({y:t},{paddingTop:e="0",paddingBottom:i="0"})=>t.max-t.min-parseFloat(e)-parseFloat(i),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>si(e,"x"),y:(t,{transform:e})=>si(e,"y")};li.translateX=li.x,li.translateY=li.y;const hi=new Set;let ui=!1,ci=!1,di=!1;function pi(){if(ci){const t=Array.from(hi).filter(t=>t.needsMeasurement),e=new Set(t.map(t=>t.element)),i=new Map;e.forEach(t=>{const e=function(t){const e=[];return ai.forEach(i=>{const s=t.getValue(i);void 0!==s&&(e.push([i,s.get()]),s.set(i.startsWith("scale")?1:0))}),e}(t);e.length&&(i.set(t,e),t.render())}),t.forEach(t=>t.measureInitialState()),e.forEach(t=>{t.render();const e=i.get(t);e&&e.forEach(([e,i])=>{t.getValue(e)?.set(i)})}),t.forEach(t=>t.measureEndState()),t.forEach(t=>{void 0!==t.suspendedScrollY&&window.scrollTo(0,t.suspendedScrollY)})}ci=!1,ui=!1,hi.forEach(t=>t.complete(di)),hi.clear()}function mi(){hi.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(ci=!0)})}class fi{constructor(t,e,i,s,n,o=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=e,this.name=i,this.motionValue=s,this.element=n,this.isAsync=o}scheduleResolve(){this.state="scheduled",this.isAsync?(hi.add(this),ui||(ui=!0,Et.read(mi),Et.resolveKeyframes(pi))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:e,element:i,motionValue:s}=this;if(null===t[0]){const n=s?.get(),o=t[t.length-1];if(void 0!==n)t[0]=n;else if(i&&e){const s=i.readValue(e,o);null!=s&&(t[0]=s)}void 0===t[0]&&(t[0]=o),s&&void 0===n&&s.set(t[0])}!function(t){for(let e=1;evoid 0!==window.ScrollTimeline),gi={};function vi(t,e){const i=Z(t);return()=>gi[e]??i()}const xi=vi(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch(t){return!1}return!0},"linearEasing"),Ti=([t,e,i,s])=>`cubic-bezier(${t}, ${e}, ${i}, ${s})`,Pi={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Ti([0,.65,.55,1]),circOut:Ti([.55,0,1,.45]),backIn:Ti([.31,.01,.66,-.59]),backOut:Ti([.33,1.53,.69,.99])};function wi(t,e){return t?"function"==typeof t?xi()?pe(t,e):"ease-out":Tt(t)?Ti(t):Array.isArray(t)?t.map(t=>wi(t,e)||Pi.easeOut):Pi[t]:void 0}function Si(t,e,i,{delay:s=0,duration:n=300,repeat:o=0,repeatType:r="loop",ease:a="easeOut",times:l}={},h=void 0){const u={[e]:i};l&&(u.offset=l);const c=wi(a,n);Array.isArray(c)&&(u.easing=c);const d={delay:s,duration:n,easing:Array.isArray(c)?"linear":c,fill:"both",iterations:o+1,direction:"reverse"===r?"alternate":"normal"};h&&(d.pseudoElement=h);return t.animate(u,d)}function Ai(t){return"function"==typeof t&&"applyToOptions"in t}class bi extends Xe{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:e,name:i,keyframes:s,pseudoElement:n,allowFlatten:o=!1,finalKeyframe:r,onComplete:a}=t;this.isPseudoElement=Boolean(n),this.allowFlatten=o,this.options=t,t.type;const l=function({type:t,...e}){return Ai(t)&&xi()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}(t);this.animation=Si(e,i,s,l,n),!1===l.autoplay&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!n){const t=$e(s,this.options,r,this.speed);this.updateMotionValue?this.updateMotionValue(t):function(t,e,i){(t=>t.startsWith("--"))(e)?t.style.setProperty(e,i):t.style[e]=i}(e,i,t),this.animation.cancel()}a?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),"finished"===this.state&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch(t){}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;"idle"!==t&&"finished"!==t&&(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming?.().duration||0;return nt(Number(t))}get time(){return nt(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=st(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return null!==this.finishedTime?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:e}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&yi()?(this.animation.timeline=t,J):e(this)}}const Ei={anticipate:pt,backInOut:dt,circInOut:yt};function Vi(t){"string"==typeof t.ease&&t.ease in Ei&&(t.ease=Ei[t.ease])}class Mi extends bi{constructor(t){Vi(t),Ye(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:e,onUpdate:i,onComplete:s,element:n,...o}=this.options;if(!e)return;if(void 0!==t)return void e.set(t);const r=new Ge({...o,autoplay:!1}),a=st(this.finishedTime??this.time);e.setWithVelocity(r.sample(a-10).value,r.sample(a).value,10),r.stop()}}const Di=(t,e)=>"zIndex"!==e&&(!("number"!=typeof t&&!Array.isArray(t))||!("string"!=typeof t||!Zt.test(t)&&"0"!==t||t.startsWith("url(")));function Ci(t){t.duration=0,t.type}const ki=new Set(["opacity","clipPath","filter","transform"]),Ri=Z(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));class Li extends Xe{constructor({autoplay:t=!0,delay:e=0,type:i="keyframes",repeat:s=0,repeatDelay:n=0,repeatType:o="loop",keyframes:r,name:a,motionValue:l,element:h,...u}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=Rt.now();const c={autoplay:t,delay:e,type:i,repeat:s,repeatDelay:n,repeatType:o,name:a,motionValue:l,element:h,...u},d=h?.KeyframeResolver||fi;this.keyframeResolver=new d(r,(t,e,i)=>this.onKeyframesResolved(t,e,c,!i),a,l,h),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,e,i,s){this.keyframeResolver=void 0;const{name:n,type:o,velocity:r,delay:a,isHandoff:l,onUpdate:h}=i;this.resolvedAt=Rt.now(),function(t,e,i,s){const n=t[0];if(null===n)return!1;if("display"===e||"visibility"===e)return!0;const o=t[t.length-1],r=Di(n,e),a=Di(o,e);return!(!r||!a)&&(function(t){const e=t[0];if(1===t.length)return!0;for(let i=0;i40?this.resolvedAt:this.createdAt:void 0,finalKeyframe:e,...i,keyframes:t},c=!l&&function(t){const{motionValue:e,name:i,repeatDelay:s,repeatType:n,damping:o,type:r}=t,a=e?.owner?.current;if(!(a instanceof HTMLElement))return!1;const{onUpdate:l,transformTemplate:h}=e.owner.getProps();return Ri()&&i&&ki.has(i)&&("transform"!==i||!h)&&!l&&!s&&"mirror"!==n&&0!==o&&"inertia"!==r}(u)?new Mi({...u,element:u.motionValue.owner.current}):new Ge(u);c.finished.then(()=>this.notifyFinished()).catch(J),this.pendingTimeline&&(this.stopTimeline=c.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=c}get finished(){return this._animation?this.animation.finished:this._finished}then(t,e){return this.finished.finally(t).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),di=!0,mi(),pi(),di=!1),this._animation}get duration(){return this.animation.duration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}const ji=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Bi(t,e,i=1){const[s,o]=function(t){const e=ji.exec(t);if(!e)return[,];const[,i,s,n]=e;return[`--${i??s}`,n]}(t);if(!s)return;const r=window.getComputedStyle(e).getPropertyValue(s);if(r){const t=r.trim();return G(t)?parseFloat(t):t}return n(o)?Bi(o,e,i+1):o}function Fi(t,e){return t?.[e]??t?.default??t}const Ii=new Set(["width","height","top","left","right","bottom",...r]),Oi=t=>e=>e.test(t),Ui=[t,o,s,a,l,h,{test:t=>"auto"===t,parse:t=>t}],Ni=t=>Ui.find(Oi(t));function Ki(t){return"number"==typeof t?0===t:null===t||("none"===t||"0"===t||_(t))}const Wi=new Set(["brightness","contrast","saturate","opacity"]);function $i(t){const[e,i]=t.slice(0,-1).split("(");if("drop-shadow"===e)return t;const[s]=i.match(jt)||[];if(!s)return t;const n=i.replace(s,"");let o=Wi.has(e)?1:0;return s!==i&&(o*=100),e+"("+o+n+")"}const zi=/\b([a-z-]*)\(.*?\)/gu,Yi={...Zt,getAnimatableNone:t=>{const e=t.match(zi);return e?e.map($i).join(" "):t}},Xi={...u,color:Wt,backgroundColor:Wt,outlineColor:Wt,fill:Wt,stroke:Wt,borderColor:Wt,borderTopColor:Wt,borderRightColor:Wt,borderBottomColor:Wt,borderLeftColor:Wt,filter:Yi,WebkitFilter:Yi},Hi=t=>Xi[t];function Gi(t,e){let i=Hi(t);return i!==Yi&&(i=Zt),i.getAnimatableNone?i.getAnimatableNone(e):void 0}const qi=new Set(["auto","none","0"]);class _i extends fi{constructor(t,e,i,s,n){super(t,e,i,s,n,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:e,name:i}=this;if(!e||!e.current)return;super.readKeyframes();for(let i=0;i{t.getValue(e).set(i)}),this.resolveNoneKeyframes()}}class Zi{constructor(t,e={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=t=>{const e=Rt.now();if(this.updatedAt!==e&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(t),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const t of this.dependents)t.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=e.owner}setCurrent(t){var e;this.current=t,this.updatedAt=Rt.now(),null===this.canTrackVelocity&&void 0!==t&&(this.canTrackVelocity=(e=this.current,!isNaN(parseFloat(e))))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return this.on("change",t)}on(t,e){this.events[t]||(this.events[t]=new it);const i=this.events[t].add(e);return"change"===t?()=>{i(),Et.read(()=>{this.events.change.getSize()||this.stop()})}:i}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,e){this.passiveEffect=t,this.stopPassiveEffect=e}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,e,i){this.set(e),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-i}jump(t,e=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,e&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=Rt.now();if(!this.canTrackVelocity||void 0===this.prevFrameValue||t-this.updatedAt>30)return 0;const e=Math.min(this.updatedAt-this.prevUpdatedAt,30);return ot(parseFloat(this.current)-parseFloat(this.prevFrameValue),e)}start(t){return this.stop(),new Promise(e=>{this.hasAnimated=!0,this.animation=t(e),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function Ji(t,e){return new Zi(t,e)}const{schedule:Qi,cancel:ts}=bt(queueMicrotask,!1),es={x:!1,y:!1};function is(){return es.x||es.y}function ss(t,e){const i=function(t,e,i){if(t instanceof EventTarget)return[t];if("string"==typeof t){let s=document;e&&(s=e.current);const n=i?.[t]??s.querySelectorAll(t);return n?Array.from(n):[]}return Array.from(t)}(t),s=new AbortController;return[i,{passive:!0,...e,signal:s.signal},()=>s.abort()]}function ns(t){return!("touch"===t.pointerType||is())}const os=(t,e)=>!!e&&(t===e||os(t,e.parentElement)),rs=t=>"mouse"===t.pointerType?"number"!=typeof t.button||t.button<=0:!1!==t.isPrimary,as=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);const ls=new WeakSet;function hs(t){return e=>{"Enter"===e.key&&t(e)}}function us(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}function cs(t){return rs(t)&&!is()}function ds(t,e,i={}){const[s,n,o]=ss(t,i),r=t=>{const s=t.currentTarget;if(!cs(t))return;ls.add(s);const o=e(s,t),r=(t,e)=>{window.removeEventListener("pointerup",a),window.removeEventListener("pointercancel",l),ls.has(s)&&ls.delete(s),cs(t)&&"function"==typeof o&&o(t,{success:e})},a=t=>{r(t,s===window||s===document||i.useGlobalTarget||os(s,t.target))},l=t=>{r(t,!1)};window.addEventListener("pointerup",a,n),window.addEventListener("pointercancel",l,n)};return s.forEach(t=>{var e;(i.useGlobalTarget?window:t).addEventListener("pointerdown",r,n),q(e=t)&&"offsetHeight"in e&&(t.addEventListener("focus",t=>((t,e)=>{const i=t.currentTarget;if(!i)return;const s=hs(()=>{if(ls.has(i))return;us(i,"down");const t=hs(()=>{us(i,"up")});i.addEventListener("keyup",t,e),i.addEventListener("blur",()=>us(i,"cancel"),e)});i.addEventListener("keydown",s,e),i.addEventListener("blur",()=>i.removeEventListener("keydown",s),e)})(t,n)),function(t){return as.has(t.tagName)||-1!==t.tabIndex}(t)||t.hasAttribute("tabindex")||(t.tabIndex=0))}),o}function ps(t){return q(t)&&"ownerSVGElement"in t}const ms=[...Ui,Wt,Zt];class fs{constructor(t){this.isMounted=!1,this.node=t}update(){}}const ys=t=>null!==t;const gs={type:"spring",stiffness:500,damping:25,restSpeed:10},vs={type:"keyframes",duration:.8},xs={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Ts=(t,{keyframes:e})=>e.length>2?vs:c.has(t)?t.startsWith("scale")?{type:"spring",stiffness:550,damping:0===e[1]?2*Math.sqrt(550):30,restSpeed:10}:gs:xs;const Ps=(t,e,i,s={},n,o)=>r=>{const a=Fi(s,t)||{},l=a.delay||s.delay||0;let{elapsed:h=0}=s;h-=st(l);const u={keyframes:Array.isArray(i)?i:[null,i],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-h,onUpdate:t=>{e.set(t),a.onUpdate&&a.onUpdate(t)},onComplete:()=>{r(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:n};(function({when:t,delay:e,delayChildren:i,staggerChildren:s,staggerDirection:n,repeat:o,repeatType:r,repeatDelay:a,from:l,elapsed:h,...u}){return!!Object.keys(u).length})(a)||Object.assign(u,Ts(t,u)),u.duration&&(u.duration=st(u.duration)),u.repeatDelay&&(u.repeatDelay=st(u.repeatDelay)),void 0!==u.from&&(u.keyframes[0]=u.from);let c=!1;if((!1===u.type||0===u.duration&&!u.repeatDelay)&&(Ci(u),0===u.delay&&(c=!0)),(H.instantAnimations||H.skipAnimations)&&(c=!0,Ci(u),u.delay=0),u.allowFlatten=!a.type&&!a.ease,c&&!o&&void 0!==e.get()){const t=function(t,{repeat:e,repeatType:i="loop"},s){const n=t.filter(ys),o=e&&"loop"!==i&&e%2==1?0:n.length-1;return o&&void 0!==s?s:n[o]}(u.keyframes,a);if(void 0!==t)return void Et.update(()=>{u.onUpdate(t),u.onComplete()})}return a.isSync?new Ge(u):new Li(u)};function ws(t,e,i,s={passive:!0}){return t.addEventListener(e,i,s),()=>t.removeEventListener(e,i)}function Ss(t){return{point:{x:t.pageX,y:t.pageY}}}function As(t,e,i,s){return ws(t,e,(t=>e=>rs(e)&&t(e,Ss(e)))(i),s)}function bs({top:t,left:e,right:i,bottom:s}){return{x:{min:e,max:i},y:{min:t,max:s}}}function Es(t){return t.max-t.min}function Vs(t,e,i,s=.5){t.origin=s,t.originPoint=te(e.min,e.max,t.origin),t.scale=Es(i)/Es(e),t.translate=te(i.min,i.max,t.origin)-t.originPoint,(t.scale>=.9999&&t.scale<=1.0001||isNaN(t.scale))&&(t.scale=1),(t.translate>=-.01&&t.translate<=.01||isNaN(t.translate))&&(t.translate=0)}function Ms(t,e,i,s){Vs(t.x,e.x,i.x,s?s.originX:void 0),Vs(t.y,e.y,i.y,s?s.originY:void 0)}function Ds(t,e,i){t.min=i.min+e.min,t.max=t.min+Es(e)}function Cs(t,e,i){t.min=e.min-i.min,t.max=t.min+Es(e)}function ks(t,e,i){Cs(t.x,e.x,i.x),Cs(t.y,e.y,i.y)}const Rs=()=>({x:{min:0,max:0},y:{min:0,max:0}});function Ls(t){return[t("x"),t("y")]}function js(t){return void 0===t||1===t}function Bs({scale:t,scaleX:e,scaleY:i}){return!js(t)||!js(e)||!js(i)}function Fs(t){return Bs(t)||Is(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Is(t){return Os(t.x)||Os(t.y)}function Os(t){return t&&"0%"!==t}function Us(t,e,i){return i+e*(t-i)}function Ns(t,e,i,s,n){return void 0!==n&&(t=Us(t,n,s)),Us(t,i,s)+e}function Ks(t,e=0,i=1,s,n){t.min=Ns(t.min,e,i,s,n),t.max=Ns(t.max,e,i,s,n)}function Ws(t,{x:e,y:i}){Ks(t.x,e.translate,e.scale,e.originPoint),Ks(t.y,i.translate,i.scale,i.originPoint)}const $s=.999999999999,zs=1.0000000000001;function Ys(t,e){t.min=t.min+e,t.max=t.max+e}function Xs(t,e,i,s,n=.5){Ks(t,e,i,te(t.min,t.max,n),s)}function Hs(t,e){Xs(t.x,e.x,e.scaleX,e.scale,e.originX),Xs(t.y,e.y,e.scaleY,e.scale,e.originY)}function Gs(t,e){return bs(function(t,e){if(!e)return t;const i=e({x:t.left,y:t.top}),s=e({x:t.right,y:t.bottom});return{top:i.y,left:i.x,bottom:s.y,right:s.x}}(t.getBoundingClientRect(),e))}const qs=({current:t})=>t?t.ownerDocument.defaultView:null;function _s(t,e){const i=t.getValue("willChange");if(s=i,Boolean(d(s)&&s.add))return i.add(e);if(!i&&H.WillChange){const i=new H.WillChange("auto");t.addValue("willChange",i),i.add(e)}var s}const Zs=(t,e)=>Math.abs(t-e);class Js{constructor(t,e,{transformPagePoint:i,contextWindow:s=window,dragSnapToOrigin:n=!1,distanceThreshold:o=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!this.lastMoveEvent||!this.lastMoveEventInfo)return;const t=en(this.lastMoveEventInfo,this.history),e=null!==this.startEvent,i=function(t,e){const i=Zs(t.x,e.x),s=Zs(t.y,e.y);return Math.sqrt(i**2+s**2)}(t.offset,{x:0,y:0})>=this.distanceThreshold;if(!e&&!i)return;const{point:s}=t,{timestamp:n}=Mt;this.history.push({...s,timestamp:n});const{onStart:o,onMove:r}=this.handlers;e||(o&&o(this.lastMoveEvent,t),this.startEvent=this.lastMoveEvent),r&&r(this.lastMoveEvent,t)},this.handlePointerMove=(t,e)=>{this.lastMoveEvent=t,this.lastMoveEventInfo=Qs(e,this.transformPagePoint),Et.update(this.updatePoint,!0)},this.handlePointerUp=(t,e)=>{this.end();const{onEnd:i,onSessionEnd:s,resumeAnimation:n}=this.handlers;if(this.dragSnapToOrigin&&n&&n(),!this.lastMoveEvent||!this.lastMoveEventInfo)return;const o=en("pointercancel"===t.type?this.lastMoveEventInfo:Qs(e,this.transformPagePoint),this.history);this.startEvent&&i&&i(t,o),s&&s(t,o)},!rs(t))return;this.dragSnapToOrigin=n,this.handlers=e,this.transformPagePoint=i,this.distanceThreshold=o,this.contextWindow=s||window;const r=Qs(Ss(t),this.transformPagePoint),{point:a}=r,{timestamp:l}=Mt;this.history=[{...a,timestamp:l}];const{onSessionStart:h}=e;h&&h(t,en(r,this.history)),this.removeListeners=tt(As(this.contextWindow,"pointermove",this.handlePointerMove),As(this.contextWindow,"pointerup",this.handlePointerUp),As(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),Vt(this.updatePoint)}}function Qs(t,e){return e?{point:e(t.point)}:t}function tn(t,e){return{x:t.x-e.x,y:t.y-e.y}}function en({point:t},e){return{point:t,delta:tn(t,nn(e)),offset:tn(t,sn(e)),velocity:on(e,.1)}}function sn(t){return t[0]}function nn(t){return t[t.length-1]}function on(t,e){if(t.length<2)return{x:0,y:0};let i=t.length-1,s=null;const n=nn(t);for(;i>=0&&(s=t[i],!(n.timestamp-s.timestamp>st(e)));)i--;if(!s)return{x:0,y:0};const o=nt(n.timestamp-s.timestamp);if(0===o)return{x:0,y:0};const r={x:(n.x-s.x)/o,y:(n.y-s.y)/o};return r.x===1/0&&(r.x=0),r.y===1/0&&(r.y=0),r}function rn(t,e,i){return{min:void 0!==e?t.min+e:void 0,max:void 0!==i?t.max+i-(t.max-t.min):void 0}}function an(t,e){let i=e.min-t.min,s=e.max-t.max;return e.max-e.min{const{dragSnapToOrigin:i}=this.getProps();i?this.pauseAnimation():this.stopAnimation(),e&&this.snapToCursor(Ss(t).point)},onStart:(t,e)=>{const{drag:i,dragPropagation:n,onDragStart:o}=this.getProps();if(i&&!n&&(this.openDragLock&&this.openDragLock(),this.openDragLock="x"===(r=i)||"y"===r?es[r]?null:(es[r]=!0,()=>{es[r]=!1}):es.x||es.y?null:(es.x=es.y=!0,()=>{es.x=es.y=!1}),!this.openDragLock))return;var r;this.latestPointerEvent=t,this.latestPanInfo=e,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Ls(t=>{let e=this.getAxisMotionValue(t).get()||0;if(s.test(e)){const{projection:i}=this.visualElement;if(i&&i.layout){const s=i.layout.layoutBox[t];if(s){e=Es(s)*(parseFloat(e)/100)}}}this.originPoint[t]=e}),o&&Et.postRender(()=>o(t,e)),_s(this.visualElement,"transform");const{animationState:a}=this.visualElement;a&&a.setActive("whileDrag",!0)},onMove:(t,e)=>{this.latestPointerEvent=t,this.latestPanInfo=e;const{dragPropagation:i,dragDirectionLock:s,onDirectionLock:n,onDrag:o}=this.getProps();if(!i&&!this.openDragLock)return;const{offset:r}=e;if(s&&null===this.currentDirection)return this.currentDirection=function(t,e=10){let i=null;Math.abs(t.y)>e?i="y":Math.abs(t.x)>e&&(i="x");return i}(r),void(null!==this.currentDirection&&n&&n(this.currentDirection));this.updateAxis("x",e.point,r),this.updateAxis("y",e.point,r),this.visualElement.render(),o&&o(t,e)},onSessionEnd:(t,e)=>{this.latestPointerEvent=t,this.latestPanInfo=e,this.stop(t,e),this.latestPointerEvent=null,this.latestPanInfo=null},resumeAnimation:()=>Ls(t=>"paused"===this.getAnimationState(t)&&this.getAxisMotionValue(t).animation?.play())},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:o,distanceThreshold:i,contextWindow:qs(this.visualElement)})}stop(t,e){const i=t||this.latestPointerEvent,s=e||this.latestPanInfo,n=this.isDragging;if(this.cancel(),!n||!s||!i)return;const{velocity:o}=s;this.startAnimation(o);const{onDragEnd:r}=this.getProps();r&&Et.postRender(()=>r(i,s))}cancel(){this.isDragging=!1;const{projection:t,animationState:e}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:i}=this.getProps();!i&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),e&&e.setActive("whileDrag",!1)}updateAxis(t,e,i){const{drag:s}=this.getProps();if(!i||!pn(t,s,this.currentDirection))return;const n=this.getAxisMotionValue(t);let o=this.originPoint[t]+i[t];this.constraints&&this.constraints[t]&&(o=function(t,{min:e,max:i},s){return void 0!==e&&ti&&(t=s?te(i,t,s.max):Math.min(t,i)),t}(o,this.constraints[t],this.elastic[t])),n.set(o)}resolveConstraints(){const{dragConstraints:t,dragElastic:e}=this.getProps(),i=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,s=this.constraints;t&&p(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):this.constraints=!(!t||!i)&&function(t,{top:e,left:i,bottom:s,right:n}){return{x:rn(t.x,i,n),y:rn(t.y,e,s)}}(i.layoutBox,t),this.elastic=function(t=ln){return!1===t?t=0:!0===t&&(t=ln),{x:hn(t,"left","right"),y:hn(t,"top","bottom")}}(e),s!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&Ls(t=>{!1!==this.constraints&&this.getAxisMotionValue(t)&&(this.constraints[t]=function(t,e){const i={};return void 0!==e.min&&(i.min=e.min-t.min),void 0!==e.max&&(i.max=e.max-t.min),i}(i.layoutBox[t],this.constraints[t]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:e}=this.getProps();if(!t||!p(t))return!1;const i=t.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const n=function(t,e,i){const s=Gs(t,i),{scroll:n}=e;return n&&(Ys(s.x,n.offset.x),Ys(s.y,n.offset.y)),s}(i,s.root,this.visualElement.getTransformPagePoint());let o=function(t,e){return{x:an(t.x,e.x),y:an(t.y,e.y)}}(s.layout.layoutBox,n);if(e){const t=e(function({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}(o));this.hasMutatedConstraints=!!t,t&&(o=bs(t))}return o}startAnimation(t){const{drag:e,dragMomentum:i,dragElastic:s,dragTransition:n,dragSnapToOrigin:o,onDragTransitionEnd:r}=this.getProps(),a=this.constraints||{},l=Ls(r=>{if(!pn(r,e,this.currentDirection))return;let l=a&&a[r]||{};o&&(l={min:0,max:0});const h=s?200:1e6,u=s?40:1e7,c={type:"inertia",velocity:i?t[r]:0,bounceStiffness:h,bounceDamping:u,timeConstant:750,restDelta:1,restSpeed:10,...n,...l};return this.startAxisValueAnimation(r,c)});return Promise.all(l).then(r)}startAxisValueAnimation(t,e){const i=this.getAxisMotionValue(t);return _s(this.visualElement,t),i.start(Ps(t,i,0,e,this.visualElement,!1))}stopAnimation(){Ls(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){Ls(t=>this.getAxisMotionValue(t).animation?.pause())}getAnimationState(t){return this.getAxisMotionValue(t).animation?.state}getAxisMotionValue(t){const e=`_drag${t.toUpperCase()}`,i=this.visualElement.getProps(),s=i[e];return s||this.visualElement.getValue(t,(i.initial?i.initial[t]:void 0)||0)}snapToCursor(t){Ls(e=>{const{drag:i}=this.getProps();if(!pn(e,i,this.currentDirection))return;const{projection:s}=this.visualElement,n=this.getAxisMotionValue(e);if(s&&s.layout){const{min:i,max:o}=s.layout.layoutBox[e];n.set(t[e]-te(i,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:e}=this.getProps(),{projection:s}=this.visualElement;if(!p(e)||!s||!this.constraints)return;this.stopAnimation();const n={x:0,y:0};Ls(t=>{const e=this.getAxisMotionValue(t);if(e&&!1!==this.constraints){const s=e.get();n[t]=function(t,e){let s=.5;const n=Es(t),o=Es(e);return o>n?s=et(e.min,e.max-n,t.min):n>o&&(s=et(t.min,t.max-o,e.min)),i(0,1,s)}({min:s,max:s},this.constraints[t])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",s.root&&s.root.updateScroll(),s.updateLayout(),this.resolveConstraints(),Ls(e=>{if(!pn(e,t,null))return;const i=this.getAxisMotionValue(e),{min:s,max:o}=this.constraints[e];i.set(te(s,o,n[e]))})}addListeners(){if(!this.visualElement.current)return;cn.set(this.visualElement,this);const t=As(this.visualElement.current,"pointerdown",t=>{const{drag:e,dragListener:i=!0}=this.getProps();e&&i&&this.start(t)}),e=()=>{const{dragConstraints:t}=this.getProps();p(t)&&t.current&&(this.constraints=this.resolveRefConstraints())},{projection:i}=this.visualElement,s=i.addEventListener("measure",e);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),Et.read(e);const n=ws(window,"resize",()=>this.scalePositionWithinConstraints()),o=i.addEventListener("didUpdate",({delta:t,hasLayoutChanged:e})=>{this.isDragging&&e&&(Ls(e=>{const i=this.getAxisMotionValue(e);i&&(this.originPoint[e]+=t[e].translate,i.set(i.get()+t[e].translate))}),this.visualElement.render())});return()=>{n(),t(),s(),o&&o()}}getProps(){const t=this.visualElement.getProps(),{drag:e=!1,dragDirectionLock:i=!1,dragPropagation:s=!1,dragConstraints:n=!1,dragElastic:o=ln,dragMomentum:r=!0}=t;return{...t,drag:e,dragDirectionLock:i,dragPropagation:s,dragConstraints:n,dragElastic:o,dragMomentum:r}}}function pn(t,e,i){return!(!0!==e&&e!==t||null!==i&&i!==t)}const mn=t=>(e,i)=>{t&&Et.postRender(()=>t(e,i))};function fn(t){return t.props[m]}const yn=(t,e)=>t.depth-e.depth;class gn{constructor(){this.children=[],this.isDirty=!1}add(t){Y(this.children,t),this.isDirty=!0}remove(t){X(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(yn),this.isDirty=!1,this.children.forEach(t)}}const vn=["TopLeft","TopRight","BottomLeft","BottomRight"],xn=vn.length,Tn=t=>"string"==typeof t?parseFloat(t):t,Pn=t=>"number"==typeof t||o.test(t);function wn(t,e){return void 0!==t[e]?t[e]:t.borderRadius}const Sn=bn(0,.5,ft),An=bn(.5,.95,J);function bn(t,e,i){return s=>se?1:i(et(t,e,s))}function En(t,e){t.min=e.min,t.max=e.max}function Vn(t,e){En(t.x,e.x),En(t.y,e.y)}function Mn(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Dn(t,e,i,s,n){return t=Us(t-=e,1/i,s),void 0!==n&&(t=Us(t,1/n,s)),t}function Cn(t,e,[i,n,o],r,a){!function(t,e=0,i=1,n=.5,o,r=t,a=t){s.test(e)&&(e=parseFloat(e),e=te(a.min,a.max,e/100)-a.min);if("number"!=typeof e)return;let l=te(r.min,r.max,n);t===r&&(l-=e),t.min=Dn(t.min,e,i,l,o),t.max=Dn(t.max,e,i,l,o)}(t,e[i],e[n],e[o],e.scale,r,a)}const kn=["x","scaleX","originX"],Rn=["y","scaleY","originY"];function Ln(t,e,i,s){Cn(t.x,e,kn,i?i.x:void 0,s?s.x:void 0),Cn(t.y,e,Rn,i?i.y:void 0,s?s.y:void 0)}function jn(t){return 0===t.translate&&1===t.scale}function Bn(t){return jn(t.x)&&jn(t.y)}function Fn(t,e){return t.min===e.min&&t.max===e.max}function In(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function On(t,e){return In(t.x,e.x)&&In(t.y,e.y)}function Un(t){return Es(t.x)/Es(t.y)}function Nn(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class Kn{constructor(){this.members=[]}add(t){Y(this.members,t),t.scheduleRender()}remove(t){if(X(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const t=this.members[this.members.length-1];t&&this.promote(t)}}relegate(t){const e=this.members.findIndex(e=>t===e);if(0===e)return!1;let i;for(let t=e;t>=0;t--){const e=this.members[t];if(!1!==e.isPresent){i=e;break}}return!!i&&(this.promote(i),!0)}promote(t,e){const i=this.lead;if(t!==i&&(this.prevLead=i,this.lead=t,t.show(),i)){i.instance&&i.scheduleRender(),t.scheduleRender(),t.resumeFrom=i,e&&(t.resumeFrom.preserveOpacity=!0),i.snapshot&&(t.snapshot=i.snapshot,t.snapshot.latestValues=i.animationValues||i.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:s}=t.options;!1===s&&i.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:e,resumingFrom:i}=t;e.onExitComplete&&e.onExitComplete(),i&&i.options.onExitComplete&&i.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}const Wn={hasAnimatedSinceResize:!0,hasEverUpdated:!1},$n=["","X","Y","Z"];let zn=0;function Yn(t,e,i,s){const{latestValues:n}=e;n[t]&&(i[t]=n[t],e.setStaticValue(t,0),s&&(s[t]=0))}function Xn(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const i=fn(e);if(window.MotionHasOptimisedAnimation(i,"transform")){const{layout:e,layoutId:s}=t.options;window.MotionCancelOptimisedAnimation(i,"transform",Et,!(e||s))}const{parent:s}=t;s&&!s.hasCheckedOptimisedAppear&&Xn(s)}function Hn({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:o,resetTransform:r}){return class{constructor(t={},i=e?.()){this.id=zn++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(_n),this.nodes.forEach(so),this.nodes.forEach(no),this.nodes.forEach(Zn)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=t,this.root=i?i.root||i:this,this.path=i?[...i.path,i]:[],this.parent=i,this.depth=i?i.depth+1:0;for(let t=0;tthis.root.updateBlockedByResize=!1;Et.read(()=>{s=window.innerWidth}),t(e,()=>{const t=window.innerWidth;t!==s&&(s=t,this.root.updateBlockedByResize=!0,i&&i(),i=function(t,e){const i=Rt.now(),s=({timestamp:n})=>{const o=n-i;o>=e&&(Vt(s),t(o-e))};return Et.setup(s,!0),()=>Vt(s)}(n,250),Wn.hasAnimatedSinceResize&&(Wn.hasAnimatedSinceResize=!1,this.nodes.forEach(io)))})}s&&this.root.registerSharedNode(s,this),!1!==this.options.animate&&o&&(s||n)&&this.addEventListener("didUpdate",({delta:t,hasLayoutChanged:e,hasRelativeLayoutChanged:i,layout:s})=>{if(this.isTreeAnimationBlocked())return this.target=void 0,void(this.relativeTarget=void 0);const n=this.options.transition||o.getDefaultTransition()||uo,{onLayoutAnimationStart:r,onLayoutAnimationComplete:a}=o.getProps(),l=!this.targetLayout||!On(this.targetLayout,s),h=!e&&i;if(this.options.layoutRoot||this.resumeFrom||h||e&&(l||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const e={...Fi(n,"layout"),onPlay:r,onComplete:a};(o.shouldReduceMotion||this.options.layoutRoot)&&(e.delay=0,e.type=!1),this.startAnimation(e),this.setAnimationOrigin(t,h)}else e||io(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=s})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const t=this.getStack();t&&t.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Vt(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(oo),this.animationId++)}getTransformTemplate(){const{visualElement:t}=this.options;return t&&t.getProps().transformTemplate}willUpdate(t=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked())return void(this.options.onExitComplete&&this.options.onExitComplete());if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Xn(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let t=0;t{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){!this.snapshot&&this.instance&&(this.snapshot=this.measure(),!this.snapshot||Es(this.snapshot.measuredBox.x)||Es(this.snapshot.measuredBox.y)||(this.snapshot=void 0))}updateLayout(){if(!this.instance)return;if(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead()||this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let t=0;t$s&&(e.x=1),e.y$s&&(e.y=1)}(this.layoutCorrected,this.treeScale,this.path,e),!t.layout||t.target||1===this.treeScale.x&&1===this.treeScale.y||(t.target=t.layout.layoutBox,t.targetWithTransforms={x:{min:0,max:0},y:{min:0,max:0}});const{target:a}=t;a?(this.projectionDelta&&this.prevProjectionDelta?(Mn(this.prevProjectionDelta.x,this.projectionDelta.x),Mn(this.prevProjectionDelta.y,this.projectionDelta.y)):this.createProjectionDeltas(),Ms(this.projectionDelta,this.layoutCorrected,a,this.latestValues),this.treeScale.x===o&&this.treeScale.y===r&&Nn(this.projectionDelta.x,this.prevProjectionDelta.x)&&Nn(this.projectionDelta.y,this.prevProjectionDelta.y)||(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",a))):this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender())}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(t=!0){if(this.options.visualElement?.scheduleRender(),t){const t=this.getStack();t&&t.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}},this.projectionDelta={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}},this.projectionDeltaWithTransform={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}}}setAnimationOrigin(t,e=!1){const i=this.snapshot,n=i?i.latestValues:{},o={...this.latestValues},r={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}};this.relativeParent&&this.relativeParent.options.layoutRoot||(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!e;const a={x:{min:0,max:0},y:{min:0,max:0}},l=(i?i.source:void 0)!==(this.layout?this.layout.source:void 0),h=this.getStack(),u=!h||h.members.length<=1,c=Boolean(l&&!u&&!0===this.options.crossfade&&!this.path.some(ho));let d;this.animationProgress=0,this.mixTargetDelta=e=>{const i=e/1e3;var h,p,m,f,y,g;ao(r.x,t.x,i),ao(r.y,t.y,i),this.setTargetDelta(r),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(ks(a,this.layout.layoutBox,this.relativeParent.layout.layoutBox),m=this.relativeTarget,f=this.relativeTargetOrigin,y=a,g=i,lo(m.x,f.x,y.x,g),lo(m.y,f.y,y.y,g),d&&(h=this.relativeTarget,p=d,Fn(h.x,p.x)&&Fn(h.y,p.y))&&(this.isProjectionDirty=!1),d||(d={x:{min:0,max:0},y:{min:0,max:0}}),Vn(d,this.relativeTarget)),l&&(this.animationValues=o,function(t,e,i,n,o,r){o?(t.opacity=te(0,i.opacity??1,Sn(n)),t.opacityExit=te(e.opacity??1,0,An(n))):r&&(t.opacity=te(e.opacity??1,i.opacity??1,n));for(let o=0;o{Wn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Ji(0)),this.currentAnimation=function(t,e,i){const s=d(t)?t:Ji(t);return s.start(Ps("",s,e,i)),s.animation}(this.motionValue,[0,1e3],{...t,velocity:0,isSync:!0,onUpdate:e=>{this.mixTargetDelta(e),t.onUpdate&&t.onUpdate(e)},onStop:()=>{},onComplete:()=>{t.onComplete&&t.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const t=this.getStack();t&&t.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(1e3),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const t=this.getLead();let{targetWithTransforms:e,target:i,layout:s,latestValues:n}=t;if(e&&i&&s){if(this!==t&&this.layout&&s&&fo(this.options.animationType,this.layout.layoutBox,s.layoutBox)){i=this.target||{x:{min:0,max:0},y:{min:0,max:0}};const e=Es(this.layout.layoutBox.x);i.x.min=t.target.x.min,i.x.max=i.x.min+e;const s=Es(this.layout.layoutBox.y);i.y.min=t.target.y.min,i.y.max=i.y.min+s}Vn(e,i),Hs(e,n),Ms(this.projectionDeltaWithTransform,this.layoutCorrected,e,n)}}registerSharedNode(t,e){this.sharedNodes.has(t)||this.sharedNodes.set(t,new Kn);this.sharedNodes.get(t).add(e);const i=e.options.initialPromotionConfig;e.promote({transition:i?i.transition:void 0,preserveFollowOpacity:i&&i.shouldPreserveFollowOpacity?i.shouldPreserveFollowOpacity(e):void 0})}isLead(){const t=this.getStack();return!t||t.lead===this}getLead(){const{layoutId:t}=this.options;return t&&this.getStack()?.lead||this}getPrevLead(){const{layoutId:t}=this.options;return t?this.getStack()?.prevLead:void 0}getStack(){const{layoutId:t}=this.options;if(t)return this.root.sharedNodes.get(t)}promote({needsReset:t,transition:e,preserveFollowOpacity:i}={}){const s=this.getStack();s&&s.promote(this,i),t&&(this.projectionDelta=void 0,this.needsReset=!0),e&&this.setOptions({transition:e})}relegate(){const t=this.getStack();return!!t&&t.relegate(this)}resetSkewAndRotation(){const{visualElement:t}=this.options;if(!t)return;let e=!1;const{latestValues:i}=t;if((i.z||i.rotate||i.rotateX||i.rotateY||i.rotateZ||i.skewX||i.skewY)&&(e=!0),!e)return;const s={};i.z&&Yn("z",t,s,this.animationValues);for(let e=0;e<$n.length;e++)Yn(`rotate${$n[e]}`,t,s,this.animationValues),Yn(`skew${$n[e]}`,t,s,this.animationValues);t.render();for(const e in s)t.setStaticValue(e,s[e]),this.animationValues&&(this.animationValues[e]=s[e]);t.scheduleRender()}applyProjectionStyles(t,e){if(!this.instance||this.isSVG)return;if(!this.isVisible)return void(t.visibility="hidden");const i=this.getTransformTemplate();if(this.needsReset)return this.needsReset=!1,t.visibility="",t.opacity="",t.pointerEvents=f(e?.pointerEvents)||"",void(t.transform=i?i(this.latestValues,""):"none");const s=this.getLead();if(!this.projectionDelta||!this.layout||!s.target)return this.options.layoutId&&(t.opacity=void 0!==this.latestValues.opacity?this.latestValues.opacity:1,t.pointerEvents=f(e?.pointerEvents)||""),void(this.hasProjected&&!Fs(this.latestValues)&&(t.transform=i?i({},""):"none",this.hasProjected=!1));t.visibility="";const n=s.animationValues||s.latestValues;this.applyTransformsToTarget();let o=function(t,e,i){let s="";const n=t.x.translate/e.x,o=t.y.translate/e.y,r=i?.z||0;if((n||o||r)&&(s=`translate3d(${n}px, ${o}px, ${r}px) `),1===e.x&&1===e.y||(s+=`scale(${1/e.x}, ${1/e.y}) `),i){const{transformPerspective:t,rotate:e,rotateX:n,rotateY:o,skewX:r,skewY:a}=i;t&&(s=`perspective(${t}px) ${s}`),e&&(s+=`rotate(${e}deg) `),n&&(s+=`rotateX(${n}deg) `),o&&(s+=`rotateY(${o}deg) `),r&&(s+=`skewX(${r}deg) `),a&&(s+=`skewY(${a}deg) `)}const a=t.x.scale*e.x,l=t.y.scale*e.y;return 1===a&&1===l||(s+=`scale(${a}, ${l})`),s||"none"}(this.projectionDeltaWithTransform,this.treeScale,n);i&&(o=i(n,o)),t.transform=o;const{x:r,y:a}=this.projectionDelta;t.transformOrigin=`${100*r.origin}% ${100*a.origin}% 0`,s.animationValues?t.opacity=s===this?n.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:n.opacityExit:t.opacity=s===this?void 0!==n.opacity?n.opacity:"":void 0!==n.opacityExit?n.opacityExit:0;for(const e in y){if(void 0===n[e])continue;const{correct:i,applyTo:r,isCSSVariable:a}=y[e],l="none"===o?n[e]:i(n[e],s);if(r){const e=r.length;for(let i=0;it.currentAnimation?.stop()),this.root.nodes.forEach(Qn),this.root.sharedNodes.clear()}}}function Gn(t){t.updateLayout()}function qn(t){const e=t.resumeFrom?.snapshot||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:i,measuredBox:s}=t.layout,{animationType:n}=t.options,o=e.source!==t.layout.source;"size"===n?Ls(t=>{const s=o?e.measuredBox[t]:e.layoutBox[t],n=Es(s);s.min=i[t].min,s.max=s.min+n}):fo(n,e.layoutBox,i)&&Ls(s=>{const n=o?e.measuredBox[s]:e.layoutBox[s],r=Es(i[s]);n.max=n.min+r,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[s].max=t.relativeTarget[s].min+r)});const r={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}};Ms(r,i,e.layoutBox);const a={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}};o?Ms(a,t.applyTransform(s,!0),e.measuredBox):Ms(a,i,e.layoutBox);const l=!Bn(r);let h=!1;if(!t.resumeFrom){const s=t.getClosestProjectingParent();if(s&&!s.resumeFrom){const{snapshot:n,layout:o}=s;if(n&&o){const r={x:{min:0,max:0},y:{min:0,max:0}};ks(r,e.layoutBox,n.layoutBox);const a={x:{min:0,max:0},y:{min:0,max:0}};ks(a,i,o.layoutBox),On(r,a)||(h=!0),s.options.layoutRoot&&(t.relativeTarget=a,t.relativeTargetOrigin=r,t.relativeParent=s)}}}t.notifyListeners("didUpdate",{layout:i,snapshot:e,delta:a,layoutDelta:r,hasLayoutChanged:l,hasRelativeLayoutChanged:h})}else if(t.isLead()){const{onExitComplete:e}=t.options;e&&e()}t.options.transition=void 0}function _n(t){t.parent&&(t.isProjecting()||(t.isProjectionDirty=t.parent.isProjectionDirty),t.isSharedProjectionDirty||(t.isSharedProjectionDirty=Boolean(t.isProjectionDirty||t.parent.isProjectionDirty||t.parent.isSharedProjectionDirty)),t.isTransformDirty||(t.isTransformDirty=t.parent.isTransformDirty))}function Zn(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Jn(t){t.clearSnapshot()}function Qn(t){t.clearMeasurements()}function to(t){t.isLayoutDirty=!1}function eo(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function io(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function so(t){t.resolveTargetDelta()}function no(t){t.calcProjection()}function oo(t){t.resetSkewAndRotation()}function ro(t){t.removeLeadSnapshot()}function ao(t,e,i){t.translate=te(e.translate,0,i),t.scale=te(e.scale,1,i),t.origin=e.origin,t.originPoint=e.originPoint}function lo(t,e,i,s){t.min=te(e.min,i.min,s),t.max=te(e.max,i.max,s)}function ho(t){return t.animationValues&&void 0!==t.animationValues.opacityExit}const uo={duration:.45,ease:[.4,0,.1,1]},co=t=>"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),po=co("applewebkit/")&&!co("chrome/")?Math.round:J;function mo(t){t.min=po(t.min),t.max=po(t.max)}function fo(t,e,i){return"position"===t||"preserve-aspect"===t&&(s=Un(e),n=Un(i),o=.2,!(Math.abs(s-n)<=o));var s,n,o}function yo(t){return t!==t.root&&t.scroll?.wasRoot}const go=Hn({attachResizeListener:(t,e)=>ws(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),vo={current:void 0},xo=Hn({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!vo.current){const t=new go({});t.mount(window),t.setOptions({layoutScroll:!0}),vo.current=t}return vo.current},resetTransform:(t,e)=>{t.style.transform=void 0!==e?e:"none"},checkIsScrollRoot:t=>Boolean("fixed"===window.getComputedStyle(t).position)});function To(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const Po={correct:(t,e)=>{if(!e.target)return t;if("string"==typeof t){if(!o.test(t))return t;t=parseFloat(t)}return`${To(t,e.target.x)}% ${To(t,e.target.y)}%`}},wo={correct:(t,{treeScale:e,projectionDelta:i})=>{const s=t,n=Zt.parse(t);if(n.length>5)return s;const o=Zt.createTransformer(t),r="number"!=typeof n[0]?1:0,a=i.x.scale*e.x,l=i.y.scale*e.y;n[0+r]/=a,n[1+r]/=l;const h=te(a,l,.5);return"number"==typeof n[2+r]&&(n[2+r]/=h),"number"==typeof n[3+r]&&(n[3+r]/=h),o(n)}},So={current:null},Ao={current:!1};const bo=new WeakMap;const Eo=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Vo{scrapeMotionValuesFromProps(t,e,i){return{}}constructor({parent:t,props:e,presenceContext:i,reducedMotionConfig:s,blockInitialAnimation:n,visualState:o},r={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=fi,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const t=Rt.now();this.renderScheduledAtthis.bindToMotionValue(e,t)),Ao.current||function(){if(Ao.current=!0,g)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>So.current=t.matches;t.addEventListener("change",e),e()}else So.current=!1}(),this.shouldReduceMotion="never"!==this.reducedMotionConfig&&("always"===this.reducedMotionConfig||So.current),this.parent?.addChild(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),Vt(this.notifyUpdate),Vt(this.render),this.valueSubscriptions.forEach(t=>t()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const t in this.events)this.events[t].clear();for(const t in this.features){const e=this.features[t];e&&(e.unmount(),e.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,e){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const i=c.has(t);i&&this.onBindTransform&&this.onBindTransform();const s=e.on("change",e=>{this.latestValues[t]=e,this.props.onUpdate&&Et.preRender(this.notifyUpdate),i&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let n;window.MotionCheckAppearSync&&(n=window.MotionCheckAppearSync(this,t,e)),this.valueSubscriptions.set(t,()=>{s(),n&&n(),e.owner&&e.stop()})}sortNodePosition(t){return this.current&&this.sortInstanceNodePosition&&this.type===t.type?this.sortInstanceNodePosition(this.current,t.current):0}updateFeatures(){let t="animation";for(t in T){const e=T[t];if(!e)continue;const{isEnabled:i,Feature:s}=e;if(!this.features[t]&&s&&i(this.props)&&(this.features[t]=new s(this)),this.features[t]){const e=this.features[t];e.isMounted?e.update():(e.mount(),e.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):{x:{min:0,max:0},y:{min:0,max:0}}}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,e){this.latestValues[t]=e}update(t,e){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=e;for(let e=0;ee.variantChildren.delete(t)}addValue(t,e){const i=this.values.get(t);e!==i&&(i&&this.removeValue(t),this.bindToMotionValue(t,e),this.values.set(t,e),this.latestValues[t]=e.get())}removeValue(t){this.values.delete(t);const e=this.valueSubscriptions.get(t);e&&(e(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,e){if(this.props.values&&this.props.values[t])return this.props.values[t];let i=this.values.get(t);return void 0===i&&void 0!==e&&(i=Ji(null===e?void 0:e,{owner:this}),this.addValue(t,i)),i}readValue(t,e){let i=void 0===this.latestValues[t]&&this.current?this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options):this.latestValues[t];var s;return null!=i&&("string"==typeof i&&(G(i)||_(i))?i=parseFloat(i):(s=i,!ms.find(Oi(s))&&Zt.test(e)&&(i=Gi(t,e))),this.setBaseTarget(t,d(i)?i.get():i)),d(i)?i.get():i}setBaseTarget(t,e){this.baseTarget[t]=e}getBaseTarget(t){const{initial:e}=this.props;let i;if("string"==typeof e||"object"==typeof e){const s=P(this.props,e,this.presenceContext?.custom);s&&(i=s[t])}if(e&&void 0!==i)return i;const s=this.getBaseTargetFromProps(this.props,t);return void 0===s||d(s)?void 0!==this.initialValues[t]&&void 0===i?void 0:this.baseTarget[t]:s}on(t,e){return this.events[t]||(this.events[t]=new it),this.events[t].add(e)}notify(t,...e){this.events[t]&&this.events[t].notify(...e)}scheduleRenderMicrotask(){Qi.render(this.render)}}class Mo extends Vo{constructor(){super(...arguments),this.KeyframeResolver=_i}sortInstanceNodePosition(t,e){return 2&t.compareDocumentPosition(e)?1:-1}getBaseTargetFromProps(t,e){return t.style?t.style[e]:void 0}removeValueFromRenderState(t,{vars:e,style:i}){delete e[t],delete i[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;d(t)&&(this.childSubscription=t.on("change",t=>{this.current&&(this.current.textContent=`${t}`)}))}}function Do(t,{style:e,vars:i},s,n){const o=t.style;let r;for(r in e)o[r]=e[r];for(r in n?.applyProjectionStyles(o,s),i)o.setProperty(r,i[r])}class Co extends Mo{constructor(){super(...arguments),this.type="html",this.renderInstance=Do}readValueFromInstance(t,e){if(c.has(e))return this.projection?.isProjecting?ii(e):((t,e)=>{const{transform:i="none"}=getComputedStyle(t);return si(i,e)})(t,e);{const s=(i=t,window.getComputedStyle(i)),n=(w(e)?s.getPropertyValue(e):s[e])||0;return"string"==typeof n?n.trim():n}var i}measureInstanceViewportBox(t,{transformPagePoint:e}){return Gs(t,e)}build(t,e,i){S(t,e,i.transformTemplate)}scrapeMotionValuesFromProps(t,e,i){return A(t,e,i)}}let ko=!1;class Ro extends ${componentDidMount(){const{visualElement:t,layoutGroup:e,switchLayoutGroup:i,layoutId:s}=this.props,{projection:n}=t;M(jo),n&&(e.group&&e.group.add(n),i&&i.register&&s&&i.register(n),ko&&n.root.didUpdate(),n.addEventListener("animationComplete",()=>{this.safeToRemove()}),n.setOptions({...n.options,onExitComplete:()=>this.safeToRemove()})),Wn.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:e,visualElement:i,drag:s,isPresent:n}=this.props,{projection:o}=i;return o?(o.isPresent=n,ko=!0,s||t.layoutDependency!==e||void 0===e||t.isPresent!==n?o.willUpdate():this.safeToRemove(),t.isPresent!==n&&(n?o.promote():o.relegate()||Et.postRender(()=>{const t=o.getStack();t&&t.members.length||this.safeToRemove()})),null):null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),Qi.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:e,switchLayoutGroup:i}=this.props,{projection:s}=t;ko=!0,s&&(s.scheduleCheckAfterUnmount(),e&&e.group&&e.group.remove(s),i&&i.deregister&&i.deregister(s))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function Lo(t){const[e,i]=function(t=!0){const e=U(b);if(null===e)return[!0,null];const{isPresent:i,onExitComplete:s,register:n}=e,o=N();K(()=>{if(t)return n(o)},[t]);const r=W(()=>t&&s&&s(o),[o,s,t]);return!i&&s?[!1,r]:[!0]}(),s=U(E);return O(Ro,{...t,layoutGroup:s,switchLayoutGroup:U(V),isPresent:e,safeToRemove:i})}const jo={borderRadius:{...Po,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Po,borderTopRightRadius:Po,borderBottomLeftRadius:Po,borderBottomRightRadius:Po,boxShadow:wo},Bo={pan:{Feature:class extends fs{constructor(){super(...arguments),this.removePointerDownListener=J}onPointerDown(t){this.session=new Js(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:qs(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:e,onPan:i,onPanEnd:s}=this.node.getProps();return{onSessionStart:mn(t),onStart:mn(e),onMove:i,onEnd:(t,e)=>{delete this.session,s&&Et.postRender(()=>s(t,e))}}}mount(){this.removePointerDownListener=As(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}},drag:{Feature:class extends fs{constructor(t){super(t),this.removeGroupControls=J,this.removeListeners=J,this.controls=new dn(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||J}unmount(){this.removeGroupControls(),this.removeListeners()}},ProjectionNode:xo,MeasureLayout:Lo}},Fo={layout:{ProjectionNode:xo,MeasureLayout:Lo}};function Io(t,e,i){const s=t.getProps();return P(s,e,void 0!==i?i:s.custom,t)}const Oo=t=>Array.isArray(t);function Uo(t,e,i){t.hasValue(e)?t.getValue(e).set(i):t.addValue(e,Ji(i))}function No(t){return Oo(t)?t[t.length-1]||0:t}function Ko({protectedKeys:t,needsAnimating:e},i){const s=t.hasOwnProperty(i)&&!0!==e[i];return e[i]=!1,s}function Wo(t,e,{delay:i=0,transitionOverride:s,type:n}={}){let{transition:o=t.getDefaultTransition(),transitionEnd:r,...a}=e;s&&(o=s);const l=[],h=n&&t.animationState&&t.animationState.getState()[n];for(const e in a){const s=t.getValue(e,t.latestValues[e]??null),n=a[e];if(void 0===n||h&&Ko(h,e))continue;const r={delay:i,...Fi(o||{},e)},u=s.get();if(void 0!==u&&!s.isAnimating&&!Array.isArray(n)&&n===u&&!r.velocity)continue;let c=!1;if(window.MotionHandoffAnimation){const i=fn(t);if(i){const t=window.MotionHandoffAnimation(i,e,Et);null!==t&&(r.startTime=t,c=!0)}}_s(t,e),s.start(Ps(e,s,n,t.shouldReduceMotion&&Ii.has(e)?{type:!1}:r,t,c));const d=s.animation;d&&l.push(d)}return r&&Promise.all(l).then(()=>{Et.update(()=>{r&&function(t,e){const i=Io(t,e);let{transitionEnd:s={},transition:n={},...o}=i||{};o={...o,...s};for(const e in o)Uo(t,e,No(o[e]))}(t,r)})}),l}function $o(t,e,i,s=0,n=1){const o=Array.from(t).sort((t,e)=>t.sortNodePosition(e)).indexOf(e),r=t.size,a=(r-1)*s;return"function"==typeof i?i(o,r):1===n?o*s:a-o*s}function zo(t,e,i={}){const s=Io(t,e,"exit"===i.type?t.presenceContext?.custom:void 0);let{transition:n=t.getDefaultTransition()||{}}=s||{};i.transitionOverride&&(n=i.transitionOverride);const o=s?()=>Promise.all(Wo(t,s,i)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(s=0)=>{const{delayChildren:o=0,staggerChildren:r,staggerDirection:a}=n;return function(t,e,i=0,s=0,n=0,o=1,r){const a=[];for(const l of t.variantChildren)l.notify("AnimationStart",e),a.push(zo(l,e,{...r,delay:i+("function"==typeof s?0:s)+$o(t.variantChildren,l,s,n,o)}).then(()=>l.notify("AnimationComplete",e)));return Promise.all(a)}(t,e,s,o,r,a,i)}:()=>Promise.resolve(),{when:a}=n;if(a){const[t,e]="beforeChildren"===a?[o,r]:[r,o];return t().then(()=>e())}return Promise.all([o(),r(i.delay)])}function Yo(t,e){if(!Array.isArray(e))return!1;const i=e.length;if(i!==t.length)return!1;for(let s=0;sPromise.all(e.map(({animation:e,options:i})=>function(t,e,i={}){let s;if(t.notify("AnimationStart",e),Array.isArray(e)){const n=e.map(e=>zo(t,e,i));s=Promise.all(n)}else if("string"==typeof e)s=zo(t,e,i);else{const n="function"==typeof e?Io(t,e,i.custom):e;s=Promise.all(Wo(t,n,i))}return s.then(()=>{t.notify("AnimationComplete",e)})}(t,e,i)))}function Zo(t){let e=_o(t),i=tr(),s=!0;const n=e=>(i,s)=>{const n=Io(t,s,"exit"===e?t.presenceContext?.custom:void 0);if(n){const{transition:t,transitionEnd:e,...s}=n;i={...i,...s,...e}}return i};function o(o){const{props:r}=t,a=Ho(t.parent)||{},l=[],h=new Set;let u={},c=1/0;for(let e=0;ec&&f,T=!1;const P=Array.isArray(m)?m:[m];let w=P.reduce(n(d),{});!1===y&&(w={});const{prevResolvedValues:S={}}=p,A={...S,...w},b=e=>{x=!0,h.has(e)&&(T=!0,h.delete(e)),p.needsAnimating[e]=!0;const i=t.getValue(e);i&&(i.liveStyle=!1)};for(const t in A){const e=w[t],i=S[t];if(u.hasOwnProperty(t))continue;let s=!1;s=Oo(e)&&Oo(i)?!Yo(e,i):e!==i,s?null!=e?b(t):h.add(t):void 0!==e&&h.has(t)?b(t):p.protectedKeys[t]=!0}p.prevProp=m,p.prevResolvedValues=w,p.isActive&&(u={...u,...w}),s&&t.blockInitialAnimation&&(x=!1);const E=g&&v;x&&(!E||T)&&l.push(...P.map(e=>{const i={type:d};if("string"==typeof e&&s&&!E&&t.manuallyAnimateOnMount&&t.parent){const{parent:s}=t,n=Io(s,e);if(s.enteringChildren&&n){const{delayChildren:e}=n.transition||{};i.delay=$o(s.enteringChildren,t,e)}}return{animation:e,options:i}}))}if(h.size){const e={};if("boolean"!=typeof r.initial){const i=Io(t,Array.isArray(r.initial)?r.initial[0]:r.initial);i&&i.transition&&(e.transition=i.transition)}h.forEach(i=>{const s=t.getBaseTarget(i),n=t.getValue(i);n&&(n.liveStyle=!0),e[i]=s??null}),l.push({animation:e})}let d=Boolean(l.length);return!s||!1!==r.initial&&r.initial!==r.animate||t.manuallyAnimateOnMount||(d=!1),s=!1,d?e(l):Promise.resolve()}return{animateChanges:o,setActive:function(e,s){if(i[e].isActive===s)return Promise.resolve();t.variantChildren?.forEach(t=>t.animationState?.setActive(e,s)),i[e].isActive=s;const n=o(e);for(const t in i)i[t].protectedKeys={};return n},setAnimateFunction:function(i){e=i(t)},getState:()=>i,reset:()=>{i=tr(),s=!0}}}function Jo(t,e){return"string"==typeof e?e!==t:!!Array.isArray(e)&&!Yo(e,t)}function Qo(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function tr(){return{animate:Qo(!0),whileInView:Qo(),whileHover:Qo(),whileTap:Qo(),whileDrag:Qo(),whileFocus:Qo(),exit:Qo()}}let er=0;const ir={animation:{Feature:class extends fs{constructor(t){super(t),t.animationState||(t.animationState=Zo(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();k(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:e}=this.node.prevProps||{};t!==e&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}},exit:{Feature:class extends fs{constructor(){super(...arguments),this.id=er++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:e}=this.node.presenceContext,{isPresent:i}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===i)return;const s=this.node.animationState.setActive("exit",!t);e&&!t&&s.then(()=>{e(this.id)})}mount(){const{register:t,onExitComplete:e}=this.node.presenceContext||{};e&&e(this.id),t&&(this.unmount=t(this.id))}unmount(){}}}};function sr(t,e,i){const{props:s}=t;t.animationState&&s.whileHover&&t.animationState.setActive("whileHover","Start"===i);const n=s["onHover"+i];n&&Et.postRender(()=>n(e,Ss(e)))}function nr(t,e,i){const{props:s}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&s.whileTap&&t.animationState.setActive("whileTap","Start"===i);const n=s["onTap"+("End"===i?"":i)];n&&Et.postRender(()=>n(e,Ss(e)))}const or=new WeakMap,rr=new WeakMap,ar=t=>{const e=or.get(t.target);e&&e(t)},lr=t=>{t.forEach(ar)};function hr(t,e,i){const s=function({root:t,...e}){const i=t||document;rr.has(i)||rr.set(i,{});const s=rr.get(i),n=JSON.stringify(e);return s[n]||(s[n]=new IntersectionObserver(lr,{root:t,...e})),s[n]}(e);return or.set(t,i),s.observe(t),()=>{or.delete(t),s.unobserve(t)}}const ur={some:0,all:1};const cr={inView:{Feature:class extends fs{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:e,margin:i,amount:s="some",once:n}=t,o={root:e?e.current:void 0,rootMargin:i,threshold:"number"==typeof s?s:ur[s]};return hr(this.node.current,o,t=>{const{isIntersecting:e}=t;if(this.isInView===e)return;if(this.isInView=e,n&&!e&&this.hasEnteredView)return;e&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",e);const{onViewportEnter:i,onViewportLeave:s}=this.node.getProps(),o=e?i:s;o&&o(t)})}mount(){this.startObserver()}update(){if("undefined"==typeof IntersectionObserver)return;const{props:t,prevProps:e}=this.node;["amount","margin","root"].some(function({viewport:t={}},{viewport:e={}}={}){return i=>t[i]!==e[i]}(t,e))&&this.startObserver()}unmount(){}}},tap:{Feature:class extends fs{mount(){const{current:t}=this.node;t&&(this.unmount=ds(t,(t,e)=>(nr(this.node,e,"Start"),(t,{success:e})=>nr(this.node,t,e?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}},focus:{Feature:class extends fs{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch(e){t=!0}t&&this.node.animationState&&(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){this.isActive&&this.node.animationState&&(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=tt(ws(this.node.current,"focus",()=>this.onFocus()),ws(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}},hover:{Feature:class extends fs{mount(){const{current:t}=this.node;t&&(this.unmount=function(t,e,i={}){const[s,n,o]=ss(t,i),r=t=>{if(!ns(t))return;const{target:i}=t,s=e(i,t);if("function"!=typeof s||!i)return;const o=t=>{ns(t)&&(s(t),i.removeEventListener("pointerleave",o))};i.addEventListener("pointerleave",o,n)};return s.forEach(t=>{t.addEventListener("pointerenter",r,n)}),o}(t,(t,e)=>(sr(this.node,e,"Start"),t=>sr(this.node,t,"End"))))}unmount(){}}}},dr=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);class pr extends Mo{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Rs}getBaseTargetFromProps(t,e){return t[e]}readValueFromInstance(t,e){if(c.has(e)){const t=Hi(e);return t&&t.default||0}return e=dr.has(e)?e:L(e),t.getAttribute(e)}scrapeMotionValuesFromProps(t,e,i){return j(t,e,i)}build(t,e,i){B(t,e,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(t,e,i,s){!function(t,e,i,s){Do(t,e,void 0,s);for(const i in e.attrs)t.setAttribute(dr.has(i)?i:L(i),e.attrs[i])}(t,e,0,s)}mount(t){this.isSVGTag=F(t.tagName),super.mount(t)}}const mr={renderer:(t,e)=>I(t)?new pr(e):new Co(e,{allowProjection:t!==z}),...ir,...cr},fr={...mr,...Bo,...Fo};export{fr as domMax}; diff --git a/frontend/node_modules/framer-motion/dist/size-rollup-m.js b/frontend/node_modules/framer-motion/dist/size-rollup-m.js new file mode 100644 index 0000000000000000000000000000000000000000..300bab421ec971692674f35b7577924afa6b1808 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/size-rollup-m.js @@ -0,0 +1 @@ +import{jsxs as t,jsx as n}from"react/jsx-runtime";import{createContext as o,useContext as r,useMemo as e,Fragment as a,createElement as i,useRef as s,useCallback as c,useLayoutEffect as l,useEffect as u,useInsertionEffect as f,forwardRef as d}from"react";const m=o({}),p=o({strict:!1}),y=o({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"}),g=o({});function h(t){return null!==t&&"object"==typeof t&&"function"==typeof t.start}function v(t){return"string"==typeof t||Array.isArray(t)}const w=["initial","animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"];function b(t){return h(t.animate)||w.some(n=>v(t[n]))}function S(t){const{initial:n,animate:o}=function(t,n){if(b(t)){const{initial:n,animate:o}=t;return{initial:!1===n||v(n)?n:void 0,animate:v(o)?o:void 0}}return!1!==t.inherit?n:{}}(t,r(g));return e(()=>({initial:n,animate:o}),[x(n),x(o)])}function x(t){return Array.isArray(t)?t.join(" "):t}const M=(t=>n=>"string"==typeof n&&n.startsWith(t))("--"),P={test:t=>"number"==typeof t,parse:parseFloat,transform:t=>t},T={...P,transform:t=>((t,n,o)=>o>n?n:o({test:n=>"string"==typeof n&&n.endsWith(t)&&1===n.split(" ").length,parse:parseFloat,transform:n=>`${n}${t}`}),W=O("deg"),C=O("%"),E=O("px"),L=(()=>({...C,parse:t=>C.parse(t)/100,transform:t=>C.transform(100*t)}))(),A=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],V=(()=>new Set(A))(),j={...P,transform:Math.round},B={borderWidth:E,borderTopWidth:E,borderRightWidth:E,borderBottomWidth:E,borderLeftWidth:E,borderRadius:E,radius:E,borderTopLeftRadius:E,borderTopRightRadius:E,borderBottomRightRadius:E,borderBottomLeftRadius:E,width:E,maxWidth:E,height:E,maxHeight:E,top:E,right:E,bottom:E,left:E,padding:E,paddingTop:E,paddingRight:E,paddingBottom:E,paddingLeft:E,margin:E,marginTop:E,marginRight:E,marginBottom:E,marginLeft:E,backgroundPositionX:E,backgroundPositionY:E,...{rotate:W,rotateX:W,rotateY:W,rotateZ:W,scale:k,scaleX:k,scaleY:k,scaleZ:k,skew:W,skewX:W,skewY:W,distance:E,translateX:E,translateY:E,translateZ:E,x:E,y:E,z:E,perspective:E,transformPerspective:E,opacity:T,originX:L,originY:L,originZ:E},zIndex:j,fillOpacity:T,strokeOpacity:T,numOctaves:j},I=(t,n)=>n&&"number"==typeof t?n.transform(t):t,R=t=>Boolean(t&&t.getVelocity),X={};function Y(t,{layout:n,layoutId:o}){return V.has(t)||t.startsWith("origin")||(n||void 0!==o)&&(!!X[t]||"opacity"===t)}const $={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},D=A.length;function H(t,n,o){const{style:r,vars:e,transformOrigin:a}=t;let i=!1,s=!1;for(const t in n){const o=n[t];if(V.has(t))i=!0;else if(M(t))e[t]=o;else{const n=I(o,B[t]);t.startsWith("origin")?(s=!0,a[t]=n):r[t]=n}}if(n.transform||(i||o?r.transform=function(t,n,o){let r="",e=!0;for(let a=0;a({style:{},transform:{},transformOrigin:{},vars:{}});function Z(t,n,o){for(const r in n)R(n[r])||Y(r,o)||(t[r]=n[r])}function z(t,n){const o={};return Z(o,t.style||{},t),Object.assign(o,function({transformTemplate:t},n){return e(()=>{const o={style:{},transform:{},transformOrigin:{},vars:{}};return H(o,n,t),Object.assign({},o.vars,o.style)},[n])}(t,n)),o}function N(t,n){const o={},r=z(t,n);return t.drag&&!1!==t.dragListener&&(o.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout="none",r.touchAction=!0===t.drag?"none":"pan-"+("x"===t.drag?"y":"x")),void 0===t.tabIndex&&(t.onTap||t.onTapStart||t.whileTap)&&(o.tabIndex=0),o.style=r,o}const U={offset:"stroke-dashoffset",array:"stroke-dasharray"},q={offset:"strokeDashoffset",array:"strokeDasharray"};function _(t,{attrX:n,attrY:o,attrScale:r,pathLength:e,pathSpacing:a=1,pathOffset:i=0,...s},c,l,u){if(H(t,s,l),c)return void(t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox));t.attrs=t.style,t.style={};const{attrs:f,style:d}=t;f.transform&&(d.transform=f.transform,delete f.transform),(d.transform||f.transformOrigin)&&(d.transformOrigin=f.transformOrigin??"50% 50%",delete f.transformOrigin),d.transform&&(d.transformBox=u?.transformBox??"fill-box",delete f.transformBox),void 0!==n&&(f.x=n),void 0!==o&&(f.y=o),void 0!==r&&(f.scale=r),void 0!==e&&function(t,n,o=1,r=0,e=!0){t.pathLength=1;const a=e?U:q;t[a.offset]=E.transform(-r);const i=E.transform(n),s=E.transform(o);t[a.array]=`${i} ${s}`}(f,e,a,i,!1)}const G=()=>({style:{},transform:{},transformOrigin:{},vars:{},attrs:{}});function J(t,n,o,r){const a=e(()=>{const o={style:{},transform:{},transformOrigin:{},vars:{},attrs:{}};var e;return _(o,n,"string"==typeof(e=r)&&"svg"===e.toLowerCase(),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[n]);if(t.style){const n={};Z(n,t.style,t),a.style={...n,...a.style}}return a}const K=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function Q(t){return t.startsWith("while")||t.startsWith("drag")&&"draggable"!==t||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||K.has(t)}let tt=t=>!Q(t);try{"function"==typeof(nt=require("@emotion/is-prop-valid").default)&&(tt=t=>t.startsWith("on")?!Q(t):nt(t))}catch{}var nt;const ot=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function rt(t){return"string"==typeof t&&!t.includes("-")&&!!(ot.indexOf(t)>-1||/[A-Z]/u.test(t))}function et(t,n,o,{latestValues:r},s,c=!1){const l=(rt(t)?J:N)(n,r,s,t),u=function(t,n,o){const r={};for(const e in t)"values"===e&&"object"==typeof t.values||(tt(e)||!0===o&&Q(e)||!n&&!Q(e)||t.draggable&&e.startsWith("onDrag"))&&(r[e]=t[e]);return r}(n,"string"==typeof t,c),f=t!==a?{...u,...l,ref:o}:{},{children:d}=n,m=e(()=>R(d)?d.get():d,[d]);return i(t,{...f,children:m})}const at=o(null);function it(t){const n=[{},{}];return t?.values.forEach((t,o)=>{n[0][o]=t.get(),n[1][o]=t.getVelocity()}),n}function st(t,n,o,r){if("function"==typeof n){const[e,a]=it(r);n=n(void 0!==o?o:t.custom,e,a)}if("string"==typeof n&&(n=t.variants&&t.variants[n]),"function"==typeof n){const[e,a]=it(r);n=n(void 0!==o?o:t.custom,e,a)}return n}function ct(t){return R(t)?t.get():t}function lt(t,n,o,r){const e={},a=r(t,{});for(const t in a)e[t]=ct(a[t]);let{initial:i,animate:s}=t;const c=b(t),l=function(t){return Boolean(b(t)||t.variants)}(t);n&&l&&!c&&!1!==t.inherit&&(void 0===i&&(i=n.initial),void 0===s&&(s=n.animate));let u=!!o&&!1===o.initial;u=u||!1===i;const f=u?s:i;if(f&&"boolean"!=typeof f&&!h(f)){const n=Array.isArray(f)?f:[f];for(let o=0;o(n,o)=>{const e=r(g),a=r(at),i=()=>function({scrapeMotionValuesFromProps:t,createRenderState:n},o,r,e){return{latestValues:lt(o,r,e,t),renderState:n()}}(t,n,e,a);return o?i():function(t){const n=s(null);return null===n.current&&(n.current=t()),n.current}(i)};function ft(t,n,o){const{style:r}=t,e={};for(const a in r)(R(r[a])||n.style&&R(n.style[a])||Y(a,t)||void 0!==o?.getValue(a)?.liveStyle)&&(e[a]=r[a]);return e}const dt=ut({scrapeMotionValuesFromProps:ft,createRenderState:F});const mt=ut({scrapeMotionValuesFromProps:function(t,n,o){const r=ft(t,n,o);for(const o in t)if(R(t[o])||R(n[o])){r[-1!==A.indexOf(o)?"attr"+o.charAt(0).toUpperCase()+o.substring(1):o]=t[o]}return r},createRenderState:G}),pt="undefined"!=typeof window,yt={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},gt={};for(const t in yt)gt[t]={isEnabled:n=>yt[t].some(t=>!!n[t])};const ht=Symbol.for("motionComponentSymbol");function vt(t){return t&&"object"==typeof t&&Object.prototype.hasOwnProperty.call(t,"current")}function wt(t,n,o){return c(r=>{r&&t.onMount&&t.onMount(r),n&&(r?n.mount(r):n.unmount()),o&&("function"==typeof o?o(r):vt(o)&&(o.current=r))},[n])}const bt="data-"+"framerAppearId".replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase();const St=o({}),xt=pt?l:u;function Mt(t,n,o,e,a){const{visualElement:i}=r(g),c=r(p),l=r(at),d=r(y).reducedMotion,m=s(null);e=e||c.renderer,!m.current&&e&&(m.current=e(t,{visualState:n,parent:i,props:o,presenceContext:l,blockInitialAnimation:!!l&&!1===l.initial,reducedMotionConfig:d}));const h=m.current,v=r(St);!h||h.projection||!a||"html"!==h.type&&"svg"!==h.type||function(t,n,o,r){const{layoutId:e,layout:a,drag:i,dragConstraints:s,layoutScroll:c,layoutRoot:l,layoutCrossfade:u}=n;t.projection=new o(t.latestValues,n["data-framer-portal-id"]?void 0:Pt(t.parent)),t.projection.setOptions({layoutId:e,layout:a,alwaysMeasureLayout:Boolean(i)||s&&vt(s),visualElement:t,animationType:"string"==typeof a?a:"both",initialPromotionConfig:r,crossfade:u,layoutScroll:c,layoutRoot:l})}(m.current,o,a,v);const w=s(!1);f(()=>{h&&w.current&&h.update(o,l)});const b=o[bt],S=s(Boolean(b)&&!window.MotionHandoffIsComplete?.(b)&&window.MotionHasOptimisedAnimation?.(b));return xt(()=>{h&&(w.current=!0,window.MotionIsMounted=!0,h.updateFeatures(),h.scheduleRenderMicrotask(),S.current&&h.animationState&&h.animationState.animateChanges())}),u(()=>{h&&(!S.current&&h.animationState&&h.animationState.animateChanges(),S.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(b)}),S.current=!1),h.enteringChildren=void 0)}),h}function Pt(t){if(t)return!1!==t.options.allowProjection?t.projection:Pt(t.parent)}function Tt(o,{forwardMotionProps:e=!1}={},a,i){a&&function(t){for(const n in t)gt[n]={...gt[n],...t[n]}}(a);const s=rt(o)?mt:dt;function c(a,c){let l;const u={...r(y),...a,layoutId:kt(a)},{isStatic:f}=u,d=S(a),m=s(a,f);if(!f&&pt){r(p).strict;const t=function(t){const{drag:n,layout:o}=gt;if(!n&&!o)return{};const r={...n,...o};return{MeasureLayout:n?.isEnabled(t)||o?.isEnabled(t)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}(u);l=t.MeasureLayout,d.visualElement=Mt(o,m,u,i,t.ProjectionNode)}return t(g.Provider,{value:d,children:[l&&d.visualElement?n(l,{visualElement:d.visualElement,...u}):null,et(o,a,wt(m,d.visualElement,c),m,f,e)]})}c.displayName=`motion.${"string"==typeof o?o:`create(${o.displayName??o.name??""})`}`;const l=d(c);return l[ht]=o,l}function kt({layoutId:t}){const n=r(m).id;return n&&void 0!==t?n+"-"+t:t}function Ot(t,n){return Tt(t,n)}const Wt=Ot("div");export{Wt as MotionDiv}; diff --git a/frontend/node_modules/framer-motion/dist/size-rollup-motion.js b/frontend/node_modules/framer-motion/dist/size-rollup-motion.js new file mode 100644 index 0000000000000000000000000000000000000000..883b3527a47e9d37b5387e562315506bd069cb2f --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/size-rollup-motion.js @@ -0,0 +1 @@ +import{jsxs as t,jsx as e}from"react/jsx-runtime";import{createContext as n,useContext as i,useMemo as s,Fragment as o,createElement as r,useRef as a,useCallback as l,useLayoutEffect as h,useEffect as u,useInsertionEffect as c,forwardRef as d,useId as p,Component as m}from"react";function f(t,e){-1===t.indexOf(e)&&t.push(e)}function y(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const g=(t,e,n)=>n>e?e:n/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function T(t){return"object"==typeof t&&null!==t}const w=t=>/^0[^.\s]+$/u.test(t);function P(t){let e;return()=>(void 0===e&&(e=t()),e)}const S=t=>t,b=(t,e)=>n=>e(t(n)),A=(...t)=>t.reduce(b),E=(t,e,n)=>{const i=e-t;return 0===i?1:(n-t)/i};class V{constructor(){this.subscriptions=[]}add(t){return f(this.subscriptions,t),()=>y(this.subscriptions,t)}notify(t,e,n){const i=this.subscriptions.length;if(i)if(1===i)this.subscriptions[0](t,e,n);else for(let s=0;s1e3*t,C=t=>t/1e3;function D(t,e){return e?t*(1e3/e):0}const k=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t;function R(t,e,n,i){if(t===e&&n===i)return S;const s=e=>function(t,e,n,i,s){let o,r,a=0;do{r=e+(n-e)/2,o=k(r,i,s)-t,o>0?n=r:e=r}while(Math.abs(o)>1e-7&&++a<12);return r}(e,0,1,t,n);return t=>0===t||1===t?t:k(s(t),e,i)}const L=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,j=t=>e=>1-t(1-e),B=R(.33,1.53,.69,.99),F=j(B),O=L(F),I=t=>(t*=2)<1?.5*F(t):.5*(2-Math.pow(2,-10*(t-1))),U=t=>1-Math.sin(Math.acos(t)),N=j(U),W=L(U),$=R(.42,0,1,1),Y=R(0,0,.58,1),X=R(.42,0,.58,1),K=t=>Array.isArray(t)&&"number"==typeof t[0],z={linear:S,easeIn:$,easeInOut:X,easeOut:Y,circIn:U,circInOut:W,circOut:N,backIn:F,backInOut:O,backOut:B,anticipate:I},H=t=>{if(K(t)){t.length;const[e,n,i,s]=t;return R(e,n,i,s)}return"string"==typeof t?z[t]:t},G=n({}),q=n({strict:!1}),Z=n({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"}),_=n({});function J(t){return null!==t&&"object"==typeof t&&"function"==typeof t.start}function Q(t){return"string"==typeof t||Array.isArray(t)}const tt=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],et=["initial",...tt];function nt(t){return J(t.animate)||et.some(e=>Q(t[e]))}function it(t){return Boolean(nt(t)||t.variants)}function st(t){const{initial:e,animate:n}=function(t,e){if(nt(t)){const{initial:e,animate:n}=t;return{initial:!1===e||Q(e)?e:void 0,animate:Q(n)?n:void 0}}return!1!==t.inherit?e:{}}(t,i(_));return s(()=>({initial:e,animate:n}),[ot(e),ot(n)])}function ot(t){return Array.isArray(t)?t.join(" "):t}const rt=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],at={value:null,addProjectionMetrics:null};function lt(t,e){let n=!1,i=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,r=rt.reduce((t,n)=>(t[n]=function(t,e){let n=new Set,i=new Set,s=!1,o=!1;const r=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},l=0;function h(e){r.has(e)&&(u.schedule(e),t()),l++,e(a)}const u={schedule:(t,e=!1,o=!1)=>{const a=o&&s?n:i;return e&&r.add(t),a.has(t)||a.add(t),t},cancel:t=>{i.delete(t),r.delete(t)},process:t=>{a=t,s?o=!0:(s=!0,[n,i]=[i,n],n.forEach(h),e&&at.value&&at.value.frameloop[e].push(l),l=0,n.clear(),s=!1,o&&(o=!1,u.process(t)))}};return u}(o,e?n:void 0),t),{}),{setup:a,read:l,resolveKeyframes:h,preUpdate:u,update:c,preRender:d,render:p,postRender:m}=r,f=()=>{const o=v.useManualTiming?s.timestamp:performance.now();n=!1,v.useManualTiming||(s.delta=i?1e3/60:Math.max(Math.min(o-s.timestamp,40),1)),s.timestamp=o,s.isProcessing=!0,a.process(s),l.process(s),h.process(s),u.process(s),c.process(s),d.process(s),p.process(s),m.process(s),s.isProcessing=!1,n&&e&&(i=!1,t(f))};return{schedule:rt.reduce((e,o)=>{const a=r[o];return e[o]=(e,o=!1,r=!1)=>(n||(n=!0,i=!0,s.isProcessing||t(f)),a.schedule(e,o,r)),e},{}),cancel:t=>{for(let e=0;e(void 0===pt&&ft.set(ct.isProcessing||v.useManualTiming?ct.timestamp:performance.now()),pt),set:t=>{pt=t,queueMicrotask(mt)}},yt=t=>e=>"string"==typeof e&&e.startsWith(t),gt=yt("--"),vt=yt("var(--"),xt=t=>!!vt(t)&&Tt.test(t.split("/*")[0].trim()),Tt=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,wt={test:t=>"number"==typeof t,parse:parseFloat,transform:t=>t},Pt={...wt,transform:t=>g(0,1,t)},St={...wt,default:1},bt=t=>Math.round(1e5*t)/1e5,At=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;const Et=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Vt=(t,e)=>n=>Boolean("string"==typeof n&&Et.test(n)&&n.startsWith(t)||e&&!function(t){return null==t}(n)&&Object.prototype.hasOwnProperty.call(n,e)),Mt=(t,e,n)=>i=>{if("string"!=typeof i)return i;const[s,o,r,a]=i.match(At);return{[t]:parseFloat(s),[e]:parseFloat(o),[n]:parseFloat(r),alpha:void 0!==a?parseFloat(a):1}},Ct={...wt,transform:t=>Math.round((t=>g(0,255,t))(t))},Dt={test:Vt("rgb","red"),parse:Mt("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+Ct.transform(t)+", "+Ct.transform(e)+", "+Ct.transform(n)+", "+bt(Pt.transform(i))+")"};const kt={test:Vt("#"),parse:function(t){let e="",n="",i="",s="";return t.length>5?(e=t.substring(1,3),n=t.substring(3,5),i=t.substring(5,7),s=t.substring(7,9)):(e=t.substring(1,2),n=t.substring(2,3),i=t.substring(3,4),s=t.substring(4,5),e+=e,n+=n,i+=i,s+=s),{red:parseInt(e,16),green:parseInt(n,16),blue:parseInt(i,16),alpha:s?parseInt(s,16)/255:1}},transform:Dt.transform},Rt=t=>({test:e=>"string"==typeof e&&e.endsWith(t)&&1===e.split(" ").length,parse:parseFloat,transform:e=>`${e}${t}`}),Lt=Rt("deg"),jt=Rt("%"),Bt=Rt("px"),Ft=Rt("vh"),Ot=Rt("vw"),It=(()=>({...jt,parse:t=>jt.parse(t)/100,transform:t=>jt.transform(100*t)}))(),Ut={test:Vt("hsl","hue"),parse:Mt("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+jt.transform(bt(e))+", "+jt.transform(bt(n))+", "+bt(Pt.transform(i))+")"},Nt={test:t=>Dt.test(t)||kt.test(t)||Ut.test(t),parse:t=>Dt.test(t)?Dt.parse(t):Ut.test(t)?Ut.parse(t):kt.parse(t),transform:t=>"string"==typeof t?t:t.hasOwnProperty("red")?Dt.transform(t):Ut.transform(t),getAnimatableNone:t=>{const e=Nt.parse(t);return e.alpha=0,Nt.transform(e)}},Wt=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;const $t="number",Yt="color",Xt=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function Kt(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},s=[];let o=0;const r=e.replace(Xt,t=>(Nt.test(t)?(i.color.push(o),s.push(Yt),n.push(Nt.parse(t))):t.startsWith("var(")?(i.var.push(o),s.push("var"),n.push(t)):(i.number.push(o),s.push($t),n.push(parseFloat(t))),++o,"${}")).split("${}");return{values:n,split:r,indexes:i,types:s}}function zt(t){return Kt(t).values}function Ht(t){const{split:e,types:n}=Kt(t),i=e.length;return t=>{let s="";for(let o=0;o"number"==typeof t?0:Nt.test(t)?Nt.getAnimatableNone(t):t;const qt={test:function(t){return isNaN(t)&&"string"==typeof t&&(t.match(At)?.length||0)+(t.match(Wt)?.length||0)>0},parse:zt,createTransformer:Ht,getAnimatableNone:function(t){const e=zt(t);return Ht(t)(e.map(Gt))}};function Zt(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<.5?e:n<2/3?t+(e-t)*(2/3-n)*6:t}function _t(t,e){return n=>n>0?e:t}const Jt=(t,e,n)=>t+(e-t)*n,Qt=(t,e,n)=>{const i=t*t,s=n*(e*e-i)+i;return s<0?0:Math.sqrt(s)},te=[kt,Dt,Ut];function ee(t){const e=(n=t,te.find(t=>t.test(n)));var n;if(!Boolean(e))return!1;let i=e.parse(t);return e===Ut&&(i=function({hue:t,saturation:e,lightness:n,alpha:i}){t/=360,n/=100;let s=0,o=0,r=0;if(e/=100){const i=n<.5?n*(1+e):n+e-n*e,a=2*n-i;s=Zt(a,i,t+1/3),o=Zt(a,i,t),r=Zt(a,i,t-1/3)}else s=o=r=n;return{red:Math.round(255*s),green:Math.round(255*o),blue:Math.round(255*r),alpha:i}}(i)),i}const ne=(t,e)=>{const n=ee(t),i=ee(e);if(!n||!i)return _t(t,e);const s={...n};return t=>(s.red=Qt(n.red,i.red,t),s.green=Qt(n.green,i.green,t),s.blue=Qt(n.blue,i.blue,t),s.alpha=Jt(n.alpha,i.alpha,t),Dt.transform(s))},ie=new Set(["none","hidden"]);function se(t,e){return n=>Jt(t,e,n)}function oe(t){return"number"==typeof t?se:"string"==typeof t?xt(t)?_t:Nt.test(t)?ne:le:Array.isArray(t)?re:"object"==typeof t?Nt.test(t)?ne:ae:_t}function re(t,e){const n=[...t],i=n.length,s=t.map((t,n)=>oe(t)(t,e[n]));return t=>{for(let e=0;e{for(const e in i)n[e]=i[e](t);return n}}const le=(t,e)=>{const n=qt.createTransformer(e),i=Kt(t),s=Kt(e);return i.indexes.var.length===s.indexes.var.length&&i.indexes.color.length===s.indexes.color.length&&i.indexes.number.length>=s.indexes.number.length?ie.has(t)&&!s.values.length||ie.has(e)&&!i.values.length?function(t,e){return ie.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}(t,e):A(re(function(t,e){const n=[],i={color:0,var:0,number:0};for(let s=0;s{const e=({timestamp:e})=>t(e);return{start:(t=!0)=>ht.update(e,t),stop:()=>ut(e),now:()=>ct.isProcessing?ct.timestamp:ft.now()}},ce=(t,e,n=10)=>{let i="";const s=Math.max(Math.round(e/n),2);for(let e=0;e=de?1/0:e}function me(t,e,n){const i=Math.max(e-5,0);return D(n-t(i),e-i)}const fe=100,ye=10,ge=1,ve=0,xe=800,Te=.3,we=.3,Pe={granular:.01,default:2},Se={granular:.005,default:.5},be=.01,Ae=10,Ee=.05,Ve=1,Me=.001;function Ce({duration:t=xe,bounce:e=Te,velocity:n=ve,mass:i=ge}){let s,o,r=1-e;r=g(Ee,Ve,r),t=g(be,Ae,C(t)),r<1?(s=e=>{const i=e*r,s=i*t,o=i-n,a=ke(e,r),l=Math.exp(-s);return Me-o/a*l},o=e=>{const i=e*r*t,o=i*n+n,a=Math.pow(r,2)*Math.pow(e,2)*t,l=Math.exp(-i),h=ke(Math.pow(e,2),r);return(-s(e)+Me>0?-1:1)*((o-a)*l)/h}):(s=e=>Math.exp(-e*t)*((e-n)*t+1)-.001,o=e=>Math.exp(-e*t)*(t*t*(n-e)));const a=function(t,e,n){let i=n;for(let n=1;nvoid 0!==t[e])}function Be(t=we,e=Te){const n="object"!=typeof t?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:i,restDelta:s}=n;const o=n.keyframes[0],r=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:l,damping:h,mass:u,duration:c,velocity:d,isResolvedFromDuration:p}=function(t){let e={velocity:ve,stiffness:fe,damping:ye,mass:ge,isResolvedFromDuration:!1,...t};if(!je(t,Le)&&je(t,Re))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(1.2*n),s=i*i,o=2*g(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:ge,stiffness:s,damping:o}}else{const n=Ce(t);e={...e,...n,mass:ge},e.isResolvedFromDuration=!0}return e}({...n,velocity:-C(n.velocity||0)}),m=d||0,f=h/(2*Math.sqrt(l*u)),y=r-o,v=C(Math.sqrt(l/u)),x=Math.abs(y)<5;let T;if(i||(i=x?Pe.granular:Pe.default),s||(s=x?Se.granular:Se.default),f<1){const t=ke(v,f);T=e=>{const n=Math.exp(-f*v*e);return r-n*((m+f*v*y)/t*Math.sin(t*e)+y*Math.cos(t*e))}}else if(1===f)T=t=>r-Math.exp(-v*t)*(y+(m+v*y)*t);else{const t=v*Math.sqrt(f*f-1);T=e=>{const n=Math.exp(-f*v*e),i=Math.min(t*e,300);return r-n*((m+f*v*y)*Math.sinh(i)+t*y*Math.cosh(i))/t}}const w={calculatedDuration:p&&c||null,next:t=>{const e=T(t);if(p)a.done=t>=c;else{let n=0===t?m:0;f<1&&(n=0===t?M(m):me(T,t,e));const o=Math.abs(n)<=i,l=Math.abs(r-e)<=s;a.done=o&&l}return a.value=a.done?r:e,a},toString:()=>{const t=Math.min(pe(w),de),e=ce(e=>w.next(t*e).value,t,30);return t+"ms "+e},toTransition:()=>{}};return w}function Fe({keyframes:t,velocity:e=0,power:n=.8,timeConstant:i=325,bounceDamping:s=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:l,restDelta:h=.5,restSpeed:u}){const c=t[0],d={done:!1,value:c},p=t=>void 0===a?l:void 0===l||Math.abs(a-t)-m*Math.exp(-t/i),v=t=>y+g(t),x=t=>{const e=g(t),n=v(t);d.done=Math.abs(e)<=h,d.value=d.done?y:n};let T,w;const P=t=>{var e;(e=d.value,void 0!==a&&el)&&(T=t,w=Be({keyframes:[d.value,p(d.value)],velocity:me(v,t,d.value),damping:s,stiffness:o,restDelta:h,restSpeed:u}))};return P(0),{calculatedDuration:null,next:t=>{let e=!1;return w||void 0!==T||(e=!0,x(t),P(t)),void 0!==T&&t>=T?w.next(t-T):(!e&&x(t),d)}}}function Oe(t,e,{clamp:n=!0,ease:i,mixer:s}={}){const o=t.length;if(e.length,1===o)return()=>e[0];if(2===o&&e[0]===e[1])return()=>e[1];const r=t[0]===t[1];t[0]>t[o-1]&&(t=[...t].reverse(),e=[...e].reverse());const a=function(t,e,n){const i=[],s=n||v.mix||he,o=t.length-1;for(let n=0;n{if(r&&n1)for(;ih(g(t[0],t[o-1],e)):h}function Ie(t){const e=[0];return function(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const s=E(0,e,i);t.push(Jt(n,1,s))}}(e,t.length-1),e}function Ue({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const s=(t=>Array.isArray(t)&&"number"!=typeof t[0])(i)?i.map(H):H(i),o={done:!1,value:e[0]},r=function(t,e){return t.map(t=>t*e)}(n&&n.length===e.length?n:Ie(e),t),a=Oe(r,e,{ease:Array.isArray(s)?s:(l=e,h=s,l.map(()=>h||X).splice(0,l.length-1))});var l,h;return{calculatedDuration:t,next:e=>(o.value=a(e),o.done=e>=t,o)}}Be.applyToOptions=t=>{const e=function(t,e=100,n){const i=n({...t,keyframes:[0,e]}),s=Math.min(pe(i),de);return{type:"keyframes",ease:t=>i.next(s*t).value/e,duration:C(s)}}(t,100,Be);return t.ease=e.ease,t.duration=M(e.duration),t.type="keyframes",t};const Ne=t=>null!==t;function We(t,{repeat:e,repeatType:n="loop"},i,s=1){const o=t.filter(Ne),r=s<0||e&&"loop"!==n&&e%2==1?0:o.length-1;return r&&void 0!==i?i:o[r]}const $e={decay:Fe,inertia:Fe,tween:Ue,keyframes:Ue,spring:Be};function Ye(t){"string"==typeof t.type&&(t.type=$e[t.type])}class Xe{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,e){return this.finished.then(t,e)}}const Ke=t=>t/100;class ze extends Xe{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:t}=this.options;t&&t.updatedAt!==ft.now()&&this.tick(ft.now()),this.isStopped=!0,"idle"!==this.state&&(this.teardown(),this.options.onStop?.())},this.options=t,this.initAnimation(),this.play(),!1===t.autoplay&&this.pause()}initAnimation(){const{options:t}=this;Ye(t);const{type:e=Ue,repeat:n=0,repeatDelay:i=0,repeatType:s,velocity:o=0}=t;let{keyframes:r}=t;const a=e||Ue;a!==Ue&&"number"!=typeof r[0]&&(this.mixKeyframes=A(Ke,he(r[0],r[1])),r=[0,100]);const l=a({...t,keyframes:r});"mirror"===s&&(this.mirroredGenerator=a({...t,keyframes:[...r].reverse(),velocity:-o})),null===l.calculatedDuration&&(l.calculatedDuration=pe(l));const{calculatedDuration:h}=l;this.calculatedDuration=h,this.resolvedDuration=h+i,this.totalDuration=this.resolvedDuration*(n+1)-i,this.generator=l}updateTime(t){const e=Math.round(t-this.startTime)*this.playbackSpeed;null!==this.holdTime?this.currentTime=this.holdTime:this.currentTime=e}tick(t,e=!1){const{generator:n,totalDuration:i,mixKeyframes:s,mirroredGenerator:o,resolvedDuration:r,calculatedDuration:a}=this;if(null===this.startTime)return n.next(0);const{delay:l=0,keyframes:h,repeat:u,repeatType:c,repeatDelay:d,type:p,onUpdate:m,finalKeyframe:f}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-i/this.speed,this.startTime)),e?this.currentTime=t:this.updateTime(t);const y=this.currentTime-l*(this.playbackSpeed>=0?1:-1),v=this.playbackSpeed>=0?y<0:y>i;this.currentTime=Math.max(y,0),"finished"===this.state&&null===this.holdTime&&(this.currentTime=i);let x=this.currentTime,T=n;if(u){const t=Math.min(this.currentTime,i)/r;let e=Math.floor(t),n=t%1;!n&&t>=1&&(n=1),1===n&&e--,e=Math.min(e,u+1);Boolean(e%2)&&("reverse"===c?(n=1-n,d&&(n-=d/r)):"mirror"===c&&(T=o)),x=g(0,1,n)*r}const w=v?{done:!1,value:h[0]}:T.next(x);s&&(w.value=s(w.value));let{done:P}=w;v||null===a||(P=this.playbackSpeed>=0?this.currentTime>=i:this.currentTime<=0);const S=null===this.holdTime&&("finished"===this.state||"running"===this.state&&P);return S&&p!==Fe&&(w.value=We(h,this.options,f,this.speed)),m&&m(w.value),S&&this.finish(),w}then(t,e){return this.finished.then(t,e)}get duration(){return C(this.calculatedDuration)}get time(){return C(this.currentTime)}set time(t){t=M(t),this.currentTime=t,null===this.startTime||null!==this.holdTime||0===this.playbackSpeed?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime(ft.now());const e=this.playbackSpeed!==t;this.playbackSpeed=t,e&&(this.time=C(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=ue,startTime:e}=this.options;this.driver||(this.driver=t(t=>this.tick(t))),this.options.onPlay?.();const n=this.driver.now();"finished"===this.state?(this.updateFinished(),this.startTime=n):null!==this.holdTime?this.startTime=n-this.holdTime:this.startTime||(this.startTime=e??n),"finished"===this.state&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(ft.now()),this.holdTime=this.currentTime}complete(){"running"!==this.state&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),t.observe(this)}}const He=t=>180*t/Math.PI,Ge=t=>{const e=He(Math.atan2(t[1],t[0]));return Ze(e)},qe={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Ge,rotateZ:Ge,skewX:t=>He(Math.atan(t[1])),skewY:t=>He(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Ze=t=>((t%=360)<0&&(t+=360),t),_e=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Je=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Qe={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:_e,scaleY:Je,scale:t=>(_e(t)+Je(t))/2,rotateX:t=>Ze(He(Math.atan2(t[6],t[5]))),rotateY:t=>Ze(He(Math.atan2(-t[2],t[0]))),rotateZ:Ge,rotate:Ge,skewX:t=>He(Math.atan(t[4])),skewY:t=>He(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function tn(t){return t.includes("scale")?1:0}function en(t,e){if(!t||"none"===t)return tn(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,s;if(n)i=Qe,s=n;else{const e=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=qe,s=e}if(!s)return tn(e);const o=i[e],r=s[1].split(",").map(nn);return"function"==typeof o?o(r):r[o]}function nn(t){return parseFloat(t.trim())}const sn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],on=(()=>new Set(sn))(),rn=t=>t===wt||t===Bt,an=new Set(["x","y","z"]),ln=sn.filter(t=>!an.has(t));const hn={width:({x:t},{paddingLeft:e="0",paddingRight:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),height:({y:t},{paddingTop:e="0",paddingBottom:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>en(e,"x"),y:(t,{transform:e})=>en(e,"y")};hn.translateX=hn.x,hn.translateY=hn.y;const un=new Set;let cn=!1,dn=!1,pn=!1;function mn(){if(dn){const t=Array.from(un).filter(t=>t.needsMeasurement),e=new Set(t.map(t=>t.element)),n=new Map;e.forEach(t=>{const e=function(t){const e=[];return ln.forEach(n=>{const i=t.getValue(n);void 0!==i&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}(t);e.length&&(n.set(t,e),t.render())}),t.forEach(t=>t.measureInitialState()),e.forEach(t=>{t.render();const e=n.get(t);e&&e.forEach(([e,n])=>{t.getValue(e)?.set(n)})}),t.forEach(t=>t.measureEndState()),t.forEach(t=>{void 0!==t.suspendedScrollY&&window.scrollTo(0,t.suspendedScrollY)})}dn=!1,cn=!1,un.forEach(t=>t.complete(pn)),un.clear()}function fn(){un.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(dn=!0)})}class yn{constructor(t,e,n,i,s,o=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=e,this.name=n,this.motionValue=i,this.element=s,this.isAsync=o}scheduleResolve(){this.state="scheduled",this.isAsync?(un.add(this),cn||(cn=!0,ht.read(fn),ht.resolveKeyframes(mn))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:e,element:n,motionValue:i}=this;if(null===t[0]){const s=i?.get(),o=t[t.length-1];if(void 0!==s)t[0]=s;else if(n&&e){const i=n.readValue(e,o);null!=i&&(t[0]=i)}void 0===t[0]&&(t[0]=o),i&&void 0===s&&i.set(t[0])}!function(t){for(let e=1;evoid 0!==window.ScrollTimeline),vn={};function xn(t,e){const n=P(t);return()=>vn[e]??n()}const Tn=xn(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch(t){return!1}return!0},"linearEasing"),wn=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,Pn={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:wn([0,.65,.55,1]),circOut:wn([.55,0,1,.45]),backIn:wn([.31,.01,.66,-.59]),backOut:wn([.33,1.53,.69,.99])};function Sn(t,e){return t?"function"==typeof t?Tn()?ce(t,e):"ease-out":K(t)?wn(t):Array.isArray(t)?t.map(t=>Sn(t,e)||Pn.easeOut):Pn[t]:void 0}function bn(t,e,n,{delay:i=0,duration:s=300,repeat:o=0,repeatType:r="loop",ease:a="easeOut",times:l}={},h=void 0){const u={[e]:n};l&&(u.offset=l);const c=Sn(a,s);Array.isArray(c)&&(u.easing=c);const d={delay:i,duration:s,easing:Array.isArray(c)?"linear":c,fill:"both",iterations:o+1,direction:"reverse"===r?"alternate":"normal"};h&&(d.pseudoElement=h);return t.animate(u,d)}function An(t){return"function"==typeof t&&"applyToOptions"in t}class En extends Xe{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:e,name:n,keyframes:i,pseudoElement:s,allowFlatten:o=!1,finalKeyframe:r,onComplete:a}=t;this.isPseudoElement=Boolean(s),this.allowFlatten=o,this.options=t,t.type;const l=function({type:t,...e}){return An(t)&&Tn()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}(t);this.animation=bn(e,n,i,l,s),!1===l.autoplay&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!s){const t=We(i,this.options,r,this.speed);this.updateMotionValue?this.updateMotionValue(t):function(t,e,n){(t=>t.startsWith("--"))(e)?t.style.setProperty(e,n):t.style[e]=n}(e,n,t),this.animation.cancel()}a?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),"finished"===this.state&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch(t){}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;"idle"!==t&&"finished"!==t&&(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming?.().duration||0;return C(Number(t))}get time(){return C(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=M(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return null!==this.finishedTime?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:e}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&gn()?(this.animation.timeline=t,S):e(this)}}const Vn={anticipate:I,backInOut:O,circInOut:W};function Mn(t){"string"==typeof t.ease&&t.ease in Vn&&(t.ease=Vn[t.ease])}class Cn extends En{constructor(t){Mn(t),Ye(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:e,onUpdate:n,onComplete:i,element:s,...o}=this.options;if(!e)return;if(void 0!==t)return void e.set(t);const r=new ze({...o,autoplay:!1}),a=M(this.finishedTime??this.time);e.setWithVelocity(r.sample(a-10).value,r.sample(a).value,10),r.stop()}}const Dn=(t,e)=>"zIndex"!==e&&(!("number"!=typeof t&&!Array.isArray(t))||!("string"!=typeof t||!qt.test(t)&&"0"!==t||t.startsWith("url(")));function kn(t){t.duration=0,t.type}const Rn=new Set(["opacity","clipPath","filter","transform"]),Ln=P(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));class jn extends Xe{constructor({autoplay:t=!0,delay:e=0,type:n="keyframes",repeat:i=0,repeatDelay:s=0,repeatType:o="loop",keyframes:r,name:a,motionValue:l,element:h,...u}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=ft.now();const c={autoplay:t,delay:e,type:n,repeat:i,repeatDelay:s,repeatType:o,name:a,motionValue:l,element:h,...u},d=h?.KeyframeResolver||yn;this.keyframeResolver=new d(r,(t,e,n)=>this.onKeyframesResolved(t,e,c,!n),a,l,h),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,e,n,i){this.keyframeResolver=void 0;const{name:s,type:o,velocity:r,delay:a,isHandoff:l,onUpdate:h}=n;this.resolvedAt=ft.now(),function(t,e,n,i){const s=t[0];if(null===s)return!1;if("display"===e||"visibility"===e)return!0;const o=t[t.length-1],r=Dn(s,e),a=Dn(o,e);return!(!r||!a)&&(function(t){const e=t[0];if(1===t.length)return!0;for(let n=0;n40?this.resolvedAt:this.createdAt:void 0,finalKeyframe:e,...n,keyframes:t},c=!l&&function(t){const{motionValue:e,name:n,repeatDelay:i,repeatType:s,damping:o,type:r}=t,a=e?.owner?.current;if(!(a instanceof HTMLElement))return!1;const{onUpdate:l,transformTemplate:h}=e.owner.getProps();return Ln()&&n&&Rn.has(n)&&("transform"!==n||!h)&&!l&&!i&&"mirror"!==s&&0!==o&&"inertia"!==r}(u)?new Cn({...u,element:u.motionValue.owner.current}):new ze(u);c.finished.then(()=>this.notifyFinished()).catch(S),this.pendingTimeline&&(this.stopTimeline=c.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=c}get finished(){return this._animation?this.animation.finished:this._finished}then(t,e){return this.finished.finally(t).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),pn=!0,fn(),mn(),pn=!1),this._animation}get duration(){return this.animation.duration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}const Bn=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Fn(t,e,n=1){const[i,s]=function(t){const e=Bn.exec(t);if(!e)return[,];const[,n,i,s]=e;return[`--${n??i}`,s]}(t);if(!i)return;const o=window.getComputedStyle(e).getPropertyValue(i);if(o){const t=o.trim();return x(t)?parseFloat(t):t}return xt(s)?Fn(s,e,n+1):s}function On(t,e){return t?.[e]??t?.default??t}const In=new Set(["width","height","top","left","right","bottom",...sn]),Un=t=>e=>e.test(t),Nn=[wt,Bt,jt,Lt,Ot,Ft,{test:t=>"auto"===t,parse:t=>t}],Wn=t=>Nn.find(Un(t));function $n(t){return"number"==typeof t?0===t:null===t||("none"===t||"0"===t||w(t))}const Yn=new Set(["brightness","contrast","saturate","opacity"]);function Xn(t){const[e,n]=t.slice(0,-1).split("(");if("drop-shadow"===e)return t;const[i]=n.match(At)||[];if(!i)return t;const s=n.replace(i,"");let o=Yn.has(e)?1:0;return i!==n&&(o*=100),e+"("+o+s+")"}const Kn=/\b([a-z-]*)\(.*?\)/gu,zn={...qt,getAnimatableNone:t=>{const e=t.match(Kn);return e?e.map(Xn).join(" "):t}},Hn={...wt,transform:Math.round},Gn={borderWidth:Bt,borderTopWidth:Bt,borderRightWidth:Bt,borderBottomWidth:Bt,borderLeftWidth:Bt,borderRadius:Bt,radius:Bt,borderTopLeftRadius:Bt,borderTopRightRadius:Bt,borderBottomRightRadius:Bt,borderBottomLeftRadius:Bt,width:Bt,maxWidth:Bt,height:Bt,maxHeight:Bt,top:Bt,right:Bt,bottom:Bt,left:Bt,padding:Bt,paddingTop:Bt,paddingRight:Bt,paddingBottom:Bt,paddingLeft:Bt,margin:Bt,marginTop:Bt,marginRight:Bt,marginBottom:Bt,marginLeft:Bt,backgroundPositionX:Bt,backgroundPositionY:Bt,...{rotate:Lt,rotateX:Lt,rotateY:Lt,rotateZ:Lt,scale:St,scaleX:St,scaleY:St,scaleZ:St,skew:Lt,skewX:Lt,skewY:Lt,distance:Bt,translateX:Bt,translateY:Bt,translateZ:Bt,x:Bt,y:Bt,z:Bt,perspective:Bt,transformPerspective:Bt,opacity:Pt,originX:It,originY:It,originZ:Bt},zIndex:Hn,fillOpacity:Pt,strokeOpacity:Pt,numOctaves:Hn},qn={...Gn,color:Nt,backgroundColor:Nt,outlineColor:Nt,fill:Nt,stroke:Nt,borderColor:Nt,borderTopColor:Nt,borderRightColor:Nt,borderBottomColor:Nt,borderLeftColor:Nt,filter:zn,WebkitFilter:zn},Zn=t=>qn[t];function _n(t,e){let n=Zn(t);return n!==zn&&(n=qt),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const Jn=new Set(["auto","none","0"]);class Qn extends yn{constructor(t,e,n,i,s){super(t,e,n,i,s,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:e,name:n}=this;if(!e||!e.current)return;super.readKeyframes();for(let n=0;n{t.getValue(e).set(n)}),this.resolveNoneKeyframes()}}const ti=(t,e)=>e&&"number"==typeof t?e.transform(t):t;class ei{constructor(t,e={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=t=>{const e=ft.now();if(this.updatedAt!==e&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(t),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const t of this.dependents)t.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=e.owner}setCurrent(t){var e;this.current=t,this.updatedAt=ft.now(),null===this.canTrackVelocity&&void 0!==t&&(this.canTrackVelocity=(e=this.current,!isNaN(parseFloat(e))))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return this.on("change",t)}on(t,e){this.events[t]||(this.events[t]=new V);const n=this.events[t].add(e);return"change"===t?()=>{n(),ht.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,e){this.passiveEffect=t,this.stopPassiveEffect=e}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,e,n){this.set(e),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-n}jump(t,e=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,e&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=ft.now();if(!this.canTrackVelocity||void 0===this.prevFrameValue||t-this.updatedAt>30)return 0;const e=Math.min(this.updatedAt-this.prevUpdatedAt,30);return D(parseFloat(this.current)-parseFloat(this.prevFrameValue),e)}start(t){return this.stop(),new Promise(e=>{this.hasAnimated=!0,this.animation=t(e),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function ni(t,e){return new ei(t,e)}const{schedule:ii,cancel:si}=lt(queueMicrotask,!1),oi={x:!1,y:!1};function ri(){return oi.x||oi.y}function ai(t,e){const n=function(t,e,n){if(t instanceof EventTarget)return[t];if("string"==typeof t){let i=document;e&&(i=e.current);const s=n?.[t]??i.querySelectorAll(t);return s?Array.from(s):[]}return Array.from(t)}(t),i=new AbortController;return[n,{passive:!0,...e,signal:i.signal},()=>i.abort()]}function li(t){return!("touch"===t.pointerType||ri())}const hi=(t,e)=>!!e&&(t===e||hi(t,e.parentElement)),ui=t=>"mouse"===t.pointerType?"number"!=typeof t.button||t.button<=0:!1!==t.isPrimary,ci=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);const di=new WeakSet;function pi(t){return e=>{"Enter"===e.key&&t(e)}}function mi(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}function fi(t){return ui(t)&&!ri()}function yi(t,e,n={}){const[i,s,o]=ai(t,n),r=t=>{const i=t.currentTarget;if(!fi(t))return;di.add(i);const o=e(i,t),r=(t,e)=>{window.removeEventListener("pointerup",a),window.removeEventListener("pointercancel",l),di.has(i)&&di.delete(i),fi(t)&&"function"==typeof o&&o(t,{success:e})},a=t=>{r(t,i===window||i===document||n.useGlobalTarget||hi(i,t.target))},l=t=>{r(t,!1)};window.addEventListener("pointerup",a,s),window.addEventListener("pointercancel",l,s)};return i.forEach(t=>{var e;(n.useGlobalTarget?window:t).addEventListener("pointerdown",r,s),T(e=t)&&"offsetHeight"in e&&(t.addEventListener("focus",t=>((t,e)=>{const n=t.currentTarget;if(!n)return;const i=pi(()=>{if(di.has(n))return;mi(n,"down");const t=pi(()=>{mi(n,"up")});n.addEventListener("keyup",t,e),n.addEventListener("blur",()=>mi(n,"cancel"),e)});n.addEventListener("keydown",i,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",i),e)})(t,s)),function(t){return ci.has(t.tagName)||-1!==t.tabIndex}(t)||t.hasAttribute("tabindex")||(t.tabIndex=0))}),o}function gi(t){return T(t)&&"ownerSVGElement"in t}const vi=t=>Boolean(t&&t.getVelocity),xi=[...Nn,Nt,qt],Ti={};function wi(t,{layout:e,layoutId:n}){return on.has(t)||t.startsWith("origin")||(e||void 0!==n)&&(!!Ti[t]||"opacity"===t)}const Pi={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Si=sn.length;function bi(t,e,n){const{style:i,vars:s,transformOrigin:o}=t;let r=!1,a=!1;for(const t in e){const n=e[t];if(on.has(t))r=!0;else if(gt(t))s[t]=n;else{const e=ti(n,Gn[t]);t.startsWith("origin")?(a=!0,o[t]=e):i[t]=e}}if(e.transform||(r||n?i.transform=function(t,e,n){let i="",s=!0;for(let o=0;o({style:{},transform:{},transformOrigin:{},vars:{}});function Ei(t,e,n){for(const i in e)vi(e[i])||wi(i,n)||(t[i]=e[i])}function Vi(t,e){const n={};return Ei(n,t.style||{},t),Object.assign(n,function({transformTemplate:t},e){return s(()=>{const n={style:{},transform:{},transformOrigin:{},vars:{}};return bi(n,e,t),Object.assign({},n.vars,n.style)},[e])}(t,e)),n}function Mi(t,e){const n={},i=Vi(t,e);return t.drag&&!1!==t.dragListener&&(n.draggable=!1,i.userSelect=i.WebkitUserSelect=i.WebkitTouchCallout="none",i.touchAction=!0===t.drag?"none":"pan-"+("x"===t.drag?"y":"x")),void 0===t.tabIndex&&(t.onTap||t.onTapStart||t.whileTap)&&(n.tabIndex=0),n.style=i,n}const Ci={offset:"stroke-dashoffset",array:"stroke-dasharray"},Di={offset:"strokeDashoffset",array:"strokeDasharray"};function ki(t,{attrX:e,attrY:n,attrScale:i,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,h,u){if(bi(t,a,h),l)return void(t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox));t.attrs=t.style,t.style={};const{attrs:c,style:d}=t;c.transform&&(d.transform=c.transform,delete c.transform),(d.transform||c.transformOrigin)&&(d.transformOrigin=c.transformOrigin??"50% 50%",delete c.transformOrigin),d.transform&&(d.transformBox=u?.transformBox??"fill-box",delete c.transformBox),void 0!==e&&(c.x=e),void 0!==n&&(c.y=n),void 0!==i&&(c.scale=i),void 0!==s&&function(t,e,n=1,i=0,s=!0){t.pathLength=1;const o=s?Ci:Di;t[o.offset]=Bt.transform(-i);const r=Bt.transform(e),a=Bt.transform(n);t[o.array]=`${r} ${a}`}(c,s,o,r,!1)}const Ri=()=>({style:{},transform:{},transformOrigin:{},vars:{},attrs:{}}),Li=t=>"string"==typeof t&&"svg"===t.toLowerCase();function ji(t,e,n,i){const o=s(()=>{const n={style:{},transform:{},transformOrigin:{},vars:{},attrs:{}};return ki(n,e,Li(i),t.transformTemplate,t.style),{...n.attrs,style:{...n.style}}},[e]);if(t.style){const e={};Ei(e,t.style,t),o.style={...e,...o.style}}return o}const Bi=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function Fi(t){return t.startsWith("while")||t.startsWith("drag")&&"draggable"!==t||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||Bi.has(t)}let Oi=t=>!Fi(t);try{"function"==typeof(Ii=require("@emotion/is-prop-valid").default)&&(Oi=t=>t.startsWith("on")?!Fi(t):Ii(t))}catch{}var Ii;const Ui=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function Ni(t){return"string"==typeof t&&!t.includes("-")&&!!(Ui.indexOf(t)>-1||/[A-Z]/u.test(t))}function Wi(t,e,n,{latestValues:i},a,l=!1){const h=(Ni(t)?ji:Mi)(e,i,a,t),u=function(t,e,n){const i={};for(const s in t)"values"===s&&"object"==typeof t.values||(Oi(s)||!0===n&&Fi(s)||!e&&!Fi(s)||t.draggable&&s.startsWith("onDrag"))&&(i[s]=t[s]);return i}(e,"string"==typeof t,l),c=t!==o?{...u,...h,ref:n}:{},{children:d}=e,p=s(()=>vi(d)?d.get():d,[d]);return r(t,{...c,children:p})}const $i=n(null);function Yi(t){const e=[{},{}];return t?.values.forEach((t,n)=>{e[0][n]=t.get(),e[1][n]=t.getVelocity()}),e}function Xi(t,e,n,i){if("function"==typeof e){const[s,o]=Yi(i);e=e(void 0!==n?n:t.custom,s,o)}if("string"==typeof e&&(e=t.variants&&t.variants[e]),"function"==typeof e){const[s,o]=Yi(i);e=e(void 0!==n?n:t.custom,s,o)}return e}function Ki(t){return vi(t)?t.get():t}function zi(t,e,n,i){const s={},o=i(t,{});for(const t in o)s[t]=Ki(o[t]);let{initial:r,animate:a}=t;const l=nt(t),h=it(t);e&&h&&!l&&!1!==t.inherit&&(void 0===r&&(r=e.initial),void 0===a&&(a=e.animate));let u=!!n&&!1===n.initial;u=u||!1===r;const c=u?a:r;if(c&&"boolean"!=typeof c&&!J(c)){const e=Array.isArray(c)?c:[c];for(let n=0;n(e,n)=>{const s=i(_),o=i($i),r=()=>function({scrapeMotionValuesFromProps:t,createRenderState:e},n,i,s){return{latestValues:zi(n,i,s,t),renderState:e()}}(t,e,s,o);return n?r():function(t){const e=a(null);return null===e.current&&(e.current=t()),e.current}(r)};function Gi(t,e,n){const{style:i}=t,s={};for(const o in i)(vi(i[o])||e.style&&vi(e.style[o])||wi(o,t)||void 0!==n?.getValue(o)?.liveStyle)&&(s[o]=i[o]);return s}const qi=Hi({scrapeMotionValuesFromProps:Gi,createRenderState:Ai});function Zi(t,e,n){const i=Gi(t,e,n);for(const n in t)if(vi(t[n])||vi(e[n])){i[-1!==sn.indexOf(n)?"attr"+n.charAt(0).toUpperCase()+n.substring(1):n]=t[n]}return i}const _i=Hi({scrapeMotionValuesFromProps:Zi,createRenderState:Ri}),Ji="undefined"!=typeof window,Qi={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},ts={};for(const t in Qi)ts[t]={isEnabled:e=>Qi[t].some(t=>!!e[t])};const es=Symbol.for("motionComponentSymbol");function ns(t){return t&&"object"==typeof t&&Object.prototype.hasOwnProperty.call(t,"current")}function is(t,e,n){return l(i=>{i&&t.onMount&&t.onMount(i),e&&(i?e.mount(i):e.unmount()),n&&("function"==typeof n?n(i):ns(n)&&(n.current=i))},[e])}const ss=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),os="data-"+ss("framerAppearId"),rs=n({}),as=Ji?h:u;function ls(t,e,n,s,o){const{visualElement:r}=i(_),l=i(q),h=i($i),d=i(Z).reducedMotion,p=a(null);s=s||l.renderer,!p.current&&s&&(p.current=s(t,{visualState:e,parent:r,props:n,presenceContext:h,blockInitialAnimation:!!h&&!1===h.initial,reducedMotionConfig:d}));const m=p.current,f=i(rs);!m||m.projection||!o||"html"!==m.type&&"svg"!==m.type||function(t,e,n,i){const{layoutId:s,layout:o,drag:r,dragConstraints:a,layoutScroll:l,layoutRoot:h,layoutCrossfade:u}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:hs(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:Boolean(r)||a&&ns(a),visualElement:t,animationType:"string"==typeof o?o:"both",initialPromotionConfig:i,crossfade:u,layoutScroll:l,layoutRoot:h})}(p.current,n,o,f);const y=a(!1);c(()=>{m&&y.current&&m.update(n,h)});const g=n[os],v=a(Boolean(g)&&!window.MotionHandoffIsComplete?.(g)&&window.MotionHasOptimisedAnimation?.(g));return as(()=>{m&&(y.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),v.current&&m.animationState&&m.animationState.animateChanges())}),u(()=>{m&&(!v.current&&m.animationState&&m.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(g)}),v.current=!1),m.enteringChildren=void 0)}),m}function hs(t){if(t)return!1!==t.options.allowProjection?t.projection:hs(t.parent)}function us(n,{forwardMotionProps:s=!1}={},o,r){o&&function(t){for(const e in t)ts[e]={...ts[e],...t[e]}}(o);const a=Ni(n)?_i:qi;function l(o,l){let h;const u={...i(Z),...o,layoutId:cs(o)},{isStatic:c}=u,d=st(o),p=a(o,c);if(!c&&Ji){i(q).strict;const t=function(t){const{drag:e,layout:n}=ts;if(!e&&!n)return{};const i={...e,...n};return{MeasureLayout:e?.isEnabled(t)||n?.isEnabled(t)?i.MeasureLayout:void 0,ProjectionNode:i.ProjectionNode}}(u);h=t.MeasureLayout,d.visualElement=ls(n,p,u,r,t.ProjectionNode)}return t(_.Provider,{value:d,children:[h&&d.visualElement?e(h,{visualElement:d.visualElement,...u}):null,Wi(n,o,is(p,d.visualElement,l),p,c,s)]})}l.displayName=`motion.${"string"==typeof n?n:`create(${n.displayName??n.name??""})`}`;const h=d(l);return h[es]=n,h}function cs({layoutId:t}){const e=i(G).id;return e&&void 0!==t?e+"-"+t:t}function ds({top:t,left:e,right:n,bottom:i}){return{x:{min:e,max:n},y:{min:t,max:i}}}function ps(t){return void 0===t||1===t}function ms({scale:t,scaleX:e,scaleY:n}){return!ps(t)||!ps(e)||!ps(n)}function fs(t){return ms(t)||ys(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function ys(t){return gs(t.x)||gs(t.y)}function gs(t){return t&&"0%"!==t}function vs(t,e,n){return n+e*(t-n)}function xs(t,e,n,i,s){return void 0!==s&&(t=vs(t,s,i)),vs(t,n,i)+e}function Ts(t,e=0,n=1,i,s){t.min=xs(t.min,e,n,i,s),t.max=xs(t.max,e,n,i,s)}function ws(t,{x:e,y:n}){Ts(t.x,e.translate,e.scale,e.originPoint),Ts(t.y,n.translate,n.scale,n.originPoint)}const Ps=.999999999999,Ss=1.0000000000001;function bs(t,e){t.min=t.min+e,t.max=t.max+e}function As(t,e,n,i,s=.5){Ts(t,e,n,Jt(t.min,t.max,s),i)}function Es(t,e){As(t.x,e.x,e.scaleX,e.scale,e.originX),As(t.y,e.y,e.scaleY,e.scale,e.originY)}function Vs(t,e){return ds(function(t,e){if(!e)return t;const n=e({x:t.left,y:t.top}),i=e({x:t.right,y:t.bottom});return{top:n.y,left:n.x,bottom:i.y,right:i.x}}(t.getBoundingClientRect(),e))}const Ms=()=>({x:{min:0,max:0},y:{min:0,max:0}}),Cs={current:null},Ds={current:!1};const ks=new WeakMap;const Rs=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Ls{scrapeMotionValuesFromProps(t,e,n){return{}}constructor({parent:t,props:e,presenceContext:n,reducedMotionConfig:i,blockInitialAnimation:s,visualState:o},r={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=yn,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const t=ft.now();this.renderScheduledAtthis.bindToMotionValue(e,t)),Ds.current||function(){if(Ds.current=!0,Ji)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Cs.current=t.matches;t.addEventListener("change",e),e()}else Cs.current=!1}(),this.shouldReduceMotion="never"!==this.reducedMotionConfig&&("always"===this.reducedMotionConfig||Cs.current),this.parent?.addChild(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),ut(this.notifyUpdate),ut(this.render),this.valueSubscriptions.forEach(t=>t()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const t in this.events)this.events[t].clear();for(const t in this.features){const e=this.features[t];e&&(e.unmount(),e.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,e){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const n=on.has(t);n&&this.onBindTransform&&this.onBindTransform();const i=e.on("change",e=>{this.latestValues[t]=e,this.props.onUpdate&&ht.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let s;window.MotionCheckAppearSync&&(s=window.MotionCheckAppearSync(this,t,e)),this.valueSubscriptions.set(t,()=>{i(),s&&s(),e.owner&&e.stop()})}sortNodePosition(t){return this.current&&this.sortInstanceNodePosition&&this.type===t.type?this.sortInstanceNodePosition(this.current,t.current):0}updateFeatures(){let t="animation";for(t in ts){const e=ts[t];if(!e)continue;const{isEnabled:n,Feature:i}=e;if(!this.features[t]&&i&&n(this.props)&&(this.features[t]=new i(this)),this.features[t]){const e=this.features[t];e.isMounted?e.update():(e.mount(),e.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):{x:{min:0,max:0},y:{min:0,max:0}}}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,e){this.latestValues[t]=e}update(t,e){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=e;for(let e=0;ee.variantChildren.delete(t)}addValue(t,e){const n=this.values.get(t);e!==n&&(n&&this.removeValue(t),this.bindToMotionValue(t,e),this.values.set(t,e),this.latestValues[t]=e.get())}removeValue(t){this.values.delete(t);const e=this.valueSubscriptions.get(t);e&&(e(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,e){if(this.props.values&&this.props.values[t])return this.props.values[t];let n=this.values.get(t);return void 0===n&&void 0!==e&&(n=ni(null===e?void 0:e,{owner:this}),this.addValue(t,n)),n}readValue(t,e){let n=void 0===this.latestValues[t]&&this.current?this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options):this.latestValues[t];var i;return null!=n&&("string"==typeof n&&(x(n)||w(n))?n=parseFloat(n):(i=n,!xi.find(Un(i))&&qt.test(e)&&(n=_n(t,e))),this.setBaseTarget(t,vi(n)?n.get():n)),vi(n)?n.get():n}setBaseTarget(t,e){this.baseTarget[t]=e}getBaseTarget(t){const{initial:e}=this.props;let n;if("string"==typeof e||"object"==typeof e){const i=Xi(this.props,e,this.presenceContext?.custom);i&&(n=i[t])}if(e&&void 0!==n)return n;const i=this.getBaseTargetFromProps(this.props,t);return void 0===i||vi(i)?void 0!==this.initialValues[t]&&void 0===n?void 0:this.baseTarget[t]:i}on(t,e){return this.events[t]||(this.events[t]=new V),this.events[t].add(e)}notify(t,...e){this.events[t]&&this.events[t].notify(...e)}scheduleRenderMicrotask(){ii.render(this.render)}}class js extends Ls{constructor(){super(...arguments),this.KeyframeResolver=Qn}sortInstanceNodePosition(t,e){return 2&t.compareDocumentPosition(e)?1:-1}getBaseTargetFromProps(t,e){return t.style?t.style[e]:void 0}removeValueFromRenderState(t,{vars:e,style:n}){delete e[t],delete n[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;vi(t)&&(this.childSubscription=t.on("change",t=>{this.current&&(this.current.textContent=`${t}`)}))}}function Bs(t,{style:e,vars:n},i,s){const o=t.style;let r;for(r in e)o[r]=e[r];for(r in s?.applyProjectionStyles(o,i),n)o.setProperty(r,n[r])}class Fs extends js{constructor(){super(...arguments),this.type="html",this.renderInstance=Bs}readValueFromInstance(t,e){if(on.has(e))return this.projection?.isProjecting?tn(e):((t,e)=>{const{transform:n="none"}=getComputedStyle(t);return en(n,e)})(t,e);{const i=(n=t,window.getComputedStyle(n)),s=(gt(e)?i.getPropertyValue(e):i[e])||0;return"string"==typeof s?s.trim():s}var n}measureInstanceViewportBox(t,{transformPagePoint:e}){return Vs(t,e)}build(t,e,n){bi(t,e,n.transformTemplate)}scrapeMotionValuesFromProps(t,e,n){return Gi(t,e,n)}}const Os=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);class Is extends js{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Ms}getBaseTargetFromProps(t,e){return t[e]}readValueFromInstance(t,e){if(on.has(e)){const t=Zn(e);return t&&t.default||0}return e=Os.has(e)?e:ss(e),t.getAttribute(e)}scrapeMotionValuesFromProps(t,e,n){return Zi(t,e,n)}build(t,e,n){ki(t,e,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(t,e,n,i){!function(t,e,n,i){Bs(t,e,void 0,i);for(const n in e.attrs)t.setAttribute(Os.has(n)?n:ss(n),e.attrs[n])}(t,e,0,i)}mount(t){this.isSVGTag=Li(t.tagName),super.mount(t)}}const Us=(t,e)=>Ni(t)?new Is(e):new Fs(e,{allowProjection:t!==o});function Ns(t,e,n){const i=t.getProps();return Xi(i,e,void 0!==n?n:i.custom,t)}const Ws=t=>Array.isArray(t);function $s(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,ni(n))}function Ys(t){return Ws(t)?t[t.length-1]||0:t}function Xs(t,e){const n=t.getValue("willChange");if(i=n,Boolean(vi(i)&&i.add))return n.add(e);if(!n&&v.WillChange){const n=new v.WillChange("auto");t.addValue("willChange",n),n.add(e)}var i}function Ks(t){return t.props[os]}const zs=t=>null!==t;const Hs={type:"spring",stiffness:500,damping:25,restSpeed:10},Gs={type:"keyframes",duration:.8},qs={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Zs=(t,{keyframes:e})=>e.length>2?Gs:on.has(t)?t.startsWith("scale")?{type:"spring",stiffness:550,damping:0===e[1]?2*Math.sqrt(550):30,restSpeed:10}:Hs:qs;const _s=(t,e,n,i={},s,o)=>r=>{const a=On(i,t)||{},l=a.delay||i.delay||0;let{elapsed:h=0}=i;h-=M(l);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-h,onUpdate:t=>{e.set(t),a.onUpdate&&a.onUpdate(t)},onComplete:()=>{r(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:s};(function({when:t,delay:e,delayChildren:n,staggerChildren:i,staggerDirection:s,repeat:o,repeatType:r,repeatDelay:a,from:l,elapsed:h,...u}){return!!Object.keys(u).length})(a)||Object.assign(u,Zs(t,u)),u.duration&&(u.duration=M(u.duration)),u.repeatDelay&&(u.repeatDelay=M(u.repeatDelay)),void 0!==u.from&&(u.keyframes[0]=u.from);let c=!1;if((!1===u.type||0===u.duration&&!u.repeatDelay)&&(kn(u),0===u.delay&&(c=!0)),(v.instantAnimations||v.skipAnimations)&&(c=!0,kn(u),u.delay=0),u.allowFlatten=!a.type&&!a.ease,c&&!o&&void 0!==e.get()){const t=function(t,{repeat:e,repeatType:n="loop"},i){const s=t.filter(zs),o=e&&"loop"!==n&&e%2==1?0:s.length-1;return o&&void 0!==i?i:s[o]}(u.keyframes,a);if(void 0!==t)return void ht.update(()=>{u.onUpdate(t),u.onComplete()})}return a.isSync?new ze(u):new jn(u)};function Js({protectedKeys:t,needsAnimating:e},n){const i=t.hasOwnProperty(n)&&!0!==e[n];return e[n]=!1,i}function Qs(t,e,{delay:n=0,transitionOverride:i,type:s}={}){let{transition:o=t.getDefaultTransition(),transitionEnd:r,...a}=e;i&&(o=i);const l=[],h=s&&t.animationState&&t.animationState.getState()[s];for(const e in a){const i=t.getValue(e,t.latestValues[e]??null),s=a[e];if(void 0===s||h&&Js(h,e))continue;const r={delay:n,...On(o||{},e)},u=i.get();if(void 0!==u&&!i.isAnimating&&!Array.isArray(s)&&s===u&&!r.velocity)continue;let c=!1;if(window.MotionHandoffAnimation){const n=Ks(t);if(n){const t=window.MotionHandoffAnimation(n,e,ht);null!==t&&(r.startTime=t,c=!0)}}Xs(t,e),i.start(_s(e,i,s,t.shouldReduceMotion&&In.has(e)?{type:!1}:r,t,c));const d=i.animation;d&&l.push(d)}return r&&Promise.all(l).then(()=>{ht.update(()=>{r&&function(t,e){const n=Ns(t,e);let{transitionEnd:i={},transition:s={},...o}=n||{};o={...o,...i};for(const e in o)$s(t,e,Ys(o[e]))}(t,r)})}),l}function to(t,e,n,i=0,s=1){const o=Array.from(t).sort((t,e)=>t.sortNodePosition(e)).indexOf(e),r=t.size,a=(r-1)*i;return"function"==typeof n?n(o,r):1===s?o*i:a-o*i}function eo(t,e,n={}){const i=Ns(t,e,"exit"===n.type?t.presenceContext?.custom:void 0);let{transition:s=t.getDefaultTransition()||{}}=i||{};n.transitionOverride&&(s=n.transitionOverride);const o=i?()=>Promise.all(Qs(t,i,n)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(i=0)=>{const{delayChildren:o=0,staggerChildren:r,staggerDirection:a}=s;return function(t,e,n=0,i=0,s=0,o=1,r){const a=[];for(const l of t.variantChildren)l.notify("AnimationStart",e),a.push(eo(l,e,{...r,delay:n+("function"==typeof i?0:i)+to(t.variantChildren,l,i,s,o)}).then(()=>l.notify("AnimationComplete",e)));return Promise.all(a)}(t,e,i,o,r,a,n)}:()=>Promise.resolve(),{when:a}=s;if(a){const[t,e]="beforeChildren"===a?[o,r]:[r,o];return t().then(()=>e())}return Promise.all([o(),r(n.delay)])}function no(t,e){if(!Array.isArray(e))return!1;const n=e.length;if(n!==t.length)return!1;for(let i=0;iPromise.all(e.map(({animation:e,options:n})=>function(t,e,n={}){let i;if(t.notify("AnimationStart",e),Array.isArray(e)){const s=e.map(e=>eo(t,e,n));i=Promise.all(s)}else if("string"==typeof e)i=eo(t,e,n);else{const s="function"==typeof e?Ns(t,e,n.custom):e;i=Promise.all(Qs(t,s,n))}return i.then(()=>{t.notify("AnimationComplete",e)})}(t,e,n)))}function lo(t){let e=ao(t),n=co(),i=!0;const s=e=>(n,i)=>{const s=Ns(t,i,"exit"===e?t.presenceContext?.custom:void 0);if(s){const{transition:t,transitionEnd:e,...i}=s;n={...n,...i,...e}}return n};function o(o){const{props:r}=t,a=so(t.parent)||{},l=[],h=new Set;let u={},c=1/0;for(let e=0;ec&&f,T=!1;const w=Array.isArray(m)?m:[m];let P=w.reduce(s(d),{});!1===y&&(P={});const{prevResolvedValues:S={}}=p,b={...S,...P},A=e=>{x=!0,h.has(e)&&(T=!0,h.delete(e)),p.needsAnimating[e]=!0;const n=t.getValue(e);n&&(n.liveStyle=!1)};for(const t in b){const e=P[t],n=S[t];if(u.hasOwnProperty(t))continue;let i=!1;i=Ws(e)&&Ws(n)?!no(e,n):e!==n,i?null!=e?A(t):h.add(t):void 0!==e&&h.has(t)?A(t):p.protectedKeys[t]=!0}p.prevProp=m,p.prevResolvedValues=P,p.isActive&&(u={...u,...P}),i&&t.blockInitialAnimation&&(x=!1);const E=g&&v;x&&(!E||T)&&l.push(...w.map(e=>{const n={type:d};if("string"==typeof e&&i&&!E&&t.manuallyAnimateOnMount&&t.parent){const{parent:i}=t,s=Ns(i,e);if(i.enteringChildren&&s){const{delayChildren:e}=s.transition||{};n.delay=to(i.enteringChildren,t,e)}}return{animation:e,options:n}}))}if(h.size){const e={};if("boolean"!=typeof r.initial){const n=Ns(t,Array.isArray(r.initial)?r.initial[0]:r.initial);n&&n.transition&&(e.transition=n.transition)}h.forEach(n=>{const i=t.getBaseTarget(n),s=t.getValue(n);s&&(s.liveStyle=!0),e[n]=i??null}),l.push({animation:e})}let d=Boolean(l.length);return!i||!1!==r.initial&&r.initial!==r.animate||t.manuallyAnimateOnMount||(d=!1),i=!1,d?e(l):Promise.resolve()}return{animateChanges:o,setActive:function(e,i){if(n[e].isActive===i)return Promise.resolve();t.variantChildren?.forEach(t=>t.animationState?.setActive(e,i)),n[e].isActive=i;const s=o(e);for(const t in n)n[t].protectedKeys={};return s},setAnimateFunction:function(n){e=n(t)},getState:()=>n,reset:()=>{n=co(),i=!0}}}function ho(t,e){return"string"==typeof e?e!==t:!!Array.isArray(e)&&!no(e,t)}function uo(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function co(){return{animate:uo(!0),whileInView:uo(),whileHover:uo(),whileTap:uo(),whileDrag:uo(),whileFocus:uo(),exit:uo()}}class po{constructor(t){this.isMounted=!1,this.node=t}update(){}}let mo=0;const fo={animation:{Feature:class extends po{constructor(t){super(t),t.animationState||(t.animationState=lo(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();J(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:e}=this.node.prevProps||{};t!==e&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}},exit:{Feature:class extends po{constructor(){super(...arguments),this.id=mo++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:e}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===n)return;const i=this.node.animationState.setActive("exit",!t);e&&!t&&i.then(()=>{e(this.id)})}mount(){const{register:t,onExitComplete:e}=this.node.presenceContext||{};e&&e(this.id),t&&(this.unmount=t(this.id))}unmount(){}}}};function yo(t,e,n,i={passive:!0}){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n)}function go(t){return{point:{x:t.pageX,y:t.pageY}}}function vo(t,e,n,i){return yo(t,e,(t=>e=>ui(e)&&t(e,go(e)))(n),i)}function xo(t){return t.max-t.min}function To(t,e,n,i=.5){t.origin=i,t.originPoint=Jt(e.min,e.max,t.origin),t.scale=xo(n)/xo(e),t.translate=Jt(n.min,n.max,t.origin)-t.originPoint,(t.scale>=.9999&&t.scale<=1.0001||isNaN(t.scale))&&(t.scale=1),(t.translate>=-.01&&t.translate<=.01||isNaN(t.translate))&&(t.translate=0)}function wo(t,e,n,i){To(t.x,e.x,n.x,i?i.originX:void 0),To(t.y,e.y,n.y,i?i.originY:void 0)}function Po(t,e,n){t.min=n.min+e.min,t.max=t.min+xo(e)}function So(t,e,n){t.min=e.min-n.min,t.max=t.min+xo(e)}function bo(t,e,n){So(t.x,e.x,n.x),So(t.y,e.y,n.y)}function Ao(t){return[t("x"),t("y")]}const Eo=({current:t})=>t?t.ownerDocument.defaultView:null,Vo=(t,e)=>Math.abs(t-e);class Mo{constructor(t,e,{transformPagePoint:n,contextWindow:i=window,dragSnapToOrigin:s=!1,distanceThreshold:o=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!this.lastMoveEvent||!this.lastMoveEventInfo)return;const t=ko(this.lastMoveEventInfo,this.history),e=null!==this.startEvent,n=function(t,e){const n=Vo(t.x,e.x),i=Vo(t.y,e.y);return Math.sqrt(n**2+i**2)}(t.offset,{x:0,y:0})>=this.distanceThreshold;if(!e&&!n)return;const{point:i}=t,{timestamp:s}=ct;this.history.push({...i,timestamp:s});const{onStart:o,onMove:r}=this.handlers;e||(o&&o(this.lastMoveEvent,t),this.startEvent=this.lastMoveEvent),r&&r(this.lastMoveEvent,t)},this.handlePointerMove=(t,e)=>{this.lastMoveEvent=t,this.lastMoveEventInfo=Co(e,this.transformPagePoint),ht.update(this.updatePoint,!0)},this.handlePointerUp=(t,e)=>{this.end();const{onEnd:n,onSessionEnd:i,resumeAnimation:s}=this.handlers;if(this.dragSnapToOrigin&&s&&s(),!this.lastMoveEvent||!this.lastMoveEventInfo)return;const o=ko("pointercancel"===t.type?this.lastMoveEventInfo:Co(e,this.transformPagePoint),this.history);this.startEvent&&n&&n(t,o),i&&i(t,o)},!ui(t))return;this.dragSnapToOrigin=s,this.handlers=e,this.transformPagePoint=n,this.distanceThreshold=o,this.contextWindow=i||window;const r=Co(go(t),this.transformPagePoint),{point:a}=r,{timestamp:l}=ct;this.history=[{...a,timestamp:l}];const{onSessionStart:h}=e;h&&h(t,ko(r,this.history)),this.removeListeners=A(vo(this.contextWindow,"pointermove",this.handlePointerMove),vo(this.contextWindow,"pointerup",this.handlePointerUp),vo(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),ut(this.updatePoint)}}function Co(t,e){return e?{point:e(t.point)}:t}function Do(t,e){return{x:t.x-e.x,y:t.y-e.y}}function ko({point:t},e){return{point:t,delta:Do(t,Lo(e)),offset:Do(t,Ro(e)),velocity:jo(e,.1)}}function Ro(t){return t[0]}function Lo(t){return t[t.length-1]}function jo(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,i=null;const s=Lo(t);for(;n>=0&&(i=t[n],!(s.timestamp-i.timestamp>M(e)));)n--;if(!i)return{x:0,y:0};const o=C(s.timestamp-i.timestamp);if(0===o)return{x:0,y:0};const r={x:(s.x-i.x)/o,y:(s.y-i.y)/o};return r.x===1/0&&(r.x=0),r.y===1/0&&(r.y=0),r}function Bo(t,e,n){return{min:void 0!==e?t.min+e:void 0,max:void 0!==n?t.max+n-(t.max-t.min):void 0}}function Fo(t,e){let n=e.min-t.min,i=e.max-t.max;return e.max-e.min{const{dragSnapToOrigin:n}=this.getProps();n?this.pauseAnimation():this.stopAnimation(),e&&this.snapToCursor(go(t).point)},onStart:(t,e)=>{const{drag:n,dragPropagation:i,onDragStart:s}=this.getProps();if(n&&!i&&(this.openDragLock&&this.openDragLock(),this.openDragLock="x"===(o=n)||"y"===o?oi[o]?null:(oi[o]=!0,()=>{oi[o]=!1}):oi.x||oi.y?null:(oi.x=oi.y=!0,()=>{oi.x=oi.y=!1}),!this.openDragLock))return;var o;this.latestPointerEvent=t,this.latestPanInfo=e,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Ao(t=>{let e=this.getAxisMotionValue(t).get()||0;if(jt.test(e)){const{projection:n}=this.visualElement;if(n&&n.layout){const i=n.layout.layoutBox[t];if(i){e=xo(i)*(parseFloat(e)/100)}}}this.originPoint[t]=e}),s&&ht.postRender(()=>s(t,e)),Xs(this.visualElement,"transform");const{animationState:r}=this.visualElement;r&&r.setActive("whileDrag",!0)},onMove:(t,e)=>{this.latestPointerEvent=t,this.latestPanInfo=e;const{dragPropagation:n,dragDirectionLock:i,onDirectionLock:s,onDrag:o}=this.getProps();if(!n&&!this.openDragLock)return;const{offset:r}=e;if(i&&null===this.currentDirection)return this.currentDirection=function(t,e=10){let n=null;Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x");return n}(r),void(null!==this.currentDirection&&s&&s(this.currentDirection));this.updateAxis("x",e.point,r),this.updateAxis("y",e.point,r),this.visualElement.render(),o&&o(t,e)},onSessionEnd:(t,e)=>{this.latestPointerEvent=t,this.latestPanInfo=e,this.stop(t,e),this.latestPointerEvent=null,this.latestPanInfo=null},resumeAnimation:()=>Ao(t=>"paused"===this.getAnimationState(t)&&this.getAxisMotionValue(t).animation?.play())},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:s,distanceThreshold:n,contextWindow:Eo(this.visualElement)})}stop(t,e){const n=t||this.latestPointerEvent,i=e||this.latestPanInfo,s=this.isDragging;if(this.cancel(),!s||!i||!n)return;const{velocity:o}=i;this.startAnimation(o);const{onDragEnd:r}=this.getProps();r&&ht.postRender(()=>r(n,i))}cancel(){this.isDragging=!1;const{projection:t,animationState:e}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),e&&e.setActive("whileDrag",!1)}updateAxis(t,e,n){const{drag:i}=this.getProps();if(!n||!$o(t,i,this.currentDirection))return;const s=this.getAxisMotionValue(t);let o=this.originPoint[t]+n[t];this.constraints&&this.constraints[t]&&(o=function(t,{min:e,max:n},i){return void 0!==e&&tn&&(t=i?Jt(n,t,i.max):Math.min(t,n)),t}(o,this.constraints[t],this.elastic[t])),s.set(o)}resolveConstraints(){const{dragConstraints:t,dragElastic:e}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,i=this.constraints;t&&ns(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):this.constraints=!(!t||!n)&&function(t,{top:e,left:n,bottom:i,right:s}){return{x:Bo(t.x,n,s),y:Bo(t.y,e,i)}}(n.layoutBox,t),this.elastic=function(t=Oo){return!1===t?t=0:!0===t&&(t=Oo),{x:Io(t,"left","right"),y:Io(t,"top","bottom")}}(e),i!==this.constraints&&n&&this.constraints&&!this.hasMutatedConstraints&&Ao(t=>{!1!==this.constraints&&this.getAxisMotionValue(t)&&(this.constraints[t]=function(t,e){const n={};return void 0!==e.min&&(n.min=e.min-t.min),void 0!==e.max&&(n.max=e.max-t.min),n}(n.layoutBox[t],this.constraints[t]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:e}=this.getProps();if(!t||!ns(t))return!1;const n=t.current,{projection:i}=this.visualElement;if(!i||!i.layout)return!1;const s=function(t,e,n){const i=Vs(t,n),{scroll:s}=e;return s&&(bs(i.x,s.offset.x),bs(i.y,s.offset.y)),i}(n,i.root,this.visualElement.getTransformPagePoint());let o=function(t,e){return{x:Fo(t.x,e.x),y:Fo(t.y,e.y)}}(i.layout.layoutBox,s);if(e){const t=e(function({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}(o));this.hasMutatedConstraints=!!t,t&&(o=ds(t))}return o}startAnimation(t){const{drag:e,dragMomentum:n,dragElastic:i,dragTransition:s,dragSnapToOrigin:o,onDragTransitionEnd:r}=this.getProps(),a=this.constraints||{},l=Ao(r=>{if(!$o(r,e,this.currentDirection))return;let l=a&&a[r]||{};o&&(l={min:0,max:0});const h=i?200:1e6,u=i?40:1e7,c={type:"inertia",velocity:n?t[r]:0,bounceStiffness:h,bounceDamping:u,timeConstant:750,restDelta:1,restSpeed:10,...s,...l};return this.startAxisValueAnimation(r,c)});return Promise.all(l).then(r)}startAxisValueAnimation(t,e){const n=this.getAxisMotionValue(t);return Xs(this.visualElement,t),n.start(_s(t,n,0,e,this.visualElement,!1))}stopAnimation(){Ao(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){Ao(t=>this.getAxisMotionValue(t).animation?.pause())}getAnimationState(t){return this.getAxisMotionValue(t).animation?.state}getAxisMotionValue(t){const e=`_drag${t.toUpperCase()}`,n=this.visualElement.getProps(),i=n[e];return i||this.visualElement.getValue(t,(n.initial?n.initial[t]:void 0)||0)}snapToCursor(t){Ao(e=>{const{drag:n}=this.getProps();if(!$o(e,n,this.currentDirection))return;const{projection:i}=this.visualElement,s=this.getAxisMotionValue(e);if(i&&i.layout){const{min:n,max:o}=i.layout.layoutBox[e];s.set(t[e]-Jt(n,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:e}=this.getProps(),{projection:n}=this.visualElement;if(!ns(e)||!n||!this.constraints)return;this.stopAnimation();const i={x:0,y:0};Ao(t=>{const e=this.getAxisMotionValue(t);if(e&&!1!==this.constraints){const n=e.get();i[t]=function(t,e){let n=.5;const i=xo(t),s=xo(e);return s>i?n=E(e.min,e.max-i,t.min):i>s&&(n=E(t.min,t.max-s,e.min)),g(0,1,n)}({min:n,max:n},this.constraints[t])}});const{transformTemplate:s}=this.visualElement.getProps();this.visualElement.current.style.transform=s?s({},""):"none",n.root&&n.root.updateScroll(),n.updateLayout(),this.resolveConstraints(),Ao(e=>{if(!$o(e,t,null))return;const n=this.getAxisMotionValue(e),{min:s,max:o}=this.constraints[e];n.set(Jt(s,o,i[e]))})}addListeners(){if(!this.visualElement.current)return;No.set(this.visualElement,this);const t=vo(this.visualElement.current,"pointerdown",t=>{const{drag:e,dragListener:n=!0}=this.getProps();e&&n&&this.start(t)}),e=()=>{const{dragConstraints:t}=this.getProps();ns(t)&&t.current&&(this.constraints=this.resolveRefConstraints())},{projection:n}=this.visualElement,i=n.addEventListener("measure",e);n&&!n.layout&&(n.root&&n.root.updateScroll(),n.updateLayout()),ht.read(e);const s=yo(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:t,hasLayoutChanged:e})=>{this.isDragging&&e&&(Ao(e=>{const n=this.getAxisMotionValue(e);n&&(this.originPoint[e]+=t[e].translate,n.set(n.get()+t[e].translate))}),this.visualElement.render())});return()=>{s(),t(),i(),o&&o()}}getProps(){const t=this.visualElement.getProps(),{drag:e=!1,dragDirectionLock:n=!1,dragPropagation:i=!1,dragConstraints:s=!1,dragElastic:o=Oo,dragMomentum:r=!0}=t;return{...t,drag:e,dragDirectionLock:n,dragPropagation:i,dragConstraints:s,dragElastic:o,dragMomentum:r}}}function $o(t,e,n){return!(!0!==e&&e!==t||null!==n&&n!==t)}const Yo=t=>(e,n)=>{t&&ht.postRender(()=>t(e,n))};const Xo=(t,e)=>t.depth-e.depth;class Ko{constructor(){this.children=[],this.isDirty=!1}add(t){f(this.children,t),this.isDirty=!0}remove(t){y(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(Xo),this.isDirty=!1,this.children.forEach(t)}}const zo=["TopLeft","TopRight","BottomLeft","BottomRight"],Ho=zo.length,Go=t=>"string"==typeof t?parseFloat(t):t,qo=t=>"number"==typeof t||Bt.test(t);function Zo(t,e){return void 0!==t[e]?t[e]:t.borderRadius}const _o=Qo(0,.5,N),Jo=Qo(.5,.95,S);function Qo(t,e,n){return i=>ie?1:n(E(t,e,i))}function tr(t,e){t.min=e.min,t.max=e.max}function er(t,e){tr(t.x,e.x),tr(t.y,e.y)}function nr(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function ir(t,e,n,i,s){return t=vs(t-=e,1/n,i),void 0!==s&&(t=vs(t,1/s,i)),t}function sr(t,e,[n,i,s],o,r){!function(t,e=0,n=1,i=.5,s,o=t,r=t){jt.test(e)&&(e=parseFloat(e),e=Jt(r.min,r.max,e/100)-r.min);if("number"!=typeof e)return;let a=Jt(o.min,o.max,i);t===o&&(a-=e),t.min=ir(t.min,e,n,a,s),t.max=ir(t.max,e,n,a,s)}(t,e[n],e[i],e[s],e.scale,o,r)}const or=["x","scaleX","originX"],rr=["y","scaleY","originY"];function ar(t,e,n,i){sr(t.x,e,or,n?n.x:void 0,i?i.x:void 0),sr(t.y,e,rr,n?n.y:void 0,i?i.y:void 0)}function lr(t){return 0===t.translate&&1===t.scale}function hr(t){return lr(t.x)&&lr(t.y)}function ur(t,e){return t.min===e.min&&t.max===e.max}function cr(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function dr(t,e){return cr(t.x,e.x)&&cr(t.y,e.y)}function pr(t){return xo(t.x)/xo(t.y)}function mr(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class fr{constructor(){this.members=[]}add(t){f(this.members,t),t.scheduleRender()}remove(t){if(y(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const t=this.members[this.members.length-1];t&&this.promote(t)}}relegate(t){const e=this.members.findIndex(e=>t===e);if(0===e)return!1;let n;for(let t=e;t>=0;t--){const e=this.members[t];if(!1!==e.isPresent){n=e;break}}return!!n&&(this.promote(n),!0)}promote(t,e){const n=this.lead;if(t!==n&&(this.prevLead=n,this.lead=t,t.show(),n)){n.instance&&n.scheduleRender(),t.scheduleRender(),t.resumeFrom=n,e&&(t.resumeFrom.preserveOpacity=!0),n.snapshot&&(t.snapshot=n.snapshot,t.snapshot.latestValues=n.animationValues||n.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:i}=t.options;!1===i&&n.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:e,resumingFrom:n}=t;e.onExitComplete&&e.onExitComplete(),n&&n.options.onExitComplete&&n.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}const yr={hasAnimatedSinceResize:!0,hasEverUpdated:!1},gr=["","X","Y","Z"];let vr=0;function xr(t,e,n,i){const{latestValues:s}=e;s[t]&&(n[t]=s[t],e.setStaticValue(t,0),i&&(i[t]=0))}function Tr(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=Ks(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:e,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",ht,!(e||i))}const{parent:i}=t;i&&!i.hasCheckedOptimisedAppear&&Tr(i)}function wr({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:i,resetTransform:s}){return class{constructor(t={},n=e?.()){this.id=vr++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(br),this.nodes.forEach(kr),this.nodes.forEach(Rr),this.nodes.forEach(Ar)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=t,this.root=n?n.root||n:this,this.path=n?[...n.path,n]:[],this.parent=n,this.depth=n?n.depth+1:0;for(let t=0;tthis.root.updateBlockedByResize=!1;ht.read(()=>{i=window.innerWidth}),t(e,()=>{const t=window.innerWidth;t!==i&&(i=t,this.root.updateBlockedByResize=!0,n&&n(),n=function(t,e){const n=ft.now(),i=({timestamp:s})=>{const o=s-n;o>=e&&(ut(i),t(o-e))};return ht.setup(i,!0),()=>ut(i)}(s,250),yr.hasAnimatedSinceResize&&(yr.hasAnimatedSinceResize=!1,this.nodes.forEach(Dr)))})}i&&this.root.registerSharedNode(i,this),!1!==this.options.animate&&o&&(i||s)&&this.addEventListener("didUpdate",({delta:t,hasLayoutChanged:e,hasRelativeLayoutChanged:n,layout:i})=>{if(this.isTreeAnimationBlocked())return this.target=void 0,void(this.relativeTarget=void 0);const s=this.options.transition||o.getDefaultTransition()||Ir,{onLayoutAnimationStart:r,onLayoutAnimationComplete:a}=o.getProps(),l=!this.targetLayout||!dr(this.targetLayout,i),h=!e&&n;if(this.options.layoutRoot||this.resumeFrom||h||e&&(l||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const e={...On(s,"layout"),onPlay:r,onComplete:a};(o.shouldReduceMotion||this.options.layoutRoot)&&(e.delay=0,e.type=!1),this.startAnimation(e),this.setAnimationOrigin(t,h)}else e||Dr(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=i})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const t=this.getStack();t&&t.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),ut(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(Lr),this.animationId++)}getTransformTemplate(){const{visualElement:t}=this.options;return t&&t.getProps().transformTemplate}willUpdate(t=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked())return void(this.options.onExitComplete&&this.options.onExitComplete());if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Tr(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let t=0;t{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){!this.snapshot&&this.instance&&(this.snapshot=this.measure(),!this.snapshot||xo(this.snapshot.measuredBox.x)||xo(this.snapshot.measuredBox.y)||(this.snapshot=void 0))}updateLayout(){if(!this.instance)return;if(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead()||this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let t=0;tPs&&(e.x=1),e.yPs&&(e.y=1)}(this.layoutCorrected,this.treeScale,this.path,e),!t.layout||t.target||1===this.treeScale.x&&1===this.treeScale.y||(t.target=t.layout.layoutBox,t.targetWithTransforms={x:{min:0,max:0},y:{min:0,max:0}});const{target:a}=t;a?(this.projectionDelta&&this.prevProjectionDelta?(nr(this.prevProjectionDelta.x,this.projectionDelta.x),nr(this.prevProjectionDelta.y,this.projectionDelta.y)):this.createProjectionDeltas(),wo(this.projectionDelta,this.layoutCorrected,a,this.latestValues),this.treeScale.x===o&&this.treeScale.y===r&&mr(this.projectionDelta.x,this.prevProjectionDelta.x)&&mr(this.projectionDelta.y,this.prevProjectionDelta.y)||(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",a))):this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender())}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(t=!0){if(this.options.visualElement?.scheduleRender(),t){const t=this.getStack();t&&t.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}},this.projectionDelta={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}},this.projectionDeltaWithTransform={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}}}setAnimationOrigin(t,e=!1){const n=this.snapshot,i=n?n.latestValues:{},s={...this.latestValues},o={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}};this.relativeParent&&this.relativeParent.options.layoutRoot||(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!e;const r={x:{min:0,max:0},y:{min:0,max:0}},a=(n?n.source:void 0)!==(this.layout?this.layout.source:void 0),l=this.getStack(),h=!l||l.members.length<=1,u=Boolean(a&&!h&&!0===this.options.crossfade&&!this.path.some(Or));let c;this.animationProgress=0,this.mixTargetDelta=e=>{const n=e/1e3;var l,d,p,m,f,y;Br(o.x,t.x,n),Br(o.y,t.y,n),this.setTargetDelta(o),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(bo(r,this.layout.layoutBox,this.relativeParent.layout.layoutBox),p=this.relativeTarget,m=this.relativeTargetOrigin,f=r,y=n,Fr(p.x,m.x,f.x,y),Fr(p.y,m.y,f.y,y),c&&(l=this.relativeTarget,d=c,ur(l.x,d.x)&&ur(l.y,d.y))&&(this.isProjectionDirty=!1),c||(c={x:{min:0,max:0},y:{min:0,max:0}}),er(c,this.relativeTarget)),a&&(this.animationValues=s,function(t,e,n,i,s,o){s?(t.opacity=Jt(0,n.opacity??1,_o(i)),t.opacityExit=Jt(e.opacity??1,0,Jo(i))):o&&(t.opacity=Jt(e.opacity??1,n.opacity??1,i));for(let s=0;s{yr.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=ni(0)),this.currentAnimation=function(t,e,n){const i=vi(t)?t:ni(t);return i.start(_s("",i,e,n)),i.animation}(this.motionValue,[0,1e3],{...t,velocity:0,isSync:!0,onUpdate:e=>{this.mixTargetDelta(e),t.onUpdate&&t.onUpdate(e)},onStop:()=>{},onComplete:()=>{t.onComplete&&t.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const t=this.getStack();t&&t.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(1e3),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const t=this.getLead();let{targetWithTransforms:e,target:n,layout:i,latestValues:s}=t;if(e&&n&&i){if(this!==t&&this.layout&&i&&$r(this.options.animationType,this.layout.layoutBox,i.layoutBox)){n=this.target||{x:{min:0,max:0},y:{min:0,max:0}};const e=xo(this.layout.layoutBox.x);n.x.min=t.target.x.min,n.x.max=n.x.min+e;const i=xo(this.layout.layoutBox.y);n.y.min=t.target.y.min,n.y.max=n.y.min+i}er(e,n),Es(e,s),wo(this.projectionDeltaWithTransform,this.layoutCorrected,e,s)}}registerSharedNode(t,e){this.sharedNodes.has(t)||this.sharedNodes.set(t,new fr);this.sharedNodes.get(t).add(e);const n=e.options.initialPromotionConfig;e.promote({transition:n?n.transition:void 0,preserveFollowOpacity:n&&n.shouldPreserveFollowOpacity?n.shouldPreserveFollowOpacity(e):void 0})}isLead(){const t=this.getStack();return!t||t.lead===this}getLead(){const{layoutId:t}=this.options;return t&&this.getStack()?.lead||this}getPrevLead(){const{layoutId:t}=this.options;return t?this.getStack()?.prevLead:void 0}getStack(){const{layoutId:t}=this.options;if(t)return this.root.sharedNodes.get(t)}promote({needsReset:t,transition:e,preserveFollowOpacity:n}={}){const i=this.getStack();i&&i.promote(this,n),t&&(this.projectionDelta=void 0,this.needsReset=!0),e&&this.setOptions({transition:e})}relegate(){const t=this.getStack();return!!t&&t.relegate(this)}resetSkewAndRotation(){const{visualElement:t}=this.options;if(!t)return;let e=!1;const{latestValues:n}=t;if((n.z||n.rotate||n.rotateX||n.rotateY||n.rotateZ||n.skewX||n.skewY)&&(e=!0),!e)return;const i={};n.z&&xr("z",t,i,this.animationValues);for(let e=0;et.currentAnimation?.stop()),this.root.nodes.forEach(Vr),this.root.sharedNodes.clear()}}}function Pr(t){t.updateLayout()}function Sr(t){const e=t.resumeFrom?.snapshot||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:i}=t.layout,{animationType:s}=t.options,o=e.source!==t.layout.source;"size"===s?Ao(t=>{const i=o?e.measuredBox[t]:e.layoutBox[t],s=xo(i);i.min=n[t].min,i.max=i.min+s}):$r(s,e.layoutBox,n)&&Ao(i=>{const s=o?e.measuredBox[i]:e.layoutBox[i],r=xo(n[i]);s.max=s.min+r,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[i].max=t.relativeTarget[i].min+r)});const r={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}};wo(r,n,e.layoutBox);const a={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}};o?wo(a,t.applyTransform(i,!0),e.measuredBox):wo(a,n,e.layoutBox);const l=!hr(r);let h=!1;if(!t.resumeFrom){const i=t.getClosestProjectingParent();if(i&&!i.resumeFrom){const{snapshot:s,layout:o}=i;if(s&&o){const r={x:{min:0,max:0},y:{min:0,max:0}};bo(r,e.layoutBox,s.layoutBox);const a={x:{min:0,max:0},y:{min:0,max:0}};bo(a,n,o.layoutBox),dr(r,a)||(h=!0),i.options.layoutRoot&&(t.relativeTarget=a,t.relativeTargetOrigin=r,t.relativeParent=i)}}}t.notifyListeners("didUpdate",{layout:n,snapshot:e,delta:a,layoutDelta:r,hasLayoutChanged:l,hasRelativeLayoutChanged:h})}else if(t.isLead()){const{onExitComplete:e}=t.options;e&&e()}t.options.transition=void 0}function br(t){t.parent&&(t.isProjecting()||(t.isProjectionDirty=t.parent.isProjectionDirty),t.isSharedProjectionDirty||(t.isSharedProjectionDirty=Boolean(t.isProjectionDirty||t.parent.isProjectionDirty||t.parent.isSharedProjectionDirty)),t.isTransformDirty||(t.isTransformDirty=t.parent.isTransformDirty))}function Ar(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Er(t){t.clearSnapshot()}function Vr(t){t.clearMeasurements()}function Mr(t){t.isLayoutDirty=!1}function Cr(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Dr(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function kr(t){t.resolveTargetDelta()}function Rr(t){t.calcProjection()}function Lr(t){t.resetSkewAndRotation()}function jr(t){t.removeLeadSnapshot()}function Br(t,e,n){t.translate=Jt(e.translate,0,n),t.scale=Jt(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function Fr(t,e,n,i){t.min=Jt(e.min,n.min,i),t.max=Jt(e.max,n.max,i)}function Or(t){return t.animationValues&&void 0!==t.animationValues.opacityExit}const Ir={duration:.45,ease:[.4,0,.1,1]},Ur=t=>"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Nr=Ur("applewebkit/")&&!Ur("chrome/")?Math.round:S;function Wr(t){t.min=Nr(t.min),t.max=Nr(t.max)}function $r(t,e,n){return"position"===t||"preserve-aspect"===t&&(i=pr(e),s=pr(n),o=.2,!(Math.abs(i-s)<=o));var i,s,o}function Yr(t){return t!==t.root&&t.scroll?.wasRoot}const Xr=wr({attachResizeListener:(t,e)=>yo(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Kr={current:void 0},zr=wr({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Kr.current){const t=new Xr({});t.mount(window),t.setOptions({layoutScroll:!0}),Kr.current=t}return Kr.current},resetTransform:(t,e)=>{t.style.transform=void 0!==e?e:"none"},checkIsScrollRoot:t=>Boolean("fixed"===window.getComputedStyle(t).position)});function Hr(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const Gr={correct:(t,e)=>{if(!e.target)return t;if("string"==typeof t){if(!Bt.test(t))return t;t=parseFloat(t)}return`${Hr(t,e.target.x)}% ${Hr(t,e.target.y)}%`}},qr={correct:(t,{treeScale:e,projectionDelta:n})=>{const i=t,s=qt.parse(t);if(s.length>5)return i;const o=qt.createTransformer(t),r="number"!=typeof s[0]?1:0,a=n.x.scale*e.x,l=n.y.scale*e.y;s[0+r]/=a,s[1+r]/=l;const h=Jt(a,l,.5);return"number"==typeof s[2+r]&&(s[2+r]/=h),"number"==typeof s[3+r]&&(s[3+r]/=h),o(s)}};let Zr=!1;class _r extends m{componentDidMount(){const{visualElement:t,layoutGroup:e,switchLayoutGroup:n,layoutId:i}=this.props,{projection:s}=t;!function(t){for(const e in t)Ti[e]=t[e],gt(e)&&(Ti[e].isCSSVariable=!0)}(Qr),s&&(e.group&&e.group.add(s),n&&n.register&&i&&n.register(s),Zr&&s.root.didUpdate(),s.addEventListener("animationComplete",()=>{this.safeToRemove()}),s.setOptions({...s.options,onExitComplete:()=>this.safeToRemove()})),yr.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:e,visualElement:n,drag:i,isPresent:s}=this.props,{projection:o}=n;return o?(o.isPresent=s,Zr=!0,i||t.layoutDependency!==e||void 0===e||t.isPresent!==s?o.willUpdate():this.safeToRemove(),t.isPresent!==s&&(s?o.promote():o.relegate()||ht.postRender(()=>{const t=o.getStack();t&&t.members.length||this.safeToRemove()})),null):null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),ii.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:e,switchLayoutGroup:n}=this.props,{projection:i}=t;Zr=!0,i&&(i.scheduleCheckAfterUnmount(),e&&e.group&&e.group.remove(i),n&&n.deregister&&n.deregister(i))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function Jr(t){const[n,s]=function(t=!0){const e=i($i);if(null===e)return[!0,null];const{isPresent:n,onExitComplete:s,register:o}=e,r=p();u(()=>{if(t)return o(r)},[t]);const a=l(()=>t&&s&&s(r),[r,s,t]);return!n&&s?[!1,a]:[!0]}(),o=i(G);return e(_r,{...t,layoutGroup:o,switchLayoutGroup:i(rs),isPresent:n,safeToRemove:s})}const Qr={borderRadius:{...Gr,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Gr,borderTopRightRadius:Gr,borderBottomLeftRadius:Gr,borderBottomRightRadius:Gr,boxShadow:qr},ta={pan:{Feature:class extends po{constructor(){super(...arguments),this.removePointerDownListener=S}onPointerDown(t){this.session=new Mo(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Eo(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:e,onPan:n,onPanEnd:i}=this.node.getProps();return{onSessionStart:Yo(t),onStart:Yo(e),onMove:n,onEnd:(t,e)=>{delete this.session,i&&ht.postRender(()=>i(t,e))}}}mount(){this.removePointerDownListener=vo(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}},drag:{Feature:class extends po{constructor(t){super(t),this.removeGroupControls=S,this.removeListeners=S,this.controls=new Wo(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||S}unmount(){this.removeGroupControls(),this.removeListeners()}},ProjectionNode:zr,MeasureLayout:Jr}};function ea(t,e,n){const{props:i}=t;t.animationState&&i.whileHover&&t.animationState.setActive("whileHover","Start"===n);const s=i["onHover"+n];s&&ht.postRender(()=>s(e,go(e)))}function na(t,e,n){const{props:i}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&i.whileTap&&t.animationState.setActive("whileTap","Start"===n);const s=i["onTap"+("End"===n?"":n)];s&&ht.postRender(()=>s(e,go(e)))}const ia=new WeakMap,sa=new WeakMap,oa=t=>{const e=ia.get(t.target);e&&e(t)},ra=t=>{t.forEach(oa)};function aa(t,e,n){const i=function({root:t,...e}){const n=t||document;sa.has(n)||sa.set(n,{});const i=sa.get(n),s=JSON.stringify(e);return i[s]||(i[s]=new IntersectionObserver(ra,{root:t,...e})),i[s]}(e);return ia.set(t,n),i.observe(t),()=>{ia.delete(t),i.unobserve(t)}}const la={some:0,all:1};const ha={...fo,...{inView:{Feature:class extends po{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:e,margin:n,amount:i="some",once:s}=t,o={root:e?e.current:void 0,rootMargin:n,threshold:"number"==typeof i?i:la[i]};return aa(this.node.current,o,t=>{const{isIntersecting:e}=t;if(this.isInView===e)return;if(this.isInView=e,s&&!e&&this.hasEnteredView)return;e&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",e);const{onViewportEnter:n,onViewportLeave:i}=this.node.getProps(),o=e?n:i;o&&o(t)})}mount(){this.startObserver()}update(){if("undefined"==typeof IntersectionObserver)return;const{props:t,prevProps:e}=this.node;["amount","margin","root"].some(function({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}(t,e))&&this.startObserver()}unmount(){}}},tap:{Feature:class extends po{mount(){const{current:t}=this.node;t&&(this.unmount=yi(t,(t,e)=>(na(this.node,e,"Start"),(t,{success:e})=>na(this.node,t,e?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}},focus:{Feature:class extends po{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch(e){t=!0}t&&this.node.animationState&&(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){this.isActive&&this.node.animationState&&(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=A(yo(this.node.current,"focus",()=>this.onFocus()),yo(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}},hover:{Feature:class extends po{mount(){const{current:t}=this.node;t&&(this.unmount=function(t,e,n={}){const[i,s,o]=ai(t,n),r=t=>{if(!li(t))return;const{target:n}=t,i=e(n,t);if("function"!=typeof i||!n)return;const o=t=>{li(t)&&(i(t),n.removeEventListener("pointerleave",o))};n.addEventListener("pointerleave",o,s)};return i.forEach(t=>{t.addEventListener("pointerenter",r,s)}),o}(t,(t,e)=>(ea(this.node,e,"Start"),t=>ea(this.node,t,"End"))))}unmount(){}}}},...ta,...{layout:{ProjectionNode:zr,MeasureLayout:Jr}}};function ua(t,e){return us(t,e,ha,Us)}const ca=ua("div");export{ca as MotionDiv}; diff --git a/frontend/node_modules/framer-motion/dist/size-rollup-scroll.js b/frontend/node_modules/framer-motion/dist/size-rollup-scroll.js new file mode 100644 index 0000000000000000000000000000000000000000..fbdc24d5c5b5c215c1642185caab9c36479ff232 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/size-rollup-scroll.js @@ -0,0 +1 @@ +const e=(e,t,n)=>n>t?t:n(void 0===t&&(t=e()),t)}const s=e=>e,o=(e,t)=>n=>t(e(n)),i=(...e)=>e.reduce(o),a=(e,t,n)=>{const r=t-e;return 0===r?1:(n-e)/r};const c=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],u={value:null,addProjectionMetrics:null};function l(e,n){let r=!1,s=!0;const o={delta:0,timestamp:0,isProcessing:!1},i=()=>r=!0,a=c.reduce((e,t)=>(e[t]=function(e,t){let n=new Set,r=new Set,s=!1,o=!1;const i=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},c=0;function l(t){i.has(t)&&(f.schedule(t),e()),c++,t(a)}const f={schedule:(e,t=!1,o=!1)=>{const a=o&&s?n:r;return t&&i.add(e),a.has(e)||a.add(e),e},cancel:e=>{r.delete(e),i.delete(e)},process:e=>{a=e,s?o=!0:(s=!0,[n,r]=[r,n],n.forEach(l),t&&u.value&&u.value.frameloop[t].push(c),c=0,n.clear(),s=!1,o&&(o=!1,f.process(e)))}};return f}(i,n?t:void 0),e),{}),{setup:l,read:f,resolveKeyframes:g,preUpdate:d,update:h,preRender:p,render:m,postRender:v}=a,y=()=>{const i=t.useManualTiming?o.timestamp:performance.now();r=!1,t.useManualTiming||(o.delta=s?1e3/60:Math.max(Math.min(i-o.timestamp,40),1)),o.timestamp=i,o.isProcessing=!0,l.process(o),f.process(o),g.process(o),d.process(o),h.process(o),p.process(o),m.process(o),v.process(o),o.isProcessing=!1,r&&n&&(s=!1,e(y))};return{schedule:c.reduce((t,n)=>{const i=a[n];return t[n]=(t,n=!1,a=!1)=>(r||(r=!0,s=!0,o.isProcessing||e(y)),i.schedule(t,n,a)),t},{}),cancel:e=>{for(let t=0;tt=>"string"==typeof t&&t.startsWith(e))("var(--"),m=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,v={test:e=>"number"==typeof e,parse:parseFloat,transform:e=>e},y={...v,transform:t=>e(0,1,t)},b=e=>Math.round(1e5*e)/1e5,w=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;const x=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,E=(e,t)=>n=>Boolean("string"==typeof n&&x.test(n)&&n.startsWith(e)||t&&!function(e){return null==e}(n)&&Object.prototype.hasOwnProperty.call(n,t)),W=(e,t,n)=>r=>{if("string"!=typeof r)return r;const[s,o,i,a]=r.match(w);return{[e]:parseFloat(s),[t]:parseFloat(o),[n]:parseFloat(i),alpha:void 0!==a?parseFloat(a):1}},L={...v,transform:t=>Math.round((t=>e(0,255,t))(t))},M={test:E("rgb","red"),parse:W("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:r=1})=>"rgba("+L.transform(e)+", "+L.transform(t)+", "+L.transform(n)+", "+b(y.transform(r))+")"};const A={test:E("#"),parse:function(e){let t="",n="",r="",s="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),r=e.substring(5,7),s=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),r=e.substring(3,4),s=e.substring(4,5),t+=t,n+=n,r+=r,s+=s),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:s?parseInt(s,16)/255:1}},transform:M.transform},B=(e=>({test:t=>"string"==typeof t&&t.endsWith(e)&&1===t.split(" ").length,parse:parseFloat,transform:t=>`${t}${e}`}))("%"),S={test:E("hsl","hue"),parse:W("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(e)+", "+B.transform(b(t))+", "+B.transform(b(n))+", "+b(y.transform(r))+")"},O={test:e=>M.test(e)||A.test(e)||S.test(e),parse:e=>M.test(e)?M.parse(e):S.test(e)?S.parse(e):A.parse(e),transform:e=>"string"==typeof e?e:e.hasOwnProperty("red")?M.transform(e):S.transform(e),getAnimatableNone:e=>{const t=O.parse(e);return t.alpha=0,O.transform(t)}},T=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;const z="number",H="color",F=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function N(e){const t=e.toString(),n=[],r={color:[],number:[],var:[]},s=[];let o=0;const i=t.replace(F,e=>(O.test(e)?(r.color.push(o),s.push(H),n.push(O.parse(e))):e.startsWith("var(")?(r.var.push(o),s.push("var"),n.push(e)):(r.number.push(o),s.push(z),n.push(parseFloat(e))),++o,"${}")).split("${}");return{values:n,split:i,indexes:r,types:s}}function P(e){return N(e).values}function $(e){const{split:t,types:n}=N(e),r=t.length;return e=>{let s="";for(let o=0;o"number"==typeof e?0:O.test(e)?O.getAnimatableNone(e):e;const k={test:function(e){return isNaN(e)&&"string"==typeof e&&(e.match(w)?.length||0)+(e.match(T)?.length||0)>0},parse:P,createTransformer:$,getAnimatableNone:function(e){const t=P(e);return $(e)(t.map(R))}};function j(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function q(e,t){return n=>n>0?t:e}const I=(e,t,n)=>e+(t-e)*n,U=(e,t,n)=>{const r=e*e,s=n*(t*t-r)+r;return s<0?0:Math.sqrt(s)},G=[A,M,S];function C(e){const t=(n=e,G.find(e=>e.test(n)));var n;if(!Boolean(t))return!1;let r=t.parse(e);return t===S&&(r=function({hue:e,saturation:t,lightness:n,alpha:r}){e/=360,n/=100;let s=0,o=0,i=0;if(t/=100){const r=n<.5?n*(1+t):n+t-n*t,a=2*n-r;s=j(a,r,e+1/3),o=j(a,r,e),i=j(a,r,e-1/3)}else s=o=i=n;return{red:Math.round(255*s),green:Math.round(255*o),blue:Math.round(255*i),alpha:r}}(r)),r}const K=(e,t)=>{const n=C(e),r=C(t);if(!n||!r)return q(e,t);const s={...n};return e=>(s.red=U(n.red,r.red,e),s.green=U(n.green,r.green,e),s.blue=U(n.blue,r.blue,e),s.alpha=I(n.alpha,r.alpha,e),M.transform(s))},V=new Set(["none","hidden"]);function D(e,t){return n=>I(e,t,n)}function J(e){return"number"==typeof e?D:"string"==typeof e?p(t=e)&&m.test(t.split("/*")[0].trim())?q:O.test(e)?K:Y:Array.isArray(e)?Q:"object"==typeof e?O.test(e)?K:X:q;var t}function Q(e,t){const n=[...e],r=n.length,s=e.map((e,n)=>J(e)(e,t[n]));return e=>{for(let t=0;t{for(const t in r)n[t]=r[t](e);return n}}const Y=(e,t)=>{const n=k.createTransformer(t),r=N(e),s=N(t);return r.indexes.var.length===s.indexes.var.length&&r.indexes.color.length===s.indexes.color.length&&r.indexes.number.length>=s.indexes.number.length?V.has(e)&&!s.values.length||V.has(t)&&!r.values.length?function(e,t){return V.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}(e,t):i(Q(function(e,t){const n=[],r={color:0,var:0,number:0};for(let s=0;sr[0];if(2===l&&r[0]===r[1])return()=>r[1];const f=n[0]===n[1];n[0]>n[l-1]&&(n=[...n].reverse(),r=[...r].reverse());const g=function(e,n,r){const o=[],a=r||t.mix||Z,c=e.length-1;for(let t=0;t{if(f&&e1)for(;th(e(n[0],n[l-1],t)):h}function ee(e){const t=[0];return function(e,t){const n=e[e.length-1];for(let r=1;r<=t;r++){const s=a(0,t,r);e.push(I(n,1,s))}}(t,e.length-1),t}const te=r(()=>void 0!==window.ScrollTimeline);function ne(e){return n(e)&&"offsetHeight"in e}const re=new WeakMap;let se;const oe=(e,t,r)=>(s,o)=>{return o&&o[0]?o[0][e+"Size"]:n(i=s)&&"ownerSVGElement"in i&&"getBBox"in s?s.getBBox()[t]:s[r];var i},ie=oe("inline","width","offsetWidth"),ae=oe("block","height","offsetHeight");function ce({target:e,borderBoxSize:t}){re.get(e)?.forEach(n=>{n(e,{get width(){return ie(e,t)},get height(){return ae(e,t)}})})}function ue(e){e.forEach(ce)}function le(e,t){se||"undefined"!=typeof ResizeObserver&&(se=new ResizeObserver(ue));const n=function(e,t,n){if(e instanceof EventTarget)return[e];if("string"==typeof e){let r=document;t&&(r=t.current);const s=n?.[e]??r.querySelectorAll(e);return s?Array.from(s):[]}return Array.from(e)}(e);return n.forEach(e=>{let n=re.get(e);n||(n=new Set,re.set(e,n)),n.add(t),se?.observe(e)}),()=>{n.forEach(e=>{const n=re.get(e);n?.delete(t),n?.size||se?.unobserve(e)})}}const fe=new Set;let ge;function de(e){return fe.add(e),ge||(ge=()=>{const e={get width(){return window.innerWidth},get height(){return window.innerHeight}};fe.forEach(t=>t(e))},window.addEventListener("resize",ge)),()=>{fe.delete(e),fe.size||"function"!=typeof ge||(window.removeEventListener("resize",ge),ge=void 0)}}function he(e,t){let n;const r=()=>{const{currentTime:r}=t,s=(null===r?0:r.value)/100;n!==s&&e(s),n=s};return f.preUpdate(r,!0),()=>g(r)}const pe={x:{length:"Width",position:"Left"},y:{length:"Height",position:"Top"}};function me(e,t,n,r){const s=n[t],{length:o,position:i}=pe[t],c=s.current,u=n.time;s.current=e[`scroll${i}`],s.scrollLength=e[`scroll${o}`]-e[`client${o}`],s.offset.length=0,s.offset[0]=0,s.offset[1]=s.scrollLength,s.progress=a(0,s.scrollLength,s.current);const l=r-u;var f,g;s.velocity=l>50?0:(f=s.current-c,(g=l)?f*(1e3/g):0)}const ve={start:0,center:.5,end:1};function ye(e,t,n=0){let r=0;if(e in ve&&(e=ve[e]),"string"==typeof e){const t=parseFloat(e);e.endsWith("px")?r=t:e.endsWith("%")?e=t/100:e.endsWith("vw")?r=t/100*document.documentElement.clientWidth:e.endsWith("vh")?r=t/100*document.documentElement.clientHeight:e=t}return"number"==typeof e&&(r=t*e),n+r}const be=[0,0];function we(e,t,n,r){let s=Array.isArray(e)?e:be,o=0,i=0;return"number"==typeof e?s=[e,e]:"string"==typeof e&&(s=(e=e.trim()).includes(" ")?e.split(" "):[e,ve[e]?e:"0"]),o=ye(s[0],n,r),i=ye(s[1],t),o-i}const xe={Enter:[[0,1],[1,1]],Exit:[[0,0],[1,0]],Any:[[1,0],[0,1]],All:[[0,0],[1,1]]},Ee={x:0,y:0};function We(t,n,r){const{offset:s=xe.All}=r,{target:o=t,axis:i="y"}=r,a="y"===i?"height":"width",c=o!==t?function(e,t){const n={x:0,y:0};let r=e;for(;r&&r!==t;)if(ne(r))n.x+=r.offsetLeft,n.y+=r.offsetTop,r=r.offsetParent;else if("svg"===r.tagName){const e=r.getBoundingClientRect();r=r.parentElement;const t=r.getBoundingClientRect();n.x+=e.left-t.left,n.y+=e.top-t.top}else{if(!(r instanceof SVGGraphicsElement))break;{const{x:e,y:t}=r.getBBox();n.x+=e,n.y+=t;let s=null,o=r.parentNode;for(;!s;)"svg"===o.tagName&&(s=o),o=r.parentNode;r=s}}return n}(o,t):Ee,u=o===t?{width:t.scrollWidth,height:t.scrollHeight}:function(e){return"getBBox"in e&&"svg"!==e.tagName?e.getBBox():{width:e.clientWidth,height:e.clientHeight}}(o),l={width:t.clientWidth,height:t.clientHeight};n[i].offset.length=0;let f=!n[i].interpolate;const g=s.length;for(let e=0;e{!function(e,t=e,n){if(n.x.targetOffset=0,n.y.targetOffset=0,t!==e){let r=t;for(;r&&r!==e;)n.x.targetOffset+=r.offsetLeft,n.y.targetOffset+=r.offsetTop,r=r.offsetParent}n.x.targetLength=t===e?t.scrollWidth:t.clientWidth,n.y.targetLength=t===e?t.scrollHeight:t.clientHeight,n.x.containerLength=e.clientWidth,n.y.containerLength=e.clientHeight}(e,r.target,n),function(e,t,n){me(e,"x",t,n),me(e,"y",t,n),t.time=n}(e,n,t),(r.offset||r.target)&&We(e,n,r)},notify:()=>t(n)}}const Me=new WeakMap,Ae=new WeakMap,Be=new WeakMap,Se=e=>e===document.scrollingElement?window:e;function Oe(e,{container:t=document.scrollingElement,...n}={}){if(!t)return s;let r=Be.get(t);r||(r=new Set,Be.set(t,r));const o=Le(t,e,{time:0,x:{current:0,offset:[],progress:0,scrollLength:0,targetOffset:0,targetLength:0,containerLength:0,velocity:0},y:{current:0,offset:[],progress:0,scrollLength:0,targetOffset:0,targetLength:0,containerLength:0,velocity:0}},n);if(r.add(o),!Me.has(t)){const e=()=>{for(const e of r)e.measure(d.timestamp);f.preUpdate(n)},n=()=>{for(const e of r)e.notify()},s=()=>f.read(e);Me.set(t,s);const o=Se(t);window.addEventListener("resize",s,{passive:!0}),t!==document.documentElement&&Ae.set(t,(a=s,"function"==typeof(i=t)?de(i):le(i,a))),o.addEventListener("scroll",s,{passive:!0}),s()}var i,a;const c=Me.get(t);return f.read(c,!1,!0),()=>{g(c);const e=Be.get(t);if(!e)return;if(e.delete(o),e.size)return;const n=Me.get(t);Me.delete(t),n&&(Se(t).removeEventListener("scroll",n),Ae.get(t)?.(),window.removeEventListener("resize",n))}}const Te=new Map;function ze({source:e,container:t,...n}){const{axis:r}=n;e&&(t=e);const s=Te.get(t)??new Map;Te.set(t,s);const o=n.target??"self",i=s.get(o)??{},a=r+(n.offset??[]).join(",");return i[a]||(i[a]=!n.target&&te()?new ScrollTimeline({source:t,axis:r}):function(e){const t={value:0},n=Oe(n=>{t.value=100*n[e.axis].progress},e);return{currentTime:t,cancel:n}}({container:t,...n})),i[a]}function He(e,{axis:t="y",container:n=document.scrollingElement,...r}={}){if(!n)return s;const o={axis:t,container:n,...r};return"function"==typeof e?function(e,t){return function(e){return 2===e.length}(e)?Oe(n=>{e(n[t.axis].progress,n)},t):he(e,ze(t))}(e,o):function(e,t){const n=ze(t);return e.attachTimeline({timeline:t.target?void 0:n,observe:e=>(e.pause(),he(t=>{e.time=e.duration*t},n))})}(e,o)}export{He as scroll}; diff --git a/frontend/node_modules/framer-motion/dist/size-rollup-waapi-animate.js b/frontend/node_modules/framer-motion/dist/size-rollup-waapi-animate.js new file mode 100644 index 0000000000000000000000000000000000000000..d1c1461dec0caa4bb414ebee588f770f1c4c393d --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/size-rollup-waapi-animate.js @@ -0,0 +1 @@ +function t(t){let e;return()=>(void 0===e&&(e=t()),e)}const e=t=>t,i=t=>1e3*t,n=t=>t/1e3,s=t=>null!==t;class a{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,e){return this.finished.then(t,e)}}function o(t){for(let e=1;et.startsWith("--");const l=t(()=>void 0!==window.ScrollTimeline),u={};function h(e,i){const n=t(e);return()=>u[i]??n()}const m=h(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch(t){return!1}return!0},"linearEasing"),d=([t,e,i,n])=>`cubic-bezier(${t}, ${e}, ${i}, ${n})`,c={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:d([0,.65,.55,1]),circOut:d([.55,0,1,.45]),backIn:d([.31,.01,.66,-.59]),backOut:d([.33,1.53,.69,.99])};function p(t,e){return t?"function"==typeof t?m()?((t,e,i=10)=>{let n="";const s=Math.max(Math.round(e/i),2);for(let e=0;eArray.isArray(t)&&"number"==typeof t[0])(t)?d(t):Array.isArray(t)?t.map(t=>p(t,e)||c.easeOut):c[t]:void 0}class f extends a{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:e,name:i,keyframes:n,pseudoElement:a,allowFlatten:o=!1,finalKeyframe:l,onComplete:u}=t;this.isPseudoElement=Boolean(a),this.allowFlatten=o,this.options=t,t.type;const h=function({type:t,...e}){return function(t){return"function"==typeof t&&"applyToOptions"in t}(t)&&m()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}(t);this.animation=function(t,e,i,{delay:n=0,duration:s=300,repeat:a=0,repeatType:o="loop",ease:r="easeOut",times:l}={},u){const h={[e]:i};l&&(h.offset=l);const m=p(r,s);Array.isArray(m)&&(h.easing=m);const d={delay:n,duration:s,easing:Array.isArray(m)?"linear":m,fill:"both",iterations:a+1,direction:"reverse"===o?"alternate":"normal"};return u&&(d.pseudoElement=u),t.animate(h,d)}(e,i,n,h,a),!1===h.autoplay&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!a){const t=function(t,{repeat:e,repeatType:i="loop"},n,a=1){const o=t.filter(s),r=a<0||e&&"loop"!==i&&e%2==1?0:o.length-1;return r&&void 0!==n?n:o[r]}(n,this.options,l,this.speed);this.updateMotionValue?this.updateMotionValue(t):function(t,e,i){r(e)?t.style.setProperty(e,i):t.style[e]=i}(e,i,t),this.animation.cancel()}u?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),"finished"===this.state&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch(t){}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;"idle"!==t&&"finished"!==t&&(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming?.().duration||0;return n(Number(t))}get time(){return n(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=i(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return null!==this.finishedTime?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:i}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&l()?(this.animation.timeline=t,e):i(this)}}class y{constructor(t){this.stop=()=>this.runAll("stop"),this.animations=t.filter(Boolean)}get finished(){return Promise.all(this.animations.map(t=>t.finished))}getAll(t){return this.animations[0][t]}setAll(t,e){for(let i=0;ie.attachTimeline(t));return()=>{e.forEach((t,e)=>{t&&t(),this.animations[e].stop()})}}get time(){return this.getAll("time")}set time(t){this.setAll("time",t)}get speed(){return this.getAll("speed")}set speed(t){this.setAll("speed",t)}get state(){return this.getAll("state")}get startTime(){return this.getAll("startTime")}get duration(){let t=0;for(let e=0;ee[t]())}play(){this.runAll("play")}pause(){this.runAll("pause")}cancel(){this.runAll("cancel")}complete(){this.runAll("complete")}}class g extends y{then(t,e){return this.finished.finally(t).then(()=>{})}}const T=new WeakMap,b=(t,e="")=>`${t}:${e}`;function A(t){const e=T.get(t)||new Map;return T.set(t,e),e}function w(t,e){return t?.[e]??t?.default??t}const v=new Set(["borderWidth","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderRadius","radius","borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius","width","maxWidth","height","maxHeight","top","right","bottom","left","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","margin","marginTop","marginRight","marginBottom","marginLeft","backgroundPositionX","backgroundPositionY"]);function E(t,e){for(let i=0;ie.delete(i)),u.push(s)}return u}const k=t=>function(e,i,n){return new g(S(e,i,n,t))},M=k();export{M as animateMini,k as createScopedWaapiAnimate}; diff --git a/frontend/node_modules/framer-motion/dist/types.d-Cjd591yU.d.ts b/frontend/node_modules/framer-motion/dist/types.d-Cjd591yU.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..91e3859307e82a659befb121b8e7e7b03c73aaa9 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/types.d-Cjd591yU.d.ts @@ -0,0 +1,958 @@ +/// +import * as React$1 from 'react'; +import { CSSProperties, PropsWithoutRef, RefAttributes, JSX, SVGAttributes } from 'react'; +import * as motion_dom from 'motion-dom'; +import { Transition, TransformProperties, MotionNodeOptions, MotionValue, SVGPathProperties, JSAnimation, ValueTransition, TargetAndTransition, AnyResolvedKeyframe, KeyframeResolver, AnimationDefinition, Batcher } from 'motion-dom'; +import { TransformPoint, Box, Delta, Point, Axis } from 'motion-utils'; +import * as react_jsx_runtime from 'react/jsx-runtime'; + +type ReducedMotionConfig = "always" | "never" | "user"; +/** + * @public + */ +interface MotionConfigContext { + /** + * Internal, exported only for usage in Framer + */ + transformPagePoint: TransformPoint; + /** + * Internal. Determines whether this is a static context ie the Framer canvas. If so, + * it'll disable all dynamic functionality. + */ + isStatic: boolean; + /** + * Defines a new default transition for the entire tree. + * + * @public + */ + transition?: Transition; + /** + * If true, will respect the device prefersReducedMotion setting by switching + * transform animations off. + * + * @public + */ + reducedMotion?: ReducedMotionConfig; + /** + * A custom `nonce` attribute used when wanting to enforce a Content Security Policy (CSP). + * For more details see: + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-src#unsafe_inline_styles + * + * @public + */ + nonce?: string; +} +/** + * @public + */ +declare const MotionConfigContext: React$1.Context; + +/** + * Either a string, or array of strings, that reference variants defined via the `variants` prop. + * @public + */ +type VariantLabels = string | string[]; + +type MotionValueString = MotionValue; +type MotionValueNumber = MotionValue; +type MotionValueAny = MotionValue; +type AnyMotionValue = MotionValueNumber | MotionValueString | MotionValueAny; +type MotionValueHelper = T | AnyMotionValue; +type MakeMotionHelper = { + [K in keyof T]: MotionValueHelper; +}; +type MakeCustomValueTypeHelper = MakeMotionHelper; +type MakeMotion = MakeCustomValueTypeHelper; +type MotionCSS = MakeMotion>; +/** + * @public + */ +type MotionTransform = MakeMotion; +type MotionSVGProps = MakeMotion; +/** + * @public + */ +interface MotionStyle extends MotionCSS, MotionTransform, MotionSVGProps { +} +/** + * Props for `motion` components. + * + * @public + */ +interface MotionProps extends MotionNodeOptions { + /** + * + * The React DOM `style` prop, enhanced with support for `MotionValue`s and separate `transform` values. + * + * ```jsx + * export const MyComponent = () => { + * const x = useMotionValue(0) + * + * return + * } + * ``` + */ + style?: MotionStyle; + children?: React.ReactNode | MotionValueNumber | MotionValueString; +} + +/** + * @public + */ +interface PresenceContextProps { + id: string; + isPresent: boolean; + register: (id: string | number) => () => void; + onExitComplete?: (id: string | number) => void; + initial?: false | VariantLabels; + custom?: any; +} +/** + * @public + */ +declare const PresenceContext: React$1.Context; + +interface VisualState { + renderState: RenderState; + latestValues: ResolvedValues; + onMount?: (instance: Instance) => void; +} +type UseVisualState = (props: MotionProps, isStatic: boolean) => VisualState; +interface UseVisualStateConfig { + scrapeMotionValuesFromProps: ScrapeMotionValuesFromProps; + createRenderState: () => RenderState; +} +declare const makeUseVisualState: (config: UseVisualStateConfig) => UseVisualState; + +interface HTMLElements { + a: HTMLAnchorElement; + abbr: HTMLElement; + address: HTMLElement; + area: HTMLAreaElement; + article: HTMLElement; + aside: HTMLElement; + audio: HTMLAudioElement; + b: HTMLElement; + base: HTMLBaseElement; + bdi: HTMLElement; + bdo: HTMLElement; + big: HTMLElement; + blockquote: HTMLQuoteElement; + body: HTMLBodyElement; + br: HTMLBRElement; + button: HTMLButtonElement; + canvas: HTMLCanvasElement; + caption: HTMLElement; + center: HTMLElement; + cite: HTMLElement; + code: HTMLElement; + col: HTMLTableColElement; + colgroup: HTMLTableColElement; + data: HTMLDataElement; + datalist: HTMLDataListElement; + dd: HTMLElement; + del: HTMLModElement; + details: HTMLDetailsElement; + dfn: HTMLElement; + dialog: HTMLDialogElement; + div: HTMLDivElement; + dl: HTMLDListElement; + dt: HTMLElement; + em: HTMLElement; + embed: HTMLEmbedElement; + fieldset: HTMLFieldSetElement; + figcaption: HTMLElement; + figure: HTMLElement; + footer: HTMLElement; + form: HTMLFormElement; + h1: HTMLHeadingElement; + h2: HTMLHeadingElement; + h3: HTMLHeadingElement; + h4: HTMLHeadingElement; + h5: HTMLHeadingElement; + h6: HTMLHeadingElement; + head: HTMLHeadElement; + header: HTMLElement; + hgroup: HTMLElement; + hr: HTMLHRElement; + html: HTMLHtmlElement; + i: HTMLElement; + iframe: HTMLIFrameElement; + img: HTMLImageElement; + input: HTMLInputElement; + ins: HTMLModElement; + kbd: HTMLElement; + keygen: HTMLElement; + label: HTMLLabelElement; + legend: HTMLLegendElement; + li: HTMLLIElement; + link: HTMLLinkElement; + main: HTMLElement; + map: HTMLMapElement; + mark: HTMLElement; + menu: HTMLElement; + menuitem: HTMLElement; + meta: HTMLMetaElement; + meter: HTMLMeterElement; + nav: HTMLElement; + noindex: HTMLElement; + noscript: HTMLElement; + object: HTMLObjectElement; + ol: HTMLOListElement; + optgroup: HTMLOptGroupElement; + option: HTMLOptionElement; + output: HTMLOutputElement; + p: HTMLParagraphElement; + param: HTMLParamElement; + picture: HTMLElement; + pre: HTMLPreElement; + progress: HTMLProgressElement; + q: HTMLQuoteElement; + rp: HTMLElement; + rt: HTMLElement; + ruby: HTMLElement; + s: HTMLElement; + samp: HTMLElement; + search: HTMLElement; + slot: HTMLSlotElement; + script: HTMLScriptElement; + section: HTMLElement; + select: HTMLSelectElement; + small: HTMLElement; + source: HTMLSourceElement; + span: HTMLSpanElement; + strong: HTMLElement; + style: HTMLStyleElement; + sub: HTMLElement; + summary: HTMLElement; + sup: HTMLElement; + table: HTMLTableElement; + template: HTMLTemplateElement; + tbody: HTMLTableSectionElement; + td: HTMLTableDataCellElement; + textarea: HTMLTextAreaElement; + tfoot: HTMLTableSectionElement; + th: HTMLTableHeaderCellElement; + thead: HTMLTableSectionElement; + time: HTMLTimeElement; + title: HTMLTitleElement; + tr: HTMLTableRowElement; + track: HTMLTrackElement; + u: HTMLElement; + ul: HTMLUListElement; + var: HTMLElement; + video: HTMLVideoElement; + wbr: HTMLElement; + webview: HTMLWebViewElement; +} + +interface TransformOrigin { + originX?: number | string; + originY?: number | string; + originZ?: number | string; +} +interface HTMLRenderState { + /** + * A mutable record of transforms we want to apply directly to the rendered Element + * every frame. We use a mutable data structure to reduce GC during animations. + */ + transform: ResolvedValues; + /** + * A mutable record of transform origins we want to apply directly to the rendered Element + * every frame. We use a mutable data structure to reduce GC during animations. + */ + transformOrigin: TransformOrigin; + /** + * A mutable record of styles we want to apply directly to the rendered Element + * every frame. We use a mutable data structure to reduce GC during animations. + */ + style: ResolvedValues; + /** + * A mutable record of CSS variables we want to apply directly to the rendered Element + * every frame. We use a mutable data structure to reduce GC during animations. + */ + vars: ResolvedValues; +} +/** + * @public + */ +type ForwardRefComponent = { + readonly $$typeof: symbol; +} & ((props: PropsWithoutRef

& RefAttributes) => JSX.Element); +type AttributesWithoutMotionProps = { + [K in Exclude]?: Attributes[K]; +}; +/** + * @public + */ +type HTMLMotionProps = AttributesWithoutMotionProps & MotionProps; +/** + * Motion-optimised versions of React's HTML components. + * + * @public + */ +type HTMLMotionComponents = { + [K in keyof HTMLElements]: ForwardRefComponent>; +}; + +type UnionStringArray> = T[number]; +declare const svgElements: readonly ["animate", "circle", "defs", "desc", "ellipse", "g", "image", "line", "filter", "marker", "mask", "metadata", "path", "pattern", "polygon", "polyline", "rect", "stop", "svg", "switch", "symbol", "text", "tspan", "use", "view", "clipPath", "feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feDropShadow", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence", "foreignObject", "linearGradient", "radialGradient", "textPath"]; +type SVGElements = UnionStringArray; + +interface SVGAttributesWithoutMotionProps extends Pick, Exclude, keyof MotionProps>> { +} +/** + * Blanket-accept any SVG attribute as a `MotionValue` + * @public + */ +type SVGAttributesAsMotionValues = MakeMotion>; +type UnwrapSVGFactoryElement = F extends React.SVGProps ? P : never; +/** + * @public + */ +interface SVGMotionProps extends SVGAttributesAsMotionValues, MotionProps { +} +/** + * Motion-optimised versions of React's SVG components. + * + * @public + */ +type SVGMotionComponents = { + [K in SVGElements]: ForwardRefComponent, SVGMotionProps>>; +}; + +type DOMMotionComponents = HTMLMotionComponents & SVGMotionComponents; + +interface SwitchLayoutGroup { + register?: (member: IProjectionNode) => void; + deregister?: (member: IProjectionNode) => void; +} +type InitialPromotionConfig = { + /** + * The initial transition to use when the elements in this group mount (and automatically promoted). + * Subsequent updates should provide a transition in the promote method. + */ + transition?: Transition; + /** + * If the follow tree should preserve its opacity when the lead is promoted on mount + */ + shouldPreserveFollowOpacity?: (member: IProjectionNode) => boolean; +}; +type SwitchLayoutGroupContext = SwitchLayoutGroup & InitialPromotionConfig; +/** + * Internal, exported only for usage in Framer + */ +declare const SwitchLayoutGroupContext: React$1.Context; + +interface WithDepth { + depth: number; +} + +declare class FlatTree { + private children; + private isDirty; + add(child: WithDepth): void; + remove(child: WithDepth): void; + forEach(callback: (child: WithDepth) => void): void; +} + +declare class NodeStack { + lead?: IProjectionNode; + prevLead?: IProjectionNode; + members: IProjectionNode[]; + add(node: IProjectionNode): void; + remove(node: IProjectionNode): void; + relegate(node: IProjectionNode): boolean; + promote(node: IProjectionNode, preserveFollowOpacity?: boolean): void; + exitAnimationComplete(): void; + scheduleRender(): void; + /** + * Clear any leads that have been removed this render to prevent them from being + * used in future animations and to prevent memory leaks + */ + removeLeadSnapshot(): void; +} + +interface Measurements { + animationId: number; + measuredBox: Box; + layoutBox: Box; + latestValues: ResolvedValues; + source: number; +} +type Phase = "snapshot" | "measure"; +interface ScrollMeasurements { + animationId: number; + phase: Phase; + offset: Point; + isRoot: boolean; + wasRoot: boolean; +} +type LayoutEvents = "willUpdate" | "didUpdate" | "beforeMeasure" | "measure" | "projectionUpdate" | "animationStart" | "animationComplete"; +interface IProjectionNode { + id: number; + animationId: number; + animationCommitId: number; + parent?: IProjectionNode; + relativeParent?: IProjectionNode; + root?: IProjectionNode; + children: Set; + path: IProjectionNode[]; + nodes?: FlatTree; + depth: number; + instance: I | undefined; + mount: (node: I, isLayoutDirty?: boolean) => void; + unmount: () => void; + options: ProjectionNodeOptions; + setOptions(options: ProjectionNodeOptions): void; + layout?: Measurements; + snapshot?: Measurements; + target?: Box; + relativeTarget?: Box; + relativeTargetOrigin?: Box; + targetDelta?: Delta; + targetWithTransforms?: Box; + scroll?: ScrollMeasurements; + treeScale?: Point; + projectionDelta?: Delta; + projectionDeltaWithTransform?: Delta; + latestValues: ResolvedValues; + isLayoutDirty: boolean; + isProjectionDirty: boolean; + isSharedProjectionDirty: boolean; + isTransformDirty: boolean; + resolvedRelativeTargetAt?: number; + shouldResetTransform: boolean; + prevTransformTemplateValue: string | undefined; + isUpdateBlocked(): boolean; + updateManuallyBlocked: boolean; + updateBlockedByResize: boolean; + blockUpdate(): void; + unblockUpdate(): void; + isUpdating: boolean; + needsReset: boolean; + startUpdate(): void; + willUpdate(notifyListeners?: boolean): void; + didUpdate(): void; + measure(removeTransform?: boolean): Measurements; + measurePageBox(): Box; + updateLayout(): void; + updateSnapshot(): void; + clearSnapshot(): void; + updateScroll(phase?: Phase): void; + scheduleUpdateProjection(): void; + scheduleCheckAfterUnmount(): void; + checkUpdateFailed(): void; + sharedNodes: Map; + registerSharedNode(id: string, node: IProjectionNode): void; + getStack(): NodeStack | undefined; + isVisible: boolean; + hide(): void; + show(): void; + scheduleRender(notifyAll?: boolean): void; + getClosestProjectingParent(): IProjectionNode | undefined; + setTargetDelta(delta: Delta): void; + resetTransform(): void; + resetSkewAndRotation(): void; + applyTransform(box: Box, transformOnly?: boolean): Box; + resolveTargetDelta(force?: boolean): void; + calcProjection(): void; + applyProjectionStyles(targetStyle: CSSStyleDeclaration, styleProp?: MotionStyle): void; + clearMeasurements(): void; + resetTree(): void; + isProjecting(): boolean; + animationValues?: ResolvedValues; + currentAnimation?: JSAnimation; + isTreeAnimating?: boolean; + isAnimationBlocked?: boolean; + isTreeAnimationBlocked: () => boolean; + setAnimationOrigin(delta: Delta): void; + startAnimation(transition: ValueTransition): void; + finishAnimation(): void; + hasCheckedOptimisedAppear: boolean; + isLead(): boolean; + promote(options?: { + needsReset?: boolean; + transition?: Transition; + preserveFollowOpacity?: boolean; + }): void; + relegate(): boolean; + resumeFrom?: IProjectionNode; + resumingFrom?: IProjectionNode; + isPresent?: boolean; + addEventListener(name: LayoutEvents, handler: any): VoidFunction; + notifyListeners(name: LayoutEvents, ...args: any): void; + hasListeners(name: LayoutEvents): boolean; + hasTreeAnimated: boolean; + preserveOpacity?: boolean; +} +interface ProjectionNodeOptions { + animate?: boolean; + layoutScroll?: boolean; + layoutRoot?: boolean; + alwaysMeasureLayout?: boolean; + onExitComplete?: VoidFunction; + animationType?: "size" | "position" | "both" | "preserve-aspect"; + layoutId?: string; + layout?: boolean | string; + visualElement?: VisualElement; + crossfade?: boolean; + transition?: Transition; + initialPromotionConfig?: InitialPromotionConfig; +} + +type AnimationType = "animate" | "whileHover" | "whileTap" | "whileDrag" | "whileFocus" | "whileInView" | "exit"; + +type VisualElementAnimationOptions = { + delay?: number; + transitionOverride?: Transition; + custom?: any; + type?: AnimationType; +}; + +interface AnimationState { + animateChanges: (type?: AnimationType) => Promise; + setActive: (type: AnimationType, isActive: boolean, options?: VisualElementAnimationOptions) => Promise; + setAnimateFunction: (fn: any) => void; + getState: () => { + [key: string]: AnimationTypeState; + }; + reset: () => void; +} +interface AnimationTypeState { + isActive: boolean; + protectedKeys: { + [key: string]: true; + }; + needsAnimating: { + [key: string]: boolean; + }; + prevResolvedValues: { + [key: string]: any; + }; + prevProp?: VariantLabels | TargetAndTransition; +} + +/** + * A VisualElement is an imperative abstraction around UI elements such as + * HTMLElement, SVGElement, Three.Object3D etc. + */ +declare abstract class VisualElement { + /** + * VisualElements are arranged in trees mirroring that of the React tree. + * Each type of VisualElement has a unique name, to detect when we're crossing + * type boundaries within that tree. + */ + abstract type: string; + /** + * An `Array.sort` compatible function that will compare two Instances and + * compare their respective positions within the tree. + */ + abstract sortInstanceNodePosition(a: Instance, b: Instance): number; + /** + * Measure the viewport-relative bounding box of the Instance. + */ + abstract measureInstanceViewportBox(instance: Instance, props: MotionProps & Partial): Box; + /** + * When a value has been removed from all animation props we need to + * pick a target to animate back to. For instance, for HTMLElements + * we can look in the style prop. + */ + abstract getBaseTargetFromProps(props: MotionProps, key: string): AnyResolvedKeyframe | undefined | MotionValue; + /** + * When we first animate to a value we need to animate it *from* a value. + * Often this have been specified via the initial prop but it might be + * that the value needs to be read from the Instance. + */ + abstract readValueFromInstance(instance: Instance, key: string, options: Options): AnyResolvedKeyframe | null | undefined; + /** + * When a value has been removed from the VisualElement we use this to remove + * it from the inherting class' unique render state. + */ + abstract removeValueFromRenderState(key: string, renderState: RenderState): void; + /** + * Run before a React or VisualElement render, builds the latest motion + * values into an Instance-specific format. For example, HTMLVisualElement + * will use this step to build `style` and `var` values. + */ + abstract build(renderState: RenderState, latestValues: ResolvedValues, props: MotionProps): void; + /** + * Apply the built values to the Instance. For example, HTMLElements will have + * styles applied via `setProperty` and the style attribute, whereas SVGElements + * will have values applied to attributes. + */ + abstract renderInstance(instance: Instance, renderState: RenderState, styleProp?: MotionStyle, projection?: IProjectionNode): void; + /** + * This method is called when a transform property is bound to a motion value. + * It's currently used to measure SVG elements when a new transform property is bound. + */ + onBindTransform?(): void; + /** + * If the component child is provided as a motion value, handle subscriptions + * with the renderer-specific VisualElement. + */ + handleChildMotionValue?(): void; + /** + * This method takes React props and returns found MotionValues. For example, HTML + * MotionValues will be found within the style prop, whereas for Three.js within attribute arrays. + * + * This isn't an abstract method as it needs calling in the constructor, but it is + * intended to be one. + */ + scrapeMotionValuesFromProps(_props: MotionProps, _prevProps: MotionProps, _visualElement: VisualElement): { + [key: string]: MotionValue | AnyResolvedKeyframe; + }; + /** + * A reference to the current underlying Instance, e.g. a HTMLElement + * or Three.Mesh etc. + */ + current: Instance | null; + /** + * A reference to the parent VisualElement (if exists). + */ + parent: VisualElement | undefined; + /** + * A set containing references to this VisualElement's children. + */ + children: Set>; + /** + * A set containing the latest children of this VisualElement. This is flushed + * at the start of every commit. We use it to calculate the stagger delay + * for newly-added children. + */ + enteringChildren?: Set; + /** + * The depth of this VisualElement within the overall VisualElement tree. + */ + depth: number; + /** + * The current render state of this VisualElement. Defined by inherting VisualElements. + */ + renderState: RenderState; + /** + * An object containing the latest static values for each of this VisualElement's + * MotionValues. + */ + latestValues: ResolvedValues; + /** + * Determine what role this visual element should take in the variant tree. + */ + isVariantNode: boolean; + isControllingVariants: boolean; + /** + * If this component is part of the variant tree, it should track + * any children that are also part of the tree. This is essentially + * a shadow tree to simplify logic around how to stagger over children. + */ + variantChildren?: Set; + /** + * Decides whether this VisualElement should animate in reduced motion + * mode. + * + * TODO: This is currently set on every individual VisualElement but feels + * like it could be set globally. + */ + shouldReduceMotion: boolean | null; + /** + * Normally, if a component is controlled by a parent's variants, it can + * rely on that ancestor to trigger animations further down the tree. + * However, if a component is created after its parent is mounted, the parent + * won't trigger that mount animation so the child needs to. + * + * TODO: This might be better replaced with a method isParentMounted + */ + manuallyAnimateOnMount: boolean; + /** + * This can be set by AnimatePresence to force components that mount + * at the same time as it to mount as if they have initial={false} set. + */ + blockInitialAnimation: boolean; + /** + * A reference to this VisualElement's projection node, used in layout animations. + */ + projection?: IProjectionNode; + /** + * A map of all motion values attached to this visual element. Motion + * values are source of truth for any given animated value. A motion + * value might be provided externally by the component via props. + */ + values: Map>; + /** + * The AnimationState, this is hydrated by the animation Feature. + */ + animationState?: AnimationState; + KeyframeResolver: typeof KeyframeResolver; + /** + * The options used to create this VisualElement. The Options type is defined + * by the inheriting VisualElement and is passed straight through to the render functions. + */ + readonly options: Options; + /** + * A reference to the latest props provided to the VisualElement's host React component. + */ + props: MotionProps; + prevProps?: MotionProps; + presenceContext: PresenceContextProps | null; + prevPresenceContext?: PresenceContextProps | null; + /** + * Cleanup functions for active features (hover/tap/exit etc) + */ + private features; + /** + * A map of every subscription that binds the provided or generated + * motion values onChange listeners to this visual element. + */ + private valueSubscriptions; + /** + * A reference to the ReducedMotionConfig passed to the VisualElement's host React component. + */ + private reducedMotionConfig; + /** + * On mount, this will be hydrated with a callback to disconnect + * this visual element from its parent on unmount. + */ + private removeFromVariantTree; + /** + * A reference to the previously-provided motion values as returned + * from scrapeMotionValuesFromProps. We use the keys in here to determine + * if any motion values need to be removed after props are updated. + */ + private prevMotionValues; + /** + * When values are removed from all animation props we need to search + * for a fallback value to animate to. These values are tracked in baseTarget. + */ + private baseTarget; + /** + * Create an object of the values we initially animated from (if initial prop present). + */ + private initialValues; + /** + * An object containing a SubscriptionManager for each active event. + */ + private events; + /** + * An object containing an unsubscribe function for each prop event subscription. + * For example, every "Update" event can have multiple subscribers via + * VisualElement.on(), but only one of those can be defined via the onUpdate prop. + */ + private propEventSubscriptions; + constructor({ parent, props, presenceContext, reducedMotionConfig, blockInitialAnimation, visualState, }: VisualElementOptions, options?: Options); + mount(instance: Instance): void; + unmount(): void; + addChild(child: VisualElement): void; + removeChild(child: VisualElement): void; + private bindToMotionValue; + sortNodePosition(other: VisualElement): number; + updateFeatures(): void; + notifyUpdate: () => void; + triggerBuild(): void; + render: () => void; + private renderScheduledAt; + scheduleRender: () => void; + /** + * Measure the current viewport box with or without transforms. + * Only measures axis-aligned boxes, rotate and skew must be manually + * removed with a re-render to work. + */ + measureViewportBox(): Box; + getStaticValue(key: string): AnyResolvedKeyframe; + setStaticValue(key: string, value: AnyResolvedKeyframe): void; + /** + * Update the provided props. Ensure any newly-added motion values are + * added to our map, old ones removed, and listeners updated. + */ + update(props: MotionProps, presenceContext: PresenceContextProps | null): void; + getProps(): MotionProps; + /** + * Returns the variant definition with a given name. + */ + getVariant(name: string): motion_dom.Variant | undefined; + /** + * Returns the defined default transition on this component. + */ + getDefaultTransition(): motion_dom.Transition | undefined; + getTransformPagePoint(): any; + getClosestVariantNode(): VisualElement | undefined; + /** + * Add a child visual element to our set of children. + */ + addVariantChild(child: VisualElement): (() => boolean) | undefined; + /** + * Add a motion value and bind it to this visual element. + */ + addValue(key: string, value: MotionValue): void; + /** + * Remove a motion value and unbind any active subscriptions. + */ + removeValue(key: string): void; + /** + * Check whether we have a motion value for this key + */ + hasValue(key: string): boolean; + /** + * Get a motion value for this key. If called with a default + * value, we'll create one if none exists. + */ + getValue(key: string): MotionValue | undefined; + getValue(key: string, defaultValue: AnyResolvedKeyframe | null): MotionValue; + /** + * If we're trying to animate to a previously unencountered value, + * we need to check for it in our state and as a last resort read it + * directly from the instance (which might have performance implications). + */ + readValue(key: string, target?: AnyResolvedKeyframe | null): any; + /** + * Set the base target to later animate back to. This is currently + * only hydrated on creation and when we first read a value. + */ + setBaseTarget(key: string, value: AnyResolvedKeyframe): void; + /** + * Find the base target for a value thats been removed from all animation + * props. + */ + getBaseTarget(key: string): ResolvedValues[string] | undefined | null; + on(eventName: EventName, callback: VisualElementEventCallbacks[EventName]): VoidFunction; + notify(eventName: EventName, ...args: any): void; + scheduleRenderMicrotask(): void; +} + +type ScrapeMotionValuesFromProps = (props: MotionProps, prevProps: MotionProps, visualElement?: VisualElement) => { + [key: string]: MotionValue | AnyResolvedKeyframe; +}; +interface VisualElementOptions { + visualState: VisualState; + parent?: VisualElement; + variantParent?: VisualElement; + presenceContext: PresenceContextProps | null; + props: MotionProps; + blockInitialAnimation?: boolean; + reducedMotionConfig?: ReducedMotionConfig; +} +/** + * A generic set of string/number values + */ +interface ResolvedValues { + [key: string]: AnyResolvedKeyframe; +} +interface VisualElementEventCallbacks { + BeforeLayoutMeasure: () => void; + LayoutMeasure: (layout: Box, prevLayout?: Box) => void; + LayoutUpdate: (layout: Axis, prevLayout: Axis) => void; + Update: (latest: ResolvedValues) => void; + AnimationStart: (definition: AnimationDefinition) => void; + AnimationComplete: (definition: AnimationDefinition) => void; + LayoutAnimationStart: () => void; + LayoutAnimationComplete: () => void; + SetAxisTarget: () => void; + Unmount: () => void; +} +type CreateVisualElement = (Component: TagName | string | React.ComponentType, options: VisualElementOptions) => VisualElement; + +declare abstract class Feature { + isMounted: boolean; + node: VisualElement; + constructor(node: VisualElement); + abstract mount(): void; + abstract unmount(): void; + update(): void; +} + +declare function MeasureLayout(props: MotionProps & { + visualElement: VisualElement; +}): react_jsx_runtime.JSX.Element; + +interface FeatureClass { + new (props: Props): Feature; +} +interface HydratedFeatureDefinition { + isEnabled: (props: MotionProps) => boolean; + Feature: FeatureClass; + ProjectionNode?: any; + MeasureLayout?: typeof MeasureLayout; +} +interface HydratedFeatureDefinitions { + animation?: HydratedFeatureDefinition; + exit?: HydratedFeatureDefinition; + drag?: HydratedFeatureDefinition; + tap?: HydratedFeatureDefinition; + focus?: HydratedFeatureDefinition; + hover?: HydratedFeatureDefinition; + pan?: HydratedFeatureDefinition; + inView?: HydratedFeatureDefinition; + layout?: HydratedFeatureDefinition; +} +interface FeatureDefinition { + isEnabled: HydratedFeatureDefinition["isEnabled"]; + Feature?: HydratedFeatureDefinition["Feature"]; + ProjectionNode?: HydratedFeatureDefinition["ProjectionNode"]; + MeasureLayout?: HydratedFeatureDefinition["MeasureLayout"]; +} +type FeatureDefinitions = { + [K in keyof HydratedFeatureDefinitions]: FeatureDefinition; +}; +interface FeaturePackage { + Feature?: HydratedFeatureDefinition["Feature"]; + ProjectionNode?: HydratedFeatureDefinition["ProjectionNode"]; + MeasureLayout?: HydratedFeatureDefinition["MeasureLayout"]; +} +type FeaturePackages = { + [K in keyof HydratedFeatureDefinitions]: FeaturePackage; +}; +interface FeatureBundle extends FeaturePackages { + renderer: CreateVisualElement; +} +type LazyFeatureBundle = () => Promise; + +type MotionComponentProps = { + [K in Exclude]?: Props[K]; +} & MotionProps; +type MotionComponent = T extends keyof DOMMotionComponents ? DOMMotionComponents[T] : React$1.ComponentType, "children"> & { + children?: "children" extends keyof P ? P["children"] | MotionComponentProps

["children"] : MotionComponentProps

["children"]; +}>; +interface MotionComponentOptions { + forwardMotionProps?: boolean; +} +/** + * Create a `motion` component. + * + * This function accepts a Component argument, which can be either a string (ie "div" + * for `motion.div`), or an actual React component. + * + * Alongside this is a config option which provides a way of rendering the provided + * component "offline", or outside the React render cycle. + */ +declare function createMotionComponent(Component: TagName | string | React$1.ComponentType, { forwardMotionProps }?: MotionComponentOptions, preloadedFeatures?: FeaturePackages, createVisualElement?: CreateVisualElement): MotionComponent; + +declare const optimizedAppearDataAttribute: "data-framer-appear-id"; + +/** + * Expose only the needed part of the VisualElement interface to + * ensure React types don't end up in the generic DOM bundle. + */ +interface WithAppearProps { + props: { + [optimizedAppearDataAttribute]?: string; + values?: { + [key: string]: MotionValue | MotionValue; + }; + }; +} +type HandoffFunction = (storeId: string, valueName: string, frame: Batcher) => number | null; +/** + * The window global object acts as a bridge between our inline script + * triggering the optimized appear animations, and Motion. + */ +declare global { + interface Window { + MotionHandoffAnimation?: HandoffFunction; + MotionHandoffMarkAsComplete?: (elementId: string) => void; + MotionHandoffIsComplete?: (elementId: string) => boolean; + MotionHasOptimisedAnimation?: (elementId?: string, valueName?: string) => boolean; + MotionCancelOptimisedAnimation?: (elementId?: string, valueName?: string, frame?: Batcher, canResume?: boolean) => void; + MotionCheckAppearSync?: (visualElement: WithAppearProps, valueName: string, value: MotionValue) => VoidFunction | void; + MotionIsMounted?: boolean; + } +} + +export { type AnimationType as A, type CreateVisualElement as C, type DOMMotionComponents as D, type FeatureBundle as F, type HTMLMotionProps as H, type IProjectionNode as I, type LazyFeatureBundle as L, type MotionProps as M, PresenceContext as P, type ResolvedValues as R, type SVGMotionComponents as S, VisualElement as V, MotionConfigContext as a, type HTMLElements as b, createMotionComponent as c, type HTMLMotionComponents as d, type FeaturePackages as e, type VisualElementAnimationOptions as f, type HTMLRenderState as g, type ScrapeMotionValuesFromProps as h, type VisualState as i, SwitchLayoutGroupContext as j, type MotionStyle as k, type MotionTransform as l, makeUseVisualState as m, type VariantLabels as n, optimizedAppearDataAttribute as o, type ForwardRefComponent as p, type SVGAttributesAsMotionValues as q, type SVGMotionProps as r, FlatTree as s, type HydratedFeatureDefinition as t, type HydratedFeatureDefinitions as u, type FeatureDefinition as v, type FeatureDefinitions as w, type FeaturePackage as x }; diff --git a/frontend/node_modules/framer-motion/dist/types/client.d.ts b/frontend/node_modules/framer-motion/dist/types/client.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9549674a962e86503b8a1c9102fa893bc46947d3 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/types/client.d.ts @@ -0,0 +1,179 @@ +import { p as ForwardRefComponent, H as HTMLMotionProps, r as SVGMotionProps } from '../types.d-Cjd591yU.js'; +export { c as create } from '../types.d-Cjd591yU.js'; +import 'react'; +import 'motion-dom'; +import 'motion-utils'; +import 'react/jsx-runtime'; + +/** + * HTML components + */ +declare const MotionA: ForwardRefComponent>; +declare const MotionAbbr: ForwardRefComponent>; +declare const MotionAddress: ForwardRefComponent>; +declare const MotionArea: ForwardRefComponent>; +declare const MotionArticle: ForwardRefComponent>; +declare const MotionAside: ForwardRefComponent>; +declare const MotionAudio: ForwardRefComponent>; +declare const MotionB: ForwardRefComponent>; +declare const MotionBase: ForwardRefComponent>; +declare const MotionBdi: ForwardRefComponent>; +declare const MotionBdo: ForwardRefComponent>; +declare const MotionBig: ForwardRefComponent>; +declare const MotionBlockquote: ForwardRefComponent>; +declare const MotionBody: ForwardRefComponent>; +declare const MotionButton: ForwardRefComponent>; +declare const MotionCanvas: ForwardRefComponent>; +declare const MotionCaption: ForwardRefComponent>; +declare const MotionCite: ForwardRefComponent>; +declare const MotionCode: ForwardRefComponent>; +declare const MotionCol: ForwardRefComponent>; +declare const MotionColgroup: ForwardRefComponent>; +declare const MotionData: ForwardRefComponent>; +declare const MotionDatalist: ForwardRefComponent>; +declare const MotionDd: ForwardRefComponent>; +declare const MotionDel: ForwardRefComponent>; +declare const MotionDetails: ForwardRefComponent>; +declare const MotionDfn: ForwardRefComponent>; +declare const MotionDialog: ForwardRefComponent>; +declare const MotionDiv: ForwardRefComponent>; +declare const MotionDl: ForwardRefComponent>; +declare const MotionDt: ForwardRefComponent>; +declare const MotionEm: ForwardRefComponent>; +declare const MotionEmbed: ForwardRefComponent>; +declare const MotionFieldset: ForwardRefComponent>; +declare const MotionFigcaption: ForwardRefComponent>; +declare const MotionFigure: ForwardRefComponent>; +declare const MotionFooter: ForwardRefComponent>; +declare const MotionForm: ForwardRefComponent>; +declare const MotionH1: ForwardRefComponent>; +declare const MotionH2: ForwardRefComponent>; +declare const MotionH3: ForwardRefComponent>; +declare const MotionH4: ForwardRefComponent>; +declare const MotionH5: ForwardRefComponent>; +declare const MotionH6: ForwardRefComponent>; +declare const MotionHead: ForwardRefComponent>; +declare const MotionHeader: ForwardRefComponent>; +declare const MotionHgroup: ForwardRefComponent>; +declare const MotionHr: ForwardRefComponent>; +declare const MotionHtml: ForwardRefComponent>; +declare const MotionI: ForwardRefComponent>; +declare const MotionIframe: ForwardRefComponent>; +declare const MotionImg: ForwardRefComponent>; +declare const MotionInput: ForwardRefComponent>; +declare const MotionIns: ForwardRefComponent>; +declare const MotionKbd: ForwardRefComponent>; +declare const MotionKeygen: ForwardRefComponent>; +declare const MotionLabel: ForwardRefComponent>; +declare const MotionLegend: ForwardRefComponent>; +declare const MotionLi: ForwardRefComponent>; +declare const MotionLink: ForwardRefComponent>; +declare const MotionMain: ForwardRefComponent>; +declare const MotionMap: ForwardRefComponent>; +declare const MotionMark: ForwardRefComponent>; +declare const MotionMenu: ForwardRefComponent>; +declare const MotionMenuitem: ForwardRefComponent>; +declare const MotionMeter: ForwardRefComponent>; +declare const MotionNav: ForwardRefComponent>; +declare const MotionObject: ForwardRefComponent>; +declare const MotionOl: ForwardRefComponent>; +declare const MotionOptgroup: ForwardRefComponent>; +declare const MotionOption: ForwardRefComponent>; +declare const MotionOutput: ForwardRefComponent>; +declare const MotionP: ForwardRefComponent>; +declare const MotionParam: ForwardRefComponent>; +declare const MotionPicture: ForwardRefComponent>; +declare const MotionPre: ForwardRefComponent>; +declare const MotionProgress: ForwardRefComponent>; +declare const MotionQ: ForwardRefComponent>; +declare const MotionRp: ForwardRefComponent>; +declare const MotionRt: ForwardRefComponent>; +declare const MotionRuby: ForwardRefComponent>; +declare const MotionS: ForwardRefComponent>; +declare const MotionSamp: ForwardRefComponent>; +declare const MotionScript: ForwardRefComponent>; +declare const MotionSection: ForwardRefComponent>; +declare const MotionSelect: ForwardRefComponent>; +declare const MotionSmall: ForwardRefComponent>; +declare const MotionSource: ForwardRefComponent>; +declare const MotionSpan: ForwardRefComponent>; +declare const MotionStrong: ForwardRefComponent>; +declare const MotionStyle: ForwardRefComponent>; +declare const MotionSub: ForwardRefComponent>; +declare const MotionSummary: ForwardRefComponent>; +declare const MotionSup: ForwardRefComponent>; +declare const MotionTable: ForwardRefComponent>; +declare const MotionTbody: ForwardRefComponent>; +declare const MotionTd: ForwardRefComponent>; +declare const MotionTextarea: ForwardRefComponent>; +declare const MotionTfoot: ForwardRefComponent>; +declare const MotionTh: ForwardRefComponent>; +declare const MotionThead: ForwardRefComponent>; +declare const MotionTime: ForwardRefComponent>; +declare const MotionTitle: ForwardRefComponent>; +declare const MotionTr: ForwardRefComponent>; +declare const MotionTrack: ForwardRefComponent>; +declare const MotionU: ForwardRefComponent>; +declare const MotionUl: ForwardRefComponent>; +declare const MotionVideo: ForwardRefComponent>; +declare const MotionWbr: ForwardRefComponent>; +declare const MotionWebview: ForwardRefComponent>; +/** + * SVG components + */ +declare const MotionAnimate: ForwardRefComponent>; +declare const MotionCircle: ForwardRefComponent>; +declare const MotionDefs: ForwardRefComponent>; +declare const MotionDesc: ForwardRefComponent>; +declare const MotionEllipse: ForwardRefComponent>; +declare const MotionG: ForwardRefComponent>; +declare const MotionImage: ForwardRefComponent>; +declare const MotionLine: ForwardRefComponent>; +declare const MotionFilter: ForwardRefComponent>; +declare const MotionMarker: ForwardRefComponent>; +declare const MotionMask: ForwardRefComponent>; +declare const MotionMetadata: ForwardRefComponent>; +declare const MotionPath: ForwardRefComponent>; +declare const MotionPattern: ForwardRefComponent>; +declare const MotionPolygon: ForwardRefComponent>; +declare const MotionPolyline: ForwardRefComponent>; +declare const MotionRect: ForwardRefComponent>; +declare const MotionStop: ForwardRefComponent>; +declare const MotionSvg: ForwardRefComponent>; +declare const MotionSymbol: ForwardRefComponent>; +declare const MotionText: ForwardRefComponent>; +declare const MotionTspan: ForwardRefComponent>; +declare const MotionUse: ForwardRefComponent>; +declare const MotionView: ForwardRefComponent>; +declare const MotionClipPath: ForwardRefComponent>; +declare const MotionFeBlend: ForwardRefComponent>; +declare const MotionFeColorMatrix: ForwardRefComponent>; +declare const MotionFeComponentTransfer: ForwardRefComponent>; +declare const MotionFeComposite: ForwardRefComponent>; +declare const MotionFeConvolveMatrix: ForwardRefComponent>; +declare const MotionFeDiffuseLighting: ForwardRefComponent>; +declare const MotionFeDisplacementMap: ForwardRefComponent>; +declare const MotionFeDistantLight: ForwardRefComponent>; +declare const MotionFeDropShadow: ForwardRefComponent>; +declare const MotionFeFlood: ForwardRefComponent>; +declare const MotionFeFuncA: ForwardRefComponent>; +declare const MotionFeFuncB: ForwardRefComponent>; +declare const MotionFeFuncG: ForwardRefComponent>; +declare const MotionFeFuncR: ForwardRefComponent>; +declare const MotionFeGaussianBlur: ForwardRefComponent>; +declare const MotionFeImage: ForwardRefComponent>; +declare const MotionFeMerge: ForwardRefComponent>; +declare const MotionFeMergeNode: ForwardRefComponent>; +declare const MotionFeMorphology: ForwardRefComponent>; +declare const MotionFeOffset: ForwardRefComponent>; +declare const MotionFePointLight: ForwardRefComponent>; +declare const MotionFeSpecularLighting: ForwardRefComponent>; +declare const MotionFeSpotLight: ForwardRefComponent>; +declare const MotionFeTile: ForwardRefComponent>; +declare const MotionFeTurbulence: ForwardRefComponent>; +declare const MotionForeignObject: ForwardRefComponent>; +declare const MotionLinearGradient: ForwardRefComponent>; +declare const MotionRadialGradient: ForwardRefComponent>; +declare const MotionTextPath: ForwardRefComponent>; + +export { MotionA as a, MotionAbbr as abbr, MotionAddress as address, MotionAnimate as animate, MotionArea as area, MotionArticle as article, MotionAside as aside, MotionAudio as audio, MotionB as b, MotionBase as base, MotionBdi as bdi, MotionBdo as bdo, MotionBig as big, MotionBlockquote as blockquote, MotionBody as body, MotionButton as button, MotionCanvas as canvas, MotionCaption as caption, MotionCircle as circle, MotionCite as cite, MotionClipPath as clipPath, MotionCode as code, MotionCol as col, MotionColgroup as colgroup, MotionData as data, MotionDatalist as datalist, MotionDd as dd, MotionDefs as defs, MotionDel as del, MotionDesc as desc, MotionDetails as details, MotionDfn as dfn, MotionDialog as dialog, MotionDiv as div, MotionDl as dl, MotionDt as dt, MotionEllipse as ellipse, MotionEm as em, MotionEmbed as embed, MotionFeBlend as feBlend, MotionFeColorMatrix as feColorMatrix, MotionFeComponentTransfer as feComponentTransfer, MotionFeComposite as feComposite, MotionFeConvolveMatrix as feConvolveMatrix, MotionFeDiffuseLighting as feDiffuseLighting, MotionFeDisplacementMap as feDisplacementMap, MotionFeDistantLight as feDistantLight, MotionFeDropShadow as feDropShadow, MotionFeFlood as feFlood, MotionFeFuncA as feFuncA, MotionFeFuncB as feFuncB, MotionFeFuncG as feFuncG, MotionFeFuncR as feFuncR, MotionFeGaussianBlur as feGaussianBlur, MotionFeImage as feImage, MotionFeMerge as feMerge, MotionFeMergeNode as feMergeNode, MotionFeMorphology as feMorphology, MotionFeOffset as feOffset, MotionFePointLight as fePointLight, MotionFeSpecularLighting as feSpecularLighting, MotionFeSpotLight as feSpotLight, MotionFeTile as feTile, MotionFeTurbulence as feTurbulence, MotionFieldset as fieldset, MotionFigcaption as figcaption, MotionFigure as figure, MotionFilter as filter, MotionFooter as footer, MotionForeignObject as foreignObject, MotionForm as form, MotionG as g, MotionH1 as h1, MotionH2 as h2, MotionH3 as h3, MotionH4 as h4, MotionH5 as h5, MotionH6 as h6, MotionHead as head, MotionHeader as header, MotionHgroup as hgroup, MotionHr as hr, MotionHtml as html, MotionI as i, MotionIframe as iframe, MotionImage as image, MotionImg as img, MotionInput as input, MotionIns as ins, MotionKbd as kbd, MotionKeygen as keygen, MotionLabel as label, MotionLegend as legend, MotionLi as li, MotionLine as line, MotionLinearGradient as linearGradient, MotionLink as link, MotionMain as main, MotionMap as map, MotionMark as mark, MotionMarker as marker, MotionMask as mask, MotionMenu as menu, MotionMenuitem as menuitem, MotionMetadata as metadata, MotionMeter as meter, MotionNav as nav, MotionObject as object, MotionOl as ol, MotionOptgroup as optgroup, MotionOption as option, MotionOutput as output, MotionP as p, MotionParam as param, MotionPath as path, MotionPattern as pattern, MotionPicture as picture, MotionPolygon as polygon, MotionPolyline as polyline, MotionPre as pre, MotionProgress as progress, MotionQ as q, MotionRadialGradient as radialGradient, MotionRect as rect, MotionRp as rp, MotionRt as rt, MotionRuby as ruby, MotionS as s, MotionSamp as samp, MotionScript as script, MotionSection as section, MotionSelect as select, MotionSmall as small, MotionSource as source, MotionSpan as span, MotionStop as stop, MotionStrong as strong, MotionStyle as style, MotionSub as sub, MotionSummary as summary, MotionSup as sup, MotionSvg as svg, MotionSymbol as symbol, MotionTable as table, MotionTbody as tbody, MotionTd as td, MotionText as text, MotionTextPath as textPath, MotionTextarea as textarea, MotionTfoot as tfoot, MotionTh as th, MotionThead as thead, MotionTime as time, MotionTitle as title, MotionTr as tr, MotionTrack as track, MotionTspan as tspan, MotionU as u, MotionUl as ul, MotionUse as use, MotionVideo as video, MotionView as view, MotionWbr as wbr, MotionWebview as webview }; diff --git a/frontend/node_modules/framer-motion/dist/types/index.d.ts b/frontend/node_modules/framer-motion/dist/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..167cfec2bc0a278158ac47a7ac7d19ba560ba129 --- /dev/null +++ b/frontend/node_modules/framer-motion/dist/types/index.d.ts @@ -0,0 +1,1163 @@ +/// +import * as motion_dom from 'motion-dom'; +import { AnyResolvedKeyframe, OnKeyframesResolved, KeyframeResolver, UnresolvedValueKeyframe, MotionValue, Transition, ElementOrSelector, DOMKeyframesDefinition, AnimationOptions, AnimationPlaybackOptions, AnimationScope, AnimationPlaybackControlsWithThen, ValueAnimationTransition, AnimationPlaybackControls, EventInfo, MotionValueEventCallbacks, SpringOptions, TransformOptions, LegacyAnimationControls, AnimationDefinition } from 'motion-dom'; +export * from 'motion-dom'; +import * as react_jsx_runtime from 'react/jsx-runtime'; +import * as React$1 from 'react'; +import { useEffect, RefObject } from 'react'; +import { F as FeatureBundle, M as MotionProps, a as MotionConfigContext, H as HTMLMotionProps, b as HTMLElements, c as createMotionComponent, d as HTMLMotionComponents, S as SVGMotionComponents, e as FeaturePackages, V as VisualElement, f as VisualElementAnimationOptions, I as IProjectionNode, R as ResolvedValues, g as HTMLRenderState } from '../types.d-Cjd591yU.js'; +export { A as AnimationType, C as CreateVisualElement, D as DOMMotionComponents, v as FeatureDefinition, w as FeatureDefinitions, x as FeaturePackage, s as FlatTree, p as ForwardRefComponent, t as HydratedFeatureDefinition, u as HydratedFeatureDefinitions, L as LazyFeatureBundle, k as MotionStyle, l as MotionTransform, P as PresenceContext, q as SVGAttributesAsMotionValues, r as SVGMotionProps, h as ScrapeMotionValuesFromProps, j as SwitchLayoutGroupContext, n as VariantLabels, i as VisualState, m as makeUseVisualState, o as optimizedAppearDataAttribute } from '../types.d-Cjd591yU.js'; +import { Easing, EasingFunction, Point, Axis, Box } from 'motion-utils'; +export * from 'motion-utils'; +export { MotionGlobalConfig } from 'motion-utils'; + +type ResolveKeyframes = (keyframes: V[], onComplete: OnKeyframesResolved, name?: string, motionValue?: any) => KeyframeResolver; + +/** + * @public + */ +interface AnimatePresenceProps { + /** + * By passing `initial={false}`, `AnimatePresence` will disable any initial animations on children + * that are present when the component is first rendered. + * + * ```jsx + * + * {isVisible && ( + * + * )} + * + * ``` + * + * @public + */ + initial?: boolean; + /** + * When a component is removed, there's no longer a chance to update its props. So if a component's `exit` + * prop is defined as a dynamic variant and you want to pass a new `custom` prop, you can do so via `AnimatePresence`. + * This will ensure all leaving components animate using the latest data. + * + * @public + */ + custom?: any; + /** + * Fires when all exiting nodes have completed animating out. + * + * @public + */ + onExitComplete?: () => void; + /** + * Determines how to handle entering and exiting elements. + * + * - `"sync"`: Default. Elements animate in and out as soon as they're added/removed. + * - `"popLayout"`: Exiting elements are "popped" from the page layout, allowing sibling + * elements to immediately occupy their new layouts. + * - `"wait"`: Only renders one component at a time. Wait for the exiting component to animate out + * before animating the next component in. + * + * @public + */ + mode?: "sync" | "popLayout" | "wait"; + /** + * Root element to use when injecting styles, used when mode === `"popLayout"`. + * This defaults to document.head but can be overridden e.g. for use in shadow DOM. + */ + root?: HTMLElement | ShadowRoot; + /** + * Internal. Used in Framer to flag that sibling children *shouldn't* re-render as a result of a + * child being removed. + */ + presenceAffectsLayout?: boolean; + /** + * If true, the `AnimatePresence` component will propagate parent exit animations + * to its children. + */ + propagate?: boolean; + /** + * Internal. Set whether to anchor the x position of the exiting element to the left or right + * when using `mode="popLayout"`. + */ + anchorX?: "left" | "right"; +} + +/** + * `AnimatePresence` enables the animation of components that have been removed from the tree. + * + * When adding/removing more than a single child, every child **must** be given a unique `key` prop. + * + * Any `motion` components that have an `exit` property defined will animate out when removed from + * the tree. + * + * ```jsx + * import { motion, AnimatePresence } from 'framer-motion' + * + * export const Items = ({ items }) => ( + * + * {items.map(item => ( + * + * ))} + * + * ) + * ``` + * + * You can sequence exit animations throughout a tree using variants. + * + * If a child contains multiple `motion` components with `exit` props, it will only unmount the child + * once all `motion` components have finished animating out. Likewise, any components using + * `usePresence` all need to call `safeToRemove`. + * + * @public + */ +declare const AnimatePresence: ({ children, custom, initial, onExitComplete, presenceAffectsLayout, mode, propagate, anchorX, root }: React$1.PropsWithChildren) => react_jsx_runtime.JSX.Element | null; + +type InheritOption = boolean | "id"; +interface Props$2 { + id?: string; + inherit?: InheritOption; +} +declare const LayoutGroup: React$1.FunctionComponent>; + +type LazyFeatureBundle = () => Promise; +/** + * @public + */ +interface LazyProps { + children?: React.ReactNode; + /** + * Can be used to provide a feature bundle synchronously or asynchronously. + * + * ```jsx + * // features.js + * import { domAnimation } from "framer-motion" + * export default domAnimation + * + * // index.js + * import { LazyMotion, m } from "framer-motion" + * + * const loadFeatures = () =>import("./features.js") + * .then(res => res.default) + * + * function Component() { + * return ( + * + * + * + * ) + * } + * ``` + * + * @public + */ + features: FeatureBundle | LazyFeatureBundle; + /** + * If `true`, will throw an error if a `motion` component renders within + * a `LazyMotion` component. + * + * ```jsx + * // This component will throw an error that explains using a motion component + * // instead of the m component will break the benefits of code-splitting. + * function Component() { + * return ( + * + * + * + * ) + * } + * ``` + * + * @public + */ + strict?: boolean; +} + +/** + * Used in conjunction with the `m` component to reduce bundle size. + * + * `m` is a version of the `motion` component that only loads functionality + * critical for the initial render. + * + * `LazyMotion` can then be used to either synchronously or asynchronously + * load animation and gesture support. + * + * ```jsx + * // Synchronous loading + * import { LazyMotion, m, domAnimation } from "framer-motion" + * + * function App() { + * return ( + * + * + * + * ) + * } + * + * // Asynchronous loading + * import { LazyMotion, m } from "framer-motion" + * + * function App() { + * return ( + * import('./path/to/domAnimation')}> + * + * + * ) + * } + * ``` + * + * @public + */ +declare function LazyMotion({ children, features, strict }: LazyProps): react_jsx_runtime.JSX.Element; + +type IsValidProp = (key: string) => boolean; +declare function filterProps(props: MotionProps, isDom: boolean, forwardMotionProps: boolean): MotionProps; + +interface MotionConfigProps extends Partial { + children?: React$1.ReactNode; + isValidProp?: IsValidProp; +} +/** + * `MotionConfig` is used to set configuration options for all children `motion` components. + * + * ```jsx + * import { motion, MotionConfig } from "framer-motion" + * + * export function App() { + * return ( + * + * + * + * ) + * } + * ``` + * + * @public + */ +declare function MotionConfig({ children, isValidProp, ...config }: MotionConfigProps): react_jsx_runtime.JSX.Element; + +interface Props$1 { + /** + * A HTML element to render this component as. Defaults to `"ul"`. + * + * @public + */ + as?: keyof HTMLElements; + /** + * The axis to reorder along. By default, items will be draggable on this axis. + * To make draggable on both axes, set `` + * + * @public + */ + axis?: "x" | "y"; + /** + * A callback to fire with the new value order. For instance, if the values + * are provided as a state from `useState`, this could be the set state function. + * + * @public + */ + onReorder: (newOrder: V[]) => void; + /** + * The latest values state. + * + * ```jsx + * function Component() { + * const [items, setItems] = useState([0, 1, 2]) + * + * return ( + * + * {items.map((item) => )} + * + * ) + * } + * ``` + * + * @public + */ + values: V[]; +} +type ReorderGroupProps = Props$1 & Omit, "values"> & React$1.PropsWithChildren<{}>; +declare function ReorderGroupComponent({ children, as, axis, onReorder, values, ...props }: ReorderGroupProps, externalRef?: React$1.ForwardedRef): react_jsx_runtime.JSX.Element; +declare const ReorderGroup: (props: ReorderGroupProps & { + ref?: React$1.ForwardedRef; +}) => ReturnType; + +interface Props { + /** + * A HTML element to render this component as. Defaults to `"li"`. + * + * @public + */ + as?: keyof HTMLElements; + /** + * The value in the list that this component represents. + * + * @public + */ + value: V; + /** + * A subset of layout options primarily used to disable layout="size" + * + * @public + * @default true + */ + layout?: true | "position"; +} +type ReorderItemProps = Props & Omit, "value" | "layout"> & React$1.PropsWithChildren<{}>; +declare function ReorderItemComponent({ children, style, value, as, onDrag, layout, ...props }: ReorderItemProps, externalRef?: React$1.ForwardedRef): react_jsx_runtime.JSX.Element; +declare const ReorderItem: (props: ReorderItemProps & { + ref?: React$1.ForwardedRef; +}) => ReturnType; + +declare namespace namespace_d { + export { ReorderGroup as Group, ReorderItem as Item }; +} + +type ObjectTarget = { + [K in keyof O]?: O[K] | UnresolvedValueKeyframe[]; +}; +type SequenceTime = number | "<" | `+${number}` | `-${number}` | `${string}`; +type SequenceLabel = string; +interface SequenceLabelWithTime { + name: SequenceLabel; + at: SequenceTime; +} +interface At { + at?: SequenceTime; +} +type MotionValueSegment = [ + MotionValue, + UnresolvedValueKeyframe | UnresolvedValueKeyframe[] +]; +type MotionValueSegmentWithTransition = [ + MotionValue, + UnresolvedValueKeyframe | UnresolvedValueKeyframe[], + Transition & At +]; +type DOMSegment = [ElementOrSelector, DOMKeyframesDefinition]; +type DOMSegmentWithTransition = [ + ElementOrSelector, + DOMKeyframesDefinition, + AnimationOptions & At +]; +type ObjectSegment = [O, ObjectTarget]; +type ObjectSegmentWithTransition = [ + O, + ObjectTarget, + AnimationOptions & At +]; +type Segment = ObjectSegment | ObjectSegmentWithTransition | SequenceLabel | SequenceLabelWithTime | MotionValueSegment | MotionValueSegmentWithTransition | DOMSegment | DOMSegmentWithTransition; +type AnimationSequence = Segment[]; +interface SequenceOptions extends AnimationPlaybackOptions { + delay?: number; + duration?: number; + defaultTransition?: Transition; +} +interface AbsoluteKeyframe { + value: AnyResolvedKeyframe | null; + at: number; + easing?: Easing; +} +type ValueSequence = AbsoluteKeyframe[]; +interface SequenceMap { + [key: string]: ValueSequence; +} +type ResolvedAnimationDefinition = { + keyframes: { + [key: string]: UnresolvedValueKeyframe[]; + }; + transition: { + [key: string]: Transition; + }; +}; +type ResolvedAnimationDefinitions = Map; + +/** + * Creates an animation function that is optionally scoped + * to a specific element. + */ +declare function createScopedAnimate(scope?: AnimationScope): { + (sequence: AnimationSequence, options?: SequenceOptions): AnimationPlaybackControlsWithThen; + (value: string | MotionValue, keyframes: string | UnresolvedValueKeyframe[], options?: ValueAnimationTransition): AnimationPlaybackControlsWithThen; + (value: number | MotionValue, keyframes: number | UnresolvedValueKeyframe[], options?: ValueAnimationTransition): AnimationPlaybackControlsWithThen; + (value: V | MotionValue, keyframes: V | UnresolvedValueKeyframe[], options?: ValueAnimationTransition): AnimationPlaybackControlsWithThen; + (element: ElementOrSelector, keyframes: DOMKeyframesDefinition, options?: AnimationOptions): AnimationPlaybackControlsWithThen; + (object: O | O[], keyframes: ObjectTarget, options?: AnimationOptions): AnimationPlaybackControlsWithThen; +}; +declare const animate: { + (sequence: AnimationSequence, options?: SequenceOptions): AnimationPlaybackControlsWithThen; + (value: string | MotionValue, keyframes: string | UnresolvedValueKeyframe[], options?: ValueAnimationTransition): AnimationPlaybackControlsWithThen; + (value: number | MotionValue, keyframes: number | UnresolvedValueKeyframe[], options?: ValueAnimationTransition): AnimationPlaybackControlsWithThen; + (value: V | MotionValue, keyframes: V | UnresolvedValueKeyframe[], options?: ValueAnimationTransition): AnimationPlaybackControlsWithThen; + (element: ElementOrSelector, keyframes: DOMKeyframesDefinition, options?: AnimationOptions): AnimationPlaybackControlsWithThen; + (object: O | O[], keyframes: ObjectTarget, options?: AnimationOptions): AnimationPlaybackControlsWithThen; +}; + +declare const animateMini: (elementOrSelector: ElementOrSelector, keyframes: DOMKeyframesDefinition, options?: AnimationOptions) => AnimationPlaybackControlsWithThen; + +interface ScrollOptions { + source?: HTMLElement; + container?: Element; + target?: Element; + axis?: "x" | "y"; + offset?: ScrollOffset; +} +type OnScrollProgress = (progress: number) => void; +type OnScrollWithInfo = (progress: number, info: ScrollInfo) => void; +type OnScroll = OnScrollProgress | OnScrollWithInfo; +interface AxisScrollInfo { + current: number; + offset: number[]; + progress: number; + scrollLength: number; + velocity: number; + targetOffset: number; + targetLength: number; + containerLength: number; + interpolatorOffsets?: number[]; + interpolate?: EasingFunction; +} +interface ScrollInfo { + time: number; + x: AxisScrollInfo; + y: AxisScrollInfo; +} +type OnScrollInfo = (info: ScrollInfo) => void; +type SupportedEdgeUnit = "px" | "vw" | "vh" | "%"; +type EdgeUnit = `${number}${SupportedEdgeUnit}`; +type NamedEdges = "start" | "end" | "center"; +type EdgeString = NamedEdges | EdgeUnit | `${number}`; +type Edge = EdgeString | number; +type ProgressIntersection = [number, number]; +type Intersection = `${Edge} ${Edge}`; +type ScrollOffset = Array; +interface ScrollInfoOptions { + container?: Element; + target?: Element; + axis?: "x" | "y"; + offset?: ScrollOffset; +} + +declare function scroll(onScroll: OnScroll | AnimationPlaybackControls, { axis, container, ...options }?: ScrollOptions): VoidFunction; + +declare function scrollInfo(onScroll: OnScrollInfo, { container, ...options }?: ScrollInfoOptions): VoidFunction; + +type ViewChangeHandler = (entry: IntersectionObserverEntry) => void; +type MarginValue = `${number}${"px" | "%"}`; +type MarginType = MarginValue | `${MarginValue} ${MarginValue}` | `${MarginValue} ${MarginValue} ${MarginValue}` | `${MarginValue} ${MarginValue} ${MarginValue} ${MarginValue}`; +interface InViewOptions { + root?: Element | Document; + margin?: MarginType; + amount?: "some" | "all" | number; +} +declare function inView(elementOrSelector: ElementOrSelector, onStart: (element: Element, entry: IntersectionObserverEntry) => void | ViewChangeHandler, { root, margin: rootMargin, amount }?: InViewOptions): VoidFunction; + +type DelayedFunction = (overshoot: number) => void; +/** + * Timeout defined in ms + */ +declare function delay(callback: DelayedFunction, timeout: number): () => void; + +declare const distance: (a: number, b: number) => number; +declare function distance2D(a: Point, b: Point): number; + +declare const m: typeof createMotionComponent & HTMLMotionComponents & SVGMotionComponents & { + create: typeof createMotionComponent; +}; + +declare const motion: typeof createMotionComponent & HTMLMotionComponents & SVGMotionComponents & { + create: typeof createMotionComponent; +}; + +type EventListenerWithPointInfo = (e: PointerEvent, info: EventInfo) => void; +declare const addPointerInfo: (handler: EventListenerWithPointInfo) => EventListener; + +declare function addPointerEvent(target: EventTarget, eventName: string, handler: EventListenerWithPointInfo, options?: AddEventListenerOptions): () => void; + +declare const animations: FeaturePackages; + +declare function calcLength(axis: Axis): number; + +declare const createBox: () => Box; + +declare const isBrowser: boolean; + +declare function useForceUpdate(): [VoidFunction, number]; + +declare const useIsomorphicLayoutEffect: typeof useEffect; + +declare function useUnmountEffect(callback: () => void): void; + +/** + * @public + */ +declare const domAnimation: FeatureBundle; + +/** + * @public + */ +declare const domMax: FeatureBundle; + +/** + * @public + */ +declare const domMin: FeatureBundle; + +declare function useMotionValueEvent>(value: MotionValue, event: EventName, callback: MotionValueEventCallbacks[EventName]): void; + +/** + * @deprecated useElementScroll is deprecated. Convert to useScroll({ container: ref }) + */ +declare function useElementScroll(ref: RefObject): { + scrollX: motion_dom.MotionValue; + scrollY: motion_dom.MotionValue; + scrollXProgress: motion_dom.MotionValue; + scrollYProgress: motion_dom.MotionValue; +}; + +/** + * @deprecated useViewportScroll is deprecated. Convert to useScroll() + */ +declare function useViewportScroll(): { + scrollX: motion_dom.MotionValue; + scrollY: motion_dom.MotionValue; + scrollXProgress: motion_dom.MotionValue; + scrollYProgress: motion_dom.MotionValue; +}; + +/** + * Combine multiple motion values into a new one using a string template literal. + * + * ```jsx + * import { + * motion, + * useSpring, + * useMotionValue, + * useMotionTemplate + * } from "framer-motion" + * + * function Component() { + * const shadowX = useSpring(0) + * const shadowY = useMotionValue(0) + * const shadow = useMotionTemplate`drop-shadow(${shadowX}px ${shadowY}px 20px rgba(0,0,0,0.3))` + * + * return + * } + * ``` + * + * @public + */ +declare function useMotionTemplate(fragments: TemplateStringsArray, ...values: Array): MotionValue; + +/** + * Creates a `MotionValue` to track the state and velocity of a value. + * + * Usually, these are created automatically. For advanced use-cases, like use with `useTransform`, you can create `MotionValue`s externally and pass them into the animated component via the `style` prop. + * + * ```jsx + * export const MyComponent = () => { + * const scale = useMotionValue(1) + * + * return + * } + * ``` + * + * @param initial - The initial state. + * + * @public + */ +declare function useMotionValue(initial: T): MotionValue; + +interface UseScrollOptions extends Omit { + container?: RefObject; + target?: RefObject; +} +declare function useScroll({ container, target, ...options }?: UseScrollOptions): { + scrollX: motion_dom.MotionValue; + scrollY: motion_dom.MotionValue; + scrollXProgress: motion_dom.MotionValue; + scrollYProgress: motion_dom.MotionValue; +}; + +/** + * Creates a `MotionValue` that, when `set`, will use a spring animation to animate to its new state. + * + * It can either work as a stand-alone `MotionValue` by initialising it with a value, or as a subscriber + * to another `MotionValue`. + * + * @remarks + * + * ```jsx + * const x = useSpring(0, { stiffness: 300 }) + * const y = useSpring(x, { damping: 10 }) + * ``` + * + * @param inputValue - `MotionValue` or number. If provided a `MotionValue`, when the input `MotionValue` changes, the created `MotionValue` will spring towards that value. + * @param springConfig - Configuration options for the spring. + * @returns `MotionValue` + * + * @public + */ +declare function useSpring(source: MotionValue, options?: SpringOptions): MotionValue; +declare function useSpring(source: string, options?: SpringOptions): MotionValue; +declare function useSpring(source: MotionValue, options?: SpringOptions): MotionValue; +declare function useSpring(source: number, options?: SpringOptions): MotionValue; + +declare function useTime(): motion_dom.MotionValue; + +type InputRange = number[]; +type SingleTransformer = (input: I) => O; +type MultiTransformer = (input: I[]) => O; +/** + * Create a `MotionValue` that transforms the output of another `MotionValue` by mapping it from one range of values into another. + * + * @remarks + * + * Given an input range of `[-200, -100, 100, 200]` and an output range of + * `[0, 1, 1, 0]`, the returned `MotionValue` will: + * + * - When provided a value between `-200` and `-100`, will return a value between `0` and `1`. + * - When provided a value between `-100` and `100`, will return `1`. + * - When provided a value between `100` and `200`, will return a value between `1` and `0` + * + * + * The input range must be a linear series of numbers. The output range + * can be any value type supported by Motion: numbers, colors, shadows, etc. + * + * Every value in the output range must be of the same type and in the same format. + * + * ```jsx + * export const MyComponent = () => { + * const x = useMotionValue(0) + * const xRange = [-200, -100, 100, 200] + * const opacityRange = [0, 1, 1, 0] + * const opacity = useTransform(x, xRange, opacityRange) + * + * return ( + * + * ) + * } + * ``` + * + * @param inputValue - `MotionValue` + * @param inputRange - A linear series of numbers (either all increasing or decreasing) + * @param outputRange - A series of numbers, colors or strings. Must be the same length as `inputRange`. + * @param options - + * + * - clamp: boolean. Clamp values to within the given range. Defaults to `true` + * - ease: EasingFunction[]. Easing functions to use on the interpolations between each value in the input and output ranges. If provided as an array, the array must be one item shorter than the input and output ranges, as the easings apply to the transition between each. + * + * @returns `MotionValue` + * + * @public + */ +declare function useTransform(value: MotionValue, inputRange: InputRange, outputRange: O[], options?: TransformOptions): MotionValue; +/** + * Create a `MotionValue` that transforms the output of another `MotionValue` through a function. + * In this example, `y` will always be double `x`. + * + * ```jsx + * export const MyComponent = () => { + * const x = useMotionValue(10) + * const y = useTransform(x, value => value * 2) + * + * return + * } + * ``` + * + * @param input - A `MotionValue` that will pass its latest value through `transform` to update the returned `MotionValue`. + * @param transform - A function that accepts the latest value from `input` and returns a new value. + * @returns `MotionValue` + * + * @public + */ +declare function useTransform(input: MotionValue, transformer: SingleTransformer): MotionValue; +/** + * Pass an array of `MotionValue`s and a function to combine them. In this example, `z` will be the `x` multiplied by `y`. + * + * ```jsx + * export const MyComponent = () => { + * const x = useMotionValue(0) + * const y = useMotionValue(0) + * const z = useTransform([x, y], ([latestX, latestY]) => latestX * latestY) + * + * return + * } + * ``` + * + * @param input - An array of `MotionValue`s that will pass their latest values through `transform` to update the returned `MotionValue`. + * @param transform - A function that accepts the latest values from `input` and returns a new value. + * @returns `MotionValue` + * + * @public + */ +declare function useTransform(input: MotionValue[] | MotionValue[] | MotionValue[], transformer: MultiTransformer): MotionValue; +declare function useTransform(transformer: () => O): MotionValue; + +/** + * Creates a `MotionValue` that updates when the velocity of the provided `MotionValue` changes. + * + * ```javascript + * const x = useMotionValue(0) + * const xVelocity = useVelocity(x) + * const xAcceleration = useVelocity(xVelocity) + * ``` + * + * @public + */ +declare function useVelocity(value: MotionValue): MotionValue; + +interface WillChange extends MotionValue { + add(name: string): void; +} + +declare function useWillChange(): WillChange; + +declare class WillChangeMotionValue extends MotionValue implements WillChange { + private isEnabled; + add(name: string): void; + private update; +} + +/** + * If the provided value is a MotionValue, this returns the actual value, otherwise just the value itself + * + * TODO: Remove and move to library + */ +declare function resolveMotionValue(value?: AnyResolvedKeyframe | MotionValue): AnyResolvedKeyframe; + +/** + * A hook that returns `true` if we should be using reduced motion based on the current device's Reduced Motion setting. + * + * This can be used to implement changes to your UI based on Reduced Motion. For instance, replacing motion-sickness inducing + * `x`/`y` animations with `opacity`, disabling the autoplay of background videos, or turning off parallax motion. + * + * It will actively respond to changes and re-render your components with the latest setting. + * + * ```jsx + * export function Sidebar({ isOpen }) { + * const shouldReduceMotion = useReducedMotion() + * const closedX = shouldReduceMotion ? 0 : "-100%" + * + * return ( + * + * ) + * } + * ``` + * + * @return boolean + * + * @public + */ +declare function useReducedMotion(): boolean | null; + +declare function useReducedMotionConfig(): boolean | null; + +/** + * @public + */ +declare function animationControls(): LegacyAnimationControls; + +declare function useAnimate(): [AnimationScope, { + (sequence: AnimationSequence, options?: SequenceOptions | undefined): motion_dom.AnimationPlaybackControlsWithThen; + (value: string | motion_dom.MotionValue, keyframes: string | motion_dom.UnresolvedValueKeyframe[], options?: motion_dom.ValueAnimationTransition | undefined): motion_dom.AnimationPlaybackControlsWithThen; + (value: number | motion_dom.MotionValue, keyframes: number | motion_dom.UnresolvedValueKeyframe[], options?: motion_dom.ValueAnimationTransition | undefined): motion_dom.AnimationPlaybackControlsWithThen; + (value: V | motion_dom.MotionValue, keyframes: V | motion_dom.UnresolvedValueKeyframe[], options?: motion_dom.ValueAnimationTransition | undefined): motion_dom.AnimationPlaybackControlsWithThen; + (element: motion_dom.ElementOrSelector, keyframes: motion_dom.DOMKeyframesDefinition, options?: motion_dom.AnimationOptions | undefined): motion_dom.AnimationPlaybackControlsWithThen; + (object: O | O[], keyframes: ObjectTarget, options?: motion_dom.AnimationOptions | undefined): motion_dom.AnimationPlaybackControlsWithThen; +}]; + +declare function useAnimateMini(): [AnimationScope, (elementOrSelector: motion_dom.ElementOrSelector, keyframes: motion_dom.DOMKeyframesDefinition, options?: motion_dom.AnimationOptions | undefined) => motion_dom.AnimationPlaybackControlsWithThen]; + +/** + * Creates `LegacyAnimationControls`, which can be used to manually start, stop + * and sequence animations on one or more components. + * + * The returned `LegacyAnimationControls` should be passed to the `animate` property + * of the components you want to animate. + * + * These components can then be animated with the `start` method. + * + * ```jsx + * import * as React from 'react' + * import { motion, useAnimation } from 'framer-motion' + * + * export function MyComponent(props) { + * const controls = useAnimation() + * + * controls.start({ + * x: 100, + * transition: { duration: 0.5 }, + * }) + * + * return + * } + * ``` + * + * @returns Animation controller with `start` and `stop` methods + * + * @public + */ +declare function useAnimationControls(): LegacyAnimationControls; +declare const useAnimation: typeof useAnimationControls; + +declare function animateVisualElement(visualElement: VisualElement, definition: AnimationDefinition, options?: VisualElementAnimationOptions): Promise; + +type SafeToRemove = () => void; +type AlwaysPresent = [true, null]; +type Present = [true]; +type NotPresent = [false, SafeToRemove]; +/** + * When a component is the child of `AnimatePresence`, it can use `usePresence` + * to access information about whether it's still present in the React tree. + * + * ```jsx + * import { usePresence } from "framer-motion" + * + * export const Component = () => { + * const [isPresent, safeToRemove] = usePresence() + * + * useEffect(() => { + * !isPresent && setTimeout(safeToRemove, 1000) + * }, [isPresent]) + * + * return

+ * } + * ``` + * + * If `isPresent` is `false`, it means that a component has been removed the tree, but + * `AnimatePresence` won't really remove it until `safeToRemove` has been called. + * + * @public + */ +declare function usePresence(subscribe?: boolean): AlwaysPresent | Present | NotPresent; +/** + * Similar to `usePresence`, except `useIsPresent` simply returns whether or not the component is present. + * There is no `safeToRemove` function. + * + * ```jsx + * import { useIsPresent } from "framer-motion" + * + * export const Component = () => { + * const isPresent = useIsPresent() + * + * useEffect(() => { + * !isPresent && console.log("I've been removed!") + * }, [isPresent]) + * + * return
+ * } + * ``` + * + * @public + */ +declare function useIsPresent(): boolean; + +declare function usePresenceData(): any; + +/** + * Attaches an event listener directly to the provided DOM element. + * + * Bypassing React's event system can be desirable, for instance when attaching non-passive + * event handlers. + * + * ```jsx + * const ref = useRef(null) + * + * useDomEvent(ref, 'wheel', onWheel, { passive: false }) + * + * return
+ * ``` + * + * @param ref - React.RefObject that's been provided to the element you want to bind the listener to. + * @param eventName - Name of the event you want listen for. + * @param handler - Function to fire when receiving the event. + * @param options - Options to pass to `Event.addEventListener`. + * + * @public + */ +declare function useDomEvent(ref: RefObject, eventName: string, handler?: EventListener | undefined, options?: AddEventListenerOptions): void; + +interface DragControlOptions { + /** + * This distance after which dragging starts and a direction is locked in. + * + * @public + */ + distanceThreshold?: number; + /** + * Whether to immediately snap to the cursor when dragging starts. + * + * @public + */ + snapToCursor?: boolean; +} + +/** + * Can manually trigger a drag gesture on one or more `drag`-enabled `motion` components. + * + * ```jsx + * const dragControls = useDragControls() + * + * function startDrag(event) { + * dragControls.start(event, { snapToCursor: true }) + * } + * + * return ( + * <> + *
+ * + * + * ) + * ``` + * + * @public + */ +declare class DragControls { + private componentControls; + /** + * Start a drag gesture on every `motion` component that has this set of drag controls + * passed into it via the `dragControls` prop. + * + * ```jsx + * dragControls.start(e, { + * snapToCursor: true + * }) + * ``` + * + * @param event - PointerEvent + * @param options - Options + * + * @public + */ + start(event: React$1.PointerEvent | PointerEvent, options?: DragControlOptions): void; + /** + * Cancels a drag gesture. + * + * ```jsx + * dragControls.cancel() + * ``` + * + * @public + */ + cancel(): void; + /** + * Stops a drag gesture. + * + * ```jsx + * dragControls.stop() + * ``` + * + * @public + */ + stop(): void; +} +/** + * Usually, dragging is initiated by pressing down on a `motion` component with a `drag` prop + * and moving it. For some use-cases, for instance clicking at an arbitrary point on a video scrubber, we + * might want to initiate that dragging from a different component than the draggable one. + * + * By creating a `dragControls` using the `useDragControls` hook, we can pass this into + * the draggable component's `dragControls` prop. It exposes a `start` method + * that can start dragging from pointer events on other components. + * + * ```jsx + * const dragControls = useDragControls() + * + * function startDrag(event) { + * dragControls.start(event, { snapToCursor: true }) + * } + * + * return ( + * <> + *
+ * + * + * ) + * ``` + * + * @public + */ +declare function useDragControls(): DragControls; + +/** + * Checks if a component is a `motion` component. + */ +declare function isMotionComponent(component: React.ComponentType | string): boolean; + +/** + * Unwraps a `motion` component and returns either a string for `motion.div` or + * the React component for `motion(Component)`. + * + * If the component is not a `motion` component it returns undefined. + */ +declare function unwrapMotionComponent(component: React.ComponentType | string): React.ComponentType | string | undefined; + +/** + * Check whether a prop name is a valid `MotionProp` key. + * + * @param key - Name of the property to check + * @returns `true` is key is a valid `MotionProp`. + * + * @public + */ +declare function isValidMotionProp(key: string): boolean; + +type ScaleCorrector = (latest: AnyResolvedKeyframe, node: IProjectionNode) => AnyResolvedKeyframe; +interface ScaleCorrectorDefinition { + correct: ScaleCorrector; + applyTo?: string[]; + isCSSVariable?: boolean; +} +interface ScaleCorrectorMap { + [key: string]: ScaleCorrectorDefinition; +} + +declare function addScaleCorrector(correctors: ScaleCorrectorMap): void; + +declare function useInstantLayoutTransition(): (cb?: (() => void) | undefined) => void; + +declare function useResetProjection(): () => void; + +/** + * Build a CSS transform style from individual x/y/scale etc properties. + * + * This outputs with a default order of transforms/scales/rotations, this can be customised by + * providing a transformTemplate function. + */ +declare function buildTransform(latestValues: ResolvedValues, transform: HTMLRenderState["transform"], transformTemplate?: MotionProps["transformTemplate"]): string; + +declare const visualElementStore: WeakMap>; + +type FrameCallback = (timestamp: number, delta: number) => void; +declare function useAnimationFrame(callback: FrameCallback): void; + +type Cycle = (i?: number) => void; +type CycleState = [T, Cycle]; +/** + * Cycles through a series of visual properties. Can be used to toggle between or cycle through animations. It works similar to `useState` in React. It is provided an initial array of possible states, and returns an array of two arguments. + * + * An index value can be passed to the returned `cycle` function to cycle to a specific index. + * + * ```jsx + * import * as React from "react" + * import { motion, useCycle } from "framer-motion" + * + * export const MyComponent = () => { + * const [x, cycleX] = useCycle(0, 50, 100) + * + * return ( + * cycleX()} + * /> + * ) + * } + * ``` + * + * @param items - items to cycle through + * @returns [currentState, cycleState] + * + * @public + */ +declare function useCycle(...items: T[]): CycleState; + +interface UseInViewOptions extends Omit { + root?: RefObject; + once?: boolean; + amount?: "some" | "all" | number; + initial?: boolean; +} +declare function useInView(ref: RefObject, { root, margin, amount, once, initial, }?: UseInViewOptions): boolean; + +declare function useInstantTransition(): (callback: () => void) => void; +declare function disableInstantTransitions(): void; + +declare function usePageInView(): boolean; + +declare function startOptimizedAppearAnimation(element: HTMLElement, name: string, keyframes: string[] | number[], options: ValueAnimationTransition, onReady?: (animation: Animation) => void): void; + +interface NodeGroup { + add: (node: IProjectionNode) => void; + remove: (node: IProjectionNode) => void; + dirty: VoidFunction; +} + +interface LayoutGroupContextProps { + id?: string; + group?: NodeGroup; + forceRender?: VoidFunction; +} +declare const LayoutGroupContext: React$1.Context; + +interface MotionContextProps { + visualElement?: VisualElement; + initial?: false | string | string[]; + animate?: string | string[]; +} +declare const MotionContext: React$1.Context>; + +/** + * @public + */ +interface ScrollMotionValues { + scrollX: MotionValue; + scrollY: MotionValue; + scrollXProgress: MotionValue; + scrollYProgress: MotionValue; +} + +/** + * This is not an officially supported API and may be removed + * on any version. + */ +declare function useAnimatedState(initialState: any): any[]; + +declare const AnimateSharedLayout: React$1.FunctionComponent>; + +/** + * Note: Still used by components generated by old versions of Framer + * + * @deprecated + */ +declare const DeprecatedLayoutGroupContext: React$1.Context; + +interface ScaleMotionValues { + scaleX: MotionValue; + scaleY: MotionValue; +} +/** + * Returns a `MotionValue` each for `scaleX` and `scaleY` that update with the inverse + * of their respective parent scales. + * + * This is useful for undoing the distortion of content when scaling a parent component. + * + * By default, `useInvertedScale` will automatically fetch `scaleX` and `scaleY` from the nearest parent. + * By passing other `MotionValue`s in as `useInvertedScale({ scaleX, scaleY })`, it will invert the output + * of those instead. + * + * ```jsx + * const MyComponent = () => { + * const { scaleX, scaleY } = useInvertedScale() + * return + * } + * ``` + * + * @deprecated + */ +declare function useInvertedScale(scale?: Partial): ScaleMotionValues; + +export { type AbsoluteKeyframe, AnimatePresence, type AnimatePresenceProps, AnimateSharedLayout, type AnimationSequence, type At, type Cycle, type CycleState, type DOMSegment, type DOMSegmentWithTransition, type DelayedFunction, DeprecatedLayoutGroupContext, DragControls, FeatureBundle, FeaturePackages, HTMLMotionProps, IProjectionNode, LayoutGroup, LayoutGroupContext, LazyMotion, type LazyProps, MotionConfig, MotionConfigContext, type MotionConfigProps, MotionContext, MotionProps, type MotionValueSegment, type MotionValueSegmentWithTransition, type ObjectSegment, type ObjectSegmentWithTransition, type ObjectTarget, namespace_d as Reorder, type ResolveKeyframes, type ResolvedAnimationDefinition, type ResolvedAnimationDefinitions, ResolvedValues, type ScrollMotionValues, type Segment, type SequenceLabel, type SequenceLabelWithTime, type SequenceMap, type SequenceOptions, type SequenceTime, type UseInViewOptions, type UseScrollOptions, type ValueSequence, VisualElement, WillChangeMotionValue, addPointerEvent, addPointerInfo, addScaleCorrector, animate, animateMini, animateVisualElement, animationControls, animations, buildTransform, calcLength, createBox, createScopedAnimate, delay, disableInstantTransitions, distance, distance2D, domAnimation, domMax, domMin, filterProps, inView, isBrowser, isMotionComponent, isValidMotionProp, m, motion, resolveMotionValue, scroll, scrollInfo, startOptimizedAppearAnimation, unwrapMotionComponent, useAnimate, useAnimateMini, useAnimation, useAnimationControls, useAnimationFrame, useCycle, useAnimatedState as useDeprecatedAnimatedState, useInvertedScale as useDeprecatedInvertedScale, useDomEvent, useDragControls, useElementScroll, useForceUpdate, useInView, useInstantLayoutTransition, useInstantTransition, useIsPresent, useIsomorphicLayoutEffect, useMotionTemplate, useMotionValue, useMotionValueEvent, usePageInView, usePresence, usePresenceData, useReducedMotion, useReducedMotionConfig, useResetProjection, useScroll, useSpring, useTime, useTransform, useUnmountEffect, useVelocity, useViewportScroll, useWillChange, visualElementStore }; diff --git a/frontend/node_modules/framer-motion/dom/README.md b/frontend/node_modules/framer-motion/dom/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9f4c437ac6b51738676e4b39e864cb79ade30445 --- /dev/null +++ b/frontend/node_modules/framer-motion/dom/README.md @@ -0,0 +1 @@ +This directory is a fallback for `exports["./dom"]` in the root `framer-motion` `package.json`. diff --git a/frontend/node_modules/framer-motion/dom/mini/package.json b/frontend/node_modules/framer-motion/dom/mini/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6d6ee8d7d403d63d65b3cb0969df8e194904f388 --- /dev/null +++ b/frontend/node_modules/framer-motion/dom/mini/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "types": "../../dist/dom-mini.d.ts", + "main": "../../dist/cjs/dom-mini.js", + "module": "../../dist/es/dom-mini.mjs" +} diff --git a/frontend/node_modules/framer-motion/dom/package.json b/frontend/node_modules/framer-motion/dom/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c08f91cd648d1335e774115fb41016d2283c02b6 --- /dev/null +++ b/frontend/node_modules/framer-motion/dom/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "types": "../dist/dom.d.ts", + "main": "../dist/cjs/dom.js", + "module": "../dist/es/dom.mjs" +} diff --git a/frontend/node_modules/framer-motion/m/package.json b/frontend/node_modules/framer-motion/m/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5e76408c4ba18172b5be83a130ad45c582278ef4 --- /dev/null +++ b/frontend/node_modules/framer-motion/m/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "types": "../dist/m.d.ts", + "main": "../dist/cjs/m.js", + "module": "../dist/es/m.mjs" +} diff --git a/frontend/node_modules/framer-motion/mini/package.json b/frontend/node_modules/framer-motion/mini/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1ed44076d07e6d82e62f8c923b3b998510417922 --- /dev/null +++ b/frontend/node_modules/framer-motion/mini/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "types": "../dist/mini.d.ts", + "main": "../dist/cjs/mini.js", + "module": "../dist/es/mini.mjs" +} diff --git a/frontend/node_modules/framer-motion/package.json b/frontend/node_modules/framer-motion/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3d98fb921fc292d45917f3f33a35c8ed7d5363ef --- /dev/null +++ b/frontend/node_modules/framer-motion/package.json @@ -0,0 +1,146 @@ +{ + "name": "framer-motion", + "version": "12.23.12", + "description": "A simple and powerful JavaScript animation library", + "main": "dist/cjs/index.js", + "module": "dist/es/index.mjs", + "exports": { + ".": { + "types": "./dist/types/index.d.ts", + "require": "./dist/cjs/index.js", + "import": "./dist/es/index.mjs", + "default": "./dist/cjs/index.js" + }, + "./debug": { + "types": "./dist/debug.d.ts", + "require": "./dist/cjs/debug.js", + "import": "./dist/es/debug.mjs", + "default": "./dist/cjs/debug.js" + }, + "./dom/mini": { + "types": "./dist/dom-mini.d.ts", + "require": "./dist/cjs/dom-mini.js", + "import": "./dist/es/dom-mini.mjs", + "default": "./dist/cjs/dom-mini.js" + }, + "./dom": { + "types": "./dist/dom.d.ts", + "require": "./dist/cjs/dom.js", + "import": "./dist/es/dom.mjs", + "default": "./dist/cjs/dom.js" + }, + "./client": { + "types": "./dist/types/client.d.ts", + "require": "./dist/cjs/client.js", + "import": "./dist/es/client.mjs", + "default": "./dist/cjs/client.js" + }, + "./m": { + "types": "./dist/m.d.ts", + "require": "./dist/cjs/m.js", + "import": "./dist/es/m.mjs", + "default": "./dist/cjs/m.js" + }, + "./mini": { + "types": "./dist/mini.d.ts", + "require": "./dist/cjs/mini.js", + "import": "./dist/es/mini.mjs", + "default": "./dist/cjs/mini.js" + }, + "./projection": { + "import": "./dist/es/projection.mjs", + "default": "./dist/es/projection.mjs" + }, + "./package.json": "./package.json" + }, + "types": "dist/types/index.d.ts", + "author": "Matt Perry", + "license": "MIT", + "repository": "https://github.com/motiondivision/motion/", + "sideEffects": false, + "keywords": [ + "react animation", + "react", + "pose", + "react pose", + "animation", + "gestures", + "drag", + "spring", + "popmotion", + "framer", + "waapi" + ], + "scripts": { + "eslint": "yarn run lint", + "lint": "yarn eslint src/**/*.ts", + "build": "yarn clean && tsc --noEmitOnError -p . && rollup -c && node ./scripts/check-bundle.js", + "dev": "yarn watch", + "clean": "rm -rf types dist lib", + "test": "yarn test-server && yarn test-client", + "test-client": "jest --config jest.config.json --max-workers=2", + "test-server": "jest --config jest.config.ssr.json", + "prettier": "prettier ./src/* --write", + "watch": "concurrently -c blue,red -n tsc --noEmitOnError ,rollup --kill-others \"tsc --noEmitOnError --watch -p . --preserveWatchOutput\" \"rollup --config --watch --no-watch.clearScreen\"", + "prepack": "yarn build && yarn measure", + "postpublish": "git push --tags", + "measure": "rollup -c ./rollup.size.config.mjs" + }, + "dependencies": { + "motion-dom": "^12.23.12", + "motion-utils": "^12.23.6", + "tslib": "^2.4.0" + }, + "devDependencies": { + "@thednp/dommatrix": "^2.0.11", + "@types/three": "0.137.0", + "three": "0.137.0" + }, + "peerDependencies": { + "@emotion/is-prop-valid": "*", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@emotion/is-prop-valid": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + }, + "bundlesize": [ + { + "path": "./dist/size-rollup-motion.js", + "maxSize": "34.9 kB" + }, + { + "path": "./dist/size-rollup-m.js", + "maxSize": "6 kB" + }, + { + "path": "./dist/size-rollup-dom-animation.js", + "maxSize": "17.85 kB" + }, + { + "path": "./dist/size-rollup-dom-max.js", + "maxSize": "29.8 kB" + }, + { + "path": "./dist/size-rollup-animate.js", + "maxSize": "19.1 kB" + }, + { + "path": "./dist/size-rollup-scroll.js", + "maxSize": "5.2 kB" + }, + { + "path": "./dist/size-rollup-waapi-animate.js", + "maxSize": "2.26 kB" + } + ], + "gitHead": "e0f7e07570e281b8932c897afb5f6a348c7f97de" +}