@nova-energy/openamx 0.12.0 → 0.14.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.
@@ -33,21 +33,97 @@ export function formatAmx(source) {
33
33
  lines.pop();
34
34
  if (lines.length === 0)
35
35
  return '';
36
- parseStatements(lines.join('\n'));
36
+ const statements = parseStatements(lines.join('\n'));
37
+ const diagramsByLine = new Map();
38
+ collectDiagramDeclarations(statements, diagramsByLine);
37
39
  let depth = 0;
38
- const formatted = lines.map((rawLine) => {
40
+ const formatted = [];
41
+ for (let index = 0; index < lines.length; index++) {
42
+ const diagram = diagramsByLine.get(index);
43
+ if (diagram) {
44
+ formatted.push(...formatDiagram(diagram, depth));
45
+ index = diagramEndLine(lines, index);
46
+ continue;
47
+ }
48
+ const rawLine = lines[index];
39
49
  const line = rawLine.replace(/[ \t]+$/, '');
40
- if (line.trim().length === 0)
41
- return '';
50
+ if (line.trim().length === 0) {
51
+ formatted.push('');
52
+ continue;
53
+ }
42
54
  const content = line.trimStart();
43
55
  const braces = scanBraces(content);
44
56
  const lineDepth = Math.max(0, depth - braces.leadingClosures);
45
- const result = `${' '.repeat(lineDepth)}${content}`;
57
+ formatted.push(`${' '.repeat(lineDepth)}${content}`);
46
58
  depth = Math.max(0, depth + braces.opens - braces.closes);
47
- return result;
48
- });
59
+ }
49
60
  return `${formatted.join('\n')}\n`;
50
61
  }
