|
| 1 | +// CreatePage — add a new object. |
| 2 | +// |
| 3 | +// Fetches the create-form schema from GET <app>/<model>/add/ (same |
| 4 | +// field/fieldset shape as detail, for an unsaved object), renders the |
| 5 | +// shared FieldInput form, and POSTs via createObject. Field-level |
| 6 | +// validation errors come back in the envelope and render next to each |
| 7 | +// input. On success, navigates to the new object's detail page. |
| 8 | + |
| 9 | +import { useEffect, useState } from 'react'; |
| 10 | +import { Link, useNavigate, useParams } from 'react-router-dom'; |
| 11 | + |
| 12 | +import { |
| 13 | + ApiError, |
| 14 | + createObject, |
| 15 | + useApiClient, |
| 16 | + type AddFormResponse, |
| 17 | + type WriteValue, |
| 18 | +} from '@dar/data'; |
| 19 | +import { Button, Card, EmptyState, Spinner } from '@dar/ui'; |
| 20 | + |
| 21 | +import { FieldInput } from '../components/FieldInput'; |
| 22 | + |
| 23 | +export function CreatePage() { |
| 24 | + const params = useParams<{ appLabel: string; modelName: string }>(); |
| 25 | + const appLabel = params.appLabel ?? ''; |
| 26 | + const modelName = params.modelName ?? ''; |
| 27 | + const client = useApiClient(); |
| 28 | + const navigate = useNavigate(); |
| 29 | + |
| 30 | + const [schema, setSchema] = useState<AddFormResponse | null>(null); |
| 31 | + const [loadError, setLoadError] = useState<string | null>(null); |
| 32 | + |
| 33 | + useEffect(() => { |
| 34 | + let alive = true; |
| 35 | + setSchema(null); |
| 36 | + setLoadError(null); |
| 37 | + client |
| 38 | + .addForm(appLabel, modelName) |
| 39 | + .then((s) => { |
| 40 | + if (alive) setSchema(s); |
| 41 | + }) |
| 42 | + .catch((e: unknown) => { |
| 43 | + if (alive) setLoadError(e instanceof Error ? e.message : 'Could not load the add form.'); |
| 44 | + }); |
| 45 | + return () => { |
| 46 | + alive = false; |
| 47 | + }; |
| 48 | + }, [client, appLabel, modelName]); |
| 49 | + |
| 50 | + if (loadError) { |
| 51 | + return <EmptyState title="Couldn't open the add form" description={loadError} />; |
| 52 | + } |
| 53 | + if (!schema) return <Spinner label="Loading…" />; |
| 54 | + |
| 55 | + return ( |
| 56 | + <div className="space-y-4"> |
| 57 | + <header> |
| 58 | + <Link to={`/${appLabel}/${modelName}`} className="text-sm text-blue-600 hover:underline"> |
| 59 | + ← Back to list |
| 60 | + </Link> |
| 61 | + <h1 className="mt-1 text-2xl font-semibold">Add {appLabel} · {modelName}</h1> |
| 62 | + </header> |
| 63 | + <CreateForm |
| 64 | + schema={schema} |
| 65 | + onCreate={async (payload) => { |
| 66 | + const created = await createObject({ client, appLabel, modelName, payload }); |
| 67 | + navigate(`/${appLabel}/${modelName}/${created.pk}`); |
| 68 | + }} |
| 69 | + onCancel={() => navigate(`/${appLabel}/${modelName}`)} |
| 70 | + /> |
| 71 | + </div> |
| 72 | + ); |
| 73 | +} |
| 74 | + |
| 75 | +interface CreateFormProps { |
| 76 | + schema: AddFormResponse; |
| 77 | + onCreate: (payload: Record<string, WriteValue>) => Promise<void>; |
| 78 | + onCancel: () => void; |
| 79 | +} |
| 80 | + |
| 81 | +function CreateForm({ schema, onCreate, onCancel }: CreateFormProps) { |
| 82 | + const [values, setValues] = useState<Record<string, WriteValue>>(() => { |
| 83 | + const init: Record<string, WriteValue> = {}; |
| 84 | + for (const [name, field] of Object.entries(schema.fields)) { |
| 85 | + if (field.readonly) continue; |
| 86 | + const v = field.value; |
| 87 | + // Seed with the model default where the wire carries a scalar; |
| 88 | + // FK envelopes / arrays / html start empty for a new object. |
| 89 | + init[name] = v !== null && typeof v !== 'object' ? v : null; |
| 90 | + } |
| 91 | + return init; |
| 92 | + }); |
| 93 | + const [errors, setErrors] = useState<Record<string, string[]>>({}); |
| 94 | + const [nonFieldError, setNonFieldError] = useState<string | null>(null); |
| 95 | + const [saving, setSaving] = useState(false); |
| 96 | + |
| 97 | + async function handleSubmit(e: React.FormEvent) { |
| 98 | + e.preventDefault(); |
| 99 | + setSaving(true); |
| 100 | + setErrors({}); |
| 101 | + setNonFieldError(null); |
| 102 | + try { |
| 103 | + await onCreate(values); |
| 104 | + } catch (err) { |
| 105 | + if (err instanceof ApiError && err.envelope?.error) { |
| 106 | + const fieldErrors = err.envelope.error.fields ?? {}; |
| 107 | + setErrors(fieldErrors); |
| 108 | + if (Object.keys(fieldErrors).length === 0) { |
| 109 | + setNonFieldError(err.envelope.error.message || 'Create failed.'); |
| 110 | + } |
| 111 | + } else { |
| 112 | + setNonFieldError(err instanceof Error ? err.message : 'Create failed.'); |
| 113 | + } |
| 114 | + } finally { |
| 115 | + setSaving(false); |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + return ( |
| 120 | + <form onSubmit={handleSubmit} className="space-y-4"> |
| 121 | + {nonFieldError && ( |
| 122 | + <div className="rounded border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700"> |
| 123 | + {nonFieldError} |
| 124 | + </div> |
| 125 | + )} |
| 126 | + {schema.fieldsets.map((fieldset, idx) => ( |
| 127 | + <Card |
| 128 | + key={`cfs-${idx}-${fieldset.title ?? 'default'}`} |
| 129 | + title={fieldset.title ?? undefined} |
| 130 | + > |
| 131 | + <div className="divide-y divide-gray-100"> |
| 132 | + {fieldset.fields.map((name) => { |
| 133 | + const field = schema.fields[name]; |
| 134 | + if (!field) return null; |
| 135 | + return ( |
| 136 | + <FieldInput |
| 137 | + key={name} |
| 138 | + name={name} |
| 139 | + field={field} |
| 140 | + value={values[name] ?? null} |
| 141 | + error={errors[name]} |
| 142 | + onChange={(v) => setValues((prev) => ({ ...prev, [name]: v }))} |
| 143 | + /> |
| 144 | + ); |
| 145 | + })} |
| 146 | + </div> |
| 147 | + </Card> |
| 148 | + ))} |
| 149 | + <div className="flex gap-2"> |
| 150 | + <Button type="submit" variant="primary" disabled={saving}> |
| 151 | + {saving ? 'Saving…' : 'Add'} |
| 152 | + </Button> |
| 153 | + <Button type="button" variant="secondary" onClick={onCancel} disabled={saving}> |
| 154 | + Cancel |
| 155 | + </Button> |
| 156 | + </div> |
| 157 | + </form> |
| 158 | + ); |
| 159 | +} |
0 commit comments