@milesroxas/design-hub 0.8.1 → 0.10.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 (78) hide show
  1. package/README.md +7 -2
  2. package/core/controls.test.ts +176 -0
  3. package/core/controls.ts +195 -0
  4. package/core/prototype.test.ts +83 -0
  5. package/core/prototype.ts +84 -0
  6. package/core/review/model.ts +32 -0
  7. package/core/review/policy.test.ts +4 -2
  8. package/core/review/policy.ts +4 -2
  9. package/core/review/service.test.ts +223 -4
  10. package/core/review/service.ts +111 -2
  11. package/core/review/store.ts +13 -0
  12. package/dist/core/controls.d.ts +55 -0
  13. package/dist/core/controls.js +174 -0
  14. package/dist/core/prototype.d.ts +35 -0
  15. package/dist/core/prototype.js +84 -0
  16. package/dist/core/review/model.d.ts +13 -0
  17. package/dist/core/review/model.js +27 -0
  18. package/dist/core/review/policy.d.ts +1 -1
  19. package/dist/core/review/policy.js +1 -0
  20. package/dist/core/review/service.d.ts +50 -1
  21. package/dist/core/review/service.js +97 -3
  22. package/dist/core/review/store.d.ts +13 -0
  23. package/dist/core/review/store.js +13 -0
  24. package/dist/scripts/guard.d.ts +11 -0
  25. package/dist/scripts/guard.js +44 -0
  26. package/dist/scripts/lib/cdp.js +6 -1
  27. package/dist/scripts/lib/export-smoke.d.ts +18 -0
  28. package/dist/scripts/lib/export-smoke.js +73 -0
  29. package/dist/scripts/lib/rules.d.ts +1 -0
  30. package/dist/scripts/lib/rules.js +1 -0
  31. package/dist/scripts/new.js +5 -2
  32. package/dist/scripts/release-check.d.ts +5 -3
  33. package/dist/scripts/release-check.js +17 -4
  34. package/dist/scripts/share.d.ts +2 -2
  35. package/dist/server/api.js +21 -0
  36. package/dist/server/session.d.ts +5 -1
  37. package/dist/server/session.js +39 -21
  38. package/dist/vercel/proxy.js +44 -8
  39. package/dist/vite/boundary.d.ts +93 -0
  40. package/dist/vite/boundary.js +218 -0
  41. package/dist/vite/css-boundary.d.ts +39 -0
  42. package/dist/vite/css-boundary.js +167 -0
  43. package/dist/vite/kit.js +15 -6
  44. package/dist/vite/leaks.d.ts +37 -0
  45. package/dist/vite/leaks.js +331 -0
  46. package/dist/vite/plugin.js +2 -1
  47. package/dist/vite/registry.d.ts +15 -4
  48. package/dist/vite/registry.js +531 -27
  49. package/dist/vite/settle.d.ts +27 -0
  50. package/dist/vite/settle.js +185 -0
  51. package/kit/Artboard.tsx +21 -8
  52. package/kit/Space.tsx +4 -3
  53. package/kit/Variants.tsx +193 -65
  54. package/kit/ViewTools.tsx +77 -11
  55. package/kit/audience.ts +85 -0
  56. package/kit/dials.css +59 -0
  57. package/kit/dials.tsx +272 -35
  58. package/kit/harness.css +34 -0
  59. package/kit/prefs.ts +23 -1
  60. package/package.json +5 -4
  61. package/shell/ClientViewNote.tsx +46 -0
  62. package/shell/Guide.tsx +17 -2
  63. package/shell/Index.tsx +257 -25
  64. package/shell/audience.test.ts +63 -0
  65. package/shell/audience.ts +47 -0
  66. package/shell/controls.ts +26 -0
  67. package/shell/hub.ts +36 -0
  68. package/shell/main.tsx +51 -5
  69. package/shell/registry.ts +28 -7
  70. package/shell/registry.virtual.d.ts +12 -4
  71. package/shell/review/client.ts +16 -4
  72. package/shell/review/review.css +2 -2
  73. package/shell/shell.css +54 -3
  74. package/shell/system.css +5 -0
  75. package/skills/miles-brand/SKILL.md +11 -1
  76. package/skills/miles-deploy/SKILL.md +19 -0
  77. package/skills/miles-new-feature/SKILL.md +1 -1
  78. package/skills/miles-prototype/SKILL.md +48 -2
