diff --git a/.changeset/eight-apricots-arrive.md b/.changeset/eight-apricots-arrive.md new file mode 100644 index 0000000000..551d798374 --- /dev/null +++ b/.changeset/eight-apricots-arrive.md @@ -0,0 +1,5 @@ +--- +'mermaid': minor +--- + +feat: Add support for iconify icons diff --git a/.changeset/yellow-maps-poke.md b/.changeset/yellow-maps-poke.md new file mode 100644 index 0000000000..4e6d6bd235 --- /dev/null +++ b/.changeset/yellow-maps-poke.md @@ -0,0 +1,5 @@ +--- +'@mermaid-js/parser': patch +--- + +feat: Support - in architecture icons diff --git a/.cspell/libraries.txt b/.cspell/libraries.txt index ad0e3e7011..73a2dceeb2 100644 --- a/.cspell/libraries.txt +++ b/.cspell/libraries.txt @@ -30,6 +30,7 @@ Foswiki Gitea graphlib Grav +icones iconify Inkdrop jiti diff --git a/cypress/helpers/util.ts b/cypress/helpers/util.ts index 133a350328..74b17cf055 100644 --- a/cypress/helpers/util.ts +++ b/cypress/helpers/util.ts @@ -73,7 +73,7 @@ export const imgSnapshotTest = ( export const urlSnapshotTest = ( url: string, - options: CypressMermaidConfig, + options: CypressMermaidConfig = {}, _api = false, validation?: any ): void => { diff --git a/cypress/integration/rendering/architecture.spec.ts b/cypress/integration/rendering/architecture.spec.ts index 9eefbe1e42..1deb1f7da1 100644 --- a/cypress/integration/rendering/architecture.spec.ts +++ b/cypress/integration/rendering/architecture.spec.ts @@ -1,4 +1,4 @@ -import { imgSnapshotTest } from '../../helpers/util.ts'; +import { imgSnapshotTest, urlSnapshotTest } from '../../helpers/util.ts'; describe.skip('architecture diagram', () => { it('should render a simple architecture diagram with groups', () => { @@ -172,3 +172,9 @@ describe.skip('architecture diagram', () => { ); }); }); + +describe('architecture - external', () => { + it('should allow adding external icons', () => { + urlSnapshotTest('http://localhost:9000/architecture-external.html'); + }); +}); diff --git a/cypress/platform/architecture-external.html b/cypress/platform/architecture-external.html new file mode 100644 index 0000000000..71770425d6 --- /dev/null +++ b/cypress/platform/architecture-external.html @@ -0,0 +1,52 @@ + + + + + + Architecture Mermaid Test Page + + + + + +

External Icons Demo

+
+    architecture-beta
+      service s3(logos:aws-s3)[Cloud Store]
+      service ec2(logos:aws-ec2)[Server]
+      service api(logos:aws-api-gateway)[Api Gateway]
+      service fa(fa:image)[Font Awesome Icon]
+    
+ + + + diff --git a/demos/architecture.html b/demos/architecture.html index 137b3fbf01..6d978d9525 100644 --- a/demos/architecture.html +++ b/demos/architecture.html @@ -226,27 +226,31 @@

Junction Demo Groups


- + service s3(logos:aws-s3)[Cloud Store] + service ec2(logos:aws-ec2)[Server] + service api(logos:aws-api-gateway)[Api Gateway] + service fa(fa:image)[Font Awesome Icon] + diff --git a/docs/config/setup/interfaces/mermaid.Mermaid.md b/docs/config/setup/interfaces/mermaid.Mermaid.md index 09fab149cd..f4e9eb4ec3 100644 --- a/docs/config/setup/interfaces/mermaid.Mermaid.md +++ b/docs/config/setup/interfaces/mermaid.Mermaid.md @@ -28,7 +28,7 @@ page. #### Defined in -[packages/mermaid/src/mermaid.ts:435](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L435) +[packages/mermaid/src/mermaid.ts:436](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L436) --- @@ -59,7 +59,7 @@ A graph definition key #### Defined in -[packages/mermaid/src/mermaid.ts:437](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L437) +[packages/mermaid/src/mermaid.ts:438](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L438) --- @@ -89,7 +89,7 @@ Use [initialize](mermaid.Mermaid.md#initialize) and [run](mermaid.Mermaid.md#run #### Defined in -[packages/mermaid/src/mermaid.ts:430](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L430) +[packages/mermaid/src/mermaid.ts:431](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L431) --- @@ -116,7 +116,7 @@ This function should be called before the run function. #### Defined in -[packages/mermaid/src/mermaid.ts:434](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L434) +[packages/mermaid/src/mermaid.ts:435](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L435) --- @@ -130,7 +130,7 @@ Use [parse](mermaid.Mermaid.md#parse) and [render](mermaid.Mermaid.md#render) in #### Defined in -[packages/mermaid/src/mermaid.ts:424](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L424) +[packages/mermaid/src/mermaid.ts:425](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L425) --- @@ -180,7 +180,7 @@ Error if the diagram is invalid and parseOptions.suppressErrors is false or not #### Defined in -[packages/mermaid/src/mermaid.ts:425](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L425) +[packages/mermaid/src/mermaid.ts:426](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L426) --- @@ -190,7 +190,7 @@ Error if the diagram is invalid and parseOptions.suppressErrors is false or not #### Defined in -[packages/mermaid/src/mermaid.ts:419](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L419) +[packages/mermaid/src/mermaid.ts:420](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L420) --- @@ -218,7 +218,31 @@ Used to register external diagram types. #### Defined in -[packages/mermaid/src/mermaid.ts:433](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L433) +[packages/mermaid/src/mermaid.ts:434](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L434) + +--- + +### registerIconPacks + +• **registerIconPacks**: (`iconLoaders`: `IconLoader`\[]) => `void` + +#### Type declaration + +▸ (`iconLoaders`): `void` + +##### Parameters + +| Name | Type | +| :------------ | :-------------- | +| `iconLoaders` | `IconLoader`\[] | + +##### Returns + +`void` + +#### Defined in + +[packages/mermaid/src/mermaid.ts:439](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L439) --- @@ -242,7 +266,7 @@ Used to register external diagram types. #### Defined in -[packages/mermaid/src/mermaid.ts:432](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L432) +[packages/mermaid/src/mermaid.ts:433](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L433) --- @@ -268,7 +292,7 @@ Used to register external diagram types. #### Defined in -[packages/mermaid/src/mermaid.ts:426](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L426) +[packages/mermaid/src/mermaid.ts:427](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L427) --- @@ -316,7 +340,7 @@ Renders the mermaid diagrams #### Defined in -[packages/mermaid/src/mermaid.ts:431](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L431) +[packages/mermaid/src/mermaid.ts:432](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L432) --- @@ -351,7 +375,7 @@ to it (eg. dart interop wrapper). (Initially there is no parseError member of me #### Defined in -[packages/mermaid/src/mermaid.ts:436](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L436) +[packages/mermaid/src/mermaid.ts:437](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L437) --- @@ -361,4 +385,4 @@ to it (eg. dart interop wrapper). (Initially there is no parseError member of me #### Defined in -[packages/mermaid/src/mermaid.ts:418](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L418) +[packages/mermaid/src/mermaid.ts:419](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L419) diff --git a/docs/config/setup/interfaces/mermaid.RunOptions.md b/docs/config/setup/interfaces/mermaid.RunOptions.md index aae004d6d5..0bcfc2356e 100644 --- a/docs/config/setup/interfaces/mermaid.RunOptions.md +++ b/docs/config/setup/interfaces/mermaid.RunOptions.md @@ -18,7 +18,7 @@ The nodes to render. If this is set, `querySelector` will be ignored. #### Defined in -[packages/mermaid/src/mermaid.ts:48](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L48) +[packages/mermaid/src/mermaid.ts:49](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L49) --- @@ -44,7 +44,7 @@ A callback to call after each diagram is rendered. #### Defined in -[packages/mermaid/src/mermaid.ts:52](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L52) +[packages/mermaid/src/mermaid.ts:53](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L53) --- @@ -56,7 +56,7 @@ The query selector to use when finding elements to render. Default: `".mermaid"` #### Defined in -[packages/mermaid/src/mermaid.ts:44](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L44) +[packages/mermaid/src/mermaid.ts:45](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L45) --- @@ -68,4 +68,4 @@ If `true`, errors will be logged to the console, but not thrown. Default: `false #### Defined in -[packages/mermaid/src/mermaid.ts:56](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L56) +[packages/mermaid/src/mermaid.ts:57](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L57) diff --git a/docs/config/setup/modules/mermaid.md b/docs/config/setup/modules/mermaid.md index bdaeb05e1e..60c219f2d2 100644 --- a/docs/config/setup/modules/mermaid.md +++ b/docs/config/setup/modules/mermaid.md @@ -87,4 +87,4 @@ #### Defined in -[packages/mermaid/src/mermaid.ts:440](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L440) +[packages/mermaid/src/mermaid.ts:442](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L442) diff --git a/docs/syntax/architecture.md b/docs/syntax/architecture.md index 2d71d84fba..10d6b9aba7 100644 --- a/docs/syntax/architecture.md +++ b/docs/syntax/architecture.md @@ -191,4 +191,85 @@ architecture-beta bottom_gateway:T -- B:junctionRight ``` -## Configuration +## Icons + +By default, architecture diagram supports the following icons: `cloud`, `database`, `disk`, `internet`, `server`. +Users can use any of the 200,000+ icons available in iconify.design, or add their own custom icons, by following the steps below. + +The icon packs available can be found at [icones.js.org](https://icones.js.org/). +We use the name defined when registering the icon pack, to override the prefix field of the iconify pack. This allows the user to use shorter names for the icons. It also allows us to load a particular pack only when it is used in a diagram. + +Using JSON file directly from CDN: + +```js +import mermaid from 'CDN/mermaid.esm.mjs'; +mermaid.registerIconPacks([ + { + name: 'logos', + loader: () => + fetch('https://unpkg.com/@iconify-json/logos/icons.json').then((res) => res.json()), + }, +]); +``` + +Using packages and a bundler: + +```bash +npm install @iconify-json/logos +``` + +With lazy loading + +```js +import mermaid from 'mermaid'; + +mermaid.registerIconPacks([ + { + name: 'logos', + loader: () => import('@iconify-json/logos').then((module) => module.icons), + }, +]); +``` + +Without lazy loading + +```js +import mermaid from 'mermaid'; +import { icons } from '@iconify-json/logos'; +mermaid.registerIconPacks([ + { + name: icons.prefix, // To use the prefix defined in the icon pack + icons, + }, +]); +``` + +After the icons are installed, they can be used in the architecture diagram by using the format "name:icon-name", where name is the value used when registering the icon pack. + +```mermaid-example +architecture-beta + group api(logos:aws-lambda)[API] + + service db(logos:aws-aurora)[Database] in api + service disk1(logos:aws-glacier)[Storage] in api + service disk2(logos:aws-s3)[Storage] in api + service server(logos:aws-ec2)[Server] in api + + db:L -- R:server + disk1:T -- B:server + disk2:T -- B:db +``` + +```mermaid +architecture-beta + group api(logos:aws-lambda)[API] + + service db(logos:aws-aurora)[Database] in api + service disk1(logos:aws-glacier)[Storage] in api + service disk2(logos:aws-s3)[Storage] in api + service server(logos:aws-ec2)[Server] in api + + db:L -- R:server + disk1:T -- B:server + disk2:T -- B:db +``` diff --git a/packages/mermaid/package.json b/packages/mermaid/package.json index 3fee53a0da..198627560d 100644 --- a/packages/mermaid/package.json +++ b/packages/mermaid/package.json @@ -68,6 +68,7 @@ }, "dependencies": { "@braintree/sanitize-url": "^7.0.1", + "@iconify/utils": "^2.1.32", "@mermaid-js/parser": "workspace:^", "cytoscape": "^3.29.2", "cytoscape-cose-bilkent": "^4.1.0", @@ -88,8 +89,9 @@ }, "devDependencies": { "@adobe/jsonschema2md": "^8.0.0", - "@types/cytoscape-fcose": "^2.2.4", + "@iconify/types": "^2.0.0", "@types/cytoscape": "^3.21.4", + "@types/cytoscape-fcose": "^2.2.4", "@types/d3": "^7.4.3", "@types/d3-sankey": "^0.12.4", "@types/d3-scale": "^4.0.8", diff --git a/packages/mermaid/src/diagrams/architecture/architectureIcons.ts b/packages/mermaid/src/diagrams/architecture/architectureIcons.ts new file mode 100644 index 0000000000..dd6c99f9c9 --- /dev/null +++ b/packages/mermaid/src/diagrams/architecture/architectureIcons.ts @@ -0,0 +1,43 @@ +import { unknownIcon } from '$root/rendering-util/icons.js'; +import type { IconifyJSON } from '@iconify/types'; + +const wrapIcon = (icon: string) => { + return `${icon}`; +}; + +export const architectureIcons: IconifyJSON = { + prefix: 'mermaid-architecture', + height: 80, + width: 80, + icons: { + database: { + body: wrapIcon( + '' + ), + }, + server: { + body: wrapIcon( + '' + ), + }, + disk: { + body: wrapIcon( + '' + ), + }, + internet: { + body: wrapIcon( + '' + ), + }, + cloud: { + body: wrapIcon( + '' + ), + }, + unknown: unknownIcon, + blank: { + body: wrapIcon(''), + }, + }, +}; diff --git a/packages/mermaid/src/diagrams/architecture/architectureRenderer.ts b/packages/mermaid/src/diagrams/architecture/architectureRenderer.ts index 558b904835..3abb69b9f7 100644 --- a/packages/mermaid/src/diagrams/architecture/architectureRenderer.ts +++ b/packages/mermaid/src/diagrams/architecture/architectureRenderer.ts @@ -1,3 +1,4 @@ +import { registerIconPacks } from '$root/rendering-util/icons.js'; import type { Position } from 'cytoscape'; import cytoscape from 'cytoscape'; import type { FcoseLayoutOptions } from 'cytoscape-fcose'; @@ -9,6 +10,7 @@ import { log } from '../../logger.js'; import { selectSvgElement } from '../../rendering-util/selectSvgElement.js'; import { setupGraphViewbox } from '../../setupGraphViewbox.js'; import { getConfigField } from './architectureDb.js'; +import { architectureIcons } from './architectureIcons.js'; import type { ArchitectureDataStructures, ArchitectureJunction, @@ -30,11 +32,14 @@ import { isArchitectureDirectionY, nodeData, } from './architectureTypes.js'; -import { defaultIconLibrary } from './icons/default.js'; -import { registerIconLibrary } from './icons/svgRegister.js'; import { drawEdges, drawGroups, drawJunctions, drawServices } from './svgDraw.js'; -registerIconLibrary(defaultIconLibrary); +registerIconPacks([ + { + name: architectureIcons.prefix, + icons: architectureIcons, + }, +]); cytoscape.use(fcose); function addServices(services: ArchitectureService[], cy: cytoscape.Core) { diff --git a/packages/mermaid/src/diagrams/architecture/icons/default.ts b/packages/mermaid/src/diagrams/architecture/icons/default.ts deleted file mode 100644 index 8c33df09c6..0000000000 --- a/packages/mermaid/src/diagrams/architecture/icons/default.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { createIcon, type IconLibrary } from './svgRegister.js'; - -export const defaultIconLibrary: IconLibrary = { - database: createIcon( - ` - - - - - - - -`, - 80 - ), - server: createIcon( - ` - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -`, - 80 - ), - disk: createIcon( - ` - - - - - - - - - -`, - 80 - ), - internet: createIcon( - ` - - - - - - - - -`, - 80 - ), - cloud: createIcon( - ` - - - `, - 80 - ), - unknown: createIcon( - ` - - ? -`, - 80 - ), - blank: createIcon( - ` - -`, - 80 - ), -}; diff --git a/packages/mermaid/src/diagrams/architecture/icons/svgRegister.ts b/packages/mermaid/src/diagrams/architecture/icons/svgRegister.ts deleted file mode 100644 index 712644afa6..0000000000 --- a/packages/mermaid/src/diagrams/architecture/icons/svgRegister.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { log } from '$root/logger.js'; -import type { Selection } from 'd3-selection'; - -export type IconResolver = ( - parent: Selection, - width?: number -) => Selection; -export type IconLibrary = Record; - -/** - * Converts an SVG Icon passed as a string into a properly formatted IconResolver - * @param icon - html code for the svg icon as a string (the SVG tag should not be included) - * @param originalSize - the original size of the SVG Icon in pixels - * @returns IconResolver - */ -export const createIcon: (icon: string, originalSize: number) => IconResolver = ( - icon, - originalSize -) => { - return ( - parent: Selection, - size: number = originalSize - ) => { - parent.html(`${icon}`); - return parent; - }; -}; - -const icons: IconLibrary = {}; - -export const isIconNameInUse = (name: string): boolean => { - return icons[name] !== undefined; -}; - -export const registerIconLibrary = (library: IconLibrary) => { - Object.entries(library).forEach(([name, resolver]) => { - if (!isIconNameInUse(name)) { - icons[name] = resolver; - } else { - log.warn(`Icon with name ${name} already exists. Skipping registration.`); - } - }); -}; - -export const getIcon = (name: string): IconResolver | null => { - if (isIconNameInUse(name)) { - return icons[name]; - } - return icons.unknown; -}; diff --git a/packages/mermaid/src/diagrams/architecture/svgDraw.ts b/packages/mermaid/src/diagrams/architecture/svgDraw.ts index ef3ddb7f6c..3578393949 100644 --- a/packages/mermaid/src/diagrams/architecture/svgDraw.ts +++ b/packages/mermaid/src/diagrams/architecture/svgDraw.ts @@ -1,10 +1,10 @@ -// TODO remove no-console -/* eslint-disable no-console */ +import { getIconSVG } from '$root/rendering-util/icons.js'; import type cytoscape from 'cytoscape'; import { getConfig } from '../../diagram-api/diagramAPI.js'; import { createText } from '../../rendering-util/createText.js'; import type { D3Element } from '../../types.js'; import { db, getConfigField } from './architectureDb.js'; +import { architectureIcons } from './architectureIcons.js'; import { ArchitectureDirectionArrow, ArchitectureDirectionArrowShift, @@ -20,7 +20,6 @@ import { type ArchitectureJunction, type ArchitectureService, } from './architectureTypes.js'; -import { getIcon } from './icons/svgRegister.js'; export const drawEdges = async function (edgesEl: D3Element, cy: cytoscape.Core) { const padding = getConfigField('padding'); @@ -198,7 +197,6 @@ export const drawGroups = async function (groupsEl: D3Element, cy: cytoscape.Cor const data = nodeData(node); if (data.type === 'group') { const { h, w, x1, y1 } = node.boundingBox(); - console.log(`Draw group (${data.id}): pos=(${x1}, ${y1}), dim=(${w}, ${h})`); groupsEl .append('rect') @@ -213,7 +211,9 @@ export const drawGroups = async function (groupsEl: D3Element, cy: cytoscape.Cor let shiftedY1 = y1; if (data.icon) { const bkgElem = groupLabelContainer.append('g'); - getIcon(data.icon)?.(bkgElem, groupIconSize); + bkgElem.html( + `${await getIconSVG(data.icon, { height: groupIconSize, width: groupIconSize, fallbackPrefix: architectureIcons.prefix })}` + ); bkgElem.attr( 'transform', 'translate(' + @@ -290,15 +290,19 @@ export const drawServices = async function ( textElem.attr('transform', 'translate(' + iconSize / 2 + ', ' + iconSize + ')'); } - let bkgElem = serviceElem.append('g'); + const bkgElem = serviceElem.append('g'); if (service.icon) { // TODO: should a warning be given to end-users saying which icon names are available? // if (!isIconNameInUse(service.icon)) { // throw new Error(`Invalid SVG Icon name: "${service.icon}"`); // } - bkgElem = getIcon(service.icon)?.(bkgElem, iconSize); + bkgElem.html( + `${await getIconSVG(service.icon, { height: iconSize, width: iconSize, fallbackPrefix: architectureIcons.prefix })}` + ); } else if (service.iconText) { - bkgElem = getIcon('blank')?.(bkgElem, iconSize); + bkgElem.html( + `${await getIconSVG('blank', { height: iconSize, width: iconSize, fallbackPrefix: architectureIcons.prefix })}` + ); const textElemContainer = bkgElem.append('g'); const fo = textElemContainer .append('foreignObject') diff --git a/packages/mermaid/src/docs/.vitepress/theme/mermaid.ts b/packages/mermaid/src/docs/.vitepress/theme/mermaid.ts index 47e2386926..2357fe384b 100644 --- a/packages/mermaid/src/docs/.vitepress/theme/mermaid.ts +++ b/packages/mermaid/src/docs/.vitepress/theme/mermaid.ts @@ -2,6 +2,13 @@ import mermaid, { type MermaidConfig } from 'mermaid'; import zenuml from '../../../../../mermaid-zenuml/dist/mermaid-zenuml.core.mjs'; const init = mermaid.registerExternalDiagrams([zenuml]); +mermaid.registerIconPacks([ + { + name: 'logos', + loader: () => + fetch('https://unpkg.com/@iconify-json/logos/icons.json').then((res) => res.json()), + }, +]); export const render = async (id: string, code: string, config: MermaidConfig): Promise => { await init; diff --git a/packages/mermaid/src/docs/syntax/architecture.md b/packages/mermaid/src/docs/syntax/architecture.md index e74995ce33..0d199c8b15 100644 --- a/packages/mermaid/src/docs/syntax/architecture.md +++ b/packages/mermaid/src/docs/syntax/architecture.md @@ -153,4 +153,71 @@ architecture-beta bottom_gateway:T -- B:junctionRight ``` -## Configuration +## Icons + +By default, architecture diagram supports the following icons: `cloud`, `database`, `disk`, `internet`, `server`. +Users can use any of the 200,000+ icons available in iconify.design, or add their own custom icons, by following the steps below. + +The icon packs available can be found at [icones.js.org](https://icones.js.org/). +We use the name defined when registering the icon pack, to override the prefix field of the iconify pack. This allows the user to use shorter names for the icons. It also allows us to load a particular pack only when it is used in a diagram. + +Using JSON file directly from CDN: + +```js +import mermaid from 'CDN/mermaid.esm.mjs'; +mermaid.registerIconPacks([ + { + name: 'logos', + loader: () => + fetch('https://unpkg.com/@iconify-json/logos/icons.json').then((res) => res.json()), + }, +]); +``` + +Using packages and a bundler: + +```bash +npm install @iconify-json/logos +``` + +With lazy loading + +```js +import mermaid from 'mermaid'; + +mermaid.registerIconPacks([ + { + name: 'logos', + loader: () => import('@iconify-json/logos').then((module) => module.icons), + }, +]); +``` + +Without lazy loading + +```js +import mermaid from 'mermaid'; +import { icons } from '@iconify-json/logos'; +mermaid.registerIconPacks([ + { + name: icons.prefix, // To use the prefix defined in the icon pack + icons, + }, +]); +``` + +After the icons are installed, they can be used in the architecture diagram by using the format "name:icon-name", where name is the value used when registering the icon pack. + +```mermaid-example +architecture-beta + group api(logos:aws-lambda)[API] + + service db(logos:aws-aurora)[Database] in api + service disk1(logos:aws-glacier)[Storage] in api + service disk2(logos:aws-s3)[Storage] in api + service server(logos:aws-ec2)[Server] in api + + db:L -- R:server + disk1:T -- B:server + disk2:T -- B:db +``` diff --git a/packages/mermaid/src/mermaid.ts b/packages/mermaid/src/mermaid.ts index 43fc5bd31b..52cca1cfe4 100644 --- a/packages/mermaid/src/mermaid.ts +++ b/packages/mermaid/src/mermaid.ts @@ -2,6 +2,7 @@ * Web page integration module for the mermaid framework. It uses the mermaidAPI for mermaid * functionality and to render the diagrams to svg code! */ +import { registerIconPacks } from '$root/rendering-util/icons.js'; import { dedent } from 'ts-dedent'; import type { MermaidConfig } from './config.type.js'; import { detectType, registerLazyLoadedDiagrams } from './diagram-api/detectType.js'; @@ -435,6 +436,7 @@ export interface Mermaid { contentLoaded: typeof contentLoaded; setParseErrorHandler: typeof setParseErrorHandler; detectType: typeof detectType; + registerIconPacks: typeof registerIconPacks; } const mermaid: Mermaid = { @@ -451,6 +453,7 @@ const mermaid: Mermaid = { contentLoaded, setParseErrorHandler, detectType, + registerIconPacks, }; export default mermaid; diff --git a/packages/mermaid/src/rendering-util/icons.ts b/packages/mermaid/src/rendering-util/icons.ts new file mode 100644 index 0000000000..27709b8229 --- /dev/null +++ b/packages/mermaid/src/rendering-util/icons.ts @@ -0,0 +1,100 @@ +import { log } from '$root/logger.js'; +import type { ExtendedIconifyIcon, IconifyIcon, IconifyJSON } from '@iconify/types'; +import type { IconifyIconCustomisations } from '@iconify/utils'; +import { getIconData, iconToHTML, iconToSVG, replaceIDs, stringToIcon } from '@iconify/utils'; + +interface AsyncIconLoader { + name: string; + loader: () => Promise; +} + +interface SyncIconLoader { + name: string; + icons: IconifyJSON; +} + +export type IconLoader = AsyncIconLoader | SyncIconLoader; + +export const unknownIcon: IconifyIcon = { + body: '?', + height: 80, + width: 80, +}; + +const iconsStore = new Map(); +const loaderStore = new Map(); + +export const registerIconPacks = (iconLoaders: IconLoader[]) => { + for (const iconLoader of iconLoaders) { + if (!iconLoader.name) { + throw new Error( + 'Invalid icon loader. Must have a "name" property with non-empty string value.' + ); + } + log.debug('Registering icon pack:', iconLoader.name); + if ('loader' in iconLoader) { + loaderStore.set(iconLoader.name, iconLoader.loader); + } else if ('icons' in iconLoader) { + iconsStore.set(iconLoader.name, iconLoader.icons); + } else { + log.error('Invalid icon loader:', iconLoader); + throw new Error('Invalid icon loader. Must have either "icons" or "loader" property.'); + } + } +}; + +const getRegisteredIconData = async (iconName: string, fallbackPrefix?: string) => { + const data = stringToIcon(iconName, true, fallbackPrefix !== undefined); + if (!data) { + throw new Error(`Invalid icon name: ${iconName}`); + } + const prefix = data.prefix || fallbackPrefix; + if (!prefix) { + throw new Error(`Icon name must contain a prefix: ${iconName}`); + } + let icons = iconsStore.get(prefix); + if (!icons) { + const loader = loaderStore.get(prefix); + if (!loader) { + throw new Error(`Icon set not found: ${data.prefix}`); + } + try { + const loaded = await loader(); + icons = { ...loaded, prefix }; + iconsStore.set(prefix, icons); + } catch (e) { + log.error(e); + throw new Error(`Failed to load icon set: ${data.prefix}`); + } + } + const iconData = getIconData(icons, data.name); + if (!iconData) { + throw new Error(`Icon not found: ${iconName}`); + } + return iconData; +}; + +export const isIconAvailable = async (iconName: string) => { + try { + await getRegisteredIconData(iconName); + return true; + } catch { + return false; + } +}; + +export const getIconSVG = async ( + iconName: string, + customisations?: IconifyIconCustomisations & { fallbackPrefix?: string } +) => { + let iconData: ExtendedIconifyIcon; + try { + iconData = await getRegisteredIconData(iconName, customisations?.fallbackPrefix); + } catch (e) { + log.error(e); + iconData = unknownIcon; + } + const renderData = iconToSVG(iconData, customisations); + const svg = iconToHTML(replaceIDs(renderData.body), renderData.attributes); + return svg; +}; diff --git a/packages/parser/src/language/architecture/architecture.langium b/packages/parser/src/language/architecture/architecture.langium index 6246b423ed..11af262432 100644 --- a/packages/parser/src/language/architecture/architecture.langium +++ b/packages/parser/src/language/architecture/architecture.langium @@ -49,7 +49,7 @@ Edge: terminal ARROW_DIRECTION: 'L' | 'R' | 'T' | 'B'; terminal ARCH_ID: /[\w]+/; terminal ARCH_TEXT_ICON: /\("[^"]+"\)/; -terminal ARCH_ICON: /\([\w:]+\)/; +terminal ARCH_ICON: /\([\w-:]+\)/; terminal ARCH_TITLE: /\[[\w ]+\]/; terminal ARROW_GROUP: /\{group\}/; -terminal ARROW_INTO: /<|>/; \ No newline at end of file +terminal ARROW_INTO: /<|>/; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fff57c2ccf..7fcdbb5f3f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -209,6 +209,9 @@ importers: '@braintree/sanitize-url': specifier: ^7.0.1 version: 7.1.0 + '@iconify/utils': + specifier: ^2.1.32 + version: 2.1.32 '@mermaid-js/parser': specifier: workspace:^ version: link:../parser @@ -264,6 +267,9 @@ importers: '@adobe/jsonschema2md': specifier: ^8.0.0 version: 8.0.2 + '@iconify/types': + specifier: ^2.0.0 + version: 2.0.0 '@types/cytoscape': specifier: ^3.21.4 version: 3.21.5 @@ -670,6 +676,9 @@ packages: '@antfu/install-pkg@0.1.1': resolution: {integrity: sha512-LyB/8+bSfa0DFGC06zpCEfs89/XoWZwws5ygEa5D+Xsm3OfI+aXQ86VgVG7Acyef+rSZ5HE7J8rrxzrQeM3PjQ==} + '@antfu/install-pkg@0.4.1': + resolution: {integrity: sha512-T7yB5QNG29afhWVkVq7XeIMBa5U/vs9mX69YqayXypPRmYzUmzwnYltplHmPtZ4HPCn+sQKeXW8I47wCbuBOjw==} + '@antfu/utils@0.7.10': resolution: {integrity: sha512-+562v9k4aI80m1+VuMHehNJWLOFjBnXn3tdOitzD0il5b7smkSBal4+a3oKiQTbrwMmN/TBUMDvbdoWDehgOww==} @@ -2233,6 +2242,9 @@ packages: '@iconify/utils@2.1.30': resolution: {integrity: sha512-bY0IO5xLOlbzJBnjWLxknp6Sss3yla03sVY9VeUz9nT6dbc+EGKlLfCt+6uytJnWm5CUvTF/BNotsLWF7kI61A==} + '@iconify/utils@2.1.32': + resolution: {integrity: sha512-LeifFZPPKu28O3AEDpYJNdEbvS4/ojAPyIW+pF/vUpJTYnbTiXUHkCh0bwgFRzKvdpb8H4Fbfd/742++MF4fPQ==} + '@img/sharp-darwin-arm64@0.33.5': resolution: {integrity: sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} @@ -7205,6 +7217,9 @@ packages: package-json-from-dist@1.0.0: resolution: {integrity: sha512-dATvCeZN/8wQsGywez1mzHtTlP22H8OEfPrVMLNr4/eGa+ijtLn/6M5f0dY8UKNrC2O9UCU6SSoG3qRKnt7STw==} + package-manager-detector@0.2.0: + resolution: {integrity: sha512-E385OSk9qDcXhcM9LNSe4sdhx8a9mAPrZ4sMLW+tmxl5ZuGtPUcdFu+MPP2jbgiWAZ6Pfe5soGFMd+0Db5Vrog==} + pako@1.0.11: resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==} @@ -8336,6 +8351,9 @@ packages: tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + tinyexec@0.3.0: + resolution: {integrity: sha512-tVGE0mVJPGb0chKhqmsoosjsS+qUnJVGJpZgsHYQcGoPlG3B51R3PouqTgEGH2Dc9jjFyOqOpix6ZHNMXp1FZg==} + tinypool@0.8.4: resolution: {integrity: sha512-i11VH5gS6IFeLY3gMBQ00/MmLncVP7JLXOw1vlgkytLmJK7QnEr7NXf0LBdxfmNPAeyetukOk0bOYrJrFGjYJQ==} engines: {node: '>=14.0.0'} @@ -9334,6 +9352,11 @@ snapshots: execa: 5.1.1 find-up: 5.0.0 + '@antfu/install-pkg@0.4.1': + dependencies: + package-manager-detector: 0.2.0 + tinyexec: 0.3.0 + '@antfu/utils@0.7.10': {} '@apideck/better-ajv-errors@0.3.6(ajv@8.17.1)': @@ -11302,6 +11325,18 @@ snapshots: transitivePeerDependencies: - supports-color + '@iconify/utils@2.1.32': + dependencies: + '@antfu/install-pkg': 0.4.1 + '@antfu/utils': 0.7.10 + '@iconify/types': 2.0.0 + debug: 4.3.6(supports-color@8.1.1) + kolorist: 1.8.0 + local-pkg: 0.5.0 + mlly: 1.7.1 + transitivePeerDependencies: + - supports-color + '@img/sharp-darwin-arm64@0.33.5': optionalDependencies: '@img/sharp-libvips-darwin-arm64': 1.0.4 @@ -17387,6 +17422,8 @@ snapshots: package-json-from-dist@1.0.0: {} + package-manager-detector@0.2.0: {} + pako@1.0.11: {} parent-module@1.0.1: @@ -18651,6 +18688,8 @@ snapshots: tinybench@2.9.0: {} + tinyexec@0.3.0: {} + tinypool@0.8.4: {} tinyspy@2.2.1: {}