-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmermaid-isomorphic.ts
340 lines (295 loc) · 8.15 KB
/
mermaid-isomorphic.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import { type Mermaid, type MermaidConfig } from 'mermaid'
import { type BrowserType, chromium, type LaunchOptions, type Page } from 'playwright'
declare const mermaid: Mermaid
const html = import.meta.resolve('../index.html')
const mermaidScript = {
url: import.meta.resolve('mermaid/dist/mermaid.js')
}
const faStyle = {
// We use url, not path. If we use path, the fonts can’t be resolved.
url: import.meta.resolve('@fortawesome/fontawesome-free/css/all.css')
}
export interface CreateMermaidRendererOptions {
/**
* The Playwright browser to use.
*
* @default chromium
*/
browserType?: BrowserType
/**
* The options used to launch the browser.
*/
launchOptions?: LaunchOptions
}
export interface RenderResult {
/**
* The aria description of the diagram.
*/
description?: string
/**
* The height of the resulting SVG.
*/
height: number
/**
* The DOM id of the SVG node.
*/
id: string
/**
* The diagram SVG rendered as a PNG buffer.
*/
screenshot?: Buffer
/**
* The diagram rendered as an SVG.
*/
svg: string
/**
* The title of the rendered diagram.
*/
title?: string
/**
* The width of the resulting SVG.
*/
width: number
}
export interface RenderOptions {
/**
* A URL that points to a custom CSS file to load.
*
* Use this to load custom fonts.
*
* This option is ignored in the browser. You need to include the CSS in your build manually.
*/
css?: Iterable<URL | string> | URL | string | undefined
/**
* If true, a PNG screenshot of the diagram will be added.
*
* This is only supported in the Node.js.
*/
screenshot?: boolean
/**
* The mermaid configuration.
*
* By default `fontFamily` is set to `arial,sans-serif`.
*
* This option is ignored in the browser. You need to call `mermaid.initialize()` manually.
*/
mermaidConfig?: MermaidConfig
/**
* The prefix of the id.
*
* @default 'mermaid'
*/
prefix?: string | undefined
}
/**
* Render Mermaid diagrams in the browser.
*
* @param diagrams
* The Mermaid diagrams to render.
* @param options
* Additional options to use when rendering the diagrams.
* @returns
* A list of settled promises that contains the rendered Mermaid diagram. Each result matches the
* same index of the input diagrams.
*/
export type MermaidRenderer = (
diagrams: string[],
options?: RenderOptions
) => Promise<PromiseSettledResult<RenderResult>[]>
interface RenderDiagramsOptions
extends Required<Pick<RenderOptions, 'mermaidConfig' | 'prefix' | 'screenshot'>> {
/**
* The diagrams to process.
*/
diagrams: string[]
}
/* c8 ignore start */
/**
* Render mermaid diagrams in the browser.
*
* @param options
* The options used to render the diagrams
* @returns
* A settled promise that holds the rendering results.
*/
async function renderDiagrams({
diagrams,
mermaidConfig,
prefix,
screenshot
}: RenderDiagramsOptions): Promise<PromiseSettledResult<RenderResult>[]> {
await Promise.all(Array.from(document.fonts, (font) => font.load()))
const parser = new DOMParser()
const serializer = new XMLSerializer()
mermaid.initialize(mermaidConfig)
/**
* Get an aria value form a referencing attribute.
*
* @param element
* The SVG element the get the value from.
* @param attribute
* The attribute whose value to get.
* @returns
* The aria value.
*/
// eslint-disable-next-line unicorn/consistent-function-scoping
function getAriaValue(element: SVGSVGElement, attribute: string): string | undefined {
const value = element.getAttribute(attribute)
if (!value) {
return
}
let result = ''
for (const id of value.split(/\s+/)) {
const node = element.getElementById(id)
if (node) {
result += node.textContent
}
}
return result
}
return Promise.allSettled(
diagrams.map(async (diagram, index) => {
const id = `${prefix}-${index}`
try {
const { svg } = await mermaid.render(id, diagram)
const root = parser.parseFromString(svg, 'text/html')
const [element] = root.getElementsByTagName('svg')
const { height, width } = element.viewBox.baseVal
const description = getAriaValue(element, 'aria-describedby')
const title = getAriaValue(element, 'aria-labelledby')
if (screenshot) {
document.body.append(element)
}
const result: RenderResult = {
height,
id,
svg: serializer.serializeToString(element),
width
}
if (description) {
result.description = description
}
if (title) {
result.title = title
}
return result
} catch (error) {
throw error instanceof Error
? { name: error.name, stack: error.stack, message: error.message }
: error
}
})
)
}
/* c8 ignore stop */
interface SimpleContext {
/**
* Gracefully close the browser context and the browser.
*/
close: () => Promise<undefined>
/**
* Open a new page.
*/
newPage: () => Promise<Page>
}
/**
* Launch a browser and a single browser context.
*
* @param browserType
* The browser type to launch.
* @param launchOptions
* Optional launch options
* @returns
* A simple browser context wrapper
*/
async function getBrowser(
browserType: BrowserType,
launchOptions: LaunchOptions | undefined
): Promise<SimpleContext> {
const browser = await browserType.launch(launchOptions)
const context = await browser.newContext({ bypassCSP: true })
return {
async close() {
await context.close()
await browser.close()
},
newPage() {
return context.newPage()
}
}
}
/**
* Create a Mermaid renderer.
*
* The Mermaid renderer manages a browser instance. If multiple diagrams are being rendered
* simultaneously, the internal browser instance will be re-used. If no diagrams are being rendered,
* the browser will be closed.
*
* @param options
* The options of the Mermaid renderer.
* @returns
* A function that renders Mermaid diagrams in the browser.
*/
export function createMermaidRenderer(options: CreateMermaidRendererOptions = {}): MermaidRenderer {
const { browserType = chromium, launchOptions } = options
let browserPromise: Promise<SimpleContext> | undefined
let count = 0
return async (diagrams, renderOptions) => {
count += 1
if (!browserPromise) {
browserPromise = getBrowser(browserType, launchOptions)
}
const context = await browserPromise
let page: Page | undefined
let renderResults: PromiseSettledResult<RenderResult>[]
try {
page = await context.newPage()
await page.goto(html)
const promises = [page.addStyleTag(faStyle), page.addScriptTag(mermaidScript)]
const css = renderOptions?.css
if (typeof css === 'string' || css instanceof URL) {
promises.push(page.addStyleTag({ url: String(css) }))
} else if (css) {
for (const url of css) {
promises.push(page.addStyleTag({ url: String(url) }))
}
}
await Promise.all(promises)
renderResults = await page.evaluate(renderDiagrams, {
diagrams,
screenshot: Boolean(renderOptions?.screenshot),
mermaidConfig: {
fontFamily: 'arial,sans-serif',
...renderOptions?.mermaidConfig
},
prefix: renderOptions?.prefix ?? 'mermaid'
})
if (renderOptions?.screenshot) {
for (const result of renderResults) {
if (result.status === 'fulfilled') {
result.value.screenshot = await page
.locator(`#${result.value.id}`)
.screenshot({ omitBackground: true })
}
}
}
} finally {
await page?.close()
count -= 1
if (!count) {
browserPromise = undefined
context.close()
}
}
for (const result of renderResults) {
if (result.status !== 'rejected') {
continue
}
const { reason } = result
if (reason && 'name' in reason && 'message' in reason && 'stack' in reason) {
Object.setPrototypeOf(reason, Error.prototype)
}
}
return renderResults
}
}