@turing-machine-js/visuals 7.0.0-alpha.6 → 7.0.0-alpha.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/format.ts DELETED
@@ -1,51 +0,0 @@
1
- import { movements, symbolCommands, type MachineState, type TapeCommand } from '@turing-machine-js/machine';
2
-
3
- export const MOVEMENT_LETTER = new Map<symbol, 'L' | 'R' | 'S'>([
4
- [movements.left, 'L'],
5
- [movements.right, 'R'],
6
- [movements.stay, 'S'],
7
- ]);
8
-
9
- /**
10
- * Render a single tape command in `WRITE/MOVE` form.
11
- * - Write: `'X'` (literal symbol) | `K` (keep) | `E` (erase = write blank).
12
- * - Move: `L` / `R` / `S` from `movements.*`.
13
- *
14
- * Matches the engine's edge-label vocabulary so formatted commands line up
15
- * with the write/move cells in `toMermaid`-emitted edge labels.
16
- */
17
- export function formatCommand(tapeCommand: TapeCommand): string {
18
- let write: string;
19
-
20
- if (tapeCommand.symbol === symbolCommands.keep) {
21
- write = 'K';
22
- } else if (tapeCommand.symbol === symbolCommands.erase) {
23
- write = 'E';
24
- } else {
25
- write = `'${tapeCommand.symbol as string}'`;
26
- }
27
-
28
- const move = MOVEMENT_LETTER.get(tapeCommand.movement) ?? '?';
29
-
30
- return `${write}/${move}`;
31
- }
32
-
33
- /**
34
- * Render one step's edge-label notation: `[reads] → [writes]/[moves]`.
35
- * Each role is wrapped in a single `[…]`; multi-tape entries are
36
- * comma-separated inside the brackets.
37
- *
38
- * Matches the engine's `toMermaid` emit so logged steps line up with
39
- * graph edge labels. Note: `nextSymbols` in `MachineState` is already
40
- * resolved (keep → current symbol, erase → blank) — `K` is inferred
41
- * by comparing `nextSymbols[i] === currentSymbols[i]`.
42
- */
43
- export function formatStep(m: MachineState): string {
44
- const reads = m.currentSymbols.map((s) => `'${s}'`).join(',');
45
- const writes = m.nextSymbols
46
- .map((s, i) => (s === m.currentSymbols[i] ? 'K' : `'${s}'`))
47
- .join(',');
48
- const moves = m.movements.map((mv) => MOVEMENT_LETTER.get(mv) ?? '?').join(',');
49
-
50
- return `[${reads}] → [${writes}]/[${moves}]`;
51
- }
@@ -1,84 +0,0 @@
1
- import type { Graph } from '@turing-machine-js/machine';
2
-
3
- /**
4
- * Derived lookups over an engine `Graph` that the highlight + indicator
5
- * passes need. Recomputed once per Build; consumed read-only thereafter.
6
- *
7
- * Pure transformation of `graph` — same input always produces deep-equal
8
- * output. See `docs/graph-highlight-and-breakpoints.md` for how each
9
- * field is consumed.
10
- */
11
- export type GraphIndexes = {
12
- /** `GraphNode.id` → containing callable-subtree frameId. Only nodes
13
- * with `frameId !== null` (i.e. in-frame states) are present. */
14
- nodeFrameMap: Map<number, number>;
15
-
16
- /** frameId → list of wrappers calling into that frame, each with the
17
- * wrapper's id and its override-target id. Used by both source and
18
- * destination return-chain passes. */
19
- frameWrappersMap: Map<number, Array<{ wrapperId: number; overrideId: number | null }>>;
20
-
21
- /** Cluster label text (as emitted by `toMermaid`) → frameId. The
22
- * rendered SVG's `g.cluster` carries the label inside a
23
- * `<foreignObject>`; consumers match by `label.textContent.trim()` to
24
- * build their own `clusterCache: Map<frameId, SVGElement>`. */
25
- frameLabelToId: Map<string, number>;
26
- };
27
-
28
- /**
29
- * Walk the engine graph once and build all derived lookups. Cheap;
30
- * intended to run on every Build (graph identity changes per build).
31
- */
32
- export function indexGraph(graph: Graph | null): GraphIndexes {
33
- const nodeFrameMap = new Map<number, number>();
34
- const frameWrappersMap = new Map<
35
- number,
36
- Array<{ wrapperId: number; overrideId: number | null }>
37
- >();
38
- const frameLabelToId = new Map<string, number>();
39
-
40
- if (!graph) return { nodeFrameMap, frameWrappersMap, frameLabelToId };
41
-
42
- for (const node of Object.values(graph.nodes)) {
43
- if (node.frameId !== null) nodeFrameMap.set(node.id, node.frameId);
44
- }
45
-
46
- // For each wrapper, append to its bare's frame entry. Multiple wrappers
47
- // can share the same bare with different overrides; we record them all
48
- // so the return-chain passes can highlight every candidate.
49
- for (const node of Object.values(graph.nodes)) {
50
- if (!node.isWrapper || node.bareStateId === null) continue;
51
- const bare = graph.nodes[node.bareStateId];
52
- if (!bare || bare.frameId === null) continue;
53
- const entry = { wrapperId: node.id, overrideId: node.overriddenHaltStateId };
54
- const arr = frameWrappersMap.get(bare.frameId);
55
- if (arr) arr.push(entry);
56
- else frameWrappersMap.set(bare.frameId, [entry]);
57
- }
58
-
59
- // Cluster label reconstruction: mirrors the engine's `toMermaid` emit
60
- // (`callable subtree of NAME` for single-bare frames, `callable scope:
61
- // A ∪ B ∪ …` for union frames; bare names sorted by id). Consumers
62
- // need this to map mermaid's rendered cluster (whose own SVG id is the
63
- // useless literal `[object Object]`) back to a frameId.
64
- const bareIds = new Set<number>();
65
- for (const n of Object.values(graph.nodes)) {
66
- if (n.isWrapper && n.bareStateId !== null) bareIds.add(n.bareStateId);
67
- }
68
- const frameToBareNames = new Map<number, string[]>();
69
- for (const n of Object.values(graph.nodes).sort((a, b) => a.id - b.id)) {
70
- if (n.isWrapper || n.isHaltMarker || n.frameId === null) continue;
71
- if (!bareIds.has(n.id)) continue;
72
- const arr = frameToBareNames.get(n.frameId) ?? [];
73
- arr.push(n.name);
74
- frameToBareNames.set(n.frameId, arr);
75
- }
76
- for (const [frameId, names] of frameToBareNames) {
77
- const label = names.length > 1
78
- ? `callable scope: ${names.join(' ∪ ')}`
79
- : `callable subtree of ${names[0] ?? frameId}`;
80
- frameLabelToId.set(label, frameId);
81
- }
82
-
83
- return { nodeFrameMap, frameWrappersMap, frameLabelToId };
84
- }
@@ -1,112 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { readFileSync } from 'node:fs';
3
- import { resolve, dirname } from 'node:path';
4
- import { fileURLToPath } from 'node:url';
5
- import { bareIdOf, equivalentIds, highlightExpand } from './graphUtils';
6
- import type { Graph } from '@turing-machine-js/machine';
7
-
8
- /**
9
- * Tests for the pure breakpoint / highlight class helpers in
10
- * `graphUtils.ts`. These rules feed both the breakpoint indicator
11
- * (`applyIndicator`) and the context-menu "Shared with" info line
12
- * (`MachineGraph.svelte`); the upstream engine v7 collapses wrapper
13
- * states (`State.withOverriddenHaltState`) onto a shared `#debugRef`
14
- * with their bare, so the demo collapses them into one breakpoint per
15
- * equivalence class.
16
- *
17
- * Fixture: `turing-callable-subtree` has
18
- * 3 → bare `walkToBlank` (frameId 3)
19
- * 4 → `writeMarker` (override)
20
- * 5 → wrapper `walkToBlank(writeMarker)` (bareStateId 3)
21
- * 0 → halt singleton
22
- * -3 → halt marker for frame 3
23
- */
24
-
25
- const __filename = fileURLToPath(import.meta.url);
26
- const __dirname = dirname(__filename);
27
-
28
- function loadGraph(name: string): Graph {
29
- const path = resolve(__dirname, './fixtures/graphs', `${name}.json`);
30
- return JSON.parse(readFileSync(path, 'utf8')) as Graph;
31
- }
32
-
33
- describe('bareIdOf', () => {
34
- const g = loadGraph('turing-callable-subtree');
35
-
36
- it('maps a wrapper id to its bareStateId', () => {
37
- expect(bareIdOf(5, g)).toBe(3);
38
- });
39
-
40
- it('returns the bare id unchanged for non-wrapper positive ids', () => {
41
- expect(bareIdOf(3, g)).toBe(3);
42
- expect(bareIdOf(4, g)).toBe(4);
43
- });
44
-
45
- it('collapses halt markers (negative ids) to the halt singleton (0)', () => {
46
- expect(bareIdOf(-3, g)).toBe(0);
47
- });
48
-
49
- it('returns 0 for the halt singleton itself', () => {
50
- expect(bareIdOf(0, g)).toBe(0);
51
- });
52
-
53
- it('returns the id unchanged when graph is null', () => {
54
- expect(bareIdOf(5, null)).toBe(5);
55
- expect(bareIdOf(-3, null)).toBe(-3);
56
- });
57
-
58
- it('returns the id unchanged when no node entry exists', () => {
59
- expect(bareIdOf(999, g)).toBe(999);
60
- });
61
- });
62
-
63
- describe('highlightExpand (asymmetric)', () => {
64
- const g = loadGraph('turing-callable-subtree');
65
-
66
- it('expands wrapper → [wrapper, bare]', () => {
67
- expect(highlightExpand(5, g).sort()).toEqual([3, 5]);
68
- });
69
-
70
- it('does NOT expand bare → [bare] only (no wrapper sync from bare side)', () => {
71
- expect(highlightExpand(3, g)).toEqual([3]);
72
- });
73
-
74
- it('returns [id] for a non-wrapper non-bare id', () => {
75
- expect(highlightExpand(4, g)).toEqual([4]);
76
- });
77
-
78
- it('returns [id] when graph is null', () => {
79
- expect(highlightExpand(5, null)).toEqual([5]);
80
- });
81
- });
82
-
83
- describe('equivalentIds (symmetric class lookup)', () => {
84
- const g = loadGraph('turing-callable-subtree');
85
-
86
- it('returns [bare, ...wrappers] from a wrapper input', () => {
87
- expect(equivalentIds(5, g).sort()).toEqual([3, 5]);
88
- });
89
-
90
- it('returns [bare, ...wrappers] from the bare input — symmetric', () => {
91
- expect(equivalentIds(3, g).sort()).toEqual([3, 5]);
92
- });
93
-
94
- it('returns [singleton] for a stand-alone state', () => {
95
- expect(equivalentIds(4, g)).toEqual([4]);
96
- });
97
-
98
- it('halt singleton (0) → [0, ...all halt markers]', () => {
99
- const ids = equivalentIds(0, g).sort((a, b) => a - b);
100
- expect(ids).toEqual([-3, 0]);
101
- });
102
-
103
- it('halt marker (-3) → same class as halt singleton (symmetric)', () => {
104
- const ids = equivalentIds(-3, g).sort((a, b) => a - b);
105
- expect(ids).toEqual([-3, 0]);
106
- });
107
-
108
- it('returns [id] when graph is null', () => {
109
- expect(equivalentIds(5, null)).toEqual([5]);
110
- expect(equivalentIds(0, null)).toEqual([0]);
111
- });
112
- });
package/src/graphUtils.ts DELETED
@@ -1,74 +0,0 @@
1
- import type { Graph } from '@turing-machine-js/machine';
2
-
3
- /**
4
- * Normalize an engine `GraphNode.id` to its canonical representative for
5
- * breakpoint-class lookups (machines-demo#37). Wrappers produced by
6
- * `State.withOverriddenHaltState` share `#debugRef` with their bare state
7
- * engine-side (turing-machine-js v7 `State.ts`: `state.#debugRef =
8
- * bare.#debugRef`), so they form a single breakpoint from the user's POV.
9
- * This collapses any wrapper id to its bare's id; non-wrapper ids return
10
- * self. Used so the demo can store ONE canonical id per equivalence class
11
- * in its breakpoint set, and expand to all class members for indicator
12
- * rendering — keeping the worker-side toggle count to one per class
13
- * (multiple toggles on the shared ref would double-flip).
14
- */
15
- export function bareIdOf(id: number, graph: Graph | null): number {
16
- if (!graph) return id;
17
- // Halt markers (negative ids, one per frame) are visualization sentinels;
18
- // at runtime they all collapse to the haltState singleton (id 0). For
19
- // breakpoint purposes they're a single class — setting BP on any
20
- // halt-related node sets it on the global haltState.
21
- if (id < 0) return 0;
22
- const node = graph.nodes[id];
23
- if (node && node.isWrapper && node.bareStateId !== null) {
24
- return node.bareStateId;
25
- }
26
- return id;
27
- }
28
-
29
- /**
30
- * Asymmetric expansion for the highlight effect (machines-demo#37).
31
- * Wrapper → `[wrapper, bare]` (the wrapper-entry pause is visually joined
32
- * to its bare, since the user thinks of them as one call site).
33
- * Bare → `[bare]` only (when the engine is genuinely on the bare — e.g. a
34
- * loop iter — the wrapper is not the "active" state and shouldn't get the
35
- * strong highlight).
36
- * Non-wrapper / non-bare ids return `[id]`.
37
- */
38
- export function highlightExpand(id: number, graph: Graph | null): number[] {
39
- if (!graph) return [id];
40
- const node = graph.nodes[id];
41
- if (node?.isWrapper && node.bareStateId !== null) {
42
- return [id, node.bareStateId];
43
- }
44
- return [id];
45
- }
46
-
47
- /**
48
- * All GraphNode ids in the same breakpoint equivalence class as `id`.
49
- * Symmetric — gives consumers the full list of nodes that share an engine
50
- * breakpoint, regardless of which class member is the input. Used by the
51
- * context-menu's "Shared with" info line so the user can see at a glance
52
- * which other nodes flip together.
53
- *
54
- * Halt class (canonical id 0): the halt singleton + every halt marker in
55
- * the graph. Wrapper/bare class: the bare + every wrapper pointing at it.
56
- * Singleton classes (regular states, idle sentinel proxies) return just
57
- * the input id.
58
- */
59
- export function equivalentIds(id: number, graph: Graph | null): number[] {
60
- if (!graph) return [id];
61
- const canonical = bareIdOf(id, graph);
62
- if (canonical === 0) {
63
- const ids: number[] = [0];
64
- for (const node of Object.values(graph.nodes)) {
65
- if (node.isHaltMarker) ids.push(node.id);
66
- }
67
- return ids;
68
- }
69
- const result = new Set<number>([canonical]);
70
- for (const node of Object.values(graph.nodes)) {
71
- if (node.isWrapper && node.bareStateId === canonical) result.add(node.id);
72
- }
73
- return [...result];
74
- }
@@ -1,94 +0,0 @@
1
- /**
2
- * Contract between the pure highlight logic (`applyHighlight`,
3
- * `applyIndicator`) and any consumer that actually renders the graph
4
- * (Svelte component, vanilla embed, server-side snapshot, etc.).
5
- *
6
- * The pure functions decide *what* should happen (which node gets a class,
7
- * which edge lights up, where to pulse); the consumer's `HighlightOps`
8
- * implementation decides *how* (DOM mutation, recording for tests, etc.).
9
- *
10
- * See `docs/graph-highlight-and-breakpoints.md` for the rules each
11
- * implementation must respect.
12
- */
13
-
14
- export type NodeKey = number | 'idle';
15
-
16
- /** Classes the apply-highlight pass may add to a `g.node` element. */
17
- export type HighlightClass =
18
- | 'mg-highlight-from'
19
- | 'mg-highlight-to'
20
- | 'mg-highlight-strong';
21
-
22
- /**
23
- * Operations the highlight logic invokes on the rendered graph. Purely
24
- * additive — the consumer is expected to clear previous highlight state
25
- * (classes, marker swaps) BEFORE invoking `applyHighlight`. The pure
26
- * function never reads back from the consumer; it just emits ops.
27
- *
28
- * Edge keys follow mermaid's data-id token form: `'idle'` for the
29
- * synthetic entry sentinel, `'s${id}'` for regular/wrapper/bare states,
30
- * `'c${id}'` for halt markers (id = `-frameId`), `'w_${id}'` for callable-
31
- * subtree subgraph clusters. Mermaid emits `L_${from}_${to}_${ix}` per
32
- * edge; ix-resolution is the consumer's concern (multiple edges between
33
- * the same pair are rare; the consumer typically picks the first match).
34
- */
35
- export interface HighlightOps {
36
- /** Add a highlight class to the node identified by `id`. */
37
- addNodeClass(id: NodeKey, cls: HighlightClass): void;
38
-
39
- /** Highlight the edge whose data-id matches `L_${fromKey}_${toKey}_*`. */
40
- highlightEdge(fromKey: string, toKey: string): void;
41
-
42
- /** Mark the callable-subtree cluster for `frameId` as active. */
43
- markFrameActive(frameId: number): void;
44
-
45
- /** Fire a one-shot pulse animation on the given node. */
46
- pulse(id: NodeKey): void;
47
-
48
- /** Scroll the given node into the visible area of its container. */
49
- scrollIntoView(id: NodeKey): void;
50
- }
51
-
52
- /** Operations the indicator (breakpoint dot) pass invokes. */
53
- export interface IndicatorOps {
54
- /** Set or clear the breakpoint indicator on the given node. */
55
- setBreakpoint(id: NodeKey, on: boolean): void;
56
- }
57
-
58
- /** A single recorded op — serializable, suitable for snapshot tests. */
59
- export type RecordedOp =
60
- | { op: 'addNodeClass'; id: NodeKey; cls: HighlightClass }
61
- | { op: 'highlightEdge'; fromKey: string; toKey: string }
62
- | { op: 'markFrameActive'; frameId: number }
63
- | { op: 'pulse'; id: NodeKey }
64
- | { op: 'scrollIntoView'; id: NodeKey }
65
- | { op: 'setBreakpoint'; id: NodeKey; on: boolean };
66
-
67
- /**
68
- * Build a recording `HighlightOps` + `IndicatorOps` pair plus the shared
69
- * `record` array of calls in invocation order. Used by tests to assert
70
- * what the pure logic would have done without running a real DOM.
71
- *
72
- * Snapshot-friendly: the record contains only plain JSON-serializable
73
- * values (no DOM nodes, no function refs).
74
- */
75
- export function recordingOps(): {
76
- highlight: HighlightOps;
77
- indicator: IndicatorOps;
78
- record: RecordedOp[];
79
- } {
80
- const record: RecordedOp[] = [];
81
- return {
82
- record,
83
- highlight: {
84
- addNodeClass(id, cls) { record.push({ op: 'addNodeClass', id, cls }); },
85
- highlightEdge(fromKey, toKey) { record.push({ op: 'highlightEdge', fromKey, toKey }); },
86
- markFrameActive(frameId) { record.push({ op: 'markFrameActive', frameId }); },
87
- pulse(id) { record.push({ op: 'pulse', id }); },
88
- scrollIntoView(id) { record.push({ op: 'scrollIntoView', id }); },
89
- },
90
- indicator: {
91
- setBreakpoint(id, on) { record.push({ op: 'setBreakpoint', id, on }); },
92
- },
93
- };
94
- }
package/src/index.ts DELETED
@@ -1,10 +0,0 @@
1
- // Public API — extracted modules + Snippet recording surface.
2
- export type { NodeKey, HighlightClass, HighlightOps, IndicatorOps, RecordedOp } from './highlightOps';
3
- export { recordingOps } from './highlightOps';
4
- export { bareIdOf, highlightExpand, equivalentIds } from './graphUtils';
5
- export type { GraphIndexes } from './graphIndexes';
6
- export { indexGraph } from './graphIndexes';
7
- export type { GraphHighlight, TapeSnapshot, Frame, Snippet } from './types';
8
- export { applyHighlight, applyIndicator } from './applyHighlight';
9
- export { formatCommand, formatStep } from './format';
10
- export { recordSnippet, type RecordSnippetOptions } from './recordSnippet';