Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@
"dependencies": {
"@arielcharts/shared": "workspace:*",
"@codemirror/commands": "6.8.1",
"@codemirror/lang-markdown": "6.3.3",
"@codemirror/language": "6.12.3",
"@codemirror/state": "6.5.2",
"@codemirror/view": "6.38.6",
"@mermaid-js/parser": "1.2.0",
"@lezer/highlight": "1.2.3",
"@xyflow/react": "^12.11.0",
"codemirror": "6.0.2",
"fast-diff": "^1.3.0",
Expand Down
21 changes: 21 additions & 0 deletions apps/web/src/app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ html[data-theme='light'] {
--ink: #252522;
--ink-muted: #5f5f5a;
--ink-subtle: #5f5f5a;
--source-syntax-keyword: #1559c8;
--source-syntax-string: #195e2d;
--source-syntax-number: #774400;
--source-syntax-comment: #5f5f5a;
--source-syntax-operator: #8d1730;
--source-syntax-invalid: #a80f24;
--line-subtle: #d4d4cd;
--line-strong: #a4a49b;
--control-surface: #ffffff;
Expand Down Expand Up @@ -68,6 +74,12 @@ html[data-theme='dark'] {
--ink: #e7e7e7;
--ink-muted: #b3b3b3;
--ink-subtle: #929292;
--source-syntax-keyword: #9abfff;
--source-syntax-string: #a2e6b2;
--source-syntax-number: #f4d493;
--source-syntax-comment: #b3b3b3;
--source-syntax-operator: #ffb8c4;
--source-syntax-invalid: #ff9eaa;
--line-subtle: #363636;
--line-strong: #666666;
--control-surface: #252525;
Expand Down Expand Up @@ -2443,6 +2455,15 @@ code {
}

@media (forced-colors: active) {
:root {
--source-syntax-keyword: CanvasText;
--source-syntax-string: CanvasText;
--source-syntax-number: CanvasText;
--source-syntax-comment: CanvasText;
--source-syntax-operator: CanvasText;
--source-syntax-invalid: CanvasText;
}

.laser-pointer-sample {
background: Highlight !important;
border-color: CanvasText;
Expand Down
11 changes: 11 additions & 0 deletions apps/web/src/app/globals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ describe('mobile workspace CSS contracts', () => {
});
});

describe('Mermaid source highlighting accessibility', () => {
it('uses theme tokens and a forced-colors fallback instead of fixed editor colors', () => {
expect(css).toMatch(/--source-syntax-keyword:\s*#1559c8;/u);
expect(css).toMatch(/html\[data-theme='dark'\]\s*\{[^}]*--source-syntax-keyword:\s*#9abfff;/u);
const forcedColors = css.slice(css.indexOf('@media (forced-colors: active)'));
expect(forcedColors).toMatch(/:root\s*\{[^}]*--source-syntax-keyword:\s*CanvasText;/u);
expect(forcedColors).toMatch(/--source-syntax-comment:\s*CanvasText;/u);
expect(forcedColors).toMatch(/--source-syntax-invalid:\s*CanvasText;/u);
});
});

describe('flow-node shape surface contracts', () => {
it('clips only the painted shape surface, leaving React Flow handles outside it', () => {
expect(css).toMatch(/\.mermaid-flow-node\s*\{[^}]*position:\s*relative;[^}]*\}/u);
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/components/session-workspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { APP_NAME, STARTER_TEMPLATES, getStarterTemplate } from '@arielcharts/sh
import { basicSetup } from 'codemirror';
import mermaid from 'mermaid';
import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react';
import { markdown } from '@codemirror/lang-markdown';
import { Compartment, EditorState } from '@codemirror/state';
import { EditorView, keymap } from '@codemirror/view';
import { Check, KeyRound, Share2 } from 'lucide-react';
Expand Down Expand Up @@ -130,6 +129,7 @@ import { getAcceptedGenericSourceLayoutPolicy, getSourceLayoutPolicy, pruneNodeP
import { getServerHttpUrl, getWebsocketServerUrl } from '../lib/session';
import { listDiagramHistory, readCurrentDiagram, readDiagramRevision, restoreDiagramRevision } from '../lib/history-api';
import { getMermaidRenderId } from '../lib/mermaid-render-id';
import { mermaidSourceLanguage } from '../lib/mermaid-language';
import { formatMermaidForGitHub } from '../lib/github-mermaid';
import { getNextPreviewCameraLock } from '../lib/renderer-camera-policy';
import type { ConnectionState } from '../lib/connection-state';
Expand Down Expand Up @@ -1364,7 +1364,7 @@ export function SessionWorkspace({ initialRoomKey, sessionId }: { initialRoomKey
doc: activeDiagram.yText.toString(),
extensions: [
basicSetup,
markdown(),
mermaidSourceLanguage,
keymap.of(yUndoManagerKeymap),
editorThemeRef.current.of(editorTheme),
yCollab(activeDiagram.yText, collaboration.awareness, { undoManager }),
Expand Down
135 changes: 135 additions & 0 deletions apps/web/src/lib/mermaid-language.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { classHighlighter, highlightTree } from '@lezer/highlight';
import { EditorState } from '@codemirror/state';
import { describe, expect, it } from 'vitest';
import { MERMAID_CAPABILITY_FIXTURES } from './diagram-capabilities.fixtures';
import {
MERMAID_HIGHLIGHT_PARSE_BUDGET_MS,
MERMAID_HIGHLIGHT_STRESS_FIXTURE_LINES,
createMermaidHighlightStressFixture,
mermaidLanguage,
} from './mermaid-language';

type TokenSpan = { className: string; from: number; to: number };

function tokenClasses(source: string): string[] {
return tokenSpans(source).map(({ className }) => className);
}

function tokenSpans(source: string): TokenSpan[] {
const spans: TokenSpan[] = [];
highlightTree(mermaidLanguage.parser.parse(source), classHighlighter, (from, to, className) => spans.push({ className, from, to }));
return spans;
}

function expectTokenSpan(source: string, token: string, className: string): void {
const from = source.indexOf(token, Math.max(0, source.indexOf('\n') + 1));
expect(from, `Could not find ${JSON.stringify(token)} in source`).toBeGreaterThanOrEqual(0);
expect(tokenSpans(source)).toContainEqual({ className, from, to: from + token.length });
}

const FAMILY_GRAMMAR_EXPECTATIONS = {
architecture: ['service', 'tok-keyword'],
block: ['columns', 'tok-keyword'],
c4: ['Person', 'tok-keyword'],
class: ['class', 'tok-keyword'],
cynefin: ['complex', 'tok-keyword'],
'entity-relationship': ['string', 'tok-keyword'],
'event-modeling': ['entity', 'tok-keyword'],
flowchart: ['subgraph', 'tok-keyword'],
gantt: ['dateFormat', 'tok-keyword'],
gitgraph: ['commit', 'tok-keyword'],
ishikawa: ['"Problem"', 'tok-string'],
journey: ['section', 'tok-keyword'],
kanban: ['todo', 'tok-variableName'],
mindmap: ['Root', 'tok-variableName'],
packet: ['"Version"', 'tok-string'],
pie: ['title', 'tok-keyword'],
quadrant: ['x-axis', 'tok-keyword'],
radar: ['axis', 'tok-keyword'],
railroad: ['optional', 'tok-keyword'],
requirement: ['requirement', 'tok-keyword'],
sankey: ['A', 'tok-variableName'],
sequence: ['participant', 'tok-keyword'],
state: ['state', 'tok-keyword'],
swimlane: ['subgraph', 'tok-keyword'],
timeline: ['title', 'tok-keyword'],
'tree-view': ['Root', 'tok-variableName'],
treemap: ['"Root"', 'tok-string'],
venn: ['set', 'tok-keyword'],
wardley: ['component', 'tok-keyword'],
'xy-chart': ['x-axis', 'tok-keyword'],
} as const;

describe('mermaid source language', () => {
it('recognizes every current catalog family header without importing the renderer parser', () => {
for (const fixture of MERMAID_CAPABILITY_FIXTURES) {
expect(tokenClasses(fixture.headerOnlySource), fixture.family).toContain('tok-typeName');
}
});

it('uses position-aware grammar classes across every current catalog fixture', () => {
for (const fixture of MERMAID_CAPABILITY_FIXTURES) {
const expectation = FAMILY_GRAMMAR_EXPECTATIONS[fixture.family];
expect(expectation, `${fixture.family} needs an explicit grammar-token expectation`).toBeDefined();
expectTokenSpan(fixture.advancedSource, expectation[0], expectation[1]);
}
});

it('recognizes supported authored header aliases', () => {
for (const header of ['classDiagram-v2', 'flowchart-elk TD', 'graph LR', 'railroad-ebnf-beta', 'stateDiagram', 'zenuml']) {
expect(tokenClasses(header), header).toContain('tok-typeName');
}
});

it('classifies directives, frontmatter, comments, labels, connectors, numbers, and keywords', () => {
const source = `---\nconfig:\n theme: dark\n---\n%%{init: { \"theme\": \"base\" }}%%\nflowchart LR\n A[\"Label\"] --> B\n classDef hot fill:#ff0\n value: 42\n %% comment`;
const classes = tokenClasses(source);
expect(classes).toEqual(expect.arrayContaining([
'tok-meta', 'tok-propertyName', 'tok-string', 'tok-typeName', 'tok-variableName',
'tok-operator', 'tok-keyword', 'tok-number', 'tok-punctuation', 'tok-comment',
]));
const directive = '%%{init: { "theme": "base" }}%%';
expectTokenSpan(source, directive, 'tok-meta');
const directiveStart = source.indexOf(directive);
expect(tokenSpans(source).some((span) => span.className === 'tok-comment'
&& span.from < directiveStart + directive.length
&& span.to > directiveStart)).toBe(false);
expectTokenSpan(source, '%% comment', 'tok-comment');
});

it('keeps compact relation spans intact and marks unsupported characters explicitly', () => {
for (const [source, connector] of [
['flowchart LR\n node-name-->peer-node', '-->'],
['sequenceDiagram\n Alice->>Bob: request', '->>'],
['erDiagram\n CUSTOMER ||--o{ ORDER : places', '||--o{'],
]) {
expectTokenSpan(source, connector, 'tok-operator');
}
expectTokenSpan('flowchart LR\n node-name-->peer-node', 'node-name', 'tok-variableName');
expectTokenSpan('flowchart LR\n node-name-->peer-node', 'peer-node', 'tok-variableName');
expectTokenSpan('flowchart LR\n A ? B', '?', 'tok-invalid');
});

it('fails soft for partial and invalid input', () => {
expect(() => tokenClasses('sequenceDiagram\n participant Alice\n Alice->>')).not.toThrow();
expect(() => tokenClasses('---\nconfig: [\nflowchart LR\n A[unterminated')).not.toThrow();
});

it(`parses ${MERMAID_HIGHLIGHT_STRESS_FIXTURE_LINES.toLocaleString()} source lines within the ${MERMAID_HIGHLIGHT_PARSE_BUDGET_MS}ms budget`, () => {
const source = createMermaidHighlightStressFixture();
const startedAt = performance.now();
const tree = mermaidLanguage.parser.parse(source);
const elapsedMs = performance.now() - startedAt;
expect(tree.length).toBe(source.length);
expect(elapsedMs).toBeLessThan(MERMAID_HIGHLIGHT_PARSE_BUDGET_MS);
});

it('adds presentation data without normalizing source during incremental edits', () => {
const source = 'flowchart LR\n Browser --> API';
const initial = EditorState.create({ doc: source, extensions: mermaidLanguage });
const updated = initial.update({ changes: { from: initial.doc.length, insert: '\n API --> DB' } }).state;
expect(initial.doc.toString()).toBe(source);
expect(updated.doc.toString()).toBe(`${source}\n API --> DB`);
expect(tokenClasses(updated.doc.toString())).toContain('tok-operator');
});
});
Loading
Loading