@adula/ui 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -18,7 +18,8 @@
18
18
  "hijri-calendar",
19
19
  "calendar-date",
20
20
  "ui-preferences",
21
- "messages"
21
+ "messages",
22
+ "user-avatar"
22
23
  ],
23
24
  "dependencies": [
24
25
  "axios@1.19.0",
@@ -29,7 +30,7 @@
29
30
  {
30
31
  "path": "registry/ui/resource-field.tsx",
31
32
  "type": "registry:ui",
32
- "content": "import { useEffect, useId, useRef, useState, type ComponentProps } from 'react'\nimport { useHttp } from '@inertiajs/react'\nimport axios from 'axios'\nimport { format } from 'date-fns'\nimport {\n ArrowDown,\n ArrowUp,\n CalendarDays,\n Check,\n ChevronsUpDown,\n Paperclip,\n Plus,\n Trash2,\n Undo2,\n Upload,\n X,\n} from 'lucide-react'\nimport type { CalendarSystem, ResourceEditor, ResourceField as Field } from 'adula'\nimport { Badge } from '~/components/ui/badge'\nimport { Button } from '~/components/ui/button'\nimport { Checkbox } from '~/components/ui/checkbox'\nimport { Calendar } from '~/components/ui/calendar'\nimport { HijriCalendar } from '~/components/ui/hijri-calendar'\nimport { calendarInput, calendarIso } from '~/components/ui/calendar_date'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\nimport { useMessages } from '~/components/ui/messages'\nimport { AttachmentPreviewButton } from '~/components/ui/attachment-preview'\nimport {\n Command,\n CommandEmpty,\n CommandGroup,\n CommandInput,\n CommandItem,\n CommandList,\n} from '~/components/ui/command'\nimport { Input } from '~/components/ui/input'\nimport { Label } from '~/components/ui/label'\nimport {\n Popover,\n PopoverAnchor,\n PopoverContent,\n PopoverTrigger,\n} from '~/components/ui/popover'\nimport { Switch } from '~/components/ui/switch'\nimport { Textarea } from '~/components/ui/textarea'\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from '~/components/ui/select'\nimport {\n decimalScale,\n hiddenFields,\n listInput,\n listValue,\n orderedSelection,\n parseDecimal,\n} from '~/components/ui/field_values'\nimport {\n CURRENCY_LABEL,\n PERCENT_LABEL,\n fieldOptions,\n fileSize,\n isAttachment,\n moneyDisplay,\n moneyInput,\n parseMoney,\n toLatinDigits,\n type AttachmentValue,\n type Option,\n} from '~/components/ui/resource-value'\n\nexport type RelationSource = { url: string; searchable: boolean }\nexport type InlineDefinition = ResourceEditor['inline'][string]\nexport type InlineRow = {\n key: string\n id?: number\n version?: number\n values: Record<string, string>\n deleted?: boolean\n dirty?: boolean\n}\nexport type FieldProps = {\n field: Field\n id: string\n value: string\n onChange: (value: string) => void\n disabled?: boolean\n error?: string\n options?: Option[]\n relation?: RelationSource\n attachment?: AttachmentValue | null\n /** The stored files of a multiple attachment field, in order (ADR 047). */\n attachments?: AttachmentValue[]\n /** Resource name; attachment uploads are claimed against it. */\n resource?: string\n /** Accessible name when the visible label lives elsewhere, e.g. inline rows. */\n label?: string\n}\nexport function ResourceSelect({\n value,\n onChange,\n options,\n placeholder,\n required,\n disabled,\n className = 'h-10 w-full',\n ...trigger\n}: Pick<\n ComponentProps<typeof SelectTrigger>,\n 'id' | 'aria-label' | 'aria-invalid' | 'aria-describedby'\n> & {\n value: string\n onChange: (value: string) => void\n options: Option[]\n placeholder?: string\n required?: boolean\n disabled?: boolean\n /** Trigger size and width; forms keep the default, toolbars pass a compact size. */\n className?: string\n}) {\n const { t } = useMessages()\n const empty = placeholder ?? t('اختر قيمة')\n // Encode values so an empty selection cannot collide with a business lookup key.\n return (\n <Select\n value={`value:${value}`}\n onValueChange={(next) => onChange(next.slice(6))}\n required={required}\n disabled={disabled}\n >\n <SelectTrigger {...trigger} className={className} aria-required={required}>\n <SelectValue placeholder={empty} />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value=\"value:\">{empty}</SelectItem>\n {options\n .filter((option) => String(option.value) !== '')\n .map((option) => (\n <SelectItem key={option.value} value={`value:${option.value}`}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n )\n}\n\nexport function ResourceField(props: FieldProps) {\n const { field, id, error } = props\n const { label } = useMessages()\n return (\n <div\n className={`min-w-0 space-y-2 ${['text', 'json', 'manyToMany'].includes(field.type) ? 'md:col-span-2' : ''}`}\n >\n {/* The marker stays outside the label so the field's accessible name is the label alone. */}\n <div className=\"flex items-center gap-1\">\n <Label id={`${id}-label`} htmlFor={id}>\n {label(field.label)}\n </Label>\n {field.required && (\n <span className=\"text-destructive\" aria-hidden=\"true\">\n *\n </span>\n )}\n </div>\n <FieldControl {...props} />\n {error && (\n <p role=\"alert\" id={`${id}-error`} className=\"text-xs text-destructive\">\n {error}\n </p>\n )}\n </div>\n )\n}\n\nexport function FieldControl(props: FieldProps) {\n const { field, id, value, onChange, disabled, error, label } = props\n const { t, locale } = useMessages()\n const shared = {\n id,\n disabled,\n 'required': field.required,\n 'aria-label': label,\n 'aria-invalid': error ? true : undefined,\n 'aria-describedby': error ? `${id}-error` : undefined,\n }\n switch (field.type) {\n case 'belongsTo':\n case 'user':\n return <RelationCombobox {...props} />\n case 'manyToMany':\n return <RelationMultiPicker {...props} />\n case 'multiSelect':\n return <MultiSelectControl {...props} />\n case 'enum':\n return (\n <ResourceSelect\n {...shared}\n value={value}\n onChange={onChange}\n options={props.options ?? fieldOptions(field, locale)}\n />\n )\n case 'decimal':\n case 'percent':\n return <DecimalControl {...props} />\n case 'email':\n case 'phone':\n case 'url':\n case 'string': {\n // A string with `format` uses the same control as the dedicated type.\n const kind = field.type === 'string' ? field.format : field.type\n if (!kind) break\n return (\n <Input\n {...shared}\n type={kind === 'phone' ? 'tel' : kind}\n inputMode={kind === 'phone' ? 'tel' : kind}\n autoComplete={kind === 'url' ? 'url' : kind === 'email' ? 'email' : 'tel'}\n dir=\"ltr\"\n spellCheck={false}\n placeholder={\n kind === 'url' ? 'https://' : kind === 'email' ? 'name@example.com' : '+966 5x xxx xxxx'\n }\n className=\"h-10 text-start\"\n value={value}\n onChange={(event) => onChange(event.target.value)}\n />\n )\n }\n case 'lookup':\n return (\n <ResourceSelect\n {...shared}\n value={value}\n onChange={onChange}\n options={props.options ?? []}\n />\n )\n case 'boolean':\n return (\n <div className=\"flex h-10 items-center gap-3\">\n <Switch\n {...shared}\n required={undefined}\n checked={value === 'true'}\n onCheckedChange={(checked) => onChange(checked ? 'true' : 'false')}\n />\n <span className=\"text-sm text-muted-foreground\">\n {value === 'true' ? t('نعم') : t('لا')}\n </span>\n </div>\n )\n case 'attachment':\n return field.multiple ? (\n <MultipleAttachmentControl {...props} />\n ) : (\n <AttachmentControl {...props} />\n )\n case 'text':\n return (\n <Textarea\n {...shared}\n rows={4}\n value={value}\n onChange={(event) => onChange(event.target.value)}\n />\n )\n case 'json':\n return <JsonControl {...props} />\n case 'money':\n return <MoneyControl {...props} />\n case 'date':\n return <DateControl {...props} />\n case 'datetime':\n return <DatetimeControl {...props} />\n case 'integer':\n return (\n <Input\n {...shared}\n type=\"number\"\n step={1}\n inputMode=\"numeric\"\n dir=\"ltr\"\n className=\"h-10\"\n value={value}\n onChange={(event) => onChange(event.target.value)}\n />\n )\n }\n return (\n <Input\n {...shared}\n type=\"text\"\n className=\"h-10\"\n value={value}\n onChange={(event) => onChange(event.target.value)}\n />\n )\n}\n\nfunction MoneyControl({ id, value, onChange, disabled, error, field, label }: FieldProps) {\n const { t } = useMessages()\n let preview = ''\n try {\n if (value) preview = moneyDisplay(parseMoney(value))\n } catch {\n preview = ''\n }\n return (\n <div className=\"space-y-1\">\n {/* LTR like the input, so the suffix and its padding share one physical side. */}\n <div className=\"relative\" dir=\"ltr\">\n <Input\n id={id}\n type=\"text\"\n inputMode=\"decimal\"\n dir=\"ltr\"\n placeholder=\"0.00\"\n className=\"h-10 pe-16 text-end tabular-nums\"\n value={value}\n disabled={disabled}\n required={field.required}\n aria-label={label}\n aria-invalid={error ? true : undefined}\n aria-describedby={error ? `${id}-error` : undefined}\n onChange={(event) => onChange(event.target.value)}\n onBlur={() => {\n try {\n if (value) onChange(moneyInput(parseMoney(value)))\n } catch {\n // Keep the typed text so the submit error can point at it.\n }\n }}\n />\n <span className=\"pointer-events-none absolute inset-y-0 end-3 flex items-center text-xs text-muted-foreground\">\n {t(CURRENCY_LABEL)}\n </span>\n </div>\n {preview && (\n <p className=\"text-xs text-muted-foreground\" dir=\"ltr\">\n {preview} {t(CURRENCY_LABEL)}\n </p>\n )}\n </div>\n )\n}\n\n/**\n * Decimal and percent entry: Arabic-Indic digits and the Arabic decimal separator are\n * accepted and normalized to the field's scale on blur; percent shows the ٪ suffix.\n */\nfunction DecimalControl({ id, value, onChange, disabled, error, field, label }: FieldProps) {\n const { t } = useMessages()\n const scale = decimalScale(field)\n const percent = field.type === 'percent'\n const hint = `${id}-hint`\n return (\n <div className=\"space-y-1\">\n {/* LTR like the input, so the suffix and its padding share one physical side. */}\n <div className=\"relative\" dir=\"ltr\">\n <Input\n id={id}\n type=\"text\"\n inputMode=\"decimal\"\n dir=\"ltr\"\n placeholder={scale ? `0.${'0'.repeat(scale)}` : '0'}\n className={`h-10 text-end tabular-nums ${percent ? 'pe-9' : ''}`}\n value={value}\n disabled={disabled}\n required={field.required}\n aria-label={label}\n aria-invalid={error ? true : undefined}\n aria-describedby={error ? `${id}-error ${hint}` : hint}\n onChange={(event) => onChange(event.target.value)}\n onBlur={() => {\n try {\n if (value) onChange(parseDecimal(value, scale))\n } catch {\n // Keep the typed text so the submit error can point at it.\n }\n }}\n />\n {percent && (\n <span className=\"pointer-events-none absolute inset-y-0 end-3 flex items-center text-sm text-muted-foreground\">\n {t(PERCENT_LABEL)}\n </span>\n )}\n </div>\n <p id={hint} className=\"text-xs text-muted-foreground\">\n {scale\n ? t('المنازل العشرية: {scale} على الأكثر', { scale })\n : t('عدد صحيح بلا منازل عشرية')}\n </p>\n </div>\n )\n}\n\n/** Every option as a checkbox in definition order; the value is stored in that order. */\nfunction MultiSelectControl({\n id,\n value,\n onChange,\n disabled,\n error,\n field,\n label,\n options,\n}: FieldProps) {\n const { t, label: localized, locale } = useMessages()\n const choices = options ?? fieldOptions(field, locale)\n const selected = listValue(value)\n const toggle = (option: string, checked: boolean) => {\n const next = checked ? [...selected, option] : selected.filter((entry) => entry !== option)\n onChange(listInput(orderedSelection(choices, next)))\n }\n const described = [error ? `${id}-error` : '', field.required ? `${id}-required` : '']\n .filter(Boolean)\n .join(' ')\n return (\n <div\n id={id}\n role=\"group\"\n // Named by the visible field label (ResourceField); inline rows pass their own name.\n aria-labelledby={label ? undefined : `${id}-label`}\n aria-label={label ?? localized(field.label)}\n aria-invalid={error ? true : undefined}\n aria-describedby={described || undefined}\n className=\"flex min-h-10 flex-wrap items-center gap-x-5 gap-y-2 rounded-md border px-3 py-2\"\n >\n {field.required && (\n <span id={`${id}-required`} className=\"sr-only\">\n {t('مطلوب')}\n </span>\n )}\n {choices.map((option) => {\n const optionId = `${id}-${option.value}`\n return (\n <div key={option.value} className=\"flex items-center gap-2\">\n <Checkbox\n id={optionId}\n checked={selected.includes(option.value)}\n disabled={disabled}\n onCheckedChange={(checked) => toggle(option.value, checked === true)}\n />\n <Label htmlFor={optionId} className=\"font-normal\">\n {option.label}\n </Label>\n </div>\n )\n })}\n </div>\n )\n}\n\nfunction DateControl({ id, value, onChange, disabled, error, field, label }: FieldProps) {\n const { calendar: preference } = useUiPreferences()\n const { t, label: localized } = useMessages()\n const name = label ?? localized(field.label)\n const [entryCalendar, setEntryCalendar] = useState<CalendarSystem>('gregory')\n const calendar = preference === 'both' ? entryCalendar : preference\n const [open, setOpen] = useState(false)\n let normalized = toLatinDigits(value)\n try {\n if (value.startsWith('hijri:')) normalized = calendarIso(value.slice(6), 'islamic-umalqura')\n } catch {\n normalized = ''\n }\n const displayed =\n calendar === 'islamic-umalqura'\n ? value.startsWith('hijri:')\n ? value.slice(6)\n : calendarInput(value, calendar)\n : normalized\n const selected = /^\\d{4}-\\d{2}-\\d{2}$/.test(normalized)\n ? new Date(`${normalized}T00:00:00`)\n : undefined\n const valid = selected !== undefined && !Number.isNaN(selected.getTime())\n return (\n <div className=\"space-y-1\">\n {preference === 'both' && (\n <div\n className=\"flex gap-1\"\n role=\"group\"\n aria-label={t('تقويم الإدخال: {field}', { field: name })}\n >\n <Button\n type=\"button\"\n size=\"sm\"\n variant={calendar === 'gregory' ? 'secondary' : 'ghost'}\n aria-pressed={calendar === 'gregory'}\n onClick={() => setEntryCalendar('gregory')}\n >\n {t('إدخال ميلادي')}\n </Button>\n <Button\n type=\"button\"\n size=\"sm\"\n variant={calendar === 'islamic-umalqura' ? 'secondary' : 'ghost'}\n aria-pressed={calendar === 'islamic-umalqura'}\n onClick={() => setEntryCalendar('islamic-umalqura')}\n >\n {t('إدخال هجري')}\n </Button>\n </div>\n )}\n <div className=\"flex gap-2\">\n <Input\n id={id}\n type=\"text\"\n inputMode=\"numeric\"\n dir=\"ltr\"\n placeholder={calendar === 'islamic-umalqura' ? '1447-09-01' : '2026-01-31'}\n className=\"h-10 tabular-nums\"\n value={displayed}\n disabled={disabled}\n required={field.required}\n aria-label={label}\n aria-invalid={error ? true : undefined}\n aria-describedby={error ? `${id}-error` : undefined}\n onChange={(event) =>\n onChange(\n calendar === 'islamic-umalqura' && event.target.value\n ? `hijri:${event.target.value}`\n : event.target.value\n )\n }\n />\n <Popover open={open} onOpenChange={setOpen}>\n <PopoverTrigger asChild>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"icon-lg\"\n disabled={disabled}\n aria-label={t('التقويم: {field}', { field: name })}\n >\n <CalendarDays />\n </Button>\n </PopoverTrigger>\n <PopoverContent className=\"w-auto p-0\" align=\"start\">\n {calendar === 'islamic-umalqura' ? (\n <HijriCalendar\n value={valid ? normalized : ''}\n onSelect={(iso) => {\n onChange(iso)\n setOpen(false)\n }}\n />\n ) : (\n <Calendar\n mode=\"single\"\n selected={valid ? selected : undefined}\n defaultMonth={valid ? selected : undefined}\n onSelect={(date) => {\n onChange(date ? format(date, 'yyyy-MM-dd') : '')\n setOpen(false)\n }}\n />\n )}\n </PopoverContent>\n </Popover>\n </div>\n {calendar === 'islamic-umalqura' && (\n <p className=\"text-xs text-muted-foreground\">\n {t('هجري · أم القرى')}{' '}\n {valid && <span dir=\"ltr\">{t('({date} ميلادي)', { date: normalized })}</span>}\n </p>\n )}\n {preference === 'both' && calendar === 'gregory' && valid && (\n <p className=\"text-xs text-muted-foreground\" aria-live=\"polite\">\n {t('الموافق هجريًا:')}{' '}\n <span dir=\"ltr\">{calendarInput(normalized, 'islamic-umalqura')}</span> {t('هـ')}\n </p>\n )}\n </div>\n )\n}\n\nfunction DatetimeControl(props: FieldProps) {\n const { calendar } = useUiPreferences()\n const { t, label } = useMessages()\n if (calendar === 'gregory')\n return (\n <Input\n id={props.id}\n type=\"datetime-local\"\n dir=\"ltr\"\n className=\"h-10\"\n value={props.value}\n disabled={props.disabled}\n required={props.field.required}\n aria-label={props.label}\n aria-invalid={Boolean(props.error)}\n onChange={(event) => props.onChange(event.target.value)}\n />\n )\n const [date, time = '00:00'] = props.value.split('T')\n return (\n <div className=\"space-y-2\">\n <DateControl\n {...props}\n value={date}\n onChange={(next) => props.onChange(next ? `${next}T${time}` : '')}\n />\n <Input\n type=\"time\"\n dir=\"ltr\"\n aria-label={t('الوقت: {field}', { field: props.label ?? label(props.field.label) })}\n value={time}\n disabled={props.disabled}\n onChange={(event) => props.onChange(`${date}T${event.target.value}`)}\n />\n </div>\n )\n}\n\nfunction JsonControl({ id, value, onChange, disabled, error, field, label }: FieldProps) {\n const { t } = useMessages()\n const [invalid, setInvalid] = useState('')\n const check = () => {\n if (!value.trim()) return setInvalid('')\n try {\n JSON.parse(value)\n setInvalid('')\n } catch {\n setInvalid(t('أدخل بيانات JSON صحيحة'))\n }\n }\n return (\n <div className=\"space-y-2\">\n <Textarea\n id={id}\n dir=\"ltr\"\n rows={6}\n spellCheck={false}\n className=\"font-mono text-xs\"\n value={value}\n disabled={disabled}\n required={field.required}\n aria-label={label}\n aria-invalid={error || invalid ? true : undefined}\n aria-describedby={error ? `${id}-error` : undefined}\n onChange={(event) => onChange(event.target.value)}\n onBlur={check}\n />\n <div className=\"flex items-center gap-3\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n disabled={disabled || !value.trim()}\n onClick={() => {\n try {\n onChange(JSON.stringify(JSON.parse(value), null, 2))\n setInvalid('')\n } catch {\n setInvalid(t('أدخل بيانات JSON صحيحة'))\n }\n }}\n >\n {t('تنسيق JSON')}\n </Button>\n {invalid && !error && (\n <p role=\"alert\" className=\"text-xs text-destructive\">\n {invalid}\n </p>\n )}\n </div>\n </div>\n )\n}\n\n/** Uploads on selection so the saved record only references an already-owned attachment id. */\nfunction AttachmentControl({\n id,\n value,\n onChange,\n disabled,\n error,\n field,\n label,\n attachment,\n resource,\n}: FieldProps) {\n const { t, label: localized } = useMessages()\n const [current, setCurrent] = useState<AttachmentValue | null>(attachment ?? null)\n const [progress, setProgress] = useState<number | null>(null)\n const [failure, setFailure] = useState('')\n const input = useRef<HTMLInputElement>(null)\n const upload = async (file: File) => {\n setFailure('')\n setProgress(0)\n const body = new FormData()\n body.append('file', file)\n if (resource) body.append('resource', resource)\n body.append('field', field.key)\n try {\n const response = await axios.post<{ data: AttachmentValue }>('/attachments', body, {\n headers: { Accept: 'application/json' },\n withXSRFToken: true,\n onUploadProgress: (event) =>\n setProgress(event.total ? Math.round((event.loaded / event.total) * 100) : 50),\n })\n setCurrent(response.data.data)\n onChange(String(response.data.data.id))\n } catch (caught) {\n setFailure(\n axios.isAxiosError(caught)\n ? (caught.response?.data?.error?.message ?? t('تعذر رفع الملف. حاول مجدداً.'))\n : t('تعذر الاتصال بالخادم.')\n )\n } finally {\n setProgress(null)\n if (input.current) input.current.value = ''\n }\n }\n const shown = value && current && String(current.id) === value ? current : null\n return (\n <div className=\"space-y-2\">\n <input\n ref={input}\n id={id}\n type=\"file\"\n className=\"sr-only\"\n disabled={disabled || progress !== null}\n aria-label={label}\n aria-describedby={error ? `${id}-error` : undefined}\n onChange={(event) => {\n const file = event.target.files?.[0]\n if (file) void upload(file)\n }}\n />\n {shown ? (\n <div className=\"flex flex-wrap items-center gap-3 rounded-md border bg-white px-3 py-2 text-sm\">\n <Paperclip size={15} className=\"text-muted-foreground\" />\n <a\n href={shown.url}\n download={shown.name}\n className=\"text-primary underline-offset-4 hover:underline\"\n >\n {shown.name}\n </a>\n <span className=\"text-xs text-muted-foreground\">{fileSize(shown.size, t)}</span>\n <span className=\"ms-auto flex gap-1\">\n <AttachmentPreviewButton file={shown} disabled={disabled} />\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n disabled={disabled}\n onClick={() => input.current?.click()}\n >\n <Upload size={14} />\n {t('استبدال')}\n </Button>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n disabled={disabled}\n className=\"text-destructive\"\n onClick={() => onChange('')}\n >\n <X size={14} />\n {t('إزالة')}\n </Button>\n </span>\n </div>\n ) : (\n <Button\n type=\"button\"\n variant=\"outline\"\n disabled={disabled || progress !== null}\n onClick={() => input.current?.click()}\n >\n <Upload size={15} />\n {progress === null ? t('اختيار ملف') : t('جارٍ الرفع {progress}%', { progress })}\n </Button>\n )}\n {progress !== null && (\n <div\n role=\"progressbar\"\n aria-valuemin={0}\n aria-valuemax={100}\n aria-valuenow={progress}\n aria-label={t('رفع {field}', { field: label ?? localized(field.label) })}\n className=\"h-1.5 w-full overflow-hidden rounded-full bg-muted\"\n >\n <div className=\"h-full bg-primary transition-all\" style={{ width: `${progress}%` }} />\n </div>\n )}\n {failure && (\n <p role=\"alert\" className=\"text-xs text-destructive\">\n {failure}\n </p>\n )}\n </div>\n )\n}\n\n/** The upload failure as the server worded it, or a generic Arabic message. */\nfunction uploadFailure(caught: unknown, t: ReturnType<typeof useMessages>['t']) {\n return axios.isAxiosError(caught)\n ? (caught.response?.data?.error?.message ?? t('تعذر رفع الملف. حاول مجدداً.'))\n : t('تعذر الاتصال بالخادم.')\n}\n\n/**\n * Several files for one field: each selected file uploads on its own (with its own\n * progress) and joins the ordered list; files can be moved, removed and previewed. The\n * value is the JSON array of attachment ids the record saves; the server checks every\n * limit again.\n */\nfunction MultipleAttachmentControl({\n id,\n value,\n onChange,\n disabled,\n error,\n field,\n label,\n attachments,\n resource,\n}: FieldProps) {\n const { t, label: localized } = useMessages()\n // The editor sends the resolved limit; 10 is AdulaJS's default for older payloads.\n const max = field.type === 'attachment' ? (field.max ?? 10) : 10\n const [known, setKnown] = useState<AttachmentValue[]>(attachments ?? [])\n const [uploads, setUploads] = useState<{ key: string; name: string; progress: number }[]>([])\n const [failures, setFailures] = useState<{ key: string; text: string }[]>([])\n const [announcement, setAnnouncement] = useState('')\n const input = useRef<HTMLInputElement>(null)\n // The latest value, so uploads finishing one after another append to each other.\n const latest = useRef(value)\n latest.current = value\n // A reloaded record brings its stored files; keep summaries of files uploaded here too.\n const storedIds = (attachments ?? []).map((file) => file.id).join(',')\n useEffect(() => {\n if (!attachments?.length) return\n setKnown((current) => [\n ...attachments,\n ...current.filter((file) => !attachments.some((stored) => stored.id === file.id)),\n ])\n // The stored ids decide a re-sync; a new array with the same files changes nothing.\n }, [storedIds])\n const ids = listValue(value).map(Number)\n const fileOf = (fileId: number) => known.find((file) => file.id === fileId)\n const nameOf = (fileId: number) => fileOf(fileId)?.name ?? t('ملف رقم {id}', { id: fileId })\n const save = (next: number[]) => {\n latest.current = listInput(next)\n onChange(latest.current)\n }\n const fail = (text: string) =>\n setFailures((current) => [...current, { key: `${Date.now()}-${current.length}`, text }])\n const upload = async (file: File, key: string) => {\n const body = new FormData()\n body.append('file', file)\n if (resource) body.append('resource', resource)\n body.append('field', field.key)\n try {\n const response = await axios.post<{ data: AttachmentValue }>('/attachments', body, {\n headers: { Accept: 'application/json' },\n withXSRFToken: true,\n onUploadProgress: (event) =>\n setUploads((current) =>\n current.map((entry) =>\n entry.key === key\n ? {\n ...entry,\n progress: event.total ? Math.round((event.loaded / event.total) * 100) : 50,\n }\n : entry\n )\n ),\n })\n const stored = response.data.data\n setKnown((current) => [...current, stored])\n save([...listValue(latest.current).map(Number), stored.id])\n setAnnouncement(t('أُضيف الملف {name}', { name: stored.name }))\n } catch (caught) {\n fail(`${file.name}: ${uploadFailure(caught, t)}`)\n } finally {\n setUploads((current) => current.filter((entry) => entry.key !== key))\n }\n }\n const choose = async (chosen: File[]) => {\n setFailures([])\n if (input.current) input.current.value = ''\n const room = max - ids.length - uploads.length\n if (chosen.length > room) {\n fail(t('يمكن إرفاق {max} ملفات على الأكثر', { max }))\n return\n }\n const batch = chosen.map((file, index) => ({\n file,\n key: `${Date.now()}-${index}-${file.name}`,\n }))\n setUploads((current) => [\n ...current,\n ...batch.map(({ file, key }) => ({ key, name: file.name, progress: 0 })),\n ])\n // One after another, so the files keep the order they were chosen in.\n for (const { file, key } of batch) await upload(file, key)\n }\n // Moves and removals address the file by id, never by its position in a filtered list.\n const move = (fileId: number, offset: number) => {\n const from = ids.indexOf(fileId)\n const to = from + offset\n if (from < 0 || to < 0 || to >= ids.length) return\n const next = [...ids]\n next.splice(from, 1)\n next.splice(to, 0, fileId)\n save(next)\n setAnnouncement(\n t('نُقل الملف {name} إلى الموضع {position}', { name: nameOf(fileId), position: to + 1 })\n )\n }\n const remove = (fileId: number) => {\n save(ids.filter((entry) => entry !== fileId))\n setAnnouncement(t('أُزيل الملف {name}', { name: nameOf(fileId) }))\n }\n const busy = disabled || uploads.length > 0\n const name = label ?? localized(field.label)\n return (\n <div className=\"space-y-2\">\n <input\n ref={input}\n id={id}\n type=\"file\"\n multiple\n className=\"sr-only\"\n disabled={busy || ids.length >= max}\n aria-label={label}\n aria-describedby={error ? `${id}-error` : undefined}\n onChange={(event) => {\n const chosen = [...(event.target.files ?? [])]\n if (chosen.length) void choose(chosen)\n }}\n />\n {ids.length > 0 && (\n <ol className=\"divide-y rounded-md border bg-white text-sm\" aria-label={name}>\n {ids.map((fileId, index) => {\n const file = fileOf(fileId)\n const fileName = nameOf(fileId)\n return (\n <li key={fileId} className=\"flex flex-wrap items-center gap-2 px-3 py-2\">\n <Paperclip size={15} className=\"text-muted-foreground\" />\n {file ? (\n <>\n <a\n href={file.url}\n download={file.name}\n className=\"min-w-0 truncate text-primary underline-offset-4 hover:underline\"\n >\n {file.name}\n </a>\n <span className=\"text-xs text-muted-foreground\">\n {fileSize(file.size, t)}\n </span>\n </>\n ) : (\n <span className=\"text-muted-foreground\">{fileName}</span>\n )}\n <span className=\"ms-auto flex gap-1\">\n {file && <AttachmentPreviewButton file={file} disabled={disabled} />}\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon\"\n className=\"size-8\"\n disabled={busy || index === 0}\n aria-label={t('تقديم {name}', { name: fileName })}\n onClick={() => move(fileId, -1)}\n >\n <ArrowUp size={14} />\n </Button>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon\"\n className=\"size-8\"\n disabled={busy || index === ids.length - 1}\n aria-label={t('تأخير {name}', { name: fileName })}\n onClick={() => move(fileId, 1)}\n >\n <ArrowDown size={14} />\n </Button>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n disabled={busy}\n className=\"text-destructive\"\n aria-label={t('إزالة {name}', { name: fileName })}\n onClick={() => remove(fileId)}\n >\n <X size={14} />\n {t('إزالة')}\n </Button>\n </span>\n </li>\n )\n })}\n </ol>\n )}\n {uploads.map((entry) => (\n <div key={entry.key} className=\"space-y-1\">\n <p className=\"truncate text-xs text-muted-foreground\">\n {t('جارٍ رفع {name} {progress}%', { name: entry.name, progress: entry.progress })}\n </p>\n <div\n role=\"progressbar\"\n aria-valuemin={0}\n aria-valuemax={100}\n aria-valuenow={entry.progress}\n aria-label={t('رفع {field}', { field: entry.name })}\n className=\"h-1.5 w-full overflow-hidden rounded-full bg-muted\"\n >\n <div\n className=\"h-full bg-primary transition-all\"\n style={{ width: `${entry.progress}%` }}\n />\n </div>\n </div>\n ))}\n <div className=\"flex flex-wrap items-center gap-3\">\n <Button\n type=\"button\"\n variant=\"outline\"\n disabled={busy || ids.length >= max}\n onClick={() => input.current?.click()}\n >\n <Upload size={15} />\n {t('إضافة ملفات')}\n </Button>\n <span className=\"text-xs text-muted-foreground\">\n {t('{count} من {max} ملفات', { count: ids.length, max })}\n </span>\n </div>\n <p role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n {announcement}\n </p>\n {failures.map((failure) => (\n <p key={failure.key} role=\"alert\" className=\"text-xs text-destructive\">\n {failure.text}\n </p>\n ))}\n </div>\n )\n}\n\ntype OptionPage = { data: Option[]; nextCursor: string | null }\n/**\n * Server-side search through the authorized options route; keyset \"more\" keeps large\n * relations usable. A new search keeps the chosen records so their titles stay known.\n */\nfunction useRelationOptions(\n options: Option[],\n relation: RelationSource | undefined,\n chosen: string[]\n) {\n const { t } = useMessages()\n const [search, setSearch] = useState('')\n const [loaded, setLoaded] = useState<Option[]>(options)\n const [cursor, setCursor] = useState<string | null>(null)\n const [fetched, setFetched] = useState(false)\n const [failure, setFailure] = useState('')\n const timer = useRef<ReturnType<typeof setTimeout>>(undefined)\n const http = useHttp<Record<string, never>, OptionPage>({})\n const load = async (more: boolean, term = search) => {\n if (!relation) return\n setFailure('')\n const url = new URL(relation.url, window.location.origin)\n if (term && relation.searchable) url.searchParams.set('search', term)\n if (more && cursor) url.searchParams.set('cursor', cursor)\n try {\n const page = await http.get(url.pathname + url.search)\n if (!page) return\n setFetched(true)\n setCursor(page.nextCursor)\n setLoaded((previous) => {\n const keep = more ? previous : previous.filter((option) => chosen.includes(option.value))\n return [\n ...new Map([...keep, ...page.data].map((option) => [option.value, option])).values(),\n ]\n })\n } catch {\n setFailure(t('تعذر تحميل الخيارات'))\n }\n }\n useEffect(() => () => clearTimeout(timer.current), [])\n const searchable = Boolean(relation?.searchable)\n const find = (key: string) =>\n loaded.find((option) => option.value === key) ?? options.find((option) => option.value === key)\n const typed = (term: string) => {\n setSearch(term)\n if (!searchable) return\n clearTimeout(timer.current)\n timer.current = setTimeout(() => void load(false, term), 300)\n }\n const opened = () => {\n if (relation && !fetched) void load(false, '')\n }\n return { search, typed, loaded, cursor, failure, http, load, find, opened, searchable }\n}\n\nfunction RelationCombobox({\n id,\n value,\n onChange,\n disabled,\n error,\n field,\n label,\n options = [],\n relation,\n}: FieldProps) {\n const { t, label: localized } = useMessages()\n const [open, setOpen] = useState(false)\n const listId = useId()\n const { search, typed, loaded, cursor, failure, http, load, find, opened, searchable } =\n useRelationOptions(options, relation, value ? [value] : [])\n const current = find(value)\n return (\n <Popover\n open={open}\n onOpenChange={(next) => {\n setOpen(next)\n if (next) opened()\n }}\n >\n <PopoverTrigger asChild>\n <Button\n id={id}\n type=\"button\"\n role=\"combobox\"\n variant=\"outline\"\n aria-expanded={open}\n aria-controls={listId}\n aria-label={label}\n aria-invalid={error ? true : undefined}\n aria-describedby={error ? `${id}-error` : undefined}\n disabled={disabled}\n className={`h-10 w-full justify-between font-normal ${current ? '' : 'text-muted-foreground'}`}\n >\n <span className=\"truncate\">\n {current?.label ??\n (value ? `#${value}` : field.type === 'user' ? t('اختر مستخدماً') : t('اختر سجلاً'))}\n </span>\n <ChevronsUpDown className=\"opacity-50\" />\n </Button>\n </PopoverTrigger>\n <PopoverContent className=\"w-(--radix-popover-trigger-width) min-w-64 p-0\" align=\"start\">\n <Command shouldFilter={!searchable}>\n <CommandInput\n placeholder={\n field.type === 'user'\n ? t('ابحث بالاسم')\n : searchable\n ? t('ابحث في السجلات المرتبطة')\n : t('تصفية الخيارات')\n }\n aria-label={t('البحث في {field}', { field: label ?? localized(field.label) })}\n value={search}\n onValueChange={typed}\n />\n <CommandList id={listId}>\n <CommandEmpty>\n {http.processing ? t('جارٍ البحث...') : t('لا توجد سجلات مطابقة')}\n </CommandEmpty>\n <CommandGroup>\n {value && !field.required && (\n <CommandItem\n value=\"__none__\"\n onSelect={() => {\n onChange('')\n setOpen(false)\n }}\n >\n <X />\n {t('بدون اختيار')}\n </CommandItem>\n )}\n {loaded.map((option) => (\n <CommandItem\n key={option.value}\n value={option.value}\n keywords={[option.label]}\n onSelect={() => {\n onChange(option.value)\n setOpen(false)\n }}\n >\n <Check className={option.value === value ? 'opacity-100' : 'opacity-0'} />\n {option.label}\n </CommandItem>\n ))}\n </CommandGroup>\n {cursor && (\n <div className=\"border-t p-1\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"w-full\"\n disabled={http.processing}\n onClick={() => void load(true)}\n >\n {http.processing ? t('جارٍ التحميل...') : t('المزيد')}\n </Button>\n </div>\n )}\n {failure && (\n <p role=\"alert\" className=\"p-2 text-xs text-destructive\">\n {failure}\n </p>\n )}\n </CommandList>\n </Command>\n </PopoverContent>\n </Popover>\n )\n}\n\n/**\n * manyToMany: the same authorized options search as belongsTo, choosing several records.\n * Chosen records show as removable badges; the list stays open while picking.\n */\nfunction RelationMultiPicker({\n id,\n value,\n onChange,\n disabled,\n error,\n field,\n label,\n options = [],\n relation,\n}: FieldProps) {\n const { t, label: localized } = useMessages()\n const [open, setOpen] = useState(false)\n const listId = useId()\n const selected = listValue(value)\n const { search, typed, loaded, cursor, failure, http, load, find, opened, searchable } =\n useRelationOptions(options, relation, selected)\n const name = label ?? localized(field.label)\n const toggle = (key: string) =>\n onChange(\n listInput(\n selected.includes(key) ? selected.filter((entry) => entry !== key) : [...selected, key]\n )\n )\n return (\n <Popover\n open={open}\n onOpenChange={(next) => {\n setOpen(next)\n if (next) opened()\n }}\n >\n {/* The list anchors below the chosen badges, so it never covers them. */}\n <PopoverAnchor asChild>\n <div className=\"space-y-2\">\n <PopoverTrigger asChild>\n <Button\n id={id}\n type=\"button\"\n role=\"combobox\"\n variant=\"outline\"\n aria-expanded={open}\n aria-controls={listId}\n aria-label={label}\n aria-invalid={error ? true : undefined}\n aria-describedby={error ? `${id}-error` : undefined}\n disabled={disabled}\n className={`h-10 w-full justify-between font-normal ${selected.length ? '' : 'text-muted-foreground'}`}\n >\n <span className=\"truncate\">\n {selected.length\n ? t('{count} محدد', { count: selected.length })\n : t('اختر سجلاً أو أكثر')}\n </span>\n <ChevronsUpDown className=\"opacity-50\" />\n </Button>\n </PopoverTrigger>\n {selected.length > 0 && (\n <ul\n className=\"flex flex-wrap gap-1.5\"\n aria-label={t('المحدد في {field}', { field: name })}\n >\n {selected.map((key) => {\n const title = find(key)?.label ?? `#${key}`\n return (\n <li key={key}>\n <Badge variant=\"secondary\" className=\"gap-1 py-0.5 pe-0.5 font-normal\">\n {title}\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-xs\"\n className=\"size-5\"\n disabled={disabled}\n aria-label={t('إزالة {record}', { record: title })}\n onClick={() => toggle(key)}\n >\n <X />\n </Button>\n </Badge>\n </li>\n )\n })}\n </ul>\n )}\n </div>\n </PopoverAnchor>\n <PopoverContent className=\"w-(--radix-popper-anchor-width) min-w-64 p-0\" align=\"start\">\n <Command shouldFilter={!searchable}>\n <CommandInput\n placeholder={searchable ? t('ابحث في السجلات المرتبطة') : t('تصفية الخيارات')}\n aria-label={t('البحث في {field}', { field: name })}\n value={search}\n onValueChange={typed}\n />\n <CommandList id={listId}>\n <CommandEmpty>\n {http.processing ? t('جارٍ البحث...') : t('لا توجد سجلات مطابقة')}\n </CommandEmpty>\n <CommandGroup>\n {loaded.map((option) => (\n <CommandItem\n key={option.value}\n value={option.value}\n keywords={[option.label]}\n aria-checked={selected.includes(option.value)}\n onSelect={() => toggle(option.value)}\n >\n <Check\n className={selected.includes(option.value) ? 'opacity-100' : 'opacity-0'}\n />\n {option.label}\n </CommandItem>\n ))}\n </CommandGroup>\n {cursor && (\n <div className=\"border-t p-1\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"w-full\"\n disabled={http.processing}\n onClick={() => void load(true)}\n >\n {http.processing ? t('جارٍ التحميل...') : t('المزيد')}\n </Button>\n </div>\n )}\n {failure && (\n <p role=\"alert\" className=\"p-2 text-xs text-destructive\">\n {failure}\n </p>\n )}\n </CommandList>\n </Command>\n </PopoverContent>\n </Popover>\n )\n}\n\nlet rowSequence = 0\nexport function newInlineRow(fields: Field[]): InlineRow {\n rowSequence += 1\n return {\n key: `new-${rowSequence}`,\n values: Object.fromEntries(\n fields.map((field) => [field.key, field.type === 'boolean' ? 'false' : ''])\n ),\n dirty: true,\n }\n}\n\n/** Inline hasMany rows: new rows, versioned updates and explicit `_delete` markers in one editable table. */\nexport function InlineRows({\n field,\n inline,\n rows,\n onChange,\n errors = {},\n sectionError,\n disabled,\n resource,\n}: {\n field: Field\n inline: InlineDefinition\n rows: InlineRow[]\n onChange: (rows: InlineRow[]) => void\n errors?: Record<string, Record<string, string>>\n sectionError?: string\n disabled?: boolean\n resource: string\n}) {\n const update = (key: string, patch: Partial<InlineRow>) =>\n onChange(rows.map((row) => (row.key === key ? { ...row, ...patch } : row)))\n const editable = (row: InlineRow, key: string) =>\n row.id === undefined\n ? inline.createFields.includes(key)\n : Boolean(inline.permissions[String(row.id)]?.update) &&\n (inline.updateFields[String(row.id)] ?? []).includes(key)\n const { t, label } = useMessages()\n const live = rows.filter((row) => !row.deleted)\n // Row files upload for the child resource and field, which is what the child's own\n // write claims; a saved row shows its stored files (ADR 047).\n const childResource = (field as { resource?: string }).resource ?? resource\n const storedValue = (row: InlineRow, key: string) =>\n row.id === undefined\n ? undefined\n : inline.rows.find((entry) => String(entry.id) === String(row.id))?.[key]\n return (\n <section aria-label={label(field.label)} className=\"rounded-xl border bg-white\">\n <div className=\"flex flex-wrap items-center justify-between gap-3 border-b px-7 py-4\">\n <div>\n <h2 className=\"text-sm font-semibold\">{label(field.label)}</h2>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {live.length ? t('{count} بند', { count: live.length }) : t('لا توجد بنود بعد')}\n {inline.hasMore && ` · ${t('تظهر أول 100 بند فقط')}`}\n </p>\n </div>\n {inline.canCreate && (\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n disabled={disabled}\n onClick={() => onChange([...rows, newInlineRow(inline.fields)])}\n >\n <Plus size={15} />\n {t('إضافة بند')}\n </Button>\n )}\n </div>\n {sectionError && (\n <p role=\"alert\" className=\"border-b px-7 py-3 text-sm text-destructive\">\n {sectionError}\n </p>\n )}\n {rows.length > 0 && (\n <div className=\"overflow-x-auto\">\n <table className=\"w-full min-w-[560px] text-sm\">\n <thead className=\"bg-muted text-xs text-muted-foreground\">\n <tr>\n <th className=\"w-12 px-4 py-3 text-start font-medium\">#</th>\n {inline.fields.map((child) => (\n <th key={child.key} className=\"px-3 py-3 text-start font-medium\">\n {label(child.label)}\n {child.required && (\n <span className=\"text-destructive\" aria-hidden=\"true\">\n {' '}\n *\n </span>\n )}\n </th>\n ))}\n <th className=\"w-24 px-4 py-3 text-start font-medium\">\n <span className=\"sr-only\">{t('الإجراء')}</span>\n </th>\n </tr>\n </thead>\n <tbody>\n {rows.map((row, index) => {\n const number = index + 1\n const rowErrors = errors[row.key] ?? {}\n // A child whose visibleWhen does not hold in this row shows no control.\n const rowHidden = hiddenFields(inline.fields, row.values)\n return (\n <tr\n key={row.key}\n aria-label={t('بند {number}', { number })}\n className={`border-b align-top last:border-0 ${row.deleted ? 'bg-destructive/5 opacity-60' : ''}`}\n >\n <td className=\"px-4 py-3 tabular-nums text-muted-foreground\">{number}</td>\n {inline.fields.map((child) => (\n <td key={child.key} className=\"min-w-40 px-3 py-2\">\n {rowHidden.has(child.key) ? (\n <span className=\"text-muted-foreground\" aria-hidden=\"true\">\n —\n </span>\n ) : (\n <FieldControl\n field={child}\n id={`${field.key}-${row.key}-${child.key}`}\n label={t('{field} للبند {number}', { field: label(child.label), number })}\n value={row.values[child.key] ?? ''}\n disabled={disabled || row.deleted || !editable(row, child.key)}\n error={rowErrors[child.key]}\n resource={childResource}\n attachment={\n child.type === 'attachment' &&\n isAttachment(storedValue(row, child.key))\n ? (storedValue(row, child.key) as AttachmentValue)\n : null\n }\n attachments={\n child.type === 'attachment' &&\n Array.isArray(storedValue(row, child.key))\n ? (storedValue(row, child.key) as unknown[]).filter(isAttachment)\n : undefined\n }\n relation={\n child.type === 'belongsTo' || child.type === 'user'\n ? {\n url: `/resources/${(field as { resource?: string }).resource}/options/${child.key}`,\n searchable: child.type === 'user',\n }\n : undefined\n }\n onChange={(value) =>\n update(row.key, {\n values: { ...row.values, [child.key]: value },\n dirty: true,\n })\n }\n />\n )}\n {!rowHidden.has(child.key) && rowErrors[child.key] && (\n <p role=\"alert\" className=\"mt-1 text-xs text-destructive\">\n {rowErrors[child.key]}\n </p>\n )}\n </td>\n ))}\n <td className=\"px-4 py-2\">\n {row.id === undefined ? (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n disabled={disabled}\n aria-label={t('إزالة البند {number}', { number })}\n onClick={() => onChange(rows.filter((entry) => entry.key !== row.key))}\n >\n <Trash2 className=\"text-destructive\" />\n </Button>\n ) : inline.permissions[String(row.id)]?.delete ? (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n disabled={disabled}\n aria-label={\n row.deleted\n ? t('التراجع عن حذف البند {number}', { number })\n : t('حذف البند {number}', { number })\n }\n onClick={() => update(row.key, { deleted: !row.deleted })}\n >\n {row.deleted ? <Undo2 /> : <Trash2 className=\"text-destructive\" />}\n </Button>\n ) : null}\n </td>\n </tr>\n )\n })}\n </tbody>\n </table>\n </div>\n )}\n </section>\n )\n}\n",
33
+ "content": "import { useEffect, useId, useRef, useState, type ComponentProps } from 'react'\nimport { useHttp } from '@inertiajs/react'\nimport axios from 'axios'\nimport { format } from 'date-fns'\nimport {\n ArrowDown,\n ArrowUp,\n CalendarDays,\n Check,\n ChevronsUpDown,\n Paperclip,\n Plus,\n Trash2,\n Undo2,\n Upload,\n X,\n} from 'lucide-react'\nimport type { CalendarSystem, ResourceEditor, ResourceField as Field } from 'adula'\nimport { Badge } from '~/components/ui/badge'\nimport { UserAvatar } from '~/components/ui/user-avatar'\nimport { Button } from '~/components/ui/button'\nimport { Checkbox } from '~/components/ui/checkbox'\nimport { Calendar } from '~/components/ui/calendar'\nimport { HijriCalendar } from '~/components/ui/hijri-calendar'\nimport { calendarInput, calendarIso } from '~/components/ui/calendar_date'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\nimport { useMessages } from '~/components/ui/messages'\nimport { AttachmentPreviewButton } from '~/components/ui/attachment-preview'\nimport {\n Command,\n CommandEmpty,\n CommandGroup,\n CommandInput,\n CommandItem,\n CommandList,\n} from '~/components/ui/command'\nimport { Input } from '~/components/ui/input'\nimport { Label } from '~/components/ui/label'\nimport {\n Popover,\n PopoverAnchor,\n PopoverContent,\n PopoverTrigger,\n} from '~/components/ui/popover'\nimport { Switch } from '~/components/ui/switch'\nimport { Textarea } from '~/components/ui/textarea'\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from '~/components/ui/select'\nimport {\n decimalScale,\n foldedFilter,\n hiddenFields,\n listInput,\n listValue,\n orderedSelection,\n parseDecimal,\n} from '~/components/ui/field_values'\nimport {\n CURRENCY_LABEL,\n PERCENT_LABEL,\n fieldOptions,\n fileSize,\n isAttachment,\n moneyDisplay,\n moneyInput,\n parseMoney,\n toLatinDigits,\n type AttachmentValue,\n type Option,\n} from '~/components/ui/resource-value'\n\nexport type RelationSource = { url: string; searchable: boolean }\nexport type InlineDefinition = ResourceEditor['inline'][string]\nexport type InlineRow = {\n key: string\n id?: number\n version?: number\n values: Record<string, string>\n deleted?: boolean\n dirty?: boolean\n}\nexport type FieldProps = {\n field: Field\n id: string\n value: string\n onChange: (value: string) => void\n disabled?: boolean\n error?: string\n options?: Option[]\n relation?: RelationSource\n attachment?: AttachmentValue | null\n /** The stored files of a multiple attachment field, in order (ADR 047). */\n attachments?: AttachmentValue[]\n /** Resource name; attachment uploads are claimed against it. */\n resource?: string\n /** Accessible name when the visible label lives elsewhere, e.g. inline rows. */\n label?: string\n}\n/** Above this many choices a select offers a search box that folds Arabic letters (#114). */\nexport const SEARCHABLE_OPTIONS = 8\n\ntype ResourceSelectProps = Pick<\n ComponentProps<typeof SelectTrigger>,\n 'id' | 'aria-label' | 'aria-invalid' | 'aria-describedby'\n> & {\n value: string\n onChange: (value: string) => void\n options: Option[]\n placeholder?: string\n required?: boolean\n disabled?: boolean\n /** Trigger size and width; forms keep the default, toolbars pass a compact size. */\n className?: string\n}\n\nexport function ResourceSelect(props: ResourceSelectProps) {\n const {\n value,\n onChange,\n options,\n placeholder,\n required,\n disabled,\n className = 'h-10 w-full',\n ...trigger\n } = props\n const { t } = useMessages()\n const empty = placeholder ?? t('اختر قيمة')\n const choices = options.filter((option) => String(option.value) !== '')\n if (choices.length > SEARCHABLE_OPTIONS) return <SearchableSelect {...props} options={choices} />\n // Encode values so an empty selection cannot collide with a business lookup key.\n return (\n <Select\n value={`value:${value}`}\n onValueChange={(next) => onChange(next.slice(6))}\n required={required}\n disabled={disabled}\n >\n <SelectTrigger\n {...trigger}\n className={className}\n aria-required={required}\n // Radix prevents the pointer's focus; without it, text typed next lands in the previous field.\n onPointerDown={(event) => event.currentTarget.focus()}\n >\n <SelectValue placeholder={empty} />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value=\"value:\">{empty}</SelectItem>\n {choices.map((option) => (\n <SelectItem key={option.value} value={`value:${option.value}`}>\n {/* A code such as 12-3-ABC keeps its own order inside an RTL list (#113). */}\n <span dir=\"auto\">{option.label}</span>\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n )\n}\n\n/** A long list of choices: a combobox whose filter folds Arabic letter variants (#114). */\nfunction SearchableSelect({\n value,\n onChange,\n options,\n placeholder,\n required,\n disabled,\n className = 'h-10 w-full',\n ...trigger\n}: ResourceSelectProps) {\n const { t } = useMessages()\n const [open, setOpen] = useState(false)\n const [search, setSearch] = useState('')\n const input = useRef<HTMLInputElement>(null)\n const listId = useId()\n const empty = placeholder ?? t('اختر قيمة')\n const current = options.find((option) => String(option.value) === value)\n return (\n <Popover\n open={open}\n onOpenChange={(next) => {\n setOpen(next)\n if (!next) return\n // Reopened during its closing animation, the popover keeps its content: it neither\n // focuses the search box again nor clears the last search, so do both on every open.\n setSearch('')\n requestAnimationFrame(() => input.current?.focus())\n }}\n >\n <PopoverTrigger asChild>\n <Button\n {...trigger}\n type=\"button\"\n role=\"combobox\"\n variant=\"outline\"\n aria-expanded={open}\n aria-controls={listId}\n aria-required={required}\n disabled={disabled}\n className={`justify-between font-normal ${current ? '' : 'text-muted-foreground'} ${className}`}\n >\n <span className=\"truncate\" dir=\"auto\">\n {current?.label ?? empty}\n </span>\n <ChevronsUpDown className=\"opacity-50\" />\n </Button>\n </PopoverTrigger>\n <PopoverContent className=\"w-(--radix-popover-trigger-width) min-w-56 p-0\" align=\"start\">\n <Command filter={foldedFilter}>\n <CommandInput\n ref={input}\n value={search}\n onValueChange={setSearch}\n placeholder={t('تصفية الخيارات')}\n aria-label={t('تصفية الخيارات')}\n dir=\"auto\"\n />\n <CommandList id={listId}>\n <CommandEmpty>{t('لا توجد خيارات مطابقة')}</CommandEmpty>\n <CommandGroup>\n {value && !required && (\n <CommandItem\n value=\"__none__\"\n keywords={[empty]}\n onSelect={() => {\n onChange('')\n setOpen(false)\n }}\n >\n <X />\n {empty}\n </CommandItem>\n )}\n {options.map((option) => (\n <CommandItem\n key={option.value}\n value={`value:${option.value}`}\n keywords={[option.label]}\n onSelect={() => {\n onChange(String(option.value))\n setOpen(false)\n }}\n >\n <Check\n className={String(option.value) === value ? 'opacity-100' : 'opacity-0'}\n />\n <span dir=\"auto\">{option.label}</span>\n </CommandItem>\n ))}\n </CommandGroup>\n </CommandList>\n </Command>\n </PopoverContent>\n </Popover>\n )\n}\n\nexport function ResourceField(props: FieldProps) {\n const { field, id, error } = props\n const { label } = useMessages()\n return (\n <div\n className={`min-w-0 space-y-2 ${['text', 'json', 'manyToMany'].includes(field.type) ? 'md:col-span-2' : ''}`}\n >\n {/* The marker stays outside the label so the field's accessible name is the label alone. */}\n <div className=\"flex items-center gap-1\">\n <Label id={`${id}-label`} htmlFor={id}>\n {label(field.label)}\n </Label>\n {field.required && (\n <span className=\"text-destructive\" aria-hidden=\"true\">\n *\n </span>\n )}\n </div>\n <FieldControl {...props} />\n {error && (\n <p role=\"alert\" id={`${id}-error`} className=\"text-xs text-destructive\">\n {error}\n </p>\n )}\n </div>\n )\n}\n\nexport function FieldControl(props: FieldProps) {\n const { field, id, value, onChange, disabled, error, label } = props\n const { t, locale } = useMessages()\n const shared = {\n id,\n disabled,\n 'required': field.required,\n 'aria-label': label,\n 'aria-invalid': error ? true : undefined,\n 'aria-describedby': error ? `${id}-error` : undefined,\n }\n switch (field.type) {\n case 'belongsTo':\n case 'user':\n return <RelationCombobox {...props} />\n case 'manyToMany':\n return <RelationMultiPicker {...props} />\n case 'multiSelect':\n return <MultiSelectControl {...props} />\n case 'enum':\n return (\n <ResourceSelect\n {...shared}\n value={value}\n onChange={onChange}\n options={props.options ?? fieldOptions(field, locale)}\n />\n )\n case 'decimal':\n case 'percent':\n return <DecimalControl {...props} />\n case 'email':\n case 'phone':\n case 'url':\n case 'string': {\n // A string with `format` uses the same control as the dedicated type.\n const kind = field.type === 'string' ? field.format : field.type\n if (!kind) break\n return (\n <Input\n {...shared}\n type={kind === 'phone' ? 'tel' : kind}\n inputMode={kind === 'phone' ? 'tel' : kind}\n autoComplete={kind === 'url' ? 'url' : kind === 'email' ? 'email' : 'tel'}\n dir=\"ltr\"\n spellCheck={false}\n placeholder={\n kind === 'url' ? 'https://' : kind === 'email' ? 'name@example.com' : '+966 5x xxx xxxx'\n }\n className=\"h-10 text-start\"\n value={value}\n onChange={(event) => onChange(event.target.value)}\n />\n )\n }\n case 'lookup':\n return (\n <ResourceSelect\n {...shared}\n value={value}\n onChange={onChange}\n options={props.options ?? []}\n />\n )\n case 'boolean':\n return (\n <div className=\"flex h-10 items-center gap-3\">\n <Switch\n {...shared}\n required={undefined}\n checked={value === 'true'}\n onCheckedChange={(checked) => onChange(checked ? 'true' : 'false')}\n />\n <span className=\"text-sm text-muted-foreground\">\n {value === 'true' ? t('نعم') : t('لا')}\n </span>\n </div>\n )\n case 'attachment':\n return field.multiple ? (\n <MultipleAttachmentControl {...props} />\n ) : (\n <AttachmentControl {...props} />\n )\n case 'text':\n return (\n <Textarea\n {...shared}\n dir=\"auto\"\n rows={4}\n value={value}\n onChange={(event) => onChange(event.target.value)}\n />\n )\n case 'json':\n return <JsonControl {...props} />\n case 'money':\n return <MoneyControl {...props} />\n case 'date':\n return <DateControl {...props} />\n case 'datetime':\n return <DatetimeControl {...props} />\n case 'integer':\n return (\n <Input\n {...shared}\n type=\"number\"\n step={1}\n inputMode=\"numeric\"\n dir=\"ltr\"\n // One side for every number: integers align like decimal and money (#113).\n className=\"h-10 text-end tabular-nums\"\n value={value}\n onChange={(event) => onChange(event.target.value)}\n />\n )\n }\n return (\n <Input\n {...shared}\n type=\"text\"\n // A Latin code such as 12-3-ABC keeps its order in an RTL form (#113).\n dir=\"auto\"\n className=\"h-10\"\n value={value}\n onChange={(event) => onChange(event.target.value)}\n />\n )\n}\n\nfunction MoneyControl({ id, value, onChange, disabled, error, field, label }: FieldProps) {\n const { t } = useMessages()\n let preview = ''\n try {\n if (value) preview = moneyDisplay(parseMoney(value))\n } catch {\n preview = ''\n }\n return (\n <div className=\"space-y-1\">\n {/* LTR like the input, so the suffix and its padding share one physical side. */}\n <div className=\"relative\" dir=\"ltr\">\n <Input\n id={id}\n type=\"text\"\n inputMode=\"decimal\"\n dir=\"ltr\"\n placeholder=\"0.00\"\n className=\"h-10 pe-16 text-end tabular-nums\"\n value={value}\n disabled={disabled}\n required={field.required}\n aria-label={label}\n aria-invalid={error ? true : undefined}\n aria-describedby={error ? `${id}-error` : undefined}\n onChange={(event) => onChange(event.target.value)}\n onBlur={() => {\n try {\n if (value) onChange(moneyInput(parseMoney(value)))\n } catch {\n // Keep the typed text so the submit error can point at it.\n }\n }}\n />\n <span className=\"pointer-events-none absolute inset-y-0 end-3 flex items-center text-xs text-muted-foreground\">\n {t(CURRENCY_LABEL)}\n </span>\n </div>\n {preview && (\n <p className=\"text-xs text-muted-foreground\" dir=\"ltr\">\n {preview} {t(CURRENCY_LABEL)}\n </p>\n )}\n </div>\n )\n}\n\n/**\n * Decimal and percent entry: Arabic-Indic digits and the Arabic decimal separator are\n * accepted and normalized to the field's scale on blur; percent shows the ٪ suffix.\n */\nfunction DecimalControl({ id, value, onChange, disabled, error, field, label }: FieldProps) {\n const { t } = useMessages()\n const scale = decimalScale(field)\n const percent = field.type === 'percent'\n const hint = `${id}-hint`\n return (\n <div className=\"space-y-1\">\n {/* LTR like the input, so the suffix and its padding share one physical side. */}\n <div className=\"relative\" dir=\"ltr\">\n <Input\n id={id}\n type=\"text\"\n inputMode=\"decimal\"\n dir=\"ltr\"\n placeholder={scale ? `0.${'0'.repeat(scale)}` : '0'}\n className={`h-10 text-end tabular-nums ${percent ? 'pe-9' : ''}`}\n value={value}\n disabled={disabled}\n required={field.required}\n aria-label={label}\n aria-invalid={error ? true : undefined}\n aria-describedby={error ? `${id}-error ${hint}` : hint}\n onChange={(event) => onChange(event.target.value)}\n onBlur={() => {\n try {\n if (value) onChange(parseDecimal(value, scale))\n } catch {\n // Keep the typed text so the submit error can point at it.\n }\n }}\n />\n {percent && (\n <span className=\"pointer-events-none absolute inset-y-0 end-3 flex items-center text-sm text-muted-foreground\">\n {t(PERCENT_LABEL)}\n </span>\n )}\n </div>\n <p id={hint} className=\"text-xs text-muted-foreground\">\n {scale\n ? t('المنازل العشرية: {scale} على الأكثر', { scale })\n : t('عدد صحيح بلا منازل عشرية')}\n </p>\n </div>\n )\n}\n\n/** Every option as a checkbox in definition order; the value is stored in that order. */\nfunction MultiSelectControl({\n id,\n value,\n onChange,\n disabled,\n error,\n field,\n label,\n options,\n}: FieldProps) {\n const { t, label: localized, locale } = useMessages()\n const choices = options ?? fieldOptions(field, locale)\n const selected = listValue(value)\n const toggle = (option: string, checked: boolean) => {\n const next = checked ? [...selected, option] : selected.filter((entry) => entry !== option)\n onChange(listInput(orderedSelection(choices, next)))\n }\n const described = [error ? `${id}-error` : '', field.required ? `${id}-required` : '']\n .filter(Boolean)\n .join(' ')\n return (\n <div\n id={id}\n role=\"group\"\n // Named by the visible field label (ResourceField); inline rows pass their own name.\n aria-labelledby={label ? undefined : `${id}-label`}\n aria-label={label ?? localized(field.label)}\n aria-invalid={error ? true : undefined}\n aria-describedby={described || undefined}\n className=\"flex min-h-10 flex-wrap items-center gap-x-5 gap-y-2 rounded-md border px-3 py-2\"\n >\n {field.required && (\n <span id={`${id}-required`} className=\"sr-only\">\n {t('مطلوب')}\n </span>\n )}\n {choices.map((option) => {\n const optionId = `${id}-${option.value}`\n return (\n <div key={option.value} className=\"flex items-center gap-2\">\n <Checkbox\n id={optionId}\n checked={selected.includes(option.value)}\n disabled={disabled}\n onCheckedChange={(checked) => toggle(option.value, checked === true)}\n />\n <Label htmlFor={optionId} className=\"font-normal\">\n {option.label}\n </Label>\n </div>\n )\n })}\n </div>\n )\n}\n\nfunction DateControl({ id, value, onChange, disabled, error, field, label }: FieldProps) {\n const { calendar: preference } = useUiPreferences()\n const { t, label: localized } = useMessages()\n const name = label ?? localized(field.label)\n const [entryCalendar, setEntryCalendar] = useState<CalendarSystem>('gregory')\n const calendar = preference === 'both' ? entryCalendar : preference\n const [open, setOpen] = useState(false)\n let normalized = toLatinDigits(value)\n try {\n if (value.startsWith('hijri:')) normalized = calendarIso(value.slice(6), 'islamic-umalqura')\n } catch {\n normalized = ''\n }\n const displayed =\n calendar === 'islamic-umalqura'\n ? value.startsWith('hijri:')\n ? value.slice(6)\n : calendarInput(value, calendar)\n : normalized\n const selected = /^\\d{4}-\\d{2}-\\d{2}$/.test(normalized)\n ? new Date(`${normalized}T00:00:00`)\n : undefined\n const valid = selected !== undefined && !Number.isNaN(selected.getTime())\n return (\n <div className=\"space-y-1\">\n {preference === 'both' && (\n <div\n className=\"flex gap-1\"\n role=\"group\"\n aria-label={t('تقويم الإدخال: {field}', { field: name })}\n >\n <Button\n type=\"button\"\n size=\"sm\"\n variant={calendar === 'gregory' ? 'secondary' : 'ghost'}\n aria-pressed={calendar === 'gregory'}\n onClick={() => setEntryCalendar('gregory')}\n >\n {t('إدخال ميلادي')}\n </Button>\n <Button\n type=\"button\"\n size=\"sm\"\n variant={calendar === 'islamic-umalqura' ? 'secondary' : 'ghost'}\n aria-pressed={calendar === 'islamic-umalqura'}\n onClick={() => setEntryCalendar('islamic-umalqura')}\n >\n {t('إدخال هجري')}\n </Button>\n </div>\n )}\n <div className=\"flex gap-2\">\n <Input\n id={id}\n type=\"text\"\n inputMode=\"numeric\"\n dir=\"ltr\"\n // No sample date: digits read as a stored value, and bidi reorders mixed text (#113).\n placeholder={\n calendar === 'islamic-umalqura'\n ? t('اكتب التاريخ الهجري أو اختره')\n : t('اكتب التاريخ أو اختره')\n }\n className=\"h-10 tabular-nums\"\n value={displayed}\n disabled={disabled}\n required={field.required}\n aria-label={label}\n aria-invalid={error ? true : undefined}\n aria-describedby={error ? `${id}-error` : undefined}\n onChange={(event) =>\n onChange(\n calendar === 'islamic-umalqura' && event.target.value\n ? `hijri:${event.target.value}`\n : event.target.value\n )\n }\n />\n <Popover open={open} onOpenChange={setOpen}>\n <PopoverTrigger asChild>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"icon-lg\"\n disabled={disabled}\n aria-label={t('التقويم: {field}', { field: name })}\n >\n <CalendarDays />\n </Button>\n </PopoverTrigger>\n <PopoverContent className=\"w-auto p-0\" align=\"start\">\n {calendar === 'islamic-umalqura' ? (\n <HijriCalendar\n value={valid ? normalized : ''}\n onSelect={(iso) => {\n onChange(iso)\n setOpen(false)\n }}\n />\n ) : (\n <Calendar\n mode=\"single\"\n selected={valid ? selected : undefined}\n defaultMonth={valid ? selected : undefined}\n onSelect={(date) => {\n onChange(date ? format(date, 'yyyy-MM-dd') : '')\n setOpen(false)\n }}\n />\n )}\n </PopoverContent>\n </Popover>\n </div>\n {calendar === 'islamic-umalqura' && (\n <p className=\"text-xs text-muted-foreground\">\n {t('هجري · أم القرى')}{' '}\n {valid && <span dir=\"ltr\">{t('({date} ميلادي)', { date: normalized })}</span>}\n </p>\n )}\n {preference === 'both' && calendar === 'gregory' && valid && (\n <p className=\"text-xs text-muted-foreground\" aria-live=\"polite\">\n {t('الموافق هجريًا:')}{' '}\n <span dir=\"ltr\">{calendarInput(normalized, 'islamic-umalqura')}</span> {t('هـ')}\n </p>\n )}\n </div>\n )\n}\n\nfunction DatetimeControl(props: FieldProps) {\n const { calendar } = useUiPreferences()\n const { t, label } = useMessages()\n if (calendar === 'gregory')\n return (\n <Input\n id={props.id}\n type=\"datetime-local\"\n dir=\"ltr\"\n className=\"h-10\"\n value={props.value}\n disabled={props.disabled}\n required={props.field.required}\n aria-label={props.label}\n aria-invalid={Boolean(props.error)}\n onChange={(event) => props.onChange(event.target.value)}\n />\n )\n const [date, time = '00:00'] = props.value.split('T')\n return (\n <div className=\"space-y-2\">\n <DateControl\n {...props}\n value={date}\n onChange={(next) => props.onChange(next ? `${next}T${time}` : '')}\n />\n <Input\n type=\"time\"\n dir=\"ltr\"\n aria-label={t('الوقت: {field}', { field: props.label ?? label(props.field.label) })}\n value={time}\n disabled={props.disabled}\n onChange={(event) => props.onChange(`${date}T${event.target.value}`)}\n />\n </div>\n )\n}\n\nfunction JsonControl({ id, value, onChange, disabled, error, field, label }: FieldProps) {\n const { t } = useMessages()\n const [invalid, setInvalid] = useState('')\n const check = () => {\n if (!value.trim()) return setInvalid('')\n try {\n JSON.parse(value)\n setInvalid('')\n } catch {\n setInvalid(t('أدخل بيانات JSON صحيحة'))\n }\n }\n return (\n <div className=\"space-y-2\">\n <Textarea\n id={id}\n dir=\"ltr\"\n rows={6}\n spellCheck={false}\n className=\"font-mono text-xs\"\n value={value}\n disabled={disabled}\n required={field.required}\n aria-label={label}\n aria-invalid={error || invalid ? true : undefined}\n aria-describedby={error ? `${id}-error` : undefined}\n onChange={(event) => onChange(event.target.value)}\n onBlur={check}\n />\n <div className=\"flex items-center gap-3\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n disabled={disabled || !value.trim()}\n onClick={() => {\n try {\n onChange(JSON.stringify(JSON.parse(value), null, 2))\n setInvalid('')\n } catch {\n setInvalid(t('أدخل بيانات JSON صحيحة'))\n }\n }}\n >\n {t('تنسيق JSON')}\n </Button>\n {invalid && !error && (\n <p role=\"alert\" className=\"text-xs text-destructive\">\n {invalid}\n </p>\n )}\n </div>\n </div>\n )\n}\n\n/** Uploads on selection so the saved record only references an already-owned attachment id. */\nfunction AttachmentControl({\n id,\n value,\n onChange,\n disabled,\n error,\n field,\n label,\n attachment,\n resource,\n}: FieldProps) {\n const { t, label: localized } = useMessages()\n const [current, setCurrent] = useState<AttachmentValue | null>(attachment ?? null)\n const [progress, setProgress] = useState<number | null>(null)\n const [failure, setFailure] = useState('')\n const input = useRef<HTMLInputElement>(null)\n const upload = async (file: File) => {\n setFailure('')\n setProgress(0)\n const body = new FormData()\n body.append('file', file)\n if (resource) body.append('resource', resource)\n body.append('field', field.key)\n try {\n const response = await axios.post<{ data: AttachmentValue }>('/attachments', body, {\n headers: { Accept: 'application/json' },\n withXSRFToken: true,\n onUploadProgress: (event) =>\n setProgress(event.total ? Math.round((event.loaded / event.total) * 100) : 50),\n })\n setCurrent(response.data.data)\n onChange(String(response.data.data.id))\n } catch (caught) {\n setFailure(\n axios.isAxiosError(caught)\n ? (caught.response?.data?.error?.message ?? t('تعذر رفع الملف. حاول مجدداً.'))\n : t('تعذر الاتصال بالخادم.')\n )\n } finally {\n setProgress(null)\n if (input.current) input.current.value = ''\n }\n }\n const shown = value && current && String(current.id) === value ? current : null\n return (\n <div className=\"space-y-2\">\n <input\n ref={input}\n id={id}\n type=\"file\"\n className=\"sr-only\"\n disabled={disabled || progress !== null}\n aria-label={label}\n aria-describedby={error ? `${id}-error` : undefined}\n onChange={(event) => {\n const file = event.target.files?.[0]\n if (file) void upload(file)\n }}\n />\n {shown ? (\n <div className=\"flex flex-wrap items-center gap-3 rounded-md border bg-card px-3 py-2 text-sm\">\n <Paperclip size={15} className=\"text-muted-foreground\" />\n <a\n href={shown.url}\n download={shown.name}\n className=\"text-primary underline-offset-4 hover:underline\"\n >\n {shown.name}\n </a>\n <span className=\"text-xs text-muted-foreground\">{fileSize(shown.size, t)}</span>\n <span className=\"ms-auto flex gap-1\">\n <AttachmentPreviewButton file={shown} disabled={disabled} />\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n disabled={disabled}\n onClick={() => input.current?.click()}\n >\n <Upload size={14} />\n {t('استبدال')}\n </Button>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n disabled={disabled}\n className=\"text-destructive\"\n onClick={() => onChange('')}\n >\n <X size={14} />\n {t('إزالة')}\n </Button>\n </span>\n </div>\n ) : (\n <Button\n type=\"button\"\n variant=\"outline\"\n disabled={disabled || progress !== null}\n onClick={() => input.current?.click()}\n >\n <Upload size={15} />\n {progress === null ? t('اختيار ملف') : t('جارٍ الرفع {progress}%', { progress })}\n </Button>\n )}\n {progress !== null && (\n <div\n role=\"progressbar\"\n aria-valuemin={0}\n aria-valuemax={100}\n aria-valuenow={progress}\n aria-label={t('رفع {field}', { field: label ?? localized(field.label) })}\n className=\"h-1.5 w-full overflow-hidden rounded-full bg-muted\"\n >\n <div className=\"h-full bg-primary transition-all\" style={{ width: `${progress}%` }} />\n </div>\n )}\n {failure && (\n <p role=\"alert\" className=\"text-xs text-destructive\">\n {failure}\n </p>\n )}\n </div>\n )\n}\n\n/** The upload failure as the server worded it, or a generic Arabic message. */\nfunction uploadFailure(caught: unknown, t: ReturnType<typeof useMessages>['t']) {\n return axios.isAxiosError(caught)\n ? (caught.response?.data?.error?.message ?? t('تعذر رفع الملف. حاول مجدداً.'))\n : t('تعذر الاتصال بالخادم.')\n}\n\n/**\n * Several files for one field: each selected file uploads on its own (with its own\n * progress) and joins the ordered list; files can be moved, removed and previewed. The\n * value is the JSON array of attachment ids the record saves; the server checks every\n * limit again.\n */\nfunction MultipleAttachmentControl({\n id,\n value,\n onChange,\n disabled,\n error,\n field,\n label,\n attachments,\n resource,\n}: FieldProps) {\n const { t, label: localized } = useMessages()\n // The editor sends the resolved limit; 10 is AdulaJS's default for older payloads.\n const max = field.type === 'attachment' ? (field.max ?? 10) : 10\n const [known, setKnown] = useState<AttachmentValue[]>(attachments ?? [])\n const [uploads, setUploads] = useState<{ key: string; name: string; progress: number }[]>([])\n const [failures, setFailures] = useState<{ key: string; text: string }[]>([])\n const [announcement, setAnnouncement] = useState('')\n const input = useRef<HTMLInputElement>(null)\n // The latest value, so uploads finishing one after another append to each other.\n const latest = useRef(value)\n latest.current = value\n // A reloaded record brings its stored files; keep summaries of files uploaded here too.\n const storedIds = (attachments ?? []).map((file) => file.id).join(',')\n useEffect(() => {\n if (!attachments?.length) return\n setKnown((current) => [\n ...attachments,\n ...current.filter((file) => !attachments.some((stored) => stored.id === file.id)),\n ])\n // The stored ids decide a re-sync; a new array with the same files changes nothing.\n }, [storedIds])\n const ids = listValue(value).map(Number)\n const fileOf = (fileId: number) => known.find((file) => file.id === fileId)\n const nameOf = (fileId: number) => fileOf(fileId)?.name ?? t('ملف رقم {id}', { id: fileId })\n const save = (next: number[]) => {\n latest.current = listInput(next)\n onChange(latest.current)\n }\n const fail = (text: string) =>\n setFailures((current) => [...current, { key: `${Date.now()}-${current.length}`, text }])\n const upload = async (file: File, key: string) => {\n const body = new FormData()\n body.append('file', file)\n if (resource) body.append('resource', resource)\n body.append('field', field.key)\n try {\n const response = await axios.post<{ data: AttachmentValue }>('/attachments', body, {\n headers: { Accept: 'application/json' },\n withXSRFToken: true,\n onUploadProgress: (event) =>\n setUploads((current) =>\n current.map((entry) =>\n entry.key === key\n ? {\n ...entry,\n progress: event.total ? Math.round((event.loaded / event.total) * 100) : 50,\n }\n : entry\n )\n ),\n })\n const stored = response.data.data\n setKnown((current) => [...current, stored])\n save([...listValue(latest.current).map(Number), stored.id])\n setAnnouncement(t('أُضيف الملف {name}', { name: stored.name }))\n } catch (caught) {\n fail(`${file.name}: ${uploadFailure(caught, t)}`)\n } finally {\n setUploads((current) => current.filter((entry) => entry.key !== key))\n }\n }\n const choose = async (chosen: File[]) => {\n setFailures([])\n if (input.current) input.current.value = ''\n const room = max - ids.length - uploads.length\n if (chosen.length > room) {\n fail(t('يمكن إرفاق {max} ملفات على الأكثر', { max }))\n return\n }\n const batch = chosen.map((file, index) => ({\n file,\n key: `${Date.now()}-${index}-${file.name}`,\n }))\n setUploads((current) => [\n ...current,\n ...batch.map(({ file, key }) => ({ key, name: file.name, progress: 0 })),\n ])\n // One after another, so the files keep the order they were chosen in.\n for (const { file, key } of batch) await upload(file, key)\n }\n // Moves and removals address the file by id, never by its position in a filtered list.\n const move = (fileId: number, offset: number) => {\n const from = ids.indexOf(fileId)\n const to = from + offset\n if (from < 0 || to < 0 || to >= ids.length) return\n const next = [...ids]\n next.splice(from, 1)\n next.splice(to, 0, fileId)\n save(next)\n setAnnouncement(\n t('نُقل الملف {name} إلى الموضع {position}', { name: nameOf(fileId), position: to + 1 })\n )\n }\n const remove = (fileId: number) => {\n save(ids.filter((entry) => entry !== fileId))\n setAnnouncement(t('أُزيل الملف {name}', { name: nameOf(fileId) }))\n }\n const busy = disabled || uploads.length > 0\n const name = label ?? localized(field.label)\n return (\n <div className=\"space-y-2\">\n <input\n ref={input}\n id={id}\n type=\"file\"\n multiple\n className=\"sr-only\"\n disabled={busy || ids.length >= max}\n aria-label={label}\n aria-describedby={error ? `${id}-error` : undefined}\n onChange={(event) => {\n const chosen = [...(event.target.files ?? [])]\n if (chosen.length) void choose(chosen)\n }}\n />\n {ids.length > 0 && (\n <ol className=\"divide-y rounded-md border bg-card text-sm\" aria-label={name}>\n {ids.map((fileId, index) => {\n const file = fileOf(fileId)\n const fileName = nameOf(fileId)\n return (\n <li key={fileId} className=\"flex flex-wrap items-center gap-2 px-3 py-2\">\n <Paperclip size={15} className=\"text-muted-foreground\" />\n {file ? (\n <>\n <a\n href={file.url}\n download={file.name}\n className=\"min-w-0 truncate text-primary underline-offset-4 hover:underline\"\n >\n {file.name}\n </a>\n <span className=\"text-xs text-muted-foreground\">\n {fileSize(file.size, t)}\n </span>\n </>\n ) : (\n <span className=\"text-muted-foreground\">{fileName}</span>\n )}\n <span className=\"ms-auto flex gap-1\">\n {file && <AttachmentPreviewButton file={file} disabled={disabled} />}\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n disabled={busy || index === 0}\n aria-label={t('تقديم {name}', { name: fileName })}\n onClick={() => move(fileId, -1)}\n >\n <ArrowUp size={14} />\n </Button>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n disabled={busy || index === ids.length - 1}\n aria-label={t('تأخير {name}', { name: fileName })}\n onClick={() => move(fileId, 1)}\n >\n <ArrowDown size={14} />\n </Button>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n disabled={busy}\n className=\"text-destructive\"\n aria-label={t('إزالة {name}', { name: fileName })}\n onClick={() => remove(fileId)}\n >\n <X size={14} />\n {t('إزالة')}\n </Button>\n </span>\n </li>\n )\n })}\n </ol>\n )}\n {uploads.map((entry) => (\n <div key={entry.key} className=\"space-y-1\">\n <p className=\"truncate text-xs text-muted-foreground\">\n {t('جارٍ رفع {name} {progress}%', { name: entry.name, progress: entry.progress })}\n </p>\n <div\n role=\"progressbar\"\n aria-valuemin={0}\n aria-valuemax={100}\n aria-valuenow={entry.progress}\n aria-label={t('رفع {field}', { field: entry.name })}\n className=\"h-1.5 w-full overflow-hidden rounded-full bg-muted\"\n >\n <div\n className=\"h-full bg-primary transition-all\"\n style={{ width: `${entry.progress}%` }}\n />\n </div>\n </div>\n ))}\n <div className=\"flex flex-wrap items-center gap-3\">\n <Button\n type=\"button\"\n variant=\"outline\"\n disabled={busy || ids.length >= max}\n onClick={() => input.current?.click()}\n >\n <Upload size={15} />\n {t('إضافة ملفات')}\n </Button>\n <span className=\"text-xs text-muted-foreground\">\n {t('{count} من {max} ملفات', { count: ids.length, max })}\n </span>\n </div>\n <p role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n {announcement}\n </p>\n {failures.map((failure) => (\n <p key={failure.key} role=\"alert\" className=\"text-xs text-destructive\">\n {failure.text}\n </p>\n ))}\n </div>\n )\n}\n\ntype OptionPage = { data: Option[]; nextCursor: string | null }\n/**\n * Server-side search through the authorized options route; keyset \"more\" keeps large\n * relations usable. A new search keeps the chosen records so their titles stay known.\n */\nfunction useRelationOptions(\n options: Option[],\n relation: RelationSource | undefined,\n chosen: string[]\n) {\n const { t } = useMessages()\n const [search, setSearch] = useState('')\n const [loaded, setLoaded] = useState<Option[]>(options)\n const [cursor, setCursor] = useState<string | null>(null)\n const [fetched, setFetched] = useState(false)\n const [failure, setFailure] = useState('')\n const timer = useRef<ReturnType<typeof setTimeout>>(undefined)\n const http = useHttp<Record<string, never>, OptionPage>({})\n const load = async (more: boolean, term = search) => {\n if (!relation) return\n setFailure('')\n const url = new URL(relation.url, window.location.origin)\n if (term && relation.searchable) url.searchParams.set('search', term)\n if (more && cursor) url.searchParams.set('cursor', cursor)\n try {\n const page = await http.get(url.pathname + url.search)\n if (!page) return\n setFetched(true)\n setCursor(page.nextCursor)\n setLoaded((previous) => {\n const keep = more ? previous : previous.filter((option) => chosen.includes(option.value))\n return [\n ...new Map([...keep, ...page.data].map((option) => [option.value, option])).values(),\n ]\n })\n } catch {\n setFailure(t('تعذر تحميل الخيارات'))\n }\n }\n useEffect(() => () => clearTimeout(timer.current), [])\n const searchable = Boolean(relation?.searchable)\n const find = (key: string) =>\n loaded.find((option) => option.value === key) ?? options.find((option) => option.value === key)\n const typed = (term: string) => {\n setSearch(term)\n if (!searchable) return\n clearTimeout(timer.current)\n timer.current = setTimeout(() => void load(false, term), 300)\n }\n const opened = () => {\n if (relation && !fetched) void load(false, '')\n }\n return { search, typed, loaded, cursor, failure, http, load, find, opened, searchable }\n}\n\nfunction RelationCombobox({\n id,\n value,\n onChange,\n disabled,\n error,\n field,\n label,\n options = [],\n relation,\n}: FieldProps) {\n const { t, label: localized } = useMessages()\n const [open, setOpen] = useState(false)\n const listId = useId()\n const { search, typed, loaded, cursor, failure, http, load, find, opened, searchable } =\n useRelationOptions(options, relation, value ? [value] : [])\n const current = find(value)\n return (\n <Popover\n open={open}\n onOpenChange={(next) => {\n setOpen(next)\n if (next) opened()\n }}\n >\n <PopoverTrigger asChild>\n <Button\n id={id}\n type=\"button\"\n role=\"combobox\"\n variant=\"outline\"\n aria-expanded={open}\n aria-controls={listId}\n aria-label={label}\n aria-invalid={error ? true : undefined}\n aria-describedby={error ? `${id}-error` : undefined}\n disabled={disabled}\n className={`h-10 w-full justify-between font-normal ${current ? '' : 'text-muted-foreground'}`}\n >\n <span className=\"flex min-w-0 items-center gap-2\">\n {field.type === 'user' && current && /^\\d+$/.test(current.value) ? (\n <UserAvatar\n user={{\n id: Number(current.value),\n name: current.label,\n avatarUrl: current.avatarUrl,\n }}\n size=\"sm\"\n />\n ) : null}\n <span className=\"truncate\" dir=\"auto\">\n {current?.label ??\n (value ? `#${value}` : field.type === 'user' ? t('اختر مستخدماً') : t('اختر سجلاً'))}\n </span>\n </span>\n <ChevronsUpDown className=\"opacity-50\" />\n </Button>\n </PopoverTrigger>\n <PopoverContent className=\"w-(--radix-popover-trigger-width) min-w-64 p-0\" align=\"start\">\n <Command shouldFilter={!searchable} filter={foldedFilter}>\n <CommandInput\n placeholder={\n field.type === 'user'\n ? t('ابحث بالاسم')\n : searchable\n ? t('ابحث في السجلات المرتبطة')\n : t('تصفية الخيارات')\n }\n aria-label={t('البحث في {field}', { field: label ?? localized(field.label) })}\n value={search}\n onValueChange={typed}\n />\n <CommandList id={listId}>\n <CommandEmpty>\n {http.processing ? t('جارٍ البحث...') : t('لا توجد سجلات مطابقة')}\n </CommandEmpty>\n <CommandGroup>\n {value && !field.required && (\n <CommandItem\n value=\"__none__\"\n onSelect={() => {\n onChange('')\n setOpen(false)\n }}\n >\n <X />\n {t('بدون اختيار')}\n </CommandItem>\n )}\n {loaded.map((option) => (\n <CommandItem\n key={option.value}\n value={option.value}\n keywords={[option.label]}\n onSelect={() => {\n onChange(option.value)\n setOpen(false)\n }}\n >\n <Check className={option.value === value ? 'opacity-100' : 'opacity-0'} />\n {field.type === 'user' && /^\\d+$/.test(option.value) ? (\n <UserAvatar\n user={{\n id: Number(option.value),\n name: option.label,\n avatarUrl: option.avatarUrl,\n }}\n size=\"xs\"\n />\n ) : null}\n <span dir=\"auto\">{option.label}</span>\n </CommandItem>\n ))}\n </CommandGroup>\n {cursor && (\n <div className=\"border-t p-1\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"w-full\"\n disabled={http.processing}\n onClick={() => void load(true)}\n >\n {http.processing ? t('جارٍ التحميل...') : t('المزيد')}\n </Button>\n </div>\n )}\n {failure && (\n <p role=\"alert\" className=\"p-2 text-xs text-destructive\">\n {failure}\n </p>\n )}\n </CommandList>\n </Command>\n </PopoverContent>\n </Popover>\n )\n}\n\n/**\n * manyToMany: the same authorized options search as belongsTo, choosing several records.\n * Chosen records show as removable badges; the list stays open while picking.\n */\nfunction RelationMultiPicker({\n id,\n value,\n onChange,\n disabled,\n error,\n field,\n label,\n options = [],\n relation,\n}: FieldProps) {\n const { t, label: localized } = useMessages()\n const [open, setOpen] = useState(false)\n const listId = useId()\n const selected = listValue(value)\n const { search, typed, loaded, cursor, failure, http, load, find, opened, searchable } =\n useRelationOptions(options, relation, selected)\n const name = label ?? localized(field.label)\n const toggle = (key: string) =>\n onChange(\n listInput(\n selected.includes(key) ? selected.filter((entry) => entry !== key) : [...selected, key]\n )\n )\n return (\n <Popover\n open={open}\n onOpenChange={(next) => {\n setOpen(next)\n if (next) opened()\n }}\n >\n {/* The list anchors below the chosen badges, so it never covers them. */}\n <PopoverAnchor asChild>\n <div className=\"space-y-2\">\n <PopoverTrigger asChild>\n <Button\n id={id}\n type=\"button\"\n role=\"combobox\"\n variant=\"outline\"\n aria-expanded={open}\n aria-controls={listId}\n aria-label={label}\n aria-invalid={error ? true : undefined}\n aria-describedby={error ? `${id}-error` : undefined}\n disabled={disabled}\n className={`h-10 w-full justify-between font-normal ${selected.length ? '' : 'text-muted-foreground'}`}\n >\n <span className=\"truncate\" dir=\"auto\">\n {selected.length\n ? t('{count} محدد', { count: selected.length })\n : t('اختر سجلاً أو أكثر')}\n </span>\n <ChevronsUpDown className=\"opacity-50\" />\n </Button>\n </PopoverTrigger>\n {selected.length > 0 && (\n <ul\n className=\"flex flex-wrap gap-1.5\"\n aria-label={t('المحدد في {field}', { field: name })}\n >\n {selected.map((key) => {\n const title = find(key)?.label ?? `#${key}`\n return (\n <li key={key}>\n <Badge variant=\"secondary\" className=\"gap-1 py-0.5 pe-0.5 font-normal\">\n {title}\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-xs\"\n disabled={disabled}\n aria-label={t('إزالة {record}', { record: title })}\n onClick={() => toggle(key)}\n >\n <X />\n </Button>\n </Badge>\n </li>\n )\n })}\n </ul>\n )}\n </div>\n </PopoverAnchor>\n <PopoverContent className=\"w-(--radix-popper-anchor-width) min-w-64 p-0\" align=\"start\">\n <Command shouldFilter={!searchable} filter={foldedFilter}>\n <CommandInput\n placeholder={searchable ? t('ابحث في السجلات المرتبطة') : t('تصفية الخيارات')}\n aria-label={t('البحث في {field}', { field: name })}\n value={search}\n onValueChange={typed}\n />\n <CommandList id={listId}>\n <CommandEmpty>\n {http.processing ? t('جارٍ البحث...') : t('لا توجد سجلات مطابقة')}\n </CommandEmpty>\n <CommandGroup>\n {loaded.map((option) => (\n <CommandItem\n key={option.value}\n value={option.value}\n keywords={[option.label]}\n aria-checked={selected.includes(option.value)}\n onSelect={() => toggle(option.value)}\n >\n <Check\n className={selected.includes(option.value) ? 'opacity-100' : 'opacity-0'}\n />\n <span dir=\"auto\">{option.label}</span>\n </CommandItem>\n ))}\n </CommandGroup>\n {cursor && (\n <div className=\"border-t p-1\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"w-full\"\n disabled={http.processing}\n onClick={() => void load(true)}\n >\n {http.processing ? t('جارٍ التحميل...') : t('المزيد')}\n </Button>\n </div>\n )}\n {failure && (\n <p role=\"alert\" className=\"p-2 text-xs text-destructive\">\n {failure}\n </p>\n )}\n </CommandList>\n </Command>\n </PopoverContent>\n </Popover>\n )\n}\n\nlet rowSequence = 0\nexport function newInlineRow(fields: Field[]): InlineRow {\n rowSequence += 1\n return {\n key: `new-${rowSequence}`,\n values: Object.fromEntries(\n fields.map((field) => [field.key, field.type === 'boolean' ? 'false' : ''])\n ),\n dirty: true,\n }\n}\n\n/** Inline hasMany rows: new rows, versioned updates and explicit `_delete` markers in one editable table. */\nexport function InlineRows({\n field,\n inline,\n rows,\n onChange,\n errors = {},\n sectionError,\n disabled,\n resource,\n}: {\n field: Field\n inline: InlineDefinition\n rows: InlineRow[]\n onChange: (rows: InlineRow[]) => void\n errors?: Record<string, Record<string, string>>\n sectionError?: string\n disabled?: boolean\n resource: string\n}) {\n const update = (key: string, patch: Partial<InlineRow>) =>\n onChange(rows.map((row) => (row.key === key ? { ...row, ...patch } : row)))\n const editable = (row: InlineRow, key: string) =>\n row.id === undefined\n ? inline.createFields.includes(key)\n : Boolean(inline.permissions[String(row.id)]?.update) &&\n (inline.updateFields[String(row.id)] ?? []).includes(key)\n const { t, label } = useMessages()\n const live = rows.filter((row) => !row.deleted)\n // Row files upload for the child resource and field, which is what the child's own\n // write claims; a saved row shows its stored files (ADR 047).\n const childResource = (field as { resource?: string }).resource ?? resource\n const storedValue = (row: InlineRow, key: string) =>\n row.id === undefined\n ? undefined\n : inline.rows.find((entry) => String(entry.id) === String(row.id))?.[key]\n return (\n <section aria-label={label(field.label)} className=\"rounded-xl border bg-card\">\n <div className=\"flex flex-wrap items-center justify-between gap-3 border-b px-7 py-4\">\n <div>\n <h2 className=\"text-sm font-semibold\">{label(field.label)}</h2>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {live.length ? t('{count} بند', { count: live.length }) : t('لا توجد بنود بعد')}\n {inline.hasMore && ` · ${t('تظهر أول 100 بند فقط')}`}\n </p>\n </div>\n {inline.canCreate && (\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n disabled={disabled}\n onClick={() => onChange([...rows, newInlineRow(inline.fields)])}\n >\n <Plus size={15} />\n {t('إضافة بند')}\n </Button>\n )}\n </div>\n {sectionError && (\n <p role=\"alert\" className=\"border-b px-7 py-3 text-sm text-destructive\">\n {sectionError}\n </p>\n )}\n {rows.length > 0 && (\n <div className=\"overflow-x-auto\">\n <table className=\"w-full min-w-[560px] text-sm\">\n <thead className=\"bg-muted text-xs text-muted-foreground\">\n <tr>\n <th className=\"w-12 px-4 py-3 text-start font-medium\">#</th>\n {inline.fields.map((child) => (\n <th key={child.key} className=\"px-3 py-3 text-start font-medium\">\n {label(child.label)}\n {child.required && (\n <span className=\"text-destructive\" aria-hidden=\"true\">\n {' '}\n *\n </span>\n )}\n </th>\n ))}\n <th className=\"w-24 px-4 py-3 text-start font-medium\">\n <span className=\"sr-only\">{t('الإجراء')}</span>\n </th>\n </tr>\n </thead>\n <tbody>\n {rows.map((row, index) => {\n const number = index + 1\n const rowErrors = errors[row.key] ?? {}\n // A child whose visibleWhen does not hold in this row shows no control.\n const rowHidden = hiddenFields(inline.fields, row.values)\n return (\n <tr\n key={row.key}\n aria-label={t('بند {number}', { number })}\n className={`border-b align-top last:border-0 ${row.deleted ? 'bg-destructive/5 opacity-60' : ''}`}\n >\n <td className=\"px-4 py-3 tabular-nums text-muted-foreground\">{number}</td>\n {inline.fields.map((child) => (\n <td key={child.key} className=\"min-w-40 px-3 py-2\">\n {rowHidden.has(child.key) ? (\n <span className=\"text-muted-foreground\" aria-hidden=\"true\">\n —\n </span>\n ) : (\n <FieldControl\n field={child}\n id={`${field.key}-${row.key}-${child.key}`}\n label={t('{field} للبند {number}', { field: label(child.label), number })}\n value={row.values[child.key] ?? ''}\n disabled={disabled || row.deleted || !editable(row, child.key)}\n error={rowErrors[child.key]}\n resource={childResource}\n attachment={\n child.type === 'attachment' &&\n isAttachment(storedValue(row, child.key))\n ? (storedValue(row, child.key) as AttachmentValue)\n : null\n }\n attachments={\n child.type === 'attachment' &&\n Array.isArray(storedValue(row, child.key))\n ? (storedValue(row, child.key) as unknown[]).filter(isAttachment)\n : undefined\n }\n relation={\n child.type === 'belongsTo' || child.type === 'user'\n ? {\n url: `/resources/${(field as { resource?: string }).resource}/options/${child.key}`,\n searchable: child.type === 'user',\n }\n : undefined\n }\n onChange={(value) =>\n update(row.key, {\n values: { ...row.values, [child.key]: value },\n dirty: true,\n })\n }\n />\n )}\n {!rowHidden.has(child.key) && rowErrors[child.key] && (\n <p role=\"alert\" className=\"mt-1 text-xs text-destructive\">\n {rowErrors[child.key]}\n </p>\n )}\n </td>\n ))}\n <td className=\"px-4 py-2\">\n {row.id === undefined ? (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n disabled={disabled}\n aria-label={t('إزالة البند {number}', { number })}\n onClick={() => onChange(rows.filter((entry) => entry.key !== row.key))}\n >\n <Trash2 className=\"text-destructive\" />\n </Button>\n ) : inline.permissions[String(row.id)]?.delete ? (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n disabled={disabled}\n aria-label={\n row.deleted\n ? t('التراجع عن حذف البند {number}', { number })\n : t('حذف البند {number}', { number })\n }\n onClick={() => update(row.key, { deleted: !row.deleted })}\n >\n {row.deleted ? <Undo2 /> : <Trash2 className=\"text-destructive\" />}\n </Button>\n ) : null}\n </td>\n </tr>\n )\n })}\n </tbody>\n </table>\n </div>\n )}\n </section>\n )\n}\n",
33
34
  "target": "inertia/components/ui/resource-field.tsx"
34
35
  }
35
36
  ],
