Merge pull request #3598 from mermaid-js/lazy-load-import

Lazy load import
This commit is contained in:
Knut Sveidqvist 2022-10-07 16:06:48 +02:00 committed by GitHub
commit c99fd2baa9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 77 additions and 106 deletions

View File

@ -22,22 +22,22 @@ const packageOptions = {
'mermaid-mindmap': {
name: 'mermaid-mindmap',
packageName: 'mermaid-mindmap',
file: 'add-diagram.ts',
file: 'diagram-definition.ts',
},
'mermaid-mindmap-detector': {
name: 'mermaid-mindmap-detector',
packageName: 'mermaid-mindmap',
file: 'registry.ts',
file: 'detector.ts',
},
'mermaid-example-diagram': {
name: 'mermaid-example-diagram',
packageName: 'mermaid-example-diagram',
file: 'add-diagram.ts',
file: 'diagram-definition.ts',
},
'mermaid-example-diagram-detector': {
name: 'mermaid-example-diagram-detector',
packageName: 'mermaid-example-diagram',
file: 'registry.ts',
file: 'detector.ts',
},
};

5
V10-BreakingChanges.md Normal file
View File

@ -0,0 +1,5 @@
# A collection of updates that change the behaviour
## Lazy loading and asynchronisity
- Invalid dates are rendered as syntax error instead of returning best guess or the current date

View File

