@pairdraw/mermaid 0.0.0-stage → 0.16.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/LICENSE +21 -0
- package/README.md +4 -2
- package/dist/chunks/detect.js +171 -0
- package/dist/chunks/detect.js.map +1 -0
- package/dist/chunks/flowchart/builder.js +538 -0
- package/dist/chunks/flowchart/builder.js.map +1 -0
- package/dist/chunks/flowchart/parse.js +3763 -0
- package/dist/chunks/flowchart/parse.js.map +1 -0
- package/dist/index.d.ts +155 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/package.json +42 -4
- package/src/detect.ts +14 -0
- package/src/flowchart/builder.ts +418 -0
- package/src/flowchart/model.ts +72 -0
- package/src/flowchart/parse.ts +19 -0
- package/src/flowchart/shapes.ts +105 -0
- package/src/index.ts +13 -0
- package/src/label.ts +37 -0
- package/src/source.ts +51 -0
- package/src/upstream/MERMAID-LICENSE.txt +21 -0
- package/src/upstream/comments.ts +13 -0
- package/src/upstream/flow.d.ts +8 -0
- package/src/upstream/flow.jison +635 -0
- package/src/upstream/flow.js +1099 -0
- package/src/upstream/preprocess.ts +62 -0
- package/src/upstream/regexes.ts +199 -0
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
import * as v from 'valibot'
|
|
2
|
+
import { parse as parseYAML } from 'yaml'
|
|
3
|
+
|
|
4
|
+
import { readLabel, type GrammarText } from '../label'
|
|
5
|
+
import type {
|
|
6
|
+
FlowArrowhead,
|
|
7
|
+
FlowDirection,
|
|
8
|
+
FlowEdge,
|
|
9
|
+
FlowNode,
|
|
10
|
+
FlowStroke,
|
|
11
|
+
FlowSubgraph,
|
|
12
|
+
Flowchart
|
|
13
|
+
} from './model'
|
|
14
|
+
import { bracketShape, shapeNamed } from './shapes'
|
|
15
|
+
|
|
16
|
+
/** An edge as the grammar describes it before its ends are known. */
|
|
17
|
+
interface GrammarLink {
|
|
18
|
+
type: string
|
|
19
|
+
stroke: string
|
|
20
|
+
length?: number
|
|
21
|
+
text?: GrammarText
|
|
22
|
+
id?: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** A `direction` statement inside a subgraph, as the grammar lists it among the members. */
|
|
26
|
+
interface DirectionStatement {
|
|
27
|
+
stmt: 'dir'
|
|
28
|
+
value: string
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const STROKES: Record<string, FlowStroke> = {
|
|
32
|
+
normal: 'normal',
|
|
33
|
+
thick: 'thick',
|
|
34
|
+
dotted: 'dotted',
|
|
35
|
+
invisible: 'invisible'
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const ARROWHEADS: Record<string, FlowArrowhead> = {
|
|
39
|
+
arrow_point: 'arrow',
|
|
40
|
+
arrow_circle: 'circle',
|
|
41
|
+
arrow_cross: 'cross',
|
|
42
|
+
arrow_open: 'none'
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The arrowhead a link's first character opens it with, as in `<-->` or `o--o`. */
|
|
46
|
+
const START_HEADS: Record<string, string> = {
|
|
47
|
+
'<': 'arrow_point',
|
|
48
|
+
x: 'arrow_cross',
|
|
49
|
+
o: 'arrow_circle'
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The arrowhead a link's last character closes it with, and the one that opens it as well. */
|
|
53
|
+
const END_HEADS = new Map([
|
|
54
|
+
['x', { type: 'arrow_cross', opening: 'x' }],
|
|
55
|
+
['>', { type: 'arrow_point', opening: '<' }],
|
|
56
|
+
['o', { type: 'arrow_circle', opening: 'o' }]
|
|
57
|
+
])
|
|
58
|
+
|
|
59
|
+
/** Mermaid's longest edge: more dashes than this count as this many. */
|
|
60
|
+
const MAX_EDGE_LENGTH = 10
|
|
61
|
+
|
|
62
|
+
function direction(text: string): FlowDirection {
|
|
63
|
+
const dir = text.trim()
|
|
64
|
+
if (dir.includes('<')) return 'RL'
|
|
65
|
+
if (dir.includes('^')) return 'BT'
|
|
66
|
+
if (dir.includes('>')) return 'LR'
|
|
67
|
+
if (dir.includes('v')) return 'TB'
|
|
68
|
+
if (dir === 'BT' || dir === 'LR' || dir === 'RL') return dir
|
|
69
|
+
return 'TB'
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function isDirectionStatement(item: unknown): item is DirectionStatement {
|
|
73
|
+
return typeof item === 'object' && item !== null && 'stmt' in item && item.stmt === 'dir'
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** What `@{ … }` data sets that a node keeps; other keys, such as `icon`, are left out. */
|
|
77
|
+
const shapeDataSchema = v.looseObject({
|
|
78
|
+
shape: v.optional(v.string()),
|
|
79
|
+
label: v.optional(v.pipe(v.union([v.string(), v.number()]), v.toString())),
|
|
80
|
+
labelType: v.optional(v.string())
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
type ShapeData = v.InferOutput<typeof shapeDataSchema>
|
|
84
|
+
|
|
85
|
+
/** `@{ … }` data, which is YAML, written as a flow mapping when it fits on one line. */
|
|
86
|
+
function shapeData(text: string): ShapeData {
|
|
87
|
+
const data: unknown = parseYAML(text.includes('\n') ? `${text}\n` : `{\n${text}\n}`)
|
|
88
|
+
const parsed = v.safeParse(shapeDataSchema, data)
|
|
89
|
+
return parsed.success ? parsed.output : {}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function arrowheads(type: string): { startArrow: FlowArrowhead; endArrow: FlowArrowhead } {
|
|
93
|
+
if (type.startsWith('double_')) {
|
|
94
|
+
const head = ARROWHEADS[type.slice('double_'.length)] ?? 'arrow'
|
|
95
|
+
return { startArrow: head, endArrow: head }
|
|
96
|
+
}
|
|
97
|
+
return { startArrow: 'none', endArrow: ARROWHEADS[type] ?? 'arrow' }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The `yy` object Mermaid's flowchart grammar calls as it parses, building a `Flowchart`. It
|
|
102
|
+
* keeps the meaning Mermaid's `FlowDB` gives each call in the pinned release (MIT, Copyright (c)
|
|
103
|
+
* 2014 - 2022 Knut Sveidqvist), without what only Mermaid's renderer needs: DOM ids, click
|
|
104
|
+
* callbacks, sanitizing for the page, and edge animation.
|
|
105
|
+
*/
|
|
106
|
+
export class FlowchartBuilder {
|
|
107
|
+
private dir: FlowDirection = 'TB'
|
|
108
|
+
private readonly nodes = new Map<string, FlowNode>()
|
|
109
|
+
private readonly edges: FlowEdge[] = []
|
|
110
|
+
private readonly subgraphs: FlowSubgraph[] = []
|
|
111
|
+
private readonly classDefs = new Map<string, string[]>()
|
|
112
|
+
private defaultEdgeStyle: string[] = []
|
|
113
|
+
private subgraphCount = 0
|
|
114
|
+
private firstGraphSeen = false
|
|
115
|
+
private accessibleTitle?: string
|
|
116
|
+
private accessibleDescription?: string
|
|
117
|
+
|
|
118
|
+
readonly lex = {
|
|
119
|
+
/** True for the first `graph`/`flowchart` keyword only; a later one is text. */
|
|
120
|
+
firstGraph: () => {
|
|
121
|
+
if (this.firstGraphSeen) return false
|
|
122
|
+
this.firstGraphSeen = true
|
|
123
|
+
return true
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The calls the grammar makes, as the plain object it copies them from: JISON copies `yy`'s
|
|
129
|
+
* enumerable properties into its own state, which leaves out a class's methods.
|
|
130
|
+
*/
|
|
131
|
+
grammarCalls() {
|
|
132
|
+
return {
|
|
133
|
+
lex: this.lex,
|
|
134
|
+
setDirection: this.setDirection.bind(this),
|
|
135
|
+
setAccTitle: this.setAccTitle.bind(this),
|
|
136
|
+
setAccDescription: this.setAccDescription.bind(this),
|
|
137
|
+
addVertex: this.addVertex.bind(this),
|
|
138
|
+
destructLink: this.destructLink.bind(this),
|
|
139
|
+
addLink: this.addLink.bind(this),
|
|
140
|
+
updateLinkInterpolate: this.updateLinkInterpolate.bind(this),
|
|
141
|
+
updateLink: this.updateLink.bind(this),
|
|
142
|
+
addClass: this.addClass.bind(this),
|
|
143
|
+
setClass: this.setClass.bind(this),
|
|
144
|
+
setLink: this.setLink.bind(this),
|
|
145
|
+
setTooltip: this.setTooltip.bind(this),
|
|
146
|
+
setClickEvent: this.setClickEvent.bind(this),
|
|
147
|
+
addSubGraph: this.addSubGraph.bind(this)
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
result(title?: string): Flowchart {
|
|
152
|
+
// `style` and `class` statements naming a subgraph style the subgraph, though the grammar
|
|
153
|
+
// reports them as nodes.
|
|
154
|
+
const subgraphIds = new Set(this.subgraphs.map((subgraph) => subgraph.id))
|
|
155
|
+
for (const subgraph of this.subgraphs) {
|
|
156
|
+
const node = this.nodes.get(subgraph.id)
|
|
157
|
+
if (!node) continue
|
|
158
|
+
subgraph.styles.push(...node.styles)
|
|
159
|
+
subgraph.classes.push(...node.classes)
|
|
160
|
+
}
|
|
161
|
+
return {
|
|
162
|
+
direction: this.dir,
|
|
163
|
+
nodes: [...this.nodes.values()].filter((node) => !subgraphIds.has(node.id)),
|
|
164
|
+
edges: this.edges.map((edge) => ({
|
|
165
|
+
...edge,
|
|
166
|
+
styles: [...this.defaultEdgeStyle, ...edge.styles]
|
|
167
|
+
})),
|
|
168
|
+
subgraphs: this.subgraphs,
|
|
169
|
+
classDefs: this.classDefs,
|
|
170
|
+
title,
|
|
171
|
+
accessibleTitle: this.accessibleTitle,
|
|
172
|
+
accessibleDescription: this.accessibleDescription
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
setDirection(dir: string): void {
|
|
177
|
+
this.dir = direction(dir)
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
setAccTitle(text: string): void {
|
|
181
|
+
this.accessibleTitle = text
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
setAccDescription(text: string): void {
|
|
185
|
+
this.accessibleDescription = text
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
addVertex(
|
|
189
|
+
id: string,
|
|
190
|
+
text?: GrammarText,
|
|
191
|
+
type?: string,
|
|
192
|
+
styles?: string[],
|
|
193
|
+
classes?: string[],
|
|
194
|
+
_dir?: string,
|
|
195
|
+
_props?: Record<string, unknown>,
|
|
196
|
+
metadata?: string
|
|
197
|
+
): void {
|
|
198
|
+
if (!id || id.trim().length === 0) return
|
|
199
|
+
const data = metadata === undefined ? undefined : shapeData(metadata)
|
|
200
|
+
// An edge's id, or `@{ … }` after a subgraph's, names that edge or subgraph, not a node;
|
|
201
|
+
// the data it carries is animation and the like, which nothing here draws.
|
|
202
|
+
if (this.edges.some((edge) => edge.id === id) || (data && this.isSubgraph(id))) return
|
|
203
|
+
let node = this.nodes.get(id)
|
|
204
|
+
if (!node) {
|
|
205
|
+
node = {
|
|
206
|
+
id,
|
|
207
|
+
label: { text: id, format: 'text' },
|
|
208
|
+
shape: 'rect',
|
|
209
|
+
classes: [],
|
|
210
|
+
styles: []
|
|
211
|
+
}
|
|
212
|
+
this.nodes.set(id, node)
|
|
213
|
+
}
|
|
214
|
+
if (text) node.label = readLabel(text)
|
|
215
|
+
if (type !== undefined) node.shape = bracketShape(type)
|
|
216
|
+
if (styles) node.styles.push(...styles)
|
|
217
|
+
if (classes) node.classes.push(...classes)
|
|
218
|
+
if (!data) return
|
|
219
|
+
if (typeof data.shape === 'string') {
|
|
220
|
+
const shape = data.shape === data.shape.toLowerCase() ? shapeNamed(data.shape) : null
|
|
221
|
+
if (!shape) throw new Error(`No such shape: ${data.shape}.`)
|
|
222
|
+
node.shape = shape
|
|
223
|
+
}
|
|
224
|
+
if (typeof data.label === 'string') {
|
|
225
|
+
node.label = readLabel({
|
|
226
|
+
text: data.label,
|
|
227
|
+
type: data.labelType === 'text' || data.labelType === 'string' ? 'text' : 'markdown'
|
|
228
|
+
})
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
destructLink(end: string, start?: string): GrammarLink {
|
|
233
|
+
const info = this.endOfLink(end)
|
|
234
|
+
if (!start) return info
|
|
235
|
+
const begin = this.startOfLink(start)
|
|
236
|
+
if (begin.stroke !== info.stroke) return { type: 'INVALID', stroke: 'INVALID' }
|
|
237
|
+
if (begin.type === 'arrow_open') return { ...info, type: info.type }
|
|
238
|
+
if (begin.type !== info.type) return { type: 'INVALID', stroke: 'INVALID' }
|
|
239
|
+
return { ...info, type: `double_${begin.type}` }
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
addLink(starts: string[], ends: string[], link: GrammarLink): void {
|
|
243
|
+
const id = link.id?.replace('@', '')
|
|
244
|
+
for (const from of starts) {
|
|
245
|
+
for (const to of ends) {
|
|
246
|
+
// In `A e1@--> B & C`, the id names the edge from the last start to the first end.
|
|
247
|
+
const named = from === starts.at(-1) && to === ends[0]
|
|
248
|
+
this.addEdge(from, to, link, named ? id : undefined)
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
updateLinkInterpolate(): void {
|
|
254
|
+
// Curve styles are Mermaid's renderer's; connectors take their own line type.
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
updateLink(positions: ('default' | number)[], styles: string[]): void {
|
|
258
|
+
for (const position of positions) {
|
|
259
|
+
if (position === 'default') {
|
|
260
|
+
this.defaultEdgeStyle = styles
|
|
261
|
+
continue
|
|
262
|
+
}
|
|
263
|
+
const edge = this.edges.at(position)
|
|
264
|
+
if (!edge || position < 0) {
|
|
265
|
+
throw new Error(
|
|
266
|
+
`The index ${position} for linkStyle is out of bounds. Valid indices for linkStyle are between 0 and ${this.edges.length - 1}.`
|
|
267
|
+
)
|
|
268
|
+
}
|
|
269
|
+
edge.styles = styles
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
addClass(ids: string, styles: string[]): void {
|
|
274
|
+
// Commas and semicolons separate declarations; an escaped comma, as in `font-family:a\,b`,
|
|
275
|
+
// is part of one.
|
|
276
|
+
const declarations = styles
|
|
277
|
+
.join(',')
|
|
278
|
+
.split(/(?<!\\)[,;]/)
|
|
279
|
+
.map((declaration) => declaration.replaceAll('\\,', ','))
|
|
280
|
+
for (const id of ids.split(',')) {
|
|
281
|
+
const existing = this.classDefs.get(id) ?? []
|
|
282
|
+
this.classDefs.set(id, [...existing, ...declarations])
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
setClass(ids: string, className: string): void {
|
|
287
|
+
for (const id of ids.split(',')) {
|
|
288
|
+
const subgraph = this.subgraphs.find((candidate) => candidate.id === id)
|
|
289
|
+
if (subgraph) subgraph.classes.push(className)
|
|
290
|
+
else this.nodes.get(id)?.classes.push(className)
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
setLink(ids: string, href: string, target?: string): void {
|
|
295
|
+
for (const id of ids.split(',')) {
|
|
296
|
+
const node = this.nodes.get(id)
|
|
297
|
+
if (node) node.link = target ? { href, target } : { href }
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
setTooltip(ids: string, tooltip?: string): void {
|
|
302
|
+
if (tooltip === undefined) return
|
|
303
|
+
for (const id of ids.split(',')) {
|
|
304
|
+
const node = this.nodes.get(id)
|
|
305
|
+
if (node) node.tooltip = tooltip
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
setClickEvent(): void {
|
|
310
|
+
// Callbacks run scripts on Mermaid's page; a design layer has none to run.
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
addSubGraph(
|
|
314
|
+
idText: GrammarText | undefined,
|
|
315
|
+
list: unknown[],
|
|
316
|
+
titleText: GrammarText | undefined
|
|
317
|
+
): string {
|
|
318
|
+
// `subgraph Some title` gives the title as the id too; an id with spaces is no id.
|
|
319
|
+
let id = idText?.text.trim()
|
|
320
|
+
if (idText && idText === titleText && /\s/.test(idText.text)) id = undefined
|
|
321
|
+
let dir: FlowDirection | undefined
|
|
322
|
+
const members: string[] = []
|
|
323
|
+
for (const item of list.flat()) {
|
|
324
|
+
if (isDirectionStatement(item)) {
|
|
325
|
+
dir = direction(item.value)
|
|
326
|
+
continue
|
|
327
|
+
}
|
|
328
|
+
if (typeof item !== 'string' || item.trim() === '' || members.includes(item)) continue
|
|
329
|
+
members.push(item)
|
|
330
|
+
}
|
|
331
|
+
const subgraphId = id ?? `subGraph${this.subgraphCount}`
|
|
332
|
+
this.subgraphCount++
|
|
333
|
+
// A node belongs to the subgraph that closes first, which is the innermost one, and a
|
|
334
|
+
// subgraph never holds itself.
|
|
335
|
+
const own = members.filter(
|
|
336
|
+
(member) =>
|
|
337
|
+
member !== subgraphId &&
|
|
338
|
+
!this.subgraphs.some((subgraph) => subgraph.members.includes(member))
|
|
339
|
+
)
|
|
340
|
+
const existing = this.subgraphs.find((subgraph) => subgraph.id === subgraphId)
|
|
341
|
+
if (existing) {
|
|
342
|
+
// A repeated id adds to the first declaration, which keeps its title and direction.
|
|
343
|
+
existing.members.push(...own)
|
|
344
|
+
return subgraphId
|
|
345
|
+
}
|
|
346
|
+
this.subgraphs.push({
|
|
347
|
+
id: subgraphId,
|
|
348
|
+
title: titleText ? readLabel(titleText) : { text: '', format: 'text' },
|
|
349
|
+
members: own,
|
|
350
|
+
direction: dir,
|
|
351
|
+
classes: [],
|
|
352
|
+
styles: []
|
|
353
|
+
})
|
|
354
|
+
return subgraphId
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
private isSubgraph(id: string): boolean {
|
|
358
|
+
return this.subgraphs.some((subgraph) => subgraph.id === id)
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
private addEdge(from: string, to: string, link: GrammarLink, id?: string): void {
|
|
362
|
+
const label = link.text && readLabel(link.text)
|
|
363
|
+
const edgeId =
|
|
364
|
+
id && !this.edges.some((edge) => edge.id === id)
|
|
365
|
+
? id
|
|
366
|
+
: `L_${from}_${to}_${this.edges.filter((edge) => edge.from === from && edge.to === to).length}`
|
|
367
|
+
this.edges.push({
|
|
368
|
+
id: edgeId,
|
|
369
|
+
from,
|
|
370
|
+
to,
|
|
371
|
+
...(label && label.text !== '' ? { label } : {}),
|
|
372
|
+
...arrowheads(link.type),
|
|
373
|
+
stroke: STROKES[link.stroke] ?? 'normal',
|
|
374
|
+
length: Math.min(link.length ?? 1, MAX_EDGE_LENGTH),
|
|
375
|
+
styles: []
|
|
376
|
+
})
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
private startOfLink(text: string): { type: string; stroke: string } {
|
|
380
|
+
let rest = text.trim()
|
|
381
|
+
let type = 'arrow_open'
|
|
382
|
+
const head = rest[0]
|
|
383
|
+
const opening = head && START_HEADS[head]
|
|
384
|
+
if (opening) {
|
|
385
|
+
type = opening
|
|
386
|
+
rest = rest.slice(1)
|
|
387
|
+
}
|
|
388
|
+
let stroke = 'normal'
|
|
389
|
+
if (rest.includes('=')) stroke = 'thick'
|
|
390
|
+
if (rest.includes('.')) stroke = 'dotted'
|
|
391
|
+
return { type, stroke }
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
private endOfLink(text: string): GrammarLink {
|
|
395
|
+
const link = text.trim()
|
|
396
|
+
let line = link.slice(0, -1)
|
|
397
|
+
let type = 'arrow_open'
|
|
398
|
+
const tail = link.slice(-1)
|
|
399
|
+
const head = END_HEADS.get(tail)
|
|
400
|
+
if (head) {
|
|
401
|
+
type = head.type
|
|
402
|
+
if (link.startsWith(head.opening)) {
|
|
403
|
+
type = `double_${type}`
|
|
404
|
+
line = line.slice(1)
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
let stroke = 'normal'
|
|
408
|
+
let length = line.length - 1
|
|
409
|
+
if (line.startsWith('=')) stroke = 'thick'
|
|
410
|
+
if (line.startsWith('~')) stroke = 'invisible'
|
|
411
|
+
const dots = line.split('.').length - 1
|
|
412
|
+
if (dots) {
|
|
413
|
+
stroke = 'dotted'
|
|
414
|
+
length = dots
|
|
415
|
+
}
|
|
416
|
+
return { type, stroke, length }
|
|
417
|
+
}
|
|
418
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { FlowShape } from './shapes'
|
|
2
|
+
|
|
3
|
+
/** The way a flowchart, or a subgraph inside one, lays its nodes out: top to bottom, and so on. */
|
|
4
|
+
export type FlowDirection = 'TB' | 'BT' | 'LR' | 'RL'
|
|
5
|
+
|
|
6
|
+
/** A label's text; `markdown` text came in backticks and may hold `**bold**` and `*italic*`. */
|
|
7
|
+
export interface FlowLabel {
|
|
8
|
+
text: string
|
|
9
|
+
format: 'text' | 'markdown'
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface FlowNode {
|
|
13
|
+
id: string
|
|
14
|
+
label: FlowLabel
|
|
15
|
+
shape: FlowShape
|
|
16
|
+
/** Class names in the order they were given, `classDef` names among them. */
|
|
17
|
+
classes: string[]
|
|
18
|
+
/** CSS declarations from `style` statements, as written (`fill:#f9f`). */
|
|
19
|
+
styles: string[]
|
|
20
|
+
/** Where `click` sends a reader, with its target window when given. */
|
|
21
|
+
link?: { href: string; target?: string }
|
|
22
|
+
tooltip?: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** What an edge's end is drawn with. */
|
|
26
|
+
export type FlowArrowhead = 'none' | 'arrow' | 'circle' | 'cross'
|
|
27
|
+
|
|
28
|
+
/** How an edge's line is drawn: `-->`, `==>`, `-.->`, or `~~~`, which lays out but is not drawn. */
|
|
29
|
+
export type FlowStroke = 'normal' | 'thick' | 'dotted' | 'invisible'
|
|
30
|
+
|
|
31
|
+
export interface FlowEdge {
|
|
32
|
+
id: string
|
|
33
|
+
from: string
|
|
34
|
+
to: string
|
|
35
|
+
label?: FlowLabel
|
|
36
|
+
startArrow: FlowArrowhead
|
|
37
|
+
endArrow: FlowArrowhead
|
|
38
|
+
stroke: FlowStroke
|
|
39
|
+
/** How many ranks the edge spans at least: one more for each extra dash, dot, or equals sign. */
|
|
40
|
+
length: number
|
|
41
|
+
/** CSS declarations from `linkStyle`, the default ones first. */
|
|
42
|
+
styles: string[]
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface FlowSubgraph {
|
|
46
|
+
id: string
|
|
47
|
+
title: FlowLabel
|
|
48
|
+
/** Ids of the nodes and subgraphs it holds, each in exactly one subgraph. */
|
|
49
|
+
members: string[]
|
|
50
|
+
/** Its own `direction`, when it sets one. */
|
|
51
|
+
direction?: FlowDirection
|
|
52
|
+
classes: string[]
|
|
53
|
+
/** CSS declarations from `style` statements naming the subgraph. */
|
|
54
|
+
styles: string[]
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A Mermaid flowchart (`flowchart` or `graph`) as written, before anything lays it out. */
|
|
58
|
+
export interface Flowchart {
|
|
59
|
+
direction: FlowDirection
|
|
60
|
+
/** Nodes in the order they first appear. */
|
|
61
|
+
nodes: FlowNode[]
|
|
62
|
+
/** Edges in the order they appear, which is the order `linkStyle` numbers them in. */
|
|
63
|
+
edges: FlowEdge[]
|
|
64
|
+
/** Subgraphs in the order they close, so a subgraph comes after those inside it. */
|
|
65
|
+
subgraphs: FlowSubgraph[]
|
|
66
|
+
/** `classDef` declarations by class name; `default` applies to every node. */
|
|
67
|
+
classDefs: Map<string, string[]>
|
|
68
|
+
/** The front matter's `title`. */
|
|
69
|
+
title?: string
|
|
70
|
+
accessibleTitle?: string
|
|
71
|
+
accessibleDescription?: string
|
|
72
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { prepareSource } from '../source'
|
|
2
|
+
import flowParser from '../upstream/flow.js'
|
|
3
|
+
import { FlowchartBuilder } from './builder'
|
|
4
|
+
import type { Flowchart } from './model'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A Mermaid flowchart (`flowchart …` or `graph …`) read into its model. Throws Mermaid's parse
|
|
8
|
+
* error, which names the line and what was expected, when the text is not a flowchart.
|
|
9
|
+
*/
|
|
10
|
+
export function parseFlowchart(text: string): Flowchart {
|
|
11
|
+
const { code, title } = prepareSource(text)
|
|
12
|
+
const builder = new FlowchartBuilder()
|
|
13
|
+
// The grammar keeps its state in `yy` and its own lexer, so each parse gets a fresh copy.
|
|
14
|
+
const parser = Object.create(flowParser) as typeof flowParser
|
|
15
|
+
parser.yy = builder.grammarCalls()
|
|
16
|
+
// Mermaid drops spaces after a closing brace at a line's end, which its grammar trips over.
|
|
17
|
+
parser.parse(code.replace(/}\s*\n/g, '}\n'))
|
|
18
|
+
return builder.result(title)
|
|
19
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mermaid's flowchart shapes by their short names, with the other names `@{ shape: … }` accepts
|
|
3
|
+
* for each, from `rendering-util/rendering-elements/shapes.ts` in the pinned Mermaid release
|
|
4
|
+
* (MIT, Copyright (c) 2014 - 2022 Knut Sveidqvist). `bun run generate:mermaid-sources --check`
|
|
5
|
+
* reports when a newer release changes that file.
|
|
6
|
+
*/
|
|
7
|
+
const SHAPE_NAMES = {
|
|
8
|
+
rect: ['proc', 'process', 'rectangle', 'squareRect'],
|
|
9
|
+
rounded: ['event', 'roundedRect'],
|
|
10
|
+
stadium: ['terminal', 'pill'],
|
|
11
|
+
'fr-rect': ['subprocess', 'subproc', 'framed-rectangle', 'subroutine'],
|
|
12
|
+
cyl: ['db', 'database', 'cylinder'],
|
|
13
|
+
datastore: ['data-store'],
|
|
14
|
+
folder: ['directory'],
|
|
15
|
+
bucket: [],
|
|
16
|
+
console: [],
|
|
17
|
+
browser: [],
|
|
18
|
+
person: [],
|
|
19
|
+
circle: ['circ'],
|
|
20
|
+
bang: [],
|
|
21
|
+
cloud: [],
|
|
22
|
+
diam: ['decision', 'diamond', 'question'],
|
|
23
|
+
hex: ['hexagon', 'prepare'],
|
|
24
|
+
'lean-r': ['lean-right', 'in-out', 'lean_right'],
|
|
25
|
+
'lean-l': ['lean-left', 'out-in', 'lean_left'],
|
|
26
|
+
'trap-b': ['priority', 'trapezoid-bottom', 'trapezoid'],
|
|
27
|
+
'trap-t': ['manual', 'trapezoid-top', 'inv-trapezoid', 'inv_trapezoid'],
|
|
28
|
+
'dbl-circ': ['double-circle', 'doublecircle'],
|
|
29
|
+
text: [],
|
|
30
|
+
'notch-rect': ['card', 'notched-rectangle'],
|
|
31
|
+
'lin-rect': ['lined-rectangle', 'lined-process', 'lin-proc', 'shaded-process'],
|
|
32
|
+
'sm-circ': ['start', 'small-circle', 'stateStart'],
|
|
33
|
+
'fr-circ': ['stop', 'framed-circle', 'stateEnd'],
|
|
34
|
+
fork: ['join', 'forkJoin'],
|
|
35
|
+
hourglass: ['collate'],
|
|
36
|
+
brace: ['comment', 'brace-l'],
|
|
37
|
+
'brace-r': [],
|
|
38
|
+
braces: [],
|
|
39
|
+
bolt: ['com-link', 'lightning-bolt'],
|
|
40
|
+
doc: ['document'],
|
|
41
|
+
delay: ['half-rounded-rectangle'],
|
|
42
|
+
'h-cyl': ['das', 'horizontal-cylinder'],
|
|
43
|
+
'lin-cyl': ['disk', 'lined-cylinder'],
|
|
44
|
+
'curv-trap': ['curved-trapezoid', 'display'],
|
|
45
|
+
'div-rect': ['div-proc', 'divided-rectangle', 'divided-process'],
|
|
46
|
+
tri: ['extract', 'triangle'],
|
|
47
|
+
'win-pane': ['internal-storage', 'window-pane'],
|
|
48
|
+
'f-circ': ['junction', 'filled-circle'],
|
|
49
|
+
'notch-pent': ['loop-limit', 'notched-pentagon'],
|
|
50
|
+
'flip-tri': ['manual-file', 'flipped-triangle'],
|
|
51
|
+
'sl-rect': ['manual-input', 'sloped-rectangle'],
|
|
52
|
+
docs: ['documents', 'st-doc', 'stacked-document'],
|
|
53
|
+
'st-rect': ['procs', 'processes', 'stacked-rectangle'],
|
|
54
|
+
'bow-rect': ['stored-data', 'bow-tie-rectangle'],
|
|
55
|
+
'cross-circ': ['summary', 'crossed-circle'],
|
|
56
|
+
'tag-doc': ['tagged-document'],
|
|
57
|
+
'tag-rect': ['tagged-rectangle', 'tag-proc', 'tagged-process'],
|
|
58
|
+
flag: ['paper-tape'],
|
|
59
|
+
odd: ['rect_left_inv_arrow'],
|
|
60
|
+
'lin-doc': ['lined-document']
|
|
61
|
+
} as const satisfies Record<string, readonly string[]>
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* A flowchart node's shape, by Mermaid's short name for it, or `ellipse` for `A(-text-)`, which
|
|
65
|
+
* Mermaid's grammar reads but its renderer refuses (mermaid-js/mermaid#5976).
|
|
66
|
+
*/
|
|
67
|
+
export type FlowShape = keyof typeof SHAPE_NAMES | 'ellipse'
|
|
68
|
+
|
|
69
|
+
const SHAPE_BY_NAME = new Map<string, FlowShape>(
|
|
70
|
+
Object.entries(SHAPE_NAMES).flatMap(([shape, aliases]) =>
|
|
71
|
+
[shape, ...aliases].map((name) => [name, shape as FlowShape] as const)
|
|
72
|
+
)
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
/** The shape a name from `@{ shape: … }` stands for, or null for one Mermaid does not know. */
|
|
76
|
+
export function shapeNamed(name: string): FlowShape | null {
|
|
77
|
+
return SHAPE_BY_NAME.get(name) ?? null
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The shape each bracket form stands for, by the vertex type Mermaid's grammar gives it: `[ ]` a
|
|
82
|
+
* rectangle, `( )` a rounded one, `([ ])` a stadium, and so on.
|
|
83
|
+
*/
|
|
84
|
+
const BRACKET_SHAPES: Record<string, FlowShape> = {
|
|
85
|
+
square: 'rect',
|
|
86
|
+
rect: 'rect',
|
|
87
|
+
round: 'rounded',
|
|
88
|
+
ellipse: 'ellipse',
|
|
89
|
+
stadium: 'stadium',
|
|
90
|
+
subroutine: 'fr-rect',
|
|
91
|
+
cylinder: 'cyl',
|
|
92
|
+
circle: 'circle',
|
|
93
|
+
doublecircle: 'dbl-circ',
|
|
94
|
+
diamond: 'diam',
|
|
95
|
+
hexagon: 'hex',
|
|
96
|
+
odd: 'odd',
|
|
97
|
+
trapezoid: 'trap-b',
|
|
98
|
+
inv_trapezoid: 'trap-t',
|
|
99
|
+
lean_right: 'lean-r',
|
|
100
|
+
lean_left: 'lean-l'
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function bracketShape(vertexType: string): FlowShape {
|
|
104
|
+
return BRACKET_SHAPES[vertexType] ?? 'rect'
|
|
105
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export { detectMermaidDiagram, type MermaidDiagramType } from './detect'
|
|
2
|
+
export type {
|
|
3
|
+
FlowArrowhead,
|
|
4
|
+
FlowDirection,
|
|
5
|
+
FlowEdge,
|
|
6
|
+
FlowLabel,
|
|
7
|
+
FlowNode,
|
|
8
|
+
FlowStroke,
|
|
9
|
+
FlowSubgraph,
|
|
10
|
+
Flowchart
|
|
11
|
+
} from './flowchart/model'
|
|
12
|
+
export { parseFlowchart } from './flowchart/parse'
|
|
13
|
+
export type { FlowShape } from './flowchart/shapes'
|
package/src/label.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { decodeHTML } from 'entities'
|
|
2
|
+
import { parseFragment, type DefaultTreeAdapterTypes } from 'parse5'
|
|
3
|
+
|
|
4
|
+
import type { FlowLabel } from './flowchart/model'
|
|
5
|
+
import { decodeEntities } from './upstream/preprocess'
|
|
6
|
+
|
|
7
|
+
/** A label as Mermaid's grammar hands it over: its text, and how that text is to be read. */
|
|
8
|
+
export interface GrammarText {
|
|
9
|
+
text: string
|
|
10
|
+
type: string
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
type HTMLNode = DefaultTreeAdapterTypes.ChildNode
|
|
14
|
+
|
|
15
|
+
/** The text HTML shows: its text nodes, and a line break for each `<br>`. */
|
|
16
|
+
function shownText(nodes: HTMLNode[]): string {
|
|
17
|
+
return nodes
|
|
18
|
+
.map((node) => {
|
|
19
|
+
if (node.nodeName === '#text' && 'value' in node) return node.value
|
|
20
|
+
if (node.nodeName === 'br') return '\n'
|
|
21
|
+
return 'childNodes' in node ? shownText(node.childNodes) : ''
|
|
22
|
+
})
|
|
23
|
+
.join('')
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* A label's text as plain text and its format. Mermaid draws a label as HTML, so its tags only
|
|
28
|
+
* style the text, `<br>` breaks the line, and entities stand for characters. Markdown, written
|
|
29
|
+
* in backticks, keeps its marks for whoever draws it.
|
|
30
|
+
*/
|
|
31
|
+
export function readLabel(label: GrammarText): FlowLabel {
|
|
32
|
+
let text = decodeEntities(label.text.trim())
|
|
33
|
+
// Mermaid drops the quotes around a label written in them.
|
|
34
|
+
if (text.length >= 2 && text.startsWith('"') && text.endsWith('"')) text = text.slice(1, -1)
|
|
35
|
+
if (label.type === 'markdown') return { text: decodeHTML(text), format: 'markdown' }
|
|
36
|
+
return { text: shownText(parseFragment(text).childNodes), format: 'text' }
|
|
37
|
+
}
|