pi-pocket 0.27.0-beta.9 → 0.27.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.
Files changed (47) hide show
  1. package/docs/design/design-mode.md +1 -1
  2. package/docs/extensions/reference/names.md +1 -1
  3. package/docs/map.md +3 -2
  4. package/package.json +1 -1
  5. package/src/server/design/docsite-color-section.ts +0 -1
  6. package/src/server/design/docsite-components.ts +0 -1
  7. package/src/server/design/docsite-core.ts +4 -14
  8. package/src/server/design/docsite-space.ts +0 -2
  9. package/src/server/design/docsite.ts +0 -4
  10. package/src/server/design/fix.ts +136 -15
  11. package/src/server/design/guide.ts +0 -1
  12. package/src/server/design/lint-color.ts +34 -12
  13. package/src/server/design/lint-suggest.ts +74 -28
  14. package/src/server/design/scan-categorize.ts +0 -2
  15. package/src/server/design/scan-colors.ts +1 -9
  16. package/src/server/design/scan-facts-files.ts +0 -1
  17. package/src/server/design/scan-facts.ts +0 -4
  18. package/src/server/design/scan-files.ts +0 -2
  19. package/src/server/design/scan-import-eval.ts +0 -1
  20. package/src/server/design/scan-import.ts +0 -1
  21. package/src/server/design/scan-infer.ts +1 -1
  22. package/src/server/design/scan-palette.ts +0 -2
  23. package/src/server/design/scan-parse.ts +0 -3
  24. package/src/server/design/scan-prepare.ts +0 -1
  25. package/src/server/design/scan-render-pages.ts +90 -8
  26. package/src/server/design/scan-render-probe.ts +0 -1
  27. package/src/server/design/scan-roles.ts +2 -9
  28. package/src/server/design/scan-scales.ts +0 -1
  29. package/src/server/design/scan-tailwind.ts +0 -1
  30. package/src/server/design/tokens-cache.ts +202 -0
  31. package/src/server/design/tokens-io.ts +14 -0
  32. package/src/server/design/tokens-values.ts +5 -2
  33. package/src/server/design/tokens.ts +11 -3
  34. package/src/server/extensions/artifacts.ts +0 -1
  35. package/src/server/extensions/codemode.ts +13 -0
  36. package/src/server/extensions/design/color.js +0 -1
  37. package/src/server/extensions/design/style.css +5 -0
  38. package/src/server/extensions/design/system-routes.ts +7 -4
  39. package/src/server/extensions/design/system-widgets.js +0 -1
  40. package/src/server/extensions/design/system.css +0 -2
  41. package/src/server/extensions/prompt.ts +1 -6
  42. package/src/server/extensions/tool-search.ts +3 -17
  43. package/src/server/gallery/reach.ts +36 -17
  44. package/docs/design/notes-a.md +0 -106
  45. package/docs/design/notes-b.md +0 -123
  46. package/docs/design/notes-c.md +0 -92
  47. package/docs/design/notes-d.md +0 -78
@@ -1,6 +1,6 @@
1
1
  # Design mode (0.26.0)
2
2
 
3
- Status: built. The four streams (A to D) are merged into `feat/design`, off `release/0.26.0`. This page is the plan, corrected where the build differs from it. Each place that changed says "Built:". What each stream built is in `notes-a.md` to `notes-d.md`; the words for the release are in `release-notes-design.md`.
3
+ Status: built. The four streams (A to D) are merged into `feat/design`, off `release/0.26.0`. This page is the plan, corrected where the build differs from it. Each place that changed says "Built:". The words for the release are in `release-notes-design.md`.
4
4
 
5
5
  Design mode gives Pi Pocket what Claude Design has: a big canvas beside the chat, where Pi makes interactive designs (prototypes, screens, one-pagers, slide decks), and people point at them, comment, tweak, edit text, compare versions and variations, export, and hand off to code.
6
6
 
@@ -7,7 +7,7 @@ The rules for the names that a module gives. These are the names of its file, ex
7
7
  To install an extension with the name of an installed extension replaces that extension. A tool with the name of another tool replaces it in all sessions. Thus Pi Pocket refuses a drop-in that would take a name that Pi Pocket keeps, or a name that another module has. Menu → Extensions says why.
8
8
 
9
9
  - **Extension names that Pi Pocket keeps:** `coding-tools`, and all names that start with `pocket-`, such as `pocket-core`, `pocket-prompt`, and `pocket-guard`. This is true also when that built-in module is off.
