Merge pull request #3731 from aloisklink/fix/load-lazy-loaded-diagrams-in-initThrowsErrors

[9.2.0] Support `lazyLoadedDiagrams` when calling `initThrowsErrorsAsync`
This commit is contained in:
Knut Sveidqvist 2022-10-28 09:33:58 +02:00 committed by GitHub
commit 120940f9f4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 47 additions and 44 deletions

View File

@ -72,7 +72,7 @@ classDiagram
Student "1" --o "1" IdCard : carries Student "1" --o "1" IdCard : carries
Student "1" --o "1" Bike : rides Student "1" --o "1" Bike : rides
</pre> </pre>
<pre id="diagram" class="mermaid"> <pre id="diagram" class="mermaid2">
mindmap mindmap
root root
child1((Circle)) child1((Circle))

View File

@ -25,6 +25,7 @@ function parse(text: string, parseError?: Function): boolean {
// original version cannot be modified since it was frozen with `Object.freeze()` // original version cannot be modified since it was frozen with `Object.freeze()`
export const mermaidAPI = { export const mermaidAPI = {
render: vi.fn(), render: vi.fn(),
renderAsync: vi.fn(),
parse, parse,
parseDirective: vi.fn(), parseDirective: vi.fn(),
initialize: vi.fn(), initialize: vi.fn(),

View File

@ -48,11 +48,13 @@ describe('when using mermaid and ', function () {
const node = document.createElement('div'); const node = document.createElement('div');
node.appendChild(document.createTextNode('graph TD;\na;')); node.appendChild(document.createTextNode('graph TD;\na;'));
await mermaid.initThrowsErrors(undefined, node); mermaid.initThrowsErrors(undefined, node);
// mermaidAPI.render function has been mocked, since it doesn't yet work // mermaidAPI.render function has been mocked, since it doesn't yet work
// in Node.JS (only works in browser) // in Node.JS (only works in browser)
expect(mermaidAPI.render).toHaveBeenCalled(); expect(mermaidAPI.render).toHaveBeenCalled();
}); });
});
describe('when using #initThrowsErrorsAsync', function () {
it('should throw error (but still render) if lazyLoadedDiagram fails', async () => { it('should throw error (but still render) if lazyLoadedDiagram fails', async () => {
const node = document.createElement('div'); const node = document.createElement('div');
node.appendChild(document.createTextNode('graph TD;\na;')); node.appendChild(document.createTextNode('graph TD;\na;'));
@ -60,14 +62,14 @@ describe('when using mermaid and ', function () {
mermaidAPI.setConfig({ mermaidAPI.setConfig({
lazyLoadedDiagrams: ['this-file-does-not-exist.mjs'], lazyLoadedDiagrams: ['this-file-does-not-exist.mjs'],
}); });
await expect(mermaid.initThrowsErrors(undefined, node)).rejects.toThrowError( await expect(mermaid.initThrowsErrorsAsync(undefined, node)).rejects.toThrowError(
// this error message is probably different on every platform // this error message is probably different on every platform
// this one is just for vite-note (node/jest/browser may be different) // this one is just for vite-note (node/jest/browser may be different)
'Failed to load this-file-does-not-exist.mjs' 'Failed to load this-file-does-not-exist.mjs'
); );
// should still render, even if lazyLoadedDiagrams fails // should still render, even if lazyLoadedDiagrams fails
expect(mermaidAPI.render).toHaveBeenCalled(); expect(mermaidAPI.renderAsync).toHaveBeenCalled();
}); });
afterEach(() => { afterEach(() => {

View File

@ -47,7 +47,12 @@ const init = async function (
callback?: Function callback?: Function
) { ) {
try { try {
await initThrowsErrors(config, nodes, callback); const conf = mermaidAPI.getConfig();
if (conf?.lazyLoadedDiagrams && conf.lazyLoadedDiagrams.length > 0) {
await initThrowsErrorsAsync(config, nodes, callback);
} else {
initThrowsErrors(config, nodes, callback);
}
} catch (e) { } catch (e) {
log.warn('Syntax Error rendering'); log.warn('Syntax Error rendering');
if (isDetailedError(e)) { if (isDetailedError(e)) {
@ -84,19 +89,7 @@ const handleError = (error: unknown, errors: DetailedError[], parseError?: Funct
} }
} }
}; };
/** const initThrowsErrors = function (
* Equivalent to {@link init()}, except an error will be thrown on error.
*
* @param config - **Deprecated** Mermaid sequenceConfig.
* @param nodes - One of:
* - A DOM Node
* - An array of DOM nodes (as would come from a jQuery selector)
* - A W3C selector, a la `.mermaid` (default)
* @param callback - Function that is called with the id of each generated mermaid diagram.
*
* @returns Resolves on success, otherwise the {@link Promise} will be rejected with an Error.
*/
const initThrowsErrors = async function (
config?: MermaidConfig, config?: MermaidConfig,
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
nodes?: string | HTMLElement | NodeListOf<HTMLElement>, nodes?: string | HTMLElement | NodeListOf<HTMLElement>,
@ -110,24 +103,6 @@ const initThrowsErrors = async function (
mermaid.sequenceConfig = config; mermaid.sequenceConfig = config;
} }
const errors = [];
if (conf?.lazyLoadedDiagrams && conf.lazyLoadedDiagrams.length > 0) {
// Load all lazy loaded diagrams in parallel
const results = await Promise.allSettled(
conf.lazyLoadedDiagrams.map(async (diagram: string) => {
const { id, detector, loadDiagram } = await import(diagram);
addDetector(id, detector, loadDiagram);
})
);
for (const result of results) {
if (result.status == 'rejected') {
log.warn(`Failed to lazyLoadedDiagram due to `, result.reason);
errors.push(result.reason);
}
}
}
// if last argument is a function this is the callback function // if last argument is a function this is the callback function
log.debug(`${!callback ? 'No ' : ''}Callback function found`); log.debug(`${!callback ? 'No ' : ''}Callback function found`);
let nodesToProcess: ArrayLike<HTMLElement>; let nodesToProcess: ArrayLike<HTMLElement>;
@ -153,6 +128,7 @@ const initThrowsErrors = async function (
const idGenerator = new utils.initIdGenerator(conf.deterministicIds, conf.deterministicIDSeed); const idGenerator = new utils.initIdGenerator(conf.deterministicIds, conf.deterministicIDSeed);
let txt: string; let txt: string;
const errors: DetailedError[] = [];
// element is the current div with mermaid class // element is the current div with mermaid class
for (const element of Array.from(nodesToProcess)) { for (const element of Array.from(nodesToProcess)) {
@ -201,10 +177,12 @@ const initThrowsErrors = async function (
} }
}; };
let lazyLoadingPromise: Promise<unknown> | undefined = undefined; let lazyLoadingPromise: Promise<PromiseSettledResult<void>[]> | undefined = undefined;
/** /**
* @param conf * This is an internal function and should not be made public, as it will likely change.
* @deprecated This is an internal function and should not be used. Will be removed in v10. * @internal
* @param conf - Mermaid config.
* @returns An array of {@link PromiseSettledResult}, showing the status of imports.
*/ */
const registerLazyLoadedDiagrams = async (conf: MermaidConfig) => { const registerLazyLoadedDiagrams = async (conf: MermaidConfig) => {
// Only lazy load once // Only lazy load once
@ -218,7 +196,7 @@ const registerLazyLoadedDiagrams = async (conf: MermaidConfig) => {
}) })
); );
} }
await lazyLoadingPromise; return await lazyLoadingPromise;
}; };
let loadingPromise: Promise<unknown> | undefined = undefined; let loadingPromise: Promise<unknown> | undefined = undefined;
@ -241,9 +219,20 @@ const loadExternalDiagrams = async (conf: MermaidConfig) => {
}; };
/** /**
* @deprecated This is an internal function and should not be used. Will be removed in v10. * Equivalent to {@link init()}, except an error will be thrown on error.
*
* @alpha
* @deprecated This is an internal function and will very likely be modified in v10, or earlier.
* We recommend staying with {@link initThrowsErrors} if you don't need `lazyLoadedDiagrams`.
*
* @param config - **Deprecated** Mermaid sequenceConfig.
* @param nodes - One of:
* - A DOM Node
* - An array of DOM nodes (as would come from a jQuery selector)
* - A W3C selector, a la `.mermaid` (default)
* @param callback - Function that is called with the id of each generated mermaid diagram.
* @returns Resolves on success, otherwise the {@link Promise} will be rejected.
*/ */
const initThrowsErrorsAsync = async function ( const initThrowsErrorsAsync = async function (
config?: MermaidConfig, config?: MermaidConfig,
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
@ -252,6 +241,14 @@ const initThrowsErrorsAsync = async function (
callback?: Function callback?: Function
) { ) {
const conf = mermaidAPI.getConfig(); const conf = mermaidAPI.getConfig();
const registerLazyLoadedDiagramsErrors: Error[] = [];
for (const registerResult of await registerLazyLoadedDiagrams(conf)) {
if (registerResult.status == 'rejected') {
registerLazyLoadedDiagramsErrors.push(registerResult.reason);
}
}
if (config) { if (config) {
// This is a legacy way of setting config. It is not documented and should be removed in the future. // 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 // @ts-ignore: TODO Fix ts errors
@ -326,9 +323,10 @@ const initThrowsErrorsAsync = async function (
handleError(error, errors, mermaid.parseError); handleError(error, errors, mermaid.parseError);
} }
} }
if (errors.length > 0) { const allErrors = [...registerLazyLoadedDiagramsErrors, ...errors];
if (allErrors.length > 0) {
// TODO: We should be throwing an error object. // TODO: We should be throwing an error object.
throw errors[0]; throw allErrors[0];
} }
}; };
@ -523,6 +521,7 @@ const mermaid: {
renderAsync: typeof renderAsync; renderAsync: typeof renderAsync;
init: typeof init; init: typeof init;
initThrowsErrors: typeof initThrowsErrors; initThrowsErrors: typeof initThrowsErrors;
initThrowsErrorsAsync: typeof initThrowsErrorsAsync;
initialize: typeof initialize; initialize: typeof initialize;
initializeAsync: typeof initializeAsync; initializeAsync: typeof initializeAsync;
contentLoaded: typeof contentLoaded; contentLoaded: typeof contentLoaded;
@ -537,6 +536,7 @@ const mermaid: {
renderAsync, renderAsync,
init, init,
initThrowsErrors, initThrowsErrors,
initThrowsErrorsAsync,
initialize, initialize,
initializeAsync, initializeAsync,
parseError: undefined, parseError: undefined,