@milesroxas/design-hub 0.9.0 → 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.
@@ -0,0 +1,176 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+ import { DialStore } from 'dialkit';
4
+ import {
5
+ client,
6
+ clientVariants,
7
+ controlField,
8
+ defaultOf,
9
+ dialAudience,
10
+ isControlId,
11
+ keepDials,
12
+ type Marks,
13
+ NO_MARKS,
14
+ readConfig,
15
+ readMarks,
16
+ withDefaults,
17
+ withMark,
18
+ } from './controls.ts';
19
+
20
+ const select = { type: 'select', options: ['comfortable', 'compact'], default: 'comfortable' };
21
+
22
+ test('a dial is internal until marked: in code with client(), or in the hub, which overrules the code', () => {
23
+ const { dials } = readConfig('Review', {
24
+ fixtures: select,
25
+ density: client(select),
26
+ avatars: client(true),
27
+ });
28
+ assert.deepEqual(dials, [
29
+ { id: 'Review/fixtures', path: ['fixtures'], inCode: 'internal' },
30
+ { id: 'Review/density', path: ['density'], inCode: 'client' },
31
+ { id: 'Review/avatars', path: ['avatars'], inCode: 'client' },
32
+ ]);
33
+ const marks: Marks = { dials: { 'Review/fixtures': 'client', 'Review/density': 'internal' }, variants: [] };
34
+ const audience = Object.fromEntries(dials.map((d) => [d.id, dialAudience(marks, d.id, d.inCode)]));
35
+ assert.deepEqual(audience, {
36
+ 'Review/fixtures': 'client',
37
+ 'Review/density': 'internal',
38
+ 'Review/avatars': 'client',
39
+ });
40
+ assert.equal(dialAudience(NO_MARKS, 'Review/fixtures', 'internal'), 'internal');
41
+ });
42
+
43
+ test('readConfig unwraps every client() and reads folders, a marked folder marking each dial in it', () => {
44
+ const { config, dials } = readConfig('Card', {
45
+ radius: [8, 0, 24, 1],
46
+ shadow: client({ blur: [12, 0, 40, 1], _collapsed: true, tint: { hue: 200 } }),
47
+ motion: { rise: client([220, 0, 600, 10]), ease: { type: 'easing', ease: [0, 0, 1, 1], duration: 0.2 } },
48
+ });
49
+ assert.deepEqual(config, {
50
+ radius: [8, 0, 24, 1],
51
+ shadow: { blur: [12, 0, 40, 1], _collapsed: true, tint: { hue: 200 } },
52
+ motion: { rise: [220, 0, 600, 10], ease: { type: 'easing', ease: [0, 0, 1, 1], duration: 0.2 } },
53
+ });
54
+ assert.deepEqual(
55
+ dials.map((d) => `${d.id} ${d.inCode}`),
56
+ [
57
+ 'Card/radius internal',
58
+ 'Card/shadow.blur client',
59
+ 'Card/shadow.tint.hue client',
60
+ 'Card/motion.rise client',
61
+ 'Card/motion.ease internal',
62
+ ],
63
+ );
64
+ });
65
+
66
+ test('keepDials leaves out every dial not shown, and a folder with none left', () => {
67
+ const { config } = readConfig('Card', {
68
+ radius: [8, 0, 24, 1],
69
+ shadow: { _collapsed: true, blur: [12, 0, 40, 1], spread: 2 },
70
+ motion: { rise: [220, 0, 600, 10] },
71
+ });
72
+ const kept = keepDials('Card', config, (id) => id === 'Card/shadow.blur');
73
+ assert.deepEqual(kept, { shadow: { blur: [12, 0, 40, 1], _collapsed: true } });
74
+ assert.deepEqual(
75
+ keepDials('Card', config, () => false),
76
+ {},
77
+ );
78
+ assert.deepEqual(
79
+ keepDials('Card', config, () => true),
80
+ config,
81
+ );
82
+ });
83
+
84
+ // Every kind of dial DialKit has, with and without a default of its own.
85
+ const EVERY = {
86
+ bare: 0.4,
87
+ slider: [220, 0, 600, 10],
88
+ outside: [900, 0, 600, 10],
89
+ swapped: [5, 10, 0],
90
+ open: [7],
91
+ toggle: true,
92
+ word: 'hello',
93
+ chosen: { type: 'select', options: ['a', 'b'], default: 'b' },
94
+ first: { type: 'select', options: [{ value: 'x', label: 'X' }, 'y'] },
95
+ none: { type: 'select', options: [] },
96
+ color: { type: 'color', default: '#ff0000' },
97
+ black: { type: 'color' },
98
+ text: { type: 'text', default: 'Title' },
99
+ blank: { type: 'text' },
100
+ image: { type: 'image', options: ['/a.png', '/b.png'] },
101
+ pad: { type: 'pad', x: [0.333, 0, 1, 0.01], y: [5, -10, 10] },
102
+ centre: { type: 'pad' },
103
+ spring: { type: 'spring', visualDuration: 0.3, bounce: 0.2 },
104
+ ease: { type: 'easing', ease: [0.2, 0, 0, 1], duration: 0.3 },
105
+ folder: { depth: [2, 0, 8, 1], inner: { on: false } },
106
+ };
107
+
108
+ test('defaultOf is DialKit’s own starting value, for every kind of dial', () => {
109
+ DialStore.registerPanel('every', 'Every', EVERY as any);
110
+ const flat = DialStore.getValues('every') as Record<string, unknown>;
111
+ DialStore.unregisterPanel('every');
112
+ const ours = withDefaults(EVERY, {});
113
+ const flatten = (node: Record<string, unknown>, prefix = ''): Record<string, unknown> =>
114
+ Object.fromEntries(
115
+ Object.entries(node).flatMap(([k, v]) =>
116
+ prefix === '' && k === 'folder'
117
+ ? Object.entries(flatten(v as Record<string, unknown>, 'folder.'))
118
+ : k === 'inner'
119
+ ? Object.entries(flatten(v as Record<string, unknown>, `${prefix}inner.`))
120
+ : [[prefix + k, v]],
121
+ ),
122
+ );
123
+ assert.deepEqual(flatten(ours), flat);
124
+ });
125
+
126
+ test('withDefaults keeps the values DialKit gave and fills the dials it did not draw', () => {
127
+ const config = { fixtures: select, density: select, shadow: { blur: [12, 0, 40, 1], spread: 2 } };
128
+ assert.deepEqual(withDefaults(config, { density: 'compact', shadow: { blur: 30 } }), {
129
+ fixtures: 'comfortable',
130
+ density: 'compact',
131
+ shadow: { blur: 30, spread: 2 },
132
+ });
133
+ assert.equal(defaultOf([3, 0, 10, 1]), 3);
134
+ });
135
+
136
+ test('a Client gets the variants Studio marked, in the prototype’s order, and the first when none is', () => {
137
+ const names = ['Baseline', 'Lift', 'Sink'];
138
+ assert.deepEqual(clientVariants(names, NO_MARKS), ['Baseline']);
139
+ assert.deepEqual(clientVariants(names, { dials: {}, variants: ['Sink', 'Lift'] }), ['Lift', 'Sink']);
140
+ // A mark for a variant the prototype no longer has counts for nothing.
141
+ assert.deepEqual(clientVariants(names, { dials: {}, variants: ['Gone'] }), ['Baseline']);
142
+ assert.deepEqual(clientVariants([], NO_MARKS), []);
143
+ });
144
+
145
+ test('marks read from the store ignore what is not theirs, and withMark switches one', () => {
146
+ const marks = readMarks({
147
+ [controlField('dial', 'Review/density')]: 'client',
148
+ [controlField('dial', 'Review/fixtures')]: 'internal',
149
+ [controlField('dial', 'Review/odd')]: 'yes',
150
+ [controlField('variant', 'Lift')]: 'client',
151
+ [controlField('variant', 'Sink')]: 'internal',
152
+ 'thing:x': 'client',
153
+ 'dial:': 'client',
154
+ plain: 'client',
155
+ });
156
+ assert.deepEqual(marks, {
157
+ dials: { 'Review/density': 'client', 'Review/fixtures': 'internal' },
158
+ variants: ['Lift'],
159
+ });
160
+ const next = withMark(
161
+ withMark(marks, 'variant', 'Baseline', 'client'),
162
+ 'dial',
163
+ 'Review/density',
164
+ 'internal',
165
+ );
166
+ assert.deepEqual(next.variants, ['Baseline', 'Lift']);
167
+ assert.equal(next.dials['Review/density'], 'internal');
168
+ assert.deepEqual(withMark(next, 'variant', 'Lift', 'internal').variants, ['Baseline']);
169
+ });
170
+
171
+ test('a control id is one trimmed line of at most 200 characters', () => {
172
+ for (const ok of ['Review/density', 'Outline, as legal asked', 'a', 'x'.repeat(200)])
173
+ assert.ok(isControlId(ok), ok);
174
+ for (const bad of ['', ' a', 'a ', 'a\nb', 'a\u0000', 'x'.repeat(201), 3, null, undefined])
175
+ assert.ok(!isControlId(bad), String(bad));
176
+ });
@@ -0,0 +1,195 @@
1
+ // Which of a prototype's controls a Client gets: its dials and its variants.
2
+ // Pure, so the server, the kit and the tests read one set of rules.
3
+ //
4
+ // A dial is internal until marked client-facing. It is marked in two places:
5
+ // in code, with `client(...)` around the dial where it is declared, which is
6
+ // where it starts; and in the hub, by Studio, which is stored per deployed
7
+ // site and overrules the code either way. A variant is marked only in the
8
+ // hub. The View tools are never asked about: they are always a Client's.
9
+ //
10
+ // The mark decides what a Client's panel draws and nothing else. A prototype's
11
+ // code is one file a Client's browser loads, so an internal dial's name, range
12
+ // and default are still in it; its value stays at the default.
13
+
14
+ export type ControlAudience = 'internal' | 'client';
15
+
16
+ export const CONTROL_KINDS = ['dial', 'variant'] as const;
17
+ export type ControlKind = (typeof CONTROL_KINDS)[number];
18
+
19
+ /** What the hub stored for one prototype: a mark per dial Studio switched, and the variants a Client gets. */
20
+ export type Marks = { dials: Record<string, ControlAudience>; variants: string[] };
21
+
22
+ export const NO_MARKS: Marks = { dials: {}, variants: [] };
23
+
24
+ const MAX_ID = 200;
25
+
26
+ /** A dial's or a variant's name as the store keeps it: one line of text, trimmed, at most 200 characters. */
27
+ export const isControlId = (v: unknown): v is string =>
28
+ typeof v === 'string' &&
29
+ v.length > 0 &&
30
+ v.length <= MAX_ID &&
31
+ v.trim() === v &&
32
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what is refused
33
+ !/[\u0000-\u001f\u007f]/.test(v);
34
+
35
+ /** A dial is named by its panel and its key, a folder's dial by the keys down to it: `Review/density`, `Card/shadow.blur`. */
36
+ export const dialId = (panel: string, path: readonly string[]) => `${panel}/${path.join('.')}`;
37
+
38
+ /** The store's field for one control. */
39
+ export const controlField = (kind: ControlKind, id: string) => `${kind}:${id}`;
40
+
41
+ /** The marks in a prototype's stored fields. A field or a value that is not one of ours is left out, so it reads as unmarked. */
42
+ export function readMarks(fields: Record<string, string>): Marks {
43
+ const dials: Record<string, ControlAudience> = {};
44
+ const variants: string[] = [];
45
+ for (const [field, value] of Object.entries(fields)) {
46
+ const at = field.indexOf(':');
47
+ const [kind, id] = [field.slice(0, at), field.slice(at + 1)];
48
+ if (!isControlId(id)) continue;
49
+ if (kind === 'dial' && (value === 'client' || value === 'internal')) dials[id] = value;
50
+ if (kind === 'variant' && value === 'client') variants.push(id);
51
+ }
52
+ return { dials, variants: variants.sort() };
53
+ }
54
+
55
+ /** The marks after one control is switched. */
56
+ export function withMark(marks: Marks, kind: ControlKind, id: string, audience: ControlAudience): Marks {
57
+ if (kind === 'dial') return { ...marks, dials: { ...marks.dials, [id]: audience } };
58
+ const rest = marks.variants.filter((v) => v !== id);
59
+ return { ...marks, variants: audience === 'client' ? [...rest, id].sort() : rest };
60
+ }
61
+
62
+ /** Who a dial is for: the hub's mark when Studio set one, else what the code says, else internal. */
63
+ export const dialAudience = (marks: Marks, id: string, inCode: ControlAudience): ControlAudience =>
64
+ marks.dials[id] ?? inCode;
65
+
66
+ /**
67
+ * The variants a Client gets, in the order the prototype declares them. One
68
+ * is no picker. None marked is still one: the first, so a page is never empty.
69
+ */
70
+ export function clientVariants(names: readonly string[], marks: Marks): string[] {
71
+ const kept = names.filter((n) => marks.variants.includes(n));
72
+ return kept.length ? kept : names.slice(0, 1);
73
+ }
74
+
75
+ // The config a prototype hands to useDials, read without DialKit's types: a
76
+ // leaf is a dial, an object without a `type` is a folder of them.
77
+
78
+ type Config = Record<string, unknown>;
79
+ type Marked = { __client: unknown };
80
+
81
+ const isRecord = (v: unknown): v is Config => typeof v === 'object' && v !== null && !Array.isArray(v);
82
+ const isMarked = (v: unknown): v is Marked => isRecord(v) && '__client' in v;
83
+ const isFolder = (v: unknown): v is Config => isRecord(v) && !('type' in v);
84
+ /** DialKit's own key for a folder that starts closed: not a dial. */
85
+ const SETTING = '_collapsed';
86
+
87
+ /**
88
+ * Marks a dial client-facing where it is declared, or a folder and every dial
89
+ * in it. Typed as the dial itself, so the values a prototype reads keep their types.
90
+ */
91
+ export const client = <T>(dial: T): T => ({ __client: dial }) as T;
92
+
93
+ export type Dial = { id: string; path: string[]; inCode: ControlAudience };
94
+
95
+ /** A config as DialKit takes it (every `client()` unwrapped) and the dials in it. */
96
+ export function readConfig(panel: string, config: Config): { config: Config; dials: Dial[] } {
97
+ const dials: Dial[] = [];
98
+ const walk = (node: Config, path: string[], inherited: ControlAudience): Config => {
99
+ const out: Config = {};
100
+ for (const [key, raw] of Object.entries(node)) {
101
+ if (key === SETTING) {
102
+ out[key] = raw;
103
+ continue;
104
+ }
105
+ const inCode: ControlAudience = isMarked(raw) ? 'client' : inherited;
106
+ const value = isMarked(raw) ? raw.__client : raw;
107
+ const at = [...path, key];
108
+ if (isFolder(value)) out[key] = walk(value, at, inCode);
109
+ else {
110
+ out[key] = value;
111
+ dials.push({ id: dialId(panel, at), path: at, inCode });
112
+ }
113
+ }
114
+ return out;
115
+ };
116
+ return { config: walk(config, [], 'internal'), dials };
117
+ }
118
+
119
+ /** The part of an unwrapped config whose dials `shown` keeps. A folder with none left goes with them. */
120
+ export function keepDials(panel: string, config: Config, shown: (id: string) => boolean): Config {
121
+ const walk = (node: Config, path: string[]): Config => {
122
+ const out: Config = {};
123
+ for (const [key, value] of Object.entries(node)) {
124
+ if (key === SETTING) continue;
125
+ const at = [...path, key];
126
+ if (isFolder(value)) {
127
+ const inner = walk(value, at);
128
+ if (Object.keys(inner).length)
129
+ out[key] = SETTING in value ? { ...inner, [SETTING]: value[SETTING] } : inner;
130
+ } else if (shown(dialId(panel, at))) out[key] = value;
131
+ }
132
+ return out;
133
+ };
134
+ return walk(config, []);
135
+ }
136
+
137
+ const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
138
+ const clamp = (v: number, min: number, max: number) => Math.max(min, Math.min(max, v));
139
+
140
+ /** A slider's starting value: its first number, kept inside a range that is given. */
141
+ function sliderDefault(value: readonly unknown[]): number {
142
+ const seed = finite(value[0]) ? value[0] : 0;
143
+ if (!finite(value[1]) || !finite(value[2])) return seed;
144
+ const [min, max] = value[1] <= value[2] ? [value[1], value[2]] : [value[2], value[1]];
145
+ return clamp(seed, min, min === max ? min + 1 : max);
146
+ }
147
+
148
+ const firstOption = (options: unknown): unknown => {
149
+ const first = Array.isArray(options) ? options[0] : undefined;
150
+ if (first === undefined) return '';
151
+ return typeof first === 'string' ? first : (first as { value: unknown }).value;
152
+ };
153
+
154
+ /** One axis of a pad: `[default, min, max, step?]`, the default snapped to the step as DialKit snaps it. */
155
+ function padAxis(axis: unknown): number {
156
+ const [initial, min, max, given] = (Array.isArray(axis) ? axis : [0, -1, 1, 0.01]) as number[];
157
+ const step = given ?? (max - min) / 200;
158
+ const at = clamp(initial, min, max);
159
+ if (at === min || at === max) return at;
160
+ return clamp(Number((min + Math.round((at - min) / step) * step).toPrecision(12)), min, max);
161
+ }
162
+
163
+ /** By `type`: what DialKit starts each kind of dial at when its config names no default. */
164
+ const TYPED: Record<string, (v: Config) => unknown> = {
165
+ select: (v) => v.default ?? firstOption(v.options),
166
+ color: (v) => v.default ?? '#000000',
167
+ image: (v) => v.default ?? firstOption(v.options ?? []),
168
+ text: (v) => v.default ?? '',
169
+ pad: (v) => ({ x: padAxis(v.x), y: padAxis(v.y) }),
170
+ };
171
+
172
+ /**
173
+ * What a dial reads when nobody can move it: the value DialKit would start it
174
+ * at. A test holds this equal to DialKit's own for every kind of dial.
175
+ */
176
+ export function defaultOf(dial: unknown): unknown {
177
+ if (Array.isArray(dial)) return sliderDefault(dial);
178
+ if (!isRecord(dial) || typeof dial.type !== 'string') return dial;
179
+ const typed = TYPED[dial.type];
180
+ return typed ? typed(dial) : dial;
181
+ }
182
+
183
+ /**
184
+ * The values a prototype reads: DialKit's for the dials it drew, the default
185
+ * for every dial it did not, in the shape of the whole config.
186
+ */
187
+ export function withDefaults(config: Config, values: Config): Config {
188
+ const out: Config = {};
189
+ for (const [key, dial] of Object.entries(config)) {
190
+ if (key === SETTING) continue;
191
+ if (isFolder(dial)) out[key] = withDefaults(dial, isRecord(values[key]) ? values[key] : {});
192
+ else out[key] = key in values ? values[key] : defaultOf(dial);
193
+ }
194
+ return out;
195
+ }
@@ -4,6 +4,7 @@
4
4
  // enforced by the service, whichever adapter (Vercel, Vite dev, the CLI)
