@adula/ui 2.0.0 → 2.2.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.
- package/README.md +14 -3
- package/build/attachment-preview.json +21 -0
- package/build/calendar.json +1 -1
- package/build/checkbox.json +1 -1
- package/build/command.json +1 -1
- package/build/confirm-action.json +3 -2
- package/build/data-table.json +7 -2
- package/build/dialog.json +3 -2
- package/build/dropdown-menu.json +1 -1
- package/build/form.json +1 -1
- package/build/hijri-calendar.json +1 -1
- package/build/label.json +1 -1
- package/build/list-filters.json +34 -0
- package/build/manifest.json +106 -76
- package/build/messages.json +21 -0
- package/build/pagination.json +3 -2
- package/build/popover.json +1 -1
- package/build/radio-group.json +1 -1
- package/build/record-collaboration.json +3 -2
- package/build/record-print.json +24 -0
- package/build/record-workflows.json +1 -1
- package/build/resource-actions.json +3 -2
- package/build/resource-bulk.json +27 -0
- package/build/resource-dashboard.json +27 -0
- package/build/resource-field.json +6 -2
- package/build/resource-form.json +3 -2
- package/build/resource-import.json +5 -2
- package/build/resource-page.json +3 -2
- package/build/resource-show.json +4 -2
- package/build/resource-surface.json +3 -2
- package/build/resource-value.json +10 -2
- package/build/select.json +1 -1
- package/build/separator.json +1 -1
- package/build/sheet.json +1 -1
- package/build/sonner.json +1 -1
- package/build/switch.json +1 -1
- package/build/table.json +1 -1
- package/build/tabs.json +1 -1
- package/build/theme.css +16 -16
- package/build/tooltip.json +1 -1
- package/package.json +5 -2
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
"input",
|
|
6
6
|
"textarea",
|
|
7
7
|
"button",
|
|
8
|
+
"checkbox",
|
|
9
|
+
"badge",
|
|
8
10
|
"label",
|
|
9
11
|
"select",
|
|
10
12
|
"switch",
|
|
@@ -12,9 +14,11 @@
|
|
|
12
14
|
"calendar",
|
|
13
15
|
"command",
|
|
14
16
|
"resource-value",
|
|
17
|
+
"attachment-preview",
|
|
15
18
|
"hijri-calendar",
|
|
16
19
|
"calendar-date",
|
|
17
|
-
"ui-preferences"
|
|
20
|
+
"ui-preferences",
|
|
21
|
+
"messages"
|
|
18
22
|
],
|
|
19
23
|
"dependencies": [
|
|
20
24
|
"axios@1.19.0",
|
|
@@ -25,7 +29,7 @@
|
|
|
25
29
|
{
|
|
26
30
|
"path": "registry/ui/resource-field.tsx",
|
|
27
31
|
"type": "registry:ui",
|
|
28
|
-
"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 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 { Button } from '~/components/ui/button'\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 {\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 { Popover, PopoverContent, PopoverTrigger } 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 CURRENCY_LABEL,\n fileSize,\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 /** 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 // 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={placeholder} />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value=\"value:\">{placeholder}</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 return (\n <div\n className={`min-w-0 space-y-2 ${['text', 'json'].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 htmlFor={id}>{field.label.ar}</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 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 '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\">{value === 'true' ? 'نعم' : 'لا'}</span>\n </div>\n )\n case 'attachment':\n return <AttachmentControl {...props} />\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 default:\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}\n\nfunction MoneyControl({ id, value, onChange, disabled, error, field, label }: FieldProps) {\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 <div className=\"relative\">\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 {CURRENCY_LABEL}\n </span>\n </div>\n {preview && (\n <p className=\"text-xs text-muted-foreground\" dir=\"ltr\">\n {preview} {CURRENCY_LABEL}\n </p>\n )}\n </div>\n )\n}\n\nfunction DateControl({ id, value, onChange, disabled, error, field, label }: FieldProps) {\n const { calendar: preference } = useUiPreferences()\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={`تقويم الإدخال: ${label ?? field.label.ar}`}\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 إدخال ميلادي\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 إدخال هجري\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={`التقويم: ${label ?? field.label.ar}`}\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 هجري · أم القرى {valid && <span dir=\"ltr\">({normalized} ميلادي)</span>}\n </p>\n )}\n {preference === 'both' && calendar === 'gregory' && valid && (\n <p className=\"text-xs text-muted-foreground\" aria-live=\"polite\">\n الموافق هجريًا: <span dir=\"ltr\">{calendarInput(normalized, 'islamic-umalqura')}</span> هـ\n </p>\n )}\n </div>\n )\n}\n\nfunction DatetimeControl(props: FieldProps) {\n const { calendar } = useUiPreferences()\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={`الوقت: ${props.label ?? props.field.label.ar}`}\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 [invalid, setInvalid] = useState('')\n const check = () => {\n if (!value.trim()) return setInvalid('')\n try {\n JSON.parse(value)\n setInvalid('')\n } catch {\n setInvalid('أدخل بيانات 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('أدخل بيانات JSON صحيحة')\n }\n }}\n >\n تنسيق 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 [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 ?? 'تعذر رفع الملف. حاول مجدداً.')\n : 'تعذر الاتصال بالخادم.'\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)}</span>\n <span className=\"ms-auto flex gap-1\">\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 استبدال\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 إزالة\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 ? 'اختيار ملف' : `جارٍ الرفع ${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={`رفع ${label ?? field.label.ar}`}\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\ntype OptionPage = { data: Option[]; nextCursor: string | null }\n/** Server-side search through the authorized options route; keyset \"more\" keeps large relations usable. */\nfunction RelationCombobox({\n id,\n value,\n onChange,\n disabled,\n error,\n field,\n label,\n options = [],\n relation,\n}: FieldProps) {\n const [open, setOpen] = useState(false)\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 listId = useId()\n const current =\n loaded.find((option) => option.value === value) ??\n options.find((option) => option.value === value)\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) => option.value === value)\n return [\n ...new Map([...keep, ...page.data].map((option) => [option.value, option])).values(),\n ]\n })\n } catch {\n setFailure('تعذر تحميل الخيارات')\n }\n }\n useEffect(() => () => clearTimeout(timer.current), [])\n const searchable = Boolean(relation?.searchable)\n return (\n <Popover\n open={open}\n onOpenChange={(next) => {\n setOpen(next)\n if (next && relation && !fetched) void load(false, '')\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' ? 'اختر مستخدماً' : 'اختر سجلاً')}\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 ? 'ابحث بالاسم'\n : searchable\n ? 'ابحث في السجلات المرتبطة'\n : 'تصفية الخيارات'\n }\n aria-label={`البحث في ${label ?? field.label.ar}`}\n value={search}\n onValueChange={(term) => {\n setSearch(term)\n if (!searchable) return\n clearTimeout(timer.current)\n timer.current = setTimeout(() => void load(false, term), 300)\n }}\n />\n <CommandList id={listId}>\n <CommandEmpty>\n {http.processing ? 'جارٍ البحث...' : 'لا توجد سجلات مطابقة'}\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 بدون اختيار\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 ? 'جارٍ التحميل...' : 'المزيد'}\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 live = rows.filter((row) => !row.deleted)\n return (\n <section aria-label={field.label.ar} 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\">{field.label.ar}</h2>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {live.length ? `${live.length} بند` : 'لا توجد بنود بعد'}\n {inline.hasMore && ' · تظهر أول 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 إضافة بند\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 {child.label.ar}\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\">الإجراء</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 return (\n <tr\n key={row.key}\n aria-label={`بند ${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 <FieldControl\n field={child}\n id={`${field.key}-${row.key}-${child.key}`}\n label={`${child.label.ar} للبند ${number}`}\n value={row.values[child.key] ?? ''}\n disabled={disabled || row.deleted || !editable(row, child.key)}\n error={rowErrors[child.key]}\n resource={resource}\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 {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={`إزالة البند ${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 ? `التراجع عن حذف البند ${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",
|
|
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",
|
|
29
33
|
"target": "inertia/components/ui/resource-field.tsx"
|
|
30
34
|
}
|
|
31
35
|
],
|
package/build/resource-form.json
CHANGED
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
"label",
|
|
8
8
|
"resource-actions",
|
|
9
9
|
"resource-field",
|
|
10
|
-
"resource-value"
|
|
10
|
+
"resource-value",
|
|
11
|
+
"messages"
|
|
11
12
|
],
|
|
12
13
|
"dependencies": [
|
|
13
14
|
"axios@1.19.0",
|
|
@@ -18,7 +19,7 @@
|
|
|
18
19
|
{
|
|
19
20
|
"path": "registry/ui/resource-form.tsx",
|
|
20
21
|
"type": "registry:ui",
|
|
21
|
-
"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 { inputValue, isAttachment, parseValue } from '~/components/ui/resource-value'\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 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\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 for (const child of definition.fields) {\n if (!allowed.includes(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] = (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.ar ?? 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 const raw = values[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 if (editor.mode === 'create' && raw === '' && !field.required) continue\n try {\n const parsed = parseValue(field, raw)\n if (parsed === null && field.required) throw new Error('هذا الحقل مطلوب')\n payload[field.key] = parsed\n } catch (error) {\n fieldErrors[field.key] = (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: 'راجع الحقول المحددة ثم أعد المحاولة.', 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 ? `تمت إضافة ${editor.recordLabel}`\n : 'تمت إضافة السجل'\n : 'تم حفظ التعديلات'\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 ? 'تغير السجل منذ فتحه. احتفظ بتعديلاتك ثم أعد تحميل الصفحة.'\n : unknown.length\n ? unknown.join(' · ')\n : failureMessage(error, 'تعذر الحفظ. راجع البيانات وحاول مجدداً.'),\n })\n } finally {\n setBusy(false)\n }\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 ? 'تعارض في الإصدار' : 'تعذر الحفظ'}</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 إعادة التحميل\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\">تفاصيل السجل</h2>\n <p className=\"mt-2 text-xs text-muted-foreground\">\n الحقول المتاحة بحسب صلاحياتك · الحقول المعلّمة بـ{' '}\n <span className=\"text-destructive\">*</span> مطلوبة\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 الوحدة التنظيمية\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.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 onChange={(value) => setValues((current) => ({ ...current, [field.key]: value }))}\n relation={\n field.type === 'belongsTo'\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 إلغاء\n </Button>\n ) : (\n <Button type=\"button\" variant=\"outline\" asChild>\n <Link href={editor.record ? `${base}/${editor.record.id}` : base}>إلغاء</Link>\n </Button>\n )}\n <Button type=\"submit\" disabled={busy}>\n <Save size={16} />\n {busy ? 'جارٍ الحفظ...' : 'حفظ السجل'}\n </Button>\n </div>\n </div>\n </form>\n )\n}\n",
|
|
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",
|
|
22
23
|
"target": "inertia/components/ui/resource-form.tsx"
|
|
23
24
|
}
|
|
24
25
|
],
|
|
@@ -2,11 +2,14 @@
|
|
|
2
2
|
"name": "resource-import",
|
|
3
3
|
"type": "registry:ui",
|
|
4
4
|
"registryDependencies": [
|
|
5
|
+
"badge",
|
|
5
6
|
"button",
|
|
6
7
|
"input",
|
|
7
8
|
"label",
|
|
9
|
+
"radio-group",
|
|
8
10
|
"dialog",
|
|
9
|
-
"select"
|
|
11
|
+
"select",
|
|
12
|
+
"table"
|
|
10
13
|
],
|
|
11
14
|
"dependencies": [
|
|
12
15
|
"lucide-react@1.47.0",
|
|
@@ -16,7 +19,7 @@
|
|
|
16
19
|
{
|
|
17
20
|
"path": "registry/ui/resource-import.tsx",
|
|
18
21
|
"type": "registry:ui",
|
|
19
|
-
"content": "import { useState } from 'react'\nimport { router } from '@inertiajs/react'\nimport axios from 'axios'\nimport { FileUp } from 'lucide-react'\nimport type { ImportBatch } from 'adula'\nimport { Button } from '~/components/ui/button'\nimport { Input } from '~/components/ui/input'\nimport { Label } from '~/components/ui/label'\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'\n\nconst json = { headers: { Accept: 'application/json' }, withXSRFToken: true }\nconst SKIP = '__skip__'\n\n/** Upload a CSV, map its columns to writable fields, then queue the import. */\nexport function ResourceImport({ resource, label }: { resource: string; label: string }) {\n const [open, setOpen] = useState(false)\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 [error, setError] = useState('')\n const [busy, setBusy] = useState(false)\n const reset = () => {\n setFile(null)\n setBatch(null)\n setMapping({})\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 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 } catch (caught) {\n failure(caught, 'تعذر قراءة الملف.')\n } finally {\n setBusy(false)\n }\n }\n const start = async (event: React.FormEvent) => {\n event.preventDefault()\n if (!batch) return\n setBusy(true)\n setError('')\n try {\n await axios.post(`/imports/${batch.id}/start`, { mapping }, json)\n setOpen(false)\n reset()\n router.visit('/imports')\n } catch (caught) {\n failure(caught, 'تعذر بدء الاستيراد.')\n } finally {\n setBusy(false)\n }\n }\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>\n {batch\n ? `طابِق أعمدة الملف (${batch.total} صفاً) مع الحقول، ثم ابدأ الاستيراد.`\n : 'ملف CSV بترميز UTF-8، صفه الأول عناوين الأعمدة، حتى 5000 صف.'}\n </DialogDescription>\n </DialogHeader>\n {!batch ? (\n <form id=\"import-upload\" className=\"space-y-2\" onSubmit={upload}>\n <Label htmlFor=\"import-file\">الملف</Label>\n <Input\n id=\"import-file\"\n type=\"file\"\n accept=\".csv,text/csv\"\n onChange={(event) => setFile(event.target.files?.[0] ?? null)}\n />\n </form>\n ) : (\n <form\n id=\"import-mapping\"\n className=\"max-h-96 space-y-3 overflow-y-auto\"\n onSubmit={start}\n >\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 </form>\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 {batch ? (\n <Button type=\"submit\" form=\"import-mapping\" disabled={busy}>\n بدء الاستيراد\n </Button>\n ) : (\n <Button type=\"submit\" form=\"import-upload\" disabled={busy || !file}>\n رفع الملف\n </Button>\n )}\n </DialogFooter>\n </DialogContent>\n </Dialog>\n </>\n )\n}\n",
|
|
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",
|
|
20
23
|
"target": "inertia/components/ui/resource-import.tsx"
|
|
21
24
|
}
|
|
22
25
|
],
|
package/build/resource-page.json
CHANGED
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
"resource-form",
|
|
8
8
|
"resource-show",
|
|
9
9
|
"resource-surface",
|
|
10
|
-
"resource-import"
|
|
10
|
+
"resource-import",
|
|
11
|
+
"messages"
|
|
11
12
|
],
|
|
12
13
|
"dependencies": [
|
|
13
14
|
"lucide-react@1.47.0"
|
|
@@ -16,7 +17,7 @@
|
|
|
16
17
|
{
|
|
17
18
|
"path": "registry/ui/resource-page.tsx",
|
|
18
19
|
"type": "registry:ui",
|
|
19
|
-
"content": "import { Head, usePage } from '@inertiajs/react'\nimport { Link } from '@adonisjs/inertia/react'\nimport { Plus } from 'lucide-react'\nimport type {\n RecordPermissions,\n ResourceActivity,\n ResourceChildren,\n ResourceDescription,\n ResourceEditor,\n ResourceList,\n ResourceLookups,\n SavedView,\n ResourceShow as Show,\n} from 'adula'\nimport { Button } from '~/components/ui/button'\nimport { DataTable } from '~/components/ui/data-table'\nimport { ResourceForm } from '~/components/ui/resource-form'\nimport { ResourceShow } from '~/components/ui/resource-show'\nimport { ResourceImport } from '~/components/ui/resource-import'\nimport {\n ResourceSurface,\n closeRecord,\n openRecord,\n type RecordOverlay,\n type ResourcePresentation,\n} from '~/components/ui/resource-surface'\n\n/** The discriminated view stays nested: Inertia's page typing flattens top-level unions. */\nexport type ResourceView =\n | {\n mode: 'index'\n resource: ResourceDescription\n lookups: ResourceLookups\n savedViews: SavedView[]\n }\n | { mode: 'form'; editor: ResourceEditor; permissions: RecordPermissions }\n | {\n mode: 'show'\n resource: ResourceDescription\n result: Show\n lookups: ResourceLookups\n childResources: Record<string, ResourceDescription>\n }\nexport type ResourcePageProps = {\n view: ResourceView\n /** Index pages receive the list as a top-level `inertia.scroll` prop so pages merge into `result.data`. */\n result?: ResourceList\n childrenData?: ResourceChildren\n activity?: ResourceActivity\n /** Set to page only when the user requests a non-modal form/detail override. */\n presentation?: ResourcePresentation\n}\ntype RecordView = Exclude<ResourceView, { mode: 'index' }>\n\n/** Title of a record dialog: «إضافة حساب», «تعديل · الحسابات» or «تفاصيل · الحسابات». */\nfunction recordTitle(view: RecordView) {\n if (view.mode === 'show') return
|
|
20
|
+
"content": "import { Head, usePage } from '@inertiajs/react'\nimport { Link } from '@adonisjs/inertia/react'\nimport { Plus } from 'lucide-react'\nimport type {\n RecordPermissions,\n ResourceActivity,\n ResourceChildren,\n ResourceDescription,\n ResourceEditor,\n ResourceList,\n ResourceLookups,\n SavedView,\n ResourceShow as Show,\n} from 'adula'\nimport { Button } from '~/components/ui/button'\nimport { DataTable } from '~/components/ui/data-table'\nimport { ResourceForm } from '~/components/ui/resource-form'\nimport { ResourceShow } from '~/components/ui/resource-show'\nimport { ResourceImport } from '~/components/ui/resource-import'\nimport {\n ResourceSurface,\n closeRecord,\n openRecord,\n type RecordOverlay,\n type ResourcePresentation,\n} from '~/components/ui/resource-surface'\nimport { useMessages, type Translate } from '~/components/ui/messages'\n\n/** The discriminated view stays nested: Inertia's page typing flattens top-level unions. */\nexport type ResourceView =\n | {\n mode: 'index'\n resource: ResourceDescription\n lookups: ResourceLookups\n savedViews: SavedView[]\n /** `/resources/:name/trash`: the soft-deleted records, offered for restore (ADR 046). */\n trashed?: boolean\n }\n | { mode: 'form'; editor: ResourceEditor; permissions: RecordPermissions }\n | {\n mode: 'show'\n resource: ResourceDescription\n result: Show\n lookups: ResourceLookups\n childResources: Record<string, ResourceDescription>\n }\nexport type ResourcePageProps = {\n view: ResourceView\n /** Index pages receive the list as a top-level `inertia.scroll` prop so pages merge into `result.data`. */\n result?: ResourceList\n childrenData?: ResourceChildren\n activity?: ResourceActivity\n /** Set to page only when the user requests a non-modal form/detail override. */\n presentation?: ResourcePresentation\n}\ntype RecordView = Exclude<ResourceView, { mode: 'index' }>\n\n/** Title of a record dialog: «إضافة حساب», «تعديل · الحسابات» or «تفاصيل · الحسابات». */\nfunction recordTitle(view: RecordView, t: Translate) {\n if (view.mode === 'show') return t('تفاصيل · {resource}', { resource: view.resource.label })\n const create = view.editor.mode === 'create'\n // A singular record noun («حساب») reads better than the plural list label (#37).\n if (view.editor.recordLabel)\n return create\n ? t('إضافة {record}', { record: view.editor.recordLabel })\n : t('تعديل {record}', { record: view.editor.recordLabel })\n return create\n ? t('إضافة · {resource}', { resource: view.editor.label })\n : t('تعديل · {resource}', { resource: view.editor.label })\n}\n\nfunction RecordBody({\n view,\n childrenData,\n activity,\n onSaved,\n onCancel,\n onEdit,\n onAction,\n}: {\n view: RecordView\n childrenData?: ResourceChildren\n activity?: ResourceActivity\n onSaved?: (id: number) => void\n onCancel?: () => void\n onEdit?: () => void\n onAction?: (action: string) => void\n}) {\n return view.mode === 'form' ? (\n <ResourceForm\n key={`${view.editor.name}:${view.editor.record?.id ?? 'new'}`}\n editor={view.editor}\n permissions={view.permissions}\n onSaved={onSaved}\n onCancel={onCancel}\n onAction={onAction}\n />\n ) : (\n <ResourceShow\n key={`${view.resource.name}:${view.result.data.id}`}\n resource={view.resource}\n result={view.result}\n lookups={view.lookups}\n childResources={view.childResources}\n childrenData={childrenData}\n activity={activity}\n onEdit={onEdit}\n onAction={onAction}\n />\n )\n}\n\nexport function ResourcePage({\n view,\n result,\n childrenData,\n activity,\n presentation,\n}: ResourcePageProps) {\n // A record opened over this list by openRecord(); a client-only prop, never sent by the server.\n const overlay = usePage<{ overlay?: RecordOverlay }>().props.overlay\n const { t } = useMessages()\n const name = view.mode === 'form' ? view.editor.name : view.resource.name\n const label = view.mode === 'form' ? view.editor.label : view.resource.label\n const trashed = view.mode === 'index' && view.trashed === true\n const title =\n view.mode === 'index'\n ? trashed\n ? t('المحذوفات · {resource}', { resource: label })\n : label\n : recordTitle(view, t)\n const noun = view.mode === 'index' ? view.resource.recordLabel : null\n const createText =\n view.mode === 'index'\n ? (view.resource.createLabel ??\n (noun ? t('إضافة {record}', { record: noun }) : t('إضافة سجل')))\n : ''\n const overlayView = view.mode === 'index' ? (overlay?.view as RecordView | undefined) : undefined\n const overlayRecord =\n overlayView?.mode === 'form' ? overlayView.editor.record?.id : overlayView?.result.data.id\n const overlayId =\n overlayRecord === undefined || overlayRecord === null ? undefined : String(overlayRecord)\n return (\n <>\n <Head title={title} />\n {view.mode === 'index' && (\n <div className=\"mb-8 flex flex-wrap items-start justify-between gap-5\">\n <div>\n <h1 className=\"text-3xl font-semibold tracking-tight\">{title}</h1>\n <p className=\"mt-3 text-sm text-muted-foreground\">\n {trashed\n ? t('السجلات المحذوفة ضمن نطاقك؛ استعد ما تحتاجه منها إلى السجلات النشطة.')\n : t('سجلاتك ومتابعتك اليومية في مكان واحد.')}\n </p>\n </div>\n {view.mode === 'index' && view.resource.canCreate && !trashed && (\n <div className=\"flex flex-wrap gap-2\">\n <ResourceImport resource={name} label={label} />\n <Button asChild>\n <Link href={`/resources/${name}/create`}>\n <Plus size={16} />\n {createText}\n </Link>\n </Button>\n </div>\n )}\n </div>\n )}\n {view.mode === 'index' ? (\n <>\n {result ? (\n <DataTable\n key={`${name}:${trashed ? 'trash' : 'active'}`}\n resource={view.resource}\n result={result}\n lookups={view.lookups}\n savedViews={view.savedViews}\n trashed={trashed}\n />\n ) : null}\n {overlay && overlayView && overlayId !== undefined && (\n // Keyed by record, so saving an edit switches the same dialog to the details.\n <ResourceSurface\n key={`overlay:${name}:${overlayId}`}\n mode={overlayView.mode === 'form' ? 'edit' : 'view'}\n title={recordTitle(overlayView, t)}\n description={\n overlayView.mode === 'form'\n ? t('أكمل الحقول المطلوبة ثم احفظ السجل.')\n : t('راجع التفاصيل المتاحة لك وأكمل عملك.')\n }\n backHref={overlay.list}\n onClose={() => closeRecord(overlay)}\n >\n <RecordBody\n view={overlayView}\n childrenData={childrenData}\n activity={activity}\n onSaved={(id) =>\n void openRecord(name, id, 'show', {\n replace: true,\n changed: true,\n })\n }\n onCancel={() => void openRecord(name, overlayId, 'show', { replace: true })}\n onEdit={() => void openRecord(name, overlayId, 'edit', { replace: true })}\n onAction={(action) =>\n action === 'delete'\n ? closeRecord({ ...overlay, changed: true })\n : void openRecord(name, overlayId, 'show', {\n replace: true,\n changed: true,\n })\n }\n />\n </ResourceSurface>\n )}\n </>\n ) : (\n <ResourceSurface\n // Keyed by record, not mode: saving an edit shows the details in the same dialog.\n key={`${name}:${view.mode === 'form' ? (view.editor.record?.id ?? 'new') : view.result.data.id}`}\n mode={view.mode === 'form' ? 'edit' : 'view'}\n title={title}\n description={\n view.mode === 'form'\n ? t('أكمل الحقول المطلوبة ثم احفظ السجل.')\n : t('راجع التفاصيل المتاحة لك وأكمل عملك.')\n }\n backHref={`/resources/${name}`}\n presentation={presentation}\n >\n <RecordBody view={view} childrenData={childrenData} activity={activity} />\n </ResourceSurface>\n )}\n </>\n )\n}\n",
|
|
20
21
|
"target": "inertia/components/ui/resource-page.tsx"
|
|
21
22
|
}
|
|
22
23
|
],
|
package/build/resource-show.json
CHANGED
|
@@ -11,7 +11,9 @@
|
|
|
11
11
|
"ui-preferences",
|
|
12
12
|
"record-collaboration",
|
|
13
13
|
"record-assignments",
|
|
14
|
-
"record-workflows"
|
|
14
|
+
"record-workflows",
|
|
15
|
+
"record-print",
|
|
16
|
+
"messages"
|
|
15
17
|
],
|
|
16
18
|
"dependencies": [
|
|
17
19
|
"lucide-react@1.47.0"
|
|
@@ -20,7 +22,7 @@
|
|
|
20
22
|
{
|
|
21
23
|
"path": "registry/ui/resource-show.tsx",
|
|
22
24
|
"type": "registry:ui",
|
|
23
|
-
"content": "import { Deferred, router } from '@inertiajs/react'\nimport { Link } from '@adonisjs/inertia/react'\nimport { History, Pencil, Printer } from 'lucide-react'\nimport type {\n ResourceActivity,\n ResourceChildren as Children,\n ResourceDescription,\n ResourceShow as Show,\n SerializedRecord,\n} from 'adula'\nimport { Badge } from '~/components/ui/badge'\nimport { Button } from '~/components/ui/button'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\nimport { Can } from '~/components/ui/can'\nimport { Skeleton } from '~/components/ui/skeleton'\nimport { ResourceActions } from '~/components/ui/resource-actions'\nimport { ResourceValue, formatDatetime, type LookupOptions } from '~/components/ui/resource-value'\nimport { RecordCollaboration } from '~/components/ui/record-collaboration'\nimport { RecordAssignments } from '~/components/ui/record-assignments'\nimport { RecordWorkflows } from '~/components/ui/record-workflows'\n\nexport type ResourceChildren = Children\nconst meta = new Set(['id', 'version', 'docStatus', 'orgUnitId'])\nconst activityLabels: Record<string, string> = {\n create: 'إنشاء السجل',\n update: 'تعديل السجل',\n delete: 'حذف السجل',\n submit: 'اعتماد المستند',\n cancel: 'إلغاء الاعتماد',\n amend: 'تعديل بعد الاعتماد',\n assignment_closed: 'إغلاق مهمة مع السجل',\n}\n\nexport function documentStatus(status: unknown) {\n return status === 1 ? 'معتمد' : status === 2 ? 'ملغي' : 'مسودة'\n}\n\nexport function ResourceShow({\n resource,\n result,\n lookups = {},\n childResources = {},\n childrenData,\n activity,\n onEdit,\n onAction,\n}: {\n resource: ResourceDescription\n result: Show\n lookups?: LookupOptions\n childResources?: Record<string, ResourceDescription>\n childrenData?: ResourceChildren\n activity?: ResourceActivity\n /** Replaces the edit link (record dialogs switch to the form in place). */\n onEdit?: () => void\n /** Called after a record action instead of reloading or leaving the page. */\n onAction?: (action: string) => void\n}) {\n const { calendar } = useUiPreferences()\n const base = `/resources/${resource.name}/${result.data.id}`\n const fields = resource.fields.filter(\n (field) =>\n resource.show.includes(field.key) && field.type !== 'hasMany' && field.key in result.data\n )\n const children = resource.fields.filter(\n (field) => field.type === 'hasMany' && resource.show.includes(field.key)\n )\n const fieldLabel = (key: string) =>\n resource.fields.find((field) => field.key === key)?.label.ar ?? key\n return (\n <div className=\"max-w-5xl space-y-6\">\n <div className=\"flex flex-wrap items-center gap-3\">\n <Can permissions={result.permissions} action=\"update\">\n {onEdit ? (\n <Button onClick={onEdit}>\n <Pencil size={15} />\n تعديل السجل\n </Button>\n ) : (\n <Button asChild>\n <Link href={`${base}/edit`}>\n <Pencil size={15} />\n تعديل السجل\n </Link>\n </Button>\n )}\n </Can>\n <Button variant=\"outline\" asChild>\n <a href={`${base}/print`} target=\"_blank\" rel=\"noopener\">\n <Printer size={15} />\n طباعة\n </a>\n </Button>\n <ResourceActions\n resource={resource.name}\n id={result.data.id as number}\n version={result.data.version ?? undefined}\n permissions={result.permissions}\n onDone={(action) =>\n onAction\n ? onAction(action)\n : action === 'delete'\n ? router.visit(`/resources/${resource.name}`)\n : router.reload()\n }\n />\n {resource.submittable && (\n <Badge\n variant={result.data.docStatus === 1 ? 'default' : 'secondary'}\n className={result.data.docStatus === 2 ? 'bg-red-50 text-red-800' : ''}\n >\n {documentStatus(result.data.docStatus)}\n </Badge>\n )}\n </div>\n <dl className=\"grid gap-7 rounded-xl border bg-white p-7 md:grid-cols-2\">\n {fields.map((field) => (\n <div\n key={field.key}\n className={['text', 'json'].includes(field.type) ? 'md:col-span-2' : ''}\n >\n <dt className=\"mb-2 text-xs text-muted-foreground\">{field.label.ar}</dt>\n <dd className=\"break-words text-sm whitespace-pre-wrap\">\n <ResourceValue\n field={field}\n row={result.data}\n related={result.related}\n lookups={lookups}\n />\n </dd>\n </div>\n ))}\n {resource.scoped && result.data.orgUnitId !== undefined && (\n <div>\n <dt className=\"mb-2 text-xs text-muted-foreground\">الوحدة التنظيمية</dt>\n <dd className=\"text-sm\">#{String(result.data.orgUnitId)}</dd>\n </div>\n )}\n </dl>\n {children.length > 0 && (\n <Deferred data=\"childrenData\" fallback={<SectionSkeleton title=\"البنود\" rows={3} />}>\n <div className=\"space-y-5\">\n {children.map((field) => {\n const group = childrenData?.[field.key]\n if (!group) return null\n const child = childResources[field.key]\n const columns = child\n ? child.fields.filter(\n (entry) => child.list.includes(entry.key) && entry.type !== 'hasMany'\n )\n : []\n const keys = columns.length\n ? columns.map((entry) => entry.key)\n : [...new Set(group.rows.flatMap((row) => Object.keys(row)))].filter(\n (key) => !meta.has(key)\n )\n return (\n <section\n key={field.key}\n aria-label={field.label.ar}\n className=\"rounded-xl border bg-white\"\n >\n <div className=\"flex items-center justify-between border-b px-7 py-4\">\n <h2 className=\"text-sm font-semibold\">{field.label.ar}</h2>\n <span className=\"text-xs text-muted-foreground\">\n {group.rows.length} بند{group.hasMore ? ' · تظهر أول 100 بند متاح' : ''}\n </span>\n </div>\n {group.rows.length ? (\n <div className=\"overflow-x-auto\">\n <table className=\"w-full min-w-[480px] text-sm\">\n <thead className=\"bg-muted text-xs text-muted-foreground\">\n <tr>\n {keys.map((key) => (\n <th\n key={key}\n scope=\"col\"\n className=\"px-5 py-3 text-start font-medium\"\n >\n {columns.find((entry) => entry.key === key)?.label.ar ?? key}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {group.rows.map((row) => (\n <tr key={String(row.id)} className=\"border-b last:border-0\">\n {keys.map((key) => {\n const column = columns.find((entry) => entry.key === key)\n return (\n <td key={key} className=\"px-5 py-3\">\n {column ? (\n <ResourceValue field={column} row={row} lookups={lookups} />\n ) : (\n plain(row, key)\n )}\n </td>\n )\n })}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n ) : (\n <p className=\"px-7 py-6 text-xs text-muted-foreground\">لا توجد بنود متاحة.</p>\n )}\n </section>\n )\n })}\n </div>\n </Deferred>\n )}\n {resource.submittable && (\n <RecordWorkflows resource={resource.name} id={result.data.id as number} />\n )}\n <RecordAssignments\n resource={resource.name}\n id={result.data.id as number}\n canAssign={Boolean(result.permissions.update)}\n />\n <RecordCollaboration resource={resource} id={result.data.id as number} />\n <Deferred data=\"activity\" fallback={<SectionSkeleton title=\"سجل النشاط\" rows={4} />}>\n <section aria-label=\"سجل النشاط\" className=\"rounded-xl border bg-white\">\n <div className=\"flex items-center gap-2 border-b px-7 py-4\">\n <History size={16} className=\"text-muted-foreground\" />\n <h2 className=\"text-sm font-semibold\">سجل النشاط</h2>\n <span className=\"ms-auto text-xs text-muted-foreground\">\n آخر {activity?.length ?? 0} إجراء\n </span>\n </div>\n {activity?.length ? (\n <ol className=\"divide-y\">\n {activity.map((entry) => (\n <li\n key={entry.id}\n className=\"flex flex-wrap items-baseline gap-x-4 gap-y-1 px-7 py-3 text-sm\"\n >\n <span className=\"font-medium\">\n {activityLabels[entry.action] ?? entry.action}\n </span>\n <span className=\"text-xs text-muted-foreground\">\n {entry.actorName ?? `مستخدم #${entry.actorId}`}\n </span>\n <time\n dateTime={entry.createdAt}\n className=\"text-xs text-muted-foreground tabular-nums\"\n >\n {formatDatetime(entry.createdAt, calendar)}\n </time>\n {entry.fields.length > 0 && (\n <span className=\"basis-full text-xs text-muted-foreground\">\n الحقول: {entry.fields.map(fieldLabel).join('، ')}\n </span>\n )}\n </li>\n ))}\n </ol>\n ) : (\n <p className=\"px-7 py-6 text-xs text-muted-foreground\">لا يوجد نشاط مسجل بعد.</p>\n )}\n </section>\n </Deferred>\n </div>\n )\n}\n\nfunction plain(row: SerializedRecord, key: string) {\n const value = row[key]\n if (value === null || value === undefined) return '—'\n return typeof value === 'object' ? JSON.stringify(value) : String(value)\n}\n\nfunction SectionSkeleton({ title, rows }: { title: string; rows: number }) {\n return (\n <section\n role=\"status\"\n aria-label={`جارٍ تحميل ${title}`}\n className=\"rounded-xl border bg-white\"\n >\n <div className=\"border-b px-7 py-4\">\n <Skeleton className=\"h-4 w-32\" />\n </div>\n <div className=\"space-y-3 px-7 py-5\">\n {Array.from({ length: rows }, (_, index) => (\n <Skeleton key={index} className=\"h-4 w-full\" />\n ))}\n </div>\n </section>\n )\n}\n",
|
|
25
|
+
"content": "import { Deferred, router } from '@inertiajs/react'\nimport { Link } from '@adonisjs/inertia/react'\nimport { History, Pencil } from 'lucide-react'\nimport type {\n ResourceActivity,\n ResourceChildren as Children,\n ResourceDescription,\n ResourceShow as Show,\n SerializedRecord,\n} from 'adula'\nimport { Badge } from '~/components/ui/badge'\nimport { Button } from '~/components/ui/button'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\nimport { Can } from '~/components/ui/can'\nimport { arabicText, useMessages, type Translate } from '~/components/ui/messages'\nimport { Skeleton } from '~/components/ui/skeleton'\nimport { ResourceActions } from '~/components/ui/resource-actions'\nimport { ResourceValue, formatDatetime, type LookupOptions } from '~/components/ui/resource-value'\nimport { RecordCollaboration } from '~/components/ui/record-collaboration'\nimport { RecordAssignments } from '~/components/ui/record-assignments'\nimport { RecordWorkflows } from '~/components/ui/record-workflows'\nimport { RecordPrint } from '~/components/ui/record-print'\n\nexport type ResourceChildren = Children\nconst meta = new Set(['id', 'version', 'docStatus', 'orgUnitId'])\nconst activityLabels: Record<string, string> = {\n create: 'إنشاء السجل',\n update: 'تعديل السجل',\n delete: 'حذف السجل',\n submit: 'اعتماد المستند',\n cancel: 'إلغاء الاعتماد',\n amend: 'تعديل بعد الاعتماد',\n assignment_closed: 'إغلاق مهمة مع السجل',\n printed: 'طباعة السجل بقالب',\n}\n\nexport function documentStatus(status: unknown, t: Translate = arabicText) {\n return status === 1 ? t('معتمد') : status === 2 ? t('ملغي') : t('مسودة')\n}\n\nexport function ResourceShow({\n resource,\n result,\n lookups = {},\n childResources = {},\n childrenData,\n activity,\n onEdit,\n onAction,\n}: {\n resource: ResourceDescription\n result: Show\n lookups?: LookupOptions\n childResources?: Record<string, ResourceDescription>\n childrenData?: ResourceChildren\n activity?: ResourceActivity\n /** Replaces the edit link (record dialogs switch to the form in place). */\n onEdit?: () => void\n /** Called after a record action instead of reloading or leaving the page. */\n onAction?: (action: string) => void\n}) {\n const { calendar } = useUiPreferences()\n const { t, label } = useMessages()\n const base = `/resources/${resource.name}/${result.data.id}`\n const fields = resource.fields.filter(\n (field) =>\n resource.show.includes(field.key) && field.type !== 'hasMany' && field.key in result.data\n )\n const children = resource.fields.filter(\n (field) => field.type === 'hasMany' && resource.show.includes(field.key)\n )\n const fieldLabel = (key: string) => {\n const field = resource.fields.find((entry) => entry.key === key)\n return field ? label(field.label) : key\n }\n const columnLabel = (field: ResourceDescription['fields'][number] | undefined) =>\n field ? label(field.label) : undefined\n return (\n <div className=\"max-w-5xl space-y-6\">\n <div className=\"flex flex-wrap items-center gap-3\">\n <Can permissions={result.permissions} action=\"update\">\n {onEdit ? (\n <Button onClick={onEdit}>\n <Pencil size={15} />\n {t('تعديل السجل')}\n </Button>\n ) : (\n <Button asChild>\n <Link href={`${base}/edit`}>\n <Pencil size={15} />\n {t('تعديل السجل')}\n </Link>\n </Button>\n )}\n </Can>\n <RecordPrint resource={resource.name} id={result.data.id as number} />\n <ResourceActions\n resource={resource.name}\n id={result.data.id as number}\n version={result.data.version ?? undefined}\n permissions={result.permissions}\n onDone={(action) =>\n onAction\n ? onAction(action)\n : action === 'delete'\n ? router.visit(`/resources/${resource.name}`)\n : router.reload()\n }\n />\n {resource.submittable && (\n <Badge\n variant={result.data.docStatus === 1 ? 'default' : 'secondary'}\n className={result.data.docStatus === 2 ? 'bg-red-50 text-red-800' : ''}\n >\n {documentStatus(result.data.docStatus, t)}\n </Badge>\n )}\n </div>\n <dl className=\"grid gap-7 rounded-xl border bg-white p-7 md:grid-cols-2\">\n {fields.map((field) => (\n <div\n key={field.key}\n className={['text', 'json'].includes(field.type) ? 'md:col-span-2' : ''}\n >\n <dt className=\"mb-2 text-xs text-muted-foreground\">{label(field.label)}</dt>\n <dd className=\"break-words text-sm whitespace-pre-wrap\">\n <ResourceValue\n field={field}\n row={result.data}\n related={result.related}\n lookups={lookups}\n />\n </dd>\n </div>\n ))}\n {resource.scoped && result.data.orgUnitId !== undefined && (\n <div>\n <dt className=\"mb-2 text-xs text-muted-foreground\">{t('الوحدة التنظيمية')}</dt>\n <dd className=\"text-sm\">#{String(result.data.orgUnitId)}</dd>\n </div>\n )}\n </dl>\n {children.length > 0 && (\n <Deferred data=\"childrenData\" fallback={<SectionSkeleton title={t('البنود')} rows={3} />}>\n <div className=\"space-y-5\">\n {children.map((field) => {\n const group = childrenData?.[field.key]\n if (!group) return null\n const child = childResources[field.key]\n const columns = child\n ? child.fields.filter(\n (entry) => child.list.includes(entry.key) && entry.type !== 'hasMany'\n )\n : []\n const keys = columns.length\n ? columns.map((entry) => entry.key)\n : [...new Set(group.rows.flatMap((row) => Object.keys(row)))].filter(\n (key) => !meta.has(key)\n )\n return (\n <section\n key={field.key}\n aria-label={label(field.label)}\n className=\"rounded-xl border bg-white\"\n >\n <div className=\"flex items-center justify-between border-b px-7 py-4\">\n <h2 className=\"text-sm font-semibold\">{label(field.label)}</h2>\n <span className=\"text-xs text-muted-foreground\">\n {t('{count} بند', { count: group.rows.length })}\n {group.hasMore ? ` · ${t('تظهر أول 100 بند متاح')}` : ''}\n </span>\n </div>\n {group.rows.length ? (\n <div className=\"overflow-x-auto\">\n <table className=\"w-full min-w-[480px] text-sm\">\n <thead className=\"bg-muted text-xs text-muted-foreground\">\n <tr>\n {keys.map((key) => (\n <th\n key={key}\n scope=\"col\"\n className=\"px-5 py-3 text-start font-medium\"\n >\n {columnLabel(columns.find((entry) => entry.key === key)) ?? key}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {group.rows.map((row) => (\n <tr key={String(row.id)} className=\"border-b last:border-0\">\n {keys.map((key) => {\n const column = columns.find((entry) => entry.key === key)\n return (\n <td key={key} className=\"px-5 py-3\">\n {column ? (\n <ResourceValue field={column} row={row} lookups={lookups} />\n ) : (\n plain(row, key)\n )}\n </td>\n )\n })}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n ) : (\n <p className=\"px-7 py-6 text-xs text-muted-foreground\">\n {t('لا توجد بنود متاحة.')}\n </p>\n )}\n </section>\n )\n })}\n </div>\n </Deferred>\n )}\n {resource.submittable && (\n <RecordWorkflows resource={resource.name} id={result.data.id as number} />\n )}\n <RecordAssignments\n resource={resource.name}\n id={result.data.id as number}\n canAssign={Boolean(result.permissions.update)}\n />\n <RecordCollaboration resource={resource} id={result.data.id as number} />\n <Deferred data=\"activity\" fallback={<SectionSkeleton title={t('سجل النشاط')} rows={4} />}>\n <section aria-label={t('سجل النشاط')} className=\"rounded-xl border bg-white\">\n <div className=\"flex items-center gap-2 border-b px-7 py-4\">\n <History size={16} className=\"text-muted-foreground\" />\n <h2 className=\"text-sm font-semibold\">{t('سجل النشاط')}</h2>\n <span className=\"ms-auto text-xs text-muted-foreground\">\n {t('آخر {count} إجراء', { count: activity?.length ?? 0 })}\n </span>\n </div>\n {activity?.length ? (\n <ol className=\"divide-y\">\n {activity.map((entry) => (\n <li\n key={entry.id}\n className=\"flex flex-wrap items-baseline gap-x-4 gap-y-1 px-7 py-3 text-sm\"\n >\n <span className=\"font-medium\">\n {activityLabels[entry.action] ? t(activityLabels[entry.action]) : entry.action}\n </span>\n <span className=\"text-xs text-muted-foreground\">\n {entry.actorName ?? t('مستخدم #{id}', { id: String(entry.actorId) })}\n </span>\n <time\n dateTime={entry.createdAt}\n className=\"text-xs text-muted-foreground tabular-nums\"\n >\n {formatDatetime(entry.createdAt, calendar)}\n </time>\n {entry.fields.length > 0 && (\n <span className=\"basis-full text-xs text-muted-foreground\">\n {t('الحقول: {fields}', {\n fields: entry.fields.map(fieldLabel).join(t('، ')),\n })}\n </span>\n )}\n </li>\n ))}\n </ol>\n ) : (\n <p className=\"px-7 py-6 text-xs text-muted-foreground\">{t('لا يوجد نشاط مسجل بعد.')}</p>\n )}\n </section>\n </Deferred>\n </div>\n )\n}\n\nfunction plain(row: SerializedRecord, key: string) {\n const value = row[key]\n if (value === null || value === undefined) return '—'\n return typeof value === 'object' ? JSON.stringify(value) : String(value)\n}\n\nfunction SectionSkeleton({ title, rows }: { title: string; rows: number }) {\n const { t } = useMessages()\n return (\n <section\n role=\"status\"\n aria-label={t('جارٍ تحميل {section}', { section: title })}\n className=\"rounded-xl border bg-white\"\n >\n <div className=\"border-b px-7 py-4\">\n <Skeleton className=\"h-4 w-32\" />\n </div>\n <div className=\"space-y-3 px-7 py-5\">\n {Array.from({ length: rows }, (_, index) => (\n <Skeleton key={index} className=\"h-4 w-full\" />\n ))}\n </div>\n </section>\n )\n}\n",
|
|
24
26
|
"target": "inertia/components/ui/resource-show.tsx"
|
|
25
27
|
}
|
|
26
28
|
],
|