API reference
The main API of @mochart/core, grouped by task. Smaller exports, such as the helpers' option and result types and the value constants, are documented by their JSDoc, which editors show on hover:
| Section | Exports |
|---|---|
| Entry points | createDefaultChart, createChart, ChartHandle |
| Data providers | ArrayOfObjectsDataProvider, ObjectOfArraysDataProvider, the DataProvider interface |
| Config helpers | enhanceConfig, validateConfig, validateConfigDetailed, migrateConfig, getDefaults, getConfigWithDefaults, getConfigWithoutDefaults, getDataErrors, hasConfigStructureChange |
| Chart helpers | createHistogram, createWaterfall, createHeatmap, createCandlestick, createOhlc, createPie, createSparklineConfig |
| Config union types | the literal types of the enumerated config values |
| Styling hooks | mochartCssClasses |
| Version | getVersionString |
The framework bindings (see the framework pages) have their own entry points but accept the same props, callbacks, and helpers documented here.
The props the entry points accept are listed property by property in Chart props and Callbacks and payloads, and the name each binding gives them in Framework props. All three are generated from the packages' type declarations.
createDefaultChart
createDefaultChart(container: Element, props: DefaultChartProps): ChartHandle<DefaultChartProps>The simplest entry point (see Getting started). Mounts a chart into container from a raw config and a plain dataset (an array of objects or an object of arrays). Whenever config or data changes, the config is validated and enhanced internally, data is wrapped in the matching data provider (ArrayOfObjectsDataProvider or ObjectOfArraysDataProvider) by shape, and the dataset is checked with getDataErrors. An invalid config shows the config error chart state, a data problem the error state, instead of a broken chart.
Props: config and data, plus everything in Chart props (sizing, loading/error, the controlled focus and filter props, the state factories, and the callbacks).
createChart
createChart(container: Element, props: ManagedChartProps): ChartHandle<ManagedChartProps>The lower-level entry point for hosts that manage config enhancement and data providers themselves. Identical to createDefaultChart except it takes mochartConfig (from enhanceConfig) and dataProvider in place of config and data, which is useful when several charts share one enhanced config, or when data lives in a custom store. Either may be null while the host is still loading. A managed chart trusts its inputs: it does not run getDataErrors, so run it yourself when the data isn't guaranteed valid. Its props are listed under Chart props.
ChartHandle
Returned by both entry points, typed by the props they take:
interface ChartHandle<TProps> {
update(nextProps: Partial<TProps>): void;
replace(nextProps: TProps): void;
refresh(): void;
destroy(): void;
}update(nextProps)merges new props into the chart. Change detection is by object identity: pass a new config/data reference; a key set toundefinedmeans "no change", like an absent key. Data changes (and config changes that move the chart data, such as an axis bound) animate through the staged animation phases when animation is enabled; other config changes redraw instantly; structural config changes rebuild the chart and replay its initial animation; width/height changes re-layout the chart instantly.replace(nextProps)swaps the props wholesale: a key absent fromnextPropsis unset and returns to chart-managed behavior, whereupdatewould keep its previous value. For hosts that pass the complete prop set on every render.refresh()re-reads the current data without a new reference, for hosts that mutate their data in place. A default chart rebuilds its provider overdata; a managed chart calls the provider's optionalrefresh()hook, then re-reads it.destroy()cancels running tweens and removes the chart's DOM. It is safe to call more than once, andupdate,replaceandrefreshno-op afterwards: a late call from a pending timer or an unmounted component does nothing at all, not even re-read the data or call the provider'srefresh()hook.
Data providers
import { ArrayOfObjectsDataProvider, ObjectOfArraysDataProvider } from '@mochart/core';
new ArrayOfObjectsDataProvider(data) // [{ month: 'Jan', revenue: 10 }, …]
new ObjectOfArraysDataProvider(data) // { month: ['Jan', …], revenue: [10, …] }Both take only the dataset, because which property holds the category values is the config's knowledge (categoryAxis.property), and both are stateless: the chart's next re-read sees any in-place change.
Both implement the DataProvider interface, which custom providers can implement to read straight from an existing store:
type DataValue = number | string | Date | null | undefined;
interface DataProvider {
// required: one property's values, index-aligned across properties; undefined when absent
getPropertyValues(property: string): readonly DataValue[] | undefined;
getError?(): unknown; // non-null → the chart shows its error state ('' and 0 count)
getLoading?(): boolean; // true → the chart shows its loading state
refresh?(): void; // called by the handle's refresh() before re-reading, so invalidate caches here
}getPropertyValues is the interface's one accessor: the chart requests every property the config names (the category property, categoryAxis.keyProperty, and the series properties alike) as all of that property's values. Series values are numbers, with null, undefined, and NaN all reading as missing; category values are strings, numbers, or Dates matching categoryAxis.type, and key values are strings or numbers. The config's category property defines the category count, and getDataErrors flags any other property whose value count doesn't match. A provider missing the accessor is invalid, and getDataErrors says so.
See Data providers for the full contract and which properties are read.
Config helpers
import {
enhanceConfig, validateConfig, validateConfigDetailed, migrateConfig,
getDefaults, getConfigWithDefaults, getConfigWithoutDefaults, getDataErrors,
hasConfigStructureChange
} from '@mochart/core';
enhanceConfig(config) // → MochartConfig (migrated, validated, defaults applied)
validateConfig(config, defaults?, strict?) // → { valid, errors, warnings }
validateConfigDetailed(config, defaults?, strict?)
// → { valid, errors, warnings, diagnostics }
migrateConfig(config) // → a copy upgraded to the current format version
getDefaults(config) // → the default values derived from the config
getConfigWithDefaults(config, defaults?) // → the config with every default value filled in
getConfigWithoutDefaults(config, defaults?) // → the minimal config: every default-matching value removed
getDataErrors(mochartConfig, dataProvider) // → string[] of readable data problems
hasConfigStructureChange(prev, next) // → whether applying next rebuilds the chartEvery defaults parameter is optional: when omitted it is derived from the config, which is what one-off calls want. Pass it explicitly (from getDefaults(config)) to reuse one set of defaults across several calls on the same config.
Defaults belong to the config they were derived from. Every default depends on the whole config, not just on the property it fills: a second series turns the default legend.visible from false to true, for instance. So defaults passed for a config they were not derived from are rejected: a section they leave out, or a series/valueAxes list they do not cover, throws rather than filling the config in halfway. Derive them again after editing the config; the saving they offer is worth less than a chart built from the wrong defaults.
strict defaults to true, which is what the chart entry points use: warnings (an unknown config property, for instance) make the config invalid. Pass false to keep a config valid while still collecting its warnings, which is what a live-preview editor wants.
enhanceConfigproduces the fully-builtMochartConfigthatcreateChartconsumes: migrated to the current format, validated, every default applied,*Defaultssections merged, and cross-references resolved. It never mutates the config it is given. An invalid config is returned, not thrown: itsvalidationmember holdsvalid: falsewith theerrorsandwarnings, and a chart given it shows the config error state. The lower-level helpers below do not migrate: callmigrateConfigfirst if you use them directly on a stored config.validateConfigchecks a raw config against the same validators that generate this reference, returning human-readableerrorsandwarnings(unknown properties). See Validation.validateConfigDetailedperforms the same validation, keeps thevalidateConfigresult shape, and addsdiagnostics: one entry per problem with a configpath(keys and array indexes),severity('error'|'warning'),message, andsource, so an editor can highlight the property responsible. An unknown-property warning also carriesinvalidProperties(the offending key names), because itspathstops at the section that contains them.migrateConfigupgrades a config written against an olderversionto the current format, returning a copy; a config with noversionis stamped with the current one.getDefaultsreturns the default values for a config: what every omitted property falls back to. It takes the config because some defaults are conditional (pie mode hides the axes, a sole value axis becomes every series' defaultaxis, and so on).getConfigWithDefaultsreturns the config a chart would actually run: every default filled in and the*Defaultssections merged into their entries. UnlikeenhanceConfig, the result is still a plain raw config: serializable JSON, no cross-references resolved.getConfigWithoutDefaultsis its inverse: the minimal config, with every value that only restates a default removed, which is what a config editor wants to display or store. Re-applying defaults to a minimal config reproduces the fully-defaulted one.- Both return fully independent copies sharing no object with their arguments, so the results can be serialized, diffed, or edited freely without reaching into a mounted chart.
- Both leave out list section entries marked
ignore: true, as the built chart does, so an editor that must keep entries a user switched off has to store the raw config. getDataErrorschecks a dataset against an enhanced config: non-numeric series values, category values that don't match the configured type, duplicate category values, a value count that differs from the category count, and out-of-order category values on a linear category scale under line or area series. A property the provider reports as absent (getPropertyValuesreturnsundefined) is an error too (a lone one for the category property, since nothing else is checkable without it), unless the series setsallowAbsentDataProperties, which reads an absent series property as all-missing values. An invalid config or anullprovider yields no errors.createDefaultChartruns this for you;createChartdoes not.hasConfigStructureChangecompares two enhanced configs (either may benullwhile a host is still loading) and reports whether applying the new one is a structural change, which rebuilds the chart and clears its focus and filters. A host that controls focus or filtering can use it to see that reset coming.
Chart helpers
Factories for chart shapes that are really data transforms plus config conventions. Each returns chart-ready data rows alongside config fragments (categoryAxis, series, …) to spread into your own config. They never touch the chart, so titles, axes, and styling stay yours. Each links to a recipe with a live example.
import {
createHistogram, createWaterfall, createHeatmap,
createCandlestick, createOhlc, createPie, createSparklineConfig
} from '@mochart/core';
createHistogram(values, options?) // → { bins, data, categoryAxis, seriesConfig }
createWaterfall(items, options?) // → { steps, data, categoryAxis, series, valueAxes }
createHeatmap(rows, options?) // → { domain, colorScale, data, categoryAxis, valueAxes, series }
createCandlestick(items, options?) // → { candles, data, categoryAxis, series, valueAxes? }
createOhlc(items, options?) // → { candles, data, categoryAxis, series, valueAxes? }
createPie(items, options?) // → { total, fractions, data, chart, pie, categoryAxis, series }
createSparklineConfig(config, options?) // → config with the sparkline preset appliedcreateHistogrambins an array of numbers (Sturges' count and round bin edges by default;binCount/binWidth/domainoverrides,normalizeandcumulativemodes) into contiguous bars. See Histogram.createWaterfallaccumulates signed steps into floating bars with increase/decrease/total series; itsvalueAxesfragment carries thebasethe bars span from. See Waterfall.createHeatmapturns a grid of row values into one bar-band series per row, each cell colored by value from a shared sequential ramp; the value axis fragment labels the rows. See Heatmap.createCandlestickturns OHLC items into candles: direction-colored open/close bodies over thin low/high wicks, or outlined up bodies with thehollowoption. Thevolumeoption adds a volume pane on a second axis (the result gains avalueAxesfragment), and theaxisTypeoption charts date labels on an ordinal date axis instead of a string one. See Candlestick.createOhlcturns the same OHLC items into tick bars: thin low/high lines with a left open tick and a right close tick, with the samevolumeandaxisTypeoptions. See OHLC bars.createPieturns labelled values into pie or donut slices, one series per slice, sized by its share of the total. Itschartfragment is what switches the chart into pie mode (type: 'pie'); thedonutoption fills thepiefragment. See Pie and donut.createSparklineConfigis a config preset rather than a data transform: it hides axes, legend, tooltip, crosshairs and markers, and collapses margins for tiny inline charts. Values already set on the passed config win; theinteractiveoption keeps the tooltip and crosshairs,paddingsets the uniform edge padding. See Sparklines.
Config union types
Enumerated config values are written as string literals (renderer: 'bar', curveType: 'monotoneX'), and each member's page in this reference lists its allowed values. The literal type each set of values forms is exported, so a wrapper can name one in its own signature (function setRenderer(renderer: RendererType)) instead of indexing into a config type as SeriesConfig['renderer']. Enumerated values lists every one of them with its values and the config members that use it.
Styling hooks
mochartCssClasses maps every chart part to the CSS class the renderer puts on it (mochart-chart, mochart-title-text, mochart-plot, …), which is useful for targeted CSS overrides and DOM queries. The @mochart/export package uses these to serialize rendered charts to SVG/PNG (see Exporting images).
Not every value is a single class name. Parts that exist once per series, axis or category carry two space-separated tokens: the class shared by all of them, then a prefix to which the id (or index) is appended. Prefixes that take a configured id end in -id-, so no id can spell out another structural class.
import { mochartCssClasses } from '@mochart/core';
mochartCssClasses.series // 'mochart-series mochart-series-id-'
mochartCssClasses.seriesBar // 'mochart-series-bar mochart-series-bar-'
const [shared, prefix] = mochartCssClasses.series.split(' ');
document.querySelectorAll('.' + shared); // every series
document.querySelector('.' + prefix + 'S0'); // the series with id S0So '.' + mochartCssClasses.series is not a valid selector: split first. Treat any value containing a space this way. The one exception to the base-plus-prefix reading is chartError, whose two tokens are both complete classes: 'mochart-chart mochart-chart-error'.
What each prefix is followed by:
| Keys | Suffix |
|---|---|
series, legendItem, tooltipSeriesLine | the series id |
seriesBar, seriesMarker, seriesLabel, seriesErrorBar | the category index |
valueAxis, valueAxisGrid, valueAxisBaseLine, valueAxisThreshold | the value axis id |
axisTickMark, axisTickLabel, axisGridLine | the tick's position in the axis's tick list |
axisFocusTickMark | the mark's position among the axis's focus tick marks |
axisThresholdTitle | the threshold's index in the axis's thresholds list |
clipIndicatorBand | the edge: top, right, bottom or left |
A tick's position equals its category index only on an ordinal axis that ticks every category. With explicit ticks, a tick step, a linear scale or the hidden tick at an axis end, the positions and the category indexes differ.
Version
getVersionString() returns the library's package version, e.g. '1.0.0'.
CONFIG_VERSION is the config format version: what migrateConfig stamps onto a config that has none, and what config.version is compared against. The two are separate values and free to diverge, so a host persisting user configs should compare a stored version against CONFIG_VERSION, never against getVersionString().
What is not exported
The internals are not exported: the retained-mode components and rendering primitives, the data-source and focus controllers, the measure/layout and staged-animation pipeline types, and the enhanced config views. The shipped .d.ts still describes the shape of every prop and result (editor hovers show them), but internals are not importable by name from @mochart/core and change without notice. Everything that is importable is supported API: this page covers the main exports, and the rest are documented by their JSDoc.