How the Parser works under the hood ?
This is the entry point of the library.
parseMermaidToExcalidraw
function is the only function exposed which receives mermaid syntax as the input, parses the mermaid syntax and resolves to Excalidraw Skeleton.
Lets look at the high level overview at how the parse works 👇
Lets dive deeper into individual section now to understand better.
Parsing Mermaid diagram
One of the dependencies of the library is mermaid
library.
We need the mermaid diagram in some extractable format so we can parse it to Excalidraw Elements.
Parsing is broken into two steps
Rendering Mermaid to Svg
- This helps in determining the position and dimensions of each element in the diagramParsing the mermaid syntax
- We also need to know how elements are connected which isn't possible with svg alone hence we also parse the mermaid syntax which helps in determining the connections and bindings between elements in the diagram.
Rendering Mermaid to Svg
The mermaid
library provides the API mermaid.render
API which gives the output of the diagram in svg
.
If the diagram isn't supported, this svg is converted to dataURL
and can be rendered as an image in Excalidraw.
Parsing the mermaid syntax
For this we first need to process the options along with mermaid defination for diagram provided by the user.
processMermaidTextWithOptions
takes the mermaid defination and options and returns the full defination including the mermaid directives .
Next we use mermaid api getDiagramFromText to parse the full defination and get the Diagram json from it.
const diagram = await mermaid.mermaidAPI.getDiagramFromText(fullDefinition);
Next we write our own parser to parse this diagram.
Parsing the Diagram
For each diagram type, we need a parser as the result of every diagram would differ and dependinng on the data we have to write the parser. Since currently we support flowchart, so here is the parseMermaidFlowChartDiagram
to parse the flowchart diagram.
If you want to understand how flowchart parser works, you can navigate to Flowchart Parser.
Converting to ExcalidrawElementSkeleton
Now we have all the data, we just need to transform it to ExcalidrawElementSkeleton API so it can be rendered in Excalidraw.
For this we have converters
which takes the parsed mermaid data and gives back the Excalidraw Skeleton.
For Unsupported types, we have already mentioned above that we convert it to dataURL
and return the ExcalidrawImageSkeleton.
For supported types, currently only flowchart, we have flowchartConverter which parses the data and converts to ExcalidrawElementSkeleton.