@@ -0,0 +1,185 @@
1
+ /// <reference types="node" />
2
+ // The last step of a build, after Vite's own generateBundle work, so the
3
+ // preload lists Vite writes into each entry are final text. Every asset goes
4
+ // where the owners of its content are (vite/boundary.ts), each file that
5
+ // really reads it is pointed at its own owner's copy, and every read that
6
+ // crosses an owner fails the build, naming reader and source.
7
+ //
8
+ // Sources are recorded, never inferred from who reads a file: a stylesheet's
9
+ // CSS modules as each chunk's sheet is written (registry.ts, renderChunk,
10
+ // before Vite moves a CSS-only chunk's sheet onto its importers), an asset's
11
+ // original files, a worker's output as its bundle is written. A file with no
12
+ // record fails the build unless its name is fixed.
13
+ //
14
+ // A real read is one Vite records (a chunk's imports, its importedCss and
15
+ // importedAssets) or a built file's hashed name in another built file's
16
+ // text: a preload list, a stylesheet's url(), an asset URL in a chunk. Files
17
+ // with fixed names (`_p/all.js`, each `entry.js`, `_gate/*`) are never read
18
+ // for that, never moved, and prose that names them is never rewritten.
19
+ import { createHash } from 'node:crypto';
20
+ import { chunkProblems, copyFor, isFixed, ownersOf, placementsOf, readsAcross, relativeTo, repointText, unrecorded, } from './boundary.js';
21
+ const metaOf = (chunk) => chunk.viteMetadata;
22
+ const textOf = (file) => file.type === 'chunk' ? file.code : typeof file.source === 'string' ? file.source : undefined;
23
+ const hash8 = (source) => createHash('sha256').update(source).digest('hex').slice(0, 8);
24
+ /** A chunk's owner by its modules: one prototype's slug, or null. Two are refused by chunkProblems. */
25
+ const chunkOwner = (chunk, o) => ownersOf(o.owner, chunk.moduleIds)[0] ?? null;
26
+ /**
27
+ * One chunk's sheet as a source: its prototype's, when any of its CSS modules
28
+ * is a prototype's (kit CSS bundled into a prototype's chunk is that
29
+ * prototype's content), else the kit's or the hub's. Two chunks writing the
30
+ * same bytes are two sources.
31
+ */
32
+ function sheetSource({ modules, writer }, o) {
33
+ const owner = ownersOf(o.owner, modules)[0] ?? null;
34
+ const from = modules.find((id) => o.owner(id) === owner) ?? modules[0];
35
+ return { owner, file: relativeTo(o.root, from), writer };
36
+ }
37
+ /**
38
+ * Where an asset's content comes from, as recorded: a stylesheet's CSS
39
+ * modules, a worker's bundle (the kit's), or an asset's original files.
40
+ * Null when nothing was recorded.
41
+ */
42
+ function sourcesOf(asset, o) {
43
+ const css = o.css.get(asset.fileName);
44
+ // A sheet with no CSS module recorded is no one's, never the hub's: it fails as unrecorded.
45
+ if (css?.length)
46
+ return css.some((w) => !w.modules.length) ? null : css.map((w) => sheetSource(w, o));
47
+ if (o.workers.has(asset.fileName))
48
+ return [{ owner: null, file: asset.fileName }];
49
+ if (!asset.originalFileNames.length)
50
+ return null;
51
+ return asset.originalFileNames.map((f) => {
52
+ const abs = o.inRoot(f);
53
+ return { owner: o.owner(abs), file: relativeTo(o.root, abs) };
54
+ });
55
+ }
56
+ /** What a file really reads: the chunks it imports, what Vite records it brings in, and built names in its text. */
57
+ function readsOf(file, all) {
58
+ const text = textOf(file);
59
+ const meta = file.type === 'chunk' ? metaOf(file) : undefined;
60
+ const named = new Set([
61
+ ...(file.type === 'chunk' ? [...file.imports, ...file.dynamicImports] : []),
62
+ ...(meta ? [...meta.importedCss, ...meta.importedAssets] : []),
63
+ ]);
64
+ return all.filter((x) => x !== file && (named.has(x.fileName) || (!isFixed(x.fileName) && text?.includes(x.fileName) === true)));
65
+ }
66
+ /** The owner a kept asset reads as: its one source owner, else the hub. */
67
+ const keptOwner = (plan) => {
68
+ const owners = new Set(plan.sources?.map((s) => s.owner));
69
+ return owners.size === 1 ? [...owners][0] : null;
70
+ };
71
+ function readersOf(file, plans, o) {
72
+ if (file.type === 'chunk')
73
+ return [{ file, owner: chunkOwner(file, o), fileName: file.fileName }];
74
+ const plan = plans.get(file.fileName);
75
+ if (plan?.places)
76
+ return plan.places.map((p) => ({ file, owner: p.owner, fileName: p.fileName }));
77
+ return [{ file, owner: plan ? keptOwner(plan) : null, fileName: file.fileName }];
78
+ }
79
+ /** The copy a reader gets of a file it reads, or the problem that it may not read it. */
80
+ function resolveRead(reader, x, plans, o) {
81
+ if (x.type === 'chunk') {
82
+ const owner = chunkOwner(x, o);
83
+ return owner && owner !== reader.owner
84
+ ? { problem: readsAcross(reader.fileName, { owner, file: x.fileName }) }
85
+ : {};
86
+ }
87
+ const plan = plans.get(x.fileName);
88
+ if (!plan.sources)
89
+ return {};
90
+ // Not split: it stays where it is, for its one owner.
91
+ const copy = copyFor(plan.places ?? [{ owner: keptOwner(plan), fileName: x.fileName }], reader.owner);
92
+ if (!copy)
93
+ return { problem: readsAcross(reader.fileName, plan.sources.find((s) => s.owner !== reader.owner)) };
94
+ return copy.fileName === x.fileName ? {} : { to: copy.fileName };
95
+ }
96
+ /** Points Vite's record of what a chunk brings in at the copies it now reads. */
97
+ function repointMeta(file, moved) {
98
+ const meta = file.type === 'chunk' ? metaOf(file) : undefined;
99
+ for (const set of meta ? [meta.importedCss, meta.importedAssets] : [])
100
+ for (const [from, to] of moved)
101
+ if (set.delete(from))
102
+ set.add(to);
103
+ }
104
+ /** Every asset's sources and placement. */
105
+ function planAll(all, o) {
106
+ const plans = new Map();
107
+ for (const f of all)
108
+ if (f.type === 'asset') {
109
+ const sources = sourcesOf(f, o);
110
+ plans.set(f.fileName, { sources, places: placementsOf(f.fileName, sources, o.slugs, hash8(f.source)) });
111
+ }
112
+ return plans;
113
+ }
114
+ /** One reader's reads: where each now points, and the problems. */
115
+ function readAll(reader, all, plans, o) {
116
+ const moved = new Map();
117
+ const problems = [];
118
+ for (const x of readsOf(reader.file, all)) {
119
+ const r = resolveRead(reader, x, plans, o);
120
+ if (r.problem)
121
+ problems.push(r.problem);
122
+ if (r.to)
123
+ moved.set(x.fileName, r.to);
124
+ }
125
+ return { moved, problems };
126
+ }
127
+ /**
128
+ * Places every asset by the owners of its content, points each real read at
129
+ * the reader's own copy, and returns every problem: a chunk with two
130
+ * prototypes' modules or outside its folder, a read across owners, and a
131
+ * file with no record of its source and no fixed name.
132
+ * Writes nothing when there is a problem.
133
+ */
134
+ export function settle(bundle, o, emit) {
135
+ const all = Object.values(bundle);
136
+ const plans = planAll(all, o);
137
+ const problems = all.flatMap((c) => c.type === 'chunk' ? chunkProblems(c.fileName, ownersOf(o.owner, c.moduleIds)) : []);
138
+ for (const [fileName, plan] of plans)
139
+ if (!plan.sources && !isFixed(fileName))
140
+ problems.push(unrecorded(fileName));
141
+ const edits = [];
142
+ for (const file of all)
143
+ for (const reader of readersOf(file, plans, o)) {
144
+ const read = readAll(reader, all, plans, o);
145
+ problems.push(...read.problems);
146
+ edits.push({ reader, moved: read.moved });
147
+ }
148
+ if (problems.length)
149
+ return [...new Set(problems)];
150
+ apply(bundle, edits, plans, emit);
151
+ return [];
152
+ }
153
+ /** Writes the plan: each reader's text and record pointed at its copies, new copies emitted, replaced originals removed. */
154
+ function apply(bundle, edits, plans, emit) {
155
+ // Every new text from the original texts first, so a kept copy's edit never leaks into another copy.
156
+ const written = edits.map(({ reader, moved }) => {
157
+ let text = textOf(reader.file);
158
+ for (const [from, to] of moved)
159
+ if (text !== undefined)
160
+ text = repointText(text, reader.fileName, from, to);
161
+ return { reader, moved, text };
162
+ });
163
+ const kept = new Set();
164
+ const copies = [];
165
+ for (const { reader, moved, text } of written) {
166
+ const { file } = reader;
167
+ if (reader.fileName !== file.fileName) {
168
+ copies.push([reader.fileName, text ?? file.source]);
169
+ continue;
170
+ }
171
+ kept.add(file.fileName);
172
+ repointMeta(file, moved);
173
+ if (text === undefined)
174
+ continue;
175
+ if (file.type === 'chunk')
176
+ file.code = text;
177
+ else
178
+ file.source = text;
179
+ }
180
+ for (const [fileName, plan] of plans)
181
+ if (plan.places && !kept.has(fileName))
182
+ delete bundle[fileName];
183
+ for (const [fileName, source] of copies)
184
+ emit(fileName, source);
185
+ }
package/kit/Artboard.tsx CHANGED
@@ -8,8 +8,9 @@ import {
8
8
  useState,
9
9
  } from 'react';
