@devicechain/widget-sdk 0.24.0 → 0.25.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.
- package/README.md +15 -0
- package/dist/chunks/{chunk-A5BJ2ALW.js → chunk-G6I5HKQM.js} +36 -105
- package/dist/chunks/chunk-G6I5HKQM.js.map +7 -0
- package/dist/chunks/chunk-IG6DBHKZ.js +109 -0
- package/dist/chunks/chunk-IG6DBHKZ.js.map +7 -0
- package/dist/chunks/chunk-PECV5KDV.js +154 -0
- package/dist/chunks/chunk-PECV5KDV.js.map +7 -0
- package/dist/chunks/export-menu-727YDRIA.js +184 -0
- package/dist/chunks/export-menu-727YDRIA.js.map +7 -0
- package/dist/context.d.ts +22 -0
- package/dist/echarts.js +9 -3
- package/dist/echarts.js.map +2 -2
- package/dist/empty-state.d.ts +38 -0
- package/dist/empty-state.js +105 -0
- package/dist/empty-state.js.map +7 -0
- package/dist/export-csv.d.ts +12 -0
- package/dist/export-menu.d.ts +24 -0
- package/dist/frame.d.ts +3 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +103 -166
- package/dist/index.js.map +4 -4
- package/dist/widget-export.d.ts +7 -0
- package/package.json +7 -3
- package/dist/chunks/chunk-A5BJ2ALW.js.map +0 -7
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
// src/export-csv.ts
|
|
2
|
+
var PLAIN_NUMBER = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
|
|
3
|
+
var FORMULA_LEAD = /^[=+\-@=+-@]/;
|
|
4
|
+
function formulaLike(text) {
|
|
5
|
+
if (/^[\t\r]/.test(text)) return true;
|
|
6
|
+
const lead = text.replace(/^\s+/, "");
|
|
7
|
+
return FORMULA_LEAD.test(lead) && !PLAIN_NUMBER.test(text);
|
|
8
|
+
}
|
|
9
|
+
function csvCell(value) {
|
|
10
|
+
if (value === null || value === void 0) return "";
|
|
11
|
+
if (typeof value === "number") return Number.isFinite(value) ? String(value) : "";
|
|
12
|
+
let text = typeof value === "string" ? value : String(value);
|
|
13
|
+
if (typeof value === "string" && formulaLike(text)) text = `'${text}`;
|
|
14
|
+
return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
|
|
15
|
+
}
|
|
16
|
+
function toCsv(table) {
|
|
17
|
+
const lines = [table.columns.map(csvCell).join(",")];
|
|
18
|
+
for (const row of table.rows) lines.push(table.columns.map((_c, i) => csvCell(row[i])).join(","));
|
|
19
|
+
return lines.join("\r\n") + "\r\n";
|
|
20
|
+
}
|
|
21
|
+
var WINDOWS_RESERVED = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/i;
|
|
22
|
+
function safeFileStem(name, fallback = "widget") {
|
|
23
|
+
const stem = name.normalize("NFKD").replace(/\p{M}+/gu, "").replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^[-.]+/, "").slice(0, 160).replace(/[-.]+$/, "");
|
|
24
|
+
if (stem === "") return fallback;
|
|
25
|
+
return WINDOWS_RESERVED.test(stem) ? `_${stem}` : stem;
|
|
26
|
+
}
|
|
27
|
+
var UTF8_BOM = String.fromCharCode(65279);
|
|
28
|
+
function downloadBlob(filename, blob) {
|
|
29
|
+
const url = URL.createObjectURL(blob);
|
|
30
|
+
const a = document.createElement("a");
|
|
31
|
+
a.href = url;
|
|
32
|
+
a.download = filename;
|
|
33
|
+
document.body.appendChild(a);
|
|
34
|
+
a.click();
|
|
35
|
+
a.remove();
|
|
36
|
+
setTimeout(() => URL.revokeObjectURL(url), 0);
|
|
37
|
+
}
|
|
38
|
+
function downloadCsv(table) {
|
|
39
|
+
downloadBlob(`${safeFileStem(table.name)}.csv`, new Blob([UTF8_BOM, toCsv(table)], { type: "text/csv;charset=utf-8" }));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// src/export-menu.ts
|
|
43
|
+
var WORDS = {
|
|
44
|
+
en: { button: "Export data", csv: "Download CSV", image: "Download image (PNG)" },
|
|
45
|
+
es: { button: "Exportar datos", csv: "Descargar CSV", image: "Descargar imagen (PNG)" }
|
|
46
|
+
};
|
|
47
|
+
function opaqueBackground(el) {
|
|
48
|
+
for (let node = el; node; node = node.parentElement) {
|
|
49
|
+
const color = getComputedStyle(node).backgroundColor;
|
|
50
|
+
if (color && color !== "transparent" && !/^rgba\(.*,\s*0\)$/.test(color) && !/\/\s*0\)$/.test(color)) return color;
|
|
51
|
+
}
|
|
52
|
+
return "#ffffff";
|
|
53
|
+
}
|
|
54
|
+
function fileStamp(at) {
|
|
55
|
+
return at.toISOString().replace(/[-:]/g, "").replace(/\d\d\.\d+Z$/, "Z");
|
|
56
|
+
}
|
|
57
|
+
function spanish() {
|
|
58
|
+
const lang = typeof document !== "undefined" && document.documentElement.lang || typeof navigator !== "undefined" && navigator.language || "";
|
|
59
|
+
return lang.toLowerCase().startsWith("es");
|
|
60
|
+
}
|
|
61
|
+
var MENU_STYLE = "position:absolute;top:100%;right:4px;z-index:5;margin-top:2px;padding:4px 0;min-width:160px;background:hsl(var(--card));border:1px solid hsl(var(--border));border-radius:6px;box-shadow:0 4px 12px rgb(0 0 0 / 0.15)";
|
|
62
|
+
var ITEM_STYLE = "display:block;width:100%;padding:6px 12px;border:none;background:transparent;color:hsl(var(--card-foreground));font:inherit;font-size:0.8125rem;text-align:left;white-space:nowrap;cursor:pointer";
|
|
63
|
+
function openExportMenu(host, o) {
|
|
64
|
+
const words = spanish() ? WORDS.es : WORDS.en;
|
|
65
|
+
const menu = document.createElement("div");
|
|
66
|
+
menu.setAttribute("role", "menu");
|
|
67
|
+
menu.setAttribute("data-widget-export-menu", "");
|
|
68
|
+
menu.style.cssText = MENU_STYLE;
|
|
69
|
+
let open = true;
|
|
70
|
+
const close = () => {
|
|
71
|
+
if (!open) return;
|
|
72
|
+
open = false;
|
|
73
|
+
document.removeEventListener("pointerdown", away);
|
|
74
|
+
menu.remove();
|
|
75
|
+
};
|
|
76
|
+
const done = (refocus) => {
|
|
77
|
+
if (!open) return;
|
|
78
|
+
close();
|
|
79
|
+
o.onClose(refocus);
|
|
80
|
+
};
|
|
81
|
+
function away(e) {
|
|
82
|
+
if (!(e.target instanceof Node) || !host.contains(e.target)) done(false);
|
|
83
|
+
}
|
|
84
|
+
const csv = async () => {
|
|
85
|
+
try {
|
|
86
|
+
const table = await o.exportRows?.();
|
|
87
|
+
if (table) downloadCsv(table);
|
|
88
|
+
} catch (err) {
|
|
89
|
+
console.error("Widget export failed", err);
|
|
90
|
+
}
|
|
91
|
+
done(true);
|
|
92
|
+
};
|
|
93
|
+
const png = async () => {
|
|
94
|
+
const url = o.image?.({ backgroundColor: opaqueBackground(o.frameElement()) });
|
|
95
|
+
if (url) {
|
|
96
|
+
const named = await Promise.resolve().then(() => o.exportRows?.()).then((t) => t?.name, () => void 0);
|
|
97
|
+
const a = document.createElement("a");
|
|
98
|
+
a.href = url;
|
|
99
|
+
a.download = `${safeFileStem(named ?? `${o.title ?? ""}-${fileStamp(/* @__PURE__ */ new Date())}`)}.png`;
|
|
100
|
+
document.body.appendChild(a);
|
|
101
|
+
a.click();
|
|
102
|
+
a.remove();
|
|
103
|
+
}
|
|
104
|
+
done(true);
|
|
105
|
+
};
|
|
106
|
+
const items = [];
|
|
107
|
+
const add = (label, run) => {
|
|
108
|
+
const item = document.createElement("button");
|
|
109
|
+
item.type = "button";
|
|
110
|
+
item.setAttribute("role", "menuitem");
|
|
111
|
+
item.style.cssText = ITEM_STYLE;
|
|
112
|
+
item.textContent = label;
|
|
113
|
+
item.addEventListener("click", () => void run());
|
|
114
|
+
items.push(item);
|
|
115
|
+
menu.appendChild(item);
|
|
116
|
+
};
|
|
117
|
+
if (o.exportRows) add(words.csv, csv);
|
|
118
|
+
if (o.image) add(words.image, png);
|
|
119
|
+
menu.addEventListener("keydown", (e) => {
|
|
120
|
+
if (e.key === "Escape") {
|
|
121
|
+
e.stopPropagation();
|
|
122
|
+
done(true);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
|
|
126
|
+
const at = items.indexOf(document.activeElement);
|
|
127
|
+
items[(at + (e.key === "ArrowDown" ? 1 : items.length - 1)) % items.length]?.focus();
|
|
128
|
+
e.preventDefault();
|
|
129
|
+
});
|
|
130
|
+
document.addEventListener("pointerdown", away);
|
|
131
|
+
host.appendChild(menu);
|
|
132
|
+
items[0]?.focus();
|
|
133
|
+
return close;
|
|
134
|
+
}
|
|
135
|
+
var ICON = '<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 2v8M4.5 6.5 8 10l3.5-3.5M2.5 13.5h11"/></svg>';
|
|
136
|
+
function mountExportButton(host, size, source) {
|
|
137
|
+
const words = spanish() ? WORDS.es : WORDS.en;
|
|
138
|
+
const button = document.createElement("button");
|
|
139
|
+
button.type = "button";
|
|
140
|
+
button.setAttribute("aria-label", words.button);
|
|
141
|
+
button.title = words.button;
|
|
142
|
+
button.setAttribute("aria-haspopup", "menu");
|
|
143
|
+
button.innerHTML = ICON;
|
|
144
|
+
const look = (open) => {
|
|
145
|
+
button.setAttribute("aria-expanded", String(open));
|
|
146
|
+
button.style.cssText = `width:${size}px;height:${size}px;padding:0;display:inline-flex;align-items:center;justify-content:center;border:none;border-radius:4px;color:hsl(var(--muted-foreground));cursor:pointer;background:${open ? "hsl(var(--muted))" : "transparent"}`;
|
|
147
|
+
};
|
|
148
|
+
look(false);
|
|
149
|
+
let close;
|
|
150
|
+
button.addEventListener("click", () => {
|
|
151
|
+
if (close) {
|
|
152
|
+
close();
|
|
153
|
+
close = void 0;
|
|
154
|
+
look(false);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
look(true);
|
|
158
|
+
const s = source();
|
|
159
|
+
close = openExportMenu(host, {
|
|
160
|
+
// Read at the click, so an item acts on the widget as it is then.
|
|
161
|
+
exportRows: s.exportRows && (() => source().exportRows?.()),
|
|
162
|
+
image: s.image && ((o) => source().image?.(o)),
|
|
163
|
+
title: s.title,
|
|
164
|
+
frameElement: s.frameElement,
|
|
165
|
+
onClose: (refocus) => {
|
|
166
|
+
close = void 0;
|
|
167
|
+
look(false);
|
|
168
|
+
if (refocus) button.focus();
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
host.appendChild(button);
|
|
173
|
+
return () => {
|
|
174
|
+
close?.();
|
|
175
|
+
button.remove();
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
export {
|
|
179
|
+
fileStamp,
|
|
180
|
+
mountExportButton,
|
|
181
|
+
opaqueBackground,
|
|
182
|
+
openExportMenu
|
|
183
|
+
};
|
|
184
|
+
//# sourceMappingURL=export-menu-727YDRIA.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/export-csv.ts", "../../src/export-menu.ts"],
|
|
4
|
+
"sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// CSV for the frame's export menu: RFC 4180 encoding and a spreadsheet-formula guard. Loaded with\n// the menu, only when the viewer opens it.\n//\n// This is the console's list-export encoder (apps/console/src/lib/csv.ts) copied, not imported: a\n// widget package cannot depend on an application. Keep the two in step.\n//\n// \uD83D\uDD34 An export is a spreadsheet opened by a person, and the cells are attacker-influenced (a device\n// name, a measurement name, a title). A TEXT cell that begins with `=`, `+`, `-`, `@`, tab or carriage\n// return is read by Excel/Sheets as a FORMULA, so it is written with a leading single quote. The guard\n// is applied here, once, to every text cell and heading; a widget cannot forget it per column. A number\n// is written as a number (never guarded: -12.5 must stay summable) and a string that is entirely a plain\n// number is left alone for the same reason.\n//\n// \uD83D\uDD34 UTF-8 WITH A BYTE-ORDER MARK, on purpose. Units are not ASCII (\"\u00B0C\", \"\u00B5S/cm\") and neither are\n// many device names, and Excel, the tool an auditor opens this in, decodes a BOM-less file as the\n// system code page and shows \"\u00C2\u00B0C\". The cost is that a program reading the file raw sees U+FEFF at\n// the start of the first heading; the ones that matter strip it (Python's utf-8-sig, every\n// spreadsheet). A consumer that cannot should drop the first three bytes.\n\nimport type { WidgetExportCell, WidgetExportTable } from './widget-export';\n\n// A string that is entirely a plain number cannot start a formula, and quoting it would turn a\n// reading like -12.5 into text a spreadsheet will not sum.\nconst PLAIN_NUMBER = /^[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$/;\n\n// The formula triggers, plus their full-width forms (an IME produces those, and some spreadsheet\n// builds normalise them on entry). Matched after any leading whitespace too: an importer that trims\n// cells would otherwise hand ` =cmd` to the formula parser with its guard trimmed away.\nconst FORMULA_LEAD = /^[=+\\-@\uFF1D\uFF0B\uFF0D\uFF20]/;\n\n/** True when a spreadsheet could read the text as a formula. */\nexport function formulaLike(text: string): boolean {\n if (/^[\\t\\r]/.test(text)) return true;\n const lead = text.replace(/^\\s+/, '');\n return FORMULA_LEAD.test(lead) && !PLAIN_NUMBER.test(text);\n}\n\n/** Encodes one cell: formula-guarded, then quoted when RFC 4180 requires it. */\nexport function csvCell(value: WidgetExportCell): string {\n if (value === null || value === undefined) return '';\n if (typeof value === 'number') return Number.isFinite(value) ? String(value) : '';\n let text = typeof value === 'string' ? value : String(value);\n if (typeof value === 'string' && formulaLike(text)) text = `'${text}`;\n return /[\",\\r\\n]/.test(text) ? `\"${text.replace(/\"/g, '\"\"')}\"` : text;\n}\n\n/** The table as CSV text: headings first, CRLF line endings, a trailing CRLF. */\nexport function toCsv(table: Pick<WidgetExportTable, 'columns' | 'rows'>): string {\n const lines = [table.columns.map(csvCell).join(',')];\n for (const row of table.rows) lines.push(table.columns.map((_c, i) => csvCell(row[i])).join(','));\n return lines.join('\\r\\n') + '\\r\\n';\n}\n\n// A name safe on every file system: what is not a letter, digit, dot, dash or underscore becomes a\n// dash, runs collapse, and a name that is nothing but separators falls to `fallback`. An accented letter\n// keeps its base letter (the accent is a combining mark once decomposed, and is dropped). A name Windows\n// reserves for a device (`CON`, `nul.csv`, `COM1`: reserved whatever the extension) is prefixed with an\n// underscore, since a widget title is the tenant's to choose.\nconst WINDOWS_RESERVED = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\\.|$)/i;\nexport function safeFileStem(name: string, fallback = 'widget'): string {\n const stem = name\n .normalize('NFKD')\n .replace(/\\p{M}+/gu, '')\n .replace(/[^A-Za-z0-9._-]+/g, '-')\n .replace(/^[-.]+/, '')\n .slice(0, 160)\n .replace(/[-.]+$/, '');\n if (stem === '') return fallback;\n return WINDOWS_RESERVED.test(stem) ? `_${stem}` : stem;\n}\n\n// U+FEFF, spelled as a code point so no editor can silently drop the invisible character.\nconst UTF8_BOM = String.fromCharCode(0xfeff);\n\n/** Saves bytes as a file download. */\nexport function downloadBlob(filename: string, blob: Blob): void {\n const url = URL.createObjectURL(blob);\n const a = document.createElement('a');\n a.href = url;\n a.download = filename;\n document.body.appendChild(a);\n a.click();\n a.remove();\n setTimeout(() => URL.revokeObjectURL(url), 0);\n}\n\n/** Saves the table as `<name>.csv`: UTF-8 with a byte-order mark (see the top of this file). */\nexport function downloadCsv(table: WidgetExportTable): void {\n downloadBlob(`${safeFileStem(table.name)}.csv`, new Blob([UTF8_BOM, toCsv(table)], { type: 'text/csv;charset=utf-8' }));\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// The frame's export button, its menu and what the menu's items do (Download CSV, Download image).\n// Its own chunk, with the CSV encoder: fetched by a frame that has something to export (frame.tsx\n// draws only the box the button sits in), so a board's first download holds none of it.\n//\n// - Download CSV builds the table at the moment of the click, from what the widget is showing;\n// - Download image reads the chart's canvas on the card's own background (a canvas is transparent,\n// and a dark theme's light text on white is unreadable), at twice the on-screen resolution.\n//\n// \uD83D\uDD34 PLAIN DOM, AND IMPORTS NOTHING BUT THE ENCODER. Every chunk a lazy chunk reaches must be in the\n// same group as the code a board always loads, or the app's bundler splits that shared code into a\n// file of its own just for this chunk. A React menu here split React out of the shared vendor chunk,\n// and the lost compression cost every board ~0.8 KB of its first download whether or not it held an\n// exportable widget; an eager React button instead cost ~0.6 KB. So this builds its handful of elements by hand, reads the viewer's language the\n// way freshness.ts does, and names theme colours as the `hsl(var(--token))` that theme.ts's css() writes.\n\nimport { downloadCsv, safeFileStem } from './export-csv';\nimport type { WidgetImageSource } from './context';\nimport type { WidgetExportResult } from './widget-export';\n\nconst WORDS = {\n en: { button: 'Export data', csv: 'Download CSV', image: 'Download image (PNG)' },\n es: { button: 'Exportar datos', csv: 'Descargar CSV', image: 'Descargar imagen (PNG)' },\n};\n\nexport interface ExportMenuOptions {\n exportRows: (() => WidgetExportResult) | undefined;\n image: WidgetImageSource | undefined;\n // The frame's own title, the name of a file with nothing better to call it.\n title: string | undefined;\n // The element whose background an image is drawn on.\n frameElement: () => Element | null;\n // The menu has closed. `refocus` when the focus belongs back on the button (an item was picked,\n // Escape was pressed); not when the viewer clicked somewhere else.\n onClose: (refocus: boolean) => void;\n}\n\n// The first opaque background at or above `el`: what the card is drawn on. White when nothing in the\n// page sets one.\nexport function opaqueBackground(el: Element | null): string {\n for (let node: Element | null = el; node; node = node.parentElement) {\n const color = getComputedStyle(node).backgroundColor;\n if (color && color !== 'transparent' && !/^rgba\\(.*,\\s*0\\)$/.test(color) && !/\\/\\s*0\\)$/.test(color)) return color;\n }\n return '#ffffff';\n}\n\n// `2026-10-22T14:05:09.123Z` -> `20261022T1405Z`: a file name's time, to the minute, in UTC.\nexport function fileStamp(at: Date): string {\n return at.toISOString().replace(/[-:]/g, '').replace(/\\d\\d\\.\\d+Z$/, 'Z');\n}\n\n// The viewer's language, as freshness.ts's viewerLocale reads it (see the top of this file).\nfunction spanish(): boolean {\n const lang = (typeof document !== 'undefined' && document.documentElement.lang) || (typeof navigator !== 'undefined' && navigator.language) || '';\n return lang.toLowerCase().startsWith('es');\n}\n\nconst MENU_STYLE =\n 'position:absolute;top:100%;right:4px;z-index:5;margin-top:2px;padding:4px 0;min-width:160px;' +\n 'background:hsl(var(--card));border:1px solid hsl(var(--border));border-radius:6px;box-shadow:0 4px 12px rgb(0 0 0 / 0.15)';\nconst ITEM_STYLE =\n 'display:block;width:100%;padding:6px 12px;border:none;background:transparent;color:hsl(var(--card-foreground));' +\n 'font:inherit;font-size:0.8125rem;text-align:left;white-space:nowrap;cursor:pointer';\n\n/**\n * Opens the menu inside `host` (the positioned box around the button) and focuses its first item.\n * Returns a function that closes it without calling `onClose` (the frame unmounting, or the button\n * pressed again).\n */\nexport function openExportMenu(host: HTMLElement, o: ExportMenuOptions): () => void {\n const words = spanish() ? WORDS.es : WORDS.en;\n const menu = document.createElement('div');\n menu.setAttribute('role', 'menu');\n menu.setAttribute('data-widget-export-menu', '');\n menu.style.cssText = MENU_STYLE;\n\n let open = true;\n const close = (): void => {\n if (!open) return;\n open = false;\n document.removeEventListener('pointerdown', away);\n menu.remove();\n };\n const done = (refocus: boolean): void => {\n if (!open) return;\n close();\n o.onClose(refocus);\n };\n // A press outside the button and the menu closes it, leaving the focus where the viewer put it.\n function away(e: Event): void {\n if (!(e.target instanceof Node) || !host.contains(e.target)) done(false);\n }\n\n const csv = async (): Promise<void> => {\n try {\n const table = await o.exportRows?.();\n if (table) downloadCsv(table);\n } catch (err) {\n // Loud, not silent: a click that produced no file says why in the console.\n console.error('Widget export failed', err);\n }\n done(true);\n };\n const png = async (): Promise<void> => {\n const url = o.image?.({ backgroundColor: opaqueBackground(o.frameElement()) });\n if (url) {\n // A chart that also exports rows names its image for the same span and bucket as its CSV.\n const named = await Promise.resolve()\n .then(() => o.exportRows?.())\n .then((t) => t?.name, () => undefined);\n const a = document.createElement('a');\n a.href = url;\n a.download = `${safeFileStem(named ?? `${o.title ?? ''}-${fileStamp(new Date())}`)}.png`;\n document.body.appendChild(a);\n a.click();\n a.remove();\n }\n done(true);\n };\n\n const items: HTMLButtonElement[] = [];\n const add = (label: string, run: () => Promise<void>): void => {\n const item = document.createElement('button');\n item.type = 'button';\n item.setAttribute('role', 'menuitem');\n item.style.cssText = ITEM_STYLE;\n item.textContent = label;\n item.addEventListener('click', () => void run());\n items.push(item);\n menu.appendChild(item);\n };\n if (o.exportRows) add(words.csv, csv);\n if (o.image) add(words.image, png);\n\n // Arrow keys move between the items (a menu's own convention), Escape closes it and gives the focus\n // back to the button, and Tab leaves it.\n menu.addEventListener('keydown', (e) => {\n if (e.key === 'Escape') {\n e.stopPropagation();\n done(true);\n return;\n }\n if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return;\n const at = items.indexOf(document.activeElement as HTMLButtonElement);\n items[(at + (e.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length]?.focus();\n e.preventDefault();\n });\n\n document.addEventListener('pointerdown', away);\n host.appendChild(menu);\n items[0]?.focus();\n return close;\n}\n\n// What the frame hands the button, read again each time the menu opens.\nexport type ExportSource = Omit<ExportMenuOptions, 'onClose'>;\n\n// A down arrow onto a tray: a constant, never built from data.\nconst ICON =\n '<svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.6\" stroke-linecap=\"round\" ' +\n 'stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M8 2v8M4.5 6.5 8 10l3.5-3.5M2.5 13.5h11\"/></svg>';\n\n/**\n * Draws the export button (`size` px square) inside `host`, the box the frame reserves for it in the\n * title bar. The button opens and closes the menu. Returns a function that removes both (the frame\n * unmounting, or no longer having anything to export).\n */\nexport function mountExportButton(host: HTMLElement, size: number, source: () => ExportSource): () => void {\n const words = spanish() ? WORDS.es : WORDS.en;\n const button = document.createElement('button');\n button.type = 'button';\n button.setAttribute('aria-label', words.button);\n button.title = words.button;\n button.setAttribute('aria-haspopup', 'menu');\n button.innerHTML = ICON;\n const look = (open: boolean): void => {\n button.setAttribute('aria-expanded', String(open));\n button.style.cssText =\n `width:${size}px;height:${size}px;padding:0;display:inline-flex;align-items:center;justify-content:center;border:none;` +\n `border-radius:4px;color:hsl(var(--muted-foreground));cursor:pointer;background:${open ? 'hsl(var(--muted))' : 'transparent'}`;\n };\n look(false);\n\n let close: (() => void) | undefined;\n button.addEventListener('click', () => {\n if (close) {\n close();\n close = undefined;\n look(false);\n return;\n }\n look(true);\n const s = source();\n close = openExportMenu(host, {\n // Read at the click, so an item acts on the widget as it is then.\n exportRows: s.exportRows && (() => source().exportRows?.()),\n image: s.image && ((o) => source().image?.(o)),\n title: s.title,\n frameElement: s.frameElement,\n onClose: (refocus) => {\n close = undefined;\n look(false);\n if (refocus) button.focus();\n },\n });\n });\n host.appendChild(button);\n return () => {\n close?.();\n button.remove();\n };\n}\n"],
|
|
5
|
+
"mappings": ";AA0BA,IAAM,eAAe;AAKrB,IAAM,eAAe;AAGd,SAAS,YAAY,MAAuB;AACjD,MAAI,UAAU,KAAK,IAAI,EAAG,QAAO;AACjC,QAAM,OAAO,KAAK,QAAQ,QAAQ,EAAE;AACpC,SAAO,aAAa,KAAK,IAAI,KAAK,CAAC,aAAa,KAAK,IAAI;AAC3D;AAGO,SAAS,QAAQ,OAAiC;AACvD,MAAI,UAAU,QAAQ,UAAU,OAAW,QAAO;AAClD,MAAI,OAAO,UAAU,SAAU,QAAO,OAAO,SAAS,KAAK,IAAI,OAAO,KAAK,IAAI;AAC/E,MAAI,OAAO,OAAO,UAAU,WAAW,QAAQ,OAAO,KAAK;AAC3D,MAAI,OAAO,UAAU,YAAY,YAAY,IAAI,EAAG,QAAO,IAAI,IAAI;AACnE,SAAO,WAAW,KAAK,IAAI,IAAI,IAAI,KAAK,QAAQ,MAAM,IAAI,CAAC,MAAM;AACnE;AAGO,SAAS,MAAM,OAA4D;AAChF,QAAM,QAAQ,CAAC,MAAM,QAAQ,IAAI,OAAO,EAAE,KAAK,GAAG,CAAC;AACnD,aAAW,OAAO,MAAM,KAAM,OAAM,KAAK,MAAM,QAAQ,IAAI,CAAC,IAAI,MAAM,QAAQ,IAAI,CAAC,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC;AAChG,SAAO,MAAM,KAAK,MAAM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c,QAAwC;AACzG,QAAM,QAAQ,QAAQ,IAAI,MAAM,KAAK,MAAM;AAC3C,QAAM,SAAS,SAAS,cAAc,QAAQ;AAC9C,SAAO,OAAO;AACd,SAAO,aAAa,cAAc,MAAM,MAAM;AAC9C,SAAO,QAAQ,MAAM;AACrB,SAAO,aAAa,iBAAiB,MAAM;AAC3C,SAAO,YAAY;AACnB,QAAM,OAAO,CAAC,SAAwB;AACpC,WAAO,aAAa,iBAAiB,OAAO,IAAI,CAAC;AACjD,WAAO,MAAM,UACX,SAAS,IAAI,aAAa,IAAI,yKACoD,OAAO,sBAAsB,aAAa;AAAA,EAChI;AACA,OAAK,KAAK;AAEV,MAAI;AACJ,SAAO,iBAAiB,SAAS,MAAM;AACrC,QAAI,OAAO;AACT,YAAM;AACN,cAAQ;AACR,WAAK,KAAK;AACV;AAAA,IACF;AACA,SAAK,IAAI;AACT,UAAM,IAAI,OAAO;AACjB,YAAQ,eAAe,MAAM;AAAA;AAAA,MAE3B,YAAY,EAAE,eAAe,MAAM,OAAO,EAAE,aAAa;AAAA,MACzD,OAAO,EAAE,UAAU,CAAC,MAAM,OAAO,EAAE,QAAQ,CAAC;AAAA,MAC5C,OAAO,EAAE;AAAA,MACT,cAAc,EAAE;AAAA,MAChB,SAAS,CAAC,YAAY;AACpB,gBAAQ;AACR,aAAK,KAAK;AACV,YAAI,QAAS,QAAO,MAAM;AAAA,MAC5B;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AACD,OAAK,YAAY,MAAM;AACvB,SAAO,MAAM;AACX,YAAQ;AACR,WAAO,OAAO;AAAA,EAChB;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/context.d.ts
CHANGED
|
@@ -50,6 +50,15 @@ export declare function WidgetFreshnessProvider({ freshness, children, }: {
|
|
|
50
50
|
children: ReactNode;
|
|
51
51
|
}): import("react").JSX.Element;
|
|
52
52
|
export declare function useWidgetFreshness(): WidgetFreshness | undefined;
|
|
53
|
+
export interface WidgetDeclaredMetrics {
|
|
54
|
+
declared: readonly string[] | null | undefined;
|
|
55
|
+
ask: () => void;
|
|
56
|
+
}
|
|
57
|
+
export declare function WidgetDeclaredMetricsProvider({ value, children, }: {
|
|
58
|
+
value: WidgetDeclaredMetrics;
|
|
59
|
+
children: ReactNode;
|
|
60
|
+
}): import("react").JSX.Element;
|
|
61
|
+
export declare function useWidgetDeclaredMetrics(): WidgetDeclaredMetrics;
|
|
53
62
|
export declare function WidgetFrameStyleProvider({ frame, children }: {
|
|
54
63
|
frame: ResolvedFrame | undefined;
|
|
55
64
|
children: ReactNode;
|
|
@@ -60,3 +69,16 @@ export declare function WidgetTimeRangeProvider({ range, children, }: {
|
|
|
60
69
|
children: ReactNode;
|
|
61
70
|
}): import("react").JSX.Element;
|
|
62
71
|
export declare function useWidgetTimeRange(): TimeRangeState | undefined;
|
|
72
|
+
/** Reads the chart as a PNG data URL on the given background (a canvas is transparent), or undefined while it has none. */
|
|
73
|
+
export type WidgetImageSource = (options: {
|
|
74
|
+
backgroundColor: string;
|
|
75
|
+
}) => string | undefined;
|
|
76
|
+
export declare function WidgetImageRegistrarProvider({ register, children, }: {
|
|
77
|
+
register: (source: WidgetImageSource | undefined) => void;
|
|
78
|
+
children: ReactNode;
|
|
79
|
+
}): import("react").JSX.Element;
|
|
80
|
+
/**
|
|
81
|
+
* Offers the caller's image to the enclosing frame while `source` is given. It may change every
|
|
82
|
+
* render; passing `undefined` withdraws it (a chart that has not drawn yet has no image to offer).
|
|
83
|
+
*/
|
|
84
|
+
export declare function useRegisterWidgetImage(source: WidgetImageSource | undefined): void;
|
package/dist/echarts.js
CHANGED
|
@@ -3,14 +3,17 @@ import {
|
|
|
3
3
|
bandAt,
|
|
4
4
|
fitValueFont,
|
|
5
5
|
formatValue,
|
|
6
|
+
parseThresholds,
|
|
7
|
+
thresholdBands
|
|
8
|
+
} from "./chunks/chunk-IG6DBHKZ.js";
|
|
9
|
+
import {
|
|
6
10
|
isAlarmLevel,
|
|
7
11
|
levelColor,
|
|
8
|
-
parseThresholds,
|
|
9
12
|
severityColorsAt,
|
|
10
13
|
severityFallbackColors,
|
|
11
|
-
|
|
14
|
+
useRegisterWidgetImage,
|
|
12
15
|
useWidgetThemeRoot
|
|
13
|
-
} from "./chunks/chunk-
|
|
16
|
+
} from "./chunks/chunk-G6I5HKQM.js";
|
|
14
17
|
|
|
15
18
|
// src/chart/echart.tsx
|
|
16
19
|
import { useEffect, useRef, useState } from "react";
|
|
@@ -59,6 +62,9 @@ function EChart({ option, className, style }) {
|
|
|
59
62
|
const [failed, setFailed] = useState();
|
|
60
63
|
const [markersLoaded, setMarkersLoaded] = useState(markersReady);
|
|
61
64
|
const needsMarkers = optionUsesMarkers(option) && !markersLoaded;
|
|
65
|
+
useRegisterWidgetImage(
|
|
66
|
+
loaded ? ({ backgroundColor }) => chartRef.current?.getDataURL({ type: "png", pixelRatio: 2, backgroundColor }) : void 0
|
|
67
|
+
);
|
|
62
68
|
useEffect(() => {
|
|
63
69
|
if (loaded) return;
|
|
64
70
|
let live = true;
|
package/dist/echarts.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/chart/echart.tsx", "../src/chart/chart-options.ts", "../src/chart/chart-theme.ts"],
|
|
4
|
-
"sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// A thin React wrapper over Apache ECharts (ADR-039 chart engine).\n//\n// \uD83D\uDD34 ECHARTS IS NOT IMPORTED HERE. The engine (ECharts + zrender, ~170 KB gzip, the largest single\n// dependency of a board) lives in echart-engine.ts and is loaded on demand, ONCE, as one chunk:\n// the first <EChart> to mount fetches it, and a host that wants the first frame complete fetches\n// it first with loadChartEngine (preloadWidgets does, for a board that holds a chart). Only TYPES\n// come from echarts here, and they are erased.\n//\n// The public surface is unchanged: <EChart option> is still a synchronous component. Once the\n// engine is here, a mount initialises the chart exactly as it always did; before it is, the\n// component renders its (empty) container and draws as soon as the engine arrives. A failed load\n// is THROWN, so the widget's error boundary shows it rather than an empty box that looks like a\n// chart with nothing to say, and it is NOT remembered: the next mount (the boundary's Reset)\n// fetches again, and nothing retries on its own.\n//\n// The wrapper owns the imperative lifecycle: init on mount, setOption on change, resize with the\n// container, dispose on unmount.\n\nimport type * as echarts from 'echarts/core';\nimport { useEffect, useRef, useState } from 'react';\n\ntype Engine = typeof import('./echart-engine');\n\nlet engine: Engine | undefined;\nlet engineLoading: Promise<Engine> | undefined;\n\n// Memoized while in flight or loaded; a rejection is forgotten, so the next caller fetches again.\nfunction loadEngine(): Promise<Engine> {\n engineLoading ??= import('./echart-engine').then(\n (m) => (engine = m),\n (err: unknown) => {\n engineLoading = undefined;\n throw err;\n },\n );\n return engineLoading;\n}\n\n/**\n * Fetches the chart engine that <EChart> draws with, so the charts a host renders after awaiting\n * it draw on their first frame. Optional: an <EChart> that mounts first loads the engine itself.\n * Rejects if the engine cannot be fetched; a later call (or mount) fetches it again.\n */\nexport function loadChartEngine(): Promise<void> {\n return loadEngine().then(() => undefined);\n}\n\n// markLine / markArea are registered on first use (see echart-markers.ts for why). Until they\n// are, a chart that asks for them draws without them, and EChart re-applies its option once\n// they arrive -- a beat later on the first threshold chart of a page, never silently absent.\nlet markersReady = false;\nlet markersLoading: Promise<void> | undefined;\n\nexport function loadThresholdMarkers(): Promise<void> {\n markersLoading ??= loadEngine()\n .then((e) => e.registerThresholdMarkers())\n .then(\n () => {\n markersReady = true;\n },\n (err: unknown) => {\n markersLoading = undefined; // a failed chunk load is retried by the next chart that needs it\n throw err;\n },\n );\n return markersLoading;\n}\n\n// True when any series of the option carries a markLine or markArea.\nexport function optionUsesMarkers(option: EChartOption): boolean {\n const series = (option as { series?: unknown }).series;\n const list = Array.isArray(series) ? series : series ? [series] : [];\n return list.some((s) => {\n const m = s as { markLine?: unknown; markArea?: unknown } | null;\n return typeof m === 'object' && m !== null && (m.markLine != null || m.markArea != null);\n });\n}\n\n// A resolved ECharts option object (the shape echarts.setOption accepts). Widgets\n// build these with the pure builders in chart-options.ts.\nexport type EChartOption = echarts.EChartsCoreOption;\n\nexport interface EChartProps {\n option: EChartOption;\n className?: string;\n style?: React.CSSProperties;\n}\n\n// EChart fills its parent; the dashboard canvas sizes the parent, and a\n// ResizeObserver keeps the chart matched to it.\nexport function EChart({ option, className, style }: EChartProps) {\n const containerRef = useRef<HTMLDivElement>(null);\n const chartRef = useRef<echarts.ECharts | null>(null);\n const [loaded, setLoaded] = useState(engine);\n const [failed, setFailed] = useState<{ error: unknown }>();\n const [markersLoaded, setMarkersLoaded] = useState(markersReady);\n const needsMarkers = optionUsesMarkers(option) && !markersLoaded;\n\n // The engine, when this is the first chart to mount and nobody preloaded it.\n useEffect(() => {\n if (loaded) return;\n let live = true;\n loadEngine().then(\n (e) => live && setLoaded(e),\n (error: unknown) => live && setFailed({ error }),\n );\n return () => {\n live = false;\n };\n }, [loaded]);\n\n useEffect(() => {\n if (!needsMarkers) return;\n let live = true;\n loadThresholdMarkers().then(\n () => live && setMarkersLoaded(true),\n // Loud, not silent: the chart still draws, without its threshold lines.\n (err: unknown) => console.error('EChart: the threshold markers failed to load', err),\n );\n return () => {\n live = false;\n };\n }, [needsMarkers]);\n\n // Init + teardown once for the element's lifetime (from the moment the engine is here).\n useEffect(() => {\n const el = containerRef.current;\n if (!el || !loaded) return;\n\n const chart = loaded.init(el);\n chartRef.current = chart;\n\n const observer = new ResizeObserver(() => chart.resize());\n observer.observe(el);\n\n return () => {\n observer.disconnect();\n chart.dispose();\n chartRef.current = null;\n };\n }, [loaded]);\n\n // Re-apply the option whenever it changes. notMerge:true so a shrinking series\n // (rolling window) doesn't leave stale points behind.\n useEffect(() => {\n chartRef.current?.setOption(option, { notMerge: true });\n }, [option, markersLoaded, loaded]);\n\n // To the widget's error boundary: a chart that cannot draw says so.\n if (failed) throw failed.error;\n\n // `data-echart` marks the chart's box, so a host (and the readability gate) can tell a chart\n // that has drawn (ECharts stamps `_echarts_instance_` on it) from one still waiting.\n return (\n <div ref={containerRef} data-echart=\"\" className={className} style={{ width: '100%', height: '100%', ...style }} />\n );\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Pure ECharts option builders. Kept free of React/DOM so the data\u2192chart mapping\n// is unit-testable without a canvas: a widget resolves a ChartTheme + samples and\n// hands the result straight to <EChart>.\n\nimport type { MeasurementSample } from '@devicechain/dashboards';\n\nimport { FIT_MIN_FONT_PX, fitValueFont } from '../fit-text';\nimport { formatValue } from '../format';\nimport type { ElementSize } from '../hooks';\nimport { isAlarmLevel, levelColor, type AlarmLevel } from '../severity';\nimport { bandAt, parseThresholds, thresholdBands, type Threshold } from '../thresholds';\n\nimport type { ChartTheme } from './chart-theme';\nimport type { EChartOption } from './echart';\n\n// distinctNames returns the measurement names present in `samples`, in first-seen\n// order \u2014 used when a chart's datasource doesn't pin an explicit series list.\nfunction distinctNames(samples: MeasurementSample[]): string[] {\n const seen: string[] = [];\n for (const s of samples) {\n if (!seen.includes(s.name)) seen.push(s.name);\n }\n return seen;\n}\n\n// A severity colour with an alpha, for a band drawn UNDER the data (markArea). The theme's\n// severity colours are comma-form hsl(), so the alpha form is a string edit.\nexport function severityFill(theme: ChartTheme, level: AlarmLevel, alpha: number): string {\n return theme.severity[level].replace(/^hsl\\(/, 'hsla(').replace(/\\)$/, `, ${alpha})`);\n}\n\n// Opacity of a threshold band behind a line: enough to read as a zone, faint enough that the\n// line and its grid stay the subject. A `normal` band has no fill at all.\nconst BAND_ALPHA = 0.14;\n\nconst clamp = (v: number, lo: number, hi: number): number => Math.max(lo, Math.min(hi, v));\n\n// gauge/line fonts and tick counts scale with the smaller container dimension so a\n// widget stays legible when resized. A zero/absent size (before first measure, or\n// in a non-DOM test) falls back to a nominal medium size.\nfunction shortSide(size?: ElementSize): number {\n const s = Math.min(size?.width ?? 0, size?.height ?? 0);\n return s > 0 ? s : 200;\n}\n\nexport interface LineChartOptions {\n // Measurement names to plot, one series each. Empty \u2192 every name seen in the\n // window (first-seen order).\n measurements?: string[];\n // Unit suffix: named on the y-axis and appended to every tooltip value.\n unit?: string;\n // Decimal places for axis labels and tooltip values; unset uses the default rounding.\n precision?: number;\n // Severity thresholds, drawn as a labelled line each plus a faint band between them.\n // Any order: the builder sorts them.\n thresholds?: readonly Threshold[];\n // The board's density scale (useWidgetScale().scale): multiplies the axis-font clamp. Default 1.\n scale?: number;\n // Instants (ISO-8601, oldest first) after which nothing is known until the next sample: the live\n // feed was interrupted (MeasurementStreamState.gaps). Every line breaks at each one instead of\n // joining the samples on either side.\n gaps?: readonly string[];\n // The value axis's ends, as the author chose them. Each is a bound the axis REACHES, never a\n // clip: a reading or a threshold beyond it widens the axis to take it in, so a fixed end can\n // frame the data but never hide any. Unset (or not finite), that end is ECharts' own, as before.\n // Both set and not ascending, neither applies (the descriptor refuses such a pair).\n min?: number;\n max?: number;\n}\n\n// breakAtGaps puts an empty point -- which ECharts draws as a break in the line -- at each gap\n// that falls between two of a series' points. Points are in sample order (chronological).\nfunction breakAtGaps(points: Array<[string, number]>, gaps: readonly number[]): Array<[string, number | null]> {\n let g = 0;\n return points.flatMap((point, i): Array<[string, number | null]> => {\n // The last gap before this point; past the end of `gaps` the comparison is false.\n let gap = Number.NaN;\n while (gaps[g] < Date.parse(point[0])) gap = gaps[g++];\n return i > 0 && !Number.isNaN(gap) ? [[new Date(gap).toISOString(), null], point] : [point];\n });\n}\n\n// The markLine / markArea for a chart's thresholds, attached to the first series (the markers\n// belong to a series in ECharts, and every series shares the one y-axis).\nfunction thresholdMarks(theme: ChartTheme, thresholds: readonly Threshold[], unit: string | undefined, precision: number | undefined, fontSize: number) {\n const suffix = unit ? ` ${unit}` : '';\n // A `normal` threshold is still drawn: it is where the value RETURNS to normal, which an\n // operator wants to see. It is drawn in the muted text colour, the same ink as the axis\n // labels, which reads in light and dark and says \"boundary\" without saying \"alarm\".\n const ink = (t: Threshold) => levelColor(theme.severity, t.level) ?? theme.mutedForeground;\n const markLine = {\n silent: true,\n symbol: 'none',\n animation: false,\n data: thresholds.map((t) => ({\n yAxis: t.value,\n name: t.label ?? String(t.value),\n lineStyle: { color: ink(t), type: 'dashed' as const, width: 1.5 },\n label: {\n show: true,\n position: 'insideEndTop' as const,\n color: ink(t),\n fontSize,\n formatter: () => t.label ?? `${formatValue(t.value, precision)}${suffix}`,\n },\n })),\n };\n const markArea = {\n silent: true,\n animation: false,\n data: thresholdBands(thresholds, -Infinity, Infinity)\n .filter((b) => isAlarmLevel(b.level))\n .map((b) => [\n { yAxis: b.from, itemStyle: { color: severityFill(theme, b.level as AlarmLevel, BAND_ALPHA) } },\n { yAxis: b.to },\n ]),\n };\n return { markLine, markArea };\n}\n\n// One end of a line chart's value axis: `low` is the min end, otherwise the max end. `data` is\n// ECharts' own extent at that end (not finite with no data). With no author end, a threshold\n// beyond the data fixes the end at the threshold and otherwise ECharts keeps its auto range\n// (null). With one, the end is the furthest of the author's end, the threshold and the data, so\n// nothing drawn falls off the axis.\nfunction axisEnd(low: boolean, data: number, fixed: number | undefined, threshold: number | undefined): number | null {\n const beyond = (a: number, b: number): boolean => (low ? a < b : a > b);\n if (fixed === undefined) return threshold !== undefined && beyond(threshold, data) ? threshold : null;\n let end = fixed;\n if (Number.isFinite(data) && beyond(data, end)) end = data;\n if (threshold !== undefined && beyond(threshold, end)) end = threshold;\n return end;\n}\n\n// buildLineOption maps a rolling window of samples to a multi-series time chart,\n// one line per measurement name, coloured from the theme's chart palette.\nexport function buildLineOption(\n samples: MeasurementSample[],\n theme: ChartTheme,\n options: LineChartOptions = {},\n size?: ElementSize,\n): EChartOption {\n const names = options.measurements?.length ? options.measurements : distinctNames(samples);\n const scale = options.scale ?? 1;\n const axisFont = clamp(Math.round(shortSide(size) / 22), Math.round(8 * scale), Math.round(12 * scale));\n\n // Re-parsed (validated + sorted): the builder is public, and a caller may hand it a list\n // that never went through parseThresholds. Every rule below assumes ascending order.\n const thresholds = parseThresholds(options.thresholds ?? []);\n const lowest = thresholds.length > 0 ? thresholds[0].value : 0;\n const highest = thresholds.length > 0 ? thresholds[thresholds.length - 1].value : 0;\n const marks = thresholds.length > 0 ? thresholdMarks(theme, thresholds, options.unit, options.precision, axisFont) : undefined;\n const suffix = options.unit ? ` ${options.unit}` : '';\n const precision = options.precision;\n const gaps = (options.gaps ?? []).map(Date.parse).filter((g) => !Number.isNaN(g));\n const finite = (v: number | undefined): number | undefined => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);\n let fixedMin = finite(options.min);\n let fixedMax = finite(options.max);\n if (fixedMin !== undefined && fixedMax !== undefined && fixedMin >= fixedMax) fixedMin = fixedMax = undefined;\n\n const series = names.map((name, i) => {\n const color = theme.series[i % theme.series.length];\n return {\n ...(i === 0 ? marks : undefined),\n name,\n type: 'line' as const,\n showSymbol: false,\n lineStyle: { color },\n itemStyle: { color },\n data: breakAtGaps(\n samples\n .filter((s) => s.name === name && s.value != null && s.occurredTime != null)\n .map((s): [string, number] => [s.occurredTime as string, s.value as number]),\n gaps,\n ),\n };\n });\n\n return {\n animation: false,\n textStyle: { color: theme.foreground, fontSize: axisFont },\n grid: { left: 8, right: 12, top: names.length > 1 || options.unit ? 28 : 12, bottom: 8, containLabel: true },\n tooltip: {\n trigger: 'axis',\n valueFormatter: (v: unknown) => (typeof v === 'number' ? `${formatValue(v, precision)}${suffix}` : String(v ?? '\u2014')),\n },\n legend:\n names.length > 1 ? { textStyle: { color: theme.mutedForeground, fontSize: axisFont }, top: 0 } : undefined,\n xAxis: {\n type: 'time',\n axisLine: { lineStyle: { color: theme.border } },\n axisLabel: { color: theme.mutedForeground, fontSize: axisFont, hideOverlap: true },\n },\n yAxis: {\n type: 'value',\n // The unit rides the axis once, at its head, rather than on every tick.\n name: options.unit,\n nameTextStyle: { color: theme.mutedForeground, fontSize: axisFont, align: 'left' as const },\n splitLine: { lineStyle: { color: theme.border } },\n axisLabel: {\n color: theme.mutedForeground,\n fontSize: axisFont,\n // Rounded only when the author asked; otherwise ECharts' own tick rounding applies.\n ...(precision != null ? { formatter: (v: number) => formatValue(v, precision) } : {}),\n },\n // A threshold outside the data's range must still be on the chart: extend the range to\n // take it in. Only then -- a returned number FIXES that end of the axis (no nice\n // rounding, no zero baseline), so a threshold inside the data returns null and leaves\n // ECharts' own auto range exactly as it is without thresholds. An author's end (min/max)\n // is the same kind of bound: the axis reaches it, and goes past it only for a reading or a\n // threshold beyond it.\n ...(thresholds.length > 0 || fixedMin !== undefined || fixedMax !== undefined\n ? {\n min: (e: { min: number }) => axisEnd(true, e.min, fixedMin, thresholds.length > 0 ? lowest : undefined),\n max: (e: { max: number }) => axisEnd(false, e.max, fixedMax, thresholds.length > 0 ? highest : undefined),\n }\n : {}),\n },\n series,\n };\n}\n\nexport interface GaugeChartOptions {\n min?: number;\n max?: number;\n unit?: string;\n // Decimal places for the readout; unset uses the default rounding.\n precision?: number;\n // Severity thresholds, drawn as coloured bands on the arc (any order).\n thresholds?: readonly Threshold[];\n // The board's density scale: multiplies the label-font clamp and the readout's floor. Default 1.\n scale?: number;\n // Where the number is drawn. 'canvas' (the default) paints it inside the dial, as the builder\n // always has, so a widget that renders only the chart keeps its readout. 'none' leaves the dial\n // bare for a caller that draws the number itself as DOM text in gaugeReadoutBox, which the\n // readability gate can measure (the built-in gauge does).\n readout?: 'canvas' | 'none';\n // Where the needle is with no value. 'min' (the default) rests it at the scale's minimum, as the\n // builder always has. 'none' draws no needle, so an empty dial cannot be read as a reading of\n // its minimum (the built-in gauge, whose readout already says there is no value, asks for it).\n emptyNeedle?: 'min' | 'none';\n}\n\n// The dial's geometry as fractions of its box: where its centre sits and how much of the short\n// side's half it fills. The DOM readout is placed from the same numbers (gaugeReadoutBox).\nconst GAUGE_CENTER_Y = 0.58;\nconst GAUGE_RADIUS = 0.95;\n// How far below the hub the readout sits, as a fraction of the radius.\nconst GAUGE_READOUT_OFFSET = 0.3;\n\n// The box (px, relative to the chart) the gauge's DOM readout is centred in and fitted to: under\n// the hub and inside the dial, where the canvas detail used to be drawn. A zero size (before the\n// first measure) takes the nominal one the builder assumes.\nexport function gaugeReadoutBox(size?: ElementSize): { centerX: number; centerY: number; width: number; height: number } {\n const s = shortSide(size);\n const w = (size?.width ?? 0) > 0 ? size!.width : s;\n const h = (size?.height ?? 0) > 0 ? size!.height : s;\n return {\n centerX: w / 2,\n centerY: GAUGE_CENTER_Y * h + GAUGE_READOUT_OFFSET * GAUGE_RADIUS * (s / 2),\n width: s * 0.7,\n height: s * 0.25,\n };\n}\n\n// Below this short side (px) the gauge drops its axis labels: at that size they would be\n// drawn at the 8 px floor, which is noise rather than a scale.\nexport const GAUGE_AXIS_LABELS_MIN_SIDE = 120;\n\n// The arc's colour stops: ECharts wants [[endFraction, colour], ...] ending at 1. A neutral\n// stretch (below the lowest threshold, or a `normal` band) takes the track colour. With no bands: one track.\nfunction gaugeArcColors(bands: ReturnType<typeof thresholdBands>, min: number, max: number, theme: ChartTheme): [number, string][] {\n if (bands.length === 0) return [[1, theme.border]];\n return bands.map((b, i): [number, string] => [\n i === bands.length - 1 ? 1 : (b.to - min) / (max - min),\n levelColor(theme.severity, b.level) ?? theme.border,\n ]);\n}\n\n// buildGaugeOption maps a single latest value to a gauge. A null value (nothing\n// received yet) shows an em dash and rests the needle at the minimum. Ticks, fonts,\n// and the arc width scale with the widget size so it stays legible when resized\n// (ECharts' default gauge crams ~10 labels at fixed fonts on a small canvas).\nexport function buildGaugeOption(\n value: number | null,\n theme: ChartTheme,\n options: GaugeChartOptions = {},\n size?: ElementSize,\n): EChartOption {\n const min = options.min ?? 0;\n const max = options.max ?? 100;\n const thresholds = parseThresholds(options.thresholds ?? []); // validated + sorted, as above\n const bands = thresholdBands(thresholds, min, max);\n // Banded only when a COLOURED band actually lands on the arc: thresholds that all sit above\n // `max`, or only `normal` bands, leave a plain neutral track, which keeps the progress arc\n // like any other gauge.\n const banded = bands.some((b) => isAlarmLevel(b.level));\n // The needle takes the colour of the band the value sits in; with no bands, below the\n // lowest, or in a `normal` band it keeps the chart accent.\n const accent = levelColor(theme.severity, bandAt(thresholds, value)?.level) ?? theme.series[0];\n\n const s = shortSide(size);\n const arcWidth = clamp(Math.round(s / 26), 4, 12);\n const scale = options.scale ?? 1;\n const labelFont = clamp(Math.round(s / 20), Math.round(8 * scale), Math.round(13 * scale));\n const showAxisLabels = s >= GAUGE_AXIS_LABELS_MIN_SIDE;\n const unitSuffix = options.unit ? ` ${options.unit}` : '';\n // The readout is fitted to the dial's inner box and its own length, like every big number.\n const readout = value == null ? '\u2014' : `${formatValue(value, options.precision)}${unitSuffix}`;\n const valueFont = fitValueFont({ width: s * 0.7, height: s * 0.25 }, readout.length, {\n floor: Math.round(FIT_MIN_FONT_PX * scale),\n });\n return {\n animation: false,\n series: [\n {\n type: 'gauge',\n min,\n max,\n splitNumber: s < 160 ? 4 : 5, // fewer ticks than the default 10 \u2192 no cram\n radius: `${GAUGE_RADIUS * 100}%`,\n center: ['50%', `${GAUGE_CENTER_Y * 100}%`],\n // The progress arc would paint over the bands, so with bands the needle alone marks the value.\n progress: { show: !banded, width: arcWidth, itemStyle: { color: accent } },\n pointer: {\n show: value != null || options.emptyNeedle !== 'none',\n itemStyle: { color: accent },\n length: '55%',\n width: clamp(Math.round(s / 50), 2, 6),\n },\n anchor: { show: false },\n axisLine: { lineStyle: { width: arcWidth, color: gaugeArcColors(bands, min, max, theme) } },\n axisTick: { show: false },\n splitLine: { length: arcWidth, lineStyle: { color: theme.border, width: 1 } },\n axisLabel: { show: showAxisLabels, color: theme.mutedForeground, fontSize: labelFont, distance: arcWidth + 2 },\n detail:\n options.readout === 'none'\n ? { show: false }\n : {\n valueAnimation: false,\n color: theme.foreground,\n fontSize: valueFont,\n offsetCenter: [0, `${GAUGE_READOUT_OFFSET * 100}%`],\n formatter: (v: number) => (value == null ? '\u2014' : `${formatValue(v, options.precision)}${unitSuffix}`),\n },\n data: [{ value: value ?? min }],\n },\n ],\n };\n}\n\n// A heading in degrees folded onto [0, 360): 370 is 10 and -90 is 270, because a compass has no\n// \"beyond a full turn\" and a bearing sensor may well report either. 360 is 0, never 360, and a\n// value that is not a finite number has no heading at all (undefined), not a plausible one.\nexport function wrapHeading(value: number | null | undefined): number | undefined {\n if (value == null || !Number.isFinite(value)) return undefined;\n return ((value % 360) + 360) % 360;\n}\n\nexport interface CompassChartOptions {\n // The four point labels in N, E, S, W order (a locale writes West as \"O\", so the caller owns them).\n cardinals: readonly [string, string, string, string];\n thresholds?: readonly Threshold[];\n // The board's density scale; multiplies the label-font clamp. Default 1.\n scale?: number;\n}\n\n// buildCompassOption draws a full turn on the registered gauge series: north at the top, the\n// angle running clockwise, so 90 is east. The needle takes the colour of the band the (wrapped)\n// heading is in and the chart accent in a `normal` band or none. The degrees themselves are DOM\n// text beside it (compass.tsx). With no reading the needle rests at north.\nexport function buildCompassOption(\n value: number | null,\n theme: ChartTheme,\n options: CompassChartOptions,\n size?: ElementSize,\n): EChartOption {\n const heading = wrapHeading(value);\n const thresholds = parseThresholds(options.thresholds ?? []);\n const bands = thresholdBands(thresholds, 0, 360);\n const accent = levelColor(theme.severity, bandAt(thresholds, heading ?? null)?.level) ?? theme.series[0];\n const s = shortSide(size);\n const scale = options.scale ?? 1;\n const arcWidth = clamp(Math.round(s / 30), 3, 10);\n const labelFont = clamp(Math.round(s / 11), Math.round(10 * scale), Math.round(20 * scale));\n const [north, east, south, west] = options.cardinals;\n const points: Record<number, string> = { 0: north, 90: east, 180: south, 270: west };\n return {\n animation: false,\n series: [\n {\n type: 'gauge',\n min: 0,\n max: 360,\n startAngle: 90,\n endAngle: -270,\n splitNumber: 4,\n radius: '92%',\n center: ['50%', '50%'],\n progress: { show: false },\n pointer: { itemStyle: { color: accent }, length: '62%', width: clamp(Math.round(s / 36), 3, 8) },\n anchor: { show: true, size: clamp(Math.round(s / 24), 5, 12), itemStyle: { color: accent } },\n axisLine: { lineStyle: { width: arcWidth, color: gaugeArcColors(bands, 0, 360, theme) } },\n axisTick: { show: s >= GAUGE_AXIS_LABELS_MIN_SIDE, splitNumber: 3, length: arcWidth, lineStyle: { color: theme.border, width: 1 } },\n splitLine: { length: arcWidth * 1.6, lineStyle: { color: theme.mutedForeground, width: 2 } },\n // Only the four points are labelled; 360 is the same tick as 0, so it stays blank.\n axisLabel: {\n show: true,\n color: theme.foreground,\n fontSize: labelFont,\n distance: arcWidth * 1.6 + 6,\n formatter: (v: number) => points[v] ?? '',\n },\n detail: { show: false },\n data: [{ value: heading ?? 0 }],\n },\n ],\n };\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// The chart colour theme: concrete colours resolved from the host's CSS custom properties,\n// because an ECharts canvas cannot resolve `var(--x)`. Pure DOM + React, no echarts import,\n// but it lives on the `/echarts` subpath with the rest of the chart helpers so the SDK root\n// stays chart-free.\n\nimport { useMemo, useSyncExternalStore } from 'react';\n\nimport { useWidgetThemeRoot } from '../context';\nimport { severityColorsAt, severityFallbackColors, type AlarmLevel } from '../severity';\n\n// Concrete colors for an ECharts canvas, resolved from the CSS variables in scope\n// at a given element (charts can't use CSS vars directly).\nexport interface ChartTheme {\n foreground: string;\n mutedForeground: string;\n border: string;\n series: string[];\n // The four coloured threshold levels, concrete (comma-form `hsl(h, s%, l%)`, which every\n // canvas colour parser accepts and which severityFill can add an alpha to). `normal` has\n // none: it renders in the widget's own neutral (see severity.ts).\n severity: Record<AlarmLevel, string>;\n}\n\n// Fallbacks used when a variable is absent (e.g. jsdom, or a host that hasn't set\n// the token) so a chart still renders in sensible default colors.\nconst FALLBACK: ChartTheme = {\n foreground: 'hsl(240 10% 3.9%)',\n mutedForeground: 'hsl(240 3.8% 46.1%)',\n border: 'hsl(240 5.9% 90%)',\n series: [\n 'hsl(220 70% 50%)',\n 'hsl(160 60% 45%)',\n 'hsl(30 80% 55%)',\n 'hsl(280 65% 60%)',\n 'hsl(340 75% 55%)',\n ],\n severity: severityFallbackColors(),\n};\n\nfunction readVar(style: CSSStyleDeclaration, name: string, fallback: string): string {\n const raw = style.getPropertyValue(`--${name}`).trim();\n return raw ? `hsl(${raw})` : fallback;\n}\n\n// resolveChartTheme reads the theme tokens in scope at `el` into concrete colors\n// for ECharts. Reading at the element (not the document root) means a widget\n// nested under a re-themed subtree picks up the local override.\nexport function resolveChartTheme(el: Element): ChartTheme {\n const style = getComputedStyle(el);\n return {\n foreground: readVar(style, 'foreground', FALLBACK.foreground),\n mutedForeground: readVar(style, 'muted-foreground', FALLBACK.mutedForeground),\n border: readVar(style, 'border', FALLBACK.border),\n series: FALLBACK.series.map((fallback, i) => readVar(style, `chart-${i + 1}`, fallback)),\n severity: severityColorsAt(el, style),\n };\n}\n\n// --- shared chart-theme store ------------------------------------------------\n//\n// Charts need concrete colors resolved from the CSS-variable theme. Rather than\n// have every chart widget mount its own MutationObserver on <html> and recompute\n// the same theme, one page-wide observer resolves it once per change and every\n// widget reads the shared, memoized value via useSyncExternalStore \u2014 so a busy\n// dashboard pays O(1), not O(number of charts), per theme toggle.\n\nlet sharedTheme: ChartTheme | null = null;\nconst themeListeners = new Set<() => void>();\nlet themeObserver: MutationObserver | null = null;\n\nfunction recomputeTheme(): void {\n sharedTheme = resolveChartTheme(document.documentElement);\n}\n\nfunction subscribeTheme(listener: () => void): () => void {\n if (!themeObserver) {\n recomputeTheme();\n themeObserver = new MutationObserver(() => {\n recomputeTheme();\n for (const l of themeListeners) l();\n });\n themeObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ['class', 'style'],\n });\n }\n themeListeners.add(listener);\n return () => {\n themeListeners.delete(listener);\n if (themeListeners.size === 0 && themeObserver) {\n themeObserver.disconnect();\n themeObserver = null;\n sharedTheme = null;\n }\n };\n}\n\nfunction getThemeSnapshot(): ChartTheme {\n if (!sharedTheme) recomputeTheme();\n return sharedTheme as ChartTheme;\n}\n\n// useChartTheme returns the current chart colors and re-renders the caller when\n// the document theme changes (a light/dark class or inline-style swap on <html>).\nexport function useChartTheme(): ChartTheme {\n const shared = useSyncExternalStore(subscribeTheme, getThemeSnapshot, getThemeSnapshot);\n // A host that scopes its tokens to a container says so (WidgetThemeRoot); its tokens are\n // fixed for the container's life, so they are read once there rather than observed.\n const root = useWidgetThemeRoot();\n const scoped = useMemo(() => (root ? resolveChartTheme(root) : null), [root]);\n return scoped ?? shared;\n}\n\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;AAsBA,SAAS,WAAW,QAAQ,gBAAgB;AAuIxC;AAnIJ,IAAI;AACJ,IAAI;AAGJ,SAAS,aAA8B;AACrC,oCAAkB,OAAO,oCAAiB,EAAE;AAAA,IAC1C,CAAC,MAAO,SAAS;AAAA,IACjB,CAAC,QAAiB;AAChB,sBAAgB;AAChB,YAAM;AAAA,IACR;AAAA,EACF;AACA,SAAO;AACT;AAOO,SAAS,kBAAiC;AAC/C,SAAO,WAAW,EAAE,KAAK,MAAM,MAAS;AAC1C;AAKA,IAAI,eAAe;AACnB,IAAI;AAEG,SAAS,uBAAsC;AACpD,sCAAmB,WAAW,EAC3B,KAAK,CAAC,MAAM,EAAE,yBAAyB,CAAC,EACxC;AAAA,IACC,MAAM;AACJ,qBAAe;AAAA,IACjB;AAAA,IACA,CAAC,QAAiB;AAChB,uBAAiB;AACjB,YAAM;AAAA,IACR;AAAA,EACF;AACF,SAAO;AACT;AAGO,SAAS,kBAAkB,QAA+B;AAC/D,QAAM,SAAU,OAAgC;AAChD,QAAM,OAAO,MAAM,QAAQ,MAAM,IAAI,SAAS,SAAS,CAAC,MAAM,IAAI,CAAC;AACnE,SAAO,KAAK,KAAK,CAAC,MAAM;AACtB,UAAM,IAAI;AACV,WAAO,OAAO,MAAM,YAAY,MAAM,SAAS,EAAE,YAAY,QAAQ,EAAE,YAAY;AAAA,EACrF,CAAC;AACH;AAcO,SAAS,OAAO,EAAE,QAAQ,WAAW,MAAM,GAAgB;AAChE,QAAM,eAAe,OAAuB,IAAI;AAChD,QAAM,WAAW,OAA+B,IAAI;AACpD,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAS,MAAM;AAC3C,QAAM,CAAC,QAA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;AAC3B,SAAO,MAAM;AACX,mBAAe,OAAO,QAAQ;AAC9B,QAAI,eAAe,SAAS,KAAK,eAAe;AAC9C,oBAAc,WAAW;AACzB,sBAAgB;AAChB,oBAAc;AAAA,IAChB;AAAA,EACF;AACF;AAEA,SAAS,mBAA+B;AACtC,MAAI,CAAC,YAAa,gBAAe;AACjC,SAAO;AACT;AAIO,SAAS,gBAA4B;AAC1C,QAAM,SAAS,qBAAqB,gBAAgB,kBAAkB,gBAAgB;AAGtF,QAAM,OAAO,mBAAmB;AAChC,QAAM,SAAS,QAAQ,MAAO,OAAO,kBAAkB,IAAI,IAAI,MAAO,CAAC,IAAI,CAAC;AAC5E,SAAO,UAAU;AACnB;",
|
|
4
|
+
"sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// A thin React wrapper over Apache ECharts (ADR-039 chart engine).\n//\n// \uD83D\uDD34 ECHARTS IS NOT IMPORTED HERE. The engine (ECharts + zrender, ~170 KB gzip, the largest single\n// dependency of a board) lives in echart-engine.ts and is loaded on demand, ONCE, as one chunk:\n// the first <EChart> to mount fetches it, and a host that wants the first frame complete fetches\n// it first with loadChartEngine (preloadWidgets does, for a board that holds a chart). Only TYPES\n// come from echarts here, and they are erased.\n//\n// The public surface is unchanged: <EChart option> is still a synchronous component. Once the\n// engine is here, a mount initialises the chart exactly as it always did; before it is, the\n// component renders its (empty) container and draws as soon as the engine arrives. A failed load\n// is THROWN, so the widget's error boundary shows it rather than an empty box that looks like a\n// chart with nothing to say, and it is NOT remembered: the next mount (the boundary's Reset)\n// fetches again, and nothing retries on its own.\n//\n// The wrapper owns the imperative lifecycle: init on mount, setOption on change, resize with the\n// container, dispose on unmount.\n\nimport type * as echarts from 'echarts/core';\nimport { useEffect, useRef, useState } from 'react';\n\nimport { useRegisterWidgetImage } from '../context';\n\ntype Engine = typeof import('./echart-engine');\n\nlet engine: Engine | undefined;\nlet engineLoading: Promise<Engine> | undefined;\n\n// Memoized while in flight or loaded; a rejection is forgotten, so the next caller fetches again.\nfunction loadEngine(): Promise<Engine> {\n engineLoading ??= import('./echart-engine').then(\n (m) => (engine = m),\n (err: unknown) => {\n engineLoading = undefined;\n throw err;\n },\n );\n return engineLoading;\n}\n\n/**\n * Fetches the chart engine that <EChart> draws with, so the charts a host renders after awaiting\n * it draw on their first frame. Optional: an <EChart> that mounts first loads the engine itself.\n * Rejects if the engine cannot be fetched; a later call (or mount) fetches it again.\n */\nexport function loadChartEngine(): Promise<void> {\n return loadEngine().then(() => undefined);\n}\n\n// markLine / markArea are registered on first use (see echart-markers.ts for why). Until they\n// are, a chart that asks for them draws without them, and EChart re-applies its option once\n// they arrive -- a beat later on the first threshold chart of a page, never silently absent.\nlet markersReady = false;\nlet markersLoading: Promise<void> | undefined;\n\nexport function loadThresholdMarkers(): Promise<void> {\n markersLoading ??= loadEngine()\n .then((e) => e.registerThresholdMarkers())\n .then(\n () => {\n markersReady = true;\n },\n (err: unknown) => {\n markersLoading = undefined; // a failed chunk load is retried by the next chart that needs it\n throw err;\n },\n );\n return markersLoading;\n}\n\n// True when any series of the option carries a markLine or markArea.\nexport function optionUsesMarkers(option: EChartOption): boolean {\n const series = (option as { series?: unknown }).series;\n const list = Array.isArray(series) ? series : series ? [series] : [];\n return list.some((s) => {\n const m = s as { markLine?: unknown; markArea?: unknown } | null;\n return typeof m === 'object' && m !== null && (m.markLine != null || m.markArea != null);\n });\n}\n\n// A resolved ECharts option object (the shape echarts.setOption accepts). Widgets\n// build these with the pure builders in chart-options.ts.\nexport type EChartOption = echarts.EChartsCoreOption;\n\nexport interface EChartProps {\n option: EChartOption;\n className?: string;\n style?: React.CSSProperties;\n}\n\n// EChart fills its parent; the dashboard canvas sizes the parent, and a\n// ResizeObserver keeps the chart matched to it.\nexport function EChart({ option, className, style }: EChartProps) {\n const containerRef = useRef<HTMLDivElement>(null);\n const chartRef = useRef<echarts.ECharts | null>(null);\n const [loaded, setLoaded] = useState(engine);\n const [failed, setFailed] = useState<{ error: unknown }>();\n const [markersLoaded, setMarkersLoaded] = useState(markersReady);\n const needsMarkers = optionUsesMarkers(option) && !markersLoaded;\n\n // Offer the chart's image to the frame it is drawn in (its \"Download image\") once the engine is\n // here and the chart exists: a PNG at twice the on-screen resolution, on the background the frame\n // hands over, since the canvas itself is transparent.\n useRegisterWidgetImage(\n loaded ? ({ backgroundColor }) => chartRef.current?.getDataURL({ type: 'png', pixelRatio: 2, backgroundColor }) : undefined,\n );\n\n // The engine, when this is the first chart to mount and nobody preloaded it.\n useEffect(() => {\n if (loaded) return;\n let live = true;\n loadEngine().then(\n (e) => live && setLoaded(e),\n (error: unknown) => live && setFailed({ error }),\n );\n return () => {\n live = false;\n };\n }, [loaded]);\n\n useEffect(() => {\n if (!needsMarkers) return;\n let live = true;\n loadThresholdMarkers().then(\n () => live && setMarkersLoaded(true),\n // Loud, not silent: the chart still draws, without its threshold lines.\n (err: unknown) => console.error('EChart: the threshold markers failed to load', err),\n );\n return () => {\n live = false;\n };\n }, [needsMarkers]);\n\n // Init + teardown once for the element's lifetime (from the moment the engine is here).\n useEffect(() => {\n const el = containerRef.current;\n if (!el || !loaded) return;\n\n const chart = loaded.init(el);\n chartRef.current = chart;\n\n const observer = new ResizeObserver(() => chart.resize());\n observer.observe(el);\n\n return () => {\n observer.disconnect();\n chart.dispose();\n chartRef.current = null;\n };\n }, [loaded]);\n\n // Re-apply the option whenever it changes. notMerge:true so a shrinking series\n // (rolling window) doesn't leave stale points behind.\n useEffect(() => {\n chartRef.current?.setOption(option, { notMerge: true });\n }, [option, markersLoaded, loaded]);\n\n // To the widget's error boundary: a chart that cannot draw says so.\n if (failed) throw failed.error;\n\n // `data-echart` marks the chart's box, so a host (and the readability gate) can tell a chart\n // that has drawn (ECharts stamps `_echarts_instance_` on it) from one still waiting.\n return (\n <div ref={containerRef} data-echart=\"\" className={className} style={{ width: '100%', height: '100%', ...style }} />\n );\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Pure ECharts option builders. Kept free of React/DOM so the data\u2192chart mapping\n// is unit-testable without a canvas: a widget resolves a ChartTheme + samples and\n// hands the result straight to <EChart>.\n\nimport type { MeasurementSample } from '@devicechain/dashboards';\n\nimport { FIT_MIN_FONT_PX, fitValueFont } from '../fit-text';\nimport { formatValue } from '../format';\nimport type { ElementSize } from '../hooks';\nimport { isAlarmLevel, levelColor, type AlarmLevel } from '../severity';\nimport { bandAt, parseThresholds, thresholdBands, type Threshold } from '../thresholds';\n\nimport type { ChartTheme } from './chart-theme';\nimport type { EChartOption } from './echart';\n\n// distinctNames returns the measurement names present in `samples`, in first-seen\n// order \u2014 used when a chart's datasource doesn't pin an explicit series list.\nfunction distinctNames(samples: MeasurementSample[]): string[] {\n const seen: string[] = [];\n for (const s of samples) {\n if (!seen.includes(s.name)) seen.push(s.name);\n }\n return seen;\n}\n\n// A severity colour with an alpha, for a band drawn UNDER the data (markArea). The theme's\n// severity colours are comma-form hsl(), so the alpha form is a string edit.\nexport function severityFill(theme: ChartTheme, level: AlarmLevel, alpha: number): string {\n return theme.severity[level].replace(/^hsl\\(/, 'hsla(').replace(/\\)$/, `, ${alpha})`);\n}\n\n// Opacity of a threshold band behind a line: enough to read as a zone, faint enough that the\n// line and its grid stay the subject. A `normal` band has no fill at all.\nconst BAND_ALPHA = 0.14;\n\nconst clamp = (v: number, lo: number, hi: number): number => Math.max(lo, Math.min(hi, v));\n\n// gauge/line fonts and tick counts scale with the smaller container dimension so a\n// widget stays legible when resized. A zero/absent size (before first measure, or\n// in a non-DOM test) falls back to a nominal medium size.\nfunction shortSide(size?: ElementSize): number {\n const s = Math.min(size?.width ?? 0, size?.height ?? 0);\n return s > 0 ? s : 200;\n}\n\nexport interface LineChartOptions {\n // Measurement names to plot, one series each. Empty \u2192 every name seen in the\n // window (first-seen order).\n measurements?: string[];\n // Unit suffix: named on the y-axis and appended to every tooltip value.\n unit?: string;\n // Decimal places for axis labels and tooltip values; unset uses the default rounding.\n precision?: number;\n // Severity thresholds, drawn as a labelled line each plus a faint band between them.\n // Any order: the builder sorts them.\n thresholds?: readonly Threshold[];\n // The board's density scale (useWidgetScale().scale): multiplies the axis-font clamp. Default 1.\n scale?: number;\n // Instants (ISO-8601, oldest first) after which nothing is known until the next sample: the live\n // feed was interrupted (MeasurementStreamState.gaps). Every line breaks at each one instead of\n // joining the samples on either side.\n gaps?: readonly string[];\n // The value axis's ends, as the author chose them. Each is a bound the axis REACHES, never a\n // clip: a reading or a threshold beyond it widens the axis to take it in, so a fixed end can\n // frame the data but never hide any. Unset (or not finite), that end is ECharts' own, as before.\n // Both set and not ascending, neither applies (the descriptor refuses such a pair).\n min?: number;\n max?: number;\n}\n\n// breakAtGaps puts an empty point -- which ECharts draws as a break in the line -- at each gap\n// that falls between two of a series' points. Points are in sample order (chronological).\nfunction breakAtGaps(points: Array<[string, number]>, gaps: readonly number[]): Array<[string, number | null]> {\n let g = 0;\n return points.flatMap((point, i): Array<[string, number | null]> => {\n // The last gap before this point; past the end of `gaps` the comparison is false.\n let gap = Number.NaN;\n while (gaps[g] < Date.parse(point[0])) gap = gaps[g++];\n return i > 0 && !Number.isNaN(gap) ? [[new Date(gap).toISOString(), null], point] : [point];\n });\n}\n\n// The markLine / markArea for a chart's thresholds, attached to the first series (the markers\n// belong to a series in ECharts, and every series shares the one y-axis).\nfunction thresholdMarks(theme: ChartTheme, thresholds: readonly Threshold[], unit: string | undefined, precision: number | undefined, fontSize: number) {\n const suffix = unit ? ` ${unit}` : '';\n // A `normal` threshold is still drawn: it is where the value RETURNS to normal, which an\n // operator wants to see. It is drawn in the muted text colour, the same ink as the axis\n // labels, which reads in light and dark and says \"boundary\" without saying \"alarm\".\n const ink = (t: Threshold) => levelColor(theme.severity, t.level) ?? theme.mutedForeground;\n const markLine = {\n silent: true,\n symbol: 'none',\n animation: false,\n data: thresholds.map((t) => ({\n yAxis: t.value,\n name: t.label ?? String(t.value),\n lineStyle: { color: ink(t), type: 'dashed' as const, width: 1.5 },\n label: {\n show: true,\n position: 'insideEndTop' as const,\n color: ink(t),\n fontSize,\n formatter: () => t.label ?? `${formatValue(t.value, precision)}${suffix}`,\n },\n })),\n };\n const markArea = {\n silent: true,\n animation: false,\n data: thresholdBands(thresholds, -Infinity, Infinity)\n .filter((b) => isAlarmLevel(b.level))\n .map((b) => [\n { yAxis: b.from, itemStyle: { color: severityFill(theme, b.level as AlarmLevel, BAND_ALPHA) } },\n { yAxis: b.to },\n ]),\n };\n return { markLine, markArea };\n}\n\n// One end of a line chart's value axis: `low` is the min end, otherwise the max end. `data` is\n// ECharts' own extent at that end (not finite with no data). With no author end, a threshold\n// beyond the data fixes the end at the threshold and otherwise ECharts keeps its auto range\n// (null). With one, the end is the furthest of the author's end, the threshold and the data, so\n// nothing drawn falls off the axis.\nfunction axisEnd(low: boolean, data: number, fixed: number | undefined, threshold: number | undefined): number | null {\n const beyond = (a: number, b: number): boolean => (low ? a < b : a > b);\n if (fixed === undefined) return threshold !== undefined && beyond(threshold, data) ? threshold : null;\n let end = fixed;\n if (Number.isFinite(data) && beyond(data, end)) end = data;\n if (threshold !== undefined && beyond(threshold, end)) end = threshold;\n return end;\n}\n\n// buildLineOption maps a rolling window of samples to a multi-series time chart,\n// one line per measurement name, coloured from the theme's chart palette.\nexport function buildLineOption(\n samples: MeasurementSample[],\n theme: ChartTheme,\n options: LineChartOptions = {},\n size?: ElementSize,\n): EChartOption {\n const names = options.measurements?.length ? options.measurements : distinctNames(samples);\n const scale = options.scale ?? 1;\n const axisFont = clamp(Math.round(shortSide(size) / 22), Math.round(8 * scale), Math.round(12 * scale));\n\n // Re-parsed (validated + sorted): the builder is public, and a caller may hand it a list\n // that never went through parseThresholds. Every rule below assumes ascending order.\n const thresholds = parseThresholds(options.thresholds ?? []);\n const lowest = thresholds.length > 0 ? thresholds[0].value : 0;\n const highest = thresholds.length > 0 ? thresholds[thresholds.length - 1].value : 0;\n const marks = thresholds.length > 0 ? thresholdMarks(theme, thresholds, options.unit, options.precision, axisFont) : undefined;\n const suffix = options.unit ? ` ${options.unit}` : '';\n const precision = options.precision;\n const gaps = (options.gaps ?? []).map(Date.parse).filter((g) => !Number.isNaN(g));\n const finite = (v: number | undefined): number | undefined => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);\n let fixedMin = finite(options.min);\n let fixedMax = finite(options.max);\n if (fixedMin !== undefined && fixedMax !== undefined && fixedMin >= fixedMax) fixedMin = fixedMax = undefined;\n\n const series = names.map((name, i) => {\n const color = theme.series[i % theme.series.length];\n return {\n ...(i === 0 ? marks : undefined),\n name,\n type: 'line' as const,\n showSymbol: false,\n lineStyle: { color },\n itemStyle: { color },\n data: breakAtGaps(\n samples\n .filter((s) => s.name === name && s.value != null && s.occurredTime != null)\n .map((s): [string, number] => [s.occurredTime as string, s.value as number]),\n gaps,\n ),\n };\n });\n\n return {\n animation: false,\n textStyle: { color: theme.foreground, fontSize: axisFont },\n grid: { left: 8, right: 12, top: names.length > 1 || options.unit ? 28 : 12, bottom: 8, containLabel: true },\n tooltip: {\n trigger: 'axis',\n valueFormatter: (v: unknown) => (typeof v === 'number' ? `${formatValue(v, precision)}${suffix}` : String(v ?? '\u2014')),\n },\n legend:\n names.length > 1 ? { textStyle: { color: theme.mutedForeground, fontSize: axisFont }, top: 0 } : undefined,\n xAxis: {\n type: 'time',\n axisLine: { lineStyle: { color: theme.border } },\n axisLabel: { color: theme.mutedForeground, fontSize: axisFont, hideOverlap: true },\n },\n yAxis: {\n type: 'value',\n // The unit rides the axis once, at its head, rather than on every tick.\n name: options.unit,\n nameTextStyle: { color: theme.mutedForeground, fontSize: axisFont, align: 'left' as const },\n splitLine: { lineStyle: { color: theme.border } },\n axisLabel: {\n color: theme.mutedForeground,\n fontSize: axisFont,\n // Rounded only when the author asked; otherwise ECharts' own tick rounding applies.\n ...(precision != null ? { formatter: (v: number) => formatValue(v, precision) } : {}),\n },\n // A threshold outside the data's range must still be on the chart: extend the range to\n // take it in. Only then -- a returned number FIXES that end of the axis (no nice\n // rounding, no zero baseline), so a threshold inside the data returns null and leaves\n // ECharts' own auto range exactly as it is without thresholds. An author's end (min/max)\n // is the same kind of bound: the axis reaches it, and goes past it only for a reading or a\n // threshold beyond it.\n ...(thresholds.length > 0 || fixedMin !== undefined || fixedMax !== undefined\n ? {\n min: (e: { min: number }) => axisEnd(true, e.min, fixedMin, thresholds.length > 0 ? lowest : undefined),\n max: (e: { max: number }) => axisEnd(false, e.max, fixedMax, thresholds.length > 0 ? highest : undefined),\n }\n : {}),\n },\n series,\n };\n}\n\nexport interface GaugeChartOptions {\n min?: number;\n max?: number;\n unit?: string;\n // Decimal places for the readout; unset uses the default rounding.\n precision?: number;\n // Severity thresholds, drawn as coloured bands on the arc (any order).\n thresholds?: readonly Threshold[];\n // The board's density scale: multiplies the label-font clamp and the readout's floor. Default 1.\n scale?: number;\n // Where the number is drawn. 'canvas' (the default) paints it inside the dial, as the builder\n // always has, so a widget that renders only the chart keeps its readout. 'none' leaves the dial\n // bare for a caller that draws the number itself as DOM text in gaugeReadoutBox, which the\n // readability gate can measure (the built-in gauge does).\n readout?: 'canvas' | 'none';\n // Where the needle is with no value. 'min' (the default) rests it at the scale's minimum, as the\n // builder always has. 'none' draws no needle, so an empty dial cannot be read as a reading of\n // its minimum (the built-in gauge, whose readout already says there is no value, asks for it).\n emptyNeedle?: 'min' | 'none';\n}\n\n// The dial's geometry as fractions of its box: where its centre sits and how much of the short\n// side's half it fills. The DOM readout is placed from the same numbers (gaugeReadoutBox).\nconst GAUGE_CENTER_Y = 0.58;\nconst GAUGE_RADIUS = 0.95;\n// How far below the hub the readout sits, as a fraction of the radius.\nconst GAUGE_READOUT_OFFSET = 0.3;\n\n// The box (px, relative to the chart) the gauge's DOM readout is centred in and fitted to: under\n// the hub and inside the dial, where the canvas detail used to be drawn. A zero size (before the\n// first measure) takes the nominal one the builder assumes.\nexport function gaugeReadoutBox(size?: ElementSize): { centerX: number; centerY: number; width: number; height: number } {\n const s = shortSide(size);\n const w = (size?.width ?? 0) > 0 ? size!.width : s;\n const h = (size?.height ?? 0) > 0 ? size!.height : s;\n return {\n centerX: w / 2,\n centerY: GAUGE_CENTER_Y * h + GAUGE_READOUT_OFFSET * GAUGE_RADIUS * (s / 2),\n width: s * 0.7,\n height: s * 0.25,\n };\n}\n\n// Below this short side (px) the gauge drops its axis labels: at that size they would be\n// drawn at the 8 px floor, which is noise rather than a scale.\nexport const GAUGE_AXIS_LABELS_MIN_SIDE = 120;\n\n// The arc's colour stops: ECharts wants [[endFraction, colour], ...] ending at 1. A neutral\n// stretch (below the lowest threshold, or a `normal` band) takes the track colour. With no bands: one track.\nfunction gaugeArcColors(bands: ReturnType<typeof thresholdBands>, min: number, max: number, theme: ChartTheme): [number, string][] {\n if (bands.length === 0) return [[1, theme.border]];\n return bands.map((b, i): [number, string] => [\n i === bands.length - 1 ? 1 : (b.to - min) / (max - min),\n levelColor(theme.severity, b.level) ?? theme.border,\n ]);\n}\n\n// buildGaugeOption maps a single latest value to a gauge. A null value (nothing\n// received yet) shows an em dash and rests the needle at the minimum. Ticks, fonts,\n// and the arc width scale with the widget size so it stays legible when resized\n// (ECharts' default gauge crams ~10 labels at fixed fonts on a small canvas).\nexport function buildGaugeOption(\n value: number | null,\n theme: ChartTheme,\n options: GaugeChartOptions = {},\n size?: ElementSize,\n): EChartOption {\n const min = options.min ?? 0;\n const max = options.max ?? 100;\n const thresholds = parseThresholds(options.thresholds ?? []); // validated + sorted, as above\n const bands = thresholdBands(thresholds, min, max);\n // Banded only when a COLOURED band actually lands on the arc: thresholds that all sit above\n // `max`, or only `normal` bands, leave a plain neutral track, which keeps the progress arc\n // like any other gauge.\n const banded = bands.some((b) => isAlarmLevel(b.level));\n // The needle takes the colour of the band the value sits in; with no bands, below the\n // lowest, or in a `normal` band it keeps the chart accent.\n const accent = levelColor(theme.severity, bandAt(thresholds, value)?.level) ?? theme.series[0];\n\n const s = shortSide(size);\n const arcWidth = clamp(Math.round(s / 26), 4, 12);\n const scale = options.scale ?? 1;\n const labelFont = clamp(Math.round(s / 20), Math.round(8 * scale), Math.round(13 * scale));\n const showAxisLabels = s >= GAUGE_AXIS_LABELS_MIN_SIDE;\n const unitSuffix = options.unit ? ` ${options.unit}` : '';\n // The readout is fitted to the dial's inner box and its own length, like every big number.\n const readout = value == null ? '\u2014' : `${formatValue(value, options.precision)}${unitSuffix}`;\n const valueFont = fitValueFont({ width: s * 0.7, height: s * 0.25 }, readout.length, {\n floor: Math.round(FIT_MIN_FONT_PX * scale),\n });\n return {\n animation: false,\n series: [\n {\n type: 'gauge',\n min,\n max,\n splitNumber: s < 160 ? 4 : 5, // fewer ticks than the default 10 \u2192 no cram\n radius: `${GAUGE_RADIUS * 100}%`,\n center: ['50%', `${GAUGE_CENTER_Y * 100}%`],\n // The progress arc would paint over the bands, so with bands the needle alone marks the value.\n progress: { show: !banded, width: arcWidth, itemStyle: { color: accent } },\n pointer: {\n show: value != null || options.emptyNeedle !== 'none',\n itemStyle: { color: accent },\n length: '55%',\n width: clamp(Math.round(s / 50), 2, 6),\n },\n anchor: { show: false },\n axisLine: { lineStyle: { width: arcWidth, color: gaugeArcColors(bands, min, max, theme) } },\n axisTick: { show: false },\n splitLine: { length: arcWidth, lineStyle: { color: theme.border, width: 1 } },\n axisLabel: { show: showAxisLabels, color: theme.mutedForeground, fontSize: labelFont, distance: arcWidth + 2 },\n detail:\n options.readout === 'none'\n ? { show: false }\n : {\n valueAnimation: false,\n color: theme.foreground,\n fontSize: valueFont,\n offsetCenter: [0, `${GAUGE_READOUT_OFFSET * 100}%`],\n formatter: (v: number) => (value == null ? '\u2014' : `${formatValue(v, options.precision)}${unitSuffix}`),\n },\n data: [{ value: value ?? min }],\n },\n ],\n };\n}\n\n// A heading in degrees folded onto [0, 360): 370 is 10 and -90 is 270, because a compass has no\n// \"beyond a full turn\" and a bearing sensor may well report either. 360 is 0, never 360, and a\n// value that is not a finite number has no heading at all (undefined), not a plausible one.\nexport function wrapHeading(value: number | null | undefined): number | undefined {\n if (value == null || !Number.isFinite(value)) return undefined;\n return ((value % 360) + 360) % 360;\n}\n\nexport interface CompassChartOptions {\n // The four point labels in N, E, S, W order (a locale writes West as \"O\", so the caller owns them).\n cardinals: readonly [string, string, string, string];\n thresholds?: readonly Threshold[];\n // The board's density scale; multiplies the label-font clamp. Default 1.\n scale?: number;\n}\n\n// buildCompassOption draws a full turn on the registered gauge series: north at the top, the\n// angle running clockwise, so 90 is east. The needle takes the colour of the band the (wrapped)\n// heading is in and the chart accent in a `normal` band or none. The degrees themselves are DOM\n// text beside it (compass.tsx). With no reading the needle rests at north.\nexport function buildCompassOption(\n value: number | null,\n theme: ChartTheme,\n options: CompassChartOptions,\n size?: ElementSize,\n): EChartOption {\n const heading = wrapHeading(value);\n const thresholds = parseThresholds(options.thresholds ?? []);\n const bands = thresholdBands(thresholds, 0, 360);\n const accent = levelColor(theme.severity, bandAt(thresholds, heading ?? null)?.level) ?? theme.series[0];\n const s = shortSide(size);\n const scale = options.scale ?? 1;\n const arcWidth = clamp(Math.round(s / 30), 3, 10);\n const labelFont = clamp(Math.round(s / 11), Math.round(10 * scale), Math.round(20 * scale));\n const [north, east, south, west] = options.cardinals;\n const points: Record<number, string> = { 0: north, 90: east, 180: south, 270: west };\n return {\n animation: false,\n series: [\n {\n type: 'gauge',\n min: 0,\n max: 360,\n startAngle: 90,\n endAngle: -270,\n splitNumber: 4,\n radius: '92%',\n center: ['50%', '50%'],\n progress: { show: false },\n pointer: { itemStyle: { color: accent }, length: '62%', width: clamp(Math.round(s / 36), 3, 8) },\n anchor: { show: true, size: clamp(Math.round(s / 24), 5, 12), itemStyle: { color: accent } },\n axisLine: { lineStyle: { width: arcWidth, color: gaugeArcColors(bands, 0, 360, theme) } },\n axisTick: { show: s >= GAUGE_AXIS_LABELS_MIN_SIDE, splitNumber: 3, length: arcWidth, lineStyle: { color: theme.border, width: 1 } },\n splitLine: { length: arcWidth * 1.6, lineStyle: { color: theme.mutedForeground, width: 2 } },\n // Only the four points are labelled; 360 is the same tick as 0, so it stays blank.\n axisLabel: {\n show: true,\n color: theme.foreground,\n fontSize: labelFont,\n distance: arcWidth * 1.6 + 6,\n formatter: (v: number) => points[v] ?? '',\n },\n detail: { show: false },\n data: [{ value: heading ?? 0 }],\n },\n ],\n };\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// The chart colour theme: concrete colours resolved from the host's CSS custom properties,\n// because an ECharts canvas cannot resolve `var(--x)`. Pure DOM + React, no echarts import,\n// but it lives on the `/echarts` subpath with the rest of the chart helpers so the SDK root\n// stays chart-free.\n\nimport { useMemo, useSyncExternalStore } from 'react';\n\nimport { useWidgetThemeRoot } from '../context';\nimport { severityColorsAt, severityFallbackColors, type AlarmLevel } from '../severity';\n\n// Concrete colors for an ECharts canvas, resolved from the CSS variables in scope\n// at a given element (charts can't use CSS vars directly).\nexport interface ChartTheme {\n foreground: string;\n mutedForeground: string;\n border: string;\n series: string[];\n // The four coloured threshold levels, concrete (comma-form `hsl(h, s%, l%)`, which every\n // canvas colour parser accepts and which severityFill can add an alpha to). `normal` has\n // none: it renders in the widget's own neutral (see severity.ts).\n severity: Record<AlarmLevel, string>;\n}\n\n// Fallbacks used when a variable is absent (e.g. jsdom, or a host that hasn't set\n// the token) so a chart still renders in sensible default colors.\nconst FALLBACK: ChartTheme = {\n foreground: 'hsl(240 10% 3.9%)',\n mutedForeground: 'hsl(240 3.8% 46.1%)',\n border: 'hsl(240 5.9% 90%)',\n series: [\n 'hsl(220 70% 50%)',\n 'hsl(160 60% 45%)',\n 'hsl(30 80% 55%)',\n 'hsl(280 65% 60%)',\n 'hsl(340 75% 55%)',\n ],\n severity: severityFallbackColors(),\n};\n\nfunction readVar(style: CSSStyleDeclaration, name: string, fallback: string): string {\n const raw = style.getPropertyValue(`--${name}`).trim();\n return raw ? `hsl(${raw})` : fallback;\n}\n\n// resolveChartTheme reads the theme tokens in scope at `el` into concrete colors\n// for ECharts. Reading at the element (not the document root) means a widget\n// nested under a re-themed subtree picks up the local override.\nexport function resolveChartTheme(el: Element): ChartTheme {\n const style = getComputedStyle(el);\n return {\n foreground: readVar(style, 'foreground', FALLBACK.foreground),\n mutedForeground: readVar(style, 'muted-foreground', FALLBACK.mutedForeground),\n border: readVar(style, 'border', FALLBACK.border),\n series: FALLBACK.series.map((fallback, i) => readVar(style, `chart-${i + 1}`, fallback)),\n severity: severityColorsAt(el, style),\n };\n}\n\n// --- shared chart-theme store ------------------------------------------------\n//\n// Charts need concrete colors resolved from the CSS-variable theme. Rather than\n// have every chart widget mount its own MutationObserver on <html> and recompute\n// the same theme, one page-wide observer resolves it once per change and every\n// widget reads the shared, memoized value via useSyncExternalStore \u2014 so a busy\n// dashboard pays O(1), not O(number of charts), per theme toggle.\n\nlet sharedTheme: ChartTheme | null = null;\nconst themeListeners = new Set<() => void>();\nlet themeObserver: MutationObserver | null = null;\n\nfunction recomputeTheme(): void {\n sharedTheme = resolveChartTheme(document.documentElement);\n}\n\nfunction subscribeTheme(listener: () => void): () => void {\n if (!themeObserver) {\n recomputeTheme();\n themeObserver = new MutationObserver(() => {\n recomputeTheme();\n for (const l of themeListeners) l();\n });\n themeObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ['class', 'style'],\n });\n }\n themeListeners.add(listener);\n return () => {\n themeListeners.delete(listener);\n if (themeListeners.size === 0 && themeObserver) {\n themeObserver.disconnect();\n themeObserver = null;\n sharedTheme = null;\n }\n };\n}\n\nfunction getThemeSnapshot(): ChartTheme {\n if (!sharedTheme) recomputeTheme();\n return sharedTheme as ChartTheme;\n}\n\n// useChartTheme returns the current chart colors and re-renders the caller when\n// the document theme changes (a light/dark class or inline-style swap on <html>).\nexport function useChartTheme(): ChartTheme {\n const shared = useSyncExternalStore(subscribeTheme, getThemeSnapshot, getThemeSnapshot);\n // A host that scopes its tokens to a container says so (WidgetThemeRoot); its tokens are\n // fixed for the container's life, so they are read once there rather than observed.\n const root = useWidgetThemeRoot();\n const scoped = useMemo(() => (root ? resolveChartTheme(root) : null), [root]);\n return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AAC3B,SAAO,MAAM;AACX,mBAAe,OAAO,QAAQ;AAC9B,QAAI,eAAe,SAAS,KAAK,eAAe;AAC9C,oBAAc,WAAW;AACzB,sBAAgB;AAChB,oBAAc;AAAA,IAChB;AAAA,EACF;AACF;AAEA,SAAS,mBAA+B;AACtC,MAAI,CAAC,YAAa,gBAAe;AACjC,SAAO;AACT;AAIO,SAAS,gBAA4B;AAC1C,QAAM,SAAS,qBAAqB,gBAAgB,kBAAkB,gBAAgB;AAGtF,QAAM,OAAO,mBAAmB;AAChC,QAAM,SAAS,QAAQ,MAAO,OAAO,kBAAkB,IAAI,IAAI,MAAO,CAAC,IAAI,CAAC;AAC5E,SAAO,UAAU;AACnB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export type WidgetEmptyKind = 'unbound' | 'not-reported' | 'no-data' | 'forbidden' | 'error';
|
|
2
|
+
export interface WidgetEmptyStrings {
|
|
3
|
+
unbound: {
|
|
4
|
+
title: string;
|
|
5
|
+
detail: string;
|
|
6
|
+
};
|
|
7
|
+
notReported: {
|
|
8
|
+
title: string;
|
|
9
|
+
detail: (measurement: string | undefined) => string;
|
|
10
|
+
};
|
|
11
|
+
noData: {
|
|
12
|
+
title: string;
|
|
13
|
+
detail: (measurement: string | undefined) => string;
|
|
14
|
+
};
|
|
15
|
+
forbidden: {
|
|
16
|
+
title: string;
|
|
17
|
+
detail: string;
|
|
18
|
+
};
|
|
19
|
+
error: {
|
|
20
|
+
title: string;
|
|
21
|
+
detail: string;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
export declare const WIDGET_EMPTY_STRINGS: Record<'en' | 'es', WidgetEmptyStrings>;
|
|
25
|
+
export declare function widgetEmptyStrings(locale?: string | undefined): WidgetEmptyStrings;
|
|
26
|
+
export interface WidgetEmptyStateProps {
|
|
27
|
+
kind: WidgetEmptyKind;
|
|
28
|
+
measurement?: string;
|
|
29
|
+
hint?: string;
|
|
30
|
+
detail?: string;
|
|
31
|
+
locale?: string;
|
|
32
|
+
}
|
|
33
|
+
export declare function WidgetEmptyState({ kind, measurement, hint, detail, locale }: WidgetEmptyStateProps): import("react").JSX.Element;
|
|
34
|
+
export interface LastValueStrings {
|
|
35
|
+
lastValue: (value: string, age: string) => string;
|
|
36
|
+
}
|
|
37
|
+
export declare const LAST_VALUE_STRINGS: Record<'en' | 'es', LastValueStrings>;
|
|
38
|
+
export declare function lastValueHint(value: string, age: string, locale?: string | undefined): string;
|