@kiosko/sdk 0.2.1 → 0.2.3

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/src/testing.ts ADDED
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Helpers for plugin tests (Node only: they paint with @napi-rs/canvas).
3
+ *
4
+ * import { renderWidget, checkPlugin } from '@kiosko/sdk/testing';
5
+ *
6
+ * const r = renderWidget(forecast, { size: { w: 600, h: 300 }, locale: 'es' });
7
+ * assert.deepEqual(r.texts.slice(0, 2), ['13°', 'Parcialmente nublado']);
8
+ * assert.equal(r.outside, 0);
9
+ *
10
+ * assert.deepEqual(checkPlugin(plugin), []); // every widget, several sizes, themes and languages
11
+ *
12
+ * A widget is painted the way Kiosko paints it (same context, same drawing
13
+ * kit), with its `demo` data unless given other, and every text it draws
14
+ * through the kit is collected in order. It is painted with a margin around
15
+ * its box, so what it draws outside (which the panel would clip) is counted.
16
+ */
17
+ import { createCanvas, loadImage, type Canvas } from '@napi-rs/canvas';
18
+ import * as kit from '@loksly/lcd-canvas-kit';
19
+ import { createBaseContext } from './context.ts';
20
+ import type { TimeFormat } from './format.ts';
21
+ import type { Box, PluginDefinition, RenderContext, StateContext, WidgetDefinition } from './plugin.ts';
22
+ import { validate } from './schema.ts';
23
+ import { THEMES, themeById, type Theme } from './theme.ts';
24
+ import { DEFAULT_WORKDAY } from './workday.ts';
25
+
26
+ export interface RenderOptions {
27
+ /** The instance's options (validated against the widget's schema, defaults filled in). Default: the demo's, if any. */
28
+ options?: Record<string, unknown>;
29
+ /** The widget's own data. Default: its demo data. */
30
+ data?: unknown;
31
+ /** Data of its sources, by type. Default: its demo's. */
32
+ sources?: Record<string, unknown>;
33
+ /** The box it paints in. Default: its preferred size, else 480×300. */
34
+ size?: { w: number; h: number };
35
+ locale?: string;
36
+ /** A theme or its id (`midnight`, `paper`…). Default: the first. */
37
+ theme?: string | Theme;
38
+ now?: number;
39
+ timeFormat?: TimeFormat;
40
+ /** Painted for the editor's preview rather than the panel. */
41
+ preview?: boolean;
42
+ /** Use the widget's `demo` for what isn't given. Default true. */
43
+ demo?: boolean;
44
+ }
45
+
46
+ export interface RenderResult {
47
+ /** Every text drawn with `kit.drawTracked`, in order. */
48
+ texts: string[];
49
+ /** The picture: the box with `margin` pixels around it. */
50
+ canvas: Canvas;
51
+ /** Where the box is on `canvas`. */
52
+ box: Box;
53
+ margin: number;
54
+ /** Pixels painted outside the box (the panel would cut them off). */
55
+ outside: number;
56
+ /** How long `render` took. */
57
+ ms: number;
58
+ /** What `render` threw, if it did. */
59
+ error?: string;
60
+ /** The box alone, as PNG. */
61
+ png(): Buffer;
62
+ }
63
+
64
+ const MARGIN = 24;
65
+
66
+ function resolve(w: WidgetDefinition<any, any>, o: RenderOptions) {
67
+ const now = o.now ?? Date.UTC(2026, 10, 5, 9, 42);
68
+ const locale = o.locale ?? 'en';
69
+ const demoOpts = w.options ? (validate(w.options, {}).value as Record<string, unknown>) : {};
70
+ const demo = o.demo === false ? undefined : w.demo?.({ options: demoOpts as never, now, locale });
71
+ const options = w.options ? (validate(w.options, o.options ?? demo?.options ?? {}).value as Record<string, unknown>) : {};
72
+ const data = 'data' in o ? o.data : demo?.data;
73
+ const sources = o.sources ?? demo?.sources ?? {};
74
+ return { now, locale, options, data, sources };
75
+ }
76
+
77
+ /** Paints a widget alone and says what it drew. Never throws: a failing `render` is reported in `error`. */
78
+ export function renderWidget(w: WidgetDefinition<any, any>, o: RenderOptions = {}): RenderResult {
79
+ const { now, locale, options, data, sources } = resolve(w, o);
80
+ const size = o.size ?? w.size?.preferred ?? { w: 480, h: 300 };
81
+ const theme = typeof o.theme === 'object' ? o.theme : themeById(o.theme);
82
+ const texts: string[] = [];
83
+ const spy = { ...kit, drawTracked: (...a: Parameters<typeof kit.drawTracked>) => (texts.push(a[1]), kit.drawTracked(...a)) };
84
+ const canvas = createCanvas(size.w + 2 * MARGIN, size.h + 2 * MARGIN);
85
+ const g = canvas.getContext('2d');
86
+ const box: Box = { x: MARGIN, y: MARGIN, w: size.w, h: size.h };
87
+ const ctx: RenderContext<any, any> = {
88
+ ...createBaseContext({ now, locale, ...(o.timeFormat ? { timeFormat: o.timeFormat } : {}) }),
89
+ options,
90
+ data,
91
+ sources,
92
+ working: true,
93
+ box,
94
+ theme,
95
+ fonts: theme.fonts,
96
+ kit: spy,
97
+ canvas: { createCanvas, loadImage },
98
+ preview: !!o.preview,
99
+ };
100
+ const t0 = performance.now();
101
+ let error: string | undefined;
102
+ try {
103
+ w.render(g, ctx);
104
+ } catch (err) {
105
+ error = err instanceof Error ? err.message : String(err);
106
+ }
107
+ const ms = performance.now() - t0;
108
+ const px = g.getImageData(0, 0, canvas.width, canvas.height).data;
109
+ let outside = 0;
110
+ for (let y = 0; y < canvas.height; y++) {
111
+ for (let x = 0; x < canvas.width; x++) {
112
+ if (x >= box.x && x < box.x + box.w && y >= box.y && y < box.y + box.h) continue;
113
+ if (px[(y * canvas.width + x) * 4 + 3]! > 24) outside++;
114
+ }
115
+ }
116
+ return {
117
+ texts,
118
+ canvas,
119
+ box,
120
+ margin: MARGIN,
121
+ outside,
122
+ ms,
123
+ ...(error !== undefined ? { error } : {}),
124
+ png() {
125
+ const out = createCanvas(box.w, box.h);
126
+ out.getContext('2d').drawImage(canvas, -box.x, -box.y);
127
+ return out.toBuffer('image/png');
128
+ },
129
+ };
130
+ }
131
+
132
+ /** Asks a widget's `urgent`, `idle`, `empty` or `visible` with the same inputs `renderWidget` would use. */
133
+ export function widgetState(w: WidgetDefinition<any, any>, hook: 'urgent' | 'idle' | 'empty' | 'visible', o: RenderOptions = {}): boolean | undefined {
134
+ const fn = w[hook];
135
+ if (!fn) return undefined;
136
+ const { now, options, data, sources } = resolve(w, o);
137
+ const ctx: StateContext<any, any> = { options, data, sources, now, working: true, workday: DEFAULT_WORKDAY };
138
+ return fn(ctx);
139
+ }
140
+
141
+ export interface PluginIssue {
142
+ /** `plugin/widget`. */
143
+ type: string;
144
+ /** `600x300 midnight es`. */
145
+ where: string;
146
+ problem: string;
147
+ }
148
+
149
+ /**
150
+ * Paints every widget of a plugin with its demo data at its minimum and
151
+ * preferred sizes and a wide and a tall one, in every theme and in each
152
+ * language given, and lists what went wrong: a `render` that throws, one
153
+ * that paints nothing, paints outside its box, or takes longer than
154
+ * `slowMs` (Kiosko warns at 50 ms). An empty list is a pass.
155
+ */
156
+ export function checkPlugin(p: PluginDefinition, o: { locales?: string[]; themes?: string[]; slowMs?: number; extraSizes?: { w: number; h: number }[] } = {}): PluginIssue[] {
157
+ const issues: PluginIssue[] = [];
158
+ const locales = o.locales ?? ['en', 'es'];
159
+ const themes = o.themes ?? THEMES.map((t) => t.id);
160
+ const slow = o.slowMs ?? 50;
161
+ for (const w of p.widgets ?? []) {
162
+ const type = `${p.id}/${w.id}`;
163
+ const pref = w.size?.preferred ?? { w: 480, h: 300 };
164
+ const min = w.size?.min ?? { w: Math.round(pref.w / 2), h: Math.round(pref.h / 2) };
165
+ const sizes = [min, pref, { w: Math.max(pref.w * 2, 900), h: Math.max(min.h, 120) }, { w: Math.max(min.w, 200), h: Math.max(pref.h * 2, 500) }, ...(o.extraSizes ?? [])];
166
+ for (const size of sizes) {
167
+ for (const theme of themes) {
168
+ for (const locale of locales) {
169
+ const where = `${size.w}x${size.h} ${theme} ${locale}`;
170
+ const r = renderWidget(w, { size, theme, locale });
171
+ if (r.error) issues.push({ type, where, problem: `render threw: ${r.error}` });
172
+ else if (r.outside > 0) issues.push({ type, where, problem: `painted ${r.outside} px outside its box` });
173
+ // The first paint pays for loading fonts and compiling code; on the panel a widget paints
174
+ // again and again. Slow means slow every time: the best of three.
175
+ if (r.ms > slow && !r.error) {
176
+ const ms = Math.min(r.ms, renderWidget(w, { size, theme, locale }).ms, renderWidget(w, { size, theme, locale }).ms);
177
+ if (ms > slow) issues.push({ type, where, problem: `render took ${Math.round(ms)} ms` });
178
+ }
179
+ }
180
+ }
181
+ }
182
+ // Something must show with the demo data, at least at the preferred size.
183
+ const r = renderWidget(w, { size: pref });
184
+ if (!r.error) {
185
+ const px = r.canvas.getContext('2d').getImageData(r.box.x, r.box.y, r.box.w, r.box.h).data;
186
+ let inked = 0;
187
+ for (let i = 3; i < px.length; i += 4) if (px[i]! > 24) inked++;
188
+ if (!inked) issues.push({ type, where: `${pref.w}x${pref.h}`, problem: 'painted nothing with its demo data (add a `demo`)' });
189
+ }
190
+ }
191
+ return issues;
192
+ }