@metronforge/concept-map 0.0.0-stage → 0.1.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.
Files changed (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +109 -2
  3. package/css/concept-map.css +903 -0
  4. package/dist/dom/animator.d.ts +25 -0
  5. package/dist/dom/animator.d.ts.map +1 -0
  6. package/dist/dom/animator.js +124 -0
  7. package/dist/dom/animator.js.map +1 -0
  8. package/dist/dom/geometry.d.ts +15 -0
  9. package/dist/dom/geometry.d.ts.map +1 -0
  10. package/dist/dom/geometry.js +52 -0
  11. package/dist/dom/geometry.js.map +1 -0
  12. package/dist/dom/panelDom.d.ts +15 -0
  13. package/dist/dom/panelDom.d.ts.map +1 -0
  14. package/dist/dom/panelDom.js +61 -0
  15. package/dist/dom/panelDom.js.map +1 -0
  16. package/dist/dom/player.d.ts +40 -0
  17. package/dist/dom/player.d.ts.map +1 -0
  18. package/dist/dom/player.js +273 -0
  19. package/dist/dom/player.js.map +1 -0
  20. package/dist/dom/svgDom.d.ts +19 -0
  21. package/dist/dom/svgDom.d.ts.map +1 -0
  22. package/dist/dom/svgDom.js +70 -0
  23. package/dist/dom/svgDom.js.map +1 -0
  24. package/dist/index.d.ts +18 -0
  25. package/dist/index.d.ts.map +1 -0
  26. package/dist/index.js +12 -0
  27. package/dist/index.js.map +1 -0
  28. package/dist/model/flow.d.ts +43 -0
  29. package/dist/model/flow.d.ts.map +1 -0
  30. package/dist/model/flow.js +87 -0
  31. package/dist/model/flow.js.map +1 -0
  32. package/dist/model/frame.d.ts +61 -0
  33. package/dist/model/frame.d.ts.map +1 -0
  34. package/dist/model/frame.js +124 -0
  35. package/dist/model/frame.js.map +1 -0
  36. package/dist/model/labels.d.ts +18 -0
  37. package/dist/model/labels.d.ts.map +1 -0
  38. package/dist/model/labels.js +25 -0
  39. package/dist/model/labels.js.map +1 -0
  40. package/dist/model/path.d.ts +4 -0
  41. package/dist/model/path.d.ts.map +1 -0
  42. package/dist/model/path.js +51 -0
  43. package/dist/model/path.js.map +1 -0
  44. package/dist/model/state.d.ts +30 -0
  45. package/dist/model/state.d.ts.map +1 -0
  46. package/dist/model/state.js +30 -0
  47. package/dist/model/state.js.map +1 -0
  48. package/dist/render/concepts.d.ts +4 -0
  49. package/dist/render/concepts.d.ts.map +1 -0
  50. package/dist/render/concepts.js +16 -0
  51. package/dist/render/concepts.js.map +1 -0
  52. package/dist/render/inline.d.ts +6 -0
  53. package/dist/render/inline.d.ts.map +1 -0
  54. package/dist/render/inline.js +70 -0
  55. package/dist/render/inline.js.map +1 -0
  56. package/dist/render/panel.d.ts +27 -0
  57. package/dist/render/panel.d.ts.map +1 -0
  58. package/dist/render/panel.js +57 -0
  59. package/dist/render/panel.js.map +1 -0
  60. package/dist/render/svg.d.ts +8 -0
  61. package/dist/render/svg.d.ts.map +1 -0
  62. package/dist/render/svg.js +43 -0
  63. package/dist/render/svg.js.map +1 -0
  64. package/dist/schema.d.ts +352 -0
  65. package/dist/schema.d.ts.map +1 -0
  66. package/dist/schema.js +138 -0
  67. package/dist/schema.js.map +1 -0
  68. package/package.json +74 -4
  69. package/resolved-map.schema.json +769 -0
  70. package/src/dom/animator.ts +129 -0
  71. package/src/dom/geometry.ts +81 -0
  72. package/src/dom/panelDom.ts +72 -0
  73. package/src/dom/player.ts +318 -0
  74. package/src/dom/svgDom.ts +79 -0
  75. package/src/index.ts +18 -0
  76. package/src/model/flow.ts +122 -0
  77. package/src/model/frame.ts +180 -0
  78. package/src/model/labels.ts +37 -0
  79. package/src/model/path.ts +56 -0
  80. package/src/model/state.ts +51 -0
  81. package/src/render/concepts.ts +21 -0
  82. package/src/render/inline.ts +71 -0
  83. package/src/render/panel.ts +69 -0
  84. package/src/render/svg.ts +52 -0
  85. package/src/schema.ts +162 -0
@@ -0,0 +1,122 @@
1
+ import type { ResolvedMap } from "../schema.js";
2
+ import type { LogLine } from "./frame.js";
3
+ import { pathEnds, type Point } from "./path.js";
4
+ export type Segment =
5
+ | { type: "pause"; duration: number; at: Point }
6
+ | { type: "jump"; duration: number; from: Point; to: Point }
7
+ | {
8
+ type: "travel";
9
+ duration: number;
10
+ edge: string;
11
+ reverse: boolean;
12
+ from: Point;
13
+ to: Point;
14
+ };
15
+ export interface FlowPlan {
16
+ segments: Segment[];
17
+ hops: {
18
+ startSegment: number;
19
+ segment: number;
20
+ step: number;
21
+ node: string;
22
+ log: string[];
23
+ fail: boolean;
24
+ }[];
25
+ }
26
+ export function planFlow(
27
+ map: ResolvedMap,
28
+ scenario: number,
29
+ geo: { length(edge: string): number },
30
+ ): FlowPlan {
31
+ const s = map.scenarios[scenario],
32
+ flow = s.flow ?? [];
33
+ const plan: FlowPlan = { segments: [], hops: [] };
34
+ if (!flow.length) return plan;
35
+ const center = (id: string): Point => {
36
+ const [x, y, w, h] = map.nodes[id].box;
37
+ return [x + w / 2, y + h / 2];
38
+ };
39
+ let pos = center(flow[0].node);
40
+ plan.segments.push({ type: "pause", duration: 400, at: pos });
41
+ const jump = (to: Point) => {
42
+ const distance = Math.hypot(to[0] - pos[0], to[1] - pos[1]);
43
+ if (distance < 2) return;
44
+ plan.segments.push({
45
+ type: "jump",
46
+ duration: Math.max(120, distance / 0.28),
47
+ from: pos,
48
+ to,
49
+ });
50
+ pos = to;
51
+ };
52
+ for (const h of flow) {
53
+ const startSegment = plan.segments.length;
54
+ if (h.edge) {
55
+ const ends = pathEnds(map.edges[h.edge].path);
56
+ const [from, to] = h.reverse ? [ends[1], ends[0]] : ends;
57
+ jump(from);
58
+ plan.segments.push({
59
+ type: "travel",
60
+ duration: Math.max(220, geo.length(h.edge) / 0.28),
61
+ edge: h.edge,
62
+ reverse: !!h.reverse,
63
+ from,
64
+ to,
65
+ });
66
+ pos = to;
67
+ } else jump(center(h.node));
68
+ plan.hops.push({
69
+ startSegment,
70
+ segment: plan.segments.length,
71
+ step: s.steps.findIndex((t) => t.id === h.step),
72
+ node: h.node,
73
+ log: h.log,
74
+ fail: !!h.fail,
75
+ });
76
+ plan.segments.push({
77
+ type: "pause",
78
+ duration: h.fail ? 750 : 280,
79
+ at: pos,
80
+ });
81
+ }
82
+ return plan;
83
+ }
84
+ export function appendLog(previous: LogLine[], lines: string[]): LogLine[] {
85
+ return [
86
+ ...previous.map((l) => ({ text: l.text, kind: "old" as const })),
87
+ ...lines.map((text) => ({
88
+ text,
89
+ kind: text.startsWith("Error") ? ("err" as const) : ("new" as const),
90
+ })),
91
+ ];
92
+ }
93
+ export function reducedFlow(
94
+ map: ResolvedMap,
95
+ scenario: number,
96
+ ): {
97
+ trail: string[];
98
+ visited: string[];
99
+ failed: string[];
100
+ log: LogLine[];
101
+ lastStep: number;
102
+ } {
103
+ const s = map.scenarios[scenario];
104
+ const trail = new Set<string>(),
105
+ visited = new Set<string>(),
106
+ failed = new Set<string>();
107
+ let log: LogLine[] = [],
108
+ lastStep = -1;
109
+ for (const h of s.flow ?? []) {
110
+ if (h.edge) trail.add(h.edge);
111
+ (h.fail ? failed : visited).add(h.node);
112
+ log = appendLog(log, h.log);
113
+ lastStep = s.steps.findIndex((t) => t.id === h.step);
114
+ }
115
+ return {
116
+ trail: [...trail],
117
+ visited: [...visited],
118
+ failed: [...failed],
119
+ log,
120
+ lastStep,
121
+ };
122
+ }
@@ -0,0 +1,180 @@
1
+ import type { ResolvedMap } from "../schema.js";
2
+ import type { PlayerState } from "./state.js";
3
+ export interface LogLine {
4
+ text: string;
5
+ kind: "old" | "new" | "err";
6
+ }
7
+ export interface Badge {
8
+ x: number;
9
+ y: number;
10
+ n: number;
11
+ current: boolean;
12
+ }
13
+ export type StepPanel = {
14
+ kind: "step";
15
+ count: string;
16
+ title: string;
17
+ html: string;
18
+ log: LogLine[];
19
+ fix?: string;
20
+ code?: ResolvedMap["code"][string];
21
+ defs: ResolvedMap["definitions"][string][];
22
+ sources: ResolvedMap["scenarios"][number]["steps"][number]["sources"];
23
+ deeper: ResolvedMap["scenarios"][number]["steps"][number]["deeper"];
24
+ canBack: boolean;
25
+ canNext: boolean;
26
+ nextScenario?: string;
27
+ };
28
+ export type AllPanel = {
29
+ kind: "all";
30
+ count: string;
31
+ title: string;
32
+ text: string;
33
+ steps: string[];
34
+ hasFlowLog: boolean;
35
+ };
36
+ export interface Frame {
37
+ state: PlayerState;
38
+ nodes: Record<string, { revealed: boolean; current: boolean; label: string }>;
39
+ edges: Record<string, { revealed: boolean; current: boolean }>;
40
+ lanes: Record<string, { revealed: boolean }>;
41
+ frames: Record<string, { revealed: boolean }>;
42
+ edgeLabels: Record<string, { revealed: boolean; lines: string[] }>;
43
+ badges: Badge[];
44
+ panel: StepPanel | AllPanel;
45
+ }
46
+ export function derive(map: ResolvedMap, state: PlayerState): Frame {
47
+ const s = map.scenarios[state.scenario],
48
+ steps = s.steps,
49
+ all = state.mode === "all";
50
+ const upto = all ? steps.length - 1 : state.step;
51
+ const shown = new Set<string>();
52
+ const first = new Map<string, number>();
53
+ steps.slice(0, upto + 1).forEach((step, i) => {
54
+ step.show.forEach((id) => shown.add(id));
55
+ step.edges.forEach((id) => {
56
+ if (!first.has(id)) first.set(id, i + 1);
57
+ });
58
+ });
59
+ const current = new Set(all ? [] : steps[state.step].current);
60
+ const currentEdges = new Set(all ? [] : steps[state.step].edges);
61
+ const nodes = Object.fromEntries(
62
+ Object.entries(map.nodes).map(([id, node]) => [
63
+ id,
64
+ {
65
+ revealed: shown.has(id),
66
+ current: current.has(id),
67
+ label: s.nodeLabels?.[id] ?? node.label,
68
+ },
69
+ ]),
70
+ );
71
+ const lanes = Object.fromEntries(
72
+ Object.keys(map.lanes).map((id) => [
73
+ id,
74
+ { revealed: [...shown].some((node) => map.nodes[node].lane === id) },
75
+ ]),
76
+ );
77
+ const frames = Object.fromEntries(
78
+ Object.entries(map.frames).map(([id, frame]) => [
79
+ id,
80
+ { revealed: frame.showWith.some((node) => shown.has(node)) },
81
+ ]),
82
+ );
83
+ const edges: Frame["edges"] = {},
84
+ edgeLabels: Frame["edgeLabels"] = {},
85
+ badges: Badge[] = [];
86
+ const repeat = s.repeatBadges ?? [];
87
+ for (const [id, edge] of Object.entries(map.edges)) {
88
+ const revealed = s.display.edges === "all" || first.has(id);
89
+ edges[id] = { revealed, current: currentEdges.has(id) };
90
+ if (edge.label) edgeLabels[id] = { revealed, lines: [edge.label.text] };
91
+ if (
92
+ revealed &&
93
+ edge.badge &&
94
+ (all || s.display.edgeBadges) &&
95
+ first.has(id) &&
96
+ !(
97
+ !all &&
98
+ repeat.some((b) => b.edge === id && b.step === steps[state.step].id)
99
+ )
100
+ ) {
101
+ badges.push({
102
+ x: edge.badge[0],
103
+ y: edge.badge[1],
104
+ n: first.get(id)!,
105
+ current: currentEdges.has(id),
106
+ });
107
+ }
108
+ }
109
+ for (const b of repeat) {
110
+ const index = steps.findIndex((t) => t.id === b.step);
111
+ if ((!all && index !== state.step) || !steps[index]?.edges.includes(b.edge))
112
+ continue;
113
+ badges.push({ x: b.at[0], y: b.at[1], n: index + 1, current: !all });
114
+ }
115
+ if (s.display.nodeBadges)
116
+ steps.forEach((step, i) => {
117
+ if (i > upto || step.edges.length || !step.current.length) return;
118
+ const [x, y, w] = map.nodes[step.current[0]].box;
119
+ badges.push({
120
+ x: x + w - 2,
121
+ y: y + 2,
122
+ n: i + 1,
123
+ current: !all && i === state.step,
124
+ });
125
+ });
126
+ let panel: Frame["panel"];
127
+ if (all)
128
+ panel = {
129
+ kind: "all",
130
+ count: `Whole map · ${steps.length} step${steps.length > 1 ? "s" : ""}`,
131
+ title: s.whole?.title ?? s.label,
132
+ text: `${s.whole?.text ?? "The numbers follow the order of the steps."} Choose a step to walk through it.`,
133
+ steps: steps.map((t) => t.title),
134
+ hasFlowLog: (s.flow ?? []).some((h) => h.log.length > 0),
135
+ };
136
+ else {
137
+ const t = steps[state.step];
138
+ const before =
139
+ t.log?.length && s.display.log !== "cumulative"
140
+ ? steps
141
+ .slice(Math.max(0, state.step - 1), state.step)
142
+ .flatMap((t) => t.log ?? [])
143
+ .slice(-3)
144
+ : [];
145
+ panel = {
146
+ kind: "step",
147
+ count: `${s.display.counterLabel ? s.label + " · " : ""}Step ${state.step + 1} of ${steps.length}`,
148
+ title: t.title,
149
+ html: t.text,
150
+ log: [
151
+ ...before.map((text) => ({ text, kind: "old" as const })),
152
+ ...(t.log ?? []).map((text) => ({
153
+ text,
154
+ kind: text.startsWith("Error") ? ("err" as const) : ("new" as const),
155
+ })),
156
+ ],
157
+ ...(t.fix ? { fix: t.fix } : {}),
158
+ ...(t.code ? { code: map.code[t.code] } : {}),
159
+ defs: t.defs.map((id) => map.definitions[id]),
160
+ sources: t.sources,
161
+ deeper: t.deeper,
162
+ canBack: state.step > 0,
163
+ canNext: state.step < steps.length - 1,
164
+ ...(state.step === steps.length - 1 &&
165
+ state.scenario < map.scenarios.length - 1
166
+ ? { nextScenario: map.scenarios[state.scenario + 1].label }
167
+ : {}),
168
+ };
169
+ }
170
+ return {
171
+ state: { ...state },
172
+ nodes,
173
+ lanes,
174
+ frames,
175
+ edges,
176
+ edgeLabels,
177
+ badges,
178
+ panel,
179
+ };
180
+ }
@@ -0,0 +1,37 @@
1
+ import type { Point } from "./path.js";
2
+ export const labelMinimum = (viewBoxWidth: number, renderedWidth: number) =>
3
+ (10.55 * viewBoxWidth) / renderedWidth;
4
+ export function fitNodeLabels(
5
+ [, y, , h]: number[],
6
+ main: { y: number; height: number },
7
+ tag: { y: number; height: number },
8
+ ) {
9
+ const baseline = { main: y + 17, tag: y + 32 };
10
+ if (
11
+ main.y >= y &&
12
+ main.y + main.height <= tag.y &&
13
+ tag.y + tag.height <= y + h
14
+ )
15
+ return baseline;
16
+ const gap = Math.min(2, Math.max(0, h - main.height - tag.height));
17
+ const top = y + (h - main.height - gap - tag.height) / 2;
18
+ return {
19
+ main: baseline.main + top - main.y,
20
+ tag: baseline.tag + top + main.height + gap - tag.y,
21
+ };
22
+ }
23
+ export function fitEdgeLabel(
24
+ text: string,
25
+ [x, y]: Point,
26
+ viewBoxWidth: number,
27
+ measuredWidth: number,
28
+ fontSize: number,
29
+ ): { text: string; x: number; y: number }[] | null {
30
+ if (measuredWidth <= viewBoxWidth - x - 6 || !text.includes(" ")) return null;
31
+ const words = text.split(" ");
32
+ return words.map((word, index) => ({
33
+ text: word + (index < words.length - 1 ? " " : ""),
34
+ x,
35
+ y: y + (index - (words.length - 1) / 2) * fontSize,
36
+ }));
37
+ }
@@ -0,0 +1,56 @@
1
+ export type Point = [number, number];
2
+ /** Only endpoints are needed here; curve length and intermediate points use Geometry. */
3
+ export function pathEnds(path: string): [Point, Point] {
4
+ const tokens =
5
+ path.match(
6
+ /[a-df-zA-DF-Z]|[-+]?(?:\d*\.\d+|\d+\.?\d*)(?:[eE][-+]?\d+)?/g,
7
+ ) ?? [];
8
+ const arity: Record<string, number> = {
9
+ m: 2,
10
+ l: 2,
11
+ h: 1,
12
+ v: 1,
13
+ c: 6,
14
+ s: 4,
15
+ q: 4,
16
+ t: 2,
17
+ a: 7,
18
+ };
19
+ let i = 0,
20
+ command = "",
21
+ point: Point = [0, 0],
22
+ start: Point = [0, 0],
23
+ first: Point | undefined;
24
+ while (i < tokens.length) {
25
+ if (/^[a-z]$/i.test(tokens[i])) command = tokens[i++];
26
+ const lower = command.toLowerCase();
27
+ if (lower === "z") {
28
+ point = [...start];
29
+ command = "";
30
+ continue;
31
+ }
32
+ const count = arity[lower];
33
+ if (!count || i + count > tokens.length || /^[a-z]$/i.test(tokens[i]))
34
+ throw new Error(`Invalid SVG path: ${path}`);
35
+ const values = tokens.slice(i, (i += count)).map(Number);
36
+ if (values.some((n) => !Number.isFinite(n)))
37
+ throw new Error(`Invalid SVG path: ${path}`);
38
+ const relative = command === lower;
39
+ if (lower === "h")
40
+ point = [values[0] + (relative ? point[0] : 0), point[1]];
41
+ else if (lower === "v")
42
+ point = [point[0], values[0] + (relative ? point[1] : 0)];
43
+ else
44
+ point = [
45
+ values[count - 2] + (relative ? point[0] : 0),
46
+ values[count - 1] + (relative ? point[1] : 0),
47
+ ];
48
+ if (lower === "m") {
49
+ start = [...point];
50
+ first ??= [...point];
51
+ command = relative ? "l" : "L";
52
+ }
53
+ }
54
+ if (!first) throw new Error(`SVG path needs a moveto: ${path}`);
55
+ return [first, point];
56
+ }
@@ -0,0 +1,51 @@
1
+ import type { ResolvedMap } from "../schema.js";
2
+ export type Mode = "step" | "all";
3
+ export interface PlayerState {
4
+ scenario: number;
5
+ step: number;
6
+ mode: Mode;
7
+ }
8
+ export const initialState: Readonly<PlayerState> = {
9
+ scenario: 0,
10
+ step: 0,
11
+ mode: "step",
12
+ };
13
+ export type Action =
14
+ | { type: "next" }
15
+ | { type: "back" }
16
+ | { type: "go"; step: number }
17
+ | { type: "scenario"; index: number }
18
+ | { type: "mode"; mode: Mode }
19
+ | { type: "concept"; scenario: number; step: number }
20
+ | { type: "reset" };
21
+ const clamp = (n: number, count: number) => Math.max(0, Math.min(count - 1, n));
22
+ export function reduce(
23
+ map: ResolvedMap,
24
+ s: PlayerState,
25
+ a: Action,
26
+ ): PlayerState {
27
+ switch (a.type) {
28
+ case "reset":
29
+ return { ...initialState };
30
+ case "mode":
31
+ return { ...s, mode: a.mode };
32
+ case "scenario":
33
+ return { ...s, scenario: clamp(a.index, map.scenarios.length), step: 0 };
34
+ case "concept": {
35
+ const scenario = clamp(a.scenario, map.scenarios.length);
36
+ return {
37
+ scenario,
38
+ step: clamp(a.step, map.scenarios[scenario].steps.length),
39
+ mode: "step",
40
+ };
41
+ }
42
+ default:
43
+ return {
44
+ ...s,
45
+ step: clamp(
46
+ a.type === "go" ? a.step : s.step + (a.type === "next" ? 1 : -1),
47
+ map.scenarios[s.scenario].steps.length,
48
+ ),
49
+ };
50
+ }
51
+ }
@@ -0,0 +1,21 @@
1
+ import type { ResolvedMap } from "../schema.js";
2
+ import { escapeHtml as esc } from "./inline.js";
3
+ export function renderConcepts(map: ResolvedMap): string {
4
+ return `<div class="concepts">${map.concepts
5
+ .map(
6
+ (g) =>
7
+ `<section class="cgroup" style="--c:var(--pw-${esc(g.layer === "app" ? "test" : g.layer)})"><h3><span class="dot" aria-hidden="true"></span>${esc(g.label)}</h3><ul>${g.items
8
+ .map((c) => {
9
+ const scenario = map.scenarios.find(
10
+ (s) => s.id === (c.step.scenario ?? map.conceptScenario),
11
+ )!;
12
+ const index = scenario.steps.findIndex((s) => s.id === c.step.step);
13
+ return `<li data-nodes="${esc(c.nodes.join(" "))}"><span class="term">${esc(map.definitions[c.definition].term)}</span><span class="def">${c.short}</span><span class="meta"><a href="${esc(c.source.url)}" title="${esc(c.source.label)}">Source ↗</a><button type="button" data-step="${index}"${c.step.scenario ? ` data-concept-scenario="${esc(c.step.scenario)}"` : ""}>Step ${index + 1}</button></span></li>`;
14
+ })
15
+ .join("")}</ul></section>`,
16
+ )
17
+ .join("")}</div>`;
18
+ }
19
+ export function renderDeeper(map: ResolvedMap): string {
20
+ return `<ul class="deeper">${map.deeper.map((d) => `<li><a href="${esc(d.href)}">${esc(d.title)}</a><span>${d.why}</span></li>`).join("")}</ul>`;
21
+ }
@@ -0,0 +1,71 @@
1
+ export const escapeHtml = (text: string): string =>
2
+ text
3
+ .replace(/&/g, "&amp;")
4
+ .replace(/</g, "&lt;")
5
+ .replace(/>/g, "&gt;")
6
+ .replace(/"/g, "&quot;");
7
+ /** Make legacy literal marks explicit when authoring inline text. */
8
+ export const escapeMarks = (text: string): string =>
9
+ text.replace(/[\\*`]/g, "\\$&");
10
+ function closing(input: string, start: number, mark: string): number {
11
+ for (let i = start; i < input.length; i++) {
12
+ if (input[i] === "\\" && /[*`\\]/.test(input[i + 1] ?? "")) {
13
+ i++;
14
+ continue;
15
+ }
16
+ if (input[i] === "`") {
17
+ const end = input.indexOf("`", i + 1);
18
+ if (end >= 0) {
19
+ i = end;
20
+ continue;
21
+ }
22
+ }
23
+ if (mark === "*" && input.startsWith("**", i)) {
24
+ const end = closing(input, i + 2, "**");
25
+ if (end >= 0) {
26
+ i = end + 1;
27
+ continue;
28
+ }
29
+ i++;
30
+ continue;
31
+ }
32
+ if (input.startsWith(mark, i)) return i;
33
+ }
34
+ return -1;
35
+ }
36
+ /** Authored strings are text. Only paired inline marks introduce markup. */
37
+ export function renderInline(input: string): string {
38
+ let html = "";
39
+ for (let i = 0; i < input.length;) {
40
+ const ch = input[i];
41
+ if (ch === "\\" && /[*`\\]/.test(input[i + 1] ?? "")) {
42
+ html += escapeHtml(input[i + 1]);
43
+ i += 2;
44
+ continue;
45
+ }
46
+ if (ch === "`") {
47
+ const end = input.indexOf("`", i + 1);
48
+ if (end >= 0) {
49
+ html += `<code>${escapeHtml(input.slice(i + 1, end))}</code>`;
50
+ i = end + 1;
51
+ continue;
52
+ }
53
+ }
54
+ if (ch === "*") {
55
+ const mark = input.startsWith("**", i) ? "**" : "*",
56
+ end = closing(input, i + mark.length, mark);
57
+ if (end >= 0) {
58
+ const tag = mark === "**" ? "strong" : "em";
59
+ html += `<${tag}>${renderInline(input.slice(i + mark.length, end))}</${tag}>`;
60
+ i = end + mark.length;
61
+ continue;
62
+ }
63
+ html += mark;
64
+ i += mark.length;
65
+ continue;
66
+ }
67
+ html += escapeHtml(ch);
68
+ i++;
69
+ }
70
+ return html;
71
+ }
@@ -0,0 +1,69 @@
1
+ import type { ResolvedMap } from "../schema.js";
2
+ import type { Frame } from "../model/frame.js";
3
+ import { escapeHtml as esc } from "./inline.js";
4
+ export const defaultStrings = {
5
+ replay: "Replay the flow",
6
+ callLog: "Call log",
7
+ fix: "Fix:",
8
+ source: "Source",
9
+ sourceLink: "Source ↗",
10
+ newOnMap: "New on the map",
11
+ goDeeper: "Go deeper",
12
+ previousStep: "Previous step",
13
+ nextStep: "Next step",
14
+ stepsGroup: "Steps of this figure",
15
+ step: "Step",
16
+ nextScenario: "Next scenario:",
17
+ hint: "Use ‹ › or the bars to move through this figure. Keyboard: ← →.",
18
+ };
19
+ export type UiStrings = typeof defaultStrings;
20
+ /** Plain text for the figure's live status: announced on each step or view
21
+ * change instead of the whole panel, so controls and hints stay silent. */
22
+ export function statusText(frame: Frame): string {
23
+ return `${frame.panel.count}: ${frame.panel.title}`;
24
+ }
25
+ function parts(map: ResolvedMap, frame: Frame, overrides: Partial<UiStrings>) {
26
+ const ui = { ...defaultStrings, ...overrides },
27
+ p = frame.panel;
28
+ if (p.kind === "all")
29
+ return {
30
+ lead: `<div class="count">${esc(p.count)}</div><h2>${esc(p.title)}</h2><p>${p.text}</p><div class="flowbar"><button type="button" data-role="replay">${esc(ui.replay)}</button></div>`,
31
+ details: `<div class="all"><ol>${p.steps.map((title, n) => `<li data-li="${n}"><button type="button" data-go="${n}"><span class="n">${n + 1}</span><span>${esc(title)}</span></button></li>`).join("")}</ol></div><div class="log" data-role="flowlog"${p.hasFlowLog ? "" : " hidden"}><h3>${esc(ui.callLog)}</h3></div>`,
32
+ controls: "",
33
+ };
34
+ let details = p.log.length
35
+ ? `<div class="log"><h3>${esc(ui.callLog)}</h3>${p.log.map((l) => `<div class="${l.kind}">${esc(l.text)}</div>`).join("")}</div>`
36
+ : "";
37
+ if (p.fix)
38
+ details += `<p class="fix"><strong>${esc(ui.fix)}</strong> ${p.fix}</p>`;
39
+ if (p.code) {
40
+ const c = p.code;
41
+ details += `<div class="code"><div class="ttl"><span>${esc(c.title)}</span>${c.source ? `<a href="${esc(c.source.url)}">${esc(ui.sourceLink)}</a>` : ""}</div><pre>${c.lines.map((l) => `<span class="${l.trim().startsWith("// ✗") ? "bad" : l.trim().startsWith("// ✓") ? "good" : l.trim().startsWith("//") ? "cm" : ""}">${esc(l)}</span>`).join("\n")}</pre></div>`;
42
+ }
43
+ if (p.defs.length)
44
+ details += `<div class="defs"><h3>${esc(ui.newOnMap)}</h3><dl>${p.defs.map((d) => `<div><dt>${esc(d.term)}</dt><dd>${d.text}</dd></div>`).join("")}</dl></div>`;
45
+ details += `<div class="refs"><div class="src"><h3>${esc(ui.source)}</h3><ul>${p.sources.map((s) => `<li><a href="${esc(s.url)}" target="_blank" rel="noopener">${esc(s.label)}</a></li>`).join("")}</ul></div>${p.deeper.length ? `<div><h3>${esc(ui.goDeeper)}</h3><ul>${p.deeper.map((d) => `<li><a href="${esc(d.href)}" target="_blank" rel="noopener">${esc(d.title)}</a></li>`).join("")}</ul></div>` : ""}</div>`;
46
+ const steps = map.scenarios[frame.state.scenario].steps.map((t) => t.title),
47
+ index = frame.state.step;
48
+ return {
49
+ lead: `<div class="count">${esc(p.count)}</div><h2>${esc(p.title)}</h2><p>${p.html}</p>`,
50
+ details,
51
+ controls: `<div class="stepper" role="group" aria-label="${esc(ui.stepsGroup)}"><button type="button" class="sbtn" data-role="back" aria-label="${esc(ui.previousStep)}"${p.canBack ? "" : " disabled"}><svg viewBox="0 0 16 16" aria-hidden="true"><path d="M10 3 5 8l5 5"/></svg></button><ol class="segs">${steps.map((title, n) => `<li><button type="button" data-seg="${n}" aria-label="${esc(ui.step)} ${n + 1}: ${esc(title)}"${n === index ? ' aria-current="step"' : ""} class="${n < index ? "done" : n === index ? "now" : ""}"></button></li>`).join("")}</ol><button type="button" class="sbtn fwd" data-role="next" aria-label="${esc(ui.nextStep)}"${p.canNext ? "" : " disabled"}><svg viewBox="0 0 16 16" aria-hidden="true"><path d="M6 3l5 5-5 5"/></svg></button></div><div class="hint">${p.nextScenario ? `${esc(ui.nextScenario)} <button type="button" class="linkbtn" data-role="nextscenario">${esc(p.nextScenario)}</button>. ` : ""}${esc(ui.hint)}</div>`,
52
+ };
53
+ }
54
+ export function renderPanel(
55
+ map: ResolvedMap,
56
+ frame: Frame,
57
+ strings: Partial<UiStrings> = {},
58
+ ): string {
59
+ const p = parts(map, frame, strings);
60
+ return p.lead + p.details + p.controls;
61
+ }
62
+ export function renderPanelParts(
63
+ map: ResolvedMap,
64
+ frame: Frame,
65
+ strings: Partial<UiStrings> = {},
66
+ ) {
67
+ const p = parts(map, frame, strings);
68
+ return { head: p.lead + p.controls, more: p.details };
69
+ }
@@ -0,0 +1,52 @@
1
+ import type { ResolvedMap } from "../schema.js";
2
+ import { derive, type Frame, type Badge } from "../model/frame.js";
3
+ import { initialState } from "../model/state.js";
4
+ import { escapeHtml as esc } from "./inline.js";
5
+ export function renderBadges(badges: Badge[]): string {
6
+ return badges
7
+ .map(
8
+ (b) =>
9
+ `<g class="badge${b.current ? " cur" : ""}"><circle cx="${b.x}" cy="${b.y}" r="8"></circle><text x="${b.x}" y="${b.y + 0.5}">${b.n}</text></g>`,
10
+ )
11
+ .join("");
12
+ }
13
+ export function renderSvg(
14
+ map: ResolvedMap,
15
+ options: { frame?: Frame; markerId?: string } = {},
16
+ ): string {
17
+ const frame = options.frame ?? derive(map, initialState),
18
+ marker = esc(
19
+ options.markerId ?? `map-arrow-${map.spread.replaceAll(".", "-")}`,
20
+ );
21
+ let html = `<svg viewBox="0 0 ${map.viewBox.join(" ")}" role="img" aria-label="${esc(map.title)}"><defs><marker id="${marker}" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="8" markerHeight="8" markerUnits="userSpaceOnUse" orient="auto-start-reverse"><path d="M0,0 L8,4 L0,8 z" fill="var(--muted-fg)"></path></marker></defs><g data-map-layers>`;
22
+ for (const [id, l] of Object.entries(map.lanes))
23
+ html += `<g class="lane${frame.lanes[id].revealed ? "" : " ghost"}" data-lane="${esc(id)}" style="--c:var(--${esc(l.layer)})"><rect x="${l.x ?? 6}" y="${l.y}" width="${l.w ?? map.viewBox[0] - 12}" height="${l.h}" rx="6"></rect><text x="16" y="${l.y + 16}">${esc(l.label)}</text></g>`;
24
+ for (const [id, f] of Object.entries(map.frames)) {
25
+ const [x, y, w, h] = f.box;
26
+ html += `<g class="frame${frame.frames[id].revealed ? "" : " ghost"}" data-frame="${esc(id)}"><rect x="${x}" y="${y}" width="${w}" height="${h}" rx="5"></rect><text x="${x + w - 8}" y="${y + 16}" text-anchor="end">${esc(f.label)}</text></g>`;
27
+ }
28
+ html += `</g><g data-map-edges>`;
29
+ for (const [id, e] of Object.entries(map.edges))
30
+ html += `<g class="edge${e.dashed ? " dash" : ""}${frame.edges[id].revealed ? "" : " ghost"}${frame.edges[id].current ? " cur" : ""}" data-edge="${esc(id)}"><path d="${esc(e.path)}" marker-end="url(#${marker})"></path></g>`;
31
+ html += `</g><g data-map-nodes>`;
32
+ for (const [id, n] of Object.entries(map.nodes)) {
33
+ const [x, y, w, h] = n.box,
34
+ f = frame.nodes[id];
35
+ const numbers = Object.entries(map.callouts)
36
+ .filter(([, ids]) => ids.includes(id))
37
+ .map(([number]) => number);
38
+ html += `<g class="node${n.custom ? " custom" : ""}${n.fail ? " fail" : ""}${f.revealed ? "" : " ghost"}${f.current ? " cur" : ""}" style="--c:var(--${esc(n.layer)})" data-node="${esc(id)}"${numbers.length ? ` data-callout="${esc(numbers.join(" "))}"` : ""}><rect x="${x}" y="${y}" width="${w}" height="${h}" rx="5"></rect><text x="${x + 10}" y="${y + (n.tag ? 17 : h / 2 + 4.5)}" class="${n.mono ? "mono" : ""}">${esc(f.label)}</text>${n.tag ? `<text x="${x + 10}" y="${y + 32}" class="tag">${esc(n.tag)}</text>` : ""}</g>`;
39
+ }
40
+ html += `</g><g data-map-edge-labels>`;
41
+ for (const [id, e] of Object.entries(map.edges))
42
+ if (e.label)
43
+ html += `<text x="${e.label.at[0]}" y="${e.label.at[1]}" class="etext${frame.edgeLabels[id].revealed ? "" : " ghost"}" data-edge="${esc(id)}">${esc(e.label.text)}</text>`;
44
+ html += `</g><g data-map-badges>${renderBadges(frame.badges)}</g><g data-map-token><circle r="11" class="token-glow" visibility="hidden"></circle><circle r="6" class="token" visibility="hidden"></circle></g><g data-map-callouts>`;
45
+ for (const [number, ids] of Object.entries(map.callouts)) {
46
+ const n = map.nodes[ids[0]];
47
+ if (!n) continue;
48
+ const [x, y] = n.box;
49
+ html += `<g class="callout" data-callout="${esc(number)}"><circle cx="${x + 4}" cy="${y + 4}" r="8"></circle><text x="${x + 4}" y="${y + 4.5}">${esc(number)}</text></g>`;
50
+ }
51
+ return html + `</g></svg>`;
52
+ }