chartist 1.5.0 → 2.0.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -101
- package/dist/_settings.scss +1 -89
- package/dist/chartist.min.css +2 -0
- package/dist/chartist.min.js +2 -0
- package/dist/compat.cjs +624 -0
- package/dist/compat.cjs.map +1 -0
- package/dist/compat.d.cts +202 -0
- package/dist/compat.d.ts +201 -0
- package/dist/compat.js +603 -0
- package/dist/compat.js.map +1 -0
- package/dist/compat.min.js +2 -0
- package/dist/compat.min.js.map +1 -0
- package/dist/compat.umd.js +2 -0
- package/dist/compat.umd.js.map +1 -0
- package/dist/index.cjs +5970 -3489
- package/dist/index.cjs.map +1 -1
- package/dist/index.css +903 -2
- package/dist/index.css.map +1 -1
- package/dist/index.d.cts +5167 -0
- package/dist/index.d.ts +5166 -8
- package/dist/index.js +5935 -3484
- package/dist/index.js.map +1 -1
- package/dist/index.min.css +2 -0
- package/dist/index.min.css.map +1 -0
- package/dist/index.min.js +2 -0
- package/dist/index.min.js.map +1 -0
- package/dist/index.scss +1 -204
- package/dist/index.umd.js +2 -2
- package/dist/index.umd.js.map +1 -1
- package/dist/scss/_settings.scss +155 -0
- package/dist/scss/index.scss +262 -0
- package/dist/scss/themes/accessible.scss +53 -0
- package/dist/themes/accessible.css +34 -0
- package/dist/themes/accessible.min.css +1 -0
- package/package.json +238 -12
- package/dist/axes/AutoScaleAxis.d.ts +0 -12
- package/dist/axes/AutoScaleAxis.d.ts.map +0 -1
- package/dist/axes/Axis.d.ts +0 -40
- package/dist/axes/Axis.d.ts.map +0 -1
- package/dist/axes/FixedScaleAxis.d.ts +0 -11
- package/dist/axes/FixedScaleAxis.d.ts.map +0 -1
- package/dist/axes/StepAxis.d.ts +0 -9
- package/dist/axes/StepAxis.d.ts.map +0 -1
- package/dist/axes/index.d.ts +0 -6
- package/dist/axes/index.d.ts.map +0 -1
- package/dist/axes/types.d.ts +0 -5
- package/dist/axes/types.d.ts.map +0 -1
- package/dist/charts/BarChart/BarChart.d.ts +0 -50
- package/dist/charts/BarChart/BarChart.d.ts.map +0 -1
- package/dist/charts/BarChart/BarChart.types.d.ts +0 -66
- package/dist/charts/BarChart/BarChart.types.d.ts.map +0 -1
- package/dist/charts/BarChart/index.d.ts +0 -3
- package/dist/charts/BarChart/index.d.ts.map +0 -1
- package/dist/charts/BaseChart.d.ts +0 -47
- package/dist/charts/BaseChart.d.ts.map +0 -1
- package/dist/charts/LineChart/LineChart.d.ts +0 -97
- package/dist/charts/LineChart/LineChart.d.ts.map +0 -1
- package/dist/charts/LineChart/LineChart.types.d.ts +0 -83
- package/dist/charts/LineChart/LineChart.types.d.ts.map +0 -1
- package/dist/charts/LineChart/index.d.ts +0 -3
- package/dist/charts/LineChart/index.d.ts.map +0 -1
- package/dist/charts/PieChart/PieChart.d.ts +0 -101
- package/dist/charts/PieChart/PieChart.d.ts.map +0 -1
- package/dist/charts/PieChart/PieChart.types.d.ts +0 -95
- package/dist/charts/PieChart/PieChart.types.d.ts.map +0 -1
- package/dist/charts/PieChart/index.d.ts +0 -3
- package/dist/charts/PieChart/index.d.ts.map +0 -1
- package/dist/charts/index.d.ts +0 -6
- package/dist/charts/index.d.ts.map +0 -1
- package/dist/charts/types.d.ts +0 -11
- package/dist/charts/types.d.ts.map +0 -1
- package/dist/core/constants.d.ts +0 -13
- package/dist/core/constants.d.ts.map +0 -1
- package/dist/core/creation.d.ts +0 -61
- package/dist/core/creation.d.ts.map +0 -1
- package/dist/core/data/bounds.d.ts +0 -14
- package/dist/core/data/bounds.d.ts.map +0 -1
- package/dist/core/data/data.d.ts +0 -23
- package/dist/core/data/data.d.ts.map +0 -1
- package/dist/core/data/highLow.d.ts +0 -13
- package/dist/core/data/highLow.d.ts.map +0 -1
- package/dist/core/data/index.d.ts +0 -7
- package/dist/core/data/index.d.ts.map +0 -1
- package/dist/core/data/normalize.d.ts +0 -11
- package/dist/core/data/normalize.d.ts.map +0 -1
- package/dist/core/data/segments.d.ts +0 -29
- package/dist/core/data/segments.d.ts.map +0 -1
- package/dist/core/data/serialize.d.ts +0 -12
- package/dist/core/data/serialize.d.ts.map +0 -1
- package/dist/core/index.d.ts +0 -8
- package/dist/core/index.d.ts.map +0 -1
- package/dist/core/lang.d.ts +0 -23
- package/dist/core/lang.d.ts.map +0 -1
- package/dist/core/math.d.ts +0 -42
- package/dist/core/math.d.ts.map +0 -1
- package/dist/core/optionsProvider.d.ts +0 -15
- package/dist/core/optionsProvider.d.ts.map +0 -1
- package/dist/core/types.d.ts +0 -274
- package/dist/core/types.d.ts.map +0 -1
- package/dist/event/EventEmitter.d.ts +0 -27
- package/dist/event/EventEmitter.d.ts.map +0 -1
- package/dist/event/index.d.ts +0 -2
- package/dist/event/index.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/interpolation/cardinal.d.ts +0 -30
- package/dist/interpolation/cardinal.d.ts.map +0 -1
- package/dist/interpolation/index.d.ts +0 -6
- package/dist/interpolation/index.d.ts.map +0 -1
- package/dist/interpolation/monotoneCubic.d.ts +0 -30
- package/dist/interpolation/monotoneCubic.d.ts.map +0 -1
- package/dist/interpolation/none.d.ts +0 -22
- package/dist/interpolation/none.d.ts.map +0 -1
- package/dist/interpolation/simple.d.ts +0 -30
- package/dist/interpolation/simple.d.ts.map +0 -1
- package/dist/interpolation/step.d.ts +0 -26
- package/dist/interpolation/step.d.ts.map +0 -1
- package/dist/svg/Svg.d.ts +0 -201
- package/dist/svg/Svg.d.ts.map +0 -1
- package/dist/svg/SvgList.d.ts +0 -31
- package/dist/svg/SvgList.d.ts.map +0 -1
- package/dist/svg/SvgPath.d.ts +0 -125
- package/dist/svg/SvgPath.d.ts.map +0 -1
- package/dist/svg/animation.d.ts +0 -37
- package/dist/svg/animation.d.ts.map +0 -1
- package/dist/svg/index.d.ts +0 -6
- package/dist/svg/index.d.ts.map +0 -1
- package/dist/svg/types.d.ts +0 -55
- package/dist/svg/types.d.ts.map +0 -1
- package/dist/utils/extend.d.ts +0 -10
- package/dist/utils/extend.d.ts.map +0 -1
- package/dist/utils/functional.d.ts +0 -31
- package/dist/utils/functional.d.ts.map +0 -1
- package/dist/utils/index.d.ts +0 -5
- package/dist/utils/index.d.ts.map +0 -1
- package/dist/utils/types.d.ts +0 -7
- package/dist/utils/types.d.ts.map +0 -1
- package/dist/utils/utils.d.ts +0 -31
- package/dist/utils/utils.d.ts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.min.js","names":["precision","CLASS_NAMES","rawSeries","normalizePadding","PHASES","axesConfig","CLASS_NAMES","serialize","__defProp","__exportAll","target","name","all","no_symbols","namespaces","precision","escapingMap","ensureUnit","value","unit","quantity","input","match","alphaNumerate","n","EPSILON","orderOfMagnitude","projectLength","length","bounds","axisLength","roundWithPrecision","precision$1","digits","rho","num","gcd","i","p","q","remainder","f","x","x1","x2","divisor","polarToCartesian","angleInRadians","angleInDegrees","centerX","radius","centerY","getBounds","highLow","scaleUp","scaleMinSpace","smallestFactor","onlyInteger","optimizationCounter","safeIncrement","increment","newMin","newMax","values","extend","sources","source","targetProto","prop","sourceProp","targetProp","noop","times","filler","sum","previous","current","serialMap","array","element","callback","index","safeHasProperty","property","isNumeric","isFalseyButZero","getNumberOrUndefined","isArrayOfArrays","data","each","list","reverse","item","itemIndex","getMetaData","seriesData","isDataHoleValue","isArrayOfSeries","_","isMultiValue","getMultiValue","dimension","nonEmptyRange","high","low","getHighLow","options","findHigh","findLow","recursiveHighLow","sourceData","extent","normalizeData","labelCount","normalized","normalizeSeries","multi","distributed","inputLabelCount","series","reverseData","normalizeMulti","y","normalizePrimitive","normalizeSingleSeries","normalizedSeries","splitIntoSegments","finalOptions","segments","hole","pathCoordinates","valueData","serialize","serialized","result","key","deserialize","parsedData","SvgList","nodeList","Svg","method","args","easings","ANIMATION_EMITTER","animationEmitterOf","node","emitter","createAnimation","def","animationDefinition","attributeProperties","animationEasing","timeout","easing","createGuided","attribute","animate","animateNode","eventEmitter","parent","attributes","className","insertFirst","ns","namespacedAttribute","foundNode","selector","contentNode","content","container","fnObj","t","newElement","classNames","names","self","elem","pos","removedClasses","animations","attributeAnimation","guided","createSvg","svg","width","height","viewBox","normalizePadding","padding","createChartRect","hasAxis","yAxisOffset","xAxisOffset","yAxisPosition","xAxisPosition","normalizedPadding","chartRect","createGrid","positionalData","axis","position","offset","gridElement","group","classes","createGridBackground","gridBackground","gridGroup","createLabel","labelOffset","axisOffset","stepLength","stepCounterLength","label","labelElement","optionsProvider","currentOptions","mediaQueryListeners","updateCurrentOptions","previousOptions","responsiveOptions","responsiveOption","mediaEvent","removeMediaQueryListeners","mql","EventEmitter","event","allListeners","listener","listeners","eventListeners","instances","BaseChart","defaultOptions","query","prevInstance","override","plugin","elementDescriptions","scaleAxes","translateAxes","commandPattern","numberPattern","flagPattern","separatorPattern","parseCommands","read","path","pattern","fail","commands","command","params","next","pathElement","relative","pathElements","forEachParam","cb","paramName","pathElementIndex","paramIndex","SvgPath","joinedPath","close","paths","j","count","y1","y2","elements","accuracyMultiplier","accuracy","transformed","transformFnc","clone","letter","pieces","piece","none","currX","currY","currData","splitByDirection","segment","direction","dx","sign","monotoneCubic","monotoneCubicInterpolation","xs","ys","ms","ds","dys","dxs","splitClasses","builder","attrs","withFields","added","removed","child","existing","create","created","field","fields","changes","attr","meta","DEFAULTS","CLASS_NAMES$2","rawSeries$1","seriesOption","fallback","line","axisX","axisY","axes","seriesIndexes","shift","order","seriesIndex","dataIndex","localIndex","seriesName","seriesClassName","seriesMeta","pathData","area","valueIndex","lineSmooth","seriesContext","children","pathElementData","areaBase","areaBaseProjected","first","last","areaPath","directionOf","side","definitionsOf","config","definitions","insetsOf","sums","inset","definition","axisArea","w","h","axisUnits","Axis","units","ticks","axisOptions","chartOptions","projectedValues","tick","labelValues","labelValue","labelLength","projectedValue","labelGroup","isLegacyAxisClass","type","legacyAxis","legacyOptions","instance","bindLayers","firstOf","d","ids","layers","id","layer","s","boundSeries","seriesCount","bound","binding","bindings","set","a","b","normalizeForAxes","raw","normalize","layerExtents","merged","selection","reported","createAxis","presetAxes","insets","boundOf","extents","allSeries","indexes","cartesianAxes","withOffset","setup","given","extra","valueOf","stepAxis","labels","autoScaleAxis","fixedScaleAxis","range","lineDefaults","without","entries","entry","createPhaseEmitter","wildcards","observe","matches","candidate","findAll","found","visit","scene","mapNodes","changed","mapped","mapper","assignKeys","layerIndex","DEFAULT_PADDING","normalizePadding$1","check","phase","resolve","resolved","prepareSeries","prepare","validate","layout","initial","compose","composed","byId","layerData","layerNormalized","nodes","top","root","size","built","runPipeline","reuse","from","laidOut","environment","withRootClass","measure","measureOptions","measureText","measureStyle","textAscent","estimateText","fontSize","text","setAttribute","separator","prefix","build","document","html","childrenAreHtml","removePrevious","probe","measureInDocument","box","domRenderer","view","chartTypeClass","types","withChartTypeClass","withOptions","untyped","handle","PHASES$1","LEGACY_EVENTS","warnedEvents","warn","message","plugins","scopes","listenerScope","addingAs","scope","owner","add","asUserListeners","chart","installPlugins","provided","registerListeners","eventMethods","payload","fixedSize","resolveTarget","renderer","rendererMeasure","measuredText","rendererStyle","effective","watcher","state","output","observer","destroyed","attached","fonts","onFontsLoaded","render","printed","printing","applyPrintViewBox","onBeforePrint","onAfterPrint","measureSvg","px","measured","elementOf","resolveResponsive","onResponsiveChange","previousConfig","watch","Observer","UNITS","axisNodes","frame","place","projected","gridOffset","gridLength","grids","atStart","ctx","span","labelAlign","kind","wrapText","lines","word","widthOf","svgLabels","classList","metrics","align","blockHeight","round","isContainerCondition","condition","warned","warnMissingApi","sameIndexes","watchResponsive","host","lists","error","onEvent","onChange","observeResize","responsive","applyResponsive","matching","merge","base","context","gridLayer","labelLayer","svgLabel","seriesGroup","PRESET_STATE","rootStyle","getOptions","presetConfig","spec","createPreset","initialData","withResponsive","baseOptions","overrides","withState","controller","inner","nextData","nextOptions","ready","detachedEarly","how","labelStepAxis","step","axesConfig$1","lineSpec","preset","lineChartConfig","createLineChart","lineChart","warnedPlugins","PHASES","v2Plugins","runner","PresetChart","defaults","chartResponsiveOptions","queued","syncFields","wildcard","filtered","queuedListener","getSeriesOption","LineChart","valueAlong","stackedExtent","positive","negative","amount","rawSeries","bar","horizontal","seriesBarDistance","stackMode","stacks","valueAxis","labelAxis","labelPos","counterPos","zeroPoint","isAccumulate","isAccumulateRelative","posStack","negStack","stack","biPol","periodHalfLength","bars","valueX","valueY","labelIndex","previousStack","positions","barDefaults","axesConfig","valueSetup","labelSetup","barSpec","extentOf","barChartConfig","createBarChart","barChart","BarChart","determineAnchorPosition","toTheRight","center","moveLabel","existingLabelPos","textOffset","cssWidth","sliceClass","CLASS_NAMES$1","pie","labelInterpolationFnc","labelPositions","startAngle","totalDataSum","donutWidth","labelRadius","hasSingleValInSeries","val","groups","labelNodes","endAngle","overlappingStartAngle","fullCircle","start","opposite","end","slice","labelPosition","rawValue","interpolated","pieDefaults","pieSpec","pieChartConfig","createPieChart","pieChart","PieChart","AutoScaleAxis","axisUnit","finalValue","FixedScaleAxis","StepAxis","calc","simple","prevX","prevY","prevData","cardinal","c","cardinalInterpolation","iLen","interpolation_exports","seriesColors","escape","char","parts","serialize$1","open","childPosition","renderToString","unavailable","toScene","CLASS_NAMES","drawnOptions","selectedAxes","placeOnSide","nodesOf","axisGrid","axisLabels"],"sources":["../src/core/constants.ts","../src/core/lang.ts","../src/core/math.ts","../src/core/data/bounds.ts","../src/utils/extend.ts","../src/utils/functional.ts","../src/utils/utils.ts","../src/core/data/data.ts","../src/core/data/range.ts","../src/core/data/highLow.ts","../src/core/data/normalize.ts","../src/core/data/segments.ts","../src/core/data/serialize.ts","../src/svg/SvgList.ts","../src/svg/animation.ts","../src/svg/Svg.ts","../src/core/creation.ts","../src/core/optionsProvider.ts","../src/event/EventEmitter.ts","../src/charts/BaseChart.ts","../src/svg/SvgPath.ts","../src/interpolation/none.ts","../src/interpolation/monotoneCubic.ts","../src/scene/node.ts","../src/layers/line.ts","../src/scales/axis.ts","../src/axes/Axis.ts","../src/scales/legacy.ts","../src/scales/cartesian.ts","../src/scales/factories.ts","../src/presets/lineDefaults.ts","../src/pipeline/emitter.ts","../src/scene/tree.ts","../src/pipeline/phases.ts","../src/render/measure.ts","../src/render/dom.ts","../src/chart/className.ts","../src/chart/types.ts","../src/chart/plugins.ts","../src/chart/chart.ts","../src/scales/grid.ts","../src/scales/svgLabels.ts","../src/responsive/responsive.ts","../src/presets/preset.ts","../src/presets/lineChart.ts","../src/charts/PresetChart.ts","../src/charts/LineChart/LineChart.ts","../src/layers/bar.ts","../src/presets/barDefaults.ts","../src/presets/barChart.ts","../src/charts/BarChart/BarChart.ts","../src/layers/pie.ts","../src/presets/pieDefaults.ts","../src/presets/pieChart.ts","../src/charts/PieChart/PieChart.ts","../src/axes/AutoScaleAxis.ts","../src/axes/FixedScaleAxis.ts","../src/axes/StepAxis.ts","../src/interpolation/simple.ts","../src/interpolation/step.ts","../src/interpolation/cardinal.ts","../src/interpolation/index.ts","../src/render/colors.ts","../src/render/string.ts","../src/chart/toScene.ts","../src/layers/axes.ts"],"sourcesContent":["/**\n * This object contains all namespaces used within Chartist.\n */\nexport const namespaces: Record<string, string> = {\n svg: 'http://www.w3.org/2000/svg',\n xmlns: 'http://www.w3.org/2000/xmlns/',\n xhtml: 'http://www.w3.org/1999/xhtml',\n xlink: 'http://www.w3.org/1999/xlink',\n ct: 'http://gionkunz.github.com/chartist-js/ct'\n};\n\n/**\n * Precision level used internally in Chartist for rounding. If you require more decimal places you can increase this number.\n */\nexport const precision = 8;\n\n/**\n * A map with characters to escape for strings to be safely used as attribute values.\n */\nexport const escapingMap: Record<string, string> = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": '''\n};\n","/**\n * Converts a number to a string with a unit. If a string is passed then this will be returned unmodified.\n * @return Returns the passed number value with unit.\n */\nexport function ensureUnit<T>(value: T, unit: string) {\n if (typeof value === 'number') {\n return value + unit;\n }\n\n return value;\n}\n\n/**\n * Converts a number or string to a quantity object.\n * @return Returns an object containing the value as number and the unit as string.\n */\nexport function quantity<T>(input: T) {\n if (typeof input === 'string') {\n const match = /^(\\d+)\\s*(.*)$/g.exec(input);\n return {\n value: match ? +match[1] : 0,\n unit: match?.[2] || undefined\n };\n }\n\n return {\n value: Number(input)\n };\n}\n\n/**\n * Generates a-z from a number 0 to 26\n * @param n A number from 0 to 26 that will result in a letter a-z\n * @return A character from a-z based on the input number n\n */\nexport function alphaNumerate(n: number) {\n // Limit to a-z\n return String.fromCharCode(97 + (n % 26));\n}\n","import type { Bounds } from './types';\nimport { precision as globalPrecision } from './constants';\n\n/** A tiny number, about the gap between 1 and the next float: the tolerance of float comparisons. */\nexport const EPSILON = 2.221e-16;\n\n/**\n * Calculate the order of magnitude for the chart scale\n * @param value The value Range of the chart\n * @return The order of magnitude\n */\nexport function orderOfMagnitude(value: number) {\n return Math.floor(Math.log(Math.abs(value)) / Math.LN10);\n}\n\n/**\n * Project a data length into screen coordinates (pixels)\n * @param axisLength The svg element for the chart\n * @param length Single data value from a series array\n * @param bounds All the values to set the bounds of the chart\n * @return The projected data length in pixels\n */\nexport function projectLength(\n axisLength: number,\n length: number,\n bounds: Bounds\n) {\n return (length / bounds.range) * axisLength;\n}\n\n/**\n * Rounds a value to a number of digits after the decimal point, to remove\n * float errors such as `0.30000000000000004`. `0` digits round to whole\n * numbers.\n * @param value The value to round\n * @param [digits] The digits after the decimal point; without it, the\n * global precision (8)\n * @returns The rounded value\n */\nexport function roundWithPrecision(value: number, digits?: number) {\n const precision = Math.pow(10, digits ?? globalPrecision);\n return Math.round(value * precision) / precision;\n}\n\n/**\n * Pollard Rho Algorithm to find smallest factor of an integer value. There are more efficient algorithms for factorization, but this one is quite efficient and not so complex.\n * @param num An integer number where the smallest factor should be searched for\n * @returns The smallest integer factor of the parameter num, or num itself when it is not finite.\n */\nexport function rho(num: number) {\n // A non-finite range (from an empty one) has no factor to find (#1057).\n if (num === 1 || !Number.isFinite(num)) {\n return num;\n }\n\n // Euclid's algorithm, bounded so that input it can't finish on (NaN,\n // Infinity) gives NaN instead of running forever.\n function gcd(p: number, q: number): number {\n for (let i = 0; i < 1000 && Number.isFinite(p) && q !== 0; i++) {\n const remainder = p % q;\n if (remainder === 0) {\n return q;\n }\n p = q;\n q = remainder;\n }\n return NaN;\n }\n\n function f(x: number) {\n return x * x + 1;\n }\n\n let x1 = 2;\n let x2 = 2;\n let divisor: number;\n\n if (num % 2 === 0) {\n return 2;\n }\n\n do {\n x1 = f(x1) % num;\n x2 = f(f(x2)) % num;\n divisor = gcd(Math.abs(x1 - x2), num);\n } while (divisor === 1);\n\n return divisor;\n}\n\n/**\n * Calculate cartesian coordinates of polar coordinates\n * @param centerX X-axis coordinates of center point of circle segment\n * @param centerY X-axis coordinates of center point of circle segment\n * @param radius Radius of circle segment\n * @param angleInDegrees Angle of circle segment in degrees\n * @return Coordinates of point on circumference\n */\nexport function polarToCartesian(\n centerX: number,\n centerY: number,\n radius: number,\n angleInDegrees: number\n) {\n const angleInRadians = ((angleInDegrees - 90) * Math.PI) / 180.0;\n\n return {\n x: centerX + radius * Math.cos(angleInRadians),\n y: centerY + radius * Math.sin(angleInRadians)\n };\n}\n","import type { Bounds } from '../types';\nimport {\n orderOfMagnitude,\n projectLength,\n roundWithPrecision,\n rho,\n EPSILON\n} from '../math';\n\n/**\n * Calculate and retrieve all the bounds for the chart and return them in one array\n * @param axisLength The length of the Axis used for\n * @param highLow An object containing a high and low property indicating the value range of the chart.\n * @param scaleMinSpace The minimum projected length a step should result in\n * @param onlyInteger\n * @return All the values to set the bounds of the chart\n */\nexport function getBounds(\n axisLength: number,\n highLow: { high: number; low: number },\n scaleMinSpace: number,\n onlyInteger = false\n) {\n const bounds: Bounds = {\n high: highLow.high,\n low: highLow.low,\n valueRange: 0,\n oom: 0,\n step: 0,\n min: 0,\n max: 0,\n range: 0,\n numberOfSteps: 0,\n values: []\n };\n\n bounds.valueRange = bounds.high - bounds.low;\n bounds.oom = orderOfMagnitude(bounds.valueRange);\n bounds.step = Math.pow(10, bounds.oom);\n bounds.min = Math.floor(bounds.low / bounds.step) * bounds.step;\n bounds.max = Math.ceil(bounds.high / bounds.step) * bounds.step;\n bounds.range = bounds.max - bounds.min;\n bounds.numberOfSteps = Math.round(bounds.range / bounds.step);\n\n // Optimize scale step by checking if subdivision is possible based on horizontalGridMinSpace\n // If we are already below the scaleMinSpace value we will scale up\n const length = projectLength(axisLength, bounds.step, bounds);\n const scaleUp = length < scaleMinSpace;\n const smallestFactor = onlyInteger ? rho(bounds.range) : 0;\n\n // First check if we should only use integer steps and if step 1 is still larger than scaleMinSpace so we can use 1\n if (onlyInteger && projectLength(axisLength, 1, bounds) >= scaleMinSpace) {\n bounds.step = 1;\n } else if (\n onlyInteger &&\n smallestFactor < bounds.step &&\n projectLength(axisLength, smallestFactor, bounds) >= scaleMinSpace\n ) {\n // If step 1 was too small, we can try the smallest factor of range\n // If the smallest factor is smaller than the current bounds.step and the projected length of smallest factor\n // is larger than the scaleMinSpace we should go for it.\n bounds.step = smallestFactor;\n } else {\n // Trying to divide or multiply by 2 and find the best step value\n let optimizationCounter = 0;\n for (;;) {\n if (\n scaleUp &&\n projectLength(axisLength, bounds.step, bounds) <= scaleMinSpace\n ) {\n bounds.step *= 2;\n } else if (\n !scaleUp &&\n projectLength(axisLength, bounds.step / 2, bounds) >= scaleMinSpace\n ) {\n bounds.step /= 2;\n if (onlyInteger && bounds.step % 1 !== 0) {\n bounds.step *= 2;\n break;\n }\n } else {\n break;\n }\n\n if (optimizationCounter++ > 1000) {\n throw new Error(\n 'Exceeded maximum number of iterations while optimizing scale step!'\n );\n }\n }\n }\n\n bounds.step = Math.max(bounds.step, EPSILON);\n function safeIncrement(value: number, increment: number) {\n // If increment is too small use *= (1+EPSILON) as a simple nextafter\n if (value === (value += increment)) {\n value *= 1 + (increment > 0 ? EPSILON : -EPSILON);\n }\n return value;\n }\n\n // Narrow min and max based on new step\n let newMin = bounds.min;\n let newMax = bounds.max;\n while (newMin + bounds.step <= bounds.low) {\n newMin = safeIncrement(newMin, bounds.step);\n }\n while (newMax - bounds.step >= bounds.high) {\n newMax = safeIncrement(newMax, -bounds.step);\n }\n bounds.min = newMin;\n bounds.max = newMax;\n bounds.range = bounds.max - bounds.min;\n\n const values: number[] = [];\n for (let i = bounds.min; i <= bounds.max; i = safeIncrement(i, bounds.step)) {\n const value = roundWithPrecision(i);\n if (value !== values[values.length - 1]) {\n values.push(value);\n }\n }\n bounds.values = values;\n\n return bounds;\n}\n","/**\n * Merges the sources into `target`, deeply, and returns `target`. Plain\n * objects merge key by key into an object already there, and replace any\n * other value (an object over a number gives a copy of the object); arrays,\n * from any realm, and other values replace what's there.\n * Keys of the target's prototype are skipped, against prototype pollution.\n * @param target The object the sources are merged into (changed in place).\n * @returns `target`, with the sources' properties.\n */\nexport function extend<T>(target: T): T;\nexport function extend<T, A>(target: T, a: A): T & A;\nexport function extend<T, A, B>(target: T, a: A, b: B): T & A & B;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function extend(target: any = {}, ...sources: any[]) {\n for (let i = 0; i < sources.length; i++) {\n const source = sources[i];\n const targetProto = Object.getPrototypeOf(target);\n for (const prop in source) {\n if (targetProto !== null && prop in targetProto) {\n continue; // prevent prototype pollution\n }\n const sourceProp = source[prop];\n if (\n typeof sourceProp === 'object' &&\n sourceProp !== null &&\n !Array.isArray(sourceProp)\n ) {\n const targetProp = target[prop];\n target[prop] = extend(\n typeof targetProp === 'object' && targetProp !== null\n ? targetProp\n : {},\n sourceProp\n );\n } else {\n target[prop] = sourceProp;\n }\n }\n }\n\n return target;\n}\n","/**\n * Helps to simplify functional style code\n * @param n This exact value will be returned by the noop function\n * @return The same value that was provided to the n parameter\n */\nexport const noop = <T>(n: T) => n;\n\n/**\n * Functional style helper to produce array with given length initialized with undefined values\n */\nexport function times(length: number): undefined[];\nexport function times<T = unknown>(\n length: number,\n filler: (index: number) => T\n): T[];\nexport function times<T = unknown>(\n length: number,\n filler?: (index: number) => T\n) {\n return Array.from({ length }, filler ? (_, i) => filler(i) : () => void 0);\n}\n\n/**\n * Sum helper to be used in reduce functions\n */\nexport const sum = (previous: number, current: number) =>\n previous + (current ? current : 0);\n\n/**\n * Map for multi dimensional arrays where their nested arrays will be mapped in serial. The output array will have the length of the largest nested array. The callback function is called with variable arguments where each argument is the nested array value (or undefined if there are no more values).\n *\n * For example:\n * @example\n * ```ts\n * const data = [[1, 2], [3], []];\n * serialMap(data, cb);\n *\n * // where cb will be called 2 times\n * // 1. call arguments: (1, 3, undefined)\n * // 2. call arguments: (2, undefined, undefined)\n * ```\n */\nexport const serialMap = <T, K>(array: T[][], callback: (...args: T[]) => K) =>\n times(Math.max(...array.map(element => element.length)), index =>\n callback(...array.map(element => element[index]))\n );\n","import type { FilterByKey } from './types';\n\n/**\n * This function safely checks if an objects has an owned property.\n * @param target The object where to check for a property\n * @param property The property name\n * @returns Returns true if the object owns the specified property\n */\nexport function safeHasProperty<T, K extends string>(\n target: T,\n property: K\n): target is FilterByKey<T, K>;\nexport function safeHasProperty(target: unknown, property: string) {\n return (\n target !== null &&\n typeof target === 'object' &&\n Reflect.has(target, property)\n );\n}\n\n/**\n * Checks if a value can be safely coerced to a number. This includes all values except null which result in finite numbers when coerced. This excludes NaN, since it's not finite.\n */\nexport function isNumeric(value: number): true;\nexport function isNumeric(value: unknown): boolean;\nexport function isNumeric(value: unknown) {\n return value !== null && isFinite(value as number);\n}\n\n/**\n * Returns true on all falsey values except the numeric value 0.\n */\nexport function isFalseyButZero(\n value: unknown\n): value is undefined | null | false | '' {\n return !value && value !== 0;\n}\n\n/**\n * Returns a number if the passed parameter is a valid number or the function will return undefined. On all other values than a valid number, this function will return undefined.\n */\nexport function getNumberOrUndefined(value: number): number;\nexport function getNumberOrUndefined(value: unknown): number | undefined;\nexport function getNumberOrUndefined(value: unknown) {\n return isNumeric(value) ? Number(value) : undefined;\n}\n\n/**\n * Checks if value is array of arrays or not.\n */\nexport function isArrayOfArrays(data: unknown): data is unknown[][] {\n if (!Array.isArray(data)) {\n return false;\n }\n\n return data.every(Array.isArray);\n}\n\n/**\n * Loop over array.\n */\nexport function each<T>(\n list: T[],\n callback: (item: T, index: number, itemIndex: number) => void,\n reverse = false\n) {\n let index = 0;\n\n list[reverse ? 'reduceRight' : 'reduce']<void>(\n (_, item, itemIndex) => callback(item, index++, itemIndex),\n void 0\n );\n}\n","import type {\n Multi,\n AxisName,\n FlatSeriesValue,\n Series,\n SeriesObject\n} from '../types';\nimport { safeHasProperty, getNumberOrUndefined } from '../../utils';\n\n/**\n * Get meta data of a specific value in a series.\n */\nexport function getMetaData(\n seriesData: FlatSeriesValue | Series | SeriesObject,\n index: number\n) {\n const value = Array.isArray(seriesData)\n ? seriesData[index]\n : safeHasProperty(seriesData, 'data')\n ? seriesData.data[index]\n : null;\n return safeHasProperty(value, 'meta') ? value.meta : undefined;\n}\n\n/**\n * Checks if a value is considered a hole in the data series.\n * @returns True if the value is considered a data hole\n */\nexport function isDataHoleValue(value: unknown): value is null | undefined;\nexport function isDataHoleValue(value: unknown) {\n return (\n value === null ||\n value === undefined ||\n (typeof value === 'number' && isNaN(value))\n );\n}\n\n/**\n * Checks if value is array of series objects.\n */\nexport function isArrayOfSeries(\n value: unknown\n): value is (Series | SeriesObject)[] {\n return (\n Array.isArray(value) &&\n value.every(_ => Array.isArray(_) || safeHasProperty(_, 'data'))\n );\n}\n\n/**\n * Checks if provided value object is multi value (contains x or y properties)\n */\nexport function isMultiValue(value: unknown): value is Multi {\n return (\n typeof value === 'object' &&\n value !== null &&\n (Reflect.has(value, 'x') || Reflect.has(value, 'y'))\n );\n}\n\n/**\n * Gets a value from a dimension `value.x` or `value.y` while returning value directly if it's a valid numeric value. If the value is not numeric and it's falsey this function will return `defaultValue`.\n */\nexport function getMultiValue(\n value: Multi | number | unknown,\n dimension: AxisName = 'y'\n) {\n if (isMultiValue(value) && safeHasProperty(value, dimension)) {\n return getNumberOrUndefined(value[dimension]);\n } else {\n return getNumberOrUndefined(value);\n }\n}\n","/**\n * Repairs a value range that's empty because high is at or below low, from\n * flat data or a misconfigured `high`/`low`: sets the bound on the other\n * side of zero to 0, or gives `0` to `1` when there are no values. Chart\n * code that overrides a bound after `getHighLow` calls it again.\n *\n * @param highLow The range to check.\n * @returns The range, or the repaired one.\n */\nexport function nonEmptyRange(highLow: {\n readonly high: number;\n readonly low: number;\n}): { high: number; low: number } {\n const { high, low } = highLow;\n if (high > low) {\n return { high, low };\n }\n if (low === 0) {\n // Both are 0.\n return { high: 1, low };\n }\n if (low < 0) {\n // The same negative value for both.\n return { high: 0, low };\n }\n if (high > 0) {\n // The same positive value for both.\n return { high, low: 0 };\n }\n // No values: high and low are still -Number.MAX_VALUE and Number.MAX_VALUE.\n return { high: 1, low: 0 };\n}\n","import type {\n Options,\n AxisName,\n NormalizedSeries,\n NormalizedSeriesValue\n} from '../types';\nimport { safeHasProperty } from '../../utils';\nimport { isDataHoleValue } from './data';\nimport { nonEmptyRange } from './range';\n\n/**\n * Get highest and lowest value of data array. This Array contains the data that will be visualized in the chart.\n * @param data The array that contains the data to be visualized in the chart\n * @param options The Object that contains the chart options\n * @param dimension Axis dimension 'x' or 'y' used to access the correct value and high / low configuration\n * @param extent A range to include beyond the data, such as the sums of stacked bars\n * @return An object that contains the highest and lowest value that will be visualized on the chart.\n */\nexport function getHighLow(\n data: NormalizedSeries[],\n options: Options,\n dimension?: AxisName,\n extent?: { readonly low: number; readonly high: number }\n) {\n // TODO: Remove workaround for deprecated global high / low config. Axis high / low configuration is preferred\n options = {\n ...options,\n ...(dimension ? (dimension === 'x' ? options.axisX : options.axisY) : {})\n };\n\n const highLow = {\n high: options.high === undefined ? -Number.MAX_VALUE : +options.high,\n low: options.low === undefined ? Number.MAX_VALUE : +options.low\n };\n const findHigh = options.high === undefined;\n const findLow = options.low === undefined;\n\n // Function to recursively walk through arrays and find highest and lowest number\n function recursiveHighLow(\n sourceData: NormalizedSeriesValue | NormalizedSeries | NormalizedSeries[]\n ) {\n if (isDataHoleValue(sourceData)) {\n return;\n } else if (Array.isArray(sourceData)) {\n for (let i = 0; i < sourceData.length; i++) {\n recursiveHighLow(sourceData[i]);\n }\n } else {\n const value = Number(\n dimension && safeHasProperty(sourceData, dimension)\n ? sourceData[dimension]\n : sourceData\n );\n\n if (findHigh && value > highLow.high) {\n highLow.high = value;\n }\n\n if (findLow && value < highLow.low) {\n highLow.low = value;\n }\n }\n }\n\n // Start to find highest and lowest number recursively\n if (findHigh || findLow) {\n recursiveHighLow(data);\n }\n\n // A range the chart needs beyond the values, e.g. the sums of stacked\n // bars, widens what isn't set explicitly.\n if (extent) {\n if (findHigh) {\n highLow.high = Math.max(extent.high, highLow.high);\n }\n if (findLow) {\n highLow.low = Math.min(extent.low, highLow.low);\n }\n }\n\n // The reference value (e.g. 0 for bars) widens the range to include it,\n // for bipolar scales. An explicit high or low wins over it (#1476).\n if (options.referenceValue || options.referenceValue === 0) {\n if (findHigh) {\n highLow.high = Math.max(options.referenceValue, highLow.high);\n }\n if (findLow) {\n highLow.low = Math.min(options.referenceValue, highLow.low);\n }\n }\n\n // Flat data (only the same value) or a misconfigured high or low leave\n // the range empty.\n return nonEmptyRange(highLow);\n}\n","import type {\n Data,\n NormalizedData,\n Multi,\n AxisName,\n NormalizedMulti,\n Series,\n FlatSeries,\n NormalizedSeries,\n NormalizedFlatSeries,\n SeriesObject,\n SeriesPrimitiveValue\n} from '../types';\nimport {\n isArrayOfArrays,\n times,\n safeHasProperty,\n getNumberOrUndefined\n} from '../../utils';\nimport { isDataHoleValue, isArrayOfSeries } from './data';\n\n/**\n * Ensures that the data object passed as second argument to the charts is present and correctly initialized.\n * @param data The data object that is passed as second argument to the charts\n * @return The normalized data object\n */\nexport function normalizeData(\n data: Data<FlatSeries>,\n reverse?: boolean,\n multi?: false\n): NormalizedData<NormalizedFlatSeries>;\nexport function normalizeData(\n data: Data<(Series | SeriesObject)[]>,\n reverse: boolean | undefined,\n multi: true | AxisName\n): NormalizedData<NormalizedSeries[]>;\nexport function normalizeData(\n data: Data<FlatSeries | (Series | SeriesObject)[]>,\n reverse: boolean | undefined,\n multi: boolean | AxisName,\n distributed: true\n): NormalizedData<NormalizedSeries[]>;\nexport function normalizeData(\n data: Data<FlatSeries | (Series | SeriesObject)[]>,\n reverse?: boolean,\n multi?: boolean | AxisName\n): NormalizedData<NormalizedFlatSeries | NormalizedSeries[]>;\nexport function normalizeData(\n data: Data,\n reverse = false,\n multi?: boolean | AxisName,\n distributed?: boolean\n) {\n let labelCount: number;\n const normalized: NormalizedData = {\n labels: (data.labels || []).slice(),\n series: normalizeSeries(data.series, multi, distributed)\n };\n const inputLabelCount = normalized.labels.length;\n\n // If all elements of the normalized data array are arrays we're dealing with\n // multi series data and we need to find the largest series if they are un-even\n if (isArrayOfArrays(normalized.series)) {\n // Getting the series with the the most elements\n labelCount = Math.max(\n inputLabelCount,\n ...normalized.series.map(series => series.length)\n );\n\n normalized.series.forEach(series => {\n series.push(...times(Math.max(0, labelCount - series.length)));\n });\n } else {\n // We're dealing with Pie data so we just take the normalized array length\n labelCount = normalized.series.length;\n }\n\n // Padding the labels to labelCount with empty strings\n normalized.labels.push(\n ...times(Math.max(0, labelCount - inputLabelCount), () => '')\n );\n\n if (reverse) {\n reverseData(normalized);\n }\n\n return normalized;\n}\n\n/**\n * Reverses the series, labels and series data arrays.\n */\nfunction reverseData(data: Data) {\n data.labels?.reverse();\n data.series.reverse();\n for (const series of data.series) {\n if (safeHasProperty(series, 'data')) {\n series.data.reverse();\n } else if (Array.isArray(series)) {\n series.reverse();\n }\n }\n}\n\nfunction normalizeMulti(\n value: number | string | boolean | Date | Multi,\n multi?: boolean | AxisName\n) {\n // We need to prepare multi value output (x and y data)\n let x: number | undefined;\n let y: number | undefined;\n\n // Single series value arrays are assumed to specify the Y-Axis value\n // For example: [1, 2] => [{x: undefined, y: 1}, {x: undefined, y: 2}]\n // If multi is a string then it's assumed that it specified which dimension should be filled as default\n if (typeof value !== 'object') {\n const num = getNumberOrUndefined(value);\n\n if (multi === 'x') {\n x = num;\n } else {\n y = num;\n }\n } else {\n if (safeHasProperty(value, 'x')) {\n x = getNumberOrUndefined(value.x);\n }\n\n if (safeHasProperty(value, 'y')) {\n y = getNumberOrUndefined(value.y);\n }\n }\n\n if (x === undefined && y === undefined) {\n return undefined;\n }\n\n return { x, y } as NormalizedMulti;\n}\n\nfunction normalizePrimitive(\n value: SeriesPrimitiveValue,\n multi?: boolean | AxisName\n) {\n if (isDataHoleValue(value)) {\n // We're dealing with a hole in the data and therefore need to return undefined\n // We're also returning undefined for multi value output\n return undefined;\n }\n\n if (multi) {\n return normalizeMulti(value, multi);\n }\n\n return getNumberOrUndefined(value);\n}\n\nfunction normalizeSingleSeries(\n series: Series | SeriesObject,\n multi?: boolean | AxisName\n): NormalizedSeries {\n if (!Array.isArray(series)) {\n // We are dealing with series object notation so we need to recurse on data property\n return normalizeSingleSeries(series.data, multi);\n }\n\n return series.map(value => {\n if (safeHasProperty(value, 'value')) {\n // We are dealing with value object notation so we need to recurse on value property\n return normalizePrimitive(value.value, multi);\n }\n\n return normalizePrimitive(value, multi);\n });\n}\n\n/**\n * Convert data series into plain array\n * @param series The series object that contains the data to be visualized in the chart\n * @param multi Create a multi dimensional array from a series data array where a value object with `x` and `y` values will be created.\n * @return A plain array that contains the data to be visualized in the chart\n */\nfunction normalizeSeries(\n series: FlatSeries,\n multi?: false,\n distributed?: false\n): NormalizedFlatSeries;\nfunction normalizeSeries(\n series: (Series | SeriesObject)[],\n multi: true | AxisName,\n distributed?: false\n): NormalizedSeries[];\nfunction normalizeSeries(\n series: FlatSeries | (Series | SeriesObject)[],\n multi: boolean | undefined | AxisName,\n distributed: true\n): NormalizedSeries[];\nfunction normalizeSeries(\n series: FlatSeries | (Series | SeriesObject)[],\n multi?: boolean | undefined | AxisName,\n distributed?: boolean\n): NormalizedFlatSeries | NormalizedSeries[];\nfunction normalizeSeries(\n series: FlatSeries | (Series | SeriesObject)[],\n multi?: boolean | undefined | AxisName,\n distributed?: boolean\n) {\n if (isArrayOfSeries(series)) {\n return series.map(_ => normalizeSingleSeries(_, multi));\n }\n\n const normalizedSeries = normalizeSingleSeries(series, multi);\n\n if (distributed) {\n return normalizedSeries.map(value => [value]);\n }\n\n return normalizedSeries;\n}\n","import type { Segment, SegmentData } from '../types';\nimport { getMultiValue } from './data';\n\n/**\n * Splits a list of coordinates and associated values into segments. Each returned segment contains a pathCoordinates\n * valueData property describing the segment.\n *\n * With the default options, segments consist of contiguous sets of points that do not have an undefined value. Any\n * points with undefined values are discarded.\n *\n * **Options**\n * The following options are used to determine how segments are formed\n * ```javascript\n * var options = {\n * // If fillHoles is true, undefined values are simply discarded without creating a new segment. Assuming other options are default, this returns single segment.\n * fillHoles: false,\n * // If increasingX is true, the coordinates in all segments have strictly increasing x-values.\n * increasingX: false\n * };\n * ```\n *\n * @param pathCoordinates List of point coordinates to be split in the form [x1, y1, x2, y2 ... xn, yn]\n * @param valueData List of associated point values in the form [v1, v2 .. vn]\n * @param options Options set by user\n * @return List of segments, each containing a pathCoordinates and valueData property.\n */\nexport function splitIntoSegments(\n pathCoordinates: number[],\n valueData: SegmentData[],\n options?: {\n increasingX?: boolean;\n fillHoles?: boolean;\n }\n) {\n const finalOptions = {\n increasingX: false,\n fillHoles: false,\n ...options\n };\n\n const segments: Segment[] = [];\n let hole = true;\n\n for (let i = 0; i < pathCoordinates.length; i += 2) {\n // If this value is a \"hole\" we set the hole flag\n if (getMultiValue(valueData[i / 2].value) === undefined) {\n // if(valueData[i / 2].value === undefined) {\n if (!finalOptions.fillHoles) {\n hole = true;\n }\n } else {\n if (\n finalOptions.increasingX &&\n i >= 2 &&\n pathCoordinates[i] <= pathCoordinates[i - 2]\n ) {\n // X is not increasing, so we need to make sure we start a new segment\n hole = true;\n }\n\n // If it's a valid value we need to check if we're coming out of a hole and create a new empty segment\n if (hole) {\n segments.push({\n pathCoordinates: [],\n valueData: []\n });\n // As we have a valid value now, we are not in a \"hole\" anymore\n hole = false;\n }\n\n // Add to the segment pathCoordinates and valueData\n segments[segments.length - 1].pathCoordinates.push(\n pathCoordinates[i],\n pathCoordinates[i + 1]\n );\n segments[segments.length - 1].valueData.push(valueData[i / 2]);\n }\n }\n\n return segments;\n}\n","import { escapingMap } from '../constants';\n\n/**\n * This function serializes arbitrary data to a string. In case of data that can't be easily converted to a string, this function will create a wrapper object and serialize the data using JSON.stringify. The outcoming string will always be escaped using Chartist.escapingMap.\n * If called with null or undefined the function will return immediately with null or undefined.\n */\nexport function serialize(data: number | string | object): string;\nexport function serialize(\n data: number | string | object | null | undefined | unknown\n): string | null | undefined;\nexport function serialize(\n data: number | string | object | null | undefined | unknown\n) {\n let serialized = '';\n\n if (data === null || data === undefined) {\n return data;\n } else if (typeof data === 'number') {\n serialized = '' + data;\n } else if (typeof data === 'object') {\n serialized = JSON.stringify({ data: data });\n } else {\n serialized = String(data);\n }\n\n return Object.keys(escapingMap).reduce(\n (result, key) => result.replaceAll(key, escapingMap[key]),\n serialized\n );\n}\n\n/**\n * This function de-serializes a string previously serialized with Chartist.serialize. The string will always be unescaped using Chartist.escapingMap before it's returned. Based on the input value the return type can be Number, String or Object. JSON.parse is used with try / catch to see if the unescaped string can be parsed into an Object and this Object will be returned on success.\n */\nexport function deserialize<T extends object | number | string = object>(\n data: string\n): T;\nexport function deserialize<T extends object | number | string = object>(\n data: string | null | undefined\n): T | null | undefined;\nexport function deserialize(data: unknown) {\n if (typeof data !== 'string') {\n return data;\n }\n\n if (data === 'NaN') {\n return NaN;\n }\n\n data = Object.keys(escapingMap).reduce(\n (result, key) => result.replaceAll(escapingMap[key], key),\n data\n );\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let parsedData: any = data;\n\n if (typeof data === 'string') {\n try {\n parsedData = JSON.parse(data);\n parsedData = parsedData.data !== undefined ? parsedData.data : parsedData;\n } catch (e) {\n /* Ingore */\n }\n }\n\n return parsedData;\n}\n","import { Svg } from './Svg';\n\ntype SvgMethods = Exclude<\n keyof Svg,\n | 'constructor'\n | 'parent'\n | 'querySelector'\n | 'querySelectorAll'\n | 'replace'\n | 'append'\n | 'classes'\n | 'height'\n | 'width'\n>;\n\ntype SvgListMethods = {\n [method in SvgMethods]: (...args: Parameters<Svg[method]>) => SvgList;\n};\n\n/**\n * A list of {@link Svg} wrappers that calls an `Svg` method on all of them\n * at once, such as `addClass` or `animate`. Each method returns the list,\n * for chaining. {@link Svg.querySelectorAll} returns one.\n */\nexport class SvgList implements SvgListMethods {\n private svgElements: Svg[] = [];\n\n /**\n * Wraps each element of the list in an {@link Svg}.\n * @param nodeList An Array of SVG DOM nodes or a SVG DOM NodeList (as returned by document.querySelectorAll)\n */\n constructor(nodeList: ArrayLike<Element>) {\n for (let i = 0; i < nodeList.length; i++) {\n this.svgElements.push(new Svg(nodeList[i]));\n }\n }\n\n private call<T extends SvgMethods>(method: T, args: Parameters<Svg[T]>) {\n this.svgElements.forEach(element =>\n Reflect.apply(element[method], element, args)\n );\n return this;\n }\n\n /** Sets attributes on every element, as {@link Svg.attr} does. */\n attr(...args: Parameters<Svg['attr']>) {\n return this.call('attr', args);\n }\n\n /** Adds a child element to every element, as {@link Svg.elem} does. */\n elem(...args: Parameters<Svg['elem']>) {\n return this.call('elem', args);\n }\n\n /** Calls {@link Svg.root} on every element; returns the list, not the roots. */\n root(...args: Parameters<Svg['root']>) {\n return this.call('root', args);\n }\n\n /** Calls {@link Svg.getNode} on every element; returns the list, not the nodes. */\n getNode(...args: Parameters<Svg['getNode']>) {\n return this.call('getNode', args);\n }\n\n /** Adds a `foreignObject` with the content to every element, as {@link Svg.foreignObject} does. */\n foreignObject(...args: Parameters<Svg['foreignObject']>) {\n return this.call('foreignObject', args);\n }\n\n /** Adds a text node to every element, as {@link Svg.text} does. */\n text(...args: Parameters<Svg['text']>) {\n return this.call('text', args);\n }\n\n /** Removes the children of every element, as {@link Svg.empty} does. */\n empty(...args: Parameters<Svg['empty']>) {\n return this.call('empty', args);\n }\n\n /** Removes every element from its parent, as {@link Svg.remove} does. */\n remove(...args: Parameters<Svg['remove']>) {\n return this.call('remove', args);\n }\n\n /** Adds classes to every element, as {@link Svg.addClass} does. */\n addClass(...args: Parameters<Svg['addClass']>) {\n return this.call('addClass', args);\n }\n\n /** Removes classes from every element, as {@link Svg.removeClass} does. */\n removeClass(...args: Parameters<Svg['removeClass']>) {\n return this.call('removeClass', args);\n }\n\n /** Removes all classes from every element, as {@link Svg.removeAllClasses} does. */\n removeAllClasses(...args: Parameters<Svg['removeAllClasses']>) {\n return this.call('removeAllClasses', args);\n }\n\n /** Animates attributes of every element with SMIL, as {@link Svg.animate} does. */\n animate(...args: Parameters<Svg['animate']>) {\n return this.call('animate', args);\n }\n}\n","import type { EventEmitter } from '../event';\nimport { ensureUnit, quantity } from '../core/lang';\nimport type { Attributes, AnimationDefinition, AnimationEvent } from './types';\nimport type { Svg } from './Svg';\n\n/**\n * The named easing curves for {@link Svg.animate}, from `easeInSine` to\n * `easeInOutBack`: each the four numbers of a cubic Bézier curve. Name one\n * as an animation's `easing`, or pass four numbers of your own, such as\n * `easing: [0.25, 0.1, 0.25, 1]`.\n *\n * @example\n * ```ts\n * import { lineChart, findAll, Svg, type ChartPlugin } from 'chartist';\n *\n * // Points drop in from the top and bounce a little at the end.\n * const dropIn: ChartPlugin = {\n * name: 'drop-in',\n * install(chart) {\n * chart.on('mount', ({ scene, elementOf }) => {\n * for (const point of findAll(scene, { role: 'point' })) {\n * const element = elementOf(point);\n * const { y } = point.ctx;\n * if (element) {\n * new Svg(element).animate({\n * y1: { dur: 600, from: 0, to: y, easing: 'easeOutBack' },\n * y2: { dur: 600, from: 0, to: y, easing: 'easeOutBack' }\n * });\n * }\n * }\n * });\n * }\n * };\n *\n * lineChart('#chart', { series: [[5, 2, 4, 3]] }, { plugins: [dropIn] });\n * ```\n */\nexport const easings = {\n easeInSine: [0.47, 0, 0.745, 0.715],\n easeOutSine: [0.39, 0.575, 0.565, 1],\n easeInOutSine: [0.445, 0.05, 0.55, 0.95],\n easeInQuad: [0.55, 0.085, 0.68, 0.53],\n easeOutQuad: [0.25, 0.46, 0.45, 0.94],\n easeInOutQuad: [0.455, 0.03, 0.515, 0.955],\n easeInCubic: [0.55, 0.055, 0.675, 0.19],\n easeOutCubic: [0.215, 0.61, 0.355, 1],\n easeInOutCubic: [0.645, 0.045, 0.355, 1],\n easeInQuart: [0.895, 0.03, 0.685, 0.22],\n easeOutQuart: [0.165, 0.84, 0.44, 1],\n easeInOutQuart: [0.77, 0, 0.175, 1],\n easeInQuint: [0.755, 0.05, 0.855, 0.06],\n easeOutQuint: [0.23, 1, 0.32, 1],\n easeInOutQuint: [0.86, 0, 0.07, 1],\n easeInExpo: [0.95, 0.05, 0.795, 0.035],\n easeOutExpo: [0.19, 1, 0.22, 1],\n easeInOutExpo: [1, 0, 0, 1],\n easeInCirc: [0.6, 0.04, 0.98, 0.335],\n easeOutCirc: [0.075, 0.82, 0.165, 1],\n easeInOutCirc: [0.785, 0.135, 0.15, 0.86],\n easeInBack: [0.6, -0.28, 0.735, 0.045],\n easeOutBack: [0.175, 0.885, 0.32, 1.275],\n easeInOutBack: [0.68, -0.55, 0.265, 1.55]\n};\n\n/**\n * The property of an element that holds the emitter its descendants'\n * animations report to when `animate()` gets none. The compat plugin\n * sets it on a chart's `svg`. A global symbol, so separate builds of the\n * core and `chartist/compat` share it.\n */\nexport const ANIMATION_EMITTER = Symbol.for('chartist.animationEmitter');\n\n/** The emitter set on the element or its closest ancestor that has one. */\nexport function animationEmitterOf(node: Element): EventEmitter | undefined {\n for (\n let current: Element | null = node;\n current;\n current = current.parentElement\n ) {\n const emitter = (current as { [ANIMATION_EMITTER]?: EventEmitter })[\n ANIMATION_EMITTER\n ];\n if (emitter) {\n return emitter;\n }\n }\n return undefined;\n}\n\nexport function createAnimation(\n element: Svg,\n attribute: string,\n animationDefinition: AnimationDefinition,\n createGuided = false,\n eventEmitter?: EventEmitter\n) {\n const { easing, ...def } = animationDefinition;\n const attributeProperties: Attributes = {};\n let animationEasing;\n let timeout;\n\n // Check if an easing is specified in the definition object and delete it from the object as it will not\n // be part of the animate element attributes.\n if (easing) {\n // If already an easing Bézier curve array we take it or we lookup a easing array in the Easing object\n animationEasing = Array.isArray(easing) ? easing : easings[easing];\n }\n\n // If numeric dur or begin was provided we assume milli seconds\n def.begin = ensureUnit(def.begin, 'ms');\n def.dur = ensureUnit(def.dur, 'ms');\n\n if (animationEasing) {\n def.calcMode = 'spline';\n def.keySplines = animationEasing.join(' ');\n def.keyTimes = '0;1';\n }\n\n // Adding \"fill: freeze\" if we are in guided mode and set initial attribute values\n if (createGuided) {\n def.fill = 'freeze';\n // Animated property on our element should already be set to the animation from value in guided mode\n attributeProperties[attribute] = def.from;\n element.attr(attributeProperties);\n\n // In guided mode we also set begin to indefinite so we can trigger the start manually and put the begin\n // which needs to be in ms aside\n timeout = quantity(def.begin || 0).value;\n def.begin = 'indefinite';\n }\n\n const animate = element.elem('animate', {\n attributeName: attribute,\n ...def\n });\n\n if (createGuided) {\n // If guided we take the value that was put aside in timeout and trigger the animation manually with a timeout\n setTimeout(() => {\n // If beginElement fails we set the animated attribute to the end position and remove the animate element\n // This happens if the SMIL ElementTimeControl interface is not supported or any other problems occurred in\n // the browser. (Currently FF 34 does not support animate elements in foreignObjects)\n try {\n // @ts-expect-error Try legacy API.\n animate._node.beginElement();\n } catch (err) {\n // Set animated attribute to current animated value\n attributeProperties[attribute] = def.to;\n element.attr(attributeProperties);\n // Remove the animate element as it's no longer required\n animate.remove();\n }\n }, timeout);\n }\n\n const animateNode = animate.getNode();\n\n if (eventEmitter) {\n animateNode.addEventListener('beginEvent', () =>\n eventEmitter.emit<AnimationEvent>('animationBegin', {\n element: element,\n animate: animateNode,\n params: animationDefinition\n })\n );\n }\n\n animateNode.addEventListener('endEvent', () => {\n if (eventEmitter) {\n eventEmitter.emit<AnimationEvent>('animationEnd', {\n element: element,\n animate: animateNode,\n params: animationDefinition\n });\n }\n\n if (createGuided) {\n // Set animated attribute to current animated value\n attributeProperties[attribute] = def.to;\n element.attr(attributeProperties);\n // Remove the animate element as it's no longer required\n animate.remove();\n }\n });\n}\n","import type { EventEmitter } from '../event';\nimport { namespaces } from '../core/constants';\nimport type { Attributes, AnimationDefinition } from './types';\nimport { SvgList } from './SvgList';\nimport { animationEmitterOf, createAnimation, easings } from './animation';\n\n/**\n * Wraps an SVG element for chaining: set attributes and classes, add child\n * elements, and animate attributes with SMIL. Wrap an element of a rendered\n * chart (from `elementOf` in a `mount` listener), or create a new one by\n * name.\n *\n * @example\n * ```ts\n * import { barChart, findAll, Svg, type ChartPlugin } from 'chartist';\n *\n * // Bars grow from the axis, animated from a plugin's mount listener.\n * const growBars: ChartPlugin = {\n * name: 'grow-bars',\n * install(chart) {\n * chart.on('mount', ({ scene, elementOf }) => {\n * for (const bar of findAll(scene, { role: 'bar' })) {\n * const element = elementOf(bar);\n * if (element) {\n * new Svg(element).animate({\n * y2: {\n * begin: bar.ctx.valueIndex * 120,\n * dur: 700,\n * from: bar.attrs.y1,\n * to: bar.attrs.y2,\n * easing: 'easeOutQuint'\n * }\n * });\n * }\n * }\n * });\n * }\n * };\n *\n * barChart('#chart', { series: [[5, 4, 3, 7]] }, { plugins: [growBars] });\n * ```\n */\nexport class Svg {\n /**\n * The easing curves for {@link Svg.animate}, as 1.x had them on the class.\n * @deprecated Use the {@link easings} export.\n */\n static readonly Easing = easings;\n\n private _node: Element;\n\n /**\n * Creates an SVG element and wraps it, or wraps an existing element.\n * @param name The name of the SVG element to create or an SVG dom element which should be wrapped into Svg\n * @param attributes An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added.\n * @param className This class or class list will be added to the SVG element\n * @param parent The parent SVG wrapper object where this newly created wrapper and it's element will be attached to as child\n * @param insertFirst If this param is set to true in conjunction with a parent element the newly created element will be added as first child element in the parent element\n */\n constructor(\n name: string | Element,\n attributes?: Attributes,\n className?: string,\n parent?: Svg,\n insertFirst = false\n ) {\n // An element is wrapped. Tested by kind, not with `instanceof Element`,\n // which fails for elements of another window and without DOM globals.\n if (typeof name !== 'string') {\n this._node = name;\n } else {\n // In the parent's document, so elements can be added to an iframe's\n // or a jsdom document's chart (see #1424). Without a parent, in the\n // global document.\n this._node = (parent?._node.ownerDocument ?? document).createElementNS(\n namespaces.svg,\n name\n );\n\n // If this is an SVG element created then custom namespace\n if (name === 'svg') {\n this.attr({\n 'xmlns:ct': namespaces.ct\n });\n }\n }\n\n if (attributes) {\n this.attr(attributes);\n }\n\n if (className) {\n this.addClass(className);\n }\n\n if (parent) {\n if (insertFirst && parent._node.firstChild) {\n parent._node.insertBefore(this._node, parent._node.firstChild);\n } else {\n parent._node.appendChild(this._node);\n }\n }\n }\n\n /**\n * Set attributes on the current SVG element of the wrapper you're currently working on.\n * @param attributes An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added. If this parameter is a String then the function is used as a getter and will return the attribute value.\n * @param ns If specified, the attribute will be obtained using getAttributeNs. In order to write namepsaced attributes you can use the namespace:attribute notation within the attributes object.\n * @return The current wrapper object will be returned so it can be used for chaining or the attribute value if used as getter function.\n */\n attr(attributes: string, ns?: string): string | null;\n attr(attributes: Attributes): this;\n attr(attributes: string | Attributes, ns?: string) {\n if (typeof attributes === 'string') {\n if (ns) {\n return this._node.getAttributeNS(ns, attributes);\n } else {\n return this._node.getAttribute(attributes);\n }\n }\n\n Object.keys(attributes).forEach(key => {\n // If the attribute value is undefined we can skip this one\n if (attributes[key] === undefined) {\n return;\n }\n\n if (key.indexOf(':') !== -1) {\n const namespacedAttribute = key.split(':');\n this._node.setAttributeNS(\n namespaces[namespacedAttribute[0]],\n key,\n String(attributes[key])\n );\n } else {\n this._node.setAttribute(key, String(attributes[key]));\n }\n });\n\n return this;\n }\n\n /**\n * Create a new SVG element whose wrapper object will be selected for further operations. This way you can also create nested groups easily.\n * @param name The name of the SVG element that should be created as child element of the currently selected element wrapper\n * @param attributes An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added.\n * @param className This class or class list will be added to the SVG element\n * @param insertFirst If this param is set to true in conjunction with a parent element the newly created element will be added as first child element in the parent element\n * @return Returns a Svg wrapper object that can be used to modify the containing SVG data\n */\n elem(\n name: string,\n attributes?: Attributes,\n className?: string,\n insertFirst = false\n ) {\n return new Svg(name, attributes, className, this, insertFirst);\n }\n\n /**\n * Wraps the element's parent.\n * @returns The parent in a new `Svg`, or `null` if there is none or it isn't an SVG element.\n */\n parent() {\n // What `instanceof SVGElement` tests, for elements of any window.\n const parent = this._node.parentNode as Element | null;\n return parent?.nodeType === 1 && parent.namespaceURI === namespaces.svg\n ? new Svg(parent)\n : null;\n }\n\n /**\n * This method returns a Svg wrapper around the root SVG element of the current tree.\n * @return The root SVG element wrapped in a Svg element\n */\n root() {\n let node = this._node;\n\n while (node.nodeName !== 'svg') {\n if (node.parentElement) {\n node = node.parentElement;\n } else {\n break;\n }\n }\n\n return new Svg(node);\n }\n\n /**\n * Find the first child SVG element of the current element that matches a CSS selector. The returned object is a Svg wrapper.\n * @param selector A CSS selector that is used to query for child SVG elements\n * @return The SVG wrapper for the element found or null if no element was found\n */\n querySelector(selector: string) {\n const foundNode = this._node.querySelector(selector);\n return foundNode ? new Svg(foundNode) : null;\n }\n\n /**\n * Finds all descendants of the element that match a CSS selector.\n * @param selector A CSS selector that is used to query for child SVG elements\n * @returns The elements found in an {@link SvgList} (empty if none match).\n */\n querySelectorAll(selector: string) {\n const foundNodes = this._node.querySelectorAll(selector);\n return new SvgList(foundNodes);\n }\n\n /**\n * Returns the underlying SVG node for the current element.\n */\n getNode<T extends Element = Element>() {\n return this._node as T;\n }\n\n /**\n * This method creates a foreignObject (see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject) that allows to embed HTML content into a SVG graphic. With the help of foreignObjects you can enable the usage of regular HTML elements inside of SVG where they are subject for SVG positioning and transformation but the Browser will use the HTML rendering capabilities for the containing DOM.\n * @param content The DOM Node, or HTML string that will be converted to a DOM Node, that is then placed into and wrapped by the foreignObject\n * @param attributes An object with properties that will be added as attributes to the foreignObject element that is created. Attributes with undefined values will not be added.\n * @param className This class or class list will be added to the SVG element\n * @param insertFirst Specifies if the foreignObject should be inserted as first child\n * @return New wrapper object that wraps the foreignObject element\n */\n foreignObject(\n content: string | Node,\n attributes?: Attributes,\n className?: string,\n insertFirst = false\n ) {\n let contentNode: Node;\n // If content is string then we convert it to DOM\n // TODO: Handle case where content is not a string nor a DOM Node\n if (typeof content === 'string') {\n const container = this._node.ownerDocument.createElement('div');\n container.innerHTML = content;\n contentNode = container.firstChild as Node;\n } else {\n contentNode = content;\n }\n\n // Creating the foreignObject without required extension attribute (as described here\n // http://www.w3.org/TR/SVG/extend.html#ForeignObjectElement)\n const fnObj = this.elem(\n 'foreignObject',\n attributes,\n className,\n insertFirst\n );\n\n // Add content to foreignObjectElement\n fnObj._node.appendChild(contentNode);\n\n return fnObj;\n }\n\n /**\n * This method adds a new text element to the current Svg wrapper.\n * @param t The text that should be added to the text element that is created\n * @return The same wrapper object that was used to add the newly created element\n */\n text(t: string) {\n this._node.appendChild(this._node.ownerDocument.createTextNode(t));\n return this;\n }\n\n /**\n * This method will clear all child nodes of the current wrapper object.\n * @return The same wrapper object that got emptied\n */\n empty() {\n while (this._node.firstChild) {\n this._node.removeChild(this._node.firstChild);\n }\n\n return this;\n }\n\n /**\n * Removes the element from its parent.\n * @returns The parent it had, wrapped in a new `Svg`, or `null` if it had\n * none or the parent isn't an SVG element.\n */\n remove() {\n const parent = this.parent();\n this._node.parentNode?.removeChild(this._node);\n return parent;\n }\n\n /**\n * This method will replace the element with a new element that can be created outside of the current DOM.\n * @param newElement The new Svg object that will be used to replace the current wrapper object\n * @return The wrapper of the new element\n */\n replace(newElement: Svg) {\n this._node.parentNode?.replaceChild(newElement._node, this._node);\n return newElement;\n }\n\n /**\n * This method will append an element to the current element as a child.\n * @param element The Svg element that should be added as a child\n * @param insertFirst Specifies if the element should be inserted as first child\n * @return The wrapper of the appended object\n */\n append(element: Svg, insertFirst = false) {\n if (insertFirst && this._node.firstChild) {\n this._node.insertBefore(element._node, this._node.firstChild);\n } else {\n this._node.appendChild(element._node);\n }\n\n return this;\n }\n\n /**\n * Returns an array of class names that are attached to the current wrapper element. This method can not be chained further.\n * @return A list of classes or an empty array if there are no classes on the current element\n */\n classes() {\n const classNames = this._node.getAttribute('class');\n\n return classNames ? classNames.trim().split(/\\s+/) : [];\n }\n\n /**\n * Adds one or a space separated list of classes to the current element and ensures the classes are only existing once.\n * @param names A white space separated list of class names\n * @return The wrapper of the current element\n */\n addClass(names: string) {\n this._node.setAttribute(\n 'class',\n this.classes()\n .concat(names.trim().split(/\\s+/))\n .filter(function (elem, pos, self) {\n return self.indexOf(elem) === pos;\n })\n .join(' ')\n );\n\n return this;\n }\n\n /**\n * Removes one or a space separated list of classes from the current element.\n * @param names A white space separated list of class names\n * @return The wrapper of the current element\n */\n removeClass(names: string) {\n const removedClasses = names.trim().split(/\\s+/);\n\n this._node.setAttribute(\n 'class',\n this.classes()\n .filter(name => removedClasses.indexOf(name) === -1)\n .join(' ')\n );\n\n return this;\n }\n\n /**\n * Removes all classes from the current element.\n * @return The wrapper of the current element\n */\n removeAllClasses() {\n this._node.setAttribute('class', '');\n return this;\n }\n\n /**\n * Get element height using `clientHeight`\n * @return The elements height in pixels\n */\n height() {\n return this._node.clientHeight;\n }\n\n /**\n * Get element width using `clientWidth`\n * @return The elements width in pixels\n */\n width() {\n return this._node.clientWidth;\n }\n\n /**\n * Animates attributes of the element with SMIL: adds an `<animate>`\n * element per attribute. Each {@link AnimationDefinition} holds SMIL\n * attributes (usually `begin`, `dur`, `from` and `to`, see\n * https://www.w3.org/TR/SVG11/animate.html), plus an optional `easing`: a\n * name from {@link easings} or four numbers of a cubic Bézier curve.\n *\n * An animations object could look like this:\n * ```ts\n * element.animate({\n * opacity: {\n * dur: 1000,\n * from: 0,\n * to: 1\n * },\n * x1: {\n * dur: '1000ms',\n * from: 100,\n * to: 200,\n * easing: 'easeOutQuart'\n * },\n * y1: {\n * dur: '2s',\n * from: 0,\n * to: 100\n * }\n * });\n * ```\n *\n * `dur` and `begin` given as numbers are milliseconds.\n *\n * **Guided mode** (the default) makes one-off animations behave: the\n * attribute is set to `from` right away, even before a delayed start; the\n * animation starts after `begin` ms (a timeout, not the document's\n * timeline); and when it ends, the attribute keeps `to` and the\n * `<animate>` element is removed. Pass `guided: false` to write the\n * `<animate>` elements as given. An attribute with an array of\n * definitions never runs guided.\n * @param animations The attributes to animate, each with a definition, or\n * an array of definitions to run several animations on one attribute.\n * @param guided Runs the animations in guided mode (see above).\n * @param eventEmitter Gets `animationBegin` and `animationEnd` events\n * ({@link AnimationEvent}) when an animation starts and ends. With the\n * compat plugin, elements of a chart send them to the chart by default.\n * @returns The same wrapper, for chaining.\n */\n animate(\n animations: Record<string, AnimationDefinition | AnimationDefinition[]>,\n guided = true,\n eventEmitter?: EventEmitter\n ) {\n const emitter = eventEmitter ?? animationEmitterOf(this._node);\n Object.keys(animations).forEach(attribute => {\n const attributeAnimation = animations[attribute];\n\n // If current attribute is an array of definition objects we create an animate for each and disable guided mode\n if (Array.isArray(attributeAnimation)) {\n attributeAnimation.forEach(animationDefinition =>\n createAnimation(this, attribute, animationDefinition, false, emitter)\n );\n } else {\n createAnimation(this, attribute, attributeAnimation, guided, emitter);\n }\n });\n\n return this;\n }\n}\n","import type {\n ChartPadding,\n ChartRect,\n Options,\n Label,\n GridDrawEvent,\n GridBackgroundDrawEvent,\n LabelDrawEvent,\n ViewBox\n} from './types';\nimport type { EventEmitter } from '../event';\nimport type { Axis } from '../axes';\nimport { namespaces } from './constants';\nimport { Svg } from '../svg/Svg';\nimport { quantity } from './lang';\n\n/**\n * Create or reinitialize the SVG element for the chart\n * @param container The containing DOM Node object that will be used to plant the SVG element\n * @param width Set the width of the SVG element. Default is 100%\n * @param height Set the height of the SVG element. Default is 100%\n * @param className Specify a class to be added to the SVG element\n * @return The created/reinitialized SVG element\n *\n * @deprecated Part of the 1.x chart classes. The functional API builds a scene instead. Removed in 3.0.\n */\nexport function createSvg(\n container: Element,\n width: number | string = '100%',\n height: number | string = '100%',\n className?: string,\n viewBox?: ViewBox\n) {\n if (!container) {\n throw new Error('Container element is not found');\n }\n\n // Check if there is a previous SVG element in the container that contains the Chartist XML namespace and remove it\n // Since the DOM API does not support namespaces we need to manually search the returned list http://www.w3.org/TR/selectors-api/\n Array.from(container.querySelectorAll('svg'))\n .filter(svg => svg.getAttributeNS(namespaces.xmlns, 'ct'))\n .forEach(svg => container.removeChild(svg));\n\n // Create svg object with width and height or use 100% as default\n const svg = new Svg('svg')\n .attr({\n width,\n height\n })\n .attr({\n // TODO: Check better solution (browser support) and remove inline styles due to CSP\n style: `width: ${width}; height: ${height};`\n });\n\n if (className) {\n svg.addClass(className);\n }\n\n if (viewBox) {\n svg.attr({ viewBox: `0 0 ${viewBox.width} ${viewBox.height}` });\n }\n\n // Add the DOM node to our container\n container.appendChild(svg.getNode());\n\n return svg;\n}\n\n/**\n * Turns a padding option into a full {@link ChartPadding}: a number pads\n * every side, an object keeps its numeric sides and sets the missing ones\n * to 0, and `undefined` gives 0 on every side.\n * @returns A new padding object with `top`, `right`, `bottom` and `left`.\n */\nexport function normalizePadding(\n padding: number | Partial<ChartPadding> | undefined\n) {\n return typeof padding === 'number'\n ? {\n top: padding,\n right: padding,\n bottom: padding,\n left: padding\n }\n : padding === undefined\n ? { top: 0, right: 0, bottom: 0, left: 0 }\n : {\n top: typeof padding.top === 'number' ? padding.top : 0,\n right: typeof padding.right === 'number' ? padding.right : 0,\n bottom: typeof padding.bottom === 'number' ? padding.bottom : 0,\n left: typeof padding.left === 'number' ? padding.left : 0\n };\n}\n\n/**\n * Initialize chart drawing rectangle (area where chart is drawn) x1,y1 = bottom left / x2,y2 = top right\n * @param svg The svg element for the chart\n * @param options The Object that contains all the optional values for the chart\n * @return The chart rectangles coordinates inside the svg element plus the rectangles measurements\n */\nexport function createChartRect(svg: Svg, options: Options) {\n const hasAxis = Boolean(options.axisX || options.axisY);\n const yAxisOffset = options.axisY?.offset || 0;\n const xAxisOffset = options.axisX?.offset || 0;\n const yAxisPosition = options.axisY?.position;\n const xAxisPosition = options.axisX?.position;\n // If width or height results in invalid value (including 0) we fallback to the unitless settings or even 0\n let width =\n options.viewBox?.width || svg.width() || quantity(options.width).value || 0;\n let height =\n options.viewBox?.height ||\n svg.height() ||\n quantity(options.height).value ||\n 0;\n const normalizedPadding = normalizePadding(options.chartPadding);\n\n // If settings were to small to cope with offset (legacy) and padding, we'll adjust\n width = Math.max(\n width,\n yAxisOffset + normalizedPadding.left + normalizedPadding.right\n );\n height = Math.max(\n height,\n xAxisOffset + normalizedPadding.top + normalizedPadding.bottom\n );\n\n const chartRect = {\n x1: 0,\n x2: 0,\n y1: 0,\n y2: 0,\n padding: normalizedPadding,\n width() {\n return this.x2 - this.x1;\n },\n height() {\n return this.y1 - this.y2;\n }\n };\n\n if (hasAxis) {\n if (xAxisPosition === 'start') {\n chartRect.y2 = normalizedPadding.top + xAxisOffset;\n chartRect.y1 = Math.max(\n height - normalizedPadding.bottom,\n chartRect.y2 + 1\n );\n } else {\n chartRect.y2 = normalizedPadding.top;\n chartRect.y1 = Math.max(\n height - normalizedPadding.bottom - xAxisOffset,\n chartRect.y2 + 1\n );\n }\n\n if (yAxisPosition === 'start') {\n chartRect.x1 = normalizedPadding.left + yAxisOffset;\n chartRect.x2 = Math.max(\n width - normalizedPadding.right,\n chartRect.x1 + 1\n );\n } else {\n chartRect.x1 = normalizedPadding.left;\n chartRect.x2 = Math.max(\n width - normalizedPadding.right - yAxisOffset,\n chartRect.x1 + 1\n );\n }\n } else {\n chartRect.x1 = normalizedPadding.left;\n chartRect.x2 = Math.max(width - normalizedPadding.right, chartRect.x1 + 1);\n chartRect.y2 = normalizedPadding.top;\n chartRect.y1 = Math.max(\n height - normalizedPadding.bottom,\n chartRect.y2 + 1\n );\n }\n\n return chartRect;\n}\n\n/**\n * Creates a grid line based on a projected value.\n *\n * @deprecated Use the `axisGrid()` layer. Removed in 3.0.\n */\nexport function createGrid(\n position: number,\n index: number,\n axis: Axis,\n offset: number,\n length: number,\n group: Svg,\n classes: string[],\n eventEmitter: EventEmitter\n) {\n const positionalData = {\n [`${axis.units.pos}1`]: position,\n [`${axis.units.pos}2`]: position,\n [`${axis.counterUnits.pos}1`]: offset,\n [`${axis.counterUnits.pos}2`]: offset + length\n } as Record<'x1' | 'y1' | 'x2' | 'y2', number>;\n\n const gridElement = group.elem('line', positionalData, classes.join(' '));\n\n // Event for grid draw\n eventEmitter.emit<GridDrawEvent>('draw', {\n type: 'grid',\n axis,\n index,\n group,\n element: gridElement,\n ...positionalData\n });\n}\n\n/**\n * Creates a grid background rect and emits the draw event.\n *\n * @deprecated Use the `axisGrid()` layer. Removed in 3.0.\n */\nexport function createGridBackground(\n gridGroup: Svg,\n chartRect: ChartRect,\n className: string,\n eventEmitter: EventEmitter\n) {\n const gridBackground = gridGroup.elem(\n 'rect',\n {\n x: chartRect.x1,\n y: chartRect.y2,\n width: chartRect.width(),\n height: chartRect.height()\n },\n className,\n true\n );\n\n // Event for grid background draw\n eventEmitter.emit<GridBackgroundDrawEvent>('draw', {\n type: 'gridBackground',\n group: gridGroup,\n element: gridBackground\n });\n}\n\n/**\n * Creates a label based on a projected value and an axis.\n *\n * @deprecated Use the `axisLabels()` layer. Removed in 3.0.\n */\nexport function createLabel(\n position: number,\n length: number,\n index: number,\n label: Label,\n axis: Axis,\n axisOffset: number,\n labelOffset: { x: number; y: number },\n group: Svg,\n classes: string[],\n eventEmitter: EventEmitter\n) {\n const positionalData = {\n [axis.units.pos]: position + labelOffset[axis.units.pos],\n [axis.counterUnits.pos]: labelOffset[axis.counterUnits.pos],\n [axis.units.len]: length,\n [axis.counterUnits.len]: Math.max(0, axisOffset - 10)\n } as Record<'x' | 'y' | 'width' | 'height', number>;\n // We need to set width and height explicitly to px as span will not expand with width and height being\n // 100% in all browsers\n const stepLength = Math.round(positionalData[axis.units.len]);\n const stepCounterLength = Math.round(positionalData[axis.counterUnits.len]);\n const content = group.getNode().ownerDocument.createElement('span');\n\n content.className = classes.join(' ');\n content.style[axis.units.len] = stepLength + 'px';\n content.style[axis.counterUnits.len] = stepCounterLength + 'px';\n content.textContent = String(label);\n\n const labelElement = group.foreignObject(content, {\n style: 'overflow: visible;',\n ...positionalData\n });\n\n eventEmitter.emit<LabelDrawEvent>('draw', {\n type: 'label',\n axis,\n index,\n group,\n element: labelElement,\n text: label,\n ...positionalData\n });\n}\n","import type { EventEmitter } from '../event';\nimport type { OptionsChangedEvent, ResponsiveOptions } from './types';\nimport { extend } from '../utils';\n\n/**\n * What {@link optionsProvider} returns: the current options, and a way to stop listening to media queries.\n *\n * @deprecated Part of the 1.x chart classes. Responsive options are an argument of the chart functions. Removed in 3.0.\n */\nexport interface OptionsProvider<T = unknown> {\n removeMediaQueryListeners(): void;\n getCurrentOptions(): T;\n}\n\n/**\n * Provides options handling functionality with callback for options changes triggered by responsive options and media query matches\n * @param options Options set by user\n * @param responsiveOptions Optional functions to add responsive behavior to chart\n * @param eventEmitter The event emitter that will be used to emit the options changed events\n * @return The consolidated options object from the defaults, base and matching responsive options\n *\n * @deprecated Part of the 1.x chart classes. Responsive options are an argument of the chart functions. Removed in 3.0.\n */\nexport function optionsProvider<T = unknown>(\n options: T,\n responsiveOptions: ResponsiveOptions<T> | undefined,\n eventEmitter: EventEmitter\n): OptionsProvider<T> {\n let currentOptions: T;\n const mediaQueryListeners: MediaQueryList[] = [];\n\n function updateCurrentOptions(mediaEvent?: Event) {\n const previousOptions = currentOptions;\n currentOptions = extend({}, options);\n\n if (responsiveOptions) {\n responsiveOptions.forEach(responsiveOption => {\n const mql = window.matchMedia(responsiveOption[0]);\n if (mql.matches) {\n currentOptions = extend({}, currentOptions, responsiveOption[1]);\n }\n });\n }\n\n if (eventEmitter && mediaEvent) {\n eventEmitter.emit<OptionsChangedEvent<T>>('optionsChanged', {\n previousOptions,\n currentOptions\n });\n }\n }\n\n function removeMediaQueryListeners() {\n mediaQueryListeners.forEach(mql =>\n mql.removeEventListener('change', updateCurrentOptions)\n );\n }\n\n if (!window.matchMedia) {\n throw new Error(\n \"window.matchMedia not found! Make sure you're using a polyfill.\"\n );\n } else if (responsiveOptions) {\n responsiveOptions.forEach(responsiveOption => {\n const mql = window.matchMedia(responsiveOption[0]);\n mql.addEventListener('change', updateCurrentOptions);\n mediaQueryListeners.push(mql);\n });\n }\n // Execute initially without an event argument so we get the correct options\n updateCurrentOptions();\n\n return {\n removeMediaQueryListeners,\n getCurrentOptions() {\n return currentOptions;\n }\n };\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * A listener of one event: gets the event's payload.\n *\n * @deprecated Use the chart handle's `on()` and `off()`. Removed in 3.0.\n */\nexport type EventListener<T = any> = (data: T) => void;\n\n/**\n * A listener of every event (`'*'`): gets the event's name and payload.\n *\n * @deprecated Use the chart handle's `on()` and `off()`. Removed in 3.0.\n */\nexport type AllEventsListener<T = any> = (event: string, data: T) => void;\n\n/**\n * The 1.x event emitter: `on`, `off` and `emit` by event name, with `'*'` for all events.\n *\n * @deprecated Use the chart handle's `on()` and `off()`. Removed in 3.0.\n */\nexport class EventEmitter {\n private readonly listeners = new Map<string, Set<EventListener>>();\n private readonly allListeners = new Set<AllEventsListener>();\n\n /**\n * Add an event handler for a specific event\n * @param event The event name\n * @param listener A event handler function\n */\n on(event: '*', listener: AllEventsListener): void;\n on(event: string, listener: EventListener): void;\n on(event: string, listener: EventListener | AllEventsListener) {\n const { allListeners, listeners } = this;\n\n if (event === '*') {\n allListeners.add(listener);\n } else {\n if (!listeners.has(event)) {\n listeners.set(event, new Set());\n }\n\n (listeners.get(event) as Set<EventListener>).add(\n listener as EventListener\n );\n }\n }\n\n /**\n * Remove an event handler of a specific event name or remove all event handlers for a specific event.\n * @param event The event name where a specific or all handlers should be removed\n * @param [listener] An optional event handler function. If specified only this specific handler will be removed and otherwise all handlers are removed.\n */\n off(event: '*', listener?: AllEventsListener): void;\n off(event: string, listener?: EventListener): void;\n off(event: string, listener?: EventListener | AllEventsListener) {\n const { allListeners, listeners } = this;\n\n if (event === '*') {\n if (listener) {\n allListeners.delete(listener);\n } else {\n allListeners.clear();\n }\n } else if (listeners.has(event)) {\n const eventListeners = listeners.get(event) as Set<EventListener>;\n\n if (listener) {\n eventListeners.delete(listener as EventListener);\n } else {\n eventListeners.clear();\n }\n\n if (!eventListeners.size) {\n listeners.delete(event);\n }\n }\n }\n\n /**\n * Use this function to emit an event. All handlers that are listening for this event will be triggered with the data parameter.\n * @param event The event name that should be triggered\n * @param data Arbitrary data that will be passed to the event handler callback functions\n */\n emit<T = any>(event: string, data: T) {\n const { allListeners, listeners } = this;\n\n // Only do something if there are event handlers with this name existing\n if (listeners.has(event)) {\n (listeners.get(event) as Set<EventListener>).forEach(listener =>\n listener(data)\n );\n }\n\n // Emit event to star event handlers\n allListeners.forEach(listener => listener(event, data));\n }\n}\n","import type { Data, Options, DataEvent, ResponsiveOptions } from '../core';\nimport type { Svg } from '../svg';\nimport type { BaseChartEventsTypes } from './types';\nimport { OptionsProvider, optionsProvider } from '../core';\nimport { extend } from '../utils';\nimport { EventListener, AllEventsListener, EventEmitter } from '../event';\n\nconst instances = new WeakMap<Element, BaseChart<unknown>>();\n\n/**\n * The base class of the 1.x chart classes ({@link LineChart},\n * {@link BarChart}, {@link PieChart}): the container, `update`, `detach`,\n * `on` and `off`.\n *\n * @deprecated Use the chart functions: `lineChart()`, `barChart()`, `pieChart()` and `chart()`. Removed in 3.0.\n */\nexport abstract class BaseChart<TEventsTypes = BaseChartEventsTypes> {\n protected svg?: Svg;\n protected readonly container: Element;\n protected readonly eventEmitter = new EventEmitter();\n private readonly resizeListener = () => this.update();\n // Set at the end of the constructor, so a constructor that throws leaves\n // no first render scheduled.\n private initializeTimeoutId: ReturnType<typeof setTimeout> | null = null;\n private optionsProvider?: OptionsProvider<Options>;\n\n constructor(\n query: string | Element | null,\n protected data: Data,\n private readonly defaultOptions: Options,\n private options: Options,\n private readonly responsiveOptions?: ResponsiveOptions<Options>\n ) {\n const container =\n typeof query === 'string' ? document.querySelector(query) : query;\n\n if (!container) {\n throw new Error(\n `Target element ${\n typeof query === 'string' ? `\"${query}\"` : ''\n } is not found`\n );\n }\n\n this.container = container;\n\n const prevInstance = instances.get(container);\n\n // If chartist was already initialized in this container we are detaching all event listeners first\n if (prevInstance) {\n prevInstance.detach();\n }\n\n instances.set(container, this);\n\n // Using event loop for first draw to make it possible to register event listeners in the same call stack where\n // the chart was created.\n this.initializeTimeoutId = setTimeout(() => this.initialize(), 0);\n }\n\n abstract createChart(options: Options): void;\n\n // TODO: Currently we need to re-draw the chart on window resize. This is usually very bad and will affect performance.\n // This is done because we can't work with relative coordinates when drawing the chart because SVG Path does not\n // work with relative positions yet. We need to check if we can do a viewBox hack to switch to percentage.\n // See http://mozilla.6506.n7.nabble.com/Specyfing-paths-with-percentages-unit-td247474.html\n // Update: can be done using the above method tested here: http://codepen.io/gionkunz/pen/KDvLj\n // The problem is with the label offsets that can't be converted into percentage and affecting the chart container\n /**\n * Updates the chart which currently does a full reconstruction of the SVG DOM\n * @param data Optional data you'd like to set for the chart before it will update. If not specified the update method will use the data that is already configured with the chart.\n * @param options Optional options you'd like to add to the previous options for the chart before it will update. If not specified the update method will use the options that have been already configured with the chart.\n * @param override If set to true, the passed options will be used to extend the options that have been configured already. Otherwise the chart default options will be used as the base\n */\n update(data?: Data, options?: Options, override = false) {\n if (data) {\n this.data = data || {};\n this.data.labels = this.data.labels || [];\n this.data.series = this.data.series || [];\n // Event for data transformation that allows to manipulate the data before it gets rendered in the charts\n this.eventEmitter.emit<DataEvent>('data', {\n type: 'update',\n data: this.data\n });\n }\n\n if (options) {\n this.options = extend(\n {},\n override ? this.options : this.defaultOptions,\n options\n );\n\n // If chartist was not initialized yet, we just set the options and leave the rest to the initialization\n // Otherwise we re-create the optionsProvider at this point\n if (!this.initializeTimeoutId) {\n this.optionsProvider?.removeMediaQueryListeners();\n this.optionsProvider = optionsProvider(\n this.options,\n this.responsiveOptions,\n this.eventEmitter\n );\n }\n }\n\n // Only re-created the chart if it has been initialized yet\n if (!this.initializeTimeoutId && this.optionsProvider) {\n this.createChart(this.optionsProvider.getCurrentOptions());\n }\n\n // Return a reference to the chart object to chain up calls\n return this;\n }\n\n /**\n * This method can be called on the API object of each chart and will un-register all event listeners that were added to other components. This currently includes a window.resize listener as well as media query listeners if any responsive options have been provided. Use this function if you need to destroy and recreate Chartist charts dynamically.\n */\n detach() {\n // Only detach if initialization already occurred on this chart. If this chart still hasn't initialized (therefore\n // the initializationTimeoutId is still a valid timeout reference, we will clear the timeout\n if (!this.initializeTimeoutId) {\n this.container.ownerDocument.defaultView?.removeEventListener(\n 'resize',\n this.resizeListener\n );\n this.optionsProvider?.removeMediaQueryListeners();\n } else {\n clearTimeout(this.initializeTimeoutId);\n }\n\n instances.delete(this.container);\n\n return this;\n }\n\n /**\n * Use this function to register event handlers. The handler callbacks are synchronous and will run in the main thread rather than the event loop.\n * @param event Name of the event. Check the examples for supported events.\n * @param listener The handler function that will be called when an event with the given name was emitted. This function will receive a data argument which contains event data. See the example for more details.\n */\n on<T extends keyof TEventsTypes>(\n event: T,\n listener: EventListener<TEventsTypes[T]>\n ): this;\n on(event: '*', listener: AllEventsListener): this;\n on(event: string, listener: EventListener): this;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n on(event: string, listener: any) {\n this.eventEmitter.on(event, listener);\n return this;\n }\n\n /**\n * Use this function to un-register event handlers. If the handler function parameter is omitted all handlers for the given event will be un-registered.\n * @param event Name of the event for which a handler should be removed\n * @param listener The handler function that that was previously used to register a new event handler. This handler will be removed from the event handler list. If this parameter is omitted then all event handlers for the given event are removed from the list.\n */\n off<T extends keyof TEventsTypes>(\n event: T,\n listener?: EventListener<TEventsTypes[T]>\n ): this;\n off(event: '*', listener?: AllEventsListener): this;\n off(event: string, listener?: EventListener): this;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n off(event: string, listener?: any) {\n this.eventEmitter.off(event, listener);\n return this;\n }\n\n initialize() {\n // Add window resize listener that re-creates the chart\n this.container.ownerDocument.defaultView?.addEventListener(\n 'resize',\n this.resizeListener\n );\n\n // Obtain current options based on matching media queries (if responsive options are given)\n // This will also register a listener that is re-creating the chart based on media changes\n this.optionsProvider = optionsProvider(\n this.options,\n this.responsiveOptions,\n this.eventEmitter\n );\n // Register options change listener that will trigger a chart update\n this.eventEmitter.on('optionsChanged', () => this.update());\n\n // Before the first chart creation we need to register us with all plugins that are configured\n // Initialize all relevant plugins with our chart object and the plugin options specified in the config\n if (this.options.plugins) {\n this.options.plugins.forEach(plugin => {\n if (Array.isArray(plugin)) {\n plugin[0](this, plugin[1]);\n } else if (typeof plugin === 'function') {\n plugin(this);\n }\n // v2 plugin objects (e.g. compat) are for the v2-based charts; the\n // 1.x implementations emit 1.x events natively.\n });\n }\n\n // Event for data transformation that allows to manipulate the data before it gets rendered in the charts\n this.eventEmitter.emit<DataEvent>('data', {\n type: 'initial',\n data: this.data\n });\n\n // Create the first chart\n this.createChart(this.optionsProvider.getCurrentOptions());\n\n // As chart is initialized from the event loop now we can reset our timeout reference\n // This is important if the chart gets initialized on the same element twice\n this.initializeTimeoutId = null;\n }\n}\n","import type { SegmentData } from '../core';\nimport type { SvgPathOptions, PathCommand, PathParams } from './types';\n\n/**\n * The parameters of each SVG path command, in the order the `d` attribute\n * lists them. `Z` has none.\n */\nconst elementDescriptions: Record<string, string[]> = {\n m: ['x', 'y'],\n l: ['x', 'y'],\n h: ['x'],\n v: ['y'],\n c: ['x1', 'y1', 'x2', 'y2', 'x', 'y'],\n s: ['x2', 'y2', 'x', 'y'],\n q: ['x1', 'y1', 'x', 'y'],\n t: ['x', 'y'],\n a: ['rx', 'ry', 'xAr', 'lAf', 'sf', 'x', 'y'],\n z: []\n};\n\n/**\n * The axis each parameter is scaled along. An arc's rotation and flags\n * aren't coordinates, so they're left out.\n */\nconst scaleAxes: Record<string, 'x' | 'y'> = {\n x: 'x',\n x1: 'x',\n x2: 'x',\n rx: 'x',\n y: 'y',\n y1: 'y',\n y2: 'y',\n ry: 'y'\n};\n\n/** The axis each parameter is translated along: the points, not an arc's radii. */\nconst translateAxes: Record<string, 'x' | 'y'> = {\n x: 'x',\n x1: 'x',\n x2: 'x',\n y: 'y',\n y1: 'y',\n y2: 'y'\n};\n\n/**\n * Default options for newly created SVG path objects.\n */\nconst defaultOptions: Required<SvgPathOptions> = {\n // The decimals numbers are rounded to; `false` doesn't round.\n accuracy: 3\n};\n\nconst commandPattern = /[MmZzLlHhVvCcSsQqTtAa]/y;\nconst numberPattern = /[-+]?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][-+]?\\d+)?/y;\nconst flagPattern = /[01]/y;\nconst separatorPattern = /[\\s,]*/y;\n\n/**\n * Reads the commands of an SVG path's `d`: numbers with signs and exponents,\n * numbers without separators (`.5.5`, `1-2`), arc flags written together, and\n * implicit repeats of a command (after a move, as lines).\n */\nfunction parseCommands(path: string): PathCommand[] {\n let index = 0;\n const read = (pattern: RegExp) => {\n separatorPattern.lastIndex = index;\n separatorPattern.exec(path);\n pattern.lastIndex = separatorPattern.lastIndex;\n const match = pattern.exec(path);\n if (match) {\n index = pattern.lastIndex;\n }\n return match?.[0];\n };\n const fail = (): never => {\n throw new Error(\n `Invalid SVG path at position ${index}: \"${path.slice(index, index + 20)}\"`\n );\n };\n\n const commands: PathCommand[] = [];\n let command = read(commandPattern) ?? (path.trim() ? fail() : undefined);\n while (command) {\n const names = elementDescriptions[command.toLowerCase()];\n const params: Record<string, number> = {};\n for (const name of names) {\n const value = read(\n name === 'lAf' || name === 'sf' ? flagPattern : numberPattern\n );\n params[name] = value === undefined ? fail() : +value;\n }\n commands.push({ command, ...params } as PathCommand);\n\n const next = read(commandPattern);\n if (next) {\n command = next;\n continue;\n }\n // A number without a command letter repeats the command; after a move it's a line.\n separatorPattern.lastIndex = index;\n separatorPattern.exec(path);\n index = separatorPattern.lastIndex;\n if (index >= path.length) {\n break;\n }\n if (names.length === 0) {\n fail();\n }\n numberPattern.lastIndex = index;\n if (!numberPattern.test(path)) {\n fail();\n }\n command = command === 'M' ? 'L' : command === 'm' ? 'l' : command;\n }\n return commands;\n}\n\nfunction element(\n command: string,\n params: PathParams,\n pathElements: PathCommand[],\n pos: number,\n relative: boolean,\n data?: SegmentData\n) {\n const pathElement: PathCommand = {\n command: relative ? command.toLowerCase() : command.toUpperCase(),\n ...params,\n ...(data ? { data } : {})\n };\n\n pathElements.splice(pos, 0, pathElement);\n}\n\nfunction forEachParam<T extends PathParams = PathParams>(\n pathElements: PathCommand<T>[],\n cb: (\n cmd: PathCommand<T>,\n param: keyof T,\n cmdIndex: number,\n paramIndex: number,\n cmds: PathCommand<T>[]\n ) => void\n) {\n pathElements.forEach((pathElement, pathElementIndex) => {\n elementDescriptions[pathElement.command.toLowerCase()].forEach(\n (paramName, paramIndex) => {\n cb(\n pathElement,\n paramName as keyof PathParams,\n pathElementIndex,\n paramIndex,\n pathElements\n );\n }\n );\n });\n}\n\n/**\n * Builds and changes the `d` of an SVG `path`: move, line, curve and arc\n * commands, with a cursor where new commands go. Lines, areas and slices\n * are `SvgPath`s, and interpolations such as {@link Interpolation.cardinal}\n * return one. Each command can carry the data of its point, which the\n * chart reads back for its points.\n *\n * @example\n * ```ts\n * import { SvgPath } from 'chartist';\n *\n * const path = new SvgPath()\n * .move(0, 100)\n * .line(50, 20)\n * .curve(70, 0, 90, 0, 100, 40);\n *\n * path.stringify(); // 'M0,100L50,20C70,0,90,0,100,40'\n *\n * // 10px to the right, at half the height\n * path.translate(10, 0).scale(1, 0.5);\n * ```\n */\nexport class SvgPath {\n /**\n * Joins paths into a new path, in the order given. The new path gets\n * copies of the commands, and its cursor is at the end.\n * @param paths A list of paths to be joined together. The order is important.\n * @param close If the newly created path should be a closed path\n * @param options Path options for the newly created path.\n */\n static join(paths: SvgPath[], close = false, options?: SvgPathOptions) {\n const joinedPath = new SvgPath(close, options);\n for (let i = 0; i < paths.length; i++) {\n const path = paths[i];\n for (let j = 0; j < path.pathElements.length; j++) {\n joinedPath.pathElements.push({ ...path.pathElements[j] });\n }\n }\n joinedPath.pos = joinedPath.pathElements.length;\n return joinedPath;\n }\n\n /** The path's commands, in order: each with its letter, its coordinates and the data of its point. */\n pathElements: PathCommand[] = [];\n private pos = 0;\n private options: Required<SvgPathOptions>;\n\n /**\n * Creates an empty path.\n * @param close Closes the path when it's stringified (a `Z` at the end).\n * @param options The path's options, such as the rounding `accuracy`.\n */\n constructor(\n private readonly close = false,\n options?: SvgPathOptions\n ) {\n this.options = { ...defaultOptions, ...options };\n }\n\n /**\n * Gets or sets the current position (cursor) inside of the path. You can move around the cursor freely but limited to 0 or the count of existing elements. All modifications with element functions will insert new elements at the position of this cursor.\n * @param pos If a number is passed then the cursor is set to this position in the path element array.\n * @return If the position parameter was passed then the return value will be the path object for easy call chaining. If no position parameter was passed then the current position is returned.\n */\n position(pos: number): this;\n position(): number;\n position(pos?: number) {\n if (pos !== undefined) {\n this.pos = Math.max(0, Math.min(this.pathElements.length, pos));\n return this;\n } else {\n return this.pos;\n }\n }\n\n /**\n * Removes elements from the path starting at the current position.\n * @param count Number of path elements that should be removed from the current position.\n * @return The current path object for easy call chaining.\n */\n remove(count: number) {\n this.pathElements.splice(this.pos, count);\n return this;\n }\n\n /**\n * Use this function to add a new move SVG path element.\n * @param x The x coordinate for the move element.\n * @param y The y coordinate for the move element.\n * @param relative If set to true the move element will be created with relative coordinates (lowercase letter)\n * @param data Any data that should be stored with the element object that will be accessible in pathElement\n * @return The current path object for easy call chaining.\n */\n move(x: number, y: number, relative = false, data?: SegmentData) {\n element(\n 'M',\n {\n x: +x,\n y: +y\n },\n this.pathElements,\n this.pos++,\n relative,\n data\n );\n return this;\n }\n\n /**\n * Use this function to add a new line SVG path element.\n * @param x The x coordinate for the line element.\n * @param y The y coordinate for the line element.\n * @param relative If set to true the line element will be created with relative coordinates (lowercase letter)\n * @param data Any data that should be stored with the element object that will be accessible in pathElement\n * @return The current path object for easy call chaining.\n */\n line(x: number, y: number, relative = false, data?: SegmentData) {\n element(\n 'L',\n {\n x: +x,\n y: +y\n },\n this.pathElements,\n this.pos++,\n relative,\n data\n );\n return this;\n }\n\n /**\n * Use this function to add a new curve SVG path element.\n * @param x1 The x coordinate for the first control point of the bezier curve.\n * @param y1 The y coordinate for the first control point of the bezier curve.\n * @param x2 The x coordinate for the second control point of the bezier curve.\n * @param y2 The y coordinate for the second control point of the bezier curve.\n * @param x The x coordinate for the target point of the curve element.\n * @param y The y coordinate for the target point of the curve element.\n * @param relative If set to true the curve element will be created with relative coordinates (lowercase letter)\n * @param data Any data that should be stored with the element object that will be accessible in pathElement\n * @return The current path object for easy call chaining.\n */\n curve(\n x1: number,\n y1: number,\n x2: number,\n y2: number,\n x: number,\n y: number,\n relative = false,\n data?: SegmentData\n ) {\n element(\n 'C',\n {\n x1: +x1,\n y1: +y1,\n x2: +x2,\n y2: +y2,\n x: +x,\n y: +y\n },\n this.pathElements,\n this.pos++,\n relative,\n data\n );\n return this;\n }\n\n /**\n * Use this function to add a new non-bezier curve SVG path element.\n * @param rx The radius to be used for the x-axis of the arc.\n * @param ry The radius to be used for the y-axis of the arc.\n * @param xAr Defines the orientation of the arc\n * @param lAf Large arc flag\n * @param sf Sweep flag\n * @param x The x coordinate for the target point of the curve element.\n * @param y The y coordinate for the target point of the curve element.\n * @param relative If set to true the curve element will be created with relative coordinates (lowercase letter)\n * @param data Any data that should be stored with the element object that will be accessible in pathElement\n * @return The current path object for easy call chaining.\n */\n arc(\n rx: number,\n ry: number,\n xAr: number,\n lAf: number,\n sf: number,\n x: number,\n y: number,\n relative = false,\n data?: SegmentData\n ) {\n element(\n 'A',\n {\n rx,\n ry,\n xAr,\n lAf,\n sf,\n x,\n y\n },\n this.pathElements,\n this.pos++,\n relative,\n data\n );\n return this;\n }\n\n /**\n * Parses the `d` of an SVG path and inserts its commands at the cursor. A\n * closing `Z` at the end is dropped: the `close` of the path object decides\n * that.\n * @param path An SVG path of any commands (`M`, `L`, `H`, `V`, `C`, `S`, `Q`, `T`, `A`, `Z`), absolute or relative.\n * @return The current path object for easy call chaining.\n * @throws An `Error` if the path isn't valid SVG path syntax.\n */\n parse(path: string) {\n const elements = parseCommands(path);\n\n // The path's own `close` decides about a closing Z at the end.\n if (elements.at(-1)?.command.toUpperCase() === 'Z') {\n elements.pop();\n }\n\n this.pathElements.splice(this.pos, 0, ...elements);\n this.pos += elements.length;\n\n return this;\n }\n\n /**\n * Writes the path as a string for the `d` attribute of a `path` element.\n * Numbers are rounded to the `accuracy` option's decimals (to integers\n * with `0`, not at all with `false`), and a closed path ends with `Z`.\n */\n stringify() {\n const { accuracy } = this.options;\n const accuracyMultiplier = Math.pow(10, accuracy || 0);\n\n return (\n this.pathElements.reduce((path, pathElement) => {\n const params = elementDescriptions[\n pathElement.command.toLowerCase()\n ].map(paramName => {\n const value = pathElement[paramName as keyof PathCommand] as number;\n\n return typeof accuracy === 'number'\n ? Math.round(value * accuracyMultiplier) / accuracyMultiplier\n : value;\n });\n\n return path + pathElement.command + params.join(',');\n }, '') + (this.close ? 'Z' : '')\n );\n }\n\n /**\n * Scales all elements in the current SVG path object. There is an individual parameter for each coordinate. Scaling will also be done for control points of curves and the radii of arcs, affecting the given coordinate; an arc's rotation and flags stay as they are.\n * @param x The number which will be used to scale the x, x1, x2 and rx of all path elements.\n * @param y The number which will be used to scale the y, y1, y2 and ry of all path elements.\n * @return The current path object for easy call chaining.\n */\n scale(x: number, y: number) {\n forEachParam(this.pathElements, (pathElement, paramName) => {\n const axis = scaleAxes[paramName as string];\n if (axis) {\n pathElement[paramName] *= axis === 'x' ? x : y;\n }\n });\n return this;\n }\n\n /**\n * Translates all elements in the current SVG path object. The translation is relative and there is an individual parameter for each coordinate. Translation will also be done for control points of curves, affecting the given coordinate; an arc's radii, rotation and flags stay as they are.\n * @param x The number which will be used to translate the x, x1 and x2 of all path elements.\n * @param y The number which will be used to translate the y, y1 and y2 of all path elements.\n * @return The current path object for easy call chaining.\n */\n translate(x: number, y: number) {\n forEachParam(this.pathElements, (pathElement, paramName) => {\n const axis = translateAxes[paramName as string];\n if (axis) {\n pathElement[paramName] += axis === 'x' ? x : y;\n }\n });\n return this;\n }\n\n /**\n * This function will run over all existing path elements and then loop over their attributes. The callback function will be called for every path element attribute that exists in the current path.\n * The method signature of the callback function looks like this:\n * ```javascript\n * function(pathElement, paramName, pathElementIndex, paramIndex, pathElements)\n * ```\n * If something else than undefined is returned by the callback function, this value will be used to replace the old value. This allows you to build custom transformations of path objects that can't be achieved using the basic transformation functions scale and translate.\n * @param transformFnc The callback function for the transformation. Check the signature in the function description.\n * @return The current path object for easy call chaining.\n */\n transform(\n transformFnc: <T extends PathParams = PathParams>(\n cmd: PathCommand<T>,\n param: keyof T,\n cmdIndex: number,\n paramIndex: number,\n cmds: PathCommand<T>[]\n ) => number | void\n ) {\n forEachParam(\n this.pathElements,\n (pathElement, paramName, pathElementIndex, paramIndex, pathElements) => {\n const transformed = transformFnc(\n pathElement,\n paramName,\n pathElementIndex,\n paramIndex,\n pathElements\n );\n if (transformed || transformed === 0) {\n pathElement[paramName] = transformed;\n }\n }\n );\n return this;\n }\n\n /**\n * This function clones a whole path object with all its properties. This is a deep clone and path element objects will also be cloned.\n * @param close Optional option to set the new cloned path to closed. If not specified or false, the original path close option will be used.\n */\n clone(close = false) {\n const clone = new SvgPath(close || this.close);\n clone.pos = this.pos;\n clone.pathElements = this.pathElements\n .slice()\n .map(pathElement => ({ ...pathElement }));\n clone.options = { ...this.options };\n return clone;\n }\n\n /**\n * Splits the path into new paths, each starting at the given command,\n * such as `'M'` to get the separate pieces of a line with holes. The\n * letter matches absolute and relative commands. The pieces get copies of\n * the commands and the path's options, with their cursor at the end; the\n * last piece is closed if the path is.\n * @param command The command letter to split at.\n */\n splitByCommand(command: string) {\n const letter = command.toUpperCase();\n const pieces: PathCommand[][] = [[]];\n\n this.pathElements.forEach(pathElement => {\n if (\n pathElement.command.toUpperCase() === letter &&\n pieces[pieces.length - 1].length !== 0\n ) {\n pieces.push([]);\n }\n\n pieces[pieces.length - 1].push({ ...pathElement });\n });\n\n return pieces.map((pathElements, index) => {\n const piece = new SvgPath(\n this.close && index === pieces.length - 1,\n this.options\n );\n piece.pathElements = pathElements;\n piece.pos = pathElements.length;\n return piece;\n });\n }\n}\n","import type { SegmentData } from '../core';\nimport { getMultiValue } from '../core';\nimport { SvgPath } from '../svg';\n\n/** The options of {@link Interpolation.none}. */\nexport interface NoneInterpolationOptions {\n /**\n * Joins the line across holes (`null` or `undefined` values) instead of\n * breaking it. Off by default.\n */\n fillHoles?: boolean;\n}\n\n/**\n * Draws a line as straight segments from point to point, without\n * smoothing. It's what `lineSmooth: false` uses.\n *\n * @example\n * ```ts\n * import { lineChart, Interpolation } from 'chartist';\n *\n * lineChart(\n * '#chart',\n * { labels: [1, 2, 3, 4, 5], series: [[1, 2, 8, 1, 7]] },\n * { lineSmooth: Interpolation.none({ fillHoles: true }) }\n * );\n * ```\n *\n * @param options Whether to join the line across holes.\n * @returns The interpolation, for the `lineSmooth` option.\n */\nexport function none(options?: NoneInterpolationOptions) {\n const finalOptions = {\n fillHoles: false,\n ...options\n };\n\n return function noneInterpolation(\n pathCoordinates: number[],\n valueData: SegmentData[]\n ) {\n const path = new SvgPath();\n let hole = true;\n\n for (let i = 0; i < pathCoordinates.length; i += 2) {\n const currX = pathCoordinates[i];\n const currY = pathCoordinates[i + 1];\n const currData = valueData[i / 2];\n\n if (getMultiValue(currData.value) !== undefined) {\n if (hole) {\n path.move(currX, currY, false, currData);\n } else {\n path.line(currX, currY, false, currData);\n }\n\n hole = false;\n } else if (!finalOptions.fillHoles) {\n hole = true;\n }\n }\n\n return path;\n };\n}\n","import type { Segment, SegmentData } from '../core';\nimport { splitIntoSegments } from '../core';\nimport { SvgPath } from '../svg';\nimport { none } from './none';\n\n/** The options of {@link Interpolation.monotoneCubic}. */\nexport interface MonotoneCubicInterpolationOptions {\n /**\n * Joins the line across holes (`null` or `undefined` values) instead of\n * breaking it. Off by default.\n */\n fillHoles?: boolean;\n}\n\n/**\n * Splits a segment where x repeats or changes direction. The curve needs\n * strictly monotonic x within a piece, in either direction: a decreasing\n * piece gives the same curve as its points in increasing order.\n */\nfunction splitByDirection(segment: Segment): Segment[] {\n const { pathCoordinates, valueData } = segment;\n const pieces: Segment[] = [];\n let direction = 0;\n\n for (let i = 0; i < pathCoordinates.length; i += 2) {\n const dx = i >= 2 ? pathCoordinates[i] - pathCoordinates[i - 2] : 0;\n const sign = Math.sign(dx);\n\n if (i === 0 || sign === 0 || (direction !== 0 && sign !== direction)) {\n pieces.push({ pathCoordinates: [], valueData: [] });\n direction = 0;\n } else {\n direction = sign;\n }\n\n const piece = pieces[pieces.length - 1];\n piece.pathCoordinates.push(pathCoordinates[i], pathCoordinates[i + 1]);\n piece.valueData.push(valueData[i / 2]);\n }\n\n return pieces;\n}\n\n/**\n * Smooths a line with a monotone cubic spline: a smooth curve through\n * every point that never swings above or below the values around it. It's\n * what `lineSmooth: true` uses.\n *\n * The x values have to keep one direction, increasing or decreasing:\n * where an x value repeats or turns back, the line breaks. With two points\n * or fewer, the line is straight, as with {@link Interpolation.none}.\n *\n * @example\n * ```ts\n * import { lineChart, Interpolation } from 'chartist';\n *\n * lineChart(\n * '#chart',\n * { labels: [1, 2, 3, 4, 5], series: [[1, 2, 8, 1, 7]] },\n * { lineSmooth: Interpolation.monotoneCubic({ fillHoles: true }) }\n * );\n * ```\n *\n * @param options Whether to join the line across holes.\n * @returns The interpolation, for the `lineSmooth` option.\n */\nexport function monotoneCubic(options?: MonotoneCubicInterpolationOptions) {\n const finalOptions = {\n fillHoles: false,\n ...options\n };\n\n return function monotoneCubicInterpolation(\n pathCoordinates: number[],\n valueData: SegmentData[]\n ): SvgPath {\n // First we try to split the coordinates into segments\n // This is necessary to treat \"holes\" in line charts\n const segments = splitIntoSegments(pathCoordinates, valueData, {\n fillHoles: finalOptions.fillHoles\n }).flatMap(splitByDirection);\n\n if (!segments.length) {\n // If there were no segments return 'Chartist.Interpolation.none'\n return none()([], []);\n } else if (segments.length > 1) {\n // If the split resulted in more that one segment we need to interpolate each segment individually and join them\n // afterwards together into a single path.\n // For each segment we will recurse the monotoneCubic fn function\n // Join the segment path data into a single path and return\n return SvgPath.join(\n segments.map(segment =>\n monotoneCubicInterpolation(segment.pathCoordinates, segment.valueData)\n )\n );\n } else {\n // If there was only one segment we can proceed regularly by using pathCoordinates and valueData from the first\n // segment\n pathCoordinates = segments[0].pathCoordinates;\n valueData = segments[0].valueData;\n\n // If less than three points we need to fallback to no smoothing\n if (pathCoordinates.length <= 4) {\n return none()(pathCoordinates, valueData);\n }\n\n const xs = [];\n const ys = [];\n const n = pathCoordinates.length / 2;\n const ms = [];\n const ds = [];\n const dys = [];\n const dxs = [];\n\n // Populate x and y coordinates into separate arrays, for readability\n for (let i = 0; i < n; i++) {\n xs[i] = pathCoordinates[i * 2];\n ys[i] = pathCoordinates[i * 2 + 1];\n }\n\n // Calculate deltas and derivative\n for (let i = 0; i < n - 1; i++) {\n dys[i] = ys[i + 1] - ys[i];\n dxs[i] = xs[i + 1] - xs[i];\n ds[i] = dys[i] / dxs[i];\n }\n\n // Determine desired slope (m) at each point using Fritsch-Carlson method\n // See: http://math.stackexchange.com/questions/45218/implementation-of-monotone-cubic-interpolation\n ms[0] = ds[0];\n ms[n - 1] = ds[n - 2];\n\n for (let i = 1; i < n - 1; i++) {\n if (ds[i] === 0 || ds[i - 1] === 0 || ds[i - 1] > 0 !== ds[i] > 0) {\n ms[i] = 0;\n } else {\n ms[i] =\n (3 * (dxs[i - 1] + dxs[i])) /\n ((2 * dxs[i] + dxs[i - 1]) / ds[i - 1] +\n (dxs[i] + 2 * dxs[i - 1]) / ds[i]);\n\n if (!isFinite(ms[i])) {\n ms[i] = 0;\n }\n }\n }\n\n // Now build a path from the slopes\n const path = new SvgPath().move(xs[0], ys[0], false, valueData[0]);\n\n for (let i = 0; i < n - 1; i++) {\n path.curve(\n // First control point\n xs[i] + dxs[i] / 3,\n ys[i] + (ms[i] * dxs[i]) / 3,\n // Second control point\n xs[i + 1] - dxs[i] / 3,\n ys[i + 1] - (ms[i + 1] * dxs[i]) / 3,\n // End point\n xs[i + 1],\n ys[i + 1],\n\n false,\n valueData[i + 1]\n );\n }\n\n return path;\n }\n };\n}\n","/**\n * Scene nodes: the renderer-independent tree that v2 charts produce.\n * Nodes are immutable. Builder methods keep the 1.x `Svg` names but return\n * a new node and share every field they don't change.\n *\n * @experimental The v2 API may change until v2.0.\n */\n\nimport type { NodeRole, NodeRoles } from './roles';\n\n/**\n * The value of a node attribute. Numbers are written as they are, e.g.\n * `x1=\"12.5\"`.\n */\nexport type AttrValue = string | number;\n\n/**\n * Data attached to a node without a role, e.g. by a plugin. Never rendered.\n * Any fields are allowed; the ones below have a meaning to Chartist.\n */\nexport interface NodeContext {\n /**\n * The index of the series the node belongs to. With it, the node gets a\n * `key` and {@link findAll} can find it by series.\n */\n readonly seriesIndex?: number;\n /** The index of the value in its series the node stands for. */\n readonly valueIndex?: number;\n /** The value the node stands for. */\n readonly value?: unknown;\n /** The `meta` of the value or series, as given in the data. */\n readonly meta?: unknown;\n /** Any other data you want to keep with the node. */\n readonly [key: string]: unknown;\n}\n\n/**\n * What a node means, next to how it looks: its key, role and data\n * context. None of it is rendered.\n */\nexport interface NodeMeta {\n /** A stable id, e.g. `0/1/3` (layer, series, value). */\n readonly key?: string;\n /** What the node draws, e.g. `point` or `bar`: a key of {@link NodeRoles}. */\n readonly role?: NodeRole;\n /** The node's data: what its role declares, or anything for plain nodes. */\n readonly ctx?: object;\n}\n\n/** The fields every node has, whatever its role. */\nexport interface SceneNodeFields {\n /** SVG element name, e.g. `g`, `path`, `line`. */\n readonly name: string;\n /**\n * The element's attributes, without `class`. Names with a `ct:` prefix\n * (`ct:value`, `ct:meta`) are written in the Chartist namespace.\n */\n readonly attrs: Readonly<Record<string, AttrValue>>;\n /** The element's class names, each once, in the order they were added. */\n readonly classes: readonly string[];\n /** The child nodes, in document order. */\n readonly children: readonly SceneNode[];\n /** Text content, set with `text()`. */\n readonly content?: string;\n /**\n * A stable id that survives updates. The pipeline keys data nodes that\n * have none: `layer/series/value` for a value's node (e.g. `0/1/3`),\n * `layer/series` for a series' node.\n */\n readonly key?: string;\n}\n\n/**\n * The builder methods of every node. Each returns a changed copy of the\n * same type and leaves the node it's called on as it was.\n */\nexport interface SceneNodeMethods {\n /** Sets attributes; `undefined` or `null` removes one. */\n attr(attributes: Record<string, AttrValue | undefined | null>): this;\n /** Adds space-separated class names that aren't present yet. */\n addClass(names: string): this;\n /** Removes space-separated class names. */\n removeClass(names: string): this;\n /** Adds a child at the end, or at the start with `insertFirst`. */\n append(child: SceneNode, insertFirst?: boolean): this;\n /** Removes a direct child (by identity). */\n remove(child: SceneNode): this;\n /** Replaces a direct child (by identity). */\n replace(child: SceneNode, next: SceneNode): this;\n /** Sets the text content. */\n text(content: string): this;\n /** Removes all children and text content. */\n empty(): this;\n}\n\n/**\n * A node of a role, such as `RoleNode<'point'>`: its context and\n * attributes are the ones {@link NodeRoles} declares for that role.\n * {@link findAll} with a `role` returns these.\n */\nexport type RoleNode<R extends NodeRole> = SceneNodeFields &\n SceneNodeMethods & {\n /** What the node draws, e.g. `point`. */\n readonly role: R;\n /**\n * The node's data, as its role declares it. `seriesIndex` and\n * `valueIndex` read as `number | undefined` on any node, declared or\n * not.\n */\n readonly ctx: NodeRoles[R]['ctx'] & {\n readonly seriesIndex?: number;\n readonly valueIndex?: number;\n };\n /**\n * The element's attributes, typed as the built-in layers set them;\n * `attr()` can change them.\n */\n readonly attrs: Readonly<Record<string, AttrValue>> & NodeRoles[R]['attrs'];\n };\n\n/** A node without a role: groups, decorations, anything a plugin adds. */\nexport type PlainNode = SceneNodeFields &\n SceneNodeMethods & {\n /** Always absent: plain nodes have no role. */\n readonly role?: undefined;\n /** Data you attach to the node, if any. */\n readonly ctx?: NodeContext;\n };\n\n/**\n * A scene node: a node of one of the roles in {@link NodeRoles}, or a plain\n * one. Check `role` to narrow it, e.g. `if (node.role === 'point') node.ctx.x`.\n *\n * Nodes are immutable: the builder methods ({@link SceneNodeMethods}) return\n * a new node. The `compose` and `scene` phase events pass nodes to your\n * listeners, and the renderers turn them into SVG.\n */\nexport type SceneNode = { [R in NodeRole]: RoleNode<R> }[NodeRole] | PlainNode;\n\nconst splitClasses = (names: string) => names.split(/\\s+/).filter(Boolean);\n\n/** The node fields as stored, for copying. */\ntype StoredFields = SceneNodeFields & NodeMeta;\n\nconst builder: SceneNodeMethods = {\n attr(this: SceneNode, attributes) {\n const attrs: Record<string, AttrValue> = { ...this.attrs };\n for (const [name, value] of Object.entries(attributes)) {\n if (value === undefined || value === null) {\n delete attrs[name];\n } else {\n attrs[name] = value;\n }\n }\n return withFields(this as SceneNode, { attrs });\n },\n addClass(this: SceneNode, names) {\n const added = splitClasses(names).filter(\n (name, i, all) => !this.classes.includes(name) && all.indexOf(name) === i\n );\n return added.length\n ? withFields(this as SceneNode, { classes: [...this.classes, ...added] })\n : this;\n },\n removeClass(this: SceneNode, names) {\n const removed = splitClasses(names);\n return withFields(this as SceneNode, {\n classes: this.classes.filter(name => !removed.includes(name))\n });\n },\n append(this: SceneNode, child, insertFirst = false) {\n return withFields(this as SceneNode, {\n children: insertFirst\n ? [child, ...this.children]\n : [...this.children, child]\n });\n },\n remove(this: SceneNode, child) {\n return withFields(this as SceneNode, {\n children: this.children.filter(existing => existing !== child)\n });\n },\n replace(this: SceneNode, child, next) {\n return withFields(this as SceneNode, {\n children: this.children.map(existing =>\n existing === child ? next : existing\n )\n });\n },\n text(this: SceneNode, content) {\n return withFields(this as SceneNode, { content });\n },\n empty(this: SceneNode) {\n return withFields(this as SceneNode, { children: [], content: undefined });\n }\n};\n\nfunction create(fields: StoredFields): SceneNode {\n const created = Object.create(builder) as SceneNode;\n for (const [field, value] of Object.entries(fields)) {\n if (value !== undefined) {\n (created as unknown as Record<string, unknown>)[field] = value;\n }\n }\n return created;\n}\n\n/**\n * Copies a node with some fields replaced. Shares all other fields. The\n * copy has the source's type unless the changes give it another role.\n */\nexport function withFields<T extends SceneNode>(\n source: T,\n changes: Partial<Omit<SceneNodeFields, 'attrs'>> & {\n readonly attrs?: Readonly<Record<string, AttrValue>>;\n }\n): T;\nexport function withFields<R extends NodeRole>(\n source: SceneNode,\n changes: Partial<SceneNodeFields> & {\n readonly role: R;\n /** Indexes read as `number | undefined` on any node, declared or not. */\n readonly ctx: NodeRoles[R]['ctx'] & {\n readonly seriesIndex?: number;\n readonly valueIndex?: number;\n };\n }\n): RoleNode<R>;\nexport function withFields(\n source: SceneNode,\n changes: Partial<StoredFields>\n): SceneNode {\n return create({ ...(source as StoredFields), ...changes });\n}\n\n/**\n * What {@link node} takes as `meta` for a node of role `R`: the role, a key,\n * and the role's context (required when the role declares fields).\n */\nexport type RoleMeta<R extends NodeRole> = {\n /** The node's role, e.g. `point`. */\n readonly role: R;\n /** A stable id; the pipeline sets one for data nodes that have none. */\n readonly key?: string;\n} & (object extends NodeRoles[R]['ctx']\n ? { readonly ctx?: NodeRoles[R]['ctx'] }\n : { readonly ctx: NodeRoles[R]['ctx'] });\n\n/**\n * Creates a scene node: an SVG element with attributes and classes, and,\n * for a node with a role, its data context. Use it in `compose` listeners\n * and custom layers to add or replace elements. With a `role` in `meta`,\n * the node is typed as that role's node and the context is checked.\n *\n * @param name SVG element name, e.g. `circle`, `g` or `text`\n * @param attributes Attributes; `undefined` and `null` values are skipped\n * @param className Space-separated class names\n * @param meta Role, data context and key of the node\n * @returns A new node without children\n * @example\n * ```ts\n * import { lineChart, node } from 'chartist';\n *\n * // Circles instead of the line chart's points.\n * lineChart(\n * '#chart',\n * { series: [[1, 3, 2, 4]] },\n * {\n * plugins: [\n * {\n * name: 'circles',\n * install(chart) {\n * chart.on('compose', current => {\n * if (current.role !== 'point') {\n * return;\n * }\n * const { x, y } = current.ctx;\n * return node('circle', { cx: x, cy: y, r: 5 }, 'ct-circle', {\n * role: 'point',\n * ctx: current.ctx,\n * key: current.key\n * });\n * });\n * }\n * }\n * ]\n * }\n * );\n * ```\n */\nexport function node<R extends NodeRole>(\n name: string,\n attributes: Record<string, AttrValue | undefined | null>,\n className: string,\n meta: RoleMeta<R>\n): RoleNode<R>;\nexport function node(\n name: string,\n attributes?: Record<string, AttrValue | undefined | null>,\n className?: string,\n meta?: { readonly key?: string; readonly ctx?: NodeContext }\n): PlainNode;\nexport function node(\n name: string,\n attributes: Record<string, AttrValue | undefined | null> = {},\n className = '',\n meta: NodeMeta = {}\n): SceneNode {\n const attrs: Record<string, AttrValue> = {};\n for (const [attr, value] of Object.entries(attributes)) {\n if (value !== undefined && value !== null) {\n attrs[attr] = value;\n }\n }\n return create({\n name,\n attrs,\n classes: [...new Set(splitClasses(className))],\n children: [],\n ...meta\n });\n}\n","/**\n * Line layer: points, line and area per series, drawn like 1.x\n * `LineChart` (element order, classes and `ct:` attributes).\n */\nimport { getMetaData } from '../core/data/data';\nimport { alphaNumerate } from '../core/lang';\nimport { serialize } from '../core/data/serialize';\nimport type {\n NormalizedSeries,\n SegmentData,\n Series,\n SeriesObject\n} from '../core/types';\nimport { monotoneCubic } from '../interpolation/monotoneCubic';\nimport { none } from '../interpolation/none';\nimport type { LineInterpolation } from '../charts/LineChart/LineChart.types';\nimport type { Layer, PreparedSeries } from '../pipeline/types';\nimport { node, withFields, type SceneNode } from '../scene/node';\nimport { isNumeric, safeHasProperty } from '../utils/utils';\n\n/**\n * The line options you can set per series: in the `overrides` of\n * {@link line}, or the `series` option of `lineChart`.\n */\nexport interface LineSeriesOptions {\n /**\n * How a line runs between its points: `true` smooths it with\n * `Interpolation.monotoneCubic`, `false` draws straight segments\n * (`Interpolation.none`), or pass an interpolation such as\n * `Interpolation.cardinal()`, `Interpolation.step()` or your own.\n */\n readonly lineSmooth?: boolean | LineInterpolation;\n /** Draws a point at each value. */\n readonly showPoint?: boolean;\n /** Draws the lines. */\n readonly showLine?: boolean;\n /** Fills the area between each line and `areaBase`. */\n readonly showArea?: boolean;\n /**\n * The value the areas close at, usually 0. It's kept within the Y axis\n * range.\n */\n readonly areaBase?: number;\n}\n\n/**\n * The options of the {@link line} layer. Without them, it draws every\n * series as a smooth line with points and no area, on the first X and Y\n * axis.\n * @experimental\n */\nexport interface LineLayerOptions extends LineSeriesOptions {\n /** Series to draw, by index or name; default: all series. */\n readonly series?: readonly (number | string)[];\n /** The id of the X axis to draw on; default: the first X axis. */\n readonly x?: string;\n /** The id of the Y axis to draw on; default: the first Y axis. */\n readonly y?: string;\n /**\n * Point position on a step axis: `start` of each step (1.x) or its\n * `center`, where bars are centered.\n */\n readonly align?: 'start' | 'center';\n /** Option overrides per series name (the 1.x `series` option). */\n readonly overrides?: Readonly<Record<string, LineSeriesOptions>>;\n /**\n * Draws the series in reverse order (1.x `reverseData`). Can't be\n * combined with `series`.\n */\n readonly reverseData?: boolean;\n /**\n * Replaces the classes of what the layer draws: `series` (`ct-series`),\n * `line` (`ct-line`), `point` (`ct-point`) and `area` (`ct-area`).\n */\n readonly classNames?: {\n readonly series?: string;\n readonly line?: string;\n readonly point?: string;\n readonly area?: string;\n };\n}\n\nconst DEFAULTS = {\n lineSmooth: true,\n showPoint: true,\n showLine: true,\n showArea: false,\n areaBase: 0\n};\n\nconst CLASS_NAMES = {\n series: 'ct-series',\n line: 'ct-line',\n point: 'ct-point',\n area: 'ct-area'\n};\n\n/** The raw series as passed in the chart data (1.x reads names and meta from it). */\nfunction rawSeries(series: PreparedSeries): Series | SeriesObject {\n return {\n name: series.name,\n className: series.className,\n meta: series.meta,\n data: series.values\n } as SeriesObject;\n}\n\nfunction seriesOption<K extends keyof LineSeriesOptions>(\n series: Series | SeriesObject,\n options: LineLayerOptions,\n key: K\n): NonNullable<LineSeriesOptions[K]> {\n const fallback = (options[key] ?? DEFAULTS[key]) as NonNullable<\n LineSeriesOptions[K]\n >;\n if (\n safeHasProperty(series, 'name') &&\n series.name &&\n options.overrides?.[series.name]\n ) {\n const value = options.overrides[series.name][key];\n return (value === undefined ? fallback : value) as NonNullable<\n LineSeriesOptions[K]\n >;\n }\n return fallback;\n}\n\n/**\n * Creates a layer that draws series as lines, with points and optional\n * areas, in the markup of the 1.x line chart (`g.ct-series` with\n * `path.ct-line`, `line.ct-point` and `path.ct-area`). It needs an X and a\n * Y axis, from {@link cartesianAxes}.\n *\n * @example\n * ```ts\n * import {\n * autoScaleAxis,\n * axisGrid,\n * axisLabels,\n * cartesianAxes,\n * chart,\n * line,\n * stepAxis\n * } from 'chartist';\n *\n * const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];\n *\n * chart('#chart', {\n * data: {\n * labels: days,\n * series: [\n * { name: 'visits', data: [12, 9, 7, 8, 5] },\n * { name: 'sales', data: [2, 1, 3.5, 7, 3] }\n * ]\n * },\n * axes: cartesianAxes([\n * { id: 'day', side: 'bottom', type: stepAxis(), ticks: days },\n * { id: 'count', side: 'left', type: autoScaleAxis(), low: 0 }\n * ]),\n * layers: [\n * axisGrid(),\n * line({ showArea: true, overrides: { sales: { showArea: false } } }),\n * axisLabels()\n * ]\n * });\n * ```\n * @experimental\n */\nexport function line(options: LineLayerOptions = {}): Layer {\n const classNames = { ...CLASS_NAMES, ...options.classNames };\n return {\n type: 'line',\n coordinates: ['cartesian'],\n axes: { x: options.x, y: options.y },\n series: options.series,\n compose({ data, area, axes, normalized, seriesIndexes }) {\n const { x: axisX, y: axisY } = axes;\n if (!axisX || !axisY || !normalized) {\n throw new Error('Layer \"line\" needs an x and a y axis');\n }\n if (seriesIndexes && options.reverseData) {\n throw new Error(\n 'Layer \"line\": a series selection can\\'t be combined with reverseData'\n );\n }\n // Centered points sit where bars are centered on a step axis.\n const shift =\n options.align === 'center' && axisX.kind === 'step' && !axisX.stretch\n ? (axisX.step ?? 0) / 2\n : 0;\n const order = data.series.map((_, i) => i);\n if (options.reverseData) {\n order.reverse();\n }\n\n return order.map((dataIndex, localIndex) => {\n // The chart-wide index, for classes, keys and contexts.\n const seriesIndex = seriesIndexes?.[dataIndex] ?? localIndex;\n const series = rawSeries(data.series[dataIndex]);\n const values = normalized.series[localIndex] as NormalizedSeries;\n const seriesName = safeHasProperty(series, 'name') && series.name;\n const seriesClassName =\n safeHasProperty(series, 'className') && series.className;\n const seriesMeta = safeHasProperty(series, 'meta')\n ? series.meta\n : undefined;\n\n const pathCoordinates: number[] = [];\n const pathData: SegmentData[] = [];\n values.forEach((value, valueIndex) => {\n pathCoordinates.push(\n area.x1 + shift + axisX.project(value, valueIndex, values),\n area.y1 - axisY.project(value, valueIndex, values)\n );\n pathData.push({\n value,\n valueIndex,\n meta: getMetaData(series, valueIndex)\n });\n });\n\n const lineSmooth = seriesOption(series, options, 'lineSmooth');\n const smoothing =\n typeof lineSmooth === 'function'\n ? lineSmooth\n : lineSmooth\n ? monotoneCubic()\n : none();\n const path = smoothing(pathCoordinates, pathData);\n const seriesContext = { series, seriesIndex, meta: seriesMeta };\n\n let children: SceneNode[] = [];\n\n if (seriesOption(series, options, 'showPoint')) {\n children = path.pathElements.map(pathElement => {\n const { data: pathElementData } = pathElement;\n const value = pathElementData?.value;\n const x = safeHasProperty(value, 'x') ? value.x : undefined;\n const y = safeHasProperty(value, 'y') ? value.y : undefined;\n return node(\n 'line',\n {\n x1: pathElement.x,\n y1: pathElement.y,\n x2: pathElement.x + 0.01,\n y2: pathElement.y,\n ...(pathElementData && {\n 'ct:value': [x, y].filter(isNumeric).join(','),\n 'ct:meta': serialize(pathElementData.meta) as\n | string\n | undefined\n })\n },\n classNames.point,\n {\n role: 'point',\n ctx: {\n ...seriesContext,\n valueIndex: pathElementData?.valueIndex || 0,\n value,\n meta: pathElementData?.meta,\n x: pathElement.x,\n y: pathElement.y\n }\n }\n );\n });\n }\n\n if (seriesOption(series, options, 'showLine')) {\n children = [\n node('path', { d: path.stringify() }, classNames.line, {\n role: 'line',\n ctx: { ...seriesContext, values, path: path.clone() }\n }),\n ...children\n ];\n }\n\n if (seriesOption(series, options, 'showArea') && axisY.range) {\n const areaBase = Math.max(\n Math.min(\n seriesOption(series, options, 'areaBase'),\n axisY.range.max\n ),\n axisY.range.min\n );\n const areaBaseProjected = area.y1 - axisY.project(areaBase);\n path\n .splitByCommand('M')\n .filter(segment => segment.pathElements.length > 1)\n .map(segment => {\n const first = segment.pathElements[0];\n const last =\n segment.pathElements[segment.pathElements.length - 1];\n return segment\n .clone(true)\n .position(0)\n .remove(1)\n .move(first.x, areaBaseProjected)\n .line(first.x, first.y)\n .position(segment.pathElements.length + 1)\n .line(last.x, areaBaseProjected);\n })\n .forEach(areaPath => {\n children = [\n node('path', { d: areaPath.stringify() }, classNames.area, {\n role: 'area',\n ctx: { ...seriesContext, values, path: areaPath.clone() }\n }),\n ...children\n ];\n });\n }\n\n const group = node(\n 'g',\n {\n 'ct:series-name': seriesName || undefined,\n 'ct:meta': seriesMeta\n ? (serialize(seriesMeta) as string)\n : undefined\n },\n `${classNames.series} ${\n seriesClassName ||\n `${classNames.series}-${alphaNumerate(seriesIndex)}`\n }`,\n { role: 'series', ctx: seriesContext }\n );\n return withFields(group, { children });\n });\n }\n };\n}\n","/**\n * v2 axes: plain objects created by factories. Same scale math as the 1.x\n * axis classes; see stepAxis, autoScaleAxis and fixedScaleAxis.\n */\nimport type {\n AxisOptions,\n ChartPadding,\n Label,\n NormalizedSeries,\n NormalizedSeriesPrimitiveValue\n} from '../core/types';\nimport type {\n Area,\n Layer,\n NormalizedChartData,\n PreparedData\n} from '../pipeline/types';\n\n/** Which way an axis runs: `x` (horizontal) or `y` (vertical). */\nexport type AxisDimension = 'x' | 'y';\n\n/** Where an axis sits: `top`/`bottom` are X axes, `left`/`right` Y axes. */\nexport type AxisSide = 'top' | 'bottom' | 'left' | 'right';\n\n/**\n * What an {@link AxisFactory} gets to create an axis: its direction, the\n * data, the chart area and the axis options.\n */\nexport interface AxisContext {\n /** Which way the axis runs: `x` or `y`, from its side. */\n readonly dimension: AxisDimension;\n /**\n * Normalized multi-value series (`{ x, y }` values): the series bound to\n * the axis, or all of them.\n */\n readonly series: NormalizedSeries[];\n /** Normalized labels, padded to the longest series. */\n readonly labels: readonly Label[];\n /** The chart area in px, with the offsets of all axes reserved. */\n readonly area: Area;\n /** The options of the axis definition, without `id`, `side` and `type`. */\n readonly options: AxisOptions;\n /**\n * The range the layers drawn on the axis need beyond their values, such\n * as the sums of stacked bars (see {@link Layer.extent}). Scale axes\n * include it in the range they fit to the data; their own `low` and\n * `high` still win.\n */\n readonly extent?: AxisExtent;\n}\n\n/**\n * A range of values on an axis, from `low` to `high`: what a layer reports\n * in {@link Layer.extent}.\n * @experimental\n */\nexport interface AxisExtent {\n /** The lowest value. */\n readonly low: number;\n /** The highest value. */\n readonly high: number;\n}\n\n/**\n * A positioned axis: ticks, range and projection into px along the axis.\n * An {@link AxisFactory} creates it once the chart area is known; layers\n * read it to place what they draw.\n * @experimental\n */\nexport interface ScaleAxis {\n /** Which way the axis runs: `x` or `y`. */\n readonly dimension: AxisDimension;\n /** The axis type, e.g. `step`, `autoScale`, `fixedScale`. */\n readonly kind: string;\n /** Step axes: whether the last tick sits at the axis end. */\n readonly stretch?: boolean;\n /** Step axes: the distance between two ticks in px. */\n readonly step?: number;\n /**\n * The values at which grid lines and labels are drawn: labels on a step\n * axis, numbers on a scale.\n */\n readonly ticks: readonly Label[];\n /**\n * The values at the axis start (`min`) and end (`max`). Step axes have\n * none.\n */\n readonly range?: { readonly min: number; readonly max: number };\n /** Axis length in px. */\n readonly length: number;\n /**\n * Places a value on the axis: the distance in px from the axis start\n * (left, or bottom for y). Step axes place by `index` instead.\n */\n project(\n value: NormalizedSeriesPrimitiveValue | Label,\n index?: number,\n series?: NormalizedSeries\n ): number;\n}\n\n/**\n * An axis type: creates the axis once the chart area and data are known.\n * {@link stepAxis}, {@link autoScaleAxis} and {@link fixedScaleAxis} return\n * one; write your own for a scale they don't cover. It goes in the `type`\n * of an axis.\n * @experimental\n */\nexport interface AxisFactory {\n /**\n * The axis type, e.g. `step`. The axis it creates has the same `kind`;\n * the line and bar layers center on `step` axes.\n */\n readonly kind: string;\n /**\n * Creates the axis for a chart area and data. Runs on every layout, so\n * after resizes too.\n */\n create(context: AxisContext): ScaleAxis;\n}\n\n/** A 1.x axis class (or a custom subclass of the 1.x `Axis`). */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type LegacyAxisClass = abstract new (...args: any[]) => unknown;\n\n/**\n * An axis's setup: an axis type plus the 1.x axis options (`offset`,\n * `low`, `high`, `ticks`, `showGrid`, …).\n */\nexport interface AxisSetup extends Omit<AxisOptions, 'type'> {\n /** A v2 axis factory, or a 1.x axis class. */\n readonly type: AxisFactory | LegacyAxisClass;\n}\n\n/**\n * An axis of a composed chart, in the list form of {@link cartesianAxes}:\n * an id that layers bind to, a side, a type and the 1.x axis options.\n * @experimental\n */\nexport interface AxisDefinition extends AxisSetup {\n /**\n * Names the axis, for the `x` and `y` of layers and the `axes` of\n * {@link axisGrid} and {@link axisLabels}. Ids must be unique.\n */\n readonly id: string;\n /**\n * Where the axis sits: `bottom` or `top` makes an X axis, `left` or\n * `right` a Y axis. Axes on the same side stack outward in list order.\n */\n readonly side: AxisSide;\n}\n\n/**\n * The config of {@link cartesianAxes}: one X and one Y axis in the 1.x\n * form, or a list of axes, plus how the data is read.\n */\nexport interface AxesConfig {\n /**\n * The X axis in the 1.x form: at the bottom, or the top with\n * `position: 'start'`. Its `offset` defaults to 30 px.\n */\n readonly x?: AxisSetup;\n /**\n * The Y axis in the 1.x form: on the left, or the right with\n * `position: 'end'`. Its `offset` defaults to 40 px.\n */\n readonly y?: AxisSetup;\n /** The axis list form; used instead of `x`/`y`. */\n readonly axes?: readonly AxisDefinition[];\n /** Reverse labels and series before projecting (1.x `reverseData`). */\n readonly reverseData?: boolean;\n /**\n * How values are normalized (1.x `normalizeData`): `multi` is `true` for\n * `{ x, y }` values, or the dimension single values go to; `distributed`\n * turns a flat series into one series per value.\n */\n readonly normalize?: {\n readonly multi?: true | AxisDimension;\n readonly distributed?: boolean;\n };\n}\n\n/**\n * A created axis with its place in the chart: what the axis layers draw,\n * and what a layer finds in `axes.all`.\n */\nexport interface PlacedScaleAxis extends ScaleAxis {\n /** The axis id: from its definition, or `x` and `y` in the 1.x form. */\n readonly id: string;\n /** The side the axis sits on. */\n readonly side: AxisSide;\n /** Distance in px from the chart area to this axis's band (stacking). */\n readonly inset: number;\n /** The axis options (offset, labels, grid), without the type. */\n readonly options: Omit<AxisSetup, 'type'>;\n}\n\n/** The axes of a laid-out chart. */\nexport interface ChartAxes {\n /** The X axis (for layers: the bound one; for the chart: the first). */\n readonly x?: ScaleAxis;\n /** The Y axis (for layers: the bound one; for the chart: the first). */\n readonly y?: ScaleAxis;\n /** All axes of the chart, in declaration order. */\n readonly all?: readonly PlacedScaleAxis[];\n}\n\n/**\n * Axes for a chart's `axes` option, created by {@link cartesianAxes}. The\n * pipeline asks them for the chart area and, after `layout`, to create the\n * axes. Charts without axes don't bundle any of this.\n * @experimental\n */\nexport interface CartesianAxes {\n /** The config the axes were created from, with the default offsets filled in. */\n readonly config: AxesConfig;\n /** The chart area with the axis offsets reserved. */\n area(\n width: number,\n height: number,\n padding: ChartPadding\n ): { width: number; height: number; area: Area };\n /** The axis definitions, in declaration order. */\n readonly definitions: readonly AxisDefinition[];\n /**\n * Each layer's axis ids and series selection, checked against the data.\n * Without it, every layer draws all series on the first X and Y axis.\n */\n bind?(layers: readonly Layer[], data: PreparedData): LayerBinding[];\n /**\n * The axes for the final chart area, and the data as they see it. With\n * `bindings`, each axis's range comes only from the series bound to it.\n * With `layers`, it also covers the extents they report (see\n * {@link Layer.extent}).\n */\n create(\n data: PreparedData,\n area: Area,\n bindings?: readonly LayerBinding[],\n layers?: readonly Layer[]\n ): { axes: ChartAxes; normalized: NormalizedChartData };\n}\n\n/** How a layer is bound: its axis ids and series indexes. */\nexport interface LayerBinding {\n /** The id of the X axis the layer draws on. */\n readonly x?: string;\n /** The id of the Y axis the layer draws on. */\n readonly y?: string;\n /** Selected series indexes; undefined means all. */\n readonly series?: readonly number[];\n}\n\nexport const directionOf = (side: AxisSide): AxisDimension =>\n side === 'top' || side === 'bottom' ? 'x' : 'y';\n\n/**\n * The `{ x, y }` shorthand as definitions, with sides from the 1.x\n * `position`: X at the bottom unless `'start'`, Y on the left unless\n * `'end'`.\n */\nexport function definitionsOf(config: AxesConfig): readonly AxisDefinition[] {\n if (config.axes) {\n return config.axes;\n }\n const definitions: AxisDefinition[] = [];\n if (config.x) {\n definitions.push({\n ...config.x,\n id: 'x',\n side: config.x.position === 'start' ? 'top' : 'bottom'\n });\n }\n if (config.y) {\n definitions.push({\n ...config.y,\n id: 'y',\n side: config.y.position === 'end' ? 'right' : 'left'\n });\n }\n return definitions;\n}\n\n/** Per axis, the summed offsets of the axes before it on the same side. */\nexport function insetsOf(definitions: readonly AxisDefinition[]) {\n const sums: Record<AxisSide, number> = {\n top: 0,\n bottom: 0,\n left: 0,\n right: 0\n };\n return definitions.map(definition => {\n const inset = sums[definition.side];\n sums[definition.side] += definition.offset || 0;\n return inset;\n });\n}\n\nexport function axisLength(dimension: AxisDimension, area: Area) {\n return dimension === 'x' ? area.x2 - area.x1 : area.y1 - area.y2;\n}\n\n/**\n * The chart area for a chart with axes, as 1.x `createChartRect` computes\n * it, generalized to several axes per side: the offsets per side are\n * summed, and the area is at least 1 px.\n */\nexport function axisArea(\n width: number,\n height: number,\n padding: ChartPadding,\n axes: AxesConfig | readonly AxisDefinition[]\n): { width: number; height: number; area: Area } {\n const definitions = Array.isArray(axes)\n ? (axes as readonly AxisDefinition[])\n : definitionsOf(axes as AxesConfig);\n const sum: Record<AxisSide, number> = {\n top: 0,\n bottom: 0,\n left: 0,\n right: 0\n };\n for (const definition of definitions) {\n sum[definition.side] += definition.offset || 0;\n }\n const w = Math.max(\n width,\n sum.left + sum.right + padding.left + padding.right\n );\n const h = Math.max(\n height,\n sum.top + sum.bottom + padding.top + padding.bottom\n );\n const y2 = padding.top + sum.top;\n const y1 = Math.max(h - padding.bottom - sum.bottom, y2 + 1);\n const x1 = padding.left + sum.left;\n const x2 = Math.max(w - padding.right - sum.right, x1 + 1);\n return {\n width: w,\n height: h,\n area: { x1, y1, x2, y2, width: x2 - x1, height: y1 - y2 }\n };\n}\n\nexport type { NormalizedSeriesPrimitiveValue };\n","import type {\n Label,\n ChartRect,\n OptionsWithDefaults,\n NormalizedSeriesPrimitiveValue,\n NormalizedSeries\n} from '../core';\nimport type { Svg } from '../svg';\nimport type { EventEmitter } from '../event';\nimport { isFalseyButZero } from '../utils';\nimport { createGrid, createLabel } from '../core';\n\n/** The names an axis uses per dimension: its position, length and direction, and its edges in the {@link ChartRect}. */\nexport const axisUnits = {\n x: {\n pos: 'x',\n len: 'width',\n dir: 'horizontal',\n rectStart: 'x1',\n rectEnd: 'x2',\n rectOffset: 'y2'\n },\n y: {\n pos: 'y',\n len: 'height',\n dir: 'vertical',\n rectStart: 'y2',\n rectEnd: 'y1',\n rectOffset: 'x1'\n }\n} as const;\n\n/** The units of the X axis: `axisUnits.x`. */\nexport type XAxisUnits = typeof axisUnits.x;\n/** The units of the Y axis: `axisUnits.y`. */\nexport type YAxisUnits = typeof axisUnits.y;\n/** The units of either axis. */\nexport type AxisUnits = XAxisUnits | YAxisUnits;\n\n/**\n * The base class of the 1.x axes: projects values to px along the drawing\n * area and draws its grid lines and labels.\n *\n * @deprecated Use the scale functions `autoScaleAxis()`, `fixedScaleAxis()` and `stepAxis()`. Removed in 3.0.\n */\nexport abstract class Axis {\n public readonly counterUnits: AxisUnits;\n public readonly range:\n | {\n min: number;\n max: number;\n }\n | undefined;\n readonly axisLength: number;\n private readonly gridOffset: number;\n\n constructor(\n public readonly units: AxisUnits,\n private readonly chartRect: ChartRect,\n private readonly ticks: Label[]\n ) {\n this.counterUnits = units === axisUnits.x ? axisUnits.y : axisUnits.x;\n this.axisLength =\n chartRect[this.units.rectEnd] - chartRect[this.units.rectStart];\n this.gridOffset = chartRect[this.units.rectOffset];\n }\n\n abstract projectValue(\n value: NormalizedSeriesPrimitiveValue | Label,\n index?: number,\n series?: NormalizedSeries\n ): number;\n\n createGridAndLabels(\n gridGroup: Svg,\n labelGroup: Svg,\n chartOptions: OptionsWithDefaults,\n eventEmitter: EventEmitter\n ) {\n const axisOptions =\n this.units.pos === 'x' ? chartOptions.axisX : chartOptions.axisY;\n const projectedValues = this.ticks.map((tick, i) =>\n this.projectValue(tick, i)\n );\n const labelValues = this.ticks.map(axisOptions.labelInterpolationFnc);\n\n projectedValues.forEach((projectedValue, index) => {\n const labelValue = labelValues[index];\n const labelOffset = {\n x: 0,\n y: 0\n };\n\n // TODO: Find better solution for solving this problem\n // Calculate how much space we have available for the label\n let labelLength;\n if (index + 1 < projectedValues.length) {\n // If we still have one label ahead, we can calculate the distance to the next tick / label\n labelLength = projectedValues[index + 1] - projectedValue;\n } else {\n // If we don't have a label ahead and we have only two labels in total, we just take the remaining distance to\n // on the whole axis length. We limit that to a minimum of 30 pixel, so that labels close to the border will\n // still be visible inside of the chart padding.\n labelLength = Math.max(\n this.axisLength - projectedValue,\n this.axisLength / this.ticks.length\n );\n }\n\n // Skip grid lines and labels where interpolated label values are falsey (except for 0)\n if (labelValue !== '' && isFalseyButZero(labelValue)) {\n return;\n }\n\n // Transform to global coordinates using the chartRect\n // We also need to set the label offset for the createLabel function\n if (this.units.pos === 'x') {\n projectedValue = this.chartRect.x1 + projectedValue;\n labelOffset.x = chartOptions.axisX.labelOffset.x;\n\n // If the labels should be positioned in start position (top side for vertical axis) we need to set a\n // different offset as for positioned with end (bottom)\n if (chartOptions.axisX.position === 'start') {\n labelOffset.y =\n this.chartRect.padding.top + chartOptions.axisX.labelOffset.y + 5;\n } else {\n labelOffset.y =\n this.chartRect.y1 + chartOptions.axisX.labelOffset.y + 5;\n }\n } else {\n projectedValue = this.chartRect.y1 - projectedValue;\n labelOffset.y = chartOptions.axisY.labelOffset.y - labelLength;\n\n // If the labels should be positioned in start position (left side for horizontal axis) we need to set a\n // different offset as for positioned with end (right side)\n if (chartOptions.axisY.position === 'start') {\n labelOffset.x =\n this.chartRect.padding.left + chartOptions.axisY.labelOffset.x;\n } else {\n labelOffset.x =\n this.chartRect.x2 + chartOptions.axisY.labelOffset.x + 10;\n }\n }\n\n if (axisOptions.showGrid) {\n createGrid(\n projectedValue,\n index,\n this,\n this.gridOffset,\n this.chartRect[this.counterUnits.len](),\n gridGroup,\n [\n chartOptions.classNames.grid,\n chartOptions.classNames[this.units.dir]\n ],\n eventEmitter\n );\n }\n\n if (axisOptions.showLabel) {\n createLabel(\n projectedValue,\n labelLength,\n index,\n labelValue,\n this,\n axisOptions.offset,\n labelOffset,\n labelGroup,\n [\n chartOptions.classNames.label,\n chartOptions.classNames[this.units.dir],\n axisOptions.position === 'start'\n ? chartOptions.classNames[axisOptions.position]\n : chartOptions.classNames.end\n ],\n eventEmitter\n );\n }\n });\n }\n}\n","import { axisUnits } from '../axes/Axis';\nimport { getHighLow } from '../core/data/highLow';\nimport type { ChartRect, Label, Options } from '../core/types';\nimport { axisLength, type AxisFactory, type LegacyAxisClass } from './axis';\n\ninterface LegacyAxisInstance {\n ticks: Label[];\n stretch?: boolean;\n stepLength?: number;\n range?: { min: number; max: number };\n projectValue(value: unknown, index?: number, series?: unknown): number;\n}\n\n/** True for 1.x axis classes and custom subclasses of the 1.x `Axis`. */\nexport function isLegacyAxisClass(type: unknown): type is LegacyAxisClass {\n return (\n typeof type === 'function' &&\n typeof (type as { prototype?: { projectValue?: unknown } }).prototype\n ?.projectValue === 'function'\n );\n}\n\n/**\n * Wraps a 1.x axis class as a factory: constructs it with the 1.x\n * arguments and uses its ticks, range and projection.\n */\nexport function legacyAxis(type: LegacyAxisClass): AxisFactory {\n return {\n kind: 'legacy',\n create({ dimension, series, area, options, extent }) {\n const chartRect: ChartRect = {\n x1: area.x1,\n x2: area.x2,\n y1: area.y1,\n y2: area.y2,\n padding: { top: 0, right: 0, bottom: 0, left: 0 },\n width: () => area.x2 - area.x1,\n height: () => area.y1 - area.y2\n };\n // 1.x classes fit their scale to `highLow` when given, so an extent\n // reaches them as the range it widens.\n const legacyOptions =\n extent && !options.highLow\n ? {\n ...options,\n highLow: getHighLow(series, options as Options, dimension, extent)\n }\n : options;\n const instance = new (type as unknown as new (\n ...args: unknown[]\n ) => LegacyAxisInstance)(\n axisUnits[dimension],\n series,\n chartRect,\n legacyOptions\n );\n return {\n dimension,\n // 1.x positions bars by `instanceof StepAxis`; step axes have `stretch`.\n kind: typeof instance.stretch === 'boolean' ? 'step' : 'legacy',\n stretch: instance.stretch,\n step: instance.stepLength,\n ticks: instance.ticks,\n range: instance.range,\n length: axisLength(dimension, area),\n project: (value, index, values) =>\n instance.projectValue(value, index, values)\n };\n }\n };\n}\n","import { normalizeData } from '../core/data/normalize';\nimport type { ChartPadding, Data, NormalizedSeries } from '../core/types';\nimport type {\n Area,\n Layer,\n NormalizedChartData,\n PreparedData\n} from '../pipeline/types';\nimport {\n axisArea,\n definitionsOf,\n directionOf,\n insetsOf,\n type AxesConfig,\n type AxisDefinition,\n type AxisExtent,\n type AxisSetup,\n type CartesianAxes,\n type LayerBinding,\n type PlacedScaleAxis\n} from './axis';\nimport { isLegacyAxisClass, legacyAxis } from './legacy';\n\n/** Resolves every layer's axis ids and series selection. */\nfunction bindLayers(\n definitions: readonly AxisDefinition[],\n layers: readonly Layer[],\n data: PreparedData\n): LayerBinding[] {\n const firstOf = (dimension: 'x' | 'y') =>\n definitions.find(d => directionOf(d.side) === dimension)?.id;\n const ids = new Set(definitions.map(d => d.id));\n return layers.map(layer => {\n for (const id of [layer.axes?.x, layer.axes?.y]) {\n if (id !== undefined && !ids.has(id)) {\n throw new Error(\n `Chartist: unknown axis \"${id}\" in layer \"${layer.type}\"`\n );\n }\n }\n const series = layer.series?.map(selector => {\n const index =\n typeof selector === 'number'\n ? selector\n : data.series.findIndex(s => s.name === selector);\n if (index < 0 || index >= data.series.length) {\n throw new Error(\n `Chartist: unknown series ${JSON.stringify(selector)} in layer \"${layer.type}\"`\n );\n }\n return index;\n });\n return {\n x: layer.axes?.x ?? firstOf('x'),\n y: layer.axes?.y ?? firstOf('y'),\n series\n };\n });\n}\n\n/**\n * The series indexes bound to each axis id. Axes no series layer is bound\n * to are missing, so they cover all series.\n */\nfunction boundSeries(\n bindings: readonly LayerBinding[],\n seriesCount: number\n): Map<string, number[]> {\n const all = Array.from({ length: seriesCount }, (_, i) => i);\n const bound = new Map<string, Set<number>>();\n for (const binding of bindings) {\n // Layers without series (grids, labels) don't shape axis ranges.\n if (binding.series?.length === 0) {\n continue;\n }\n for (const id of [binding.x, binding.y]) {\n if (id === undefined) {\n continue;\n }\n const set = bound.get(id) ?? new Set<number>();\n (binding.series ?? all).forEach(i => set.add(i));\n bound.set(id, set);\n }\n }\n return new Map(\n [...bound].map(([id, set]) => [id, [...set].sort((a, b) => a - b)])\n );\n}\n\n/** The data as axes see it: multi values, padded labels, optional reverse. */\nfunction normalizeForAxes(\n data: PreparedData,\n reverse = false,\n normalize: AxesConfig['normalize'] = {}\n): NormalizedChartData {\n const raw = {\n labels: data.labels,\n series: data.series.map(series => ({\n name: series.name,\n className: series.className,\n meta: series.meta,\n data: series.values\n }))\n } as unknown as Data;\n // A flat series (e.g. distributed bars) stays flat for normalizeData.\n const input = data.flat\n ? ({\n labels: data.labels,\n series: data.series[0].values\n } as unknown as Data)\n : raw;\n const normalized = normalizeData(\n input,\n reverse,\n normalize.multi ?? true,\n normalize.distributed as true\n );\n return {\n labels: normalized.labels,\n series: normalized.series as NormalizedSeries[]\n };\n}\n\n/**\n * The extents the layers report, merged per axis id: each axis gets the\n * range that covers every layer's extent on it.\n */\nfunction layerExtents(\n definitions: readonly AxisDefinition[],\n layers: readonly Layer[],\n bindings: readonly LayerBinding[],\n data: PreparedData,\n normalized: NormalizedChartData\n): Map<string, AxisExtent> {\n const firstOf = (dimension: 'x' | 'y') =>\n definitions.find(d => directionOf(d.side) === dimension)?.id;\n const merged = new Map<string, AxisExtent>();\n layers.forEach((layer, index) => {\n if (!layer.extent) {\n return;\n }\n const binding = bindings[index] ?? {};\n // As in compose: a flat series isn't split by a selection.\n const selection = data.flat ? undefined : binding.series;\n const reported = layer.extent({\n normalized: selection\n ? { ...normalized, series: selection.map(i => normalized.series[i]) }\n : normalized,\n axes: { x: binding.x ?? firstOf('x'), y: binding.y ?? firstOf('y') }\n });\n for (const [id, extent] of Object.entries(reported ?? {})) {\n const current = merged.get(id);\n merged.set(\n id,\n current\n ? {\n low: Math.min(current.low, extent.low),\n high: Math.max(current.high, extent.high)\n }\n : extent\n );\n }\n });\n return merged;\n}\n\nfunction createAxis(\n definition: AxisDefinition,\n inset: number,\n series: NormalizedSeries[],\n normalized: NormalizedChartData,\n area: Area,\n extent: AxisExtent | undefined\n): PlacedScaleAxis {\n const { type, id, side, ...options } = definition;\n const factory = isLegacyAxisClass(type) ? legacyAxis(type) : type;\n const axis = factory.create({\n dimension: directionOf(side),\n series,\n labels: normalized.labels,\n area,\n options,\n ...(extent && { extent })\n });\n return { ...axis, id, side, inset, options };\n}\n\n/**\n * The axes of a `{ x, y }` config, without layer binding: what presets use.\n * `cartesianAxes()` adds the binding, so presets don't bundle it.\n * @internal\n */\nexport function presetAxes(\n config: AxesConfig,\n boundOf?: typeof boundSeries\n): CartesianAxes {\n const definitions = definitionsOf(config);\n const insets = insetsOf(definitions);\n return {\n config,\n definitions,\n area: (width: number, height: number, padding: ChartPadding) =>\n axisArea(width, height, padding, definitions),\n create(data, area, bindings, layers) {\n const bound = bindings && boundOf?.(bindings, data.series.length);\n const normalized = normalizeForAxes(\n data,\n config.reverseData,\n config.normalize\n );\n const extents = layers\n ? layerExtents(definitions, layers, bindings ?? [], data, normalized)\n : undefined;\n const allSeries = normalized.series as NormalizedSeries[];\n const all = definitions.map((definition, index) => {\n const indexes = bound?.get(definition.id);\n const series =\n indexes && !data.flat ? indexes.map(i => allSeries[i]) : allSeries;\n return createAxis(\n definition,\n insets[index],\n series,\n normalized,\n area,\n extents?.get(definition.id)\n );\n });\n return {\n normalized,\n axes: {\n x: all.find(axis => axis.dimension === 'x'),\n y: all.find(axis => axis.dimension === 'y'),\n all\n }\n };\n }\n };\n}\n\n/**\n * Creates the axes for the `axes` option of {@link chart}: a list of axes,\n * each with an `id`, a `side` and a `type`, several per side if needed.\n * Axis types are v2 factories ({@link stepAxis}, {@link autoScaleAxis},\n * {@link fixedScaleAxis}) or 1.x axis classes; the other fields are the\n * 1.x axis options (`offset`, `low`, `high`, `ticks`, …).\n *\n * Layers pick their axes by id, and each axis scales to the series of the\n * layers drawn on it. Offsets default to 30 px for X axes and 40 px for Y\n * axes, and axes on the same side stack outward in list order. Unknown or\n * duplicate ids throw.\n *\n * The 1.x-style `{ x, y }` form also works, with the same defaults: X at\n * the bottom unless its `position` is `'start'`, Y on the left unless\n * it's `'end'`.\n *\n * @example\n * ```ts\n * import {\n * autoScaleAxis,\n * axisGrid,\n * axisLabels,\n * bar,\n * cartesianAxes,\n * chart,\n * line,\n * stepAxis\n * } from 'chartist';\n *\n * const months = ['Jan', 'Feb', 'Mar', 'Apr'];\n *\n * chart('#chart', {\n * data: {\n * labels: months,\n * series: [\n * { name: 'eur', data: [120, 180, 150, 210] },\n * { name: 'usd', data: [130, 195, 160, 230] }\n * ]\n * },\n * axes: cartesianAxes([\n * { id: 'month', side: 'bottom', type: stepAxis(), ticks: months },\n * // Both on the left: 'eur' next to the chart, 'usd' outside it.\n * { id: 'eur', side: 'left', type: autoScaleAxis(), low: 0 },\n * { id: 'usd', side: 'left', type: autoScaleAxis(), low: 0, offset: 50 }\n * ]),\n * layers: [\n * axisGrid({ axes: ['month', 'eur'] }),\n * bar({ series: ['eur'], y: 'eur' }),\n * line({ series: ['usd'], y: 'usd', align: 'center' }),\n * axisLabels()\n * ],\n * className: 'ct-chart-bar'\n * });\n * ```\n * @param input The axes: a list of {@link AxisDefinition}s, or the 1.x\n * `{ x, y }` form.\n * @param extra `reverseData` and `normalize`, for the list form (the\n * `{ x, y }` form takes them inline).\n * @experimental\n */\nexport function cartesianAxes(\n input: AxesConfig | readonly AxisDefinition[],\n extra: Pick<AxesConfig, 'reverseData' | 'normalize'> = {}\n): CartesianAxes {\n // Both forms get the 1.x default offsets (30 px for X, 40 px for Y).\n const withOffset = <T extends AxisSetup>(\n setup: T,\n dimension: 'x' | 'y'\n ): T => ({ ...setup, offset: setup.offset ?? (dimension === 'x' ? 30 : 40) });\n const given: AxesConfig = Array.isArray(input)\n ? { ...extra, axes: input as readonly AxisDefinition[] }\n : { ...extra, ...(input as AxesConfig) };\n const config: AxesConfig = given.axes\n ? {\n ...given,\n axes: given.axes.map(definition =>\n withOffset(definition, directionOf(definition.side))\n )\n }\n : {\n ...given,\n x: given.x && withOffset(given.x, 'x'),\n y: given.y && withOffset(given.y, 'y')\n };\n const axes = presetAxes(config, boundSeries);\n const ids = new Set<string>();\n for (const { id } of axes.definitions) {\n if (ids.has(id)) {\n throw new Error(`Chartist: the axis id \"${id}\" is used twice`);\n }\n ids.add(id);\n }\n return {\n ...axes,\n bind: (layers, data) => bindLayers(axes.definitions, layers, data)\n };\n}\n","import { getBounds } from '../core/data/bounds';\nimport { getMultiValue } from '../core/data/data';\nimport { getHighLow } from '../core/data/highLow';\nimport type { NormalizedSeriesPrimitiveValue, Options } from '../core/types';\nimport { times } from '../utils/functional';\nimport { axisLength, type AxisFactory } from './axis';\n\nconst valueOf = (value: unknown, dimension: 'x' | 'y') =>\n Number(getMultiValue(value as NormalizedSeriesPrimitiveValue, dimension));\n\n/**\n * Creates a step axis: evenly spaced ticks, one per step, that place\n * values by their index rather than by their value. It's the label axis of\n * line and bar charts. Same rules as 1.x `StepAxis`.\n *\n * Its ticks are the data's `labels`, or the axis's `ticks` when you give\n * them. With `stretch`, the last tick sits at the axis end.\n *\n * @example\n * ```ts\n * import {\n * autoScaleAxis,\n * axisGrid,\n * axisLabels,\n * cartesianAxes,\n * chart,\n * line,\n * stepAxis\n * } from 'chartist';\n *\n * const months = ['Jan', 'Feb', 'Mar', 'Apr'];\n *\n * chart('#chart', {\n * data: { labels: months, series: [[4, 6, 5, 9]] },\n * axes: cartesianAxes([\n * // The months as ticks; stretch: the first and last at the edges.\n * { id: 'month', side: 'bottom', type: stepAxis(), stretch: true },\n * { id: 'value', side: 'left', type: autoScaleAxis() }\n * ]),\n * layers: [axisGrid(), line(), axisLabels()]\n * });\n * ```\n * @experimental\n */\nexport function stepAxis(): AxisFactory {\n return {\n kind: 'step',\n create({ dimension, area, labels, options }) {\n const ticks = options.ticks ?? [...labels];\n const length = axisLength(dimension, area);\n const stepLength =\n length / Math.max(1, ticks.length - (options.stretch ? 1 : 0));\n return {\n dimension,\n kind: 'step',\n stretch: Boolean(options.stretch),\n step: stepLength,\n ticks,\n length,\n project: (_value, index = 0) => stepLength * index\n };\n }\n };\n}\n\n/**\n * Creates an auto-scaled axis: a scale fitted to the data, with round\n * ticks at least `scaleMinSpace` px apart. Set `low`, `high` or\n * `referenceValue` to widen it, and `onlyInteger` for whole-number steps.\n * Same rules as 1.x `AutoScaleAxis`.\n *\n * It's the value axis of line and bar charts. As an X axis, it places\n * `{ x, y }` values at their real distances.\n *\n * @example\n * ```ts\n * import {\n * autoScaleAxis,\n * axisGrid,\n * axisLabels,\n * cartesianAxes,\n * chart,\n * line\n * } from 'chartist';\n *\n * chart('#chart', {\n * data: {\n * series: [\n * [\n * { x: 1, y: 2 },\n * { x: 2.5, y: 5 },\n * { x: 7, y: 3 },\n * { x: 10, y: 8 }\n * ]\n * ]\n * },\n * axes: cartesianAxes([\n * { id: 'x', side: 'bottom', type: autoScaleAxis(), onlyInteger: true },\n * { id: 'y', side: 'left', type: autoScaleAxis(), low: 0 }\n * ]),\n * layers: [axisGrid(), line(), axisLabels()]\n * });\n * ```\n * @experimental\n */\nexport function autoScaleAxis(): AxisFactory {\n return {\n kind: 'autoScale',\n create({ dimension, series, area, options, extent }) {\n const length = axisLength(dimension, area);\n const highLow =\n options.highLow ||\n getHighLow(series, options as Options, dimension, extent);\n const bounds = getBounds(\n length,\n highLow,\n options.scaleMinSpace || 20,\n options.onlyInteger\n );\n return {\n dimension,\n kind: 'autoScale',\n ticks: bounds.values,\n range: { min: bounds.min, max: bounds.max },\n length,\n project: value =>\n (length * (valueOf(value, dimension) - bounds.min)) / bounds.range\n };\n }\n };\n}\n\n/**\n * Creates a fixed-scale axis: a scale from `low` to `high` (by default the\n * smallest and largest value) with the `ticks` you give. Without `ticks`,\n * `divisor` splits the range into equal parts with a tick at each end, so\n * `divisor: 4` makes 5 ticks from `low` to `high` (1.x left out the one\n * at `high`).\n *\n * @example\n * ```ts\n * import {\n * axisGrid,\n * axisLabels,\n * cartesianAxes,\n * chart,\n * fixedScaleAxis,\n * line,\n * stepAxis\n * } from 'chartist';\n *\n * const teams = ['Red', 'Blue', 'Green'];\n *\n * chart('#chart', {\n * data: { labels: teams, series: [[64, 81, 47]] },\n * axes: cartesianAxes([\n * { id: 'team', side: 'bottom', type: stepAxis(), ticks: teams },\n * // A percentage scale with three grid lines.\n * {\n * id: 'percent',\n * side: 'left',\n * type: fixedScaleAxis(),\n * ticks: [0, 50, 100],\n * low: 0,\n * high: 100\n * }\n * ]),\n * layers: [axisGrid(), line({ showLine: false }), axisLabels()]\n * });\n * ```\n * @experimental\n */\nexport function fixedScaleAxis(): AxisFactory {\n return {\n kind: 'fixedScale',\n create({ dimension, series, area, options, extent }) {\n const length = axisLength(dimension, area);\n const highLow =\n options.highLow ||\n getHighLow(series, options as Options, dimension, extent);\n const divisor = options.divisor || 1;\n // `divisor` parts have `divisor + 1` ends, `high` included (#1022).\n const ticks = (\n options.ticks ||\n times(\n divisor + 1,\n index =>\n highLow.low + ((highLow.high - highLow.low) / divisor) * index\n )\n ).sort((a, b) => Number(a) - Number(b));\n const range = { min: highLow.low, max: highLow.high };\n return {\n dimension,\n kind: 'fixedScale',\n ticks,\n range,\n length,\n project: value =>\n (length * (valueOf(value, dimension) - range.min)) /\n (range.max - range.min)\n };\n }\n };\n}\n","import { noop } from '../utils/functional';\n\n/**\n * The 1.x `LineChart` default options. The 1.x class keeps its own copy until\n * it becomes a wrapper over `lineChart`.\n */\nexport const lineDefaults = {\n axisX: {\n offset: 30,\n position: 'end' as const,\n labelOffset: { x: 0, y: 0 },\n showLabel: true,\n showGrid: true,\n labelInterpolationFnc: noop,\n type: undefined\n },\n axisY: {\n offset: 40,\n position: 'start' as const,\n labelOffset: { x: 0, y: 0 },\n showLabel: true,\n showGrid: true,\n labelInterpolationFnc: noop,\n type: undefined,\n scaleMinSpace: 20,\n onlyInteger: false\n },\n width: undefined,\n height: undefined,\n showLine: true,\n showPoint: true,\n showArea: false,\n areaBase: 0,\n lineSmooth: true,\n showGridBackground: false,\n low: undefined,\n high: undefined,\n chartPadding: { top: 15, right: 15, bottom: 5, left: 10 },\n fullWidth: false,\n reverseData: false,\n classNames: {\n chart: 'ct-chart-line',\n label: 'ct-label',\n labelGroup: 'ct-labels',\n series: 'ct-series',\n line: 'ct-line',\n point: 'ct-point',\n area: 'ct-area',\n grid: 'ct-grid',\n gridGroup: 'ct-grids',\n gridBackground: 'ct-grid-background',\n vertical: 'ct-vertical',\n horizontal: 'ct-horizontal',\n start: 'ct-start',\n end: 'ct-end'\n }\n};\n","/**\n * Event emitter for pipeline phases. Listeners transform a phase by\n * returning a new value; `undefined` keeps the current one. Created by a\n * factory, state lives in the closure.\n */\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyListener = (value: any) => unknown;\nexport type WildcardListener = (name: string, value: unknown) => void;\n\n/**\n * Who added a listener: a plugin while it installs, or the chart's user\n * (config `on`, the handle's `on`). `off(name)` without a listener removes\n * only the user's, so it never breaks a plugin.\n */\nexport type ListenerOwner = 'plugin' | 'user';\n\nexport interface PhaseEmitter {\n on(name: '*', listener: WildcardListener, owner?: ListenerOwner): void;\n on(name: string, listener: AnyListener, owner?: ListenerOwner): void;\n /**\n * Removes `listener`, whoever added it, or without a listener, every\n * listener of the event that the user added.\n */\n off(name: '*', listener?: WildcardListener): void;\n off(name: string, listener?: AnyListener): void;\n /**\n * Runs the listeners in registration order, each receiving the previous\n * result. `null` ends the chain (the value is dropped). `'*'` listeners\n * observe the final value.\n */\n transform<T>(name: string, value: T): T | null;\n /** Runs the listeners and ignores their return values. */\n notify(name: string, value: unknown): void;\n /** Removes every listener, plugins' too. */\n clear(): void;\n}\n\ninterface Entry<T> {\n readonly listener: T;\n readonly owner: ListenerOwner;\n}\n\n/** The entries without `listener`, or without the user's ones. */\nfunction without<T>(entries: readonly Entry<T>[], listener?: T) {\n return entries.filter(entry =>\n listener ? entry.listener !== listener : entry.owner !== 'user'\n );\n}\n\nexport function createPhaseEmitter(): PhaseEmitter {\n const listeners = new Map<string, Entry<AnyListener>[]>();\n let wildcards: Entry<WildcardListener>[] = [];\n\n function observe(name: string, value: unknown) {\n wildcards.forEach(({ listener }) => listener(name, value));\n }\n\n return {\n on(\n name: string,\n listener: AnyListener | WildcardListener,\n owner: ListenerOwner = 'user'\n ) {\n if (name === '*') {\n wildcards = [\n ...wildcards,\n { listener: listener as WildcardListener, owner }\n ];\n } else {\n listeners.set(name, [\n ...(listeners.get(name) ?? []),\n { listener: listener as AnyListener, owner }\n ]);\n }\n },\n off(name: string, listener?: AnyListener | WildcardListener) {\n if (name === '*') {\n wildcards = without(wildcards, listener as WildcardListener);\n } else {\n listeners.set(\n name,\n without(listeners.get(name) ?? [], listener as AnyListener)\n );\n }\n },\n transform<T>(name: string, value: T): T | null {\n let current: T | null = value;\n for (const { listener } of listeners.get(name) ?? []) {\n const result = listener(current) as T | null | undefined;\n if (result === null) {\n current = null;\n break;\n }\n if (result !== undefined) {\n current = result;\n }\n }\n observe(name, current);\n return current;\n },\n notify(name: string, value: unknown) {\n (listeners.get(name) ?? []).forEach(({ listener }) => listener(value));\n observe(name, value);\n },\n clear() {\n listeners.clear();\n wildcards = [];\n }\n };\n}\n","import { withFields, type RoleNode, type SceneNode } from './node';\nimport type { NodeRole } from './roles';\n\n/**\n * What {@link findAll} looks for: nodes by role, key and data context\n * fields. A node matches when it matches every field given; an empty query\n * matches every node.\n */\nexport interface NodeQuery {\n /** Only nodes of this role, e.g. `bar`. */\n readonly role?: NodeRole;\n /** Only the node with this key, e.g. `0/1/3` (layer, series, value). */\n readonly key?: string;\n /** Only nodes of the series with this index (`ctx.seriesIndex`). */\n readonly seriesIndex?: number;\n /** Only nodes of the value with this index (`ctx.valueIndex`). */\n readonly valueIndex?: number;\n}\n\nfunction matches(candidate: SceneNode, query: NodeQuery) {\n return (\n (query.role === undefined || candidate.role === query.role) &&\n (query.key === undefined || candidate.key === query.key) &&\n (query.seriesIndex === undefined ||\n candidate.ctx?.seriesIndex === query.seriesIndex) &&\n (query.valueIndex === undefined ||\n candidate.ctx?.valueIndex === query.valueIndex)\n );\n}\n\n/**\n * Finds all nodes of a scene that match the query, in document order, the\n * root included. With a `role`, the nodes are typed as that role's nodes.\n *\n * @param scene The root of the tree to search, e.g. the `scene` payload\n * @param query The fields to match; without one, every node matches\n * @example\n * ```ts\n * import { barChart, findAll } from 'chartist';\n *\n * barChart(\n * '#chart',\n * { labels: ['Q1', 'Q2', 'Q3', 'Q4'], series: [[5, 4, 3, 7]] },\n * {\n * plugins: [\n * {\n * name: 'log-bars',\n * install(chart) {\n * chart.on('scene', ({ scene }) => {\n * for (const bar of findAll(scene, { role: 'bar' })) {\n * console.log(bar.key, bar.ctx.value, bar.ctx.y2);\n * }\n * });\n * }\n * }\n * ]\n * }\n * );\n * ```\n * @experimental\n */\nexport function findAll<R extends NodeRole>(\n scene: SceneNode,\n query: NodeQuery & { readonly role: R }\n): RoleNode<R>[];\nexport function findAll(scene: SceneNode, query?: NodeQuery): SceneNode[];\nexport function findAll(scene: SceneNode, query: NodeQuery = {}): SceneNode[] {\n const found: SceneNode[] = [];\n const visit = (current: SceneNode) => {\n if (matches(current, query)) {\n found.push(current);\n }\n current.children.forEach(visit);\n };\n visit(scene);\n return found;\n}\n\n/**\n * Maps a tree bottom-up: children first, then their parent with the mapped\n * children. Return a node to replace, `null` to drop, or `undefined` to\n * keep. Subtrees without changes are reused, not copied.\n *\n * @param scene The root of the tree to map\n * @param mapper Called once per node, with the node's mapped children\n * @returns The mapped tree, or `null` if the mapper dropped the root\n * @example\n * ```ts\n * import {\n * autoScaleAxis,\n * axisGrid,\n * cartesianAxes,\n * line,\n * mapNodes,\n * renderToString,\n * stepAxis,\n * toScene\n * } from 'chartist';\n *\n * const labels = ['Mon', 'Tue', 'Wed'];\n * const scene = toScene(\n * {\n * data: { labels, series: [[1, 3, 2]] },\n * axes: cartesianAxes([\n * { id: 'x', side: 'bottom', type: stepAxis(), ticks: labels },\n * { id: 'y', side: 'left', type: autoScaleAxis() }\n * ]),\n * layers: [axisGrid(), line()]\n * },\n * { width: 600, height: 300 }\n * );\n *\n * // No grid lines, and the points marked for the stylesheet.\n * const mapped = mapNodes(scene, current => {\n * if (current.role === 'grid') {\n * return null;\n * }\n * if (current.role === 'point') {\n * return current.addClass('is-marked');\n * }\n * });\n * const markup = mapped ? renderToString(mapped) : '';\n * ```\n * @experimental\n */\nexport function mapNodes(\n scene: SceneNode,\n mapper: (current: SceneNode) => SceneNode | null | undefined | void\n): SceneNode | null {\n let children = scene.children as SceneNode[];\n let changed = false;\n const mapped: SceneNode[] = [];\n for (const child of children) {\n const result = mapNodes(child, mapper);\n if (result !== child) {\n changed = true;\n }\n if (result) {\n mapped.push(result);\n }\n }\n if (changed) {\n children = mapped;\n }\n const current = changed ? withFields(scene, { children }) : scene;\n const result = mapper(current);\n return result === undefined ? current : result;\n}\n\n/**\n * Keys data nodes that have none: `layer/series/value` for nodes with a\n * series and value index, `layer/series` for nodes with only a series.\n */\nexport function assignKeys(scene: SceneNode, layerIndex: number): SceneNode {\n return mapNodes(scene, current => {\n const seriesIndex = current.ctx?.seriesIndex;\n if (current.key !== undefined || seriesIndex === undefined) {\n return undefined;\n }\n const valueIndex = current.ctx?.valueIndex;\n return withFields(current, {\n key:\n valueIndex === undefined\n ? `${layerIndex}/${seriesIndex}`\n : `${layerIndex}/${seriesIndex}/${valueIndex}`\n });\n }) as SceneNode;\n}\n","import type { ChartPadding } from '../core/types';\nimport type { LabelMode, MeasureStyle, MeasureText } from '../render/measure';\nimport type { CartesianAxes, ChartAxes, LayerBinding } from '../scales/axis';\nimport { node, withFields, type SceneNode } from '../scene/node';\nimport { assignKeys, mapNodes } from '../scene/tree';\nimport type { PhaseEmitter } from './emitter';\nimport type {\n Area,\n ChartData,\n Coordinates,\n Layer,\n Layout,\n NormalizedChartData,\n PreparedData,\n PreparedSeries,\n ResolvedConfig\n} from './types';\n\n/** The 1.x default `chartPadding`. */\nexport const DEFAULT_PADDING: ChartPadding = {\n top: 15,\n right: 15,\n bottom: 5,\n left: 10\n};\n\n/** Options accepted by the pipeline (a chart config without listeners). */\nexport interface PipelineOptions {\n /** The labels and series to draw. */\n readonly data: ChartData;\n /** What to draw, in this order (later layers on top), e.g. `[axisGrid(), line()]`. */\n readonly layers: readonly Layer[];\n /**\n * The coordinate system the layers draw in: `cartesian` (the default)\n * for axes, `polar` for `pie()`.\n */\n readonly coordinates?: Coordinates;\n /**\n * Space in px between the chart's edge and the drawing area: one number\n * for all sides, or some sides (the others keep the 1.x defaults).\n */\n readonly padding?: number | Partial<ChartPadding>;\n /** Axes (see `cartesianAxes`); their offsets are reserved around the area. */\n readonly axes?: CartesianAxes;\n /**\n * The chart's width: px as a number, or a CSS length such as `100%` or\n * `20rem`. Without it, `chart()` fills the container's width.\n */\n readonly width?: number | string;\n /**\n * The chart's height: px as a number, or a CSS length such as `300px`.\n * Without it, `chart()` fills the container's height.\n */\n readonly height?: number | string;\n /** Fixed drawing coordinates; sets the layout size and the root `viewBox`. */\n readonly viewBox?: { readonly width: number; readonly height: number };\n /** Class names for the root svg, e.g. `ct-chart-line` for the 1.x line chart CSS. */\n readonly className?: string;\n /**\n * Draws labels as HTML in `foreignObject` (1.x) or as SVG `text`. The\n * default depends on the renderer: `html` for the DOM, `svg` in\n * `toScene()`.\n */\n readonly labels?: LabelMode;\n /** The preset that created the chart, if any (read by plugins). */\n readonly preset?: ResolvedConfig['preset'];\n}\n\nexport interface PipelineEnvironment {\n /** Layout size in px. */\n readonly width: number;\n readonly height: number;\n readonly measureText: MeasureText;\n /** Reads computed styles for layout; absent without a DOM. */\n readonly measureStyle?: MeasureStyle;\n /** The renderer's default label mode; `html` if omitted. */\n readonly labels?: LabelMode;\n /** Size attributes of the root svg; defaults to the layout size. */\n readonly rootSize?: { width: number | string; height: number | string };\n}\n\n/** Results of the phases, cached so a resize can re-run from `layout`. */\nexport interface PipelineState {\n readonly config: ResolvedConfig;\n readonly data: PreparedData;\n readonly layout: Layout;\n readonly axes: ChartAxes;\n readonly normalized?: NormalizedChartData;\n readonly scene: SceneNode;\n}\n\nfunction normalizePadding(\n padding: number | Partial<ChartPadding> | undefined\n): ChartPadding {\n if (typeof padding === 'number') {\n return { top: padding, right: padding, bottom: padding, left: padding };\n }\n return { ...DEFAULT_PADDING, ...padding };\n}\n\nfunction check<T>(value: T | null, phase: string): T {\n if (value === null || value === undefined) {\n throw new Error(`Chartist: a \"${phase}\" listener returned null`);\n }\n return value;\n}\n\nexport function resolve(\n emitter: PhaseEmitter,\n options: PipelineOptions\n): ResolvedConfig {\n const config: ResolvedConfig = {\n data: options.data,\n layers: options.layers,\n coordinates: options.coordinates ?? 'cartesian',\n padding: normalizePadding(options.padding),\n axes: options.axes,\n width: options.width,\n height: options.height,\n viewBox: options.viewBox,\n className: options.className,\n labels: options.labels,\n preset: options.preset\n };\n const resolved = check(\n emitter.transform('resolve', { config }),\n 'resolve'\n ).config;\n for (const layer of resolved.layers) {\n if (!layer.coordinates.includes(resolved.coordinates)) {\n throw new Error(\n `Layer \"${layer.type}\" does not support ${resolved.coordinates} coordinates`\n );\n }\n }\n return resolved;\n}\n\nfunction prepareSeries(series: unknown): PreparedSeries {\n if (Array.isArray(series)) {\n return { values: series };\n }\n if (series && typeof series === 'object' && 'data' in series) {\n const { data, name, className, meta } = series as {\n data: readonly unknown[];\n name?: string;\n className?: string;\n meta?: unknown;\n };\n return { name, className, meta, values: data };\n }\n return { values: [series] };\n}\n\n/**\n * Normalizes series into `{ values }` objects. A flat series (no arrays or\n * series objects, e.g. pie data) becomes one series with all values.\n */\nexport function prepare(\n emitter: PhaseEmitter,\n config: ResolvedConfig\n): PreparedData {\n const { labels = [], series } = config.data;\n const flat = series.every(\n entry =>\n !Array.isArray(entry) &&\n !(entry && typeof entry === 'object' && 'data' in entry)\n );\n const data: PreparedData =\n flat && series.length\n ? { labels, series: [{ values: series }], flat: true }\n : { labels, series: series.map(prepareSeries) };\n return check(emitter.transform('prepare', { data }), 'prepare').data;\n}\n\nfunction validate(result: Layout) {\n const { area } = result;\n const values = [\n result.width,\n result.height,\n area.x1,\n area.x2,\n area.y1,\n area.y2,\n area.width,\n area.height\n ];\n if (!values.every(Number.isFinite) || area.width < 0 || area.height < 0) {\n throw new Error(\n `Chartist: invalid layout after the \"layout\" phase (area ${JSON.stringify(area)})`\n );\n }\n}\n\nexport function layout(\n emitter: PhaseEmitter,\n config: ResolvedConfig,\n width: number,\n height: number\n): Layout {\n const { padding } = config;\n let initial: Layout;\n if (config.axes) {\n initial = { ...config.axes.area(width, height, padding), padding };\n } else {\n // The 1.x `createChartRect` minimums: at least the padding, 1 px area.\n const w = Math.max(width, padding.left + padding.right);\n const h = Math.max(height, padding.top + padding.bottom);\n const x1 = padding.left;\n const y2 = padding.top;\n const x2 = Math.max(w - padding.right, x1 + 1);\n const y1 = Math.max(h - padding.bottom, y2 + 1);\n const area: Area = { x1, y1, x2, y2, width: x2 - x1, height: y1 - y2 };\n initial = { width: w, height: h, padding, area };\n }\n const result = check(emitter.transform('layout', initial), 'layout');\n validate(result);\n return result;\n}\n\nexport function compose(\n emitter: PhaseEmitter,\n config: ResolvedConfig,\n data: PreparedData,\n area: Area,\n measureText: MeasureText,\n axes: ChartAxes = {},\n normalized?: NormalizedChartData,\n padding: ChartPadding = config.padding,\n bindings: readonly LayerBinding[] = [],\n labels: LabelMode = 'html',\n measureStyle?: MeasureStyle\n): SceneNode[] {\n const composed: SceneNode[] = [];\n const byId = new Map((axes.all ?? []).map(axis => [axis.id, axis]));\n config.layers.forEach((layer, layerIndex) => {\n const binding = bindings[layerIndex] ?? {};\n const selection = data.flat ? undefined : binding.series;\n const layerData = selection\n ? { ...data, series: selection.map(i => data.series[i]) }\n : data;\n const layerNormalized =\n selection && normalized\n ? {\n ...normalized,\n series: selection.map(i => normalized.series[i])\n }\n : normalized;\n const nodes = layer.compose({\n data: layerData,\n area,\n padding,\n layerIndex,\n coordinates: config.coordinates,\n measureText,\n axes: {\n x: (binding.x && byId.get(binding.x)) || axes.x,\n y: (binding.y && byId.get(binding.y)) || axes.y,\n all: axes.all\n },\n normalized: layerNormalized,\n seriesIndexes: selection,\n labels,\n measureStyle\n });\n for (const top of nodes) {\n const result = mapNodes(assignKeys(top, layerIndex), current =>\n current.role === undefined\n ? undefined\n : emitter.transform('compose', current)\n );\n if (result) {\n composed.push(result);\n }\n }\n });\n return composed;\n}\n\nexport function scene(\n emitter: PhaseEmitter,\n config: ResolvedConfig,\n children: readonly SceneNode[],\n size: { width: number | string; height: number | string }\n): SceneNode {\n const root = node(\n 'svg',\n {\n width: size.width,\n height: size.height,\n viewBox: config.viewBox\n ? `0 0 ${config.viewBox.width} ${config.viewBox.height}`\n : undefined\n },\n config.className\n );\n const built = children.length ? withFields(root, { children }) : root;\n return check(emitter.transform('scene', { scene: built }), 'scene').scene;\n}\n\n/**\n * Runs the phases `resolve` to `scene`. With a previous state and\n * `from: 'layout'`, `resolve` and `prepare` are reused.\n */\nexport function runPipeline(\n emitter: PhaseEmitter,\n options: PipelineOptions,\n environment: PipelineEnvironment,\n previous?: PipelineState,\n from: 'resolve' | 'layout' = 'resolve'\n): PipelineState {\n const reuse = from === 'layout' && previous;\n const config = reuse ? previous.config : resolve(emitter, options);\n const data = reuse ? previous.data : prepare(emitter, config);\n const laidOut = layout(\n emitter,\n config,\n environment.width,\n environment.height\n );\n // Axis ids and series selections; only cartesian axes bind layers.\n const bindings = config.axes?.bind?.(config.layers, data) ?? [];\n // The layers go along for the extents they report (stacked bars).\n const { axes = {}, normalized = undefined } =\n config.axes?.create(data, laidOut.area, bindings, config.layers) ?? {};\n // Measure with the root classes, so chart-type CSS applies.\n const { className } = config;\n const withRootClass = <T extends MeasureText | MeasureStyle | undefined>(\n measure: T\n ): T =>\n (className && measure\n ? (value: string, measureOptions?: object) =>\n measure(value, { rootClass: className, ...measureOptions })\n : measure) as T;\n const measureText = withRootClass(environment.measureText);\n const measureStyle = withRootClass(environment.measureStyle);\n const children = compose(\n emitter,\n config,\n data,\n laidOut.area,\n measureText,\n axes,\n normalized,\n laidOut.padding,\n bindings,\n config.labels ?? environment.labels ?? 'html',\n measureStyle\n );\n const built = scene(\n emitter,\n config,\n children,\n environment.rootSize ?? {\n width: config.width ?? laidOut.width,\n height: config.height ?? laidOut.height\n }\n );\n return { config, data, layout: laidOut, axes, normalized, scene: built };\n}\n","/** The size of a measured text, as a {@link MeasureText} function returns it. */\nexport interface TextMetrics {\n /** The text's width in px. */\n readonly width: number;\n /** The text's height in px: one line. */\n readonly height: number;\n /** The font size in px the text was measured with, when known. */\n readonly fontSize?: number;\n}\n\n/**\n * How labels are drawn: HTML in a `foreignObject` (1.x) or SVG `text`.\n * @experimental\n */\nexport type LabelMode = 'html' | 'svg';\n\n/** What a {@link MeasureText} function gets with the text to measure. */\nexport interface MeasureTextOptions {\n /** Class names of the text, for renderers that apply CSS. */\n readonly classes?: readonly string[];\n /**\n * Font size in px. Without it, the browser measures with the CSS font\n * size and the estimate uses 12, the size of 1.x `.ct-label`.\n */\n readonly fontSize?: number;\n /** Classes of the chart's root svg, so chart-type CSS applies. */\n readonly rootClass?: string;\n /** Where to measure (the chart container), so its CSS applies. */\n readonly container?: Element;\n}\n\n/**\n * Measures how much space a text takes, in px, so labels can be wrapped\n * and aligned. In the browser, Chartist measures with the page's fonts;\n * `toScene()` estimates (0.6 em per character, 1.2 em per line) unless you\n * pass your own in its size.\n *\n * @example\n * ```ts\n * import type { MeasureText } from 'chartist';\n *\n * // Wider glyphs than the estimate, for a wide font.\n * export const measureText: MeasureText = (text, options = {}) => {\n * const fontSize = options.fontSize ?? 12;\n * return { width: text.length * fontSize * 0.7, height: fontSize * 1.25 };\n * };\n * ```\n */\nexport type MeasureText = (\n text: string,\n options?: MeasureTextOptions\n) => TextMetrics;\n\n/** What a {@link MeasureStyle} function gets with the property to read. */\nexport interface MeasureStyleOptions {\n /** Class names of the element whose style is read. */\n readonly classes?: readonly string[];\n /** Classes of the chart's root svg, so chart-type CSS applies. */\n readonly rootClass?: string;\n /** Where to measure (the chart container), so its CSS applies. */\n readonly container?: Element;\n}\n\n/**\n * Reads a computed CSS property of an SVG `path` with the given classes,\n * for values that the stylesheet decides and layout needs: the pie layer\n * reads the `stroke-width` of a donut slice to fit the ring. Returns\n * `undefined` when it can't tell. In the browser, Chartist reads it in\n * the chart's container; `toScene()` has no stylesheet, so layout uses\n * its defaults there.\n *\n * @example\n * ```ts\n * import { domRenderer, type Renderer } from 'chartist';\n *\n * // The DOM renderer, but donuts are laid out for 30px rings, whatever\n * // the stylesheet says. Pass it as `renderer` to `chart()`.\n * export const renderer: Renderer = {\n * ...domRenderer(),\n * measureStyle: property => (property === 'stroke-width' ? '30px' : undefined)\n * };\n * ```\n */\nexport type MeasureStyle = (\n property: string,\n options?: MeasureStyleOptions\n) => string | undefined;\n\nexport const DEFAULT_FONT_SIZE = 12;\n\n/**\n * Where SVG text labels put a line's baseline: this share of the font size\n * below the top of the line (a typical font's ascent). Lines are one font\n * size apart, so a renderer finds a line's vertical center at\n * `y - (textAscent - 0.5) * fontSize` from its `y`.\n * @experimental\n */\nexport const textAscent = 0.85;\n\n/**\n * Estimates text size without a DOM: an average glyph is 0.6 em wide, and a\n * line is 1.2 em high, at `fontSize` or else 12 px. `toScene()` measures\n * with it unless you pass your own, which can build on it.\n *\n * @example\n * ```ts\n * import { estimateText, type MeasureText } from 'chartist';\n *\n * // Bold labels: a tenth wider than the estimate.\n * export const measureText: MeasureText = (text, options) => {\n * const size = estimateText(text, options);\n * return { ...size, width: size.width * 1.1 };\n * };\n * ```\n * @experimental\n */\nexport const estimateText: MeasureText = (text, options = {}) => {\n const fontSize = options.fontSize ?? DEFAULT_FONT_SIZE;\n return {\n width: text.length * fontSize * 0.6,\n height: fontSize * 1.2,\n fontSize\n };\n};\n","import { namespaces } from '../core/constants';\nimport type { SceneNode } from '../scene/node';\nimport {\n estimateText,\n type MeasureStyleOptions,\n type MeasureText,\n type MeasureTextOptions\n} from './measure';\nimport type { Renderer, RenderOutput } from './types';\n\n/**\n * What {@link domRenderer} returns from `render()`: the inline SVG it\n * added to the container.\n * @experimental\n */\nexport interface DomRenderOutput extends RenderOutput {\n /** The chart's `svg` element, in the container. */\n readonly svg: SVGSVGElement;\n /** The rendered element of a scene node of this render. */\n readonly elementOf: (node: SceneNode) => Element | undefined;\n /** Takes the SVG out of the container again. */\n readonly remove: () => void;\n}\n\nfunction setAttribute(element: Element, name: string, value: string | number) {\n const separator = name.indexOf(':');\n const prefix = separator > 0 ? name.slice(0, separator) : '';\n if (prefix && prefix !== 'xmlns' && namespaces[prefix]) {\n element.setAttributeNS(namespaces[prefix], name, String(value));\n } else {\n element.setAttribute(name, String(value));\n }\n}\n\n/**\n * Creates the element tree. Content of a `foreignObject` is HTML and is\n * created in the XHTML namespace.\n */\nfunction build(\n document: Document,\n current: SceneNode,\n elements: WeakMap<SceneNode, Element>,\n html = false\n): Element {\n const element = document.createElementNS(\n html ? namespaces.xhtml : namespaces.svg,\n current.name\n );\n if (current.classes.length) {\n element.setAttribute('class', current.classes.join(' '));\n }\n for (const [name, value] of Object.entries(current.attrs)) {\n setAttribute(element, name, value);\n }\n // Like textContent = '': empty text creates no text node.\n if (current.content) {\n element.appendChild(document.createTextNode(current.content));\n }\n const childrenAreHtml = html || current.name === 'foreignObject';\n for (const child of current.children) {\n element.appendChild(build(document, child, elements, childrenAreHtml));\n }\n elements.set(current, element);\n return element;\n}\n\n/** Removes Chartist SVGs (the ones with the ct namespace) from a container. */\nfunction removePrevious(container: Element) {\n Array.from(container.querySelectorAll('svg'))\n .filter(svg => svg.getAttributeNS(namespaces.xmlns, 'ct'))\n .forEach(svg => svg.remove());\n}\n\n/**\n * Adds a hidden probe svg (with the chart's root class) holding one element\n * with the given classes to the container, or else the document's body, so\n * the page's CSS applies; reads it and removes the probe again.\n */\nfunction probe<T>(\n document: Document,\n name: 'text' | 'path',\n options: MeasureTextOptions | MeasureStyleOptions,\n read: (node: SVGGraphicsElement) => T\n): T {\n const svg = document.createElementNS(namespaces.svg, 'svg');\n svg.setAttribute(\n 'style',\n 'position: absolute; visibility: hidden; width: 0; height: 0;'\n );\n if (options.rootClass) {\n svg.setAttribute('class', options.rootClass);\n }\n const node = document.createElementNS(\n namespaces.svg,\n name\n ) as SVGGraphicsElement;\n if (options.classes?.length) {\n node.setAttribute('class', options.classes.join(' '));\n }\n svg.appendChild(node);\n (options.container ?? document.body).appendChild(svg);\n try {\n return read(node);\n } finally {\n svg.remove();\n }\n}\n\n/**\n * Measures text with an offscreen SVG `<text>` in the given document (in\n * the container, if there is one), so CSS fonts apply. Falls back to the\n * estimate where SVG metrics are missing.\n */\nfunction measureInDocument(document: Document): MeasureText {\n return (text, options = {}) =>\n probe(document, 'text', options, node => {\n if (options.fontSize) {\n node.setAttribute('font-size', String(options.fontSize));\n }\n node.textContent = text;\n if (typeof node.getBBox !== 'function') {\n return estimateText(text, options);\n }\n const box = node.getBBox();\n const fontSize = parseFloat(\n document.defaultView?.getComputedStyle(node).fontSize ?? ''\n );\n return box.width || box.height\n ? {\n width: box.width,\n height: box.height,\n ...(fontSize > 0 && { fontSize })\n }\n : estimateText(text, options);\n });\n}\n\n/**\n * Creates the renderer `chart()` uses by default: it renders scenes as\n * inline SVG into the container, replacing an earlier Chartist SVG there\n * (as 1.x does), and measures text and reads styles for layout in the\n * container, so its CSS applies.\n * Wrap it to change what every render puts on the page.\n *\n * @example\n * ```ts\n * import { chart, domRenderer, pie, type Renderer } from 'chartist';\n *\n * const dom = domRenderer();\n * // The DOM renderer, with a name for screen readers on every render.\n * const renderer: Renderer = {\n * ...dom,\n * render(scene, container) {\n * const output = dom.render(scene, container);\n * output.svg.setAttribute('role', 'img');\n * output.svg.setAttribute('aria-label', 'Monthly budget');\n * return output;\n * }\n * };\n *\n * chart('#chart', {\n * data: { series: [50, 30, 20] },\n * coordinates: 'polar',\n * layers: [pie()],\n * renderer\n * });\n * ```\n * @experimental\n */\nexport function domRenderer(): Renderer<DomRenderOutput> {\n return {\n labels: 'html',\n render(scene, container) {\n const document = container.ownerDocument;\n const elements = new WeakMap<SceneNode, Element>();\n const svg = build(document, scene, elements) as SVGSVGElement;\n svg.setAttributeNS(namespaces.xmlns, 'xmlns:ct', namespaces.ct);\n removePrevious(container);\n container.appendChild(svg);\n return {\n svg,\n elementOf: (node: SceneNode) => elements.get(node),\n remove: () => svg.remove()\n };\n },\n measureText(text, options) {\n // The container's document, not the global one, so charts in an\n // iframe or in a jsdom document measure there (see #1424).\n const document = options?.container?.ownerDocument ?? globalThis.document;\n return document\n ? measureInDocument(document)(text, options)\n : estimateText(text, options);\n },\n measureStyle(property, options = {}) {\n const document = options.container?.ownerDocument ?? globalThis.document;\n const view = document?.defaultView;\n return view\n ? probe(document, 'path', options, node =>\n view.getComputedStyle(node).getPropertyValue(property)\n ) || undefined\n : undefined;\n }\n };\n}\n","import type { Layer } from '../pipeline/types';\nimport type { ChartConfig } from './types';\n\n/**\n * The chart type class for a chart's layers, so the stylesheet's chart\n * type rules (label alignment, for one) apply: bar first, since composed\n * charts with bars need the bar label alignment, then pie or donut, else\n * line.\n */\nexport function chartTypeClass(layers: readonly Layer[]): string {\n const types = layers.map(layer => layer.chartType ?? layer.type);\n if (types.includes('bar')) {\n return 'ct-chart-bar';\n }\n if (types.includes('donut')) {\n return 'ct-chart-donut';\n }\n return types.includes('pie') ? 'ct-chart-pie' : 'ct-chart-line';\n}\n\n/** The config with the chart type class when it has no `className`. */\nexport function withChartTypeClass<T extends ChartConfig>(config: T): T {\n return config.className === undefined\n ? { ...config, className: chartTypeClass(config.layers) }\n : config;\n}\n","import type { PipelineOptions } from '../pipeline/phases';\nimport type {\n AllPhasesListener,\n PhaseListener,\n PhaseListeners,\n PhaseName\n} from '../pipeline/types';\nimport type { Renderer } from '../render/types';\nimport type { ResponsiveSet } from '../responsive/responsive';\n\n/**\n * The custom events a chart can emit, by name, with their payloads. The\n * core emits only `responsive`. A plugin that emits events of its own\n * declares them here (TypeScript merges your declaration into Chartist's),\n * so `on()`, `off()` and `emit()` check the names and payloads:\n *\n * ```ts\n * declare module 'chartist' {\n * interface ChartEvents {\n * 'legend:click': { readonly seriesIndex: number };\n * }\n * }\n * ```\n *\n * `chartist/compat` declares the 1.x events (`draw`, `created`, …).\n * @experimental\n */\nexport interface ChartEvents {\n /**\n * Responsive entries changed which overrides apply: the config before\n * and after (`chart()`), or the options before and after (presets).\n */\n responsive:\n | {\n readonly previousConfig: ChartConfig;\n readonly currentConfig: ChartConfig;\n }\n | { readonly previousOptions: unknown; readonly currentOptions: unknown };\n}\n\n/**\n * The name of a custom event: a key of {@link ChartEvents}. Plugins list\n * the names they emit in `provides`.\n */\nexport type CustomEventName = keyof ChartEvents & string;\n\n/**\n * A plugin: a name and an `install` function that registers listeners on\n * the chart. Plugins go into `plugins`, in the config of {@link chart} or\n * the options of the presets. They install in order, so with two\n * listeners on the same event, the earlier plugin's runs first.\n *\n * For options, write a function that takes them and returns the plugin, or\n * read them from the second argument of `install` and pass the plugin\n * with {@link withOptions}.\n *\n * @example\n * ```ts\n * import { barChart, type ChartPlugin } from 'chartist';\n *\n * // Bars at or above the limit get the class ct-over.\n * const threshold = (limit: number): ChartPlugin => ({\n * name: 'threshold',\n * install(chart) {\n * chart.on('compose', current => {\n * if (current.role !== 'bar') {\n * return;\n * }\n * const { value } = current.ctx;\n * const y =\n * typeof value === 'number'\n * ? value\n * : value && 'y' in value\n * ? value.y\n * : undefined;\n * return y !== undefined && y >= limit\n * ? current.addClass('ct-over')\n * : undefined;\n * });\n * }\n * });\n *\n * barChart('#chart', { series: [[5, 4, 3, 7]] }, { plugins: [threshold(5)] });\n * ```\n * @experimental\n */\nexport interface ChartPlugin<TOptions = unknown> {\n /** Names the plugin. Prefix your custom events with it to keep them apart. */\n readonly name: string;\n /**\n * The custom events this plugin emits with `chart.emit()`, each declared\n * in {@link ChartEvents}. They're known before any plugin installs, so\n * another plugin may listen to them.\n */\n readonly provides?: readonly CustomEventName[];\n /**\n * Sets the plugin up: runs once, before the first render, with the\n * chart's handle. Listeners registered here stay for every later render,\n * after updates and resizes too, and `off(name)` without a listener\n * leaves them alone: remove one with its reference.\n * @param chart The chart's handle, to listen to events and emit them.\n * @param options The options of a `[plugin, options]` entry, if any.\n */\n install(chart: ChartHandle, options?: TOptions): void;\n}\n\n/**\n * A plugin paired with its options, as {@link withOptions} creates it.\n * `install` receives the options as its second argument.\n */\nexport type PluginWithOptions<TOptions = unknown> = readonly [\n ChartPlugin<TOptions>,\n TOptions\n];\n\n/**\n * An entry of a chart's `plugins`: a plugin, or a plugin with its options.\n * Prefer {@link withOptions} (it checks the options) or a function that\n * returns a plugin over a bare `[plugin, options]` pair. A 1.x plugin (a\n * plain function) throws; convert it with `fromLegacyPlugin()` from\n * `chartist/compat`.\n */\nexport type PluginEntry =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ChartPlugin<any> | PluginWithOptions<any>;\n\n/**\n * The config of {@link chart}: the data, the layers that draw it and the\n * axes they draw on, plus size, padding, plugins and listeners.\n *\n * Without `axes`, layers draw into the whole chart area; the pie layer\n * needs `coordinates: 'polar'`. {@link toScene} takes the same config.\n * @experimental\n */\nexport interface ChartConfig extends PipelineOptions {\n /**\n * Plugins to install before the first render, in order: plugins, or\n * plugins with their options from {@link withOptions}.\n */\n readonly plugins?: readonly PluginEntry[];\n /**\n * Phase listeners by phase name (or `'*'` for all phases). They're\n * registered before the first render, so they see it too.\n */\n readonly on?: PhaseListeners;\n /** Turns the scene into output; the DOM renderer by default. */\n readonly renderer?: Renderer;\n /**\n * Overrides that apply while their condition matches, created with\n * `responsive([...])`: entries of a media query string or a\n * `container()` condition, and a partial config. The chart renders again\n * when the matching entries change.\n */\n readonly responsive?: ResponsiveSet<ChartOverrides>;\n}\n\n/**\n * The part of a {@link ChartConfig} that responsive entries can override:\n * everything but `responsive`, `plugins`, `on` and `renderer`. The\n * matching entries merge over the config in order, shallowly.\n * @experimental\n */\nexport type ChartOverrides = Partial<\n Omit<ChartConfig, 'responsive' | 'plugins' | 'on' | 'renderer'>\n>;\n\n/**\n * The handle {@link chart} returns: update or remove the chart, and listen\n * to its events. Plugins get the same handle in `install`. The methods\n * other than `destroy` and `emit` return the handle, so calls chain.\n * @experimental\n */\nexport interface ChartHandle {\n /** The element the chart renders into (undefined in `toScene`). */\n readonly container?: Element;\n /**\n * Shallow-merges the changes into the config and renders again. Plugins\n * and listeners stay; `plugins` and `on` can't change.\n */\n update(config: Partial<Omit<ChartConfig, 'plugins' | 'on'>>): this;\n /**\n * Stops reacting to container size changes (and media queries in\n * presets). The output and the listeners stay.\n */\n detach(): this;\n /** Detaches, removes the output and clears all listeners. */\n destroy(): void;\n /**\n * Emits a custom event (declared in {@link ChartEvents}), e.g. from a\n * plugin. Phase names are reserved: emitting one throws.\n */\n emit<K extends CustomEventName>(name: K, payload: ChartEvents[K]): void;\n /**\n * Listens to a phase event, which fires on every render. Listeners of\n * `resolve` to `scene` may return a new payload to change what's drawn;\n * `compose` listeners may return `null` to drop a node.\n */\n on<K extends PhaseName>(name: K, listener: PhaseListener<K>): this;\n /** Listens to every phase event, with the phase name and its payload. */\n on(name: '*', listener: AllPhasesListener): this;\n /** Listens to a custom event, declared in {@link ChartEvents}. */\n on<K extends CustomEventName>(\n name: K,\n listener: (payload: ChartEvents[K]) => void\n ): this;\n /**\n * Removes a phase listener, whoever added it. Without a listener,\n * removes the listeners of the phase added through `on` and the\n * config's `on`; plugins keep theirs.\n */\n off<K extends PhaseName>(name: K, listener?: PhaseListener<K>): this;\n /**\n * Removes a listener of all phases, or without a listener, those added\n * through `on`.\n */\n off(name: '*', listener?: AllPhasesListener): this;\n /**\n * Removes a custom event listener, or without a listener, the event's\n * listeners added through `on`.\n */\n off<K extends CustomEventName>(\n name: K,\n listener?: (payload: ChartEvents[K]) => void\n ): this;\n}\n\n/**\n * Pairs a plugin with its options for a chart's `plugins`, and checks the\n * options against the plugin's options type. `install` receives them as\n * its second argument.\n *\n * @example\n * ```ts\n * import { lineChart, withOptions, type ChartPlugin } from 'chartist';\n *\n * const lastPoint: ChartPlugin<{ className: string }> = {\n * name: 'last-point',\n * install(chart, options) {\n * chart.on('compose', current => {\n * if (current.role !== 'series') {\n * return;\n * }\n * const last = current.children.at(-1);\n * return last && options\n * ? current.replace(last, last.addClass(options.className))\n * : undefined;\n * });\n * }\n * };\n *\n * lineChart(\n * '#chart',\n * { series: [[1, 3, 2, 5]] },\n * { plugins: [withOptions(lastPoint, { className: 'ct-last' })] }\n * );\n * ```\n * @experimental\n */\nexport function withOptions<TOptions>(\n plugin: ChartPlugin<TOptions>,\n options: TOptions\n): PluginWithOptions<TOptions> {\n return [plugin, options];\n}\n\n/**\n * The handle without event typing, for code that routes event names it\n * doesn't know (the 1.x chart classes, compat). Internal.\n */\nexport interface UntypedEvents {\n on(name: string, listener: (payload: unknown) => void): unknown;\n off(name: string, listener?: (payload: unknown) => void): unknown;\n emit(name: string, payload?: unknown): void;\n}\n\n/** The same handle, seen without event typing. Internal. */\nexport const untyped = (handle: ChartHandle): UntypedEvents =>\n handle as unknown as UntypedEvents;\n","import type { ListenerOwner, PhaseEmitter } from '../pipeline/emitter';\nimport type { PhaseListeners } from '../pipeline/types';\nimport type { ChartHandle, ChartPlugin, PluginEntry } from './types';\nimport { untyped } from './types';\n\nconst PHASES = new Set([\n 'resolve',\n 'prepare',\n 'layout',\n 'compose',\n 'scene',\n 'render',\n 'mount'\n]);\n\n/**\n * The 1.x event names. Listening to one that no installed plugin provides\n * logs a migration hint; this list is all the core knows about 1.x events.\n */\nconst LEGACY_EVENTS = new Set([\n 'data',\n 'optionsChanged',\n 'draw',\n 'created',\n 'animationBegin',\n 'animationEnd'\n]);\n\nconst warnedEvents = new Set<string>();\n\nfunction warn(message: string) {\n // Intentional: tells 1.x users how to migrate.\n // eslint-disable-next-line no-console\n console.warn(message);\n}\n\n/** Plugin entries as `[plugin, options]`; throws for 1.x plugin functions. */\nfunction normalize(plugins: readonly PluginEntry[]) {\n return (plugins as readonly unknown[]).map(entry => {\n const [plugin, options] = Array.isArray(entry) ? entry : [entry];\n if (typeof plugin === 'function') {\n throw new Error(\n `Chartist: the plugin \"${plugin.name || 'anonymous'}\" is a 1.x plugin (a plain function). ` +\n 'chart() and the preset functions accept only v2 plugins; convert it with fromLegacyPlugin() from chartist/compat.'\n );\n }\n return [plugin as ChartPlugin, options] as const;\n });\n}\n\n/**\n * Who a chart's `on` attributes new listeners to: plugins while they\n * install, the user otherwise. `off(name)` removes only the user's.\n */\nexport interface ListenerScope {\n owner: ListenerOwner;\n}\n\nconst scopes = new WeakMap<ChartHandle, ListenerScope>();\n\n/** A new scope, attributing listeners to the user. */\nexport const listenerScope = (): ListenerScope => ({ owner: 'user' });\n\n/** Runs `add` with the chart's listeners attributed to `owner`. */\nfunction addingAs(scope: ListenerScope, owner: ListenerOwner, add: () => void) {\n const previous = scope.owner;\n scope.owner = owner;\n try {\n add();\n } finally {\n scope.owner = previous;\n }\n}\n\n/**\n * Internal: adds the listeners in `add` as the user's, though a plugin's\n * `install` runs it. The 1.x classes register their users' listeners from\n * a plugin, so they're in place for the first render.\n */\nexport function asUserListeners(chart: ChartHandle, add: () => void) {\n const scope = scopes.get(chart);\n if (scope) {\n addingAs(scope, 'user', add);\n } else {\n add();\n }\n}\n\n/**\n * Installs v2 plugins in order and returns the event names they provide.\n * Provided names are known before any plugin installs, so a plugin may\n * listen to events another plugin provides. Listeners added while a\n * plugin installs belong to plugins.\n */\nexport function installPlugins(\n chart: ChartHandle,\n plugins: readonly PluginEntry[] = [],\n provided: Set<string>,\n scope: ListenerScope\n) {\n scopes.set(chart, scope);\n const entries = normalize(plugins);\n for (const [plugin] of entries) {\n plugin.provides?.forEach(name => provided.add(name));\n }\n for (const [plugin, options] of entries) {\n addingAs(scope, 'plugin', () => plugin.install(chart, options));\n }\n}\n\n/** Registers `config.on` listeners. */\nexport function registerListeners(\n chart: ChartHandle,\n listeners: PhaseListeners = {}\n) {\n for (const [name, listener] of Object.entries(listeners)) {\n if (listener) {\n untyped(chart).on(name, listener as (value: unknown) => void);\n }\n }\n}\n\ntype Listener = (...args: never[]) => unknown;\n\n/**\n * `on`, `off` and `emit` for a handle: forward to the emitter and return\n * the handle. `on` warns once per name for 1.x events nobody provides, and\n * records who adds the listener (see {@link ListenerScope}).\n */\nexport function eventMethods(\n emitter: PhaseEmitter,\n handle: () => ChartHandle,\n provided: Set<string>,\n scope: ListenerScope\n): Pick<ChartHandle, 'on' | 'off' | 'emit'> {\n return {\n on: ((name: string, listener: Listener) => {\n if (\n LEGACY_EVENTS.has(name) &&\n !provided.has(name) &&\n !warnedEvents.has(name)\n ) {\n warnedEvents.add(name);\n warn(\n `Chartist: \"${name}\" is a 1.x event. v2 charts emit it only with the compat plugin: add compat from chartist/compat to plugins (see the migration guide).`\n );\n }\n emitter.on(name, listener as (value: unknown) => unknown, scope.owner);\n return handle();\n }) as ChartHandle['on'],\n off: ((name: string, listener?: Listener) => {\n emitter.off(name, listener as ((value: unknown) => unknown) | undefined);\n return handle();\n }) as ChartHandle['off'],\n emit(name: string, payload?: unknown) {\n if (PHASES.has(name)) {\n throw new Error(\n `Chartist: \"${name}\" is a phase event; plugins can't emit phase events`\n );\n }\n emitter.notify(name, payload);\n }\n };\n}\n","import { createPhaseEmitter } from '../pipeline/emitter';\nimport { runPipeline, type PipelineState } from '../pipeline/phases';\nimport { domRenderer } from '../render/dom';\nimport {\n estimateText,\n type MeasureStyle,\n type MeasureText\n} from '../render/measure';\nimport type { RenderOutput } from '../render/types';\nimport type { ResponsiveWatcher } from '../responsive/responsive';\nimport { withChartTypeClass } from './className';\nimport {\n eventMethods,\n installPlugins,\n listenerScope,\n registerListeners\n} from './plugins';\nimport type { ChartConfig, ChartHandle } from './types';\n\n/** A fixed size in px: a number or a px string. Other units are measured. */\nfunction fixedSize(value: number | string | undefined): number | undefined {\n if (typeof value === 'number') {\n return value;\n }\n const match = value?.match(/^\\s*(\\d+(?:\\.\\d+)?)(?:px)?\\s*$/);\n return match ? Number(match[1]) : undefined;\n}\n\nfunction resolveTarget(target: string | Element): Element {\n const container =\n typeof target === 'string' ? document.querySelector(target) : target;\n if (!container) {\n throw new Error(\n `Target element ${typeof target === 'string' ? `\"${target}\"` : ''} is not found`\n );\n }\n return container;\n}\n\n/**\n * Creates a chart from data, axes and layers in a container, and renders\n * it right away. The presets (`lineChart`, `barChart`, `pieChart`) are\n * built on it; use it for what they don't cover, like bars and a line on\n * two Y axes.\n *\n * The chart fills its container unless the config sets a size, and renders\n * again when the container resizes, web fonts finish loading or the\n * matching `responsive` entries change. Listeners in `config.on` and\n * plugins receive the events of the first render too. While the page is\n * printed, the SVG gets a `viewBox` of its layout size (unless the config\n * sets one), so the drawing scales into the box it gets in the print.\n *\n * Without `className`, the SVG gets the chart type class of its layers,\n * so the stylesheet's chart type rules apply: `ct-chart-bar` if a layer\n * draws bars, else `ct-chart-pie` or `ct-chart-donut` for a pie layer,\n * else `ct-chart-line`. A `className` replaces it.\n *\n * @example\n * ```ts\n * import {\n * autoScaleAxis,\n * axisGrid,\n * axisLabels,\n * bar,\n * cartesianAxes,\n * chart,\n * line,\n * stepAxis\n * } from 'chartist';\n *\n * const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];\n *\n * chart('#chart', {\n * data: {\n * labels: months,\n * series: [\n * { name: 'rain', data: [64, 58, 70, 82, 104, 120] },\n * { name: 'temperature', data: [1, 3, 8, 12, 16, 20] }\n * ]\n * },\n * axes: cartesianAxes([\n * { id: 'month', side: 'bottom', type: stepAxis(), ticks: months },\n * { id: 'mm', side: 'left', type: autoScaleAxis(), low: 0 },\n * { id: 'celsius', side: 'right', type: autoScaleAxis(), low: 0 }\n * ]),\n * layers: [\n * axisGrid({ axes: ['month', 'mm'] }),\n * bar({ series: ['rain'], x: 'month', y: 'mm' }),\n * line({ series: ['temperature'], y: 'celsius', align: 'center' }),\n * axisLabels()\n * ]\n * });\n * ```\n * @param target The container element, or a CSS selector for it.\n * @param config The data, axes, layers and the rest of the chart.\n * @returns A handle to update the chart, listen to it or remove it.\n * @experimental\n */\nexport function chart(\n target: string | Element,\n config: ChartConfig\n): ChartHandle {\n const container = resolveTarget(target);\n const emitter = createPhaseEmitter();\n const scope = listenerScope();\n const renderer = config.renderer ?? domRenderer();\n const rendererMeasure = renderer.measureText;\n // Whether the last render measured text (SVG text labels do).\n let measuredText = false;\n // Text is measured in the container, so the chart's CSS applies.\n const measureText: MeasureText = (text, options) => {\n measuredText = true;\n return rendererMeasure\n ? rendererMeasure(text, { container, ...options })\n : estimateText(text, options);\n };\n // Styles for layout (a donut's ring width), read in the container too.\n const rendererStyle = renderer.measureStyle;\n const measureStyle: MeasureStyle | undefined =\n rendererStyle &&\n ((property, options) => rendererStyle(property, { container, ...options }));\n // The config as given, and with the matching responsive overrides.\n let current = config;\n let effective = config;\n let watcher: ResponsiveWatcher | undefined;\n let state: PipelineState | undefined;\n let output: RenderOutput | undefined;\n let observer: ResizeObserver | undefined;\n let destroyed = false;\n // Cleared by detach(), also when it's called during the first render.\n let attached = true;\n const provided = new Set<string>();\n // The container's window, which may be an iframe's or jsdom's.\n const view = container.ownerDocument.defaultView;\n const fonts = container.ownerDocument.fonts as FontFaceSet | undefined;\n // Layout that measured text depends on font metrics, so it runs again\n // when web fonts finish loading. HTML labels reflow by themselves.\n const onFontsLoaded = () => {\n if (!destroyed && state && measuredText) {\n render('layout');\n }\n };\n\n // While printing, the svg gets a viewBox of its layout size, so the\n // drawing scales into the box print CSS gives it. Browsers don't reliably\n // take a new layout at the print size into the print, but they do take\n // changes made in `beforeprint`.\n let printed: Element | undefined;\n let printing = false;\n function applyPrintViewBox() {\n printed?.removeAttribute('viewBox');\n printed = undefined;\n if (!printing || effective.viewBox || !state || !output?.elementOf) {\n return;\n }\n printed = output.elementOf(state.scene);\n printed?.setAttribute(\n 'viewBox',\n `0 0 ${state.layout.width} ${state.layout.height}`\n );\n }\n const onBeforePrint = () => {\n printing = true;\n applyPrintViewBox();\n };\n const onAfterPrint = () => {\n printing = false;\n applyPrintViewBox();\n };\n\n /**\n * Measures like 1.x: a probe svg with the chart's size attributes is\n * placed in the container and its size read, so percentages and CSS apply.\n */\n function measureSvg() {\n const width = String(effective.width ?? '100%');\n const height = String(effective.height ?? '100%');\n const probe = container.ownerDocument.createElementNS(\n 'http://www.w3.org/2000/svg',\n 'svg'\n );\n probe.setAttribute('width', width);\n probe.setAttribute('height', height);\n // CSS lengths need a unit, unlike the attributes (see #1482).\n const px = (value: unknown) => (typeof value === 'number' ? 'px' : '');\n probe.setAttribute(\n 'style',\n `width: ${width}${px(effective.width)}; height: ${height}${px(effective.height)};`\n );\n container.appendChild(probe);\n const measured = { width: probe.clientWidth, height: probe.clientHeight };\n probe.remove();\n return measured;\n }\n\n function size() {\n // The 1.x order: viewBox, the rendered svg, the fixed size option.\n const svg = measureSvg();\n return {\n width:\n effective.viewBox?.width ||\n svg.width ||\n (fixedSize(effective.width) ?? container.clientWidth),\n height:\n effective.viewBox?.height ||\n svg.height ||\n (fixedSize(effective.height) ?? container.clientHeight)\n };\n }\n\n function render(from: 'resolve' | 'layout') {\n const { width, height } = size();\n measuredText = false;\n state = runPipeline(\n emitter,\n withChartTypeClass(effective),\n {\n width,\n height,\n measureText,\n measureStyle,\n labels: renderer.labels ?? 'html',\n rootSize: {\n width: effective.width ?? '100%',\n height: effective.height ?? '100%'\n }\n },\n state,\n from\n );\n const { scene } = state;\n output = renderer.render(scene, container);\n if (printing) {\n applyPrintViewBox();\n }\n emitter.notify('render', { scene, output });\n const elementOf = output.elementOf ?? (() => undefined);\n emitter.notify('mount', { scene, output, elementOf });\n }\n\n function resolveResponsive() {\n const entries = current.responsive?.entries;\n effective = watcher\n ? watcher.matching.reduce(\n (result, index) => ({ ...result, ...entries![index][1] }),\n current\n )\n : current;\n }\n\n function onResponsiveChange() {\n const previousConfig = effective;\n resolveResponsive();\n handle.emit('responsive', { previousConfig, currentConfig: effective });\n render('resolve');\n }\n\n /** (Re)creates the watcher of the responsive entries. */\n function watch() {\n watcher?.stop();\n watcher = current.responsive?.watch(container, () => {\n if (!destroyed) {\n onResponsiveChange();\n }\n });\n resolveResponsive();\n }\n\n const handle: ChartHandle = {\n container,\n update(changes) {\n current = { ...current, ...changes };\n if ('responsive' in changes) {\n watch();\n } else {\n resolveResponsive();\n }\n render('resolve');\n return handle;\n },\n detach() {\n attached = false;\n view?.removeEventListener('beforeprint', onBeforePrint);\n view?.removeEventListener('afterprint', onAfterPrint);\n onAfterPrint();\n observer?.disconnect();\n observer = undefined;\n fonts?.removeEventListener('loadingdone', onFontsLoaded);\n watcher?.stop();\n watcher = undefined;\n return handle;\n },\n destroy() {\n if (destroyed) {\n return;\n }\n destroyed = true;\n handle.detach();\n output?.remove?.();\n emitter.clear();\n },\n ...eventMethods(emitter, () => handle, provided, scope)\n };\n\n // Subscribed before the plugins install and the first render, so a\n // detach() from one of their listeners unsubscribes them.\n fonts?.addEventListener('loadingdone', onFontsLoaded);\n view?.addEventListener('beforeprint', onBeforePrint);\n view?.addEventListener('afterprint', onAfterPrint);\n\n const Observer = view?.ResizeObserver ?? globalThis.ResizeObserver;\n if (typeof Observer !== 'undefined') {\n observer = new Observer(() => {\n if (destroyed || !state) {\n return;\n }\n // A crossed container breakpoint renders the new size too.\n if (watcher?.check()) {\n onResponsiveChange();\n return;\n }\n const { width, height } = size();\n if (width !== state.layout.width || height !== state.layout.height) {\n render('layout');\n }\n });\n observer.observe(container);\n }\n\n installPlugins(handle, config.plugins, provided, scope);\n registerListeners(handle, config.on);\n if (attached) {\n watch();\n } else {\n resolveResponsive();\n }\n render('resolve');\n\n return handle;\n}\n","/**\n * Grid lines, grid background and HTML labels of an axis as scene nodes,\n * with the geometry and classes of 1.x `Axis.createGridAndLabels`.\n */\nimport type { AxisOptions, ChartPadding } from '../core/types';\nimport type { Area } from '../pipeline/types';\nimport { node, withFields, type SceneNode } from '../scene/node';\nimport { isFalseyButZero } from '../utils/utils';\nimport type { ScaleAxis } from './axis';\nimport type { SvgLabelBuilder } from './svgLabels';\n\n/** The classes of an axis's grid lines and labels. */\nexport interface AxisClassNames {\n /** Each grid line (`ct-grid`). */\n readonly grid: string;\n /** Each label (`ct-label`). */\n readonly label: string;\n /** Grid lines and labels of an X axis (`ct-horizontal`). */\n readonly horizontal: string;\n /** Grid lines and labels of a Y axis (`ct-vertical`). */\n readonly vertical: string;\n /** Labels of an axis at the top or left (`ct-start`). */\n readonly start: string;\n /** Labels of an axis at the bottom or right (`ct-end`). */\n readonly end: string;\n}\n\n/** Axis options with the 1.x defaults applied. */\nexport interface DrawnAxisOptions extends AxisOptions {\n readonly offset: number;\n readonly position: 'start' | 'end';\n readonly labelOffset: { x: number; y: number };\n readonly showLabel: boolean;\n readonly showGrid: boolean;\n readonly labelInterpolationFnc: NonNullable<\n AxisOptions['labelInterpolationFnc']\n >;\n}\n\nexport interface AxisFrame {\n readonly area: Area;\n readonly padding: ChartPadding;\n /** The 1.x options of both axes (presets). */\n readonly axisX?: DrawnAxisOptions;\n readonly axisY?: DrawnAxisOptions;\n readonly classNames: AxisClassNames;\n /**\n * Composed charts: this axis's options and place. Labels go to `side`,\n * `inset` px further out than the area edge (stacked axes).\n */\n readonly options?: DrawnAxisOptions;\n /**\n * Composed charts: positions a label on any side. Kept out of this module\n * (see `layers/axes.ts`), so the presets don't bundle it.\n */\n readonly place?: LabelPlacer;\n /** Whether labels get the start class (top, left) or the end class. */\n readonly atStart?: boolean;\n /**\n * Draws labels as SVG text instead of HTML in a `foreignObject`. Kept\n * out of this module (see `svgLabels.ts`) like `place`.\n */\n readonly svgLabel?: SvgLabelBuilder;\n}\n\n/** Position of a tick and the offset of its label, per axis side. */\nexport type LabelPlacer = (\n axis: ScaleAxis,\n relative: number,\n labelLength: number,\n options: DrawnAxisOptions,\n area: Area\n) => { position: number; labelOffset: { x: number; y: number } };\n\nconst UNITS = {\n x: {\n pos: 'x',\n len: 'width',\n counterPos: 'y',\n counterLen: 'height',\n dir: 'horizontal'\n },\n y: {\n pos: 'y',\n len: 'height',\n counterPos: 'x',\n counterLen: 'width',\n dir: 'vertical'\n }\n} as const;\n\n/** Grid line and label nodes of one axis, in tick order. */\nexport function axisNodes(\n axis: ScaleAxis,\n frame: AxisFrame\n): { grids: SceneNode[]; labels: SceneNode[] } {\n const { area, padding, classNames } = frame;\n const units = UNITS[axis.dimension];\n const options = (frame.options ??\n (axis.dimension === 'x' ? frame.axisX : frame.axisY))!;\n const place = frame.place;\n const projected = axis.ticks.map((tick, i) => axis.project(tick, i));\n const labelValues = axis.ticks.map(options.labelInterpolationFnc);\n const gridOffset = axis.dimension === 'x' ? area.y2 : area.x1;\n const gridLength = axis.dimension === 'x' ? area.height : area.width;\n const grids: SceneNode[] = [];\n const labels: SceneNode[] = [];\n\n projected.forEach((relative, index) => {\n const labelValue = labelValues[index];\n // 1.x: the distance to the next tick, or the rest of the axis.\n const labelLength =\n index + 1 < projected.length\n ? projected[index + 1] - relative\n : Math.max(axis.length - relative, axis.length / axis.ticks.length);\n\n if (labelValue !== '' && isFalseyButZero(labelValue)) {\n return;\n }\n\n let position: number;\n let labelOffset = { x: 0, y: 0 };\n if (place) {\n ({ position, labelOffset } = place(\n axis,\n relative,\n labelLength,\n options,\n area\n ));\n } else if (axis.dimension === 'x') {\n const axisX = frame.axisX!;\n position = area.x1 + relative;\n labelOffset.x = axisX.labelOffset.x;\n labelOffset.y =\n axisX.position === 'start'\n ? padding.top + axisX.labelOffset.y + 5\n : area.y1 + axisX.labelOffset.y + 5;\n } else {\n const axisY = frame.axisY!;\n position = area.y1 - relative;\n labelOffset.y = axisY.labelOffset.y - labelLength;\n labelOffset.x =\n axisY.position === 'start'\n ? padding.left + axisY.labelOffset.x\n : area.x2 + axisY.labelOffset.x + 10;\n }\n\n if (options.showGrid) {\n // x1, x2, y1, y2 in the axis direction first (the output order).\n const attrs = {\n [`${units.pos}1`]: position,\n [`${units.pos}2`]: position,\n [`${units.counterPos}1`]: gridOffset,\n [`${units.counterPos}2`]: gridOffset + gridLength\n } as Record<'x1' | 'x2' | 'y1' | 'y2', number>;\n grids.push(\n node('line', attrs, `${classNames.grid} ${classNames[units.dir]}`, {\n role: 'grid',\n ctx: { axis, index, ...attrs }\n })\n );\n }\n\n if (options.showLabel) {\n // x, y, width, height in the axis direction first (the output order).\n const attrs = {\n [units.pos]: position + labelOffset[units.pos],\n [units.counterPos]: labelOffset[units.counterPos],\n [units.len]: labelLength,\n [units.counterLen]: Math.max(0, options.offset - 10)\n } as Record<'x' | 'y' | 'width' | 'height', number>;\n const atStart = frame.atStart ?? options.position === 'start';\n const classes = [\n classNames.label,\n classNames[units.dir],\n atStart ? classNames.start : classNames.end\n ].join(' ');\n const ctx = {\n kind: 'axis' as const,\n axis,\n index,\n text: labelValue,\n ...attrs\n };\n if (frame.svgLabel) {\n const label = frame.svgLabel(\n String(labelValue),\n attrs,\n classes,\n axis.dimension,\n atStart\n );\n if (label) {\n labels.push(withFields(label, { role: 'label', ctx }));\n }\n return;\n }\n // 1.x sizes the span in px, the axis direction first.\n const style =\n `${units.len}: ${Math.round(attrs[units.len])}px; ` +\n `${units.counterLen}: ${Math.round(attrs[units.counterLen])}px;`;\n const span = node('span', { style }, classes).text(String(labelValue));\n labels.push(\n node('foreignObject', { style: 'overflow: visible;', ...attrs }, '', {\n role: 'label',\n ctx\n }).append(span)\n );\n }\n });\n\n return { grids, labels };\n}\n\n/** The 1.x grid background: a rect over the chart area. */\nexport function gridBackground(area: Area, className: string): SceneNode {\n return node(\n 'rect',\n { x: area.x1, y: area.y2, width: area.width, height: area.height },\n className,\n { role: 'gridBackground' }\n );\n}\n","/**\n * SVG text labels: the label text wrapped into `tspan` lines and aligned\n * inside the label box the way the 1.x CSS aligns HTML labels (flexbox\n * rules per chart type), since CSS can't align SVG text in a box.\n */\nimport { textAscent, type MeasureText } from '../render/measure';\nimport { node, withFields, type SceneNode } from '../scene/node';\nimport type { AxisDimension } from './axis';\n\n/**\n * How an SVG text label sits in its label box, as set in the `align`\n * option of {@link axisLabels}.\n * @experimental\n */\nexport interface LabelAlign {\n /** Aligns the text to the box's left (`start`), center or right (`end`). */\n readonly horizontal: 'start' | 'middle' | 'end';\n /** Aligns the lines of text to the box's top, middle or bottom. */\n readonly vertical: 'top' | 'middle' | 'bottom';\n}\n\n/** Which row of the 1.x label CSS applies. */\nexport type LabelChartKind = 'line' | 'bar' | 'horizontalBar';\n\nexport interface LabelBox {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/** Builds the SVG node of one label, or nothing for empty text. */\nexport type SvgLabelBuilder = (\n text: string,\n box: LabelBox,\n classes: string,\n dimension: AxisDimension,\n atStart: boolean\n) => SceneNode | undefined;\n\n/**\n * The alignment the default CSS gives HTML labels (`ct-align-justify`):\n * line and composed charts, bar charts and horizontal bar charts.\n */\nexport function labelAlign(\n kind: LabelChartKind,\n dimension: AxisDimension,\n atStart: boolean\n): LabelAlign {\n const vertical = atStart ? 'bottom' : 'top';\n if (dimension === 'x') {\n return {\n vertical,\n horizontal: kind === 'bar' ? 'middle' : 'start'\n };\n }\n return {\n vertical: kind === 'horizontalBar' ? 'middle' : 'bottom',\n horizontal: atStart ? 'end' : 'start'\n };\n}\n\n/**\n * Greedy word wrap: words are added to a line while it fits `width`. A\n * word wider than `width` stays on a line of its own.\n */\nexport function wrapText(\n text: string,\n width: number,\n widthOf: (line: string) => number\n): string[] {\n const lines: string[] = [];\n let line = '';\n for (const word of text.split(/\\s+/).filter(Boolean)) {\n const candidate = line ? `${line} ${word}` : word;\n if (line && widthOf(candidate) > width) {\n lines.push(line);\n line = word;\n } else {\n line = candidate;\n }\n }\n if (line) {\n lines.push(line);\n }\n return lines;\n}\n\n/**\n * Creates the SVG label builder for a chart: text measured with the\n * label's classes, lines one font size apart (the 1.x label CSS sets\n * `line-height: 1`), absolute `x`/`y` on every line.\n */\nexport function svgLabels(\n measureText: MeasureText,\n kind: LabelChartKind,\n override: Partial<LabelAlign> = {}\n): SvgLabelBuilder {\n return (text, box, classes, dimension, atStart) => {\n const classList = classes.split(' ');\n const measure = (value: string) =>\n measureText(value, { classes: classList });\n // HTML labels get the width rounded to px (1.x span style); same here.\n const lines = wrapText(\n text,\n Math.round(box.width),\n line => measure(line).width\n );\n if (!lines.length) {\n return undefined;\n }\n const metrics = measure(lines[0]);\n const fontSize = metrics.fontSize ?? metrics.height / 1.2;\n const align = { ...labelAlign(kind, dimension, atStart), ...override };\n const blockHeight = lines.length * fontSize;\n const top =\n align.vertical === 'top'\n ? box.y\n : align.vertical === 'middle'\n ? box.y + (box.height - blockHeight) / 2\n : box.y + box.height - blockHeight;\n const x =\n align.horizontal === 'start'\n ? box.x\n : align.horizontal === 'middle'\n ? box.x + box.width / 2\n : box.x + box.width;\n const round = (value: number) => Math.round(value * 100) / 100;\n return withFields(\n node(\n 'text',\n {\n x: round(x),\n y: round(top + textAscent * fontSize),\n 'text-anchor': align.horizontal\n },\n classes\n ),\n {\n children: lines.map((line, index) =>\n node('tspan', {\n x: round(x),\n y: round(top + (index + textAscent) * fontSize)\n }).text(line)\n )\n }\n );\n };\n}\n","/**\n * Responsive entries: `[condition, overrides]` pairs, merged in order when\n * their condition matches. A plain string is a window media query (1.x); a\n * `container()` condition is a CSS container query, evaluated with\n * `Element.matchContainer()` (native or the `match-container` polyfill).\n */\n\n/**\n * A container query condition for a responsive entry, created with\n * {@link container}.\n * @experimental\n */\nexport interface ContainerCondition {\n /** Always `container`: tells the condition from a media query string. */\n readonly type: 'container';\n /** A `@container` condition, e.g. `(width < 400px)`. */\n readonly query: string;\n}\n\n/**\n * When a responsive entry applies: a window media query string, such as\n * `(max-width: 640px)` (as in 1.x), or a {@link container} condition.\n * Media queries are matched in the window of the chart's container, so a\n * chart in an iframe follows the iframe's viewport.\n * @experimental\n */\nexport type ResponsiveCondition = string | ContainerCondition;\n\n/**\n * A responsive entry: a condition and the overrides that apply while it\n * matches, e.g. `['(max-width: 640px)', { showPoint: false }]`. Matching\n * entries apply in order, so later ones win.\n * @experimental\n */\nexport type ResponsiveEntry<T> = readonly [ResponsiveCondition, T];\n\n/**\n * Marks a responsive entry as a container query, evaluated against the\n * chart container or an ancestor with a CSS `container-type`. Needs\n * `Element.matchContainer()`; until browsers ship it, load the\n * `match-container` polyfill. Without it, Chartist warns once and ignores\n * container entries; in `toScene()`, they never match.\n *\n * Works in the responsive entries of `chart()` and of the presets.\n *\n * @param query The condition you'd write after `@container` in CSS\n * @example\n * ```ts\n * import 'match-container';\n * import { container, lineChart } from 'chartist';\n *\n * lineChart(\n * '#chart',\n * {\n * labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],\n * series: [[12, 9, 7, 8, 5]]\n * },\n * { low: 0 },\n * [\n * [\n * container('(width < 400px)'),\n * {\n * showPoint: false,\n * axisX: { labelInterpolationFnc: value => String(value)[0] }\n * }\n * ]\n * ]\n * );\n * ```\n * @experimental\n */\nexport function container(query: string): ContainerCondition {\n return Object.freeze({ type: 'container', query });\n}\n\nexport function isContainerCondition(\n condition: unknown\n): condition is ContainerCondition {\n return (\n typeof condition === 'object' &&\n condition !== null &&\n (condition as ContainerCondition).type === 'container'\n );\n}\n\n/** What `matchMedia()` and `matchContainer()` return, as far as we use it. */\ninterface QueryList {\n readonly matches: boolean;\n addEventListener?(type: 'change', listener: () => void): void;\n removeEventListener?(type: 'change', listener: () => void): void;\n}\n\ntype MatchContainer = (query: string) => QueryList;\n\nlet warned = false;\n\nfunction warnMissingApi() {\n if (!warned) {\n warned = true;\n // eslint-disable-next-line no-console\n console.warn(\n 'Chartist: container() needs Element.matchContainer(); ' +\n 'load the match-container polyfill. Container entries are ignored.'\n );\n }\n}\n\n/** @internal For tests: shows the missing-API warning again. */\nexport function resetResponsiveWarning() {\n warned = false;\n}\n\n/**\n * Watches the conditions of a {@link ResponsiveSet}'s entries, as its\n * `watch()` returns it: which entries match, and when that changes.\n * @experimental\n */\nexport interface ResponsiveWatcher {\n /** Indexes of the matching entries, as of the last `check()`. */\n readonly matching: readonly number[];\n /** Re-reads all conditions; true if the matching set changed. */\n check(): boolean;\n /** Stops watching: no more `onChange` calls, and no listeners left. */\n stop(): void;\n}\n\nconst sameIndexes = (a: readonly number[], b: readonly number[]) =>\n a.length === b.length && a.every((value, i) => value === b[i]);\n\n/**\n * Watches the conditions of responsive entries. `onChange` runs when the\n * matching set changes through a query list's `change` event, or through a\n * container resize if `observeResize` is set; callers with their own resize\n * handling call `check()` instead.\n */\nexport function watchResponsive(\n entries: readonly ResponsiveEntry<unknown>[],\n host: Element | undefined,\n onChange: () => void,\n observeResize = false\n): ResponsiveWatcher {\n // Media queries are the container's window's, which may be an iframe's.\n const view =\n host?.ownerDocument.defaultView ??\n (typeof window !== 'undefined' ? window : undefined);\n let probe: HTMLElement | undefined;\n const lists: (QueryList | undefined)[] = entries.map(([condition]) => {\n if (!isContainerCondition(condition)) {\n return view?.matchMedia?.(condition);\n }\n if (!host) {\n // No DOM (toScene): container entries never match.\n return undefined;\n }\n const element = host.ownerDocument.createElement('span');\n const match = (element as unknown as { matchContainer?: MatchContainer })\n .matchContainer;\n if (typeof match !== 'function') {\n warnMissingApi();\n return undefined;\n }\n if (!probe) {\n // matchContainer() asks an element about its ancestor containers;\n // the svg is replaced on every render, so a stable probe asks.\n probe = host.appendChild(element);\n probe.className = 'ct-probe';\n probe.setAttribute('aria-hidden', 'true');\n probe.style.cssText =\n 'position:absolute;width:0;height:0;overflow:hidden';\n }\n try {\n return (\n probe as unknown as { matchContainer: MatchContainer }\n ).matchContainer(condition.query);\n } catch (error) {\n probe.remove();\n throw new Error(\n `Chartist: invalid container condition \"${condition.query}\": ${\n (error as Error).message\n }`\n );\n }\n });\n\n const read = () =>\n lists.flatMap((list, index) => (list?.matches ? [index] : []));\n\n const watcher: ResponsiveWatcher & { matching: number[] } = {\n matching: read(),\n check() {\n const next = read();\n if (sameIndexes(next, watcher.matching)) {\n return false;\n }\n watcher.matching = next;\n return true;\n },\n stop() {\n lists.forEach(list => list?.removeEventListener?.('change', onEvent));\n observer?.disconnect();\n probe?.remove();\n }\n };\n\n function onEvent() {\n if (watcher.check()) {\n onChange();\n }\n }\n\n lists.forEach(list => list?.addEventListener?.('change', onEvent));\n const Observer = view?.ResizeObserver ?? globalThis.ResizeObserver;\n const observer =\n observeResize && probe && typeof Observer !== 'undefined'\n ? new Observer(onEvent)\n : undefined;\n if (observer && host) {\n observer.observe(host);\n }\n return watcher;\n}\n\n/**\n * Responsive entries for `chart()`, with the watcher that evaluates them.\n * Created by `responsive()`, so charts without responsive entries don't\n * bundle the watcher.\n * @experimental\n */\nexport interface ResponsiveSet<T> {\n /** The entries as given to `responsive()`. */\n readonly entries: readonly ResponsiveEntry<T>[];\n /**\n * Starts watching the entries' conditions; `chart()` calls it. Calls\n * `onChange` when the set of matching entries changes.\n * @param host The chart's container, for container conditions\n * @param onChange Called after the matching entries changed\n */\n watch(host: Element | undefined, onChange: () => void): ResponsiveWatcher;\n}\n\n/**\n * Responsive overrides for `chart()`: `[condition, overrides]` entries with\n * a media query string or a `container()` condition. Matching overrides are\n * shallow-merged over the config in order, so later entries win and an\n * override replaces a whole option (e.g. all `layers`).\n *\n * When the matching entries change, the chart emits a `responsive` event\n * with the config before and after, and renders again.\n *\n * @param entries `[condition, overrides]` pairs; the overrides are a\n * partial config: padding, axes, layers, size and the like\n * @example\n * ```ts\n * import {\n * autoScaleAxis,\n * axisGrid,\n * axisLabels,\n * cartesianAxes,\n * chart,\n * line,\n * responsive,\n * stepAxis\n * } from 'chartist';\n *\n * const labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];\n *\n * chart('#chart', {\n * data: { labels, series: [[12, 9, 7, 8, 5]] },\n * axes: cartesianAxes([\n * { id: 'x', side: 'bottom', type: stepAxis(), ticks: labels },\n * { id: 'y', side: 'left', type: autoScaleAxis(), low: 0 }\n * ]),\n * layers: [axisGrid(), line({ showArea: true }), axisLabels()],\n * responsive: responsive([\n * [\n * '(max-width: 640px)',\n * {\n * padding: 5,\n * layers: [axisGrid(), line({ showPoint: false }), axisLabels()]\n * }\n * ]\n * ])\n * });\n * ```\n * @experimental\n */\nexport function responsive<T>(\n entries: readonly ResponsiveEntry<T>[]\n): ResponsiveSet<T> {\n return {\n entries,\n watch: (host, onChange) => watchResponsive(entries, host, onChange)\n };\n}\n\n/** Merges the overrides of the matching entries over `base`, in order. */\nexport function applyResponsive<T>(\n base: T,\n entries: readonly ResponsiveEntry<Partial<T>>[] | undefined,\n matching: readonly number[],\n merge: (target: T, overrides: Partial<T>) => T\n): T {\n return matching.reduce(\n (result, index) => merge(result, entries![index][1]),\n base\n );\n}\n","/**\n * Shared machinery of the 1.x presets (`lineChart`, `barChart`, …): the 1.x\n * option merge, window responsive options, the preset state that plugins\n * (compat) read, and the grid and label layers.\n */\nimport { chart } from '../chart/chart';\nimport type { ChartConfig, ChartHandle, ChartPlugin } from '../chart/types';\nimport { untyped } from '../chart/types';\nimport type { Layer, LayerContext, PhaseListeners } from '../pipeline/types';\nimport { node, withFields, type SceneNode } from '../scene/node';\nimport type { AxisOptions } from '../core/types';\nimport type { AxisDimension, AxisSetup } from '../scales/axis';\nimport {\n axisNodes,\n gridBackground,\n type AxisClassNames,\n type AxisFrame,\n type DrawnAxisOptions\n} from '../scales/grid';\nimport {\n svgLabels,\n type LabelChartKind,\n type SvgLabelBuilder\n} from '../scales/svgLabels';\nimport {\n applyResponsive,\n watchResponsive,\n type ResponsiveEntry\n} from '../responsive/responsive';\nimport { extend } from '../utils/extend';\n\n/**\n * What a preset passes to plugins as `ResolvedConfig.preset`: its kind, the\n * current 1.x options and 1.x-style updates.\n */\nexport interface PresetState<\n TData = unknown,\n TOptions = unknown,\n TKind extends string = string\n> {\n /** Which preset: `line`, `bar` or `pie`. */\n readonly kind: TKind;\n /**\n * The current options: the given ones over the defaults, with the\n * matching responsive options applied.\n */\n readonly options: TOptions;\n /** The current data. */\n readonly data: TData;\n /**\n * Changes the data, the options or both and redraws, as 1.x `update()`:\n * the options extend the current ones, or with `override`, the defaults.\n */\n update(data?: TData, options?: TOptions, override?: boolean): void;\n /** Stops the chart's responsive updates, as 1.x `detach()`. */\n detach(): void;\n}\n\n/**\n * The handle `lineChart`, `barChart` and `pieChart` return: a\n * {@link ChartHandle} that also changes the chart's options.\n * `update({ data })` changes the preset's data too, so responsive changes\n * redraw with it.\n *\n * @example\n * ```ts\n * import { lineChart } from 'chartist';\n *\n * const chart = lineChart('#chart', { series: [[1, 3, 2, 5]] });\n *\n * // Areas from now on; the other options stay.\n * chart.setOptions({ showArea: true });\n * ```\n * @experimental\n */\nexport interface PresetHandle<TOptions> extends ChartHandle {\n /**\n * Changes the options and redraws: they extend the current options, or\n * with `{ replace: true }`, the defaults, dropping the options given\n * before. Matching responsive options still apply on top. `plugins` and\n * `on` can't change. Coming from 1.x, `setOptions(options)` is\n * `update(undefined, options, true)` and\n * `setOptions(options, { replace: true })` is `update(undefined, options)`.\n * @param options The options to change.\n * @param how `replace: true` starts from the defaults instead of the\n * current options.\n */\n setOptions(\n options: Omit<TOptions, 'plugins' | 'on'>,\n how?: { readonly replace?: boolean }\n ): this;\n}\n\n/** Internal: a preset with 1.x-style data and option updates. */\nexport interface PresetController<TData, TOptions> {\n readonly handle: PresetHandle<TOptions>;\n /** Replaces the data (1.x `update(data)`); call `render()` after. */\n setData(data: TData): void;\n /** 1.x option update: extends the defaults, or the current options. */\n setOptions(options: TOptions, override?: boolean): void;\n render(): void;\n options(): TOptions;\n data(): TData;\n}\n\n/** 1.x axis options whose `type` may also be a v2 axis factory. */\nexport type PresetAxisOptions = Omit<AxisOptions, 'type'> & {\n /** A v2 axis factory or a 1.x axis class. */\n readonly type?: AxisSetup['type'];\n};\n\n/** What a chart type contributes to `createPreset`. */\nexport interface PresetSpec<TData, TOptions> {\n readonly kind: string;\n readonly defaults: object;\n /** The `chart()` config for the data and the merged 1.x options. */\n config(data: TData, options: TOptions): ChartConfig;\n}\n\ninterface ClassNames extends AxisClassNames {\n readonly gridGroup: string;\n readonly labelGroup: string;\n readonly gridBackground: string;\n}\n\n/** 1.x options with the defaults applied, as the shared layers need them. */\nexport interface AxisPresetOptions {\n readonly axisX: DrawnAxisOptions;\n readonly axisY: DrawnAxisOptions;\n readonly showGridBackground?: boolean;\n readonly classNames: ClassNames;\n /** Which 1.x label CSS row SVG text labels follow. */\n readonly labelKind?: LabelChartKind;\n}\n\nfunction frame(\n options: AxisPresetOptions,\n context: LayerContext,\n svgLabel?: SvgLabelBuilder\n): AxisFrame {\n return {\n svgLabel,\n area: context.area,\n padding: context.padding,\n axisX: options.axisX,\n axisY: options.axisY,\n classNames: options.classNames\n };\n}\n\nexport function group(className: string, children: SceneNode[]) {\n return withFields(node('g', {}, className), { children });\n}\n\n/** `g.ct-grids`: grid lines per axis in `order`, the background first. */\nexport function gridLayer(\n options: AxisPresetOptions,\n order: readonly AxisDimension[] = ['x', 'y']\n): Layer {\n return {\n type: 'grid',\n coordinates: ['cartesian'],\n compose(context) {\n const lines = order.flatMap(dimension => {\n const axis = context.axes[dimension];\n return axis ? axisNodes(axis, frame(options, context)).grids : [];\n });\n if (options.showGridBackground) {\n lines.unshift(\n gridBackground(context.area, options.classNames.gridBackground)\n );\n }\n return [group(options.classNames.gridGroup, lines)];\n }\n };\n}\n\n/** `g.ct-labels`: labels per axis in `order`. */\nexport function labelLayer(\n options: AxisPresetOptions,\n order: readonly AxisDimension[] = ['x', 'y']\n): Layer {\n return {\n type: 'labels',\n coordinates: ['cartesian'],\n compose(context) {\n const svgLabel =\n context.labels === 'svg'\n ? svgLabels(context.measureText, options.labelKind ?? 'line')\n : undefined;\n return [\n group(\n options.classNames.labelGroup,\n order.flatMap(dimension => {\n const axis = context.axes[dimension];\n return axis\n ? axisNodes(axis, frame(options, context, svgLabel)).labels\n : [];\n })\n )\n ];\n }\n };\n}\n\n/**\n * Wraps a layer's output in the unclassed 1.x series group; everything\n * else about the layer (its series, axes, extent) stays.\n */\nexport function seriesGroup(layer: Layer): Layer {\n return {\n ...layer,\n compose: context => [group('', [...layer.compose(context)])]\n };\n}\n\n/**\n * The property of a preset's chart handle that holds its {@link PresetState}\n * from the moment plugins install, before the first `resolve` hands it over\n * in the config. The compat plugin reads it to give 1.x plugins the chart's\n * data and options while they install, as 1.x did. A global symbol, so\n * separate builds of the core and `chartist/compat` share it.\n */\nexport const PRESET_STATE = Symbol.for('chartist.presetState');\n\n/**\n * Adds the 1.x inline size style to the root svg. Installed first, it also\n * puts the preset state on the handle for the plugins after it.\n */\nfunction rootStyle(\n getOptions: () => { width?: number | string; height?: number | string },\n state: PresetState\n): ChartPlugin {\n return {\n name: 'preset-root-style',\n install(handle) {\n Object.defineProperty(handle, PRESET_STATE, { value: state });\n handle.on('scene', ({ scene }) => {\n const { width = '100%', height = '100%' } = getOptions();\n return {\n scene: scene.attr({ style: `width: ${width}; height: ${height};` })\n };\n });\n }\n };\n}\n\n/**\n * Internal: a preset's chart config for data and options, without a\n * container. The options extend the preset's defaults as in\n * `createPreset`; the root gets no inline size style, which only sizes the\n * svg in a container.\n */\nexport function presetConfig<\n TData extends { labels?: unknown[]; series?: unknown[] },\n TOptions\n>(\n spec: PresetSpec<TData, TOptions>,\n data: TData,\n options?: TOptions\n): ChartConfig {\n const resolved = extend({}, spec.defaults, options) as TOptions;\n const { plugins, on } = (options ?? {}) as Pick<\n ChartConfig,\n 'plugins' | 'on'\n >;\n return {\n // As 1.x: missing labels and series are empty.\n ...spec.config(\n { ...data, labels: data.labels || [], series: data.series || [] },\n resolved\n ),\n plugins,\n on\n };\n}\n\n/**\n * Responsive options of presets: the 1.x media query pairs, plus container\n * conditions (`container()`). Matching entries extend the options in order.\n * @experimental\n */\nexport type PresetResponsiveOptions<T> = readonly ResponsiveEntry<T>[];\n\n/** Internal: creates a preset chart; used by the preset functions and classes. */\nexport function createPreset<\n TData extends { labels?: unknown[]; series?: unknown[] },\n TOptions extends { width?: number | string; height?: number | string }\n>(\n spec: PresetSpec<TData, TOptions>,\n target: string | Element,\n initialData: TData,\n options: TOptions = {} as TOptions,\n responsiveOptions?: PresetResponsiveOptions<TOptions>,\n plugins: ChartConfig['plugins'] = (options as { plugins?: unknown })\n .plugins as ChartConfig['plugins']\n): PresetController<TData, TOptions> {\n let data = initialData;\n let base = extend({}, spec.defaults, options) as TOptions;\n // Created before the chart: on a resize that crosses a container\n // breakpoint, its callback runs first and renders the new size once.\n const watcher = watchResponsive(\n responsiveOptions ?? [],\n (typeof target === 'string' ? document.querySelector(target) : target) ??\n undefined,\n () => onResponsiveChange(),\n true\n );\n const withResponsive = (baseOptions: TOptions) =>\n applyResponsive(\n extend({}, baseOptions) as TOptions,\n responsiveOptions as PresetResponsiveOptions<Partial<TOptions>>,\n watcher.matching,\n (result, overrides) => extend({}, result, overrides) as TOptions\n );\n let current = withResponsive(base);\n\n const withState = (config: ChartConfig): ChartConfig => ({\n ...config,\n // Generic here; each preset's spec gives its own kind, data and options.\n preset: state as ChartConfig['preset']\n });\n\n const controller: PresetController<TData, TOptions> = {\n get handle() {\n return handle;\n },\n setData(next) {\n // As 1.x: missing labels and series default to empty arrays.\n next.labels = next.labels || [];\n next.series = next.series || [];\n data = next;\n },\n setOptions(next, override = false) {\n base = extend({}, override ? base : spec.defaults, next) as TOptions;\n current = withResponsive(base);\n },\n render() {\n inner.update(withState(spec.config(data, current)));\n },\n options: () => current,\n data: () => data\n };\n\n const state: PresetState<TData, TOptions> = {\n kind: spec.kind,\n get options() {\n return current;\n },\n get data() {\n return data;\n },\n update(nextData, nextOptions, override) {\n if (nextData) {\n controller.setData(nextData);\n }\n if (nextOptions) {\n controller.setOptions(nextOptions, override);\n }\n controller.render();\n },\n // A detach() during the first render (from a listener or a 1.x plugin)\n // runs before the handle exists, so it's applied once it does.\n detach: () => {\n if (ready) {\n handle.detach();\n } else {\n detachedEarly = true;\n }\n }\n };\n let ready = false;\n let detachedEarly = false;\n\n const inner = chart(target, {\n ...withState(spec.config(data, current)),\n plugins: [rootStyle(() => current, state), ...(plugins ?? [])],\n on: (options as { on?: PhaseListeners }).on\n });\n\n function onResponsiveChange() {\n const previousOptions = current;\n current = withResponsive(base);\n inner.emit('responsive', { previousOptions, currentOptions: current });\n controller.render();\n }\n\n const handle: PresetHandle<TOptions> = {\n container: inner.container,\n update(changes) {\n // Kept as the preset's data, so responsive changes and plugins\n // reading the preset state (compat) see it.\n if (changes.data) {\n data = changes.data as TData;\n }\n inner.update(changes);\n return handle;\n },\n setOptions(next, how) {\n // The controller's flag is 1.x's: true extends the current options.\n controller.setOptions(next as TOptions, !how?.replace);\n controller.render();\n return handle;\n },\n detach() {\n watcher.stop();\n inner.detach();\n return handle;\n },\n destroy() {\n handle.detach();\n inner.destroy();\n },\n emit: (name, payload) => untyped(inner).emit(name, payload),\n on: ((name: never, listener: never) => {\n inner.on(name, listener);\n return handle;\n }) as PresetHandle<TOptions>['on'],\n off: ((name: never, listener?: never) => {\n inner.off(name, listener);\n return handle;\n }) as PresetHandle<TOptions>['off']\n };\n ready = true;\n if (detachedEarly) {\n handle.detach();\n }\n return controller;\n}\n","/**\n * `lineChart`: the 1.x line chart as a preset over `chart()`. Takes the 1.x\n * arguments and options and renders the 1.x structure.\n */\nimport type {\n LineChartData,\n LineChartOptions\n} from '../charts/LineChart/LineChart.types';\nimport type { Label } from '../core/types';\nimport type { ChartConfig, PluginEntry } from '../chart/types';\nimport type { PhaseListeners } from '../pipeline/types';\nimport { line, type LineSeriesOptions } from '../layers/line';\nimport type { AxisFactory, AxisSetup, AxesConfig } from '../scales/axis';\nimport type { LabelMode } from '../render/measure';\nimport { presetAxes } from '../scales/cartesian';\nimport { autoScaleAxis, stepAxis } from '../scales/factories';\nimport { isNumeric } from '../utils/utils';\nimport { lineDefaults } from './lineDefaults';\nimport {\n createPreset,\n presetConfig,\n gridLayer,\n labelLayer,\n seriesGroup,\n type AxisPresetOptions,\n type PresetAxisOptions,\n type PresetController,\n type PresetHandle,\n type PresetSpec,\n type PresetState,\n type PresetResponsiveOptions\n} from './preset';\n\n/**\n * Options of `lineChart`: the 1.x `LineChart` options; axis types may also\n * be v2 axis factories.\n * @experimental\n */\nexport type LineChartPresetOptions = Omit<\n LineChartOptions,\n 'axisX' | 'axisY' | 'plugins' | 'series'\n> & {\n /** v2 plugins; convert 1.x plugins with `fromLegacyPlugin`. */\n readonly plugins?: readonly PluginEntry[];\n /**\n * Phase listeners by phase name (or `'*'` for all phases), as `on` in\n * the config of `chart()`. They're registered before the first render,\n * so they see it too.\n */\n readonly on?: PhaseListeners;\n /** Options per series name: only these five apply per series. */\n readonly series?: Readonly<Record<string, LineSeriesOptions>>;\n /** Options of the X axis; its `type` may also be a v2 axis factory. */\n readonly axisX?: PresetAxisOptions &\n Omit<NonNullable<LineChartOptions['axisX']>, 'type'>;\n /** Options of the Y axis; its `type` may also be a v2 axis factory. */\n readonly axisY?: PresetAxisOptions &\n Omit<NonNullable<LineChartOptions['axisY']>, 'type'>;\n /** HTML (1.x) or SVG text labels; default: the renderer's mode. */\n readonly labels?: LabelMode;\n};\n\ntype Resolved = typeof lineDefaults & LineChartPresetOptions;\n\n/** What the line preset passes to plugins as `ResolvedConfig.preset`. */\nexport type LinePresetState = PresetState<\n LineChartData,\n LineChartPresetOptions,\n 'line'\n>;\n\n/** Internal: the line preset with 1.x-style data and option updates. */\nexport type LineChartController = PresetController<\n LineChartData,\n LineChartPresetOptions\n>;\n\n/** The default 1.x X axis: one step per label; `fullWidth` stretches it. */\nfunction labelStepAxis(stretch: boolean): AxisFactory {\n const step = stepAxis();\n return {\n kind: 'step',\n create: context =>\n step.create({\n ...context,\n options: {\n ...context.options,\n ticks: context.labels as Label[],\n stretch\n }\n })\n };\n}\n\nfunction axesConfig(options: Resolved): AxesConfig {\n const { axisX, axisY } = options;\n const x: AxisSetup = {\n ...axisX,\n type: axisX.type ?? labelStepAxis(options.fullWidth)\n };\n const y: AxisSetup =\n axisY.type === undefined\n ? {\n ...axisY,\n type: autoScaleAxis(),\n high: isNumeric(options.high) ? options.high : axisY.high,\n low: isNumeric(options.low) ? options.low : axisY.low,\n // As for bars, the axis's own reference value wins.\n referenceValue: axisY.referenceValue ?? options.referenceValue\n }\n : { ...axisY, type: axisY.type };\n return { x, y, reverseData: options.reverseData };\n}\n\nconst lineSpec: PresetSpec<LineChartData, LineChartPresetOptions> = {\n kind: 'line',\n defaults: lineDefaults,\n config(data, preset): ChartConfig {\n const options = preset as Resolved;\n const axisOptions = options as unknown as AxisPresetOptions;\n return {\n data,\n axes: presetAxes(axesConfig(options)),\n padding: options.chartPadding,\n width: options.width,\n height: options.height,\n viewBox: options.viewBox,\n className: options.classNames.chart,\n labels: options.labels,\n layers: [\n gridLayer(axisOptions),\n seriesGroup(\n line({\n lineSmooth: options.lineSmooth,\n showPoint: options.showPoint,\n showLine: options.showLine,\n showArea: options.showArea,\n areaBase: options.areaBase,\n overrides: options.series,\n reverseData: options.reverseData,\n classNames: options.classNames\n })\n ),\n labelLayer(axisOptions)\n ]\n };\n }\n};\n\n/**\n * Builds the chart config that `lineChart()` renders for the data and\n * options, without a container: the line layer with its axes, grid and labels. Pass it to `toScene()` to render\n * the preset chart with another renderer. Responsive options and the\n * inline size style of the root svg are left out; both need a container.\n * @example\n * ```ts\n * import { lineChartConfig, renderToString, toScene } from 'chartist';\n *\n * const config = lineChartConfig(\n * { labels: ['Mon', 'Tue', 'Wed'], series: [[5, 2, 4]] },\n * { showArea: true }\n * );\n * export const svg = renderToString(\n * toScene(config, { width: 600, height: 300 })\n * );\n * ```\n * @experimental\n */\nexport function lineChartConfig(\n data: LineChartData,\n options: LineChartPresetOptions = {}\n): ChartConfig {\n return presetConfig(lineSpec, data, options);\n}\n\n/** Internal: creates the line preset; used by `lineChart` and `LineChart`. */\nexport function createLineChart(\n target: string | Element,\n data: LineChartData,\n options: LineChartPresetOptions = {},\n responsiveOptions?: PresetResponsiveOptions<LineChartPresetOptions>,\n plugins?: ChartConfig['plugins']\n): LineChartController {\n return createPreset(\n lineSpec,\n target,\n data,\n options,\n responsiveOptions,\n plugins ?? options.plugins\n );\n}\n\n/**\n * Creates a line chart with the 1.x options and output, rendered\n * synchronously. Plugins must be v2 plugins; convert 1.x plugins with\n * `fromLegacyPlugin` from `chartist/compat`.\n * @experimental\n */\nexport function lineChart(\n target: string | Element,\n data: LineChartData,\n options: LineChartPresetOptions = {},\n responsiveOptions?: PresetResponsiveOptions<LineChartPresetOptions>\n): PresetHandle<LineChartPresetOptions> {\n return createLineChart(target, data, options, responsiveOptions).handle;\n}\n","import type { ChartHandle, ChartPlugin, PluginEntry } from '../chart/types';\nimport { untyped } from '../chart/types';\nimport { asUserListeners } from '../chart/plugins';\nimport type { Data, Options, ResponsiveOptions } from '../core';\nimport type { AllEventsListener, EventListener } from '../event';\nimport type { PresetController } from '../presets/preset';\nimport { extend } from '../utils';\nimport { BaseChart } from './BaseChart';\n\n/** What the class needs from the compat plugin to run 1.x plugins. */\ninterface LegacyPluginRunner {\n legacyPlugin(\n plugin: (chart: unknown, options?: unknown) => void,\n options: unknown,\n chart: unknown\n ): ChartPlugin;\n}\n\nconst warnedPlugins = new Set<unknown>();\n\nconst PHASES = new Set([\n 'resolve',\n 'prepare',\n 'layout',\n 'compose',\n 'scene',\n 'render',\n 'mount'\n]);\n\n/**\n * Splits 1.x plugin options into v2 plugins. Plugin functions run through\n * the compat plugin (found by duck typing, so the class never imports it),\n * or are skipped with a one-time warning.\n */\nfunction v2Plugins(plugins: readonly unknown[], chart: object) {\n const runner = plugins.find(\n (entry): entry is LegacyPluginRunner =>\n typeof (entry as Partial<LegacyPluginRunner> | null)?.legacyPlugin ===\n 'function'\n );\n return plugins.flatMap(entry => {\n const [plugin, options] = Array.isArray(entry) ? entry : [entry];\n if (typeof plugin !== 'function') {\n return [entry as PluginEntry];\n }\n if (runner) {\n return [runner.legacyPlugin(plugin, options, chart)];\n }\n if (!warnedPlugins.has(plugin)) {\n warnedPlugins.add(plugin);\n // Intentional: tells 1.x users how to migrate.\n // eslint-disable-next-line no-console\n console.warn(\n `Chartist: the plugin \"${plugin.name || 'anonymous'}\" looks like a 1.x plugin (a plain function) and was skipped. 1.x plugins run only with the compat plugin: add compat from chartist/compat to plugins.`\n );\n }\n return [];\n });\n}\n\n/**\n * Base of the 1.x chart classes that wrap a v2 preset. Keeps the 1.x API:\n * deferred first render, `update(data, options, override)`, `detach()`,\n * `on`/`off`, and re-rendering when the window resizes (and, like the chart\n * functions, when the container does). 1.x events and 1.x plugin functions\n * need the compat plugin (`chartist/compat`).\n */\nexport abstract class PresetChart<\n TEventsTypes,\n TData extends Data,\n TOptions extends Options\n> extends BaseChart<TEventsTypes> {\n private controller?: PresetController<TData, TOptions>;\n /** The chart handle while plugins install (before `controller` is set). */\n private installing?: ChartHandle;\n private readonly queued: [string, EventListener | AllEventsListener][] = [];\n private readonly onWindowResize = () => this.update();\n /** Set by detach(), also when a listener of the first render calls it. */\n private detached = false;\n private readonly wildcards = new Map<AllEventsListener, AllEventsListener>();\n\n constructor(\n query: string | Element | null,\n protected override data: TData,\n defaults: TOptions,\n private chartOptions?: TOptions,\n private readonly chartResponsiveOptions?: ResponsiveOptions<TOptions>\n ) {\n super(\n query,\n data,\n defaults,\n extend({}, defaults, chartOptions),\n chartResponsiveOptions as ResponsiveOptions<Options>\n );\n // 1.x plugins use chart.eventEmitter, e.g. for Svg.animate events.\n Object.defineProperty(this, 'eventEmitter', {\n value: {\n on: (event: string, listener: EventListener) =>\n this.on(event, listener),\n off: (event: string, listener?: EventListener) =>\n this.off(event, listener),\n emit: (event: string, payload: unknown) =>\n this.controller &&\n untyped(this.controller.handle).emit(event, payload)\n }\n });\n }\n\n /** Creates the preset this class wraps. */\n protected abstract createController(\n container: Element,\n data: TData,\n options: TOptions | undefined,\n responsiveOptions: ResponsiveOptions<TOptions> | undefined,\n plugins: PluginEntry[]\n ): PresetController<TData, TOptions>;\n\n override initialize() {\n (this as unknown as { initializeTimeoutId: null }).initializeTimeoutId =\n null;\n const queued = this.queued.splice(0);\n const listeners: ChartPlugin = {\n name: 'chart-listeners',\n install: handle => {\n // 1.x plugins call chart.on() while they install.\n this.installing = handle;\n // The queued listeners are the user's, though added from a plugin,\n // so off(name) removes them.\n asUserListeners(handle, () =>\n queued.forEach(([event, listener]) =>\n this.on(event as never, listener as never)\n )\n );\n }\n };\n // Keeps the 1.x fields that plugins read (data, options) current. The\n // compat plugin sets `svg` for 1.x plugins, so the class doesn't need\n // the Svg wrapper.\n const syncFields: ChartPlugin = {\n name: 'chart-fields',\n install: handle =>\n void handle\n // The 1.x classes always draw HTML labels (no v2 features).\n .on('resolve', ({ config }) =>\n config.labels\n ? { config: { ...config, labels: undefined } }\n : undefined\n )\n .on('mount', () => {\n if (this.controller) {\n this.data = this.controller.data();\n (this as unknown as { options: unknown }).options =\n this.controller.options();\n }\n })\n };\n // Added before the first render (as 1.x does), so a detach() from one of\n // its listeners removes it. The container's window may be an iframe's.\n this.container.ownerDocument.defaultView?.addEventListener(\n 'resize',\n this.onWindowResize\n );\n this.controller = this.createController(\n this.container,\n this.data,\n this.chartOptions,\n // The 1.x classes keep media queries only (no container()).\n this.chartResponsiveOptions?.filter(\n ([condition]) => typeof condition === 'string'\n ),\n [\n listeners,\n syncFields,\n ...v2Plugins(this.chartOptions?.plugins ?? [], this)\n ]\n );\n this.installing = undefined;\n if (this.detached) {\n this.controller.handle.detach();\n }\n }\n\n createChart() {\n // Rendering is done by the wrapped preset.\n }\n\n /**\n * Updates the chart. New options extend the defaults, or the current\n * options when `override` is true (1.x semantics).\n */\n override update(data?: Data, options?: TOptions, override = false) {\n if (data) {\n this.data = data as TData;\n }\n if (options) {\n this.chartOptions = extend(\n {},\n override ? this.chartOptions : {},\n options\n ) as TOptions;\n }\n if (this.controller) {\n if (data) {\n this.controller.setData(data as TData);\n }\n if (options) {\n this.controller.setOptions(options as TOptions, override);\n }\n this.controller.render();\n }\n return this;\n }\n\n /** Stops resize and media query handling; the chart stays rendered. */\n override detach() {\n super.detach();\n this.detached = true;\n this.container.ownerDocument.defaultView?.removeEventListener(\n 'resize',\n this.onWindowResize\n );\n this.controller?.handle.detach();\n return this;\n }\n\n override on<T extends keyof TEventsTypes>(\n event: T,\n listener: EventListener<TEventsTypes[T]>\n ): this;\n override on(event: '*', listener: AllEventsListener): this;\n override on(event: string, listener: EventListener): this;\n override on(event: string, listener: EventListener | AllEventsListener) {\n const handle = this.controller?.handle ?? this.installing;\n if (!handle) {\n this.queued.push([event, listener]);\n } else if (event === '*') {\n // As 1.x: '*' listeners receive chart events, not the v2 phases.\n const wildcard = listener as AllEventsListener;\n const filtered: AllEventsListener = (name, payload) => {\n if (!PHASES.has(name)) {\n wildcard(name, payload);\n }\n };\n this.wildcards.set(wildcard, filtered);\n handle.on('*', filtered);\n } else {\n untyped(handle).on(event, listener as (payload: unknown) => void);\n }\n return this;\n }\n\n override off<T extends keyof TEventsTypes>(\n event: T,\n listener?: EventListener<TEventsTypes[T]>\n ): this;\n override off(event: '*', listener?: AllEventsListener): this;\n override off(event: string, listener?: EventListener): this;\n override off(event: string, listener?: EventListener | AllEventsListener) {\n const handle = this.controller?.handle ?? this.installing;\n if (handle) {\n const target =\n event === '*' && listener\n ? this.wildcards.get(listener as AllEventsListener)\n : listener;\n untyped(handle).off(\n event,\n target as ((payload: unknown) => void) | undefined\n );\n } else {\n const index = this.queued.findIndex(\n ([name, queuedListener]) =>\n name === event && (!listener || queuedListener === listener)\n );\n if (listener && index >= 0) {\n this.queued.splice(index, 1);\n } else if (!listener) {\n this.queued.splice(\n 0,\n this.queued.length,\n ...this.queued.filter(([name]) => name !== event)\n );\n }\n }\n return this;\n }\n}\n","import type {\n LineChartData,\n LineChartOptions,\n LineChartOptionsWithDefaults,\n LineChartEventsTypes\n} from './LineChart.types';\nimport type { Series, SeriesObject, ResponsiveOptions } from '../../core';\nimport type { PluginEntry } from '../../chart/types';\nimport {\n createLineChart,\n type LineChartPresetOptions\n} from '../../presets/lineChart';\nimport { lineDefaults } from '../../presets/lineDefaults';\nimport type { PresetController } from '../../presets/preset';\nimport { safeHasProperty } from '../../utils';\nimport { PresetChart } from '../PresetChart';\n\n/**\n * Reads a line chart option for a series: the per-series value from\n * `options.series[name]` if the series has a name and sets it, the chart's\n * value otherwise.\n *\n * @deprecated Part of the 1.x chart classes, with no functional counterpart. Removed in 3.0.\n */\nexport function getSeriesOption<\n T extends keyof Omit<LineChartOptionsWithDefaults, 'series'>\n>(\n series: Series | SeriesObject,\n options: LineChartOptionsWithDefaults,\n key: T\n) {\n if (\n safeHasProperty(series, 'name') &&\n series.name &&\n options.series?.[series.name]\n ) {\n const seriesOptions = options?.series[series.name];\n const value = seriesOptions[key];\n const result = value === undefined ? options[key] : value;\n\n return result as LineChartOptionsWithDefaults[T];\n } else {\n return options[key];\n }\n}\n\n/**\n * The 1.x line chart class: a wrapper over the `lineChart` preset with the\n * 1.x API. 1.x events and 1.x plugin functions need the compat plugin\n * (`chartist/compat`).\n * @see {@link lineChart} for the v2 functional API.\n *\n * @deprecated Use `lineChart()`. Removed in 3.0.\n */\nexport class LineChart extends PresetChart<\n LineChartEventsTypes,\n LineChartData,\n LineChartOptions\n> {\n /**\n * Creates a line chart. The first render happens on the next tick, so\n * listeners registered right after construction receive it.\n * @param query A selector query string or a DOM element\n * @param data The data with labels and series\n * @param options Options that override the defaults\n * @param responsiveOptions `[mediaQuery, options]` pairs\n */\n constructor(\n query: string | Element | null,\n data: LineChartData,\n options?: LineChartOptions,\n responsiveOptions?: ResponsiveOptions<LineChartOptions>\n ) {\n super(\n query,\n data,\n lineDefaults as LineChartOptions,\n options,\n responsiveOptions\n );\n }\n\n protected createController(\n container: Element,\n data: LineChartData,\n options: LineChartOptions | undefined,\n responsiveOptions: ResponsiveOptions<LineChartOptions> | undefined,\n plugins: PluginEntry[]\n ) {\n return createLineChart(\n container,\n data,\n options as LineChartPresetOptions,\n responsiveOptions as ResponsiveOptions<LineChartPresetOptions>,\n plugins\n ) as unknown as PresetController<LineChartData, LineChartOptions>;\n }\n}\n","/**\n * Bar layer: bars per series, drawn like 1.x `BarChart` (geometry, stacking,\n * classes and `ct:` attributes).\n */\nimport { getMetaData } from '../core/data/data';\nimport { serialize } from '../core/data/serialize';\nimport { alphaNumerate } from '../core/lang';\nimport type { NormalizedSeries, Series, SeriesObject } from '../core/types';\nimport type { Layer, PreparedSeries } from '../pipeline/types';\nimport type { AxisExtent } from '../scales/axis';\nimport { node, withFields, type SceneNode } from '../scene/node';\nimport { isNumeric, safeHasProperty } from '../utils/utils';\n\n/**\n * The options of the {@link bar} layer. Without them, it draws the bars of\n * each label side by side, 15 px apart, on the first X and Y axis.\n * @experimental\n */\nexport interface BarLayerOptions {\n /** Series to draw, by index or name; default: all series. */\n readonly series?: readonly (number | string)[];\n /** The id of the X axis to draw on; default: the first X axis. */\n readonly x?: string;\n /** The id of the Y axis to draw on; default: the first Y axis. */\n readonly y?: string;\n /** Values on the X axis, labels on the Y axis. */\n readonly horizontalBars?: boolean;\n /**\n * Stacks the bars of a label on each other; `stackMode` says how. The\n * value axis grows to fit the stacks (see {@link Layer.extent}).\n */\n readonly stackBars?: boolean;\n /**\n * How stacked bars stack: `accumulate` (default) adds each value to the\n * ones before, `accumulate-relative` stacks positive values up and\n * negative values down from zero, and `overlap` (or `true`) draws every\n * bar from zero, on top of each other.\n */\n readonly stackMode?:\n | 'accumulate'\n | 'accumulate-relative'\n | 'overlap'\n | boolean;\n /** Distance between the bars of different series, in px. */\n readonly seriesBarDistance?: number;\n /** One series per value of a flat series (1.x `distributeSeries`). */\n readonly distributeSeries?: boolean;\n /**\n * Draws the series in reverse order (1.x `reverseData`). Can't be\n * combined with `series`.\n */\n readonly reverseData?: boolean;\n /**\n * Replaces the classes of what the layer draws: `series` (`ct-series`)\n * and `bar` (`ct-bar`).\n */\n readonly classNames?: { readonly series?: string; readonly bar?: string };\n}\n\n/** A value along one dimension; holes and missing values count as 0. */\nfunction valueAlong(value: unknown, dimension: 'x' | 'y') {\n const raw =\n value !== null && typeof value === 'object'\n ? (value as Record<string, unknown>)[dimension]\n : value;\n return isNumeric(raw) ? Number(raw) : 0;\n}\n\n/**\n * The range stacked bars reach on the value axis: per index, the running\n * sums of the values in series order (`accumulate`), or of the positive\n * and the negative values apart (`accumulate-relative`). Undefined\n * without values.\n */\nexport function stackedExtent(\n series: readonly NormalizedSeries[],\n dimension: 'x' | 'y',\n relative = false\n): AxisExtent | undefined {\n const positive: number[] = [];\n const negative: number[] = [];\n let low = Infinity;\n let high = -Infinity;\n for (const values of series) {\n values.forEach((value, index) => {\n const amount = valueAlong(value, dimension);\n const sums = relative && amount < 0 ? negative : positive;\n sums[index] = (sums[index] ?? 0) + amount;\n low = Math.min(low, sums[index]);\n high = Math.max(high, sums[index]);\n });\n }\n return low <= high ? { low, high } : undefined;\n}\n\nfunction rawSeries(series: PreparedSeries): Series | SeriesObject {\n return {\n name: series.name,\n className: series.className,\n meta: series.meta,\n data: series.values\n } as SeriesObject;\n}\n\n/**\n * Creates a layer that draws series as bars, in the markup of the 1.x bar\n * chart (`g.ct-series` with a `line.ct-bar` per value). The label axis is\n * X (Y with `horizontalBars`), the value axis the other one; both come\n * from {@link cartesianAxes}.\n *\n * Bars grow from zero on the value axis, so keep zero on it: `low: 0`, or\n * `referenceValue: 0`. On a step axis they sit in the middle of each step.\n *\n * @example\n * ```ts\n * import {\n * autoScaleAxis,\n * axisGrid,\n * axisLabels,\n * bar,\n * cartesianAxes,\n * chart,\n * stepAxis\n * } from 'chartist';\n *\n * const quarters = ['Q1', 'Q2', 'Q3', 'Q4'];\n *\n * chart('#chart', {\n * data: {\n * labels: quarters,\n * series: [\n * [800, 1200, 1400, 1300],\n * [200, 400, 500, 300]\n * ]\n * },\n * axes: cartesianAxes([\n * { id: 'quarter', side: 'bottom', type: stepAxis(), ticks: quarters },\n * { id: 'sales', side: 'left', type: autoScaleAxis(), low: 0 }\n * ]),\n * layers: [axisGrid(), bar({ seriesBarDistance: 12 }), axisLabels()],\n * className: 'ct-chart-bar'\n * });\n * ```\n * @experimental\n */\nexport function bar(options: BarLayerOptions = {}): Layer {\n const classNames = {\n series: 'ct-series',\n bar: 'ct-bar',\n ...options.classNames\n };\n const horizontal = Boolean(options.horizontalBars);\n const seriesBarDistance = options.seriesBarDistance ?? 15;\n const stackMode = options.stackMode ?? 'accumulate';\n // `overlap` and `true` draw every bar from zero: the values fit them.\n const stacks =\n options.stackBars && stackMode !== 'overlap' && stackMode !== true;\n return {\n type: 'bar',\n coordinates: ['cartesian'],\n axes: { x: options.x, y: options.y },\n series: options.series,\n extent({ normalized, axes }) {\n const id = horizontal ? axes.x : axes.y;\n const extent =\n stacks && id !== undefined\n ? stackedExtent(\n normalized.series,\n horizontal ? 'x' : 'y',\n stackMode === 'accumulate-relative'\n )\n : undefined;\n return id !== undefined && extent ? { [id]: extent } : {};\n },\n compose({ data, area, axes, normalized, seriesIndexes }) {\n const valueAxis = horizontal ? axes.x : axes.y;\n const labelAxis = horizontal ? axes.y : axes.x;\n if (!valueAxis || !labelAxis || !normalized) {\n throw new Error('Layer \"bar\" needs an x and a y axis');\n }\n const labelPos = horizontal ? 'y' : 'x';\n const counterPos = horizontal ? 'x' : 'y';\n const series = normalized.series as NormalizedSeries[];\n // As 1.x: a flat (distributed) series iterates its values as series.\n const raw: unknown[] = data.flat\n ? [...data.series[0].values]\n : data.series.map(rawSeries);\n const order = raw.map((_, i) => i);\n if (options.reverseData) {\n order.reverse();\n }\n\n const zeroPoint = horizontal\n ? area.x1 + valueAxis.project(0)\n : area.y1 - valueAxis.project(0);\n const isAccumulate = stackMode === 'accumulate';\n const isAccumulateRelative = stackMode === 'accumulate-relative';\n const posStack: number[] = [];\n const negStack: number[] = [];\n let stack = posStack;\n\n if (seriesIndexes && options.reverseData) {\n throw new Error(\n 'Layer \"bar\": a series selection can\\'t be combined with reverseData'\n );\n }\n\n return order.map((dataIndex, localIndex) => {\n // The chart-wide index, for classes, keys and contexts.\n const seriesIndex = seriesIndexes?.[dataIndex] ?? localIndex;\n const current = raw[dataIndex] as Series | SeriesObject;\n // Bar offsets count within the layer, as 1.x counts within a chart.\n const biPol = localIndex - (raw.length - 1) / 2;\n let periodHalfLength: number;\n if (options.distributeSeries && !options.stackBars) {\n periodHalfLength = labelAxis.length / series.length / 2;\n } else if (options.distributeSeries && options.stackBars) {\n periodHalfLength = labelAxis.length / 2;\n } else {\n periodHalfLength = labelAxis.length / series[localIndex].length / 2;\n }\n\n const seriesName = safeHasProperty(current, 'name') && current.name;\n const seriesClassName =\n safeHasProperty(current, 'className') && current.className;\n const seriesMeta = safeHasProperty(current, 'meta')\n ? current.meta\n : undefined;\n const bars: SceneNode[] = [];\n\n series[localIndex].forEach((value, valueIndex) => {\n const valueX = safeHasProperty(value, 'x') && value.x;\n const valueY = safeHasProperty(value, 'y') && value.y;\n const labelIndex =\n options.distributeSeries && !options.stackBars\n ? localIndex\n : options.distributeSeries && options.stackBars\n ? 0\n : valueIndex;\n const values = series[localIndex];\n const projected = horizontal\n ? {\n x: area.x1 + valueAxis.project(valueX || 0, valueIndex, values),\n y: area.y1 - labelAxis.project(valueY || 0, labelIndex, values)\n }\n : {\n x: area.x1 + labelAxis.project(valueX || 0, labelIndex, values),\n y: area.y1 - valueAxis.project(valueY || 0, valueIndex, values)\n };\n\n if (labelAxis.kind === 'step') {\n if (!labelAxis.stretch) {\n projected[labelPos] += periodHalfLength * (horizontal ? -1 : 1);\n }\n projected[labelPos] +=\n options.stackBars || options.distributeSeries\n ? 0\n : biPol * seriesBarDistance * (horizontal ? -1 : 1);\n }\n\n if (isAccumulateRelative) {\n // By the value along the value axis only: the other one is\n // missing or a position (#1469).\n stack =\n Number(horizontal ? valueX : valueY) < 0 ? negStack : posStack;\n }\n const previousStack = stack[valueIndex] || zeroPoint;\n stack[valueIndex] =\n previousStack - (zeroPoint - projected[counterPos]);\n\n if (value === undefined) {\n return;\n }\n\n const positions = {\n [`${labelPos}1`]: projected[labelPos],\n [`${labelPos}2`]: projected[labelPos]\n } as Record<'x1' | 'y1' | 'x2' | 'y2', number>;\n if (\n options.stackBars &&\n (isAccumulate || isAccumulateRelative || !stackMode)\n ) {\n positions[`${counterPos}1`] = previousStack;\n positions[`${counterPos}2`] = stack[valueIndex];\n } else {\n positions[`${counterPos}1`] = zeroPoint;\n positions[`${counterPos}2`] = projected[counterPos];\n }\n positions.x1 = Math.min(Math.max(positions.x1, area.x1), area.x2);\n positions.x2 = Math.min(Math.max(positions.x2, area.x1), area.x2);\n positions.y1 = Math.min(Math.max(positions.y1, area.y2), area.y1);\n positions.y2 = Math.min(Math.max(positions.y2, area.y2), area.y1);\n\n const meta = getMetaData(current, valueIndex);\n bars.push(\n node(\n 'line',\n {\n ...positions,\n 'ct:value': [valueX, valueY].filter(isNumeric).join(','),\n 'ct:meta': serialize(meta) as string | undefined\n },\n classNames.bar,\n {\n role: 'bar',\n ctx: {\n series: current,\n seriesIndex,\n valueIndex,\n value,\n meta,\n ...positions\n }\n }\n )\n );\n });\n\n const group = node(\n 'g',\n {\n 'ct:series-name': seriesName || undefined,\n 'ct:meta': seriesMeta\n ? (serialize(seriesMeta) as string)\n : undefined\n },\n `${classNames.series} ${\n seriesClassName ||\n `${classNames.series}-${alphaNumerate(seriesIndex)}`\n }`,\n {\n role: 'series',\n ctx: { series: current, seriesIndex, meta: seriesMeta }\n }\n );\n return withFields(group, { children: bars });\n });\n }\n };\n}\n","import { noop } from '../utils/functional';\n\n/** The 1.x `BarChart` default options. */\nexport const barDefaults = {\n axisX: {\n offset: 30,\n position: 'end' as const,\n labelOffset: { x: 0, y: 0 },\n showLabel: true,\n showGrid: true,\n labelInterpolationFnc: noop,\n scaleMinSpace: 30,\n onlyInteger: false\n },\n axisY: {\n offset: 40,\n position: 'start' as const,\n labelOffset: { x: 0, y: 0 },\n showLabel: true,\n showGrid: true,\n labelInterpolationFnc: noop,\n scaleMinSpace: 20,\n onlyInteger: false\n },\n width: undefined,\n height: undefined,\n high: undefined,\n low: undefined,\n referenceValue: 0,\n chartPadding: { top: 15, right: 15, bottom: 5, left: 10 },\n seriesBarDistance: 15,\n stackBars: false,\n stackMode: 'accumulate' as const,\n horizontalBars: false,\n distributeSeries: false,\n reverseData: false,\n showGridBackground: false,\n classNames: {\n chart: 'ct-chart-bar',\n horizontalBars: 'ct-horizontal-bars',\n label: 'ct-label',\n labelGroup: 'ct-labels',\n series: 'ct-series',\n bar: 'ct-bar',\n grid: 'ct-grid',\n gridGroup: 'ct-grids',\n gridBackground: 'ct-grid-background',\n vertical: 'ct-vertical',\n horizontal: 'ct-horizontal',\n start: 'ct-start',\n end: 'ct-end'\n }\n};\n","/**\n * `barChart`: the 1.x bar chart as a preset over `chart()`. Takes the 1.x\n * arguments and options and renders the 1.x structure.\n */\nimport type {\n BarChartData,\n BarChartOptions\n} from '../charts/BarChart/BarChart.types';\nimport type { ChartConfig, PluginEntry } from '../chart/types';\nimport type { PhaseListeners } from '../pipeline/types';\nimport { getHighLow } from '../core/data/highLow';\nimport { nonEmptyRange } from '../core/data/range';\nimport type { Label, Options } from '../core/types';\nimport { bar } from '../layers/bar';\nimport type { AxisFactory, AxisSetup, AxesConfig } from '../scales/axis';\nimport type { LabelMode } from '../render/measure';\nimport { presetAxes } from '../scales/cartesian';\nimport { autoScaleAxis, stepAxis } from '../scales/factories';\nimport { isLegacyAxisClass, legacyAxis } from '../scales/legacy';\nimport { barDefaults } from './barDefaults';\nimport {\n createPreset,\n presetConfig,\n gridLayer,\n labelLayer,\n seriesGroup,\n type AxisPresetOptions,\n type PresetAxisOptions,\n type PresetController,\n type PresetHandle,\n type PresetSpec,\n type PresetState,\n type PresetResponsiveOptions\n} from './preset';\n\n/**\n * Options of `barChart`: the 1.x `BarChart` options; axis types may also be\n * v2 axis factories.\n * @experimental\n */\nexport type BarChartPresetOptions = Omit<\n BarChartOptions,\n 'axisX' | 'axisY' | 'plugins' | 'stackMode'\n> & {\n /** v2 plugins; convert 1.x plugins with `fromLegacyPlugin`. */\n readonly plugins?: readonly PluginEntry[];\n /**\n * Phase listeners by phase name (or `'*'` for all phases), as `on` in\n * the config of `chart()`. They're registered before the first render,\n * so they see it too.\n */\n readonly on?: PhaseListeners;\n /**\n * How stacked bars stack: `accumulate` (default), `accumulate-relative`\n * (positives up, negatives down), or `overlap` (also `true`): every bar\n * from zero.\n */\n readonly stackMode?:\n | 'accumulate'\n | 'accumulate-relative'\n | 'overlap'\n | boolean;\n /** Options of the X axis; its `type` may also be a v2 axis factory. */\n readonly axisX?: PresetAxisOptions &\n Omit<NonNullable<BarChartOptions['axisX']>, 'type'>;\n /** Options of the Y axis; its `type` may also be a v2 axis factory. */\n readonly axisY?: PresetAxisOptions &\n Omit<NonNullable<BarChartOptions['axisY']>, 'type'>;\n /** HTML (1.x) or SVG text labels; default: the renderer's mode. */\n readonly labels?: LabelMode;\n};\n\ntype Resolved = Omit<typeof barDefaults, 'stackMode'> & BarChartPresetOptions;\n\n/** What the bar preset passes to plugins as `ResolvedConfig.preset`. */\nexport type BarPresetState = PresetState<\n BarChartData,\n BarChartPresetOptions,\n 'bar'\n>;\n\nexport type BarChartController = PresetController<\n BarChartData,\n BarChartPresetOptions\n>;\n\n/**\n * The 1.x value axis: bounds from the data and the stacks the bar layer\n * reports, chart-level `high`/`low`, and `referenceValue: 0`.\n */\nfunction valueAxis(\n options: Resolved,\n type: AxisSetup['type'] | undefined\n): AxisFactory {\n const dimension = options.horizontalBars ? 'x' : 'y';\n const inner = !type\n ? autoScaleAxis()\n : isLegacyAxisClass(type)\n ? legacyAxis(type)\n : type;\n return {\n kind: inner.kind,\n create(context) {\n const found = getHighLow(\n context.series,\n options as Options,\n dimension,\n context.extent\n );\n // The chart-level bounds win, but can empty the range again (#1057).\n const highLow = nonEmptyRange({\n high: typeof options.high === 'number' ? options.high : found.high,\n low: typeof options.low === 'number' ? options.low : found.low\n });\n return inner.create({\n ...context,\n options: { ...context.options, highLow, referenceValue: 0 }\n });\n }\n };\n}\n\n/** The default 1.x label axis: one step per label (only the first for stacked distributed bars). */\nfunction labelAxis(options: Resolved): AxisFactory {\n const step = stepAxis();\n return {\n kind: 'step',\n create: context =>\n step.create({\n ...context,\n options: {\n ticks: (options.distributeSeries && options.stackBars\n ? context.labels.slice(0, 1)\n : context.labels) as Label[]\n }\n })\n };\n}\n\nfunction axesConfig(options: Resolved): AxesConfig {\n const horizontal = options.horizontalBars;\n const value = horizontal ? options.axisX : options.axisY;\n const label = horizontal ? options.axisY : options.axisX;\n const valueSetup: AxisSetup = {\n ...value,\n type: valueAxis(options, value.type)\n };\n const labelSetup: AxisSetup = {\n ...label,\n type: label.type ?? labelAxis(options)\n };\n return {\n x: horizontal ? valueSetup : labelSetup,\n y: horizontal ? labelSetup : valueSetup,\n reverseData: options.reverseData,\n normalize: { multi: horizontal ? 'x' : 'y', distributed: true }\n };\n}\n\nconst barSpec: PresetSpec<BarChartData, BarChartPresetOptions> = {\n kind: 'bar',\n defaults: barDefaults,\n config(data, preset): ChartConfig {\n const options = preset as Resolved;\n const axisOptions = options as unknown as AxisPresetOptions;\n // 1.x draws the label axis grid and labels before the value axis.\n const order = options.horizontalBars\n ? (['y', 'x'] as const)\n : (['x', 'y'] as const);\n const layer = bar({\n horizontalBars: options.horizontalBars,\n stackBars: options.stackBars,\n stackMode: options.stackMode,\n seriesBarDistance: options.seriesBarDistance,\n distributeSeries: options.distributeSeries,\n reverseData: options.reverseData,\n classNames: options.classNames\n });\n // As 1.x, `overlap` keeps the axis at the stacked sums, though its\n // bars all start at zero; only `true` fits the axis to the values.\n const extentOf =\n options.stackMode === 'overlap'\n ? bar({\n horizontalBars: options.horizontalBars,\n stackBars: options.stackBars\n })\n : layer;\n const bars = { ...seriesGroup(layer), extent: extentOf.extent };\n return {\n data,\n axes: presetAxes(axesConfig(options)),\n padding: options.chartPadding,\n width: options.width,\n height: options.height,\n viewBox: options.viewBox,\n className:\n options.classNames.chart +\n (options.horizontalBars ? ` ${options.classNames.horizontalBars}` : ''),\n labels: options.labels,\n layers: [\n gridLayer(axisOptions, order),\n bars,\n labelLayer(\n {\n ...axisOptions,\n labelKind: options.horizontalBars ? 'horizontalBar' : 'bar'\n },\n order\n )\n ]\n };\n }\n};\n\n/**\n * Builds the chart config that `barChart()` renders for the data and\n * options, without a container: the bar layer with its axes, grid and labels, horizontal or stacked as the options say. Pass it to `toScene()` to render\n * the preset chart with another renderer. Responsive options and the\n * inline size style of the root svg are left out; both need a container.\n * @experimental\n */\nexport function barChartConfig(\n data: BarChartData,\n options: BarChartPresetOptions = {}\n): ChartConfig {\n return presetConfig(barSpec, data, options);\n}\n\n/** Internal: creates the bar preset; used by `barChart` and `BarChart`. */\nexport function createBarChart(\n target: string | Element,\n data: BarChartData,\n options: BarChartPresetOptions = {},\n responsiveOptions?: PresetResponsiveOptions<BarChartPresetOptions>,\n plugins?: ChartConfig['plugins']\n): BarChartController {\n return createPreset(\n barSpec,\n target,\n data,\n options,\n responsiveOptions,\n plugins ?? options.plugins\n );\n}\n\n/**\n * Creates a bar chart with the 1.x options and output, rendered\n * synchronously. Plugins must be v2 plugins; convert 1.x plugins with\n * `fromLegacyPlugin` from `chartist/compat`.\n * @experimental\n */\nexport function barChart(\n target: string | Element,\n data: BarChartData,\n options: BarChartPresetOptions = {},\n responsiveOptions?: PresetResponsiveOptions<BarChartPresetOptions>\n): PresetHandle<BarChartPresetOptions> {\n return createBarChart(target, data, options, responsiveOptions).handle;\n}\n","import type {\n BarChartData,\n BarChartOptions,\n BarChartEventsTypes\n} from './BarChart.types';\nimport type { ResponsiveOptions } from '../../core';\nimport type { PluginEntry } from '../../chart/types';\nimport {\n createBarChart,\n type BarChartPresetOptions\n} from '../../presets/barChart';\nimport { barDefaults } from '../../presets/barDefaults';\nimport type { PresetController } from '../../presets/preset';\nimport { PresetChart } from '../PresetChart';\n\n/**\n * The 1.x bar chart class: a wrapper over the `barChart` preset with the\n * 1.x API. 1.x events and 1.x plugin functions need the compat plugin\n * (`chartist/compat`).\n * @see {@link barChart} for the v2 functional API.\n *\n * @deprecated Use `barChart()`. Removed in 3.0.\n */\nexport class BarChart extends PresetChart<\n BarChartEventsTypes,\n BarChartData,\n BarChartOptions\n> {\n /**\n * Creates a bar chart. The first render happens on the next tick, so\n * listeners registered right after construction receive it.\n * @param query A selector query string or a DOM element\n * @param data The data with labels and series\n * @param options Options that override the defaults\n * @param responsiveOptions `[mediaQuery, options]` pairs\n */\n constructor(\n query: string | Element | null,\n data: BarChartData,\n options?: BarChartOptions,\n responsiveOptions?: ResponsiveOptions<BarChartOptions>\n ) {\n super(\n query,\n data,\n barDefaults as unknown as BarChartOptions,\n options,\n responsiveOptions\n );\n }\n\n protected createController(\n container: Element,\n data: BarChartData,\n options: BarChartOptions | undefined,\n responsiveOptions: ResponsiveOptions<BarChartOptions> | undefined,\n plugins: PluginEntry[]\n ) {\n return createBarChart(\n container,\n data,\n options as BarChartPresetOptions,\n responsiveOptions as ResponsiveOptions<BarChartPresetOptions>,\n plugins\n ) as unknown as PresetController<BarChartData, BarChartOptions>;\n }\n}\n","/**\n * Pie layer: slices and labels in polar coordinates, drawn like 1.x\n * `PieChart` (geometry, classes, labels and `ct:` attributes).\n */\nimport { serialize } from '../core/data/serialize';\nimport { normalizeData } from '../core/data/normalize';\nimport { alphaNumerate, quantity } from '../core/lang';\nimport { polarToCartesian } from '../core/math';\nimport type { Data, Label } from '../core/types';\nimport type { Layer } from '../pipeline/types';\nimport type { MeasureStyle } from '../render/measure';\nimport { node, withFields, type SceneNode } from '../scene/node';\nimport { SvgPath } from '../svg/SvgPath';\nimport { sum } from '../utils/functional';\nimport { isFalseyButZero, safeHasProperty } from '../utils/utils';\n\n/** Which way pie labels anchor, relative to the center. */\nexport type LabelDirection = 'implode' | 'neutral' | 'explode';\n/** The `text-anchor` of a pie label. */\nexport type AnchorPosition = 'start' | 'middle' | 'end';\n\ninterface Dot {\n x: number;\n y: number;\n}\n\n/**\n * The options of the {@link pie} layer. Without them, it draws a filled\n * pie from the top, with a label halfway out on each slice.\n * @experimental\n */\nexport interface PieLayerOptions {\n /** Where the first slice starts, in degrees clockwise from the top. */\n readonly startAngle?: number;\n /** Fixed total; slices are relative to it (gauges). Defaults to the sum. */\n readonly total?: number;\n /** Draws a donut: rings instead of filled slices. */\n readonly donut?: boolean;\n /**\n * Donut ring width in px, or a share of the radius (`'25%'`). Without\n * it, the stylesheet sets the width (`--ct-donut-width`, 60px by\n * default), and in the browser the ring is laid out for the width the\n * stylesheet gives a slice. Without a DOM (`toScene()`,\n * `renderToString()`), it's laid out for 60 px, so set `donutWidth`\n * there if the page's CSS draws another width.\n */\n readonly donutWidth?: number | string;\n /** Draws a label for each slice; on by default. */\n readonly showLabel?: boolean;\n /**\n * Moves the labels away from the center (positive) or toward it\n * (negative), in px.\n */\n readonly labelOffset?: number;\n /**\n * Where labels go: `inside` (the default: halfway out on a pie, on the\n * middle of a donut's ring), `outside` (at the outer edge) or `center`\n * (in the middle; move them with `labelOffset`).\n */\n readonly labelPosition?: 'inside' | 'outside' | 'center';\n /** Formats a slice's label: its entry in `labels`, or else its value. */\n readonly labelInterpolationFnc?: (\n value: Label,\n index: number\n ) => Label | null | undefined;\n /**\n * Which way labels anchor: `neutral` (the default), `explode` (away from\n * the center, for labels outside the pie) or `implode` (toward it).\n */\n readonly labelDirection?: LabelDirection;\n /** Leaves out the slices and labels of zero values. */\n readonly ignoreEmptyValues?: boolean;\n /**\n * Shifts labels that would overlap another one by this many px, up and\n * left, judging the overlap by the length of the drawn label text.\n */\n readonly preventOverlappingLabelOffset?: number;\n /**\n * Replaces the classes of what the layer draws: `series` (`ct-series`),\n * `slicePie` (`ct-slice-pie`), `sliceDonut` (`ct-slice-donut`) and\n * `label` (`ct-label`).\n */\n readonly classNames?: {\n readonly series?: string;\n readonly slicePie?: string;\n readonly sliceDonut?: string;\n readonly label?: string;\n };\n}\n\n/** The 1.x label anchor: `start`, `middle` or `end` by side and direction. */\nexport function determineAnchorPosition(\n center: Dot,\n label: Dot,\n direction: LabelDirection\n): AnchorPosition {\n const toTheRight = label.x > center.x;\n if (\n (toTheRight && direction === 'explode') ||\n (!toTheRight && direction === 'implode')\n ) {\n return 'start';\n } else if (\n (toTheRight && direction === 'implode') ||\n (!toTheRight && direction === 'explode')\n ) {\n return 'end';\n }\n return 'middle';\n}\n\n/** Moves a label up and left until it no longer overlaps another one (1.x). */\nexport function moveLabel(\n labelPos: Dot,\n existingLabelPos: Dot,\n textOffset: number,\n length: number\n) {\n if (\n labelPos.y > existingLabelPos.y - textOffset &&\n labelPos.y < existingLabelPos.y + textOffset &&\n labelPos.x > existingLabelPos.x - length * textOffset &&\n labelPos.x < existingLabelPos.x + length * textOffset\n ) {\n labelPos.y -= textOffset;\n labelPos.x -= textOffset;\n moveLabel(labelPos, existingLabelPos, textOffset, length);\n }\n}\n\n/**\n * The stroke width of a donut slice in px, as the renderer reads it from\n * the stylesheet. Only px values count: anything else (an unresolved\n * `var()`, a percentage) is left to the default.\n */\nfunction cssWidth(\n measureStyle: MeasureStyle | undefined,\n sliceClass: string\n): number | undefined {\n const width = measureStyle?.('stroke-width', {\n classes: sliceClass.split(' ')\n });\n return width && /^[\\d.]+px$/.test(width) ? parseFloat(width) : undefined;\n}\n\nconst CLASS_NAMES = {\n series: 'ct-series',\n slicePie: 'ct-slice-pie',\n sliceDonut: 'ct-slice-donut',\n label: 'ct-label'\n};\n\n/**\n * Creates a layer that draws a flat series as pie or donut slices with\n * labels, in the markup of the 1.x pie chart (a `g.ct-series` per slice,\n * then a group of `text.ct-label`). It draws in polar coordinates, so the\n * chart needs `coordinates: 'polar'` and no axes. With several series, it\n * draws one slice per series, from each series' first value.\n *\n * @example\n * ```ts\n * import { chart, pie } from 'chartist';\n *\n * chart('#chart', {\n * data: {\n * labels: ['Rent', 'Food', 'Fun'],\n * series: [50, 30, 20]\n * },\n * coordinates: 'polar',\n * layers: [pie({ donut: true, donutWidth: 30 })],\n * className: 'ct-chart-donut'\n * });\n * ```\n * @experimental\n */\nexport function pie(options: PieLayerOptions = {}): Layer {\n const classNames = { ...CLASS_NAMES, ...options.classNames };\n const labelInterpolationFnc =\n options.labelInterpolationFnc ?? ((value: Label) => value);\n return {\n type: 'pie',\n chartType: options.donut ? 'donut' : 'pie',\n coordinates: ['polar'],\n compose({ data, area, measureStyle }) {\n // Values or `{ value, name, className, meta }` objects, as in 1.x.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const raw: any[] = data.flat\n ? [...data.series[0].values]\n : data.series.map(series => ({\n name: series.name,\n className: series.className,\n meta: series.meta,\n value: series.values[0]\n }));\n const normalized = normalizeData({\n labels: data.labels as Label[],\n series: raw\n } as Data);\n const values = normalized.series as number[];\n const labels = normalized.labels;\n const labelPositions: Dot[] = [];\n let startAngle = options.startAngle ?? 0;\n\n let radius = Math.min(area.width / 2, area.height / 2);\n const totalDataSum = options.total || values.reduce(sum, 0);\n // Without `donutWidth`, CSS draws the ring (`--ct-donut-width`), and\n // the layout fits the width the renderer reads from it; 60px, the\n // stylesheet's default, when it can't (see #1474, #1493).\n const donutWidth = quantity(\n options.donutWidth ??\n (options.donut\n ? cssWidth(measureStyle, classNames.sliceDonut)\n : undefined) ??\n 60\n );\n if (donutWidth.unit === '%') {\n donutWidth.value *= radius / 100;\n }\n radius -= options.donut ? donutWidth.value / 2 : 0;\n\n // `radius` is the middle of a donut's ring, and a pie's edge. Unlike\n // 1.x, donut labels follow `labelPosition` too (see #478).\n let labelRadius: number;\n if (options.labelPosition === 'center') {\n labelRadius = 0;\n } else if (options.labelPosition === 'outside') {\n labelRadius = options.donut ? radius + donutWidth.value / 2 : radius;\n } else {\n labelRadius = options.donut ? radius : radius / 2;\n }\n if (options.labelOffset) {\n labelRadius += options.labelOffset;\n }\n\n const center = {\n x: area.x1 + area.width / 2,\n y: area.y2 + area.height / 2\n };\n const hasSingleValInSeries =\n raw.filter(val =>\n safeHasProperty(val, 'value') ? val.value !== 0 : val !== 0\n ).length === 1;\n\n const groups: SceneNode[] = [];\n const labelNodes: SceneNode[] = [];\n\n raw.forEach((series, index) => {\n if (values[index] === 0 && options.ignoreEmptyValues) {\n // 1.x creates the group anyway and leaves it empty.\n groups.push(node('g'));\n return;\n }\n const seriesName = safeHasProperty(series, 'name') && series.name;\n const seriesClassName =\n safeHasProperty(series, 'className') && series.className;\n const seriesMeta = safeHasProperty(series, 'meta')\n ? series.meta\n : undefined;\n\n let endAngle =\n totalDataSum > 0\n ? startAngle + (values[index] / totalDataSum) * 360\n : 0;\n const overlappingStartAngle = Math.max(\n 0,\n startAngle - (index === 0 || hasSingleValInSeries ? 0 : 0.2)\n );\n // A slice that fills the circle itself (one value, or one at least\n // the total), not one that only reaches round with the overlap.\n const fullCircle = endAngle - startAngle >= 359.99;\n if (endAngle - overlappingStartAngle >= 359.99) {\n endAngle = overlappingStartAngle + 359.99;\n }\n const start = polarToCartesian(\n center.x,\n center.y,\n radius,\n overlappingStartAngle\n );\n const path = new SvgPath(!options.donut);\n if (fullCircle) {\n // Two half circles through opposite points: their midpoint is the\n // centre, so rounding the coordinates can't move the ring, as it\n // does with one arc between points 0.01° apart (#1302).\n const opposite = polarToCartesian(\n center.x,\n center.y,\n radius,\n overlappingStartAngle + 180\n );\n path\n .move(start.x, start.y)\n .arc(radius, radius, 0, 0, 0, opposite.x, opposite.y);\n } else {\n const end = polarToCartesian(center.x, center.y, radius, endAngle);\n path.move(end.x, end.y);\n }\n path.arc(\n radius,\n radius,\n 0,\n Number(!fullCircle && endAngle - startAngle > 180),\n 0,\n start.x,\n start.y\n );\n if (!options.donut) {\n path.line(center.x, center.y);\n }\n\n const slice = node(\n 'path',\n {\n d: path.stringify(),\n 'ct:value': values[index],\n 'ct:meta': serialize(seriesMeta) as string | undefined,\n style:\n options.donut && options.donutWidth !== undefined\n ? `stroke-width: ${donutWidth.value}px`\n : undefined\n },\n options.donut ? classNames.sliceDonut : classNames.slicePie,\n {\n role: 'slice',\n ctx: {\n value: values[index],\n totalDataSum,\n index,\n seriesIndex: index,\n valueIndex: 0,\n meta: seriesMeta,\n series,\n path: path.clone(),\n center,\n radius,\n startAngle,\n endAngle\n }\n }\n );\n groups.push(\n withFields(\n node(\n 'g',\n { 'ct:series-name': seriesName || undefined },\n `${classNames.series} ${\n seriesClassName ||\n `${classNames.series}-${alphaNumerate(index)}`\n }`,\n {\n role: 'series',\n ctx: { seriesIndex: index, series, meta: seriesMeta }\n }\n ),\n { children: [slice] }\n )\n );\n\n if (options.showLabel ?? true) {\n const labelPosition =\n raw.length === 1\n ? { x: center.x, y: center.y }\n : polarToCartesian(\n center.x,\n center.y,\n labelRadius,\n startAngle + (endAngle - startAngle) / 2\n );\n const rawValue =\n labels && !isFalseyButZero(labels[index])\n ? labels[index]\n : values[index];\n const interpolated = labelInterpolationFnc(rawValue, index);\n if (interpolated || interpolated === 0) {\n const text = String(interpolated);\n if (options.preventOverlappingLabelOffset) {\n // The drawn text, not the label entry, which may be missing\n // or formatted differently (see #1485).\n const length = text.length;\n labelPositions.forEach(item =>\n moveLabel(\n labelPosition,\n item,\n options.preventOverlappingLabelOffset!,\n length\n )\n );\n labelPositions.push(labelPosition);\n }\n labelNodes.push(\n node(\n 'text',\n {\n dx: labelPosition.x,\n dy: labelPosition.y,\n 'text-anchor': determineAnchorPosition(\n center,\n labelPosition,\n options.labelDirection ?? 'neutral'\n )\n },\n classNames.label,\n {\n role: 'label',\n ctx: {\n kind: 'pie',\n index,\n seriesIndex: index,\n valueIndex: 0,\n text,\n series,\n meta: seriesMeta,\n x: labelPosition.x,\n y: labelPosition.y\n }\n }\n ).text(text)\n );\n }\n }\n startAngle = endAngle;\n });\n\n return (options.showLabel ?? true)\n ? [...groups, withFields(node('g'), { children: labelNodes })]\n : groups;\n }\n };\n}\n","import { noop } from '../utils/functional';\n\n/** The 1.x `PieChart` default options. */\nexport const pieDefaults = {\n width: undefined,\n height: undefined,\n chartPadding: { top: 5, right: 5, bottom: 5, left: 5 },\n classNames: {\n chartPie: 'ct-chart-pie',\n chartDonut: 'ct-chart-donut',\n series: 'ct-series',\n slicePie: 'ct-slice-pie',\n sliceDonut: 'ct-slice-donut',\n label: 'ct-label'\n },\n startAngle: 0,\n total: undefined,\n donut: false,\n showLabel: true,\n labelOffset: 0,\n labelPosition: 'inside' as const,\n labelInterpolationFnc: noop,\n labelDirection: 'neutral' as const,\n ignoreEmptyValues: false,\n preventOverlappingLabelOffset: 0\n};\n","/**\n * `pieChart`: the 1.x pie chart as a preset over `chart()`, in polar\n * coordinates. Takes the 1.x arguments and options and renders the 1.x\n * structure.\n */\nimport type {\n PieChartData,\n PieChartOptions\n} from '../charts/PieChart/PieChart.types';\nimport type { ChartConfig, PluginEntry } from '../chart/types';\nimport type { PhaseListeners } from '../pipeline/types';\nimport { pie } from '../layers/pie';\nimport { pieDefaults } from './pieDefaults';\nimport {\n createPreset,\n presetConfig,\n type PresetController,\n type PresetHandle,\n type PresetSpec,\n type PresetState,\n type PresetResponsiveOptions\n} from './preset';\n\n/**\n * Options of `pieChart`: the 1.x `PieChart` options, with v2 plugins and\n * phase listeners.\n * @experimental\n */\nexport type PieChartPresetOptions = Omit<PieChartOptions, 'plugins'> & {\n /** v2 plugins; convert 1.x plugins with `fromLegacyPlugin`. */\n readonly plugins?: readonly PluginEntry[];\n /**\n * Phase listeners by phase name (or `'*'` for all phases), as `on` in\n * the config of `chart()`. They're registered before the first render,\n * so they see it too.\n */\n readonly on?: PhaseListeners;\n};\n\ntype Resolved = typeof pieDefaults & PieChartOptions;\n\n/** What the pie preset passes to plugins as `ResolvedConfig.preset`. */\nexport type PiePresetState = PresetState<\n PieChartData,\n PieChartPresetOptions,\n 'pie'\n>;\n\nexport type PieChartController = PresetController<\n PieChartData,\n PieChartPresetOptions\n>;\n\nconst pieSpec: PresetSpec<PieChartData, PieChartPresetOptions> = {\n kind: 'pie',\n defaults: pieDefaults,\n config(data, preset): ChartConfig {\n const options = preset as Resolved;\n return {\n data,\n coordinates: 'polar',\n padding: options.chartPadding,\n width: options.width,\n height: options.height,\n viewBox: options.viewBox,\n className: options.donut\n ? options.classNames.chartDonut\n : options.classNames.chartPie,\n layers: [\n pie({\n startAngle: options.startAngle,\n total: options.total,\n donut: options.donut,\n donutWidth: options.donutWidth,\n showLabel: options.showLabel,\n labelOffset: options.labelOffset,\n labelPosition: options.labelPosition,\n labelInterpolationFnc: options.labelInterpolationFnc,\n labelDirection: options.labelDirection,\n ignoreEmptyValues: options.ignoreEmptyValues,\n preventOverlappingLabelOffset: options.preventOverlappingLabelOffset,\n classNames: options.classNames\n })\n ]\n };\n }\n};\n\n/**\n * Builds the chart config that `pieChart()` renders for the data and\n * options, without a container: the pie layer with its labels. Pass it to `toScene()` to render\n * the preset chart with another renderer. Responsive options and the\n * inline size style of the root svg are left out; both need a container.\n * @experimental\n */\nexport function pieChartConfig(\n data: PieChartData,\n options: PieChartPresetOptions = {}\n): ChartConfig {\n return presetConfig(pieSpec, data, options);\n}\n\n/** Internal: creates the pie preset; used by `pieChart` and `PieChart`. */\nexport function createPieChart(\n target: string | Element,\n data: PieChartData,\n options: PieChartPresetOptions = {},\n responsiveOptions?: PresetResponsiveOptions<PieChartPresetOptions>,\n plugins?: ChartConfig['plugins']\n): PieChartController {\n return createPreset(\n pieSpec,\n target,\n data,\n options,\n responsiveOptions,\n plugins ?? options.plugins\n );\n}\n\n/**\n * Creates a pie or donut chart with the 1.x options and output, rendered\n * synchronously. Plugins must be v2 plugins; convert 1.x plugins with\n * `fromLegacyPlugin` from `chartist/compat`.\n * @experimental\n */\nexport function pieChart(\n target: string | Element,\n data: PieChartData,\n options: PieChartPresetOptions = {},\n responsiveOptions?: PresetResponsiveOptions<PieChartPresetOptions>\n): PresetHandle<PieChartPresetOptions> {\n return createPieChart(target, data, options, responsiveOptions).handle;\n}\n","import type {\n Dot,\n PieChartData,\n PieChartOptions,\n PieChartEventsTypes\n} from './PieChart.types';\nimport type { ResponsiveOptions } from '../../core';\nimport type { PluginEntry } from '../../chart/types';\nimport { moveLabel } from '../../layers/pie';\nimport {\n createPieChart,\n type PieChartPresetOptions\n} from '../../presets/pieChart';\nimport { pieDefaults } from '../../presets/pieDefaults';\nimport type { PresetController } from '../../presets/preset';\nimport { PresetChart } from '../PresetChart';\n\nexport { determineAnchorPosition } from '../../layers/pie';\n\n/**\n * The 1.x pie chart class: a wrapper over the `pieChart` preset with the\n * 1.x API. 1.x events and 1.x plugin functions need the compat plugin\n * (`chartist/compat`).\n * @see {@link pieChart} for the v2 functional API.\n *\n * @deprecated Use `pieChart()`. Removed in 3.0.\n */\nexport class PieChart extends PresetChart<\n PieChartEventsTypes,\n PieChartData,\n PieChartOptions\n> {\n /**\n * Creates a pie chart. The first render happens on the next tick, so\n * listeners registered right after construction receive it.\n * @param query A selector query string or a DOM element\n * @param data The data with labels and series\n * @param options Options that override the defaults\n * @param responsiveOptions `[mediaQuery, options]` pairs\n */\n constructor(\n query: string | Element | null,\n data: PieChartData,\n options?: PieChartOptions,\n responsiveOptions?: ResponsiveOptions<PieChartOptions>\n ) {\n super(\n query,\n data,\n pieDefaults as unknown as PieChartOptions,\n options,\n responsiveOptions\n );\n }\n\n /**\n * Checks if a label overlaps another one and moves it up and left until\n * it doesn't (1.x).\n */\n moveLabel(\n labelPos: Dot,\n existingLabelPos: Dot,\n textOffset: number,\n length: number\n ) {\n moveLabel(labelPos, existingLabelPos, textOffset, length);\n }\n\n protected createController(\n container: Element,\n data: PieChartData,\n options: PieChartOptions | undefined,\n responsiveOptions: ResponsiveOptions<PieChartOptions> | undefined,\n plugins: PluginEntry[]\n ) {\n return createPieChart(\n container,\n data,\n options as PieChartPresetOptions,\n responsiveOptions as ResponsiveOptions<PieChartPresetOptions>,\n plugins\n ) as unknown as PresetController<PieChartData, PieChartOptions>;\n }\n}\n","import type {\n ChartRect,\n AxisOptions,\n Bounds,\n NormalizedSeries,\n NormalizedSeriesPrimitiveValue\n} from '../core';\nimport { getBounds, getHighLow, getMultiValue } from '../core';\nimport { AxisUnits, Axis } from './Axis';\n\n/**\n * The 1.x axis with a scale fitted to the values, in round steps at least `scaleMinSpace` px apart.\n *\n * @deprecated Use `autoScaleAxis()`. Removed in 3.0.\n */\nexport class AutoScaleAxis extends Axis {\n private readonly bounds: Bounds;\n public override readonly range: {\n min: number;\n max: number;\n };\n\n constructor(\n axisUnit: AxisUnits,\n data: NormalizedSeries[],\n chartRect: ChartRect,\n options: AxisOptions\n ) {\n // Usually we calculate highLow based on the data but this can be overriden by a highLow object in the options\n const highLow = options.highLow || getHighLow(data, options, axisUnit.pos);\n const bounds = getBounds(\n chartRect[axisUnit.rectEnd] - chartRect[axisUnit.rectStart],\n highLow,\n options.scaleMinSpace || 20,\n options.onlyInteger\n );\n const range = {\n min: bounds.min,\n max: bounds.max\n };\n\n super(axisUnit, chartRect, bounds.values);\n\n this.bounds = bounds;\n this.range = range;\n }\n\n projectValue(value: NormalizedSeriesPrimitiveValue) {\n const finalValue = Number(getMultiValue(value, this.units.pos));\n\n return (\n (this.axisLength * (finalValue - this.bounds.min)) / this.bounds.range\n );\n }\n}\n","import type {\n ChartRect,\n AxisOptions,\n NormalizedSeries,\n NormalizedSeriesPrimitiveValue\n} from '../core';\nimport { getMultiValue, getHighLow } from '../core/data';\nimport { times } from '../utils';\nimport { AxisUnits, Axis } from './Axis';\n\n/**\n * The 1.x axis with fixed ticks: the `ticks` option, or `divisor` equal steps from low to high, with a tick at both ends.\n *\n * @deprecated Use `fixedScaleAxis()`. Removed in 3.0.\n */\nexport class FixedScaleAxis extends Axis {\n public override readonly range: {\n min: number;\n max: number;\n };\n\n constructor(\n axisUnit: AxisUnits,\n data: NormalizedSeries[],\n chartRect: ChartRect,\n options: AxisOptions\n ) {\n const highLow = options.highLow || getHighLow(data, options, axisUnit.pos);\n const divisor = options.divisor || 1;\n // `divisor` parts have `divisor + 1` ends, `high` included (#1022).\n const ticks = (\n options.ticks ||\n times(\n divisor + 1,\n index => highLow.low + ((highLow.high - highLow.low) / divisor) * index\n )\n ).sort((a, b) => Number(a) - Number(b));\n const range = {\n min: highLow.low,\n max: highLow.high\n };\n\n super(axisUnit, chartRect, ticks);\n\n this.range = range;\n }\n\n projectValue(value: NormalizedSeriesPrimitiveValue) {\n const finalValue = Number(getMultiValue(value, this.units.pos));\n\n return (\n (this.axisLength * (finalValue - this.range.min)) /\n (this.range.max - this.range.min)\n );\n }\n}\n","import type { ChartRect, AxisOptions } from '../core';\nimport { AxisUnits, Axis } from './Axis';\n\n/**\n * The 1.x axis with one step per tick, such as the labels of a line chart's X axis.\n *\n * @deprecated Use `stepAxis()`. Removed in 3.0.\n */\nexport class StepAxis extends Axis {\n private readonly stepLength: number;\n public readonly stretch: boolean;\n\n constructor(\n axisUnit: AxisUnits,\n _data: unknown,\n chartRect: ChartRect,\n options: AxisOptions\n ) {\n const ticks = options.ticks || [];\n\n super(axisUnit, chartRect, ticks);\n\n const calc = Math.max(1, ticks.length - (options.stretch ? 1 : 0));\n this.stepLength = this.axisLength / calc;\n this.stretch = Boolean(options.stretch);\n }\n\n projectValue(_value: unknown, index: number) {\n return this.stepLength * index;\n }\n}\n","import type { SegmentData } from '../core/types';\nimport { getMultiValue } from '../core';\nimport { SvgPath } from '../svg';\n\n/** The options of {@link Interpolation.simple}. */\nexport interface SimpleInteractionOptions {\n /**\n * How long the curve's handles are: the distance between two points\n * divided by this, so larger values give tighter curves. `2` by default,\n * at least `1`.\n */\n divisor?: number;\n /**\n * Joins the line across holes (`null` or `undefined` values) instead of\n * breaking it. Off by default.\n */\n fillHoles?: boolean;\n}\n\n/**\n * Smooths a line with curves whose handles are horizontal: it goes through\n * every point and never swings above or below them, but flows less than\n * {@link Interpolation.cardinal}. `divisor` sets how round it is.\n *\n * @example\n * ```ts\n * import { lineChart, Interpolation } from 'chartist';\n *\n * lineChart(\n * '#chart',\n * { labels: [1, 2, 3, 4, 5], series: [[1, 2, 8, 1, 7]] },\n * { lineSmooth: Interpolation.simple({ divisor: 3 }) }\n * );\n * ```\n *\n * @param options The divisor, and whether to join the line across holes.\n * @returns The interpolation, for the `lineSmooth` option.\n */\nexport function simple(options?: SimpleInteractionOptions) {\n const finalOptions = {\n divisor: 2,\n fillHoles: false,\n ...options\n };\n\n const d = 1 / Math.max(1, finalOptions.divisor);\n\n return function simpleInterpolation(\n pathCoordinates: number[],\n valueData: SegmentData[]\n ) {\n const path = new SvgPath();\n let prevX = 0;\n let prevY = 0;\n let prevData;\n\n for (let i = 0; i < pathCoordinates.length; i += 2) {\n const currX = pathCoordinates[i];\n const currY = pathCoordinates[i + 1];\n const length = (currX - prevX) * d;\n const currData = valueData[i / 2];\n\n if (getMultiValue(currData.value) !== undefined) {\n if (prevData === undefined) {\n path.move(currX, currY, false, currData);\n } else {\n path.curve(\n prevX + length,\n prevY,\n currX - length,\n currY,\n currX,\n currY,\n false,\n currData\n );\n }\n\n prevX = currX;\n prevY = currY;\n prevData = currData;\n } else if (!finalOptions.fillHoles) {\n prevX = prevY = 0;\n prevData = undefined;\n }\n }\n\n return path;\n };\n}\n","import type { SegmentData } from '../core';\nimport { getMultiValue } from '../core';\nimport { SvgPath } from '../svg';\n\n/** The options of {@link Interpolation.step}. */\nexport interface StepInterpolationOptions {\n /**\n * Holds each value until the next point, so the step happens where the\n * value changes (the default). With `false`, the line steps to the next\n * value right away.\n */\n postpone?: boolean;\n /**\n * Joins the line across holes (`null` or `undefined` values) instead of\n * breaking it. Off by default.\n */\n fillHoles?: boolean;\n}\n\n/**\n * Draws a line in steps: horizontal and vertical segments instead of\n * diagonals or curves. Each step adds a corner to the path, and with\n * `showPoint` a point is drawn there too.\n *\n * @example\n * ```ts\n * import { lineChart, Interpolation } from 'chartist';\n *\n * lineChart(\n * '#chart',\n * { labels: [1, 2, 3, 4, 5], series: [[1, 2, 8, 1, 7]] },\n * { lineSmooth: Interpolation.step({ postpone: false }) }\n * );\n * ```\n *\n * @param options When to step, and whether to join the line across holes.\n * @returns The interpolation, for the `lineSmooth` option.\n */\nexport function step(options?: StepInterpolationOptions) {\n const finalOptions = {\n postpone: true,\n fillHoles: false,\n ...options\n };\n\n return function stepInterpolation(\n pathCoordinates: number[],\n valueData: SegmentData[]\n ) {\n const path = new SvgPath();\n\n let prevX = 0;\n let prevY = 0;\n let prevData;\n\n for (let i = 0; i < pathCoordinates.length; i += 2) {\n const currX = pathCoordinates[i];\n const currY = pathCoordinates[i + 1];\n const currData = valueData[i / 2];\n\n // If the current point is also not a hole we can draw the step lines\n if (getMultiValue(currData.value) !== undefined) {\n if (prevData === undefined) {\n path.move(currX, currY, false, currData);\n } else {\n if (finalOptions.postpone) {\n // If postponed we should draw the step line with the value of the previous value\n path.line(currX, prevY, false, prevData);\n } else {\n // If not postponed we should draw the step line with the value of the current value\n path.line(prevX, currY, false, currData);\n }\n // Line to the actual point (this should only be a Y-Axis movement\n path.line(currX, currY, false, currData);\n }\n\n prevX = currX;\n prevY = currY;\n prevData = currData;\n } else if (!finalOptions.fillHoles) {\n prevX = prevY = 0;\n prevData = undefined;\n }\n }\n\n return path;\n };\n}\n","import type { SegmentData } from '../core';\nimport { splitIntoSegments } from '../core';\nimport { SvgPath } from '../svg';\nimport { none } from './none';\n\n/** The options of {@link Interpolation.cardinal}. */\nexport interface CardinalInterpolationOptions {\n /**\n * How round the curve is, from `0` (straight segments) to `1` (the\n * default, a Catmull-Rom spline).\n */\n tension?: number;\n /**\n * Joins the line across holes (`null` or `undefined` values) instead of\n * breaking it. Off by default.\n */\n fillHoles?: boolean;\n}\n\n/**\n * Smooths a line with a cardinal (Catmull-Rom) spline: round curves that\n * go through every point. When values change quickly, the curve can swing\n * past them; {@link Interpolation.monotoneCubic} (the default for\n * `lineSmooth: true`) doesn't.\n *\n * With two points or fewer, the line is straight, as with\n * {@link Interpolation.none}.\n *\n * @example\n * ```ts\n * import { lineChart, Interpolation } from 'chartist';\n *\n * lineChart(\n * '#chart',\n * { labels: [1, 2, 3, 4, 5], series: [[1, 2, 8, 1, 7]] },\n * { lineSmooth: Interpolation.cardinal({ tension: 0.2 }) }\n * );\n * ```\n *\n * @param options The tension, and whether to join the line across holes.\n * @returns The interpolation, for the `lineSmooth` option.\n */\nexport function cardinal(options?: CardinalInterpolationOptions) {\n const finalOptions = {\n tension: 1,\n fillHoles: false,\n ...options\n };\n\n const t = Math.min(1, Math.max(0, finalOptions.tension));\n const c = 1 - t;\n\n return function cardinalInterpolation(\n pathCoordinates: number[],\n valueData: SegmentData[]\n ): SvgPath {\n // First we try to split the coordinates into segments\n // This is necessary to treat \"holes\" in line charts\n const segments = splitIntoSegments(pathCoordinates, valueData, {\n fillHoles: finalOptions.fillHoles\n });\n\n if (!segments.length) {\n // If there were no segments return 'none' interpolation\n return none()([], []);\n } else if (segments.length > 1) {\n // If the split resulted in more that one segment we need to interpolate each segment individually and join them\n // afterwards together into a single path.\n // For each segment we will recurse the cardinal function\n // Join the segment path data into a single path and return\n return SvgPath.join(\n segments.map(segment =>\n cardinalInterpolation(segment.pathCoordinates, segment.valueData)\n )\n );\n } else {\n // If there was only one segment we can proceed regularly by using pathCoordinates and valueData from the first\n // segment\n pathCoordinates = segments[0].pathCoordinates;\n valueData = segments[0].valueData;\n\n // If less than two points we need to fallback to no smoothing\n if (pathCoordinates.length <= 4) {\n return none()(pathCoordinates, valueData);\n }\n\n const path = new SvgPath().move(\n pathCoordinates[0],\n pathCoordinates[1],\n false,\n valueData[0]\n );\n const z = false;\n\n for (\n let i = 0, iLen = pathCoordinates.length;\n iLen - 2 * Number(!z) > i;\n i += 2\n ) {\n const p = [\n { x: +pathCoordinates[i - 2], y: +pathCoordinates[i - 1] },\n { x: +pathCoordinates[i], y: +pathCoordinates[i + 1] },\n { x: +pathCoordinates[i + 2], y: +pathCoordinates[i + 3] },\n { x: +pathCoordinates[i + 4], y: +pathCoordinates[i + 5] }\n ];\n\n if (z) {\n if (!i) {\n p[0] = {\n x: +pathCoordinates[iLen - 2],\n y: +pathCoordinates[iLen - 1]\n };\n } else if (iLen - 4 === i) {\n p[3] = { x: +pathCoordinates[0], y: +pathCoordinates[1] };\n } else if (iLen - 2 === i) {\n p[2] = { x: +pathCoordinates[0], y: +pathCoordinates[1] };\n p[3] = { x: +pathCoordinates[2], y: +pathCoordinates[3] };\n }\n } else {\n if (iLen - 4 === i) {\n p[3] = p[2];\n } else if (!i) {\n p[0] = { x: +pathCoordinates[i], y: +pathCoordinates[i + 1] };\n }\n }\n\n path.curve(\n (t * (-p[0].x + 6 * p[1].x + p[2].x)) / 6 + c * p[2].x,\n (t * (-p[0].y + 6 * p[1].y + p[2].y)) / 6 + c * p[2].y,\n (t * (p[1].x + 6 * p[2].x - p[3].x)) / 6 + c * p[2].x,\n (t * (p[1].y + 6 * p[2].y - p[3].y)) / 6 + c * p[2].y,\n p[2].x,\n p[2].y,\n false,\n valueData[(i + 2) / 2]\n );\n }\n\n return path;\n }\n };\n}\n","/**\n * The line interpolations: functions that turn a series' points into the\n * {@link SvgPath} of its line, for the `lineSmooth` option of line charts.\n * Each one is a factory: call it with its options, such as\n * `Interpolation.cardinal({ tension: 0.2 })`, and pass the result. Write\n * your own as a {@link LineInterpolation}.\n *\n * @module\n */\nexport * from './none';\nexport * from './simple';\nexport * from './step';\nexport * from './cardinal';\nexport * from './monotoneCubic';\n","/**\n * The default series colors, `a` to `o`, as hex: the colors of\n * `chartist/styles.css` (`$ct-series-colors` in the Sass settings).\n * Renderers without CSS use them to color series the way the styles do.\n * The styles color the first fifteen series only.\n *\n * @example\n * ```ts\n * import { seriesColors } from 'chartist';\n *\n * // The color of series `c`, the third.\n * export const third = seriesColors[2];\n * ```\n * @experimental\n */\nexport const seriesColors: readonly string[] = [\n '#d70206',\n '#f05b4f',\n '#f4c63d',\n '#d17905',\n '#453d3f',\n '#59922b',\n '#0544d3',\n '#6b0392',\n '#e6805e',\n '#dda458',\n '#eacf7d',\n '#86797d',\n '#b2c326',\n '#6188e2',\n '#a748ca'\n];\n","import { escapingMap, namespaces } from '../core/constants';\nimport type { SceneNode } from '../scene/node';\n\nconst escape = (value: string | number) =>\n String(value).replace(/[&<>\"']/g, char => escapingMap[char]);\n\ntype Position = 'root' | 'html-root' | 'other';\n\nfunction attributes(current: SceneNode, position: Position) {\n const parts: string[] = [];\n if (position === 'root') {\n parts.push(`xmlns=\"${namespaces.svg}\"`, `xmlns:ct=\"${namespaces.ct}\"`);\n } else if (position === 'html-root') {\n // HTML inside a foreignObject; any other xmlns value is replaced.\n parts.push(`xmlns=\"${namespaces.xhtml}\"`);\n }\n if (current.classes.length) {\n parts.push(`class=\"${escape(current.classes.join(' '))}\"`);\n }\n for (const [name, value] of Object.entries(current.attrs)) {\n if (name !== 'xmlns') {\n parts.push(`${name}=\"${escape(value)}\"`);\n }\n }\n return parts.length ? ` ${parts.join(' ')}` : '';\n}\n\nfunction serialize(current: SceneNode, position: Position): string {\n const open = `<${current.name}${attributes(current, position)}`;\n const childPosition: Position =\n current.name === 'foreignObject' ? 'html-root' : 'other';\n const content =\n (current.content === undefined ? '' : escape(current.content)) +\n current.children.map(child => serialize(child, childPosition)).join('');\n return content ? `${open}>${content}</${current.name}>` : `${open}/>`;\n}\n\n/**\n * Serializes a scene to standalone SVG markup. Needs no DOM, so it works in\n * Node.js and in server bundles.\n *\n * The root gets the SVG and `ct:` namespaces, and attribute values and\n * text are escaped. The markup has the chart's classes but no styles: load\n * `chartist/styles.css` where it's shown, or add a `style` element to the\n * scene.\n *\n * @param scene A scene, usually from `toScene()`\n * @returns The SVG markup, e.g. `<svg xmlns=\"…\" …>…</svg>`\n * @example\n * ```ts\n * import {\n * autoScaleAxis,\n * axisGrid,\n * axisLabels,\n * cartesianAxes,\n * line,\n * renderToString,\n * stepAxis,\n * toScene\n * } from 'chartist';\n *\n * export function weekChart(values: number[]): string {\n * const labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];\n * const scene = toScene(\n * {\n * data: { labels, series: [values] },\n * axes: cartesianAxes([\n * { id: 'x', side: 'bottom', type: stepAxis(), ticks: labels },\n * { id: 'y', side: 'left', type: autoScaleAxis() }\n * ]),\n * layers: [axisGrid(), line(), axisLabels()],\n * className: 'ct-chart-line'\n * },\n * { width: 600, height: 300 }\n * );\n * return renderToString(scene);\n * }\n * ```\n * @experimental\n */\nexport function renderToString(scene: SceneNode): string {\n return serialize(scene, 'root');\n}\n","import { createPhaseEmitter } from '../pipeline/emitter';\nimport { runPipeline } from '../pipeline/phases';\nimport {\n estimateText,\n type LabelMode,\n type MeasureText\n} from '../render/measure';\nimport type { SceneNode } from '../scene/node';\nimport { withChartTypeClass } from './className';\nimport {\n eventMethods,\n installPlugins,\n listenerScope,\n registerListeners\n} from './plugins';\nimport type { ChartConfig, ChartHandle } from './types';\n\n/**\n * The size {@link toScene} lays a chart out at, since there's no container\n * to measure, and how to measure text there.\n */\nexport interface SceneSize {\n /**\n * The width to lay out at, in px. The root svg gets it as its `width`,\n * unless the config sets one.\n */\n readonly width: number;\n /**\n * The height to lay out at, in px. The root svg gets it as its `height`,\n * unless the config sets one.\n */\n readonly height: number;\n /** Text measurement for layout; an estimate by default. */\n readonly measureText?: MeasureText;\n /**\n * Label mode when the config sets none: `svg` by default, since string\n * output often goes to tools without HTML support.\n */\n readonly labels?: LabelMode;\n}\n\nfunction unavailable(method: string): never {\n throw new Error(`Chartist: ${method}() is not available in toScene()`);\n}\n\n/**\n * Builds a chart's scene without rendering it: no DOM, timers or globals.\n * Runs the phases `resolve` to `scene` with the config's plugins and\n * listeners.\n *\n * It takes the same config as `chart()`, and the SVG gets the same chart\n * type class without `className`. Listeners of `render` and `mount`\n * never run, responsive overrides and the `renderer` are ignored, and\n * calling `update()`, `detach()` or `destroy()` on the handle a plugin gets\n * throws. Turn the scene into markup with {@link renderToString}.\n *\n * @param config The chart: data, axes, layers, plugins and listeners\n * @param size The size to lay out at, in px, and how to measure text\n * @returns The scene, its root the `svg`\n * @example\n * ```ts\n * import {\n * autoScaleAxis,\n * axisGrid,\n * axisLabels,\n * cartesianAxes,\n * line,\n * node,\n * renderToString,\n * stepAxis,\n * toScene\n * } from 'chartist';\n *\n * const labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];\n * const scene = toScene(\n * {\n * data: { labels, series: [[12, 9, 7, 8, 5]] },\n * axes: cartesianAxes([\n * { id: 'x', side: 'bottom', type: stepAxis(), ticks: labels },\n * { id: 'y', side: 'left', type: autoScaleAxis() }\n * ]),\n * layers: [axisGrid(), line(), axisLabels()],\n * viewBox: { width: 600, height: 300 },\n * on: {\n * // Styles inside the SVG, for tools that read it on its own.\n * scene: ({ scene }) => ({\n * scene: scene.append(\n * node('style').text('.ct-line { fill: none; stroke: #d70206; }'),\n * true\n * )\n * })\n * }\n * },\n * { width: 600, height: 300 }\n * );\n *\n * export const markup = renderToString(scene);\n * ```\n * @experimental\n */\nexport function toScene(config: ChartConfig, size: SceneSize): SceneNode {\n const emitter = createPhaseEmitter();\n const provided = new Set<string>();\n const scope = listenerScope();\n const handle: ChartHandle = {\n update: () => unavailable('update'),\n detach: () => unavailable('detach'),\n destroy: () => unavailable('destroy'),\n ...eventMethods(emitter, () => handle, provided, scope)\n };\n installPlugins(handle, config.plugins, provided, scope);\n registerListeners(handle, config.on);\n return runPipeline(emitter, withChartTypeClass(config), {\n width: size.width,\n height: size.height,\n measureText: size.measureText ?? estimateText,\n labels: size.labels ?? 'svg'\n }).scene;\n}\n","/**\n * Grid and label layers for composed charts: `axisGrid()` and\n * `axisLabels()` draw the axes of `cartesianAxes()` with the 1.x geometry\n * and classes, so 1.x CSS applies.\n */\nimport type { Layer, LayerContext } from '../pipeline/types';\nimport { node, withFields, type SceneNode } from '../scene/node';\nimport type { LabelMode } from '../render/measure';\nimport type { PlacedScaleAxis } from '../scales/axis';\nimport {\n axisNodes,\n gridBackground,\n type AxisClassNames,\n type DrawnAxisOptions,\n type LabelPlacer\n} from '../scales/grid';\nimport {\n svgLabels,\n type LabelAlign,\n type SvgLabelBuilder\n} from '../scales/svgLabels';\n\n/**\n * The classes {@link axisGrid} and {@link axisLabels} give what they draw.\n * The defaults are the 1.x classes, so 1.x CSS applies.\n */\nexport interface AxisLayerClassNames extends AxisClassNames {\n /** The group of all grid lines (`ct-grids`). */\n readonly gridGroup: string;\n /** The group of all labels (`ct-labels`). */\n readonly labelGroup: string;\n /** The rect behind the grid, with `background: true` (`ct-grid-background`). */\n readonly gridBackground: string;\n}\n\nconst CLASS_NAMES: AxisLayerClassNames = {\n grid: 'ct-grid',\n label: 'ct-label',\n horizontal: 'ct-horizontal',\n vertical: 'ct-vertical',\n start: 'ct-start',\n end: 'ct-end',\n gridGroup: 'ct-grids',\n labelGroup: 'ct-labels',\n gridBackground: 'ct-grid-background'\n};\n\n/**\n * The options of {@link axisGrid} and {@link axisLabels}.\n * @experimental\n */\nexport interface AxisLayerOptions {\n /**\n * Axis ids to draw; default: all axes, in declaration order. An unknown\n * id throws.\n */\n readonly axes?: readonly string[];\n /** Replaces some of the classes; the others keep their 1.x names. */\n readonly classNames?: Partial<AxisLayerClassNames>;\n}\n\n/**\n * The options of {@link axisLabels}: those of every axis layer, plus how\n * the labels are drawn.\n * @experimental\n */\nexport interface AxisLabelsOptions extends AxisLayerOptions {\n /** HTML (`foreignObject`) or SVG `text`; default: the chart's mode. */\n readonly labels?: LabelMode;\n /**\n * Aligns SVG text labels in their box, on every axis of the layer;\n * default: as the 1.x CSS aligns HTML labels. HTML labels ignore it\n * (align them with CSS).\n */\n readonly align?: Partial<LabelAlign>;\n}\n\n/** The 1.x axis defaults, for options an axis definition leaves out. */\nfunction drawnOptions(axis: PlacedScaleAxis): DrawnAxisOptions {\n const options = axis.options;\n return {\n ...options,\n offset: options.offset ?? 0,\n position: axis.side === 'top' || axis.side === 'left' ? 'start' : 'end',\n labelOffset: options.labelOffset ?? { x: 0, y: 0 },\n showLabel: options.showLabel ?? true,\n showGrid: options.showGrid ?? true,\n labelInterpolationFnc:\n options.labelInterpolationFnc ?? ((value: unknown) => value as never)\n } as DrawnAxisOptions;\n}\n\nfunction selectedAxes(context: LayerContext, ids?: readonly string[]) {\n const all = context.axes.all ?? [];\n if (!ids) {\n return all;\n }\n return ids.map(id => {\n const axis = all.find(candidate => candidate.id === id);\n if (!axis) {\n throw new Error(`Chartist: unknown axis \"${id}\" in an axis layer`);\n }\n return axis;\n });\n}\n\n/**\n * Labels per side, stacked outward by the axis inset. With an inset of 0\n * these are the 1.x formulas of the presets.\n */\nexport const placeOnSide =\n (side: PlacedScaleAxis['side'], inset: number): LabelPlacer =>\n (axis, relative, labelLength, options, area) =>\n axis.dimension === 'x'\n ? {\n position: area.x1 + relative,\n labelOffset: {\n x: options.labelOffset.x,\n y:\n side === 'top'\n ? area.y2 - inset - options.offset + options.labelOffset.y + 5\n : area.y1 + inset + options.labelOffset.y + 5\n }\n }\n : {\n position: area.y1 - relative,\n labelOffset: {\n x:\n side === 'left'\n ? area.x1 - inset - options.offset + options.labelOffset.x\n : area.x2 + inset + options.labelOffset.x + 10,\n y: options.labelOffset.y - labelLength\n }\n };\n\nfunction nodesOf(\n axis: PlacedScaleAxis,\n context: LayerContext,\n classNames: AxisLayerClassNames,\n svgLabel?: SvgLabelBuilder\n) {\n return axisNodes(axis, {\n svgLabel,\n area: context.area,\n padding: context.padding,\n classNames,\n options: drawnOptions(axis),\n place: placeOnSide(axis.side, axis.inset),\n atStart: axis.side === 'top' || axis.side === 'left'\n });\n}\n\n/**\n * Creates a layer that draws the grid lines of the named axes (default:\n * all) in `g.ct-grids`, one `line.ct-grid` per tick. List it first, so\n * the series draw over it.\n *\n * @example\n * ```ts\n * import {\n * autoScaleAxis,\n * axisGrid,\n * axisLabels,\n * cartesianAxes,\n * chart,\n * line,\n * stepAxis\n * } from 'chartist';\n *\n * const hours = ['6am', '9am', '12pm', '3pm', '6pm'];\n *\n * chart('#chart', {\n * data: { labels: hours, series: [[12, 17, 23, 21, 15]] },\n * axes: cartesianAxes([\n * { id: 'time', side: 'bottom', type: stepAxis(), ticks: hours },\n * { id: 'celsius', side: 'left', type: autoScaleAxis() }\n * ]),\n * // Horizontal lines only, on a background rect.\n * layers: [\n * axisGrid({ axes: ['celsius'], background: true }),\n * line(),\n * axisLabels()\n * ]\n * });\n * ```\n * @param options The axes to draw and their classes; `background` adds a\n * `rect.ct-grid-background` over the chart area, behind the lines.\n * @experimental\n */\nexport function axisGrid(\n options: AxisLayerOptions & { readonly background?: boolean } = {}\n): Layer {\n const classNames = { ...CLASS_NAMES, ...options.classNames };\n return {\n type: 'axisGrid',\n coordinates: ['cartesian'],\n // Draws no series, so it doesn't count toward any axis range.\n series: [],\n compose(context) {\n const lines: SceneNode[] = selectedAxes(context, options.axes).flatMap(\n axis => nodesOf(axis, context, classNames).grids\n );\n if (options.background) {\n lines.unshift(gridBackground(context.area, classNames.gridBackground));\n }\n return [\n withFields(node('g', {}, classNames.gridGroup), { children: lines })\n ];\n }\n };\n}\n\n/**\n * Creates a layer that draws the labels of the named axes (default: all)\n * in `g.ct-labels`, each on its axis's side. Axes on the same side stack\n * outward, each in its own `offset`. List it last, so the labels draw\n * over the series.\n *\n * Labels are HTML in a `foreignObject` (as in 1.x) or SVG `text`: the\n * chart's `labels` option decides, unless the layer sets its own.\n *\n * @example\n * ```ts\n * import {\n * autoScaleAxis,\n * axisGrid,\n * axisLabels,\n * cartesianAxes,\n * chart,\n * line,\n * stepAxis\n * } from 'chartist';\n *\n * const weeks = ['W1', 'W2', 'W3', 'W4'];\n *\n * chart('#chart', {\n * data: { labels: weeks, series: [[3, 5, 4, 8]] },\n * axes: cartesianAxes([\n * { id: 'week', side: 'bottom', type: stepAxis(), ticks: weeks },\n * { id: 'km', side: 'left', type: autoScaleAxis(), low: 0 }\n * ]),\n * layers: [\n * axisGrid(),\n * line(),\n * // SVG text instead of HTML, e.g. to export the SVG.\n * axisLabels({ labels: 'svg' })\n * ]\n * });\n * ```\n * @experimental\n */\nexport function axisLabels(options: AxisLabelsOptions = {}): Layer {\n const classNames = { ...CLASS_NAMES, ...options.classNames };\n return {\n type: 'axisLabels',\n coordinates: ['cartesian'],\n series: [],\n compose(context) {\n const svgLabel =\n (options.labels ?? context.labels) === 'svg'\n ? svgLabels(context.measureText, 'line', options.align)\n : undefined;\n return [\n withFields(node('g', {}, classNames.labelGroup), {\n children: selectedAxes(context, options.axes).flatMap(\n axis => nodesOf(axis, context, classNames, svgLabel).labels\n )\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