8000 Dark scheme and the Light | Dark | System choice by kiran-brahma · Pull Request #81 · kiran-brahma/writing-tool · GitHub
[go: up one dir, main page]

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
4 changes: 3 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#1c1917" />
<meta name="color-scheme" content="light dark" />
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#fafaf9" />
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#191816" />
<link rel="manifest" href="/manifest.webmanifest" />
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
<title>Obelus</title>
Expand Down
2 changes: 2 additions & 0 deletions scripts/agent-gates.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { checkForbiddenAffordances } from "./gates/affordances.mjs";
import { checkSecurityHeaderParity } from "./gates/headers.mjs";
import { checkImports } from "./gates/imports.mjs";
import { checkLockfileDrift } from "./gates/lockfile.mjs";
import { checkPaletteClasses } from "./gates/palette.mjs";
import { PNPM_LOCK_FILE, readPnpmLock } from "./gates/pnpm-lock.mjs";
import { collectSourceFiles } from "./gates/scan.mjs";
import { checkSilentCatches } from "./gates/silent-catch.mjs";
Expand All @@ -30,6 +31,7 @@ function runChecks() {
],
["no silent catch", checkSilentCatches({ files, repoRoot: REPO_ROOT })],
["no forbidden affordance in the UI source", checkForbiddenAffordances({ files, repoRoot: REPO_ROOT })],
["no palette colour class in the UI source", checkPaletteClasses({ files, repoRoot: REPO_ROOT })],
["no Worker route to a provider", checkNoProviderRoute({ files, repoRoot: REPO_ROOT })],
["the reference Vercel config carries the Worker's Content-Security-Policy", checkSecurityHeaderParity({ repoRoot: REPO_ROOT })],
["lockfile in sync", checkLockfileDrift(packageJson, lock)],
Expand Down
140 changes: 140 additions & 0 deletions scripts/gates/palette.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import { readFileSync } from "node:fs";
import ts from "typescript";
import { finding, parseSource, toRepoPath, walk } from "./scan.mjs";

/**
* Build gate: colour by name, never by palette step (spec v1.3, stories
* 201–210).
*
* Every colour the UI draws is a name defined in `src/index.css` — paper, ink,
* muted ink, mark, warning, failure — with a light and a dark value. A palette
* class such as `bg-stone-100` or `text-white` has only one value, so a single
* one left in a component is a patch that stays light in the dark scheme. This
* reads the UI source's string literals, where class names live, and fails the
* build on any palette class or palette variable, whatever its variant or
* opacity. The fix is the name the table in `src/index.css` gives.
*/

const PALETTE_HUES = [
"slate",
"gray",
"zinc",
"neutral",
"stone",
"red",
"orange",
"amber",
"yellow",
"lime",
"green",
"emerald",
"teal",
"cyan",
"sky",
"blue",
"indigo",
"violet",
"purple",
"fuchsia",
"pink",
"rose",
"mauve",
"olive",
"mist",
"taupe",
];

const PALETTE_STEPS = "(?:50|[1-9]00|950)";

/** Every utility that takes a colour. */
const COLOR_UTILITIES = [
"bg",
"text",
"border",
"border-[xytrblse]",
"border-b[se]",
"divide",
"outline",
"ring",
"ring-offset",
"inset-ring",
"shadow",
"inset-shadow",
"drop-shadow",
"text-shadow",
"decoration",
"accent",
"caret",
"fill",
"stroke",
"from",
"via",
"to",
"placeholder",
];

const PALETTE_COLOR = `(?:(?:${PALETTE_HUES.join("|")})-${PALETTE_STEPS}|white|black)`;

/** One class token, once its variants, `!` and opacity are stripped. */
const PALETTE_CLASS = new RegExp(`^-?(?:${COLOR_UTILITIES.join("|")})-${PALETTE_COLOR}$`);

/** A palette variable, as in `bg-(--color-stone-100)` or `var(--color-white)`. */
const PALETTE_VARIABLE = new RegExp(`--color-${PALETTE_COLOR}(?![\\w-])`);

/** UI source: the app's `.ts` and `.tsx` modules, where a class name can be built. */
export function isUiSource(repoPath) {
return (
repoPath.startsWith("src/") &&
(repoPath.endsWith(".tsx") || repoPath.endsWith(".ts")) &&
!repoPath.includes(".test.")
);
}

