-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathwidgets.tsx
More file actions
2042 lines (1922 loc) · 78.9 KB
/
Copy pathwidgets.tsx
File metadata and controls
2042 lines (1922 loc) · 78.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* Built-in widget renderers for SchemaForm.
*
* These cover the common widget hints declared in spec `*.form.ts`
* files (e.g. `widget: 'ref:object'`, `widget: 'master-detail'`).
*
* Each widget receives `WidgetProps`:
* - schema — the JSONSchema fragment for THIS field (so widgets
* for nested arrays can read items.properties)
* - value — the current value
* - onChange — write-back callback
* - readOnly — disable
* - context — out-of-band data (object list, ObjectQL fields, …)
*
* To register a new widget, add an entry to `WIDGETS` below. To wire
* extra context (e.g. a fields list), extend `WidgetContext` in
* SchemaForm.tsx and prefetch it in ResourceEditPage.
*/
import * as React from 'react';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
Input,
Button,
Label,
Switch,
LazyIcon,
toKebabIconName,
Popover,
PopoverTrigger,
PopoverContent,
FilterBuilder,
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@object-ui/components';
import { ChevronDown, ChevronsUpDown, ChevronUp, Eye, EyeOff, Plus, Search, Trash2 } from 'lucide-react';
import { iconNames } from 'lucide-react/dynamic.mjs';
import { useMetadataLocale, t, tFormat } from './i18n';
import { ColorVariantPicker } from './color-variant-field';
import { ConditionBuilder } from './inspectors/ConditionBuilder';
export interface WidgetContext {
/** Names of all object metadata records (for `ref:object`). */
objectNames?: string[];
/** Loading flag for the object list. */
objectsLoading?: boolean;
/**
* Field catalog of the bound object. Drives the `field-ref` /
* `field-multi` pickers so View config props that reference a field
* (kanban.groupByField, calendar.startDateField, chart.xAxisField, …)
* render as dropdowns of the object's real fields instead of free text.
*/
objectFields?: Array<{ name: string; label?: string; type?: string }>;
/** Loading flag for the field catalog. */
objectFieldsLoading?: boolean;
/**
* View catalog of the bound/source object. Drives the `view-ref` picker
* so `interfaceConfig.sourceView` renders as a dropdown of the source
* object's real views instead of a free-text name the author can typo.
*/
objectViews?: Array<{ name: string; label?: string }>;
/** Loading flag for the view catalog. */
objectViewsLoading?: boolean;
/**
* Action catalog of the bound/source object. Drives the `action-multi`
* picker so interface-page toolbar `buttons` reference the object's real
* actions (ActionSchema) instead of free-text — correct-by-construction.
*/
objectActions?: Array<{ name: string; label?: string; locations?: string[] }>;
/** Loading flag for the action catalog. */
objectActionsLoading?: boolean;
/**
* Per-value sub-schemas for the `dynamic-config` widget: a map from a parent
* field's value (e.g. the chosen driver id) to the JSON-Schema describing the
* config object for that value. Lets a single `config` field render different
* fields depending on a sibling selection (driver → connection settings).
*/
dynamicSchemas?: Record<string, { properties?: Record<string, any>; required?: string[] }>;
/**
* Component ids placed on the page being edited — extracted from the draft's
* `regions[].components[]` tree (see {@link collectPageComponentIds}). Drives
* the `ref:component` picker so a page variable's `source` (the component that
* writes it) is chosen from the real components on the canvas instead of a
* free-text id the author can typo.
*/
componentIds?: Array<{ id: string; type?: string; label?: string }>;
}
export interface WidgetProps {
id?: string;
schema: Record<string, any>;
value: unknown;
onChange: (v: unknown) => void;
readOnly?: boolean;
context?: WidgetContext;
/** Optional FormFieldSpec with type/options/reference/constraints */
fieldSpec?: {
field: string;
type?: string;
options?: Array<{ label: string; value: string; color?: string }>;
reference?: string;
maxLength?: number;
minLength?: number;
min?: number;
max?: number;
multiple?: boolean;
dependsOn?: string | string[]; // NEW: field name(s) this widget depends on
/** Sub-fields for `composite` / `repeater` types */
fields?: Array<any>;
/** Code editor language (for type=code) */
language?: string;
/** Form-level helpers passed through from FormField */
label?: string;
placeholder?: string;
helpText?: string;
widget?: string;
colSpan?: number;
immutable?: boolean;
readonly?: boolean;
required?: boolean;
};
/** All form data (for reading dependency values) */
formData?: Record<string, unknown>;
}
export type WidgetRenderer = (props: WidgetProps) => React.ReactElement;
/* -------------------------------------------------------------------------- */
/* ref:object — pick an object by name */
/* -------------------------------------------------------------------------- */
function RefObjectWidget({
id,
value,
onChange,
readOnly,
context,
}: WidgetProps) {
const locale = useMetadataLocale();
const names = context?.objectNames ?? [];
const v = value == null ? '' : String(value);
if (context?.objectsLoading) {
return (
<Input
id={id}
value={v}
disabled
placeholder={t('engine.form.loadingObjects', locale)}
/>
);
}
// If list is empty (e.g. no objects defined yet), fall back to a
// freeform text input so the user can still type a value.
if (names.length === 0) {
return (
<Input
id={id}
value={v}
disabled={readOnly}
onChange={(e) => onChange(e.target.value || undefined)}
placeholder={t('engine.form.noObjects', locale)}
/>
);
}
return (
<Select
value={v}
onValueChange={(next) => onChange(next || undefined)}
disabled={readOnly}
>
<SelectTrigger id={id}>
<SelectValue placeholder={t('engine.form.selectObject', locale)} />
</SelectTrigger>
<SelectContent>
{names.map((n) => (
<SelectItem key={n} value={n}>
{n}
</SelectItem>
))}
</SelectContent>
</Select>
);
}
/* -------------------------------------------------------------------------- */
/* ref:component — pick a component id from the page's canvas tree */
/* -------------------------------------------------------------------------- */
/**
* Walk a page draft's `regions[].components[]` tree and collect every component
* that carries an `id`, returning `{ id, type, label }` in document order (and
* de-duplicated on id, first-wins). Traverses nested containers via any array-
* valued `components` / `children` under a node or its `properties`, so ids
* inside `page:tabs` / `page:section` style containers are surfaced too.
*
* Used to fuel the `ref:component` picker (a page variable's `source` names the
* component that writes it). Exported for unit testing.
*/
export function collectPageComponentIds(
draft: unknown,
): Array<{ id: string; type?: string; label?: string }> {
const out: Array<{ id: string; type?: string; label?: string }> = [];
const seen = new Set<string>();
const visitNode = (node: unknown): void => {
if (!node || typeof node !== 'object') return;
const rec = node as Record<string, unknown>;
const id = rec.id;
if (typeof id === 'string' && id && !seen.has(id)) {
seen.add(id);
out.push({
id,
type: typeof rec.type === 'string' ? rec.type : undefined,
label: typeof rec.label === 'string' ? rec.label : undefined,
});
}
// Recurse into nested component collections — directly on the node and
// under `properties` (some container components nest children there).
visitList(rec.components);
visitList(rec.children);
const props = rec.properties;
if (props && typeof props === 'object') {
visitList((props as Record<string, unknown>).components);
visitList((props as Record<string, unknown>).children);
}
};
const visitList = (list: unknown): void => {
if (Array.isArray(list)) for (const n of list) visitNode(n);
};
if (draft && typeof draft === 'object') {
const regions = (draft as Record<string, unknown>).regions;
if (Array.isArray(regions)) {
for (const region of regions) {
if (region && typeof region === 'object') {
visitList((region as Record<string, unknown>).components);
}
}
}
}
return out;
}
/**
* Single component-id picker for a page variable's `source` — the component
* whose selection writes the variable (e.g. an `element:record_picker` with
* `id="project_picker"`). Component ids come from `context.componentIds`
* (extracted from the page draft's region/component tree). A stored value not
* present in the tree is still shown so a stale/renamed id survives; when the
* page has no components yet, degrades to a free-text input so the field stays
* editable. Mirrors {@link RefObjectWidget} / {@link ViewRefWidget}.
*/
function RefComponentWidget({ id, value, onChange, readOnly, context }: WidgetProps) {
const locale = useMetadataLocale();
const components = context?.componentIds ?? [];
const current = value == null ? '' : String(value);
// No components placed yet → free-text fallback so the field is still usable.
if (components.length === 0) {
return (
<Input
id={id}
value={current}
disabled={readOnly}
onChange={(e) => onChange(e.target.value || undefined)}
placeholder={t('engine.form.noComponents', locale)}
/>
);
}
const inTree = !current || components.some((c) => c.id === current);
return (
<Select
value={current || NO_FIELD}
onValueChange={(v) => onChange(v === NO_FIELD ? undefined : v)}
disabled={readOnly}
>
<SelectTrigger id={id}>
<SelectValue placeholder={t('engine.form.selectComponent', locale)} />
</SelectTrigger>
<SelectContent>
<SelectItem value={NO_FIELD}>
<span className="text-muted-foreground">{t('engine.form.none', locale)}</span>
</SelectItem>
{!inTree && current && (
<SelectItem value={current}>
<span className="flex items-center gap-2">
<span className="font-mono">{current}</span>
<span className="text-xs text-muted-foreground">{t('engine.form.notInObject', locale)}</span>
</span>
</SelectItem>
)}
{components.map((c) => (
<SelectItem key={c.id} value={c.id}>
<span className="flex items-center gap-2">
<span className="font-mono">{c.id}</span>
{(c.label || c.type) && (
<span className="text-xs text-muted-foreground">{c.label || c.type}</span>
)}
</span>
</SelectItem>
))}
</SelectContent>
</Select>
);
}
/* -------------------------------------------------------------------------- */
/* object-selector — multi-select object picker */
/* -------------------------------------------------------------------------- */
function ObjectSelectorWidget({
id,
value,
onChange,
readOnly,
context,
fieldSpec,
}: WidgetProps) {
const locale = useMetadataLocale();
const names = context?.objectNames ?? [];
const multiple = fieldSpec?.multiple ?? false;
// Parse value: string[], string (comma-separated), or empty
const selectedValues = React.useMemo(() => {
if (!value) return [];
if (Array.isArray(value)) return value.map(String);
return String(value).split(',').map(s => s.trim()).filter(Boolean);
}, [value]);
const handleToggle = (objName: string) => {
if (readOnly) return;
if (!multiple) {
onChange(objName);
return;
}
const newSelection = selectedValues.includes(objName)
? selectedValues.filter(v => v !== objName)
: [...selectedValues, objName];
onChange(newSelection);
};
const handleRemove = (objName: string) => {
if (readOnly) return;
const newSelection = selectedValues.filter(v => v !== objName);
onChange(multiple ? newSelection : '');
};
if (context?.objectsLoading) {
return <Input id={id} value={t('engine.form.loadingObjects', locale)} readOnly disabled />;
}
return (
<div className="space-y-2">
{/* Selected items */}
{selectedValues.length > 0 && (
<div className="flex flex-wrap gap-2">
{selectedValues.map(obj => (
<div
key={obj}
className="inline-flex items-center gap-1 rounded bg-secondary px-2 py-1 text-sm"
>
<span>{obj}</span>
{!readOnly && (
<button
type="button"
onClick={() => handleRemove(obj)}
className="text-muted-foreground hover:text-foreground"
>
×
</button>
)}
</div>
))}
</div>
)}
{/* Object picker */}
<Select
value=""
onValueChange={handleToggle}
disabled={readOnly || names.length === 0}
>
<SelectTrigger id={id}>
<SelectValue placeholder={multiple ? t('engine.form.addObjects', locale) : t('engine.form.selectObjectDots', locale)} />
</SelectTrigger>
<SelectContent>
{names.map(name => (
<SelectItem key={name} value={name} disabled={!multiple && selectedValues.includes(name)}>
{name}
{selectedValues.includes(name) && ' ✓'}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
);
}
/* -------------------------------------------------------------------------- */
/* field-selector — smart field picker (depends on selected object) */
/* -------------------------------------------------------------------------- */
function FieldSelectorWidget({
id,
value,
onChange,
readOnly,
fieldSpec,
formData,
}: WidgetProps) {
const locale = useMetadataLocale();
const [fields, setFields] = React.useState<Array<{ name: string; label: string; type: string }>>([]);
const [loading, setLoading] = React.useState(false);
// Resolve dependency: fieldSpec.dependsOn or fieldSpec.reference or 'objectName'
const dependsOnRaw = fieldSpec?.dependsOn || fieldSpec?.reference || 'objectName';
const dependsOnField = Array.isArray(dependsOnRaw) ? dependsOnRaw[0] : dependsOnRaw;
const objectName = formData?.[dependsOnField] as string | undefined;
// Load fields when objectName changes
React.useEffect(() => {
if (!objectName) {
setFields([]);
return;
}
setLoading(true);
fetch(`/api/v1/objects/${objectName}/fields`)
.then(r => r.json())
.then(data => {
setFields(data.fields || []);
setLoading(false);
})
.catch(err => {
console.error('Failed to load fields:', err);
setFields([]);
setLoading(false);
});
}, [objectName]);
const multiple = fieldSpec?.multiple ?? false;
// Parse value
const selectedValues = React.useMemo(() => {
if (!value) return [];
if (Array.isArray(value)) return value.map(String);
return String(value).split(',').map(s => s.trim()).filter(Boolean);
}, [value]);
const handleToggle = (fieldName: string) => {
if (readOnly) return;
if (!multiple) {
onChange(fieldName);
return;
}
const newSelection = selectedValues.includes(fieldName)
? selectedValues.filter(v => v !== fieldName)
: [...selectedValues, fieldName];
onChange(newSelection);
};
const handleRemove = (fieldName: string) => {
if (readOnly) return;
const newSelection = selectedValues.filter(v => v !== fieldName);
onChange(multiple ? newSelection : '');
};
if (!objectName) {
return <Input id={id} value={t('engine.form.selectObjectFirst', locale)} readOnly disabled />;
}
if (loading) {
return <Input id={id} value={t('engine.form.loadingFields', locale)} readOnly disabled />;
}
return (
<div className="space-y-2">
{/* Selected fields */}
{selectedValues.length > 0 && (
<div className="flex flex-wrap gap-2">
{selectedValues.map(field => {
const fieldMeta = fields.find(f => f.name === field);
return (
<div
key={field}
className="inline-flex items-center gap-1 rounded bg-secondary px-2 py-1 text-sm"
>
<span>{fieldMeta?.label || field}</span>
<code className="text-xs text-muted-foreground">{fieldMeta?.type}</code>
{!readOnly && (
<button
type="button"
onClick={() => handleRemove(field)}
className="text-muted-foreground hover:text-foreground"
>
×
</button>
)}
</div>
);
})}
</div>
)}
{/* Field picker */}
<Select
value=""
onValueChange={handleToggle}
disabled={readOnly || fields.length === 0}
>
<SelectTrigger id={id}>
<SelectValue placeholder={multiple ? t('engine.form.addFields', locale) : t('engine.form.selectFieldDots', locale)} />
</SelectTrigger>
<SelectContent>
{fields.map(f => (
<SelectItem key={f.name} value={f.name} disabled={!multiple && selectedValues.includes(f.name)}>
<div className="flex items-center gap-2">
<span>{f.label || f.name}</span>
<code className="text-xs text-muted-foreground">{f.type}</code>
{selectedValues.includes(f.name) && ' ✓'}
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
);
}
/* -------------------------------------------------------------------------- */
/* master-detail — inline row editor for array-of-object fields */
/* -------------------------------------------------------------------------- */
function MasterDetailWidget({
schema,
value,
onChange,
readOnly,
context,
}: WidgetProps) {
const locale = useMetadataLocale();
// Unwrap anyOf/oneOf: pick the first array-of-object branch.
let resolved = schema as Record<string, any> | undefined;
if (resolved?.anyOf || resolved?.oneOf) {
const branches = (resolved.anyOf ?? resolved.oneOf) as any[];
const objBranch = branches.find(
(b) => b?.type === 'array' && b?.items?.type === 'object',
);
if (objBranch) resolved = { ...resolved, ...objBranch };
}
const items = (resolved?.items ?? {}) as Record<string, any>;
const itemProps = (items.properties ?? {}) as Record<string, any>;
const required = new Set<string>(
Array.isArray(items.required) ? items.required : [],
);
const rows = Array.isArray(value) ? (value as any[]) : [];
const cols = Object.keys(itemProps);
if (cols.length === 0) {
// Falls back to JSON if the array items aren't a typed object.
return (
<div className="rounded border border-dashed border-amber-500/40 bg-amber-500/5 p-2 text-xs text-amber-700 dark:text-amber-300">
{t('engine.form.masterDetailSchemaError', locale)}
</div>
);
}
function updateRow(idx: number, patch: Record<string, unknown>) {
const next = rows.slice();
next[idx] = { ...(next[idx] ?? {}), ...patch };
onChange(next);
}
function addRow() {
onChange([...rows, {}]);
}
function removeRow(idx: number) {
const next = rows.slice();
next.splice(idx, 1);
onChange(next);
}
return (
<div className="space-y-2">
<div className="overflow-x-auto rounded border border-border/40">
<table className="w-full text-sm">
<thead className="bg-muted/40">
<tr>
{cols.map((c) => (
<th
key={c}
className="px-2 py-1.5 text-left text-xs font-medium text-muted-foreground"
>
{(itemProps[c]?.title as string) ?? c}
{required.has(c) && (
<span className="text-destructive ml-0.5">*</span>
)}
</th>
))}
<th className="w-8" />
</tr>
</thead>
<tbody>
{rows.length === 0 && (
<tr>
<td
colSpan={cols.length + 1}
className="px-2 py-3 text-center text-xs text-muted-foreground"
>
{t('engine.form.noRows', locale)}
</td>
</tr>
)}
{rows.map((row, idx) => (
<tr key={idx} className="border-t border-border/30">
{cols.map((c) => (
<td key={c} className="p-1">
<RowCell
schema={itemProps[c]}
value={(row ?? {})[c]}
readOnly={readOnly}
context={context}
onChange={(v) => updateRow(idx, { [c]: v })}
/>
</td>
))}
<td className="p-1 text-right">
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => removeRow(idx)}
disabled={readOnly}
className="h-7 w-7 p-0"
aria-label={t('engine.form.removeRow', locale)}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</td>
</tr>
))}
</tbody>
</table>
</div>
<Button
type="button"
variant="outline"
size="sm"
onClick={addRow}
disabled={readOnly}
>
<Plus className="h-3.5 w-3.5 mr-1" /> {t('engine.form.addRow', locale)}
</Button>
</div>
);
}
function RowCell({
schema,
value,
readOnly,
context,
onChange,
}: {
schema: Record<string, any>;
value: unknown;
readOnly?: boolean;
context?: WidgetContext;
onChange: (v: unknown) => void;
}) {
// ref:object hint inside a row cell
if (schema?.widget === 'ref:object') {
return (
<RefObjectWidget
schema={schema}
value={value}
onChange={onChange}
readOnly={readOnly}
context={context}
/>
);
}
// ref:component hint inside a row cell (page variable `source` picker)
if (schema?.widget === 'ref:component') {
return (
<RefComponentWidget
schema={schema}
value={value}
onChange={onChange}
readOnly={readOnly}
context={context}
/>
);
}
// enum → dropdown
const enumVals = schema?.enum as unknown[] | undefined;
if (Array.isArray(enumVals) && enumVals.length > 0) {
return (
<Select
value={value == null ? '' : String(value)}
onValueChange={(v) => onChange(v || undefined)}
disabled={readOnly}
>
<SelectTrigger className="h-8 text-xs">
<SelectValue placeholder="—" />
</SelectTrigger>
<SelectContent>
{enumVals.map((o) => (
<SelectItem key={String(o)} value={String(o)}>
{String(o)}
</SelectItem>
))}
</SelectContent>
</Select>
);
}
// boolean → checkbox-ish
if (schema?.type === 'boolean') {
return (
<input
type="checkbox"
checked={!!value}
disabled={readOnly}
onChange={(e) => onChange(e.target.checked)}
className="h-4 w-4"
/>
);
}
// number
if (schema?.type === 'number' || schema?.type === 'integer') {
return (
<Input
type="number"
value={value == null ? '' : String(value)}
disabled={readOnly}
onChange={(e) => {
const n = e.target.valueAsNumber;
onChange(Number.isFinite(n) ? n : undefined);
}}
className="h-8 text-xs"
/>
);
}
// default: text
return (
<Input
value={value == null ? '' : String(value)}
disabled={readOnly}
onChange={(e) => onChange(e.target.value || undefined)}
className="h-8 text-xs"
/>
);
}
/* -------------------------------------------------------------------------- */
/* string-tags — chip input for string[] (e.g. searchableFields) */
/* -------------------------------------------------------------------------- */
function StringTagsWidget({
id,
value,
onChange,
readOnly,
}: WidgetProps) {
const locale = useMetadataLocale();
const tags = Array.isArray(value) ? (value as string[]) : [];
const [draft, setDraft] = React.useState('');
function add(raw: string) {
const parts = raw
.split(/[,\n]/)
.map((s) => s.trim())
.filter(Boolean);
if (parts.length === 0) return;
const next = [...tags];
for (const p of parts) if (!next.includes(p)) next.push(p);
onChange(next);
setDraft('');
}
function remove(idx: number) {
const next = tags.slice();
next.splice(idx, 1);
onChange(next);
}
return (
<div className="rounded border border-input bg-background p-1.5">
<div className="flex flex-wrap items-center gap-1">
{tags.map((t, i) => (
<span
key={i}
className="inline-flex items-center gap-1 rounded bg-muted px-1.5 py-0.5 text-xs"
>
<span className="font-mono">{t}</span>
{!readOnly && (
<button
type="button"
aria-label={`Remove ${t}`}
onClick={() => remove(i)}
className="text-muted-foreground hover:text-destructive"
>
×
</button>
)}
</span>
))}
<input
id={id}
type="text"
value={draft}
disabled={readOnly}
placeholder={tags.length === 0 ? t('engine.form.tagsPlaceholder', locale) : ''}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ',') {
e.preventDefault();
add(draft);
} else if (e.key === 'Backspace' && !draft && tags.length > 0) {
remove(tags.length - 1);
}
}}
onBlur={() => draft && add(draft)}
className="min-w-[8rem] flex-1 bg-transparent text-sm outline-none"
/>
</div>
</div>
);
}
/* -------------------------------------------------------------------------- */
/* multiselect — pick from a fixed option set (array of enum) */
/* -------------------------------------------------------------------------- */
/** "grid" → "Grid", "start_date" → "Start Date". */
function humanizeOption(v: string): string {
return v
.replace(/[_-]+/g, ' ')
.replace(/\b\w/g, (c) => c.toUpperCase());
}
/**
* Toggleable option set for `array<enum>` fields (e.g.
* `appearance.allowedVisualizations`). Options come from the JSON Schema's
* `items.enum` (or `fieldSpec.options`); the value is the selected subset
* as a `string[]`, preserving the enum's declared order. Replaces the
* free-text tag input the generic array renderer fell back to — the author
* picks from the real allowed values instead of typing (and mistyping) them.
*/
function MultiSelectWidget({ value, onChange, readOnly, schema, fieldSpec }: WidgetProps) {
// Prefer explicit form options; else the JSON Schema enum on the items.
const options: Array<{ label: string; value: string }> = React.useMemo(() => {
if (Array.isArray(fieldSpec?.options) && fieldSpec!.options!.length) {
return fieldSpec!.options!.map((o) => ({ label: o.label, value: o.value }));
}
const enumVals: unknown =
schema?.items?.enum ?? schema?.enum ?? [];
return (Array.isArray(enumVals) ? enumVals : [])
.filter((v): v is string => typeof v === 'string')
.map((v) => ({ label: humanizeOption(v), value: v }));
}, [fieldSpec, schema]);
const selected = React.useMemo(
() => (Array.isArray(value) ? (value as unknown[]).filter((v): v is string => typeof v === 'string') : []),
[value],
);
function toggle(opt: string) {
if (readOnly) return;
// Keep selection ordered by the option list so behaviour is stable
// (e.g. allowedVisualizations[0] = the default/initial visualization).
const set = new Set(selected);
if (set.has(opt)) set.delete(opt);
else set.add(opt);
const next = options.map((o) => o.value).filter((v) => set.has(v));
onChange(next.length ? next : undefined);
}
if (options.length === 0) {
// No known option set — degrade to the comma-tag editor so the field
// is still editable rather than rendering an empty box.
return <StringTagsWidget value={value} onChange={onChange} readOnly={readOnly} schema={schema} fieldSpec={fieldSpec} />;
}
return (
<div className="flex flex-wrap gap-1.5" role="group">
{options.map((o) => {
const on = selected.includes(o.value);
return (
<button
key={o.value}
type="button"
role="checkbox"
aria-checked={on}
disabled={readOnly}
onClick={() => toggle(o.value)}
className={
'inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs font-medium transition-colors ' +
(on
? 'border-primary bg-primary/10 text-primary'
: 'border-input bg-background text-muted-foreground hover:text-foreground hover:bg-muted') +
(readOnly ? ' opacity-60 cursor-not-allowed' : '')
}
>
<span
aria-hidden
className={
'flex h-3.5 w-3.5 items-center justify-center rounded-[3px] border text-[9px] leading-none ' +
(on ? 'border-primary bg-primary text-primary-foreground' : 'border-muted-foreground/40')
}
>
{on ? '✓' : ''}
</span>
{o.label}
</button>
);
})}
</div>
);
}
/* -------------------------------------------------------------------------- */
/* field-ref / field-multi — pick object field(s) from the bound object */
/* -------------------------------------------------------------------------- */
const NO_FIELD = '__none__';
/**
* Single object-field picker. Used for View config props that reference one
* field by name (titleField, groupByField, startDateField, colorField,
* xAxisField, …). Field list comes from `context.objectFields`; a value not
* present in the catalog is still shown so stale/custom values survive.
*/
function FieldRefWidget({ id, value, onChange, readOnly, context }: WidgetProps) {
const locale = useMetadataLocale();
const fields = context?.objectFields ?? [];
const current = value == null ? '' : String(value);
const inCatalog = !current || fields.some((f) => f.name === current);
return (
<Select
value={current || NO_FIELD}
onValueChange={(v) => onChange(v === NO_FIELD ? '' : v)}
disabled={readOnly}
>
<SelectTrigger id={id}>
<SelectValue placeholder={fields.length ? t('engine.form.selectField', locale) : t('engine.form.noObjectBound', locale)} />
</SelectTrigger>
<SelectContent>
<SelectItem value={NO_FIELD}>
<span className="text-muted-foreground">{t('engine.form.none', locale)}</span>
</SelectItem>
{!inCatalog && current && (
<SelectItem value={current}>
<span className="font-mono">{current}</span>
<span className="ml-2 text-xs text-muted-foreground">{t('engine.form.notInObject', locale)}</span>
</SelectItem>
)}
{fields.map((f) => (
<SelectItem key={f.name} value={f.name}>
<span className="flex items-center gap-2">
<span>{f.label || f.name}</span>
<code className="text-xs text-muted-foreground">{f.name}</code>
</span>
</SelectItem>
))}
</SelectContent>
</Select>
);
}
/**
* Resolve a stored `sourceView` value against a source object's view catalog,
* mirroring the runtime resolver (InterfaceListPage.resolveSourceView): a value
* resolves if it's an exact view name, a bare name matching a view's
* `<object>.<name>` suffix, or the special `default`/`list` (→ object default
* view). `showStored` is true when the stored value needs a synthesized option
* (i.e. it isn't already an exact catalog entry). Exported for unit tests.
*/
export function resolveStoredViewRef(
views: Array<{ name: string; label?: string }>,
current: string,
): { exact?: { name: string; label?: string }; suffixMatch?: { name: string; label?: string }; isSpecial: boolean; resolves: boolean; showStored: boolean } {
const exact = current ? views.find((v) => v.name === current) : undefined;
const suffixMatch = current && !exact ? views.find((v) => v.name.endsWith(`.${current}`)) : undefined;
const isSpecial = current === 'default' || current === 'list';
return { exact, suffixMatch, isSpecial, resolves: !!exact || !!suffixMatch || isSpecial, showStored: !!current && !exact };
}
/**
* Single view picker for `interfaceConfig.sourceView`. Views come from