paseo-plugin-mermaid 0.4.2 → 0.5.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,126 @@
1
+ /**
2
+ * The bracket rewrite of shape objects for Paseo's Mermaid renderer. It walks a line its
3
+ * own way and reads each object through the flowchart parser.
4
+ */
5
+
6
+ import {
7
+ type NodeMention,
8
+ OPENERS,
9
+ readNodeMention,
10
+ readShapeFields,
11
+ readStatement,
12
+ scanShapeObject,
13
+ type ShapeField,
14
+ } from "./flowchart";
15
+
16
+ /**
17
+ * Where a node mention can start and where `@{` can be text instead. One match is one
18
+ * piece of a line, found left to right: the `@{` of an object, a double-quoted string, a
19
+ * `%%` comment, an edge label between pipes, an operator, or the `&` and `;` that run one
20
+ * statement into the next. The operators are the ones Mermaid reads, with the lengthened
21
+ * and the `x` and `o` ended forms, so `A---B@{ ... }` and `A--oB@{ ... }` have a `B`.
22
+ */
23
+ // Keep the operators here in step with `OPERATORS` in flowchart.ts: every one the parser reads must also end a mention here.
24
+ const LINE_PIECES = /@\{|"[^"]*(?:"|$)|%%|\|[^|]*(?:\||$)|-{2,}[>ox]|-{3,}|-\.+->?|={2,}[>ox]|={3,}|~{3,}|[&;]/g;
25
+
26
+ /**
27
+ * `source` with each shape object this plugin reads written in Mermaid's bracket syntax,
28
+ * `A@{ shape: db, label: "Orders" }` as `A[("Orders")]`, for a diagram handed to Paseo's
29
+ * own Mermaid renderer. That renderer refuses any source holding `@{`, so left alone such a
30
+ * diagram shows as code even when this plugin understood every object in it.
31
+ *
32
+ * An object that gives no label keeps the last one an earlier mention of the node gave, as
33
+ * in Mermaid (`A[Orders]`, then `A@{ shape: db }`, is a cylinder labelled Orders), and with
34
+ * none it takes the id. Labels are read with the parser's own mention reading; one on a line
35
+ * neither the parser nor the walk here can read is missed, and the id stands in for it.
36
+ *
37
+ * An object stays as it is when `readShapeFields` refuses it, when its shape has no bracket
38
+ * form here, or when its label holds a `"` that a bracket label cannot. Text that is not a
39
+ * node mention is never rewritten: a `@{` in a quoted label, in an edge label or in a
40
+ * comment, or after something other than an id (`A[x]@{ ... }`). Everything else in the
41
+ * source, line breaks included, comes back byte for byte.
42
+ */
43
+ export function classicShapes(source: string): string {
44
+ if (!source.includes("@{")) return source;
45
+ // The last label each node has been given so far, for an object that gives none.
46
+ const labels = new Map<string, string>();
47
+ return source
48
+ .split("\n")
49
+ .map((line) => {
50
+ const rewritten = classicShapesInLine(line, labels);
51
+ // Where the parser reads the line, its reading is the one to keep. It also has the node
52
+ // in front of `A -- text --> B`, which the walk cannot tell from the edge label.
53
+ for (const mention of readStatement(line.replace(/%%.*$/, "").trim())?.mentions ?? []) remember(labels, mention);
54
+ return rewritten;
55
+ })
56
+ .join("\n");
57
+ }
58
+
59
+ /** Notes the label a mention gives, if it gives one, as a bracket label writes it: the parser's line breaks go back to `<br/>`. */
60
+ function remember(labels: Map<string, string>, mention: NodeMention | null): void {
61
+ if (mention?.labelled) labels.set(mention.node.id, mention.node.label.replace(/\n/g, "<br/>"));
62
+ }
63
+
64
+ function classicShapesInLine(line: string, labels: Map<string, string>): string {
65
+ const pieces = new RegExp(LINE_PIECES);
66
+ let result = "";
67
+ let copied = 0;
68
+ // Where the current node mention starts: after the last operator, edge label, `&` or `;`.
69
+ let mention = 0;
70
+ let end = line.length;
71
+ // The mention up to `to` is over: its label counts for any object later on the line.
72
+ const passed = (to: number) => remember(labels, readNodeMention(line.slice(mention, to)));
73
+
74
+ for (let piece = pieces.exec(line); piece; piece = pieces.exec(line)) {
75
+ if (piece[0] === "%%") {
76
+ end = piece.index;
77
+ break;
78
+ }
79
+ if (piece[0] !== "@{") {
80
+ // A quoted string sits inside a mention (`A["x"]`); everything else starts the next one.
81
+ if (piece[0][0] !== '"') {
82
+ passed(piece.index);
83
+ mention = pieces.lastIndex;
84
+ }
85
+ continue;
86
+ }
87
+
88
+ const object = scanShapeObject(line, piece.index + 2);
89
+ if (!object) continue;
90
+ // Whatever this object holds, its text is not looked at again.
91
+ pieces.lastIndex = object.end;
92
+
93
+ const id = /^\s*([\w.-]+)(\s*)$/.exec(line.slice(mention, piece.index));
94
+ if (!id) continue;
95
+ const bracket = bracketForm(id[1], object.fields, labels.get(id[1]));
96
+ if (bracket === null) continue;
97
+
98
+ // Mermaid 11.16 refuses a space before `@{`; the parser is lenient and reads `A @{ ... }`
99
+ // as node A. The spaces go with the object, so the bracket form is one Mermaid accepts.
100
+ result += line.slice(copied, piece.index - id[2].length) + bracket;
101
+ copied = object.end;
102
+ }
103
+ passed(end);
104
+ return result + line.slice(copied);
105
+ }
106
+
107
+ /**
108
+ * The bracket form of the node a shape object gives, label double-quoted, or null when the
109
+ * object cannot be handed over. `earlier` is the label the node was last given before it.
110
+ */
111
+ function bracketForm(id: string, fields: ShapeField[], earlier: string | undefined): string | null {
112
+ const read = readShapeFields(fields);
113
+ if (!read) return null;
114
+ const opener = OPENERS.find(({ shape }) => shape === read.shape);
115
+ if (!opener) return null;
116
+
117
+ // The text as written, `<br/>` and all: Mermaid breaks the line itself. No label, or a
118
+ // blank one, keeps the label given earlier, and with none the id.
119
+ const text = read.label?.value.trim() ?? "";
120
+ const label = text.length > 0 ? text : (earlier ?? id);
121
+ // A bracket label cannot hold a `"`, and the output would turn to garbage. The object's own
122
+ // label has none while `scanShapeObject` refuses one outside a double-quoted value, but a
123
+ // label given earlier can (`A['say "hi"']`).
124
+ if (label.includes('"')) return null;
125
+ return `${opener.open}"${label}"${opener.close}`;
126
+ }
@@ -1,28 +1,48 @@
1
- import { parseFlowchart } from "./flowchart";
1
+ import { type NodeShape, parseFlowchart } from "./flowchart";
2
2
  import { parseSequence } from "./sequence";
3
3
 
4
4
  /** Diagram keywords whose diagrams this plugin draws, in Mermaid's spelling. */
5
5
  const DRAWN = ["flowchart", "graph", "sequenceDiagram"];
6
6
 
7
+ /** Shapes drawn by shearing a View, which needs `skewX`. */
8
+ const SLANTED: ReadonlySet<NodeShape> = new Set(["lean-right", "lean-left", "trapezoid", "trapezoid-top"]);
9
+
10
+ export interface DrawableOptions {
11
+ /**
12
+ * Whether the app can shear a View. React Native on Android drops `skewX`, so
13
+ * there a parallelogram or trapezoid would come out as an upright box, and a
14
+ * diagram with one is left to Mermaid like any other this plugin does not draw.
15
+ * True by default.
16
+ */
17
+ skew?: boolean;
18
+ }
19
+
7
20
  /**
8
21
  * Whether this plugin draws everything in a diagram.
9
22
  *
10
- * When it does not, the message is left to Paseo, whose own renderer runs Mermaid
11
- * and draws every diagram type, so a diagram is not shown with lines missing or as
12
- * bare source. The parsers decide, not a guess from the first word: a line either
13
- * parser reports as skipped is a line this plugin would not draw.
23
+ * When it does not, the diagram goes to Mermaid, which draws every diagram type, so
24
+ * a diagram is not shown with lines missing or as bare source: on Paseo 0.13 and
25
+ * newer through Paseo's Markdown inside the plugin's message, on 0.11 and 0.12 by
26
+ * leaving the whole message to Paseo. The parsers decide, not a guess from the
27
+ * first word: a line either parser reports as skipped is a line this plugin would
28
+ * not draw.
14
29
  *
15
30
  * `pending` is the line being typed while the diagram can still grow, and null once
16
31
  * it cannot. Only `finished` lines are judged while it grows, so a half-typed edge
17
- * never hands the message over and takes it back a moment later, and a diagram with
32
+ * never hands the diagram over and takes it back a moment later, and a diagram with
18
33
  * nothing to draw yet is kept. Finished lines never change, so for one diagram the
19
- * answer only ever moves from this plugin to Paseo, and the renderer swaps at most
20
- * once.
34
+ * answer only ever moves from this plugin to Mermaid, and the renderer swaps at most
35
+ * once. Without skew a slanted shape counts once any finished line has given it,
36
+ * even if a later line gives that node another shape, for the same reason.
21
37
  */
22
- export function drawable(finished: string, pending: string | null): boolean {
38
+ export function drawable(finished: string, pending: string | null, options: DrawableOptions = {}): boolean {
39
+ const skew = options.skew ?? true;
23
40
  const growing = pending !== null;
24
41
  const flow = parseFlowchart(finished);
25
- if (flow) return flow.skipped.length === 0 && (growing || flow.nodes.length > 0);
42
+ if (flow) {
43
+ if (!skew && flow.shapes.some((shape) => SLANTED.has(shape))) return false;
44
+ return flow.skipped.length === 0 && (growing || flow.nodes.length > 0);
45
+ }
26
46
  const sequence = parseSequence(finished);
27
47
  if (sequence) return sequence.skipped.length === 0 && (growing || sequence.participants.length > 0);
28
48
 
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Wraps Mermaid source in a fence for Paseo's Markdown, which renders the diagram
3
+ * with Mermaid itself. A fence closes on a run of backticks at least as long as its
4
+ * own, so it must be longer than any run inside the source.
5
+ */
6
+ export function mermaidFence(source: string): string {
7
+ const longest = Math.max(2, ...(source.match(/`+/g) ?? []).map((run) => run.length));
8
+ const fence = "`".repeat(longest + 1);
9
+ return `${fence}mermaid\n${source}\n${fence}`;
10
+ }
@@ -1,4 +1,6 @@
1
- import { drawable } from "./drawable";
1
+ import { classicShapes } from "./classic-shapes";
2
+ import { type DrawableOptions, drawable } from "./drawable";
3
+ import { mermaidFence } from "./fence";
2
4
 
3
5
  export type FileView = { kind: "empty" } | { kind: "diagram"; source: string } | { kind: "markdown"; markdown: string };
4
6
 
@@ -7,13 +9,9 @@ export type FileView = { kind: "empty" } | { kind: "diagram"; source: string } |
7
9
  * the whole diagram, otherwise a mermaid fence for Paseo's Markdown, which renders
8
10
  * the diagram with Mermaid itself. The file is complete, so nothing is still arriving.
9
11
  */
10
- export function fileView(text: string): FileView {
12
+ export function fileView(text: string, options: DrawableOptions = {}): FileView {
11
13
  const source = text.trim();
12
14
  if (source.length === 0) return { kind: "empty" };
13
- if (drawable(source, null)) return { kind: "diagram", source };
14
- // A fence closes on a run of backticks at least as long as its own, so it must
15
- // be longer than any run inside the source.
16
- const longest = Math.max(2, ...(source.match(/`+/g) ?? []).map((run) => run.length));
17
- const fence = "`".repeat(longest + 1);
18
- return { kind: "markdown", markdown: `${fence}mermaid\n${source}\n${fence}` };
15
+ if (drawable(source, null, options)) return { kind: "diagram", source };
16
+ return { kind: "markdown", markdown: mermaidFence(classicShapes(source)) };
19
17
  }