Compare commits

..
Author SHA1 Message Date
Sidharth Vinod 449dead2e5 fix: Race condition with async queue. 2022-10-19 00:27:36 +05:30
Sidharth Vinod aaec5912b4 fix: features spelling 2022-10-18 14:39:42 +05:30
Sidharth Vinod 187edf0f9f Merge branch 'sidv/tsMermaid' into sidv/mindmap
* sidv/tsMermaid:
  feat: New diagrams
  Rename samples
  Remove mermaid types
  Mermaid 9.2.0-rc1
2022-10-18 14:37:59 +05:30
Sidharth Vinod 5efc9ae10d Merge branch 'develop' into sidv/tsMermaid
* develop: (40 commits)
  Add tabindex
  chore: A11y changes
  chore(deps): update all non-major dependencies
  fix: favicon size
  Update Browserslist
  chore: Update favicon
  Update Browserslist
  chore(deps): update all non-major dependencies
  Update Browserslist
  Fix an issue where the image is jpg format on mermaid.ink
  chore(deps): update all non-major dependencies
  chore(deps): update all non-major dependencies
  chore: Remove stability days from renovate
  Update Browserslist
  chore(deps): update all non-major dependencies
  Update Browserslist
  chore(deps): update all non-major dependencies
  Update Browserslist
  chore(deps): update all non-major dependencies
  Update Browserslist
  ...
2022-10-18 14:36:20 +05:30
Sidharth Vinod 77522abef6 Merge branch 'develop' into sidv/mindmap
* develop:
  Add tabindex
2022-10-18 14:34:20 +05:30
Sidharth Vinod 90a4db2644 Merge branch 'develop' into sidv/mindmap
* develop:
  chore: A11y changes
2022-10-18 14:30:01 +05:30
Sidharth Vinod 7de5b3bfb1 Merge branch 'sidv/mindmap' of https://github.com/mermaid-js/mermaid-live-editor into sidv/mindmap
* 'sidv/mindmap' of https://github.com/mermaid-js/mermaid-live-editor:
  Update Browserslist
2022-10-18 12:26:05 +05:30
sidharthv96 826ccd983f Update Browserslist 2022-10-18 06:45:53 +00:00
Sidharth Vinod 78d3ed6e6c Merge branch 'develop' into sidv/mindmap
* develop:
  chore(deps): update all non-major dependencies
  fix: favicon size
  Update Browserslist
  chore: Update favicon
  Update Browserslist
  chore(deps): update all non-major dependencies
2022-10-18 12:15:42 +05:30
Sidharth Vinod 36083c849b fix: state url 2022-10-18 12:14:40 +05:30
Sidharth Vinod 29fc3fef21 fix: Ignore handle empty serialized state 2022-10-18 11:42:40 +05:30
Sidharth Vinod 1f3c74ae19 Merge branch 'sidv/mindmap' of https://github.com/mermaid-js/mermaid-live-editor into sidv/mindmap
* 'sidv/mindmap' of https://github.com/mermaid-js/mermaid-live-editor:
  Update Browserslist
2022-10-17 14:11:35 +05:30
Sidharth Vinod 433fd4d045 chore: ENV types, mindmap rc4 2022-10-17 14:11:26 +05:30
sidharthv96 814ce1aee3 Update Browserslist 2022-10-17 07:00:59 +00:00
Sidharth Vinod ce0517b782 Merge branch 'develop' into sidv/mindmap
* develop:
  Update Browserslist
  Fix an issue where the image is jpg format on mermaid.ink
2022-10-17 12:29:46 +05:30
sidharthv96 260d4970ae Update Browserslist 2022-10-17 06:31:20 +00:00
Sidharth Vinod 7f22aea3eb Async statestore, Update mermaid version 2022-10-17 12:00:02 +05:30
Sidharth Vinod b90cf45eff 9.2.0-rc5 2022-10-12 13:08:58 +05:30
Sidharth Vinod 020075da92 feat: lazy load 2022-10-12 12:26:04 +05:30
Sidharth Vinod de41008284 feat: Add lazyload 2022-10-11 13:49:20 +05:30
Sidharth Vinod bc9d53b701 feat: New diagrams 2022-09-09 23:18:02 +05:30
Sidharth Vinod c21db93399 Merge branch 'master' into sidv/tsMermaid
* master:
  chore(deps): update all non-major dependencies
  chore(deps): update dependency node-html-parser to v6
  chore(deps): update dependency font-awesome to v6
  chore(deps): update actions/setup-node action to v3
  fix(deps): pin dependency analytics-plugin-plausible to 0.0.6
2022-09-09 20:58:44 +05:30
Sidharth Vinod 9777be9a7b Rename samples 2022-09-09 20:58:32 +05:30
Sidharth Vinod 00b80d224c Remove mermaid types 2022-09-09 18:51:59 +05:30
Sidharth Vinod 2aa4666dab Merge branch 'master' into sidv/tsMermaid
* master:
  chore(deps): update all non-major dependencies
  chore(deps): update dependency @types/pako to v2
