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 b03d862b53 Playwright init 2022-08-13 13:47:10 +05:30
44 changed files with 1731 additions and 1254 deletions
+2 -38
View File
@@ -6,18 +6,9 @@ module.exports = {
'plugin:@typescript-eslint/recommended',
// 'plugin:@typescript-eslint/recommended-requiring-type-checking',
'plugin:@typescript-eslint/strict',
'plugin:unicorn/recommended',
'prettier'
],
plugins: [
'svelte3',
'tailwindcss',
'@typescript-eslint',
'es',
'vitest',
'no-only-tests',
'unicorn'
],
plugins: ['svelte3', 'tailwindcss', '@typescript-eslint', 'es', 'vitest', 'no-only-tests'],
ignorePatterns: [
'docs/*',
'*.cjs',
@@ -68,33 +59,6 @@ module.exports = {
'@typescript-eslint/no-unsafe-assignment': 'off',
'es/no-regexp-lookbehind-assertions': 'error',
curly: ['error', 'all'],
'no-only-tests/no-only-tests': 'error',
'unicorn/no-null': 'off',
'unicorn/filename-case': [
'error',
{
case: 'camelCase'
}
],
'unicorn/prevent-abbreviations': [
'error',
{
allowList: {
ctx: true,
db: true,
doc: true,
env: true,
fn: true,
i: true,
param: true,
req: true,
res: true,
str: true,
searchParams: true,
temp: true,
ImportMetaEnv: true
}
}
]
'no-only-tests/no-only-tests': 'error'
}
};
+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
+13 -27
View File
@@ -1,32 +1,18 @@
name: Update Browserslist database
name: Update Browserslist
on:
schedule:
- cron: '0 2 1,15 * *'
permissions:
contents: write
pull-requests: write
push:
branches-ignore:
- 'develop'
- 'master'
jobs:
update-browserslist-database:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
- uses: actions/checkout@v3
- run: npx browserslist@latest --update-db
- name: Commit changes
uses: EndBug/add-and-commit@v9
with:
fetch-depth: 0
- name: Configure git
run: |
git config --global user.email "action@github.com"
git config --global user.name "GitHub Action"
- name: Update Browserslist database and create PR if applies
uses: c2corg/browserslist-update-action@v2
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: browserslist-update
base_branch: develop
commit_message: 'build: update Browserslist db'
title: 'build: update Browserslist db'
body: Auto-generated by [browserslist-update-action](https://github.com/c2corg/browserslist-update-action/)
labels: 'chores, github action'
author_name: ${{ github.actor }}
author_email: ${{ github.actor }}@users.noreply.github.com
message: 'Update Browserslist'
+3
View File
@@ -12,3 +12,6 @@ yarn-error.log
/cypress/downloads
/cypress/videos
/cypress/screenshots
/test-results/
/playwright-report/
/playwright/.cache/
+1 -15
View File
@@ -1,20 +1,6 @@
{
"editor.formatOnSave": true,
"cSpell.words": [
"Browserslist",
"KROKI",
"Serde",
"asyncable",
"corg",
"cssnano",
"daisyui",
"esserializer",
"localstorage",
"mindmap",
"pako",
"serdes",
"tailwindcss"
],
"cSpell.words": ["asyncable", "KROKI", "mindmap", "pako", "Serde", "serdes", "tailwindcss"],
"vitest.commandLine": "yarn test:unit",
"vitest.enable": true,
"testing.autoRun.mode": "rerun",
+1 -1
View File
@@ -6,7 +6,7 @@
# Stop : press ctrl + c
# or
# docker stop mermaid-live-editor
FROM node:18.14.0 as mermaid-live-editor-builder
FROM node:18.12.1 as mermaid-live-editor-builder
COPY --chown=node:node . /home
WORKDIR /home
RUN yarn install
+6 -9
View File
@@ -47,20 +47,17 @@ Then open http://localhost:8000
## Setup
Below link will help you making a copy of the repository in your local system.
[Volta](https://volta.sh) is used for managing node and yarn versions.
https://docs.github.com/en/get-started/quickstart/fork-a-repo
This project is set up using [Yarn](https://classic.yarnpkg.com/en/docs/getting-started):
## Requirements
- [volta](https://volta.sh/) to manage node versions.
- [Node.js](https://nodejs.org/en/). `volta install node`
- [yarn](https://yarnpkg.com/) package manager. `volta install yarn`
```
yarn install
```
## Development
```sh
yarn install
```
yarn dev -- --open
```
+6 -7
View File
@@ -1,9 +1,8 @@
import { verifyFileSizeGreaterThan } from './util';
import { verifyFileSize } from './util';
describe('Check actions', () => {
beforeEach(() => {
cy.clearLocalStorage();
cy.visit('/edit');
cy.contains('Actions').click();
});
it('should update markdown code', () => {
@@ -19,7 +18,7 @@ describe('Check actions', () => {
});
});
it.skip('should load gists from URL', () => {
it('should load gists from URL', () => {
cy.get('#gist').type('https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a');
cy.contains('Load Gist').click();
cy.contains('Go shopping!!');
@@ -29,20 +28,20 @@ describe('Check actions', () => {
cy.clock(new Date(2022, 0, 1).getTime());
cy.get(`#downloadPNG`).click();
verifyFileSizeGreaterThan('diagram', 'png', 35_000);
verifyFileSize('diagram', 'png', 21_000);
cy.get(`#downloadSVG`).click();
verifyFileSizeGreaterThan('diagram', 'svg', 10_000);
verifyFileSize('diagram', 'svg', 10_000);
// Verify downloaded file is different for different diagrams
cy.contains('Sample Diagrams').click();
cy.contains('ER').click();
cy.get(`#downloadPNG`).click();
verifyFileSizeGreaterThan('diagram', 'png', 40_000);
verifyFileSize('diagram', 'png', 46_000);
cy.get(`#downloadSVG`).click();
verifyFileSizeGreaterThan('diagram', 'svg', 11_000);
verifyFileSize('diagram', 'svg', 12_000);
cy.clock().invoke('restore');
});
+1 -1
View File
@@ -49,7 +49,7 @@ describe('Auto sync tests', () => {
});
it('supports commenting code out/in', () => {
getEditor({ bottom: true, newline: false }).type(`{uparrow}${cmd}/`);
getEditor().type(`{uparrow}${cmd}/`);
cy.get('#view').contains('Car').should('not.exist');
getEditor().type(`{uparrow}${cmd}/`);
+5 -3
View File
@@ -6,6 +6,7 @@ describe('Save History', () => {
cy.clearLocalStorage();
cy.visit('/edit');
cy.contains('Actions').click();
cy.contains('History').click();
});
@@ -23,6 +24,7 @@ describe('Save History', () => {
'[{"state":{"code":"graph TD\\n A[New Year] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":false},"time":0,"type":"auto","id":"69ea820e-522b-4a44-86cf-fd58acde09df","name":"barking-dog"},{"state":{"code":"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)","mermaid":"{\\n \\"theme\\": \\"dark\\"\\n}","autoSync":true,"updateDiagram":true},"time":0,"type":"manual","id":"x749ffc6-21dd-418a-b984-7c1ffc3146b3","name":"needy-mosquito"}]'
);
cy.reload();
cy.contains('Actions').click();
cy.contains('History').click();
cy.get('#historyList').find('li').should('have.length', 2);
cy.get('#historyList').find('No items in History').should('not.exist');
@@ -82,15 +84,15 @@ describe('Save History', () => {
// TODO: Fix #639
xit('should auto save history', () => {
getEditor().type(' C --> HistoryTest');
cy.tick(70_000);
cy.tick(70000);
cy.contains('Timeline').click();
cy.get('#historyList').find('li').should('have.length', 1);
cy.get('#editor').type('ing');
cy.tick(70_000);
cy.tick(70000);
cy.get('#historyList').find('li').should('have.length', 2);
for (let i = 0; i < 31; i++) {
cy.get('#editor').type('.');
cy.tick(70_000);
cy.tick(70000);
}
cy.get('#historyList').find('li').should('have.length', 30);
});
+11 -11
View File
@@ -94,17 +94,6 @@ describe('Site Loads', () => {
cy.contains('Please Click here to Raise an issue in github.');
});
it('should load compressed URL', () => {
cy.visit(
'/edit#pako:eNpVkM2KwkAQhF-l6dMK5gVyEDRxvYi7sF6WjIcm0zqDzg_jBJEk725Hd2G3Tw31VVFUj23QjCWeEkUD-1p5kFs2O77BN1M6QFEshg1ncMHzfYDV2ybA1YQYrT_NXvhqgqDqtxPGkI315_ElVU__h-cB6mZLMYd4-Kvsb2GAdWM_jcT_V0xicb03RyqPVLSUoJI-OEfHyZHV0rqfDAqzYccKS3k1pbNC5Ufhuqgp81rbHBJKxuXKc6Quh6-7b7HMqeNfqLYkC7gfanwAlW1ZvQ'
);
cy.contains('New Year');
cy.visit(
'/edit#pako:eNptkU1PwzAMhv9K5BOI9Q9EXBDbJA477YYqITcxndV8QD40weh_Jy1rGR0-OY_tV2_sEyivCSQogzGuGduAtnaixINji0bcf1WVWGfVXdMtx8M1faYm4B8sxR27JLClJd6nwK4VLTlN4bI4jMQd2pLe3C4KFhNNcLQ92jv9ADGLNoTdozc-zIV4ZDsNlud7RtVN7_5Sb_jYrFcN3iN_0pPbEqUZK3QbTP_Ojyv4NdR4bwTHlyMbPcOQ3WJ2CliBpWCRdbnLqFJDOpClGmRJNYauhtr1pS-_6bKMjebkA8hXNJFWgDn5_YdTIFPINDWdb3vu6r8BaWOZRQ'
);
cy.contains('Animal');
});
it('should load uncompressed URL', () => {
cy.visit(
'/edit/#eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW05ldyBZZWFyXSAtLT58R2V0IG1vbmV5fCBCKEdvIHNob3BwaW5nKVxuICAgIEIgLS0-IEN7TGV0IG1lIHRoaW5rfVxuICAgIEMgLS0-fE9uZXwgRFtMYXB0b3BdXG4gICAgQyAtLT58VHdvfCBFW2lQaG9uZV1cbiAgICBDIC0tPnxUaHJlZXwgRltmYTpmYS1jYXIgQ2FyXSIsIm1lcm1haWQiOiJ7XG4gIFwidGhlbWVcIjogXCJkZWZhdWx0XCJcbn0iLCJ1cGRhdGVFZGl0b3IiOmZhbHNlLCJhdXRvU3luYyI6dHJ1ZSwidXBkYXRlRGlhZ3JhbSI6ZmFsc2V9'
@@ -119,4 +108,15 @@ describe('Site Loads', () => {
);
cy.contains('New Year');
});
it('should load compressed URL', () => {
cy.visit(
'/edit#pako:eNpVkM2KwkAQhF-l6dMK5gVyEDRxvYi7sF6WjIcm0zqDzg_jBJEk725Hd2G3Tw31VVFUj23QjCWeEkUD-1p5kFs2O77BN1M6QFEshg1ncMHzfYDV2ybA1YQYrT_NXvhqgqDqtxPGkI315_ElVU__h-cB6mZLMYd4-Kvsb2GAdWM_jcT_V0xicb03RyqPVLSUoJI-OEfHyZHV0rqfDAqzYccKS3k1pbNC5Ufhuqgp81rbHBJKxuXKc6Quh6-7b7HMqeNfqLYkC7gfanwAlW1ZvQ'
);
cy.contains('New Year');
cy.visit(
'/edit#pako:eNptkU1PwzAMhv9K5BOI9Q9EXBDbJA477YYqITcxndV8QD40weh_Jy1rGR0-OY_tV2_sEyivCSQogzGuGduAtnaixINji0bcf1WVWGfVXdMtx8M1faYm4B8sxR27JLClJd6nwK4VLTlN4bI4jMQd2pLe3C4KFhNNcLQ92jv9ADGLNoTdozc-zIV4ZDsNlud7RtVN7_5Sb_jYrFcN3iN_0pPbEqUZK3QbTP_Ojyv4NdR4bwTHlyMbPcOQ3WJ2CliBpWCRdbnLqFJDOpClGmRJNYauhtr1pS-_6bKMjebkA8hXNJFWgDn5_YdTIFPINDWdb3vu6r8BaWOZRQ'
);
cy.contains('Animal');
});
});
+4 -7
View File
@@ -10,7 +10,7 @@ export const getEditor = ({ bottom = true, newline = false } = {}) =>
const downloadsFolder = Cypress.config('downloadsFolder');
export const verifyFileSizeGreaterThan = (
export const verifyFileSize = (
fileType: 'history' | 'diagram',
extension: string,
size: number
@@ -21,10 +21,7 @@ export const verifyFileSizeGreaterThan = (
cy.verifyDownload(fileName);
cy.readFile(filePath, null, {
log: false
}).then((buffer: ArrayBuffer) => {
expect(buffer.byteLength).to.be.gt(size);
expect(buffer.byteLength).to.be.lt(size * 1.3);
});
}).then((buffer) => expect((buffer as ArrayBuffer).byteLength).to.be.gt(size));
cy.task('deleteFile', filePath);
};
@@ -39,8 +36,8 @@ export const verifyFileSnapshot = (
cy.verifyDownload(fileName);
cy.readFile(filePath, null, {
log: false
}).then((buffer: ArrayBuffer) =>
expect(new TextDecoder('utf8').decode(buffer)).to.contain(content)
}).then((buffer) =>
expect(new TextDecoder('utf-8').decode(buffer as ArrayBuffer)).to.contain(content)
);
cy.task('deleteFile', filePath);
};
+3 -3
View File
@@ -1,7 +1,7 @@
module.exports = {
"Site Loads": {
"Check Home page load": {
"1": "{\"code\":\"flowchart TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n \",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":true}"
"1": "{\"code\":\"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n \",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":true}"
},
"Check Redirect from old URL": {
"1": "{\"code\":\"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":true}"
@@ -19,10 +19,10 @@ module.exports = {
"__version": "11.2.0",
"Auto sync tests": {
"should dim diagram when code is edited": {
"1": "{\"code\":\"flowchart TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n C --> Test\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":false,\"updateDiagram\":false}"
"1": "{\"code\":\"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n C --> Test\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":false,\"updateDiagram\":false}"
},
"should not dim diagram when code is in sync": {
"1": "{\"code\":\"flowchart TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n C --> Testing\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":false}"
"1": "{\"code\":\"graph TD\\n A[Christmas] -->|Get money| B(Go shopping)\\n B --> C{Let me think}\\n C -->|One| D[Laptop]\\n C -->|Two| E[iPhone]\\n C -->|Three| F[fa:fa-car Car]\\n C --> Testing\",\"mermaid\":\"{\\n \\\"theme\\\": \\\"default\\\"\\n}\",\"autoSync\":true,\"updateDiagram\":false}"
}
},
"Test themes": {
+1 -1
View File
@@ -1,7 +1,7 @@
{
"compilerOptions": {
"allowJs": true,
"types": ["cypress", "cypress-localstorage-commands", "cy-verify-downloads", "node"]
"types": ["cypress", "cypress-localstorage-commands", "cy-verify-downloads"]
},
"include": ["**/*.ts"]
}
+26 -24
View File
@@ -19,61 +19,63 @@
"test:coverage": "vitest run --coverage",
"test:browser": "cypress run",
"test": "test:unit && test:browser",
"cy": "cypress open"
"cy": "cypress open",
"pw": "npx playwright test"
},
"devDependencies": {
"@cypress/snapshot": "2.1.7",
"@sveltejs/adapter-static": "1.0.6",
"@sveltejs/kit": "1.5.0",
"@playwright/test": "^1.28.1",
"@sveltejs/adapter-static": "1.0.0-next.48",
"@sveltejs/kit": "1.0.0-next.561",
"@testing-library/jest-dom": "5.16.5",
"@testing-library/svelte": "3.2.2",
"@types/pako": "2.0.0",
"@types/uuid": "8.3.4",
"@typescript-eslint/eslint-plugin": "5.51.0",
"@typescript-eslint/parser": "5.51.0",
"@vitest/ui": "^0.28.0",
"@typescript-eslint/eslint-plugin": "5.44.0",
"@typescript-eslint/parser": "5.44.0",
"@vitest/ui": "^0.25.3",
"autoprefixer": "^10.4.13",
"c8": "7.12.0",
"chai": "^4.3.7",
"cssnano": "^5.1.14",
"cy-verify-downloads": "0.1.11",
"cypress": "11.2.0",
"cypress-localstorage-commands": "2.2.2",
"eslint": "8.33.0",
"eslint-config-prettier": "8.6.0",
"cypress-localstorage-commands": "2.2.1",
"eslint": "8.28.0",
"eslint-config-prettier": "8.5.0",
"eslint-plugin-cypress": "2.12.1",
"eslint-plugin-es": "4.1.0",
"eslint-plugin-no-only-tests": "^3.1.0",
"eslint-plugin-postcss-modules": "2.0.0",
"eslint-plugin-svelte3": "4.0.0",
"eslint-plugin-tailwindcss": "3.8.3",
"eslint-plugin-unicorn": "^45.0.0",
"eslint-plugin-vitest": "^0.0.32",
"esserializer": "1.3.10",
"eslint-plugin-tailwindcss": "3.7.0",
"eslint-plugin-vitest": "^0.0.20",
"esserializer": "1.3.5",
"font-awesome": "^4.7.0",
"husky": "^8.0.2",
"jsdom": "20.0.3",
"lint-staged": "13.1.1",
"lint-staged": "13.0.3",
"node-html-parser": "^6.1.4",
"postcss": "^8.4.19",
"postcss-load-config": "4.0.1",
"prettier": "2.8.3",
"prettier": "2.8.0",
"prettier-plugin-svelte": "^2.8.1",
"svelte": "3.55.1",
"svelte": "3.53.1",
"svelte-preprocess": "4.10.7",
"tailwindcss": "^3.2.4",
"tslib": "^2.4.1",
"typescript": "4.9.5",
"vite": "^4.0.1",
"vitest": "^0.28.0"
"typescript": "4.9.3",
"vite": "^3.2.4",
"vitest": "^0.25.3"
},
"dependencies": {
"@mermaid-js/mermaid-mindmap": "9.2.2",
"analytics": "0.8.1",
"analytics-plugin-plausible": "0.0.6",
"daisyui": "2.50.0",
"dayjs": "^1.11.7",
"js-base64": "3.7.4",
"mermaid": "10.0.1-rc.3",
"daisyui": "2.42.1",
"js-base64": "3.7.3",
"mermaid": "9.2.2",
"moment": "2.29.4",
"monaco-editor": "0.34.1",
"monaco-mermaid": "1.0.8",
"pako": "2.1.0",
@@ -88,7 +90,7 @@
]
},
"volta": {
"node": "18.14.0",
"node": "18.12.1",
"yarn": "1.22.19"
},
"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;
+3 -3
View File
@@ -6,13 +6,13 @@
import { stateStore } from '$lib/util/state';
import { logEvent } from '$lib/util/stats';
import { toBase64 } from 'js-base64';
import dayjs from 'dayjs';
import moment from 'moment';
const { krokiRendererUrl, rendererUrl } = env;
type Exporter = (context: CanvasRenderingContext2D, image: HTMLImageElement) => () => void;
const getFileName = (ext: string) =>
`mermaid-diagram-${dayjs().format('YYYY-MM-DD-HHmmss')}.${ext}`;
`mermaid-diagram-${moment().format('YYYY-MM-DD-HHmmss')}.${ext}`;
const getBase64SVG = (svg?: HTMLElement, width?: number, height?: number): string => {
height && svg?.setAttribute('height', `${height}px`);
@@ -180,7 +180,7 @@
});
</script>
<Card title="Actions" isOpen={false}>
<Card title="Actions" isOpen={true}>
<div class="flex flex-wrap gap-2 m-2">
{#if isClipboardAvailable()}
<button class="action-btn w-full" on:click={onCopyClipboard}
@@ -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
View File
@@ -19,5 +19,6 @@ describe('card.svelte', () => {
expect(container).toHaveTextContent('title1');
expect(container).toHaveTextContent('title2');
expect(container).not.toHaveTextContent('title3');
expect(container.innerHTML).toMatchSnapshot();
});
});
+6 -6
View File
@@ -21,7 +21,7 @@
let text = '';
stateStore.subscribe(({ errorMarkers, editorMode, code, mermaid }) => {
// console.log('editor store subscription', { code, mermaid });
console.log('editor store subscription', { code, mermaid });
if (!editor || !Monaco) {
return;
}
@@ -29,7 +29,7 @@
// Update editor text if it's different
const newText = editorMode === 'code' ? code : mermaid;
if (newText !== text) {
// console.log('updating editor text', newText);
console.log('updating editor text', newText);
editor.setValue(newText);
text = newText;
}
@@ -54,7 +54,7 @@
});
const handleUpdate = (text: string, mode: EditorMode) => {
// console.log('editor HandleUpdate', { text, mode });
console.log('editor HandleUpdate', { text, mode });
if (mode === 'code') {
updateCode(text);
} else {
@@ -91,7 +91,7 @@
editor = Monaco.editor.create(divEl, editorOptions);
editor.onDidChangeModelContent(({ isFlush, changes }) => {
const newText = editor?.getValue();
// console.log('editor onDidChangeModelContent', { text, newText, isFlush, changes });
console.log('editor onDidChangeModelContent', { text, newText, isFlush, changes });
if (!newText || text === newText || isFlush) {
return;
}
@@ -120,9 +120,9 @@
if (divEl.parentElement) {
resizeObserver.observe(divEl.parentElement);
}
// console.log(`editor mounted`);
console.log(`editor mounted`);
return () => {
// console.log(`editor disposed`);
console.log(`editor disposed`);
editor?.dispose();
};
});
+3 -6
View File
@@ -13,13 +13,10 @@
import { notify, prompt } from '$lib/util/notify';
import { onMount } from 'svelte';
import { get } from 'svelte/store';
import dayjs from 'dayjs';
import dayjsRelativeTime from 'dayjs/plugin/relativeTime';
import moment from 'moment';
import type { HistoryEntry, HistoryType, State, Tab } from '$lib/types';
import { logEvent } from '$lib/util/stats';
dayjs.extend(dayjsRelativeTime);
const HISTORY_SAVE_INTERVAL = 60000;
const tabSelectHandler = (message: CustomEvent<Tab>) => {
@@ -44,7 +41,7 @@
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `mermaid-history-${dayjs().format('YYYY-MM-DD-HHmmss')}.json`;
a.download = `mermaid-history-${moment().format('YYYY-MM-DD-HHmmss')}.json`;
a.click();
URL.revokeObjectURL(url);
logEvent('history', {
@@ -98,7 +95,7 @@
const relativeTime = (time: number) => {
const t = new Date(time);
return `${new Date(t).toLocaleString()} (${dayjs(t).fromNow()})`;
return `${new Date(t).toLocaleString()} (${moment(t).fromNow()})`;
};
onMount(() => {
+8 -8
View File
@@ -17,7 +17,7 @@ describe('history', () => {
addHistoryEntry({
state: defaultState,
time: 12_345,
time: 12345,
type: 'manual'
});
@@ -25,14 +25,14 @@ describe('history', () => {
window.localStorage.getItem('manualHistoryStore') ?? '[]'
) as HistoryEntry[];
expect(manualEntry.time).toBe(12_345);
expect(manualEntry.time).toBe(12345);
expect(manualEntry.type).toBe('manual');
expect(manualEntry.name).not.toBeNull();
expect(manualEntry.state).not.toBeNull();
addHistoryEntry({
state: defaultState,
time: 54_321,
time: 54321,
type: 'auto'
});
@@ -40,7 +40,7 @@ describe('history', () => {
window.localStorage.getItem('autoHistoryStore') ?? '[]'
) as HistoryEntry[];
expect(autoEntry.time).toBe(54_321);
expect(autoEntry.time).toBe(54321);
expect(autoEntry.type).toBe('auto');
expect(autoEntry.name).not.toBeNull();
expect(autoEntry.state).not.toBeNull();
@@ -56,12 +56,12 @@ describe('history', () => {
it('should clear history entries', () => {
addHistoryEntry({
state: defaultState,
time: 12_345,
time: 12345,
type: 'manual'
});
addHistoryEntry({
state: { ...defaultState, code: 'graph TD\\n A[Christmas] -->|Get money| B(Go shopping)' },
time: 123_456,
time: 123456,
type: 'manual'
});
@@ -76,12 +76,12 @@ describe('history', () => {
historyModeStore.set('auto');
addHistoryEntry({
state: defaultState,
time: 54_321,
time: 54321,
type: 'auto'
});
addHistoryEntry({
state: { ...defaultState, code: 'graph TD\\n A[Christmas] -->|Get money| B(Go shopping)' },
time: 654_321,
time: 654321,
type: 'auto'
});
expect(get(historyStore).length).toBe(2);
+18 -29
View File
@@ -26,27 +26,19 @@ const manualHistoryStore: Writable<HistoryEntry[]> = persist(
'manualHistoryStore'
);
export const loaderHistoryStore: Writable<HistoryEntry[]> = writable([]);
export const loaderHistoryStore: Writable<HistoryEntry[]> = writable([] as HistoryEntry[]);
export const historyStore: Readable<HistoryEntry[]> = derived(
[historyModeStore, autoHistoryStore, manualHistoryStore, loaderHistoryStore],
([historyMode, autoHistories, manualHistories, loadedHistories], set) => {
switch (historyMode) {
case 'auto': {
set(autoHistories);
break;
}
case 'manual': {
set(manualHistories);
break;
}
case 'loader': {
set(loadedHistories);
break;
}
default: {
set(autoHistories);
}
if (historyMode === 'auto') {
set(autoHistories);
} else if (historyMode === 'manual') {
set(manualHistories);
} else if (historyMode === 'loader') {
set(loadedHistories);
} else {
set(autoHistories);
}
}
);
@@ -98,7 +90,7 @@ export const getPreviousState = (auto: boolean): string => {
};
export const restoreHistory = (data: HistoryEntry[]) => {
const entries = data.filter((element) => validateEntry(element));
const entries = data.filter(validateEntry);
const invalidEntryCount = data.length - entries.length;
if (invalidEntryCount > 0) {
console.error(`${invalidEntryCount} invalid history entries were removed.`);
@@ -130,23 +122,20 @@ export const restoreHistory = (data: HistoryEntry[]) => {
alert('No valid entries found.');
}
};
const setIDs = (entries: HistoryEntry[]) => {
for (const entry of entries) {
if (!entry.id) {
entry.id = uuidV4();
}
}
return entries;
};
export const injectHistoryIDs = (): void => {
const setIDs = (entries: HistoryEntry[]) => {
for (const entry of entries) {
if (!entry.id) {
entry.id = uuidV4();
}
}
return entries;
};
autoHistoryStore.update(setIDs);
manualHistoryStore.update(setIDs);
};
const validateEntry = (entry: HistoryEntry): boolean => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
return entry.type && entry.state && entry.time && true;
};
+2 -2
View File
@@ -17,11 +17,11 @@
const links: Link[] = [
{
title: 'Documentation',
href: 'https://mermaid-js.github.io/mermaid/intro/n00b-gettingStarted.html'
href: 'https://mermaid-js.github.io/mermaid/#/n00b-gettingStarted'
},
{
title: 'Tutorial',
href: 'https://mermaid-js.github.io/mermaid/config/Tutorials.html'
href: 'https://github.com/mermaid-js/mermaid/blob/develop/docs/Tutorials.md'
},
{
title: 'Mermaid',
+1 -1
View File
@@ -4,7 +4,7 @@
import { logEvent } from '$lib/util/stats';
const samples = {
Flow: `flowchart TD
Flow: `graph TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
C -->|One| D[Laptop]
+20 -20
View File
@@ -79,27 +79,27 @@
panZoomEnabled = state.panZoom;
const scroll = view.parentElement!.scrollTop;
delete container.dataset.processed;
const { svg, bindFunctions } = await renderDiagram(
await renderDiagram(
Object.assign({}, JSON.parse(state.mermaid)) as MermaidConfig,
code,
'graph-div'
'graph-div',
(svgCode, bindFunctions) => {
if (svgCode.length > 0) {
handlePanZoom(state);
container.innerHTML = svgCode;
// console.log(container.innerHTML);
const graphDiv = document.getElementById('graph-div');
if (!graphDiv) {
throw new Error('graph-div not found');
}
graphDiv.setAttribute('height', '100%');
graphDiv.style.maxWidth = '100%';
if (bindFunctions) {
bindFunctions(graphDiv);
}
}
}
);
if (svg.length > 0) {
handlePanZoom(state);
container.innerHTML = svg;
console.log({ svg });
const graphDiv = document.getElementById('graph-div');
if (!graphDiv) {
throw new Error('graph-div not found');
}
graphDiv.setAttribute('height', '100%');
graphDiv.style.maxWidth = '100%';
if (bindFunctions) {
bindFunctions(graphDiv);
}
}
view.parentElement!.scrollTop = scroll;
error = false;
} else if (manualUpdate) {
@@ -122,7 +122,7 @@
pzoom.resize();
}
});
// console.log('View mounted');
console.log('View mounted');
});
</script>
@@ -133,7 +133,7 @@
: 'text-yellow-600'} bg-base-100 bg-opacity-80 text-center"
id="errorContainer">
{#if error}
{@html $stateStore.error?.toString().replace(/\n/g, '<br />')}
{@html $stateStore.error.toString().replace(/\n/g, '<br />')}
{:else}
Diagram out of sync. <br />
Press <i class="fas fa-sync" /> (Sync button) or <kbd>{cmdKey} + Enter</kbd> to sync.
+1 -1
View File
@@ -65,7 +65,7 @@ export type HistoryEntry = { id: string; state: State; time: number; url?: strin
}
);
export type DocumentationConfig = Record<
export type DocConfig = Record<
string,
{
code: string;
+8 -9
View File
@@ -5,7 +5,6 @@
import type { State } from '$lib/types';
import { defaultState } from '$lib/util/state';
import { addHistoryEntry } from '$lib/components/History/history';
import { fetchJSON, fetchText } from '$lib/util/util';
const codeFileName = 'code.mmd';
const configFileName = 'config.json';
@@ -22,7 +21,7 @@ const isValidGist = (files: any): boolean => {
const getFileContent = async (file: GithubFile): Promise<string> => {
if (file.truncated) {
return await fetchText(file.raw_url);
return await (await fetch(file.raw_url)).text();
}
return file.content;
};
@@ -50,9 +49,9 @@ const getGistData = async (gistURL: string): Promise<GistData> => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_, __, gistID, revisionID] = path.split('/');
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const { html_url, files, history }: GistResponse = await fetchJSON(
`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`
);
const { html_url, files, history }: GistResponse = await (
await fetch(`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`)
).json();
if (isValidGist(files)) {
const code = await getFileContent(files[codeFileName]);
let config = '{}';
@@ -97,12 +96,12 @@ export const loadGistData = async (gistURL: string): Promise<State> => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_, __, gistID, revisionID] = path.split('/');
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const { history }: GistResponse = await fetchJSON(
`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`
);
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();
const data: GistData | undefined = await getGistData(entry.url).catch(() => undefined);
data && gistHistory.push(data);
}
if (gistHistory.length === 0) {
+22 -20
View File
@@ -1,8 +1,6 @@
import { loadGistData } from './gist';
import { updateCodeStore, defaultState } from '$lib/util/state';
import { fetchText } from '$lib/util/util';
import { updateCodeStore, defaultState } from '../state';
import type { Loader, State } from '$lib/types';
const loaders: Record<string, Loader> = {
gist: loadGistData
};
@@ -10,18 +8,34 @@ const loaders: Record<string, Loader> = {
export const loadDataFromUrl = async (): Promise<void> => {
const searchParams = new URLSearchParams(window.location.search);
let state: Partial<State> = defaultState;
let code: string | undefined = undefined;
let config: string | undefined = undefined;
let loaded = false;
const codeURL: string | undefined = searchParams.get('code') ?? undefined;
const configURL: string | undefined = searchParams.get('config') ?? undefined;
let code: string | undefined;
const config = configURL ? await fetchText(configURL) : defaultState.mermaid;
if (codeURL) {
code = await fetchText(codeURL);
code = await (await fetch(codeURL)).text();
loaded = true;
}
if (code) {
if (configURL) {
config = await (await fetch(configURL)).text();
} else {
config = defaultState.mermaid;
}
if (!code) {
for (const [key, value] of searchParams.entries()) {
if (key in loaders) {
try {
state = await loaders[key](value);
loaded = true;
break;
} catch (err) {
console.error(err);
}
}
}
} else {
if (!codeURL) {
throw new Error('Code URL is not defined');
}
@@ -36,18 +50,6 @@ export const loadDataFromUrl = async (): Promise<void> => {
}
}
};
} else {
for (const [key, value] of searchParams.entries()) {
if (key in loaders) {
try {
state = await loaders[key](value);
loaded = true;
break;
} catch (error) {
console.error(error);
}
}
}
}
loaded &&
updateCodeStore({
+18 -7
View File
@@ -1,16 +1,27 @@
import mermaid from 'mermaid';
import type { MermaidConfig, RenderResult } from 'mermaid';
import mermaid, { type MermaidConfig } from 'mermaid';
import mindmap from '@mermaid-js/mermaid-mindmap';
const initialize = mermaid.registerExternalDiagrams([mindmap]);
export const init = async () => {
await initialize;
};
export const render = async (
config: MermaidConfig,
code: string,
id: string
): Promise<RenderResult> => {
id: string,
callback: Parameters<typeof mermaid.render>[2]
): Promise<void> => {
// Should be able to call this multiple times without any issues.
mermaid.initialize(config);
return await mermaid.render(id, code);
// console.log('Rendering', code);
// mermaid.mermaidAPI.render(id, code, callback);
await init();
await mermaid.mermaidAPI.renderAsync(id, code, callback);
};
export const parse = async (code: string): Promise<unknown> => {
return await mermaid.parse(code);
export const parse = async (code: string): Promise<boolean> => {
await init();
return await mermaid.parseAsync(code);
};
+7 -5
View File
@@ -70,13 +70,13 @@ const deserialize = (value?: string | null): unknown => {
if (value !== null && value !== undefined) {
try {
return ESSerializer.deserialize(value);
} catch {
} catch (e) {
// Do nothing
// use the value "as is"
}
try {
return JSON.parse(value);
} catch {
} catch (e) {
// Do nothing
// use the value "as is"
}
@@ -179,9 +179,11 @@ function getBrowserStorage(
const listenerFunction = (event: StorageEvent) => {
const eventKey = event.key;
if (event.storageArea === browserStorage) {
for (const { listener } of listeners.filter(({ key }) => key === eventKey)) {
listener(deserialize(event.newValue));
}
listeners
.filter(({ key }) => key === eventKey)
.forEach(({ listener }) => {
listener(deserialize(event.newValue));
});
}
};
const connect = () => {
+10 -10
View File
@@ -3,29 +3,29 @@ import { serializeState, deserializeState, type SerdeType } from './serde';
import { defaultState } from './state';
import type { State } from '$lib/types';
const verifySerde = (state: State, serde?: SerdeType): string => {
const serialized = serializeState(state, serde);
const deserialized = deserializeState(serialized);
expect(deserialized).to.deep.equal(state);
return serialized;
};
describe('Serde tests', () => {
const verifySerde = (state: State, serde?: SerdeType): string => {
const serialized = serializeState(state, serde);
const deserialized = deserializeState(serialized);
expect(deserialized).to.deep.equal(state);
return serialized;
};
it('should serialize and deserialize with default serde', () => {
expect(verifySerde(defaultState)).toMatchInlineSnapshot(
'"pako:eNpVjk2Lg0AMhv9KyGkL9Q94WGh1t5fCFurN6SFo7AztfDBGpKj_fcd62c0pvM_zhkzY-JYxx-7px0ZTFKhK5SDNoS50NL1Y6m-QZZ_ziQWsd_ya4fhx8tBrH4Jx993mH1cJium8agyijXssGyre_R_HM5T1mYL4cPtLqtHP8FWbi07n_xMdObW-647yjrKGIhQU3wru0XK0ZNr0_rQmCkWzZYV5WlvuaHiKQuWWpNIg_vpyDeYSB97jEFoSLg3dI9ktXH4B_cJWqw"'
'"pako:eNpVj81qw0AMhF9F6NRC_AI-BGK7zSXQQHLz5iBsObuk-8Naphjb7551fEl1EjPfiNGEjW8Zc7xHChqulXKQ5lCXOppeLPU3yLL9fGQB6x2PMxQfRw-99iEYd__c-GKFoJxOK8Yg2rjHslnlK__jeIaqPlEQH27vzvXPz_BVm7NO5_87OnJKfdcd5R1lDUUoKb4Q3KHlaMm0qfq0KgpFs2WFeVpb7mj4FYXKLQmlQfxldA3mEgfe4RBaEq4MpaftJi5PNtJU8w"'
);
});
it('should serialize and deserialize with base64 serde', () => {
expect(verifySerde(defaultState, 'base64')).toMatchInlineSnapshot(
'"base64:eyJjb2RlIjoiZmxvd2NoYXJ0IFREXG4gICAgQVtDaHJpc3RtYXNdIC0tPnxHZXQgbW9uZXl8IEIoR28gc2hvcHBpbmcpXG4gICAgQiAtLT4gQ3tMZXQgbWUgdGhpbmt9XG4gICAgQyAtLT58T25lfCBEW0xhcHRvcF1cbiAgICBDIC0tPnxUd298IEVbaVBob25lXVxuICAgIEMgLS0-fFRocmVlfCBGW2ZhOmZhLWNhciBDYXJdXG4gICIsIm1lcm1haWQiOiJ7XG4gIFwidGhlbWVcIjogXCJkZWZhdWx0XCJcbn0iLCJhdXRvU3luYyI6dHJ1ZSwidXBkYXRlRGlhZ3JhbSI6dHJ1ZX0"'
'"base64:eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW0NocmlzdG1hc10gLS0-fEdldCBtb25leXwgQihHbyBzaG9wcGluZylcbiAgICBCIC0tPiBDe0xldCBtZSB0aGlua31cbiAgICBDIC0tPnxPbmV8IERbTGFwdG9wXVxuICAgIEMgLS0-fFR3b3wgRVtpUGhvbmVdXG4gICAgQyAtLT58VGhyZWV8IEZbZmE6ZmEtY2FyIENhcl1cbiAgIiwibWVybWFpZCI6IntcbiAgXCJ0aGVtZVwiOiBcImRlZmF1bHRcIlxufSIsImF1dG9TeW5jIjp0cnVlLCJ1cGRhdGVEaWFncmFtIjp0cnVlfQ"'
);
});
it('should serialize and deserialize with pako serde', () => {
expect(verifySerde(defaultState, 'pako')).toMatchInlineSnapshot(
'"pako:eNpVjk2Lg0AMhv9KyGkL9Q94WGh1t5fCFurN6SFo7AztfDBGpKj_fcd62c0pvM_zhkzY-JYxx-7px0ZTFKhK5SDNoS50NL1Y6m-QZZ_ziQWsd_ya4fhx8tBrH4Jx993mH1cJium8agyijXssGyre_R_HM5T1mYL4cPtLqtHP8FWbi07n_xMdObW-647yjrKGIhQU3wru0XK0ZNr0_rQmCkWzZYV5WlvuaHiKQuWWpNIg_vpyDeYSB97jEFoSLg3dI9ktXH4B_cJWqw"'
'"pako:eNpVj81qw0AMhF9F6NRC_AI-BGK7zSXQQHLz5iBsObuk-8Naphjb7551fEl1EjPfiNGEjW8Zc7xHChqulXKQ5lCXOppeLPU3yLL9fGQB6x2PMxQfRw-99iEYd__c-GKFoJxOK8Yg2rjHslnlK__jeIaqPlEQH27vzvXPz_BVm7NO5_87OnJKfdcd5R1lDUUoKb4Q3KHlaMm0qfq0KgpFs2WFeVpb7mj4FYXKLQmlQfxldA3mEgfe4RBaEq4MpaftJi5PNtJU8w"'
);
});
+24 -20
View File
@@ -2,28 +2,32 @@ import { writable, get, type Readable, derived } from 'svelte/store';
import { persist, localStorage } from './persist';
import { saveStatistics, countLines } from './stats';
import { serializeState, deserializeState } from './serde';
import { cmdKey, errorDebug, formatJSON } from './util';
import { cmdKey, errorDebug } from './util';
import { parse } from './mermaid';
import type { ErrorHash, MarkerData, State, ValidatedState } from '$lib/types';
import type { MermaidConfig } from 'mermaid';
export const defaultState: State = {
code: `flowchart TD
code: `graph TD
A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think}
C -->|One| D[Laptop]
C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car]
`,
mermaid: formatJSON({
theme: 'default'
}),
mermaid: JSON.stringify(
{
theme: 'default'
},
null,
2
),
autoSync: true,
updateDiagram: true
};
const urlParseFailedState = `flowchart TD
const urlParseFailedState = `graph TD
A[Loading URL failed. We can try to figure out why.] -->|Decode JSON| B(Please check the console to see the JSON and error details.)
B --> C{Is the JSON correct?}
C -->|Yes| D(Please Click here to Raise an issue in github.<br/>Including the broken link in the issue <br/> will speed up the fix.)
@@ -61,16 +65,16 @@ const processState = async (state: State) => {
processed.serialized = serializeState(state);
await parse(state.code);
JSON.parse(state.mermaid);
} catch (error) {
processed.error = error as Error;
} catch (e) {
processed.error = e as Error;
errorDebug();
console.error(error);
if ('hash' in error) {
console.error(e);
if ('hash' in e) {
try {
const {
loc: { first_line, last_line, first_column, last_column }
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
} = error.hash as ErrorHash;
} = e.hash as ErrorHash;
const marker: MarkerData = {
severity: 8, // Error
startLineNumber: first_line,
@@ -78,11 +82,11 @@ const processState = async (state: State) => {
endLineNumber: last_line,
endColumn: last_column + 1,
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment
message: error.str
message: e.str
};
processed.errorMarkers = [marker];
} catch (error) {
console.error('Error without line helper', error);
} catch (err) {
console.error('Error without line helper', err);
}
}
}
@@ -116,11 +120,11 @@ export const loadState = (data: string): void => {
) {
delete mermaidConfig.securityLevel; // Prevent setting overriding securityLevel when loading state to mitigate possible XSS attack
}
state.mermaid = formatJSON(mermaidConfig);
} catch (error) {
state.mermaid = JSON.stringify(mermaidConfig, null, 2);
} catch (e) {
state = get(inputStateStore);
if (data) {
console.error('Init error', error);
console.error('Init error', e);
state.code = urlParseFailedState;
state.mermaid = defaultState.mermaid;
}
@@ -142,7 +146,7 @@ export const updateCode = (
resetPanZoom = false
}: { updateDiagram?: boolean; resetPanZoom?: boolean } = {}
): void => {
// console.log('updateCode', code);
console.log('updateCode', code);
const lines = countLines(code);
saveStatistics(code);
errorDebug();
@@ -168,7 +172,7 @@ export const updateCode = (
};
export const updateConfig = (config: string): void => {
// console.log('updateConfig', config);
console.log('updateConfig', config);
inputStateStore.update((state) => {
return { ...state, mermaid: config };
});
@@ -181,7 +185,7 @@ export const toggleDarkTheme = (dark: boolean): void => {
config.theme = dark ? 'dark' : 'default';
}
return { ...state, mermaid: formatJSON(config) };
return { ...state, mermaid: JSON.stringify(config, null, 2) };
});
};
+5 -5
View File
@@ -20,8 +20,8 @@ export const initAnalytics = async (): Promise<void> => {
})
]
});
} catch (error) {
console.log(error);
} catch (e) {
console.log(e);
console.info('Analytics blocked ;)');
}
}
@@ -87,10 +87,10 @@ export const logEvent = (name: AnalyticsEvent, data?: unknown): void => {
return;
}
const key = data ? JSON.stringify({ name, data }) : name;
if (timeouts.has(key)) {
clearTimeout(timeouts.get(key));
} else {
if (!timeouts.has(key)) {
void analytics.track(name, data);
} else {
clearTimeout(timeouts.get(key));
}
timeouts.set(
key,
+3 -3
View File
@@ -16,7 +16,7 @@ export const themeStore: Writable<ThemeConfig> = persist(
'themeStore'
);
const darkThemes = new Set([
const darkThemes = [
'dark',
'synthwave',
'halloween',
@@ -25,13 +25,13 @@ const darkThemes = new Set([
'luxury',
'black',
'dracula'
]);
];
export const setTheme = (theme: string): void => {
if (theme.includes(' ')) {
theme = theme.split(' ')[1].trim();
}
const isDark = darkThemes.has(theme);
const isDark = darkThemes.includes(theme);
console.log('Setting theme', theme);
themeStore.set({ theme, isDark });
logEvent('themeChange', { theme, isDark });
+2 -10
View File
@@ -3,6 +3,7 @@ import { analytics, initAnalytics } from './stats';
import { loadDataFromUrl } from './fileLoaders/loader';
import { initLoading } from './loading';
import { applyMigrations } from './migrations';
import { init } from './mermaid';
export const loadStateFromURL = (): void => {
loadState(window.location.hash.slice(1));
@@ -16,6 +17,7 @@ export const syncDiagram = (): void => {
export const initHandler = async (): Promise<void> => {
applyMigrations();
await initLoading('Loading Mermaid...', init());
loadStateFromURL();
await initLoading('Loading Gist...', loadDataFromUrl().catch(console.error));
syncDiagram();
@@ -36,13 +38,3 @@ export const errorDebug = (limit = 100) => {
debugger;
}
};
export const formatJSON = (data: unknown): string => JSON.stringify(data, undefined, 2);
export const fetchJSON = async <T>(url: string): Promise<T> => {
const res = await fetch(url);
return res.json() as T;
};
export const fetchText = async (url: string): Promise<string> => {
const res = await fetch(url);
return res.text();
};
+4 -7
View File
@@ -9,11 +9,11 @@
import { inputStateStore, stateStore, updateCodeStore } from '$lib/util/state';
import { cmdKey, initHandler, syncDiagram } from '$lib/util/util';
import { onMount } from 'svelte';
import type { Tab, DocumentationConfig, EditorMode, ValidatedState } from '$lib/types';
import type { Tab, DocConfig, EditorMode, ValidatedState } from '$lib/types';
import { base } from '$app/paths';
const docURLBase = 'https://mermaid-js.github.io/mermaid';
const docMap: DocumentationConfig = {
const docMap: DocConfig = {
graph: {
code: '/#/flowchart',
config: '/#/flowchart?id=configuration'
@@ -54,12 +54,11 @@
};
let docURL = docURLBase;
let activeTabID = 'code';
let docKey = '';
stateStore.subscribe(({ code, editorMode }: ValidatedState) => {
activeTabID = editorMode;
const codeTypeMatch = /([\S]+)[\s\n]/.exec(code);
if (codeTypeMatch && codeTypeMatch.length > 1) {
docKey = codeTypeMatch[1];
const docKey = codeTypeMatch[1];
const docConfig = docMap[docKey] ?? { code: '' };
docURL = docURLBase + (docConfig[editorMode] ?? docConfig.code ?? '');
}
@@ -134,9 +133,7 @@
on:click={syncDiagram}><i class="fas fa-sync" /></button>
{/if}
<button
class="btn btn-secondary btn-xs"
title="View documentation for {docKey.replace('Diagram', '')} diagram">
<button class="btn btn-secondary btn-xs" title="View documentation">
<a target="_blank" rel="noreferrer" href={docURL} data-cy="docs">
<i class="fas fa-book mr-1" />Docs
</a>
+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":"[]"}]}]
+5 -1
View File
@@ -6,8 +6,12 @@
"cypress/**/*.ts",
"cypress/**/*.js",
"cypress/**/*.json",
"tests/**/*.ts",
"tests/**/*.js",
"tests/**/*.json",
"static/**/*.js",
"static/**/*.json"
"static/**/*.json",
"./playwright.config.ts"
],
"compilerOptions": {
"resolveJsonModule": true,
+4 -4
View File
@@ -1,7 +1,6 @@
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vitest/config';
export default defineConfig({
/** @type {import('vite').UserConfig} */
const config = {
plugins: [sveltekit()],
envPrefix: 'MERMAID_',
optimizeDeps: { include: ['mermaid'] },
@@ -23,4 +22,5 @@ export default defineConfig({
reporter: ['text', 'json', 'html', 'lcov']
}
}
});
};
export default config;
+742 -930
View File
File diff suppressed because it is too large Load Diff