@m3ui-vue/m3ui-vue 1.2.2 → 1.3.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 (235) hide show
  1. package/dist/API.md +2776 -351
  2. package/dist/MButton-CuNzpoxm.js +172 -0
  3. package/dist/MButton-CuNzpoxm.js.map +1 -0
  4. package/dist/MDialog-HxEL-m58.js +173 -0
  5. package/dist/MDialog-HxEL-m58.js.map +1 -0
  6. package/dist/MIconButton-DoNotQ9v.js +282 -0
  7. package/dist/MIconButton-DoNotQ9v.js.map +1 -0
  8. package/dist/MListItem-DnPtv-hY.js +824 -0
  9. package/dist/MListItem-DnPtv-hY.js.map +1 -0
  10. package/dist/MLoadingIndicator-BQMNX6Dx.js +115 -0
  11. package/dist/MLoadingIndicator-BQMNX6Dx.js.map +1 -0
  12. package/dist/MMenuItem-Bih0h4-n.js +604 -0
  13. package/dist/MMenuItem-Bih0h4-n.js.map +1 -0
  14. package/dist/MProgressBar-BCoruxA-.js +184 -0
  15. package/dist/MProgressBar-BCoruxA-.js.map +1 -0
  16. package/dist/MSeekBar-LURE1Ah7.js +435 -0
  17. package/dist/MSeekBar-LURE1Ah7.js.map +1 -0
  18. package/dist/MSegmentedButton-DL9JtJFX.js +65 -0
  19. package/dist/MSegmentedButton-DL9JtJFX.js.map +1 -0
  20. package/dist/MSlider-_J4IS2_z.js +691 -0
  21. package/dist/MSlider-_J4IS2_z.js.map +1 -0
  22. package/dist/MSpinner-BhkMYKOM.js +65 -0
  23. package/dist/MSpinner-BhkMYKOM.js.map +1 -0
  24. package/dist/MTextField-CkzwNBWS.js +296 -0
  25. package/dist/MTextField-CkzwNBWS.js.map +1 -0
  26. package/dist/MTooltip-B67ZDSGp.js +756 -0
  27. package/dist/MTooltip-B67ZDSGp.js.map +1 -0
  28. package/dist/_storageKeys-CYXsUBwK.js +18 -0
  29. package/dist/_storageKeys-CYXsUBwK.js.map +1 -0
  30. package/dist/_useEscapeStack-CjndQhqg.js +19 -0
  31. package/dist/_useEscapeStack-CjndQhqg.js.map +1 -0
  32. package/dist/api.json +1 -1
  33. package/dist/chart.js +1 -1
  34. package/dist/code-editor.js +1 -1
  35. package/dist/components/MAudioPlayer.vue.d.ts +115 -0
  36. package/dist/components/MBadge.vue.d.ts +1 -1
  37. package/dist/components/MBottomSheetScaffold.vue.d.ts +1 -1
  38. package/dist/components/MBox.vue.d.ts +1 -1
  39. package/dist/components/MButton.vue.d.ts +1 -1
  40. package/dist/components/MConfirmDialog.vue.d.ts +1 -1
  41. package/dist/components/MCopyButton.vue.d.ts +2 -2
  42. package/dist/components/MDataTable.vue.d.ts +2 -2
  43. package/dist/components/MDialog.vue.d.ts +2 -2
  44. package/dist/components/MDivider.vue.d.ts +1 -1
  45. package/dist/components/MDragHandle.vue.d.ts +1 -1
  46. package/dist/components/MDrawCanvas.vue.d.ts +148 -0
  47. package/dist/components/MDrawLayers.vue.d.ts +3 -0
  48. package/dist/components/MDrawToolbar.vue.d.ts +34 -0
  49. package/dist/components/MExportButton.vue.d.ts +1 -1
  50. package/dist/components/MFab.vue.d.ts +2 -2
  51. package/dist/components/MFabMenu.vue.d.ts +2 -2
  52. package/dist/components/MFixed.vue.d.ts +1 -1
  53. package/dist/components/MFlex.vue.d.ts +2 -2
  54. package/dist/components/MFloorPlan.vue.d.ts +160 -0
  55. package/dist/components/MFlow.vue.d.ts +305 -0
  56. package/dist/components/MFlowControls.vue.d.ts +33 -0
  57. package/dist/components/MFlowHandle.vue.d.ts +16 -0
  58. package/dist/components/MFlowMinimap.vue.d.ts +22 -0
  59. package/dist/components/MFlowNode.vue.d.ts +35 -0
  60. package/dist/components/MGantt.vue.d.ts +141 -0
  61. package/dist/components/MGanttControls.vue.d.ts +32 -0
  62. package/dist/components/MIconButton.vue.d.ts +3 -1
  63. package/dist/components/MImageCropper.vue.d.ts +110 -0
  64. package/dist/components/MInfiniteScroll.vue.d.ts +1 -1
  65. package/dist/components/MLightbox.vue.d.ts +2 -2
  66. package/dist/components/MList.vue.d.ts +1 -1
  67. package/dist/components/MLoadingOverlay.vue.d.ts +1 -1
  68. package/dist/components/MMapControl.vue.d.ts +1 -1
  69. package/dist/components/MMapSearch.vue.d.ts +1 -1
  70. package/dist/components/MMaskField.vue.d.ts +12 -1
  71. package/dist/components/MMenu.vue.d.ts +1 -1
  72. package/dist/components/MNavigationDrawer.vue.d.ts +1 -1
  73. package/dist/components/MNumberField.vue.d.ts +11 -2
  74. package/dist/components/MPdfViewer.vue.d.ts +174 -0
  75. package/dist/components/MPullToRefresh.vue.d.ts +1 -1
  76. package/dist/components/MResourceTimeline.vue.d.ts +149 -0
  77. package/dist/components/MScheduler.vue.d.ts +3 -3
  78. package/dist/components/MScheme.vue.d.ts +1 -1
  79. package/dist/components/MSearchField.vue.d.ts +1 -1
  80. package/dist/components/MSeekBar.vue.d.ts +1 -1
  81. package/dist/components/MSimpleCarousel.vue.d.ts +1 -1
  82. package/dist/components/MSkeleton.vue.d.ts +1 -1
  83. package/dist/components/MSlider.vue.d.ts +2 -2
  84. package/dist/components/MSparkline.vue.d.ts +1 -1
  85. package/dist/components/MSplitter.vue.d.ts +1 -1
  86. package/dist/components/MStack.vue.d.ts +2 -2
  87. package/dist/components/MSwipeToDismiss.vue.d.ts +1 -1
  88. package/dist/components/MSwitch.vue.d.ts +1 -1
  89. package/dist/components/MTable.vue.d.ts +1 -1
  90. package/dist/components/MTagInput.vue.d.ts +12 -1
  91. package/dist/components/MTextField.vue.d.ts +13 -2
  92. package/dist/components/MToolbar.vue.d.ts +1 -1
  93. package/dist/components/MTree.vue.d.ts +2 -2
  94. package/dist/components/MVideoPlayer.vue.d.ts +253 -0
  95. package/dist/components/MVirtualTable.vue.d.ts +1 -1
  96. package/dist/components/MWindow.vue.d.ts +3 -3
  97. package/dist/components/_MFlowEdge.vue.d.ts +9 -0
  98. package/dist/components/_MFlowEdgeLabel.vue.d.ts +9 -0
  99. package/dist/components/_MFlowNodeShell.vue.d.ts +9 -0
  100. package/dist/components/_MPdfPage.vue.d.ts +76 -0
  101. package/dist/components/_MTimeBackground.vue.d.ts +14 -0
  102. package/dist/components/_MTimeHeader.vue.d.ts +20 -0
  103. package/dist/composables/_flowPanel.d.ts +2 -0
  104. package/dist/composables/_flowSlot.d.ts +5 -0
  105. package/dist/composables/_ganttTime.d.ts +41 -0
  106. package/dist/composables/_useTimeAxis.d.ts +90 -0
  107. package/dist/composables/drawGeometry.d.ts +119 -0
  108. package/dist/composables/flowFormats.d.ts +79 -0
  109. package/dist/composables/flowLayout.d.ts +45 -0
  110. package/dist/composables/flowPaths.d.ts +53 -0
  111. package/dist/composables/ganttFormats.d.ts +52 -0
  112. package/dist/composables/ganttSchedule.d.ts +99 -0
  113. package/dist/composables/useDrawing.d.ts +44 -0
  114. package/dist/composables/useFlow.d.ts +266 -0
  115. package/dist/composables/useGantt.d.ts +87 -0
  116. package/dist/composables/useLocale.d.ts +163 -0
  117. package/dist/composables/useMediaPlayer.d.ts +101 -0
  118. package/dist/composables/usePdf.d.ts +119 -0
  119. package/dist/composables/useResourceTimeline.d.ts +70 -0
  120. package/dist/draw.d.ts +7 -0
  121. package/dist/draw.js +1700 -0
  122. package/dist/draw.js.map +1 -0
  123. package/dist/flow.d.ts +14 -0
  124. package/dist/flow.js +3542 -0
  125. package/dist/flow.js.map +1 -0
  126. package/dist/flowPaths-CUc6X373.js +161 -0
  127. package/dist/flowPaths-CUc6X373.js.map +1 -0
  128. package/dist/gantt.d.ts +12 -0
  129. package/dist/gantt.js +3575 -0
  130. package/dist/gantt.js.map +1 -0
  131. package/dist/index.d.ts +4 -0
  132. package/dist/locales/index.js +1148 -7
  133. package/dist/locales/index.js.map +1 -1
  134. package/dist/m3ui-vue.css +1 -1
  135. package/dist/m3ui.js +7286 -7654
  136. package/dist/m3ui.js.map +1 -1
  137. package/dist/map.js +113 -108
  138. package/dist/map.js.map +1 -1
  139. package/dist/media.d.ts +5 -0
  140. package/dist/media.js +1311 -0
  141. package/dist/media.js.map +1 -0
  142. package/dist/pdf.d.ts +4 -0
  143. package/dist/pdf.js +1871 -0
  144. package/dist/pdf.js.map +1 -0
  145. package/dist/rich-text-editor.js +28 -26
  146. package/dist/rich-text-editor.js.map +1 -1
  147. package/dist/styles.css +1 -1
  148. package/dist/{useLocale-JYxDDeXC.js → useLocale-BpGxplLV.js} +165 -2
  149. package/dist/useLocale-BpGxplLV.js.map +1 -0
  150. package/dist/{useThemeTokens-y0HZpyhL.js → useThemeTokens-DQQcaWbE.js} +40 -54
  151. package/dist/useThemeTokens-DQQcaWbE.js.map +1 -0
  152. package/package.json +29 -5
  153. package/src/__tests__/MAudioPlayer.test.ts +75 -0
  154. package/src/__tests__/MDrawCanvas.test.ts +110 -0
  155. package/src/__tests__/MFloorPlan.test.ts +97 -0
  156. package/src/__tests__/MFlow.test.ts +575 -0
  157. package/src/__tests__/MGantt.test.ts +130 -0
  158. package/src/__tests__/MImageCropper.test.ts +89 -0
  159. package/src/__tests__/MPdfViewer.test.ts +235 -0
  160. package/src/__tests__/MResourceTimeline.test.ts +102 -0
  161. package/src/__tests__/MVideoPlayer.test.ts +201 -0
  162. package/src/__tests__/drawGeometry.test.ts +58 -0
  163. package/src/__tests__/fieldExpose.test.ts +30 -0
  164. package/src/__tests__/flowFormats.test.ts +185 -0
  165. package/src/__tests__/flowLayout.test.ts +113 -0
  166. package/src/__tests__/ganttFormats.test.ts +76 -0
  167. package/src/__tests__/ganttSchedule.test.ts +136 -0
  168. package/src/__tests__/pdfMock.ts +83 -0
  169. package/src/__tests__/useMediaPlayer.test.ts +182 -0
  170. package/src/__tests__/usePdf.test.ts +102 -0
  171. package/src/components/MAudioPlayer.vue +319 -0
  172. package/src/components/MDrawCanvas.vue +813 -0
  173. package/src/components/MDrawLayers.vue +114 -0
  174. package/src/components/MDrawToolbar.vue +171 -0
  175. package/src/components/MFloorPlan.vue +581 -0
  176. package/src/components/MFlow.vue +2049 -0
  177. package/src/components/MFlowControls.vue +110 -0
  178. package/src/components/MFlowHandle.vue +60 -0
  179. package/src/components/MFlowMinimap.vue +134 -0
  180. package/src/components/MFlowNode.vue +98 -0
  181. package/src/components/MGantt.vue +1609 -0
  182. package/src/components/MGanttControls.vue +77 -0
  183. package/src/components/MIconButton.vue +3 -1
  184. package/src/components/MImageCropper.vue +507 -0
  185. package/src/components/MMaskField.vue +13 -0
  186. package/src/components/MNumberField.vue +13 -0
  187. package/src/components/MPdfViewer.vue +1269 -0
  188. package/src/components/MResourceTimeline.vue +1020 -0
  189. package/src/components/MTagInput.vue +13 -0
  190. package/src/components/MTextField.vue +16 -0
  191. package/src/components/MVideoPlayer.vue +839 -0
  192. package/src/components/_MFlowEdge.vue +100 -0
  193. package/src/components/_MFlowEdgeLabel.vue +56 -0
  194. package/src/components/_MFlowNodeShell.vue +111 -0
  195. package/src/components/_MPdfPage.vue +456 -0
  196. package/src/components/_MTimeBackground.vue +16 -0
  197. package/src/components/_MTimeHeader.vue +31 -0
  198. package/src/composables/_flowPanel.ts +13 -0
  199. package/src/composables/_flowSlot.ts +6 -0
  200. package/src/composables/_ganttTime.ts +200 -0
  201. package/src/composables/_useTimeAxis.ts +224 -0
  202. package/src/composables/drawGeometry.ts +405 -0
  203. package/src/composables/flowFormats.ts +916 -0
  204. package/src/composables/flowLayout.ts +297 -0
  205. package/src/composables/flowPaths.ts +239 -0
  206. package/src/composables/ganttFormats.ts +366 -0
  207. package/src/composables/ganttSchedule.ts +403 -0
  208. package/src/composables/useDrawing.ts +53 -0
  209. package/src/composables/useFlow.ts +250 -0
  210. package/src/composables/useGantt.ts +92 -0
  211. package/src/composables/useLocale.ts +328 -0
  212. package/src/composables/useMediaPlayer.ts +406 -0
  213. package/src/composables/usePdf.ts +456 -0
  214. package/src/composables/useResourceTimeline.ts +76 -0
  215. package/src/draw.ts +25 -0
  216. package/src/flow.ts +26 -0
  217. package/src/gantt.ts +12 -0
  218. package/src/index.ts +4 -0
  219. package/src/locales/de.ts +163 -0
  220. package/src/locales/es.ts +163 -0
  221. package/src/locales/fr.ts +163 -0
  222. package/src/locales/ja.ts +163 -0
  223. package/src/locales/ko.ts +163 -0
  224. package/src/locales/pt.ts +163 -0
  225. package/src/locales/zh.ts +163 -0
  226. package/src/media.ts +5 -0
  227. package/src/pdf.ts +15 -0
  228. package/dist/MMenuItem-D4Gx_l3F.js +0 -929
  229. package/dist/MMenuItem-D4Gx_l3F.js.map +0 -1
  230. package/dist/MSlider-Dx_S3vJ9.js +0 -1506
  231. package/dist/MSlider-Dx_S3vJ9.js.map +0 -1
  232. package/dist/MTextField-Bz8JIsnl.js +0 -633
  233. package/dist/MTextField-Bz8JIsnl.js.map +0 -1
  234. package/dist/useLocale-JYxDDeXC.js.map +0 -1
  235. package/dist/useThemeTokens-y0HZpyhL.js.map +0 -1
