1- import mermaid from 'mermaid'
1+ type MermaidNamespace = {
2+ initialize : ( config : { startOnLoad : boolean ; theme : string ; securityLevel ?: string } ) => void
3+ render : ( id : string , definition : string ) => Promise < { svg : string ; bindFunctions ?: ( element : Element ) => void } >
4+ }
25import { DEFAULT_SETTINGS , getSettings , normalizeSettings } from '../shared/settings'
36import { doesUrlMatchPatterns } from '../shared/url'
47
@@ -11,6 +14,17 @@ let observer: MutationObserver | null = null
1114let isActive = false
1215let currentSettings = DEFAULT_SETTINGS
1316const processedBlocks = new Map < HTMLElement , BlockRegistryEntry > ( )
17+ let mermaidPromise : Promise < MermaidNamespace > | null = null
18+
19+ async function ensureMermaid ( ) : Promise < MermaidNamespace > {
20+ if ( ! mermaidPromise ) {
21+ mermaidPromise = import ( 'mermaid' ) . then ( ( module ) => {
22+ const candidate = ( module as { default ?: MermaidNamespace } ) ?. default
23+ return ( candidate ?? ( module as unknown as MermaidNamespace ) )
24+ } )
25+ }
26+ return mermaidPromise
27+ }
1428
1529const RENDER_HARD_FAIL_NOTICE = 'Mermaid could not render this diagram.'
1630const MERMAID_KEYWORDS = [
@@ -53,7 +67,7 @@ async function initialise() {
5367 return
5468 }
5569 const nextSettings = normalizeSettings ( changes . settings . newValue )
56- applySettings ( nextSettings )
70+ void applySettings ( nextSettings )
5771 } )
5872}
5973
@@ -63,7 +77,7 @@ async function activate() {
6377
6478 await ensureDomReady ( )
6579
66- configureMermaid ( )
80+ await configureMermaid ( )
6781 processRoots ( [ document ] )
6882 startObservers ( )
6983}
@@ -76,7 +90,7 @@ function deactivate() {
7690 clearRenderedBlocks ( )
7791}
7892
79- function applySettings ( next : typeof currentSettings ) {
93+ async function applySettings ( next : typeof currentSettings ) {
8094 const shouldBeActive = shouldActivate ( next )
8195 currentSettings = next
8296
@@ -88,7 +102,7 @@ function applySettings(next: typeof currentSettings) {
88102 deactivate ( )
89103 }
90104 if ( shouldBeActive && isActive ) {
91- configureMermaid ( )
105+ await configureMermaid ( )
92106 processRoots ( [ document ] )
93107 }
94108}
@@ -242,6 +256,7 @@ function looksLikeMermaid(code: HTMLElement): boolean {
242256}
243257
244258async function renderBlock ( block : MermaidBlock ) {
259+ const mermaid = await ensureMermaid ( )
245260 const source = extractSource ( block . code )
246261 if ( ! source ) {
247262 return
@@ -451,7 +466,8 @@ function extractSource(code: HTMLElement): string {
451466 return rawText . replace ( / \u200B / g, '' ) . trim ( )
452467}
453468
454- function configureMermaid ( ) {
469+ async function configureMermaid ( ) {
470+ const mermaid = await ensureMermaid ( )
455471 mermaid . initialize ( {
456472 startOnLoad : false ,
457473 theme : isDarkMode ( ) ? 'dark' : 'default' ,
0 commit comments