ml-time-graph 1.5.2 → 1.7.1

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,217 @@
1
+ # Quickstart: `GraphBuilder` (Deutsch)
2
+
3
+ `GraphBuilder` ist der imperative, objektorientierte Weg, mit MLTimeGraph ein
4
+ Diagramm aufzubauen. Statt einen großen Options-Objekt-Baum in einem Rutsch
5
+ zusammenzustellen, erzeugst du einen Builder und fügst die Konfiguration
6
+ Schritt für Schritt hinzu — jede `set*()` / `add*()`-Methode gibt `this`
7
+ zurück, sodass sich alles natürlich ketten lässt. Es funktioniert im Browser
8
+ **und** auf Node (SSR, Reportgenerierung, Datei-Output), weil das Rendern nur
9
+ einen SVG-String erzeugt.
10
+
11
+ Die vollständige Feld-zu-Feld-Referenz der Options, die `toOptions()`
12
+ liefert, findest du in [GRAPH_JSON_STRUCTURE.md](GRAPH_JSON_STRUCTURE.md) (englisch).
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ pnpm add ml-time-graph # oder: npm i / yarn add
18
+ ```
19
+
20
+ Benötigt Node >= 18. Der Build ist ESM-only.
21
+
22
+ ## Import
23
+
24
+ ```ts
25
+ import { GraphBuilder } from "ml-time-graph";
26
+ ```
27
+
28
+ Alle unterstützenden Typen (`Threshold`, `Annotation`, `Marker`, …) werden als
29
+ Typen aus demselben Einstiegspunkt exportiert.
30
+
31
+ ## Minimales Diagramm
32
+
33
+ ```ts
34
+ const g = new GraphBuilder(800, 400);
35
+
36
+ // Zeiten sind Epoche-Millisekunden (Zahl) – niemals `Date`-Objekte.
37
+ g.addSeries({
38
+ name: "Temperatur",
39
+ data: [
40
+ { time: Date.parse("2026-01-15T08:00:00Z"), value: 20.5 }, // 1768464000000
41
+ { time: Date.parse("2026-01-15T09:00:00Z"), value: 24.1 }, // 1768467600000
42
+ { time: Date.parse("2026-01-15T10:00:00Z"), value: 31.8 }, // 1768471200000
43
+ ],
44
+ });
45
+
46
+ // In ein DOM-Element …
47
+ g.mount("#chart");
48
+
49
+ // … oder als SVG-String (SSR / Datei / innerHTML)
50
+ const svg = g.getSvg();
51
+ ```
52
+
53
+ Breite `0` übergeben (oder weglassen) und `mount()` aufrufen, um die Pixelweite
54
+ automatisch aus der `clientWidth` des Ziels zu ermitteln.
55
+
56
+ ## Kettung (Chaining)
57
+
58
+ Jeder Setter und Adder gibt den Builder zurück, sodass ein komplettes Diagramm
59
+ in einer einzigen Aussage steht:
60
+
61
+ ```ts
62
+ new GraphBuilder(900, 420)
63
+ .setLocale("de-DE")
64
+ .addSeries({ name: "Sensor 1", data })
65
+ .addThreshold({ name: "Limit", value: 35, color: "#dc2626" })
66
+ .addHighlight({ startTime: t1, endTime: t2, color: "#fef2f2" }) // Epoche-ms-Zahlen
67
+ .setXAxis({ label: "Zeit" })
68
+ .setLeftAxis({ label: "Temperatur (°C)" })
69
+ .setLegend(true, "inside-right")
70
+ .mount("#chart");
71
+ ```
72
+
73
+ ## Setter
74
+
75
+ | Methode | Wirkung |
76
+ | --- | --- |
77
+ | `setWidth(w)` / `setHeight(h)` / `setSize(w, h)` | Pixelwerte für die Größe. |
78
+ | `setMargin(margin)` oder `setMargin(top, right, bottom, left)` | Rand pro Seite in Pixeln. |
79
+ | `setLocale(locale)` | z. B. `"de-DE"` für Datum-/Zahlenformatierung. |
80
+ | `setAxes({ x?, left?, right? })` | Ersetzt den gesamten Achsenblock. |
81
+ | `setXAxis(cfg)` | Patcht nur die X-Achse (Spread-Merge). |
82
+ | `setLeftAxis(cfg)` | Patcht nur die linke Y-Achse, rechts bleibt unangetastet. |
83
+ | `setRightAxis(cfg)` | Patcht nur die rechte Y-Achse. |
84
+ | `setYAxis(index, cfg)` | Patcht eine beliebige Y-Achse per Index (Array wächst automatisch). |
85
+ | `setLegend(opts)` oder `setLegend(show, position?, orientation?)` | Legende zeigen / platzieren / ausrichten. Positionen: `"inside-right"`, `"inside-left"`, `"outside-right"`, `"outside-left"`, `"separate"`. |
86
+ | `setGaps(gapArrayOrConfig)` | Datengap-Handling — legacy `Gap[]` oder `{ regions?, autoDetect?, minGapMs?, style? }`. |
87
+ | `setTooltip({ show?, format?, snapRadius?, … })` | Tooltip; wirkt nur zusammen mit `mount()` (in reinem `getSvg()`-Output gibt es nichts zum Überfahren). Standard bei Aufruf: `show: true`. |
88
+
89
+ Achsen-Beispiele:
90
+
91
+ ```ts
92
+ g.setXAxis({ label: "Zeit", format: (d) => d.toLocaleTimeString("de-DE") });
93
+
94
+ g.setLeftAxis({ label: "Temperatur (°C)", grid: { major: { color: "#e5e7eb" } } });
95
+
96
+ // Zwei Serien auf unterschiedlichen Skalen:
97
+ g.addSeries({ name: "Temp", data: tempData, yAxisIndex: 0 });
98
+ g.addSeries({ name: "Fluss", data: flowData, yAxisIndex: 1 });
99
+ g.setLeftAxis({ label: "°C" });
100
+ g.setRightAxis({ label: "L/h" });
101
+ ```
102
+
103
+ ## Adder
104
+
105
+ Jeder Adder hängt ein Element an seine interne Liste an; die `*All` / Plural-
106
+ Varianten hängen Arrays an. Alle geben `this` zurück.
107
+
108
+ | Methode | Fügt hinzu |
109
+ | --- | --- |
110
+ | `addSeries(s)` / `addSeriesAll(s[])` | Eine Zeitserie (`AnySeries`: rohe `DataPoint[]` oder aggregiert min/max/avg). |
111
+ | `addThreshold(t)` / `addThresholds(t[])` | Eine Schwelle: Linie, optionale Füllzone, optionales Label. |
112
+ | `addAnnotation(a)` / `addAnnotations(a[])` | Freiform-Overlay — eine der Varianten `line`, `arrow`, `rect`, `point`, `label` (diskriminiert über das Feld `type`). |
113
+ | `addHighlight(h)` | Ein hinterlegter Zeitraum, gezeichnet hinter den Daten. |
114
+ | `addMarker(m)` | Eine vertikale Markierung zu einem Zeitstempel, optional Wertpunkt + Label. |
115
+ | `addAnnotationBand(band)` | Ein horizontaler Streifen unter dem Diagramm mit farbigen Zeitfenstern und Labels. |
116
+
117
+ Beispiele:
118
+
119
+ ```ts
120
+ // Schwellwert: `fill` ist eine Zeichenkette ("above" | "below" | "none") und
121
+ // `line` ist eine Zeichenkette ("solid" | "dashed" | "dotted" | "none");
122
+ // die Deckkraft ist ein separates Feld.
123
+ g.addThreshold({
124
+ name: "Max",
125
+ value: 35,
126
+ color: "#dc2626",
127
+ fill: "above",
128
+ fillOpacity: 0.1,
129
+ line: "dashed",
130
+ label: { position: "right" }, // oder direkt `label: "Max"` / `label: false`
131
+ });
132
+
133
+ // Hervorgehobener Zeitraum (Störungs-Fenster). `startTime`/`endTime` sind Epoche-ms-Zahlen:
134
+ g.addHighlight({
135
+ startTime: Date.parse("2026-01-15T09:10:00Z"), // 1768468200000
136
+ endTime: Date.parse("2026-01-15T09:40:00Z"), // 1768470000000
137
+ color: "#fee2e2",
138
+ });
139
+
140
+ // Ein Pfeil zwischen zwei Datenpunkten (Koordinaten: Epoche-ms + Wert).
141
+ // `title` ist Metadaten für Toggle-Panels / Legenden – im Diagramm NICHT gezeichnet:
142
+ g.addAnnotation({
143
+ id: "pfeil-sprung",
144
+ title: "Sprung bei Stoerung", // optional, nicht gerendert
145
+ type: "arrow",
146
+ from: { time: 1768469100000, value: 28.5 },
147
+ to: { time: 1768469160000, value: 41.3 },
148
+ color: "#b91c1c",
149
+ });
150
+
151
+ // Sichtbarer Text im Diagramm ist ein eigener `label`-Annotation-Typ:
152
+ g.addAnnotation({
153
+ type: "label",
154
+ at: { time: 1768469160000, value: 41.3 },
155
+ text: "Sprung bei Stoerung",
156
+ anchor: "start",
157
+ dx: 8,
158
+ });
159
+
160
+ // Ein Marker (Epoche-ms):
161
+ g.addMarker({
162
+ time: Date.parse("2026-01-15T09:25:00Z"), // 1768469100000
163
+ value: 41.3,
164
+ label: "Spitze",
165
+ color: "#b91c1c",
166
+ });
167
+
168
+ // Annotationsband unter dem Diagramm. Das Band hat ein `name` (kein title);
169
+ // seine Items verwenden `startTime`/`endTime` und eine CSS-Farb-angabe `fill`:
170
+ g.addAnnotationBand({
171
+ name: "Betriebszustand",
172
+ height: 28,
173
+ items: [
174
+ { startTime: Date.parse("2026-01-15T08:00:00Z"), endTime: Date.parse("2026-01-15T09:20:00Z"), fill: "#dcfce7", label: "Normal" },
175
+ { startTime: Date.parse("2026-01-15T09:20:00Z"), endTime: Date.parse("2026-01-15T10:30:00Z"), fill: "#fee2e2", label: "Anlage gestoppt" },
176
+ ],
177
+ });
178
+ ```
179
+
180
+ ## Teilweise Neudefinition eines Charts
181
+
182
+ `clear()` entfernt eine Kategorie (oder alles, ohne Argument), wodurch sich
183
+ Abschnitte einfach neu aufbauen lassen — z. B. den Datensatz tauschen, aber
184
+ Schwellen und Annotationen behalten:
185
+
186
+ ```ts
187
+ g.clear("series"); // nur Serien entfernen
188
+ g.addSeries({ name: "Temperatur", data });
189
+
190
+ // oder ganz von vorn beginnen:
191
+ g.clear(); // entfernt series, thresholds, annotations, highlights, markers, bands
192
+ ```
193
+
194
+ ## Abschluss-Methoden (Terminal methods)
195
+
196
+ Diese geben den Builder **nicht** zurück. Sie kommen ans Ende der Kette.
197
+
198
+ | Methode | Rückgabe | Typische Anwendung |
199
+ | --- | --- | --- |
200
+ | `toOptions()` | `MLTimeGraphOptions` | Die vollständige, serialisierbare Konfiguration — an anderen Orten verwenden, persistieren oder mit einem anderen Chart diffen. Per Adder gesetzte Felder überschreiben gleichnamige Felder aus dem Konstruktionspfad. |
201
+ | `build()` | `MLTimeGraph` | Eine frische Chart-Instanz pro Aufruf, für erweiterte Nutzung: `project()`, `invertTime()`, `setData()`, manuelle `attachTooltip(...)`-Aufrufe, kustomes Rendern. |
202
+ | `getSvg()` | `string` | Komplette `<svg …>`-Markup. In die Datei schreiben (`fs.writeFileSync("chart.svg", svg)`), als HTTP-Antwort übermitteln oder per `el.innerHTML = g.getSvg()` setzen. Wiederholte Aufrufe rendern neu mit dem aktuellen Builder-Zustand. |
203
+ | `mount(target)` | `MLTimeGraph` | Rendern in ein DOM-Element (Element oder Selektor-String wie `"#chart"`). Ermittelt die Breite automatisch, schreibt responsives SVG und hängt das Tooltip an, falls eines konfiguriert wurde. Wirft, wenn das Ziel nicht gefunden wird. |
204
+
205
+ ### SSR / Reportgenerierung (Node)
206
+
207
+ ```ts
208
+ import { GraphBuilder } from "ml-time-graph";
209
+ import { writeFileSync } from "node:fs";
210
+
211
+ const svg = new GraphBuilder(1200, 600)
212
+ .addSeries({ name: "CPU", data })
213
+ .setAxes({ left: { label: "%", ticks: { count: 5 } } })
214
+ .getSvg();
215
+
216
+ writeFileSync("report-chart.svg", svg);
217
+ ```
@@ -0,0 +1,244 @@
1
+ # Quickstart: `GraphBuilder`
2
+
3
+ `GraphBuilder` is the imperative, object-oriented way to author a chart with
4
+ MLTimeGraph. Instead of assembling one big options object up front, you create
5
+ a builder and add config step by step — every `set*()` / `add*()` method
6
+ returns `this`, so calls chain naturally. It works in the browser **and** on
7
+ Node (SSR, report generation, file output) because rendering just produces an
8
+ SVG string.
9
+
10
+ For the full field-by-field reference of the options that `toOptions()`
11
+ produces, see [GRAPH_JSON_STRUCTURE.md](GRAPH_JSON_STRUCTURE.md).
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ pnpm add ml-time-graph # or: npm i / yarn add
17
+ ```
18
+
19
+ Requires Node >= 18. The build is ESM-only.
20
+
21
+ ## Import
22
+
23
+ ```ts
24
+ import { GraphBuilder } from "ml-time-graph";
25
+ ```
26
+
27
+ All supporting types (`Threshold`, `Annotation`, `Marker`, ...) are exported
28
+ as types from the same entry point.
29
+
30
+ ## Minimal chart
31
+
32
+ ```ts
33
+ const g = new GraphBuilder(800, 400);
34
+
35
+ // Times are epoch milliseconds (number) — never `Date` objects.
36
+ g.addSeries({
37
+ name: "Temperatur",
38
+ data: [
39
+ { time: Date.parse("2026-01-15T08:00:00Z"), value: 20.5 }, // 1768464000000
40
+ { time: Date.parse("2026-01-15T09:00:00Z"), value: 24.1 }, // 1768467600000
41
+ { time: Date.parse("2026-01-15T10:00:00Z"), value: 31.8 }, // 1768471200000
42
+ ],
43
+ });
44
+
45
+ // Into a DOM element …
46
+ g.mount("#chart");
47
+
48
+ // … or as an SVG string (SSR / file / innerHTML)
49
+ const svg = g.getSvg();
50
+ ```
51
+
52
+ Pass width `0` (or omit it) and call `mount()` to auto-detect the pixel width
53
+ from the target's `clientWidth`.
54
+
55
+ ## Chaining
56
+
57
+ Every setter and adder returns the builder, so a complete chart can be one
58
+ statement:
59
+
60
+ ```ts
61
+ new GraphBuilder(900, 420)
62
+ .setLocale("de-DE")
63
+ .addSeries({ name: "Sensor 1", data })
64
+ .addThreshold({ name: "Limit", value: 35, color: "#dc2626" })
65
+ .addHighlight({ startTime: t1, endTime: t2, color: "#fef2f2" }) // epoch ms numbers
66
+ .setXAxis({ label: "Zeit" })
67
+ .setLeftAxis({ label: "Temperatur (°C)" })
68
+ .setLegend(true, "inside-right")
69
+ .mount("#chart");
70
+ ```
71
+
72
+ ## Setters
73
+
74
+ | Method | Effect |
75
+ | --- | --- |
76
+ | `setWidth(w)` / `setHeight(h)` / `setSize(w, h)` | Pixel dimensions. |
77
+ | `setMargin(margin)` or `setMargin(top, right, bottom, left)` | Per-side pixel margins. |
78
+ | `setLocale(locale)` | e.g. `"de-DE"` for date/number formatting. |
79
+ | `setAxes({ x?, left?, right? })` | Replace the entire axes block. |
80
+ | `setXAxis(cfg)` | Patch only the X-axis (spread merge). |
81
+ | `setLeftAxis(cfg)` | Patch the left Y-axis only; leaves the right one untouched. |
82
+ | `setRightAxis(cfg)` | Patch the right Y-axis only. |
83
+ | `setYAxis(index, cfg)` | Patch any Y-axis by index (array auto-expands). |
84
+ | `setLegend(opts)` or `setLegend(show, position?, orientation?)` | Show / place / orient the legend. Positions: `"inside-right"`, `"inside-left"`, `"outside-right"`, `"outside-left"`, `"separate"`. |
85
+ | `setGaps(gapArrayOrConfig)` | Data-gap handling — legacy `Gap[]` or `{ regions?, autoDetect?, minGapMs?, style? }`. |
86
+ | `setTooltip({ show?, format?, snapRadius?, ... })` | Tooltip; only takes effect with `mount()` (there is nothing to hover over in pure `getSvg()` output). Defaults to `show: true` when called. |
87
+
88
+ Axes examples:
89
+
90
+ ```ts
91
+ g.setXAxis({ label: "Zeit", format: (d) => d.toLocaleTimeString("de-DE") });
92
+
93
+ g.setLeftAxis({ label: "Temperatur (°C)", grid: { major: { color: "#e5e7eb" } } });
94
+
95
+ // Two series on different scales:
96
+ g.addSeries({ name: "Temp", data: tempData, yAxisIndex: 0 });
97
+ g.addSeries({ name: "Fluss", data: flowData, yAxisIndex: 1 });
98
+ g.setLeftAxis({ label: "°C" });
99
+ g.setRightAxis({ label: "L/h" });
100
+ ```
101
+
102
+ ## Adders
103
+
104
+ Each adder appends one item to its internal list; the `*All` / plural variants
105
+ append arrays. All return `this`.
106
+
107
+ | Method | Adds |
108
+ | --- | --- |
109
+ | `addSeries(s)` / `addSeriesAll(s[])` | A time series (`AnySeries`: raw `DataPoint[]` or aggregated min/max/avg). |
110
+ | `addThreshold(t)` / `addThresholds(t[])` | A threshold: line, optional fill zone, optional label. |
111
+ | `addAnnotation(a)` / `addAnnotations(a[])` | Free-form overlay — one of the variants `line`, `arrow`, `rect`, `point`, `label` (discriminated on the `type` field). |
112
+ | `addHighlight(h)` | A highlighted time range drawn behind the data. |
113
+ | `addMarker(m)` | A vertical pin at a timestamp, optional value dot + label. |
114
+ | `addAnnotationBand(band)` | A horizontal strip below the chart showing colored time ranges with items/labels. |
115
+
116
+ Examples:
117
+
118
+ ```ts
119
+ // Threshold: `fill` is a string ("above" | "below" | "none") and `line` is
120
+ // a string ("solid" | "dashed" | "dotted" | "none"); opacity is a separate field.
121
+ g.addThreshold({
122
+ name: "Max",
123
+ value: 35,
124
+ color: "#dc2626",
125
+ fill: "above",
126
+ fillOpacity: 0.1,
127
+ line: "dashed",
128
+ label: { position: "right" }, // or just `label: "Max"` / `label: false`
129
+ });
130
+
131
+ // Highlighted region (incident window). `startTime`/`endTime` are epoch ms numbers:
132
+ g.addHighlight({
133
+ startTime: Date.parse("2026-01-15T09:10:00Z"), // 1768468200000
134
+ endTime: Date.parse("2026-01-15T09:40:00Z"), // 1768470000000
135
+ color: "#fee2e2",
136
+ });
137
+
138
+ // An arrow between two data points (coordinates are epoch ms + value numbers).
139
+ // `title` is metadata for toggle panels / legends — not drawn in the chart:
140
+ g.addAnnotation({
141
+ id: "arrow-spike",
142
+ title: "Sprung bei Stoerung", // optional, not rendered
143
+ type: "arrow",
144
+ from: { time: 1768469100000, value: 28.5 },
145
+ to: { time: 1768469160000, value: 41.3 },
146
+ color: "#b91c1c",
147
+ });
148
+
149
+ // Visible text on the chart is a separate `label` annotation:
150
+ g.addAnnotation({
151
+ type: "label",
152
+ at: { time: 1768469160000, value: 41.3 },
153
+ text: "Sprung bei Stoerung",
154
+ anchor: "start",
155
+ dx: 8,
156
+ });
157
+
158
+ // A marker pin (epoch ms):
159
+ g.addMarker({
160
+ time: Date.parse("2026-01-15T09:25:00Z"), // 1768469100000
161
+ value: 41.3,
162
+ label: "Spitze",
163
+ color: "#b91c1c",
164
+ });
165
+
166
+ // Annotation band below the chart. The band has a `name` (not title);
167
+ // its items use `startTime`/`endTime` and a CSS-color `fill`:
168
+ g.addAnnotationBand({
169
+ name: "Betriebszustand",
170
+ height: 28,
171
+ items: [
172
+ { startTime: Date.parse("2026-01-15T08:00:00Z"), endTime: Date.parse("2026-01-15T09:20:00Z"), fill: "#dcfce7", label: "Normal" },
173
+ { startTime: Date.parse("2026-01-15T09:20:00Z"), endTime: Date.parse("2026-01-15T10:30:00Z"), fill: "#fee2e2", label: "Anlage gestoppt" },
174
+ ],
175
+ });
176
+ ```
177
+
178
+ ## Rebuilding parts of a chart
179
+
180
+ `clear()` wipes one category (or everything when called with no argument),
181
+ which makes it easy to rebuild sections — e.g. swap the dataset while keeping
182
+ thresholds and annotations:
183
+
184
+ ```ts
185
+ g.clear("series"); // remove only series
186
+ g.addSeries({ name: "Temperatur", data });
187
+
188
+ // or start completely over:
189
+ g.clear(); // removes series, thresholds, annotations, highlights, markers, bands
190
+ ```
191
+
192
+ ## Terminal methods
193
+
194
+ These **do not** return the builder. Call them last.
195
+
196
+ | Method | Returns | Typical use |
197
+ | --- | --- | --- |
198
+ | `toOptions()` | `MLTimeGraphOptions` | The complete, serializable config — pass it to other code, persist it, or diff against another chart. Fields added via adders win over same-named fields set through the constructor path. |
199
+ | `build()` | `MLTimeGraph` | A fresh chart instance each call, for advanced use: `project()`, `invertTime()`, `setData()`, manual `attachTooltip(...)` calls, custom rendering. |
200
+ | `getSvg()` | `string` | Full `<svg …>` markup. Write to a file (`fs.writeFileSync("chart.svg", svg)`), send as an HTTP response body, or set via `el.innerHTML = g.getSvg()`. Repeated calls re-render with the current builder state. |
201
+ | `mount(target)` | `MLTimeGraph` | Render into a DOM element (element or selector string like `"#chart"`). Auto-detects width when not set, writes responsive SVG, and attaches the tooltip if one was configured. Throws if the target is not found. |
202
+
203
+ ### SSR / report generation (Node)
204
+
205
+ ```ts
206
+ import { GraphBuilder } from "ml-time-graph";
207
+ import { writeFileSync } from "node:fs";
208
+
209
+ const svg = new GraphBuilder(1200, 600)
210
+ .addSeries({ name: "CPU", data })
211
+ .setAxes({ left: { label: "%", ticks: { count: 5 } } })
212
+ .getSvg();
213
+
214
+ writeFileSync("report-chart.svg", svg);
215
+ ```
216
+
217
+ ### Browser
218
+
219
+ ```ts
220
+ g.mount("#chart"); // renders + tooltip (if set)
221
+
222
+ // … or grab the instance for further interaction:
223
+ const chart = g.build();
224
+ const x = chart.project(time).x; // data → pixel mapping
225
+ const t = chart.invertTime(x); // pixel → time
226
+ ```
227
+
228
+ ## Relationship to the other entry points
229
+
230
+ - **`mount(target, options)`** — one-shot: build from a single options object
231
+ and install it. Simplest API for dashboards.
232
+ - **`new MLTimeGraph(options)`** — instance-level construction without any
233
+ DOM coupling (project/invert/setData, custom renderers).
234
+ - **`GraphBuilder`** — step-by-step config accumulation with clean terminal
235
+ methods; the best fit when the chart is assembled programmatically or the
236
+ output is a file / SSR payload.
237
+ - The companion builders (`TimeSeriesBuilder`, `ThresholdBuilder`, …) are
238
+ exported from the same entry point and work on individual items — use them
239
+ with or without `GraphBuilder`.
240
+
241
+ For the complete, field-by-field structure of what `toOptions()` produces, see
242
+ [GRAPH_JSON_STRUCTURE.md](GRAPH_JSON_STRUCTURE.md). For general usage topics
243
+ (MKT lines, overlays, aggregation) see [USAGE.md](USAGE.md); for design-level
244
+ details see [USAGE.md](USAGE.md).
package/README.de.md CHANGED
@@ -91,7 +91,7 @@ Demo-Galerie zu sehen (`pnpm dev`).
91
91
 