5
5
  // calls it.
6
6
 
7
+ import { CONTROL_KINDS, type ControlKind, isControlId } from '../controls.ts';
7
8
  import { SLUG } from '../feature.ts';
8
9
 
9
10
  /** Which side a person is on: the studio that makes the work, or the client it is for. */
@@ -241,6 +242,30 @@ export function checkPrototypeAudience(input: unknown): Checked<Audience> {
241
242
  : { ok: false, problems: [`audience: one of ${AUDIENCES.join(', ')}`] };
242
243
  }
243
244
 
245
+ /** One control's mark as Studio sets it: which kind, its id, and who it is for. */
246
+ export function checkControl(input: {
247
+ kind: unknown;
248
+ id: unknown;
249
+ audience: unknown;
250
+ }): Checked<{ kind: ControlKind; id: string; audience: Audience }> {
251
+ const problems: string[] = [];
252
+ if (!CONTROL_KINDS.includes(input.kind as ControlKind))
253
+ problems.push(`kind: one of ${CONTROL_KINDS.join(', ')}`);
254
+ if (!isControlId(input.id)) problems.push('id: the control’s name, one line of at most 200 characters');
255
+ if (!AUDIENCES.includes(input.audience as Audience))
256
+ problems.push(`audience: one of ${AUDIENCES.join(', ')}`);
257
+ return problems.length
258
+ ? { ok: false, problems }
259
+ : {
260
+ ok: true,
261
+ value: {
262
+ kind: input.kind as ControlKind,
263
+ id: input.id as string,
264
+ audience: input.audience as Audience,
265
+ },
266
+ };
267
+ }
268
+
244
269
  /** Whose view of the comments is asked for: a person kind, or null for the caller's own. */
