Compare commits
151
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
acd1353b12 | ||
|
|
8215f56eba | ||
|
|
395e0a558b | ||
|
|
7dc59f1396 | ||
|
|
59168d2437 | ||
|
|
5a6dccb263 | ||
|
|
6c16fa76ff | ||
|
|
ccbb45a09c | ||
|
|
052665ef09 | ||
|
|
ee1652e9f2 | ||
|
|
bbd6378065 | ||
|
|
e93641e41f | ||
|
|
5925448ca4 | ||
|
|
5e930d19e7 | ||
|
|
131dd06cde | ||
|
|
e96225dc69 | ||
|
|
3a42afd102 | ||
|
|
5394074ac5 | ||
|
|
20358bc254 | ||
|
|
6ece0a8a94 | ||
|
|
71f4097fa0 | ||
|
|
308aec1580 | ||
|
|
8c07649b10 | ||
|
|
3a1b8f87c3 | ||
|
|
af4f60874e | ||
|
|
e5f303e6e2 | ||
|
|
e461f108f1 | ||
|
|
64519ba8a1 | ||
|
|
ec5937b4fb | ||
|
|
10a11cfc32 | ||
|
|
9ebbd3b36c | ||
|
|
9e25c2d2c4 | ||
|
|
9853442201 | ||
|
|
ebca0ebe34 | ||
|
|
abb2405436 | ||
|
|
a6b1254425 | ||
|
|
95bf41d3e6 | ||
|
|
68f81df59b | ||
|
|
d3b25e5cb8 | ||
|
|
65c1ea844c | ||
|
|
864988e24a | ||
|
|
2fc032f58a | ||
|
|
2033e9002f | ||
|
|
651a5cb7ef | ||
|
|
a7454aa8cb | ||
|
|
43ff34178e | ||
|
|
703744ebf3 | ||
|
|
15eaee6e9b | ||
|
|
fa9b0344f4 | ||
|
|
965b39c2f2 | ||
|
|
26908080cb | ||
|
|
7c64a65497 | ||
|
|
be75d950bd | ||
|
|
4022d8d872 | ||
|
|
ccb294e5df | ||
|
|
8d1f3f08f8 | ||
|
|
a12e9a3e6d | ||
|
|
c138e1dc94 | ||
|
|
74431cdc08 | ||
|
|
0812b84487 | ||
|
|
cfc5567980 | ||
|
|
096f005938 | ||
|
|
37d96f9a87 | ||
|
|
8c4b7d52d1 | ||
|
|
cc7411fef8 | ||
|
|
1382504456 | ||
|
|
860039a924 | ||
|
|
33a4cbbf78 | ||
|
|
7be86b5fa7 | ||
|
|
b835e0448d | ||
|
|
7c5f9f1661 | ||
|
|
0a34cbe9c7 | ||
|
|
a2146da8e1 | ||
|
|
d23de5f9e0 | ||
|
|
7d18fa6b95 | ||
|
|
8dbb011b98 | ||
|
|
4c398ed8dd | ||
|
|
532e7a6537 | ||
|
|
049635cf3a | ||
|
|
c06511f11f | ||
|
|
e6adff074a | ||
|
|
55988eb750 | ||
|
|
e368a20b8d | ||
|
|
3cc56a0348 | ||
|
|
36b7aba2f4 | ||
|
|
54485ac068 | ||
|
|
fc6cf1f014 | ||
|
|
048f280b8e | ||
|
|
19f26ce4b9 | ||
|
|
6f115d4ac2 | ||
|
|
347d669c9c | ||
|
|
df7da711a9 | ||
|
|
282dfcc701 | ||
|
|
998c5f7fd9 | ||
|
|
6c907c48c7 | ||
|
|
fe981b7646 | ||
|
|
e36b1d42e4 | ||
|
|
a62a65ea05 | ||
|
|
d9cdab3528 | ||
|
|
5b3b0a499e | ||
|
|
1b6a1910ce | ||
|
|
f794fa9e0e | ||
|
|
17ca5f29d0 | ||
|
|
b7aae5f94f | ||
|
|
6888765e37 | ||
|
|
25e186158d | ||
|
|
ffd68c7551 | ||
|
|
909b95ba7b | ||
|
|
f4dd01c4fe | ||
|
|
7508a555d4 | ||
|
|
4453a04a05 | ||
|
|
9d3a33e593 | ||
|
|
0378cd4ba6 | ||
|
|
c518217ba7 | ||
|
|
c9a2e6bf09 | ||
|
|
f136f7bd58 | ||
|
|
03d2be91e6 | ||
|
|
3e6c28f15a | ||
|
|
2b800e960d | ||
|
|
06bd4cf176 | ||
|
|
42a55e10a6 | ||
|
|
996db3b198 | ||
|
|
7a598f408c | ||
|
|
924d10aac3 | ||
|
|
22df217b44 | ||
|
|
7c4c2a02f9 | ||
|
|
20c6e9146c | ||
|
|
afeb649833 | ||
|
|
fcf53c98c2 | ||
|
|
749968e0f5 | ||
|
|
ba56f08370 | ||
|
|
d92bf85009 | ||
|
|
6936dc5755 | ||
|
|
b41ff80d9d | ||
|
|
68ab43ac5d | ||
|
|
68b589a33a | ||
|
|
9eb39f31a0 | ||
|
|
08eaf725b9 | ||
|
|
85ad89b915 | ||
|
|
60c352a849 | ||
|
|
b0aa0a9cb2 | ||
|
|
34dafa13c9 | ||
|
|
684bd708de | ||
|
|
d5ee6d4c02 | ||
|
|
233f1822d1 | ||
|
|
bf06bdf71a | ||
|
|
68a0d29320 | ||
|
|
14ac5f23a5 | ||
|
|
e7676cf4a8 | ||
|
|
0f34a76ded | ||
|
|
ee934c60b4 |
+53
-3
@@ -5,9 +5,19 @@ module.exports = {
|
||||
'eslint:recommended',
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
// 'plugin:@typescript-eslint/recommended-requiring-type-checking',
|
||||
'plugin:@typescript-eslint/strict',
|
||||
'plugin:unicorn/recommended',
|
||||
'prettier'
|
||||
],
|
||||
plugins: ['svelte3', 'tailwindcss', '@typescript-eslint', 'es', 'vitest'],
|
||||
plugins: [
|
||||
'svelte3',
|
||||
'tailwindcss',
|
||||
'@typescript-eslint',
|
||||
'es',
|
||||
'vitest',
|
||||
'no-only-tests',
|
||||
'unicorn'
|
||||
],
|
||||
ignorePatterns: [
|
||||
'docs/*',
|
||||
'*.cjs',
|
||||
@@ -19,7 +29,19 @@ module.exports = {
|
||||
'package.json',
|
||||
'tsconfig.json'
|
||||
],
|
||||
overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }],
|
||||
overrides: [
|
||||
{ files: ['*.svelte'], processor: 'svelte3/svelte3' },
|
||||
{
|
||||
files: ['*.ts'],
|
||||
extends: [
|
||||
'eslint:recommended',
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:@typescript-eslint/recommended-requiring-type-checking',
|
||||
'plugin:@typescript-eslint/strict',
|
||||
'prettier'
|
||||
]
|
||||
}
|
||||
],
|
||||
settings: {
|
||||
'svelte3/typescript': () => require('typescript')
|
||||
},
|
||||
@@ -45,6 +67,34 @@ module.exports = {
|
||||
'@typescript-eslint/no-unsafe-member-access': 'off',
|
||||
'@typescript-eslint/no-unsafe-assignment': 'off',
|
||||
'es/no-regexp-lookbehind-assertions': 'error',
|
||||
curly: ['error', 'all']
|
||||
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
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
@@ -16,7 +16,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: '16'
|
||||
node-version: 18
|
||||
cache: yarn
|
||||
|
||||
- name: Build & Deploy
|
||||
|
||||
@@ -32,7 +32,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16
|
||||
node-version: 18
|
||||
cache: 'yarn'
|
||||
|
||||
# Install NPM dependencies, cache them correctly
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16
|
||||
node-version: 18
|
||||
cache: 'yarn'
|
||||
|
||||
- name: Lint & Test
|
||||
|
||||
@@ -1,18 +1,32 @@
|
||||
name: Update Browserslist
|
||||
name: Update Browserslist database
|
||||
|
||||
on:
|
||||
push:
|
||||
branches-ignore:
|
||||
- 'develop'
|
||||
- 'master'
|
||||
schedule:
|
||||
- cron: '0 2 1,15 * *'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
build:
|
||||
update-browserslist-database:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- run: npx browserslist@latest --update-db
|
||||
- name: Commit changes
|
||||
uses: EndBug/add-and-commit@v9
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
author_name: ${{ github.actor }}
|
||||
author_email: ${{ github.actor }}@users.noreply.github.com
|
||||
message: 'Update Browserslist'
|
||||
fetch-depth: 0
|
||||
- name: Configure git
|
||||
run: |
|
||||
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'
|
||||
|
||||
Vendored
+15
-1
@@ -1,6 +1,20 @@
|
||||
{
|
||||
"editor.formatOnSave": true,
|
||||
"cSpell.words": ["asyncable", "mindmap", "pako", "Serde", "serdes"],
|
||||
"cSpell.words": [
|
||||
"Browserslist",
|
||||
"KROKI",
|
||||
"Serde",
|
||||
"asyncable",
|
||||
"corg",
|
||||
"cssnano",
|
||||
"daisyui",
|
||||
"esserializer",
|
||||
"localstorage",
|
||||
"mindmap",
|
||||
"pako",
|
||||
"serdes",
|
||||
"tailwindcss"
|
||||
],
|
||||
"vitest.commandLine": "yarn test:unit",
|
||||
"vitest.enable": true,
|
||||
"testing.autoRun.mode": "rerun",
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
# Stop : press ctrl + c
|
||||
# or
|
||||
# docker stop mermaid-live-editor
|
||||
FROM node:18.12.0 as mermaid-live-editor-builder
|
||||
FROM node:18.14.0 as mermaid-live-editor-builder
|
||||
COPY --chown=node:node . /home
|
||||
WORKDIR /home
|
||||
RUN yarn install
|
||||
|
||||
@@ -47,17 +47,20 @@ Then open http://localhost:8000
|
||||
|
||||
## Setup
|
||||
|
||||
[Volta](https://volta.sh) is used for managing node and yarn versions.
|
||||
Below link will help you making a copy of the repository in your local system.
|
||||
|
||||
This project is set up using [Yarn](https://classic.yarnpkg.com/en/docs/getting-started):
|
||||
https://docs.github.com/en/get-started/quickstart/fork-a-repo
|
||||
|
||||
```
|
||||
yarn install
|
||||
```
|
||||
## Requirements
|
||||
|
||||
- [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
|
||||
|
||||
```
|
||||
```sh
|
||||
yarn install
|
||||
yarn dev -- --open
|
||||
```
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { verifyFileSize } from './util';
|
||||
import { verifyFileSizeGreaterThan } from './util';
|
||||
describe('Check actions', () => {
|
||||
beforeEach(() => {
|
||||
cy.clearLocalStorage();
|
||||
cy.visit('/edit');
|
||||
cy.contains('Actions').click();
|
||||
});
|
||||
|
||||
it('should update markdown code', () => {
|
||||
@@ -18,7 +19,7 @@ describe('Check actions', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('should load gists from URL', () => {
|
||||
it.skip('should load gists from URL', () => {
|
||||
cy.get('#gist').type('https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a');
|
||||
cy.contains('Load Gist').click();
|
||||
cy.contains('Go shopping!!');
|
||||
@@ -28,20 +29,20 @@ describe('Check actions', () => {
|
||||
cy.clock(new Date(2022, 0, 1).getTime());
|
||||
|
||||
cy.get(`#downloadPNG`).click();
|
||||
verifyFileSize('diagram', 'png', 21_000);
|
||||
verifyFileSizeGreaterThan('diagram', 'png', 35_000);
|
||||
|
||||
cy.get(`#downloadSVG`).click();
|
||||
verifyFileSize('diagram', 'svg', 10_000);
|
||||
verifyFileSizeGreaterThan('diagram', 'svg', 10_000);
|
||||
|
||||
// Verify downloaded file is different for different diagrams
|
||||
cy.contains('Sample Diagrams').click();
|
||||
cy.contains('ER').click();
|
||||
|
||||
cy.get(`#downloadPNG`).click();
|
||||
verifyFileSize('diagram', 'png', 46_000);
|
||||
verifyFileSizeGreaterThan('diagram', 'png', 40_000);
|
||||
|
||||
cy.get(`#downloadSVG`).click();
|
||||
verifyFileSize('diagram', 'svg', 12_000);
|
||||
verifyFileSizeGreaterThan('diagram', 'svg', 11_000);
|
||||
|
||||
cy.clock().invoke('restore');
|
||||
});
|
||||
|
||||
@@ -49,7 +49,7 @@ describe('Auto sync tests', () => {
|
||||
});
|
||||
|
||||
it('supports commenting code out/in', () => {
|
||||
getEditor().type(`{uparrow}${cmd}/`);
|
||||
getEditor({ bottom: true, newline: false }).type(`{uparrow}${cmd}/`);
|
||||
cy.get('#view').contains('Car').should('not.exist');
|
||||
|
||||
getEditor().type(`{uparrow}${cmd}/`);
|
||||
@@ -69,6 +69,14 @@ describe('Auto sync tests', () => {
|
||||
)
|
||||
.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', () => {
|
||||
|
||||
@@ -6,7 +6,6 @@ describe('Save History', () => {
|
||||
cy.clearLocalStorage();
|
||||
cy.visit('/edit');
|
||||
|
||||
cy.contains('Actions').click();
|
||||
cy.contains('History').click();
|
||||
});
|
||||
|
||||
@@ -24,7 +23,6 @@ describe('Save History', () => {
|
||||
'[{"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.contains('Actions').click();
|
||||
cy.contains('History').click();
|
||||
cy.get('#historyList').find('li').should('have.length', 2);
|
||||
cy.get('#historyList').find('No items in History').should('not.exist');
|
||||
@@ -84,15 +82,15 @@ describe('Save History', () => {
|
||||
// TODO: Fix #639
|
||||
xit('should auto save history', () => {
|
||||
getEditor().type(' C --> HistoryTest');
|
||||
cy.tick(70000);
|
||||
cy.tick(70_000);
|
||||
cy.contains('Timeline').click();
|
||||
cy.get('#historyList').find('li').should('have.length', 1);
|
||||
cy.get('#editor').type('ing');
|
||||
cy.tick(70000);
|
||||
cy.tick(70_000);
|
||||
cy.get('#historyList').find('li').should('have.length', 2);
|
||||
for (let i = 0; i < 31; i++) {
|
||||
cy.get('#editor').type('.');
|
||||
cy.tick(70000);
|
||||
cy.tick(70_000);
|
||||
}
|
||||
cy.get('#historyList').find('li').should('have.length', 30);
|
||||
});
|
||||
|
||||
@@ -94,6 +94,17 @@ describe('Site Loads', () => {
|
||||
cy.contains('Please Click here to Raise an issue in github.');
|
||||
});
|
||||
|
||||
it('should load compressed URL', () => {
|
||||
cy.visit(
|
||||
'/edit#pako:eNpVkM2KwkAQhF-l6dMK5gVyEDRxvYi7sF6WjIcm0zqDzg_jBJEk725Hd2G3Tw31VVFUj23QjCWeEkUD-1p5kFs2O77BN1M6QFEshg1ncMHzfYDV2ybA1YQYrT_NXvhqgqDqtxPGkI315_ElVU__h-cB6mZLMYd4-Kvsb2GAdWM_jcT_V0xicb03RyqPVLSUoJI-OEfHyZHV0rqfDAqzYccKS3k1pbNC5Ufhuqgp81rbHBJKxuXKc6Quh6-7b7HMqeNfqLYkC7gfanwAlW1ZvQ'
|
||||
);
|
||||
cy.contains('New Year');
|
||||
cy.visit(
|
||||
'/edit#pako:eNptkU1PwzAMhv9K5BOI9Q9EXBDbJA477YYqITcxndV8QD40weh_Jy1rGR0-OY_tV2_sEyivCSQogzGuGduAtnaixINji0bcf1WVWGfVXdMtx8M1faYm4B8sxR27JLClJd6nwK4VLTlN4bI4jMQd2pLe3C4KFhNNcLQ92jv9ADGLNoTdozc-zIV4ZDsNlud7RtVN7_5Sb_jYrFcN3iN_0pPbEqUZK3QbTP_Ojyv4NdR4bwTHlyMbPcOQ3WJ2CliBpWCRdbnLqFJDOpClGmRJNYauhtr1pS-_6bKMjebkA8hXNJFWgDn5_YdTIFPINDWdb3vu6r8BaWOZRQ'
|
||||
);
|
||||
cy.contains('Animal');
|
||||
});
|
||||
|
||||
it('should load uncompressed URL', () => {
|
||||
cy.visit(
|
||||
'/edit/#eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW05ldyBZZWFyXSAtLT58R2V0IG1vbmV5fCBCKEdvIHNob3BwaW5nKVxuICAgIEIgLS0-IEN7TGV0IG1lIHRoaW5rfVxuICAgIEMgLS0-fE9uZXwgRFtMYXB0b3BdXG4gICAgQyAtLT58VHdvfCBFW2lQaG9uZV1cbiAgICBDIC0tPnxUaHJlZXwgRltmYTpmYS1jYXIgQ2FyXSIsIm1lcm1haWQiOiJ7XG4gIFwidGhlbWVcIjogXCJkZWZhdWx0XCJcbn0iLCJ1cGRhdGVFZGl0b3IiOmZhbHNlLCJhdXRvU3luYyI6dHJ1ZSwidXBkYXRlRGlhZ3JhbSI6ZmFsc2V9'
|
||||
@@ -108,15 +119,4 @@ describe('Site Loads', () => {
|
||||
);
|
||||
cy.contains('New Year');
|
||||
});
|
||||
|
||||
it('should load compressed URL', () => {
|
||||
cy.visit(
|
||||
'/edit#pako:eNpVkM2KwkAQhF-l6dMK5gVyEDRxvYi7sF6WjIcm0zqDzg_jBJEk725Hd2G3Tw31VVFUj23QjCWeEkUD-1p5kFs2O77BN1M6QFEshg1ncMHzfYDV2ybA1YQYrT_NXvhqgqDqtxPGkI315_ElVU__h-cB6mZLMYd4-Kvsb2GAdWM_jcT_V0xicb03RyqPVLSUoJI-OEfHyZHV0rqfDAqzYccKS3k1pbNC5Ufhuqgp81rbHBJKxuXKc6Quh6-7b7HMqeNfqLYkC7gfanwAlW1ZvQ'
|
||||
);
|
||||
cy.contains('New Year');
|
||||
cy.visit(
|
||||
'/edit#pako:eNptkU1PwzAMhv9K5BOI9Q9EXBDbJA477YYqITcxndV8QD40weh_Jy1rGR0-OY_tV2_sEyivCSQogzGuGduAtnaixINji0bcf1WVWGfVXdMtx8M1faYm4B8sxR27JLClJd6nwK4VLTlN4bI4jMQd2pLe3C4KFhNNcLQ92jv9ADGLNoTdozc-zIV4ZDsNlud7RtVN7_5Sb_jYrFcN3iN_0pPbEqUZK3QbTP_Ojyv4NdR4bwTHlyMbPcOQ3WJ2CliBpWCRdbnLqFJDOpClGmRJNYauhtr1pS-_6bKMjebkA8hXNJFWgDn5_YdTIFPINDWdb3vu6r8BaWOZRQ'
|
||||
);
|
||||
cy.contains('Animal');
|
||||
});
|
||||
});
|
||||
|
||||
+9
-4
@@ -10,17 +10,21 @@ export const getEditor = ({ bottom = true, newline = false } = {}) =>
|
||||
|
||||
const downloadsFolder = Cypress.config('downloadsFolder');
|
||||
|
||||
export const verifyFileSize = (
|
||||
export const verifyFileSizeGreaterThan = (
|
||||
fileType: 'history' | 'diagram',
|
||||
extension: string,
|
||||
size: number
|
||||
) => {
|
||||
const fileName = `mermaid-${fileType}-2022-01-01-000000.${extension}`;
|
||||
const filePath = `${downloadsFolder}/${fileName}`;
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
||||
cy.verifyDownload(fileName);
|
||||
cy.readFile(filePath, null, {
|
||||
log: false
|
||||
}).then((buffer) => expect((buffer as ArrayBuffer).byteLength).to.be.gt(size));
|
||||
}).then((buffer: ArrayBuffer) => {
|
||||
expect(buffer.byteLength).to.be.gt(size);
|
||||
expect(buffer.byteLength).to.be.lt(size * 1.3);
|
||||
});
|
||||
cy.task('deleteFile', filePath);
|
||||
};
|
||||
|
||||
@@ -31,11 +35,12 @@ export const verifyFileSnapshot = (
|
||||
) => {
|
||||
const fileName = `mermaid-${fileType}-2022-01-01-000000.${extension}`;
|
||||
const filePath = `${downloadsFolder}/${fileName}`;
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
||||
cy.verifyDownload(fileName);
|
||||
cy.readFile(filePath, null, {
|
||||
log: false
|
||||
}).then((buffer) =>
|
||||
expect(new TextDecoder('utf-8').decode(buffer as ArrayBuffer)).to.contain(content)
|
||||
}).then((buffer: ArrayBuffer) =>
|
||||
expect(new TextDecoder('utf8').decode(buffer)).to.contain(content)
|
||||
);
|
||||
cy.task('deleteFile', filePath);
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
module.exports = {
|
||||
"Site Loads": {
|
||||
"Check Home page load": {
|
||||
"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}"
|
||||
"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}"
|
||||
},
|
||||
"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}"
|
||||
@@ -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\"}}}"
|
||||
}
|
||||
},
|
||||
"__version": "10.10.0",
|
||||
"__version": "11.2.0",
|
||||
"Auto sync tests": {
|
||||
"should dim diagram when code is edited": {
|
||||
"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}"
|
||||
"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}"
|
||||
},
|
||||
"should not dim diagram when code is in sync": {
|
||||
"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}"
|
||||
"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}"
|
||||
}
|
||||
},
|
||||
"Test themes": {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"allowJs": true,
|
||||
"types": ["cypress", "cypress-localstorage-commands", "cy-verify-downloads"]
|
||||
"types": ["cypress", "cypress-localstorage-commands", "cy-verify-downloads", "node"]
|
||||
},
|
||||
"include": ["**/*.ts"]
|
||||
}
|
||||
|
||||
+37
-35
@@ -23,57 +23,59 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@cypress/snapshot": "2.1.7",
|
||||
"@sveltejs/adapter-static": "1.0.0-next.46",
|
||||
"@sveltejs/kit": "1.0.0-next.522",
|
||||
"@sveltejs/adapter-static": "1.0.6",
|
||||
"@sveltejs/kit": "1.5.0",
|
||||
"@testing-library/jest-dom": "5.16.5",
|
||||
"@testing-library/svelte": "3.2.2",
|
||||
"@types/pako": "2.0.0",
|
||||
"@types/uuid": "8.3.4",
|
||||
"@typescript-eslint/eslint-plugin": "5.42.0",
|
||||
"@typescript-eslint/parser": "5.42.0",
|
||||
"@vitest/ui": "0.25.1",
|
||||
"autoprefixer": "10.4.12",
|
||||
"@typescript-eslint/eslint-plugin": "5.51.0",
|
||||
"@typescript-eslint/parser": "5.51.0",
|
||||
"@vitest/ui": "^0.28.0",
|
||||
"autoprefixer": "^10.4.13",
|
||||
"c8": "7.12.0",
|
||||
"chai": "4.3.6",
|
||||
"cssnano": "5.1.13",
|
||||
"chai": "^4.3.7",
|
||||
"cssnano": "^5.1.14",
|
||||
"cy-verify-downloads": "0.1.11",
|
||||
"cypress": "11.0.1",
|
||||
"cypress-localstorage-commands": "2.2.1",
|
||||
"eslint": "8.27.0",
|
||||
"eslint-config-prettier": "8.5.0",
|
||||
"cypress": "11.2.0",
|
||||
"cypress-localstorage-commands": "2.2.2",
|
||||
"eslint": "8.33.0",
|
||||
"eslint-config-prettier": "8.6.0",
|
||||
"eslint-plugin-cypress": "2.12.1",
|
||||
"eslint-plugin-es": "4.1.0",
|
||||
"eslint-plugin-no-only-tests": "^3.1.0",
|
||||
"eslint-plugin-postcss-modules": "2.0.0",
|
||||
"eslint-plugin-svelte3": "4.0.0",
|
||||
"eslint-plugin-tailwindcss": "3.6.2",
|
||||
"eslint-plugin-vitest": "0.0.11",
|
||||
"esserializer": "1.3.2",
|
||||
"husky": "8.0.1",
|
||||
"jsdom": "20.0.1",
|
||||
"lint-staged": "13.0.3",
|
||||
"node-html-parser": "6.1.1",
|
||||
"postcss": "8.4.18",
|
||||
"eslint-plugin-tailwindcss": "3.8.3",
|
||||
"eslint-plugin-unicorn": "^45.0.0",
|
||||
"eslint-plugin-vitest": "^0.0.32",
|
||||
"esserializer": "1.3.10",
|
||||
"font-awesome": "^4.7.0",
|
||||
"husky": "^8.0.2",
|
||||
"jsdom": "20.0.3",
|
||||
"lint-staged": "13.1.1",
|
||||
"node-html-parser": "^6.1.4",
|
||||
"postcss": "^8.4.19",
|
||||
"postcss-load-config": "4.0.1",
|
||||
"prettier": "2.7.1",
|
||||
"prettier-plugin-svelte": "2.8.0",
|
||||
"svelte": "3.53.1",
|
||||
"prettier": "2.8.3",
|
||||
"prettier-plugin-svelte": "^2.8.1",
|
||||
"svelte": "3.55.1",
|
||||
"svelte-preprocess": "4.10.7",
|
||||
"tailwindcss": "3.2.1",
|
||||
"tslib": "2.4.0",
|
||||
"typescript": "4.8.4",
|
||||
"vite": "3.2.2",
|
||||
"vitest": "0.25.1"
|
||||
"tailwindcss": "^3.2.4",
|
||||
"tslib": "^2.4.1",
|
||||
"typescript": "4.9.5",
|
||||
"vite": "^4.0.1",
|
||||
"vitest": "^0.28.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@mermaid-js/mermaid-mindmap": "9.2.2",
|
||||
"analytics": "0.8.1",
|
||||
"analytics-plugin-plausible": "0.0.6",
|
||||
"daisyui": "2.39.1",
|
||||
"js-base64": "3.7.2",
|
||||
"mermaid": "9.2.2",
|
||||
"moment": "2.29.4",
|
||||
"daisyui": "2.50.0",
|
||||
"dayjs": "^1.11.7",
|
||||
"js-base64": "3.7.4",
|
||||
"mermaid": "10.0.2",
|
||||
"monaco-editor": "0.34.1",
|
||||
"monaco-mermaid": "1.0.6",
|
||||
"monaco-mermaid": "1.0.8",
|
||||
"pako": "2.1.0",
|
||||
"random-word-slugs": "0.1.6",
|
||||
"svg-pan-zoom": "3.6.1",
|
||||
@@ -86,7 +88,7 @@
|
||||
]
|
||||
},
|
||||
"volta": {
|
||||
"node": "18.12.0",
|
||||
"node": "18.14.0",
|
||||
"yarn": "1.22.19"
|
||||
},
|
||||
"engines": {
|
||||
|
||||
+2
-2
@@ -17,8 +17,8 @@
|
||||
<link rel="manifest" href="%sveltekit.assets%/manifest.json" />
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"
|
||||
integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A=="
|
||||
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
|
||||
integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w=="
|
||||
crossorigin="anonymous"
|
||||
referrerpolicy="no-referrer" />
|
||||
<link
|
||||
|
||||
Vendored
+5
-5
@@ -1,11 +1,11 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly MERMAID_RENDERER_URL: string;
|
||||
readonly MERMAID_KROKI_RENDERER_URL: string;
|
||||
readonly MERMAID_CDN_URL: string;
|
||||
readonly MERMAID_BASE_URL: string;
|
||||
readonly MERMAID_LOCAL: boolean;
|
||||
readonly MERMAID_RENDERER_URL?: string;
|
||||
readonly MERMAID_KROKI_RENDERER_URL?: string;
|
||||
readonly MERMAID_CDN_URL?: string;
|
||||
readonly MERMAID_BASE_URL?: string;
|
||||
readonly MERMAID_LOCAL?: boolean;
|
||||
// more env variables...
|
||||
}
|
||||
|
||||
|
||||
Vendored
+2
-1
@@ -9,7 +9,8 @@ declare global {
|
||||
namespace jest {
|
||||
interface Matchers<R = void>
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
// @ts-expect-error
|
||||
// eslint-disable-next-line no-undef
|
||||
extends TestingLibraryMatchers<typeof expect.stringContaining, R> {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,17 +6,17 @@
|
||||
import { stateStore } from '$lib/util/state';
|
||||
import { logEvent } from '$lib/util/stats';
|
||||
import { toBase64 } from 'js-base64';
|
||||
import moment from 'moment';
|
||||
import dayjs from 'dayjs';
|
||||
const { krokiRendererUrl, rendererUrl } = env;
|
||||
|
||||
type Exporter = (context: CanvasRenderingContext2D, image: HTMLImageElement) => () => void;
|
||||
|
||||
const getFileName = (ext: string) =>
|
||||
`mermaid-diagram-${moment().format('YYYY-MM-DD-HHmmss')}.${ext}`;
|
||||
`mermaid-diagram-${dayjs().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
|
||||
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();
|
||||
}
|
||||
@@ -28,7 +28,10 @@
|
||||
|
||||
const exportImage = (event: Event, exporter: Exporter) => {
|
||||
const canvas: HTMLCanvasElement = document.createElement('canvas');
|
||||
const svg: HTMLElement = document.querySelector('#container svg');
|
||||
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;
|
||||
@@ -43,6 +46,9 @@
|
||||
}
|
||||
|
||||
const context = canvas.getContext('2d');
|
||||
if (!context) {
|
||||
throw new Error('context not found');
|
||||
}
|
||||
context.fillStyle = 'white';
|
||||
context.fillRect(0, 0, canvas.width, canvas.height);
|
||||
|
||||
@@ -56,12 +62,12 @@
|
||||
|
||||
const getSvgEl = () => {
|
||||
const svgEl: HTMLElement = document
|
||||
.querySelector('#container svg')
|
||||
.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'));
|
||||
.find((h) => h.includes('font-awesome'));
|
||||
if (fontAwesomeCdnUrl == null) {
|
||||
return svgEl;
|
||||
}
|
||||
@@ -99,10 +105,10 @@
|
||||
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
|
||||
if (!blob) {
|
||||
throw new Error('blob is empty');
|
||||
}
|
||||
void navigator.clipboard.write([
|
||||
/* eslint-disable no-undef */
|
||||
// @ts-ignore: https://github.com/microsoft/TypeScript/issues/43821
|
||||
new ClipboardItem({
|
||||
[blob.type]: blob
|
||||
})
|
||||
@@ -142,7 +148,7 @@
|
||||
let gistURL = '';
|
||||
stateStore.subscribe(({ loader }) => {
|
||||
if (loader?.type === 'gist') {
|
||||
// @ts-ignore Gist will have url
|
||||
// @ts-expect-error Gist will have url
|
||||
gistURL = loader.config.url;
|
||||
}
|
||||
});
|
||||
@@ -166,8 +172,7 @@
|
||||
if (browser && ['mermaid.live', 'netlify'].some((path) => window.location.host.includes(path))) {
|
||||
isNetlify = true;
|
||||
}
|
||||
stateStore.subscribe(async (state) => {
|
||||
const { code, serialized } = await state;
|
||||
stateStore.subscribe(({ code, serialized }) => {
|
||||
iUrl = `${rendererUrl}/img/${serialized}?type=png`;
|
||||
svgUrl = `${rendererUrl}/svg/${serialized}`;
|
||||
krokiUrl = `${krokiRendererUrl}/mermaid/svg/${pakoSerde.serialize(code)}`;
|
||||
@@ -175,7 +180,7 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
<Card title="Actions" isOpen={true}>
|
||||
<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}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
export let isCloseable = true;
|
||||
export let isOpen = true;
|
||||
export let tabs: Tab[] = [];
|
||||
export let activeTabID: string = '';
|
||||
export let activeTabID = '';
|
||||
export let title: string;
|
||||
$: isOpen = isCloseable ? isOpen : true;
|
||||
$: isTabsShown = isOpen && tabs.length > 0;
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
// 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>"`;
|
||||
@@ -10,8 +10,8 @@ describe('card.svelte', () => {
|
||||
const { container } = render(Card, {
|
||||
title: 'TabTest',
|
||||
tabs: [
|
||||
{ id: 't1', title: 'title1' },
|
||||
{ id: 't2', title: 'title2' }
|
||||
{ id: 't1', title: 'title1', icon: 'fab fa-git-alt' },
|
||||
{ id: 't2', title: 'title2', icon: 'far fa-bookmark' }
|
||||
]
|
||||
});
|
||||
expect(container).toBeTruthy();
|
||||
@@ -19,6 +19,5 @@ describe('card.svelte', () => {
|
||||
expect(container).toHaveTextContent('title1');
|
||||
expect(container).toHaveTextContent('title2');
|
||||
expect(container).not.toHaveTextContent('title3');
|
||||
expect(container.innerHTML).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,9 +8,9 @@
|
||||
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 divEl: HTMLDivElement | undefined = undefined;
|
||||
let editor: monaco.editor.IStandaloneCodeEditor | undefined;
|
||||
let Monaco: typeof monaco | undefined;
|
||||
let editorOptions: monaco.editor.IStandaloneEditorConstructionOptions = {
|
||||
minimap: {
|
||||
enabled: false
|
||||
@@ -21,25 +21,32 @@
|
||||
let text = '';
|
||||
|
||||
stateStore.subscribe(({ errorMarkers, editorMode, code, mermaid }) => {
|
||||
console.log('editor store subscription', { code, mermaid });
|
||||
if (!editor) return;
|
||||
// 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);
|
||||
// console.log('updating editor text', newText);
|
||||
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);
|
||||
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(editor.getModel(), 'mermaid', errorMarkers);
|
||||
Monaco.editor.setModelMarkers(model, 'mermaid', errorMarkers);
|
||||
});
|
||||
|
||||
themeStore.subscribe(({ isDark }) => {
|
||||
@@ -47,7 +54,7 @@
|
||||
});
|
||||
|
||||
const handleUpdate = (text: string, mode: EditorMode) => {
|
||||
console.log('editor HandleUpdate', { text, mode });
|
||||
// console.log('editor HandleUpdate', { text, mode });
|
||||
if (mode === 'code') {
|
||||
updateCode(text);
|
||||
} else {
|
||||
@@ -60,7 +67,7 @@
|
||||
// errorDebug();
|
||||
let i = 0;
|
||||
while (i++ < 500) {
|
||||
// @ts-ignore : This is a hack to handle a svelte-kit error when importing monaco.
|
||||
// @ts-expect-error : This is a hack to handle a svelte-kit error when importing monaco.
|
||||
Monaco = window.monaco;
|
||||
if (Monaco !== undefined) {
|
||||
return;
|
||||
@@ -72,13 +79,20 @@
|
||||
|
||||
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 (text === newText || isFlush) {
|
||||
const newText = editor?.getValue();
|
||||
// console.log('editor onDidChangeModelContent', { text, newText, isFlush, changes });
|
||||
if (!newText || text === newText || isFlush) {
|
||||
return;
|
||||
}
|
||||
text = newText;
|
||||
@@ -95,19 +109,21 @@
|
||||
});
|
||||
}
|
||||
});
|
||||
Monaco?.editor.setTheme($themeStore.isDark ? 'mermaid-dark' : 'mermaid');
|
||||
Monaco.editor.setTheme($themeStore.isDark ? 'mermaid-dark' : 'mermaid');
|
||||
const resizeObserver = new ResizeObserver((entries) => {
|
||||
editor.layout({
|
||||
editor!.layout({
|
||||
height: entries[0].contentRect.height,
|
||||
width: entries[0].contentRect.width
|
||||
});
|
||||
});
|
||||
|
||||
resizeObserver.observe(divEl.parentElement);
|
||||
console.log(`editor mounted`);
|
||||
if (divEl.parentElement) {
|
||||
resizeObserver.observe(divEl.parentElement);
|
||||
}
|
||||
// console.log(`editor mounted`);
|
||||
return () => {
|
||||
console.log(`editor disposed`);
|
||||
editor.dispose();
|
||||
// console.log(`editor disposed`);
|
||||
editor?.dispose();
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -13,10 +13,13 @@
|
||||
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 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>) => {
|
||||
@@ -41,7 +44,7 @@
|
||||
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.download = `mermaid-history-${dayjs().format('YYYY-MM-DD-HHmmss')}.json`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
logEvent('history', {
|
||||
@@ -60,7 +63,7 @@
|
||||
}
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
const data = JSON.parse(e.target.result as string);
|
||||
const data: HistoryEntry[] = JSON.parse(e.target.result as string);
|
||||
restoreHistory(data);
|
||||
};
|
||||
reader.readAsText(file);
|
||||
@@ -95,7 +98,7 @@
|
||||
|
||||
const relativeTime = (time: number) => {
|
||||
const t = new Date(time);
|
||||
return `${new Date(t).toLocaleString()} (${moment(t).fromNow()})`;
|
||||
return `${new Date(t).toLocaleString()} (${dayjs(t).fromNow()})`;
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
|
||||
@@ -17,28 +17,30 @@ describe('history', () => {
|
||||
|
||||
addHistoryEntry({
|
||||
state: defaultState,
|
||||
time: 12345,
|
||||
time: 12_345,
|
||||
type: 'manual'
|
||||
});
|
||||
|
||||
const [manualEntry]: HistoryEntry[] = JSON.parse(
|
||||
window.localStorage.getItem('manualHistoryStore')
|
||||
);
|
||||
const [manualEntry] = JSON.parse(
|
||||
window.localStorage.getItem('manualHistoryStore') ?? '[]'
|
||||
) as HistoryEntry[];
|
||||
|
||||
expect(manualEntry.time).toBe(12345);
|
||||
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: 54321,
|
||||
time: 54_321,
|
||||
type: 'auto'
|
||||
});
|
||||
|
||||
const [autoEntry]: HistoryEntry[] = JSON.parse(window.localStorage.getItem('autoHistoryStore'));
|
||||
const [autoEntry] = JSON.parse(
|
||||
window.localStorage.getItem('autoHistoryStore') ?? '[]'
|
||||
) as HistoryEntry[];
|
||||
|
||||
expect(autoEntry.time).toBe(54321);
|
||||
expect(autoEntry.time).toBe(54_321);
|
||||
expect(autoEntry.type).toBe('auto');
|
||||
expect(autoEntry.name).not.toBeNull();
|
||||
expect(autoEntry.state).not.toBeNull();
|
||||
@@ -54,12 +56,12 @@ describe('history', () => {
|
||||
it('should clear history entries', () => {
|
||||
addHistoryEntry({
|
||||
state: defaultState,
|
||||
time: 12345,
|
||||
time: 12_345,
|
||||
type: 'manual'
|
||||
});
|
||||
addHistoryEntry({
|
||||
state: { ...defaultState, code: 'graph TD\\n A[Christmas] -->|Get money| B(Go shopping)' },
|
||||
time: 123456,
|
||||
time: 123_456,
|
||||
type: 'manual'
|
||||
});
|
||||
|
||||
@@ -74,12 +76,12 @@ describe('history', () => {
|
||||
historyModeStore.set('auto');
|
||||
addHistoryEntry({
|
||||
state: defaultState,
|
||||
time: 54321,
|
||||
time: 54_321,
|
||||
type: 'auto'
|
||||
});
|
||||
addHistoryEntry({
|
||||
state: { ...defaultState, code: 'graph TD\\n A[Christmas] -->|Get money| B(Go shopping)' },
|
||||
time: 654321,
|
||||
time: 654_321,
|
||||
type: 'auto'
|
||||
});
|
||||
expect(get(historyStore).length).toBe(2);
|
||||
@@ -101,19 +103,23 @@ describe('history migration', () => {
|
||||
'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')
|
||||
);
|
||||
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'));
|
||||
autoHistoryStore = JSON.parse(window.localStorage.getItem('autoHistoryStore'));
|
||||
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);
|
||||
});
|
||||
|
||||
@@ -26,19 +26,27 @@ const manualHistoryStore: Writable<HistoryEntry[]> = persist(
|
||||
'manualHistoryStore'
|
||||
);
|
||||
|
||||
export const loaderHistoryStore: Writable<HistoryEntry[]> = writable([] as HistoryEntry[]);
|
||||
export const loaderHistoryStore: Writable<HistoryEntry[]> = writable([]);
|
||||
|
||||
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);
|
||||
switch (historyMode) {
|
||||
case 'auto': {
|
||||
set(autoHistories);
|
||||
break;
|
||||
}
|
||||
case 'manual': {
|
||||
set(manualHistories);
|
||||
break;
|
||||
}
|
||||
case 'loader': {
|
||||
set(loadedHistories);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
set(autoHistories);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -90,7 +98,7 @@ export const getPreviousState = (auto: boolean): string => {
|
||||
};
|
||||
|
||||
export const restoreHistory = (data: HistoryEntry[]) => {
|
||||
const entries = data.filter(validateEntry);
|
||||
const entries = data.filter((element) => validateEntry(element));
|
||||
const invalidEntryCount = data.length - entries.length;
|
||||
if (invalidEntryCount > 0) {
|
||||
console.error(`${invalidEntryCount} invalid history entries were removed.`);
|
||||
@@ -122,20 +130,23 @@ export const restoreHistory = (data: HistoryEntry[]) => {
|
||||
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 => {
|
||||
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 => {
|
||||
// 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;
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script context="module">
|
||||
<script context="module" lang="ts">
|
||||
import { version } from 'mermaid/package.json';
|
||||
import { analytics } from '$lib/util/stats';
|
||||
analytics?.track('version', {
|
||||
void analytics?.track('version', {
|
||||
mermaidVersion: version
|
||||
});
|
||||
</script>
|
||||
@@ -17,11 +17,11 @@
|
||||
const links: Link[] = [
|
||||
{
|
||||
title: 'Documentation',
|
||||
href: 'https://mermaid-js.github.io/mermaid/#/n00b-gettingStarted'
|
||||
href: 'https://mermaid-js.github.io/mermaid/intro/n00b-gettingStarted.html'
|
||||
},
|
||||
{
|
||||
title: 'Tutorial',
|
||||
href: 'https://github.com/mermaid-js/mermaid/blob/develop/docs/Tutorials.md'
|
||||
href: 'https://mermaid-js.github.io/mermaid/config/Tutorials.html'
|
||||
},
|
||||
{
|
||||
title: 'Mermaid',
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import { logEvent } from '$lib/util/stats';
|
||||
|
||||
const samples = {
|
||||
Flow: `graph TD
|
||||
Flow: `flowchart TD
|
||||
A[Christmas] -->|Get money| B(Go shopping)
|
||||
B --> C{Let me think}
|
||||
C -->|One| D[Laptop]
|
||||
@@ -104,7 +104,8 @@
|
||||
Mermaid`
|
||||
};
|
||||
|
||||
const loadSampleDiagram = (diagramType: string): void => {
|
||||
type SampleTypes = keyof typeof samples;
|
||||
const loadSampleDiagram = (diagramType: SampleTypes): void => {
|
||||
updateCode(samples[diagramType], {
|
||||
updateDiagram: true,
|
||||
resetPanZoom: true
|
||||
@@ -113,8 +114,8 @@
|
||||
};
|
||||
|
||||
// Adding in this array will add an icon to the preset menu
|
||||
const newDiagrams: Array<keyof typeof samples> = ['Mindmap'];
|
||||
const diagramOrder: Array<keyof typeof samples> = [
|
||||
const newDiagrams: SampleTypes[] = ['Mindmap'];
|
||||
const diagramOrder: SampleTypes[] = [
|
||||
'Sequence',
|
||||
'Flow',
|
||||
'Class',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<script>
|
||||
<script lang="ts">
|
||||
import { setTheme, themeStore } from '$lib/util/theme';
|
||||
|
||||
const themes = [
|
||||
@@ -52,7 +52,7 @@
|
||||
<!-- 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' : ''}>
|
||||
<li class:bordered={$themeStore.theme !== undefined && theme.includes($themeStore.theme)}>
|
||||
<span
|
||||
class="btn btn-ghost justify-start"
|
||||
on:click={() => setTheme(theme)}
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
import panzoom from 'svg-pan-zoom';
|
||||
import type { State, ValidatedState } from '$lib/types';
|
||||
import { logEvent } from '$lib/util/stats';
|
||||
import { AsyncQueue, cmdKey } from '$lib/util/util';
|
||||
import { cmdKey } from '$lib/util/util';
|
||||
import { render as renderDiagram } from '$lib/util/mermaid';
|
||||
import type { MermaidConfig } from 'mermaid';
|
||||
|
||||
let code = '';
|
||||
let config = '';
|
||||
@@ -16,9 +17,12 @@
|
||||
let hide = false;
|
||||
let manualUpdate = true;
|
||||
let panZoomEnabled = $stateStore.panZoom;
|
||||
let pzoom: SvgPanZoom.Instance;
|
||||
let pzoom: typeof panzoom | undefined;
|
||||
|
||||
const handlePanZoomChange = () => {
|
||||
if (!pzoom) {
|
||||
return;
|
||||
}
|
||||
const pan = pzoom.getPan();
|
||||
const zoom = pzoom.getZoom();
|
||||
updateCodeStore({ pan, zoom });
|
||||
@@ -32,8 +36,11 @@
|
||||
hide = true;
|
||||
pzoom?.destroy();
|
||||
pzoom = undefined;
|
||||
Promise.resolve().then(() => {
|
||||
void Promise.resolve().then(() => {
|
||||
const graphDiv = document.getElementById('graph-div');
|
||||
if (!graphDiv) {
|
||||
return;
|
||||
}
|
||||
pzoom = panzoom(graphDiv, {
|
||||
onPan: handlePanZoomChange,
|
||||
onZoom: handlePanZoomChange,
|
||||
@@ -70,27 +77,30 @@
|
||||
code = state.code;
|
||||
config = state.mermaid;
|
||||
panZoomEnabled = state.panZoom;
|
||||
const scroll = view.parentElement.scrollTop;
|
||||
const scroll = view.parentElement!.scrollTop;
|
||||
delete container.dataset.processed;
|
||||
await renderDiagram(
|
||||
Object.assign({}, JSON.parse(state.mermaid)),
|
||||
const { svg, bindFunctions } = await renderDiagram(
|
||||
Object.assign({}, JSON.parse(state.mermaid)) as MermaidConfig,
|
||||
code,
|
||||
'graph-div',
|
||||
(svgCode, bindFunctions) => {
|
||||
if (svgCode.length > 0) {
|
||||
handlePanZoom(state);
|
||||
container.innerHTML = svgCode;
|
||||
// console.log(container.innerHTML);
|
||||
const graphDiv = document.getElementById('graph-div');
|
||||
graphDiv.setAttribute('height', '100%');
|
||||
graphDiv.style.maxWidth = '100%';
|
||||
if (bindFunctions) {
|
||||
bindFunctions(graphDiv);
|
||||
}
|
||||
}
|
||||
}
|
||||
'graph-div'
|
||||
);
|
||||
view.parentElement.scrollTop = scroll;
|
||||
|
||||
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;
|
||||
@@ -103,29 +113,27 @@
|
||||
}
|
||||
};
|
||||
|
||||
const q = new AsyncQueue(handleStateChange);
|
||||
|
||||
onMount(() => {
|
||||
stateStore.subscribe(async (state) => {
|
||||
await q.process(state);
|
||||
stateStore.subscribe((state) => {
|
||||
void handleStateChange(state);
|
||||
});
|
||||
window.addEventListener('resize', () => {
|
||||
if ($stateStore.panZoom && pzoom) {
|
||||
pzoom.resize();
|
||||
}
|
||||
});
|
||||
console.log('View mounted');
|
||||
// console.log('View mounted');
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if (error && $stateStore.error instanceof Error) || outOfSync}
|
||||
<div
|
||||
class="absolute w-full p-2 z-10 {error
|
||||
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}
|
||||
{$stateStore.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.
|
||||
|
||||
@@ -1,260 +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 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(async (state) => {
|
||||
const { code, serialized } = await state;
|
||||
iUrl = `${rendererUrl}/img/${serialized}?type=png`;
|
||||
svgUrl = `${rendererUrl}/svg/${serialized}`;
|
||||
krokiUrl = `${krokiRendererUrl}/mermaid/svg/${pakoSerde.serialize(code)}`;
|
||||
mdCode = `[](${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>
|
||||
@@ -1,3 +0,0 @@
|
||||
// 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>"`;
|
||||
@@ -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: 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>
|
||||
@@ -1,24 +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' },
|
||||
{ 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();
|
||||
});
|
||||
});
|
||||
@@ -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>
|
||||
@@ -1,192 +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 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>
|
||||
@@ -1,120 +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: 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);
|
||||
});
|
||||
});
|
||||
@@ -1,141 +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([] 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;
|
||||
};
|
||||
@@ -1,82 +0,0 @@
|
||||
<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,144 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { updateCode } from '$lib/util/state';
|
||||
import Card from '$lib/components/Card/Card.svelte';
|
||||
import { logEvent } from '$lib/util/stats';
|
||||
|
||||
const samples = {
|
||||
Flow: `graph TD
|
||||
A[Christmas] -->|Get money| B(Go shopping)
|
||||
B --> C{Let me think}
|
||||
C -->|One| D[Laptop]
|
||||
C -->|Two| E[iPhone]
|
||||
C -->|Three| F[fa:fa-car Car]`,
|
||||
Sequence: `sequenceDiagram
|
||||
Alice->>+John: Hello John, how are you?
|
||||
Alice->>+John: John, can you hear me?
|
||||
John-->>-Alice: Hi Alice, I can hear you!
|
||||
John-->>-Alice: I feel great!`,
|
||||
Class: `classDiagram
|
||||
Animal <|-- Duck
|
||||
Animal <|-- Fish
|
||||
Animal <|-- Zebra
|
||||
Animal : +int age
|
||||
Animal : +String gender
|
||||
Animal: +isMammal()
|
||||
Animal: +mate()
|
||||
class Duck{
|
||||
+String beakColor
|
||||
+swim()
|
||||
+quack()
|
||||
}
|
||||
class Fish{
|
||||
-int sizeInFeet
|
||||
-canEat()
|
||||
}
|
||||
class Zebra{
|
||||
+bool is_wild
|
||||
+run()
|
||||
}`,
|
||||
State: `stateDiagram-v2
|
||||
[*] --> Still
|
||||
Still --> [*]
|
||||
Still --> Moving
|
||||
Moving --> Still
|
||||
Moving --> Crash
|
||||
Crash --> [*]`,
|
||||
Gantt: `gantt
|
||||
title A Gantt Diagram
|
||||
dateFormat YYYY-MM-DD
|
||||
section Section
|
||||
A task :a1, 2014-01-01, 30d
|
||||
Another task :after a1 , 20d
|
||||
section Another
|
||||
Task in sec :2014-01-12 , 12d
|
||||
another task : 24d`,
|
||||
Pie: `pie title Pets adopted by volunteers
|
||||
"Dogs" : 386
|
||||
"Cats" : 85
|
||||
"Rats" : 15`,
|
||||
ER: `erDiagram
|
||||
CUSTOMER }|..|{ DELIVERY-ADDRESS : has
|
||||
CUSTOMER ||--o{ ORDER : places
|
||||
CUSTOMER ||--o{ INVOICE : "liable for"
|
||||
DELIVERY-ADDRESS ||--o{ ORDER : receives
|
||||
INVOICE ||--|{ ORDER : covers
|
||||
ORDER ||--|{ ORDER-ITEM : includes
|
||||
PRODUCT-CATEGORY ||--|{ PRODUCT : contains
|
||||
PRODUCT ||--o{ ORDER-ITEM : "ordered in"`,
|
||||
'User Journey': `journey
|
||||
title My working day
|
||||
section Go to work
|
||||
Make tea: 5: Me
|
||||
Go upstairs: 3: Me
|
||||
Do work: 1: Me, Cat
|
||||
section Go home
|
||||
Go downstairs: 5: Me
|
||||
Sit down: 3: Me`,
|
||||
Git: `gitGraph
|
||||
commit
|
||||
commit
|
||||
branch develop
|
||||
checkout develop
|
||||
commit
|
||||
commit
|
||||
checkout main
|
||||
merge develop
|
||||
commit
|
||||
commit`,
|
||||
Mindmap: `mindmap
|
||||
root((mindmap))
|
||||
Origins
|
||||
Long history
|
||||
::icon(fa fa-book)
|
||||
Popularisation
|
||||
British popular psychology author Tony Buzan
|
||||
Research
|
||||
On effectivness<br/>and features
|
||||
On Automatic creation
|
||||
Uses
|
||||
Creative techniques
|
||||
Strategic planning
|
||||
Argument mapping
|
||||
Tools
|
||||
Pen and paper
|
||||
Mermaid`
|
||||
};
|
||||
|
||||
const loadSampleDiagram = (diagramType: string): void => {
|
||||
updateCode(samples[diagramType], {
|
||||
updateDiagram: true,
|
||||
resetPanZoom: true
|
||||
});
|
||||
logEvent('loadSampleDiagram', { diagramType });
|
||||
};
|
||||
|
||||
// Adding in this array will add an icon to the preset menu
|
||||
const newDiagrams: Array<keyof typeof samples> = ['Mindmap'];
|
||||
const diagramOrder: Array<keyof typeof samples> = [
|
||||
'Sequence',
|
||||
'Flow',
|
||||
'Class',
|
||||
'State',
|
||||
'ER',
|
||||
'Gantt',
|
||||
'User Journey',
|
||||
'Git',
|
||||
'Pie',
|
||||
'Mindmap'
|
||||
];
|
||||
</script>
|
||||
|
||||
<Card title="Sample Diagrams" isOpen={false}>
|
||||
<div class="flex flex-wrap p-2 gap-2">
|
||||
{#each diagramOrder as sample}
|
||||
<button
|
||||
class="btn btn-sm btn-primary w-28 normal-case flex-grow"
|
||||
on:click={() => loadSampleDiagram(sample)}>
|
||||
{sample}
|
||||
{#if newDiagrams.includes(sample)}
|
||||
<span class="ml-2 fa fa-heart" />
|
||||
{/if}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</Card>
|
||||
@@ -1,64 +0,0 @@
|
||||
<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>
|
||||
@@ -1,157 +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 { AsyncQueue, cmdKey } from '$lib/util/util';
|
||||
import { render as renderDiagram } from '$lib/util/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: 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 = 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;
|
||||
await renderDiagram(
|
||||
Object.assign({}, JSON.parse(state.mermaid)),
|
||||
code,
|
||||
'graph-div',
|
||||
(svgCode, bindFunctions) => {
|
||||
if (svgCode.length > 0) {
|
||||
handlePanZoom(state);
|
||||
container.innerHTML = svgCode;
|
||||
// console.log(container.innerHTML);
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
const q = new AsyncQueue(handleStateChange);
|
||||
|
||||
onMount(() => {
|
||||
stateStore.subscribe(async (state) => {
|
||||
await q.process(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 {error
|
||||
? 'text-red-600'
|
||||
: 'text-yellow-600'} bg-base-100 bg-opacity-80 text-center"
|
||||
id="errorContainer">
|
||||
{#if error}
|
||||
{$stateStore.error}
|
||||
{: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>
|
||||
Vendored
+15
-13
@@ -1,11 +1,3 @@
|
||||
/**
|
||||
* Can be made globally available by placing this
|
||||
* inside `global.d.ts` and removing `export` keyword
|
||||
*/
|
||||
export interface Locals {
|
||||
userid: string;
|
||||
}
|
||||
|
||||
export interface MarkerData {
|
||||
severity: number;
|
||||
message: string;
|
||||
@@ -40,7 +32,7 @@ export interface State {
|
||||
|
||||
export interface ValidatedState extends State {
|
||||
editorMode: EditorMode;
|
||||
error: unknown;
|
||||
error?: Error;
|
||||
errorMarkers: MarkerData[];
|
||||
serialized: string;
|
||||
}
|
||||
@@ -73,14 +65,24 @@ export type HistoryEntry = { id: string; state: State; time: number; url?: strin
|
||||
}
|
||||
);
|
||||
|
||||
export interface DocConfig {
|
||||
[key: string]: {
|
||||
export type DocumentationConfig = Record<
|
||||
string,
|
||||
{
|
||||
code: string;
|
||||
config?: string;
|
||||
};
|
||||
}
|
||||
}
|
||||
>;
|
||||
|
||||
export type EditorMode = 'code' | 'config';
|
||||
|
||||
export type Loader = (url: string) => Promise<State>;
|
||||
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;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3,19 +3,26 @@
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import type { State } from '$lib/types';
|
||||
import { defaultState } from '../state';
|
||||
import { addHistoryEntry } from '../../components/History/history';
|
||||
import { defaultState } from '$lib/util/state';
|
||||
import { addHistoryEntry } from '$lib/components/History/history';
|
||||
import { fetchJSON, fetchText } from '$lib/util/util';
|
||||
|
||||
const codeFileName = 'code.mmd';
|
||||
const configFileName = 'config.json';
|
||||
|
||||
interface GithubFile {
|
||||
truncated: boolean;
|
||||
raw_url: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
const isValidGist = (files: any): boolean => {
|
||||
return codeFileName in files;
|
||||
};
|
||||
|
||||
const getFileContent = async (file: any): Promise<string> => {
|
||||
const getFileContent = async (file: GithubFile): Promise<string> => {
|
||||
if (file.truncated) {
|
||||
return await (await fetch(file.raw_url)).text();
|
||||
return await fetchText(file.raw_url);
|
||||
}
|
||||
return file.content;
|
||||
};
|
||||
@@ -29,16 +36,26 @@ interface GistData {
|
||||
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 path = gistURL.split('github.com').pop();
|
||||
if (!path) {
|
||||
throw new Error('Invalid GitHub URL' + gistURL);
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const [_, __, gistID, revisionID] = gistURL.split('github.com').pop().split('/');
|
||||
const [_, __, gistID, revisionID] = path.split('/');
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const { html_url, files, history } = await (
|
||||
await fetch(`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`)
|
||||
).json();
|
||||
const { html_url, files, history }: GistResponse = await fetchJSON(
|
||||
`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`
|
||||
);
|
||||
if (isValidGist(files)) {
|
||||
const code = await getFileContent(files[codeFileName]);
|
||||
let config: string;
|
||||
let config = '{}';
|
||||
if (configFileName in files) {
|
||||
config = await getFileContent(files[configFileName]);
|
||||
}
|
||||
@@ -50,10 +67,10 @@ const getGistData = async (gistURL: string): Promise<GistData> => {
|
||||
config,
|
||||
author: currentItem.user.login,
|
||||
time: new Date(currentItem.committed_at).getTime(),
|
||||
version: (currentItem.version as string).slice(-7)
|
||||
version: currentItem.version.slice(-7)
|
||||
};
|
||||
} else {
|
||||
throw 'Invalid gist provided';
|
||||
throw new Error('Invalid gist provided');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -73,35 +90,38 @@ const getStateFromGist = (gist: GistData, gistURL: string = gist.url): State =>
|
||||
};
|
||||
|
||||
export const loadGistData = async (gistURL: string): Promise<State> => {
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const [_, __, gistID, revisionID] = gistURL.split('github.com').pop().split('/');
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const { history } = await (
|
||||
await fetch(`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`)
|
||||
).json();
|
||||
const gistHistory: GistData[] = [];
|
||||
for (const entry of history) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const data: GistData = await getGistData(entry.url).catch(() => undefined);
|
||||
data && gistHistory.push(data);
|
||||
}
|
||||
if (gistHistory.length === 0) {
|
||||
throw 'Invalid gist provided';
|
||||
}
|
||||
gistHistory.reverse();
|
||||
const state = getStateFromGist(gistHistory.slice(-1).pop(), gistURL);
|
||||
for (const gist of gistHistory) {
|
||||
addHistoryEntry({
|
||||
state: getStateFromGist(gist),
|
||||
time: gist.time,
|
||||
type: 'loader',
|
||||
url: gist.url,
|
||||
name: `${gist.author} v${gist.version}`
|
||||
});
|
||||
}
|
||||
return state;
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
const path = gistURL.split('github.com').pop();
|
||||
if (!path) {
|
||||
throw new Error('Invalid GitHub URL' + gistURL);
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const [_, __, gistID, revisionID] = path.split('/');
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const { history }: GistResponse = await fetchJSON(
|
||||
`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`
|
||||
);
|
||||
const gistHistory: GistData[] = [];
|
||||
for (const entry of history) {
|
||||
const data: GistData | undefined = await getGistData(entry.url).catch();
|
||||
data && gistHistory.push(data);
|
||||
}
|
||||
if (gistHistory.length === 0) {
|
||||
throw new Error('Invalid gist provided');
|
||||
}
|
||||
gistHistory.reverse();
|
||||
const entry = gistHistory.slice(-1).pop();
|
||||
if (!entry) {
|
||||
throw new Error('Invalid gist provided');
|
||||
}
|
||||
const state = getStateFromGist(entry, gistURL);
|
||||
for (const gist of gistHistory) {
|
||||
addHistoryEntry({
|
||||
state: getStateFromGist(gist),
|
||||
time: gist.time,
|
||||
type: 'loader',
|
||||
url: gist.url,
|
||||
name: `${gist.author} v${gist.version}`
|
||||
});
|
||||
}
|
||||
return state;
|
||||
};
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { loadGistData } from './gist';
|
||||
import { updateCodeStore, defaultState } from '../state';
|
||||
import { updateCodeStore, defaultState } from '$lib/util/state';
|
||||
import { fetchText } from '$lib/util/util';
|
||||
import type { Loader, State } from '$lib/types';
|
||||
|
||||
const loaders: Record<string, Loader> = {
|
||||
gist: loadGistData
|
||||
};
|
||||
@@ -8,36 +10,21 @@ const loaders: Record<string, Loader> = {
|
||||
export const loadDataFromUrl = async (): Promise<void> => {
|
||||
const searchParams = new URLSearchParams(window.location.search);
|
||||
let state: Partial<State> = defaultState;
|
||||
let code: string, config: string;
|
||||
let loaded = false;
|
||||
const codeURL: string = searchParams.get('code');
|
||||
const configURL: string = searchParams.get('config');
|
||||
const codeURL: string | undefined = searchParams.get('code') ?? undefined;
|
||||
const configURL: string | undefined = searchParams.get('config') ?? undefined;
|
||||
|
||||
let code: string | undefined;
|
||||
const config = configURL ? await fetchText(configURL) : defaultState.mermaid;
|
||||
|
||||
if (codeURL) {
|
||||
code = await (await fetch(codeURL)).text();
|
||||
code = await fetchText(codeURL);
|
||||
loaded = true;
|
||||
}
|
||||
if (configURL) {
|
||||
config = await (await fetch(configURL)).text();
|
||||
} else {
|
||||
config = defaultState.mermaid;
|
||||
}
|
||||
if (!code) {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
||||
for (const [key, value] of searchParams.entries()) {
|
||||
if (key in loaders) {
|
||||
try {
|
||||
state = await loaders[key](value);
|
||||
loaded = true;
|
||||
break;
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
if (code) {
|
||||
if (!codeURL) {
|
||||
throw new Error('Code URL is not defined');
|
||||
}
|
||||
} else {
|
||||
state = {
|
||||
code,
|
||||
mermaid: config,
|
||||
@@ -49,6 +36,18 @@ export const loadDataFromUrl = async (): Promise<void> => {
|
||||
}
|
||||
}
|
||||
};
|
||||
} else {
|
||||
for (const [key, value] of searchParams.entries()) {
|
||||
if (key in loaders) {
|
||||
try {
|
||||
state = await loaders[key](value);
|
||||
loaded = true;
|
||||
break;
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
loaded &&
|
||||
updateCodeStore({
|
||||
|
||||
+8
-16
@@ -1,24 +1,16 @@
|
||||
import mermaid, { type MermaidConfig } from 'mermaid';
|
||||
import mindmap from '@mermaid-js/mermaid-mindmap';
|
||||
|
||||
const initialize = mermaid.registerExternalDiagrams([mindmap]);
|
||||
|
||||
export const init = async () => {
|
||||
await initialize;
|
||||
};
|
||||
import mermaid from 'mermaid';
|
||||
import type { MermaidConfig, RenderResult } from 'mermaid';
|
||||
|
||||
export const render = async (
|
||||
config: MermaidConfig,
|
||||
code: string,
|
||||
id: string,
|
||||
callback: Parameters<typeof mermaid.render>[2]
|
||||
): Promise<void> => {
|
||||
await init();
|
||||
id: string
|
||||
): Promise<RenderResult> => {
|
||||
// Should be able to call this multiple times without any issues.
|
||||
mermaid.initialize(config);
|
||||
await mermaid.mermaidAPI.renderAsync(id, code, callback);
|
||||
return await mermaid.render(id, code);
|
||||
};
|
||||
|
||||
export const parse = async (code: string): Promise<boolean> => {
|
||||
await init();
|
||||
return (await mermaid.parseAsync(code)) as boolean;
|
||||
export const parse = async (code: string): Promise<unknown> => {
|
||||
return await mermaid.parse(code);
|
||||
};
|
||||
|
||||
@@ -16,18 +16,22 @@ describe('migrations', () => {
|
||||
it('should migrate from v0 to v1', async () => {
|
||||
const { applyMigrations } = await import('./migrations');
|
||||
let manualHistoryStore: HistoryEntry[] = JSON.parse(
|
||||
window.localStorage.getItem('manualHistoryStore')
|
||||
);
|
||||
window.localStorage.getItem('manualHistoryStore') ?? '[]'
|
||||
) as HistoryEntry[];
|
||||
let autoHistoryStore: HistoryEntry[] = JSON.parse(
|
||||
window.localStorage.getItem('autoHistoryStore')
|
||||
);
|
||||
window.localStorage.getItem('autoHistoryStore') ?? '[]'
|
||||
) as HistoryEntry[];
|
||||
expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(false);
|
||||
expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(false);
|
||||
|
||||
applyMigrations();
|
||||
|
||||
manualHistoryStore = JSON.parse(window.localStorage.getItem('manualHistoryStore'));
|
||||
autoHistoryStore = JSON.parse(window.localStorage.getItem('autoHistoryStore'));
|
||||
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);
|
||||
});
|
||||
|
||||
@@ -7,7 +7,7 @@ interface MigrationState {
|
||||
version: number;
|
||||
}
|
||||
|
||||
const migrations: { [key: string]: () => void } = {
|
||||
const migrations: Record<string, () => void> = {
|
||||
injectHistoryIDs
|
||||
};
|
||||
|
||||
|
||||
+21
-29
@@ -39,16 +39,16 @@ let noWarnings = false;
|
||||
/**
|
||||
* List of storages where the warning have already been displayed.
|
||||
*/
|
||||
const alreadyWarnFor: Array<string> = [];
|
||||
const alreadyWarnFor: string[] = [];
|
||||
|
||||
/**
|
||||
* Add a log to indicate that the requested Storage have not been found.
|
||||
* @param {string} storageName
|
||||
*/
|
||||
const warnStorageNotFound = (storageName) => {
|
||||
const isProduction = typeof process !== 'undefined' && process.env?.NODE_ENV === 'production';
|
||||
const warnStorageNotFound = (storageName: string) => {
|
||||
const isProduction = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
|
||||
|
||||
if (!noWarnings && alreadyWarnFor.indexOf(storageName) === -1 && !isProduction) {
|
||||
if (!noWarnings && !alreadyWarnFor.includes(storageName) && !isProduction) {
|
||||
let message = `Unable to find the ${storageName}. No data will be persisted.`;
|
||||
if (typeof window === 'undefined') {
|
||||
message +=
|
||||
@@ -60,17 +60,8 @@ const warnStorageNotFound = (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 deserialize = (value: string): unknown => {
|
||||
const deserialize = (value?: string | null): unknown => {
|
||||
// @TODO: to remove in the next major
|
||||
if (value === 'undefined') {
|
||||
return undefined;
|
||||
@@ -78,14 +69,14 @@ const deserialize = (value: string): unknown => {
|
||||
|
||||
if (value !== null && value !== undefined) {
|
||||
try {
|
||||
return ESSerializer.deserialize(value, allowedClasses);
|
||||
} catch (e) {
|
||||
return ESSerializer.deserialize(value);
|
||||
} catch {
|
||||
// Do nothing
|
||||
// use the value "as is"
|
||||
}
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
} catch (e) {
|
||||
} catch {
|
||||
// Do nothing
|
||||
// use the value "as is"
|
||||
}
|
||||
@@ -162,7 +153,7 @@ export function persist<T>(
|
||||
store.set(initialValue);
|
||||
}
|
||||
|
||||
if ((storage as SelfUpdateStorageInterface<T>).addListener) {
|
||||
if ('addListener' in storage) {
|
||||
(storage as SelfUpdateStorageInterface<T>).addListener(key, (newValue) => {
|
||||
store.set(newValue);
|
||||
});
|
||||
@@ -184,24 +175,24 @@ function getBrowserStorage(
|
||||
browserStorage: Storage,
|
||||
listenExternalChanges = false
|
||||
): SelfUpdateStorageInterface<any> {
|
||||
const listeners: Array<{ key: string; listener: (newValue: any) => void }> = [];
|
||||
const listeners: { key: string; listener: (newValue: any) => void }[] = [];
|
||||
const listenerFunction = (event: StorageEvent) => {
|
||||
const eventKey = event.key;
|
||||
if (event.storageArea === browserStorage) {
|
||||
listeners
|
||||
.filter(({ key }) => key === eventKey)
|
||||
.forEach(({ listener }) => {
|
||||
listener(deserialize(event.newValue));
|
||||
});
|
||||
for (const { listener } of listeners.filter(({ key }) => key === eventKey)) {
|
||||
listener(deserialize(event.newValue));
|
||||
}
|
||||
}
|
||||
};
|
||||
const connect = () => {
|
||||
if (listenExternalChanges && typeof window !== 'undefined' && window?.addEventListener) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
||||
if (listenExternalChanges && typeof window !== 'undefined' && window.addEventListener) {
|
||||
window.addEventListener('storage', listenerFunction);
|
||||
}
|
||||
};
|
||||
const disconnect = () => {
|
||||
if (listenExternalChanges && typeof window !== 'undefined' && window?.removeEventListener) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
||||
if (listenExternalChanges && typeof window !== 'undefined' && window.removeEventListener) {
|
||||
window.removeEventListener('storage', listenerFunction);
|
||||
}
|
||||
};
|
||||
@@ -237,10 +228,11 @@ function getBrowserStorage(
|
||||
|
||||
/**
|
||||
* Storage implementation that use the browser local storage
|
||||
* @param {boolean} listenExternalChanges - Update the store if the localStorage is updated from another page
|
||||
* @param listenExternalChanges - Update the store if the localStorage is updated from another page
|
||||
*/
|
||||
export function localStorage<T>(listenExternalChanges = false): StorageInterface<T> {
|
||||
if (typeof window !== 'undefined' && window?.localStorage) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
||||
if (typeof window !== 'undefined' && window.localStorage) {
|
||||
return getBrowserStorage(window.localStorage, listenExternalChanges);
|
||||
}
|
||||
warnStorageNotFound('window.localStorage');
|
||||
@@ -250,7 +242,7 @@ export function localStorage<T>(listenExternalChanges = false): StorageInterface
|
||||
/**
|
||||
* Storage implementation that do nothing
|
||||
*/
|
||||
export function noopStorage(): StorageInterface<any> {
|
||||
export function noopStorage<T>(): StorageInterface<T> {
|
||||
return {
|
||||
getValue(): null {
|
||||
return null;
|
||||
|
||||
+10
-10
@@ -3,29 +3,29 @@ import { serializeState, deserializeState, type SerdeType } from './serde';
|
||||
import { defaultState } from './state';
|
||||
import type { State } from '$lib/types';
|
||||
|
||||
describe('Serde tests', () => {
|
||||
const verifySerde = (state: State, serde?: SerdeType): string => {
|
||||
const serialized = serializeState(state, serde);
|
||||
const deserialized = deserializeState(serialized);
|
||||
expect(deserialized).to.deep.equal(state);
|
||||
return serialized;
|
||||
};
|
||||
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', () => {
|
||||
it('should serialize and deserialize with default serde', () => {
|
||||
expect(verifySerde(defaultState)).toMatchInlineSnapshot(
|
||||
'"pako:eNpVj81qw0AMhF9F6NRC_AI-BGK7zSXQQHLz5iBsObuk-8Naphjb7551fEl1EjPfiNGEjW8Zc7xHChqulXKQ5lCXOppeLPU3yLL9fGQB6x2PMxQfRw-99iEYd__c-GKFoJxOK8Yg2rjHslnlK__jeIaqPlEQH27vzvXPz_BVm7NO5_87OnJKfdcd5R1lDUUoKb4Q3KHlaMm0qfq0KgpFs2WFeVpb7mj4FYXKLQmlQfxldA3mEgfe4RBaEq4MpaftJi5PNtJU8w"'
|
||||
'"pako:eNpVjk2Lg0AMhv9KyGkL9Q94WGh1t5fCFurN6SFo7AztfDBGpKj_fcd62c0pvM_zhkzY-JYxx-7px0ZTFKhK5SDNoS50NL1Y6m-QZZ_ziQWsd_ya4fhx8tBrH4Jx993mH1cJium8agyijXssGyre_R_HM5T1mYL4cPtLqtHP8FWbi07n_xMdObW-647yjrKGIhQU3wru0XK0ZNr0_rQmCkWzZYV5WlvuaHiKQuWWpNIg_vpyDeYSB97jEFoSLg3dI9ktXH4B_cJWqw"'
|
||||
);
|
||||
});
|
||||
|
||||
it('should serialize and deserialize with base64 serde', () => {
|
||||
expect(verifySerde(defaultState, 'base64')).toMatchInlineSnapshot(
|
||||
'"base64:eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW0NocmlzdG1hc10gLS0-fEdldCBtb25leXwgQihHbyBzaG9wcGluZylcbiAgICBCIC0tPiBDe0xldCBtZSB0aGlua31cbiAgICBDIC0tPnxPbmV8IERbTGFwdG9wXVxuICAgIEMgLS0-fFR3b3wgRVtpUGhvbmVdXG4gICAgQyAtLT58VGhyZWV8IEZbZmE6ZmEtY2FyIENhcl1cbiAgIiwibWVybWFpZCI6IntcbiAgXCJ0aGVtZVwiOiBcImRlZmF1bHRcIlxufSIsImF1dG9TeW5jIjp0cnVlLCJ1cGRhdGVEaWFncmFtIjp0cnVlfQ"'
|
||||
'"base64:eyJjb2RlIjoiZmxvd2NoYXJ0IFREXG4gICAgQVtDaHJpc3RtYXNdIC0tPnxHZXQgbW9uZXl8IEIoR28gc2hvcHBpbmcpXG4gICAgQiAtLT4gQ3tMZXQgbWUgdGhpbmt9XG4gICAgQyAtLT58T25lfCBEW0xhcHRvcF1cbiAgICBDIC0tPnxUd298IEVbaVBob25lXVxuICAgIEMgLS0-fFRocmVlfCBGW2ZhOmZhLWNhciBDYXJdXG4gICIsIm1lcm1haWQiOiJ7XG4gIFwidGhlbWVcIjogXCJkZWZhdWx0XCJcbn0iLCJhdXRvU3luYyI6dHJ1ZSwidXBkYXRlRGlhZ3JhbSI6dHJ1ZX0"'
|
||||
);
|
||||
});
|
||||
|
||||
it('should serialize and deserialize with pako serde', () => {
|
||||
expect(verifySerde(defaultState, 'pako')).toMatchInlineSnapshot(
|
||||
'"pako:eNpVj81qw0AMhF9F6NRC_AI-BGK7zSXQQHLz5iBsObuk-8Naphjb7551fEl1EjPfiNGEjW8Zc7xHChqulXKQ5lCXOppeLPU3yLL9fGQB6x2PMxQfRw-99iEYd__c-GKFoJxOK8Yg2rjHslnlK__jeIaqPlEQH27vzvXPz_BVm7NO5_87OnJKfdcd5R1lDUUoKb4Q3KHlaMm0qfq0KgpFs2WFeVpb7mj4FYXKLQmlQfxldA3mEgfe4RBaEq4MpaftJi5PNtJU8w"'
|
||||
'"pako:eNpVjk2Lg0AMhv9KyGkL9Q94WGh1t5fCFurN6SFo7AztfDBGpKj_fcd62c0pvM_zhkzY-JYxx-7px0ZTFKhK5SDNoS50NL1Y6m-QZZ_ziQWsd_ya4fhx8tBrH4Jx993mH1cJium8agyijXssGyre_R_HM5T1mYL4cPtLqtHP8FWbi07n_xMdObW-647yjrKGIhQU3wru0XK0ZNr0_rQmCkWzZYV5WlvuaHiKQuWWpNIg_vpyDeYSB97jEFoSLg3dI9ktXH4B_cJWqw"'
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ const serdes: { [key in SerdeType]: Serde } = {
|
||||
};
|
||||
|
||||
export const serializeState = (state: State, serde: SerdeType = 'pako'): string => {
|
||||
if (serdes[serde] === undefined) {
|
||||
if (!(serde in serdes)) {
|
||||
throw new Error(`Unknown serde type: ${serde}`);
|
||||
}
|
||||
const json = JSON.stringify(state);
|
||||
|
||||
+38
-42
@@ -2,30 +2,28 @@ import { writable, get, type Readable, derived } from 'svelte/store';
|
||||
import { persist, localStorage } from './persist';
|
||||
import { saveStatistics, countLines } from './stats';
|
||||
import { serializeState, deserializeState } from './serde';
|
||||
import { cmdKey, errorDebug, AsyncQueue } from './util';
|
||||
import { cmdKey, errorDebug, formatJSON } from './util';
|
||||
import { parse } from './mermaid';
|
||||
|
||||
import type { MarkerData, State, ValidatedState } from '$lib/types';
|
||||
import type { ErrorHash, MarkerData, State, ValidatedState } from '$lib/types';
|
||||
import type { MermaidConfig } from 'mermaid';
|
||||
|
||||
export const defaultState: State = {
|
||||
code: `graph TD
|
||||
code: `flowchart TD
|
||||
A[Christmas] -->|Get money| B(Go shopping)
|
||||
B --> C{Let me think}
|
||||
C -->|One| D[Laptop]
|
||||
C -->|Two| E[iPhone]
|
||||
C -->|Three| F[fa:fa-car Car]
|
||||
`,
|
||||
mermaid: JSON.stringify(
|
||||
{
|
||||
theme: 'default'
|
||||
},
|
||||
null,
|
||||
2
|
||||
),
|
||||
mermaid: formatJSON({
|
||||
theme: 'default'
|
||||
}),
|
||||
autoSync: true,
|
||||
updateDiagram: true
|
||||
};
|
||||
|
||||
const urlParseFailedState = `graph TD
|
||||
const urlParseFailedState = `flowchart 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.)
|
||||
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.)
|
||||
@@ -50,8 +48,6 @@ export const currentState: ValidatedState = (() => {
|
||||
};
|
||||
})();
|
||||
|
||||
let q: AsyncQueue<State>;
|
||||
|
||||
const processState = async (state: State) => {
|
||||
const processed: ValidatedState = {
|
||||
...state,
|
||||
@@ -65,23 +61,28 @@ const processState = async (state: State) => {
|
||||
processed.serialized = serializeState(state);
|
||||
await parse(state.code);
|
||||
JSON.parse(state.mermaid);
|
||||
} catch (e) {
|
||||
processed.error = e;
|
||||
} catch (error) {
|
||||
processed.error = error as Error;
|
||||
errorDebug();
|
||||
console.error(e);
|
||||
if (e.hash) {
|
||||
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: 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
|
||||
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 (err) {
|
||||
console.error('Error without line helper', err);
|
||||
} catch (error) {
|
||||
console.error('Error without line helper', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -92,14 +93,7 @@ const processState = async (state: State) => {
|
||||
export const stateStore: Readable<ValidatedState> = derived(
|
||||
[inputStateStore],
|
||||
([state], set) => {
|
||||
if (!q) {
|
||||
// Initialize the queue for first time.
|
||||
q = new AsyncQueue(async (state: State) => {
|
||||
const newState = await processState(state);
|
||||
set(newState);
|
||||
});
|
||||
}
|
||||
q.process(state);
|
||||
void processState(state).then(set);
|
||||
},
|
||||
currentState
|
||||
);
|
||||
@@ -109,8 +103,10 @@ export const loadState = (data: string): void => {
|
||||
console.log(`Loading '${data}'`);
|
||||
try {
|
||||
state = deserializeState(data);
|
||||
const mermaidConfig: { [key: string]: string } =
|
||||
typeof state.mermaid === 'string' ? JSON.parse(state.mermaid) : state.mermaid;
|
||||
const mermaidConfig: MermaidConfig =
|
||||
typeof state.mermaid === 'string'
|
||||
? (JSON.parse(state.mermaid) as MermaidConfig)
|
||||
: state.mermaid;
|
||||
if (
|
||||
mermaidConfig.securityLevel &&
|
||||
mermaidConfig.securityLevel !== 'strict' &&
|
||||
@@ -120,11 +116,11 @@ export const loadState = (data: string): void => {
|
||||
) {
|
||||
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);
|
||||
} catch (error) {
|
||||
state = get(inputStateStore);
|
||||
if (data) {
|
||||
console.error('Init error', e);
|
||||
console.error('Init error', error);
|
||||
state.code = urlParseFailedState;
|
||||
state.mermaid = defaultState.mermaid;
|
||||
}
|
||||
@@ -146,7 +142,7 @@ export const updateCode = (
|
||||
resetPanZoom = false
|
||||
}: { updateDiagram?: boolean; resetPanZoom?: boolean } = {}
|
||||
): void => {
|
||||
console.log('updateCode', code);
|
||||
// console.log('updateCode', code);
|
||||
const lines = countLines(code);
|
||||
saveStatistics(code);
|
||||
errorDebug();
|
||||
@@ -172,7 +168,7 @@ export const updateCode = (
|
||||
};
|
||||
|
||||
export const updateConfig = (config: string): void => {
|
||||
console.log('updateConfig', config);
|
||||
// console.log('updateConfig', config);
|
||||
inputStateStore.update((state) => {
|
||||
return { ...state, mermaid: config };
|
||||
});
|
||||
@@ -180,12 +176,12 @@ export const updateConfig = (config: string): void => {
|
||||
|
||||
export const toggleDarkTheme = (dark: boolean): void => {
|
||||
inputStateStore.update((state) => {
|
||||
const config = JSON.parse(state.mermaid);
|
||||
const config = JSON.parse(state.mermaid) as MermaidConfig;
|
||||
if (!config.theme || ['dark', 'default'].includes(config.theme)) {
|
||||
config.theme = dark ? 'dark' : 'default';
|
||||
}
|
||||
|
||||
return { ...state, mermaid: JSON.stringify(config, null, 2) };
|
||||
return { ...state, mermaid: formatJSON(config) };
|
||||
});
|
||||
};
|
||||
|
||||
@@ -194,7 +190,7 @@ export const initURLSubscription = (): void => {
|
||||
stateStore.subscribe(({ serialized }) => {
|
||||
clearTimeout(urlDebounce);
|
||||
urlDebounce = window.setTimeout(() => {
|
||||
history.replaceState(undefined, undefined, `#${serialized}`);
|
||||
history.replaceState(undefined, '', `#${serialized}`);
|
||||
}, 250);
|
||||
});
|
||||
};
|
||||
|
||||
+13
-12
@@ -1,6 +1,6 @@
|
||||
import { browser } from '$app/environment';
|
||||
import type { AnalyticsInstance } from 'analytics';
|
||||
export let analytics: AnalyticsInstance;
|
||||
export let analytics: AnalyticsInstance | undefined;
|
||||
|
||||
export const initAnalytics = async (): Promise<void> => {
|
||||
if (browser && !analytics) {
|
||||
@@ -20,14 +20,14 @@ export const initAnalytics = async (): Promise<void> => {
|
||||
})
|
||||
]
|
||||
});
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
console.info('Analytics blocked ;)');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const detectType = (text: string): string => {
|
||||
export const detectType = (text: string): string | undefined => {
|
||||
const possibleDiagramTypes = [
|
||||
'classDiagram',
|
||||
'erDiagram',
|
||||
@@ -49,7 +49,7 @@ export const detectType = (text: string): string => {
|
||||
};
|
||||
|
||||
export const countLines = (code: string): number => {
|
||||
return (code.match(/\n/g) || '').length + 1;
|
||||
return (code.match(/\n/g)?.length ?? 0) + 1;
|
||||
};
|
||||
|
||||
export const saveStatistics = (graph: string): void => {
|
||||
@@ -80,19 +80,20 @@ const delaysPerEvent = {
|
||||
themeChange: defaultDelay
|
||||
};
|
||||
export type AnalyticsEvent = keyof typeof delaysPerEvent;
|
||||
const timeouts: Record<string, number> = {};
|
||||
const timeouts: Map<string, number> = new Map<string, number>();
|
||||
// manual debounce to reduce the number of events sent to analytics
|
||||
export const logEvent = (name: AnalyticsEvent, data?: unknown): void => {
|
||||
if (!analytics) {
|
||||
return;
|
||||
}
|
||||
const key = data ? JSON.stringify({ name, data }) : name;
|
||||
if (timeouts[key] === undefined) {
|
||||
void analytics.track(name, data);
|
||||
if (timeouts.has(key)) {
|
||||
clearTimeout(timeouts.get(key));
|
||||
} else {
|
||||
clearTimeout(timeouts[key]);
|
||||
void analytics.track(name, data);
|
||||
}
|
||||
timeouts[key] = window.setTimeout(() => {
|
||||
delete timeouts[key];
|
||||
}, delaysPerEvent[name]);
|
||||
timeouts.set(
|
||||
key,
|
||||
window.setTimeout(() => timeouts.delete(key), delaysPerEvent[name])
|
||||
);
|
||||
};
|
||||
|
||||
@@ -16,7 +16,7 @@ export const themeStore: Writable<ThemeConfig> = persist(
|
||||
'themeStore'
|
||||
);
|
||||
|
||||
const darkThemes = [
|
||||
const darkThemes = new Set([
|
||||
'dark',
|
||||
'synthwave',
|
||||
'halloween',
|
||||
@@ -25,13 +25,13 @@ const darkThemes = [
|
||||
'luxury',
|
||||
'black',
|
||||
'dracula'
|
||||
];
|
||||
]);
|
||||
|
||||
export const setTheme = (theme: string): void => {
|
||||
if (theme.includes(' ')) {
|
||||
theme = theme.split(' ')[1].trim();
|
||||
}
|
||||
const isDark = darkThemes.includes(theme);
|
||||
const isDark = darkThemes.has(theme);
|
||||
console.log('Setting theme', theme);
|
||||
themeStore.set({ theme, isDark });
|
||||
logEvent('themeChange', { theme, isDark });
|
||||
|
||||
+11
-24
@@ -3,7 +3,6 @@ import { analytics, initAnalytics } from './stats';
|
||||
import { loadDataFromUrl } from './fileLoaders/loader';
|
||||
import { initLoading } from './loading';
|
||||
import { applyMigrations } from './migrations';
|
||||
import { init } from './mermaid';
|
||||
|
||||
export const loadStateFromURL = (): void => {
|
||||
loadState(window.location.hash.slice(1));
|
||||
@@ -17,16 +16,15 @@ export const syncDiagram = (): void => {
|
||||
|
||||
export const initHandler = async (): Promise<void> => {
|
||||
applyMigrations();
|
||||
await initLoading('Loading Mermaid...', init());
|
||||
loadStateFromURL();
|
||||
await initLoading('Loading Gist...', loadDataFromUrl().catch(console.error));
|
||||
syncDiagram();
|
||||
initURLSubscription();
|
||||
await initAnalytics();
|
||||
analytics?.page();
|
||||
await analytics?.page();
|
||||
};
|
||||
|
||||
export const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
|
||||
export const isMac = navigator.platform.toUpperCase().includes('MAC');
|
||||
export const cmdKey = isMac ? 'Cmd' : 'Ctrl';
|
||||
|
||||
let count = 0;
|
||||
@@ -39,23 +37,12 @@ export const errorDebug = (limit = 100) => {
|
||||
}
|
||||
};
|
||||
|
||||
// To queue async tasks so they are executed one after the other, not concurrently.
|
||||
export class AsyncQueue<T> {
|
||||
private readonly queue: T[] = [];
|
||||
private running = false;
|
||||
constructor(private processor: (item: T) => Promise<void>) {}
|
||||
public async process(item: T): Promise<void> {
|
||||
this.queue.push(item);
|
||||
if (this.running) {
|
||||
return;
|
||||
}
|
||||
this.running = true;
|
||||
while (this.queue.length > 0) {
|
||||
const item = this.queue.shift();
|
||||
if (item) {
|
||||
await this.processor(item);
|
||||
}
|
||||
}
|
||||
this.running = false;
|
||||
}
|
||||
}
|
||||
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,3 +1,4 @@
|
||||
export const prerender = true;
|
||||
export const csr = true;
|
||||
export const ssr = false;
|
||||
export const trailingSlash = 'ignore';
|
||||
@@ -10,8 +10,8 @@
|
||||
// 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.
|
||||
onMount(() => {
|
||||
window.addEventListener('hashchange', async (ev) => {
|
||||
await initHandler();
|
||||
window.addEventListener('hashchange', () => {
|
||||
void initHandler();
|
||||
});
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker
|
||||
|
||||
@@ -9,11 +9,11 @@
|
||||
import { inputStateStore, stateStore, updateCodeStore } from '$lib/util/state';
|
||||
import { cmdKey, initHandler, syncDiagram } from '$lib/util/util';
|
||||
import { onMount } from 'svelte';
|
||||
import type { Tab, DocConfig, EditorMode, ValidatedState } from '$lib/types';
|
||||
import type { Tab, DocumentationConfig, EditorMode, ValidatedState } from '$lib/types';
|
||||
import { base } from '$app/paths';
|
||||
|
||||
const docURLBase = 'https://mermaid-js.github.io/mermaid';
|
||||
const docMap: DocConfig = {
|
||||
const docMap: DocumentationConfig = {
|
||||
graph: {
|
||||
code: '/#/flowchart',
|
||||
config: '/#/flowchart?id=configuration'
|
||||
@@ -54,11 +54,12 @@
|
||||
};
|
||||
let docURL = docURLBase;
|
||||
let activeTabID = 'code';
|
||||
let docKey = '';
|
||||
stateStore.subscribe(({ code, editorMode }: ValidatedState) => {
|
||||
activeTabID = editorMode;
|
||||
const codeTypeMatch = /([\S]+)[\s\n]/.exec(code);
|
||||
if (codeTypeMatch && codeTypeMatch.length > 1) {
|
||||
const docKey = codeTypeMatch[1];
|
||||
docKey = codeTypeMatch[1];
|
||||
const docConfig = docMap[docKey] ?? { code: '' };
|
||||
docURL = docURLBase + (docConfig[editorMode] ?? docConfig.code ?? '');
|
||||
}
|
||||
@@ -86,6 +87,10 @@
|
||||
await initHandler();
|
||||
const resizer = document.getElementById('resizeHandler');
|
||||
const element = document.getElementById('editorPane');
|
||||
if (!resizer || !element) {
|
||||
console.debug('Failed to find resize handler or editor pane', { resizer, element });
|
||||
return;
|
||||
}
|
||||
const resize = (e: { pageX: number }) => {
|
||||
const newWidth = e.pageX - element.getBoundingClientRect().left;
|
||||
if (newWidth > 50) {
|
||||
@@ -129,7 +134,9 @@
|
||||
on:click={syncDiagram}><i class="fas fa-sync" /></button>
|
||||
{/if}
|
||||
|
||||
<button class="btn btn-secondary btn-xs" title="View documentation">
|
||||
<button
|
||||
class="btn btn-secondary btn-xs"
|
||||
title="View documentation for {docKey.replace('Diagram', '')} diagram">
|
||||
<a target="_blank" rel="noreferrer" href={docURL} data-cy="docs">
|
||||
<i class="fas fa-book mr-1" />Docs
|
||||
</a>
|
||||
|
||||
+1
-2
@@ -18,8 +18,7 @@ const config = {
|
||||
? {
|
||||
base: `/mermaid-live-editor`
|
||||
}
|
||||
: {},
|
||||
trailingSlash: 'ignore'
|
||||
: {}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
"compilerOptions": {
|
||||
"resolveJsonModule": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strictNullChecks": true,
|
||||
"types": ["vitest/importMeta"]
|
||||
},
|
||||
"extends": "./.svelte-kit/tsconfig.json"
|
||||
|
||||
+4
-4
@@ -1,6 +1,7 @@
|
||||
import { sveltekit } from '@sveltejs/kit/vite';
|
||||
/** @type {import('vite').UserConfig} */
|
||||
const config = {
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [sveltekit()],
|
||||
envPrefix: 'MERMAID_',
|
||||
optimizeDeps: { include: ['mermaid'] },
|
||||
@@ -22,5 +23,4 @@ const config = {
|
||||
reporter: ['text', 'json', 'html', 'lcov']
|
||||
}
|
||||
}
|
||||
};
|
||||
export default config;
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user