Skip to content

armgit / cogit

Public Imported from GitHub
0

Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.

feat(map): draw diagrams in the map's light and dark palette

Eren9a6e54378b5d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 84c32e0..5711fef 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Diagrams take their colours from the map's palette: the light and dark themes each render a diagram in their own colours, including in the Shape's Open window and the panel preview, and switching the theme repaints an open diagram in place.
- A diagram in the Shape's Open window opens fitted to the window and can be dragged, zoomed with the wheel or the **−** / **Fit** / **+** buttons, moved with the arrow keys and fitted again with a double-click, instead of being read through a horizontal scrollbar.
- Captured work: `cogit captures` and the map's **Captured** list gather what the sessions left open — each session's pending items and each branch summary's open line — with the source message, who recorded it and how old it is; items waiting for you come first. Read-only and derived from the record; cogit keeps no planning state.
diff --git a/docs/guide/map.md b/docs/guide/map.md
index 0305c85..16309bf 100644
--- a/docs/guide/map.md
+++ b/docs/guide/map.md
@@ -110,7 +110,8 @@ The message details show a short preview and an **Open** button. Open shows the
with 1/2/3 tabs (the number keys work too), starting on Shape. A message with nothing
recorded yet says "being prepared"; with `shapes` off, it says so. In the Open window a wide
diagram opens fitted to the window: drag it to move it, use the wheel or **−** / **Fit** / **+**
-to zoom, the arrow keys to move it, and double-click to fit it again.
+to zoom, the arrow keys to move it, and double-click to fit it again. Diagrams follow the
+map's light and dark theme.
diff --git a/packages/template/src/MermaidDiagram.tsx b/packages/template/src/MermaidDiagram.tsx
index 964daa6..4a8df09 100644
--- a/packages/template/src/MermaidDiagram.tsx
+++ b/packages/template/src/MermaidDiagram.tsx
@@ -6,7 +6,9 @@ import {
useRef,
useState,
} from "react";
+import { type DiagramTheme, effectiveTheme, mermaidThemeVariables } from "./diagramTheme.js";
import { clampPan, fitView, type PanView, type Size, zoomAt } from "./panZoom.js";
+import { getTheme, subscribeTheme, type ThemeMode } from "./theme.js";
/**
* Draws a Mermaid flowchart (Story 13.6). Mermaid is ~3.5 MB, so it is not
@@ -44,15 +46,7 @@ function loadMermaid(): Promise<Mermaid> {
script.onload = () => {
const mermaid = window.mermaid;
if (mermaid === undefined) reject(new Error("mermaid did not load"));
- else {
- mermaid.initialize({
- startOnLoad: false,
- securityLevel: "strict",
- theme: "neutral",
- fontFamily: "inherit",
- });
- resolve(mermaid);
- }
+ else resolve(mermaid);
};
script.onerror = () => {
loading = undefined;
@@ -63,6 +57,25 @@ function loadMermaid(): Promise<Mermaid> {
return loading;
}
+/** One of the page's colour tokens, or `undefined` when it is missing. */
+function readToken(name: string): string | undefined {
+ if (typeof document === "undefined") return undefined;
+ const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
+ return value === "" ? undefined : value;
+}
+
+/** The palette the page is showing right now (Story 14.3). */
+function pageTheme(): DiagramTheme {
+ if (typeof document === "undefined") return "dark";
+ const marked = document.documentElement.dataset.theme;
+ const mode: ThemeMode = marked === "light" || marked === "dark" ? marked : getTheme();
+ const prefersDark =
+ typeof window !== "undefined" &&
+ typeof window.matchMedia === "function" &&
+ window.matchMedia("(prefers-color-scheme: dark)").matches;
+ return effectiveTheme(mode, prefersDark);
+}
+
let seq = 0;
/**
@@ -103,6 +116,7 @@ export function MermaidDiagram({
const host = useRef<HTMLDivElement>(null);
const viewport = useRef<HTMLDivElement>(null);
const [failed, setFailed] = useState(false);
+ const [theme, setTheme] = useState<DiagramTheme>(pageTheme);
const [view, setView] = useState<PanView>({ x: 0, y: 0, scale: 1 });
const [dragging, setDragging] = useState(false);
const drag = useRef<{ id: number; x: number; y: number } | null>(null);
@@ -132,13 +146,40 @@ export function MermaidDiagram({
[sizes],
);
+ // The theme switch (and the system preference while on System) repaints the
+ // diagrams in place; the Mermaid already loaded is reused, never fetched again.
+ useEffect(() => {
+ const update = () => setTheme(pageTheme());
+ update();
+ const unsubscribe = subscribeTheme(update);
+ const media =
+ typeof window !== "undefined" && typeof window.matchMedia === "function"
+ ? window.matchMedia("(prefers-color-scheme: dark)")
+ : undefined;
+ media?.addEventListener("change", update);
+ return () => {
+ unsubscribe();
+ media?.removeEventListener("change", update);
+ };
+ }, []);
+
useEffect(() => {
if (!available) return;
let cancelled = false;
setFailed(false);
const id = `cogit-shape-${(seq += 1)}`;
loadMermaid()
- .then((mermaid) => mermaid.render(id, source))
+ .then((mermaid) => {
+ // Mermaid keeps its config globally, so it is set again for every
+ // render: the colours come from the page's tokens, never from here.
+ mermaid.initialize({
+ startOnLoad: false,
+ securityLevel: "strict",
+ theme: "base",
+ themeVariables: mermaidThemeVariables(readToken),
+ });
+ return mermaid.render(id, source);
+ })
.then(({ svg }) => {
if (cancelled || host.current === null) return;
host.current.innerHTML = svg;
@@ -152,7 +193,7 @@ export function MermaidDiagram({
return () => {
cancelled = true;
};
- }, [source, available, fit, interactive, refit]);
+ }, [source, available, fit, interactive, refit, theme]);
// A plain wheel over the diagram zooms around the pointer and never scrolls
// the window behind it; React's wheel listener is passive, so this one is not.
diff --git a/packages/template/src/diagramTheme.ts b/packages/template/src/diagramTheme.ts
new file mode 100644
index 0000000..f111e1b
--- /dev/null
+++ b/packages/template/src/diagramTheme.ts
@@ -0,0 +1,84 @@
+import type { ThemeMode } from "./theme.js";
+
+/**
+ * Diagrams follow the map's palette (Story 14.3). Mermaid is initialised with
+ * its `base` theme, whose colours all come from `themeVariables`; the values
+ * are read from the page's CSS custom properties, so the stylesheet stays the
+ * only place a colour is written down.
+ */
+
+export type DiagramTheme = "light" | "dark";
+
+/** The palette the page is showing: the switch wins, else the system preference. */
+export function effectiveTheme(mode: ThemeMode, prefersDark: boolean): DiagramTheme {
+ if (mode === "light" || mode === "dark") return mode;
+ return prefersDark ? "dark" : "light";
+}
+
+/** Reads one token's value, or `undefined` when the page does not define it. */
+export type TokenReader = (name: string) => string | undefined;
+
+interface TokenRule {
+ /** The app token the diagram takes its colour from. */
+ readonly token: string;
+ /** Mermaid's theme variables that colour this part of a diagram. */
+ readonly variables: readonly string[];
+ /**
+ * CSS system colour used when the page has no such token — still theme-aware
+ * through `color-scheme`, so no colour is written in TypeScript.
+ */
+ readonly fallback: string;
+}
+
+/**
+ * The whole map, in one place: a diagram type that needs another variable is
+ * covered by adding it here, not by touching the component.
+ */
+export const MERMAID_TOKENS: readonly TokenRule[] = [
+ { token: "--chip-bg", variables: ["primaryColor", "mainBkg", "actorBkg"], fallback: "Canvas" },
+ {
+ token: "--text",
+ variables: [
+ "primaryTextColor",
+ "textColor",
+ "actorTextColor",
+ "signalTextColor",
+ "labelTextColor",
+ "loopTextColor",
+ "noteTextColor",
+ ],
+ fallback: "CanvasText",
+ },
+ {
+ token: "--chip-line",
+ variables: [
+ "primaryBorderColor",
+ "nodeBorder",
+ "actorBorder",
+ "labelBoxBorderColor",
+ "noteBorderColor",
+ "activationBorderColor",
+ ],
+ fallback: "GrayText",
+ },
+ { token: "--muted", variables: ["lineColor", "signalColor"], fallback: "GrayText" },
+ { token: "--line", variables: ["actorLineColor", "clusterBorder"], fallback: "GrayText" },
+ {
+ token: "--raised",
+ variables: ["edgeLabelBackground", "labelBoxBkgColor", "activationBkgColor", "secondaryColor"],
+ fallback: "Canvas",
+ },
+ { token: "--raised-2", variables: ["tertiaryColor", "clusterBkg"], fallback: "Canvas" },
+ { token: "--kind-bg", variables: ["noteBkgColor"], fallback: "Canvas" },
+];
+
+/** Mermaid's `themeVariables` for the page's current palette. */
+export function mermaidThemeVariables(read: TokenReader): Record<string, string> {
+ const themeVariables: Record<string, string> = { fontFamily: "inherit" };
+ for (const rule of MERMAID_TOKENS) {
+ const value = read(rule.token)?.trim();
+ const colour = value === undefined || value === "" ? rule.fallback : value;
+ for (const variable of rule.variables) themeVariables[variable] = colour;
+ }
+ return themeVariables;
+}
diff --git a/packages/template/test/diagramTheme.test.ts b/packages/template/test/diagramTheme.test.ts
new file mode 100644
index 0000000..edb2624
--- /dev/null
+++ b/packages/template/test/diagramTheme.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from "vitest";
+import {
+ effectiveTheme,
+ MERMAID_TOKENS,
+ mermaidThemeVariables,
+ type TokenReader,
+} from "../src/diagramTheme.js";
+
+/** A stub stylesheet: each token answers with its own name. */
+const reader: TokenReader = (name) => `colour:${name}`;
+
+describe("effectiveTheme", () => {
+ it("follows the system preference while on System", () => {
+ expect(effectiveTheme("system", true)).toBe("dark");
+ expect(effectiveTheme("system", false)).toBe("light");
+ });
+
+ it("passes a chosen theme through", () => {
+ expect(effectiveTheme("light", true)).toBe("light");
+ expect(effectiveTheme("dark", false)).toBe("dark");
+ });
+});
+
+describe("mermaidThemeVariables", () => {
+ it("takes every Mermaid colour from its page token", () => {
+ const variables = mermaidThemeVariables(reader);
+ for (const rule of MERMAID_TOKENS) {
+ for (const name of rule.variables) {
+ expect(variables[name], name).toBe(`colour:${rule.token}`);
+ }
+ }
+ expect(variables.fontFamily).toBe("inherit");
+ });
+
+ it("falls back to a readable system colour when a token is missing", () => {
+ for (const answer of [undefined, "", " "]) {
+ const variables = mermaidThemeVariables(() => answer);
+ for (const rule of MERMAID_TOKENS) {
+ for (const name of rule.variables) {
+ expect(variables[name], name).toBe(rule.fallback);
+ expect(variables[name]).not.toBe("");
+ }
+ }
+ }
+ });
+});
diff --git a/packages/template/test/layout.test.ts b/packages/template/test/layout.test.ts
index 5099bf1..638dd27 100644
--- a/packages/template/test/layout.test.ts
+++ b/packages/template/test/layout.test.ts
@@ -140,6 +140,9 @@ describe("small text contrast (Story 9.2)", () => {
// Diff lines in the message details (Story 10.5).
["diff-add-text", "diff-add-bg"],
["diff-remove-text", "diff-remove-bg"],
+ // Diagrams use the chip surface as their background (Story 14.3).
+ ["text", "chip-bg"],
+ ["muted", "chip-bg"],
];
it("declares a light theme besides the dark default", () => {