Compare commits

..
Author SHA1 Message Date
Sidharth Vinod d1fd4dc244 feat: More edit modes in CTA 2026-04-02 17:33:52 +05:30
Sidharth Vinod 9436f8ddda chore: Remove canonical 2026-04-01 22:43:58 +05:30
Sidharth Vinod 62699769d5 fix: Use {} instead of undefined 2026-04-01 22:19:02 +05:30
Sidharth Vinod 5608dc5661 feat: Add visual editor button 2026-04-01 21:50:18 +05:30
Sidharth VinodandGitHub 29e92a9702 Merge pull request #1917 from mermaid-js/sidv/fixBasePath
fix(#1914): Resolve base path
2026-04-01 15:13:59 +00:00
Sidharth Vinod 0e0da3b1e9 chore: Reduce Error debounce interval 2026-04-01 20:43:15 +05:30
Sidharth Vinod d273e1d722 fix: Asset links 2026-03-30 21:30:13 +05:30
Sidharth Vinod c799dff042 fix(#1914): Resolve redirectURL considering base path 2026-03-30 21:24:33 +05:30
Sidharth Vinod c675dc02e9 fix: Avoid double popups 2026-03-25 17:03:04 +09:00
Sidharth Vinod ab760f35fa feat: Retain search query in URL to get insights into traffic flow 2026-03-18 22:05:07 +09:00
Sidharth VinodandGitHub 8a436791de Merge pull request #1908 from mermaid-js/renovate/mermaid-packages
fix(deps): update dependency mermaid to ^11.13.0
2026-03-16 07:41:08 -07:00
Sidharth VinodandGitHub d16a1776e6 Merge pull request #1909 from mermaid-js/sidv/correctPrivacyPolicy
feat: Configure Privacy Policy
2026-03-16 07:40:41 -07:00
Sidharth Vinod ab720e0267 fix: local test change 2026-03-16 23:33:20 +09:00
Sidharth Vinod d7db71e38a chore: Add new mermaid home button 2026-03-16 23:29:49 +09:00
Sidharth Vinod b466e8430e feat: Show mermaid.live privacy policy only on mermaid.live
As the OSS project only controls the mermaid.live domain, we're adding an env variable to let anyone who is self hosting live editor to set their own privacy policy, or to hide the button if they want to.
2026-03-16 23:29:13 +09:00
renovate[bot]andGitHub ea404df79b fix(deps): update dependency mermaid to ^11.13.0 2026-03-16 01:36:21 +00:00
Sidharth Vinod 15cdb7b64a chore: Show editor picker once to existing users as well 2026-03-12 13:35:42 +09:00
Sidharth Vinod 340911f271 chore: Remove panZoom event 2026-03-05 23:28:34 +05:30
Sidharth VinodandGitHub 44d15c0f5e Merge pull request #1901 from mermaid-js/claude/hide-editor-picker-mobile-2h7p0
Hide editor picker on mobile
2026-03-03 14:09:58 -08:00
Claude c36e51fb9f Hide editor picker dialog on mobile in shouldShowEditorChooser
Return false when viewport width is below 640px (Tailwind sm breakpoint),
matching the isMobile check used elsewhere in the app.

https://claude.ai/code/session_01KoPM7CZKWdwdZPm4MneGVE
2026-03-03 22:02:10 +00:00
Sidharth Vinod 82f7371fed fix: Do not show editor selector to users coming from docs site, as they have seen one already 2026-03-04 01:50:29 +05:30
Sidharth Vinod e56451e027 chore: Update coupon code 2026-03-04 01:43:34 +05:30
Sidharth VinodandGitHub 1ed126e684 Merge pull request #1898 from mermaid-js/sidv/fixTests
tests: Tweak failing tests
2026-03-03 11:41:35 -08:00
Sidharth Vinod a85bc09092 fix: Track mermaid.ai outflow 2026-03-04 01:10:12 +05:30
Sidharth Vinod 5cc29dfebe tests: Tweak failing tests 2026-03-04 00:32:16 +05:30
Sidharth VinodandGitHub 6079e5e1ba Merge pull request #1896 from mermaid-js/sidv/popup
Editor Chooser popup
2026-03-03 10:33:43 -08:00
Sidharth Vinod dabbf5700a test: Disable popup in tests 2026-03-03 23:45:51 +05:30
Sidharth Vinod 13e5e834a2 fix: Respect MERMAID_IS_ENABLED_MERMAID_CHART_LINKS for popup 2026-03-03 15:56:47 +05:30
Sidharth Vinod bf1a7581e8 chore: Add editor chooser dialog for first time users 2026-03-03 15:54:37 +05:30
Sidharth Vinod d092480cf3 chore: Auto redirect to new domain 2026-03-03 13:22:36 +05:30
Sidharth VinodandGitHub 94f7dafc72 Merge pull request #1886 from chouheiwa/fix/cjk-text-visibility-in-svg-export
fix: ensure CJK text visibility in SVG export
2026-02-16 21:11:50 +05:30
Sidharth VinodandGitHub 8d7db5501a Merge pull request #1883 from saurabhg772244/saurabh/add-mermaid-inline-ai
add mermaid inline AI
2026-02-16 20:44:51 +05:30
saurabhg772244 f6cf766986 added dark mode for icon 2026-02-16 19:36:20 +05:30
Sidharth VinodandGitHub 4bfe42458e Merge pull request #1887 from mermaid-js/sidv/promo
chore: Update promo URL
2026-02-16 16:46:25 +05:30
Sidharth Vinod f6f9668044 fix: Update couponID 2026-02-16 16:13:33 +05:30
Sidharth Vinod 2b13fde292 chore: Update promo URL 2026-02-16 15:55:21 +05:30
chouheiwa 5aed4ea7a0 fix: use viewBox dimensions for PNG export canvas size
In rough mode, SVG width/height are set to 100%, so getBoundingClientRect
returns the container size instead of the actual diagram size. Use viewBox
dimensions when available to get the correct aspect ratio for PNG export.
2026-02-16 16:19:22 +08:00
chouheiwa 5dd1ec6b63 fix: apply foreignObject clipping fix to PNG export path
Move fixForeignObjectClipping into getBase64SVG so it covers both
SVG and PNG export flows. Previously only getSvgElement (SVG export)
applied the fix, while exportImage (PNG export) passed the svg element
directly to getBase64SVG, bypassing the fix entirely.
2026-02-16 11:12:40 +08:00
chouheiwa 49f800bacb fix: apply foreignObject clipping fix to all languages in rough mode SVG export 2026-02-16 09:18:17 +08:00
chouheiwa 83ba64c8c8 fix: ensure CJK text visibility in SVG export 2026-02-15 17:31:32 +08:00
Sidharth VinodandGitHub 49629cfb61 Update Canonicals 2026-02-13 19:30:59 +05:30
saurabhg772244 6160617458 Fix AI inline popup issues and remove quick edit functionality 2026-02-13 13:54:39 +05:30
saurabhg772244 1166479277 remove unused global style 2026-02-12 20:02:48 +05:30
saurabhg772244 958e7aa62c close popup on outside click and escape button 2026-02-12 19:51:54 +05:30
saurabhg772244 aa3479d508 code refactor and fix icon hover issue 2026-02-12 15:52:21 +05:30
saurabhg772244 830df8c44b add mermaid inline AI 2026-02-12 13:13:16 +05:30
Sidharth VinodandGitHub 629d9639d2 Merge pull request #1882 from mermaid-js/sidv/promo
feat: Add new year promo
2026-02-02 15:33:56 +05:30
Sidharth Vinod 1a529f598f feat: Add new year promo 2026-02-02 15:33:02 +05:30
Sidharth Vinod f3d580b8eb fix: Update tiny tree 2026-01-29 14:22:08 +05:30
Sidharth VinodandGitHub 7414ac0926 Merge pull request #1878 from mermaid-js/sidv/updateMcDomain
feat: Hide tooltip based on domain
2026-01-28 12:02:01 +05:30
Sidharth VinodandGitHub c05fa21dcc Merge pull request #1877 from mermaid-js/sidv/updateDocsURL
chore: Make docs URL configurable during build
2026-01-28 12:01:52 +05:30
Sidharth VinodandGitHub 61e194517d Merge pull request #1875 from mermaid-js/sidv/removePlayground
chore: Remove playground toggle
2026-01-28 12:01:29 +05:30
Sidharth Vinod 9946dff29d feat: Hide tooltip based on domain 2026-01-28 11:52:30 +05:30
Sidharth Vinod d72e91a7b8 chore: Make docs URL configurable during build 2026-01-28 11:37:12 +05:30
Sidharth Vinod 832cf7d4e7 fix: lint errors 2026-01-28 00:35:02 +05:30
Sidharth Vinod b92fda6279 Merge branch 'develop' into sidv/removePlayground
* develop:
  fix: lint errors
  chore: update dependencies
2026-01-28 00:33:21 +05:30
Sidharth Vinod 7f551dbbe6 fix: lint errors 2026-01-28 00:32:44 +05:30
Sidharth Vinod 5dd2fe4bd0 chore: update dependencies 2026-01-28 00:32:32 +05:30
Sidharth Vinod d9e70427af chore: Remove playground toggle 2026-01-28 00:25:17 +05:30
Sidharth Vinod 739ef6dfe2 chore: remove trackOnLocalhost 2025-10-15 15:59:05 +05:30
Sidharth Vinod 48c560c979 fix: Catch panZoom errors 2025-10-15 15:58:04 +05:30
Sidharth Vinod b1367c2178 fix(#1791): Disable plausible init when analytics url is empty 2025-10-15 15:57:41 +05:30
Sidharth Vinod ef6aa4b09d feat: Add layout-tidy-tree 2025-10-15 15:25:43 +05:30
Sidharth Vinod ea6ae3d7e2 feat: debounce error section 2025-10-08 19:57:20 +05:30
Sidharth VinodandGitHub 01cd13c712 Merge pull request #1798 from junqwoopark/bug/1797_fix_export_background_color
fix(export): Remove redundant hsl() from background color
2025-09-18 20:21:25 +05:30
Sidharth VinodandGitHub e41499eda3 Merge pull request #1799 from mermaid-js/renovate/mermaid-packages
fix(deps): update dependency mermaid to ^11.12.0
2025-09-18 20:08:22 +05:30
renovate[bot]andGitHub 6c08c490b1 fix(deps): update dependency mermaid to ^11.12.0 2025-09-18 09:41:15 +00:00
junqwoopark b237dd64eb fix(export): Remove redundant hsl() from background color 2025-09-07 20:59:34 +09:00
Sidharth VinodandGitHub e943ffad49 Merge pull request #1788 from PetrLaskevic/develop
fix: light background with dark diagram theme when downloading SVG ([#1777](https://github.com/mermaid-js/mermaid-live-editor/issues/1777))
2025-09-03 12:37:03 +00:00
Sidharth VinodandGitHub 0e203d3ebd Merge pull request #1795 from mermaid-js/sidv/mainMenu
Update Menu items
2025-09-03 12:31:15 +00:00
Sidharth Vinod c532b06b1a fix: Hover 2025-09-03 17:23:19 +05:30
Sidharth Vinod 7d709fecc5 fix: Add hamburger icon 2025-09-03 17:22:09 +05:30
Sidharth VinodandGitHub b87538cfe4 Merge branch 'develop' into sidv/mainMenu 2025-09-03 17:14:09 +05:30
Sidharth VinodandGitHub 7172054b91 Merge pull request #1793 from mermaid-js/sidv/updateDeps2
Update Deps
2025-09-03 17:13:43 +05:30
Sidharth Vinod c70bfe8cfa chore: Upgrade vitest 2025-09-03 16:59:41 +05:30
Sidharth Vinod fe7d04457a chore: lint fix 2025-09-03 16:49:35 +05:30
Sidharth Vinod 2c717b670e chore: Update menu 2025-09-03 16:47:14 +05:30
Sidharth Vinod cb062d49b1 chore: Update utils 2025-09-03 16:42:08 +05:30
Sidharth Vinod def809f6bd chore: Remove postcss 2025-09-03 16:38:03 +05:30
Sidharth Vinod 7da0081ace Update tailwind and shadcn 2025-09-03 16:36:09 +05:30
Sidharth Vinod ee6f595880 chore: Remove .eslintrc.cjs configuration file 2025-09-03 01:43:25 +05:30
Sidharth Vinod d991139b0a chore: Update eslint 2025-09-03 01:41:51 +05:30
Sidharth Vinod eb9121de12 chore: Update deps 2025-09-02 22:57:16 +05:30
PetrLaskevic 2aaa2e872f fix: light background with dark diagram theme when downloading SVG ([#1777](https://github.com/mermaid-js/mermaid-live-editor/issues/1777)) 2025-08-21 20:04:28 +02:00
Sidharth VinodandGitHub 6f26aec073 Merge pull request #1786 from aschaber1/develop
ci(docker-publish): :contruction_worker: fix quotes
2025-08-20 12:29:32 +05:30
Alexander Schaber f9a9686d76 ci(docker-publish): :contruction_worker: fix quotes 2025-08-20 08:49:04 +02:00
Sidharth VinodandGitHub 6b7a4803a4 Merge pull request #1761 from aschaber1/develop
ci(docker-publish): add arm64 builds and attestations
2025-08-20 12:06:34 +05:30
Sidharth Vinod 5817555d91 chore: Update browserlist 2025-08-20 11:59:49 +05:30
Sidharth VinodandGitHub 5a7ee057c3 Merge pull request #1783 from mermaid-js/sidv/updateMermaid
chore: Update mermaid version
2025-08-20 11:51:41 +05:30
Sidharth Vinod 75126f180d test: Update svg size 2025-08-20 11:47:59 +05:30
Sidharth Vinod 74777b3791 chore: Update mermaid version 2025-08-20 11:42:39 +05:30
Alexander Schaber c9c235b85f ci(docker-publish): 👷 Update Docker publish workflow metadata tagging
- Replace manual version checks with built-in conditions in docker/metadata-action
2025-08-18 18:54:38 +02:00
Alexander Schaber d7ce5aeb42 ci(docker-publish): 👷 Update workflow to trigger certain steps only on push events
- Modify conditions to ensure `docker/login-action` runs only on push
- Add condition to gate `docker/publish-action` execution on push event
2025-08-18 18:18:10 +02:00
Alexander Schaber 8221a1ca48 ci(docker-publish): 👷 Enhance Docker publish workflow security and permissions
- Configure required permissions for package registry and attestations
- Enable build provenance attestation using actions/attest-build-provenance@v2
2025-08-18 18:18:10 +02:00
Alexander Schaber 0ebad9e207 ci(docker-publish): 👷 enable arm64 builds 2025-08-18 18:18:10 +02:00
Sidharth VinodandGitHub ce50b65cde Merge pull request #1775 from mermaid-js/sidv/privacy
chore: Highlight external services
2025-08-11 19:49:24 +05:30
Sidharth Vinod ceaeb1eb23 chore: Organize imports 2025-08-05 01:08:14 +05:30
Sidharth Vinod cf3957c2a2 feat: Example highlight in Privacy 2025-08-05 01:00:18 +05:30
Sidharth Vinod 9fd3a032a9 refactor: Simplify labelPrefix logic 2025-08-05 00:47:24 +05:30
Sidharth Vinod f8842d2ce2 chore: Remove redundant prefix 2025-08-05 00:43:06 +05:30
Sidharth Vinod ee14854139 fix: Remove hardcoded domains 2025-08-05 00:42:01 +05:30
Sidharth Vinod 4d50ec39f3 chore: Clarify privacy statement 2025-08-05 00:28:47 +05:30
Sidharth Vinod 41874f6d44 feat: Wrap all 3rd party services in tooltip 2025-08-05 00:27:37 +05:30
Sidharth VinodandGitHub 2275404e9d Merge pull request #1701 from mermaid-js/sidv/examples
Add examples for all diagrams
2025-08-04 07:19:03 +00:00
Sidharth VinodandGitHub 956a584322 Merge branch 'develop' into sidv/examples 2025-08-04 12:45:45 +05:30
Sidharth Vinod cc308b81c9 test: Update size to match new diagram 2025-08-04 12:45:26 +05:30
Sidharth VinodandGitHub 19b82c3d44 Merge pull request #1769 from mermaid-js/sidv/disposeEditorModels
fix: Dispose editor models
2025-08-02 19:40:47 +00:00
Sidharth Vinod ae928c3713 chore: Run tests on merge queue 2025-08-03 01:10:09 +05:30
Sidharth Vinod 1a2d752ca4 test: Update diagram names 2025-08-02 19:29:46 +05:30
Sidharth Vinod d3e2d137ea Merge branch 'develop' into sidv/examples
* develop:
  fix: #1766 hide external buttons if env var is not set
  chore: Rename layout to ts
  fix(deps): update dependency mermaid to ^11.9.0
2025-08-02 19:19:44 +05:30
Sidharth VinodandGitHub 1da5a3c193 Merge pull request #1757 from mermaid-js/renovate/mermaid-packages
fix(deps): update dependency mermaid to ^11.9.0
2025-08-02 13:47:49 +00:00
Sidharth VinodandGitHub 273a2c06c0 Merge pull request #1770 from mermaid-js/sidv/disableExternalButtons
fix: Disable external buttons based on env
2025-08-02 13:47:08 +00:00
Sidharth Vinod 3ace70a439 fix: #1766 hide external buttons if env var is not set 2025-08-02 19:14:32 +05:30
Sidharth Vinod bc4b24f049 chore: Rename layout to ts 2025-08-02 19:13:46 +05:30
Sidharth Vinod b5c5c8e7b0 fix: Dispose editor models to avoid model already exists issue when switching from mobile to desktop view 2025-08-02 18:58:58 +05:30
renovate[bot]andGitHub 6b09a7ef2d fix(deps): update dependency mermaid to ^11.9.0 2025-07-21 01:24:27 +00:00
Sidharth Vinod 58aa3c0b67 Merge branch 'develop' into sidv/examples
* develop:
  feat: Add Treemap support (mermaid 11.8.1)
  chore: Update text-size
  Chore: Update banner ad
  Enable MC Links
  fix: Trace path
  fix: Hide AI Repair button in config tab
  fix(deps): update all non-major dependencies
  Update as per PR suggestion
  chore: Cleanup tagline logic
  chore(deps): update dependency lucide-svelte to ^0.507.0
  chore: Update announcement bar
2025-07-16 19:59:34 +05:30
Sidharth VinodandGitHub b577f4b2d4 Merge pull request #1750 from mermaid-js/sidv/11.8.1
feat: Add Treemap support (mermaid 11.8.1)
2025-07-10 07:03:31 +00:00
Sidharth Vinod 1dbf0ab5f6 feat: Add Treemap support (mermaid 11.8.1) 2025-07-07 21:16:54 +05:30
Sidharth VinodandGitHub 99dd67e359 Merge pull request #1742 from mermaid-js/rajat-ht/chore-update-banner-ad
Chore: Update banner ad
2025-06-20 10:24:47 +05:30
rajat-ht 7475360115 chore: Update text-size 2025-06-19 16:06:29 +05:30
rajat-ht 470c704542 Chore: Update banner ad 2025-06-18 20:01:43 +05:30
Sidharth VinodandGitHub 0683cdbaa2 Merge pull request #1726 from mermaid-js/sidv/hideAIRepair
fix: Hide AI Repair button in config tab
2025-05-27 13:53:04 +00:00
Sidharth Vinod 569f3ca232 Enable MC Links 2025-05-27 18:43:17 +05:30
Sidharth Vinod 4052221168 fix: Trace path 2025-05-27 18:25:18 +05:30
Sidharth VinodandAlois Klink 400f3ecf95 fix: Hide AI Repair button in config tab
Co-authored-by: Alois Klink <alois@aloisklink.com>
2025-05-26 23:14:45 +05:30
Sidharth Vinod 4d1c6e4702 Merge branch 'develop' into sidv/examples
* develop:
  chore(deps): update all non-major dependencies
  fix(deps): update all non-major dependencies
  fix: #1659 Frozen UI with comment regex
2025-05-02 02:39:16 +05:30
Sidharth Vinod d963baf96e Merge branch 'develop' into sidv/examples
* develop: (32 commits)
  feat: Support jsonSchema to validate config
  link: live version
  fix: Fallback page
  chore(deps): update dependency vite to v5.4.18 [security]
  fix: Fallback to sveltekit on 404 in GH pages
  chore(deps): update all non-major dependencies
  fix: New diagram link
  chore(deps): update dependency @sveltejs/kit to v2.20.6 [security]
  feat: Wait for fontawesome to load
  chore(deps): update all non-major dependencies
  feat: Support pan while zooming
  Update src/lib/util/panZoom.ts
  chore: Track PWA install device type
  chore: Track PWA installs
  chore: Add analytics for mobileViewToggle
  fix: Reduce gap in mobile
  fix: SVG size to avoid
  chore: Unify code update logic
  chore: Cleanup deps
  feat: Add syntax highlighting
  ...
2025-04-20 13:42:04 +05:30
Sidharth Vinod 70ea4f59a0 chore: Update @mermaid-js/examples version 2025-04-20 13:41:17 +05:30
Sidharth Vinod a0e54ff7bd chore: Use mermaid examples package to populate samples 2025-04-12 17:27:24 +05:30
95 changed files with 4004 additions and 2789 deletions
+3 -1
View File
@@ -1,7 +1,9 @@
MERMAID_DOMAIN=''
MERMAID_BASE_PATH=''
MERMAID_DOCS_URL='https://mermaid.js.org'
MERMAID_ANALYTICS_URL=''
MERMAID_RENDERER_URL='https://mermaid.ink'
MERMAID_KROKI_RENDERER_URL='https://kroki.io'
MERMAID_IS_ENABLED_MERMAID_CHART_LINKS=''
MERMAID_IS_ENABLED_MERMAID_CHART_LINKS='true'
# cp .env .env.local to make local changes
-8
View File
@@ -1,8 +0,0 @@
docs/**
.svelte-kit/**
static/**
build/**
node_modules/**
coverage/**
__snapshots__/**
snapshots.js
-121
View File
@@ -1,121 +0,0 @@
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
// 'plugin:@typescript-eslint/recommended-requiring-type-checking',
'plugin:@typescript-eslint/strict',
'plugin:unicorn/recommended',
'plugin:svelte/recommended',
'plugin:svelte/prettier',
'prettier'
],
plugins: [
'tailwindcss',
'@typescript-eslint',
'es',
'vitest',
'no-only-tests',
'sort-keys',
'unicorn'
],
ignorePatterns: [
'docs/*',
'*.cjs',
'*.js',
'*.md',
'snapshots.js',
'svelte.config.js',
'renovate.json',
'package.json',
'tsconfig.json'
],
overrides: [
{
files: ['*.svelte'],
parser: 'svelte-eslint-parser',
parserOptions: {
parser: '@typescript-eslint/parser'
}
},
{
files: ['*.ts'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended-requiring-type-checking',
'plugin:@typescript-eslint/strict',
'prettier'
]
},
{
files: ['**/components/ui/**'],
rules: {
'unicorn/prefer-export-from': 'off',
'unicorn/prevent-abbreviations': 'off',
'unicorn/explicit-length-check': 'off',
'sort-keys/sort-keys-fix': 'off'
}
}
],
parserOptions: {
sourceType: 'module',
ecmaVersion: 2020,
tsconfigRootDir: __dirname,
project: './tsconfig.json',
extraFileExtensions: ['.svelte']
},
env: {
browser: true,
es2020: true
},
rules: {
'sort-keys/sort-keys-fix': ['error', 'asc', { minKeys: 5 }],
'@typescript-eslint/ban-ts-comment': [
'error',
{
'ts-ignore': 'allow-with-description'
}
],
'@typescript-eslint/no-unsafe-member-access': 'off',
'@typescript-eslint/no-unsafe-assignment': 'off',
'es/no-regexp-lookbehind-assertions': 'error',
curly: ['error', 'all'],
'no-only-tests/no-only-tests': 'error',
'unicorn/no-null': 'off',
'unicorn/filename-case': [
'error',
{
case: 'camelCase'
}
],
'unicorn/filename-case': 'off',
'unicorn/prevent-abbreviations': [
'error',
{
allowList: {
args: true,
ctx: true,
db: true,
doc: true,
env: true,
fn: true,
i: true,
j: true,
k: true,
param: true,
Params: true,
params: true,
Props: true,
props: true,
req: true,
res: true,
str: true,
temp: true,
ImportMetaEnv: true
}
}
]
}
};
+17 -6
View File
@@ -17,32 +17,43 @@ on:
jobs:
docker:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
attestations: write
id-token: write
steps:
- uses: actions/checkout@v4
- uses: docker/setup-qemu-action@v3
- uses: docker/setup-buildx-action@v3
- name: Login to GitHub Container Registry
if: github.event_name != 'pull_request'
if: github.event_name == 'push'
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Get release version
run: |
RELEASE_VERSION=$([ "${{ github.ref_name }}" = "master" ] && echo "latest" || echo "nightly")
echo "RELEASE_VERSION=${RELEASE_VERSION}" >> "${GITHUB_ENV}"
- uses: docker/metadata-action@v5
id: meta
with:
images: ghcr.io/${{ github.repository }}
tags: |
type=raw,value=${{ env.RELEASE_VERSION }}
type=raw,value=latest,enable=${{ github.ref_name == 'master' }}
type=raw,value=nightly,enable=${{ github.ref_name == 'develop' }}
- uses: docker/build-push-action@v5
id: build
with:
context: .
target: mermaid
push: ${{ github.event_name == 'push' }}
platforms: linux/amd64,linux/arm64
pull: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
- name: Generate Build Attestation
uses: actions/attest-build-provenance@v2
with:
subject-name: ghcr.io/${{ github.repository }}
subject-digest: ${{ steps.build.outputs.digest }}
push-to-registry: true
if: github.event_name == 'push'
+4 -3
View File
@@ -5,6 +5,7 @@ on:
branches:
- master
- develop
merge_group:
jobs:
playwright:
@@ -49,6 +50,6 @@ jobs:
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() }}
with:
name: playwright-report
path: playwright-report/
retention-days: 30
name: test-results
path: test-results/
retention-days: 7
+1
View File
@@ -5,6 +5,7 @@ on:
branches:
- master
- develop
merge_group:
jobs:
unit-tests:
+2 -2
View File
@@ -4,6 +4,6 @@
"bracketSameLine": true,
"trailingComma": "none",
"printWidth": 100,
"tailwindConfig": "./tailwind.config.js",
"plugins": ["prettier-plugin-svelte", "prettier-plugin-tailwindcss"]
"plugins": ["prettier-plugin-svelte", "prettier-plugin-tailwindcss"],
"tailwindStylesheet": "./src/app.css"
}
+10
View File
@@ -0,0 +1,10 @@
{
"servers": {
"svelte": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@sveltejs/mcp"]
}
},
"inputs": []
}
+9 -1
View File
@@ -16,6 +16,7 @@
"localstorage",
"mermaidchart",
"mindmap",
"NEWYEAR",
"Pageview",
"pako",
"panmove",
@@ -25,11 +26,14 @@
"pinchstart",
"pzoom",
"roughjs",
"sankey",
"Serde",
"serdes",
"Stackable",
"tailwindcss",
"treemap",
"uparrow",
"xychart",
"zenuml"
],
"vitest.commandLine": "pnpm test:unit",
@@ -44,5 +48,9 @@
"tailwindCSS.experimental.classRegex": [
["([\"'`][^\"'`]*.*?[\"'`])", "[\"'`]([^\"'`]*).*?[\"'`]"]
],
"tailwindCSS.emmetCompletions": true
"tailwindCSS.emmetCompletions": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit",
"source.organizeImports": "explicit"
}
}
+3
View File
@@ -19,6 +19,9 @@ ARG MERMAID_KROKI_RENDERER_URL
ARG MERMAID_ANALYTICS_URL
ARG MERMAID_DOMAIN
ARG MERMAID_IS_ENABLED_MERMAID_CHART_LINKS
ARG MERMAID_PRIVACY_POLICY_URL
ARG MERMAID_HIDE_PRIVACY_POLICY
ARG MERMAID_BASE_PATH
COPY . ./
+2
View File
@@ -28,6 +28,8 @@ If you want to speed up the progress for mermaid-live-editor, join the Discord c
docker run --platform linux/amd64 --publish 8000:8080 ghcr.io/mermaid-js/mermaid-live-editor
```
The published docker image is built using our default environment variables. You cannot override them when running the image. If you need to customize them, you will need to build the image yourself.
### To configure renderer URL
When building set the MERMAID_RENDERER_URL build argument to the rendering
+4 -5
View File
@@ -1,17 +1,16 @@
{
"$schema": "https://next.shadcn-svelte.com/schema.json",
"style": "new-york",
"tailwind": {
"config": "tailwind.config.js",
"css": "src/app.postcss",
"css": "src/app.css",
"baseColor": "slate"
},
"aliases": {
"components": "$lib/components",
"utils": "$lib/utils",
"ui": "$lib/components/ui",
"hooks": "$lib/hooks"
"hooks": "$lib/hooks",
"lib": "$lib"
},
"typescript": true,
"registry": "https://next.shadcn-svelte.com/registry"
"registry": "https://tw3.shadcn-svelte.com/registry/new-york"
}
+74
View File
@@ -0,0 +1,74 @@
import { includeIgnoreFile } from '@eslint/compat';
import js from '@eslint/js';
import prettier from 'eslint-config-prettier';
import sortKeysPlugin from 'eslint-plugin-sort-keys';
import svelte from 'eslint-plugin-svelte';
import eslintPluginUnicorn from 'eslint-plugin-unicorn';
import { defineConfig } from 'eslint/config';
import globals from 'globals';
import { fileURLToPath } from 'node:url';
import ts from 'typescript-eslint';
import svelteConfig from './svelte.config.js';
const gitignorePath = fileURLToPath(new URL('./.gitignore', import.meta.url));
export default defineConfig(
includeIgnoreFile(gitignorePath),
js.configs.recommended,
...ts.configs.strict,
...ts.configs.stylistic,
...svelte.configs.recommended,
prettier,
...svelte.configs.prettier,
{
languageOptions: {
globals: { ...globals.browser, ...globals.node }
},
rules: {
// typescript-eslint strongly recommend that you do not use the no-undef lint rule on TypeScript projects.
// see: https://typescript-eslint.io/troubleshooting/faqs/eslint/#i-get-errors-from-the-no-undef-rule-about-global-variables-not-being-defined-even-though-there-are-no-typescript-errors
'no-undef': 'off'
}
},
{
plugins: {
unicorn: eslintPluginUnicorn
},
rules: {
'unicorn/no-null': 'off',
'unicorn/filename-case': 'off'
}
},
{
files: ['src/**'],
plugins: {
'sort-keys': sortKeysPlugin
},
rules: {
'sort-keys/sort-keys-fix': ['error', 'asc', { minKeys: 5 }]
}
},
{
files: ['**/*.svelte', '**/*.svelte.ts', '**/*.svelte.js'],
languageOptions: {
parserOptions: {
projectService: true,
extraFileExtensions: ['.svelte'],
parser: ts.parser,
svelteConfig
}
},
rules: {
'svelte/no-unused-props': 'off'
}
},
{
files: ['**/components/ui/**'],
rules: {
'unicorn/prefer-export-from': 'off',
'unicorn/prevent-abbreviations': 'off',
'unicorn/explicit-length-check': 'off',
'sort-keys/sort-keys-fix': 'off'
}
}
);
+1
View File
@@ -1,5 +1,6 @@
[build.environment]
MERMAID_ANALYTICS_URL = 'https://p.mermaid.live'
MERMAID_DOCS_URL = 'https://mermaid.js.org'
MERMAID_DOMAIN = 'mermaid.live'
MERMAID_RENDERER_URL = 'https://mermaid.ink'
MERMAID_KROKI_RENDERER_URL = 'https://kroki.io'
+43 -38
View File
@@ -9,8 +9,8 @@
"dev:test": "pnpm dev",
"build": "vite build",
"preview": "vite preview",
"lint": "prettier --check --cache . && eslint --ignore-path .gitignore .",
"lint:fix": "prettier --write --cache . && eslint --fix --ignore-path .gitignore .",
"lint": "prettier --check --cache . && eslint .",
"lint:fix": "prettier --write --cache . && eslint --fix .",
"format": "prettier --write --cache .",
"pre-commit": "lint-staged",
"postinstall": "husky install && svelte-kit sync && (git config blame.ignoreRevsFile .git-blame-ignore-revs || true)",
@@ -23,62 +23,65 @@
"test:e2e:debug": "playwright test --debug"
},
"devDependencies": {
"@eslint/compat": "^1.2.5",
"@eslint/eslintrc": "^3.3.3",
"@eslint/js": "^9.39.2",
"@fortawesome/fontawesome-free": "^6.7.2",
"@iconify-json/material-symbols": "^1.2.20",
"@iconify-json/mdi": "^1.2.3",
"@playwright/test": "^1.52.0",
"@sveltejs/adapter-static": "3.0.8",
"@sveltejs/kit": "2.20.8",
"@sveltejs/vite-plugin-svelte": "^4.0.4",
"@sveltejs/adapter-static": "^3.0.9",
"@sveltejs/kit": "^2.37.0",
"@sveltejs/vite-plugin-svelte": "^6.1.3",
"@tailwindcss/typography": "^0.5.19",
"@tailwindcss/vite": "^4.1.18",
"@types/hammerjs": "^2.0.46",
"@types/lodash-es": "^4.17.12",
"@types/node": "^22.15.10",
"@types/pako": "2.0.3",
"@types/uuid": "9.0.8",
"@typescript-eslint/eslint-plugin": "6.21.0",
"@typescript-eslint/parser": "6.21.0",
"@vitest/coverage-v8": "2.1.9",
"@vitest/ui": "^2.1.9",
"@vitest/coverage-v8": "^3.2.4",
"@vitest/ui": "^3.2.4",
"autoprefixer": "^10.4.21",
"bits-ui": "^1.4.6",
"bits-ui": "^2.9.6",
"c8": "7.14.0",
"chai": "^4.5.0",
"clsx": "^2.1.1",
"cssnano": "^6.1.2",
"eslint": "8.57.1",
"eslint-config-prettier": "9.1.0",
"dotenv": "^17.3.1",
"eslint": "^9.39.2",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-es": "^4.1.0",
"eslint-plugin-no-only-tests": "^3.3.0",
"eslint-plugin-postcss-modules": "^2.0.0",
"eslint-plugin-sort-keys": "^2.3.5",
"eslint-plugin-svelte": "^2.46.1",
"eslint-plugin-tailwindcss": "^3.18.0",
"eslint-plugin-unicorn": "^50.0.1",
"eslint-plugin-vitest": "^0.5.4",
"eslint-plugin-svelte": "^3.0.0",
"eslint-plugin-tailwindcss": "^3.18.2",
"eslint-plugin-unicorn": "^60.0.0",
"esserializer": "^1.3.11",
"globals": "^16.0.0",
"husky": "^8.0.3",
"jsdom": "^25.0.1",
"lint-staged": "^15.5.1",
"lucide-svelte": "^0.507.0",
"node-html-parser": "^6.1.13",
"paneforge": "^1.0.0-next.5",
"postcss": "^8.5.3",
"postcss-load-config": "5.1.0",
"prettier": "^3.5.3",
"prettier-plugin-svelte": "^3.3.3",
"prettier-plugin-tailwindcss": "^0.6.11",
"svelte": "^5.28.2",
"paneforge": "1.0.0-next.6",
"prettier": "^3.8.1",
"prettier-plugin-svelte": "^3.4.1",
"prettier-plugin-tailwindcss": "^0.7.2",
"svelte": "^5.38.6",
"svelte-preprocess": "^6.0.3",
"svelte-sonner": "^0.3.28",
"tailwind-merge": "^3.2.0",
"tailwind-variants": "^0.3.1",
"tailwindcss": "^3.4.17",
"tailwindcss-animate": "^1.0.7",
"svelte-sonner": "^1.0.5",
"tailwind-merge": "^3.3.1",
"tailwind-variants": "^3.1.0",
"tailwindcss": "^4.1.18",
"tslib": "^2.8.1",
"typescript": "^5.8.3",
"unplugin-icons": "^22.1.0",
"vite": "^5.4.19",
"vitest": "^2.1.9",
"tw-animate-css": "^1.3.8",
"typescript": "^5.9.2",
"typescript-eslint": "^8.42.0",
"unplugin-icons": "^22.2.0",
"vite": "^7.1.4",
"vite-plugin-devtools-json": "^1.0.0",
"vitest": "^3.2.4",
"vitest-dom": "^0.1.1"
},
"dependencies": {
@@ -91,14 +94,16 @@
"@fontsource-variable/recursive": "^5.2.5",
"@fsegurai/codemirror-theme-vscode-dark": "^6.1.4",
"@fsegurai/codemirror-theme-vscode-light": "^6.1.4",
"@mermaid-js/layout-elk": "^0.1.7",
"@mermaid-js/mermaid-zenuml": "^0.2.0",
"@mermaid-js/examples": "^1.0.0",
"@mermaid-js/layout-elk": "^0.1.9",
"@mermaid-js/layout-tidy-tree": "^0.2.1",
"@mermaid-js/mermaid-zenuml": "^0.2.2",
"codemirror": "^6.0.1",
"dayjs": "^1.11.13",
"hammerjs": "^2.0.8",
"js-base64": "3.7.7",
"lodash-es": "^4.17.21",
"mermaid": "^11.6.0",
"mermaid": "^11.13.0",
"mode-watcher": "^0.5.1",
"monaco-editor": "0.52.2",
"pako": "2.1.0",
@@ -111,11 +116,11 @@
"lint-staged": {
"*.{ts,svelte,js,css,md,json}": [
"prettier --plugin-search-dir=. --write",
"eslint --ignore-path .gitignore "
"eslint "
]
},
"engines": {
"node": ">=20.19.1"
"node": ">=20.19.0"
},
"packageManager": "pnpm@10.10.0+sha512.d615db246fe70f25dcfea6d8d73dee782ce23e2245e3c4f6f888249fb568149318637dca73c2c5c8ef2a4ca0d5657fb9567188bfab47f566d1ee6ce987815c39",
"pnpm": {
+2077 -1693
View File
File diff suppressed because it is too large Load Diff
-23
View File
@@ -1,23 +0,0 @@
const tailwindcss = require('tailwindcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
const mode = process.env.NODE_ENV;
const dev = mode === 'development';
module.exports = {
plugins: [
// Some plugins, like postcss-nested, need to run before Tailwind
tailwindcss,
// But others, like autoprefixer, need to run after
autoprefixer,
!dev &&
cssnano({
preset: 'default'
})
]
};
+119
View File
@@ -0,0 +1,119 @@
@import '@fontsource-variable/recursive/crsv.css';
@import 'tailwindcss';
@import 'tw-animate-css';
@custom-variant dark (&:is(.dark *));
@layer base {
*,
::after,
::before,
::backdrop,
::file-selector-button {
border-color: var(--color-gray-200, currentcolor);
}
}
@layer base {
:root {
--background: hsl(0 0% 100%);
--foreground: hsl(222.2 84% 4.9%);
--card: hsl(0 0% 100%);
--card-foreground: hsl(222.2 84% 4.9%);
--popover: hsl(0 0% 100%);
--popover-foreground: hsl(222.2 84% 4.9%);
--primary: hsl(240 10% 91%);
--primary-foreground: hsl(255 20% 15%);
--secondary: hsl(210 40% 96.1%);
--secondary-foreground: hsl(222.2 47.4% 11.2%);
--muted: hsl(228 24% 96%);
--muted-foreground: hsl(215.4 16.3% 46.9%);
--accent: hsl(340 100% 44%);
--accent-foreground: hsl(210 40% 98%);
--destructive: hsl(0 72.22% 50.59%);
--destructive-foreground: hsl(210 40% 98%);
--border: hsl(214.3 31.8% 91.4%);
--border-dark: hsl(214.3 31.8% 81.4%);
--input: hsl(214.3 31.8% 91.4%);
--ring: hsl(222.2 84% 4.9%);
--radius: 0.75rem;
}
.dark {
--background: hsl(222.2 84% 4.9%);
--foreground: hsl(210 40% 98%);
--card: hsl(222.2 84% 4.9%);
--card-foreground: hsl(210 40% 98%);
--popover: hsl(222.2 84% 4.9%);
--popover-foreground: hsl(210 40% 98%);
--primary: hsl(210 40% 30%);
--primary-foreground: hsl(222.2 47.4% 90%);
--secondary: hsl(217.2 32.6% 17.5%);
--secondary-foreground: hsl(210 40% 98%);
--muted: hsl(217.2 32.6% 17.5%);
--muted-foreground: hsl(215 20.2% 65.1%);
--accent: hsl(340 100% 44%);
--accent-foreground: hsl(210 40% 98%);
--destructive: hsl(0 62.8% 30.6%);
--destructive-foreground: hsl(210 40% 98%);
--border: hsl(217.2 32.6% 17.5%);
--border-dark: hsl(217.2 32.6% 27.5%);
--input: hsl(217.2 32.6% 17.5%);
--ring: hsl(212.7 26.8% 83.9%);
}
}
@theme inline {
/* Radius (for rounded-*) */
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
/* Colors */
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-border: var(--border);
--color-border-dark: var(--border-dark);
--color-input: var(--input);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-ring: var(--ring);
--color-radius: var(--radius);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
}
@layer base {
* {
@apply border-border;
}
body {
@apply h-screen w-screen overflow-hidden bg-background text-foreground;
}
}
body {
font-family: 'Recursive Variable', sans-serif;
}
.d {
@apply border border-red-500;
}
-1
View File
@@ -5,7 +5,6 @@
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Online FlowChart &amp; Diagrams Editor - Mermaid Live Editor</title>
<meta name="og:image" content="%sveltekit.assets%/favicon.svg" />
<link rel="canonical" href="https://mermaid.live" />
<meta
name="description"
content="Simplify documentation and avoid heavy tools. Open source Visio Alternative. Commonly used for explaining your code! Mermaid is a simple markdown-like script language for generating charts from text via javascript." />
-68
View File
@@ -1,68 +0,0 @@
@import '@fontsource-variable/recursive/crsv.css';
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--primary: 240 10% 91%;
--primary-foreground: 255 20% 15%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--muted: 228 24% 96%;
--muted-foreground: 215.4 16.3% 46.9%;
--accent: 340 100% 44%;
--accent-foreground: 210 40% 98%;
--destructive: 0 72.22% 50.59%;
--destructive-foreground: 210 40% 98%;
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
--ring: 222.2 84% 4.9%;
--radius: 0.75rem;
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
--primary: 210 40% 30%;
--primary-foreground: 222.2 47.4% 90%;
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--accent: 340 100% 44%;
--accent-foreground: 210 40% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--ring: 212.7 26.8% 83.9%;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply h-screen w-screen overflow-hidden bg-background text-foreground;
}
}
body {
font-family: 'Recursive Variable', sans-serif;
}
.d {
@apply border border-red-500;
}
+3
View File
@@ -4,8 +4,11 @@ interface ImportMetaEnv {
readonly MERMAID_RENDERER_URL?: string;
readonly MERMAID_KROKI_RENDERER_URL?: string;
readonly MERMAID_ANALYTICS_URL?: string;
readonly MERMAID_DOCS_URL?: string;
readonly MERMAID_DOMAIN?: string;
readonly MERMAID_IS_ENABLED_MERMAID_CHART_LINKS?: string;
readonly MERMAID_PRIVACY_POLICY_URL?: string;
readonly MERMAID_HIDE_PRIVACY_POLICY?: string;
// more env variables...
}
-6
View File
@@ -1,6 +0,0 @@
import type { Handle } from '@sveltejs/kit';
export const handle: Handle = async ({ event, resolve }) => {
const response = await resolve(event, {});
return response;
};
+174
View File
@@ -0,0 +1,174 @@
<script lang="ts">
import { Button } from '$/components/ui/button';
import { cn } from '$lib/utils.js';
import CloseIcon from '~icons/material-symbols/close-rounded';
interface Props {
show: boolean;
input: string;
onClose: () => void;
onHeightChange?: (height: number) => void;
onTryFree: () => void;
}
let { show, input = $bindable(), onClose, onHeightChange, onTryFree }: Props = $props();
let textarea = $state<HTMLTextAreaElement>();
let container = $state<HTMLDivElement>();
$effect(() => {
if (!container || !onHeightChange) return;
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
if (entry.target instanceof HTMLElement) {
onHeightChange(entry.target.offsetHeight);
}
}
});
observer.observe(container);
return () => observer.disconnect();
});
function resizeTextarea() {
if (!textarea) return;
const computed = globalThis.getComputedStyle(textarea);
const lineHeight =
Number.parseFloat(computed.lineHeight) || Number.parseFloat(computed.fontSize) * 1.5 || 0;
const paddingTop = Number.parseFloat(computed.paddingTop) || 0;
const paddingBottom = Number.parseFloat(computed.paddingBottom) || 0;
const minHeight = lineHeight + paddingTop + paddingBottom;
const maxLines = 8;
const maxHeight = lineHeight * maxLines + paddingTop + paddingBottom;
textarea.style.height = 'auto';
const nextHeight = Math.max(minHeight, Math.min(textarea.scrollHeight, maxHeight));
textarea.style.height = `${nextHeight}px`;
textarea.style.overflowY = textarea.scrollHeight > maxHeight ? 'auto' : 'hidden';
}
$effect(() => {
if (input !== undefined) {
resizeTextarea();
}
});
function handleKeydown(e: KeyboardEvent) {
if (show && e.key === 'Escape') {
onClose();
}
}
function handleOutsideClick(e: MouseEvent) {
if (show && container && e.target instanceof Node && !container.contains(e.target)) {
onClose();
}
}
</script>
<svelte:window onkeydown={handleKeydown} onmousedown={handleOutsideClick} />
{#if show}
<div
bind:this={container}
class={cn(
'button-container-for-animation relative z-50 mr-6 flex w-auto flex-col gap-2 rounded-xl border-2 border-border bg-background p-2 shadow-xl dark:border-border-dark dark:bg-secondary',
!input.trim() && 'rainbow-border'
)}
role="dialog"
aria-modal="true"
tabindex="-1">
<div class="relative flex min-h-2 items-start gap-1 px-1">
<textarea
bind:this={textarea}
bind:value={input}
onkeydown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
if (input.trim()) {
onTryFree();
}
}
}}
placeholder="Describe what to add or change"
rows="1"
class="focus font-recursive min-h-0 flex-1 resize-none border-none bg-transparent px-1 text-sm font-normal text-foreground placeholder:text-muted-foreground focus:ring-0 focus:outline-none disabled:opacity-50 dark:text-foreground dark:placeholder:text-muted-foreground"
style="height: 20px; overflow-y: hidden;"></textarea>
<button onclick={onClose} class="text-muted-foreground hover:text-foreground">
<CloseIcon class="size-4" />
</button>
</div>
<div class="flex items-center justify-between">
<span class="font-recursive text-xs font-normal text-foreground dark:text-foreground"
>Sign Up at Mermaid.ai to try AI</span>
<Button
class="font-recursive h-6 w-16 gap-1.5 rounded-sm bg-accent p-1 text-xs font-medium text-white no-underline hover:bg-accent/90 hover:text-white hover:no-underline active:bg-accent/80 dark:bg-accent dark:text-white! dark:hover:bg-accent/90 dark:active:bg-accent/80"
onclick={onTryFree}>
Try free
</Button>
</div>
</div>
{/if}
<style>
@property --gradient-angle {
syntax: '<angle>';
initial-value: 0deg;
inherits: false;
}
@keyframes gradient-angle-shift {
0% {
--gradient-angle: 0deg;
}
100% {
--gradient-angle: 360deg;
}
}
.button-container-for-animation {
border-radius: 12px;
}
.button-container-for-animation::before {
content: '';
position: absolute;
inset: -2px;
border-radius: 14px;
padding: 2px;
background: conic-gradient(
from var(--gradient-angle, 0deg),
color-mix(in srgb, var(--color-accent) 0%, transparent) 0%,
color-mix(in srgb, var(--color-accent) 0%, transparent) 12%,
color-mix(in srgb, var(--color-accent) 12%, transparent) 18%,
color-mix(in srgb, var(--color-accent) 42%, transparent) 24%,
color-mix(in srgb, var(--color-accent) 77%, transparent) 32%,
rgba(93, 85, 212, 0.923) 41%,
rgba(93, 85, 212, 0.5) 52%,
color-mix(in srgb, var(--color-accent) 58%, transparent) 72%,
color-mix(in srgb, var(--color-accent) 56%, transparent) 82%,
color-mix(in srgb, var(--color-accent) 36%, transparent) 87%,
color-mix(in srgb, var(--color-accent) 19%, transparent) 92%,
color-mix(in srgb, var(--color-accent) 10%, transparent) 96%,
color-mix(in srgb, var(--color-accent) 3%, transparent) 98%,
color-mix(in srgb, var(--color-accent) 0%, transparent) 100%
);
-webkit-mask:
linear-gradient(#fff 0 0) content-box,
linear-gradient(#fff 0 0);
-webkit-mask-composite: xor;
mask:
linear-gradient(#fff 0 0) content-box,
linear-gradient(#fff 0 0);
mask-composite: exclude;
pointer-events: none;
z-index: 0;
opacity: 0;
transition: opacity 0.3s ease-out;
}
.button-container-for-animation.rainbow-border::before {
opacity: 1;
animation: gradient-angle-shift 2s linear infinite;
}
</style>
+80 -118
View File
@@ -2,12 +2,13 @@
import Card from '$/components/Card/Card.svelte';
import CopyButton from '$/components/CopyButton.svelte';
import CopyInput from '$/components/CopyInput.svelte';
import ExternalLinkWrapper from '$/components/ExternalLinkWrapper.svelte';
import { Button } from '$/components/ui/button';
import { Input } from '$/components/ui/input';
import { Separator } from '$/components/ui/separator';
import * as ToggleGroup from '$/components/ui/toggle-group';
import { TID } from '$/constants';
import { env } from '$/util/env';
import { getDomain } from '$/util/util';
import { browser } from '$app/environment';
import { waitForRender } from '$lib/util/autoSync';
import { inputStateStore, stateStore, urlsStore } from '$lib/util/state';
@@ -19,129 +20,81 @@
import ExternalLinkIcon from '~icons/material-symbols/open-in-new-rounded';
import WidthIcon from '~icons/material-symbols/width-rounded';
const FONT_AWESOME_URL = `https://cdnjs.cloudflare.com/ajax/libs/font-awesome/${FAVersion}`;
const FONT_AWESOME_URL = `https://cdnjs.cloudflare.com/ajax/libs/font-awesome/${FAVersion}/css/all.min.css`;
type Exporter = (context: CanvasRenderingContext2D, image: HTMLImageElement) => () => void;
const getFileName = (extension: string) =>
`mermaid-diagram-${dayjs().format('YYYY-MM-DD-HHmmss')}.${extension}`;
/**
* Fix text clipping in exported SVG for hand-drawn (rough) mode.
* svg2roughjs copies foreignObject elements but their height is often insufficient,
* causing text bottom edges to be cut off regardless of language.
*/
const fixForeignObjectClipping = (svg: HTMLElement) => {
const foreignObjects = svg.querySelectorAll('foreignObject');
foreignObjects.forEach((foreignObj) => {
const currentHeight = parseFloat(foreignObj.getAttribute('height') || '0');
if (currentHeight <= 0) return;
const currentY = parseFloat(foreignObj.getAttribute('y') || '0');
const newHeight = currentHeight * 1.5;
const heightDiff = newHeight - currentHeight;
foreignObj.setAttribute('height', newHeight.toString());
foreignObj.setAttribute('y', (currentY - heightDiff / 2).toString());
// Ensure inner HTML elements are vertically centered within the expanded area
const htmlElements = foreignObj.querySelectorAll('div, span, p');
htmlElements.forEach((htmlEl) => {
const el = htmlEl as HTMLElement;
el.style.display = 'flex';
el.style.alignItems = 'center';
el.style.justifyContent = 'center';
el.style.height = '100%';
});
});
};
const getSvgElement = () => {
const svgElement = document.querySelector('#container svg')?.cloneNode(true) as HTMLElement;
svgElement.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
return svgElement;
};
/**
* Converts a Blob to base64 string
*/
export function blobToBase64(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener('load', () => resolve(reader.result as string));
reader.addEventListener('error', () => reject(new Error('Failed to convert blob to base64')));
reader.readAsDataURL(blob);
});
}
const getBase64SVG = async (
svg?: HTMLElement,
width?: number,
height?: number
): Promise<string> => {
const getBase64SVG = (svg?: HTMLElement, width?: number, height?: number): string => {
if (svg) {
// Prevents the SVG size of the interface from being changed
svg = svg.cloneNode(true) as HTMLElement;
}
height && svg?.setAttribute('height', `${height}px`);
width && svg?.setAttribute('width', `${width}px`); // Workaround https://stackoverflow.com/questions/28690643/firefox-error-rendering-an-svg-image-to-html5-canvas-with-drawimage
if (height) {
svg?.setAttribute('height', `${height}px`);
}
if (width) {
svg?.setAttribute('width', `${width}px`);
}
// Workaround https://stackoverflow.com/questions/28690643/firefox-error-rendering-an-svg-image-to-html5-canvas-with-drawimage
if (!svg) {
svg = getSvgElement();
}
try {
// Fetch both regular and brands Font Awesome CSS and font files
const [fontAwesomeCSS, solidFontBlob, brandsFontBlob, regularFontBlob] = await Promise.all([
fetch(`${FONT_AWESOME_URL}/css/all.min.css`).then((response) => response.text()),
fetch(`${FONT_AWESOME_URL}/webfonts/fa-solid-900.woff2`)
.then((res) => res.blob())
.catch(() => new Blob()),
fetch(`${FONT_AWESOME_URL}/webfonts/fa-brands-400.woff2`)
.then((res) => res.blob())
.catch(() => new Blob()),
fetch(`${FONT_AWESOME_URL}/webfonts/fa-regular-400.woff2`)
.then((res) => res.blob())
.catch(() => new Blob())
]);
// Convert font blobs to base64
const [solidFontBase64, brandsFontBase64, regularFontBase64] = await Promise.all([
blobToBase64(solidFontBlob).then((data) => data.split(',')[1]),
blobToBase64(brandsFontBlob).then((data) => data.split(',')[1]),
blobToBase64(regularFontBlob).then((data) => data.split(',')[1])
]);
// Create font-face definitions for all Font Awesome types
const fontFaceCSS = `
@font-face {
font-family: 'Font Awesome 6 Free';
font-style: normal;
font-weight: 900;
src: url(data:font/woff2;base64,${solidFontBase64}) format('woff2');
}
@font-face {
font-family: 'Font Awesome 6 Free';
font-style: normal;
font-weight: 400;
src: url(data:font/woff2;base64,${regularFontBase64}) format('woff2');
}
@font-face {
font-family: 'Font Awesome 6 Brands';
font-style: normal;
font-weight: 400;
src: url(data:font/woff2;base64,${brandsFontBase64}) format('woff2');
}
.fa, .fas {
font-family: 'Font Awesome 6 Free';
font-weight: 900;
}
.far {
font-family: 'Font Awesome 6 Free';
font-weight: 400;
}
.fab {
font-family: 'Font Awesome 6 Brands';
font-weight: 400;
}
.fa, .fas, .far, .fab {
font-size: 16px;
width: 16px;
fill: currentColor;
}
`;
// Fix self-closing tags for XML compatibility
const svgString = svg.outerHTML
.replaceAll('<br>', '<br/>')
.replaceAll(/<img([^>]*)>/g, (m, g: string) => `<img ${g} />`)
.replace('<style>', `<style>${fontFaceCSS} ${fontAwesomeCSS}`);
return toBase64(svgString);
} catch {
// Fallback to simple SVG if font loading fails
const svgString = svg.outerHTML
.replaceAll('<br>', '<br/>')
.replaceAll(/<img([^>]*)>/g, (m, g: string) => `<img ${g} />`);
return toBase64(svgString);
if ($stateStore.rough) {
fixForeignObjectClipping(svg);
}
svg.style.backgroundColor = window
.getComputedStyle(document.body)
.getPropertyValue('--background');
const svgString = svg.outerHTML
.replaceAll('<br>', '<br/>')
.replaceAll(/<img([^>]*)>/g, (m, g: string) => `<img ${g} />`);
return toBase64(`<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="${FONT_AWESOME_URL}" type="text/css"?>
${svgString}`);
};
const simulateDownload = (download: string, href: string): void => {
@@ -164,18 +117,25 @@
const box = svg.getBoundingClientRect();
// In rough mode, SVG has width/height="100%" so getBoundingClientRect returns
// the container size, not the actual diagram size. Use viewBox dimensions instead.
const svgEl = svg as unknown as SVGSVGElement;
const viewBox = svgEl.viewBox?.baseVal;
const contentWidth = viewBox && viewBox.width > 0 ? viewBox.width : box.width;
const contentHeight = viewBox && viewBox.height > 0 ? viewBox.height : box.height;
if (imageSizeMode === 'width') {
const ratio = box.height / box.width;
const ratio = contentHeight / contentWidth;
canvas.width = imageSize;
canvas.height = imageSize * ratio;
} else if (imageSizeMode === 'height') {
const ratio = box.width / box.height;
const ratio = contentWidth / contentHeight;
canvas.width = imageSize * ratio;
canvas.height = imageSize;
} else {
const multiplier = 2;
canvas.width = box.width * multiplier;
canvas.height = box.height * multiplier;
canvas.width = contentWidth * multiplier;
canvas.height = contentHeight * multiplier;
}
const context = canvas.getContext('2d');
@@ -183,7 +143,7 @@
throw new Error('context not found');
}
context.fillStyle = `hsl(${window.getComputedStyle(document.body).getPropertyValue('--background')})`;
context.fillStyle = window.getComputedStyle(document.body).getPropertyValue('--background');
context.fillRect(0, 0, canvas.width, canvas.height);
const image = new Image();
@@ -191,7 +151,7 @@
exporter(context, image)();
$inputStateStore.panZoom = true;
});
image.src = `data:image/svg+xml;base64,${await getBase64SVG(svg, canvas.width, canvas.height)}`;
image.src = `data:image/svg+xml;base64,${getBase64SVG(svg, canvas.width, canvas.height)}`;
// Fallback to set panZoom to true after 2 seconds
// This is a workaround for the case when the image is not loaded
setTimeout(() => {
@@ -251,8 +211,8 @@
});
};
const onDownloadSVG = async () => {
simulateDownload(getFileName('svg'), `data:image/svg+xml;base64,${await getBase64SVG()}`);
const onDownloadSVG = () => {
simulateDownload(getFileName('svg'), `data:image/svg+xml;base64,${getBase64SVG()}`);
logEvent('download', {
type: 'svg'
});
@@ -295,17 +255,17 @@
<DownloadIcon />
{text}
</Button>
{#if url}
<ExternalLinkWrapper domain={getDomain(url)} isVisible={!!url}>
<Button class="rounded-l-none" href={url} target="_blank" rel="noreferrer noopener">
<ExternalLinkIcon />
</Button>
{/if}
</ExternalLinkWrapper>
</div>
{/snippet}
<Card title="Actions" isStackable icon={{ component: DownloadIcon, class: 'rotate-180' }}>
<div class="flex min-w-fit flex-col gap-2 p-2">
<div class="flex w-full items-center gap-2 whitespace-nowrap py-2">
<div class="flex w-full items-center gap-2 py-2 whitespace-nowrap">
PNG size
<ToggleGroup.Root type="single" variant="outline" bind:value={imageSizeMode}>
<ToggleGroup.Item value="auto">Auto</ToggleGroup.Item>
@@ -326,22 +286,24 @@
<div class="flex gap-2">
{@render dualActionButton('PNG', onDownloadPNG, $urlsStore.png)}
{@render dualActionButton('SVG', onDownloadSVG, $urlsStore.svg)}
{#if env.krokiRendererUrl}
<ExternalLinkWrapper domain={getDomain($urlsStore.kroki)} isVisible={!!$urlsStore.kroki}>
<a target="_blank" rel="noreferrer" class="flex-grow" href={$urlsStore.kroki}>
<Button class="action-btn flex w-full items-center gap-2">
<ExternalLinkIcon /> Kroki
</Button>
</a>
{/if}
</ExternalLinkWrapper>
</div>
<Separator />
{#if isClipboardAvailable()}
<CopyButton onclick={onCopyClipboard} label="Copy Image" />
{/if}
{#if $urlsStore.mdCode}
<ExternalLinkWrapper
labelPrefix="Thumbnail generated by"
domain={getDomain($urlsStore.png)}
isVisible={!!$urlsStore.mdCode}>
<CopyInput value={$urlsStore.mdCode} label="Copy Markdown" testID={TID.copyMarkdown} />
{/if}
</ExternalLinkWrapper>
<div class="flex w-full items-center gap-2">
<Input type="url" bind:value={gistURL} placeholder="Enter Gist URL" />
<Button onclick={loadGist}>Load Gist</Button>
+1 -1
View File
@@ -54,7 +54,7 @@
role="toolbar"
tabindex="0"
class={[
'flex h-11 flex-none cursor-pointer items-center justify-between whitespace-nowrap bg-muted p-2',
'flex h-11 flex-none cursor-pointer items-center justify-between bg-muted p-2 whitespace-nowrap',
isTabsShown && 'pb-1'
]}
onclick={toggleCardOpen}
+1 -1
View File
@@ -28,7 +28,7 @@
<div class="flex w-fit cursor-default items-center gap-2">
<ul class="flex gap-2 align-middle" transition:fade>
{#each tabs as tab, index}
{#each tabs as tab, index (tab.id)}
<Button
role="tab"
variant="ghost"
+1 -2
View File
@@ -1,6 +1,5 @@
<script lang="ts">
import { Button } from '$/components/ui/button';
import type { InputType } from '$/types';
import { notify } from '$/util/notify';
import { scale } from 'svelte/transition';
import CheckIcon from '~icons/material-symbols/check-rounded';
@@ -9,7 +8,7 @@
let {
onclick,
label = 'Copy'
}: { onclick: (event?: Event) => Promise<unknown>; label?: string; type?: InputType } = $props();
}: { onclick: (event?: Event) => Promise<unknown>; label?: string } = $props();
let showCheckIcon = $state(false);
</script>
+138 -5
View File
@@ -1,6 +1,9 @@
<script lang="ts">
import type { EditorProps } from '$/types';
import { stateStore } from '$/util/state';
import { env } from '$/util/env';
import { stateStore, urlsStore } from '$/util/state';
import { logMermaidChartClick } from '$/util/stats';
import { AIPromptViewZoneManager } from '$lib/util/AIPromptViewZoneManager';
import { initEditor } from '$lib/util/monacoExtra';
import { errorDebug } from '$lib/util/util';
import { mode } from 'mode-watcher';
@@ -8,18 +11,28 @@
import monacoEditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
import monacoJsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
import { onMount } from 'svelte';
import AIPromptPopup from './AIPromptPopup.svelte';
const { onUpdate }: EditorProps = $props();
let divElement: HTMLDivElement | undefined = $state();
let aiPromptPopupElement: HTMLDivElement | undefined = $state();
let editor: monaco.editor.IStandaloneCodeEditor | undefined;
let editorOptions = {
minimap: {
enabled: false
},
overviewRulerLanes: 0
overviewRulerLanes: 0,
glyphMargin: true,
lineNumbersMinChars: 4
} satisfies monaco.editor.IStandaloneEditorConstructionOptions;
let currentText = '';
let showPopup = $state(false);
let popupPosition = $state({ top: 0, lineNumber: 0 });
let decorationsCollection: monaco.editor.IEditorDecorationsCollection | undefined;
let input = $state('');
let lastMouseLine = 0;
const aiPromptManager = new AIPromptViewZoneManager();
const jsonModel = monaco.editor.createModel(
'',
@@ -32,6 +45,51 @@
monaco.Uri.parse('internal://mermaid.mmd')
);
const renderAIPromptGutterGlyphIcon = () => {
decorationsCollection?.clear();
if (!editor || showPopup) {
return;
}
const model = editor.getModel();
if (!model) {
return;
}
if (lastMouseLine > 0 && model.id === mermaidModel.id) {
decorationsCollection?.set([
{
range: new monaco.Range(lastMouseLine, 1, lastMouseLine, 1),
options: {
glyphMarginClassName: 'suggestion-icon'
}
}
]);
}
};
const closePopup = () => {
showPopup = false;
input = '';
aiPromptManager.hide();
renderAIPromptGutterGlyphIcon();
};
const toggleAIPopup = (lineNumber: number) => {
if (!divElement || !aiPromptPopupElement) return;
popupPosition = {
top: 0,
lineNumber
};
showPopup = !showPopup;
if (showPopup) {
aiPromptManager.show(popupPosition.lineNumber, aiPromptPopupElement, 100);
editor?.setSelection(new monaco.Range(0, 0, 0, 0));
} else {
aiPromptManager.hide();
}
renderAIPromptGutterGlyphIcon();
};
onMount(() => {
self.MonacoEnvironment = {
getWorker(_, label) {
@@ -52,7 +110,7 @@
schemas: [
{
fileMatch: ['config.json'],
uri: 'https://mermaid.js.org/schemas/config.schema.json'
uri: `${env.docsUrl}/schemas/config.schema.json`
}
]
});
@@ -60,6 +118,18 @@
initEditor(monaco);
errorDebug();
editor = monaco.editor.create(divElement, editorOptions);
aiPromptManager.setEditor(editor);
decorationsCollection = editor.createDecorationsCollection([]);
editor.onMouseDown((e) => {
const isGutter = e.target.type === monaco.editor.MouseTargetType.GUTTER_GLYPH_MARGIN;
if (isGutter && e.target.position?.lineNumber === lastMouseLine && lastMouseLine > 0) {
e.event.preventDefault();
e.event.stopPropagation();
toggleAIPopup(e.target.position.lineNumber);
}
});
editor.onDidChangeModelContent(({ isFlush }) => {
const newText = editor?.getValue();
if (!newText || currentText === newText || isFlush) {
@@ -78,6 +148,12 @@
if (editor.getModel()?.id !== model.id) {
editor.setModel(model);
renderAIPromptGutterGlyphIcon();
}
// Clear decorations if not in 'code' mode, or if the model changes
if (editorMode !== 'code' || editor.getModel()?.id !== mermaidModel.id) {
decorationsCollection?.clear();
}
// Update editor text if it's different
@@ -86,14 +162,32 @@
editor.setScrollTop(0);
editor.setValue(newText);
currentText = newText;
renderAIPromptGutterGlyphIcon();
}
// Display/clear errors
monaco.editor.setModelMarkers(model, 'mermaid', errorMarkers);
});
editor.onMouseMove((e) => {
if (!editor) return;
if (showPopup) return;
if (editor.getModel()?.id !== mermaidModel.id) return;
lastMouseLine = e.target.position?.lineNumber ?? 0;
renderAIPromptGutterGlyphIcon();
});
editor.onMouseLeave(() => {
lastMouseLine = 0;
renderAIPromptGutterGlyphIcon();
});
const unsubscribeMode = mode.subscribe((mode) => {
editor && monaco.editor.setTheme(`mermaid${mode === 'dark' ? '-dark' : ''}`);
if (editor) {
monaco.editor.setTheme(`mermaid${mode === 'dark' ? '-dark' : ''}`);
divElement?.classList.toggle('mermaid-dark', mode === 'dark');
}
});
const resizeObserver = new ResizeObserver((entries) => {
editor?.layout({
@@ -106,13 +200,52 @@
resizeObserver.observe(divElement);
}
renderAIPromptGutterGlyphIcon();
return () => {
unsubscribeState();
unsubscribeMode();
resizeObserver.disconnect();
jsonModel.dispose();
mermaidModel.dispose();
aiPromptManager.destroy();
editor?.dispose();
};
});
</script>
<div bind:this={divElement} id="editor" class="h-full flex-grow overflow-hidden"></div>
<div class="relative h-full grow overflow-hidden">
<div bind:this={divElement} id="editor" class="h-full w-full"></div>
<div bind:this={aiPromptPopupElement}>
<AIPromptPopup
show={showPopup}
bind:input
onHeightChange={(height) => aiPromptManager.updateHeight(height)}
onClose={closePopup}
onTryFree={() => {
logMermaidChartClick('vibeDiagramming');
window.open($urlsStore.mermaidChart({ medium: 'vibe_diagramming' }).save, '_blank');
closePopup();
}} />
</div>
</div>
<style>
:global(.suggestion-icon) {
background-color: #e8eaf9;
width: 20px !important;
height: 20px !important;
margin-left: 4px;
background-image: url('/icons/use-chat.svg');
background-size: 16px 16px;
background-repeat: no-repeat;
background-position: center;
border-radius: 4px;
cursor: pointer;
}
:global(#editor.mermaid-dark .suggestion-icon) {
background-color: #2e4d6b;
background-image: url('/icons/use-chat-dark.svg');
}
</style>
@@ -2,11 +2,12 @@
import { Button } from '$/components/ui/button';
import { TID } from '$/constants';
import type { DocumentationConfig } from '$/types';
import { env } from '$/util/env';
import { standardizeDiagramType } from '$/util/mermaid';
import { stateStore } from '$/util/state';
import BookIcon from '~icons/material-symbols/book-2-outline-rounded';
const docURLBase = 'https://mermaid.js.org';
const docURLBase = env.docsUrl;
const docMap = {
architecture: {
code: '/syntax/architecture.html'
@@ -77,6 +78,10 @@
code: '/syntax/timeline.html',
config: '/syntax/timeline.html#themes'
},
treemap: {
code: '/syntax/treemap.html',
config: '/syntax/treemap.html#configuration-options'
},
xychart: {
code: '/syntax/xyChart.html',
config: '/syntax/xyChart.html#chart-configurations'
+1 -1
View File
@@ -21,7 +21,7 @@
<Popover.Content>
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<ul tabindex="0" class="flex flex-col">
{#each props.links as { href, title }}
{#each props.links as { href, title } (title)}
<li class="rounded-md p-2 hover:bg-muted">
<a
role="menuitem"
+41 -13
View File
@@ -7,9 +7,11 @@
import { TID } from '$/constants';
import { env } from '$/util/env';
import { stateStore, updateCode, updateConfig, urlsStore } from '$lib/util/state';
import { logMermaidChartClick } from '$lib/util/stats';
import { debounce } from 'lodash-es';
import ExclamationCircleIcon from '~icons/material-symbols/error-outline-rounded';
let { isMobile }: { isMobile: boolean } = $props();
const { isMobile } = $props<{ isMobile: boolean }>();
const onUpdate = (text: string) => {
if ($stateStore.editorMode === 'code') {
updateCode(text);
@@ -17,6 +19,25 @@
updateConfig(text);
}
};
let showError = $state(false);
const showErrorDebounced = debounce(() => {
showError = true;
}, 3000);
$effect(() => {
if ($stateStore.error) {
showErrorDebounced();
} else {
showErrorDebounced.cancel();
showError = false;
}
return () => {
showErrorDebounced.cancel();
};
});
</script>
<div class="flex h-full flex-col">
@@ -25,27 +46,34 @@
{:else}
<DesktopEditor {onUpdate} />
{/if}
{#if $stateStore.error instanceof Error}
{#if showError && $stateStore.error instanceof Error}
<div class="flex flex-col text-sm" data-testid={TID.errorContainer}>
<div class="flex items-center justify-between gap-2 bg-slate-900 p-2 text-white">
<div class="flex w-fit items-center gap-2">
<ExclamationCircleIcon class="size-6 text-destructive" aria-hidden="true" />
<div class="flex flex-col">
<p>Syntax error</p>
{#if env.isEnabledMermaidChartLinks}
<p class="text-xs text-white/60">Create a free account to repair with AI</p>
{#if env.isEnabledMermaidChartLinks && $stateStore.editorMode === 'code'}
<p class="text-xs text-white/60" data-testid={TID.aiHelpText}>
Create a free account to repair with AI
</p>
{/if}
</div>
</div>
<McWrapper>
<Button
variant="accent"
size="sm"
href={$urlsStore.mermaidChart({ medium: 'ai_repair' }).save}>
<MermaidChartIcon />
AI Repair
</Button>
</McWrapper>
{#if $stateStore.editorMode === 'code'}
<McWrapper>
<Button
variant="accent"
size="sm"
data-testid={TID.aiRepairButton}
href={$urlsStore.mermaidChart({ medium: 'ai_repair' }).save}
target="_blank"
onclick={() => logMermaidChartClick('aiRepair')}>
<MermaidChartIcon />
AI Repair
</Button>
</McWrapper>
{/if}
</div>
<output class="max-h-32 overflow-auto bg-muted p-2" name="mermaid-error" for="editor">
<pre>{$stateStore.error?.toString()}</pre>
@@ -0,0 +1,118 @@
<script lang="ts">
import McWrapper from '$/components/McWrapper.svelte';
import MermaidChartIcon from '$/components/MermaidChartIcon.svelte';
import { Button } from '$/components/ui/button';
import { standardizeDiagramType } from '$/util/mermaid';
import { stateStore, urlsStore } from '$/util/state';
import { logMermaidChartClick } from '$/util/stats';
import { quintInOut } from 'svelte/easing';
import { slide } from 'svelte/transition';
const visualEditDiagramTypes = new Set([
'flowchart',
'stateDiagram',
'classDiagram',
'sequenceDiagram',
'er',
'requirement',
'mindmap'
]);
const diagramType = $derived.by(() => {
const dt = $stateStore.diagramType;
return dt ? standardizeDiagramType(dt) : undefined;
});
const showVisualEdit = $derived.by(() => {
return diagramType ? visualEditDiagramTypes.has(diagramType) : false;
});
interface EnhancedEditAction {
campaign: string;
label: string;
medium: 'ai_edit' | 'visual_edit' | 'voice_edit';
source: string;
}
let currentActionMedium = $state<EnhancedEditAction['medium'] | undefined>(undefined);
let previousDiagramType = $state<string | undefined>(undefined);
const availableActions = $derived.by<EnhancedEditAction[]>(() => {
if (!$stateStore.diagramType) {
return [];
}
const actions: EnhancedEditAction[] = [
{ campaign: 'ai_1', label: 'with AI', medium: 'ai_edit', source: 'aiEdit' },
{ campaign: 'voice_1', label: 'with Voice', medium: 'voice_edit', source: 'voiceEdit' }
];
if (showVisualEdit) {
actions.unshift({
campaign: 'visual_1',
label: 'Visually',
medium: 'visual_edit',
source: 'visualEdit'
});
}
return actions;
});
const currentAction = $derived.by(() => {
const actions = availableActions;
if (actions.length === 0) {
return undefined;
}
return actions.find(({ medium }) => medium === currentActionMedium) ?? actions[0];
});
$effect(() => {
const actions = availableActions;
if (!diagramType || actions.length === 0) {
return;
}
const hasCurrentAction = actions.some(({ medium }) => medium === currentActionMedium);
if (diagramType !== previousDiagramType || !hasCurrentAction) {
currentActionMedium = actions[Math.floor(Math.random() * actions.length)].medium;
previousDiagramType = diagramType;
}
});
$effect(() => {
if (diagramType) {
return;
}
previousDiagramType = undefined;
});
</script>
{#if currentAction}
<McWrapper>
<Button
variant="secondary"
size="sm"
href={$urlsStore.mermaidChart({
medium: currentAction.medium,
campaign: currentAction.campaign
}).save}
target="_blank"
onclick={() => logMermaidChartClick(currentAction.source)}>
<MermaidChartIcon />
Edit
{#key currentAction.label}
<span
class="-ml-1"
in:slide={{ axis: 'x', easing: quintInOut, delay: 400 }}
out:slide={{ axis: 'x', easing: quintInOut }}>
{currentAction.label}
</span>
{/key}
</Button>
</McWrapper>
{/if}
@@ -0,0 +1,63 @@
<script lang="ts">
import { stateStore } from '$/util/state';
import * as Tooltip from '$lib/components/ui/tooltip';
import type { ComponentProps, Snippet } from 'svelte';
import ExternalLinkIcon from '~icons/material-symbols/open-in-new-rounded';
let {
children,
domain,
shouldCheckDiagramType = true,
side = 'bottom',
labelPrefix = 'Opens your diagram in',
isVisible = true,
sharesData = true,
showPopup = true
}: {
children: Snippet;
domain: string;
shouldCheckDiagramType?: boolean;
side?: ComponentProps<typeof Tooltip.Content>['side'];
labelPrefix?: string;
isVisible?: boolean;
sharesData?: boolean;
showPopup?: boolean;
} = $props();
let shouldDisableComponent = $derived(
shouldCheckDiagramType && $stateStore.diagramType === 'zenuml'
);
</script>
{#if isVisible}
<Tooltip.Provider>
<Tooltip.Root delayDuration={100}>
<Tooltip.Trigger>
<div class={[shouldDisableComponent && 'pointer-events-none cursor-not-allowed grayscale']}>
{@render children()}
</div>
</Tooltip.Trigger>
{#if showPopup}
<Tooltip.Content {side} class="bg-secondary shadow-xl">
<div
class="flex cursor-help items-center gap-2"
title={sharesData
? 'Your diagram will be sent to the external service'
: 'Your diagram is not shared'}>
{#if shouldDisableComponent}
<div class="text-muted-foreground">
This diagram type is not supported in {domain}
</div>
{:else}
<ExternalLinkIcon />
<span class="flex items-center gap-1">
{labelPrefix}
<div class="text-accent">{domain}</div>
</span>
{/if}
</div>
</Tooltip.Content>
{/if}
</Tooltip.Root>
</Tooltip.Provider>
{/if}
-1
View File
@@ -29,7 +29,6 @@
// Vite will automatically take care of adding this to our `<head>`
let lazyLoadFontAwesomeCSS = import('./FontAwesomeCSS.svelte');
// eslint-disable-next-line unicorn/prefer-top-level-await
let fontsLoaded = (async () => {
await lazyLoadFontAwesomeCSS;
+2 -2
View File
@@ -175,13 +175,13 @@
{:else}
<span class="whitespace-nowrap">{name}</span>
{/if}
<span class="whitespace-nowrap text-xs text-primary-foreground/30">
<span class="text-xs whitespace-nowrap text-primary-foreground/30">
{new Date(time).toLocaleString()}
</span>
</div>
<div class="flex items-center gap-2">
<span class="whitespace-nowrap text-sm text-primary-foreground/50">
<span class="text-sm whitespace-nowrap text-primary-foreground/50">
{dayjs(time).fromNow()}
</span>
<Button size="icon" variant="ghost" onclick={() => restoreHistoryItem(state)}>
+13 -14
View File
@@ -1,15 +1,14 @@
/* eslint-disable @typescript-eslint/no-unnecessary-condition */
import type { HistoryEntry } from '$lib/types';
import { describe, it, expect } from 'vitest';
import {
addHistoryEntry,
injectHistoryIDs,
clearHistoryData,
historyModeStore,
historyStore
} from './history';
import { defaultState } from '$lib/util/state';
import { get } from 'svelte/store';
import { describe, expect, it } from 'vitest';
import {
addHistoryEntry,
clearHistoryData,
historyModeStore,
historyStore,
injectHistoryIDs
} from './history';
describe('history', () => {
it('should handle saving individual history entry', () => {
@@ -105,11 +104,11 @@ describe('history migration', () => {
'[{"state":{"code":"graph TD\\n A[New Year] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":false},"time":0,"type":"auto","name":"barking-dog"},{"state":{"code":"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":true},"time":0,"type":"manual","name":"needy-mosquito"}]'
);
let manualHistoryStore = JSON.parse(
window.localStorage.getItem('manualHistoryStore') ?? '[]'
) as HistoryEntry[];
let autoHistoryStore = JSON.parse(
window.localStorage.getItem('autoHistoryStore') ?? '[]'
) as HistoryEntry[];
window.localStorage.getItem('manualHistoryStore') ?? '[]'
) as HistoryEntry[],
autoHistoryStore = JSON.parse(
window.localStorage.getItem('autoHistoryStore') ?? '[]'
) as HistoryEntry[];
expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(false);
expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(false);
-1
View File
@@ -147,6 +147,5 @@ export const injectHistoryIDs = (): void => {
const validateEntry = (entry: HistoryEntry): boolean => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
return entry.type && entry.state && entry.time && true;
};
+100 -44
View File
@@ -1,54 +1,102 @@
<script lang="ts">
import McWrapper from '$/components/McWrapper.svelte';
import ThemeIcon from '$/components/ThemeIcon.svelte';
import * as Popover from '$/components/ui/popover';
import { Switch } from '$/components/ui/switch';
import { env } from '$/util/env';
import { urlsStore } from '$/util/state';
import { logMermaidChartClick } from '$/util/stats';
import { cn } from '$/utils';
import { mode, setMode } from 'mode-watcher';
import type { Component } from 'svelte';
import type { Component, Snippet } from 'svelte';
import MermaidTailIcon from '~icons/custom/mermaid-tail';
import AddIcon from '~icons/material-symbols/add-2-rounded';
import BookIcon from '~icons/material-symbols/book-2-outline-rounded';
import PluginIcon from '~icons/material-symbols/extension-outline';
import HomeIcon from '~icons/material-symbols/house-outline-rounded';
import DuplicateIcon from '~icons/material-symbols/content-copy-outline-rounded';
import ContrastIcon from '~icons/material-symbols/contrast';
import PluginIcon from '~icons/material-symbols/electrical-services-rounded';
import MenuIcon from '~icons/material-symbols/menu-rounded';
import CommunityIcon from '~icons/material-symbols/person-play-outline-rounded';
import PlaygroundIcon from '~icons/material-symbols/shape-line-outline';
import MermaidChartIcon from './MermaidChartIcon.svelte';
const menuItems = $derived([
{ label: 'New Diagram', icon: AddIcon, href: $urlsStore.new },
{ label: 'Home', icon: HomeIcon, href: 'https://mermaid.js.org/' },
{ label: 'Documentation', icon: BookIcon, href: 'https://mermaid.js.org/intro/' },
{ label: 'Community', icon: CommunityIcon, href: 'https://discord.gg/sKeNQX4Wtj' }
]);
interface MenuItem {
label: string;
icon: Component;
href: string;
class?: string;
onclick?: () => void;
sharesData?: boolean;
checkDiagramType?: boolean;
isSectionEnd?: boolean;
renderer: (item: Omit<MenuItem, 'renderer'>) => ReturnType<Snippet>;
}
const mermaidChartMenuItems = $derived([
const menuItems: MenuItem[] = $derived([
{ label: 'New', icon: AddIcon, href: $urlsStore.new, renderer: menuItem },
{ label: 'Duplicate', icon: DuplicateIcon, href: window.location.href, renderer: menuItem },
{
label: 'Edit in Playground',
href: $urlsStore.mermaidChart({ medium: 'main_menu' }).playground,
icon: PlaygroundIcon,
href: $urlsStore.mermaidChart({ medium: 'main_menu' }).playground
isSectionEnd: true,
label: 'Edit in Playground',
onclick: () => logMermaidChartClick('editInPlayground'),
renderer: mcMenuItem
},
{
label: 'Plugins',
icon: PluginIcon,
label: 'Mermaid.js',
icon: MermaidTailIcon,
href: env.docsUrl,
renderer: menuItem
},
{
label: 'Documentation',
icon: BookIcon,
href: `${env.docsUrl}/intro/`,
renderer: menuItem
},
{
label: 'Community',
icon: CommunityIcon,
href: 'https://discord.gg/sKeNQX4Wtj',
renderer: menuItem
},
{
checkDiagramType: false,
href: $urlsStore.mermaidChart({ medium: 'main_menu' }).plugins,
checkDiagramType: false
icon: PluginIcon,
label: 'Plugins',
onclick: () => logMermaidChartClick('plugins'),
renderer: mcMenuItem,
sharesData: false
},
{
label: 'MermaidChart',
icon: MermaidChartIcon,
href: '#',
icon: ContrastIcon,
isSectionEnd: true,
label: 'Dark Mode',
renderer: darkModeMenuItem
},
{
checkDiagramType: false,
class: 'text-accent border-b-0',
href: $urlsStore.mermaidChart({ medium: 'main_menu' }).home,
checkDiagramType: false
icon: MermaidChartIcon,
label: 'Mermaid',
onclick: () => logMermaidChartClick('mermaidHome'),
renderer: mcMenuItem,
sharesData: false
}
]);
</script>
{#snippet menuItem(options: { label: string; icon: Component; href: string; class?: string })}
{#snippet menuItem(options: MenuItem)}
<a
href={options.href}
target="_blank"
onclick={options.onclick}
class={cn(
'flex items-center justify-start gap-2 border-b bg-muted p-2 px-3 hover:bg-background',
'flex items-center justify-start gap-2 border-b-2 p-2 px-3 hover:bg-muted',
options.isSectionEnd && 'border-border-dark',
options.class
)}>
<options.icon class="size-5" />
@@ -56,32 +104,40 @@
</a>
{/snippet}
{#snippet mcMenuItem(item: MenuItem)}
<McWrapper
side="right"
labelPrefix={item.sharesData === false ? 'Opens a new tab in' : undefined}
sharesData={item.sharesData}
shouldCheckDiagramType={item.checkDiagramType}>
{@render menuItem(item)}
</McWrapper>
{/snippet}
{#snippet darkModeMenuItem(options: MenuItem)}
<div
class={cn(
'flex cursor-pointer items-center justify-between border-b-2 px-3 py-2 hover:bg-muted',
options.isSectionEnd && 'border-border-dark',
options.class
)}>
<span class="flex items-center gap-2">
<ContrastIcon />
Dark Mode
</span>
<Switch
checked={$mode === 'dark'}
onCheckedChange={(dark) => setMode(dark ? 'dark' : 'light')} />
</div>
{/snippet}
<Popover.Root>
<Popover.Trigger class="shrink-0">
<img class="size-6" src="/favicon.svg" alt="Mermaid Live Editor" />
<MenuIcon class="size-6" />
</Popover.Trigger>
<Popover.Content align="start" class="flex flex-col overflow-hidden p-0" sideOffset={16}>
{#each menuItems as item}
{@render menuItem(item)}
{/each}
<div class="flex items-center justify-between border-b bg-muted px-3 py-2 hover:bg-background">
<span class="flex items-center gap-2">
<ThemeIcon />
Dark Mode
</span>
<Switch
checked={$mode === 'dark'}
onCheckedChange={(dark) => setMode(dark ? 'dark' : 'light')} />
</div>
{#each mermaidChartMenuItems as item}
<McWrapper side="right" shouldCheckDiagramType={item.checkDiagramType}>
{@render menuItem({
...item,
class: 'text-accent bg-background hover:bg-muted'
})}
</McWrapper>
<Popover.Content align="start" class="flex flex-col overflow-hidden border-2 p-0" sideOffset={16}>
{#each menuItems as { renderer, ...item } (item.label)}
{@render renderer(item)}
{/each}
</Popover.Content>
</Popover.Root>
+16 -42
View File
@@ -1,50 +1,24 @@
<script lang="ts">
import { env } from '$/util/env';
import { stateStore } from '$/util/state';
import * as Tooltip from '$lib/components/ui/tooltip';
import type { ComponentProps, Snippet } from 'svelte';
import ExternalLinkIcon from '~icons/material-symbols/open-in-new-rounded';
import { isOnMermaidAI } from '$/util/migration/domainMigration';
import type { ComponentProps } from 'svelte';
import ExternalLinkWrapper from './ExternalLinkWrapper.svelte';
let {
children,
shouldCheckDiagramType = true,
side = 'bottom',
labelPrefix = 'Opens a new tab in'
}: {
children: Snippet;
shouldCheckDiagramType?: boolean;
side?: ComponentProps<typeof Tooltip.Content>['side'];
labelPrefix?: string;
} = $props();
...props
}: Omit<
ComponentProps<typeof ExternalLinkWrapper>,
'isVisible' | 'domain' | 'showPopup'
> = $props();
let shouldDisableComponent = $derived(
shouldCheckDiagramType && $stateStore.diagramType === 'zenuml'
);
const mermaidChartDomain = 'mermaid.ai';
</script>
{#if env.isEnabledMermaidChartLinks}
<Tooltip.Provider>
<Tooltip.Root delayDuration={100}>
<Tooltip.Trigger>
<div class={[shouldDisableComponent && 'pointer-events-none cursor-not-allowed grayscale']}>
{@render children()}
</div>
</Tooltip.Trigger>
<Tooltip.Content {side}>
<div class="flex items-center gap-2">
{#if shouldDisableComponent}
<div class="text-muted-foreground">
This diagram type is not supported in MermaidChart.com
</div>
{:else}
<ExternalLinkIcon />
<span class="flex items-center gap-1">
{labelPrefix}
<div class="text-accent">MermaidChart.com</div>
</span>
{/if}
</div>
</Tooltip.Content>
</Tooltip.Root>
</Tooltip.Provider>
{/if}
<ExternalLinkWrapper
{...props}
domain={mermaidChartDomain}
isVisible={env.isEnabledMermaidChartLinks}
showPopup={!isOnMermaidAI()}>
{@render children()}
</ExternalLinkWrapper>
+2 -1
View File
@@ -1,7 +1,8 @@
<script lang="ts">
import { asset } from '$app/paths';
import type { ClassValue } from 'svelte/elements';
let { class: className }: { class?: ClassValue } = $props();
</script>
<img class={['size-4', className]} src="/mermaidchart-logo.svg" alt="Mermaid Chart" />
<img class={['size-4', className]} src={asset('/mermaidchart-logo.svg')} alt="Mermaid Chart" />
+16 -52
View File
@@ -1,5 +1,5 @@
<script lang="ts" module>
import { logEvent, plausible } from '$lib/util/stats';
import { logEvent, logMermaidChartClick } from '$lib/util/stats';
import { version } from 'mermaid/package.json';
void logEvent('version', {
@@ -9,14 +9,11 @@
<script lang="ts">
import MainMenu from '$/components/MainMenu.svelte';
import McWrapper from '$/components/McWrapper.svelte';
import { Button } from '$/components/ui/button';
import { Separator } from '$/components/ui/separator';
import { Switch } from '$/components/ui/switch';
import { dismissPromotion, getActivePromotion } from '$lib/util/promos/promo';
import { urlsStore } from '$lib/util/state';
import { MCBaseURL } from '$lib/util/util';
import type { ComponentProps, Snippet } from 'svelte';
import MermaidIcon from '~icons/custom/mermaid';
import CloseIcon from '~icons/material-symbols/close-rounded';
import GithubIcon from '~icons/mdi/github';
import DropdownNavMenu from './DropdownNavMenu.svelte';
@@ -24,11 +21,10 @@
interface Props {
mobileToggle?: Snippet;
children: Snippet;
hidePromotion?: boolean;
}
let { children, mobileToggle }: Props = $props();
const isReferral = document.referrer.includes(MCBaseURL);
let { children, mobileToggle, hidePromotion = false }: Props = $props();
type Links = ComponentProps<typeof DropdownNavMenu>['links'];
@@ -44,22 +40,23 @@
}
];
let activePromotion = $state(getActivePromotion());
let activePromotion = $state(hidePromotion ? undefined : getActivePromotion());
const trackBannerClick = () => {
if (!plausible || !activePromotion) {
if (!activePromotion) {
return;
}
logEvent('bannerClick', {
promotion: activePromotion.id
});
logMermaidChartClick('banner');
};
</script>
{#if activePromotion}
<div class="top-bar z-10 flex h-fit w-full bg-primary">
<div
class="flex flex-grow"
class="flex grow"
role="button"
tabindex="0"
onclick={trackBannerClick}
@@ -83,48 +80,15 @@
{/if}
<nav class="z-50 flex p-4 sm:p-6">
<div class="flex flex-1 items-center gap-4">
<div class="flex flex-1 items-center gap-2">
<MainMenu />
<div
id="switcher"
class="flex items-center justify-center gap-4 font-medium"
class:flex-row-reverse={isReferral}>
<a href="/" class="whitespace-nowrap text-accent">
{#if !isReferral && !mobileToggle}
Mermaid
{/if}
Live Editor
</a>
<McWrapper labelPrefix="Opens the current diagram in">
<div class="hidden items-center justify-center gap-4 md:flex">
<Separator orientation="vertical" />
<Switch
id="editorMode"
class="data-[state=checked]:bg-secondary"
checked={isReferral}
onclick={() => {
logEvent('playgroundToggle', { isReferred: isReferral });
// Wait for the event to be logged
setTimeout(() => {
window.open(
$urlsStore.mermaidChart({ medium: 'toggle' }).playground,
'_self',
// Do not send referrer header, if the user already came from playground
isReferral ? 'noreferrer' : ''
);
}, 100);
}} />
<a
href={$urlsStore.mermaidChart({ medium: 'toggle' }).playground}
class="whitespace-nowrap">
Playground <span class="hidden text-sm opacity-50 lg:inline"
>- more features, no account required</span>
</a>
</div>
</McWrapper>
</div>
<MermaidIcon class="size-6" />
<a href="/" class="whitespace-nowrap text-accent">
{#if !mobileToggle}
Mermaid
{/if}
Live Editor
</a>
</div>
<div
id="menu"
+17 -178
View File
@@ -1,171 +1,12 @@
<script lang="ts">
import Card from '$/components/Card/Card.svelte';
import { Button } from '$/components/ui/button';
import { getSampleDiagrams } from '$/util/mermaid';
import { updateCode } from '$lib/util/state';
import { logEvent } from '$lib/util/stats';
import ShapesIcon from '~icons/material-symbols/account-tree-outline-rounded';
const samples = {
Block: `block-beta
columns 3
doc>"Document"]:3
space down1<[" "]>(down) space
block:e:3
l["left"]
m("A wide one in the middle")
r["right"]
end
space down2<[" "]>(down) space
db[("DB")]:3
space:3
D space C
db --> D
C --> db
D --> C
style m fill:#d6d,stroke:#333,stroke-width:4px
`,
Class: `classDiagram
Animal <|-- Duck
Animal <|-- Fish
Animal <|-- Zebra
Animal : +int age
Animal : +String gender
Animal: +isMammal()
Animal: +mate()
class Duck{
+String beakColor
+swim()
+quack()
}
class Fish{
-int sizeInFeet
-canEat()
}
class Zebra{
+bool is_wild
+run()
}`,
ER: `erDiagram
CUSTOMER }|..|{ DELIVERY-ADDRESS : has
CUSTOMER ||--o{ ORDER : places
CUSTOMER ||--o{ INVOICE : "liable for"
DELIVERY-ADDRESS ||--o{ ORDER : receives
INVOICE ||--|{ ORDER : covers
ORDER ||--|{ ORDER-ITEM : includes
PRODUCT-CATEGORY ||--|{ PRODUCT : contains
PRODUCT ||--o{ ORDER-ITEM : "ordered in"`,
Flow: `flowchart TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
C -->|One| D[Laptop]
C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car]`,
Gantt: `gantt
title A Gantt Diagram
dateFormat YYYY-MM-DD
section Section
A task :a1, 2014-01-01, 30d
Another task :after a1 , 20d
section Another
Task in sec :2014-01-12 , 12d
another task : 24d`,
Git: `gitGraph
commit
commit
branch develop
checkout develop
commit
commit
checkout main
merge develop
commit
commit`,
Mindmap: `mindmap
root((mindmap))
Origins
Long history
::icon(fa fa-book)
Popularisation
British popular psychology author Tony Buzan
Research
On effectiveness<br/>and features
On Automatic creation
Uses
Creative techniques
Strategic planning
Argument mapping
Tools
Pen and paper
Mermaid`,
Packet: `---
title: "TCP Packet"
---
packet-beta
0-15: "Source Port"
16-31: "Destination Port"
32-63: "Sequence Number"
64-95: "Acknowledgment Number"
96-99: "Data Offset"
100-105: "Reserved"
106: "URG"
107: "ACK"
108: "PSH"
109: "RST"
110: "SYN"
111: "FIN"
112-127: "Window"
128-143: "Checksum"
144-159: "Urgent Pointer"
160-191: "(Options and Padding)"
192-255: "Data (variable length)"
`,
Pie: `pie title Pets adopted by volunteers
"Dogs" : 386
"Cats" : 85
"Rats" : 15`,
QuadrantChart: `quadrantChart
title Reach and engagement of campaigns
x-axis Low Reach --> High Reach
y-axis Low Engagement --> High Engagement
quadrant-1 We should expand
quadrant-2 Need to promote
quadrant-3 Re-evaluate
quadrant-4 May be improved
Campaign A: [0.3, 0.6]
Campaign B: [0.45, 0.23]
Campaign C: [0.57, 0.69]
Campaign D: [0.78, 0.34]
Campaign E: [0.40, 0.34]
Campaign F: [0.35, 0.78]`,
Sequence: `sequenceDiagram
Alice->>+John: Hello John, how are you?
Alice->>+John: John, can you hear me?
John-->>-Alice: Hi Alice, I can hear you!
John-->>-Alice: I feel great!`,
State: `stateDiagram-v2
[*] --> Still
Still --> [*]
Still --> Moving
Moving --> Still
Moving --> Crash
Crash --> [*]`,
'User Journey': `journey
title My working day
section Go to work
Make tea: 5: Me
Go upstairs: 3: Me
Do work: 1: Me, Cat
section Go home
Go downstairs: 5: Me
Sit down: 3: Me`,
XYChart: `
xychart-beta
title "Sales Revenue"
x-axis [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
bar [5000, 6000, 7500, 8200, 9500, 10500, 11000, 10200, 9200, 8500, 7000, 6000]
line [5000, 6000, 7500, 8200, 9500, 10500, 11000, 10200, 9200, 8500, 7000, 6000]`,
const extras = {
ZenUML: `zenuml
title Order Service
@Actor Client #FFEBE6
@@ -192,8 +33,8 @@ packet-beta
`
};
type SampleTypes = keyof typeof samples;
const loadSampleDiagram = (diagramType: SampleTypes): void => {
const samples = { ...getSampleDiagrams(), ...extras } as const;
const loadSampleDiagram = (diagramType: string): void => {
updateCode(samples[diagramType], {
resetPanZoom: true,
updateDiagram: true
@@ -201,28 +42,26 @@ packet-beta
logEvent('loadSampleDiagram', { diagramType });
};
const diagramOrder: SampleTypes[] = [
'Flow',
'Sequence',
const mainDiagrams = [
'Flowchart',
'Class',
'Sequence',
'Entity Relationship',
'State',
'ER',
'Gantt',
'User Journey',
'Git',
'Pie',
'Mindmap',
'ZenUML',
'QuadrantChart',
'XYChart',
'Block',
'Packet'
'Mindmap'
];
const diagramOrder = [
...mainDiagrams,
...Object.keys(samples)
.filter((key) => !mainDiagrams.includes(key))
.sort()
];
</script>
<Card title="Sample Diagrams" isOpen isStackable icon={{ component: ShapesIcon }}>
<div class="flex h-fit max-h-52 flex-wrap gap-2 overflow-y-auto p-2">
{#each diagramOrder as sample}
{#each diagramOrder as sample (sample)}
<Button
size="sm"
class="w-fit min-w-20 flex-grow normal-case"
+59 -46
View File
@@ -1,53 +1,66 @@
<script>
import ExternalLinkWrapper from '$/components/ExternalLinkWrapper.svelte';
import * as Dialog from '$/components/ui/dialog';
import { env } from '$/util/env';
import { isOnMermaidLive } from '$/util/migration/domainMigration';
import ShieldIcon from '~icons/material-symbols/shield-lock-outline-rounded';
</script>
<Dialog.Root>
<Dialog.Trigger>
{#if env.privacyPolicyUrl}
<a href={env.privacyPolicyUrl} target="_blank">
<ShieldIcon />
</Dialog.Trigger>
<Dialog.Content class="max-h-full overflow-y-auto">
<Dialog.Header>
<Dialog.Title class="flex items-center gap-2 text-xl">
<ShieldIcon class="size-8 text-green-700" />
Data security
</Dialog.Title>
</Dialog.Header>
</a>
{:else}
<Dialog.Root>
<Dialog.Trigger>
<ShieldIcon />
</Dialog.Trigger>
<Dialog.Content class="max-h-full overflow-hidden overflow-y-auto p-12">
<Dialog.Header>
<Dialog.Title class="flex items-center gap-2 text-xl">
<ShieldIcon class="size-8 text-green-700" />
Data security
</Dialog.Title>
</Dialog.Header>
<p class="text-xl font-semibold">
The content of the diagrams you create never leaves your browser.
</p>
<p>It's only stored in the URL, and your browser's local storage.</p>
<p>
Mermaid Live Editor is a fully open source, client side application, deployed transparently on <a
href="https://github.com/mermaid-js/mermaid-live-editor/deployments"
class="underline"
target="_blank">
GitHub Pages
</a>.
</p>
<p>
It will also work as a fully offline
<a href="https://web.dev/explore/progressive-web-apps" target="_blank">
Progressive Web App.
</a>
</p>
<p>
The only server we have is a self hosted version of the open source and privacy friendly
Plausible Analytics. We only collect anonymous data related to actions performed, like the
type of diagram rendered, number of times a feature was used, etc.
</p>
<p>
All the data we collect is anonymized and
<a href="https://p.mermaid.live/mermaid.live" class="underline" target="_blank">
available publicly.
</a>
</p>
<p>
Additional services like the external PNG/SVG/Kroki links and "Save to Mermaid Chart" feature
will share your diagram with the respective 3rd party service.
</p>
</Dialog.Content>
</Dialog.Root>
{#if isOnMermaidLive()}
<p class="text-xl font-semibold">Your diagrams never leave your browser.</p>
<p>They're only stored in the URL and your browser's local storage.</p>
<p>
This is a fully open source, client-side app deployed on <a
href="https://github.com/mermaid-js/mermaid-live-editor/deployments"
class="underline"
target="_blank">GitHub Pages</a>
that works offline as a
<a href="https://web.dev/explore/progressive-web-apps" target="_blank"
>Progressive Web App</a
>.
</p>
<p>
We use self hosted, privacy-friendly Plausible Analytics to collect anonymous usage
metadata (diagram types, feature usage, etc.). All data is <a
href="https://p.mermaid.live/mermaid.live"
class="underline"
target="_blank">publicly available</a
>.
</p>
<ExternalLinkWrapper domain="example.com" isVisible>
<p class="text-left">
External services (PNG/SVG/Kroki exports, "Save to Mermaid Chart", "Repair with AI",
etc) will share your diagram with those 3rd parties, and are highlighted in the UI on
hover.
</p>
</ExternalLinkWrapper>
{:else}
<p>No privacy policy has been configured for this deployment.</p>
<p>
If you are self-hosting the Mermaid Live Editor, set the
<code class="rounded bg-muted px-1.5 py-0.5 text-sm">MERMAID_PRIVACY_POLICY_URL</code>
environment variable at build time to link to your privacy policy, or set
<code class="rounded bg-muted px-1.5 py-0.5 text-sm">MERMAID_HIDE_PRIVACY_POLICY</code>
to <code class="rounded bg-muted px-1.5 py-0.5 text-sm">true</code> to hide this button.
</p>
{/if}
</Dialog.Content>
</Dialog.Root>
{/if}
+2 -1
View File
@@ -4,6 +4,7 @@
import { Separator } from '$/components/ui/separator';
import { env } from '$/util/env';
import { urlsStore } from '$/util/state';
import { asset } from '$app/paths';
import ShareIcon from '~icons/material-symbols/share';
import CopyInput from './CopyInput.svelte';
import MermaidChartIcon from './MermaidChartIcon.svelte';
@@ -22,7 +23,7 @@
<div class="flex flex-col gap-4">
<div class="flex flex-col gap-2">
<h2 class="flex items-center gap-2">
<img class="size-5" src="/favicon.svg" alt="Mermaid Live Editor" />
<img class="size-5" src={asset('/favicon.svg')} alt="Mermaid Live Editor" />
Mermaid Live Editor
</h2>
<CopyInput value={window.location.href} />
@@ -4,6 +4,7 @@
import { Button } from '$/components/ui/button';
import { Separator } from '$/components/ui/separator';
import { TID } from '$/constants';
import { env } from '$/util/env';
import { version } from 'mermaid/package.json';
import { mode, setMode } from 'mode-watcher';
import ThemeIcon from './ThemeIcon.svelte';
@@ -11,11 +12,13 @@
<FloatingToolbar>
<span class="text-sm font-semibold opacity-60">v{version}</span>
<Button variant="ghost" size="icon" title="Privacy & Security">
<Privacy />
</Button>
{#if !env.hidePrivacyPolicy}
<Button variant="ghost" size="icon" title="Privacy & Security">
<Privacy />
</Button>
<Separator orientation="vertical" />
<Separator orientation="vertical" />
{/if}
<Button
variant="ghost"
size="icon"
+8 -3
View File
@@ -4,7 +4,7 @@
import { render as renderDiagram } from '$/util/mermaid';
import { PanZoomState } from '$/util/panZoom';
import { inputStateStore, stateStore, updateCodeStore } from '$/util/state';
import { logEvent, saveStatistics } from '$/util/stats';
import { saveStatistics } from '$/util/stats';
import FontAwesome, { mayContainFontAwesome } from '$lib/components/FontAwesome.svelte';
import uniqueID from 'lodash-es/uniqueId';
import type { MermaidConfig } from 'mermaid';
@@ -30,12 +30,15 @@
const setupPanZoomObserver = () => {
panZoomState.onPanZoomChange = (pan, zoom) => {
updateCodeStore({ pan, zoom });
logEvent('panZoom');
};
};
const handlePanZoom = (state: State, graphDiv: SVGSVGElement) => {
panZoomState.updateElement(graphDiv, state);
try {
panZoomState.updateElement(graphDiv, state);
} catch (error) {
console.error('PanZoom error:', error);
}
};
const handleStateChange = async (state: ValidatedState) => {
@@ -82,6 +85,7 @@
} = await renderDiagram(JSON.parse(state.mermaid) as MermaidConfig, code, viewID);
diagramType = detectedDiagramType;
if (svg.length > 0) {
// eslint-disable-next-line svelte/no-dom-manipulating
container.innerHTML = svg;
let graphDiv = document.querySelector<SVGSVGElement>(`#${viewID}`);
if (!graphDiv) {
@@ -138,6 +142,7 @@
// Queue state changes to avoid race condition
let pendingStateChange = Promise.resolve();
stateStore.subscribe((state) => {
// eslint-disable-next-line @typescript-eslint/no-empty-function
pendingStateChange = pendingStateChange.then(() => handleStateChange(state).catch(() => {}));
});
});
@@ -0,0 +1,164 @@
<script lang="ts">
import { Button } from '$/components/ui/button';
import * as Dialog from '$/components/ui/dialog';
import { dismissEditorChooser } from '$/util/migration/domainMigration';
import { logEvent, logMermaidChartClick } from '$/util/stats';
import { getCheckoutUrl } from '$/util/util';
import CodeIcon from '~icons/custom/code';
import ArrowIcon from '~icons/material-symbols/arrow-forward-rounded';
import OpenSourceIcon from '~icons/material-symbols/book-2-outline-rounded';
import ChatIcon from '~icons/material-symbols/chat-outline-rounded';
import EditIcon from '~icons/material-symbols/edit-outline-rounded';
import HistoryIcon from '~icons/material-symbols/history';
import HomeIcon from '~icons/material-symbols/home-storage-outline-rounded';
import SparklesIcon from '~icons/material-symbols/kid-star-outline';
import LanguageIcon from '~icons/material-symbols/language';
import WidthIcon from '~icons/material-symbols/width-rounded';
interface Props {
open: boolean;
}
let { open = $bindable() }: Props = $props();
const close = () => {
dismissEditorChooser();
open = false;
};
const handleStartTrial = () => {
logEvent('chooseEditor', { choice: 'plus' });
logMermaidChartClick('editorPicker');
close();
window.open(
getCheckoutUrl({ utmCampaign: 'start_plus', utmMedium: '2_editor_selection' }),
'_blank'
);
};
const handleStartFree = () => {
logEvent('chooseEditor', { choice: 'openSource' });
close();
};
const handleContinueToNewHome = () => {
logEvent('chooseEditor', { choice: 'newHome' });
close();
window.open('https://mermaid.ai/live', '_blank');
};
</script>
<Dialog.Root
bind:open
onOpenChange={(v) => {
if (!v) handleStartFree();
}}>
<Dialog.Content class="flex max-w-2xl flex-col gap-6 bg-pink-50 p-6 dark:bg-background">
<Dialog.Header>
<Dialog.Title class="text-center text-2xl font-semibold">Choose your editor</Dialog.Title>
<Dialog.Description class="text-center text-sm font-light">
You'll never see this again
</Dialog.Description>
</Dialog.Header>
<div class="grid gap-4 sm:grid-cols-2">
<!-- Mermaid Plus Card -->
<div
class="relative flex flex-col overflow-hidden rounded-xl border-2 border-accent bg-white shadow dark:bg-card">
<div class="bg-accent px-6 py-2 text-center text-sm font-semibold text-accent-foreground">
Recommended
</div>
<div class="flex flex-col gap-4 p-6">
<div>
<h3 class="text-xl font-bold">Mermaid Plus</h3>
<p class="text-sm text-muted-foreground">Unlock AI, storage and collaboration</p>
</div>
<div class="flex flex-col gap-2">
<div class="flex justify-center">
<span
class="rounded-full bg-pink-100 px-3 py-0.5 text-xs font-semibold text-pink-700 dark:bg-pink-950 dark:text-pink-300">
10% off with code JS26
</span>
</div>
<Button variant="accent" class="w-full" onclick={handleStartTrial}>
Start free trial
</Button>
</div>
<ul class="space-y-3 text-sm">
<li class="flex items-center gap-2">
<EditIcon class="size-4 shrink-0 text-muted-foreground" />
Visual editor
</li>
<li class="flex items-center gap-2">
<SparklesIcon class="size-4 shrink-0 text-muted-foreground" />
300 AI credits
</li>
<li class="flex items-center gap-2">
<HomeIcon class="size-4 shrink-0 text-muted-foreground" />
Unlimited diagram storage
</li>
<li class="flex items-center gap-2">
<WidthIcon class="size-4 shrink-0 text-muted-foreground" />
Limitless diagram size
</li>
<li class="flex items-center gap-2">
<ChatIcon class="size-4 shrink-0 text-muted-foreground" />
View & comment collaboration
</li>
</ul>
</div>
</div>
<!-- Open Source Card -->
<div class="flex flex-col gap-4 rounded-xl border bg-white p-6 shadow dark:bg-card">
<div class="flex flex-col justify-end pt-10">
<h3 class="text-xl font-bold">Open Source</h3>
<p class="text-sm text-muted-foreground">Code only, no login, always free</p>
</div>
<div class="flex flex-col gap-2">
<p class="mt-2 text-sm text-muted-foreground">Mermaid has a new home</p>
<Button variant="outline" class="w-full border-accent" onclick={handleContinueToNewHome}>
Continue to mermaid.ai/live
<ArrowIcon class="ml-1 size-4" />
</Button>
<Button variant="outline" class="w-full" onclick={handleStartFree}>
Stay on mermaid.live
</Button>
</div>
<ul class="space-y-3 text-sm">
<li class="flex items-center gap-2">
<LanguageIcon class="size-4 shrink-0 text-muted-foreground" />
Diagram stored in URL
</li>
<li class="flex items-center gap-2">
<CodeIcon class="size-4 shrink-0 text-muted-foreground" />
Code editor
</li>
<li class="flex items-center gap-2">
<OpenSourceIcon class="size-4 shrink-0 text-muted-foreground" />
Open source
</li>
<li class="flex items-center gap-2">
<HistoryIcon class="size-4 shrink-0 text-muted-foreground" />
Version history
</li>
</ul>
</div>
</div>
<div class="text-center">
<a
href="https://mermaid.ai/privacy-policy"
target="_blank"
class="text-sm text-foreground underline hover:text-accent">
mermaid.ai Privacy Policy
</a>
</div>
</Dialog.Content>
</Dialog.Root>
+2 -4
View File
@@ -1,7 +1,7 @@
<script lang="ts" module>
import type { WithElementRef } from 'bits-ui';
import { cn, type WithElementRef } from '$lib/utils.js';
import type { HTMLAnchorAttributes, HTMLButtonAttributes } from 'svelte/elements';
import { type VariantProps, tv } from 'tailwind-variants';
import { tv, type VariantProps } from 'tailwind-variants';
export const buttonVariants = tv({
base: 'focus-visible:ring-ring inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-6 [&_svg]:shrink-0',
@@ -40,8 +40,6 @@
</script>
<script lang="ts">
import { cn } from '$lib/utils.js';
let {
class: className,
variant = 'default',
@@ -1,6 +1,6 @@
<script lang="ts">
import { cn } from '$lib/utils.js';
import { Dialog as DialogPrimitive, type WithoutChildrenOrChild } from 'bits-ui';
import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';
import { Dialog as DialogPrimitive } from 'bits-ui';
import X from 'lucide-svelte/icons/x';
import type { Snippet } from 'svelte';
import * as Dialog from './index.js';
@@ -22,13 +22,13 @@
<DialogPrimitive.Content
bind:ref
class={cn(
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
'fixed top-[50%] left-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
className
)}
{...restProps}>
{@render children?.()}
<DialogPrimitive.Close
class="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:text-muted-foreground">
class="absolute top-4 right-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-none disabled:pointer-events-none data-[state=open]:text-muted-foreground">
<X class="size-4" />
<span class="sr-only">Close</span>
</DialogPrimitive.Close>
@@ -1,7 +1,6 @@
<script lang="ts">
import type { WithElementRef } from 'bits-ui';
import { cn, type WithElementRef } from '$lib/utils.js';
import type { HTMLAttributes } from 'svelte/elements';
import { cn } from '$lib/utils.js';
let {
ref = $bindable(null),
@@ -1,7 +1,6 @@
<script lang="ts">
import { cn, type WithElementRef } from '$lib/utils.js';
import type { HTMLAttributes } from 'svelte/elements';
import type { WithElementRef } from 'bits-ui';
import { cn } from '$lib/utils.js';
let {
ref = $bindable(null),
@@ -12,7 +12,7 @@
<DialogPrimitive.Overlay
bind:ref
class={cn(
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'fixed inset-0 z-50 bg-black/80 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0',
className
)}
{...restProps} />
@@ -11,5 +11,5 @@
<DialogPrimitive.Title
bind:ref
class={cn('text-lg font-semibold leading-none tracking-tight', className)}
class={cn('text-lg leading-none font-semibold tracking-tight', className)}
{...restProps} />
+3 -4
View File
@@ -1,7 +1,6 @@
<script lang="ts">
import type { InputType } from '$/types';
import { cn } from '$lib/utils.js';
import type { WithElementRef } from 'bits-ui';
import { cn, type WithElementRef } from '$lib/utils.js';
import type { HTMLInputAttributes } from 'svelte/elements';
type Props = WithElementRef<
@@ -23,7 +22,7 @@
<input
bind:this={ref}
class={cn(
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
className
)}
type="file"
@@ -34,7 +33,7 @@
<input
bind:this={ref}
class={cn(
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
className
)}
{type}
@@ -20,7 +20,7 @@
{align}
{sideOffset}
class={cn(
'z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
'z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',
className
)}
{...restProps} />
@@ -1,8 +1,7 @@
<script lang="ts">
import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';
import GripVertical from 'lucide-svelte/icons/grip-vertical';
import * as ResizablePrimitive from 'paneforge';
import type { WithoutChildrenOrChild } from 'bits-ui';
import { cn } from '$lib/utils.js';
let {
ref = $bindable(null),
@@ -17,7 +16,7 @@
<ResizablePrimitive.PaneResizer
bind:ref
class={cn(
'relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[direction=vertical]:h-px data-[direction=vertical]:w-full data-[direction=vertical]:after:left-0 data-[direction=vertical]:after:h-1 data-[direction=vertical]:after:w-full data-[direction=vertical]:after:-translate-y-1/2 data-[direction=vertical]:after:translate-x-0 [&[data-direction=vertical]>div]:rotate-90',
'relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:outline-none data-[direction=vertical]:h-px data-[direction=vertical]:w-full data-[direction=vertical]:after:left-0 data-[direction=vertical]:after:h-1 data-[direction=vertical]:after:w-full data-[direction=vertical]:after:translate-x-0 data-[direction=vertical]:after:-translate-y-1/2 [&[data-direction=vertical]>div]:rotate-90',
className
)}
{...restProps}>
+3 -3
View File
@@ -1,6 +1,6 @@
<script lang="ts">
import { cn } from '$lib/utils.js';
import { Switch as SwitchPrimitive, type WithoutChildrenOrChild } from 'bits-ui';
import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';
import { Switch as SwitchPrimitive } from 'bits-ui';
let {
ref = $bindable(null),
@@ -14,7 +14,7 @@
bind:ref
bind:checked
class={cn(
'peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-accent data-[state=unchecked]:bg-slate-700',
'peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-accent data-[state=unchecked]:bg-slate-700',
className
)}
{...restProps}>
@@ -14,7 +14,7 @@
bind:ref
{sideOffset}
class={cn(
'z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
'z-50 animate-in overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95',
className
)}
{...restProps} />
+4
View File
@@ -1,4 +1,6 @@
export const TID = {
aiHelpText: 'ai-help-text',
aiRepairButton: 'ai-repair-button',
copyMarkdown: 'copy-markdown',
diagramDocumentationButton: 'diagram-documentation-button',
downloadPNG: 'download-PNG',
@@ -8,5 +10,7 @@ export const TID = {
} as const;
export const C = {
aiLiveEditor: 'ai_live_editor',
editorChooserDismissedKey: 'mermaid-editor-chooser-dismissed',
utmSource: 'mermaid_live_editor'
} as const;
+71
View File
@@ -0,0 +1,71 @@
import type * as monaco from 'monaco-editor';
export class AIPromptViewZoneManager {
private editor: monaco.editor.IStandaloneCodeEditor | null = null;
private viewZoneId: string | null = null;
private viewZoneNode: HTMLElement | null = null;
private viewZone: monaco.editor.IViewZone | null = null;
private topPopupSpace = 8;
public setEditor(editor: monaco.editor.IStandaloneCodeEditor): void {
this.editor = editor;
}
public show(lineNumber: number, node: HTMLElement, height: number): void {
if (!this.editor) return;
this.viewZoneNode = node;
this.editor.changeViewZones((changeAccessor) => {
if (this.viewZoneId) {
changeAccessor.removeZone(this.viewZoneId);
}
const domNode = document.createElement('div');
domNode.style.top = '0px';
domNode.style.paddingTop = '8px';
domNode.style.paddingBottom = '0px';
domNode.appendChild(this.viewZoneNode as Node);
this.viewZone = {
afterLineNumber: lineNumber,
heightInPx: height + this.topPopupSpace,
domNode: domNode
};
this.viewZoneId = changeAccessor.addZone(this.viewZone);
});
}
public updateHeight(height: number): void {
if (!this.editor || !this.viewZoneId || !this.viewZone) return;
this.viewZone.heightInPx = height + this.topPopupSpace;
this.editor.changeViewZones((changeAccessor) => {
if (this.viewZoneId) {
changeAccessor.layoutZone(this.viewZoneId);
}
});
}
public hide(): void {
if (!this.editor || !this.viewZoneId) return;
this.editor.changeViewZones((changeAccessor) => {
if (this.viewZoneId) {
changeAccessor.removeZone(this.viewZoneId);
this.viewZoneId = null;
this.viewZone = null;
}
});
if (this.viewZoneNode) {
this.viewZoneNode = null;
}
}
public destroy(): void {
this.hide();
this.editor = null;
}
}
+3
View File
@@ -1,7 +1,10 @@
export const env = {
analyticsUrl: import.meta.env.MERMAID_ANALYTICS_URL ?? '',
docsUrl: import.meta.env.MERMAID_DOCS_URL ?? 'https://mermaid.js.org',
domain: import.meta.env.MERMAID_DOMAIN ?? '',
hidePrivacyPolicy: import.meta.env.MERMAID_HIDE_PRIVACY_POLICY === 'true',
isEnabledMermaidChartLinks: import.meta.env.MERMAID_IS_ENABLED_MERMAID_CHART_LINKS === 'true',
krokiRendererUrl: import.meta.env.MERMAID_KROKI_RENDERER_URL ?? '',
privacyPolicyUrl: import.meta.env.MERMAID_PRIVACY_POLICY_URL ?? '',
rendererUrl: import.meta.env.MERMAID_RENDERER_URL ?? ''
} as const;
+6 -7
View File
@@ -1,6 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { addHistoryEntry } from '$lib/components/History/history';
import type { State } from '$lib/types';
@@ -49,7 +46,7 @@ const getGistData = async (gistURL: string): Promise<GistData> => {
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_, __, gistID, revisionID] = path.split('/');
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const { html_url, files, history }: GistResponse = await fetchJSON(
`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`
);
@@ -65,7 +62,7 @@ const getGistData = async (gistURL: string): Promise<GistData> => {
code,
config,
time: new Date(currentItem.committed_at).getTime(),
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
url: `${html_url}/${currentItem.version}`,
version: currentItem.version.slice(-7)
};
@@ -85,7 +82,9 @@ const getStateFromGist = (gist: GistData, gistURL: string = gist.url): State =>
type: 'gist'
}
};
gist.config && (state.mermaid = gist.config);
if (gist.config) {
state.mermaid = gist.config;
}
return state;
};
@@ -96,7 +95,7 @@ export const loadGistData = async (gistURL: string): Promise<State> => {
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_, __, gistID, revisionID] = path.split('/');
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const { history }: GistResponse = await fetchJSON(
`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`
);
+2 -1
View File
@@ -49,9 +49,10 @@ export const loadDataFromUrl = async (): Promise<void> => {
}
}
}
loaded &&
if (loaded) {
updateCodeStore({
...state,
updateDiagram: true
});
}
};
+23 -1
View File
@@ -1,9 +1,11 @@
import { diagramData } from '@mermaid-js/examples';
import elkLayouts from '@mermaid-js/layout-elk';
import tidyTreeLayouts from '@mermaid-js/layout-tidy-tree';
import zenuml from '@mermaid-js/mermaid-zenuml';
import type { MermaidConfig, RenderResult } from 'mermaid';
import mermaid from 'mermaid';
mermaid.registerLayoutLoaders(elkLayouts);
mermaid.registerLayoutLoaders([...elkLayouts, ...tidyTreeLayouts]);
const init = mermaid.registerExternalDiagrams([zenuml]);
export const render = async (
@@ -39,3 +41,23 @@ export const standardizeDiagramType = (diagramType: string) => {
}
}
};
type DiagramDefinition = (typeof diagramData)[number];
const isValidDiagram = (diagram: DiagramDefinition): diagram is Required<DiagramDefinition> => {
return Boolean(diagram.name && diagram.examples && diagram.examples.length > 0);
};
export const getSampleDiagrams = () => {
const diagrams = diagramData
.filter((d) => isValidDiagram(d))
.map(({ examples, ...rest }) => ({
...rest,
example: examples?.filter(({ isDefault }) => isDefault)[0]
}));
const examples: Record<string, string> = {};
for (const diagram of diagrams) {
examples[diagram.name.replace(/ (Diagram|Chart|Graph)/, '')] = diagram.example.code;
}
return examples;
};
+74
View File
@@ -0,0 +1,74 @@
import { C } from '$/constants';
import { env } from '$/util/env';
const mermaidAiDomain = 'mermaid.ai';
const mermaidLiveDomain = 'mermaid.live';
/**
* Check if we're on mermaid.ai
*/
export const isOnMermaidAI = (): boolean => {
const domain = window.location.hostname;
return domain === mermaidAiDomain || domain.endsWith(`.${mermaidAiDomain}`);
};
/**
* Check if we're on mermaid.live
*/
export const isOnMermaidLive = (): boolean => {
const domain = window.location.hostname;
return domain === mermaidLiveDomain || domain.endsWith(`.${mermaidLiveDomain}`);
};
/**
* Check if the current URL has pako data (diagram content from a shared link).
*/
const hasPakoData = (): boolean => {
const hash = window.location.hash;
return (
hash.includes('pako:') || hash.includes('base64:') || (hash.length > 10 && hash.startsWith('#'))
);
};
/**
* Check if the user arrived from a known Mermaid domain (mermaid.ai or mermaid.js.org).
*/
const isReferredFromMermaid = (): boolean => {
try {
const referrer = document.referrer;
if (!referrer) return false;
const hostname = new URL(referrer).hostname;
return (
hostname === 'mermaid.ai' ||
hostname.endsWith('.mermaid.ai') ||
hostname === 'mermaid.js.org' ||
hostname.endsWith('.mermaid.js.org') ||
hostname === 'mermaid.live' ||
hostname.endsWith('.mermaid.live')
);
} catch {
return false;
}
};
/**
* Check if the editor chooser modal should be shown.
* Shows for new users who haven't dismissed it and aren't viewing a shared link.
* Not shown on mobile (viewport width < 640px).
*/
export const shouldShowEditorChooser = (): boolean => {
if (!env.isEnabledMermaidChartLinks) return false;
if (!isOnMermaidAI() && !isOnMermaidLive()) return false;
if (window.innerWidth < 640) return false;
if (window.localStorage.getItem(C.editorChooserDismissedKey) === 'true') return false;
if (hasPakoData()) return false;
if (isReferredFromMermaid()) return false;
return true;
};
/**
* Dismiss the editor chooser modal permanently
*/
export const dismissEditorChooser = (): void => {
window.localStorage.setItem(C.editorChooserDismissedKey, 'true');
};
-2
View File
@@ -2,7 +2,6 @@
import type * as Monaco from 'monaco-editor';
// eslint-disable-next-line es/no-regexp-lookbehind-assertions
const commentRegex = /(?<!["'])%%(?![^"']*["']\)).*$/;
export const initEditor = (monacoEditor: typeof Monaco): void => {
@@ -235,7 +234,6 @@ export const initEditor = (monacoEditor: typeof Monaco): void => {
])
)
)
// eslint-disable-next-line unicorn/no-array-reduce
.reduce(
(overallKeywords, nextKeyword) => ({
...overallKeywords,
-3
View File
@@ -185,13 +185,11 @@ function getBrowserStorage(
}
};
const connect = () => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (listenExternalChanges && typeof window !== 'undefined' && window.addEventListener) {
window.addEventListener('storage', listenerFunction);
}
};
const disconnect = () => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (listenExternalChanges && typeof window !== 'undefined' && window.removeEventListener) {
window.removeEventListener('storage', listenerFunction);
}
@@ -231,7 +229,6 @@ function getBrowserStorage(
* @param listenExternalChanges - Update the store if the localStorage is updated from another page
*/
export function localStorage<T>(listenExternalChanges = false): StorageInterface<T> {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (typeof window !== 'undefined' && window.localStorage) {
return getBrowserStorage(window.localStorage, listenExternalChanges);
}
+12 -51
View File
@@ -21,37 +21,6 @@
const commonParams = { utm_source: C.utmSource, utm_medium: 'banner_ad' } as const;
const randomTagLines: Taglines[] = [
{
label: 'Customize your layout and design in Mermaid Charts whiteboard!',
url: {
path: '/whiteboard',
params: { utm_campaign: 'whiteboard' }
}
},
{
label: 'Customize your layout and design in Mermaid Charts visual editor!',
url: {
path: '/whiteboard',
params: { utm_campaign: 'visual_editor' }
}
},
{
label: 'Customize your layout and design with Mermaid Charts GUI!',
url: {
path: '/whiteboard',
params: { utm_campaign: 'gui' }
}
},
{
label: 'Customize your layout and design in Mermaid Chart!',
url: {
path: '/whiteboard',
params: { utm_campaign: 'visual_editor_whiteboard_gui' }
}
}
];
let taglines: Taglines[] = [
{
label: 'Replace ChatGPT Pro, Mermaid.live, and Lucid Chart with Mermaid Chart',
@@ -66,33 +35,25 @@
path: '/landing',
params: { utm_campaign: 'team_collaboration' }
}
},
{
label: 'Customize your layout and design in Mermaid Charts visual editor!',
url: {
path: '/whiteboard',
params: { utm_campaign: 'visual_editor' }
}
}
];
const getRandomIndex = (array: unknown[]) => Math.floor(Math.random() * array.length);
const getSessionHeadlineIndex = (): number => {
const storageKey = 'mermaidBannerIndex';
const storedIndex = sessionStorage.getItem(storageKey);
if (storedIndex) {
return Number.parseInt(storedIndex, 10);
}
const randomIndex = getRandomIndex(randomTagLines);
sessionStorage.setItem(storageKey, randomIndex.toString());
return randomIndex;
};
const selectedHeadlineIndex = getSessionHeadlineIndex();
const currentBannerSet = [...taglines, randomTagLines[selectedHeadlineIndex]];
let index = $state(getRandomIndex(currentBannerSet));
let currentTagline = $derived(currentBannerSet[index]);
let index = $state(getRandomIndex(taglines));
let currentTagline = $derived(taglines[index]);
let shouldAnimate = $state(true);
const interval = setInterval(() => {
if (shouldAnimate) {
index = (index + 1) % currentBannerSet.length;
index = (index + 1) % taglines.length;
}
}, 5000);
@@ -117,9 +78,9 @@
class="col-start-1 row-start-1 flex items-center justify-center gap-4 no-underline"
in:fade={{ delay: 800 }}
out:fade={{ duration: 1000 }}>
<span class="text-sm tracking-wider text-white">{currentTagline.label}</span>
<span class="text-base tracking-wider text-white">{currentTagline.label}</span>
<Button
class="shrink-0 rounded-md bg-[#1E1A2E] px-3 py-1.5 text-sm font-semibold tracking-wide text-white hover:bg-[#261A56]">
class="shrink-0 rounded-md bg-[#1E1A2E] px-3 py-1.5 text-base font-semibold tracking-wide text-white hover:bg-[#261A56]">
Try now
</Button>
</a>
+31
View File
@@ -0,0 +1,31 @@
<script lang="ts">
import { Button } from '$/components/ui/button';
import { getCheckoutUrl } from '$/util/util';
import type { Snippet } from 'svelte';
interface Props {
closeBanner: Snippet;
}
let { closeBanner }: Props = $props();
const url = getCheckoutUrl({ utmCampaign: 'oss_coupon', utmMedium: 'banner_ad' });
</script>
<div class="flex w-full items-center bg-[#E0095F] p-1.5" role="banner">
<div class="grid grow">
<a
href={url}
target="_blank"
class="col-start-1 row-start-1 flex items-center justify-center gap-4 no-underline">
<span class="text-base tracking-wider text-white">
Try Mermaid Advanced Editor — OSS users get 10% off with code JS26
</span>
<Button
class="shrink-0 rounded-md bg-[#1E1A2E] px-3 py-1.5 text-base font-semibold tracking-wide text-white hover:bg-[#261A56]">
Get started
</Button>
</a>
</div>
{@render closeBanner()}
</div>
+7
View File
@@ -5,6 +5,7 @@ import type { Component } from 'svelte';
import { get, writable, type Writable } from 'svelte/store';
import { localStorage, persist } from '../persist';
import April2025 from './April2025.svelte';
import JS2026 from './JS2026.svelte';
dayjs.extend(duration);
@@ -16,6 +17,12 @@ interface Promotion {
}
const promotions: Record<string, Promotion> = {
'promo-js-2026': {
startDate: new Date('2026-01-01'),
endDate: new Date('2026-12-31'),
component: JS2026,
hideDurationMs: dayjs.duration(1, 'week').asMilliseconds()
},
'promo-april-2025': {
startDate: new Date('2025-04-01'),
endDate: new Date('2028-12-31'),
+51
View File
@@ -0,0 +1,51 @@
import { describe, expect, it } from 'vitest';
import { buildRedirectUrl } from './redirect';
const mockLocation = (url: string): Location => {
const parsed = new URL(url);
return { hash: parsed.hash, search: parsed.search } as Location;
};
describe('buildRedirectUrl', () => {
it('should redirect to /edit by default when hash is empty', () => {
expect(buildRedirectUrl(mockLocation('https://mermaid.live/'))).toBe('/edit');
});
it('should preserve search params', () => {
expect(buildRedirectUrl(mockLocation('https://mermaid.live/?utm_source=github'))).toBe(
'/edit?utm_source=github'
);
});
it('should extract route and fragment from old hash format', () => {
expect(buildRedirectUrl(mockLocation('https://mermaid.live/#/edit/pako:abc123'))).toBe(
'/edit#pako:abc123'
);
});
it('should place search params before the hash fragment', () => {
expect(
buildRedirectUrl(mockLocation('https://mermaid.live/?utm_source=twitter#/edit/pako:abc123'))
).toBe('/edit?utm_source=twitter#pako:abc123');
});
it('should handle hash with view route', () => {
expect(buildRedirectUrl(mockLocation('https://mermaid.live/#/view/pako:xyz'))).toBe(
'/view#pako:xyz'
);
});
it('should default to edit when hash has no route', () => {
expect(buildRedirectUrl(mockLocation('https://mermaid.live/#somethingelse'))).toBe('/edit');
});
it('should handle multiple search params with hash', () => {
expect(
buildRedirectUrl(
mockLocation(
'https://mermaid.live/?utm_source=gh&utm_medium=link&utm_campaign=test#/edit/pako:data'
)
)
).toBe('/edit?utm_source=gh&utm_medium=link&utm_campaign=test#pako:data');
});
});
+17
View File
@@ -0,0 +1,17 @@
import { resolve } from '$app/paths';
/**
* Build the redirect URL for legacy root-path links.
* Extracts the route and fragment from the old hash-based URL format,
* and ensures search params (e.g. UTM) come before the hash fragment.
*/
export const buildRedirectUrl = (location: Location): string => {
const parts = location.hash.split('/');
let path = 'edit';
let fragment = '';
if (parts.length > 2) {
path = parts[1];
fragment = `#${parts[2]}`;
}
return `${resolve(`/${path}`, {})}${location.search}${fragment}`;
};
+3 -3
View File
@@ -1,6 +1,6 @@
import { deflate, inflate } from 'pako';
import { toUint8Array, fromUint8Array, toBase64, fromBase64 } from 'js-base64';
import type { State } from '$lib/types';
import { fromBase64, fromUint8Array, toBase64, toUint8Array } from 'js-base64';
import { deflate, inflate } from 'pako';
interface Serde {
serialize: (state: string) => string;
@@ -30,7 +30,7 @@ export const pakoSerde: Serde = {
export type SerdeType = 'base64' | 'pako';
const serdes: { [key in SerdeType]: Serde } = {
const serdes: Record<SerdeType, Serde> = {
base64: base64Serde,
pako: pakoSerde
};
+24 -12
View File
@@ -1,4 +1,3 @@
import { C } from '$/constants';
import type { ErrorHash, MarkerData, State, ValidatedState } from '$/types';
import { debounce } from 'lodash-es';
import type { MermaidConfig } from 'mermaid';
@@ -12,7 +11,7 @@ import {
import { parse } from './mermaid';
import { localStorage, persist } from './persist';
import { deserializeState, pakoSerde, serializeState } from './serde';
import { errorDebug, formatJSON, MCBaseURL } from './util';
import { errorDebug, formatJSON, getUTMSource, MCBaseURL } from './util';
export const defaultState: State = {
code: `flowchart TD
@@ -81,7 +80,7 @@ const processState = async (state: State) => {
processed.error = error as Error;
errorDebug();
console.error(error);
if ('hash' in error) {
if (error && typeof error === 'object' && 'hash' in error) {
try {
let errorString = processed.error.toString();
const errorLineText = extractErrorLineText(errorString);
@@ -89,7 +88,6 @@ const processState = async (state: State) => {
let first_line: number, last_line: number, first_column: number, last_column: number;
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
({ first_line, last_line, first_column, last_column } = (error.hash as ErrorHash).loc);
} catch {
const lineNo = findMostRelevantLineNumber(errorString, state.code);
@@ -132,18 +130,32 @@ export const stateStore: Readable<ValidatedState> = derived(
export const urlsStore = derived([stateStore], ([{ code, serialized }]) => {
const { krokiRendererUrl, rendererUrl } = env;
const png = `${rendererUrl}/img/${serialized}?type=png`;
const png = rendererUrl ? `${rendererUrl}/img/${serialized}?type=png` : '';
return {
kroki: `${krokiRendererUrl}/mermaid/svg/${pakoSerde.serialize(code)}`,
mdCode: `[![](${png})](${window.location.protocol}//${window.location.host}${window.location.pathname}#${serialized})`,
kroki: krokiRendererUrl ? `${krokiRendererUrl}/mermaid/svg/${pakoSerde.serialize(code)}` : '',
mdCode: png
? `[![](${png})](${window.location.protocol}//${window.location.host}${window.location.pathname}#${serialized})`
: '',
mermaidChart: ({
medium
medium,
campaign
}: {
medium: 'ai_repair' | 'main_menu' | 'save_diagram' | 'share' | 'toggle';
medium:
| 'ai_repair'
| 'ai_edit'
| 'main_menu'
| 'save_diagram'
| 'share'
| 'vibe_diagramming'
| 'visual_edit'
| 'voice_edit';
campaign?: string;
}) => {
const utmSource = getUTMSource();
const params = new URLSearchParams({
utm_source: C.utmSource,
utm_medium: medium
utm_source: utmSource,
utm_medium: medium,
...(campaign ? { utm_campaign: campaign } : {})
}).toString();
return {
save: `${MCBaseURL}/app/plugin/save?state=${serialized}&${params}`,
@@ -154,7 +166,7 @@ export const urlsStore = derived([stateStore], ([{ code, serialized }]) => {
},
new: `${window.location.protocol}//${window.location.host}${window.location.pathname}#${serializeState(defaultState)}`,
png,
svg: `${rendererUrl}/svg/${serialized}`,
svg: rendererUrl ? `${rendererUrl}/svg/${serialized}` : '',
view: `/view#${serialized}`
};
});
+47
View File
@@ -0,0 +1,47 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { getAnalyticsSafeUrl } from './stats';
describe('getAnalyticsUrl', () => {
beforeEach(() => {
// Reset location to a clean state before each test
window.history.replaceState(null, '', '/');
});
it('should return origin and pathname for a simple URL', () => {
window.history.replaceState(null, '', '/edit');
const url = getAnalyticsSafeUrl();
expect(url).toBe(`${window.location.origin}/edit`);
});
it('should include search/query params (UTM parameters)', () => {
window.history.replaceState(null, '', '/edit?utm_source=github&utm_medium=docs');
const url = getAnalyticsSafeUrl();
expect(url).toBe(`${window.location.origin}/edit?utm_source=github&utm_medium=docs`);
});
it('should never include the hash', () => {
window.history.replaceState(null, '', '/edit#pako:someDiagramData');
// replaceState doesn't set hash, so set it via location
window.location.hash = '#pako:someDiagramData';
const url = getAnalyticsSafeUrl();
expect(url).not.toContain('#');
expect(url).not.toContain('pako:');
expect(url).toBe(`${window.location.origin}/edit`);
});
it('should include search params but exclude hash when both are present', () => {
window.history.replaceState(null, '', '/edit?utm_campaign=launch');
window.location.hash = '#pako:diagramDataHere';
const url = getAnalyticsSafeUrl();
expect(url).not.toContain('#');
expect(url).not.toContain('pako:');
expect(url).toContain('utm_campaign=launch');
expect(url).toBe(`${window.location.origin}/edit?utm_campaign=launch`);
});
it('should return just origin for root path with no params', () => {
window.history.replaceState(null, '', '/');
const url = getAnalyticsSafeUrl();
expect(url).toBe(`${window.location.origin}/`);
});
});
+33 -21
View File
@@ -5,20 +5,31 @@ import { env } from './env';
export let plausible: ReturnType<typeof PlausibleInstance> | undefined;
export const initAnalytics = async (): Promise<void> => {
if (browser && !plausible) {
try {
const { default: Plausible } = await import('plausible-tracker');
plausible = Plausible({
// All tracked stats are public and available at https://p.mermaid.live/mermaid.live
apiHost: env.analyticsUrl,
domain: env.domain,
hashMode: false
});
} catch (error) {
console.log(error);
console.info('Analytics blocked ;)');
}
if (!env.analyticsUrl || !browser || plausible) {
return;
}
try {
const { default: Plausible } = await import('plausible-tracker');
plausible = Plausible({
// All tracked stats are public and available at https://p.mermaid.live/mermaid.live
apiHost: env.analyticsUrl,
domain: env.domain,
hashMode: false
});
} catch (error) {
console.log(error);
console.info('Analytics blocked ;)');
}
};
/**
* Build the current page URL for analytics tracking.
* Includes origin, pathname, and search (for UTM params),
* but never the hash (which contains diagram data).
*/
export const getAnalyticsSafeUrl = (): string => {
return window.location.origin + window.location.pathname + window.location.search;
};
export const countLines = (code: string): number => {
@@ -75,19 +86,20 @@ const minutesToMilliSeconds = (minutes: number): number => {
return minutes * 60_000;
};
const noDelay = 0;
const defaultDelay = minutesToMilliSeconds(1);
const delaysPerEvent = {
bannerClick: defaultDelay,
bannerClick: noDelay,
chooseEditor: noDelay,
copyClipboard: defaultDelay,
copyMarkdown: defaultDelay,
download: defaultDelay,
history: defaultDelay,
loadGist: defaultDelay,
loadSampleDiagram: defaultDelay,
mermaidChartClick: noDelay,
migration: defaultDelay,
mobileViewToggle: defaultDelay,
panZoom: minutesToMilliSeconds(10),
playgroundToggle: 0,
pwaInstalled: defaultDelay,
render: minutesToMilliSeconds(5),
renderDiagram: defaultDelay,
@@ -108,14 +120,14 @@ export const logEvent = (
if (timeouts.has(key)) {
clearTimeout(timeouts.get(key));
} else {
plausible.trackEvent(
name,
{ props: data },
{ url: window.location.origin + window.location.pathname }
);
plausible.trackEvent(name, { props: data }, { url: getAnalyticsSafeUrl() });
}
timeouts.set(
key,
window.setTimeout(() => timeouts.delete(key), delaysPerEvent[name])
);
};
export const logMermaidChartClick = (source: string): void => {
logEvent('mermaidChartClick', { source });
};
+37 -3
View File
@@ -1,9 +1,17 @@
import { C } from '$/constants';
import { env } from './env';
import { loadDataFromUrl } from './fileLoaders/loader';
import { initLoading } from './loading';
import { isOnMermaidAI } from './migration/domainMigration';
import { applyMigrations } from './migrations';
import { initURLSubscription, loadState, updateCodeStore, verifyState } from './state';
import { initAnalytics, plausible } from './stats';
import { getAnalyticsSafeUrl, initAnalytics, plausible } from './stats';
export const getDomain = (url?: string): string => {
if (!url) return '';
const domain = new URL(url).hostname;
return domain;
};
export const loadStateFromURL = (): void => {
loadState(window.location.hash.slice(1));
@@ -22,16 +30,35 @@ export const initHandler = async (): Promise<void> => {
syncDiagram();
initURLSubscription();
await initAnalytics();
plausible?.trackPageview({ url: window.location.origin + window.location.pathname });
plausible?.trackPageview({
url: getAnalyticsSafeUrl()
});
verifyState();
};
export const isMac = navigator.platform.toUpperCase().includes('MAC');
export const cmdKey = isMac ? 'Cmd' : 'Ctrl';
export const MCBaseURL = env.isEnabledMermaidChartLinks
? 'https://mermaidchart.com' // 'http://localhost:5174'
? 'https://mermaid.ai' // 'http://localhost:5174'
: 'https://example.com';
export const getCheckoutUrl = ({
utmCampaign,
utmMedium
}: {
utmCampaign: string;
utmMedium: string;
}): string => {
const params = new URLSearchParams({
coupon: 'arDfyFT8',
tier: 'plus',
utm_campaign: utmCampaign,
utm_medium: utmMedium,
utm_source: getUTMSource()
});
return `${MCBaseURL}/app/user/billing/checkout?${params.toString()}`;
};
let count = 0;
export const errorDebug = (limit = 1000) => {
count += 1;
@@ -82,3 +109,10 @@ function fallbackCopyToClipboard(text: string) {
textArea.remove();
}
}
export const getUTMSource = (): string => {
if (typeof window !== 'undefined' && isOnMermaidAI()) {
return C.aiLiveEditor;
}
return C.utmSource;
};
+7
View File
@@ -4,3 +4,10 @@ import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type WithoutChild<T> = T extends { child?: any } ? Omit<T, 'child'> : T;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type WithoutChildren<T> = T extends { children?: any } ? Omit<T, 'children'> : T;
export type WithoutChildrenOrChild<T> = WithoutChildren<WithoutChild<T>>;
export type WithElementRef<T, U extends HTMLElement = HTMLElement> = T & { ref?: U | null };
+5 -6
View File
@@ -6,7 +6,7 @@
import { base } from '$app/paths';
import { mode, ModeWatcher } from 'mode-watcher';
import { onMount, type Snippet } from 'svelte';
import '../app.postcss';
import '../app.css';
interface Props {
children: Snippet;
@@ -20,11 +20,10 @@
window.addEventListener('hashchange', () => {
void initHandler();
});
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register(`${base}/service-worker.js`, {
scope: `${base}/`
})
.register(`${base}/service-worker.js`, { scope: `${base}/` })
.then(function (registration) {
console.log('Registration successful, scope is:', registration.scope);
})
@@ -42,13 +41,13 @@
<ModeWatcher />
<Toaster />
<main class="h-[100dvh]">
<main class="h-dvh">
{@render children()}
</main>
{#if $loadingStateStore.loading}
<div
class="absolute left-0 top-0 z-50 flex h-screen w-screen justify-center bg-gray-600 align-middle opacity-50">
class="absolute top-0 left-0 z-50 flex h-screen w-screen justify-center bg-gray-600 align-middle opacity-50">
<div class="my-auto text-4xl font-bold text-indigo-100">
<div class="loader mx-auto"></div>
<div>{$loadingStateStore.message}</div>
+2 -8
View File
@@ -1,16 +1,10 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { buildRedirectUrl } from '$lib/util/redirect';
import { onMount } from 'svelte';
import { base } from '$app/paths';
onMount(async () => {
// Handle old live editor links and redirect to new version
const hash = window.location.hash.split('/');
let newURL = 'edit';
if (hash.length > 2) {
newURL = `${hash[1]}#${hash[2]}`;
}
await goto(`${base}/${newURL}`, {
await goto(buildRedirectUrl(window.location), {
replaceState: true
});
});
+14 -8
View File
@@ -3,9 +3,11 @@
import Card from '$/components/Card/Card.svelte';
import DiagramDocButton from '$/components/DiagramDocumentationButton.svelte';
import Editor from '$/components/Editor.svelte';
import EnhancedEditsButton from '$/components/EnhancedEditsButton.svelte';
import History from '$/components/History/History.svelte';
import McWrapper from '$/components/McWrapper.svelte';
import MermaidChartIcon from '$/components/MermaidChartIcon.svelte';
import EditorChooserModal from '$/components/migration/EditorChooserModal.svelte';
import Navbar from '$/components/Navbar.svelte';
import PanZoomToolbar from '$/components/PanZoomToolbar.svelte';
import Preset from '$/components/Preset.svelte';
@@ -18,9 +20,10 @@
import VersionSecurityToolbar from '$/components/VersionSecurityToolbar.svelte';
import View from '$/components/View.svelte';
import type { EditorMode, Tab } from '$/types';
import { shouldShowEditorChooser } from '$/util/migration/domainMigration';
import { PanZoomState } from '$/util/panZoom';
import { stateStore, updateCodeStore, urlsStore } from '$/util/state';
import { logEvent } from '$/util/stats';
import { logEvent, logMermaidChartClick } from '$/util/stats';
import { initHandler } from '$/util/util';
import { onMount } from 'svelte';
import CodeIcon from '~icons/custom/code';
@@ -50,8 +53,10 @@
let width = $state(0);
let isMobile = $derived(width < 640);
let isViewMode = $state(true);
let showEditorChooser = $state(false);
onMount(async () => {
showEditorChooser = shouldShowEditorChooser();
await initHandler();
window.addEventListener('appinstalled', () => {
logEvent('pwaInstalled', { isMobile });
@@ -91,7 +96,8 @@
variant="accent"
size="sm"
href={$urlsStore.mermaidChart({ medium: 'save_diagram' }).save}
target="_blank">
target="_blank"
onclick={() => logMermaidChartClick('saveDiagram')}>
<MermaidChartIcon />
Save diagram
</Button>
@@ -131,16 +137,14 @@
<Resizable.Handle class="mr-1 hidden opacity-0 sm:block" />
<Resizable.Pane minSize={15} class="relative flex h-full flex-1 flex-col overflow-hidden">
<View {panZoomState} shouldShowGrid={$stateStore.grid} />
<div class="absolute right-0 top-0"><PanZoomToolbar {panZoomState} /></div>
<div class="absolute bottom-0 right-0"><VersionSecurityToolbar /></div>
<div class="absolute top-0 left-5 hidden md:block"><EnhancedEditsButton /></div>
<div class="absolute top-0 right-0"><PanZoomToolbar {panZoomState} /></div>
<div class="absolute right-0 bottom-0"><VersionSecurityToolbar /></div>
<div class="absolute bottom-0 left-0 sm:left-5"><SyncRoughToolbar /></div>
</Resizable.Pane>
{#if isHistoryOpen}
<Resizable.Handle class="ml-1 hidden opacity-0 sm:block" />
<Resizable.Pane
minSize={15}
defaultSize={30}
class="hidden h-full flex-grow flex-col sm:flex">
<Resizable.Pane minSize={15} defaultSize={30} class="hidden h-full grow flex-col sm:flex">
<History />
</Resizable.Pane>
{/if}
@@ -148,3 +152,5 @@
</div>
</div>
</div>
<EditorChooserModal bind:open={showEditorChooser} />
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg viewBox="40 40 410 410" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<path d="M407.48,111.18C335.587,108.103 269.573,152.338 245.08,220C220.587,152.338 154.573,108.103 82.68,111.18C80.285,168.229 107.577,222.632 154.74,254.82C178.908,271.419 193.35,298.951 193.27,328.27L193.27,379.13L296.9,379.13L296.9,328.27C296.816,298.953 311.255,271.42 335.42,254.82C382.596,222.644 409.892,168.233 407.48,111.18Z" fill="currentColor"/>
</svg>

After

Width:  |  Height:  |  Size: 689 B

+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg viewBox="0 0 490 490" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<path d="M490.16,84.61C490.16,37.912 452.248,0 405.55,0L84.61,0C37.912,0 0,37.912 0,84.61L0,405.55C0,452.248 37.912,490.16 84.61,490.16L405.55,490.16C452.248,490.16 490.16,452.248 490.16,405.55L490.16,84.61Z" style="fill:#ff3670;"/>
<path d="M407.48,111.18C335.587,108.103 269.573,152.338 245.08,220C220.587,152.338 154.573,108.103 82.68,111.18C80.285,168.229 107.577,222.632 154.74,254.82C178.908,271.419 193.35,298.951 193.27,328.27L193.27,379.13L296.9,379.13L296.9,328.27C296.816,298.953 311.255,271.42 335.42,254.82C382.596,222.644 409.892,168.233 407.48,111.18Z" style="fill:white;fill-rule:nonzero;"/>
</svg>

After

Width:  |  Height:  |  Size: 942 B

+9
View File
@@ -0,0 +1,9 @@
<svg id="mySvg" width="64" height="64" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"
aria-hidden="true" role="img">
<path class="p1"
d="M19 4C19 6.50909 19.8727 8.63636 21.6182 10.3818C23.3636 12.1273 25.4909 13 28 13C25.4909 13 23.3636 13.8727 21.6182 15.6182C19.8727 17.3636 19 19.4909 19 22C19 19.4909 18.1273 17.3636 16.3818 15.6182C14.6364 13.8727 12.5091 13 10 13C12.5091 13 14.6364 12.1273 16.3818 10.3818C18.1273 8.63636 19 6.50909 19 4Z"
fill="white" />
<path class="p2"
d="M8.5 16C8.5 17.2545 8.93636 18.3182 9.80909 19.1909C10.6818 20.0636 11.7455 20.5 13 20.5C11.7455 20.5 10.6818 20.9364 9.80909 21.8091C8.93636 22.6818 8.5 23.7455 8.5 25C8.5 23.7455 8.06364 22.6818 7.19091 21.8091C6.31818 20.9364 5.25455 20.5 4 20.5C5.25455 20.5 6.31818 20.0636 7.19091 19.1909C8.06364 18.3182 8.5 17.2545 8.5 16Z"
fill="white" />
</svg>

After

Width:  |  Height:  |  Size: 879 B

+9
View File
@@ -0,0 +1,9 @@
<svg id="mySvg" width="64" height="64" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"
aria-hidden="true" role="img">
<path class="p1"
d="M19 4C19 6.50909 19.8727 8.63636 21.6182 10.3818C23.3636 12.1273 25.4909 13 28 13C25.4909 13 23.3636 13.8727 21.6182 15.6182C19.8727 17.3636 19 19.4909 19 22C19 19.4909 18.1273 17.3636 16.3818 15.6182C14.6364 13.8727 12.5091 13 10 13C12.5091 13 14.6364 12.1273 16.3818 10.3818C18.1273 8.63636 19 6.50909 19 4Z"
fill="black" />
<path class="p2"
d="M8.5 16C8.5 17.2545 8.93636 18.3182 9.80909 19.1909C10.6818 20.0636 11.7455 20.5 13 20.5C11.7455 20.5 10.6818 20.9364 9.80909 21.8091C8.93636 22.6818 8.5 23.7455 8.5 25C8.5 23.7455 8.06364 22.6818 7.19091 21.8091C6.31818 20.9364 5.25455 20.5 4 20.5C5.25455 20.5 6.31818 20.0636 7.19091 19.1909C8.06364 18.3182 8.5 17.2545 8.5 16Z"
fill="black" />
</svg>

After

Width:  |  Height:  |  Size: 879 B

+5 -5
View File
@@ -1,19 +1,19 @@
import adapter from '@sveltejs/adapter-static';
import 'dotenv/config';
import { sveltePreprocess } from 'svelte-preprocess';
/** @type {import('@sveltejs/kit').Config} */
const config = {
// Consult https://github.com/sveltejs/svelte-preprocess
// for more information about preprocessors
preprocess: [
sveltePreprocess({
postcss: true
})
],
preprocess: [sveltePreprocess({})],
kit: {
alias: {
'$/*': './src/lib/*'
},
paths: {
base: process.env.MERMAID_BASE_PATH ?? ''
},
adapter: adapter({
pages: 'docs',
fallback: '404.html'
-96
View File
@@ -1,96 +0,0 @@
import tailwindcssAnimate from 'tailwindcss-animate';
import { fontFamily } from 'tailwindcss/defaultTheme';
/** @type {import('tailwindcss').Config} */
const config = {
darkMode: ['class'],
content: ['./src/**/*.{html,js,svelte,ts}'],
safelist: ['dark'],
theme: {
container: {
center: true,
padding: '2rem',
screens: {
'2xl': '1400px'
}
},
extend: {
colors: {
border: 'hsl(var(--border) / <alpha-value>)',
input: 'hsl(var(--input) / <alpha-value>)',
ring: 'hsl(var(--ring) / <alpha-value>)',
background: 'hsl(var(--background) / <alpha-value>)',
foreground: 'hsl(var(--foreground) / <alpha-value>)',
primary: {
DEFAULT: 'hsl(var(--primary) / <alpha-value>)',
foreground: 'hsl(var(--primary-foreground) / <alpha-value>)'
},
secondary: {
DEFAULT: 'hsl(var(--secondary) / <alpha-value>)',
foreground: 'hsl(var(--secondary-foreground) / <alpha-value>)'
},
destructive: {
DEFAULT: 'hsl(var(--destructive) / <alpha-value>)',
foreground: 'hsl(var(--destructive-foreground) / <alpha-value>)'
},
muted: {
DEFAULT: 'hsl(var(--muted) / <alpha-value>)',
foreground: 'hsl(var(--muted-foreground) / <alpha-value>)'
},
accent: {
DEFAULT: 'hsl(var(--accent) / <alpha-value>)',
foreground: 'hsl(var(--accent-foreground) / <alpha-value>)'
},
popover: {
DEFAULT: 'hsl(var(--popover) / <alpha-value>)',
foreground: 'hsl(var(--popover-foreground) / <alpha-value>)'
},
card: {
DEFAULT: 'hsl(var(--card) / <alpha-value>)',
foreground: 'hsl(var(--card-foreground) / <alpha-value>)'
},
sidebar: {
DEFAULT: 'hsl(var(--sidebar-background))',
foreground: 'hsl(var(--sidebar-foreground))',
primary: 'hsl(var(--sidebar-primary))',
'primary-foreground': 'hsl(var(--sidebar-primary-foreground))',
accent: 'hsl(var(--sidebar-accent))',
'accent-foreground': 'hsl(var(--sidebar-accent-foreground))',
border: 'hsl(var(--sidebar-border))',
ring: 'hsl(var(--sidebar-ring))'
}
},
borderRadius: {
xl: 'calc(var(--radius) + 4px)',
lg: 'var(--radius)',
md: 'calc(var(--radius) - 2px)',
sm: 'calc(var(--radius) - 4px)'
},
fontFamily: {
sans: [...fontFamily.sans]
},
keyframes: {
'accordion-down': {
from: { height: '0' },
to: { height: 'var(--bits-accordion-content-height)' }
},
'accordion-up': {
from: { height: 'var(--bits-accordion-content-height)' },
to: { height: '0' }
},
'caret-blink': {
'0%,70%,100%': { opacity: '1' },
'20%,50%': { opacity: '0' }
}
},
animation: {
'accordion-down': 'accordion-down 0.2s ease-out',
'accordion-up': 'accordion-up 0.2s ease-out',
'caret-blink': 'caret-blink 1.25s ease-out infinite'
}
}
},
plugins: [tailwindcssAnimate]
};
export default config;
+5 -6
View File
@@ -8,8 +8,7 @@ test.describe('Check actions', () => {
test('should update markdown code', async ({ editPage }) => {
const oldText = await editPage.markdownInput.inputValue();
await editPage.typeInEditor('C --> HistoryTest', { bottom: true, newline: true });
const newText = await editPage.markdownInput.inputValue();
expect(newText).not.toBe(oldText);
await expect(editPage.markdownInput).not.toHaveValue(oldText);
});
test.skip('should load gists from URL', async ({ page }) => {
@@ -21,15 +20,15 @@ test.describe('Check actions', () => {
});
test('should download png and svg', async ({ editPage }) => {
const firstPngSize = await editPage.checkAndDownloadPNG(80_000);
const firstPngSize = await editPage.checkAndDownloadPNG(20_000);
const firstSvgSize = await editPage.downloadSVG(10_000);
// Verify downloaded file is different for different diagrams
await editPage.toggleSampleDiagrams();
await editPage.loadSampleDiagram('ER');
await editPage.loadSampleDiagram('Entity Relationship');
const secondPngSize = await editPage.checkAndDownloadPNG(81_000);
const secondSvgSize = await editPage.downloadSVG(11_000);
const secondPngSize = await editPage.checkAndDownloadPNG(20_000);
const secondSvgSize = await editPage.downloadSVG(10_000);
// Verify files are actually different
expect(firstPngSize).not.toBe(secondPngSize);
+6
View File
@@ -4,6 +4,9 @@ test.describe('Auto sync tests', () => {
test('should automatically defer rendering when complex diagrams are edited', async ({
editPage
}) => {
test.slow(); // Complex diagram rendering can be slow under parallel load
// Wait for the default diagram to fully render before typing
await editPage.checkTextInView('Christmas');
await editPage.typeInEditor(
`
A & B & C & D & E --> F & G & H & I & J & K
@@ -27,9 +30,12 @@ A & B & C & D & E --> F & G & H & I & J & K & LongTest`
});
test('supports editing code when code is incorrect', async ({ editPage }) => {
test.slow(); // Error display has a 5s debounce; rendering pipeline adds more delay under load
await editPage.start(
'/edit#pako:eNpljjEKwzAMRa8SNOcEnlt6gK5eVFvYJsgOqkwpIXevg9smEE1PnyfxF3DFExgISW-CczQ2D21cYU7a-SGYXRwyvTp9jUhuKlVP-eHy7zA-leQsMEmg_QOM0BLG5FujZVMsaCQmC6ahR5ks2Lw2r84ela4-aREwKpVGwKrl_s7ut3fnkjAIcg_XDzuaUhs'
);
// Wait for the gitGraph code to load in the editor before typing
await editPage.checkInEditor('gitGraph');
await editPage.typeInEditor('branch test', { bottom: true, newline: true });
await editPage.checkTextNotInView('test');
await editPage.checkInEditor('branch test');
+1 -1
View File
@@ -12,7 +12,7 @@ test.describe('Editor docs tests', () => {
test('Test to see if the correct URL loads when changing from one diagram to other', async ({
editPage
}) => {
await editPage.loadSampleDiagram('Flow');
await editPage.loadSampleDiagram('Flowchart');
await editPage.checkDocURL(/syntax\/flowchart\.html/);
await editPage.setEditorMode('Config');
await editPage.checkDocURL(/syntax\/flowchart\.html#configuration/);
+34
View File
@@ -0,0 +1,34 @@
import { test } from './test';
test.describe('Error display tests', () => {
test('should show AI Repair button for syntax errors in Code tab', async ({ editPage }) => {
// Enter code with syntax error
await editPage.clearEditor();
await editPage.typeInEditor('graph TD\nA --> B -->');
// Verify error is displayed
await editPage.checkError('Syntax error');
// Verify AI Repair button and help text is shown in Code tab
await editPage.checkAIHelperVisibility(true);
});
test('should not show AI Repair button for errors in Config tab', async ({ editPage }) => {
// First enter valid diagram
await editPage.clearEditor();
await editPage.typeInEditor('graph TD\nA --> B');
// Switch to Config tab
await editPage.setEditorMode('Config');
// Enter invalid JSON in config
await editPage.clearEditor();
await editPage.typeInEditor('{\n "theme": "default",\n invalid json');
// Verify error is displayed
await editPage.checkError('Syntax error');
// Verify AI Repair button and help text is NOT shown in Config tab
await editPage.checkAIHelperVisibility(false);
});
});
+16 -2
View File
@@ -1,4 +1,4 @@
import { TID } from '$/constants';
import { C, TID } from '$/constants';
import { test as base, expect, type Locator, type Page } from '@playwright/test';
import { verifyFileSizeGreaterThan, type EditorOptions } from './utils';
@@ -17,6 +17,7 @@ export class EditorPage {
await this.page.goto(url);
await expect(this.page)
.toHaveURL(/.*\/edit#pako/)
// eslint-disable-next-line @typescript-eslint/no-empty-function
.catch(() => {});
}
@@ -70,7 +71,9 @@ export class EditorPage {
}
async checkError(text: string) {
await expect(this.page.getByTestId(TID.errorContainer)).toContainText(text);
await expect(this.page.getByTestId(TID.errorContainer)).toContainText(text, {
timeout: 10_000
});
}
async checkInEditor(text: string) {
@@ -103,10 +106,21 @@ export class EditorPage {
`Switch to ${theme === 'light' ? 'dark' : 'light'} theme`
);
}
async checkAIHelperVisibility(shouldBeVisible: boolean) {
const button = this.page.getByTestId(TID.aiRepairButton);
const helpText = this.page.getByTestId(TID.aiHelpText);
await expect(button)[shouldBeVisible ? 'toBeVisible' : 'toBeHidden']();
await expect(helpText)[shouldBeVisible ? 'toBeVisible' : 'toBeHidden']();
}
}
export const test = base.extend<{ editPage: EditorPage }>({
editPage: async ({ page }, use) => {
// Dismiss the editor chooser modal so it doesn't block interactions
await page.addInitScript((key) => {
window.localStorage.setItem(key, 'true');
}, C.editorChooserDismissedKey);
const editorPage = new EditorPage(page);
await editorPage.start();
await editorPage.toggleSampleDiagrams();
+3 -6
View File
@@ -8,12 +8,10 @@ export interface EditorOptions {
newline?: boolean;
}
interface WindowWithEditor {
editorLoaded: boolean;
}
declare global {
interface Window extends WindowWithEditor {}
interface Window {
editorLoaded: boolean;
}
}
export async function typeInEditor(
@@ -44,7 +42,6 @@ export async function verifyFileSizeGreaterThan(
if (!path) throw new Error('Download path not available');
const fileSize = statSync(path).size;
expect(fileSize).toBeGreaterThan(size);
expect(fileSize).toBeLessThan(size * 2);
return fileSize;
}
+12 -14
View File
@@ -1,7 +1,9 @@
import tailwindcss from '@tailwindcss/vite';
import { sveltekit } from '@sveltejs/kit/vite';
import { FileSystemIconLoader } from 'unplugin-icons/loaders';
import Icons from 'unplugin-icons/vite';
import { defineConfig } from 'vitest/config';
import { defineConfig } from 'vite';
import devtoolsJson from 'vite-plugin-devtools-json';
/**
* HMR creates state inconsistencies, so we always reload the page.
@@ -17,6 +19,7 @@ const alwaysFullReload = {
export default defineConfig({
plugins: [
tailwindcss(),
sveltekit(),
Icons({
compiler: 'svelte',
@@ -24,17 +27,12 @@ export default defineConfig({
custom: FileSystemIconLoader('./static/icons')
}
}),
alwaysFullReload
alwaysFullReload,
devtoolsJson()
],
envPrefix: 'MERMAID_',
server: {
port: 3000,
host: true
},
preview: {
port: 3000,
host: true
},
server: { port: 3000, host: true },
preview: { port: 3000, host: true },
test: {
environment: 'jsdom',
// in-source testing
@@ -42,10 +40,10 @@ export default defineConfig({
// Ignore E2E tests
exclude: [
'tests/**/*',
'**\/node_modules/**',
'**\/dist/**',
'**\/.{idea,git,cache,output,temp}/**',
'**\/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build,eslint,prettier}.config.*'
'**/node_modules/**',
'**/dist/**',
'**/.{idea,git,cache,output,temp}/**',
'**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build,eslint,prettier}.config.*'
],
setupFiles: ['./src/tests/setup.ts'],
coverage: {