@ -92,7 +92,7 @@ describe('Gantt diagram', () => {
{}
);
});
it('should render a gantt chart for issue #1060', () => {
it('should FAIL redering a gantt chart for issue #1060 with invalid date', () => {
imgSnapshotTest(
`
gantt

View File

@ -385,7 +385,7 @@ flowchart TD
htmlLabels: false,
fontFamily: 'courier',
},
extraDiagrams: ['./mermaid-mindmap-detector.js'],
lazyLoadedDiagrams: ['./mermaid-mindmap-detector.js'],
});
function callback() {
alert('It worked');

View File

@ -55,11 +55,24 @@
</head>
<body>
<div>Security check</div>
<pre id="diagram" class="mermaid2">
example-diagram
</pre
>
<pre id="diagram" class="mermaid">
classDiagram
direction LR
class Student {
-idCard : IdCard
}
class IdCard{
-id : int
-name : string
}
class Bike{
-id : int
-name : string
}
Student "1" --o "1" IdCard : carries
Student "1" --o "1" Bike : rides
</pre>
<pre id="diagram" class="mermaid2">
mindmap
root
A
@ -85,9 +98,14 @@ mindmap
::icon(mdi mdi-fire)
gc7((grand<br/>grand<br/>child 8))
</pre>
<pre id="diagram" class="mermaid2">
example-diagram
</pre>
<!-- <div id="cy"></div> -->
<!-- <script src="http://localhost:9000/packages/mermaid-mindmap/dist/mermaid-mindmap-detector.js"></script> -->
<!-- <script src="./mermaid-example-diagram-detector.js"></script> -->
<!-- <script src="//cdn.jsdelivr.net/npm/mermaid@9.1.7/dist/mermaid.min.js"></script> -->
<script src="./mermaid.js"></script>
<script>
@ -100,8 +118,11 @@ mindmap
logLevel: 0,
// basePath: './packages/',
// themeVariables: { darkMode: true },
extraDiagrams: ['./mermaid-mindmap-detector.esm.mjs'],
// extraDiagrams: ['../../mermaid-mindmap/registry.ts'],
lazyLoadedDiagrams: [
'./mermaid-mindmap-detector.esm.mjs',
'./mermaid-example-diagram-detector.esm.mjs',
],
// lazyLoadedDiagrams: ['../../mermaid-mindmap/registry.ts'],
});
function callback() {
alert('It worked');

View File

@ -36,7 +36,7 @@ const contentLoaded = function () {
document.getElementsByTagName('body')[0].appendChild(div);
}
graphObj.mermaid.extraDiagrams = ['/mermaid-mindmap-detector.esm.mjs'];
graphObj.mermaid.lazyLoadedDiagrams = ['/mermaid-mindmap-detector.esm.mjs'];
mermaid2.initialize(graphObj.mermaid);
mermaid2.init();

View File

@ -125,7 +125,6 @@
"jsdom": "^20.0.1",
"lint-staged": "^13.0.3",
"markdown-it": "^13.0.1",
"moment": "^2.23.0",
"path-browserify": "^1.0.1",
"pnpm": "^7.13.2",
"prettier": "^2.7.1",

View File

@ -1,3 +1,6 @@
// @ts-ignore: TODO Fix ts errors
export const id = 'example-diagram';
/**
* Detector function that will be called by mermaid to determine if the diagram is this type of digram.
*
@ -8,3 +11,8 @@
export const detector = (txt: string) => {
return txt.match(/^\s*example-diagram/) !== null;
};
export const loadDiagram = async () => {
const { diagram } = await import('./diagram-definition');
return { id, diagram };
};

View File

@ -5,13 +5,10 @@ import renderer from './exampleDiagramRenderer';
import styles from './styles';
import { injectUtils } from './mermaidUtils';
window.mermaid.connectDiagram(
'example-diagram',
{
db,
renderer,
parser,
styles,
},
injectUtils
);
export const diagram = {
db,
renderer,
parser,
styles,
injectUtils,
};

View File

@ -1,33 +0,0 @@
// @ts-ignore: TODO Fix ts errors
import { detector } from './exampleDetector';
const scriptElement = document.currentScript as HTMLScriptElement;
const path = scriptElement.src;
const lastSlash = path.lastIndexOf('/');
const baseFolder = lastSlash < 0 ? path : path.substring(0, lastSlash + 1);
if (typeof document !== 'undefined') {
if (window.mermaid && typeof window.mermaid.detectors === 'object') {
window.mermaid.detectors.push({ id: 'example-diagram', detector });
} else {
window.mermaid = {};
window.mermaid.detectors = [{ id: 'example-diagram', detector }];
}
/*
* Wait for document loaded before starting the execution.
*/
window.addEventListener(
'load',
() => {
if (window.mermaid && typeof window.mermaid.detectors === 'object') {
window.mermaid.detectors.push({
id: 'example-diagram',
detector,
path: baseFolder,
});
}
},
false
);
}

View File

@ -5,6 +5,6 @@ export const detector = (txt: string) => {
};
export const loadDiagram = async () => {
const { mindmap } = await import('./add-diagram');
return { id, diagram: mindmap };
const { diagram } = await import('./diagram-definition');
return { id, diagram };
};

View File

@ -5,7 +5,7 @@ import mindmapRenderer from './mindmapRenderer';
import mindmapStyles from './styles';
import { injectUtils } from './mermaidUtils';
export const mindmap = {
export const diagram = {
db: mindmapDb,
renderer: mindmapRenderer,
parser: mindmapParser,

View File

@ -53,29 +53,3 @@ export const injectUtils = (
sanitizeText = _sanitizeText;
setupGraphViewbox = _setupGraphViewbox;
};
/*
const warning = (..._args: any[]) => {
console.error('Log function was called before initialization');
};
export let log = {
trace: warning,
debug: warning,
info: warning,
warn: warning,
error: warning,
fatal: warning,
};
export let setLogLevel;
export let getConfig;
export let sanitizeText;
export let setupGraphViewbox;
export const injectUtils = (_log, _setLogLevel, _getConfig, _sanitizeText, _setupGraphViewbox) => {
log = _log;
setLogLevel = _setLogLevel;
getConfig = _getConfig;
sanitizeText = _sanitizeText;
setupGraphViewbox = _setupGraphViewbox;
};
*/

View File

@ -3,7 +3,7 @@
import DOMPurify from 'dompurify';
export interface MermaidConfig {
extraDiagrams?: any;
lazyLoadedDiagrams?: any;
theme?: string;
themeVariables?: any;
themeCSS?: string;

View File

@ -115,7 +115,7 @@ const config: Partial<MermaidConfig> = {
* Default value: ['secure', 'securityLevel', 'startOnLoad', 'maxTextSize']
*/
secure: ['secure', 'securityLevel', 'startOnLoad', 'maxTextSize'],
extraDiagrams: [],
lazyLoadedDiagrams: [],
/**
* This option controls if the generated ids of nodes in the SVG are generated randomly or based
* on a seed. If set to false, the IDs are generated based on the current date and thus are not

View File

@ -347,9 +347,10 @@ const buildMethodDisplay = function (parsedText) {
};
const buildLegacyDisplay = function (text) {
// if for some reason we don't have any match, use old format to parse text
// if for some reason we dont have any match, use old format to parse text
let displayText = '';
let cssStyle = '';
let memberText = '';
let returnType = '';
let methodStart = text.indexOf('(');
let methodEnd = text.indexOf(')');
@ -370,21 +371,21 @@ const buildLegacyDisplay = function (text) {
}
const parameters = text.substring(methodStart + 1, methodEnd);
const classifier = text.substring(methodEnd + 1, methodEnd + 2);
cssStyle = parseClassifier(classifier);
const classifier = text.substring(methodEnd + 1, 1);
cssStyle = parseClassifier(text.substring(methodEnd + 1, methodEnd + 2));
displayText = visibility + methodName + '(' + parseGenericTypes(parameters.trim()) + ')';
if (methodEnd <= text.length) {
if (methodEnd < text.length) {
returnType = text.substring(methodEnd + 2).trim();
if (returnType !== '') {
returnType = ' : ' + parseGenericTypes(returnType);
displayText += returnType;
}
} else {
// finally - if all else fails, just send the text back as written (other than parsing for generic types)
displayText = parseGenericTypes(text);
}
} else {
// finally - if all else fails, just send the text back as written (other than parsing for generic types)
displayText = parseGenericTypes(text);
}
return {
@ -392,7 +393,6 @@ const buildLegacyDisplay = function (text) {
cssStyle,
};
};
/**
* Adds a <tspan> for a member in a diagram
*

View File

@ -217,10 +217,12 @@ const getStartDate = function (prevTime, dateFormat, str) {
} else {
log.debug('Invalid date:' + str);
log.debug('With date format:' + dateFormat.trim());
const d = new Date(str);
if (typeof d === 'undefined' || isNaN(d.getTime())) {
throw new Error('Invalid date:' + str);
}
return d;
}
// Default date - now
return new Date();
};
/**

View File

@ -55,11 +55,11 @@ const init = async function (
try {
log.info('Detectors in init', mermaid.detectors); // eslint-disable-line
const conf = mermaidAPI.getConfig();
if (typeof conf.extraDiagrams !== 'undefined' && conf.extraDiagrams.length > 0) {
// config.extraDiagrams.forEach(async (diagram: string) => {
const { id, detector, loadDiagram } = await import(conf.extraDiagrams[0]);
addDetector(id, detector, loadDiagram);
// });
if (typeof conf.lazyLoadedDiagrams !== 'undefined' && conf.lazyLoadedDiagrams.length > 0) {
for (let i = 0; i < conf.lazyLoadedDiagrams.length; i++) {
const { id, detector, loadDiagram } = await import(conf.lazyLoadedDiagrams[i]);
addDetector(id, detector, loadDiagram);
}
}
mermaid.detectors.forEach(({ id, detector, path }) => {
addDetector(id, detector, path);

View File

@ -56,7 +56,6 @@ importers:
lint-staged: ^13.0.3
lodash: ^4.17.21
markdown-it: ^13.0.1
moment: ^2.23.0
moment-mini: ^2.24.0
non-layered-tidy-tree-layout: ^2.0.2
path-browserify: ^1.0.1
@ -133,7 +132,6 @@ importers:
jsdom: 20.0.1
lint-staged: 13.0.3
markdown-it: 13.0.1
moment: 2.29.4
path-browserify: 1.0.1
pnpm: 7.13.2
prettier: 2.7.1