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
49 changed files with 2277 additions and 2118 deletions
+2 -38
View File
@@ -6,18 +6,9 @@ module.exports = {
'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', 'plugin:@typescript-eslint/strict',
'plugin:unicorn/recommended',
'prettier' 'prettier'
], ],
plugins: [ plugins: ['svelte3', 'tailwindcss', '@typescript-eslint', 'es', 'vitest', 'no-only-tests'],
'svelte3',
'tailwindcss',
'@typescript-eslint',
'es',
'vitest',
'no-only-tests',
'unicorn'
],
ignorePatterns: [ ignorePatterns: [
'docs/*', 'docs/*',
'*.cjs', '*.cjs',
@@ -68,33 +59,6 @@ module.exports = {
'@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', 'no-only-tests/no-only-tests': 'error'
'unicorn/no-null': 'off',
'unicorn/filename-case': [
'error',
{
case: 'camelCase'
}
],
'unicorn/prevent-abbreviations': [
'error',
{
allowList: {
ctx: true,
db: true,
doc: true,
env: true,
fn: true,
i: true,
param: true,
req: true,
res: true,
str: true,
searchParams: true,
temp: true,
ImportMetaEnv: true
}
}
]
} }
}; };
+27
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
@@ -8,7 +8,7 @@ jobs:
stale: stale:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/stale@v8 - uses: actions/stale@v6
with: with:
repo-token: ${{ secrets.GITHUB_TOKEN }} repo-token: ${{ secrets.GITHUB_TOKEN }}
exempt-issue-labels: 'retained' exempt-issue-labels: 'retained'
+13 -27
View File
@@ -1,32 +1,18 @@
name: Update Browserslist database name: Update Browserslist
on: on:
schedule: push:
- cron: '0 2 1,15 * *' branches-ignore:
- 'develop'
permissions: - 'master'
contents: write
pull-requests: write
jobs: jobs:
update-browserslist-database: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: 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: with:
fetch-depth: 0 author_name: ${{ github.actor }}
- name: Configure git author_email: ${{ github.actor }}@users.noreply.github.com
run: | message: 'Update Browserslist'
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'
+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 -19
View File
@@ -1,24 +1,6 @@
{ {
"editor.formatOnSave": true, "editor.formatOnSave": true,
"cSpell.blockCheckingWhenLineLengthGreaterThan": 150, "cSpell.words": ["asyncable", "KROKI", "mindmap", "pako", "Serde", "serdes", "tailwindcss"],
"cSpell.words": [
"asyncable",
"Browserslist",
"ckppp",
"corg",
"cssnano",
"daisyui",
"esserializer",
"KROKI",
"localstorage",
"mermaidchart",
"mindmap",
"pako",
"Serde",
"serdes",
"tailwindcss",
"uparrow"
],
"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:19.9.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
+1 -1
View File
@@ -1,4 +1,4 @@
FROM node:19 FROM node:18
WORKDIR /app WORKDIR /app
COPY package.json . COPY package.json .
COPY yarn.lock . COPY yarn.lock .
+6 -9
View File
@@ -47,20 +47,17 @@ Then open http://localhost:8000
## Setup ## 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 ```
yarn install
- [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`
## Development ## Development
```sh ```
yarn install
yarn dev -- --open yarn dev -- --open
``` ```
+3 -3
View File
@@ -6,10 +6,10 @@ export default defineConfig({
viewportWidth: 1440, viewportWidth: 1440,
viewportHeight: 768, viewportHeight: 768,
snapshotFileName: './cypress/snapshots.js', snapshotFileName: './cypress/snapshots.js',
defaultCommandTimeout: 5000, defaultCommandTimeout: 16000,
requestTimeout: 5000, requestTimeout: 16000,
retries: { retries: {
runMode: 2, runMode: 4,
openMode: 0 openMode: 0
}, },
e2e: { e2e: {
+7 -8
View File
@@ -1,16 +1,15 @@
import { typeInEditor, verifyFileSizeGreaterThan } from './util'; import { verifyFileSize } from './util';
describe('Check actions', () => { describe('Check actions', () => {
beforeEach(() => { beforeEach(() => {
cy.clearLocalStorage(); cy.clearLocalStorage();
cy.visit('/edit'); cy.visit('/edit');
cy.contains('Actions').click();
}); });
it('should update markdown code', () => { it('should update markdown code', () => {
cy.get('#markdown') cy.get('#markdown')
.invoke('val') .invoke('val')
.then((oldText) => { .then((oldText) => {
typeInEditor('C --> HistoryTest', { bottom: true, newline: true }); cy.get('#editor').click('bottom').type('{enter}C --> HistoryTest');
cy.get('#markdown') cy.get('#markdown')
.invoke('val') .invoke('val')
.then((newText) => { .then((newText) => {
@@ -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.get('#gist').type('https://gist.github.com/sidharthv96/6268a23e673a533dcb198f241fd7012a');
cy.contains('Load Gist').click(); cy.contains('Load Gist').click();
cy.contains('Go shopping!!'); cy.contains('Go shopping!!');
@@ -29,20 +28,20 @@ describe('Check actions', () => {
cy.clock(new Date(2022, 0, 1).getTime()); cy.clock(new Date(2022, 0, 1).getTime());
cy.get(`#downloadPNG`).click(); cy.get(`#downloadPNG`).click();
verifyFileSizeGreaterThan('diagram', 'png', 34_000); verifyFileSize('diagram', 'png', 21_000);
cy.get(`#downloadSVG`).click(); cy.get(`#downloadSVG`).click();
verifyFileSizeGreaterThan('diagram', 'svg', 10_000); verifyFileSize('diagram', 'svg', 10_000);
// Verify downloaded file is different for different diagrams // Verify downloaded file is different for different diagrams
cy.contains('Sample Diagrams').click(); cy.contains('Sample Diagrams').click();
cy.contains('ER').click(); cy.contains('ER').click();
cy.get(`#downloadPNG`).click(); cy.get(`#downloadPNG`).click();
verifyFileSizeGreaterThan('diagram', 'png', 40_000); verifyFileSize('diagram', 'png', 46_000);
cy.get(`#downloadSVG`).click(); cy.get(`#downloadSVG`).click();
verifyFileSizeGreaterThan('diagram', 'svg', 11_000); verifyFileSize('diagram', 'svg', 12_000);
cy.clock().invoke('restore'); cy.clock().invoke('restore');
}); });
+12 -14
View File
@@ -1,17 +1,16 @@
import { typeInEditor, cmd } from './util'; import { getEditor, cmd } from './util';
describe('Auto sync tests', () => { describe('Auto sync tests', () => {
beforeEach(() => { beforeEach(() => {
cy.clearLocalStorage(); cy.clearLocalStorage();
cy.visit('/'); cy.visit('/');
cy.url().should('contain', '/edit#pako');
}); });
it('should dim diagram when code is edited', () => { it('should dim diagram when code is edited', () => {
cy.contains('Auto sync').click(); cy.contains('Auto sync').click();
cy.get('#view').should('not.have.class', 'outOfSync'); cy.get('#view').should('not.have.class', 'outOfSync');
cy.get('#errorContainer').should('not.exist'); cy.get('#errorContainer').should('not.exist');
typeInEditor(' C --> Test', { bottom: true }); getEditor({ bottom: true, newline: true }).type(' C --> Test');
cy.get('#view').should('have.class', 'outOfSync'); cy.get('#view').should('have.class', 'outOfSync');
cy.get('#errorContainer').should('contain.text', 'Diagram out of sync.'); cy.get('#errorContainer').should('contain.text', 'Diagram out of sync.');
cy.getLocalStorage('codeStore').snapshot(); cy.getLocalStorage('codeStore').snapshot();
@@ -20,10 +19,10 @@ describe('Auto sync tests', () => {
it('should update diagram when shortcut is used', () => { it('should update diagram when shortcut is used', () => {
cy.contains('Auto sync').click(); cy.contains('Auto sync').click();
cy.get('#view').should('not.have.class', 'outOfSync'); cy.get('#view').should('not.have.class', 'outOfSync');
typeInEditor(' C --> Test'); getEditor().type(' C --> Test');
cy.get('#view').should('have.class', 'outOfSync'); cy.get('#view').should('have.class', 'outOfSync');
cy.get('#errorContainer').should('contain.text', 'Diagram out of sync.'); cy.get('#errorContainer').should('contain.text', 'Diagram out of sync.');
typeInEditor(`${cmd}{enter}`); getEditor().type(`${cmd}{enter}`);
cy.get('#errorContainer').should('not.exist'); cy.get('#errorContainer').should('not.exist');
cy.get('#view').should('not.have.class', 'outOfSync'); cy.get('#view').should('not.have.class', 'outOfSync');
}); });
@@ -39,22 +38,21 @@ describe('Auto sync tests', () => {
it('should not dim diagram when code is in sync', () => { it('should not dim diagram when code is in sync', () => {
cy.contains('Auto sync').click(); cy.contains('Auto sync').click();
cy.get('#view').should('not.have.class', 'outOfSync'); cy.get('#view').should('not.have.class', 'outOfSync');
typeInEditor(' C --> Test'); getEditor().type(' C --> Test');
cy.get('#view').should('have.class', 'outOfSync'); cy.get('#view').should('have.class', 'outOfSync');
cy.get('[data-cy=sync]').click(); cy.get('[data-cy=sync]').click();
cy.get('#view').should('not.have.class', 'outOfSync'); cy.get('#view').should('not.have.class', 'outOfSync');
cy.get('#autoSync').check(); cy.get('#autoSync').check();
typeInEditor('ing'); getEditor().type('ing');
cy.get('#view').should('not.have.class', 'outOfSync'); cy.get('#view').should('not.have.class', 'outOfSync');
cy.getLocalStorage('codeStore').snapshot(); cy.getLocalStorage('codeStore').snapshot();
}); });
it('supports commenting code out/in', () => { it('supports commenting code out/in', () => {
cy.get('#editor').contains('Car').click(); getEditor().type(`{uparrow}${cmd}/`);
cy.focused().type(`${cmd}/`);
cy.get('#view').contains('Car').should('not.exist'); cy.get('#view').contains('Car').should('not.exist');
typeInEditor(`{uparrow}${cmd}/`); getEditor().type(`{uparrow}${cmd}/`);
cy.get('#view').contains('Car').should('exist'); cy.get('#view').contains('Car').should('exist');
}); });
@@ -63,7 +61,7 @@ describe('Auto sync tests', () => {
'/edit#pako:eNpljjEKwzAMRa8SNOcEnlt6gK5eVFvYJsgOqkwpIXevg9smEE1PnyfxF3DFExgISW-CczQ2D21cYU7a-SGYXRwyvTp9jUhuKlVP-eHy7zA-leQsMEmg_QOM0BLG5FujZVMsaCQmC6ahR5ks2Lw2r84ela4-aREwKpVGwKrl_s7ut3fnkjAIcg_XDzuaUhs' '/edit#pako:eNpljjEKwzAMRa8SNOcEnlt6gK5eVFvYJsgOqkwpIXevg9smEE1PnyfxF3DFExgISW-CczQ2D21cYU7a-SGYXRwyvTp9jUhuKlVP-eHy7zA-leQsMEmg_QOM0BLG5FujZVMsaCQmC6ahR5ks2Lw2r84ela4-aREwKpVGwKrl_s7ut3fnkjAIcg_XDzuaUhs'
); );
cy.get('#errorContainer').should('not.exist'); cy.get('#errorContainer').should('not.exist');
typeInEditor(`branch test`, { bottom: true, newline: true }); getEditor({ newline: true }).type(`branch test`);
cy.get('#editor').contains('branch test').should('exist'); cy.get('#editor').contains('branch test').should('exist');
cy.get('#errorContainer') cy.get('#errorContainer')
.contains( .contains(
@@ -74,9 +72,9 @@ describe('Auto sync tests', () => {
it('should update diagram after entire text is removed', () => { it('should update diagram after entire text is removed', () => {
// https://github.com/mermaid-js/mermaid-live-editor/issues/1102 // https://github.com/mermaid-js/mermaid-live-editor/issues/1102
typeInEditor(`${cmd} a {backspace}`); getEditor().type(`${cmd} a {backspace}`);
typeInEditor('graph LR'); getEditor().type('graph LR');
typeInEditor(' {enter} A-->Car'); getEditor().type(' {enter} A-->Car');
cy.get('#view').contains('Car').should('exist'); cy.get('#view').contains('Car').should('exist');
}); });
}); });
+10 -8
View File
@@ -1,4 +1,4 @@
import { typeInEditor, verifyFileSnapshot } from './util'; import { getEditor, verifyFileSnapshot } from './util';
describe('Save History', () => { describe('Save History', () => {
beforeEach(() => { beforeEach(() => {
@@ -6,6 +6,7 @@ describe('Save History', () => {
cy.clearLocalStorage(); cy.clearLocalStorage();
cy.visit('/edit'); cy.visit('/edit');
cy.contains('Actions').click();
cy.contains('History').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"}]' '[{"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.reload();
cy.contains('Actions').click();
cy.contains('History').click(); cy.contains('History').click();
cy.get('#historyList').find('li').should('have.length', 2); cy.get('#historyList').find('li').should('have.length', 2);
cy.get('#historyList').find('No items in History').should('not.exist'); cy.get('#historyList').find('No items in History').should('not.exist');
@@ -51,14 +53,14 @@ describe('Save History', () => {
expect(str).to.equal('State already saved.'); expect(str).to.equal('State already saved.');
}); });
cy.on('window:confirm', () => true); cy.on('window:confirm', () => true);
typeInEditor(' C --> HistoryTest'); getEditor().type(' C --> HistoryTest');
cy.get('#saveHistory').click(); cy.get('#saveHistory').click();
cy.get('#historyList').find('li').should('have.length', 2); cy.get('#historyList').find('li').should('have.length', 2);
}); });
it('should be able to restore and delete', () => { it('should be able to restore and delete', () => {
cy.get('#saveHistory').click(); cy.get('#saveHistory').click();
typeInEditor(' C --> HistoryTest'); getEditor().type(' C --> HistoryTest');
cy.get('#historyList').find('No items in History').should('not.exist'); cy.get('#historyList').find('No items in History').should('not.exist');
cy.get('#historyList').find('li').should('have.length', 1); cy.get('#historyList').find('li').should('have.length', 1);
cy.contains('HistoryTest'); cy.contains('HistoryTest');
@@ -68,7 +70,7 @@ describe('Save History', () => {
cy.get('#historyList').find('li').should('have.length', 0); cy.get('#historyList').find('li').should('have.length', 0);
cy.get('#historyList').contains('No items in History'); cy.get('#historyList').contains('No items in History');
cy.get('#saveHistory').click(); cy.get('#saveHistory').click();
typeInEditor(' C --> HistoryTest'); getEditor().type(' C --> HistoryTest');
cy.get('#saveHistory').click(); cy.get('#saveHistory').click();
cy.get('#editor').type('ing'); cy.get('#editor').type('ing');
cy.get('#clearHistory').click(); cy.get('#clearHistory').click();
@@ -81,16 +83,16 @@ describe('Save History', () => {
// TODO: Fix #639 // TODO: Fix #639
xit('should auto save history', () => { xit('should auto save history', () => {
typeInEditor(' C --> HistoryTest'); getEditor().type(' C --> HistoryTest');
cy.tick(70_000); cy.tick(70000);
cy.contains('Timeline').click(); cy.contains('Timeline').click();
cy.get('#historyList').find('li').should('have.length', 1); cy.get('#historyList').find('li').should('have.length', 1);
cy.get('#editor').type('ing'); cy.get('#editor').type('ing');
cy.tick(70_000); cy.tick(70000);
cy.get('#historyList').find('li').should('have.length', 2); cy.get('#historyList').find('li').should('have.length', 2);
for (let i = 0; i < 31; i++) { for (let i = 0; i < 31; i++) {
cy.get('#editor').type('.'); cy.get('#editor').type('.');
cy.tick(70_000); cy.tick(70000);
} }
cy.get('#historyList').find('li').should('have.length', 30); cy.get('#historyList').find('li').should('have.length', 30);
}); });
+15 -23
View File
@@ -4,7 +4,6 @@ describe('Site Loads', () => {
beforeEach(() => { beforeEach(() => {
cy.clearLocalStorage(); cy.clearLocalStorage();
cy.visit('/'); cy.visit('/');
cy.url().should('include', '/edit#pako');
}); });
it('Check Home page load', () => { it('Check Home page load', () => {
@@ -94,9 +93,22 @@ describe('Site Loads', () => {
cy.reload(true); cy.reload(true);
cy.contains('Please Click here to Raise an issue in github.'); cy.contains('Please Click here to Raise an issue in github.');
}); });
});
describe('Verify types of URLs', () => { 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', () => { it('should load compressed URL', () => {
cy.visit( cy.visit(
'/edit#pako:eNpVkM2KwkAQhF-l6dMK5gVyEDRxvYi7sF6WjIcm0zqDzg_jBJEk725Hd2G3Tw31VVFUj23QjCWeEkUD-1p5kFs2O77BN1M6QFEshg1ncMHzfYDV2ybA1YQYrT_NXvhqgqDqtxPGkI315_ElVU__h-cB6mZLMYd4-Kvsb2GAdWM_jcT_V0xicb03RyqPVLSUoJI-OEfHyZHV0rqfDAqzYccKS3k1pbNC5Ufhuqgp81rbHBJKxuXKc6Quh6-7b7HMqeNfqLYkC7gfanwAlW1ZvQ' '/edit#pako:eNpVkM2KwkAQhF-l6dMK5gVyEDRxvYi7sF6WjIcm0zqDzg_jBJEk725Hd2G3Tw31VVFUj23QjCWeEkUD-1p5kFs2O77BN1M6QFEshg1ncMHzfYDV2ybA1YQYrT_NXvhqgqDqtxPGkI315_ElVU__h-cB6mZLMYd4-Kvsb2GAdWM_jcT_V0xicb03RyqPVLSUoJI-OEfHyZHV0rqfDAqzYccKS3k1pbNC5Ufhuqgp81rbHBJKxuXKc6Quh6-7b7HMqeNfqLYkC7gfanwAlW1ZvQ'
@@ -107,24 +119,4 @@ describe('Verify types of URLs', () => {
); );
cy.contains('Animal'); cy.contains('Animal');
}); });
describe('Uncompressed URLs', () => {
it('should load URL without specifier', () => {
cy.visit(
'/edit/#eyJjb2RlIjoiZ3JhcGhcbiAgICBUZXN0TGFiZWwiLCJtZXJtYWlkIjoie1xuICBcInRoZW1lXCI6IFwiZGVmYXVsdFwiXG59IiwidXBkYXRlRWRpdG9yIjpmYWxzZSwiYXV0b1N5bmMiOnRydWUsInVwZGF0ZURpYWdyYW0iOmZhbHNlfQ'
);
cy.contains('TestLabel');
cy.visit(
'/edit#eyJjb2RlIjoiY2xhc3NEaWFncmFtXG4gICAgQW5pbWFsIDx8LS0gRHVja1xuICAgIEFuaW1hbCA8fC0tIEZpc2hcbiAgICBBbmltYWwgPHwtLSBaZWJyYVxuICAgIEFuaW1hbCA6ICtpbnQgYWdlXG4gICAgQW5pbWFsIDogK1N0cmluZyBnZW5kZXJcbiAgICBBbmltYWw6ICtpc01hbW1hbCgpXG4gICAgQW5pbWFsOiArbWF0ZSgpXG4gICAgY2xhc3MgRHVja3tcbiAgICAgICtTdHJpbmcgYmVha0NvbG9yXG4gICAgICArc3dpbSgpXG4gICAgICArcXVhY2soKVxuICAgIH1cbiAgICBjbGFzcyBGaXNoe1xuICAgICAgLWludCBzaXplSW5GZWV0XG4gICAgICAtY2FuRWF0KClcbiAgICB9XG4gICAgY2xhc3MgWmVicmF7XG4gICAgICArYm9vbCBpc193aWxkXG4gICAgICArcnVuKClcbiAgICB9XG4gICAgICAgICAgICAiLCJtZXJtYWlkIjoie1xuICBcInRoZW1lXCI6IFwiZGFya1wiXG59IiwidXBkYXRlRWRpdG9yIjpmYWxzZSwiYXV0b1N5bmMiOnRydWUsInVwZGF0ZURpYWdyYW0iOmZhbHNlfQ'
);
cy.contains('Animal');
});
it('should load URL with "base64" specifier', () => {
cy.visit(
'/edit/#base64:eyJjb2RlIjoiZ3JhcGhcbiAgICBUZXN0TGFiZWwiLCJtZXJtYWlkIjoie1xuICBcInRoZW1lXCI6IFwiZGVmYXVsdFwiXG59IiwidXBkYXRlRWRpdG9yIjpmYWxzZSwiYXV0b1N5bmMiOnRydWUsInVwZGF0ZURpYWdyYW0iOmZhbHNlfQ'
);
cy.contains('TestLabel');
});
});
}); });
+11 -25
View File
@@ -1,27 +1,16 @@
export const cmd = `{${Cypress.platform === 'darwin' ? 'meta' : 'ctrl'}}`; export const cmd = `{${Cypress.platform === 'darwin' ? 'meta' : 'ctrl'}}`;
interface EditorOptions { export const getEditor = ({ bottom = true, newline = false } = {}) =>
bottom?: boolean; cy
newline?: boolean; .get('#editor textarea:first')
} .click()
.focused()
export const typeInEditor = ( .type(`${bottom ? '{pageDown}' : cmd}`)
text: string, .type(`${newline ? '{enter}' : cmd}`);
{ bottom = true, newline = false }: EditorOptions = {}
) => {
cy.get('#editor').click();
if (bottom) {
cy.focused().type('{pageDown}');
}
if (newline) {
cy.focused().type('{enter}');
}
cy.focused().type(text);
};
const downloadsFolder = Cypress.config('downloadsFolder'); const downloadsFolder = Cypress.config('downloadsFolder');
export const verifyFileSizeGreaterThan = ( export const verifyFileSize = (
fileType: 'history' | 'diagram', fileType: 'history' | 'diagram',
extension: string, extension: string,
size: number size: number
@@ -32,10 +21,7 @@ export const verifyFileSizeGreaterThan = (
cy.verifyDownload(fileName); cy.verifyDownload(fileName);
cy.readFile(filePath, null, { cy.readFile(filePath, null, {
log: false log: false
}).then((buffer: ArrayBuffer) => { }).then((buffer) => expect((buffer as ArrayBuffer).byteLength).to.be.gt(size));
expect(buffer.byteLength).to.be.gt(size);
expect(buffer.byteLength).to.be.lt(size * 1.3);
});
cy.task('deleteFile', filePath); cy.task('deleteFile', filePath);
}; };
@@ -50,8 +36,8 @@ export const verifyFileSnapshot = (
cy.verifyDownload(fileName); cy.verifyDownload(fileName);
cy.readFile(filePath, null, { cy.readFile(filePath, null, {
log: false log: false
}).then((buffer: ArrayBuffer) => }).then((buffer) =>
expect(new TextDecoder('utf8').decode(buffer)).to.contain(content) expect(new TextDecoder('utf-8').decode(buffer as ArrayBuffer)).to.contain(content)
); );
cy.task('deleteFile', filePath); cy.task('deleteFile', filePath);
}; };
+4 -4
View File
@@ -1,7 +1,7 @@
module.exports = { module.exports = {
"Site Loads": { "Site Loads": {
"Check Home page load": { "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": { "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}" "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}"
@@ -16,13 +16,13 @@ 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": "12.9.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\":\"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": { "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": { "Test themes": {
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"compilerOptions": { "compilerOptions": {
"allowJs": true, "allowJs": true,
"types": ["cypress", "cypress-localstorage-commands", "cy-verify-downloads", "node"] "types": ["cypress", "cypress-localstorage-commands", "cy-verify-downloads"]
}, },
"include": ["**/*.ts"] "include": ["**/*.ts"]
} }
+43 -41
View File
@@ -19,65 +19,67 @@
"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": "2.0.2", "@playwright/test": "^1.28.1",
"@sveltejs/kit": "1.15.7", "@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": "9.0.1", "@types/uuid": "8.3.4",
"@typescript-eslint/eslint-plugin": "5.58.0", "@typescript-eslint/eslint-plugin": "5.44.0",
"@typescript-eslint/parser": "5.58.0", "@typescript-eslint/parser": "5.44.0",
"@vitest/ui": "^0.30.1", "@vitest/ui": "^0.25.3",
"autoprefixer": "^10.4.14", "autoprefixer": "^10.4.13",
"c8": "7.13.0", "c8": "7.12.0",
"chai": "^4.3.7", "chai": "^4.3.7",
"cssnano": "^6.0.0", "cssnano": "^5.1.14",
"cy-verify-downloads": "0.1.14", "cy-verify-downloads": "0.1.11",
"cypress": "12.9.0", "cypress": "11.2.0",
"cypress-localstorage-commands": "2.2.3", "cypress-localstorage-commands": "2.2.1",
"eslint": "8.38.0", "eslint": "8.28.0",
"eslint-config-prettier": "8.8.0", "eslint-config-prettier": "8.5.0",
"eslint-plugin-cypress": "2.13.2", "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-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.11.0", "eslint-plugin-tailwindcss": "3.7.0",
"eslint-plugin-unicorn": "^46.0.0", "eslint-plugin-vitest": "^0.0.20",
"eslint-plugin-vitest": "^0.1.4", "esserializer": "1.3.5",
"esserializer": "1.3.10",
"font-awesome": "^4.7.0", "font-awesome": "^4.7.0",
"husky": "^8.0.3", "husky": "^8.0.2",
"jsdom": "21.1.1", "jsdom": "20.0.3",
"lint-staged": "13.2.1", "lint-staged": "13.0.3",
"node-html-parser": "^6.1.5", "node-html-parser": "^6.1.4",
"postcss": "^8.4.21", "postcss": "^8.4.19",
"postcss-load-config": "4.0.1", "postcss-load-config": "4.0.1",
"prettier": "2.8.7", "prettier": "2.8.0",
"prettier-plugin-svelte": "^2.10.0", "prettier-plugin-svelte": "^2.8.1",
"svelte": "3.58.0", "svelte": "3.53.1",
"svelte-preprocess": "5.0.3", "svelte-preprocess": "4.10.7",
"tailwindcss": "^3.3.1", "tailwindcss": "^3.2.4",
"tslib": "^2.5.0", "tslib": "^2.4.1",
"typescript": "5.0.4", "typescript": "4.9.3",
"vite": "^4.2.1", "vite": "^3.2.4",
"vitest": "^0.30.1" "vitest": "^0.25.3"
}, },
"dependencies": { "dependencies": {
"@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.51.5", "daisyui": "2.42.1",
"dayjs": "^1.11.7", "js-base64": "3.7.3",
"js-base64": "3.7.5", "mermaid": "9.2.2",
"mermaid": "10.1.0", "moment": "2.29.4",
"monaco-editor": "0.37.1", "monaco-editor": "0.34.1",
"monaco-mermaid": "1.0.8", "monaco-mermaid": "1.0.8",
"pako": "2.1.0", "pako": "2.1.0",
"random-word-slugs": "0.1.7", "random-word-slugs": "0.1.6",
"svg-pan-zoom": "3.6.1", "svg-pan-zoom": "3.6.1",
"uuid": "9.0.0" "uuid": "9.0.0"
}, },
@@ -88,7 +90,7 @@
] ]
}, },
"volta": { "volta": {
"node": "18.16.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;
+13 -16
View File
@@ -17,14 +17,14 @@
<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.4.0/css/all.min.css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w=="
crossorigin="anonymous" crossorigin="anonymous"
referrerpolicy="no-referrer" /> referrerpolicy="no-referrer" />
<link <link
rel="stylesheet" rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.37.1/min/vs/editor/editor.main.min.css" href="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.1/min/vs/editor/editor.main.min.css"
integrity="sha512-wB3xfL98hWg1bpkVYSyL0js/Jx9s7FsDg9aYO6nOMSJTgPuk/PFqxXQJKKSUjteZjeYrfgo9NFBOA1r9HwDuZw==" integrity="sha512-GzcoZD7y5zvBofYtImXPZaPVhoY7xLPt+ysmbPb/vU+quSKFkcngxaSrxuwprDZL4MALUqGFmnqCxQZqMozv1Q=="
crossorigin="anonymous" crossorigin="anonymous"
referrerpolicy="no-referrer" /> referrerpolicy="no-referrer" />
<script> <script>
@@ -35,23 +35,20 @@
}; };
</script> </script>
<script <script
src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.37.1/min/vs/loader.min.js" src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.1/min/vs/loader.min.js"
integrity="sha512-A+6SvPGkIN9Rf0mUXmW4xh7rDvALXf/f0VtOUiHlDUSPknu2kcfz1KzLpOJyL2pO+nZS13hhIjLqVgiQExLJrw==" integrity="sha512-6bIYsGqvLpAiEBXPdRQeFf5cueeBECtAKJjIHer3BhBZNTV3WLcLA8Tm3pDfxUwTMIS+kAZwTUvJ1IrMdX8C5w=="
crossorigin="anonymous" crossorigin="anonymous"
referrerpolicy="no-referrer" referrerpolicy="no-referrer"></script>
async></script>
<script <script
src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.37.1/min/vs/editor/editor.main.nls.min.js" src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.1/min/vs/editor/editor.main.nls.min.js"
integrity="sha512-rWneFgUi2AyxOdM2M4CqPQVSJOidtmUflUfKroRoxsX3qaQrXAZ17fiPXASJo12ta0RUO+lgQtRbEbRFaClJ6g==" integrity="sha512-CCv+DKWw+yZhxf4Z+ExT6HC5G+3S45TeMTYcJyYbdrv4BpK2vyALJ4FoVR/KGWDIPu7w4tNCOC9MJQIkYPR5FA=="
crossorigin="anonymous" crossorigin="anonymous"
referrerpolicy="no-referrer" referrerpolicy="no-referrer"></script>
async></script>
<script <script
src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.37.1/min/vs/editor/editor.main.js" src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.1/min/vs/editor/editor.main.js"
integrity="sha512-y99DgzNm8N3flFl0hvmTFfWVtj6prXGxll7PUbNc51mKGFiyWqTBqBFr06N8k7mLKp7LqvitwaIz8sJOfdHM4A==" integrity="sha512-BtSZPhzoyN8kq1axY6cgOFPSgLJgFwvAZ3WxeDGxEFXeFcFuK2s7Hr+zF75npVHASUY1dxudAfIVzwmgdR89Bw=="
crossorigin="anonymous" crossorigin="anonymous"
referrerpolicy="no-referrer" referrerpolicy="no-referrer"></script>
async></script>
%sveltekit.head% %sveltekit.head%
</head> </head>
<body> <body>
+3 -3
View File
@@ -6,13 +6,13 @@
import { stateStore } from '$lib/util/state'; import { stateStore } from '$lib/util/state';
import { logEvent } from '$lib/util/stats'; import { logEvent } from '$lib/util/stats';
import { toBase64 } from 'js-base64'; import { toBase64 } from 'js-base64';
import dayjs from 'dayjs'; import moment from 'moment';
const { krokiRendererUrl, rendererUrl } = env; const { krokiRendererUrl, rendererUrl } = env;
type Exporter = (context: CanvasRenderingContext2D, image: HTMLImageElement) => () => void; type Exporter = (context: CanvasRenderingContext2D, image: HTMLImageElement) => () => void;
const getFileName = (ext: string) => 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 => { const getBase64SVG = (svg?: HTMLElement, width?: number, height?: number): string => {
height && svg?.setAttribute('height', `${height}px`); height && svg?.setAttribute('height', `${height}px`);
@@ -180,7 +180,7 @@
}); });
</script> </script>
<Card title="Actions" isOpen={false}> <Card title="Actions" isOpen={true}>
<div class="flex flex-wrap gap-2 m-2"> <div class="flex flex-wrap gap-2 m-2">
{#if isClipboardAvailable()} {#if isClipboardAvailable()}
<button class="action-btn w-full" on:click={onCopyClipboard} <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('title1');
expect(container).toHaveTextContent('title2'); expect(container).toHaveTextContent('title2');
expect(container).not.toHaveTextContent('title3'); expect(container).not.toHaveTextContent('title3');
expect(container.innerHTML).toMatchSnapshot();
}); });
}); });
+6 -6
View File
@@ -21,7 +21,7 @@
let text = ''; let text = '';
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 || !Monaco) { if (!editor || !Monaco) {
return; return;
} }
@@ -29,7 +29,7 @@
// 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;
if (newText !== text) { if (newText !== text) {
// console.log('updating editor text', newText); console.log('updating editor text', newText);
editor.setValue(newText); editor.setValue(newText);
text = newText; text = newText;
} }
@@ -54,7 +54,7 @@
}); });
const handleUpdate = (text: string, mode: EditorMode) => { const handleUpdate = (text: string, mode: EditorMode) => {
// console.log('editor HandleUpdate', { text, mode }); console.log('editor HandleUpdate', { text, mode });
if (mode === 'code') { if (mode === 'code') {
updateCode(text); updateCode(text);
} else { } else {
@@ -91,7 +91,7 @@
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 (!newText || text === newText || isFlush) { if (!newText || text === newText || isFlush) {
return; return;
} }
@@ -120,9 +120,9 @@
if (divEl.parentElement) { if (divEl.parentElement) {
resizeObserver.observe(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();
}; };
}); });
+3 -6
View File
@@ -13,13 +13,10 @@
import { notify, prompt } from '$lib/util/notify'; import { notify, prompt } from '$lib/util/notify';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import { get } from 'svelte/store'; import { get } from 'svelte/store';
import dayjs from 'dayjs'; import moment from 'moment';
import dayjsRelativeTime from 'dayjs/plugin/relativeTime';
import type { HistoryEntry, 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';
dayjs.extend(dayjsRelativeTime);
const HISTORY_SAVE_INTERVAL = 60000; const HISTORY_SAVE_INTERVAL = 60000;
const tabSelectHandler = (message: CustomEvent<Tab>) => { const tabSelectHandler = (message: CustomEvent<Tab>) => {
@@ -44,7 +41,7 @@
const url = URL.createObjectURL(blob); const url = URL.createObjectURL(blob);
const a = document.createElement('a'); const a = document.createElement('a');
a.href = url; 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(); a.click();
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
logEvent('history', { logEvent('history', {
@@ -98,7 +95,7 @@
const relativeTime = (time: number) => { const relativeTime = (time: number) => {
const t = new Date(time); const t = new Date(time);
return `${new Date(t).toLocaleString()} (${dayjs(t).fromNow()})`; return `${new Date(t).toLocaleString()} (${moment(t).fromNow()})`;
}; };
onMount(() => { onMount(() => {
+8 -8
View File
@@ -17,7 +17,7 @@ describe('history', () => {
addHistoryEntry({ addHistoryEntry({
state: defaultState, state: defaultState,
time: 12_345, time: 12345,
type: 'manual' type: 'manual'
}); });
@@ -25,14 +25,14 @@ describe('history', () => {
window.localStorage.getItem('manualHistoryStore') ?? '[]' window.localStorage.getItem('manualHistoryStore') ?? '[]'
) as HistoryEntry[]; ) as HistoryEntry[];
expect(manualEntry.time).toBe(12_345); expect(manualEntry.time).toBe(12345);
expect(manualEntry.type).toBe('manual'); expect(manualEntry.type).toBe('manual');
expect(manualEntry.name).not.toBeNull(); expect(manualEntry.name).not.toBeNull();
expect(manualEntry.state).not.toBeNull(); expect(manualEntry.state).not.toBeNull();
addHistoryEntry({ addHistoryEntry({
state: defaultState, state: defaultState,
time: 54_321, time: 54321,
type: 'auto' type: 'auto'
}); });
@@ -40,7 +40,7 @@ describe('history', () => {
window.localStorage.getItem('autoHistoryStore') ?? '[]' window.localStorage.getItem('autoHistoryStore') ?? '[]'
) as HistoryEntry[]; ) as HistoryEntry[];
expect(autoEntry.time).toBe(54_321); expect(autoEntry.time).toBe(54321);
expect(autoEntry.type).toBe('auto'); expect(autoEntry.type).toBe('auto');
expect(autoEntry.name).not.toBeNull(); expect(autoEntry.name).not.toBeNull();
expect(autoEntry.state).not.toBeNull(); expect(autoEntry.state).not.toBeNull();
@@ -56,12 +56,12 @@ describe('history', () => {
it('should clear history entries', () => { it('should clear history entries', () => {
addHistoryEntry({ addHistoryEntry({
state: defaultState, state: defaultState,
time: 12_345, time: 12345,
type: 'manual' type: 'manual'
}); });
addHistoryEntry({ addHistoryEntry({
state: { ...defaultState, code: 'graph TD\\n A[Christmas] -->|Get money| B(Go shopping)' }, state: { ...defaultState, code: 'graph TD\\n A[Christmas] -->|Get money| B(Go shopping)' },
time: 123_456, time: 123456,
type: 'manual' type: 'manual'
}); });
@@ -76,12 +76,12 @@ describe('history', () => {
historyModeStore.set('auto'); historyModeStore.set('auto');
addHistoryEntry({ addHistoryEntry({
state: defaultState, state: defaultState,
time: 54_321, time: 54321,
type: 'auto' type: 'auto'
}); });
addHistoryEntry({ addHistoryEntry({
state: { ...defaultState, code: 'graph TD\\n A[Christmas] -->|Get money| B(Go shopping)' }, state: { ...defaultState, code: 'graph TD\\n A[Christmas] -->|Get money| B(Go shopping)' },
time: 654_321, time: 654321,
type: 'auto' type: 'auto'
}); });
expect(get(historyStore).length).toBe(2); expect(get(historyStore).length).toBe(2);
+18 -29
View File
@@ -26,27 +26,19 @@ const manualHistoryStore: Writable<HistoryEntry[]> = persist(
'manualHistoryStore' 'manualHistoryStore'
); );
export const loaderHistoryStore: Writable<HistoryEntry[]> = writable([]); export const loaderHistoryStore: Writable<HistoryEntry[]> = writable([] as HistoryEntry[]);
export const historyStore: Readable<HistoryEntry[]> = derived( export const historyStore: Readable<HistoryEntry[]> = derived(
[historyModeStore, autoHistoryStore, manualHistoryStore, loaderHistoryStore], [historyModeStore, autoHistoryStore, manualHistoryStore, loaderHistoryStore],
([historyMode, autoHistories, manualHistories, loadedHistories], set) => { ([historyMode, autoHistories, manualHistories, loadedHistories], set) => {
switch (historyMode) { if (historyMode === 'auto') {
case 'auto': { set(autoHistories);
set(autoHistories); } else if (historyMode === 'manual') {
break; set(manualHistories);
} } else if (historyMode === 'loader') {
case 'manual': { set(loadedHistories);
set(manualHistories); } else {
break; set(autoHistories);
}
case 'loader': {
set(loadedHistories);
break;
}
default: {
set(autoHistories);
}
} }
} }
); );
@@ -98,7 +90,7 @@ export const getPreviousState = (auto: boolean): string => {
}; };
export const restoreHistory = (data: HistoryEntry[]) => { export const restoreHistory = (data: HistoryEntry[]) => {
const entries = data.filter((element) => validateEntry(element)); const entries = data.filter(validateEntry);
const invalidEntryCount = data.length - entries.length; const invalidEntryCount = data.length - entries.length;
if (invalidEntryCount > 0) { if (invalidEntryCount > 0) {
console.error(`${invalidEntryCount} invalid history entries were removed.`); console.error(`${invalidEntryCount} invalid history entries were removed.`);
@@ -130,23 +122,20 @@ export const restoreHistory = (data: HistoryEntry[]) => {
alert('No valid entries found.'); 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 => { export const injectHistoryIDs = (): void => {
const setIDs = (entries: HistoryEntry[]) => {
for (const entry of entries) {
if (!entry.id) {
entry.id = uuidV4();
}
}
return entries;
};
autoHistoryStore.update(setIDs); autoHistoryStore.update(setIDs);
manualHistoryStore.update(setIDs); manualHistoryStore.update(setIDs);
}; };
const validateEntry = (entry: HistoryEntry): boolean => { 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; return entry.type && entry.state && entry.time && true;
}; };
+6 -20
View File
@@ -10,19 +10,18 @@
import Theme from './Theme.svelte'; import Theme from './Theme.svelte';
interface Link { interface Link {
title: string;
href: string; href: string;
title?: string;
icon?: string; icon?: string;
img?: string;
} }
const links: Link[] = [ const links: Link[] = [
{ {
title: 'Documentation', title: 'Documentation',
href: 'https://mermaid-js.github.io/mermaid/intro/n00b-gettingStarted.html' href: 'https://mermaid-js.github.io/mermaid/#/n00b-gettingStarted'
}, },
{ {
title: 'Tutorial', 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', title: 'Mermaid',
@@ -33,12 +32,9 @@
href: 'https://github.com/mermaid-js/mermaid-cli' href: 'https://github.com/mermaid-js/mermaid-cli'
}, },
{ {
title: '',
href: 'https://github.com/mermaid-js/mermaid-live-editor', href: 'https://github.com/mermaid-js/mermaid-live-editor',
icon: 'fab fa-github fa-lg' icon: 'fab fa-github fa-lg'
},
{
href: 'https://mermaidchart.com',
img: '/mermaidchart-logo.svg'
} }
]; ];
</script> </script>
@@ -63,18 +59,13 @@
<Theme /> <Theme />
<div class="hidden lg:flex lg:items-center lg:w-auto w-full" id="menu"> <div class="hidden lg:flex lg:items-center lg:w-auto w-full" id="menu">
<ul class="lg:flex items-center justify-between text-base pt-4 lg:pt-0"> <ul class="lg:flex items-center justify-between text-base pt-4 lg:pt-0">
{#each links as { title, href, icon, img }} {#each links as { title, href, icon }}
<li> <li>
<a class="btn btn-ghost" target="_blank" rel="noreferrer" {href}> <a class="btn btn-ghost" target="_blank" rel="noreferrer" {href}>
{#if icon} {#if icon}
<i class={icon} /> <i class={icon} />
{:else if img}
<img src={img} alt={title} />
{/if} {/if}
{#if title} {title}</a>
{title}
{/if}
</a>
</li> </li>
{/each} {/each}
</ul> </ul>
@@ -88,9 +79,4 @@
.navbar { .navbar {
z-index: 10000; z-index: 10000;
} }
img {
width: 1.5rem;
height: 1.5rem;
}
</style> </style>
+1 -1
View File
@@ -4,7 +4,7 @@
import { logEvent } from '$lib/util/stats'; import { logEvent } from '$lib/util/stats';
const samples = { const samples = {
Flow: `flowchart TD Flow: `graph TD
A[Christmas] -->|Get money| B(Go shopping) A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think} B --> C{Let me think}
C -->|One| D[Laptop] C -->|One| D[Laptop]
+20 -20
View File
@@ -79,27 +79,27 @@
panZoomEnabled = state.panZoom; panZoomEnabled = state.panZoom;
const scroll = view.parentElement!.scrollTop; const scroll = view.parentElement!.scrollTop;
delete container.dataset.processed; delete container.dataset.processed;
const { svg, bindFunctions } = await renderDiagram( await renderDiagram(
Object.assign({}, JSON.parse(state.mermaid)) as MermaidConfig, Object.assign({}, JSON.parse(state.mermaid)) as MermaidConfig,
code, 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; view.parentElement!.scrollTop = scroll;
error = false; error = false;
} else if (manualUpdate) { } else if (manualUpdate) {
@@ -122,7 +122,7 @@
pzoom.resize(); pzoom.resize();
} }
}); });
// console.log('View mounted'); console.log('View mounted');
}); });
</script> </script>
@@ -133,7 +133,7 @@
: '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}
{@html $stateStore.error?.toString().replace(/\n/g, '<br />')} {@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 -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, string,
{ {
code: string; code: string;
+8 -9
View File
@@ -5,7 +5,6 @@
import type { State } from '$lib/types'; import type { State } from '$lib/types';
import { defaultState } from '$lib/util/state'; import { defaultState } from '$lib/util/state';
import { addHistoryEntry } from '$lib/components/History/history'; import { addHistoryEntry } from '$lib/components/History/history';
import { fetchJSON, fetchText } from '$lib/util/util';
const codeFileName = 'code.mmd'; const codeFileName = 'code.mmd';
const configFileName = 'config.json'; const configFileName = 'config.json';
@@ -22,7 +21,7 @@ const isValidGist = (files: any): boolean => {
const getFileContent = async (file: GithubFile): Promise<string> => { const getFileContent = async (file: GithubFile): Promise<string> => {
if (file.truncated) { if (file.truncated) {
return await fetchText(file.raw_url); return await (await fetch(file.raw_url)).text();
} }
return file.content; return file.content;
}; };
@@ -50,9 +49,9 @@ const getGistData = async (gistURL: string): Promise<GistData> => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_, __, gistID, revisionID] = path.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 }: GistResponse = await fetchJSON( const { html_url, files, history }: GistResponse = await (
`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}` await fetch(`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`)
); ).json();
if (isValidGist(files)) { if (isValidGist(files)) {
const code = await getFileContent(files[codeFileName]); const code = await getFileContent(files[codeFileName]);
let config = '{}'; let config = '{}';
@@ -97,12 +96,12 @@ export const loadGistData = async (gistURL: string): Promise<State> => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_, __, gistID, revisionID] = path.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 { history }: GistResponse = await fetchJSON( const { history }: GistResponse = await (
`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}` await fetch(`https://api.github.com/gists/${gistID}${revisionID ? '/' + revisionID : ''}`)
); ).json();
const gistHistory: GistData[] = []; const gistHistory: GistData[] = [];
for (const entry of history) { 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); data && gistHistory.push(data);
} }
if (gistHistory.length === 0) { if (gistHistory.length === 0) {
+22 -20
View File
@@ -1,8 +1,6 @@
import { loadGistData } from './gist'; import { loadGistData } from './gist';
import { updateCodeStore, defaultState } from '$lib/util/state'; import { updateCodeStore, defaultState } from '../state';
import { fetchText } from '$lib/util/util';
import type { Loader, State } from '$lib/types'; import type { Loader, State } from '$lib/types';
const loaders: Record<string, Loader> = { const loaders: Record<string, Loader> = {
gist: loadGistData gist: loadGistData
}; };
@@ -10,18 +8,34 @@ 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 | undefined = undefined;
let config: string | undefined = undefined;
let loaded = false; let loaded = false;
const codeURL: string | undefined = searchParams.get('code') ?? undefined; const codeURL: string | undefined = searchParams.get('code') ?? undefined;
const configURL: string | undefined = searchParams.get('config') ?? undefined; const configURL: string | undefined = searchParams.get('config') ?? undefined;
let code: string | undefined;
const config = configURL ? await fetchText(configURL) : defaultState.mermaid;
if (codeURL) { if (codeURL) {
code = await fetchText(codeURL); code = await (await fetch(codeURL)).text();
loaded = true; 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) { if (!codeURL) {
throw new Error('Code URL is not defined'); 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 && loaded &&
updateCodeStore({ updateCodeStore({
+18 -7
View File
@@ -1,16 +1,27 @@
import mermaid from 'mermaid'; import mermaid, { type MermaidConfig } from 'mermaid';
import type { MermaidConfig, RenderResult } from 'mermaid'; import mindmap from '@mermaid-js/mermaid-mindmap';
const initialize = mermaid.registerExternalDiagrams([mindmap]);
export const init = async () => {
await initialize;
};
export const render = async ( export const render = async (
config: MermaidConfig, config: MermaidConfig,
code: string, code: string,
id: string id: string,
): Promise<RenderResult> => { callback: Parameters<typeof mermaid.render>[2]
): Promise<void> => {
// Should be able to call this multiple times without any issues. // Should be able to call this multiple times without any issues.
mermaid.initialize(config); 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> => { export const parse = async (code: string): Promise<boolean> => {
return await mermaid.parse(code); 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) { if (value !== null && value !== undefined) {
try { try {
return ESSerializer.deserialize(value); return ESSerializer.deserialize(value);
} catch { } catch (e) {
// Do nothing // Do nothing
// use the value "as is" // use the value "as is"
} }
try { try {
return JSON.parse(value); return JSON.parse(value);
} catch { } catch (e) {
// Do nothing // Do nothing
// use the value "as is" // use the value "as is"
} }
@@ -179,9 +179,11 @@ function getBrowserStorage(
const listenerFunction = (event: StorageEvent) => { const listenerFunction = (event: StorageEvent) => {
const eventKey = event.key; const eventKey = event.key;
if (event.storageArea === browserStorage) { if (event.storageArea === browserStorage) {
for (const { listener } of listeners.filter(({ key }) => key === eventKey)) { listeners
listener(deserialize(event.newValue)); .filter(({ key }) => key === eventKey)
} .forEach(({ listener }) => {
listener(deserialize(event.newValue));
});
} }
}; };
const connect = () => { const connect = () => {
+10 -10
View File
@@ -3,29 +3,29 @@ import { serializeState, deserializeState, type SerdeType } from './serde';
import { defaultState } from './state'; import { defaultState } from './state';
import type { State } from '$lib/types'; 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', () => { 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', () => { it('should serialize and deserialize with default serde', () => {
expect(verifySerde(defaultState)).toMatchInlineSnapshot( 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', () => { it('should serialize and deserialize with base64 serde', () => {
expect(verifySerde(defaultState, 'base64')).toMatchInlineSnapshot( expect(verifySerde(defaultState, 'base64')).toMatchInlineSnapshot(
'"base64:eyJjb2RlIjoiZmxvd2NoYXJ0IFREXG4gICAgQVtDaHJpc3RtYXNdIC0tPnxHZXQgbW9uZXl8IEIoR28gc2hvcHBpbmcpXG4gICAgQiAtLT4gQ3tMZXQgbWUgdGhpbmt9XG4gICAgQyAtLT58T25lfCBEW0xhcHRvcF1cbiAgICBDIC0tPnxUd298IEVbaVBob25lXVxuICAgIEMgLS0-fFRocmVlfCBGW2ZhOmZhLWNhciBDYXJdXG4gICIsIm1lcm1haWQiOiJ7XG4gIFwidGhlbWVcIjogXCJkZWZhdWx0XCJcbn0iLCJhdXRvU3luYyI6dHJ1ZSwidXBkYXRlRGlhZ3JhbSI6dHJ1ZX0"' '"base64:eyJjb2RlIjoiZ3JhcGggVERcbiAgICBBW0NocmlzdG1hc10gLS0-fEdldCBtb25leXwgQihHbyBzaG9wcGluZylcbiAgICBCIC0tPiBDe0xldCBtZSB0aGlua31cbiAgICBDIC0tPnxPbmV8IERbTGFwdG9wXVxuICAgIEMgLS0-fFR3b3wgRVtpUGhvbmVdXG4gICAgQyAtLT58VGhyZWV8IEZbZmE6ZmEtY2FyIENhcl1cbiAgIiwibWVybWFpZCI6IntcbiAgXCJ0aGVtZVwiOiBcImRlZmF1bHRcIlxufSIsImF1dG9TeW5jIjp0cnVlLCJ1cGRhdGVEaWFncmFtIjp0cnVlfQ"'
); );
}); });
it('should serialize and deserialize with pako serde', () => { it('should serialize and deserialize with pako serde', () => {
expect(verifySerde(defaultState, 'pako')).toMatchInlineSnapshot( 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 { 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, formatJSON } from './util'; import { cmdKey, errorDebug } from './util';
import { parse } from './mermaid'; import { parse } from './mermaid';
import type { ErrorHash, MarkerData, State, ValidatedState } from '$lib/types'; import type { ErrorHash, MarkerData, State, ValidatedState } from '$lib/types';
import type { MermaidConfig } from 'mermaid'; import type { MermaidConfig } from 'mermaid';
export const defaultState: State = { export const defaultState: State = {
code: `flowchart TD code: `graph TD
A[Christmas] -->|Get money| B(Go shopping) A[Christmas] -->|Get money| B(Go shopping)
B --> C{Let me think} B --> C{Let me think}
C -->|One| D[Laptop] C -->|One| D[Laptop]
C -->|Two| E[iPhone] C -->|Two| E[iPhone]
C -->|Three| F[fa:fa-car Car] C -->|Three| F[fa:fa-car Car]
`, `,
mermaid: formatJSON({ mermaid: JSON.stringify(
theme: 'default' {
}), theme: 'default'
},
null,
2
),
autoSync: true, autoSync: true,
updateDiagram: 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.) 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?} 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.) 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); processed.serialized = serializeState(state);
await parse(state.code); await parse(state.code);
JSON.parse(state.mermaid); JSON.parse(state.mermaid);
} catch (error) { } catch (e) {
processed.error = error as Error; processed.error = e as Error;
errorDebug(); errorDebug();
console.error(error); console.error(e);
if ('hash' in error) { if ('hash' in e) {
try { try {
const { const {
loc: { first_line, last_line, first_column, last_column } loc: { first_line, last_line, first_column, last_column }
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
} = error.hash as ErrorHash; } = e.hash as ErrorHash;
const marker: MarkerData = { const marker: MarkerData = {
severity: 8, // Error severity: 8, // Error
startLineNumber: first_line, startLineNumber: first_line,
@@ -78,11 +82,11 @@ const processState = async (state: State) => {
endLineNumber: last_line, endLineNumber: last_line,
endColumn: last_column + 1, endColumn: last_column + 1,
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment
message: error.str message: e.str
}; };
processed.errorMarkers = [marker]; processed.errorMarkers = [marker];
} catch (error) { } catch (err) {
console.error('Error without line helper', error); 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 delete mermaidConfig.securityLevel; // Prevent setting overriding securityLevel when loading state to mitigate possible XSS attack
} }
state.mermaid = formatJSON(mermaidConfig); state.mermaid = JSON.stringify(mermaidConfig, null, 2);
} catch (error) { } catch (e) {
state = get(inputStateStore); state = get(inputStateStore);
if (data) { if (data) {
console.error('Init error', error); console.error('Init error', e);
state.code = urlParseFailedState; state.code = urlParseFailedState;
state.mermaid = defaultState.mermaid; state.mermaid = defaultState.mermaid;
} }
@@ -142,7 +146,7 @@ export const updateCode = (
resetPanZoom = false resetPanZoom = false
}: { updateDiagram?: boolean; resetPanZoom?: boolean } = {} }: { updateDiagram?: boolean; resetPanZoom?: boolean } = {}
): void => { ): void => {
// console.log('updateCode', code); console.log('updateCode', code);
const lines = countLines(code); const lines = countLines(code);
saveStatistics(code); saveStatistics(code);
errorDebug(); errorDebug();
@@ -168,7 +172,7 @@ export const updateCode = (
}; };
export const updateConfig = (config: string): void => { export const updateConfig = (config: string): void => {
// console.log('updateConfig', config); console.log('updateConfig', config);
inputStateStore.update((state) => { inputStateStore.update((state) => {
return { ...state, mermaid: config }; return { ...state, mermaid: config };
}); });
@@ -181,7 +185,7 @@ export const toggleDarkTheme = (dark: boolean): void => {
config.theme = dark ? 'dark' : 'default'; 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) { } catch (e) {
console.log(error); console.log(e);
console.info('Analytics blocked ;)'); console.info('Analytics blocked ;)');
} }
} }
@@ -87,10 +87,10 @@ export const logEvent = (name: AnalyticsEvent, data?: unknown): void => {
return; return;
} }
const key = data ? JSON.stringify({ name, data }) : name; const key = data ? JSON.stringify({ name, data }) : name;
if (timeouts.has(key)) { if (!timeouts.has(key)) {
clearTimeout(timeouts.get(key));
} else {
void analytics.track(name, data); void analytics.track(name, data);
} else {
clearTimeout(timeouts.get(key));
} }
timeouts.set( timeouts.set(
key, key,
+3 -3
View File
@@ -16,7 +16,7 @@ export const themeStore: Writable<ThemeConfig> = persist(
'themeStore' 'themeStore'
); );
const darkThemes = new Set([ const darkThemes = [
'dark', 'dark',
'synthwave', 'synthwave',
'halloween', 'halloween',
@@ -25,13 +25,13 @@ const darkThemes = new Set([
'luxury', 'luxury',
'black', 'black',
'dracula' 'dracula'
]); ];
export const setTheme = (theme: string): void => { export const setTheme = (theme: string): void => {
if (theme.includes(' ')) { if (theme.includes(' ')) {
theme = theme.split(' ')[1].trim(); theme = theme.split(' ')[1].trim();
} }
const isDark = darkThemes.has(theme); const isDark = darkThemes.includes(theme);
console.log('Setting theme', theme); console.log('Setting theme', theme);
themeStore.set({ theme, isDark }); themeStore.set({ theme, isDark });
logEvent('themeChange', { 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 { loadDataFromUrl } from './fileLoaders/loader';
import { initLoading } from './loading'; import { initLoading } from './loading';
import { applyMigrations } from './migrations'; import { applyMigrations } from './migrations';
import { init } from './mermaid';
export const loadStateFromURL = (): void => { export const loadStateFromURL = (): void => {
loadState(window.location.hash.slice(1)); loadState(window.location.hash.slice(1));
@@ -16,6 +17,7 @@ export const syncDiagram = (): void => {
export const initHandler = async (): Promise<void> => { export const initHandler = async (): Promise<void> => {
applyMigrations(); applyMigrations();
await initLoading('Loading Mermaid...', init());
loadStateFromURL(); loadStateFromURL();
await initLoading('Loading Gist...', loadDataFromUrl().catch(console.error)); await initLoading('Loading Gist...', loadDataFromUrl().catch(console.error));
syncDiagram(); syncDiagram();
@@ -36,13 +38,3 @@ export const errorDebug = (limit = 100) => {
debugger; 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 { 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';
import type { Tab, DocumentationConfig, EditorMode, ValidatedState } from '$lib/types'; import type { Tab, DocConfig, EditorMode, ValidatedState } from '$lib/types';
import { base } from '$app/paths'; import { base } from '$app/paths';
const docURLBase = 'https://mermaid-js.github.io/mermaid'; const docURLBase = 'https://mermaid-js.github.io/mermaid';
const docMap: DocumentationConfig = { const docMap: DocConfig = {
graph: { graph: {
code: '/#/flowchart', code: '/#/flowchart',
config: '/#/flowchart?id=configuration' config: '/#/flowchart?id=configuration'
@@ -54,12 +54,11 @@
}; };
let docURL = docURLBase; let docURL = docURLBase;
let activeTabID = 'code'; let activeTabID = 'code';
let docKey = '';
stateStore.subscribe(({ code, editorMode }: ValidatedState) => { stateStore.subscribe(({ code, editorMode }: ValidatedState) => {
activeTabID = editorMode; activeTabID = editorMode;
const codeTypeMatch = /([\S]+)[\s\n]/.exec(code); const codeTypeMatch = /([\S]+)[\s\n]/.exec(code);
if (codeTypeMatch && codeTypeMatch.length > 1) { if (codeTypeMatch && codeTypeMatch.length > 1) {
docKey = codeTypeMatch[1]; const docKey = codeTypeMatch[1];
const docConfig = docMap[docKey] ?? { code: '' }; const docConfig = docMap[docKey] ?? { code: '' };
docURL = docURLBase + (docConfig[editorMode] ?? docConfig.code ?? ''); docURL = docURLBase + (docConfig[editorMode] ?? docConfig.code ?? '');
} }
@@ -134,9 +133,7 @@
on:click={syncDiagram}><i class="fas fa-sync" /></button> on:click={syncDiagram}><i class="fas fa-sync" /></button>
{/if} {/if}
<button <button class="btn btn-secondary btn-xs" title="View documentation">
class="btn btn-secondary btn-xs"
title="View documentation for {docKey.replace('Diagram', '')} diagram">
<a target="_blank" rel="noreferrer" href={docURL} data-cy="docs"> <a target="_blank" rel="noreferrer" href={docURL} data-cy="docs">
<i class="fas fa-book mr-1" />Docs <i class="fas fa-book mr-1" />Docs
</a> </a>
-1
View File
@@ -1 +0,0 @@
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 490.16 490.16"><defs><style>.cls-1{fill:#ff3670;}.cls-2{fill:#fff;}</style></defs><rect class="cls-1" width="490.16" height="490.16" rx="84.61"/><path class="cls-2" d="M407.48,111.18A165.2,165.2,0,0,0,245.08,220,165.2,165.2,0,0,0,82.68,111.18a165.5,165.5,0,0,0,72.06,143.64,88.81,88.81,0,0,1,38.53,73.45v50.86H296.9V328.27a88.8,88.8,0,0,1,38.52-73.45,165.41,165.41,0,0,0,72.06-143.64Z"/><path class="cls-2" d="M160.63,328.27a56.09,56.09,0,0,0-24.27-46.49,198.74,198.74,0,0,1-28.54-23.66A196.87,196.87,0,0,1,82.53,227V379.13h78.1Z"/><path class="cls-2" d="M329.53,328.27a56.09,56.09,0,0,1,24.27-46.49,198.74,198.74,0,0,0,28.54-23.66A196.87,196.87,0,0,0,407.63,227V379.13h-78.1Z"/></svg>

Before

Width:  |  Height:  |  Size: 772 B

+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/**/*.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,
+4 -4
View File
@@ -1,7 +1,6 @@
import { sveltekit } from '@sveltejs/kit/vite'; import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vitest/config'; /** @type {import('vite').UserConfig} */
const config = {
export default defineConfig({
plugins: [sveltekit()], plugins: [sveltekit()],
envPrefix: 'MERMAID_', envPrefix: 'MERMAID_',
optimizeDeps: { include: ['mermaid'] }, optimizeDeps: { include: ['mermaid'] },
@@ -23,4 +22,5 @@ export default defineConfig({
reporter: ['text', 'json', 'html', 'lcov'] reporter: ['text', 'json', 'html', 'lcov']
} }
} }
}); };
export default config;
+1220 -1683
View File
File diff suppressed because it is too large Load Diff