@oberik/sdk 0.83.0 → 0.85.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2545 @@
1
+ "use strict";
2
+ /**
3
+ * Oberik widgets — render what the agent writes into a conversation.
4
+ *
5
+ * import { createWidgetComponent } from "@oberik/sdk/widgets";
6
+ *
7
+ * A widget is data: a tree of components from a closed catalog, plus local state and
8
+ * formulas over it. Nothing in it is code, which is what lets one widget render natively
9
+ * in React, React Native, Vue, Svelte, a plain page — or as text in a language with no
10
+ * renderer at all — and what lets the server prove it works before anyone sees it.
11
+ *
12
+ * This file has NO imports and touches no global it does not check for first. The same
13
+ * rule as the client: it must bundle under Metro, Vite, webpack and Node unchanged, so
14
+ * React is passed IN (`createWidgetComponent(React)`) rather than imported, and React
15
+ * Native's primitives likewise (`nativePlatform(RN)`).
16
+ *
17
+ * Layers, each usable on its own:
18
+ *
19
+ * evaluate / resolveWidget the formula language and the resolver — the same ones the
20
+ * server checks with (`app/widgets/expr.py`, `check.py`);
21
+ * `app/widgets/expr_cases.json` holds the two equal
22
+ * WidgetSession state, presses and replies, for any UI toolkit
23
+ * layoutWidget a resolved widget → a small host-neutral element tree
24
+ * createWidgetComponent that tree → React elements (web, or native via primitives)
25
+ * mountWidget / <oberik-widget> that tree → the DOM, for every other framework
26
+ * widgetToText the text a widget also is, for anything that can't render
27
+ *
28
+ * Never broken, on this side too: a formula that fails at a point the server did not
29
+ * sample keeps the last good rendering rather than showing an error, a component this
30
+ * version does not know renders as its text, an image that fails to load shows its alt
31
+ * text, and the React host's error boundary falls back to the widget's `fallback`.
32
+ */
33
+ Object.defineProperty(exports, "__esModule", { value: true });
34
+ exports.WidgetSession = exports.WIDGET_FUNCTIONS = exports.WidgetExprError = exports.WIDGET_CATALOG_VERSION = exports.WIDGET_COMPONENTS = void 0;
35
+ exports.previewRender = previewRender;
36
+ exports.widgetValueText = widgetValueText;
37
+ exports.formatWidgetValue = formatWidgetValue;
38
+ exports.evaluateFormula = evaluateFormula;
39
+ exports.templateParts = templateParts;
40
+ exports.renderTemplate = renderTemplate;
41
+ exports.widgetScope = widgetScope;
42
+ exports.resolveWidget = resolveWidget;
43
+ exports.widgetActionId = widgetActionId;
44
+ exports.widgetToText = widgetToText;
45
+ exports.resolveWidgetTheme = resolveWidgetTheme;
46
+ exports.layoutWidget = layoutWidget;
47
+ exports.chartGeometry = chartGeometry;
48
+ exports.createWidgetComponent = createWidgetComponent;
49
+ exports.webPlatform = webPlatform;
50
+ exports.nativePlatform = nativePlatform;
51
+ exports.mountWidget = mountWidget;
52
+ exports.defineWidgetElement = defineWidgetElement;
53
+ /** A preview as something to draw. */
54
+ function previewRender(p) {
55
+ return { id: `preview:${p.call_id}`, call_id: p.call_id, widget: p.widget, fallback: p.fallback, interactive: false, preview: true };
56
+ }
57
+ /**
58
+ * Every component and its props. Checked against the server's catalog
59
+ * (`app/widgets/catalog.json`) by `ui/src/widget-catalog-agrees.test.ts`, and every
60
+ * key here must have a layout below — `Record<WidgetNode["type"], …>` makes that a type
61
+ * error rather than a blank box.
62
+ */
63
+ exports.WIDGET_COMPONENTS = {
64
+ badge: ["label", "tone", "visible"],
65
+ button: ["action", "disabled", "label", "style", "visible"],
66
+ callout: ["text", "title", "tone", "visible"],
67
+ chart: ["currency", "data", "format", "height", "kind", "series", "stacked", "title", "visible", "x"],
68
+ column: ["align", "children", "gap", "visible"],
69
+ disclosure: ["children", "label", "open", "visible"],
70
+ divider: ["visible"],
71
+ fields: ["columns", "items", "visible"],
72
+ image: ["alt", "aspect", "fit", "src", "visible"],
73
+ input: ["bind", "kind", "label", "placeholder", "required", "visible"],
74
+ list: ["items", "visible"],
75
+ progress: ["label", "max", "show_value", "tone", "value", "visible"],
76
+ row: ["align", "children", "gap", "justify", "visible", "wrap"],
77
+ select: ["bind", "label", "options", "visible"],
78
+ slider: ["bind", "currency", "format", "label", "max", "min", "step", "visible"],
79
+ stat: ["caption", "delta", "label", "tone", "trend", "value", "visible"],
80
+ table: ["columns", "currency", "rows", "visible"],
81
+ tabs: ["tabs", "visible"],
82
+ text: ["align", "max_lines", "style", "tone", "value", "visible", "weight"],
83
+ timeline: ["items", "visible"],
84
+ toggle: ["bind", "description", "label", "visible"],
85
+ };
86
+ exports.WIDGET_CATALOG_VERSION = 1;
87
+ // ============================================================================ formulas
88
+ //
89
+ // A line-for-line port of app/widgets/expr.py. Change one, change both, and add a case
90
+ // to app/widgets/expr_cases.json — both suites run every case there.
91
+ const STEP_BUDGET = 200_000;
92
+ const MAX_LIST = 1000;
93
+ const MAX_STRING = 10_000;
94
+ class WidgetExprError extends Error {
95
+ constructor(message) {
96
+ super(message);
97
+ this.name = "WidgetExprError";
98
+ }
99
+ }
100
+ exports.WidgetExprError = WidgetExprError;
101
+ const fail = (m) => {
102
+ throw new WidgetExprError(m);
103
+ };
104
+ const PUNCT = ["=>", "==", "!=", "<=", ">=", "&&", "||", "+", "-", "*", "/", "%", "<", ">", "!", "?", ":", "(", ")", "[", "]", "{", "}", ",", "."];
105
+ const KEYWORDS = { and: "&&", or: "||", not: "!" };
106
+ const isDigit = (c) => c >= "0" && c <= "9";
107
+ const isAlpha = (c) => /[A-Za-z_]/.test(c);
108
+ const isAlnum = (c) => /[A-Za-z0-9_]/.test(c);
109
+ function tokenize(src) {
110
+ const out = [];
111
+ let i = 0;
112
+ const n = src.length;
113
+ while (i < n) {
114
+ const c = src[i];
115
+ if (/\s/.test(c)) {
116
+ i++;
117
+ continue;
118
+ }
119
+ if (isDigit(c) || (c === "." && i + 1 < n && isDigit(src[i + 1]))) {
120
+ let j = i;
121
+ while (j < n && (isDigit(src[j]) || src[j] === "."))
122
+ j++;
123
+ if (j < n && (src[j] === "e" || src[j] === "E")) {
124
+ let k = j + 1;
125
+ if (k < n && (src[k] === "+" || src[k] === "-"))
126
+ k++;
127
+ if (k < n && isDigit(src[k])) {
128
+ j = k;
129
+ while (j < n && isDigit(src[j]))
130
+ j++;
131
+ }
132
+ }
133
+ const text = src.slice(i, j);
134
+ const v = Number(text);
135
+ if (Number.isNaN(v) || (text.match(/\./g) || []).length > 1)
136
+ fail(`'${text}' is not a number`);
137
+ out.push({ kind: "num", value: v, pos: i });
138
+ i = j;
139
+ continue;
140
+ }
141
+ if (c === "'" || c === '"') {
142
+ let j = i + 1;
143
+ let buf = "";
144
+ while (j < n && src[j] !== c) {
145
+ if (src[j] === "\\" && j + 1 < n) {
146
+ const e = src[j + 1];
147
+ buf += e === "n" ? "\n" : e === "t" ? "\t" : e;
148
+ j += 2;
149
+ continue;
150
+ }
151
+ buf += src[j];
152
+ j++;
153
+ }
154
+ if (j >= n)
155
+ fail("a string is missing its closing quote");
156
+ out.push({ kind: "str", value: buf, pos: i });
157
+ i = j + 1;
158
+ continue;
159
+ }
160
+ if (isAlpha(c)) {
161
+ let j = i;
162
+ while (j < n && isAlnum(src[j]))
163
+ j++;
164
+ const word = src.slice(i, j);
165
+ out.push(word in KEYWORDS ? { kind: "op", value: KEYWORDS[word], pos: i } : { kind: "ident", value: word, pos: i });
166
+ i = j;
167
+ continue;
168
+ }
169
+ const p = PUNCT.find((q) => src.startsWith(q, i));
170
+ if (!p)
171
+ fail(`unexpected character '${c}'`);
172
+ out.push({ kind: "op", value: p, pos: i });
173
+ i += p.length;
174
+ }
175
+ out.push({ kind: "end", value: null, pos: n });
176
+ return out;
177
+ }
178
+ /** name → [min args, max args]. Must equal `FUNCTIONS` in app/widgets/expr.py. */
179
+ exports.WIDGET_FUNCTIONS = {
180
+ min: [1, 50], max: [1, 50], abs: [1, 1], round: [1, 2], floor: [1, 1],
181
+ ceil: [1, 1], sqrt: [1, 1], pow: [2, 2], log: [1, 1], exp: [1, 1],
182
+ clamp: [3, 3], sum: [1, 1], avg: [1, 1], len: [1, 1], range: [1, 3],
183
+ map: [2, 2], filter: [2, 2], if: [3, 3], str: [1, 1], number: [1, 2],
184
+ currency: [1, 3], percent: [1, 2], compact: [1, 1], pmt: [3, 3],
185
+ upper: [1, 1], lower: [1, 1], plural: [3, 3], contains: [2, 2],
186
+ first: [1, 1], last: [1, 1],
187
+ };
188
+ const LEVELS = [["||"], ["&&"], ["==", "!="], ["<", "<=", ">", ">="], ["+", "-"], ["*", "/", "%"]];
189
+ class Parser {
190
+ toks;
191
+ i = 0;
192
+ constructor(src) {
193
+ this.toks = tokenize(src);
194
+ }
195
+ peek(value, kind) {
196
+ const t = this.toks[this.i];
197
+ return (kind === undefined || t.kind === kind) && (value === undefined || t.value === value);
198
+ }
199
+ take(value) {
200
+ const t = this.toks[this.i];
201
+ if (t.kind !== "op" || t.value !== value) {
202
+ fail(`expected '${value}' but found ${t.kind === "end" ? "the end" : `'${t.value}'`}`);
203
+ }
204
+ this.i++;
205
+ return t;
206
+ }
207
+ parse() {
208
+ const node = this.expr();
209
+ if (!this.peek(undefined, "end"))
210
+ fail(`unexpected '${this.toks[this.i].value}'`);
211
+ return node;
212
+ }
213
+ expr() {
214
+ if (this.peek(undefined, "ident") && this.toks[this.i + 1].value === "=>") {
215
+ const name = this.toks[this.i].value;
216
+ this.i += 2;
217
+ return ["fn", [name], this.expr()];
218
+ }
219
+ if (this.peek("(")) {
220
+ let j = this.i + 1;
221
+ const params = [];
222
+ while (this.toks[j].kind === "ident") {
223
+ params.push(this.toks[j].value);
224
+ if (this.toks[j + 1].value === ",") {
225
+ j += 2;
226
+ continue;
227
+ }
228
+ j += 1;
229
+ break;
230
+ }
231
+ if (params.length && this.toks[j].value === ")" && this.toks[j + 1].value === "=>") {
232
+ this.i = j + 2;
233
+ return ["fn", params, this.expr()];
234
+ }
235
+ }
236
+ return this.cond();
237
+ }
238
+ cond() {
239
+ const c = this.binary(0);
240
+ if (this.peek("?")) {
241
+ this.i++;
242
+ const a = this.expr();
243
+ this.take(":");
244
+ const b = this.expr();
245
+ return ["cond", c, a, b];
246
+ }
247
+ return c;
248
+ }
249
+ binary(level) {
250
+ if (level === LEVELS.length)
251
+ return this.unary();
252
+ let left = this.binary(level + 1);
253
+ while (this.peek(undefined, "op") && LEVELS[level].includes(this.toks[this.i].value)) {
254
+ const op = this.toks[this.i].value;
255
+ this.i++;
256
+ left = ["bin", op, left, this.binary(level + 1)];
257
+ }
258
+ return left;
259
+ }
260
+ unary() {
261
+ if (this.peek("-") || this.peek("!")) {
262
+ const op = this.toks[this.i].value;
263
+ this.i++;
264
+ return ["un", op, this.unary()];
265
+ }
266
+ return this.postfix();
267
+ }
268
+ postfix() {
269
+ let node = this.primary();
270
+ for (;;) {
271
+ if (this.peek(".")) {
272
+ this.i++;
273
+ const t = this.toks[this.i];
274
+ if (t.kind !== "ident")
275
+ fail("expected a field name after '.'");
276
+ this.i++;
277
+ node = ["get", node, ["lit", t.value]];
278
+ }
279
+ else if (this.peek("[")) {
280
+ this.i++;
281
+ const key = this.expr();
282
+ this.take("]");
283
+ node = ["get", node, key];
284
+ }
285
+ else
286
+ return node;
287
+ }
288
+ }
289
+ primary() {
290
+ const t = this.toks[this.i];
291
+ if (t.kind === "num" || t.kind === "str") {
292
+ this.i++;
293
+ return ["lit", t.value];
294
+ }
295
+ if (t.kind === "ident") {
296
+ this.i++;
297
+ if (t.value === "true" || t.value === "false")
298
+ return ["lit", t.value === "true"];
299
+ if (t.value === "null")
300
+ return ["lit", null];
301
+ if (this.peek("(")) {
302
+ this.i++;
303
+ const args = [];
304
+ if (!this.peek(")")) {
305
+ args.push(this.expr());
306
+ while (this.peek(",")) {
307
+ this.i++;
308
+ args.push(this.expr());
309
+ }
310
+ }
311
+ this.take(")");
312
+ if (!(t.value in exports.WIDGET_FUNCTIONS)) {
313
+ fail(`'${t.value}' is not a function (have: ${Object.keys(exports.WIDGET_FUNCTIONS).sort().join(", ")})`);
314
+ }
315
+ return ["call", t.value, args];
316
+ }
317
+ return ["name", t.value];
318
+ }
319
+ if (this.peek("(")) {
320
+ this.i++;
321
+ const node = this.expr();
322
+ this.take(")");
323
+ return node;
324
+ }
325
+ if (this.peek("[")) {
326
+ this.i++;
327
+ const items = [];
328
+ if (!this.peek("]")) {
329
+ items.push(this.expr());
330
+ while (this.peek(",")) {
331
+ this.i++;
332
+ items.push(this.expr());
333
+ }
334
+ }
335
+ this.take("]");
336
+ return ["list", items];
337
+ }
338
+ if (this.peek("{")) {
339
+ this.i++;
340
+ const pairs = [];
341
+ while (!this.peek("}")) {
342
+ const k = this.toks[this.i];
343
+ if (k.kind !== "ident" && k.kind !== "str")
344
+ fail("an object key must be a name or a string");
345
+ this.i++;
346
+ this.take(":");
347
+ pairs.push([k.value, this.expr()]);
348
+ if (!this.peek(","))
349
+ break;
350
+ this.i++;
351
+ }
352
+ this.take("}");
353
+ return ["obj", pairs];
354
+ }
355
+ if (t.kind === "end")
356
+ fail("the formula ends too soon");
357
+ return fail(`unexpected '${t.value}'`);
358
+ }
359
+ }
360
+ const AST_CACHE = new Map();
361
+ function parseExpr(src) {
362
+ if (typeof src !== "string" || !src.trim())
363
+ fail("a formula cannot be empty");
364
+ if (src.length > 2000)
365
+ fail("a formula is limited to 2000 characters");
366
+ let hit = AST_CACHE.get(src);
367
+ if (!hit) {
368
+ hit = new Parser(src).parse();
369
+ if (AST_CACHE.size < 4096)
370
+ AST_CACHE.set(src, hit);
371
+ }
372
+ return hit;
373
+ }
374
+ function typeName(v) {
375
+ if (v === null || v === undefined)
376
+ return "null";
377
+ if (typeof v === "boolean")
378
+ return "boolean";
379
+ if (typeof v === "number")
380
+ return "number";
381
+ if (typeof v === "string")
382
+ return "text";
383
+ if (Array.isArray(v))
384
+ return "list";
385
+ return "object";
386
+ }
387
+ const num = (v, what) => (typeof v === "number" ? v : fail(`${what} needs a number, got ${typeName(v)}`));
388
+ const finite = (x, what) => (Number.isFinite(x) ? x : fail(`${what} is not a finite number`));
389
+ function roundHalfAway(x, digits) {
390
+ const m = 10 ** digits;
391
+ const r = Math.floor(Math.abs(x) * m + 0.5) / m;
392
+ return x < 0 ? -r : r;
393
+ }
394
+ function truthy(v) {
395
+ if (typeof v === "boolean")
396
+ return v;
397
+ if (v === null || v === undefined)
398
+ return false;
399
+ if (typeof v === "number")
400
+ return v !== 0;
401
+ if (typeof v === "string" || Array.isArray(v))
402
+ return v.length > 0;
403
+ if (typeof v === "object")
404
+ return Object.keys(v).length > 0;
405
+ return true;
406
+ }
407
+ function group(intDigits) {
408
+ let out = "";
409
+ for (let i = 0; i < intDigits.length; i++) {
410
+ if (i && (intDigits.length - i) % 3 === 0)
411
+ out += ",";
412
+ out += intDigits[i];
413
+ }
414
+ return out;
415
+ }
416
+ function formatNumber(x, decimals, grouped = true) {
417
+ finite(x, "the value");
418
+ let neg;
419
+ let whole;
420
+ let frac;
421
+ if (decimals === null) {
422
+ const r = roundHalfAway(x, 6);
423
+ neg = r < 0;
424
+ whole = Math.trunc(Math.abs(r));
425
+ const f = (Math.abs(r) - whole).toFixed(6);
426
+ frac = f.slice(2).replace(/0+$/, "");
427
+ if (f.startsWith("1")) {
428
+ whole += 1;
429
+ frac = "";
430
+ }
431
+ }
432
+ else {
433
+ const r = roundHalfAway(x, decimals);
434
+ neg = r < 0;
435
+ const text = Math.abs(r).toFixed(decimals);
436
+ const [w, f = ""] = text.split(".");
437
+ whole = Number(w);
438
+ frac = f;
439
+ }
440
+ const body = (grouped ? group(String(whole)) : String(whole)) + (frac ? `.${frac}` : "");
441
+ return neg && /[1-9]/.test(body) ? `-${body}` : body;
442
+ }
443
+ const CURRENCY = {
444
+ USD: "$", EUR: "€", GBP: "£", JPY: "¥", TRY: "₺", INR: "₹", CNY: "¥", KRW: "₩",
445
+ AUD: "A$", CAD: "C$", CHF: "CHF ", SEK: "kr ", BRL: "R$", MXN: "MX$",
446
+ };
447
+ function formatCurrency(x, code, decimals) {
448
+ code = code.toUpperCase();
449
+ const d = decimals ?? (code === "JPY" || code === "KRW" ? 0 : 2);
450
+ const body = formatNumber(Math.abs(x), d);
451
+ const sym = CURRENCY[code];
452
+ const text = sym ? `${sym}${body}` : `${code} ${body}`;
453
+ return x < 0 && /[1-9]/.test(body) ? `-${text}` : text;
454
+ }
455
+ function formatCompact(x) {
456
+ const a = Math.abs(x);
457
+ for (const [limit, suffix] of [[1e12, "T"], [1e9, "B"], [1e6, "M"], [1e3, "K"]]) {
458
+ if (a >= limit) {
459
+ const v = roundHalfAway(x / limit, 1);
460
+ if (Math.abs(v) >= 1000 && suffix !== "T")
461
+ continue;
462
+ return formatNumber(v, null) + suffix;
463
+ }
464
+ }
465
+ return formatNumber(roundHalfAway(x, 1), null);
466
+ }
467
+ /** How a value reads in text. Identical to `to_text` in expr.py. */
468
+ function widgetValueText(v) {
469
+ if (v === null || v === undefined)
470
+ return "";
471
+ if (typeof v === "boolean")
472
+ return v ? "true" : "false";
473
+ if (typeof v === "number") {
474
+ if (Number.isInteger(v) && Math.abs(v) < 1e15)
475
+ return String(v === 0 ? 0 : v);
476
+ // Not grouped — see `to_text` in expr.py.
477
+ return formatNumber(v, null, false);
478
+ }
479
+ if (typeof v === "string")
480
+ return v;
481
+ return fail(`a ${typeName(v)} cannot be shown as text — pick a field or use len()`);
482
+ }
483
+ /** A value in one of the catalog's formats — tables, axes, slider readouts. */
484
+ function formatWidgetValue(v, format = "number", currency = "USD") {
485
+ if (v === null || v === undefined || v === "")
486
+ return "—";
487
+ if (typeof v !== "number" || format === "text") {
488
+ try {
489
+ return widgetValueText(v);
490
+ }
491
+ catch {
492
+ return "—";
493
+ }
494
+ }
495
+ if (!Number.isFinite(v))
496
+ return "—";
497
+ if (format === "currency")
498
+ return formatCurrency(v, currency, null);
499
+ if (format === "percent")
500
+ return formatNumber(v * 100, 0) + "%";
501
+ if (format === "compact")
502
+ return formatCompact(v);
503
+ return formatNumber(v, null);
504
+ }
505
+ function intArg(a, i, dflt, what) {
506
+ if (a.length <= i || a[i] === null)
507
+ return dflt;
508
+ const v = num(a[i], what);
509
+ if (!Number.isInteger(v) || v < 0 || v > 10)
510
+ fail(`${what} must be a whole number from 0 to 10`);
511
+ return v;
512
+ }
513
+ function numbers(v, name) {
514
+ if (!Array.isArray(v))
515
+ fail(`${name}() needs a list of numbers`);
516
+ return v.map((x) => num(x, `${name}()`));
517
+ }
518
+ function plainSum(vals) {
519
+ let t = 0;
520
+ for (const v of vals)
521
+ t += v;
522
+ return t;
523
+ }
524
+ class Evaluator {
525
+ scope;
526
+ steps = 0;
527
+ constructor(scope) {
528
+ this.scope = scope;
529
+ }
530
+ tick(n = 1) {
531
+ this.steps += n;
532
+ if (this.steps > STEP_BUDGET)
533
+ fail("this formula does too much work — use a shorter range");
534
+ }
535
+ run(node, env) {
536
+ this.tick();
537
+ switch (node[0]) {
538
+ case "lit":
539
+ return node[1];
540
+ case "name": {
541
+ const name = node[1];
542
+ if (Object.prototype.hasOwnProperty.call(env, name))
543
+ return env[name];
544
+ if (Object.prototype.hasOwnProperty.call(this.scope, name))
545
+ return this.scope[name];
546
+ return fail(`'${name}' is not defined`);
547
+ }
548
+ case "list":
549
+ return node[1].map((n) => this.run(n, env));
550
+ case "obj": {
551
+ const o = {};
552
+ for (const [k, v] of node[1])
553
+ o[k] = this.run(v, env);
554
+ return o;
555
+ }
556
+ case "un": {
557
+ const v = this.run(node[2], env);
558
+ return node[1] === "-" ? -num(v, "'-'") : !truthy(v);
559
+ }
560
+ case "bin":
561
+ return this.binary(node[1], node[2], node[3], env);
562
+ case "cond":
563
+ return this.run(truthy(this.run(node[1], env)) ? node[2] : node[3], env);
564
+ case "get":
565
+ return this.get(this.run(node[1], env), this.run(node[2], env));
566
+ case "call":
567
+ return this.call(node[1], node[2], env);
568
+ case "fn":
569
+ return fail("'=>' only works inside map() or filter()");
570
+ }
571
+ }
572
+ get(base, key) {
573
+ if (Array.isArray(base)) {
574
+ const i = num(key, "a list index");
575
+ if (!Number.isInteger(i) || i < -base.length || i >= base.length) {
576
+ fail(`index ${widgetValueText(i)} is outside a list of ${base.length}`);
577
+ }
578
+ return base[i < 0 ? base.length + i : i];
579
+ }
580
+ if (base !== null && typeof base === "object") {
581
+ if (typeof key !== "string")
582
+ fail("an object field name must be text");
583
+ const o = base;
584
+ if (!Object.prototype.hasOwnProperty.call(o, key)) {
585
+ fail(`no field '${key}' (have: ${Object.keys(o).join(", ") || "none"})`);
586
+ }
587
+ return o[key];
588
+ }
589
+ return fail(`a ${typeName(base)} has no fields`);
590
+ }
591
+ binary(op, an, bn, env) {
592
+ if (op === "&&") {
593
+ const a = this.run(an, env);
594
+ return truthy(a) ? this.run(bn, env) : a;
595
+ }
596
+ if (op === "||") {
597
+ const a = this.run(an, env);
598
+ return truthy(a) ? a : this.run(bn, env);
599
+ }
600
+ const a = this.run(an, env);
601
+ const b = this.run(bn, env);
602
+ if (op === "==" || op === "!=") {
603
+ for (const v of [a, b]) {
604
+ if (v !== null && typeof v === "object")
605
+ fail("only numbers, text and true/false can be compared");
606
+ }
607
+ const same = typeName(a) === typeName(b) && a === b;
608
+ return op === "==" ? same : !same;
609
+ }
610
+ if (op === "+" && (typeof a === "string" || typeof b === "string")) {
611
+ if (!(typeof a === "string" && typeof b === "string"))
612
+ fail("'+' joins text only to text — wrap the number in str()");
613
+ const out = a + b;
614
+ if (out.length > MAX_STRING)
615
+ fail("text grew too long");
616
+ return out;
617
+ }
618
+ if (op === "<" || op === "<=" || op === ">" || op === ">=") {
619
+ let x, y;
620
+ if (typeof a === "string" && typeof b === "string")
621
+ [x, y] = [a, b];
622
+ else
623
+ [x, y] = [num(a, `'${op}'`), num(b, `'${op}'`)];
624
+ return op === "<" ? x < y : op === "<=" ? x <= y : op === ">" ? x > y : x >= y;
625
+ }
626
+ const x = num(a, `'${op}'`);
627
+ const y = num(b, `'${op}'`);
628
+ if (op === "+")
629
+ return finite(x + y, "a sum");
630
+ if (op === "-")
631
+ return finite(x - y, "a difference");
632
+ if (op === "*")
633
+ return finite(x * y, "a product");
634
+ if (op === "/" || op === "%") {
635
+ if (y === 0)
636
+ fail(`division by zero — guard it, e.g. if(d == 0, 0, n ${op} d)`);
637
+ return finite(op === "/" ? x / y : x % y, "a quotient");
638
+ }
639
+ return fail(`unknown operator ${op}`);
640
+ }
641
+ apply(fn, env, args) {
642
+ const [, params, body] = fn;
643
+ const inner = { ...env };
644
+ params.forEach((p, i) => (inner[p] = i < args.length ? args[i] : null));
645
+ return this.run(body, inner);
646
+ }
647
+ call(name, argNodes, env) {
648
+ const [lo, hi] = exports.WIDGET_FUNCTIONS[name];
649
+ if (argNodes.length < lo || argNodes.length > hi) {
650
+ fail(`${name}() takes ${lo === hi ? lo : `${lo} to ${hi}`} arguments, got ${argNodes.length}`);
651
+ }
652
+ if (name === "if") {
653
+ return this.run(truthy(this.run(argNodes[0], env)) ? argNodes[1] : argNodes[2], env);
654
+ }
655
+ if (name === "map" || name === "filter") {
656
+ const items = this.run(argNodes[0], env);
657
+ if (!Array.isArray(items))
658
+ fail(`${name}() needs a list first, got ${typeName(items)}`);
659
+ const fn = argNodes[1];
660
+ if (fn[0] !== "fn")
661
+ fail(`${name}() needs a function like x => x * 2`);
662
+ const out = [];
663
+ items.forEach((item, i) => {
664
+ this.tick();
665
+ const v = this.apply(fn, env, [item, i]);
666
+ if (name === "map")
667
+ out.push(v);
668
+ else if (truthy(v))
669
+ out.push(item);
670
+ });
671
+ return out;
672
+ }
673
+ const a = argNodes.map((n) => this.run(n, env));
674
+ return builtin(name, a, this);
675
+ }
676
+ }
677
+ function builtin(name, a, ev) {
678
+ switch (name) {
679
+ case "min":
680
+ case "max": {
681
+ const vals = a.length === 1 && Array.isArray(a[0]) ? numbers(a[0], name) : a.map((x) => num(x, `${name}()`));
682
+ if (!vals.length)
683
+ fail(`${name}() of an empty list`);
684
+ return name === "min" ? Math.min(...vals) : Math.max(...vals);
685
+ }
686
+ case "abs":
687
+ return Math.abs(num(a[0], "abs()"));
688
+ case "round":
689
+ return roundHalfAway(num(a[0], "round()"), intArg(a, 1, 0, "round()'s digits"));
690
+ case "floor":
691
+ return Math.floor(num(a[0], "floor()"));
692
+ case "ceil":
693
+ return Math.ceil(num(a[0], "ceil()"));
694
+ case "sqrt": {
695
+ const x = num(a[0], "sqrt()");
696
+ if (x < 0)
697
+ fail("sqrt() of a negative number");
698
+ return Math.sqrt(x);
699
+ }
700
+ case "pow": {
701
+ const r = Math.pow(num(a[0], "pow()"), num(a[1], "pow()"));
702
+ if (!Number.isFinite(r))
703
+ fail("pow() has no finite result here");
704
+ return r;
705
+ }
706
+ case "log": {
707
+ const x = num(a[0], "log()");
708
+ if (x <= 0)
709
+ fail("log() needs a number above zero");
710
+ return Math.log(x);
711
+ }
712
+ case "exp": {
713
+ const r = Math.exp(num(a[0], "exp()"));
714
+ if (!Number.isFinite(r))
715
+ fail("exp() has no finite result here");
716
+ return r;
717
+ }
718
+ case "clamp": {
719
+ const [x, lo, hi] = a.map((v) => num(v, "clamp()"));
720
+ return Math.max(lo, Math.min(hi, x));
721
+ }
722
+ case "sum":
723
+ return finite(plainSum(numbers(a[0], "sum")), "sum()");
724
+ case "avg": {
725
+ const vals = numbers(a[0], "avg");
726
+ if (!vals.length)
727
+ fail("avg() of an empty list");
728
+ return plainSum(vals) / vals.length;
729
+ }
730
+ case "len":
731
+ if (!Array.isArray(a[0]) && typeof a[0] !== "string")
732
+ fail(`len() needs a list or text, got ${typeName(a[0])}`);
733
+ return a[0].length;
734
+ case "range": {
735
+ const ns = a.map((x) => num(x, "range()"));
736
+ const [start, end, step] = ns.length === 1 ? [0, ns[0], 1] : [ns[0], ns[1], ns.length === 3 ? ns[2] : 1];
737
+ if (step === 0)
738
+ fail("range() step cannot be zero");
739
+ const count = Math.max(0, Math.ceil((end - start) / step));
740
+ if (count > MAX_LIST)
741
+ fail(`range() would make ${count} items; the limit is ${MAX_LIST}`);
742
+ ev.tick(count);
743
+ return Array.from({ length: count }, (_, i) => start + i * step);
744
+ }
745
+ case "str":
746
+ return widgetValueText(a[0]);
747
+ case "number":
748
+ return formatNumber(num(a[0], "number()"), intArg(a, 1, null, "number()'s decimals"));
749
+ case "currency": {
750
+ const code = a.length > 1 && a[1] !== null ? a[1] : "USD";
751
+ if (typeof code !== "string" || !/^[A-Za-z]{3}$/.test(code))
752
+ fail("currency() needs a three-letter code like 'USD'");
753
+ return formatCurrency(num(a[0], "currency()"), code, intArg(a, 2, null, "currency()'s decimals"));
754
+ }
755
+ case "percent":
756
+ return formatNumber(num(a[0], "percent()") * 100, intArg(a, 1, 0, "percent()'s decimals")) + "%";
757
+ case "compact":
758
+ return formatCompact(num(a[0], "compact()"));
759
+ case "pmt": {
760
+ const [r, n, p] = a.map((v) => num(v, "pmt()"));
761
+ if (n <= 0)
762
+ fail("pmt() needs more than zero periods");
763
+ if (r === 0)
764
+ return p / n;
765
+ const denom = 1 - Math.pow(1 + r, -n);
766
+ if (denom === 0)
767
+ fail("pmt() has no finite result here");
768
+ return finite((p * r) / denom, "pmt()");
769
+ }
770
+ case "upper":
771
+ case "lower":
772
+ if (typeof a[0] !== "string")
773
+ fail(`${name}() needs text`);
774
+ return name === "upper" ? a[0].toUpperCase() : a[0].toLowerCase();
775
+ case "plural": {
776
+ const n = num(a[0], "plural()");
777
+ if (typeof a[1] !== "string" || typeof a[2] !== "string")
778
+ fail("plural(n, 'one', 'many') needs two words");
779
+ return n === 1 ? a[1] : a[2];
780
+ }
781
+ case "contains":
782
+ if (Array.isArray(a[0]))
783
+ return a[0].some((x) => typeName(x) === typeName(a[1]) && x === a[1]);
784
+ if (typeof a[0] === "string" && typeof a[1] === "string")
785
+ return a[0].includes(a[1]);
786
+ return fail("contains() needs a list or text first");
787
+ case "first":
788
+ case "last":
789
+ if (!Array.isArray(a[0]) || !a[0].length)
790
+ fail(`${name}() needs a non-empty list`);
791
+ return name === "first" ? a[0][0] : a[0][a[0].length - 1];
792
+ }
793
+ return fail(`unknown function ${name}`);
794
+ }
795
+ /** Evaluate one formula against a scope. Throws `WidgetExprError` and nothing else. */
796
+ function evaluateFormula(src, scope) {
797
+ const tree = parseExpr(src);
798
+ try {
799
+ return new Evaluator(scope).run(tree, {});
800
+ }
801
+ catch (e) {
802
+ if (e instanceof WidgetExprError)
803
+ throw e;
804
+ if (e instanceof RangeError)
805
+ fail("this formula is nested too deeply");
806
+ return fail(`cannot evaluate: ${e?.message ?? e}`);
807
+ }
808
+ }
809
+ /** `"Pay {currency(p)}"` → parts. `{{` / `}}` are literal braces. */
810
+ function templateParts(text) {
811
+ const out = [];
812
+ let buf = "";
813
+ let i = 0;
814
+ const n = text.length;
815
+ while (i < n) {
816
+ const c = text[i];
817
+ if (c === "{" && text.startsWith("{{", i)) {
818
+ buf += "{";
819
+ i += 2;
820
+ continue;
821
+ }
822
+ if (c === "}" && text.startsWith("}}", i)) {
823
+ buf += "}";
824
+ i += 2;
825
+ continue;
826
+ }
827
+ if (c === "}")
828
+ fail("a '}' with no '{' — write '}}' for a literal brace");
829
+ if (c === "{") {
830
+ let depth = 1;
831
+ let j = i + 1;
832
+ let quote = null;
833
+ while (j < n && depth) {
834
+ const d = text[j];
835
+ if (quote) {
836
+ if (d === "\\")
837
+ j++;
838
+ else if (d === quote)
839
+ quote = null;
840
+ }
841
+ else if (d === "'" || d === '"')
842
+ quote = d;
843
+ else if (d === "{")
844
+ depth++;
845
+ else if (d === "}")
846
+ depth--;
847
+ j++;
848
+ }
849
+ if (depth)
850
+ fail("a '{' is never closed — write '{{' for a literal brace");
851
+ if (buf) {
852
+ out.push(["t", buf]);
853
+ buf = "";
854
+ }
855
+ out.push(["e", text.slice(i + 1, j - 1)]);
856
+ i = j;
857
+ continue;
858
+ }
859
+ buf += c;
860
+ i++;
861
+ }
862
+ if (buf)
863
+ out.push(["t", buf]);
864
+ return out;
865
+ }
866
+ function renderTemplate(text, scope) {
867
+ let out = "";
868
+ for (const [kind, part] of templateParts(text))
869
+ out += kind === "t" ? part : widgetValueText(evaluateFormula(part, scope));
870
+ if (out.length > MAX_STRING)
871
+ fail("text grew too long");
872
+ return out;
873
+ }
874
+ // ============================================================================ resolve
875
+ const NOT_TEMPLATED = new Set([
876
+ "type", "bind", "key", "x", "kind", "style", "weight", "tone", "align", "justify",
877
+ "gap", "aspect", "fit", "format", "currency", "size", "height", "trend", "v", "include",
878
+ ]);
879
+ const isExpr = (v) => !!v && typeof v === "object" && !Array.isArray(v) && Object.keys(v).length === 1 && typeof v.expr === "string";
880
+ function computedOrder(computed) {
881
+ const names = new Set(Object.keys(computed));
882
+ const deps = {};
883
+ for (const [k, v] of Object.entries(computed))
884
+ deps[k] = [...freeNames(parseExpr(v))].filter((d) => names.has(d)).sort();
885
+ const order = [];
886
+ const done = new Set();
887
+ const visit = (k, stack) => {
888
+ if (done.has(k))
889
+ return;
890
+ if (stack.includes(k))
891
+ fail(`computed values refer to each other in a loop: ${[...stack, k].join(" → ")}`);
892
+ for (const d of deps[k])
893
+ visit(d, [...stack, k]);
894
+ done.add(k);
895
+ order.push(k);
896
+ };
897
+ for (const k of Object.keys(computed))
898
+ visit(k, []);
899
+ return order;
900
+ }
901
+ function freeNames(node, bound = new Set()) {
902
+ const out = new Set();
903
+ const walk = (n, b) => {
904
+ switch (n[0]) {
905
+ case "name":
906
+ if (!b.has(n[1]))
907
+ out.add(n[1]);
908
+ return;
909
+ case "lit":
910
+ return;
911
+ case "fn":
912
+ return walk(n[2], new Set([...b, ...n[1]]));
913
+ case "list":
914
+ return n[1].forEach((c) => walk(c, b));
915
+ case "obj":
916
+ return n[1].forEach(([, c]) => walk(c, b));
917
+ case "un":
918
+ return walk(n[2], b);
919
+ case "bin":
920
+ walk(n[2], b);
921
+ return walk(n[3], b);
922
+ case "cond":
923
+ walk(n[1], b);
924
+ walk(n[2], b);
925
+ return walk(n[3], b);
926
+ case "call":
927
+ return n[2].forEach((c) => walk(c, b));
928
+ case "get":
929
+ walk(n[1], b);
930
+ return walk(n[2], b);
931
+ }
932
+ };
933
+ walk(node, bound);
934
+ return out;
935
+ }
936
+ /** State plus every computed value. */
937
+ function widgetScope(widget, state) {
938
+ const computed = widget.computed ?? {};
939
+ const scope = { ...state };
940
+ for (const name of computedOrder(computed))
941
+ scope[name] = evaluateFormula(computed[name], scope);
942
+ return scope;
943
+ }
944
+ /**
945
+ * The widget with every formula evaluated against `state` — what is drawn. Mirrors
946
+ * `resolve` in app/widgets/check.py, which proved the widget at sampled states.
947
+ */
948
+ function resolveWidget(widget, state) {
949
+ const scope = widgetScope(widget, state);
950
+ const go = (node, key, top, inOptions) => {
951
+ if (isExpr(node))
952
+ return evaluateFormula(node.expr, scope);
953
+ if (Array.isArray(node))
954
+ return node.map((v) => go(v, key, false, key === "options"));
955
+ if (node && typeof node === "object") {
956
+ const out = {};
957
+ for (const [k, v] of Object.entries(node)) {
958
+ out[k] = top && (k === "state" || k === "computed") ? v : go(v, k, false, inOptions);
959
+ }
960
+ return out;
961
+ }
962
+ if (typeof node === "string" && key !== null && !NOT_TEMPLATED.has(key) && !(inOptions && key === "value")) {
963
+ return node.includes("{") || node.includes("}") ? renderTemplate(node, scope) : node;
964
+ }
965
+ return node;
966
+ };
967
+ const out = go(widget, null, true, false);
968
+ out.state = { ...state };
969
+ return out;
970
+ }
971
+ /** Stable id of every action, by path — the same ids the server computes. */
972
+ function widgetActionId(path) {
973
+ return `${path}.action`;
974
+ }
975
+ // ============================================================================ text
976
+ /** A resolved widget as text. The same function as app/widgets/fallback.py. */
977
+ function widgetToText(widget) {
978
+ const out = [];
979
+ if (widget.title)
980
+ out.push(`**${widget.title}**`);
981
+ if (widget.subtitle)
982
+ out.push(widget.subtitle);
983
+ out.push(...textChildren(widget.children || []));
984
+ return out.filter(Boolean).join("\n\n");
985
+ }
986
+ function textChildren(nodes) {
987
+ const out = [];
988
+ for (const n of nodes)
989
+ if (n.visible !== false)
990
+ out.push(...textOf(n));
991
+ return out;
992
+ }
993
+ function textOf(n) {
994
+ switch (n.type) {
995
+ case "text":
996
+ return [n.style === "heading" ? `**${n.value}**` : n.value];
997
+ case "row": {
998
+ const parts = textChildren(n.children);
999
+ const inline = parts.filter((p) => !p.includes("\n"));
1000
+ return inline.length === parts.length && parts.length ? [inline.join(" · ")] : parts;
1001
+ }
1002
+ case "column":
1003
+ return textChildren(n.children);
1004
+ case "tabs":
1005
+ return n.tabs.flatMap((t) => [`**${t.label}**`, ...textChildren(t.children)]);
1006
+ case "disclosure":
1007
+ return [`**${n.label}**`, ...textChildren(n.children)];
1008
+ case "stat": {
1009
+ const value = typeof n.value === "string" ? n.value : widgetValueText(n.value);
1010
+ return [`${n.label}: **${value}**${n.delta ? ` (${n.delta})` : ""}${n.caption ? ` — ${n.caption}` : ""}`];
1011
+ }
1012
+ case "progress": {
1013
+ const max = n.max ?? 100;
1014
+ const pct = max === 0 ? 0 : Math.max(0, Math.min(100, (n.value / max) * 100));
1015
+ return [`${n.label ? `${n.label}: ` : ""}${formatNumber(pct, 0)}%`];
1016
+ }
1017
+ case "image":
1018
+ return [`[Image: ${n.alt}]`];
1019
+ case "list":
1020
+ return [
1021
+ n.items
1022
+ .map((it) => `- ${it.title}${it.subtitle ? ` — ${it.subtitle}` : ""}${it.meta ? ` (${it.meta})` : ""}${it.badge ? ` [${it.badge.label}]` : ""}`)
1023
+ .join("\n"),
1024
+ ];
1025
+ case "table": {
1026
+ const head = `| ${n.columns.map((c) => c.label).join(" | ")} |`;
1027
+ const sep = `| ${n.columns.map(() => "---").join(" | ")} |`;
1028
+ const rows = n.rows.map((r) => `| ${n.columns.map((c) => formatWidgetValue(r[c.key], c.format ?? "text", n.currency ?? "USD").replace(/\|/g, "\\|")).join(" | ")} |`);
1029
+ return [[head, sep, ...rows].join("\n")];
1030
+ }
1031
+ case "fields":
1032
+ return [n.items.map((f) => `${f.label}: ${f.value}`).join("\n")];
1033
+ case "chart": {
1034
+ const lines = [`**${n.title || "Chart"}**`];
1035
+ for (const row of n.data.slice(0, 24)) {
1036
+ const vals = n.series
1037
+ .map((s) => `${s.label || s.key} ${formatWidgetValue(row[s.key], n.format ?? "number", n.currency ?? "USD")}`)
1038
+ .join(", ");
1039
+ lines.push(`- ${widgetValueText(row[n.x])}: ${vals}`);
1040
+ }
1041
+ if (n.data.length > 24)
1042
+ lines.push(`- … ${n.data.length - 24} more`);
1043
+ return [lines.join("\n")];
1044
+ }
1045
+ case "timeline":
1046
+ return [n.items.map((it) => `- ${it.time ? `${it.time} — ` : ""}${it.title}${it.description ? `: ${it.description}` : ""}`).join("\n")];
1047
+ case "callout":
1048
+ return [`> ${n.title ? `**${n.title}** ` : ""}${n.text}`];
1049
+ case "badge":
1050
+ return [`[${n.label}]`];
1051
+ default:
1052
+ return [];
1053
+ }
1054
+ }
1055
+ const LIGHT = {
1056
+ background: "#ffffff", surface: "#f5f6f8", border: "#e4e6eb", text: "#14161a", muted: "#5f6672",
1057
+ faint: "#9aa1ab", accent: "#4f46e5", onAccent: "#ffffff", success: "#15803d", warning: "#b45309",
1058
+ danger: "#dc2626", info: "#2563eb",
1059
+ series: ["#4f46e5", "#0ea5e9", "#f59e0b", "#10b981", "#ef4444", "#8b5cf6"],
1060
+ };
1061
+ const DARK = {
1062
+ background: "#17191e", surface: "#1f2228", border: "#2d313a", text: "#f2f3f5", muted: "#a3a9b3",
1063
+ faint: "#6c7380", accent: "#8b85ff", onAccent: "#0d0d14", success: "#4ade80", warning: "#fbbf24",
1064
+ danger: "#f87171", info: "#60a5fa",
1065
+ series: ["#8b85ff", "#38bdf8", "#fbbf24", "#34d399", "#f87171", "#c084fc"],
1066
+ };
1067
+ function detectDark() {
1068
+ try {
1069
+ const g = globalThis;
1070
+ return !!g.matchMedia?.("(prefers-color-scheme: dark)")?.matches;
1071
+ }
1072
+ catch {
1073
+ return false;
1074
+ }
1075
+ }
1076
+ function resolveWidgetTheme(theme = {}) {
1077
+ const dark = theme.scheme ? theme.scheme === "dark" : detectDark();
1078
+ const base = dark ? DARK : LIGHT;
1079
+ const density = theme.density ?? "regular";
1080
+ const k = density === "compact" ? 0.75 : density === "comfortable" ? 1.25 : 1;
1081
+ return {
1082
+ c: { ...base, ...(theme.colors ?? {}) },
1083
+ dark,
1084
+ radius: theme.radius ?? 12,
1085
+ space: { none: 0, xs: Math.round(4 * k), sm: Math.round(8 * k), md: Math.round(12 * k), lg: Math.round(20 * k) },
1086
+ font: theme.fontFamily,
1087
+ chrome: theme.chrome ?? true,
1088
+ };
1089
+ }
1090
+ /** A tone as a colour, and as a soft background behind text in that colour. */
1091
+ function toneColor(t, tone) {
1092
+ switch (tone) {
1093
+ case "accent": return t.c.accent;
1094
+ case "success": return t.c.success;
1095
+ case "warning": return t.c.warning;
1096
+ case "danger": return t.c.danger;
1097
+ case "info": return t.c.info;
1098
+ default: return t.c.text;
1099
+ }
1100
+ }
1101
+ function soft(t, color, alpha = t.dark ? 0.18 : 0.1) {
1102
+ const m = /^#([0-9a-f]{6})$/i.exec(color.trim());
1103
+ if (!m)
1104
+ return t.c.surface; // a CSS variable or a name: no arithmetic possible, stay neutral
1105
+ const v = parseInt(m[1], 16);
1106
+ return `rgba(${(v >> 16) & 255}, ${(v >> 8) & 255}, ${v & 255}, ${alpha})`;
1107
+ }
1108
+ function toneSoft(t, tone) {
1109
+ return !tone || tone === "neutral" ? t.c.surface : soft(t, toneColor(t, tone));
1110
+ }
1111
+ class WidgetSession {
1112
+ render;
1113
+ opts;
1114
+ holdReplies;
1115
+ state;
1116
+ last = null;
1117
+ listeners = new Set();
1118
+ sent = false;
1119
+ view;
1120
+ /** Per-instance UI state that isn't the widget's: which tab, which disclosure is open. */
1121
+ ui = {};
1122
+ constructor(render, opts = {}, holdReplies = false) {
1123
+ this.render = render;
1124
+ this.opts = opts;
1125
+ this.holdReplies = holdReplies;
1126
+ this.state = { ...(render.widget.state ?? {}) };
1127
+ if (render.answered?.values) {
1128
+ for (const [k, v] of Object.entries(render.answered.values)) {
1129
+ if (k in this.state)
1130
+ this.state[k] = v;
1131
+ }
1132
+ }
1133
+ this.view = this.compute();
1134
+ }
1135
+ get() {
1136
+ return this.view;
1137
+ }
1138
+ /** Carry another session's local state over — the same widget, grown. */
1139
+ adopt(prev) {
1140
+ for (const [k, v] of Object.entries(prev.state))
1141
+ if (k in this.state)
1142
+ this.state[k] = v;
1143
+ Object.assign(this.ui, prev.ui);
1144
+ this.view = this.compute();
1145
+ }
1146
+ subscribe(fn) {
1147
+ this.listeners.add(fn);
1148
+ return () => this.listeners.delete(fn);
1149
+ }
1150
+ /** New handlers or a new `holdReplies`. Silent: the host calling this is already redrawing. */
1151
+ setOptions(opts, holdReplies = false) {
1152
+ this.opts = opts;
1153
+ if (holdReplies !== this.holdReplies) {
1154
+ this.holdReplies = holdReplies;
1155
+ this.view = this.compute();
1156
+ }
1157
+ }
1158
+ value(key) {
1159
+ return this.state[key] ?? null;
1160
+ }
1161
+ set(key, value) {
1162
+ if (!(key in this.state))
1163
+ return;
1164
+ if (this.state[key] === value)
1165
+ return;
1166
+ this.state = { ...this.state, [key]: value };
1167
+ this.refresh();
1168
+ }
1169
+ setUi(key, value) {
1170
+ this.ui[key] = value;
1171
+ this.emit();
1172
+ }
1173
+ /** Run the action at `path` (from `layoutWidget`). */
1174
+ press(path) {
1175
+ const action = findAction(this.render.widget, path);
1176
+ if (!action)
1177
+ return;
1178
+ if (action.type === "link") {
1179
+ if (this.opts.onEvent?.({ type: "link", url: action.url }) === false)
1180
+ return;
1181
+ const url = this.resolvedAction(path)?.type === "link" ? this.resolvedAction(path).url : action.url;
1182
+ if (this.opts.onLink)
1183
+ this.opts.onLink(url);
1184
+ else {
1185
+ try {
1186
+ globalThis.open?.(url, "_blank", "noopener,noreferrer");
1187
+ }
1188
+ catch {
1189
+ /* nowhere to open it */
1190
+ }
1191
+ }
1192
+ return;
1193
+ }
1194
+ if (action.type === "set") {
1195
+ let v;
1196
+ try {
1197
+ v = (isExpr(action.value) ? evaluateFormula(action.value.expr, widgetScope(this.render.widget, this.state)) : action.value);
1198
+ }
1199
+ catch {
1200
+ return; // a press that cannot be computed changes nothing rather than something wrong
1201
+ }
1202
+ if (this.opts.onEvent?.({ type: "set", key: action.key, value: v }) === false)
1203
+ return;
1204
+ this.set(action.key, v);
1205
+ return;
1206
+ }
1207
+ if (this.view.replyLocked || !this.view.canReply)
1208
+ return;
1209
+ const include = action.include ?? boundKeys(this.render.widget);
1210
+ const values = {};
1211
+ for (const k of include)
1212
+ if (k in this.state)
1213
+ values[k] = this.state[k];
1214
+ let text = action.text;
1215
+ try {
1216
+ text = renderTemplate(action.text, widgetScope(this.render.widget, this.state));
1217
+ }
1218
+ catch {
1219
+ /* the server words the message anyway; this is only the optimistic copy */
1220
+ }
1221
+ const press = { widget_id: this.render.id, action_id: widgetActionId(path), values };
1222
+ if (this.opts.onEvent?.({ type: "reply", press, text }) === false)
1223
+ return;
1224
+ this.sent = true;
1225
+ this.refresh();
1226
+ this.opts.onReply?.(press, text);
1227
+ }
1228
+ resolvedAction(path) {
1229
+ return findAction(this.view.widget, path);
1230
+ }
1231
+ refresh() {
1232
+ this.view = this.compute();
1233
+ this.emit();
1234
+ }
1235
+ emit() {
1236
+ for (const fn of this.listeners)
1237
+ fn();
1238
+ }
1239
+ compute() {
1240
+ let widget;
1241
+ let broken = false;
1242
+ try {
1243
+ widget = resolveWidget(this.render.widget, this.state);
1244
+ this.last = widget;
1245
+ }
1246
+ catch {
1247
+ // Proven at sampled points, not every point. Between them, keep what was last
1248
+ // drawn rather than draw an error — the user sees the previous numbers, never a
1249
+ // broken card.
1250
+ if (this.last)
1251
+ widget = { ...this.last, state: { ...this.state } };
1252
+ else {
1253
+ widget = this.render.widget;
1254
+ broken = true;
1255
+ }
1256
+ }
1257
+ const replyLocked = this.holdReplies || this.sent || !!this.render.answered || !!this.render.preview;
1258
+ let canReply = !replyLocked;
1259
+ if (canReply) {
1260
+ for (const n of allNodes(this.render.widget)) {
1261
+ if (n.type === "input" && n.required && (this.state[n.bind] === "" || this.state[n.bind] === null))
1262
+ canReply = false;
1263
+ }
1264
+ }
1265
+ return { widget, broken, replyLocked, sent: this.sent || !!this.render.answered, canReply };
1266
+ }
1267
+ }
1268
+ exports.WidgetSession = WidgetSession;
1269
+ function* allNodes(w) {
1270
+ const visit = function* (nodes) {
1271
+ for (const n of nodes ?? []) {
1272
+ if (!n || typeof n !== "object")
1273
+ continue;
1274
+ yield n;
1275
+ if ("children" in n && Array.isArray(n.children))
1276
+ yield* visit(n.children);
1277
+ if (n.type === "tabs")
1278
+ for (const t of n.tabs ?? [])
1279
+ yield* visit(t.children);
1280
+ }
1281
+ };
1282
+ yield* visit(w.children);
1283
+ yield* visit(w.actions);
1284
+ }
1285
+ function boundKeys(w) {
1286
+ const out = [];
1287
+ for (const n of allNodes(w))
1288
+ if ("bind" in n && typeof n.bind === "string")
1289
+ out.push(n.bind);
1290
+ return out;
1291
+ }
1292
+ /** Walk `children[0].items[2]` back to its action. */
1293
+ function findAction(w, path) {
1294
+ let cur = w;
1295
+ for (const m of path.matchAll(/([A-Za-z_]+)|\[(\d+)\]/g)) {
1296
+ if (cur == null)
1297
+ return null;
1298
+ cur = m[1] !== undefined ? cur[m[1]] : cur[Number(m[2])];
1299
+ }
1300
+ const action = cur?.action;
1301
+ return action && typeof action === "object" && typeof action.type === "string" ? action : null;
1302
+ }
1303
+ const FONT = { caption: 12, label: 13, body: 14, subheading: 15, heading: 18, stat: 24, title: 16 };
1304
+ const WEIGHT = { regular: "400", medium: "500", bold: "600" };
1305
+ /** Lay out a session's current view. Hosts call this on every change. */
1306
+ function layoutWidget(session, theme) {
1307
+ const v = session.get();
1308
+ const t = theme;
1309
+ const ctx = { t, s: session, v };
1310
+ const w = v.widget;
1311
+ const maxWidth = w.size === "compact" ? 380 : w.size === "wide" ? undefined : 600;
1312
+ const body = [];
1313
+ if (w.title || w.subtitle) {
1314
+ const head = [];
1315
+ if (w.title)
1316
+ head.push(text(t, w.title, { fontSize: FONT.title, fontWeight: "600", color: t.c.text }));
1317
+ if (w.subtitle)
1318
+ head.push(text(t, w.subtitle, { fontSize: FONT.label, color: t.c.muted }));
1319
+ body.push(box({ gap: 2 }, head));
1320
+ }
1321
+ body.push(...nodes(ctx, w.children ?? [], "children"));
1322
+ const footer = (w.actions ?? []).filter((b) => b.visible !== false).map((b, i) => button(ctx, b, `actions[${i}]`));
1323
+ const replies = (w.actions ?? []).some((b) => b.visible !== false && b.action.type === "reply");
1324
+ if (session.render.preview) {
1325
+ footer.unshift(text(t, "Building…", { fontSize: FONT.caption, color: t.c.muted, marginRight: "auto" }, 1));
1326
+ }
1327
+ else if (replies && !v.replyLocked && !v.canReply) {
1328
+ // A disabled button that does not say why reads as broken.
1329
+ footer.unshift(text(t, "Fill in what's marked *", { fontSize: FONT.caption, color: t.c.muted, marginRight: "auto" }, 1));
1330
+ }
1331
+ if (v.sent) {
1332
+ footer.unshift(box({ flexDirection: "row", alignItems: "center", gap: 6, marginRight: "auto" }, [
1333
+ text(t, "✓", { color: t.c.success, fontSize: FONT.label, fontWeight: "600" }),
1334
+ text(t, "Sent", { color: t.c.muted, fontSize: FONT.label }),
1335
+ ]));
1336
+ }
1337
+ if (footer.length) {
1338
+ body.push(box({ flexDirection: "row", flexWrap: "wrap", justifyContent: "flex-end", alignItems: "center", gap: t.space.sm, paddingTop: 4 }, footer));
1339
+ }
1340
+ return box({
1341
+ width: "100%",
1342
+ maxWidth,
1343
+ gap: t.space.md,
1344
+ padding: t.chrome ? 16 : 0,
1345
+ borderRadius: t.radius,
1346
+ borderWidth: t.chrome ? 1 : 0,
1347
+ borderColor: t.c.border,
1348
+ borderStyle: "solid",
1349
+ backgroundColor: t.chrome ? t.c.background : undefined,
1350
+ fontFamily: t.font,
1351
+ overflow: "hidden",
1352
+ }, body, { role: "group", label: w.title ?? undefined });
1353
+ }
1354
+ function box(style, children, a11y, press, hover) {
1355
+ return { k: "box", style: { display: "flex", flexDirection: "column", ...style }, children, a11y, press, hover };
1356
+ }
1357
+ function text(t, value, style = {}, lines, numeric) {
1358
+ return { k: "text", style: { color: t.c.text, fontSize: FONT.body, lineHeight: Math.round((style.fontSize ?? FONT.body) * 1.4), fontFamily: t.font, ...style }, text: value, lines, numeric };
1359
+ }
1360
+ function nodes(ctx, list, path) {
1361
+ const out = [];
1362
+ list.forEach((n, i) => {
1363
+ if (!n || n.visible === false)
1364
+ return;
1365
+ const el = node(ctx, n, `${path}[${i}]`);
1366
+ if (el)
1367
+ out.push(el);
1368
+ });
1369
+ return out;
1370
+ }
1371
+ const ALIGN = { start: "flex-start", center: "center", end: "flex-end", stretch: "stretch", between: "space-between" };
1372
+ const TEXT_ALIGN = { start: "left", center: "center", end: "right" };
1373
+ function node(ctx, n, path) {
1374
+ const { t } = ctx;
1375
+ const L = LAYOUTS[n.type];
1376
+ if (!L) {
1377
+ // A component from a newer catalog than this SDK knows: its text, never a hole.
1378
+ const fallback = textOf(n).join("\n");
1379
+ return fallback ? text(t, fallback, { color: t.c.muted }) : null;
1380
+ }
1381
+ return L(ctx, n, path);
1382
+ }
1383
+ const LAYOUTS = {
1384
+ row: (ctx, n, path) => box({
1385
+ flexDirection: "row",
1386
+ gap: ctx.t.space[n.gap ?? "sm"],
1387
+ alignItems: ALIGN[n.align ?? "center"],
1388
+ justifyContent: ALIGN[n.justify ?? "start"],
1389
+ flexWrap: n.wrap ? "wrap" : "nowrap",
1390
+ }, nodes(ctx, n.children, `${path}.children`)),
1391
+ column: (ctx, n, path) => box({ gap: ctx.t.space[n.gap ?? "sm"], alignItems: ALIGN[n.align ?? "stretch"] }, nodes(ctx, n.children, `${path}.children`)),
1392
+ divider: (ctx) => box({ height: 1, backgroundColor: ctx.t.c.border, alignSelf: "stretch" }, []),
1393
+ tabs: (ctx, n, path) => {
1394
+ const { t, s } = ctx;
1395
+ const key = `tab:${path}`;
1396
+ const active = Math.min(Number(s.ui[key] ?? 0), n.tabs.length - 1);
1397
+ const bar = box({ flexDirection: "row", gap: 2, padding: 3, borderRadius: Math.max(6, t.radius - 4), backgroundColor: t.c.surface, alignSelf: "flex-start", flexWrap: "wrap" }, n.tabs.map((tab, i) => box({
1398
+ paddingVertical: 5,
1399
+ paddingHorizontal: 12,
1400
+ borderRadius: Math.max(4, t.radius - 6),
1401
+ backgroundColor: i === active ? t.c.background : undefined,
1402
+ cursor: "pointer",
1403
+ ...(i === active ? { shadowColor: "#000", shadowOpacity: t.dark ? 0 : 0.06, shadowRadius: 2, shadowOffset: { width: 0, height: 1 } } : {}),
1404
+ }, [text(t, tab.label, { fontSize: FONT.label, fontWeight: i === active ? "600" : "500", color: i === active ? t.c.text : t.c.muted })], { role: "tab", selected: i === active, label: tab.label }, () => s.setUi(key, i))), { role: "tablist" });
1405
+ const tab = n.tabs[active];
1406
+ return box({ gap: t.space.md }, [bar, box({ gap: t.space.sm }, nodes(ctx, tab.children, `${path}.tabs[${active}].children`))]);
1407
+ },
1408
+ disclosure: (ctx, n, path) => {
1409
+ const { t, s } = ctx;
1410
+ const key = `open:${path}`;
1411
+ const open = s.ui[key] ?? !!n.open;
1412
+ return box({ gap: t.space.sm }, [
1413
+ box({ flexDirection: "row", alignItems: "center", gap: 6, cursor: "pointer", paddingVertical: 2 }, [text(t, open ? "▾" : "▸", { color: t.c.muted, fontSize: FONT.subheading, width: 14, textAlign: "center" }), text(t, n.label, { fontWeight: "500", fontSize: FONT.body })], { role: "button", label: n.label, value: open ? "expanded" : "collapsed" }, () => s.setUi(key, !open)),
1414
+ ...(open ? [box({ gap: t.space.sm, paddingLeft: 18 }, nodes(ctx, n.children, `${path}.children`))] : []),
1415
+ ]);
1416
+ },
1417
+ text: (ctx, n) => {
1418
+ const { t } = ctx;
1419
+ const style = n.style ?? "body";
1420
+ const size = style === "heading" ? FONT.heading : style === "subheading" ? FONT.subheading : style === "caption" ? FONT.caption : style === "label" ? FONT.label : FONT.body;
1421
+ const tone = n.tone && n.tone !== "neutral" ? toneColor(t, n.tone) : style === "caption" || style === "label" ? t.c.muted : t.c.text;
1422
+ const weight = n.weight ? WEIGHT[n.weight] : style === "heading" || style === "subheading" ? "600" : style === "label" ? "500" : "400";
1423
+ return text(t, n.value, {
1424
+ fontSize: size,
1425
+ color: tone,
1426
+ fontWeight: weight,
1427
+ textAlign: TEXT_ALIGN[n.align ?? "start"],
1428
+ fontFamily: style === "mono" ? "Menlo, Consolas, monospace" : t.font,
1429
+ letterSpacing: style === "label" ? 0.2 : undefined,
1430
+ }, n.max_lines ?? undefined);
1431
+ },
1432
+ badge: (ctx, n) => pill(ctx.t, n.label, n.tone),
1433
+ stat: (ctx, n) => {
1434
+ const { t } = ctx;
1435
+ const value = typeof n.value === "number" ? widgetValueText(n.value) : n.value;
1436
+ const trendColor = n.trend === "up" ? t.c.success : n.trend === "down" ? t.c.danger : t.c.muted;
1437
+ const arrow = n.trend === "up" ? "↑ " : n.trend === "down" ? "↓ " : "";
1438
+ const children = [
1439
+ text(t, n.label, { fontSize: FONT.label, color: t.c.muted, fontWeight: "500" }),
1440
+ box({ flexDirection: "row", alignItems: "baseline", gap: 8, flexWrap: "wrap" }, [
1441
+ text(t, value, { fontSize: FONT.stat, fontWeight: "600", color: n.tone && n.tone !== "neutral" ? toneColor(t, n.tone) : t.c.text, lineHeight: 30 }, 1, true),
1442
+ ...(n.delta || n.trend ? [text(t, `${arrow}${n.delta ?? ""}`, { fontSize: FONT.label, fontWeight: "500", color: trendColor }, 1, true)] : []),
1443
+ ]),
1444
+ ];
1445
+ if (n.caption)
1446
+ children.push(text(t, n.caption, { fontSize: FONT.caption, color: t.c.faint }));
1447
+ return box({ gap: 2, padding: 12, borderRadius: Math.max(6, t.radius - 4), backgroundColor: t.c.surface, flexGrow: 1, flexBasis: 0, minWidth: 120 }, children);
1448
+ },
1449
+ progress: (ctx, n) => {
1450
+ const { t } = ctx;
1451
+ const max = n.max ?? 100;
1452
+ const pct = max === 0 ? 0 : Math.max(0, Math.min(1, n.value / max));
1453
+ const head = [];
1454
+ if (n.label)
1455
+ head.push(text(t, n.label, { fontSize: FONT.label, color: t.c.muted, flexGrow: 1 }));
1456
+ if (n.show_value !== false)
1457
+ head.push(text(t, `${formatNumber(pct * 100, 0)}%`, { fontSize: FONT.label, fontWeight: "500" }, 1, true));
1458
+ return box({ gap: 6 }, [
1459
+ ...(head.length ? [box({ flexDirection: "row", alignItems: "center", justifyContent: "space-between" }, head)] : []),
1460
+ box({ height: 8, borderRadius: 4, backgroundColor: t.c.surface, overflow: "hidden" }, [
1461
+ box({ height: 8, width: `${pct * 100}%`, borderRadius: 4, backgroundColor: toneColor(ctx.t, n.tone ?? "accent") }, []),
1462
+ ], { role: "progressbar", value: `${Math.round(pct * 100)}%`, label: n.label ?? undefined }),
1463
+ ]);
1464
+ },
1465
+ image: (ctx, n) => {
1466
+ const [a, b] = (n.aspect ?? "16:9").split(":").map(Number);
1467
+ return { k: "image", style: { width: "100%", aspectRatio: a / b, borderRadius: Math.max(6, ctx.t.radius - 4), backgroundColor: ctx.t.c.surface, overflow: "hidden" }, src: n.src, alt: n.alt, fit: n.fit ?? "cover" };
1468
+ },
1469
+ list: (ctx, n, path) => {
1470
+ const { t, s, v } = ctx;
1471
+ return box({ borderRadius: Math.max(6, t.radius - 4), borderWidth: 1, borderColor: t.c.border, borderStyle: "solid", overflow: "hidden" }, n.items.map((it, i) => {
1472
+ const p = `${path}.items[${i}]`;
1473
+ const pressable = !!it.action && (it.action.type !== "reply" || v.canReply);
1474
+ const right = [];
1475
+ if (it.badge)
1476
+ right.push(pill(t, it.badge.label, it.badge.tone));
1477
+ if (it.meta)
1478
+ right.push(text(t, it.meta, { fontSize: FONT.label, color: t.c.muted }, 1, true));
1479
+ if (it.action)
1480
+ right.push(text(t, it.action.type === "link" ? "↗" : "›", { fontSize: FONT.subheading, color: t.c.faint }));
1481
+ const row = [];
1482
+ if (it.image)
1483
+ row.push({ k: "image", style: { width: 40, height: 40, borderRadius: 8, backgroundColor: t.c.surface }, src: it.image, alt: it.title, fit: "cover" });
1484
+ row.push(box({ flexGrow: 1, flexShrink: 1, gap: 1 }, [
1485
+ text(t, it.title, { fontWeight: "500" }, 2),
1486
+ ...(it.subtitle ? [text(t, it.subtitle, { fontSize: FONT.label, color: t.c.muted }, 3)] : []),
1487
+ ]));
1488
+ if (right.length)
1489
+ row.push(box({ flexDirection: "row", alignItems: "center", gap: 8, flexShrink: 0 }, right));
1490
+ return box({ flexDirection: "row", alignItems: "center", gap: 12, paddingVertical: 10, paddingHorizontal: 12, borderTopWidth: i ? 1 : 0, borderColor: t.c.border, borderStyle: "solid", cursor: pressable ? "pointer" : undefined, opacity: it.action && !pressable ? 0.6 : 1 }, row, pressable ? { role: it.action.type === "link" ? "link" : "button", label: it.title } : undefined, pressable ? () => s.press(p) : undefined, pressable ? { backgroundColor: t.c.surface } : undefined);
1491
+ }));
1492
+ },
1493
+ table: (ctx, n) => {
1494
+ const { t } = ctx;
1495
+ const cell = (value, col, head) => {
1496
+ const numeric = (col.format ?? "text") !== "text";
1497
+ const align = col.align ?? (numeric ? "end" : "start");
1498
+ return box({ flexGrow: 1, flexBasis: 0, minWidth: 64, paddingVertical: 8, paddingHorizontal: 10 }, [
1499
+ text(t, value, { fontSize: head ? FONT.caption : FONT.label, fontWeight: head ? "600" : "400", color: head ? t.c.muted : t.c.text, textAlign: TEXT_ALIGN[align], textTransform: head ? "uppercase" : undefined, letterSpacing: head ? 0.4 : undefined }, 3, numeric),
1500
+ ]);
1501
+ };
1502
+ const rows = [
1503
+ box({ flexDirection: "row", backgroundColor: t.c.surface }, n.columns.map((c) => cell(c.label, c, true)), { role: "row" }),
1504
+ ...n.rows.map((r, i) => box({ flexDirection: "row", borderTopWidth: 1, borderColor: t.c.border, borderStyle: "solid" }, n.columns.map((c) => cell(formatWidgetValue(r[c.key], c.format ?? "text", n.currency ?? "USD"), c, false)), { role: "row" })),
1505
+ ];
1506
+ return box({ borderRadius: Math.max(6, t.radius - 4), borderWidth: 1, borderColor: t.c.border, borderStyle: "solid", overflow: "hidden" }, rows, { role: "table" });
1507
+ },
1508
+ fields: (ctx, n) => {
1509
+ const { t } = ctx;
1510
+ const two = n.columns === 2;
1511
+ return box({ flexDirection: two ? "row" : "column", flexWrap: two ? "wrap" : undefined, rowGap: t.space.sm, columnGap: t.space.lg }, n.items.map((f) => box({ flexDirection: two ? "column" : "row", gap: two ? 1 : 12, justifyContent: "space-between", width: two ? "46%" : undefined, flexGrow: two ? 1 : undefined }, [
1512
+ text(t, f.label, { fontSize: FONT.label, color: t.c.muted, flexShrink: 0 }),
1513
+ text(t, f.value, { fontWeight: "500", color: f.tone && f.tone !== "neutral" ? toneColor(t, f.tone) : t.c.text, textAlign: two ? "left" : "right", flexShrink: 1 }),
1514
+ ])));
1515
+ },
1516
+ chart: (ctx, n, path) => {
1517
+ const { t, s } = ctx;
1518
+ const geo = chartGeometry(n, t);
1519
+ const key = `point:${path}`;
1520
+ const active = s.ui[key];
1521
+ const children = [];
1522
+ if (n.title)
1523
+ children.push(text(t, n.title, { fontSize: FONT.label, fontWeight: "600" }));
1524
+ children.push({ k: "chart", style: { width: "100%", height: geo.height }, chart: { ...geo, active, select: (i) => s.setUi(key, i) }, theme: t });
1525
+ // The legend doubles as the readout: the selected point's values, or the series names.
1526
+ const row = active !== undefined ? n.data[active] : undefined;
1527
+ const legend = [];
1528
+ if (row)
1529
+ legend.push(text(t, widgetValueText(row[n.x]), { fontSize: FONT.caption, fontWeight: "600" }, 1));
1530
+ geo.series.forEach((sr) => {
1531
+ const label = sr.label + (row ? ` ${formatWidgetValue(row[sr.key], n.format ?? "number", n.currency ?? "USD")}` : "");
1532
+ if (geo.series.length > 1 || row) {
1533
+ legend.push(box({ flexDirection: "row", alignItems: "center", gap: 5 }, [
1534
+ box({ width: 8, height: 8, borderRadius: 2, backgroundColor: sr.color }, []),
1535
+ text(t, label, { fontSize: FONT.caption, color: t.c.muted }, 1, true),
1536
+ ]));
1537
+ }
1538
+ });
1539
+ if (legend.length)
1540
+ children.push(box({ flexDirection: "row", flexWrap: "wrap", gap: 12, alignItems: "center", minHeight: 18 }, legend));
1541
+ return box({ gap: 8 }, children, { role: "img", label: n.title ?? "chart" });
1542
+ },
1543
+ timeline: (ctx, n) => {
1544
+ const { t } = ctx;
1545
+ return box({ gap: 0 }, n.items.map((it, i) => box({ flexDirection: "row", gap: 12 }, [
1546
+ box({ alignItems: "center", width: 12 }, [
1547
+ box({ width: 10, height: 10, borderRadius: 5, marginTop: 5, backgroundColor: it.tone && it.tone !== "neutral" ? toneColor(t, it.tone) : t.c.accent }, []),
1548
+ ...(i < n.items.length - 1 ? [box({ width: 2, flexGrow: 1, backgroundColor: t.c.border, marginVertical: 3, minHeight: 12 }, [])] : []),
1549
+ ]),
1550
+ box({ flexGrow: 1, flexShrink: 1, gap: 1, paddingBottom: i < n.items.length - 1 ? 14 : 0 }, [
1551
+ box({ flexDirection: "row", gap: 8, alignItems: "baseline", flexWrap: "wrap" }, [
1552
+ text(t, it.title, { fontWeight: "500" }),
1553
+ ...(it.time ? [text(t, it.time, { fontSize: FONT.caption, color: t.c.faint }, 1)] : []),
1554
+ ]),
1555
+ ...(it.description ? [text(t, it.description, { fontSize: FONT.label, color: t.c.muted })] : []),
1556
+ ]),
1557
+ ])));
1558
+ },
1559
+ callout: (ctx, n) => {
1560
+ const { t } = ctx;
1561
+ const tone = n.tone ?? "info";
1562
+ return box({ flexDirection: "row", gap: 10, padding: 12, borderRadius: Math.max(6, t.radius - 4), backgroundColor: toneSoft(t, tone), borderLeftWidth: 3, borderColor: toneColor(t, tone), borderStyle: "solid" }, [
1563
+ box({ flexShrink: 1, gap: 2 }, [
1564
+ ...(n.title ? [text(t, n.title, { fontWeight: "600", color: toneColor(t, tone) })] : []),
1565
+ text(t, n.text, { fontSize: FONT.label + 1 }),
1566
+ ]),
1567
+ ]);
1568
+ },
1569
+ slider: (ctx, n) => {
1570
+ const { t, s, v } = ctx;
1571
+ const value = Number(s.value(n.bind) ?? n.min);
1572
+ return box({ gap: 6 }, [
1573
+ box({ flexDirection: "row", justifyContent: "space-between", alignItems: "baseline", gap: 8 }, [
1574
+ text(t, n.label, { fontSize: FONT.label, color: t.c.muted, fontWeight: "500", flexShrink: 1 }),
1575
+ text(t, formatWidgetValue(value, n.format ?? "number", n.currency ?? "USD"), { fontSize: FONT.label, fontWeight: "600" }, 1, true),
1576
+ ]),
1577
+ {
1578
+ k: "slider",
1579
+ style: { height: 24, width: "100%" },
1580
+ value,
1581
+ min: n.min,
1582
+ max: n.max,
1583
+ step: n.step ?? 1,
1584
+ label: n.label,
1585
+ disabled: false,
1586
+ track: t.c.surface === t.c.background ? t.c.border : t.c.border,
1587
+ fill: t.c.accent,
1588
+ thumb: t.c.background,
1589
+ change: (x) => s.set(n.bind, snap(x, n.min, n.max, n.step ?? 1)),
1590
+ },
1591
+ ]);
1592
+ },
1593
+ toggle: (ctx, n) => {
1594
+ const { t, s, v } = ctx;
1595
+ const on = !!s.value(n.bind);
1596
+ return box({ flexDirection: "row", alignItems: "center", gap: 12, cursor: "pointer" }, [
1597
+ box({ flexGrow: 1, flexShrink: 1, gap: 1 }, [
1598
+ text(t, n.label, { fontWeight: "500" }),
1599
+ ...(n.description ? [text(t, n.description, { fontSize: FONT.label, color: t.c.muted })] : []),
1600
+ ]),
1601
+ box({ width: 36, height: 20, borderRadius: 10, padding: 2, backgroundColor: on ? t.c.accent : t.c.border, alignItems: on ? "flex-end" : "flex-start", justifyContent: "center" }, [
1602
+ box({ width: 16, height: 16, borderRadius: 8, backgroundColor: "#ffffff" }, []),
1603
+ ]),
1604
+ ], { role: "switch", label: n.label, checked: on }, () => s.set(n.bind, !on));
1605
+ },
1606
+ select: (ctx, n) => {
1607
+ const { t, s, v } = ctx;
1608
+ const current = s.value(n.bind);
1609
+ return box({ gap: 6 }, [
1610
+ ...(n.label ? [text(t, n.label, { fontSize: FONT.label, color: t.c.muted, fontWeight: "500" })] : []),
1611
+ box({ flexDirection: "row", flexWrap: "wrap", gap: 6 }, n.options.map((o) => {
1612
+ const on = o.value === current;
1613
+ return box({
1614
+ paddingVertical: 6,
1615
+ paddingHorizontal: 12,
1616
+ borderRadius: 999,
1617
+ borderWidth: 1,
1618
+ borderStyle: "solid",
1619
+ borderColor: on ? t.c.accent : t.c.border,
1620
+ backgroundColor: on ? soft(t, t.c.accent, t.dark ? 0.22 : 0.1) : t.c.background,
1621
+ cursor: "pointer",
1622
+ }, [text(t, o.label, { fontSize: FONT.label, fontWeight: on ? "600" : "500", color: on ? t.c.accent : t.c.text })], { role: "radio", checked: on, label: o.label }, () => s.set(n.bind, o.value));
1623
+ }), { role: "radiogroup", label: n.label ?? undefined }),
1624
+ ]);
1625
+ },
1626
+ input: (ctx, n) => {
1627
+ const { t, s, v } = ctx;
1628
+ const raw = s.value(n.bind);
1629
+ return box({ gap: 6 }, [
1630
+ text(t, `${n.label}${n.required ? " *" : ""}`, { fontSize: FONT.label, color: t.c.muted, fontWeight: "500" }),
1631
+ {
1632
+ k: "field",
1633
+ style: {
1634
+ borderWidth: 1,
1635
+ borderStyle: "solid",
1636
+ borderColor: t.c.border,
1637
+ borderRadius: Math.max(6, t.radius - 4),
1638
+ paddingVertical: 8,
1639
+ paddingHorizontal: 10,
1640
+ fontSize: FONT.body,
1641
+ color: t.c.text,
1642
+ backgroundColor: t.c.background,
1643
+ minHeight: n.kind === "multiline" ? 84 : undefined,
1644
+ fontFamily: t.font,
1645
+ },
1646
+ value: raw === null || raw === undefined ? "" : String(raw),
1647
+ kind: n.kind ?? "text",
1648
+ placeholder: n.placeholder ?? (n.kind === "date" ? "YYYY-MM-DD" : ""),
1649
+ label: n.label,
1650
+ disabled: false,
1651
+ placeholderColor: t.c.faint,
1652
+ change: (x) => {
1653
+ if (n.kind === "number") {
1654
+ const parsed = x.trim() === "" ? null : Number(x);
1655
+ s.set(n.bind, parsed === null || Number.isFinite(parsed) ? parsed : s.value(n.bind));
1656
+ }
1657
+ else
1658
+ s.set(n.bind, x);
1659
+ },
1660
+ },
1661
+ ]);
1662
+ },
1663
+ button: (ctx, n, path) => button(ctx, n, path),
1664
+ };
1665
+ function pill(t, label, tone) {
1666
+ const color = !tone || tone === "neutral" ? t.c.muted : toneColor(t, tone);
1667
+ return box({ paddingVertical: 2, paddingHorizontal: 8, borderRadius: 999, backgroundColor: toneSoft(t, tone ?? "neutral"), alignSelf: "flex-start" }, [
1668
+ text(t, label, { fontSize: FONT.caption, fontWeight: "600", color, lineHeight: 16 }, 1),
1669
+ ]);
1670
+ }
1671
+ function button(ctx, n, path) {
1672
+ const { t, s, v } = ctx;
1673
+ const isLink = n.action.type === "link";
1674
+ // Only a reply waits on anything. A set button is local and a link is a link — both
1675
+ // work in a widget that was answered long ago.
1676
+ const off = !!n.disabled || (n.action.type === "reply" && !v.canReply);
1677
+ const style = n.style ?? "secondary";
1678
+ const bg = style === "primary" ? t.c.accent : style === "danger" ? t.c.danger : style === "ghost" ? undefined : t.c.background;
1679
+ const fg = style === "primary" ? t.c.onAccent : style === "danger" ? "#ffffff" : style === "ghost" ? t.c.accent : t.c.text;
1680
+ return box({
1681
+ flexDirection: "row",
1682
+ alignItems: "center",
1683
+ justifyContent: "center",
1684
+ paddingVertical: 8,
1685
+ paddingHorizontal: 14,
1686
+ borderRadius: Math.max(6, t.radius - 4),
1687
+ backgroundColor: bg,
1688
+ borderWidth: style === "secondary" ? 1 : 0,
1689
+ borderColor: t.c.border,
1690
+ borderStyle: "solid",
1691
+ opacity: off ? 0.45 : 1,
1692
+ cursor: off ? "default" : "pointer",
1693
+ alignSelf: "flex-start",
1694
+ }, [text(t, n.label + (isLink ? " ↗" : ""), { fontSize: FONT.label + 1, fontWeight: "600", color: fg }, 1)], { role: isLink ? "link" : "button", label: n.label, disabled: off }, off ? undefined : () => s.press(path), off ? undefined : { opacity: 0.88 });
1695
+ }
1696
+ function snap(x, min, max, step) {
1697
+ const k = Math.round((x - min) / step);
1698
+ const v = Math.max(min, Math.min(max, min + k * step));
1699
+ return Number(v.toFixed(10));
1700
+ }
1701
+ function niceStep(span, ticks) {
1702
+ const raw = span / ticks;
1703
+ const mag = 10 ** Math.floor(Math.log10(raw));
1704
+ const r = raw / mag;
1705
+ return (r <= 1 ? 1 : r <= 2 ? 2 : r <= 2.5 ? 2.5 : r <= 5 ? 5 : 10) * mag;
1706
+ }
1707
+ /** Short enough for the axis gutter: `$600K`, not `$600,000.00`. */
1708
+ function axisLabel(v, format, currency) {
1709
+ if (format === "percent")
1710
+ return formatWidgetValue(v, "percent");
1711
+ const short = formatCompact(Math.abs(v));
1712
+ if (format === "currency") {
1713
+ const code = currency.toUpperCase();
1714
+ const sym = (CURRENCY[code] ?? `${code} `).trim();
1715
+ return `${v < 0 ? "-" : ""}${sym}${short}`;
1716
+ }
1717
+ return `${v < 0 ? "-" : ""}${short}`;
1718
+ }
1719
+ function chartGeometry(n, t) {
1720
+ const height = n.height === "sm" ? 140 : n.height === "lg" ? 280 : 200;
1721
+ const count = n.data.length;
1722
+ const stacked = !!n.stacked && n.kind !== "line";
1723
+ let lo = 0;
1724
+ let hi = 0;
1725
+ const base = new Array(count).fill(0);
1726
+ const baseNeg = new Array(count).fill(0);
1727
+ const stackedTops = [];
1728
+ n.series.forEach(() => stackedTops.push([]));
1729
+ n.data.forEach((row, i) => {
1730
+ n.series.forEach((s, si) => {
1731
+ const v = row[s.key];
1732
+ if (typeof v !== "number")
1733
+ return;
1734
+ if (stacked) {
1735
+ if (v >= 0) {
1736
+ base[i] += v;
1737
+ hi = Math.max(hi, base[i]);
1738
+ }
1739
+ else {
1740
+ baseNeg[i] += v;
1741
+ lo = Math.min(lo, baseNeg[i]);
1742
+ }
1743
+ stackedTops[si][i] = v >= 0 ? base[i] : baseNeg[i];
1744
+ }
1745
+ else {
1746
+ hi = Math.max(hi, v);
1747
+ lo = Math.min(lo, v);
1748
+ }
1749
+ });
1750
+ });
1751
+ if (hi === lo)
1752
+ hi = lo + 1;
1753
+ const step = niceStep(hi - lo, 4);
1754
+ const min = Math.floor(lo / step) * step;
1755
+ const max = Math.ceil(hi / step) * step;
1756
+ const y = (v) => (v - min) / (max - min);
1757
+ const yTicks = [];
1758
+ for (let v = min; v <= max + step / 2; v += step) {
1759
+ yTicks.push({ y: y(v), label: axisLabel(Number(v.toFixed(10)), n.format ?? "number", n.currency ?? "USD") });
1760
+ }
1761
+ const bandW = 1 / count;
1762
+ const slots = n.data.map((_, i) => (n.kind === "bar" ? (i + 0.5) * bandW : count === 1 ? 0.5 : i / (count - 1)));
1763
+ const every = Math.max(1, Math.ceil(count / 8));
1764
+ const xLabels = n.data
1765
+ .map((row, i) => ({ x: slots[i], label: widgetValueText(row[n.x] ?? "") }))
1766
+ .filter((_, i) => i % every === 0 || i === count - 1);
1767
+ const inner = n.kind === "bar" ? bandW * 0.72 : 0;
1768
+ const series = n.series.map((s, si) => {
1769
+ const color = s.tone ? toneColor(t, s.tone) : t.c.series[si % t.c.series.length];
1770
+ const points = n.data.map((row, i) => {
1771
+ const v = row[s.key];
1772
+ if (typeof v !== "number")
1773
+ return null;
1774
+ return { x: slots[i], y: y(stacked ? stackedTops[si][i] : v) };
1775
+ });
1776
+ const bars = n.kind !== "bar"
1777
+ ? []
1778
+ : n.data.flatMap((row, i) => {
1779
+ const v = row[s.key];
1780
+ if (typeof v !== "number")
1781
+ return [];
1782
+ if (stacked) {
1783
+ const top = stackedTops[si][i];
1784
+ const bottom = top - v;
1785
+ return [{ x: slots[i] - inner / 2, w: inner, y0: y(Math.min(top, bottom)), y1: y(Math.max(top, bottom)) }];
1786
+ }
1787
+ const w = inner / n.series.length;
1788
+ return [{ x: slots[i] - inner / 2 + si * w + w * 0.08, w: w * 0.84, y0: y(Math.min(0, v)), y1: y(Math.max(0, v)) }];
1789
+ });
1790
+ return { key: s.key, label: s.label || s.key, color, points, bars };
1791
+ });
1792
+ return { kind: n.kind, height, yTicks, xLabels, series, slots, zero: y(0) };
1793
+ }
1794
+ /**
1795
+ * A React component that renders a widget.
1796
+ *
1797
+ * import * as React from "react";
1798
+ * const OberikWidget = createWidgetComponent(React);
1799
+ * <OberikWidget render={w} onReply={(press) => client.chat.stream({ session_id, widget_action: press })} />
1800
+ *
1801
+ * React Native: `createWidgetComponent(React, nativePlatform(RN, { svg }))`.
1802
+ */
1803
+ function createWidgetComponent(React, platform) {
1804
+ const P = platform ?? webPlatform(React);
1805
+ const h = React.createElement;
1806
+ function Inner(props) {
1807
+ const opts = {
1808
+ onReply: props.onReply,
1809
+ onLink: props.onLink ?? P.openURL,
1810
+ onEvent: props.onEvent,
1811
+ };
1812
+ const ref = React.useRef(null);
1813
+ if (ref.current === null || ref.current.render !== props.render) {
1814
+ const prev = ref.current;
1815
+ ref.current = new WidgetSession(props.render, opts, !!props.holdReplies);
1816
+ // A preview growing, or becoming the finished widget, keeps what the user already
1817
+ // did to it — a slider dragged while the rest was still arriving stays put.
1818
+ if (prev && prev.render.call_id && prev.render.call_id === props.render.call_id) {
1819
+ ref.current.adopt(prev);
1820
+ }
1821
+ }
1822
+ const session = ref.current;
1823
+ session.setOptions(opts, !!props.holdReplies);
1824
+ const [, bump] = React.useReducer((x) => x + 1, 0);
1825
+ React.useEffect(() => session.subscribe(bump), [session]);
1826
+ const theme = React.useMemo(() => resolveWidgetTheme(props.theme), [JSON.stringify(props.theme ?? {})]);
1827
+ const view = session.get();
1828
+ if (view.broken)
1829
+ return fallbackEl(props.render.fallback, theme);
1830
+ return draw(layoutWidget(session, theme), "root");
1831
+ }
1832
+ function fallbackEl(textValue, theme) {
1833
+ return h(P.View, { style: P.style({ padding: 12, borderRadius: theme.radius, borderWidth: 1, borderColor: theme.c.border, borderStyle: "solid", display: "flex", flexDirection: "column" }, "box") }, h(P.Text, { style: P.style({ color: theme.c.text, fontSize: 14, lineHeight: 20 }, "text") }, textValue || "(widget)"));
1834
+ }
1835
+ function draw(el, key, depth = 0) {
1836
+ // The card's direct children fall in as they arrive — a widget being written shows
1837
+ // its pieces landing, and the first paint does too.
1838
+ if (depth === 1 && P.name === "web")
1839
+ return h(Appear, { key }, drawInner(el, key, depth));
1840
+ return drawInner(el, key, depth);
1841
+ }
1842
+ function Appear({ children }) {
1843
+ const [shown, setShown] = React.useState(false);
1844
+ React.useEffect(() => {
1845
+ const raf = globalThis.requestAnimationFrame ?? ((f) => setTimeout(f, 16));
1846
+ raf(() => setShown(true));
1847
+ }, []);
1848
+ return h("div", { style: { display: "flex", flexDirection: "column", opacity: shown ? 1 : 0, transform: shown ? "none" : "translateY(6px)", transition: "opacity 240ms ease, transform 280ms cubic-bezier(0.2, 0.8, 0.2, 1)" } }, children);
1849
+ }
1850
+ function drawInner(el, key, depth) {
1851
+ switch (el.k) {
1852
+ case "text": {
1853
+ const props = { key, style: P.style(el.style, "text") };
1854
+ if (el.lines)
1855
+ props.numberOfLines = el.lines;
1856
+ if (el.numeric)
1857
+ props.style = { ...props.style, fontVariant: P.name === "native" ? ["tabular-nums"] : undefined, fontVariantNumeric: P.name === "web" ? "tabular-nums" : undefined };
1858
+ return h(P.Text, props, el.text);
1859
+ }
1860
+ case "box": {
1861
+ const kids = el.children.map((c, i) => draw(c, `${key}.${i}`, depth + 1));
1862
+ if (el.press) {
1863
+ return h(P.Pressable, { key, onPress: el.press, style: P.style(el.style, "box"), hoverStyle: el.hover ? P.style(el.hover, "box") : undefined, a11y: el.a11y }, ...kids);
1864
+ }
1865
+ return h(P.View, { key, style: P.style(el.style, "box"), a11y: el.a11y }, ...kids);
1866
+ }
1867
+ case "image":
1868
+ return h(SafeImage, { key, el });
1869
+ case "slider":
1870
+ return h(P.Slider, { key, ...el });
1871
+ case "field":
1872
+ return h(P.TextInput, { key, el });
1873
+ case "chart":
1874
+ return h(P.Chart, { key, geo: el.chart, theme: el.theme, style: el.style });
1875
+ }
1876
+ }
1877
+ function SafeImage({ el }) {
1878
+ const [failed, setFailed] = React.useState(false);
1879
+ if (failed) {
1880
+ return h(P.View, { style: P.style({ ...el.style, display: "flex", alignItems: "center", justifyContent: "center", padding: 8 }, "box") }, h(P.Text, { style: P.style({ color: "#888", fontSize: 12, textAlign: "center" }, "text") }, el.alt));
1881
+ }
1882
+ return h(P.Image, { el, onError: () => setFailed(true) });
1883
+ }
1884
+ // The last line of defence: anything that throws while drawing shows the widget's
1885
+ // text instead of taking the conversation down with it.
1886
+ class Boundary extends React.Component {
1887
+ state = { failed: false };
1888
+ static getDerivedStateFromError() {
1889
+ return { failed: true };
1890
+ }
1891
+ componentDidCatch() { }
1892
+ componentDidUpdate(prev) {
1893
+ // A new render (the preview grew, or became final) gets a fresh chance to draw.
1894
+ if (this.state.failed && prev.render !== this.props.render)
1895
+ this.setState({ failed: false });
1896
+ }
1897
+ render() {
1898
+ const p = this.props;
1899
+ if (this.state.failed)
1900
+ return fallbackEl(p.render.fallback, resolveWidgetTheme(p.theme));
1901
+ return h(Inner, p);
1902
+ }
1903
+ }
1904
+ return function OberikWidget(props) {
1905
+ // Keyed by the call that made it, not the render id: a preview and the finished widget
1906
+ // are one card, and remounting between them would replay every entrance.
1907
+ return h(Boundary, { ...props, key: props.render.call_id ?? props.render.id });
1908
+ };
1909
+ }
1910
+ const UNITLESS = new Set(["flex", "flexGrow", "flexShrink", "opacity", "fontWeight", "zIndex", "aspectRatio"]);
1911
+ function webStyle(s, k) {
1912
+ const out = {};
1913
+ // React Native's border widths default to 0; CSS's default to `medium`. A layout that
1914
+ // sets only `borderTopWidth` (a divider between rows) draws all four sides on the web
1915
+ // unless the rest are zeroed — first, so the per-side width written after it wins.
1916
+ if (s.borderStyle && s.borderWidth === undefined)
1917
+ out.borderWidth = 0;
1918
+ for (const [key, v] of Object.entries(s)) {
1919
+ if (v === undefined)
1920
+ continue;
1921
+ switch (key) {
1922
+ case "paddingVertical":
1923
+ out.paddingTop = v;
1924
+ out.paddingBottom = v;
1925
+ break;
1926
+ case "paddingHorizontal":
1927
+ out.paddingLeft = v;
1928
+ out.paddingRight = v;
1929
+ break;
1930
+ case "marginVertical":
1931
+ out.marginTop = v;
1932
+ out.marginBottom = v;
1933
+ break;
1934
+ case "lineHeight":
1935
+ out.lineHeight = typeof v === "number" ? `${v}px` : v;
1936
+ break;
1937
+ case "shadowColor":
1938
+ case "shadowOpacity":
1939
+ case "shadowRadius":
1940
+ case "shadowOffset":
1941
+ break;
1942
+ default:
1943
+ out[key] = v;
1944
+ }
1945
+ }
1946
+ if (s.shadowOpacity)
1947
+ out.boxShadow = `0 1px ${s.shadowRadius ?? 2}px rgba(0,0,0,${s.shadowOpacity})`;
1948
+ if (k === "box") {
1949
+ out.boxSizing = "border-box";
1950
+ out.minWidth = out.minWidth ?? 0;
1951
+ }
1952
+ if (k === "text") {
1953
+ out.margin = 0;
1954
+ out.overflowWrap = "anywhere";
1955
+ }
1956
+ return out;
1957
+ }
1958
+ /** The web's primitives: DOM elements with inline styles. The default. */
1959
+ function webPlatform(React) {
1960
+ const h = React.createElement;
1961
+ const aria = (a) => a
1962
+ ? {
1963
+ role: a.role,
1964
+ "aria-label": a.label,
1965
+ "aria-checked": a.checked,
1966
+ "aria-selected": a.selected,
1967
+ "aria-disabled": a.disabled,
1968
+ "aria-valuetext": a.value,
1969
+ }
1970
+ : {};
1971
+ return {
1972
+ name: "web",
1973
+ style: webStyle,
1974
+ View: ({ style, a11y, children }) => h("div", { style, ...aria(a11y) }, children),
1975
+ Text: ({ style, numberOfLines, children }) => h("div", {
1976
+ style: numberOfLines
1977
+ ? { ...style, display: "-webkit-box", WebkitLineClamp: numberOfLines, WebkitBoxOrient: "vertical", overflow: "hidden" }
1978
+ : style,
1979
+ }, children),
1980
+ Pressable: function WebPressable({ style, hoverStyle, onPress, a11y, children }) {
1981
+ const [hover, setHover] = React.useState(false);
1982
+ return h("div", {
1983
+ style: { ...style, ...(hover && hoverStyle ? hoverStyle : {}), userSelect: "none", outline: "none" },
1984
+ tabIndex: a11y?.disabled ? -1 : 0,
1985
+ ...aria(a11y),
1986
+ role: a11y?.role ?? "button",
1987
+ onClick: onPress,
1988
+ onKeyDown: (e) => {
1989
+ if (e.key === "Enter" || e.key === " ") {
1990
+ e.preventDefault();
1991
+ onPress();
1992
+ }
1993
+ },
1994
+ onMouseEnter: () => setHover(true),
1995
+ onMouseLeave: () => setHover(false),
1996
+ }, children);
1997
+ },
1998
+ Image: ({ el, onError }) => h("img", { src: el.src, alt: el.alt, onError, loading: "lazy", style: { ...webStyle(el.style, "image"), objectFit: el.fit, display: "block" } }),
1999
+ TextInput: ({ el }) => {
2000
+ const kind = el.kind === "multiline" ? null : el.kind === "number" ? "number" : el.kind === "email" ? "email" : el.kind === "tel" ? "tel" : el.kind === "date" ? "date" : "text";
2001
+ const common = {
2002
+ value: el.value,
2003
+ placeholder: el.placeholder,
2004
+ disabled: el.disabled,
2005
+ "aria-label": el.label,
2006
+ onChange: (e) => el.change(e.target.value),
2007
+ style: { ...webStyle(el.style, "field"), outline: "none", width: "100%", boxSizing: "border-box", resize: "vertical", font: "inherit", fontSize: el.style.fontSize },
2008
+ };
2009
+ return kind === null ? h("textarea", { ...common, rows: 3 }) : h("input", { ...common, type: kind });
2010
+ },
2011
+ Slider: (el) => h("input", {
2012
+ type: "range",
2013
+ min: el.min,
2014
+ max: el.max,
2015
+ step: el.step,
2016
+ value: el.value,
2017
+ disabled: el.disabled,
2018
+ "aria-label": el.label,
2019
+ onChange: (e) => el.change(Number(e.target.value)),
2020
+ style: { width: "100%", accentColor: el.fill, margin: 0, height: 24, cursor: el.disabled ? "default" : "pointer" },
2021
+ }),
2022
+ Chart: (props) => webChart(React, props),
2023
+ openURL: undefined,
2024
+ };
2025
+ }
2026
+ function webChart(React, { geo, theme, style }) {
2027
+ const h = React.createElement;
2028
+ const t = theme;
2029
+ const gutter = 44;
2030
+ const bottom = 20;
2031
+ const plotH = geo.height - bottom;
2032
+ const Y = (v) => (1 - v) * 1000;
2033
+ const shapes = [];
2034
+ geo.yTicks.forEach((tick, i) => shapes.push(h("line", { key: `g${i}`, x1: 0, x2: 1000, y1: Y(tick.y), y2: Y(tick.y), stroke: t.c.border, strokeWidth: 1, vectorEffect: "non-scaling-stroke", strokeDasharray: tick.y === geo.zero ? undefined : "3 3" })));
2035
+ if (geo.active !== undefined) {
2036
+ const x = geo.slots[geo.active] * 1000;
2037
+ shapes.push(h("line", { key: "cursor", x1: x, x2: x, y1: 0, y2: 1000, stroke: t.c.faint, strokeWidth: 1, vectorEffect: "non-scaling-stroke" }));
2038
+ }
2039
+ geo.series.forEach((s, si) => {
2040
+ if (geo.kind === "bar") {
2041
+ s.bars.forEach((b, bi) => shapes.push(h("rect", { key: `b${si}.${bi}`, x: b.x * 1000, width: b.w * 1000, y: Y(b.y1), height: Math.max(1, (b.y1 - b.y0) * 1000), fill: s.color, rx: 0 })));
2042
+ return;
2043
+ }
2044
+ const segs = segments(s.points);
2045
+ segs.forEach((seg, gi) => {
2046
+ const d = seg.map((p, i) => `${i ? "L" : "M"}${p.x * 1000},${Y(p.y)}`).join(" ");
2047
+ if (geo.kind === "area") {
2048
+ const area = `${d} L${seg[seg.length - 1].x * 1000},${Y(geo.zero)} L${seg[0].x * 1000},${Y(geo.zero)} Z`;
2049
+ shapes.push(h("path", { key: `a${si}.${gi}`, d: area, fill: s.color, fillOpacity: 0.16, stroke: "none" }));
2050
+ }
2051
+ shapes.push(h("path", { key: `l${si}.${gi}`, d, fill: "none", stroke: s.color, strokeWidth: 2, vectorEffect: "non-scaling-stroke", strokeLinejoin: "round", strokeLinecap: "round" }));
2052
+ });
2053
+ });
2054
+ const dots = geo.kind !== "bar" && geo.active !== undefined
2055
+ ? geo.series.map((s, si) => {
2056
+ const p = s.points[geo.active];
2057
+ if (!p)
2058
+ return null;
2059
+ return h("div", { key: `d${si}`, style: { position: "absolute", left: `calc(${p.x * 100}% - 4px)`, top: (1 - p.y) * plotH - 4, width: 8, height: 8, borderRadius: 4, background: s.color, border: `2px solid ${t.c.background}`, boxSizing: "content-box", pointerEvents: "none" } });
2060
+ })
2061
+ : [];
2062
+ const n = geo.slots.length;
2063
+ const hits = geo.slots.map((x, i) => {
2064
+ const left = i === 0 ? 0 : (geo.slots[i - 1] + x) / 2;
2065
+ const right = i === n - 1 ? 1 : (x + geo.slots[i + 1]) / 2;
2066
+ return h("div", {
2067
+ key: `h${i}`,
2068
+ onMouseEnter: () => geo.select?.(i),
2069
+ onClick: () => geo.select?.(geo.active === i ? undefined : i),
2070
+ style: { position: "absolute", top: 0, bottom: 0, left: `${left * 100}%`, width: `${(right - left) * 100}%`, cursor: "crosshair" },
2071
+ });
2072
+ });
2073
+ return h("div", { style: { ...webStyle(style, "chart"), display: "flex", flexDirection: "row", position: "relative" }, onMouseLeave: () => geo.select?.(undefined) }, h("div", { style: { width: gutter, height: plotH, position: "relative", flexShrink: 0 } }, geo.yTicks.map((tick, i) => h("div", { key: i, style: { position: "absolute", right: 6, top: (1 - tick.y) * plotH - 7, fontSize: 10, lineHeight: "14px", color: t.c.faint, fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap" } }, tick.label))), h("div", { style: { flexGrow: 1, position: "relative", minWidth: 0 } }, h("svg", { width: "100%", height: plotH, viewBox: "0 0 1000 1000", preserveAspectRatio: "none", style: { display: "block", overflow: "visible" } }, ...shapes), ...dots, ...hits, h("div", { style: { position: "relative", height: bottom } }, geo.xLabels.map((l, i) => h("div", { key: i, style: { position: "absolute", top: 4, left: `${l.x * 100}%`, transform: "translateX(-50%)", fontSize: 10, color: t.c.faint, whiteSpace: "nowrap", maxWidth: 80, overflow: "hidden", textOverflow: "ellipsis" } }, l.label)))));
2074
+ }
2075
+ function segments(points) {
2076
+ const out = [];
2077
+ let cur = [];
2078
+ for (const p of points) {
2079
+ if (p)
2080
+ cur.push(p);
2081
+ else if (cur.length) {
2082
+ out.push(cur);
2083
+ cur = [];
2084
+ }
2085
+ }
2086
+ if (cur.length)
2087
+ out.push(cur);
2088
+ return out.filter((s) => s.length > 0);
2089
+ }
2090
+ /**
2091
+ * React Native's primitives.
2092
+ *
2093
+ * import * as RN from "react-native";
2094
+ * import Svg, { Path, Rect, Line } from "react-native-svg"; // optional
2095
+ * const OberikWidget = createWidgetComponent(React, nativePlatform(React, RN, { Svg, Path, Rect, Line }));
2096
+ *
2097
+ * Without react-native-svg, bar charts are drawn with views and look the same; line and
2098
+ * area charts are drawn as connected segments.
2099
+ */
2100
+ function nativePlatform(React, RN, svg) {
2101
+ const h = React.createElement;
2102
+ const nativeStyle = (s, k) => {
2103
+ const out = {};
2104
+ for (const [key, v] of Object.entries(s)) {
2105
+ if (v === undefined || key === "cursor")
2106
+ continue;
2107
+ // A CSS font stack means nothing to React Native; the system font is the right default.
2108
+ if (key === "fontFamily" && typeof v === "string" && v.includes(","))
2109
+ continue;
2110
+ out[key] = v;
2111
+ }
2112
+ if (k === "text")
2113
+ delete out.display;
2114
+ return out;
2115
+ };
2116
+ const a11y = (a) => a
2117
+ ? {
2118
+ accessibilityRole: a.role === "switch" ? "switch" : a.role === "radio" ? "radio" : a.role === "link" ? "link" : a.role === "tab" ? "tab" : a.role === "img" ? "image" : a.role === "progressbar" ? "progressbar" : a.role === "button" ? "button" : undefined,
2119
+ accessibilityLabel: a.label,
2120
+ accessibilityState: { checked: a.checked, selected: a.selected, disabled: a.disabled },
2121
+ accessibilityValue: a.value ? { text: a.value } : undefined,
2122
+ }
2123
+ : {};
2124
+ const Slider = (el) => {
2125
+ const [width, setWidth] = React.useState(0);
2126
+ const frac = el.max === el.min ? 0 : (el.value - el.min) / (el.max - el.min);
2127
+ const at = (x) => el.change(el.min + Math.max(0, Math.min(1, x / Math.max(1, width))) * (el.max - el.min));
2128
+ const handlers = el.disabled
2129
+ ? {}
2130
+ : {
2131
+ onStartShouldSetResponder: () => true,
2132
+ onMoveShouldSetResponder: () => true,
2133
+ onResponderTerminationRequest: () => false,
2134
+ onResponderGrant: (e) => at(e.nativeEvent.locationX),
2135
+ onResponderMove: (e) => at(e.nativeEvent.locationX),
2136
+ };
2137
+ return h(RN.View, {
2138
+ style: { height: 28, justifyContent: "center" },
2139
+ onLayout: (e) => setWidth(e.nativeEvent.layout.width),
2140
+ accessibilityRole: "adjustable",
2141
+ accessibilityLabel: el.label,
2142
+ accessibilityValue: { min: el.min, max: el.max, now: el.value },
2143
+ onAccessibilityAction: (e) => el.change(el.value + (e.nativeEvent.actionName === "increment" ? el.step : -el.step)),
2144
+ accessibilityActions: [{ name: "increment" }, { name: "decrement" }],
2145
+ ...handlers,
2146
+ }, h(RN.View, { pointerEvents: "none", style: { height: 4, borderRadius: 2, backgroundColor: el.track } }, h(RN.View, { style: { height: 4, borderRadius: 2, width: `${frac * 100}%`, backgroundColor: el.fill } })), h(RN.View, { pointerEvents: "none", style: { position: "absolute", left: Math.max(0, frac * width - 10), width: 20, height: 20, borderRadius: 10, backgroundColor: el.thumb, borderWidth: 2, borderColor: el.fill, opacity: el.disabled ? 0.6 : 1 } }));
2147
+ };
2148
+ const Chart = ({ geo, theme, style }) => nativeChart(React, RN, svg, geo, theme, style);
2149
+ return {
2150
+ name: "native",
2151
+ style: nativeStyle,
2152
+ View: ({ style, a11y: a, children }) => h(RN.View, { style, ...a11y(a) }, children),
2153
+ Text: ({ style, numberOfLines, children }) => h(RN.Text, { style, numberOfLines }, children),
2154
+ Pressable: ({ style, onPress, a11y: a, children }) => h(RN.Pressable, { onPress, disabled: a?.disabled, style: ({ pressed }) => [style, pressed ? { opacity: 0.7 } : null], ...a11y(a) }, children),
2155
+ Image: ({ el, onError }) => h(RN.Image, { source: { uri: el.src }, accessibilityLabel: el.alt, onError, resizeMode: el.fit, style: nativeStyle(el.style, "image") }),
2156
+ TextInput: ({ el }) => h(RN.TextInput, {
2157
+ value: el.value,
2158
+ onChangeText: el.change,
2159
+ placeholder: el.placeholder,
2160
+ placeholderTextColor: el.placeholderColor,
2161
+ editable: !el.disabled,
2162
+ multiline: el.kind === "multiline",
2163
+ keyboardType: el.kind === "number" ? "decimal-pad" : el.kind === "email" ? "email-address" : el.kind === "tel" ? "phone-pad" : "default",
2164
+ autoCapitalize: el.kind === "email" ? "none" : undefined,
2165
+ accessibilityLabel: el.label,
2166
+ style: { ...nativeStyle(el.style, "field"), textAlignVertical: el.kind === "multiline" ? "top" : undefined },
2167
+ }),
2168
+ Slider,
2169
+ Chart,
2170
+ openURL: RN.Linking ? (url) => void RN.Linking.openURL(url) : undefined,
2171
+ };
2172
+ }
2173
+ function nativeChart(React, RN, svg, geo, t, style) {
2174
+ const h = React.createElement;
2175
+ const [width, setWidth] = React.useState(0);
2176
+ const gutter = 44;
2177
+ const bottom = 20;
2178
+ const plotH = geo.height - bottom;
2179
+ const plotW = Math.max(0, width - gutter);
2180
+ const X = (x) => x * plotW;
2181
+ const Y = (y) => (1 - y) * plotH;
2182
+ const layers = [];
2183
+ geo.yTicks.forEach((tick, i) => layers.push(h(RN.View, { key: `g${i}`, style: { position: "absolute", left: 0, right: 0, top: Y(tick.y), height: 1, backgroundColor: t.c.border, opacity: tick.y === geo.zero ? 1 : 0.6 } })));
2184
+ if (svg && plotW > 0) {
2185
+ const shapes = [];
2186
+ geo.series.forEach((s, si) => {
2187
+ if (geo.kind === "bar") {
2188
+ s.bars.forEach((b, bi) => shapes.push(h(svg.Rect, { key: `b${si}.${bi}`, x: X(b.x), width: X(b.w), y: Y(b.y1), height: Math.max(1, (b.y1 - b.y0) * plotH), fill: s.color })));
2189
+ return;
2190
+ }
2191
+ segments(s.points).forEach((seg, gi) => {
2192
+ const d = seg.map((p, i) => `${i ? "L" : "M"}${X(p.x)},${Y(p.y)}`).join(" ");
2193
+ if (geo.kind === "area") {
2194
+ shapes.push(h(svg.Path, { key: `a${si}.${gi}`, d: `${d} L${X(seg[seg.length - 1].x)},${Y(geo.zero)} L${X(seg[0].x)},${Y(geo.zero)} Z`, fill: s.color, fillOpacity: 0.16 }));
2195
+ }
2196
+ shapes.push(h(svg.Path, { key: `l${si}.${gi}`, d, fill: "none", stroke: s.color, strokeWidth: 2, strokeLinejoin: "round", strokeLinecap: "round" }));
2197
+ });
2198
+ });
2199
+ layers.push(h(svg.Svg, { key: "svg", width: plotW, height: plotH, style: { position: "absolute", left: 0, top: 0 } }, ...shapes));
2200
+ }
2201
+ else if (plotW > 0) {
2202
+ // Views only: bars are exact; lines become rotated segments.
2203
+ geo.series.forEach((s, si) => {
2204
+ if (geo.kind === "bar") {
2205
+ s.bars.forEach((b, bi) => layers.push(h(RN.View, { key: `b${si}.${bi}`, style: { position: "absolute", left: X(b.x), width: Math.max(1, X(b.w)), top: Y(b.y1), height: Math.max(1, (b.y1 - b.y0) * plotH), backgroundColor: s.color } })));
2206
+ return;
2207
+ }
2208
+ segments(s.points).forEach((seg, gi) => {
2209
+ for (let i = 1; i < seg.length; i++) {
2210
+ const x1 = X(seg[i - 1].x), y1 = Y(seg[i - 1].y), x2 = X(seg[i].x), y2 = Y(seg[i].y);
2211
+ const len = Math.hypot(x2 - x1, y2 - y1);
2212
+ const angle = Math.atan2(y2 - y1, x2 - x1);
2213
+ layers.push(h(RN.View, { key: `s${si}.${gi}.${i}`, style: { position: "absolute", left: (x1 + x2) / 2 - len / 2, top: (y1 + y2) / 2 - 1, width: len, height: 2, borderRadius: 1, backgroundColor: s.color, transform: [{ rotate: `${angle}rad` }] } }));
2214
+ }
2215
+ });
2216
+ });
2217
+ }
2218
+ if (geo.active !== undefined && plotW > 0) {
2219
+ layers.push(h(RN.View, { key: "cursor", style: { position: "absolute", top: 0, bottom: 0, left: X(geo.slots[geo.active]), width: 1, backgroundColor: t.c.faint } }));
2220
+ }
2221
+ const n = geo.slots.length;
2222
+ const hits = geo.slots.map((x, i) => {
2223
+ const left = i === 0 ? 0 : (geo.slots[i - 1] + x) / 2;
2224
+ const right = i === n - 1 ? 1 : (x + geo.slots[i + 1]) / 2;
2225
+ return h(RN.Pressable, { key: `h${i}`, onPress: () => geo.select?.(geo.active === i ? undefined : i), style: { position: "absolute", top: 0, bottom: 0, left: X(left), width: X(right - left) } });
2226
+ });
2227
+ return h(RN.View, { style: { ...style, flexDirection: "row" }, onLayout: (e) => setWidth(e.nativeEvent.layout.width) }, h(RN.View, { style: { width: gutter, height: plotH } }, geo.yTicks.map((tick, i) => h(RN.Text, { key: i, style: { position: "absolute", right: 6, top: Y(tick.y) - 7, fontSize: 10, color: t.c.faint } }, tick.label))), h(RN.View, { style: { flex: 1 } }, h(RN.View, { style: { height: plotH } }, ...layers, ...hits), h(RN.View, { style: { height: bottom } }, geo.xLabels.map((l, i) => h(RN.Text, { key: i, numberOfLines: 1, style: { position: "absolute", top: 4, left: X(l.x) - 30, width: 60, textAlign: "center", fontSize: 10, color: t.c.faint } }, l.label)))));
2228
+ }
2229
+ function mountWidget(target, render, opts = {}) {
2230
+ const doc = target.ownerDocument ?? globalThis.document;
2231
+ if (!doc)
2232
+ throw new Error("mountWidget needs a DOM; use widgetToText on a server");
2233
+ let session = new WidgetSession(render, opts, !!opts.holdReplies);
2234
+ let theme = resolveWidgetTheme(opts.theme);
2235
+ let root = null;
2236
+ let unsubscribe = session.subscribe(paint);
2237
+ function paint() {
2238
+ const v = session.get();
2239
+ const tree = v.broken ? { k: "text", style: { color: theme.c.text, fontSize: 14 }, text: render.fallback } : layoutWidget(session, theme);
2240
+ root = patch(doc, target, root, tree, 0, root !== null);
2241
+ }
2242
+ paint();
2243
+ return {
2244
+ update(next, nextOpts = opts) {
2245
+ opts = nextOpts;
2246
+ theme = resolveWidgetTheme(opts.theme);
2247
+ if (next !== render) {
2248
+ render = next;
2249
+ unsubscribe();
2250
+ const prev = session;
2251
+ session = new WidgetSession(render, opts, !!opts.holdReplies);
2252
+ if (prev.render.call_id && prev.render.call_id === render.call_id)
2253
+ session.adopt(prev);
2254
+ unsubscribe = session.subscribe(paint);
2255
+ }
2256
+ else
2257
+ session.setOptions(opts, !!opts.holdReplies);
2258
+ paint();
2259
+ },
2260
+ destroy() {
2261
+ unsubscribe();
2262
+ if (root)
2263
+ target.removeChild(root);
2264
+ root = null;
2265
+ },
2266
+ };
2267
+ }
2268
+ const SVG_NS = "http://www.w3.org/2000/svg";
2269
+ /** Draw `el` into `parent`, reusing `existing` where its tag matches. */
2270
+ function patch(doc, parent, existing, el, depth = 0, animate = false) {
2271
+ const tag = el.k === "field" ? (el.kind === "multiline" ? "textarea" : "input") : el.k === "slider" ? "input" : el.k === "image" ? "img" : "div";
2272
+ let node = existing;
2273
+ if (!node || node.tagName?.toLowerCase() !== tag || node.__k !== el.k) {
2274
+ const fresh = doc.createElement(tag);
2275
+ fresh.__k = el.k;
2276
+ // A piece of the card arriving after it was first drawn — the widget is being written
2277
+ // — falls in rather than popping. Same entrance as the React host's.
2278
+ fresh.__enter = animate && depth === 1;
2279
+ if (node)
2280
+ parent.replaceChild(fresh, node);
2281
+ else
2282
+ parent.appendChild(fresh);
2283
+ node = fresh;
2284
+ }
2285
+ const setStyle = (s) => {
2286
+ node.removeAttribute("style");
2287
+ if (depth === 1) {
2288
+ s = { ...s, transition: "opacity 240ms ease, transform 280ms cubic-bezier(0.2, 0.8, 0.2, 1)" };
2289
+ if (node.__enter) {
2290
+ const settled = { opacity: s.opacity === undefined ? "" : String(s.opacity), transform: s.transform === undefined ? "" : String(s.transform) };
2291
+ s = { ...s, opacity: 0, transform: "translateY(6px)" };
2292
+ node.__enter = false;
2293
+ const raf = globalThis.requestAnimationFrame ?? ((f) => setTimeout(f, 16));
2294
+ raf(() => {
2295
+ node.style.opacity = settled.opacity;
2296
+ node.style.transform = settled.transform;
2297
+ });
2298
+ }
2299
+ }
2300
+ for (const [k, v] of Object.entries(s)) {
2301
+ if (v === undefined || v === null)
2302
+ continue;
2303
+ const cssKey = k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
2304
+ node.style.setProperty(cssKey.startsWith("webkit-") ? `-${cssKey}` : cssKey, typeof v === "number" && !UNITLESS.has(k) ? `${v}px` : String(v));
2305
+ }
2306
+ };
2307
+ switch (el.k) {
2308
+ case "text": {
2309
+ const s = webStyle(el.style, "text");
2310
+ if (el.lines)
2311
+ Object.assign(s, { display: "-webkit-box", WebkitLineClamp: el.lines, WebkitBoxOrient: "vertical", overflow: "hidden" });
2312
+ if (el.numeric)
2313
+ s.fontVariantNumeric = "tabular-nums";
2314
+ setStyle(s);
2315
+ if (node.textContent !== el.text)
2316
+ node.textContent = el.text;
2317
+ return node;
2318
+ }
2319
+ case "box": {
2320
+ setStyle(webStyle(el.style, "box"));
2321
+ setAria(node, el.a11y);
2322
+ if (el.press) {
2323
+ node.tabIndex = el.a11y?.disabled ? -1 : 0;
2324
+ if (!el.a11y?.role)
2325
+ node.setAttribute("role", "button");
2326
+ node.style.userSelect = "none";
2327
+ node.onclick = el.press;
2328
+ node.onkeydown = (e) => {
2329
+ if (e.key === "Enter" || e.key === " ") {
2330
+ e.preventDefault();
2331
+ el.press();
2332
+ }
2333
+ };
2334
+ }
2335
+ else {
2336
+ node.onclick = null;
2337
+ node.onkeydown = null;
2338
+ node.removeAttribute("tabindex");
2339
+ }
2340
+ const kids = Array.from(node.childNodes);
2341
+ el.children.forEach((c, i) => patch(doc, node, kids[i], c, depth + 1, animate));
2342
+ for (let i = kids.length - 1; i >= el.children.length; i--)
2343
+ node.removeChild(kids[i]);
2344
+ return node;
2345
+ }
2346
+ case "image": {
2347
+ setStyle({ ...webStyle(el.style, "image"), objectFit: el.fit, display: "block" });
2348
+ if (node.getAttribute("src") !== el.src)
2349
+ node.setAttribute("src", el.src);
2350
+ node.setAttribute("alt", el.alt);
2351
+ node.onerror = () => {
2352
+ const box = doc.createElement("div");
2353
+ box.textContent = el.alt;
2354
+ box.setAttribute("style", "display:flex;align-items:center;justify-content:center;padding:8px;font-size:12px;color:#888;text-align:center");
2355
+ node.replaceWith?.(box);
2356
+ };
2357
+ return node;
2358
+ }
2359
+ case "slider": {
2360
+ node.type = "range";
2361
+ node.min = String(el.min);
2362
+ node.max = String(el.max);
2363
+ node.step = String(el.step);
2364
+ if (Number(node.value) !== el.value)
2365
+ node.value = String(el.value);
2366
+ node.disabled = el.disabled;
2367
+ node.setAttribute("aria-label", el.label);
2368
+ node.oninput = (e) => el.change(Number(e.target.value));
2369
+ setStyle({ width: "100%", accentColor: el.fill, margin: 0, height: 24 });
2370
+ return node;
2371
+ }
2372
+ case "field": {
2373
+ if (tag === "input")
2374
+ node.type = el.kind === "number" ? "number" : el.kind === "email" ? "email" : el.kind === "tel" ? "tel" : el.kind === "date" ? "date" : "text";
2375
+ else
2376
+ node.rows = 3;
2377
+ if (node.value !== el.value)
2378
+ node.value = el.value;
2379
+ node.placeholder = el.placeholder;
2380
+ node.disabled = el.disabled;
2381
+ node.setAttribute("aria-label", el.label);
2382
+ node.oninput = (e) => el.change(e.target.value);
2383
+ setStyle({ ...webStyle(el.style, "field"), outline: "none", width: "100%", boxSizing: "border-box", font: "inherit", fontSize: el.style.fontSize });
2384
+ return node;
2385
+ }
2386
+ case "chart": {
2387
+ setStyle({ ...webStyle(el.style, "chart"), position: "relative" });
2388
+ node.innerHTML = "";
2389
+ node.appendChild(domChart(doc, el.chart, el.theme));
2390
+ return node;
2391
+ }
2392
+ }
2393
+ }
2394
+ function setAria(node, a) {
2395
+ for (const attr of ["role", "aria-label", "aria-checked", "aria-selected", "aria-disabled", "aria-valuetext"])
2396
+ node.removeAttribute(attr);
2397
+ if (!a)
2398
+ return;
2399
+ if (a.role)
2400
+ node.setAttribute("role", a.role);
2401
+ if (a.label)
2402
+ node.setAttribute("aria-label", a.label);
2403
+ if (a.checked !== undefined)
2404
+ node.setAttribute("aria-checked", String(a.checked));
2405
+ if (a.selected !== undefined)
2406
+ node.setAttribute("aria-selected", String(a.selected));
2407
+ if (a.disabled)
2408
+ node.setAttribute("aria-disabled", "true");
2409
+ if (a.value)
2410
+ node.setAttribute("aria-valuetext", a.value);
2411
+ }
2412
+ function domChart(doc, geo, t) {
2413
+ const plotH = geo.height - 20;
2414
+ const wrap = doc.createElement("div");
2415
+ wrap.setAttribute("style", `display:flex;flex-direction:row;height:${geo.height}px;position:relative`);
2416
+ wrap.onmouseleave = () => geo.select?.(undefined);
2417
+ const gut = doc.createElement("div");
2418
+ gut.setAttribute("style", `width:44px;height:${plotH}px;position:relative;flex-shrink:0`);
2419
+ for (const tick of geo.yTicks) {
2420
+ const l = doc.createElement("div");
2421
+ l.textContent = tick.label;
2422
+ l.setAttribute("style", `position:absolute;right:6px;top:${(1 - tick.y) * plotH - 7}px;font-size:10px;line-height:14px;color:${t.c.faint};white-space:nowrap;font-variant-numeric:tabular-nums`);
2423
+ gut.appendChild(l);
2424
+ }
2425
+ wrap.appendChild(gut);
2426
+ const plot = doc.createElement("div");
2427
+ plot.setAttribute("style", "flex-grow:1;position:relative;min-width:0");
2428
+ const svg = doc.createElementNS(SVG_NS, "svg");
2429
+ svg.setAttribute("width", "100%");
2430
+ svg.setAttribute("height", String(plotH));
2431
+ svg.setAttribute("viewBox", "0 0 1000 1000");
2432
+ svg.setAttribute("preserveAspectRatio", "none");
2433
+ svg.setAttribute("style", "display:block;overflow:visible");
2434
+ const Y = (v) => (1 - v) * 1000;
2435
+ const add = (tag, attrs) => {
2436
+ const e = doc.createElementNS(SVG_NS, tag);
2437
+ for (const [k, v] of Object.entries(attrs))
2438
+ e.setAttribute(k, String(v));
2439
+ svg.appendChild(e);
2440
+ };
2441
+ for (const tick of geo.yTicks) {
2442
+ add("line", { x1: 0, x2: 1000, y1: Y(tick.y), y2: Y(tick.y), stroke: t.c.border, "stroke-width": 1, "vector-effect": "non-scaling-stroke", ...(tick.y === geo.zero ? {} : { "stroke-dasharray": "3 3" }) });
2443
+ }
2444
+ if (geo.active !== undefined) {
2445
+ const x = geo.slots[geo.active] * 1000;
2446
+ add("line", { x1: x, x2: x, y1: 0, y2: 1000, stroke: t.c.faint, "stroke-width": 1, "vector-effect": "non-scaling-stroke" });
2447
+ }
2448
+ for (const s of geo.series) {
2449
+ if (geo.kind === "bar") {
2450
+ for (const b of s.bars)
2451
+ add("rect", { x: b.x * 1000, width: b.w * 1000, y: Y(b.y1), height: Math.max(1, (b.y1 - b.y0) * 1000), fill: s.color });
2452
+ continue;
2453
+ }
2454
+ for (const seg of segments(s.points)) {
2455
+ const d = seg.map((p, i) => `${i ? "L" : "M"}${p.x * 1000},${Y(p.y)}`).join(" ");
2456
+ if (geo.kind === "area")
2457
+ add("path", { d: `${d} L${seg[seg.length - 1].x * 1000},${Y(geo.zero)} L${seg[0].x * 1000},${Y(geo.zero)} Z`, fill: s.color, "fill-opacity": 0.16 });
2458
+ add("path", { d, fill: "none", stroke: s.color, "stroke-width": 2, "vector-effect": "non-scaling-stroke", "stroke-linejoin": "round" });
2459
+ }
2460
+ }
2461
+ plot.appendChild(svg);
2462
+ const n = geo.slots.length;
2463
+ geo.slots.forEach((x, i) => {
2464
+ const left = i === 0 ? 0 : (geo.slots[i - 1] + x) / 2;
2465
+ const right = i === n - 1 ? 1 : (x + geo.slots[i + 1]) / 2;
2466
+ const hit = doc.createElement("div");
2467
+ hit.setAttribute("style", `position:absolute;top:0;height:${plotH}px;left:${left * 100}%;width:${(right - left) * 100}%;cursor:crosshair`);
2468
+ hit.onmouseenter = () => geo.select?.(i);
2469
+ hit.onclick = () => geo.select?.(geo.active === i ? undefined : i);
2470
+ plot.appendChild(hit);
2471
+ });
2472
+ const axis = doc.createElement("div");
2473
+ axis.setAttribute("style", "position:relative;height:20px");
2474
+ for (const l of geo.xLabels) {
2475
+ const e = doc.createElement("div");
2476
+ e.textContent = l.label;
2477
+ e.setAttribute("style", `position:absolute;top:4px;left:${l.x * 100}%;transform:translateX(-50%);font-size:10px;color:${t.c.faint};white-space:nowrap`);
2478
+ axis.appendChild(e);
2479
+ }
2480
+ plot.appendChild(axis);
2481
+ wrap.appendChild(plot);
2482
+ return wrap;
2483
+ }
2484
+ /**
2485
+ * `<oberik-widget>` — a custom element for any framework that speaks HTML.
2486
+ *
2487
+ * defineWidgetElement();
2488
+ * el.render = widgetRender; // a WidgetRender from the stream
2489
+ * el.addEventListener("widget-reply", (e) => send(e.detail.press));
2490
+ *
2491
+ * Also fires `widget-link` and `widget-set`. Set `el.theme` to restyle it.
2492
+ */
2493
+ function defineWidgetElement(tag = "oberik-widget") {
2494
+ const g = globalThis;
2495
+ if (!g.customElements || g.customElements.get(tag))
2496
+ return;
2497
+ class OberikWidgetElement extends g.HTMLElement {
2498
+ mounted = null;
2499
+ _render = null;
2500
+ _theme;
2501
+ _holdReplies = false;
2502
+ set render(v) {
2503
+ this._render = v;
2504
+ this.sync();
2505
+ }
2506
+ get render() {
2507
+ return this._render;
2508
+ }
2509
+ set theme(v) {
2510
+ this._theme = v;
2511
+ this.sync();
2512
+ }
2513
+ set holdReplies(v) {
2514
+ this._holdReplies = !!v;
2515
+ this.sync();
2516
+ }
2517
+ connectedCallback() {
2518
+ this.sync();
2519
+ }
2520
+ disconnectedCallback() {
2521
+ this.mounted?.destroy();
2522
+ this.mounted = null;
2523
+ }
2524
+ sync() {
2525
+ if (!this._render || !this.isConnected)
2526
+ return;
2527
+ const opts = {
2528
+ theme: this._theme,
2529
+ holdReplies: this._holdReplies,
2530
+ onReply: (press, text) => this.dispatchEvent(new g.CustomEvent("widget-reply", { detail: { press, text }, bubbles: true })),
2531
+ onLink: (url) => {
2532
+ const ok = this.dispatchEvent(new g.CustomEvent("widget-link", { detail: { url }, bubbles: true, cancelable: true }));
2533
+ if (ok)
2534
+ g.open?.(url, "_blank", "noopener,noreferrer");
2535
+ },
2536
+ };
2537
+ if (this.mounted)
2538
+ this.mounted.update(this._render, opts);
2539
+ else
2540
+ this.mounted = mountWidget(this, this._render, opts);
2541
+ }
2542
+ }
2543
+ g.customElements.define(tag, OberikWidgetElement);
2544
+ }
2545
+ //# sourceMappingURL=widgets.js.map