ml-time-graph 1.17.0 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,113 @@
1
+ ---
2
+ name: ml-time-graph
3
+ description: Build time-series charts with ml-time-graph (TypeScript, SVG as a string without DOM) and its Go port go-time-graph — thresholds and zone colouring, data gaps, annotations, several value axes, legends, tooltips, server-side and PDF rendering, and the Svelte 5 components in ml-time-graph-svelte. Use when writing or changing code that imports ml-time-graph, ml-time-graph-svelte or go-time-graph, or when sensor or measurement data over time has to become a chart.
4
+ ---
5
+
6
+ # ml-time-graph
7
+
8
+ MLTimeGraph is a TypeScript library for visualizing any time-series measurement data (telemetry, physical sensors, system metrics, logs, finance, laboratory or process measurements). Its standout capability is rich contextual annotation — turning raw curves into explanatory records with free-form annotations (arrows, labels, callout rects in data coordinates), time-range highlights, status/phase bands, and threshold zones. It has a single defining architectural property: it generates SVG as a pure string without touching the DOM — the exact same call runs identically in the browser and on the server.
9
+
10
+ For the exhaustive reference, see `USAGE.md` in the package root ([USAGE.md](../../USAGE.md)); the task-by-task
11
+ details are in `reference/` next to this file (index below).
12
+
13
+ ## Shortest Path to a Visible Chart
14
+
15
+ ```ts
16
+ import { mount } from 'ml-time-graph';
17
+
18
+ mount('#chart', {
19
+ width: 800,
20
+ height: 400,
21
+ series: [
22
+ {
23
+ name: 'Temperature',
24
+ data: [
25
+ { time: 1704067200000, value: 21.5 },
26
+ { time: 1704070800000, value: 22.8 },
27
+ { time: 1704074400000, value: 20.3 },
28
+ ],
29
+ style: { line: { color: '#ef4444' } },
30
+ },
31
+ ],
32
+ });
33
+ ```
34
+
35
+ ### The data does not look like that
36
+
37
+ `{ time, value }` is what the chart wants, not what you have. Convert instead of rebuilding —
38
+ tuples, a REST payload in Unix seconds, a CSV export of strings, a nested document:
39
+
40
+ ```ts
41
+ import { toSeries } from 'ml-time-graph';
42
+
43
+ toSeries('Temperature', tuples) // [[1704067200000, 21.5], …]
44
+ toSeries('Temperature', rows, { time: 'ts', value: 'val', timeUnit: 's' })
45
+ ```
46
+
47
+ Missing readings (`null`, `undefined`, `NaN`, `''`) become gaps. A string that is not a number
48
+ throws and names the row — silently dropping it would turn a broken export into a plausible
49
+ chart.
50
+
51
+ ### The same options in every chart
52
+
53
+ Dimensions, axes, legend, colours repeat across reports. Put them underneath instead of copying
54
+ them:
55
+
56
+ ```ts
57
+ import { mergeOptions, MLTimeGraph } from 'ml-time-graph';
58
+
59
+ new MLTimeGraph(mergeOptions(houseTheme, readings)); // the later layer wins
60
+ ```
61
+
62
+ Objects merge, everything else is replaced — arrays included, so a theme carrying one line
63
+ style does not turn one curve into two. `{ ...a, ...b }` is **not** the same: the spread is
64
+ shallow and an `axes` in `b` drops `a`'s grid and ticks. Server-side the same rule is
65
+ `graph-cli -with theme.json`, stackable.
66
+
67
+ ## When to Use What
68
+
69
+ - `mount(target, options)`: The declarative browser shortcut when a DOM element or selector exists — measures container width, renders SVG, and injects markup in one call.
70
+ - `new MLTimeGraph(options)`: The core headless engine when working with options objects directly — use for Node.js SSR, headless testing, or custom render pipelines.
71
+ - Builders (`GraphBuilder`, etc.): The fluent, imperative chaining API — use when assembling charts dynamically across conditional branches.
72
+ - Go port (`go-time-graph`): The 1:1 server-side Go implementation (`gitlab.com/mlc0911/mlctimegraph/go-time-graph`) — use when rendering charts in Go backends or microservices without a Node runtime.
73
+ - PDF output (`mlctimegraph-pdf`): A second consumer of the same draw commands (`gitlab.com/mlc0911/mlctimegraphpdf`) — writes native PDF vectors without a browser. Early (0.2.0); a fill on a path is still opaque and unhatched there.
74
+
75
+ ## Package Entry Points
76
+
77
+ - `ml-time-graph`: Core chart rendering API — `mount`, `MLTimeGraph`, `SVGRenderer`, `GraphBuilder`, `attachTooltip`, input adapters (`toSeries`, `toDataPoints`), options layering (`mergeOptions`), types, and legend helpers (`resolveDash`, `getLineStyle`, `drawMarker`).
78
+ - `ml-time-graph/analyze`: Pure-math statistics companion — `aggregateBySlot`, `downsample` (LTTB), `detectGaps`, `rollingMkt`, `rollingStdDev`, `computeLimitExcursions`, `StatsAggregator`.
79
+ - `ml-time-graph/interaction`: Headless interaction primitives — `Zoom`, `Minimap`, and coordinate-based interaction state management.
80
+ - `ml-time-graph/internals`: Low-level building blocks for custom renderers — `DrawCommand` model, base `Renderer`, layout engine, scales, and axis renderers.
81
+ - `ml-time-graph-svelte` (separate package, same version): Svelte 5 components `<TimeGraph>` and `<Legend>` — container width, `autoMargin`, tooltip and keyboard, hiding, zoom, `syncTime` for dashboards, dark mode, export, print. `tooltip={false}` drops only the tooltip box. Its README is the manual.
82
+
83
+ ## Tasks — read the matching reference file
84
+
85
+ | Task | File |
86
+ | --- | --- |
87
+ | Several series, a second or third value axis, `axisGroups`, axis titles and `labelOffset`, margins, grid, minor ticks, time zone | [reference/axes.md](reference/axes.md) |
88
+ | Threshold lines and zone colouring, filled areas between curve and threshold or between two series, `where`, `divergenceExcursions` | [reference/thresholds-and-fills.md](reference/thresholds-and-fills.md) |
89
+ | Missing data (`value: null`), gap regions and labels, `gaps.atEnd` for a device that went quiet, `holdToEnd` for a sensor that reports only on change | [reference/gaps.md](reference/gaps.md) |
90
+ | Arrows, labels and rectangles in data coordinates, time-range highlights, status bands, markers | [reference/annotations-and-markers.md](reference/annotations-and-markers.md) |
91
+ | Legend placement, a clickable legend, a panel behind it, line patterns in the swatches | [reference/legend.md](reference/legend.md) |
92
+ | Smoothing (which spline), aggregated min/max/avg series, moving average and other overlays | [reference/series-styles.md](reference/series-styles.md) |
93
+ | Draw commands, tooltips and `pointsAt`, server-side rendering, CSS classes, `idPrefix`, `classPrefix` | [reference/rendering.md](reference/rendering.md) |
94
+ | Svelte 5 components (`ml-time-graph-svelte`) | [reference/svelte.md](reference/svelte.md) |
95
+
96
+ ## Traps (Read Before Coding)
97
+
98
+ - **Timestamps are numbers, not Date objects:** `time` is always milliseconds since Unix epoch (`number`). Passing a `Date` object fails typechecking or evaluates to `NaN`.
99
+ - **Margins are fixed unless you measure them:** The chart draws into `margin` (default `{ top: 20, right: 20, bottom: 40, left: 60 }`). A right Y-axis or a formatted unit (`120.5 °C`) does not fit into `right: 20`, and a clipped number is a wrong number (`120` clipped to `20`). Use `margin: autoMargin(options)` — it measures the labels the chart actually draws (no DOM, a few ms) — or set the margins yourself.
100
+ - **Something you configured does not show up — ask `chart.warnings()`.** Drawing never throws for a threshold name with a typo, a fill bound naming an unknown series, `side` where it is ignored, two series sharing an id, or a deprecated field; it just leaves the thing out. `warnings()` (Go: `Warnings()`, same texts) lists exactly these. Thresholds are found by `id`, and by `name` only when they have no `id`.
101
+ - **`resolveDash()` vs `getLineStyle()`:** `dashed` and `dotted` predate the scalable dash table and keep fixed SVG patterns (`"4,4"` and `"2,4"`) in the renderer for backwards compatibility. `getLineStyle()` returns the scalable table (`"6, 4"` for width 2). Anyone rendering custom legend swatches must call `resolveDash(variant, width)` so the swatch matches what is actually drawn.
102
+ - **Markers do not inherit `line.width`:** `style.markers` carries its own pen — `strokeWidth`, `stroke`, `fill`. That is usually what you want (a 10 px line with 10 px marker outlines is a blob), but it means a marker stays hairline-thin when the line gets thick, and nothing tells you. Set `markers.strokeWidth` explicitly whenever `line.width` leaves the default.
103
+ - **Marker suppression at threshold:** `style.markers.threshold` (and default `theme.pointThreshold = 100`) hides point markers when series sample count exceeds it to prevent visual crowding. Crucially, `chart.legendItems()` also omits the `marker` property when points are suppressed, because a symbol in the legend missing from the curve states something untrue.
104
+ - **A built-in legend carries no behaviour, but it is reachable.** Until 1.12.0 this entry said a
105
+ built-in legend was "non-interactive" and that toggling meant `position: 'separate'` and drawing
106
+ it yourself. That is no longer true: every entry is its own group with the same stable key as its
107
+ series (`#legend-<id>` → `#series-<id>`), and `legend.itemClass` adds your own hook. The library
108
+ still ships no click handler — you write one, and one on the chart is enough. `'separate'` remains
109
+ the way when the legend belongs in HTML, or needs to do more than toggle.
110
+ - **An annotation's `dash` takes a variant, not a pattern:** the type is `'dashed' | 'dotted'`. A raw SVG pattern like `'5,5'` is not rejected — it draws a solid line, in both libraries.
111
+ - **One option is still accepted and does nothing:** `series.sensorType` is in the types and the parser reads it, but no renderer acts on it — in either library. Setting it to `'enum'` does not label the axis; that is `series.enumMap`, which 1.10.0 wired up. Since 1.17.1 it is marked **deprecated** and will be removed before 2.0; so is the flat gap style `'label'` (use `'empty'` with a `label`), which `warnings()` reports. Until 1.10.0 this list also held `ticks.minor`, `grid.minor` and `enumMap` itself: three fields the types promised and both renderers swallowed. Since 1.18 `warnings()` reports `sensorType` too (any value but `"numeric"`, which `parseJSON` sets itself).
112
+ - **CSS classes are not namespaced:** the chart uses plain names like `.series` and `.time-axis`. Inline the SVG into a page whose stylesheet has a `.series` rule and that rule applies to the chart. Scope your own selectors, and suspect the host page when an embedded chart looks wrong but the standalone file does not.
113
+ - **Hatch lines adapt to fill colour:** Hatch patterns inherit the opaque colour of the area they belong to (`opaqueColor(fill)`), while the backdrop stays translucent. An earlier default drew fixed blue lines (`#4D88FF`), which falsely signaled an extra state on incident charts where colour is semantic.
@@ -0,0 +1,63 @@
1
+ # Annotations, highlights and markers — ml-time-graph
2
+
3
+ Part of the `ml-time-graph` skill — back to [SKILL.md](../SKILL.md). The exhaustive reference
4
+ is `USAGE.md` in the package root ([USAGE.md](../../../USAGE.md)).
5
+
6
+ ## Annotations & Region Highlights
7
+ Enrich charts with domain context: vertical time-span highlights across the plot, free-form annotations in data coordinates (which automatically scale through zoom/resize), and status bands below:
8
+ ```ts
9
+ mount('#chart', {
10
+ series,
11
+ // Vertical time-range highlight behind the data:
12
+ highlights: [
13
+ { startTime: t1, endTime: t2, label: 'Calibration Phase', color: '#3b82f6', opacity: 0.15 },
14
+ ],
15
+ // Overlays anchored in data coordinates (time/value) tracking zoom & resize:
16
+ annotations: [
17
+ { type: 'arrow', from: { time: t1, value: 20 }, to: { time: t2, value: 35 }, color: '#ef4444' },
18
+ { type: 'label', at: { time: t2, value: 35 }, text: 'Pressure Spike', dy: -10 },
19
+ { type: 'rect', from: { time: t1, value: 15 }, to: { time: t2, value: 25 }, fill: '#10b98122' },
20
+ { type: 'line', from: { time: t1, value: 30 }, to: { time: t3, value: 30 }, dash: 'dashed' },
21
+ { type: 'point', at: { time: t2, value: 35 }, shape: 'circle' },
22
+ ],
23
+ // Horizontal status/phase bands below the plot (sharing the time axis):
24
+ annotationBands: [
25
+ {
26
+ name: 'Operating State',
27
+ height: 20,
28
+ items: [
29
+ { startTime: t1, endTime: t2, label: 'Running', fill: '#22c55e44' },
30
+ { startTime: t2, endTime: t3, label: 'Standby', fill: '#eab30844' },
31
+ ],
32
+ },
33
+ ],
34
+ });
35
+ ```
36
+
37
+ **The five annotation types and what each one takes:**
38
+
39
+ | `type` | Coordinates | Own fields |
40
+ | :--- | :--- | :--- |
41
+ | `line` | `from`, `to` | `color`, `width`, `dash` |
42
+ | `arrow` | `from`, `to` | `color`, `width`, `headSize` — the head sits on `to` |
43
+ | `rect` | `from`, `to` | `fill`, `hatch`, `stroke`, `opacity` |
44
+ | `point` | `at` | `shape` (`circle` \| `square` \| `cross`), `color`, `radius` |
45
+ | `label` | `at` | `text`, `dx`, `dy`, `anchor`, `rotate`, `color` |
46
+
47
+ A coordinate is `{ time, value, axis? }` — `axis` picks the y-scale (0 = left). An
48
+ annotation with an `id` is wrapped in `<g class="annotation annotation--{slug}">` and can
49
+ be targeted from CSS or toggled; without one its shapes are emitted bare. Both libraries
50
+ draw all five types identically — the Go port did not draw any of them before 1.8.0.
51
+
52
+ ## Markers
53
+ Render sample markers on curves or standalone timestamp event lines:
54
+ ```ts
55
+ series: [{
56
+ name: 'Sensor',
57
+ data: sensorData,
58
+ style: { markers: { type: 'circle', size: 3, stroke: '#3b82f6', fill: '#ffffff', threshold: 100 } },
59
+ }],
60
+ markers: [
61
+ { time: 1704070800000, value: 25, label: 'Peak event', color: '#ef4444', lineStyle: 'to-value' },
62
+ ]
63
+ ```
@@ -0,0 +1,112 @@
1
+ # Axes, grids and time zones — ml-time-graph
2
+
3
+ Part of the `ml-time-graph` skill — back to [SKILL.md](../SKILL.md). The exhaustive reference
4
+ is `USAGE.md` in the package root ([USAGE.md](../../../USAGE.md)).
5
+
6
+ ## Multiple Series & Multi-Axis
7
+ Map series to vertical axes via `yAxisIndex`:
8
+ ```ts
9
+ mount('#chart', {
10
+ margin: { top: 20, right: 80, bottom: 40, left: 60 },
11
+ series: [
12
+ { name: 'Temp', data: tempData, yAxisIndex: 0, style: { line: { color: '#ef4444' } } },
13
+ { name: 'Humidity', data: humData, yAxisIndex: 1, style: { line: { color: '#3b82f6', style: 'dashed' } } },
14
+ ],
15
+ axes: {
16
+ left: { label: 'Temperature (°C)' },
17
+ right: { label: 'Humidity (%)' },
18
+ },
19
+ });
20
+ ```
21
+
22
+ **Which series share an axis** can be decided from the data: `axisGroups(items)` takes unit
23
+ and readings per series and returns `indices` (a `yAxisIndex` each) and `axes` for `axes.y` —
24
+ same unit and nearby ranges together, a gap larger than the larger range apart.
25
+
26
+ **Axis titles** find their own lane between neighbouring axes. To pin one, set
27
+ `axes.y[i].labelOffset` (or `axes.left/right.labelOffset`): the distance from the axis line to
28
+ the middle of the title; the others avoid it. `labels.color` / `labels.fontSize` style the tick
29
+ numbers and the title alike.
30
+
31
+ ## Axes & Margins
32
+ The layout engine does not call into the DOM, but it does know how wide text is: the advance
33
+ widths of the default font stack (`Liberation Sans, Arial, Helvetica` — the three are
34
+ metric-compatible) ship with both libraries. Margins still have to be large enough for your
35
+ labels; the library reserves room inside them, it does not grow them.
36
+ And because the computed domain ends exactly on the smallest and largest reading, a thick line
37
+ or a marker at the extreme loses half of itself to the clip — `padding` adds room **in pixels**
38
+ (the cause is in pixels: `line.width`, `markers.size`), without giving up the automatic domain:
39
+ ```ts
40
+ margin: { top: 20, right: 80, bottom: 40, left: 60 },
41
+ axes: {
42
+ x: { label: 'Time', format: (d: Date) => d.toISOString().slice(11, 16) },
43
+ left: {
44
+ label: 'Temperature (°C)',
45
+ format: (v: number) => `${v.toFixed(1)} °C`,
46
+ padding: 8, // or { top: 24, bottom: 4 }
47
+ },
48
+ right: { label: 'Humidity (%)', format: (v: number) => `${v.toFixed(0)} %` },
49
+ }
50
+ ```
51
+
52
+ Using a different font? Either generate the table for it
53
+ (`node scripts/gen-text-metrics.mjs --font YourFont.ttf`, in the repository) or measure yourself:
54
+
55
+ ```ts
56
+ const canvas = document.createElement('canvas').getContext('2d')!;
57
+ new MLTimeGraph({
58
+ fontFamily: 'Inter, sans-serif',
59
+ textMetrics: (text, fontSize) => {
60
+ canvas.font = `${fontSize}px Inter, sans-serif`;
61
+ return canvas.measureText(text).width;
62
+ },
63
+ });
64
+ ```
65
+
66
+ **A measuring callback leaves the parity with the Go port, deliberately** — a function does not
67
+ travel in JSON, so the server cannot run yours. Same chart, two renderers, two layouts. Use it when
68
+ the browser is the only renderer; use a generated table when both have to agree. `estimateMetrics`
69
+ (exported) reproduces the layout of versions before 1.10.0.
70
+
71
+ ## Grid
72
+ `axes: { x: { grid: true } }` — a grid in both directions; one axis is enough. `grid: false` on
73
+ the other axis leaves that direction out; a `false` alone switches nothing on. `true` is short for
74
+ `{ major: {} }`; use the object form for colour, minor lines or `layer`.
75
+
76
+ ## Minor Ticks & Grid
77
+ ```ts
78
+ axes: {
79
+ x: { grid: { major: {}, minor: { color: '#eee', style: 'dashed' } }, ticks: { minor: 1 } },
80
+ left: { grid: { major: {}, minor: {} }, ticks: { major: 5, minor: 3 } },
81
+ }
82
+ ```
83
+ `ticks.minor` is how many ticks sit **between** two major ones (3 → quarters). `grid.minor` draws
84
+ the matching lines, by default at half the strength of the major grid; setting it without
85
+ `ticks.minor` means one. One minor style governs both directions — `axes.x` wins over `axes.left`,
86
+ same as for the major grid.
87
+
88
+ ## Grid in front or behind — `grid.layer`
89
+ ```ts
90
+ axes: { x: { grid: { major: {}, layer: 'back' } }, left: { grid: { major: {} } } }
91
+ ```
92
+ By default the grid is drawn **after** the series (`layer: 'front'`): a filled area down to the
93
+ baseline does not hide it, and its lines stay visible over the curve. Markers, annotations and
94
+ labels are drawn later still and stay on top either way.
95
+
96
+ `'back'` draws it first of all, before highlights and thresholds — the choice when an opaque fill
97
+ is *meant* to cover it, or when a faint raster behind the data is enough. One setting governs the
98
+ whole grid; `axes.x` wins over `axes.left`, same as for the style.
99
+
100
+ ## Time Zone
101
+ `locale` decides *how* a time is written, `timeZone` **which** time:
102
+
103
+ ```ts
104
+ new MLTimeGraph({ locale: 'de-DE', timeZone: 'Europe/Berlin', series });
105
+ ```
106
+
107
+ Unset means the machine's zone — fine on one machine, a trap across two: a browser sits in
108
+ the reader's zone, a server in UTC, and the same JSON then labels the same reading with
109
+ different times. Set it whenever a chart is produced in one place and read in another. Only
110
+ the labels move; tick positions are epoch arithmetic. Same option in Go
111
+ (`Options.TimeZone`, JSON `timeZone`), which embeds the zone database so it works in a
112
+ scratch image.
@@ -0,0 +1,75 @@
1
+ # Data gaps, quiet devices and held states — ml-time-graph
2
+
3
+ Part of the `ml-time-graph` skill — back to [SKILL.md](../SKILL.md). The exhaustive reference
4
+ is `USAGE.md` in the package root ([USAGE.md](../../../USAGE.md)).
5
+
6
+ ## Data Gaps
7
+ `value: null` marks missing data and breaks the *line*. What is drawn over the span is
8
+ `display`, and the four values mean the same per series and chart-wide:
9
+
10
+ | `display` | draws |
11
+ | --- | --- |
12
+ | `filled` | the area in the fill colour, no edges |
13
+ | `dashed_border` | the area **plus** two vertical dashed lines at its borders (default) |
14
+ | `empty` | nothing — the line breaks, that is all |
15
+ | `bridge_line` | a dotted line between the readings around the gap (per series only) |
16
+
17
+ Two things make a gap readable, and both are off unless you ask:
18
+
19
+ ```ts
20
+ gaps: {
21
+ style: {
22
+ label: { rotate: 'auto' }, // turn it upright when it does not fit
23
+ band: { height: 6, fill: '#dc2626', opacity: 0.8 }, // a strip on the baseline
24
+ },
25
+ regions: [...],
26
+ }
27
+ ```
28
+
29
+ `rotate: 'auto'` turns a label to -90° **only when it is wider than its gap** — measured with the
30
+ same advance table the rest of the layout uses. *Sensor Offline* is about 72 px; a two-hour gap on
31
+ a 600 px chart is 50. Flat, it spills out over the data next to it. A label placed in the margin
32
+ (`baseline: 'above' | 'below'`) stays flat: nothing is in its way there.
33
+
34
+ `band` draws a strip on the plot's baseline, **one per gap** — the data between two gaps is not
35
+ missing. It is the answer for `display: 'empty'`, where the picture otherwise shows nothing but a
36
+ break in the line, and it needs no extra margin (an annotation band does). `offset` pushes it into
37
+ the bottom margin if you have room there.
38
+
39
+ A **label** is separate from all of this and comes from `gaps.regions[].label` — a region knows
40
+ which gap it describes, a series style would have to give all of them the same text:
41
+
42
+ ```ts
43
+ gaps: {
44
+ style: { display: 'filled', fill: '#6b7280', opacity: 0.15, label: { baseline: 'middle' } },
45
+ regions: [{ startTime: 1704070800000, endTime: 1704074400000, label: 'Sensor offline' }],
46
+ }
47
+ ```
48
+
49
+ Connect with a bridge or render gap spans:
50
+ ```ts
51
+ series: [{
52
+ name: 'Sensor',
53
+ data: [{ time: 1704067200000, value: 20 }, { time: 1704070800000, value: null }, { time: 1704074400000, value: 25 }],
54
+ style: {
55
+ line: { color: '#3b82f6' },
56
+ gap: { display: 'bridge_line', bridge: { color: '#94a3b8', width: 1.5, style: 'dotted' } },
57
+ },
58
+ }]
59
+ ```
60
+
61
+ **A device that went quiet** gets an area from its last reading to now — `gaps.atEnd`:
62
+ ```ts
63
+ gaps: { atEnd: { afterMs: 30 * 60_000, label: 'no data since {since} · {duration}' } }
64
+ ```
65
+ *Now* is `atEnd.now` or the end of the time axis; the library reads no clock. Per series:
66
+ `gaps: { atEnd: false }` or `{ afterMs }`.
67
+
68
+ **A sensor that reports only on change** (a door contact) is silent on purpose. `holdToEnd`
69
+ draws its last value on to the end of the axis (or `atEnd.now`), at most `maxAgeMs`:
70
+ ```ts
71
+ { name: 'Door', data, style: { line: { shape: 'step' } }, holdToEnd: true }
72
+ ```
73
+ Only line and fill are extended — markers, tooltip and value axis keep the real readings — and
74
+ such a series gets no `atEnd` area. Without it the line ends at the last report and looks like
75
+ an outage, while the tooltip still shows the state.
@@ -0,0 +1,57 @@
1
+ # Legends — ml-time-graph
2
+
3
+ Part of the `ml-time-graph` skill — back to [SKILL.md](../SKILL.md). The exhaustive reference
4
+ is `USAGE.md` in the package root ([USAGE.md](../../../USAGE.md)).
5
+
6
+ ## A legend you can click — `legend.itemClass`
7
+ ```ts
8
+ legend: { show: true, itemClass: 'clickmetotoggle' }
9
+ ```
10
+ Every entry is its own group: `<g class="legend-item legend-item--<id>" id="legend-<id>">`, and
11
+ `<id>` is the **same key the series group carries** (`#series-<id>`, from `series.id` or the name).
12
+ `itemClass` adds your own class to every entry.
13
+
14
+ That is the whole feature — the library brings nothing to click *with*, it brings something to
15
+ click *on*:
16
+
17
+ ```js
18
+ container.addEventListener('click', (e) => {
19
+ const item = e.target.closest('.clickmetotoggle');
20
+ if (!item) return;
21
+ container.querySelector('#' + item.id.replace('legend-', 'series-'))
22
+ .classList.toggle('hidden'); // .hidden { display: none }
23
+ });
24
+ ```
25
+ `chart.legendItems()` returns the same key as `id`, for anyone still rendering their own legend.
26
+
27
+ ## A panel behind the legend — `legend.box`
28
+ ```ts
29
+ legend: { show: true, position: 'inside-right', box: {} }
30
+ ```
31
+ A legend inside the plot sits **over** the data, and over a dense curve or a filled area it can be
32
+ unreadable. `box` puts a quiet panel under it. Like the grid, it is drawn only when you ask:
33
+ `box: {}` takes the defaults — white, a grey hairline, 6 px padding, 85 % opaque, so the data still
34
+ shows through faintly. `fill`, `stroke`, `strokeWidth`, `padding` and `opacity` override them, and
35
+ `stroke: 'none'` keeps the background without a border.
36
+
37
+ The panel takes the place where the entries would otherwise end, rather than pushing them around:
38
+ turning it on does not move the legend out over the plot edge. With an outside legend the padding
39
+ is reserved as real space, so the border never reaches into the plot.
40
+
41
+ There are no rounded corners — the draw-command model has no corner radius, and adding one would
42
+ mean changing SVG, Go and the PDF renderer for a rounding.
43
+
44
+ ## Legend Placement
45
+ `inside-left` / `inside-right` draw over the plot, `outside-left` / `outside-right` beside it,
46
+ `above` / `below` as a horizontal strip that wraps into as many rows as the entries need — the
47
+ chart reserves exactly that much height. `separate` draws nothing and hands you
48
+ `chart.legendItems()` to build your own.
49
+
50
+ ```ts
51
+ legend: { show: true, position: 'below' }, // waagerecht, bricht um
52
+ legend: { show: true, position: 'above', orientation: 'vertical' }, // Säule, wenn du darauf bestehst
53
+ ```
54
+
55
+ When a legend contains a dashed or dotted series, every entry shows a short line in its
56
+ series' colour, width and pattern instead of a square — the only way to tell two series apart in
57
+ black-and-white print. A legend of solid lines keeps its squares.
@@ -0,0 +1,84 @@
1
+ # Rendering, tooltips, server and CSS — ml-time-graph
2
+
3
+ Part of the `ml-time-graph` skill — back to [SKILL.md](../SKILL.md). The exhaustive reference
4
+ is `USAGE.md` in the package root ([USAGE.md](../../../USAGE.md)).
5
+
6
+ ## Building draw commands — `CommandBuilder`
7
+ ```ts
8
+ import { CommandBuilder } from 'ml-time-graph/internals';
9
+
10
+ const b = new CommandBuilder();
11
+ b.rect({ x: 0, y: 0, w: 10, h: 10, fill: '#eee' })
12
+ .text({ content: 'Label', x: 14, y: 9 })
13
+ .group({ cssClass: 'marks' }, (g) => g.circle({ cx: 5, cy: 5, r: 2 }));
14
+ const group = b.toGroup({ cssClass: 'my-layer' });
15
+ ```
16
+ For anyone producing draw commands — a custom layer, an annotation of your own, a renderer that
17
+ feeds the same `SVGRenderer`. It sets `type` for you, chains, and nests.
18
+
19
+ Two rules worth knowing. `group` draws **nothing** when its body adds nothing, so you cannot leave
20
+ an empty `<g>` behind; `toGroup` always returns a group, because a function that promises one must
21
+ deliver one. And `commands` hands out a copy — what you do with it afterwards cannot reach back
22
+ into the chart.
23
+
24
+ In Go it is `renderer.NewCommandBuilder()` with the same methods.
25
+
26
+ ## Tooltips & Interactive Projections
27
+ Attach DOM tooltips or use pixel/data coordinate projections:
28
+ ```ts
29
+ // Built-in DOM tooltip:
30
+ const chart = mount('#chart', { series, tooltip: { show: true } });
31
+
32
+ // Interactive coordinate projections (crosshairs, zoom, scrubbers):
33
+ chart.renderCommands();
34
+ const timeMs = chart.invertTime(pixelX);
35
+ const value = chart.invertValue(pixelY, yAxisIndex);
36
+ const { x, y } = chart.project(timeMs, value, yAxisIndex);
37
+
38
+ // The plot area the scales map onto (an outside legend included):
39
+ const { x: px0, y: py0, width, height } = chart.plotRect;
40
+ // Data for your own tooltip — per visible series the point nearest in time:
41
+ const points = chart.pointsAt(pixelX, pixelY, { hidden: ['flow'] });
42
+ ```
43
+
44
+ ## Server-Side Rendering (Node.js)
45
+ Generate pure SVG strings without browser dependencies:
46
+ ```ts
47
+ import { MLTimeGraph, SVGRenderer } from 'ml-time-graph';
48
+ import * as fs from 'node:fs';
49
+
50
+ const chart = new MLTimeGraph({ width: 800, height: 400, series });
51
+ const { content } = new SVGRenderer().render(chart.renderCommands());
52
+ fs.writeFileSync('chart.svg', content);
53
+ ```
54
+
55
+ ## Styling the SVG from CSS
56
+ Every group the renderer emits carries a class, and the Go port emits the same ones:
57
+
58
+ `value-axis left` / `value-axis right`, `time-axis`, `axis-labels`, `chart-grid`,
59
+ `chart-legend`, `series series--<slug>`, `thresholds` / `threshold threshold--<slug>`,
60
+ `threshold-labels` / `threshold-label threshold-label--<slug>`, `markers`, `gaps`,
61
+ `highlights`, `annotation-band`, `annotation-band-axis`.
62
+
63
+ On the `<path>` elements inside a series: `series-line` and `series-fill`.
64
+
65
+ The `<slug>` is `config.id ?? slugify(config.name)` — an explicit `id` verbatim, a name
66
+ lowercased with non-alphanumeric runs collapsed to `-`. Export `slugify` to build the
67
+ selector for a name you hold at runtime:
68
+ ```ts
69
+ import { slugify } from 'ml-time-graph';
70
+ svgRoot.querySelector(`.series--${slugify(series.name)}`)?.classList.toggle('is-hidden');
71
+ ```
72
+ The group also carries the same string as an `id` (`#series-temperatur`). Elements
73
+ *inside* a series group use a different, stable key instead: `s-<crc32 of the name>`
74
+ (`-line-<n>`, `-fill-r<region>-<piece>`).
75
+
76
+ **Several charts on one page:** an `id` is unique per *document*. Give each chart its own
77
+ `idPrefix` (`'fridge-2'` → `#fridge-2-series-temperature`) and pass it to
78
+ `new SVGRenderer({ idPrefix })` for the `<defs>` ids too; `ml-time-graph-svelte` does this
79
+ per instance. **A host stylesheet using the same words** (`.series { … }`) reaches into the chart
80
+ — `classPrefix: 'mltg'` prefixes every class (`mltg-series--temperature`), except your own
81
+ `legend.itemClass`; pass it to `SVGRenderer({ classPrefix })` as well.
82
+
83
+ Full table and the provenance comment (`<!-- MLTimeGraph x.y.z -->`, the first child of
84
+ every `<svg>`): [USAGE.md — CSS classes in the SVG](../../../USAGE.md#css-classes-in-the-svg).
@@ -0,0 +1,58 @@
1
+ # Smoothing, aggregated series and statistic overlays — ml-time-graph
2
+
3
+ Part of the `ml-time-graph` skill — back to [SKILL.md](../SKILL.md). The exhaustive reference
4
+ is `USAGE.md` in the package root ([USAGE.md](../../../USAGE.md)).
5
+
6
+ ## Smoothing — which spline
7
+ ```ts
8
+ style: { line: { smoothing: true, smoothingType: 'monotone' } }
9
+ ```
10
+ `'catmull-rom'` is the default: soft, cheap, and it **overshoots** — between two readings it
11
+ draws values that neither of them is. On a chart of measurements that is the picture claiming
12
+ something the sensor never reported.
13
+
14
+ `'monotone'` (Fritsch-Carlson) never leaves the span between two readings. Use it for anything
15
+ with a ceiling or a floor: humidity at 100 %, tank levels, battery charge, percentages.
16
+
17
+ `'akima'` takes its slope from five points and weights it against the change on the other side,
18
+ so a long flat run stays flat right up to an edge. Use it for sensors that only transmit on
19
+ change — a cliff in the data is a real event, not a reason to draw a wave before it.
20
+
21
+ `smoothing: true` remains the switch; `smoothingType` on its own draws straight segments. A step
22
+ shape is never smoothed, whatever you set.
23
+
24
+ If you write your own renderer against the draw commands, read `smoothingType` off the path and
25
+ pass it on — in Go that is `SmoothPathWith`, not `SmoothPath`, which always takes Catmull-Rom.
26
+ Drop it and the same chart comes out as one curve from your renderer and another from the SVG,
27
+ with nothing to warn you: this is exactly what happened to the PDF output in 1.10.0.
28
+
29
+ ## Aggregated Series (`showAs`)
30
+ Points of the shape `{ time, min, max, avg, count }` — one slot per bucket, as
31
+ `aggregateBySlot()` produces:
32
+
33
+ - `showAs: 'minmaxavg'` — three lines (min / max / avg) plus optional `fillToMax` /
34
+ `fillToMin` envelopes. **Geometrically identical to three ordinary series**; what it adds
35
+ is one legend entry instead of three, one series key for all three paths, and
36
+ `avgDashed` on by default (`tests/series/minmaxavg_drei_serien.test.ts` proves the
37
+ equality). Use three plain series when they should behave as three.
38
+ - `showAs: 'band'` — one filled rectangle per slot, min→max. No three-series equivalent.
39
+
40
+ The envelope fills are reachable from plain series too: a fill bound takes
41
+ `{ series: '<id or name>' }`, which spans the area between two curves. The referenced
42
+ curve is interpolated onto this series' timestamps, and the area **breaks where that
43
+ curve has a gap** — same rule as a line.
44
+ Its `avgLine` and `countOpacity` options are TypeScript-only so far.
45
+
46
+ ## Statistic Overlays
47
+ `series.overlays` computes from the series' own data at render time:
48
+ `movingAverage` (`type: 'simple' | 'exponential'`), `movingMkt` (USP <1079.2>),
49
+ `stdDevBand`, `limits`. **Both libraries render all of them** — the Go port since 1.8.0.
50
+
51
+ Every window is in **milliseconds**, including the exponential one
52
+ (`alpha = 1 - exp(-Δt / window)`, not the count-based `2/(N+1)`).
53
+
54
+ The same numbers are available without drawing anything — `rollingMean`, `rollingEma`,
55
+ `rollingStdDev`, `rollingMkt` from `ml-time-graph/analyze`, `analyze.RollingMean` … from
56
+ `pkg/analyze` in Go. An overlay is a convenience, not a second implementation; passing the
57
+ pre-computed series as an ordinary one gives the identical picture, which
58
+ `tests/series/overlay_extern.test.ts` proves rather than claims.
@@ -0,0 +1,37 @@
1
+ # Svelte 5 components — ml-time-graph-svelte
2
+
3
+ Part of the `ml-time-graph` skill — back to [SKILL.md](../SKILL.md). The full manual is the
4
+ README of the `ml-time-graph-svelte` package (`node_modules/ml-time-graph-svelte/README.md`).
5
+
6
+ A separate package with the same version as `ml-time-graph` (its peer dependency):
7
+
8
+ ```svelte
9
+ <script lang="ts">
10
+ import { TimeGraph, Legend } from "ml-time-graph-svelte";
11
+ import type { LegendItem } from "ml-time-graph";
12
+
13
+ let hidden = $state(new Set<string>());
14
+ let legend: LegendItem[] = $state([]);
15
+ </script>
16
+
17
+ <Legend items={legend} bind:hidden />
18
+ <TimeGraph {options} height={260} bind:hidden bind:legend zoomable />
19
+ ```
20
+
21
+ - **`<TimeGraph>`** measures its container, computes margins with `autoMargin`, leaves room
22
+ above and below the curve (`valuePadding`), and shows a tooltip on hover and from the
23
+ keyboard (arrow keys, Home/End, Esc) with a screen-reader announcement.
24
+ - **Tooltip:** your own content as a `tooltip(points, cursor)` snippet; `tooltip={false}`
25
+ drops only the box — crosshair, points, `onhover`, zoom and keyboard stay.
26
+ - **Values:** the axis `format` (with its unit) is used in tooltip, announcement and value
27
+ table alike; `formatValue(v, { seriesId, name, axisIndex, label })` replaces it and gets
28
+ the axis-formatted `label` to keep the unit.
29
+ - **Zoom:** `zoomable` with `bind:zoom`; `applyZoom={false}` only reports the window and
30
+ follows the app's `axes.x.domain`. `followEnd` moves the window along with live data.
31
+ - **Dashboards:** `syncTime` draws crosshair and points at another chart's time; outside
32
+ the window an arrow at the plot edge shows where it lies.
33
+ - **App-wide defaults:** `setTimeGraphDefaults({ locale, timeZone, formatValue, labels, … })`
34
+ in the root layout; order: prop > options > context > built-in.
35
+ - **Dark mode** follows a class on `<html>` (`colorScheme='class'`) or the media query;
36
+ print is always light. `exportSvg()` / `exportPng()` via `bind:this`.
37
+ - Every instance gets its own `idPrefix`; a `classPrefix` in the options is honoured.