245
270
  export function checkViewAs(input: unknown): Checked<PersonKind | null> {
246
271
  if (input === undefined || input === null) return { ok: true, value: null };
@@ -921,3 +921,82 @@ test('a Client acting on a client-facing thread of an internal prototype is told
921
921
  assert.ok(await review.add(studio, { body: 'Internal note', anchor }));
922
922
  assert.ok(await review.reply(studio, { ...at, thread: root.id, body: 'Studio reply' }));
923
923
  });
924
+
925
+ // Slice 6: what Studio marks on a prototype's dials and variants.
926
+ test('controls: Studio marks a dial either way and a variant on or off, one field each', async () => {
927
+ const kv = memoryKV();
928
+ const own = createReview(kv);
929
+ const mark = (kind: string, id: string, audience: string) =>
930
+ own.setControl(studio, { prototype: 'sample-list', kind, id, audience });
931
+ assert.deepEqual(await own.controlsOf(studio, 'sample-list'), { view: 'studio', dials: {}, variants: [] });
932
+ assert.deepEqual(await mark('dial', 'Review/density', 'client'), {
933
+ kind: 'dial',
934
+ id: 'Review/density',
935
+ audience: 'client',
936
+ });
937
+ // Internal is stored for a dial: it overrules a client() in the code.
938
+ await mark('dial', 'Review/avatars', 'internal');
939
+ await mark('variant', 'Lift', 'client');
940
+ await mark('variant', 'Sink', 'client');
941
+ await mark('variant', 'Sink', 'internal');
942
+ // Unmarking a variant never marked is no error.
943
+ await mark('variant', 'Baseline', 'internal');
944
+ assert.deepEqual(await kv.hgetall(KEY.controls('sample-list')), {
945
+ 'dial:Review/density': 'client',
946
+ 'dial:Review/avatars': 'internal',
947
+ 'variant:Lift': 'client',
948
+ });
949
+ assert.deepEqual(await own.controlsOf(studio, 'sample-list'), {
950
+ view: 'studio',
951
+ dials: { 'Review/density': 'client', 'Review/avatars': 'internal' },
952
+ variants: ['Lift'],
953
+ });
954
+ // Marks are per prototype.
955
+ assert.deepEqual(await own.controlsOf(studio, 'sample-page'), { view: 'studio', dials: {}, variants: [] });
956
+ });
957
+
958
+ test('controls: only Studio marks, and every field is checked', async () => {
959
+ const input = { prototype: 'sample-list', kind: 'dial', id: 'Review/density', audience: 'client' };
960
+ await rejects(review.setControl(client, input), 'forbidden');
961
+ await rejects(review.setControl(null, input), 'unauthorized');
962
+ await assert.rejects(
963
+ review.setControl(studio, { prototype: 'guide', kind: 'knob', id: ' x', audience: 'all' }),
964
+ (e: unknown) =>
965
+ e instanceof ReviewError &&
966
+ e.code === 'invalid' &&
967
+ e.problems.join('|') ===
968
+ [
969
+ 'prototype: a prototype slug',
970
+ 'kind: one of dial, variant',
971
+ 'id: the control’s name, one line of at most 200 characters',
972
+ 'audience: one of internal, client',
973
+ ].join('|'),
974
+ );
975
+ assert.deepEqual((await review.controlsOf(studio, 'sample-list')).dials, {});
976
+ });
977
+
978
+ test('controls: a Client reads the marks of a client-facing prototype, and none of an internal one', async () => {
979
+ await review.setControl(studio, {
980
+ prototype: 'sample-list',
981
+ kind: 'dial',
982
+ id: 'Review/density',
983
+ audience: 'client',
984
+ });
985
+ await review.setControl(studio, {
986
+ prototype: 'secret-plan',
987
+ kind: 'variant',
988
+ id: 'Lift',
989
+ audience: 'client',
990
+ });
991
+ assert.deepEqual(await review.controlsOf(client, 'sample-list'), {
992
+ view: 'client',
993
+ dials: { 'Review/density': 'client' },
994
+ variants: [],
995
+ });
996
+ // The same answer as for a prototype that does not exist.
997
+ await rejects(review.controlsOf(client, 'secret-plan'), 'not_found');
998
+ await rejects(review.controlsOf(client, 'never-made'), 'not_found');
999
+ await rejects(review.controlsOf(null, 'sample-list'), 'unauthorized');
1000
+ await rejects(review.controlsOf(studio, 'guide'), 'invalid');
1001
+ assert.deepEqual((await review.controlsOf(studio, 'secret-plan')).variants, ['Lift']);
1002
+ });
@@ -5,6 +5,7 @@
5
5
  // person, per comment), so two people commenting at once never collide;
