Compare commits

...
Author SHA1 Message Date
Sidharth Vinod 9c74126ce5 sample PW tests 2022-11-25 14:18:54 +05:30
Sidharth Vinod db92134444 Merge branch 'develop' into sidv/playwright
* develop: (174 commits)
  chore: cleanup
  fix: Error type
  chore: Bump node
  Show good error messages.
  chore: fix trailing slash
  chore(deps): update all non-major dependencies
  Block only tests
  snapshot
  Remove it.only
  fix #1103
  chore(deps): update all non-major dependencies
  Update Browserslist
  chore: Update deps
  fix: Remove AsyncQueue
  Update Browserslist
  Fix #1089: Update monaco-mermaid
  chore(deps): update all non-major dependencies
  fix lint
  chore: Cleanup, fix theme
  fix: Snapshot, env types
  ...
2022-11-25 13:36:46 +05:30
Sidharth Vinod 1b6a1910ce Merge pull request #1107 from mermaid-js/sidv/betterErrors
Show properly formatted error messages.
2022-11-25 13:32:58 +05:30
Sidharth Vinod f794fa9e0e chore: cleanup 2022-11-25 13:25:20 +05:30
Sidharth Vinod 17ca5f29d0 fix: Error type 2022-11-25 13:23:42 +05:30
Sidharth Vinod b7aae5f94f chore: Bump node 2022-11-25 13:19:12 +05:30
Sidharth Vinod ffd68c7551 Show good error messages. 2022-11-25 12:11:11 +05:30
Sidharth Vinod 909b95ba7b Merge pull request #1105 from mermaid-js/renovate/patch-all-minor-patch
chore(deps): update all non-major dependencies (patch)
2022-11-25 11:27:44 +05:30
Sidharth Vinod f4dd01c4fe chore: fix trailing slash 2022-11-25 11:17:30 +05:30
renovate[bot] 7508a555d4 chore(deps): update all non-major dependencies 2022-11-24 22:05:13 +00:00
Sidharth Vinod 9d3a33e593 Block only tests 2022-11-24 22:07:14 +05:30
Sidharth Vinod 0378cd4ba6 Merge branch 'sidv/fixEditorHang' into develop
* sidv/fixEditorHang:
  Remove it.only
2022-11-24 22:05:27 +05:30
Sidharth Vinod c518217ba7 Merge branch 'develop' of https://github.com/mermaid-js/mermaid-live-editor into develop
* 'develop' of https://github.com/mermaid-js/mermaid-live-editor:
  fix #1103
  fix: Remove AsyncQueue
  Update Browserslist
2022-11-24 22:04:52 +05:30
Sidharth Vinod c9a2e6bf09 snapshot 2022-11-24 22:04:48 +05:30
Sidharth Vinod f136f7bd58 Remove it.only 2022-11-24 22:04:15 +05:30
Sidharth Vinod 03d2be91e6 Merge pull request #1099 from mermaid-js/sidv/fixEditorHang
Remove AsyncQueue
2022-11-24 22:03:50 +05:30
Sidharth Vinod 3e6c28f15a fix #1103 2022-11-24 21:56:20 +05:30
Sidharth Vinod 2b800e960d Merge branch 'develop' into sidv/fixEditorHang
* develop:
  chore(deps): update all non-major dependencies
  Update Browserslist
  chore: Update deps
2022-11-24 21:26:47 +05:30
Sidharth Vinod 06bd4cf176 Merge pull request #1101 from mermaid-js/renovate/all-minor-patch
chore(deps): update all non-major dependencies (minor)
2022-11-24 21:16:10 +05:30
renovate[bot] 42a55e10a6 chore(deps): update all non-major dependencies 2022-11-24 14:57:03 +00:00
Sidharth Vinod 996db3b198 Merge pull request #1100 from mermaid-js/sidv/updateDeps
chore: Update deps
2022-11-24 20:24:51 +05:30
sidharthv96 7a598f408c Update Browserslist 2022-11-24 10:56:27 +00:00
Sidharth Vinod 924d10aac3 chore: Update deps 2022-11-24 16:25:12 +05:30
Sidharth Vinod 22df217b44 Merge branch 'sidv/fixEditorHang' of https://github.com/mermaid-js/mermaid-live-editor into sidv/fixEditorHang
* 'sidv/fixEditorHang' of https://github.com/mermaid-js/mermaid-live-editor:
  Update Browserslist
