//#endregion //#region src/core/constants.d.ts /** * This object contains all namespaces used within Chartist. */ export declare const namespaces: Record; /** * Precision level used internally in Chartist for rounding. If you require more decimal places you can increase this number. */ export declare const precision = 8; /** * A map with characters to escape for strings to be safely used as attribute values. */ export declare const escapingMap: Record; //#endregion //#region src/core/lang.d.ts /** * Converts a number to a string with a unit. If a string is passed then this will be returned unmodified. * @return Returns the passed number value with unit. */ export declare function ensureUnit(value: T, unit: string): string | T; /** * Converts a number or string to a quantity object. * @return Returns an object containing the value as number and the unit as string. */ export declare function quantity(input: T): { value: number; unit: string | undefined; } | { value: number; unit?: undefined; }; /** * Generates a-z from a number 0 to 26 * @param n A number from 0 to 26 that will result in a letter a-z * @return A character from a-z based on the input number n */ export declare function alphaNumerate(n: number): string; //#endregion //#region src/utils/types.d.ts /** Narrows a union `T` to the members that have the key `K` (an optional `K` becomes required). */ export type FilterByKey = T extends Record ? T : T extends Partial> ? T & { [key in K]: T[K]; } : never; /** `T` with the keys `K` required, and the keys `V` required down one level. */ export type RequiredKeys = T & Required> & { [key in V]: Required; }; //#endregion //#region src/utils/extend.d.ts /** * Merges the sources into `target`, deeply, and returns `target`. Plain * objects merge key by key into an object already there, and replace any * other value (an object over a number gives a copy of the object); arrays, * from any realm, and other values replace what's there. * Keys of the target's prototype are skipped, against prototype pollution. * @param target The object the sources are merged into (changed in place). * @returns `target`, with the sources' properties. */ export declare function extend(target: T): T; export declare function extend(target: T, a: A): T & A; export declare function extend(target: T, a: A, b: B): T & A & B; //#endregion //#region src/utils/functional.d.ts /** * Helps to simplify functional style code * @param n This exact value will be returned by the noop function * @return The same value that was provided to the n parameter */ export declare const noop: (n: T) => T; /** * Functional style helper to produce array with given length initialized with undefined values */ export declare function times(length: number): undefined[]; export declare function times(length: number, filler: (index: number) => T): T[]; /** * Sum helper to be used in reduce functions */ export declare const sum: (previous: number, current: number) => number; /** * 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). * * For example: * @example * ```ts * const data = [[1, 2], [3], []]; * serialMap(data, cb); * * // where cb will be called 2 times * // 1. call arguments: (1, 3, undefined) * // 2. call arguments: (2, undefined, undefined) * ``` */ export declare const serialMap: (array: T[][], callback: (...args: T[]) => K) => K[]; //#endregion //#region src/utils/utils.d.ts /** * This function safely checks if an objects has an owned property. * @param target The object where to check for a property * @param property The property name * @returns Returns true if the object owns the specified property */ export declare function safeHasProperty(target: T, property: K): target is FilterByKey; /** * 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. */ export declare function isNumeric(value: number): true; export declare function isNumeric(value: unknown): boolean; /** * Returns true on all falsey values except the numeric value 0. */ export declare function isFalseyButZero(value: unknown): value is undefined | null | false | ''; /** * 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. */ export declare function getNumberOrUndefined(value: number): number; export declare function getNumberOrUndefined(value: unknown): number | undefined; /** * Checks if value is array of arrays or not. */ export declare function isArrayOfArrays(data: unknown): data is unknown[][]; /** * Loop over array. */ export declare function each(list: T[], callback: (item: T, index: number, itemIndex: number) => void, reverse?: boolean): void; //#endregion //#region src/event/EventEmitter.d.ts /** * A listener of one event: gets the event's payload. * * @deprecated Use the chart handle's `on()` and `off()`. Removed in 3.0. */ export type EventListener = (data: T) => void; /** * A listener of every event (`'*'`): gets the event's name and payload. * * @deprecated Use the chart handle's `on()` and `off()`. Removed in 3.0. */ export type AllEventsListener = (event: string, data: T) => void; /** * The 1.x event emitter: `on`, `off` and `emit` by event name, with `'*'` for all events. * * @deprecated Use the chart handle's `on()` and `off()`. Removed in 3.0. */ export declare class EventEmitter { private readonly listeners; private readonly allListeners; /** * Add an event handler for a specific event * @param event The event name * @param listener A event handler function */ on(event: '*', listener: AllEventsListener): void; on(event: string, listener: EventListener): void; /** * Remove an event handler of a specific event name or remove all event handlers for a specific event. * @param event The event name where a specific or all handlers should be removed * @param [listener] An optional event handler function. If specified only this specific handler will be removed and otherwise all handlers are removed. */ off(event: '*', listener?: AllEventsListener): void; off(event: string, listener?: EventListener): void; /** * Use this function to emit an event. All handlers that are listening for this event will be triggered with the data parameter. * @param event The event name that should be triggered * @param data Arbitrary data that will be passed to the event handler callback functions */ emit(event: string, data: T): void; } //#endregion //#region src/svg/SvgList.d.ts type SvgMethods = Exclude; type SvgListMethods = { [method in SvgMethods]: (...args: Parameters) => SvgList; }; /** * A list of {@link Svg} wrappers that calls an `Svg` method on all of them * at once, such as `addClass` or `animate`. Each method returns the list, * for chaining. {@link Svg.querySelectorAll} returns one. */ export declare class SvgList implements SvgListMethods { private svgElements; /** * Wraps each element of the list in an {@link Svg}. * @param nodeList An Array of SVG DOM nodes or a SVG DOM NodeList (as returned by document.querySelectorAll) */ constructor(nodeList: ArrayLike); private call; /** Sets attributes on every element, as {@link Svg.attr} does. */ attr(...args: Parameters): this; /** Adds a child element to every element, as {@link Svg.elem} does. */ elem(...args: Parameters): this; /** Calls {@link Svg.root} on every element; returns the list, not the roots. */ root(...args: Parameters): this; /** Calls {@link Svg.getNode} on every element; returns the list, not the nodes. */ getNode(...args: Parameters): this; /** Adds a `foreignObject` with the content to every element, as {@link Svg.foreignObject} does. */ foreignObject(...args: Parameters): this; /** Adds a text node to every element, as {@link Svg.text} does. */ text(...args: Parameters): this; /** Removes the children of every element, as {@link Svg.empty} does. */ empty(...args: Parameters): this; /** Removes every element from its parent, as {@link Svg.remove} does. */ remove(...args: Parameters): this; /** Adds classes to every element, as {@link Svg.addClass} does. */ addClass(...args: Parameters): this; /** Removes classes from every element, as {@link Svg.removeClass} does. */ removeClass(...args: Parameters): this; /** Removes all classes from every element, as {@link Svg.removeAllClasses} does. */ removeAllClasses(...args: Parameters): this; /** Animates attributes of every element with SMIL, as {@link Svg.animate} does. */ animate(...args: Parameters): this; } //#endregion //#region src/svg/Svg.d.ts /** * Wraps an SVG element for chaining: set attributes and classes, add child * elements, and animate attributes with SMIL. Wrap an element of a rendered * chart (from `elementOf` in a `mount` listener), or create a new one by * name. * * @example * ```ts * import { barChart, findAll, Svg, type ChartPlugin } from 'chartist'; * * // Bars grow from the axis, animated from a plugin's mount listener. * const growBars: ChartPlugin = { * name: 'grow-bars', * install(chart) { * chart.on('mount', ({ scene, elementOf }) => { * for (const bar of findAll(scene, { role: 'bar' })) { * const element = elementOf(bar); * if (element) { * new Svg(element).animate({ * y2: { * begin: bar.ctx.valueIndex * 120, * dur: 700, * from: bar.attrs.y1, * to: bar.attrs.y2, * easing: 'easeOutQuint' * } * }); * } * } * }); * } * }; * * barChart('#chart', { series: [[5, 4, 3, 7]] }, { plugins: [growBars] }); * ``` */ export declare class Svg { /** * The easing curves for {@link Svg.animate}, as 1.x had them on the class. * @deprecated Use the {@link easings} export. */ static readonly Easing: { easeInSine: number[]; easeOutSine: number[]; easeInOutSine: number[]; easeInQuad: number[]; easeOutQuad: number[]; easeInOutQuad: number[]; easeInCubic: number[]; easeOutCubic: number[]; easeInOutCubic: number[]; easeInQuart: number[]; easeOutQuart: number[]; easeInOutQuart: number[]; easeInQuint: number[]; easeOutQuint: number[]; easeInOutQuint: number[]; easeInExpo: number[]; easeOutExpo: number[]; easeInOutExpo: number[]; easeInCirc: number[]; easeOutCirc: number[]; easeInOutCirc: number[]; easeInBack: number[]; easeOutBack: number[]; easeInOutBack: number[]; }; private _node; /** * Creates an SVG element and wraps it, or wraps an existing element. * @param name The name of the SVG element to create or an SVG dom element which should be wrapped into Svg * @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. * @param className This class or class list will be added to the SVG element * @param parent The parent SVG wrapper object where this newly created wrapper and it's element will be attached to as child * @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 */ constructor(name: string | Element, attributes?: Attributes, className?: string, parent?: Svg, insertFirst?: boolean); /** * Set attributes on the current SVG element of the wrapper you're currently working on. * @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. * @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. * @return The current wrapper object will be returned so it can be used for chaining or the attribute value if used as getter function. */ attr(attributes: string, ns?: string): string | null; attr(attributes: Attributes): this; /** * Create a new SVG element whose wrapper object will be selected for further operations. This way you can also create nested groups easily. * @param name The name of the SVG element that should be created as child element of the currently selected element wrapper * @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. * @param className This class or class list will be added to the SVG element * @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 * @return Returns a Svg wrapper object that can be used to modify the containing SVG data */ elem(name: string, attributes?: Attributes, className?: string, insertFirst?: boolean): Svg; /** * Wraps the element's parent. * @returns The parent in a new `Svg`, or `null` if there is none or it isn't an SVG element. */ parent(): Svg | null; /** * This method returns a Svg wrapper around the root SVG element of the current tree. * @return The root SVG element wrapped in a Svg element */ root(): Svg; /** * Find the first child SVG element of the current element that matches a CSS selector. The returned object is a Svg wrapper. * @param selector A CSS selector that is used to query for child SVG elements * @return The SVG wrapper for the element found or null if no element was found */ querySelector(selector: string): Svg | null; /** * Finds all descendants of the element that match a CSS selector. * @param selector A CSS selector that is used to query for child SVG elements * @returns The elements found in an {@link SvgList} (empty if none match). */ querySelectorAll(selector: string): SvgList; /** * Returns the underlying SVG node for the current element. */ getNode(): T; /** * 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. * @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 * @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. * @param className This class or class list will be added to the SVG element * @param insertFirst Specifies if the foreignObject should be inserted as first child * @return New wrapper object that wraps the foreignObject element */ foreignObject(content: string | Node, attributes?: Attributes, className?: string, insertFirst?: boolean): Svg; /** * This method adds a new text element to the current Svg wrapper. * @param t The text that should be added to the text element that is created * @return The same wrapper object that was used to add the newly created element */ text(t: string): this; /** * This method will clear all child nodes of the current wrapper object. * @return The same wrapper object that got emptied */ empty(): this; /** * Removes the element from its parent. * @returns The parent it had, wrapped in a new `Svg`, or `null` if it had * none or the parent isn't an SVG element. */ remove(): Svg | null; /** * This method will replace the element with a new element that can be created outside of the current DOM. * @param newElement The new Svg object that will be used to replace the current wrapper object * @return The wrapper of the new element */ replace(newElement: Svg): Svg; /** * This method will append an element to the current element as a child. * @param element The Svg element that should be added as a child * @param insertFirst Specifies if the element should be inserted as first child * @return The wrapper of the appended object */ append(element: Svg, insertFirst?: boolean): this; /** * Returns an array of class names that are attached to the current wrapper element. This method can not be chained further. * @return A list of classes or an empty array if there are no classes on the current element */ classes(): string[]; /** * Adds one or a space separated list of classes to the current element and ensures the classes are only existing once. * @param names A white space separated list of class names * @return The wrapper of the current element */ addClass(names: string): this; /** * Removes one or a space separated list of classes from the current element. * @param names A white space separated list of class names * @return The wrapper of the current element */ removeClass(names: string): this; /** * Removes all classes from the current element. * @return The wrapper of the current element */ removeAllClasses(): this; /** * Get element height using `clientHeight` * @return The elements height in pixels */ height(): number; /** * Get element width using `clientWidth` * @return The elements width in pixels */ width(): number; /** * Animates attributes of the element with SMIL: adds an `` * element per attribute. Each {@link AnimationDefinition} holds SMIL * attributes (usually `begin`, `dur`, `from` and `to`, see * https://www.w3.org/TR/SVG11/animate.html), plus an optional `easing`: a * name from {@link easings} or four numbers of a cubic Bézier curve. * * An animations object could look like this: * ```ts * element.animate({ * opacity: { * dur: 1000, * from: 0, * to: 1 * }, * x1: { * dur: '1000ms', * from: 100, * to: 200, * easing: 'easeOutQuart' * }, * y1: { * dur: '2s', * from: 0, * to: 100 * } * }); * ``` * * `dur` and `begin` given as numbers are milliseconds. * * **Guided mode** (the default) makes one-off animations behave: the * attribute is set to `from` right away, even before a delayed start; the * animation starts after `begin` ms (a timeout, not the document's * timeline); and when it ends, the attribute keeps `to` and the * `` element is removed. Pass `guided: false` to write the * `` elements as given. An attribute with an array of * definitions never runs guided. * @param animations The attributes to animate, each with a definition, or * an array of definitions to run several animations on one attribute. * @param guided Runs the animations in guided mode (see above). * @param eventEmitter Gets `animationBegin` and `animationEnd` events * ({@link AnimationEvent}) when an animation starts and ends. With the * compat plugin, elements of a chart send them to the chart by default. * @returns The same wrapper, for chaining. */ animate(animations: Record, guided?: boolean, eventEmitter?: EventEmitter): this; } //#endregion //#region src/svg/types.d.ts /** The end point every path command has. */ export interface BasePathParams { /** The x of the command's end point. */ x: number; /** The y of the command's end point. */ y: number; } /** The parameters of a move command (`M`): the point to move to. */ export type MoveParams = BasePathParams; /** The parameters of a line command (`L`): the point to draw to. */ export type LineParams = BasePathParams; /** The parameters of a cubic Bézier curve command (`C`). */ export interface CurveParams extends BasePathParams { /** The x of the first control point. */ x1: number; /** The y of the first control point. */ y1: number; /** The x of the second control point. */ x2: number; /** The y of the second control point. */ y2: number; } /** The parameters of an elliptical arc command (`A`), as in SVG. */ export interface ArcParams extends BasePathParams { /** The x radius of the ellipse. */ rx: number; /** The y radius of the ellipse. */ ry: number; /** The rotation of the ellipse's x axis, in degrees. */ xAr: number; /** The large arc flag: `1` takes the longer way around, `0` the shorter. */ lAf: number; /** The sweep flag: `1` draws the arc clockwise, `0` counterclockwise. */ sf: number; } /** The parameters of any path command. */ export type PathParams = MoveParams | LineParams | CurveParams | ArcParams; /** A command of an {@link SvgPath}: its letter, its parameters and the data of its point. */ export type PathCommand = { /** The command letter: `M`, `L`, `C` or `A`, or from a parsed path also `H`, `V`, `S`, `Q`, `T` or `Z` (lowercase when relative). */ command: string; /** The value of the chart point the command draws to, if any. */ data?: SegmentData; } & T; /** The options of an {@link SvgPath}. */ export interface SvgPathOptions { /** * The decimals numbers are rounded to when the path is stringified: `0` * rounds to integers, `false` doesn't round. */ accuracy?: number | false; } /** * SVG attributes by name, for {@link Svg.attr}. `undefined` values are * skipped; names with a prefix such as `ct:value` use its namespace. */ export type Attributes = Record; /** * One SMIL animation of an attribute, for {@link Svg.animate}: the * attributes of its `` element, plus an `easing`. */ export interface AnimationDefinition { /** The `id` of the `` element, to start other animations relative to it. */ id?: string; /** * The easing: a name from {@link easings}, four numbers of a cubic * Bézier curve, or a CSS easing such as `'ease-out'`, * `'cubic-bezier(0.34, 1.56, 0.64, 1)'`, `linear()` or `steps()`. Sets * `calcMode`, `keySplines` and `keyTimes` for you, or, for easings SMIL * can't express (ones that overshoot, `linear()`, `steps()`), `values` * sampled between `from` and `to`. */ easing?: number[] | keyof typeof easings | (string & {}); /** How values are interpolated (SMIL `calcMode`); an `easing` sets `'spline'`. */ calcMode?: 'discrete' | 'linear' | 'paced' | 'spline'; /** Whether the animation can restart while it's running (SMIL `restart`). */ restart?: 'always' | 'whenNotActive' | 'never'; /** How many times the animation repeats, or `'indefinite'`. */ repeatCount?: number | 'indefinite'; /** How long the animation repeats in total, or `'indefinite'`. */ repeatDur?: string | 'indefinite'; /** The Bézier control points of a `'spline'` animation (SMIL `keySplines`); an `easing` sets them. */ keySplines?: string; /** The times of the key values, from `0` to `1` (SMIL `keyTimes`); an `easing` sets them. */ keyTimes?: string; /** The values in between, `;`-separated (SMIL `values`); an easing that overshoots sets them. */ values?: string; /** `'freeze'` keeps the last value after the animation, `'remove'` resets it. Guided mode sets `'freeze'`. */ fill?: string; /** The minimum active duration (SMIL `min`). */ min?: number | string; /** The maximum active duration (SMIL `max`). */ max?: number | string; /** When the animation starts: ms as a number, or a SMIL time such as `'1s'`. */ begin?: number | string; /** When the animation ends (SMIL `end`). */ end?: number | string; /** How long the animation runs: ms as a number, or a SMIL time such as `'2s'`. */ dur: number | string; /** The value the attribute starts at. */ from: number | string; /** The value the attribute ends at. */ to: number | string; } /** * The payload of the `animationBegin` and `animationEnd` events that * {@link Svg.animate} emits when it gets an event emitter. */ export interface AnimationEvent { /** The animated element. */ element: Svg; /** The `` element. */ animate: Element; /** The animation's definition, as given. */ params: AnimationDefinition; } //#endregion //#region src/svg/animation.d.ts /** * The named easing curves for {@link Svg.animate}, from `easeInSine` to * `easeInOutBack`: each the four numbers of a cubic Bézier curve. Name one * as an animation's `easing`, or pass four numbers of your own, such as * `easing: [0.25, 0.1, 0.25, 1]`. * * @example * ```ts * import { lineChart, findAll, Svg, type ChartPlugin } from 'chartist'; * * // Points drop in from the top and bounce a little at the end. * const dropIn: ChartPlugin = { * name: 'drop-in', * install(chart) { * chart.on('mount', ({ scene, elementOf }) => { * for (const point of findAll(scene, { role: 'point' })) { * const element = elementOf(point); * const { y } = point.ctx; * if (element) { * new Svg(element).animate({ * y1: { dur: 600, from: 0, to: y, easing: 'easeOutBack' }, * y2: { dur: 600, from: 0, to: y, easing: 'easeOutBack' } * }); * } * } * }); * } * }; * * lineChart('#chart', { series: [[5, 2, 4, 3]] }, { plugins: [dropIn] }); * ``` */ export declare const easings: { easeInSine: number[]; easeOutSine: number[]; easeInOutSine: number[]; easeInQuad: number[]; easeOutQuad: number[]; easeInOutQuad: number[]; easeInCubic: number[]; easeOutCubic: number[]; easeInOutCubic: number[]; easeInQuart: number[]; easeOutQuart: number[]; easeInOutQuart: number[]; easeInQuint: number[]; easeOutQuint: number[]; easeInOutQuint: number[]; easeInExpo: number[]; easeOutExpo: number[]; easeInOutExpo: number[]; easeInCirc: number[]; easeOutCirc: number[]; easeInOutCirc: number[]; easeInBack: number[]; easeOutBack: number[]; easeInOutBack: number[]; }; /** * The SMIL `keySplines` of an easing SMIL can express: a cubic Bézier * curve whose four numbers lie within 0 and 1 (the CSS keywords, many * `cubic-bezier()` curves, most names of {@link easings}). Browsers ignore * an animation whose `keySplines` leave that range, so for other easings * it returns nothing: sample them with {@link sampleEasing} instead. * * @example * ```ts * import { keySplinesOf } from 'chartist'; * * keySplinesOf('ease-out'); // '0 0 0.58 1' * keySplinesOf('easeOutBack'); // undefined: it overshoots * ``` * @param easing A CSS easing, a name of {@link easings}, or four numbers * @returns The `keySplines` value, or nothing */ export declare function keySplinesOf(easing: string | readonly number[]): string | undefined; /** * The eased progress of an animation at evenly spaced times, for SMIL * `values` with even `keyTimes`: 12 points, and one per 50 ms for * animations longer than 600 ms, at most 40. It takes the CSS easings * (the keywords, `cubic-bezier()` curves, also ones that overshoot, * `linear()` and `steps()`), the names of {@link easings} and four * numbers of a cubic Bézier curve; anything else is sampled as `ease`. * Points lie below 0 or above 1 where the easing overshoots. * * @example * ```ts * import { sampleEasing } from 'chartist'; * * // A value that grows from 10 to 20 and overshoots a little on the way. * const progress = sampleEasing('cubic-bezier(0.34, 1.56, 0.64, 1)', 400); * const values = progress.map(p => 10 + (20 - 10) * p).join(';'); * ``` * @param easing The easing * @param duration The animation's duration in ms * @returns The progress at each point, from 0 to 1 */ export declare function sampleEasing(easing: string | readonly number[], duration: number): number[]; //#endregion //#region src/svg/SvgPath.d.ts /** * Builds and changes the `d` of an SVG `path`: move, line, curve and arc * commands, with a cursor where new commands go. Lines, areas and slices * are `SvgPath`s, and interpolations such as {@link Interpolation.cardinal} * return one. Each command can carry the data of its point, which the * chart reads back for its points. * * @example * ```ts * import { SvgPath } from 'chartist'; * * const path = new SvgPath() * .move(0, 100) * .line(50, 20) * .curve(70, 0, 90, 0, 100, 40); * * path.stringify(); // 'M0,100L50,20C70,0,90,0,100,40' * * // 10px to the right, at half the height * path.translate(10, 0).scale(1, 0.5); * ``` */ export declare class SvgPath { private readonly close; /** * Joins paths into a new path, in the order given. The new path gets * copies of the commands, and its cursor is at the end. * @param paths A list of paths to be joined together. The order is important. * @param close If the newly created path should be a closed path * @param options Path options for the newly created path. */ static join(paths: SvgPath[], close?: boolean, options?: SvgPathOptions): SvgPath; /** The path's commands, in order: each with its letter, its coordinates and the data of its point. */ pathElements: PathCommand[]; private pos; private options; /** * Creates an empty path. * @param close Closes the path when it's stringified (a `Z` at the end). * @param options The path's options, such as the rounding `accuracy`. */ constructor(close?: boolean, options?: SvgPathOptions); /** * 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. * @param pos If a number is passed then the cursor is set to this position in the path element array. * @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. */ position(pos: number): this; position(): number; /** * Removes elements from the path starting at the current position. * @param count Number of path elements that should be removed from the current position. * @return The current path object for easy call chaining. */ remove(count: number): this; /** * Use this function to add a new move SVG path element. * @param x The x coordinate for the move element. * @param y The y coordinate for the move element. * @param relative If set to true the move element will be created with relative coordinates (lowercase letter) * @param data Any data that should be stored with the element object that will be accessible in pathElement * @return The current path object for easy call chaining. */ move(x: number, y: number, relative?: boolean, data?: SegmentData): this; /** * Use this function to add a new line SVG path element. * @param x The x coordinate for the line element. * @param y The y coordinate for the line element. * @param relative If set to true the line element will be created with relative coordinates (lowercase letter) * @param data Any data that should be stored with the element object that will be accessible in pathElement * @return The current path object for easy call chaining. */ line(x: number, y: number, relative?: boolean, data?: SegmentData): this; /** * Use this function to add a new curve SVG path element. * @param x1 The x coordinate for the first control point of the bezier curve. * @param y1 The y coordinate for the first control point of the bezier curve. * @param x2 The x coordinate for the second control point of the bezier curve. * @param y2 The y coordinate for the second control point of the bezier curve. * @param x The x coordinate for the target point of the curve element. * @param y The y coordinate for the target point of the curve element. * @param relative If set to true the curve element will be created with relative coordinates (lowercase letter) * @param data Any data that should be stored with the element object that will be accessible in pathElement * @return The current path object for easy call chaining. */ curve(x1: number, y1: number, x2: number, y2: number, x: number, y: number, relative?: boolean, data?: SegmentData): this; /** * Use this function to add a new non-bezier curve SVG path element. * @param rx The radius to be used for the x-axis of the arc. * @param ry The radius to be used for the y-axis of the arc. * @param xAr Defines the orientation of the arc * @param lAf Large arc flag * @param sf Sweep flag * @param x The x coordinate for the target point of the curve element. * @param y The y coordinate for the target point of the curve element. * @param relative If set to true the curve element will be created with relative coordinates (lowercase letter) * @param data Any data that should be stored with the element object that will be accessible in pathElement * @return The current path object for easy call chaining. */ arc(rx: number, ry: number, xAr: number, lAf: number, sf: number, x: number, y: number, relative?: boolean, data?: SegmentData): this; /** * Parses the `d` of an SVG path and inserts its commands at the cursor. A * closing `Z` at the end is dropped: the `close` of the path object decides * that. * @param path An SVG path of any commands (`M`, `L`, `H`, `V`, `C`, `S`, `Q`, `T`, `A`, `Z`), absolute or relative. * @return The current path object for easy call chaining. * @throws An `Error` if the path isn't valid SVG path syntax. */ parse(path: string): this; /** * Writes the path as a string for the `d` attribute of a `path` element. * Numbers are rounded to the `accuracy` option's decimals (to integers * with `0`, not at all with `false`), and a closed path ends with `Z`. */ stringify(): string; /** * 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. * @param x The number which will be used to scale the x, x1, x2 and rx of all path elements. * @param y The number which will be used to scale the y, y1, y2 and ry of all path elements. * @return The current path object for easy call chaining. */ scale(x: number, y: number): this; /** * 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. * @param x The number which will be used to translate the x, x1 and x2 of all path elements. * @param y The number which will be used to translate the y, y1 and y2 of all path elements. * @return The current path object for easy call chaining. */ translate(x: number, y: number): this; /** * 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. * The method signature of the callback function looks like this: * ```javascript * function(pathElement, paramName, pathElementIndex, paramIndex, pathElements) * ``` * 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. * @param transformFnc The callback function for the transformation. Check the signature in the function description. * @return The current path object for easy call chaining. */ transform(transformFnc: (cmd: PathCommand, param: keyof T, cmdIndex: number, paramIndex: number, cmds: PathCommand[]) => number | void): this; /** * This function clones a whole path object with all its properties. This is a deep clone and path element objects will also be cloned. * @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. */ clone(close?: boolean): SvgPath; /** * Splits the path into new paths, each starting at the given command, * such as `'M'` to get the separate pieces of a line with holes. The * letter matches absolute and relative commands. The pieces get copies of * the commands and the path's options, with their cursor at the end; the * last piece is closed if the path is. * @param command The command letter to split at. */ splitByCommand(command: string): SvgPath[]; } //#endregion //#region src/axes/Axis.d.ts /** The names an axis uses per dimension: its position, length and direction, and its edges in the {@link ChartRect}. */ export declare const axisUnits: { readonly x: { readonly pos: "x"; readonly len: "width"; readonly dir: "horizontal"; readonly rectStart: "x1"; readonly rectEnd: "x2"; readonly rectOffset: "y2"; }; readonly y: { readonly pos: "y"; readonly len: "height"; readonly dir: "vertical"; readonly rectStart: "y2"; readonly rectEnd: "y1"; readonly rectOffset: "x1"; }; }; /** The units of the X axis: `axisUnits.x`. */ export type XAxisUnits = typeof axisUnits.x; /** The units of the Y axis: `axisUnits.y`. */ export type YAxisUnits = typeof axisUnits.y; /** The units of either axis. */ export type AxisUnits = XAxisUnits | YAxisUnits; /** * The base class of the 1.x axes: projects values to px along the drawing * area and draws its grid lines and labels. * * @deprecated Use the scale functions `autoScaleAxis()`, `fixedScaleAxis()` and `stepAxis()`. Removed in 3.0. */ export declare abstract class Axis { readonly units: AxisUnits; private readonly chartRect; private readonly ticks; readonly counterUnits: AxisUnits; readonly range: { min: number; max: number; } | undefined; readonly axisLength: number; private readonly gridOffset; constructor(units: AxisUnits, chartRect: ChartRect, ticks: Label[]); abstract projectValue(value: NormalizedSeriesPrimitiveValue | Label, index?: number, series?: NormalizedSeries): number; createGridAndLabels(gridGroup: Svg, labelGroup: Svg, chartOptions: OptionsWithDefaults, eventEmitter: EventEmitter): void; } //#endregion //#region src/axes/AutoScaleAxis.d.ts /** * The 1.x axis with a scale fitted to the values, in round steps at least `scaleMinSpace` px apart. * * @deprecated Use `autoScaleAxis()`. Removed in 3.0. */ export declare class AutoScaleAxis extends Axis { private readonly bounds; readonly range: { min: number; max: number; }; constructor(axisUnit: AxisUnits, data: NormalizedSeries[], chartRect: ChartRect, options: AxisOptions); projectValue(value: NormalizedSeriesPrimitiveValue): number; } //#endregion //#region src/axes/FixedScaleAxis.d.ts /** * The 1.x axis with fixed ticks: the `ticks` option, or `divisor` equal steps from low to high, with a tick at both ends. * * @deprecated Use `fixedScaleAxis()`. Removed in 3.0. */ export declare class FixedScaleAxis extends Axis { readonly range: { min: number; max: number; }; constructor(axisUnit: AxisUnits, data: NormalizedSeries[], chartRect: ChartRect, options: AxisOptions); projectValue(value: NormalizedSeriesPrimitiveValue): number; } //#endregion //#region src/axes/StepAxis.d.ts /** * The 1.x axis with one step per tick, such as the labels of a line chart's X axis. * * @deprecated Use `stepAxis()`. Removed in 3.0. */ export declare class StepAxis extends Axis { private readonly stepLength; readonly stretch: boolean; constructor(axisUnit: AxisUnits, _data: unknown, chartRect: ChartRect, options: AxisOptions); projectValue(_value: unknown, index: number): number; } //#endregion //#region src/axes/types.d.ts /** * The 1.x axis classes an axis's `type` option takes: {@link AutoScaleAxis}, {@link FixedScaleAxis} or {@link StepAxis}. * * @deprecated Use the scale functions `autoScaleAxis()`, `fixedScaleAxis()` and `stepAxis()`. Removed in 3.0. */ export type AxisType = typeof AutoScaleAxis | typeof FixedScaleAxis | typeof StepAxis; //#endregion //#region src/render/measure.d.ts /** The size of a measured text, as a {@link MeasureText} function returns it. */ interface TextMetrics { /** The text's width in px. */ readonly width: number; /** The text's height in px: one line. */ readonly height: number; /** The font size in px the text was measured with, when known. */ readonly fontSize?: number; } /** * How labels are drawn: HTML in a `foreignObject` (1.x) or SVG `text`. */ type LabelMode = 'html' | 'svg'; /** What a {@link MeasureText} function gets with the text to measure. */ interface MeasureTextOptions { /** Class names of the text, for renderers that apply CSS. */ readonly classes?: readonly string[]; /** * Font size in px. Without it, the browser measures with the CSS font * size and the estimate uses 12, the size of 1.x `.ct-label`. */ readonly fontSize?: number; /** Classes of the chart's root svg, so chart-type CSS applies. */ readonly rootClass?: string; /** Where to measure (the chart container), so its CSS applies. */ readonly container?: Element; } /** * Measures how much space a text takes, in px, so labels can be wrapped * and aligned. In the browser, Chartist measures with the page's fonts; * `toScene()` estimates (0.6 em per character, 1.2 em per line) unless you * pass your own in its size. * * @example * ```ts * import type { MeasureText } from 'chartist'; * * // Wider glyphs than the estimate, for a wide font. * export const measureText: MeasureText = (text, options = {}) => { * const fontSize = options.fontSize ?? 12; * return { width: text.length * fontSize * 0.7, height: fontSize * 1.25 }; * }; * ``` */ type MeasureText = (text: string, options?: MeasureTextOptions) => TextMetrics; /** What a {@link MeasureStyle} function gets with the property to read. */ interface MeasureStyleOptions { /** Class names of the element whose style is read. */ readonly classes?: readonly string[]; /** Classes of the chart's root svg, so chart-type CSS applies. */ readonly rootClass?: string; /** Where to measure (the chart container), so its CSS applies. */ readonly container?: Element; } /** * Reads a computed CSS property of an SVG `path` with the given classes, * for values that the stylesheet decides and layout needs: the pie layer * reads the `stroke-width` of a donut slice to fit the ring. Returns * `undefined` when it can't tell. In the browser, Chartist reads it in * the chart's container; `toScene()` has no stylesheet, so layout uses * its defaults there. * * @example * ```ts * import { domRenderer, type Renderer } from 'chartist'; * * // The DOM renderer, but donuts are laid out for 30px rings, whatever * // the stylesheet says. Pass it as `renderer` to `chart()`. * export const renderer: Renderer = { * ...domRenderer(), * measureStyle: property => (property === 'stroke-width' ? '30px' : undefined) * }; * ``` */ type MeasureStyle = (property: string, options?: MeasureStyleOptions) => string | undefined; /** * Where SVG text labels put a line's baseline: this share of the font size * below the top of the line (a typical font's ascent). Lines are one font * size apart, so a renderer finds a line's vertical center at * `y - (textAscent - 0.5) * fontSize` from its `y`. */ export declare const textAscent = 0.85; /** * Estimates text size without a DOM: an average glyph is 0.6 em wide, and a * line is 1.2 em high, at `fontSize` or else 12 px. `toScene()` measures * with it unless you pass your own, which can build on it. * * @example * ```ts * import { estimateText, type MeasureText } from 'chartist'; * * // Bold labels: a tenth wider than the estimate. * export const measureText: MeasureText = (text, options) => { * const size = estimateText(text, options); * return { ...size, width: size.width * 1.1 }; * }; * ``` */ export declare const estimateText: MeasureText; //#endregion //#region src/render/types.d.ts /** * Why a chart rendered: `create` for its first render, `hydrate` for the * first render of a chart that took server markup over (see * `renderForHydration()`), `update` for `update()` (and the presets' * `setOptions()`), `resize` when its container's size changed, * `responsive` when its matching `responsive` entries changed, `fonts` * when web fonts finished loading. */ type RenderCause = 'create' | 'hydrate' | 'update' | 'resize' | 'responsive' | 'fonts'; /** * What a render did to one node of the output: `add` for a node the * previous scene didn't have, `update` for a node whose attributes, * classes or text changed (with its `previous` node), `remove` for a node * of the previous scene that's gone. */ interface SceneChange { /** What happened to the node. */ readonly op: 'add' | 'update' | 'remove'; /** The node: of the new scene, or of the previous one for `remove`. */ readonly node: SceneNode; /** The node in the previous scene, for `update`. */ readonly previous?: SceneNode; } /** * The keyframes of a node's update animation: one set of attributes per * progress point, in the order of the points. */ type Keyframes = readonly Readonly>[]; /** * The timing of a render's update animation: its duration in ms and its * easing as a CSS easing, such as `ease-out`. */ interface UpdateAnimation { /** The duration in ms. */ readonly duration: number; /** The CSS easing, such as `ease-out` or `cubic-bezier(0.3, 0, 0.2, 1)`. */ readonly easing: string; } /** * What a renderer gets about the previous render, from a chart's second * render on. A renderer can change its previous output in place with it, * instead of replacing it; renderers keep no state themselves. */ interface RenderUpdate { /** What this renderer returned for the previous render. */ readonly previous: TOutput; /** The previous render's scene. */ readonly previousScene: SceneNode; /** Why the chart renders. */ readonly cause: RenderCause; /** The data's labels, for keys from labels. */ readonly labels: readonly unknown[]; /** The previous render's labels, for keys from labels in the previous scene. */ readonly previousLabels: readonly unknown[]; /** * Asks the chart's plugins, then the layer that drew the node, for the * keyframes of a node's update at the given progress points (0 is the * previous node, 1 the new one; points may lie beyond them when the * easing overshoots). Returns nothing when none of them has any. */ readonly keyframes: (previous: SceneNode, next: SceneNode, progress: readonly number[]) => Keyframes | undefined; } /** * What a renderer returns from `render()`. The `render` and `mount` phase * events pass it on as `output`. */ interface RenderOutput { /** The rendered element of a scene node, if the output is DOM. */ readonly elementOf?: (node: SceneNode) => Element | undefined; /** Removes the output again. */ readonly remove?: () => void; /** * `true` when the renderer changed its previous output in place with * the `update` it got, instead of replacing it. Then `changes` says what * it did. */ readonly patched?: boolean; /** * What the renderer did to each changed node, with `patched`. Without * them, the chart describes the render as a replacement. */ readonly changes?: readonly SceneChange[]; /** * The timing of the update animation the renderer started, if any. The * `mount` event passes it on as `animation`. */ readonly animation?: UpdateAnimation; } /** * Turns a scene into output. `chart()` renders inline SVG into its * container with the DOM renderer, unless its config sets a `renderer`. * To get markup instead, without a DOM, use `toScene()` and * `renderToString()` from `chartist/server`. A renderer that wraps another * one keeps its `adopt` only if it passes it on, as spreading the wrapped * renderer does. */ interface Renderer { /** * Renders a scene into the chart's container, after the `scene` phase * and on every update and resize. From the second render on, it gets * the previous render as `update`: a renderer that changes its previous * output in place returns `patched: true` and its `changes`; one that * ignores `update` replaces its output, as the DOM renderer does. * @param scene The scene to render, its root the `svg` * @param target The chart's container element * @param update The previous render, from the chart's second render on */ render(scene: SceneNode, target: Element, update?: RenderUpdate): TOutput; /** * Measures text for layout, in the container so its CSS applies; * without it, Chartist estimates text sizes. */ readonly measureText?: MeasureText; /** * Reads computed styles for layout, in the container so its CSS * applies; without it, layout uses its defaults (a donut's ring is * laid out for 60 px). */ readonly measureStyle?: MeasureStyle; /** The default label mode of this renderer; `html` if omitted. */ readonly labels?: LabelMode; /** * Takes over markup from `renderForHydration()` in the chart's container, * instead of rendering: finds it and reads the layout its marker * records, gets the scene for that layout from `replay`, binds the * scene's nodes to the markup's elements and makes them what `render()` * would draw. A chart calls it once, before its first render, unless it * always draws a new svg; later renders go through `render()`, with the * adopted output as the previous one. Returns nothing when there's no * markup to take over or it doesn't match the scene, and the chart then * renders as usual. `liveDomRenderer()` from `chartist/live` has it; the * DOM renderer doesn't, since it replaces its svg on every render. * @param container The chart's container element * @param replay Builds the chart's scene at the server's layout size and * label mode, with the plugins and listeners of the chart, as `render` * and `mount` then get it * @returns The output, with the number of attributes, classes and texts * that differed and were set as `repaired`; or nothing */ adopt?(container: Element, replay: (layout: { readonly width: number; readonly height: number; readonly labels: LabelMode; }) => SceneNode): (TOutput & { readonly repaired: number; }) | undefined; } //#endregion //#region src/charts/types.d.ts /** * The 1.x events every chart class emits and their payloads, by event name. * * @deprecated The 1.x events of the chart classes. On the chart functions, the handle's `on()` knows its events. Removed in 3.0. */ export interface BaseChartEventsTypes { data: DataEvent; options: OptionsChangedEvent; animationBegin: AnimationEvent; animationEnd: AnimationEvent; created: TCreateEvent; draw: TDrawEvents; } //#endregion //#region src/charts/LineChart/LineChart.types.d.ts /** Turns a series' points into the path of its line (see `Interpolation`). */ export type LineInterpolation = (pathCoordinates: number[], valueData: SegmentData[]) => SvgPath; /** The data of a line chart: series of values, and labels for the X axis. */ export type LineChartData = Data<(Series | SeriesObject)[]>; /** * The options of a line chart (1.x `LineChart`, and `lineChart`). * * @deprecated For `lineChart()`, the options type is `LineChartPresetOptions`. Removed in 3.0. */ export interface LineChartOptions extends Options { /** * The class names of the chart's elements. Change them to style the * chart with your own CSS instead of Chartist's. */ classNames?: { /** The chart's SVG element. */ chart?: string; /** Each axis label. */ label?: string; /** The group of an axis's labels. */ labelGroup?: string; /** The group of each series. */ series?: string; /** Each line. */ line?: string; /** Each point. */ point?: string; /** Each area. */ area?: string; /** Each grid line. */ grid?: string; /** The group of the grid lines. */ gridGroup?: string; /** The grid background (with `showGridBackground`). */ gridBackground?: string; /** Labels and grid lines of the vertical axis. */ vertical?: string; /** Labels and grid lines of the horizontal axis. */ horizontal?: string; /** Labels at the start of their axis (left or top). */ start?: string; /** Labels at the end of their axis (right or bottom). */ end?: string; }; /** Draws the lines. */ showLine?: boolean; /** Draws a point at each value. */ showPoint?: boolean; /** Fills the area between each line and `areaBase`. */ showArea?: boolean; /** The value the areas close at, usually 0. */ areaBase?: number; /** * How a line runs between its points: `true` smooths it with * `Interpolation.monotoneCubic`, `false` draws straight segments * (`Interpolation.none`), or pass an interpolation such as * `Interpolation.cardinal()`, `Interpolation.step()` or your own. */ lineSmooth?: boolean | LineInterpolation; /** Fills the grid area with a background (class `ct-grid-background`). */ showGridBackground?: boolean; /** * Stretches the X axis so the last value lands on the right edge, without * a last grid line. The last label may need chart padding to fit. */ fullWidth?: boolean; /** Reverses the labels, the order of the series and each series' values. */ reverseData?: boolean; /** Options per series, by series name: line options for one series. */ series?: Record, 'series'>>; } /** * {@link LineChartOptions} after the defaults are applied: the 1.x `LineChart` works with these. * * @deprecated The resolved options of the 1.x `LineChart`. Removed in 3.0. */ export type LineChartOptionsWithDefaults = RequiredKeys, RequiredKeys>, 'showLine' | 'showPoint' | 'areaBase' | 'lineSmooth' | 'chartPadding' | 'axisX' | 'axisY', 'classNames'>; /** * The payload of a line chart's 1.x `created` event. * * @deprecated Import it from `chartist/compat`, which turns on the 1.x events and plugins. Removed in 3.0. */ export type LineChartCreatedEvent = CreatedEvent; /** * The 1.x `draw` event of a line chart's point, one per value. The point is a * very short `line` element at `x`, `y` (CSS gives it a round cap). * * @deprecated Import it from `chartist/compat`, which turns on the 1.x events and plugins. Removed in 3.0. */ export interface PointDrawEvent extends DrawEvent { /** Always `'point'`. */ type: 'point'; /** The point's normalized value: `{ x, y }` numbers, or a number. */ value: NormalizedSeriesValue; /** The point's x, in px. */ x: number; /** The point's y, in px. */ y: number; } /** * The 1.x `draw` event of a line, one per series. `index` is the series' * index and `meta` the series' meta. * * @deprecated Import it from `chartist/compat`, which turns on the 1.x events and plugins. Removed in 3.0. */ export interface LineDrawEvent extends DrawEvent { /** Always `'line'`. */ type: 'line'; /** All normalized values of the series. */ values: NormalizedSeries; /** The line's path as drawn (a copy, safe to change). */ path: SvgPath; } /** * The 1.x `draw` event of an area (with `showArea`), one per series and * segment. `index` is the series' index and `meta` the series' meta. * * @deprecated Import it from `chartist/compat`, which turns on the 1.x events and plugins. Removed in 3.0. */ export interface AreaDrawEvent extends DrawEvent { /** Always `'area'`. */ type: 'area'; /** All normalized values of the series. */ values: NormalizedSeries; /** The area's path as drawn (a copy, safe to change). */ path: SvgPath; } /** * The 1.x events of a {@link LineChart} and their payloads, by event name. * * @deprecated The 1.x events of a `LineChart`. On `lineChart()`, the handle's `on()` knows its events. Removed in 3.0. */ export type LineChartEventsTypes = BaseChartEventsTypes; //#endregion //#region src/pipeline/phases.d.ts /** Options accepted by the pipeline (a chart config without listeners). */ interface PipelineOptions { /** The labels and series to draw. */ readonly data: ChartData; /** What to draw, in this order (later layers on top), e.g. `[axisGrid(), line()]`. */ readonly layers: readonly Layer[]; /** * The coordinate system the layers draw in: `cartesian` (the default) * for axes, `polar` for `pie()`. */ readonly coordinates?: Coordinates; /** * Space in px between the chart's edge and the drawing area: one number * for all sides, or some sides (the others keep the 1.x defaults). */ readonly padding?: number | Partial; /** Axes (see `cartesianAxes`); their offsets are reserved around the area. */ readonly axes?: CartesianAxes; /** * The chart's width: px as a number, or a CSS length such as `100%` or * `20rem`. Without it, `chart()` fills the container's width. */ readonly width?: number | string; /** * The chart's height: px as a number, or a CSS length such as `300px`. * Without it, `chart()` fills the container's height. */ readonly height?: number | string; /** Fixed drawing coordinates; sets the layout size and the root `viewBox`. */ readonly viewBox?: { readonly width: number; readonly height: number; }; /** Class names for the root svg, e.g. `ct-chart-line` for the 1.x line chart CSS. */ readonly className?: string; /** * Draws labels as HTML in `foreignObject` (1.x) or as SVG `text`. The * default depends on the renderer: `html` for the DOM, `svg` in * `toScene()`. */ readonly labels?: LabelMode; /** The preset that created the chart, if any (read by plugins). */ readonly preset?: ResolvedConfig['preset']; } //#endregion //#region src/responsive/responsive.d.ts /** * Responsive entries: `[condition, overrides]` pairs, merged in order when * their condition matches. A plain string is a window media query (1.x); a * `container()` condition is a CSS container query, evaluated with * `Element.matchContainer()` (native or the `match-container` polyfill). */ /** * A container query condition for a responsive entry, created with * {@link container}. * @experimental It rests on `Element.matchContainer()`, a draft standard * (w3c/csswg-drafts#6205), through a polyfill: it may still change in a * 2.x minor. */ interface ContainerCondition { /** Always `container`: tells the condition from a media query string. */ readonly type: 'container'; /** A `@container` condition, e.g. `(width < 400px)`. */ readonly query: string; } /** * When a responsive entry applies: a window media query string, such as * `(max-width: 640px)` (as in 1.x), or a {@link container} condition. * Media queries are matched in the window of the chart's container, so a * chart in an iframe follows the iframe's viewport. */ type ResponsiveCondition = string | ContainerCondition; /** * A responsive entry: a condition and the overrides that apply while it * matches, e.g. `['(max-width: 640px)', { showPoint: false }]`. Matching * entries apply in order, so later ones win. */ type ResponsiveEntry = readonly [ResponsiveCondition, T]; /** * Marks a responsive entry as a container query, evaluated against the * chart container or an ancestor with a CSS `container-type`. Needs * `Element.matchContainer()`; until browsers ship it, load the * `match-container` polyfill. Without it, Chartist warns once and ignores * container entries; in `toScene()`, they never match. * * Works in the responsive entries of `chart()` and of the presets. * * @param query The condition you'd write after `@container` in CSS * @example * ```ts * import 'match-container'; * import { container, lineChart } from 'chartist'; * * lineChart( * '#chart', * { * labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], * series: [[12, 9, 7, 8, 5]] * }, * { low: 0 }, * [ * [ * container('(width < 400px)'), * { * showPoint: false, * axisX: { labelTransform: value => String(value)[0] } * } * ] * ] * ); * ``` * @experimental It rests on `Element.matchContainer()`, a draft standard * (w3c/csswg-drafts#6205), through a polyfill: it may still change in a * 2.x minor. */ export declare function container(query: string): ContainerCondition; /** * Watches the conditions of a {@link ResponsiveSet}'s entries, as its * `watch()` returns it: which entries match, and when that changes. */ interface ResponsiveWatcher { /** Indexes of the matching entries, as of the last `check()`. */ readonly matching: readonly number[]; /** Re-reads all conditions; true if the matching set changed. */ check(): boolean; /** Stops watching: no more `onChange` calls, and no listeners left. */ stop(): void; } /** * Responsive entries for `chart()`, with the watcher that evaluates them. * Created by `responsive()`, so charts without responsive entries don't * bundle the watcher. */ interface ResponsiveSet { /** The entries as given to `responsive()`. */ readonly entries: readonly ResponsiveEntry[]; /** * Starts watching the entries' conditions; `chart()` calls it. Calls * `onChange` when the set of matching entries changes. * @param host The chart's container, for container conditions * @param onChange Called after the matching entries changed */ watch(host: Element | undefined, onChange: () => void): ResponsiveWatcher; } /** * Responsive overrides for `chart()`: `[condition, overrides]` entries with * a media query string or a `container()` condition. Matching overrides are * shallow-merged over the config in order, so later entries win and an * override replaces a whole option (e.g. all `layers`). * * When the matching entries change, the chart emits a `responsive` event * with the config before and after, and renders again. * * @param entries `[condition, overrides]` pairs; the overrides are a * partial config: padding, axes, layers, size and the like * @example * ```ts * import { * autoScaleAxis, * axisGrid, * axisLabels, * cartesianAxes, * chart, * line, * responsive, * stepAxis * } from 'chartist'; * * const labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']; * * chart('#chart', { * data: { labels, series: [[12, 9, 7, 8, 5]] }, * axes: cartesianAxes([ * { id: 'x', side: 'bottom', type: stepAxis(), ticks: labels }, * { id: 'y', side: 'left', type: autoScaleAxis(), low: 0 } * ]), * layers: [axisGrid(), line({ showArea: true }), axisLabels()], * responsive: responsive([ * [ * '(max-width: 640px)', * { * padding: 5, * layers: [axisGrid(), line({ showPoint: false }), axisLabels()] * } * ] * ]) * }); * ``` */ export declare function responsive(entries: readonly ResponsiveEntry[]): ResponsiveSet; //#endregion //#region src/chart/types.d.ts /** * The custom events a chart can emit, by name, with their payloads. The * core emits only `responsive`. A plugin that emits events of its own * declares them here (TypeScript merges your declaration into Chartist's), * so `on()`, `off()` and `emit()` check the names and payloads: * * ```ts * declare module 'chartist' { * interface ChartEvents { * 'legend:click': { readonly seriesIndex: number }; * } * } * ``` * * `chartist/compat` declares the 1.x events (`draw`, `created`, …). */ interface ChartEvents { /** * Responsive entries changed which overrides apply: the config before * and after (`chart()`), or the options before and after (presets). */ responsive: { readonly previousConfig: ChartConfig; readonly currentConfig: ChartConfig; } | { readonly previousOptions: unknown; readonly currentOptions: unknown; }; } /** * The name of a custom event: a key of {@link ChartEvents}. Plugins list * the names they emit in `provides`. */ type CustomEventName = keyof ChartEvents & string; /** * A plugin: a name and an `install` function that registers listeners on * the chart. Plugins go into `plugins`, in the config of {@link chart} or * the options of the presets. They install in order, so with two * listeners on the same event, the earlier plugin's runs first. * * For options, write a function that takes them and returns the plugin, or * read them from the second argument of `install` and pass the plugin * with {@link withOptions}. * * @example * ```ts * import { barChart, type ChartPlugin } from 'chartist'; * * // Bars at or above the limit get the class ct-over. * const threshold = (limit: number): ChartPlugin => ({ * name: 'threshold', * install(chart) { * chart.on('compose', current => { * if (current.role !== 'bar') { * return; * } * const { value } = current.ctx; * const y = * typeof value === 'number' * ? value * : value && 'y' in value * ? value.y * : undefined; * return y !== undefined && y >= limit * ? current.addClass('ct-over') * : undefined; * }); * } * }); * * barChart('#chart', { series: [[5, 4, 3, 7]] }, { plugins: [threshold(5)] }); * ``` */ interface ChartPlugin { /** Names the plugin. Prefix your custom events with it to keep them apart. */ readonly name: string; /** * The custom events this plugin emits with `chart.emit()`, each declared * in {@link ChartEvents}. They're known before any plugin installs, so * another plugin may listen to them. */ readonly provides?: readonly CustomEventName[]; /** * Sets the plugin up: runs once, before the first render, with the * chart's handle. Listeners registered here stay for every later render, * after updates and resizes too, and `off(name)` without a listener * leaves them alone: remove one with its reference. * * Return a function to undo what `install` set up outside the chart, * such as a listener on the document: `destroy()` calls it once, after * the chart's output is removed. `detach()` doesn't. * @param chart The chart's handle, to listen to events and emit them. * @param options The options of a `[plugin, options]` entry, if any. * @returns A cleanup function for `destroy()`, or anything else, which is * ignored (so `install: chart => chart.on(…)` stays valid). */ install(chart: ChartHandle, options?: TOptions): unknown; /** * Gives the keyframes of a node's update animation, for nodes that don't * move well number by number, such as a path the plugin draws. A * renderer that animates updates (`smilAnimations()` from * `chartist/live`) asks it once per update, never per frame, with the * progress points of the chart's easing: 0 is the previous node, 1 the * new one, and points beyond them come from an easing that overshoots. * Plugins are asked in their order, before the layer that drew the node; * the first one that returns keyframes wins. * * @example * ```ts * import type { ChartPlugin } from 'chartist'; * * // Turns the gauge needle the plugin draws (its angle in `ct:angle`), * // instead of morphing its path. * const needle: ChartPlugin = { * name: 'needle', * install() {}, * keyframes(previous, next, progress) { * if (!next.classes.includes('needle')) { * return undefined; * } * const from = Number(previous.attrs['ct:angle']); * const to = Number(next.attrs['ct:angle']); * return progress.map(p => ({ * transform: `rotate(${from + (to - from) * p} 100 100)` * })); * } * }; * ``` * @param previous The node in the previous scene * @param next The node in the new scene * @param progress The progress points to give attributes for * @returns One set of attributes per progress point, or nothing. */ keyframes?(previous: SceneNode, next: SceneNode, progress: readonly number[]): Keyframes | undefined; } /** * A plugin paired with its options, as {@link withOptions} creates it. * `install` receives the options as its second argument. */ type PluginWithOptions = readonly [ChartPlugin, TOptions]; /** * An entry of a chart's `plugins`: a plugin, or a plugin with its options. * Prefer {@link withOptions} (it checks the options) or a function that * returns a plugin over a bare `[plugin, options]` pair. A 1.x plugin (a * plain function) throws; convert it with `fromLegacyPlugin()` from * `chartist/compat`. */ type PluginEntry = ChartPlugin | PluginWithOptions; /** * The config of {@link chart}: the data, the layers that draw it and the * axes they draw on, plus size, padding, plugins and listeners. * * Without `axes`, layers draw into the whole chart area; the pie layer * needs `coordinates: 'polar'`. {@link toScene} takes the same config. */ interface ChartConfig extends PipelineOptions { /** * Plugins to install before the first render, in order: plugins, or * plugins with their options from {@link withOptions}. */ readonly plugins?: readonly PluginEntry[]; /** * Phase listeners by phase name (or `'*'` for all phases). They're * registered before the first render, so they see it too. */ readonly on?: PhaseListeners; /** Turns the scene into output; the DOM renderer by default. */ readonly renderer?: Renderer; /** * Overrides that apply while their condition matches, created with * `responsive([...])`: entries of a media query string or a * `container()` condition, and a partial config. The chart renders again * when the matching entries change. */ readonly responsive?: ResponsiveSet; } /** * The part of a {@link ChartConfig} that responsive entries can override: * everything but `responsive`, `plugins`, `on` and `renderer`. The * matching entries merge over the config in order, shallowly. */ type ChartOverrides = Partial>; /** * The handle {@link chart} returns: update or remove the chart, and listen * to its events. Plugins get the same handle in `install`. The methods * other than `destroy` and `emit` return the handle, so calls chain. */ interface ChartHandle { /** The element the chart renders into (undefined in `toScene`). */ readonly container?: Element; /** * Shallow-merges the changes into the config and renders again. Plugins * and listeners stay; `plugins` and `on` can't change. */ update(config: Partial>): this; /** * Stops reacting to container size changes (and media queries in * presets). The output and the listeners stay. */ detach(): this; /** Detaches, removes the output and clears all listeners. */ destroy(): void; /** * Emits a custom event (declared in {@link ChartEvents}), e.g. from a * plugin. Phase names are reserved: emitting one throws. */ emit(name: K, payload: ChartEvents[K]): void; /** * Listens to a phase event, which fires on every render. Listeners of * `resolve` to `scene` may return a new payload to change what's drawn; * `compose` listeners may return `null` to drop a node. */ on(name: K, listener: PhaseListener): this; /** Listens to every phase event, with the phase name and its payload. */ on(name: '*', listener: AllPhasesListener): this; /** Listens to a custom event, declared in {@link ChartEvents}. */ on(name: K, listener: (payload: ChartEvents[K]) => void): this; /** * Removes a phase listener, whoever added it. Without a listener, * removes the listeners of the phase added through `on` and the * config's `on`; plugins keep theirs. */ off(name: K, listener?: PhaseListener): this; /** * Removes a listener of all phases, or without a listener, those added * through `on`. */ off(name: '*', listener?: AllPhasesListener): this; /** * Removes a custom event listener, or without a listener, the event's * listeners added through `on`. */ off(name: K, listener?: (payload: ChartEvents[K]) => void): this; } /** * Pairs a plugin with its options for a chart's `plugins`, and checks the * options against the plugin's options type. `install` receives them as * its second argument. * * @example * ```ts * import { lineChart, withOptions, type ChartPlugin } from 'chartist'; * * const lastPoint: ChartPlugin<{ className: string }> = { * name: 'last-point', * install(chart, options) { * chart.on('compose', current => { * if (current.role !== 'series') { * return; * } * const last = current.children.at(-1); * return last && options * ? current.replace(last, last.addClass(options.className)) * : undefined; * }); * } * }; * * lineChart( * '#chart', * { series: [[1, 3, 2, 5]] }, * { plugins: [withOptions(lastPoint, { className: 'ct-last' })] } * ); * ``` */ export declare function withOptions(plugin: ChartPlugin, options: TOptions): PluginWithOptions; //#endregion //#region src/layers/line.d.ts /** * The line options you can set per series: in the `overrides` of * {@link line}, or the `series` option of `lineChart`. */ interface LineSeriesOptions { /** * How a line runs between its points: `true` smooths it with * `Interpolation.monotoneCubic`, `false` draws straight segments * (`Interpolation.none`), or pass an interpolation such as * `Interpolation.cardinal()`, `Interpolation.step()` or your own. */ readonly lineSmooth?: boolean | LineInterpolation; /** Draws a point at each value. */ readonly showPoint?: boolean; /** Draws the lines. */ readonly showLine?: boolean; /** Fills the area between each line and `areaBase`. */ readonly showArea?: boolean; /** * The value the areas close at, usually 0. It's kept within the Y axis * range. */ readonly areaBase?: number; } /** * The options of the {@link line} layer. Without them, it draws every * series as a smooth line with points and no area, on the first X and Y * axis. */ interface LineLayerOptions extends LineSeriesOptions { /** Series to draw, by index or name; default: all series. */ readonly series?: readonly (number | string)[]; /** The id of the X axis to draw on; default: the first X axis. */ readonly x?: string; /** The id of the Y axis to draw on; default: the first Y axis. */ readonly y?: string; /** * Point position on a step axis: `start` of each step (1.x) or its * `center`, where bars are centered. */ readonly align?: 'start' | 'center'; /** Option overrides per series name (the 1.x `series` option). */ readonly overrides?: Readonly>; /** * Draws the series in reverse order (1.x `reverseData`). Can't be * combined with `series`. */ readonly reverseData?: boolean; /** * Replaces the classes of what the layer draws: `series` (`ct-series`), * `line` (`ct-line`), `point` (`ct-point`) and `area` (`ct-area`). */ readonly classNames?: { readonly series?: string; readonly line?: string; readonly point?: string; readonly area?: string; }; } /** * Creates a layer that draws series as lines, with points and optional * areas, in the markup of the 1.x line chart (`g.ct-series` with * `path.ct-line`, `line.ct-point` and `path.ct-area`). It needs an X and a * Y axis, from {@link cartesianAxes}. * * @example * ```ts * import { * autoScaleAxis, * axisGrid, * axisLabels, * cartesianAxes, * chart, * line, * stepAxis * } from 'chartist'; * * const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']; * * chart('#chart', { * data: { * labels: days, * series: [ * { name: 'visits', data: [12, 9, 7, 8, 5] }, * { name: 'sales', data: [2, 1, 3.5, 7, 3] } * ] * }, * axes: cartesianAxes([ * { id: 'day', side: 'bottom', type: stepAxis(), ticks: days }, * { id: 'count', side: 'left', type: autoScaleAxis(), low: 0 } * ]), * layers: [ * axisGrid(), * line({ showArea: true, overrides: { sales: { showArea: false } } }), * axisLabels() * ] * }); * ``` */ export declare function line(options?: LineLayerOptions): Layer; //#endregion //#region src/scales/grid.d.ts /** The classes of an axis's grid lines and labels. */ interface AxisClassNames { /** Each grid line (`ct-grid`). */ readonly grid: string; /** Each label (`ct-label`). */ readonly label: string; /** Grid lines and labels of an X axis (`ct-horizontal`). */ readonly horizontal: string; /** Grid lines and labels of a Y axis (`ct-vertical`). */ readonly vertical: string; /** Labels of an axis at the top or left (`ct-start`). */ readonly start: string; /** Labels of an axis at the bottom or right (`ct-end`). */ readonly end: string; /** * Grid lines at an axis's `minorTicks`, next to the `grid` class * (`ct-grid-minor`). */ readonly gridMinor?: string; } //#endregion //#region src/presets/preset.d.ts /** * What a preset passes to plugins as `ResolvedConfig.preset`: its kind, the * current 1.x options and 1.x-style updates. */ interface PresetState { /** Which preset: `line`, `bar` or `pie`. */ readonly kind: TKind; /** * The current options: the given ones over the defaults, with the * matching responsive options applied. */ readonly options: TOptions; /** The current data. */ readonly data: TData; /** * Changes the data, the options or both and redraws, as 1.x `update()`: * the options extend the current ones, or with `override`, the defaults. */ update(data?: TData, options?: TOptions, override?: boolean): void; /** Stops the chart's responsive updates, as 1.x `detach()`. */ detach(): void; } /** * The handle `lineChart`, `barChart` and `pieChart` return: a * {@link ChartHandle} that also changes the chart's options. * `update({ data })` changes the preset's data too, so responsive changes * redraw with it. * * @example * ```ts * import { lineChart } from 'chartist'; * * const chart = lineChart('#chart', { series: [[1, 3, 2, 5]] }); * * // Areas from now on; the other options stay. * chart.setOptions({ showArea: true }); * ``` */ interface PresetHandle extends ChartHandle { /** * Changes the options and redraws: they extend the current options, or * with `{ replace: true }`, the defaults, dropping the options given * before. Matching responsive options still apply on top. `plugins`, * `on` and `renderer` can't change. Coming from 1.x, `setOptions(options)` is * `update(undefined, options, true)` and * `setOptions(options, { replace: true })` is `update(undefined, options)`. * @param options The options to change. * @param how `replace: true` starts from the defaults instead of the * current options. */ setOptions(options: Omit, how?: { readonly replace?: boolean; }): this; } /** Internal: a preset with 1.x-style data and option updates. */ interface PresetController { readonly handle: PresetHandle; /** Replaces the data (1.x `update(data)`); call `render()` after. */ setData(data: TData): void; /** 1.x option update: extends the defaults, or the current options. */ setOptions(options: TOptions, override?: boolean): void; render(): void; options(): TOptions; data(): TData; } /** 1.x axis options whose `type` may also be a v2 axis factory. */ type PresetAxisOptions = Omit & { /** A v2 axis factory or a 1.x axis class. */ readonly type?: AxisSetup['type']; }; /** * Extra layers of a preset chart, such as `band()` or the target and * trend lines of `@chartist-js/essentials`: they draw on the preset's * axes and get all series. * @example * ```ts * import { barChart, band } from 'chartist'; * * barChart( * '#chart', * { labels: ['Q1', 'Q2', 'Q3'], series: [[800, 1200, 950]] }, * { layers: { below: [band({ low: 800, high: 1200 })] } } * ); * ``` */ interface PresetLayers { /** Layers drawn above the grid and below the chart's series. */ readonly below?: readonly Layer[]; /** Layers drawn above the chart's series and below the axis labels. */ readonly above?: readonly Layer[]; } /** * Responsive options of presets: the 1.x media query pairs, plus container * conditions (`container()`). Matching entries extend the options in order. */ type PresetResponsiveOptions = readonly ResponsiveEntry[]; //#endregion //#region src/presets/lineChart.d.ts /** * Options of `lineChart`: the 1.x `LineChart` options; axis types may also * be v2 axis factories. */ type LineChartPresetOptions = Omit & { /** v2 plugins; convert 1.x plugins with `fromLegacyPlugin`. */ readonly plugins?: readonly PluginEntry[]; /** * Phase listeners by phase name (or `'*'` for all phases), as `on` in * the config of `chart()`. They're registered before the first render, * so they see it too. */ readonly on?: PhaseListeners; /** * Turns the scene into output, as `renderer` in the config of * `chart()`: the DOM renderer by default, or `liveDomRenderer()` from * `chartist/live` for a chart that changes in place on updates. It can't * change after the chart is created. */ readonly renderer?: Renderer; /** Extra layers below or above the chart's lines. */ readonly layers?: PresetLayers; /** Options per series name: only these five apply per series. */ readonly series?: Readonly>; /** Options of the X axis; its `type` may also be a v2 axis factory. */ readonly axisX?: PresetAxisOptions & Omit, 'type'>; /** Options of the Y axis; its `type` may also be a v2 axis factory. */ readonly axisY?: PresetAxisOptions & Omit, 'type'>; /** HTML (1.x) or SVG text labels; default: the renderer's mode. */ readonly labels?: LabelMode; }; /** What the line preset passes to plugins as `ResolvedConfig.preset`. */ type LinePresetState = PresetState; /** * Builds the chart config that `lineChart()` renders for the data and * options, without a container: the line layer with its axes, grid and labels. Pass it to `toScene()` to render * the preset chart with another renderer. Responsive options and the * inline size style of the root svg are left out; both need a container. * @example * ```ts * import { lineChartConfig } from 'chartist'; * import { renderToString, toScene } from 'chartist/server'; * * const config = lineChartConfig( * { labels: ['Mon', 'Tue', 'Wed'], series: [[5, 2, 4]] }, * { showArea: true } * ); * export const svg = renderToString( * toScene(config, { width: 600, height: 300 }) * ); * ``` */ export declare function lineChartConfig(data: LineChartData, options?: LineChartPresetOptions): ChartConfig; /** * Creates a line chart with the 1.x options and output, rendered * synchronously. Plugins must be v2 plugins; convert 1.x plugins with * `fromLegacyPlugin` from `chartist/compat`. */ export declare function lineChart(target: string | Element, data: LineChartData, options?: LineChartPresetOptions, responsiveOptions?: PresetResponsiveOptions): PresetHandle; //#endregion //#region src/charts/BarChart/BarChart.types.d.ts /** The data of a bar chart: series of values, and labels for the bar groups. */ export type BarChartData = Data; /** * The options of a bar chart (1.x `BarChart`, and `barChart`). * * @deprecated For `barChart()`, the options type is `BarChartPresetOptions`. Removed in 3.0. */ export interface BarChartOptions extends Options { /** * The class names of the chart's elements. Change them to style the * chart with your own CSS instead of Chartist's. */ classNames?: { /** The chart's SVG element. */ chart?: string; /** The chart's SVG element, with `horizontalBars`. */ horizontalBars?: string; /** Each axis label. */ label?: string; /** The group of an axis's labels. */ labelGroup?: string; /** The group of each series. */ series?: string; /** Each bar. */ bar?: string; /** Each grid line. */ grid?: string; /** The group of the grid lines. */ gridGroup?: string; /** The grid background (with `showGridBackground`). */ gridBackground?: string; /** Labels and grid lines of the vertical axis. */ vertical?: string; /** Labels and grid lines of the horizontal axis. */ horizontal?: string; /** Labels at the start of their axis (left or top). */ start?: string; /** Labels at the end of their axis (right or bottom). */ end?: string; }; /** The distance in px between the bars of a group (one bar per series). */ seriesBarDistance?: number; /** Stacks the bars of a group on each other; `stackMode` says how. */ stackBars?: boolean; /** * How stacked bars stack: `accumulate` adds up each group's values (the * value axis fits the totals), `accumulate-relative` stacks positive * values up and negative values down, and `true` draws every bar from * zero, overlapping. */ stackMode?: 'accumulate' | 'accumulate-relative' | boolean; /** * Draws horizontal bars. The axes swap: the Y axis shows the labels and * the X axis the values, so swap their options too. */ horizontalBars?: boolean; /** * Treats one flat array of values as one series per value, each in its * own color: a profile rather than values over time. */ distributeSeries?: boolean; /** Reverses the labels, the order of the series and each series' values. */ reverseData?: boolean; /** Fills the grid area with a background (class `ct-grid-background`). */ showGridBackground?: boolean; } /** * {@link BarChartOptions} after the defaults are applied: the 1.x `BarChart` works with these. * * @deprecated The resolved options of the 1.x `BarChart`. Removed in 3.0. */ export type BarChartOptionsWithDefaults = RequiredKeys, RequiredKeys>, 'referenceValue' | 'chartPadding' | 'seriesBarDistance' | 'stackMode' | 'axisX' | 'axisY', 'classNames'>; /** * The payload of a bar chart's 1.x `created` event. * * @deprecated Import it from `chartist/compat`, which turns on the 1.x events and plugins. Removed in 3.0. */ export type BarChartCreatedEvent = CreatedEvent; /** * The 1.x `draw` event of a bar, one per value. The bar is a `line` element * from its base (`x1`, `y1`) to its value (`x2`, `y2`). * * @deprecated Import it from `chartist/compat`, which turns on the 1.x events and plugins. Removed in 3.0. */ export interface BarDrawEvent extends DrawEvent { /** Always `'bar'`. */ type: 'bar'; /** The bar's normalized value: a number, or `{ x, y }` numbers. */ value: number | NormalizedMulti; /** The x of the bar's base, in px. */ x1: number; /** The y of the bar's base, in px. */ y1: number; /** The x of the bar's end (its value), in px. */ x2: number; /** The y of the bar's end (its value), in px. */ y2: number; } /** * The 1.x events of a {@link BarChart} and their payloads, by event name. * * @deprecated The 1.x events of a `BarChart`. On `barChart()`, the handle's `on()` knows its events. Removed in 3.0. */ export type BarChartEventsTypes = BaseChartEventsTypes; //#endregion //#region src/presets/barChart.d.ts /** * Options of `barChart`: the 1.x `BarChart` options; axis types may also be * v2 axis factories. */ type BarChartPresetOptions = Omit & { /** v2 plugins; convert 1.x plugins with `fromLegacyPlugin`. */ readonly plugins?: readonly PluginEntry[]; /** * Phase listeners by phase name (or `'*'` for all phases), as `on` in * the config of `chart()`. They're registered before the first render, * so they see it too. */ readonly on?: PhaseListeners; /** * Turns the scene into output, as `renderer` in the config of * `chart()`: the DOM renderer by default, or `liveDomRenderer()` from * `chartist/live` for a chart that changes in place on updates. It can't * change after the chart is created. */ readonly renderer?: Renderer; /** Extra layers below or above the chart's bars. */ readonly layers?: PresetLayers; /** * How stacked bars stack: `accumulate` (default), `accumulate-relative` * (positives up, negatives down), or `overlap` (also `true`): every bar * from zero. */ readonly stackMode?: 'accumulate' | 'accumulate-relative' | 'overlap' | boolean; /** Options of the X axis; its `type` may also be a v2 axis factory. */ readonly axisX?: PresetAxisOptions & Omit, 'type'>; /** Options of the Y axis; its `type` may also be a v2 axis factory. */ readonly axisY?: PresetAxisOptions & Omit, 'type'>; /** HTML (1.x) or SVG text labels; default: the renderer's mode. */ readonly labels?: LabelMode; }; /** What the bar preset passes to plugins as `ResolvedConfig.preset`. */ type BarPresetState = PresetState; /** * Builds the chart config that `barChart()` renders for the data and * 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 * the preset chart with another renderer. Responsive options and the * inline size style of the root svg are left out; both need a container. */ export declare function barChartConfig(data: BarChartData, options?: BarChartPresetOptions): ChartConfig; /** * Creates a bar chart with the 1.x options and output, rendered * synchronously. Plugins must be v2 plugins; convert 1.x plugins with * `fromLegacyPlugin` from `chartist/compat`. */ export declare function barChart(target: string | Element, data: BarChartData, options?: BarChartPresetOptions, responsiveOptions?: PresetResponsiveOptions): PresetHandle; //#endregion //#region src/charts/PieChart/PieChart.types.d.ts /** The data of a pie chart: one value per slice, and labels for the slices. */ export type PieChartData = Data; /** Which way pie labels anchor: see `labelDirection` in {@link PieChartOptions}. */ export type LabelDirection = 'implode' | 'neutral' | 'explode'; /** The `text-anchor` of a pie label: `'start'`, `'middle'` or `'end'`. */ export type AnchorPosition = 'start' | 'middle' | 'end'; /** Where pie labels go: see `labelPosition` in {@link PieChartOptions}. */ export type RadialLabelPosition = 'inside' | 'center' | 'outside'; /** A point in px, such as the center of a pie. */ export interface Dot { /** The x, in px. */ x: number; /** The y, in px. */ y: number; } /** * The options of a pie or donut chart (1.x `PieChart`, and `pieChart`). * * @deprecated For `pieChart()`, the options type is `PieChartPresetOptions`. Removed in 3.0. */ export interface PieChartOptions extends Omit { /** * The class names of the chart's elements. Change them to style the * chart with your own CSS instead of Chartist's. */ classNames?: { /** The chart's SVG element, for pies. */ chartPie?: string; /** The chart's SVG element, for donuts. */ chartDonut?: string; /** The group of each series. */ series?: string; /** Each pie slice. */ slicePie?: string; /** Each donut slice. */ sliceDonut?: string; /** Each axis label. */ label?: string; }; /** Where the first slice starts, in degrees clockwise from the top. */ startAngle?: number; /** * The value a full circle stands for. With a total above the sum of the * values, the pie stays open, as for a gauge. */ total?: number; /** Draws a donut: rings instead of filled slices. */ donut?: boolean; /** * The width of a donut's ring: px as a number, or a share of the radius as * a string (`'30%'`). Without it, the stylesheet sets the width * (`--ct-donut-width`, 60px by default), and in the browser the ring is * laid out for the width the stylesheet gives a slice. Without a DOM * (`renderToString()`), it's laid out for 60 px. */ donutWidth?: number | string; /** Draws a label for each slice. */ showLabel?: boolean; /** * Moves the labels away from the center (positive) or toward it * (negative), in px. */ labelOffset?: number; /** * Where labels go: `inside` (halfway out on a pie, on the middle of a * donut's ring, plus `labelOffset`), `outside` (at the outer edge) or * `center` (in the middle; move them with `labelOffset`). */ labelPosition?: RadialLabelPosition; /** * Turns each slice's label (or value) and index into the text to show. * Return `null` or `undefined` to leave a label out. Wins over * `labelInterpolationFnc` when both are set. */ labelTransform?(value: Label, index: number): Label | null | undefined; /** * The 1.x name of `labelTransform`, which wins when both are set. * * @deprecated Use `labelTransform`. Removed in 3.0. */ labelInterpolationFnc?(value: Label, index: number): Label | null | undefined; /** * Which way labels anchor: `neutral`, `explode` (away from the center, * for labels outside the pie) or `implode` (toward it). */ labelDirection?: LabelDirection; /** Leaves out the slices and labels of empty values. */ ignoreEmptyValues?: boolean; /** * Moves labels apart so they don't overlap, using this offset in px. The * overlap is judged by the length of the drawn label text. 0 leaves them * where they are. */ preventOverlappingLabelOffset?: number; } /** * {@link PieChartOptions} after the defaults are applied: the 1.x `PieChart` works with these. * * @deprecated The resolved options of the 1.x `PieChart`. Removed in 3.0. */ export type PieChartOptionsWithDefaults = RequiredKeys; /** * The payload of a pie chart's 1.x `created` event: as for other charts, without axes. * * @deprecated Import it from `chartist/compat`, which turns on the 1.x events and plugins. Removed in 3.0. */ export type PieChartCreatedEvent = Omit, 'axisX' | 'axisY'>; /** * The 1.x `draw` event of a pie or donut slice, one per value. `index` is * the slice's index and `series` its value as given in the data. * * @deprecated Import it from `chartist/compat`, which turns on the 1.x events and plugins. Removed in 3.0. */ export interface SliceDrawEvent extends Omit { /** Always `'slice'`. */ type: 'slice'; /** The slice's value. */ value: NormalizedSeriesValue; /** The value of the full circle: the sum of all values, or the `total` option. */ totalDataSum: number; /** The slice's path as drawn (a copy, safe to change). */ path: SvgPath; /** The center of the pie, in px. */ center: Dot; /** The radius of the pie, in px. */ radius: number; /** Where the slice starts, in degrees clockwise from the top. */ startAngle: number; /** Where the slice ends, in degrees clockwise from the top. */ endAngle: number; } /** * The 1.x `draw` event of a pie slice's label. `index` is the slice's * index; the label is a `text` element anchored at `x`, `y`. * * @deprecated Import it from `chartist/compat`, which turns on the 1.x events and plugins. Removed in 3.0. */ export interface SliceLabelDrawEvent extends Omit { /** Always `'label'`. */ type: 'label'; /** The label as shown, after `labelTransform`. */ text: string; /** The x the label is anchored at, in px. */ x: number; /** The y the label is anchored at, in px. */ y: number; } /** * The 1.x events of a {@link PieChart} and their payloads, by event name. * * @deprecated The 1.x events of a `PieChart`. On `pieChart()`, the handle's `on()` knows its events. Removed in 3.0. */ export type PieChartEventsTypes = BaseChartEventsTypes; //#endregion //#region src/presets/pieChart.d.ts /** * Options of `pieChart`: the 1.x `PieChart` options, with v2 plugins and * phase listeners. */ type PieChartPresetOptions = Omit & { /** v2 plugins; convert 1.x plugins with `fromLegacyPlugin`. */ readonly plugins?: readonly PluginEntry[]; /** * Phase listeners by phase name (or `'*'` for all phases), as `on` in * the config of `chart()`. They're registered before the first render, * so they see it too. */ readonly on?: PhaseListeners; /** * Turns the scene into output, as `renderer` in the config of * `chart()`: the DOM renderer by default, or `liveDomRenderer()` from * `chartist/live` for a chart that changes in place on updates. It can't * change after the chart is created. */ readonly renderer?: Renderer; /** Extra layers below or above the pie's slices, in polar coordinates. */ readonly layers?: PresetLayers; }; /** What the pie preset passes to plugins as `ResolvedConfig.preset`. */ type PiePresetState = PresetState; /** * Builds the chart config that `pieChart()` renders for the data and * options, without a container: the pie layer with its labels. Pass it to `toScene()` to render * the preset chart with another renderer. Responsive options and the * inline size style of the root svg are left out; both need a container. */ export declare function pieChartConfig(data: PieChartData, options?: PieChartPresetOptions): ChartConfig; /** * Creates a pie or donut chart with the 1.x options and output, rendered * synchronously. Plugins must be v2 plugins; convert 1.x plugins with * `fromLegacyPlugin` from `chartist/compat`. */ export declare function pieChart(target: string | Element, data: PieChartData, options?: PieChartPresetOptions, responsiveOptions?: PresetResponsiveOptions): PresetHandle; //#endregion //#region src/pipeline/types.d.ts /** * The coordinate system a chart draws in: `cartesian` places values on X * and Y axes (lines, bars), `polar` around a center (pies and donuts). */ type Coordinates = 'cartesian' | 'polar'; /** Chart data as passed to `chart()` or `toScene()`. */ interface ChartData { /** The labels of the values, e.g. for the X axis or the slices. */ readonly labels?: readonly (string | number | Date)[]; /** * The series: arrays of values, series objects with `data`, or, for a * pie, one value per slice. */ readonly series: readonly unknown[]; } /** One series after the `prepare` phase. */ interface PreparedSeries { /** The series' `name`, from a series object. */ readonly name?: string; /** The series' `className`, from a series object. */ readonly className?: string; /** The series' `meta`, from a series object. */ readonly meta?: unknown; /** The series' values, as given. */ readonly values: readonly unknown[]; } /** * The data after the `prepare` phase: every series as a * {@link PreparedSeries}, whether it was given as an array or an object. */ interface PreparedData { /** The labels as given, or an empty array. */ readonly labels: readonly (string | number | Date)[]; /** The series, each with its `values`. */ readonly series: readonly PreparedSeries[]; /** The input was a flat series (e.g. pie or distributed bar data). */ readonly flat?: boolean; } /** * The drawing area inside the padding (and the axes), in px in the SVG. * `y1` is the bottom edge, as in 1.x. */ interface Area { /** The left edge. */ readonly x1: number; /** The bottom edge. */ readonly y1: number; /** The right edge. */ readonly x2: number; /** The top edge. */ readonly y2: number; /** The area's width in px. */ readonly width: number; /** The area's height in px. */ readonly height: number; } /** * The payload of the `layout` phase: the chart's size and the drawing area * inside its padding and axes. A `layout` listener can return a changed * layout, e.g. to make room for a legend. */ interface Layout { /** The chart's width in px (at least the left and right padding). */ readonly width: number; /** The chart's height in px (at least the top and bottom padding). */ readonly height: number; /** The padding around the drawing area, in px. */ readonly padding: ChartPadding; /** Where the layers draw, inside the padding and the axes. */ readonly area: Area; /** * The room layers reserved outside the drawing area with * {@link Layer.inset}, in px per side; `padding` includes it. Absent when * no layer reserved room. */ readonly inset?: ChartPadding; } /** Data normalized for axes: multi values (`{ x, y }`), padded labels. */ interface NormalizedChartData { /** The labels, padded with empty strings to the longest series. */ readonly labels: readonly Label[]; /** * The series' values as numbers, `{ x, y }` values or holes, each * series padded with holes to the longest one. */ readonly series: readonly NormalizedSeries[]; } /** * What a layer's `compose` gets: the data it draws, the area to draw in, * the axes and ways to measure text and styles. */ interface LayerContext { /** * The prepared data; only the layer's series when it selects some, all * of them when it selects none (`series: []`). */ readonly data: PreparedData; /** The drawing area, in px in the SVG. */ readonly area: Area; /** The chart's padding, in px. */ readonly padding: ChartPadding; /** The layer's index in the chart's `layers`; part of its nodes' keys. */ readonly layerIndex: number; /** The chart's coordinate system. */ readonly coordinates: Coordinates; /** * Measures text with the renderer's metrics (in the browser, with the * page's fonts and the chart's classes), for layers that lay out labels. */ readonly measureText: MeasureText; /** * Reads computed styles with the renderer (in the browser, with the * page's CSS and the chart's classes), for layout that depends on the * stylesheet, such as a donut's ring width. Absent without a DOM. */ readonly measureStyle?: MeasureStyle; /** Axes created after `layout`, when the chart has axes. */ readonly axes: ChartAxes; /** The data as the axes see it, when the chart has axes. */ readonly normalized?: NormalizedChartData; /** * Chart-wide index of each series in `data` (a layer may select a subset * of the series). Absent when `data` has all series. */ readonly seriesIndexes?: readonly number[]; /** How label layers draw labels: chart option, else the renderer's. */ readonly labels: LabelMode; /** * The boxes the layer reserved with {@link Layer.inset}, one per side, * in px in the SVG: just outside the axes on that side (and the boxes of * layers listed before it), as long as the drawing area. Absent when the * layer reserved no room. */ readonly insetArea?: Partial>; } /** * What a layer's `inset` gets: the chart's size and padding, its axes, the * layer's series and ways to measure text and styles, so it can size the * room it needs. */ interface InsetContext { /** The chart's width in px. */ readonly width: number; /** The chart's height in px. */ readonly height: number; /** The chart's padding option, in px, without any reserved room. */ readonly padding: ChartPadding; /** * The prepared data; only the layer's series when it selects some, all * of them when it selects none (`series: []`). */ readonly data: PreparedData; /** The chart's axis definitions, with their ids, sides and offsets; empty without axes. */ readonly axes: readonly AxisDefinition[]; /** The chart's coordinate system. */ readonly coordinates: Coordinates; /** The layer's index in the chart's `layers`. */ readonly layerIndex: number; /** How label layers draw labels: chart option, else the renderer's. */ readonly labels: LabelMode; /** * Measures text with the renderer's metrics (in the browser, with the * page's fonts and the chart's classes). */ readonly measureText: MeasureText; /** Reads computed styles with the renderer. Absent without a DOM. */ readonly measureStyle?: MeasureStyle; } /** * What a layer's `extent` gets: its series as the axes see them, and the * ids of the axes it draws on. */ interface ExtentContext { /** * The layer's series, normalized as for the axes (`{ x, y }` values or * holes); only the layer's series when it selects some, all of them * when it selects none (`series: []`). */ readonly normalized: NormalizedChartData; /** The ids of the X and Y axis the layer draws on. */ readonly axes: { readonly x?: string; readonly y?: string; }; /** * The transforms of the X and Y axis the layer draws on, for axes that * declare one (see {@link AxisTransform}), such as a log axis. */ readonly transforms?: { readonly x?: AxisTransform; readonly y?: AxisTransform; }; } /** * A layer renders series into the chart area. Built-in and custom layers * use the same contract: the "Custom layers" guide explains each field * and how to write and share a layer. * @see https://chartist.dev/docs/custom-layers/ */ interface Layer { /** Name used in error messages, e.g. `line`. */ readonly type: string; /** * The kind of chart the layer draws, when `type` doesn't say it: a * {@link chart} without `className` gets `ct-chart-bar` if a layer is a * `bar`, else `ct-chart-pie` or `ct-chart-donut` for a `pie` or `donut`, * else `ct-chart-line`. Without it, `type` counts. */ readonly chartType?: string; /** Coordinate systems the layer can draw in. */ readonly coordinates: readonly Coordinates[]; /** Axis ids to draw on; default: the first X and the first Y axis. */ readonly axes?: { readonly x?: string; readonly y?: string; }; /** * Series to draw, by index or name; default: all series. The axes fit * the series of the layers drawn on them. A layer that draws none, such * as a reference line or a legend, sets `[]`: it doesn't shape any axis, * and its context still has every series to read. */ readonly series?: readonly (number | string)[]; /** * Reports the range of values the layer needs on its axes beyond the * values themselves, by axis id, such as the sums of stacked bars. Scale * axes include it in the range they fit to the data (an axis's own `low` * and `high` still win); on an axis several layers report a range for, * the axis covers them all. Runs before the axes are created, on every * layout. * * @example * ```ts * import type { Layer } from 'chartist'; * * // Keeps 0 to 100 on the layer's Y axis, e.g. for a target line. * const withTarget = (base: Layer): Layer => ({ * ...base, * extent: ({ axes }) => (axes.y ? { [axes.y]: { low: 0, high: 100 } } : {}) * }); * ``` */ extent?(context: ExtentContext): Readonly>; /** * Reserves room outside the drawing area, in px per side, for something * the layer draws next to the chart, such as an axis title or a legend. * The room is added to the chart's padding, so the area shrinks and the * axes stay next to it; the layer draws in the boxes its context gets as * `insetArea`. Layers that reserve room on the same side stack outward in * the order of `layers`. Runs on every layout, before the `layout` * listeners, so the room can depend on the chart's size. The "Custom * layers" guide shows a layer that uses it. * * @example * ```ts * import { node, type Layer } from 'chartist'; * * // A source note below the chart, in a line of its own. * const source = (text: string): Layer => ({ * type: 'source', * coordinates: ['cartesian'], * series: [], * inset: ({ measureText }) => ({ bottom: measureText(text).height + 4 }), * compose: ({ insetArea }) => { * const box = insetArea?.bottom; * return box * ? [node('text', { x: box.x1, y: box.y1 }, 'ct-source').text(text)] * : []; * } * }); * ``` */ inset?(context: InsetContext): Partial | undefined; /** * Draws the layer: returns its top-level nodes, usually one `series` * group per series. The pipeline keys their data nodes and passes every * node with a role through the `compose` listeners. */ compose(context: LayerContext): readonly SceneNode[]; /** * Refines what the layers drew: once every layer has composed, called * for each node with a role, from all layers (children before their * parents), before the `compose` events, so listeners see the result. * Return a changed node, such as one with a class added, or `undefined` * to leave it. The node keeps its key and its children whatever you * return, and refining can't drop a node. With several refining layers, * a node passes through them in the order of `layers`. Leave it out when * the layer only draws its own nodes: charts without a refining layer * skip this step. * * @param node The node, possibly refined by layers listed earlier. * @param context The context this layer's `compose` got. * * @example * ```ts * import type { Layer } from 'chartist'; * * // Marks the points of every layer that are above a limit. * const markAbove = (limit: number): Layer => ({ * type: 'markAbove', * coordinates: ['cartesian'], * series: [], * compose: () => [], * refine: node => * node.role === 'point' && * typeof node.ctx.value === 'object' && * (node.ctx.value.y ?? -Infinity) > limit * ? node.addClass('ct-above') * : undefined * }); * ``` */ refine?(node: SceneNode, context: LayerContext): SceneNode | undefined; /** * Draws from where the other layers drew, such as a label at each bar's * end. Runs once the nodes of every layer without `annotate` are * composed, keyed, refined and through the `compose` listeners, so a bar * a listener dropped isn't there and a moved one is where it ends up. * It gets those finished top-level nodes in the order of `layers`, not * the nodes of other annotating layers. The nodes it returns are keyed, * refined and emitted like `compose`'s, after them, at the layer's place * in `layers`; their `compose` events come after the other layers'. Find * the nodes you need with `findAll()`. * * @param drawn The finished top-level nodes of the other layers. * @param context The context this layer's `compose` got. * * @example * ```ts * import { findAll, getMultiValue, node, type Layer } from 'chartist'; * * // Writes each bar's value past its end. * const barValues: Layer = { * type: 'barValues', * coordinates: ['cartesian'], * series: [], * compose: () => [], * annotate: drawn => * drawn.flatMap(top => * findAll(top, { role: 'bar' }).map(bar => * node('text', { x: bar.ctx.x2, y: bar.ctx.y2 - 4 }, 'ct-bar-value') * .text(String(getMultiValue(bar.ctx.value, 'y'))) * ) * ) * }; * ``` */ annotate?(drawn: readonly SceneNode[], context: LayerContext): SceneNode[]; /** * Gives the keyframes of an update animation for one of the layer's * nodes, for attributes that don't move well number by number, such as * an arc that should turn around its center. A renderer that animates * updates (`smilAnimations()` from `chartist/live`) asks once per update, * never per frame, with the progress points of the chart's easing: 0 is * the previous node, 1 the new one, and points beyond them come from an * easing that overshoots. Plugins with `keyframes` are asked first. * Leave it out to animate the layer's nodes number by number. * * @param previous The node in the previous scene * @param next The node in the new scene * @param context The context this layer's `compose` got for `next` * @param progress The progress points to give attributes for * @returns One set of attributes per progress point, or nothing. * * @example * ```ts * import type { Layer } from 'chartist'; * * // A gauge whose needle (its angle in `ct:angle`) turns on an update. * declare const gauge: Layer; * const turningGauge: Layer = { * ...gauge, * keyframes: (previous, next, context, progress) => { * const from = Number(previous.attrs['ct:angle']); * const to = Number(next.attrs['ct:angle']); * const { x1, y1, width, height } = context.area; * return progress.map(p => ({ * transform: `rotate(${from + (to - from) * p} ${x1 + width / 2} ${y1 - height / 2})` * })); * } * }; * ``` */ keyframes?(previous: SceneNode, next: SceneNode, context: LayerContext, progress: readonly number[]): Keyframes | undefined; } /** Options after the `resolve` phase: defaults applied, listeners removed. */ interface ResolvedConfig { /** The chart's data, as given. */ readonly data: ChartData; /** The layers, drawn in this order. */ readonly layers: readonly Layer[]; /** The coordinate system; `cartesian` unless the config says otherwise. */ readonly coordinates: Coordinates; /** The padding in px on every side, the 1.x defaults filled in. */ readonly padding: ChartPadding; /** The chart's axes, from `cartesianAxes()`, if it has any. */ readonly axes?: CartesianAxes; /** The root svg's `width` from the config, e.g. `100%` or `600`. */ readonly width?: number | string; /** The root svg's `height` from the config, e.g. `300px`. */ readonly height?: number | string; /** Fixed drawing coordinates for the root svg's `viewBox`, in px. */ readonly viewBox?: { readonly width: number; readonly height: number; }; /** Class names of the root svg, e.g. `ct-chart-line`. */ readonly className?: string; /** Label mode for all label layers; else the renderer decides. */ readonly labels?: LabelMode; /** * The preset that created the chart, if any: its kind, options and data. * Check `kind` to narrow it, e.g. `config.preset?.kind === 'line'`. */ readonly preset?: LinePresetState | BarPresetState | PiePresetState; } /** * The payloads of the phase events, by phase, in the order the phases run. * Listen with `on` in the config of `chart()`, `chart.on()` or a plugin. A * listener can return a new payload to change the phase (see * {@link PhaseResult}); later phases build on the change. * * When the container resizes, the chart runs again from `layout`, so * `resolve` and `prepare` listeners aren't called. * * @example * ```ts * import { barChart, type ChartPlugin } from 'chartist'; * * // Bars at or above the limit get the class ct-over. * const threshold = (limit: number): ChartPlugin => ({ * name: 'threshold', * install(chart) { * chart.on('compose', current => { * if (current.role !== 'bar') { * return; * } * // A number, { x, y } (with an X scale axis) or a hole. * const { value } = current.ctx; * const y = * typeof value === 'number' * ? value * : value && 'y' in value * ? value.y * : undefined; * return y !== undefined && y >= limit * ? current.addClass('ct-over') * : undefined; * }); * } * }); * * barChart( * '#chart', * { labels: ['Q1', 'Q2', 'Q3', 'Q4'], series: [[5, 4, 3, 7]] }, * { plugins: [threshold(5)] } * ); * ``` */ interface PhaseEvents { /** The config with defaults applied: padding, coordinates, layers, axes. */ resolve: { readonly config: ResolvedConfig; }; /** The data, each series as `{ values, name, className, meta }`. */ prepare: { readonly data: PreparedData; }; /** The chart's size and the drawing area inside the padding and axes. */ layout: Layout; /** * Each node with a role that a layer draws, children before their * parents: series, lines, areas, points, bars, slices, grid lines and * labels. Return a changed node, a new one, or `null` to drop it. */ compose: SceneNode; /** The whole scene, its root the `svg`. */ scene: { readonly scene: SceneNode; }; /** * The renderer has applied the scene: created, replaced or changed the * output in place. `output` is what it returned. */ render: RenderEvent; /** * The output is in the page; touch elements only here. Return a function * to undo what the listener did: it runs before the next render changes * the output, and on `destroy()`. */ mount: RenderEvent & { /** * The rendered element of a scene node, if the renderer has one; for a * node of a `remove` change, the element just taken out of the page. */ readonly elementOf: (node: SceneNode) => Element | undefined; /** * The timing of the update animation the renderer started, if it * animated this render. Animate what your plugin draws with it, so it * moves in step with the chart. */ readonly animation?: UpdateAnimation; }; } /** * What the `render` and `mount` events carry about a render: the scene, the * renderer's output, why the chart rendered and what changed. */ interface RenderEvent { /** The scene the renderer applied. */ readonly scene: SceneNode; /** What the renderer returned. */ readonly output: RenderOutput; /** Why the chart rendered, e.g. `update` or `resize`. */ readonly cause: RenderCause; /** The previous render's scene; absent on the first render and on `hydrate`. */ readonly previous?: SceneNode; /** * What the render did to the output, in document order. When the * renderer changed its output in place (`liveDomRenderer()` from * `chartist/live`), these are its changes; otherwise every node of the * previous scene is removed and every node of the new one added. A * `hydrate` render has an `add` entry for every node, as a first render. */ readonly changes: readonly SceneChange[]; /** * On a `hydrate` render: how many attributes, classes and texts of the * server's markup differed from the scene the browser built, and were * set. 0 when the server and the browser drew the same data and options; * more means they didn't. Styles, which the markup leaves out, don't * count. */ readonly hydration?: { readonly repaired: number; }; } /** The name of a pipeline phase, such as `compose`: a key of {@link PhaseEvents}. */ type PhaseName = keyof PhaseEvents; /** * What a phase listener returns: a new payload to transform the phase, or * nothing to keep it. `compose` listeners may return `null` to drop the * node. `render` listeners return nothing (they observe). A function a * `mount` listener returns is its cleanup; other values are ignored, so * `() => chart.detach()` stays a valid listener. */ type PhaseResult = K extends 'render' ? void : K extends 'mount' ? unknown : PhaseEvents[K] | (K extends 'compose' ? null : never) | undefined | void; /** * A listener of one phase: gets the phase's payload and may return a new * one (see {@link PhaseResult}). Listeners of a phase run in the order they * were added, each with the previous one's result. */ type PhaseListener = (payload: PhaseEvents[K]) => PhaseResult; /** * A listener of every phase (`'*'`): gets the phase name and its final * payload, after the phase's own listeners. It only observes. */ type AllPhasesListener = (name: PhaseName, payload: unknown) => void; /** * Phase listeners by phase name, as the `on` option of `chart()` takes * them. They're registered before the first render. */ type PhaseListeners = { readonly [K in PhaseName]?: PhaseListener; } & { /** Listens to every phase, with the phase name as first argument. */ readonly '*'?: AllPhasesListener; }; //#endregion //#region src/scales/axis.d.ts /** Which way an axis runs: `x` (horizontal) or `y` (vertical). */ type AxisDimension = 'x' | 'y'; /** Where an axis sits: `top`/`bottom` are X axes, `left`/`right` Y axes. */ type AxisSide = 'top' | 'bottom' | 'left' | 'right'; /** * What an {@link AxisFactory} gets to create an axis: its direction, the * data, the chart area and the axis options. */ interface AxisContext { /** Which way the axis runs: `x` or `y`, from its side. */ readonly dimension: AxisDimension; /** * Normalized multi-value series (`{ x, y }` values): the series bound to * the axis, or all of them. */ readonly series: NormalizedSeries[]; /** Normalized labels, padded to the longest series. */ readonly labels: readonly Label[]; /** The chart area in px, with the offsets of all axes reserved. */ readonly area: Area; /** The options of the axis definition, without `id`, `side` and `type`. */ readonly options: AxisOptions; /** * The range the layers drawn on the axis need beyond their values, such * as the sums of stacked bars (see {@link Layer.extent}). Scale axes * include it in the range they fit to the data; their own `low` and * `high` still win. */ readonly extent?: AxisExtent; } /** * A range of values on an axis, from `low` to `high`: what a layer reports * in {@link Layer.extent}. */ interface AxisExtent { /** The lowest value. */ readonly low: number; /** The highest value. */ readonly high: number; } /** * How an axis that isn't linear in its values maps them: the axis is * linear in `forward(value)`, as a log axis is in the logarithm of its * values. Layers that fit lines, such as `trendLine()` from * `@chartist-js/essentials`, fit them in that space, so the lines are * straight on the axis. * * @example * ```ts * import type { AxisTransform } from 'chartist'; * * // A base 10 log scale. * const log10: AxisTransform = { * forward: value => Math.log10(value), * inverse: value => 10 ** value * }; * ``` */ interface AxisTransform { /** * The value in the space the axis is linear in; `NaN` or an infinite * number for a value the axis has no place for (zero on a log axis). */ forward(value: number): number; /** The value of a number in that space: the inverse of `forward`. */ inverse(value: number): number; } /** * A positioned axis: ticks, range and projection into px along the axis. * An {@link AxisFactory} creates it once the chart area is known; layers * read it to place what they draw. */ interface ScaleAxis { /** Which way the axis runs: `x` or `y`. */ readonly dimension: AxisDimension; /** The axis type, e.g. `step`, `autoScale`, `fixedScale`. */ readonly kind: string; /** Step axes: whether the last tick sits at the axis end. */ readonly stretch?: boolean; /** Step axes: the distance between two ticks in px. */ readonly step?: number; /** * The values at which grid lines and labels are drawn: labels on a step * axis, numbers on a scale. */ readonly ticks: readonly Label[]; /** * Values between the ticks that get a grid line without a label, such * as 20 to 90 between 10 and 100 on a log axis. The grid draws them * beneath the other grid lines, with the class `ct-grid-minor`. */ readonly minorTicks?: readonly number[]; /** * How the axis maps its values, when it isn't linear in them; see * {@link AxisTransform}. */ readonly transform?: AxisTransform; /** * The values at the axis start (`min`) and end (`max`). Step axes have * none. */ readonly range?: { readonly min: number; readonly max: number; }; /** Axis length in px. */ readonly length: number; /** * Places a value on the axis: the distance in px from the axis start * (left, or bottom for y). Step axes place by `index` instead. */ project(value: NormalizedSeriesPrimitiveValue | Label, index?: number, series?: NormalizedSeries): number; } /** * An axis type: creates the axis once the chart area and data are known. * {@link stepAxis}, {@link autoScaleAxis} and {@link fixedScaleAxis} return * one; write your own for a scale they don't cover. It goes in the `type` * of an axis. */ interface AxisFactory { /** * The axis type, e.g. `step`. The axis it creates has the same `kind`; * the line and bar layers center on `step` axes. */ readonly kind: string; /** * How the axes of this type map their values, when they aren't linear * in them. Declared on the factory too, so layers know it before the * axes exist (see {@link ExtentContext}); the axis it creates carries * the same one. */ readonly transform?: AxisTransform; /** * Creates the axis for a chart area and data. Runs on every layout, so * after resizes too. */ create(context: AxisContext): ScaleAxis; } /** A 1.x axis class (or a custom subclass of the 1.x `Axis`). */ type LegacyAxisClass = abstract new (...args: any[]) => unknown; /** * An axis's setup: an axis type plus the 1.x axis options (`offset`, * `low`, `high`, `ticks`, `showGrid`, …). */ interface AxisSetup extends Omit { /** A v2 axis factory, or a 1.x axis class. */ readonly type: AxisFactory | LegacyAxisClass; } /** * An axis of a composed chart, in the list form of {@link cartesianAxes}: * an id that layers bind to, a side, a type and the 1.x axis options. */ interface AxisDefinition extends AxisSetup { /** * Names the axis, for the `x` and `y` of layers and the `axes` of * {@link axisGrid} and {@link axisLabels}. Ids must be unique. */ readonly id: string; /** * Where the axis sits: `bottom` or `top` makes an X axis, `left` or * `right` a Y axis. Axes on the same side stack outward in list order. */ readonly side: AxisSide; } /** * The config of {@link cartesianAxes}: one X and one Y axis in the 1.x * form, or a list of axes, plus how the data is read. */ interface AxesConfig { /** * The X axis in the 1.x form: at the bottom, or the top with * `position: 'start'`. Its `offset` defaults to 30 px. */ readonly x?: AxisSetup; /** * The Y axis in the 1.x form: on the left, or the right with * `position: 'end'`. Its `offset` defaults to 40 px. */ readonly y?: AxisSetup; /** The axis list form; used instead of `x`/`y`. */ readonly axes?: readonly AxisDefinition[]; /** Reverse labels and series before projecting (1.x `reverseData`). */ readonly reverseData?: boolean; /** * How values are normalized (1.x `normalizeData`): `multi` is `true` for * `{ x, y }` values, or the dimension single values go to; `distributed` * turns a flat series into one series per value. */ readonly normalize?: { readonly multi?: true | AxisDimension; readonly distributed?: boolean; }; } /** * A created axis with its place in the chart: what the axis layers draw, * and what a layer finds in `axes.all`. */ interface PlacedScaleAxis extends ScaleAxis { /** The axis id: from its definition, or `x` and `y` in the 1.x form. */ readonly id: string; /** The side the axis sits on. */ readonly side: AxisSide; /** Distance in px from the chart area to this axis's band (stacking). */ readonly inset: number; /** The axis options (offset, labels, grid), without the type. */ readonly options: Omit; } /** The axes of a laid-out chart. */ interface ChartAxes { /** The X axis (for layers: the bound one; for the chart: the first). */ readonly x?: ScaleAxis; /** The Y axis (for layers: the bound one; for the chart: the first). */ readonly y?: ScaleAxis; /** All axes of the chart, in declaration order. */ readonly all?: readonly PlacedScaleAxis[]; } /** * Axes for a chart's `axes` option, created by {@link cartesianAxes}. The * pipeline asks them for the chart area and, after `layout`, to create the * axes. Charts without axes don't bundle any of this. */ interface CartesianAxes { /** The config the axes were created from, with the default offsets filled in. */ readonly config: AxesConfig; /** The chart area with the axis offsets reserved. */ area(width: number, height: number, padding: ChartPadding): { width: number; height: number; area: Area; }; /** The axis definitions, in declaration order. */ readonly definitions: readonly AxisDefinition[]; /** * Each layer's axis ids and series selection, checked against the data. * Without it, every layer draws all series on the first X and Y axis. */ bind?(layers: readonly Layer[], data: PreparedData): LayerBinding[]; /** * The axes for the final chart area, and the data as they see it. With * `bindings`, each axis's range comes only from the series bound to it. * With `layers`, it also covers the extents they report (see * {@link Layer.extent}). */ create(data: PreparedData, area: Area, bindings?: readonly LayerBinding[], layers?: readonly Layer[]): { axes: ChartAxes; normalized: NormalizedChartData; }; } /** How a layer is bound: its axis ids and series indexes. */ interface LayerBinding { /** The id of the X axis the layer draws on. */ readonly x?: string; /** The id of the Y axis the layer draws on. */ readonly y?: string; /** Selected series indexes; undefined means all. */ readonly series?: readonly number[]; } //#endregion //#region src/scene/roles.d.ts /** A position in the chart's SVG, in px from its top left corner. */ interface Point { /** Px from the left edge of the SVG. */ readonly x: number; /** Px from the top edge of the SVG. */ readonly y: number; } /** * The context of nodes that belong to no series, such as grid lines. It * says so, so `ctx.seriesIndex` reads as `number | undefined` on any node. */ interface NoSeries { /** Always absent: the node belongs to no series. */ readonly seriesIndex?: undefined; /** Always absent: the node stands for no value. */ readonly valueIndex?: undefined; } /** * What every node of a series knows about its series: series groups, * points, lines, areas, bars and slices. */ interface SeriesContext { /** The series as given in the data (array, or object with `data`). */ readonly series: unknown; /** The series' index in the chart's data, across layers. */ readonly seriesIndex: number; /** The series' `meta`, if it's a series object with one. */ readonly meta: unknown; } /** * The context of a `series` node: the `g` element that holds one series' * lines, areas, points, bars or slice. It knows its series, but no value. */ interface SeriesGroupContext extends SeriesContext { /** Always absent: the group stands for the whole series. */ readonly valueIndex?: undefined; } /** What a node of one value knows about it: its index and its value. */ interface ValueContext { /** The value's index in its series, from 0. */ readonly valueIndex: number; /** The normalized value: a number, `{ x, y }` numbers, or a hole. */ readonly value: NormalizedSeriesValue; } /** * The context of a `point` node: one value of a line chart's series, and * where it's drawn. `x` and `y` are the point's position in px in the SVG. * Line values are normalized to `{ x, y }` (or a hole), so the value is * `ctx.value.y`. */ interface PointContext extends SeriesContext, ValueContext, Point {} /** * The context of a `bar` node: one value of a bar chart's series, and the * line it's drawn as, from the base (`x1`, `y1`) to the value (`x2`, * `y2`), in px in the SVG. A stacked bar starts where the one below it * ends. Bars are clipped to the chart area. */ interface BarContext extends SeriesContext, ValueContext { /** Whether the bar is horizontal (`horizontalBars`). */ readonly horizontal: boolean; /** * Whether the bar is a segment of a stack: stacked with `accumulate` or * `accumulate-relative`, so its base is where the previous segment * ends. False for `overlap`, whose bars all start at zero. */ readonly stacked: boolean; /** The X of the bar's base, in px. */ readonly x1: number; /** The Y of the bar's base, in px. */ readonly y1: number; /** The X of the bar's end (the value), in px. */ readonly x2: number; /** The Y of the bar's end (the value), in px. */ readonly y2: number; } /** * The context of a `line` or `area` node: the path of a whole series of a * line chart, with all its values. */ interface PathContext extends SeriesContext { /** Always absent: the path stands for the whole series. */ readonly valueIndex?: undefined; /** All values of the series. */ readonly values: NormalizedSeries; /** The path as drawn (a copy, safe to change). */ readonly path: SvgPath; /** * The interpolation the path was drawn with (`lineSmooth`), so the path * can be drawn again through other points, e.g. for update animations. */ readonly smoothing: LineInterpolation; } /** * The context of a `slice` node: a pie or donut slice, which is one series * with one value, and its geometry in px and degrees. */ interface SliceContext extends SeriesContext { /** The slice's value. */ readonly value: number; /** Always 0: a slice's series has one value. */ readonly valueIndex: 0; /** Same as `seriesIndex`, as in 1.x draw events. */ readonly index: number; /** The sum of all slices (or the `total` option). */ readonly totalDataSum: number; /** The slice's outline as drawn (a copy, safe to change). */ readonly path: SvgPath; /** The center of the pie, in px in the SVG. */ readonly center: Point; /** The pie's radius in px (for a donut, to the middle of its ring). */ readonly radius: number; /** Where the slice starts, in degrees clockwise from the top. */ readonly startAngle: number; /** Where the slice ends, in degrees clockwise from the top. */ readonly endAngle: number; } /** * The context of a `grid` node: the grid line of an axis at one tick, * across the chart area. Its ends are in px in the SVG. */ interface GridContext extends NoSeries { /** The axis the line belongs to; `axis.dimension` is `x` or `y`. */ readonly axis: ScaleAxis; /** The tick's index, in `axis.minorTicks` for a minor grid line. */ readonly index: number; /** `true` for a grid line at one of the axis's `minorTicks`. */ readonly minor?: true; /** The X of the line's start, in px. */ readonly x1: number; /** The Y of the line's start, in px. */ readonly y1: number; /** The X of the line's end, in px. */ readonly x2: number; /** The Y of the line's end, in px. */ readonly y2: number; } /** * The context of an axis `label` node: the label of an axis at one tick, * and the box it's laid out in, in px in the SVG. */ interface AxisLabelContext extends NoSeries { /** `axis` for axis labels; check it to tell them from pie labels. */ readonly kind: 'axis'; /** The axis the label belongs to; `axis.dimension` is `x` or `y`. */ readonly axis: ScaleAxis; /** The tick's index. */ readonly index: number; /** The label after `labelInterpolationFnc`. */ readonly text: Label; /** The left edge of the label's box, in px. */ readonly x: number; /** The top edge of the label's box, in px. */ readonly y: number; /** * The width of the label's box in px. On the X axis, the space to the * next tick. */ readonly width: number; /** * The height of the label's box in px. On the Y axis, the space to the * next tick. */ readonly height: number; } /** * The context of a pie `label` node: a slice's label on a pie or donut. * `x` and `y` are where the label is anchored, in px in the SVG. */ interface PieLabelContext extends SeriesContext, Point { /** `pie` for slice labels; check it to tell them from axis labels. */ readonly kind: 'pie'; /** Always 0, as for the slice. */ readonly valueIndex: 0; /** Same as `seriesIndex`, as in 1.x draw events. */ readonly index: number; /** The label as drawn. */ readonly text: string; } /** * An edge of a band: a constant value, the edge's own values (`undefined` * for a hole), or the chart-wide index of the series it follows. */ type BandEdge = { readonly value: number; } | { readonly values: readonly (number | undefined)[]; } | { readonly seriesIndex: number; }; /** * The context of a `band` node: one filled piece of a `band()` layer * (the band breaks at holes), and the edges it was drawn from. */ interface BandContext extends NoSeries { /** The low edge, when the band has edges. */ readonly low?: BandEdge; /** The high edge, when the band has edges. */ readonly high?: BandEdge; /** * The chart-wide indexes of the series whose minimum and maximum the * band covers, when it's drawn from a group. */ readonly series?: readonly number[]; /** The piece's outline as drawn (a copy, safe to change). */ readonly path: SvgPath; /** The interpolation the edges were drawn with (`lineSmooth`). */ readonly smoothing: LineInterpolation; } /** The attributes of a target label's SVG `text` element. */ interface TextAttrs { /** The X of the anchor, in px. */ readonly x: number; /** The Y of the text's baseline, in px. */ readonly y: number; /** `start` or `end`: which end of the text sits at the anchor. */ readonly 'text-anchor': 'start' | 'end'; } /** * The attributes of a `line` element: points, bars and grid lines. A point * is a line of 0.01 px, which the CSS draws as a dot with a round cap. */ interface LineAttrs { /** The X of the line's start, in px. */ readonly x1: number; /** The Y of the line's start, in px. */ readonly y1: number; /** The X of the line's end, in px. */ readonly x2: number; /** The Y of the line's end, in px. */ readonly y2: number; /** The value as written to the output, for points and bars. */ readonly 'ct:value'?: string | number; /** The value's `meta`, serialized, for points and bars that have one. */ readonly 'ct:meta'?: string; } /** The attributes of a `path` element: lines, areas and slices. */ interface PathAttrs { /** The path data, as in SVG's `d` attribute. */ readonly d: string; /** The value as written to the output, for slices. */ readonly 'ct:value'?: string | number; /** The series' `meta`, serialized, for slices that have one. */ readonly 'ct:meta'?: string; } /** The attributes of a series' `g` element. */ interface SeriesAttrs { /** The series' `name`, if it has one. */ readonly 'ct:series-name'?: string; /** The series' `meta`, serialized, if it has one (line and bar charts). */ readonly 'ct:meta'?: string; } /** The attributes of a `rect` element: the grid background. */ interface RectAttrs { /** The left edge, in px. */ readonly x: number; /** The top edge, in px. */ readonly y: number; /** The width in px. */ readonly width: number; /** The height in px. */ readonly height: number; } /** * The roles of scene nodes, and for each its data context (`ctx`) and * attributes (`attrs`). Checking `node.role` narrows a {@link SceneNode} to * its role, so `ctx` has that role's fields. * * The built-in layers and axes use the roles below; the class names are * their defaults. A plugin that adds nodes with a role of its own declares * it here with TypeScript's module augmentation; {@link node} and * {@link findAll} then accept it, and its `compose` listeners see it. * * @example * ```ts * import { node, type ChartPlugin } from 'chartist'; * * declare module 'chartist' { * interface NodeRoles { * marker: { * ctx: { readonly seriesIndex: number; readonly label: string }; * attrs: { readonly cx: number; readonly cy: number }; * }; * } * } * * // A marker on the last point of each series. * export const markers: ChartPlugin = { * name: 'markers', * install(chart) { * chart.on('compose', current => { * if (current.role !== 'series') { * return; * } * const last = current.children.at(-1); * if (last?.role !== 'point') { * return; * } * const { x, y, seriesIndex } = last.ctx; * return current.append( * node('circle', { cx: x, cy: y, r: 6 }, 'ct-marker', { * role: 'marker', * ctx: { seriesIndex, label: 'last' } * }) * ); * }); * } * }; * ``` */ interface NodeRoles { /** A value of a line chart: a `line` of 0.01 px (class `ct-point`). */ point: { ctx: PointContext; attrs: LineAttrs; }; /** A value of a bar chart: a `line` (class `ct-bar`). */ bar: { ctx: BarContext; attrs: LineAttrs; }; /** A series' line in a line chart: a `path` (class `ct-line`). */ line: { ctx: PathContext; attrs: PathAttrs; }; /** A series' filled area in a line chart: a `path` (class `ct-area`). */ area: { ctx: PathContext; attrs: PathAttrs; }; /** * A pie or donut slice: a `path` (class `ct-slice-pie` or * `ct-slice-donut`). */ slice: { ctx: SliceContext; attrs: PathAttrs; }; /** The `g` element that holds a series' nodes (class `ct-series`). */ series: { ctx: SeriesGroupContext; attrs: SeriesAttrs; }; /** A grid line of an axis at a tick: a `line` (class `ct-grid`). */ grid: { ctx: GridContext; attrs: LineAttrs; }; /** The `rect` behind the chart area (class `ct-grid-background`). */ gridBackground: { ctx: NoSeries; attrs: RectAttrs; }; /** * An axis label (a `foreignObject` with a `span`, or SVG `text`) or a * pie label (SVG `text`). Check `ctx.kind` to tell them apart. */ label: { ctx: AxisLabelContext | PieLabelContext; attrs: object; }; /** A filled piece of a `band()` layer: a `path` (class `ct-band-area`). */ band: { ctx: BandContext; attrs: PathAttrs; }; } /** A role name, such as `point` or `bar`: a key of {@link NodeRoles}. */ type NodeRole = keyof NodeRoles; //#endregion //#region src/scene/node.d.ts /** * The value of a node attribute. Numbers are written as they are, e.g. * `x1="12.5"`. */ type AttrValue = string | number; /** * Data attached to a node without a role, e.g. by a plugin. Never rendered. * Any fields are allowed; the ones below have a meaning to Chartist. */ interface NodeContext { /** * The index of the series the node belongs to. With it, the node gets a * `key` and {@link findAll} can find it by series. */ readonly seriesIndex?: number; /** The index of the value in its series the node stands for. */ readonly valueIndex?: number; /** The value the node stands for. */ readonly value?: unknown; /** The `meta` of the value or series, as given in the data. */ readonly meta?: unknown; /** Any other data you want to keep with the node. */ readonly [key: string]: unknown; } /** * What a node means, next to how it looks: its key, role and data * context. None of it is rendered. */ interface NodeMeta { /** A stable id, e.g. `0/1/3` (layer, series, value). */ readonly key?: string; /** What the node draws, e.g. `point` or `bar`: a key of {@link NodeRoles}. */ readonly role?: NodeRole; /** The node's data: what its role declares, or anything for plain nodes. */ readonly ctx?: object; } /** The fields every node has, whatever its role. */ interface SceneNodeFields { /** SVG element name, e.g. `g`, `path`, `line`. */ readonly name: string; /** * The element's attributes, without `class`. Names with a `ct:` prefix * (`ct:value`, `ct:meta`) are written in the Chartist namespace. */ readonly attrs: Readonly>; /** The element's class names, each once, in the order they were added. */ readonly classes: readonly string[]; /** The child nodes, in document order. */ readonly children: readonly SceneNode[]; /** Text content, set with `text()`. */ readonly content?: string; /** * A stable id that survives updates. The pipeline keys data nodes that * have none: `layer/series/value` for a value's node (e.g. `0/1/3`), * `layer/series` for a series' node. */ readonly key?: string; } /** * The builder methods of every node. Each returns a changed copy of the * same type and leaves the node it's called on as it was. */ interface SceneNodeMethods { /** Sets attributes; `undefined` or `null` removes one. */ attr(attributes: Record): this; /** Adds space-separated class names that aren't present yet. */ addClass(names: string): this; /** Removes space-separated class names. */ removeClass(names: string): this; /** Adds a child at the end, or at the start with `insertFirst`. */ append(child: SceneNode, insertFirst?: boolean): this; /** Removes a direct child (by identity). */ remove(child: SceneNode): this; /** Replaces a direct child (by identity). */ replace(child: SceneNode, next: SceneNode): this; /** Sets the text content. */ text(content: string): this; /** Removes all children and text content. */ empty(): this; } /** * A node of a role, such as `RoleNode<'point'>`: its context and * attributes are the ones {@link NodeRoles} declares for that role. * {@link findAll} with a `role` returns these. */ type RoleNode = SceneNodeFields & SceneNodeMethods & { /** What the node draws, e.g. `point`. */ readonly role: R; /** * The node's data, as its role declares it. `seriesIndex` and * `valueIndex` read as `number | undefined` on any node, declared or * not. */ readonly ctx: NodeRoles[R]['ctx'] & { readonly seriesIndex?: number; readonly valueIndex?: number; }; /** * The element's attributes, typed as the built-in layers set them; * `attr()` can change them. */ readonly attrs: Readonly> & NodeRoles[R]['attrs']; }; /** A node without a role: groups, decorations, anything a plugin adds. */ type PlainNode = SceneNodeFields & SceneNodeMethods & { /** Always absent: plain nodes have no role. */ readonly role?: undefined; /** Data you attach to the node, if any. */ readonly ctx?: NodeContext; }; /** * A scene node: a node of one of the roles in {@link NodeRoles}, or a plain * one. Check `role` to narrow it, e.g. `if (node.role === 'point') node.ctx.x`. * * Nodes are immutable: the builder methods ({@link SceneNodeMethods}) return * a new node. The `compose` and `scene` phase events pass nodes to your * listeners, and the renderers turn them into SVG. */ type SceneNode = { [R in NodeRole]: RoleNode; }[NodeRole] | PlainNode; /** * What {@link node} takes as `meta` for a node of role `R`: the role, a key, * and the role's context (required when the role declares fields). */ type RoleMeta = { /** The node's role, e.g. `point`. */ readonly role: R; /** A stable id; the pipeline sets one for data nodes that have none. */ readonly key?: string; } & (object extends NodeRoles[R]['ctx'] ? { readonly ctx?: NodeRoles[R]['ctx']; } : { readonly ctx: NodeRoles[R]['ctx']; }); /** * Creates a scene node: an SVG element with attributes and classes, and, * for a node with a role, its data context. Use it in `compose` listeners * and custom layers to add or replace elements. With a `role` in `meta`, * the node is typed as that role's node and the context is checked. * * @param name SVG element name, e.g. `circle`, `g` or `text` * @param attributes Attributes; `undefined` and `null` values are skipped * @param className Space-separated class names * @param meta Role, data context and key of the node * @returns A new node without children * @example * ```ts * import { lineChart, node } from 'chartist'; * * // Circles instead of the line chart's points. * lineChart( * '#chart', * { series: [[1, 3, 2, 4]] }, * { * plugins: [ * { * name: 'circles', * install(chart) { * chart.on('compose', current => { * if (current.role !== 'point') { * return; * } * const { x, y } = current.ctx; * return node('circle', { cx: x, cy: y, r: 5 }, 'ct-circle', { * role: 'point', * ctx: current.ctx, * key: current.key * }); * }); * } * } * ] * } * ); * ``` */ export declare function node(name: string, attributes: Record, className: string, meta: RoleMeta): RoleNode; export declare function node(name: string, attributes?: Record, className?: string, meta?: { readonly key?: string; readonly ctx?: NodeContext; }): PlainNode; //#endregion //#region src/scales/svgLabels.d.ts /** * How an SVG text label sits in its label box, as set in the `align` * option of {@link axisLabels}. */ interface LabelAlign { /** Aligns the text to the box's left (`start`), center or right (`end`). */ readonly horizontal: 'start' | 'middle' | 'end'; /** Aligns the lines of text to the box's top, middle or bottom. */ readonly vertical: 'top' | 'middle' | 'bottom'; } //#endregion //#region src/core/types.d.ts /** Space in px between the chart's edges and its drawing area, per side. */ export interface ChartPadding { /** Space above the drawing area, in px. */ top: number; /** Space right of the drawing area, in px. */ right: number; /** Space below the drawing area, in px. */ bottom: number; /** Space left of the drawing area, in px. */ left: number; } /** * The drawing area of a 1.x chart in px: `x1`, `y1` is its bottom left * corner and `x2`, `y2` its top right (SVG y grows downward, so `y1` is the * larger one). */ export interface ChartRect { /** The left edge of the drawing area, in px. */ x1: number; /** The right edge of the drawing area, in px. */ x2: number; /** The bottom edge of the drawing area, in px. */ y1: number; /** The top edge of the drawing area, in px. */ y2: number; /** The chart padding on each side, in px. */ padding: ChartPadding; /** The width of the drawing area (`x2 - x1`), in px. */ width(): number; /** The height of the drawing area (`y1 - y2`), in px. */ height(): number; } /** * A 1.x plugin: a function that gets the chart object (and its options) * and registers listeners with `chart.on('draw', …)`. It runs with the * `compat` plugin from `chartist/compat`, whose `fromLegacyPlugin()` also * turns it into a v2 plugin. * * @deprecated Import it from `chartist/compat`, which turns on the 1.x events and plugins. Removed in 3.0. */ export type Plugin = (chart: any, options?: any) => void; /** * Anything you attach to a series or value as `meta`, such as a tooltip * text. Chartist doesn't read it: it hands it back in events and writes it * to the `ct:meta` attribute. */ export type Meta = any; /** The size of an SVG `viewBox`. */ export interface ViewBox { /** The viewBox width, in SVG units. */ width: number; /** The viewBox height, in SVG units. */ height: number; } /** * The options all 1.x charts share: size, value range, padding, axes, class * names and plugins. {@link LineChartOptions}, {@link BarChartOptions} and * {@link PieChartOptions} build on them. * * @deprecated The base options of the 1.x chart classes. Use the options type of the chart function. Removed in 3.0. */ export interface Options { /** * The chart's width: px as a number, or a CSS length such as `'100%'`. * Without it, the chart takes the width of its container. */ width?: number | string; /** * The chart's height: px as a number, or a CSS length such as `'300px'`. * Without it, the chart takes the height of its container. */ height?: number | string; /** * The lowest value the value axis shows, instead of the data's lowest. * Values below it are drawn outside the drawing area. */ low?: number; /** * The highest value the value axis shows, instead of the data's highest. * Values above it are drawn outside the drawing area. */ high?: number; /** * A value the value axis always includes, such as 0, so it shows even * when all values are above or below it. Bar charts use 0. */ referenceValue?: number; /** * Space in px between the chart's edges and its drawing area (labels sit * in it): one number for every side, or an object with some sides. */ chartPadding?: number | Partial; /** Options of the X axis. */ axisX?: TXAxisOptions; /** Options of the Y axis. */ axisY?: TYAxisOptions; /** * The class names of the chart's elements, to style a chart with your * own classes instead of Chartist's. */ classNames?: Record; /** * 1.x plugin functions (they run with the compat plugin) and v2 plugins * such as `compat`. */ plugins?: (Plugin | [Plugin, any] | { readonly name: string; install(chart: any, options?: any): void; })[]; /** * A `viewBox` for the SVG, so the drawing scales with its box instead of * being drawn for its size. Text scales too: adjust it with responsive * options. */ viewBox?: ViewBox; } /** The options of one axis of a line or bar chart. */ export interface AxisOptions { /** * The axis type: `StepAxis` (one step per label), `AutoScaleAxis` (a * scale fitted to the values) or `FixedScaleAxis` (fixed ticks). */ type?: AxisType; /** The lowest value this axis shows, instead of the data's lowest. */ low?: number; /** The highest value this axis shows, instead of the data's highest. */ high?: number; /** A value this axis always includes, such as 0. */ referenceValue?: number; /** Room in px for the axis labels, between the drawing area and the chart's edge. */ offset?: number; /** * Where the labels go: `start` (left or top) or `end` (right or * bottom). */ position?: 'start' | 'end'; /** Moves the labels by `x` and `y` px from where they'd go. */ labelOffset?: { x: number; y: number; }; /** Draws the axis labels. */ showLabel?: boolean; /** * Aligns this axis's SVG text labels in their box, over the `align` of * {@link axisLabels}. HTML labels ignore it (align them with CSS). */ labelAlign?: Partial; /** Draws the grid lines of the axis. */ showGrid?: boolean; /** * Draws a grid line at the end of a step axis. Off by default. Requires * `showGrid`, and does not add a label or move any ticks. * * Use it on a line chart's X axis to close the grid with `fullWidth` off. * If `fullWidth: true` already puts a grid line at the edge, Chartist * skips the extra line. */ showClosingGridLine?: boolean; /** * Turns each label (and its index) into the text to show. Return `null` * or `undefined` to leave a label out. Wins over `labelInterpolationFnc` * when both are set. */ labelTransform?(value: Label, index: number): Label | null | undefined; /** * The 1.x name of {@link AxisOptions.labelTransform}, which wins when * both are set. * * @deprecated Use `labelTransform`. Removed in 3.0. */ labelInterpolationFnc?(value: Label, index: number): Label | null | undefined; /** * The minimum space in px between two grid lines of a scale: the scale * takes fewer, larger steps to keep it. */ scaleMinSpace?: number; /** Only whole numbers on the scale. */ onlyInteger?: boolean; /** * The ticks: the labels of a step axis, or the values of a fixed scale * axis. */ ticks?: Label[]; /** * Step axis: spreads the ticks over the whole axis, so the last one lands * on its end (line charts with `fullWidth` set it). */ stretch?: boolean; /** * Fixed scale axis without `ticks`: the number of equal steps between * its low and high, with a tick at each end. */ divisor?: number; /** * The value range of a scale as `{ high, low }`, instead of the one * computed from the data. */ highLow?: { high: number; low: number; }; } /** * {@link Options} after the defaults are applied: the axes and class names are set. * * @deprecated The resolved options of the 1.x chart classes. Removed in 3.0. */ export type OptionsWithDefaults = RequiredKeys, RequiredKeys>, 'axisX' | 'axisY' | 'classNames'>; /** * The 1.x responsive options: `[mediaQuery, options]` pairs, applied over * the chart's options while the media query matches. * * @deprecated For the chart functions, the type is `PresetResponsiveOptions`. Removed in 3.0. */ export type ResponsiveOptions = [string, T][]; /** The scale {@link getBounds} computes for an axis: its range and steps. */ export interface Bounds { /** The highest value to show. */ high: number; /** The lowest value to show. */ low: number; /** `high - low`. */ valueRange: number; /** The order of magnitude of the value range. */ oom: number; /** The distance between two ticks. */ step: number; /** The first tick: `low` rounded down to a step. */ min: number; /** The last tick: `high` rounded up to a step. */ max: number; /** `max - min`. */ range: number; /** The number of steps between `min` and `max`. */ numberOfSteps: number; /** The tick values, from `min` to `max`. */ values: number[]; } /** A run of points without holes, as {@link splitIntoSegments} returns it. */ export interface Segment { /** The points' coordinates in px, as `[x1, y1, x2, y2, …]`. */ pathCoordinates: number[]; /** The value of each point, in the same order. */ valueData: SegmentData[]; } /** A point's value, its index in the series and its meta. */ export interface SegmentData { /** The normalized value. */ value: NormalizedSeriesValue; /** The value's index in its series. */ valueIndex: number; /** The value's `meta`, if it has one. */ meta?: Meta; } /** An axis dimension: `'x'` or `'y'`. */ export type AxisName = 'x' | 'y'; /** * A value with coordinates: `{ x, y }`, or only `x` or `y`. Line charts * draw `{ x, y }` values on two scale axes (scatter plots). */ export type Multi = { x: number | string | Date | null; y: number | string | Date | null; } | { x: number | string | Date | null; } | { y: number | string | Date | null; }; /** A {@link Multi} value after normalizing: its coordinates as numbers. */ export type NormalizedMulti = { x: number; y: number; } | { x: number; } | { y: number; }; /** A label of an axis step or a pie slice. */ export type Label = string | number | Date; /** * Every shape `series` can take: a {@link FlatSeries} (pies, distributed * bars), or a list of {@link Series} arrays and {@link SeriesObject}s. */ export type AllSeriesTypes = FlatSeries | (Series | SeriesObject)[]; /** * Chart data: the series, and labels for the positions of their values (or * for the slices of a pie). */ export interface Data { /** * One label per value position: the steps of the X axis in line and bar * charts, the slices in pie charts. */ labels?: Label[] | undefined; /** * The values: an array per series (or a series object with a name, class * name and meta), or one flat array for pies and distributed bars. */ series: T; } /** * A series as an array of values: `[5, 2, 4]`. Use a {@link SeriesObject} * to give it a name, class name or meta. */ export type Series = SeriesValue[]; /** * A series with a name, class name or meta: * `{ name: 'Sales', data: [5, 2, 4] }`. */ export interface SeriesObject { /** * The series' name. Line charts look up per-series options in `series` * by it. */ name?: string; /** A class name for the series' group, instead of `ct-series-a`, `-b`, … */ className?: string; /** Anything to attach to the series, handed back in events. */ meta?: Meta; /** The series' values. */ data: SeriesValue[]; } /** A value of a series: a plain value, or `{ value, meta }`. */ export type SeriesValue = SeriesObjectValue | T; /** * A plain value of a series: a number (numeric strings are read as * numbers), a {@link Multi} `{ x, y }`, or `null` or `undefined` for a hole. */ export type SeriesPrimitiveValue = number | string | boolean | Date | Multi | null | undefined; /** A value with meta: `{ value: 5, meta: 'Tuesday' }`. */ export interface SeriesObjectValue { /** Anything to attach to the value, handed back in events. */ meta?: Meta; /** The value. */ value: T; } /** * One flat array of values, one per slice or bar: the series of a pie * chart, or of a bar chart with `distributeSeries`. */ export type FlatSeries = FlatSeriesValue[]; /** * A value of a {@link FlatSeries}: a plain value, `{ value, meta }`, or a * {@link FlatSeriesObjectValue} with a name and class name for its slice. */ export type FlatSeriesValue = SeriesValue | FlatSeriesObjectValue; /** * A plain value of a {@link FlatSeries}: a number (numeric strings are read * as numbers), or `null` or `undefined` for a hole. */ export type FlatSeriesPrimitiveValue = number | string | null | undefined; /** * A value of a flat series that is its own series, such as a pie slice: * `{ value: 20, name: 'Rent', className: 'rent' }`. */ export interface FlatSeriesObjectValue { /** The name of the value's series. */ name?: string; /** A class name for the value's series group, such as a slice's. */ className?: string; /** Anything to attach to the value, handed back in events. */ meta?: Meta; /** The value. */ value: T; } /** * Every shape a normalized `series` can take: a * {@link NormalizedFlatSeries} or a list of {@link NormalizedSeries}. */ export type AllNormalizedSeriesTypes = NormalizedFlatSeries | NormalizedSeries[]; /** * Chart data after {@link normalizeData}: labels filled in, and every * series an array of numbers, `{ x, y }` numbers or holes. */ export interface NormalizedData extends Data { /** One label per value position, empty strings where none was given. */ labels: Label[]; /** The normalized series. */ series: T; } /** A series after normalizing: its values without meta or series object. */ export type NormalizedSeries = NormalizedSeriesValue[]; /** A normalized value: a number, `{ x, y }` numbers, or `undefined` for a hole. */ export type NormalizedSeriesValue = NormalizedSeriesPrimitiveValue; /** A normalized value: a number, `{ x, y }` numbers, or `undefined` for a hole. */ export type NormalizedSeriesPrimitiveValue = number | NormalizedMulti | undefined; /** A {@link FlatSeries} after normalizing: one number per slice or bar. */ export type NormalizedFlatSeries = number[]; /** * The payload of the 1.x `created` event, emitted once a chart is drawn: * its SVG, drawing area, axes and options. * * @deprecated Import it from `chartist/compat`, which turns on the 1.x events and plugins. Removed in 3.0. */ export interface CreatedEvent { /** The drawing area, in px. */ chartRect: ChartRect; /** The X axis, a 1.x {@link Axis} object. */ axisX: Axis; /** The Y axis, a 1.x {@link Axis} object. */ axisY: Axis; /** The chart's SVG element, wrapped in {@link Svg}. */ svg: Svg; /** The options the chart was drawn with, defaults and responsive options applied. */ options: TOptions; } /** * The fields every 1.x `draw` event shares. A `draw` listener gets one per * element drawn; check `type` to tell them apart. * * @deprecated Import it from `chartist/compat`, which turns on the 1.x events and plugins. Removed in 3.0. */ export interface DrawEvent { /** What was drawn: `'point'`, `'line'`, `'bar'`, `'grid'`, … */ type: string; /** The drawn element, wrapped in {@link Svg}: change or animate it here. */ element: Svg; /** The group the element is in, wrapped in {@link Svg}. */ group: Svg; /** The drawing area, in px. */ chartRect: ChartRect; /** The X axis, a 1.x {@link Axis} object. */ axisX: Axis; /** The Y axis, a 1.x {@link Axis} object. */ axisY: Axis; /** The `meta` of the value (or of the series, for lines and areas). */ meta: Meta; /** The index of the value in its series (of the series, for lines and areas). */ index: number; /** The series as given in the data: an array or a series object. */ series: FlatSeriesValue | Series | SeriesObject; /** The index of the series in the data. */ seriesIndex: number; } /** * The payload of the 1.x `data` event, emitted before a chart draws new * data. Listeners may change `data` in place to transform it. * * @deprecated Import it from `chartist/compat`, which turns on the 1.x events and plugins. Removed in 3.0. */ export interface DataEvent { /** `'initial'` for the first data, `'update'` for data set later. */ type: 'initial' | 'update'; /** The data the chart is about to draw (a copy, safe to change). */ data: Data; } /** * The payload of the 1.x `optionsChanged` event, emitted when a responsive * option starts or stops applying. * * @deprecated Import it from `chartist/compat`, which turns on the 1.x events and plugins. Removed in 3.0. */ export interface OptionsChangedEvent { /** The options before the change. */ previousOptions: T; /** The options now in effect. */ currentOptions: T; } /** * The 1.x `draw` event of a grid line, one per tick of each axis. `x1`, * `y1`, `x2`, `y2` are the line's ends in px. * * @deprecated Import it from `chartist/compat`, which turns on the 1.x events and plugins. Removed in 3.0. */ export interface GridDrawEvent extends Omit { /** Always `'grid'`. */ type: 'grid'; /** The axis the grid line belongs to. */ axis: Axis; /** The x of the line's start, in px. */ x1: number; /** The y of the line's start, in px. */ y1: number; /** The x of the line's end, in px. */ x2: number; /** The y of the line's end, in px. */ y2: number; } /** * The 1.x `draw` event of the grid background, the `rect` behind the * drawing area (with `showGridBackground`). * * @deprecated Import it from `chartist/compat`, which turns on the 1.x events and plugins. Removed in 3.0. */ export interface GridBackgroundDrawEvent { /** Always `'gridBackground'`. */ type: 'gridBackground'; /** The grid group the background is in. */ group: Svg; /** The background `rect`. */ element: Svg; } /** * The 1.x `draw` event of an axis label, one per tick. The label is a * `foreignObject` with a `span`, placed at `x`, `y` with the given size. * * @deprecated Import it from `chartist/compat`, which turns on the 1.x events and plugins. Removed in 3.0. */ export interface LabelDrawEvent extends Omit { /** Always `'label'`. */ type: 'label'; /** The axis the label belongs to. */ axis: Axis; /** The label as shown, after `labelTransform`. */ text: Label; /** The x of the label's box, in px. */ x: number; /** The y of the label's box, in px. */ y: number; /** The width of the label's box, in px. */ width: number; /** The height of the label's box, in px. */ height: number; } /** * The 1.x `draw` events of the axes: grid lines, the grid background and labels. * * @deprecated Import it from `chartist/compat`, which turns on the 1.x events and plugins. Removed in 3.0. */ export type AxesDrawEvent = GridDrawEvent | GridBackgroundDrawEvent | LabelDrawEvent; //#endregion //#region src/core/math.d.ts /** A tiny number, about the gap between 1 and the next float: the tolerance of float comparisons. */ export declare const EPSILON = 2.221e-16; /** * Calculate the order of magnitude for the chart scale * @param value The value Range of the chart * @return The order of magnitude */ export declare function orderOfMagnitude(value: number): number; /** * Project a data length into screen coordinates (pixels) * @param axisLength The svg element for the chart * @param length Single data value from a series array * @param bounds All the values to set the bounds of the chart * @return The projected data length in pixels */ export declare function projectLength(axisLength: number, length: number, bounds: Bounds): number; /** * Rounds a value to a number of digits after the decimal point, to remove * float errors such as `0.30000000000000004`. `0` digits round to whole * numbers. * @param value The value to round * @param [digits] The digits after the decimal point; without it, the * global precision (8) * @returns The rounded value */ export declare function roundWithPrecision(value: number, digits?: number): number; /** * 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. * @param num An integer number where the smallest factor should be searched for * @returns The smallest integer factor of the parameter num, or num itself when it is not finite. */ export declare function rho(num: number): number; /** * Calculate cartesian coordinates of polar coordinates * @param centerX X-axis coordinates of center point of circle segment * @param centerY X-axis coordinates of center point of circle segment * @param radius Radius of circle segment * @param angleInDegrees Angle of circle segment in degrees * @return Coordinates of point on circumference */ export declare function polarToCartesian(centerX: number, centerY: number, radius: number, angleInDegrees: number): { x: number; y: number; }; //#endregion //#region src/core/data/bounds.d.ts /** * Calculate and retrieve all the bounds for the chart and return them in one array * @param axisLength The length of the Axis used for * @param highLow An object containing a high and low property indicating the value range of the chart. * @param scaleMinSpace The minimum projected length a step should result in * @param onlyInteger * @return All the values to set the bounds of the chart */ export declare function getBounds(axisLength: number, highLow: { high: number; low: number; }, scaleMinSpace: number, onlyInteger?: boolean): Bounds; //#endregion //#region src/core/data/data.d.ts /** * Get meta data of a specific value in a series. */ export declare function getMetaData(seriesData: FlatSeriesValue | Series | SeriesObject, index: number): any; /** * Checks if a value is considered a hole in the data series. * @returns True if the value is considered a data hole */ export declare function isDataHoleValue(value: unknown): value is null | undefined; /** * Checks if value is array of series objects. */ export declare function isArrayOfSeries(value: unknown): value is (Series | SeriesObject)[]; /** * Checks if provided value object is multi value (contains x or y properties) */ export declare function isMultiValue(value: unknown): value is Multi; /** * 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`. */ export declare function getMultiValue(value: Multi | number | unknown, dimension?: AxisName): number | undefined; //#endregion //#region src/core/data/highLow.d.ts /** * Get highest and lowest value of data array. This Array contains the data that will be visualized in the chart. * @param data The array that contains the data to be visualized in the chart * @param options The Object that contains the chart options * @param dimension Axis dimension 'x' or 'y' used to access the correct value and high / low configuration * @param extent A range to include beyond the data, such as the sums of stacked bars * @return An object that contains the highest and lowest value that will be visualized on the chart. */ export declare function getHighLow(data: NormalizedSeries[], options: Options, dimension?: AxisName, extent?: { readonly low: number; readonly high: number; }): { high: number; low: number; }; //#endregion //#region src/core/data/normalize.d.ts /** * Ensures that the data object passed as second argument to the charts is present and correctly initialized. * @param data The data object that is passed as second argument to the charts * @return The normalized data object */ export declare function normalizeData(data: Data, reverse?: boolean, multi?: false): NormalizedData; export declare function normalizeData(data: Data<(Series | SeriesObject)[]>, reverse: boolean | undefined, multi: true | AxisName): NormalizedData; export declare function normalizeData(data: Data, reverse: boolean | undefined, multi: boolean | AxisName, distributed: true): NormalizedData; export declare function normalizeData(data: Data, reverse?: boolean, multi?: boolean | AxisName): NormalizedData; //#endregion //#region src/core/data/segments.d.ts /** * Splits a list of coordinates and associated values into segments. Each returned segment contains a pathCoordinates * valueData property describing the segment. * * With the default options, segments consist of contiguous sets of points that do not have an undefined value. Any * points with undefined values are discarded. * * **Options** * The following options are used to determine how segments are formed * ```javascript * var options = { * // If fillHoles is true, undefined values are simply discarded without creating a new segment. Assuming other options are default, this returns single segment. * fillHoles: false, * // If increasingX is true, the coordinates in all segments have strictly increasing x-values. * increasingX: false * }; * ``` * * @param pathCoordinates List of point coordinates to be split in the form [x1, y1, x2, y2 ... xn, yn] * @param valueData List of associated point values in the form [v1, v2 .. vn] * @param options Options set by user * @return List of segments, each containing a pathCoordinates and valueData property. */ export declare function splitIntoSegments(pathCoordinates: number[], valueData: SegmentData[], options?: { increasingX?: boolean; fillHoles?: boolean; }): Segment[]; //#endregion //#region src/core/data/serialize.d.ts /** * 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. * If called with null or undefined the function will return immediately with null or undefined. */ export declare function serialize(data: number | string | object): string; export declare function serialize(data: number | string | object | null | undefined | unknown): string | null | undefined; /** * 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. */ export declare function deserialize(data: string): T; export declare function deserialize(data: string | null | undefined): T | null | undefined; //#endregion //#region src/core/creation.d.ts /** * Create or reinitialize the SVG element for the chart * @param container The containing DOM Node object that will be used to plant the SVG element * @param width Set the width of the SVG element. Default is 100% * @param height Set the height of the SVG element. Default is 100% * @param className Specify a class to be added to the SVG element * @return The created/reinitialized SVG element * * @deprecated Part of the 1.x chart classes. The functional API builds a scene instead. Removed in 3.0. */ export declare function createSvg(container: Element, width?: number | string, height?: number | string, className?: string, viewBox?: ViewBox): Svg; /** * Turns a padding option into a full {@link ChartPadding}: a number pads * every side, an object keeps its numeric sides and sets the missing ones * to 0, and `undefined` gives 0 on every side. * @returns A new padding object with `top`, `right`, `bottom` and `left`. */ export declare function normalizePadding(padding: number | Partial | undefined): { top: number; right: number; bottom: number; left: number; }; /** * Initialize chart drawing rectangle (area where chart is drawn) x1,y1 = bottom left / x2,y2 = top right * @param svg The svg element for the chart * @param options The Object that contains all the optional values for the chart * @return The chart rectangles coordinates inside the svg element plus the rectangles measurements */ export declare function createChartRect(svg: Svg, options: Options): { x1: number; x2: number; y1: number; y2: number; padding: { top: number; right: number; bottom: number; left: number; }; width(): number; height(): number; }; /** * Creates a grid line based on a projected value. * * @deprecated Use the `axisGrid()` layer. Removed in 3.0. */ export declare function createGrid(position: number, index: number, axis: Axis, offset: number, length: number, group: Svg, classes: string[], eventEmitter: EventEmitter): void; /** * Creates a grid background rect and emits the draw event. * * @deprecated Use the `axisGrid()` layer. Removed in 3.0. */ export declare function createGridBackground(gridGroup: Svg, chartRect: ChartRect, className: string, eventEmitter: EventEmitter): void; /** * Creates a label based on a projected value and an axis. * * @deprecated Use the `axisLabels()` layer. Removed in 3.0. */ export declare function createLabel(position: number, length: number, index: number, label: Label, axis: Axis, axisOffset: number, labelOffset: { x: number; y: number; }, group: Svg, classes: string[], eventEmitter: EventEmitter): void; //#endregion //#region src/core/optionsProvider.d.ts /** * What {@link optionsProvider} returns: the current options, and a way to stop listening to media queries. * * @deprecated Part of the 1.x chart classes. Responsive options are an argument of the chart functions. Removed in 3.0. */ export interface OptionsProvider { removeMediaQueryListeners(): void; getCurrentOptions(): T; } /** * Provides options handling functionality with callback for options changes triggered by responsive options and media query matches * @param options Options set by user * @param responsiveOptions Optional functions to add responsive behavior to chart * @param eventEmitter The event emitter that will be used to emit the options changed events * @return The consolidated options object from the defaults, base and matching responsive options * * @deprecated Part of the 1.x chart classes. Responsive options are an argument of the chart functions. Removed in 3.0. */ export declare function optionsProvider(options: T, responsiveOptions: ResponsiveOptions | undefined, eventEmitter: EventEmitter): OptionsProvider; //#endregion //#region src/charts/BaseChart.d.ts /** * The base class of the 1.x chart classes ({@link LineChart}, * {@link BarChart}, {@link PieChart}): the container, `update`, `detach`, * `on` and `off`. * * @deprecated Use the chart functions: `lineChart()`, `barChart()`, `pieChart()` and `chart()`. Removed in 3.0. */ export declare abstract class BaseChart { protected data: Data; private readonly defaultOptions; private options; private readonly responsiveOptions?; protected svg?: Svg; protected readonly container: Element; protected readonly eventEmitter: EventEmitter; private readonly resizeListener; private initializeTimeoutId; private optionsProvider?; constructor(query: string | Element | null, data: Data, defaultOptions: Options, options: Options, responsiveOptions?: ResponsiveOptions | undefined); abstract createChart(options: Options): void; /** * Updates the chart which currently does a full reconstruction of the SVG DOM * @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. * @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. * @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 */ update(data?: Data, options?: Options, override?: boolean): this; /** * 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. */ detach(): this; /** * Use this function to register event handlers. The handler callbacks are synchronous and will run in the main thread rather than the event loop. * @param event Name of the event. Check the examples for supported events. * @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. */ on(event: T, listener: EventListener): this; on(event: '*', listener: AllEventsListener): this; on(event: string, listener: EventListener): this; /** * 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. * @param event Name of the event for which a handler should be removed * @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. */ off(event: T, listener?: EventListener): this; off(event: '*', listener?: AllEventsListener): this; off(event: string, listener?: EventListener): this; initialize(): void; } //#endregion //#region src/charts/PresetChart.d.ts /** * Base of the 1.x chart classes that wrap a v2 preset. Keeps the 1.x API: * deferred first render, `update(data, options, override)`, `detach()`, * `on`/`off`, and re-rendering when the window resizes (and, like the chart * functions, when the container does). 1.x events and 1.x plugin functions * need the compat plugin (`chartist/compat`). */ declare abstract class PresetChart extends BaseChart { protected data: TData; private chartOptions?; private readonly chartResponsiveOptions?; private controller?; /** The chart handle while plugins install (before `controller` is set). */ private installing?; private readonly queued; private readonly onWindowResize; /** Set by detach(), also when a listener of the first render calls it. */ private detached; private readonly wildcards; constructor(query: string | Element | null, data: TData, defaults: TOptions, chartOptions?: TOptions | undefined, chartResponsiveOptions?: ResponsiveOptions | undefined); /** Creates the preset this class wraps. */ protected abstract createController(container: Element, data: TData, options: TOptions | undefined, responsiveOptions: ResponsiveOptions | undefined, plugins: PluginEntry[]): PresetController; initialize(): void; createChart(): void; /** * Updates the chart. New options extend the defaults, or the current * options when `override` is true (1.x semantics). */ update(data?: Data, options?: TOptions, override?: boolean): this; /** Stops resize and media query handling; the chart stays rendered. */ detach(): this; on(event: T, listener: EventListener): this; on(event: '*', listener: AllEventsListener): this; on(event: string, listener: EventListener): this; off(event: T, listener?: EventListener): this; off(event: '*', listener?: AllEventsListener): this; off(event: string, listener?: EventListener): this; } //#endregion //#region src/charts/LineChart/LineChart.d.ts /** * Reads a line chart option for a series: the per-series value from * `options.series[name]` if the series has a name and sets it, the chart's * value otherwise. * * @deprecated Part of the 1.x chart classes, with no functional counterpart. Removed in 3.0. */ export declare function getSeriesOption>(series: Series | SeriesObject, options: LineChartOptionsWithDefaults, key: T): LineChartOptionsWithDefaults[T]; /** * The 1.x line chart class: a wrapper over the `lineChart` preset with the * 1.x API. 1.x events and 1.x plugin functions need the compat plugin * (`chartist/compat`). * @see {@link lineChart} for the v2 functional API. * * @deprecated Use `lineChart()`. Removed in 3.0. */ export declare class LineChart extends PresetChart { /** * Creates a line chart. The first render happens on the next tick, so * listeners registered right after construction receive it. * @param query A selector query string or a DOM element * @param data The data with labels and series * @param options Options that override the defaults * @param responsiveOptions `[mediaQuery, options]` pairs */ constructor(query: string | Element | null, data: LineChartData, options?: LineChartOptions, responsiveOptions?: ResponsiveOptions); protected createController(container: Element, data: LineChartData, options: LineChartOptions | undefined, responsiveOptions: ResponsiveOptions | undefined, plugins: PluginEntry[]): PresetController; } //#endregion //#region src/charts/BarChart/BarChart.d.ts /** * The 1.x bar chart class: a wrapper over the `barChart` preset with the * 1.x API. 1.x events and 1.x plugin functions need the compat plugin * (`chartist/compat`). * @see {@link barChart} for the v2 functional API. * * @deprecated Use `barChart()`. Removed in 3.0. */ export declare class BarChart extends PresetChart { /** * Creates a bar chart. The first render happens on the next tick, so * listeners registered right after construction receive it. * @param query A selector query string or a DOM element * @param data The data with labels and series * @param options Options that override the defaults * @param responsiveOptions `[mediaQuery, options]` pairs */ constructor(query: string | Element | null, data: BarChartData, options?: BarChartOptions, responsiveOptions?: ResponsiveOptions); protected createController(container: Element, data: BarChartData, options: BarChartOptions | undefined, responsiveOptions: ResponsiveOptions | undefined, plugins: PluginEntry[]): PresetController; } //#endregion //#region src/layers/pie.d.ts /** Which way pie labels anchor, relative to the center. */ type LabelDirection$1 = 'implode' | 'neutral' | 'explode'; /** The `text-anchor` of a pie label. */ type AnchorPosition$1 = 'start' | 'middle' | 'end'; interface Dot$1 { x: number; y: number; } /** * The options of the {@link pie} layer. Without them, it draws a filled * pie from the top, with a label halfway out on each slice. */ interface PieLayerOptions { /** Where the first slice starts, in degrees clockwise from the top. */ readonly startAngle?: number; /** Fixed total; slices are relative to it (gauges). Defaults to the sum. */ readonly total?: number; /** Draws a donut: rings instead of filled slices. */ readonly donut?: boolean; /** * Donut ring width in px, or a share of the radius (`'25%'`). Without * it, the stylesheet sets the width (`--ct-donut-width`, 60px by * default), and in the browser the ring is laid out for the width the * stylesheet gives a slice. Without a DOM (`toScene()`, * `renderToString()`), it's laid out for 60 px, so set `donutWidth` * there if the page's CSS draws another width. */ readonly donutWidth?: number | string; /** Draws a label for each slice; on by default. */ readonly showLabel?: boolean; /** * Moves the labels away from the center (positive) or toward it * (negative), in px. */ readonly labelOffset?: number; /** * Where labels go: `inside` (the default: halfway out on a pie, on the * middle of a donut's ring), `outside` (at the outer edge) or `center` * (in the middle; move them with `labelOffset`). */ readonly labelPosition?: 'inside' | 'outside' | 'center'; /** * Formats a slice's label: its entry in `labels`, or else its value. * Wins over `labelInterpolationFnc` when both are set. */ readonly labelTransform?: (value: Label, index: number) => Label | null | undefined; /** * The 1.x name of `labelTransform`, which wins when both are set. * * @deprecated Use `labelTransform`. Removed in 3.0. */ readonly labelInterpolationFnc?: (value: Label, index: number) => Label | null | undefined; /** * Which way labels anchor: `neutral` (the default), `explode` (away from * the center, for labels outside the pie) or `implode` (toward it). */ readonly labelDirection?: LabelDirection$1; /** Leaves out the slices and labels of zero values. */ readonly ignoreEmptyValues?: boolean; /** * Shifts labels that would overlap another one by this many px, up and * left, judging the overlap by the length of the drawn label text. */ readonly preventOverlappingLabelOffset?: number; /** * Replaces the classes of what the layer draws: `series` (`ct-series`), * `slicePie` (`ct-slice-pie`), `sliceDonut` (`ct-slice-donut`) and * `label` (`ct-label`). */ readonly classNames?: { readonly series?: string; readonly slicePie?: string; readonly sliceDonut?: string; readonly label?: string; }; } /** The 1.x label anchor: `start`, `middle` or `end` by side and direction. */ export declare function determineAnchorPosition(center: Dot$1, label: Dot$1, direction: LabelDirection$1): AnchorPosition$1; /** * Creates a layer that draws a flat series as pie or donut slices with * labels, in the markup of the 1.x pie chart (a `g.ct-series` per slice, * then a group of `text.ct-label`). It draws in polar coordinates, so the * chart needs `coordinates: 'polar'` and no axes. With several series, it * draws one slice per series, from each series' first value. * * @example * ```ts * import { chart, pie } from 'chartist'; * * chart('#chart', { * data: { * labels: ['Rent', 'Food', 'Fun'], * series: [50, 30, 20] * }, * coordinates: 'polar', * layers: [pie({ donut: true, donutWidth: 30 })], * className: 'ct-chart-donut' * }); * ``` */ export declare function pie(options?: PieLayerOptions): Layer; //#endregion //#region src/charts/PieChart/PieChart.d.ts /** * The 1.x pie chart class: a wrapper over the `pieChart` preset with the * 1.x API. 1.x events and 1.x plugin functions need the compat plugin * (`chartist/compat`). * @see {@link pieChart} for the v2 functional API. * * @deprecated Use `pieChart()`. Removed in 3.0. */ export declare class PieChart extends PresetChart { /** * Creates a pie chart. The first render happens on the next tick, so * listeners registered right after construction receive it. * @param query A selector query string or a DOM element * @param data The data with labels and series * @param options Options that override the defaults * @param responsiveOptions `[mediaQuery, options]` pairs */ constructor(query: string | Element | null, data: PieChartData, options?: PieChartOptions, responsiveOptions?: ResponsiveOptions); /** * Checks if a label overlaps another one and moves it up and left until * it doesn't (1.x). */ moveLabel(labelPos: Dot, existingLabelPos: Dot, textOffset: number, length: number): void; protected createController(container: Element, data: PieChartData, options: PieChartOptions | undefined, responsiveOptions: ResponsiveOptions | undefined, plugins: PluginEntry[]): PresetController; } //#endregion //#region src/interpolation/none.d.ts /** The options of {@link Interpolation.none}. */ interface NoneInterpolationOptions { /** * Joins the line across holes (`null` or `undefined` values) instead of * breaking it. Off by default. */ fillHoles?: boolean; } /** * Draws a line as straight segments from point to point, without * smoothing. It's what `lineSmooth: false` uses. * * @example * ```ts * import { lineChart, Interpolation } from 'chartist'; * * lineChart( * '#chart', * { labels: [1, 2, 3, 4, 5], series: [[1, 2, 8, 1, 7]] }, * { lineSmooth: Interpolation.none({ fillHoles: true }) } * ); * ``` * * @param options Whether to join the line across holes. * @returns The interpolation, for the `lineSmooth` option. */ declare function none(options?: NoneInterpolationOptions): (pathCoordinates: number[], valueData: SegmentData[]) => SvgPath; //#endregion //#region src/interpolation/simple.d.ts /** The options of {@link Interpolation.simple}. */ interface SimpleInteractionOptions { /** * How long the curve's handles are: the distance between two points * divided by this, so larger values give tighter curves. `2` by default, * at least `1`. */ divisor?: number; /** * Joins the line across holes (`null` or `undefined` values) instead of * breaking it. Off by default. */ fillHoles?: boolean; } /** * Smooths a line with curves whose handles are horizontal: it goes through * every point and never swings above or below them, but flows less than * {@link Interpolation.cardinal}. `divisor` sets how round it is. * * @example * ```ts * import { lineChart, Interpolation } from 'chartist'; * * lineChart( * '#chart', * { labels: [1, 2, 3, 4, 5], series: [[1, 2, 8, 1, 7]] }, * { lineSmooth: Interpolation.simple({ divisor: 3 }) } * ); * ``` * * @param options The divisor, and whether to join the line across holes. * @returns The interpolation, for the `lineSmooth` option. */ declare function simple(options?: SimpleInteractionOptions): (pathCoordinates: number[], valueData: SegmentData[]) => SvgPath; //#endregion //#region src/interpolation/step.d.ts /** The options of {@link Interpolation.step}. */ interface StepInterpolationOptions { /** * Holds each value until the next point, so the step happens where the * value changes (the default). With `false`, the line steps to the next * value right away. */ postpone?: boolean; /** * Joins the line across holes (`null` or `undefined` values) instead of * breaking it. Off by default. */ fillHoles?: boolean; } /** * Draws a line in steps: horizontal and vertical segments instead of * diagonals or curves. Each step adds a corner to the path, and with * `showPoint` a point is drawn there too. * * @example * ```ts * import { lineChart, Interpolation } from 'chartist'; * * lineChart( * '#chart', * { labels: [1, 2, 3, 4, 5], series: [[1, 2, 8, 1, 7]] }, * { lineSmooth: Interpolation.step({ postpone: false }) } * ); * ``` * * @param options When to step, and whether to join the line across holes. * @returns The interpolation, for the `lineSmooth` option. */ declare function step(options?: StepInterpolationOptions): (pathCoordinates: number[], valueData: SegmentData[]) => SvgPath; //#endregion //#region src/interpolation/cardinal.d.ts /** The options of {@link Interpolation.cardinal}. */ interface CardinalInterpolationOptions { /** * How round the curve is, from `0` (straight segments) to `1` (the * default, a Catmull-Rom spline). */ tension?: number; /** * Joins the line across holes (`null` or `undefined` values) instead of * breaking it. Off by default. */ fillHoles?: boolean; } /** * Smooths a line with a cardinal (Catmull-Rom) spline: round curves that * go through every point. When values change quickly, the curve can swing * past them; {@link Interpolation.monotoneCubic} (the default for * `lineSmooth: true`) doesn't. * * With two points or fewer, the line is straight, as with * {@link Interpolation.none}. * * @example * ```ts * import { lineChart, Interpolation } from 'chartist'; * * lineChart( * '#chart', * { labels: [1, 2, 3, 4, 5], series: [[1, 2, 8, 1, 7]] }, * { lineSmooth: Interpolation.cardinal({ tension: 0.2 }) } * ); * ``` * * @param options The tension, and whether to join the line across holes. * @returns The interpolation, for the `lineSmooth` option. */ declare function cardinal(options?: CardinalInterpolationOptions): (pathCoordinates: number[], valueData: SegmentData[]) => SvgPath; //#endregion //#region src/interpolation/monotoneCubic.d.ts /** The options of {@link Interpolation.monotoneCubic}. */ interface MonotoneCubicInterpolationOptions { /** * Joins the line across holes (`null` or `undefined` values) instead of * breaking it. Off by default. */ fillHoles?: boolean; } /** * Smooths a line with a monotone cubic spline: a smooth curve through * every point that never swings above or below the values around it. It's * what `lineSmooth: true` uses. * * The x values have to keep one direction, increasing or decreasing: * where an x value repeats or turns back, the line breaks. With two points * or fewer, the line is straight, as with {@link Interpolation.none}. * * @example * ```ts * import { lineChart, Interpolation } from 'chartist'; * * lineChart( * '#chart', * { labels: [1, 2, 3, 4, 5], series: [[1, 2, 8, 1, 7]] }, * { lineSmooth: Interpolation.monotoneCubic({ fillHoles: true }) } * ); * ``` * * @param options Whether to join the line across holes. * @returns The interpolation, for the `lineSmooth` option. */ declare function monotoneCubic(options?: MonotoneCubicInterpolationOptions): (pathCoordinates: number[], valueData: SegmentData[]) => SvgPath; declare namespace index_d_exports { export { CardinalInterpolationOptions, MonotoneCubicInterpolationOptions, NoneInterpolationOptions, SimpleInteractionOptions, StepInterpolationOptions, cardinal, monotoneCubic, none, simple, step }; } //#endregion //#region src/scene/tree.d.ts /** * What {@link findAll} looks for: nodes by role, key and data context * fields. A node matches when it matches every field given; an empty query * matches every node. */ interface NodeQuery { /** Only nodes of this role, e.g. `bar`. */ readonly role?: NodeRole; /** Only the node with this key, e.g. `0/1/3` (layer, series, value). */ readonly key?: string; /** Only nodes of the series with this index (`ctx.seriesIndex`). */ readonly seriesIndex?: number; /** Only nodes of the value with this index (`ctx.valueIndex`). */ readonly valueIndex?: number; } /** * Finds all nodes of a scene that match the query, in document order, the * root included. With a `role`, the nodes are typed as that role's nodes. * * @param scene The root of the tree to search, e.g. the `scene` payload * @param query The fields to match; without one, every node matches * @example * ```ts * import { barChart, findAll } from 'chartist'; * * barChart( * '#chart', * { labels: ['Q1', 'Q2', 'Q3', 'Q4'], series: [[5, 4, 3, 7]] }, * { * plugins: [ * { * name: 'log-bars', * install(chart) { * chart.on('scene', ({ scene }) => { * for (const bar of findAll(scene, { role: 'bar' })) { * console.log(bar.key, bar.ctx.value, bar.ctx.y2); * } * }); * } * } * ] * } * ); * ``` */ export declare function findAll(scene: SceneNode, query: NodeQuery & { readonly role: R; }): RoleNode[]; export declare function findAll(scene: SceneNode, query?: NodeQuery): SceneNode[]; /** * Maps a tree bottom-up: children first, then their parent with the mapped * children. Return a node to replace, `null` to drop, or `undefined` to * keep. Subtrees without changes are reused, not copied. * * @param scene The root of the tree to map * @param mapper Called once per node, with the node's mapped children * @returns The mapped tree, or `null` if the mapper dropped the root * @example * ```ts * import { lineChartConfig, mapNodes } from 'chartist'; * import { renderToString, toScene } from 'chartist/server'; * * const scene = toScene( * lineChartConfig({ labels: ['Mon', 'Tue', 'Wed'], series: [[1, 3, 2]] }), * { width: 600, height: 300 } * ); * * // No grid lines, and the points marked for the stylesheet. * const mapped = mapNodes(scene, current => { * if (current.role === 'grid') { * return null; * } * if (current.role === 'point') { * return current.addClass('is-marked'); * } * }); * const markup = mapped ? renderToString(mapped) : ''; * ``` */ export declare function mapNodes(scene: SceneNode, mapper: (current: SceneNode) => SceneNode | null | undefined | void): SceneNode | null; //#endregion //#region src/render/dom.d.ts /** * What {@link domRenderer} returns from `render()`: the inline SVG it * added to the container. */ interface DomRenderOutput extends RenderOutput { /** The chart's `svg` element, in the container. */ readonly svg: SVGSVGElement; /** The rendered element of a scene node of this render. */ readonly elementOf: (node: SceneNode) => Element | undefined; /** Takes the SVG out of the container again. */ readonly remove: () => void; } /** * Sets one scene attribute on an element as the DOM renderer does: names * with a known prefix (`ct:value`) in their namespace, and `style` through * the CSSOM, which a Content Security Policy allows. For renderers that * change elements they keep. * * @example * ```ts * import { applyAttribute } from 'chartist'; * * const point = document.querySelector('.ct-point'); * if (point) { * applyAttribute(point, 'ct:value', 12); * applyAttribute(point, 'style', 'stroke-width: 12px;'); * } * ``` * @param element The element to change * @param name The attribute's name, as in a scene node's `attrs` * @param value The attribute's value */ export declare function applyAttribute(element: Element, name: string, value: string | number): void; /** What {@link renderElement} takes besides the node and the document. */ interface RenderElementOptions { /** Creates the elements in the XHTML namespace, as inside a `foreignObject`. */ readonly html?: boolean; /** Called for every node and the element created for it. */ readonly created?: (node: SceneNode, element: Element) => void; } /** * Creates the element tree of a scene node as the DOM renderer does: SVG * elements, HTML elements inside a `foreignObject`, attributes set with * {@link applyAttribute}. For renderers that create elements. * * @example * ```ts * import { node, renderElement } from 'chartist'; * * const dot = renderElement(node('circle', { cx: 5, cy: 5, r: 4 }, 'ct-dot'), document); * document.querySelector('svg')?.append(dot); * ``` * @param current The node to create * @param document The document to create the elements in * @param options The namespace, and a callback for each created element * @returns The node's element, with its children */ export declare function renderElement(current: SceneNode, document: Document, options?: RenderElementOptions): Element; /** * Creates the renderer `chart()` uses by default: it renders scenes as * inline SVG into the container, replacing an earlier Chartist SVG there * (as 1.x does) on every render, and measures text and reads styles for * layout in the container, so its CSS applies. It ignores the previous * render it gets from a chart's second render on; `liveDomRenderer()` * from `chartist/live` keeps its SVG and changes it instead. * Wrap it to change what every render puts on the page. * * @example * ```ts * import { chart, domRenderer, pie, type Renderer } from 'chartist'; * * const dom = domRenderer(); * // The DOM renderer, with a name for screen readers on every render. * const renderer: Renderer = { * ...dom, * render(scene, container) { * const output = dom.render(scene, container); * output.svg.setAttribute('role', 'img'); * output.svg.setAttribute('aria-label', 'Monthly budget'); * return output; * } * }; * * chart('#chart', { * data: { series: [50, 30, 20] }, * coordinates: 'polar', * layers: [pie()], * renderer * }); * ``` */ export declare function domRenderer(): Renderer; //#endregion //#region src/render/colors.d.ts /** * The default series colors, `a` to `o`, as hex: the colors of * `chartist/styles.css` (`$ct-series-colors` in the Sass settings). * Renderers without CSS use them to color series the way the styles do. * The styles color the first fifteen series only. * * @example * ```ts * import { seriesColors } from 'chartist'; * * // The color of series `c`, the third. * export const third = seriesColors[2]; * ``` */ export declare const seriesColors: readonly string[]; //#endregion //#region src/chart/chart.d.ts /** * Creates a chart from data, axes and layers in a container, and renders * it right away. The presets (`lineChart`, `barChart`, `pieChart`) are * built on it; use it for what they don't cover, like bars and a line on * two Y axes. * * The chart fills its container unless the config sets a size, and renders * again when the container resizes, web fonts finish loading or the * matching `responsive` entries change. Listeners in `config.on` and * plugins receive the events of the first render too. While the page is * printed, the SVG gets a `viewBox` of its layout size (unless the config * sets one), so the drawing scales into the box it gets in the print. * * Without `className`, the SVG gets the chart type class of its layers, * so the stylesheet's chart type rules apply: `ct-chart-bar` if a layer * draws bars, else `ct-chart-pie` or `ct-chart-donut` for a pie layer, * else `ct-chart-line`. A `className` replaces it. * * @example * ```ts * import { * autoScaleAxis, * axisGrid, * axisLabels, * bar, * cartesianAxes, * chart, * line, * stepAxis * } from 'chartist'; * * const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']; * * chart('#chart', { * data: { * labels: months, * series: [ * { name: 'rain', data: [64, 58, 70, 82, 104, 120] }, * { name: 'temperature', data: [1, 3, 8, 12, 16, 20] } * ] * }, * axes: cartesianAxes([ * { id: 'month', side: 'bottom', type: stepAxis(), ticks: months }, * { id: 'mm', side: 'left', type: autoScaleAxis(), low: 0 }, * { id: 'celsius', side: 'right', type: autoScaleAxis(), low: 0 } * ]), * layers: [ * axisGrid({ axes: ['month', 'mm'] }), * bar({ series: ['rain'], x: 'month', y: 'mm' }), * line({ series: ['temperature'], y: 'celsius', align: 'center' }), * axisLabels() * ] * }); * ``` * @param target The container element, or a CSS selector for it. * @param config The data, axes, layers and the rest of the chart. * @returns A handle to update the chart, listen to it or remove it. */ export declare function chart(target: string | Element, config: ChartConfig): ChartHandle; //#endregion //#region src/chart/toScene.d.ts /** * The size {@link toScene} and `renderForHydration()` lay a chart out at, * since there's no container to measure, and how to measure text there. */ interface SceneSize { /** * The width to lay out at, in px. In `toScene()`, the root svg gets it * as its `width`, unless the config sets one. */ readonly width: number; /** * The height to lay out at, in px. In `toScene()`, the root svg gets it * as its `height`, unless the config sets one. */ readonly height: number; /** Text measurement for layout; an estimate by default. */ readonly measureText?: MeasureText; /** * Label mode when the config sets none. `svg` by default in `toScene()`, * since string output often goes to tools without HTML support; `html` * in `renderForHydration()`, as `chart()` draws them. */ readonly labels?: LabelMode; } /** * Builds a chart's scene without rendering it: no DOM, timers or globals. * Runs the phases `resolve` to `scene` with the config's plugins and * listeners. * * It takes the same config as `chart()`, and the SVG gets the same chart * type class without `className`. Listeners of `render` and `mount` * never run, responsive overrides and the `renderer` are ignored, and * calling `update()`, `detach()` or `destroy()` on the handle a plugin gets * throws. Turn the scene into markup with `renderToString()` from * `chartist/server`, which re-exports this function. * * @param config The chart: data, axes, layers, plugins and listeners * @param size The size to lay out at, in px, and how to measure text * @returns The scene, its root the `svg` * @example * ```ts * import { lineChartConfig, node, toScene } from 'chartist'; * import { renderToString } from 'chartist/server'; * * const config = lineChartConfig( * { labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], series: [[12, 9, 7, 8, 5]] }, * { * viewBox: { width: 600, height: 300 }, * on: { * // Styles inside the SVG, for tools that read it on its own. * scene: ({ scene }) => ({ * scene: scene.append( * node('style').text('.ct-line { fill: none; stroke: #d70206; }'), * true * ) * }) * } * } * ); * const scene = toScene(config, { width: 600, height: 300 }); * * export const markup = renderToString(scene); * ``` */ export declare function toScene(config: ChartConfig, size: SceneSize): SceneNode; //#endregion //#region src/scales/factories.d.ts /** * Creates a step axis: evenly spaced ticks, one per step, that place * values by their index rather than by their value. It's the label axis of * line and bar charts. Same rules as 1.x `StepAxis`. * * Its ticks are the data's `labels`, or the axis's `ticks` when you give * them. With `stretch`, the last tick sits at the axis end. * * @example * ```ts * import { * autoScaleAxis, * axisGrid, * axisLabels, * cartesianAxes, * chart, * line, * stepAxis * } from 'chartist'; * * const months = ['Jan', 'Feb', 'Mar', 'Apr']; * * chart('#chart', { * data: { labels: months, series: [[4, 6, 5, 9]] }, * axes: cartesianAxes([ * // The months as ticks; stretch: the first and last at the edges. * { id: 'month', side: 'bottom', type: stepAxis(), stretch: true }, * { id: 'value', side: 'left', type: autoScaleAxis() } * ]), * layers: [axisGrid(), line(), axisLabels()] * }); * ``` */ export declare function stepAxis(): AxisFactory; /** * Creates an auto-scaled axis: a scale fitted to the data, with round * ticks at least `scaleMinSpace` px apart. Set `low`, `high` or * `referenceValue` to widen it, and `onlyInteger` for whole-number steps. * Same rules as 1.x `AutoScaleAxis`. * * It's the value axis of line and bar charts. As an X axis, it places * `{ x, y }` values at their real distances. * * @example * ```ts * import { * autoScaleAxis, * axisGrid, * axisLabels, * cartesianAxes, * chart, * line * } from 'chartist'; * * chart('#chart', { * data: { * series: [ * [ * { x: 1, y: 2 }, * { x: 2.5, y: 5 }, * { x: 7, y: 3 }, * { x: 10, y: 8 } * ] * ] * }, * axes: cartesianAxes([ * { id: 'x', side: 'bottom', type: autoScaleAxis(), onlyInteger: true }, * { id: 'y', side: 'left', type: autoScaleAxis(), low: 0 } * ]), * layers: [axisGrid(), line(), axisLabels()] * }); * ``` */ export declare function autoScaleAxis(): AxisFactory; /** * Creates a fixed-scale axis: a scale from `low` to `high` (by default the * smallest and largest value) with the `ticks` you give. Without `ticks`, * `divisor` splits the range into equal parts with a tick at each end, so * `divisor: 4` makes 5 ticks from `low` to `high` (1.x left out the one * at `high`). * * @example * ```ts * import { * axisGrid, * axisLabels, * cartesianAxes, * chart, * fixedScaleAxis, * line, * stepAxis * } from 'chartist'; * * const teams = ['Red', 'Blue', 'Green']; * * chart('#chart', { * data: { labels: teams, series: [[64, 81, 47]] }, * axes: cartesianAxes([ * { id: 'team', side: 'bottom', type: stepAxis(), ticks: teams }, * // A percentage scale with three grid lines. * { * id: 'percent', * side: 'left', * type: fixedScaleAxis(), * ticks: [0, 50, 100], * low: 0, * high: 100 * } * ]), * layers: [axisGrid(), line({ showLine: false }), axisLabels()] * }); * ``` */ export declare function fixedScaleAxis(): AxisFactory; //#endregion //#region src/scales/cartesian.d.ts /** * Creates the axes for the `axes` option of {@link chart}: a list of axes, * each with an `id`, a `side` and a `type`, several per side if needed. * Axis types are v2 factories ({@link stepAxis}, {@link autoScaleAxis}, * {@link fixedScaleAxis}) or 1.x axis classes; the other fields are the * 1.x axis options (`offset`, `low`, `high`, `ticks`, …). * * Layers pick their axes by id, and each axis scales to the series of the * layers drawn on it. Offsets default to 30 px for X axes and 40 px for Y * axes, and axes on the same side stack outward in list order. Unknown or * duplicate ids throw. * * The 1.x-style `{ x, y }` form also works, with the same defaults: X at * the bottom unless its `position` is `'start'`, Y on the left unless * it's `'end'`. * * @example * ```ts * import { * autoScaleAxis, * axisGrid, * axisLabels, * bar, * cartesianAxes, * chart, * line, * stepAxis * } from 'chartist'; * * const months = ['Jan', 'Feb', 'Mar', 'Apr']; * * chart('#chart', { * data: { * labels: months, * series: [ * { name: 'eur', data: [120, 180, 150, 210] }, * { name: 'usd', data: [130, 195, 160, 230] } * ] * }, * axes: cartesianAxes([ * { id: 'month', side: 'bottom', type: stepAxis(), ticks: months }, * // Both on the left: 'eur' next to the chart, 'usd' outside it. * { id: 'eur', side: 'left', type: autoScaleAxis(), low: 0 }, * { id: 'usd', side: 'left', type: autoScaleAxis(), low: 0, offset: 50 } * ]), * layers: [ * axisGrid({ axes: ['month', 'eur'] }), * bar({ series: ['eur'], y: 'eur' }), * line({ series: ['usd'], y: 'usd', align: 'center' }), * axisLabels() * ], * className: 'ct-chart-bar' * }); * ``` * @param input The axes: a list of {@link AxisDefinition}s, or the 1.x * `{ x, y }` form. * @param extra `reverseData` and `normalize`, for the list form (the * `{ x, y }` form takes them inline). */ export declare function cartesianAxes(input: AxesConfig | readonly AxisDefinition[], extra?: Pick): CartesianAxes; //#endregion //#region src/layers/band.d.ts /** * A value of a {@link band} edge given as values: a number, `{ x, y }` * on a scale X axis, or `null` for a hole. */ type BandEdgeValue = number | { readonly x: number; readonly y: number; } | null | undefined; /** * An edge of a {@link band}: a constant value, values of its own (one per * label, like a series that isn't in the data), a series by name, or a * series by index or name as `{ series }`. */ type BandEdgeOption = number | readonly BandEdgeValue[] | string | { readonly series: number | string; }; /** * The options of the {@link band} layer: `low` and `high` edges, or a * `series` group. */ interface BandOptions { /** The low edge: a constant value, values or a series. */ readonly low?: BandEdgeOption; /** The high edge: a constant value, values or a series. */ readonly high?: BandEdgeOption; /** * A group of series, by index or name: the band covers their minimum to * their maximum at each value index. Can't be combined with `low` and * `high`. */ readonly series?: readonly (number | string)[]; /** The id of the X axis to draw on; default: the first X axis. */ readonly x?: string; /** The id of the Y axis to draw on; default: the first Y axis. */ readonly y?: string; /** * How the edges run between values, as `lineSmooth` of the line layer: * `true` smooths them with `Interpolation.monotoneCubic`, `false` draws * straight segments, or pass an interpolation. */ readonly lineSmooth?: boolean | LineInterpolation; /** * Edge position on a step axis: `start` of each step (1.x) or its * `center`, where bars are centered. */ readonly align?: 'start' | 'center'; /** A class added to the band's group, such as `ct-series-c` for a color. */ readonly className?: string; /** * Gives the points and bars of every layer `ct-in-band` when their value * at their value index lies between the band's edges (edges included), * else `ct-out-band`. The value is `y`, or `x` when a value has no `y` * (the bars of a horizontal bar chart). Nodes at an index where the band * has a hole are left alone. */ readonly mark?: boolean; /** * Replaces the classes of what the layer draws and marks: `band` * (`ct-band`), `area` (`ct-band-area`), `inBand` (`ct-in-band`) and * `outBand` (`ct-out-band`). */ readonly classNames?: { readonly band?: string; readonly area?: string; readonly inBand?: string; readonly outBand?: string; }; } /** * Creates a layer that fills the area between a low and a high edge * (`g.ct-band` with a `path.ct-band-area` per piece; the band breaks at * holes). Each edge is a constant value, values of its own (one per * label) or a series, or `series` names a group and the band covers their * minimum to their maximum at each value index. Constants and own values * widen the Y axis to include them. On a preset, add it to `layers.below` * to draw it behind the series; in a composed chart, list it before the * series layers. It needs an X and a Y axis, from {@link cartesianAxes} * or a preset's. * * @example * ```ts * import { band, lineChart } from 'chartist'; * * lineChart( * '#chart', * { * labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], * series: [{ name: 'visits', data: [12, 9, 7, 8, 5] }] * }, * { low: 0, layers: { below: [band({ low: 6, high: 10, mark: true })] } } * ); * ``` */ export declare function band(options: BandOptions): Layer; //#endregion //#region src/layers/bar.d.ts /** * The options of the {@link bar} layer. Without them, it draws the bars of * each label side by side, 15 px apart, on the first X and Y axis. */ interface BarLayerOptions { /** Series to draw, by index or name; default: all series. */ readonly series?: readonly (number | string)[]; /** The id of the X axis to draw on; default: the first X axis. */ readonly x?: string; /** The id of the Y axis to draw on; default: the first Y axis. */ readonly y?: string; /** Values on the X axis, labels on the Y axis. */ readonly horizontalBars?: boolean; /** * Stacks the bars of a label on each other; `stackMode` says how. The * value axis grows to fit the stacks (see {@link Layer.extent}). */ readonly stackBars?: boolean; /** * How stacked bars stack: `accumulate` (default) adds each value to the * ones before, `accumulate-relative` stacks positive values up and * negative values down from zero, and `overlap` (or `true`) draws every * bar from zero, on top of each other. */ readonly stackMode?: 'accumulate' | 'accumulate-relative' | 'overlap' | boolean; /** Distance between the bars of different series, in px. */ readonly seriesBarDistance?: number; /** * Moves all bars of the layer along the label axis, in px: to the right * for vertical bars, down for horizontal bars (negative values move them * the other way). Two stacked bar layers with opposite offsets draw * grouped stacks. */ readonly offset?: number; /** One series per value of a flat series (1.x `distributeSeries`). */ readonly distributeSeries?: boolean; /** * Draws the series in reverse order (1.x `reverseData`). Can't be * combined with `series`. */ readonly reverseData?: boolean; /** * Replaces the classes of what the layer draws: `series` (`ct-series`) * and `bar` (`ct-bar`). */ readonly classNames?: { readonly series?: string; readonly bar?: string; }; } /** * Creates a layer that draws series as bars, in the markup of the 1.x bar * chart (`g.ct-series` with a `line.ct-bar` per value). The label axis is * X (Y with `horizontalBars`), the value axis the other one; both come * from {@link cartesianAxes}. * * Bars grow from zero on the value axis, so keep zero on it: `low: 0`, or * `referenceValue: 0`. On a step axis they sit in the middle of each step. * * @example * ```ts * import { * autoScaleAxis, * axisGrid, * axisLabels, * bar, * cartesianAxes, * chart, * stepAxis * } from 'chartist'; * * const quarters = ['Q1', 'Q2', 'Q3', 'Q4']; * * chart('#chart', { * data: { * labels: quarters, * series: [ * [800, 1200, 1400, 1300], * [200, 400, 500, 300] * ] * }, * axes: cartesianAxes([ * { id: 'quarter', side: 'bottom', type: stepAxis(), ticks: quarters }, * { id: 'sales', side: 'left', type: autoScaleAxis(), low: 0 } * ]), * layers: [axisGrid(), bar({ seriesBarDistance: 12 }), axisLabels()], * className: 'ct-chart-bar' * }); * ``` */ export declare function bar(options?: BarLayerOptions): Layer; //#endregion //#region src/layers/axes.d.ts /** * The classes {@link axisGrid} and {@link axisLabels} give what they draw. * The defaults are the 1.x classes, so 1.x CSS applies. */ interface AxisLayerClassNames extends AxisClassNames { /** The group of all grid lines (`ct-grids`). */ readonly gridGroup: string; /** The group of all labels (`ct-labels`). */ readonly labelGroup: string; /** The rect behind the grid, with `background: true` (`ct-grid-background`). */ readonly gridBackground: string; } /** * The options of {@link axisGrid} and {@link axisLabels}. */ interface AxisLayerOptions { /** * Axis ids to draw; default: all axes, in declaration order. An unknown * id throws. */ readonly axes?: readonly string[]; /** Replaces some of the classes; the others keep their 1.x names. */ readonly classNames?: Partial; } /** * The options of {@link axisLabels}: those of every axis layer, plus how * the labels are drawn. */ interface AxisLabelsOptions extends AxisLayerOptions { /** HTML (`foreignObject`) or SVG `text`; default: the chart's mode. */ readonly labels?: LabelMode; /** * Aligns SVG text labels in their box, on every axis of the layer; * default: as the 1.x CSS aligns HTML labels. An axis's own * `labelAlign` wins over it. HTML labels ignore it (align them with * CSS). */ readonly align?: Partial; } /** * Creates a layer that draws the grid lines of the named axes (default: * all) in `g.ct-grids`, one `line.ct-grid` per tick. List it first, so * the series draw over it. * * @example * ```ts * import { * autoScaleAxis, * axisGrid, * axisLabels, * cartesianAxes, * chart, * line, * stepAxis * } from 'chartist'; * * const hours = ['6am', '9am', '12pm', '3pm', '6pm']; * * chart('#chart', { * data: { labels: hours, series: [[12, 17, 23, 21, 15]] }, * axes: cartesianAxes([ * { id: 'time', side: 'bottom', type: stepAxis(), ticks: hours }, * { id: 'celsius', side: 'left', type: autoScaleAxis() } * ]), * // Horizontal lines only, on a background rect. * layers: [ * axisGrid({ axes: ['celsius'], background: true }), * line(), * axisLabels() * ] * }); * ``` * @param options The axes to draw and their classes; `background` adds a * `rect.ct-grid-background` over the chart area, behind the lines. */ export declare function axisGrid(options?: AxisLayerOptions & { readonly background?: boolean; }): Layer; /** * Creates a layer that draws the labels of the named axes (default: all) * in `g.ct-labels`, each on its axis's side. Axes on the same side stack * outward, each in its own `offset`. List it last, so the labels draw * over the series. * * Labels are HTML in a `foreignObject` (as in 1.x) or SVG `text`: the * chart's `labels` option decides, unless the layer sets its own. * * @example * ```ts * import { * autoScaleAxis, * axisGrid, * axisLabels, * cartesianAxes, * chart, * line, * stepAxis * } from 'chartist'; * * const weeks = ['W1', 'W2', 'W3', 'W4']; * * chart('#chart', { * data: { labels: weeks, series: [[3, 5, 4, 8]] }, * axes: cartesianAxes([ * { id: 'week', side: 'bottom', type: stepAxis(), ticks: weeks }, * { id: 'km', side: 'left', type: autoScaleAxis(), low: 0 } * ]), * layers: [ * axisGrid(), * line(), * // SVG text instead of HTML, e.g. to export the SVG. * axisLabels({ labels: 'svg' }) * ] * }); * ``` */ export declare function axisLabels(options?: AxisLabelsOptions): Layer; //#endregion export { type AllPhasesListener, type Area, type AttrValue, type AxesConfig, type AxisContext, type AxisDefinition, type AxisDimension, type AxisExtent, type AxisFactory, type AxisLabelContext, type AxisLabelsOptions, type AxisLayerClassNames, type AxisLayerOptions, type AxisSetup, type AxisSide, type AxisTransform, type BandContext, type BandEdge, type BandEdgeOption, type BandEdgeValue, type BandOptions, type BarChartPresetOptions, type BarContext, type BarLayerOptions, type BarPresetState, type CartesianAxes, type ChartAxes, type ChartConfig, type ChartData, type ChartEvents, type ChartHandle, type ChartOverrides, type ChartPlugin, type ContainerCondition, type Coordinates, type CustomEventName, type DomRenderOutput, type ExtentContext, type GridContext, type InsetContext, index_d_exports as Interpolation, type Keyframes, type LabelAlign, type LabelMode, type Layer, type LayerContext, type Layout, type LegacyAxisClass, type LineAttrs, type LineChartPresetOptions, type LineLayerOptions, type LinePresetState, type LineSeriesOptions, type MeasureStyle, type MeasureStyleOptions, type MeasureText, type MeasureTextOptions, type NoSeries, type NodeContext, type NodeMeta, type NodeQuery, type NodeRole, type NodeRoles, type NormalizedChartData, type PathAttrs, type PathContext, type PhaseEvents, type PhaseListener, type PhaseListeners, type PhaseName, type PhaseResult, type PieChartPresetOptions, type PieLabelContext, type PieLayerOptions, type PiePresetState, type PlacedScaleAxis, type PlainNode, type PluginEntry, type PluginWithOptions, type Point, type PointContext, type PreparedData, type PreparedSeries, type PresetAxisOptions, type PresetHandle, type PresetLayers, type PresetResponsiveOptions, type PresetState, type RectAttrs, type RenderCause, type RenderElementOptions, type RenderEvent, type RenderOutput, type RenderUpdate, type Renderer, type ResolvedConfig, type ResponsiveCondition, type ResponsiveEntry, type ResponsiveSet, type ResponsiveWatcher, type RoleMeta, type RoleNode, type ScaleAxis, type SceneChange, type SceneNode, type SceneNodeFields, type SceneNodeMethods, type SceneSize, type SeriesAttrs, type SeriesContext, type SeriesGroupContext, type SliceContext, type TextAttrs, type TextMetrics, type UpdateAnimation, type ValueContext };