feat: give every Ekklesia screen one set of design tokens and elements
Modules have owned their own UI since ADR 0021, but the platform has never said what that UI should look like. Every screen here — the Dashboard shell, the display host, the module template — invented its own hex colours, font stack, spacing, and radii, and they already disagreed. A module author had no vocabulary for "the ordinary panel background", so the only available answer was to invent one, and two modules would invent two. Add `@ekklesia/design-tokens`: one validated, enumerable registry of semantic tokens. A token declares a name, label, description, and default value; its category and `--ekklesia-*` identifier are derived from the name, so it can never claim one category while being named for another. Construction rejects duplicates, malformed names, unknown categories, empty or overlong text, and any value that is not a bounded literal — no declaration terminator, rule block, comment, at-rule, `url(`, `!important`, escape, control character, or markup. A registry that constructs can therefore be emitted as CSS without escaping, because nothing needing escaping can be in it. That validation is also what makes a future theme editor implementable rather than aspirational. Add `@ekklesia/ui`: button, icon button, text input, select, checkbox, field wrapper, panel, dialog, tabs, table and list primitives, badge, toast, and empty/error/loading states — every value a token reference, with real `:focus-visible` treatment and status that never depends on colour alone. Deliberately small: an element earns its place when two consumers need it. The stylesheet is a string rather than a `.css` file so the identical bytes install into a document or an isolated artifact root, and so hover, disabled, and focus-visible are real CSS rather than JavaScript approximations of them. `pnpm boundaries` opens exactly two shared roles to modules, by name — every other role stays rejected — and pins both design packages to the bottom of the presentation stack. Both are browser-safe by construction, proven by a real compile of module-shaped source in which `process.env` must fail to typecheck. The shell installs the defaults at its document root for the Dashboard and the display; custom properties inherit into module artifacts, so a module reads `var(--ekklesia-…)` with nothing to import at run time and nothing for a host to forget to pass. Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5
parent
b14613decd
commit
e03d38fcab
@@ -0,0 +1,46 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const run = promisify(execFile);
|
||||
const packageDirectory = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const fixtureDirectory = path.join(packageDirectory, "tests", "browser-boundary");
|
||||
const typescript = path.join(packageDirectory, "node_modules", ".bin", "tsc");
|
||||
|
||||
async function typecheck(project: string): Promise<{ code: number; output: string }> {
|
||||
try {
|
||||
await run(typescript, ["--noEmit", "--project", path.join(fixtureDirectory, project)]);
|
||||
return { code: 0, output: "" };
|
||||
} catch (error) {
|
||||
const failure = error as { code?: number; stdout?: string; stderr?: string };
|
||||
return { code: failure.code ?? 1, output: `${failure.stdout ?? ""}${failure.stderr ?? ""}` };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The design packages are consumed by module UI, so they inherit ADR 0024's browser boundary
|
||||
* exactly: importing them must not make Node's global declarations visible to browser-only code.
|
||||
*
|
||||
* Tested the way a module author experiences it — a real compile under the exact project a module
|
||||
* uses for UI source (`browser-react.json`, `"types": []`) — rather than by inspecting the
|
||||
* dependency graph, because the leak ADR 0024 found was a *type graph* leak that no dependency list
|
||||
* would have shown.
|
||||
*/
|
||||
describe("design package browser boundary", () => {
|
||||
it("compiles supported module UI source that imports both design packages", async () => {
|
||||
const result = await typecheck("tsconfig.supported.json");
|
||||
|
||||
expect(result.output).toBe("");
|
||||
expect(result.code).toBe(0);
|
||||
}, 60_000);
|
||||
|
||||
it("refuses Node globals in UI source that imports the design packages", async () => {
|
||||
const result = await typecheck("tsconfig.node-global.json");
|
||||
|
||||
expect(result.code).not.toBe(0);
|
||||
expect(result.output).toContain("Cannot find name 'process'");
|
||||
expect(result.output).toContain("node-global.tsx");
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
// The negative case. Importing the approved design packages must NOT make Node globals visible. If
|
||||
// this file ever typechecks, the browser boundary has regressed and `browser-boundary.test.ts`
|
||||
// fails.
|
||||
import { designToken } from "@ekklesia/design-tokens";
|
||||
import { Button } from "../../src/index.js";
|
||||
|
||||
export const element = Button;
|
||||
export const color = designToken("text.primary");
|
||||
export const leaked: string | undefined = process.env.NODE_ENV;
|
||||
@@ -0,0 +1,21 @@
|
||||
// A module author's supported UI source: it imports both approved design packages and must
|
||||
// typecheck cleanly under the exact browser project a module uses for its own UI
|
||||
// (`browser-react.json`, `"types": []`).
|
||||
import { designToken, ekklesiaDesignTokens } from "@ekklesia/design-tokens";
|
||||
import type { ReactElement } from "react";
|
||||
import { Badge, Button, EkklesiaUiStyles, Panel } from "../../src/index.js";
|
||||
|
||||
export function ModuleScreen(): ReactElement {
|
||||
return (
|
||||
<>
|
||||
<EkklesiaUiStyles />
|
||||
<Panel title="Slides">
|
||||
<p style={{ color: designToken("text.secondary") }}>
|
||||
{ekklesiaDesignTokens.list().length} tokens available.
|
||||
</p>
|
||||
<Badge tone="success">Ready</Badge>
|
||||
<Button variant="primary">Add</Button>
|
||||
</Panel>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "../../../typescript-config/browser-react.json",
|
||||
"compilerOptions": { "noEmit": true, "types": [] },
|
||||
"include": ["node-global.tsx"]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "../../../typescript-config/browser-react.json",
|
||||
"compilerOptions": { "noEmit": true, "types": [] },
|
||||
"include": ["supported.tsx"]
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Checkbox,
|
||||
Dialog,
|
||||
EkklesiaUiStyles,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
Field,
|
||||
IconButton,
|
||||
List,
|
||||
ListItem,
|
||||
LoadingState,
|
||||
Panel,
|
||||
Select,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableRow,
|
||||
Tabs,
|
||||
TextInput,
|
||||
Toast,
|
||||
ToastStack,
|
||||
} from "../src/index.js";
|
||||
|
||||
declare global {
|
||||
// eslint-disable-next-line no-var
|
||||
var IS_REACT_ACT_ENVIRONMENT: boolean | undefined;
|
||||
}
|
||||
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
beforeEach(() => {
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
});
|
||||
|
||||
function render(node: React.ReactNode): void {
|
||||
act(() => root.render(node));
|
||||
}
|
||||
|
||||
describe("Ekklesia elements", () => {
|
||||
it("renders a button that does not submit a form by accident", () => {
|
||||
render(<Button variant="primary">Save</Button>);
|
||||
const button = container.querySelector("button");
|
||||
|
||||
expect(button?.getAttribute("type")).toBe("button");
|
||||
expect(button?.className).toContain("ek-button--primary");
|
||||
expect(button?.className).toContain("ek-focusable");
|
||||
});
|
||||
|
||||
it("requires an accessible name on an icon-only button", () => {
|
||||
render(<IconButton label="Remove slide">×</IconButton>);
|
||||
|
||||
expect(container.querySelector("button")?.getAttribute("aria-label")).toBe("Remove slide");
|
||||
});
|
||||
|
||||
it("associates a field's label, hint, and error with its control", () => {
|
||||
render(
|
||||
<Field error="Enter a name." hint="Shown on the display." label="Name">
|
||||
{(control) => <TextInput {...control} />}
|
||||
</Field>,
|
||||
);
|
||||
|
||||
const label = container.querySelector("label");
|
||||
const input = container.querySelector("input");
|
||||
const error = container.querySelector(".ek-field__error");
|
||||
|
||||
expect(input?.id).toBeTruthy();
|
||||
expect(label?.getAttribute("for")).toBe(input?.id);
|
||||
expect(input?.getAttribute("aria-invalid")).toBe("true");
|
||||
expect(input?.getAttribute("aria-describedby")?.split(" ")).toContain(error?.id);
|
||||
expect(error?.getAttribute("role")).toBe("alert");
|
||||
});
|
||||
|
||||
it("renders a select and a labelled checkbox as real form controls", () => {
|
||||
render(
|
||||
<>
|
||||
<Select aria-label="Mode">
|
||||
<option value="a">A</option>
|
||||
</Select>
|
||||
<Checkbox label="Enabled" />
|
||||
</>,
|
||||
);
|
||||
|
||||
expect(container.querySelector("select")?.className).toContain("ek-control");
|
||||
expect(container.querySelector('input[type="checkbox"]')).not.toBeNull();
|
||||
expect(container.querySelector(".ek-checkbox")?.textContent).toContain("Enabled");
|
||||
});
|
||||
|
||||
it("renders a panel with an accessible heading and its actions", () => {
|
||||
render(
|
||||
<Panel actions={<Button>New</Button>} description="What this panel is." title="Slides">
|
||||
<p>Body</p>
|
||||
</Panel>,
|
||||
);
|
||||
|
||||
expect(container.querySelector("h2")?.textContent).toBe("Slides");
|
||||
expect(container.querySelector(".ek-panel__description")?.textContent).toBe(
|
||||
"What this panel is.",
|
||||
);
|
||||
expect(container.querySelector(".ek-panel__header button")?.textContent).toBe("New");
|
||||
});
|
||||
|
||||
it("renders a dialog in place, labels it, and dismisses it on Escape", () => {
|
||||
const onDismiss = vi.fn();
|
||||
render(
|
||||
<Dialog onDismiss={onDismiss} open title="Delete slide">
|
||||
Are you sure?
|
||||
</Dialog>,
|
||||
);
|
||||
|
||||
const dialog = container.querySelector('[role="dialog"]');
|
||||
expect(dialog?.getAttribute("aria-modal")).toBe("true");
|
||||
expect(
|
||||
container.querySelector(`#${dialog?.getAttribute("aria-labelledby")}`)?.textContent,
|
||||
).toBe("Delete slide");
|
||||
// Rendered inside the caller's own subtree, never portalled to document.body: an artifact's
|
||||
// dialog must not escape its isolated root.
|
||||
expect(document.body.querySelector(":scope > [role='dialog']")).toBeNull();
|
||||
|
||||
act(() => {
|
||||
document.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "Escape" }));
|
||||
});
|
||||
expect(onDismiss).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("renders nothing for a closed dialog", () => {
|
||||
render(
|
||||
<Dialog onDismiss={() => undefined} open={false} title="Hidden">
|
||||
Body
|
||||
</Dialog>,
|
||||
);
|
||||
|
||||
expect(container.querySelector('[role="dialog"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("exposes tabs with ARIA roles and arrow-key movement", () => {
|
||||
const onSelect = vi.fn();
|
||||
const tabs = [
|
||||
{ content: <p>One</p>, id: "one", label: "One" },
|
||||
{ content: <p>Two</p>, id: "two", label: "Two" },
|
||||
];
|
||||
render(<Tabs label="Sections" onSelect={onSelect} selectedId="one" tabs={tabs} />);
|
||||
|
||||
const tabButtons = [...container.querySelectorAll('[role="tab"]')];
|
||||
expect(tabButtons.map((tab) => tab.getAttribute("aria-selected"))).toEqual(["true", "false"]);
|
||||
expect(tabButtons.map((tab) => tab.getAttribute("tabindex"))).toEqual(["0", "-1"]);
|
||||
expect(container.querySelector('[role="tabpanel"]')?.textContent).toBe("One");
|
||||
|
||||
act(() => {
|
||||
tabButtons[0]?.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { bubbles: true, key: "ArrowRight" }),
|
||||
);
|
||||
});
|
||||
expect(onSelect).toHaveBeenCalledWith("two");
|
||||
});
|
||||
|
||||
it("renders table and list primitives with header semantics", () => {
|
||||
render(
|
||||
<>
|
||||
<Table label="Slides">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell header>Name</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
<TableRow selected>
|
||||
<TableCell>Welcome</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
<List label="Recent">
|
||||
<ListItem>First</ListItem>
|
||||
</List>
|
||||
</>,
|
||||
);
|
||||
|
||||
expect(container.querySelector("table")?.getAttribute("aria-label")).toBe("Slides");
|
||||
expect(container.querySelector("th")?.getAttribute("scope")).toBe("col");
|
||||
expect(container.querySelector("tbody tr")?.getAttribute("aria-selected")).toBe("true");
|
||||
expect(container.querySelector(".ek-list__item")?.textContent).toBe("First");
|
||||
});
|
||||
|
||||
it("never signals status with colour alone", () => {
|
||||
render(
|
||||
<>
|
||||
<Badge tone="success">Running</Badge>
|
||||
<ToastStack>
|
||||
<Toast title="Saved" tone="success">
|
||||
Everything went through.
|
||||
</Toast>
|
||||
<Toast title="Failed" tone="danger" />
|
||||
</ToastStack>
|
||||
</>,
|
||||
);
|
||||
|
||||
expect(container.querySelector(".ek-badge__symbol")?.textContent).toBe("✓");
|
||||
expect(container.querySelector(".ek-badge__symbol")?.getAttribute("aria-hidden")).toBe("true");
|
||||
const toasts = [...container.querySelectorAll(".ek-toast")];
|
||||
expect(toasts[0]?.textContent).toContain("✓");
|
||||
expect(toasts[0]?.getAttribute("aria-live")).toBe("polite");
|
||||
expect(toasts[1]?.textContent).toContain("✕");
|
||||
expect(toasts[1]?.getAttribute("aria-live")).toBe("assertive");
|
||||
});
|
||||
|
||||
it("renders empty, error, and loading states with the right announcements", () => {
|
||||
render(
|
||||
<>
|
||||
<EmptyState description="Add one to begin." title="No slides yet" />
|
||||
<ErrorState description="Try again." title="This could not load" />
|
||||
<LoadingState label="Loading slides…" />
|
||||
</>,
|
||||
);
|
||||
|
||||
expect(container.querySelector(".ek-message")?.textContent).toContain("No slides yet");
|
||||
expect(container.querySelector('[role="alert"]')?.textContent).toContain("This could not load");
|
||||
const loading = container.querySelector('[role="status"]');
|
||||
expect(loading?.getAttribute("aria-live")).toBe("polite");
|
||||
expect(loading?.textContent).toContain("Loading slides…");
|
||||
expect(container.querySelector(".ek-spinner")?.getAttribute("aria-hidden")).toBe("true");
|
||||
});
|
||||
|
||||
it("puts its stylesheet in whichever root it is rendered into", () => {
|
||||
const host = document.createElement("div");
|
||||
container.appendChild(host);
|
||||
const shadow = host.attachShadow({ mode: "open" });
|
||||
const shadowRoot = createRoot(shadow);
|
||||
|
||||
act(() =>
|
||||
shadowRoot.render(
|
||||
<>
|
||||
<EkklesiaUiStyles />
|
||||
<Button>Inside</Button>
|
||||
</>,
|
||||
),
|
||||
);
|
||||
|
||||
expect(shadow.querySelector("style[data-ekklesia-ui]")?.textContent).toContain(".ek-button");
|
||||
// The host document never receives the artifact's copy.
|
||||
expect(document.head.querySelector("style[data-ekklesia-ui]")).toBeNull();
|
||||
|
||||
act(() => shadowRoot.unmount());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { readdir, readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { ekklesiaDesignTokens } from "@ekklesia/design-tokens";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
EKKLESIA_UI_STYLE_ATTRIBUTE,
|
||||
EKKLESIA_UI_STYLESHEET,
|
||||
installEkklesiaUiStyles,
|
||||
} from "../src/index.js";
|
||||
|
||||
const packageDirectory = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
|
||||
async function sourceFiles(): Promise<readonly string[]> {
|
||||
const directory = path.join(packageDirectory, "src");
|
||||
return (await readdir(directory))
|
||||
.filter((entry) => entry.endsWith(".ts") || entry.endsWith(".tsx"))
|
||||
.map((entry) => path.join(directory, entry));
|
||||
}
|
||||
|
||||
/** Any literal that would be a theme decision rather than a layout one. */
|
||||
const THEME_LITERAL_PATTERN =
|
||||
/#[0-9a-f]{3,8}\b|\brgba?\s*\(|\bhsla?\s*\(|\boklch\s*\(|\bsystem-ui\b|\bsans-serif\b/giu;
|
||||
|
||||
describe("the shared elements consume design tokens, never hardcoded theme values", () => {
|
||||
it("expresses every theme value in the stylesheet as a token reference", () => {
|
||||
expect(EKKLESIA_UI_STYLESHEET.match(THEME_LITERAL_PATTERN)).toBeNull();
|
||||
expect(EKKLESIA_UI_STYLESHEET).toContain("var(--ekklesia-");
|
||||
});
|
||||
|
||||
it("references only registered tokens", () => {
|
||||
const referenced = [...EKKLESIA_UI_STYLESHEET.matchAll(/var\((--ekklesia-[a-z0-9-]+)\)/gu)].map(
|
||||
([, variable]) => String(variable),
|
||||
);
|
||||
const registered = new Set(ekklesiaDesignTokens.list().map((token) => token.cssVariable));
|
||||
|
||||
expect(referenced.length).toBeGreaterThan(0);
|
||||
expect([...new Set(referenced)].filter((variable) => !registered.has(variable))).toEqual([]);
|
||||
});
|
||||
|
||||
it("never defines a global Ekklesia theme variable of its own", () => {
|
||||
// Referencing `--ekklesia-*` is the contract; *declaring* one would invent a global theme
|
||||
// variable outside the registry, which is precisely what the design-token contract forbids.
|
||||
expect(EKKLESIA_UI_STYLESHEET).not.toMatch(/--ekklesia-[a-z0-9-]+\s*:/u);
|
||||
});
|
||||
|
||||
it("hardcodes no theme value in component source either", async () => {
|
||||
for (const file of await sourceFiles()) {
|
||||
if (path.basename(file) === "styles.ts") {
|
||||
continue;
|
||||
}
|
||||
expect(await readFile(file, "utf8")).not.toMatch(THEME_LITERAL_PATTERN);
|
||||
}
|
||||
});
|
||||
|
||||
it("never names a Node built-in or reads the environment", async () => {
|
||||
for (const file of await sourceFiles()) {
|
||||
const source = await readFile(file, "utf8");
|
||||
|
||||
expect(source).not.toContain('"node:');
|
||||
expect(source).not.toContain("process.env");
|
||||
}
|
||||
});
|
||||
|
||||
it("depends only on the design tokens and React", async () => {
|
||||
const manifest = JSON.parse(
|
||||
await readFile(path.join(packageDirectory, "package.json"), "utf8"),
|
||||
) as { dependencies?: Record<string, string>; peerDependencies?: Record<string, string> };
|
||||
|
||||
expect(Object.keys(manifest.dependencies ?? {})).toEqual(["@ekklesia/design-tokens"]);
|
||||
expect(Object.keys(manifest.peerDependencies ?? {})).toEqual(["react"]);
|
||||
});
|
||||
|
||||
it("installs its stylesheet into a document root exactly once", () => {
|
||||
const remove = installEkklesiaUiStyles(document);
|
||||
installEkklesiaUiStyles(document);
|
||||
|
||||
expect(document.querySelectorAll(`style[${EKKLESIA_UI_STYLE_ATTRIBUTE}]`).length).toBe(1);
|
||||
|
||||
remove();
|
||||
remove();
|
||||
expect(document.querySelectorAll(`style[${EKKLESIA_UI_STYLE_ATTRIBUTE}]`).length).toBe(0);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user