paseo-plugin-mermaid 0.2.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.
@@ -0,0 +1,135 @@
1
+ /**
2
+ * A small Markdown subset for the prose around a diagram.
3
+ *
4
+ * Taking over a timeline item means taking over its text too, so this exists to
5
+ * keep that text readable. It covers what agents actually write around a
6
+ * diagram: headings, paragraphs, lists, code and inline emphasis. Anything else
7
+ * survives as plain text rather than as broken markup.
8
+ */
9
+
10
+ export type Inline =
11
+ | { kind: "text"; text: string }
12
+ | { kind: "bold"; text: string }
13
+ | { kind: "italic"; text: string }
14
+ | { kind: "code"; text: string };
15
+
16
+ export type Block =
17
+ | { kind: "heading"; level: number; content: Inline[] }
18
+ | { kind: "paragraph"; content: Inline[] }
19
+ | { kind: "bullet"; items: Inline[][] }
20
+ | { kind: "ordered"; items: Inline[][]; start: number }
21
+ | { kind: "code"; language: string; text: string }
22
+ | { kind: "quote"; content: Inline[] }
23
+ | { kind: "rule" };
24
+
25
+ const INLINE = /(`[^`]+`|\*\*[^*]+\*\*|__[^_]+__|\*[^*\n]+\*|_[^_\n]+_)/;
26
+
27
+ export function parseInline(text: string): Inline[] {
28
+ const out: Inline[] = [];
29
+ for (const piece of text.split(INLINE)) {
30
+ if (piece.length === 0) continue;
31
+ if (piece.startsWith("`") && piece.endsWith("`") && piece.length > 1) {
32
+ out.push({ kind: "code", text: piece.slice(1, -1) });
33
+ } else if ((piece.startsWith("**") && piece.endsWith("**")) || (piece.startsWith("__") && piece.endsWith("__"))) {
34
+ out.push({ kind: "bold", text: piece.slice(2, -2) });
35
+ } else if ((piece.startsWith("*") && piece.endsWith("*")) || (piece.startsWith("_") && piece.endsWith("_"))) {
36
+ out.push({ kind: "italic", text: piece.slice(1, -1) });
37
+ } else {
38
+ out.push({ kind: "text", text: piece });
39
+ }
40
+ }
41
+ return out;
42
+ }
43
+
44
+ const HEADING = /^(#{1,6})\s+(.*)$/;
45
+ const BULLET = /^\s*[-*+]\s+(.*)$/;
46
+ const ORDERED = /^\s*(\d+)[.)]\s+(.*)$/;
47
+ const QUOTE = /^>\s?(.*)$/;
48
+ const RULE = /^\s*([-*_])\s*(?:\1\s*){2,}$/;
49
+ const FENCE = /^\s*(`{3,}|~{3,})\s*(\S*)\s*$/;
50
+
51
+ export function parseMarkdown(source: string): Block[] {
52
+ const blocks: Block[] = [];
53
+ const lines = source.split("\n");
54
+ let paragraph: string[] = [];
55
+
56
+ const flush = () => {
57
+ const text = paragraph.join(" ").trim();
58
+ if (text.length > 0) blocks.push({ kind: "paragraph", content: parseInline(text) });
59
+ paragraph = [];
60
+ };
61
+
62
+ for (let index = 0; index < lines.length; index += 1) {
63
+ const line = lines[index];
64
+
65
+ const fence = FENCE.exec(line);
66
+ if (fence) {
67
+ flush();
68
+ const body: string[] = [];
69
+ index += 1;
70
+ while (index < lines.length && !FENCE.test(lines[index])) {
71
+ body.push(lines[index]);
72
+ index += 1;
73
+ }
74
+ blocks.push({ kind: "code", language: fence[2], text: body.join("\n") });
75
+ continue;
76
+ }
77
+
78
+ if (line.trim().length === 0) {
79
+ flush();
80
+ continue;
81
+ }
82
+ if (RULE.test(line)) {
83
+ flush();
84
+ blocks.push({ kind: "rule" });
85
+ continue;
86
+ }
87
+
88
+ const heading = HEADING.exec(line);
89
+ if (heading) {
90
+ flush();
91
+ blocks.push({ kind: "heading", level: heading[1].length, content: parseInline(heading[2]) });
92
+ continue;
93
+ }
94
+
95
+ const bullet = BULLET.exec(line);
96
+ if (bullet) {
97
+ flush();
98
+ const items: Inline[][] = [parseInline(bullet[1])];
99
+ while (index + 1 < lines.length) {
100
+ const next = BULLET.exec(lines[index + 1]);
101
+ if (!next) break;
102
+ items.push(parseInline(next[1]));
103
+ index += 1;
104
+ }
105
+ blocks.push({ kind: "bullet", items });
106
+ continue;
107
+ }
108
+
109
+ const ordered = ORDERED.exec(line);
110
+ if (ordered) {
111
+ flush();
112
+ const items: Inline[][] = [parseInline(ordered[2])];
113
+ while (index + 1 < lines.length) {
114
+ const next = ORDERED.exec(lines[index + 1]);
115
+ if (!next) break;
116
+ items.push(parseInline(next[2]));
117
+ index += 1;
118
+ }
119
+ blocks.push({ kind: "ordered", items, start: Number(ordered[1]) });
120
+ continue;
121
+ }
122
+
123
+ const quote = QUOTE.exec(line);
124
+ if (quote) {
125
+ flush();
126
+ blocks.push({ kind: "quote", content: parseInline(quote[1]) });
127
+ continue;
128
+ }
129
+
130
+ paragraph.push(line.trim());
131
+ }
132
+
133
+ flush();
134
+ return blocks;
135
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Splits an assistant message into the parts this plugin renders.
3
+ *
4
+ * A transformer replaces the whole timeline entry, so once a message contains a
5
+ * diagram the plugin owns everything in it. Splitting keeps the prose intact as
6
+ * its own item instead of discarding it.
7
+ */
8
+
9
+ export type Segment =
10
+ | { kind: "text"; text: string }
11
+ | { kind: "mermaid"; source: string };
12
+
13
+ const FENCE = /^[ \t]*(`{3,}|~{3,})[ \t]*([^\s`~]*)[ \t]*$/;
14
+
15
+ /**
16
+ * Walks fenced blocks rather than reaching for one regex: a message can hold a
17
+ * shell block whose contents look like a fence, and only tracking the opening
18
+ * marker gets that right.
19
+ */
20
+ export function segmentMessage(text: string): Segment[] {
21
+ const segments: Segment[] = [];
22
+ const lines = text.split("\n");
23
+ let prose: string[] = [];
24
+ let fence: string | null = null;
25
+ let language = "";
26
+ let body: string[] = [];
27
+
28
+ const flushProse = () => {
29
+ const joined = prose.join("\n").trim();
30
+ if (joined.length > 0) segments.push({ kind: "text", text: joined });
31
+ prose = [];
32
+ };
33
+
34
+ for (const line of lines) {
35
+ const match = FENCE.exec(line);
36
+
37
+ if (fence === null) {
38
+ if (match) {
39
+ fence = match[1];
40
+ language = match[2].toLowerCase();
41
+ body = [];
42
+ } else {
43
+ prose.push(line);
44
+ }
45
+ continue;
46
+ }
47
+
48
+ // A closing fence must be at least as long as the opening one and carry no
49
+ // language, which is how nested fences inside a block stay part of the body.
50
+ if (match && match[1][0] === fence[0] && match[1].length >= fence.length && match[2] === "") {
51
+ if (language === "mermaid") {
52
+ flushProse();
53
+ segments.push({ kind: "mermaid", source: body.join("\n").trim() });
54
+ } else {
55
+ prose.push(`${fence}${language}`, ...body, fence);
56
+ }
57
+ fence = null;
58
+ body = [];
59
+ continue;
60
+ }
61
+
62
+ body.push(line);
63
+ }
64
+
65
+ // An unterminated mermaid fence is claimed anyway, while the diagram is still
66
+ // arriving. Paseo renders ```mermaid fences itself, and it starts the moment the
67
+ // fence opens, so a transformer that politely waits for the closing fence has
68
+ // already lost the item to the host and only wins it back on the next
69
+ // reprojection. That is the whole reason a fresh diagram used to look different
70
+ // from the same diagram after a reload. Other unterminated fences stay prose.
71
+ if (fence !== null) {
72
+ if (language === "mermaid") {
73
+ flushProse();
74
+ segments.push({ kind: "mermaid", source: body.join("\n").trim() });
75
+ } else {
76
+ prose.push(`${fence}${language}`, ...body);
77
+ }
78
+ }
79
+ flushProse();
80
+ return segments;
81
+ }
82
+
83
+ /**
84
+ * True when the source already names a diagram this plugin draws.
85
+ *
86
+ * Half-arrived source parses to nothing, and complaining that it is unsupported
87
+ * would be wrong: it is unfinished, not unsupported.
88
+ */
89
+ export function namesADiagram(source: string): boolean {
90
+ const first = source.split("\n").find((line) => line.trim().length > 0) ?? "";
91
+ return /^(flowchart|graph|sequenceDiagram)\b/.test(first.trim());
92
+ }
93
+
94
+ /** True when the message is worth taking over at all. */
95
+ export function hasMermaid(text: string): boolean {
96
+ return segmentMessage(text).some((segment) => segment.kind === "mermaid");
97
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Mermaid `sequenceDiagram` subset. Same rules as the flowchart parser: pure,
3
+ * synchronous, and honest about the lines it does not interpret.
4
+ */
5
+
6
+ export type MessageStyle = "solid" | "dashed";
7
+ export type ArrowHead = "none" | "open" | "filled" | "async";
8
+
9
+ export interface SeqParticipant {
10
+ id: string;
11
+ label: string;
12
+ actor: boolean;
13
+ }
14
+
15
+ export type SeqEvent =
16
+ | { kind: "message"; from: string; to: string; text: string; style: MessageStyle; arrow: ArrowHead }
17
+ | { kind: "note"; over: string[]; text: string };
18
+
19
+ export interface SequenceDiagram {
20
+ participants: SeqParticipant[];
21
+ events: SeqEvent[];
22
+ skipped: string[];
23
+ }
24
+
25
+ const HEADER = /^\s*sequenceDiagram\s*$/i;
26
+ const PARTICIPANT = /^(participant|actor)\s+([\w.-]+)(?:\s+as\s+(.+))?$/i;
27
+ const NOTE = /^note\s+(?:(over)\s+([\w.,\s-]+)|(?:left|right)\s+of\s+([\w.-]+))\s*:\s*(.*)$/i;
28
+
29
+ /** Longest first so `-->>` is never read as `-->`. */
30
+ const ARROWS: { token: string; style: MessageStyle; arrow: ArrowHead }[] = [
31
+ { token: "--)", style: "dashed", arrow: "async" },
32
+ { token: "-->>", style: "dashed", arrow: "filled" },
33
+ { token: "--x", style: "dashed", arrow: "open" },
34
+ { token: "-->", style: "dashed", arrow: "none" },
35
+ { token: "->>", style: "solid", arrow: "filled" },
36
+ { token: "-)", style: "solid", arrow: "async" },
37
+ { token: "-x", style: "solid", arrow: "open" },
38
+ { token: "->", style: "solid", arrow: "none" },
39
+ ];
40
+
41
+ /** Blocks whose contents still render; only the framing is dropped for now. */
42
+ const BLOCK = /^(loop|alt|else|opt|par|and|critical|rect|break|end|activate|deactivate|autonumber)\b/i;
43
+
44
+ export function parseSequence(source: string): SequenceDiagram | null {
45
+ const lines = source.split("\n");
46
+ if (!lines.some((line) => HEADER.test(line))) return null;
47
+
48
+ const participants = new Map<string, SeqParticipant>();
49
+ const events: SeqEvent[] = [];
50
+ const skipped: string[] = [];
51
+ let started = false;
52
+
53
+ const mention = (id: string) => {
54
+ if (!participants.has(id)) participants.set(id, { id, label: id, actor: false });
55
+ };
56
+
57
+ for (const original of lines) {
58
+ const line = original.replace(/%%.*$/, "").trim();
59
+ if (line.length === 0) continue;
60
+ if (HEADER.test(line)) {
61
+ started = true;
62
+ continue;
63
+ }
64
+ if (!started) continue;
65
+
66
+ const declared = PARTICIPANT.exec(line);
67
+ if (declared) {
68
+ participants.set(declared[2], {
69
+ id: declared[2],
70
+ label: (declared[3] ?? declared[2]).trim(),
71
+ actor: declared[1].toLowerCase() === "actor",
72
+ });
73
+ continue;
74
+ }
75
+
76
+ const note = NOTE.exec(line);
77
+ if (note) {
78
+ const over = (note[2] ?? note[3] ?? "")
79
+ .split(",")
80
+ .map((name) => name.trim())
81
+ .filter((name) => name.length > 0);
82
+ for (const name of over) mention(name);
83
+ events.push({ kind: "note", over, text: note[4].trim() });
84
+ continue;
85
+ }
86
+
87
+ if (BLOCK.test(line)) {
88
+ skipped.push(original.trim());
89
+ continue;
90
+ }
91
+
92
+ const colon = line.indexOf(":");
93
+ const head = colon >= 0 ? line.slice(0, colon) : line;
94
+ const arrow = ARROWS.find((candidate) => head.includes(candidate.token));
95
+ if (!arrow || colon < 0) {
96
+ skipped.push(original.trim());
97
+ continue;
98
+ }
99
+
100
+ const at = head.indexOf(arrow.token);
101
+ const from = head.slice(0, at).trim();
102
+ const to = head.slice(at + arrow.token.length).trim();
103
+ if (!/^[\w.-]+$/.test(from) || !/^[\w.-]+$/.test(to)) {
104
+ skipped.push(original.trim());
105
+ continue;
106
+ }
107
+
108
+ // Order of first appearance is the column order Mermaid uses.
109
+ mention(from);
110
+ mention(to);
111
+ events.push({
112
+ kind: "message",
113
+ from,
114
+ to,
115
+ text: line.slice(colon + 1).trim(),
116
+ style: arrow.style,
117
+ arrow: arrow.arrow,
118
+ });
119
+ }
120
+
121
+ return { participants: [...participants.values()], events, skipped };
122
+ }
@@ -0,0 +1,32 @@
1
+ import type { PluginTimelineItem } from "@getpaseo/plugin";
2
+ import { segmentMessage } from "./segment";
3
+
4
+ export const DIAGRAM_KIND = "mermaid-diagram";
5
+ export const TEXT_KIND = "mermaid-text";
6
+
7
+ /**
8
+ * Turns one message into the items this plugin renders, or leaves it alone.
9
+ *
10
+ * Pure and synchronous because Paseo reruns transformers while reconciling
11
+ * projected history, and because it is the part worth testing.
12
+ */
13
+ export function split(text: string): { items: PluginTimelineItem[] } | undefined {
14
+ const segments = segmentMessage(text);
15
+ // Leave the entry alone unless there is a diagram to draw: Paseo renders
16
+ // ordinary Markdown better than this plugin does.
17
+ if (!segments.some((segment) => segment.kind === "mermaid")) return undefined;
18
+
19
+ // Pushed one branch at a time rather than mapped through a ternary: a ternary
20
+ // produces a union of the two shapes, and TypeScript gives the absent members
21
+ // `?: undefined`, which the JSON-only item type rejects. `push` type-checks
22
+ // each literal on its own.
23
+ const items: PluginTimelineItem[] = [];
24
+ for (const segment of segments) {
25
+ if (segment.kind === "mermaid") {
26
+ items.push({ type: "plugin", kind: DIAGRAM_KIND, version: 1, data: { source: segment.source } });
27
+ } else {
28
+ items.push({ type: "plugin", kind: TEXT_KIND, version: 1, data: { text: segment.text } });
29
+ }
30
+ }
31
+ return { items };
32
+ }
package/shared/zoom.ts ADDED
@@ -0,0 +1,114 @@
1
+ /**
2
+ * The zoom model behind the toolbar, kept pure so it can be tested without
3
+ * mounting anything.
4
+ *
5
+ * Zoom is a multiplier over the scale the drawing was fitted at: 1 is "as
6
+ * fitted", which is what the toolbar labels 100%. This is the same convention
7
+ * as Paseo's own diagram viewport, where the fit transform has scale 1, so a
8
+ * reader who knows one knows the other. The fitted scale itself depends on
9
+ * where the drawing sits: in the row it is `fitScale` from layout.ts, in the
10
+ * pop-out it is `fitBothScale` below.
11
+ */
12
+
13
+ export const ZOOM_MIN = 0.25;
14
+ export const ZOOM_MAX = 4;
15
+ /** Paseo zooms by 1.25 in and 0.8 out; the two are exact inverses. */
16
+ export const ZOOM_STEP = 1.25;
17
+
18
+ const EPSILON = 1e-3;
19
+
20
+ export interface Size {
21
+ width: number;
22
+ height: number;
23
+ }
24
+
25
+ export function clampZoom(zoom: number): number {
26
+ return Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, zoom));
27
+ }
28
+
29
+ /**
30
+ * Snaps away the floating point residue of a multiply-then-divide, so stepping
31
+ * in and back out lands on exactly the value it started from.
32
+ */
33
+ function snap(zoom: number): number {
34
+ return Math.round(zoom * 1e6) / 1e6;
35
+ }
36
+
37
+ export function zoomIn(zoom: number): number {
38
+ return clampZoom(snap(zoom * ZOOM_STEP));
39
+ }
40
+
41
+ export function zoomOut(zoom: number): number {
42
+ return clampZoom(snap(zoom / ZOOM_STEP));
43
+ }
44
+
45
+ export function canZoomIn(zoom: number): boolean {
46
+ return zoom < ZOOM_MAX - EPSILON;
47
+ }
48
+
49
+ export function canZoomOut(zoom: number): boolean {
50
+ return zoom > ZOOM_MIN + EPSILON;
51
+ }
52
+
53
+ export function sameZoom(a: number, b: number): boolean {
54
+ return Math.abs(a - b) < EPSILON;
55
+ }
56
+
57
+ export function zoomLabel(zoom: number): string {
58
+ return `${Math.round(zoom * 100)}%`;
59
+ }
60
+
61
+ /**
62
+ * The zoom that shows the whole drawing across the row.
63
+ *
64
+ * The row's own fit stops shrinking at the readability floor and scrolls
65
+ * sideways past it; "fit to view" is the reader asking to see all of it anyway.
66
+ * It never goes above 1, because the default already grows small drawings as
67
+ * far as they should go, and 1 means the request was already satisfied.
68
+ */
69
+ export function fitRowZoom(rowScale: number, naturalWidth: number, available: number): number {
70
+ if (!(rowScale > 0) || !(naturalWidth > 0) || !(available > 0)) return 1;
71
+ return Math.min(1, snap(available / (naturalWidth * rowScale)));
72
+ }
73
+
74
+ /**
75
+ * The scale that fits a drawing inside both axes of a viewport, with `padding`
76
+ * kept clear on every side. Unlike the row, the pop-out grows a small drawing
77
+ * as far as the window allows: seeing it large is the point of popping out.
78
+ */
79
+ export function fitBothScale(natural: Size, viewport: Size, padding = 0): number {
80
+ const width = viewport.width - padding * 2;
81
+ const height = viewport.height - padding * 2;
82
+ if (!(natural.width > 0) || !(natural.height > 0) || !(width > 0) || !(height > 0)) return 1;
83
+ return Math.min(width / natural.width, height / natural.height);
84
+ }
85
+
86
+ export interface ToolbarState {
87
+ zoomIn: boolean;
88
+ zoomOut: boolean;
89
+ fit: boolean;
90
+ popOut: boolean;
91
+ }
92
+
93
+ /**
94
+ * Which drawing controls are worth pressing right now. A control that would
95
+ * change nothing is shown quiet rather than hidden, so the toolbar keeps its
96
+ * shape and the reader learns where the limits are.
97
+ */
98
+ export function toolbarState({
99
+ zoom,
100
+ fitZoom,
101
+ showCode,
102
+ }: {
103
+ zoom: number;
104
+ fitZoom: number;
105
+ showCode: boolean;
106
+ }): ToolbarState {
107
+ if (showCode) return { zoomIn: false, zoomOut: false, fit: false, popOut: false };
108
+ return {
109
+ zoomIn: canZoomIn(zoom),
110
+ zoomOut: canZoomOut(zoom),
111
+ fit: !sameZoom(zoom, fitZoom),
112
+ popOut: true,
113
+ };
114
+ }