Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Improve settled default theme text contrast (#6220)

Nick Gomeze4a5d467b0c0
diff --git a/.changeset/itchy-sloths-write.md b/.changeset/itchy-sloths-write.md
new file mode 100644
index 000000000..7c395ef51
--- /dev/null
+++ b/.changeset/itchy-sloths-write.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Improve settled text contrast in the default light and dark interface while preserving third-party and imported palette colors.
diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsx
index 7b3fff83a..88ce1e375 100644
--- a/packages/app/src/components/FileTree.tsx
+++ b/packages/app/src/components/FileTree.tsx
@@ -3059,7 +3059,7 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
if (tabId) requestPreviewTabPromotionForTab(tabId);
}
- function handleEmptyExternalFileDragOver(event: ReactDragEvent<HTMLDivElement>) {
+ function handleEmptyExternalFileDragOver(event: ReactDragEvent<HTMLElement>) {
if (!isExternalFileDrag(event.nativeEvent)) return;
event.preventDefault();
event.stopPropagation();
@@ -3067,13 +3067,13 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
setEmptyExternalFileDropActive(true);
}
- function handleEmptyExternalFileDragLeave(event: ReactDragEvent<HTMLDivElement>) {
+ function handleEmptyExternalFileDragLeave(event: ReactDragEvent<HTMLElement>) {
const related = event.relatedTarget;
if (related instanceof Node && event.currentTarget.contains(related)) return;
setEmptyExternalFileDropActive(false);
}
- function handleEmptyExternalFileDrop(event: ReactDragEvent<HTMLDivElement>) {
+ function handleEmptyExternalFileDrop(event: ReactDragEvent<HTMLElement>) {
if (!isExternalFileDrag(event.nativeEvent)) return;
const files = filesFromExternalDrop(event.nativeEvent);
if (files.length === 0) return;
@@ -3124,28 +3124,13 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
return <FileTreeFilteredToZeroNotice />;
}
return (
- <section
- aria-label={t`File drop zone`}
- className={cn(
- 'flex flex-1 flex-col items-center justify-center gap-3 rounded-md py-8',
- emptyExternalFileDropActive && 'bg-primary/5 ring-2 ring-primary/70 ring-inset',
- )}
+ <FileTreeEmptyState
+ active={emptyExternalFileDropActive}
onDragOver={handleEmptyExternalFileDragOver}
onDragLeave={handleEmptyExternalFileDragLeave}
onDrop={handleEmptyExternalFileDrop}
- >
- <span className="select-none text-sidebar-foreground/30 text-sm">
- <Trans>No files yet.</Trans>
- </span>
- <Button
- variant="link"
- size="sm"
- className="font-mono uppercase"
- onClick={() => startCreating('file', '')}
- >
- <Trans>Create your first file</Trans>
- </Button>
- </section>
+ onCreate={() => startCreating('file', '')}
+ />
);
}
@@ -3327,6 +3312,41 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {
);
}
+export function FileTreeEmptyState({
+ active,
+ onDragOver,
+ onDragLeave,
+ onDrop,
+ onCreate,
+}: {
+ active: boolean;
+ onDragOver: (event: ReactDragEvent<HTMLElement>) => void;
+ onDragLeave: (event: ReactDragEvent<HTMLElement>) => void;
+ onDrop: (event: ReactDragEvent<HTMLElement>) => void;
+ onCreate: () => void;
+}) {
+ const { t } = useLingui();
+ return (
+ <section
+ aria-label={t`File drop zone`}
+ className={cn(
+ 'flex flex-1 flex-col items-center justify-center gap-3 rounded-md py-8',
+ active && 'bg-primary/5 ring-2 ring-primary/70 ring-inset',
+ )}
+ onDragOver={onDragOver}
+ onDragLeave={onDragLeave}
+ onDrop={onDrop}
+ >
+ <span className="file-tree-empty-text select-none text-sidebar-foreground/30 text-sm">
+ <Trans>No files yet.</Trans>
+ </span>
+ <Button variant="link" size="sm" className="font-mono uppercase" onClick={onCreate}>
+ <Trans>Create your first file</Trans>
+ </Button>
+ </section>
+ );
+}
+
function hasExpandedAncestry(path: string, expandedPaths: ReadonlySet<string>): boolean {
return computeTreeAncestorPaths(path)
.slice(0, -1)
diff --git a/packages/app/src/components/TextViewer.tsx b/packages/app/src/components/TextViewer.tsx
index 5195f4ab9..542908878 100644
--- a/packages/app/src/components/TextViewer.tsx
+++ b/packages/app/src/components/TextViewer.tsx
@@ -1,10 +1,11 @@
+import { syntaxHighlighting } from '@codemirror/language';
import { EditorState } from '@codemirror/state';
import { EditorView } from '@codemirror/view';
import { codeLanguageForExtension } from '@inkeep/open-knowledge-core/constants/code-languages';
import { basicSetup } from 'codemirror';
import { useTheme } from 'next-themes';
import { useEffect, useRef } from 'react';
-import { okCmTheme } from '@/editor/extensions/cm-theme';
+import { okCmTheme, okSyntaxHighlight } from '@/editor/extensions/cm-theme';
import { loadCodeMirrorLanguageForExtension } from './text-viewer-languages';
import { useViewerText, type ViewerTextSource } from './use-viewer-text';
import { ViewerErrorPane, ViewerLoadingPane } from './ViewerStatusPane';
@@ -47,6 +48,7 @@ export function TextViewer({ fileName, extension, ...source }: TextViewerProps)
if (!containerRef.current) return;
const extensions = [
basicSetup,
+ syntaxHighlighting(okSyntaxHighlight),
...(language ? [language] : []),
EditorView.editable.of(true),
EditorState.readOnly.of(true),
diff --git a/packages/app/src/components/settings/ColorThemePicker.tsx b/packages/app/src/components/settings/ColorThemePicker.tsx
index b06d1b068..e7ddf5e19 100644
--- a/packages/app/src/components/settings/ColorThemePicker.tsx
+++ b/packages/app/src/components/settings/ColorThemePicker.tsx
@@ -174,7 +174,7 @@ export function ColorThemePicker({
aria-label={ariaLabel}
aria-describedby={ariaDescribedby}
aria-invalid={ariaInvalid}
- className="grid w-full min-w-0 grid-cols-2 gap-2 sm:grid-cols-3"
+ className="color-theme-picker grid w-full min-w-0 grid-cols-2 gap-2 sm:grid-cols-3"
>
{themes.map((theme, index) => {
const isLight = selection.light === theme.id;
diff --git a/packages/app/src/components/settings/SettingsDialogShell.tsx b/packages/app/src/components/settings/SettingsDialogShell.tsx
index 2b771f7a9..dc67b3570 100644
--- a/packages/app/src/components/settings/SettingsDialogShell.tsx
+++ b/packages/app/src/components/settings/SettingsDialogShell.tsx
@@ -749,8 +749,9 @@ function SettingsSidebarGroup({
<h3
id={headerId}
aria-describedby={group.enabled ? undefined : describedById}
+ data-disabled={!group.enabled || undefined}
className={cn(
- 'shrink-0 whitespace-nowrap px-2 text-xs font-semibold uppercase tracking-wide font-mono sm:mb-1',
+ 'settings-sidebar-group-title shrink-0 whitespace-nowrap px-2 text-xs font-semibold uppercase tracking-wide font-mono sm:mb-1',
group.enabled ? 'text-muted-foreground/80' : 'text-muted-foreground/50',
)}
>
diff --git a/packages/app/src/globals.css b/packages/app/src/globals.css
index d9b7d95e0..7d1fca82b 100644
--- a/packages/app/src/globals.css
+++ b/packages/app/src/globals.css
@@ -2949,7 +2949,7 @@ body[data-editor-tab-dragging] * {
@apply border-none!;
}
-.cm-gutters {
+:where(html[data-color-theme]) .cm-gutters {
@apply text-muted-foreground/80!;
}
@@ -3507,33 +3507,23 @@ button:active:not(:disabled) {
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
- /*
- Syntax-highlight semantic tokens — used by the PropPanel CodeMirror
- editor (`CodeMirrorPropInput`) and any future code-shaped surface
- that wants theme-adaptive coloring. Light values are the Tailwind v4
- `-700`/`-800` saturated palette (good contrast on `--background:
- oklch(1 0 0)`); the matching `.dark` block below shifts to `-300`/
- `-400` for WCAG AA on `--background: oklch(0.195 0 0)`. Hex
- fallbacks are GitHub-light defaults — only used if Tailwind's
- default theme tokens haven't loaded (SSR / preview-render edge).
- */
--syntax-keyword: var(--color-purple-700, #6f42c1);
--syntax-tag: var(--color-red-700, #b31d28);
--syntax-attr: var(--color-blue-700, #005cc5);
- --syntax-string: var(--color-green-800, #22863a);
+ --syntax-string: var(--color-green-900, oklch(0.393 0.095 152.535));
--syntax-number: var(--color-blue-800, #005cc5);
- --syntax-atom: var(--color-orange-700, #d2691e);
+ --syntax-atom: var(--color-orange-800, oklch(0.47 0.157 37.304));
/*
The remaining syntax roles. A selected color theme overrides all of these
from its base16 slots; the values here are the `default` theme's own, so
the same rules paint correctly with no palette applied.
*/
- --syntax-comment: var(--color-gray-500, #6a737d);
+ --syntax-comment: var(--color-gray-600, oklch(0.444 0.011 73.639));
--syntax-func: var(--color-purple-700, #6f42c1);
--syntax-var: var(--color-red-700, #b31d28);
--syntax-type: var(--color-yellow-700, #8b6500);
--syntax-operator: var(--foreground);
- --syntax-meta: var(--color-gray-600, #6a737d);
+ --syntax-meta: var(--color-gray-600, oklch(0.444 0.011 73.639));
/* Code-block canvas — a hair off `--background` so a fence reads as a slab. */
--syntax-bg: oklch(0.97 0 0);
@@ -3630,24 +3620,18 @@ button:active:not(:disabled) {
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
- /*
- Syntax-highlight tokens — dark-theme overrides. Lighter shades
- (`-300` / `-400`) clear WCAG AA on the dark `--background:
- oklch(0.195 0 0)`. Hex fallbacks are mid-light shades that survive
- on dark for the SSR / preview-render edge.
- */
--syntax-keyword: var(--color-purple-300, #d2a8ff);
--syntax-tag: var(--color-red-300, #ffa198);
--syntax-attr: var(--color-blue-300, #79c0ff);
- --syntax-string: var(--color-green-300, #7ee787);
+ --syntax-string: oklch(0.9 0.15 154.449);
--syntax-number: var(--color-blue-300, #79c0ff);
--syntax-atom: var(--color-orange-300, #ffa657);
- --syntax-comment: var(--color-gray-400, #8b949e);
+ --syntax-comment: oklch(0.78 0.01 56.259);
--syntax-func: var(--color-purple-300, #d2a8ff);
--syntax-var: var(--color-red-300, #ffa198);
--syntax-type: var(--color-yellow-300, #e3b341);
--syntax-operator: var(--foreground);
- --syntax-meta: var(--color-gray-400, #8b949e);
+ --syntax-meta: oklch(0.78 0.01 56.259);
--syntax-bg: oklch(0.18 0.005 285);
--link-color: var(--color-sky-blue);
@@ -6870,6 +6854,89 @@ html [data-editor-file-list-slot] [data-slot="sidebar-inner"] {
forced-color-adjust: none;
}
+html:not([data-color-theme]):not(.dark)
+ .raw-mdx-fallback-wrapper[data-severity="error"]
+ > div
+ > span {
+ color: #a31524;
+}
+
+html:not([data-color-theme]):not(.dark) file-tree-container {
+ /* biome-ignore lint/complexity/noImportantStyles: the tree host receives --trees-selected-fg as an inline style, which no selector specificity can outrank. */
+ --trees-selected-fg: #1d4ed8 !important;
+}
+
+html:not([data-color-theme]) .file-tree-empty-text {
+ color: var(--muted-foreground);
+}
+
+html:not([data-color-theme]):not(.dark) .cm-gutters {
+ color: #606060;
+}
+
+html:not([data-color-theme]) .color-theme-picker [data-state="off"]:not(:hover) {
+ color: var(--muted-foreground);
+}
+
+html:not([data-color-theme]):not(.dark) .settings-sidebar-group-title {
+ color: #5a5a5a;
+}
+
+html:not([data-color-theme]):not(.dark) .settings-sidebar-group-title[data-disabled] {
+ color: var(--muted-foreground);
+}
+
+html:not([data-color-theme]).dark .settings-sidebar-group-title[data-disabled] {
+ color: color-mix(in oklab, var(--muted-foreground) 80%, transparent);
+}
+
+html:not([data-color-theme]):not(.dark) .cm-content {
+ --muted-foreground: #5a5a5a;
+ --syntax-type: var(--color-yellow-800, oklch(0.476 0.114 61.907));
+ --link-color: var(--color-azure-700, oklch(0.4895 0.233 263.93));
+ --destructive: var(--color-red-800, oklch(0.444 0.177 26.899));
+}
+html:not([data-color-theme]).dark .cm-content {
+ --link-color: #8bb9ff;
+ --muted-foreground: oklch(0.78 0 0);
+ --destructive: var(--color-red-300, oklch(0.808 0.114 19.571));
+}
+html:not([data-color-theme]):not(.dark) .cm-selectionLayer {
+ --selection-soft: #e0ebfc;
+}
+
+html:not([data-color-theme]).dark .cm-selectionLayer {
+ --selection-soft: #20364d;
+}
+
+html:not([data-color-theme]) .cm-editor .cm-selectionBackground,
+html:not([data-color-theme])
+ .cm-editor.cm-focused
+ > .cm-scroller
+ > .cm-selectionLayer
+ .cm-selectionBackground {
+ background-color: var(--selection-soft);
+}
+
+html:not([data-color-theme]):not(.dark) .cm-editor .cm-searchMatch,
+html:not([data-color-theme]):not(.dark) .cm-editor .cm-selectionMatch {
+ background-color: rgb(230 198 76 / 24%);
+}
+html:not([data-color-theme]).dark .cm-editor .cm-searchMatch,
+html:not([data-color-theme]).dark .cm-editor .cm-selectionMatch {
+ background-color: rgb(155 122 39 / 16%);
+}
+html:not([data-color-theme]):not(.dark) .cm-editor .cm-searchMatch.cm-searchMatch-selected {
+ background-color: #cbdcfa;
+}
+html:not([data-color-theme]).dark .cm-editor .cm-searchMatch.cm-searchMatch-selected {
+ background-color: #243950;
+}
+
+html:not([data-color-theme]):not(.dark) [data-slot="kbd"] {
+ --muted-foreground: #686868;
+}
+
[data-agents-panel-mount][data-chat-alone]
[data-agent-thread-root]
> :not(.absolute):not([data-testid="agent-thread-transcript"]):not(
diff --git a/packages/app/tests/foundation/default-editor-states.browser.test.ts b/packages/app/tests/foundation/default-editor-states.browser.test.ts
new file mode 100644
index 000000000..f3738b245
--- /dev/null
+++ b/packages/app/tests/foundation/default-editor-states.browser.test.ts
@@ -0,0 +1,192 @@
+import { StreamLanguage } from '@codemirror/language';
+import {
+ closeSearchPanel,
+ findNext,
+ openSearchPanel,
+ SearchQuery,
+ setSearchQuery,
+} from '@codemirror/search';
+import { EditorSelection, EditorState } from '@codemirror/state';
+import { EditorView } from '@codemirror/view';
+import { tags } from '@lezer/highlight';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { commands } from 'vitest/browser';
+import { okCmTheme } from '@/editor/extensions/cm-theme';
+import { sourceModeSetup } from '@/editor/source-mode-setup';
+import { sourceCharacterMeasurements } from './theme-contrast.test-helper';
+
+const ROLES = [
+ { name: 'foreground', tag: tags.strong },
+ { name: 'link-color', tag: tags.link },
+ { name: 'syntax-func', tag: tags.function(tags.variableName) },
+ { name: 'syntax-attr', tag: tags.attributeName },
+ { name: 'syntax-string', tag: tags.string },
+ { name: 'syntax-comment', tag: tags.comment },
+ { name: 'syntax-keyword', tag: tags.keyword },
+ { name: 'muted-foreground', tag: tags.processingInstruction },
+ { name: 'syntax-meta', tag: tags.meta },
+ { name: 'syntax-tag', tag: tags.tagName },
+ { name: 'syntax-type', tag: tags.typeName },
+ { name: 'syntax-var', tag: tags.variableName },
+ { name: 'syntax-number', tag: tags.number },
+ { name: 'syntax-atom', tag: tags.atom },
+ { name: 'syntax-operator', tag: tags.operator },
+ { name: 'diff-added', tag: tags.inserted },
+ { name: 'diff-removed', tag: tags.deleted },
+ { name: 'destructive', tag: tags.invalid },
+] as const;
+const STATES = [
+ 'ordinary',
+ 'active',
+ 'plain-search',
+ 'selected-search',
+ 'selection-match',
+ 'primary',
+ 'secondary',
+ 'secondary-search',
+] as const;
+const LINE = 'MMMM same MMMM';
+const DOC = `${LINE}\n${LINE}\n${LINE}\n${LINE}\n${LINE}\n`;
+let stylesheet: HTMLStyleElement;
+beforeAll(async () => {
+ stylesheet = document.createElement('style');
+ stylesheet.textContent = await commands.buildAppStylesheet();
+ document.head.append(stylesheet);
+});
+afterAll(() => stylesheet.remove());
+
+async function settle(view: EditorView) {
+ await new Promise<void>((resolve) =>
+ view.requestMeasure({
+ read: () => undefined,
+ write: () => requestAnimationFrame(() => resolve()),
+ }),
+ );
+}
+
+for (const mode of ['light', 'dark'] as const) {
+ describe(`default ${mode} editor syntax in highlight states`, () => {
+ for (const role of ROLES) {
+ test(`${role.name} keeps its color and remains readable`, async () => {
+ document.documentElement.classList.toggle('dark', mode === 'dark');
+ delete document.documentElement.dataset.colorTheme;
+ document.documentElement.style.colorScheme = mode;
+ try {
+ for (const background of ['var(--background)', 'var(--syntax-bg)', 'var(--muted)']) {
+ const host = document.createElement('div');
+ host.style.cssText = `width:850px;padding:24px;background:${background};color:var(--foreground)`;
+ document.body.append(host);
+ const language = StreamLanguage.define({
+ token(stream) {
+ if (stream.eatSpace()) return null;
+ stream.eatWhile(/\S/);
+ return 'sample';
+ },
+ tokenTable: { sample: role.tag },
+ });
+ const view = new EditorView({
+ parent: host,
+ state: EditorState.create({
+ doc: DOC,
+ extensions: [sourceModeSetup, language, okCmTheme({ dark: mode === 'dark' })],
+ }),
+ });
+ try {
+ await settle(view);
+ const token = view.contentDOM.querySelector('.cm-line span');
+ expect(token).not.toBeNull();
+ if (!token) throw new Error('Syntax token did not render');
+ const ordinaryColor = getComputedStyle(token).color;
+ for (const state of STATES) {
+ closeSearchPanel(view);
+ view.dispatch({
+ effects: setSearchQuery.of(new SearchQuery({ search: '' })),
+ selection: EditorSelection.cursor(DOC.length),
+ });
+ if (state === 'active') view.dispatch({ selection: EditorSelection.cursor(2) });
+ if (state === 'primary' || state === 'selection-match')
+ view.dispatch({ selection: EditorSelection.range(0, 4) });
+ if (state === 'secondary' || state === 'secondary-search')
+ view.dispatch({
+ selection: EditorSelection.create(
+ [EditorSelection.range(0, 4), EditorSelection.range(17, 46)],
+ 0,
+ ),
+ });
+ if (
+ state === 'plain-search' ||
+ state === 'selected-search' ||
+ state === 'secondary-search'
+ ) {
+ openSearchPanel(view);
+ view.dispatch({
+ effects: setSearchQuery.of(new SearchQuery({ search: 'MMMM' })),
+ });
+ if (state === 'selected-search') findNext(view);
+ if (state === 'secondary-search') view.focus();
+ } else view.focus();
+ await settle(view);
+ let offset = 0;
+ let targets = 0;
+ for (const line of DOC.split('\n')) {
+ if (!line.length) continue;
+ for (const reading of sourceCharacterMeasurements(
+ view,
+ offset,
+ offset + line.length,
+ )) {
+ if (!reading.text.trim()) continue;
+ const at = view.domAtPos(reading.position);
+ const element =
+ at.node.nodeType === Node.TEXT_NODE
+ ? at.node.parentElement
+ : (at.node as Element);
+ if (!element) throw new Error('Missing syntax element');
+ const active = !!element.closest('.cm-activeLine');
+ const search = !!element.closest('.cm-searchMatch');
+ const selectedSearch = !!element.closest('.cm-searchMatch-selected');
+ const match = !!element.closest('.cm-selectionMatch');
+ const primary = reading.position < 4;
+ const target =
+ state === 'ordinary'
+ ? !active
+ : state === 'active'
+ ? active
+ : state === 'plain-search'
+ ? search && !selectedSearch
+ : state === 'selected-search'
+ ? selectedSearch
+ : state === 'selection-match'
+ ? match && !reading.selected
+ : state === 'primary'
+ ? reading.selected && primary
+ : reading.selected && !primary;
+ if (!target) continue;
+ targets++;
+ expect
+ .soft(reading.foreground, `${background} ${state} preserves syntax`)
+ .toBe(ordinaryColor);
+ expect
+ .soft(
+ reading.ratio,
+ `${background} ${state} ${role.name} on ${JSON.stringify(reading.background)}`,
+ )
+ .toBeGreaterThanOrEqual(4.5);
+ }
+ offset += line.length + 1;
+ }
+ expect(targets, `${background} ${state} renders`).toBeGreaterThan(0);
+ }
+ } finally {
+ view.destroy();
+ host.remove();
+ }
+ }
+ } finally {
+ document.documentElement.classList.remove('dark');
+ document.documentElement.style.removeProperty('color-scheme');
+ }
+ });
+ }
+ });
+}
diff --git a/packages/app/tests/foundation/theme-contrast-helper.browser.test.ts b/packages/app/tests/foundation/theme-contrast-helper.browser.test.ts
new file mode 100644
index 000000000..85cd55747
--- /dev/null
+++ b/packages/app/tests/foundation/theme-contrast-helper.browser.test.ts
@@ -0,0 +1,21 @@
+import { expect, test } from 'vitest';
+import { rgba } from './theme-contrast.test-helper';
+
+test.each([
+ { css: '#3e4b59', expected: [62 / 255, 75 / 255, 89 / 255, 1] },
+ { css: '#808e80', expected: [128 / 255, 142 / 255, 128 / 255, 1] },
+])('contrast measurements preserve hexadecimal $css', ({ css, expected }) => {
+ expect(rgba(css)).toEqual(expected);
+});
+
+test('contrast measurements accept scientific channels in functional colors', () => {
+ expect(rgba('color(srgb 4e-3 5e-2 0.5 / 1)')).toEqual([0.004, 0.05, 0.5, 1]);
+});
+
+test('contrast measurements preserve ordinary rendered RGB colors', () => {
+ expect(rgba('rgb(62, 75, 89)')).toEqual([62 / 255, 75 / 255, 89 / 255, 1]);
+});
+
+test('contrast measurements reject unsupported colors', () => {
+ expect(() => rgba('var(--foreground)')).toThrow();
+});
diff --git a/packages/app/tests/foundation/theme-contrast.test-helper.ts b/packages/app/tests/foundation/theme-contrast.test-helper.ts
new file mode 100644
index 000000000..87ba3d341
--- /dev/null
+++ b/packages/app/tests/foundation/theme-contrast.test-helper.ts
@@ -0,0 +1,150 @@
+import type { EditorView } from '@codemirror/view';
+import axe from 'axe-core';
+
+interface Color {
+ r: number;
+ g: number;
+ b: number;
+ alpha: number;
+ parseString(value: string): void;
+}
+
+const { Color: AxeColor } = (axe.commons as unknown as { color: { Color: new () => Color } }).color;
+
+type Rgba = [number, number, number, number];
+
+export function rgba(value: string): Rgba {
+ const color = new AxeColor();
+ const normalized = value.trimStart().startsWith('#')
+ ? value
+ : value.replace(/[-+]?\d*\.?\d+e[-+]?\d+/gi, (part) => Number(part).toFixed(20));
+ color.parseString(normalized);
+ const channels: Rgba = [Number(color.r), Number(color.g), Number(color.b), Number(color.alpha)];
+ if (channels.some((channel) => !Number.isFinite(channel))) {
+ throw new Error(`Color parser returned non-finite channels for ${value}`);
+ }
+ return channels;
+}
+
+function over(foreground: Rgba, background: Rgba): Rgba {
+ const alpha = foreground[3];
+ return [
+ foreground[0] * alpha + background[0] * (1 - alpha),
+ foreground[1] * alpha + background[1] * (1 - alpha),
+ foreground[2] * alpha + background[2] * (1 - alpha),
+ 1,
+ ];
+}
+
+function luminance(color: Rgba): number {
+ const linear = color
+ .slice(0, 3)
+ .map((value) => (value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4));
+ return linear[0] * 0.2126 + linear[1] * 0.7152 + linear[2] * 0.0722;
+}
+
+function parentElement(element: Element): Element | null {
+ if (element.parentElement) return element.parentElement;
+ const root = element.getRootNode();
+ return root instanceof ShadowRoot ? root.host : null;
+}
+
+export function textMeasurement(element: Element, overlay?: Element) {
+ const layers: { background: string; opacity: number; selection?: string }[] = [];
+ const content = overlay ? element.closest('.cm-content') : null;
+ if (overlay && !content)
+ throw new Error('Selection backdrop needs a CodeMirror content boundary');
+ let ancestor: Element | null = element;
+ while (ancestor) {
+ const style = getComputedStyle(ancestor);
+ if (Number(style.opacity) !== 1)
+ throw new Error(`Unmeasured group opacity on ${ancestor.tagName}`);
+ if (style.backgroundImage !== 'none')
+ throw new Error(`Unmeasured background image on ${ancestor.tagName}`);
+ layers.push({
+ background: style.backgroundColor,
+ opacity: Number(style.opacity),
+ ...(ancestor === content && overlay
+ ? { selection: getComputedStyle(overlay).backgroundColor }
+ : {}),
+ });
+ ancestor = parentElement(ancestor);
+ }
+ let background: Rgba = [1, 1, 1, 1];
+ for (const layer of layers.toReversed()) {
+ if (layer.selection) background = over(rgba(layer.selection), background);
+ const color = rgba(layer.background);
+ background = over(color, background);
+ }
+ const foregroundCss = getComputedStyle(element).color;
+ const foreground = rgba(foregroundCss);
+ const paintedForeground = over(foreground, background);
+ const fg = luminance(paintedForeground);
+ const bg = luminance(background);
+ return {
+ text: element.textContent?.trim(),
+ foreground: foregroundCss,
+ selectionOverlay: overlay ? getComputedStyle(overlay).backgroundColor : null,
+ background: background.slice(0, 3),
+ layers,
+ ratio: (Math.max(fg, bg) + 0.05) / (Math.min(fg, bg) + 0.05),
+ };
+}
+
+export function textLeaves(root: Element | ShadowRoot): Element[] {
+ return Array.from(root.querySelectorAll('*')).filter((element) => {
+ if (element.tagName === 'STYLE' || element.tagName === 'SCRIPT') return false;
+ if (
+ !Array.from(element.childNodes).some(
+ (node) => node.nodeType === Node.TEXT_NODE && node.textContent?.trim(),
+ )
+ )
+ return false;
+ let ancestor: Element | null = element;
+ while (ancestor) {
+ if (Number(getComputedStyle(ancestor).opacity) === 0) return false;
+ ancestor = parentElement(ancestor);
+ }
+ const style = getComputedStyle(element);
+ if (style.visibility !== 'visible' || Number(style.opacity) === 0) return false;
+ const rect = element.getBoundingClientRect();
+ return rect.width > 0 && rect.height > 0;
+ });
+}
+
+export function sourceCharacterMeasurements(view: EditorView, from: number, to: number) {
+ const selections = Array.from(view.dom.querySelectorAll('.cm-selectionBackground')).map(
+ (element) => ({ element, rect: element.getBoundingClientRect() }),
+ );
+ const readings = [];
+ const walker = document.createTreeWalker(view.contentDOM, NodeFilter.SHOW_TEXT);
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ const text = node.textContent ?? '';
+ for (let offset = 0; offset < text.length; offset++) {
+ const position = view.posAtDOM(node, offset);
+ if (position < from || position >= to) continue;
+ const range = document.createRange();
+ range.setStart(node, offset);
+ range.setEnd(node, offset + 1);
+ const rect = range.getBoundingClientRect();
+ if (rect.width <= 0 || rect.height <= 0)
+ throw new Error(`Unrendered source character ${position}`);
+ const x = rect.left + rect.width / 2;
+ const y = rect.top + rect.height / 2;
+ const selection = selections.find(
+ ({ rect }) => x >= rect.left && x < rect.right && y >= rect.top && y < rect.bottom,
+ );
+ const element = node.parentElement;
+ if (!element) throw new Error(`Missing source character parent ${position}`);
+ readings.push({
+ ...textMeasurement(element, selection?.element),
+ position,
+ text: text[offset],
+ selected: selection !== undefined,
+ });
+ }
+ }
+ if (readings.length !== to - from)
+ throw new Error(`Expected ${to - from} source characters, measured ${readings.length}`);
+ return readings;
+}
diff --git a/packages/app/tests/foundation/theme-text-backgrounds.test-helper.ts b/packages/app/tests/foundation/theme-text-backgrounds.test-helper.ts
new file mode 100644
index 000000000..c0065e9be
--- /dev/null
+++ b/packages/app/tests/foundation/theme-text-backgrounds.test-helper.ts
@@ -0,0 +1,118 @@
+export const measuredBackgrounds: Record<string, number[][]> = {
+ 'default-light/source': [
+ [0.961575572094, 0.961575488224, 0.961575620716],
+ [1.000000044587, 0.999999957075, 1.000000094692],
+ ],
+ 'default-light/source-active': [
+ [0.961575572094, 0.961575488224, 0.961575620716],
+ [1.000000044587, 0.999999957075, 1.000000094692],
+ ],
+ 'default-light/source-gutter': [[1.000000044587, 0.999999957075, 1.000000094692]],
+ 'default-light/rich-and-raw-mdx': [
+ [0.960586957496, 0.960586995262, 0.960587097486],
+ [0.986436340949, 0.8549999633, 0.86112148112],
+ [0.995322905401, 0.949999959222, 0.952110917598],
+ [1.000000044587, 0.999999957075, 1.000000094692],
+ ],
+ 'default-light/text-doc': [
+ [0.960586957496, 0.960586995262, 0.960587097486],
+ [0.961575572094, 0.961575488224, 0.961575620716],
+ [1.000000044587, 0.999999957075, 1.000000094692],
+ ],
+ 'default-light/mermaid': [
+ [0.960586957496, 0.960586995262, 0.960587097486],
+ [0.961575572094, 0.961575488224, 0.961575620716],
+ [1.000000044587, 0.999999957075, 1.000000094692],
+ ],
+ 'default-light/viewer': [
+ [0.960586957496, 0.960586995262, 0.960587097486],
+ [0.961575572094, 0.961575488224, 0.961575620716],
+ [1.000000044587, 0.999999957075, 1.000000094692],
+ ],
+ 'default-light/property': [
+ [0.960586957496, 0.960586995262, 0.960587097486],
+ [1.000000044587, 0.999999957075, 1.000000094692],
+ ],
+ 'default-light/tree-hover': [[0.960586957496, 0.960586995262, 0.960587097486]],
+ 'default-light/diff': [
+ [0.652051822502, 0.781327871174, 0.697178849312],
+ [0.813698695628, 0.876286088968, 0.82432156164],
+ [0.94225327586, 0.663960224952, 0.637033344658],
+ [0.985972716079, 0.990624412395, 0.986881582242],
+ [0.988604344825, 0.829950281191, 0.789078130823],
+ [0.999010149071, 0.987400162441, 0.985755386094],
+ [1.000000044587, 0.999999957075, 1.000000094692],
+ ],
+ 'default-light/terminal': [[1, 1, 1]],
+ 'default-dark/source': [
+ [0.081708560789, 0.081708565873, 0.081708579633],
+ [0.117650456352, 0.117650462772, 0.11765048015],
+ ],
+ 'default-dark/source-active': [
+ [0.081708560789, 0.081708565873, 0.081708579633],
+ [0.117650456352, 0.117650462772, 0.11765048015],
+ ],
+ 'default-dark/source-gutter': [[0.081708560789, 0.081708565873, 0.081708579633]],
+ 'default-dark/rich-and-raw-mdx': [
+ [0.0676052135, 0.067791876405, 0.077441216614],
+ [0.081708560789, 0.081708565873, 0.081708579633],
+ [0.12762313275, 0.097180784892, 0.097815990702],
+ [0.214860819475, 0.126578001028, 0.128420071732],
+ ],
+ 'default-dark/text-doc': [
+ [0.081708560789, 0.081708565873, 0.081708579633],
+ [0.117650456352, 0.117650462772, 0.11765048015],
+ [0.149382071714, 0.149382079314, 0.149382099886],
+ ],
+ 'default-dark/mermaid': [
+ [0.081708560789, 0.081708565873, 0.081708579633],
+ [0.117650456352, 0.117650462772, 0.11765048015],
+ [0.149382071714, 0.149382079314, 0.149382099886],
+ ],
+ 'default-dark/viewer': [
+ [0.081708560789, 0.081708565873, 0.081708579633],
+ [0.117650456352, 0.117650462772, 0.11765048015],
+ [0.149382071714, 0.149382079314, 0.149382099886],
+ ],
+ 'default-dark/property': [
+ [0.081708560789, 0.081708565873, 0.081708579633],
+ [0.149382071714, 0.149382079314, 0.149382099886],
+ ],
+ 'default-dark/tree-hover': [[0.119954736374, 0.11995474288, 0.11995476049]],
+ 'default-dark/diff': [
+ [0.081708560789, 0.081708565873, 0.081708579633],
+ [0.088231040222, 0.092511442303, 0.089385266806],
+ [0.09350916826, 0.089198100825, 0.089046840315],
+ [0.1615592116, 0.22860895912, 0.182406290904],
+ [0.22549556928, 0.372165367296, 0.277335432724],
+ [0.240612790799, 0.179772039024, 0.178400806588],
+ [0.392490232639, 0.270762431219, 0.27000564527],
+ ],
+ 'default-dark/terminal': [[0.082352941176, 0.082352941176, 0.082352941176]],
+ 'default-light/code-modal': [[1.000000044587, 0.999999957075, 1.000000094692]],
+ 'default-light/conflict-syntax': [
+ [0.605850573417, 0.757747006006, 0.668957029309],
+ [0.634698090148, 0.712318518284, 0.965567833443],
+ [0.821953022683, 0.881006864934, 0.832992853389],
+ [0.833661633218, 0.866660554669, 0.992276933715],
+ [0.888227218624, 0.925403739854, 0.895012865245],
+ [0.896716396233, 0.91616939304, 0.995588559199],
+ [0.91601578863, 0.943982109869, 0.92108240858],
+ [0.922718924434, 0.936975216703, 0.996832929842],
+ [0.999999967565, 0.999988978749, 0.999999936483],
+ [1.000000044587, 0.999999957075, 1.000000094692],
+ ],
+ 'default-dark/code-modal': [[0.082352941176, 0.082352941176, 0.082352941176]],
+ 'default-dark/conflict-syntax': [
+ [0.081708560789, 0.081708565873, 0.081708579633],
+ [0.11818703484, 0.145757449695, 0.126144680688],
+ [0.121417657231, 0.133612407572, 0.149798087721],
+ [0.130077552798, 0.167790495553, 0.141228002503],
+ [0.134553037766, 0.151408732081, 0.173370877376],
+ [0.137114492454, 0.13710295412, 0.137114668428],
+ [0.158539670471, 0.222291057816, 0.178303465033],
+ [0.166313175658, 0.195373405076, 0.23186905896],
+ [0.242518687799, 0.416929124272, 0.306275823889],
+ [0.269605662479, 0.350370518864, 0.437892196616],
+ ],
+};
diff --git a/packages/app/tests/foundation/theme-text-contrast.browser.test.tsx b/packages/app/tests/foundation/theme-text-contrast.browser.test.tsx
new file mode 100644
index 000000000..70f703dc1
--- /dev/null
+++ b/packages/app/tests/foundation/theme-text-contrast.browser.test.tsx
@@ -0,0 +1,725 @@
+import {
+ closeSearchPanel,
+ findNext,
+ openSearchPanel,
+ SearchQuery,
+ setSearchQuery,
+} from '@codemirror/search';
+import { EditorView } from '@codemirror/view';
+import { HocuspocusProvider } from '@hocuspocus/provider';
+import { sharedExtensions } from '@inkeep/open-knowledge-core/extensions/shared';
+import { tags } from '@lezer/highlight';
+import { FileTree } from '@pierre/trees';
+import { act, cleanup, waitFor } from '@testing-library/react';
+import { Editor } from '@tiptap/core';
+import { EditorContent } from '@tiptap/react';
+import axe from 'axe-core';
+import { ThemeProvider } from 'next-themes';
+import type { ReactElement } from 'react';
+import { createPortal } from 'react-dom';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest';
+import { commands, page } from 'vitest/browser';
+import * as Y from 'yjs';
+import { ActivityPanelDiffView } from '@/components/ActivityPanelDiffView';
+import { ConflictView } from '@/components/ConflictView';
+import { FileTreeEmptyState } from '@/components/FileTree';
+import { createFileTreeStyle, FILE_TREE_DENSITY_OPTIONS } from '@/components/file-tree-density';
+import { OK_FILE_TREE_READONLY_UNSAFE_CSS } from '@/components/file-tree-shared';
+import { MermaidDocEditor } from '@/components/MermaidDocEditor';
+import { ColorThemePicker } from '@/components/settings/ColorThemePicker';
+import { SettingsDialogShell } from '@/components/settings/SettingsDialogShell';
+import { TerminalPanel } from '@/components/TerminalPanel';
+import { TextDocEditor } from '@/components/TextDocEditor';
+import { TextViewer } from '@/components/TextViewer';
+import { Kbd } from '@/components/ui/kbd';
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
+import { CodeMirrorPropInput } from '@/editor/components/CodeMirrorPropInput';
+import { CodePreviewEditModal } from '@/editor/components/CodePreviewEditModal';
+import { DocumentProvider } from '@/editor/DocumentContext';
+import { evictCmEditor } from '@/editor/editor-cache';
+import { okSyntaxHighlight } from '@/editor/extensions/cm-theme';
+import { CodeBlockFidelity } from '@/editor/extensions/code-block';
+import { RawMdxFallback } from '@/editor/extensions/raw-mdx-fallback';
+import { SourceEditor } from '@/editor/SourceEditor';
+import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+import { stubApiRoutes } from './api-routes.test-helper';
+import { renderWithI18n } from './render-with-i18n.test-helper';
+import { textLeaves, textMeasurement } from './theme-contrast.test-helper';
+import { measuredBackgrounds as BACKGROUNDS } from './theme-text-backgrounds.test-helper';
+
+type ThemeCase = { id: string; mode: 'light' | 'dark' };
+const THEMES: ThemeCase[] = [
+ { id: 'default-light', mode: 'light' },
+ { id: 'default-dark', mode: 'dark' },
+];
+const CODE =
+ '// note\nconst retries = 3;\nconst config = { enabled: true };\nconst ready = "ready";\nfunction plan(value) { return true; }\n';
+const MARKDOWN = `# Release plan\n\n> quoted note\n\n[themed preview](https://example.test)\n\n\`\`\`javascript\n${CODE}\`\`\`\n`;
+const CONFIG: ConfigContextValue = {
+ userBinding: null,
+ userSynced: false,
+ projectBinding: null,
+ projectLocalBinding: null,
+ okignoreBinding: null,
+ okignoreSynced: false,
+ userConfig: null,
+ projectConfig: null,
+ projectLocalConfig: null,
+ projectSynced: false,
+ projectLocalSynced: false,
+ merged: null,
+};
+const disposers: (() => void)[] = [];
+let stylesheet: HTMLStyleElement;
+const AXE_INCOMPLETE_DISPOSITIONS: Record<string, string> = {
+ nonBmp: 'Axe cannot evaluate non-text fold glyphs; text leaves are measured separately.',
+ bgOverlap: 'Axe cannot infer xterm layered backgrounds; ordinary cells have pixel measurements.',
+};
+
+beforeAll(async () => {
+ stylesheet = document.createElement('style');
+ stylesheet.textContent = await commands.buildAppStylesheet();
+ document.head.append(stylesheet);
+});
+
+beforeEach(() => {
+ stubApiRoutes({
+ '/api/audit': () => Response.json({ entries: [], total: 0 }),
+ '/api/pages': () => Response.json({ pages: [] }),
+ '/api/documents': () => Response.json({ documents: [] }),
+ '/api/tags': () => Response.json({ tags: [] }),
+ '/api/lint/config': () => new Response(null, { status: 404 }),
+ });
+});
+
+afterEach(async () => {
+ const audit = await axe.run(document.body, { runOnly: ['color-contrast'] });
+ expect.soft(audit.violations).toEqual([]);
+ const undisposedIncomplete = audit.incomplete
+ .flatMap((result) => result.nodes.flatMap((node) => node.any))
+ .filter((check) => {
+ const messageKey =
+ check.data && typeof check.data === 'object' && 'messageKey' in check.data
+ ? check.data.messageKey
+ : null;
+ return typeof messageKey !== 'string' || !(messageKey in AXE_INCOMPLETE_DISPOSITIONS);
+ });
+ expect
+ .soft(undisposedIncomplete, 'axe incomplete results need an explicit disposition')
+ .toEqual([]);
+ cleanup();
+ for (const dispose of disposers.splice(0).reverse()) dispose();
+ delete document.documentElement.dataset.colorTheme;
+ document.documentElement.classList.remove('dark');
+ document.documentElement.style.removeProperty('color-scheme');
+ vi.unstubAllGlobals();
+});
+afterAll(() => stylesheet.remove());
+
+function applyTheme(theme: ThemeCase) {
+ document.documentElement.classList.toggle('dark', theme.mode === 'dark');
+ document.documentElement.style.colorScheme = theme.mode;
+ delete document.documentElement.dataset.colorTheme;
+}
+
+function mount(theme: ThemeCase, ui: ReactElement) {
+ applyTheme(theme);
+ return renderWithI18n(
+ <ThemeProvider
+ forcedTheme={theme.mode}
+ defaultTheme={theme.mode}
+ storageKey={`contrast-mode-${theme.id}`}
+ attribute="class"
+ enableSystem={false}
+ >
+ <ConfigContext value={CONFIG}>
+ <div
+ style={{
+ width: 900,
+ minHeight: 320,
+ background: 'var(--background)',
+ color: 'var(--foreground)',
+ }}
+ >
+ {ui}
+ </div>
+ </ConfigContext>
+ </ThemeProvider>,
+ );
+}
+
+function providerWithText(name: string, text: string) {
+ const document = new Y.Doc();
+ document.getText('source').insert(0, text);
+ const provider = new HocuspocusProvider({
+ url: 'ws://127.0.0.1:1',
+ name,
+ document,
+ autoConnect: false,
+ });
+ disposers.push(() => {
+ provider.destroy();
+ document.destroy();
+ });
+ return provider;
+}
+
+function checkReadings(
+ theme: ThemeCase,
+ surface: string,
+ readings: ReturnType<typeof textMeasurement>[],
+) {
+ const quantize = (value: number) => Math.round(value * 255) / 255;
+ expect(readings.length, `${surface} rendered text`).toBeGreaterThan(0);
+ const backgrounds = [
+ ...new Set(readings.map((reading) => JSON.stringify(reading.background.map(quantize)))),
+ ]
+ .sort()
+ .map((value: string) => JSON.parse(value) as number[]);
+ const expected = [
+ ...new Set(
+ (BACKGROUNDS[`${theme.id}/${surface}`] ?? []).map((background) =>
+ JSON.stringify(background.map(quantize)),
+ ),
+ ),
+ ]
+ .sort()
+ .map((value: string) => JSON.parse(value) as number[]);
+ expect.soft(backgrounds, `${theme.id} ${surface} preserves its backgrounds`).toEqual(expected);
+ for (const reading of readings) {
+ expect
+ .soft(
+ reading.ratio,
+ `${theme.id} ${surface} ${reading.text}: ${reading.foreground} on ${JSON.stringify(reading.background)}`,
+ )
+ .toBeGreaterThanOrEqual(4.5);
+ }
+ return readings;
+}
+
+function checkText(theme: ThemeCase, surface: string, elements: Element[], overlay?: Element) {
+ return checkReadings(
+ theme,
+ surface,
+ elements.map((element) => textMeasurement(element, overlay)),
+ );
+}
+
+async function cmView(container: Element): Promise<EditorView> {
+ return waitFor(() => {
+ const content = container.querySelector<HTMLElement>('.cm-content');
+ expect(content).toBeTruthy();
+ if (!content) throw new Error('CodeMirror content did not render');
+ const view = EditorView.findFromDOM(content);
+ if (!view) throw new Error('CodeMirror view unavailable');
+ return view;
+ });
+}
+
+async function settleCodeMirror(view: EditorView): Promise<void> {
+ await new Promise<void>((resolve) =>
+ view.requestMeasure({ read: () => undefined, write: () => queueMicrotask(resolve) }),
+ );
+}
+
+async function highlighted(container: HTMLElement, text: string, semanticClass?: string | null) {
+ return waitFor(() => {
+ const leaf = textLeaves(container).find(
+ (element) =>
+ element.tagName === 'SPAN' &&
+ element.textContent === text &&
+ (!semanticClass ||
+ semanticClass.split(' ').every((name) => element.classList.contains(name))),
+ );
+ expect(leaf, `highlighted ${text}`).toBeTruthy();
+ if (!leaf) throw new Error(`Missing rendered ${text}`);
+ return leaf;
+ });
+}
+
+function makeRichEditor() {
+ const editor = new Editor({
+ extensions: sharedExtensions.map((extension) =>
+ extension.name === 'codeBlock'
+ ? CodeBlockFidelity
+ : extension.name === 'rawMdxFallback'
+ ? RawMdxFallback
+ : extension,
+ ),
+ content: {
+ type: 'doc',
+ content: [
+ { type: 'paragraph', content: [{ type: 'text', text: 'Release plan' }] },
+ {
+ type: 'blockquote',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'quoted note' }] }],
+ },
+ {
+ type: 'codeBlock',
+ attrs: { language: 'javascript' },
+ content: [{ type: 'text', text: CODE }],
+ },
+ {
+ type: 'rawMdxFallback',
+ attrs: { reason: 'Parse failed' },
+ content: [{ type: 'text', text: '<Foo>broken</Bar>' }],
+ },
+ ],
+ },
+ });
+ disposers.push(() => editor.destroy());
+ return editor;
+}
+
+function richEditorPortal(editor: Editor) {
+ const target = document.createElement('div');
+ target.className = 'tiptap-editor-portal-content';
+ const content = createPortal(
+ // oxlint-disable-next-line ok/no-unportaled-editor-content -- This fixture gives each editor an exclusive portal target.
+ <EditorContent editor={editor} />,
+ target,
+ );
+ return (
+ <>
+ <div
+ className="tiptap-editor"
+ ref={(element) => {
+ element?.append(target);
+ }}
+ />
+ {content}
+ </>
+ );
+}
+
+function terminalBridge(): OkDesktopBridge {
+ const terminal = {
+ adopt: async () => ({
+ ok: true as const,
+ replay: 'Plain text\r\n\x1b[90mBright black\x1b[0m\r\n\x1b[31mRed text\x1b[0m\r\n',
+ }),
+ input: () => {},
+ resize: () => {},
+ drain: () => {},
+ kill: async () => {},
+ onData: () => () => {},
+ onExit: () => () => {},
+ onNotice: () => () => {},
+ };
+ return {
+ terminal,
+ config: { e2eSmoke: true, projectPath: '/contrast-fixture' },
+ platform: 'darwin',
+ } as unknown as OkDesktopBridge;
+}
+
+describe('rendered theme text contrast', () => {
+ test('measurement oracle resolves reference sRGB and Oklch pairs', () => {
+ const fixtures = [
+ ['#ffffff', '#000000', 21],
+ ['#3e4b59', '#131721', 2.0094635187573844],
+ ['oklch(0.553 0.013 58.071)', 'oklch(0.97 0 0)', 4.407529],
+ ] as const;
+ for (const [foreground, background, expected] of fixtures) {
+ const element = document.createElement('span');
+ element.textContent = 'reference';
+ element.style.color = foreground;
+ element.style.backgroundColor = background;
+ document.body.append(element);
+ try {
+ const reading = textMeasurement(element);
+ expect(reading.ratio).toBeCloseTo(expected, 5);
+ } finally {
+ element.remove();
+ }
+ }
+ });
+ for (const theme of THEMES) {
+ test(`${theme.id} source text stays readable through active search and selection states`, async () => {
+ const name = `contrast-${theme.id}.md`;
+ const provider = providerWithText(name, MARKDOWN);
+ disposers.push(() => evictCmEditor(name));
+ const { container } = mount(
+ theme,
+ <SourceEditor
+ docName={name}
+ ytext={provider.document.getText('source')}
+ provider={provider}
+ isSourceModeActive={true}
+ />,
+ );
+ const view = await cmView(container);
+ await waitFor(() =>
+ expect(view.state.facet(EditorView.darkTheme)).toBe(theme.mode === 'dark'),
+ );
+ await highlighted(container, '// note', okSyntaxHighlight.style([tags.comment]));
+ await settleCodeMirror(view);
+ checkText(theme, 'source', textLeaves(view.contentDOM));
+ const audit = await axe.run(view.contentDOM, { runOnly: ['color-contrast'] });
+ expect.soft(audit.violations, `${theme.id} source contrast audit`).toEqual([]);
+ const start = MARKDOWN.indexOf('// note');
+ await act(async () => {
+ view.dispatch({ selection: { anchor: start } });
+ view.focus();
+ });
+ await waitFor(() =>
+ expect(container.querySelector('.cm-activeLine')?.textContent).toContain('// note'),
+ );
+ await settleCodeMirror(view);
+ checkText(theme, 'source-active', textLeaves(view.contentDOM));
+ checkText(
+ theme,
+ 'source-gutter',
+ textLeaves(view.dom.querySelector('.cm-gutters') as Element).filter(
+ (element) => !element.closest('[style*="visibility: hidden"]'),
+ ),
+ );
+ await act(async () => {
+ openSearchPanel(view);
+ view.dispatch({ effects: setSearchQuery.of(new SearchQuery({ search: 'note' })) });
+ findNext(view);
+ });
+ await waitFor(() => {
+ expect(container.querySelectorAll('.cm-searchMatch').length).toBeGreaterThan(0);
+ const searchInput = view.dom.querySelector('.cm-search input[main-field]');
+ expect(searchInput).not.toBeNull();
+ expect(document.activeElement).toBe(searchInput);
+ expect(view.hasFocus).toBe(false);
+ expect(view.dom.matches('.cm-focused')).toBe(false);
+ });
+ await settleCodeMirror(view);
+ for (const element of textLeaves(view.contentDOM)) {
+ expect(textMeasurement(element).ratio, `${theme.id} search match`).toBeGreaterThanOrEqual(
+ 4.5,
+ );
+ }
+ await act(async () => {
+ closeSearchPanel(view);
+ view.dispatch({ effects: setSearchQuery.of(new SearchQuery({ search: '' })) });
+ });
+ });
+
+ test(`${theme.id} rich code prose and raw MDX text are readable`, async () => {
+ const editor = makeRichEditor();
+ const { container } = mount(theme, richEditorPortal(editor));
+ await highlighted(container, '// note');
+ await waitFor(() =>
+ expect(container.querySelector('.raw-mdx-fallback-cm .cm-line')).toBeTruthy(),
+ );
+ await settleCodeMirror(await cmView(container));
+ const rich = container.querySelector('.ProseMirror');
+ if (!rich) throw new Error('Rich editor did not mount');
+ checkText(
+ theme,
+ 'rich-and-raw-mdx',
+ textLeaves(rich).filter((element) => !element.closest('button')),
+ );
+ });
+
+ test(`${theme.id} markdown in the text viewer keeps its structure styling`, async () => {
+ const { container } = mount(
+ theme,
+ <section style={{ height: 160 }}>
+ <TextViewer
+ fileName="SKILL.md"
+ extension=".md"
+ loadText={async () => ({
+ ok: true,
+ text: '# Release plan\n\n*gently*\n\n**care**\n\n[the guide](https://example.test)\n',
+ })}
+ />
+ </section>,
+ );
+ const view = await cmView(container);
+ const leaf = (text: string) =>
+ waitFor(() => {
+ const element = textLeaves(view.contentDOM).find(
+ (candidate) => candidate.textContent?.trim() === text,
+ );
+ expect(element, `rendered ${text}`).toBeTruthy();
+ return element as Element;
+ });
+ const heading = await leaf('Release plan');
+ const emphasis = await leaf('gently');
+ const strong = await leaf('care');
+ const link = await leaf('the guide');
+ await settleCodeMirror(view);
+ expect(Number(getComputedStyle(heading).fontWeight)).toBeGreaterThanOrEqual(700);
+ expect(getComputedStyle(emphasis).fontStyle).toBe('italic');
+ expect(Number(getComputedStyle(strong).fontWeight)).toBeGreaterThanOrEqual(700);
+ expect(getComputedStyle(link).textDecorationLine).toContain('underline');
+ for (const element of textLeaves(view.contentDOM))
+ expect
+ .soft(
+ textMeasurement(element).ratio,
+ `${theme.id} viewer markdown ${element.textContent}`,
+ )
+ .toBeGreaterThanOrEqual(4.5);
+ });
+
+ test(`${theme.id} text document Mermaid source viewer and property text are readable`, async () => {
+ const textProvider = providerWithText(`contrast-${theme.id}.js`, CODE);
+ const mermaidProvider = providerWithText(
+ `contrast-${theme.id}.mmd`,
+ '%% note\ngraph TD\nA[Ready] --> B[Ship]\n',
+ );
+ const { container } = mount(
+ theme,
+ <>
+ <section data-contrast="text-doc" style={{ height: 160 }}>
+ <TextDocEditor docName={`contrast-${theme.id}.js`} provider={textProvider} />
+ </section>
+ <section data-contrast="mermaid" style={{ height: 160 }}>
+ <MermaidDocEditor
+ docName={`contrast-${theme.id}.mmd`}
+ provider={mermaidProvider}
+ isSourceMode={true}
+ />
+ </section>
+ <section data-contrast="viewer" style={{ height: 160 }}>
+ <TextViewer
+ fileName="view.js"
+ extension=".js"
+ loadText={async () => ({ ok: true, text: CODE })}
+ />
+ </section>
+ <section data-contrast="property">
+ <CodeMirrorPropInput value={CODE} language="javascript" onChange={() => {}} />
+ </section>
+ </>,
+ );
+ await waitFor(() => expect(container.querySelectorAll('.cm-editor').length).toBe(4));
+ for (const surface of ['text-doc', 'mermaid', 'viewer', 'property']) {
+ const section = container.querySelector(`[data-contrast="${surface}"]`);
+ if (!section) throw new Error(`Missing ${surface}`);
+ await waitFor(() =>
+ expect(section.querySelectorAll('.cm-line span').length).toBeGreaterThan(0),
+ );
+ await settleCodeMirror(await cmView(section));
+ checkText(theme, surface, textLeaves(section));
+ }
+ });
+
+ test(`${theme.id} file tree hover text is readable`, async () => {
+ const { container } = mount(theme, <div data-contrast="tree" style={{ height: 200 }} />);
+ const wrapper = container.querySelector('[data-contrast="tree"]') as HTMLElement;
+ const tree = new FileTree({
+ ...FILE_TREE_DENSITY_OPTIONS,
+ unsafeCSS: OK_FILE_TREE_READONLY_UNSAFE_CSS,
+ paths: ['note.md'],
+ initialExpansion: 'open',
+ });
+ disposers.push(() => tree.cleanUp());
+ tree.render({ containerWrapper: wrapper });
+ const host = tree.getFileTreeContainer();
+ if (!host) throw new Error('Tree did not mount');
+ for (const [key, value] of Object.entries(createFileTreeStyle(theme.mode)))
+ host.style.setProperty(key, String(value));
+ const root = host.shadowRoot;
+ if (!root) throw new Error('Tree shadow root missing');
+ const label = await waitFor(() => {
+ const element = root.querySelector('[role="treeitem"]');
+ expect(element).toBeTruthy();
+ if (!element) throw new Error('Tree label did not render');
+ return element;
+ });
+ await page.elementLocator(label).hover();
+ checkText(theme, 'tree-hover', textLeaves(root));
+ await page.elementLocator(label).click();
+ await waitFor(() => expect(root.querySelector('[aria-selected="true"]')).toBeTruthy());
+ for (const element of textLeaves(root))
+ expect(textMeasurement(element).ratio).toBeGreaterThanOrEqual(4.5);
+ });
+
+ test(`${theme.id} empty file tree text is readable`, async () => {
+ const { container } = mount(
+ theme,
+ <FileTreeEmptyState
+ active={false}
+ onDragOver={() => {}}
+ onDragLeave={() => {}}
+ onDrop={() => {}}
+ onCreate={() => {}}
+ />,
+ );
+ await waitFor(() => expect(container.textContent).toContain('No files yet.'));
+ const empty = container.querySelector('.file-tree-empty-text');
+ expect(empty).not.toBeNull();
+ if (!empty) throw new Error('Empty file tree did not render');
+ expect(textMeasurement(empty).ratio).toBeGreaterThanOrEqual(4.5);
+ });
+
+ test(`${theme.id} changed diff words and gutters are readable`, async () => {
+ const { container } = mount(
+ theme,
+ <ActivityPanelDiffView
+ before={'context line\nold value\nlast line\n'}
+ after={'context line\nnew value\nlast line\n'}
+ cacheKey={`contrast-${theme.id}`}
+ />,
+ );
+ const root = await waitFor(() => {
+ const root = container.querySelector('diffs-container')?.shadowRoot;
+ expect(root?.querySelector('[data-line]')).toBeTruthy();
+ if (!root) throw new Error('Diff did not render');
+ return root;
+ });
+ checkText(theme, 'diff', textLeaves(root));
+ });
+
+ test(`${theme.id} code modal text and gutters are readable`, async () => {
+ const { getByRole } = mount(
+ theme,
+ <CodePreviewEditModal
+ open={true}
+ onOpenChange={() => {}}
+ initialValue={CODE}
+ language="javascript"
+ title="Code fixture"
+ onSave={() => {}}
+ />,
+ );
+ const dialog = getByRole('dialog');
+ await Promise.all(
+ dialog.getAnimations({ subtree: true }).map((animation) => animation.finished),
+ );
+ await highlighted(dialog, '// note');
+ const editor = dialog.querySelector('.ok-codepreview-cm');
+ if (!editor) throw new Error('Code modal did not render');
+ await settleCodeMirror(await cmView(editor));
+ checkText(theme, 'code-modal', textLeaves(editor));
+ });
+
+ test(`${theme.id} syntax highlighted conflict text is readable`, async () => {
+ const { container } = mount(
+ theme,
+ <ConflictView
+ fileName="plan.js"
+ base={CODE}
+ ours={CODE.replace('"ready"', '"ours"')}
+ theirs={CODE.replace('"ready"', '"theirs"')}
+ onResolve={() => {}}
+ />,
+ );
+ const root = await waitFor(() => {
+ const root = container.querySelector('diffs-container')?.shadowRoot;
+ expect(root?.querySelector('[data-line] span')).toBeTruthy();
+ if (!root) throw new Error('Conflict did not render');
+ return root;
+ });
+ checkText(theme, 'conflict-syntax', textLeaves(root));
+ });
+
+ test(`${theme.id} theme picker text and identifying icons have contrast`, async () => {
+ const { container } = mount(
+ theme,
+ <ColorThemePicker
+ selection={{ light: 'default', dark: 'default' }}
+ onAssign={() => {}}
+ slotMode={theme.mode}
+ aria-label="Color theme"
+ />,
+ );
+ const leaves = textLeaves(container);
+ const icons = Array.from(container.querySelectorAll('button svg'));
+ expect(leaves.length).toBeGreaterThan(0);
+ expect(icons.length).toBeGreaterThan(0);
+ expect(container.querySelectorAll('[data-state="off"] svg').length).toBeGreaterThan(0);
+ for (const element of leaves)
+ expect(textMeasurement(element).ratio).toBeGreaterThanOrEqual(4.5);
+ for (const icon of icons) expect(textMeasurement(icon).ratio).toBeGreaterThanOrEqual(3);
+ const toggle = container.querySelector<HTMLElement>('button[data-state="off"]');
+ if (!toggle) throw new Error('Unpressed slot toggle did not render');
+ const probe = document.createElement('span');
+ probe.style.color = 'var(--foreground)';
+ container.append(probe);
+ const foreground = getComputedStyle(probe).color;
+ probe.remove();
+ expect(getComputedStyle(toggle).color).not.toBe(foreground);
+ await page.elementLocator(toggle).hover();
+ await waitFor(() => expect(getComputedStyle(toggle).color).toBe(foreground));
+ });
+
+ test(`${theme.id} keyboard hint chips are readable`, async () => {
+ const { container } = mount(
+ theme,
+ <div>
+ <Kbd>Ctrl</Kbd>
+ <Kbd>K</Kbd>
+ </div>,
+ );
+ const chips = Array.from(container.querySelectorAll('[data-slot="kbd"]'));
+ expect(chips.length).toBe(2);
+ for (const chip of chips)
+ expect(textMeasurement(chip).ratio, chip.textContent ?? '').toBeGreaterThanOrEqual(4.5);
+ });
+
+ test(`${theme.id} keyboard hint chips inside an open tooltip are readable`, async () => {
+ mount(
+ theme,
+ <TooltipProvider>
+ <Tooltip open>
+ <TooltipTrigger>Search</TooltipTrigger>
+ <TooltipContent>
+ Search
+ <Kbd>Ctrl K</Kbd>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>,
+ );
+ const chip = await waitFor(() => {
+ const element = document.body.querySelector(
+ '[data-slot="tooltip-content"] [data-slot="kbd"]',
+ );
+ expect(element).not.toBeNull();
+ return element as HTMLElement;
+ });
+ const content = chip.closest('[data-slot="tooltip-content"]');
+ if (!content) throw new Error('Tooltip content did not render');
+ await Promise.all(
+ content.getAnimations({ subtree: true }).map((animation) => animation.finished),
+ );
+ expect(textMeasurement(chip).ratio, chip.textContent ?? '').toBeGreaterThanOrEqual(4.5);
+ });
+
+ test(`${theme.id} settings navigation group titles are readable`, async () => {
+ mount(
+ theme,
+ <DocumentProvider>
+ <SettingsDialogShell open onOpenChange={() => {}} />
+ </DocumentProvider>,
+ );
+ const titles = await waitFor(() => {
+ const elements = Array.from(
+ document.body.querySelectorAll<HTMLElement>('.settings-sidebar-group-title'),
+ );
+ expect(elements.length).toBeGreaterThan(0);
+ return elements;
+ });
+ expect(titles[0]?.closest('[data-slot="dialog-content"]')).toBeTruthy();
+ const readings = await waitFor(() => titles.map((title) => textMeasurement(title)));
+ for (const reading of readings) {
+ expect(
+ reading.ratio,
+ `${reading.text}: ${reading.foreground} on ${reading.background.join(', ')}`,
+ ).toBeGreaterThanOrEqual(4.5);
+ }
+ });
+
+ test(`${theme.id} terminal ordinary cells are readable`, async () => {
+ const { container } = mount(
+ theme,
+ <div style={{ height: 280 }}>
+ <TerminalPanel bridge={terminalBridge()} adoptPtyId="contrast-terminal" />
+ </div>,
+ );
+ await waitFor(() =>
+ expect(container.querySelector('.xterm-rows')?.textContent).toContain('Red text'),
+ );
+ const rows = container.querySelector('.xterm-rows');
+ if (!rows) throw new Error('Terminal did not render');
+ checkText(theme, 'terminal', textLeaves(rows));
+ });
+ }
+});