Compare commits
128
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc9d53b701 | ||
|
|
c21db93399 | ||
|
|
9777be9a7b | ||
|
|
c085723530 | ||
|
|
9846bd7b4c | ||
|
|
5b34b1921d | ||
|
|
1aa4bff8f8 | ||
|
|
77501eee1c | ||
|
|
106d68efd4 | ||
|
|
00b80d224c | ||
|
|
2aa4666dab | ||
|
|
19c0c698ce | ||
|
|
4d534ddabb | ||
|
|
86d212c659 | ||
|
|
9176448e17 | ||
|
|
c0b4e37267 | ||
|
|
fa634ad25a | ||
|
|
0d13a451de | ||
|
|
7c358b5c5b | ||
|
|
8f7209de11 | ||
|
|
be42ce5f7f | ||
|
|
dc2c2a2b13 | ||
|
|
9cc1503940 | ||
|
|
55e3d0219b | ||
|
|
4825d4a5c4 | ||
|
|
45d6efac4b | ||
|
|
e4703dfd2d | ||
|
|
93a86ba7f6 | ||
|
|
44cd7c2fe8 | ||
|
|
0c037e4505 | ||
|
|
28bae8cd9b | ||
|
|
bdad74f19c | ||
|
|
243d720c25 | ||
|
|
e8ba2f1e6d | ||
|
|
83ca1c5438 | ||
|
|
aeaf80d00c | ||
|
|
fee0addc6b | ||
|
|
d375b5cfea | ||
|
|
0a19740b27 | ||
|
|
973f1b7446 | ||
|
|
4774a13446 | ||
|
|
6c74a97a32 | ||
|
|
ce1dc1f3af | ||
|
|
0f3ce99659 | ||
|
|
6f5d84c8b6 | ||
|
|
4da693cd87 | ||
|
|
da3b52454f | ||
|
|
92d66da692 | ||
|
|
e6ab76a5d1 | ||
|
|
40bd944597 | ||
|
|
2dfe417220 | ||
|
|
3ffea6f168 | ||
|
|
8ec68c1ab9 | ||
|
|
98a017806e | ||
|
|
e3e8b921bc | ||
|
|
831d1e384d | ||
|
|
4c86d95f21 | ||
|
|
64e8ed09ba | ||
|
|
70b67afb87 | ||
|
|
38824e8bab | ||
|
|
63869b8d11 | ||
|
|
913b51e748 | ||
|
|
347192c5aa | ||
|
|
aafeb0a291 | ||
|
|
c47a0254ca | ||
|
|
a2b611011f | ||
|
|
5cb681c766 | ||
|
|
de3ce94bb4 | ||
|
|
d966b23114 | ||
|
|
04b898ee54 | ||
|
|
83175127b0 | ||
|
|
adc9dc7460 | ||
|
|
52dd52bfd4 | ||
|
|
9e02aaf962 | ||
|
|
28bc6cf271 | ||
|
|
3a48e4e519 | ||
|
|
6987b6f3c6 | ||
|
|
d2acfd5d36 | ||
|
|
b384e53d8b | ||
|
|
a6dcabd4b7 | ||
|
|
082e6dfffc | ||
|
|
20c23bb338 | ||
|
|
6ad4d415b2 | ||
|
|
e2c81de42e | ||
|
|
e8162c2004 | ||
|
|
5ea615ae26 | ||
|
|
7c32365935 | ||
|
|
6c209cddf1 | ||
|
|
810315ca10 | ||
|
|
a1312fc095 | ||
|
|
9395c1f154 | ||
|
|
5a880f3efe | ||
|
|
d160e43eae | ||
|
|
1a7a79d936 | ||
|
|
080b5673e7 | ||
|
|
5e06fd5df1 | ||
|
|
bba7e55662 | ||
|
|
9b7015d2cb | ||
|
|
5531564265 | ||
|
|
b08856f42e | ||
|
|
f00095540b | ||
|
|
e07204b954 | ||
|
|
1b4ddae110 | ||
|
|
7ede189894 | ||
|
|
91c34554a9 | ||
|
|
735527ae45 | ||
|
|
c45b9079c2 | ||
|
|
e7e9d81694 | ||
|
|
a1c0f8512a | ||
|
|
bdb35843bc | ||
|
|
b9e4ccfa1c | ||
|
|
df01b89342 | ||
|
|
fe03ec9fcc | ||
|
|
585dc21d7a | ||
|
|
7c627e626f | ||
|
|
bc97a075dd | ||
|
|
37c0c65cad | ||
|
|
69349ba3f4 | ||
|
|
0e07537969 | ||
|
|
6055a147b0 | ||
|
|
1becc7183d | ||
|
|
8af7029a37 | ||
|
|
d90c414e3b | ||
|
|
ec527ddf67 | ||
|
|
ea6e45ff18 | ||
|
|
1daa67c932 | ||
|
|
1290a07ddb | ||
|
|
63e978576c |
+2
-3
@@ -25,7 +25,7 @@ module.exports = {
|
||||
},
|
||||
parserOptions: {
|
||||
sourceType: 'module',
|
||||
ecmaVersion: 2019,
|
||||
ecmaVersion: 2020,
|
||||
tsconfigRootDir: __dirname,
|
||||
project: ['./tsconfig.json'],
|
||||
extraFileExtensions: ['.svelte'],
|
||||
@@ -33,8 +33,7 @@ module.exports = {
|
||||
},
|
||||
env: {
|
||||
browser: true,
|
||||
es2017: true,
|
||||
node: true
|
||||
es2020: true
|
||||
},
|
||||
rules: {
|
||||
'@typescript-eslint/ban-ts-comment': [
|
||||
|
||||
@@ -13,8 +13,8 @@ jobs:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
exempt-issue-labels: 'retained'
|
||||
exempt-pr-labels: 'retained'
|
||||
stale-issue-message: 'This issue is stale because it has been open 90 days with no activity. Remove stale label or comment or this will be closed in 14 days'
|
||||
stale-pr-message: 'This pr is stale because it has been open 90 days with no activity. Remove stale label or comment or this will be closed in 14 days'
|
||||
stale-issue-message: 'This issue is stale because it has been open 90 days with no activity. Remove stale label or comment or this will be closed in 30 days'
|
||||
stale-pr-message: 'This pr is stale because it has been open 90 days with no activity. Remove stale label or comment or this will be closed in 30 days'
|
||||
days-before-stale: 90
|
||||
days-before-close: 14
|
||||
days-before-close: 30
|
||||
days-before-pr-close: -1
|
||||
|
||||
@@ -48,3 +48,4 @@ jobs:
|
||||
parallel: true
|
||||
env:
|
||||
CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }}
|
||||
MERMAID_DISABLE_DEBOUNCE: 'true'
|
||||
|
||||
@@ -10,7 +10,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-node@v2
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 18
|
||||
- name: Update monaco version
|
||||
|
||||
Vendored
+5
-1
@@ -1,4 +1,8 @@
|
||||
{
|
||||
"editor.formatOnSave": true,
|
||||
"cSpell.words": ["pako", "Serde", "serdes"]
|
||||
"cSpell.words": ["pako", "Serde", "serdes"],
|
||||
"vitest.commandLine": "yarn test:unit",
|
||||
"vitest.enable": true,
|
||||
"testing.autoRun.mode": "rerun",
|
||||
"svelte.enable-ts-plugin": true
|
||||
}
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
# Stop : press ctrl + c
|
||||
# or
|
||||
# docker stop mermaid-live-editor
|
||||
FROM node:18.7.0 as mermaid-live-editor-builder
|
||||
FROM node:18.9.0 as mermaid-live-editor-builder
|
||||
COPY --chown=node:node . /home
|
||||
WORKDIR /home
|
||||
RUN yarn install
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@ export default defineConfig({
|
||||
defaultCommandTimeout: 16000,
|
||||
requestTimeout: 16000,
|
||||
retries: {
|
||||
runMode: 2,
|
||||
runMode: 4,
|
||||
openMode: 0
|
||||
},
|
||||
e2e: {
|
||||
|
||||
+11
-18
@@ -1,9 +1,8 @@
|
||||
import { disableDebounce } from './util';
|
||||
import { verifyFileSize } from './util';
|
||||
describe('Check actions', () => {
|
||||
beforeEach(() => {
|
||||
cy.clearLocalStorage();
|
||||
cy.visit('/edit');
|
||||
disableDebounce();
|
||||
});
|
||||
|
||||
it('should update markdown code', () => {
|
||||
@@ -27,28 +26,22 @@ describe('Check actions', () => {
|
||||
|
||||
it('should download png and svg', () => {
|
||||
cy.clock(new Date(2022, 0, 1).getTime());
|
||||
const downloadsFolder = Cypress.config('downloadsFolder');
|
||||
|
||||
const verifyFileSize = (fileType: string, size: number) => {
|
||||
cy.get(`#download${fileType.toUpperCase()}`).click();
|
||||
const fileName = `mermaid-diagram-2022-01-01-000000.${fileType}`;
|
||||
const filePath = `${downloadsFolder}/${fileName}`;
|
||||
cy.verifyDownload(fileName);
|
||||
cy.readFile(filePath, null, {
|
||||
log: false
|
||||
}).then((buffer) => expect((buffer as ArrayBuffer).byteLength).to.be.gt(size));
|
||||
cy.task('deleteFile', filePath);
|
||||
};
|
||||
cy.get(`#downloadPNG`).click();
|
||||
verifyFileSize('diagram', 'png', 21_000);
|
||||
|
||||
verifyFileSize('png', 21_000);
|
||||
verifyFileSize('svg', 11_000);
|
||||
cy.get(`#downloadSVG`).click();
|
||||
verifyFileSize('diagram', 'svg', 10_000);
|
||||
|
||||
// Verify downloaded file is different for different diagrams
|
||||
cy.contains('Sample Diagrams').click();
|
||||
cy.contains('ER Diagram').click();
|
||||
cy.contains('ER').click();
|
||||
|
||||
verifyFileSize('png', 46_000);
|
||||
verifyFileSize('svg', 12_000);
|
||||
cy.get(`#downloadPNG`).click();
|
||||
verifyFileSize('diagram', 'png', 46_000);
|
||||
|
||||
cy.get(`#downloadSVG`).click();
|
||||
verifyFileSize('diagram', 'svg', 12_000);
|
||||
|
||||
cy.clock().invoke('restore');
|
||||
});
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { getEditor, cmd, disableDebounce } from './util';
|
||||
import { getEditor, cmd } from './util';
|
||||
|
||||
describe('Auto sync tests', () => {
|
||||
beforeEach(() => {
|
||||
cy.clearLocalStorage();
|
||||
cy.visit('/');
|
||||
disableDebounce();
|
||||
});
|
||||
|
||||
it('should dim diagram when code is edited', () => {
|
||||
@@ -72,7 +71,6 @@ describe.only('Pan and Zoom', () => {
|
||||
beforeEach(() => {
|
||||
cy.clearLocalStorage();
|
||||
cy.visit('/');
|
||||
disableDebounce();
|
||||
});
|
||||
it('should toggle pan and zoom', () => {
|
||||
cy.get('#svg-pan-zoom-reset-pan-zoom').should('not.exist');
|
||||
|
||||
@@ -13,13 +13,13 @@ describe('Editor docs tests', () => {
|
||||
});
|
||||
|
||||
it('Test to see if the correct URL loads when changing from one diagram to other', () => {
|
||||
cy.contains('Flow Chart').click();
|
||||
cy.contains('Flow').click();
|
||||
cy.get(`[data-cy=docs][href$="/#/flowchart"]`).should('exist');
|
||||
|
||||
cy.contains('Config').click();
|
||||
cy.get(`[data-cy=docs][href$="/#/flowchart?id=configuration"]`).should('exist');
|
||||
|
||||
cy.contains('Sequence Diagram').click();
|
||||
cy.contains('Sequence').click();
|
||||
cy.get(`[data-cy=docs][href$="/#/sequenceDiagram?id=configuration"]`).should('exist');
|
||||
|
||||
cy.contains('Code').click();
|
||||
@@ -27,7 +27,7 @@ describe('Editor docs tests', () => {
|
||||
});
|
||||
|
||||
it("Test to check URLs for a case where config URL doesn't exist", () => {
|
||||
cy.contains('State Diagram').click();
|
||||
cy.contains('State').click();
|
||||
cy.get(`[data-cy=docs][href$="/#/stateDiagram"]`).should('exist');
|
||||
|
||||
cy.contains('Config').click();
|
||||
|
||||
@@ -1,15 +1,47 @@
|
||||
import { getEditor, disableDebounce } from './util';
|
||||
import { getEditor, verifyFileSnapshot } from './util';
|
||||
|
||||
describe('Save History', () => {
|
||||
beforeEach(() => {
|
||||
cy.clock();
|
||||
cy.clock(new Date(2022, 0, 1).getTime());
|
||||
cy.clearLocalStorage();
|
||||
cy.visit('/edit');
|
||||
disableDebounce();
|
||||
|
||||
cy.contains('Actions').click();
|
||||
cy.contains('History').click();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cy.clock().invoke('restore');
|
||||
});
|
||||
|
||||
it('should load history from localstorage', () => {
|
||||
cy.setLocalStorage(
|
||||
'manualHistoryStore',
|
||||
'[{"state":{"code":"graph TD\\n A[Halloween] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":false},"time":0,"type":"manual","id":"d7ea820e-21dd-418a-b984-fd58acde09df","name":"hollow-art"},{"state":{"code":"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":true},"time":0,"type":"manual","id":"b749ffc6-522b-4a44-86cf-7c1ffc3146b3","name":"helpful-ocean"}]'
|
||||
);
|
||||
cy.setLocalStorage(
|
||||
'autoHistoryStore',
|
||||
'[{"state":{"code":"graph TD\\n A[New Year] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":false},"time":0,"type":"auto","id":"69ea820e-522b-4a44-86cf-fd58acde09df","name":"barking-dog"},{"state":{"code":"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":true},"time":0,"type":"manual","id":"x749ffc6-21dd-418a-b984-7c1ffc3146b3","name":"needy-mosquito"}]'
|
||||
);
|
||||
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');
|
||||
cy.get('#historyList').contains('helpful-ocean');
|
||||
cy.get('#historyList').contains('hollow-art');
|
||||
cy.contains('Restore').click();
|
||||
cy.contains('Halloween');
|
||||
cy.contains('Timeline').click();
|
||||
|
||||
cy.get('#historyList').find('li').should('have.length', 2);
|
||||
cy.get('#historyList').find('No items in History').should('not.exist');
|
||||
cy.get('#historyList').contains('needy-mosquito');
|
||||
cy.get('#historyList').contains('barking-dog');
|
||||
cy.contains('Restore').click();
|
||||
cy.contains('New Year');
|
||||
});
|
||||
|
||||
it('should save when clicked', () => {
|
||||
cy.get('#historyList').find('li').should('have.length', 0);
|
||||
cy.get('#historyList').contains('No items in History');
|
||||
@@ -64,4 +96,10 @@ describe('Save History', () => {
|
||||
}
|
||||
cy.get('#historyList').find('li').should('have.length', 30);
|
||||
});
|
||||
|
||||
it('should download history', () => {
|
||||
cy.get('#saveHistory').click();
|
||||
cy.get(`#downloadHistory`).click();
|
||||
verifyFileSnapshot('history', 'json', 'A[Christmas] -->|Get money| B(Go shopping)');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { toBase64 } from 'js-base64';
|
||||
import { disableDebounce } from './util';
|
||||
|
||||
describe('Site Loads', () => {
|
||||
beforeEach(() => {
|
||||
cy.clearLocalStorage();
|
||||
cy.visit('/');
|
||||
disableDebounce();
|
||||
});
|
||||
it('Check Home page load', () => {
|
||||
cy.url().should('include', '/edit');
|
||||
@@ -22,9 +20,9 @@ describe('Site Loads', () => {
|
||||
|
||||
it('should load sample diagrams when clicked', () => {
|
||||
cy.contains('Sample Diagrams').click();
|
||||
cy.contains('Pie Chart').click();
|
||||
cy.contains('Pie').click();
|
||||
cy.contains('pie title Pets adopted by volunteers');
|
||||
cy.contains('Class Diagram').click();
|
||||
cy.contains('Class').click();
|
||||
cy.contains('classDiagram');
|
||||
});
|
||||
|
||||
@@ -60,7 +58,7 @@ describe('Site Loads', () => {
|
||||
// Disabled temporarily. Should be enabled after the issue is fixed in Mermaid.
|
||||
// it('should prevent setting the "securityLevel" option via URL', () => {
|
||||
// const b64State = toBase64(
|
||||
// `{"code":"graph TD\\nA[\\"<img src='https://via.placeholder.com/64' width=64 />\\"]","mermaid":"{\\"securityLevel\\": \\"loose\\", \\"theme\\": \\"forest\\"}","updateEditor":true,"autoSync":true,"updateDiagram":true}`,
|
||||
// `{"code":"graph TD\\nA[\\"<img src='https://via.placeholder.com/64' width=64 />\\"]","mermaid":"{\\"securityLevel\\": \\"loose\\", \\"theme\\": \\"forest\\"}","autoSync":true,"updateDiagram":true}`,
|
||||
// true
|
||||
// );
|
||||
// cy.on('window:confirm', () => true);
|
||||
@@ -75,7 +73,7 @@ describe('Site Loads', () => {
|
||||
|
||||
it('should allow persisting "securityLevel" using confirm dialogue', () => {
|
||||
const b64State = toBase64(
|
||||
`{"code":"graph TD\\nA[\\"<img src='https://dummyimage.com/64' width=64/>\\"]","mermaid":"{\\"securityLevel\\": \\"loose\\", \\"theme\\": \\"forest\\"}","updateEditor":true,"autoSync":true,"updateDiagram":true}`,
|
||||
`{"code":"graph TD\\nA[\\"<img src='https://dummyimage.com/64' width=64/>\\"]","mermaid":"{\\"securityLevel\\": \\"loose\\", \\"theme\\": \\"forest\\"}","autoSync":true,"updateDiagram":true}`,
|
||||
true
|
||||
);
|
||||
cy.on('window:confirm', () => false);
|
||||
|
||||
+31
-1
@@ -8,4 +8,34 @@ export const getEditor = ({ bottom = true, newline = false } = {}) =>
|
||||
.type(`${bottom ? '{pageDown}' : cmd}`)
|
||||
.type(`${newline ? '{enter}' : cmd}`);
|
||||
|
||||
export const disableDebounce = () => cy.setLocalStorage('noDebounce', 'true');
|
||||
const downloadsFolder = Cypress.config('downloadsFolder');
|
||||
|
||||
export const verifyFileSize = (
|
||||
fileType: 'history' | 'diagram',
|
||||
extension: string,
|
||||
size: number
|
||||
) => {
|
||||
const fileName = `mermaid-${fileType}-2022-01-01-000000.${extension}`;
|
||||
const filePath = `${downloadsFolder}/${fileName}`;
|
||||
cy.verifyDownload(fileName);
|
||||
cy.readFile(filePath, null, {
|
||||
log: false
|
||||
}).then((buffer) => expect((buffer as ArrayBuffer).byteLength).to.be.gt(size));
|
||||
cy.task('deleteFile', filePath);
|
||||
};
|
||||
|
||||
export const verifyFileSnapshot = (
|
||||
fileType: 'history' | 'diagram',
|
||||
extension: string,
|
||||
content: string
|
||||
) => {
|
||||
const fileName = `mermaid-${fileType}-2022-01-01-000000.${extension}`;
|
||||
const filePath = `${downloadsFolder}/${fileName}`;
|
||||
cy.verifyDownload(fileName);
|
||||
cy.readFile(filePath, null, {
|
||||
log: false
|
||||
}).then((buffer) =>
|
||||
expect(new TextDecoder('utf-8').decode(buffer as ArrayBuffer)).to.contain(content)
|
||||
);
|
||||
cy.task('deleteFile', filePath);
|
||||
};
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
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}\",\"updateEditor\":true,\"autoSync\":true,\"updateDiagram\":true}"
|
||||
"1": "{\"code\":\"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n \",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":true}"
|
||||
},
|
||||
"Check Redirect from old URL": {
|
||||
"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}\",\"updateEditor\":false,\"autoSync\":true,\"updateDiagram\":true}"
|
||||
"1": "{\"code\":\"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":true}"
|
||||
},
|
||||
"should load diagram from gist": {
|
||||
"1": "{\"code\":\"graph TD\\n A[Party] -->|Get money| B(Go shopping!!)\\n \",\"mermaid\":\"{\\n \\\"theme\\\": \\\"forest\\\",\\n \\\"test\\\": \\\"hello world\\\"\\n}\",\"updateEditor\":false,\"autoSync\":true,\"updateDiagram\":true,\"loader\":{\"type\":\"gist\",\"config\":{\"url\":\"https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a\"}}}"
|
||||
"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\":\"gist\",\"config\":{\"url\":\"https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a\"}}}"
|
||||
},
|
||||
"should load diagram from gist revision": {
|
||||
"1": "{\"code\":\"graph TD\\n A[Party] -->|Get money| B(Go shopping)\\n \",\"mermaid\":\"{\\n \\\"theme\\\": \\\"forest\\\",\\n \\\"test\\\": \\\"hello\\\"\\n}\",\"updateEditor\":false,\"autoSync\":true,\"updateDiagram\":true,\"loader\":{\"type\":\"gist\",\"config\":{\"url\":\"https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/ec9b4ab0e41e4ff6287326cd3cb47affd7851e19\"}}}"
|
||||
"1": "{\"code\":\"graph TD\\n A[Party] -->|Get money| B(Go shopping)\\n \",\"mermaid\":\"{\\n \\\"theme\\\": \\\"forest\\\",\\n \\\"test\\\": \\\"hello\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":true,\"loader\":{\"type\":\"gist\",\"config\":{\"url\":\"https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/ec9b4ab0e41e4ff6287326cd3cb47affd7851e19\"}}}"
|
||||
},
|
||||
"should load diagram from raw files": {
|
||||
"1": "{\"code\":\"graph TD\\n A[Party] -->|Get money| B(Go shopping!!)\\n \",\"mermaid\":\"{\\n \\\"theme\\\": \\\"forest\\\",\\n \\\"test\\\": \\\"hello world\\\"\\n}\",\"updateEditor\":false,\"autoSync\":true,\"updateDiagram\":true,\"loader\":{\"type\":\"files\",\"config\":{\"codeURL\":\"https://gist.githubusercontent.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/raw/4eb03887e6a41397e80bdcdbf94017c498f8f1e2/code.mmd\",\"configURL\":\"https://gist.githubusercontent.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/raw/4eb03887e6a41397e80bdcdbf94017c498f8f1e2/config.json\"}}}"
|
||||
"1": "{\"code\":\"graph TD\\n A[Party] -->|Get money| B(Go shopping!!)\\n \",\"mermaid\":\"{\\n \\\"theme\\\": \\\"forest\\\",\\n \\\"test\\\": \\\"hello world\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":true,\"loader\":{\"type\":\"files\",\"config\":{\"codeURL\":\"https://gist.githubusercontent.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/raw/4eb03887e6a41397e80bdcdbf94017c498f8f1e2/code.mmd\",\"configURL\":\"https://gist.githubusercontent.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/raw/4eb03887e6a41397e80bdcdbf94017c498f8f1e2/config.json\"}}}"
|
||||
}
|
||||
},
|
||||
"__version": "10.4.0",
|
||||
"__version": "10.7.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}\",\"updateEditor\":false,\"autoSync\":false,\"updateDiagram\":false}"
|
||||
"1": "{\"code\":\"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n C --> Test\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":false,\"updateDiagram\":false}"
|
||||
},
|
||||
"should not dim diagram when code is in sync": {
|
||||
"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}\",\"updateEditor\":false,\"autoSync\":true,\"updateDiagram\":false}"
|
||||
"1": "{\"code\":\"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n C --> Testing\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":false}"
|
||||
}
|
||||
},
|
||||
"Test themes": {
|
||||
|
||||
+27
-25
@@ -5,13 +5,14 @@
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
"dev:test": "MERMAID_DISABLE_DEBOUNCE=true yarn dev",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"lint": "prettier --check --cache --plugin-search-dir=. .;eslint --ignore-path .gitignore .",
|
||||
"lint:fix": "prettier --write --cache --plugin-search-dir=. .;eslint --fix --ignore-path .gitignore .",
|
||||
"format": "prettier --write --cache --plugin-search-dir=. .",
|
||||
"pre-commit": "lint-staged",
|
||||
"postinstall": "husky install; cypress cache prune; svelte-kit sync",
|
||||
"postinstall": "husky install; svelte-kit sync",
|
||||
"test:unit": "vitest",
|
||||
"test:ui": "vitest --ui",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
@@ -21,60 +22,61 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@cypress/snapshot": "2.1.7",
|
||||
"@sveltejs/adapter-static": "1.0.0-next.39",
|
||||
"@sveltejs/kit": "1.0.0-next.405",
|
||||
"@sveltejs/adapter-static": "1.0.0-next.42",
|
||||
"@sveltejs/kit": "1.0.0-next.480",
|
||||
"@testing-library/jest-dom": "5.16.5",
|
||||
"@testing-library/svelte": "3.1.3",
|
||||
"@types/mermaid": "8.2.9",
|
||||
"@types/pako": "1.0.3",
|
||||
"@typescript-eslint/eslint-plugin": "5.33.0",
|
||||
"@typescript-eslint/parser": "5.33.0",
|
||||
"@vitest/ui": "0.21.1",
|
||||
"@testing-library/svelte": "3.2.1",
|
||||
"@types/pako": "2.0.0",
|
||||
"@types/uuid": "8.3.4",
|
||||
"@typescript-eslint/eslint-plugin": "5.36.2",
|
||||
"@typescript-eslint/parser": "5.36.2",
|
||||
"@vitest/ui": "0.23.1",
|
||||
"autoprefixer": "10.4.8",
|
||||
"c8": "7.12.0",
|
||||
"chai": "4.3.6",
|
||||
"cssnano": "5.1.12",
|
||||
"cssnano": "5.1.13",
|
||||
"cy-verify-downloads": "0.1.8",
|
||||
"cypress": "10.4.0",
|
||||
"cypress-localstorage-commands": "2.2.0",
|
||||
"eslint": "8.21.0",
|
||||
"cypress": "10.7.0",
|
||||
"cypress-localstorage-commands": "2.2.1",
|
||||
"eslint": "8.23.0",
|
||||
"eslint-config-prettier": "8.5.0",
|
||||
"eslint-plugin-cypress": "2.12.1",
|
||||
"eslint-plugin-es": "4.1.0",
|
||||
"eslint-plugin-postcss-modules": "2.0.0",
|
||||
"eslint-plugin-svelte3": "4.0.0",
|
||||
"eslint-plugin-tailwindcss": "3.6.0",
|
||||
"eslint-plugin-tailwindcss": "3.6.1",
|
||||
"eslint-plugin-vitest": "0.0.8",
|
||||
"esserializer": "1.3.2",
|
||||
"husky": "8.0.1",
|
||||
"jsdom": "20.0.0",
|
||||
"lint-staged": "13.0.3",
|
||||
"node-html-parser": "5.4.1",
|
||||
"node-html-parser": "6.0.0",
|
||||
"postcss": "8.4.16",
|
||||
"postcss-load-config": "4.0.1",
|
||||
"prettier": "2.7.1",
|
||||
"prettier-plugin-svelte": "2.7.0",
|
||||
"svelte": "3.49.0",
|
||||
"svelte": "3.50.1",
|
||||
"svelte-preprocess": "4.10.7",
|
||||
"tailwindcss": "3.1.8",
|
||||
"tslib": "2.4.0",
|
||||
"typescript": "4.7.4",
|
||||
"vite": "3.0.6",
|
||||
"vitest": "0.21.1",
|
||||
"vitest-svelte-kit": "0.0.7"
|
||||
"typescript": "4.8.3",
|
||||
"vite": "3.1.0",
|
||||
"vitest": "0.23.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@analytics/google-analytics": "1.0.3",
|
||||
"@macfja/svelte-persistent-store": "1.3.0",
|
||||
"analytics": "0.8.1",
|
||||
"daisyui": "2.22.0",
|
||||
"analytics-plugin-plausible": "0.0.6",
|
||||
"daisyui": "2.25.0",
|
||||
"js-base64": "3.7.2",
|
||||
"mermaid": "9.1.5",
|
||||
"mermaid": "9.2.0-rc1",
|
||||
"moment": "2.29.4",
|
||||
"monaco-editor": "0.34.0",
|
||||
"monaco-mermaid": "1.0.6",
|
||||
"pako": "2.0.4",
|
||||
"random-word-slugs": "0.1.6",
|
||||
"svg-pan-zoom": "^3.6.1"
|
||||
"svg-pan-zoom": "3.6.1",
|
||||
"uuid": "9.0.0"
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.{ts,svelte,js,css,md,json}": [
|
||||
@@ -84,7 +86,7 @@
|
||||
},
|
||||
"volta": {
|
||||
"node": "18.5.0",
|
||||
"yarn": "1.22.10"
|
||||
"yarn": "1.22.19"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.7"
|
||||
|
||||
+2
-2
@@ -15,8 +15,8 @@
|
||||
<link rel="manifest" href="%sveltekit.assets%/manifest.json" />
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css"
|
||||
integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w=="
|
||||
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"
|
||||
integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A=="
|
||||
crossorigin="anonymous"
|
||||
referrerpolicy="no-referrer" />
|
||||
<link
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import type { Handle } from '@sveltejs/kit';
|
||||
|
||||
export const handle: Handle = async ({ event, resolve }) => {
|
||||
const response = await resolve(event, {
|
||||
ssr: false
|
||||
});
|
||||
|
||||
const response = await resolve(event, {});
|
||||
return response;
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { browser } from '$app/env';
|
||||
import { browser } from '$app/environment';
|
||||
import Card from '$lib/components/card/card.svelte';
|
||||
import { krokiRendererUrl, rendererUrl } from '$lib/util/env';
|
||||
import { pakoSerde } from '$lib/util/serde';
|
||||
@@ -120,12 +120,16 @@
|
||||
|
||||
const onDownloadPNG = (event: Event) => {
|
||||
exportImage(event, downloadImage);
|
||||
void logEvent('downloadPNG');
|
||||
void logEvent('download', {
|
||||
type: 'png'
|
||||
});
|
||||
};
|
||||
|
||||
const onDownloadSVG = () => {
|
||||
simulateDownload(getFileName('svg'), `data:image/svg+xml;base64,${getBase64SVG()}`);
|
||||
void logEvent('downloadSVG');
|
||||
void logEvent('download', {
|
||||
type: 'svg'
|
||||
});
|
||||
};
|
||||
|
||||
const onCopyMarkdown = () => {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
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;
|
||||
@@ -15,7 +16,7 @@
|
||||
class="bg-primary p-2 {isTabsShown ? 'pb-0' : ''} flex-none cursor-pointer"
|
||||
on:click={() => (isOpen = !isOpen)}>
|
||||
<div class="flex justify-between">
|
||||
<Tabs on:select {tabs} bind:isOpen {title} {isCloseable} />
|
||||
<Tabs on:select {tabs} bind:isOpen {title} {isCloseable} {activeTabID} />
|
||||
<div class="flex gap-x-4 items-center {isTabsShown ? '-mt-2' : ''}">
|
||||
<slot name="actions" />
|
||||
</div>
|
||||
|
||||
@@ -3,12 +3,14 @@
|
||||
import { createEventDispatcher } from 'svelte';
|
||||
import { fade } from 'svelte/transition';
|
||||
export let isCloseable = true;
|
||||
export let tabs: Tab[] = [];
|
||||
export let tabs: Tab[];
|
||||
export let title: string;
|
||||
export let isOpen = false;
|
||||
export let activeTabID: string;
|
||||
|
||||
$: activeTabID = tabs[0]?.id;
|
||||
|
||||
if (!activeTabID && tabs.length > 0) {
|
||||
activeTabID = tabs[0].id;
|
||||
}
|
||||
const dispatch = createEventDispatcher<TabEvents>();
|
||||
const toggleTabs = (tab: Tab) => {
|
||||
activeTabID = tab.id;
|
||||
|
||||
@@ -1,75 +1,95 @@
|
||||
<script lang="ts">
|
||||
import type { EditorEvents } from '$lib/types';
|
||||
import { stateStore } from '$lib/util/state';
|
||||
import type { EditorMode } from '$lib/types';
|
||||
import { stateStore, updateCode, updateConfig } from '$lib/util/state';
|
||||
import { themeStore } from '$lib/util/theme';
|
||||
import { syncDiagram } from '$lib/util/util';
|
||||
import type monaco from 'monaco-editor';
|
||||
import { createEventDispatcher, onMount } from 'svelte';
|
||||
import { onMount } from 'svelte';
|
||||
import initEditor from 'monaco-mermaid';
|
||||
import { logEvent } from '$lib/util/stats';
|
||||
import { debounceEnabled } from '$lib/util/env';
|
||||
|
||||
let divEl: HTMLDivElement = null;
|
||||
let editor: monaco.editor.IStandaloneCodeEditor;
|
||||
let Monaco;
|
||||
|
||||
export let text: string;
|
||||
export let language: string;
|
||||
export let editorOptions: monaco.editor.IStandaloneEditorConstructionOptions = {
|
||||
value: text,
|
||||
language: language,
|
||||
let Monaco: typeof monaco;
|
||||
let editorOptions: monaco.editor.IStandaloneEditorConstructionOptions = {
|
||||
minimap: {
|
||||
enabled: false
|
||||
},
|
||||
theme: 'mermaid',
|
||||
overviewRulerLanes: 0
|
||||
};
|
||||
let oldText = text;
|
||||
$: editor && Monaco?.editor.setModelLanguage(editor.getModel(), language);
|
||||
let text = '';
|
||||
|
||||
const handleTextUpdate = (newText: string) => {
|
||||
if (newText !== oldText) {
|
||||
if ($stateStore.updateEditor) {
|
||||
editor?.setValue(newText);
|
||||
}
|
||||
oldText = newText;
|
||||
stateStore.subscribe(({ errorMarkers, editorMode, code, mermaid }) => {
|
||||
if (!editor) return;
|
||||
|
||||
// Update editor text if it's different
|
||||
const newText = editorMode === 'code' ? code : mermaid;
|
||||
if (newText !== text) {
|
||||
editor.setValue(newText);
|
||||
text = newText;
|
||||
}
|
||||
editor && Monaco?.editor.setModelMarkers(editor.getModel(), 'test', $stateStore.errorMarkers);
|
||||
};
|
||||
|
||||
$: handleTextUpdate(text);
|
||||
// Update editor mode if it's different
|
||||
const language = editorMode === 'code' ? 'mermaid' : 'json';
|
||||
if (editor.getModel().getLanguageId() !== language) {
|
||||
Monaco?.editor.setModelLanguage(editor.getModel(), language);
|
||||
}
|
||||
|
||||
// Display errors if present
|
||||
if (errorMarkers.length > 0) {
|
||||
Monaco?.editor.setModelMarkers(editor.getModel(), 'test', errorMarkers);
|
||||
}
|
||||
});
|
||||
|
||||
themeStore.subscribe(({ isDark }) => {
|
||||
editor && Monaco?.editor.setTheme(isDark ? 'mermaid-dark' : 'mermaid');
|
||||
});
|
||||
|
||||
const dispatch = createEventDispatcher<EditorEvents>();
|
||||
const handleUpdate = (text: string, mode: EditorMode) => {
|
||||
if (mode === 'code') {
|
||||
updateCode(text);
|
||||
} else {
|
||||
updateConfig(text);
|
||||
}
|
||||
};
|
||||
|
||||
// Debounce state updates to avoid performance issues
|
||||
let debounce: { [key: string]: number } = {};
|
||||
const updateHandler = (newText: string) => {
|
||||
text = newText;
|
||||
const mode = $stateStore.editorMode;
|
||||
if (debounceEnabled) {
|
||||
clearTimeout(debounce[mode]);
|
||||
debounce[mode] = window.setTimeout(() => {
|
||||
handleUpdate(text, mode);
|
||||
}, 300);
|
||||
} else {
|
||||
handleUpdate(text, mode);
|
||||
}
|
||||
};
|
||||
|
||||
const loadMonaco = async () => {
|
||||
let i = 0;
|
||||
while (i++ < 10) {
|
||||
while (i++ < 500) {
|
||||
try {
|
||||
// @ts-ignore : This is a hack to handle a svelte-kit error when importing monaco.
|
||||
Monaco = monaco;
|
||||
Monaco = window.monaco;
|
||||
return;
|
||||
} catch {
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
}
|
||||
}
|
||||
alert('Loading Monaco Editor failed. Please try refreshing the page.');
|
||||
};
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
// @ts-ignore : This is a hack to handle a svelte-kit error when importing monaco.
|
||||
Monaco = monaco;
|
||||
} catch {
|
||||
await loadMonaco(); // Fix https://github.com/mermaid-js/mermaid-live-editor/issues/175
|
||||
}
|
||||
await loadMonaco(); // Fix https://github.com/mermaid-js/mermaid-live-editor/issues/175
|
||||
initEditor(Monaco);
|
||||
editor = Monaco.editor.create(divEl, editorOptions);
|
||||
editor.onDidChangeModelContent(() => {
|
||||
oldText = editor.getValue();
|
||||
dispatch('update', {
|
||||
text: oldText
|
||||
});
|
||||
updateHandler(editor.getValue());
|
||||
});
|
||||
editor.addAction({
|
||||
id: 'mermaid-render-diagram',
|
||||
|
||||
@@ -7,12 +7,15 @@
|
||||
clearHistoryData,
|
||||
getPreviousState,
|
||||
historyStore,
|
||||
loaderHistoryStore
|
||||
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;
|
||||
|
||||
@@ -32,6 +35,39 @@
|
||||
}
|
||||
];
|
||||
|
||||
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);
|
||||
@@ -46,15 +82,15 @@
|
||||
}
|
||||
};
|
||||
|
||||
const clearHistory = (date?: number): void => {
|
||||
if (!date && !prompt('Clear all saved items?')) {
|
||||
const clearHistory = (id?: string): void => {
|
||||
if (!id && !prompt('Clear all saved items?')) {
|
||||
return;
|
||||
}
|
||||
clearHistoryData(date);
|
||||
clearHistoryData(id);
|
||||
};
|
||||
|
||||
const restoreHistory = (state: State): void => {
|
||||
inputStateStore.set({ ...state, updateEditor: true, updateDiagram: true });
|
||||
const restoreHistoryItem = (state: State): void => {
|
||||
inputStateStore.set({ ...state, updateDiagram: true });
|
||||
};
|
||||
|
||||
const relativeTime = (time: number) => {
|
||||
@@ -88,6 +124,19 @@
|
||||
|
||||
<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"
|
||||
@@ -103,7 +152,7 @@
|
||||
</div>
|
||||
<ul class="p-2 space-y-2 overflow-auto h-56" id="historyList">
|
||||
{#if $historyStore.length > 0}
|
||||
{#each $historyStore as { state, time, name, url, type }}
|
||||
{#each $historyStore as { id, state, time, name, url, type }}
|
||||
<li class="rounded p-2 shadow flex-col">
|
||||
<div class="flex">
|
||||
<div class="flex-1">
|
||||
@@ -121,10 +170,10 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex gap-2 content-center">
|
||||
<button class="btn btn-success" on:click={() => restoreHistory(state)}
|
||||
<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(time)}
|
||||
<button class="btn btn-error" on:click={() => clearHistory(id)}
|
||||
><i class="fas fa-trash-alt mr-1" />Delete</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import type { HistoryEntry } from '$lib/types';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
addHistoryEntry,
|
||||
injectHistoryIDs,
|
||||
clearHistoryData,
|
||||
historyModeStore,
|
||||
historyStore
|
||||
} from './history';
|
||||
import { defaultState } from '../../util/state';
|
||||
import { get } from 'svelte/store';
|
||||
|
||||
describe('history', () => {
|
||||
it('should handle saving individual history entry', () => {
|
||||
expect(window.localStorage.getItem('manualHistoryStore')).toBe('[]');
|
||||
expect(window.localStorage.getItem('autoHistoryStore')).toBe('[]');
|
||||
|
||||
addHistoryEntry({
|
||||
state: defaultState,
|
||||
time: 12345,
|
||||
type: 'manual'
|
||||
});
|
||||
|
||||
const [manualEntry]: HistoryEntry[] = JSON.parse(
|
||||
window.localStorage.getItem('manualHistoryStore')
|
||||
);
|
||||
|
||||
expect(manualEntry.time).toBe(12345);
|
||||
expect(manualEntry.type).toBe('manual');
|
||||
expect(manualEntry.name).not.toBeNull();
|
||||
expect(manualEntry.state).not.toBeNull();
|
||||
|
||||
addHistoryEntry({
|
||||
state: defaultState,
|
||||
time: 54321,
|
||||
type: 'auto'
|
||||
});
|
||||
|
||||
const [autoEntry]: HistoryEntry[] = JSON.parse(window.localStorage.getItem('autoHistoryStore'));
|
||||
|
||||
expect(autoEntry.time).toBe(54321);
|
||||
expect(autoEntry.type).toBe('auto');
|
||||
expect(autoEntry.name).not.toBeNull();
|
||||
expect(autoEntry.state).not.toBeNull();
|
||||
|
||||
historyModeStore.set('manual');
|
||||
clearHistoryData();
|
||||
historyModeStore.set('auto');
|
||||
clearHistoryData();
|
||||
expect(window.localStorage.getItem('manualHistoryStore')).toBe('[]');
|
||||
expect(window.localStorage.getItem('autoHistoryStore')).toBe('[]');
|
||||
});
|
||||
|
||||
it('should clear history entries', () => {
|
||||
addHistoryEntry({
|
||||
state: defaultState,
|
||||
time: 12345,
|
||||
type: 'manual'
|
||||
});
|
||||
addHistoryEntry({
|
||||
state: { ...defaultState, code: 'graph TD\\n A[Christmas] -->|Get money| B(Go shopping)' },
|
||||
time: 123456,
|
||||
type: 'manual'
|
||||
});
|
||||
|
||||
historyModeStore.set('manual');
|
||||
const store: HistoryEntry[] = get(historyStore);
|
||||
expect(store.length).toBe(2);
|
||||
clearHistoryData(store[1].id);
|
||||
expect(get(historyStore).length).toBe(1);
|
||||
clearHistoryData();
|
||||
expect(get(historyStore).length).toBe(0);
|
||||
|
||||
historyModeStore.set('auto');
|
||||
addHistoryEntry({
|
||||
state: defaultState,
|
||||
time: 54321,
|
||||
type: 'auto'
|
||||
});
|
||||
addHistoryEntry({
|
||||
state: { ...defaultState, code: 'graph TD\\n A[Christmas] -->|Get money| B(Go shopping)' },
|
||||
time: 654321,
|
||||
type: 'auto'
|
||||
});
|
||||
expect(get(historyStore).length).toBe(2);
|
||||
clearHistoryData();
|
||||
expect(get(historyStore).length).toBe(0);
|
||||
// Test calling when history is empty
|
||||
clearHistoryData();
|
||||
expect(get(historyStore).length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('history migration', () => {
|
||||
it('should inject history IDs as migration', () => {
|
||||
window.localStorage.setItem(
|
||||
'manualHistoryStore',
|
||||
'[{"state":{"code":"graph TD\\n A[Halloween] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":false},"time":0,"type":"manual","name":"hollow-art"},{"state":{"code":"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":true},"time":0,"type":"manual","name":"helpful-ocean"}]'
|
||||
);
|
||||
window.localStorage.setItem(
|
||||
'autoHistoryStore',
|
||||
'[{"state":{"code":"graph TD\\n A[New Year] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":false},"time":0,"type":"auto","name":"barking-dog"},{"state":{"code":"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":true},"time":0,"type":"manual","name":"needy-mosquito"}]'
|
||||
);
|
||||
let manualHistoryStore: HistoryEntry[] = JSON.parse(
|
||||
window.localStorage.getItem('manualHistoryStore')
|
||||
);
|
||||
let autoHistoryStore: HistoryEntry[] = JSON.parse(
|
||||
window.localStorage.getItem('autoHistoryStore')
|
||||
);
|
||||
expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(false);
|
||||
expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(false);
|
||||
|
||||
injectHistoryIDs();
|
||||
|
||||
manualHistoryStore = JSON.parse(window.localStorage.getItem('manualHistoryStore'));
|
||||
autoHistoryStore = JSON.parse(window.localStorage.getItem('autoHistoryStore'));
|
||||
expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(true);
|
||||
expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import { derived, writable, get } from 'svelte/store';
|
||||
import type { Readable, Writable } from 'svelte/store';
|
||||
import { persist, localStorage } from '@macfja/svelte-persistent-store';
|
||||
import { persist, localStorage } from '$lib/util/persist';
|
||||
import { generateSlug } from 'random-word-slugs';
|
||||
import type { HistoryEntry, HistoryType } from '$lib/types';
|
||||
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;
|
||||
|
||||
@@ -41,28 +43,39 @@ export const historyStore: Readable<HistoryEntry[]> = derived(
|
||||
}
|
||||
);
|
||||
|
||||
export const addHistoryEntry = (entry: HistoryEntry): void => {
|
||||
export const addHistoryEntry = (entryToAdd: Optional<HistoryEntry, 'id'>): void => {
|
||||
const entry: HistoryEntry = {
|
||||
...entryToAdd,
|
||||
id: uuidV4()
|
||||
};
|
||||
|
||||
if (entry.type === 'loader') {
|
||||
loaderHistoryStore.update((entries) => [entry, ...entries]);
|
||||
return;
|
||||
}
|
||||
entry.name = generateSlug(2);
|
||||
if (entry.type !== 'auto') {
|
||||
|
||||
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]);
|
||||
return;
|
||||
logEvent('history', { action: 'save' });
|
||||
}
|
||||
autoHistoryStore.update((entries) => {
|
||||
if (entries.length === MAX_AUTO_HISTORY_LENGTH) {
|
||||
entries.pop();
|
||||
}
|
||||
return [entry, ...entries];
|
||||
});
|
||||
};
|
||||
|
||||
export const clearHistoryData = (time?: number): void => {
|
||||
export const clearHistoryData = (idToClear?: string): void => {
|
||||
(get(historyModeStore) === 'auto' ? autoHistoryStore : manualHistoryStore).update((entries) => {
|
||||
if (get(historyModeStore) !== 'loader') {
|
||||
entries = entries.filter((entry) => time && entry.time != time);
|
||||
entries = entries.filter(({ id }) => idToClear && id != idToClear);
|
||||
logEvent('history', { action: 'clear', type: idToClear ? 'single' : 'all' });
|
||||
}
|
||||
return entries;
|
||||
});
|
||||
@@ -75,3 +88,54 @@ export const getPreviousState = (auto: boolean): string => {
|
||||
}
|
||||
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;
|
||||
};
|
||||
|
||||
@@ -4,19 +4,18 @@
|
||||
import { logEvent } from '$lib/util/stats';
|
||||
|
||||
const samples = {
|
||||
'Flow Chart': `graph TD
|
||||
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 Diagram': `sequenceDiagram
|
||||
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 Diagram': `classDiagram
|
||||
John-->>-Alice: I feel great!`,
|
||||
Class: `classDiagram
|
||||
Animal <|-- Duck
|
||||
Animal <|-- Fish
|
||||
Animal <|-- Zebra
|
||||
@@ -36,17 +35,15 @@
|
||||
class Zebra{
|
||||
+bool is_wild
|
||||
+run()
|
||||
}
|
||||
`,
|
||||
'State Diagram': `stateDiagram-v2
|
||||
}`,
|
||||
State: `stateDiagram-v2
|
||||
[*] --> Still
|
||||
Still --> [*]
|
||||
Still --> Moving
|
||||
Moving --> Still
|
||||
Moving --> Crash
|
||||
Crash --> [*]
|
||||
`,
|
||||
'Gantt Chart': `gantt
|
||||
Crash --> [*]`,
|
||||
Gantt: `gantt
|
||||
title A Gantt Diagram
|
||||
dateFormat YYYY-MM-DD
|
||||
section Section
|
||||
@@ -54,24 +51,21 @@
|
||||
Another task :after a1 , 20d
|
||||
section Another
|
||||
Task in sec :2014-01-12 , 12d
|
||||
another task : 24d
|
||||
`,
|
||||
'Pie Chart': `pie title Pets adopted by volunteers
|
||||
another task : 24d`,
|
||||
Pie: `pie title Pets adopted by volunteers
|
||||
"Dogs" : 386
|
||||
"Cats" : 85
|
||||
"Rats" : 15
|
||||
`,
|
||||
'ER Diagram': `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
|
||||
"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
|
||||
@@ -79,37 +73,72 @@
|
||||
Do work: 1: Me, Cat
|
||||
section Go home
|
||||
Go downstairs: 5: Me
|
||||
Sit down: 3: Me
|
||||
`,
|
||||
'Git Graph': ` gitGraph
|
||||
commit
|
||||
commit
|
||||
branch develop
|
||||
checkout develop
|
||||
commit
|
||||
commit
|
||||
checkout main
|
||||
merge develop
|
||||
commit
|
||||
commit
|
||||
`
|
||||
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 eatures
|
||||
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,
|
||||
updateEditor: true,
|
||||
resetPanZoom: true
|
||||
});
|
||||
void 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 gap-2 flex-wrap p-2">
|
||||
{#each Object.keys(samples) as sample}
|
||||
<button class="btn btn-primary normal-case btn-sm" on:click={() => loadSampleDiagram(sample)}
|
||||
>{sample}</button>
|
||||
<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>
|
||||
|
||||
@@ -90,11 +90,11 @@
|
||||
error = false;
|
||||
} else if (manualUpdate) {
|
||||
manualUpdate = false;
|
||||
} else {
|
||||
} else if (code !== state.code || config !== state.mermaid) {
|
||||
outOfSync = true;
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('view fail', e);
|
||||
console.error('view fail', e);
|
||||
error = true;
|
||||
}
|
||||
});
|
||||
|
||||
Vendored
+15
-15
@@ -16,13 +16,6 @@ export interface MarkerData {
|
||||
endColumn: number;
|
||||
}
|
||||
|
||||
export interface EditorUpdateEvent {
|
||||
text: string;
|
||||
}
|
||||
export interface EditorEvents {
|
||||
update: EditorUpdateEvent;
|
||||
}
|
||||
|
||||
export interface TabEvents {
|
||||
select: Tab;
|
||||
}
|
||||
@@ -36,9 +29,9 @@ export interface Tab {
|
||||
export interface State {
|
||||
code: string;
|
||||
mermaid: string;
|
||||
updateEditor: boolean;
|
||||
updateDiagram: boolean;
|
||||
autoSync: boolean;
|
||||
editorMode?: EditorMode;
|
||||
panZoom?: boolean;
|
||||
pan?: { x: number; y: number };
|
||||
zoom?: number;
|
||||
@@ -46,6 +39,7 @@ export interface State {
|
||||
}
|
||||
|
||||
export interface ValidatedState extends State {
|
||||
editorMode: EditorMode;
|
||||
error: unknown;
|
||||
errorMarkers: MarkerData[];
|
||||
serialized: string;
|
||||
@@ -68,13 +62,16 @@ export interface LoaderConfig {
|
||||
config: GistLoaderConfig | FileLoaderConfig;
|
||||
}
|
||||
export type HistoryType = 'auto' | 'manual' | 'loader';
|
||||
export interface HistoryEntry {
|
||||
state: State;
|
||||
time: number;
|
||||
name?: string;
|
||||
type: HistoryType;
|
||||
url?: string;
|
||||
}
|
||||
export type HistoryEntry = { id: string; state: State; time: number; url?: string } & (
|
||||
| {
|
||||
type: 'loader';
|
||||
name: string;
|
||||
}
|
||||
| {
|
||||
type: HistoryType;
|
||||
name?: string;
|
||||
}
|
||||
);
|
||||
|
||||
export interface DocConfig {
|
||||
[key: string]: {
|
||||
@@ -83,4 +80,7 @@ export interface DocConfig {
|
||||
};
|
||||
}
|
||||
|
||||
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>;
|
||||
|
||||
@@ -2,3 +2,4 @@ export const rendererUrl: string =
|
||||
(import.meta.env.MERMAID_RENDERER_URL as string) ?? 'https://mermaid.ink';
|
||||
export const krokiRendererUrl: string =
|
||||
(import.meta.env.MERMAID_KROKI_RENDERER_URL as string) ?? 'https://kroki.io';
|
||||
export const debounceEnabled: boolean = import.meta.env.MERMAID_DISABLE_DEBOUNCE !== 'true';
|
||||
|
||||
@@ -54,7 +54,6 @@ export const loadDataFromUrl = async (): Promise<void> => {
|
||||
updateCodeStore({
|
||||
...state,
|
||||
autoSync: true,
|
||||
updateDiagram: true,
|
||||
updateEditor: true
|
||||
updateDiagram: true
|
||||
});
|
||||
};
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { HistoryEntry } from '$lib/types';
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
|
||||
describe('migrations', () => {
|
||||
beforeEach(() => {
|
||||
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"}]'
|
||||
);
|
||||
});
|
||||
|
||||
it('should migrate from v0 to v1', async () => {
|
||||
const { applyMigrations } = await import('./migrations');
|
||||
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);
|
||||
|
||||
applyMigrations();
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { writable, get, type Writable } from 'svelte/store';
|
||||
import { persist, localStorage } from '$lib/util/persist';
|
||||
import { injectHistoryIDs } from '$lib/components/history/history';
|
||||
import { logEvent } from './stats';
|
||||
|
||||
interface MigrationState {
|
||||
version: number;
|
||||
}
|
||||
|
||||
const migrations: { [key: string]: () => void } = {
|
||||
injectHistoryIDs
|
||||
};
|
||||
|
||||
const migrationStore: Writable<MigrationState> = persist(
|
||||
writable({ version: -1 }),
|
||||
localStorage(),
|
||||
'migrations'
|
||||
);
|
||||
|
||||
export const applyMigrations = (): void => {
|
||||
const { version }: MigrationState = get(migrationStore);
|
||||
const allMigrations = Object.entries(migrations);
|
||||
if (version === allMigrations.length - 1) {
|
||||
return;
|
||||
}
|
||||
console.log(`Current migration version: v${version}. Migrating to v${allMigrations.length - 1}.`);
|
||||
for (let i = version + 1; i < allMigrations.length; i++) {
|
||||
const [key, fn] = allMigrations[i];
|
||||
console.log(`Applying migration ${i}: ${key}.`);
|
||||
fn();
|
||||
logEvent('migration', { key });
|
||||
migrationStore.set({ version: i });
|
||||
}
|
||||
logEvent('migration', { status: 'complete', from: version, to: allMigrations.length - 1 });
|
||||
};
|
||||
@@ -0,0 +1,265 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
// Copied from https://github.com/MacFJA/svelte-persistent-store
|
||||
// # The MIT License (MIT)
|
||||
|
||||
// Copyright (c) 2021 [MacFJA](https://github.com/MacFJA)
|
||||
|
||||
// > Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// > of this software and associated documentation files (the "Software"), to deal
|
||||
// > in the Software without restriction, including without limitation the rights
|
||||
// > to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// > copies of the Software, and to permit persons to whom the Software is
|
||||
// > furnished to do so, subject to the following conditions:
|
||||
// >
|
||||
// > The above copyright notice and this permission notice shall be included in
|
||||
// > all copies or substantial portions of the Software.
|
||||
// >
|
||||
// > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// > FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// > AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// > OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// > THE SOFTWARE.
|
||||
|
||||
import ESSerializer from 'esserializer';
|
||||
import type { Writable } from 'svelte/store';
|
||||
|
||||
/**
|
||||
* Disabled warnings about missing/unavailable storages
|
||||
*/
|
||||
export function disableWarnings(): void {
|
||||
noWarnings = true;
|
||||
}
|
||||
/**
|
||||
* If set to true, no warning will be emitted if the requested Storage is not found.
|
||||
* This option can be useful when the lib is used on a server.
|
||||
*/
|
||||
let noWarnings = false;
|
||||
/**
|
||||
* List of storages where the warning have already been displayed.
|
||||
*/
|
||||
const alreadyWarnFor: Array<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';
|
||||
|
||||
if (!noWarnings && alreadyWarnFor.indexOf(storageName) === -1 && !isProduction) {
|
||||
let message = `Unable to find the ${storageName}. No data will be persisted.`;
|
||||
if (typeof window === 'undefined') {
|
||||
message +=
|
||||
'\n' +
|
||||
'Are you running on a server? Most of storages are not available while running on a server.';
|
||||
}
|
||||
console.warn(message);
|
||||
alreadyWarnFor.push(storageName);
|
||||
}
|
||||
};
|
||||
|
||||
const allowedClasses = [];
|
||||
/**
|
||||
* Add a class to the allowed list of classes to be serialized
|
||||
* @param classDef The class to add to the list
|
||||
*/
|
||||
export const addSerializableClass = (classDef: () => unknown): void => {
|
||||
allowedClasses.push(classDef);
|
||||
};
|
||||
|
||||
const serialize = (value: unknown): string => ESSerializer.serialize(value);
|
||||
const deserialize = (value: string): unknown => {
|
||||
// @TODO: to remove in the next major
|
||||
if (value === 'undefined') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (value !== null && value !== undefined) {
|
||||
try {
|
||||
return ESSerializer.deserialize(value, allowedClasses);
|
||||
} catch (e) {
|
||||
// Do nothing
|
||||
// use the value "as is"
|
||||
}
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
} catch (e) {
|
||||
// Do nothing
|
||||
// use the value "as is"
|
||||
}
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
/**
|
||||
* A store that keep it's value in time.
|
||||
*/
|
||||
export interface PersistentStore<T> extends Writable<T> {
|
||||
/**
|
||||
* Delete the store value from the persistent storage
|
||||
*/
|
||||
delete(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Storage interface
|
||||
*/
|
||||
export interface StorageInterface<T> {
|
||||
/**
|
||||
* Get a value from the storage.
|
||||
*
|
||||
* If the value doesn't exists in the storage, `null` should be returned.
|
||||
* This method MUST be synchronous.
|
||||
* @param key The key/name of the value to retrieve
|
||||
*/
|
||||
getValue(key: string): T | null;
|
||||
|
||||
/**
|
||||
* Save a value in the storage.
|
||||
* @param key The key/name of the value to save
|
||||
* @param value The value to save
|
||||
*/
|
||||
setValue(key: string, value: T): void;
|
||||
|
||||
/**
|
||||
* Remove a value from the storage
|
||||
* @param key The key/name of the value to remove
|
||||
*/
|
||||
deleteValue(key: string): void;
|
||||
}
|
||||
|
||||
export interface SelfUpdateStorageInterface<T> extends StorageInterface<T> {
|
||||
/**
|
||||
* Add a listener to the storage values changes
|
||||
* @param {string} key The key to listen
|
||||
* @param {(newValue: T) => void} listener The listener callback function
|
||||
*/
|
||||
addListener(key: string, listener: (newValue: T) => void): void;
|
||||
/**
|
||||
* Remove a listener from the storage values changes
|
||||
* @param {string} key The key that was listened
|
||||
* @param {(newValue: T) => void} listener The listener callback function to remove
|
||||
*/
|
||||
removeListener(key: string, listener: (newValue: T) => void): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a store persistent
|
||||
* @param {Writable<*>} store The store to enhance
|
||||
* @param {StorageInterface} storage The storage to use
|
||||
* @param {string} key The name of the data key
|
||||
*/
|
||||
export function persist<T>(
|
||||
store: Writable<T>,
|
||||
storage: StorageInterface<T>,
|
||||
key: string
|
||||
): PersistentStore<T> {
|
||||
const initialValue = storage.getValue(key);
|
||||
|
||||
if (null !== initialValue) {
|
||||
store.set(initialValue);
|
||||
}
|
||||
|
||||
if ((storage as SelfUpdateStorageInterface<T>).addListener) {
|
||||
(storage as SelfUpdateStorageInterface<T>).addListener(key, (newValue) => {
|
||||
store.set(newValue);
|
||||
});
|
||||
}
|
||||
|
||||
store.subscribe((value) => {
|
||||
storage.setValue(key, value);
|
||||
});
|
||||
|
||||
return {
|
||||
...store,
|
||||
delete() {
|
||||
storage.deleteValue(key);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function getBrowserStorage(
|
||||
browserStorage: Storage,
|
||||
listenExternalChanges = false
|
||||
): SelfUpdateStorageInterface<any> {
|
||||
const listeners: Array<{ 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));
|
||||
});
|
||||
}
|
||||
};
|
||||
const connect = () => {
|
||||
if (listenExternalChanges && typeof window !== 'undefined' && window?.addEventListener) {
|
||||
window.addEventListener('storage', listenerFunction);
|
||||
}
|
||||
};
|
||||
const disconnect = () => {
|
||||
if (listenExternalChanges && typeof window !== 'undefined' && window?.removeEventListener) {
|
||||
window.removeEventListener('storage', listenerFunction);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
addListener(key: string, listener: (newValue: any) => void) {
|
||||
listeners.push({ key, listener });
|
||||
if (listeners.length === 1) {
|
||||
connect();
|
||||
}
|
||||
},
|
||||
removeListener(key: string, listener: (newValue: any) => void) {
|
||||
const index = listeners.indexOf({ key, listener });
|
||||
if (index !== -1) {
|
||||
listeners.splice(index, 1);
|
||||
}
|
||||
if (listeners.length === 0) {
|
||||
disconnect();
|
||||
}
|
||||
},
|
||||
getValue(key: string): any | null {
|
||||
const value = browserStorage.getItem(key);
|
||||
return deserialize(value);
|
||||
},
|
||||
deleteValue(key: string) {
|
||||
browserStorage.removeItem(key);
|
||||
},
|
||||
setValue(key: string, value: any) {
|
||||
browserStorage.setItem(key, serialize(value));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Storage implementation that use the browser local storage
|
||||
* @param {boolean} 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) {
|
||||
return getBrowserStorage(window.localStorage, listenExternalChanges);
|
||||
}
|
||||
warnStorageNotFound('window.localStorage');
|
||||
return noopStorage();
|
||||
}
|
||||
|
||||
/**
|
||||
* Storage implementation that do nothing
|
||||
*/
|
||||
export function noopStorage(): StorageInterface<any> {
|
||||
return {
|
||||
getValue(): null {
|
||||
return null;
|
||||
},
|
||||
deleteValue() {
|
||||
// Do nothing
|
||||
},
|
||||
setValue() {
|
||||
// Do nothing
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -13,19 +13,19 @@ describe('Serde tests', () => {
|
||||
|
||||
it('should serialize and deserialize with default serde', () => {
|
||||
expect(verifySerde(defaultState)).toMatchInlineSnapshot(
|
||||
'"pako:eNpVkM1qw0AMhF9F6JRC_AI-FBo7ySXQQnPz5iC8cnZp9oe1TAm2373rmEKik5j5ZhAasQ2ascRromjgXCsPeT6ayiTbi6P-AkXxPh1ZwAXP9wl2m2OA3oQYrb--rfxugaAaTwvGIMb6n3m1qkf-0_MEdXOiKCFenp3zb5hg39gvk-tfHZM4pw5NR2VHRUsJKkoPBLfoODmyOp8-LopCMexYYZlXzR0NN1Go_JzRIWoS3msrIWGuuvW8RRokfN99i6Wkgf-h2lL-hFvF-Q9-YFyS"'
|
||||
'"pako:eNpVj81qw0AMhF9F6NRC_AI-BGK7zSXQQHLz5iBsObuk-8Naphjb7551fEl1EjPfiNGEjW8Zc7xHChqulXKQ5lCXOppeLPU3yLL9fGQB6x2PMxQfRw-99iEYd__c-GKFoJxOK8Yg2rjHslnlK__jeIaqPlEQH27vzvXPz_BVm7NO5_87OnJKfdcd5R1lDUUoKb4Q3KHlaMm0qfq0KgpFs2WFeVpb7mj4FYXKLQmlQfxldA3mEgfe4RBaEq4MpaftJi5PNtJU8w"'
|
||||
);
|
||||
});
|
||||
|
||||
it('should serialize and deserialize with base64 serde', () => {
|
||||
expect(verifySerde(defaultState, 'base64')).toMatchInlineSnapshot(
|
||||
'"base64:eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW0NocmlzdG1hc10gLS0-fEdldCBtb25leXwgQihHbyBzaG9wcGluZylcbiAgICBCIC0tPiBDe0xldCBtZSB0aGlua31cbiAgICBDIC0tPnxPbmV8IERbTGFwdG9wXVxuICAgIEMgLS0-fFR3b3wgRVtpUGhvbmVdXG4gICAgQyAtLT58VGhyZWV8IEZbZmE6ZmEtY2FyIENhcl1cbiAgIiwibWVybWFpZCI6IntcbiAgXCJ0aGVtZVwiOiBcImRlZmF1bHRcIlxufSIsInVwZGF0ZUVkaXRvciI6ZmFsc2UsImF1dG9TeW5jIjp0cnVlLCJ1cGRhdGVEaWFncmFtIjp0cnVlfQ"'
|
||||
'"base64:eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW0NocmlzdG1hc10gLS0-fEdldCBtb25leXwgQihHbyBzaG9wcGluZylcbiAgICBCIC0tPiBDe0xldCBtZSB0aGlua31cbiAgICBDIC0tPnxPbmV8IERbTGFwdG9wXVxuICAgIEMgLS0-fFR3b3wgRVtpUGhvbmVdXG4gICAgQyAtLT58VGhyZWV8IEZbZmE6ZmEtY2FyIENhcl1cbiAgIiwibWVybWFpZCI6IntcbiAgXCJ0aGVtZVwiOiBcImRlZmF1bHRcIlxufSIsImF1dG9TeW5jIjp0cnVlLCJ1cGRhdGVEaWFncmFtIjp0cnVlfQ"'
|
||||
);
|
||||
});
|
||||
|
||||
it('should serialize and deserialize with pako serde', () => {
|
||||
expect(verifySerde(defaultState, 'pako')).toMatchInlineSnapshot(
|
||||
'"pako:eNpVkM1qw0AMhF9F6JRC_AI-FBo7ySXQQnPz5iC8cnZp9oe1TAm2373rmEKik5j5ZhAasQ2ascRromjgXCsPeT6ayiTbi6P-AkXxPh1ZwAXP9wl2m2OA3oQYrb--rfxugaAaTwvGIMb6n3m1qkf-0_MEdXOiKCFenp3zb5hg39gvk-tfHZM4pw5NR2VHRUsJKkoPBLfoODmyOp8-LopCMexYYZlXzR0NN1Go_JzRIWoS3msrIWGuuvW8RRokfN99i6Wkgf-h2lL-hFvF-Q9-YFyS"'
|
||||
'"pako:eNpVj81qw0AMhF9F6NRC_AI-BGK7zSXQQHLz5iBsObuk-8Naphjb7551fEl1EjPfiNGEjW8Zc7xHChqulXKQ5lCXOppeLPU3yLL9fGQB6x2PMxQfRw-99iEYd__c-GKFoJxOK8Yg2rjHslnlK__jeIaqPlEQH27vzvXPz_BVm7NO5_87OnJKfdcd5R1lDUUoKb4Q3KHlaMm0qfq0KgpFs2WFeVpb7mj4FYXKLQmlQfxldA3mEgfe4RBaEq4MpaftJi5PNtJU8w"'
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
+11
-10
@@ -1,5 +1,5 @@
|
||||
import { writable, get, derived } from 'svelte/store';
|
||||
import { persist, localStorage } from '@macfja/svelte-persistent-store';
|
||||
import { persist, localStorage } from './persist';
|
||||
import { saveStatistics } from './stats';
|
||||
import { serializeState, deserializeState } from './serde';
|
||||
import { cmdKey } from './util';
|
||||
@@ -23,7 +23,6 @@ export const defaultState: State = {
|
||||
null,
|
||||
2
|
||||
),
|
||||
updateEditor: false,
|
||||
autoSync: true,
|
||||
updateDiagram: true
|
||||
};
|
||||
@@ -48,8 +47,10 @@ export const stateStore: Readable<ValidatedState> = derived([inputStateStore], (
|
||||
...state,
|
||||
serialized: '',
|
||||
errorMarkers: [],
|
||||
error: undefined
|
||||
error: undefined,
|
||||
editorMode: state.editorMode ?? 'code'
|
||||
};
|
||||
|
||||
// No changes should be done to fields part of `state`.
|
||||
try {
|
||||
processed.serialized = serializeState(state);
|
||||
@@ -102,11 +103,12 @@ export const loadState = (data: string): void => {
|
||||
state.mermaid = defaultState.mermaid;
|
||||
}
|
||||
}
|
||||
updateCodeStore({ ...state, updateEditor: true });
|
||||
updateCodeStore({ ...state });
|
||||
};
|
||||
|
||||
export const updateCodeStore = (newState: Partial<State>): void => {
|
||||
inputStateStore.update((state) => {
|
||||
// console.log({ newState, state });
|
||||
return { ...state, ...newState };
|
||||
});
|
||||
};
|
||||
@@ -115,10 +117,9 @@ let prompted = false;
|
||||
export const updateCode = (
|
||||
code: string,
|
||||
{
|
||||
updateEditor,
|
||||
updateDiagram = false,
|
||||
resetPanZoom = false
|
||||
}: { updateEditor: boolean; updateDiagram?: boolean; resetPanZoom?: boolean }
|
||||
}: { updateDiagram?: boolean; resetPanZoom?: boolean } = {}
|
||||
): void => {
|
||||
saveStatistics(code);
|
||||
const lines = (code.match(/\n/g) || '').length + 1;
|
||||
@@ -140,13 +141,13 @@ export const updateCode = (
|
||||
state.pan = undefined;
|
||||
state.zoom = undefined;
|
||||
}
|
||||
return { ...state, code, updateEditor, updateDiagram };
|
||||
return { ...state, code, updateDiagram };
|
||||
});
|
||||
};
|
||||
|
||||
export const updateConfig = (config: string, updateEditor: boolean): void => {
|
||||
export const updateConfig = (config: string): void => {
|
||||
inputStateStore.update((state) => {
|
||||
return { ...state, mermaid: config, updateEditor };
|
||||
return { ...state, mermaid: config };
|
||||
});
|
||||
};
|
||||
|
||||
@@ -157,7 +158,7 @@ export const toggleDarkTheme = (dark: boolean): void => {
|
||||
config.theme = dark ? 'dark' : 'default';
|
||||
}
|
||||
|
||||
return { ...state, mermaid: JSON.stringify(config, null, 2), updateEditor: true };
|
||||
return { ...state, mermaid: JSON.stringify(config, null, 2) };
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
+15
-5
@@ -1,4 +1,4 @@
|
||||
import { browser } from '$app/env';
|
||||
import { browser } from '$app/environment';
|
||||
import type { AnalyticsInstance } from 'analytics';
|
||||
|
||||
export let analytics: AnalyticsInstance;
|
||||
@@ -8,18 +8,28 @@ export const initAnalytics = async (): Promise<void> => {
|
||||
try {
|
||||
const { Analytics } = await import('analytics');
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const googleAnalytics = await import('@analytics/google-analytics');
|
||||
const googleAnalytics = (await import('@analytics/google-analytics')).default;
|
||||
const plausible = (await import('analytics-plugin-plausible')).default;
|
||||
analytics = Analytics({
|
||||
app: 'mermaid-live-editor',
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
plugins: [
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
|
||||
googleAnalytics.init({
|
||||
trackingId: 'UA-153180559-1'
|
||||
googleAnalytics({
|
||||
measurementIds: ['UA-153180559-1']
|
||||
}),
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
plausible({
|
||||
domain: 'mermaid.live',
|
||||
hashMode: false,
|
||||
trackLocalhost: false, // By default 'false'
|
||||
apiHost: 'https://plausible.io'
|
||||
})
|
||||
]
|
||||
});
|
||||
} catch {
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
console.info('Analytics blocked ;)');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { writable } from 'svelte/store';
|
||||
import type { Writable } from 'svelte/store';
|
||||
import { persist, localStorage } from '@macfja/svelte-persistent-store';
|
||||
import { persist, localStorage } from '$lib/util/persist';
|
||||
import { logEvent } from './stats';
|
||||
|
||||
export interface ThemeConfig {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { initURLSubscription, loadState, updateCodeStore } from './state';
|
||||
import { analytics, initAnalytics } from './stats';
|
||||
import { loadDataFromUrl } from './fileLoaders/loader';
|
||||
import { initLoading } from './loading';
|
||||
import { applyMigrations } from './migrations';
|
||||
|
||||
export const loadStateFromURL = (): void => {
|
||||
loadState(window.location.hash.slice(1));
|
||||
@@ -14,6 +15,7 @@ export const syncDiagram = (): void => {
|
||||
};
|
||||
|
||||
export const initHandler = async (): Promise<void> => {
|
||||
applyMigrations();
|
||||
loadStateFromURL();
|
||||
await initLoading('Loading Gist...', loadDataFromUrl().catch(console.error));
|
||||
syncDiagram();
|
||||
@@ -24,5 +26,3 @@ export const initHandler = async (): Promise<void> => {
|
||||
|
||||
export const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
|
||||
export const cmdKey = isMac ? 'Cmd' : 'Ctrl';
|
||||
|
||||
export const debounceEnabled = window.localStorage.getItem('noDebounce') !== 'true';
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
export const prerender = true;
|
||||
export const csr = true;
|
||||
export const ssr = false;
|
||||
@@ -1,2 +0,0 @@
|
||||
import { GET as manifestGet } from '../manifest.json';
|
||||
export const GET = manifestGet;
|
||||
@@ -6,20 +6,12 @@
|
||||
import View from '$lib/components/view.svelte';
|
||||
import Card from '$lib/components/card/card.svelte';
|
||||
import History from '$lib/components/history/history.svelte';
|
||||
import { updateCode, updateConfig, inputStateStore, stateStore } from '$lib/util/state';
|
||||
import { cmdKey, debounceEnabled, initHandler, syncDiagram } from '$lib/util/util';
|
||||
import { inputStateStore, stateStore, updateCodeStore } from '$lib/util/state';
|
||||
import { cmdKey, initHandler, syncDiagram } from '$lib/util/util';
|
||||
import { onMount } from 'svelte';
|
||||
import type { EditorUpdateEvent, State, Tab, DocConfig } from '$lib/types';
|
||||
import type { Tab, DocConfig, EditorMode, ValidatedState } from '$lib/types';
|
||||
import { base } from '$app/paths';
|
||||
|
||||
type Modes = 'code' | 'config';
|
||||
type Languages = 'mermaid' | 'json';
|
||||
|
||||
let selectedMode: Modes = 'code';
|
||||
const languageMap: { [key in Modes]: Languages } = {
|
||||
code: 'mermaid',
|
||||
config: 'json'
|
||||
};
|
||||
const docURLBase = 'https://mermaid-js.github.io/mermaid';
|
||||
const docMap: DocConfig = {
|
||||
graph: {
|
||||
@@ -60,34 +52,23 @@
|
||||
config: '/#/gitgraph?id=gitgraph-specific-configuration-options'
|
||||
}
|
||||
};
|
||||
let text = '';
|
||||
let docURL = docURLBase;
|
||||
let language: Languages = 'mermaid';
|
||||
const handleModeUpdate = (mode: Modes) => {
|
||||
if (mode === 'code') {
|
||||
text = $stateStore.code;
|
||||
} else {
|
||||
text = $stateStore.mermaid;
|
||||
}
|
||||
};
|
||||
$: language = languageMap[selectedMode];
|
||||
$: handleModeUpdate(selectedMode);
|
||||
|
||||
stateStore.subscribe((state: State) => {
|
||||
if (state.updateEditor) {
|
||||
text = selectedMode === 'code' ? state.code : state.mermaid;
|
||||
}
|
||||
const codeTypeMatch = /([\S]+)[\s\n]/.exec(state.code);
|
||||
let activeTabID = 'code';
|
||||
stateStore.subscribe(({ code, editorMode }: ValidatedState) => {
|
||||
activeTabID = editorMode;
|
||||
const codeTypeMatch = /([\S]+)[\s\n]/.exec(code);
|
||||
if (codeTypeMatch && codeTypeMatch.length > 1) {
|
||||
const docKey = codeTypeMatch[1];
|
||||
const docConfig = docMap[docKey] ?? { code: '' };
|
||||
docURL = docURLBase + (docConfig[selectedMode] ?? docConfig.code ?? '');
|
||||
docURL = docURLBase + (docConfig[editorMode] ?? docConfig.code ?? '');
|
||||
}
|
||||
});
|
||||
|
||||
const tabSelectHandler = (message: CustomEvent<Tab>) => {
|
||||
selectedMode = message.detail.id === 'code' ? 'code' : 'config';
|
||||
$inputStateStore.updateEditor = true;
|
||||
const editorMode: EditorMode = message.detail.id === 'code' ? 'code' : 'config';
|
||||
updateCodeStore({ editorMode });
|
||||
};
|
||||
|
||||
const tabs: Tab[] = [
|
||||
{
|
||||
id: 'code',
|
||||
@@ -101,29 +82,6 @@
|
||||
}
|
||||
];
|
||||
|
||||
const handleUpdate = (text: string) => {
|
||||
if (selectedMode === 'code') {
|
||||
updateCode(text, {
|
||||
updateEditor: false
|
||||
});
|
||||
} else {
|
||||
updateConfig(text, false);
|
||||
}
|
||||
};
|
||||
|
||||
let debounce: { [key: string]: number } = {};
|
||||
const updateHandler = ({ detail: { text } }: CustomEvent<EditorUpdateEvent>) => {
|
||||
console.log({ debounceEnabled });
|
||||
if (debounceEnabled) {
|
||||
clearTimeout(debounce[selectedMode]);
|
||||
debounce[selectedMode] = window.setTimeout(() => {
|
||||
handleUpdate(text);
|
||||
}, 300);
|
||||
} else {
|
||||
handleUpdate(text);
|
||||
}
|
||||
};
|
||||
|
||||
onMount(async () => {
|
||||
await initHandler();
|
||||
const resizer = document.getElementById('resizeHandler');
|
||||
@@ -150,7 +108,7 @@
|
||||
<Navbar />
|
||||
<div class="flex-1 flex overflow-hidden">
|
||||
<div class="hidden md:flex flex-col" id="editorPane" style="width: 40%">
|
||||
<Card on:select={tabSelectHandler} {tabs} isCloseable={false} title="Mermaid">
|
||||
<Card on:select={tabSelectHandler} {tabs} isCloseable={false} {activeTabID} title="Mermaid">
|
||||
<div slot="actions" class="flex flex-row items-center">
|
||||
<div class="form-control flex-row items-center">
|
||||
<label class="cursor-pointer label" for="autoSync">
|
||||
@@ -176,7 +134,7 @@
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<Editor on:update={updateHandler} {language} {text} />
|
||||
<Editor />
|
||||
</Card>
|
||||
|
||||
<div class="-mt-2">
|
||||
@@ -1,28 +0,0 @@
|
||||
import { base } from '$app/paths';
|
||||
export const GET = (): { body: unknown } => {
|
||||
return {
|
||||
body: {
|
||||
short_name: 'Mermaid',
|
||||
name: 'Mermaid Live Editor',
|
||||
icons: [
|
||||
{
|
||||
src: `${base}/icon-192.png`,
|
||||
type: 'image/png',
|
||||
sizes: '192x192'
|
||||
},
|
||||
{
|
||||
src: `${base}/icon-512.png`,
|
||||
type: 'image/png',
|
||||
sizes: '512x512'
|
||||
}
|
||||
],
|
||||
start_url: `${base}/edit/`,
|
||||
background_color: '#6366F1',
|
||||
display: 'standalone',
|
||||
scope: `${base}/edit/`,
|
||||
theme_color: '#6366F1',
|
||||
description: 'FlowChart & Diagrams Editor.',
|
||||
orientation: 'landscape'
|
||||
}
|
||||
};
|
||||
};
|
||||
+8
-1
@@ -1,4 +1,11 @@
|
||||
import matchers from '@testing-library/jest-dom/matchers';
|
||||
import { expect } from 'vitest';
|
||||
import { expect, beforeAll, vi } from 'vitest';
|
||||
|
||||
expect.extend(matchers);
|
||||
|
||||
// TODO: Remove once https://github.com/sveltejs/kit/issues/6259 is closed.
|
||||
beforeAll(() => {
|
||||
vi.mock('$app/environment', () => ({
|
||||
browser: 'window' in globalThis
|
||||
}));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"short_name": "Mermaid",
|
||||
"name": "Mermaid Live Editor",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/icon-192.png",
|
||||
"type": "image/png",
|
||||
"sizes": "192x192"
|
||||
},
|
||||
{
|
||||
"src": "/icon-512.png",
|
||||
"type": "image/png",
|
||||
"sizes": "512x512"
|
||||
}
|
||||
],
|
||||
"start_url": "/edit/",
|
||||
"background_color": "#6366F1",
|
||||
"display": "standalone",
|
||||
"scope": "/edit/",
|
||||
"theme_color": "#6366F1",
|
||||
"description": "FlowChart & Diagrams Editor.",
|
||||
"orientation": "landscape"
|
||||
}
|
||||
+1
-4
@@ -19,10 +19,7 @@ const config = {
|
||||
base: `/mermaid-live-editor`
|
||||
}
|
||||
: {},
|
||||
trailingSlash: 'ignore',
|
||||
prerender: {
|
||||
default: true
|
||||
}
|
||||
trailingSlash: 'ignore'
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+2
-1
@@ -5,7 +5,8 @@
|
||||
"src/**/*.svelte",
|
||||
"cypress/**/*.ts",
|
||||
"cypress/**/*.js",
|
||||
"static/**/*.js"
|
||||
"static/**/*.js",
|
||||
"static/**/*.json"
|
||||
],
|
||||
"compilerOptions": {
|
||||
"resolveJsonModule": true,
|
||||
|
||||
@@ -4,9 +4,6 @@ const config = {
|
||||
plugins: [sveltekit()],
|
||||
envPrefix: 'MERMAID_',
|
||||
optimizeDeps: { include: ['mermaid'] },
|
||||
ssr: {
|
||||
noExternal: ['@macfja/svelte-persistent-store']
|
||||
},
|
||||
server: {
|
||||
port: 3000,
|
||||
host: true
|
||||
|
||||
Reference in New Issue
Block a user