Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e69b4def13 | ||
|
|
10585650fd | ||
|
|
861fd442c2 | ||
|
|
cab7ae5f65 | ||
|
|
31de1c79aa | ||
|
|
0ea5d812b2 | ||
|
|
79fb9d1cb1 | ||
|
|
4c965fbe2e | ||
|
|
b4fe60d49c | ||
|
|
e04bb15c35 | ||
|
|
1c6371cb8c | ||
|
|
0b89c8d7e8 | ||
|
|
bb536e9c36 | ||
|
|
76c421924c | ||
|
|
0e331a42d8 | ||
|
|
9cd19f2a81 | ||
|
|
a08d392b1b | ||
|
|
54cdae4f40 | ||
|
|
caa536b781 | ||
|
|
a2d95320b8 | ||
|
|
3009619e79 | ||
|
|
6977a3d4a3 | ||
|
|
e83e287546 | ||
|
|
30d67e1d6f | ||
|
|
5d66248c78 | ||
|
|
754f80dd94 | ||
|
|
2cff54b33d | ||
|
|
ddc1291d1b | ||
|
|
dd17fd7e3f | ||
|
|
33e27738af | ||
|
|
a02bd4b3ba | ||
|
|
f95c42db1e | ||
|
|
457cd02cc4 | ||
|
|
ac7cfbd286 | ||
|
|
ed093e3917 | ||
|
|
aa31a2a095 | ||
|
|
19b1ca9b2e | ||
|
|
16f032328d | ||
|
|
3394941b99 | ||
|
|
d7e38368b1 | ||
|
|
e7a777c525 | ||
|
|
1393b9985e | ||
|
|
02f3700a36 | ||
|
|
a4e10b936b | ||
|
|
af5caacc1a | ||
|
|
4dba94c9e4 | ||
|
|
bc55e97545 | ||
|
|
66a75e72ea | ||
|
|
d77d87375f | ||
|
|
92916e6f8b | ||
|
|
29387519dc | ||
|
|
e50678b530 | ||
|
|
0c48f390f1 | ||
|
|
0d4ff007fc | ||
|
|
6a91eb4a91 | ||
|
|
8ed982e5d2 | ||
|
|
d401ece398 |
@@ -0,0 +1,8 @@
|
||||
docs/**
|
||||
.svelte-kit/**
|
||||
static/**
|
||||
build/**
|
||||
node_modules/**
|
||||
coverage/**
|
||||
__snapshots__/**
|
||||
snapshots.js
|
||||
+1
-1
@@ -7,7 +7,7 @@ module.exports = {
|
||||
// 'plugin:@typescript-eslint/recommended-requiring-type-checking',
|
||||
'prettier'
|
||||
],
|
||||
plugins: ['svelte3', 'tailwindcss', '@typescript-eslint', 'es'],
|
||||
plugins: ['svelte3', 'tailwindcss', '@typescript-eslint', 'es', 'vitest'],
|
||||
ignorePatterns: [
|
||||
'docs/*',
|
||||
'*.cjs',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Cypress Tests
|
||||
name: Tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
@@ -30,17 +30,18 @@ jobs:
|
||||
node-version: 16
|
||||
cache: 'yarn'
|
||||
|
||||
- name: Build & Lint
|
||||
- name: Lint & Test
|
||||
run: |
|
||||
yarn install
|
||||
yarn build
|
||||
yarn lint
|
||||
yarn test:unit
|
||||
|
||||
# Install NPM dependencies, cache them correctly
|
||||
# and run all Cypress tests
|
||||
- name: Cypress run
|
||||
uses: cypress-io/github-action@v3
|
||||
with:
|
||||
build: yarn build
|
||||
start: yarn preview
|
||||
wait-on: 'http://localhost:3000'
|
||||
record: true
|
||||
@@ -9,5 +9,6 @@ yarn-error.log
|
||||
/build
|
||||
/functions
|
||||
/snapshots.js
|
||||
/cypress/downloads
|
||||
/cypress/videos
|
||||
/cypress/screenshots
|
||||
|
||||
@@ -3,4 +3,6 @@ docs/**
|
||||
static/**
|
||||
build/**
|
||||
node_modules/**
|
||||
coverage/**
|
||||
__snapshots__/**
|
||||
snapshots.js
|
||||
Vendored
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"type": "pwa-chrome",
|
||||
"request": "launch",
|
||||
"name": "Launch Chrome against localhost",
|
||||
"url": "http://localhost:3000",
|
||||
"webRoot": "${workspaceFolder}"
|
||||
}
|
||||
]
|
||||
}
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
# Stop : press ctrl + c
|
||||
# or
|
||||
# docker stop mermaid-live-editor
|
||||
FROM node:18.3.0 as mermaid-live-editor-builder
|
||||
FROM node:18.4.0 as mermaid-live-editor-builder
|
||||
COPY --chown=node:node . /home
|
||||
WORKDIR /home
|
||||
RUN yarn install
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ Live editor only has a single version, which will be maintained.
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------ |
|
||||
| latest | :white_check_mark: |
|
||||
| latest | :white_check_mark: |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
|
||||
+7
-2
@@ -1,6 +1,6 @@
|
||||
import { defineConfig } from 'cypress';
|
||||
import fs from 'fs';
|
||||
|
||||
import { isFileExist, findFiles } from 'cy-verify-downloads';
|
||||
export default defineConfig({
|
||||
projectId: '2ckppp',
|
||||
viewportWidth: 1440,
|
||||
@@ -11,11 +11,16 @@ export default defineConfig({
|
||||
e2e: {
|
||||
setupNodeEvents(on, config) {
|
||||
on('task', {
|
||||
isFileExist,
|
||||
findFiles,
|
||||
deleteFile(path) {
|
||||
fs.rmSync(path);
|
||||
return null;
|
||||
},
|
||||
readFileMaybe(filename) {
|
||||
if (fs.existsSync(filename)) {
|
||||
return fs.readFileSync(filename, 'utf8');
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
+4
-6
@@ -1,12 +1,10 @@
|
||||
{
|
||||
"plugins": ["cypress", "mocha"],
|
||||
"extends": ["plugin:cypress/recommended", "plugin:mocha/recommended"],
|
||||
"plugins": ["cypress"],
|
||||
"extends": ["plugin:cypress/recommended"],
|
||||
"rules": {
|
||||
"jest/expect-expect": "off",
|
||||
"mocha/no-mocha-arrows": "off"
|
||||
"jest/expect-expect": "off"
|
||||
},
|
||||
"env": {
|
||||
"cypress/globals": true,
|
||||
"mocha": true
|
||||
"cypress/globals": true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ describe('Check actions', () => {
|
||||
cy.clearLocalStorage();
|
||||
cy.visit('/edit');
|
||||
});
|
||||
|
||||
it('should update markdown code', () => {
|
||||
cy.get('#markdown')
|
||||
.invoke('val')
|
||||
@@ -21,4 +22,33 @@ describe('Check actions', () => {
|
||||
cy.contains('Load Gist').click();
|
||||
cy.contains('Go shopping!!');
|
||||
});
|
||||
|
||||
it('should download png and svg', () => {
|
||||
const now = new Date(2022, 0, 1).getTime();
|
||||
cy.clock(now);
|
||||
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);
|
||||
};
|
||||
|
||||
verifyFileSize('png', 21_000);
|
||||
verifyFileSize('svg', 11_000);
|
||||
|
||||
// Verify downloaded file is different for different diagrams
|
||||
cy.contains('Sample Diagrams').click();
|
||||
cy.contains('ER Diagram').click();
|
||||
|
||||
verifyFileSize('png', 46_000);
|
||||
verifyFileSize('svg', 12_000);
|
||||
|
||||
cy.clock().invoke('restore');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,12 +1,22 @@
|
||||
describe('Auto sync tests', () => {
|
||||
const cmd = Cypress.platform === 'darwin' ? 'meta' : 'ctrl';
|
||||
const getEditor = ({ bottom = true, newline = false } = {}) =>
|
||||
cy
|
||||
.get('#editor textarea:first')
|
||||
.click()
|
||||
.focused()
|
||||
.type(`${bottom ? '{pageDown}' : `{${cmd}}`}`)
|
||||
.type(`${newline ? '{enter}' : `{${cmd}}`}`);
|
||||
|
||||
beforeEach(() => {
|
||||
cy.clearLocalStorage();
|
||||
cy.visit('/');
|
||||
});
|
||||
|
||||
it('should dim diagram when code is edited', () => {
|
||||
cy.contains('Auto sync').click();
|
||||
cy.get('#view').should('not.have.class', 'outOfSync');
|
||||
cy.get('#editor').type(' C --> Test');
|
||||
getEditor().type(' C --> Test');
|
||||
cy.get('#view').should('have.class', 'outOfSync');
|
||||
cy.getLocalStorage('codeStore').snapshot();
|
||||
});
|
||||
@@ -18,26 +28,39 @@ describe('Auto sync tests', () => {
|
||||
cy.get('#autoSync').check();
|
||||
cy.get('[data-cy=sync]').should('not.exist');
|
||||
});
|
||||
|
||||
it('should not dim diagram when code is in sync', () => {
|
||||
cy.contains('Auto sync').click();
|
||||
cy.get('#view').should('not.have.class', 'outOfSync');
|
||||
cy.get('#editor').type(' C --> Test');
|
||||
getEditor().type(' C --> Test');
|
||||
cy.get('#view').should('have.class', 'outOfSync');
|
||||
cy.get('[data-cy=sync]').click();
|
||||
cy.get('#view').should('not.have.class', 'outOfSync');
|
||||
cy.get('#autoSync').check();
|
||||
cy.get('#editor').type('ing');
|
||||
getEditor().type('ing');
|
||||
cy.get('#view').should('not.have.class', 'outOfSync');
|
||||
cy.getLocalStorage('codeStore').snapshot();
|
||||
});
|
||||
|
||||
it('supports commenting code out/in', () => {
|
||||
const cmd = Cypress.platform === 'darwin' ? 'meta' : 'ctrl';
|
||||
|
||||
cy.get('#editor').type(`{uparrow}{${cmd}}/`);
|
||||
getEditor().type(`{uparrow}{${cmd}}/`);
|
||||
cy.get('#view').contains('Car').should('not.exist');
|
||||
|
||||
cy.get('#editor').type(`{uparrow}{${cmd}}/`);
|
||||
getEditor().type(`{uparrow}{${cmd}}/`);
|
||||
cy.get('#view').contains('Car').should('exist');
|
||||
});
|
||||
|
||||
it('supports editing code when code is incorrect', () => {
|
||||
cy.visit(
|
||||
'/edit#pako:eNpljjEKwzAMRa8SNOcEnlt6gK5eVFvYJsgOqkwpIXevg9smEE1PnyfxF3DFExgISW-CczQ2D21cYU7a-SGYXRwyvTp9jUhuKlVP-eHy7zA-leQsMEmg_QOM0BLG5FujZVMsaCQmC6ahR5ks2Lw2r84ela4-aREwKpVGwKrl_s7ut3fnkjAIcg_XDzuaUhs'
|
||||
);
|
||||
cy.get('#errorContainer').should('not.exist');
|
||||
getEditor({ newline: true }).type(`branch test`);
|
||||
cy.get('#editor').contains('branch test').should('exist');
|
||||
cy.get('#errorContainer')
|
||||
.contains(
|
||||
'Error: Trying to checkout branch which is not yet created. (Help try using "branch master")'
|
||||
)
|
||||
.should('exist');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -47,7 +47,6 @@ describe('Save History', () => {
|
||||
});
|
||||
|
||||
// TODO: Fix #639
|
||||
// eslint-disable-next-line mocha/no-skipped-tests
|
||||
xit('should auto save history', () => {
|
||||
cy.get('#editor').type(' C --> HistoryTest');
|
||||
cy.tick(70000);
|
||||
|
||||
@@ -32,7 +32,6 @@ describe('Test themes', () => {
|
||||
});
|
||||
|
||||
describe('Test dark mode', () => {
|
||||
// eslint-disable-next-line mocha/no-hooks-for-single-case
|
||||
beforeEach(() => {
|
||||
cy.clearLocalStorage();
|
||||
cy.visit('/edit', {
|
||||
|
||||
@@ -16,7 +16,7 @@ module.exports = {
|
||||
"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\"}}}"
|
||||
}
|
||||
},
|
||||
"__version": "10.0.3",
|
||||
"__version": "10.3.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}"
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
|
||||
// Import commands.js using ES2015 syntax:
|
||||
import './commands';
|
||||
require('cy-verify-downloads').addCustomCommand();
|
||||
|
||||
// Alternatively you can use CommonJS syntax:
|
||||
// require('./commands')
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"allowJs": true,
|
||||
"types": ["cypress", "cypress-localstorage-commands"]
|
||||
"types": ["cypress", "cypress-localstorage-commands", "cy-verify-downloads"]
|
||||
},
|
||||
"include": ["**/*.ts"]
|
||||
}
|
||||
|
||||
+63
-50
@@ -1,66 +1,79 @@
|
||||
{
|
||||
"name": "mermaid-live-editor",
|
||||
"version": "2.0.67",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"dev": "svelte-kit dev --host 0.0.0.0",
|
||||
"build": "svelte-kit build",
|
||||
"preview": "svelte-kit preview",
|
||||
"lint": "prettier --check --plugin-search-dir=. .;eslint --ignore-path .gitignore .",
|
||||
"lint:fix": "prettier --write --plugin-search-dir=. .;eslint --fix --ignore-path .gitignore .",
|
||||
"format": "prettier --write --plugin-search-dir=. .",
|
||||
"dev": "vite dev --host 0.0.0.0",
|
||||
"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",
|
||||
"test": "cypress run",
|
||||
"postinstall": "husky install; cypress cache prune; svelte-kit sync",
|
||||
"test:unit": "vitest",
|
||||
"test:ui": "vitest --ui",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"test:browser": "cypress run",
|
||||
"test": "test:unit && test:browser",
|
||||
"cy": "cypress open"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@cypress/snapshot": "^2.1.7",
|
||||
"@cypress/snapshot": "2.1.7",
|
||||
"@sveltejs/adapter-static": "1.0.0-next.34",
|
||||
"@sveltejs/kit": "1.0.0-next.350",
|
||||
"@types/mermaid": "^8.2.9",
|
||||
"@types/pako": "^1.0.3",
|
||||
"@typescript-eslint/eslint-plugin": "^4.33.0",
|
||||
"@typescript-eslint/parser": "^4.33.0",
|
||||
"autoprefixer": "^10.4.7",
|
||||
"chai": "^4.3.6",
|
||||
"cssnano": "^5.1.11",
|
||||
"cypress": "10.0.3",
|
||||
"cypress-localstorage-commands": "^2.1.0",
|
||||
"eslint": "^7.32.0",
|
||||
"eslint-config-prettier": "^8.5.0",
|
||||
"eslint-plugin-cypress": "^2.12.1",
|
||||
"eslint-plugin-es": "^4.1.0",
|
||||
"eslint-plugin-mocha": "^10.0.5",
|
||||
"eslint-plugin-postcss-modules": "^2.0.0",
|
||||
"eslint-plugin-svelte3": "^3.4.1",
|
||||
"eslint-plugin-tailwindcss": "^3.5.2",
|
||||
"husky": "^8.0.1",
|
||||
"lint-staged": "13.0.1",
|
||||
"mocha": "^10.0.0",
|
||||
"node-html-parser": "^5.3.3",
|
||||
"postcss": "^8.4.14",
|
||||
"postcss-load-config": "^4.0.1",
|
||||
"prettier": "~2.6.2",
|
||||
"prettier-plugin-svelte": "^2.7.0",
|
||||
"svelte": "^3.48.0",
|
||||
"@sveltejs/kit": "1.0.0-next.359",
|
||||
"@testing-library/jest-dom": "5.16.4",
|
||||
"@testing-library/svelte": "3.1.3",
|
||||
"@types/mermaid": "8.2.9",
|
||||
"@types/pako": "1.0.3",
|
||||
"@typescript-eslint/eslint-plugin": "5.30.5",
|
||||
"@typescript-eslint/parser": "5.30.5",
|
||||
"@vitest/ui": "0.17.0",
|
||||
"autoprefixer": "10.4.7",
|
||||
"c8": "7.11.3",
|
||||
"chai": "4.3.6",
|
||||
"cssnano": "5.1.12",
|
||||
"cy-verify-downloads": "0.1.8",
|
||||
"cypress": "10.3.0",
|
||||
"cypress-localstorage-commands": "2.1.0",
|
||||
"eslint": "8.19.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-vitest": "0.0.8",
|
||||
"husky": "8.0.1",
|
||||
"jsdom": "20.0.0",
|
||||
"lint-staged": "13.0.3",
|
||||
"node-html-parser": "5.3.3",
|
||||
"postcss": "8.4.14",
|
||||
"postcss-load-config": "4.0.1",
|
||||
"prettier": "2.7.1",
|
||||
"prettier-plugin-svelte": "2.7.0",
|
||||
"svelte": "3.48.0",
|
||||
"svelte-preprocess": "4.10.7",
|
||||
"tailwindcss": "^3.1.1",
|
||||
"tslib": "^2.4.0",
|
||||
"typescript": "^4.7.3"
|
||||
"tailwindcss": "3.1.4",
|
||||
"tslib": "2.4.0",
|
||||
"typescript": "4.7.4",
|
||||
"vite": "2.9.13",
|
||||
"vitest": "0.17.0",
|
||||
"vitest-svelte-kit": "0.0.6"
|
||||
},
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@analytics/google-analytics": "^0.5.3",
|
||||
"@macfja/svelte-persistent-store": "^1.3.0",
|
||||
"analytics": "^0.8.1",
|
||||
"daisyui": "2.15.2",
|
||||
"js-base64": "^3.7.2",
|
||||
"mermaid": "9.1.2",
|
||||
"moment": "^2.29.3",
|
||||
"monaco-editor": "^0.33.0",
|
||||
"monaco-mermaid": "^1.0.4",
|
||||
"@analytics/google-analytics": "0.5.3",
|
||||
"@macfja/svelte-persistent-store": "1.3.0",
|
||||
"analytics": "0.8.1",
|
||||
"daisyui": "2.17.0",
|
||||
"js-base64": "3.7.2",
|
||||
"mermaid": "9.1.3",
|
||||
"moment": "2.29.4",
|
||||
"monaco-editor": "0.33.0",
|
||||
"monaco-mermaid": "1.0.6",
|
||||
"pako": "2.0.4",
|
||||
"random-word-slugs": "^0.1.6"
|
||||
"random-word-slugs": "0.1.6"
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.{ts,svelte,js,css,md,json}": [
|
||||
|
||||
Vendored
+14
@@ -1 +1,15 @@
|
||||
/* eslint-disable @typescript-eslint/no-empty-interface */
|
||||
/* eslint-disable @typescript-eslint/ban-types */
|
||||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
|
||||
/// <reference types="@sveltejs/kit" />
|
||||
import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers';
|
||||
|
||||
declare global {
|
||||
namespace jest {
|
||||
interface Matchers<R = void>
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
extends TestingLibraryMatchers<typeof expect.stringContaining, R> {}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import type { Handle } from '@sveltejs/kit/types/hooks';
|
||||
import type { Handle } from '@sveltejs/kit';
|
||||
|
||||
export const handle: Handle = async ({ event, resolve }) => {
|
||||
const response = await resolve(event, {
|
||||
|
||||
@@ -4,17 +4,20 @@
|
||||
import Card from '$lib/components/card/card.svelte';
|
||||
import { krokiRendererUrl, rendererUrl } from '$lib/util/env';
|
||||
import { pakoSerde } from '$lib/util/serde';
|
||||
import { serializedState, codeStore } from '$lib/util/state';
|
||||
import { stateStore } from '$lib/util/state';
|
||||
import { toBase64 } from 'js-base64';
|
||||
import moment from 'moment';
|
||||
|
||||
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 = document.querySelector('#container svg');
|
||||
svg = getSvgEl();
|
||||
}
|
||||
const svgString = svg.outerHTML
|
||||
.replaceAll('<br>', '<br/>')
|
||||
@@ -50,6 +53,23 @@
|
||||
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;
|
||||
@@ -62,7 +82,7 @@
|
||||
const { canvas } = context;
|
||||
context.drawImage(image, 0, 0, canvas.width, canvas.height);
|
||||
simulateDownload(
|
||||
`mermaid-diagram-${moment().format('YYYYMMDDHHmmss')}.png`,
|
||||
getFileName('png'),
|
||||
canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream')
|
||||
);
|
||||
};
|
||||
@@ -102,10 +122,7 @@
|
||||
};
|
||||
|
||||
const onDownloadSVG = () => {
|
||||
simulateDownload(
|
||||
`mermaid-diagram-${moment().format('YYYYMMDDHHmmss')}.svg`,
|
||||
`data:image/svg+xml;base64,${getBase64SVG()}`
|
||||
);
|
||||
simulateDownload(getFileName('svg'), `data:image/svg+xml;base64,${getBase64SVG()}`);
|
||||
};
|
||||
|
||||
const onCopyMarkdown = () => {
|
||||
@@ -114,10 +131,10 @@
|
||||
};
|
||||
|
||||
let gistURL = '';
|
||||
codeStore.subscribe((state) => {
|
||||
if (state.loader?.type === 'gist') {
|
||||
stateStore.subscribe(({ loader }) => {
|
||||
if (loader?.type === 'gist') {
|
||||
// @ts-ignore Gist will have url
|
||||
gistURL = state.loader.config.url;
|
||||
gistURL = loader.config.url;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -139,11 +156,11 @@
|
||||
if (browser && ['mermaid.live', 'netlify'].some((path) => window.location.host.includes(path))) {
|
||||
isNetlify = true;
|
||||
}
|
||||
serializedState.subscribe((encodedState: string) => {
|
||||
iUrl = `${rendererUrl}/img/${encodedState}`;
|
||||
svgUrl = `${rendererUrl}/svg/${encodedState}`;
|
||||
krokiUrl = `${krokiRendererUrl}/mermaid/svg/${pakoSerde.serialize($codeStore.code)}`;
|
||||
mdCode = `[](${window.location.protocol}//${window.location.host}${window.location.pathname}#${encodedState})`;
|
||||
stateStore.subscribe(({ code, serialized }) => {
|
||||
iUrl = `${rendererUrl}/img/${serialized}`;
|
||||
svgUrl = `${rendererUrl}/svg/${serialized}`;
|
||||
krokiUrl = `${krokiRendererUrl}/mermaid/svg/${pakoSerde.serialize(code)}`;
|
||||
mdCode = `[](${window.location.protocol}//${window.location.host}${window.location.pathname}#${serialized})`;
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -154,10 +171,10 @@
|
||||
><i class="far fa-copy mr-2" /> Copy Image to clipboard
|
||||
</button>
|
||||
{/if}
|
||||
<button class="action-btn flex-auto" on:click={onDownloadPNG}>
|
||||
<button id="downloadPNG" class="action-btn flex-auto" on:click={onDownloadPNG}>
|
||||
<i class="fas fa-download mr-2" /> PNG
|
||||
</button>
|
||||
<button class="action-btn flex-auto" on:click={onDownloadSVG}>
|
||||
<button id="downloadSVG" class="action-btn flex-auto" on:click={onDownloadSVG}>
|
||||
<i class="fas fa-download mr-2" /> SVG
|
||||
</button>
|
||||
<a target="_blank" href={iUrl}>
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
// Vitest Snapshot v1
|
||||
|
||||
exports[`card.svelte > mounts 1`] = `"<div><div class=\\"card rounded overflow-hidden m-2 flex-grow flex flex-col shadow-2xl\\"><div class=\\"bg-primary p-2 pb-0 flex-none cursor-pointer\\"><div class=\\"flex justify-between\\"><div class=\\"flex cursor-default s-_wx1E_JHsCoF\\"><span class=\\"mr-2 font-semibold s-_wx1E_JHsCoF\\"><i class=\\"fas fa-chevron-right icon s-_wx1E_JHsCoF isOpen\\"></i> TabTest</span> <ul class=\\"tabs s-_wx1E_JHsCoF\\"><div class=\\"tab tab-lifted tab-active s-_wx1E_JHsCoF\\"><i class=\\"mr-1 undefined s-_wx1E_JHsCoF\\"></i> title1 </div><div class=\\"tab tab-lifted text-primary-content s-_wx1E_JHsCoF\\"><i class=\\"mr-1 undefined s-_wx1E_JHsCoF\\"></i> title2 </div></ul></div><!--<Tabs>--> <div class=\\"flex gap-x-4 items-center -mt-2\\"></div></div></div> <div class=\\"card-body p-0 flex-grow overflow-auto text-base-content\\"></div></div><!--<Card>--></div>"`;
|
||||
@@ -0,0 +1,24 @@
|
||||
import { cleanup, render } from '@testing-library/svelte';
|
||||
import { describe, expect, it, afterEach } from 'vitest';
|
||||
import Card from './card.svelte';
|
||||
|
||||
describe('card.svelte', () => {
|
||||
// TODO: @testing-library/svelte claims to add this automatically but it doesn't work without explicit afterEach
|
||||
afterEach(() => cleanup());
|
||||
|
||||
it('mounts', () => {
|
||||
const { container } = render(Card, {
|
||||
title: 'TabTest',
|
||||
tabs: [
|
||||
{ id: 't1', title: 'title1' },
|
||||
{ id: 't2', title: 'title2' }
|
||||
]
|
||||
});
|
||||
expect(container).toBeTruthy();
|
||||
expect(container).toHaveTextContent('TabTest');
|
||||
expect(container).toHaveTextContent('title1');
|
||||
expect(container).toHaveTextContent('title2');
|
||||
expect(container).not.toHaveTextContent('title3');
|
||||
expect(container.innerHTML).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import type { EditorEvents } from '$lib/types';
|
||||
import { codeStore } from '$lib/util/state';
|
||||
import { stateStore } from '$lib/util/state';
|
||||
import { themeStore } from '$lib/util/theme';
|
||||
import type monaco from 'monaco-editor';
|
||||
import { createEventDispatcher, onMount } from 'svelte';
|
||||
@@ -21,17 +21,16 @@
|
||||
theme: 'mermaid',
|
||||
overviewRulerLanes: 0
|
||||
};
|
||||
export let errorMarkers: monaco.editor.IMarkerData[] = [];
|
||||
let oldText = text;
|
||||
$: editor && Monaco?.editor.setModelLanguage(editor.getModel(), language);
|
||||
$: {
|
||||
if (text !== oldText) {
|
||||
if ($codeStore.updateEditor) {
|
||||
if ($stateStore.updateEditor) {
|
||||
editor?.setValue(text);
|
||||
}
|
||||
oldText = text;
|
||||
}
|
||||
editor && Monaco?.editor.setModelMarkers(editor.getModel(), 'test', errorMarkers);
|
||||
editor && Monaco?.editor.setModelMarkers(editor.getModel(), 'test', $stateStore.errorMarkers);
|
||||
}
|
||||
|
||||
themeStore.subscribe(({ isDark }) => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import Card from '$lib/components/card/card.svelte';
|
||||
import { codeStore, getStateString } from '$lib/util/state';
|
||||
import { inputStateStore, getStateString } from '$lib/util/state';
|
||||
import {
|
||||
addHistoryEntry,
|
||||
historyModeStore,
|
||||
@@ -37,7 +37,7 @@
|
||||
const previousState: string = getPreviousState(auto);
|
||||
if (previousState !== currentState) {
|
||||
addHistoryEntry({
|
||||
state: $codeStore,
|
||||
state: $inputStateStore,
|
||||
time: Date.now(),
|
||||
type: auto ? 'auto' : 'manual'
|
||||
});
|
||||
@@ -54,7 +54,7 @@
|
||||
};
|
||||
|
||||
const restoreHistory = (state: State): void => {
|
||||
codeStore.set({ ...state, updateEditor: true, updateDiagram: true });
|
||||
inputStateStore.set({ ...state, updateEditor: true, updateDiagram: true });
|
||||
};
|
||||
|
||||
const relativeTime = (time: number) => {
|
||||
|
||||
@@ -95,7 +95,10 @@
|
||||
};
|
||||
|
||||
const loadSampleDiagram = (diagramType: string): void => {
|
||||
updateCode(samples[diagramType], true, true);
|
||||
updateCode(samples[diagramType], {
|
||||
updateDiagram: true,
|
||||
updateEditor: true
|
||||
});
|
||||
};
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { errorStore } from '$lib/util/error';
|
||||
|
||||
import { codeStore } from '$lib/util/state';
|
||||
import { inputStateStore, stateStore } from '$lib/util/state';
|
||||
import { onMount } from 'svelte';
|
||||
import mermaid from 'mermaid';
|
||||
|
||||
@@ -13,11 +11,16 @@
|
||||
let outOfSync = false;
|
||||
let manualUpdate = true;
|
||||
onMount(() => {
|
||||
codeStore.subscribe((state) => {
|
||||
stateStore.subscribe((state) => {
|
||||
if (state.error !== undefined) {
|
||||
error = true;
|
||||
return;
|
||||
}
|
||||
error = false;
|
||||
try {
|
||||
if (container && state && (state.updateDiagram || state.autoSync)) {
|
||||
if (!state.autoSync) {
|
||||
$codeStore.updateDiagram = false;
|
||||
$inputStateStore.updateDiagram = false;
|
||||
}
|
||||
outOfSync = false;
|
||||
manualUpdate = true;
|
||||
@@ -31,7 +34,10 @@
|
||||
delete container.dataset.processed;
|
||||
mermaid.initialize(Object.assign({}, JSON.parse(state.mermaid)));
|
||||
mermaid.render('graph-div', code, (svgCode) => {
|
||||
container.innerHTML = svgCode;
|
||||
if (svgCode.length > 0) {
|
||||
console.log(svgCode);
|
||||
container.innerHTML = svgCode;
|
||||
}
|
||||
});
|
||||
view.parentElement.scrollTop = scroll;
|
||||
error = false;
|
||||
@@ -45,24 +51,19 @@
|
||||
error = true;
|
||||
}
|
||||
});
|
||||
errorStore.subscribe((err) => {
|
||||
if (typeof err === 'undefined') {
|
||||
error = false;
|
||||
} else {
|
||||
error = true;
|
||||
console.log('Error: ', err);
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if error && $stateStore.error instanceof Error}
|
||||
<div class="p-2 text-red-600" id="errorContainer">{$stateStore.error}</div>
|
||||
{/if}
|
||||
|
||||
<div id="view" bind:this={view} class="p-2" class:error class:outOfSync>
|
||||
<div id="container" bind:this={container} class="flex-1 overflow-auto" />
|
||||
</div>
|
||||
|
||||
<style>
|
||||
#view {
|
||||
border: 1px solor darkred;
|
||||
flex: 1;
|
||||
}
|
||||
.error,
|
||||
|
||||
Vendored
+17
-1
@@ -6,6 +6,16 @@ export interface Locals {
|
||||
userid: string;
|
||||
}
|
||||
|
||||
export interface MarkerData {
|
||||
severity: number;
|
||||
message: string;
|
||||
source?: string;
|
||||
startLineNumber: number;
|
||||
startColumn: number;
|
||||
endLineNumber: number;
|
||||
endColumn: number;
|
||||
}
|
||||
|
||||
export interface EditorUpdateEvent {
|
||||
text: string;
|
||||
}
|
||||
@@ -32,6 +42,12 @@ export interface State {
|
||||
loader?: LoaderConfig;
|
||||
}
|
||||
|
||||
export interface ValidatedState extends State {
|
||||
error: unknown;
|
||||
errorMarkers: MarkerData[];
|
||||
serialized: string;
|
||||
}
|
||||
|
||||
export interface GistLoaderConfig {
|
||||
url: string;
|
||||
}
|
||||
@@ -64,4 +80,4 @@ export interface DocConfig {
|
||||
};
|
||||
}
|
||||
|
||||
type Loader = (url: string) => Promise<State>;
|
||||
export type Loader = (url: string) => Promise<State>;
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
import { writable } from 'svelte/store';
|
||||
|
||||
export const errorStore = writable(undefined);
|
||||
@@ -1,3 +1,4 @@
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-return */
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
@@ -43,6 +44,7 @@ const getGistData = async (gistURL: string): Promise<GistData> => {
|
||||
}
|
||||
const currentItem = history[0];
|
||||
return {
|
||||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
||||
url: `${html_url}/${currentItem.version}`,
|
||||
code,
|
||||
config,
|
||||
|
||||
@@ -23,6 +23,9 @@ export const loadDataFromUrl = async (): Promise<void> => {
|
||||
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 {
|
||||
@@ -54,5 +57,4 @@ export const loadDataFromUrl = async (): Promise<void> => {
|
||||
updateDiagram: true,
|
||||
updateEditor: true
|
||||
});
|
||||
// window.location.search = '';
|
||||
};
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
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;
|
||||
};
|
||||
|
||||
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"'
|
||||
);
|
||||
});
|
||||
|
||||
it('should serialize and deserialize with base64 serde', () => {
|
||||
expect(verifySerde(defaultState, 'base64')).toMatchInlineSnapshot(
|
||||
'"base64:eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW0NocmlzdG1hc10gLS0-fEdldCBtb25leXwgQihHbyBzaG9wcGluZylcbiAgICBCIC0tPiBDe0xldCBtZSB0aGlua31cbiAgICBDIC0tPnxPbmV8IERbTGFwdG9wXVxuICAgIEMgLS0-fFR3b3wgRVtpUGhvbmVdXG4gICAgQyAtLT58VGhyZWV8IEZbZmE6ZmEtY2FyIENhcl1cbiAgIiwibWVybWFpZCI6IntcbiAgXCJ0aGVtZVwiOiBcImRlZmF1bHRcIlxufSIsInVwZGF0ZUVkaXRvciI6ZmFsc2UsImF1dG9TeW5jIjp0cnVlLCJ1cGRhdGVEaWFncmFtIjp0cnVlfQ"'
|
||||
);
|
||||
});
|
||||
|
||||
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"'
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw error for unrecognized serde', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-expect-error
|
||||
expect(() => serializeState(defaultState, 'unknown')).toThrowError(
|
||||
'Unknown serde type: unknown'
|
||||
);
|
||||
expect(() => deserializeState('unknown:hello')).toThrowError('Unknown serde type: unknown');
|
||||
});
|
||||
});
|
||||
+10
-8
@@ -28,18 +28,20 @@ export const pakoSerde: Serde = {
|
||||
}
|
||||
};
|
||||
|
||||
const serdes: { [key: string]: Serde } = {
|
||||
export type SerdeType = 'base64' | 'pako';
|
||||
|
||||
const serdes: { [key in SerdeType]: Serde } = {
|
||||
base64: base64Serde,
|
||||
pako: pakoSerde
|
||||
};
|
||||
|
||||
type SerdeType = keyof typeof serdes;
|
||||
|
||||
export const serializeState = (state: State): string => {
|
||||
export const serializeState = (state: State, serde: SerdeType = 'pako'): string => {
|
||||
if (serdes[serde] === undefined) {
|
||||
throw new Error(`Unknown serde type: ${serde}`);
|
||||
}
|
||||
const json = JSON.stringify(state);
|
||||
const defaultSerde: SerdeType = 'pako';
|
||||
const serialized = serdes[defaultSerde].serialize(json);
|
||||
return `${defaultSerde}:${serialized}`;
|
||||
const serialized = serdes[serde].serialize(json);
|
||||
return `${serde}:${serialized}`;
|
||||
};
|
||||
|
||||
export const deserializeState = (state: string): State => {
|
||||
@@ -48,7 +50,7 @@ export const deserializeState = (state: string): State => {
|
||||
let tempType: string;
|
||||
[tempType, serialized] = state.split(':');
|
||||
if (tempType in serdes) {
|
||||
type = tempType;
|
||||
type = tempType as SerdeType;
|
||||
} else {
|
||||
throw new Error(`Unknown serde type: ${tempType}`);
|
||||
}
|
||||
|
||||
+54
-16
@@ -1,9 +1,11 @@
|
||||
import { writable, get, derived } from 'svelte/store';
|
||||
import type { Readable } from 'svelte/store';
|
||||
import { persist, localStorage } from '@macfja/svelte-persistent-store';
|
||||
import type { State } from '$lib/types';
|
||||
import { saveStatistics } from './stats';
|
||||
import { serializeState, deserializeState } from './serde';
|
||||
import mermaid from 'mermaid';
|
||||
|
||||
import type { Readable } from 'svelte/store';
|
||||
import type { MarkerData, State, ValidatedState } from '$lib/types';
|
||||
|
||||
export const defaultState: State = {
|
||||
code: `graph TD
|
||||
@@ -36,9 +38,42 @@ const urlParseFailedState = `graph TD
|
||||
G --> |"No :("| H(Try using the Timeline tab in History <br/>from same browser you used to create the diagram.)
|
||||
click D href "https://github.com/mermaid-js/mermaid-live-editor/issues/new?assignees=&labels=bug&template=bug_report.md&title=Broken%20link" "Raise issue"`;
|
||||
|
||||
export const codeStore = persist(writable(defaultState), localStorage(), 'codeStore');
|
||||
export const serializedState: Readable<string> = derived([codeStore], ([code], set) => {
|
||||
set(serializeState(code));
|
||||
// inputStateStore handles all updates and is shared externally when exporting via URL, History, etc.
|
||||
export const inputStateStore = persist(writable(defaultState), localStorage(), 'codeStore');
|
||||
|
||||
// All internal reads should be done via stateStore, but it should not be persisted/shared externally.
|
||||
export const stateStore: Readable<ValidatedState> = derived([inputStateStore], ([state]) => {
|
||||
const processed: ValidatedState = {
|
||||
...state,
|
||||
serialized: '',
|
||||
errorMarkers: [],
|
||||
error: undefined
|
||||
};
|
||||
// No changes should be done to fields part of `state`.
|
||||
try {
|
||||
processed.serialized = serializeState(state);
|
||||
mermaid.parse(state.code);
|
||||
JSON.parse(state.mermaid);
|
||||
} catch (e) {
|
||||
processed.error = e;
|
||||
console.error(e);
|
||||
if (e.hash) {
|
||||
try {
|
||||
const marker: MarkerData = {
|
||||
severity: 8, // Error
|
||||
startLineNumber: e.hash.loc.first_line,
|
||||
startColumn: e.hash.loc.first_column,
|
||||
endLineNumber: e.hash.loc.last_line,
|
||||
endColumn: (e.hash.loc.last_column as number) + 1,
|
||||
message: e.str
|
||||
};
|
||||
processed.errorMarkers = [marker];
|
||||
} catch (err) {
|
||||
console.error('Error without line helper', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
return processed;
|
||||
});
|
||||
|
||||
export const loadState = (data: string): void => {
|
||||
@@ -57,30 +92,33 @@ 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 = get(codeStore);
|
||||
state = get(inputStateStore);
|
||||
if (data) {
|
||||
console.error('Init error', e);
|
||||
state.code = urlParseFailedState;
|
||||
state.mermaid = defaultState.mermaid;
|
||||
}
|
||||
}
|
||||
updateCodeStore({ ...state, updateEditor: true });
|
||||
};
|
||||
|
||||
export const updateCodeStore = (newState: State): void => {
|
||||
codeStore.update((state) => {
|
||||
inputStateStore.update((state) => {
|
||||
return { ...state, ...newState };
|
||||
});
|
||||
};
|
||||
|
||||
let prompted = false;
|
||||
export const updateCode = (code: string, updateEditor: boolean, updateDiagram = false): void => {
|
||||
export const updateCode = (
|
||||
code: string,
|
||||
{ updateEditor, updateDiagram = false }: { updateEditor: boolean; updateDiagram?: boolean }
|
||||
): void => {
|
||||
saveStatistics(code);
|
||||
const lines = (code.match(/\n/g) || '').length + 1;
|
||||
|
||||
if (lines > 50 && !prompted && get(codeStore).autoSync) {
|
||||
if (lines > 50 && !prompted && get(stateStore).autoSync) {
|
||||
const turnOff = confirm(
|
||||
'Long diagram detected. Turn off Auto Sync? Click the sync logo to manually sync.'
|
||||
);
|
||||
@@ -92,19 +130,19 @@ export const updateCode = (code: string, updateEditor: boolean, updateDiagram =
|
||||
}
|
||||
}
|
||||
|
||||
codeStore.update((state) => {
|
||||
inputStateStore.update((state) => {
|
||||
return { ...state, code, updateEditor, updateDiagram };
|
||||
});
|
||||
};
|
||||
|
||||
export const updateConfig = (config: string, updateEditor: boolean): void => {
|
||||
codeStore.update((state) => {
|
||||
inputStateStore.update((state) => {
|
||||
return { ...state, mermaid: config, updateEditor };
|
||||
});
|
||||
};
|
||||
|
||||
export const toggleDarkTheme = (dark: boolean): void => {
|
||||
codeStore.update((state) => {
|
||||
inputStateStore.update((state) => {
|
||||
const config = JSON.parse(state.mermaid);
|
||||
if (!config.theme || ['dark', 'default'].includes(config.theme)) {
|
||||
config.theme = dark ? 'dark' : 'default';
|
||||
@@ -115,11 +153,11 @@ export const toggleDarkTheme = (dark: boolean): void => {
|
||||
};
|
||||
|
||||
export const initURLSubscription = (): void => {
|
||||
serializedState.subscribe((state: string) => {
|
||||
history.replaceState(undefined, undefined, `#${state}`);
|
||||
stateStore.subscribe(({ serialized }) => {
|
||||
history.replaceState(undefined, undefined, `#${serialized}`);
|
||||
});
|
||||
};
|
||||
|
||||
export const getStateString = (): string => {
|
||||
return JSON.stringify(get(codeStore));
|
||||
return JSON.stringify(get(inputStateStore));
|
||||
};
|
||||
|
||||
+18
-53
@@ -6,17 +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, codeStore, serializedState } from '$lib/util/state';
|
||||
import { updateCode, updateConfig, inputStateStore, stateStore } from '$lib/util/state';
|
||||
import { initHandler, syncDiagram } from '$lib/util/util';
|
||||
import { errorStore } from '$lib/util/error';
|
||||
import { onMount } from 'svelte';
|
||||
import mermaid from 'mermaid';
|
||||
import type monaco from 'monaco-editor';
|
||||
import type { EditorUpdateEvent, State, Tab, DocConfig } from '$lib/types';
|
||||
import { base } from '$app/paths';
|
||||
|
||||
serializedState; // Weird fix for error > serializedState is not defined. Treeshaking?
|
||||
|
||||
type Modes = 'code' | 'config';
|
||||
type Languages = 'mermaid' | 'json';
|
||||
|
||||
@@ -68,17 +63,16 @@
|
||||
let text = '';
|
||||
let docURL = docURLBase;
|
||||
let language: Languages = 'mermaid';
|
||||
let errorMarkers: monaco.editor.IMarkerData[] = [];
|
||||
$: language = languageMap[selectedMode];
|
||||
$: {
|
||||
if (selectedMode === 'code') {
|
||||
text = $codeStore.code;
|
||||
text = $stateStore.code;
|
||||
} else {
|
||||
text = $codeStore.mermaid;
|
||||
text = $stateStore.mermaid;
|
||||
}
|
||||
}
|
||||
|
||||
codeStore.subscribe((state: State) => {
|
||||
stateStore.subscribe((state: State) => {
|
||||
if (state.updateEditor) {
|
||||
text = selectedMode === 'code' ? state.code : state.mermaid;
|
||||
}
|
||||
@@ -91,7 +85,7 @@
|
||||
});
|
||||
const tabSelectHandler = (message: CustomEvent<Tab>) => {
|
||||
selectedMode = message.detail.id === 'code' ? 'code' : 'config';
|
||||
$codeStore.updateEditor = true;
|
||||
$inputStateStore.updateEditor = true;
|
||||
};
|
||||
const tabs: Tab[] = [
|
||||
{
|
||||
@@ -106,55 +100,26 @@
|
||||
}
|
||||
];
|
||||
|
||||
const handleCodeUpdate = (code: string): void => {
|
||||
mermaid.parse(code);
|
||||
updateCode(code, false);
|
||||
};
|
||||
|
||||
const handleConfigUpdate = (config: string): void => {
|
||||
JSON.parse(config);
|
||||
updateConfig(config, false);
|
||||
};
|
||||
|
||||
const updateHandler = (message: CustomEvent<EditorUpdateEvent>) => {
|
||||
try {
|
||||
if (selectedMode === 'code') {
|
||||
handleCodeUpdate(message.detail.text);
|
||||
} else {
|
||||
handleConfigUpdate(message.detail.text);
|
||||
}
|
||||
errorStore.set(undefined);
|
||||
errorMarkers = [];
|
||||
} catch (e) {
|
||||
errorStore.set(e);
|
||||
if (e.hash) {
|
||||
const marker: monaco.editor.IMarkerData = {
|
||||
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
|
||||
};
|
||||
errorMarkers.push(marker);
|
||||
// Clear all previous errors before this error.
|
||||
errorMarkers = errorMarkers.filter(
|
||||
(m) => m.startLineNumber >= marker.startLineNumber && m.startColumn >= marker.startColumn
|
||||
);
|
||||
}
|
||||
console.error(e);
|
||||
const code = message.detail.text;
|
||||
if (selectedMode === 'code') {
|
||||
updateCode(code, {
|
||||
updateEditor: false
|
||||
});
|
||||
} else {
|
||||
updateConfig(code, false);
|
||||
}
|
||||
};
|
||||
|
||||
const viewDiagram = () => {
|
||||
window.open(`${base}/view#${$serializedState}`, '_blank').focus();
|
||||
window.open(`${base}/view#${$stateStore.serialized}`, '_blank').focus();
|
||||
};
|
||||
|
||||
onMount(async () => {
|
||||
await initHandler();
|
||||
const resizer = document.getElementById('resizeHandler');
|
||||
const element = document.getElementById('editorPane');
|
||||
const resize = (e) => {
|
||||
const resize = (e: { pageX: number }) => {
|
||||
const newWidth = e.pageX - element.getBoundingClientRect().left;
|
||||
if (newWidth > 50) {
|
||||
element.style.width = `${newWidth}px`;
|
||||
@@ -184,13 +149,13 @@
|
||||
<span> Auto sync</span>
|
||||
<input
|
||||
type="checkbox"
|
||||
class="toggle {$codeStore.autoSync ? 'btn-secondary' : 'toggle-primary'} ml-1"
|
||||
class="toggle {$stateStore.autoSync ? 'btn-secondary' : 'toggle-primary'} ml-1"
|
||||
id="autoSync"
|
||||
bind:checked={$codeStore.autoSync} />
|
||||
bind:checked={$inputStateStore.autoSync} />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{#if !$codeStore.autoSync}
|
||||
{#if !$stateStore.autoSync}
|
||||
<button
|
||||
class="btn btn-secondary btn-xs mr-1"
|
||||
title="Sync Diagram"
|
||||
@@ -204,7 +169,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Editor on:update={updateHandler} {language} bind:text {errorMarkers} />
|
||||
<Editor on:update={updateHandler} {language} bind:text />
|
||||
</Card>
|
||||
|
||||
<div class="-mt-2">
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import matchers from '@testing-library/jest-dom/matchers';
|
||||
import { expect } from 'vitest';
|
||||
|
||||
expect.extend(matchers);
|
||||
@@ -20,10 +20,6 @@ const config = {
|
||||
}
|
||||
: {},
|
||||
trailingSlash: 'ignore',
|
||||
vite: {
|
||||
envPrefix: 'MERMAID_',
|
||||
optimizeDeps: { include: ['mermaid'] }
|
||||
},
|
||||
prerender: {
|
||||
default: true
|
||||
}
|
||||
|
||||
@@ -7,5 +7,10 @@
|
||||
"cypress/**/*.js",
|
||||
"static/**/*.js"
|
||||
],
|
||||
"compilerOptions": {
|
||||
"resolveJsonModule": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"types": ["vitest/importMeta"]
|
||||
},
|
||||
"extends": "./.svelte-kit/tsconfig.json"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { sveltekit } from '@sveltejs/kit/vite';
|
||||
/** @type {import('vite').UserConfig} */
|
||||
const config = {
|
||||
plugins: [sveltekit()],
|
||||
envPrefix: 'MERMAID_',
|
||||
optimizeDeps: { include: ['mermaid'] },
|
||||
ssr: {
|
||||
noExternal: ['@macfja/svelte-persistent-store']
|
||||
},
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
// in-source testing
|
||||
includeSource: ['src/**/*.{js,ts,svelte}'],
|
||||
setupFiles: ['./src/tests/setup.ts'],
|
||||
coverage: {
|
||||
exclude: ['src/mocks', '.svelte-kit', 'src/**/*.test.ts'],
|
||||
reporter: ['text', 'json', 'html', 'lcov']
|
||||
}
|
||||
}
|
||||
};
|
||||
export default config;
|
||||
Reference in New Issue
Block a user