62
+ function collectDiagramDeclarations(statements, result) {
63
+ for (const statement of statements) {
64
+ if (statement.type === 'diagramDeclaration') {
65
+ if (statement.source)
66
+ result.set(statement.source.line - 1, statement);
67
+ }
68
+ else if (statement.type === 'forStatement') {
69
+ collectDiagramDeclarations(statement.body, result);
70
+ }
71
+ else if (statement.type === 'bracedIfStatement') {
72
+ collectDiagramDeclarations(statement.consequent, result);
73
+ if (statement.alternate)
74
+ collectDiagramDeclarations(statement.alternate, result);
75
+ }
76
+ }
77
+ }
78
+ function diagramEndLine(lines, start) {
79
+ let depth = 0;
80
+ for (let index = start; index < lines.length; index++) {
81
+ const braces = scanBraces(lines[index]);
82
+ depth += braces.opens - braces.closes;
83
+ if (depth === 0)
84
+ return index;
85
+ }
86
+ return lines.length - 1;
87
+ }
88
+ function orderedProperties(properties, order) {
89
+ const positions = new Map(order.map((name, index) => [name, index]));
90
+ return [...properties].sort((left, right) => (positions.get(left.name) ?? Number.MAX_SAFE_INTEGER) - (positions.get(right.name) ?? Number.MAX_SAFE_INTEGER));
91
+ }
92
+ function formatProperty(property, level) {
93
+ const indentation = ' '.repeat(level);
94
+ const continuationIndentation = ' '.repeat(level + 1);
95
+ const valueLines = property.rawValue.split('\n');
96
+ return [
97
+ `${indentation}${property.name}: ${valueLines[0]}`,
98
+ ...valueLines.slice(1).map(line => `${continuationIndentation}${line.trimStart()}`)
99
+ ];
100
+ }
101
+ function elementPropertyOrder(element) {
102
+ switch (element.primitive) {
103
+ case 'line': return ['x1', 'y1', 'x2', 'y2', 'stroke', 'lineWidth', 'arrow'];
104
+ case 'rectangle': return ['x', 'y', 'width', 'height', 'stroke', 'fill', 'lineWidth'];
105
+ case 'circle': return ['cx', 'cy', 'r', 'stroke', 'fill', 'lineWidth'];
106
+ case 'text': return ['x', 'y', 'value', 'fill'];
107
+ default: return [];
108
+ }
109
+ }
110
+ function formatDiagram(diagram, level) {
111
+ const indentation = ' '.repeat(level);
112
+ const output = [`${indentation}diagram ${diagram.name} {`];
113
+ output.push(...orderedProperties(diagram.properties, ['title', 'description', 'width', 'height'])
114
+ .flatMap(property => formatProperty(property, level + 1)));
115
+ for (const time of diagram.times) {
116
+ output.push(`${' '.repeat(level + 1)}time ${time.name} from ${time.fromText} to ${time.toText} duration ${time.durationText}`);
117
+ }
118
+ for (const element of diagram.elements) {
119
+ output.push(`${' '.repeat(level + 1)}${element.primitive} ${element.name} {`);
120
+ output.push(...orderedProperties(element.properties, elementPropertyOrder(element))
121
+ .flatMap(property => formatProperty(property, level + 2)));
122
+ output.push(`${' '.repeat(level + 1)}}`);
123
+ }
124
+ output.push(`${indentation}}`);
125
+ return output;
126
+ }
51
127
  function scanBraces(line) {
52
128
  let opens = 0;
53
129
  let closes = 0;
@@ -101,7 +101,7 @@ function tokenize(text, source) {
101
101
  continue;
102
102
  }
103
103
  // Single-character operators and grouping
104
- if ('+-*/%^()[].,{}:='.includes(ch)) {
104
+ if ('+-*/%^()[].,{}:=?'.includes(ch)) {
105
105
  if (ch === '(') {
106
106
  tokens.push({ type: 'lparen', text: ch, offset: i });
107
107
  }
@@ -117,6 +117,9 @@ function tokenize(text, source) {
117
117
  else if (ch === ',') {
118
118
  tokens.push({ type: 'comma', text: ch, offset: i });
119
119
  }
120
+ else if (ch === '?') {
121
+ tokens.push({ type: 'question', text: ch, offset: i });
122
+ }
120
123
  else if (ch === '{' || ch === '}' || ch === ':' || ch === '=' || ch === '.') {
121
124
  tokens.push({ type: { '{': 'lbrace', '}': 'rbrace', ':': 'colon', '=': 'equals', '.': 'dot' }[ch], text: ch, offset: i });
122
125
  }
@@ -446,7 +449,7 @@ export function parseExpression(text, source) {
446
449
  // power: ^ (right-assoc)
447
450
  // * / %
448
451
  // + -
449
- // comparison: == != > >= < <=
452
+ // comparison: == != > >= < <= is
450
453
  // logical and
451
454
  // logical or
452
455
  // conditional if/then/else (lowest)
@@ -458,6 +461,7 @@ export function parseExpression(text, source) {
458
461
  '>=': 2,
459
462
  '<': 2,
460
463
  '<=': 2,
464
+ 'is': 2,
461
465
  // Measurement conversion binds below arithmetic and above comparisons.
462
466
  'in': 2.5,
463
467
  // arithmetic
@@ -478,7 +482,7 @@ export function parseExpression(text, source) {
478
482
  const t = current();
479
483
  const attach = (value) => {
480
484
  const unit = current();
481
- if (unit.type !== 'identifier' || unit.name === 'in' || unit.name === 'to')
485
+ if (unit.type !== 'identifier' || unit.name === 'in' || unit.name === 'to' || unit.name === 'is')
482
486
  return value;
483
487
  advance();
484
488
  return {
@@ -637,6 +641,52 @@ export function parseExpression(text, source) {
637
641
  }
638
642
  throw new Error(`Unexpected token in expression: ${t.type} ${t.op || t.name || t.word || ''}`);
639
643
  }
644
+ function parseIsTarget() {
645
+ const name = current();
646
+ if (name.type !== 'identifier') {
647
+ syntaxError("Expected target type after 'is'", locationAt(text, tokenOffset(name, text.length), source));
648
+ }
649
+ advance();
650
+ let target = {
651
+ type: 'namedType',
652
+ name: name.name,
653
+ source: locationAt(text, name.offset, source)
654
+ };
655
+ let suffixEnd = name.offset + name.text.length;
656
+ while (current().type === 'lbracket' || current().type === 'question') {
657
+ const suffix = current();
658
+ const suffixOffset = tokenOffset(suffix, text.length);
659
+ if (suffixOffset !== suffixEnd) {
660
+ syntaxError("Invalid type suffix in 'is' target", locationAt(text, suffixOffset, source));
661
+ }
662
+ if (suffix.type === 'question') {
663
+ if (target.type === 'nullableType') {
664
+ syntaxError("Invalid type suffix in 'is' target", locationAt(text, suffixOffset, source));
665
+ }
666
+ advance();
667
+ target = {
668
+ type: 'nullableType',
669
+ element: target,
670
+ source: locationAt(text, suffixOffset, source)
671
+ };
672
+ suffixEnd = suffixOffset + 1;
673
+ continue;
674
+ }
675
+ advance();
676
+ const close = current();
677
+ if (close.type !== 'rbracket' || tokenOffset(close, text.length) !== suffixOffset + 1) {
678
+ syntaxError("Invalid type suffix in 'is' target", locationAt(text, suffixOffset, source));
679
+ }
680
+ advance();
681
+ target = {
682
+ type: 'listType',
683
+ element: target,
684
+ source: locationAt(text, suffixOffset, source)
685
+ };
686
+ suffixEnd = tokenOffset(close, text.length) + 1;
687
+ }
688
+ return target;
689
+ }
640
690
  function parseExpr(minPrec) {
641
691
  // Handle leading conditional (lowest precedence) before calling parsePrimary.
642
692
  // Conditionals only start at the top level of an expression (minPrec === 0).
@@ -665,6 +715,21 @@ export function parseExpression(text, source) {
665
715
  let left = parsePrimary();
666
716
  while (true) {
667
717
  const t = current();
718
+ if (t.type === 'identifier' && t.name === 'is') {
719
+ const prec = PREC.is;
720
+ if (prec < minPrec)
721
+ break;
722
+ advance();
723
+ const target = parseIsTarget();
724
+ left = {
725
+ type: 'typeTestExpression',
726
+ value: left,
727
+ target,
728
+ operatorSource: locationAt(text, t.offset, source),
729
+ source
730
+ };
731
+ continue;
732
+ }
668
733
  if (t.type === 'identifier' && t.name === 'in') {
669
734
  const prec = PREC.in;
670
735
  if (prec < minPrec)
@@ -167,6 +167,12 @@ export function parseStatements(body, start = { line: 1, column: 1 }, context =
167
167
  });
168
168
  }
169
169
  }
170
+ if (/^\s*diagram\b/.test(rawLine)) {
171
+ const parsed = parseDiagramDeclaration(lines, i, source);
172
+ statements.push(parsed.statement);
173
+ i = parsed.endIndex;
174
+ continue;
175
+ }
170
176
  if (/^\s*(table|chart)\b/.test(rawLine)) {
171
177
  const parsed = parseVisualization(lines, i, source, exported);
172
178
  statements.push(parsed.statement);
@@ -515,6 +521,147 @@ function parseVisualization(lines, startIndex, source, exported) {
515
521
  endIndex
516
522
  };
517
523
  }
524
+ function parseDiagramDeclaration(lines, startIndex, source) {
525
+ const headerLine = lines[startIndex];
526
+ const header = headerLine.match(/^\s*diagram\s+([A-Za-z][A-Za-z0-9_]*)\s*\{\s*$/);
527
+ if (!header)
528
+ syntaxError('Invalid diagram declaration', source);
529
+ const name = header[1];
530
+ const statement = {
531
+ type: 'diagramDeclaration',
532
+ name,
533
+ nameSource: { line: source.line, column: headerLine.indexOf(name) + 1 },
534
+ properties: [],
535
+ times: [],
536
+ elements: [],
537
+ source
538
+ };
539
+ let index = startIndex + 1;
540
+ while (index < lines.length) {
541
+ const line = lines[index];
542
+ if (/^\s*}\s*$/.test(line))
543
+ return { statement, endIndex: index };
544
+ if (!line.trim()) {
545
+ index++;
546
+ continue;
547
+ }
548
+ const lineSource = {
549
+ line: source.line + index - startIndex,
550
+ column: line.length - line.trimStart().length + 1
551
+ };
552
+ const timeHeader = line.match(/^\s*time\s+([A-Za-z][A-Za-z0-9_]*)\s+from\s+(.+)$/);
553
+ if (timeHeader) {
554
+ const tail = timeHeader[2];
555
+ const tailOffset = line.indexOf(tail);
556
+ const durationKeyword = findTopLevelKeyword(tail, 'duration');
557
+ if (!durationKeyword)
558
+ syntaxError('Invalid diagram time declaration', lineSource);
559
+ const bounds = tail.slice(0, durationKeyword.start).trim();
560
+ const toKeyword = findTopLevelKeyword(bounds, 'to');
561
+ if (!toKeyword)
562
+ syntaxError('Invalid diagram time declaration', lineSource);
563
+ const fromText = bounds.slice(0, toKeyword.start).trim();
564
+ const toText = bounds.slice(toKeyword.end).trim();
565
+ const durationText = tail.slice(durationKeyword.end).trim();
566
+ if (!fromText || !toText || !durationText)
567
+ syntaxError('Invalid diagram time declaration', lineSource);
568
+ const expressionSource = (offset) => locationAtOffset(tail, offset, {
569
+ line: lineSource.line,
570
+ column: tailOffset + 1
571
+ });
572
+ const fromSource = expressionSource(tail.indexOf(fromText));
573
+ const toSource = expressionSource(tail.indexOf(toText, toKeyword.end));
574
+ const durationSource = expressionSource(tail.indexOf(durationText, durationKeyword.end));
575
+ const time = {
576
+ name: timeHeader[1],
577
+ nameSource: { line: lineSource.line, column: line.indexOf(timeHeader[1]) + 1 },
578
+ from: parseExpression(fromText, fromSource),
579
+ fromText,
580
+ fromSource,
581
+ to: parseExpression(toText, toSource),
582
+ toText,
583
+ toSource,
584
+ duration: parseExpression(durationText, durationSource),
585
+ durationText,
586
+ durationSource,
587
+ source: lineSource
588
+ };
589
+ statement.times.push(time);
590
+ index++;
591
+ continue;
592
+ }
593
+ const elementHeader = line.match(/^\s*([A-Za-z][A-Za-z0-9_]*)\s+([A-Za-z][A-Za-z0-9_]*)\s*\{\s*$/);
594
+ if (elementHeader) {
595
+ const primitive = elementHeader[1];
596
+ const elementName = elementHeader[2];
597
+ const element = {
598
+ type: 'diagramElement',
599
+ primitive,
600
+ name: elementName,
601
+ nameSource: { line: lineSource.line, column: line.indexOf(elementName) + 1 },
602
+ properties: [],
603
+ source: { line: lineSource.line, column: lineSource.column }
604
+ };
605
+ index++;
606
+ let elementClosed = false;
607
+ while (index < lines.length) {
608
+ const propertyLine = lines[index];
609
+ if (/^\s*}\s*$/.test(propertyLine)) {
610
+ elementClosed = true;
611
+ index++;
612
+ break;
613
+ }
614
+ if (!propertyLine.trim()) {
615
+ index++;
616
+ continue;
617
+ }
618
+ const property = parseDiagramProperty(lines, index, source.line + index - startIndex);
619
+ element.properties.push(property.node);
620
+ index += property.lineCount;
621
+ }
622
+ if (!elementClosed)
623
+ syntaxError('Unclosed diagram element', element.source);
624
+ statement.elements.push(element);
625
+ continue;
626
+ }
627
+ const property = parseDiagramProperty(lines, index, source.line + index - startIndex);
628
+ statement.properties.push(property.node);
629
+ index += property.lineCount;
630
+ }
631
+ syntaxError('Unclosed diagram declaration', source);
632
+ }
633
+ function parseDiagramProperty(lines, index, lineNumber) {
634
+ const line = lines[index];
635
+ const match = line.match(/^\s*([A-Za-z][A-Za-z0-9_]*)\s*:\s*(.*)$/);
636
+ const source = {
637
+ line: lineNumber,
638
+ column: line.length - line.trimStart().length + 1
639
+ };
640
+ if (!match)
641
+ syntaxError('Invalid diagram property', source);
642
+ const name = match[1];
643
+ const initialValue = match[2];
644
+ if (!initialValue.trim())
645
+ syntaxError('Invalid diagram property value', source);
646
+ const collected = collectDelimitedExpression(lines, index, initialValue);
647
+ const rawValue = collected.text.trim();
648
+ const valueOffset = line.indexOf(initialValue) + initialValue.indexOf(initialValue.trim());
649
+ const valueSource = locationAtOffset(rawValue, 0, {
650
+ line: source.line,
651
+ column: valueOffset + 1
652
+ });
653
+ return {
654
+ node: {
655
+ name,
656
+ expression: parseExpression(rawValue, valueSource),
657
+ rawValue,
658
+ nameSource: { line: source.line, column: line.indexOf(name) + 1 },
659
+ valueSource,
660
+ source
661
+ },
662
+ lineCount: collected.lineCount
663
+ };
664
+ }
518
665
  export function parseTypeReference(text, source) {
519
666
  const name = text.match(/^[A-Za-z][A-Za-z0-9_]*/)?.[0];
520
667
  if (!name)
@@ -0,0 +1,255 @@
1
+ import { AmxError } from '../diagnostics/errors';
2
+ import { deserializeDiagramSceneModel, evaluateDiagramFrame } from '../runtime/diagramModel';
3
+ const SVG_NS = 'http://www.w3.org/2000/svg';
4
+ const activeStates = new Set();
5
+ function svgElement(name, attributes = {}) {
6
+ const element = document.createElementNS(SVG_NS, name);
7
+ for (const [key, value] of Object.entries(attributes))
8
+ element.setAttribute(key, String(value));
9
+ return element;
10
+ }
11
+ function positionText(element, x, y) {
12
+ element.setAttribute('x', String(x));
13
+ element.setAttribute('y', String(y));
14
+ element.setAttribute('transform', `translate(0 ${2 * y}) scale(1 -1)`);
15
+ }
16
+ function renderFrame(state, frame) {
17
+ const { model, canvas } = state;
18
+ const defs = svgElement('defs');
19
+ const marker = svgElement('marker', {
20
+ id: `${canvas.dataset.diagramId}-arrowhead`,
21
+ markerWidth: 6,
22
+ markerHeight: 6,
23
+ refX: 10,
24
+ refY: 5,
25
+ orient: 'auto-start-reverse',
26
+ markerUnits: 'strokeWidth',
27
+ viewBox: '0 0 10 10'
28
+ });
29
+ marker.append(svgElement('path', { d: 'M 0 0 L 10 5 L 0 10 z', fill: 'context-stroke' }));
30
+ defs.append(marker);
31
+ const coordinates = svgElement('g', { transform: `translate(0 ${model.canvas.height}) scale(1 -1)` });
32
+ for (const item of frame.elements) {
33
+ if (item.primitive === 'line') {
34
+ const line = svgElement('line', {
35
+ x1: item.x1, y1: item.y1, x2: item.x2, y2: item.y2,
36
+ stroke: item.stroke, 'stroke-width': item.lineWidth, 'stroke-linecap': 'round'
37
+ });
38
+ line.setAttribute('data-diagram-element', item.name);
39
+ if (item.arrow === 'start' || item.arrow === 'both')
40
+ line.setAttribute('marker-start', `url(#${canvas.dataset.diagramId}-arrowhead)`);
41
+ if (item.arrow === 'end' || item.arrow === 'both')
42
+ line.setAttribute('marker-end', `url(#${canvas.dataset.diagramId}-arrowhead)`);
43
+ coordinates.append(line);
44
+ }
45
+ else if (item.primitive === 'rectangle') {
46
+ const rectangle = svgElement('rect', {
47
+ x: item.x, y: item.y, width: item.width, height: item.height,
48
+ stroke: item.stroke, fill: item.fill ?? 'none', 'stroke-width': item.lineWidth
49
+ });
50
+ rectangle.setAttribute('data-diagram-element', item.name);
51
+ coordinates.append(rectangle);
52
+ }
53
+ else if (item.primitive === 'circle') {
54
+ const circle = svgElement('circle', {
55
+ cx: item.cx, cy: item.cy, r: item.r,
56
+ stroke: item.stroke, fill: item.fill ?? 'none', 'stroke-width': item.lineWidth
57
+ });
58
+ circle.setAttribute('data-diagram-element', item.name);
59
+ coordinates.append(circle);
60
+ }
61
+ else {
62
+ const text = svgElement('text', { fill: item.fill, 'font-family': 'sans-serif', 'font-size': 12 });
63
+ positionText(text, item.x, item.y);
64
+ text.setAttribute('data-diagram-element', item.name);
65
+ text.textContent = item.value;
66
+ coordinates.append(text);
67
+ }
68
+ }
69
+ canvas.replaceChildren(defs, coordinates);
70
+ canvas.removeAttribute('aria-hidden');
71
+ }
72
+ function sendFailure(detail) {
73
+ window.dispatchEvent(new CustomEvent('openamx-diagram-frame', { detail }));
74
+ }
75
+ async function deserializePayload(payload) {
76
+ if (payload.dataset.encoding !== 'gzip-base64')
77
+ throw new Error('Unsupported diagram data encoding.');
78
+ const encoded = atob(payload.textContent ?? '');
79
+ const bytes = new Uint8Array(encoded.length);
80
+ for (let index = 0; index < encoded.length; index++)
81
+ bytes[index] = encoded.charCodeAt(index);
82
+ const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip'));
83
+ return deserializeDiagramSceneModel(await new Response(stream).text());
84
+ }
85
+ function syncControls(state) {
86
+ const title = state.model.title;
87
+ state.playButton.textContent = state.running ? 'Pause' : 'Play';
88
+ state.playButton.setAttribute('aria-label', `${state.running ? 'Pause' : 'Play'} ${title}`);
89
+ state.scrubber.value = String(state.time);
90
+ state.scrubber.setAttribute('aria-valuetext', String(state.time));
91
+ state.timeOutput.value = String(state.time);
92
+ state.timeOutput.textContent = String(state.time);
93
+ }
94
+ function stop(state) {
95
+ state.running = false;
96
+ if (state.animationFrame !== undefined)
97
+ cancelAnimationFrame(state.animationFrame);
98
+ state.animationFrame = undefined;
99
+ syncControls(state);
100
+ }
101
+ function selectTime(state, time) {
102
+ state.time = time;
103
+ syncControls(state);
104
+ try {
105
+ const frame = evaluateDiagramFrame(state.model, time);
106
+ renderFrame(state, frame);
107
+ state.alert.hidden = true;
108
+ state.alert.textContent = '';
109
+ if (state.failed) {
110
+ state.failed = false;
111
+ sendFailure({ version: 1, type: 'diagram-recovered', diagramId: state.canvas.dataset.diagramId });
112
+ }
113
+ return true;
114
+ }
115
+ catch (error) {
116
+ stop(state);
117
+ state.canvas.replaceChildren();
118
+ state.canvas.setAttribute('aria-hidden', 'true');
119
+ state.failed = true;
120
+ const failure = error instanceof AmxError
121
+ ? {
122
+ code: error.code,
123
+ message: error.message,
124
+ file: error.file ?? state.model.file,
125
+ line: error.line ?? state.model.source?.line,
126
+ column: error.column ?? state.model.source?.column
127
+ }
128
+ : {
129
+ code: 'DIAGRAM_RUNTIME',
130
+ message: 'The diagram frame could not be evaluated.',
131
+ file: state.model.file,
132
+ line: state.model.source?.line,
133
+ column: state.model.source?.column
134
+ };
135
+ const location = failure.file
136
+ ? `${failure.file}${failure.line ? `:${failure.line}${failure.column ? `:${failure.column}` : ''}` : ''}`
137
+ : failure.line ? `${failure.line}${failure.column ? `:${failure.column}` : ''}` : '';
138
+ state.alert.textContent = `${failure.code}: ${failure.message}${location ? ` (${location})` : ''}`;
139
+ state.alert.hidden = false;
140
+ sendFailure({
141
+ version: 1,
142
+ type: 'diagram-error',
143
+ diagramId: state.canvas.dataset.diagramId,
144
+ ...failure
145
+ });
146
+ return false;
147
+ }
148
+ }
149
+ function play(state) {
150
+ if (state.running || state.failed)
151
+ return;
152
+ if (state.time >= state.model.timeline.to) {
153
+ const loop = state.canvas.closest('[data-openamx-diagram]')?.querySelector('[data-diagram-loop]');
154
+ if (!loop?.checked)
155
+ return;
156
+ selectTime(state, state.model.timeline.from);
157
+ }
158
+ state.running = true;
159
+ state.startedAt = performance.now() - ((state.time - state.model.timeline.from)
160
+ / (state.model.timeline.to - state.model.timeline.from)) * state.model.timeline.duration * 1000;
161
+ syncControls(state);
162
+ state.animationFrame = requestAnimationFrame(timestamp => advance(state, timestamp));
163
+ }
164
+ function advance(state, timestamp) {
165
+ if (!state.running || !document.contains(state.canvas)) {
166
+ stop(state);
167
+ return;
168
+ }
169
+ const durationSeconds = state.model.timeline.duration;
170
+ const progress = (timestamp - state.startedAt) / 1000 / durationSeconds;
171
+ if (progress >= 1) {
172
+ const root = state.canvas.closest('[data-openamx-diagram]');
173
+ const loop = root?.querySelector('[data-diagram-loop]')?.checked ?? false;
174
+ if (!loop) {
175
+ selectTime(state, state.model.timeline.to);
176
+ stop(state);
177
+ return;
178
+ }
179
+ if (!selectTime(state, state.model.timeline.from))
180
+ return;
181
+ state.startedAt = timestamp;
182
+ }
183
+ else {
184
+ const from = state.model.timeline.from;
185
+ const to = state.model.timeline.to;
186
+ const time = progress <= 0 ? from : from * (1 - progress) + to * progress;
187
+ if (!selectTime(state, time))
188
+ return;
189
+ }
190
+ state.animationFrame = requestAnimationFrame(next => advance(state, next));
191
+ }
192
+ async function initialize(root) {
193
+ const payload = root.querySelector('[data-diagram-model]');
194
+ const canvas = root.querySelector('[data-diagram-canvas]');
195
+ const playButton = root.querySelector('[data-diagram-play]');
196
+ const resetButton = root.querySelector('[data-diagram-reset]');
197
+ const scrubber = root.querySelector('[data-diagram-scrubber]');
198
+ const loop = root.querySelector('[data-diagram-loop]');
199
+ const timeOutput = root.querySelector('[data-diagram-time]');
200
+ const alert = root.querySelector('[data-diagram-error]');
201
+ if (!payload || !canvas || !playButton || !resetButton || !scrubber || !loop || !timeOutput || !alert) {
202
+ throw new Error('Diagram HTML is missing required runtime elements.');
203
+ }
204
+ const model = await deserializePayload(payload);
205
+ canvas.dataset.diagramId = root.dataset.diagramId;
206
+ const state = {
207
+ model, canvas, playButton, scrubber, timeOutput, alert,
208
+ running: false, failed: false, time: model.timeline.from, startedAt: 0
209
+ };
210
+ activeStates.add(state);
211
+ syncControls(state);
212
+ playButton.addEventListener('click', () => {
213
+ if (state.running)
214
+ stop(state);
215
+ else
216
+ play(state);
217
+ });
218
+ resetButton.addEventListener('click', () => {
219
+ stop(state);
220
+ selectTime(state, model.timeline.from);
221
+ });
222
+ scrubber.addEventListener('input', () => {
223
+ const selectedTime = Number(scrubber.value);
224
+ stop(state);
225
+ selectTime(state, selectedTime);
226
+ });
227
+ selectTime(state, model.timeline.from);
228
+ }
229
+ async function initializeAll() {
230
+ for (const root of Array.from(document.querySelectorAll('[data-openamx-diagram]'))) {
231
+ try {
232
+ await initialize(root);
233
+ }
234
+ catch (error) {
235
+ const alert = root.querySelector('[data-diagram-error]');
236
+ if (!alert)
237
+ throw error;
238
+ alert.textContent = `DIAGRAM_RUNTIME: ${error instanceof Error ? error.message : 'The diagram could not be initialized.'}`;
239
+ alert.hidden = false;
240
+ sendFailure({
241
+ version: 1,
242
+ type: 'diagram-error',
243
+ diagramId: root.dataset.diagramId ?? '',
244
+ code: 'DIAGRAM_RUNTIME',
245
+ message: alert.textContent
246
+ });
247
+ }
248
+ }
249
+ }
250
+ document.addEventListener('DOMContentLoaded', () => { void initializeAll(); }, { once: true });
251
+ window.addEventListener('pagehide', () => {
252
+ for (const state of activeStates)
253
+ stop(state);
254
+ activeStates.clear();
255
+ }, { once: true });