Skip to content

Commit

Permalink
Merge 23e590e into 8ffa7e6
Browse files Browse the repository at this point in the history
  • Loading branch information
sidharthv96 committed Oct 10, 2022
2 parents 8ffa7e6 + 23e590e commit 598fed2
Show file tree
Hide file tree
Showing 5 changed files with 412 additions and 30 deletions.
16 changes: 7 additions & 9 deletions cypress/platform/render-after-error.html
Expand Up @@ -14,16 +14,14 @@
mermaid.init({ startOnLoad: false });

mermaid.mermaidAPI.initialize({ securityLevel: 'strict' });
(async () => {
try {
console.log('rendering');
await mermaid.mermaidAPI.render('graphDiv', `>`);
} catch (e) {}
try {
console.log('rendering');
mermaid.mermaidAPI.render('graphDiv', `>`);
} catch (e) {}

await mermaid.mermaidAPI.render('graphDiv', `graph LR\n a --> b`, (html) => {
document.getElementById('graph').innerHTML = html;
});
})();
mermaid.mermaidAPI.render('graphDiv', `graph LR\n a --> b`, (html) => {
document.getElementById('graph').innerHTML = html;
});
</script>
</body>
</html>
7 changes: 3 additions & 4 deletions cypress/platform/rerender.html
Expand Up @@ -19,10 +19,9 @@
function rerender(text) {
const graphText = `graph TD
A[${text}] -->|Get money| B(Go shopping)`;
mermaid.mermaidAPI.render('id', graphText).then((svg) => {
console.log('\x1b[35m%s\x1b[0m', '>> graph', svg);
document.getElementById('graph').innerHTML = svg;
});
const graph = mermaid.mermaidAPI.render('id', graphText);
console.log('\x1b[35m%s\x1b[0m', '>> graph', graph);
document.getElementById('graph').innerHTML = graph;
}
</script>
<button id="rerender" onclick="rerender('Saturday')">Rerender</button>
Expand Down
25 changes: 16 additions & 9 deletions packages/mermaid/src/Diagram.ts
Expand Up @@ -81,25 +81,32 @@ export class Diagram {
}
}

