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