Merge pull request #1158 from mermaid-js/develop

Release 9.4
This commit is contained in:
Sidharth Vinod
2023-02-16 21:02:05 +05:30
committed by GitHub
23 changed files with 840 additions and 335 deletions
+38 -2
View File
@@ -6,9 +6,18 @@ module.exports = {
'plugin:@typescript-eslint/recommended',
// 'plugin:@typescript-eslint/recommended-requiring-type-checking',
'plugin:@typescript-eslint/strict',
'plugin:unicorn/recommended',
'prettier'
],
plugins: ['svelte3', 'tailwindcss', '@typescript-eslint', 'es', 'vitest', 'no-only-tests'],
plugins: [
'svelte3',
'tailwindcss',
'@typescript-eslint',
'es',
'vitest',
'no-only-tests',
'unicorn'
],
ignorePatterns: [
'docs/*',
'*.cjs',
@@ -59,6 +68,33 @@ module.exports = {
'@typescript-eslint/no-unsafe-assignment': 'off',
'es/no-regexp-lookbehind-assertions': 'error',
curly: ['error', 'all'],
'no-only-tests/no-only-tests': 'error'
'no-only-tests/no-only-tests': 'error',
'unicorn/no-null': 'off',
'unicorn/filename-case': [
'error',
{
case: 'camelCase'
}
],
'unicorn/prevent-abbreviations': [
'error',
{
allowList: {
ctx: true,
db: true,
doc: true,
env: true,
fn: true,
i: true,
param: true,
req: true,
res: true,
str: true,
searchParams: true,
temp: true,
ImportMetaEnv: true
}
}
]
}
};
+27 -14
View File
@@ -1,19 +1,32 @@
name: Update Browserslist
name: Update Browserslist database
on:
push:
branches-ignore:
- 'develop'
- 'master'
- 'renovate/*'
schedule:
- cron: '0 2 1,15 * *'
permissions:
contents: write
pull-requests: write
jobs:
build:
update-browserslist-database:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: npx browserslist@latest --update-db
- name: Commit changes
uses: EndBug/add-and-commit@v9
- name: Checkout repository
uses: actions/checkout@v3
with:
author_name: ${{ github.actor }}
author_email: ${{ github.actor }}@users.noreply.github.com
message: 'Update Browserslist'
fetch-depth: 0
- name: Configure git
run: |
git config --global user.email "action@github.com"
git config --global user.name "GitHub Action"
- name: Update Browserslist database and create PR if applies
uses: c2corg/browserslist-update-action@v2
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: browserslist-update
base_branch: develop
commit_message: 'build: update Browserslist db'
title: 'build: update Browserslist db'
body: Auto-generated by [browserslist-update-action](https://github.com/c2corg/browserslist-update-action/)
labels: 'chores, github action'
+11 -1
View File
@@ -1,6 +1,16 @@
{
"editor.formatOnSave": true,
"cSpell.words": ["asyncable", "KROKI", "mindmap", "pako", "Serde", "serdes", "tailwindcss"],
"cSpell.words": [
"asyncable",
"Browserslist",
"corg",
"KROKI",
"mindmap",
"pako",
"Serde",
"serdes",
"tailwindcss"
],
"vitest.commandLine": "yarn test:unit",
"vitest.enable": true,
"testing.autoRun.mode": "rerun",
+1 -1
View File
@@ -6,7 +6,7 @@
# Stop : press ctrl + c
# or
# docker stop mermaid-live-editor
FROM node:18.12.1 as mermaid-live-editor-builder
FROM node:18.14.0 as mermaid-live-editor-builder
COPY --chown=node:node . /home
WORKDIR /home
RUN yarn install
+3 -3
View File
@@ -84,15 +84,15 @@ describe('Save History', () => {
// TODO: Fix #639
xit('should auto save history', () => {
getEditor().type(' C --> HistoryTest');
cy.tick(70000);
cy.tick(70_000);
cy.contains('Timeline').click();
cy.get('#historyList').find('li').should('have.length', 1);
cy.get('#editor').type('ing');
cy.tick(70000);
cy.tick(70_000);
cy.get('#historyList').find('li').should('have.length', 2);
for (let i = 0; i < 31; i++) {
cy.get('#editor').type('.');
cy.tick(70000);
cy.tick(70_000);
}
cy.get('#historyList').find('li').should('have.length', 30);
});
+1 -1
View File
@@ -37,7 +37,7 @@ export const verifyFileSnapshot = (
cy.readFile(filePath, null, {
log: false
}).then((buffer: ArrayBuffer) =>
expect(new TextDecoder('utf-8').decode(buffer)).to.contain(content)
expect(new TextDecoder('utf8').decode(buffer)).to.contain(content)
);
cy.task('deleteFile', filePath);
};
+3 -3
View File
@@ -1,7 +1,7 @@
module.exports = {
"Site Loads": {
"Check Home page load": {
"1": "{\"code\":\"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n \",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":true}"
"1": "{\"code\":\"flowchart TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n \",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":true}"
},
"Check Redirect from old URL": {
"1": "{\"code\":\"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":true}"
@@ -19,10 +19,10 @@ module.exports = {
"__version": "11.2.0",
"Auto sync tests": {
"should dim diagram when code is edited": {
"1": "{\"code\":\"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n C --> Test\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":false,\"updateDiagram\":false}"
"1": "{\"code\":\"flowchart TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n C --> Test\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":false,\"updateDiagram\":false}"
},
"should not dim diagram when code is in sync": {
"1": "{\"code\":\"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n C --> Testing\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":false}"
"1": "{\"code\":\"flowchart TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n C --> Testing\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":false}"
}
},
"Test themes": {
+20 -19
View File
@@ -23,55 +23,56 @@
},
"devDependencies": {
"@cypress/snapshot": "2.1.7",
"@sveltejs/adapter-static": "1.0.0",
"@sveltejs/kit": "1.0.0",
"@sveltejs/adapter-static": "1.0.6",
"@sveltejs/kit": "1.5.0",
"@testing-library/jest-dom": "5.16.5",
"@testing-library/svelte": "3.2.2",
"@types/pako": "2.0.0",
"@types/uuid": "8.3.4",
"@typescript-eslint/eslint-plugin": "5.45.0",
"@typescript-eslint/parser": "5.45.0",
"@vitest/ui": "^0.25.3",
"@typescript-eslint/eslint-plugin": "5.51.0",
"@typescript-eslint/parser": "5.51.0",
"@vitest/ui": "^0.28.0",
"autoprefixer": "^10.4.13",
"c8": "7.12.0",
"chai": "^4.3.7",
"cssnano": "^5.1.14",
"cy-verify-downloads": "0.1.11",
"cypress": "11.2.0",
"cypress-localstorage-commands": "2.2.1",
"eslint": "8.29.0",
"eslint-config-prettier": "8.5.0",
"cypress-localstorage-commands": "2.2.2",
"eslint": "8.33.0",
"eslint-config-prettier": "8.6.0",
"eslint-plugin-cypress": "2.12.1",
"eslint-plugin-es": "4.1.0",
"eslint-plugin-no-only-tests": "^3.1.0",
"eslint-plugin-postcss-modules": "2.0.0",
"eslint-plugin-svelte3": "4.0.0",
"eslint-plugin-tailwindcss": "3.7.1",
"eslint-plugin-vitest": "^0.0.20",
"esserializer": "1.3.6",
"eslint-plugin-tailwindcss": "3.8.3",
"eslint-plugin-unicorn": "^45.0.0",
"eslint-plugin-vitest": "^0.0.32",
"esserializer": "1.3.10",
"font-awesome": "^4.7.0",
"husky": "^8.0.2",
"jsdom": "20.0.3",
"lint-staged": "13.1.0",
"lint-staged": "13.1.1",
"node-html-parser": "^6.1.4",
"postcss": "^8.4.19",
"postcss-load-config": "4.0.1",
"prettier": "2.8.0",
"prettier": "2.8.3",
"prettier-plugin-svelte": "^2.8.1",
"svelte": "3.55.0",
"svelte": "3.55.1",
"svelte-preprocess": "4.10.7",
"tailwindcss": "^3.2.4",
"tslib": "^2.4.1",
"typescript": "4.9.3",
"typescript": "4.9.5",
"vite": "^4.0.1",
"vitest": "^0.25.8"
"vitest": "^0.28.0"
},
"dependencies": {
"@mermaid-js/mermaid-mindmap": "9.3.0",
"analytics": "0.8.1",
"analytics-plugin-plausible": "0.0.6",
"daisyui": "2.42.1",
"js-base64": "3.7.3",
"daisyui": "2.50.0",
"js-base64": "3.7.4",
"mermaid": "9.3.0",
"moment": "2.29.4",
"monaco-editor": "0.34.1",
@@ -88,7 +89,7 @@
]
},
"volta": {
"node": "18.12.1",
"node": "18.14.0",
"yarn": "1.22.19"
},
"engines": {
+8 -8
View File
@@ -17,7 +17,7 @@ describe('history', () => {
addHistoryEntry({
state: defaultState,
time: 12345,
time: 12_345,
type: 'manual'
});
@@ -25,14 +25,14 @@ describe('history', () => {
window.localStorage.getItem('manualHistoryStore') ?? '[]'
) as HistoryEntry[];
expect(manualEntry.time).toBe(12345);
expect(manualEntry.time).toBe(12_345);
expect(manualEntry.type).toBe('manual');
expect(manualEntry.name).not.toBeNull();
expect(manualEntry.state).not.toBeNull();
addHistoryEntry({
state: defaultState,
time: 54321,
time: 54_321,
type: 'auto'
});
@@ -40,7 +40,7 @@ describe('history', () => {
window.localStorage.getItem('autoHistoryStore') ?? '[]'
) as HistoryEntry[];
expect(autoEntry.time).toBe(54321);
expect(autoEntry.time).toBe(54_321);
expect(autoEntry.type).toBe('auto');
expect(autoEntry.name).not.toBeNull();
expect(autoEntry.state).not.toBeNull();
@@ -56,12 +56,12 @@ describe('history', () => {
it('should clear history entries', () => {
addHistoryEntry({
state: defaultState,
time: 12345,
time: 12_345,
type: 'manual'
});
addHistoryEntry({
state: { ...defaultState, code: 'graph TD\\n A[Christmas] -->|Get money| B(Go shopping)' },
time: 123456,
time: 123_456,
type: 'manual'
});
@@ -76,12 +76,12 @@ describe('history', () => {
historyModeStore.set('auto');
addHistoryEntry({
state: defaultState,
time: 54321,
time: 54_321,
type: 'auto'
});
addHistoryEntry({
state: { ...defaultState, code: 'graph TD\\n A[Christmas] -->|Get money| B(Go shopping)' },
time: 654321,
time: 654_321,
type: 'auto'
});
expect(get(historyStore).length).toBe(2);
+29 -18
View File
@@ -26,19 +26,27 @@ const manualHistoryStore: Writable<HistoryEntry[]> = persist(
'manualHistoryStore'
);
export const loaderHistoryStore: Writable<HistoryEntry[]> = writable([] as HistoryEntry[]);
export const loaderHistoryStore: Writable<HistoryEntry[]> = writable([]);
export const historyStore: Readable<HistoryEntry[]> = derived(
[historyModeStore, autoHistoryStore, manualHistoryStore, loaderHistoryStore],
([historyMode, autoHistories, manualHistories, loadedHistories], set) => {
if (historyMode === 'auto') {
set(autoHistories);
} else if (historyMode === 'manual') {
set(manualHistories);
} else if (historyMode === 'loader') {
set(loadedHistories);
} else {
set(autoHistories);
switch (historyMode) {
case 'auto': {
set(autoHistories);
break;
}
case 'manual': {
set(manualHistories);
break;
}
case 'loader': {
set(loadedHistories);
break;
}
default: {
set(autoHistories);
}
}
}
);
@@ -90,7 +98,7 @@ export const getPreviousState = (auto: boolean): string => {
};
export const restoreHistory = (data: HistoryEntry[]) => {
const entries = data.filter(validateEntry);
const entries = data.filter((element) => validateEntry(element));
const invalidEntryCount = data.length - entries.length;
if (invalidEntryCount > 0) {
console.error(`${invalidEntryCount} invalid history entries were removed.`);
@@ -122,20 +130,23 @@ export const restoreHistory = (data: HistoryEntry[]) => {
alert('No valid entries found.');
}
};
const setIDs = (entries: HistoryEntry[]) => {
for (const entry of entries) {
if (!entry.id) {
entry.id = uuidV4();
}
}
return entries;
};
export const injectHistoryIDs = (): void => {
const setIDs = (entries: HistoryEntry[]) => {
for (const entry of entries) {
if (!entry.id) {
entry.id = uuidV4();
}
}
return entries;
};
autoHistoryStore.update(setIDs);
manualHistoryStore.update(setIDs);
};
const validateEntry = (entry: HistoryEntry): boolean => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
return entry.type && entry.state && entry.time && true;
};
+2 -2
View File
@@ -17,11 +17,11 @@
const links: Link[] = [
{
title: 'Documentation',
href: 'https://mermaid-js.github.io/mermaid/#/n00b-gettingStarted'
href: 'https://mermaid-js.github.io/mermaid/intro/n00b-gettingStarted.html'
},
{
title: 'Tutorial',
href: 'https://mermaid-js.github.io/mermaid/#/./Tutorials'
href: 'https://mermaid-js.github.io/mermaid/config/Tutorials.html'
},
{
title: 'Mermaid',
+1 -1
View File
@@ -4,7 +4,7 @@
import { logEvent } from '$lib/util/stats';
const samples = {
Flow: `graph TD
Flow: `flowchart TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
C -->|One| D[Laptop]
+1 -1
View File
@@ -65,7 +65,7 @@ export type HistoryEntry = { id: string; state: State; time: number; url?: strin
}
);
export type DocConfig = Record<
export type DocumentationConfig = Record<
string,
{
code: string;
+9 -8
View File
@@ -5,6 +5,7 @@
import type { State } from '$lib/types';
import { defaultState } from '$lib/util/state';
import { addHistoryEntry } from '$lib/components/History/history';
import { fetchJSON, fetchText } from '$lib/util/util';
const codeFileName = 'code.mmd';
const configFileName = 'config.json';
@@ -21,7 +22,7 @@ const isValidGist = (files: any): boolean => {
const getFileContent = async (file: GithubFile): Promise<string> => {
if (file.truncated) {
return await (await fetch(file.raw_url)).text();
return await fetchText(file.raw_url);
}
return file.content;
};
@@ -49,9 +50,9 @@ const getGistData = async (gistURL: string): Promise<GistData> => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_, __, gistID, revisionID] = path.split('/');
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const { html_url, files, history }: GistResponse = await (
await fetch(`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`)
).json();
const { html_url, files, history }: GistResponse = await fetchJSON(
`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`
);
if (isValidGist(files)) {
const code = await getFileContent(files[codeFileName]);
let config = '{}';
@@ -96,12 +97,12 @@ export const loadGistData = async (gistURL: string): Promise<State> => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_, __, gistID, revisionID] = path.split('/');
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const { history }: GistResponse = await (
await fetch(`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`)
).json();
const { history }: GistResponse = await fetchJSON(
`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`
);
const gistHistory: GistData[] = [];
for (const entry of history) {
const data: GistData | undefined = await getGistData(entry.url).catch(() => undefined);
const data: GistData | undefined = await getGistData(entry.url).catch();
data && gistHistory.push(data);
}
if (gistHistory.length === 0) {
+20 -22
View File
@@ -1,6 +1,8 @@
import { loadGistData } from './gist';
import { updateCodeStore, defaultState } from '../state';
import { updateCodeStore, defaultState } from '$lib/util/state';
import { fetchText } from '$lib/util/util';
import type { Loader, State } from '$lib/types';
const loaders: Record<string, Loader> = {
gist: loadGistData
};
@@ -8,34 +10,18 @@ const loaders: Record<string, Loader> = {
export const loadDataFromUrl = async (): Promise<void> => {
const searchParams = new URLSearchParams(window.location.search);
let state: Partial<State> = defaultState;
let code: string | undefined = undefined;
let config: string | undefined = undefined;
let loaded = false;
const codeURL: string | undefined = searchParams.get('code') ?? undefined;
const configURL: string | undefined = searchParams.get('config') ?? undefined;
let code: string | undefined;
const config = configURL ? await fetchText(configURL) : defaultState.mermaid;
if (codeURL) {
code = await (await fetch(codeURL)).text();
code = await fetchText(codeURL);
loaded = true;
}
if (configURL) {
config = await (await fetch(configURL)).text();
} else {
config = defaultState.mermaid;
}
if (!code) {
for (const [key, value] of searchParams.entries()) {
if (key in loaders) {
try {
state = await loaders[key](value);
loaded = true;
break;
} catch (err) {
console.error(err);
}
}
}
} else {
if (code) {
if (!codeURL) {
throw new Error('Code URL is not defined');
}
@@ -50,6 +36,18 @@ export const loadDataFromUrl = async (): Promise<void> => {
}
}
};
} else {
for (const [key, value] of searchParams.entries()) {
if (key in loaders) {
try {
state = await loaders[key](value);
loaded = true;
break;
} catch (error) {
console.error(error);
}
}
}
}
loaded &&
updateCodeStore({
+5 -7
View File
@@ -70,13 +70,13 @@ const deserialize = (value?: string | null): unknown => {
if (value !== null && value !== undefined) {
try {
return ESSerializer.deserialize(value);
} catch (e) {
} catch {
// Do nothing
// use the value "as is"
}
try {
return JSON.parse(value);
} catch (e) {
} catch {
// Do nothing
// use the value "as is"
}
@@ -179,11 +179,9 @@ function getBrowserStorage(
const listenerFunction = (event: StorageEvent) => {
const eventKey = event.key;
if (event.storageArea === browserStorage) {
listeners
.filter(({ key }) => key === eventKey)
.forEach(({ listener }) => {
listener(deserialize(event.newValue));
});
for (const { listener } of listeners.filter(({ key }) => key === eventKey)) {
listener(deserialize(event.newValue));
}
}
};
const connect = () => {
+10 -10
View File
@@ -3,29 +3,29 @@ import { serializeState, deserializeState, type SerdeType } from './serde';
import { defaultState } from './state';
import type { State } from '$lib/types';
describe('Serde tests', () => {
const verifySerde = (state: State, serde?: SerdeType): string => {
const serialized = serializeState(state, serde);
const deserialized = deserializeState(serialized);
expect(deserialized).to.deep.equal(state);
return serialized;
};
const verifySerde = (state: State, serde?: SerdeType): string => {
const serialized = serializeState(state, serde);
const deserialized = deserializeState(serialized);
expect(deserialized).to.deep.equal(state);
return serialized;
};
describe('Serde tests', () => {
it('should serialize and deserialize with default serde', () => {
expect(verifySerde(defaultState)).toMatchInlineSnapshot(
'"pako:eNpVj81qw0AMhF9F6NRC_AI-BGK7zSXQQHLz5iBsObuk-8Naphjb7551fEl1EjPfiNGEjW8Zc7xHChqulXKQ5lCXOppeLPU3yLL9fGQB6x2PMxQfRw-99iEYd__c-GKFoJxOK8Yg2rjHslnlK__jeIaqPlEQH27vzvXPz_BVm7NO5_87OnJKfdcd5R1lDUUoKb4Q3KHlaMm0qfq0KgpFs2WFeVpb7mj4FYXKLQmlQfxldA3mEgfe4RBaEq4MpaftJi5PNtJU8w"'
'"pako:eNpVjk2Lg0AMhv9KyGkL9Q94WGh1t5fCFurN6SFo7AztfDBGpKj_fcd62c0pvM_zhkzY-JYxx-7px0ZTFKhK5SDNoS50NL1Y6m-QZZ_ziQWsd_ya4fhx8tBrH4Jx993mH1cJium8agyijXssGyre_R_HM5T1mYL4cPtLqtHP8FWbi07n_xMdObW-647yjrKGIhQU3wru0XK0ZNr0_rQmCkWzZYV5WlvuaHiKQuWWpNIg_vpyDeYSB97jEFoSLg3dI9ktXH4B_cJWqw"'
);
});
it('should serialize and deserialize with base64 serde', () => {
expect(verifySerde(defaultState, 'base64')).toMatchInlineSnapshot(
'"base64:eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW0NocmlzdG1hc10gLS0-fEdldCBtb25leXwgQihHbyBzaG9wcGluZylcbiAgICBCIC0tPiBDe0xldCBtZSB0aGlua31cbiAgICBDIC0tPnxPbmV8IERbTGFwdG9wXVxuICAgIEMgLS0-fFR3b3wgRVtpUGhvbmVdXG4gICAgQyAtLT58VGhyZWV8IEZbZmE6ZmEtY2FyIENhcl1cbiAgIiwibWVybWFpZCI6IntcbiAgXCJ0aGVtZVwiOiBcImRlZmF1bHRcIlxufSIsImF1dG9TeW5jIjp0cnVlLCJ1cGRhdGVEaWFncmFtIjp0cnVlfQ"'
'"base64:eyJjb2RlIjoiZmxvd2NoYXJ0IFREXG4gICAgQVtDaHJpc3RtYXNdIC0tPnxHZXQgbW9uZXl8IEIoR28gc2hvcHBpbmcpXG4gICAgQiAtLT4gQ3tMZXQgbWUgdGhpbmt9XG4gICAgQyAtLT58T25lfCBEW0xhcHRvcF1cbiAgICBDIC0tPnxUd298IEVbaVBob25lXVxuICAgIEMgLS0-fFRocmVlfCBGW2ZhOmZhLWNhciBDYXJdXG4gICIsIm1lcm1haWQiOiJ7XG4gIFwidGhlbWVcIjogXCJkZWZhdWx0XCJcbn0iLCJhdXRvU3luYyI6dHJ1ZSwidXBkYXRlRGlhZ3JhbSI6dHJ1ZX0"'
);
});
it('should serialize and deserialize with pako serde', () => {
expect(verifySerde(defaultState, 'pako')).toMatchInlineSnapshot(
'"pako:eNpVj81qw0AMhF9F6NRC_AI-BGK7zSXQQHLz5iBsObuk-8Naphjb7551fEl1EjPfiNGEjW8Zc7xHChqulXKQ5lCXOppeLPU3yLL9fGQB6x2PMxQfRw-99iEYd__c-GKFoJxOK8Yg2rjHslnlK__jeIaqPlEQH27vzvXPz_BVm7NO5_87OnJKfdcd5R1lDUUoKb4Q3KHlaMm0qfq0KgpFs2WFeVpb7mj4FYXKLQmlQfxldA3mEgfe4RBaEq4MpaftJi5PNtJU8w"'
'"pako:eNpVjk2Lg0AMhv9KyGkL9Q94WGh1t5fCFurN6SFo7AztfDBGpKj_fcd62c0pvM_zhkzY-JYxx-7px0ZTFKhK5SDNoS50NL1Y6m-QZZ_ziQWsd_ya4fhx8tBrH4Jx993mH1cJium8agyijXssGyre_R_HM5T1mYL4cPtLqtHP8FWbi07n_xMdObW-647yjrKGIhQU3wru0XK0ZNr0_rQmCkWzZYV5WlvuaHiKQuWWpNIg_vpyDeYSB97jEFoSLg3dI9ktXH4B_cJWqw"'
);
});
+18 -22
View File
@@ -2,32 +2,28 @@ import { writable, get, type Readable, derived } from 'svelte/store';
import { persist, localStorage } from './persist';
import { saveStatistics, countLines } from './stats';
import { serializeState, deserializeState } from './serde';
import { cmdKey, errorDebug } from './util';
import { cmdKey, errorDebug, formatJSON } from './util';
import { parse } from './mermaid';
import type { ErrorHash, MarkerData, State, ValidatedState } from '$lib/types';
import type { MermaidConfig } from 'mermaid';
export const defaultState: State = {
code: `graph TD
code: `flowchart TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
C -->|One| D[Laptop]
C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car]
`,
mermaid: JSON.stringify(
{
theme: 'default'
},
null,
2
),
mermaid: formatJSON({
theme: 'default'
}),
autoSync: true,
updateDiagram: true
};
const urlParseFailedState = `graph TD
const urlParseFailedState = `flowchart TD
A[Loading URL failed. We can try to figure out why.] -->|Decode JSON| B(Please check the console to see the JSON and error details.)
B --> C{Is the JSON correct?}
C -->|Yes| D(Please Click here to Raise an issue in github.<br/>Including the broken link in the issue <br/> will speed up the fix.)
@@ -65,16 +61,16 @@ const processState = async (state: State) => {
processed.serialized = serializeState(state);
await parse(state.code);
JSON.parse(state.mermaid);
} catch (e) {
processed.error = e as Error;
} catch (error) {
processed.error = error as Error;
errorDebug();
console.error(e);
if ('hash' in e) {
console.error(error);
if ('hash' in error) {
try {
const {
loc: { first_line, last_line, first_column, last_column }
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
} = e.hash as ErrorHash;
} = error.hash as ErrorHash;
const marker: MarkerData = {
severity: 8, // Error
startLineNumber: first_line,
@@ -82,11 +78,11 @@ const processState = async (state: State) => {
endLineNumber: last_line,
endColumn: last_column + 1,
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment
message: e.str
message: error.str
};
processed.errorMarkers = [marker];
} catch (err) {
console.error('Error without line helper', err);
} catch (error) {
console.error('Error without line helper', error);
}
}
}
@@ -120,11 +116,11 @@ export const loadState = (data: string): void => {
) {
delete mermaidConfig.securityLevel; // Prevent setting overriding securityLevel when loading state to mitigate possible XSS attack
}
state.mermaid = JSON.stringify(mermaidConfig, null, 2);
} catch (e) {
state.mermaid = formatJSON(mermaidConfig);
} catch (error) {
state = get(inputStateStore);
if (data) {
console.error('Init error', e);
console.error('Init error', error);
state.code = urlParseFailedState;
state.mermaid = defaultState.mermaid;
}
@@ -185,7 +181,7 @@ export const toggleDarkTheme = (dark: boolean): void => {
config.theme = dark ? 'dark' : 'default';
}
return { ...state, mermaid: JSON.stringify(config, null, 2) };
return { ...state, mermaid: formatJSON(config) };
});
};
+5 -5
View File
@@ -20,8 +20,8 @@ export const initAnalytics = async (): Promise<void> => {
})
]
});
} catch (e) {
console.log(e);
} catch (error) {
console.log(error);
console.info('Analytics blocked ;)');
}
}
@@ -87,10 +87,10 @@ export const logEvent = (name: AnalyticsEvent, data?: unknown): void => {
return;
}
const key = data ? JSON.stringify({ name, data }) : name;
if (!timeouts.has(key)) {
void analytics.track(name, data);
} else {
if (timeouts.has(key)) {
clearTimeout(timeouts.get(key));
} else {
void analytics.track(name, data);
}
timeouts.set(
key,
+3 -3
View File
@@ -16,7 +16,7 @@ export const themeStore: Writable<ThemeConfig> = persist(
'themeStore'
);
const darkThemes = [
const darkThemes = new Set([
'dark',
'synthwave',
'halloween',
@@ -25,13 +25,13 @@ const darkThemes = [
'luxury',
'black',
'dracula'
];
]);
export const setTheme = (theme: string): void => {
if (theme.includes(' ')) {
theme = theme.split(' ')[1].trim();
}
const isDark = darkThemes.includes(theme);
const isDark = darkThemes.has(theme);
console.log('Setting theme', theme);
themeStore.set({ theme, isDark });
logEvent('themeChange', { theme, isDark });
+10
View File
@@ -38,3 +38,13 @@ export const errorDebug = (limit = 100) => {
debugger;
}
};
export const formatJSON = (data: unknown): string => JSON.stringify(data, undefined, 2);
export const fetchJSON = async <T>(url: string): Promise<T> => {
const res = await fetch(url);
return res.json() as T;
};
export const fetchText = async (url: string): Promise<string> => {
const res = await fetch(url);
return res.text();
};
+2 -2
View File
@@ -9,11 +9,11 @@
import { inputStateStore, stateStore, updateCodeStore } from '$lib/util/state';
import { cmdKey, initHandler, syncDiagram } from '$lib/util/util';
import { onMount } from 'svelte';
import type { Tab, DocConfig, EditorMode, ValidatedState } from '$lib/types';
import type { Tab, DocumentationConfig, EditorMode, ValidatedState } from '$lib/types';
import { base } from '$app/paths';
const docURLBase = 'https://mermaid-js.github.io/mermaid';
const docMap: DocConfig = {
const docMap: DocumentationConfig = {
graph: {
code: '/#/flowchart',
config: '/#/flowchart?id=configuration'
+613 -182
View File
File diff suppressed because it is too large Load Diff