@@ -8,6 +8,7 @@
8
8
  "resource-actions",
9
9
  "resource-field",
10
10
  "resource-value",
11
+ "resource-surface",
11
12
  "messages"
12
13
  ],
13
14
  "dependencies": [
@@ -19,7 +20,7 @@
19
20
  {
20
21
  "path": "registry/ui/resource-form.tsx",
21
22
  "type": "registry:ui",
22
- "content": "import { useState, type FormEvent } from 'react'\nimport { router } from '@inertiajs/react'\nimport { Link } from '@adonisjs/inertia/react'\nimport axios from 'axios'\nimport { toast } from 'sonner'\nimport { RefreshCw, Save } from 'lucide-react'\nimport type { RecordPermissions, ResourceEditor, ResourceField as Field } from 'adula'\nimport { Alert, AlertDescription, AlertTitle } from '~/components/ui/alert'\nimport { Button } from '~/components/ui/button'\nimport { ResourceActions, failureMessage, isConflict } from '~/components/ui/resource-actions'\nimport {\n InlineRows,\n ResourceField,\n ResourceSelect,\n type InlineRow,\n} from '~/components/ui/resource-field'\nimport { Label } from '~/components/ui/label'\nimport { useMessages } from '~/components/ui/messages'\nimport { inputValue, isAttachment, parseValue } from '~/components/ui/resource-value'\nimport { hiddenFields, listInput } from '~/components/ui/field_values'\n\ntype Failure = { message: string; conflict: boolean }\ntype RowErrors = Record<string, Record<string, Record<string, string>>>\ntype ServerError = { field?: string; message: string }\n\nfunction initialValue(field: Field, value: unknown) {\n if (field.type === 'boolean' && (value === null || value === undefined)) return 'false'\n return inputValue(field, value)\n}\n\nexport function ResourceForm({\n editor,\n permissions = {},\n onSaved,\n onCancel,\n onAction,\n}: {\n editor: ResourceEditor\n permissions?: RecordPermissions\n /** Called with the saved record id instead of visiting its page (record dialogs). */\n onSaved?: (id: number) => void\n /** Replaces the cancel link (record dialogs return to the details). */\n onCancel?: () => void\n /** Called after a record action (submit, delete...) instead of visiting a page. */\n onAction?: (action: string) => void\n}) {\n const { t, label } = useMessages()\n const base = `/resources/${editor.name}`\n const scalar = editor.fields.filter((field) => field.type !== 'hasMany')\n const inlineFields = editor.fields.filter(\n (field) => field.type === 'hasMany' && field.inline && editor.inline[field.key]\n )\n const [values, setValues] = useState<Record<string, string>>(() =>\n Object.fromEntries(\n scalar.map((field) => [\n field.key,\n initialValue(field, editor.record?.[field.key] ?? editor.defaults?.[field.key]),\n ])\n )\n )\n const [rows, setRows] = useState<Record<string, InlineRow[]>>(() =>\n Object.fromEntries(\n inlineFields.map((field) => {\n const definition = editor.inline[field.key]\n return [\n field.key,\n definition.rows.map((row) => ({\n key: `row-${row.id}`,\n id: Number(row.id),\n version:\n row.version === undefined || row.version === null ? undefined : Number(row.version),\n values: Object.fromEntries(\n definition.fields.map((child) => [child.key, initialValue(child, row[child.key])])\n ),\n })),\n ]\n })\n )\n )\n const [unit, setUnit] = useState(\n String(editor.record?.orgUnitId ?? editor.orgUnits[0]?.value ?? '')\n )\n const [failure, setFailure] = useState<Failure | null>(null)\n const [errors, setErrors] = useState<Record<string, string>>({})\n const [rowErrors, setRowErrors] = useState<RowErrors>({})\n const [sectionErrors, setSectionErrors] = useState<Record<string, string>>({})\n const [busy, setBusy] = useState(false)\n const multiValued = new Set(\n editor.fields\n .filter((field) => field.type === 'multiSelect' || field.type === 'manyToMany')\n .map((field) => field.key)\n )\n // visibleWhen reads the live form values; siblings outside the form keep their stored\n // value. A field whose sibling is hidden is evaluated with that sibling empty.\n const current = { ...values }\n for (const field of scalar)\n for (const key of Object.keys(field.visibleWhen ?? {}))\n if (!(key in current)) {\n const stored = editor.record?.[key] ?? editor.defaults?.[key]\n current[key] = Array.isArray(stored)\n ? listInput(stored)\n : stored === null || stored === undefined\n ? ''\n : String(stored)\n }\n const hidden = hiddenFields(scalar, current)\n const applies = (field: Field) => !hidden.has(field.key)\n\n const inlinePayload = (field: Field, collected: RowErrors) => {\n const definition = editor.inline[field.key]\n const list = rows[field.key] ?? []\n const changed = list.filter((row) =>\n row.id === undefined ? !row.deleted : Boolean(row.dirty || row.deleted)\n )\n const payload = changed.map((row) => {\n if (row.deleted) return { id: row.id, version: row.version, _delete: true }\n const allowed =\n row.id === undefined\n ? definition.createFields\n : (definition.updateFields[String(row.id)] ?? [])\n const entry: Record<string, unknown> =\n row.id === undefined ? {} : { id: row.id, version: row.version }\n // A child field whose visibleWhen does not hold in its row is hidden and not submitted.\n const rowHidden = hiddenFields(definition.fields, row.values)\n for (const child of definition.fields) {\n if (!allowed.includes(child.key) || rowHidden.has(child.key)) continue\n const raw = row.values[child.key] ?? ''\n if (raw === '' && !child.required && row.id === undefined) continue\n try {\n const parsed = parseValue(child, raw)\n if (parsed === null && child.required) throw new Error('هذا الحقل مطلوب')\n entry[child.key] = parsed\n } catch (error) {\n collected[field.key] ??= {}\n collected[field.key][row.key] ??= {}\n collected[field.key][row.key][child.key] = t((error as Error).message)\n }\n }\n return entry\n })\n return changed.length ? payload : undefined\n }\n\n const mapServerErrors = (entries: ServerError[]) => {\n const fieldErrors: Record<string, string> = {}\n const sections: Record<string, string> = {}\n const unknown: string[] = []\n for (const entry of entries) {\n const key = entry.field ?? ''\n if (scalar.some((field) => field.key === key)) {\n fieldErrors[key] = entry.message\n continue\n }\n const section = inlineFields.find((field) =>\n editor.inline[field.key].fields.some(\n (child) => child.key === key || key.endsWith(`.${child.key}`)\n )\n )\n if (section) {\n const child = editor.inline[section.key].fields.find(\n (candidate) => candidate.key === key || key.endsWith(`.${candidate.key}`)\n )\n // Nested validators report the child field only, never which row; surface it on the section.\n sections[section.key] = `${child ? label(child.label) : key}: ${entry.message}`\n continue\n }\n unknown.push(key ? `${key}: ${entry.message}` : entry.message)\n }\n setErrors(fieldErrors)\n setSectionErrors(sections)\n return unknown\n }\n\n const submit = async (event: FormEvent) => {\n event.preventDefault()\n setFailure(null)\n setErrors({})\n setRowErrors({})\n setSectionErrors({})\n const payload: Record<string, unknown> = {}\n const fieldErrors: Record<string, string> = {}\n const collected: RowErrors = {}\n for (const field of editor.fields) {\n if (field.type === 'hasMany') {\n if (!editor.inline[field.key]) continue\n const inline = inlinePayload(field, collected)\n if (inline) payload[field.key] = inline\n continue\n }\n // A field whose visibleWhen does not hold is hidden and not submitted; the server\n // stores null for it whatever was typed before it was hidden.\n if (!applies(field)) continue\n const raw = values[field.key] ?? ''\n const multiple = multiValued.has(field.key)\n // Updates submit the whole form: the resource validator checks the submitted\n // document, and `version` — not a partial payload — protects concurrent edits.\n // A cleared multi-value field is still submitted so its declared default is not applied.\n if (editor.mode === 'create' && raw === '' && !field.required && !multiple) continue\n try {\n const parsed = parseValue(field, raw)\n const empty = parsed === null || (Array.isArray(parsed) && parsed.length === 0)\n if (empty && field.required) throw new Error('هذا الحقل مطلوب')\n payload[field.key] = parsed\n } catch (error) {\n fieldErrors[field.key] = t((error as Error).message)\n }\n }\n if (Object.keys(fieldErrors).length || Object.keys(collected).length) {\n setErrors(fieldErrors)\n setRowErrors(collected)\n setFailure({ message: t('راجع الحقول المحددة ثم أعد المحاولة.'), conflict: false })\n return\n }\n if (editor.scoped && !editor.scopeFrom) payload.orgUnitId = Number(unit)\n if (editor.record?.version !== undefined && editor.record.version !== null)\n payload.version = editor.record.version\n setBusy(true)\n try {\n const response = await axios.request<{ data: { id: number } }>({\n method: editor.mode === 'create' ? 'post' : 'patch',\n url: base + (editor.record ? `/${editor.record.id}` : ''),\n data: payload,\n headers: { Accept: 'application/json' },\n withXSRFToken: true,\n })\n toast.success(\n editor.mode === 'create'\n ? editor.recordLabel\n ? t('تمت إضافة {record}', { record: editor.recordLabel })\n : t('تمت إضافة السجل')\n : t('تم حفظ التعديلات')\n )\n if (onSaved) onSaved(response.data.data.id)\n // The details replace the form in the same dialog instead of closing and reopening.\n else router.visit(`${base}/${response.data.data.id}`, { preserveState: true })\n } catch (error) {\n const unknown =\n axios.isAxiosError(error) && Array.isArray(error.response?.data?.errors)\n ? mapServerErrors(error.response.data.errors as ServerError[])\n : []\n const conflict = isConflict(error)\n setFailure({\n conflict,\n message: conflict\n ? t('تغير السجل منذ فتحه. احتفظ بتعديلاتك ثم أعد تحميل الصفحة.')\n : unknown.length\n ? unknown.join(' · ')\n : failureMessage(error, t('تعذر الحفظ. راجع البيانات وحاول مجدداً.'), t),\n })\n } finally {\n setBusy(false)\n }\n }\n\n // The required mark sits inside the sentence: «… المعلّمة بـ * مطلوبة».\n const requiredHint = t('الحقول المتاحة بحسب صلاحياتك · الحقول المعلّمة بـ {mark} مطلوبة').split(\n '{mark}'\n )\n\n return (\n <form onSubmit={submit} noValidate className=\"max-w-4xl space-y-6\" aria-busy={busy}>\n {failure && (\n <Alert variant=\"destructive\" role=\"alert\">\n <AlertTitle>{failure.conflict ? t('تعارض في الإصدار') : t('تعذر الحفظ')}</AlertTitle>\n <AlertDescription className=\"flex flex-wrap items-center gap-3\">\n {failure.message}\n {failure.conflict && (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={() => router.reload()}>\n <RefreshCw size={14} />\n {t('إعادة التحميل')}\n </Button>\n )}\n </AlertDescription>\n </Alert>\n )}\n <section className=\"rounded-xl border bg-white\">\n <div className=\"border-b px-7 py-5\">\n <h2 className=\"text-sm font-semibold\">{t('تفاصيل السجل')}</h2>\n <p className=\"mt-2 text-xs text-muted-foreground\">\n {requiredHint[0]}\n <span className=\"text-destructive\">*</span>\n {requiredHint[1]}\n </p>\n </div>\n <div className=\"grid gap-6 p-7 md:grid-cols-2\">\n {editor.scoped && !editor.scopeFrom && (\n <div className=\"min-w-0 space-y-2\">\n <Label htmlFor=\"orgUnitId\" className=\"flex items-center gap-2 text-sm font-medium\">\n {t('الوحدة التنظيمية')}\n <span className=\"text-destructive\" aria-hidden=\"true\">\n *\n </span>\n </Label>\n <ResourceSelect\n id=\"orgUnitId\"\n required\n value={unit}\n disabled={busy}\n onChange={setUnit}\n options={editor.orgUnits}\n />\n </div>\n )}\n {scalar.filter(applies).map((field) => {\n const stored = editor.record?.[field.key]\n return (\n <ResourceField\n // User choices depend on the unit: a new unit reloads them.\n key={field.type === 'user' ? `${field.key}:${unit}` : field.key}\n field={field}\n id={field.key}\n value={values[field.key] ?? ''}\n options={editor.options[field.key]}\n error={errors[field.key]}\n disabled={busy}\n resource={editor.name}\n attachment={field.type === 'attachment' && isAttachment(stored) ? stored : null}\n attachments={\n field.type === 'attachment' && Array.isArray(stored)\n ? stored.filter(isAttachment)\n : undefined\n }\n onChange={(value) => setValues((current) => ({ ...current, [field.key]: value }))}\n relation={\n field.type === 'belongsTo' || field.type === 'manyToMany'\n ? {\n url: `${base}/options/${field.key}${editor.record ? `?id=${editor.record.id}` : ''}`,\n searchable: editor.relationSearch[field.key] ?? false,\n }\n : field.type === 'user'\n ? {\n url: `${base}/options/${field.key}?${new URLSearchParams({\n ...(editor.record ? { id: String(editor.record.id) } : {}),\n // An inherited unit is resolved on the server from the record.\n ...(editor.scoped && !editor.scopeFrom && unit\n ? { orgUnitId: unit }\n : {}),\n })}`,\n searchable: true,\n }\n : undefined\n }\n />\n )\n })}\n </div>\n </section>\n {inlineFields.map((field) => (\n <InlineRows\n key={field.key}\n field={field}\n inline={editor.inline[field.key]}\n rows={rows[field.key] ?? []}\n errors={rowErrors[field.key]}\n sectionError={sectionErrors[field.key]}\n disabled={busy}\n resource={editor.name}\n onChange={(next) => setRows((current) => ({ ...current, [field.key]: next }))}\n />\n ))}\n {editor.record?.version !== undefined && editor.record.version !== null && (\n <input type=\"hidden\" name=\"version\" value={String(editor.record.version)} />\n )}\n <div className=\"flex flex-wrap items-center justify-between gap-3\">\n <div className=\"flex flex-wrap gap-2\">\n {editor.record && (\n <ResourceActions\n resource={editor.name}\n id={editor.record.id as number}\n version={editor.record.version ?? undefined}\n permissions={permissions}\n onDone={(action) =>\n onAction\n ? onAction(action)\n : router.visit(action === 'delete' ? base : `${base}/${editor.record?.id}`)\n }\n />\n )}\n </div>\n <div className=\"flex gap-3\">\n {onCancel ? (\n <Button type=\"button\" variant=\"outline\" onClick={onCancel}>\n {t('إلغاء')}\n </Button>\n ) : (\n <Button type=\"button\" variant=\"outline\" asChild>\n <Link href={editor.record ? `${base}/${editor.record.id}` : base}>{t('إلغاء')}</Link>\n </Button>\n )}\n <Button type=\"submit\" disabled={busy}>\n <Save size={16} />\n {busy ? t('جارٍ الحفظ...') : t('حفظ السجل')}\n </Button>\n </div>\n </div>\n </form>\n )\n}\n",
23
+ "content": "import { useEffect, useId, useRef, useState, type FormEvent } from 'react'\nimport { router } from '@inertiajs/react'\nimport { Link } from '@adonisjs/inertia/react'\nimport axios from 'axios'\nimport { toast } from 'sonner'\nimport { RefreshCw, Save } from 'lucide-react'\nimport type { RecordPermissions, ResourceEditor, ResourceField as Field } from 'adula'\nimport { Alert, AlertDescription, AlertTitle } from '~/components/ui/alert'\nimport { Button } from '~/components/ui/button'\nimport { ResourceActions, failureMessage, isConflict } from '~/components/ui/resource-actions'\nimport {\n InlineRows,\n ResourceField,\n ResourceSelect,\n type InlineRow,\n} from '~/components/ui/resource-field'\nimport { Label } from '~/components/ui/label'\nimport { useDialogValue } from '~/components/ui/dialog'\nimport { useMessages } from '~/components/ui/messages'\nimport { inputValue, isAttachment, parseValue } from '~/components/ui/resource-value'\nimport { hiddenFields, listInput } from '~/components/ui/field_values'\nimport { RecordFooter, openRecord, pinCreated } from '~/components/ui/resource-surface'\n\ntype Failure = { message: string; conflict: boolean }\ntype RowErrors = Record<string, Record<string, Record<string, string>>>\ntype ServerError = { field?: string; message: string }\n\nfunction initialValue(field: Field, value: unknown) {\n if (field.type === 'boolean' && (value === null || value === undefined)) return 'false'\n return inputValue(field, value)\n}\n\nconst entries = (record: Record<string, string>) =>\n Object.keys(record)\n .sort()\n .map((key) => [key, record[key]])\n\n/** What the form would submit, independent of key order, for the unsaved-changes check. */\nfunction snapshot(values: Record<string, string>, rows: Record<string, InlineRow[]>, unit: string) {\n return JSON.stringify([\n entries(values),\n Object.keys(rows)\n .sort()\n .map((key) => [\n key,\n rows[key]\n // A row added and removed again changes nothing.\n .filter((row) => !(row.id === undefined && row.deleted))\n .map((row) => [row.id ?? null, Boolean(row.deleted), entries(row.values)]),\n ]),\n unit,\n ])\n}\n\n/** The first control to focus for an invalid field: the field itself or its first focusable part. */\nfunction focusable(element: HTMLElement): HTMLElement | null {\n if (element.tabIndex >= 0 && !element.hasAttribute('disabled')) return element\n return element.querySelector<HTMLElement>(\n 'input:not([disabled]):not([type=hidden]), button:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex=\"-1\"])'\n )\n}\n\nexport function ResourceForm({\n editor,\n permissions = {},\n onSaved,\n createdAction,\n onCancel,\n onAction,\n}: {\n editor: ResourceEditor\n permissions?: RecordPermissions\n /** Called with the saved record id instead of visiting its page (record dialogs). */\n onSaved?: (id: number) => void\n /** An action offered in the toast after a create, for example «عرض» the new record. */\n createdAction?: { label: string; onClick: (id: number) => void }\n /** Replaces the cancel link (record dialogs return to the details). */\n onCancel?: () => void\n /** Called after a record action (submit, delete...) instead of visiting a page. */\n onAction?: (action: string) => void\n}) {\n const { t, label } = useMessages()\n const base = `/resources/${editor.name}`\n // «عرض» in the toast after a create opens the new record over the list.\n const created = createdAction ?? {\n label: t('عرض'),\n onClick: (id: number) => void openRecord(editor.name, id, 'show'),\n }\n const scalar = editor.fields.filter((field) => field.type !== 'hasMany')\n const inlineFields = editor.fields.filter(\n (field) => field.type === 'hasMany' && field.inline && editor.inline[field.key]\n )\n const [values, setValues] = useState<Record<string, string>>(() =>\n Object.fromEntries(\n scalar.map((field) => [\n field.key,\n initialValue(field, editor.record?.[field.key] ?? editor.defaults?.[field.key]),\n ])\n )\n )\n const [rows, setRows] = useState<Record<string, InlineRow[]>>(() =>\n Object.fromEntries(\n inlineFields.map((field) => {\n const definition = editor.inline[field.key]\n return [\n field.key,\n definition.rows.map((row) => ({\n key: `row-${row.id}`,\n id: Number(row.id),\n version:\n row.version === undefined || row.version === null ? undefined : Number(row.version),\n values: Object.fromEntries(\n definition.fields.map((child) => [child.key, initialValue(child, row[child.key])])\n ),\n })),\n ]\n })\n )\n )\n const [unit, setUnit] = useState(\n String(editor.record?.orgUnitId ?? editor.orgUnits[0]?.value ?? '')\n )\n const [failure, setFailure] = useState<Failure | null>(null)\n const [errors, setErrors] = useState<Record<string, string>>({})\n const [rowErrors, setRowErrors] = useState<RowErrors>({})\n const [sectionErrors, setSectionErrors] = useState<Record<string, string>>({})\n const [busy, setBusy] = useState(false)\n // In a dialog, the dialog compares this with how the form opened (nothing on a page).\n useDialogValue(snapshot(values, rows, unit))\n const form = useRef<HTMLFormElement>(null)\n // The save button sits in the dialog's fixed footer, outside the form's markup.\n const formId = useId()\n // Counts refused submits, so focus moves to the first invalid field after the errors render.\n const [refused, setRefused] = useState(0)\n useEffect(() => {\n if (!refused || !form.current) return\n const invalid = [...form.current.querySelectorAll<HTMLElement>('[aria-invalid=\"true\"]')]\n const target =\n invalid.map(focusable).find((element) => element !== null) ??\n form.current.querySelector<HTMLElement>(':scope > [data-slot=\"alert\"]')\n target?.focus({ preventScroll: true })\n // The nearest scroller: the dialog body in a dialog, the window on a page.\n target?.scrollIntoView({ block: 'nearest' })\n }, [refused])\n const multiValued = new Set(\n editor.fields\n .filter((field) => field.type === 'multiSelect' || field.type === 'manyToMany')\n .map((field) => field.key)\n )\n // visibleWhen reads the live form values; siblings outside the form keep their stored\n // value. A field whose sibling is hidden is evaluated with that sibling empty.\n const current = { ...values }\n for (const field of scalar)\n for (const key of Object.keys(field.visibleWhen ?? {}))\n if (!(key in current)) {\n const stored = editor.record?.[key] ?? editor.defaults?.[key]\n current[key] = Array.isArray(stored)\n ? listInput(stored)\n : stored === null || stored === undefined\n ? ''\n : String(stored)\n }\n const hidden = hiddenFields(scalar, current)\n const applies = (field: Field) => !hidden.has(field.key)\n\n const inlinePayload = (field: Field, collected: RowErrors) => {\n const definition = editor.inline[field.key]\n const list = rows[field.key] ?? []\n const changed = list.filter((row) =>\n row.id === undefined ? !row.deleted : Boolean(row.dirty || row.deleted)\n )\n const payload = changed.map((row) => {\n if (row.deleted) return { id: row.id, version: row.version, _delete: true }\n const allowed =\n row.id === undefined\n ? definition.createFields\n : (definition.updateFields[String(row.id)] ?? [])\n const entry: Record<string, unknown> =\n row.id === undefined ? {} : { id: row.id, version: row.version }\n // A child field whose visibleWhen does not hold in its row is hidden and not submitted.\n const rowHidden = hiddenFields(definition.fields, row.values)\n for (const child of definition.fields) {\n if (!allowed.includes(child.key) || rowHidden.has(child.key)) continue\n const raw = row.values[child.key] ?? ''\n if (raw === '' && !child.required && row.id === undefined) continue\n try {\n const parsed = parseValue(child, raw)\n if (parsed === null && child.required) throw new Error('هذا الحقل مطلوب')\n entry[child.key] = parsed\n } catch (error) {\n collected[field.key] ??= {}\n collected[field.key][row.key] ??= {}\n collected[field.key][row.key][child.key] = t((error as Error).message)\n }\n }\n return entry\n })\n return changed.length ? payload : undefined\n }\n\n const mapServerErrors = (entries: ServerError[]) => {\n const fieldErrors: Record<string, string> = {}\n const sections: Record<string, string> = {}\n const unknown: string[] = []\n for (const entry of entries) {\n const key = entry.field ?? ''\n if (scalar.some((field) => field.key === key)) {\n fieldErrors[key] = entry.message\n continue\n }\n const section = inlineFields.find((field) =>\n editor.inline[field.key].fields.some(\n (child) => child.key === key || key.endsWith(`.${child.key}`)\n )\n )\n if (section) {\n const child = editor.inline[section.key].fields.find(\n (candidate) => candidate.key === key || key.endsWith(`.${candidate.key}`)\n )\n // Nested validators report the child field only, never which row; surface it on the section.\n sections[section.key] = `${child ? label(child.label) : key}: ${entry.message}`\n continue\n }\n unknown.push(key ? `${key}: ${entry.message}` : entry.message)\n }\n setErrors(fieldErrors)\n setSectionErrors(sections)\n return unknown\n }\n\n const submit = async (event: FormEvent) => {\n event.preventDefault()\n setFailure(null)\n setErrors({})\n setRowErrors({})\n setSectionErrors({})\n const payload: Record<string, unknown> = {}\n const fieldErrors: Record<string, string> = {}\n const collected: RowErrors = {}\n for (const field of editor.fields) {\n if (field.type === 'hasMany') {\n if (!editor.inline[field.key]) continue\n const inline = inlinePayload(field, collected)\n if (inline) payload[field.key] = inline\n continue\n }\n // A field whose visibleWhen does not hold is hidden and not submitted; the server\n // stores null for it whatever was typed before it was hidden.\n if (!applies(field)) continue\n const raw = values[field.key] ?? ''\n const multiple = multiValued.has(field.key)\n // Updates submit the whole form: the resource validator checks the submitted\n // document, and `version` — not a partial payload — protects concurrent edits.\n // A cleared multi-value field is still submitted so its declared default is not applied.\n if (editor.mode === 'create' && raw === '' && !field.required && !multiple) continue\n try {\n const parsed = parseValue(field, raw)\n const empty = parsed === null || (Array.isArray(parsed) && parsed.length === 0)\n if (empty && field.required) throw new Error('هذا الحقل مطلوب')\n payload[field.key] = parsed\n } catch (error) {\n fieldErrors[field.key] = t((error as Error).message)\n }\n }\n if (Object.keys(fieldErrors).length || Object.keys(collected).length) {\n setErrors(fieldErrors)\n setRowErrors(collected)\n setFailure({ message: t('راجع الحقول المحددة ثم أعد المحاولة.'), conflict: false })\n setRefused((count) => count + 1)\n return\n }\n if (editor.scoped && !editor.scopeFrom) payload.orgUnitId = Number(unit)\n if (editor.record?.version !== undefined && editor.record.version !== null)\n payload.version = editor.record.version\n setBusy(true)\n try {\n const response = await axios.request<{ data: { id: number } }>({\n method: editor.mode === 'create' ? 'post' : 'patch',\n url: base + (editor.record ? `/${editor.record.id}` : ''),\n data: payload,\n headers: { Accept: 'application/json' },\n withXSRFToken: true,\n })\n const savedId = response.data.data.id\n toast.success(\n editor.mode === 'create'\n ? editor.recordLabel\n ? t('تمت إضافة {record}', { record: editor.recordLabel })\n : t('تمت إضافة السجل')\n : t('تم حفظ التعديلات'),\n editor.mode === 'create'\n ? {\n action: {\n label: created.label,\n onClick: () => created.onClick(savedId),\n },\n }\n : undefined\n )\n if (onSaved) onSaved(savedId)\n // A new record returns to the list, pinned first and highlighted (owner, 2.3.0).\n else if (editor.mode === 'create')\n router.visit(base, { onSuccess: () => void pinCreated(editor.name, savedId) })\n // The details replace the form in the same dialog instead of closing and reopening.\n else router.visit(`${base}/${savedId}`, { preserveState: true })\n } catch (error) {\n const unknown =\n axios.isAxiosError(error) && Array.isArray(error.response?.data?.errors)\n ? mapServerErrors(error.response.data.errors as ServerError[])\n : []\n const conflict = isConflict(error)\n setFailure({\n conflict,\n message: conflict\n ? t('تغير السجل منذ فتحه. احتفظ بتعديلاتك ثم أعد تحميل الصفحة.')\n : unknown.length\n ? unknown.join(' · ')\n : failureMessage(error, t('تعذر الحفظ. راجع البيانات وحاول مجدداً.'), t),\n })\n setRefused((count) => count + 1)\n } finally {\n setBusy(false)\n }\n }\n\n // The required mark sits inside the sentence: «… المعلّمة بـ * مطلوبة».\n const requiredHint = t('الحقول المتاحة بحسب صلاحياتك · الحقول المعلّمة بـ {mark} مطلوبة').split(\n '{mark}'\n )\n\n return (\n <form\n ref={form}\n id={formId}\n onSubmit={submit}\n noValidate\n // The page keeps a reading width; a dialog body is already bounded.\n className=\"max-w-4xl space-y-6 in-data-[slot=dialog-content]:max-w-none\"\n aria-busy={busy}\n >\n {failure && (\n <Alert variant=\"destructive\" role=\"alert\" tabIndex={-1}>\n <AlertTitle>{failure.conflict ? t('تعارض في الإصدار') : t('تعذر الحفظ')}</AlertTitle>\n <AlertDescription className=\"flex flex-wrap items-center gap-3\">\n {failure.message}\n {failure.conflict && (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={() => router.reload()}>\n <RefreshCw size={14} />\n {t('إعادة التحميل')}\n </Button>\n )}\n </AlertDescription>\n </Alert>\n )}\n <section className=\"rounded-xl border bg-card\">\n <div className=\"border-b px-7 py-5\">\n <h2 className=\"text-sm font-semibold\">{t('تفاصيل السجل')}</h2>\n <p className=\"mt-2 text-xs text-muted-foreground\">\n {requiredHint[0]}\n <span className=\"text-destructive\">*</span>\n {requiredHint[1]}\n </p>\n </div>\n <div className=\"grid gap-6 p-7 md:grid-cols-2\">\n {editor.scoped && !editor.scopeFrom && (\n <div className=\"min-w-0 space-y-2\">\n <Label htmlFor=\"orgUnitId\" className=\"flex items-center gap-2 text-sm font-medium\">\n {t('الوحدة التنظيمية')}\n <span className=\"text-destructive\" aria-hidden=\"true\">\n *\n </span>\n </Label>\n <ResourceSelect\n id=\"orgUnitId\"\n required\n value={unit}\n disabled={busy}\n onChange={setUnit}\n options={editor.orgUnits}\n />\n </div>\n )}\n {scalar.filter(applies).map((field) => {\n const stored = editor.record?.[field.key]\n return (\n <ResourceField\n // User choices depend on the unit: a new unit reloads them.\n key={field.type === 'user' ? `${field.key}:${unit}` : field.key}\n field={field}\n id={field.key}\n value={values[field.key] ?? ''}\n options={editor.options[field.key]}\n error={errors[field.key]}\n disabled={busy}\n resource={editor.name}\n attachment={field.type === 'attachment' && isAttachment(stored) ? stored : null}\n attachments={\n field.type === 'attachment' && Array.isArray(stored)\n ? stored.filter(isAttachment)\n : undefined\n }\n onChange={(value) => setValues((current) => ({ ...current, [field.key]: value }))}\n relation={\n field.type === 'belongsTo' || field.type === 'manyToMany'\n ? {\n url: `${base}/options/${field.key}${editor.record ? `?id=${editor.record.id}` : ''}`,\n searchable: editor.relationSearch[field.key] ?? false,\n }\n : field.type === 'user'\n ? {\n url: `${base}/options/${field.key}?${new URLSearchParams({\n ...(editor.record ? { id: String(editor.record.id) } : {}),\n // An inherited unit is resolved on the server from the record.\n ...(editor.scoped && !editor.scopeFrom && unit\n ? { orgUnitId: unit }\n : {}),\n })}`,\n searchable: true,\n }\n : undefined\n }\n />\n )\n })}\n </div>\n </section>\n {inlineFields.map((field) => (\n <InlineRows\n key={field.key}\n field={field}\n inline={editor.inline[field.key]}\n rows={rows[field.key] ?? []}\n errors={rowErrors[field.key]}\n sectionError={sectionErrors[field.key]}\n disabled={busy}\n resource={editor.name}\n onChange={(next) => setRows((current) => ({ ...current, [field.key]: next }))}\n />\n ))}\n {editor.record?.version !== undefined && editor.record.version !== null && (\n <input type=\"hidden\" name=\"version\" value={String(editor.record.version)} />\n )}\n <RecordFooter>\n <div className=\"me-auto flex flex-wrap gap-2\">\n {editor.record && (\n <ResourceActions\n resource={editor.name}\n id={editor.record.id as number}\n version={editor.record.version ?? undefined}\n permissions={permissions}\n onDone={(action) =>\n onAction\n ? onAction(action)\n : router.visit(action === 'delete' ? base : `${base}/${editor.record?.id}`)\n }\n />\n )}\n </div>\n {onCancel ? (\n <Button type=\"button\" variant=\"outline\" onClick={onCancel}>\n {t('إلغاء')}\n </Button>\n ) : (\n <Button type=\"button\" variant=\"outline\" asChild>\n <Link\n href={editor.record ? `${base}/${editor.record.id}` : base}\n // Back to the details in the same dialog; a new record returns to the list.\n preserveState={Boolean(editor.record)}\n >\n {t('إلغاء')}\n </Link>\n </Button>\n )}\n <Button type=\"submit\" form={formId} disabled={busy}>\n <Save size={16} />\n {busy ? t('جارٍ الحفظ...') : t('حفظ السجل')}\n </Button>\n </RecordFooter>\n </form>\n )\n}\n",
23
24
  "target": "inertia/components/ui/resource-form.tsx"
24
25
  }
25
26
  ],