10
- - **Built-in tools:** `read`, `write`, `edit`, `bash`, `artifact`, `artifact_inline`, `browser`, `subagent`, `team`, `schedule`, `codemode`, `tool_search`, and `memory`. PiP's tools: `sessions`, `session_read`, `session_start`, `session_send`, `session_follow`, `session_stop`, `session_archive`, `session_schedule`, `approvals`, `repo_watch`, and `session_watch_pr`. The triggers' tool: `watch_pr`. Design's tools: `design_preview`, `design_export`, and `design_system`.
10
+ - **Built-in tools:** `read`, `write`, `edit`, `bash`, `artifact`, `artifact_inline`, `browser`, `subagent`, `team`, `schedule`, `background`, `codemode`, `tool_search`, `memory`, `ask`, and `ask_someone`. PiP's tools: `sessions`, `session_read`, `session_start`, `session_send`, `session_follow`, `session_stop`, `session_archive`, `session_schedule`, `approvals`, `repo_watch`, and `session_watch_pr`. The triggers' tool: `watch_pr`. Design's tools: `design_preview`, `design_export`, and `design_system`.
11
11
  - **Names that another module has:** the first module to install an extension or tool keeps its name.
12
12
 
13
13
  Give each extension and tool a name of your own, with a prefix: `example-clock`, `acme_lookup`. To change how a built-in tool works, do not replace it. Wrap it (`wrapTool` in Pi Durable's README), or check its calls with a hook.
package/docs/map.md CHANGED
@@ -150,6 +150,7 @@ The agent's side of Design mode. `extensions/design.ts` installs it (see Extensi
150
150
  | `design/pptx.ts` | The PPTX writer: one image for each slide, at the deck's slide size (16:9 by default), with the slide's text as speaker notes, through `zip.ts` |
151
151
  | `design/system-types.ts` | The shared shapes: `DesignSystem`, `ResolvedToken`, `ComponentSpec`, `SystemChange`, `CheckReport`, `CheckFinding` |
152
152
  | `design/tokens.ts` | The tokens engine: `loadDesignSystem`, `writeDesignSystem` (validate, atomic writes, rebuild `dist/`), `compileDesignSystem`, `systemSummary`; `tokens-model.ts` (`buildSystem`: the phases in order) with `tokens-model-defs.ts` (definitions and modes), `tokens-model-resolve.ts` (types and references), `tokens-model-checks.ts` (the warnings and contrast), and `tokens-model-report.ts` (the problem list), `tokens-values.ts` (value forms), `tokens-ramps.ts` (the ramp-order warning), `tokens-compile.ts` (`tokens.css`, `components.css`), `tokens-tailwind.ts` (the Tailwind v4 theme), `tokens-names.ts` (the names table, `names.md`), `tokens-dtcg.ts` (the DTCG files for each mode, the 2025.10 forms, and `tokens.studio.json`), `tokens-io.ts` (bounded reads without links), `tokens-summary.ts` (the prompt summary: roles and components first), `tokens-base.ts` |
153
+ | `design/tokens-cache.ts` | A loaded system kept while its folder's files stay the same: the revision is read on every call, so an edit by any program shows at once |
153
154
  | `design/components.ts` | Component specimens: `components/<slug>.html` with its metadata, CSS, and one template for each state |
154
155
  | `design/color.ts` | Color math: re-exports `extensions/design/color.js` (every CSS color syntax and DTCG color objects, OKLab and OKLCH, WCAG luminance and contrast, hex), the one copy that the server and the System view share, and adds `mixColors` |
155
156
  | `design/system.ts` | `design_system`: the actions on `.pi/design/` and the 0.26 `.pi/design-system.md`, its parameters, bounded, read and written without following links, output fenced as project data |
@@ -158,11 +159,11 @@ The agent's side of Design mode. `extensions/design.ts` installs it (see Extensi
158
159
  | `design/scan-render.ts` | The rendered scan: a project's HTML pages shown offline in the private Chromium, once as they are and once in dark mode, and read as the browser computed them; the static scan wins where it is sure, the rendered values fill the rest |
159
160
  | `design/scan-render-pages.ts` | The pages the rendered scan shows: the project's HTML (and its built output), the files they need, and the custom property names and dark-mode switches the stylesheets name; a bounded walk that follows no link |
160
161
  | `design/scan-render-probe.ts` | The script that reads a rendered page in an isolated world: only values the author's styles set (it reads the page again with all styles off), as bounded plain data |
161
- | `design/lint.ts` | `checkDesign` and `checkPage`: the page checks of `design_preview`, the Check tab, and the CLI; `lint-page.ts` and `lint-page-*.ts` (the script the page runs, in an isolated world: setup, the author's CSS index, values, elements, states, focus, and page checks), `lint-color.ts` (token sets and OKLab distance); `analyze` calls its phases in `lint-analyze-system.ts` (color, font, size), `lint-analyze-contrast.ts`, `lint-analyze-page.ts`, and `lint-analyze-util.ts` |
162
+ | `design/lint.ts` | `checkDesign` and `checkPage`: the page checks of `design_preview` and the Check tab; `lint-page.ts` and `lint-page-*.ts` (the script the page runs, in an isolated world: setup, the author's CSS index, values, elements, states, focus, and page checks), `lint-color.ts` (token sets and OKLab distance); `analyze` calls its phases in `lint-analyze-system.ts` (color, font, size), `lint-analyze-contrast.ts`, `lint-analyze-page.ts`, and `lint-analyze-util.ts` |
162
163
  | `design/lint-suggest.ts` | Which token a check suggests for a color: what a token is for, how the page uses the color, and the order of preference |
163
164
  | `design/fix.ts` | `applyExactFixes`: one-tap fixes; a literal that equals a token exactly becomes `var(--token)`, only in `<style>` and `style=""`, only where the place is certain |
164
165
  | `design/docsite.ts` | `renderSystemDoc`: the documentation page of a system; `docsite-core.ts` (the context, counts, and the nonce CSP), one file for each group of sections (`docsite-color-section.ts`, `docsite-type.ts`, `docsite-space.ts`, `docsite-components.ts`, `docsite-reference.ts`), `docsite-sanitize.ts` (the allowlist sanitizer and CSS parser for component specimens, drawn in shadow roots), `docsite-css.ts` and `docsite-js.ts` (the page's one sheet and one script), `docsite-markdown.ts` |
165
- | `design/guide.ts` | The prompt section: a page skeleton, craft rules, and the design system's summary as fenced, untrusted data |
166
+ | `design/guide.ts` | The prompt section: a pointer to `guides/design.md`, and the design system's summary as fenced, untrusted data |
166
167
 
167
168
  ### Elsewhere
168
169
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-pocket",
3
- "version": "0.27.0-beta.9",
3
+ "version": "0.27.0",
4
4
  "description": "A durable, multiplayer, mobile-first web app for Pi agents, built on Pi Durable",
5
5
  "keywords": [
6
6
  "pi",
@@ -208,7 +208,6 @@ export function colorSection(ctx: Ctx): string | undefined {
208
208
  `<h3 id="color-roles">Roles</h3><p class="sub">Roles say what a color is for. Use a role, never a palette step, so the color follows the mode.</p>${capNote(roles.length, allRoles.length)}`,
209
209
  );
210
210
 
211
- // Groups of one or two cards would leave rows half empty: they share one grid.
212
211
  const groups = grouped(roles);
213
212
  const small = groups.filter(([, list]) => list.length <= 2);
214
213
  const shown: [string, ResolvedToken[]][] = [
@@ -15,7 +15,6 @@ import type { ComponentSpec } from "./system-types.ts";
15
15
  export const snippet = (id: string, text: string, label: string, kind = "") =>
16
16
  `<div class="snip"${kind === "" ? "" : ` data-kind="${kind}" data-panel="${esc(label)}"`}><div class="snip-head"><span>${esc(label)}</span><button class="mini" type="button" data-copy-from="${esc(id)}">Copy</button></div><pre id="${esc(id)}"><code>${esc(text)}</code></pre></div>`;
17
17
 
18
- // The page's script draws each state from the listings below, sanitized, in a shadow root (see docsite-js.ts).
19
18
  function stage(ctx: Ctx): string {
20
19
  const ground = groundToken(ctx);
21
20
  const text = textToken(ctx);
@@ -92,7 +92,6 @@ export function stackOf(value: unknown): string | undefined {
92
92
  export const valueIn = (token: ResolvedToken, mode: string): ModeValue | undefined =>
93
93
  token.modes[mode];
94
94
 
95
- /** A color as CSS text: the engine's own form when it gave one, else the value itself. */
96
95
  function colorText(value: unknown): string | undefined {
97
96
  if (typeof value === "string") {
98
97
  return value;
@@ -242,7 +241,6 @@ export interface Ctx {
242
241
 
243
242
  export const nameOfRef = (text: string) => text.replace(/^\{|\}$/g, "").trim();
244
243
 
245
- /** Text that is the same in every mode is written once; texts that differ show by the mode in force, in CSS alone. */
246
244
  export function variants(ctx: Ctx, make: (mode: string) => string): string {
247
245
  const texts = ctx.modes.map((mode) => make(mode));
248
246
 
@@ -352,7 +350,6 @@ export const copyName = (token: ResolvedToken) => `<button class="tk">${esc(toke
352
350
  export const descOf = (token: ResolvedToken) =>
353
351
  token.description === undefined ? "" : `<span class="desc">${esc(token.description)}</span>`;
354
352
 
355
- /** Specimens of one section, and whether any list was cut, for one note under it. */
356
353
  export function limiter(ctx: Ctx): {
357
354
  take: (list: ResolvedToken[]) => ResolvedToken[];
358
355
  note: () => string;
@@ -378,18 +375,13 @@ export function limiter(ctx: Ctx): {
378
375
  };
379
376
  }
380
377
 
381
- /** A token as a row: its name and description, its value in each mode, and a sample. */
382
378
  export function rowOf(ctx: Ctx, token: ResolvedToken, sample: string): string {
383
379
  const value = variants(ctx, (mode) => esc(plain(token.type, valueIn(token, mode))));
384
380
 
385
381
  return `<div class="row" data-s><div class="meta">${copyName(token)}${descOf(token)}</div><div class="val">${value}</div><div class="sample">${sample}</div></div>`;
386
382
  }
387
383
 
388
- /**
389
- * The headline (the number in the navigation) is the section's role tokens, the semantic tier; a section with none
390
- * counts its primitives. The palette and a component's own tokens are counted inside the section. The System view
391
- * counts the same way.
392
- */
384
+ /** The System view counts the same way: semantic tokens, else primitives. */
393
385
  export function sectionCount(ctx: Ctx, id: SectionId) {
394
386
  const list = tokensOf(ctx, id);
395
387
  const semantic = list.filter((token) => token.tier === "semantic").length;
@@ -419,7 +411,7 @@ export function countsLine(ctx: Ctx, id: SectionId): string {
419
411
  return count.total === 0 ? "" : `<p class="counts">${parts.join(" · ")}</p>`;
420
412
  }
421
413
 
422
- function modeCell(ctx: Ctx, token: ResolvedToken, mode: string, across: number): string {
414
+ function modeCell(token: ResolvedToken, mode: string, across: number): string {
423
415
  const value = valueIn(token, mode);
424
416
  const hex = token.type === "color" ? hexOf(token, mode) : undefined;
425
417
  const body = `${hex === undefined ? "" : `<i class="chip" style="background:${esc(hex)}"></i>`}${esc(clip(plain(token.type, value), 160))}`;
@@ -429,7 +421,6 @@ function modeCell(ctx: Ctx, token: ResolvedToken, mode: string, across: number):
429
421
  : `<td data-label="${esc(modeLabel(mode))}" class="v">${body}</td>`;
430
422
  }
431
423
 
432
- /** Rows of the token table: a column for each mode, or one cell across them when the value is the same in every mode. */
433
424
  export function tableRows(ctx: Ctx, tokens: ResolvedToken[]): string {
434
425
  return tokens
435
426
  .map((token) => {
@@ -438,8 +429,8 @@ export function tableRows(ctx: Ctx, tokens: ResolvedToken[]): string {
438
429
  );
439
430
  const same = ctx.modes.length > 1 && texts.every((text) => text === texts[0]);
440
431
  const cells = same
441
- ? modeCell(ctx, token, ctx.modes[0]!, ctx.modes.length)
442
- : ctx.modes.map((mode) => modeCell(ctx, token, mode, 1)).join("");
432
+ ? modeCell(token, ctx.modes[0]!, ctx.modes.length)
433
+ : ctx.modes.map((mode) => modeCell(token, mode, 1)).join("");
443
434
  const deprecated =
444
435
  token.deprecated === undefined || token.deprecated === false
445
436
  ? ""
@@ -450,7 +441,6 @@ export function tableRows(ctx: Ctx, tokens: ResolvedToken[]): string {
450
441
  .join("");
451
442
  }
452
443
 
453
- /** The tokens of a section that no specimen drew (most are a component's), so every token is on the page. */
454
444
  export function moreTokens(ctx: Ctx, id: SectionId): string {
455
445
  const left = tokensOf(ctx, id).filter((token) => !ctx.claimed.has(token));
456
446
 
@@ -37,7 +37,6 @@ export function spacingSection(ctx: Ctx): string | undefined {
37
37
  const own = mine.filter((token) => token.tier !== "component" && token.type === "dimension");
38
38
  const space = take(own.filter((token) => SPACE_ROOT.test(rootOf(token))));
39
39
  const sizes = take(own.filter((token) => SIZE_ROOT.test(rootOf(token))));
40
- // The roles that use a step: semantic tokens of the section that are neither the scale nor sizes.
41
40
  const roles = take(
42
41
  own.filter(
43
42
  (token) =>
@@ -111,7 +110,6 @@ export function shadowSection(ctx: Ctx): string | undefined {
111
110
  .join("")}</div>${note()}${moreTokens(ctx, "shadows")}`;
112
111
  }
113
112
 
114
- /** Breakpoints, borders, layers, and what fits no other section: one table. */
115
113
  export function otherSection(ctx: Ctx): string | undefined {
116
114
  const mine = tokensOf(ctx, "other");
117
115
 
@@ -58,7 +58,6 @@ const ACCENTS = [
58
58
  "color.accent",
59
59
  ];
60
60
 
61
- /** The page's own accent: the system's, when it reads at 4.5:1 on the page's ground in that scheme. */
62
61
  function chromeAccent(ctx: Ctx, theme: "light" | "dark"): string {
63
62
  const fallback = theme === "dark" ? "#8fb0ff" : "#3557a5";
64
63
  const page = parseColor(theme === "dark" ? "#0e0f15" : "#fafafc")!;
@@ -75,7 +74,6 @@ function chromeAccent(ctx: Ctx, theme: "light" | "dark"): string {
75
74
 
76
75
  const ICON_MENU = `<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M3 5.5h14M3 10h14M3 14.5h14"/></svg>`;
77
76
 
78
- /** The swatches of the overview: the base roles first, in a fixed order, then any semantic color, up to 12. */
79
77
  const SAMPLER: [string, string[], RegExp][] = [
80
78
  ["background", BASE_GROUNDS, /^color\.(bg|background)\.(base|default|canvas|page)$/],
81
79
  [
@@ -138,7 +136,6 @@ function sampler(ctx: Ctx): string {
138
136
  .join("")}</div>`;
139
137
  }
140
138
 
141
- /** The tokens as custom properties on `body.ds`: the first mode's values, then what each other mode changes. */
142
139
  function tokenVars(ctx: Ctx): string {
143
140
  const first = ctx.modes[0]!;
144
141
  const declare = (mode: string, only: (token: ResolvedToken) => boolean) =>
@@ -168,7 +165,6 @@ function tokenVars(ctx: Ctx): string {
168
165
  return rules.join("\n");
169
166
  }
170
167
 
171
- // An artifact holds 2 MB at most: a system so large that its page would not fit shows fewer rows in the token table.
172
168
  export function renderSystemDoc(system: DesignSystem): SystemDoc {
173
169
  let rows = MAX_TOKENS;
174
170
  let doc = build(system, rows);
@@ -405,7 +405,6 @@ function colorIn(entry: ModeValue) {
405
405
  return css === undefined ? undefined : parseColor(css);
406
406
  }
407
407
 
408
- /** True when the token has one value in every mode of the system: a page that uses it looks the same in each. */
409
408
  export function sameInEveryMode(token: ResolvedToken, modes: string[]): boolean {
410
409
  const [first, ...rest] = modes.map((mode) => token.modes[mode]);
411
410
 
@@ -502,6 +501,112 @@ function families(text: string): string[] {
502
501
  .filter((name) => name !== "");
503
502
  }
504
503
 
504
+ interface Piece {
505
+ text: string;
506
+ start: number;
507
+ end: number;
508
+ color: ReturnType<typeof parseColor> | null | false;
509
+ }
510
+
511
+ const pieces = new WeakMap<Declaration, Piece[]>();
512
+
513
+ function piecesOf(declaration: Declaration): Piece[] {
514
+ let found = pieces.get(declaration);
515
+
516
+ if (found === undefined) {
517
+ found = tokens(declaration.masked).map((token) => ({ ...token, color: false as const }));
518
+ pieces.set(declaration, found);
519
+ }
520
+
521
+ return found;
522
+ }
523
+
524
+ function colorOf(piece: Piece) {
525
+ if (piece.color === false) {
526
+ piece.color = parseColor(piece.text) ?? null;
527
+ }
528
+
529
+ return piece.color ?? undefined;
530
+ }
531
+
532
+ type Color = NonNullable<ReturnType<typeof parseColor>>;
533
+
534
+ const byteOf = (channel: number) => Math.round(channel * 255);
535
+ const colorIndexes = new WeakMap<Declaration[], Map<string, [number, number][]>>();
536
+
537
+ // A color that `sameColor` takes is at most half a byte step away: in this bucket or a next one.
538
+ function colorIndexOf(all: Declaration[]): Map<string, [number, number][]> {
539
+ let index = colorIndexes.get(all);
540
+
541
+ if (index === undefined) {
542
+ const made = new Map<string, [number, number][]>();
543
+
544
+ all.forEach((declaration, at) => {
545
+ piecesOf(declaration).forEach((piece, place) => {
546
+ const color = colorOf(piece);
547
+
548
+ if (color !== undefined) {
549
+ const key = `${byteOf(color.r)},${byteOf(color.g)},${byteOf(color.b)}`;
550
+ const list = made.get(key);
551
+
552
+ if (list === undefined) {
553
+ made.set(key, [[at, place]]);
554
+ } else {
555
+ list.push([at, place]);
556
+ }
557
+ }
558
+ });
559
+ });
560
+ index = made;
561
+ colorIndexes.set(all, index);
562
+ }
563
+
564
+ return index;
565
+ }
566
+
567
+ // The same places, in the same order, as a scan of every declaration of the properties, piece by piece.
568
+ function colorMatches(all: Declaration[], literal: Color, properties: Set<string>): Match[] {
569
+ const index = colorIndexOf(all);
570
+ const keys = new Set<string>();
571
+ const [r, g, b] = [byteOf(literal.r), byteOf(literal.g), byteOf(literal.b)];
572
+
573
+ for (const dr of [-1, 0, 1]) {
574
+ for (const dg of [-1, 0, 1]) {
575
+ for (const db of [-1, 0, 1]) {
576
+ keys.add(`${r + dr},${g + dg},${b + db}`);
577
+ }
578
+ }
579
+ }
580
+
581
+ const found: [number, number][] = [];
582
+
583
+ for (const key of keys) {
584
+ for (const item of index.get(key) ?? []) {
585
+ const declaration = all[item[0]]!;
586
+
587
+ if (
588
+ properties.has(declaration.property) &&
589
+ sameColor(colorOf(piecesOf(declaration)[item[1]]!)!, literal)
590
+ ) {
591
+ found.push(item);
592
+ }
593
+ }
594
+ }
595
+
596
+ return found
597
+ .sort((x, y) => x[0] - y[0] || x[1] - y[1])
598
+ .map(([at, place]) => {
599
+ const declaration = all[at]!;
600
+ const piece = piecesOf(declaration)[place]!;
601
+
602
+ return {
603
+ start: declaration.start + piece.start,
604
+ end: declaration.start + piece.end,
605
+ declaration,
606
+ };
607
+ });
608
+ }
609
+
505
610
  function placesIn(
506
611
  content: string,
507
612
  declaration: Declaration,
@@ -518,18 +623,11 @@ function placesIn(
518
623
  }
519
624
 
520
625
  const found: { start: number; end: number }[] = [];
521
- const literal = fix.kind === "color" ? parseColor(fix.literal) : undefined;
522
626
  const pixels = fix.kind === "length" ? Number.parseFloat(fix.literal) : Number.NaN;
523
627
  let first = true;
524
628
 
525
- for (const token of tokens(declaration.masked)) {
526
- if (fix.kind === "color") {
527
- const color = literal === undefined ? undefined : parseColor(token.text);
528
-
529
- if (color !== undefined && literal !== undefined && sameColor(color, literal)) {
530
- found.push({ start: base + token.start, end: base + token.end });
531
- }
532
- } else if (/^\d*\.?\d+px$/i.test(token.text)) {
629
+ for (const token of piecesOf(declaration)) {
630
+ if (/^\d*\.?\d+px$/i.test(token.text)) {
533
631
  // In the `font` shorthand only the first length is the size; the next, after a slash, is the line height.
534
632
  if (
535
633
  Number.parseFloat(token.text) === pixels &&
@@ -566,6 +664,17 @@ export function applyExactFixes(
566
664
 
567
665
  const scanned = regions(content);
568
666
  const all = scanned.regions.flatMap((region) => declarations(content, region));
667
+ const byProperty = new Map<string, number[]>();
668
+
669
+ all.forEach((declaration, index) => {
670
+ const list = byProperty.get(declaration.property);
671
+
672
+ if (list === undefined) {
673
+ byProperty.set(declaration.property, [index]);
674
+ } else {
675
+ list.push(index);
676
+ }
677
+ });
569
678
  const fixable = findings.filter((finding) => finding.fix !== undefined);
570
679
 
571
680
  for (const finding of findings) {
@@ -588,13 +697,25 @@ export function applyExactFixes(
588
697
  const properties = new Set(fix.properties.map((property) => property.toLowerCase()));
589
698
  const matches: Match[] = [];
590
699
 
591
- for (const declaration of all) {
592
- if (!properties.has(declaration.property)) {
593
- continue;
700
+ if (fix.kind === "color") {
701
+ const literal = parseColor(fix.literal);
702
+
703
+ for (const match of literal === undefined
704
+ ? []
705
+ : colorMatches(all, literal, properties)) {
706
+ matches.push(match);
594
707
  }
708
+ } else {
709
+ const order = [...properties]
710
+ .flatMap((property) => byProperty.get(property) ?? [])
711
+ .sort((a, b) => a - b);
712
+
713
+ for (const index of order) {
714
+ const declaration = all[index]!;
595
715
 
596
- for (const place of placesIn(content, declaration, fix)) {
597
- matches.push({ ...place, declaration });
716
+ for (const place of placesIn(content, declaration, fix)) {
717
+ matches.push({ ...place, declaration });
718
+ }
598
719
  }
599
720
  }
600
721
 
@@ -10,7 +10,6 @@ import { loadDesignSystem, systemSummary } from "./tokens.ts";
10
10
 
11
11
  export const SUMMARY_BYTES = 12_000;
12
12
 
13
- /** The full instructions (order of work, skeleton, craft, checks, design systems): read when a design is made. */
14
13
  export const DESIGN_GUIDE = join(APP_ROOT, "src", "server", "guides", "design.md");
15
14
 
16
15
  const GUIDE = `Designs live in the Design canvas as HTML artifacts, shown beside the chat. Before you make or change a design, read ${DESIGN_GUIDE}: the order of work, the page skeleton, craft, checks, feedback, the hand-off to code, and how to make or use a design system. Check each design with design_preview at mobile and desktop sizes before you reply.`;
@@ -1,4 +1,4 @@
1
- import { colorObjectCss, contrastRatio, oklabOf, toHex } from "./color.ts";
1
+ import { colorObjectCss, luminance, oklabOf, toHex } from "./color.ts";
2
2
  import { sameInEveryMode } from "./fix.ts";
3
3
  import type { DesignSystem, ModeValue, ResolvedToken } from "./system-types.ts";
4
4
 
@@ -10,24 +10,47 @@ const clamp = (value: number, low: number, high: number) => Math.min(high, Math.
10
10
  export const toOklab = (red: number, green: number, blue: number): [number, number, number] =>
11
11
  oklabOf({ r: red / 255, g: green / 255, b: blue / 255, a: 1 });
12
12
 
13
+ // A Check compares each page color with every token: the conversions are kept by array, and no color array is changed in place.
14
+ const labs = new WeakMap<readonly number[], [number, number, number]>();
15
+ const lights = new WeakMap<readonly number[], number>();
16
+
17
+ export function labOf(color: readonly number[]): [number, number, number] {
18
+ let lab = labs.get(color);
19
+
20
+ if (lab === undefined) {
21
+ lab = toOklab(color[0]!, color[1]!, color[2]!);
22
+ labs.set(color, lab);
23
+ }
24
+
25
+ return lab;
26
+ }
27
+
28
+ function lightOf(color: readonly number[]): number {
29
+ let light = lights.get(color);
30
+
31
+ if (light === undefined) {
32
+ light = luminance({ r: color[0]! / 255, g: color[1]! / 255, b: color[2]! / 255, a: 1 });
33
+ lights.set(color, light);
34
+ }
35
+
36
+ return light;
37
+ }
38
+
13
39
  // The OKLab distance times 100: about 1 is the smallest step a person sees, 0.4 is one 8-bit step. The alpha difference in percent is added.
14
40
  export function colorDistance(a: RgbaTuple, b: RgbaTuple): number {
15
- const [l1, a1, b1] = toOklab(a[0], a[1], a[2]);
16
- const [l2, a2, b2] = toOklab(b[0], b[1], b[2]);
41
+ const [l1, a1, b1] = labOf(a);
42
+ const [l2, a2, b2] = labOf(b);
17
43
  const lab = Math.hypot(l1 - l2, a1 - a2, b1 - b2) * 100;
18
44
 
19
45
  return lab + Math.abs(a[3] - b[3]) * 100;
20
46
  }
21
47
 
48
+ // `contrastRatio` of two opaque colors.
22
49
  export function contrastOf(a: readonly number[], b: readonly number[]): number {
23
- const color = (value: readonly number[]) => ({
24
- r: value[0]! / 255,
25
- g: value[1]! / 255,
26
- b: value[2]! / 255,
27
- a: 1,
28
- });
29
-
30
- return contrastRatio(color(a), color(b));
50
+ const one = lightOf(a);
51
+ const two = lightOf(b);
52
+
53
+ return (Math.max(one, two) + 0.05) / (Math.min(one, two) + 0.05);
31
54
  }
32
55
 
33
56
  export function formatColor(color: readonly number[]): string {
@@ -142,7 +165,6 @@ interface TokenColor {
142
165
  tier: ResolvedToken["tier"];
143
166
  css: string;
144
167
  rgba?: RgbaTuple;
145
- /** False when the value differs between modes: only a steady token may be put in a page by a one-tap fix. */
146
168
  steady?: boolean;
147
169
  }
148
170
 
@@ -1,7 +1,7 @@
1
1
  // Suggestion rules: a token of the same color to the last digit wins, by role (text for text, a ground for a background, a border for a border), then an accent, a palette step, another role, and a component's own token last.
2
2
  // Otherwise the nearest token of the use's role (or with no role, never a component's) that stays in the hue family: a neutral gets a neutral, a chromatic color a near hue.
3
3
  // A color that fails contrast gets a passing token by the same rules; if none of its hue passes, a text or border token, and the message says that the hue changes.
4
- import { colorDistance, type RgbaTuple, toOklab, type TokenSet } from "./lint-color.ts";
4
+ import { colorDistance, labOf, type RgbaTuple, toOklab, type TokenSet } from "./lint-color.ts";
5
5
 
6
6
  /** Two colors this close (see `colorDistance`) are the same: a little over 2 steps of 8 bits. */
7
7
  export const SAME_COLOR = 1;
@@ -27,13 +27,34 @@ const ROLE_WORDS: [ColorRole, RegExp][] = [
27
27
  ["background", /^(bg|background|surface|fill|canvas|base|ground|wash|soft|scrim|overlay)$/],
28
28
  ];
29
29
 
30
- export function colorRoleOf(name: string): ColorRole | undefined {
31
- const words = name
32
- .replace(/([a-z])([A-Z])/g, "$1 $2")
33
- .toLowerCase()
34
- .split(/[^a-z0-9]+/);
30
+ const names = new Map<string, { words: string[]; role: ColorRole | undefined }>();
31
+
32
+ function wordsOf(name: string): { words: string[]; role: ColorRole | undefined } {
33
+ let found = names.get(name);
34
+
35
+ if (found === undefined) {
36
+ const words = name
37
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
38
+ .toLowerCase()
39
+ .split(/[^a-z0-9]+/);
40
+
41
+ found = {
42
+ words,
43
+ role: ROLE_WORDS.find(([, pattern]) => words.some((word) => pattern.test(word)))?.[0],
44
+ };
45
+
46
+ if (names.size >= 20_000) {
47
+ names.clear();
48
+ }
49
+
50
+ names.set(name, found);
51
+ }
52
+
53
+ return found;
54
+ }
35
55
 
36
- return ROLE_WORDS.find(([, pattern]) => words.some((word) => pattern.test(word)))?.[0];
56
+ export function colorRoleOf(name: string): ColorRole | undefined {
57
+ return wordsOf(name).role;
37
58
  }
38
59
 
39
60
  export const USE_ROLE: Record<string, ColorRole> = {
@@ -68,10 +89,19 @@ export const USE_PROPERTIES: Record<string, string[]> = {
68
89
  outline: ["outline-color", "outline"],
69
90
  };
70
91
 
92
+ const lchs = new WeakMap<readonly number[], { c: number; h: number }>();
93
+
71
94
  function lch(color: readonly number[]): { c: number; h: number } {
72
- const [, a, b] = toOklab(color[0]!, color[1]!, color[2]!);
95
+ let found = lchs.get(color);
96
+
97
+ if (found === undefined) {
98
+ const [, a, b] = labOf(color);
99
+
100
+ found = { c: Math.hypot(a, b), h: ((Math.atan2(b, a) * 180) / Math.PI + 360) % 360 };
101
+ lchs.set(color, found);
102
+ }
73
103
 
74
- return { c: Math.hypot(a, b), h: ((Math.atan2(b, a) * 180) / Math.PI + 360) % 360 };
104
+ return found;
75
105
  }
76
106
 
77
107
  const hueGap = (a: number, b: number) => Math.min(Math.abs(a - b), 360 - Math.abs(a - b));
@@ -147,18 +177,16 @@ function rank(token: Token, role: ColorRole | undefined): number {
147
177
  return role === undefined ? 1 : 3;
148
178
  }
149
179
 
180
+ const STRONG: Record<ColorRole, string[]> = {
181
+ text: ["text"],
182
+ background: ["bg", "background", "surface"],
183
+ border: ["border"],
184
+ };
185
+
150
186
  function strength(token: Token, role: ColorRole | undefined): number {
151
- const words = token.name
152
- .replace(/([a-z])([A-Z])/g, "$1 $2")
153
- .toLowerCase()
154
- .split(/[^a-z0-9]+/);
155
- const named = {
156
- text: ["text"],
157
- background: ["bg", "background", "surface"],
158
- border: ["border"],
159
- }[role ?? "text"];
160
-
161
- return words.some((word) => named.includes(word)) ? 0 : 1;
187
+ const named = STRONG[role ?? "text"];
188
+
189
+ return wordsOf(token.name).words.some((word) => named.includes(word)) ? 0 : 1;
162
190
  }
163
191
 
164
192
  const colored = (set: TokenSet) => set.colors.filter((token) => token.rgba !== undefined);
@@ -171,15 +199,33 @@ export function exactColorToken(
171
199
  worst = 4,
172
200
  ): Token | undefined {
173
201
  const role = use === undefined ? undefined : USE_ROLE[use];
202
+ let best: { token: Token; rank: number; strength: number } | undefined;
203
+
204
+ // The first of a stable sort by rank, strength, and name: each key is made once per token.
205
+ for (const token of colored(set)) {
206
+ if (!sameBytes(color, token.rgba!)) {
207
+ continue;
208
+ }
209
+
210
+ const level = rank(token, role);
211
+
212
+ if (level > worst) {
213
+ continue;
214
+ }
215
+
216
+ const next = { token, rank: level, strength: strength(token, role) };
217
+
218
+ if (
219
+ best === undefined ||
220
+ (next.rank - best.rank ||
221
+ next.strength - best.strength ||
222
+ token.name.localeCompare(best.token.name)) < 0
223
+ ) {
224
+ best = next;
225
+ }
226
+ }
174
227
 
175
- return colored(set)
176
- .filter((token) => sameBytes(color, token.rgba!) && rank(token, role) <= worst)
177
- .sort(
178
- (a, b) =>
179
- rank(a, role) - rank(b, role) ||
180
- strength(a, role) - strength(b, role) ||
181
- a.name.localeCompare(b.name),
182
- )[0];
228
+ return best?.token;
183
229
  }
184
230
 
185
231
  export function nearestColor(set: TokenSet, color: RgbaTuple, use?: string): Nearest | undefined {
@@ -103,7 +103,6 @@ export function categorize(
103
103
  return "ease";
104
104
  }
105
105
 
106
- // A path or an address is not a font stack (`--fa-font-path: "../fonts"`).
107
106
  if (
108
107
  !/[/\\]|\.(?:woff2?|ttf|otf|eot)\b|^url\(|^https?:/i.test(text) &&
109
108
  (FONT_WORDS.test(text) || (/font|family|typeface/.test(name) && /[,"']/.test(text)))
@@ -111,7 +110,6 @@ export function categorize(
111
110
  return "font";
112
111
  }
113
112
 
114
- // A value made of shadow layers is a shadow, whatever the variable is called (`--lift`).
115
113
  if ((/shadow|elevation/.test(name) && /\d/.test(text)) || looksLikeShadow(text)) {
116
114
  return "shadow";
117
115
  }