Merge branch 'develop' into sidv/fixDetectDiagram

* develop:
  chore: cleanup
  fix: dynamic import
  fix: Filename in viewer.js
  fix: pnpm not found
  fix: Import diagram
  Updated logic for diagram loading
  WIP
This commit is contained in:
Sidharth Vinod
2022-10-07 16:30:34 +08:00
20 changed files with 115 additions and 91 deletions

View File

@@ -5,13 +5,10 @@ import mindmapRenderer from './mindmapRenderer';
import mindmapStyles from './styles';
import { injectUtils } from './mermaidUtils';
window.mermaid.connectDiagram(
'mindmap',
{
db: mindmapDb,
renderer: mindmapRenderer,
parser: mindmapParser,
styles: mindmapStyles,
},
injectUtils
);
export const mindmap = {
db: mindmapDb,
renderer: mindmapRenderer,
parser: mindmapParser,
styles: mindmapStyles,
injectUtils,
};

View File

@@ -1,3 +0,0 @@
export const mindmapDetector = (txt: string) => {
return txt.match(/^\s*mindmap/) !== null;
};

View File

@@ -1,34 +1,10 @@
// @ts-ignore: TODO Fix ts errors
import { mindmapDetector } from './mindmapDetector';
export const id = 'mindmap';
const scriptElement = document.currentScript as HTMLScriptElement;
const path = scriptElement.src;
const lastSlash = path.lastIndexOf('/');
const baseFolder = lastSlash < 0 ? path : path.substring(0, lastSlash + 1);
export const detector = (txt: string) => {
return txt.match(/^\s*mindmap/) !== null;
};
if (typeof document !== 'undefined') {
if (window.mermaid && typeof window.mermaid.detectors === 'object') {
window.mermaid.detectors.push({ id: 'mindmap', detector: mindmapDetector });
} else {
window.mermaid = {};
window.mermaid.detectors = [{ id: 'mindmap', detector: mindmapDetector }];
}
/*!
* Wait for document loaded before starting the execution.
*/
window.addEventListener(
'load',
() => {
if (window.mermaid && typeof window.mermaid.detectors === 'object') {
window.mermaid.detectors.push({
id: 'mindmap',
detector: mindmapDetector,
path: baseFolder,
});
console.error(window.mermaid.detectors); // eslint-disable-line no-console
}
},
false
);
}
export const loadDiagram = async () => {
const { mindmap } = await import('./add-diagram');
return { id, diagram: mindmap };
};

View File

