@devicechain/widget-sdk 1.5.0 → 1.6.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +40 -0
- package/README.md +33 -0
- package/dist/chunks/{chunk-25TE35L2.js → chunk-KKUMZN7N.js} +6 -5
- package/dist/chunks/chunk-KKUMZN7N.js.map +7 -0
- package/dist/chunks/{chunk-G6I5HKQM.js → chunk-MYW73WDC.js} +1 -1
- package/dist/chunks/chunk-MYW73WDC.js.map +7 -0
- package/dist/chunks/{chunk-IG6DBHKZ.js → chunk-R5MVRXBO.js} +3 -3
- package/dist/chunks/{chunk-IG6DBHKZ.js.map → chunk-R5MVRXBO.js.map} +1 -1
- package/dist/chunks/{chunk-6AJHBKU3.js → chunk-ZCOHPFPW.js} +2 -2
- package/dist/chunks/{chunk-6AJHBKU3.js.map → chunk-ZCOHPFPW.js.map} +1 -1
- package/dist/chunks/{echart-engine-FO4HQ22H.js → echart-engine-HYUPSQUL.js} +1 -1
- package/dist/chunks/echart-engine-HYUPSQUL.js.map +7 -0
- package/dist/chunks/{export-menu-727YDRIA.js → export-menu-VFLUUFWM.js} +8 -6
- package/dist/chunks/export-menu-VFLUUFWM.js.map +7 -0
- package/dist/echarts.js +48 -41
- package/dist/echarts.js.map +2 -2
- package/dist/empty-state.js +31 -15
- package/dist/empty-state.js.map +2 -2
- package/dist/freshness.d.ts +1 -1
- package/dist/index.js +7 -6
- package/dist/index.js.map +2 -2
- package/dist/strict-csp.js +1 -1
- package/package.json +4 -3
- package/dist/chunks/chunk-25TE35L2.js.map +0 -7
- package/dist/chunks/chunk-G6I5HKQM.js.map +0 -7
- package/dist/chunks/echart-engine-FO4HQ22H.js.map +0 -7
- package/dist/chunks/export-menu-727YDRIA.js.map +0 -7
package/AGENTS.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
Copyright The DeviceChain Authors
|
|
3
|
+
SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
-->
|
|
5
|
+
|
|
6
|
+
# AGENTS.md: @devicechain/widget-sdk
|
|
7
|
+
|
|
8
|
+
Notes for an AI coding agent writing a dashboard widget, or changing this package.
|
|
9
|
+
|
|
10
|
+
## What it is
|
|
11
|
+
|
|
12
|
+
The typed contract for a dashboard widget written as a React component, plus the sealed
|
|
13
|
+
registry that makes it available to a host application. The built-in widgets are declared
|
|
14
|
+
through exactly this interface. Read `README.md` for the full list of exports.
|
|
15
|
+
|
|
16
|
+
## Rules that save time
|
|
17
|
+
|
|
18
|
+
- **One copy of this package.** It defines the React contexts a widget reads (selection,
|
|
19
|
+
time range, theme root, density, freshness and others). A context is identified by the
|
|
20
|
+
object that created it, so declare `@devicechain/widget-sdk` as a **peer dependency** in
|
|
21
|
+
a widget package, never a dependency. Two copies means every context reads empty.
|
|
22
|
+
- **Peers, not bundles.** `react`, `echarts` and `@devicechain/dashboards` are peer
|
|
23
|
+
dependencies. Do not import ECharts or the map library from the chart-free root entry;
|
|
24
|
+
chart helpers live in their own entry so a DOM-only widget stays small.
|
|
25
|
+
- **Exports are public API.** A removal or rename breaks widget packages built elsewhere.
|
|
26
|
+
`src/dist-shape.test.ts` guards the built shape: when it fails, treat that as a
|
|
27
|
+
compatibility question before you update the expectation.
|
|
28
|
+
- **Colour comes from theme variables** (the `css` references), not hard-coded values, so a
|
|
29
|
+
widget follows light and dark themes and tenant branding.
|
|
30
|
+
- Every source file begins with the two-line SPDX header used across the repository.
|
|
31
|
+
|
|
32
|
+
## Commands
|
|
33
|
+
|
|
34
|
+
Run from `frontend/packages/widget-sdk` (the test script builds the sibling packages first):
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
npm run typecheck
|
|
38
|
+
npm test
|
|
39
|
+
npm run build
|
|
40
|
+
```
|
package/README.md
CHANGED
|
@@ -46,6 +46,17 @@ wants charts drawn on its first frame awaits `loadChartEngine()` before renderin
|
|
|
46
46
|
draws a chart can set `MyWidget.preload = loadChartEngine` on its component, and then
|
|
47
47
|
`preloadWidgets` from `@devicechain/widgets` fetches the engine for any board that contains it.
|
|
48
48
|
|
|
49
|
+
The other public subpaths are:
|
|
50
|
+
|
|
51
|
+
- `@devicechain/widget-sdk/empty-state`: `WidgetEmptyState`, `widgetEmptyStrings`,
|
|
52
|
+
`WIDGET_EMPTY_STRINGS` and their types. Render `<WidgetEmptyState kind="no-data" />`
|
|
53
|
+
inside a frame; kinds are `unbound`, `not-reported`, `no-data`, `forbidden`, `error`.
|
|
54
|
+
Optional `measurement`, `hint`, `detail` and `locale` customize the explanation.
|
|
55
|
+
- `@devicechain/widget-sdk/strict-csp`: `configureStrictCsp`, `strictCspEnabled` and
|
|
56
|
+
`plainTooltipText`. These are also root exports. Call `configureStrictCsp(true)`
|
|
57
|
+
before mounting under a strict style policy; use `plainTooltipText(text)` to
|
|
58
|
+
escape braces for canvas tooltips.
|
|
59
|
+
|
|
49
60
|
## Declare a widget
|
|
50
61
|
|
|
51
62
|
```tsx
|
|
@@ -98,6 +109,28 @@ for the built-in widgets.
|
|
|
98
109
|
Trusted widget code runs with the host page's privileges. The declarations in a descriptor
|
|
99
110
|
shape the API; they are not a security boundary.
|
|
100
111
|
|
|
112
|
+
## Component and host contract
|
|
113
|
+
|
|
114
|
+
A `WidgetProps<D>` component receives `widget`, channel-specific `data` and optional
|
|
115
|
+
`actions`. `useWidgetSelect()` and `useWidgetCandidates()` read optional host
|
|
116
|
+
interaction callbacks; handle undefined in a host without those services.
|
|
117
|
+
`useWidgetTimeRange()` and `useWidgetTimeZone()` read the board's range and zone.
|
|
118
|
+
Use `pickSample(latest, name)` for a single measurement (pass undefined for the
|
|
119
|
+
first one), and `optString(options, key)`, `optNumber(options, key)` or
|
|
120
|
+
`optBoolean(options, key)` for defensive option reads.
|
|
121
|
+
|
|
122
|
+
`useDashboardHub(resolver, authorities)` creates and disposes a live hub; pass
|
|
123
|
+
undefined for authorities in a read-only host. Standalone widgets can bind channel
|
|
124
|
+
state with `useMeasurementStream`, `useAlarmStream`, `useCommandStream` and
|
|
125
|
+
`useLocationStream`; a component registered with `defineWidget` already receives
|
|
126
|
+
its data from the host. `WidgetFrame` supplies body-size context for
|
|
127
|
+
`useWidgetScale()`; `useElementSize<T>(step?)` returns `[ref, { width, height }]`.
|
|
128
|
+
|
|
129
|
+
The registry exposes `catalog` for `parseDashboardDefinition(raw, { catalog })`;
|
|
130
|
+
pass that same registry to the renderer. An optional `implementation.editor`
|
|
131
|
+
receives `WidgetEditorProps`: `options`, `setOptions(patch)`, `descriptor` and
|
|
132
|
+
`services` (`slots`, optional device token and optional `commandChoices`).
|
|
133
|
+
|
|
101
134
|
## Offering a download from the frame
|
|
102
135
|
|
|
103
136
|
A widget can let the viewer save the data it shows. Pass `exportRows` to `WidgetFrame`: a function
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
severityTokenCss
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-MYW73WDC.js";
|
|
4
4
|
import {
|
|
5
5
|
strictCspEnabled
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-ZCOHPFPW.js";
|
|
7
7
|
|
|
8
8
|
// src/widget-options.ts
|
|
9
9
|
function pickSample(latest, name) {
|
|
@@ -78,11 +78,12 @@ function formatAge(age, locale = viewerLocale()) {
|
|
|
78
78
|
}
|
|
79
79
|
var FRESHNESS_STRINGS = {
|
|
80
80
|
en: { stale: "stale", ageLabel: "Last sample" },
|
|
81
|
-
es: { stale: "obsoleto", ageLabel: "
|
|
81
|
+
es: { stale: "obsoleto", ageLabel: "Última muestra" },
|
|
82
|
+
"zh-CN": { stale: "已过期", ageLabel: "最新样本" }
|
|
82
83
|
};
|
|
83
84
|
function freshnessStrings(locale = viewerLocale()) {
|
|
84
85
|
const base = locale?.toLowerCase().split("-")[0];
|
|
85
|
-
return base === "es" ? FRESHNESS_STRINGS.es : FRESHNESS_STRINGS.en;
|
|
86
|
+
return base === "es" ? FRESHNESS_STRINGS.es : base === "zh" ? FRESHNESS_STRINGS["zh-CN"] : FRESHNESS_STRINGS.en;
|
|
86
87
|
}
|
|
87
88
|
|
|
88
89
|
// src/theme.ts
|
|
@@ -170,4 +171,4 @@ export {
|
|
|
170
171
|
tokenStyle,
|
|
171
172
|
WidgetTokenStyles
|
|
172
173
|
};
|
|
173
|
-
//# sourceMappingURL=chunk-
|
|
174
|
+
//# sourceMappingURL=chunk-KKUMZN7N.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/widget-options.ts", "../../src/freshness.ts", "../../src/theme.ts", "../../src/tokens.tsx"],
|
|
4
|
+
"sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Small helpers for reading a widget's opaque `options` bag and picking the measurement a\n// single-value widget should show. They are the SDK's, not the built-ins': a third-party\n// widget reads its own options the same defensive way.\n\nimport type { MeasurementSample, WidgetInstance } from '@devicechain/dashboards';\n\n// pickSample chooses the sample a single-value widget (card, gauge) shows: the\n// named measurement, or the first available when no name is pinned.\nexport function pickSample(\n latest: Record<string, MeasurementSample>,\n name: string | undefined,\n): MeasurementSample | undefined {\n return name ? latest[name] : Object.values(latest)[0];\n}\n\n// --- options helpers ---------------------------------------------------------\n// A widget's `options` is opaque JSON (Record<string, unknown>) owned by the\n// widget; these read a key defensively, returning undefined on the wrong type\n// rather than throwing on a hand-edited definition.\n\ntype Options = Record<string, unknown> | undefined;\n\nexport function optString(options: Options, key: string): string | undefined {\n const value = options?.[key];\n return typeof value === 'string' ? value : undefined;\n}\n\nexport function optNumber(options: Options, key: string): number | undefined {\n const value = options?.[key];\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\n// A boolean flag option: true only when explicitly stored true (absent/other → false), so\n// an opt-in feature stays off by default and a hand-edited value can't accidentally enable it.\nexport function optBoolean(options: Options, key: string): boolean {\n return options?.[key] === true;\n}\n\n// primaryMeasurementName is the measurement a single-value widget (card, gauge)\n// displays: an explicit `options.measurement`, else the first measurement its\n// datasource selects, else undefined (fall back to whatever arrives first).\nexport function primaryMeasurementName(widget: WidgetInstance): string | undefined {\n const explicit = optString(widget.options, 'measurement');\n if (explicit) return explicit;\n const ds = widget.datasource;\n if (ds?.measurements && ds.measurements.length > 0) return ds.measurements[0];\n return undefined;\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// How old a widget's newest sample is, whether that is \"stale\", and how to say so. Pure, so\n// the precedence and the wording are testable without a DOM or a clock.\n\nimport type { MeasurementSample } from '@devicechain/dashboards';\n\nimport { optNumber } from './widget-options';\n\n// resolveStaleAfterSeconds is the age, in seconds, past which a widget's value is called stale,\n// or undefined when no honest threshold is known. Precedence:\n//\n// 1. the widget's own `staleAfterSeconds` option;\n// 2. (no source today) the device profile's expected reporting interval x 3 -- a profile\n// carries no measurement reporting interval at present, only a location-fix interval that\n// is documented as descriptive, so nothing is read here and nothing is invented;\n// 3. otherwise undefined: show the age, never style anything stale.\n//\n// 🔴 There is deliberately NO default. A fleet that reports hourly would be painted stale all\n// day by any number chosen here, and \"stale\" painted on healthy data teaches viewers to ignore\n// the badge. A non-positive value is not a threshold and counts as none.\nexport function resolveStaleAfterSeconds(options: Record<string, unknown> | undefined): number | undefined {\n const configured = optNumber(options, 'staleAfterSeconds');\n return configured !== undefined && configured > 0 ? configured : undefined;\n}\n\n// newestSampleTime is the latest occurredTime (epoch ms) among the named measurements' latest\n// samples, or undefined when none carries a parseable time. `names` empty or omitted means\n// every measurement the widget holds.\nexport function newestSampleTime(\n latest: Record<string, MeasurementSample>,\n names?: readonly string[],\n): number | undefined {\n let newest: number | undefined;\n for (const [name, sample] of Object.entries(latest)) {\n if (names && names.length > 0 && !names.includes(name)) continue;\n if (!sample.occurredTime) continue;\n const at = Date.parse(sample.occurredTime);\n if (Number.isNaN(at)) continue;\n if (newest === undefined || at > newest) newest = at;\n }\n return newest;\n}\n\n// ageSeconds is whole seconds since `at`, never negative: a device clock slightly ahead of the\n// viewer's would otherwise read \"in 3 seconds\".\nexport function ageSeconds(at: number, now: number): number {\n return Math.max(0, Math.floor((now - at) / 1000));\n}\n\n// isStale is true only when a threshold is known and the age has passed it.\nexport function isStale(age: number, staleAfter: number | undefined): boolean {\n return staleAfter !== undefined && age > staleAfter;\n}\n\n// The viewer's language, as the host app set it on <html lang>, else the browser's.\nexport function viewerLocale(): string | undefined {\n if (typeof document !== 'undefined' && document.documentElement.lang) return document.documentElement.lang;\n if (typeof navigator !== 'undefined' && navigator.language) return navigator.language;\n return undefined;\n}\n\n// One formatter per locale tag: every readout on a board re-formats once a second, and\n// building an Intl formatter is far dearer than using one.\nconst formatters = new Map<string, Intl.RelativeTimeFormat>();\n\nfunction relativeTimeFormat(locale: string | undefined): Intl.RelativeTimeFormat {\n const key = locale ?? '';\n let formatter = formatters.get(key);\n if (!formatter) {\n try {\n formatter = new Intl.RelativeTimeFormat(locale, { numeric: 'auto', style: 'short' });\n } catch {\n // An unparseable tag in <html lang> must not take a widget down: the runtime's default.\n formatter = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto', style: 'short' });\n }\n formatters.set(key, formatter);\n }\n return formatter;\n}\n\n// formatAge renders an age as \"12 sec. ago\" / \"hace 12 s\" in the viewer's locale, stepping up\n// to minutes, hours and days. Under a second it reads \"now\".\nexport function formatAge(age: number, locale: string | undefined = viewerLocale()): string {\n const formatter = relativeTimeFormat(locale);\n if (age < 60) return formatter.format(-age, 'second');\n if (age < 3600) return formatter.format(-Math.floor(age / 60), 'minute');\n if (age < 86400) return formatter.format(-Math.floor(age / 3600), 'hour');\n return formatter.format(-Math.floor(age / 86400), 'day');\n}\n\n// The SDK carries no i18n runtime, so the one word it adds to a board ships here, per\n// language, falling back to English. A host that wants another language passes `staleLabel`.\nexport interface FreshnessStrings {\n stale: string;\n ageLabel: string;\n}\n\nexport const FRESHNESS_STRINGS: Record<'en' | 'es' | 'zh-CN', FreshnessStrings> = {\n en: { stale: 'stale', ageLabel: 'Last sample' },\n es: { stale: 'obsoleto', ageLabel: 'Última muestra' },\n 'zh-CN': { stale: '已过期', ageLabel: '最新样本' },\n};\n\nexport function freshnessStrings(locale: string | undefined = viewerLocale()): FreshnessStrings {\n const base = locale?.toLowerCase().split('-')[0];\n return base === 'es' ? FRESHNESS_STRINGS.es : base === 'zh' ? FRESHNESS_STRINGS['zh-CN'] : FRESHNESS_STRINGS.en;\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Theming without Tailwind (widgets are embeddable — no Tailwind leakage).\n//\n// Widgets style themselves with inline styles that reference the SAME CSS custom\n// properties the console (and any host) defines — `--card`, `--foreground`,\n// `--border`, `--chart-1..5`, etc. A host that sets those variables themes the\n// widgets for free (light/dark included); a host without Tailwind still works.\n//\n// DOM elements can use `hsl(var(--card))` directly. ECharts renders to a <canvas>,\n// which cannot resolve CSS variables — so for charts we read the variables off the\n// live computed style and hand ECharts concrete color strings (resolveChartTheme).\n\nimport type { ThemeColorToken } from '@devicechain/dashboards';\n\n// css returns an `hsl(var(--name))` reference for use in an inline style. The host\n// defines the variable as HSL channels (e.g. `--card: 0 0% 100%`), matching the\n// console's token set.\nexport function css(name: ThemeVar): string {\n return `hsl(var(--${name}))`;\n}\n\n// The subset of the console's design tokens widgets rely on. Kept small and\n// semantic so the contract a host must provide is explicit and stable.\n//\n// Colours only: sizes are SizeTokens (see ./tokens). The chart ramp and the severity hues are\n// part of the set, so a widget colours itself from a token rather than a literal; `normal` has\n// NO severity token (it renders in the ordinary foreground, see ./severity).\n//\n// The list itself lives with the dashboard format (THEME_COLOR_TOKENS), because a definition\n// names these too, for a frame's border and background: one list, so a colour a widget can use\n// is exactly a colour a board may name.\nexport type ThemeVar = ThemeColorToken;\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Size tokens: the type ramp and spacing steps a widget draws from instead of writing px\n// literals, and the density scale they all multiply by.\n//\n// --dc-scale the board's density scale (0.9 compact / 1 comfortable / 1.5 wall)\n// --dc-font-<xs|sm|md|lg|xl|display> calc(<base px> * var(--dc-scale))\n// --dc-space-<1..4> calc(<base px> * var(--dc-scale))\n//\n// The `dc-` prefix is load-bearing: these are set on a board that lives inside someone else's\n// page, and the bare names collide -- Tailwind v4 keeps font FAMILIES in `--font-*` (a host's\n// `--font-display: \"Inter\"` is its documented example), so `var(--font-display, 28px)` in such\n// a host resolves to a family name and the font size is thrown away.\n//\n// The renderer sets them on its root (tokenStyle), so every widget under it scales with the\n// board's density; `fontVar('md')` is `var(--dc-font-md, 13px)`, which still renders the base\n// size anywhere the tokens are not set (a host that mounts a bare WidgetFrame). Canvas widgets\n// cannot read a CSS variable and take the numeric equivalent from useWidgetScale().px().\n//\n// Colour tokens are the ThemeVar set in ./theme; the severity hues are generated from the\n// table in ./severity (WidgetTokenStyles below injects them), so no colour is typed twice.\n\nimport { DENSITY_SCALE, SPACE_TOKEN_PX, type CanvasDensity } from '@devicechain/dashboards';\nimport type { CSSProperties } from 'react';\n\nimport { severityTokenCss } from './severity';\nimport { strictCspEnabled } from './strict-csp';\n\nexport const FONT_TOKENS = {\n xs: 11,\n sm: 12,\n md: 13,\n lg: 16,\n xl: 20,\n display: 28,\n} as const;\nexport type FontToken = keyof typeof FONT_TOKENS;\n\n// The spacing steps a widget draws from, read from the dashboard format's table (which also has\n// `space-0`, for a seamless board's gutter and a frameless widget's padding).\nexport const SPACE_TOKENS = {\n 1: SPACE_TOKEN_PX['space-1'],\n 2: SPACE_TOKEN_PX['space-2'],\n 3: SPACE_TOKEN_PX['space-3'],\n 4: SPACE_TOKEN_PX['space-4'],\n} as const;\nexport type SpaceToken = keyof typeof SPACE_TOKENS;\n\n// 'font-md' | 'space-3' -- the names useWidgetScale().px() accepts.\nexport type SizeToken = `font-${FontToken}` | `space-${SpaceToken}`;\n\nexport function densityScale(density: CanvasDensity | undefined): number {\n return DENSITY_SCALE[density ?? 'comfortable'];\n}\n\nexport function fontVar(token: FontToken): string {\n return `var(--dc-font-${token}, ${FONT_TOKENS[token]}px)`;\n}\n\nexport function spaceVar(token: SpaceToken): string {\n return `var(--dc-space-${token}, ${SPACE_TOKENS[token]}px)`;\n}\n\n// The numeric px of a size token at a scale, for a canvas that cannot read the variable.\nexport function tokenPx(token: SizeToken, scale = 1): number {\n const [kind, name] = token.split('-') as ['font' | 'space', string];\n const base = kind === 'font' ? FONT_TOKENS[name as FontToken] : SPACE_TOKENS[Number(name) as SpaceToken];\n return Math.round(base * scale * 100) / 100;\n}\n\n// The custom properties a board root sets for a density scale.\nexport function tokenStyle(scale: number): CSSProperties {\n const vars: Record<string, string> = { '--dc-scale': String(scale) };\n for (const [name, px] of Object.entries(FONT_TOKENS)) vars[`--dc-font-${name}`] = `calc(${px}px * var(--dc-scale))`;\n for (const [name, px] of Object.entries(SPACE_TOKENS)) vars[`--dc-space-${name}`] = `calc(${px}px * var(--dc-scale))`;\n return vars as CSSProperties;\n}\n\n// The severity hues as a stylesheet at ZERO specificity (`:where`), so a host that defines\n// `--sev-<level>` itself (any ordinary `:root` / `.dark` rule) always wins and a host that\n// does not still gets the colours. They sit on the document root, where useSeverityColors\n// reads them -- nothing is scoped to a board element, so no WidgetThemeRoot registration is\n// needed for them to resolve.\n//\n// 🔴 STRICT-CSP HOST MODE (configureStrictCsp). A page whose content-security policy has no\n// `style-src 'unsafe-inline'` refuses a <style> element, so in that mode, where constructed\n// stylesheets exist, the CSS is adopted by the document instead (CSSOM, which style-src does not\n// govern) -- once per page, however many boards mount. Otherwise, and whenever adoption fails, it\n// is the element, exactly as it always was.\nconst adoptedTokenCss = new Set<string>();\n\nfunction adoptTokenCss(css: string): boolean {\n if (adoptedTokenCss.has(css)) return true;\n if (typeof document === 'undefined' || !('adoptedStyleSheets' in document) || typeof CSSStyleSheet !== 'function') return false;\n try {\n const sheet = new CSSStyleSheet();\n sheet.replaceSync(css);\n document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];\n adoptedTokenCss.add(css);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function WidgetTokenStyles() {\n const css = severityTokenCss({ hostWins: true });\n // Adopted DURING render, not in an effect: an effect runs after the first commit, by which time a\n // <style> element would already have been rendered (and refused). The adoption is idempotent\n // (once per distinct CSS per page), so a repeated or discarded render does no harm.\n if (strictCspEnabled() && adoptTokenCss(css)) return <></>;\n return <style data-dc-tokens=\"\">{css}</style>;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;AAWO,SAAS,WACd,QACA,MAC+B;AAC/B,SAAO,OAAO,OAAO,IAAI,IAAI,OAAO,OAAO,MAAM,EAAE,CAAC;AACtD;AASO,SAAS,UAAU,SAAkB,KAAiC;AAC3E,QAAM,QAAQ,UAAU,GAAG;AAC3B,SAAO,OAAO,UAAU,WAAW,QAAQ;AAC7C;AAEO,SAAS,UAAU,SAAkB,KAAiC;AAC3E,QAAM,QAAQ,UAAU,GAAG;AAC3B,SAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;AAIO,SAAS,WAAW,SAAkB,KAAsB;AACjE,SAAO,UAAU,GAAG,MAAM;AAC5B;AAKO,SAAS,uBAAuB,QAA4C;AACjF,QAAM,WAAW,UAAU,OAAO,SAAS,aAAa;AACxD,MAAI,SAAU,QAAO;AACrB,QAAM,KAAK,OAAO;AAClB,MAAI,IAAI,gBAAgB,GAAG,aAAa,SAAS,EAAG,QAAO,GAAG,aAAa,CAAC;AAC5E,SAAO;AACT;;;AC5BO,SAAS,yBAAyB,SAAkE;AACzG,QAAM,aAAa,UAAU,SAAS,mBAAmB;AACzD,SAAO,eAAe,UAAa,aAAa,IAAI,aAAa;AACnE;AAKO,SAAS,iBACd,QACA,OACoB;AACpB,MAAI;AACJ,aAAW,CAAC,MAAM,MAAM,KAAK,OAAO,QAAQ,MAAM,GAAG;AACnD,QAAI,SAAS,MAAM,SAAS,KAAK,CAAC,MAAM,SAAS,IAAI,EAAG;AACxD,QAAI,CA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AQ,GAAG,IAAI;AAC1C;AAGO,SAAS,WAAW,OAA8B;AACvD,QAAM,OAA+B,EAAE,cAAc,OAAO,KAAK,EAAE;AACnE,aAAW,CAAC,MAAM,EAAE,KAAK,OAAO,QAAQ,WAAW,EAAG,MAAK,aAAa,IAAI,EAAE,IAAI,QAAQ,EAAE;AAC5F,aAAW,CAAC,MAAM,EAAE,KAAK,OAAO,QAAQ,YAAY,EAAG,MAAK,cAAc,IAAI,EAAE,IAAI,QAAQ,EAAE;AAC9F,SAAO;AACT;AAaA,IAAM,kBAAkB,oBAAI,IAAY;AAExC,SAAS,cAAcA,MAAsB;AAC3C,MAAI,gBAAgB,IAAIA,IAAG,EAAG,QAAO;AACrC,MAAI,OAAO,aAAa,eAAe,EAAE,wBAAwB,aAAa,OAAO,kBAAkB,WAAY,QAAO;AAC1H,MAAI;AACF,UAAM,QAAQ,IAAI,cAAc;AAChC,UAAM,YAAYA,IAAG;AACrB,aAAS,qBAAqB,CAAC,GAAG,SAAS,oBAAoB,KAAK;AACpE,oBAAgB,IAAIA,IAAG;AACvB,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,oBAAoB;AAClC,QAAMA,OAAM,iBAAiB,EAAE,UAAU,KAAK,CAAC;AAI/C,MAAI,iBAAiB,KAAK,cAAcA,IAAG,EAAG,QAAO,gCAAE;AACvD,SAAO,oBAAC,WAAM,kBAAe,IAAI,UAAAA,MAAI;AACvC;",
|
|
6
|
+
"names": ["css"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/context.tsx", "../../src/severity.ts"],
|
|
4
|
+
"sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// The ambient host context a widget reads: the resolved subject, the display time zone, the\n// theme root, the selection callback and the candidate provider.\n//\n// 🔴 THESE CONTEXTS ARE DEFINED HERE AND NOWHERE ELSE. A React context is identified by the\n// OBJECT createContext returned, so two copies of this module — one bundled into a widget\n// package, one in the host — are two unrelated contexts: the host's provider writes to one\n// and the widget reads the other, and the selector silently does nothing. Exactly one\n// definition, in this package, which `@devicechain/widgets` and every third-party widget\n// package depend on as a PEER (never a dependency) so the host's install supplies the\n// single copy.\n\nimport { createContext, useContext, useEffect, useRef, type ReactNode } from 'react';\n\nimport type { ResolvedFrame, SelectionCandidate, SelectionTarget, TimeRangeState } from '@devicechain/dashboards';\n\n// WidgetSubjectContext carries the resolved entity a widget shows (its datasource's\n// bound device/anchor), computed once by the renderer and provided per widget. The\n// frame reads it as a subtitle so every board answers \"which asset is this?\" — and,\n// because it reads the RESOLVED binding, it updates for free once selection re-points a\n// slot (ADR-039 selection-overlay amendment). Kept as ambient context, not a widget\n// prop, so the pure widget contract (widget, data) stays untouched and no widget needs\n// to know how a subject is resolved.\nconst WidgetSubjectContext = createContext<string | undefined>(undefined);\n\n// useWidgetSubject reads the resolved subject line (the frame's fallback subtitle).\nexport function useWidgetSubject(): string | undefined {\n return useContext(WidgetSubjectContext);\n}\n\nexport function WidgetSubjectProvider({\n label,\n children,\n}: {\n label: string | undefined;\n children: ReactNode;\n}) {\n return <WidgetSubjectContext.Provider value={label}>{children}</WidgetSubjectContext.Provider>;\n}\n\n// WidgetTimeZone is the zone widgets print instants in. Undefined (the default) means the\n// viewer's own zone, which is what every live host wants; a host replaying a recording\n// pins one so the board's times agree with the recording's own clock.\nconst WidgetTimeZoneContext = createContext<string | undefined>(undefined);\n\nexport function WidgetTimeZoneProvider({\n timeZone,\n children,\n}: {\n timeZone: string | undefined;\n children: ReactNode;\n}) {\n return <WidgetTimeZoneContext.Provider value={timeZone}>{children}</WidgetTimeZoneContext.Provider>;\n}\n\nexport function useWidgetTimeZone(): string | undefined {\n return useContext(WidgetTimeZoneContext);\n}\n\n// WidgetThemeRoot is the element chart colors are read from. Undefined (the default) means\n// the document root, which is where a console or dashboard app sets its tokens. A host that\n// scopes its tokens to a container (an embed on a page whose own stylesheet owns the root)\n// provides that container, and charts resolve their colors there instead.\nconst WidgetThemeRootContext = createContext<Element | undefined>(undefined);\n\nexport function WidgetThemeRootProvider({\n root,\n children,\n}: {\n root: Element | undefined;\n children: ReactNode;\n}) {\n return <WidgetThemeRootContext.Provider value={root}>{children}</WidgetThemeRootContext.Provider>;\n}\n\nexport function useWidgetThemeRoot(): Element | undefined {\n return useContext(WidgetThemeRootContext);\n}\n\n// The density scale the board renders at (0.9 compact / 1 comfortable / 1.5 wall), provided by\n// the renderer. Outside a renderer it is 1.\nconst WidgetDensityContext = createContext<number>(1);\n\nexport function WidgetDensityProvider({ scale, children }: { scale: number; children: ReactNode }) {\n return <WidgetDensityContext.Provider value={scale}>{children}</WidgetDensityContext.Provider>;\n}\n\nexport function useWidgetDensityScale(): number {\n return useContext(WidgetDensityContext);\n}\n\n// The size of the widget frame's padded content column in px (quantised), provided by\n// WidgetFrame to everything rendered inside it. {0,0} until measured, and outside a frame.\nexport interface WidgetBodySize {\n width: number;\n height: number;\n}\nconst ZERO_SIZE: WidgetBodySize = { width: 0, height: 0 };\nconst WidgetBodySizeContext = createContext<WidgetBodySize>(ZERO_SIZE);\n\nexport function WidgetBodySizeProvider({ size, children }: { size: WidgetBodySize; children: ReactNode }) {\n return <WidgetBodySizeContext.Provider value={size}>{children}</WidgetBodySizeContext.Provider>;\n}\n\nexport function useWidgetBodySize(): WidgetBodySize {\n return useContext(WidgetBodySizeContext);\n}\n\n// WidgetSelect is a view-interaction callback (ADR-039 selection amendment): a widget\n// drives a slot selection (an alarm-table originator drill, a context-selector pick) by\n// naming its target slot + the entity to bind. Kept DISTINCT from WidgetActions (the\n// write seam) — selection changes only the view's binding overlay, never the backend.\n// Provided by the renderer from the host; absent (undefined) in edit mode and any host\n// that wires no selection, so a widget feature-detects it before offering a drill.\nexport type WidgetSelect = (target: SelectionTarget) => void;\n\nconst WidgetSelectContext = createContext<WidgetSelect | undefined>(undefined);\n\nexport function WidgetSelectProvider({\n select,\n children,\n}: {\n select: WidgetSelect | undefined;\n children: ReactNode;\n}) {\n return <WidgetSelectContext.Provider value={select}>{children}</WidgetSelectContext.Provider>;\n}\n\n// useWidgetSelect returns the ambient selection callback, or undefined where selection is\n// not wired (edit mode, a read-only embedder). A widget renders its drill affordance only\n// when this is defined.\nexport function useWidgetSelect(): WidgetSelect | undefined {\n return useContext(WidgetSelectContext);\n}\n\n// WidgetCandidates is the ambient companion to WidgetSelect (ADR-039 selection amendment): a\n// context/entity-selector widget asks it for the options a target slot may bind to. The host\n// computes candidates from the definition's scope + resolved bindings (useSlotCandidates), so\n// the widget stays presentational and the pure widget contract stays untouched. Distinct from\n// the hub's data channels — candidates are a fetch-on-open list, not a live stream. Undefined\n// where not wired (edit/preview, a host that supplies no selection) → the selector is inert.\nexport type WidgetCandidates = (slot: string) => Promise<SelectionCandidate[]>;\n\nconst WidgetCandidatesContext = createContext<WidgetCandidates | undefined>(undefined);\n\nexport function WidgetCandidatesProvider({\n candidates,\n children,\n}: {\n candidates: WidgetCandidates | undefined;\n children: ReactNode;\n}) {\n return <WidgetCandidatesContext.Provider value={candidates}>{children}</WidgetCandidatesContext.Provider>;\n}\n\n// useWidgetCandidates returns the ambient candidate provider, or undefined where selection is\n// not wired. A selector widget renders its picker only when both this and useWidgetSelect are\n// defined.\nexport function useWidgetCandidates(): WidgetCandidates | undefined {\n return useContext(WidgetCandidatesContext);\n}\n\n// WidgetFreshness is what the host knows about how current a widget's data is: the time of its\n// newest sample (epoch ms) and the age past which that is stale. Provided only for a widget\n// whose descriptor opts in (`freshness: true`); the frame reads it and draws the age readout.\n// Absent, the frame draws nothing, so a widget that does not opt in is unchanged.\n//\n// `staleAfterSeconds` is undefined when no threshold is known, which means the age is shown\n// and nothing is ever styled stale. `at` is undefined while no sample has arrived.\nexport interface WidgetFreshness {\n at: number | undefined;\n staleAfterSeconds: number | undefined;\n}\n\nconst WidgetFreshnessContext = createContext<WidgetFreshness | undefined>(undefined);\n\nexport function WidgetFreshnessProvider({\n freshness,\n children,\n}: {\n freshness: WidgetFreshness | undefined;\n children: ReactNode;\n}) {\n return <WidgetFreshnessContext.Provider value={freshness}>{children}</WidgetFreshnessContext.Provider>;\n}\n\nexport function useWidgetFreshness(): WidgetFreshness | undefined {\n return useContext(WidgetFreshnessContext);\n}\n\n// What the widget's bound device's ACTIVE profile declares, for a widget that has nothing to draw and\n// needs to say whether the device will ever report what it asks for. `declared` is the declared\n// measurement names, `null` when the profile cannot say (none published, no way to look), and\n// `undefined` until it has been asked for and answered. Nothing is read until a widget calls\n// `ask()` -- a board whose widgets all have data costs no lookup. An unknown declaration is read\n// as declared, never as absent.\nexport interface WidgetDeclaredMetrics {\n declared: readonly string[] | null | undefined;\n ask: () => void;\n}\n\nconst NO_DECLARED: WidgetDeclaredMetrics = { declared: undefined, ask: () => undefined };\nconst WidgetDeclaredMetricsContext = createContext<WidgetDeclaredMetrics>(NO_DECLARED);\n\nexport function WidgetDeclaredMetricsProvider({\n value,\n children,\n}: {\n value: WidgetDeclaredMetrics;\n children: ReactNode;\n}) {\n return <WidgetDeclaredMetricsContext.Provider value={value}>{children}</WidgetDeclaredMetricsContext.Provider>;\n}\n\nexport function useWidgetDeclaredMetrics(): WidgetDeclaredMetrics {\n return useContext(WidgetDeclaredMetricsContext);\n}\n\n// The frame a board gives a widget: its canvas default merged with the widget's own override\n// (resolveFrame in @devicechain/dashboards). Absent -- a widget mounted outside a board -- the\n// frame is today's card.\nconst WidgetFrameStyleContext = createContext<ResolvedFrame | undefined>(undefined);\n\nexport function WidgetFrameStyleProvider({ frame, children }: { frame: ResolvedFrame | undefined; children: ReactNode }) {\n return <WidgetFrameStyleContext.Provider value={frame}>{children}</WidgetFrameStyleContext.Provider>;\n}\n\nexport function useWidgetFrameStyle(): ResolvedFrame | undefined {\n return useContext(WidgetFrameStyleContext);\n}\n\n// The board's time range: the span its time-series widgets draw (seconds back from now) and\n// whether the viewer has frozen the board. Provided by the renderer. A widget that draws\n// history reads it to label its axis or to ask its own questions; the built-in time-series chart\n// needs no code of its own, because the host sizes its window from the same value. `pausedAt`\n// is set exactly while `paused`, and is the instant the window ends at while frozen.\n//\n// Undefined outside a board (a widget mounted on its own), which is \"no range is imposed\" -- not\n// a default span. A widget must handle that rather than assume an hour.\nconst WidgetTimeRangeContext = createContext<TimeRangeState | undefined>(undefined);\n\nexport function WidgetTimeRangeProvider({\n range,\n children,\n}: {\n range: TimeRangeState | undefined;\n children: ReactNode;\n}) {\n return <WidgetTimeRangeContext.Provider value={range}>{children}</WidgetTimeRangeContext.Provider>;\n}\n\nexport function useWidgetTimeRange(): TimeRangeState | undefined {\n return useContext(WidgetTimeRangeContext);\n}\n\n// ---- Chart image export --------------------------------------------------------------------\n//\n// A chart widget draws into a canvas the frame cannot reach, and the frame owns the export menu. So\n// the chart wrapper (<EChart>) REGISTERS a way to read its image, and the frame offers \"Download\n// image\" only while one is registered: a widget that draws no chart has nothing to register and is\n// offered no image. The registrar is provided by the frame around its content; outside a frame it is\n// absent and registering does nothing.\n\n/** Reads the chart as a PNG data URL on the given background (a canvas is transparent), or undefined while it has none. */\nexport type WidgetImageSource = (options: { backgroundColor: string }) => string | undefined;\n\nconst WidgetImageRegistrarContext = createContext<((source: WidgetImageSource | undefined) => void) | undefined>(undefined);\n\nexport function WidgetImageRegistrarProvider({\n register,\n children,\n}: {\n register: (source: WidgetImageSource | undefined) => void;\n children: ReactNode;\n}) {\n return <WidgetImageRegistrarContext.Provider value={register}>{children}</WidgetImageRegistrarContext.Provider>;\n}\n\n/**\n * Offers the caller's image to the enclosing frame while `source` is given. It may change every\n * render; passing `undefined` withdraws it (a chart that has not drawn yet has no image to offer).\n */\nexport function useRegisterWidgetImage(source: WidgetImageSource | undefined): void {\n const register = useContext(WidgetImageRegistrarContext);\n const latest = useRef(source);\n latest.current = source;\n const offered = source !== undefined;\n useEffect(() => {\n if (!register || !offered) return;\n register((options) => latest.current?.(options));\n return () => register(undefined);\n }, [register, offered]);\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// The severity levels a threshold names, and the colours the ABNORMAL ones resolve to. A\n// threshold names a LEVEL, never a colour: an author cannot write `#f00`, so a board stays coherent under a re-themed host,\n// dark mode and (later) a greyscale operator theme where colour means severity and nothing\n// else.\n//\n// 🔑 `normal` HAS NO COLOUR. Colour appears only when something is abnormal (the ISA-101\n// rule): a value in a `normal` band renders exactly as it would with no thresholds at all --\n// the card's ordinary text, the gauge's neutral track and accent needle, no chart fill. So a\n// healthy \"below X\" rule and a healthy \"above X\" rule look the same. `normal` stays in the\n// level vocabulary because it is how a band ENDS (\"low fuel below 15\" is critical from 0,\n// normal from 15); it simply is not one of the coloured levels, and there is no\n// `--sev-normal` token. Each widget's own neutral is different (text, track, accent), which\n// is why the theme does not pretend to own one.\n//\n// 🔑 DEFINED ONCE, HERE. The values below are the single source of the `--sev-*` custom\n// properties. A host that defines `--sev-<level>` as HSL channels (the same convention as\n// every other token) wins; a host that does not still renders the colours below, light or\n// dark, so a threshold never draws as nothing for want of a token. `severityTokenCss()` emits\n// the same values as a stylesheet so a host's token set can be generated from this table\n// instead of re-typed.\n\nimport { useMemo, useSyncExternalStore } from 'react';\n\nimport { useWidgetThemeRoot } from './context';\n\nexport const SEVERITY_LEVELS = ['normal', 'warning', 'minor', 'major', 'critical'] as const;\nexport type SeverityLevel = (typeof SEVERITY_LEVELS)[number];\n\nexport function isSeverityLevel(value: unknown): value is SeverityLevel {\n return typeof value === 'string' && (SEVERITY_LEVELS as readonly string[]).includes(value);\n}\n\n// The levels that carry a colour: every level but `normal`.\nexport const ALARM_LEVELS = ['warning', 'minor', 'major', 'critical'] as const;\nexport type AlarmLevel = (typeof ALARM_LEVELS)[number];\n\nexport function isAlarmLevel(level: SeverityLevel | undefined): level is AlarmLevel {\n return level !== undefined && level !== 'normal';\n}\n\n// The colour a level renders in, or undefined for `normal` (and for no level): the caller then\n// uses its own neutral colour.\nexport function levelColor(colors: Readonly<Record<AlarmLevel, string>>, level: SeverityLevel | undefined): string | undefined {\n return isAlarmLevel(level) ? colors[level] : undefined;\n}\n\n// HSL channels (\"h s% l%\"), the form the host tokens use. The warm-to-cool ramp mirrors the\n// alarm severities (red, orange, amber, sky) so one hue means one severity on a card, a gauge\n// band and an alarm row. The dark column is lighter so each reads as INK against a dark ground.\nexport const SEVERITY_TOKENS: Readonly<Record<AlarmLevel, { light: string; dark: string }>> = {\n warning: { light: '199 89% 44%', dark: '199 89% 62%' },\n minor: { light: '32 95% 40%', dark: '38 92% 56%' },\n major: { light: '25 95% 48%', dark: '25 95% 62%' },\n critical: { light: '0 72% 46%', dark: '0 84% 66%' },\n};\n\n// The custom-property name a host defines for a coloured level.\nexport function severityVar(level: AlarmLevel): string {\n return `--sev-${level}`;\n}\n\n// The tokens as CSS, `:root` light and `.dark` dark -- what a host stylesheet pastes (or a\n// build step writes) so the host and this package cannot disagree about a colour. `hostWins`\n// wraps the selectors in `:where()` (zero specificity) for a stylesheet injected alongside a\n// host's own: any ordinary host rule for the same variable then beats it.\nexport function severityTokenCss(options: { hostWins?: boolean } = {}): string {\n const wrap = (selector: string) => (options.hostWins ? `:where(${selector})` : selector);\n const block = (selector: string, side: 'light' | 'dark') =>\n [\n `${wrap(selector)} {`,\n ...ALARM_LEVELS.map((l) => ` ${severityVar(l)}: ${SEVERITY_TOKENS[l][side]};`),\n '}',\n ].join('\\n');\n return `${block(':root', 'light')}\\n${block('.dark', 'dark')}\\n`;\n}\n\n// --- concrete colours ---------------------------------------------------------------\n//\n// A canvas (and an inline style that must be one value) needs a concrete colour, not\n// `var(--sev-x)`. These resolve the level colours in scope at an element: the host's\n// `--sev-<level>` token when it defines one, else the table above for the light or dark ground.\n// They live HERE, not with the chart theme, so a DOM-only widget (a card colouring its value\n// by threshold) gets them from the SDK root without reaching into the `/echarts` entry; the\n// chart theme reads its severity colours through the same functions.\n\n// A channel triple (\"h s% l%\", space- or comma-separated) as a comma-form hsl() colour, the\n// form every canvas colour parser accepts and severityFill can add an alpha to.\nfunction hslFromChannels(channels: string): string {\n const [h, s, l] = channels.replace(/,/g, ' ').trim().split(/\\s+/);\n return `hsl(${h}, ${s}, ${l})`;\n}\n\nfunction severityColors(dark: boolean, host: (cssVar: string) => string | undefined): Record<AlarmLevel, string> {\n const out = {} as Record<AlarmLevel, string>;\n for (const level of ALARM_LEVELS) {\n out[level] = hslFromChannels(host(severityVar(level)) || SEVERITY_TOKENS[level][dark ? 'dark' : 'light']);\n }\n return out;\n}\n\n// Dark when the element sits under a `.dark` ancestor -- the host convention every token block\n// here uses -- or the document root carries it.\nfunction isDark(el: Element): boolean {\n return el.closest('.dark') !== null || el.ownerDocument.documentElement.classList.contains('dark');\n}\n\n// The light colours with no host involved (jsdom, a host with no tokens yet).\nexport function severityFallbackColors(): Record<AlarmLevel, string> {\n return severityColors(false, () => undefined);\n}\n\n// The colours in scope at `el`. `style` is its computed style when the caller already has it.\nexport function severityColorsAt(el: Element, style: CSSStyleDeclaration = getComputedStyle(el)): Record<AlarmLevel, string> {\n return severityColors(isDark(el), (name) => style.getPropertyValue(name).trim() || undefined);\n}\n\n// One page-wide observer, shared by every caller (the same O(1)-per-toggle shape as the chart\n// theme store): re-resolved when <html> changes class (light/dark) or inline style (tokens).\nlet shared: Record<AlarmLevel, string> | null = null;\nconst listeners = new Set<() => void>();\nlet observer: MutationObserver | null = null;\n\nfunction subscribe(listener: () => void): () => void {\n if (!observer) {\n shared = severityColorsAt(document.documentElement);\n observer = new MutationObserver(() => {\n shared = severityColorsAt(document.documentElement);\n for (const l of listeners) l();\n });\n observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style'] });\n }\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0 && observer) {\n observer.disconnect();\n observer = null;\n shared = null;\n }\n };\n}\n\nfunction snapshot(): Record<AlarmLevel, string> {\n shared ??= severityColorsAt(document.documentElement);\n return shared;\n}\n\n// useSeverityColors returns the four concrete severity colours (none for `normal`) and re-renders the caller when\n// the document theme changes. A container-scoped theme (WidgetThemeRoot) is read once there,\n// as the chart theme does.\nexport function useSeverityColors(): Record<AlarmLevel, string> {\n const page = useSyncExternalStore(subscribe, snapshot, snapshot);\n const root = useWidgetThemeRoot();\n const scoped = useMemo(() => (root ? severityColorsAt(root) : null), [root]);\n return scoped ?? page;\n}\n"],
|
|
5
|
+
"mappings": ";AAcA,SAAS,eAAe,YAAY,WAAW,cAA8B;AAyBpE;AAdT,IAAM,uBAAuB,cAAkC,MAAS;AAGjE,SAAS,mBAAuC;AACrD,SAAO,WAAW,oBAAoB;AACxC;AAEO,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AACF,GAGG;AACD,SAAO,oBAAC,qBAAqB,UAArB,EAA8B,OAAO,OAAQ,UAAS;AAChE;AAKA,IAAM,wBAAwB,cAAkC,MAAS;AAElE,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AACF,GAGG;AACD,SAAO,oBAAC,sBAAsB,UAAtB,EAA+B,OAAO,UAAW,UAAS;AACpE;AAEO,SAAS,oBAAwC;AACtD,SAAO,WAAW,qBAAqB;AACzC;AAMA,IAAM,yBAAyB,cAAmC,MAAS;AAEpE,SAAS,wBAAwB;AAAA,EACtC;AAAA,EACA;AACF,GAGG;AACD,SAAO,oBAAC,uBAAuB,UAAvB,EAAgC,OAAO,MAAO,UAAS;AACjE;AAEO,SAAS,qBAA0C;AACxD,SAAO,WAAW,sBAAsB;AAC1C;AAIA,IAAM,uBAAuB,cAAsB,CAAC;AAE7C,SAAS,sBAAsB,EAAE,OAAO,SAAS,GAA2C;AACjG,SAAO,oBAAC,qBAAqB,UAArB,EAA8B,OAAO,OAAQ,UAAS;AAChE;AAEO,SAAS,wBAAgC;AAC9C,SAAO,WAAW,oBAAoB;AACxC;AAQA,IAAM,YAA4B,EAAE,OAAO,GAAG,QAAQ,EAAE;AACxD,IAAM,wBAAwB,cAA8B,SAAS;AAE9D,SAAS,uBAAuB,EAAE,MAAM,SAAS,GAAkD;AACxG,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I,SAA4C;AAChD,IAAM,YAAY,oBAAI,IAAgB;AACtC,IAAI,WAAoC;AAExC,SAAS,UAAU,UAAkC;AACnD,MAAI,CAAC,UAAU;AACb,aAAS,iBAAiB,SAAS,eAAe;AAClD,eAAW,IAAI,iBAAiB,MAAM;AACpC,eAAS,iBAAiB,SAAS,eAAe;AAClD,iBAAW,KAAK,UAAW,GAAE;AAAA,IAC/B,CAAC;AACD,aAAS,QAAQ,SAAS,iBAAiB,EAAE,YAAY,MAAM,iBAAiB,CAAC,SAAS,OAAO,EAAE,CAAC;AAAA,EACtG;AACA,YAAU,IAAI,QAAQ;AACtB,SAAO,MAAM;AACX,cAAU,OAAO,QAAQ;AACzB,QAAI,UAAU,SAAS,KAAK,UAAU;AACpC,eAAS,WAAW;AACpB,iBAAW;AACX,eAAS;AAAA,IACX;AAAA,EACF;AACF;AAEA,SAAS,WAAuC;AAC9C,sBAAW,iBAAiB,SAAS,eAAe;AACpD,SAAO;AACT;AAKO,SAAS,oBAAgD;AAC9D,QAAM,OAAO,qBAAqB,WAAW,UAAU,QAAQ;AAC/D,QAAM,OAAO,mBAAmB;AAChC,QAAM,SAAS,QAAQ,MAAO,OAAO,iBAAiB,IAAI,IAAI,MAAO,CAAC,IAAI,CAAC;AAC3E,SAAO,UAAU;AACnB;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
isSeverityLevel
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-MYW73WDC.js";
|
|
4
4
|
|
|
5
5
|
// src/fit-text.ts
|
|
6
6
|
var FIT_MIN_FONT_PX = 12;
|
|
@@ -49,7 +49,7 @@ function defaultFormat(value) {
|
|
|
49
49
|
return String(rounded);
|
|
50
50
|
}
|
|
51
51
|
function formatValue(value, precision) {
|
|
52
|
-
if (value == null) return "
|
|
52
|
+
if (value == null) return "—";
|
|
53
53
|
if (precision == null) return defaultFormat(value);
|
|
54
54
|
const places = Math.min(100, Math.max(0, Math.trunc(precision)));
|
|
55
55
|
return value.toFixed(places);
|
|
@@ -106,4 +106,4 @@ export {
|
|
|
106
106
|
bandAt,
|
|
107
107
|
thresholdBands
|
|
108
108
|
};
|
|
109
|
-
//# sourceMappingURL=chunk-
|
|
109
|
+
//# sourceMappingURL=chunk-R5MVRXBO.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/fit-text.ts", "../../src/format.ts", "../../src/thresholds.ts"],
|
|
4
|
-
"sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// fitValueFont -- the one font-size curve for a big readout (a card's number, a KPI count, a\n// gauge's value). Every widget used to carry its own clamp of the card HEIGHT with a hard cap\n// (44 px, 56 px); that ignored the width, so a long string overflowed a wide-but-short or\n// narrow-but-tall box, and it stopped growing on a wall display. This curve reads both\n// dimensions and the string length.\n//\n// font = min( height * HEIGHT_SHARE , width / (chars * GLYPH_WIDTH) )\n//\n// then floored at MIN_FONT_PX. There is no upper cap: a bigger box gets a bigger number.\n//\n// `size` is the box the text may occupy, so a caller passes its content box (the measured\n// element minus its own padding). HEIGHT_SHARE leaves room for the line's leading and for a\n// secondary line (unit, caption) beneath it. GLYPH_WIDTH is the advance of a digit as a\n// fraction of the font size. Measured: system faces (Segoe UI, Roboto, Arial bold) set a\n// digit at 0.56-0.58 em, but the console's Inter sets them at 0.61-0.62 em on average and\n// 0.67 em at the widest in the 600-700 weights a readout uses. 0.65 covers Inter's digits to\n// within a few percent (which the caller's padding absorbs) without shrinking a system-font\n// number much; a '.' or '-' counted as a full character adds slack.\n\nexport const FIT_MIN_FONT_PX = 12;\n// What to use before the first measure (ElementSize is {0,0} until then) or in a non-DOM test.\nexport const FIT_FALLBACK_FONT_PX = 32;\n\n// The curve's two constants. Exported so the CSS path (fitValueFontCss, `cq` units) and the\n// JS path (fitValueFont, a canvas widget's numeric font) are built from THESE and cannot\n// drift: a number in a card and a number in a gauge of the same size look the same.\nexport const FIT_HEIGHT_SHARE = 0.6;\nexport const FIT_GLYPH_WIDTH = 0.65;\n\nexport interface FitOptions {\n // The smallest font the curve returns, in px. Density scales THIS (a wall display's floor is\n // larger, a compact board's smaller); the curve itself never changes. Default FIT_MIN_FONT_PX.\n floor?: number;\n}\n\nfunction charCount(chars: number): number {\n return Math.max(1, Math.ceil(Number.isFinite(chars) ? chars : 1));\n}\n\nexport function fitValueFont(size: { width: number; height: number }, chars: number, options: FitOptions = {}): number {\n const floor = options.floor ?? FIT_MIN_FONT_PX;\n if (!(size.width > 0) || !(size.height > 0)) return Math.max(floor, FIT_FALLBACK_FONT_PX);\n const byHeight = size.height * FIT_HEIGHT_SHARE;\n const byWidth = size.width / (charCount(chars) * FIT_GLYPH_WIDTH);\n return Math.max(floor, Math.floor(Math.min(byHeight, byWidth)));\n}\n\n// The same curve as a CSS length, for text inside a `container-type: size` box (the widget\n// frame's content column): `cqh`/`cqw` are that box's height and width, so the browser resolves\n// the font on the very first frame -- no {0,0} measure flash -- and re-resolves on every\n// resize with no JS. The box a caller passes to fitValueFont is the SAME box these units\n// measure (the frame's padded content column).\nexport function fitValueFontCss(chars: number, options: FitOptions = {}): string {\n const floor = options.floor ?? FIT_MIN_FONT_PX;\n const perChar = 100 / (charCount(chars) * FIT_GLYPH_WIDTH);\n return `max(${floor}px, min(${FIT_HEIGHT_SHARE * 100}cqh, ${Number(perChar.toFixed(3))}cqw))`;\n}\n\n// A big readout's character count held at the longest recently seen, so a value crossing\n// 9.99 -> 10.01 does not jump the font size by a character's worth (~20 % on a short\n// string). The count grows at once and shrinks only after `holdMs` with nothing longer.\nexport interface StickyChars {\n value: number;\n since: number;\n}\n\nexport function stickyChars(prev: StickyChars | undefined, chars: number, now: number, holdMs: number): StickyChars {\n if (!prev || chars >= prev.value) return { value: chars, since: now };\n if (now - prev.since >= holdMs) return { value: chars, since: now };\n return prev;\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Both formatters take an optional IANA `timeZone`. Omitted, they are exactly what they\n// always were: the viewer's own zone and locale defaults, which is right for a live board.\n// A host that plays a RECORDING pins one (the renderer's `timeZone` prop), because the\n// recorded instants are the point and a viewer's zone would shift them across a date line;\n// a pinned zone also prints its short name, so the reading says which clock it is.\n\n// formatTimestamp renders an RFC3339 event time as a locale time string, leaving\n// an unparseable value untouched and an absent one blank.\nexport function formatTimestamp(iso: string | null, timeZone?: string): string {\n if (!iso) return '';\n const date = new Date(iso);\n if (Number.isNaN(date.getTime())) return iso;\n return timeZone ? date.toLocaleTimeString(undefined, { timeZone, timeZoneName: 'short' }) : date.toLocaleTimeString();\n}\n\n// formatDateTime renders an RFC3339 time as a locale date+time string. Unlike\n// formatTimestamp (time-only, right for a live measurement tick) this keeps the date,\n// because an alarm can have been raised days ago and a bare \"09:14:32\" would mislead.\nexport function formatDateTime(iso: string | null, timeZone?: string): string {\n if (!iso) return '';\n const date = new Date(iso);\n if (Number.isNaN(date.getTime())) return iso;\n return timeZone ? date.toLocaleString(undefined, { timeZone, timeZoneName: 'short' }) : date.toLocaleString();\n}\n\n// With no precision configured a value is still not printed at full float width: a sensor's\n// 30.203057033956792 is noise on a card, a gauge or an alarm row. So an unset precision shows\n// at most DEFAULT_FRACTION_DIGITS decimals (trailing zeros dropped), and a value under 1 keeps\n// DEFAULT_SMALL_SIGNIFICANT significant digits instead, so a 0.000123 reading is not rounded\n// to nothing. An author who wants exact decimals sets `precision`.\nexport const DEFAULT_FRACTION_DIGITS = 3;\nexport const DEFAULT_SMALL_SIGNIFICANT = 4;\n\nfunction defaultFormat(value: number): string {\n if (!Number.isFinite(value)) return String(value);\n const rounded =\n Math.abs(value) >= 1 ? Number(value.toFixed(DEFAULT_FRACTION_DIGITS)) : Number(value.toPrecision(DEFAULT_SMALL_SIGNIFICANT));\n return String(rounded);\n}\n\n// formatValue renders a measurement value, applying a fixed precision when given\n// (else the default rounding above) and showing an em dash for a missing value.\n//\n// The precision is clamped to toFixed's domain because it arrives from an opaque stored\n// definition: outside 0..100 toFixed throws a RangeError, which is an exception thrown\n// during render \u2014 it unmounts the widget's whole subtree rather than degrading, and every\n// other bad option value in this package degrades. The console's config panel can author\n// a negative one today, and a hand-edited definition always could.\nexport function formatValue(value: number | null | undefined, precision?: number): string {\n if (value == null) return '\u2014';\n if (precision == null) return defaultFormat(value);\n const places = Math.min(100, Math.max(0, Math.trunc(precision)));\n return value.toFixed(places);\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Thresholds: where a measurement crosses from one severity to the next.\n//\n// A threshold STARTS a band: it holds from its `value` up to the next threshold's value (or\n// without end, for the last). Below the lowest threshold there is no band, so a value there\n// reads in the widget's own neutral colour, as does a value in a `normal` band (normal has no\n// colour; see severity.ts), so a healthy value looks the same under either kind of rule.\n// This one rule covers both directions:\n// - \"overheat above 105\" -> [{ value: 105, level: 'critical' }]\n// - \"low fuel below 15\" -> [{ value: 0, level: 'critical' }, { value: 15, level: 'normal' }]\n// A value ON a threshold belongs to the band that threshold starts (>=), never the one below.\n\nimport { isSeverityLevel, type SeverityLevel } from './severity';\n\nexport interface Threshold {\n value: number;\n level: SeverityLevel;\n label?: string;\n}\n\n// A band resolved over a numeric range. `level` is undefined for the neutral stretch below the\n// lowest threshold. `to` is Infinity for the last band.\nexport interface ThresholdBand {\n from: number;\n to: number;\n level: SeverityLevel | undefined;\n label?: string;\n}\n\n// parseThresholds reads the stored option defensively: a hand-edited definition may carry\n// anything, and a threshold that cannot be read must drop out rather than throw during render\n// (or, worse, colour a value by a guess). Only a finite `value` and a known `level` survive --\n// so a free colour in the `level` slot is dropped, and an extra `color` key is never read.\n// The result is sorted ascending by value (stable, so equal values keep their authored order\n// and the later one wins).\nexport function parseThresholds(raw: unknown): Threshold[] {\n if (!Array.isArray(raw)) return [];\n const out: Threshold[] = [];\n for (const item of raw) {\n if (typeof item !== 'object' || item === null) continue;\n const { value, level, label } = item as Record<string, unknown>;\n if (typeof value !== 'number' || !Number.isFinite(value) || !isSeverityLevel(level)) continue;\n out.push(typeof label === 'string' && label !== '' ? { value, level, label } : { value, level });\n }\n return out.map((t, i) => ({ t, i })).sort((a, b) => a.t.value - b.t.value || a.i - b.i).map(({ t }) => t);\n}\n\nexport function optThresholds(options: Record<string, unknown> | undefined, key = 'thresholds'): Threshold[] {\n return parseThresholds(options?.[key]);\n}\n\n// bandAt returns the threshold whose band holds `value`, or undefined below the lowest.\n// `thresholds` must be sorted (parseThresholds does). A null value has no band.\nexport function bandAt(thresholds: readonly Threshold[], value: number | null | undefined): Threshold | undefined {\n if (value == null || !Number.isFinite(value)) return undefined;\n let hit: Threshold | undefined;\n for (const t of thresholds) {\n if (value >= t.value) hit = t;\n else break;\n }\n return hit;\n}\n\n// thresholdBands lays the bands over [min, max]: a neutral lead-in up to the first threshold,\n// then one band per threshold, each clipped to the range. Bands that fall wholly outside the\n// range are dropped, and the band in effect AT `min` is carried in from a threshold below it.\n// The result tiles [min, max] exactly, which is what a gauge arc needs.\nexport function thresholdBands(thresholds: readonly Threshold[], min: number, max: number): ThresholdBand[] {\n if (!(max > min)) return [];\n const bands: ThresholdBand[] = [];\n const push = (from: number, to: number, level: SeverityLevel | undefined, label?: string) => {\n const a = Math.max(from, min);\n const b = Math.min(to, max);\n if (b > a) bands.push(label === undefined ? { from: a, to: b, level } : { from: a, to: b, level, label });\n };\n if (thresholds.length === 0) return [];\n push(-Infinity, thresholds[0].value, undefined);\n thresholds.forEach((t, i) => push(t.value, thresholds[i + 1]?.value ?? Infinity, t.level, t.label));\n return bands;\n}\n"],
|
|
4
|
+
"sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// fitValueFont -- the one font-size curve for a big readout (a card's number, a KPI count, a\n// gauge's value). Every widget used to carry its own clamp of the card HEIGHT with a hard cap\n// (44 px, 56 px); that ignored the width, so a long string overflowed a wide-but-short or\n// narrow-but-tall box, and it stopped growing on a wall display. This curve reads both\n// dimensions and the string length.\n//\n// font = min( height * HEIGHT_SHARE , width / (chars * GLYPH_WIDTH) )\n//\n// then floored at MIN_FONT_PX. There is no upper cap: a bigger box gets a bigger number.\n//\n// `size` is the box the text may occupy, so a caller passes its content box (the measured\n// element minus its own padding). HEIGHT_SHARE leaves room for the line's leading and for a\n// secondary line (unit, caption) beneath it. GLYPH_WIDTH is the advance of a digit as a\n// fraction of the font size. Measured: system faces (Segoe UI, Roboto, Arial bold) set a\n// digit at 0.56-0.58 em, but the console's Inter sets them at 0.61-0.62 em on average and\n// 0.67 em at the widest in the 600-700 weights a readout uses. 0.65 covers Inter's digits to\n// within a few percent (which the caller's padding absorbs) without shrinking a system-font\n// number much; a '.' or '-' counted as a full character adds slack.\n\nexport const FIT_MIN_FONT_PX = 12;\n// What to use before the first measure (ElementSize is {0,0} until then) or in a non-DOM test.\nexport const FIT_FALLBACK_FONT_PX = 32;\n\n// The curve's two constants. Exported so the CSS path (fitValueFontCss, `cq` units) and the\n// JS path (fitValueFont, a canvas widget's numeric font) are built from THESE and cannot\n// drift: a number in a card and a number in a gauge of the same size look the same.\nexport const FIT_HEIGHT_SHARE = 0.6;\nexport const FIT_GLYPH_WIDTH = 0.65;\n\nexport interface FitOptions {\n // The smallest font the curve returns, in px. Density scales THIS (a wall display's floor is\n // larger, a compact board's smaller); the curve itself never changes. Default FIT_MIN_FONT_PX.\n floor?: number;\n}\n\nfunction charCount(chars: number): number {\n return Math.max(1, Math.ceil(Number.isFinite(chars) ? chars : 1));\n}\n\nexport function fitValueFont(size: { width: number; height: number }, chars: number, options: FitOptions = {}): number {\n const floor = options.floor ?? FIT_MIN_FONT_PX;\n if (!(size.width > 0) || !(size.height > 0)) return Math.max(floor, FIT_FALLBACK_FONT_PX);\n const byHeight = size.height * FIT_HEIGHT_SHARE;\n const byWidth = size.width / (charCount(chars) * FIT_GLYPH_WIDTH);\n return Math.max(floor, Math.floor(Math.min(byHeight, byWidth)));\n}\n\n// The same curve as a CSS length, for text inside a `container-type: size` box (the widget\n// frame's content column): `cqh`/`cqw` are that box's height and width, so the browser resolves\n// the font on the very first frame -- no {0,0} measure flash -- and re-resolves on every\n// resize with no JS. The box a caller passes to fitValueFont is the SAME box these units\n// measure (the frame's padded content column).\nexport function fitValueFontCss(chars: number, options: FitOptions = {}): string {\n const floor = options.floor ?? FIT_MIN_FONT_PX;\n const perChar = 100 / (charCount(chars) * FIT_GLYPH_WIDTH);\n return `max(${floor}px, min(${FIT_HEIGHT_SHARE * 100}cqh, ${Number(perChar.toFixed(3))}cqw))`;\n}\n\n// A big readout's character count held at the longest recently seen, so a value crossing\n// 9.99 -> 10.01 does not jump the font size by a character's worth (~20 % on a short\n// string). The count grows at once and shrinks only after `holdMs` with nothing longer.\nexport interface StickyChars {\n value: number;\n since: number;\n}\n\nexport function stickyChars(prev: StickyChars | undefined, chars: number, now: number, holdMs: number): StickyChars {\n if (!prev || chars >= prev.value) return { value: chars, since: now };\n if (now - prev.since >= holdMs) return { value: chars, since: now };\n return prev;\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Both formatters take an optional IANA `timeZone`. Omitted, they are exactly what they\n// always were: the viewer's own zone and locale defaults, which is right for a live board.\n// A host that plays a RECORDING pins one (the renderer's `timeZone` prop), because the\n// recorded instants are the point and a viewer's zone would shift them across a date line;\n// a pinned zone also prints its short name, so the reading says which clock it is.\n\n// formatTimestamp renders an RFC3339 event time as a locale time string, leaving\n// an unparseable value untouched and an absent one blank.\nexport function formatTimestamp(iso: string | null, timeZone?: string): string {\n if (!iso) return '';\n const date = new Date(iso);\n if (Number.isNaN(date.getTime())) return iso;\n return timeZone ? date.toLocaleTimeString(undefined, { timeZone, timeZoneName: 'short' }) : date.toLocaleTimeString();\n}\n\n// formatDateTime renders an RFC3339 time as a locale date+time string. Unlike\n// formatTimestamp (time-only, right for a live measurement tick) this keeps the date,\n// because an alarm can have been raised days ago and a bare \"09:14:32\" would mislead.\nexport function formatDateTime(iso: string | null, timeZone?: string): string {\n if (!iso) return '';\n const date = new Date(iso);\n if (Number.isNaN(date.getTime())) return iso;\n return timeZone ? date.toLocaleString(undefined, { timeZone, timeZoneName: 'short' }) : date.toLocaleString();\n}\n\n// With no precision configured a value is still not printed at full float width: a sensor's\n// 30.203057033956792 is noise on a card, a gauge or an alarm row. So an unset precision shows\n// at most DEFAULT_FRACTION_DIGITS decimals (trailing zeros dropped), and a value under 1 keeps\n// DEFAULT_SMALL_SIGNIFICANT significant digits instead, so a 0.000123 reading is not rounded\n// to nothing. An author who wants exact decimals sets `precision`.\nexport const DEFAULT_FRACTION_DIGITS = 3;\nexport const DEFAULT_SMALL_SIGNIFICANT = 4;\n\nfunction defaultFormat(value: number): string {\n if (!Number.isFinite(value)) return String(value);\n const rounded =\n Math.abs(value) >= 1 ? Number(value.toFixed(DEFAULT_FRACTION_DIGITS)) : Number(value.toPrecision(DEFAULT_SMALL_SIGNIFICANT));\n return String(rounded);\n}\n\n// formatValue renders a measurement value, applying a fixed precision when given\n// (else the default rounding above) and showing an em dash for a missing value.\n//\n// The precision is clamped to toFixed's domain because it arrives from an opaque stored\n// definition: outside 0..100 toFixed throws a RangeError, which is an exception thrown\n// during render — it unmounts the widget's whole subtree rather than degrading, and every\n// other bad option value in this package degrades. The console's config panel can author\n// a negative one today, and a hand-edited definition always could.\nexport function formatValue(value: number | null | undefined, precision?: number): string {\n if (value == null) return '—';\n if (precision == null) return defaultFormat(value);\n const places = Math.min(100, Math.max(0, Math.trunc(precision)));\n return value.toFixed(places);\n}\n", "// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Thresholds: where a measurement crosses from one severity to the next.\n//\n// A threshold STARTS a band: it holds from its `value` up to the next threshold's value (or\n// without end, for the last). Below the lowest threshold there is no band, so a value there\n// reads in the widget's own neutral colour, as does a value in a `normal` band (normal has no\n// colour; see severity.ts), so a healthy value looks the same under either kind of rule.\n// This one rule covers both directions:\n// - \"overheat above 105\" -> [{ value: 105, level: 'critical' }]\n// - \"low fuel below 15\" -> [{ value: 0, level: 'critical' }, { value: 15, level: 'normal' }]\n// A value ON a threshold belongs to the band that threshold starts (>=), never the one below.\n\nimport { isSeverityLevel, type SeverityLevel } from './severity';\n\nexport interface Threshold {\n value: number;\n level: SeverityLevel;\n label?: string;\n}\n\n// A band resolved over a numeric range. `level` is undefined for the neutral stretch below the\n// lowest threshold. `to` is Infinity for the last band.\nexport interface ThresholdBand {\n from: number;\n to: number;\n level: SeverityLevel | undefined;\n label?: string;\n}\n\n// parseThresholds reads the stored option defensively: a hand-edited definition may carry\n// anything, and a threshold that cannot be read must drop out rather than throw during render\n// (or, worse, colour a value by a guess). Only a finite `value` and a known `level` survive --\n// so a free colour in the `level` slot is dropped, and an extra `color` key is never read.\n// The result is sorted ascending by value (stable, so equal values keep their authored order\n// and the later one wins).\nexport function parseThresholds(raw: unknown): Threshold[] {\n if (!Array.isArray(raw)) return [];\n const out: Threshold[] = [];\n for (const item of raw) {\n if (typeof item !== 'object' || item === null) continue;\n const { value, level, label } = item as Record<string, unknown>;\n if (typeof value !== 'number' || !Number.isFinite(value) || !isSeverityLevel(level)) continue;\n out.push(typeof label === 'string' && label !== '' ? { value, level, label } : { value, level });\n }\n return out.map((t, i) => ({ t, i })).sort((a, b) => a.t.value - b.t.value || a.i - b.i).map(({ t }) => t);\n}\n\nexport function optThresholds(options: Record<string, unknown> | undefined, key = 'thresholds'): Threshold[] {\n return parseThresholds(options?.[key]);\n}\n\n// bandAt returns the threshold whose band holds `value`, or undefined below the lowest.\n// `thresholds` must be sorted (parseThresholds does). A null value has no band.\nexport function bandAt(thresholds: readonly Threshold[], value: number | null | undefined): Threshold | undefined {\n if (value == null || !Number.isFinite(value)) return undefined;\n let hit: Threshold | undefined;\n for (const t of thresholds) {\n if (value >= t.value) hit = t;\n else break;\n }\n return hit;\n}\n\n// thresholdBands lays the bands over [min, max]: a neutral lead-in up to the first threshold,\n// then one band per threshold, each clipped to the range. Bands that fall wholly outside the\n// range are dropped, and the band in effect AT `min` is carried in from a threshold below it.\n// The result tiles [min, max] exactly, which is what a gauge arc needs.\nexport function thresholdBands(thresholds: readonly Threshold[], min: number, max: number): ThresholdBand[] {\n if (!(max > min)) return [];\n const bands: ThresholdBand[] = [];\n const push = (from: number, to: number, level: SeverityLevel | undefined, label?: string) => {\n const a = Math.max(from, min);\n const b = Math.min(to, max);\n if (b > a) bands.push(label === undefined ? { from: a, to: b, level } : { from: a, to: b, level, label });\n };\n if (thresholds.length === 0) return [];\n push(-Infinity, thresholds[0].value, undefined);\n thresholds.forEach((t, i) => push(t.value, thresholds[i + 1]?.value ?? Infinity, t.level, t.label));\n return bands;\n}\n"],
|
|
5
5
|
"mappings": ";;;;;AAsBO,IAAM,kBAAkB;AAExB,IAAM,uBAAuB;AAK7B,IAAM,mBAAmB;AACzB,IAAM,kBAAkB;AAQ/B,SAAS,UAAU,OAAuB;AACxC,SAAO,KAAK,IAAI,GAAG,KAAK,KAAK,OAAO,SAAS,KAAK,IAAI,QAAQ,CAAC,CAAC;AAClE;AAEO,SAAS,aAAa,MAAyC,OAAe,UAAsB,CAAC,GAAW;AACrH,QAAM,QAAQ,QAAQ,SAAS;AAC/B,MAAI,EAAE,KAAK,QAAQ,MAAM,EAAE,KAAK,SAAS,GAAI,QAAO,KAAK,IAAI,OAAO,oBAAoB;AACxF,QAAM,WAAW,KAAK,SAAS;AAC/B,QAAM,UAAU,KAAK,SAAS,UAAU,KAAK,IAAI;AACjD,SAAO,KAAK,IAAI,OAAO,KAAK,MAAM,KAAK,IAAI,UAAU,OAAO,CAAC,CAAC;AAChE;AAOO,SAAS,gBAAgB,OAAe,UAAsB,CAAC,GAAW;AAC/E,QAAM,QAAQ,QAAQ,SAAS;AAC/B,QAAM,UAAU,OAAO,UAAU,KAAK,IAAI;AAC1C,SAAO,OAAO,KAAK,WAAW,mBAAmB,GAAG,QAAQ,OAAO,QAAQ,QAAQ,CAAC,CAAC,CAAC;AACxF;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AAI,GAAG,MAAM,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,MAAM,CAAC;AAAA,EAC1G;AACA,MAAI,WAAW,WAAW,EAAG,QAAO,CAAC;AACrC,OAAK,WAAW,WAAW,CAAC,EAAE,OAAO,MAAS;AAC9C,aAAW,QAAQ,CAAC,GAAG,MAAM,KAAK,EAAE,OAAO,WAAW,IAAI,CAAC,GAAG,SAAS,UAAU,EAAE,OAAO,EAAE,KAAK,CAAC;AAClG,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -7,7 +7,7 @@ function strictCspEnabled() {
|
|
|
7
7
|
return strict;
|
|
8
8
|
}
|
|
9
9
|
function plainTooltipText(text) {
|
|
10
|
-
return text.replace(/\{/g, "
|
|
10
|
+
return text.replace(/\{/g, "{").replace(/\}/g, "}");
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
export {
|
|
@@ -15,4 +15,4 @@ export {
|
|
|
15
15
|
strictCspEnabled,
|
|
16
16
|
plainTooltipText
|
|
17
17
|
};
|
|
18
|
-
//# sourceMappingURL=chunk-
|
|
18
|
+
//# sourceMappingURL=chunk-ZCOHPFPW.js.map
|
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/strict-csp.ts"],
|
|
4
4
|
"sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Strict-CSP host mode: run the SDK's widgets on a page whose content-security policy has no\n// `style-src 'unsafe-inline'` (for example `style-src 'self'`).\n//\n// OFF BY DEFAULT, and the default behaviour is unchanged: HTML chart tooltips and a <style>\n// element for the token CSS. A host that serves under a strict policy calls\n// `configureStrictCsp(true)` once, before it mounts anything:\n//\n// - chart tooltips are drawn on the canvas (ECharts `renderMode: 'richText'`) instead of as HTML,\n// because the HTML tooltip writes `style=\"...\"` attributes into its markup and a strict\n// policy refuses those (the rows lose their spacing and colour keys). Consequences: a custom\n// formatter must return plain text, not HTML; `{name|text}` in a string is zrender rich-text\n// syntax, so a `{` or `}` in a series or event name can truncate that tooltip line; and the\n// tooltip's `extraCssText`, `className` and `appendTo` options have no effect.\n// - the token CSS is adopted by the document as a constructed stylesheet (CSSOM, which\n// `style-src` does not govern) rather than rendered as a <style> element. It is adopted on\n// `document`, so a board hosted inside a shadow root does not receive it.\n//\n// A browser without constructed stylesheets (Safari before 16.4) falls back to the element.\n\nlet strict = false;\n\nexport function configureStrictCsp(enabled: boolean): void {\n strict = enabled;\n}\n\nexport function strictCspEnabled(): boolean {\n return strict;\n}\n\n// A string the canvas tooltip will show as written: `{` and `}` are zrender rich-text delimiters,\n// so they become their full-width forms rather than starting or ending a style run.\nexport function plainTooltipText(text: string): string {\n return text.replace(/\\{/g, '\\uFF5B').replace(/\\}/g, '\\uFF5D');\n}\n"],
|
|
5
|
-
"mappings": ";AAsBA,IAAI,SAAS;AAEN,SAAS,mBAAmB,SAAwB;AACzD,WAAS;AACX;AAEO,SAAS,mBAA4B;AAC1C,SAAO;AACT;AAIO,SAAS,iBAAiB,MAAsB;AACrD,SAAO,KAAK,QAAQ,OAAO,
|
|
5
|
+
"mappings": ";AAsBA,IAAI,SAAS;AAEN,SAAS,mBAAmB,SAAwB;AACzD,WAAS;AACX;AAEO,SAAS,mBAA4B;AAC1C,SAAO;AACT;AAIO,SAAS,iBAAiB,MAAsB;AACrD,SAAO,KAAK,QAAQ,OAAO,GAAQ,EAAE,QAAQ,OAAO,GAAQ;AAC9D;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/chart/echart-engine.ts"],
|
|
4
|
+
"sourcesContent": ["// Copyright The DeviceChain Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// The chart engine: Apache ECharts (and zrender beneath it), registered with ONLY the chart types\n// and components the option builders emit -- line + gauge, grid/tooltip/legend, canvas renderer --\n// so tree-shaking keeps the rest of ECharts out of the bundle.\n//\n// 🔴 THIS MODULE IS LOADED LAZILY, AND IT IS THE ONLY MODULE THAT IMPORTS ECHARTS AT RUNTIME.\n// echart.tsx reaches it through `import('./echart-engine')`, so a host bundler emits ECharts as ONE\n// chunk, fetched the first time a chart mounts (or earlier, through loadChartEngine, which\n// preloadWidgets calls for a board that holds a chart). At ~170 KB gzip it is the largest single\n// dependency of a board, and a board with no chart never downloads it. A STATIC import of this\n// module, or of `echarts/*`, from anywhere in the SDK folds the whole engine back into every host's\n// first download: dist-shape.test.ts asserts the boundary on the built artifact.\n//\n// The threshold markers are imported from HERE, not from echart.tsx, for the same reason: their\n// chunk then depends on this one, which is already loaded whenever it is fetched, so the bundler\n// has no ECharts code that two independent lazy chunks share and no reason to split the engine.\n\nimport { GaugeChart, LineChart } from 'echarts/charts';\nimport { GridComponent, LegendPlainComponent, TooltipComponent } from 'echarts/components';\nimport * as echarts from 'echarts/core';\nimport { CanvasRenderer } from 'echarts/renderers';\n\n// 🔴 EVERY COMPONENT AN OPTION BUILDER EMITS MUST BE REGISTERED -- here, or (the threshold\n// markers) by registerThresholdMarkers below. ECharts ignores an option key whose component is\n// not registered -- silently, no warning -- so a `legend` or a `markLine` the builder sets\n// draws nothing. The legend was dropped this way for as long as multi-series charts existed.\n// echart.registration.test.tsx renders each through a real ECharts instance, so a builder\n// that grows a new component fails there until it is registered.\n//\n// The PLAIN legend, not LegendComponent: that one also installs the scrollable legend, which\n// no builder asks for (~1.8 KB gzip).\necharts.use([LineChart, GaugeChart, GridComponent, TooltipComponent, LegendPlainComponent, CanvasRenderer]);\n\nexport const init = echarts.init;\n\n// markLine / markArea are registered on first use (see echart-markers.ts for why).\nlet markers: Promise<void> | undefined;\n\nexport function registerThresholdMarkers(): Promise<void> {\n markers ??= import('./echart-markers').then(\n (m) => {\n echarts.use(m.MARKER_COMPONENTS);\n },\n (err: unknown) => {\n markers = undefined; // a failed chunk load is retried by the next chart that needs it\n throw err;\n },\n );\n return markers;\n}\n"],
|
|
5
|
+
"mappings": ";AAmBA,SAAS,YAAY,iBAAiB;AACtC,SAAS,eAAe,sBAAsB,wBAAwB;AACtE,YAAY,aAAa;AACzB,SAAS,sBAAsB;AAWvB,YAAI,CAAC,WAAW,YAAY,eAAe,kBAAkB,sBAAsB,cAAc,CAAC;AAEnG,IAAMA,QAAe;AAG5B,IAAI;AAEG,SAAS,2BAA0C;AACxD,wBAAY,OAAO,8BAAkB,EAAE;AAAA,IACrC,CAAC,MAAM;AACL,MAAQ,YAAI,EAAE,iBAAiB;AAAA,IACjC;AAAA,IACA,CAAC,QAAiB;AAChB,gBAAU;AACV,YAAM;AAAA,IACR;AAAA,EACF;AACA,SAAO;AACT;",
|
|
6
|
+
"names": ["init"]
|
|
7
|
+
}
|
|
@@ -42,7 +42,8 @@ function downloadCsv(table) {
|
|
|
42
42
|
// src/export-menu.ts
|
|
43
43
|
var WORDS = {
|
|
44
44
|
en: { button: "Export data", csv: "Download CSV", image: "Download image (PNG)" },
|
|
45
|
-
es: { button: "Exportar datos", csv: "Descargar CSV", image: "Descargar imagen (PNG)" }
|
|
45
|
+
es: { button: "Exportar datos", csv: "Descargar CSV", image: "Descargar imagen (PNG)" },
|
|
46
|
+
"zh-CN": { button: "导出数据", csv: "下载 CSV", image: "下载图片(PNG)" }
|
|
46
47
|
};
|
|
47
48
|
function opaqueBackground(el) {
|
|
48
49
|
for (let node = el; node; node = node.parentElement) {
|
|
@@ -54,14 +55,15 @@ function opaqueBackground(el) {
|
|
|
54
55
|
function fileStamp(at) {
|
|
55
56
|
return at.toISOString().replace(/[-:]/g, "").replace(/\d\d\.\d+Z$/, "Z");
|
|
56
57
|
}
|
|
57
|
-
function
|
|
58
|
+
function exportWords() {
|
|
58
59
|
const lang = typeof document !== "undefined" && document.documentElement.lang || typeof navigator !== "undefined" && navigator.language || "";
|
|
59
|
-
|
|
60
|
+
const base = lang.toLowerCase().split("-")[0];
|
|
61
|
+
return base === "es" ? WORDS.es : base === "zh" ? WORDS["zh-CN"] : WORDS.en;
|
|
60
62
|
}
|
|
61
63
|
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
64
|
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
65
|
function openExportMenu(host, o) {
|
|
64
|
-
const words =
|
|
66
|
+
const words = exportWords();
|
|
65
67
|
const menu = document.createElement("div");
|
|
66
68
|
menu.setAttribute("role", "menu");
|
|
67
69
|
menu.setAttribute("data-widget-export-menu", "");
|
|
@@ -134,7 +136,7 @@ function openExportMenu(host, o) {
|
|
|
134
136
|
}
|
|
135
137
|
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
138
|
function mountExportButton(host, size, source) {
|
|
137
|
-
const words =
|
|
139
|
+
const words = exportWords();
|
|
138
140
|
const button = document.createElement("button");
|
|
139
141
|
button.type = "button";
|
|
140
142
|
button.setAttribute("aria-label", words.button);
|
|
@@ -181,4 +183,4 @@ export {
|
|
|
181
183
|
opaqueBackground,
|
|
182
184
|
openExportMenu
|
|
183
185
|
};
|
|
184
|
-
//# sourceMappingURL=export-menu-
|
|
186
|
+
//# sourceMappingURL=export-menu-VFLUUFWM.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// 🔴 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// 🔴 UTF-8 WITH A BYTE-ORDER MARK, on purpose. Units are not ASCII (\"°C\", \"µS/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 \"°C\". 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 = /^[=+\\-@=+-@]/;\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// 🔴 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 'zh-CN': { button: '导出数据', csv: '下载 CSV', image: '下载图片(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 exportWords() {\n const lang = (typeof document !== 'undefined' && document.documentElement.lang) || (typeof navigator !== 'undefined' && navigator.language) || '';\n const base = lang.toLowerCase().split('-')[0];\n return base === 'es' ? WORDS.es : base === 'zh' ? WORDS['zh-CN'] : WORDS.en;\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 = exportWords();\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 = exportWords();\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,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