92
92
  ## 🔄 Go-Port & 1:1 Rendering-Parität
93
93
 
94
- Benötigst du serverseitiges Rendering der exakt gleichen Charts? Es gibt einen 1:1 Go-Port dieser Engine unter **[gitlab.com/mlc0911/mlctimegraph/go-time-graph](https://gitlab.com/mlc0911/mlctimegraph/go-time-graph)**.
94
+ Benötigst du serverseitiges Rendering der exakt gleichen Charts? Es gibt einen 1:1 Go-Port dieser Engine unter **[gitlab.com/mlc0911/mlctimegraph/go-time-graph](https://gitlab.com/mlc0911/mlctimegraph/-/tree/main/go-time-graph)**.
95
95
 
96
96
  Sowohl die TypeScript- als auch die Go-Bibliothek:
97
97
  - Verarbeiten das **exakt gleiche JSON-Konfigurationsschema**.
@@ -101,6 +101,36 @@ Sowohl die TypeScript- als auch die Go-Bibliothek:
101
101
 
102
102
  ---
103
103
 
104
+ ## 📜 Versionsverlauf
105
+
106
+ Beide Bibliotheken werden im Gleichschritt unter einer Versionsnummer veröffentlicht —
107
+ deshalb gibt es **ein** Changelog für beide: [CHANGELOG.md](https://gitlab.com/mlc0911/mlctimegraph/-/blob/main/CHANGELOG.md).
108
+
109
+ ---
110
+
111
+ ## 📄 PDF-Ausgabe
112
+
113
+ Die Engine zeichnet kein SVG — sie erzeugt eine Liste von Zeichenbefehlen, und SVG ist ein
114
+ Abnehmer dieser Liste. **[mlctimegraph-pdf](https://gitlab.com/mlc0911/mlctimegraphpdf)** ist der
115
+ zweite: Es geht dieselben Befehle durch und schreibt native PDF-Vektoren. Kein Browser, kein
116
+ SVG-Parsen, kein Headless-Chromium — und es ist dasselbe Diagramm, weil es aus denselben
117
+ Befehlen kommt.
118
+
119
+ Es liest dasselbe JSON, mit dem auch das Diagramm konfiguriert wird:
120
+
121
+ ```bash
122
+ go get gitlab.com/mlc0911/mlctimegraphpdf
123
+ mtg-pdf -in chart.json -out chart.pdf
124
+ ```
125
+
126
+ Noch jung: Version 0.2.0, nicht 1.0, und ein, zwei Fähigkeiten hinter dieser Bibliothek. Was man
127
+ vorher wissen sollte — eine Füllung auf einem *Pfad*, also die Fläche unter einer Linie oder
128
+ einer Treppe, kommt derzeit deckend und ohne Schraffur heraus, weil nur Rechtecke beides
129
+ durchreichen. Linien, Marker, Text, Strichmuster, Kurvengeometrie und rechteckige Füllungen sind
130
+ da.
131
+
132
+ ---
133
+
104
134
  ## Warum schon wieder eine neue Library?
105
135
 
106
136
  Alle Libraries, die ich in der Vergangenheit professionell genutzt habe, haben
package/README.md CHANGED
@@ -91,7 +91,7 @@ library, all live in the demo gallery (`pnpm dev`).
91
91
 
92
92
  ## 🔄 Go Port & 1:1 Rendering Parity
93
93
 
94
- Need server-side rendering of the exact same charts? There is a 1:1 Go port of this engine available at **[gitlab.com/mlc0911/mlctimegraph/go-time-graph](https://gitlab.com/mlc0911/mlctimegraph/go-time-graph)**.
94
+ Need server-side rendering of the exact same charts? There is a 1:1 Go port of this engine available at **[gitlab.com/mlc0911/mlctimegraph/go-time-graph](https://gitlab.com/mlc0911/mlctimegraph/-/tree/main/go-time-graph)**.
95
95
 
96
96
  Both the TypeScript and Go libraries:
97
97
  - Process the **exact same JSON configuration schema**.
@@ -101,6 +101,34 @@ Both the TypeScript and Go libraries:
101
101
 
102
102
  ---
103
103
 
104
+ ## 📜 Release history
105
+
106
+ Both libraries are released in lockstep on one version number, so there is **one**
107
+ changelog for both: [CHANGELOG.md](https://gitlab.com/mlc0911/mlctimegraph/-/blob/main/CHANGELOG.md).
108
+
109
+ ---
110
+
111
+ ## 📄 PDF Output
112
+
113
+ The engine does not draw SVG — it produces a list of draw commands, and SVG is one consumer
114
+ of that list. **[mlctimegraph-pdf](https://gitlab.com/mlc0911/mlctimegraphpdf)** is the second
115
+ one: it walks the same commands and writes native PDF vectors. No browser, no SVG parsing, no
116
+ headless Chromium — and it is the same chart, because it comes from the same commands.
117
+
118
+ It reads the same JSON your chart is configured with:
119
+
120
+ ```bash
121
+ go get gitlab.com/mlc0911/mlctimegraphpdf
122
+ mtg-pdf -in chart.json -out chart.pdf
123
+ ```
124
+
125
+ Early days: it is at 0.2.0, not 1.0, and trails this library by a feature or two. Worth knowing
126
+ before you rely on it — a fill on a *path* (the area under a line or a step) currently renders
127
+ opaque and without its hatch pattern, because only rectangles carry those through. Lines,
128
+ markers, text, dash patterns, curve geometry and rectangular fills are there.
129
+
130
+ ---
131
+
104
132
  ## Why another chart library?
105
133
 
106
134
  Every charting library I relied on professionally eventually switched its license
package/SKILLS.md CHANGED
@@ -32,6 +32,7 @@ mount('#chart', {
32
32
  - `new MLTimeGraph(options)`: The core headless engine when working with options objects directly — use for Node.js SSR, headless testing, or custom render pipelines.
33
33
  - Builders (`GraphBuilder`, etc.): The fluent, imperative chaining API — use when assembling charts dynamically across conditional branches.
34
34
  - 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.
35
+ - 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.
35
36
 
36
37
  ## Package Entry Points
37
38
 
package/USAGE.md CHANGED
@@ -58,6 +58,46 @@ the browser and server-side. For DOM-specific behaviour, extend
58
58
  A `series` entry is either a **raw** time series (`DataPoint[]` = `{ time, value }`)
59
59
  or an **aggregated** series (`AggregatedPoint[]` = `{ time, min, max, avg, count }`).
60
60
 
61
+ ### Your data is shaped differently — `toDataPoints`
62
+
63
+ `{ time, value }` is what the chart reads everywhere: scales, run splitting, zone
64
+ cuts, the tooltip, the Go port. It stays strict on purpose. The give is at the
65
+ boundary — one conversion, instead of a `.map()` in every caller:
66
+
67
+ ```ts
68
+ import { toDataPoints, toSeries } from 'ml-time-graph';
69
+
70
+ // Tuples
71
+ toDataPoints([[1758434400000, 2.1], [1758438000000, 3.4]]);
72
+
73
+ // Other field names, Unix seconds
74
+ toDataPoints(rows, { time: 'ts', value: 'val', timeUnit: 's' });
75
+
76
+ // ISO strings or Date objects — recognised on their own
77
+ toDataPoints(rows, { time: 'recorded_at', value: 'reading' });
78
+
79
+ // Anything else: read it yourself
80
+ toDataPoints(rows, { time: (r) => r.meta.at, value: (r) => r.payload.power.kw });
81
+
82
+ // Series name and conversion in one line
83
+ series: [toSeries('Load', rows, { time: 'ts', value: 'val', timeUnit: 's' })];
84
+ ```
85
+
86
+ Details worth knowing:
87
+
88
+ - **Numbers are milliseconds** unless you say otherwise. No guessing by default —
89
+ `timeUnit: 's'` for Unix seconds, `'auto'` to detect them. `'auto'` leaves a
90
+ relative time base (0, 1000, 2000 …) alone, so it cannot silently shift it.
91
+ - **A missing reading becomes a gap**, not a zero: `null`, `undefined`, `NaN` and
92
+ `''` all break the line. Drawing a missing measurement as 0 would claim a value
93
+ the sensor never reported.
94
+ - **Numeric strings are converted** (`'21.5'` → `21.5`) — the usual CSV and JSON
95
+ case. A non-numeric string throws and names the row, instead of quietly
96
+ producing an empty chart.
97
+ - **Sorted by time** by default; pass `sort: false` if you sorted already.
98
+
99
+ See `demos/adapters.html` — the same chart from four input shapes.
100
+
61
101
  Visual styling lives in a nested `style` block — `line`, `fill`, `markers`, `shadow`,
62
102
  `gap`. Any combination is allowed: set `line` for a line, add `fill` for an area
63
103
  underneath, add `markers` for points, set `style.line: false` for points only.
@@ -74,12 +114,16 @@ underneath, add `markers` for points, set `style.line: false` for points only.
74
114
  }
75
115
 
76
116
  // Step + smoothed overlay (multi-line array — same data, both rendered)
117
+ // Each entry keeps its own shape: the first is the staircase, the second a
118
+ // smoothed line through the readings. An entry without a `shape` of its own is
119
+ // a straight line — it does NOT inherit the first one's. The first entry is
120
+ // the series' shape: fill, zone colours and markers follow it.
77
121
  {
78
122
  name: 'CPU',
79
123
  data,
80
124
  style: { line: [
81
125
  { color: '#999', width: 1, shape: 'step' },
82
- { color: '#3b82f6', width: 2, smoothing: true },
126
+ { color: '#3b82f6', width: 2, smoothing: true, opacity: 0.8 },
83
127
  ] },
84
128
  }
85
129
 
@@ -176,6 +220,23 @@ style: { fill: fillBetweenThresholds({
176
220
 
177
221
  A `FillBound` is `'series' | 'chartTop' | 'chartBottom' | { threshold: name } | { value: n }`.
178
222
 
223
+ A fill follows the shape of its line. With `shape: 'step'` the area is a
224
+ staircase too — it never claims a value between two readings, which is the whole
225
+ point of a step for state-like quantities (runtime, stage, operating mode):
226
+
227
+ ```ts
228
+ style: {
229
+ line: { color: '#1d4ed8', width: 2, shape: 'step' },
230
+ fill: { color: '#1d4ed822', hatch: 'classic-diagonal' },
231
+ }
232
+ ```
233
+
234
+ A threshold bound cuts the vertical jump at the reading's timestamp, so the part
235
+ above a limit is a rectangle, not a triangle. Steps are never smoothed: a
236
+ `smoothing: true` next to `shape: 'step'` is ignored for both line and fill.
237
+ (Before 1.7.0 the area ran as a ramp underneath the staircase — see
238
+ `demos/steps.html`.)
239
+
179
240
  For *classified* (mutually-exclusive) zone bands, give a region both a `side`
180
241
  and an `outer` bound — the region renders only in X-spans where the line's
181
242
  value is between the fixed inner bound and `outer`:
@@ -119,6 +119,7 @@ declare class SeriesProcessor {
119
119
  static splitByBoundaries<T>(run: T[], boundaries: number[], getValue: (p: T) => number, interpolate: (p1: T, p2: T, t: number) => T): {
120
120
  data: T[];
121
121
  zoneIndex: number;
122
+ zoneLow: number;
122
123
  }[];
123
124
  /**
124
125
  * Splits a contiguous run into two groups: those below and those at/above a threshold.