Skip to content

Commit

Permalink
Commiton issue #3061 Injecting mermaid utilities in registered diagram
Browse files Browse the repository at this point in the history
  • Loading branch information
knsv committed Sep 26, 2022
1 parent 493aac6 commit 9566f51
Show file tree
Hide file tree
Showing 15 changed files with 197 additions and 77 deletions.
25 changes: 12 additions & 13 deletions .vite/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
},
};
Expand All @@ -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,
Expand Down Expand Up @@ -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 })),
]);
};

Expand All @@ -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();
}
15 changes: 7 additions & 8 deletions cypress/platform/knsv2.html
Original file line number Diff line number Diff line change
Expand Up @@ -45,33 +45,32 @@
</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>
mermaid.parseError = function (err, hash) {
// 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>
18 changes: 0 additions & 18 deletions packages/mermaid-mindmap-detector/src/registry.ts

This file was deleted.

18 changes: 14 additions & 4 deletions packages/mermaid-mindmap/src/diagram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
77 changes: 77 additions & 0 deletions packages/mermaid-mindmap/src/mermaidUtils.ts
Original file line number Diff line number Diff line change
@@ -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;
};
*/
3 changes: 2 additions & 1 deletion packages/mermaid-mindmap/src/mindmapDb.js
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion packages/mermaid-mindmap/src/mindmapRenderer.js
Original file line number Diff line number Diff line change
@@ -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';
Expand Down
46 changes: 23 additions & 23 deletions packages/mermaid-mindmap/src/registry.ts
Original file line number Diff line number Diff line change
@@ -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
);
}
20 changes: 14 additions & 6 deletions packages/mermaid/src/Diagram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 16 additions & 2 deletions packages/mermaid/src/diagram-api/diagramAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down
Loading

0 comments on commit 9566f51

Please sign in to comment.