@@ -1,5 +1,6 @@
{
"extends": "../../tsconfig.json",
"module": "esnext",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist"

View File

@@ -1,7 +1,7 @@
import * as configApi from './config';
import { log } from './logger';
import { getDiagram, loadDiagram } from './diagram-api/diagramAPI';
import { detectType, getPathForDiagram } from './diagram-api/detectType';
import { getDiagram, registerDiagram } from './diagram-api/diagramAPI';
import { detectType, getDiagramLoader } from './diagram-api/detectType';
import { isDetailedError } from './utils';
export class Diagram {
type = 'graph';
@@ -90,10 +90,25 @@ export const getDiagramFromText = async (txt: string, parseError?: Function) =>
// Trying to find the diagram
getDiagram(type);
} catch (error) {
const loader = getDiagramLoader(type);
if (!loader) {
throw new Error(`Diagram ${type} not found.`);
}
// Diagram not avaiable, loading it
const path = getPathForDiagram(type);
// const path = getPathForDiagram(type);
const { diagram } = await loader(); // eslint-disable-line @typescript-eslint/no-explicit-any
registerDiagram(
type,
{
db: diagram.db,
renderer: diagram.renderer,
parser: diagram.parser,
styles: diagram.styles,
},
diagram.injectUtils
);
// await loadDiagram('./packages/mermaid-mindmap/dist/mermaid-mindmap.js');
await loadDiagram(path + 'mermaid-' + type + '.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

View File

@@ -3,6 +3,7 @@
import DOMPurify from 'dompurify';
export interface MermaidConfig {
extraDiagrams?: 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: [],
/**
* 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

@@ -1,8 +1,8 @@
import { MermaidConfig } from '../config.type';
export type DiagramDetector = (text: string, config?: MermaidConfig) => boolean;
export type DetectorRecord = { detector: DiagramDetector; path: string };
export type DiagramLoader = (() => Promise<unknown>) | null;
export type DetectorRecord = { detector: DiagramDetector; loader: DiagramLoader };
const directive =
/[%]{2}[{]\s*(?:(?:(\w+)\s*:|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi;
const anyComment = /\s*%%.*\n/gm;
@@ -34,9 +34,9 @@ const detectors: Record<string, DetectorRecord> = {};
*/
export const detectType = function (text: string, config?: MermaidConfig): string {
text = text.replace(directive, '').replace(anyComment, '\n');
for (const [key, detectorRecord] of Object.entries(detectors)) {
if (detectorRecord.detector(text, config)) {
for (const [key, { detector }] of Object.entries(detectors)) {
const diagram = detector(text, config);
if (diagram) {
return key;
}
}
@@ -44,13 +44,12 @@ export const detectType = function (text: string, config?: MermaidConfig): strin
throw new Error(`No diagram type detected for text: ${text}`);
};
export const addDetector = (key: string, detector: DiagramDetector, path: string) => {
detectors[key] = { detector, path };
export const addDetector = (
key: string,
detector: DiagramDetector,
loader: DiagramLoader | null
) => {
detectors[key] = { detector, loader };
};
export const getPathForDiagram = (id: string) => {
const detectorRecord = detectors[id];
if (detectorRecord) {
return detectorRecord.path;
}
};
export const getDiagramLoader = (key: string) => detectors[key].loader;

View File

@@ -112,7 +112,7 @@ const registerDiagramAndDetector = (
detector: DiagramDetector
) => {
registerDiagram(id, diagram);
registerDetector(id, detector, '');
registerDetector(id, detector);
};
export const addDiagrams = () => {

View File

@@ -21,17 +21,13 @@ describe('DiagramAPI', () => {
const detector: DiagramDetector = (str: string) => {
return str.match('loki') !== null;
};
registerDetector('loki', detector, '');
registerDiagram(
'loki',
{
db: {},
parser: {},
renderer: {},
styles: {},
},
(text: string) => text.includes('loki')
);
registerDetector('loki', detector);
registerDiagram('loki', {
db: {},
parser: {},
renderer: {},
styles: {},
});
expect(getDiagram('loki')).not.toBeNull();
expect(detectType('loki diagram')).toBe('loki');
});

View File

@@ -18,12 +18,21 @@ export const getConfig = _getConfig;
export const sanitizeText = (text: string) => _sanitizeText(text, getConfig());
export const setupGraphViewbox = _setupGraphViewbox;
export interface InjectUtils {
_log: any;
_setLogLevel: any;
_getConfig: any;
_sanitizeText: any;
_setupGraphViewbox: any;
}
export interface DiagramDefinition {
db: any;
renderer: any;
parser: any;
styles: any;
init?: (config: MermaidConfig) => void;
injectUtils?: (utils: InjectUtils) => void;
}
const diagrams: Record<string, DiagramDefinition> = {};
@@ -32,8 +41,8 @@ export interface Detectors {
[key: string]: DiagramDetector;
}
export const registerDetector = (id: string, detector: DiagramDetector, path: string) => {
addDetector(id, detector, path);
export const registerDetector = (id: string, detector: DiagramDetector) => {
addDetector(id, detector, null);
};
export const registerDiagram = (
@@ -52,7 +61,9 @@ export const registerDiagram = (
}
diagrams[id] = diagram;
addStylesForDiagram(id, diagram.styles);
connectCallbacks[id] = callback;
if (typeof callback !== 'undefined') {
callback(log, setLogLevel, getConfig, sanitizeText, setupGraphViewbox);
}
};
export const getDiagram = (name: string): DiagramDefinition => {

View File

@@ -54,10 +54,17 @@ 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);
// });
}
mermaid.detectors.forEach(({ id, detector, path }) => {
addDetector(id, detector, path);
});
initThrowsErrors(config, nodes, callback);
await initThrowsErrors(config, nodes, callback);
} catch (e) {
log.warn('Syntax Error rendering');
if (isDetailedError(e)) {
@@ -164,8 +171,8 @@ const initThrowsErrors = async function (
}
};
const initialize = function (config: MermaidConfig) {
mermaidAPI.initialize(config);
const initialize = async function (config: MermaidConfig) {
await mermaidAPI.initialize(config);
};
/**

View File

@@ -18,6 +18,7 @@ import { compile, serialize, stringify } from 'stylis';
import pkg from '../package.json';
import * as configApi from './config';
import { addDiagrams } from './diagram-api/diagram-orchestration';
import { addDetector } from './diagram-api/detectType';
import classDb from './diagrams/class/classDb';
import flowDb from './diagrams/flowchart/flowDb';
import flowRenderer from './diagrams/flowchart/flowRenderer';
@@ -461,7 +462,7 @@ const handleDirective = function (p: any, directive: any, type: string): void {
};
/** @param {MermaidConfig} options */
function initialize(options: MermaidConfig) {
async function initialize(options: MermaidConfig) {
// Handle legacy location of font-family configuration
if (options?.fontFamily) {
if (!options.themeVariables?.fontFamily) {
@@ -485,6 +486,7 @@ function initialize(options: MermaidConfig) {
typeof options === 'object' ? configApi.setSiteConfig(options) : configApi.getSiteConfig();
setLogLevel(config.logLevel);
if (!hasLoadedDiagrams) {
addDiagrams();
hasLoadedDiagrams = true;