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