6
6
  // two edits of the same comment at once keep the last.
7
7
  import { base64url, hex, sha256 } from '../bytes.ts';
8
+ import { type ControlKind, controlField, type Marks, readMarks } from '../controls.ts';
8
9
  import { isPrototypeSlug } from '../prototype.ts';
9
10
  import {
10
11
  type Access,
@@ -18,6 +19,7 @@ import {
18
19
  checkAnchor,
19
20
  checkAudience,
20
21
  checkBody,
22
+ checkControl,
21
23
  checkPersonInput,
22
24
  checkPrototypeAudience,
23
25
  checkStates,
@@ -547,6 +549,45 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
547
549
  return value;
548
550
  },
549
551
 
552
+ /**
553
+ * What Studio marked on a prototype's dials and variants, with the view
554
+ * the actor gets. A Client reads the marks too: their page needs a dial
555
+ * Studio switched back to internal as much as one it shared, and the
556
+ * names are in the prototype's own code already. An internal prototype
557
+ * has none for a Client, as it has no comments.
558
+ */
559
+ async controlsOf(actor: Person | null, prototype: unknown): Promise<{ view: PersonKind } & Marks> {
560
+ allow(actor, 'read');
561
+ if (!isPrototypeSlug(prototype))
562
+ throw new ReviewError('invalid', 'Some fields are not valid.', ['prototype: a prototype slug']);
563
+ const view = viewOf(actor);
564
+ if (!(await reachable(view, prototype))) throw new ReviewError('not_found', 'No such prototype.');
565
+ return { view, ...readMarks(await kv.hgetall(KEY.controls(prototype))) };
566
+ },
567
+
568
+ /**
569
+ * Marks one dial or one variant client-facing or internal. A dial's mark
570
+ * is stored either way, because it overrules what the code says; a
571
+ * variant's internal is the field's absence. Studio only. The server
572
+ * keeps no list of a prototype's controls, so any well-formed id is taken.
573
+ */
574
+ async setControl(
575
+ actor: Person | null,
576
+ input: { prototype: unknown; kind: unknown; id: unknown; audience: unknown },
577
+ ): Promise<{ kind: ControlKind; id: string; audience: Audience }> {
578
+ allow(actor, 'audience');
579
+ const [slug, mark] = validAll<[string, { kind: ControlKind; id: string; audience: Audience }]>(
580
+ isPrototypeSlug(input.prototype)
581
+ ? { ok: true, value: input.prototype }
582
+ : { ok: false, problems: ['prototype: a prototype slug'] },
583
+ checkControl(input),
584
+ );
585
+ const field = controlField(mark.kind, mark.id);
586
+ if (mark.kind === 'variant' && mark.audience === 'internal') await kv.hdel(KEY.controls(slug), field);
587
+ else await kv.hset(KEY.controls(slug), field, mark.audience);
588
+ return mark;
589
+ },
590
+
550
591
  /**
551
592
  * Who a prototype is for, asked by the gate with no actor. Absent, or any
552
593
  * value but `client`, is internal; a name that cannot be a prototype is
@@ -46,6 +46,13 @@ export const KEY = {
46
46
  */
47
47
  counters: `${PREFIX}counters`,
48
48
  comments: (prototype: string) => `${PREFIX}comments:${prototype}`,
49
+ /**
50
+ * What Studio marked on one prototype's controls (core/controls.ts): field
51
+ * `dial:<id>` is `client` or `internal`, overruling the code either way;
52
+ * field `variant:<name>` is `client`, and internal is its absence. One
53
+ * field per control, so two people marking at once never undo each other.
54
+ */
55
+ controls: (prototype: string) => `${PREFIX}controls:${prototype}`,
49
56
  } as const;
