-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathFieldDesigner.tsx
More file actions
423 lines (392 loc) · 17.4 KB
/
Copy pathFieldDesigner.tsx
File metadata and controls
423 lines (392 loc) · 17.4 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
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* FieldDesigner Component
*
* Enterprise-grade visual designer for configuring object fields.
* Uses standard ObjectGrid for the list view and a right-side DrawerForm for
* create/edit with basic / type-specific / advanced sections.
*/
import React, { useState, useCallback, useMemo } from 'react';
import type { DesignerFieldDefinition, DesignerFieldType } from '@object-ui/types';
import type { ObjectGridSchema, ListColumn } from '@object-ui/types';
import { ObjectGrid } from '@object-ui/plugin-grid';
import { DrawerForm } from '@object-ui/plugin-form';
import type { DrawerFormSchema } from '@object-ui/plugin-form';
import { ValueDataSource } from '@object-ui/core';
import {
Columns3,
Hash,
Type,
Calendar,
ToggleLeft,
ListOrdered,
Link2,
AtSign,
Phone,
Globe,
FileText,
Image,
Palette,
Code,
MapPin,
Star,
SlidersHorizontal,
Lock,
} from 'lucide-react';
import { clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
import { useDesignerTranslation } from './hooks/useDesignerTranslation';
import { useConfirmDialog } from './hooks/useConfirmDialog';
import { ConfirmDialog } from './components/ConfirmDialog';
function cn(...inputs: (string | undefined | false)[]) {
return twMerge(clsx(inputs));
}
// ============================================================================
// Types
// ============================================================================
export interface FieldDesignerProps {
/** Object name this designer belongs to */
objectName: string;
/** List of field definitions */
fields: DesignerFieldDefinition[];
/** Callback when fields change */
onFieldsChange?: (fields: DesignerFieldDefinition[]) => void;
/** Read-only mode */
readOnly?: boolean;
/** CSS class */
className?: string;
}
// ============================================================================
// Constants
// ============================================================================
const FIELD_TYPE_META: Record<DesignerFieldType, { label: string; Icon: React.FC<{ className?: string }> }> = {
text: { label: 'Text', Icon: Type },
textarea: { label: 'Text Area', Icon: FileText },
number: { label: 'Number', Icon: Hash },
boolean: { label: 'Checkbox', Icon: ToggleLeft },
date: { label: 'Date', Icon: Calendar },
datetime: { label: 'Date/Time', Icon: Calendar },
time: { label: 'Time', Icon: Calendar },
select: { label: 'Picklist', Icon: ListOrdered },
email: { label: 'Email', Icon: AtSign },
phone: { label: 'Phone', Icon: Phone },
url: { label: 'URL', Icon: Globe },
password: { label: 'Password', Icon: Lock },
currency: { label: 'Currency', Icon: Hash },
percent: { label: 'Percent', Icon: Hash },
lookup: { label: 'Lookup', Icon: Link2 },
formula: { label: 'Formula', Icon: Code },
autonumber: { label: 'Auto Number', Icon: Hash },
file: { label: 'File', Icon: FileText },
image: { label: 'Image', Icon: Image },
markdown: { label: 'Markdown', Icon: FileText },
html: { label: 'Rich Text', Icon: FileText },
color: { label: 'Color', Icon: Palette },
code: { label: 'Code', Icon: Code },
location: { label: 'Location', Icon: MapPin },
address: { label: 'Address', Icon: MapPin },
rating: { label: 'Rating', Icon: Star },
slider: { label: 'Slider', Icon: SlidersHorizontal },
};
type FieldTypeCategory = 'text' | 'number' | 'date' | 'choice' | 'relation' | 'advanced';
/**
* Category partition of the designer vocabulary, driving the type filter and
* the drawer's type `<select>`. Exported (with {@link CATEGORY_ORDER}) so
* `fieldTypeCategories.test.ts` can assert it stays a complete partition of
* `DESIGNER_FIELD_TYPES` — a type added to the vocabulary but left out here
* would otherwise silently vanish from those pickers (objectui#3017).
*/
export const FIELD_TYPE_CATEGORIES: Record<FieldTypeCategory, DesignerFieldType[]> = {
text: ['text', 'textarea', 'email', 'phone', 'url', 'password', 'markdown', 'html'],
number: ['number', 'currency', 'percent', 'autonumber', 'rating', 'slider'],
date: ['date', 'datetime', 'time'],
choice: ['boolean', 'select'],
relation: ['lookup'],
advanced: ['formula', 'file', 'image', 'color', 'code', 'location', 'address'],
};
export const CATEGORY_ORDER: FieldTypeCategory[] = ['text', 'number', 'date', 'choice', 'relation', 'advanced'];
// ============================================================================
// Main Component
// ============================================================================
export function FieldDesigner({
objectName,
fields,
onFieldsChange,
readOnly = false,
className,
}: FieldDesignerProps) {
const { t } = useDesignerTranslation();
const confirmDialog = useConfirmDialog();
const [formOpen, setFormOpen] = useState(false);
const [editingField, setEditingField] = useState<DesignerFieldDefinition | null>(null);
const [typeFilter, setTypeFilter] = useState<DesignerFieldType | ''>('');
// Pre-filter fields by type (external filter before ObjectGrid)
const filteredFields = useMemo(() => {
if (!typeFilter) return fields;
return fields.filter((f) => f.type === typeFilter);
}, [fields, typeFilter]);
// Create ValueDataSource for ObjectGrid
const dataSource = useMemo(
() => new ValueDataSource({ items: filteredFields }),
[filteredFields]
);
// Grid schema
const gridColumns: ListColumn[] = useMemo(() => [
{ field: 'name', label: t('appDesigner.fieldDesigner.fieldName'), width: 140 },
{ field: 'label', label: t('appDesigner.fieldDesigner.fieldLabel'), width: 160 },
{ field: 'type', label: t('appDesigner.fieldDesigner.fieldType'), width: 100 },
{ field: 'required', label: t('appDesigner.fieldDesigner.required'), width: 80 },
{ field: 'unique', label: t('appDesigner.fieldDesigner.unique'), width: 80 },
{ field: 'group', label: t('appDesigner.fieldDesigner.fieldGroup'), width: 120 },
], [t]);
const gridSchema = useMemo<ObjectGridSchema>(() => ({
type: 'object-grid',
objectName: 'field_definition',
columns: gridColumns,
searchableFields: ['name', 'label', 'description'],
showSearch: true,
operations: readOnly ? undefined : { create: true, update: true, delete: true },
}), [gridColumns, readOnly]);
// Handlers
// Note: ObjectGrid applies $select using column fields, which strips `id`.
// Use `name` (always in columns) as the lookup key instead of `id`.
const handleEdit = useCallback((record: Record<string, unknown>) => {
const field = fields.find((f) => f.name === record.name);
if (field) {
setEditingField(field);
setFormOpen(true);
}
}, [fields]);
const handleDelete = useCallback(async (record: Record<string, unknown>) => {
const field = fields.find((f) => f.name === record.name);
if (!field || field.isSystem) return;
const confirmed = await confirmDialog.confirm(
t('appDesigner.fieldDesigner.deleteConfirmTitle'),
t('appDesigner.fieldDesigner.deleteConfirmMessage')
);
if (confirmed) {
onFieldsChange?.(fields.filter((f) => f.id !== field.id));
}
}, [fields, onFieldsChange, confirmDialog, t]);
const handleAddField = useCallback(() => {
setEditingField(null);
setFormOpen(true);
}, []);
const handleFormSuccess = useCallback((data: Record<string, unknown>) => {
if (editingField) {
// Update existing field
const updated: DesignerFieldDefinition = {
...editingField,
name: String(data.name || editingField.name),
label: String(data.label || editingField.label),
type: (data.type as DesignerFieldType) || editingField.type,
group: data.group ? String(data.group) : undefined,
description: data.description ? String(data.description) : undefined,
required: data.required === true,
unique: data.unique === true,
readonly: data.readonly === true,
hidden: data.hidden === true,
indexed: data.indexed === true,
externalId: data.externalId === true,
trackHistory: data.trackHistory === true,
defaultValue: data.defaultValue ? String(data.defaultValue) : undefined,
placeholder: data.placeholder ? String(data.placeholder) : undefined,
referenceTo: data.referenceTo ? String(data.referenceTo) : undefined,
formula: data.formula ? String(data.formula) : undefined,
};
onFieldsChange?.(fields.map((f) => (f.id === editingField.id ? updated : f)));
} else {
// Create new field
const newField: DesignerFieldDefinition = {
id: `fld_${Date.now()}`,
name: String(data.name || `new_field_${fields.length + 1}`),
label: String(data.label || `New Field ${fields.length + 1}`),
type: (data.type as DesignerFieldType) || 'text',
group: data.group ? String(data.group) : undefined,
description: data.description ? String(data.description) : undefined,
required: data.required === true,
unique: data.unique === true,
readonly: data.readonly === true,
hidden: data.hidden === true,
indexed: data.indexed === true,
externalId: data.externalId === true,
trackHistory: data.trackHistory === true,
defaultValue: data.defaultValue ? String(data.defaultValue) : undefined,
placeholder: data.placeholder ? String(data.placeholder) : undefined,
referenceTo: data.referenceTo ? String(data.referenceTo) : undefined,
formula: data.formula ? String(data.formula) : undefined,
isSystem: false,
};
onFieldsChange?.([...fields, newField]);
}
setFormOpen(false);
setEditingField(null);
}, [editingField, fields, onFieldsChange]);
const handleFormClose = useCallback((open: boolean) => {
if (!open) {
setFormOpen(false);
setEditingField(null);
}
}, []);
// Grouped type options for the <select> used inside the Drawer.
// The top-of-page type filter also uses these groupings (see <optgroup> below).
const typeOptionsByCategory = useMemo(
() => CATEGORY_ORDER.map((cat) => ({
category: cat,
label: t(`appDesigner.fieldDesigner.typeCategory.${cat}`),
options: FIELD_TYPE_CATEGORIES[cat].map((ft) => ({
label: FIELD_TYPE_META[ft].label,
value: ft,
})),
})),
[t],
);
// Flatten for the <select> widget inside the drawer (which only takes `options`).
// Visually grouped via inserting separator-like labels is not supported by shadcn Select.
// For now we flatten and rely on the top filter for category-based filtering.
const flatTypeOptions = useMemo(
() => typeOptionsByCategory.flatMap((g) => g.options),
[typeOptionsByCategory],
);
// DrawerForm schema — right-side panel with Basic / Type-specific / Advanced sections
const drawerSchema = useMemo<DrawerFormSchema>(() => ({
type: 'object-form',
formType: 'drawer',
objectName: 'field_definition',
mode: editingField ? 'edit' : 'create',
title: editingField
? `${t('common.edit')} — ${editingField.label}`
: t('appDesigner.fieldDesigner.addField'),
open: formOpen,
onOpenChange: handleFormClose,
drawerSide: 'right',
drawerWidth: '480px',
sections: [
{
name: 'basic',
label: t('appDesigner.fieldDesigner.basicSection'),
fields: [
{ name: 'name', label: t('appDesigner.fieldDesigner.fieldName'), type: 'text', required: true, placeholder: 'api_name', disabled: readOnly || (editingField?.isSystem ?? false) },
{ name: 'label', label: t('appDesigner.fieldDesigner.fieldLabel'), type: 'text', required: true, placeholder: 'Display Label', disabled: readOnly },
{ name: 'type', label: t('appDesigner.fieldDesigner.fieldType'), type: 'select', required: true, options: flatTypeOptions, disabled: readOnly || (editingField?.isSystem ?? false) },
{ name: 'required', label: t('appDesigner.fieldDesigner.required'), type: 'boolean', disabled: readOnly },
{ name: 'unique', label: t('appDesigner.fieldDesigner.unique'), type: 'boolean', disabled: readOnly },
{ name: 'description', label: t('appDesigner.fieldDesigner.description'), type: 'textarea', disabled: readOnly },
],
},
{
name: 'typeSpecific',
label: t('appDesigner.fieldDesigner.typeSpecificSection'),
fields: [
{ name: 'referenceTo', label: t('appDesigner.fieldDesigner.referenceTo'), type: 'text', placeholder: 'Referenced object', disabled: readOnly, visibleWhen: "record.type == 'lookup'" },
{ name: 'formula', label: t('appDesigner.fieldDesigner.formula'), type: 'textarea', placeholder: 'e.g. price * quantity', disabled: readOnly, visibleWhen: "record.type == 'formula'" },
{ name: 'defaultValue', label: t('appDesigner.fieldDesigner.defaultValue'), type: 'text', placeholder: 'Default value', disabled: readOnly },
{ name: 'placeholder', label: t('appDesigner.fieldDesigner.placeholder'), type: 'text', placeholder: 'Placeholder text', disabled: readOnly },
{ name: 'group', label: t('appDesigner.fieldDesigner.fieldGroup'), type: 'text', placeholder: 'Field Group', disabled: readOnly },
],
},
{
name: 'advanced',
label: t('appDesigner.fieldDesigner.advancedSection'),
collapsible: true,
collapsed: true,
fields: [
{ name: 'indexed', label: t('appDesigner.fieldDesigner.indexed'), type: 'boolean', disabled: readOnly },
{ name: 'externalId', label: t('appDesigner.fieldDesigner.externalId'), type: 'boolean', disabled: readOnly },
{ name: 'trackHistory', label: t('appDesigner.fieldDesigner.trackHistory'), type: 'boolean', disabled: readOnly },
{ name: 'readonly', label: t('appDesigner.fieldDesigner.readOnly'), type: 'boolean', disabled: readOnly },
{ name: 'hidden', label: t('appDesigner.fieldDesigner.hidden'), type: 'boolean', disabled: readOnly },
],
},
],
initialValues: editingField
? {
name: editingField.name,
label: editingField.label,
type: editingField.type,
group: editingField.group || '',
description: editingField.description || '',
required: editingField.required || false,
unique: editingField.unique || false,
readonly: editingField.readonly || false,
hidden: editingField.hidden || false,
indexed: editingField.indexed || false,
externalId: editingField.externalId || false,
trackHistory: editingField.trackHistory || false,
defaultValue: editingField.defaultValue != null ? String(editingField.defaultValue) : '',
placeholder: editingField.placeholder || '',
referenceTo: editingField.referenceTo || '',
formula: editingField.formula || '',
}
: { type: 'text', required: false, unique: false },
onSuccess: handleFormSuccess,
onCancel: () => handleFormClose(false),
readOnly,
}), [editingField, formOpen, handleFormClose, handleFormSuccess, flatTypeOptions, readOnly, t]);
return (
<div
data-testid="field-designer"
className={cn('w-full space-y-3', className)}
>
{/* Header */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Columns3 className="h-4 w-4 text-primary" />
<h2 className="text-sm font-semibold">
{t('appDesigner.fieldDesigner.title')}
</h2>
{objectName && (
<span className="text-xs text-muted-foreground">— {objectName}</span>
)}
<span className="rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">
{filteredFields.length}
</span>
</div>
{/* Type filter — grouped by 6 categories (Airtable-style) */}
<select
value={typeFilter}
onChange={(e) => setTypeFilter(e.target.value as DesignerFieldType | '')}
data-testid="field-designer-type-filter"
className="rounded-md border border-input bg-background px-2 py-1 text-xs outline-none transition-colors focus:border-primary focus:ring-1 focus:ring-primary"
>
<option value="">{t('appDesigner.fieldDesigner.allTypes')}</option>
{typeOptionsByCategory.map((group) => (
<optgroup key={group.category} label={group.label}>
{group.options.map((opt) => (
<option key={opt.value} value={opt.value}>{opt.label}</option>
))}
</optgroup>
))}
</select>
</div>
{/* ObjectGrid for the field list */}
<ObjectGrid
schema={gridSchema}
dataSource={dataSource}
onEdit={readOnly ? undefined : handleEdit}
onDelete={readOnly ? undefined : handleDelete}
onAddRecord={readOnly ? undefined : handleAddField}
/>
{/* DrawerForm for create / edit — right-side panel keeps the field list visible */}
{formOpen && <DrawerForm schema={drawerSchema} />}
{/* Confirm Dialog */}
<ConfirmDialog
isOpen={confirmDialog.isOpen}
title={confirmDialog.title}
message={confirmDialog.message}
confirmLabel={t('common.delete')}
cancelLabel={t('common.cancel')}
onConfirm={confirmDialog.onConfirm}
onCancel={confirmDialog.onCancel}
destructive
/>
</div>
);
}
export default FieldDesigner;