@@ -4,10 +4,11 @@
4
4
  "registryDependencies": [
5
5
  "badge",
6
6
  "button",
7
- "input",
7
+ "file-input",
8
8
  "label",
9
9
  "radio-group",
10
10
  "dialog",
11
+ "long-dialog",
11
12
  "select",
12
13
  "table"
13
14
  ],
@@ -19,7 +20,7 @@
19
20
  {
20
21
  "path": "registry/ui/resource-import.tsx",
21
22
  "type": "registry:ui",
22
- "content": "import { useEffect, useState } from 'react'\nimport { router } from '@inertiajs/react'\nimport axios from 'axios'\nimport { Download, FileUp } from 'lucide-react'\nimport type { ImportBatchRecord as ImportBatch, ImportMode } from 'adula'\nimport { Badge } from '~/components/ui/badge'\nimport { Button } from '~/components/ui/button'\nimport { Input } from '~/components/ui/input'\nimport { Label } from '~/components/ui/label'\nimport { RadioGroup, RadioGroupItem } from '~/components/ui/radio-group'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from '~/components/ui/dialog'\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from '~/components/ui/select'\nimport {\n Table,\n TableBody,\n TableCell,\n TableHead,\n TableHeader,\n TableRow,\n} from '~/components/ui/table'\n\nconst json = { headers: { Accept: 'application/json' }, withXSRFToken: true }\nconst SKIP = '__skip__'\ntype Step = 'upload' | 'mapping' | 'validating' | 'report'\n\n/** Counts of a finished dry run: what the real import would create, update and refuse. */\nexport function ImportSummary({ batch }: { batch: ImportBatch }) {\n return (\n <p className=\"text-sm tabular-nums\">\n سيُضاف {batch.created}\n {batch.mode === 'upsert' && ` · سيُحدَّث ${batch.updated}`} · أخطاء {batch.failed}\n </p>\n )\n}\n\n/** The per-row dry-run report of a validated batch. */\nexport function ImportReport({ batch }: { batch: ImportBatch }) {\n if (!batch.report.length)\n return <p className=\"text-sm text-muted-foreground\">لا يوجد تقرير صفوف لهذه الدفعة.</p>\n return (\n <div className=\"max-h-80 overflow-y-auto rounded-lg border\">\n <Table aria-label=\"تقرير التحقق\">\n <TableHeader>\n <TableRow>\n <TableHead className=\"w-20\">الصف</TableHead>\n <TableHead className=\"w-28\">النتيجة</TableHead>\n <TableHead>الملاحظة</TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {batch.report.map((entry) => (\n <TableRow key={entry.row}>\n <TableCell className=\"tabular-nums\">{entry.row}</TableCell>\n <TableCell>\n {entry.ok ? (\n <Badge variant={entry.action === 'update' ? 'secondary' : 'outline'}>\n {entry.action === 'update' ? 'تحديث' : 'إضافة'}\n </Badge>\n ) : (\n <Badge variant=\"destructive\">خطأ</Badge>\n )}\n </TableCell>\n <TableCell className=\"text-xs whitespace-normal\">{entry.message ?? '—'}</TableCell>\n </TableRow>\n ))}\n </TableBody>\n </Table>\n </div>\n )\n}\n\n/**\n * Upload a file, map its columns to writable fields, choose add-only or add-or-update,\n * optionally validate every row without saving, then queue the import.\n */\nexport function ResourceImport({\n resource,\n label,\n accept = '.csv,text/csv',\n}: {\n resource: string\n label: string\n /** File picker filter; add the extensions of registered import adapters. */\n accept?: string\n}) {\n const [open, setOpen] = useState(false)\n const [step, setStep] = useState<Step>('upload')\n const [file, setFile] = useState<File | null>(null)\n const [batch, setBatch] = useState<ImportBatch | null>(null)\n const [mapping, setMapping] = useState<Record<string, string>>({})\n const [mode, setMode] = useState<ImportMode>('create')\n const [matchField, setMatchField] = useState('')\n const [error, setError] = useState('')\n const [busy, setBusy] = useState(false)\n const reset = () => {\n setStep('upload')\n setFile(null)\n setBatch(null)\n setMapping({})\n setMode('create')\n setMatchField('')\n setError('')\n }\n const failure = (caught: unknown, fallback: string) =>\n setError(\n axios.isAxiosError(caught) && caught.response?.data?.error?.message\n ? String(caught.response.data.error.message)\n : fallback\n )\n // The worker validates in the background; follow the batch until its report is ready.\n useEffect(() => {\n if (step !== 'validating' || !batch) return\n const timer = setInterval(async () => {\n try {\n const response = await axios.get<{ data: ImportBatch }>(`/imports/${batch.id}`, json)\n const next = response.data.data\n setBatch(next)\n if (next.status === 'validated') setStep('report')\n if (next.status === 'failed') {\n setError('تعذر التحقق من الملف.')\n setStep('mapping')\n }\n } catch (caught) {\n failure(caught, 'تعذر قراءة حالة التحقق.')\n }\n }, 1500)\n return () => clearInterval(timer)\n }, [step, batch?.id])\n const unique = batch?.targets.filter((target) => target.unique) ?? []\n const upload = async (event: React.FormEvent) => {\n event.preventDefault()\n if (!file) return\n setBusy(true)\n setError('')\n try {\n const form = new FormData()\n form.append('file', file)\n const response = await axios.post<{ data: ImportBatch }>(\n `/resources/${resource}/imports`,\n form,\n json\n )\n setBatch(response.data.data)\n setMapping(response.data.data.mapping)\n setStep('mapping')\n } catch (caught) {\n failure(caught, 'تعذر قراءة الملف.')\n } finally {\n setBusy(false)\n }\n }\n const run = async (dryRun: boolean) => {\n if (!batch) return\n setBusy(true)\n setError('')\n try {\n const response = await axios.post<{ data: ImportBatch }>(\n `/imports/${batch.id}/start`,\n { mapping, mode, matchField: mode === 'upsert' ? matchField : undefined, dryRun },\n json\n )\n if (dryRun) {\n setBatch(response.data.data)\n setStep('validating')\n return\n }\n setOpen(false)\n reset()\n router.visit('/imports')\n } catch (caught) {\n failure(caught, dryRun ? 'تعذر بدء التحقق.' : 'تعذر بدء الاستيراد.')\n } finally {\n setBusy(false)\n }\n }\n const description = {\n upload: 'ملف CSV بترميز UTF-8، صفه الأول عناوين الأعمدة، حتى 5000 صف. نزّل القالب لتبدأ بالأعمدة الصحيحة.',\n mapping: `طابِق أعمدة الملف (${batch?.total ?? 0} صفاً) مع الحقول، ثم تحقق دون حفظ أو ابدأ الاستيراد.`,\n validating: `جارٍ التحقق من الصفوف دون حفظ: ${batch?.processed ?? 0} من ${batch?.total ?? 0}.`,\n report: 'نتيجة التحقق لكل صف. لم يُحفظ شيء بعد؛ ابدأ الاستيراد أو ارجع لتعديل المطابقة.',\n }[step]\n return (\n <>\n <Button variant=\"outline\" onClick={() => setOpen(true)}>\n <FileUp size={16} />\n استيراد CSV\n </Button>\n <Dialog\n open={open}\n onOpenChange={(value) => {\n setOpen(value)\n if (!value) reset()\n }}\n >\n <DialogContent dir=\"rtl\" className=\"sm:max-w-2xl\">\n <DialogHeader>\n <DialogTitle>استيراد إلى {label}</DialogTitle>\n <DialogDescription>{description}</DialogDescription>\n </DialogHeader>\n {step === 'upload' && (\n <form id=\"import-upload\" className=\"space-y-3\" onSubmit={upload}>\n <div className=\"space-y-2\">\n <Label htmlFor=\"import-file\">الملف</Label>\n <Input\n id=\"import-file\"\n type=\"file\"\n accept={accept}\n onChange={(event) => setFile(event.target.files?.[0] ?? null)}\n />\n </div>\n <Button type=\"button\" variant=\"link\" size=\"sm\" className=\"px-0\" asChild>\n <a href={`/resources/${resource}/imports/template`} download>\n <Download size={14} />\n تنزيل قالب CSV\n </a>\n </Button>\n </form>\n )}\n {step === 'mapping' && batch && (\n <form\n id=\"import-mapping\"\n className=\"max-h-[60vh] space-y-4 overflow-y-auto\"\n onSubmit={(event) => {\n event.preventDefault()\n void run(false)\n }}\n >\n <fieldset className=\"space-y-2\">\n <legend className=\"text-sm font-medium\">نمط الاستيراد</legend>\n <RadioGroup\n value={mode}\n onValueChange={(value) => setMode(value as ImportMode)}\n className=\"flex flex-wrap gap-6\"\n >\n <div className=\"flex items-center gap-2\">\n <RadioGroupItem id=\"import-mode-create\" value=\"create\" />\n <Label htmlFor=\"import-mode-create\">إضافة فقط</Label>\n </div>\n <div className=\"flex items-center gap-2\">\n <RadioGroupItem\n id=\"import-mode-upsert\"\n value=\"upsert\"\n disabled={unique.length === 0}\n />\n <Label htmlFor=\"import-mode-upsert\">إضافة أو تحديث</Label>\n </div>\n </RadioGroup>\n {unique.length === 0 && (\n <p className=\"text-xs text-muted-foreground\">\n التحديث يحتاج حقلاً فريداً، ولا يوجد حقل فريد قابل للاستيراد هنا.\n </p>\n )}\n </fieldset>\n {mode === 'upsert' && (\n <div className=\"grid grid-cols-2 items-center gap-3\">\n <div>\n <p className=\"text-sm font-medium\">حقل المطابقة</p>\n <p className=\"text-xs text-muted-foreground\">\n يُحدَّث السجل الذي يحمل القيمة نفسها، ويُضاف الباقي. الخلية الفارغة تُبقي القيمة المحفوظة.\n </p>\n </div>\n <Select value={matchField} onValueChange={setMatchField}>\n <SelectTrigger aria-label=\"حقل المطابقة\">\n <SelectValue placeholder=\"اختر حقلاً فريداً\" />\n </SelectTrigger>\n <SelectContent>\n {unique.map((target) => (\n <SelectItem key={target.key} value={target.key}>\n {target.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n )}\n <div className=\"space-y-3 border-t pt-4\">\n {batch.headers.map((header, index) => (\n <div key={index} className=\"grid grid-cols-2 items-center gap-3\">\n <div className=\"min-w-0\">\n <p className=\"truncate text-sm font-medium\">{header || `عمود ${index + 1}`}</p>\n <p className=\"truncate text-xs text-muted-foreground\">\n مثال: {batch.sample[0]?.[index] || '—'}\n </p>\n </div>\n <Select\n value={mapping[String(index)] ?? SKIP}\n onValueChange={(value) =>\n setMapping((current) => {\n const next = { ...current }\n if (value === SKIP) delete next[String(index)]\n else next[String(index)] = value\n return next\n })\n }\n >\n <SelectTrigger aria-label={`حقل العمود ${header || index + 1}`}>\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value={SKIP}>تجاهل العمود</SelectItem>\n {batch.targets.map((target) => (\n <SelectItem key={target.key} value={target.key}>\n {target.label}\n {target.required ? ' *' : ''}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n ))}\n </div>\n </form>\n )}\n {step === 'validating' && batch && (\n <div\n role=\"progressbar\"\n aria-label=\"تقدم التحقق\"\n aria-valuemin={0}\n aria-valuemax={batch.total}\n aria-valuenow={batch.processed}\n className=\"h-2 overflow-hidden rounded-full bg-muted\"\n >\n <div\n className=\"h-full bg-primary transition-all\"\n style={{ width: `${batch.total ? (batch.processed / batch.total) * 100 : 0}%` }}\n />\n </div>\n )}\n {step === 'report' && batch && (\n <div className=\"space-y-3\">\n <ImportSummary batch={batch} />\n <ImportReport batch={batch} />\n </div>\n )}\n {error && (\n <p role=\"alert\" className=\"rounded-lg bg-red-50 px-3 py-2 text-xs text-red-800\">\n {error}\n </p>\n )}\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" onClick={() => setOpen(false)}>\n إلغاء\n </Button>\n {step === 'upload' && (\n <Button type=\"submit\" form=\"import-upload\" disabled={busy || !file}>\n رفع الملف\n </Button>\n )}\n {step === 'mapping' && (\n <>\n <Button\n type=\"button\"\n variant=\"outline\"\n disabled={busy || (mode === 'upsert' && !matchField)}\n onClick={() => void run(true)}\n >\n تحقق دون حفظ\n </Button>\n <Button\n type=\"submit\"\n form=\"import-mapping\"\n disabled={busy || (mode === 'upsert' && !matchField)}\n >\n بدء الاستيراد\n </Button>\n </>\n )}\n {step === 'report' && (\n <>\n <Button type=\"button\" variant=\"outline\" onClick={() => setStep('mapping')}>\n تعديل المطابقة\n </Button>\n <Button type=\"button\" disabled={busy} onClick={() => void run(false)}>\n بدء الاستيراد\n </Button>\n </>\n )}\n </DialogFooter>\n </DialogContent>\n </Dialog>\n </>\n )\n}\n",
23
+ "content": "import { useEffect, useState } from \"react\";\nimport { router } from \"@inertiajs/react\";\nimport axios from \"axios\";\nimport { Download, FileUp } from \"lucide-react\";\nimport type { ImportBatchRecord as ImportBatch, ImportMode } from \"adula\";\nimport { Badge } from \"~/components/ui/badge\";\nimport { Button } from \"~/components/ui/button\";\nimport { FileInput } from \"~/components/ui/file-input\";\nimport { Label } from \"~/components/ui/label\";\nimport { RadioGroup, RadioGroupItem } from \"~/components/ui/radio-group\";\nimport { Dialog, DialogClose, DialogValue } from \"~/components/ui/dialog\";\nimport { LongDialogContent } from \"~/components/ui/long-dialog\";\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from \"~/components/ui/select\";\nimport {\n Table,\n TableBody,\n TableCell,\n TableHead,\n TableHeader,\n TableRow,\n} from \"~/components/ui/table\";\n\nconst json = { headers: { Accept: \"application/json\" }, withXSRFToken: true };\nconst SKIP = \"__skip__\";\ntype Step = \"upload\" | \"mapping\" | \"validating\" | \"report\";\n\n/** Counts of a finished dry run: what the real import would create, update and refuse. */\nexport function ImportSummary({ batch }: { batch: ImportBatch }) {\n return (\n <p className=\"text-sm tabular-nums\">\n سيُضاف {batch.created}\n {batch.mode === \"upsert\" && ` · سيُحدَّث ${batch.updated}`} · أخطاء{\" \"}\n {batch.failed}\n </p>\n );\n}\n\n/** The per-row dry-run report of a validated batch. */\nexport function ImportReport({ batch }: { batch: ImportBatch }) {\n if (!batch.report.length)\n return (\n <p className=\"text-sm text-muted-foreground\">\n لا يوجد تقرير صفوف لهذه الدفعة.\n </p>\n );\n return (\n <div className=\"max-h-80 overflow-y-auto rounded-lg border\">\n <Table aria-label=\"تقرير التحقق\">\n <TableHeader>\n <TableRow>\n <TableHead className=\"w-20\">الصف</TableHead>\n <TableHead className=\"w-28\">النتيجة</TableHead>\n <TableHead>الملاحظة</TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {batch.report.map((entry) => (\n <TableRow key={entry.row}>\n <TableCell className=\"tabular-nums\">{entry.row}</TableCell>\n <TableCell>\n {entry.ok ? (\n <Badge\n variant={\n entry.action === \"update\" ? \"secondary\" : \"outline\"\n }\n >\n {entry.action === \"update\" ? \"تحديث\" : \"إضافة\"}\n </Badge>\n ) : (\n <Badge variant=\"destructive\">خطأ</Badge>\n )}\n </TableCell>\n <TableCell className=\"text-xs whitespace-normal\">\n {entry.message ?? \"—\"}\n </TableCell>\n </TableRow>\n ))}\n </TableBody>\n </Table>\n </div>\n );\n}\n\n/**\n * Upload a file, map its columns to writable fields, choose add-only or add-or-update,\n * optionally validate every row without saving, then queue the import.\n */\nexport function ResourceImport({\n resource,\n label,\n accept = \".csv,.xlsx,text/csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n}: {\n resource: string;\n label: string;\n /** File picker filter; add the extensions of registered import adapters. */\n accept?: string;\n}) {\n const [open, setOpen] = useState(false);\n const [step, setStep] = useState<Step>(\"upload\");\n const [file, setFile] = useState<File | null>(null);\n const [batch, setBatch] = useState<ImportBatch | null>(null);\n const [mapping, setMapping] = useState<Record<string, string>>({});\n const [mode, setMode] = useState<ImportMode>(\"create\");\n const [matchField, setMatchField] = useState(\"\");\n const [error, setError] = useState(\"\");\n const [busy, setBusy] = useState(false);\n const reset = () => {\n setStep(\"upload\");\n setFile(null);\n setBatch(null);\n setMapping({});\n setMode(\"create\");\n setMatchField(\"\");\n setError(\"\");\n };\n const failure = (caught: unknown, fallback: string) =>\n setError(\n axios.isAxiosError(caught) && caught.response?.data?.error?.message\n ? String(caught.response.data.error.message)\n : fallback,\n );\n // The worker validates in the background; follow the batch until its report is ready.\n useEffect(() => {\n if (step !== \"validating\" || !batch) return;\n const timer = setInterval(async () => {\n try {\n const response = await axios.get<{ data: ImportBatch }>(\n `/imports/${batch.id}`,\n json,\n );\n const next = response.data.data;\n setBatch(next);\n if (next.status === \"validated\") setStep(\"report\");\n if (next.status === \"failed\") {\n setError(\"تعذر التحقق من الملف.\");\n setStep(\"mapping\");\n }\n } catch (caught) {\n failure(caught, \"تعذر قراءة حالة التحقق.\");\n }\n }, 1500);\n return () => clearInterval(timer);\n }, [step, batch?.id]);\n const unique = batch?.targets.filter((target) => target.unique) ?? [];\n const upload = async (event: React.FormEvent) => {\n event.preventDefault();\n if (!file) return;\n setBusy(true);\n setError(\"\");\n try {\n const form = new FormData();\n form.append(\"file\", file);\n const response = await axios.post<{ data: ImportBatch }>(\n `/resources/${resource}/imports`,\n form,\n json,\n );\n setBatch(response.data.data);\n setMapping(response.data.data.mapping);\n setStep(\"mapping\");\n } catch (caught) {\n failure(caught, \"تعذر قراءة الملف.\");\n } finally {\n setBusy(false);\n }\n };\n const run = async (dryRun: boolean) => {\n if (!batch) return;\n setBusy(true);\n setError(\"\");\n try {\n const response = await axios.post<{ data: ImportBatch }>(\n `/imports/${batch.id}/start`,\n {\n mapping,\n mode,\n matchField: mode === \"upsert\" ? matchField : undefined,\n dryRun,\n },\n json,\n );\n if (dryRun) {\n setBatch(response.data.data);\n setStep(\"validating\");\n return;\n }\n setOpen(false);\n reset();\n router.visit(\"/imports\");\n } catch (caught) {\n failure(caught, dryRun ? \"تعذر بدء التحقق.\" : \"تعذر بدء الاستيراد.\");\n } finally {\n setBusy(false);\n }\n };\n const description = {\n upload:\n \"ملف Excel (xlsx، الورقة الأولى فقط) أو CSV بترميز UTF-8، صفه الأول عناوين الأعمدة، حتى 5000 صف. نزّل القالب لتبدأ بالأعمدة الصحيحة.\",\n mapping: `طابِق أعمدة الملف (${batch?.total ?? 0} صفاً) مع الحقول، ثم تحقق دون حفظ أو ابدأ الاستيراد.`,\n validating: `جارٍ التحقق من الصفوف دون حفظ: ${batch?.processed ?? 0} من ${batch?.total ?? 0}.`,\n report:\n \"نتيجة التحقق لكل صف. لم يُحفظ شيء بعد؛ ابدأ الاستيراد أو ارجع لتعديل المطابقة.\",\n }[step];\n return (\n <>\n <Button variant=\"outline\" onClick={() => setOpen(true)}>\n <FileUp size={16} />\n استيراد من ملف\n </Button>\n <Dialog\n open={open}\n onOpenChange={(value) => {\n setOpen(value);\n if (!value) reset();\n }}\n >\n <LongDialogContent\n dir=\"rtl\"\n width=\"3xl\"\n title={<>استيراد إلى {label}</>}\n description={description}\n footer={\n <>\n {step === \"mapping\" && (\n <Button\n type=\"button\"\n variant=\"outline\"\n disabled={busy || (mode === \"upsert\" && !matchField)}\n onClick={() => void run(true)}\n >\n تحقق دون حفظ\n </Button>\n )}\n {step === \"report\" && (\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => setStep(\"mapping\")}\n >\n تعديل المطابقة\n </Button>\n )}\n <DialogClose asChild>\n <Button type=\"button\" variant=\"outline\">\n إلغاء\n </Button>\n </DialogClose>\n {step === \"upload\" && (\n <Button\n type=\"submit\"\n form=\"import-upload\"\n disabled={busy || !file}\n >\n رفع الملف\n </Button>\n )}\n {step === \"mapping\" && (\n <Button\n type=\"submit\"\n form=\"import-mapping\"\n disabled={busy || (mode === \"upsert\" && !matchField)}\n >\n بدء الاستيراد\n </Button>\n )}\n {step === \"report\" && (\n <Button\n type=\"button\"\n disabled={busy}\n onClick={() => void run(false)}\n >\n بدء الاستيراد\n </Button>\n )}\n </>\n }\n >\n {/* Each step starts afresh: the uploaded file is saved, and the suggested mapping is\n the new starting point. */}\n <DialogValue\n key={step === \"upload\" ? \"upload\" : `mapping-${batch?.id ?? \"\"}`}\n value={step === \"upload\" ? file : { mapping, mode, matchField }}\n />\n {step === \"upload\" && (\n <form\n id=\"import-upload\"\n className=\"space-y-3\"\n onSubmit={upload}\n >\n <div className=\"space-y-2\">\n <Label id=\"import-file-label\" htmlFor=\"import-file\">\n الملف\n </Label>\n <FileInput\n id=\"import-file\"\n labelId=\"import-file-label\"\n accept={accept}\n onFilesChange={(files) => setFile(files[0] ?? null)}\n />\n </div>\n <div className=\"flex flex-wrap gap-x-4\">\n <Button\n type=\"button\"\n variant=\"link\"\n size=\"sm\"\n className=\"px-0\"\n asChild\n >\n <a\n href={`/resources/${resource}/imports/template?format=xlsx`}\n download\n >\n <Download size={14} />\n تنزيل قالب Excel\n </a>\n </Button>\n <Button\n type=\"button\"\n variant=\"link\"\n size=\"sm\"\n className=\"px-0\"\n asChild\n >\n <a href={`/resources/${resource}/imports/template`} download>\n <Download size={14} />\n تنزيل قالب CSV\n </a>\n </Button>\n </div>\n </form>\n )}\n {step === \"mapping\" && batch && (\n <form\n id=\"import-mapping\"\n className=\"space-y-4\"\n onSubmit={(event) => {\n event.preventDefault();\n void run(false);\n }}\n >\n <fieldset className=\"space-y-2\">\n <legend className=\"text-sm font-medium\">نمط الاستيراد</legend>\n <RadioGroup\n value={mode}\n onValueChange={(value) => setMode(value as ImportMode)}\n className=\"flex flex-wrap gap-6\"\n >\n <div className=\"flex items-center gap-2\">\n <RadioGroupItem id=\"import-mode-create\" value=\"create\" />\n <Label htmlFor=\"import-mode-create\">إضافة فقط</Label>\n </div>\n <div className=\"flex items-center gap-2\">\n <RadioGroupItem\n id=\"import-mode-upsert\"\n value=\"upsert\"\n disabled={unique.length === 0}\n />\n <Label htmlFor=\"import-mode-upsert\">إضافة أو تحديث</Label>\n </div>\n </RadioGroup>\n {unique.length === 0 && (\n <p className=\"text-xs text-muted-foreground\">\n التحديث يحتاج حقلاً فريداً، ولا يوجد حقل فريد قابل للاستيراد\n هنا.\n </p>\n )}\n </fieldset>\n {mode === \"upsert\" && (\n <div className=\"grid grid-cols-2 items-center gap-3\">\n <div>\n <p className=\"text-sm font-medium\">حقل المطابقة</p>\n <p className=\"text-xs text-muted-foreground\">\n يُحدَّث السجل الذي يحمل القيمة نفسها، ويُضاف الباقي.\n الخلية الفارغة تُبقي القيمة المحفوظة.\n </p>\n </div>\n <Select value={matchField} onValueChange={setMatchField}>\n <SelectTrigger aria-label=\"حقل المطابقة\">\n <SelectValue placeholder=\"اختر حقلاً فريداً\" />\n </SelectTrigger>\n <SelectContent>\n {unique.map((target) => (\n <SelectItem key={target.key} value={target.key}>\n {target.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n )}\n <div className=\"space-y-3 border-t pt-4\">\n {batch.headers.map((header, index) => (\n <div\n key={index}\n className=\"grid grid-cols-2 items-center gap-3\"\n >\n <div className=\"min-w-0\">\n <p className=\"truncate text-sm font-medium\">\n {header || `عمود ${index + 1}`}\n </p>\n <p className=\"truncate text-xs text-muted-foreground\">\n مثال: {batch.sample[0]?.[index] || \"—\"}\n </p>\n </div>\n <Select\n value={mapping[String(index)] ?? SKIP}\n onValueChange={(value) =>\n setMapping((current) => {\n const next = { ...current };\n if (value === SKIP) delete next[String(index)];\n else next[String(index)] = value;\n return next;\n })\n }\n >\n <SelectTrigger\n aria-label={`حقل العمود ${header || index + 1}`}\n >\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value={SKIP}>تجاهل العمود</SelectItem>\n {batch.targets.map((target) => (\n <SelectItem key={target.key} value={target.key}>\n {target.label}\n {target.required ? \" *\" : \"\"}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n ))}\n </div>\n </form>\n )}\n {step === \"validating\" && batch && (\n <div\n role=\"progressbar\"\n aria-label=\"تقدم التحقق\"\n aria-valuemin={0}\n aria-valuemax={batch.total}\n aria-valuenow={batch.processed}\n className=\"h-2 overflow-hidden rounded-full bg-muted\"\n >\n <div\n className=\"h-full bg-primary transition-all\"\n style={{\n width: `${batch.total ? (batch.processed / batch.total) * 100 : 0}%`,\n }}\n />\n </div>\n )}\n {step === \"report\" && batch && (\n <div className=\"space-y-3\">\n <ImportSummary batch={batch} />\n <ImportReport batch={batch} />\n </div>\n )}\n {error && (\n <p\n role=\"alert\"\n className=\"rounded-lg bg-destructive/10 px-3 py-2 text-xs text-destructive\"\n >\n {error}\n </p>\n )}\n </LongDialogContent>\n </Dialog>\n </>\n );\n}\n",
23
24
  "target": "inertia/components/ui/resource-import.tsx"
24
25
  }
25
26
  ],