// eslint-disable-next-line @typescript-eslint/ban-types
export const getDiagramFromText = async (txt: string, parseError?: Function): Promise<Diagram> => {
export const getDiagramFromText = (
txt: string,
// eslint-disable-next-line @typescript-eslint/ban-types
parseError?: Function
): Diagram | Promise<Diagram> => {
const type = detectType(txt, configApi.getConfig());
try {
// Trying to find the diagram
getDiagram(type);
return new Diagram(txt, parseError);
} catch (error) {
const loader = getDiagramLoader(type);
if (!loader) {
throw new Error(`Diagram ${type} not found.`);
}
// Diagram not available, loading it
const { diagram } = await loader();
registerDiagram(type, diagram, undefined, diagram.injectUtils);
// new diagram will try getDiagram again and if fails then it is a valid throw
// TODO: Uncomment for v10
// // Diagram not available, loading it
// const { diagram } = await loader();
// registerDiagram(type, diagram, undefined, diagram.injectUtils);
// // new diagram will try getDiagram again and if fails then it is a valid throw
return loader().then(({ diagram }) => {
registerDiagram(type, diagram, undefined, diagram.injectUtils);
return new Diagram(txt, parseError);
});
}
// If either of the above worked, we have the diagram
// logic and can continue
return new Diagram(txt, parseError);
// return new Diagram(txt, parseError);
};

export default Diagram;
111 changes: 106 additions & 5 deletions packages/mermaid/src/mermaid.ts
Expand Up @@ -54,8 +54,10 @@ const init = async function (
addDetector(id, detector, loadDiagram);
})
);
await initThrowsErrorsAsync(config, nodes, callback);
} else {
initThrowsErrors(config, nodes, callback);
}
await initThrowsErrors(config, nodes, callback);
} catch (e) {
log.warn('Syntax Error rendering');
if (isDetailedError(e)) {
Expand All @@ -67,7 +69,7 @@ const init = async function (
}
};

const initThrowsErrors = async function (
const initThrowsErrors = function (
config?: MermaidConfig,
// eslint-disable-next-line no-undef
nodes?: string | HTMLElement | NodeListOf<HTMLElement>,
Expand Down Expand Up @@ -134,7 +136,7 @@ const initThrowsErrors = async function (
log.debug('Detected early reinit: ', init);
}
try {
await mermaidAPI.render(
mermaidAPI.render(
id,
txt,
(svgCode: string, bindFunctions?: (el: Element) => void) => {
Expand Down Expand Up @@ -162,8 +164,107 @@ const initThrowsErrors = async function (
}
};

const initialize = async function (config: MermaidConfig) {
await mermaidAPI.initialize(config);
/**
* @deprecated This is an internal function and should not be used. Will be removed in v10.
*/

const initThrowsErrorsAsync = async function (
config?: MermaidConfig,
// eslint-disable-next-line no-undef
nodes?: string | HTMLElement | NodeListOf<HTMLElement>,
// eslint-disable-next-line @typescript-eslint/ban-types
callback?: Function
) {
const conf = mermaidAPI.getConfig();
// console.log('Starting rendering diagrams (init) - mermaid.init', conf);
if (config) {
// This is a legacy way of setting config. It is not documented and should be removed in the future.
// @ts-ignore: TODO Fix ts errors
mermaid.sequenceConfig = config;
}

// if last argument is a function this is the callback function
log.debug(`${!callback ? 'No ' : ''}Callback function found`);
let nodesToProcess: ArrayLike<HTMLElement>;
if (typeof nodes === 'undefined') {
nodesToProcess = document.querySelectorAll('.mermaid');
} else if (typeof nodes === 'string') {
nodesToProcess = document.querySelectorAll(nodes);
} else if (nodes instanceof HTMLElement) {
nodesToProcess = [nodes];
} else if (nodes instanceof NodeList) {
nodesToProcess = nodes;
} else {
throw new Error('Invalid argument nodes for mermaid.init');
}

log.debug(`Found ${nodesToProcess.length} diagrams`);
if (typeof config?.startOnLoad !== 'undefined') {
log.debug('Start On Load: ' + config?.startOnLoad);
mermaidAPI.updateSiteConfig({ startOnLoad: config?.startOnLoad });
}

// generate the id of the diagram
const idGenerator = new utils.initIdGenerator(conf.deterministicIds, conf.deterministicIDSeed);

let txt: string;
const errors = [];

// element is the current div with mermaid class
for (const element of Array.from(nodesToProcess)) {
log.info('Rendering diagram: ' + element.id);
/*! Check if previously processed */
if (element.getAttribute('data-processed')) {
continue;
}
element.setAttribute('data-processed', 'true');

const id = `mermaid-${idGenerator.next()}`;

// Fetch the graph definition including tags
txt = element.innerHTML;

// transforms the html to pure text
txt = utils
.entityDecode(txt)
.trim()
.replace(/<br\s*\/?>/gi, '<br/>');

const init = utils.detectInit(txt);
if (init) {
log.debug('Detected early reinit: ', init);
}
try {
await mermaidAPI.renderAsync(
id,
txt,
(svgCode: string, bindFunctions?: (el: Element) => void) => {
element.innerHTML = svgCode;
if (typeof callback !== 'undefined') {
callback(id);
}
if (bindFunctions) bindFunctions(element);
},
element
);
} catch (error) {
log.warn('Catching Error (bootstrap)', error);
// @ts-ignore: TODO Fix ts errors
const mermaidError = { error, str: error.str, hash: error.hash, message: error.str };
if (typeof mermaid.parseError === 'function') {
mermaid.parseError(mermaidError);
}
errors.push(mermaidError);
}
}
if (errors.length > 0) {
// TODO: We should be throwing an error object.
throw errors[0];
}
};

const initialize = function (config: MermaidConfig) {
mermaidAPI.initialize(config);
};

/**
Expand Down

0 comments on commit 598fed2

Please sign in to comment.