2022-09-09 18:49:48 +05:30
Sidharth Vinod 19c0c698ce Mermaid 9.2.0-rc1 2022-09-09 18:49:13 +05:30
88 changed files with 4099 additions and 4582 deletions
+48 -98
View File
@@ -1,100 +1,50 @@
module.exports = { module.exports = {
root: true, root: true,
parser: '@typescript-eslint/parser', parser: '@typescript-eslint/parser',
extends: [ extends: [
'eslint:recommended', 'eslint:recommended',
'plugin:@typescript-eslint/recommended', 'plugin:@typescript-eslint/recommended',
// 'plugin:@typescript-eslint/recommended-requiring-type-checking', // 'plugin:@typescript-eslint/recommended-requiring-type-checking',
'plugin:@typescript-eslint/strict', 'prettier'
'plugin:unicorn/recommended', ],
'prettier' plugins: ['svelte3', 'tailwindcss', '@typescript-eslint', 'es', 'vitest'],
], ignorePatterns: [
plugins: [ 'docs/*',
'svelte3', '*.cjs',
'tailwindcss', '*.js',
'@typescript-eslint', '*.md',
'es', 'snapshots.js',
'vitest', 'svelte.config.js',
'no-only-tests', 'renovate.json',
'unicorn' 'package.json',
], 'tsconfig.json'
ignorePatterns: [ ],
'docs/*', overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }],
'*.cjs', settings: {
'*.js', 'svelte3/typescript': () => require('typescript')
'*.md', },
'snapshots.js', parserOptions: {
'svelte.config.js', sourceType: 'module',
'renovate.json', ecmaVersion: 2020,
'package.json', tsconfigRootDir: __dirname,
'tsconfig.json' project: ['./tsconfig.json'],
], extraFileExtensions: ['.svelte'],
overrides: [ allowAutomaticSingleRunInference: true
{ files: ['*.svelte'], processor: 'svelte3/svelte3' }, },
{ env: {
files: ['*.ts'], browser: true,
extends: [ es2020: true
'eslint:recommended', },
'plugin:@typescript-eslint/recommended', rules: {
'plugin:@typescript-eslint/recommended-requiring-type-checking', '@typescript-eslint/ban-ts-comment': [
'plugin:@typescript-eslint/strict', 'error',
'prettier' {
] 'ts-ignore': 'allow-with-description'
} }
], ],
settings: { '@typescript-eslint/no-unsafe-member-access': 'off',
'svelte3/typescript': () => require('typescript') '@typescript-eslint/no-unsafe-assignment': 'off',
}, 'es/no-regexp-lookbehind-assertions': 'error',
parserOptions: { curly: ['error', 'all']
sourceType: 'module', }
ecmaVersion: 2020,
tsconfigRootDir: __dirname,
project: ['./tsconfig.json'],
extraFileExtensions: ['.svelte'],
allowAutomaticSingleRunInference: true
},
env: {
browser: true,
es2020: true
},
rules: {
'@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/prevent-abbreviations': [
'error',
{
allowList: {
ctx: true,
db: true,
doc: true,
env: true,
fn: true,
i: true,
param: true,
req: true,
res: true,
str: true,
searchParams: true,
temp: true,
ImportMetaEnv: true
}
}
]
}
}; };
-5
View File
@@ -1,5 +0,0 @@
# .git-blame-ignore-revs
# Prettier Pass
6fde9e22a3ba0b80879a1909fb233367ef20b738
# Tabs -> Spaces
0ac606b8fbf6f94215cbda1d4511e2dcd30e4655
-1
View File
@@ -1 +0,0 @@
github: [sidharthv96, knsv]
+1 -1
View File
@@ -16,7 +16,7 @@ jobs:
- uses: actions/setup-node@v3 - uses: actions/setup-node@v3
with: with:
node-version: 18 node-version: '16'
cache: yarn cache: yarn
- name: Build & Deploy - name: Build & Deploy
+1 -1
View File
@@ -8,7 +8,7 @@ jobs:
stale: stale:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/stale@v6 - uses: actions/stale@v5
with: with:
repo-token: ${{ secrets.GITHUB_TOKEN }} repo-token: ${{ secrets.GITHUB_TOKEN }}
exempt-issue-labels: 'retained' exempt-issue-labels: 'retained'
+1 -2
View File
@@ -32,7 +32,7 @@ jobs:
- uses: actions/setup-node@v3 - uses: actions/setup-node@v3
with: with:
node-version: 18 node-version: 16
cache: 'yarn' cache: 'yarn'
# Install NPM dependencies, cache them correctly # Install NPM dependencies, cache them correctly
@@ -48,4 +48,3 @@ jobs:
parallel: true parallel: true
env: env:
CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }} CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }}
CYPRESS_CI: true
+1 -1
View File
@@ -26,7 +26,7 @@ jobs:
- uses: actions/setup-node@v3 - uses: actions/setup-node@v3
with: with:
node-version: 18 node-version: 16
cache: 'yarn' cache: 'yarn'
- name: Lint & Test - name: Lint & Test
+13 -27
View File
@@ -1,32 +1,18 @@
name: Update Browserslist database name: Update Browserslist
on: on:
schedule: push:
- cron: '0 2 1,15 * *' branches-ignore:
- 'develop'
permissions: - 'master'
contents: write
pull-requests: write
jobs: jobs:
update-browserslist-database: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout repository - uses: actions/checkout@v3
uses: actions/checkout@v3 - run: npx browserslist@latest --update-db
- name: Commit changes
uses: EndBug/add-and-commit@v9
with: with:
fetch-depth: 0 author_name: ${{ github.actor }}
- name: Configure git author_email: ${{ github.actor }}@users.noreply.github.com
run: | message: 'Update Browserslist'
git config --global user.email "action@github.com"
git config --global user.name "GitHub Action"
- name: Update Browserslist database and create PR if applies
uses: c2corg/browserslist-update-action@v2
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: browserslist-update
base_branch: develop
commit_message: 'build: update Browserslist db'
title: 'build: update Browserslist db'
body: Auto-generated by [browserslist-update-action](https://github.com/c2corg/browserslist-update-action/)
labels: 'chores, github action'
+6 -5
View File
@@ -1,7 +1,8 @@
{ {
"singleQuote": true, "singleQuote": true,
"svelteSortOrder": "options-scripts-markup-styles", "svelteSortOrder": "options-scripts-markup-styles",
"bracketSameLine": true, "bracketSameLine": true,
"trailingComma": "none", "useTabs": true,
"printWidth": 100 "trailingComma": "none",
"printWidth": 100
} }
+13 -13
View File
@@ -1,15 +1,15 @@
{ {
// Use IntelliSense to learn about possible attributes. // Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes. // Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0", "version": "0.2.0",
"configurations": [ "configurations": [
{ {
"type": "pwa-chrome", "type": "pwa-chrome",
"request": "launch", "request": "launch",
"name": "Launch Chrome against localhost", "name": "Launch Chrome against localhost",
"url": "http://localhost:3000", "url": "http://localhost:3000",
"webRoot": "${workspaceFolder}" "webRoot": "${workspaceFolder}"
} }
] ]
} }
+7 -21
View File
@@ -1,23 +1,9 @@
{ {
"editor.formatOnSave": true, "editor.formatOnSave": true,
"cSpell.words": [ "cSpell.words": ["pako", "Serde", "serdes"],
"Browserslist", "vitest.commandLine": "yarn test:unit",
"KROKI", "vitest.enable": true,
"Serde", "testing.autoRun.mode": "rerun",
"asyncable", "svelte.enable-ts-plugin": true,
"corg", "githubPullRequests.ignoredPullRequestBranches": ["develop"]
"cssnano",
"daisyui",
"esserializer",
"localstorage",
"mindmap",
"pako",
"serdes",
"tailwindcss"
],
"vitest.commandLine": "yarn test:unit",
"vitest.enable": true,
"testing.autoRun.mode": "rerun",
"svelte.enable-ts-plugin": true,
"githubPullRequests.ignoredPullRequestBranches": ["develop"]
} }
+1 -1
View File
@@ -6,7 +6,7 @@
# Stop : press ctrl + c # Stop : press ctrl + c
# or # or
# docker stop mermaid-live-editor # docker stop mermaid-live-editor
FROM node:18.14.0 as mermaid-live-editor-builder FROM node:18.11.0 as mermaid-live-editor-builder
COPY --chown=node:node . /home COPY --chown=node:node . /home
WORKDIR /home WORKDIR /home
RUN yarn install RUN yarn install
+6 -9
View File
@@ -47,20 +47,17 @@ Then open http://localhost:8000
## Setup ## Setup
Below link will help you making a copy of the repository in your local system. [Volta](https://volta.sh) is used for managing node and yarn versions.
https://docs.github.com/en/get-started/quickstart/fork-a-repo This project is set up using [Yarn](https://classic.yarnpkg.com/en/docs/getting-started):
## Requirements ```
yarn install
- [volta](https://volta.sh/) to manage node versions. ```
- [Node.js](https://nodejs.org/en/). `volta install node`
- [yarn](https://yarnpkg.com/) package manager. `volta install yarn`
## Development ## Development
```sh ```
yarn install
yarn dev -- --open yarn dev -- --open
``` ```
+28 -28
View File
@@ -9,37 +9,37 @@ const monacoVersion = packageJson.dependencies['monaco-editor'].replace('^', '')
// fetch monaco sri info from cdnjs api // fetch monaco sri info from cdnjs api
const cdnjsAPIResp = await fetch( const cdnjsAPIResp = await fetch(
`https://api.cdnjs.com/libraries/monaco-editor/${monacoVersion}?fields=sri` `https://api.cdnjs.com/libraries/monaco-editor/${monacoVersion}?fields=sri`
); );
if (cdnjsAPIResp.ok) { if (cdnjsAPIResp.ok) {
const respJson = await cdnjsAPIResp.json(); const respJson = await cdnjsAPIResp.json();
const htmlPath = path.join('src', 'app.html'); const htmlPath = path.join('src', 'app.html');
const appHtml = fs const appHtml = fs
.readFileSync(htmlPath, 'utf8') .readFileSync(htmlPath, 'utf8')
// update monaco version of every asset in app.html // update monaco version of every asset in app.html
.replaceAll(/[0-9.]+\/min\/vs/g, `${monacoVersion}/min/vs`); .replaceAll(/[0-9.]+\/min\/vs/g, `${monacoVersion}/min/vs`);
const root = parse(appHtml); const root = parse(appHtml);
const updateIntegrity = (tag, attr) => { const updateIntegrity = (tag, attr) => {
for (const node of root for (const node of root
.getElementsByTagName(tag) .getElementsByTagName(tag)
.filter((node) => node.getAttribute(attr)?.includes('monaco-editor'))) { .filter((node) => node.getAttribute(attr)?.includes('monaco-editor'))) {
const file = node.getAttribute(attr).split(`${monacoVersion}/`)[1]; const file = node.getAttribute(attr).split(`${monacoVersion}/`)[1];
node.setAttribute('integrity', respJson.sri[file]); node.setAttribute('integrity', respJson.sri[file]);
} }
}; };
updateIntegrity('script', 'src'); updateIntegrity('script', 'src');
updateIntegrity('link', 'href'); updateIntegrity('link', 'href');
fs.writeFileSync( fs.writeFileSync(
htmlPath, htmlPath,
prettier.format(root.toString(), { prettier.format(root.toString(), {
singleQuote: false, singleQuote: false,
parser: 'html', parser: 'html',
bracketSameLine: true, bracketSameLine: true,
useTabs: true useTabs: true
}) })
); );
} else { } else {
throw Error('Unable to fetch monaco sri data from cdnjs api.'); throw Error('Unable to fetch monaco sri data from cdnjs api.');
} }
+30 -30
View File
@@ -2,34 +2,34 @@ import { defineConfig } from 'cypress';
import fs from 'fs'; import fs from 'fs';
import { isFileExist, findFiles } from 'cy-verify-downloads'; import { isFileExist, findFiles } from 'cy-verify-downloads';
export default defineConfig({ export default defineConfig({
projectId: '2ckppp', projectId: '2ckppp',
viewportWidth: 1440, viewportWidth: 1440,
viewportHeight: 768, viewportHeight: 768,
snapshotFileName: './cypress/snapshots.js', snapshotFileName: './cypress/snapshots.js',
defaultCommandTimeout: 16000, defaultCommandTimeout: 16000,
requestTimeout: 16000, requestTimeout: 16000,
retries: { retries: {
runMode: 4, runMode: 4,
openMode: 0 openMode: 0
}, },
e2e: { e2e: {
setupNodeEvents(on, config) { setupNodeEvents(on, config) {
on('task', { on('task', {
isFileExist, isFileExist,
findFiles, findFiles,
deleteFile(path) { deleteFile(path) {
fs.rmSync(path); fs.rmSync(path);
return null; return null;
}, },
readFileMaybe(filename) { readFileMaybe(filename) {
if (fs.existsSync(filename)) { if (fs.existsSync(filename)) {
return fs.readFileSync(filename, 'utf8'); return fs.readFileSync(filename, 'utf8');
} }
return null; return null;
} }
}); });
}, },
baseUrl: 'http://localhost:3000', baseUrl: 'http://localhost:3000',
specPattern: 'cypress/e2e/**/*.spec.ts' specPattern: 'cypress/e2e/**/*.spec.ts'
} }
}); });
+8 -8
View File
@@ -1,10 +1,10 @@
{ {
"plugins": ["cypress"], "plugins": ["cypress"],
"extends": ["plugin:cypress/recommended"], "extends": ["plugin:cypress/recommended"],
"rules": { "rules": {
"jest/expect-expect": "off" "jest/expect-expect": "off"
}, },
"env": { "env": {
"cypress/globals": true "cypress/globals": true
} }
} }
+37 -38
View File
@@ -1,49 +1,48 @@
import { verifyFileSizeGreaterThan } from './util'; import { verifyFileSize } from './util';
describe('Check actions', () => { describe('Check actions', () => {
beforeEach(() => { beforeEach(() => {
cy.clearLocalStorage(); cy.clearLocalStorage();
cy.visit('/edit'); cy.visit('/edit');
cy.contains('Actions').click(); });
});
it('should update markdown code', () => { it('should update markdown code', () => {
cy.get('#markdown') cy.get('#markdown')
.invoke('val') .invoke('val')
.then((oldText) => { .then((oldText) => {
cy.get('#editor').click('bottom').type('{enter}C --> HistoryTest'); cy.get('#editor').click('bottom').type('{enter}C --> HistoryTest');
cy.get('#markdown') cy.get('#markdown')
.invoke('val') .invoke('val')
.then((newText) => { .then((newText) => {
expect(oldText).to.not.eq(newText); expect(oldText).to.not.eq(newText);
}); });
}); });
}); });
it.skip('should load gists from URL', () => { it('should load gists from URL', () => {
cy.get('#gist').type('https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a'); cy.get('#gist').type('https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a');
cy.contains('Load Gist').click(); cy.contains('Load Gist').click();
cy.contains('Go shopping!!'); cy.contains('Go shopping!!');
}); });
it('should download png and svg', () => { it('should download png and svg', () => {
cy.clock(new Date(2022, 0, 1).getTime()); cy.clock(new Date(2022, 0, 1).getTime());
cy.get(`#downloadPNG`).click(); cy.get(`#downloadPNG`).click();
verifyFileSizeGreaterThan('diagram', 'png', 35_000); verifyFileSize('diagram', 'png', 21_000);
cy.get(`#downloadSVG`).click(); cy.get(`#downloadSVG`).click();
verifyFileSizeGreaterThan('diagram', 'svg', 10_000); verifyFileSize('diagram', 'svg', 10_000);
// Verify downloaded file is different for different diagrams // Verify downloaded file is different for different diagrams
cy.contains('Sample Diagrams').click(); cy.contains('Sample Diagrams').click();
cy.contains('ER').click(); cy.contains('ER').click();
cy.get(`#downloadPNG`).click(); cy.get(`#downloadPNG`).click();
verifyFileSizeGreaterThan('diagram', 'png', 40_000); verifyFileSize('diagram', 'png', 46_000);
cy.get(`#downloadSVG`).click(); cy.get(`#downloadSVG`).click();
verifyFileSizeGreaterThan('diagram', 'svg', 11_000); verifyFileSize('diagram', 'svg', 12_000);
cy.clock().invoke('restore'); cy.clock().invoke('restore');
}); });
}); });
+73 -81
View File
@@ -1,94 +1,86 @@
import { getEditor, cmd } from './util'; import { getEditor, cmd } from './util';
describe('Auto sync tests', () => { describe('Auto sync tests', () => {
beforeEach(() => { beforeEach(() => {
cy.clearLocalStorage(); cy.clearLocalStorage();
cy.visit('/'); cy.visit('/');
}); });
it('should dim diagram when code is edited', () => { it('should dim diagram when code is edited', () => {
cy.contains('Auto sync').click(); cy.contains('Auto sync').click();
cy.get('#view').should('not.have.class', 'outOfSync'); cy.get('#view').should('not.have.class', 'outOfSync');
cy.get('#errorContainer').should('not.exist'); cy.get('#view').should('not.contain.text', 'Diagram out of sync.');
getEditor({ bottom: true, newline: true }).type(' C --> Test'); getEditor().type(' C --> Test');
cy.get('#view').should('have.class', 'outOfSync'); cy.get('#view').should('have.class', 'outOfSync');
cy.get('#errorContainer').should('contain.text', 'Diagram out of sync.'); cy.get('#view').should('contain.text', 'Diagram out of sync.');
cy.getLocalStorage('codeStore').snapshot(); cy.getLocalStorage('codeStore').snapshot();
}); });
it('should update diagram when shortcut is used', () => { it('should update diagram when shortcut is used', () => {
cy.contains('Auto sync').click(); cy.contains('Auto sync').click();
cy.get('#view').should('not.have.class', 'outOfSync'); cy.get('#view').should('not.have.class', 'outOfSync');
getEditor().type(' C --> Test'); getEditor().type(' C --> Test');
cy.get('#view').should('have.class', 'outOfSync'); cy.get('#view').should('have.class', 'outOfSync');
cy.get('#errorContainer').should('contain.text', 'Diagram out of sync.'); cy.get('#view').should('contain.text', 'Diagram out of sync.');
getEditor().type(`${cmd}{enter}`); getEditor().type(`${cmd}{enter}`);
cy.get('#errorContainer').should('not.exist'); cy.get('#view').should('not.contain.text', 'Diagram out of sync.');
cy.get('#view').should('not.have.class', 'outOfSync'); cy.get('#view').should('not.have.class', 'outOfSync');
}); });
it('should show/hide sync button with auto sync', () => { it('should show/hide sync button with auto sync', () => {
cy.get('[data-cy=sync]').should('not.exist'); cy.get('[data-cy=sync]').should('not.exist');
cy.contains('Auto sync').click(); cy.contains('Auto sync').click();
cy.get('[data-cy=sync]').should('exist'); cy.get('[data-cy=sync]').should('exist');
cy.get('#autoSync').check(); cy.get('#autoSync').check();
cy.get('[data-cy=sync]').should('not.exist'); cy.get('[data-cy=sync]').should('not.exist');
}); });
it('should not dim diagram when code is in sync', () => { it('should not dim diagram when code is in sync', () => {
cy.contains('Auto sync').click(); cy.contains('Auto sync').click();
cy.get('#view').should('not.have.class', 'outOfSync'); cy.get('#view').should('not.have.class', 'outOfSync');
getEditor().type(' C --> Test'); getEditor().type(' C --> Test');
cy.get('#view').should('have.class', 'outOfSync'); cy.get('#view').should('have.class', 'outOfSync');
cy.get('[data-cy=sync]').click(); cy.get('[data-cy=sync]').click();
cy.get('#view').should('not.have.class', 'outOfSync'); cy.get('#view').should('not.have.class', 'outOfSync');
cy.get('#autoSync').check(); cy.get('#autoSync').check();
getEditor().type('ing'); getEditor().type('ing');
cy.get('#view').should('not.have.class', 'outOfSync'); cy.get('#view').should('not.have.class', 'outOfSync');
cy.getLocalStorage('codeStore').snapshot(); cy.getLocalStorage('codeStore').snapshot();
}); });
it('supports commenting code out/in', () => { it('supports commenting code out/in', () => {
getEditor({ bottom: true, newline: false }).type(`{uparrow}${cmd}/`); getEditor().type(`{uparrow}${cmd}/`);
cy.get('#view').contains('Car').should('not.exist'); cy.get('#view').contains('Car').should('not.exist');
getEditor().type(`{uparrow}${cmd}/`); getEditor().type(`{uparrow}${cmd}/`);
cy.get('#view').contains('Car').should('exist'); cy.get('#view').contains('Car').should('exist');
}); });
it('supports editing code when code is incorrect', () => { it('supports editing code when code is incorrect', () => {
cy.visit( cy.visit(
'/edit#pako:eNpljjEKwzAMRa8SNOcEnlt6gK5eVFvYJsgOqkwpIXevg9smEE1PnyfxF3DFExgISW-CczQ2D21cYU7a-SGYXRwyvTp9jUhuKlVP-eHy7zA-leQsMEmg_QOM0BLG5FujZVMsaCQmC6ahR5ks2Lw2r84ela4-aREwKpVGwKrl_s7ut3fnkjAIcg_XDzuaUhs' '/edit#pako:eNpljjEKwzAMRa8SNOcEnlt6gK5eVFvYJsgOqkwpIXevg9smEE1PnyfxF3DFExgISW-CczQ2D21cYU7a-SGYXRwyvTp9jUhuKlVP-eHy7zA-leQsMEmg_QOM0BLG5FujZVMsaCQmC6ahR5ks2Lw2r84ela4-aREwKpVGwKrl_s7ut3fnkjAIcg_XDzuaUhs'
); );
cy.get('#errorContainer').should('not.exist'); cy.get('#errorContainer').should('not.exist');
getEditor({ newline: true }).type(`branch test`); getEditor({ newline: true }).type(`branch test`);
cy.get('#editor').contains('branch test').should('exist'); cy.get('#editor').contains('branch test').should('exist');
cy.get('#errorContainer') cy.get('#errorContainer')
.contains( .contains(
'Error: Trying to checkout branch which is not yet created. (Help try using "branch master")' 'Error: Trying to checkout branch which is not yet created. (Help try using "branch master")'
) )
.should('exist'); .should('exist');
}); });
it('should update diagram after entire text is removed', () => {
// https://github.com/mermaid-js/mermaid-live-editor/issues/1102
getEditor().type(`${cmd} a {backspace}`);
getEditor().type('graph LR');
getEditor().type(' {enter} A-->Car');
cy.get('#view').contains('Car').should('exist');
});
}); });
describe('Pan and Zoom', () => { describe.only('Pan and Zoom', () => {
beforeEach(() => { beforeEach(() => {
cy.clearLocalStorage(); cy.clearLocalStorage();
cy.visit('/'); cy.visit('/');
}); });
it('should toggle pan and zoom', () => { it('should toggle pan and zoom', () => {
cy.get('#svg-pan-zoom-reset-pan-zoom').should('not.exist'); cy.get('#svg-pan-zoom-reset-pan-zoom').should('not.exist');
cy.contains('Pan & Zoom').click(); cy.contains('Pan & Zoom').click();
cy.get('#svg-pan-zoom-reset-pan-zoom').should('exist'); cy.get('#svg-pan-zoom-reset-pan-zoom').should('exist');
cy.contains('Pan & Zoom').click(); cy.contains('Pan & Zoom').click();
cy.get('#svg-pan-zoom-reset-pan-zoom').should('not.exist'); cy.get('#svg-pan-zoom-reset-pan-zoom').should('not.exist');
}); });
}); });
+27 -27
View File
@@ -1,36 +1,36 @@
describe('Editor docs tests', () => { describe('Editor docs tests', () => {
beforeEach(() => { beforeEach(() => {
cy.on('uncaught:exception', () => { cy.on('uncaught:exception', () => {
return false; return false;
}); });
cy.clearLocalStorage(); cy.clearLocalStorage();
cy.visit('/edit'); cy.visit('/edit');
cy.contains('Sample Diagrams').click(); cy.contains('Sample Diagrams').click();
}); });
it('Test default loading', () => { it('Test default loading', () => {
cy.get(`[data-cy=docs][href^="https://mermaid-js.github.io/mermaid"]`).should('exist'); cy.get(`[data-cy=docs][href^="https://mermaid-js.github.io/mermaid"]`).should('exist');
}); });
it('Test to see if the correct URL loads when changing from one diagram to other', () => { it('Test to see if the correct URL loads when changing from one diagram to other', () => {
cy.contains('Flow').click(); cy.contains('Flow').click();
cy.get(`[data-cy=docs][href$="/#/flowchart"]`).should('exist'); cy.get(`[data-cy=docs][href$="/#/flowchart"]`).should('exist');
cy.contains('Config').click(); cy.contains('Config').click();
cy.get(`[data-cy=docs][href$="/#/flowchart?id=configuration"]`).should('exist'); cy.get(`[data-cy=docs][href$="/#/flowchart?id=configuration"]`).should('exist');
cy.contains('Sequence').click(); cy.contains('Sequence').click();
cy.get(`[data-cy=docs][href$="/#/sequenceDiagram?id=configuration"]`).should('exist'); cy.get(`[data-cy=docs][href$="/#/sequenceDiagram?id=configuration"]`).should('exist');
cy.contains('Code').click(); cy.contains('Code').click();
cy.get(`[data-cy=docs][href$="/#/sequenceDiagram"]`).should('exist'); cy.get(`[data-cy=docs][href$="/#/sequenceDiagram"]`).should('exist');
}); });
it("Test to check URLs for a case where config URL doesn't exist", () => { it("Test to check URLs for a case where config URL doesn't exist", () => {
cy.contains('State').click(); cy.contains('State').click();
cy.get(`[data-cy=docs][href$="/#/stateDiagram"]`).should('exist'); cy.get(`[data-cy=docs][href$="/#/stateDiagram"]`).should('exist');
cy.contains('Config').click(); cy.contains('Config').click();
cy.get(`[data-cy=docs][href$="/#/stateDiagram"]`).should('exist'); cy.get(`[data-cy=docs][href$="/#/stateDiagram"]`).should('exist');
}); });
}); });
+93 -91
View File
@@ -1,103 +1,105 @@
import { getEditor, verifyFileSnapshot } from './util'; import { getEditor, verifyFileSnapshot } from './util';
describe('Save History', () => { describe('Save History', () => {
beforeEach(() => { beforeEach(() => {
cy.clock(new Date(2022, 0, 1).getTime()); cy.clock(new Date(2022, 0, 1).getTime());
cy.clearLocalStorage(); cy.clearLocalStorage();
cy.visit('/edit'); cy.visit('/edit');
cy.contains('History').click(); cy.contains('Actions').click();
}); cy.contains('History').click();
});
afterEach(() => { afterEach(() => {
cy.clock().invoke('restore'); cy.clock().invoke('restore');
}); });
it('should load history from localstorage', () => { it('should load history from localstorage', () => {
cy.setLocalStorage( cy.setLocalStorage(
'manualHistoryStore', 'manualHistoryStore',
'[{"state":{"code":"graph TD\\n A[Halloween] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":false},"time":0,"type":"manual","id":"d7ea820e-21dd-418a-b984-fd58acde09df","name":"hollow-art"},{"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","id":"b749ffc6-522b-4a44-86cf-7c1ffc3146b3","name":"helpful-ocean"}]' '[{"state":{"code":"graph TD\\n A[Halloween] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":false},"time":0,"type":"manual","id":"d7ea820e-21dd-418a-b984-fd58acde09df","name":"hollow-art"},{"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","id":"b749ffc6-522b-4a44-86cf-7c1ffc3146b3","name":"helpful-ocean"}]'
); );
cy.setLocalStorage( cy.setLocalStorage(
'autoHistoryStore', 'autoHistoryStore',
'[{"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","id":"69ea820e-522b-4a44-86cf-fd58acde09df","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","id":"x749ffc6-21dd-418a-b984-7c1ffc3146b3","name":"needy-mosquito"}]' '[{"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","id":"69ea820e-522b-4a44-86cf-fd58acde09df","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","id":"x749ffc6-21dd-418a-b984-7c1ffc3146b3","name":"needy-mosquito"}]'
); );
cy.reload(); cy.reload();
cy.contains('History').click(); cy.contains('Actions').click();
cy.get('#historyList').find('li').should('have.length', 2); cy.contains('History').click();
cy.get('#historyList').find('No items in History').should('not.exist'); cy.get('#historyList').find('li').should('have.length', 2);
cy.get('#historyList').contains('helpful-ocean'); cy.get('#historyList').find('No items in History').should('not.exist');
cy.get('#historyList').contains('hollow-art'); cy.get('#historyList').contains('helpful-ocean');
cy.contains('Restore').click(); cy.get('#historyList').contains('hollow-art');
cy.contains('Halloween'); cy.contains('Restore').click();
cy.contains('Timeline').click(); cy.contains('Halloween');
cy.contains('Timeline').click();
cy.get('#historyList').find('li').should('have.length', 2); cy.get('#historyList').find('li').should('have.length', 2);
cy.get('#historyList').find('No items in History').should('not.exist'); cy.get('#historyList').find('No items in History').should('not.exist');
cy.get('#historyList').contains('needy-mosquito'); cy.get('#historyList').contains('needy-mosquito');
cy.get('#historyList').contains('barking-dog'); cy.get('#historyList').contains('barking-dog');
cy.contains('Restore').click(); cy.contains('Restore').click();
cy.contains('New Year'); cy.contains('New Year');
}); });
it('should save when clicked', () => { it('should save when clicked', () => {
cy.get('#historyList').find('li').should('have.length', 0); cy.get('#historyList').find('li').should('have.length', 0);
cy.get('#historyList').contains('No items in History'); cy.get('#historyList').contains('No items in History');
cy.get('#saveHistory').click(); cy.get('#saveHistory').click();
cy.get('#historyList').find('No items in History').should('not.exist'); cy.get('#historyList').find('No items in History').should('not.exist');
cy.get('#historyList').find('li').should('have.length', 1); cy.get('#historyList').find('li').should('have.length', 1);
cy.get('#saveHistory').click(); cy.get('#saveHistory').click();
cy.on('window:alert', (str) => { cy.on('window:alert', (str) => {
expect(str).to.equal('State already saved.'); expect(str).to.equal('State already saved.');
}); });
cy.on('window:confirm', () => true); cy.on('window:confirm', () => true);
getEditor().type(' C --> HistoryTest'); getEditor().type(' C --> HistoryTest');
cy.get('#saveHistory').click(); cy.get('#saveHistory').click();
cy.get('#historyList').find('li').should('have.length', 2); cy.get('#historyList').find('li').should('have.length', 2);
}); });
it('should be able to restore and delete', () => { it('should be able to restore and delete', () => {
cy.get('#saveHistory').click(); cy.get('#saveHistory').click();
getEditor().type(' C --> HistoryTest'); getEditor().type(' C --> HistoryTest');
cy.get('#historyList').find('No items in History').should('not.exist'); cy.get('#historyList').find('No items in History').should('not.exist');
cy.get('#historyList').find('li').should('have.length', 1); cy.get('#historyList').find('li').should('have.length', 1);
cy.contains('HistoryTest'); cy.contains('HistoryTest');
cy.contains('Restore').click(); cy.contains('Restore').click();
cy.contains('HistoryTest').should('not.exist'); cy.contains('HistoryTest').should('not.exist');
cy.contains('Delete').click(); cy.contains('Delete').click();
cy.get('#historyList').find('li').should('have.length', 0); cy.get('#historyList').find('li').should('have.length', 0);
cy.get('#historyList').contains('No items in History'); cy.get('#historyList').contains('No items in History');
cy.get('#saveHistory').click(); cy.get('#saveHistory').click();
getEditor().type(' C --> HistoryTest'); getEditor().type(' C --> HistoryTest');
cy.get('#saveHistory').click(); cy.get('#saveHistory').click();
cy.get('#editor').type('ing'); cy.get('#editor').type('ing');
cy.get('#clearHistory').click(); cy.get('#clearHistory').click();
cy.on('window:alert', (str) => { cy.on('window:alert', (str) => {
expect(str).to.equal('Clear all saved items?'); expect(str).to.equal('Clear all saved items?');
}); });
cy.on('window:confirm', () => true); cy.on('window:confirm', () => true);
cy.get('#historyList').contains('No items in History'); cy.get('#historyList').contains('No items in History');
}); });
// TODO: Fix #639 // TODO: Fix #639
xit('should auto save history', () => { xit('should auto save history', () => {
getEditor().type(' C --> HistoryTest'); getEditor().type(' C --> HistoryTest');
cy.tick(70_000); cy.tick(70000);
cy.contains('Timeline').click(); cy.contains('Timeline').click();
cy.get('#historyList').find('li').should('have.length', 1); cy.get('#historyList').find('li').should('have.length', 1);
cy.get('#editor').type('ing'); cy.get('#editor').type('ing');
cy.tick(70_000); cy.tick(70000);
cy.get('#historyList').find('li').should('have.length', 2); cy.get('#historyList').find('li').should('have.length', 2);
for (let i = 0; i < 31; i++) { for (let i = 0; i < 31; i++) {
cy.get('#editor').type('.'); cy.get('#editor').type('.');
cy.tick(70_000); cy.tick(70000);
} }
cy.get('#historyList').find('li').should('have.length', 30); cy.get('#historyList').find('li').should('have.length', 30);
}); });
it('should download history', () => { it('should download history', () => {
cy.get('#saveHistory').click(); cy.get('#saveHistory').click();
cy.get(`#downloadHistory`).click(); cy.get(`#downloadHistory`).click();
verifyFileSnapshot('history', 'json', 'A[Christmas] -->|Get money| B(Go shopping)'); verifyFileSnapshot('history', 'json', 'A[Christmas] -->|Get money| B(Go shopping)');
}); });
}); });
+104 -108
View File
@@ -1,122 +1,118 @@
import { toBase64 } from 'js-base64'; import { toBase64 } from 'js-base64';
describe('Site Loads', () => { describe('Site Loads', () => {
beforeEach(() => { beforeEach(() => {
cy.clearLocalStorage(); cy.clearLocalStorage();
cy.visit('/'); cy.visit('/');
}); });
it('Check Home page load', () => {
cy.url().should('include', '/edit');
cy.contains('History').click();
cy.getLocalStorage('codeStore').snapshot();
});
it('Check Home page load', () => { it('Check Redirect from old URL', () => {
cy.url().should('include', '/edit'); cy.visit(
cy.contains('History').click(); '/#/edit/eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW0NocmlzdG1hc10gLS0-fEdldCBtb25leXwgQihHbyBzaG9wcGluZylcbiAgICBCIC0tPiBDe0xldCBtZSB0aGlua31cbiAgICBDIC0tPnxPbmV8IERbTGFwdG9wXVxuICAgIEMgLS0-fFR3b3wgRVtpUGhvbmVdXG4gICAgQyAtLT58VGhyZWV8IEZbZmE6ZmEtY2FyIENhcl0iLCJtZXJtYWlkIjp7InRoZW1lIjoiZGVmYXVsdCJ9LCJ1cGRhdGVFZGl0b3IiOmZhbHNlfQ'
cy.getLocalStorage('codeStore').snapshot(); );
}); cy.url().should('include', '/edit#pako:eNp');
});
it('Check Redirect from old URL', () => { it('should load sample diagrams when clicked', () => {
cy.visit( cy.contains('Sample Diagrams').click();
'/#/edit/eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW0NocmlzdG1hc10gLS0-fEdldCBtb25leXwgQihHbyBzaG9wcGluZylcbiAgICBCIC0tPiBDe0xldCBtZSB0aGlua31cbiAgICBDIC0tPnxPbmV8IERbTGFwdG9wXVxuICAgIEMgLS0-fFR3b3wgRVtpUGhvbmVdXG4gICAgQyAtLT58VGhyZWV8IEZbZmE6ZmEtY2FyIENhcl0iLCJtZXJtYWlkIjp7InRoZW1lIjoiZGVmYXVsdCJ9LCJ1cGRhdGVFZGl0b3IiOmZhbHNlfQ' cy.contains('Pie').click();
); cy.contains('pie title Pets adopted by volunteers');
cy.url().should('include', '/edit#pako:eNp'); cy.contains('Class').click();
}); cy.contains('classDiagram');
});
it('should load sample diagrams when clicked', () => { it('should load diagram from gist', () => {
cy.contains('Sample Diagrams').click(); cy.visit(`/edit?gist=https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a`);
cy.contains('Pie').click(); cy.contains('History').click();
cy.contains('pie title Pets adopted by volunteers'); cy.contains('Go shopping!!');
cy.contains('Class').click(); cy.contains('Revisions');
cy.contains('classDiagram'); cy.contains('sidharthv96 v8f8f1e2');
}); cy.contains('sidharthv96 v7851e19');
cy.getLocalStorage('codeStore').snapshot();
});
(Cypress.env('CI') === 'true' ? describe : describe.skip)('github', () => { it('should load diagram from gist revision', () => {
it('should load diagram from gist', () => { cy.visit(
cy.visit(`/edit?gist=https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a`); '/edit?gist=https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/ec9b4ab0e41e4ff6287326cd3cb47affd7851e19'
cy.contains('History').click(); );
cy.contains('Go shopping!!'); cy.contains('History').click();
cy.contains('Revisions'); cy.contains('Party');
cy.contains('sidharthv96 v8f8f1e2'); cy.contains('Revisions');
cy.contains('sidharthv96 v7851e19'); cy.contains('sidharthv96 v7851e19');
cy.getLocalStorage('codeStore').snapshot(); cy.getLocalStorage('codeStore').snapshot();
}); });
it('should load diagram from gist revision', () => { it('should load diagram from raw files', () => {
cy.visit( cy.visit(
'/edit?gist=https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/ec9b4ab0e41e4ff6287326cd3cb47affd7851e19' '/edit?code=https://gist.githubusercontent.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/raw/4eb03887e6a41397e80bdcdbf94017c498f8f1e2/code.mmd&config=https://gist.githubusercontent.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/raw/4eb03887e6a41397e80bdcdbf94017c498f8f1e2/config.json'
); );
cy.contains('History').click(); cy.contains('Party');
cy.contains('Party'); cy.getLocalStorage('codeStore').snapshot();
cy.contains('Revisions'); });
cy.contains('sidharthv96 v7851e19');
cy.getLocalStorage('codeStore').snapshot();
});
it('should load diagram from raw files', () => { // Disabled temporarily. Should be enabled after the issue is fixed in Mermaid.
cy.visit( // it('should prevent setting the "securityLevel" option via URL', () => {
'/edit?code=https://gist.githubusercontent.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/raw/4eb03887e6a41397e80bdcdbf94017c498f8f1e2/code.mmd&config=https://gist.githubusercontent.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/raw/4eb03887e6a41397e80bdcdbf94017c498f8f1e2/config.json' // const b64State = toBase64(
); // `{"code":"graph TD\\nA[\\"<img src='https://via.placeholder.com/64' width=64 />\\"]","mermaid":"{\\"securityLevel\\": \\"loose\\", \\"theme\\": \\"forest\\"}","autoSync":true,"updateDiagram":true}`,
cy.contains('Party'); // true
cy.getLocalStorage('codeStore').snapshot(); // );
}); // cy.on('window:confirm', () => true);
}); // cy.visit(`/edit#${b64State}`);
// cy.contains('Config').click();
// cy.contains('forest');
// cy.contains('securityLevel').should('not.exist');
// cy.get('#view').find('img').should('not.exist');
// cy.get('#view').contains('<img');
// cy.get('#view').contains(`src='https://via.placeholder.com/64'`);
// });
// Disabled temporarily. Should be enabled after the issue is fixed in Mermaid. it('should allow persisting "securityLevel" using confirm dialogue', () => {
// it('should prevent setting the "securityLevel" option via URL', () => { const b64State = toBase64(
// const b64State = toBase64( `{"code":"graph TD\\nA[\\"<img src='https://dummyimage.com/64' width=64/>\\"]","mermaid":"{\\"securityLevel\\": \\"loose\\", \\"theme\\": \\"forest\\"}","autoSync":true,"updateDiagram":true}`,
// `{"code":"graph TD\\nA[\\"<img src='https://via.placeholder.com/64' width=64 />\\"]","mermaid":"{\\"securityLevel\\": \\"loose\\", \\"theme\\": \\"forest\\"}","autoSync":true,"updateDiagram":true}`, true
// true );
// ); cy.on('window:confirm', () => false);
// cy.on('window:confirm', () => true); cy.visit(`/edit#${b64State}`);
// cy.visit(`/edit#${b64State}`); cy.contains('Config').click();
// cy.contains('Config').click(); cy.contains('forest');
// cy.contains('forest'); cy.contains('securityLevel');
// cy.contains('securityLevel').should('not.exist'); cy.get('#view').find('img').should('be.visible');
// cy.get('#view').find('img').should('not.exist'); });
// cy.get('#view').contains('<img');
// cy.get('#view').contains(`src='https://via.placeholder.com/64'`);
// });
it.skip('should allow persisting "securityLevel" using confirm dialogue', () => { it('should show troubleshooting steps if loading fails', () => {
const b64State = toBase64( cy.visit('/#/edit/eyJjb2RlIjoiZ3JhcGggVERcbiAg');
`{"code":"graph TD\\nA[\\"<img src='https://dummyimage.com/64' width=64/>\\"]","mermaid":"{\\"securityLevel\\": \\"loose\\", \\"theme\\": \\"forest\\"}","autoSync":true,"updateDiagram":true}`, cy.reload(true);
true cy.contains('Please Click here to Raise an issue in github.');
); });
cy.on('window:confirm', () => false);
cy.visit(`/edit#${b64State}`);
cy.get('#editor').type(' ');
cy.contains('Config').click();
cy.contains('forest');
cy.contains('securityLevel');
cy.get('#view').find('img').should('be.visible');
});
it('should show troubleshooting steps if loading fails', () => { it('should load uncompressed URL', () => {
cy.visit('/#/edit/eyJjb2RlIjoiZ3JhcGggVERcbiAg'); cy.visit(
cy.reload(true); '/edit/#eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW05ldyBZZWFyXSAtLT58R2V0IG1vbmV5fCBCKEdvIHNob3BwaW5nKVxuICAgIEIgLS0-IEN7TGV0IG1lIHRoaW5rfVxuICAgIEMgLS0-fE9uZXwgRFtMYXB0b3BdXG4gICAgQyAtLT58VHdvfCBFW2lQaG9uZV1cbiAgICBDIC0tPnxUaHJlZXwgRltmYTpmYS1jYXIgQ2FyXSIsIm1lcm1haWQiOiJ7XG4gIFwidGhlbWVcIjogXCJkZWZhdWx0XCJcbn0iLCJ1cGRhdGVFZGl0b3IiOmZhbHNlLCJhdXRvU3luYyI6dHJ1ZSwidXBkYXRlRGlhZ3JhbSI6ZmFsc2V9'
cy.contains('Please Click here to Raise an issue in github.'); );
}); cy.contains('New Year');
cy.visit(
'/edit#eyJjb2RlIjoiY2xhc3NEaWFncmFtXG4gICAgQW5pbWFsIDx8LS0gRHVja1xuICAgIEFuaW1hbCA8fC0tIEZpc2hcbiAgICBBbmltYWwgPHwtLSBaZWJyYVxuICAgIEFuaW1hbCA6ICtpbnQgYWdlXG4gICAgQW5pbWFsIDogK1N0cmluZyBnZW5kZXJcbiAgICBBbmltYWw6ICtpc01hbW1hbCgpXG4gICAgQW5pbWFsOiArbWF0ZSgpXG4gICAgY2xhc3MgRHVja3tcbiAgICAgICtTdHJpbmcgYmVha0NvbG9yXG4gICAgICArc3dpbSgpXG4gICAgICArcXVhY2soKVxuICAgIH1cbiAgICBjbGFzcyBGaXNoe1xuICAgICAgLWludCBzaXplSW5GZWV0XG4gICAgICAtY2FuRWF0KClcbiAgICB9XG4gICAgY2xhc3MgWmVicmF7XG4gICAgICArYm9vbCBpc193aWxkXG4gICAgICArcnVuKClcbiAgICB9XG4gICAgICAgICAgICAiLCJtZXJtYWlkIjoie1xuICBcInRoZW1lXCI6IFwiZGFya1wiXG59IiwidXBkYXRlRWRpdG9yIjpmYWxzZSwiYXV0b1N5bmMiOnRydWUsInVwZGF0ZURpYWdyYW0iOmZhbHNlfQ'
);
cy.contains('Animal');
cy.visit(
'/edit/#base64:eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW05ldyBZZWFyXSAtLT58R2V0IG1vbmV5fCBCKEdvIHNob3BwaW5nKVxuICAgIEIgLS0-IEN7TGV0IG1lIHRoaW5rfVxuICAgIEMgLS0-fE9uZXwgRFtMYXB0b3BdXG4gICAgQyAtLT58VHdvfCBFW2lQaG9uZV1cbiAgICBDIC0tPnxUaHJlZXwgRltmYTpmYS1jYXIgQ2FyXSIsIm1lcm1haWQiOiJ7XG4gIFwidGhlbWVcIjogXCJkZWZhdWx0XCJcbn0iLCJ1cGRhdGVFZGl0b3IiOmZhbHNlLCJhdXRvU3luYyI6dHJ1ZSwidXBkYXRlRGlhZ3JhbSI6ZmFsc2V9'
);
cy.contains('New Year');
});
it('should load compressed URL', () => { it('should load compressed URL', () => {
cy.visit( cy.visit(
'/edit#pako:eNpVkM2KwkAQhF-l6dMK5gVyEDRxvYi7sF6WjIcm0zqDzg_jBJEk725Hd2G3Tw31VVFUj23QjCWeEkUD-1p5kFs2O77BN1M6QFEshg1ncMHzfYDV2ybA1YQYrT_NXvhqgqDqtxPGkI315_ElVU__h-cB6mZLMYd4-Kvsb2GAdWM_jcT_V0xicb03RyqPVLSUoJI-OEfHyZHV0rqfDAqzYccKS3k1pbNC5Ufhuqgp81rbHBJKxuXKc6Quh6-7b7HMqeNfqLYkC7gfanwAlW1ZvQ' '/edit#pako:eNpVkM2KwkAQhF-l6dMK5gVyEDRxvYi7sF6WjIcm0zqDzg_jBJEk725Hd2G3Tw31VVFUj23QjCWeEkUD-1p5kFs2O77BN1M6QFEshg1ncMHzfYDV2ybA1YQYrT_NXvhqgqDqtxPGkI315_ElVU__h-cB6mZLMYd4-Kvsb2GAdWM_jcT_V0xicb03RyqPVLSUoJI-OEfHyZHV0rqfDAqzYccKS3k1pbNC5Ufhuqgp81rbHBJKxuXKc6Quh6-7b7HMqeNfqLYkC7gfanwAlW1ZvQ'
); );
cy.contains('New Year'); cy.contains('New Year');
cy.visit( cy.visit(
'/edit#pako:eNptkU1PwzAMhv9K5BOI9Q9EXBDbJA477YYqITcxndV8QD40weh_Jy1rGR0-OY_tV2_sEyivCSQogzGuGduAtnaixINji0bcf1WVWGfVXdMtx8M1faYm4B8sxR27JLClJd6nwK4VLTlN4bI4jMQd2pLe3C4KFhNNcLQ92jv9ADGLNoTdozc-zIV4ZDsNlud7RtVN7_5Sb_jYrFcN3iN_0pPbEqUZK3QbTP_Ojyv4NdR4bwTHlyMbPcOQ3WJ2CliBpWCRdbnLqFJDOpClGmRJNYauhtr1pS-_6bKMjebkA8hXNJFWgDn5_YdTIFPINDWdb3vu6r8BaWOZRQ' '/edit#pako:eNptkU1PwzAMhv9K5BOI9Q9EXBDbJA477YYqITcxndV8QD40weh_Jy1rGR0-OY_tV2_sEyivCSQogzGuGduAtnaixINji0bcf1WVWGfVXdMtx8M1faYm4B8sxR27JLClJd6nwK4VLTlN4bI4jMQd2pLe3C4KFhNNcLQ92jv9ADGLNoTdozc-zIV4ZDsNlud7RtVN7_5Sb_jYrFcN3iN_0pPbEqUZK3QbTP_Ojyv4NdR4bwTHlyMbPcOQ3WJ2CliBpWCRdbnLqFJDOpClGmRJNYauhtr1pS-_6bKMjebkA8hXNJFWgDn5_YdTIFPINDWdb3vu6r8BaWOZRQ'
); );
cy.contains('Animal'); cy.contains('Animal');
}); });
it('should load uncompressed URL', () => {
cy.visit(
'/edit/#eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW05ldyBZZWFyXSAtLT58R2V0IG1vbmV5fCBCKEdvIHNob3BwaW5nKVxuICAgIEIgLS0-IEN7TGV0IG1lIHRoaW5rfVxuICAgIEMgLS0-fE9uZXwgRFtMYXB0b3BdXG4gICAgQyAtLT58VHdvfCBFW2lQaG9uZV1cbiAgICBDIC0tPnxUaHJlZXwgRltmYTpmYS1jYXIgQ2FyXSIsIm1lcm1haWQiOiJ7XG4gIFwidGhlbWVcIjogXCJkZWZhdWx0XCJcbn0iLCJ1cGRhdGVFZGl0b3IiOmZhbHNlLCJhdXRvU3luYyI6dHJ1ZSwidXBkYXRlRGlhZ3JhbSI6ZmFsc2V9'
);
cy.contains('New Year');
cy.visit(
'/edit#eyJjb2RlIjoiY2xhc3NEaWFncmFtXG4gICAgQW5pbWFsIDx8LS0gRHVja1xuICAgIEFuaW1hbCA8fC0tIEZpc2hcbiAgICBBbmltYWwgPHwtLSBaZWJyYVxuICAgIEFuaW1hbCA6ICtpbnQgYWdlXG4gICAgQW5pbWFsIDogK1N0cmluZyBnZW5kZXJcbiAgICBBbmltYWw6ICtpc01hbW1hbCgpXG4gICAgQW5pbWFsOiArbWF0ZSgpXG4gICAgY2xhc3MgRHVja3tcbiAgICAgICtTdHJpbmcgYmVha0NvbG9yXG4gICAgICArc3dpbSgpXG4gICAgICArcXVhY2soKVxuICAgIH1cbiAgICBjbGFzcyBGaXNoe1xuICAgICAgLWludCBzaXplSW5GZWV0XG4gICAgICAtY2FuRWF0KClcbiAgICB9XG4gICAgY2xhc3MgWmVicmF7XG4gICAgICArYm9vbCBpc193aWxkXG4gICAgICArcnVuKClcbiAgICB9XG4gICAgICAgICAgICAiLCJtZXJtYWlkIjoie1xuICBcInRoZW1lXCI6IFwiZGFya1wiXG59IiwidXBkYXRlRWRpdG9yIjpmYWxzZSwiYXV0b1N5bmMiOnRydWUsInVwZGF0ZURpYWdyYW0iOmZhbHNlfQ'
);
cy.contains('Animal');
cy.visit(
'/edit/#base64:eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW05ldyBZZWFyXSAtLT58R2V0IG1vbmV5fCBCKEdvIHNob3BwaW5nKVxuICAgIEIgLS0-IEN7TGV0IG1lIHRoaW5rfVxuICAgIEMgLS0-fE9uZXwgRFtMYXB0b3BdXG4gICAgQyAtLT58VHdvfCBFW2lQaG9uZV1cbiAgICBDIC0tPnxUaHJlZXwgRltmYTpmYS1jYXIgQ2FyXSIsIm1lcm1haWQiOiJ7XG4gIFwidGhlbWVcIjogXCJkZWZhdWx0XCJcbn0iLCJ1cGRhdGVFZGl0b3IiOmZhbHNlLCJhdXRvU3luYyI6dHJ1ZSwidXBkYXRlRGlhZ3JhbSI6ZmFsc2V9'
);
cy.contains('New Year');
});
}); });
+50 -50
View File
@@ -1,56 +1,56 @@
describe('Test themes', () => { describe('Test themes', () => {
describe('Test light themes', () => { describe('Test light themes', () => {
beforeEach(() => { beforeEach(() => {
cy.clearLocalStorage(); cy.clearLocalStorage();
cy.visit('/edit', { cy.visit('/edit', {
onBeforeLoad(win) { onBeforeLoad(win) {
cy.stub(win, 'matchMedia') cy.stub(win, 'matchMedia')
.callThrough() .callThrough()
.withArgs('(prefers-color-scheme: dark)') .withArgs('(prefers-color-scheme: dark)')
.returns({ .returns({
matches: false matches: false
}); });
} }
}); });
cy.contains('Change Theme').click(); cy.contains('Change Theme').click();
}); });
it('should set light theme as default', () => { it('should set light theme as default', () => {
cy.contains('light').parent().should('have.class', 'bordered'); cy.contains('light').parent().should('have.class', 'bordered');
cy.contains('dark').parent().should('not.have.class', 'bordered'); cy.contains('dark').parent().should('not.have.class', 'bordered');
cy.getLocalStorage('themeStore').snapshot(); cy.getLocalStorage('themeStore').snapshot();
}); });
it('should change themes when clicked', () => { it('should change themes when clicked', () => {
cy.contains('light').parent().should('have.class', 'bordered'); cy.contains('light').parent().should('have.class', 'bordered');
cy.contains('cupcake').click(); cy.contains('cupcake').click();
cy.contains('cupcake').parent().should('have.class', 'bordered'); cy.contains('cupcake').parent().should('have.class', 'bordered');
cy.contains('light').parent().should('not.have.class', 'bordered'); cy.contains('light').parent().should('not.have.class', 'bordered');
cy.contains('dark').parent().should('not.have.class', 'bordered'); cy.contains('dark').parent().should('not.have.class', 'bordered');
cy.getLocalStorage('themeStore').snapshot(); cy.getLocalStorage('themeStore').snapshot();
}); });
}); });
describe('Test dark mode', () => { describe('Test dark mode', () => {
beforeEach(() => { beforeEach(() => {
cy.clearLocalStorage(); cy.clearLocalStorage();
cy.visit('/edit', { cy.visit('/edit', {
onBeforeLoad(win) { onBeforeLoad(win) {
cy.stub(win, 'matchMedia') cy.stub(win, 'matchMedia')
.callThrough() .callThrough()
.withArgs('(prefers-color-scheme: dark)') .withArgs('(prefers-color-scheme: dark)')
.returns({ .returns({
matches: true matches: true
}); });
} }
}); });
cy.contains('Change Theme').click(); cy.contains('Change Theme').click();
}); });
it('should set dark theme as default', () => { it('should set dark theme as default', () => {
cy.contains('light').parent().should('not.have.class', 'bordered'); cy.contains('light').parent().should('not.have.class', 'bordered');
cy.contains('dark').parent().should('have.class', 'bordered'); cy.contains('dark').parent().should('have.class', 'bordered');
cy.getLocalStorage('themeStore').snapshot(); cy.getLocalStorage('themeStore').snapshot();
}); });
}); });
}); });
+29 -34
View File
@@ -1,46 +1,41 @@
export const cmd = `{${Cypress.platform === 'darwin' ? 'meta' : 'ctrl'}}`; export const cmd = `{${Cypress.platform === 'darwin' ? 'meta' : 'ctrl'}}`;
export const getEditor = ({ bottom = true, newline = false } = {}) => export const getEditor = ({ bottom = true, newline = false } = {}) =>
cy cy
.get('#editor textarea:first') .get('#editor textarea:first')
.click() .click()
.focused() .focused()
.type(`${bottom ? '{pageDown}' : cmd}`) .type(`${bottom ? '{pageDown}' : cmd}`)
.type(`${newline ? '{enter}' : cmd}`); .type(`${newline ? '{enter}' : cmd}`);
const downloadsFolder = Cypress.config('downloadsFolder'); const downloadsFolder = Cypress.config('downloadsFolder');
export const verifyFileSizeGreaterThan = ( export const verifyFileSize = (
fileType: 'history' | 'diagram', fileType: 'history' | 'diagram',
extension: string, extension: string,
size: number size: number
) => { ) => {
const fileName = `mermaid-${fileType}-2022-01-01-000000.${extension}`; const fileName = `mermaid-${fileType}-2022-01-01-000000.${extension}`;
const filePath = `${downloadsFolder}/${fileName}`; const filePath = `${downloadsFolder}/${fileName}`;
// eslint-disable-next-line @typescript-eslint/no-unsafe-call cy.verifyDownload(fileName);
cy.verifyDownload(fileName); cy.readFile(filePath, null, {
cy.readFile(filePath, null, { log: false
log: false }).then((buffer) => expect((buffer as ArrayBuffer).byteLength).to.be.gt(size));
}).then((buffer: ArrayBuffer) => { cy.task('deleteFile', filePath);
expect(buffer.byteLength).to.be.gt(size);
expect(buffer.byteLength).to.be.lt(size * 1.3);
});
cy.task('deleteFile', filePath);
}; };
export const verifyFileSnapshot = ( export const verifyFileSnapshot = (
fileType: 'history' | 'diagram', fileType: 'history' | 'diagram',
extension: string, extension: string,
content: string content: string
) => { ) => {
const fileName = `mermaid-${fileType}-2022-01-01-000000.${extension}`; const fileName = `mermaid-${fileType}-2022-01-01-000000.${extension}`;
const filePath = `${downloadsFolder}/${fileName}`; const filePath = `${downloadsFolder}/${fileName}`;
// eslint-disable-next-line @typescript-eslint/no-unsafe-call cy.verifyDownload(fileName);
cy.verifyDownload(fileName); cy.readFile(filePath, null, {
cy.readFile(filePath, null, { log: false
log: false }).then((buffer) =>
}).then((buffer: ArrayBuffer) => expect(new TextDecoder('utf-8').decode(buffer as ArrayBuffer)).to.contain(content)
expect(new TextDecoder('utf8').decode(buffer)).to.contain(content) );
); cy.task('deleteFile', filePath);
cy.task('deleteFile', filePath);
}; };
+3 -3
View File
@@ -1,5 +1,5 @@
{ {
"name": "Using fixtures to represent data", "name": "Using fixtures to represent data",
"email": "hello@cypress.io", "email": "hello@cypress.io",
"body": "Fixtures are a great way to mock data for responses to routes" "body": "Fixtures are a great way to mock data for responses to routes"
} }
+4 -4
View File
@@ -1,7 +1,7 @@
module.exports = { module.exports = {
"Site Loads": { "Site Loads": {
"Check Home page load": { "Check Home page load": {
"1": "{\"code\":\"flowchart TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n \",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":true}" "1": "{\"code\":\"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n \",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":true}"
}, },
"Check Redirect from old URL": { "Check Redirect from old URL": {
"1": "{\"code\":\"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":true}" "1": "{\"code\":\"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":true}"
@@ -16,13 +16,13 @@ module.exports = {
"1": "{\"code\":\"graph TD\\n A[Party] -->|Get money| B(Go shopping!!)\\n \",\"mermaid\":\"{\\n \\\"theme\\\": \\\"forest\\\",\\n \\\"test\\\": \\\"hello world\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":true,\"loader\":{\"type\":\"files\",\"config\":{\"codeURL\":\"https://gist.githubusercontent.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/raw/4eb03887e6a41397e80bdcdbf94017c498f8f1e2/code.mmd\",\"configURL\":\"https://gist.githubusercontent.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/raw/4eb03887e6a41397e80bdcdbf94017c498f8f1e2/config.json\"}}}" "1": "{\"code\":\"graph TD\\n A[Party] -->|Get money| B(Go shopping!!)\\n \",\"mermaid\":\"{\\n \\\"theme\\\": \\\"forest\\\",\\n \\\"test\\\": \\\"hello world\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":true,\"loader\":{\"type\":\"files\",\"config\":{\"codeURL\":\"https://gist.githubusercontent.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/raw/4eb03887e6a41397e80bdcdbf94017c498f8f1e2/code.mmd\",\"configURL\":\"https://gist.githubusercontent.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/raw/4eb03887e6a41397e80bdcdbf94017c498f8f1e2/config.json\"}}}"
} }
}, },
"__version": "11.2.0", "__version": "10.10.0",
"Auto sync tests": { "Auto sync tests": {
"should dim diagram when code is edited": { "should dim diagram when code is edited": {
"1": "{\"code\":\"flowchart TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n C --> Test\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":false,\"updateDiagram\":false}" "1": "{\"code\":\"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n C --> Test\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":false,\"updateDiagram\":false}"
}, },
"should not dim diagram when code is in sync": { "should not dim diagram when code is in sync": {
"1": "{\"code\":\"flowchart TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n C --> Testing\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":false}" "1": "{\"code\":\"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n C --> Testing\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":false}"
} }
}, },
"Test themes": { "Test themes": {
+6 -6
View File
@@ -27,12 +27,12 @@ import { register } from '@cypress/snapshot';
// eslint-disable-next-line @typescript-eslint/no-unsafe-call // eslint-disable-next-line @typescript-eslint/no-unsafe-call
register(); register();
declare global { declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace // eslint-disable-next-line @typescript-eslint/no-namespace
namespace Cypress { namespace Cypress {
interface Chainable { interface Chainable {
snapshot(): void; snapshot(): void;
} }
} }
} }
import 'cypress-localstorage-commands'; import 'cypress-localstorage-commands';
+4 -4
View File
@@ -21,8 +21,8 @@ require('cy-verify-downloads').addCustomCommand();
// require('./commands') // require('./commands')
Cypress.on('uncaught:exception', (err) => { Cypress.on('uncaught:exception', (err) => {
/* returning false here prevents Cypress from failing the test */ /* returning false here prevents Cypress from failing the test */
if (err.message.includes('ResizeObserver loop limit exceeded')) { if (err.message.includes('ResizeObserver loop limit exceeded')) {
return false; return false;
} }
}); });
+5 -5
View File
@@ -1,7 +1,7 @@
{ {
"compilerOptions": { "compilerOptions": {
"allowJs": true, "allowJs": true,
"types": ["cypress", "cypress-localstorage-commands", "cy-verify-downloads", "node"] "types": ["cypress", "cypress-localstorage-commands", "cy-verify-downloads"]
}, },
"include": ["**/*.ts"] "include": ["**/*.ts"]
} }
+94 -95
View File
@@ -1,97 +1,96 @@
{ {
"name": "mermaid-live-editor", "name": "mermaid-live-editor",
"version": "2.0.67", "version": "2.0.67",
"type": "module", "type": "module",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
"dev": "vite dev", "dev": "vite dev",
"dev:force": "MERMAID_LOCAL=true yarn dev --force", "dev:force": "MERMAID_LOCAL=true yarn dev --force",
"dev:test": "yarn dev", "dev:test": "yarn dev",
"build": "vite build", "build": "vite build",
"preview": "vite preview", "preview": "vite preview",
"lint": "prettier --check --cache --plugin-search-dir=. .;eslint --ignore-path .gitignore .", "lint": "prettier --check --cache --plugin-search-dir=. .;eslint --ignore-path .gitignore .",
"lint:fix": "prettier --write --cache --plugin-search-dir=. .;eslint --fix --ignore-path .gitignore .", "lint:fix": "prettier --write --cache --plugin-search-dir=. .;eslint --fix --ignore-path .gitignore .",
"format": "prettier --write --cache --plugin-search-dir=. .", "format": "prettier --write --cache --plugin-search-dir=. .",
"pre-commit": "lint-staged", "pre-commit": "lint-staged",
"postinstall": "husky install && svelte-kit sync && (git config blame.ignoreRevsFile .git-blame-ignore-revs || true)", "postinstall": "husky install; svelte-kit sync",
"test:unit": "vitest", "test:unit": "vitest",
"test:ui": "vitest --ui", "test:ui": "vitest --ui",
"test:coverage": "vitest run --coverage", "test:coverage": "vitest run --coverage",
"test:browser": "cypress run", "test:browser": "cypress run",
"test": "test:unit && test:browser", "test": "test:unit && test:browser",
"cy": "cypress open" "cy": "cypress open"
}, },
"devDependencies": { "devDependencies": {
"@cypress/snapshot": "2.1.7", "@cypress/snapshot": "2.1.7",
"@sveltejs/adapter-static": "1.0.6", "@sveltejs/adapter-static": "1.0.0-next.44",
"@sveltejs/kit": "1.5.0", "@sveltejs/kit": "1.0.0-next.516",
"@testing-library/jest-dom": "5.16.5", "@testing-library/jest-dom": "5.16.5",
"@testing-library/svelte": "3.2.2", "@testing-library/svelte": "3.2.2",
"@types/pako": "2.0.0", "@types/async": "^3.2.15",
"@types/uuid": "8.3.4", "@types/pako": "2.0.0",
"@typescript-eslint/eslint-plugin": "5.51.0", "@types/uuid": "8.3.4",
"@typescript-eslint/parser": "5.51.0", "@typescript-eslint/eslint-plugin": "5.40.1",
"@vitest/ui": "^0.28.0", "@typescript-eslint/parser": "5.40.1",
"autoprefixer": "^10.4.13", "@vitest/ui": "0.24.3",
"c8": "7.12.0", "autoprefixer": "10.4.12",
"chai": "^4.3.7", "c8": "7.12.0",
"cssnano": "^5.1.14", "chai": "4.3.6",
"cy-verify-downloads": "0.1.11", "cssnano": "5.1.13",
"cypress": "11.2.0", "cy-verify-downloads": "0.1.11",
"cypress-localstorage-commands": "2.2.2", "cypress": "10.10.0",
"eslint": "8.33.0", "cypress-localstorage-commands": "2.2.1",
"eslint-config-prettier": "8.6.0", "eslint": "8.25.0",
"eslint-plugin-cypress": "2.12.1", "eslint-config-prettier": "8.5.0",
"eslint-plugin-es": "4.1.0", "eslint-plugin-cypress": "2.12.1",
"eslint-plugin-no-only-tests": "^3.1.0", "eslint-plugin-es": "4.1.0",
"eslint-plugin-postcss-modules": "2.0.0", "eslint-plugin-postcss-modules": "2.0.0",
"eslint-plugin-svelte3": "4.0.0", "eslint-plugin-svelte3": "4.0.0",
"eslint-plugin-tailwindcss": "3.8.3", "eslint-plugin-tailwindcss": "3.6.2",
"eslint-plugin-unicorn": "^45.0.0", "eslint-plugin-vitest": "0.0.11",
"eslint-plugin-vitest": "^0.0.32", "esserializer": "1.3.2",
"esserializer": "1.3.10", "husky": "8.0.1",
"font-awesome": "^4.7.0", "jsdom": "20.0.1",
"husky": "^8.0.2", "lint-staged": "13.0.3",
"jsdom": "20.0.3", "node-html-parser": "6.1.1",
"lint-staged": "13.1.1", "postcss": "8.4.18",
"node-html-parser": "^6.1.4", "postcss-load-config": "4.0.1",
"postcss": "^8.4.19", "prettier": "2.7.1",
"postcss-load-config": "4.0.1", "prettier-plugin-svelte": "2.8.0",
"prettier": "2.8.3", "svelte": "3.52.0",
"prettier-plugin-svelte": "^2.8.1", "svelte-preprocess": "4.10.7",
"svelte": "3.55.1", "tailwindcss": "3.1.8",
"svelte-preprocess": "4.10.7", "tslib": "2.4.0",
"tailwindcss": "^3.2.4", "typescript": "4.8.4",
"tslib": "^2.4.1", "vite": "3.1.8",
"typescript": "4.9.5", "vitest": "0.24.3"
"vite": "^4.0.1", },
"vitest": "^0.28.0" "dependencies": {
}, "analytics": "0.8.1",
"dependencies": { "analytics-plugin-plausible": "0.0.6",
"analytics": "0.8.1", "async": "^3.2.4",
"analytics-plugin-plausible": "0.0.6", "daisyui": "2.31.0",
"daisyui": "2.50.0", "js-base64": "3.7.2",
"dayjs": "^1.11.7", "mermaid": "9.2.0-rc6",
"js-base64": "3.7.4", "moment": "2.29.4",
"mermaid": "10.0.1-rc.3", "monaco-editor": "0.34.1",
"monaco-editor": "0.34.1", "monaco-mermaid": "1.0.6",
"monaco-mermaid": "1.0.8", "pako": "2.0.4",
"pako": "2.1.0", "random-word-slugs": "0.1.6",
"random-word-slugs": "0.1.6", "svg-pan-zoom": "3.6.1",
"svg-pan-zoom": "3.6.1", "uuid": "9.0.0"
"uuid": "9.0.0" },
}, "lint-staged": {
"lint-staged": { "*.{ts,svelte,js,css,md,json}": [
"*.{ts,svelte,js,css,md,json}": [ "prettier --plugin-search-dir=. --write",
"prettier --plugin-search-dir=. --write", "eslint --ignore-path .gitignore "
"eslint --ignore-path .gitignore " ]
] },
}, "volta": {
"volta": { "node": "18.5.0",
"node": "18.14.0", "yarn": "1.22.19"
"yarn": "1.22.19" },
}, "engines": {
"engines": { "node": ">=16.7"
"node": ">=16.7" }
}
} }
+10 -10
View File
@@ -6,18 +6,18 @@ const mode = process.env.NODE_ENV;
const dev = mode === 'development'; const dev = mode === 'development';
module.exports = { module.exports = {
plugins: [ plugins: [
// Some plugins, like postcss-nested, need to run before Tailwind // Some plugins, like postcss-nested, need to run before Tailwind
tailwindcss, tailwindcss,
// But others, like autoprefixer, need to run after // But others, like autoprefixer, need to run after
autoprefixer, autoprefixer,
!dev && !dev &&
cssnano({ cssnano({
preset: 'default' preset: 'default'
}) })
] ]
}; };
+22 -22
View File
@@ -1,24 +1,24 @@
{ {
"extends": [ "extends": [
"config:base", "config:base",
":rebaseStalePrs", ":rebaseStalePrs",
"group:allNonMajor", "group:allNonMajor",
"schedule:earlyMondays", "schedule:earlyMondays",
":automergeMinor", ":automergeMinor",
":automergeTesters", ":automergeTesters",
":automergeLinters", ":automergeLinters",
":automergeTypes", ":automergeTypes",
":automergePatch" ":automergePatch"
], ],
"packageRules": [ "packageRules": [
{ {
"matchUpdateTypes": ["minor", "patch", "pin", "digest"], "matchUpdateTypes": ["minor", "patch", "pin", "digest"],
"automerge": true "automerge": true
} }
], ],
"dependencyDashboard": true, "dependencyDashboard": true,
"major": { "major": {
"dependencyDashboardApproval": true "dependencyDashboardApproval": true
}, },
"dependencyDashboardAutoclose": true "dependencyDashboardAutoclose": true
} }
+54 -54
View File
@@ -1,57 +1,57 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Online FlowChart &amp; Diagrams Editor - Mermaid Live Editor</title> <title>Online FlowChart &amp; Diagrams Editor - Mermaid Live Editor</title>
<meta <meta
name="og:image" name="og:image"
content="https://github.com/mermaid-js/mermaid/raw/develop/img/header.png" /> content="https://github.com/mermaid-js/mermaid/raw/develop/img/header.png" />
<link rel="canonical" href="https://mermaid.live" /> <link rel="canonical" href="https://mermaid.live" />
<meta <meta
name="description" 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." /> 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." />
<link rel="icon" type="image/png" href="%sveltekit.assets%/favicon.svg" /> <link rel="icon" type="image/png" href="%sveltekit.assets%/favicon.svg" />
<link rel="mask-icon" href="%sveltekit.assets%/favicon.svg" color="#000000" /> <link rel="mask-icon" href="%sveltekit.assets%/favicon.svg" color="#000000" />
<meta name="theme-color" content="#6366F1" /> <meta name="theme-color" content="#6366F1" />
<link rel="manifest" href="%sveltekit.assets%/manifest.json" /> <link rel="manifest" href="%sveltekit.assets%/manifest.json" />
<link <link
rel="stylesheet" rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"
integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A=="
crossorigin="anonymous" crossorigin="anonymous"
referrerpolicy="no-referrer" /> referrerpolicy="no-referrer" />
<link <link
rel="stylesheet" rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.1/min/vs/editor/editor.main.min.css" href="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.1/min/vs/editor/editor.main.min.css"
integrity="sha512-GzcoZD7y5zvBofYtImXPZaPVhoY7xLPt+ysmbPb/vU+quSKFkcngxaSrxuwprDZL4MALUqGFmnqCxQZqMozv1Q==" integrity="sha512-GzcoZD7y5zvBofYtImXPZaPVhoY7xLPt+ysmbPb/vU+quSKFkcngxaSrxuwprDZL4MALUqGFmnqCxQZqMozv1Q=="
crossorigin="anonymous" crossorigin="anonymous"
referrerpolicy="no-referrer" /> referrerpolicy="no-referrer" />
<script> <script>
var require = { var require = {
paths: { paths: {
vs: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.0/min/vs' vs: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.0/min/vs'
} }
}; };
</script> </script>
<script <script
src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.1/min/vs/loader.min.js" src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.1/min/vs/loader.min.js"
integrity="sha512-6bIYsGqvLpAiEBXPdRQeFf5cueeBECtAKJjIHer3BhBZNTV3WLcLA8Tm3pDfxUwTMIS+kAZwTUvJ1IrMdX8C5w==" integrity="sha512-6bIYsGqvLpAiEBXPdRQeFf5cueeBECtAKJjIHer3BhBZNTV3WLcLA8Tm3pDfxUwTMIS+kAZwTUvJ1IrMdX8C5w=="
crossorigin="anonymous" crossorigin="anonymous"
referrerpolicy="no-referrer"></script> referrerpolicy="no-referrer"></script>
<script <script
src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.1/min/vs/editor/editor.main.nls.min.js" src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.1/min/vs/editor/editor.main.nls.min.js"
integrity="sha512-CCv+DKWw+yZhxf4Z+ExT6HC5G+3S45TeMTYcJyYbdrv4BpK2vyALJ4FoVR/KGWDIPu7w4tNCOC9MJQIkYPR5FA==" integrity="sha512-CCv+DKWw+yZhxf4Z+ExT6HC5G+3S45TeMTYcJyYbdrv4BpK2vyALJ4FoVR/KGWDIPu7w4tNCOC9MJQIkYPR5FA=="
crossorigin="anonymous" crossorigin="anonymous"
referrerpolicy="no-referrer"></script> referrerpolicy="no-referrer"></script>
<script <script
src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.1/min/vs/editor/editor.main.js" src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.1/min/vs/editor/editor.main.js"
integrity="sha512-BtSZPhzoyN8kq1axY6cgOFPSgLJgFwvAZ3WxeDGxEFXeFcFuK2s7Hr+zF75npVHASUY1dxudAfIVzwmgdR89Bw==" integrity="sha512-BtSZPhzoyN8kq1axY6cgOFPSgLJgFwvAZ3WxeDGxEFXeFcFuK2s7Hr+zF75npVHASUY1dxudAfIVzwmgdR89Bw=="
crossorigin="anonymous" crossorigin="anonymous"
referrerpolicy="no-referrer"></script> referrerpolicy="no-referrer"></script>
%sveltekit.head% %sveltekit.head%
</head> </head>
<body> <body>
<div id="svelte">%sveltekit.body%</div> <div id="svelte">%sveltekit.body%</div>
</body> </body>
</html> </html>
+2 -2
View File
@@ -3,8 +3,8 @@
@tailwind utilities; @tailwind utilities;
.input { .input {
@apply flex-1 border-primary border-solid border-2 rounded; @apply flex-1 border-primary border-solid border-2 rounded;
} }
.action-btn { .action-btn {
@apply btn btn-primary; @apply btn btn-primary;
} }
+7 -7
View File
@@ -1,14 +1,14 @@
/// <reference types="vite/client" /> /// <reference types="vite/client" />
interface ImportMetaEnv { interface ImportMetaEnv {
readonly MERMAID_RENDERER_URL?: string; readonly MERMAID_RENDERER_URL: string;
readonly MERMAID_KROKI_RENDERER_URL?: string; readonly MERMAID_KROKI_RENDERER_URL: string;
readonly MERMAID_CDN_URL?: string; readonly MERMAID_CDN_URL: string;
readonly MERMAID_BASE_URL?: string; readonly MERMAID_BASE_URL: string;
readonly MERMAID_LOCAL?: boolean; readonly MERMAID_LOCAL: boolean;
// more env variables... // more env variables...
} }
interface ImportMeta { interface ImportMeta {
readonly env: ImportMetaEnv; readonly env: ImportMetaEnv;
} }
+6 -7
View File
@@ -6,11 +6,10 @@
import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers'; import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers';
declare global { declare global {
namespace jest { namespace jest {
interface Matchers<R = void> interface Matchers<R = void>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error // @ts-ignore
// eslint-disable-next-line no-undef extends TestingLibraryMatchers<typeof expect.stringContaining, R> {}
extends TestingLibraryMatchers<typeof expect.stringContaining, R> {} }
}
} }
+2 -2
View File
@@ -1,6 +1,6 @@
import type { Handle } from '@sveltejs/kit'; import type { Handle } from '@sveltejs/kit';
export const handle: Handle = async ({ event, resolve }) => { export const handle: Handle = async ({ event, resolve }) => {
const response = await resolve(event, {}); const response = await resolve(event, {});
return response; return response;
}; };
-265
View File
@@ -1,265 +0,0 @@
<script lang="ts">
import { browser } from '$app/environment';
import Card from '$lib/components/Card/Card.svelte';
import { env } from '$lib/util/env';
import { pakoSerde } from '$lib/util/serde';
import { stateStore } from '$lib/util/state';
import { logEvent } from '$lib/util/stats';
import { toBase64 } from 'js-base64';
import dayjs from 'dayjs';
const { krokiRendererUrl, rendererUrl } = env;
type Exporter = (context: CanvasRenderingContext2D, image: HTMLImageElement) => () => void;
const getFileName = (ext: string) =>
`mermaid-diagram-${dayjs().format('YYYY-MM-DD-HHmmss')}.${ext}`;
const getBase64SVG = (svg?: HTMLElement, width?: number, height?: number): string => {
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 (!svg) {
svg = getSvgEl();
}
const svgString = svg.outerHTML
.replaceAll('<br>', '<br/>')
.replaceAll(/<img([^>]*)>/g, (m, g: string) => `<img ${g} />`);
return toBase64(svgString);
};
const exportImage = (event: Event, exporter: Exporter) => {
const canvas: HTMLCanvasElement = document.createElement('canvas');
const svg: HTMLElement | null = document.querySelector('#container svg');
if (!svg) {
throw new Error('svg not found');
}
const box: DOMRect = svg.getBoundingClientRect();
canvas.width = box.width;
canvas.height = box.height;
if (imagemodeselected === 'width') {
const ratio = box.height / box.width;
canvas.width = userimagesize;
canvas.height = userimagesize * ratio;
} else if (imagemodeselected === 'height') {
const ratio = box.width / box.height;
canvas.width = userimagesize * ratio;
canvas.height = userimagesize;
}
const context = canvas.getContext('2d');
if (!context) {
throw new Error('context not found');
}
context.fillStyle = 'white';
context.fillRect(0, 0, canvas.width, canvas.height);
const image = new Image();
image.onload = exporter(context, image);
image.src = `data:image/svg+xml;base64,${getBase64SVG(svg, canvas.width, canvas.height)}`;
event.stopPropagation();
event.preventDefault();
};
const getSvgEl = () => {
const svgEl: HTMLElement = document
.querySelector('#container svg')!
.cloneNode(true) as HTMLElement;
svgEl.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
const fontAwesomeCdnUrl = Array.from(document.head.getElementsByTagName('link'))
.map((l) => l.href)
.find((h) => h.includes('font-awesome'));
if (fontAwesomeCdnUrl == null) {
return svgEl;
}
const styleEl = document.createElement('style');
styleEl.innerText = `@import url("${fontAwesomeCdnUrl}");'`;
svgEl.prepend(styleEl);
return svgEl;
};
const simulateDownload = (download: string, href: string): void => {
const a = document.createElement('a');
a.download = download;
a.href = href;
a.click();
a.remove();
};
const downloadImage: Exporter = (context, image) => {
return () => {
const { canvas } = context;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
simulateDownload(
getFileName('png'),
canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream')
);
};
};
const isClipboardAvailable = (): boolean => {
return Object.prototype.hasOwnProperty.call(window, 'ClipboardItem') as boolean;
};
const clipboardCopy: Exporter = (context, image) => {
return () => {
const { canvas } = context;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
canvas.toBlob((blob) => {
try {
if (!blob) {
throw new Error('blob is empty');
}
void navigator.clipboard.write([
new ClipboardItem({
[blob.type]: blob
})
]);
} catch (error) {
console.error(error);
}
});
};
};
const onCopyClipboard = (event: Event) => {
exportImage(event, clipboardCopy);
logEvent('copyClipboard');
};
const onDownloadPNG = (event: Event) => {
exportImage(event, downloadImage);
logEvent('download', {
type: 'png'
});
};
const onDownloadSVG = () => {
simulateDownload(getFileName('svg'), `data:image/svg+xml;base64,${getBase64SVG()}`);
logEvent('download', {
type: 'svg'
});
};
const onCopyMarkdown = () => {
(document.getElementById('markdown') as HTMLInputElement).select();
document.execCommand('Copy');
logEvent('copyMarkdown');
};
let gistURL = '';
stateStore.subscribe(({ loader }) => {
if (loader?.type === 'gist') {
// @ts-expect-error Gist will have url
gistURL = loader.config.url;
}
});
const loadGist = () => {
if (!gistURL) {
alert('Please enter a Gist URL first');
}
window.location.href = `${window.location.pathname}?gist=${gistURL}`;
logEvent('loadGist');
};
let iUrl: string;
let svgUrl: string;
let krokiUrl: string;
let mdCode: string;
let imagemodeselected = 'auto';
let userimagesize = 1080;
let isNetlify = false;
if (browser && ['mermaid.live', 'netlify'].some((path) => window.location.host.includes(path))) {
isNetlify = true;
}
stateStore.subscribe(({ code, serialized }) => {
iUrl = `${rendererUrl}/img/${serialized}?type=png`;
svgUrl = `${rendererUrl}/svg/${serialized}`;
krokiUrl = `${krokiRendererUrl}/mermaid/svg/${pakoSerde.serialize(code)}`;
mdCode = `[![](${iUrl})](${window.location.protocol}//${window.location.host}${window.location.pathname}#${serialized})`;
});
</script>
<Card title="Actions" isOpen={false}>
<div class="flex flex-wrap gap-2 m-2">
{#if isClipboardAvailable()}
<button class="action-btn w-full" on:click={onCopyClipboard}
><i class="far fa-copy mr-2" /> Copy Image to clipboard
</button>
{/if}
<button id="downloadPNG" class="action-btn flex-grow" on:click={onDownloadPNG}>
<i class="fas fa-download mr-2" /> PNG
</button>
<button id="downloadSVG" class="action-btn flex-grow" on:click={onDownloadSVG}>
<i class="fas fa-download mr-2" /> SVG
</button>
<a target="_blank" rel="noreferrer" class="flex-grow" href={iUrl}>
<button class="action-btn w-full">
<i class="fas fa-external-link-alt mr-2" /> PNG
</button>
</a>
<a target="_blank" rel="noreferrer" class="flex-grow" href={svgUrl}>
<button class="action-btn w-full">
<i class="fas fa-external-link-alt mr-2" /> SVG
</button>
</a>
<a target="_blank" rel="noreferrer" class="flex-grow" href={krokiUrl}>
<button class="action-btn w-full">
<i class="fas fa-external-link-alt mr-2" /> Kroki
</button>
</a>
<div class="flex gap-2 items-center">
PNG size
<label for="autosize">
<input type="radio" value="auto" id="autosize" bind:group={imagemodeselected} /> Auto
</label>
<label for="width">
<input type="radio" value="width" id="width" bind:group={imagemodeselected} /> Width
</label>
<label for="height">
<input type="radio" value="height" id="height" bind:group={imagemodeselected} /> Height
</label>
{#if imagemodeselected !== 'auto'}
<input
id="height"
class="input"
type="number"
min="3"
max="10000"
bind:value={userimagesize} />
{/if}
</div>
<div class="w-full flex gap-2 items-center">
<input class="input" id="markdown" type="text" value={mdCode} on:click={onCopyMarkdown} />
<label for="markdown">
<button class="btn btn-primary btn-md flex-auto" on:click={onCopyMarkdown}>
Copy Markdown
</button>
</label>
</div>
<div class="w-full flex gap-2 items-center">
<input
class="input"
id="gist"
type="text"
bind:value={gistURL}
placeholder="Enter Gist URL" />
<label for="gist">
<button class="btn btn-primary btn-md flex-auto" on:click={loadGist}> Load Gist </button>
</label>
</div>
{#if isNetlify}
<div class="w-full flex items-center justify-center">
<a class="link underline text-gray-500 text-sm" href="https://netlify.com">
This site is powered by Netlify
</a>
</div>
{/if}
</div>
</Card>
-31
View File
@@ -1,31 +0,0 @@
<script lang="ts">
import type { Tab } from '$lib/types';
import { slide } from 'svelte/transition';
import Tabs from './Tabs.svelte';
export let isCloseable = true;
export let isOpen = true;
export let tabs: Tab[] = [];
export let activeTabID = '';
export let title: string;
$: isOpen = isCloseable ? isOpen : true;
$: isTabsShown = isOpen && tabs.length > 0;
</script>
<div class="card rounded overflow-hidden m-2 flex-grow flex flex-col shadow-2xl">
<div
class="bg-primary p-2 {isTabsShown ? 'pb-0' : ''} flex-none cursor-pointer"
on:click={() => (isOpen = !isOpen)}
on:keypress={() => (isOpen = !isOpen)}>
<div class="flex justify-between">
<Tabs on:select {tabs} bind:isOpen {title} {isCloseable} {activeTabID} />
<div class="flex gap-x-4 items-center {isTabsShown ? '-mt-2' : ''}">
<slot name="actions" />
</div>
</div>
</div>
{#if isOpen}
<div class="card-body p-0 flex-grow overflow-auto text-base-content" transition:slide>
<slot />
</div>
{/if}
</div>
-52
View File
@@ -1,52 +0,0 @@
<script lang="ts">
import type { Tab, TabEvents } from '$lib/types';
import { createEventDispatcher } from 'svelte';
import { fade } from 'svelte/transition';
export let isCloseable = true;
export let tabs: Tab[];
export let title: string;
export let isOpen = false;
export let activeTabID: string;
if (!activeTabID && tabs.length > 0) {
activeTabID = tabs[0].id;
}
const dispatch = createEventDispatcher<TabEvents>();
const toggleTabs = (tab: Tab) => {
activeTabID = tab.id;
dispatch('select', tab);
};
</script>
<div class="flex cursor-default">
<span
class="mr-2 font-semibold"
on:click|stopPropagation={() => (isOpen = !isOpen)}
on:keypress|stopPropagation={() => (isOpen = !isOpen)}>
{#if isCloseable}
<i class="fas fa-chevron-right icon" class:isOpen />
{/if}
{title}</span>
{#if isOpen && tabs}
<ul class="tabs" transition:fade>
{#each tabs as tab}
<div
class="tab tab-lifted {activeTabID === tab.id ? 'tab-active' : 'text-primary-content'}"
on:click|stopPropagation={() => toggleTabs(tab)}
on:keypress|stopPropagation={() => toggleTabs(tab)}>
<i class="mr-1 {tab.icon}" />
{tab.title}
</div>
{/each}
</ul>
{/if}
</div>
<style>
.icon {
transition-duration: 0.5s;
}
.isOpen {
transform: rotate(90deg);
}
</style>
-23
View File
@@ -1,23 +0,0 @@
import { cleanup, render } from '@testing-library/svelte';
import { describe, expect, it, afterEach } from 'vitest';
import Card from './Card.svelte';
describe('card.svelte', () => {
// TODO: @testing-library/svelte claims to add this automatically but it doesn't work without explicit afterEach
afterEach(() => cleanup());
it('mounts', () => {
const { container } = render(Card, {
title: 'TabTest',
tabs: [
{ id: 't1', title: 'title1', icon: 'fab fa-git-alt' },
{ id: 't2', title: 'title2', icon: 'far fa-bookmark' }
]
});
expect(container).toBeTruthy();
expect(container).toHaveTextContent('TabTest');
expect(container).toHaveTextContent('title1');
expect(container).toHaveTextContent('title2');
expect(container).not.toHaveTextContent('title3');
});
});
-131
View File
@@ -1,131 +0,0 @@
<script lang="ts">
import type { EditorMode } from '$lib/types';
import { stateStore, updateCode, updateConfig } from '$lib/util/state';
import { themeStore } from '$lib/util/theme';
import { errorDebug, syncDiagram } from '$lib/util/util';
import type monaco from 'monaco-editor';
import { onMount } from 'svelte';
import initEditor from 'monaco-mermaid';
import { logEvent } from '$lib/util/stats';
let divEl: HTMLDivElement | undefined = undefined;
let editor: monaco.editor.IStandaloneCodeEditor | undefined;
let Monaco: typeof monaco | undefined;
let editorOptions: monaco.editor.IStandaloneEditorConstructionOptions = {
minimap: {
enabled: false
},
theme: 'mermaid',
overviewRulerLanes: 0
};
let text = '';
stateStore.subscribe(({ errorMarkers, editorMode, code, mermaid }) => {
// console.log('editor store subscription', { code, mermaid });
if (!editor || !Monaco) {
return;
}
// Update editor text if it's different
const newText = editorMode === 'code' ? code : mermaid;
if (newText !== text) {
// console.log('updating editor text', newText);
editor.setValue(newText);
text = newText;
}
// Update editor mode if it's different
const language = editorMode === 'code' ? 'mermaid' : 'json';
const model = editor.getModel();
if (!model) {
console.error("editor model doesn't exist");
return;
}
if (model.getLanguageId() !== language) {
Monaco.editor.setModelLanguage(model, language);
}
// Display/clear errors
Monaco.editor.setModelMarkers(model, 'mermaid', errorMarkers);
});
themeStore.subscribe(({ isDark }) => {
editor && Monaco?.editor.setTheme(isDark ? 'mermaid-dark' : 'mermaid');
});
const handleUpdate = (text: string, mode: EditorMode) => {
// console.log('editor HandleUpdate', { text, mode });
if (mode === 'code') {
updateCode(text);
} else {
updateConfig(text);
}
};
const loadMonaco = async () => {
console.log('Loading Monaco...');
// errorDebug();
let i = 0;
while (i++ < 500) {
// @ts-expect-error : This is a hack to handle a svelte-kit error when importing monaco.
Monaco = window.monaco;
if (Monaco !== undefined) {
return;
}
await new Promise((r) => setTimeout(r, 100));
}
alert('Loading Monaco Editor failed. Please try refreshing the page.');
};
onMount(async () => {
await loadMonaco(); // Fix https://github.com/mermaid-js/mermaid-live-editor/issues/175
if (!Monaco) {
throw new Error('Monaco failed to load');
}
if (!divEl) {
throw new Error('divEl is undefined');
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
initEditor(Monaco);
errorDebug(100);
editor = Monaco.editor.create(divEl, editorOptions);
editor.onDidChangeModelContent(({ isFlush, changes }) => {
const newText = editor?.getValue();
// console.log('editor onDidChangeModelContent', { text, newText, isFlush, changes });
if (!newText || text === newText || isFlush) {
return;
}
text = newText;
handleUpdate(text, $stateStore.editorMode);
});
editor.addAction({
id: 'mermaid-render-diagram',
label: 'Render Diagram',
keybindings: [Monaco.KeyMod.CtrlCmd | Monaco.KeyCode.Enter],
run: function () {
syncDiagram();
logEvent('renderDiagram', {
method: 'keyboadShortcut'
});
}
});
Monaco.editor.setTheme($themeStore.isDark ? 'mermaid-dark' : 'mermaid');
const resizeObserver = new ResizeObserver((entries) => {
editor!.layout({
height: entries[0].contentRect.height,
width: entries[0].contentRect.width
});
});
if (divEl.parentElement) {
resizeObserver.observe(divEl.parentElement);
}
// console.log(`editor mounted`);
return () => {
// console.log(`editor disposed`);
editor?.dispose();
};
});
</script>
<div bind:this={divEl} id="editor" class="overflow-hidden" />
-195
View File
@@ -1,195 +0,0 @@
<script lang="ts">
import Card from '$lib/components/Card/Card.svelte';
import { inputStateStore, getStateString } from '$lib/util/state';
import {
addHistoryEntry,
historyModeStore,
clearHistoryData,
getPreviousState,
historyStore,
loaderHistoryStore,
restoreHistory
} from './history';
import { notify, prompt } from '$lib/util/notify';
import { onMount } from 'svelte';
import { get } from 'svelte/store';
import dayjs from 'dayjs';
import dayjsRelativeTime from 'dayjs/plugin/relativeTime';
import type { HistoryEntry, HistoryType, State, Tab } from '$lib/types';
import { logEvent } from '$lib/util/stats';
dayjs.extend(dayjsRelativeTime);
const HISTORY_SAVE_INTERVAL = 60000;
const tabSelectHandler = (message: CustomEvent<Tab>) => {
historyModeStore.set(message.detail.id as HistoryType);
};
let tabs: Tab[] = [
{
id: 'manual',
title: 'Saved',
icon: 'far fa-bookmark'
},
{
id: 'auto',
title: 'Timeline',
icon: 'fas fa-history'
}
];
const downloadHistory = () => {
const data = get(historyStore);
const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `mermaid-history-${dayjs().format('YYYY-MM-DD-HHmmss')}.json`;
a.click();
URL.revokeObjectURL(url);
logEvent('history', {
action: 'download'
});
};
const uploadHistory = () => {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'application/json';
input.addEventListener('change', ({ target }: Event) => {
const file = (<HTMLInputElement>target).files[0];
if (!file) {
return;
}
const reader = new FileReader();
reader.onload = (e) => {
const data: HistoryEntry[] = JSON.parse(e.target.result as string);
restoreHistory(data);
};
reader.readAsText(file);
});
input.click();
};
const saveHistory = (auto = false) => {
const currentState: string = getStateString();
const previousState: string = getPreviousState(auto);
if (previousState !== currentState) {
addHistoryEntry({
state: $inputStateStore,
time: Date.now(),
type: auto ? 'auto' : 'manual'
});
} else if (!auto) {
notify('State already saved.');
}
};
const clearHistory = (id?: string): void => {
if (!id && !prompt('Clear all saved items?')) {
return;
}
clearHistoryData(id);
};
const restoreHistoryItem = (state: State): void => {
inputStateStore.set({ ...state, updateDiagram: true });
};
const relativeTime = (time: number) => {
const t = new Date(time);
return `${new Date(t).toLocaleString()} (${dayjs(t).fromNow()})`;
};
onMount(() => {
historyModeStore.set('manual');
setInterval(() => {
saveHistory(true);
}, HISTORY_SAVE_INTERVAL);
});
loaderHistoryStore.subscribe((entries) => {
if (entries.length > 0 && tabs.length === 2) {
tabs = [
{
id: 'loader',
title: 'Revisions',
icon: 'fab fa-git-alt'
},
...tabs
];
historyModeStore.set('loader');
}
});
let isOpen = false;
</script>
<Card on:select={tabSelectHandler} bind:isOpen {tabs} title="History">
<div slot="actions">
<button
id="uploadHistory"
class="btn btn-xs btn-secondary w-12"
on:click|stopPropagation={() => uploadHistory()}
title="Upload history"><i class="fa fa-upload" /></button>
{#if $historyStore.length > 0}
<button
id="downloadHistory"
class="btn btn-xs btn-secondary w-12"
on:click|stopPropagation={() => downloadHistory()}
title="Download history"><i class="fa fa-download" /></button>
{/if}
|
<button
id="saveHistory"
class="btn btn-xs btn-success w-12"
on:click|stopPropagation={() => saveHistory()}
title="Save current state"><i class="far fa-save" /></button>
{#if $historyModeStore !== 'loader'}
<button
id="clearHistory"
class="btn btn-xs btn-error w-12"
on:click|stopPropagation={() => clearHistory()}
title="Delete all saved states"><i class="fas fa-trash-alt" /></button>
{/if}
</div>
<ul class="p-2 space-y-2 overflow-auto h-56" id="historyList">
{#if $historyStore.length > 0}
{#each $historyStore as { id, state, time, name, url, type }}
<li class="rounded p-2 shadow flex-col">
<div class="flex">
<div class="flex-1">
<div class="flex flex-col text-base-content">
{#if url}
<a
href={url}
target="_blank"
rel="noreferrer"
title="Open revision in new tab"
class="hover:underline text-blue-500">{name}</a>
{:else}
<span>{name}</span>
{/if}
<span class="text-gray-400 text-sm">{relativeTime(time)}</span>
</div>
</div>
<div class="flex gap-2 content-center">
<button class="btn btn-success" on:click={() => restoreHistoryItem(state)}
><i class="fas fa-undo mr-1" />Restore</button>
{#if type !== 'loader'}
<button class="btn btn-error" on:click={() => clearHistory(id)}
><i class="fas fa-trash-alt mr-1" />Delete</button>
{/if}
</div>
</div>
</li>
{/each}
{:else}
<div class="m-2">
No items in History<br />
Click the Save button to save current state and restore it later.<br />
Timeline will automatically be saved every minute.
</div>
{/if}
</ul>
</Card>
-126
View File
@@ -1,126 +0,0 @@
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';
describe('history', () => {
it('should handle saving individual history entry', () => {
expect(window.localStorage.getItem('manualHistoryStore')).toBe('[]');
expect(window.localStorage.getItem('autoHistoryStore')).toBe('[]');
addHistoryEntry({
state: defaultState,
time: 12_345,
type: 'manual'
});
const [manualEntry] = JSON.parse(
window.localStorage.getItem('manualHistoryStore') ?? '[]'
) as HistoryEntry[];
expect(manualEntry.time).toBe(12_345);
expect(manualEntry.type).toBe('manual');
expect(manualEntry.name).not.toBeNull();
expect(manualEntry.state).not.toBeNull();
addHistoryEntry({
state: defaultState,
time: 54_321,
type: 'auto'
});
const [autoEntry] = JSON.parse(
window.localStorage.getItem('autoHistoryStore') ?? '[]'
) as HistoryEntry[];
expect(autoEntry.time).toBe(54_321);
expect(autoEntry.type).toBe('auto');
expect(autoEntry.name).not.toBeNull();
expect(autoEntry.state).not.toBeNull();
historyModeStore.set('manual');
clearHistoryData();
historyModeStore.set('auto');
clearHistoryData();
expect(window.localStorage.getItem('manualHistoryStore')).toBe('[]');
expect(window.localStorage.getItem('autoHistoryStore')).toBe('[]');
});
it('should clear history entries', () => {
addHistoryEntry({
state: defaultState,
time: 12_345,
type: 'manual'
});
addHistoryEntry({
state: { ...defaultState, code: 'graph TD\\n A[Christmas] -->|Get money| B(Go shopping)' },
time: 123_456,
type: 'manual'
});
historyModeStore.set('manual');
const store: HistoryEntry[] = get(historyStore);
expect(store.length).toBe(2);
clearHistoryData(store[1].id);
expect(get(historyStore).length).toBe(1);
clearHistoryData();
expect(get(historyStore).length).toBe(0);
historyModeStore.set('auto');
addHistoryEntry({
state: defaultState,
time: 54_321,
type: 'auto'
});
addHistoryEntry({
state: { ...defaultState, code: 'graph TD\\n A[Christmas] -->|Get money| B(Go shopping)' },
time: 654_321,
type: 'auto'
});
expect(get(historyStore).length).toBe(2);
clearHistoryData();
expect(get(historyStore).length).toBe(0);
// Test calling when history is empty
clearHistoryData();
expect(get(historyStore).length).toBe(0);
});
});
describe('history migration', () => {
it('should inject history IDs as migration', () => {
window.localStorage.setItem(
'manualHistoryStore',
'[{"state":{"code":"graph TD\\n A[Halloween] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":false},"time":0,"type":"manual","name":"hollow-art"},{"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":"helpful-ocean"}]'
);
window.localStorage.setItem(
'autoHistoryStore',
'[{"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[];
expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(false);
expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(false);
injectHistoryIDs();
manualHistoryStore = JSON.parse(
window.localStorage.getItem('manualHistoryStore') ?? '[]'
) as HistoryEntry[];
autoHistoryStore = JSON.parse(
window.localStorage.getItem('autoHistoryStore') ?? '[]'
) as HistoryEntry[];
expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(true);
expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(true);
});
});
-152
View File
@@ -1,152 +0,0 @@
import { derived, writable, get } from 'svelte/store';
import type { Readable, Writable } from 'svelte/store';
import { persist, localStorage } from '$lib/util/persist';
import { generateSlug } from 'random-word-slugs';
import type { HistoryEntry, HistoryType, Optional } from '$lib/types';
import { v4 as uuidV4 } from 'uuid';
import { logEvent } from '$lib/util/stats';
const MAX_AUTO_HISTORY_LENGTH = 30;
export const historyModeStore: Writable<HistoryType> = persist(
writable('manual'),
localStorage(),
'autoHistoryMode'
);
const autoHistoryStore: Writable<HistoryEntry[]> = persist(
writable([]),
localStorage(),
'autoHistoryStore'
);
const manualHistoryStore: Writable<HistoryEntry[]> = persist(
writable([]),
localStorage(),
'manualHistoryStore'
);
export const loaderHistoryStore: Writable<HistoryEntry[]> = writable([]);
export const historyStore: Readable<HistoryEntry[]> = derived(
[historyModeStore, autoHistoryStore, manualHistoryStore, loaderHistoryStore],
([historyMode, autoHistories, manualHistories, loadedHistories], set) => {
switch (historyMode) {
case 'auto': {
set(autoHistories);
break;
}
case 'manual': {
set(manualHistories);
break;
}
case 'loader': {
set(loadedHistories);
break;
}
default: {
set(autoHistories);
}
}
}
);
export const addHistoryEntry = (entryToAdd: Optional<HistoryEntry, 'id'>): void => {
const entry: HistoryEntry = {
...entryToAdd,
id: uuidV4()
};
if (entry.type === 'loader') {
loaderHistoryStore.update((entries) => [entry, ...entries]);
return;
}
if (!entry.name) {
entry.name = generateSlug(2);
}
if (entry.type === 'auto') {
autoHistoryStore.update((entries) => {
if (entries.length >= MAX_AUTO_HISTORY_LENGTH) {
entries = entries.slice(0, MAX_AUTO_HISTORY_LENGTH - 1);
}
return [entry, ...entries];
});
} else if (entry.type === 'manual') {
manualHistoryStore.update((entries) => [entry, ...entries]);
logEvent('history', { action: 'save' });
}
};
export const clearHistoryData = (idToClear?: string): void => {
(get(historyModeStore) === 'auto' ? autoHistoryStore : manualHistoryStore).update((entries) => {
if (get(historyModeStore) !== 'loader') {
entries = entries.filter(({ id }) => idToClear && id != idToClear);
logEvent('history', { action: 'clear', type: idToClear ? 'single' : 'all' });
}
return entries;
});
};
export const getPreviousState = (auto: boolean): string => {
const entries = get(auto ? autoHistoryStore : manualHistoryStore);
if (entries.length > 0) {
return JSON.stringify(entries[0].state);
}
return '';
};
export const restoreHistory = (data: HistoryEntry[]) => {
const entries = data.filter((element) => validateEntry(element));
const invalidEntryCount = data.length - entries.length;
if (invalidEntryCount > 0) {
console.error(`${invalidEntryCount} invalid history entries were removed.`);
console.error(data);
}
if (entries.length > 0) {
let entryCount = 0;
(entries[0].type === 'auto' ? autoHistoryStore : manualHistoryStore).update((existing) => {
const existingIDs = new Set(existing.map(({ id }) => id));
const newEntries = entries.filter(({ id }) => !existingIDs.has(id));
entryCount = newEntries.length;
const combined = [...existing, ...newEntries];
combined.sort((a, b) => b.time - a.time);
return combined;
});
alert(
`${entryCount} entries restored. ${invalidEntryCount} invalid, ${
entries.length - entryCount
} duplicates.`
);
logEvent('history', {
action: 'restore',
success: entryCount,
invalid: invalidEntryCount,
duplicates: entries.length - entryCount
});
} else {
alert('No valid entries found.');
}
};
const setIDs = (entries: HistoryEntry[]) => {
for (const entry of entries) {
if (!entry.id) {
entry.id = uuidV4();
}
}
return entries;
};
export const injectHistoryIDs = (): void => {
autoHistoryStore.update(setIDs);
manualHistoryStore.update(setIDs);
};
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;
};
-82
View File
@@ -1,82 +0,0 @@
<script context="module" lang="ts">
import { version } from 'mermaid/package.json';
import { analytics } from '$lib/util/stats';
void analytics?.track('version', {
mermaidVersion: version
});
</script>
<script lang="ts">
import Theme from './Theme.svelte';
interface Link {
title: string;
href: string;
icon?: string;
}
const links: Link[] = [
{
title: 'Documentation',
href: 'https://mermaid-js.github.io/mermaid/intro/n00b-gettingStarted.html'
},
{
title: 'Tutorial',
href: 'https://mermaid-js.github.io/mermaid/config/Tutorials.html'
},
{
title: 'Mermaid',
href: 'https://github.com/mermaid-js/mermaid'
},
{
title: 'CLI',
href: 'https://github.com/mermaid-js/mermaid-cli'
},
{
title: '',
href: 'https://github.com/mermaid-js/mermaid-live-editor',
icon: 'fab fa-github fa-lg'
}
];
</script>
<div class="navbar shadow-lg bg-primary p-0">
<div class="flex-1 px-2 mx-2">
<span class="text-lg font-bold">
<a href="/">Mermaid<span class="text-xs font-thin">v{version}</span> Live Editor</a>
</span>
</div>
<label for="menu-toggle" class="pointer-cursor lg:hidden block"
><svg
class="fill-current "
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 20 20"
><title>Menu</title><path d="M0 3h20v2H0V3zm0 6h20v2H0V9zm0 6h20v2H0v-2z" /></svg
></label>
<input class="hidden" type="checkbox" id="menu-toggle" />
<Theme />
<div class="hidden lg:flex lg:items-center lg:w-auto w-full" id="menu">
<ul class="lg:flex items-center justify-between text-base pt-4 lg:pt-0">
{#each links as { title, href, icon }}
<li>
<a class="btn btn-ghost" target="_blank" rel="noreferrer" {href}>
{#if icon}
<i class={icon} />
{/if}
{title}</a>
</li>
{/each}
</ul>
</div>
</div>
<style>
#menu-toggle:checked + #menu {
display: block;
}
.navbar {
z-index: 10000;
}
</style>
-64
View File
@@ -1,64 +0,0 @@
<script lang="ts">
import { setTheme, themeStore } from '$lib/util/theme';
const themes = [
'🌝 light',
'🌚 dark',
'🧁 cupcake',
'🐝 bumblebee',
'✳️ emerald',
'🏢 corporate',
'🌃 synthwave',
'👴 retro',
'🤖 cyberpunk',
'🌸 valentine',
'🎃 halloween',
'🌷 garden',
'🌲 forest',
'🐟 aqua',
'👓 lofi',
'🖍 pastel',
'🧚‍♀️ fantasy',
'📝 wireframe',
'🏴 black',
'💎 luxury',
'🧛‍♂️ dracula'
];
</script>
<div class="hidden lg:block dropdown">
<!-- svelte-ignore a11y-no-noninteractive-tabindex -->
<div tabindex="0" class="btn btn-ghost ">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
class="inline-block w-6 h-6 stroke-current md:mr-2"
><path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01" /></svg>
<span class="hidden md:inline"> Change Theme </span>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 1792 1792"
class="inline-block w-4 h-4 ml-1 fill-current"
><path
d="M1395 736q0 13-10 23l-466 466q-10 10-23 10t-23-10l-466-466q-10-10-10-23t10-23l50-50q10-10 23-10t23 10l393 393 393-393q10-10 23-10t23 10l50 50q10 10 10 23z" /></svg>
</div>
<div
class="mt-14 overflow-y-auto shadow-2xl top-px dropdown-content h-96 w-56 bg-base-200 text-base-content">
<!-- svelte-ignore a11y-no-noninteractive-tabindex -->
<ul tabindex="0" class="p-4 menu compact">
{#each themes as theme}
<li class:bordered={$themeStore.theme !== undefined && theme.includes($themeStore.theme)}>
<span
class="btn btn-ghost justify-start"
on:click={() => setTheme(theme)}
on:keypress={() => setTheme(theme)}>{theme}</span>
</li>
{/each}
</ul>
</div>
</div>
-165
View File
@@ -1,165 +0,0 @@
<script lang="ts">
import { inputStateStore, stateStore, updateCodeStore } from '$lib/util/state';
import { onMount } from 'svelte';
import panzoom from 'svg-pan-zoom';
import type { State, ValidatedState } from '$lib/types';
import { logEvent } from '$lib/util/stats';
import { cmdKey } from '$lib/util/util';
import { render as renderDiagram } from '$lib/util/mermaid';
import type { MermaidConfig } from 'mermaid';
let code = '';
let config = '';
let container: HTMLDivElement;
let view: HTMLDivElement;
let error = false;
let outOfSync = false;
let hide = false;
let manualUpdate = true;
let panZoomEnabled = $stateStore.panZoom;
let pzoom: typeof panzoom | undefined;
const handlePanZoomChange = () => {
if (!pzoom) {
return;
}
const pan = pzoom.getPan();
const zoom = pzoom.getZoom();
updateCodeStore({ pan, zoom });
logEvent('panZoom');
};
const handlePanZoom = (state: State) => {
if (!state.panZoom) {
return;
}
hide = true;
pzoom?.destroy();
pzoom = undefined;
void Promise.resolve().then(() => {
const graphDiv = document.getElementById('graph-div');
if (!graphDiv) {
return;
}
pzoom = panzoom(graphDiv, {
onPan: handlePanZoomChange,
onZoom: handlePanZoomChange,
controlIconsEnabled: true,
fit: true,
center: true
});
const { pan, zoom } = state;
if (pan !== undefined && zoom !== undefined && Number.isFinite(zoom)) {
pzoom.zoom(zoom);
pzoom.pan(pan);
}
hide = false;
});
};
const handleStateChange = async (state: ValidatedState) => {
if (state.error !== undefined) {
error = true;
return;
}
error = false;
try {
if (container && state && (state.updateDiagram || state.autoSync)) {
if (!state.autoSync) {
$inputStateStore.updateDiagram = false;
}
outOfSync = false;
manualUpdate = true;
// Do not render if there is no change in Code/Config/PanZoom
if (code === state.code && config === state.mermaid && panZoomEnabled === state.panZoom) {
return;
}
code = state.code;
config = state.mermaid;
panZoomEnabled = state.panZoom;
const scroll = view.parentElement!.scrollTop;
delete container.dataset.processed;
const { svg, bindFunctions } = await renderDiagram(
Object.assign({}, JSON.parse(state.mermaid)) as MermaidConfig,
code,
'graph-div'
);
if (svg.length > 0) {
handlePanZoom(state);
container.innerHTML = svg;
console.log({ svg });
const graphDiv = document.getElementById('graph-div');
if (!graphDiv) {
throw new Error('graph-div not found');
}
graphDiv.setAttribute('height', '100%');
graphDiv.style.maxWidth = '100%';
if (bindFunctions) {
bindFunctions(graphDiv);
}
}
view.parentElement!.scrollTop = scroll;
error = false;
} else if (manualUpdate) {
manualUpdate = false;
} else if (code !== state.code || config !== state.mermaid) {
outOfSync = true;
}
} catch (e) {
console.error('view fail', e);
error = true;
}
};
onMount(() => {
stateStore.subscribe((state) => {
void handleStateChange(state);
});
window.addEventListener('resize', () => {
if ($stateStore.panZoom && pzoom) {
pzoom.resize();
}
});
// console.log('View mounted');
});
</script>
{#if (error && $stateStore.error instanceof Error) || outOfSync}
<div
class="absolute w-full p-2 z-10 font-mono {error
? 'text-red-600'
: 'text-yellow-600'} bg-base-100 bg-opacity-80 text-center"
id="errorContainer">
{#if error}
{@html $stateStore.error?.toString().replace(/\n/g, '<br />')}
{:else}
Diagram out of sync. <br />
Press <i class="fas fa-sync" /> (Sync button) or <kbd>{cmdKey} + Enter</kbd> to sync.
{/if}
</div>
{/if}
<div id="view" bind:this={view} class="p-2 h-full" class:error class:outOfSync>
<div id="container" bind:this={container} class="h-full overflow-auto" class:hide />
</div>
<style>
#view {
flex: 1;
}
#container {
transition: visibility 0.3s;
}
.error,
.outOfSync {
opacity: 0.5;
}
.hide {
visibility: hidden;
}
</style>
+259
View File
@@ -0,0 +1,259 @@
<script lang="ts">
import { browser } from '$app/environment';
import Card from '$lib/components/card/card.svelte';
import { env } from '$lib/util/env';
import { pakoSerde } from '$lib/util/serde';
import { stateStore } from '$lib/util/state';
import { logEvent } from '$lib/util/stats';
import { toBase64 } from 'js-base64';
import moment from 'moment';
const { krokiRendererUrl, rendererUrl } = env;
type Exporter = (context: CanvasRenderingContext2D, image: HTMLImageElement) => () => void;
const getFileName = (ext: string) =>
`mermaid-diagram-${moment().format('YYYY-MM-DD-HHmmss')}.${ext}`;
const getBase64SVG = (svg?: HTMLElement, width?: number, height?: number): string => {
svg?.setAttribute('height', `${height}px`);
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 = getSvgEl();
}
const svgString = svg.outerHTML
.replaceAll('<br>', '<br/>')
.replaceAll(/<img([^>]*)>/g, (m, g: string) => `<img ${g} />`);
return toBase64(svgString);
};
const exportImage = (event: Event, exporter: Exporter) => {
const canvas: HTMLCanvasElement = document.createElement('canvas');
const svg: HTMLElement = document.querySelector('#container svg');
const box: DOMRect = svg.getBoundingClientRect();
canvas.width = box.width;
canvas.height = box.height;
if (imagemodeselected === 'width') {
const ratio = box.height / box.width;
canvas.width = userimagesize;
canvas.height = userimagesize * ratio;
} else if (imagemodeselected === 'height') {
const ratio = box.width / box.height;
canvas.width = userimagesize * ratio;
canvas.height = userimagesize;
}
const context = canvas.getContext('2d');
context.fillStyle = 'white';
context.fillRect(0, 0, canvas.width, canvas.height);
const image = new Image();
image.onload = exporter(context, image);
image.src = `data:image/svg+xml;base64,${getBase64SVG(svg, canvas.width, canvas.height)}`;
event.stopPropagation();
event.preventDefault();
};
const getSvgEl = () => {
const svgEl: HTMLElement = document
.querySelector('#container svg')
.cloneNode(true) as HTMLElement;
svgEl.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
const fontAwesomeCdnUrl = Array.from(document.head.getElementsByTagName('link'))
.map((l) => l.href)
.find((h) => h && h.includes('font-awesome'));
if (fontAwesomeCdnUrl == null) {
return svgEl;
}
const styleEl = document.createElement('style');
styleEl.innerText = `@import url("${fontAwesomeCdnUrl}");'`;
svgEl.prepend(styleEl);
return svgEl;
};
const simulateDownload = (download: string, href: string): void => {
const a = document.createElement('a');
a.download = download;
a.href = href;
a.click();
a.remove();
};
const downloadImage: Exporter = (context, image) => {
return () => {
const { canvas } = context;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
simulateDownload(
getFileName('png'),
canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream')
);
};
};
const isClipboardAvailable = (): boolean => {
return Object.prototype.hasOwnProperty.call(window, 'ClipboardItem') as boolean;
};
const clipboardCopy: Exporter = (context, image) => {
return () => {
const { canvas } = context;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
canvas.toBlob((blob) => {
try {
// @ts-ignore: https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1004/files
void navigator.clipboard.write([
/* eslint-disable no-undef */
// @ts-ignore: https://github.com/microsoft/TypeScript/issues/43821
new ClipboardItem({
[blob.type]: blob
})
]);
} catch (error) {
console.error(error);
}
});
};
};
const onCopyClipboard = (event: Event) => {
exportImage(event, clipboardCopy);
logEvent('copyClipboard');
};
const onDownloadPNG = (event: Event) => {
exportImage(event, downloadImage);
logEvent('download', {
type: 'png'
});
};
const onDownloadSVG = () => {
simulateDownload(getFileName('svg'), `data:image/svg+xml;base64,${getBase64SVG()}`);
logEvent('download', {
type: 'svg'
});
};
const onCopyMarkdown = () => {
(document.getElementById('markdown') as HTMLInputElement).select();
document.execCommand('Copy');
logEvent('copyMarkdown');
};
let gistURL = '';
stateStore.subscribe(({ loader }) => {
if (loader?.type === 'gist') {
// @ts-ignore Gist will have url
gistURL = loader.config.url;
}
});
const loadGist = () => {
if (!gistURL) {
alert('Please enter a Gist URL first');
}
window.location.href = `${window.location.pathname}?gist=${gistURL}`;
logEvent('loadGist');
};
let iUrl: string;
let svgUrl: string;
let krokiUrl: string;
let mdCode: string;
let imagemodeselected = 'auto';
let userimagesize = 1080;
let isNetlify = false;
if (browser && ['mermaid.live', 'netlify'].some((path) => window.location.host.includes(path))) {
isNetlify = true;
}
stateStore.subscribe(({ code, serialized }) => {
iUrl = `${rendererUrl}/img/${serialized}?type=png`;
svgUrl = `${rendererUrl}/svg/${serialized}`;
krokiUrl = `${krokiRendererUrl}/mermaid/svg/${pakoSerde.serialize(code)}`;
mdCode = `[![](${iUrl})](${window.location.protocol}//${window.location.host}${window.location.pathname}#${serialized})`;
});
</script>
<Card title="Actions" isOpen={true}>
<div class="flex flex-wrap gap-2 m-2">
{#if isClipboardAvailable()}
<button class="action-btn w-full" on:click={onCopyClipboard}
><i class="far fa-copy mr-2" /> Copy Image to clipboard
</button>
{/if}
<button id="downloadPNG" class="action-btn flex-grow" on:click={onDownloadPNG}>
<i class="fas fa-download mr-2" /> PNG
</button>
<button id="downloadSVG" class="action-btn flex-grow" on:click={onDownloadSVG}>
<i class="fas fa-download mr-2" /> SVG
</button>
<a target="_blank" rel="noreferrer" class="flex-grow" href={iUrl}>
<button class="action-btn w-full">
<i class="fas fa-external-link-alt mr-2" /> PNG
</button>
</a>
<a target="_blank" rel="noreferrer" class="flex-grow" href={svgUrl}>
<button class="action-btn w-full">
<i class="fas fa-external-link-alt mr-2" /> SVG
</button>
</a>
<a target="_blank" rel="noreferrer" class="flex-grow" href={krokiUrl}>
<button class="action-btn w-full">
<i class="fas fa-external-link-alt mr-2" /> Kroki
</button>
</a>
<div class="flex gap-2 items-center">
PNG size
<label for="autosize">
<input type="radio" value="auto" id="autosize" bind:group={imagemodeselected} /> Auto
</label>
<label for="width">
<input type="radio" value="width" id="width" bind:group={imagemodeselected} /> Width
</label>
<label for="height">
<input type="radio" value="height" id="height" bind:group={imagemodeselected} /> Height
</label>
{#if imagemodeselected !== 'auto'}
<input
id="height"
class="input"
type="number"
min="3"
max="10000"
bind:value={userimagesize} />
{/if}
</div>
<div class="w-full flex gap-2 items-center">
<input class="input" id="markdown" type="text" value={mdCode} on:click={onCopyMarkdown} />
<label for="markdown">
<button class="btn btn-primary btn-md flex-auto" on:click={onCopyMarkdown}>
Copy Markdown
</button>
</label>
</div>
<div class="w-full flex gap-2 items-center">
<input
class="input"
id="gist"
type="text"
bind:value={gistURL}
placeholder="Enter Gist URL" />
<label for="gist">
<button class="btn btn-primary btn-md flex-auto" on:click={loadGist}> Load Gist </button>
</label>
</div>
{#if isNetlify}
<div class="w-full flex items-center justify-center">
<a class="link underline text-gray-500 text-sm" href="https://netlify.com">
This site is powered by Netlify
</a>
</div>
{/if}
</div>
</Card>
@@ -0,0 +1,3 @@
// Vitest Snapshot v1
exports[`card.svelte > mounts 1`] = `"<div><div class=\\"card rounded overflow-hidden m-2 flex-grow flex flex-col shadow-2xl\\"><div class=\\"bg-primary p-2 pb-0 flex-none cursor-pointer\\"><div class=\\"flex justify-between\\"><div class=\\"flex cursor-default s-_wx1E_JHsCoF\\"><span class=\\"mr-2 font-semibold s-_wx1E_JHsCoF\\"><i class=\\"fas fa-chevron-right icon s-_wx1E_JHsCoF isOpen\\"></i> TabTest</span> <ul class=\\"tabs s-_wx1E_JHsCoF\\"><div class=\\"tab tab-lifted tab-active s-_wx1E_JHsCoF\\"><i class=\\"mr-1 undefined s-_wx1E_JHsCoF\\"></i> title1 </div><div class=\\"tab tab-lifted text-primary-content s-_wx1E_JHsCoF\\"><i class=\\"mr-1 undefined s-_wx1E_JHsCoF\\"></i> title2 </div></ul></div><!--<Tabs>--> <div class=\\"flex gap-x-4 items-center -mt-2\\"></div></div></div> <div class=\\"card-body p-0 flex-grow overflow-auto text-base-content\\"></div></div><!--<Card>--></div>"`;
+31
View File
@@ -0,0 +1,31 @@
<script lang="ts">
import type { Tab } from '$lib/types';
import { slide } from 'svelte/transition';
import Tabs from './tabs.svelte';
export let isCloseable = true;
export let isOpen = true;
export let tabs: Tab[] = [];
export let activeTabID: string = '';
export let title: string;
$: isOpen = isCloseable ? isOpen : true;
$: isTabsShown = isOpen && tabs.length > 0;
</script>
<div class="card rounded overflow-hidden m-2 flex-grow flex flex-col shadow-2xl">
<div
class="bg-primary p-2 {isTabsShown ? 'pb-0' : ''} flex-none cursor-pointer"
on:click={() => (isOpen = !isOpen)}
on:keypress={() => (isOpen = !isOpen)}>
<div class="flex justify-between">
<Tabs on:select {tabs} bind:isOpen {title} {isCloseable} {activeTabID} />
<div class="flex gap-x-4 items-center {isTabsShown ? '-mt-2' : ''}">
<slot name="actions" />
</div>
</div>
</div>
{#if isOpen}
<div class="card-body p-0 flex-grow overflow-auto text-base-content" transition:slide>
<slot />
</div>
{/if}
</div>
+24
View File
@@ -0,0 +1,24 @@
import { cleanup, render } from '@testing-library/svelte';
import { describe, expect, it, afterEach } from 'vitest';
import Card from './card.svelte';
describe('card.svelte', () => {
// TODO: @testing-library/svelte claims to add this automatically but it doesn't work without explicit afterEach
afterEach(() => cleanup());
it('mounts', () => {
const { container } = render(Card, {
title: 'TabTest',
tabs: [
{ id: 't1', title: 'title1' },
{ id: 't2', title: 'title2' }
]
});
expect(container).toBeTruthy();
expect(container).toHaveTextContent('TabTest');
expect(container).toHaveTextContent('title1');
expect(container).toHaveTextContent('title2');
expect(container).not.toHaveTextContent('title3');
expect(container.innerHTML).toMatchSnapshot();
});
});
+52
View File
@@ -0,0 +1,52 @@
<script lang="ts">
import type { Tab, TabEvents } from '$lib/types';
import { createEventDispatcher } from 'svelte';
import { fade } from 'svelte/transition';
export let isCloseable = true;
export let tabs: Tab[];
export let title: string;
export let isOpen = false;
export let activeTabID: string;
if (!activeTabID && tabs.length > 0) {
activeTabID = tabs[0].id;
}
const dispatch = createEventDispatcher<TabEvents>();
const toggleTabs = (tab: Tab) => {
activeTabID = tab.id;
dispatch('select', tab);
};
</script>
<div class="flex cursor-default">
<span
class="mr-2 font-semibold"
on:click|stopPropagation={() => (isOpen = !isOpen)}
on:keypress|stopPropagation={() => (isOpen = !isOpen)}>
{#if isCloseable}
<i class="fas fa-chevron-right icon" class:isOpen />
{/if}
{title}</span>
{#if isOpen && tabs}
<ul class="tabs" transition:fade>
{#each tabs as tab}
<div
class="tab tab-lifted {activeTabID === tab.id ? 'tab-active' : 'text-primary-content'}"
on:click|stopPropagation={() => toggleTabs(tab)}
on:keypress|stopPropagation={() => toggleTabs(tab)}>
<i class="mr-1 {tab.icon}" />
{tab.title}
</div>
{/each}
</ul>
{/if}
</div>
<style>
.icon {
transition-duration: 0.5s;
}
.isOpen {
transform: rotate(90deg);
}
</style>
+103
View File
@@ -0,0 +1,103 @@
<script lang="ts">
import type { EditorMode } from '$lib/types';
import { stateStore, updateCode, updateConfig } from '$lib/util/state';
import { themeStore } from '$lib/util/theme';
import { syncDiagram } from '$lib/util/util';
import type monaco from 'monaco-editor';
import { onMount } from 'svelte';
import initEditor from 'monaco-mermaid';
import { logEvent } from '$lib/util/stats';
let divEl: HTMLDivElement = null;
let editor: monaco.editor.IStandaloneCodeEditor;
let Monaco: typeof monaco;
let editorOptions: monaco.editor.IStandaloneEditorConstructionOptions = {
minimap: {
enabled: false
},
theme: 'mermaid',
overviewRulerLanes: 0
};
let text = '';
stateStore.subscribe(({ errorMarkers, editorMode, code, mermaid }) => {
if (!editor) return;
// Update editor text if it's different
const newText = editorMode === 'code' ? code : mermaid;
if (newText !== text) {
editor.setValue(newText);
text = newText;
}
// Update editor mode if it's different
const language = editorMode === 'code' ? 'mermaid' : 'json';
if (editor.getModel().getLanguageId() !== language) {
Monaco?.editor.setModelLanguage(editor.getModel(), language);
}
// Display/clear errors
Monaco?.editor.setModelMarkers(editor.getModel(), 'mermaid', errorMarkers);
});
themeStore.subscribe(({ isDark }) => {
editor && Monaco?.editor.setTheme(isDark ? 'mermaid-dark' : 'mermaid');
});
const handleUpdate = (text: string, mode: EditorMode) => {
if (mode === 'code') {
updateCode(text);
} else {
updateConfig(text);
}
};
const loadMonaco = async () => {
console.log('Loading Monaco...');
let i = 0;
while (i++ < 500) {
// @ts-ignore : This is a hack to handle a svelte-kit error when importing monaco.
Monaco = window.monaco;
if (Monaco !== undefined) {
return;
}
await new Promise((r) => setTimeout(r, 100));
}
alert('Loading Monaco Editor failed. Please try refreshing the page.');
};
onMount(async () => {
await loadMonaco(); // Fix https://github.com/mermaid-js/mermaid-live-editor/issues/175
initEditor(Monaco);
editor = Monaco.editor.create(divEl, editorOptions);
editor.onDidChangeModelContent(() => {
text = editor.getValue();
handleUpdate(text, $stateStore.editorMode);
});
editor.addAction({
id: 'mermaid-render-diagram',
label: 'Render Diagram',
keybindings: [Monaco.KeyMod.CtrlCmd | Monaco.KeyCode.Enter],
run: function () {
syncDiagram();
logEvent('renderDiagram', {
method: 'keyboadShortcut'
});
}
});
Monaco?.editor.setTheme($themeStore.isDark ? 'mermaid-dark' : 'mermaid');
const resizeObserver = new ResizeObserver((entries) => {
editor.layout({
height: entries[0].contentRect.height,
width: entries[0].contentRect.width
});
});
resizeObserver.observe(divEl.parentElement);
return () => {
editor.dispose();
};
});
</script>
<div bind:this={divEl} id="editor" class="overflow-hidden" />
+192
View File
@@ -0,0 +1,192 @@
<script lang="ts">
import Card from '$lib/components/card/card.svelte';
import { inputStateStore, getStateString } from '$lib/util/state';
import {
addHistoryEntry,
historyModeStore,
clearHistoryData,
getPreviousState,
historyStore,
loaderHistoryStore,
restoreHistory
} from './history';
import { notify, prompt } from '$lib/util/notify';
import { onMount } from 'svelte';
import { get } from 'svelte/store';
import moment from 'moment';
import type { HistoryType, State, Tab } from '$lib/types';
import { logEvent } from '$lib/util/stats';
const HISTORY_SAVE_INTERVAL = 60000;
const tabSelectHandler = (message: CustomEvent<Tab>) => {
historyModeStore.set(message.detail.id as HistoryType);
};
let tabs: Tab[] = [
{
id: 'manual',
title: 'Saved',
icon: 'far fa-bookmark'
},
{
id: 'auto',
title: 'Timeline',
icon: 'fas fa-history'
}
];
const downloadHistory = () => {
const data = get(historyStore);
const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `mermaid-history-${moment().format('YYYY-MM-DD-HHmmss')}.json`;
a.click();
URL.revokeObjectURL(url);
logEvent('history', {
action: 'download'
});
};
const uploadHistory = () => {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'application/json';
input.addEventListener('change', ({ target }: Event) => {
const file = (<HTMLInputElement>target).files[0];
if (!file) {
return;
}
const reader = new FileReader();
reader.onload = (e) => {
const data = JSON.parse(e.target.result as string);
restoreHistory(data);
};
reader.readAsText(file);
});
input.click();
};
const saveHistory = (auto = false) => {
const currentState: string = getStateString();
const previousState: string = getPreviousState(auto);
if (previousState !== currentState) {
addHistoryEntry({
state: $inputStateStore,
time: Date.now(),
type: auto ? 'auto' : 'manual'
});
} else if (!auto) {
notify('State already saved.');
}
};
const clearHistory = (id?: string): void => {
if (!id && !prompt('Clear all saved items?')) {
return;
}
clearHistoryData(id);
};
const restoreHistoryItem = (state: State): void => {
inputStateStore.set({ ...state, updateDiagram: true });
};
const relativeTime = (time: number) => {
const t = new Date(time);
return `${new Date(t).toLocaleString()} (${moment(t).fromNow()})`;
};
onMount(() => {
historyModeStore.set('manual');
setInterval(() => {
saveHistory(true);
}, HISTORY_SAVE_INTERVAL);
});
loaderHistoryStore.subscribe((entries) => {
if (entries.length > 0 && tabs.length === 2) {
tabs = [
{
id: 'loader',
title: 'Revisions',
icon: 'fab fa-git-alt'
},
...tabs
];
historyModeStore.set('loader');
}
});
let isOpen = false;
</script>
<Card on:select={tabSelectHandler} bind:isOpen {tabs} title="History">
<div slot="actions">
<button
id="uploadHistory"
class="btn btn-xs btn-secondary w-12"
on:click|stopPropagation={() => uploadHistory()}
title="Upload history"><i class="fa fa-upload" /></button>
{#if $historyStore.length > 0}
<button
id="downloadHistory"
class="btn btn-xs btn-secondary w-12"
on:click|stopPropagation={() => downloadHistory()}
title="Download history"><i class="fa fa-download" /></button>
{/if}
|
<button
id="saveHistory"
class="btn btn-xs btn-success w-12"
on:click|stopPropagation={() => saveHistory()}
title="Save current state"><i class="far fa-save" /></button>
{#if $historyModeStore !== 'loader'}
<button
id="clearHistory"
class="btn btn-xs btn-error w-12"
on:click|stopPropagation={() => clearHistory()}
title="Delete all saved states"><i class="fas fa-trash-alt" /></button>
{/if}
</div>
<ul class="p-2 space-y-2 overflow-auto h-56" id="historyList">
{#if $historyStore.length > 0}
{#each $historyStore as { id, state, time, name, url, type }}
<li class="rounded p-2 shadow flex-col">
<div class="flex">
<div class="flex-1">
<div class="flex flex-col text-base-content">
{#if url}
<a
href={url}
target="_blank"
rel="noreferrer"
title="Open revision in new tab"
class="hover:underline text-blue-500">{name}</a>
{:else}
<span>{name}</span>
{/if}
<span class="text-gray-400 text-sm">{relativeTime(time)}</span>
</div>
</div>
<div class="flex gap-2 content-center">
<button class="btn btn-success" on:click={() => restoreHistoryItem(state)}
><i class="fas fa-undo mr-1" />Restore</button>
{#if type !== 'loader'}
<button class="btn btn-error" on:click={() => clearHistory(id)}
><i class="fas fa-trash-alt mr-1" />Delete</button>
{/if}
</div>
</div>
</li>
{/each}
{:else}
<div class="m-2">
No items in History<br />
Click the Save button to save current state and restore it later.<br />
Timeline will automatically be saved every minute.
</div>
{/if}
</ul>
</Card>
+120
View File
@@ -0,0 +1,120 @@
import type { HistoryEntry } from '$lib/types';
import { describe, it, expect } from 'vitest';
import {
addHistoryEntry,
injectHistoryIDs,
clearHistoryData,
historyModeStore,
historyStore
} from './history';
import { defaultState } from '../../util/state';
import { get } from 'svelte/store';
describe('history', () => {
it('should handle saving individual history entry', () => {
expect(window.localStorage.getItem('manualHistoryStore')).toBe('[]');
expect(window.localStorage.getItem('autoHistoryStore')).toBe('[]');
addHistoryEntry({
state: defaultState,
time: 12345,
type: 'manual'
});
const [manualEntry]: HistoryEntry[] = JSON.parse(
window.localStorage.getItem('manualHistoryStore')
);
expect(manualEntry.time).toBe(12345);
expect(manualEntry.type).toBe('manual');
expect(manualEntry.name).not.toBeNull();
expect(manualEntry.state).not.toBeNull();
addHistoryEntry({
state: defaultState,
time: 54321,
type: 'auto'
});
const [autoEntry]: HistoryEntry[] = JSON.parse(window.localStorage.getItem('autoHistoryStore'));
expect(autoEntry.time).toBe(54321);
expect(autoEntry.type).toBe('auto');
expect(autoEntry.name).not.toBeNull();
expect(autoEntry.state).not.toBeNull();
historyModeStore.set('manual');
clearHistoryData();
historyModeStore.set('auto');
clearHistoryData();
expect(window.localStorage.getItem('manualHistoryStore')).toBe('[]');
expect(window.localStorage.getItem('autoHistoryStore')).toBe('[]');
});
it('should clear history entries', () => {
addHistoryEntry({
state: defaultState,
time: 12345,
type: 'manual'
});
addHistoryEntry({
state: { ...defaultState, code: 'graph TD\\n A[Christmas] -->|Get money| B(Go shopping)' },
time: 123456,
type: 'manual'
});
historyModeStore.set('manual');
const store: HistoryEntry[] = get(historyStore);
expect(store.length).toBe(2);
clearHistoryData(store[1].id);
expect(get(historyStore).length).toBe(1);
clearHistoryData();
expect(get(historyStore).length).toBe(0);
historyModeStore.set('auto');
addHistoryEntry({
state: defaultState,
time: 54321,
type: 'auto'
});
addHistoryEntry({
state: { ...defaultState, code: 'graph TD\\n A[Christmas] -->|Get money| B(Go shopping)' },
time: 654321,
type: 'auto'
});
expect(get(historyStore).length).toBe(2);
clearHistoryData();
expect(get(historyStore).length).toBe(0);
// Test calling when history is empty
clearHistoryData();
expect(get(historyStore).length).toBe(0);
});
});
describe('history migration', () => {
it('should inject history IDs as migration', () => {
window.localStorage.setItem(
'manualHistoryStore',
'[{"state":{"code":"graph TD\\n A[Halloween] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":false},"time":0,"type":"manual","name":"hollow-art"},{"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":"helpful-ocean"}]'
);
window.localStorage.setItem(
'autoHistoryStore',
'[{"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: HistoryEntry[] = JSON.parse(
window.localStorage.getItem('manualHistoryStore')
);
let autoHistoryStore: HistoryEntry[] = JSON.parse(
window.localStorage.getItem('autoHistoryStore')
);
expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(false);
expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(false);
injectHistoryIDs();
manualHistoryStore = JSON.parse(window.localStorage.getItem('manualHistoryStore'));
autoHistoryStore = JSON.parse(window.localStorage.getItem('autoHistoryStore'));
expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(true);
expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(true);
});
});
+141
View File
@@ -0,0 +1,141 @@
import { derived, writable, get } from 'svelte/store';
import type { Readable, Writable } from 'svelte/store';
import { persist, localStorage } from '$lib/util/persist';
import { generateSlug } from 'random-word-slugs';
import type { HistoryEntry, HistoryType, Optional } from '$lib/types';
import { v4 as uuidV4 } from 'uuid';
import { logEvent } from '$lib/util/stats';
const MAX_AUTO_HISTORY_LENGTH = 30;
export const historyModeStore: Writable<HistoryType> = persist(
writable('manual'),
localStorage(),
'autoHistoryMode'
);
const autoHistoryStore: Writable<HistoryEntry[]> = persist(
writable([]),
localStorage(),
'autoHistoryStore'
);
const manualHistoryStore: Writable<HistoryEntry[]> = persist(
writable([]),
localStorage(),
'manualHistoryStore'
);
export const loaderHistoryStore: Writable<HistoryEntry[]> = writable([] as HistoryEntry[]);
export const historyStore: Readable<HistoryEntry[]> = derived(
[historyModeStore, autoHistoryStore, manualHistoryStore, loaderHistoryStore],
([historyMode, autoHistories, manualHistories, loadedHistories], set) => {
if (historyMode === 'auto') {
set(autoHistories);
} else if (historyMode === 'manual') {
set(manualHistories);
} else if (historyMode === 'loader') {
set(loadedHistories);
} else {
set(autoHistories);
}
}
);
export const addHistoryEntry = (entryToAdd: Optional<HistoryEntry, 'id'>): void => {
const entry: HistoryEntry = {
...entryToAdd,
id: uuidV4()
};
if (entry.type === 'loader') {
loaderHistoryStore.update((entries) => [entry, ...entries]);
return;
}
if (!entry.name) {
entry.name = generateSlug(2);
}
if (entry.type === 'auto') {
autoHistoryStore.update((entries) => {
if (entries.length >= MAX_AUTO_HISTORY_LENGTH) {
entries = entries.slice(0, MAX_AUTO_HISTORY_LENGTH - 1);
}
return [entry, ...entries];
});
} else if (entry.type === 'manual') {
manualHistoryStore.update((entries) => [entry, ...entries]);
logEvent('history', { action: 'save' });
}
};
export const clearHistoryData = (idToClear?: string): void => {
(get(historyModeStore) === 'auto' ? autoHistoryStore : manualHistoryStore).update((entries) => {
if (get(historyModeStore) !== 'loader') {
entries = entries.filter(({ id }) => idToClear && id != idToClear);
logEvent('history', { action: 'clear', type: idToClear ? 'single' : 'all' });
}
return entries;
});
};
export const getPreviousState = (auto: boolean): string => {
const entries = get(auto ? autoHistoryStore : manualHistoryStore);
if (entries.length > 0) {
return JSON.stringify(entries[0].state);
}
return '';
};
export const restoreHistory = (data: HistoryEntry[]) => {
const entries = data.filter(validateEntry);
const invalidEntryCount = data.length - entries.length;
if (invalidEntryCount > 0) {
console.error(`${invalidEntryCount} invalid history entries were removed.`);
console.error(data);
}
if (entries.length > 0) {
let entryCount = 0;
(entries[0].type === 'auto' ? autoHistoryStore : manualHistoryStore).update((existing) => {
const existingIDs = new Set(existing.map(({ id }) => id));
const newEntries = entries.filter(({ id }) => !existingIDs.has(id));
entryCount = newEntries.length;
const combined = [...existing, ...newEntries];
combined.sort((a, b) => b.time - a.time);
return combined;
});
alert(
`${entryCount} entries restored. ${invalidEntryCount} invalid, ${
entries.length - entryCount
} duplicates.`
);
logEvent('history', {
action: 'restore',
success: entryCount,
invalid: invalidEntryCount,
duplicates: entries.length - entryCount
});
} else {
alert('No valid entries found.');
}
};
export const injectHistoryIDs = (): void => {
const setIDs = (entries: HistoryEntry[]) => {
for (const entry of entries) {
if (!entry.id) {
entry.id = uuidV4();
}
}
return entries;
};
autoHistoryStore.update(setIDs);
manualHistoryStore.update(setIDs);
};
const validateEntry = (entry: HistoryEntry): boolean => {
return entry.type && entry.state && entry.time && true;
};
+82
View File
@@ -0,0 +1,82 @@
<script context="module">
import { version } from 'mermaid/package.json';
import { analytics } from '$lib/util/stats';
analytics?.track('version', {
mermaidVersion: version
});
</script>
<script lang="ts">
import Theme from './theme.svelte';
interface Link {
title: string;
href: string;
icon?: string;
}
const links: Link[] = [
{
title: 'Documentation',
href: 'https://mermaid-js.github.io/mermaid/#/n00b-gettingStarted'
},
{
title: 'Tutorial',
href: 'https://github.com/mermaid-js/mermaid/blob/develop/docs/Tutorials.md'
},
{
title: 'Mermaid',
href: 'https://github.com/mermaid-js/mermaid'
},
{
title: 'CLI',
href: 'https://github.com/mermaid-js/mermaid-cli'
},
{
title: '',
href: 'https://github.com/mermaid-js/mermaid-live-editor',
icon: 'fab fa-github fa-lg'
}
];
</script>
<div class="navbar shadow-lg bg-primary p-0">
<div class="flex-1 px-2 mx-2">
<span class="text-lg font-bold">
<a href="/">Mermaid<span class="text-xs font-thin">v{version}</span> Live Editor</a>
</span>
</div>
<label for="menu-toggle" class="pointer-cursor lg:hidden block"
><svg
class="fill-current "
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 20 20"
><title>Menu</title><path d="M0 3h20v2H0V3zm0 6h20v2H0V9zm0 6h20v2H0v-2z" /></svg
></label>
<input class="hidden" type="checkbox" id="menu-toggle" />
<Theme />
<div class="hidden lg:flex lg:items-center lg:w-auto w-full" id="menu">
<ul class="lg:flex items-center justify-between text-base pt-4 lg:pt-0">
{#each links as { title, href, icon }}
<li>
<a class="btn btn-ghost" target="_blank" rel="noreferrer" {href}>
{#if icon}
<i class={icon} />
{/if}
{title}</a>
</li>
{/each}
</ul>
</div>
</div>
<style>
#menu-toggle:checked + #menu {
display: block;
}
.navbar {
z-index: 10000;
}
</style>
@@ -1,21 +1,21 @@
<script lang="ts"> <script lang="ts">
import { updateCode } from '$lib/util/state'; import { updateCode } from '$lib/util/state';
import Card from '$lib/components/Card/Card.svelte'; import Card from '$lib/components/card/card.svelte';
import { logEvent } from '$lib/util/stats'; import { logEvent } from '$lib/util/stats';
const samples = { const samples = {
Flow: `flowchart TD Flow: `graph TD
A[Christmas] -->|Get money| B(Go shopping) A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think} B --> C{Let me think}
C -->|One| D[Laptop] C -->|One| D[Laptop]
C -->|Two| E[iPhone] C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car]`, C -->|Three| F[fa:fa-car Car]`,
Sequence: `sequenceDiagram Sequence: `sequenceDiagram
Alice->>+John: Hello John, how are you? Alice->>+John: Hello John, how are you?
Alice->>+John: John, can you hear me? Alice->>+John: John, can you hear me?
John-->>-Alice: Hi Alice, I can hear you! John-->>-Alice: Hi Alice, I can hear you!
John-->>-Alice: I feel great!`, John-->>-Alice: I feel great!`,
Class: `classDiagram Class: `classDiagram
Animal <|-- Duck Animal <|-- Duck
Animal <|-- Fish Animal <|-- Fish
Animal <|-- Zebra Animal <|-- Zebra
@@ -36,14 +36,14 @@
+bool is_wild +bool is_wild
+run() +run()
}`, }`,
State: `stateDiagram-v2 State: `stateDiagram-v2
[*] --> Still [*] --> Still
Still --> [*] Still --> [*]
Still --> Moving Still --> Moving
Moving --> Still Moving --> Still
Moving --> Crash Moving --> Crash
Crash --> [*]`, Crash --> [*]`,
Gantt: `gantt Gantt: `gantt
title A Gantt Diagram title A Gantt Diagram
dateFormat YYYY-MM-DD dateFormat YYYY-MM-DD
section Section section Section
@@ -52,11 +52,11 @@
section Another section Another
Task in sec :2014-01-12 , 12d Task in sec :2014-01-12 , 12d
another task : 24d`, another task : 24d`,
Pie: `pie title Pets adopted by volunteers Pie: `pie title Pets adopted by volunteers
"Dogs" : 386 "Dogs" : 386
"Cats" : 85 "Cats" : 85
"Rats" : 15`, "Rats" : 15`,
ER: `erDiagram ER: `erDiagram
CUSTOMER }|..|{ DELIVERY-ADDRESS : has CUSTOMER }|..|{ DELIVERY-ADDRESS : has
CUSTOMER ||--o{ ORDER : places CUSTOMER ||--o{ ORDER : places
CUSTOMER ||--o{ INVOICE : "liable for" CUSTOMER ||--o{ INVOICE : "liable for"
@@ -65,7 +65,7 @@
ORDER ||--|{ ORDER-ITEM : includes ORDER ||--|{ ORDER-ITEM : includes
PRODUCT-CATEGORY ||--|{ PRODUCT : contains PRODUCT-CATEGORY ||--|{ PRODUCT : contains
PRODUCT ||--o{ ORDER-ITEM : "ordered in"`, PRODUCT ||--o{ ORDER-ITEM : "ordered in"`,
'User Journey': `journey 'User Journey': `journey
title My working day title My working day
section Go to work section Go to work
Make tea: 5: Me Make tea: 5: Me
@@ -74,7 +74,7 @@
section Go home section Go home
Go downstairs: 5: Me Go downstairs: 5: Me
Sit down: 3: Me`, Sit down: 3: Me`,
Git: `gitGraph Git: `gitGraph
commit commit
commit commit
branch develop branch develop
@@ -85,7 +85,7 @@
merge develop merge develop
commit commit
commit`, commit`,
Mindmap: `mindmap Mindmap: `mindmap
root((mindmap)) root((mindmap))
Origins Origins
Long history Long history
@@ -102,44 +102,43 @@
Tools Tools
Pen and paper Pen and paper
Mermaid` Mermaid`
}; };
type SampleTypes = keyof typeof samples; const loadSampleDiagram = (diagramType: string): void => {
const loadSampleDiagram = (diagramType: SampleTypes): void => { updateCode(samples[diagramType], {
updateCode(samples[diagramType], { updateDiagram: true,
updateDiagram: true, resetPanZoom: true
resetPanZoom: true });
}); logEvent('loadSampleDiagram', { diagramType });
logEvent('loadSampleDiagram', { diagramType }); };
};
// Adding in this array will add an icon to the preset menu // Adding in this array will add an icon to the preset menu
const newDiagrams: SampleTypes[] = ['Mindmap']; const newDiagrams: Array<keyof typeof samples> = ['Mindmap'];
const diagramOrder: SampleTypes[] = [ const diagramOrder: Array<keyof typeof samples> = [
'Sequence', 'Sequence',
'Flow', 'Flow',
'Class', 'Class',
'State', 'State',
'ER', 'ER',
'Gantt', 'Gantt',
'User Journey', 'User Journey',
'Git', 'Git',
'Pie', 'Pie',
'Mindmap' 'Mindmap'
]; ];
</script> </script>
<Card title="Sample Diagrams" isOpen={false}> <Card title="Sample Diagrams" isOpen={false}>
<div class="flex flex-wrap p-2 gap-2"> <div class="flex flex-wrap p-2 gap-2">
{#each diagramOrder as sample} {#each diagramOrder as sample}
<button <button
class="btn btn-sm btn-primary w-28 normal-case flex-grow" class="btn btn-sm btn-primary w-28 normal-case flex-grow"
on:click={() => loadSampleDiagram(sample)}> on:click={() => loadSampleDiagram(sample)}>
{sample} {sample}
{#if newDiagrams.includes(sample)} {#if newDiagrams.includes(sample)}
<span class="ml-2 fa fa-heart" /> <span class="ml-2 fa fa-heart" />
{/if} {/if}
</button> </button>
{/each} {/each}
</div> </div>
</Card> </Card>
+64
View File
@@ -0,0 +1,64 @@
<script>
import { setTheme, themeStore } from '$lib/util/theme';
const themes = [
'🌝 light',
'🌚 dark',
'🧁 cupcake',
'🐝 bumblebee',
'✳️ emerald',
'🏢 corporate',
'🌃 synthwave',
'👴 retro',
'🤖 cyberpunk',
'🌸 valentine',
'🎃 halloween',
'🌷 garden',
'🌲 forest',
'🐟 aqua',
'👓 lofi',
'🖍 pastel',
'🧚‍♀️ fantasy',
'📝 wireframe',
'🏴 black',
'💎 luxury',
'🧛‍♂️ dracula'
];
</script>
<div class="hidden lg:block dropdown">
<!-- svelte-ignore a11y-no-noninteractive-tabindex -->
<div tabindex="0" class="btn btn-ghost ">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
class="inline-block w-6 h-6 stroke-current md:mr-2"
><path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01" /></svg>
<span class="hidden md:inline"> Change Theme </span>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 1792 1792"
class="inline-block w-4 h-4 ml-1 fill-current"
><path
d="M1395 736q0 13-10 23l-466 466q-10 10-23 10t-23-10l-466-466q-10-10-10-23t10-23l50-50q10-10 23-10t23 10l393 393 393-393q10-10 23-10t23 10l50 50q10 10 10 23z" /></svg>
</div>
<div
class="mt-14 overflow-y-auto shadow-2xl top-px dropdown-content h-96 w-56 bg-base-200 text-base-content">
<!-- svelte-ignore a11y-no-noninteractive-tabindex -->
<ul tabindex="0" class="p-4 menu compact">
{#each themes as theme}
<li class={theme.includes($themeStore.theme) ? 'bordered' : ''}>
<span
class="btn btn-ghost justify-start"
on:click={() => setTheme(theme)}
on:keypress={() => setTheme(theme)}>{theme}</span>
</li>
{/each}
</ul>
</div>
</div>
+152
View File
@@ -0,0 +1,152 @@
<script lang="ts">
import { inputStateStore, stateStore, updateCodeStore } from '$lib/util/state';
import { onMount } from 'svelte';
import panzoom from 'svg-pan-zoom';
import type { State, ValidatedState } from '$lib/types';
import { logEvent } from '$lib/util/stats';
import { cmdKey } from '$lib/util/util';
import { render as renderDiagram, init as mermaidInit } from '$lib/util/mermaid';
const init = mermaidInit();
let code = '';
let config = '';
let container: HTMLDivElement;
let view: HTMLDivElement;
let error = false;
let outOfSync = false;
let hide = false;
let manualUpdate = true;
let panZoomEnabled = $stateStore.panZoom;
let pzoom: SvgPanZoom.Instance;
const handlePanZoomChange = () => {
const pan = pzoom.getPan();
const zoom = pzoom.getZoom();
updateCodeStore({ pan, zoom });
logEvent('panZoom');
};
const handlePanZoom = (state: State) => {
if (!state.panZoom) {
return;
}
hide = true;
pzoom?.destroy();
pzoom = undefined;
Promise.resolve().then(() => {
const graphDiv = document.getElementById('graph-div');
pzoom = panzoom(graphDiv, {
onPan: handlePanZoomChange,
onZoom: handlePanZoomChange,
controlIconsEnabled: true,
fit: true,
center: true
});
const { pan, zoom } = state;
if (pan !== undefined && zoom !== undefined && Number.isFinite(zoom)) {
pzoom.zoom(zoom);
pzoom.pan(pan);
}
hide = false;
});
};
const handleStateChange = (state: ValidatedState) => {
if (state.error !== undefined) {
error = true;
return;
}
error = false;
try {
if (container && state && (state.updateDiagram || state.autoSync)) {
if (!state.autoSync) {
$inputStateStore.updateDiagram = false;
}
outOfSync = false;
manualUpdate = true;
if (code === state.code && config === state.mermaid && panZoomEnabled === state.panZoom) {
// Do not render if there is no change in Code/Config/PanZoom
return;
}
code = state.code;
config = state.mermaid;
panZoomEnabled = state.panZoom;
const scroll = view.parentElement.scrollTop;
delete container.dataset.processed;
renderDiagram({
config: Object.assign({}, JSON.parse(state.mermaid)),
code,
id: 'graph-div',
callback: (svgCode, bindFunctions) => {
if (svgCode.length > 0) {
handlePanZoom(state);
container.innerHTML = svgCode;
const graphDiv = document.getElementById('graph-div');
graphDiv.setAttribute('height', '100%');
graphDiv.style.maxWidth = '100%';
if (bindFunctions) {
bindFunctions(graphDiv);
}
}
}
});
view.parentElement.scrollTop = scroll;
error = false;
} else if (manualUpdate) {
manualUpdate = false;
} else if (code !== state.code || config !== state.mermaid) {
outOfSync = true;
}
} catch (e) {
console.error('view fail', e);
error = true;
}
};
onMount(() => {
stateStore.subscribe((state) => {
handleStateChange(state);
});
window.addEventListener('resize', () => {
if ($stateStore.panZoom && pzoom) {
pzoom.resize();
}
});
});
</script>
{#await init}
Loading...
{:then}
{#if error && $stateStore.error instanceof Error}
<div class="p-2 text-red-600" id="errorContainer">{$stateStore.error}</div>
{/if}
{#if outOfSync}
<div class="absolute w-full p-2 z-10 text-yellow-600 bg-base-100 bg-opacity-80 text-center">
Diagram out of sync. <br />
Press <i class="fas fa-sync" /> (Sync button) or <kbd>{cmdKey} + Enter</kbd> to sync.
</div>
{/if}
<div id="view" bind:this={view} class="p-2 h-full" class:error class:outOfSync>
<div id="container" bind:this={container} class="h-full overflow-auto" class:hide />
</div>
{/await}
<style>
#view {
flex: 1;
}
#container {
transition: visibility 0.3s;
}
.error,
.outOfSync {
opacity: 0.5;
}
.hide {
visibility: hidden;
}
</style>
+53 -55
View File
@@ -1,88 +1,86 @@
/**
* Can be made globally available by placing this
* inside `global.d.ts` and removing `export` keyword
*/
export interface Locals {
userid: string;
}
export interface MarkerData { export interface MarkerData {
severity: number; severity: number;
message: string; message: string;
source?: string; source?: string;
startLineNumber: number; startLineNumber: number;
startColumn: number; startColumn: number;
endLineNumber: number; endLineNumber: number;
endColumn: number; endColumn: number;
} }
export interface TabEvents { export interface TabEvents {
select: Tab; select: Tab;
} }
export interface Tab { export interface Tab {
id: string; id: string;
title: string; title: string;
icon: string; icon: string;
} }
export interface State { export interface State {
code: string; code: string;
mermaid: string; mermaid: string;
updateDiagram: boolean; updateDiagram: boolean;
autoSync: boolean; autoSync: boolean;
editorMode?: EditorMode; editorMode?: EditorMode;
panZoom?: boolean; panZoom?: boolean;
pan?: { x: number; y: number }; pan?: { x: number; y: number };
zoom?: number; zoom?: number;
loader?: LoaderConfig; loader?: LoaderConfig;
} }
export interface ValidatedState extends State { export interface ValidatedState extends State {
editorMode: EditorMode; editorMode: EditorMode;
error?: Error; error: unknown;
errorMarkers: MarkerData[]; errorMarkers: MarkerData[];
serialized: string; serialized: string;
} }
export interface GistLoaderConfig { export interface GistLoaderConfig {
url: string; url: string;
} }
export interface LoadingState { export interface LoadingState {
loading: boolean; loading: boolean;
message?: string; message?: string;
} }
export interface FileLoaderConfig { export interface FileLoaderConfig {
codeURL: string; codeURL: string;
configURL?: string; configURL?: string;
} }
export interface LoaderConfig { export interface LoaderConfig {
type: 'gist' | 'files'; type: 'gist' | 'files';
config: GistLoaderConfig | FileLoaderConfig; config: GistLoaderConfig | FileLoaderConfig;
} }
export type HistoryType = 'auto' | 'manual' | 'loader'; export type HistoryType = 'auto' | 'manual' | 'loader';
export type HistoryEntry = { id: string; state: State; time: number; url?: string } & ( export type HistoryEntry = { id: string; state: State; time: number; url?: string } & (
| { | {
type: 'loader'; type: 'loader';
name: string; name: string;
} }
| { | {
type: HistoryType; type: HistoryType;
name?: string; name?: string;
} }
); );
export type DocumentationConfig = Record< export interface DocConfig {
string, [key: string]: {
{ code: string;
code: string; config?: string;
config?: string; };
} }
>;
export type EditorMode = 'code' | 'config'; export type EditorMode = 'code' | 'config';
export type Loader = (url: string) => Promise<State>; export type Loader = (url: string) => Promise<State>;
export type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>; export type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
export interface ErrorHash {
loc: {
first_line: number;
last_line: number;
first_column: number;
last_column: number;
};
}
+7 -7
View File
@@ -1,9 +1,9 @@
export const env = { export const env = {
rendererUrl: import.meta.env.MERMAID_RENDERER_URL ?? 'https://mermaid.ink', rendererUrl: import.meta.env.MERMAID_RENDERER_URL ?? 'https://mermaid.ink',
krokiRendererUrl: import.meta.env.MERMAID_KROKI_RENDERER_URL ?? 'https://kroki.io', krokiRendererUrl: import.meta.env.MERMAID_KROKI_RENDERER_URL ?? 'https://kroki.io',
mermaidCDNUrl: import.meta.env.MERMAID_CDN_URL ?? 'https://unpkg.com/@mermaid-js', mermaidCDNUrl: import.meta.env.MERMAID_CDN_URL ?? 'https://unpkg.com/@mermaid-js',
mermaidBaseURL: import.meta.env.MERMAID_BASE_URL ?? 'http://localhost:9000', mermaidBaseURL: import.meta.env.MERMAID_BASE_URL ?? 'http://localhost:9000',
useLocalMermaid: import.meta.env.MERMAID_LOCAL ?? false, useLocalMermaid: import.meta.env.MERMAID_LOCAL ?? false,
isDev: import.meta.env.DEV, isDev: import.meta.env.DEV,
baseURL: import.meta.env.BASE_URL baseURL: import.meta.env.BASE_URL
}; };
+82 -102
View File
@@ -3,125 +3,105 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access */ /* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
import type { State } from '$lib/types'; import type { State } from '$lib/types';
import { defaultState } from '$lib/util/state'; import { defaultState } from '../state';
import { addHistoryEntry } from '$lib/components/History/history'; import { addHistoryEntry } from '../../components/history/history';
import { fetchJSON, fetchText } from '$lib/util/util';
const codeFileName = 'code.mmd'; const codeFileName = 'code.mmd';
const configFileName = 'config.json'; const configFileName = 'config.json';
interface GithubFile {
truncated: boolean;
raw_url: string;
content: string;
}
const isValidGist = (files: any): boolean => { const isValidGist = (files: any): boolean => {
return codeFileName in files; return codeFileName in files;
}; };
const getFileContent = async (file: GithubFile): Promise<string> => { const getFileContent = async (file: any): Promise<string> => {
if (file.truncated) { if (file.truncated) {
return await fetchText(file.raw_url); return await (await fetch(file.raw_url)).text();
} }
return file.content; return file.content;
}; };
interface GistData { interface GistData {
code: string; code: string;
config?: string; config?: string;
author: string; author: string;
time: number; time: number;
version: string; version: string;
url: string; url: string;
}
interface GistResponse {
files: Record<string, GithubFile>;
html_url: string;
history: { url: string; committed_at: string; version: string; user: { login: string } }[];
} }
const getGistData = async (gistURL: string): Promise<GistData> => { const getGistData = async (gistURL: string): Promise<GistData> => {
const path = gistURL.split('github.com').pop(); // eslint-disable-next-line @typescript-eslint/no-unused-vars
if (!path) { const [_, __, gistID, revisionID] = gistURL.split('github.com').pop().split('/');
throw new Error('Invalid GitHub URL' + gistURL); // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
} const { html_url, files, history } = await (
// eslint-disable-next-line @typescript-eslint/no-unused-vars await fetch(`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`)
const [_, __, gistID, revisionID] = path.split('/'); ).json();
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment if (isValidGist(files)) {
const { html_url, files, history }: GistResponse = await fetchJSON( const code = await getFileContent(files[codeFileName]);
`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}` let config: string;
); if (configFileName in files) {
if (isValidGist(files)) { config = await getFileContent(files[configFileName]);
const code = await getFileContent(files[codeFileName]); }
let config = '{}'; const currentItem = history[0];
if (configFileName in files) { return {
config = await getFileContent(files[configFileName]); // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
} url: `${html_url}/${currentItem.version}`,
const currentItem = history[0]; code,
return { config,
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions author: currentItem.user.login,
url: `${html_url}/${currentItem.version}`, time: new Date(currentItem.committed_at).getTime(),
code, version: (currentItem.version as string).slice(-7)
config, };
author: currentItem.user.login, } else {
time: new Date(currentItem.committed_at).getTime(), throw 'Invalid gist provided';
version: currentItem.version.slice(-7) }
};
} else {
throw new Error('Invalid gist provided');
}
}; };
const getStateFromGist = (gist: GistData, gistURL: string = gist.url): State => { const getStateFromGist = (gist: GistData, gistURL: string = gist.url): State => {
const state: State = { const state: State = {
...defaultState, ...defaultState,
code: gist.code, code: gist.code,
loader: { loader: {
type: 'gist', type: 'gist',
config: { config: {
url: gistURL url: gistURL
} }
} }
}; };
gist.config && (state.mermaid = gist.config); gist.config && (state.mermaid = gist.config);
return state; return state;
}; };
export const loadGistData = async (gistURL: string): Promise<State> => { export const loadGistData = async (gistURL: string): Promise<State> => {
const path = gistURL.split('github.com').pop(); try {
if (!path) { // eslint-disable-next-line @typescript-eslint/no-unused-vars
throw new Error('Invalid GitHub URL' + gistURL); const [_, __, gistID, revisionID] = gistURL.split('github.com').pop().split('/');
} // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
// eslint-disable-next-line @typescript-eslint/no-unused-vars const { history } = await (
const [_, __, gistID, revisionID] = path.split('/'); await fetch(`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`)
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment ).json();
const { history }: GistResponse = await fetchJSON( const gistHistory: GistData[] = [];
`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}` for (const entry of history) {
); // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const gistHistory: GistData[] = []; const data: GistData = await getGistData(entry.url).catch(() => undefined);
for (const entry of history) { data && gistHistory.push(data);
const data: GistData | undefined = await getGistData(entry.url).catch(); }
data && gistHistory.push(data); if (gistHistory.length === 0) {
} throw 'Invalid gist provided';
if (gistHistory.length === 0) { }
throw new Error('Invalid gist provided'); gistHistory.reverse();
} const state = getStateFromGist(gistHistory.slice(-1).pop(), gistURL);
gistHistory.reverse(); for (const gist of gistHistory) {
const entry = gistHistory.slice(-1).pop(); addHistoryEntry({
if (!entry) { state: getStateFromGist(gist),
throw new Error('Invalid gist provided'); time: gist.time,
} type: 'loader',
const state = getStateFromGist(entry, gistURL); url: gist.url,
for (const gist of gistHistory) { name: `${gist.author} v${gist.version}`
addHistoryEntry({ });
state: getStateFromGist(gist), }
time: gist.time, return state;
type: 'loader', } catch (err) {
url: gist.url, console.error(err);
name: `${gist.author} v${gist.version}` }
});
}
return state;
}; };
+51 -50
View File
@@ -1,58 +1,59 @@
import { loadGistData } from './gist'; import { loadGistData } from './gist';
import { updateCodeStore, defaultState } from '$lib/util/state'; import { updateCodeStore, defaultState } from '../state';
import { fetchText } from '$lib/util/util';
import type { Loader, State } from '$lib/types'; import type { Loader, State } from '$lib/types';
const loaders: Record<string, Loader> = { const loaders: Record<string, Loader> = {
gist: loadGistData gist: loadGistData
}; };
export const loadDataFromUrl = async (): Promise<void> => { export const loadDataFromUrl = async (): Promise<void> => {
const searchParams = new URLSearchParams(window.location.search); const searchParams = new URLSearchParams(window.location.search);
let state: Partial<State> = defaultState; let state: Partial<State> = defaultState;
let loaded = false; let code: string, config: string;
const codeURL: string | undefined = searchParams.get('code') ?? undefined; let loaded = false;
const configURL: string | undefined = searchParams.get('config') ?? undefined; const codeURL: string = searchParams.get('code');
const configURL: string = searchParams.get('config');
let code: string | undefined; if (codeURL) {
const config = configURL ? await fetchText(configURL) : defaultState.mermaid; code = await (await fetch(codeURL)).text();
loaded = true;
if (codeURL) { }
code = await fetchText(codeURL); if (configURL) {
loaded = true; config = await (await fetch(configURL)).text();
} } else {
if (code) { config = defaultState.mermaid;
if (!codeURL) { }
throw new Error('Code URL is not defined'); if (!code) {
} // eslint-disable-next-line @typescript-eslint/ban-ts-comment
state = { // @ts-ignore
code, // eslint-disable-next-line @typescript-eslint/no-unsafe-call
mermaid: config, for (const [key, value] of searchParams.entries()) {
loader: { if (key in loaders) {
type: 'files', try {
config: { state = await loaders[key](value);
codeURL, loaded = true;
configURL break;
} } catch (err) {
} console.error(err);
}; }
} else { }
for (const [key, value] of searchParams.entries()) { }
if (key in loaders) { } else {
try { state = {
state = await loaders[key](value); code,
loaded = true; mermaid: config,
break; loader: {
} catch (error) { type: 'files',
console.error(error); config: {
} codeURL,
} configURL
} }
} }
loaded && };
updateCodeStore({ }
...state, loaded &&
autoSync: true, updateCodeStore({
updateDiagram: true ...state,
}); autoSync: true,
updateDiagram: true
});
}; };
+10 -10
View File
@@ -3,18 +3,18 @@ import type { Writable } from 'svelte/store';
import type { LoadingState } from '$lib/types'; import type { LoadingState } from '$lib/types';
const defaultLoading: LoadingState = { const defaultLoading: LoadingState = {
loading: false loading: false
}; };
export const loadingStateStore: Writable<LoadingState> = writable(defaultLoading); export const loadingStateStore: Writable<LoadingState> = writable(defaultLoading);
export const initLoading = async <T>(message: string, task: Promise<T>): Promise<T> => { export const initLoading = async <T>(message: string, task: Promise<T>): Promise<T> => {
loadingStateStore.set({ loadingStateStore.set({
loading: true, loading: true,
message message
}); });
const result: T = await task; const result: T = await task;
loadingStateStore.set({ loadingStateStore.set({
loading: false loading: false
}); });
return result; return result;
}; };
+69 -11
View File
@@ -1,16 +1,74 @@
import mermaid from 'mermaid'; import mermaid from 'mermaid';
import type { MermaidConfig, RenderResult } from 'mermaid'; // We need to export MermaidConfig and all related types from mermaid.
import type { MermaidConfig } from 'mermaid/dist/config.type';
import { env } from './env';
import queue from 'async/queue';
import type { QueueObject } from 'async';
const { mermaidBaseURL, mermaidCDNUrl, useLocalMermaid } = env;
export const render = async ( const getDiagramURL = (name: string, version: string): string => {
config: MermaidConfig, if (useLocalMermaid) {
code: string, return `${mermaidBaseURL}/${name}-detector.esm.mjs`;
id: string }
): Promise<RenderResult> => { return `${mermaidCDNUrl}/${name}@${version}/dist/${name}-detector.esm.mjs`;
// Should be able to call this multiple times without any issues.
mermaid.initialize(config);
return await mermaid.render(id, code);
}; };
export const parse = async (code: string): Promise<unknown> => { const initialize = mermaid.initializeAsync({
return await mermaid.parse(code); logLevel: 0,
lazyLoadedDiagrams: [getDiagramURL('mermaid-mindmap', '9.2.0-rc4')],
loadExternalDiagramsAtStartup: true
});
export const init = async () => {
await initialize;
};
interface RenderPayload {
config: MermaidConfig;
code: string;
id: string;
callback: Parameters<typeof mermaid.render>[2];
}
interface ParsePayload {
code: string;
}
interface MermaidTask {
action: 'render' | 'parse';
payload: RenderPayload | ParsePayload;
}
const mermaidQueue: QueueObject<MermaidTask> = queue(async (task: MermaidTask) => {
console.log('adding ', task);
if (task.action === 'render') {
const { config, code, id, callback } = task.payload as RenderPayload;
await mermaid.mermaidAPI.renderAsync(id, code, callback);
}
console.log('done', task);
}, 1);
mermaidQueue.error(function (err, task) {
console.error('task experienced an error', task, err);
});
export const render = async (payload: RenderPayload): Promise<void> => {
// Should be able to call this multiple times without any issues.
// await mermaid.initialize({
// ...config,
// lazyLoadedDiagrams: [
// // We should make SRI mandatory for all lazy-loaded diagrams.
// 'https://unpkg.com/@mermaid-js/mermaid-mindmap@9.2.0-rc2/dist/mermaid-mindmap-detector.esm.mjs'
// ]
// });
// console.log('Rendering', code);
// mermaid.mermaidAPI.render(id, code, callback);
await mermaidQueue.push({
action: 'render',
payload
});
};
export const parse = async (code: string): Promise<boolean> => {
await init();
return mermaid.parseAsync(code);
}; };
+26 -30
View File
@@ -2,37 +2,33 @@ import type { HistoryEntry } from '$lib/types';
import { describe, it, expect, beforeEach } from 'vitest'; import { describe, it, expect, beforeEach } from 'vitest';
describe('migrations', () => { describe('migrations', () => {
beforeEach(() => { beforeEach(() => {
window.localStorage.setItem( window.localStorage.setItem(
'manualHistoryStore', 'manualHistoryStore',
'[{"state":{"code":"graph TD\\n A[Halloween] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":false},"time":0,"type":"manual","name":"hollow-art"},{"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":"helpful-ocean"}]' '[{"state":{"code":"graph TD\\n A[Halloween] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":false},"time":0,"type":"manual","name":"hollow-art"},{"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":"helpful-ocean"}]'
); );
window.localStorage.setItem( window.localStorage.setItem(
'autoHistoryStore', 'autoHistoryStore',
'[{"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"}]' '[{"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"}]'
); );
}); });
it('should migrate from v0 to v1', async () => { it('should migrate from v0 to v1', async () => {
const { applyMigrations } = await import('./migrations'); const { applyMigrations } = await import('./migrations');
let manualHistoryStore: HistoryEntry[] = JSON.parse( let manualHistoryStore: HistoryEntry[] = JSON.parse(
window.localStorage.getItem('manualHistoryStore') ?? '[]' window.localStorage.getItem('manualHistoryStore')
) as HistoryEntry[]; );
let autoHistoryStore: HistoryEntry[] = JSON.parse( let autoHistoryStore: HistoryEntry[] = JSON.parse(
window.localStorage.getItem('autoHistoryStore') ?? '[]' window.localStorage.getItem('autoHistoryStore')
) as HistoryEntry[]; );
expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(false); expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(false);
expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(false); expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(false);
applyMigrations(); applyMigrations();
manualHistoryStore = JSON.parse( manualHistoryStore = JSON.parse(window.localStorage.getItem('manualHistoryStore'));
window.localStorage.getItem('manualHistoryStore') ?? '[]' autoHistoryStore = JSON.parse(window.localStorage.getItem('autoHistoryStore'));
) as HistoryEntry[]; expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(true);
autoHistoryStore = JSON.parse( expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(true);
window.localStorage.getItem('autoHistoryStore') ?? '[]' });
) as HistoryEntry[];
expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(true);
expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(true);
});
}); });
+21 -21
View File
@@ -1,35 +1,35 @@
import { writable, get, type Writable } from 'svelte/store'; import { writable, get, type Writable } from 'svelte/store';
import { persist, localStorage } from '$lib/util/persist'; import { persist, localStorage } from '$lib/util/persist';
import { injectHistoryIDs } from '$lib/components/History/history'; import { injectHistoryIDs } from '$lib/components/history/history';
import { logEvent } from './stats'; import { logEvent } from './stats';
interface MigrationState { interface MigrationState {
version: number; version: number;
} }
const migrations: Record<string, () => void> = { const migrations: { [key: string]: () => void } = {
injectHistoryIDs injectHistoryIDs
}; };
const migrationStore: Writable<MigrationState> = persist( const migrationStore: Writable<MigrationState> = persist(
writable({ version: -1 }), writable({ version: -1 }),
localStorage(), localStorage(),
'migrations' 'migrations'
); );
export const applyMigrations = (): void => { export const applyMigrations = (): void => {
const { version }: MigrationState = get(migrationStore); const { version }: MigrationState = get(migrationStore);
const allMigrations = Object.entries(migrations); const allMigrations = Object.entries(migrations);
if (version === allMigrations.length - 1) { if (version === allMigrations.length - 1) {
return; return;
} }
console.log(`Current migration version: v${version}. Migrating to v${allMigrations.length - 1}.`); console.log(`Current migration version: v${version}. Migrating to v${allMigrations.length - 1}.`);
for (let i = version + 1; i < allMigrations.length; i++) { for (let i = version + 1; i < allMigrations.length; i++) {
const [key, fn] = allMigrations[i]; const [key, fn] = allMigrations[i];
console.log(`Applying migration ${i}: ${key}.`); console.log(`Applying migration ${i}: ${key}.`);
fn(); fn();
logEvent('migration', { key }); logEvent('migration', { key });
migrationStore.set({ version: i }); migrationStore.set({ version: i });
} }
logEvent('migration', { status: 'complete', from: version, to: allMigrations.length - 1 }); logEvent('migration', { status: 'complete', from: version, to: allMigrations.length - 1 });
}; };
+2 -2
View File
@@ -1,7 +1,7 @@
export const notify = (message: string): void => { export const notify = (message: string): void => {
alert(message); alert(message);
}; };
export const prompt = (message: string): boolean => { export const prompt = (message: string): boolean => {
return confirm(message); return confirm(message);
}; };
+167 -159
View File
@@ -29,7 +29,7 @@ import type { Writable } from 'svelte/store';
* Disabled warnings about missing/unavailable storages * Disabled warnings about missing/unavailable storages
*/ */
export function disableWarnings(): void { export function disableWarnings(): void {
noWarnings = true; noWarnings = true;
} }
/** /**
* If set to true, no warning will be emitted if the requested Storage is not found. * If set to true, no warning will be emitted if the requested Storage is not found.
@@ -39,101 +39,110 @@ let noWarnings = false;
/** /**
* List of storages where the warning have already been displayed. * List of storages where the warning have already been displayed.
*/ */
const alreadyWarnFor: string[] = []; const alreadyWarnFor: Array<string> = [];
/** /**
* Add a log to indicate that the requested Storage have not been found. * Add a log to indicate that the requested Storage have not been found.
* @param {string} storageName * @param {string} storageName
*/ */
const warnStorageNotFound = (storageName: string) => { const warnStorageNotFound = (storageName) => {
const isProduction = typeof process !== 'undefined' && process.env.NODE_ENV === 'production'; const isProduction = typeof process !== 'undefined' && process.env?.NODE_ENV === 'production';
if (!noWarnings && !alreadyWarnFor.includes(storageName) && !isProduction) { if (!noWarnings && alreadyWarnFor.indexOf(storageName) === -1 && !isProduction) {
let message = `Unable to find the ${storageName}. No data will be persisted.`; let message = `Unable to find the ${storageName}. No data will be persisted.`;
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
message += message +=
'\n' + '\n' +
'Are you running on a server? Most of storages are not available while running on a server.'; 'Are you running on a server? Most of storages are not available while running on a server.';
} }
console.warn(message); console.warn(message);
alreadyWarnFor.push(storageName); alreadyWarnFor.push(storageName);
} }
};
const allowedClasses = [];
/**
* Add a class to the allowed list of classes to be serialized
* @param classDef The class to add to the list
*/
export const addSerializableClass = (classDef: () => unknown): void => {
allowedClasses.push(classDef);
}; };
const serialize = (value: unknown): string => ESSerializer.serialize(value); const serialize = (value: unknown): string => ESSerializer.serialize(value);
const deserialize = (value?: string | null): unknown => { const deserialize = (value: string): unknown => {
// @TODO: to remove in the next major // @TODO: to remove in the next major
if (value === 'undefined') { if (value === 'undefined') {
return undefined; return undefined;
} }
if (value !== null && value !== undefined) { if (value !== null && value !== undefined) {
try { try {
return ESSerializer.deserialize(value); return ESSerializer.deserialize(value, allowedClasses);
} catch { } catch (e) {
// Do nothing // Do nothing
// use the value "as is" // use the value "as is"
} }
try { try {
return JSON.parse(value); return JSON.parse(value);
} catch { } catch (e) {
// Do nothing // Do nothing
// use the value "as is" // use the value "as is"
} }
} }
return value; return value;
}; };
/** /**
* A store that keep it's value in time. * A store that keep it's value in time.
*/ */
export interface PersistentStore<T> extends Writable<T> { export interface PersistentStore<T> extends Writable<T> {
/** /**
* Delete the store value from the persistent storage * Delete the store value from the persistent storage
*/ */
delete(): void; delete(): void;
} }
/** /**
* Storage interface * Storage interface
*/ */
export interface StorageInterface<T> { export interface StorageInterface<T> {
/** /**
* Get a value from the storage. * Get a value from the storage.
* *
* If the value doesn't exists in the storage, `null` should be returned. * If the value doesn't exists in the storage, `null` should be returned.
* This method MUST be synchronous. * This method MUST be synchronous.
* @param key The key/name of the value to retrieve * @param key The key/name of the value to retrieve
*/ */
getValue(key: string): T | null; getValue(key: string): T | null;
/** /**
* Save a value in the storage. * Save a value in the storage.
* @param key The key/name of the value to save * @param key The key/name of the value to save
* @param value The value to save * @param value The value to save
*/ */
setValue(key: string, value: T): void; setValue(key: string, value: T): void;
/** /**
* Remove a value from the storage * Remove a value from the storage
* @param key The key/name of the value to remove * @param key The key/name of the value to remove
*/ */
deleteValue(key: string): void; deleteValue(key: string): void;
} }
export interface SelfUpdateStorageInterface<T> extends StorageInterface<T> { export interface SelfUpdateStorageInterface<T> extends StorageInterface<T> {
/** /**
* Add a listener to the storage values changes * Add a listener to the storage values changes
* @param {string} key The key to listen * @param {string} key The key to listen
* @param {(newValue: T) => void} listener The listener callback function * @param {(newValue: T) => void} listener The listener callback function
*/ */
addListener(key: string, listener: (newValue: T) => void): void; addListener(key: string, listener: (newValue: T) => void): void;
/** /**
* Remove a listener from the storage values changes * Remove a listener from the storage values changes
* @param {string} key The key that was listened * @param {string} key The key that was listened
* @param {(newValue: T) => void} listener The listener callback function to remove * @param {(newValue: T) => void} listener The listener callback function to remove
*/ */
removeListener(key: string, listener: (newValue: T) => void): void; removeListener(key: string, listener: (newValue: T) => void): void;
} }
/** /**
@@ -143,115 +152,114 @@ export interface SelfUpdateStorageInterface<T> extends StorageInterface<T> {
* @param {string} key The name of the data key * @param {string} key The name of the data key
*/ */
export function persist<T>( export function persist<T>(
store: Writable<T>, store: Writable<T>,
storage: StorageInterface<T>, storage: StorageInterface<T>,
key: string key: string
): PersistentStore<T> { ): PersistentStore<T> {
const initialValue = storage.getValue(key); const initialValue = storage.getValue(key);
if (null !== initialValue) { if (null !== initialValue) {
store.set(initialValue); store.set(initialValue);
} }
if ('addListener' in storage) { if ((storage as SelfUpdateStorageInterface<T>).addListener) {
(storage as SelfUpdateStorageInterface<T>).addListener(key, (newValue) => { (storage as SelfUpdateStorageInterface<T>).addListener(key, (newValue) => {
store.set(newValue); store.set(newValue);
}); });
} }
store.subscribe((value) => { store.subscribe((value) => {
storage.setValue(key, value); storage.setValue(key, value);
}); });
return { return {
...store, ...store,
delete() { delete() {
storage.deleteValue(key); storage.deleteValue(key);
} }
}; };
} }
function getBrowserStorage( function getBrowserStorage(
browserStorage: Storage, browserStorage: Storage,
listenExternalChanges = false listenExternalChanges = false
): SelfUpdateStorageInterface<any> { ): SelfUpdateStorageInterface<any> {
const listeners: { key: string; listener: (newValue: any) => void }[] = []; const listeners: Array<{ key: string; listener: (newValue: any) => void }> = [];
const listenerFunction = (event: StorageEvent) => { const listenerFunction = (event: StorageEvent) => {
const eventKey = event.key; const eventKey = event.key;
if (event.storageArea === browserStorage) { if (event.storageArea === browserStorage) {
for (const { listener } of listeners.filter(({ key }) => key === eventKey)) { listeners
listener(deserialize(event.newValue)); .filter(({ key }) => key === eventKey)
} .forEach(({ listener }) => {
} listener(deserialize(event.newValue));
}; });
const connect = () => { }
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition };
if (listenExternalChanges && typeof window !== 'undefined' && window.addEventListener) { const connect = () => {
window.addEventListener('storage', listenerFunction); if (listenExternalChanges && typeof window !== 'undefined' && window?.addEventListener) {
} window.addEventListener('storage', listenerFunction);
}; }
const disconnect = () => { };
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition const disconnect = () => {
if (listenExternalChanges && typeof window !== 'undefined' && window.removeEventListener) { if (listenExternalChanges && typeof window !== 'undefined' && window?.removeEventListener) {
window.removeEventListener('storage', listenerFunction); window.removeEventListener('storage', listenerFunction);
} }
}; };
return { return {
addListener(key: string, listener: (newValue: any) => void) { addListener(key: string, listener: (newValue: any) => void) {
listeners.push({ key, listener }); listeners.push({ key, listener });
if (listeners.length === 1) { if (listeners.length === 1) {
connect(); connect();
} }
}, },
removeListener(key: string, listener: (newValue: any) => void) { removeListener(key: string, listener: (newValue: any) => void) {
const index = listeners.indexOf({ key, listener }); const index = listeners.indexOf({ key, listener });
if (index !== -1) { if (index !== -1) {
listeners.splice(index, 1); listeners.splice(index, 1);
} }
if (listeners.length === 0) { if (listeners.length === 0) {
disconnect(); disconnect();
} }
}, },
getValue(key: string): any | null { getValue(key: string): any | null {
const value = browserStorage.getItem(key); const value = browserStorage.getItem(key);
return deserialize(value); return deserialize(value);
}, },
deleteValue(key: string) { deleteValue(key: string) {
browserStorage.removeItem(key); browserStorage.removeItem(key);
}, },
setValue(key: string, value: any) { setValue(key: string, value: any) {
browserStorage.setItem(key, serialize(value)); browserStorage.setItem(key, serialize(value));
} }
}; };
} }
/** /**
* Storage implementation that use the browser local storage * Storage implementation that use the browser local storage
* @param listenExternalChanges - Update the store if the localStorage is updated from another page * @param {boolean} listenExternalChanges - Update the store if the localStorage is updated from another page
*/ */
export function localStorage<T>(listenExternalChanges = false): StorageInterface<T> { export function localStorage<T>(listenExternalChanges = false): StorageInterface<T> {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (typeof window !== 'undefined' && window?.localStorage) {
if (typeof window !== 'undefined' && window.localStorage) { return getBrowserStorage(window.localStorage, listenExternalChanges);
return getBrowserStorage(window.localStorage, listenExternalChanges); }
} warnStorageNotFound('window.localStorage');
warnStorageNotFound('window.localStorage'); return noopStorage();
return noopStorage();
} }
/** /**
* Storage implementation that do nothing * Storage implementation that do nothing
*/ */
export function noopStorage<T>(): StorageInterface<T> { export function noopStorage(): StorageInterface<any> {
return { return {
getValue(): null { getValue(): null {
return null; return null;
}, },
deleteValue() { deleteValue() {
// Do nothing // Do nothing
}, },
setValue() { setValue() {
// Do nothing // Do nothing
} }
}; };
} }
+30 -30
View File
@@ -3,38 +3,38 @@ import { serializeState, deserializeState, type SerdeType } from './serde';
import { defaultState } from './state'; import { defaultState } from './state';
import type { State } from '$lib/types'; import type { State } from '$lib/types';
const verifySerde = (state: State, serde?: SerdeType): string => {
const serialized = serializeState(state, serde);
const deserialized = deserializeState(serialized);
expect(deserialized).to.deep.equal(state);
return serialized;
};
describe('Serde tests', () => { describe('Serde tests', () => {
it('should serialize and deserialize with default serde', () => { const verifySerde = (state: State, serde?: SerdeType): string => {
expect(verifySerde(defaultState)).toMatchInlineSnapshot( const serialized = serializeState(state, serde);
'"pako:eNpVjk2Lg0AMhv9KyGkL9Q94WGh1t5fCFurN6SFo7AztfDBGpKj_fcd62c0pvM_zhkzY-JYxx-7px0ZTFKhK5SDNoS50NL1Y6m-QZZ_ziQWsd_ya4fhx8tBrH4Jx993mH1cJium8agyijXssGyre_R_HM5T1mYL4cPtLqtHP8FWbi07n_xMdObW-647yjrKGIhQU3wru0XK0ZNr0_rQmCkWzZYV5WlvuaHiKQuWWpNIg_vpyDeYSB97jEFoSLg3dI9ktXH4B_cJWqw"' const deserialized = deserializeState(serialized);
); expect(deserialized).to.deep.equal(state);
}); return serialized;
};
it('should serialize and deserialize with base64 serde', () => { it('should serialize and deserialize with default serde', () => {
expect(verifySerde(defaultState, 'base64')).toMatchInlineSnapshot( expect(verifySerde(defaultState)).toMatchInlineSnapshot(
'"base64:eyJjb2RlIjoiZmxvd2NoYXJ0IFREXG4gICAgQVtDaHJpc3RtYXNdIC0tPnxHZXQgbW9uZXl8IEIoR28gc2hvcHBpbmcpXG4gICAgQiAtLT4gQ3tMZXQgbWUgdGhpbmt9XG4gICAgQyAtLT58T25lfCBEW0xhcHRvcF1cbiAgICBDIC0tPnxUd298IEVbaVBob25lXVxuICAgIEMgLS0-fFRocmVlfCBGW2ZhOmZhLWNhciBDYXJdXG4gICIsIm1lcm1haWQiOiJ7XG4gIFwidGhlbWVcIjogXCJkZWZhdWx0XCJcbn0iLCJhdXRvU3luYyI6dHJ1ZSwidXBkYXRlRGlhZ3JhbSI6dHJ1ZX0"' '"pako:eNpVj81qw0AMhF9F6NRC_AI-BGK7zSXQQHLz5iBsObuk-8Naphjb7551fEl1EjPfiNGEjW8Zc7xHChqulXKQ5lCXOppeLPU3yLL9fGQB6x2PMxQfRw-99iEYd__c-GKFoJxOK8Yg2rjHslnlK__jeIaqPlEQH27vzvXPz_BVm7NO5_87OnJKfdcd5R1lDUUoKb4Q3KHlaMm0qfq0KgpFs2WFeVpb7mj4FYXKLQmlQfxldA3mEgfe4RBaEq4MpaftJi5PNtJU8w"'
); );
}); });
it('should serialize and deserialize with pako serde', () => { it('should serialize and deserialize with base64 serde', () => {
expect(verifySerde(defaultState, 'pako')).toMatchInlineSnapshot( expect(verifySerde(defaultState, 'base64')).toMatchInlineSnapshot(
'"pako:eNpVjk2Lg0AMhv9KyGkL9Q94WGh1t5fCFurN6SFo7AztfDBGpKj_fcd62c0pvM_zhkzY-JYxx-7px0ZTFKhK5SDNoS50NL1Y6m-QZZ_ziQWsd_ya4fhx8tBrH4Jx993mH1cJium8agyijXssGyre_R_HM5T1mYL4cPtLqtHP8FWbi07n_xMdObW-647yjrKGIhQU3wru0XK0ZNr0_rQmCkWzZYV5WlvuaHiKQuWWpNIg_vpyDeYSB97jEFoSLg3dI9ktXH4B_cJWqw"' '"base64:eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW0NocmlzdG1hc10gLS0-fEdldCBtb25leXwgQihHbyBzaG9wcGluZylcbiAgICBCIC0tPiBDe0xldCBtZSB0aGlua31cbiAgICBDIC0tPnxPbmV8IERbTGFwdG9wXVxuICAgIEMgLS0-fFR3b3wgRVtpUGhvbmVdXG4gICAgQyAtLT58VGhyZWV8IEZbZmE6ZmEtY2FyIENhcl1cbiAgIiwibWVybWFpZCI6IntcbiAgXCJ0aGVtZVwiOiBcImRlZmF1bHRcIlxufSIsImF1dG9TeW5jIjp0cnVlLCJ1cGRhdGVEaWFncmFtIjp0cnVlfQ"'
); );
}); });
it('should throw error for unrecognized serde', () => { it('should serialize and deserialize with pako serde', () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment expect(verifySerde(defaultState, 'pako')).toMatchInlineSnapshot(
// @ts-expect-error '"pako:eNpVj81qw0AMhF9F6NRC_AI-BGK7zSXQQHLz5iBsObuk-8Naphjb7551fEl1EjPfiNGEjW8Zc7xHChqulXKQ5lCXOppeLPU3yLL9fGQB6x2PMxQfRw-99iEYd__c-GKFoJxOK8Yg2rjHslnlK__jeIaqPlEQH27vzvXPz_BVm7NO5_87OnJKfdcd5R1lDUUoKb4Q3KHlaMm0qfq0KgpFs2WFeVpb7mj4FYXKLQmlQfxldA3mEgfe4RBaEq4MpaftJi5PNtJU8w"'
expect(() => serializeState(defaultState, 'unknown')).toThrowError( );
'Unknown serde type: unknown' });
);
expect(() => deserializeState('unknown:hello')).toThrowError('Unknown serde type: unknown'); it('should throw error for unrecognized serde', () => {
}); // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
expect(() => serializeState(defaultState, 'unknown')).toThrowError(
'Unknown serde type: unknown'
);
expect(() => deserializeState('unknown:hello')).toThrowError('Unknown serde type: unknown');
});
}); });
+40 -40
View File
@@ -3,61 +3,61 @@ import { toUint8Array, fromUint8Array, toBase64, fromBase64 } from 'js-base64';
import type { State } from '$lib/types'; import type { State } from '$lib/types';
interface Serde { interface Serde {
serialize: (state: string) => string; serialize: (state: string) => string;
deserialize: (state: string) => string; deserialize: (state: string) => string;
} }
const base64Serde: Serde = { const base64Serde: Serde = {
serialize: (state: string): string => { serialize: (state: string): string => {
return toBase64(state, true); return toBase64(state, true);
}, },
deserialize: (state: string): string => { deserialize: (state: string): string => {
return fromBase64(state); return fromBase64(state);
} }
}; };
export const pakoSerde: Serde = { export const pakoSerde: Serde = {
serialize: (state: string): string => { serialize: (state: string): string => {
const data = new TextEncoder().encode(state); const data = new TextEncoder().encode(state);
const compressed = deflate(data, { level: 9 }); const compressed = deflate(data, { level: 9 });
return fromUint8Array(compressed, true); return fromUint8Array(compressed, true);
}, },
deserialize: (state: string): string => { deserialize: (state: string): string => {
const data = toUint8Array(state); const data = toUint8Array(state);
return inflate(data, { to: 'string' }); return inflate(data, { to: 'string' });
} }
}; };
export type SerdeType = 'base64' | 'pako'; export type SerdeType = 'base64' | 'pako';
const serdes: { [key in SerdeType]: Serde } = { const serdes: { [key in SerdeType]: Serde } = {
base64: base64Serde, base64: base64Serde,
pako: pakoSerde pako: pakoSerde
}; };
export const serializeState = (state: State, serde: SerdeType = 'pako'): string => { export const serializeState = (state: State, serde: SerdeType = 'pako'): string => {
if (!(serde in serdes)) { if (serdes[serde] === undefined) {
throw new Error(`Unknown serde type: ${serde}`); throw new Error(`Unknown serde type: ${serde}`);
} }
const json = JSON.stringify(state); const json = JSON.stringify(state);
const serialized = serdes[serde].serialize(json); const serialized = serdes[serde].serialize(json);
return `${serde}:${serialized}`; return `${serde}:${serialized}`;
}; };
export const deserializeState = (state: string): State => { export const deserializeState = (state: string): State => {
let type: SerdeType, serialized: string; let type: SerdeType, serialized: string;
if (state.includes(':')) { if (state.includes(':')) {
let tempType: string; let tempType: string;
[tempType, serialized] = state.split(':'); [tempType, serialized] = state.split(':');
if (tempType in serdes) { if (tempType in serdes) {
type = tempType as SerdeType; type = tempType as SerdeType;
} else { } else {
throw new Error(`Unknown serde type: ${tempType}`); throw new Error(`Unknown serde type: ${tempType}`);
} }
} else { } else {
type = 'base64'; type = 'base64';
serialized = state; serialized = state;
} }
const json = serdes[type].deserialize(serialized); const json = serdes[type].deserialize(serialized);
return JSON.parse(json) as State; return JSON.parse(json) as State;
}; };
+127 -146
View File
@@ -1,29 +1,35 @@
import { writable, get, type Readable, derived } from 'svelte/store'; import { writable, get, derived } from 'svelte/store';
import { persist, localStorage } from './persist'; import { persist, localStorage } from './persist';
import { saveStatistics, countLines } from './stats'; import { saveStatistics, countLines } from './stats';
import { serializeState, deserializeState } from './serde'; import { serializeState, deserializeState } from './serde';
import { cmdKey, errorDebug, formatJSON } from './util'; import { cmdKey } from './util';
import { parse } from './mermaid'; import { parse, init } from './mermaid';
import type { ErrorHash, MarkerData, State, ValidatedState } from '$lib/types'; import type { Readable } from 'svelte/store';
import type { MermaidConfig } from 'mermaid'; import type { MarkerData, State, ValidatedState } from '$lib/types';
void init();
export const defaultState: State = { export const defaultState: State = {
code: `flowchart TD code: `graph TD
A[Christmas] -->|Get money| B(Go shopping) A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think} B --> C{Let me think}
C -->|One| D[Laptop] C -->|One| D[Laptop]
C -->|Two| E[iPhone] C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car] C -->|Three| F[fa:fa-car Car]
`, `,
mermaid: formatJSON({ mermaid: JSON.stringify(
theme: 'default' {
}), theme: 'default'
autoSync: true, },
updateDiagram: true null,
2
),
autoSync: true,
updateDiagram: true
}; };
const urlParseFailedState = `flowchart TD const urlParseFailedState = `graph TD
A[Loading URL failed. We can try to figure out why.] -->|Decode JSON| B(Please check the console to see the JSON and error details.) A[Loading URL failed. We can try to figure out why.] -->|Decode JSON| B(Please check the console to see the JSON and error details.)
B --> C{Is the JSON correct?} B --> C{Is the JSON correct?}
C -->|Yes| D(Please Click here to Raise an issue in github.<br/>Including the broken link in the issue <br/> will speed up the fix.) C -->|Yes| D(Please Click here to Raise an issue in github.<br/>Including the broken link in the issue <br/> will speed up the fix.)
@@ -37,164 +43,139 @@ const urlParseFailedState = `flowchart TD
// inputStateStore handles all updates and is shared externally when exporting via URL, History, etc. // inputStateStore handles all updates and is shared externally when exporting via URL, History, etc.
export const inputStateStore = persist(writable(defaultState), localStorage(), 'codeStore'); export const inputStateStore = persist(writable(defaultState), localStorage(), 'codeStore');
export const currentState: ValidatedState = (() => {
const state = get(inputStateStore);
return {
...state,
serialized: serializeState(state),
errorMarkers: [],
error: undefined,
editorMode: state.editorMode ?? 'code'
};
})();
const processState = async (state: State) => {
const processed: ValidatedState = {
...state,
serialized: '',
errorMarkers: [],
error: undefined,
editorMode: state.editorMode ?? 'code'
};
// No changes should be done to fields part of `state`.
try {
processed.serialized = serializeState(state);
await parse(state.code);
JSON.parse(state.mermaid);
} catch (error) {
processed.error = error as Error;
errorDebug();
console.error(error);
if ('hash' in error) {
try {
const {
loc: { first_line, last_line, first_column, last_column }
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
} = error.hash as ErrorHash;
const marker: MarkerData = {
severity: 8, // Error
startLineNumber: first_line,
startColumn: first_column,
endLineNumber: last_line,
endColumn: last_column + 1,
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment
message: error.str
};
processed.errorMarkers = [marker];
} catch (error) {
console.error('Error without line helper', error);
}
}
}
return processed;
};
// All internal reads should be done via stateStore, but it should not be persisted/shared externally. // All internal reads should be done via stateStore, but it should not be persisted/shared externally.
export const stateStore: Readable<ValidatedState> = derived( export const stateStore: Readable<ValidatedState> = derived([inputStateStore], ([state]) => {
[inputStateStore], const processed: ValidatedState = {
([state], set) => { ...state,
void processState(state).then(set); serialized: '',
}, errorMarkers: [],
currentState error: undefined,
); editorMode: state.editorMode ?? 'code'
};
// No changes should be done to fields part of `state`.
try {
processed.serialized = serializeState(state);
// await parse(state.code);
JSON.parse(state.mermaid);
} catch (e) {
processed.error = e;
console.error(e);
if (e.hash) {
try {
const marker: MarkerData = {
severity: 8, // Error
startLineNumber: e.hash.loc.first_line,
startColumn: e.hash.loc.first_column,
endLineNumber: e.hash.loc.last_line,
endColumn: (e.hash.loc.last_column as number) + 1,
message: e.str
};
processed.errorMarkers = [marker];
} catch (err) {
console.error('Error without line helper', err);
}
}
}
return processed;
});
export const loadState = (data: string): void => { export const loadState = (data: string): void => {
let state: State; let state: State;
console.log(`Loading '${data}'`); console.log(`Loading '${data}'`);
try { try {
state = deserializeState(data); state = deserializeState(data);
const mermaidConfig: MermaidConfig = const mermaidConfig: { [key: string]: string } =
typeof state.mermaid === 'string' typeof state.mermaid === 'string' ? JSON.parse(state.mermaid) : state.mermaid;
? (JSON.parse(state.mermaid) as MermaidConfig) if (
: state.mermaid; mermaidConfig.securityLevel &&
if ( mermaidConfig.securityLevel !== 'strict' &&
mermaidConfig.securityLevel && confirm(
mermaidConfig.securityLevel !== 'strict' && `Removing "securityLevel":"${mermaidConfig.securityLevel}" from the config for safety.\nClick Cancel if you trust the source of this Diagram.`
confirm( )
`Removing "securityLevel":"${mermaidConfig.securityLevel}" from the config for safety.\nClick Cancel if you trust the source of this Diagram.` ) {
) delete mermaidConfig.securityLevel; // Prevent setting overriding securityLevel when loading state to mitigate possible XSS attack
) { }
delete mermaidConfig.securityLevel; // Prevent setting overriding securityLevel when loading state to mitigate possible XSS attack state.mermaid = JSON.stringify(mermaidConfig, null, 2);
} } catch (e) {
state.mermaid = formatJSON(mermaidConfig); state = get(inputStateStore);
} catch (error) { if (data) {
state = get(inputStateStore); console.error('Init error', e);
if (data) { state.code = urlParseFailedState;
console.error('Init error', error); state.mermaid = defaultState.mermaid;
state.code = urlParseFailedState; }
state.mermaid = defaultState.mermaid; }
} updateCodeStore(state);
}
updateCodeStore(state);
}; };
export const updateCodeStore = (newState: Partial<State>): void => { export const updateCodeStore = (newState: Partial<State>): void => {
inputStateStore.update((state) => { inputStateStore.update((state) => {
return { ...state, ...newState }; return { ...state, ...newState };
}); });
}; };
let prompted = false; let prompted = false;
export const updateCode = ( export const updateCode = (
code: string, code: string,
{ {
updateDiagram = false, updateDiagram = false,
resetPanZoom = false resetPanZoom = false
}: { updateDiagram?: boolean; resetPanZoom?: boolean } = {} }: { updateDiagram?: boolean; resetPanZoom?: boolean } = {}
): void => { ): void => {
// console.log('updateCode', code); const lines = countLines(code);
const lines = countLines(code); saveStatistics(code);
saveStatistics(code);
errorDebug();
if (lines > 50 && !prompted && get(stateStore).autoSync) {
const turnOff = confirm(
`Long diagram detected. Turn off Auto Sync? Use ${cmdKey} + Enter or click the sync logo to manually sync.`
);
prompted = true;
if (turnOff) {
updateCodeStore({
autoSync: false
});
}
}
inputStateStore.update((state) => { if (lines > 50 && !prompted && get(stateStore).autoSync) {
if (resetPanZoom) { const turnOff = confirm(
state.pan = undefined; `Long diagram detected. Turn off Auto Sync? Use ${cmdKey} + Enter or click the sync logo to manually sync.`
state.zoom = undefined; );
} prompted = true;
return { ...state, code, updateDiagram }; if (turnOff) {
}); updateCodeStore({
autoSync: false
});
}
}
inputStateStore.update((state) => {
if (resetPanZoom) {
state.pan = undefined;
state.zoom = undefined;
}
return { ...state, code, updateDiagram };
});
}; };
export const updateConfig = (config: string): void => { export const updateConfig = (config: string): void => {
// console.log('updateConfig', config); inputStateStore.update((state) => {
inputStateStore.update((state) => { return { ...state, mermaid: config };
return { ...state, mermaid: config }; });
});
}; };
export const toggleDarkTheme = (dark: boolean): void => { export const toggleDarkTheme = (dark: boolean): void => {
inputStateStore.update((state) => { inputStateStore.update((state) => {
const config = JSON.parse(state.mermaid) as MermaidConfig; const config = JSON.parse(state.mermaid);
if (!config.theme || ['dark', 'default'].includes(config.theme)) { if (!config.theme || ['dark', 'default'].includes(config.theme)) {
config.theme = dark ? 'dark' : 'default'; config.theme = dark ? 'dark' : 'default';
} }
return { ...state, mermaid: formatJSON(config) }; return { ...state, mermaid: JSON.stringify(config, null, 2) };
}); });
}; };
let urlDebounce: number; let urlDebounce: number;
export const initURLSubscription = (): void => { export const initURLSubscription = (): void => {
stateStore.subscribe(({ serialized }) => { stateStore.subscribe(({ serialized }: ValidatedState) => {
clearTimeout(urlDebounce); if (serialized.length < 5) {
urlDebounce = window.setTimeout(() => { return;
history.replaceState(undefined, '', `#${serialized}`); }
}, 250); clearTimeout(urlDebounce);
}); urlDebounce = window.setTimeout(() => {
history.replaceState(undefined, undefined, `#${serialized}`);
}, 250);
});
}; };
export const getStateString = (): string => { export const getStateString = (): string => {
return JSON.stringify(get(inputStateStore)); return JSON.stringify(get(inputStateStore));
}; };
+10 -10
View File
@@ -1,19 +1,19 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { detectType } from './stats'; import { detectType } from './stats';
describe('diagram detection', () => { describe('diagram detection', () => {
it('should detect diagrams correctly', () => { it('should detect diagrams correctly', () => {
expect( expect(
detectType(`%%{{ detectType(`%%{{
graph`) graph`)
).toBe('graph'); ).toBe('graph');
expect(detectType(`gitGraph`)).toBe('gitGraph'); expect(detectType(`gitGraph`)).toBe('gitGraph');
expect( expect(
detectType(`%%{{ detectType(`%%{{
flowChart flowChart
graph`) graph`)
).toBe('flowChart'); ).toBe('flowChart');
expect(detectType(`loki -> thor`)).toBe(undefined); expect(detectType(`loki -> thor`)).toBe(undefined);
}); });
}); });
+74 -75
View File
@@ -1,99 +1,98 @@
import { browser } from '$app/environment'; import { browser } from '$app/environment';
import type { AnalyticsInstance } from 'analytics'; import type { AnalyticsInstance } from 'analytics';
export let analytics: AnalyticsInstance | undefined; export let analytics: AnalyticsInstance;
export const initAnalytics = async (): Promise<void> => { export const initAnalytics = async (): Promise<void> => {
if (browser && !analytics) { if (browser && !analytics) {
try { try {
const [{ Analytics }, { default: plausible }] = await Promise.all([ const [{ Analytics }, { default: plausible }] = await Promise.all([
import('analytics'), import('analytics'),
import('analytics-plugin-plausible') import('analytics-plugin-plausible')
]); ]);
analytics = Analytics({ analytics = Analytics({
app: 'mermaid-live-editor', app: 'mermaid-live-editor',
plugins: [ plugins: [
plausible({ plausible({
domain: 'mermaid.live', domain: 'mermaid.live',
hashMode: false, hashMode: false,
trackLocalhost: false, // By default 'false' trackLocalhost: false, // By default 'false'
apiHost: 'https://plausible.io' apiHost: 'https://plausible.io'
}) })
] ]
}); });
} catch (error) { } catch (e) {
console.log(error); console.log(e);
console.info('Analytics blocked ;)'); console.info('Analytics blocked ;)');
} }
} }
}; };
export const detectType = (text: string): string | undefined => { export const detectType = (text: string): string => {
const possibleDiagramTypes = [ const possibleDiagramTypes = [
'classDiagram', 'classDiagram',
'erDiagram', 'erDiagram',
'flowChart', 'flowChart',
'gantt', 'gantt',
'gitGraph', 'gitGraph',
'graph', 'graph',
'journey', 'journey',
'pie', 'pie',
'stateDiagram' 'stateDiagram'
]; ];
const firstLine = text const firstLine = text
.replace(/^\s*%%.*\n/g, '\n') .replace(/^\s*%%.*\n/g, '\n')
.trimStart() .trimStart()
.split(' ')[0] .split(' ')[0]
.toLowerCase(); .toLowerCase();
const detectedDiagram = possibleDiagramTypes.find((d) => firstLine.includes(d.toLowerCase())); const detectedDiagram = possibleDiagramTypes.find((d) => firstLine.includes(d.toLowerCase()));
return detectedDiagram; return detectedDiagram;
}; };
export const countLines = (code: string): number => { export const countLines = (code: string): number => {
return (code.match(/\n/g)?.length ?? 0) + 1; return (code.match(/\n/g) || '').length + 1;
}; };
export const saveStatistics = (graph: string): void => { export const saveStatistics = (graph: string): void => {
const graphType = detectType(graph); const graphType = detectType(graph);
if (!graphType) { if (!graphType) {
return; return;
} }
const length = countLines(graph); const length = countLines(graph);
logEvent('render', { graphType, length }); logEvent('render', { graphType, length });
}; };
const minutesToMilliSeconds = (minutes: number): number => { const minutesToMilliSeconds = (minutes: number): number => {
return minutes * 60_000; return minutes * 60_000;
}; };
const defaultDelay = minutesToMilliSeconds(1); const defaultDelay = minutesToMilliSeconds(1);
const delaysPerEvent = { const delaysPerEvent = {
render: minutesToMilliSeconds(5), render: minutesToMilliSeconds(5),
panZoom: minutesToMilliSeconds(10), panZoom: minutesToMilliSeconds(10),
copyClipboard: defaultDelay, copyClipboard: defaultDelay,
download: defaultDelay, download: defaultDelay,
copyMarkdown: defaultDelay, copyMarkdown: defaultDelay,
loadGist: defaultDelay, loadGist: defaultDelay,
loadSampleDiagram: defaultDelay, loadSampleDiagram: defaultDelay,
renderDiagram: defaultDelay, renderDiagram: defaultDelay,
history: defaultDelay, history: defaultDelay,
migration: defaultDelay, migration: defaultDelay,
themeChange: defaultDelay themeChange: defaultDelay
}; };
export type AnalyticsEvent = keyof typeof delaysPerEvent; export type AnalyticsEvent = keyof typeof delaysPerEvent;
const timeouts: Map<string, number> = new Map<string, number>(); const timeouts: Record<string, number> = {};
// manual debounce to reduce the number of events sent to analytics // manual debounce to reduce the number of events sent to analytics
export const logEvent = (name: AnalyticsEvent, data?: unknown): void => { export const logEvent = (name: AnalyticsEvent, data?: unknown): void => {
if (!analytics) { if (!analytics) {
return; return;
} }
const key = data ? JSON.stringify({ name, data }) : name; const key = data ? JSON.stringify({ name, data }) : name;
if (timeouts.has(key)) { if (timeouts[key] === undefined) {
clearTimeout(timeouts.get(key)); void analytics.track(name, data);
} else { } else {
void analytics.track(name, data); clearTimeout(timeouts[key]);
} }
timeouts.set( timeouts[key] = window.setTimeout(() => {
key, delete timeouts[key];
window.setTimeout(() => timeouts.delete(key), delaysPerEvent[name]) }, delaysPerEvent[name]);
);
}; };
+24 -24
View File
@@ -4,35 +4,35 @@ import { persist, localStorage } from '$lib/util/persist';
import { logEvent } from './stats'; import { logEvent } from './stats';
export interface ThemeConfig { export interface ThemeConfig {
isDark: boolean; isDark: boolean;
theme?: string; theme?: string;
} }
export const themeStore: Writable<ThemeConfig> = persist( export const themeStore: Writable<ThemeConfig> = persist(
writable({ writable({
isDark: false isDark: false
}), }),
localStorage(), localStorage(),
'themeStore' 'themeStore'
); );
const darkThemes = new Set([ const darkThemes = [
'dark', 'dark',
'synthwave', 'synthwave',
'halloween', 'halloween',
'aqua', 'aqua',
'forest', 'forest',
'luxury', 'luxury',
'black', 'black',
'dracula' 'dracula'
]); ];
export const setTheme = (theme: string): void => { export const setTheme = (theme: string): void => {
if (theme.includes(' ')) { if (theme.includes(' ')) {
theme = theme.split(' ')[1].trim(); theme = theme.split(' ')[1].trim();
} }
const isDark = darkThemes.has(theme); const isDark = darkThemes.includes(theme);
console.log('Setting theme', theme); console.log('Setting theme', theme);
themeStore.set({ theme, isDark }); themeStore.set({ theme, isDark });
logEvent('themeChange', { theme, isDark }); logEvent('themeChange', { theme, isDark });
}; };
+12 -32
View File
@@ -5,44 +5,24 @@ import { initLoading } from './loading';
import { applyMigrations } from './migrations'; import { applyMigrations } from './migrations';
export const loadStateFromURL = (): void => { export const loadStateFromURL = (): void => {
loadState(window.location.hash.slice(1)); loadState(window.location.hash.slice(1));
}; };
export const syncDiagram = (): void => { export const syncDiagram = (): void => {
updateCodeStore({ updateCodeStore({
updateDiagram: true updateDiagram: true
}); });
}; };
export const initHandler = async (): Promise<void> => { export const initHandler = async (): Promise<void> => {
applyMigrations(); applyMigrations();
loadStateFromURL(); loadStateFromURL();
await initLoading('Loading Gist...', loadDataFromUrl().catch(console.error)); await initLoading('Loading Gist...', loadDataFromUrl().catch(console.error));
syncDiagram(); syncDiagram();
initURLSubscription(); initURLSubscription();
await initAnalytics(); await initAnalytics();
await analytics?.page(); analytics?.page();
}; };
export const isMac = navigator.platform.toUpperCase().includes('MAC'); export const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
export const cmdKey = isMac ? 'Cmd' : 'Ctrl'; export const cmdKey = isMac ? 'Cmd' : 'Ctrl';
let count = 0;
export const errorDebug = (limit = 100) => {
count += 1;
if (count > limit) {
console.log(count, limit);
// eslint-disable-next-line no-debugger
debugger;
}
};
export const formatJSON = (data: unknown): string => JSON.stringify(data, undefined, 2);
export const fetchJSON = async <T>(url: string): Promise<T> => {
const res = await fetch(url);
return res.json() as T;
};
export const fetchText = async (url: string): Promise<string> => {
const res = await fetch(url);
return res.text();
};
-1
View File
@@ -1,4 +1,3 @@
export const prerender = true; export const prerender = true;
export const csr = true; export const csr = true;
export const ssr = false; export const ssr = false;
export const trailingSlash = 'ignore';
+70 -70
View File
@@ -1,87 +1,87 @@
<script lang="ts"> <script lang="ts">
import '../app.postcss'; import '../app.postcss';
import { base } from '$app/paths'; import { base } from '$app/paths';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import { loadingStateStore } from '$lib/util/loading'; import { loadingStateStore } from '$lib/util/loading';
import { setTheme, themeStore } from '$lib/util/theme'; import { setTheme, themeStore } from '$lib/util/theme';
import { toggleDarkTheme } from '$lib/util/state'; import { toggleDarkTheme } from '$lib/util/state';
import { initHandler } from '$lib/util/util'; import { initHandler } from '$lib/util/util';
// This can be removed once https://github.com/sveltejs/kit/issues/1612 is fixed. // This can be removed once https://github.com/sveltejs/kit/issues/1612 is fixed.
// Then move it into src and vite will bundle it automatically. // Then move it into src and vite will bundle it automatically.
onMount(() => { onMount(() => {
window.addEventListener('hashchange', () => { window.addEventListener('hashchange', async (ev) => {
void initHandler(); await initHandler();
}); });
if ('serviceWorker' in navigator) { if ('serviceWorker' in navigator) {
navigator.serviceWorker navigator.serviceWorker
.register(`${base}/service-worker.js`, { .register(`${base}/service-worker.js`, {
scope: `${base}/` scope: `${base}/`
}) })
.then(function (registration) { .then(function (registration) {
console.log('Registration successful, scope is:', registration.scope); console.log('Registration successful, scope is:', registration.scope);
}) })
.catch(function (error) { .catch(function (error) {
console.log('Service worker registration failed, error:', error); console.log('Service worker registration failed, error:', error);
}); });
} }
const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches; const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
if ($themeStore.theme === undefined) { if ($themeStore.theme === undefined) {
setTheme(isDarkMode ? 'dark' : 'light'); setTheme(isDarkMode ? 'dark' : 'light');
} }
themeStore.subscribe(({ theme, isDark }) => { themeStore.subscribe(({ theme, isDark }) => {
if (theme) { if (theme) {
document.getElementsByTagName('html')[0].setAttribute('data-theme', theme); document.getElementsByTagName('html')[0].setAttribute('data-theme', theme);
toggleDarkTheme(isDark); toggleDarkTheme(isDark);
} }
}); });
}); });
</script> </script>
<main class="h-screen text-primary-content"> <main class="h-screen text-primary-content">
<slot /> <slot />
</main> </main>
{#if $loadingStateStore.loading} {#if $loadingStateStore.loading}
<div <div
class="w-screen h-screen z-50 absolute left-0 top-0 bg-gray-600 opacity-50 flex align-middle justify-center"> class="w-screen h-screen z-50 absolute left-0 top-0 bg-gray-600 opacity-50 flex align-middle justify-center">
<div class="text-indigo-100 text-4xl font-bold my-auto"> <div class="text-indigo-100 text-4xl font-bold my-auto">
<div class="loader mx-auto" /> <div class="loader mx-auto" />
<div>{$loadingStateStore.message}</div> <div>{$loadingStateStore.message}</div>
</div> </div>
</div> </div>
{/if} {/if}
<style> <style>
.loader { .loader {
border: 0.45em solid #f3f3f3; border: 0.45em solid #f3f3f3;
border-radius: 50%; border-radius: 50%;
border-top: 0.45em solid #6365f1; border-top: 0.45em solid #6365f1;
width: 3em; width: 3em;
height: 3em; height: 3em;
-webkit-animation: spin 2s linear infinite; /* Safari */ -webkit-animation: spin 2s linear infinite; /* Safari */
animation: spin 2s linear infinite; animation: spin 2s linear infinite;
} }
/* Safari */ /* Safari */
@-webkit-keyframes spin { @-webkit-keyframes spin {
0% { 0% {
-webkit-transform: rotate(0deg); -webkit-transform: rotate(0deg);
} }
100% { 100% {
-webkit-transform: rotate(360deg); -webkit-transform: rotate(360deg);
} }
} }
@keyframes spin { @keyframes spin {
0% { 0% {
transform: rotate(0deg); transform: rotate(0deg);
} }
100% { 100% {
transform: rotate(360deg); transform: rotate(360deg);
} }
} }
</style> </style>
+14 -14
View File
@@ -1,17 +1,17 @@
<script lang="ts"> <script lang="ts">
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import { base } from '$app/paths'; import { base } from '$app/paths';
onMount(async () => { onMount(async () => {
// Handle old live editor links and redirect to new version // Handle old live editor links and redirect to new version
const hash = window.location.hash.split('/'); const hash = window.location.hash.split('/');
let newURL = 'edit'; let newURL = 'edit';
if (hash.length > 2) { if (hash.length > 2) {
newURL = `${hash[1]}#${hash[2]}`; newURL = `${hash[1]}#${hash[2]}`;
} }
await goto(`${base}/${newURL}`, { await goto(`${base}/${newURL}`, {
replaceState: true replaceState: true
}); });
}); });
</script> </script>
+182 -189
View File
@@ -1,209 +1,202 @@
<script lang="ts"> <script lang="ts">
import Editor from '$lib/components/Editor.svelte'; import Editor from '$lib/components/editor.svelte';
import Navbar from '$lib/components/Navbar.svelte'; import Navbar from '$lib/components/navbar.svelte';
import Preset from '$lib/components/Preset.svelte'; import Preset from '$lib/components/preset.svelte';
import Actions from '$lib/components/Actions.svelte'; import Actions from '$lib/components/actions.svelte';
import View from '$lib/components/View.svelte'; import View from '$lib/components/view.svelte';
import Card from '$lib/components/Card/Card.svelte'; import Card from '$lib/components/card/card.svelte';
import History from '$lib/components/History/History.svelte'; import History from '$lib/components/history/history.svelte';
import { inputStateStore, stateStore, updateCodeStore } from '$lib/util/state'; import { inputStateStore, stateStore, updateCodeStore } from '$lib/util/state';
import { cmdKey, initHandler, syncDiagram } from '$lib/util/util'; import { cmdKey, initHandler, syncDiagram } from '$lib/util/util';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import type { Tab, DocumentationConfig, EditorMode, ValidatedState } from '$lib/types'; import type { Tab, DocConfig, EditorMode, ValidatedState } from '$lib/types';
import { base } from '$app/paths'; import { base } from '$app/paths';
const docURLBase = 'https://mermaid-js.github.io/mermaid'; const docURLBase = 'https://mermaid-js.github.io/mermaid';
const docMap: DocumentationConfig = { const docMap: DocConfig = {
graph: { graph: {
code: '/#/flowchart', code: '/#/flowchart',
config: '/#/flowchart?id=configuration' config: '/#/flowchart?id=configuration'
}, },
flowchart: { flowchart: {
code: '/#/flowchart', code: '/#/flowchart',
config: '/#/flowchart?id=configuration' config: '/#/flowchart?id=configuration'
}, },
sequenceDiagram: { sequenceDiagram: {
code: '/#/sequenceDiagram', code: '/#/sequenceDiagram',
config: '/#/sequenceDiagram?id=configuration' config: '/#/sequenceDiagram?id=configuration'
}, },
classDiagram: { classDiagram: {
code: '/#/classDiagram', code: '/#/classDiagram',
config: '/#/classDiagram?id=configuration' config: '/#/classDiagram?id=configuration'
}, },
'stateDiagram-v2': { 'stateDiagram-v2': {
code: '/#/stateDiagram' code: '/#/stateDiagram'
}, },
gantt: { gantt: {
code: '/#/gantt', code: '/#/gantt',
config: '/#/gantt?id=configuration' config: '/#/gantt?id=configuration'
}, },
pie: { pie: {
code: '/#/pie' code: '/#/pie'
}, },
erDiagram: { erDiagram: {
code: '/#/entityRelationshipDiagram', code: '/#/entityRelationshipDiagram',
config: '/#/entityRelationshipDiagram?id=styling' config: '/#/entityRelationshipDiagram?id=styling'
}, },
journey: { journey: {
code: '/#/user-journey' code: '/#/user-journey'
}, },
gitGraph: { gitGraph: {
code: '/#/gitgraph', code: '/#/gitgraph',
config: '/#/gitgraph?id=gitgraph-specific-configuration-options' config: '/#/gitgraph?id=gitgraph-specific-configuration-options'
} }
}; };
let docURL = docURLBase; let docURL = docURLBase;
let activeTabID = 'code'; let activeTabID = 'code';
let docKey = ''; stateStore.subscribe(({ code, editorMode }: ValidatedState) => {
stateStore.subscribe(({ code, editorMode }: ValidatedState) => { activeTabID = editorMode;
activeTabID = editorMode; const codeTypeMatch = /([\S]+)[\s\n]/.exec(code);
const codeTypeMatch = /([\S]+)[\s\n]/.exec(code); if (codeTypeMatch && codeTypeMatch.length > 1) {
if (codeTypeMatch && codeTypeMatch.length > 1) { const docKey = codeTypeMatch[1];
docKey = codeTypeMatch[1]; const docConfig = docMap[docKey] ?? { code: '' };
const docConfig = docMap[docKey] ?? { code: '' }; docURL = docURLBase + (docConfig[editorMode] ?? docConfig.code ?? '');
docURL = docURLBase + (docConfig[editorMode] ?? docConfig.code ?? ''); }
} });
});
const tabSelectHandler = (message: CustomEvent<Tab>) => { const tabSelectHandler = (message: CustomEvent<Tab>) => {
const editorMode: EditorMode = message.detail.id === 'code' ? 'code' : 'config'; const editorMode: EditorMode = message.detail.id === 'code' ? 'code' : 'config';
updateCodeStore({ editorMode }); updateCodeStore({ editorMode });
}; };
const tabs: Tab[] = [ const tabs: Tab[] = [
{ {
id: 'code', id: 'code',
title: 'Code', title: 'Code',
icon: 'fas fa-code' icon: 'fas fa-code'
}, },
{ {
id: 'config', id: 'config',
title: 'Config', title: 'Config',
icon: 'fas fa-cogs' icon: 'fas fa-cogs'
} }
]; ];
onMount(async () => { onMount(async () => {
await initHandler(); await initHandler();
const resizer = document.getElementById('resizeHandler'); const resizer = document.getElementById('resizeHandler');
const element = document.getElementById('editorPane'); const element = document.getElementById('editorPane');
if (!resizer || !element) { const resize = (e: { pageX: number }) => {
console.debug('Failed to find resize handler or editor pane', { resizer, element }); const newWidth = e.pageX - element.getBoundingClientRect().left;
return; if (newWidth > 50) {
} element.style.width = `${newWidth}px`;
const resize = (e: { pageX: number }) => { }
const newWidth = e.pageX - element.getBoundingClientRect().left; };
if (newWidth > 50) {
element.style.width = `${newWidth}px`;
}
};
const stopResize = () => { const stopResize = () => {
window.removeEventListener('mousemove', resize); window.removeEventListener('mousemove', resize);
}; };
resizer.addEventListener('mousedown', (e) => { resizer.addEventListener('mousedown', (e) => {
e.preventDefault(); e.preventDefault();
window.addEventListener('mousemove', resize); window.addEventListener('mousemove', resize);
window.addEventListener('mouseup', stopResize); window.addEventListener('mouseup', stopResize);
}); });
}); });
</script> </script>
<div class="h-full flex flex-col overflow-hidden"> <div class="h-full flex flex-col overflow-hidden">
<Navbar /> <Navbar />
<div class="flex-1 flex overflow-hidden"> <div class="flex-1 flex overflow-hidden">
<div class="hidden md:flex flex-col" id="editorPane" style="width: 40%"> <div class="hidden md:flex flex-col" id="editorPane" style="width: 40%">
<Card on:select={tabSelectHandler} {tabs} isCloseable={false} {activeTabID} title="Mermaid"> <Card on:select={tabSelectHandler} {tabs} isCloseable={false} {activeTabID} title="Mermaid">
<div slot="actions" class="flex flex-row items-center"> <div slot="actions" class="flex flex-row items-center">
<div class="form-control flex-row items-center"> <div class="form-control flex-row items-center">
<label class="cursor-pointer label" for="autoSync"> <label class="cursor-pointer label" for="autoSync">
<span> Auto sync</span> <span> Auto sync</span>
<input <input
type="checkbox" type="checkbox"
class="toggle {$stateStore.autoSync ? 'btn-secondary' : 'toggle-primary'} ml-1" class="toggle {$stateStore.autoSync ? 'btn-secondary' : 'toggle-primary'} ml-1"
id="autoSync" id="autoSync"
bind:checked={$inputStateStore.autoSync} /> bind:checked={$inputStateStore.autoSync} />
</label> </label>
</div> </div>
{#if !$stateStore.autoSync} {#if !$stateStore.autoSync}
<button <button
class="btn btn-secondary btn-xs mr-1" class="btn btn-secondary btn-xs mr-1"
title="Sync Diagram ({cmdKey} + Enter)" title="Sync Diagram ({cmdKey} + Enter)"
data-cy="sync" data-cy="sync"
on:click={syncDiagram}><i class="fas fa-sync" /></button> on:click={syncDiagram}><i class="fas fa-sync" /></button>
{/if} {/if}
<button <button class="btn btn-secondary btn-xs" title="View documentation">
class="btn btn-secondary btn-xs" <a target="_blank" rel="noreferrer" href={docURL} data-cy="docs">
title="View documentation for {docKey.replace('Diagram', '')} diagram"> <i class="fas fa-book mr-1" />Docs
<a target="_blank" rel="noreferrer" href={docURL} data-cy="docs"> </a>
<i class="fas fa-book mr-1" />Docs </button>
</a> </div>
</button>
</div>
<Editor /> <Editor />
</Card> </Card>
<div class="-mt-2"> <div class="-mt-2">
<Preset /> <Preset />
<History /> <History />
<Actions /> <Actions />
</div> </div>
</div> </div>
<div id="resizeHandler" class="hidden md:block" /> <div id="resizeHandler" class="hidden md:block" />
<div class="flex-1 flex flex-col overflow-hidden"> <div class="flex-1 flex flex-col overflow-hidden">
<Card title="Diagram" isCloseable={false}> <Card title="Diagram" isCloseable={false}>
<div slot="actions" class="flex flex-row items-center"> <div slot="actions" class="flex flex-row items-center">
<label class="cursor-pointer label py-0" for="panZoom"> <label class="cursor-pointer label py-0" for="panZoom">
<span>Pan & Zoom</span> <span>Pan & Zoom</span>
<input <input
type="checkbox" type="checkbox"
class="toggle {$stateStore.panZoom ? 'btn-secondary' : 'toggle-primary'} ml-1" class="toggle {$stateStore.panZoom ? 'btn-secondary' : 'toggle-primary'} ml-1"
id="panZoom" id="panZoom"
bind:checked={$inputStateStore.panZoom} /> bind:checked={$inputStateStore.panZoom} />
</label> </label>
<a <a
href={`${base}/view#${$stateStore.serialized}`} href={`${base}/view#${$stateStore.serialized}`}
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
class="btn btn-secondary btn-xs" class="btn btn-secondary btn-xs"
title="View diagram in new page" title="View diagram in new page"
><i class="fas fa-external-link-alt mr-1" />Full screen</a> ><i class="fas fa-external-link-alt mr-1" />Full screen</a>
</div> </div>
<div class="flex-1 overflow-auto"> <div class="flex-1 overflow-auto">
<View /> <View />
</div> </div>
</Card> </Card>
<div class="md:hidden rounded shadow p-2 mx-2"> <div class="md:hidden rounded shadow p-2 mx-2">
Code editing not supported on mobile. Please use a desktop browser. Code editing not supported on mobile. Please use a desktop browser.
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<style> <style>
#resizeHandler { #resizeHandler {
cursor: col-resize; cursor: col-resize;
padding: 0 2px; padding: 0 2px;
} }
#resizeHandler::after { #resizeHandler::after {
width: 2px; width: 2px;
height: 100%; height: 100%;
top: 0; top: 0;
content: ''; content: '';
position: absolute; position: absolute;
background-color: hsla(var(--b3)); background-color: hsla(var(--b3));
margin-left: -1px; margin-left: -1px;
transition-duration: 0.2s; transition-duration: 0.2s;
} }
#resizeHandler:hover::after { #resizeHandler:hover::after {
margin-left: -2px; margin-left: -2px;
background-color: hsla(var(--p)); background-color: hsla(var(--p));
width: 4px; width: 4px;
} }
</style> </style>
+4 -4
View File
@@ -1,8 +1,8 @@
<script lang="ts"> <script lang="ts">
import View from '$lib/components/View.svelte'; import View from '$lib/components/view.svelte';
import { initHandler } from '$lib/util/util'; import { initHandler } from '$lib/util/util';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
onMount(initHandler); onMount(initHandler);
</script> </script>
<View /> <View />
+3 -3
View File
@@ -5,7 +5,7 @@ expect.extend(matchers);
// TODO: Remove once https://github.com/sveltejs/kit/issues/6259 is closed. // TODO: Remove once https://github.com/sveltejs/kit/issues/6259 is closed.
beforeAll(() => { beforeAll(() => {
vi.mock('$app/environment', () => ({ vi.mock('$app/environment', () => ({
browser: 'window' in globalThis browser: 'window' in globalThis
})); }));
}); });
+18 -17
View File
@@ -3,23 +3,24 @@ import adapter from '@sveltejs/adapter-static';
/** @type {import('@sveltejs/kit').Config} */ /** @type {import('@sveltejs/kit').Config} */
const config = { const config = {
// Consult https://github.com/sveltejs/svelte-preprocess // Consult https://github.com/sveltejs/svelte-preprocess
// for more information about preprocessors // for more information about preprocessors
preprocess: [ preprocess: [
preprocess({ preprocess({
postcss: true postcss: true
}) })
], ],
kit: { kit: {
adapter: adapter({ adapter: adapter({
pages: `docs` pages: `docs`
}), }),
paths: process.env['DEPLOY'] paths: process.env['DEPLOY']
? { ? {
base: `/mermaid-live-editor` base: `/mermaid-live-editor`
} }
: {} : {},
} trailingSlash: 'ignore'
}
}; };
export default config; export default config;
+8 -8
View File
@@ -1,10 +1,10 @@
module.exports = { module.exports = {
plugins: [require('daisyui')], plugins: [require('daisyui')],
content: ['./src/**/*.{html,js,svelte,ts}'], content: ['./src/**/*.{html,js,svelte,ts}'],
theme: { theme: {
extend: {} extend: {}
}, },
variants: { variants: {
extend: {} extend: {}
} }
}; };
+15 -17
View File
@@ -1,19 +1,17 @@
{ {
"include": [ "include": [
"src/**/*.d.ts", "src/**/*.d.ts",
"src/**/*.ts", "src/**/*.ts",
"src/**/*.svelte", "src/**/*.svelte",
"cypress/**/*.ts", "cypress/**/*.ts",
"cypress/**/*.js", "cypress/**/*.js",
"cypress/**/*.json", "static/**/*.js",
"static/**/*.js", "static/**/*.json"
"static/**/*.json" ],
], "compilerOptions": {
"compilerOptions": { "resolveJsonModule": true,
"resolveJsonModule": true, "allowSyntheticDefaultImports": true,
"allowSyntheticDefaultImports": true, "types": ["vitest/importMeta"]
"strictNullChecks": true, },
"types": ["vitest/importMeta"] "extends": "./.svelte-kit/tsconfig.json"
},
"extends": "./.svelte-kit/tsconfig.json"
} }
+25 -25
View File
@@ -1,26 +1,26 @@
import { sveltekit } from '@sveltejs/kit/vite'; import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vitest/config'; /** @type {import('vite').UserConfig} */
const config = {
export default defineConfig({ plugins: [sveltekit()],
plugins: [sveltekit()], envPrefix: 'MERMAID_',
envPrefix: 'MERMAID_', optimizeDeps: { include: ['mermaid'] },
optimizeDeps: { include: ['mermaid'] }, server: {
server: { port: 3000,
port: 3000, host: true
host: true },
}, preview: {
preview: { port: 3000,
port: 3000, host: true
host: true },
}, test: {
test: { environment: 'jsdom',
environment: 'jsdom', // in-source testing
// in-source testing includeSource: ['src/**/*.{js,ts,svelte}'],
includeSource: ['src/**/*.{js,ts,svelte}'], setupFiles: ['./src/tests/setup.ts'],
setupFiles: ['./src/tests/setup.ts'], coverage: {
coverage: { exclude: ['src/mocks', '.svelte-kit', 'src/**/*.test.ts'],
exclude: ['src/mocks', '.svelte-kit', 'src/**/*.test.ts'], reporter: ['text', 'json', 'html', 'lcov']
reporter: ['text', 'json', 'html', 'lcov'] }
} }
} };
}); export default config;
+888 -1194
View File
File diff suppressed because it is too large Load Diff