| 1 | # @mermaid-js/examples |
| 2 | |
| 3 | The `@mermaid-js/examples` package contains a collection of examples used by tools like [mermaid.live](https://mermaid.live) to help users get started with new diagrams. |
| 4 | |
| 5 | You can duplicate an existing diagram example file, e.g., `packages/examples/src/examples/flowchart.ts`, and modify it with details specific to your diagram. |
| 6 | |
| 7 | Then, import the example in the `packages/examples/src/index.ts` file and add it to the `examples` array. |
| 8 | |
| 9 | Each diagram should have at least one example, which should be marked as the default. It's a good idea to add more examples to showcase different features of the diagram. |
| 10 | |
| 11 | ## Usage |
| 12 | |
| 13 | ```bash |
| 14 | pnpm add @mermaid-js/examples |
| 15 | ``` |
| 16 | |
| 17 | A sample usage of the package in mermaid.live, to get the default example for every diagram type: |
| 18 | |
| 19 | ```ts |
| 20 | import { diagramData } from '@mermaid-js/examples'; |
| 21 | |
| 22 | type DiagramDefinition = (typeof diagramData)[number]; |
| 23 | |
| 24 | const isValidDiagram = (diagram: DiagramDefinition): diagram is Required<DiagramDefinition> => { |
| 25 | return Boolean(diagram.name && diagram.examples && diagram.examples.length > 0); |
| 26 | }; |
| 27 | |
| 28 | export const getSampleDiagrams = () => { |
| 29 | const diagrams = diagramData |
| 30 | .filter((d) => isValidDiagram(d)) |
| 31 | .map(({ examples, ...rest }) => ({ |
| 32 | ...rest, |
| 33 | example: examples?.filter(({ isDefault }) => isDefault)[0], |
| 34 | })); |
| 35 | const examples: Record<string, string> = {}; |
| 36 | for (const diagram of diagrams) { |
| 37 | examples[diagram.name.replace(/ (Diagram|Chart|Graph)/, '')] = diagram.example.code; |
| 38 | } |
| 39 | return examples; |
| 40 | }; |
| 41 | ``` |
| 42 | |