@bridgebrew/plugin-manager 0.0.0-stage → 0.0.2

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,918 @@
1
+ // The settings form's visual field kinds (./settings-form.tsx), chosen by a property's annotations (./settings-fields.ts
2
+ // `controlOf`), for any plugin:
3
+ // - a colour (`x-bridge-colour`): the kit's `ColourPicker`, the default (the theme's colour or none) and the theme's
4
+ // accents inline, more of its colours in a popover, then any CSS colour the schema's `pattern` takes (Custom);
5
+ // - a slider (`x-bridge-slider` on a number with a `minimum` and a `maximum`): the value read out beside it as it
6
+ // moves, saved once it rests 200 ms (or as the field goes);
7
+ // - swatches (`x-bridge-swatches` on an `enum`): a radio group of drawn choices, the arrow keys moving the choice; an enum
8
+ // without a `default` starts with Default (unset); each kind draws from the section's fields the annotation names
9
+ // (`swatchKinds`);
10
+ // - an image (`x-bridge-image`): a thumbnail, Choose or Replace (or an image dropped on it), Remove; the bytes go to the
11
+ // workspace's Bridge (`FormContext.files`), which answers the value to save; its refusal shows under the field;
12
+ // - by mode (`x-bridge-modes`, research-028): a colour's light and dark halves side by side, a half left unset drawn in
13
+ // the theme's own colour for that mode (`x-bridge-theme-colour`) in that mode's theme; an image for both modes, or a
14
+ // light one and a dark one ("Add a dark image…"), each replaced or removed on its own.
15
+ import * as React from 'react';
16
+ import {
17
+ Button,
18
+ ColourPicker,
19
+ getInitials,
20
+ Icon,
21
+ Slider,
22
+ THEME_COLOUR_GROUPS,
23
+ THEME_COLOURS,
24
+ cn,
25
+ useThemeOfMode,
26
+ } from '@bridge/ui';
27
+ import {
28
+ halvesOf,
29
+ modeColour,
30
+ paintSwatch,
31
+ tileColourOf,
32
+ tileShapeStyles,
33
+ withHalf,
34
+ } from '@bridge/kernel/look';
35
+ import type { Schema, Swatches } from './settings-fields.ts';
36
+ import type { FormContext, Path } from './settings-form.tsx';
37
+
38
+ type Props = {
39
+ schema: Schema;
40
+ value: unknown;
41
+ onChange: (next: unknown) => void;
42
+ ctx: FormContext;
43
+ path: Path;
44
+ labelledBy: string;
45
+ };
46
+ type Mode = 'light' | 'dark';
47
+ const modes = ['light', 'dark'] as const;
48
+ const modeTitles = { light: 'Light', dark: 'Dark' };
49
+ const glyphs = {
50
+ light:
51
+ 'M12 3v1M12 20v1M4.2 4.2l.7.7M19.1 19.1l.7.7M3 12h1M20 12h1M4.2 19.8l.7-.7M19.1 4.9l.7-.7M16 12a4 4 0 1 1-8 0 4 4 0 0 1 8 0Z',
52
+ dark: 'M20 14.5A8 8 0 0 1 9.5 4 8 8 0 1 0 20 14.5Z',
53
+ };
54
+ /** A mode's name with its sun or moon, over a half; `id` names the half's controls with the setting's title. */
55
+ const ModeLabel = ({ mode, id }: { mode: Mode; id: string }) => (
56
+ <span id={id} className="flex items-center gap-1 text-xs font-medium text-secondary">
57
+ <svg
58
+ aria-hidden="true"
59
+ viewBox="0 0 24 24"
60
+ fill="none"
61
+ stroke="currentColor"
62
+ strokeWidth="2"
63
+ strokeLinecap="round"
64
+ strokeLinejoin="round"
65
+ className="size-3.5 text-muted"
66
+ >
67
+ <path d={glyphs[mode]} />
68
+ </svg>
69
+ {modeTitles[mode]}
70
+ </span>
71
+ );
72
+ const HalfError = ({ message }: { message: string | undefined }) =>
73
+ message ? (
74
+ <p
75
+ role="alert"
76
+ className="text-xs text-destructive"
77
+ >{`${message.charAt(0).toUpperCase()}${message.slice(1)}`}</p>
78
+ ) : null;
79
+
80
+ const idOf = (ctx: FormContext, path: Path) =>
81
+ `${ctx.id}-${path.join('-')}`.replace(/[^\w-]/g, '_');
82
+
83
+ /** A half of a colour by mode: its name, the text shown unset, and what the swatch draws unset (the theme's colour, in
84
+ * that mode's theme). */
85
+ type Half = {
86
+ name: string;
87
+ placeholder: string;
88
+ unset?: string | undefined;
89
+ theme?: string | undefined;
90
+ };
91
+
92
+ /** A number on its range (`x-bridge-slider`): unset, the schema's `default` (else its `minimum`); the value moved
93
+ * shows at once, saved once it rests 200 ms, at once if the field goes first. */
94
+ export function SliderField({ schema, value, onChange, ctx, path, labelledBy }: Props) {
95
+ const min = schema.minimum!;
96
+ const max = schema.maximum!;
97
+ const stored =
98
+ typeof value === 'number' ? value : typeof schema.default === 'number' ? schema.default : min;
99
+ const [shown, setShown] = React.useState(stored);
100
+ const timer = React.useRef<ReturnType<typeof setTimeout>>(undefined);
101
+ /** The value waiting for `timer`. */
102
+ const pending = React.useRef<number>(undefined);
103
+ React.useEffect(() => {
104
+ if (pending.current === undefined) setShown(stored);
105
+ }, [stored]);
106
+ const onChangeRef = React.useRef(onChange);
107
+ onChangeRef.current = onChange;
108
+ React.useEffect(
109
+ () => () => {
110
+ clearTimeout(timer.current);
111
+ if (pending.current !== undefined) onChangeRef.current(pending.current);
112
+ },
113
+ [],
114
+ );
115
+ return (
116
+ <div data-slider className="flex w-[280px] max-w-full items-center gap-3">
117
+ <Slider
118
+ id={idOf(ctx, path)}
119
+ aria-labelledby={labelledBy}
120
+ min={min}
121
+ max={max}
122
+ step={schema['x-bridge-step'] ?? (schema.type === 'integer' ? 1 : (max - min) / 100)}
123
+ disabled={ctx.disabled}
124
+ value={shown}
125
+ onValueChange={(next) => {
126
+ setShown(next);
127
+ clearTimeout(timer.current);
128
+ pending.current = next;
129
+ timer.current = setTimeout(() => {
130
+ pending.current = undefined;
131
+ if (next !== stored) onChangeRef.current(next);
132
+ }, 200);
133
+ }}
134
+ />
135
+ <output
136
+ aria-hidden="true"
137
+ className="w-9 shrink-0 text-right text-sm tabular-nums text-secondary"
138
+ >
139
+ {shown}
140
+ </output>
141
+ </div>
142
+ );
143
+ }
144
+
145
+ /** A colour (`x-bridge-colour`): the kit's picker, the theme's accents first, then more, then any (Custom). */
146
+ export function ColourField({
147
+ value,
148
+ onChange,
149
+ ctx,
150
+ path,
151
+ labelledBy,
152
+ half,
153
+ }: Props & { half?: Half }) {
154
+ return (
155
+ <ColourPicker
156
+ value={typeof value === 'string' && value !== '' ? value : undefined}
157
+ onChange={onChange}
158
+ defaultColour={half?.unset}
159
+ defaultName={half?.placeholder ?? 'Default'}
160
+ theme={half?.theme}
161
+ disabled={ctx.disabled}
162
+ invalid={ctx.errorAt(path) !== undefined}
163
+ aria-labelledby={labelledBy}
164
+ />
165
+ );
166
+ }
167
+
168
+ /** The default a colour following the theme's `token` (`--paint-c1`) is named by: the theme's own, by its name. */
169
+ const themeColourName = (token: string) => {
170
+ const name = [...THEME_COLOURS, ...THEME_COLOUR_GROUPS.flatMap((group) => group.swatches)].find(
171
+ (swatch) => swatch.value === `var(${token})`,
172
+ )?.name;
173
+ return name ? `Theme's ${name.toLowerCase()}` : "Theme's";
174
+ };
175
+
176
+ /** A colour by mode (`x-bridge-modes`): its light and its dark half side by side, each a colour field; one value stored
177
+ * for both (step 4e's) shows in both halves, and a change to one keeps the other. A half left unset follows the theme. */
178
+ export function ColourPairField({ schema, value, onChange, ctx, path, labelledBy }: Props) {
179
+ const halves = halvesOf(value);
180
+ const themed = schema['x-bridge-theme-colour'];
181
+ const themes = { light: useThemeOfMode('light'), dark: useThemeOfMode('dark') };
182
+ return (
183
+ <div data-colour-pair className="flex flex-wrap gap-x-6 gap-y-3">
184
+ {modes.map((mode) => {
185
+ const at = [...path, mode];
186
+ const label = `${idOf(ctx, at)}-mode`;
187
+ return (
188
+ <div key={mode} data-mode={mode} className="flex w-48 flex-col gap-1.5">
189
+ <ModeLabel mode={mode} id={label} />
190
+ <ColourField
191
+ schema={schema}
192
+ value={halves[mode]}
193
+ onChange={(next) =>
194
+ onChange(withHalf(value, mode, typeof next === 'string' ? next : undefined))
195
+ }
196
+ ctx={ctx}
197
+ path={at}
198
+ labelledBy={`${labelledBy} ${label}`}
199
+ half={{
200
+ name: modeTitles[mode],
201
+ placeholder: themed ? themeColourName(themed) : 'Default',
202
+ unset: themed && `var(${themed})`,
203
+ theme: themes[mode],
204
+ }}
205
+ />
206
+ <HalfError message={ctx.errorAt(at)} />
207
+ </div>
208
+ );
209
+ })}
210
+ </div>
211
+ );
212
+ }
213
+
214
+ /** What a swatch kind draws with: the section's values (by field), its images' URLs, the workspace. */
215
+ interface Drawing {
216
+ /** The annotation (`x-bridge-swatches`): the fields it names. */
217
+ names: Swatches;
218
+ /** A field of the section's value, if a string. */
219
+ text: (field: string | undefined) => string | undefined;
220
+ /** A field of the section's value, as it is (a colour by mode, say). */
221
+ value: (field: string | undefined) => unknown;
222
+ /** The theme a workspace proposing none shows in a mode (a theme choice's Default). */
223
+ themeOf: (mode: Mode) => string;
224
+ imageOf: (field: string) => string | undefined;
225
+ workspace: { slug: string; title: string };
226
+ }
227
+
228
+ /** A canvas in miniature: the rail's strip and (unless `window` is false) a window, on `background`. */
229
+ const Canvas = ({
230
+ style,
231
+ className,
232
+ children,
233
+ window = true,
234
+ }: {
235
+ style?: React.CSSProperties;
236
+ className?: string;
237
+ children?: React.ReactNode;
238
+ window?: boolean;
239
+ }) => (
240
+ <span
241
+ className={cn('relative block h-12 w-[76px] overflow-hidden rounded-[9px]', className)}
242
+ style={style}
243
+ >
244
+ {children}
245
+ <span className="absolute inset-y-0 left-0 flex w-[11px] flex-col items-center gap-[3px] pt-[6px]">
246
+ {[0, 1, 2].map((n) => (
247
+ <span key={n} className="size-[5px] rounded-[2px] bg-white/45" />
248
+ ))}
249
+ </span>
250
+ {window && (
251
+ <span
252
+ data-window
253
+ className="absolute bottom-[9px] left-[24px] right-[9px] top-[9px] rounded-[3px] border border-white/30 bg-white/15 shadow-[0_1px_3px_rgb(0_0_0/0.25)]"
254
+ />
255
+ )}
256
+ </span>
257
+ );
258
+
259
+ /** Each swatch kind: its face for a choice (`undefined`: unset, Default), from the fields the annotation names. `paint`
260
+ * draws a canvas painted from `colours` (`@bridge/kernel/look`, as the shell paints it); `shape` the rail's tile in
261
+ * `colour` (else the workspace's own), with the workspace's initials, the unset one as the rail draws it (rounder, its
262
+ * outline dashed: it rounds further on hover); `fit` the `image` laid that way on the canvas `paint` and `colours`
263
+ * give. */
264
+ /** A picture standing for an image not chosen yet (a sun over hills), `contain`ed or filling its box. */
265
+ const Picture = ({ contain }: { contain?: boolean }) => (
266
+ <svg
267
+ aria-hidden="true"
268
+ viewBox="0 0 40 40"
269
+ className="size-full"
270
+ preserveAspectRatio={contain ? 'xMidYMid meet' : 'xMidYMid slice'}
271
+ >
272
+ <rect width="40" height="40" fill="#93c5fd" />
273
+ <circle cx="28" cy="13" r="5" fill="#fde68a" />
274
+ <path d="M0 30 L12 18 L22 28 L28 22 L40 33 V40 H0 Z" fill="#4f46e5" />
275
+ <path d="M0 36 L14 27 L26 35 L40 30 V40 H0 Z" fill="#312e81" />
276
+ </svg>
277
+ );
278
+
279
+ export const swatchKinds: Record<
280
+ string,
281
+ (choice: string | undefined, drawing: Drawing) => React.ReactNode
282
+ > = {
283
+ paint: (choice, { names, value, imageOf }) => {
284
+ // The wallpaper paint: the section's image (`image`) covering the canvas, else the picture standing for one.
285
+ if (choice === 'wallpaper' && names.image !== undefined) {
286
+ const image = imageOf(names.image);
287
+ return image ? (
288
+ <Canvas style={{ background: `url("${image}") center / cover no-repeat` }} />
289
+ ) : (
290
+ <Canvas>
291
+ <span className="absolute inset-0">
292
+ <Picture />
293
+ </span>
294
+ </Canvas>
295
+ );
296
+ }
297
+ const style = paintSwatch(choice ?? 'neutral', {
298
+ c1: value(names.colours?.[0]),
299
+ c2: value(names.colours?.[1]),
300
+ }) as React.CSSProperties;
301
+ return Object.keys(style).length ? (
302
+ <Canvas style={style} />
303
+ ) : (
304
+ <Canvas className="bg-sidebar outline-1 -outline-offset-1 outline-border [&>span:first-of-type>span]:bg-muted/40 [&>[data-window]]:border-border [&>[data-window]]:bg-surface" />
305
+ );
306
+ },
307
+ shape: (choice, { names, value, workspace }) => (
308
+ <span className="grid h-12 w-12 place-items-center">
309
+ <span
310
+ className={cn(
311
+ 'grid size-10 place-items-center text-[13px] font-semibold text-white',
312
+ choice === undefined &&
313
+ 'outline-[1.5px] -outline-offset-4 outline-dashed outline-white/70',
314
+ )}
315
+ style={{
316
+ background:
317
+ modeColour(value(names.colour), tileColourOf(workspace.slug)) ??
318
+ tileColourOf(workspace.slug),
319
+ ...(choice === undefined ? { borderRadius: '14px' } : tileShapeStyles[choice]),
320
+ }}
321
+ >
322
+ {getInitials(workspace.title)}
323
+ </span>
324
+ </span>
325
+ ),
326
+ fit: (choice, { names, text, value, imageOf }) => {
327
+ const image = names.image === undefined ? undefined : imageOf(names.image);
328
+ const layout: Record<string, string> = {
329
+ cover: 'center / cover no-repeat',
330
+ contain: 'center / contain no-repeat',
331
+ tile: '0 0 / 22px auto repeat',
332
+ centre: 'center / 42% auto no-repeat',
333
+ };
334
+ const paint = paintSwatch(text(names.paint) ?? 'neutral', {
335
+ c1: value(names.colours?.[0]),
336
+ c2: value(names.colours?.[1]),
337
+ }) as React.CSSProperties & { background?: string };
338
+ const under = paint.background ?? 'var(--color-active)';
339
+ if (image)
340
+ return (
341
+ <Canvas
342
+ window={false}
343
+ style={{ ...paint, background: `url("${image}") ${layout[choice ?? 'cover']}, ${under}` }}
344
+ />
345
+ );
346
+ // No image yet: a picture in its place (a sun over hills), laid the same way.
347
+ const picture = <Picture contain={choice === 'contain'} />;
348
+ return (
349
+ <Canvas window={false} style={{ ...paint, background: under }}>
350
+ {choice === 'tile' ? (
351
+ <span className="absolute inset-0 grid grid-cols-4 grid-rows-3">
352
+ {Array.from({ length: 12 }, (_, n) => (
353
+ <span key={n} className="overflow-hidden">
354
+ {picture}
355
+ </span>
356
+ ))}
357
+ </span>
358
+ ) : (
359
+ <span
360
+ className={cn(
361
+ 'absolute',
362
+ choice === 'centre' ? 'left-1/2 top-1/2 size-5 -translate-1/2' : 'inset-0',
363
+ )}
364
+ >
365
+ {picture}
366
+ </span>
367
+ )}
368
+ </Canvas>
369
+ );
370
+ },
371
+ theme: (choice, { names, themeOf }) => (
372
+ // The theme's own colours: its tokens, on this element (`[data-theme]`); unset, the Bridge default's in that mode.
373
+ <span
374
+ data-theme={choice ?? themeOf(names.mode ?? 'light')}
375
+ className="relative block h-12 w-[76px] overflow-hidden rounded-[9px] bg-sidebar outline-1 -outline-offset-1 outline-border"
376
+ >
377
+ <span className="absolute inset-y-0 left-0 flex w-[11px] flex-col items-center gap-[3px] pt-[6px]">
378
+ {[0, 1, 2].map((n) => (
379
+ <span
380
+ key={n}
381
+ className={cn('size-[5px] rounded-[2px]', n === 0 ? 'bg-accent' : 'bg-muted/50')}
382
+ />
383
+ ))}
384
+ </span>
385
+ <span className="absolute bottom-[7px] left-[17px] right-[7px] top-[7px] flex flex-col gap-[3px] rounded-[3px] border border-border bg-background p-[4px] shadow-[0_1px_2px_rgb(0_0_0/0.18)]">
386
+ <span className="h-[3px] w-3/5 rounded-full bg-foreground/80" />
387
+ <span className="h-[3px] w-4/5 rounded-full bg-muted/60" />
388
+ <span className="mt-auto h-[6px] w-[18px] rounded-[2px] bg-accent" />
389
+ </span>
390
+ </span>
391
+ ),
392
+ };
393
+
394
+ export function SwatchField({ schema, value, onChange, ctx, labelledBy }: Props) {
395
+ const names = schema['x-bridge-swatches']!;
396
+ const draw = swatchKinds[names.kind];
397
+ const labels = schema['x-bridge-labels'] ?? [];
398
+ const kind = schema['x-bridge-options'];
399
+ const themes = {
400
+ light: useThemeOfMode('light', 'bridge'),
401
+ dark: useThemeOfMode('dark', 'bridge'),
402
+ };
403
+ // An enum's choices, else the page's (`x-bridge-options`), labelled by the page; one stored that the page lacks kept.
404
+ const known = schema.enum ?? (kind === undefined ? [] : ctx.options(kind));
405
+ const listed = typeof value === 'string' && !known.includes(value) ? [...known, value] : known;
406
+ const choices: { value: string | undefined; label: string }[] = [
407
+ // Without a default, unset is a choice of its own.
408
+ ...(schema.default === undefined ? [{ value: undefined, label: 'Default' }] : []),
409
+ ...listed.map((each, at) => ({
410
+ value: String(each),
411
+ label:
412
+ labels[at] ??
413
+ (kind === undefined ? undefined : ctx.optionLabel?.(kind, String(each))) ??
414
+ String(each),
415
+ })),
416
+ ];
417
+ const current =
418
+ typeof value === 'string'
419
+ ? value
420
+ : typeof schema.default === 'string'
421
+ ? schema.default
422
+ : undefined;
423
+ const drawing: Drawing = {
424
+ names,
425
+ text: (field) => {
426
+ const each = field === undefined ? undefined : ctx.values?.[field];
427
+ return typeof each === 'string' ? each : undefined;
428
+ },
429
+ value: (field) => (field === undefined ? undefined : ctx.values?.[field]),
430
+ themeOf: (mode) => themes[mode],
431
+ imageOf: (field) => ctx.imageOf?.(field),
432
+ workspace: ctx.workspace ?? { slug: '', title: '' },
433
+ };
434
+ // A choice needing a field the section leaves unset (`x-bridge-requires`): unavailable, its reason said under the row.
435
+ const requires = schema['x-bridge-requires'] ?? {};
436
+ const unavailable = (choice: string | undefined) => {
437
+ const need = choice === undefined ? undefined : requires[choice];
438
+ return need !== undefined && ctx.values?.[need.field] === undefined ? need.message : undefined;
439
+ };
440
+ const reasons = [...new Set(choices.map((choice) => unavailable(choice.value)))].filter(
441
+ (reason) => reason !== undefined,
442
+ );
443
+ // The one Tab reaches: the chosen choice, or the first available one when the chosen is unset or unavailable.
444
+ const chosen = choices.findIndex((choice) => choice.value === current);
445
+ const stop =
446
+ chosen >= 0 && unavailable(current) === undefined
447
+ ? chosen
448
+ : Math.max(
449
+ 0,
450
+ choices.findIndex((choice) => unavailable(choice.value) === undefined),
451
+ );
452
+ const pick = (choice: string | undefined) => {
453
+ if (choice !== current && unavailable(choice) === undefined) onChange(choice);
454
+ };
455
+ const step = (event: React.KeyboardEvent<HTMLButtonElement>, index: number) => {
456
+ const by =
457
+ event.key === 'ArrowRight' || event.key === 'ArrowDown'
458
+ ? 1
459
+ : event.key === 'ArrowLeft' || event.key === 'ArrowUp'
460
+ ? -1
461
+ : 0;
462
+ if (by === 0) return;
463
+ event.preventDefault();
464
+ let next = index;
465
+ do next = (next + by + choices.length) % choices.length;
466
+ while (next !== index && unavailable(choices[next]!.value) !== undefined);
467
+ pick(choices[next]!.value);
468
+ event.currentTarget.parentElement
469
+ ?.querySelectorAll<HTMLButtonElement>('[role="radio"]')
470
+ [next]?.focus();
471
+ };
472
+ // Labels only: a segmented row of the choices, the chosen one raised.
473
+ if (names.kind === 'choice') {
474
+ return (
475
+ <div
476
+ role="radiogroup"
477
+ aria-labelledby={labelledBy}
478
+ data-swatches="choice"
479
+ className="inline-flex max-w-full flex-wrap gap-0.5 rounded-control bg-active p-0.5"
480
+ >
481
+ {choices.map((choice, index) => {
482
+ const checked = choice.value === current;
483
+ return (
484
+ <button
485
+ key={choice.label}
486
+ type="button"
487
+ role="radio"
488
+ aria-checked={checked}
489
+ data-choice={choice.value ?? ''}
490
+ tabIndex={index === stop ? 0 : -1}
491
+ disabled={ctx.disabled}
492
+ onClick={() => pick(choice.value)}
493
+ onKeyDown={(event) => step(event, index)}
494
+ className={cn(
495
+ 'h-7 cursor-pointer rounded-control-inner border-0 px-3 font-[inherit] text-xs outline-hidden transition-colors duration-100 focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-default disabled:opacity-60',
496
+ checked
497
+ ? 'bg-surface font-medium text-foreground shadow-[0_1px_2px_rgb(0_0_0/0.14),0_0_0_1px_var(--border-subtle)]'
498
+ : 'bg-transparent text-secondary hover:text-foreground',
499
+ )}
500
+ >
501
+ {choice.label}
502
+ </button>
503
+ );
504
+ })}
505
+ </div>
506
+ );
507
+ }
508
+ const row = (
509
+ <div
510
+ role="radiogroup"
511
+ aria-labelledby={labelledBy}
512
+ data-swatches={names.kind}
513
+ className="-ml-1.5 flex flex-wrap gap-1"
514
+ >
515
+ {choices.map((choice, index) => {
516
+ const checked = choice.value === current;
517
+ // One width for every choice, the widest drawing's (a theme's window, 76 px, with its ring and padding): a long
518
+ // name wraps under its swatch instead of widening it, so the wrapped rows line up in columns.
519
+ return (
520
+ <button
521
+ key={choice.label}
522
+ type="button"
523
+ role="radio"
524
+ aria-checked={checked}
525
+ aria-label={choice.label}
526
+ data-choice={choice.value ?? ''}
527
+ data-unavailable={unavailable(choice.value) !== undefined || undefined}
528
+ title={unavailable(choice.value)}
529
+ tabIndex={index === stop ? 0 : -1}
530
+ disabled={ctx.disabled || unavailable(choice.value) !== undefined}
531
+ onClick={() => pick(choice.value)}
532
+ onKeyDown={(event) => step(event, index)}
533
+ className="group/swatch flex w-[5.75rem] cursor-pointer flex-col items-center justify-start gap-1.5 rounded-lg border-0 bg-transparent px-1.5 pb-1 pt-1.5 font-[inherit] outline-hidden hover:bg-hover focus-visible:bg-hover disabled:cursor-default disabled:opacity-60"
534
+ >
535
+ <span
536
+ aria-hidden="true"
537
+ className={cn(
538
+ 'block rounded-[12px] p-[3px] ring-2 transition-shadow duration-100',
539
+ checked
540
+ ? 'ring-accent'
541
+ : 'ring-transparent group-hover/swatch:ring-border group-focus-visible/swatch:ring-border',
542
+ )}
543
+ >
544
+ {draw ? (
545
+ draw(choice.value, drawing)
546
+ ) : (
547
+ <span className="grid h-8 min-w-14 place-items-center rounded-[9px] bg-active px-2 text-xs text-foreground">
548
+ {choice.label}
549
+ </span>
550
+ )}
551
+ </span>
552
+ <span
553
+ className={cn(
554
+ 'line-clamp-2 max-w-full text-center text-xs leading-4 break-words',
555
+ checked ? 'font-medium text-foreground' : 'text-secondary',
556
+ )}
557
+ >
558
+ {choice.label}
559
+ </span>
560
+ </button>
561
+ );
562
+ })}
563
+ </div>
564
+ );
565
+ if (reasons.length === 0) return row;
566
+ return (
567
+ <div className="flex flex-col gap-1">
568
+ {row}
569
+ {reasons.map((reason) => (
570
+ <p key={reason} data-unavailable-reason className="text-xs text-muted">
571
+ {reason}
572
+ </p>
573
+ ))}
574
+ </div>
575
+ );
576
+ }
577
+
578
+ export function ImageField({ schema, value, onChange, ctx, path, labelledBy }: Props) {
579
+ const route = schema['x-bridge-image']!;
580
+ const url = typeof value === 'string' && value ? ctx.files?.url(route, value) : undefined;
581
+ const [uploading, setUploading] = React.useState(false);
582
+ const [dragging, setDragging] = React.useState(false);
583
+ const [problem, setProblem] = React.useState<{ message: string; hint?: string | undefined }>();
584
+ const file = React.useRef<HTMLInputElement>(null);
585
+ const disabled = ctx.disabled || uploading || !ctx.files;
586
+ const upload = async (image: File | undefined) => {
587
+ if (!image || disabled) return;
588
+ setUploading(true);
589
+ setProblem(undefined);
590
+ const answer = await ctx.files!.upload(route, image);
591
+ setUploading(false);
592
+ if ('error' in answer) return setProblem({ message: answer.error, hint: answer.hint });
593
+ onChange(answer.value);
594
+ };
595
+ const drop = {
596
+ onDragOver: (event: React.DragEvent) => {
597
+ if (!disabled && event.dataTransfer.types.includes('Files')) {
598
+ event.preventDefault();
599
+ setDragging(true);
600
+ }
601
+ },
602
+ onDragLeave: (event: React.DragEvent) => {
603
+ if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setDragging(false);
604
+ },
605
+ onDrop: (event: React.DragEvent) => {
606
+ if (!event.dataTransfer.types.includes('Files')) return;
607
+ event.preventDefault();
608
+ setDragging(false);
609
+ void upload(event.dataTransfer.files[0]);
610
+ },
611
+ };
612
+ return (
613
+ <div data-image className="flex flex-col gap-2">
614
+ <div className="flex items-start gap-4">
615
+ <div
616
+ {...drop}
617
+ data-dragging={dragging || undefined}
618
+ className={cn(
619
+ 'relative grid h-[110px] w-[176px] shrink-0 place-items-center overflow-hidden rounded-lg border bg-hover',
620
+ url ? 'border-border shadow-[0_1px_2px_rgb(0_0_0/0.12)]' : 'border-dashed border-input',
621
+ dragging && 'border-accent ring-2 ring-accent',
622
+ )}
623
+ >
624
+ {url ? (
625
+ <img src={url} alt="The current image" className="size-full object-cover" />
626
+ ) : (
627
+ <span className="flex flex-col items-center gap-1.5 px-3 text-center text-xs leading-4 text-muted">
628
+ <Icon name="image" size={20} />
629
+ Drop an image here
630
+ </span>
631
+ )}
632
+ {uploading && (
633
+ <span className="absolute inset-0 grid place-items-center bg-surface/70 backdrop-blur-[1px]">
634
+ <Icon
635
+ name="loader-circle"
636
+ size={18}
637
+ className="animate-spin motion-reduce:animate-none"
638
+ />
639
+ </span>
640
+ )}
641
+ </div>
642
+ <div className="flex min-w-0 flex-col gap-2 pt-0.5">
643
+ <div className="flex flex-wrap gap-1.5">
644
+ <Button
645
+ id={idOf(ctx, path)}
646
+ variant="outline"
647
+ aria-describedby={labelledBy}
648
+ disabled={disabled}
649
+ onClick={() => file.current?.click()}
650
+ >
651
+ <Icon name="image" />
652
+ {uploading ? 'Uploading…' : url ? 'Replace image…' : 'Choose image…'}
653
+ </Button>
654
+ {url && (
655
+ <Button variant="destructive" disabled={disabled} onClick={() => onChange(undefined)}>
656
+ <Icon name="trash" />
657
+ Remove
658
+ </Button>
659
+ )}
660
+ </div>
661
+ <input
662
+ ref={file}
663
+ type="file"
664
+ accept="image/*"
665
+ className="sr-only"
666
+ tabIndex={-1}
667
+ aria-labelledby={labelledBy}
668
+ onChange={(event) => {
669
+ void upload(event.target.files?.[0]);
670
+ event.target.value = '';
671
+ }}
672
+ />
673
+ <p className="text-xs leading-[18px] text-muted">
674
+ {url ? 'Drop another image on it to replace it.' : 'Or drop one on the frame.'}
675
+ </p>
676
+ </div>
677
+ </div>
678
+ {problem && (
679
+ <p
680
+ role="alert"
681
+ data-image-problem
682
+ className="flex max-w-[560px] items-start gap-1.5 rounded-default bg-destructive-subtle px-2.5 py-1.5 text-xs text-destructive"
683
+ >
684
+ <Icon name="triangle-alert" size={14} className="mt-px shrink-0" />
685
+ <span>
686
+ {`${problem.message.charAt(0).toUpperCase()}${problem.message.slice(1)}.`}
687
+ {problem.hint !== undefined && (
688
+ <>
689
+ {' '}
690
+ <span className="text-secondary">{problem.hint}</span>
691
+ </>
692
+ )}
693
+ </span>
694
+ </p>
695
+ )}
696
+ </div>
697
+ );
698
+ }
699
+
700
+ /** An image by mode (`x-bridge-modes`, research-028 A8): one image for both modes (a string), or a light one and a dark
701
+ * one. One: its frame, Choose or Replace, Remove, and "Add a dark image…"; two: a frame each, under its mode, each
702
+ * replaced (or dropped on) and removed on its own, the one left then showing in both modes. The bytes go to the
703
+ * workspace's Bridge, a half's with its mode (the host keeps the other half). One file input for all. */
704
+ export function ImagePairField({ schema, value, onChange, ctx, path, labelledBy }: Props) {
705
+ const route = schema['x-bridge-image']!;
706
+ const halves = halvesOf(value);
707
+ const one = halves.light ?? halves.dark;
708
+ const two =
709
+ halves.light !== undefined && halves.dark !== undefined && halves.light !== halves.dark;
710
+ const urlOf = (hash: string | undefined) => (hash ? ctx.files?.url(route, hash) : undefined);
711
+ /** What is uploading: the one image (`both`) or a half. */
712
+ const [uploading, setUploading] = React.useState<Mode | 'both'>();
713
+ const [dragging, setDragging] = React.useState<Mode | 'both'>();
714
+ const [problem, setProblem] = React.useState<{ message: string; hint?: string | undefined }>();
715
+ const file = React.useRef<HTMLInputElement>(null);
716
+ /** The half the file input chooses for (`both`: the one image). */
717
+ const target = React.useRef<Mode | 'both'>('both');
718
+ const disabled = ctx.disabled || uploading !== undefined || !ctx.files;
719
+ const upload = async (image: File | undefined, half: Mode | 'both') => {
720
+ if (!image || disabled) return;
721
+ setUploading(half);
722
+ setProblem(undefined);
723
+ const answer = await ctx.files!.upload(route, image, half === 'both' ? undefined : half);
724
+ setUploading(undefined);
725
+ if ('error' in answer) return setProblem({ message: answer.error, hint: answer.hint });
726
+ // A half added to one image keeps it for the other mode (one half alone is one image too).
727
+ onChange(half === 'both' ? answer.value : withHalf(two ? value : one, half, answer.value));
728
+ };
729
+ const choose = (half: Mode | 'both') => {
730
+ target.current = half;
731
+ file.current?.click();
732
+ };
733
+ /** A half removed: the other one alone, for both modes. */
734
+ const remove = (half: Mode) => {
735
+ const rest = withHalf(value, half, undefined);
736
+ onChange(rest?.light ?? rest?.dark);
737
+ };
738
+ const frame = (half: Mode | 'both', hash: string | undefined, size: 'lg' | 'sm') => {
739
+ const url = urlOf(hash);
740
+ return (
741
+ <div
742
+ data-frame={half}
743
+ data-dragging={dragging === half || undefined}
744
+ onDragOver={(event) => {
745
+ if (!disabled && event.dataTransfer.types.includes('Files')) {
746
+ event.preventDefault();
747
+ setDragging(half);
748
+ }
749
+ }}
750
+ onDragLeave={(event) => {
751
+ if (!event.currentTarget.contains(event.relatedTarget as Node | null))
752
+ setDragging(undefined);
753
+ }}
754
+ onDrop={(event) => {
755
+ if (!event.dataTransfer.types.includes('Files')) return;
756
+ event.preventDefault();
757
+ setDragging(undefined);
758
+ void upload(event.dataTransfer.files[0], half);
759
+ }}
760
+ className={cn(
761
+ 'relative grid shrink-0 place-items-center overflow-hidden rounded-lg border bg-hover',
762
+ size === 'lg' ? 'h-[110px] w-[176px]' : 'h-[92px] w-[148px]',
763
+ url ? 'border-border shadow-[0_1px_2px_rgb(0_0_0/0.12)]' : 'border-dashed border-input',
764
+ dragging === half && 'border-accent ring-2 ring-accent',
765
+ )}
766
+ >
767
+ {url ? (
768
+ <img
769
+ src={url}
770
+ alt={half === 'both' ? 'The current image' : `The ${half} image`}
771
+ className="size-full object-cover"
772
+ />
773
+ ) : (
774
+ <span className="flex flex-col items-center gap-1.5 px-3 text-center text-xs leading-4 text-muted">
775
+ <Icon name="image" size={20} />
776
+ Drop an image here
777
+ </span>
778
+ )}
779
+ {uploading === half && (
780
+ <span className="absolute inset-0 grid place-items-center bg-surface/70 backdrop-blur-[1px]">
781
+ <Icon
782
+ name="loader-circle"
783
+ size={18}
784
+ className="animate-spin motion-reduce:animate-none"
785
+ />
786
+ </span>
787
+ )}
788
+ </div>
789
+ );
790
+ };
791
+ return (
792
+ <div data-image data-image-pair={two ? 'two' : 'one'} className="flex flex-col gap-2">
793
+ {two ? (
794
+ <div className="flex flex-wrap gap-x-6 gap-y-3">
795
+ {modes.map((mode) => (
796
+ <div key={mode} data-mode={mode} className="flex flex-col gap-1.5">
797
+ <ModeLabel mode={mode} id={`${idOf(ctx, [...path, mode])}-mode`} />
798
+ {frame(mode, halves[mode], 'sm')}
799
+ <div className="flex gap-1.5">
800
+ <Button
801
+ size="sm"
802
+ variant="outline"
803
+ aria-label={`Replace the ${mode} image…`}
804
+ disabled={disabled}
805
+ onClick={() => choose(mode)}
806
+ >
807
+ <Icon name="image" />
808
+ {uploading === mode ? 'Uploading…' : 'Replace…'}
809
+ </Button>
810
+ <Button
811
+ size="sm"
812
+ variant="ghost"
813
+ aria-label={`Remove the ${mode} image`}
814
+ disabled={disabled}
815
+ onClick={() => remove(mode)}
816
+ >
817
+ <Icon name="trash" />
818
+ Remove
819
+ </Button>
820
+ </div>
821
+ </div>
822
+ ))}
823
+ </div>
824
+ ) : (
825
+ <div className="flex items-start gap-4">
826
+ {frame('both', one, 'lg')}
827
+ <div className="flex min-w-0 flex-col gap-2 pt-0.5">
828
+ <div className="flex flex-wrap gap-1.5">
829
+ <Button
830
+ id={idOf(ctx, path)}
831
+ variant="outline"
832
+ aria-describedby={labelledBy}
833
+ disabled={disabled}
834
+ onClick={() => choose('both')}
835
+ >
836
+ <Icon name="image" />
837
+ {uploading === 'both' ? 'Uploading…' : one ? 'Replace image…' : 'Choose image…'}
838
+ </Button>
839
+ {one && (
840
+ <Button
841
+ variant="destructive"
842
+ disabled={disabled}
843
+ onClick={() => onChange(undefined)}
844
+ >
845
+ <Icon name="trash" />
846
+ Remove
847
+ </Button>
848
+ )}
849
+ </div>
850
+ {one ? (
851
+ <>
852
+ <p className="text-xs leading-[18px] text-muted">
853
+ Shown in light and dark mode. Drop another image on it to replace it.
854
+ </p>
855
+ <Button
856
+ size="sm"
857
+ variant="ghost"
858
+ className="self-start"
859
+ disabled={disabled}
860
+ onClick={() => choose('dark')}
861
+ >
862
+ <svg
863
+ aria-hidden="true"
864
+ viewBox="0 0 24 24"
865
+ fill="none"
866
+ stroke="currentColor"
867
+ strokeWidth="2"
868
+ strokeLinecap="round"
869
+ strokeLinejoin="round"
870
+ className="size-3.5"
871
+ >
872
+ <path d={glyphs.dark} />
873
+ </svg>
874
+ {uploading === 'dark' ? 'Uploading…' : 'Add a dark image…'}
875
+ </Button>
876
+ </>
877
+ ) : (
878
+ <p className="text-xs leading-[18px] text-muted">
879
+ Or drop one on the frame. One image shows in both modes; add a dark one once it is
880
+ set.
881
+ </p>
882
+ )}
883
+ </div>
884
+ </div>
885
+ )}
886
+ <input
887
+ ref={file}
888
+ type="file"
889
+ accept="image/*"
890
+ className="sr-only"
891
+ tabIndex={-1}
892
+ aria-labelledby={labelledBy}
893
+ onChange={(event) => {
894
+ void upload(event.target.files?.[0], target.current);
895
+ event.target.value = '';
896
+ }}
897
+ />
898
+ {problem && (
899
+ <p
900
+ role="alert"
901
+ data-image-problem
902
+ className="flex max-w-[560px] items-start gap-1.5 rounded-default bg-destructive-subtle px-2.5 py-1.5 text-xs text-destructive"
903
+ >
904
+ <Icon name="triangle-alert" size={14} className="mt-px shrink-0" />
905
+ <span>
906
+ {`${problem.message.charAt(0).toUpperCase()}${problem.message.slice(1)}.`}
907
+ {problem.hint !== undefined && (
908
+ <>
909
+ {' '}
910
+ <span className="text-secondary">{problem.hint}</span>
911
+ </>
912
+ )}
913
+ </span>
914
+ </p>
915
+ )}
916
+ </div>
917
+ );
918
+ }