API Graphique en courbes
Tout ce qu'il faut pour intégrer un graphique en courbes dans votre code ; pour la présentation et les démos, consultez la démo Graphique en courbes.
Import
import "@michi-vz/wc/line-chart";
// <michi-vz-line-chart> is now definedimport { mountLineChart } from "@michi-vz/core";
const chart = mountLineChart(el, props);Propriétés
| Prop | Type | Default | Description |
|---|---|---|---|
timeline | boolean | TimelinePeriodConfig | - | Opt-in "play through years" (cumulative): the marks draw UP TO the active period and extend as the timeline steps; `interpolate` sweeps smoothly between years, `false` jump-cuts. Headless controller via `chart.timeline()` plus the built-in play button + scrubber. Off by default; wins over `progressiveDraw` when both are set. |
dataSet* | LineDataItem[] | - | Array of line series, each with its own points |
title | string | - | Optional chart title rendered above the plot |
yAxisDomain | [number, number] | - | Fix the y-axis range as [min, max] instead of deriving it from the data |
yAxisScale | "linear" | "log" | "linear" | Y-axis scale: "linear" (default) or a base-10 "log" scale. In "log" mode, a non-positive value (<= 0) can't be plotted, so those points are dropped as missing (reported via `onDataWarning`); a dataSet with no positive values at all renders the no-data state instead. |
xAxisDataType | "date_annual" | "date_monthly" | "number" | "number" | How x values are parsed and formatted: yearly dates, monthly dates, or plain numbers |
xAxisFormat | (d: number | string) => string | - | Formats an x tick value into its display label |
yAxisFormat | (d: number | string) => string | - | Formats a y tick value into its display label |
ticks | number | 5 | Approximate number of x-axis ticks to generate |
yTicks | number | - | Number of y-axis ticks (default 10, matching the legacy denser value axis). |
showGridLines | boolean | - | Draw horizontal dashed grid lines at each y tick (default true). |
showVerticalGridLines | boolean | - | Draw vertical dashed grid lines at each x tick (default false - the legacy chart drew none). |
highlightZeroLine | boolean | - | Emphasise the y=0 grid line with a darker solid stroke (default true). |
tickValues | Array<number | Date> | - | Explicit tick values, overriding the generated ones |
fillPeriodTicks | boolean | - | Draw a tick for EVERY period across the axis range (every month/year), not just the periods present in the data. Periods with no value render faded and show `noDataTickTooltip` on hover. Opt-in; default false. |
noDataTickTooltip | (date: number) => string | - | Tooltip content (plain text or sanitized HTML) for a faded no-data tick; receives the tick's epoch-ms value. Used only with `fillPeriodTicks`. Default: a localized "Data not available". |
noDataTickColor | string | - | Colour for faded no-data tick labels; sets the `--michi-vz-tick-nodata` CSS var on the host. Used only with `fillPeriodTicks`. |
curve | "curveBumpX" | "curveLinear" | "curveMonotoneX" | - | Default interpolation for every series (per-series `curve` wins). |
detectGaps | boolean | false | Auto-derive `certainty` from missing periods (dashes the gap segment). |
expectedStep | number | - | Expected cadence in axis units; REQUIRED for xAxisDataType "number". |
showDataPoints | boolean | false | Whether to draw a marker at each data point (default false) |
enableMouseLine | boolean | MouseLineConfig | true | Solid vertical crosshair line snapped to the nearest data point x on hover; pass a config object to style it (default true) |
singlePointLine | boolean | SinglePointLineConfig | - | true / config draws a horizontal guide line for single-point series. |
fontFamily | string | - | Font family for axis/title/tooltip text (SVG + canvas). Sets the --michi-vz-font-family CSS var so both renderers resolve it. |
filter | Filter | - | Top-N / sort filter applied to the data before rendering |
progressiveDraw | boolean | ProgressiveDrawConfig | - | Animate each line drawing itself left to right on mount (progressive reveal). `true` uses defaults; pass a config to tune duration, easing, tip labels, and autoplay. Off by default, so existing charts are unchanged. Respects prefers-reduced-motion: the chart then renders fully drawn instantly. Ignored by the webgpu renderer. |
isLoading | boolean | - | Show the loading overlay and skip the no-data check (legacy michi-vz parity). |
isNodata | | boolean | ((dataSet: LineDataItem[] | null | undefined) => boolean) | - | No-data override: boolean, or a predicate on dataSet; default = empty/all-empty-series. |
noDataLabel | string | - | Text for the vanilla default no-data overlay (ignored when suppressed). |
suppressDefaultOverlay | boolean | - | A framework wrapper sets this to render its OWN loading/no-data node instead. |
tooltipFormatter | ( d: DataPoint, series: DataPoint[], dataSet: LineDataItem[], ) => string | - | Returns custom tooltip HTML for a hovered datum (sanitized before it is inserted) |
sharedTooltip | boolean | false | When true, hovering anywhere in the plot shows ONE tooltip listing every series' value at the nearest x (year) - the "shared"/crosshair tooltip - instead of the single nearest series. Pairs with the crosshair (enableMouseLine, on by default). |
sharedTooltipFormatter | (input: { x: number | string; xLabel: string; entries: Array<{ label: string; value: number; color: string; d: DataPoint }>; }) => string | - | Custom HTML for the shared tooltip. `entries` is one row per series that has a point at the hovered x, in dataSet order, each with its resolved colour. |
onHighlightItem | (labels: string[]) => void | - | Called when the hovered/highlighted label(s) change |
svgChildren | string | - | Pre-serialised SVG markup injected as direct <svg> children (axis-title text, reference lines). The React wrapper fills this from `children`; mirrors the legacy <LineChart>'s `{children}` slot. |
Common props - shared by every chart (14)
| Prop | Type | Default | Description |
|---|---|---|---|
width | number | 1000 | Chart width in pixels |
height | number | 500 | Chart height in pixels |
margin | Margin | { top: 50, right: 50, bottom: 50, left: 60 } | Inner margins (top/right/bottom/left, in px) reserved for axes, titles, and labels |
colors | string[] | - | Categorical palette for series/labels without an explicit colour or colorsMapping entry |
colorsMapping | Record<string, string> | - | Explicit label -> colour map; takes precedence over the palette and per-item colours |
highlightItems | string[] | - | Labels to emphasise; all other marks dim |
disabledItems | string[] | - | Labels to hide and exclude from scales/stacks |
renderer | "svg" | "canvas" | "webgpu" | "svg" | Render as inline SVG (default) or to a canvas (faster for large datasets); getContext() is identical either way |
locale | string | - | BCP-47 locale used for number and date formatting |
skipColorMappingDispatch | boolean | false | External-CSS mode: unmapped labels resolve to transparent and onColorMappingGenerated is not emitted, so mark colours come from your CSS via the data-label-safe contract |
enableTransitions | boolean | true | Animate updates with CSS transitions (default true) |
onColorMappingGenerated | (mapping: Record<string, string>) => void | - | Called with the resolved label -> colour map after the chart assigns colours |
onChartDataProcessed | (context: ChartContext) => void | - | Called with the renderer-agnostic ChartContext whenever the data is (re)processed |
onDataWarning | (warnings: DataWarning[]) => void | - | Called with any non-fatal data warnings (duplicate labels, non-finite values, non-monotonic dates, ...) |
Affichage de la grille et des axes
Quatre propriétés contrôlent la densité des graduations de l'axe des ordonnées et l'affichage des lignes de grille :
| Propriété | Valeur par défaut | Remarques |
|---|---|---|
yTicks | 10 | Nombre approximatif de graduations sur l'axe des ordonnées. La valeur par défaut historique était 10 ; réduisez-la (par exemple 5) pour un axe moins dense. |
showGridLines | true | Lignes de grille horizontales en pointillés à chaque graduation de l'axe des ordonnées. |
showVerticalGridLines | false | Lignes de grille verticales en pointillés à chaque graduation de l'axe des abscisses. Le graphique historique n'en affichait aucune ; à activer uniquement lorsque ces repères supplémentaires améliorent la lisibilité. |
highlightZeroLine | true | Trace la ligne y=0 sous forme de trait plein (coloré via --michi-vz-zero-line, avec repli sur la couleur de la grille) plutôt qu'une graduation en pointillés classique. Utile lorsqu'un jeu de données couvre des valeurs positives et négatives. |
État de chargement et d'absence de données
Le moteur gère un attribut data-mv-state sur l'élément hôte, avec trois valeurs possibles - "loading", "nodata" et "ready" - et affiche des overlays intégrés pour les deux premières, sauf désactivation explicite.
| Propriété | Type | Valeur par défaut | Remarques |
|---|---|---|---|
isLoading | boolean | false | Affiche l'overlay .mv-loading et ignore entièrement la vérification d'absence de données. |
isNodata | boolean | (dataSet) => boolean | - | Remplace le prédicat par défaut (dataSet vide ou chaque série ayant zéro point). Passez false pour forcer le rendu du graphique même quand les données semblent vides. |
noDataLabel | string | - | Texte affiché dans l'overlay .mv-nodata par défaut. Ignoré lorsque suppressDefaultOverlay vaut true. |
suppressDefaultOverlay | boolean | false | Empêche le moteur d'injecter son propre nœud de chargement / d'absence de données. À utiliser lorsqu'un wrapper de framework (par exemple le LineChart de @michi-vz/react) affiche à la place isLoadingComponent / isNodataComponent sous forme d'overlay React. L'hôte n'est jamais démonté - l'overlay est simplement superposé. |
Comportement du wrapper React
Le LineChart de @michi-vz/react définit automatiquement suppressDefaultOverlay et affiche isLoadingComponent / isNodataComponent sous forme de nœud React positionné au-dessus de l'hôte du graphique. Le DOM du graphique est toujours monté, donc isNodataComponent se déclenche même sur des données vides, sans prédicat personnalisé.
Police de caractères
fontFamily définit la propriété CSS personnalisée --michi-vz-font-family sur l'élément hôte, lue à la fois par le moteur de rendu de texte SVG et par la sonde getComputedStyle du canvas. La police doit déjà être chargée par la page - aucun embarquement de police n'est effectué.
ChartContext / legendData
onChartDataProcessed reçoit un LineChartContext qui étend BaseChartContext. La base porte désormais un champ legendData :
interface LegendItem {
label: string; // series label as it appears in dataSet
color: string; // resolved colour at the time of processing
order: number; // appearance order (legend slot index)
disabled?: boolean; // true when the label is currently hidden
dataLabelSafe?: string; // sanitizeForClassName(label) - the CSS hook the canvas colour probe matches
}
interface BaseChartContext {
// ... existing fields ...
legendData?: LegendItem[]; // populated by LineChart; treat absence as []
}legendData est la charge utile canonique pour les autorités de couleur côté consommateur. Un wrapper de framework qui pilote son propre CSS de couleur (par exemple useChartUtils de thd MonitorV2) lit legendData[].{label, dataLabelSafe, color, disabled} à chaque appel de onChartDataProcessed et émet des règles stroke/fill par étiquette ciblant l'attribut data-label-safe. Cela évite d'avoir à recouper colorsMapping avec l'ordre des séries.
Événements
Le composant web émet ces CustomEvents à bouillonnement (bubbling) (le moteur expose les mêmes via les callbacks on* du tableau ci-dessus) :
| Événement | Détail | Se déclenche quand |
|---|---|---|
michi-vz:highlight | string[] | la surbrillance au survol change |
michi-vz:colormapping | Record<string, string> | un mapping de couleurs est généré |
michi-vz:dataprocessed | ChartContext | les données sont (re)traitées |
michi-vz:datawarning | DataWarning[] | des avertissements sur les données d'entrée sont détectés |
getContext()
mountLineChart(el, props).getContext() retourne un LineChartContext indépendant du moteur de rendu (statistiques structurées + un résumé déterministe en langage naturel + une table d'accessibilité). Voir Contexte LLM.
Source
Les propriétés sont typées comme LineChartProps dans @michi-vz/core.