/** The palette colour a class token names, or null. */
export function paletteClass(token) {
if (PALETTE_VARIABLE.test(token)) return token;
// Variants (`hover:`, `dark:`, `focus-visible:`) end at the last colon.
const utility = token.slice(token.lastIndexOf(":") + 1).replace(/^!|!$/g, "");
const withoutOpacity = utility.replace(/\/[\w.[\]%-]+$/, "");
return PALETTE_CLASS.test(withoutOpacity) ? token : null;
}

/** Palette classes in one file's string literals, with their line. */
export function findPaletteClasses(sourceText, fileName) {
const sourceFile = parseSource(sourceText, fileName);
const findings = [];

walk(sourceFile, (node) => {
if (
!ts.isStringLiteral(node) &&
!ts.isNoSubstitutionTemplateLiteral(node) &&
!ts.isTemplateHead(node) &&
!ts.isTemplateMiddle(node) &&
!ts.isTemplateTail(node)
) {
return;
}
for (const token of node.text.split(/\s+/)) {
const match = paletteClass(token);
if (match === null) continue;
findings.push(
finding(
fileName,
sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1,
`palette colour "${match}": use a colour name from src/index.css, which has a dark value.`,
),
);
}
});

return findings;
}

/** The palette gate over every UI source file. */
export function checkPaletteClasses({ files, repoRoot }) {
return files.flatMap((file) => {
const repoPath = toRepoPath(repoRoot, file);
if (!isUiSource(repoPath)) return [];
return findPaletteClasses(readFileSync(file, "utf8"), repoPath);
});
}
113 changes: 113 additions & 0 deletions scripts/gates/palette.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { checkPaletteClasses, findPaletteClasses, isUiSource, paletteClass } from "./palette.mjs";

describe("isUiSource", () => {
it("scans the app's components and modules", () => {
expect(isUiSource("src/App.tsx")).toBe(true);
expect(isUiSource("src/editor/railClasses.ts")).toBe(true);
});

it("skips tests and everything outside the app", () => {
expect(isUiSource("src/editor/FindingsSidebar.test.tsx")).toBe(false);
expect(isUiSource("src/core/pass.test.ts")).toBe(false);
expect(isUiSource("scripts/gates/palette.mjs")).toBe(false);
expect(isUiSource("worker/index.ts")).toBe(false);
});
});

describe("paletteClass", () => {
it.each([
"bg-stone-100",
"text-amber-900",
"border-t-stone-700",
"divide-stone-200",
"ring-stone-600",
"ring-offset-white",
"decoration-rose-500",
"bg-white",
"text-black",
"hover:bg-stone-100",
"dark:focus-visible:ring-red-600",
"bg-stone-100/60",
"!text-red-700",
"bg-(--color-stone-100)",
"fill-[var(--color-amber-200)]",
])("flags %s", (token) => {
expect(paletteClass(token)).toBe(token);
});

it.each([
"bg-paper",
"text-muted-ink",
"border-warning-rule",
"hover:bg-sunk/60",
"ring-offset-2",
"ring-2",
"text-sm",
"border-t",
"rounded-full",
"bg-stone",
"text-stone-1000",
"whitespace",
"--color-paper",
])("passes %s", (token) => {
expect(paletteClass(token)).toBeNull();
});
});

describe("findPaletteClasses", () => {
it("catches a palette class in a className string", () => {
const source = 'export const X = () => (\n <p className="px-2 text-stone-500">x</p>\n);\n';
expect(findPaletteClasses(source, "X.tsx")).toEqual([
expect.objectContaining({ file: "X.tsx", line: 2 }),
]);
});

it("catches one in a class list built in a template or an array", () => {
const source = [
"const a = `rounded ${on ? 'bg-ink' : 'bg-amber-50'}`;",
"const b = [active ? 'text-on-ink' : 'text-stone-600', `px-2 ${side} border-t-stone-300`];",
"const c = `${x} hover:bg-white`;",
].join("\n");
expect(findPaletteClasses(source, "X.tsx").map((entry) => entry.line)).toEqual([1, 2, 2, 3]);
});

it("passes classes written with colour names", () => {
const source =
'<button className="rounded bg-ink text-on-ink hover:bg-quiet-ink focus-visible:ring-2 focus-visible:ring-focus focus-visible:ring-offset-2" />';
expect(findPaletteClasses(source, "X.tsx")).toEqual([]);
});

it("does not flag a comment that names a palette class", () => {
const source = "// was bg-stone-100 before the colour names\nconst x = 'bg-sunk';\n";
expect(findPaletteClasses(source, "X.tsx")).toEqual([]);
});
});

