Skip to content

Commit

Permalink
feat: Add diagramType to RenderResult and ParseResult #5117
Browse files Browse the repository at this point in the history
  • Loading branch information
sidharthv96 committed Dec 6, 2023
1 parent 000b432 commit c3c7ccd
Show file tree
Hide file tree
Showing 5 changed files with 78 additions and 32 deletions.
16 changes: 14 additions & 2 deletions docs/config/setup/interfaces/mermaidAPI.RenderResult.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,19 @@ bindFunctions?.(div); // To call bindFunctions only if it's present.
#### Defined in
[mermaidAPI.ts:80](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L80)
[mermaidAPI.ts:96](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L96)
---
### diagramType
• **diagramType**: `string`
The diagram type, e.g. 'flowchart', 'sequence', etc.
#### Defined in
[mermaidAPI.ts:86](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L86)
---
Expand All @@ -51,4 +63,4 @@ The svg code for the rendered graph.
#### Defined in
[mermaidAPI.ts:70](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L70)
[mermaidAPI.ts:82](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L82)
30 changes: 20 additions & 10 deletions docs/config/setup/modules/mermaidAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,23 @@ Renames and re-exports [mermaidAPI](mermaidAPI.md#mermaidapi)

#### Defined in

[mermaidAPI.ts:64](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L64)
[mermaidAPI.ts:76](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L76)

---

### ParseResult

Ƭ **ParseResult**: { `diagramType`: `string` ; `isValid`: `true` } | { `isValid`: `false` }

#### Defined in

[mermaidAPI.ts:63](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L63)

## Variables

### mermaidAPI

`Const` **mermaidAPI**: `Readonly`<{ `defaultConfig`: `MermaidConfig` = configApi.defaultConfig; `getConfig`: () => `MermaidConfig` = configApi.getConfig; `getDiagramFromText`: (`text`: `string`, `metadata`: `Pick`<`DiagramMetadata`, `"title"`>) => `Promise`<`Diagram`> ; `getSiteConfig`: () => `MermaidConfig` = configApi.getSiteConfig; `globalReset`: () => `void` ; `initialize`: (`options`: `MermaidConfig`) => `void` ; `parse`: (`text`: `string`, `parseOptions?`: [`ParseOptions`](../interfaces/mermaidAPI.ParseOptions.md)) => `Promise`<`boolean`> ; `render`: (`id`: `string`, `text`: `string`, `svgContainingElement?`: `Element`) => `Promise`<[`RenderResult`](../interfaces/mermaidAPI.RenderResult.md)> ; `reset`: () => `void` ; `setConfig`: (`conf`: `MermaidConfig`) => `MermaidConfig` = configApi.setConfig; `updateSiteConfig`: (`conf`: `MermaidConfig`) => `MermaidConfig` = configApi.updateSiteConfig }>
`Const` **mermaidAPI**: `Readonly`<{ `defaultConfig`: `MermaidConfig` = configApi.defaultConfig; `getConfig`: () => `MermaidConfig` = configApi.getConfig; `getDiagramFromText`: (`text`: `string`, `metadata`: `Pick`<`DiagramMetadata`, `"title"`>) => `Promise`<`Diagram`> ; `getSiteConfig`: () => `MermaidConfig` = configApi.getSiteConfig; `globalReset`: () => `void` ; `initialize`: (`options`: `MermaidConfig`) => `void` ; `parse`: (`text`: `string`, `parseOptions?`: [`ParseOptions`](../interfaces/mermaidAPI.ParseOptions.md)) => `Promise`<[`ParseResult`](mermaidAPI.md#parseresult)> ; `render`: (`id`: `string`, `text`: `string`, `svgContainingElement?`: `Element`) => `Promise`<[`RenderResult`](../interfaces/mermaidAPI.RenderResult.md)> ; `reset`: () => `void` ; `setConfig`: (`conf`: `MermaidConfig`) => `MermaidConfig` = configApi.setConfig; `updateSiteConfig`: (`conf`: `MermaidConfig`) => `MermaidConfig` = configApi.updateSiteConfig }>

## mermaidAPI configuration defaults

Expand Down Expand Up @@ -96,7 +106,7 @@ mermaid.initialize(config);

#### Defined in

[mermaidAPI.ts:608](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L608)
[mermaidAPI.ts:621](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L621)

## Functions

Expand Down Expand Up @@ -127,7 +137,7 @@ Return the last node appended

#### Defined in

[mermaidAPI.ts:263](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L263)
[mermaidAPI.ts:275](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L275)

---

Expand All @@ -153,7 +163,7 @@ the cleaned up svgCode

#### Defined in

[mermaidAPI.ts:209](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L209)
[mermaidAPI.ts:221](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L221)

---

Expand All @@ -178,7 +188,7 @@ the string with all the user styles

#### Defined in

[mermaidAPI.ts:139](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L139)
[mermaidAPI.ts:151](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L151)

---

Expand All @@ -201,7 +211,7 @@ the string with all the user styles

#### Defined in

[mermaidAPI.ts:186](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L186)
[mermaidAPI.ts:198](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L198)

---

Expand All @@ -228,7 +238,7 @@ with an enclosing block that has each of the cssClasses followed by !important;

#### Defined in

[mermaidAPI.ts:124](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L124)
[mermaidAPI.ts:136](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L136)

---

Expand All @@ -254,7 +264,7 @@ Put the svgCode into an iFrame. Return the iFrame code

#### Defined in

[mermaidAPI.ts:240](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L240)
[mermaidAPI.ts:252](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L252)

---

Expand All @@ -279,4 +289,4 @@ Remove any existing elements from the given document

#### Defined in

[mermaidAPI.ts:313](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L313)
[mermaidAPI.ts:325](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaidAPI.ts#L325)
7 changes: 4 additions & 3 deletions packages/mermaid/src/mermaid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { dedent } from 'ts-dedent';
import type { MermaidConfig } from './config.type.js';
import { log } from './logger.js';
import utils from './utils.js';
import type { ParseOptions, RenderResult } from './mermaidAPI.js';
import type { ParseOptions, ParseResult, RenderResult } from './mermaidAPI.js';
import { mermaidAPI } from './mermaidAPI.js';
import { registerLazyLoadedDiagrams, detectType } from './diagram-api/detectType.js';
import { loadRegisteredDiagrams } from './diagram-api/loadDiagram.js';
Expand All @@ -24,6 +24,7 @@ export type {
ParseErrorFunction,
RenderResult,
ParseOptions,
ParseResult,
UnknownDiagramError,
};

Expand Down Expand Up @@ -314,10 +315,10 @@ const executeQueue = async () => {
* Parse the text and validate the syntax.
* @param text - The mermaid diagram definition.
* @param parseOptions - Options for parsing.
* @returns true if the diagram is valid, false otherwise if parseOptions.suppressErrors is true.
* @returns - If the diagram is valid, returns an object with isValid set to true and the diagramType set to type of the diagram.
* @throws Error if the diagram is invalid and parseOptions.suppressErrors is false.
*/
const parse = async (text: string, parseOptions?: ParseOptions): Promise<boolean | void> => {
const parse = async (text: string, parseOptions?: ParseOptions): Promise<ParseResult | void> => {
return new Promise((resolve, reject) => {
// This promise will resolve when the render call is done.
// It will be queued first and will be executed when it is first in line
Expand Down
24 changes: 17 additions & 7 deletions packages/mermaid/src/mermaidAPI.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'use strict';
import { vi } from 'vitest';
import { vi, it, expect, describe, beforeEach } from 'vitest';

// -------------------------------------
// Mocks and mocking
Expand Down Expand Up @@ -682,17 +682,26 @@ describe('mermaidAPI', () => {
it('returns false for invalid definition with silent option', async () => {
await expect(
mermaidAPI.parse('this is not a mermaid diagram definition', { suppressErrors: true })
).resolves.toBe(false);
).resolves.toStrictEqual({ isValid: false });
});
it('resolves for valid definition', async () => {
await expect(
mermaidAPI.parse('graph TD;A--x|text including URL space|B;')
).resolves.toBeTruthy();
await expect(mermaidAPI.parse('graph TD;A--x|text including URL space|B;')).resolves
.toMatchInlineSnapshot(`
{
"diagramType": "flowchart-v2",
"isValid": true,
}
`);
});
it('returns true for valid definition with silent option', async () => {
await expect(
mermaidAPI.parse('graph TD;A--x|text including URL space|B;', { suppressErrors: true })
).resolves.toBe(true);
).resolves.toMatchInlineSnapshot(`
{
"diagramType": "flowchart-v2",
"isValid": true,
}
`);
});
});

Expand Down Expand Up @@ -734,7 +743,8 @@ describe('mermaidAPI', () => {
it('should set aria-roledscription to the diagram type AND should call addSVGa11yTitleDescription', async () => {
const a11yDiagramInfo_spy = vi.spyOn(accessibility, 'setA11yDiagramInfo');
const a11yTitleDesc_spy = vi.spyOn(accessibility, 'addSVGa11yTitleDescription');
await mermaidAPI.render(id, diagramText);
const result = await mermaidAPI.render(id, diagramText);
expect(result.diagramType).toBe(expectedDiagramType);
expect(a11yDiagramInfo_spy).toHaveBeenCalledWith(
expect.anything(),
expectedDiagramType
Expand Down
33 changes: 23 additions & 10 deletions packages/mermaid/src/mermaidAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,18 @@ export interface ParseOptions {
suppressErrors?: boolean;
}

export type ParseResult =
| {
isValid: true;
/**
* The diagram type, e.g. 'flowchart', 'sequence', etc.
*/
diagramType: string;
}
| {
isValid: false;
};

// This makes it clear that we're working with a d3 selected element of some kind, even though it's hard to specify the exact type.
export type D3Element = any;

Expand All @@ -68,6 +80,10 @@ export interface RenderResult {
* The svg code for the rendered graph.
*/
svg: string;
/**
* The diagram type, e.g. 'flowchart', 'sequence', etc.
*/
diagramType: string;
/**
* Bind function to be called after the svg has been inserted into the DOM.
* This is necessary for adding event listeners to the elements in the svg.
Expand All @@ -91,28 +107,24 @@ function processAndSetConfigs(text: string) {
* Parse the text and validate the syntax.
* @param text - The mermaid diagram definition.
* @param parseOptions - Options for parsing.
* @returns true if the diagram is valid, false otherwise if parseOptions.suppressErrors is true.
* @returns - If the diagram is valid, returns an object with isValid set to true and the diagramType set to type of the diagram.
* @throws Error if the diagram is invalid and parseOptions.suppressErrors is false.
*/

async function parse(text: string, parseOptions?: ParseOptions): Promise<boolean> {
async function parse(text: string, parseOptions?: ParseOptions): Promise<ParseResult> {
addDiagrams();

text = processAndSetConfigs(text).code;

try {
await getDiagramFromText(text);
const { code } = processAndSetConfigs(text);
const diagram = await getDiagramFromText(code);
return { isValid: true, diagramType: diagram.type };
} catch (error) {
if (parseOptions?.suppressErrors) {
return false;
return { isValid: false };
}
throw error;
}
return true;
}

// append !important; to each cssClass followed by a final !important, all enclosed in { }
//
/**
* Create a CSS style that starts with the given class name, then the element,
* with an enclosing block that has each of the cssClasses followed by !important;
Expand Down Expand Up @@ -483,6 +495,7 @@ const render = async function (
}

return {
diagramType,
svg: svgCode,
bindFunctions: diag.db.bindFunctions,
};
Expand Down

0 comments on commit c3c7ccd

Please sign in to comment.