Commiton issue #3061 Injecting mermaid utilities in registered diagram

This commit is contained in:
Knut Sveidqvist 2022-09-26 08:01:23 +02:00
parent 493aac6885
commit 9566f51ca8
15 changed files with 197 additions and 77 deletions

View File

@ -16,14 +16,17 @@ type OutputOptions = Exclude<
const packageOptions = {
mermaid: {
name: 'mermaid',
packageName: 'mermaid',
file: 'mermaid.ts',
},
'mermaid-mindmap': {
name: 'mermaid-mindmap',
packageName: 'mermaid-mindmap',
file: 'diagram.ts',
},
'mermaid-mindmap-detector': {
name: 'mermaid-mindmap-detector',
packageName: 'mermaid-mindmap',
file: 'registry.ts',
},
};
@ -32,17 +35,13 @@ interface BuildOptions {
minify: boolean | 'esbuild';
core?: boolean;
watch?: boolean;
packageName: keyof typeof packageOptions;
entryName: keyof typeof packageOptions;
}
export const getBuildConfig = ({
minify,
core,
watch,
packageName,
}: BuildOptions): InlineConfig => {
export const getBuildConfig = ({ minify, core, watch, entryName }: BuildOptions): InlineConfig => {
const external = ['require', 'fs', 'path'];
const { name, file } = packageOptions[packageName];
console.log(entryName, packageOptions[entryName]);
const { name, file, packageName } = packageOptions[entryName];
let output: OutputOptions = [
{
name,
@ -105,11 +104,11 @@ export const getBuildConfig = ({
return config;
};
const buildPackage = async (packageName: keyof typeof packageOptions) => {
const buildPackage = async (entryName: keyof typeof packageOptions) => {
return Promise.allSettled([
build(getBuildConfig({ minify: false, packageName })),
build(getBuildConfig({ minify: 'esbuild', packageName })),
build(getBuildConfig({ minify: false, core: true, packageName })),
build(getBuildConfig({ minify: false, entryName })),
build(getBuildConfig({ minify: 'esbuild', entryName })),
build(getBuildConfig({ minify: false, core: true, entryName })),
]);
};
@ -121,7 +120,7 @@ const main = async () => {
};
if (watch) {
build(getBuildConfig({ minify: false, watch, packageName: 'mermaid' }));
build(getBuildConfig({ minify: false, watch, entryName: 'mermaid' }));
} else {
void main();
}

View File

@ -45,12 +45,17 @@
</head>
<body>
<div>Security check</div>
<pre id="diagram" class="mermaid2">
flowchart LR
A --> B
</pre>
<pre id="diagram" class="mermaid">
mindmap
root
ch1
ch2
</pre>
<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>
@ -58,20 +63,14 @@
// console.error('Mermaid error: ', err);
};
mermaid.initialize({
startOnLoad: false,
startOnLoad: true,
logLevel: 0,
basePath: './packages/',
// themeVariables: {relationLabelColor: 'red'}
});
function callback() {
alert('It worked');
}
// document.querySelector('#diagram').innerHTML = diagram;
try {
mermaid.initThrowsErrors(undefined, '#diagram');
} catch (err) {
console.log('Caught error:', err);
}
</script>
</body>
</html>

View File

@ -1,18 +0,0 @@
// @ts-ignore: TODO Fix ts errors
import { mindmapDetector } from './mindmapDetector';
if (typeof document !== 'undefined') {
/*!
* Wait for document loaded before starting the execution
*/
window.addEventListener(
'load',
() => {
if (window.mermaid && typeof window.mermaid.detectors === 'object') {
window.mermaid.detectors.push(mindmapDetector);
console.log(window.mermaid.detectors); // eslint-disable-line no-console
}
},
false
);
}

View File

@ -3,7 +3,7 @@ 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
@ -13,12 +13,22 @@ 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.detectors === 'object') {
// window.mermaid.detectors.push(mindmapDetector);
console.log(window.mermaid.detectors); // eslint-disable-line no-console
if (window.mermaid && typeof window.mermaid.c) {
window.mermaid.connectDiagram(
'mindmap',
{
db: mindmapDb,
renderer: mindmapRenderer,
parser: mindmapParser,
styles: mindmapStyles,
},
injectUtils
);
}
},
false

View File

@ -0,0 +1,77 @@
const warning = (s: string) => {
// Todo remove debug code
console.error('Log function was called before initialization', s); // eslint-disable-line
};
export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
export const LEVELS: Record<LogLevel, number> = {
trace: 0,
debug: 1,
info: 2,
warn: 3,
error: 4,
fatal: 5,
};
export const log: Record<keyof typeof LEVELS, typeof console.log> = {
trace: warning,
debug: warning,
info: warning,
warn: warning,
error: warning,
fatal: warning,
};
export let setLogLevel: (level: keyof typeof LEVELS | number | string) => void;
export let getConfig: () => object;
export let sanitizeText: (str: string) => string;
// eslint-disable @typescript-eslint/no-explicit-any
export let setupGraphViewbox: (
graph: any,
svgElem: any,
padding: any,
useMaxWidth: boolean
) => void;
export const injectUtils = (
_log: Record<keyof typeof LEVELS, typeof console.log>,
_setLogLevel: any,
_getConfig: any,
_sanitizeText: any,
_setupGraphViewbox: any
) => {
log.debug = _log.debug;
log.info = _log.info;
log.warn = _log.warn;
log.error = _log.error;
setLogLevel = _setLogLevel;
getConfig = _getConfig;
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

@ -1,5 +1,5 @@
/** Created by knut on 15-01-14. */
import { sanitizeText, getConfig, log as _log } from 'mermaid/diagramAPI';
import { sanitizeText, getConfig, log as _log } from './mermaidUtils';
let nodes = [];
let cnt = 0;
@ -133,6 +133,7 @@ export const type2Str = (type) => {
};
// Expose logger to grammar
export const log = _log;
export let graphType = 'mindmap';
export const getNodeById = (id) => nodes[id];
export const getElementById = (id) => elements[id];
// export default {

View File

@ -1,6 +1,6 @@
/** Created by knut on 14-12-11. */
import { select } from 'd3';
import { log, getConfig, setupGraphViewbox } from '../../diagram-api/diagramAPI';
import { log, getConfig, setupGraphViewbox } from './mermaidUtils';
import svgDraw from './svgDraw';
import { BoundingBox, Layout } from 'non-layered-tidy-tree-layout';
import clone from 'fast-clone';

View File

@ -1,27 +1,27 @@
// @ts-ignore: TODO Fix ts errors
// import mindmapParser from './parser/mindmap';
// import * as mindmapDb from './mindmapDb';
import { mindmapDetector } from './mindmapDetector';
// import mindmapRenderer from './mindmapRenderer';
// import mindmapStyles from './styles';
import mermaid from 'mermaid';
if (typeof document !== 'undefined') {
if (window.mermaid && typeof window.mermaid.detectors === 'object') {
window.mermaid.detectors.push({ id: 'mindmap', detector: mindmapDetector });
} else {
console.error('window.mermaid.detectors not found'); // eslint-disable-line no-console
window.mermaid = {};
window.mermaid.detectors = [{ id: 'mindmap', detector: mindmapDetector }];
console.error('Detectors now:', window.mermaid.detectors); // eslint-disable-line no-console
}
console.log('mindmapDb', mermaid.mermaidAPI.getConfig()); // eslint-disable-line no-console
// registerDiagram()
// if (typeof document !== 'undefined') {
// /*!
// * Wait for document loaded before starting the execution
// */
// window.addEventListener(
// 'load',
// () => {
// if (window.mermaid && typeof window.mermaid.detectors === 'object') {
// window.mermaid.detectors.push(mindmapDetector);
// console.log(window.mermaid.detectors); // eslint-disable-line no-console
// }
// },
// false
// );
// }
/*!
* 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 });
// console.error(window.mermaid.detectors); // eslint-disable-line no-console
}
},
false
);
}

View File

@ -26,12 +26,20 @@ export class Diagram {
log.debug('Initialized diagram ' + this.type, cnf);
}
this.txt += '\n';
this.parser.parser.yy.graphType = this.type;
this.parser.parser.yy.parseError = (str: string, hash: string) => {
const error = { str, hash };
throw error;
};
this.parse(this.txt, parseError);
try {
this.parser.parser.yy.graphType = this.type;
this.parser.parser.yy.parseError = (str: string, hash: string) => {
const error = { str, hash };
throw error;
};
} catch (error) {
log.error('error', error);
}
try {
this.parse(this.txt, parseError);
} catch (error) {
log.error('error', error);
}
}
// eslint-disable-next-line @typescript-eslint/ban-types

View File

@ -27,18 +27,32 @@ export interface DiagramDefinition {
}
const diagrams: Record<string, DiagramDefinition> = {};
const connectCallbacks: Record<string, any> = {}; // TODO fix, eslint-disable-line @typescript-eslint/no-explicit-any
export interface Detectors {
[key: string]: DiagramDetector;
}
export const registerDetector = (id: string, detector: DiagramDetector) => {
addDetector(id, detector);
};
export const registerDiagram = (
id: string,
diagram: DiagramDefinition,
detector: DiagramDetector
callback: (
_log: any,
_setLogLevel: any,
_getConfig: any,
_sanitizeText: any,
_setupGraphViewbox: any
) => void
) => {
if (diagrams[id]) {
log.warn(`Diagram ${id} already registered.`);
}
diagrams[id] = diagram;
addDetector(id, detector);
addStylesForDiagram(id, diagram.styles);
connectCallbacks[id] = callback;
};
export const getDiagram = (name: string): DiagramDefinition => {

View File

@ -6,6 +6,15 @@ import { MermaidConfig } from './config.type';
import { log } from './logger';
import utils from './utils';
import { mermaidAPI } from './mermaidAPI';
import { addDetector } from './diagram-api/detectType';
import {
registerDiagram,
DiagramDefinition,
setLogLevel,
getConfig,
setupGraphViewbox,
sanitizeText,
} from './diagram-api/diagramAPI';
import { isDetailedError } from './utils';
/**
@ -44,6 +53,10 @@ const init = function (
callback?: Function
) {
try {
console.error('Detectors in init', mermaid.detectors); // eslint-disable-line
mermaid.detectors.forEach(({ id, detector }) => {
addDetector(id, detector);
});
initThrowsErrors(config, nodes, callback);
} catch (e) {
log.warn('Syntax Error rendering');
@ -197,6 +210,22 @@ const parse = (txt: string) => {
return mermaidAPI.parse(txt, mermaid.parseError);
};
const connectDiagram = (
id: string,
diagram: DiagramDefinition,
callback: (
_log: any,
_setLogLevel: any,
_getConfig: any,
_sanitizeText: any,
_setupGraphViewbox: any
) => void
) => {
registerDiagram(id, diagram, callback);
// Todo move this connect call to after the diagram is actually loaded
callback(log, setLogLevel, getConfig, sanitizeText, setupGraphViewbox);
};
const mermaid: {
startOnLoad: boolean;
diagrams: any;
@ -212,6 +241,7 @@ const mermaid: {
setParseErrorHandler: typeof setParseErrorHandler;
// Array of functions to use for detecting diagram types
detectors: Array<any>; // eslint-disable-line @typescript-eslint/no-explicit-any
connectDiagram: (id: string, diagram: DiagramDefinition, callback: (id: string) => void) => void;
} = {
startOnLoad: true,
diagrams: {},
@ -225,6 +255,7 @@ const mermaid: {
contentLoaded,
setParseErrorHandler,
detectors: [],
connectDiagram: connectDiagram,
};
export default mermaid;

View File

@ -72,7 +72,6 @@ const directiveWithoutOpen =
* g-->h
* ```
* @param {string} text The text defining the graph
* @param {any} config
* @returns {object} The json object representing the init passed to mermaid.initialize()
*/
export const detectInit = function (text: string, config?: MermaidConfig): MermaidConfig {