#3061 Lazy loading auto derived path

This commit is contained in:
Knut Sveidqvist
2022-09-26 14:22:21 +02:00
parent a928120bec
commit 982c1b4979
14 changed files with 109 additions and 71 deletions

View File

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

View File

@@ -45,18 +45,19 @@
</head> </head>
<body> <body>
<div>Security check</div> <div>Security check</div>
<pre id="diagram" class="mermaid">
flowchart LR
A -> B
</pre>
<pre id="diagram" class="mermaid2"> <pre id="diagram" class="mermaid2">
mindmap(( flowchart LR
A -> B
</pre
>
<pre id="diagram" class="mermaid">
mindmap
root root
ch1 ch1
ch2 ch2
</pre> </pre
>
<script src="./packages/mermaid-mindmap/dist/mermaid-mindmap-detector.js"></script> <script src="./packages/mermaid-mindmap/dist/mermaid-mindmap-detector.js"></script>
<script src="./packages/mermaid-mindmap/dist/mermaid-mindmap.js"></script>
<script src="./packages/mermaid/dist/mermaid.js"></script> <script src="./packages/mermaid/dist/mermaid.js"></script>
<script> <script>
mermaid.parseError = function (err, hash) { mermaid.parseError = function (err, hash) {

View File

@@ -0,0 +1,23 @@
// @ts-ignore: TODO Fix ts errors
import mindmapParser from './parser/mindmap';
import * as mindmapDb from './mindmapDb';
import mindmapRenderer from './mindmapRenderer';
import mindmapStyles from './styles';
import { injectUtils } from './mermaidUtils';
// const getBaseFolder = (path: string) => {
// const parts = path.split('/');
// parts.pop();
// return parts.join('/');
// };
window.mermaid.connectDiagram(
'mindmap',
{
db: mindmapDb,
renderer: mindmapRenderer,
parser: mindmapParser,
styles: mindmapStyles,
},
injectUtils
);

View File

@@ -1,36 +0,0 @@
// @ts-ignore: TODO Fix ts errors
import mindmapParser from './parser/mindmap';
import * as mindmapDb from './mindmapDb';
import mindmapRenderer from './mindmapRenderer';
import mindmapStyles from './styles';
import { injectUtils } from './mermaidUtils';
// import mermaid from 'mermaid';
// console.log('mindmapDb', mindmapDb.getMindmap()); // eslint-disable-line no-console
// registerDiagram()
if (typeof document !== 'undefined') {
/*!
* Wait for document loaded before starting the execution
*/
// { parser: mindmapParser, db: mindmapDb, renderer: mindmapRenderer, styles: mindmapStyles },
window.addEventListener(
'load',
() => {
if (window.mermaid && typeof window.mermaid.c) {
window.mermaid.connectDiagram(
'mindmap',
{
db: mindmapDb,
renderer: mindmapRenderer,
parser: mindmapParser,
styles: mindmapStyles,
},
injectUtils
);
}
},
false
);
}

View File

@@ -1,8 +1,3 @@
// import type { DiagramDetector } from '../../diagram-api/detectType';
// export const mindmapDetector: DiagramDetector = (txt) => {
// return txt.match(/^\s*mindmap/) !== null;
// };
export const mindmapDetector = (txt: string) => { export const mindmapDetector = (txt: string) => {
return txt.match(/^\s*mindmap/) !== null; return txt.match(/^\s*mindmap/) !== null;
}; };

View File

@@ -1,6 +1,16 @@
// @ts-ignore: TODO Fix ts errors // @ts-ignore: TODO Fix ts errors
import { mindmapDetector } from './mindmapDetector'; import { mindmapDetector } from './mindmapDetector';
// const getBaseFolder = () => {
const scriptElement = document.currentScript as HTMLScriptElement;
const path = scriptElement.src;
const lastSlash = path.lastIndexOf('/');
const baseFolder = lastSlash < 0 ? path : path.substring(0, lastSlash + 1);
// };
// console.log('Current script', getBaseFolder(scriptElement !== null ? scriptElement.src : '')); // eslint-disable-line no-console
if (typeof document !== 'undefined') { if (typeof document !== 'undefined') {
if (window.mermaid && typeof window.mermaid.detectors === 'object') { if (window.mermaid && typeof window.mermaid.detectors === 'object') {
window.mermaid.detectors.push({ id: 'mindmap', detector: mindmapDetector }); window.mermaid.detectors.push({ id: 'mindmap', detector: mindmapDetector });
@@ -18,7 +28,11 @@ if (typeof document !== 'undefined') {
'load', 'load',
() => { () => {
if (window.mermaid && typeof window.mermaid.detectors === 'object') { if (window.mermaid && typeof window.mermaid.detectors === 'object') {
window.mermaid.detectors.push({ id: 'mindmap', detector: mindmapDetector }); window.mermaid.detectors.push({
id: 'mindmap',
detector: mindmapDetector,
path: baseFolder,
});
// console.error(window.mermaid.detectors); // eslint-disable-line no-console // console.error(window.mermaid.detectors); // eslint-disable-line no-console
} }
}, },

View File

@@ -1,7 +1,7 @@
import * as configApi from './config'; import * as configApi from './config';
import { log } from './logger'; import { log } from './logger';
import { getDiagram } from './diagram-api/diagramAPI'; import { getDiagram, loadDiagram } from './diagram-api/diagramAPI';
import { detectType } from './diagram-api/detectType'; import { detectType, getPathForDiagram } from './diagram-api/detectType';
import { isDetailedError } from './utils'; import { isDetailedError } from './utils';
export class Diagram { export class Diagram {
type = 'graph'; type = 'graph';
@@ -67,3 +67,21 @@ export class Diagram {
} }
export default Diagram; export default Diagram;
// eslint-disable-next-line @typescript-eslint/ban-types
export const getDiagramFromText = async (txt: string, parseError?: Function) => {
const type = detectType(txt, configApi.getConfig());
try {
// Trying to find the diagram
getDiagram(type);
} catch (error) {
// Diagram not avaiable, loading it
const path = getPathForDiagram(type);
// await loadDiagram('./packages/mermaid-mindmap/dist/mermaid-mindmap.js');
await loadDiagram(path + 'mermaid-' + type + '.js');
// new diagram will try getDiagram again and if fails then it is a valid throw
}
// If either of the above worked, we have the diagram
// logic and can continue
return new Diagram(txt, parseError);
};

View File

@@ -39,8 +39,6 @@ const edgeInCluster = (edge, clusterId) => {
log.debug('Tilt, ', clusterId, ',not in decendants'); log.debug('Tilt, ', clusterId, ',not in decendants');
return false; return false;
} }
log.info('Here ');
if (decendants[clusterId].indexOf(edge.v) >= 0) return true; if (decendants[clusterId].indexOf(edge.v) >= 0) return true;
if (isDecendant(edge.v, clusterId)) return true; if (isDecendant(edge.v, clusterId)) return true;
if (isDecendant(edge.w, clusterId)) return true; if (isDecendant(edge.w, clusterId)) return true;

View File

@@ -1,12 +1,13 @@
import { MermaidConfig } from '../config.type'; import { MermaidConfig } from '../config.type';
export type DiagramDetector = (text: string, config?: MermaidConfig) => boolean; export type DiagramDetector = (text: string, config?: MermaidConfig) => boolean;
export type DetectorRecord = { detector: DiagramDetector; path: string };
const directive = const directive =
/[%]{2}[{]\s*(?:(?:(\w+)\s*:|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi; /[%]{2}[{]\s*(?:(?:(\w+)\s*:|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi;
const anyComment = /\s*%%.*\n/gm; const anyComment = /\s*%%.*\n/gm;
const detectors: Record<string, DiagramDetector> = {}; const detectors: Record<string, DetectorRecord> = {};
/** /**
* @function detectType Detects the type of the graph text. Takes into consideration the possible * @function detectType Detects the type of the graph text. Takes into consideration the possible
@@ -36,8 +37,8 @@ export const detectType = function (text: string, config?: MermaidConfig): strin
// console.log(detectors); // console.log(detectors);
for (const [key, detector] of Object.entries(detectors)) { for (const [key, detectorRecord] of Object.entries(detectors)) {
if (detector(text, config)) { if (detectorRecord.detector(text, config)) {
return key; return key;
} }
} }
@@ -46,6 +47,13 @@ export const detectType = function (text: string, config?: MermaidConfig): strin
return 'flowchart'; return 'flowchart';
}; };
export const addDetector = (key: string, detector: DiagramDetector) => { export const addDetector = (key: string, detector: DiagramDetector, path: string) => {
detectors[key] = detector; detectors[key] = { detector, path };
};
export const getPathForDiagram = (id: string) => {
const detectorRecord = detectors[id];
if (detectorRecord) {
return detectorRecord.path;
}
}; };

View File

@@ -112,7 +112,7 @@ const registerDiagramAndDetector = (
detector: DiagramDetector detector: DiagramDetector
) => { ) => {
registerDiagram(id, diagram); registerDiagram(id, diagram);
registerDetector(id, detector); registerDetector(id, detector, '');
}; };
export const addDiagrams = () => { export const addDiagrams = () => {
@@ -136,9 +136,9 @@ export const addDiagrams = () => {
init: () => { init: () => {
// no op // no op
}, },
} },
(text) => text.toLowerCase().trim() === 'error'
); );
registerDetector('error', (text) => text.toLowerCase().trim() === 'error');
registerDiagramAndDetector( registerDiagramAndDetector(
'c4', 'c4',

View File

@@ -19,7 +19,7 @@ describe('DiagramAPI', () => {
const detector: DiagramDetector = (str: string) => { const detector: DiagramDetector = (str: string) => {
return str.match('loki') !== null; return str.match('loki') !== null;
}; };
registerDetector('loki', detector); registerDetector('loki', detector, '');
registerDiagram( registerDiagram(
'loki', 'loki',
{ {

View File

@@ -32,8 +32,8 @@ export interface Detectors {
[key: string]: DiagramDetector; [key: string]: DiagramDetector;
} }
export const registerDetector = (id: string, detector: DiagramDetector) => { export const registerDetector = (id: string, detector: DiagramDetector, path: string) => {
addDetector(id, detector); addDetector(id, detector, path);
}; };
export const registerDiagram = ( export const registerDiagram = (
@@ -61,3 +61,19 @@ export const getDiagram = (name: string): DiagramDefinition => {
} }
throw new Error(`Diagram ${name} not found.`); throw new Error(`Diagram ${name} not found.`);
}; };
/**
*
* @param sScriptSrc
*/
export const loadDiagram = (sScriptSrc: string) =>
new Promise((resolve) => {
const oHead = document.getElementsByTagName('HEAD')[0];
const oScript = document.createElement('script');
oScript.type = 'text/javascript';
oScript.src = sScriptSrc;
oHead.appendChild(oScript);
oScript.onload = () => {
resolve(true);
};
});

View File

@@ -54,8 +54,8 @@ const init = function (
) { ) {
try { try {
log.info('Detectors in init', mermaid.detectors); // eslint-disable-line log.info('Detectors in init', mermaid.detectors); // eslint-disable-line
mermaid.detectors.forEach(({ id, detector }) => { mermaid.detectors.forEach(({ id, detector, path }) => {
addDetector(id, detector); addDetector(id, detector, path);
}); });
initThrowsErrors(config, nodes, callback); initThrowsErrors(config, nodes, callback);
} catch (e) { } catch (e) {

View File

@@ -22,7 +22,7 @@ import classDb from './diagrams/class/classDb';
import flowDb from './diagrams/flowchart/flowDb'; import flowDb from './diagrams/flowchart/flowDb';
import flowRenderer from './diagrams/flowchart/flowRenderer'; import flowRenderer from './diagrams/flowchart/flowRenderer';
import ganttDb from './diagrams/gantt/ganttDb'; import ganttDb from './diagrams/gantt/ganttDb';
import Diagram from './Diagram'; import Diagram, { getDiagramFromText } from './Diagram';
import errorRenderer from './diagrams/error/errorRenderer'; import errorRenderer from './diagrams/error/errorRenderer';
import { attachFunctions } from './interactionDb'; import { attachFunctions } from './interactionDb';
import { log, setLogLevel } from './logger'; import { log, setLogLevel } from './logger';
@@ -115,12 +115,12 @@ export const decodeEntities = function (text: string): string {
* element will be removed when rendering is completed. * element will be removed when rendering is completed.
* @returns {void} * @returns {void}
*/ */
const render = function ( const render = async function (
id: string, id: string,
text: string, text: string,
cb: (svgCode: string, bindFunctions?: (element: Element) => void) => void, cb: (svgCode: string, bindFunctions?: (element: Element) => void) => void,
container?: Element container?: Element
): void { ): Promise<void> {
if (!hasLoadedDiagrams) { if (!hasLoadedDiagrams) {
addDiagrams(); addDiagrams();
hasLoadedDiagrams = true; hasLoadedDiagrams = true;
@@ -232,7 +232,8 @@ const render = function (
let diag; let diag;
let parseEncounteredException; let parseEncounteredException;
try { try {
diag = new Diagram(text); // diag = new Diagram(text);
diag = await getDiagramFromText(text);
} catch (error) { } catch (error) {
diag = new Diagram('error'); diag = new Diagram('error');
parseEncounteredException = error; parseEncounteredException = error;