@milesroxas/design-hub 0.4.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -27,6 +27,7 @@ import * as signin from './signin.js';
27
27
  import * as skillHint from './skill-hint.js';
28
28
  import * as skills from './skills.js';
29
29
  import * as tracks from './tracks.js';
30
+ import * as upgrade from './upgrade.js';
30
31
  import * as visualMatch from './visual-match.js';
31
32
  // `guide` is `new --guide`; `open` is `dev` with the browser.
32
33
  const COMMANDS = {
@@ -54,6 +55,7 @@ const COMMANDS = {
54
55
  export: exportCmd,
55
56
  skills,
56
57
  tracks,
58
+ upgrade,
57
59
  'skill-hint': skillHint,
58
60
  'release-check': releaseCheck,
59
61
  commands,
@@ -22,6 +22,7 @@ import * as signin from './signin.js';
22
22
  import * as skillHint from './skill-hint.js';
23
23
  import * as skills from './skills.js';
24
24
  import * as tracks from './tracks.js';
25
+ import * as upgrade from './upgrade.js';
25
26
  import * as visualMatch from './visual-match.js';
26
27
  export const spec = {
27
28
  name: 'commands',
@@ -50,6 +51,7 @@ export const COMMANDS = [
50
51
  exportCmd.spec,
51
52
  skills.spec,
52
53
  tracks.spec,
54
+ upgrade.spec,
53
55
  skillHint.spec,
54
56
  releaseCheck.spec,
55
57
  spec,
@@ -14,5 +14,5 @@ export declare function mdWriting(input: {
14
14
  additionalContext: string;
15
15
  };
16
16
  } | null;
17
- export declare const HOOKS: readonly ['fidelity-guard', 'md-writing', 'skill-hint'];
17
+ export declare const HOOKS: readonly ['fidelity-guard', 'md-writing', 'skill-hint', 'update'];
18
18
  export declare function runHook(name: string): Promise<void>;
@@ -8,6 +8,7 @@ import { readFileSync } from 'node:fs';
8
8
  import { basename } from 'node:path';
9
9
  import { guardHook } from './guard.js';
10
10
  import { skillHintHook } from './skill-hint.js';
11
+ import { upgradeHook } from './upgrade.js';
11
12
  const MD = /\.md$/i;
12
13
  /** PostToolUse on a Markdown file: ask for the writing pass before the change is reported done. */
13
14
  export function mdWriting(input) {
@@ -22,7 +23,7 @@ export function mdWriting(input) {
22
23
  },
23
24
  };
24
25
  }
25
- export const HOOKS = ['fidelity-guard', 'md-writing', 'skill-hint'];
26
+ export const HOOKS = ['fidelity-guard', 'md-writing', 'skill-hint', 'update'];
26
27
  export async function runHook(name) {
27
28
  try {
28
29
  switch (name) {
@@ -30,6 +31,8 @@ export async function runHook(name) {
30
31
  return await guardHook();
31
32
  case 'skill-hint':
32
33
  return await skillHintHook();
34
+ case 'update':
35
+ return await upgradeHook();
33
36
  case 'md-writing': {
34
37
  const output = mdWriting(JSON.parse(readFileSync(0, 'utf8')));
35
38
  if (output)
@@ -0,0 +1,71 @@
1
+ export declare const PACKAGE_NAME = "@milesroxas/design-hub";
2
+ /** `a` is a newer release than `b`. Pre-releases never count: `latest` is what upgrades. */
3
+ export declare function newer(a: string, b: string): boolean;
4
+ export type Cached = {
5
+ version: string;
6
+ at: number;
7
+ };
8
+ /** The cached `latest` while it is under an hour old, else null so npm is asked again. */
9
+ export declare const cachedLatest: (cached: Cached | null, now: number) => string | null;
10
+ export type Facts = {
11
+ /** The version spec in the project's package.json, or null when it does not depend on the hub. */
12
+ spec: string | null;
13
+ /** The version in node_modules, or null before an install. */
14
+ installed: string | null;
15
+ /** npm's `latest`, or null when npm could not be reached. */
16
+ latest: string | null;
17
+ /** DESIGN_HUB_AUTO_UPDATE=0 in the environment or the project's .env. */
18
+ disabled: boolean;
19
+ };
20
+ export type Decision = {
21
+ upgrade: string;
22
+ } | {
23
+ skip: string;
24
+ available?: string;
25
+ };
26
+ /**
27
+ * Upgrades only a project that installs the hub from npm: a workspace or a
28
+ * linked checkout (this repo's sample project, a project made with --link) is
29
+ * on the source already.
30
+ */
31
+ export declare function decide(f: Facts): Decision;
32
+ /** The SessionStart entry: new sessions only, so a resume or a compact never reinstalls mid-work. */
33
+ export declare const SESSION_HOOK: {
34
+ matcher: string;
35
+ hooks: {
36
+ type: string;
37
+ command: string;
38
+ timeout: number;
39
+ statusMessage: string;
40
+ }[];
41
+ };
42
+ type Settings = {
43
+ hooks?: Record<string, {
44
+ hooks?: {
45
+ command?: string;
46
+ }[];
47
+ }[]>;
48
+ } & Record<string, unknown>;
49
+ /** Adds the SessionStart hook when no entry runs it yet; every other hook stays as it is. Null when nothing changes. */
50
+ export declare function withSessionHook(settings: Settings): Settings | null;
51
+ export type Outcome = {
52
+ kind: 'upgraded';
53
+ from: string;
54
+ to: string;
55
+ changed: string[];
56
+ } | {
57
+ kind: 'failed';
58
+ from: string;
59
+ to: string;
60
+ error: string;
61
+ } | {
62
+ kind: 'available';
63
+ from: string;
64
+ to: string;
65
+ };
66
+ /** The hook's output: one line for the user, the context the agent acts on. */
67
+ export declare function report(o: Outcome): {
68
+ systemMessage: string;
69
+ additionalContext: string;
70
+ };
71
+ export {};
@@ -0,0 +1,83 @@
1
+ /// <reference types="node" />
2
+ // What the session-start upgrade decides, apart from the npm, pnpm and file
3
+ // calls that feed it, so every branch is tested: whether a version is newer,
4
+ // whether this project upgrades itself at all, the hook entry a project's
5
+ // .claude/settings.json carries, and what the agent is told afterwards.
6
+ export const PACKAGE_NAME = '@milesroxas/design-hub';
7
+ /** `a` is a newer release than `b`. Pre-releases never count: `latest` is what upgrades. */
8
+ export function newer(a, b) {
9
+ const parse = (v) => (/^\d+\.\d+\.\d+$/.test(v) ? v.split('.').map(Number) : null);
10
+ const x = parse(a);
11
+ const y = parse(b);
12
+ if (!x || !y)
13
+ return false;
14
+ for (let i = 0; i < 3; i++)
15
+ if (x[i] !== y[i])
16
+ return x[i] > y[i];
17
+ return false;
18
+ }
19
+ const CACHE_MS = 60 * 60_000;
20
+ /** The cached `latest` while it is under an hour old, else null so npm is asked again. */
21
+ export const cachedLatest = (cached, now) => cached && now - cached.at < CACHE_MS ? cached.version : null;
22
+ /**
23
+ * Upgrades only a project that installs the hub from npm: a workspace or a
24
+ * linked checkout (this repo's sample project, a project made with --link) is
25
+ * on the source already.
26
+ */
27
+ export function decide(f) {
28
+ if (!f.spec)
29
+ return { skip: 'not a Design Hub project' };
30
+ if (/^(workspace|link|file|portal):/.test(f.spec))
31
+ return { skip: `linked to a checkout (${f.spec})` };
32
+ if (!f.installed)
33
+ return { skip: 'not installed yet; pnpm install first' };
34
+ if (!f.latest)
35
+ return { skip: 'npm not reachable' };
36
+ if (!newer(f.latest, f.installed))
37
+ return { skip: 'up to date' };
38
+ if (f.disabled)
39
+ return { skip: 'DESIGN_HUB_AUTO_UPDATE=0', available: f.latest };
40
+ return { upgrade: f.latest };
41
+ }
42
+ const HOOK_COMMAND = 'cd "$CLAUDE_PROJECT_DIR" && node_modules/.bin/design-hub hook update';
43
+ /** The SessionStart entry: new sessions only, so a resume or a compact never reinstalls mid-work. */
44
+ export const SESSION_HOOK = {
45
+ matcher: 'startup',
46
+ hooks: [
47
+ {
48
+ type: 'command',
49
+ command: HOOK_COMMAND,
50
+ timeout: 180,
51
+ statusMessage: 'Checking for a Design Hub update',
52
+ },
53
+ ],
54
+ };
55
+ /** Adds the SessionStart hook when no entry runs it yet; every other hook stays as it is. Null when nothing changes. */
56
+ export function withSessionHook(settings) {
57
+ const start = settings.hooks?.SessionStart ?? [];
58
+ if (start.some((e) => e.hooks?.some((h) => h.command?.includes('design-hub hook update'))))
59
+ return null;
60
+ return { ...settings, hooks: { ...settings.hooks, SessionStart: [...start, SESSION_HOOK] } };
61
+ }
62
+ const MANUAL = `pnpm add ${PACKAGE_NAME}@latest && pnpm skills`;
63
+ /** The hook's output: one line for the user, the context the agent acts on. */
64
+ export function report(o) {
65
+ if (o.kind === 'upgraded')
66
+ return {
67
+ systemMessage: `Design Hub upgraded ${o.from} to ${o.to}.`,
68
+ additionalContext: `Design Hub was upgraded from ${o.from} to ${o.to} when this session started; its skills and scripts are current. ` +
69
+ `Tell the user in one line. Files it changed: ${o.changed.length ? o.changed.join(', ') : 'none'}. ` +
70
+ `They are not committed: include them in the next commit the user asks for, as their own commit "Upgrade Design Hub to ${o.to}". ` +
71
+ 'If a miles-* skill you load reads as older than this, the user can run /reload-skills.',
72
+ };
73
+ if (o.kind === 'failed')
74
+ return {
75
+ systemMessage: `Design Hub ${o.to} is available; the automatic upgrade failed.`,
76
+ additionalContext: `Design Hub ${o.to} is available (installed: ${o.from}), but the upgrade at session start failed: ${o.error}. ` +
77
+ `Tell the user in one line, and offer to run \`${MANUAL}\` once the cause is fixed.`,
78
+ };
79
+ return {
80
+ systemMessage: `Design Hub ${o.to} is available (installed: ${o.from}); automatic upgrades are off.`,
81
+ additionalContext: `Design Hub ${o.to} is available; this project has ${o.from} and DESIGN_HUB_AUTO_UPDATE=0. Mention it once; upgrade with \`${MANUAL}\` only if the user asks.`,
82
+ };
83
+ }
@@ -2,19 +2,24 @@
2
2
  import type { Args } from './lib/cli.ts';
3
3
  export declare const spec: {
4
4
  readonly name: 'skills';
5
- readonly summary: "Install or update the project's miles-* skills from this package into .claude/skills/, and add any package.json script they call that the project lacks.";
5
+ readonly summary: "Install or update the project's miles-* skills from this package into .claude/skills/, add any package.json script they call that the project lacks, and the session-start upgrade hook.";
6
6
  readonly flags: {};
7
- readonly output: '{ ok, installed: [name], into, scripts: { added: [name] } }';
7
+ readonly output: '{ ok, installed: [name], into, scripts: { added: [name] }, hooks: { sessionStart: added | kept } }';
8
8
  };
9
9
  export declare function installSkills(from?: string, into?: string): string[];
10
10
  /** The scripts a project's package.json carries, as the template writes them. The skills call them by these names. */
11
11
  export declare const SCRIPTS: Record<string, string>;
12
12
  /** Adds each missing script to the project's package.json; a script the project already has is never changed. */
13
13
  export declare function addScripts(file?: string): string[];
14
+ /** Adds the SessionStart upgrade hook to .claude/settings.json when it is missing; other hooks are never changed. */
15
+ export declare function addSessionHook(file?: string): 'added' | 'kept';
14
16
  export declare function main(_args: Args<typeof spec>): {
15
17
  installed: string[];
16
18
  into: string;
17
19
  scripts: {
18
20
  added: string[];
19
21
  };
22
+ hooks: {
23
+ sessionStart: "added" | "kept";
24
+ };
20
25
  };
@@ -10,11 +10,12 @@
10
10
  import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
11
11
  import { join } from 'node:path';
12
12
  import { PACKAGE_SKILLS, ROOT, SKILLS } from '../server/paths.js';
13
+ import { withSessionHook } from './lib/update.js';
13
14
  export const spec = {
14
15
  name: 'skills',
15
- summary: "Install or update the project's miles-* skills from this package into .claude/skills/, and add any package.json script they call that the project lacks.",
16
+ summary: "Install or update the project's miles-* skills from this package into .claude/skills/, add any package.json script they call that the project lacks, and the session-start upgrade hook.",
16
17
  flags: {},
17
- output: '{ ok, installed: [name], into, scripts: { added: [name] } }',
18
+ output: '{ ok, installed: [name], into, scripts: { added: [name] }, hooks: { sessionStart: added | kept } }',
18
19
  };
19
20
  const GLOBAL_ONLY = new Set(['miles-design-hub']);
20
21
  /** Skills the package no longer ships, removed from a project on update. miles-conductor became miles-worktrees in 0.2.0. */
@@ -75,6 +76,21 @@ export function addScripts(file = join(ROOT, 'package.json')) {
75
76
  writeFileSync(file, `${JSON.stringify(pkg, null, 2)}\n`);
76
77
  return added;
77
78
  }
79
+ /** Adds the SessionStart upgrade hook to .claude/settings.json when it is missing; other hooks are never changed. */
80
+ export function addSessionHook(file = join(ROOT, '.claude', 'settings.json')) {
81
+ const settings = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : {};
82
+ const next = withSessionHook(settings);
83
+ if (!next)
84
+ return 'kept';
85
+ mkdirSync(join(file, '..'), { recursive: true });
86
+ writeFileSync(file, `${JSON.stringify(next, null, 2)}\n`);
87
+ return 'added';
88
+ }
78
89
  export function main(_args) {
79
- return { installed: installSkills(), into: SKILLS, scripts: { added: addScripts() } };
90
+ return {
91
+ installed: installSkills(),
92
+ into: SKILLS,
93
+ scripts: { added: addScripts() },
94
+ hooks: { sessionStart: addSessionHook() },
95
+ };
80
96
  }
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ import type { Args } from './lib/cli.ts';
3
+ import { type Outcome } from './lib/update.ts';
4
+ export declare const spec: {
5
+ readonly name: 'upgrade';
6
+ readonly summary: 'Upgrade this project to the newest Design Hub and refresh its skills, scripts and hooks. The SessionStart hook runs it on every new session.';
7
+ readonly flags: {
8
+ readonly check: {
9
+ readonly type: 'boolean';
10
+ readonly description: 'Only report whether a newer version exists.';
11
+ };
12
+ };
13
+ readonly output: '{ ok, installed, latest, decision, outcome? }';
14
+ };
15
+ /** SessionStart: says nothing unless something changed or is waiting. */
16
+ export declare function upgradeHook(): Promise<void>;
17
+ export declare function main({ flags }: Args<typeof spec>): Promise<{
18
+ systemMessage?: string | undefined;
19
+ additionalContext?: string | undefined;
20
+ ok: boolean;
21
+ installed: string | null;
22
+ latest: string | null;
23
+ decision: import("./lib/update.ts").Decision;
24
+ outcome?: Outcome | undefined;
25
+ }>;
@@ -0,0 +1,166 @@
1
+ #!/usr/bin/env node
2
+ /// <reference types="node" />
3
+ // Keeping a project on the newest Design Hub without anyone remembering to.
4
+ // The SessionStart hook (`design-hub hook update`) runs this when a Claude
5
+ // session opens in the project: it asks npm for `latest` (cached an hour),
6
+ // and when that is newer than node_modules it installs it and runs the new
7
+ // version's `design-hub skills`, so the session starts on current skills,
8
+ // scripts and hooks. It fails open: offline, a slow registry or a failed
9
+ // install leaves the session as it was and tells the agent.
10
+ import { spawnSync } from 'node:child_process';
11
+ import { createHash } from 'node:crypto';
12
+ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
13
+ import { homedir } from 'node:os';
14
+ import { join } from 'node:path';
15
+ import { readEnv } from '../server/env.js';
16
+ import { ROOT } from '../server/paths.js';
17
+ import { cachedLatest, decide, PACKAGE_NAME, report, } from './lib/update.js';
18
+ export const spec = {
19
+ name: 'upgrade',
20
+ summary: 'Upgrade this project to the newest Design Hub and refresh its skills, scripts and hooks. The SessionStart hook runs it on every new session.',
21
+ flags: {
22
+ check: { type: 'boolean', description: 'Only report whether a newer version exists.' },
23
+ },
24
+ output: '{ ok, installed, latest, decision, outcome? }',
25
+ };
26
+ const LOCK_STALE_MS = 10 * 60_000;
27
+ const INSTALL_TIMEOUT_MS = 150_000;
28
+ const configDir = () => join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'design-hub');
29
+ function readJson(file) {
30
+ try {
31
+ return JSON.parse(readFileSync(file, 'utf8'));
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
37
+ function facts(latest) {
38
+ const pkg = readJson(join(ROOT, 'package.json'));
39
+ const installed = readJson(join(ROOT, 'node_modules', PACKAGE_NAME, 'package.json'));
40
+ const flag = process.env.DESIGN_HUB_AUTO_UPDATE ?? readEnv(ROOT).DESIGN_HUB_AUTO_UPDATE;
41
+ return {
42
+ spec: pkg?.dependencies?.[PACKAGE_NAME] ?? pkg?.devDependencies?.[PACKAGE_NAME] ?? null,
43
+ installed: installed?.version ?? null,
44
+ latest,
45
+ disabled: flag === '0' || flag === 'false',
46
+ };
47
+ }
48
+ /** Asks npm for `latest`; null on any failure. */
49
+ async function fetchLatest() {
50
+ try {
51
+ const res = await fetch(`https://registry.npmjs.org/${PACKAGE_NAME}/latest`, {
52
+ signal: AbortSignal.timeout(3000),
53
+ });
54
+ return res.ok ? (await res.json()).version : null;
55
+ }
56
+ catch {
57
+ return null;
58
+ }
59
+ }
60
+ /** npm's `latest`, from a cache shared by every project on the machine unless `fresh`. Null when npm is unreachable. */
61
+ async function latestVersion(fresh) {
62
+ const file = join(configDir(), 'latest.json');
63
+ const cached = readJson(file);
64
+ const hit = fresh ? null : cachedLatest(cached, Date.now());
65
+ if (hit)
66
+ return hit;
67
+ const version = await fetchLatest();
68
+ if (!version)
69
+ return cached?.version ?? null;
70
+ mkdirSync(configDir(), { recursive: true });
71
+ writeFileSync(file, `${JSON.stringify({ version, at: Date.now() })}\n`);
72
+ return version;
73
+ }
74
+ /** One upgrade per project at a time: two sessions opened together must not install over each other. */
75
+ function lock() {
76
+ const dir = join(configDir(), 'locks');
77
+ const file = join(dir, `${createHash('sha1').update(ROOT).digest('hex').slice(0, 16)}.lock`);
78
+ mkdirSync(dir, { recursive: true });
79
+ if (existsSync(file) && Date.now() - statSync(file).mtimeMs > LOCK_STALE_MS)
80
+ rmSync(file, { force: true });
81
+ try {
82
+ writeFileSync(file, String(process.pid), { flag: 'wx' });
83
+ }
84
+ catch {
85
+ return null;
86
+ }
87
+ return () => rmSync(file, { force: true });
88
+ }
89
+ function dirtyPaths() {
90
+ const out = spawnSync('git', ['-C', ROOT, 'status', '--porcelain'], { encoding: 'utf8' });
91
+ if (out.status !== 0)
92
+ return new Set();
93
+ return new Set(out.stdout
94
+ .split('\n')
95
+ .filter(Boolean)
96
+ .map((l) => l.slice(3)));
97
+ }
98
+ function run(cmd, argv) {
99
+ const out = spawnSync(cmd, argv, {
100
+ cwd: ROOT,
101
+ encoding: 'utf8',
102
+ timeout: INSTALL_TIMEOUT_MS,
103
+ env: process.env,
104
+ });
105
+ if (out.error)
106
+ return out.error.message;
107
+ if (out.status !== 0)
108
+ return `${cmd} ${argv[0]} exited ${out.status}: ${(out.stderr || out.stdout).trim().slice(-400)}`;
109
+ return null;
110
+ }
111
+ /** Installs `to` and runs that version's own `skills`, so the newest skills, scripts and hooks land. */
112
+ function install(from, to) {
113
+ const before = dirtyPaths();
114
+ const error = run('pnpm', ['add', `${PACKAGE_NAME}@^${to}`]) ??
115
+ run(join(ROOT, 'node_modules', '.bin', 'design-hub'), ['skills']);
116
+ if (error)
117
+ return { kind: 'failed', from, to, error };
118
+ const now = facts(to).installed;
119
+ if (now !== to)
120
+ return { kind: 'failed', from, to, error: `node_modules has ${now ?? 'nothing'} after the install` };
121
+ const changed = [...dirtyPaths()].filter((p) => !before.has(p)).sort();
122
+ return { kind: 'upgraded', from, to, changed };
123
+ }
124
+ async function attempt(fresh, checkOnly) {
125
+ const latest = await latestVersion(fresh);
126
+ const f = facts(latest);
127
+ const decision = decide(f);
128
+ if (checkOnly)
129
+ return { f, decision, outcome: null };
130
+ if ('skip' in decision) {
131
+ const outcome = decision.available && f.installed
132
+ ? { kind: 'available', from: f.installed, to: decision.available }
133
+ : null;
134
+ return { f, decision, outcome };
135
+ }
136
+ const release = lock();
137
+ if (!release)
138
+ return { f, decision: { skip: 'another session is upgrading this project' }, outcome: null };
139
+ try {
140
+ return { f, decision, outcome: install(f.installed, decision.upgrade) };
141
+ }
142
+ finally {
143
+ release();
144
+ }
145
+ }
146
+ /** SessionStart: says nothing unless something changed or is waiting. */
147
+ export async function upgradeHook() {
148
+ const { outcome } = await attempt(false, false);
149
+ if (!outcome)
150
+ return;
151
+ const { systemMessage, additionalContext } = report(outcome);
152
+ console.log(JSON.stringify({
153
+ systemMessage,
154
+ hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext },
155
+ }));
156
+ }
157
+ export async function main({ flags }) {
158
+ const { f, decision, outcome } = await attempt(true, flags.check);
159
+ return {
160
+ ok: outcome?.kind !== 'failed',
161
+ installed: f.installed,
162
+ latest: f.latest,
163
+ decision,
164
+ ...(outcome ? { outcome, ...report(outcome) } : {}),
165
+ };
166
+ }
package/kit/prefs.ts CHANGED
@@ -2,6 +2,8 @@ import { useSyncExternalStore } from 'react';
2
2
 
3
3
  // Theme, reduced motion and speed for the page, mirrored onto <html>
4
4
  // (.dark-mode, [data-motion="reduce"]) so CSS and JS read one source.
5
+ // Also whether the comments button and pins are hidden: a choice about the
6
+ // page a person is looking at, kept the same way as their theme.
5
7
 
6
8
  export type Appearance = 'system' | 'light' | 'dark';
7
9
 
@@ -15,7 +17,10 @@ const params = new URLSearchParams(location.search);
15
17
  const urlReduce = params.get('motion') === 'reduce';
16
18
  const listeners = new Set<() => void>();
17
19
 
20
+ const COMMENTS_KEY = 'proto:comments';
21
+
18
22
  let appearance: Appearance = readAppearance();
23
+ let commentsHidden = readStored(COMMENTS_KEY) === 'hidden';
19
24
  let forceReduce = false;
20
25
  let speed = 1;
21
26
  let lapse: LapseHandle | null = null;
@@ -23,11 +28,24 @@ let lapse: LapseHandle | null = null;
23
28
  function readAppearance(): Appearance {
24
29
  const fromUrl = params.get('theme');
25
30
  if (fromUrl === 'light' || fromUrl === 'dark' || fromUrl === 'system') return fromUrl;
31
+ const saved = readStored('proto:appearance');
32
+ if (saved === 'light' || saved === 'dark' || saved === 'system') return saved;
33
+ return 'light';
34
+ }
35
+
36
+ // Storage throws in a private window or with site data blocked: the page then runs on its defaults.
37
+ function readStored(key: string): string | null {
38
+ try {
39
+ return localStorage.getItem(key);
40
+ } catch {
41
+ return null;
42
+ }
43
+ }
44
+
45
+ function store(key: string, value: string) {
26
46
  try {
27
- const saved = localStorage.getItem('proto:appearance');
28
- if (saved === 'light' || saved === 'dark' || saved === 'system') return saved;
47
+ localStorage.setItem(key, value);
29
48
  } catch {}
30
- return 'light';
31
49
  }
32
50
 
33
51
  function emit() {
@@ -58,9 +76,7 @@ function applyMotion() {
58
76
  export function setAppearance(next: Appearance) {
59
77
  if (next === appearance) return;
60
78
  appearance = next;
61
- try {
62
- localStorage.setItem('proto:appearance', next);
63
- } catch {}
79
+ store('proto:appearance', next);
64
80
  applyTheme();
65
81
  emit();
66
82
  }
@@ -71,6 +87,16 @@ export function setForceReduce(on: boolean) {
71
87
  emit();
72
88
  }
73
89
 
90
+ /** Whether the comments button and pins are off the page. Remembered per browser. */
91
+ export const areCommentsHidden = () => commentsHidden;
92
+
93
+ export function setCommentsHidden(hidden: boolean) {
94
+ if (hidden === commentsHidden) return;
95
+ commentsHidden = hidden;
96
+ store(COMMENTS_KEY, hidden ? 'hidden' : 'shown');
97
+ emit();
98
+ }
99
+
74
100
  export const isDark = () => root.classList.contains('dark-mode');
75
101
  export const prefersReducedMotion = () => root.dataset.motion === 'reduce';
76
102
 
package/kit/ui/Menu.tsx CHANGED
@@ -21,10 +21,15 @@ export type MenuItem = {
21
21
  keys?: (string | { icon: IconName; label: string })[];
22
22
  danger?: boolean;
23
23
  disabled?: boolean;
24
+ /** One of a set of choices: drawn with a check when true. Several groups can share a menu, unlike `selected`. */
25
+ checked?: boolean;
24
26
  onClick?: () => void;
25
27
  };
26
28
 
27
- export type MenuEntry = MenuItem | '-';
29
+ /** A label over the items that follow it, for a menu that holds more than one group. */
30
+ export type MenuHeading = { heading: string };
31
+
32
+ export type MenuEntry = MenuItem | MenuHeading | '-';
28
33
 
29
34
  export type MenuConfig = {
30
35
  items: MenuEntry[];
@@ -35,6 +40,8 @@ export type MenuConfig = {
35
40
  selected?: string;
36
41
  checkable?: boolean;
37
42
  role?: 'menu' | 'listbox';
43
+ /** Added to the popup, which portals to <body>: the way a layer with its own material and stacking dresses its menus. */
44
+ className?: string;
38
45
  onSelect?: (value: string | undefined, item: MenuItem) => void;
39
46
  };
40
47
 
@@ -202,7 +209,12 @@ function MenuPopup({
202
209
  onSelect?.(item.value, item);
203
210
  };
204
211
 
205
- const cls = ['menu', shown && phase === 'open' ? 'is-open' : '', phase === 'closing' ? 'is-closing' : '']
212
+ const cls = [
213
+ 'menu',
214
+ config.className,
215
+ shown && phase === 'open' ? 'is-open' : '',
216
+ phase === 'closing' ? 'is-closing' : '',
217
+ ]
206
218
  .filter(Boolean)
207
219
  .join(' ');
208
220
 
@@ -226,12 +238,18 @@ function MenuPopup({
226
238
  // biome-ignore lint/a11y/useSemanticElements: an <hr> brings borders the menu rule does not want
227
239
  // biome-ignore lint/suspicious/noArrayIndexKey: separators have no identity; the list is fixed while open
228
240
  if (item === '-') return <div key={`sep-${n}`} className="menu-sep" role="separator" />;
241
+ if ('heading' in item)
242
+ return (
243
+ <div key={`head-${item.heading}`} className="menu-header" role="presentation">
244
+ {item.heading}
245
+ </div>
246
+ );
229
247
  return (
230
248
  <MenuRow
231
249
  key={`${item.label}-${item.value ?? n}`}
232
250
  item={item}
233
- role={role === 'listbox' ? 'option' : checkable ? 'menuitemradio' : 'menuitem'}
234
- selected={selected != null && selected === item.value}
251
+ role={rowRole(role, checkable || item.checked !== undefined)}
252
+ selected={item.checked ?? (selected != null && selected === item.value)}
235
253
  onPick={pick}
236
254
  />
237
255
  );
@@ -278,6 +296,9 @@ function MenuKeys({ keys }: { keys: NonNullable<MenuItem['keys']> }) {
278
296
  );
279
297
  }
280
298
 
299
+ const rowRole = (role: 'menu' | 'listbox', checkable: boolean | undefined) =>
300
+ role === 'listbox' ? 'option' : checkable ? 'menuitemradio' : 'menuitem';
301
+
281
302
  const rowClass = (item: MenuItem, selected: boolean) =>
282
303
  ['menu-item', item.danger && 'is-danger', item.disabled && 'is-disabled', selected && 'is-selected']
283
304
  .filter(Boolean)
@@ -334,6 +355,7 @@ export function Select({
334
355
  onChange,
335
356
  width,
336
357
  className,
358
+ menuClassName,
337
359
  placeholder = 'Select',
338
360
  labelId,
339
361
  'aria-label': ariaLabel,
@@ -343,6 +365,7 @@ export function Select({
343
365
  onChange: (value: string) => void;
344
366
  width?: number;
345
367
  className?: string;
368
+ menuClassName?: string;
346
369
  placeholder?: string;
347
370
  labelId?: string;
348
371
  'aria-label'?: string;
@@ -355,6 +378,7 @@ export function Select({
355
378
  items: options.map((o) => ({ label: o.label, value: o.value })),
356
379
  selected: value ?? undefined,
357
380
  label: ariaLabel,
381
+ className: menuClassName,
358
382
  width: (trigger) => Math.max(trigger.offsetWidth, width || 0),
359
383
  onSelect: (v) => {
360
384
  if (v != null && v !== value) onChange(v);
package/kit/ui/index.ts CHANGED
@@ -1,6 +1,14 @@
1
1
  export { Badge, Button, Checkbox, Chevron, Segmented } from './Button';
2
2
  export { installPressFeedback } from './layer';
3
- export { type MenuConfig, type MenuEntry, type MenuItem, Select, type SelectOption, useMenu } from './Menu';
3
+ export {
4
+ type MenuConfig,
5
+ type MenuEntry,
6
+ type MenuHeading,
7
+ type MenuItem,
8
+ Select,
9
+ type SelectOption,
10
+ useMenu,
11
+ } from './Menu';
4
12
  export {
5
13
  confirmDialog,
6
14
  OverlayHost,