-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathObjectDataForm.tsx
More file actions
241 lines (223 loc) · 11.5 KB
/
ObjectDataForm.tsx
File metadata and controls
241 lines (223 loc) · 11.5 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
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { useState, useEffect } from 'react';
import { useClient } from '@objectstack/client-react';
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Badge } from "@/components/ui/badge";
import { Save, Loader2, AlertCircle } from "lucide-react";
interface ObjectDataFormProps {
objectApiName: string;
record?: any;
onSuccess: () => void;
onCancel: () => void;
}
export function ObjectDataForm({ objectApiName, record, onSuccess, onCancel }: ObjectDataFormProps) {
const client = useClient();
const [def, setDef] = useState<any>(null);
const [formData, setFormData] = useState<any>({});
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let mounted = true;
async function loadDef() {
try {
const found: any = await client.meta.getItem('object', objectApiName);
if (mounted && found) {
// Spec: GetMetaItemResponse = { type, name, item }
const resolved = found.item || found;
setDef(resolved);
if (record) {
setFormData({ ...record });
} else {
setFormData({});
}
}
} catch (err) {
console.error('Failed to load definition', err);
}
}
loadDef();
return () => { mounted = false; };
}, [client, objectApiName, record]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError(null);
try {
const dataToSubmit = { ...formData };
delete dataToSubmit.id;
delete dataToSubmit.created_at;
delete dataToSubmit.updated_at;
if (def && def.fields) {
Object.keys(def.fields).forEach(key => {
const f = def.fields[key];
if (f.type === 'number' && dataToSubmit[key]) {
dataToSubmit[key] = parseFloat(dataToSubmit[key]);
}
});
}
if (record && record.id) {
await client.data.update(objectApiName, record.id, dataToSubmit);
} else {
await client.data.create(objectApiName, dataToSubmit);
}
onSuccess();
} catch (err: any) {
setError(err.message || 'Operation failed');
} finally {
setLoading(false);
}
};
const handleChange = (field: string, value: any) => {
setFormData((prev: any) => ({
...prev,
[field]: value
}));
};
if (!def) {
return (
<Dialog open={true} onOpenChange={(open) => !open && onCancel()}>
<DialogContent className="sm:max-w-lg">
<DialogHeader>
<DialogTitle>Loading...</DialogTitle>
<DialogDescription>Fetching object definition</DialogDescription>
</DialogHeader>
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
</DialogContent>
</Dialog>
);
}
const fields = def.fields || {};
const fieldKeys = Object.keys(fields).filter(k => {
return !['created_at', 'updated_at', 'created_by', 'updated_by'].includes(k);
});
const isEdit = !!(record && record.id);
return (
<Dialog open={true} onOpenChange={(open) => !open && onCancel()}>
<DialogContent className="sm:max-w-lg max-h-[85vh] flex flex-col p-0 gap-0">
<DialogHeader className="px-6 pt-6 pb-4 border-b">
<div className="flex items-center gap-2">
<DialogTitle className="text-lg">
{isEdit ? 'Edit' : 'New'} {def.label}
</DialogTitle>
<Badge variant={isEdit ? "secondary" : "default"} className="text-xs">
{isEdit ? 'Editing' : 'Creating'}
</Badge>
</div>
<DialogDescription>
{isEdit
? `Update the fields below to modify this ${def.label.toLowerCase()}.`
: `Fill in the fields below to create a new ${def.label.toLowerCase()}.`
}
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="flex-1 flex flex-col overflow-hidden">
<ScrollArea className="flex-1">
<div className="p-6 space-y-5">
{error && (
<div className="flex items-center gap-2 bg-destructive/10 text-destructive p-3 rounded-lg text-sm border border-destructive/20">
<AlertCircle className="h-4 w-4 shrink-0" />
{error}
</div>
)}
{fieldKeys.map(key => {
const field = fields[key];
const label = field.label || key;
const required = field.required;
return (
<div key={key} className="space-y-2">
<div className="flex items-center gap-2">
<Label htmlFor={key} className="text-sm font-medium">
{label}
</Label>
{required && (
<span className="text-xs text-destructive">*</span>
)}
<Badge variant="outline" className="text-[10px] px-1 py-0 font-normal opacity-40 ml-auto">
{field.type}
</Badge>
</div>
{field.type === 'boolean' ? (
<div className="flex items-center gap-3 rounded-lg border p-3">
<Switch
id={key}
checked={!!formData[key]}
onCheckedChange={(checked) => handleChange(key, checked)}
/>
<Label htmlFor={key} className="text-sm text-muted-foreground cursor-pointer">
{formData[key] ? 'Enabled' : 'Disabled'}
</Label>
</div>
) : field.type === 'select' ? (
<Select
value={formData[key] || ''}
onValueChange={(value) => handleChange(key, value)}
>
<SelectTrigger id={key}>
<SelectValue placeholder="Select an option..." />
</SelectTrigger>
<SelectContent>
{field.options?.map((opt: any) => (
<SelectItem key={opt.value} value={opt.value}>
{opt.label}
</SelectItem>
))}
</SelectContent>
</Select>
) : field.type === 'textarea' ? (
<Textarea
id={key}
value={formData[key] || ''}
onChange={e => handleChange(key, e.target.value)}
rows={3}
required={required}
placeholder={`Enter ${label.toLowerCase()}...`}
className="resize-none"
/>
) : (
<Input
id={key}
type={field.type === 'number' ? 'number' : 'text'}
value={formData[key] || ''}
onChange={e => handleChange(key, e.target.value)}
required={required}
placeholder={`Enter ${label.toLowerCase()}...`}
/>
)}
{field.description && (
<p className="text-xs text-muted-foreground">{field.description}</p>
)}
</div>
);
})}
</div>
</ScrollArea>
<DialogFooter className="px-6 py-4 border-t bg-muted/30">
<Button variant="outline" onClick={onCancel} type="button" className="gap-1.5">
Cancel
</Button>
<Button type="submit" disabled={loading} className="gap-1.5">
{loading ? (
<>
<Loader2 className="h-4 w-4 animate-spin" /> Saving...
</>
) : (
<>
<Save className="h-4 w-4" /> {isEdit ? 'Update' : 'Create'}
</>
)}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}