@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,1669 @@
1
+ // The settings form generator (the Settings screen's, and System → Providers' driver forms): one control per JSON Schema (./settings-fields.ts `controlOf`), recursive. An object with
2
+ // `properties` is a group of labelled sub-fields; a map (`additionalProperties` schema) a list of collapsible cards by
3
+ // name (rename, remove, "Add <title>"); an array of strings tags (with suggestions from `x-bridge-options`); an array of
4
+ // objects a list of cards (add, remove, move up or down); a string with `x-bridge-options` a select of those options; a
5
+ // number an input within its bounds. Every change is committed whole (`onChange` with the setting's next value): text
6
+ // and numbers on blur or Enter, the rest at once; an empty optional sub-field is removed. An error shows under the
7
+ // field its path anchors to (`FormContext.errorAt`). A colour, swatches and an image (each by mode too) are
8
+ // ./settings-kinds.tsx's. A setting that is one object may carry `x-bridge-action` (one action or a list): a button
9
+ // each, posting the saved value to the plugin's route and waiting while the value differs from the saved one. An
10
+ // explicit setting (`x-bridge-commit: "explicit"`) keeps an edit a draft, saved by a `save: true` action (Test and save): the
11
+ // draft is tested first, its sensitive values as draft secrets, and saved only once the answer is ok; Cancel drops it.
12
+ import * as React from 'react';
13
+ import {
14
+ Checkbox,
15
+ Button,
16
+ Card,
17
+ DataMenuTrigger,
18
+ Icon,
19
+ PickMenu,
20
+ TagList,
21
+ TagPill,
22
+ Input,
23
+ Combobox,
24
+ Select,
25
+ SelectContent,
26
+ SelectItem,
27
+ SelectTrigger,
28
+ SelectValue,
29
+ TagInput,
30
+ Textarea,
31
+ Toggle,
32
+ cn,
33
+ isRecord,
34
+ isComposing,
35
+ } from '@bridge/ui';
36
+ import {
37
+ checkName,
38
+ controlOf,
39
+ highlight,
40
+ humanize,
41
+ isSecretMarker,
42
+ renameKey,
43
+ type Schema,
44
+ } from './settings-fields.ts';
45
+ import {
46
+ ColourField,
47
+ ColourPairField,
48
+ ImageField,
49
+ ImagePairField,
50
+ SliderField,
51
+ SwatchField,
52
+ } from './settings-kinds.tsx';
53
+
54
+ export type Path = (string | number)[];
55
+ /** What an `x-bridge-action` answered: it worked (`message` to show), or why not and what to do. */
56
+ export type ActionResult =
57
+ | { ok: true; message?: string | undefined }
58
+ | { ok: false; error: string; hint?: string | undefined };
59
+ export interface FormContext {
60
+ disabled: boolean;
61
+ /** The error message anchored at `path`, if any. */
62
+ errorAt(path: Path): string | undefined;
63
+ /** The choices `x-bridge-options` names (`plugins`, `drivers`, `modes`, `renderings`, `icon-sets`, `window-managers`, `session-prompts`,
64
+ * or `route:<path>`: a plugin route's) for the field at `path`. */
65
+ options(kind: string, path?: Path): string[];
66
+ /** A choice's label, where the page has one (a rendering's, an icon set's, a window manager's name). */
67
+ optionLabel?: (kind: string, value: string) => string | undefined;
68
+ /** The setting's saved value (the host's), to tell an entry edited and not yet saved (`x-bridge-action`). */
69
+ saved?: unknown;
70
+ /** Runs an `x-bridge-action`: posts `entry` (saved) to the plugin's route `path`. None: the button is not shown. */
71
+ runAction?: (action: SettingAction, entry: unknown) => Promise<ActionResult>;
72
+ /** An explicit setting's draft: saves it when it differs from the saved value, resolving with the host's refusal or
73
+ * nothing once saved (or at once when nothing differs). */
74
+ commit?: () => Promise<string | undefined>;
75
+ /** An explicit setting's draft: back to the saved value, its errors cleared. */
76
+ discard?: () => void;
77
+ /** A draft secret's marker for a typed sensitive value (the host's, in memory a few minutes): what Test and save tests
78
+ * a draft with, so the plugin never sees the value. None: the draft is posted as it is. */
79
+ draftSecret?: (value: string) => Promise<string>;
80
+ /** An explicit setting: removes the sub-field at `path` (a stored secret's Remove) and saves that at once, from the saved
81
+ * value, not as a draft. */
82
+ remove?: (path: Path) => void;
83
+ /** The search, for highlighting. */
84
+ needle: string;
85
+ /** Unique per setting: control ids. */
86
+ id: string;
87
+ /** The section's values by field (the other settings of the plugin), which swatches draw with (./settings-kinds.tsx). */
88
+ values?: Record<string, unknown>;
89
+ /** The URL of the image field `field` of the section shows, if it has one. */
90
+ imageOf?: (field: string) => string | undefined;
91
+ /** The workspace shown: a tile swatch's colour and initials. */
92
+ workspace?: { slug: string; title: string };
93
+ /** An image field's route (`x-bridge-image`): its URL for a value, and an upload answering the value to save or the
94
+ * host's refusal; `mode`, a half of an image by mode (`x-bridge-modes`: `?mode=`). None: images cannot be chosen here. */
95
+ files?: {
96
+ url: (route: string, value: string) => string;
97
+ upload: (
98
+ route: string,
99
+ file: File,
100
+ mode?: 'light' | 'dark',
101
+ ) => Promise<{ value: string } | { error: string; hint?: string | undefined }>;
102
+ };
103
+ }
104
+
105
+ const idOf = (ctx: FormContext, path: Path) =>
106
+ `${ctx.id}-${path.join('-')}`.replace(/[^\w-]/g, '_');
107
+ const titleOf = (schema: Schema, key: string | number) =>
108
+ schema.title ?? (typeof key === 'number' ? `Item ${key + 1}` : humanize(key));
109
+
110
+ /** One `x-bridge-action`: its button's label and the plugin's route it posts to; `save` saves the draft first. */
111
+ type SettingAction = { label: string; path: string; save?: boolean; draft?: boolean };
112
+ /** The actions `schema` declares: one, or a list of them. */
113
+ const actionsOf = (schema: Schema): SettingAction[] => {
114
+ const action = schema['x-bridge-action'];
115
+ return action === undefined ? [] : Array.isArray(action) ? action : [action];
116
+ };
117
+ /** The one action a list item's schema declares (a setting's list items take one each). */
118
+ const singleActionOf = (schema: Schema): SettingAction | undefined => {
119
+ const action = schema['x-bridge-action'];
120
+ return action !== undefined && !Array.isArray(action) ? action : undefined;
121
+ };
122
+
123
+ export const Marked = ({ text, needle }: { text: string; needle: string }) => (
124
+ <>
125
+ {highlight(text, needle).map((part, index) =>
126
+ part.match ? (
127
+ <mark key={index} className="rounded-[2px] bg-accent-subtle px-px text-accent">
128
+ {part.text}
129
+ </mark>
130
+ ) : (
131
+ part.text
132
+ ),
133
+ )}
134
+ </>
135
+ );
136
+
137
+ const IconButton = ({
138
+ label,
139
+ icon,
140
+ onClick,
141
+ disabled,
142
+ }: {
143
+ label: string;
144
+ icon: string;
145
+ onClick: () => void;
146
+ disabled?: boolean;
147
+ }) => (
148
+ <Button size="icon-sm" aria-label={label} title={label} disabled={disabled} onClick={onClick}>
149
+ <Icon name={icon} size={14} />
150
+ </Button>
151
+ );
152
+
153
+ export const FieldMessage = ({ message }: { message: string | undefined }) =>
154
+ message ? (
155
+ <p
156
+ role="alert"
157
+ className="text-xs text-destructive"
158
+ >{`${message.charAt(0).toUpperCase()}${message.slice(1)}`}</p>
159
+ ) : null;
160
+
161
+ /** A text or number input committing on blur or Enter (Escape restores); empty commits `undefined`. */
162
+ function TextField({
163
+ schema,
164
+ value,
165
+ onChange,
166
+ ctx,
167
+ path,
168
+ number,
169
+ labelledBy,
170
+ }: {
171
+ schema: Schema;
172
+ value: unknown;
173
+ onChange: (next: unknown) => void;
174
+ ctx: FormContext;
175
+ path: Path;
176
+ number: boolean;
177
+ labelledBy: string;
178
+ }) {
179
+ const shown = value === undefined || value === null ? '' : String(value);
180
+ const [text, setText] = React.useState(shown);
181
+ React.useEffect(() => setText(shown), [shown]);
182
+ const commit = () => {
183
+ if (text === shown) return;
184
+ if (text.trim() === '') return onChange(undefined);
185
+ onChange(number ? Number(text) : text);
186
+ };
187
+ // A multi-line string: the kit's Textarea grows with its content; Enter adds a line, so it commits on blur.
188
+ if (!number && schema['x-bridge-multiline'] === true)
189
+ return (
190
+ <Textarea
191
+ id={idOf(ctx, path)}
192
+ variant="outline"
193
+ className="w-full max-w-[420px]"
194
+ aria-labelledby={labelledBy}
195
+ aria-invalid={ctx.errorAt(path) !== undefined || undefined}
196
+ disabled={ctx.disabled}
197
+ placeholder="Not set"
198
+ value={text}
199
+ onChange={(event) => setText(event.currentTarget.value)}
200
+ onBlur={commit}
201
+ onKeyDown={(event) => {
202
+ if (event.key === 'Escape') setText(shown);
203
+ }}
204
+ />
205
+ );
206
+ return (
207
+ <Input
208
+ id={idOf(ctx, path)}
209
+ variant="outline"
210
+ size="default"
211
+ className={number ? 'w-40' : 'w-full max-w-[420px]'}
212
+ aria-labelledby={labelledBy}
213
+ {...(number && {
214
+ type: 'number',
215
+ step: schema.type === 'integer' ? 1 : 'any',
216
+ ...(schema.minimum !== undefined && { min: schema.minimum }),
217
+ ...(schema.maximum !== undefined && { max: schema.maximum }),
218
+ })}
219
+ aria-invalid={ctx.errorAt(path) !== undefined || undefined}
220
+ disabled={ctx.disabled}
221
+ // A field left empty takes its default: shown in its place, not "Not set".
222
+ placeholder={
223
+ typeof schema.default === 'string' || typeof schema.default === 'number'
224
+ ? String(schema.default)
225
+ : 'Not set'
226
+ }
227
+ value={text}
228
+ onChange={(event) => setText(event.currentTarget.value)}
229
+ onBlur={commit}
230
+ onKeyDown={(event) => {
231
+ if (event.key === 'Enter' && !isComposing(event)) commit();
232
+ else if (event.key === 'Escape') setText(shown);
233
+ }}
234
+ />
235
+ );
236
+ }
237
+
238
+ /** A secret (`x-bridge-secret`, its object `sensitive`): a password input that never shows a stored value. Stored (the
239
+ * value is the host's marker): empty, "Stored secret, enter a new value to replace it", and Remove on the right. A
240
+ * typed value commits on blur or Enter, as text does; the host moves it out of the setting. */
241
+ function SecretField({
242
+ value,
243
+ onChange,
244
+ ctx,
245
+ path,
246
+ labelledBy,
247
+ }: {
248
+ value: unknown;
249
+ onChange: (next: unknown) => void;
250
+ ctx: FormContext;
251
+ path: Path;
252
+ labelledBy: string;
253
+ }) {
254
+ const stored = isSecretMarker(value);
255
+ const [text, setText] = React.useState('');
256
+ // The host's answer empties the field, unless a replacement was begun while it saved (the field stays usable).
257
+ const committed = React.useRef<string | undefined>(undefined);
258
+ React.useEffect(() => {
259
+ setText((typed) =>
260
+ committed.current === undefined || typed === committed.current ? '' : typed,
261
+ );
262
+ committed.current = undefined;
263
+ }, [value]);
264
+ const commit = () => {
265
+ if (text === '') return;
266
+ committed.current = text;
267
+ onChange(text);
268
+ };
269
+ return (
270
+ <div className="flex w-full max-w-[420px] items-center gap-2">
271
+ <Input
272
+ id={idOf(ctx, path)}
273
+ // A real password field, so screen readers do not read the value (#373). Chrome must neither save, fill nor
274
+ // generate a password there: "one-time-code" keeps its password manager out ("off" is ignored on a password
275
+ // field, "new-password" offers a generated one), no <form> encloses the field, and it empties itself once the
276
+ // host stores the secret; the data- attributes keep other password managers out.
277
+ type="password"
278
+ autoComplete="one-time-code"
279
+ spellCheck={false}
280
+ autoCapitalize="off"
281
+ data-1p-ignore=""
282
+ data-lpignore="true"
283
+ data-bwignore="true"
284
+ data-form-type="other"
285
+ data-secret
286
+ variant="outline"
287
+ size="default"
288
+ className="min-w-0 flex-1"
289
+ aria-labelledby={labelledBy}
290
+ aria-invalid={ctx.errorAt(path) !== undefined || undefined}
291
+ disabled={ctx.disabled}
292
+ placeholder={
293
+ stored
294
+ ? 'Stored secret, enter a new value to replace it'
295
+ : typeof value === 'string' && value !== ''
296
+ ? 'Saved as plain text, enter it again to store it as a secret'
297
+ : 'Not set'
298
+ }
299
+ value={text}
300
+ onChange={(event) => setText(event.currentTarget.value)}
301
+ onBlur={commit}
302
+ onKeyDown={(event) => {
303
+ if (event.key === 'Enter' && !isComposing(event)) commit();
304
+ else if (event.key === 'Escape') setText('');
305
+ }}
306
+ />
307
+ {stored && !ctx.disabled && (
308
+ <Button
309
+ size="sm"
310
+ variant="outline"
311
+ onClick={() => (ctx.remove ? ctx.remove(path) : onChange(undefined))}
312
+ >
313
+ Remove
314
+ </Button>
315
+ )}
316
+ </div>
317
+ );
318
+ }
319
+
320
+ /** Past this many choices, a select becomes a search (a `Combobox`). */
321
+ const SEARCH_FROM = 10;
322
+ /** A select of `choices` (values as JSON keys), a search past `SEARCH_FROM`; the current value kept when it is not one
323
+ * of them. */
324
+ function ChoiceField({
325
+ choices,
326
+ labels = [],
327
+ value,
328
+ onChange,
329
+ ctx,
330
+ path,
331
+ labelledBy,
332
+ }: {
333
+ choices: unknown[];
334
+ labels?: string[] | undefined;
335
+ value: unknown;
336
+ onChange: (next: unknown) => void;
337
+ ctx: FormContext;
338
+ path: Path;
339
+ labelledBy: string;
340
+ }) {
341
+ const all =
342
+ value === undefined || choices.some((each) => JSON.stringify(each) === JSON.stringify(value))
343
+ ? choices
344
+ : [...choices, value];
345
+ const items = Object.fromEntries(
346
+ all.map((each, at) => [JSON.stringify(each), labels[at] ?? String(each)]),
347
+ );
348
+ // A long list (hundreds of sessions, say) is searched as it is typed: the kit's Combobox, as its guide says.
349
+ if (all.length > SEARCH_FROM) {
350
+ const entries = Object.entries(items);
351
+ const key = value === undefined ? undefined : JSON.stringify(value);
352
+ return (
353
+ <Combobox
354
+ items={entries}
355
+ value={entries.find(([each]) => each === key) ?? null}
356
+ itemToString={([, text]) => text}
357
+ itemToKey={([each]) => each}
358
+ onValueChange={([each]) => onChange(JSON.parse(each))}
359
+ placeholder="Search…"
360
+ size="default"
361
+ disabled={ctx.disabled}
362
+ id={idOf(ctx, path)}
363
+ aria-labelledby={labelledBy}
364
+ aria-invalid={ctx.errorAt(path) !== undefined || undefined}
365
+ className="w-[260px] max-w-full"
366
+ />
367
+ );
368
+ }
369
+ return (
370
+ <Select
371
+ items={items}
372
+ value={value === undefined ? null : JSON.stringify(value)}
373
+ disabled={ctx.disabled}
374
+ onValueChange={(key) => {
375
+ if (key !== null) onChange(JSON.parse(key as string));
376
+ }}
377
+ >
378
+ <SelectTrigger
379
+ id={idOf(ctx, path)}
380
+ size="default"
381
+ aria-labelledby={labelledBy}
382
+ aria-invalid={ctx.errorAt(path) !== undefined || undefined}
383
+ className="w-[260px] max-w-full"
384
+ >
385
+ <SelectValue placeholder="Choose…" />
386
+ </SelectTrigger>
387
+ <SelectContent>
388
+ {Object.entries(items).map(([key, text]) => (
389
+ <SelectItem key={key} value={key}>
390
+ {text}
391
+ </SelectItem>
392
+ ))}
393
+ </SelectContent>
394
+ </Select>
395
+ );
396
+ }
397
+
398
+ /** Tags, with the unused options of `x-bridge-options` offered below. A `route:<path>` kind is a closed list the plugin's
399
+ * route answers, so the chips autocomplete from it and no suggestion row is drawn. */
400
+ function TagsField({
401
+ schema,
402
+ value,
403
+ onChange,
404
+ ctx,
405
+ path,
406
+ labelledBy,
407
+ }: {
408
+ schema: Schema;
409
+ value: unknown;
410
+ onChange: (next: unknown) => void;
411
+ ctx: FormContext;
412
+ path: Path;
413
+ labelledBy: string;
414
+ }) {
415
+ const tags = Array.isArray(value) ? value.map(String) : [];
416
+ // On the items or on the array itself (as the docs allow).
417
+ const kind = schema.items?.['x-bridge-options'] ?? schema['x-bridge-options'];
418
+ const route = kind?.startsWith('route:') === true ? kind : undefined;
419
+ // The route's choices, by the label the route gives them (the value when it gives none).
420
+ const routeOptions =
421
+ route === undefined
422
+ ? undefined
423
+ : ctx.options(route, path).map((value) => {
424
+ const label = ctx.optionLabel?.(route, value);
425
+ return label === undefined ? { value } : { value, label };
426
+ });
427
+ const suggestions =
428
+ kind && route === undefined ? ctx.options(kind).filter((each) => !tags.includes(each)) : [];
429
+ return (
430
+ <div className="flex w-full max-w-[420px] flex-col gap-1.5">
431
+ <TagInput
432
+ id={idOf(ctx, path)}
433
+ aria-labelledby={labelledBy}
434
+ disabled={ctx.disabled}
435
+ placeholder={route !== undefined ? 'Add…' : tags.length ? '' : 'Type and press Enter'}
436
+ options={routeOptions}
437
+ strict={route !== undefined}
438
+ sortable={schema['x-bridge-ordered'] === true}
439
+ value={tags}
440
+ onChange={(next) => onChange(next)}
441
+ />
442
+ {suggestions.length > 0 && !ctx.disabled && (
443
+ <div data-suggestions className="flex flex-wrap items-center gap-1">
444
+ <span className="mr-0.5 text-xs text-muted">Suggestions</span>
445
+ {suggestions.slice(0, 12).map((each) => (
446
+ <button
447
+ key={each}
448
+ type="button"
449
+ aria-label={`Add ${each}`}
450
+ onClick={() => onChange([...tags, each])}
451
+ className="inline-flex h-5 cursor-pointer items-center gap-1 rounded-full border border-dashed border-border bg-transparent px-2 font-[inherit] text-xs text-secondary outline-hidden hover:border-accent hover:text-accent focus-visible:ring-2 focus-visible:ring-accent"
452
+ >
453
+ <Icon name="plus" size={12} />
454
+ {each}
455
+ </button>
456
+ ))}
457
+ </div>
458
+ )}
459
+ </div>
460
+ );
461
+ }
462
+
463
+ /** A closed list of plugins: a pill each, and a + opening a multiple pick menu (no free text). */
464
+ function PluginsField({
465
+ choices,
466
+ value,
467
+ onChange,
468
+ ctx,
469
+ labelledBy,
470
+ }: {
471
+ choices: string[];
472
+ value: unknown;
473
+ onChange: (next: unknown) => void;
474
+ ctx: FormContext;
475
+ labelledBy: string;
476
+ }) {
477
+ const chosen = Array.isArray(value) ? value.map(String) : [];
478
+ const [open, setOpen] = React.useState(false);
479
+ const [anchor, setAnchor] = React.useState<HTMLElement | null>(null);
480
+ const labelOf = (each: string) => ctx.optionLabel?.('plugins', each) ?? each;
481
+ // A saved value outside the choices stays listed, so it shows and can be unchecked.
482
+ const all = [...choices, ...chosen.filter((each) => !choices.includes(each))];
483
+ return (
484
+ <>
485
+ <TagList aria-labelledby={labelledBy}>
486
+ {chosen.map((each) => (
487
+ <TagPill key={each} name={labelOf(each)} />
488
+ ))}
489
+ {!ctx.disabled && (
490
+ <DataMenuTrigger
491
+ ref={setAnchor}
492
+ empty
493
+ aria-label={chosen.length ? 'Change plugins' : 'Add plugin'}
494
+ onClick={() => setOpen(true)}
495
+ >
496
+ <Icon name="plus" size={14} />
497
+ {chosen.length ? null : 'Add plugin'}
498
+ </DataMenuTrigger>
499
+ )}
500
+ </TagList>
501
+ {/* A disabled field (read-only, or an explicit setting committing) takes no pick: its menu closes too. */}
502
+ <PickMenu
503
+ open={open && !ctx.disabled}
504
+ onOpenChange={setOpen}
505
+ anchor={anchor}
506
+ multiple
507
+ aria-label="Plugins"
508
+ placeholder="Search plugins"
509
+ options={all.map((each) => ({
510
+ key: each,
511
+ label: labelOf(each),
512
+ checked: chosen.includes(each),
513
+ }))}
514
+ onPick={(option) =>
515
+ onChange(
516
+ chosen.includes(option.key)
517
+ ? chosen.filter((each) => each !== option.key)
518
+ : [...chosen, option.key],
519
+ )
520
+ }
521
+ />
522
+ </>
523
+ );
524
+ }
525
+
526
+ /** One checkbox per choice, a list of those checked (none: the field's default again). */
527
+ function ChecksField({
528
+ choices,
529
+ labels,
530
+ value,
531
+ onChange,
532
+ ctx,
533
+ labelledBy,
534
+ }: {
535
+ choices: string[];
536
+ labels: string[];
537
+ value: unknown;
538
+ onChange: (next: unknown) => void;
539
+ ctx: FormContext;
540
+ labelledBy: string;
541
+ }) {
542
+ const checked = Array.isArray(value) ? value.map(String) : [];
543
+ return (
544
+ <div
545
+ role="group"
546
+ aria-labelledby={labelledBy}
547
+ className="flex flex-wrap items-center gap-x-4 gap-y-1.5"
548
+ >
549
+ {choices.map((each, at) => (
550
+ <label key={each} className="flex items-center gap-2 text-sm">
551
+ <Checkbox
552
+ aria-label={labels[at]}
553
+ checked={checked.includes(each)}
554
+ disabled={ctx.disabled}
555
+ onCheckedChange={(on) => {
556
+ const next = on ? [...checked, each] : checked.filter((id) => id !== each);
557
+ onChange(next.length ? next : undefined);
558
+ }}
559
+ />
560
+ {labels[at]}
561
+ </label>
562
+ ))}
563
+ </div>
564
+ );
565
+ }
566
+
567
+ /** The values of a field whose choices are the page's (`x-bridge-options`: a style, icons, a window manager, the
568
+ * navigators) that are not among them: proposed, but not installed on this Bridge (research-035). None while the page
569
+ * knows no choice at all (they load). */
570
+ export function missingOptions(
571
+ schema: Schema,
572
+ value: unknown,
573
+ ctx: FormContext,
574
+ path: Path,
575
+ ): string[] {
576
+ const kind =
577
+ schema['x-bridge-options'] ?? (asItems(schema)?.['x-bridge-options'] as string | undefined);
578
+ if (kind === undefined || kind === 'plugins' || kind === 'drivers' || kind === 'modes') return [];
579
+ const choices = ctx.options(kind, path);
580
+ if (!choices.length) return [];
581
+ const values = Array.isArray(value) ? value : value === undefined ? [] : [value];
582
+ return values.filter(
583
+ (each): each is string => typeof each === 'string' && !choices.includes(each),
584
+ );
585
+ }
586
+ const asItems = (schema: Schema) =>
587
+ typeof schema.items === 'object' && schema.items !== null && !Array.isArray(schema.items)
588
+ ? (schema.items as Schema)
589
+ : undefined;
590
+
591
+ /** One control for `schema` at `path`, without its label (the caller draws it); under it, a value proposed but not
592
+ * installed on this Bridge said so (research-035). */
593
+ export function Control(props: {
594
+ schema: Schema;
595
+ value: unknown;
596
+ onChange: (next: unknown) => void;
597
+ ctx: FormContext;
598
+ path: Path;
599
+ label: string;
600
+ labelledBy: string;
601
+ }) {
602
+ const missing = missingOptions(props.schema, props.value, props.ctx, props.path);
603
+ if (!missing.length) return <ControlBody {...props} />;
604
+ return (
605
+ <div className="flex flex-col items-start gap-1.5">
606
+ <ControlBody {...props} />
607
+ <p data-slot="setting-missing" role="note" className="m-0 text-xs text-warning-text">
608
+ {`${missing.join(', ')} ${missing.length > 1 ? 'are' : 'is'} not installed on this Bridge: ${missing.length > 1 ? 'they do' : 'it does'} not apply here.`}
609
+ </p>
610
+ </div>
611
+ );
612
+ }
613
+
614
+ function ControlBody({
615
+ schema,
616
+ value,
617
+ onChange,
618
+ ctx,
619
+ path,
620
+ label: _label,
621
+ labelledBy,
622
+ }: {
623
+ schema: Schema;
624
+ value: unknown;
625
+ onChange: (next: unknown) => void;
626
+ ctx: FormContext;
627
+ path: Path;
628
+ label: string;
629
+ labelledBy: string;
630
+ }) {
631
+ const control = controlOf(schema);
632
+ if (control === 'text' || control === 'number')
633
+ return (
634
+ <TextField
635
+ schema={schema}
636
+ value={value}
637
+ onChange={onChange}
638
+ ctx={ctx}
639
+ path={path}
640
+ number={control === 'number'}
641
+ labelledBy={labelledBy}
642
+ />
643
+ );
644
+ if (control === 'slider')
645
+ return (
646
+ <SliderField
647
+ schema={schema}
648
+ value={value}
649
+ onChange={onChange}
650
+ ctx={ctx}
651
+ path={path}
652
+ labelledBy={labelledBy}
653
+ />
654
+ );
655
+ if (control === 'colour')
656
+ return (
657
+ <ColourField
658
+ schema={schema}
659
+ value={value}
660
+ onChange={onChange}
661
+ ctx={ctx}
662
+ path={path}
663
+ labelledBy={labelledBy}
664
+ />
665
+ );
666
+ if (control === 'colour-pair')
667
+ return (
668
+ <ColourPairField
669
+ schema={schema}
670
+ value={value}
671
+ onChange={onChange}
672
+ ctx={ctx}
673
+ path={path}
674
+ labelledBy={labelledBy}
675
+ />
676
+ );
677
+ if (control === 'image-pair')
678
+ return (
679
+ <ImagePairField
680
+ schema={schema}
681
+ value={value}
682
+ onChange={onChange}
683
+ ctx={ctx}
684
+ path={path}
685
+ labelledBy={labelledBy}
686
+ />
687
+ );
688
+ if (control === 'swatches')
689
+ return (
690
+ <SwatchField
691
+ schema={schema}
692
+ value={value}
693
+ onChange={onChange}
694
+ ctx={ctx}
695
+ path={path}
696
+ labelledBy={labelledBy}
697
+ />
698
+ );
699
+ if (control === 'image')
700
+ return (
701
+ <ImageField
702
+ schema={schema}
703
+ value={value}
704
+ onChange={onChange}
705
+ ctx={ctx}
706
+ path={path}
707
+ labelledBy={labelledBy}
708
+ />
709
+ );
710
+ if (control === 'enum')
711
+ return (
712
+ <ChoiceField
713
+ choices={schema.enum!}
714
+ labels={schema['x-bridge-labels']}
715
+ // A choice left unset takes its default: shown in its place, as a field's.
716
+ value={value ?? schema.default}
717
+ onChange={onChange}
718
+ ctx={ctx}
719
+ path={path}
720
+ labelledBy={labelledBy}
721
+ />
722
+ );
723
+ if (control === 'options') {
724
+ const choices = ctx.options(schema['x-bridge-options']!, path);
725
+ // None, and the schema says why (a model without efforts): a disabled select saying so.
726
+ if (!choices.length && schema['x-bridge-empty'] !== undefined)
727
+ return (
728
+ <Select disabled value={null}>
729
+ <SelectTrigger
730
+ id={idOf(ctx, path)}
731
+ size="default"
732
+ aria-labelledby={labelledBy}
733
+ className="w-[260px] max-w-full"
734
+ >
735
+ <SelectValue placeholder={schema['x-bridge-empty']} />
736
+ </SelectTrigger>
737
+ </Select>
738
+ );
739
+ // None known (yet, or at all): any value can be typed.
740
+ if (!choices.length)
741
+ return (
742
+ <TextField
743
+ schema={schema}
744
+ value={value}
745
+ onChange={onChange}
746
+ ctx={ctx}
747
+ path={path}
748
+ number={false}
749
+ labelledBy={labelledBy}
750
+ />
751
+ );
752
+ const kind = schema['x-bridge-options']!;
753
+ return (
754
+ <ChoiceField
755
+ choices={choices}
756
+ labels={choices.map((each) => ctx.optionLabel?.(kind, each) ?? each)}
757
+ value={value}
758
+ onChange={onChange}
759
+ ctx={ctx}
760
+ path={path}
761
+ labelledBy={labelledBy}
762
+ />
763
+ );
764
+ }
765
+ // A list among the page's own choices (the navigators): one box each, by name; an open list (plugins) stays tags.
766
+ // A route's choices are a closed tags list: TagsField below, never one box each.
767
+ if (control === 'tags') {
768
+ const kind = (schema['x-bridge-options'] ?? asItems(schema)?.['x-bridge-options']) as
769
+ | string
770
+ | undefined;
771
+ const choices =
772
+ kind && !kind.startsWith('route:') && !['plugins', 'drivers', 'modes'].includes(kind)
773
+ ? ctx.options(kind, path)
774
+ : [];
775
+ if (choices.length)
776
+ return (
777
+ <ChecksField
778
+ choices={choices}
779
+ labels={choices.map((each) => ctx.optionLabel?.(kind!, each) ?? each)}
780
+ value={value}
781
+ onChange={onChange}
782
+ ctx={ctx}
783
+ labelledBy={labelledBy}
784
+ />
785
+ );
786
+ }
787
+ if (control === 'tags') {
788
+ const kind = schema['x-bridge-options'] ?? asItems(schema)?.['x-bridge-options'];
789
+ const plugins = kind === 'plugins' ? ctx.options('plugins', path) : [];
790
+ if (plugins.length)
791
+ return (
792
+ <PluginsField
793
+ choices={plugins}
794
+ value={value}
795
+ onChange={onChange}
796
+ ctx={ctx}
797
+ labelledBy={labelledBy}
798
+ />
799
+ );
800
+ }
801
+ if (control === 'tags')
802
+ return (
803
+ <TagsField
804
+ schema={schema}
805
+ value={value}
806
+ onChange={onChange}
807
+ ctx={ctx}
808
+ path={path}
809
+ labelledBy={labelledBy}
810
+ />
811
+ );
812
+ if (control === 'object') {
813
+ const fields = (
814
+ <ObjectFields schema={schema} value={value} onChange={onChange} ctx={ctx} path={path} />
815
+ );
816
+ // A setting that is one object may offer actions on its saved value (not a nested object's).
817
+ const actions = path.length === 0 ? actionsOf(schema) : [];
818
+ if (!actions.length) return fields;
819
+ return (
820
+ <div className="flex flex-col gap-2">
821
+ {fields}
822
+ <ObjectActions actions={actions} value={value} ctx={ctx} />
823
+ </div>
824
+ );
825
+ }
826
+ if (control === 'map')
827
+ return <MapField schema={schema} value={value} onChange={onChange} ctx={ctx} path={path} />;
828
+ if (control === 'list')
829
+ return <ListField schema={schema} value={value} onChange={onChange} ctx={ctx} path={path} />;
830
+ if (control === 'boolean')
831
+ return (
832
+ <Toggle
833
+ id={idOf(ctx, path)}
834
+ aria-labelledby={labelledBy}
835
+ checked={isOn(value, schema)}
836
+ disabled={ctx.disabled}
837
+ onCheckedChange={(on) => onChange(on === true)}
838
+ />
839
+ );
840
+ return <p className="text-xs text-muted">Edit this value in JSON.</p>;
841
+ }
842
+
843
+ /** Whether an object's `value` is marked `"x-bridge-secret": "always"`. */
844
+ const isAlwaysSecret = (schema: Schema | undefined) =>
845
+ isRecord(schema?.properties?.value) && schema.properties.value['x-bridge-secret'] === 'always';
846
+
847
+ /** A boolean as shown: its value, else its schema's default (an entry's `enabled` unset is on). */
848
+ const isOn = (value: unknown, schema: Schema) =>
849
+ typeof value === 'boolean' ? value : schema.default === true;
850
+
851
+ /** Whether a property is shown, given its object's value: always, unless its `x-bridge-shown-if` names a sibling
852
+ * whose value (else its default) is not one of those listed. */
853
+ const shownIn = (sub: Schema, record: Record<string, unknown>, schema: Schema) =>
854
+ Object.entries(sub['x-bridge-shown-if'] ?? {}).every(([field, values]) =>
855
+ values.some((each) => same(each, record[field] ?? schema.properties?.[field]?.default)),
856
+ );
857
+
858
+ /** An object's properties as labelled rows: the label column, then the control, its description, its error. */
859
+ export function ObjectFields({
860
+ schema,
861
+ value,
862
+ onChange,
863
+ ctx,
864
+ path,
865
+ }: {
866
+ schema: Schema;
867
+ value: unknown;
868
+ onChange: (next: unknown) => void;
869
+ ctx: FormContext;
870
+ path: Path;
871
+ }) {
872
+ // `x-bridge-secret: "always"` on its `value`: always a secret, no Sensitive checkbox, `sensitive` written true.
873
+ const always = isAlwaysSecret(schema);
874
+ const record = isRecord(value) ? value : {};
875
+ const required = new Set(schema.required ?? []);
876
+ const set = (key: string, next: unknown) => {
877
+ const { [key]: _, ...rest } = record;
878
+ const changed = next === undefined ? rest : { ...record, [key]: next };
879
+ onChange(always ? { ...changed, sensitive: true } : changed);
880
+ };
881
+ return (
882
+ <div className="flex flex-col">
883
+ {Object.entries(schema.properties ?? {}).map(([key, raw]) => {
884
+ if (always && key === 'sensitive') return null;
885
+ const sub: Schema = isRecord(raw) ? raw : {};
886
+ if (!shownIn(sub, record, schema)) return null;
887
+ const at = [...path, key];
888
+ const control = controlOf(sub);
889
+ const title = titleOf(sub, key);
890
+ const labelId = `${idOf(ctx, at)}-label`;
891
+ const mark = required.has(key) && (
892
+ <span className="ml-0.5 text-destructive" aria-hidden="true">
893
+ *
894
+ </span>
895
+ );
896
+ const error = <FieldMessage message={ctx.errorAt(at)} />;
897
+ const description = sub.description && (
898
+ <p className="text-xs leading-[18px] text-muted">
899
+ <Marked text={sub.description} needle={ctx.needle} />
900
+ </p>
901
+ );
902
+ const nested = control === 'object' || control === 'map' || control === 'list';
903
+ if (nested) {
904
+ return (
905
+ <fieldset
906
+ key={key}
907
+ data-subfield={key}
908
+ className="m-0 mt-1 flex min-w-0 flex-col gap-1 border-0 p-0 py-2"
909
+ >
910
+ <legend id={labelId} className="p-0 text-[13px] font-medium text-foreground">
911
+ <Marked text={title} needle={ctx.needle} />
912
+ {mark}
913
+ </legend>
914
+ {description}
915
+ <div className="mt-1 border-l border-border-subtle pl-4">
916
+ <Control
917
+ schema={sub}
918
+ value={record[key]}
919
+ onChange={(next) => set(key, next)}
920
+ ctx={ctx}
921
+ path={at}
922
+ label={title}
923
+ labelledBy={labelId}
924
+ />
925
+ </div>
926
+ {error}
927
+ </fieldset>
928
+ );
929
+ }
930
+ if (
931
+ (sub['x-bridge-secret'] === true && record.sensitive === true) ||
932
+ (always && key === 'value')
933
+ ) {
934
+ return (
935
+ <div
936
+ key={key}
937
+ data-subfield={key}
938
+ className="grid grid-cols-[140px_minmax(0,1fr)] items-start gap-x-4 py-1.5"
939
+ >
940
+ <label
941
+ id={labelId}
942
+ htmlFor={idOf(ctx, at)}
943
+ className="truncate pt-[7px] text-[13px] text-secondary"
944
+ title={title}
945
+ >
946
+ <Marked text={title} needle={ctx.needle} />
947
+ {mark}
948
+ </label>
949
+ <div className="flex min-w-0 flex-col gap-1">
950
+ <SecretField
951
+ value={record[key]}
952
+ onChange={(next) => set(key, next)}
953
+ ctx={ctx}
954
+ path={at}
955
+ labelledBy={labelId}
956
+ />
957
+ {description}
958
+ {error}
959
+ </div>
960
+ </div>
961
+ );
962
+ }
963
+ if (control === 'boolean') {
964
+ return (
965
+ <div
966
+ key={key}
967
+ data-subfield={key}
968
+ className="grid grid-cols-[140px_minmax(0,1fr)] items-start gap-x-4 py-1.5"
969
+ >
970
+ <span />
971
+ <div className="flex flex-col gap-1">
972
+ <label className="flex cursor-pointer items-start gap-2 text-[13px] text-foreground">
973
+ <Toggle
974
+ id={idOf(ctx, at)}
975
+ aria-labelledby={labelId}
976
+ className="mt-0.5 shrink-0"
977
+ checked={isOn(record[key], sub)}
978
+ disabled={ctx.disabled}
979
+ onCheckedChange={(on) => set(key, on === true)}
980
+ />
981
+ <span id={labelId}>
982
+ <Marked text={title} needle={ctx.needle} />
983
+ {mark}
984
+ </span>
985
+ </label>
986
+ {description}
987
+ {error}
988
+ </div>
989
+ </div>
990
+ );
991
+ }
992
+ return (
993
+ <div
994
+ key={key}
995
+ data-subfield={key}
996
+ className="grid grid-cols-[140px_minmax(0,1fr)] items-start gap-x-4 py-1.5"
997
+ >
998
+ <label
999
+ id={labelId}
1000
+ htmlFor={idOf(ctx, at)}
1001
+ className="truncate pt-[7px] text-[13px] text-secondary"
1002
+ title={title}
1003
+ >
1004
+ <Marked text={title} needle={ctx.needle} />
1005
+ {mark}
1006
+ </label>
1007
+ <div className="flex min-w-0 flex-col gap-1">
1008
+ <Control
1009
+ schema={sub}
1010
+ value={record[key]}
1011
+ onChange={(next) => set(key, next)}
1012
+ ctx={ctx}
1013
+ path={at}
1014
+ label={title}
1015
+ labelledBy={labelId}
1016
+ />
1017
+ {description}
1018
+ {error}
1019
+ </div>
1020
+ </div>
1021
+ );
1022
+ })}
1023
+ </div>
1024
+ );
1025
+ }
1026
+
1027
+ /** A card: a header (chevron, title, actions) and, open, its body. */
1028
+ function EntryCard({
1029
+ title,
1030
+ subtitle,
1031
+ open,
1032
+ onToggle,
1033
+ actions,
1034
+ notice,
1035
+ children,
1036
+ entry,
1037
+ }: {
1038
+ title: React.ReactNode;
1039
+ subtitle?: string;
1040
+ open: boolean;
1041
+ onToggle: () => void;
1042
+ actions: React.ReactNode;
1043
+ /** A line under the header, open or not (an action's answer). */
1044
+ notice?: React.ReactNode;
1045
+ children: React.ReactNode;
1046
+ entry: string;
1047
+ }) {
1048
+ return (
1049
+ <Card data-entry={entry} className="overflow-hidden p-0">
1050
+ <div
1051
+ className={cn(
1052
+ 'flex h-9 items-center gap-1 pl-1 pr-1.5',
1053
+ open && 'border-b border-border-subtle',
1054
+ )}
1055
+ >
1056
+ <Button
1057
+ type="button"
1058
+ aria-expanded={open}
1059
+ onClick={onToggle}
1060
+ className="min-w-0 flex-1 justify-start gap-1.5 text-left font-normal"
1061
+ >
1062
+ <Icon
1063
+ name="chevron-right"
1064
+ size={14}
1065
+ className={cn('text-muted transition-transform', open && 'rotate-90')}
1066
+ />
1067
+ <span className="truncate font-mono text-[13px] font-medium text-foreground">
1068
+ {title}
1069
+ </span>
1070
+ {!open && subtitle && <span className="truncate text-xs text-muted">{subtitle}</span>}
1071
+ </Button>
1072
+ <div className="flex shrink-0 items-center gap-0.5">{actions}</div>
1073
+ </div>
1074
+ {notice}
1075
+ {open && <div className="px-3 py-2">{children}</div>}
1076
+ </Card>
1077
+ );
1078
+ }
1079
+
1080
+ /** A card's subtitle: its first two strings (an enum's by its `x-bridge-labels` label, given the item's schema), a
1081
+ * sensitive entry's `value` and secret markers left out. */
1082
+ export const subtitleOf = (value: unknown, schema?: Schema) =>
1083
+ isRecord(value)
1084
+ ? Object.entries(value)
1085
+ .filter(
1086
+ ([key, each]) =>
1087
+ typeof each === 'string' &&
1088
+ !isSecretMarker(each) &&
1089
+ !(key === 'value' && (value.sensitive === true || isAlwaysSecret(schema))),
1090
+ )
1091
+ .map(([key, each]) => {
1092
+ const field = isRecord(schema?.properties)
1093
+ ? (schema.properties[key] as Schema | undefined)
1094
+ : undefined;
1095
+ const at = Array.isArray(field?.enum) ? field.enum.indexOf(each) : -1;
1096
+ return (at >= 0 ? field?.['x-bridge-labels']?.[at] : undefined) ?? (each as string);
1097
+ })
1098
+ .slice(0, 2)
1099
+ .join(' · ')
1100
+ : '';
1101
+
1102
+ /** A name asked inline (adding or renaming a map entry): Enter or the button confirms, Escape cancels. */
1103
+ function NameInput({
1104
+ label,
1105
+ initial,
1106
+ confirm,
1107
+ onConfirm,
1108
+ onCancel,
1109
+ error,
1110
+ }: {
1111
+ label: string;
1112
+ initial: string;
1113
+ confirm: string;
1114
+ onConfirm: (name: string) => void;
1115
+ onCancel: () => void;
1116
+ error: string | undefined;
1117
+ }) {
1118
+ const [name, setName] = React.useState(initial);
1119
+ // Labelled by id: inside the setting's Field, an `aria-label` loses to the Field's label.
1120
+ const labelId = React.useId();
1121
+ return (
1122
+ <div className="flex flex-col gap-1">
1123
+ <span id={labelId} className="sr-only">
1124
+ {label}
1125
+ </span>
1126
+ <div className="flex items-center gap-1.5">
1127
+ <Input
1128
+ variant="outline"
1129
+ size="sm"
1130
+ autoFocus
1131
+ aria-labelledby={labelId}
1132
+ aria-invalid={error !== undefined || undefined}
1133
+ className="w-56 font-mono"
1134
+ value={name}
1135
+ onChange={(event) => setName(event.currentTarget.value)}
1136
+ onKeyDown={(event) => {
1137
+ if (event.key === 'Enter' && !isComposing(event)) {
1138
+ event.preventDefault();
1139
+ onConfirm(name);
1140
+ } else if (event.key === 'Escape') onCancel();
1141
+ }}
1142
+ />
1143
+ <Button size="sm" variant="primary" onClick={() => onConfirm(name)}>
1144
+ {confirm}
1145
+ </Button>
1146
+ <Button size="sm" onClick={onCancel}>
1147
+ Cancel
1148
+ </Button>
1149
+ </div>
1150
+ <FieldMessage message={error} />
1151
+ </div>
1152
+ );
1153
+ }
1154
+
1155
+ /** A map: one card per entry (rename, remove), then "Add <title>". */
1156
+ function MapField({
1157
+ schema,
1158
+ value,
1159
+ onChange,
1160
+ ctx,
1161
+ path,
1162
+ }: {
1163
+ schema: Schema;
1164
+ value: unknown;
1165
+ onChange: (next: unknown) => void;
1166
+ ctx: FormContext;
1167
+ path: Path;
1168
+ }) {
1169
+ const record = isRecord(value) ? value : {};
1170
+ const item: Schema = isRecord(schema.additionalProperties) ? schema.additionalProperties : {};
1171
+ const noun = item.title ?? 'entry';
1172
+ const keys = Object.keys(record);
1173
+ const [open, setOpen] = React.useState<ReadonlySet<string>>(() => new Set(keys.slice(0, 1)));
1174
+ /** The entry being renamed, or `''` while adding one. */
1175
+ const [naming, setNaming] = React.useState<string>();
1176
+ const [nameError, setNameError] = React.useState<string>();
1177
+ const toggle = (key: string) =>
1178
+ setOpen((was) => {
1179
+ const next = new Set(was);
1180
+ if (!next.delete(key)) next.add(key);
1181
+ return next;
1182
+ });
1183
+ const closeName = () => {
1184
+ setNaming(undefined);
1185
+ setNameError(undefined);
1186
+ };
1187
+ const named = (name: string) => {
1188
+ const error = checkName(
1189
+ name,
1190
+ keys.filter((key) => key !== naming),
1191
+ );
1192
+ if (error) return setNameError(error);
1193
+ const trimmed = name.trim();
1194
+ if (naming === '') onChange({ ...record, [trimmed]: {} });
1195
+ else if (naming !== trimmed) onChange(renameKey(record, naming!, trimmed));
1196
+ setOpen((was) => new Set([...[...was].filter((key) => key !== naming), trimmed]));
1197
+ closeName();
1198
+ };
1199
+ return (
1200
+ <div className="flex flex-col gap-2">
1201
+ {keys.length === 0 && <p className="text-xs text-muted">None yet.</p>}
1202
+ {keys.map((key) =>
1203
+ naming === key ? (
1204
+ <NameInput
1205
+ key={key}
1206
+ label={`New name for ${key}`}
1207
+ initial={key}
1208
+ confirm="Rename"
1209
+ onConfirm={named}
1210
+ onCancel={closeName}
1211
+ error={nameError}
1212
+ />
1213
+ ) : (
1214
+ <EntryCard
1215
+ key={key}
1216
+ entry={key}
1217
+ title={<Marked text={key} needle={ctx.needle} />}
1218
+ subtitle={subtitleOf(record[key], item)}
1219
+ open={open.has(key)}
1220
+ onToggle={() => toggle(key)}
1221
+ actions={
1222
+ !ctx.disabled && (
1223
+ <>
1224
+ <IconButton
1225
+ label={`Rename ${key}`}
1226
+ icon="pen-line"
1227
+ onClick={() => {
1228
+ setNameError(undefined);
1229
+ setNaming(key);
1230
+ }}
1231
+ />
1232
+ <IconButton
1233
+ label={`Remove ${key}`}
1234
+ icon="trash"
1235
+ onClick={() => {
1236
+ const { [key]: _, ...rest } = record;
1237
+ onChange(rest);
1238
+ }}
1239
+ />
1240
+ </>
1241
+ )
1242
+ }
1243
+ >
1244
+ <EntryBody
1245
+ schema={item}
1246
+ value={record[key]}
1247
+ onChange={(next) => onChange({ ...record, [key]: next })}
1248
+ ctx={ctx}
1249
+ path={[...path, key]}
1250
+ />
1251
+ </EntryCard>
1252
+ ),
1253
+ )}
1254
+ {naming === '' ? (
1255
+ <NameInput
1256
+ label={`${noun} name`}
1257
+ initial=""
1258
+ confirm="Add"
1259
+ onConfirm={named}
1260
+ onCancel={closeName}
1261
+ error={nameError}
1262
+ />
1263
+ ) : (
1264
+ !ctx.disabled && (
1265
+ <div>
1266
+ <Button
1267
+ size="sm"
1268
+ variant="outline"
1269
+ onClick={() => {
1270
+ setNameError(undefined);
1271
+ setNaming('');
1272
+ }}
1273
+ >
1274
+ <Icon name="plus" size={14} />
1275
+ Add {noun}
1276
+ </Button>
1277
+ </div>
1278
+ )
1279
+ )}
1280
+ </div>
1281
+ );
1282
+ }
1283
+
1284
+ /** A card's body: an object's sub-fields, or the item's own control. */
1285
+ function EntryBody({
1286
+ schema,
1287
+ value,
1288
+ onChange,
1289
+ ctx,
1290
+ path,
1291
+ }: {
1292
+ schema: Schema;
1293
+ value: unknown;
1294
+ onChange: (next: unknown) => void;
1295
+ ctx: FormContext;
1296
+ path: Path;
1297
+ }) {
1298
+ if (controlOf(schema) === 'object')
1299
+ return <ObjectFields schema={schema} value={value} onChange={onChange} ctx={ctx} path={path} />;
1300
+ const labelId = `${idOf(ctx, path)}-label`;
1301
+ return (
1302
+ <div className="flex flex-col gap-1 py-1">
1303
+ <span id={labelId} className="sr-only">
1304
+ {schema.title ?? 'Value'}
1305
+ </span>
1306
+ <Control
1307
+ schema={schema}
1308
+ value={value}
1309
+ onChange={onChange}
1310
+ ctx={ctx}
1311
+ path={path}
1312
+ label={schema.title ?? 'Value'}
1313
+ labelledBy={labelId}
1314
+ />
1315
+ <FieldMessage message={ctx.errorAt(path)} />
1316
+ </div>
1317
+ );
1318
+ }
1319
+
1320
+ /** An action run's outcome, with the value it ran on: its answer is shown only while that value is still the one. */
1321
+ type ActionOutcome = { entry: string; running: boolean; result?: ActionResult };
1322
+
1323
+ /** An action's answer's key: two actions may post to the same route (Test, Test and save). */
1324
+ const keyOf = (action: SettingAction) => `${action.path} ${action.label}`;
1325
+ const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
1326
+ /** A secret's marker, as the host writes it (`[secret:<workspace>/<id>]`). */
1327
+ const secretMarker = /^\[secret:[a-z0-9_][a-z0-9_-]*\/[A-Za-z0-9_-]{8,64}\]$/;
1328
+ /** `value` with each sensitive entry's typed value (an object's `value`, `sensitive: true`, not a marker yet) replaced by
1329
+ * a draft secret's marker, as the host stores a saved one: what a draft is tested with. */
1330
+ const withDraftSecrets = async (
1331
+ value: unknown,
1332
+ draftSecret: (value: string) => Promise<string>,
1333
+ ): Promise<unknown> => {
1334
+ if (Array.isArray(value))
1335
+ return Promise.all(value.map((each: unknown) => withDraftSecrets(each, draftSecret)));
1336
+ if (!isRecord(value)) return value;
1337
+ const next: Record<string, unknown> = {};
1338
+ for (const [key, field] of Object.entries(value))
1339
+ next[key] = await withDraftSecrets(field, draftSecret);
1340
+ if (
1341
+ next.sensitive === true &&
1342
+ typeof next.value === 'string' &&
1343
+ next.value !== '' &&
1344
+ !secretMarker.test(next.value)
1345
+ )
1346
+ next.value = await draftSecret(next.value);
1347
+ return next;
1348
+ };
1349
+
1350
+ /** The buttons of an `x-bridge-action` on a setting that is one object: each posts the saved value to the plugin's route
1351
+ * and shows its own answer; they wait, disabled, while the value differs from the saved one, but a `save: true` action
1352
+ * commits the draft first and then posts no entry. An explicit setting's draft can be cancelled. */
1353
+ function ObjectActions({
1354
+ actions,
1355
+ value,
1356
+ ctx,
1357
+ }: {
1358
+ actions: SettingAction[];
1359
+ value: unknown;
1360
+ ctx: FormContext;
1361
+ }) {
1362
+ const [outcomes, setOutcomes] = React.useState<Record<string, ActionOutcome>>({});
1363
+ const runAction = ctx.runAction;
1364
+ const entry = JSON.stringify(value);
1365
+ /** The run in flight, by number: a Cancel, an edit, a newer run or the form's end make its answer stale, and a stale
1366
+ * Test and save saves nothing (the draft it tested is no longer the one on screen). */
1367
+ const generation = React.useRef(0);
1368
+ React.useEffect(() => {
1369
+ generation.current++;
1370
+ }, [entry]);
1371
+ React.useEffect(
1372
+ () => () => {
1373
+ generation.current++;
1374
+ },
1375
+ [],
1376
+ );
1377
+ if (!runAction) return null;
1378
+ const saved = ctx.saved;
1379
+ const unsaved = saved === undefined || !same(value, saved);
1380
+ /** The actions that only use the saved value (not a Test or a Test and save of an explicit setting). */
1381
+ const waiting = actions.filter(
1382
+ (action) => !(action.draft === true || (action.save === true && ctx.commit)),
1383
+ );
1384
+ const run = (action: SettingAction) => {
1385
+ const commit = action.save === true ? ctx.commit : undefined;
1386
+ if (!commit && !action.draft && unsaved) return;
1387
+ const mine = ++generation.current;
1388
+ const answered = (result: ActionResult) =>
1389
+ setOutcomes((was) => ({ ...was, [keyOf(action)]: { entry, running: false, result } }));
1390
+ const unanswered = () => answered({ ok: false, error: 'The action did not answer.' });
1391
+ setOutcomes((was) => ({ ...was, [keyOf(action)]: { entry, running: true } }));
1392
+ // Test: the draft as it is typed (its secrets as draft secrets), never saved; nothing edited, the saved setting.
1393
+ if (action.draft === true && !commit) {
1394
+ if (!unsaved) {
1395
+ runAction(action, undefined).then(answered, unanswered);
1396
+ return;
1397
+ }
1398
+ const draftSecret = ctx.draftSecret;
1399
+ void (async () =>
1400
+ answered(
1401
+ await runAction(action, draftSecret ? await withDraftSecrets(value, draftSecret) : value),
1402
+ ))().catch(unanswered);
1403
+ return;
1404
+ }
1405
+ if (commit) {
1406
+ // Nothing edited: the saved setting is tested (no entry). Edited: the draft is tested, each sensitive value as a
1407
+ // draft secret's marker, and saved only once the answer is ok (Test and save).
1408
+ if (!unsaved) {
1409
+ runAction(action, undefined).then(answered, unanswered);
1410
+ return;
1411
+ }
1412
+ const draftSecret = ctx.draftSecret;
1413
+ void (async () => {
1414
+ const result = await runAction(
1415
+ action,
1416
+ draftSecret ? await withDraftSecrets(value, draftSecret) : value,
1417
+ );
1418
+ answered(result);
1419
+ if (!result.ok || generation.current !== mine) return;
1420
+ const refusal = await commit();
1421
+ if (refusal)
1422
+ setOutcomes((was) => {
1423
+ const { [keyOf(action)]: _, ...rest } = was;
1424
+ return rest;
1425
+ });
1426
+ })().catch(unanswered);
1427
+ return;
1428
+ }
1429
+ runAction(action, saved).then(answered, unanswered);
1430
+ };
1431
+ return (
1432
+ <div className="flex flex-col gap-1.5">
1433
+ <div className="flex flex-wrap items-center justify-end gap-1.5">
1434
+ {unsaved && ctx.discard && (
1435
+ <Button
1436
+ size="sm"
1437
+ variant="ghost"
1438
+ onClick={() => {
1439
+ generation.current++;
1440
+ ctx.discard?.();
1441
+ }}
1442
+ >
1443
+ Cancel
1444
+ </Button>
1445
+ )}
1446
+ {actions.map((action) => {
1447
+ const outcome = outcomes[keyOf(action)];
1448
+ const commit = action.save === true || action.draft === true ? true : undefined;
1449
+ return (
1450
+ <Button
1451
+ key={`${action.path} ${action.label}`}
1452
+ size="sm"
1453
+ variant="outline"
1454
+ data-action
1455
+ disabled={ctx.disabled || (!commit && unsaved) || outcome?.running === true}
1456
+ title={!commit && unsaved ? 'Save the setting first' : undefined}
1457
+ onClick={() => run(action)}
1458
+ >
1459
+ {action.label}
1460
+ </Button>
1461
+ );
1462
+ })}
1463
+ </div>
1464
+ {unsaved && waiting.length > 0 && (
1465
+ <p data-action-hint className="text-xs text-muted">
1466
+ {waiting.length === actions.length
1467
+ ? 'Save first: the buttons use the saved value.'
1468
+ : `Save first: ${waiting.map(({ label }) => label).join(', ')} ${waiting.length === 1 ? 'uses' : 'use'} the saved value.`}
1469
+ </p>
1470
+ )}
1471
+ {actions.map((action) => {
1472
+ const outcome = outcomes[keyOf(action)];
1473
+ if (!outcome) return null;
1474
+ const saves = action.save === true;
1475
+ // A save action's answer is for the value it just saved: stale once another draft is edited.
1476
+ if (saves && outcome.entry !== entry && unsaved) return null;
1477
+ return (
1478
+ <React.Fragment key={`${action.path} ${action.label}`}>
1479
+ {noticeOf(outcome, entry, false, saves)}
1480
+ </React.Fragment>
1481
+ );
1482
+ })}
1483
+ </div>
1484
+ );
1485
+ }
1486
+
1487
+ /** The line under a card for its action: running, the answer (success, or the error with its fix), or, for an entry
1488
+ * not saved yet, why the button waits. An answer of an earlier version of the entry is not shown, unless `saved`
1489
+ * (an action that saved the draft it ran on). */
1490
+ function noticeOf(
1491
+ outcome: ActionOutcome | undefined,
1492
+ entry: string,
1493
+ unsaved: boolean,
1494
+ saved = false,
1495
+ ) {
1496
+ if (unsaved)
1497
+ return (
1498
+ <p data-action-hint className="border-b border-border-subtle px-3 py-1.5 text-xs text-muted">
1499
+ Save first: the test uses the saved entry.
1500
+ </p>
1501
+ );
1502
+ if (!outcome || (!saved && outcome.entry !== entry)) return null;
1503
+ if (outcome.running)
1504
+ return (
1505
+ <p role="status" className="border-b border-border-subtle px-3 py-1.5 text-xs text-muted">
1506
+ Working…
1507
+ </p>
1508
+ );
1509
+ const { result } = outcome;
1510
+ if (!result) return null;
1511
+ return result.ok ? (
1512
+ <p
1513
+ role="status"
1514
+ data-action-ok
1515
+ className="border-b border-border-subtle px-3 py-1.5 text-xs text-success"
1516
+ >
1517
+ {result.message ?? 'It worked.'}
1518
+ </p>
1519
+ ) : (
1520
+ <div
1521
+ role="alert"
1522
+ data-action-error
1523
+ className="border-b border-border-subtle px-3 py-1.5 text-xs"
1524
+ >
1525
+ <p className="text-danger">{result.error}</p>
1526
+ {result.hint && <p className="text-muted">{result.hint}</p>}
1527
+ </div>
1528
+ );
1529
+ }
1530
+
1531
+ /** An array of objects: one card per item (move up or down, remove), then "Add <title>". */
1532
+ function ListField({
1533
+ schema,
1534
+ value,
1535
+ onChange,
1536
+ ctx,
1537
+ path,
1538
+ }: {
1539
+ schema: Schema;
1540
+ value: unknown;
1541
+ onChange: (next: unknown) => void;
1542
+ ctx: FormContext;
1543
+ path: Path;
1544
+ }) {
1545
+ const list: unknown[] = Array.isArray(value) ? value : [];
1546
+ const item: Schema = isRecord(schema.items) ? schema.items : {};
1547
+ const noun = item.title ?? 'item';
1548
+ const [open, setOpen] = React.useState<ReadonlySet<number>>(() => new Set([0]));
1549
+ // Only a top-level list has its saved entries at hand to compare with.
1550
+ const action = path.length === 0 ? singleActionOf(item) : undefined;
1551
+ const saved: unknown[] = Array.isArray(ctx.saved) ? ctx.saved : [];
1552
+ /** An action's outcome by entry, with the entry it ran on: shown only while the entry is that one. */
1553
+ const [outcomes, setOutcomes] = React.useState<Record<number, ActionOutcome>>({});
1554
+ const run = (index: number, entry: unknown) => {
1555
+ if (!action || !ctx.runAction) return;
1556
+ const key = JSON.stringify(entry);
1557
+ setOutcomes((was) => ({ ...was, [index]: { entry: key, running: true } }));
1558
+ ctx.runAction(action, entry).then(
1559
+ (result) =>
1560
+ setOutcomes((was) => ({ ...was, [index]: { entry: key, running: false, result } })),
1561
+ () =>
1562
+ setOutcomes((was) => ({
1563
+ ...was,
1564
+ [index]: {
1565
+ entry: key,
1566
+ running: false,
1567
+ result: { ok: false, error: 'The action did not answer.' },
1568
+ },
1569
+ })),
1570
+ );
1571
+ };
1572
+ const move = (from: number, to: number) => {
1573
+ const next = [...list];
1574
+ next.splice(to, 0, ...next.splice(from, 1));
1575
+ onChange(next);
1576
+ setOpen(
1577
+ (was) =>
1578
+ new Set([...was].map((index) => (index === from ? to : index === to ? from : index))),
1579
+ );
1580
+ };
1581
+ return (
1582
+ <div className="flex flex-col gap-2">
1583
+ {list.length === 0 && <p className="text-xs text-muted">None yet.</p>}
1584
+ {list.map((each, index) => (
1585
+ <EntryCard
1586
+ key={index}
1587
+ entry={String(index)}
1588
+ title={`${noun} ${index + 1}`}
1589
+ subtitle={subtitleOf(each, item)}
1590
+ open={open.has(index)}
1591
+ onToggle={() =>
1592
+ setOpen((was) => {
1593
+ const next = new Set(was);
1594
+ if (!next.delete(index)) next.add(index);
1595
+ return next;
1596
+ })
1597
+ }
1598
+ notice={noticeOf(
1599
+ action && ctx.runAction ? outcomes[index] : undefined,
1600
+ JSON.stringify(each),
1601
+ action !== undefined && ctx.runAction !== undefined && !same(each, saved[index]),
1602
+ )}
1603
+ actions={
1604
+ <>
1605
+ {action && ctx.runAction && (
1606
+ <Button
1607
+ size="sm"
1608
+ variant="outline"
1609
+ data-action
1610
+ disabled={
1611
+ ctx.disabled || outcomes[index]?.running === true || !same(each, saved[index])
1612
+ }
1613
+ title={same(each, saved[index]) ? undefined : 'Save the entry first'}
1614
+ onClick={() => run(index, each)}
1615
+ >
1616
+ {action.label}
1617
+ </Button>
1618
+ )}
1619
+ {!ctx.disabled && (
1620
+ <>
1621
+ <IconButton
1622
+ label={`Move ${noun} ${index + 1} up`}
1623
+ icon="arrow-up"
1624
+ disabled={index === 0}
1625
+ onClick={() => move(index, index - 1)}
1626
+ />
1627
+ <IconButton
1628
+ label={`Move ${noun} ${index + 1} down`}
1629
+ icon="arrow-down"
1630
+ disabled={index === list.length - 1}
1631
+ onClick={() => move(index, index + 1)}
1632
+ />
1633
+ <IconButton
1634
+ label={`Remove ${noun} ${index + 1}`}
1635
+ icon="trash"
1636
+ onClick={() => onChange(list.filter((_, at) => at !== index))}
1637
+ />
1638
+ </>
1639
+ )}
1640
+ </>
1641
+ }
1642
+ >
1643
+ <EntryBody
1644
+ schema={item}
1645
+ value={each}
1646
+ onChange={(next) => onChange(list.map((was, at) => (at === index ? next : was)))}
1647
+ ctx={ctx}
1648
+ path={[...path, index]}
1649
+ />
1650
+ </EntryCard>
1651
+ ))}
1652
+ {!ctx.disabled && (
1653
+ <div>
1654
+ <Button
1655
+ size="sm"
1656
+ variant="outline"
1657
+ onClick={() => {
1658
+ onChange([...list, {}]);
1659
+ setOpen((was) => new Set([...was, list.length]));
1660
+ }}
1661
+ >
1662
+ <Icon name="plus" size={14} />
1663
+ Add {noun}
1664
+ </Button>
1665
+ </div>
1666
+ )}
1667
+ </div>
1668
+ );
1669
+ }