-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisual_state_resolver.ts
More file actions
686 lines (642 loc) · 24.2 KB
/
Copy pathvisual_state_resolver.ts
File metadata and controls
686 lines (642 loc) · 24.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
// visual_state_resolver.ts
//
// Pure resolver for object visual_states. Maps an object's current state plus
// its authored visual_states map plus the active protocol's material registry
// into a renderable description. This file has NO DOM and NO Solid; it is a
// pure function consumed by the Solid scene components.
//
// The resolver implements the runtime formula tokens that authored objects
// actually use after generation (see
// docs/archive/audits/formula_scene_op_inventory.md):
// - label(state(<field>), format="<string with {value}>")
// - conditional(state(<field>), <then-expr>, <else-expr>)
// - compose(<token>, <token>, ...) (zero authored uses today; implemented,
// not silently no-opped)
// Source fill_height formulas are compiler inputs and must arrive here as
// render_effect declarations; they never become whole-object overlays.
// Unknown formula tokens fail loud.
import type {
ObjectVisualStates,
RenderEffect,
RenderEffectTarget,
VisualStateCase,
VisualStateOutput,
} from "../layout/types.js";
import { resolve_color_result } from "./material_color.js";
//============================================
// Public input and output types
//============================================
// Current object state: flat map of field_name -> primitive value.
export type ObjectState = Record<string, string | number | boolean>;
// One material entry from a protocol's materials.yaml. display_color is a
// single scalar hex string (^#[0-9a-f]{6}$); this project targets light
// scientific workspaces only, so there is no light/dark theme branch.
export interface MaterialEntry {
label: string;
display_color: string;
}
// Per-protocol material registry. Each protocol package carries its own
// materials.yaml; this registry is passed in per protocol, never global.
export type MaterialRegistry = Record<string, MaterialEntry>;
// A text overlay produced by label(...) or by a conditional resolving to text.
export interface TextOverlay {
type: "text";
field_name: string;
text: string;
}
// A material effect authored against anchors in the base SVG. It is rendered
// inside the injected, namespaced SVG so the liquid stays within the
// instrument's declared vessel geometry.
export interface AnchorMaterialEffect {
type: "anchor_material";
field_name: string;
render_effect: RenderEffect;
target: RenderEffectTarget;
clip?: RenderEffectTarget;
fill_percent: number;
material_name: string;
color: string | null;
}
// Resolved, renderable description of one object instance.
export interface ResolvedVisualState {
// Base SVG asset selected by the object's enum/bool svg visual_state, or
// null when the object declares no svg case map.
asset_name: string | null;
// Transparent full-frame SVG layers selected by composite visual states.
// They are rendered over asset_name in authored order.
asset_layers: string[];
// Ordered text overlays to composite over the asset.
overlays: TextOverlay[];
// Declarative object-level material effects, kept inside their compiled SVG
// regions rather than painted over the owning item's box.
anchor_material_effects: AnchorMaterialEffect[];
// Convenience: the first text overlay's text, when present.
label_text?: string;
// Flat string attributes for the DOM node (data-* in the renderer layer).
data_attrs: Record<string, string>;
}
//============================================
// Material-name state fields
//============================================
// Material-name state fields recognized on objects and tools.
const MATERIAL_FIELDS: readonly string[] = ["material_name", "held_material_name"];
//============================================
// Formula token parsing
//============================================
// A parsed formula expression. The mini-language is small enough that a hand
// written recursive parser is clearer than a grammar framework.
type FormulaExpr =
| { token: "state"; field_name: string }
| { token: "string"; value: string }
| { token: "label"; field_name: string; format: string }
| { token: "conditional"; cond: FormulaExpr; then_expr: FormulaExpr; else_expr: FormulaExpr }
| { token: "compose"; parts: FormulaExpr[] };
// Split a comma-separated argument list at the top level only, respecting
// nested parentheses and double-quoted strings.
function split_top_level_args(inner: string): string[] {
const args: string[] = [];
let depth = 0;
let in_string = false;
let current = "";
for (let i = 0; i < inner.length; i++) {
const ch = inner[i];
if (in_string) {
current += ch;
if (ch === '"') {
in_string = false;
}
continue;
}
if (ch === '"') {
in_string = true;
current += ch;
continue;
}
if (ch === "(") {
depth++;
current += ch;
continue;
}
if (ch === ")") {
depth--;
current += ch;
continue;
}
if (ch === "," && depth === 0) {
args.push(current.trim());
current = "";
continue;
}
current += ch;
}
if (current.trim().length > 0) {
args.push(current.trim());
}
return args;
}
// Parse a double-quoted string literal token into its contents.
function parse_string_literal(text: string): string {
// text is expected to start and end with a double quote.
const inner = text.slice(1, -1);
return inner;
}
// Parse one formula expression string into a FormulaExpr. Fails loud on any
// unknown token, arity mismatch, or malformed argument.
function parse_formula_expr(text: string): FormulaExpr {
const trimmed = text.trim();
// String literal: "..."
if (trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length >= 2) {
return { token: "string", value: parse_string_literal(trimmed) };
}
// Function-call form: name(args)
const open = trimmed.indexOf("(");
if (open === -1 || !trimmed.endsWith(")")) {
throw new Error(`visual_state_resolver: malformed formula expression: ${text}`);
}
const name = trimmed.slice(0, open).trim();
const inner = trimmed.slice(open + 1, -1);
const args = split_top_level_args(inner);
// state(<field_name>)
if (name === "state") {
if (args.length !== 1) {
throw new Error(`visual_state_resolver: state(...) needs 1 arg: ${text}`);
}
return { token: "state", field_name: args[0]!.trim() };
}
// fill_height is accepted only at the source/compiler boundary. Seeing it
// here means generation failed to lower it to a render_effect declaration.
if (name === "fill_height") {
throw new Error(
`visual_state_resolver: fill_height must be compiler-lowered to render_effect: ${text}`,
);
}
// label(state(<field>), format="<string>")
if (name === "label") {
return parse_label(args, text);
}
// conditional(<cond>, <then>, <else>)
if (name === "conditional") {
if (args.length !== 3) {
throw new Error(`visual_state_resolver: conditional(...) needs 3 args: ${text}`);
}
return {
token: "conditional",
cond: parse_formula_expr(args[0]!),
then_expr: parse_formula_expr(args[1]!),
else_expr: parse_formula_expr(args[2]!),
};
}
// compose(<token>, <token>, ...)
if (name === "compose") {
if (args.length === 0) {
throw new Error(`visual_state_resolver: compose(...) needs >= 1 arg: ${text}`);
}
const parts = args.map((a) => parse_formula_expr(a));
return { token: "compose", parts };
}
throw new Error(`visual_state_resolver: unknown formula token '${name}': ${text}`);
}
// Parse the state(...) operand used by label.
function parse_state_operand(text: string): string {
const expr = parse_formula_expr(text);
if (expr.token !== "state") {
throw new Error(`visual_state_resolver: expected state(<field>), got: ${text}`);
}
return expr.field_name;
}
// Parse label(state(<field>), format="<string>").
function parse_label(args: string[], text: string): FormulaExpr {
if (args.length !== 2) {
throw new Error(`visual_state_resolver: label(...) needs 2 args: ${text}`);
}
const field_name = parse_state_operand(args[0]!);
const fmt_arg = args[1]!.trim();
const fmt_prefix = "format=";
if (!fmt_arg.startsWith(fmt_prefix)) {
throw new Error(`visual_state_resolver: label format must be 'format="..."': ${text}`);
}
const fmt_value = fmt_arg.slice(fmt_prefix.length).trim();
if (!(fmt_value.startsWith('"') && fmt_value.endsWith('"') && fmt_value.length >= 2)) {
throw new Error(`visual_state_resolver: label format must be a quoted string: ${text}`);
}
return { token: "label", field_name, format: parse_string_literal(fmt_value) };
}
//============================================
// Formula evaluation against current state
//============================================
// Read a declared state field. Missing fields fail loud (the field must exist
// because the formula names it and the schema declares it).
function read_state_field(state: ObjectState, field_name: string): string | number | boolean {
if (!(field_name in state)) {
throw new Error(
`visual_state_resolver: formula references undeclared state field '${field_name}'`,
);
}
return state[field_name]!;
}
// Truthiness for conditional(...). A numeric 0, false, empty string, and the
// `empty` sentinel are falsy; everything else is truthy.
function is_truthy(value: string | number | boolean): boolean {
if (typeof value === "boolean") {
return value;
}
if (typeof value === "number") {
return value !== 0;
}
// string
if (value.length === 0) {
return false;
}
if (value === "empty") {
return false;
}
return true;
}
// Format a value into a label string by substituting {value}.
function format_label(format: string, value: string | number | boolean): string {
// Convert the value to a string regardless of its type, then substitute.
const value_text = String(value);
const text = format.split("{value}").join(value_text);
return text;
}
// Evaluate a parsed formula into overlays appended to the accumulator.
// field_name is the visual_states key this formula belongs to (used for the
// overlay field_name tag).
function eval_formula(
expr: FormulaExpr,
field_name: string,
state: ObjectState,
overlays: TextOverlay[],
): void {
switch (expr.token) {
case "label": {
const raw = read_state_field(state, expr.field_name);
const text = format_label(expr.format, raw);
overlays.push({ type: "text", field_name, text });
return;
}
case "string": {
// A bare string literal renders as a static text overlay.
overlays.push({ type: "text", field_name, text: expr.value });
return;
}
case "conditional": {
const cond_value = eval_cond_operand(expr.cond, state);
const branch = is_truthy(cond_value) ? expr.then_expr : expr.else_expr;
eval_formula(branch, field_name, state, overlays);
return;
}
case "compose": {
// Compose has zero authored uses today but is implemented, not
// no-opped: each part contributes its overlays in order.
for (const part of expr.parts) {
eval_formula(part, field_name, state, overlays);
}
return;
}
case "state": {
// A bare state(...) as a render expression is not meaningful on its own;
// it must be wrapped by label/conditional. Fail loud.
throw new Error(
`visual_state_resolver: bare state(${expr.field_name}) is not a render expression`,
);
}
default: {
// Exhaustiveness guard. Unreachable given the union above.
const never: never = expr;
throw new Error(`visual_state_resolver: unhandled formula expr: ${JSON.stringify(never)}`);
}
}
}
// Evaluate the condition operand of a conditional into a comparable value.
function eval_cond_operand(expr: FormulaExpr, state: ObjectState): string | number | boolean {
if (expr.token === "state") {
return read_state_field(state, expr.field_name);
}
if (expr.token === "string") {
return expr.value;
}
throw new Error(
`visual_state_resolver: conditional condition must be state(...) or a string literal`,
);
}
//============================================
// Case (enum/bool) resolution for svg asset selection
//============================================
// Match a visual_state case 'when' against the current field value.
function case_matches(when: string | boolean, value: string | number | boolean): boolean {
if (typeof when === "boolean") {
return when === value;
}
// Authored 'when' is a string; the state value may be enum string.
return when === value;
}
// Select the svg asset_name from a case map for the field's current value.
function resolve_svg_asset(
field_name: string,
cases: VisualStateCase[],
state: ObjectState,
): string | null {
const value = read_state_field(state, field_name);
for (const c of cases) {
if (case_matches(c.when, value)) {
const output = c.output;
if ("asset_name" in output) {
return output.asset_name;
}
// svg case maps are expected to carry asset_name outputs.
throw new Error(`visual_state_resolver: svg case for '${field_name}' has no asset_name`);
}
}
// No matching case: fail loud so missing coverage is visible.
throw new Error(
`visual_state_resolver: no svg case matched '${field_name}' value '${String(value)}'`,
);
}
function resolve_case_output(
field_name: string,
cases: VisualStateCase[],
state: ObjectState,
): VisualStateOutput {
const value = read_state_field(state, field_name);
for (const entry of cases) {
if (case_matches(entry.when, value)) {
return entry.output;
}
}
throw new Error(
`visual_state_resolver: no composite case matched '${field_name}' value '${String(value)}'`,
);
}
function collect_asset_layers(output: VisualStateOutput, layers: string[]): void {
if ("asset_name" in output) {
layers.push(output.asset_name);
return;
}
if ("composite" in output) {
for (const part of output.composite) {
collect_asset_layers(part, layers);
}
return;
}
throw new Error("visual_state_resolver: overlay_name composites are not renderable asset layers");
}
//============================================
// Material color resolution
//============================================
// Read the object's current material name from the recognized material-name
// state fields. Returns null when the object declares no material field.
function read_material_name(state: ObjectState): string | null {
for (const f of MATERIAL_FIELDS) {
if (f in state) {
const v = state[f]!;
if (typeof v === "string") {
return v;
}
return null;
}
}
return null;
}
// Derive the corresponding material identity field from a declared driving
// field, not from an object name. The vocabulary supports material_volume,
// held_material_volume, volume_ml, held_volume_ul, and scoped fields such as
// inner_chamber_volume_ml. Each reduces to the same <prefix>material_name
// pairing convention. A declaration without its paired identity is invalid
// content and is deliberately loud rather than painted neutral gray.
function material_field_for_driver(field_name: string): string {
const without_unit = field_name.replace(/_(?:ml|ul)$/, "");
const without_volume = without_unit.endsWith("_volume")
? without_unit.slice(0, -"_volume".length)
: without_unit;
if (without_volume.length === 0 || without_volume === "material") {
return "material_name";
}
if (without_volume.endsWith("_material")) {
return `${without_volume}_name`;
}
return `${without_volume}_material_name`;
}
function material_field_for_effect(field_name: string): string {
return field_name.endsWith("material_name") ? field_name : material_field_for_driver(field_name);
}
function read_effect_material_name(
state: ObjectState,
field_name: string,
): { material_field: string; material_name: string } {
const material_field = material_field_for_effect(field_name);
const value = state[material_field];
if (typeof value !== "string") {
throw new Error(
`visual_state_resolver: render effect '${field_name}' has invalid material identity ` +
`in '${material_field}'; use a material-name string or 'empty'`,
);
}
return { material_field, material_name: value };
}
// An identity-only tint may accompany an amount field in the same generic
// naming family. It is not required (a structured well has no object-level
// volume), but when one is present, a zero amount must agree with the named
// absence value `empty`. Candidate order covers material_name -> material_volume,
// held_material_name -> held_material_volume, and scoped names such as
// inner_chamber_material_name -> inner_chamber_volume_ml without an
// object-specific branch.
function paired_volume_value(state: ObjectState, material_field_name: string): number | null {
const direct_base = material_field_name.replace(/_name$/, "");
const candidates = [`${direct_base}_volume`];
if (material_field_name.endsWith("_material_name")) {
const scoped_base = material_field_name.slice(0, -"_material_name".length);
candidates.push(
`${scoped_base}_volume`,
`${scoped_base}_volume_ml`,
`${scoped_base}_volume_ul`,
);
}
for (const candidate of candidates) {
const value = state[candidate];
if (typeof value === "number") {
return value;
}
}
return null;
}
function resolve_effect_color(
field_name: string,
state: ObjectState,
material_registry: MaterialRegistry | null,
): { material_field: string; material_name: string; color: string | null } {
const material = read_effect_material_name(state, field_name);
const { material_name } = material;
const result = resolve_color_result(material_name, material_registry);
if (!result.ok) {
throw new Error(`visual_state_resolver: ${result.reason}`);
}
return { ...material, color: result.color };
}
function resolve_anchor_effect(
field_name: string,
def: NonNullable<ObjectVisualStates[string]>,
state: ObjectState,
material_registry: MaterialRegistry | null,
): AnchorMaterialEffect {
if (def.render_effect === undefined || def.target === undefined) {
throw new Error(`visual_state_resolver: incomplete render effect '${field_name}'`);
}
const material = resolve_effect_color(field_name, state, material_registry);
let fill_percent = 100;
if (def.render_effect === "fill_height") {
const amount_value = state[field_name];
if (amount_value === undefined && material.material_name !== "empty") {
throw new Error(
`visual_state_resolver: non-empty material '${material.material_name}' requires ` +
`amount field '${field_name}' for fill_height`,
);
}
const value = read_state_field(state, field_name);
if (typeof value !== "number") {
throw new Error(`visual_state_resolver: fill_height field '${field_name}' is not numeric`);
}
if (value > 0 && material.material_name === "empty") {
throw new Error(
`visual_state_resolver: empty material has positive amount in '${field_name}'; ` +
`use a material name for a visible fill`,
);
}
const capacities = [def.capacity_ul, def.capacity_ml, def.capacity_mg].filter(
(capacity): capacity is number => capacity !== undefined,
);
const capacity = capacities[0];
if (
capacities.length !== 1 ||
capacity === undefined ||
!Number.isFinite(capacity) ||
capacity <= 0
) {
throw new Error(
`visual_state_resolver: fill_height render effect '${field_name}' needs ` +
"exactly one finite positive capacity",
);
}
fill_percent = Math.max(0, Math.min(100, (value / capacity) * 100));
} else {
const paired_volume = paired_volume_value(state, material.material_field);
if (paired_volume !== null && paired_volume === 0) {
fill_percent = 0;
}
}
const effect: AnchorMaterialEffect = {
type: "anchor_material",
field_name,
render_effect: def.render_effect,
target: def.target,
fill_percent,
material_name: material.material_name,
color: material.color,
};
if (def.clip !== undefined) {
effect.clip = def.clip;
}
return effect;
}
// Validate the object's current material name against the per-protocol
// registry. Delegates the name -> color check to the single color source in
// material_color.ts (see docs/specs/MATERIAL_CONVENTION.md): scalar
// display_color, built-in `mixed` gray, sentinel/empty null, no theme branch.
// The render path here is fail-loud: a ColorResult failure (a content defect,
// e.g. a non-sentinel material missing from a provided registry, or an invalid
// scalar color) is rethrown so the resolver surfaces it through the same loud
// channel as every other render defect, rather than being silently dropped.
function resolve_material_name(
state: ObjectState,
material_registry: MaterialRegistry | null,
): string | null {
const material_name = read_material_name(state);
const result = resolve_color_result(material_name, material_registry);
if (!result.ok) {
throw new Error(`visual_state_resolver: ${result.reason}`);
}
return material_name;
}
//============================================
// Public entry point
//============================================
// Resolve an object's visual state into a renderable description.
//
// object_visual_states: the object's authored visual_states map.
// state: the object's current flat state values.
// material_registry: the active protocol's materials.yaml registry, or null
// when there is no protocol material context (diagnostic
// scene-viewer render). A provided registry (even empty)
// is authoritative; null means "no color context".
export function resolve_visual_state(
object_visual_states: ObjectVisualStates,
state: ObjectState,
material_registry: MaterialRegistry | null,
): ResolvedVisualState {
let asset_name: string | null = null;
const asset_layers: string[] = [];
const overlays: TextOverlay[] = [];
const anchor_material_effects: AnchorMaterialEffect[] = [];
const data_attrs: Record<string, string> = {};
// Walk every authored visual_states entry, keyed by field_name.
for (const field_name of Object.keys(object_visual_states)) {
const def = object_visual_states[field_name]!;
if (def.render_effect !== undefined) {
anchor_material_effects.push(
resolve_anchor_effect(field_name, def, state, material_registry),
);
continue;
}
if (def.kind === "svg") {
// svg entries carry a case map selecting the base asset.
if (!def.cases) {
throw new Error(`visual_state_resolver: svg visual_state '${field_name}' has no cases`);
}
asset_name = resolve_svg_asset(field_name, def.cases, state);
continue;
}
if (def.kind === "composite" && def.cases) {
collect_asset_layers(resolve_case_output(field_name, def.cases, state), asset_layers);
continue;
}
// overlay and composite entries either carry a formula or an empty
// composite literal (composite: []), which contributes nothing.
if (def.formula) {
const expr = parse_formula_expr(def.formula);
eval_formula(expr, field_name, state, overlays);
continue;
}
// No formula and not svg: an empty composite (composite: []) is a valid
// no-op authored form. Anything else with no formula is also a no-op here.
}
// Resolve material color from the per-protocol registry.
const material_name = resolve_material_name(state, material_registry);
// Expose the resolved material name as a data attribute when present.
if (material_name !== null) {
data_attrs["data-material"] = material_name;
} else if (anchor_material_effects.length > 0) {
// Scoped declarative effects (e.g. inner_chamber_material_name) do not
// participate in the older object-global material field convention, but
// still expose their resolved identity for inspection and browser proof.
data_attrs["data-material"] = anchor_material_effects[0]!.material_name;
}
// Convenience: surface the first text overlay as label_text.
let label_text: string | undefined;
for (const o of overlays) {
if (o.type === "text") {
label_text = o.text;
break;
}
}
const result: ResolvedVisualState = {
asset_name,
asset_layers,
overlays,
anchor_material_effects,
data_attrs,
};
if (label_text !== undefined) {
result.label_text = label_text;
}
return result;
}