10
10
  import { FORMATS, type Format, type FormatName, sizeLabel, zoomFor } from '../core/formats.ts';
11
- import { restoreDials, useDials } from './dials';
12
- import { ViewTools } from './ViewTools';
11
+ import { client, restoreDials, useDials } from './dials';
12
+ import { pinAppearance, urlAppearance } from './prefs';
13
+ import { ViewScope } from './ViewTools';
13
14
  import './artboard.css';
14
15
 
15
16
  export { FORMAT_NAMES, FORMATS, type FormatName } from '../core/formats.ts';
@@ -54,6 +55,8 @@ function useRoom() {
54
55
  return { ref, room };
55
56
  }
56
57
 
58
+ const NO_VIEW: readonly never[] = [];
59
+
57
60
  type BoardProps = { title: string; lede?: ReactNode; children: ReactNode };
58
61
 
59
62
  /**
@@ -65,8 +68,9 @@ export function Board({ title, lede, children }: BoardProps) {
65
68
  const view = useDials(
66
69
  'Board',
67
70
  {
68
- zoom: { type: 'select', options: ZOOMS, default: 'fit' },
69
- guides: true,
71
+ // How a person looks at the boards, not the design: a Client's from the start. They are a board's only viewing tools.
72
+ zoom: client({ type: 'select', options: ZOOMS, default: 'fit' }),
73
+ guides: client(true),
70
74
  },
71
75
  {
72
76
  hints: {
@@ -81,6 +85,13 @@ export function Board({ title, lede, children }: BoardProps) {
81
85
  if (exporting) void settleForExport();
82
86
  }, []);
83
87
 
88
+ // Collateral has one look: light, or the one ?theme= names, which is what export writes.
89
+ // A person's own dark theme never recolours a piece that ships light.
90
+ useEffect(() => {
91
+ pinAppearance(urlAppearance() ?? 'light');
92
+ return () => pinAppearance(null);
93
+ }, []);
94
+
84
95
  if (exporting)
85
96
  return (
86
97
  <BoardView.Provider value={{ zoom: '100%', guides: false, room }}>
@@ -95,10 +106,12 @@ export function Board({ title, lede, children }: BoardProps) {
95
106
  <h1 className="board-title">{title}</h1>
96
107
  {lede ? <p className="board-lede">{lede}</p> : null}
97
108
  </header>
98
- <div className="board-grid" ref={ref}>
99
- {children}
100
- </div>
101
- <ViewTools />
109
+ {/* No View panel on a board: a still file has no motion to slow and no theme to flip. */}
110
+ <ViewScope.Provider value={NO_VIEW}>
111
+ <div className="board-grid" ref={ref}>
112
+ {children}
113
+ </div>
114
+ </ViewScope.Provider>
102
115
  </main>
