import { useForm } from '@inertiajs/react'; import { Lock } from 'lucide-react'; import { useEffect, useRef } from 'react'; import { CascadeSelect } from '@/components/cascade-select'; import { CrudForm, CrudFormDialog, useFormGuard, } from '@/components/crud/crud-form'; import type { FormMode } from '@/components/crud/crud-form'; import { FormField, OptionSelect } from '@/components/crud/form-field'; import { EmbedField } from '@/components/embed'; import { KeyValueInput } from '@/components/key-value-input'; import { MaskedInput } from '@/components/masked-input'; import { RichTextEditor } from '@/components/rich-text'; import { TagsInput } from '@/components/tags-input'; import { FieldError } from '@/components/ui/field'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Switch } from '@/components/ui/switch'; import { FileUpload } from '@/components/upload/file-upload'; import { GalleryUpload } from '@/components/upload/gallery-upload'; import { enumLabel } from '@/lib/format'; import { slugify } from '@/lib/slugify'; import { storedFileUrl } from '@/lib/stored-file'; import { moduleLabel, t } from '@/lib/ui-text'; // crud:form-imports import { formData as formDataRoute, store, update } from '@/routes/product'; /** The record as the form consumes it — what the `form-data` route returns. */ export type ProductFormItem = Partial<{ id: number; category_id: number; name: string; slug: string; sku: string; status: string; price: string; compare_at_price: string; cost_price: string; photos: string[] | null; video_url: string | null; description: string | null; size_chart: string | null; is_featured: boolean; published_at: string | null; published_by: number; specs: Record | null; tag_ids: number[]; tag_new: string[]; _version: string; categoryChain: Record; // crud:item-type }>; /** * What the dialog is open for: a new record (perhaps prefilled), or one to * edit or copy, which is read from the server once the dialog is open. */ export type FormTarget = | { mode: 'create'; prefill?: Partial } | { mode: 'edit'; id: number } | { mode: 'duplicate'; id: number }; type Options = { statusOptions: string[]; fkOptionsUrl: string; tagsOptions: { id: number; name: string }[]; canEditRestricted?: boolean; }; /** * Create, edit and duplicate a product without leaving the page — the * dialog is CrudFormDialog. The caller mounts this only while it is open, * keyed per target, so `useForm` starts from the record instead of being * patched once it arrives. */ export function ProductFormModal({ open, onOpenChange, target, options, }: { open: boolean; onOpenChange: (open: boolean) => void; target: FormTarget; options: Options; }) { return ( open={open} onOpenChange={onOpenChange} mode={target.mode} label={moduleLabel('product', 'Product')} recordUrl={ target.mode === 'create' ? null : formDataRoute.url(target.id, { query: target.mode === 'duplicate' ? { duplicate: 1 } : {}, }) } initial={target.mode === 'create' ? target.prefill : undefined} skeleton={{ fields: 11, wide: 3 }} > {(item) => ( )} ); } function ProductFormFields({ mode, item, options, }: { mode: FormMode; item: ProductFormItem; options: Options; }) { const isEditing = mode === 'edit'; const label = moduleLabel('product', 'Product'); const { data, setData, post, transform, processing, errors, isDirty } = useForm({ category_id: item.category_id ? String(item.category_id) : '', name: item.name ?? '', slug: item.slug ?? '', sku: item.sku ?? '', status: item.status ?? 'draft', price: item.price ?? '', compare_at_price: item.compare_at_price ?? '', cost_price: item.cost_price ?? '', photos_existing: (item.photos ?? []) as string[], photos_new: [] as File[], video_url: item.video_url ?? '', description: item.description ?? '', size_chart: null as File | null, is_featured: item.is_featured ?? false, specs: (item.specs ?? {}) as Record, tag_ids: item.tag_ids ?? [], tag_new: [] as string[], // crud:form-data }); const { close } = useFormGuard(isDirty); const { statusOptions, fkOptionsUrl, tagsOptions, canEditRestricted = true, } = options; const slugLocked = useRef(isEditing); useEffect(() => { if (!slugLocked.current) { setData('slug', slugify(String(data.name ?? ''))); } }, [data.name, setData]); function submit() { if (isEditing) { // What this editor loaded. The server refuses the save if the // record moved since — see RecordVersion. // Multipart can't be sent as PUT — spoof the method so the file uploads. transform((d) => ({ ...d, _method: 'put', _version: item._version ?? '', })); post(update.url(item.id!), { preserveScroll: true, onSuccess: () => close(), }); } else { post(store.url(), { preserveScroll: true, onSuccess: () => close(), }); } } return (
setData('category_id', id)} endpoint={fkOptionsUrl} preselected={item.categoryChain} /> {errors.category_id}
setData('name', e.target.value)} /> { slugLocked.current = true; setData('slug', e.target.value); }} placeholder="auto-generated-from-title" /> {!isEditing && ( setData('sku', e.target.value)} /> )} setData('status', value)} options={statusOptions.map((option) => ({ value: option, label: enumLabel(option), }))} placeholder={t('selectOne', { label: 'Status' })} />

Pricing

setData('price', raw)} /> {isEditing && !canEditRestricted && (

{t('restrictedField')}

)}
setData('compare_at_price', raw)} /> setData('cost_price', raw)} />

Presentation

storedFileUrl( 'product', item?.id, 'photos', path, 'thumb', ) } onExistingChange={(paths) => setData('photos_existing', paths) } files={data.photos_new} onFilesChange={(files) => setData('photos_new', files) } maxFiles={20} maxKb={5120} /> { Object.entries(errors).find(([k]) => k.startsWith('photos_new'), )?.[1] }
setData('video_url', url)} /> setData('description', html)} /> setData('size_chart', file)} types={[ 'pdf', 'docx', 'xlsx', 'csv', 'txt', 'jpg', 'jpeg', 'png', 'webp', 'zip', ]} maxKb={5120} invalid={Boolean(errors.size_chart)} />

Is Featured

setData('is_featured', value) } aria-label="Is Featured" />
setData('specs', value)} errors={errors} />
({ id: o.id, label: o.name, }))} ids={data.tag_ids} newLabels={data.tag_new} onChange={(ids, labels) => setData((prev) => ({ ...prev, tag_ids: ids, tag_new: labels, })) } placeholder={t('addTags', { label: 'Tags' })} /> {errors.tag_ids ?? errors.tag_new}
{/* crud:form-fields */}
); }