2022-11-24 16:20:08 +05:30
Sidharth Vinod 7c4c2a02f9 fix: Remove AsyncQueue 2022-11-24 16:20:01 +05:30
sidharthv96 20c6e9146c Update Browserslist 2022-11-24 10:30:12 +00:00
Sidharth Vinod afeb649833 Merge pull request #1095 from mermaid-js/develop
Release: Fix editor hang
2022-11-17 13:20:15 +05:30
Sidharth Vinod fcf53c98c2 Merge pull request #1094 from mermaid-js/sidv/fixEditorHang
Fix #1089: Update monaco-mermaid
2022-11-17 13:19:04 +05:30
Sidharth Vinod 749968e0f5 Fix #1089: Update monaco-mermaid 2022-11-17 11:21:21 +05:30
Sidharth Vinod ba56f08370 Merge pull request #1091 from mermaid-js/develop
Release
2022-11-15 20:43:45 +05:30
Sidharth Vinod d92bf85009 Merge pull request #1092 from mermaid-js/renovate/all-minor-patch
chore(deps): update all non-major dependencies (minor)
2022-11-15 20:33:03 +05:30
renovate[bot] 6936dc5755 chore(deps): update all non-major dependencies 2022-11-15 14:50:54 +00:00
Sidharth Vinod b41ff80d9d Merge pull request #1090 from mermaid-js/sidv/capitalizeSvelteComponents
chore: Capitalize components to be inline with svelte standards
2022-11-15 20:15:21 +05:30
Sidharth Vinod 68ab43ac5d fix lint 2022-11-15 19:59:13 +05:30
Sidharth Vinod 68b589a33a chore: Cleanup, fix theme 2022-11-15 19:51:00 +05:30
Sidharth Vinod 9eb39f31a0 fix: Snapshot, env types 2022-11-15 19:00:46 +05:30
Sidharth Vinod 08eaf725b9 chore: Cleanup potentially problematic code. 2022-11-15 18:57:33 +05:30
Sidharth Vinod 85ad89b915 chore: Cleanup potentially
problematic code.
2022-11-15 18:48:16 +05:30
Sidharth Vinod 60c352a849 Fix casing 2022-11-15 17:05:14 +05:30
Sidharth Vinod b0aa0a9cb2 fix: Type errors 2022-11-15 17:03:25 +05:30
Sidharth Vinod 34dafa13c9 test commit 2022-11-15 16:29:49 +05:30
Sidharth Vinod 684bd708de test commit 2022-11-15 16:29:05 +05:30
Sidharth Vinod d5ee6d4c02 Fix card.test.ts 2022-11-15 16:14:41 +05:30
Sidharth Vinod 233f1822d1 chore: Rename components 2022-11-15 16:04:36 +05:30
Sidharth Vinod b03d862b53 Playwright init 2022-08-13 13:47:10 +05:30
52 changed files with 1433 additions and 627 deletions
+17 -3
View File
@@ -5,9 +5,10 @@ module.exports = {
'eslint:recommended', 'eslint:recommended',
'plugin:@typescript-eslint/recommended', 'plugin:@typescript-eslint/recommended',
// 'plugin:@typescript-eslint/recommended-requiring-type-checking', // 'plugin:@typescript-eslint/recommended-requiring-type-checking',
'plugin:@typescript-eslint/strict',
'prettier' 'prettier'
], ],
plugins: ['svelte3', 'tailwindcss', '@typescript-eslint', 'es', 'vitest'], plugins: ['svelte3', 'tailwindcss', '@typescript-eslint', 'es', 'vitest', 'no-only-tests'],
ignorePatterns: [ ignorePatterns: [
'docs/*', 'docs/*',
'*.cjs', '*.cjs',
@@ -19,7 +20,19 @@ module.exports = {
'package.json', 'package.json',
'tsconfig.json' 'tsconfig.json'
], ],
overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }], overrides: [
{ files: ['*.svelte'], processor: 'svelte3/svelte3' },
{
files: ['*.ts'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended-requiring-type-checking',
'plugin:@typescript-eslint/strict',
'prettier'
]
}
],
settings: { settings: {
'svelte3/typescript': () => require('typescript') 'svelte3/typescript': () => require('typescript')
}, },
@@ -45,6 +58,7 @@ module.exports = {
'@typescript-eslint/no-unsafe-member-access': 'off', '@typescript-eslint/no-unsafe-member-access': 'off',
'@typescript-eslint/no-unsafe-assignment': 'off', '@typescript-eslint/no-unsafe-assignment': 'off',
'es/no-regexp-lookbehind-assertions': 'error', 'es/no-regexp-lookbehind-assertions': 'error',
curly: ['error', 'all'] curly: ['error', 'all'],
'no-only-tests/no-only-tests': 'error'
} }
}; };
+1 -1
View File
@@ -16,7 +16,7 @@ jobs:
- uses: actions/setup-node@v3 - uses: actions/setup-node@v3
with: with:
node-version: '16' node-version: 18
cache: yarn cache: yarn
- name: Build & Deploy - name: Build & Deploy
+27
View File
@@ -0,0 +1,27 @@
name: Playwright Tests
on:
push:
branches: [ main, master ]
pull_request:
branches: [ main, master ]
jobs:
test:
timeout-minutes: 60
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '14.x'
- name: Install dependencies
run: yarn
- name: Install Playwright Browsers
run: npx playwright install --with-deps
- name: Run Playwright tests
run: yarn playwright test
- uses: actions/upload-artifact@v2
if: always()
with:
name: playwright-report
path: playwright-report/
retention-days: 30
+1 -1
View File
@@ -32,7 +32,7 @@ jobs:
- uses: actions/setup-node@v3 - uses: actions/setup-node@v3
with: with:
node-version: 16 node-version: 18
cache: 'yarn' cache: 'yarn'
# Install NPM dependencies, cache them correctly # Install NPM dependencies, cache them correctly
+1 -1
View File
@@ -26,7 +26,7 @@ jobs:
- uses: actions/setup-node@v3 - uses: actions/setup-node@v3
with: with:
node-version: 16 node-version: 18
cache: 'yarn' cache: 'yarn'
- name: Lint & Test - name: Lint & Test
+3
View File
@@ -12,3 +12,6 @@ yarn-error.log
/cypress/downloads /cypress/downloads
/cypress/videos /cypress/videos
/cypress/screenshots /cypress/screenshots
/test-results/
/playwright-report/
/playwright/.cache/
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"editor.formatOnSave": true, "editor.formatOnSave": true,
"cSpell.words": ["asyncable", "mindmap", "pako", "Serde", "serdes"], "cSpell.words": ["asyncable", "KROKI", "mindmap", "pako", "Serde", "serdes", "tailwindcss"],
"vitest.commandLine": "yarn test:unit", "vitest.commandLine": "yarn test:unit",
"vitest.enable": true, "vitest.enable": true,
"testing.autoRun.mode": "rerun", "testing.autoRun.mode": "rerun",
+1 -1
View File
@@ -6,7 +6,7 @@
# Stop : press ctrl + c # Stop : press ctrl + c
# or # or
# docker stop mermaid-live-editor # docker stop mermaid-live-editor
FROM node:18.12.0 as mermaid-live-editor-builder FROM node:18.12.1 as mermaid-live-editor-builder
COPY --chown=node:node . /home COPY --chown=node:node . /home
WORKDIR /home WORKDIR /home
RUN yarn install RUN yarn install
+8
View File
@@ -69,6 +69,14 @@ describe('Auto sync tests', () => {
) )
.should('exist'); .should('exist');
}); });
it('should update diagram after entire text is removed', () => {
// https://github.com/mermaid-js/mermaid-live-editor/issues/1102
getEditor().type(`${cmd} a {backspace}`);
getEditor().type('graph LR');
getEditor().type(' {enter} A-->Car');
cy.get('#view').contains('Car').should('exist');
});
}); });
describe('Pan and Zoom', () => { describe('Pan and Zoom', () => {
+2
View File
@@ -17,6 +17,7 @@ export const verifyFileSize = (
) => { ) => {
const fileName = `mermaid-${fileType}-2022-01-01-000000.${extension}`; const fileName = `mermaid-${fileType}-2022-01-01-000000.${extension}`;
const filePath = `${downloadsFolder}/${fileName}`; const filePath = `${downloadsFolder}/${fileName}`;
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
cy.verifyDownload(fileName); cy.verifyDownload(fileName);
cy.readFile(filePath, null, { cy.readFile(filePath, null, {
log: false log: false
@@ -31,6 +32,7 @@ export const verifyFileSnapshot = (
) => { ) => {
const fileName = `mermaid-${fileType}-2022-01-01-000000.${extension}`; const fileName = `mermaid-${fileType}-2022-01-01-000000.${extension}`;
const filePath = `${downloadsFolder}/${fileName}`; const filePath = `${downloadsFolder}/${fileName}`;
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
cy.verifyDownload(fileName); cy.verifyDownload(fileName);
cy.readFile(filePath, null, { cy.readFile(filePath, null, {
log: false log: false
+1 -1
View File
@@ -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}\",\"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.10.0", "__version": "11.2.0",
"Auto sync tests": { "Auto sync tests": {
"should dim diagram when code is edited": { "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\":\"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}"
+33 -29
View File
@@ -19,61 +19,65 @@
"test:coverage": "vitest run --coverage", "test:coverage": "vitest run --coverage",
"test:browser": "cypress run", "test:browser": "cypress run",
"test": "test:unit && test:browser", "test": "test:unit && test:browser",
"cy": "cypress open" "cy": "cypress open",
"pw": "npx playwright test"
}, },
"devDependencies": { "devDependencies": {
"@cypress/snapshot": "2.1.7", "@cypress/snapshot": "2.1.7",
"@sveltejs/adapter-static": "1.0.0-next.46", "@playwright/test": "^1.28.1",
"@sveltejs/kit": "1.0.0-next.522", "@sveltejs/adapter-static": "1.0.0-next.48",
"@sveltejs/kit": "1.0.0-next.561",
"@testing-library/jest-dom": "5.16.5", "@testing-library/jest-dom": "5.16.5",
"@testing-library/svelte": "3.2.2", "@testing-library/svelte": "3.2.2",
"@types/pako": "2.0.0", "@types/pako": "2.0.0",
"@types/uuid": "8.3.4", "@types/uuid": "8.3.4",
"@typescript-eslint/eslint-plugin": "5.42.0", "@typescript-eslint/eslint-plugin": "5.44.0",
"@typescript-eslint/parser": "5.42.0", "@typescript-eslint/parser": "5.44.0",
"@vitest/ui": "0.25.1", "@vitest/ui": "^0.25.3",
"autoprefixer": "10.4.12", "autoprefixer": "^10.4.13",
"c8": "7.12.0", "c8": "7.12.0",
"chai": "4.3.6", "chai": "^4.3.7",
"cssnano": "5.1.13", "cssnano": "^5.1.14",
"cy-verify-downloads": "0.1.11", "cy-verify-downloads": "0.1.11",
"cypress": "11.0.1", "cypress": "11.2.0",
"cypress-localstorage-commands": "2.2.1", "cypress-localstorage-commands": "2.2.1",
"eslint": "8.27.0", "eslint": "8.28.0",
"eslint-config-prettier": "8.5.0", "eslint-config-prettier": "8.5.0",
"eslint-plugin-cypress": "2.12.1", "eslint-plugin-cypress": "2.12.1",
"eslint-plugin-es": "4.1.0", "eslint-plugin-es": "4.1.0",
"eslint-plugin-no-only-tests": "^3.1.0",
"eslint-plugin-postcss-modules": "2.0.0", "eslint-plugin-postcss-modules": "2.0.0",
"eslint-plugin-svelte3": "4.0.0", "eslint-plugin-svelte3": "4.0.0",
"eslint-plugin-tailwindcss": "3.6.2", "eslint-plugin-tailwindcss": "3.7.0",
"eslint-plugin-vitest": "0.0.11", "eslint-plugin-vitest": "^0.0.20",
"esserializer": "1.3.2", "esserializer": "1.3.5",
"husky": "8.0.1", "font-awesome": "^4.7.0",
"jsdom": "20.0.1", "husky": "^8.0.2",
"jsdom": "20.0.3",
"lint-staged": "13.0.3", "lint-staged": "13.0.3",
"node-html-parser": "6.1.1", "node-html-parser": "^6.1.4",
"postcss": "8.4.18", "postcss": "^8.4.19",
"postcss-load-config": "4.0.1", "postcss-load-config": "4.0.1",
"prettier": "2.7.1", "prettier": "2.8.0",
"prettier-plugin-svelte": "2.8.0", "prettier-plugin-svelte": "^2.8.1",
"svelte": "3.53.1", "svelte": "3.53.1",
"svelte-preprocess": "4.10.7", "svelte-preprocess": "4.10.7",
"tailwindcss": "3.2.1", "tailwindcss": "^3.2.4",
"tslib": "2.4.0", "tslib": "^2.4.1",
"typescript": "4.8.4", "typescript": "4.9.3",
"vite": "3.2.2", "vite": "^3.2.4",
"vitest": "0.25.1" "vitest": "^0.25.3"
}, },
"dependencies": { "dependencies": {
"@mermaid-js/mermaid-mindmap": "9.2.2", "@mermaid-js/mermaid-mindmap": "9.2.2",
"analytics": "0.8.1", "analytics": "0.8.1",
"analytics-plugin-plausible": "0.0.6", "analytics-plugin-plausible": "0.0.6",
"daisyui": "2.39.1", "daisyui": "2.42.1",
"js-base64": "3.7.2", "js-base64": "3.7.3",
"mermaid": "9.2.2", "mermaid": "9.2.2",
"moment": "2.29.4", "moment": "2.29.4",
"monaco-editor": "0.34.1", "monaco-editor": "0.34.1",
"monaco-mermaid": "1.0.6", "monaco-mermaid": "1.0.8",
"pako": "2.1.0", "pako": "2.1.0",
"random-word-slugs": "0.1.6", "random-word-slugs": "0.1.6",
"svg-pan-zoom": "3.6.1", "svg-pan-zoom": "3.6.1",
@@ -86,7 +90,7 @@
] ]
}, },
"volta": { "volta": {
"node": "18.12.0", "node": "18.12.1",
"yarn": "1.22.19" "yarn": "1.22.19"
}, },
"engines": { "engines": {
+106
View File
@@ -0,0 +1,106 @@
import type { PlaywrightTestConfig } from '@playwright/test';
import { devices } from '@playwright/test';
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
// require('dotenv').config();
/**
* See https://playwright.dev/docs/test-configuration.
*/
const config: PlaywrightTestConfig = {
testDir: './tests',
/* Maximum time one test can run for. */
timeout: 30 * 1000,
expect: {
/**
* Maximum time expect() should wait for the condition to be met.
* For example in `await expect(locator).toHaveText();`
*/
timeout: 5000
},
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'html',
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
actionTimeout: 0,
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: 'http://localhost:3000',
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry'
},
/* Configure projects for major browsers */
projects: [
{
name: 'chromium',
use: {
...devices['Desktop Chrome']
}
}
// {
// name: 'firefox',
// use: {
// ...devices['Desktop Firefox'],
// },
// },
// {
// name: 'webkit',
// use: {
// ...devices['Desktop Safari'],
// },
// },
/* Test against mobile viewports. */
// {
// name: 'Mobile Chrome',
// use: {
// ...devices['Pixel 5'],
// },
// },
// {
// name: 'Mobile Safari',
// use: {
// ...devices['iPhone 12'],
// },
// },
/* Test against branded browsers. */
// {
// name: 'Microsoft Edge',
// use: {
// channel: 'msedge',
// },
// },
// {
// name: 'Google Chrome',
// use: {
// channel: 'chrome',
// },
// },
]
/* Folder for test artifacts such as screenshots, videos, traces, etc. */
// outputDir: 'test-results/',
/* Run your local dev server before starting the tests */
// webServer: {
// command: 'npm run start',
// port: 3000,
// },
};
export default config;
+2 -2
View File
@@ -17,8 +17,8 @@
<link rel="manifest" href="%sveltekit.assets%/manifest.json" /> <link rel="manifest" href="%sveltekit.assets%/manifest.json" />
<link <link
rel="stylesheet" rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w=="
crossorigin="anonymous" crossorigin="anonymous"
referrerpolicy="no-referrer" /> referrerpolicy="no-referrer" />
<link <link
+5 -5
View File
@@ -1,11 +1,11 @@
/// <reference types="vite/client" /> /// <reference types="vite/client" />
interface ImportMetaEnv { interface ImportMetaEnv {
readonly MERMAID_RENDERER_URL: string; readonly MERMAID_RENDERER_URL?: string;
readonly MERMAID_KROKI_RENDERER_URL: string; readonly MERMAID_KROKI_RENDERER_URL?: string;
readonly MERMAID_CDN_URL: string; readonly MERMAID_CDN_URL?: string;
readonly MERMAID_BASE_URL: string; readonly MERMAID_BASE_URL?: string;
readonly MERMAID_LOCAL: boolean; readonly MERMAID_LOCAL?: boolean;
// more env variables... // more env variables...
} }
+2 -1
View File
@@ -9,7 +9,8 @@ declare global {
namespace jest { namespace jest {
interface Matchers<R = void> interface Matchers<R = void>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore // @ts-expect-error
// eslint-disable-next-line no-undef
extends TestingLibraryMatchers<typeof expect.stringContaining, R> {} extends TestingLibraryMatchers<typeof expect.stringContaining, R> {}
} }
} }
@@ -1,6 +1,6 @@
<script lang="ts"> <script lang="ts">
import { browser } from '$app/environment'; import { browser } from '$app/environment';
import Card from '$lib/components/card/card.svelte'; import Card from '$lib/components/Card/Card.svelte';
import { env } from '$lib/util/env'; import { env } from '$lib/util/env';
import { pakoSerde } from '$lib/util/serde'; import { pakoSerde } from '$lib/util/serde';
import { stateStore } from '$lib/util/state'; import { stateStore } from '$lib/util/state';
@@ -15,8 +15,8 @@
`mermaid-diagram-${moment().format('YYYY-MM-DD-HHmmss')}.${ext}`; `mermaid-diagram-${moment().format('YYYY-MM-DD-HHmmss')}.${ext}`;
const getBase64SVG = (svg?: HTMLElement, width?: number, height?: number): string => { const getBase64SVG = (svg?: HTMLElement, width?: number, height?: number): string => {
svg?.setAttribute('height', `${height}px`); height && 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 width && svg?.setAttribute('width', `${width}px`); // Workaround https://stackoverflow.com/questions/28690643/firefox-error-rendering-an-svg-image-to-html5-canvas-with-drawimage
if (!svg) { if (!svg) {
svg = getSvgEl(); svg = getSvgEl();
} }
@@ -28,7 +28,10 @@
const exportImage = (event: Event, exporter: Exporter) => { const exportImage = (event: Event, exporter: Exporter) => {
const canvas: HTMLCanvasElement = document.createElement('canvas'); const canvas: HTMLCanvasElement = document.createElement('canvas');
const svg: HTMLElement = document.querySelector('#container svg'); const svg: HTMLElement | null = document.querySelector('#container svg');
if (!svg) {
throw new Error('svg not found');
}
const box: DOMRect = svg.getBoundingClientRect(); const box: DOMRect = svg.getBoundingClientRect();
canvas.width = box.width; canvas.width = box.width;
canvas.height = box.height; canvas.height = box.height;
@@ -43,6 +46,9 @@
} }
const context = canvas.getContext('2d'); const context = canvas.getContext('2d');
if (!context) {
throw new Error('context not found');
}
context.fillStyle = 'white'; context.fillStyle = 'white';
context.fillRect(0, 0, canvas.width, canvas.height); context.fillRect(0, 0, canvas.width, canvas.height);
@@ -56,12 +62,12 @@
const getSvgEl = () => { const getSvgEl = () => {
const svgEl: HTMLElement = document const svgEl: HTMLElement = document
.querySelector('#container svg') .querySelector('#container svg')!
.cloneNode(true) as HTMLElement; .cloneNode(true) as HTMLElement;
svgEl.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); svgEl.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
const fontAwesomeCdnUrl = Array.from(document.head.getElementsByTagName('link')) const fontAwesomeCdnUrl = Array.from(document.head.getElementsByTagName('link'))
.map((l) => l.href) .map((l) => l.href)
.find((h) => h && h.includes('font-awesome')); .find((h) => h.includes('font-awesome'));
if (fontAwesomeCdnUrl == null) { if (fontAwesomeCdnUrl == null) {
return svgEl; return svgEl;
} }
@@ -99,10 +105,10 @@
context.drawImage(image, 0, 0, canvas.width, canvas.height); context.drawImage(image, 0, 0, canvas.width, canvas.height);
canvas.toBlob((blob) => { canvas.toBlob((blob) => {
try { try {
// @ts-ignore: https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1004/files if (!blob) {
throw new Error('blob is empty');
}
void navigator.clipboard.write([ void navigator.clipboard.write([
/* eslint-disable no-undef */
// @ts-ignore: https://github.com/microsoft/TypeScript/issues/43821
new ClipboardItem({ new ClipboardItem({
[blob.type]: blob [blob.type]: blob
}) })
@@ -142,7 +148,7 @@
let gistURL = ''; let gistURL = '';
stateStore.subscribe(({ loader }) => { stateStore.subscribe(({ loader }) => {
if (loader?.type === 'gist') { if (loader?.type === 'gist') {
// @ts-ignore Gist will have url // @ts-expect-error Gist will have url
gistURL = loader.config.url; gistURL = loader.config.url;
} }
}); });
@@ -166,8 +172,7 @@
if (browser && ['mermaid.live', 'netlify'].some((path) => window.location.host.includes(path))) { if (browser && ['mermaid.live', 'netlify'].some((path) => window.location.host.includes(path))) {
isNetlify = true; isNetlify = true;
} }
stateStore.subscribe(async (state) => { stateStore.subscribe(({ code, serialized }) => {
const { code, serialized } = await state;
iUrl = `${rendererUrl}/img/${serialized}?type=png`; iUrl = `${rendererUrl}/img/${serialized}?type=png`;
svgUrl = `${rendererUrl}/svg/${serialized}`; svgUrl = `${rendererUrl}/svg/${serialized}`;
krokiUrl = `${krokiRendererUrl}/mermaid/svg/${pakoSerde.serialize(code)}`; krokiUrl = `${krokiRendererUrl}/mermaid/svg/${pakoSerde.serialize(code)}`;
@@ -1,11 +1,11 @@
<script lang="ts"> <script lang="ts">
import type { Tab } from '$lib/types'; import type { Tab } from '$lib/types';
import { slide } from 'svelte/transition'; import { slide } from 'svelte/transition';
import Tabs from './tabs.svelte'; import Tabs from './Tabs.svelte';
export let isCloseable = true; export let isCloseable = true;
export let isOpen = true; export let isOpen = true;
export let tabs: Tab[] = []; export let tabs: Tab[] = [];
export let activeTabID: string = ''; export let activeTabID = '';
export let title: string; export let title: string;
$: isOpen = isCloseable ? isOpen : true; $: isOpen = isCloseable ? isOpen : true;
$: isTabsShown = isOpen && tabs.length > 0; $: isTabsShown = isOpen && tabs.length > 0;
@@ -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-lTROw8sJayZ1\\"><span class=\\"mr-2 font-semibold s-lTROw8sJayZ1\\"><i class=\\"fas fa-chevron-right icon s-lTROw8sJayZ1 isOpen\\"></i> TabTest</span> <ul class=\\"tabs s-lTROw8sJayZ1\\"><div class=\\"tab tab-lifted tab-active s-lTROw8sJayZ1\\"><i class=\\"mr-1 fab fa-git-alt s-lTROw8sJayZ1\\"></i> title1 </div><div class=\\"tab tab-lifted text-primary-content s-lTROw8sJayZ1\\"><i class=\\"mr-1 far fa-bookmark s-lTROw8sJayZ1\\"></i> title2 </div></ul></div><!--<Tabs>--> <div class=\\"flex gap-x-4 items-center -mt-2\\"></div></div></div> <div class=\\"card-body p-0 flex-grow overflow-auto text-base-content\\"></div></div><!--<Card>--></div>"`;
@@ -1,6 +1,6 @@
import { cleanup, render } from '@testing-library/svelte'; import { cleanup, render } from '@testing-library/svelte';
import { describe, expect, it, afterEach } from 'vitest'; import { describe, expect, it, afterEach } from 'vitest';
import Card from './card.svelte'; import Card from './Card.svelte';
describe('card.svelte', () => { describe('card.svelte', () => {
// TODO: @testing-library/svelte claims to add this automatically but it doesn't work without explicit afterEach // TODO: @testing-library/svelte claims to add this automatically but it doesn't work without explicit afterEach
@@ -10,8 +10,8 @@ describe('card.svelte', () => {
const { container } = render(Card, { const { container } = render(Card, {
title: 'TabTest', title: 'TabTest',
tabs: [ tabs: [
{ id: 't1', title: 'title1' }, { id: 't1', title: 'title1', icon: 'fab fa-git-alt' },
{ id: 't2', title: 'title2' } { id: 't2', title: 'title2', icon: 'far fa-bookmark' }
] ]
}); });
expect(container).toBeTruthy(); expect(container).toBeTruthy();
@@ -8,9 +8,9 @@
import initEditor from 'monaco-mermaid'; import initEditor from 'monaco-mermaid';
import { logEvent } from '$lib/util/stats'; import { logEvent } from '$lib/util/stats';
let divEl: HTMLDivElement = null; let divEl: HTMLDivElement | undefined = undefined;
let editor: monaco.editor.IStandaloneCodeEditor; let editor: monaco.editor.IStandaloneCodeEditor | undefined;
let Monaco: typeof monaco; let Monaco: typeof monaco | undefined;
let editorOptions: monaco.editor.IStandaloneEditorConstructionOptions = { let editorOptions: monaco.editor.IStandaloneEditorConstructionOptions = {
minimap: { minimap: {
enabled: false enabled: false
@@ -22,7 +22,9 @@
stateStore.subscribe(({ errorMarkers, editorMode, code, mermaid }) => { stateStore.subscribe(({ errorMarkers, editorMode, code, mermaid }) => {
console.log('editor store subscription', { code, mermaid }); console.log('editor store subscription', { code, mermaid });
if (!editor) return; if (!editor || !Monaco) {
return;
}
// Update editor text if it's different // Update editor text if it's different
const newText = editorMode === 'code' ? code : mermaid; const newText = editorMode === 'code' ? code : mermaid;
@@ -34,12 +36,17 @@
// Update editor mode if it's different // Update editor mode if it's different
const language = editorMode === 'code' ? 'mermaid' : 'json'; const language = editorMode === 'code' ? 'mermaid' : 'json';
if (editor.getModel().getLanguageId() !== language) { const model = editor.getModel();
Monaco?.editor.setModelLanguage(editor.getModel(), language); if (!model) {
console.error("editor model doesn't exist");
return;
}
if (model.getLanguageId() !== language) {
Monaco.editor.setModelLanguage(model, language);
} }
// Display/clear errors // Display/clear errors
Monaco?.editor.setModelMarkers(editor.getModel(), 'mermaid', errorMarkers); Monaco.editor.setModelMarkers(model, 'mermaid', errorMarkers);
}); });
themeStore.subscribe(({ isDark }) => { themeStore.subscribe(({ isDark }) => {
@@ -60,7 +67,7 @@
// errorDebug(); // errorDebug();
let i = 0; let i = 0;
while (i++ < 500) { while (i++ < 500) {
// @ts-ignore : This is a hack to handle a svelte-kit error when importing monaco. // @ts-expect-error : This is a hack to handle a svelte-kit error when importing monaco.
Monaco = window.monaco; Monaco = window.monaco;
if (Monaco !== undefined) { if (Monaco !== undefined) {
return; return;
@@ -72,13 +79,20 @@
onMount(async () => { onMount(async () => {
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
if (!Monaco) {
throw new Error('Monaco failed to load');
}
if (!divEl) {
throw new Error('divEl is undefined');
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
initEditor(Monaco); initEditor(Monaco);
errorDebug(100); errorDebug(100);
editor = Monaco.editor.create(divEl, editorOptions); editor = Monaco.editor.create(divEl, editorOptions);
editor.onDidChangeModelContent(({ isFlush, changes }) => { editor.onDidChangeModelContent(({ isFlush, changes }) => {
const newText = editor.getValue(); const newText = editor?.getValue();
console.log('editor onDidChangeModelContent', { text, newText, isFlush, changes }); console.log('editor onDidChangeModelContent', { text, newText, isFlush, changes });
if (text === newText || isFlush) { if (!newText || text === newText || isFlush) {
return; return;
} }
text = newText; text = newText;
@@ -95,19 +109,21 @@
}); });
} }
}); });
Monaco?.editor.setTheme($themeStore.isDark ? 'mermaid-dark' : 'mermaid'); Monaco.editor.setTheme($themeStore.isDark ? 'mermaid-dark' : 'mermaid');
const resizeObserver = new ResizeObserver((entries) => { const resizeObserver = new ResizeObserver((entries) => {
editor.layout({ editor!.layout({
height: entries[0].contentRect.height, height: entries[0].contentRect.height,
width: entries[0].contentRect.width width: entries[0].contentRect.width
}); });
}); });
resizeObserver.observe(divEl.parentElement); if (divEl.parentElement) {
resizeObserver.observe(divEl.parentElement);
}
console.log(`editor mounted`); console.log(`editor mounted`);
return () => { return () => {
console.log(`editor disposed`); console.log(`editor disposed`);
editor.dispose(); editor?.dispose();
}; };
}); });
</script> </script>
@@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import Card from '$lib/components/card/card.svelte'; import Card from '$lib/components/Card/Card.svelte';
import { inputStateStore, getStateString } from '$lib/util/state'; import { inputStateStore, getStateString } from '$lib/util/state';
import { import {
addHistoryEntry, addHistoryEntry,
@@ -14,7 +14,7 @@
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import { get } from 'svelte/store'; import { get } from 'svelte/store';
import moment from 'moment'; import moment from 'moment';
import type { HistoryType, State, Tab } from '$lib/types'; import type { HistoryEntry, HistoryType, State, Tab } from '$lib/types';
import { logEvent } from '$lib/util/stats'; import { logEvent } from '$lib/util/stats';
const HISTORY_SAVE_INTERVAL = 60000; const HISTORY_SAVE_INTERVAL = 60000;
@@ -60,7 +60,7 @@
} }
const reader = new FileReader(); const reader = new FileReader();
reader.onload = (e) => { reader.onload = (e) => {
const data = JSON.parse(e.target.result as string); const data: HistoryEntry[] = JSON.parse(e.target.result as string);
restoreHistory(data); restoreHistory(data);
}; };
reader.readAsText(file); reader.readAsText(file);
@@ -7,7 +7,7 @@ import {
historyModeStore, historyModeStore,
historyStore historyStore
} from './history'; } from './history';
import { defaultState } from '../../util/state'; import { defaultState } from '$lib/util/state';
import { get } from 'svelte/store'; import { get } from 'svelte/store';
describe('history', () => { describe('history', () => {
@@ -21,9 +21,9 @@ describe('history', () => {
type: 'manual' type: 'manual'
}); });
const [manualEntry]: HistoryEntry[] = JSON.parse( const [manualEntry] = JSON.parse(
window.localStorage.getItem('manualHistoryStore') window.localStorage.getItem('manualHistoryStore') ?? '[]'
); ) as HistoryEntry[];
expect(manualEntry.time).toBe(12345); expect(manualEntry.time).toBe(12345);
expect(manualEntry.type).toBe('manual'); expect(manualEntry.type).toBe('manual');
@@ -36,7 +36,9 @@ describe('history', () => {
type: 'auto' type: 'auto'
}); });
const [autoEntry]: HistoryEntry[] = JSON.parse(window.localStorage.getItem('autoHistoryStore')); const [autoEntry] = JSON.parse(
window.localStorage.getItem('autoHistoryStore') ?? '[]'
) as HistoryEntry[];
expect(autoEntry.time).toBe(54321); expect(autoEntry.time).toBe(54321);
expect(autoEntry.type).toBe('auto'); expect(autoEntry.type).toBe('auto');
@@ -101,19 +103,23 @@ describe('history migration', () => {
'autoHistoryStore', 'autoHistoryStore',
'[{"state":{"code":"graph TD\\n A[New Year] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":false},"time":0,"type":"auto","name":"barking-dog"},{"state":{"code":"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":true},"time":0,"type":"manual","name":"needy-mosquito"}]' '[{"state":{"code":"graph TD\\n A[New Year] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":false},"time":0,"type":"auto","name":"barking-dog"},{"state":{"code":"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":true},"time":0,"type":"manual","name":"needy-mosquito"}]'
); );
let manualHistoryStore: HistoryEntry[] = JSON.parse( let manualHistoryStore = JSON.parse(
window.localStorage.getItem('manualHistoryStore') window.localStorage.getItem('manualHistoryStore') ?? '[]'
); ) as HistoryEntry[];
let autoHistoryStore: HistoryEntry[] = JSON.parse( let autoHistoryStore = JSON.parse(
window.localStorage.getItem('autoHistoryStore') window.localStorage.getItem('autoHistoryStore') ?? '[]'
); ) as HistoryEntry[];
expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(false); expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(false);
expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(false); expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(false);
injectHistoryIDs(); injectHistoryIDs();
manualHistoryStore = JSON.parse(window.localStorage.getItem('manualHistoryStore')); manualHistoryStore = JSON.parse(
autoHistoryStore = JSON.parse(window.localStorage.getItem('autoHistoryStore')); window.localStorage.getItem('manualHistoryStore') ?? '[]'
) as HistoryEntry[];
autoHistoryStore = JSON.parse(
window.localStorage.getItem('autoHistoryStore') ?? '[]'
) as HistoryEntry[];
expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(true); expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(true);
expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(true); expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(true);
}); });
@@ -1,13 +1,13 @@
<script context="module"> <script context="module" lang="ts">
import { version } from 'mermaid/package.json'; import { version } from 'mermaid/package.json';
import { analytics } from '$lib/util/stats'; import { analytics } from '$lib/util/stats';
analytics?.track('version', { void analytics?.track('version', {
mermaidVersion: version mermaidVersion: version
}); });
</script> </script>
<script lang="ts"> <script lang="ts">
import Theme from './theme.svelte'; import Theme from './Theme.svelte';
interface Link { interface Link {
title: string; title: string;
@@ -1,6 +1,6 @@
<script lang="ts"> <script lang="ts">
import { updateCode } from '$lib/util/state'; import { updateCode } from '$lib/util/state';
import Card from '$lib/components/card/card.svelte'; import Card from '$lib/components/Card/Card.svelte';
import { logEvent } from '$lib/util/stats'; import { logEvent } from '$lib/util/stats';
const samples = { const samples = {
@@ -104,7 +104,8 @@
Mermaid` Mermaid`
}; };
const loadSampleDiagram = (diagramType: string): void => { type SampleTypes = keyof typeof samples;
const loadSampleDiagram = (diagramType: SampleTypes): void => {
updateCode(samples[diagramType], { updateCode(samples[diagramType], {
updateDiagram: true, updateDiagram: true,
resetPanZoom: true resetPanZoom: true
@@ -113,8 +114,8 @@
}; };
// Adding in this array will add an icon to the preset menu // Adding in this array will add an icon to the preset menu
const newDiagrams: Array<keyof typeof samples> = ['Mindmap']; const newDiagrams: SampleTypes[] = ['Mindmap'];
const diagramOrder: Array<keyof typeof samples> = [ const diagramOrder: SampleTypes[] = [
'Sequence', 'Sequence',
'Flow', 'Flow',
'Class', 'Class',
@@ -1,4 +1,4 @@
<script> <script lang="ts">
import { setTheme, themeStore } from '$lib/util/theme'; import { setTheme, themeStore } from '$lib/util/theme';
const themes = [ const themes = [
@@ -52,7 +52,7 @@
<!-- svelte-ignore a11y-no-noninteractive-tabindex --> <!-- svelte-ignore a11y-no-noninteractive-tabindex -->
<ul tabindex="0" class="p-4 menu compact"> <ul tabindex="0" class="p-4 menu compact">
{#each themes as theme} {#each themes as theme}
<li class={theme.includes($themeStore.theme) ? 'bordered' : ''}> <li class:bordered={$themeStore.theme !== undefined && theme.includes($themeStore.theme)}>
<span <span
class="btn btn-ghost justify-start" class="btn btn-ghost justify-start"
on:click={() => setTheme(theme)} on:click={() => setTheme(theme)}
@@ -4,8 +4,9 @@
import panzoom from 'svg-pan-zoom'; import panzoom from 'svg-pan-zoom';
import type { State, ValidatedState } from '$lib/types'; import type { State, ValidatedState } from '$lib/types';
import { logEvent } from '$lib/util/stats'; import { logEvent } from '$lib/util/stats';
import { AsyncQueue, cmdKey } from '$lib/util/util'; import { cmdKey } from '$lib/util/util';
import { render as renderDiagram } from '$lib/util/mermaid'; import { render as renderDiagram } from '$lib/util/mermaid';
import type { MermaidConfig } from 'mermaid';
let code = ''; let code = '';
let config = ''; let config = '';
@@ -16,9 +17,12 @@
let hide = false; let hide = false;
let manualUpdate = true; let manualUpdate = true;
let panZoomEnabled = $stateStore.panZoom; let panZoomEnabled = $stateStore.panZoom;
let pzoom: SvgPanZoom.Instance; let pzoom: typeof panzoom | undefined;
const handlePanZoomChange = () => { const handlePanZoomChange = () => {
if (!pzoom) {
return;
}
const pan = pzoom.getPan(); const pan = pzoom.getPan();
const zoom = pzoom.getZoom(); const zoom = pzoom.getZoom();
updateCodeStore({ pan, zoom }); updateCodeStore({ pan, zoom });
@@ -32,8 +36,11 @@
hide = true; hide = true;
pzoom?.destroy(); pzoom?.destroy();
pzoom = undefined; pzoom = undefined;
Promise.resolve().then(() => { void Promise.resolve().then(() => {
const graphDiv = document.getElementById('graph-div'); const graphDiv = document.getElementById('graph-div');
if (!graphDiv) {
return;
}
pzoom = panzoom(graphDiv, { pzoom = panzoom(graphDiv, {
onPan: handlePanZoomChange, onPan: handlePanZoomChange,
onZoom: handlePanZoomChange, onZoom: handlePanZoomChange,
@@ -70,10 +77,10 @@
code = state.code; code = state.code;
config = state.mermaid; config = state.mermaid;
panZoomEnabled = state.panZoom; panZoomEnabled = state.panZoom;
const scroll = view.parentElement.scrollTop; const scroll = view.parentElement!.scrollTop;
delete container.dataset.processed; delete container.dataset.processed;
await renderDiagram( await renderDiagram(
Object.assign({}, JSON.parse(state.mermaid)), Object.assign({}, JSON.parse(state.mermaid)) as MermaidConfig,
code, code,
'graph-div', 'graph-div',
(svgCode, bindFunctions) => { (svgCode, bindFunctions) => {
@@ -82,6 +89,9 @@
container.innerHTML = svgCode; container.innerHTML = svgCode;
// console.log(container.innerHTML); // console.log(container.innerHTML);
const graphDiv = document.getElementById('graph-div'); const graphDiv = document.getElementById('graph-div');
if (!graphDiv) {
throw new Error('graph-div not found');
}
graphDiv.setAttribute('height', '100%'); graphDiv.setAttribute('height', '100%');
graphDiv.style.maxWidth = '100%'; graphDiv.style.maxWidth = '100%';
if (bindFunctions) { if (bindFunctions) {
@@ -90,7 +100,7 @@
} }
} }
); );
view.parentElement.scrollTop = scroll; view.parentElement!.scrollTop = scroll;
error = false; error = false;
} else if (manualUpdate) { } else if (manualUpdate) {
manualUpdate = false; manualUpdate = false;
@@ -103,11 +113,9 @@
} }
}; };
const q = new AsyncQueue(handleStateChange);
onMount(() => { onMount(() => {
stateStore.subscribe(async (state) => { stateStore.subscribe((state) => {
await q.process(state); void handleStateChange(state);
}); });
window.addEventListener('resize', () => { window.addEventListener('resize', () => {
if ($stateStore.panZoom && pzoom) { if ($stateStore.panZoom && pzoom) {
@@ -120,12 +128,12 @@
{#if (error && $stateStore.error instanceof Error) || outOfSync} {#if (error && $stateStore.error instanceof Error) || outOfSync}
<div <div
class="absolute w-full p-2 z-10 {error class="absolute w-full p-2 z-10 font-mono {error
? 'text-red-600' ? 'text-red-600'
: 'text-yellow-600'} bg-base-100 bg-opacity-80 text-center" : 'text-yellow-600'} bg-base-100 bg-opacity-80 text-center"
id="errorContainer"> id="errorContainer">
{#if error} {#if error}
{$stateStore.error} {@html $stateStore.error.toString().replace(/\n/g, '<br />')}
{:else} {:else}
Diagram out of sync. <br /> Diagram out of sync. <br />
Press <i class="fas fa-sync" /> (Sync button) or <kbd>{cmdKey} + Enter</kbd> to sync. Press <i class="fas fa-sync" /> (Sync button) or <kbd>{cmdKey} + Enter</kbd> to sync.
@@ -1,3 +0,0 @@
// Vitest Snapshot v1
exports[`card.svelte > mounts 1`] = `"<div><div class=\\"card rounded overflow-hidden m-2 flex-grow flex flex-col shadow-2xl\\"><div class=\\"bg-primary p-2 pb-0 flex-none cursor-pointer\\"><div class=\\"flex justify-between\\"><div class=\\"flex cursor-default s-_wx1E_JHsCoF\\"><span class=\\"mr-2 font-semibold s-_wx1E_JHsCoF\\"><i class=\\"fas fa-chevron-right icon s-_wx1E_JHsCoF isOpen\\"></i> TabTest</span> <ul class=\\"tabs s-_wx1E_JHsCoF\\"><div class=\\"tab tab-lifted tab-active s-_wx1E_JHsCoF\\"><i class=\\"mr-1 undefined s-_wx1E_JHsCoF\\"></i> title1 </div><div class=\\"tab tab-lifted text-primary-content s-_wx1E_JHsCoF\\"><i class=\\"mr-1 undefined s-_wx1E_JHsCoF\\"></i> title2 </div></ul></div><!--<Tabs>--> <div class=\\"flex gap-x-4 items-center -mt-2\\"></div></div></div> <div class=\\"card-body p-0 flex-grow overflow-auto text-base-content\\"></div></div><!--<Card>--></div>"`;
+15 -13
View File
@@ -1,11 +1,3 @@
/**
* Can be made globally available by placing this
* inside `global.d.ts` and removing `export` keyword
*/
export interface Locals {
userid: string;
}
export interface MarkerData { export interface MarkerData {
severity: number; severity: number;
message: string; message: string;
@@ -40,7 +32,7 @@ export interface State {
export interface ValidatedState extends State { export interface ValidatedState extends State {
editorMode: EditorMode; editorMode: EditorMode;
error: unknown; error?: Error;
errorMarkers: MarkerData[]; errorMarkers: MarkerData[];
serialized: string; serialized: string;
} }
@@ -73,14 +65,24 @@ export type HistoryEntry = { id: string; state: State; time: number; url?: strin
} }
); );
export interface DocConfig { export type DocConfig = Record<
[key: string]: { string,
{
code: string; code: string;
config?: string; config?: string;
}; }
} >;
export type EditorMode = 'code' | 'config'; export type EditorMode = 'code' | 'config';
export type Loader = (url: string) => Promise<State>; export type Loader = (url: string) => Promise<State>;
export type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>; export type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
export interface ErrorHash {
loc: {
first_line: number;
last_line: number;
first_column: number;
last_column: number;
};
}
+57 -38
View File
@@ -3,17 +3,23 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access */ /* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
import type { State } from '$lib/types'; import type { State } from '$lib/types';
import { defaultState } from '../state'; import { defaultState } from '$lib/util/state';
import { addHistoryEntry } from '../../components/history/history'; import { addHistoryEntry } from '$lib/components/History/history';
const codeFileName = 'code.mmd'; const codeFileName = 'code.mmd';
const configFileName = 'config.json'; const configFileName = 'config.json';
interface GithubFile {
truncated: boolean;
raw_url: string;
content: string;
}
const isValidGist = (files: any): boolean => { const isValidGist = (files: any): boolean => {
return codeFileName in files; return codeFileName in files;
}; };
const getFileContent = async (file: any): Promise<string> => { const getFileContent = async (file: GithubFile): Promise<string> => {
if (file.truncated) { if (file.truncated) {
return await (await fetch(file.raw_url)).text(); return await (await fetch(file.raw_url)).text();
} }
@@ -29,16 +35,26 @@ interface GistData {
url: string; url: string;
} }
interface GistResponse {
files: Record<string, GithubFile>;
html_url: string;
history: { url: string; committed_at: string; version: string; user: { login: string } }[];
}
const getGistData = async (gistURL: string): Promise<GistData> => { const getGistData = async (gistURL: string): Promise<GistData> => {
const path = gistURL.split('github.com').pop();
if (!path) {
throw new Error('Invalid GitHub URL' + gistURL);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_, __, gistID, revisionID] = gistURL.split('github.com').pop().split('/'); const [_, __, gistID, revisionID] = path.split('/');
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const { html_url, files, history } = await ( const { html_url, files, history }: GistResponse = await (
await fetch(`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`) await fetch(`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`)
).json(); ).json();
if (isValidGist(files)) { if (isValidGist(files)) {
const code = await getFileContent(files[codeFileName]); const code = await getFileContent(files[codeFileName]);
let config: string; let config = '{}';
if (configFileName in files) { if (configFileName in files) {
config = await getFileContent(files[configFileName]); config = await getFileContent(files[configFileName]);
} }
@@ -50,10 +66,10 @@ const getGistData = async (gistURL: string): Promise<GistData> => {
config, config,
author: currentItem.user.login, author: currentItem.user.login,
time: new Date(currentItem.committed_at).getTime(), time: new Date(currentItem.committed_at).getTime(),
version: (currentItem.version as string).slice(-7) version: currentItem.version.slice(-7)
}; };
} else { } else {
throw 'Invalid gist provided'; throw new Error('Invalid gist provided');
} }
}; };
@@ -73,35 +89,38 @@ const getStateFromGist = (gist: GistData, gistURL: string = gist.url): State =>
}; };
export const loadGistData = async (gistURL: string): Promise<State> => { export const loadGistData = async (gistURL: string): Promise<State> => {
try { const path = gistURL.split('github.com').pop();
// eslint-disable-next-line @typescript-eslint/no-unused-vars if (!path) {
const [_, __, gistID, revisionID] = gistURL.split('github.com').pop().split('/'); throw new Error('Invalid GitHub URL' + gistURL);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const { history } = await (
await fetch(`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`)
).json();
const gistHistory: GistData[] = [];
for (const entry of history) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const data: GistData = await getGistData(entry.url).catch(() => undefined);
data && gistHistory.push(data);
}
if (gistHistory.length === 0) {
throw 'Invalid gist provided';
}
gistHistory.reverse();
const state = getStateFromGist(gistHistory.slice(-1).pop(), gistURL);
for (const gist of gistHistory) {
addHistoryEntry({
state: getStateFromGist(gist),
time: gist.time,
type: 'loader',
url: gist.url,
name: `${gist.author} v${gist.version}`
});
}
return state;
} catch (err) {
console.error(err);
} }
// 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 gistHistory: GistData[] = [];
for (const entry of history) {
const data: GistData | undefined = await getGistData(entry.url).catch(() => undefined);
data && gistHistory.push(data);
}
if (gistHistory.length === 0) {
throw new Error('Invalid gist provided');
}
gistHistory.reverse();
const entry = gistHistory.slice(-1).pop();
if (!entry) {
throw new Error('Invalid gist provided');
}
const state = getStateFromGist(entry, gistURL);
for (const gist of gistHistory) {
addHistoryEntry({
state: getStateFromGist(gist),
time: gist.time,
type: 'loader',
url: gist.url,
name: `${gist.author} v${gist.version}`
});
}
return state;
}; };
+7 -6
View File
@@ -8,10 +8,11 @@ const loaders: Record<string, Loader> = {
export const loadDataFromUrl = async (): Promise<void> => { export const loadDataFromUrl = async (): Promise<void> => {
const searchParams = new URLSearchParams(window.location.search); const searchParams = new URLSearchParams(window.location.search);
let state: Partial<State> = defaultState; let state: Partial<State> = defaultState;
let code: string, config: string; let code: string | undefined = undefined;
let config: string | undefined = undefined;
let loaded = false; let loaded = false;
const codeURL: string = searchParams.get('code'); const codeURL: string | undefined = searchParams.get('code') ?? undefined;
const configURL: string = searchParams.get('config'); const configURL: string | undefined = searchParams.get('config') ?? undefined;
if (codeURL) { if (codeURL) {
code = await (await fetch(codeURL)).text(); code = await (await fetch(codeURL)).text();
@@ -23,9 +24,6 @@ export const loadDataFromUrl = async (): Promise<void> => {
config = defaultState.mermaid; config = defaultState.mermaid;
} }
if (!code) { 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()) { for (const [key, value] of searchParams.entries()) {
if (key in loaders) { if (key in loaders) {
try { try {
@@ -38,6 +36,9 @@ export const loadDataFromUrl = async (): Promise<void> => {
} }
} }
} else { } else {
if (!codeURL) {
throw new Error('Code URL is not defined');
}
state = { state = {
code, code,
mermaid: config, mermaid: config,
+1 -1
View File
@@ -23,5 +23,5 @@ export const render = async (
export const parse = async (code: string): Promise<boolean> => { export const parse = async (code: string): Promise<boolean> => {
await init(); await init();
return (await mermaid.parseAsync(code)) as boolean; return await mermaid.parseAsync(code);
}; };
+10 -6
View File
@@ -16,18 +16,22 @@ describe('migrations', () => {
it('should migrate from v0 to v1', async () => { it('should migrate from v0 to v1', async () => {
const { applyMigrations } = await import('./migrations'); const { applyMigrations } = await import('./migrations');
let manualHistoryStore: HistoryEntry[] = JSON.parse( let manualHistoryStore: HistoryEntry[] = JSON.parse(
window.localStorage.getItem('manualHistoryStore') window.localStorage.getItem('manualHistoryStore') ?? '[]'
); ) as HistoryEntry[];
let autoHistoryStore: HistoryEntry[] = JSON.parse( let autoHistoryStore: HistoryEntry[] = JSON.parse(
window.localStorage.getItem('autoHistoryStore') window.localStorage.getItem('autoHistoryStore') ?? '[]'
); ) as HistoryEntry[];
expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(false); expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(false);
expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(false); expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(false);
applyMigrations(); applyMigrations();
manualHistoryStore = JSON.parse(window.localStorage.getItem('manualHistoryStore')); manualHistoryStore = JSON.parse(
autoHistoryStore = JSON.parse(window.localStorage.getItem('autoHistoryStore')); window.localStorage.getItem('manualHistoryStore') ?? '[]'
) as HistoryEntry[];
autoHistoryStore = JSON.parse(
window.localStorage.getItem('autoHistoryStore') ?? '[]'
) as HistoryEntry[];
expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(true); expect(manualHistoryStore.every(({ id }) => id !== undefined)).toBe(true);
expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(true); expect(autoHistoryStore.every(({ id }) => id !== undefined)).toBe(true);
}); });
+2 -2
View File
@@ -1,13 +1,13 @@
import { writable, get, type Writable } from 'svelte/store'; import { writable, get, type Writable } from 'svelte/store';
import { persist, localStorage } from '$lib/util/persist'; import { persist, localStorage } from '$lib/util/persist';
import { injectHistoryIDs } from '$lib/components/history/history'; import { injectHistoryIDs } from '$lib/components/History/history';
import { logEvent } from './stats'; import { logEvent } from './stats';
interface MigrationState { interface MigrationState {
version: number; version: number;
} }
const migrations: { [key: string]: () => void } = { const migrations: Record<string, () => void> = {
injectHistoryIDs injectHistoryIDs
}; };
+16 -22
View File
@@ -39,16 +39,16 @@ let noWarnings = false;
/** /**
* List of storages where the warning have already been displayed. * List of storages where the warning have already been displayed.
*/ */
const alreadyWarnFor: Array<string> = []; const alreadyWarnFor: string[] = [];
/** /**
* Add a log to indicate that the requested Storage have not been found. * Add a log to indicate that the requested Storage have not been found.
* @param {string} storageName * @param {string} storageName
*/ */
const warnStorageNotFound = (storageName) => { const warnStorageNotFound = (storageName: string) => {
const isProduction = typeof process !== 'undefined' && process.env?.NODE_ENV === 'production'; const isProduction = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
if (!noWarnings && alreadyWarnFor.indexOf(storageName) === -1 && !isProduction) { if (!noWarnings && !alreadyWarnFor.includes(storageName) && !isProduction) {
let message = `Unable to find the ${storageName}. No data will be persisted.`; let message = `Unable to find the ${storageName}. No data will be persisted.`;
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
message += message +=
@@ -60,17 +60,8 @@ const warnStorageNotFound = (storageName) => {
} }
}; };
const allowedClasses = [];
/**
* Add a class to the allowed list of classes to be serialized
* @param classDef The class to add to the list
*/
export const addSerializableClass = (classDef: () => unknown): void => {
allowedClasses.push(classDef);
};
const serialize = (value: unknown): string => ESSerializer.serialize(value); const serialize = (value: unknown): string => ESSerializer.serialize(value);
const deserialize = (value: string): unknown => { const deserialize = (value?: string | null): unknown => {
// @TODO: to remove in the next major // @TODO: to remove in the next major
if (value === 'undefined') { if (value === 'undefined') {
return undefined; return undefined;
@@ -78,7 +69,7 @@ const deserialize = (value: string): unknown => {
if (value !== null && value !== undefined) { if (value !== null && value !== undefined) {
try { try {
return ESSerializer.deserialize(value, allowedClasses); return ESSerializer.deserialize(value);
} catch (e) { } catch (e) {
// Do nothing // Do nothing
// use the value "as is" // use the value "as is"
@@ -162,7 +153,7 @@ export function persist<T>(
store.set(initialValue); store.set(initialValue);
} }
if ((storage as SelfUpdateStorageInterface<T>).addListener) { if ('addListener' in storage) {
(storage as SelfUpdateStorageInterface<T>).addListener(key, (newValue) => { (storage as SelfUpdateStorageInterface<T>).addListener(key, (newValue) => {
store.set(newValue); store.set(newValue);
}); });
@@ -184,7 +175,7 @@ function getBrowserStorage(
browserStorage: Storage, browserStorage: Storage,
listenExternalChanges = false listenExternalChanges = false
): SelfUpdateStorageInterface<any> { ): SelfUpdateStorageInterface<any> {
const listeners: Array<{ key: string; listener: (newValue: any) => void }> = []; const listeners: { key: string; listener: (newValue: any) => void }[] = [];
const listenerFunction = (event: StorageEvent) => { const listenerFunction = (event: StorageEvent) => {
const eventKey = event.key; const eventKey = event.key;
if (event.storageArea === browserStorage) { if (event.storageArea === browserStorage) {
@@ -196,12 +187,14 @@ function getBrowserStorage(
} }
}; };
const connect = () => { const connect = () => {
if (listenExternalChanges && typeof window !== 'undefined' && window?.addEventListener) { // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (listenExternalChanges && typeof window !== 'undefined' && window.addEventListener) {
window.addEventListener('storage', listenerFunction); window.addEventListener('storage', listenerFunction);
} }
}; };
const disconnect = () => { const disconnect = () => {
if (listenExternalChanges && typeof window !== 'undefined' && window?.removeEventListener) { // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (listenExternalChanges && typeof window !== 'undefined' && window.removeEventListener) {
window.removeEventListener('storage', listenerFunction); window.removeEventListener('storage', listenerFunction);
} }
}; };
@@ -237,10 +230,11 @@ function getBrowserStorage(
/** /**
* Storage implementation that use the browser local storage * Storage implementation that use the browser local storage
* @param {boolean} listenExternalChanges - Update the store if the localStorage is updated from another page * @param listenExternalChanges - Update the store if the localStorage is updated from another page
*/ */
export function localStorage<T>(listenExternalChanges = false): StorageInterface<T> { export function localStorage<T>(listenExternalChanges = false): StorageInterface<T> {
if (typeof window !== 'undefined' && window?.localStorage) { // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (typeof window !== 'undefined' && window.localStorage) {
return getBrowserStorage(window.localStorage, listenExternalChanges); return getBrowserStorage(window.localStorage, listenExternalChanges);
} }
warnStorageNotFound('window.localStorage'); warnStorageNotFound('window.localStorage');
@@ -250,7 +244,7 @@ export function localStorage<T>(listenExternalChanges = false): StorageInterface
/** /**
* Storage implementation that do nothing * Storage implementation that do nothing
*/ */
export function noopStorage(): StorageInterface<any> { export function noopStorage<T>(): StorageInterface<T> {
return { return {
getValue(): null { getValue(): null {
return null; return null;
+1 -1
View File
@@ -36,7 +36,7 @@ const serdes: { [key in SerdeType]: Serde } = {
}; };
export const serializeState = (state: State, serde: SerdeType = 'pako'): string => { export const serializeState = (state: State, serde: SerdeType = 'pako'): string => {
if (serdes[serde] === undefined) { if (!(serde in serdes)) {
throw new Error(`Unknown serde type: ${serde}`); throw new Error(`Unknown serde type: ${serde}`);
} }
const json = JSON.stringify(state); const json = JSON.stringify(state);
+22 -22
View File
@@ -2,10 +2,12 @@ import { writable, get, type Readable, derived } from 'svelte/store';
import { persist, localStorage } from './persist'; import { persist, localStorage } from './persist';
import { saveStatistics, countLines } from './stats'; import { saveStatistics, countLines } from './stats';
import { serializeState, deserializeState } from './serde'; import { serializeState, deserializeState } from './serde';
import { cmdKey, errorDebug, AsyncQueue } from './util'; import { cmdKey, errorDebug } from './util';
import { parse } from './mermaid'; import { parse } from './mermaid';
import type { MarkerData, State, ValidatedState } from '$lib/types'; import type { ErrorHash, MarkerData, State, ValidatedState } from '$lib/types';
import type { MermaidConfig } from 'mermaid';
export const defaultState: State = { export const defaultState: State = {
code: `graph TD code: `graph TD
A[Christmas] -->|Get money| B(Go shopping) A[Christmas] -->|Get money| B(Go shopping)
@@ -50,8 +52,6 @@ export const currentState: ValidatedState = (() => {
}; };
})(); })();
let q: AsyncQueue<State>;
const processState = async (state: State) => { const processState = async (state: State) => {
const processed: ValidatedState = { const processed: ValidatedState = {
...state, ...state,
@@ -66,17 +66,22 @@ const processState = async (state: State) => {
await parse(state.code); await parse(state.code);
JSON.parse(state.mermaid); JSON.parse(state.mermaid);
} catch (e) { } catch (e) {
processed.error = e; processed.error = e as Error;
errorDebug(); errorDebug();
console.error(e); console.error(e);
if (e.hash) { if ('hash' in e) {
try { 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;
const marker: MarkerData = { const marker: MarkerData = {
severity: 8, // Error severity: 8, // Error
startLineNumber: e.hash.loc.first_line, startLineNumber: first_line,
startColumn: e.hash.loc.first_column, startColumn: first_column,
endLineNumber: e.hash.loc.last_line, endLineNumber: last_line,
endColumn: (e.hash.loc.last_column as number) + 1, endColumn: last_column + 1,
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment
message: e.str message: e.str
}; };
processed.errorMarkers = [marker]; processed.errorMarkers = [marker];
@@ -92,14 +97,7 @@ const processState = async (state: State) => {
export const stateStore: Readable<ValidatedState> = derived( export const stateStore: Readable<ValidatedState> = derived(
[inputStateStore], [inputStateStore],
([state], set) => { ([state], set) => {
if (!q) { void processState(state).then(set);
// Initialize the queue for first time.
q = new AsyncQueue(async (state: State) => {
const newState = await processState(state);
set(newState);
});
}
q.process(state);
}, },
currentState currentState
); );
@@ -109,8 +107,10 @@ export const loadState = (data: string): void => {
console.log(`Loading '${data}'`); console.log(`Loading '${data}'`);
try { try {
state = deserializeState(data); state = deserializeState(data);
const mermaidConfig: { [key: string]: string } = const mermaidConfig: MermaidConfig =
typeof state.mermaid === 'string' ? JSON.parse(state.mermaid) : state.mermaid; typeof state.mermaid === 'string'
? (JSON.parse(state.mermaid) as MermaidConfig)
: state.mermaid;
if ( if (
mermaidConfig.securityLevel && mermaidConfig.securityLevel &&
mermaidConfig.securityLevel !== 'strict' && mermaidConfig.securityLevel !== 'strict' &&
@@ -180,7 +180,7 @@ export const updateConfig = (config: string): void => {
export const toggleDarkTheme = (dark: boolean): void => { export const toggleDarkTheme = (dark: boolean): void => {
inputStateStore.update((state) => { inputStateStore.update((state) => {
const config = JSON.parse(state.mermaid); const config = JSON.parse(state.mermaid) as MermaidConfig;
if (!config.theme || ['dark', 'default'].includes(config.theme)) { if (!config.theme || ['dark', 'default'].includes(config.theme)) {
config.theme = dark ? 'dark' : 'default'; config.theme = dark ? 'dark' : 'default';
} }
@@ -194,7 +194,7 @@ export const initURLSubscription = (): void => {
stateStore.subscribe(({ serialized }) => { stateStore.subscribe(({ serialized }) => {
clearTimeout(urlDebounce); clearTimeout(urlDebounce);
urlDebounce = window.setTimeout(() => { urlDebounce = window.setTimeout(() => {
history.replaceState(undefined, undefined, `#${serialized}`); history.replaceState(undefined, '', `#${serialized}`);
}, 250); }, 250);
}); });
}; };
+10 -9
View File
@@ -1,6 +1,6 @@
import { browser } from '$app/environment'; import { browser } from '$app/environment';
import type { AnalyticsInstance } from 'analytics'; import type { AnalyticsInstance } from 'analytics';
export let analytics: AnalyticsInstance; export let analytics: AnalyticsInstance | undefined;
export const initAnalytics = async (): Promise<void> => { export const initAnalytics = async (): Promise<void> => {
if (browser && !analytics) { if (browser && !analytics) {
@@ -27,7 +27,7 @@ export const initAnalytics = async (): Promise<void> => {
} }
}; };
export const detectType = (text: string): string => { export const detectType = (text: string): string | undefined => {
const possibleDiagramTypes = [ const possibleDiagramTypes = [
'classDiagram', 'classDiagram',
'erDiagram', 'erDiagram',
@@ -49,7 +49,7 @@ export const detectType = (text: string): string => {
}; };
export const countLines = (code: string): number => { export const countLines = (code: string): number => {
return (code.match(/\n/g) || '').length + 1; return (code.match(/\n/g)?.length ?? 0) + 1;
}; };
export const saveStatistics = (graph: string): void => { export const saveStatistics = (graph: string): void => {
@@ -80,19 +80,20 @@ const delaysPerEvent = {
themeChange: defaultDelay themeChange: defaultDelay
}; };
export type AnalyticsEvent = keyof typeof delaysPerEvent; export type AnalyticsEvent = keyof typeof delaysPerEvent;
const timeouts: Record<string, number> = {}; const timeouts: Map<string, number> = new Map<string, number>();
// manual debounce to reduce the number of events sent to analytics // manual debounce to reduce the number of events sent to analytics
export const logEvent = (name: AnalyticsEvent, data?: unknown): void => { export const logEvent = (name: AnalyticsEvent, data?: unknown): void => {
if (!analytics) { if (!analytics) {
return; return;
} }
const key = data ? JSON.stringify({ name, data }) : name; const key = data ? JSON.stringify({ name, data }) : name;
if (timeouts[key] === undefined) { if (!timeouts.has(key)) {
void analytics.track(name, data); void analytics.track(name, data);
} else { } else {
clearTimeout(timeouts[key]); clearTimeout(timeouts.get(key));
} }
timeouts[key] = window.setTimeout(() => { timeouts.set(
delete timeouts[key]; key,
}, delaysPerEvent[name]); window.setTimeout(() => timeouts.delete(key), delaysPerEvent[name])
);
}; };
+2 -23
View File
@@ -23,10 +23,10 @@ export const initHandler = async (): Promise<void> => {
syncDiagram(); syncDiagram();
initURLSubscription(); initURLSubscription();
await initAnalytics(); await initAnalytics();
analytics?.page(); await analytics?.page();
}; };
export const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0; export const isMac = navigator.platform.toUpperCase().includes('MAC');
export const cmdKey = isMac ? 'Cmd' : 'Ctrl'; export const cmdKey = isMac ? 'Cmd' : 'Ctrl';
let count = 0; let count = 0;
@@ -38,24 +38,3 @@ export const errorDebug = (limit = 100) => {
debugger; debugger;
} }
}; };
// To queue async tasks so they are executed one after the other, not concurrently.
export class AsyncQueue<T> {
private readonly queue: T[] = [];
private running = false;
constructor(private processor: (item: T) => Promise<void>) {}
public async process(item: T): Promise<void> {
this.queue.push(item);
if (this.running) {
return;
}
this.running = true;
while (this.queue.length > 0) {
const item = this.queue.shift();
if (item) {
await this.processor(item);
}
}
this.running = false;
}
}
+1
View File
@@ -1,3 +1,4 @@
export const prerender = true; export const prerender = true;
export const csr = true; export const csr = true;
export const ssr = false; export const ssr = false;
export const trailingSlash = 'ignore';
+2 -2
View File
@@ -10,8 +10,8 @@
// This can be removed once https://github.com/sveltejs/kit/issues/1612 is fixed. // This can be removed once https://github.com/sveltejs/kit/issues/1612 is fixed.
// Then move it into src and vite will bundle it automatically. // Then move it into src and vite will bundle it automatically.
onMount(() => { onMount(() => {
window.addEventListener('hashchange', async (ev) => { window.addEventListener('hashchange', () => {
await initHandler(); void initHandler();
}); });
if ('serviceWorker' in navigator) { if ('serviceWorker' in navigator) {
navigator.serviceWorker navigator.serviceWorker
+11 -7
View File
@@ -1,11 +1,11 @@
<script lang="ts"> <script lang="ts">
import Editor from '$lib/components/editor.svelte'; import Editor from '$lib/components/Editor.svelte';
import Navbar from '$lib/components/navbar.svelte'; import Navbar from '$lib/components/Navbar.svelte';
import Preset from '$lib/components/preset.svelte'; import Preset from '$lib/components/Preset.svelte';
import Actions from '$lib/components/actions.svelte'; import Actions from '$lib/components/Actions.svelte';
import View from '$lib/components/view.svelte'; import View from '$lib/components/View.svelte';
import Card from '$lib/components/card/card.svelte'; import Card from '$lib/components/Card/Card.svelte';
import History from '$lib/components/history/history.svelte'; import History from '$lib/components/History/History.svelte';
import { inputStateStore, stateStore, updateCodeStore } from '$lib/util/state'; import { inputStateStore, stateStore, updateCodeStore } from '$lib/util/state';
import { cmdKey, initHandler, syncDiagram } from '$lib/util/util'; import { cmdKey, initHandler, syncDiagram } from '$lib/util/util';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
@@ -86,6 +86,10 @@
await initHandler(); await initHandler();
const resizer = document.getElementById('resizeHandler'); const resizer = document.getElementById('resizeHandler');
const element = document.getElementById('editorPane'); const element = document.getElementById('editorPane');
if (!resizer || !element) {
console.debug('Failed to find resize handler or editor pane', { resizer, element });
return;
}
const resize = (e: { pageX: number }) => { const resize = (e: { pageX: number }) => {
const newWidth = e.pageX - element.getBoundingClientRect().left; const newWidth = e.pageX - element.getBoundingClientRect().left;
if (newWidth > 50) { if (newWidth > 50) {
+1 -1
View File
@@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import View from '$lib/components/view.svelte'; import View from '$lib/components/View.svelte';
import { initHandler } from '$lib/util/util'; import { initHandler } from '$lib/util/util';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
onMount(initHandler); onMount(initHandler);
+1 -2
View File
@@ -18,8 +18,7 @@ const config = {
? { ? {
base: `/mermaid-live-editor` base: `/mermaid-live-editor`
} }
: {}, : {}
trailingSlash: 'ignore'
} }
}; };
+398
View File
@@ -0,0 +1,398 @@
import { test, expect, type Page } from '@playwright/test';
test.beforeEach(async ({ page }) => {
await page.goto('https://demo.playwright.dev/todomvc');
});
const TODO_ITEMS = [
'buy some cheese',
'feed the cat',
'book a doctors appointment'
];
test.describe('New Todo', () => {
test('should allow me to add todo items', async ({ page }) => {
// Create 1st todo.
await page.locator('.new-todo').fill(TODO_ITEMS[0]);
await page.locator('.new-todo').press('Enter');
// Make sure the list only has one todo item.
await expect(page.locator('.view label')).toHaveText([
TODO_ITEMS[0]
]);
// Create 2nd todo.
await page.locator('.new-todo').fill(TODO_ITEMS[1]);
await page.locator('.new-todo').press('Enter');
// Make sure the list now has two todo items.
await expect(page.locator('.view label')).toHaveText([
TODO_ITEMS[0],
TODO_ITEMS[1]
]);
await checkNumberOfTodosInLocalStorage(page, 2);
});
test('should clear text input field when an item is added', async ({ page }) => {
// Create one todo item.
await page.locator('.new-todo').fill(TODO_ITEMS[0]);
await page.locator('.new-todo').press('Enter');
// Check that input is empty.
await expect(page.locator('.new-todo')).toBeEmpty();
await checkNumberOfTodosInLocalStorage(page, 1);
});
test('should append new items to the bottom of the list', async ({ page }) => {
// Create 3 items.
await createDefaultTodos(page);
// Check test using different methods.
await expect(page.locator('.todo-count')).toHaveText('3 items left');
await expect(page.locator('.todo-count')).toContainText('3');
await expect(page.locator('.todo-count')).toHaveText(/3/);
// Check all items in one call.
await expect(page.locator('.view label')).toHaveText(TODO_ITEMS);
await checkNumberOfTodosInLocalStorage(page, 3);
});
test('should show #main and #footer when items added', async ({ page }) => {
await page.locator('.new-todo').fill(TODO_ITEMS[0]);
await page.locator('.new-todo').press('Enter');
await expect(page.locator('.main')).toBeVisible();
await expect(page.locator('.footer')).toBeVisible();
await checkNumberOfTodosInLocalStorage(page, 1);
});
});
test.describe('Mark all as completed', () => {
test.beforeEach(async ({ page }) => {
await createDefaultTodos(page);
await checkNumberOfTodosInLocalStorage(page, 3);
});
test.afterEach(async ({ page }) => {
await checkNumberOfTodosInLocalStorage(page, 3);
});
test('should allow me to mark all items as completed', async ({ page }) => {
// Complete all todos.
await page.locator('.toggle-all').check();
// Ensure all todos have 'completed' class.
await expect(page.locator('.todo-list li')).toHaveClass(['completed', 'completed', 'completed']);
await checkNumberOfCompletedTodosInLocalStorage(page, 3);
});
test('should allow me to clear the complete state of all items', async ({ page }) => {
// Check and then immediately uncheck.
await page.locator('.toggle-all').check();
await page.locator('.toggle-all').uncheck();
// Should be no completed classes.
await expect(page.locator('.todo-list li')).toHaveClass(['', '', '']);
});
test('complete all checkbox should update state when items are completed / cleared', async ({ page }) => {
const toggleAll = page.locator('.toggle-all');
await toggleAll.check();
await expect(toggleAll).toBeChecked();
await checkNumberOfCompletedTodosInLocalStorage(page, 3);
// Uncheck first todo.
const firstTodo = page.locator('.todo-list li').nth(0);
await firstTodo.locator('.toggle').uncheck();
// Reuse toggleAll locator and make sure its not checked.
await expect(toggleAll).not.toBeChecked();
await firstTodo.locator('.toggle').check();
await checkNumberOfCompletedTodosInLocalStorage(page, 3);
// Assert the toggle all is checked again.
await expect(toggleAll).toBeChecked();
});
});
test.describe('Item', () => {
test('should allow me to mark items as complete', async ({ page }) => {
// Create two items.
for (const item of TODO_ITEMS.slice(0, 2)) {
await page.locator('.new-todo').fill(item);
await page.locator('.new-todo').press('Enter');
}
// Check first item.
const firstTodo = page.locator('.todo-list li').nth(0);
await firstTodo.locator('.toggle').check();
await expect(firstTodo).toHaveClass('completed');
// Check second item.
const secondTodo = page.locator('.todo-list li').nth(1);
await expect(secondTodo).not.toHaveClass('completed');
await secondTodo.locator('.toggle').check();
// Assert completed class.
await expect(firstTodo).toHaveClass('completed');
await expect(secondTodo).toHaveClass('completed');
});
test('should allow me to un-mark items as complete', async ({ page }) => {
// Create two items.
for (const item of TODO_ITEMS.slice(0, 2)) {
await page.locator('.new-todo').fill(item);
await page.locator('.new-todo').press('Enter');
}
const firstTodo = page.locator('.todo-list li').nth(0);
const secondTodo = page.locator('.todo-list li').nth(1);
await firstTodo.locator('.toggle').check();
await expect(firstTodo).toHaveClass('completed');
await expect(secondTodo).not.toHaveClass('completed');
await checkNumberOfCompletedTodosInLocalStorage(page, 1);
await firstTodo.locator('.toggle').uncheck();
await expect(firstTodo).not.toHaveClass('completed');
await expect(secondTodo).not.toHaveClass('completed');
await checkNumberOfCompletedTodosInLocalStorage(page, 0);
});
test('should allow me to edit an item', async ({ page }) => {
await createDefaultTodos(page);
const todoItems = page.locator('.todo-list li');
const secondTodo = todoItems.nth(1);
await secondTodo.dblclick();
await expect(secondTodo.locator('.edit')).toHaveValue(TODO_ITEMS[1]);
await secondTodo.locator('.edit').fill('buy some sausages');
await secondTodo.locator('.edit').press('Enter');
// Explicitly assert the new text value.
await expect(todoItems).toHaveText([
TODO_ITEMS[0],
'buy some sausages',
TODO_ITEMS[2]
]);
await checkTodosInLocalStorage(page, 'buy some sausages');
});
});
test.describe('Editing', () => {
test.beforeEach(async ({ page }) => {
await createDefaultTodos(page);
await checkNumberOfTodosInLocalStorage(page, 3);
});
test('should hide other controls when editing', async ({ page }) => {
const todoItem = page.locator('.todo-list li').nth(1);
await todoItem.dblclick();
await expect(todoItem.locator('.toggle')).not.toBeVisible();
await expect(todoItem.locator('label')).not.toBeVisible();
await checkNumberOfTodosInLocalStorage(page, 3);
});
test('should save edits on blur', async ({ page }) => {
const todoItems = page.locator('.todo-list li');
await todoItems.nth(1).dblclick();
await todoItems.nth(1).locator('.edit').fill('buy some sausages');
await todoItems.nth(1).locator('.edit').dispatchEvent('blur');
await expect(todoItems).toHaveText([
TODO_ITEMS[0],
'buy some sausages',
TODO_ITEMS[2],
]);
await checkTodosInLocalStorage(page, 'buy some sausages');
});
test('should trim entered text', async ({ page }) => {
const todoItems = page.locator('.todo-list li');
await todoItems.nth(1).dblclick();
await todoItems.nth(1).locator('.edit').fill(' buy some sausages ');
await todoItems.nth(1).locator('.edit').press('Enter');
await expect(todoItems).toHaveText([
TODO_ITEMS[0],
'buy some sausages',
TODO_ITEMS[2],
]);
await checkTodosInLocalStorage(page, 'buy some sausages');
});
test('should remove the item if an empty text string was entered', async ({ page }) => {
const todoItems = page.locator('.todo-list li');
await todoItems.nth(1).dblclick();
await todoItems.nth(1).locator('.edit').fill('');
await todoItems.nth(1).locator('.edit').press('Enter');
await expect(todoItems).toHaveText([
TODO_ITEMS[0],
TODO_ITEMS[2],
]);
});
test('should cancel edits on escape', async ({ page }) => {
const todoItems = page.locator('.todo-list li');
await todoItems.nth(1).dblclick();
await todoItems.nth(1).locator('.edit').press('Escape');
await expect(todoItems).toHaveText(TODO_ITEMS);
});
});
test.describe('Counter', () => {
test('should display the current number of todo items', async ({ page }) => {
await page.locator('.new-todo').fill(TODO_ITEMS[0]);
await page.locator('.new-todo').press('Enter');
await expect(page.locator('.todo-count')).toContainText('1');
await page.locator('.new-todo').fill(TODO_ITEMS[1]);
await page.locator('.new-todo').press('Enter');
await expect(page.locator('.todo-count')).toContainText('2');
await checkNumberOfTodosInLocalStorage(page, 2);
});
});
test.describe('Clear completed button', () => {
test.beforeEach(async ({ page }) => {
await createDefaultTodos(page);
});
test('should display the correct text', async ({ page }) => {
await page.locator('.todo-list li .toggle').first().check();
await expect(page.locator('.clear-completed')).toHaveText('Clear completed');
});
test('should remove completed items when clicked', async ({ page }) => {
const todoItems = page.locator('.todo-list li');
await todoItems.nth(1).locator('.toggle').check();
await page.locator('.clear-completed').click();
await expect(todoItems).toHaveCount(2);
await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[2]]);
});
test('should be hidden when there are no items that are completed', async ({ page }) => {
await page.locator('.todo-list li .toggle').first().check();
await page.locator('.clear-completed').click();
await expect(page.locator('.clear-completed')).toBeHidden();
});
});
test.describe('Persistence', () => {
test('should persist its data', async ({ page }) => {
for (const item of TODO_ITEMS.slice(0, 2)) {
await page.locator('.new-todo').fill(item);
await page.locator('.new-todo').press('Enter');
}
const todoItems = page.locator('.todo-list li');
await todoItems.nth(0).locator('.toggle').check();
await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[1]]);
await expect(todoItems).toHaveClass(['completed', '']);
// Ensure there is 1 completed item.
checkNumberOfCompletedTodosInLocalStorage(page, 1);
// Now reload.
await page.reload();
await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[1]]);
await expect(todoItems).toHaveClass(['completed', '']);
});
});
test.describe('Routing', () => {
test.beforeEach(async ({ page }) => {
await createDefaultTodos(page);
// make sure the app had a chance to save updated todos in storage
// before navigating to a new view, otherwise the items can get lost :(
// in some frameworks like Durandal
await checkTodosInLocalStorage(page, TODO_ITEMS[0]);
});
test('should allow me to display active items', async ({ page }) => {
await page.locator('.todo-list li .toggle').nth(1).check();
await checkNumberOfCompletedTodosInLocalStorage(page, 1);
await page.locator('.filters >> text=Active').click();
await expect(page.locator('.todo-list li')).toHaveCount(2);
await expect(page.locator('.todo-list li')).toHaveText([TODO_ITEMS[0], TODO_ITEMS[2]]);
});
test('should respect the back button', async ({ page }) => {
await page.locator('.todo-list li .toggle').nth(1).check();
await checkNumberOfCompletedTodosInLocalStorage(page, 1);
await test.step('Showing all items', async () => {
await page.locator('.filters >> text=All').click();
await expect(page.locator('.todo-list li')).toHaveCount(3);
});
await test.step('Showing active items', async () => {
await page.locator('.filters >> text=Active').click();
});
await test.step('Showing completed items', async () => {
await page.locator('.filters >> text=Completed').click();
});
await expect(page.locator('.todo-list li')).toHaveCount(1);
await page.goBack();
await expect(page.locator('.todo-list li')).toHaveCount(2);
await page.goBack();
await expect(page.locator('.todo-list li')).toHaveCount(3);
});
test('should allow me to display completed items', async ({ page }) => {
await page.locator('.todo-list li .toggle').nth(1).check();
await checkNumberOfCompletedTodosInLocalStorage(page, 1);
await page.locator('.filters >> text=Completed').click();
await expect(page.locator('.todo-list li')).toHaveCount(1);
});
test('should allow me to display all items', async ({ page }) => {
await page.locator('.todo-list li .toggle').nth(1).check();
await checkNumberOfCompletedTodosInLocalStorage(page, 1);
await page.locator('.filters >> text=Active').click();
await page.locator('.filters >> text=Completed').click();
await page.locator('.filters >> text=All').click();
await expect(page.locator('.todo-list li')).toHaveCount(3);
});
test('should highlight the currently applied filter', async ({ page }) => {
await expect(page.locator('.filters >> text=All')).toHaveClass('selected');
await page.locator('.filters >> text=Active').click();
// Page change - active items.
await expect(page.locator('.filters >> text=Active')).toHaveClass('selected');
await page.locator('.filters >> text=Completed').click();
// Page change - completed items.
await expect(page.locator('.filters >> text=Completed')).toHaveClass('selected');
});
});
async function createDefaultTodos(page: Page) {
for (const item of TODO_ITEMS) {
await page.locator('.new-todo').fill(item);
await page.locator('.new-todo').press('Enter');
}
}
async function checkNumberOfTodosInLocalStorage(page: Page, expected: number) {
return await page.waitForFunction(e => {
return JSON.parse(localStorage['react-todos']).length === e;
}, expected);
}
async function checkNumberOfCompletedTodosInLocalStorage(page: Page, expected: number) {
return await page.waitForFunction(e => {
return JSON.parse(localStorage['react-todos']).filter((todo: any) => todo.completed).length === e;
}, expected);
}
async function checkTodosInLocalStorage(page: Page, title: string) {
return await page.waitForFunction(t => {
return JSON.parse(localStorage['react-todos']).map((todo: any) => todo.title).includes(t);
}, title);
}
+179
View File
@@ -0,0 +1,179 @@
import { toBase64 } from 'js-base64';
// describe('Site Loads', () => {
// beforeEach(() => {
// cy.clearLocalStorage();
// cy.visit('/');
// });
// it('Check Home page load', () => {
// cy.url().should('include', '/edit');
// cy.contains('History').click();
// cy.getLocalStorage('codeStore').snapshot();
// });
// it('Check Redirect from old URL', () => {
// cy.visit(
// '/#/edit/eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW0NocmlzdG1hc10gLS0-fEdldCBtb25leXwgQihHbyBzaG9wcGluZylcbiAgICBCIC0tPiBDe0xldCBtZSB0aGlua31cbiAgICBDIC0tPnxPbmV8IERbTGFwdG9wXVxuICAgIEMgLS0-fFR3b3wgRVtpUGhvbmVdXG4gICAgQyAtLT58VGhyZWV8IEZbZmE6ZmEtY2FyIENhcl0iLCJtZXJtYWlkIjp7InRoZW1lIjoiZGVmYXVsdCJ9LCJ1cGRhdGVFZGl0b3IiOmZhbHNlfQ'
// );
// cy.url().should('include', '/edit#pako:eNp');
// });
// it('should load sample diagrams when clicked', () => {
// cy.contains('Sample Diagrams').click();
// cy.contains('Pie').click();
// cy.contains('pie title Pets adopted by volunteers');
// cy.contains('Class').click();
// cy.contains('classDiagram');
// });
// (Cypress.env('CI') === 'true' ? describe : describe.skip)('github', () => {
// it('should load diagram from gist', () => {
// cy.visit(`/edit?gist=https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a`);
// cy.contains('History').click();
// cy.contains('Go shopping!!');
// cy.contains('Revisions');
// cy.contains('sidharthv96 v8f8f1e2');
// cy.contains('sidharthv96 v7851e19');
// cy.getLocalStorage('codeStore').snapshot();
// });
// it('should load diagram from gist revision', () => {
// cy.visit(
// '/edit?gist=https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/ec9b4ab0e41e4ff6287326cd3cb47affd7851e19'
// );
// cy.contains('History').click();
// cy.contains('Party');
// cy.contains('Revisions');
// cy.contains('sidharthv96 v7851e19');
// cy.getLocalStorage('codeStore').snapshot();
// });
// it('should load diagram from raw files', () => {
// cy.visit(
// '/edit?code=https://gist.githubusercontent.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/raw/4eb03887e6a41397e80bdcdbf94017c498f8f1e2/code.mmd&config=https://gist.githubusercontent.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/raw/4eb03887e6a41397e80bdcdbf94017c498f8f1e2/config.json'
// );
// cy.contains('Party');
// cy.getLocalStorage('codeStore').snapshot();
// });
// });
// // 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\\"}","autoSync":true,"updateDiagram":true}`,
// // true
// // );
// // cy.on('window:confirm', () => true);
// // cy.visit(`/edit#${b64State}`);
// // cy.contains('Config').click();
// // cy.contains('forest');
// // cy.contains('securityLevel').should('not.exist');
// // cy.get('#view').find('img').should('not.exist');
// // cy.get('#view').contains('<img');
// // cy.get('#view').contains(`src='https://via.placeholder.com/64'`);
// // });
// it.skip('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\\"}","autoSync":true,"updateDiagram":true}`,
// true
// );
// cy.on('window:confirm', () => false);
// cy.visit(`/edit#${b64State}`);
// cy.get('#editor').type(' ');
// cy.contains('Config').click();
// cy.contains('forest');
// cy.contains('securityLevel');
// cy.get('#view').find('img').should('be.visible');
// });
// it('should show troubleshooting steps if loading fails', () => {
// cy.visit('/#/edit/eyJjb2RlIjoiZ3JhcGggVERcbiAg');
// cy.reload(true);
// cy.contains('Please Click here to Raise an issue in github.');
// });
// it('should load uncompressed URL', () => {
// cy.visit(
// '/edit/#eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW05ldyBZZWFyXSAtLT58R2V0IG1vbmV5fCBCKEdvIHNob3BwaW5nKVxuICAgIEIgLS0-IEN7TGV0IG1lIHRoaW5rfVxuICAgIEMgLS0-fE9uZXwgRFtMYXB0b3BdXG4gICAgQyAtLT58VHdvfCBFW2lQaG9uZV1cbiAgICBDIC0tPnxUaHJlZXwgRltmYTpmYS1jYXIgQ2FyXSIsIm1lcm1haWQiOiJ7XG4gIFwidGhlbWVcIjogXCJkZWZhdWx0XCJcbn0iLCJ1cGRhdGVFZGl0b3IiOmZhbHNlLCJhdXRvU3luYyI6dHJ1ZSwidXBkYXRlRGlhZ3JhbSI6ZmFsc2V9'
// );
// cy.contains('New Year');
// cy.visit(
// '/edit#eyJjb2RlIjoiY2xhc3NEaWFncmFtXG4gICAgQW5pbWFsIDx8LS0gRHVja1xuICAgIEFuaW1hbCA8fC0tIEZpc2hcbiAgICBBbmltYWwgPHwtLSBaZWJyYVxuICAgIEFuaW1hbCA6ICtpbnQgYWdlXG4gICAgQW5pbWFsIDogK1N0cmluZyBnZW5kZXJcbiAgICBBbmltYWw6ICtpc01hbW1hbCgpXG4gICAgQW5pbWFsOiArbWF0ZSgpXG4gICAgY2xhc3MgRHVja3tcbiAgICAgICtTdHJpbmcgYmVha0NvbG9yXG4gICAgICArc3dpbSgpXG4gICAgICArcXVhY2soKVxuICAgIH1cbiAgICBjbGFzcyBGaXNoe1xuICAgICAgLWludCBzaXplSW5GZWV0XG4gICAgICAtY2FuRWF0KClcbiAgICB9XG4gICAgY2xhc3MgWmVicmF7XG4gICAgICArYm9vbCBpc193aWxkXG4gICAgICArcnVuKClcbiAgICB9XG4gICAgICAgICAgICAiLCJtZXJtYWlkIjoie1xuICBcInRoZW1lXCI6IFwiZGFya1wiXG59IiwidXBkYXRlRWRpdG9yIjpmYWxzZSwiYXV0b1N5bmMiOnRydWUsInVwZGF0ZURpYWdyYW0iOmZhbHNlfQ'
// );
// cy.contains('Animal');
// cy.visit(
// '/edit/#base64:eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW05ldyBZZWFyXSAtLT58R2V0IG1vbmV5fCBCKEdvIHNob3BwaW5nKVxuICAgIEIgLS0-IEN7TGV0IG1lIHRoaW5rfVxuICAgIEMgLS0-fE9uZXwgRFtMYXB0b3BdXG4gICAgQyAtLT58VHdvfCBFW2lQaG9uZV1cbiAgICBDIC0tPnxUaHJlZXwgRltmYTpmYS1jYXIgQ2FyXSIsIm1lcm1haWQiOiJ7XG4gIFwidGhlbWVcIjogXCJkZWZhdWx0XCJcbn0iLCJ1cGRhdGVFZGl0b3IiOmZhbHNlLCJhdXRvU3luYyI6dHJ1ZSwidXBkYXRlRGlhZ3JhbSI6ZmFsc2V9'
// );
// cy.contains('New Year');
// });
// it('should load compressed URL', () => {
// cy.visit(
// '/edit#pako:eNpVkM2KwkAQhF-l6dMK5gVyEDRxvYi7sF6WjIcm0zqDzg_jBJEk725Hd2G3Tw31VVFUj23QjCWeEkUD-1p5kFs2O77BN1M6QFEshg1ncMHzfYDV2ybA1YQYrT_NXvhqgqDqtxPGkI315_ElVU__h-cB6mZLMYd4-Kvsb2GAdWM_jcT_V0xicb03RyqPVLSUoJI-OEfHyZHV0rqfDAqzYccKS3k1pbNC5Ufhuqgp81rbHBJKxuXKc6Quh6-7b7HMqeNfqLYkC7gfanwAlW1ZvQ'
// );
// cy.contains('New Year');
// cy.visit(
// '/edit#pako:eNptkU1PwzAMhv9K5BOI9Q9EXBDbJA477YYqITcxndV8QD40weh_Jy1rGR0-OY_tV2_sEyivCSQogzGuGduAtnaixINji0bcf1WVWGfVXdMtx8M1faYm4B8sxR27JLClJd6nwK4VLTlN4bI4jMQd2pLe3C4KFhNNcLQ92jv9ADGLNoTdozc-zIV4ZDsNlud7RtVN7_5Sb_jYrFcN3iN_0pPbEqUZK3QbTP_Ojyv4NdR4bwTHlyMbPcOQ3WJ2CliBpWCRdbnLqFJDOpClGmRJNYauhtr1pS-_6bKMjebkA8hXNJFWgDn5_YdTIFPINDWdb3vu6r8BaWOZRQ'
// );
// cy.contains('Animal');
// });
// });
import { test, expect } from '@playwright/test';
test.describe('site loads', () => {
test.beforeEach(async ({ page }) => {
await page.addInitScript(() => {
window.localStorage.clear();
});
await page.goto('/', { waitUntil: 'networkidle' });
});
test('should load home page', async ({ page }) => {
expect(page.url()).toContain('/edit');
await expect(page.locator('"History"')).toBeVisible();
// const { origins } = await context.storageState();
// console.log(JSON.stringify(origins));
// expect(JSON.stringify(origins)).toMatchSnapshot('initial-storage-state.json');
});
test('should redirect from old URL', async ({ page }) => {
// Note that Promise.all prevents a race condition
// between clicking and waiting for a navigation.
await Promise.all([
page.waitForNavigation({ url: '**/edit#pako:eNp**', timeout: 1000 }),
page.goto(
'/#/edit/eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW0NocmlzdG1hc10gLS0-fEdldCBtb25leXwgQihHbyBzaG9wcGluZylcbiAgICBCIC0tPiBDe0xldCBtZSB0aGlua31cbiAgICBDIC0tPnxPbmV8IERbTGFwdG9wXVxuICAgIEMgLS0-fFR3b3wgRVtpUGhvbmVdXG4gICAgQyAtLT58VGhyZWV8IEZbZmE6ZmEtY2FyIENhcl0iLCJtZXJtYWlkIjp7InRoZW1lIjoiZGVmYXVsdCJ9LCJ1cGRhdGVFZGl0b3IiOmZhbHNlfQ'
)
]);
expect(page.url()).toContain('/edit#pako:eNp');
});
test('should load sample diagrams when clicked', async ({ page }) => {
await page.click('"Sample Diagrams"');
await page.click('"Pie"');
await expect(page.locator('"pie title Pets adopted by volunteers"')).toBeVisible();
await page.click('"Class"');
await expect(page.locator('"classDiagram"')).toBeVisible();
});
});
// test('homepage has Playwright in title and get started link linking to the intro page', async ({
// page,
// context
// }) => {
// await page.goto(
// 'http://localhost:3000/edit?gist=https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a/ec9b4ab0e41e4ff6287326cd3cb47affd7851e19'
// );
// // cy.getLocalStorage('codeStore').snapshot();
// // Expect a title "to contain" a substring.
// await page.locator('"History"').click();
// await page.locator('"Party"').isVisible();
// await page.locator('"Revisions"').isVisible();
// await page.locator('"sidharthv96 v7851e19"').isVisible();
// await page.waitForTimeout(400);
// const storage = await context.storageState();
// expect(JSON.stringify(storage)).toMatchSnapshot();
// });
@@ -0,0 +1,17 @@
[
{
"origin": "http://localhost:3000",
"localStorage": [
{ "name": "__anon_id", "value": "\"87f53493-b439-425c-961c-9a2014f0ced8\"" },
{ "name": "manualHistoryStore", "value": "[]" },
{ "name": "autoHistoryMode", "value": "\"manual\"" },
{
"name": "codeStore",
"value": "{\"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}"
},
{ "name": "migrations", "value": "{\"version\":0}" },
{ "name": "themeStore", "value": "{\"theme\":\"light\",\"isDark\":false}" },
{ "name": "autoHistoryStore", "value": "[]" }
]
}
]
@@ -0,0 +1 @@
[{"origin":"http://localhost:3000","localStorage":[{"name":"__anon_id","value":"\"e4127e54-eced-443f-837e-0986e577b624\""},{"name":"manualHistoryStore","value":"[]"},{"name":"autoHistoryMode","value":"\"manual\""},{"name":"codeStore","value":"{\"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}"},{"name":"migrations","value":"{\"version\":0}"},{"name":"themeStore","value":"{\"theme\":\"light\",\"isDark\":false}"},{"name":"autoHistoryStore","value":"[]"}]}]
+6 -1
View File
@@ -6,12 +6,17 @@
"cypress/**/*.ts", "cypress/**/*.ts",
"cypress/**/*.js", "cypress/**/*.js",
"cypress/**/*.json", "cypress/**/*.json",
"tests/**/*.ts",
"tests/**/*.js",
"tests/**/*.json",
"static/**/*.js", "static/**/*.js",
"static/**/*.json" "static/**/*.json",
"./playwright.config.ts"
], ],
"compilerOptions": { "compilerOptions": {
"resolveJsonModule": true, "resolveJsonModule": true,
"allowSyntheticDefaultImports": true, "allowSyntheticDefaultImports": true,
"strictNullChecks": true,
"types": ["vitest/importMeta"] "types": ["vitest/importMeta"]
}, },
"extends": "./.svelte-kit/tsconfig.json" "extends": "./.svelte-kit/tsconfig.json"
+355 -354
View File
File diff suppressed because it is too large Load Diff