103
116
  </BoardView.Provider>
104
117
  );
package/kit/Space.tsx CHANGED
@@ -1,12 +1,13 @@
1
1
  import type { ReactNode } from 'react';
2
2
  import './space.css';
3
- import { ViewTools } from './ViewTools';
3
+ import { type ViewTool, ViewTools } from './ViewTools';
4
4
 
5
5
  type Props = {
6
6
  title: string;
7
7
  lede?: ReactNode;
8
8
  width?: 'narrow' | 'wide' | 'full';
9
- tools?: boolean;
9
+ /** The View tools: all of them, none (`false`), or only the ones that change something here. */
10
+ tools?: boolean | readonly ViewTool[];
10
11
  children: ReactNode;
11
12
  };
12
13
 
@@ -19,7 +20,7 @@ export function Space({ title, lede, width = 'wide', tools = true, children }: P
19
20
  {lede ? <p className="space-lede">{lede}</p> : null}
20
21
  </header>
21
22
  {children}
22
- {tools ? <ViewTools /> : null}
23
+ {tools ? <ViewTools tools={tools === true ? undefined : tools} /> : null}
23
24
  </main>
24
25
  );
25
26
  }
package/kit/Variants.tsx CHANGED
@@ -1,5 +1,7 @@
1
1
  import { type ComponentType, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
2
2
  import { createPortal } from 'react-dom';
3
+ import { clientVariants } from '../core/controls.ts';
4
+ import { markControl, useControls } from './audience';
3
5
  import './harness.css';
4
6
 
5
7
  type Props = {
@@ -16,9 +18,10 @@ const HARNESS = '.dialkit-root, [data-harness], [data-lapse-panel]';
16
18
  const popupOpen = () =>
17
19
  [...document.querySelectorAll(POPUPS)].some((el) => !el.closest(HARNESS) && el.getClientRects().length > 0);
18
20
 
19
- function initialIndex(count: number) {
21
+ /** `?v=N` counts the prototype's own variants, so a link names the same one for Studio and a Client. */
22
+ function initialName(names: string[]) {
20
23
  const v = Number(new URLSearchParams(location.search).get('v'));
21
- return Number.isInteger(v) && v >= 1 && v <= count ? v - 1 : 0;
24
+ return names[Number.isInteger(v) && v >= 1 && v <= names.length ? v - 1 : 0];
22
25
  }
23
26
 
24
27
  const modified = (e: KeyboardEvent) => e.metaKey || e.ctrlKey || e.altKey || e.shiftKey;
@@ -36,30 +39,68 @@ function keyTarget(key: string, index: number, count: number): number | 'again'
36
39
  return key.toLowerCase() === 'r' ? 'again' : null;
37
40
  }
38
41
 
39
- export function Variants({ options, replay = true, onReplay, position = 'bottom' }: Props) {
40
- const names = Object.keys(options);
41
- const [index, setIndex] = useState(() => initialIndex(names.length));
42
- const [take, setTake] = useState(0);
42
+ /**
43
+ * The variants the person looking gets (core/controls.ts). Studio gets every
44
+ * one. A Client gets the ones Studio marked, or the first when none is; with
45
+ * one, there is no picker.
46
+ */
47
+ function useShown(names: string[]) {
48
+ const { studio, canMark, marks } = useControls();
49
+ const theirs = clientVariants(names, marks);
50
+ return {
51
+ shown: studio ? names : theirs,
52
+ theirs,
53
+ /** The ones Studio marked itself: the first variant is a Client's without a mark when none is. */
54
+ marked: marks.variants,
55
+ canMark,
56
+ picker: studio || theirs.length > 1,
57
+ };
58
+ }
59
+
60
+ const EYE =
61
+ 'M2.4 12.7a1.2 1.2 0 0 1 0-1.4C3.5 9.6 6.7 5 12 5s8.5 4.6 9.6 6.3a1.2 1.2 0 0 1 0 1.4C20.5 14.4 17.3 19 12 19s-8.5-4.6-9.6-6.3Z';
62
+
63
+ const Eye = () => (
64
+ <svg
65
+ width="16"
66
+ height="16"
67
+ viewBox="0 0 24 24"
68
+ fill="none"
69
+ stroke="currentColor"
70
+ strokeWidth="2"
71
+ strokeLinecap="round"
72
+ strokeLinejoin="round"
73
+ aria-hidden="true"
74
+ >
75
+ <path d={EYE} />
76
+ <circle cx="12" cy="12" r="3" />
77
+ </svg>
78
+ );
79
+
80
+ type PickerProps = {
81
+ shown: string[];
82
+ /** The open variant's place in `shown`, or -1 while Studio is marking. */
83
+ active: number;
84
+ /** What a Client gets, dotted in Studio's picker. Empty where nobody marks. */
85
+ theirs: string[];
86
+ position: 'bottom' | 'top';
87
+ choosing: boolean;
88
+ onPick: (name: string) => void;
89
+ onReplay?: () => void;
90
+ /** Studio's eye: turns marking on and off. Absent for a Client. */
91
+ onChoose?: () => void;
92
+ };
93
+
94
+ function Picker({ shown, active, theirs, position, choosing, onPick, onReplay, onChoose }: PickerProps) {
43
95
  const [ready, setReady] = useState(false);
44
96
  const items = useRef<(HTMLButtonElement | null)[]>([]);
45
97
  const highlight = useRef<HTMLSpanElement>(null);
98
+ const count = shown.length;
46
99
 
47
- const select = useCallback(
48
- (i: number) => {
49
- if (i < 0 || i >= names.length) return;
50
- setIndex(i);
51
- const url = new URL(location.href);
52
- url.searchParams.set('v', String(i + 1));
53
- history.replaceState(history.state, '', url);
54
- },
55
- [names.length],
56
- );
57
-
58
- const again = useCallback(() => (onReplay ? onReplay() : setTake((t) => t + 1)), [onReplay]);
59
-
100
+ // biome-ignore lint/correctness/useExhaustiveDependencies: the dots change each item's width
60
101
  useLayoutEffect(() => {
61
102
  const move = () => {
62
- const el = items.current[index];
103
+ const el = items.current[active];
63
104
  if (!el || !highlight.current) return;
64
105
  highlight.current.style.width = `${el.offsetWidth}px`;
65
106
  highlight.current.style.transform = `translateX(${el.offsetLeft}px)`;
@@ -67,68 +108,155 @@ export function Variants({ options, replay = true, onReplay, position = 'bottom'
67
108
  move();
68
109
  addEventListener('resize', move);
69
110
  return () => removeEventListener('resize', move);
70
- }, [index]);
111
+ }, [active, count, theirs.length]);
71
112
 
72
113
  useEffect(() => {
73
114
  const id = requestAnimationFrame(() => requestAnimationFrame(() => setReady(true)));
74
115
  return () => cancelAnimationFrame(id);
75
116
  }, []);
76
117
 
118
+ return (
119
+ <>
120
+ {choosing ? (
121
+ <p className="proto-picker-note" data-position={position === 'top' ? 'top' : undefined} role="status">
122
+ Pick what a client can flip between
123
+ </p>
124
+ ) : null}
125
+ <nav
126
+ className="proto-picker"
127
+ aria-label="Prototype variants"
128
+ data-ready={ready ? '' : undefined}
129
+ data-position={position === 'top' ? 'top' : undefined}
130
+ >
131
+ <span ref={highlight} className="proto-picker-highlight" aria-hidden="true" hidden={active < 0} />
132
+ {shown.map((name, i) => (
133
+ <button
134
+ key={name}
135
+ ref={(el) => {
136
+ items.current[i] = el;
137
+ }}
138
+ type="button"
139
+ className="proto-picker-item"
140
+ data-active={i === active ? '' : undefined}
141
+ data-theirs={theirs.includes(name) ? '' : undefined}
142
+ aria-current={i === active ? 'true' : undefined}
143
+ aria-pressed={choosing ? theirs.includes(name) : undefined}
144
+ title={onChoose && theirs.includes(name) ? 'A client gets this one' : undefined}
145
+ onClick={() => onPick(name)}
146
+ >
147
+ {onChoose ? <span className="proto-picker-dot" aria-hidden="true" /> : null}
148
+ {name}
149
+ </button>
150
+ ))}
151
+ <Tools choosing={choosing} onReplay={onReplay} onChoose={onChoose} />
152
+ </nav>
153
+ </>
154
+ );
155
+ }
156
+
157
+ function Tools({ choosing, onReplay, onChoose }: Pick<PickerProps, 'choosing' | 'onReplay' | 'onChoose'>) {
158
+ if (!onReplay && !onChoose) return null;
159
+ return (
160
+ <>
161
+ <span className="proto-picker-divider" aria-hidden="true" />
162
+ {onReplay ? (
163
+ <button
164
+ type="button"
165
+ className="proto-picker-item proto-picker-replay"
166
+ aria-label="Replay animation (R)"
167
+ onClick={onReplay}
168
+ >
169
+ ↻
170
+ </button>
171
+ ) : null}
172
+ {onChoose ? (
173
+ <button
174
+ type="button"
175
+ className="proto-picker-item proto-picker-choose"
176
+ aria-pressed={choosing}
177
+ aria-label="Choose what a client gets"
178
+ title="Choose what a client gets"
179
+ onClick={onChoose}
180
+ >
181
+ {choosing ? 'Done' : <Eye />}
182
+ </button>
183
+ ) : null}
184
+ </>
185
+ );
186
+ }
187
+
188
+ /** The open variant, kept in `?v=N`, and the way to open another. */
189
+ function usePicked(names: string[]) {
190
+ const [picked, setPicked] = useState(() => initialName(names));
191
+ const key = names.join('\n');
192
+ const select = useCallback(
193
+ (next: string | undefined) => {
194
+ if (next === undefined) return;
195
+ setPicked(next);
196
+ const url = new URL(location.href);
197
+ url.searchParams.set('v', String(key.split('\n').indexOf(next) + 1));
198
+ history.replaceState(history.state, '', url);
199
+ },
200
+ [key],
201
+ );
202
+ return { picked, select };
203
+ }
204
+
205
+ /** 1 to N, the arrows and R, over the variants the person looking has. */
206
+ function usePickerKeys(shown: string[], index: number, select: (name: string) => void, again: () => void) {
207
+ const shownKey = shown.join('\n');
77
208
  useEffect(() => {
209
+ const list = shownKey.split('\n');
78
210
  const onKey = (e: KeyboardEvent) => {
79
211
  if (!pickerOwns(e)) return;
80
- const next = keyTarget(e.key, index, names.length);
212
+ const next = keyTarget(e.key, index, list.length);
81
213
  if (next === 'again') again();
82
- else if (next !== null) select(next);
214
+ else if (next !== null) select(list[next]);
83
215
  };
84
216
  document.addEventListener('keydown', onKey);
85
217
  return () => document.removeEventListener('keydown', onKey);
86
- }, [index, names.length, select, again]);
218
+ }, [index, shownKey, select, again]);
219
+ }
220
+
221
+ /** Studio's second state of the picker: a click marks a variant instead of opening it. */
222
+ function useMarking(canMark: boolean, marked: string[]) {
223
+ const [marking, setMarking] = useState(false);
224
+ return {
225
+ choosing: marking && canMark,
226
+ onChoose: canMark ? () => setMarking((m) => !m) : undefined,
227
+ mark: (n: string) => void markControl('variant', n, marked.includes(n) ? 'internal' : 'client'),
228
+ };
229
+ }
230
+
231
+ export function Variants({ options, replay = true, onReplay, position = 'bottom' }: Props) {
232
+ const names = Object.keys(options);
233
+ const { shown, theirs, marked, canMark, picker } = useShown(names);
234
+ const { picked, select } = usePicked(names);
235
+ const [take, setTake] = useState(0);
236
+ const { choosing, onChoose, mark } = useMarking(canMark, marked);
237
+ const name = shown.includes(picked) ? picked : shown[0];
238
+ const index = shown.indexOf(name);
239
+ const again = useCallback(() => (onReplay ? onReplay() : setTake((t) => t + 1)), [onReplay]);
240
+ usePickerKeys(shown, index, select, again);
87
241
 
88
- const Current = options[names[index]];
242
+ const Current = options[name];
243
+ const bar = (
244
+ <Picker
245
+ shown={shown}
246
+ active={choosing ? -1 : index}
247
+ theirs={onChoose ? theirs : []}
248
+ position={position}
249
+ choosing={choosing}
250
+ onPick={choosing ? mark : select}
251
+ onReplay={replay ? again : undefined}
252
+ onChoose={onChoose}
253
+ />
254
+ );
89
255
 
90
256
  return (
91
257
  <>
92
- <Current key={`${index}:${take}`} />
93
- {createPortal(
94
- <nav
95
- className="proto-picker"
96
- aria-label="Prototype variants"
97
- data-ready={ready ? '' : undefined}
98
- data-position={position === 'top' ? 'top' : undefined}
99
- >
100
- <span ref={highlight} className="proto-picker-highlight" aria-hidden="true" />
101
- {names.map((name, i) => (
102
- <button
103
- key={name}
104
- ref={(el) => {
105
- items.current[i] = el;
106
- }}
107
- type="button"
108
- className="proto-picker-item"
109
- data-active={i === index ? '' : undefined}
110
- aria-current={i === index ? 'true' : undefined}
111
- onClick={() => select(i)}
112
- >
113
- {name}
114
- </button>
115
- ))}
116
- {replay && (
117
- <>
118
- <span className="proto-picker-divider" aria-hidden="true" />
119
- <button
120
- type="button"
121
- className="proto-picker-item proto-picker-replay"
122
- aria-label="Replay animation (R)"
123
- onClick={again}
124
- >
125
- ↻
126
- </button>
127
- </>
128
- )}
129
- </nav>,
130
- document.body,
131
- )}
258
+ {Current ? <Current key={`${name}:${take}`} /> : null}
259
+ {picker ? createPortal(bar, document.body) : null}
132
260
  </>
133
261
  );
134
262
  }