describe("checkPaletteClasses", () => {
let repoRoot;

afterEach(() => {
if (repoRoot !== undefined) {
rmSync(repoRoot, { recursive: true, force: true });
repoRoot = undefined;
}
});

it("scans UI source and skips a test", () => {
repoRoot = mkdtempSync(join(tmpdir(), "palette-"));
mkdirSync(join(repoRoot, "src"), { recursive: true });
const component = join(repoRoot, "src", "Notice.tsx");
const test = join(repoRoot, "src", "Notice.test.tsx");
writeFileSync(component, 'export const N = () => <p className="bg-amber-50">x</p>;');
writeFileSync(test, "expect(className).toContain('bg-amber-50');\n");

const findings = checkPaletteClasses({ files: [component, test], repoRoot });

expect(findings).toHaveLength(1);
expect(findings[0]).toMatchObject({ file: "src/Notice.tsx", line: 1 });
});
});
6 changes: 6 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { SCRATCHPAD_DOCUMENT_ID } from "./storage/documents";
import { describeError } from "./errors";
import { useDocument } from "./useDocument";
import { AiSettingsView } from "./settings/AiSettingsView";
import { useColorScheme } from "./settings/useColorScheme";
import { WorkbenchView } from "./workbench/WorkbenchView";
import { DocumentMenu } from "./DocumentMenu";
import {
Expand Down Expand Up @@ -92,7 +93,10 @@ export default function App() {
judgeIsDefault,
firstRunNoteDismissed,
dismissFirstRunNote,
colorScheme,
setColorScheme,
} = handle;
useColorScheme(colorScheme);
const [milestoneNote, setMilestoneNote] = useState("");
const [milestonesOnly, setMilestonesOnly] = useState(false);
/** Story 20 & 190: persistent destinations; the Editor is the default. */
Expand Down Expand Up @@ -510,6 +514,7 @@ export default function App() {
characterLimit={characterLimit}
voiceList={voiceList}
priceTable={priceTable}
colorScheme={colorScheme}
=> void saveConnection(connection)}
=> void addCustomConnection()}
=> void removeConnection(connectionId)}
Expand All @@ -518,6 +523,7 @@ export default function App() {
=> void setCharacterLimit(limit)}
=> void setVoiceList(entries)}
=> void savePriceTable(table)}
=> void setColorScheme(setting)}
>
/>
)}
Expand Down
49 changes: 49 additions & 0 deletions src/core/colorScheme.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { describe, expect, it } from "vitest";
import {
COLOR_SCHEME_SETTINGS,
isColorSchemeSetting,
resolveColorScheme,
type ColorScheme,
type ColorSchemeSetting,
} from "./colorScheme";

describe("resolveColorScheme", () => {
const table: [ColorSchemeSetting, boolean, ColorScheme][] = [
["system", false, "light"],
["system", true, "dark"],
["light", false, "light"],
["light", true, "light"],
["dark", false, "dark"],
["dark", true, "dark"],
];

it.each(table)("resolves %s with the system preferring dark=%s to %s", (setting, dark, scheme) => {
expect(resolveColorScheme(setting, dark)).toBe(scheme);
});

it("covers every setting the Writer can choose", () => {
expect(new Set(table.map(([setting]) => setting))).toEqual(
new Set(COLOR_SCHEME_SETTINGS.map((entry) => entry.setting)),
);
});
});

describe("the colour scheme choice", () => {
it("offers Light, Dark and System, in that order", () => {
expect(COLOR_SCHEME_SETTINGS).toEqual([
{ setting: "light", label: "Light" },
{ setting: "dark", label: "Dark" },
{ setting: "system", label: "System" },
]);
});

it("recognises only the three settings", () => {
expect(isColorSchemeSetting("light")).toBe(true);
expect(isColorSchemeSetting("dark")).toBe(true);
expect(isColorSchemeSetting("system")).toBe(true);
expect(isColorSchemeSetting("Dark")).toBe(false);
expect(isColorSchemeSetting("sepia")).toBe(false);
expect(isColorSchemeSetting(undefined)).toBe(false);
expect(isColorSchemeSetting(true)).toBe(false);
});
});
Loading
0