@@ -0,0 +1,916 @@
1
+ // Graphs as text for MFlow: Graphviz DOT and Mermaid flowcharts, read into nodes and edges and written back. Pure
2
+ // functions without dependencies. Text formats carry no positions (DOT's `pos` aside), so what's read is laid out
3
+ // with layoutLayered (or layoutTree), clusters and subgraphs becoming groups laid out from the inside out.
4
+ import type { FlowEdge, FlowMarker, FlowNode, FlowXY } from './useFlow'
5
+ import { layoutLayered, layoutTree, type FlowLayoutDirection, type FlowLayoutOptions } from './flowLayout'
6
+
7
+ /** A graph read from text */
8
+ export interface FlowGraph {
9
+ nodes: FlowNode[]
10
+ edges: FlowEdge[]
11
+ /** The graph's own direction (DOT `rankdir`, Mermaid `flowchart LR`) */
12
+ rankdir: FlowLayoutDirection
13
+ /** The same, as MFlow's `direction` prop */
14
+ direction: 'horizontal' | 'vertical'
15
+ /** False for a DOT `graph` (edges without arrows) */
16
+ directed: boolean
17
+ /** The DOT graph's name */
18
+ name?: string
19
+ /** The DOT graph's `label` */
20
+ label?: string
21
+ /** Every graph-level DOT attribute, as written */
22
+ attrs: Record<string, string>
23
+ }
24
+
25
+ export interface FlowImportOptions {
26
+ /** How to place the nodes: `'layered'` (default), `'tree'`, or `false` to leave them at 0,0 (for MFlow's `layout` prop, which measures them first) */
27
+ layout?: 'layered' | 'tree' | false
28
+ /** Gaps, sizes and direction for the layout (the direction defaults to the graph's own) */
29
+ layoutOptions?: FlowLayoutOptions
30
+ /** The type given to plain nodes (default none: MFlow's default node) */
31
+ nodeType?: string
32
+ /** The type given to every edge (e.g. `'smoothstep'`; default none: a bezier) */
33
+ edgeType?: string
34
+ }
35
+
36
+ export interface FlowExportOptions {
37
+ /** The direction written (`rankdir` / `flowchart XX`): a layout direction or MFlow's `direction` (default TB) */
38
+ direction?: FlowLayoutDirection | 'horizontal' | 'vertical'
39
+ /** Node sizes, for `positions` (default each node's `width`/`height`, else 180 × 60) */
40
+ sizes?: Map<string, { width: number; height: number }> | Record<string, { width: number; height: number }>
41
+ }
42
+
43
+ export interface FlowDotExportOptions extends FlowExportOptions {
44
+ /** The graph's name */
45
+ name?: string
46
+ /** `digraph` (default) or `graph`, whose edges have no direction */
47
+ directed?: boolean
48
+ /** Writes each node's place as `pos` (in points, y up), for `neato -n` */
49
+ positions?: boolean
50
+ }
51
+
52
+ const ROLES = new Set(['primary', 'secondary', 'tertiary', 'error', 'neutral', 'inverse', 'outline', 'outline-variant', 'success', 'on-surface', 'on-surface-variant'])
53
+ const GROUP_PAD = 24
54
+ const GROUP_HEAD = 36
55
+ const CIRCLE = 56
56
+
57
+ function toRankdir(d: FlowExportOptions['direction']): FlowLayoutDirection {
58
+ if (d === 'horizontal') return 'LR'
59
+ if (d === 'vertical' || !d) return 'TB'
60
+ return d
61
+ }
62
+ function asDirection(r: FlowLayoutDirection): 'horizontal' | 'vertical' {
63
+ return r === 'LR' || r === 'RL' ? 'horizontal' : 'vertical'
64
+ }
65
+
66
+ // A guess at the default node's size before it's measured (min 11rem, max 18rem wide)
67
+ function estimateSize(n: FlowNode): { width: number; height: number } {
68
+ if (n.width && n.height) return { width: n.width, height: n.height }
69
+ if (n.type === 'circle') {
70
+ const s = (n.data as { size?: number } | undefined)?.size ?? CIRCLE
71
+ return { width: s, height: s }
72
+ }
73
+ const label = String((n.data as { label?: unknown } | undefined)?.label ?? n.id)
74
+ const lines = label.split('\n')
75
+ const longest = Math.max(...lines.map((l) => l.length))
76
+ const width = Math.min(288, Math.max(176, 40 + longest * 8))
77
+ const wraps = lines.reduce((sum, l) => sum + Math.max(1, Math.ceil((l.length * 8) / (width - 40))), 0)
78
+ return { width, height: 36 + wraps * 20 }
79
+ }
80
+
81
+ // Lays out each group's children inside it (deepest first), then each level with the groups at their wrapped size.
82
+ // Positions of children come out relative to their group, as MFlow wants them
83
+ function place(nodes: FlowNode[], edges: FlowEdge[], how: 'layered' | 'tree', options: FlowLayoutOptions) {
84
+ const byId = new Map(nodes.map((n) => [n.id, n]))
85
+ const children = new Map<string | undefined, FlowNode[]>()
86
+ for (const n of nodes) {
87
+ const p = n.parentId && byId.has(n.parentId) ? n.parentId : undefined
88
+ if (!children.has(p)) children.set(p, [])
89
+ children.get(p)!.push(n)
90
+ }
91
+ const given = options.sizes instanceof Map ? options.sizes : new Map(Object.entries(options.sizes ?? {}))
92
+ const sizes = new Map<string, { width: number; height: number }>()
93
+ const fn = how === 'tree' ? layoutTree : layoutLayered
94
+ // The ancestor of `id` that sits in the level under `parent`
95
+ const lift = (id: string, parent: string | undefined) => {
96
+ let n = byId.get(id)
97
+ for (let i = 0; n && i < 100; i++) {
98
+ const p = n.parentId && byId.has(n.parentId) ? n.parentId : undefined
99
+ if (p === parent) return n.id
100
+ n = p ? byId.get(p) : undefined
101
+ }
102
+ return undefined
103
+ }
104
+ const level = (parent: string | undefined): { width: number; height: number } => {
105
+ const members = children.get(parent) ?? []
106
+ for (const m of members) {
107
+ if (children.has(m.id)) {
108
+ const inner = level(m.id)
109
+ sizes.set(m.id, { width: Math.max(200, inner.width + GROUP_PAD * 2), height: Math.max(120, inner.height + GROUP_HEAD + GROUP_PAD) })
110
+ } else sizes.set(m.id, given.get(m.id) ?? estimateSize(m))
111
+ }
112
+ const flat = members.map((m) => ({ ...m, parentId: undefined }))
113
+ const lifted: FlowEdge[] = []
114
+ for (const e of edges) {
115
+ const s = lift(e.source, parent)
116
+ const t = lift(e.target, parent)
117
+ if (s && t && s !== t) lifted.push({ ...e, source: s, target: t })
118
+ }
119
+ const pos = fn(flat, lifted, { ...options, sizes })
120
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity
121
+ for (const m of members) {
122
+ const p = pos[m.id] ?? { x: 0, y: 0 }
123
+ const s = sizes.get(m.id)!
124
+ minX = Math.min(minX, p.x)
125
+ minY = Math.min(minY, p.y)
126
+ maxX = Math.max(maxX, p.x + s.width)
127
+ maxY = Math.max(maxY, p.y + s.height)
128
+ }
129
+ if (!members.length) return { width: 0, height: 0 }
130
+ // Inside a group: from its padding and header; at the top: from 0,0
131
+ const ox = parent === undefined ? -minX : GROUP_PAD - minX
132
+ const oy = parent === undefined ? -minY : GROUP_HEAD - minY
133
+ for (const m of members) {
134
+ const p = pos[m.id] ?? { x: 0, y: 0 }
135
+ m.position = { x: Math.round(p.x + ox), y: Math.round(p.y + oy) }
136
+ }
137
+ return { width: maxX - minX, height: maxY - minY }
138
+ }
139
+ level(undefined)
140
+ }
141
+
142
+ function finish(graph: FlowGraph, opts: FlowImportOptions, positioned: boolean) {
143
+ if (positioned || opts.layout === false) return graph
144
+ place(graph.nodes, graph.edges, opts.layout ?? 'layered', { direction: graph.rankdir, ...opts.layoutOptions })
145
+ return graph
146
+ }
147
+
148
+ class FlowSyntaxError extends SyntaxError {
149
+ constructor(message: string, src: string, at: number) {
150
+ const before = src.slice(0, at).split('\n')
151
+ super(`${message} (line ${before.length}, column ${before.at(-1)!.length + 1})`)
152
+ }
153
+ }
154
+
155
+ // ── DOT ──────────────────────────────────────────────────────────────────────────────────────────────────
156
+
157
+ type Tok = { t: 'id'; v: string; quoted: boolean; html: boolean; at: number } | { t: 'p'; v: string; at: number }
158
+
159
+ function tokenizeDot(src: string): Tok[] {
160
+ const toks: Tok[] = []
161
+ let i = 0
162
+ const n = src.length
163
+ while (i < n) {
164
+ const c = src[i]!
165
+ if (/\s/.test(c)) { i++; continue }
166
+ if (c === '/' && src[i + 1] === '/') { while (i < n && src[i] !== '\n') i++; continue }
167
+ if (c === '/' && src[i + 1] === '*') {
168
+ const end = src.indexOf('*/', i + 2)
169
+ i = end < 0 ? n : end + 2
170
+ continue
171
+ }
172
+ // Preprocessor output lines
173
+ if (c === '#' && (i === 0 || src[i - 1] === '\n')) { while (i < n && src[i] !== '\n') i++; continue }
174
+ if (c === '-' && (src[i + 1] === '>' || src[i + 1] === '-')) { toks.push({ t: 'p', v: src.slice(i, i + 2), at: i }); i += 2; continue }
175
+ if ('{}[];,=:'.includes(c)) { toks.push({ t: 'p', v: c, at: i }); i++; continue }
176
+ if (c === '"') {
177
+ const at = i
178
+ let v = ''
179
+ i++
180
+ for (;;) {
181
+ if (i >= n) throw new FlowSyntaxError('Unterminated string', src, at)
182
+ const ch = src[i]!
183
+ if (ch === '\\' && src[i + 1] === '"') { v += '"'; i += 2; continue }
184
+ if (ch === '\\' && src[i + 1] === '\n') { i += 2; continue }
185
+ if (ch === '"') { i++; break }
186
+ v += ch
187
+ i++
188
+ }
189
+ // "a" + "b" concatenates
190
+ const last = toks.at(-1)
191
+ if (last && last.t === 'p' && last.v === '+' && toks.at(-2)?.t === 'id' && (toks.at(-2) as { quoted: boolean }).quoted) {
192
+ toks.pop()
193
+ ;(toks.at(-1) as { v: string }).v += v
194
+ } else toks.push({ t: 'id', v, quoted: true, html: false, at })
195
+ continue
196
+ }
197
+ if (c === '+') { toks.push({ t: 'p', v: '+', at: i }); i++; continue }
198
+ if (c === '<') {
199
+ const at = i
200
+ let depth = 0
201
+ let j = i
202
+ for (; j < n; j++) {
203
+ if (src[j] === '<') depth++
204
+ else if (src[j] === '>' && --depth === 0) break
205
+ }
206
+ if (j >= n) throw new FlowSyntaxError('Unterminated HTML label', src, at)
207
+ toks.push({ t: 'id', v: src.slice(i + 1, j), quoted: true, html: true, at })
208
+ i = j + 1
209
+ continue
210
+ }
211
+ const num = /^-?(?:\.\d+|\d+(?:\.\d*)?)/.exec(src.slice(i, i + 40))
212
+ if (num) { toks.push({ t: 'id', v: num[0], quoted: false, html: false, at: i }); i += num[0].length; continue }
213
+ const word = /^[A-Za-z_\u0080-￿][\w\u0080-￿]*/.exec(src.slice(i, i + 4096))
214
+ if (word) { toks.push({ t: 'id', v: word[0], quoted: false, html: false, at: i }); i += word[0].length; continue }
215
+ throw new FlowSyntaxError(`Unexpected "${c}"`, src, i)
216
+ }
217
+ return toks
218
+ }
219
+
220
+ function htmlToText(html: string) {
221
+ return html
222
+ .replace(/<br\s*\/?>/gi, '\n')
223
+ .replace(/<[^>]*>/g, '')
224
+ .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;|&apos;/g, "'").replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&')
225
+ .trim()
226
+ }
227
+
228
+ // DOT's escapes in labels: \N the node's id, \G the graph's name, \n \l \r line breaks
229
+ function dotLabel(v: string, id: string, graph: string) {
230
+ return v
231
+ .replace(/\\N/g, id)
232
+ .replace(/\\G/g, graph)
233
+ .replace(/\\[nlr]/g, '\n')
234
+ .replace(/\\(.)/g, '$1')
235
+ .replace(/\n$/, '')
236
+ }
237
+
238
+ function dotColor(v: string | undefined) {
239
+ if (!v) return undefined
240
+ // A color list ("red:blue;0.3") takes the first; a scheme ("/x11/red") is dropped
241
+ const first = v.split(':')[0]!.split(';')[0]!.trim().replace(/^\/[^/]*\//, '')
242
+ if (/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(first)) return first.slice(0, 7) + (first.length > 7 ? first.slice(7) : '')
243
+ return /^[a-z]+$/i.test(first) ? first.toLowerCase() : undefined
244
+ }
245
+
246
+ function dotMarkers(attrs: Record<string, string>, directed: boolean): { markerEnd?: FlowMarker; markerStart?: FlowMarker } {
247
+ const dir = attrs.dir ?? (directed ? 'forward' : 'none')
248
+ const head = (a: string | undefined): FlowMarker => (a === 'none' ? 'none' : a && /vee|open|empty|normal-o|o/.test(a) && a !== 'normal' ? 'arrow' : 'arrow-closed')
249
+ const end = dir === 'forward' || dir === 'both' ? head(attrs.arrowhead) : 'none'
250
+ const start = dir === 'back' || dir === 'both' ? head(attrs.arrowtail) : 'none'
251
+ const m: { markerEnd?: FlowMarker; markerStart?: FlowMarker } = {}
252
+ if (end !== 'arrow-closed') m.markerEnd = end
253
+ if (start !== 'none') m.markerStart = start
254
+ return m
255
+ }
256
+
257
+ interface DotScope { node: Record<string, string>; edge: Record<string, string>; graph: Record<string, string>; cluster?: string; members: Set<string> }
258
+
259
+ /**
260
+ * Reads a Graphviz DOT graph (`digraph`/`graph`, `strict`, subgraphs, defaults, ports, HTML labels): nodes take
261
+ * their `label` (default the id), `shape=circle`/`doublecircle`/`point` makes a `circle` node, `style=invis` hides;
262
+ * edges take `label`, `color`, `penwidth`, `style=dashed`/`dotted`/`bold`/`invis` and `dir`/`arrowhead`/`arrowtail`;
263
+ * `cluster` subgraphs become groups. Every attribute as written is kept in each node's and edge's `data.attrs`
264
+ * (ports as `tailport`/`headport`), to map the rest yourself. Laid out in layers along `rankdir`, unless every node
265
+ * has a `pos`. Throws a SyntaxError (with line and column) on what isn't DOT.
266
+ */
267
+ export function parseDot(source: string, options: FlowImportOptions = {}): FlowGraph {
268
+ const toks = tokenizeDot(source)
269
+ let k = 0
270
+ const peek = (o = 0) => toks[k + o]
271
+ const isP = (v: string, o = 0) => { const t = peek(o); return !!t && t.t === 'p' && t.v === v }
272
+ const isKw = (v: string, o = 0) => { const t = peek(o); return !!t && t.t === 'id' && !t.quoted && t.v.toLowerCase() === v }
273
+ const fail = (msg: string): never => {
274
+ throw new FlowSyntaxError(msg, source, peek()?.at ?? source.length)
275
+ }
276
+ const expect = (v: string) => (isP(v) ? toks[k++] : fail(`Expected "${v}"`))
277
+ const id = (): string => {
278
+ const t = peek()
279
+ if (!t || t.t !== 'id') return fail('Expected an id')
280
+ k++
281
+ return t.html ? htmlToText(t.v) : t.v
282
+ }
283
+
284
+ let strict = false
285
+ if (isKw('strict')) { strict = true; k++ }
286
+ let directed: boolean
287
+ if (isKw('digraph')) directed = true
288
+ else if (isKw('graph')) directed = false
289
+ else return fail('Expected "graph" or "digraph"')
290
+ k++
291
+ const name = peek()?.t === 'id' ? id() : undefined
292
+
293
+ const nodes: FlowNode[] = []
294
+ const nodeAttrs = new Map<string, Record<string, string>>()
295
+ const nodeScope = new Map<string, string | undefined>()
296
+ const edges: FlowEdge[] = []
297
+ const groupLabels = new Map<string, Record<string, string>>()
298
+ const edgeKeys = new Set<string>()
299
+ let anon = 0
300
+
301
+ const attrList = () => {
302
+ const a: Record<string, string> = {}
303
+ while (isP('[')) {
304
+ k++
305
+ while (!isP(']')) {
306
+ if (!peek()) fail('Expected "]"')
307
+ const key = id()
308
+ if (isP('=')) { k++; a[key] = id() } else a[key] = 'true'
309
+ if (isP(';') || isP(',')) k++
310
+ }
311
+ k++
312
+ }
313
+ return a
314
+ }
315
+ const touchNode = (nid: string, scope: DotScope, attrs?: Record<string, string>) => {
316
+ for (let s: DotScope | undefined = scope; s; s = parents.get(s)) s.members.add(nid)
317
+ if (!nodeAttrs.has(nid)) {
318
+ nodeAttrs.set(nid, { ...scope.node })
319
+ nodeScope.set(nid, scope.cluster)
320
+ nodes.push({ id: nid, position: { x: 0, y: 0 } })
321
+ }
322
+ if (attrs) Object.assign(nodeAttrs.get(nid)!, attrs)
323
+ }
324
+ const parents = new Map<DotScope, DotScope | undefined>()
325
+
326
+ type Operand = { ids: string[]; port?: string }
327
+ const operand = (scope: DotScope): Operand => {
328
+ if (isKw('subgraph') || isP('{')) return { ids: [...subgraph(scope).members] }
329
+ const nid = id()
330
+ let port: string | undefined
331
+ if (isP(':')) {
332
+ k++
333
+ port = id()
334
+ if (isP(':')) { k++; port += ':' + id() }
335
+ }
336
+ touchNode(nid, scope)
337
+ return { ids: [nid], port }
338
+ }
339
+ const subgraph = (outer: DotScope): DotScope => {
340
+ let sname: string | undefined
341
+ if (isKw('subgraph')) {
342
+ k++
343
+ if (peek()?.t === 'id') sname = id()
344
+ }
345
+ const scope: DotScope = { node: { ...outer.node }, edge: { ...outer.edge }, graph: {}, cluster: outer.cluster, members: new Set() }
346
+ parents.set(scope, outer)
347
+ if (sname && /^cluster/i.test(sname)) {
348
+ let gid = sname
349
+ while (nodeAttrs.has(gid) || groupLabels.has(gid)) gid = `${sname}_${++anon}`
350
+ groupLabels.set(gid, scope.graph)
351
+ nodes.push({ id: gid, type: 'group', position: { x: 0, y: 0 }, ...(outer.cluster ? { parentId: outer.cluster } : {}) })
352
+ scope.cluster = gid
353
+ }
354
+ expect('{')
355
+ stmts(scope)
356
+ expect('}')
357
+ return scope
358
+ }
359
+ const stmts = (scope: DotScope) => {
360
+ while (peek() && !isP('}')) {
361
+ stmt(scope)
362
+ if (isP(';') || isP(',')) k++
363
+ }
364
+ }
365
+ const stmt = (scope: DotScope) => {
366
+ if ((isKw('graph') || isKw('node') || isKw('edge')) && isP('[', 1)) {
367
+ const which = (peek() as { v: string }).v.toLowerCase() as 'graph' | 'node' | 'edge'
368
+ k++
369
+ Object.assign(scope[which], attrList())
370
+ return
371
+ }
372
+ if (peek()?.t === 'id' && !isKw('subgraph') && isP('=', 1)) {
373
+ const key = id()
374
+ k++
375
+ scope.graph[key] = id()
376
+ return
377
+ }
378
+ const first = operand(scope)
379
+ if (!isP('->') && !isP('--')) {
380
+ if (isP('[')) {
381
+ const a = attrList()
382
+ for (const nid of first.ids) touchNode(nid, scope, a)
383
+ }
384
+ return
385
+ }
386
+ const chain: Operand[] = [first]
387
+ while (isP('->') || isP('--')) {
388
+ k++
389
+ chain.push(operand(scope))
390
+ }
391
+ const a = { ...scope.edge, ...attrList() }
392
+ for (let c = 0; c < chain.length - 1; c++) {
393
+ const from = chain[c]!
394
+ const to = chain[c + 1]!
395
+ for (const s of from.ids) {
396
+ for (const t of to.ids) {
397
+ const key = directed ? `${s}\u0000${t}` : [s, t].sort().join('\u0000')
398
+ if (strict && edgeKeys.has(key)) continue
399
+ edgeKeys.add(key)
400
+ const attrs = { ...a }
401
+ if (from.port) attrs.tailport = from.port
402
+ if (to.port) attrs.headport = to.port
403
+ edges.push(dotEdge(s, t, attrs, edges.length, directed, options))
404
+ }
405
+ }
406
+ }
407
+ }
408
+
409
+ const root: DotScope = { node: {}, edge: {}, graph: {}, members: new Set() }
410
+ expect('{')
411
+ stmts(root)
412
+ expect('}')
413
+ if (peek()) fail('Unexpected text after the graph')
414
+
415
+ // Ids given with `id=` must stay unique
416
+ const seen = new Set<string>()
417
+ for (const e of edges) {
418
+ while (seen.has(e.id)) e.id = `${e.id}_`
419
+ seen.add(e.id)
420
+ }
421
+
422
+ let positioned = nodes.some((n) => n.type !== 'group')
423
+ for (const n of nodes) {
424
+ if (n.type === 'group') {
425
+ const g = groupLabels.get(n.id)!
426
+ n.data = { label: g.label !== undefined ? dotLabel(g.label, n.id, name ?? '') : undefined, attrs: { ...g } }
427
+ continue
428
+ }
429
+ const attrs = nodeAttrs.get(n.id)!
430
+ const parent = nodeScope.get(n.id)
431
+ if (parent) n.parentId = parent
432
+ const label = attrs.label !== undefined ? dotLabel(attrs.label, n.id, name ?? '') : n.id
433
+ const shape = attrs.shape?.toLowerCase()
434
+ if (shape === 'circle' || shape === 'doublecircle' || shape === 'point' || shape === 'mcircle') {
435
+ n.type = 'circle'
436
+ n.data = { label: shape === 'point' ? '' : label, ...(shape === 'doublecircle' ? { ring: 'primary' } : {}), attrs }
437
+ if (shape === 'point') n.data.size = 16
438
+ } else {
439
+ if (options.nodeType) n.type = options.nodeType
440
+ n.data = { label, attrs }
441
+ }
442
+ if (/\binvis\b/.test(attrs.style ?? '')) n.hidden = true
443
+ const pos = /^\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)/.exec(attrs.pos ?? '')
444
+ if (pos) {
445
+ // Points, y up, the node's center
446
+ const s = estimateSize(n)
447
+ n.position = { x: (Number(pos[1]) * 4) / 3 - s.width / 2, y: (-Number(pos[2]) * 4) / 3 - s.height / 2 }
448
+ } else positioned = false
449
+ }
450
+ if (positioned) {
451
+ // Children's `pos` are absolute: make them relative to their group, and the whole from 0,0
452
+ const top = nodes.filter((n) => n.type !== 'group')
453
+ const minX = Math.min(...top.map((n) => n.position.x))
454
+ const minY = Math.min(...top.map((n) => n.position.y))
455
+ for (const n of top) n.position = { x: Math.round(n.position.x - minX), y: Math.round(n.position.y - minY) }
456
+ if (nodes.some((n) => n.type === 'group')) place(nodes.filter((n) => n.type === 'group' || n.parentId), [], 'layered', {})
457
+ }
458
+
459
+ const rd = (root.graph.rankdir ?? '').toUpperCase()
460
+ const rankdir: FlowLayoutDirection = rd === 'LR' || rd === 'RL' || rd === 'BT' ? rd : 'TB'
461
+ const graph: FlowGraph = {
462
+ nodes,
463
+ edges,
464
+ rankdir,
465
+ direction: asDirection(rankdir),
466
+ directed,
467
+ attrs: { ...root.graph },
468
+ ...(name !== undefined ? { name } : {}),
469
+ ...(root.graph.label !== undefined ? { label: dotLabel(root.graph.label, '', name ?? '') } : {}),
470
+ }
471
+ return finish(graph, options, positioned && !nodes.some((n) => n.type === 'group'))
472
+ }
473
+
474
+ function dotEdge(source: string, target: string, attrs: Record<string, string>, index: number, directed: boolean, options: FlowImportOptions): FlowEdge {
475
+ const e: FlowEdge = { id: attrs.id ?? `e${index + 1}`, source, target }
476
+ if (options.edgeType) e.type = options.edgeType
477
+ if (attrs.label !== undefined) e.label = dotLabel(attrs.label, '', '')
478
+ const style = attrs.style ?? ''
479
+ if (/\b(dashed|dotted)\b/.test(style)) e.dashed = true
480
+ if (/\binvis\b/.test(style)) e.hidden = true
481
+ const color = dotColor(attrs.color)
482
+ if (color) e.color = color
483
+ if (attrs.penwidth && Number(attrs.penwidth) > 0) e.width = Number(attrs.penwidth) * 2
484
+ else if (/\bbold\b/.test(style)) e.width = 4
485
+ Object.assign(e, dotMarkers(attrs, directed))
486
+ e.data = { attrs }
487
+ return e
488
+ }
489
+
490
+ const DOT_KEYWORDS = new Set(['strict', 'graph', 'digraph', 'node', 'edge', 'subgraph'])
491
+ function dotId(v: string) {
492
+ if (/^[A-Za-z_][\w]*$/.test(v) && !DOT_KEYWORDS.has(v.toLowerCase())) return v
493
+ if (/^-?(?:\.\d+|\d+(?:\.\d*)?)$/.test(v)) return v
494
+ return `"${v.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n')}"`
495
+ }
496
+ function dotAttrs(a: Record<string, string>) {
497
+ const parts = Object.entries(a).map(([key, v]) => `${dotId(key)}=${dotId(v)}`)
498
+ return parts.length ? ` [${parts.join(', ')}]` : ''
499
+ }
500
+ // What's kept from an imported `data.attrs`: the rest is written from the node's or edge's current state
501
+ const DOT_NODE_OWN = new Set(['label', 'pos', 'shape', 'style'])
502
+ const DOT_EDGE_OWN = new Set(['label', 'color', 'penwidth', 'style', 'dir', 'arrowhead', 'arrowtail', 'id', 'tailport', 'headport'])
503
+ function keptAttrs(data: unknown, own: Set<string>) {
504
+ const a = (data as { attrs?: unknown } | undefined)?.attrs
505
+ const out: Record<string, string> = {}
506
+ if (a && typeof a === 'object') for (const [key, v] of Object.entries(a)) if (!own.has(key) && typeof v === 'string') out[key] = v
507
+ return out
508
+ }
509
+ function labelOf(n: { id: string; data?: unknown }) {
510
+ const l = (n.data as { label?: unknown } | undefined)?.label
511
+ return l === undefined || l === null ? undefined : String(l)
512
+ }
513
+ function absolute(nodes: FlowNode[]) {
514
+ const byId = new Map(nodes.map((n) => [n.id, n]))
515
+ const memo = new Map<string, FlowXY>()
516
+ const at = (n: FlowNode, depth = 0): FlowXY => {
517
+ if (memo.has(n.id)) return memo.get(n.id)!
518
+ const p = n.parentId && byId.has(n.parentId) && depth < 100 ? at(byId.get(n.parentId)!, depth + 1) : { x: 0, y: 0 }
519
+ const r = { x: p.x + n.position.x, y: p.y + n.position.y }
520
+ memo.set(n.id, r)
521
+ return r
522
+ }
523
+ return at
524
+ }
525
+ // Groups first, children inside them, depth first
526
+ function tree(nodes: FlowNode[]) {
527
+ const ids = new Set(nodes.map((n) => n.id))
528
+ const kids = new Map<string | undefined, FlowNode[]>()
529
+ for (const n of nodes) {
530
+ const p = n.parentId && ids.has(n.parentId) ? n.parentId : undefined
531
+ if (!kids.has(p)) kids.set(p, [])
532
+ kids.get(p)!.push(n)
533
+ }
534
+ return kids
535
+ }
536
+
537
+ /**
538
+ * Writes nodes and edges as a Graphviz DOT graph: labels, `circle` nodes as `shape=circle` (`doublecircle` with a
539
+ * ring), groups as `cluster` subgraphs, edge labels, colors (CSS ones; M3 roles are left out), widths, dashes,
540
+ * arrows and hidden ones. Attributes kept in `data.attrs` (as `parseDot` leaves them) are written back too.
541
+ */
542
+ export function toDot(nodes: FlowNode[], edges: FlowEdge[], options: FlowDotExportOptions = {}): string {
543
+ const directed = options.directed ?? true
544
+ const out: string[] = [`${directed ? 'digraph' : 'graph'}${options.name ? ` ${dotId(options.name)}` : ''} {`]
545
+ const rankdir = toRankdir(options.direction)
546
+ if (rankdir !== 'TB') out.push(` rankdir=${rankdir};`)
547
+ const kids = tree(nodes)
548
+ const at = absolute(nodes)
549
+ const given = options.sizes instanceof Map ? options.sizes : new Map(Object.entries(options.sizes ?? {}))
550
+ const write = (parent: string | undefined, indent: string) => {
551
+ for (const n of kids.get(parent) ?? []) {
552
+ const label = labelOf(n)
553
+ if (n.type === 'group') {
554
+ const gid = /^cluster/i.test(n.id) ? n.id : `cluster_${n.id}`
555
+ out.push(`${indent}subgraph ${dotId(gid)} {`)
556
+ const ga = keptAttrs(n.data, DOT_NODE_OWN)
557
+ if (label) ga.label = label
558
+ for (const [key, v] of Object.entries(ga)) out.push(`${indent} ${dotId(key)}=${dotId(v)};`)
559
+ write(n.id, indent + ' ')
560
+ out.push(`${indent}}`)
561
+ continue
562
+ }
563
+ const a = keptAttrs(n.data, DOT_NODE_OWN)
564
+ if (label !== undefined && label !== n.id) a.label = label
565
+ if (n.type === 'circle') a.shape = (n.data as { ring?: unknown } | undefined)?.ring ? 'doublecircle' : 'circle'
566
+ else if ((n.data as { attrs?: { shape?: string } } | undefined)?.attrs?.shape) a.shape = (n.data as { attrs: { shape: string } }).attrs.shape
567
+ if (n.hidden) a.style = 'invis'
568
+ if (options.positions) {
569
+ const p = at(n)
570
+ const s = given.get(n.id) ?? estimateSize(n)
571
+ a.pos = `${round((p.x + s.width / 2) * 0.75)},${round(-(p.y + s.height / 2) * 0.75)}`
572
+ }
573
+ out.push(`${indent}${dotId(n.id)}${dotAttrs(a)};`)
574
+ }
575
+ }
576
+ write(undefined, ' ')
577
+ const op = directed ? '->' : '--'
578
+ for (const e of edges) {
579
+ const a = keptAttrs(e.data, DOT_EDGE_OWN)
580
+ if (e.label) a.label = e.label
581
+ if (e.color && !ROLES.has(e.color) && !e.color.startsWith('var(')) a.color = e.color
582
+ if (e.width && e.width !== 2) a.penwidth = String(round(e.width / 2))
583
+ const style = [e.dashed ? 'dashed' : '', e.hidden ? 'invis' : ''].filter(Boolean).join(',')
584
+ if (style) a.style = style
585
+ const end = e.markerEnd ?? 'arrow-closed'
586
+ const start = e.markerStart ?? 'none'
587
+ if (directed) {
588
+ if (end === 'none' && start === 'none') a.dir = 'none'
589
+ else if (end === 'none') a.dir = 'back'
590
+ else if (start !== 'none') a.dir = 'both'
591
+ if (end === 'arrow') a.arrowhead = 'vee'
592
+ if (start === 'arrow') a.arrowtail = 'vee'
593
+ }
594
+ const tail = (e.data as { attrs?: { tailport?: string } } | undefined)?.attrs?.tailport
595
+ const head = (e.data as { attrs?: { headport?: string } } | undefined)?.attrs?.headport
596
+ const port = (p?: string) => (p ? ':' + p.split(':').map(dotId).join(':') : '')
597
+ out.push(` ${dotId(e.source)}${port(tail)} ${op} ${dotId(e.target)}${port(head)}${dotAttrs(a)};`)
598
+ }
599
+ out.push('}')
600
+ return out.join('\n') + '\n'
601
+ }
602
+
603
+ function round(v: number) {
604
+ return Math.round(v * 100) / 100
605
+ }
606
+
607
+ // ── Mermaid ──────────────────────────────────────────────────────────────────────────────────────────────
608
+
609
+ // Node shapes, longest delimiters first
610
+ const SHAPES: { open: string; close: string; shape: string }[] = [
611
+ { open: '(((', close: ')))', shape: 'doublecircle' },
612
+ { open: '((', close: '))', shape: 'circle' },
613
+ { open: '([', close: '])', shape: 'stadium' },
614
+ { open: '[[', close: ']]', shape: 'subroutine' },
615
+ { open: '[(', close: ')]', shape: 'cylinder' },
616
+ { open: '{{', close: '}}', shape: 'hexagon' },
617
+ { open: '[/', close: '/]', shape: 'lean-right' },
618
+ { open: '[\\', close: '\\]', shape: 'lean-left' },
619
+ { open: '[/', close: '\\]', shape: 'trapezoid' },
620
+ { open: '[\\', close: '/]', shape: 'inv-trapezoid' },
621
+ { open: '>', close: ']', shape: 'odd' },
622
+ { open: '(', close: ')', shape: 'rounded' },
623
+ { open: '[', close: ']', shape: 'rect' },
624
+ { open: '{', close: '}', shape: 'diamond' },
625
+ ]
626
+ const MERMAID_SKIP = /^(classDef|class|style|linkStyle|click|accTitle|accDescr|direction)\b/
627
+ const MERMAID_RESERVED = new Set(['end', 'graph', 'flowchart', 'subgraph', 'style', 'class', 'classdef', 'linkstyle', 'click', 'direction'])
628
+
629
+ function mermaidText(v: string) {
630
+ let t = v.trim()
631
+ if (t.startsWith('"') && t.endsWith('"') && t.length > 1) t = t.slice(1, -1)
632
+ // Markdown strings ("`**bold**`")
633
+ if (t.startsWith('`') && t.endsWith('`') && t.length > 1) t = t.slice(1, -1).replace(/\*\*|__|\*|_/g, '')
634
+ return t
635
+ .replace(/<br\s*\/?>/gi, '\n')
636
+ .replace(/#quot;/g, '"')
637
+ .replace(/#(\d+);/g, (_, d) => String.fromCodePoint(Number(d)))
638
+ .replace(/#([a-z]+);/gi, (m, name) => ({ amp: '&', lt: '<', gt: '>', nbsp: ' ', apos: "'" })[name.toLowerCase() as 'amp'] ?? m)
639
+ }
640
+
641
+ // Splits on newlines and on `;` outside quotes and brackets
642
+ function mermaidStatements(src: string): { text: string; at: number }[] {
643
+ const out: { text: string; at: number }[] = []
644
+ let depth = 0
645
+ let quote = false
646
+ let start = 0
647
+ for (let i = 0; i <= src.length; i++) {
648
+ const c = src[i]
649
+ if (c === '"') quote = !quote
650
+ else if (!quote && (c === '[' || c === '(' || c === '{')) depth++
651
+ else if (!quote && (c === ']' || c === ')' || c === '}')) depth = Math.max(0, depth - 1)
652
+ if (c === undefined || c === '\n' || (c === ';' && !quote && depth === 0)) {
653
+ const raw = src.slice(start, i)
654
+ const lead = raw.length - raw.trimStart().length
655
+ const text = raw.trim()
656
+ if (text && !text.startsWith('%%')) out.push({ text, at: start + lead })
657
+ if (c === '\n') { quote = false; depth = 0 }
658
+ start = i + 1
659
+ }
660
+ }
661
+ return out
662
+ }
663
+
664
+ interface MermaidLink { line: 'solid' | 'dotted' | 'thick' | 'invisible'; start: string; end: string; label?: string; raw: string }
665
+
666
+ /**
667
+ * Reads a Mermaid flowchart (`flowchart`/`graph` with TB/TD/BT/LR/RL): node shapes (`(( ))` makes a `circle` node,
668
+ * `((( )))` one with a ring; every other shape is kept as `data.shape`), the `@{ shape, label }` syntax, chains and
669
+ * `&`, links `-->` `---` `-.->` `==>` `~~~` `<-->` `--o` `--x` with `|labels|` or `-- labels -->`, and subgraphs as
670
+ * groups. `classDef`, `style`, `click` and the like are skipped. Laid out in layers along its direction. Throws a
671
+ * SyntaxError (with line and column) on what it can't read.
672
+ */
673
+ export function parseMermaid(source: string, options: FlowImportOptions = {}): FlowGraph {
674
+ const stmts = mermaidStatements(source.replace(/^\s*---\n[\s\S]*?\n---\s*\n/, (m) => '\n'.repeat(m.split('\n').length - 1)))
675
+ const head = stmts.shift()
676
+ const hm = head && /^(flowchart|graph)(?:\s+(TB|TD|BT|RL|LR))?\s*(.*)$/i.exec(head.text)
677
+ if (!head || !hm) throw new FlowSyntaxError('Expected "flowchart" or "graph"', source, head?.at ?? 0)
678
+ const d = (hm[2] ?? 'TB').toUpperCase()
679
+ const rankdir: FlowLayoutDirection = d === 'TD' ? 'TB' : (d as FlowLayoutDirection)
680
+ // `graph TD; A-->B` on one line
681
+ if (hm[3]) stmts.unshift({ text: hm[3], at: head.at + head.text.length - hm[3].length })
682
+
683
+ const nodes: FlowNode[] = []
684
+ const byId = new Map<string, FlowNode>()
685
+ const edges: FlowEdge[] = []
686
+ const groups: string[] = []
687
+
688
+ const touch = (id: string, label?: string, shape?: string) => {
689
+ let n = byId.get(id)
690
+ if (!n) {
691
+ n = { id, position: { x: 0, y: 0 }, data: { label: id } }
692
+ if (groups.length) n.parentId = groups.at(-1)
693
+ if (options.nodeType) n.type = options.nodeType
694
+ byId.set(id, n)
695
+ nodes.push(n)
696
+ } else if (groups.length && !n.parentId && n.id !== groups.at(-1)) {
697
+ // Named again inside a subgraph, a node from outside any moves into it, as in Mermaid
698
+ n.parentId = groups.at(-1)
699
+ }
700
+ if (n.type === 'group') return n
701
+ if (label !== undefined) n.data.label = label
702
+ if (shape) {
703
+ n.data.shape = shape
704
+ if (shape === 'circle' || shape === 'doublecircle' || shape === 'sm-circ' || shape === 'dbl-circ') {
705
+ n.type = 'circle'
706
+ if (shape === 'doublecircle' || shape === 'dbl-circ') n.data.ring = 'primary'
707
+ } else if (n.type === 'circle') n.type = options.nodeType
708
+ }
709
+ return n
710
+ }
711
+
712
+ for (const { text, at } of stmts) {
713
+ const fail = (msg: string, off = 0): never => {
714
+ throw new FlowSyntaxError(msg, source, at + off)
715
+ }
716
+ if (/^end$/i.test(text)) {
717
+ if (!groups.length) fail('"end" without a subgraph')
718
+ groups.pop()
719
+ continue
720
+ }
721
+ const sg = /^subgraph\s+(.+)$/i.exec(text)
722
+ if (sg) {
723
+ const rest = sg[1]!.trim()
724
+ const m = /^([\w-]+)\s*\[(.*)\]$/.exec(rest)
725
+ const gid = m ? m[1]! : /^[\w-]+$/.test(rest) ? rest : rest.replace(/^"|"$/g, '')
726
+ const label = m ? mermaidText(m[2]!) : mermaidText(rest)
727
+ const g: FlowNode = byId.get(gid) ?? { id: gid, position: { x: 0, y: 0 } }
728
+ g.type = 'group'
729
+ g.data = { label }
730
+ if (groups.length) g.parentId = groups.at(-1)
731
+ else delete g.parentId
732
+ if (!byId.has(gid)) { byId.set(gid, g); nodes.push(g) }
733
+ groups.push(gid)
734
+ continue
735
+ }
736
+ if (MERMAID_SKIP.test(text)) continue
737
+
738
+ let i = 0
739
+ const ws = () => { while (i < text.length && /\s/.test(text[i]!)) i++ }
740
+ const nodeRef = (): string => {
741
+ ws()
742
+ const m = /^[\w$À-￿](?:[\w$.À-￿]|-(?=[\wÀ-￿]))*/.exec(text.slice(i))
743
+ if (!m) return fail(`Expected a node at "${text.slice(i, i + 12)}"`, i)
744
+ const id = m[0]
745
+ i += id.length
746
+ let label: string | undefined
747
+ let shape: string | undefined
748
+ if (text.startsWith('@{', i)) {
749
+ const end = text.indexOf('}', i)
750
+ if (end < 0) fail('Unclosed "@{"', i)
751
+ const body = text.slice(i + 2, end)
752
+ const sm = /\bshape\s*:\s*([\w-]+)/.exec(body)
753
+ const lm = /\blabel\s*:\s*("(?:[^"\\]|\\.)*"|[^,}]+)/.exec(body)
754
+ if (sm) shape = sm[1]!.toLowerCase()
755
+ if (lm) label = mermaidText(lm[1]!)
756
+ i = end + 1
757
+ } else {
758
+ for (const s of SHAPES) {
759
+ if (!text.startsWith(s.open, i)) continue
760
+ const from = i + s.open.length
761
+ const inner = text[from] === '"' ? text.indexOf('"', from + 1) + 1 : from
762
+ const end = text.indexOf(s.close, inner)
763
+ if (inner === 0 || end < 0) continue
764
+ label = mermaidText(text.slice(from, end))
765
+ shape = s.shape
766
+ i = end + s.close.length
767
+ break
768
+ }
769
+ }
770
+ // `:::className`
771
+ const cls = /^:::[\w-]+/.exec(text.slice(i))
772
+ if (cls) i += cls[0].length
773
+ touch(id, label, shape)
774
+ return id
775
+ }
776
+ const group = () => {
777
+ const ids = [nodeRef()]
778
+ for (;;) {
779
+ ws()
780
+ if (text[i] !== '&') return ids
781
+ i++
782
+ ids.push(nodeRef())
783
+ }
784
+ }
785
+ const link = (): MermaidLink | null => {
786
+ ws()
787
+ const rest = text.slice(i)
788
+ // `-- text -->`, `== text ==>`, `-. text .->`
789
+ const inline = /^(<|o|x)?(--|==|-\.)(?![-.>=|~])(?![ox](?:\s|$))\s*(.+?)\s*(-{2,}[->ox]|={2,}[=>ox]|\.+-[>ox]?|-\.+-[>ox]?)(?=\s|[\w"]|$)/.exec(rest)
790
+ const plain = /^(<|o(?=[-=.])|x(?=[-=.]))?(~{3,}|-\.+-|-{2,}|={2,})(>|o(?![\w])|x(?![\w]))?/.exec(rest)
791
+ let m: MermaidLink
792
+ // `-- text -->` starts with exactly two dashes (or `==`, `-.`) and text: `--- B`, `--x B` and `-->|x| B` are plain
793
+ if (inline) {
794
+ const startsDot = inline[2] === '-.'
795
+ const end = inline[4]!
796
+ const arrow = /[>ox]$/.test(end) && !/^-+-$|^=+=$/.test(end) ? end.slice(-1) : ''
797
+ m = { line: startsDot ? 'dotted' : inline[2] === '==' ? 'thick' : 'solid', start: inline[1] ?? '', end: arrow === '-' || arrow === '=' ? '' : arrow, label: mermaidText(inline[3]!), raw: inline[0] }
798
+ i += inline[0].length
799
+ } else if (plain) {
800
+ const body = plain[2]!
801
+ m = { line: body.startsWith('~') ? 'invisible' : body.includes('.') ? 'dotted' : body.startsWith('=') ? 'thick' : 'solid', start: plain[1] ?? '', end: plain[3] ?? '', raw: plain[0] }
802
+ i += plain[0].length
803
+ ws()
804
+ if (text[i] === '|') {
805
+ const end = text.indexOf('|', i + 1)
806
+ if (end < 0) fail('Unclosed "|"', i)
807
+ m.label = mermaidText(text.slice(i + 1, end))
808
+ i = end + 1
809
+ }
810
+ } else return null
811
+ return m
812
+ }
813
+
814
+ let from = group()
815
+ for (;;) {
816
+ ws()
817
+ if (i >= text.length) break
818
+ const l = link()
819
+ if (!l) fail(`Unexpected "${text.slice(i, i + 12)}"`, i)
820
+ const to = group()
821
+ for (const s of from) for (const t of to) edges.push(mermaidEdge(s, t, l!, edges.length, options))
822
+ from = to
823
+ }
824
+ }
825
+ if (groups.length) throw new FlowSyntaxError(`Subgraph "${groups.at(-1)}" has no "end"`, source, source.length)
826
+
827
+ // Parents before children
828
+ const ordered: FlowNode[] = []
829
+ const kids = tree(nodes)
830
+ const walk = (p: string | undefined) => {
831
+ for (const n of kids.get(p) ?? []) {
832
+ ordered.push(n)
833
+ walk(n.id)
834
+ }
835
+ }
836
+ walk(undefined)
837
+ const graph: FlowGraph = { nodes: ordered, edges, rankdir, direction: asDirection(rankdir), directed: true, attrs: {} }
838
+ return finish(graph, options, false)
839
+ }
840
+
841
+ function mermaidMarker(c: string): FlowMarker {
842
+ return c === '>' || c === '<' ? 'arrow-closed' : c === 'o' || c === 'x' ? 'arrow' : 'none'
843
+ }
844
+ function mermaidEdge(source: string, target: string, l: MermaidLink, index: number, options: FlowImportOptions): FlowEdge {
845
+ const e: FlowEdge = { id: `e${index + 1}`, source, target }
846
+ if (options.edgeType) e.type = options.edgeType
847
+ if (l.label) e.label = l.label
848
+ if (l.line === 'dotted') e.dashed = true
849
+ if (l.line === 'thick') e.width = 4
850
+ if (l.line === 'invisible') e.hidden = true
851
+ const end = mermaidMarker(l.end)
852
+ if (end !== 'arrow-closed') e.markerEnd = end
853
+ if (l.start) e.markerStart = mermaidMarker(l.start)
854
+ e.data = { link: l.raw.replace(/\s+/g, ' ') }
855
+ return e
856
+ }
857
+
858
+ function mermaidQuote(v: string) {
859
+ return `"${v.replace(/"/g, '#quot;').replace(/\n/g, '<br>')}"`
860
+ }
861
+ const MERMAID_OPEN = new Map(SHAPES.map((s) => [s.shape, s]))
862
+
863
+ /**
864
+ * Writes nodes and edges as a Mermaid flowchart: labels, `circle` nodes as `(( ))` (`((( )))` with a ring), the
865
+ * shape kept in `data.shape` (as `parseMermaid` leaves it), groups as subgraphs, and edges as `-->`, `---` (no
866
+ * arrow), `-.->` (dashed), `==>` (3px or wider), `~~~` (hidden) or `<-->`, with their labels. Ids Mermaid can't take
867
+ * are renamed (`n1`, `n2`…).
868
+ */
869
+ export function toMermaid(nodes: FlowNode[], edges: FlowEdge[], options: FlowExportOptions = {}): string {
870
+ const out = [`flowchart ${toRankdir(options.direction)}`]
871
+ const names = new Map<string, string>()
872
+ let next = 0
873
+ const used = new Set<string>()
874
+ for (const n of nodes) {
875
+ const ok = /^[A-Za-z_][\w-]*$/.test(n.id) && !n.id.endsWith('-') && !MERMAID_RESERVED.has(n.id.toLowerCase())
876
+ let name = ok ? n.id : ''
877
+ while (!name || used.has(name)) name = `n${++next}`
878
+ used.add(name)
879
+ names.set(n.id, name)
880
+ }
881
+ const kids = tree(nodes)
882
+ const write = (parent: string | undefined, indent: string) => {
883
+ for (const n of kids.get(parent) ?? []) {
884
+ const name = names.get(n.id)!
885
+ const label = labelOf(n)
886
+ if (n.type === 'group') {
887
+ out.push(`${indent}subgraph ${name}[${mermaidQuote(label ?? n.id)}]`)
888
+ write(n.id, indent + ' ')
889
+ out.push(`${indent}end`)
890
+ continue
891
+ }
892
+ const data = (n.data ?? {}) as { shape?: string; ring?: unknown }
893
+ const shape = n.type === 'circle' ? (data.ring ? 'doublecircle' : 'circle') : data.shape && MERMAID_OPEN.has(data.shape) ? data.shape : label !== undefined && label !== n.id ? 'rect' : ''
894
+ const s = shape ? MERMAID_OPEN.get(shape) : undefined
895
+ out.push(`${indent}${name}${s ? `${s.open}${mermaidQuote(label ?? n.id)}${s.close}` : ''}`)
896
+ }
897
+ }
898
+ write(undefined, ' ')
899
+ for (const e of edges) {
900
+ const s = names.get(e.source) ?? e.source
901
+ const t = names.get(e.target) ?? e.target
902
+ const end = e.markerEnd ?? 'arrow-closed'
903
+ const start = e.markerStart ?? 'none'
904
+ let l: string
905
+ if (e.hidden) l = '~~~'
906
+ else {
907
+ const head = end !== 'none'
908
+ const tail = start === 'none' ? '' : '<'
909
+ if (e.dashed) l = `${tail}-.${head ? '->' : '-'}`
910
+ else if ((e.width ?? 2) >= 3) l = `${tail}==${head ? '>' : '='}`
911
+ else l = `${tail}--${head ? '>' : '-'}`
912
+ }
913
+ out.push(` ${s} ${l}${e.label && !e.hidden ? `|${mermaidQuote(e.label)}|` : ''} ${t}`)
914
+ }
915
+ return out.join('\n') + '\n'
916
+ }