50
57
 
51
58
  export type Snapshot = { hashes: Record<string, Record<string, string>>; sets: Record<string, string[]> };
@@ -0,0 +1,55 @@
1
+ export type ControlAudience = 'internal' | 'client';
2
+ export declare const CONTROL_KINDS: readonly ['dial', 'variant'];
3
+ export type ControlKind = (typeof CONTROL_KINDS)[number];
4
+ /** What the hub stored for one prototype: a mark per dial Studio switched, and the variants a Client gets. */
5
+ export type Marks = {
6
+ dials: Record<string, ControlAudience>;
7
+ variants: string[];
8
+ };
9
+ export declare const NO_MARKS: Marks;
10
+ /** A dial's or a variant's name as the store keeps it: one line of text, trimmed, at most 200 characters. */
11
+ export declare const isControlId: (v: unknown) => v is string;
12
+ /** A dial is named by its panel and its key, a folder's dial by the keys down to it: `Review/density`, `Card/shadow.blur`. */
13
+ export declare const dialId: (panel: string, path: readonly string[]) => string;
14
+ /** The store's field for one control. */
15
+ export declare const controlField: (kind: ControlKind, id: string) => string;
16
+ /** The marks in a prototype's stored fields. A field or a value that is not one of ours is left out, so it reads as unmarked. */
17
+ export declare function readMarks(fields: Record<string, string>): Marks;
18
+ /** The marks after one control is switched. */
19
+ export declare function withMark(marks: Marks, kind: ControlKind, id: string, audience: ControlAudience): Marks;
20
+ /** Who a dial is for: the hub's mark when Studio set one, else what the code says, else internal. */
21
+ export declare const dialAudience: (marks: Marks, id: string, inCode: ControlAudience) => ControlAudience;
22
+ /**
23
+ * The variants a Client gets, in the order the prototype declares them. One
24
+ * is no picker. None marked is still one: the first, so a page is never empty.
25
+ */
26
+ export declare function clientVariants(names: readonly string[], marks: Marks): string[];
27
+ type Config = Record<string, unknown>;
28
+ /**
29
+ * Marks a dial client-facing where it is declared, or a folder and every dial
30
+ * in it. Typed as the dial itself, so the values a prototype reads keep their types.
31
+ */
32
+ export declare const client: <T>(dial: T) => T;
33
+ export type Dial = {
34
+ id: string;
35
+ path: string[];
36
+ inCode: ControlAudience;
37
+ };
38
+ /** A config as DialKit takes it (every `client()` unwrapped) and the dials in it. */
39
+ export declare function readConfig(panel: string, config: Config): {
40
+ config: Config;
41
+ dials: Dial[];
42
+ };
43
+ /** The part of an unwrapped config whose dials `shown` keeps. A folder with none left goes with them. */
44
+ export declare function keepDials(panel: string, config: Config, shown: (id: string) => boolean): Config;
45
+ /**
46
+ * What a dial reads when nobody can move it: the value DialKit would start it
47
+ * at. A test holds this equal to DialKit's own for every kind of dial.
48
+ */
49
+ export declare function defaultOf(dial: unknown): unknown;
50
+ /**
51
+ * The values a prototype reads: DialKit's for the dials it drew, the default
52
+ * for every dial it did not, in the shape of the whole config.
53
+ */
54
+ export declare function withDefaults(config: Config, values: Config): Config;
55
+ export {};