@adula/ui 2.2.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/build/attachment-preview.json +1 -1
- package/build/breadcrumb.json +18 -0
- package/build/copy-button.json +21 -0
- package/build/data-table.json +3 -2
- package/build/dialog-param.json +17 -0
- package/build/dialog.json +1 -1
- package/build/file-input.json +21 -0
- package/build/list-filters.json +2 -2
- package/build/long-dialog.json +17 -0
- package/build/manifest.json +109 -69
- package/build/messages.json +2 -2
- package/build/record-assignments.json +3 -2
- package/build/record-collaboration.json +3 -2
- package/build/record-workflows.json +3 -2
- package/build/resource-actions.json +1 -1
- package/build/resource-bulk.json +1 -1
- package/build/resource-dashboard.json +1 -1
- package/build/resource-field.json +3 -2
- package/build/resource-form.json +2 -1
- package/build/resource-import.json +3 -2
- package/build/resource-page.json +2 -1
- package/build/resource-show.json +4 -2
- package/build/resource-surface.json +2 -1
- package/build/resource-value.json +4 -3
- package/build/slider.json +17 -0
- package/build/sortable-list.json +20 -0
- package/build/tabs.json +1 -1
- package/build/theme.css +48 -2
- package/build/user-avatar.json +17 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @adula/ui
|
|
2
2
|
|
|
3
|
-
Version 2.
|
|
3
|
+
Version 2.3.0. For complete consumer setup, use the canonical [installation guide](https://github.com/adulash/adulajs/blob/main/docs/installation.md).
|
|
4
4
|
|
|
5
5
|
Arabic RTL shadcn registry for project-owned React components. This package ships JSON assets, not a runtime React component library. Install with `node ace adula:ui add all` or `node ace adula:ui add dialog`. The command invokes the pinned shadcn CLI and records each generated file hash in `ui.lock.json`. Project modifications are preserved; use `--preview` to review upstream differences before merging an update.
|
|
6
6
|
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
{
|
|
14
14
|
"path": "registry/ui/attachment-preview.tsx",
|
|
15
15
|
"type": "registry:ui",
|
|
16
|
-
"content": "import { useEffect, useState } from 'react'\nimport { Download, Eye } from 'lucide-react'\nimport { Button } from '~/components/ui/button'\nimport {
|
|
16
|
+
"content": "import { useEffect, useState } from 'react'\nimport { Download, Eye } from 'lucide-react'\nimport { Button } from '~/components/ui/button'\nimport { Dialog, DialogClose } from '~/components/ui/dialog'\nimport { LongDialogContent } from '~/components/ui/long-dialog'\nimport { useMessages } from '~/components/ui/messages'\n\n/** The parts of an attachment summary a preview needs (ADR 047). */\nexport type PreviewFile = {\n name: string\n url: string\n /** Set by the server for allow-listed images, PDF and plain text; other files download. */\n preview?: 'image' | 'pdf' | 'text' | null\n}\n\n/** Plain text longer than this is cut in the preview; the download keeps the whole file. */\nconst TEXT_PREVIEW_LIMIT = 200_000\n\n/** The authorized download route asked for inline display. */\nexport function previewUrl(file: PreviewFile) {\n return `${file.url}${file.url.includes('?') ? '&' : '?'}preview=1`\n}\n\n/** Fetched as text and rendered as text: a previewed file never becomes markup here. */\nfunction TextPreview({ file }: { file: PreviewFile }) {\n const { t } = useMessages()\n const [state, setState] = useState<{ text?: string; cut?: boolean; failed?: boolean }>({})\n useEffect(() => {\n // Read only the start of a large file: decode the stream as UTF-8 and stop at the cap.\n const controller = new AbortController()\n const read = async () => {\n const response = await fetch(previewUrl(file), {\n signal: controller.signal,\n credentials: 'same-origin',\n })\n if (!response.ok || !response.body) throw new Error(String(response.status))\n const reader = response.body.getReader()\n const decoder = new TextDecoder('utf-8')\n let text = ''\n for (;;) {\n const { done, value } = await reader.read()\n if (done) {\n text += decoder.decode()\n break\n }\n text += decoder.decode(value, { stream: true })\n if (text.length > TEXT_PREVIEW_LIMIT) {\n await reader.cancel()\n controller.abort()\n return { text: text.slice(0, TEXT_PREVIEW_LIMIT), cut: true }\n }\n }\n return { text, cut: false }\n }\n let current = true\n read()\n .then((result) => current && setState(result))\n .catch(() => current && setState({ failed: true }))\n return () => {\n current = false\n controller.abort()\n }\n }, [file.url])\n if (state.failed)\n return (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {t('تعذر تحميل المعاينة. يمكنك تنزيل الملف.')}\n </p>\n )\n if (state.text === undefined)\n return <p className=\"text-sm text-muted-foreground\">{t('جارٍ تحميل المعاينة…')}</p>\n return (\n <div className=\"space-y-2\">\n <pre\n dir=\"auto\"\n className=\"overflow-x-auto rounded-md border bg-muted p-3 text-xs whitespace-pre-wrap\"\n >\n {state.text}\n </pre>\n {state.cut && (\n <p className=\"text-xs text-muted-foreground\">\n {t('تعرض المعاينة بداية الملف فقط. نزّل الملف لقراءته كاملًا.')}\n </p>\n )}\n </div>\n )\n}\n\n/** Inline preview of one file in a Dialog: images, PDF in a same-origin frame, text as text. */\nexport function AttachmentPreviewDialog({\n file,\n open,\n onOpenChange,\n}: {\n file: PreviewFile\n open: boolean\n onOpenChange: (open: boolean) => void\n}) {\n const { t, dir } = useMessages()\n return (\n <Dialog mode=\"view\" open={open} onOpenChange={onOpenChange}>\n <LongDialogContent\n dir={dir}\n width=\"5xl\"\n title={<span className=\"block truncate\">{file.name}</span>}\n description={t('معاينة المرفق. يمكنك تنزيله من الزر أدناه.')}\n footer={\n <>\n {/* Download is the secondary action and sits at the start; «إغلاق» ends the row. */}\n <Button asChild variant=\"outline\" className=\"sm:me-auto\">\n <a href={file.url} download={file.name}>\n <Download size={15} />\n {t('تنزيل')}\n </a>\n </Button>\n <DialogClose asChild>\n <Button type=\"button\" variant=\"outline\">\n {t('إغلاق')}\n </Button>\n </DialogClose>\n </>\n }\n >\n {/* The whole image fits the body (dialog height less header and footer), so no\n scrolling is needed to see it; object-contain keeps its proportions. */}\n {open && file.preview === 'image' && (\n <img\n src={previewUrl(file)}\n alt={file.name}\n className=\"mx-auto max-h-[calc(90dvh-14rem)] max-w-full rounded-md border object-contain\"\n />\n )}\n {open && file.preview === 'pdf' && (\n <iframe\n src={previewUrl(file)}\n title={file.name}\n className=\"h-[65vh] w-full rounded-md border\"\n />\n )}\n {open && file.preview === 'text' && <TextPreview file={file} />}\n </LongDialogContent>\n </Dialog>\n )\n}\n\n/** A preview button for a previewable file; renders nothing for files that only download. */\nexport function AttachmentPreviewButton({\n file,\n disabled,\n}: {\n file: PreviewFile\n disabled?: boolean\n}) {\n const { t } = useMessages()\n const [open, setOpen] = useState(false)\n if (!file.preview) return null\n return (\n <>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n disabled={disabled}\n aria-label={t('معاينة {name}', { name: file.name })}\n onClick={() => setOpen(true)}\n >\n <Eye size={14} />\n {t('معاينة')}\n </Button>\n <AttachmentPreviewDialog file={file} open={open} onOpenChange={setOpen} />\n </>\n )\n}\n",
|
|
17
17
|
"target": "inertia/components/ui/attachment-preview.tsx"
|
|
18
18
|
}
|
|
19
19
|
],
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "breadcrumb",
|
|
3
|
+
"dependencies": [
|
|
4
|
+
"cn@0.3.0",
|
|
5
|
+
"radix-ui@1.6.7",
|
|
6
|
+
"lucide-react@1.47.0"
|
|
7
|
+
],
|
|
8
|
+
"files": [
|
|
9
|
+
{
|
|
10
|
+
"path": "registry/ui/breadcrumb.tsx",
|
|
11
|
+
"type": "registry:ui",
|
|
12
|
+
"content": "import * as React from \"react\"\nimport { cn } from \"cn\"\nimport { ChevronRight, MoreHorizontal } from \"lucide-react\"\nimport { Slot } from \"radix-ui\"\n\nfunction Breadcrumb({ ...props }: React.ComponentProps<\"nav\">) {\n return <nav aria-label=\"مسار التنقل\" data-slot=\"breadcrumb\" {...props} />\n}\n\nfunction BreadcrumbList({ className, ...props }: React.ComponentProps<\"ol\">) {\n return (\n <ol\n data-slot=\"breadcrumb-list\"\n className={cn(\n \"flex flex-wrap items-center gap-1.5 text-sm break-words text-muted-foreground sm:gap-2.5\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction BreadcrumbItem({ className, ...props }: React.ComponentProps<\"li\">) {\n return (\n <li\n data-slot=\"breadcrumb-item\"\n className={cn(\"inline-flex items-center gap-1.5\", className)}\n {...props}\n />\n )\n}\n\nfunction BreadcrumbLink({\n asChild,\n className,\n ...props\n}: React.ComponentProps<\"a\"> & {\n asChild?: boolean\n}) {\n const Comp = asChild ? Slot.Root : \"a\"\n\n return (\n <Comp\n data-slot=\"breadcrumb-link\"\n className={cn(\"transition-colors hover:text-foreground\", className)}\n {...props}\n />\n )\n}\n\nfunction BreadcrumbPage({ className, ...props }: React.ComponentProps<\"span\">) {\n return (\n <span\n data-slot=\"breadcrumb-page\"\n role=\"link\"\n aria-disabled=\"true\"\n aria-current=\"page\"\n className={cn(\"font-normal text-foreground\", className)}\n {...props}\n />\n )\n}\n\nfunction BreadcrumbSeparator({\n children,\n className,\n ...props\n}: React.ComponentProps<\"li\">) {\n return (\n <li\n data-slot=\"breadcrumb-separator\"\n role=\"presentation\"\n aria-hidden=\"true\"\n className={cn(\"[&>svg]:size-3.5\", className)}\n {...props}\n >\n {children ?? <ChevronRight className=\"rtl:rotate-180\" />}\n </li>\n )\n}\n\nfunction BreadcrumbEllipsis({\n className,\n ...props\n}: React.ComponentProps<\"span\">) {\n return (\n <span\n data-slot=\"breadcrumb-ellipsis\"\n role=\"presentation\"\n aria-hidden=\"true\"\n className={cn(\"flex size-9 items-center justify-center\", className)}\n {...props}\n >\n <MoreHorizontal className=\"size-4\" />\n <span className=\"sr-only\">المزيد</span>\n </span>\n )\n}\n\nexport {\n Breadcrumb,\n BreadcrumbList,\n BreadcrumbItem,\n BreadcrumbLink,\n BreadcrumbPage,\n BreadcrumbSeparator,\n BreadcrumbEllipsis,\n}\n",
|
|
13
|
+
"target": "inertia/components/ui/breadcrumb.tsx"
|
|
14
|
+
}
|
|
15
|
+
],
|
|
16
|
+
"type": "registry:ui",
|
|
17
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
18
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "copy-button",
|
|
3
|
+
"type": "registry:ui",
|
|
4
|
+
"registryDependencies": [
|
|
5
|
+
"button",
|
|
6
|
+
"messages"
|
|
7
|
+
],
|
|
8
|
+
"dependencies": [
|
|
9
|
+
"lucide-react@1.47.0",
|
|
10
|
+
"sonner@2.0.8"
|
|
11
|
+
],
|
|
12
|
+
"files": [
|
|
13
|
+
{
|
|
14
|
+
"path": "registry/ui/copy-button.tsx",
|
|
15
|
+
"type": "registry:ui",
|
|
16
|
+
"content": "import { useEffect, useRef, useState } from 'react'\nimport { Check, Copy } from 'lucide-react'\nimport { toast } from 'sonner'\nimport { Button } from '~/components/ui/button'\nimport { useMessages } from '~/components/ui/messages'\n\ntype CopyButtonProps = {\n /** The exact text placed on the clipboard. */\n value: string\n /** Visible label; defaults to «نسخ». */\n label?: string\n /** Accessible name when the label alone is ambiguous, e.g. «نسخ AWS_REGION». */\n ariaLabel?: string\n /** Shows the icon only; `ariaLabel` then names the button. */\n iconOnly?: boolean\n className?: string\n}\n\n/**\n * Copies a value to the clipboard and confirms it in place for two seconds. When the browser\n * refuses clipboard access it says so, so the user selects and copies the text by hand.\n */\nexport function CopyButton({ value, label, ariaLabel, iconOnly, className }: CopyButtonProps) {\n const { t } = useMessages()\n const [copied, setCopied] = useState(false)\n const timer = useRef<ReturnType<typeof setTimeout>>(undefined)\n useEffect(() => () => clearTimeout(timer.current), [])\n const text = copied ? t('تم النسخ') : (label ?? t('نسخ'))\n return (\n <Button\n type=\"button\"\n size={iconOnly ? 'icon-sm' : 'sm'}\n variant=\"outline\"\n className={className}\n aria-label={iconOnly || ariaLabel ? (ariaLabel ?? text) : undefined}\n data-copied={copied || undefined}\n onClick={async () => {\n try {\n await navigator.clipboard.writeText(value)\n setCopied(true)\n clearTimeout(timer.current)\n timer.current = setTimeout(() => setCopied(false), 2000)\n } catch {\n toast.error(t('تعذر النسخ؛ حدّد النص وانسخه يدويًا.'))\n }\n }}\n >\n {copied ? <Check aria-hidden size={14} /> : <Copy aria-hidden size={14} />}\n {!iconOnly && text}\n </Button>\n )\n}\n",
|
|
17
|
+
"target": "inertia/components/ui/copy-button.tsx"
|
|
18
|
+
}
|
|
19
|
+
],
|
|
20
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
21
|
+
}
|
package/build/data-table.json
CHANGED
|
@@ -17,7 +17,8 @@
|
|
|
17
17
|
"alert",
|
|
18
18
|
"checkbox",
|
|
19
19
|
"list-filters",
|
|
20
|
-
"resource-bulk"
|
|
20
|
+
"resource-bulk",
|
|
21
|
+
"user-avatar"
|
|
21
22
|
],
|
|
22
23
|
"dependencies": [
|
|
23
24
|
"@tanstack/react-table@9.2.4",
|
|
@@ -29,7 +30,7 @@
|
|
|
29
30
|
{
|
|
30
31
|
"path": "registry/ui/data-table.tsx",
|
|
31
32
|
"type": "registry:ui",
|
|
32
|
-
"content": "import { useEffect, useRef, useState, type ComponentRef, type MouseEvent } from 'react'\nimport { InfiniteScroll, router, usePage } from '@inertiajs/react'\nimport { Link } from '@adonisjs/inertia/react'\nimport { tableFeatures, useTable } from '@tanstack/react-table'\nimport { useVirtualizer } from '@tanstack/react-virtual'\nimport axios from 'axios'\nimport {\n ArrowDown,\n ArrowDownUp,\n ArrowUp,\n Download,\n Inbox,\n ListChecks,\n Loader2,\n Bookmark,\n BookmarkPlus,\n Search,\n SlidersHorizontal,\n Trash2,\n X,\n} from 'lucide-react'\nimport type {\n ResourceDescription,\n ResourceField,\n ResourceList,\n SavedView,\n SavedViewQuery,\n SerializedRecord,\n} from 'adula'\nimport { Alert, AlertDescription } from '~/components/ui/alert'\nimport { Badge } from '~/components/ui/badge'\nimport { Button } from '~/components/ui/button'\nimport { Checkbox } from '~/components/ui/checkbox'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\nimport { useMessages } from '~/components/ui/messages'\nimport { Can } from '~/components/ui/can'\nimport { Input } from '~/components/ui/input'\nimport { ResourceActions } from '~/components/ui/resource-actions'\nimport { openRecord, rememberListView } from '~/components/ui/resource-surface'\nimport { displayValue, type LookupOptions, type Option } from '~/components/ui/resource-value'\nimport {\n FilterControl,\n describeFilter,\n filterValueLabel,\n type FilterLabels,\n} from '~/components/ui/list-filters'\nimport { BulkBar, RestoreAction, actionScope, useBulkActions } from '~/components/ui/resource-bulk'\nimport {\n clearFilter,\n exportHref,\n fromSavedFilter,\n readFilters,\n selectionState,\n serverMessage,\n toSavedFilter,\n toggleSelection,\n writeFilter,\n type FieldFilter,\n} from '~/components/ui/list_query'\n\n/** Rows above this count render through the virtualizer (plan section 13). */\nexport const VIRTUAL_ROWS = 200\nconst ROW_HEIGHT = 52\nconst PAGE_SIZE = 100\nconst features = tableFeatures({})\n\n/**\n * List-layer keys of the description (ADR 046). Older servers omit them: no «المحذوفات»\n * toggle, and the server export stays available.\n */\ntype ListDescription = ResourceDescription & {\n trash?: boolean\n exportable?: boolean\n bulk?: boolean\n}\n\n/** The file name from `Content-Disposition`, or null. */\nfunction attachmentName(header: unknown) {\n if (typeof header !== 'string') return null\n const encoded = header.match(/filename\\*=UTF-8''([^;]+)/i)\n if (encoded) {\n try {\n return decodeURIComponent(encoded[1])\n } catch {\n // Fall through to the plain name.\n }\n }\n return header.match(/filename=\"?([^\";]+)\"?/i)?.[1] ?? null\n}\n\nexport function DataTable({\n resource,\n result,\n lookups = {},\n savedViews = [],\n trashed = false,\n}: {\n resource: ResourceDescription\n result: ResourceList\n lookups?: LookupOptions\n savedViews?: SavedView[]\n /** The «المحذوفات» list of `/resources/:name/trash`: rows offer restore only. */\n trashed?: boolean\n}) {\n const { calendar } = useUiPreferences()\n const { t, label, locale } = useMessages()\n const { url } = usePage()\n const description = resource as ListDescription\n const query = new URL(url, 'http://localhost').searchParams\n const listPath = `/resources/${resource.name}${trashed ? '/trash' : ''}`\n const [search, setSearch] = useState(query.get('search') ?? '')\n const [failure, setFailure] = useState('')\n const [queryFailure, setQueryFailure] = useState('')\n const [exporting, setExporting] = useState(false)\n const [exportFailure, setExportFailure] = useState('')\n const [selected, setSelected] = useState<Set<string>>(() => new Set())\n const labels = useRef<FilterLabels>({})\n const container = useRef<HTMLDivElement>(null)\n const scroller = useRef<ComponentRef<typeof InfiniteScroll>>(null)\n const offered = useBulkActions(resource.name, description.bulk !== false)\n // The «المحذوفات» list offers restore only; the active list everything else.\n const bulkActions = offered.filter(\n (action) => actionScope(action) === (trashed ? 'trash' : 'records')\n )\n // Opening one of this list's records remembers the view, so closing the dialog returns to it.\n useEffect(\n () =>\n router.on('before', (event) => {\n const { pathname } = event.detail.visit.url\n if (pathname.startsWith(`/resources/${resource.name}/`)) rememberListView(pathname)\n }),\n [resource.name]\n )\n // Inertia merges `result.data` page by page; permissions and labels of earlier pages accumulate here.\n const store = useRef<{\n source: ResourceList | null\n permissions: ResourceList['permissions']\n related: ResourceList['related']\n }>({ source: null, permissions: {}, related: {} })\n if (store.current.source !== result) {\n const related = { ...store.current.related }\n for (const [key, rows] of Object.entries(result.related))\n related[key] = [\n ...new Map([...(related[key] ?? []), ...rows].map((row) => [String(row.id), row])).values(),\n ]\n store.current = {\n source: result,\n permissions: { ...store.current.permissions, ...result.permissions },\n related,\n }\n }\n const { permissions, related } = store.current\n const fields = resource.fields.filter(\n (field) => resource.list.includes(field.key) && field.type !== 'hasMany'\n )\n const filterable = fields.filter((field) => field.filterable)\n const filters = readFilters(\n query,\n filterable.map((field) => field.key)\n )\n const activeFilters = filterable.filter((field) => filters[field.key])\n const table = useTable({\n features,\n data: result.data,\n columns: fields.map((field) => ({ accessorKey: field.key, id: field.key })),\n getRowId: (row) => String(row.id),\n })\n const rows = table.getRowModel().rows\n const loadedIds = rows.map((row) => row.id)\n const selectable = bulkActions.length > 0\n const columns = fields.length + 1 + (selectable ? 1 : 0)\n const virtualized = rows.length > VIRTUAL_ROWS\n const virtual = useVirtualizer({\n count: rows.length,\n getScrollElement: () => container.current,\n estimateSize: () => ROW_HEIGHT,\n overscan: 10,\n enabled: virtualized,\n getItemKey: (index) => rows[index].id,\n })\n const items = virtualized\n ? virtual.getVirtualItems()\n : rows.map((_, index) => ({ index, start: 0, end: 0 }))\n const go = (next: URLSearchParams) => {\n next.delete('cursor')\n setQueryFailure('')\n setSelected(new Set())\n const suffix = next.toString()\n router.get(\n `${listPath}${suffix ? `?${suffix}` : ''}`,\n {},\n {\n preserveScroll: true,\n // An invalid filter is 422 E_FILTER; show the server's message instead of the error page.\n onHttpException: (response) => {\n if (response.status !== 422) return\n setQueryFailure(\n serverMessage(response.data) ?? t('تعذر تطبيق التصفية. راجع القيم ثم أعد المحاولة.')\n )\n return false\n },\n }\n )\n }\n const navigate = (changes: Record<string, string | undefined>) => {\n const next = new URLSearchParams(query)\n for (const [key, value] of Object.entries(changes))\n value ? next.set(key, value) : next.delete(key)\n go(next)\n }\n const applyFilter = (key: string, filter: FieldFilter | null) => {\n const next = new URLSearchParams(query)\n writeFilter(next, key, filter)\n go(next)\n }\n const clearFilters = () => {\n const next = new URLSearchParams(query)\n for (const field of activeFilters) clearFilter(next, field.key)\n go(next)\n }\n const sort = query.get('sort')\n const direction = query.get('direction') === 'desc' ? 'desc' : 'asc'\n const valueLabel = (field: ResourceField) => (raw: string) =>\n filterValueLabel(field, raw, {\n options: lookups[field.key],\n related: related[field.key],\n labels: labels.current[field.key],\n calendar,\n t,\n language: locale,\n })\n const remember = (key: string) => (choices: Option[]) => {\n labels.current[key] = {\n ...labels.current[key],\n ...Object.fromEntries(choices.map((choice) => [choice.value, choice.label])),\n }\n }\n // The server export reads the same filtered set as this list, page by page, up to its limit.\n const exportResults = async () => {\n setExporting(true)\n setExportFailure('')\n try {\n const response = await axios.get<Blob>(exportHref(resource.name, query), {\n responseType: 'blob',\n headers: { Accept: 'text/csv, application/json' },\n })\n const href = URL.createObjectURL(response.data)\n const link = document.createElement('a')\n link.href = href\n link.download =\n attachmentName(response.headers['content-disposition']) ?? `${resource.label}.csv`\n link.click()\n // Revoking right after click can cancel the download in some browsers.\n setTimeout(() => URL.revokeObjectURL(href), 60_000)\n } catch (error) {\n const body = axios.isAxiosError(error) ? error.response?.data : null\n const message = body instanceof Blob ? serverMessage(await body.text().catch(() => '')) : null\n setExportFailure(message ?? t('تعذر تصدير النتائج. حاول مجدداً.'))\n } finally {\n setExporting(false)\n }\n }\n const refresh = () => router.visit(url, { preserveScroll: true })\n // Records open in a dialog over this list, which stays mounted (#31); modified clicks\n // (new tab, new window) keep the link's own behavior.\n const overlay = (event: MouseEvent, id: string, mode: 'show' | 'edit') => {\n if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)\n return\n event.preventDefault()\n void openRecord(resource.name, id, mode)\n }\n const currentQuery = (): SavedViewQuery => {\n const view: SavedViewQuery = {}\n const text = query.get('search')\n if (text) view.search = text\n if (sort) {\n view.sort = sort\n view.direction = direction\n }\n const saved: Record<string, unknown> = {}\n for (const field of activeFilters) saved[field.key] = toSavedFilter(filters[field.key])\n // Saved views store operator objects too (ADR 046); older type declarations list scalars.\n if (Object.keys(saved).length) view.filters = saved as SavedViewQuery['filters']\n return view\n }\n const applyView = (view: SavedView) => {\n const next = new URLSearchParams()\n if (view.query.search) next.set('search', view.query.search)\n if (view.query.sort) {\n next.set('sort', view.query.sort)\n next.set('direction', view.query.direction ?? 'asc')\n }\n for (const [key, value] of Object.entries(view.query.filters ?? {}))\n writeFilter(next, key, fromSavedFilter(value))\n setSearch(view.query.search ?? '')\n go(next)\n }\n const allState = selectionState(selected, loadedIds)\n const chosen = loadedIds.filter((id) => selected.has(id))\n return (\n <section\n aria-label={t('قائمة {resource}', { resource: resource.label })}\n className=\"min-w-0 overflow-hidden rounded-xl border border-border bg-white shadow-[0_2px_10px_#1c302804]\"\n >\n <div className=\"flex flex-wrap items-center justify-between gap-4 border-b px-5 py-4\">\n <div className=\"flex flex-wrap items-center gap-3\">\n <h2 className=\"text-sm font-semibold\">\n {trashed\n ? t('المحذوفات من {resource}', { resource: resource.label })\n : t('سجل {resource}', { resource: resource.label })}\n </h2>\n <Badge variant=\"secondary\" className=\"font-normal tabular-nums\">\n {t('{count} معروض', { count: rows.length })}\n </Badge>\n <span className=\"text-xs text-muted-foreground\">\n {result.meta.estimatedTotal !== undefined\n ? t('نحو {count} سجل ضمن نطاقك', {\n count: result.meta.estimatedTotal,\n })\n : t('حسب نطاق صلاحياتك')}\n </span>\n </div>\n <div className=\"flex flex-wrap items-center gap-2\">\n {description.trash && (\n <Button variant=\"outline\" size=\"sm\" asChild>\n <Link\n href={trashed ? `/resources/${resource.name}` : `/resources/${resource.name}/trash`}\n >\n {trashed ? <ListChecks size={15} /> : <Trash2 size={15} />}\n {trashed ? t('السجلات النشطة') : t('المحذوفات')}\n </Link>\n </Button>\n )}\n {!trashed && description.exportable !== false && (\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={() => void exportResults()}\n disabled={!rows.length || exporting}\n >\n {exporting ? <Loader2 size={15} className=\"animate-spin\" /> : <Download size={15} />}\n {exporting ? t('جارٍ التصدير...') : t('تصدير النتائج')}\n </Button>\n )}\n </div>\n </div>\n {exportFailure && (\n <div className=\"border-b px-5 py-3\">\n <Alert variant=\"destructive\">\n <AlertDescription className=\"flex flex-wrap items-center justify-between gap-2\">\n {exportFailure}\n <Button variant=\"ghost\" size=\"sm\" onClick={() => setExportFailure('')}>\n {t('إغلاق')}\n </Button>\n </AlertDescription>\n </Alert>\n </div>\n )}\n {/* Saved views belong to the active list; «المحذوفات» has none. */}\n {!trashed && (resource.searchable || filterable.length > 0) && (\n <SavedViewsBar\n resource={resource}\n views={savedViews}\n current={currentQuery}\n onApply={applyView}\n onChanged={refresh}\n onFailure={setFailure}\n />\n )}\n {(resource.searchable || filterable.length > 0) && (\n <div className=\"grid gap-3 border-b px-5 py-4\">\n <div className=\"flex flex-wrap items-center gap-3\">\n {resource.searchable && (\n <form\n role=\"search\"\n className=\"relative w-full max-w-sm\"\n onSubmit={(event) => {\n event.preventDefault()\n navigate({ search })\n }}\n >\n <Search\n className=\"pointer-events-none absolute start-3 top-2.5 text-muted-foreground\"\n size={16}\n />\n <Input\n aria-label={t('البحث في {field}', { field: resource.label })}\n value={search}\n onChange={(event) => setSearch(event.target.value)}\n placeholder={t('ابحث في السجلات...')}\n className=\"h-9 bg-background/60 ps-10 text-xs\"\n />\n </form>\n )}\n {filterable.length > 0 && (\n <span className=\"flex items-center gap-2 text-xs text-muted-foreground\">\n <SlidersHorizontal size={15} />\n {t('تصفية')}\n </span>\n )}\n {filterable.map((field) => (\n <FilterControl\n key={field.key}\n resource={resource.name}\n field={field}\n filter={filters[field.key]}\n options={lookups[field.key]}\n related={related[field.key]}\n labels={labels.current[field.key]}\n onRemember={remember(field.key)}\n onApply={(filter) => applyFilter(field.key, filter)}\n />\n ))}\n </div>\n {activeFilters.length > 0 && (\n <ul aria-label={t('التصفية المطبقة')} className=\"flex flex-wrap items-center gap-2\">\n {activeFilters.map((field) => (\n <li key={field.key}>\n <Badge\n variant=\"secondary\"\n className=\"h-7 gap-1.5 ps-3 pe-1.5 text-xs font-normal\"\n >\n <span className=\"font-medium\">{label(field.label)}:</span>\n <span className=\"max-w-[260px] truncate\">\n {describeFilter(filters[field.key], valueLabel(field), t)}\n </span>\n <button\n type=\"button\"\n aria-label={t('إزالة تصفية {field}', {\n field: label(field.label),\n })}\n className=\"rounded-full p-0.5 text-muted-foreground hover:bg-background hover:text-foreground\"\n onClick={() => applyFilter(field.key, null)}\n >\n <X size={13} />\n </button>\n </Badge>\n </li>\n ))}\n <li>\n <Button variant=\"ghost\" size=\"sm\" className=\"h-7 text-xs\" onClick={clearFilters}>\n <X size={14} />\n {t('مسح التصفية')}\n </Button>\n </li>\n </ul>\n )}\n {queryFailure && (\n <Alert variant=\"destructive\">\n <AlertDescription>{queryFailure}</AlertDescription>\n </Alert>\n )}\n </div>\n )}\n {selectable && (\n <BulkBar\n resource={resource.name}\n actions={bulkActions}\n selected={chosen}\n rows={result.data}\n onClear={() => setSelected(new Set())}\n onDone={(outcome) => {\n // Refused rows stay selected so they can be reviewed or retried.\n const failed = new Set(outcome.failed.map((entry) => String(entry.id)))\n setSelected((current) => new Set([...current].filter((id) => failed.has(id))))\n refresh()\n }}\n />\n )}\n <InfiniteScroll\n ref={(instance) => {\n scroller.current = instance\n }}\n data=\"result\"\n manual\n onlyNext\n preserveUrl\n params={{\n data: { limit: PAGE_SIZE },\n onBefore: () => {\n setFailure('')\n },\n onHttpException: () => {\n setFailure(t('تعذر تحميل السجلات التالية. أعد المحاولة.'))\n return false\n },\n onNetworkError: () => {\n setFailure(t('تعذر الاتصال بالخادم. تحقق من الاتصال ثم أعد المحاولة.'))\n return false\n },\n }}\n next={({ fetch, loading, hasMore }) => (\n <div className=\"flex flex-wrap items-center justify-center gap-4 border-t px-5 py-3 text-xs text-muted-foreground\">\n {failure && (\n <p role=\"alert\" className=\"text-destructive\">\n {failure}\n </p>\n )}\n {loading ? (\n <span role=\"status\" className=\"inline-flex items-center gap-2\">\n <Loader2 size={14} className=\"animate-spin\" />\n {t('جارٍ تحميل المزيد...')}\n </span>\n ) : hasMore ? (\n <Button variant=\"ghost\" size=\"sm\" onClick={fetch}>\n {t('تحميل المزيد')}\n </Button>\n ) : (\n <span>{rows.length ? t('نهاية السجلات') : ''}</span>\n )}\n </div>\n )}\n >\n <div\n ref={container}\n data-slot=\"table-scroll\"\n className=\"max-h-[600px] overflow-auto\"\n onScroll={(event) => {\n const element = event.currentTarget\n if (\n !failure &&\n element.scrollHeight - element.scrollTop - element.clientHeight < 200 &&\n scroller.current?.hasNext()\n )\n scroller.current.fetchNext()\n }}\n >\n <table\n className=\"w-full min-w-[720px] text-start text-sm\"\n aria-rowcount={rows.length + 1}\n aria-label={resource.label}\n >\n <thead className=\"sticky top-0 z-10 bg-muted text-xs text-muted-foreground\">\n <tr>\n {selectable && (\n <th scope=\"col\" className=\"h-11 w-10 ps-5 pe-1 text-start\">\n <Checkbox\n aria-label={t('تحديد كل السجلات المعروضة')}\n checked={allState}\n disabled={!rows.length}\n onCheckedChange={(value) =>\n setSelected(value === true ? new Set(loadedIds) : new Set())\n }\n />\n </th>\n )}\n {fields.map((field) => (\n <th\n key={field.key}\n scope=\"col\"\n className=\"h-11 whitespace-nowrap px-5 text-start font-medium\"\n aria-sort={\n sort === field.key\n ? direction === 'desc'\n ? 'descending'\n : 'ascending'\n : undefined\n }\n >\n {field.sortable ? (\n <button\n type=\"button\"\n className=\"inline-flex items-center gap-2 hover:text-foreground\"\n onClick={() =>\n navigate({\n sort: field.key,\n direction: sort === field.key && direction === 'asc' ? 'desc' : 'asc',\n })\n }\n >\n {label(field.label)}\n {sort === field.key ? (\n direction === 'desc' ? (\n <ArrowDown size={12} />\n ) : (\n <ArrowUp size={12} />\n )\n ) : (\n <ArrowDownUp size={12} className=\"opacity-60\" />\n )}\n </button>\n ) : (\n label(field.label)\n )}\n </th>\n ))}\n <th\n scope=\"col\"\n className=\"sticky end-0 border-s bg-muted px-5 text-start font-medium\"\n >\n {t('الإجراءات')}\n </th>\n </tr>\n </thead>\n <tbody>\n {virtualized && items[0] && items[0].start > 0 && (\n <tr aria-hidden=\"true\">\n <td colSpan={columns} style={{ height: items[0].start }} />\n </tr>\n )}\n {items.map(({ index }) => {\n const row = rows[index].original\n const id = String(row.id)\n const checked = selected.has(id)\n return (\n <tr\n key={id}\n aria-rowindex={index + 2}\n aria-selected={selectable ? checked : undefined}\n className={`group border-b last:border-0 hover:bg-background ${checked ? 'bg-accent/40' : ''}`}\n style={{ height: ROW_HEIGHT }}\n >\n {selectable && (\n <td className=\"w-10 ps-5 pe-1\">\n <Checkbox\n aria-label={t('تحديد السجل {id}', { id })}\n checked={checked}\n onCheckedChange={(value) =>\n setSelected((current) => toggleSelection(current, id, value === true))\n }\n />\n </td>\n )}\n {fields.map((field) => (\n <Cell\n key={field.key}\n field={field}\n row={row}\n related={related}\n lookups={lookups}\n />\n ))}\n {/* Pinned at the inline end so wide tables keep their row actions in view. */}\n <td className=\"sticky end-0 whitespace-nowrap border-s bg-card px-5 text-xs group-hover:bg-background\">\n <span className=\"inline-flex items-center gap-1\">\n {trashed ? (\n // Restore is authorized by the delete rule on the deleted record (ADR 046).\n (permissions[id] as Record<string, boolean | undefined> | undefined)\n ?.restore === true && (\n <RestoreAction\n resource={resource.name}\n id={id}\n version={row.version ?? undefined}\n label={t('السجل {id}', { id })}\n onDone={refresh}\n />\n )\n ) : (\n <>\n <Button variant=\"ghost\" size=\"sm\" asChild>\n <Link\n href={`/resources/${resource.name}/${id}`}\n aria-label={t('عرض السجل {id}', { id })}\n onClick={(event) => overlay(event, id, 'show')}\n >\n {t('عرض')}\n </Link>\n </Button>\n <Can permissions={permissions[id] ?? {}} action=\"update\">\n <Button variant=\"ghost\" size=\"sm\" asChild>\n <Link\n href={`/resources/${resource.name}/${id}/edit`}\n aria-label={t('تعديل السجل {id}', { id })}\n onClick={(event) => overlay(event, id, 'edit')}\n >\n {t('تعديل')}\n </Link>\n </Button>\n </Can>\n <ResourceActions\n resource={resource.name}\n id={id}\n version={row.version ?? undefined}\n permissions={permissions[id] ?? {}}\n label={t('السجل {id}', { id })}\n size=\"sm\"\n variant=\"ghost\"\n onDone={refresh}\n />\n </>\n )}\n </span>\n </td>\n </tr>\n )\n })}\n {virtualized && (\n <tr aria-hidden=\"true\">\n <td\n colSpan={columns}\n style={{\n height: Math.max(0, virtual.getTotalSize() - (items.at(-1)?.end ?? 0)),\n }}\n />\n </tr>\n )}\n {!rows.length && (\n <tr>\n <td colSpan={columns} className=\"py-16 text-center\">\n {trashed ? (\n <Trash2\n className=\"mx-auto mb-3 text-muted-foreground\"\n size={30}\n strokeWidth={1.3}\n />\n ) : (\n <Inbox\n className=\"mx-auto mb-3 text-muted-foreground\"\n size={30}\n strokeWidth={1.3}\n />\n )}\n <p className=\"text-sm font-medium\">\n {trashed && !query.get('search') && !activeFilters.length\n ? t('لا توجد سجلات محذوفة')\n : t('لا توجد سجلات مطابقة')}\n </p>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {query.get('search') || activeFilters.length\n ? t('غيّر البحث أو التصفية لعرض سجلات أخرى.')\n : trashed\n ? t('تظهر هنا السجلات المحذوفة ضمن نطاقك لتستعيدها.')\n : t('لم تُضف سجلات ضمن نطاقك بعد.')}\n </p>\n </td>\n </tr>\n )}\n </tbody>\n </table>\n </div>\n </InfiniteScroll>\n </section>\n )\n}\n\n/** Presets over the same query keys the list already accepts; AdulaJS validates every one. */\nfunction SavedViewsBar({\n resource,\n views,\n current,\n onApply,\n onChanged,\n onFailure,\n}: {\n resource: ResourceDescription\n views: SavedView[]\n current: () => SavedViewQuery\n onApply: (view: SavedView) => void\n onChanged: () => void\n onFailure: (message: string) => void\n}) {\n const { t } = useMessages()\n const [naming, setNaming] = useState(false)\n const [name, setName] = useState('')\n const [shared, setShared] = useState(false)\n const [busy, setBusy] = useState(false)\n const base = `/resources/${resource.name}/views`\n const save = async (event: React.FormEvent) => {\n event.preventDefault()\n setBusy(true)\n onFailure('')\n try {\n await axios.post(\n base,\n { name, query: current(), shared },\n { headers: { Accept: 'application/json' }, withXSRFToken: true }\n )\n setNaming(false)\n setName('')\n setShared(false)\n onChanged()\n } catch (error) {\n onFailure(\n axios.isAxiosError(error) && error.response?.data?.error?.message\n ? String(error.response.data.error.message)\n : t('تعذر حفظ العرض.')\n )\n } finally {\n setBusy(false)\n }\n }\n const remove = async (view: SavedView) => {\n setBusy(true)\n onFailure('')\n try {\n await axios.delete(`${base}/${view.id}`, {\n headers: { Accept: 'application/json' },\n withXSRFToken: true,\n })\n onChanged()\n } catch {\n onFailure(t('تعذر حذف العرض.'))\n } finally {\n setBusy(false)\n }\n }\n return (\n <div className=\"flex flex-wrap items-center gap-2 border-b px-5 py-3\">\n <span className=\"flex items-center gap-2 text-xs text-muted-foreground\">\n <Bookmark size={15} />\n {t('العروض المحفوظة')}\n </span>\n {views.length === 0 && (\n <span className=\"text-xs text-muted-foreground\">{t('لا عروض بعد')}</span>\n )}\n {views.map((view) => (\n <span\n key={view.id}\n className=\"flex items-center gap-1 rounded-full border border-border bg-background/60 ps-1 pe-3\"\n >\n <Button\n variant=\"ghost\"\n size=\"sm\"\n className=\"h-7 rounded-full px-2 text-xs\"\n onClick={() => onApply(view)}\n >\n {view.name}\n {!view.own && <span className=\"text-muted-foreground\"> · {t('مشترك')}</span>}\n </Button>\n {view.own && (\n <button\n type=\"button\"\n aria-label={t('حذف العرض {name}', { name: view.name })}\n disabled={busy}\n onClick={() => remove(view)}\n className=\"text-muted-foreground transition-colors hover:text-destructive\"\n >\n <X size={13} />\n </button>\n )}\n </span>\n ))}\n {naming ? (\n <form onSubmit={save} className=\"flex flex-wrap items-center gap-2\">\n <Input\n aria-label={t('اسم العرض')}\n value={name}\n autoFocus\n maxLength={60}\n onChange={(event) => setName(event.target.value)}\n placeholder={t('اسم العرض')}\n className=\"h-8 w-44 text-xs\"\n />\n <label className=\"flex items-center gap-1 text-xs text-muted-foreground\">\n <Checkbox checked={shared} onCheckedChange={(value) => setShared(value === true)} />\n {t('مشترك')}\n </label>\n <Button type=\"submit\" size=\"sm\" className=\"h-8\" disabled={busy || !name.trim()}>\n {t('حفظ')}\n </Button>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"h-8\"\n onClick={() => setNaming(false)}\n >\n {t('إلغاء')}\n </Button>\n </form>\n ) : (\n <Button variant=\"outline\" size=\"sm\" className=\"h-8 text-xs\" onClick={() => setNaming(true)}>\n <BookmarkPlus size={14} />\n {t('حفظ العرض الحالي')}\n </Button>\n )}\n </div>\n )\n}\n\nfunction Cell({\n field,\n row,\n related,\n lookups,\n}: {\n field: ResourceField\n row: SerializedRecord\n related: ResourceList['related']\n lookups: LookupOptions\n}) {\n const { calendar } = useUiPreferences()\n const { t, locale } = useMessages()\n const text = displayValue(field, row, related, lookups, calendar, t, locale)\n const numeric = ['money', 'integer', 'decimal', 'percent', 'date', 'datetime'].includes(\n field.type\n )\n return (\n <td\n className={`max-w-[280px] truncate px-5 ${numeric ? 'tabular-nums' : ''}`}\n dir={numeric ? 'ltr' : undefined}\n title={text}\n >\n {field.type === 'boolean' && row[field.key] !== null && row[field.key] !== undefined ? (\n <Badge variant={row[field.key] ? 'default' : 'secondary'}>{text}</Badge>\n ) : (\n text\n )}\n </td>\n )\n}\n",
|
|
33
|
+
"content": "import {\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n type ComponentRef,\n type MouseEvent,\n type RefObject,\n} from 'react'\nimport { InfiniteScroll, router, usePage } from '@inertiajs/react'\nimport { Link } from '@adonisjs/inertia/react'\nimport { tableFeatures, useTable } from '@tanstack/react-table'\nimport {\n elementScroll,\n observeElementOffset,\n observeElementRect,\n observeWindowOffset,\n observeWindowRect,\n useVirtualizer,\n windowScroll,\n} from '@tanstack/react-virtual'\nimport axios from 'axios'\nimport {\n ArrowDown,\n ArrowDownUp,\n ArrowUp,\n Download,\n FileSpreadsheet,\n FileText,\n Inbox,\n ListChecks,\n Loader2,\n Bookmark,\n BookmarkPlus,\n Search,\n SlidersHorizontal,\n Trash2,\n X,\n} from 'lucide-react'\nimport type {\n ResourceDescription,\n ResourceField,\n ResourceList,\n SavedView,\n SavedViewQuery,\n SerializedRecord,\n} from 'adula'\nimport { Alert, AlertDescription } from '~/components/ui/alert'\nimport { Badge } from '~/components/ui/badge'\nimport { Button } from '~/components/ui/button'\nimport { Checkbox } from '~/components/ui/checkbox'\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuTrigger,\n} from '~/components/ui/dropdown-menu'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\nimport { recordCount, useMessages } from '~/components/ui/messages'\nimport { Can } from '~/components/ui/can'\nimport { Input } from '~/components/ui/input'\nimport { ResourceActions } from '~/components/ui/resource-actions'\nimport {\n openRecord,\n plainClick,\n prefetchRecord,\n rememberListView,\n} from '~/components/ui/resource-surface'\nimport {\n displayValue,\n relatedUser,\n type LookupOptions,\n type Option,\n} from '~/components/ui/resource-value'\nimport { UserAvatar } from '~/components/ui/user-avatar'\nimport {\n FilterControl,\n describeFilter,\n filterValueLabel,\n type FilterLabels,\n} from '~/components/ui/list-filters'\nimport {\n BulkBar,\n RestoreAction,\n actionScope,\n useBulkActions,\n type BulkAction,\n} from '~/components/ui/resource-bulk'\nimport {\n clearFilter,\n exportHref,\n fromSavedFilter,\n listUrl,\n readFilters,\n selectionState,\n serverMessage,\n toSavedFilter,\n toggleSelection,\n writeFilter,\n type FieldFilter,\n} from '~/components/ui/list_query'\n\n/** Below this figure the server counts exactly instead of estimating (#111). */\nexport const EXACT_COUNT_LIMIT = 1000\n/** The actions column while the table scrolls sideways: pinned, with a shadow toward the cells. */\nconst pinned = 'sticky end-0 z-[1] shadow-[0_0_12px_color-mix(in_oklab,var(--foreground)_12%,transparent)]'\n/** Rows above this count render through the virtualizer (plan section 13). */\nexport const VIRTUAL_ROWS = 200\nconst ROW_HEIGHT = 52\nconst PAGE_SIZE = 100\nconst features = tableFeatures({})\n\n/**\n * List-layer keys of the description (ADR 046). Older servers omit them: no «المحذوفات»\n * toggle, and the server export stays available.\n */\ntype ListDescription = ResourceDescription & {\n trash?: boolean\n exportable?: boolean\n bulk?: boolean\n}\n\n/**\n * The nearest ancestor that scrolls vertically, or null when the page (window) scrolls (#109).\n * The walk starts above the table section, so the table's own horizontal overflow never counts;\n * `overflow-x: auto` alone makes an element's overflow-y auto without making it scroll.\n */\nfunction scrollingAncestor(node: HTMLElement | null) {\n for (\n let element = node?.parentElement ?? null;\n element && element !== document.body && element !== document.documentElement;\n element = element.parentElement\n ) {\n const { overflowY } = getComputedStyle(element)\n if (\n (overflowY === 'auto' || overflowY === 'scroll') &&\n element.scrollHeight > element.clientHeight\n )\n return element\n }\n return null\n}\n\n/**\n * The list scrolls with the workspace (#109): its scroller is the page or a scrolling content\n * column, resolved after mount (undefined until then) and again when an ancestor starts scrolling.\n */\nfunction useScrollParent(anchor: RefObject<HTMLElement | null>, revision: unknown) {\n const [parent, setParent] = useState<HTMLElement | null | undefined>(undefined)\n useLayoutEffect(() => {\n const resolve = () => setParent(scrollingAncestor(anchor.current))\n resolve()\n const scrolled = (event: Event) => {\n const target = event.target\n if (target instanceof HTMLElement && anchor.current && target.contains(anchor.current))\n resolve()\n }\n window.addEventListener('resize', resolve)\n document.addEventListener('scroll', scrolled, { capture: true, passive: true })\n return () => {\n window.removeEventListener('resize', resolve)\n document.removeEventListener('scroll', scrolled, { capture: true })\n }\n }, [anchor, revision])\n return parent\n}\n\n/**\n * Runs `measure` on the next frame, at most once per frame. A ResizeObserver callback that\n * changes layout (the table's overflow class) would otherwise report an observer loop.\n */\nfunction framed(measure: () => void) {\n let frame = 0\n return {\n run: () => {\n cancelAnimationFrame(frame)\n frame = requestAnimationFrame(measure)\n },\n cancel: () => cancelAnimationFrame(frame),\n }\n}\n\n/** Where the rows start inside the scroller, for the virtualizer's `scrollMargin`. */\nfunction useScrollMargin(\n target: RefObject<HTMLElement | null>,\n parent: HTMLElement | null | undefined,\n active: boolean\n) {\n const [margin, setMargin] = useState(0)\n useLayoutEffect(() => {\n if (!active || parent === undefined) return\n const measure = () => {\n const element = target.current\n if (!element) return\n const top = element.getBoundingClientRect().top\n setMargin(\n Math.round(\n parent === null\n ? top + window.scrollY\n : top - parent.getBoundingClientRect().top + parent.scrollTop\n )\n )\n }\n measure()\n const next = framed(measure)\n const observer = new ResizeObserver(next.run)\n observer.observe(parent ?? document.body)\n window.addEventListener('resize', next.run)\n return () => {\n next.cancel()\n observer.disconnect()\n window.removeEventListener('resize', next.run)\n }\n }, [target, parent, active])\n return margin\n}\n\n/** Whether the table is wider than its section, measured as the columns render (#109). */\nfunction useOverflowing(\n wrapper: RefObject<HTMLElement | null>,\n table: RefObject<HTMLElement | null>\n) {\n const [overflowing, setOverflowing] = useState(false)\n useLayoutEffect(() => {\n const measure = () => {\n if (wrapper.current && table.current)\n setOverflowing(table.current.offsetWidth > wrapper.current.clientWidth + 1)\n }\n measure()\n const next = framed(measure)\n const observer = new ResizeObserver(next.run)\n if (wrapper.current) observer.observe(wrapper.current)\n if (table.current) observer.observe(table.current)\n return () => {\n next.cancel()\n observer.disconnect()\n }\n }, [wrapper, table])\n return overflowing\n}\n\n/** The file name from `Content-Disposition`, or null. */\nfunction attachmentName(header: unknown) {\n if (typeof header !== 'string') return null\n const encoded = header.match(/filename\\*=UTF-8''([^;]+)/i)\n if (encoded) {\n try {\n return decodeURIComponent(encoded[1])\n } catch {\n // Fall through to the plain name.\n }\n }\n return header.match(/filename=\"?([^\";]+)\"?/i)?.[1] ?? null\n}\n\nexport function DataTable({\n resource,\n result,\n lookups = {},\n savedViews = [],\n trashed = false,\n bulkActions: initialBulkActions,\n}: {\n resource: ResourceDescription\n result: ResourceList\n lookups?: LookupOptions\n savedViews?: SavedView[]\n /** The «المحذوفات» list of `/resources/:name/trash`: rows offer restore only. */\n trashed?: boolean\n /**\n * The actor's bulk actions sent with the page (#108); without them the table loads them\n * after mounting and the selection column appears in a second render.\n */\n bulkActions?: BulkAction[]\n}) {\n const { calendar } = useUiPreferences()\n const { t, label, locale } = useMessages()\n const page = usePage<{ overlay?: { list?: unknown }; created?: string }>()\n const url = listUrl(page.url, page.props.overlay)\n const description = resource as ListDescription\n const query = new URL(url, 'http://localhost').searchParams\n const listPath = `/resources/${resource.name}${trashed ? '/trash' : ''}`\n const [search, setSearch] = useState(query.get('search') ?? '')\n const [failure, setFailure] = useState('')\n const [queryFailure, setQueryFailure] = useState('')\n const [exporting, setExporting] = useState(false)\n const [exportFailure, setExportFailure] = useState('')\n const [selected, setSelected] = useState<Set<string>>(() => new Set())\n const labels = useRef<FilterLabels>({})\n const section = useRef<HTMLElement>(null)\n const container = useRef<HTMLDivElement>(null)\n const tableElement = useRef<HTMLTableElement>(null)\n const body = useRef<HTMLTableSectionElement>(null)\n const sentinel = useRef<HTMLDivElement>(null)\n const scroller = useRef<ComponentRef<typeof InfiniteScroll>>(null)\n const offered = useBulkActions(resource.name, description.bulk !== false, initialBulkActions)\n // The «المحذوفات» list offers restore only; the active list everything else.\n const bulkActions = offered.filter(\n (action) => actionScope(action) === (trashed ? 'trash' : 'records')\n )\n // Opening one of this list's records remembers the view, so closing the dialog returns to it.\n useEffect(\n () =>\n router.on('before', (event) => {\n const { pathname } = event.detail.visit.url\n if (pathname.startsWith(`/resources/${resource.name}/`)) rememberListView(pathname)\n }),\n [resource.name]\n )\n // Inertia merges `result.data` page by page; permissions and labels of earlier pages accumulate here.\n const store = useRef<{\n source: ResourceList | null\n permissions: ResourceList['permissions']\n related: ResourceList['related']\n /** The first page's count; later pages send none (#111). */\n total: number | undefined\n }>({ source: null, permissions: {}, related: {}, total: undefined })\n if (store.current.source !== result) {\n const related = { ...store.current.related }\n for (const [key, rows] of Object.entries(result.related))\n related[key] = [\n ...new Map([...(related[key] ?? []), ...rows].map((row) => [String(row.id), row])).values(),\n ]\n store.current = {\n source: result,\n permissions: { ...store.current.permissions, ...result.permissions },\n related,\n total: result.meta.estimatedTotal ?? store.current.total,\n }\n }\n const { permissions, related, total } = store.current\n const fields = resource.fields.filter(\n (field) => resource.list.includes(field.key) && field.type !== 'hasMany'\n )\n const filterable = fields.filter((field) => field.filterable)\n const filters = readFilters(\n query,\n filterable.map((field) => field.key)\n )\n const activeFilters = filterable.filter((field) => filters[field.key])\n const table = useTable({\n features,\n data: result.data,\n columns: fields.map((field) => ({ accessorKey: field.key, id: field.key })),\n getRowId: (row) => String(row.id),\n })\n const rows = table.getRowModel().rows\n // A record created from this list is pinned first (closeCreated, pinCreated): highlighted\n // for a moment and scrolled into view, whatever the sort and however far the list scrolled.\n const created = page.props.created\n const [highlighted, setHighlighted] = useState<string | null>(null)\n useEffect(() => {\n if (!created) return\n setHighlighted(created)\n const timer = setTimeout(() => setHighlighted(null), 2400)\n return () => clearTimeout(timer)\n }, [created])\n const loadedIds = rows.map((row) => row.id)\n const selectable = bulkActions.length > 0\n const columns = fields.length + 1 + (selectable ? 1 : 0)\n const virtualized = rows.length > VIRTUAL_ROWS\n const scrollParent = useScrollParent(section, rows.length)\n const windowScrolling = scrollParent === null\n const scrollMargin = useScrollMargin(body, scrollParent, virtualized)\n const overflowing = useOverflowing(container, tableElement)\n // One hook for both scrollers: the window observers replace the element ones (#109).\n const virtual = useVirtualizer({\n count: rows.length,\n getScrollElement: () =>\n (windowScrolling ? window : (scrollParent ?? null)) as unknown as HTMLElement | null,\n observeElementRect: (windowScrolling\n ? observeWindowRect\n : observeElementRect) as unknown as typeof observeElementRect,\n observeElementOffset: (windowScrolling\n ? observeWindowOffset\n : observeElementOffset) as unknown as typeof observeElementOffset,\n scrollToFn: (windowScrolling ? windowScroll : elementScroll) as unknown as typeof elementScroll,\n initialOffset: () => (windowScrolling ? window.scrollY : (scrollParent?.scrollTop ?? 0)),\n scrollMargin,\n estimateSize: () => ROW_HEIGHT,\n overscan: 10,\n enabled: virtualized && scrollParent !== undefined,\n getItemKey: (index) => rows[index].id,\n })\n const scrollToCreated = useRef(virtual)\n scrollToCreated.current = virtual\n useEffect(() => {\n if (!created) return\n const row = body.current?.querySelector(`[data-row-id=\"${CSS.escape(created)}\"]`)\n if (row) row.scrollIntoView({ block: 'nearest' })\n else scrollToCreated.current.scrollToIndex(0)\n }, [created])\n const items =\n virtualized && scrollParent !== undefined\n ? virtual.getVirtualItems()\n : rows.slice(0, virtualized ? VIRTUAL_ROWS : rows.length).map((_, index) => ({\n index,\n start: scrollMargin,\n end: scrollMargin,\n }))\n // Starts and ends include the rows' offset in the scroller; the spacers do not.\n const before = virtualized ? Math.max(0, (items[0]?.start ?? scrollMargin) - scrollMargin) : 0\n const after = virtualized\n ? Math.max(0, virtual.getTotalSize() - ((items.at(-1)?.end ?? scrollMargin) - scrollMargin))\n : 0\n // The next page loads as the end of the list nears the bottom of the scroller (#109).\n const loadNext = useRef(() => {})\n loadNext.current = () => {\n const element = sentinel.current\n if (!element || failure || !scroller.current?.hasNext()) return\n const bottom = scrollParent ? scrollParent.getBoundingClientRect().bottom : window.innerHeight\n if (element.getBoundingClientRect().top - bottom < 200) scroller.current.fetchNext()\n }\n useEffect(() => {\n if (scrollParent === undefined) return\n const target: HTMLElement | Window = scrollParent ?? window\n const scrolled = () => loadNext.current()\n target.addEventListener('scroll', scrolled, { passive: true })\n return () => target.removeEventListener('scroll', scrolled)\n }, [scrollParent])\n const go = (next: URLSearchParams) => {\n next.delete('cursor')\n setQueryFailure('')\n setSelected(new Set())\n const suffix = next.toString()\n router.get(\n `${listPath}${suffix ? `?${suffix}` : ''}`,\n {},\n {\n preserveScroll: true,\n // An invalid filter is 422 E_FILTER; show the server's message instead of the error page.\n onHttpException: (response) => {\n if (response.status !== 422) return\n setQueryFailure(\n serverMessage(response.data) ?? t('تعذر تطبيق التصفية. راجع القيم ثم أعد المحاولة.')\n )\n return false\n },\n }\n )\n }\n const navigate = (changes: Record<string, string | undefined>) => {\n const next = new URLSearchParams(query)\n for (const [key, value] of Object.entries(changes))\n value ? next.set(key, value) : next.delete(key)\n go(next)\n }\n const applyFilter = (key: string, filter: FieldFilter | null) => {\n const next = new URLSearchParams(query)\n writeFilter(next, key, filter)\n go(next)\n }\n const clearFilters = () => {\n const next = new URLSearchParams(query)\n for (const field of activeFilters) clearFilter(next, field.key)\n go(next)\n }\n const sort = query.get('sort')\n const direction = query.get('direction') === 'desc' ? 'desc' : 'asc'\n const valueLabel = (field: ResourceField) => (raw: string) =>\n filterValueLabel(field, raw, {\n options: lookups[field.key],\n related: related[field.key],\n labels: labels.current[field.key],\n calendar,\n t,\n language: locale,\n })\n const remember = (key: string) => (choices: Option[]) => {\n labels.current[key] = {\n ...labels.current[key],\n ...Object.fromEntries(choices.map((choice) => [choice.value, choice.label])),\n }\n }\n // The server export reads the same filtered set as this list, page by page, up to its limit.\n const exportResults = async (format: 'csv' | 'xlsx') => {\n setExporting(true)\n setExportFailure('')\n try {\n const response = await axios.get<Blob>(exportHref(resource.name, query, format), {\n responseType: 'blob',\n headers: {\n Accept:\n format === 'xlsx'\n ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/json'\n : 'text/csv, application/json',\n },\n })\n const href = URL.createObjectURL(response.data)\n const link = document.createElement('a')\n link.href = href\n link.download =\n attachmentName(response.headers['content-disposition']) ?? `${resource.label}.${format}`\n link.click()\n // Revoking right after click can cancel the download in some browsers.\n setTimeout(() => URL.revokeObjectURL(href), 60_000)\n } catch (error) {\n const body = axios.isAxiosError(error) ? error.response?.data : null\n const message = body instanceof Blob ? serverMessage(await body.text().catch(() => '')) : null\n setExportFailure(message ?? t('تعذر تصدير النتائج. حاول مجدداً.'))\n } finally {\n setExporting(false)\n }\n }\n const refresh = () => router.visit(url, { preserveScroll: true })\n // Records open in a dialog over this list, which stays mounted (#31); modified clicks\n // (new tab, new window) keep the link's own behavior.\n const overlay = (event: MouseEvent, id: string, mode: 'show' | 'edit') => {\n if (!plainClick(event)) return\n event.preventDefault()\n void openRecord(resource.name, id, mode)\n }\n const currentQuery = (): SavedViewQuery => {\n const view: SavedViewQuery = {}\n const text = query.get('search')\n if (text) view.search = text\n if (sort) {\n view.sort = sort\n view.direction = direction\n }\n const saved: Record<string, unknown> = {}\n for (const field of activeFilters) saved[field.key] = toSavedFilter(filters[field.key])\n // Saved views store operator objects too (ADR 046); older type declarations list scalars.\n if (Object.keys(saved).length) view.filters = saved as SavedViewQuery['filters']\n return view\n }\n const applyView = (view: SavedView) => {\n const next = new URLSearchParams()\n if (view.query.search) next.set('search', view.query.search)\n if (view.query.sort) {\n next.set('sort', view.query.sort)\n next.set('direction', view.query.direction ?? 'asc')\n }\n for (const [key, value] of Object.entries(view.query.filters ?? {}))\n writeFilter(next, key, fromSavedFilter(value))\n setSearch(view.query.search ?? '')\n go(next)\n }\n const allState = selectionState(selected, loadedIds)\n const chosen = loadedIds.filter((id) => selected.has(id))\n return (\n <section\n ref={section}\n aria-label={t('قائمة {resource}', { resource: resource.label })}\n // overflow-clip keeps the rounded corners without becoming a scroll container, so the\n // header sticks to the workspace scroller (#109).\n className=\"min-w-0 overflow-clip rounded-xl border border-border bg-card shadow-[0_2px_10px_color-mix(in_oklab,var(--foreground)_2%,transparent)]\"\n >\n <div className=\"flex flex-wrap items-center justify-between gap-4 border-b px-5 py-4\">\n <div className=\"flex flex-wrap items-center gap-3\">\n <h2 className=\"text-sm font-semibold\">\n {/* The page heading names the resource; no label in an idafa slot here (#110). */}\n {trashed ? t('المحذوفات') : t('السجلات')}\n </h2>\n <Badge variant=\"secondary\" className=\"font-normal tabular-nums\">\n {t('المعروض: {count}', { count: rows.length })}\n </Badge>\n <span className=\"text-xs text-muted-foreground\">\n {result.meta.nextCursor === null\n ? t('ضمن نطاقك: {records}', { records: recordCount(rows.length, t) })\n : total === undefined\n ? t('حسب نطاق صلاحياتك')\n : total < EXACT_COUNT_LIMIT\n ? t('ضمن نطاقك: {records}', { records: recordCount(total, t) })\n : t('ضمن نطاقك: {records} تقريبًا', { records: recordCount(total, t) })}\n </span>\n </div>\n <div className=\"flex flex-wrap items-center gap-2\">\n {description.trash && (\n <Button variant=\"outline\" size=\"sm\" asChild>\n <Link\n href={trashed ? `/resources/${resource.name}` : `/resources/${resource.name}/trash`}\n >\n {trashed ? <ListChecks size={15} /> : <Trash2 size={15} />}\n {trashed ? t('السجلات النشطة') : t('المحذوفات')}\n </Link>\n </Button>\n )}\n {!trashed && description.exportable !== false && (\n <DropdownMenu dir=\"rtl\">\n <DropdownMenuTrigger asChild>\n <Button variant=\"outline\" size=\"sm\" disabled={!rows.length || exporting}>\n {exporting ? (\n <Loader2 size={15} className=\"animate-spin\" />\n ) : (\n <Download size={15} />\n )}\n {exporting ? t('جارٍ التصدير...') : t('تصدير النتائج')}\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n <DropdownMenuItem onSelect={() => void exportResults('xlsx')}>\n <FileSpreadsheet size={15} />\n {t('ملف Excel (xlsx)')}\n </DropdownMenuItem>\n <DropdownMenuItem onSelect={() => void exportResults('csv')}>\n <FileText size={15} />\n {t('ملف CSV')}\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n )}\n </div>\n </div>\n {exportFailure && (\n <div className=\"border-b px-5 py-3\">\n <Alert variant=\"destructive\">\n <AlertDescription className=\"flex flex-wrap items-center justify-between gap-2\">\n {exportFailure}\n <Button variant=\"ghost\" size=\"sm\" onClick={() => setExportFailure('')}>\n {t('إغلاق')}\n </Button>\n </AlertDescription>\n </Alert>\n </div>\n )}\n {/* Saved views belong to the active list; «المحذوفات» has none. */}\n {!trashed && (resource.searchable || filterable.length > 0) && (\n <SavedViewsBar\n resource={resource}\n views={savedViews}\n current={currentQuery}\n onApply={applyView}\n onChanged={refresh}\n onFailure={setFailure}\n />\n )}\n {(resource.searchable || filterable.length > 0) && (\n <div className=\"grid gap-3 border-b px-5 py-4\">\n <div className=\"flex flex-wrap items-center gap-3\">\n {resource.searchable && (\n <form\n role=\"search\"\n className=\"relative w-full max-w-sm\"\n onSubmit={(event) => {\n event.preventDefault()\n navigate({ search })\n }}\n >\n <Search\n className=\"pointer-events-none absolute start-3 top-2.5 text-muted-foreground\"\n size={16}\n />\n <Input\n aria-label={t('البحث في {field}', { field: resource.label })}\n value={search}\n onChange={(event) => setSearch(event.target.value)}\n placeholder={t('ابحث في السجلات...')}\n className=\"h-9 bg-background/60 ps-10 text-xs\"\n />\n </form>\n )}\n {filterable.length > 0 && (\n <span className=\"flex items-center gap-2 text-xs text-muted-foreground\">\n <SlidersHorizontal size={15} />\n {t('تصفية')}\n </span>\n )}\n {filterable.map((field) => (\n <FilterControl\n key={field.key}\n resource={resource.name}\n field={field}\n filter={filters[field.key]}\n options={lookups[field.key]}\n related={related[field.key]}\n labels={labels.current[field.key]}\n onRemember={remember(field.key)}\n onApply={(filter) => applyFilter(field.key, filter)}\n />\n ))}\n </div>\n {activeFilters.length > 0 && (\n <ul aria-label={t('التصفية المطبقة')} className=\"flex flex-wrap items-center gap-2\">\n {activeFilters.map((field) => (\n <li key={field.key}>\n <Badge\n variant=\"secondary\"\n className=\"h-7 gap-1.5 ps-3 pe-1.5 text-xs font-normal\"\n >\n <span className=\"font-medium\">{label(field.label)}:</span>\n <span className=\"max-w-[260px] truncate\">\n {describeFilter(filters[field.key], valueLabel(field), t)}\n </span>\n <button\n type=\"button\"\n aria-label={t('إزالة تصفية {field}', {\n field: label(field.label),\n })}\n className=\"rounded-full p-0.5 text-muted-foreground hover:bg-background hover:text-foreground\"\n onClick={() => applyFilter(field.key, null)}\n >\n <X size={13} />\n </button>\n </Badge>\n </li>\n ))}\n <li>\n <Button variant=\"ghost\" size=\"xs\" onClick={clearFilters}>\n <X size={14} />\n {t('مسح التصفية')}\n </Button>\n </li>\n </ul>\n )}\n {queryFailure && (\n <Alert variant=\"destructive\">\n <AlertDescription>{queryFailure}</AlertDescription>\n </Alert>\n )}\n </div>\n )}\n {selectable && (\n <BulkBar\n resource={resource.name}\n actions={bulkActions}\n selected={chosen}\n rows={result.data}\n onClear={() => setSelected(new Set())}\n onDone={(outcome) => {\n // Refused rows stay selected so they can be reviewed or retried.\n const failed = new Set(outcome.failed.map((entry) => String(entry.id)))\n setSelected((current) => new Set([...current].filter((id) => failed.has(id))))\n refresh()\n }}\n />\n )}\n <InfiniteScroll\n ref={(instance) => {\n scroller.current = instance\n }}\n data=\"result\"\n manual\n onlyNext\n preserveUrl\n params={{\n data: { limit: PAGE_SIZE },\n onBefore: () => {\n setFailure('')\n },\n onHttpException: () => {\n setFailure(t('تعذر تحميل السجلات التالية. أعد المحاولة.'))\n return false\n },\n onNetworkError: () => {\n setFailure(t('تعذر الاتصال بالخادم. تحقق من الاتصال ثم أعد المحاولة.'))\n return false\n },\n }}\n next={({ fetch, loading, hasMore }) => (\n <div className=\"flex flex-wrap items-center justify-center gap-4 border-t px-5 py-3 text-xs text-muted-foreground\">\n {failure && (\n <p role=\"alert\" className=\"text-destructive\">\n {failure}\n </p>\n )}\n {loading ? (\n <span role=\"status\" className=\"inline-flex items-center gap-2\">\n <Loader2 size={14} className=\"animate-spin\" />\n {t('جارٍ تحميل المزيد...')}\n </span>\n ) : hasMore ? (\n <Button variant=\"ghost\" size=\"sm\" onClick={fetch}>\n {t('تحميل المزيد')}\n </Button>\n ) : (\n <span>{rows.length ? t('نهاية السجلات') : ''}</span>\n )}\n </div>\n )}\n >\n <div\n ref={container}\n data-slot=\"table-scroll\"\n data-overflowing={overflowing ? '' : undefined}\n // No scroller of its own: horizontal scrolling only when the columns do not fit (#109).\n className={overflowing ? 'overflow-x-auto' : undefined}\n >\n <table\n ref={tableElement}\n className=\"w-full text-start text-sm\"\n aria-rowcount={rows.length + 1}\n aria-label={resource.label}\n >\n <thead className=\"sticky top-0 z-10 bg-muted text-xs text-muted-foreground\">\n <tr>\n {selectable && (\n <th scope=\"col\" className=\"h-11 w-10 ps-5 pe-1 text-start\">\n <Checkbox\n aria-label={t('تحديد كل السجلات المعروضة')}\n checked={allState}\n disabled={!rows.length}\n onCheckedChange={(value) =>\n setSelected(value === true ? new Set(loadedIds) : new Set())\n }\n />\n </th>\n )}\n {fields.map((field) => (\n <th\n key={field.key}\n scope=\"col\"\n className=\"h-11 px-5 text-start font-medium\"\n aria-sort={\n sort === field.key\n ? direction === 'desc'\n ? 'descending'\n : 'ascending'\n : undefined\n }\n >\n {field.sortable ? (\n <button\n type=\"button\"\n className=\"inline-flex items-center gap-2 hover:text-foreground\"\n onClick={() =>\n navigate({\n sort: field.key,\n direction: sort === field.key && direction === 'asc' ? 'desc' : 'asc',\n })\n }\n >\n {label(field.label)}\n {sort === field.key ? (\n direction === 'desc' ? (\n <ArrowDown size={12} />\n ) : (\n <ArrowUp size={12} />\n )\n ) : (\n <ArrowDownUp size={12} className=\"opacity-60\" />\n )}\n </button>\n ) : (\n label(field.label)\n )}\n </th>\n ))}\n <th\n scope=\"col\"\n className={`border-s bg-muted px-5 text-start font-medium ${overflowing ? pinned : ''}`}\n >\n {t('الإجراءات')}\n </th>\n </tr>\n </thead>\n <tbody ref={body}>\n {before > 0 && (\n <tr aria-hidden=\"true\">\n <td colSpan={columns} style={{ height: before }} />\n </tr>\n )}\n {items.map(({ index }) => {\n const row = rows[index].original\n const id = String(row.id)\n const checked = selected.has(id)\n return (\n <tr\n key={id}\n ref={virtualized ? virtual.measureElement : undefined}\n data-index={index}\n data-row-id={id}\n data-created={highlighted === id ? '' : undefined}\n aria-rowindex={index + 2}\n aria-selected={selectable ? checked : undefined}\n className={`group border-b transition-colors duration-700 last:border-0 hover:bg-background ${checked ? 'bg-accent/40' : ''} ${highlighted === id ? 'bg-primary/10' : ''}`}\n style={{ height: ROW_HEIGHT }}\n >\n {selectable && (\n <td className=\"w-10 ps-5 pe-1\">\n <Checkbox\n aria-label={t('تحديد السجل {id}', { id })}\n checked={checked}\n onCheckedChange={(value) =>\n setSelected((current) => toggleSelection(current, id, value === true))\n }\n />\n </td>\n )}\n {fields.map((field) => (\n <Cell\n key={field.key}\n field={field}\n row={row}\n related={related}\n lookups={lookups}\n />\n ))}\n {/* Pinned at the inline end, with a shadow, only while the columns overflow. */}\n <td\n className={`whitespace-nowrap border-s bg-card px-5 text-xs group-hover:bg-background ${overflowing ? pinned : ''}`}\n >\n <span className=\"inline-flex items-center gap-1\">\n {trashed ? (\n // Restore is authorized by the delete rule on the deleted record (ADR 046).\n (permissions[id] as Record<string, boolean | undefined> | undefined)\n ?.restore === true && (\n <RestoreAction\n resource={resource.name}\n id={id}\n version={row.version ?? undefined}\n label={t('السجل {id}', { id })}\n onDone={refresh}\n />\n )\n ) : (\n <>\n <Button variant=\"ghost\" size=\"sm\" asChild>\n <Link\n href={`/resources/${resource.name}/${id}`}\n aria-label={t('عرض السجل {id}', { id })}\n // Fetched on hover or focus, so the details open complete.\n onPointerEnter={() => prefetchRecord(resource.name, id, 'show')}\n onFocus={() => prefetchRecord(resource.name, id, 'show')}\n onClick={(event) => overlay(event, id, 'show')}\n >\n {t('عرض')}\n </Link>\n </Button>\n <Can permissions={permissions[id] ?? {}} action=\"update\">\n <Button variant=\"ghost\" size=\"sm\" asChild>\n <Link\n href={`/resources/${resource.name}/${id}/edit`}\n aria-label={t('تعديل السجل {id}', { id })}\n onPointerEnter={() => prefetchRecord(resource.name, id, 'edit')}\n onFocus={() => prefetchRecord(resource.name, id, 'edit')}\n onClick={(event) => overlay(event, id, 'edit')}\n >\n {t('تعديل')}\n </Link>\n </Button>\n </Can>\n <ResourceActions\n resource={resource.name}\n id={id}\n version={row.version ?? undefined}\n permissions={permissions[id] ?? {}}\n label={\n typeof row._title === 'string' && row._title\n ? row._title\n : t('السجل {id}', { id })\n }\n size=\"sm\"\n variant=\"ghost\"\n onDone={refresh}\n />\n </>\n )}\n </span>\n </td>\n </tr>\n )\n })}\n {after > 0 && (\n <tr aria-hidden=\"true\">\n <td colSpan={columns} style={{ height: after }} />\n </tr>\n )}\n {!rows.length && (\n <tr>\n <td colSpan={columns} className=\"py-16 text-center\">\n {trashed ? (\n <Trash2\n className=\"mx-auto mb-3 text-muted-foreground\"\n size={30}\n strokeWidth={1.3}\n />\n ) : (\n <Inbox\n className=\"mx-auto mb-3 text-muted-foreground\"\n size={30}\n strokeWidth={1.3}\n />\n )}\n <p className=\"text-sm font-medium\">\n {trashed && !query.get('search') && !activeFilters.length\n ? t('لا توجد سجلات محذوفة')\n : t('لا توجد سجلات مطابقة')}\n </p>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {query.get('search') || activeFilters.length\n ? t('غيّر البحث أو التصفية لعرض سجلات أخرى.')\n : trashed\n ? t('تظهر هنا السجلات المحذوفة ضمن نطاقك لتستعيدها.')\n : t('لم تُضف سجلات ضمن نطاقك بعد.')}\n </p>\n </td>\n </tr>\n )}\n </tbody>\n </table>\n </div>\n <div ref={sentinel} aria-hidden=\"true\" />\n </InfiniteScroll>\n </section>\n )\n}\n\n/** Presets over the same query keys the list already accepts; AdulaJS validates every one. */\nfunction SavedViewsBar({\n resource,\n views,\n current,\n onApply,\n onChanged,\n onFailure,\n}: {\n resource: ResourceDescription\n views: SavedView[]\n current: () => SavedViewQuery\n onApply: (view: SavedView) => void\n onChanged: () => void\n onFailure: (message: string) => void\n}) {\n const { t } = useMessages()\n const [naming, setNaming] = useState(false)\n const [name, setName] = useState('')\n const [shared, setShared] = useState(false)\n const [busy, setBusy] = useState(false)\n const base = `/resources/${resource.name}/views`\n const save = async (event: React.FormEvent) => {\n event.preventDefault()\n setBusy(true)\n onFailure('')\n try {\n await axios.post(\n base,\n { name, query: current(), shared },\n { headers: { Accept: 'application/json' }, withXSRFToken: true }\n )\n setNaming(false)\n setName('')\n setShared(false)\n onChanged()\n } catch (error) {\n onFailure(\n axios.isAxiosError(error) && error.response?.data?.error?.message\n ? String(error.response.data.error.message)\n : t('تعذر حفظ العرض.')\n )\n } finally {\n setBusy(false)\n }\n }\n const remove = async (view: SavedView) => {\n setBusy(true)\n onFailure('')\n try {\n await axios.delete(`${base}/${view.id}`, {\n headers: { Accept: 'application/json' },\n withXSRFToken: true,\n })\n onChanged()\n } catch {\n onFailure(t('تعذر حذف العرض.'))\n } finally {\n setBusy(false)\n }\n }\n return (\n <div className=\"flex flex-wrap items-center gap-2 border-b px-5 py-3\">\n <span className=\"flex items-center gap-2 text-xs text-muted-foreground\">\n <Bookmark size={15} />\n {t('العروض المحفوظة')}\n </span>\n {views.length === 0 && (\n <span className=\"text-xs text-muted-foreground\">{t('لا عروض بعد')}</span>\n )}\n {views.map((view) => (\n <span\n key={view.id}\n className=\"flex items-center gap-1 rounded-full border border-border bg-background/60 ps-1 pe-3\"\n >\n <Button\n variant=\"ghost\"\n size=\"xs\"\n className=\"rounded-full\"\n onClick={() => onApply(view)}\n >\n {view.name}\n {!view.own && <span className=\"text-muted-foreground\"> · {t('مشترك')}</span>}\n </Button>\n {view.own && (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-xs\"\n className=\"rounded-full\"\n aria-label={t('حذف العرض {name}', { name: view.name })}\n disabled={busy}\n onClick={() => remove(view)}\n >\n <X aria-hidden />\n </Button>\n )}\n </span>\n ))}\n {naming ? (\n <form onSubmit={save} className=\"flex flex-wrap items-center gap-2\">\n <Input\n aria-label={t('اسم العرض')}\n value={name}\n autoFocus\n maxLength={60}\n onChange={(event) => setName(event.target.value)}\n placeholder={t('اسم العرض')}\n className=\"h-8 w-44 text-xs\"\n />\n <label className=\"flex items-center gap-1 text-xs text-muted-foreground\">\n <Checkbox checked={shared} onCheckedChange={(value) => setShared(value === true)} />\n {t('مشترك')}\n </label>\n <Button type=\"submit\" size=\"sm\" disabled={busy || !name.trim()}>\n {t('حفظ')}\n </Button>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n onClick={() => setNaming(false)}\n >\n {t('إلغاء')}\n </Button>\n </form>\n ) : (\n <Button variant=\"outline\" size=\"sm\" onClick={() => setNaming(true)}>\n <BookmarkPlus size={14} />\n {t('حفظ العرض الحالي')}\n </Button>\n )}\n </div>\n )\n}\n\nfunction Cell({\n field,\n row,\n related,\n lookups,\n}: {\n field: ResourceField\n row: SerializedRecord\n related: ResourceList['related']\n lookups: LookupOptions\n}) {\n const { calendar } = useUiPreferences()\n const { t, locale } = useMessages()\n const text = displayValue(field, row, related, lookups, calendar, t, locale)\n const numeric = ['money', 'integer', 'decimal', 'percent', 'date', 'datetime'].includes(\n field.type\n )\n const person = relatedUser(field, row, related)\n return (\n <td className=\"px-5 py-2\" title={text}>\n {field.type === 'boolean' && row[field.key] !== null && row[field.key] !== undefined ? (\n <Badge variant={row[field.key] ? 'default' : 'secondary'}>{text}</Badge>\n ) : person ? (\n // One picture per cell, beside the name it decorates (ADR 050).\n <span className=\"inline-flex items-center gap-1.5\">\n <UserAvatar user={person} size=\"xs\" />\n <bdi dir=\"auto\" className=\"line-clamp-2 max-w-md break-words\">\n {text}\n </bdi>\n </span>\n ) : (\n // The cell keeps the page direction; the value is isolated so «-3» and «12-3-ABC» read\n // in their own order (#113), and text wraps to two lines instead of forcing width (#109).\n <bdi\n dir={numeric ? 'ltr' : 'auto'}\n className={`line-clamp-2 max-w-md break-words ${numeric ? 'tabular-nums' : ''}`}\n >\n {text}\n </bdi>\n )}\n </td>\n )\n}\n",
|
|
33
34
|
"target": "inertia/components/ui/data-table.tsx"
|
|
34
35
|
}
|
|
35
36
|
],
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "dialog-param",
|
|
3
|
+
"type": "registry:ui",
|
|
4
|
+
"registryDependencies": [
|
|
5
|
+
"resource-surface"
|
|
6
|
+
],
|
|
7
|
+
"dependencies": [],
|
|
8
|
+
"files": [
|
|
9
|
+
{
|
|
10
|
+
"path": "registry/ui/dialog_param.ts",
|
|
11
|
+
"type": "registry:ui",
|
|
12
|
+
"content": "import { useEffect, useLayoutEffect, useRef, useState } from 'react'\nimport { usePage } from '@inertiajs/react'\nimport { clientVisit } from '~/components/ui/resource-surface'\n\n/*\n * Entity dialogs with their own address (owner decision 30 for 2.3.0, ADR 016). A dialog that\n * creates, edits or shows a lasting item is open while its query parameter is in the address:\n * `?new=1` for a create dialog, `?edit=<id>` for an edit dialog. Opening adds the parameter\n * with a client-side visit (no request, no progress bar), so Back closes the dialog and stays\n * on the page, a reload keeps it open and the address can be shared. Transient dialogs\n * (confirmations, one-setting edits, reordering, one-time secrets, step flows) keep no address.\n *\n * A dialog only names its parameter and maps the value to its item; the history rules live\n * here and nowhere else.\n */\n\n/** The page address (path and query) with one query parameter set, or removed with null. */\nexport function withDialogParam(url: string, name: string, value: string | null) {\n const [beforeHash, hash = ''] = url.split('#', 2)\n const [path, search = ''] = beforeHash.split('?', 2)\n const query = new URLSearchParams(search)\n if (value === null) query.delete(name)\n else query.set(name, value)\n const rest = query.toString()\n return `${path}${rest ? `?${rest}` : ''}${hash ? `#${hash}` : ''}`\n}\n\n/** The value of one query parameter of a page address, or null. */\nexport function dialogParam(url: string, name: string) {\n const search = url.split('#', 1)[0].split('?', 2)[1] ?? ''\n return new URLSearchParams(search).get(name)\n}\n\n/** The dialog address this page pushed last; closing it again goes Back instead of forward. */\nlet pushed: string | null = null\n\n/** The address a close is going Back to, while that popstate is on its way. */\nlet returning: string | null = null\n\nconst here = () => `${window.location.pathname}${window.location.search}${window.location.hash}`\n\nif (typeof window !== 'undefined') {\n // A close goes Back to the page the dialog opened over. That history entry holds the page as\n // it was when the dialog opened, and Inertia would put it back by mounting the page again\n // (losing focus, scroll and anything saved meanwhile). This listener runs before Inertia's\n // (capture phase on the target), takes over that one popstate and keeps the mounted page,\n // with its current props, at the address it returned to. Every other Back is Inertia's.\n window.addEventListener(\n 'popstate',\n (event) => {\n const target = returning\n returning = null\n pushed = null\n if (target === null || here() !== target) return\n event.stopImmediatePropagation()\n clientVisit('replace', { url: target, preserveState: true, preserveScroll: true }, true)\n },\n { capture: true }\n )\n}\n\nexport type DialogParam<T, P = undefined> = {\n /** The parameter's value in the address, or null while the dialog is closed. */\n value: string | null\n /** The item the value names; null while closed, unknown, or still resolving. */\n item: T | null\n /**\n * Opens the dialog: pushes the parameter (`1` when no value is given). `preset` reaches\n * onOpen for this opening only (a choice the address does not carry, such as a parent).\n */\n open: (value?: string | number, preset?: P) => void\n /** Closes the dialog: Back when this page pushed it, otherwise the parameter is replaced away. */\n close: () => void\n}\n\nexport type DialogParamOptions<T, P = undefined> = {\n /** The item is still being fetched for the value (a direct load); nothing is stripped yet. */\n pending?: boolean\n /** Called once per opening, when the value first resolves, to start the dialog's draft. */\n onOpen?: (item: T, value: string, preset: P | undefined) => void\n}\n\n/**\n * Binds a dialog to the query parameter `name` of the page address. `resolve` maps the value\n * to the dialog's item and returns undefined for a value that names nothing this user may open:\n * the dialog then stays closed and the parameter is removed with replace, so an unknown or\n * forbidden id shows nothing and reveals nothing.\n */\nexport function useDialogParam<T, P = undefined>(\n name: string,\n resolve: (value: string) => T | undefined,\n options: DialogParamOptions<T, P> = {}\n): DialogParam<T, P> {\n const url = usePage().url\n const addressed = dialogParam(url, name)\n // The value being opened while its visit is on its way: the dialog opens with the click, in\n // the same frame (decision 25), not once the address has changed.\n const [opening, setOpening] = useState<string | null>(null)\n const abandoned = useRef(false)\n useEffect(() => {\n if (opening !== null && addressed !== null) setOpening(null)\n }, [opening, addressed])\n const value = addressed ?? opening\n const found = value === null ? undefined : resolve(value)\n const item = found ?? null\n const { pending = false, onOpen } = options\n\n // A value that resolves to nothing is removed from the address, without a history entry.\n const unknown = addressed !== null && found === undefined && !pending\n useEffect(() => {\n if (!unknown) return\n if (pushed === here()) pushed = null\n clientVisit(\n 'replace',\n {\n url: withDialogParam(here(), name, null),\n preserveState: true,\n preserveScroll: true,\n },\n true\n )\n }, [unknown, name])\n\n // The draft starts before paint, once per opening (a value, then the item it names).\n const started = useRef<string | null>(null)\n const latest = useRef(onOpen)\n latest.current = onOpen\n const preset = useRef<P | undefined>(undefined)\n useLayoutEffect(() => {\n if (value === null) {\n started.current = null\n return\n }\n if (found === undefined || started.current === value) return\n started.current = value\n const given = preset.current\n preset.current = undefined\n latest.current?.(found, value, given)\n }, [value, found])\n\n const open = (next: string | number = '1', given?: P) => {\n const target = withDialogParam(here(), name, String(next))\n if (target === here()) return\n preset.current = given\n abandoned.current = false\n setOpening(String(next))\n clientVisit(\n 'push',\n {\n url: target,\n preserveState: true,\n preserveScroll: true,\n onSuccess: () => {\n pushed = target\n // Closed before its address arrived: the entry it pushed is left the same way.\n if (abandoned.current) {\n abandoned.current = false\n close()\n }\n },\n },\n true\n )\n }\n\n const close = () => {\n const current = here()\n if (dialogParam(current, name) === null) {\n if (opening !== null) {\n abandoned.current = true\n setOpening(null)\n }\n return\n }\n const target = withDialogParam(current, name, null)\n if (pushed === current) {\n pushed = null\n returning = target\n window.history.back()\n return\n }\n clientVisit('replace', { url: target, preserveState: true, preserveScroll: true }, true)\n }\n\n return { value, item, open, close }\n}\n\nexport type EntityDialog<T> = {\n /** `'new'` while creating, the edited item while editing, null while closed. */\n item: T | 'new' | null\n openCreate: () => void\n openEdit: (id: string | number) => void\n close: () => void\n}\n\n/**\n * One dialog that creates and edits the same kind of item: `?new=1` creates and `?edit=<id>`\n * edits. A page with two such dialogs gives the second its own parameter names. `find` maps an\n * id to the item; `canCreate: false` drops `?new=1` as an unknown value.\n */\nexport function useEntityDialog<T>(options: {\n find: (id: string) => T | undefined\n names?: { create: string; edit: string }\n canCreate?: boolean\n pending?: boolean\n onOpen?: (item: T | 'new') => void\n}): EntityDialog<T> {\n const { create = 'new', edit = 'edit' } = options.names ?? {}\n const allowed = options.canCreate !== false\n const creating = useDialogParam(\n create,\n (value) => (value === '1' && allowed ? ('new' as const) : undefined),\n { onOpen: () => options.onOpen?.('new') }\n )\n const editing = useDialogParam(edit, options.find, {\n pending: options.pending,\n onOpen: (item) => options.onOpen?.(item),\n })\n return {\n item: editing.item ?? creating.item,\n openCreate: () => creating.open(),\n openEdit: (id) => editing.open(id),\n close: () => (editing.value !== null ? editing.close() : creating.close()),\n }\n}\n",
|
|
13
|
+
"target": "inertia/components/ui/dialog_param.ts"
|
|
14
|
+
}
|
|
15
|
+
],
|
|
16
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
17
|
+
}
|
package/build/dialog.json
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
{
|
|
10
10
|
"path": "registry/ui/dialog.tsx",
|
|
11
11
|
"type": "registry:ui",
|
|
12
|
-
"content": "import * as React from 'react'\nimport { cn } from 'cn'\nimport { XIcon } from 'lucide-react'\nimport { Dialog as DialogPrimitive } from 'radix-ui'\n\nimport { Button } from '~/components/ui/button'\nimport { useMessages } from '~/components/ui/messages'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\n\nconst DialogContentContext = React.createContext<React.RefObject<HTMLDivElement | null> | null>(\n null\n)\n\nfunction Dialog({\n mode,\n onOpenChange,\n children,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Root> & { mode?: 'view' | 'edit' | 'confirm' }) {\n const content = React.useRef<HTMLDivElement>(null)\n const [confirming, setConfirming] = React.useState(false)\n const [uncontrolledOpen, setUncontrolledOpen] = React.useState(props.defaultOpen ?? false)\n const preferences = useUiPreferences()\n const { t, dir } = useMessages()\n const open = props.open ?? uncontrolledOpen\n const commit = (next: boolean) => {\n setUncontrolledOpen(next)\n onOpenChange?.(next)\n }\n const request = (next: boolean) => {\n const editing = mode === 'edit' || (!mode && Boolean(content.current?.querySelector('form')))\n if (!next && editing && preferences.confirmDialogClose) setConfirming(true)\n else commit(next)\n }\n return (\n <DialogContentContext.Provider value={content}>\n <DialogPrimitive.Root data-slot=\"dialog\" {...props} open={open} onOpenChange={request}>\n {children}\n </DialogPrimitive.Root>\n {confirming && open && (\n <Dialog mode=\"confirm\" open onOpenChange={(next) => !next && setConfirming(false)}>\n <DialogContent showCloseButton={false} className=\"z-[70] sm:max-w-md\" dir={dir}>\n <DialogHeader>\n <DialogTitle>{t('إغلاق النموذج؟')}</DialogTitle>\n <DialogDescription>\n {t('قد تفقد التغييرات التي لم تحفظها. يمكنك متابعة التحرير أو إغلاق النموذج.')}\n </DialogDescription>\n </DialogHeader>\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" onClick={() => setConfirming(false)}>\n {t('متابعة التحرير')}\n </Button>\n <Button\n type=\"button\"\n variant=\"destructive\"\n onClick={() => {\n setConfirming(false)\n commit(false)\n }}\n >\n {t('إغلاق دون حفظ')}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )}\n </DialogContentContext.Provider>\n )\n}\n\nfunction DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {\n return <DialogPrimitive.Trigger data-slot=\"dialog-trigger\" {...props} />\n}\n\nfunction DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {\n return <DialogPrimitive.Portal data-slot=\"dialog-portal\" {...props} />\n}\n\nfunction DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {\n return <DialogPrimitive.Close data-slot=\"dialog-close\" {...props} />\n}\n\nfunction DialogOverlay({\n className,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {\n return (\n <DialogPrimitive.Overlay\n data-slot=\"dialog-overlay\"\n className={cn(\n 'fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0',\n className\n )}\n {...props}\n />\n )\n}\n\nfunction DialogContent({\n ref,\n className,\n children,\n showCloseButton = true,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Content> & {\n showCloseButton?: boolean\n}) {\n const content = React.useContext(DialogContentContext)\n const { t } = useMessages()\n return (\n <DialogPortal data-slot=\"dialog-portal\">\n <DialogOverlay />\n <DialogPrimitive.Content\n ref={(node) => {\n if (content) content.current = node\n if (typeof ref === 'function') return ref(node)\n if (ref) ref.current = node\n }}\n data-slot=\"dialog-content\"\n className={cn(\n 'fixed top-[50%] start-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] ltr:translate-x-[-50%] rtl:-translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg',\n className\n )}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close\n data-slot=\"dialog-close\"\n className=\"absolute top-4 end-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\"\n >\n <XIcon />\n <span className=\"sr-only\">{t('إغلاق')}</span>\n </DialogPrimitive.Close>\n )}\n </DialogPrimitive.Content>\n </DialogPortal>\n )\n}\n\nfunction DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"dialog-header\"\n className={cn('flex flex-col gap-2 text-center sm:text-start', className)}\n {...props}\n />\n )\n}\n\nfunction DialogFooter({\n className,\n showCloseButton = false,\n children,\n ...props\n}: React.ComponentProps<'div'> & {\n showCloseButton?: boolean\n}) {\n const { t } = useMessages()\n return (\n <div\n data-slot=\"dialog-footer\"\n className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close asChild>\n <Button variant=\"outline\">{t('إغلاق')}</Button>\n </DialogPrimitive.Close>\n )}\n </div>\n )\n}\n\nfunction DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {\n return (\n <DialogPrimitive.Title\n data-slot=\"dialog-title\"\n className={cn('text-lg leading-none font-semibold', className)}\n {...props}\n />\n )\n}\n\nfunction DialogDescription({\n className,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Description>) {\n return (\n <DialogPrimitive.Description\n data-slot=\"dialog-description\"\n className={cn('text-sm text-muted-foreground', className)}\n {...props}\n />\n )\n}\n\nexport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogOverlay,\n DialogPortal,\n DialogTitle,\n DialogTrigger,\n}\n",
|
|
12
|
+
"content": "import * as React from 'react'\nimport { cn } from 'cn'\nimport { XIcon } from 'lucide-react'\nimport { Dialog as DialogPrimitive } from 'radix-ui'\n\nimport { Button } from '~/components/ui/button'\nimport { useMessages } from '~/components/ui/messages'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\n\n/**\n * Clean close (ADR 016, decision 23 for 2.3.0): a dialog asks before closing only while\n * something differs from how it opened, and a value changed and restored is clean. The dialog\n * decides this itself; a dialog never computes its own dirty state.\n *\n * Two sources, one rule:\n * - Declared state. A dialog whose state is not plain controls (a draft object, a list order,\n * switches, an image) declares it with the `value` prop of `Dialog`, or with\n * `useDialogValue(value)` from a component inside the dialog. Each declaration is captured\n * as it renders until the user first interacts with the dialog (so values reset on opening\n * or loaded just after it are the starting point), then compared on closing.\n * - Plain controls. A dialog that declares nothing compares its inputs, text areas and\n * selects: the value each had before the user changed it against the value now.\n *\n * When a dialog declares state, the declarations are the whole truth for it and its controls\n * are not compared one by one, so a dialog that declares a value declares its full state. A\n * control that changed while no declaration did is reported once on the console.\n */\ntype Changes = { initial: Map<Element, string>; changed: Set<Element> }\ntype Declared = { opened: string; current: string; settled: boolean }\ntype DialogState = {\n content: React.RefObject<HTMLDivElement | null>\n changes: React.RefObject<Changes>\n declared: React.RefObject<Map<symbol, Declared>>\n mode: React.RefObject<'view' | 'edit' | 'confirm'>\n}\nconst DialogContentContext = React.createContext<DialogState | null>(null)\n\n/**\n * Which side the page's own scrollbar is on, as `data-root-scrollbar` on <html>. Locking page\n * scrolling hides that scrollbar and pads the body by its width (theme.css pads the measured\n * side). The direction does not decide it: Chromium keeps the page's scrollbar on the right in\n * a right-to-left page while an element's moves left, and Firefox moves both. Measured while\n * the scrollbar shows, again whenever the page's width changes (a scrollbar appearing).\n */\nfunction watchPageScrollbar() {\n if (typeof window === 'undefined' || typeof ResizeObserver === 'undefined') return\n const root = document.documentElement\n const measure = () => {\n const gap = window.innerWidth - root.clientWidth\n if (gap <= 0) return\n const side = root.getBoundingClientRect().left >= gap - 0.5 ? 'left' : 'right'\n if (root.dataset.rootScrollbar !== side) root.dataset.rootScrollbar = side\n }\n new ResizeObserver(measure).observe(root)\n measure()\n}\nwatchPageScrollbar()\n\nconst CONTROLS = 'input, textarea, select'\n\n/** A comparable value of a form control (checked state, selected options, files or text). */\nfunction controlValue(element: Element) {\n if (element instanceof HTMLInputElement) {\n if (element.type === 'checkbox' || element.type === 'radio') return String(element.checked)\n if (element.type === 'file')\n return [...(element.files ?? [])].map((file) => `${file.name}:${file.size}`).join('|')\n return element.value\n }\n if (element instanceof HTMLSelectElement)\n return [...element.selectedOptions].map((option) => option.value).join('|')\n if (element instanceof HTMLTextAreaElement) return element.value\n return ''\n}\n\n/** True for a form control the dialog compares when nothing is declared. */\nfunction isControl(element: Element) {\n return Boolean(element.matches?.(CONTROLS))\n}\n\n/**\n * Remembers a control's value before the user changes it. On mount every control is recorded;\n * taking focus records it again until it changes, so values loaded after opening count as the\n * starting point.\n */\nfunction remember(changes: Changes, element: Element, focus = false) {\n if (!isControl(element) || changes.changed.has(element)) return\n if (focus || !changes.initial.has(element)) changes.initial.set(element, controlValue(element))\n}\n\n/** A plain, ordered copy of a value: object keys sorted, files and dates as comparable data. */\nfunction normalize(value: unknown): unknown {\n if (typeof value === 'function' || typeof value === 'symbol') return undefined\n if (value === null || typeof value !== 'object') return value\n if (value instanceof Date) return value.toISOString()\n if (typeof File !== 'undefined' && value instanceof File)\n return { file: value.name, size: value.size, modified: value.lastModified }\n if (typeof Blob !== 'undefined' && value instanceof Blob)\n return { blob: value.type, size: value.size }\n if (value instanceof Map) return [...value.entries()].map(([key, item]) => [key, normalize(item)])\n if (value instanceof Set) return [...value].map((item) => normalize(item) ?? null)\n if (Array.isArray(value)) return value.map((item) => normalize(item) ?? null)\n const plain: Record<string, unknown> = {}\n for (const key of Object.keys(value).sort()) {\n const item = normalize((value as Record<string, unknown>)[key])\n if (item !== undefined) plain[key] = item\n }\n return plain\n}\n\n/** Stable text of a declared value: equal data gives equal text whatever the key order. */\nfunction serialize(value: unknown) {\n return JSON.stringify(normalize(value)) ?? ''\n}\n\nconst useIsomorphicLayoutEffect =\n typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect\n\n/** Records one declaration in a dialog while `active`; removes it when inactive or unmounted. */\nfunction useDeclaration(state: DialogState | null, value: unknown, active: boolean) {\n const [key] = React.useState(() => Symbol('dialog-value'))\n const text = active ? serialize(value) : ''\n useIsomorphicLayoutEffect(() => {\n const declared = state?.declared.current\n if (!declared) return\n if (!active) {\n declared.delete(key)\n return\n }\n const entry = declared.get(key)\n if (!entry) declared.set(key, { opened: text, current: text, settled: false })\n else {\n entry.current = text\n if (!entry.settled) entry.opened = text\n }\n })\n useIsomorphicLayoutEffect(() => () => void state?.declared.current.delete(key), [state, key])\n}\n\n/**\n * Declares state of the surrounding dialog that is not a plain control: the dialog compares it\n * on closing with how it was when the dialog opened. Outside a dialog it does nothing, so a\n * form shown both as a page and in a dialog can always call it.\n */\nfunction useDialogValue(value: unknown) {\n useDeclaration(React.useContext(DialogContentContext), value, true)\n}\n\n/**\n * `useDialogValue` as an element, for state that starts afresh within one opening: give it a\n * `key` that changes when a step is saved (an uploaded file becomes a mapping to review), and\n * the new step is compared with how it began. Place it inside the dialog's content.\n */\nfunction DialogValue({ value }: { value: unknown }) {\n useDialogValue(value)\n return null\n}\n\nfunction Dialog({\n mode,\n value,\n onOpenChange,\n children,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Root> & {\n mode?: 'view' | 'edit' | 'confirm'\n /** The dialog's editable state when it is not plain controls (see useDialogValue). */\n value?: unknown\n}) {\n const content = React.useRef<HTMLDivElement>(null)\n const changes = React.useRef<Changes>({ initial: new Map(), changed: new Set() })\n const declared = React.useRef(new Map<symbol, Declared>())\n const modeRef = React.useRef<'view' | 'edit' | 'confirm'>(mode ?? 'edit')\n modeRef.current = mode ?? 'edit'\n const state = React.useMemo(() => ({ content, changes, declared, mode: modeRef }), [])\n const [confirming, setConfirming] = React.useState(false)\n const [uncontrolledOpen, setUncontrolledOpen] = React.useState(props.defaultOpen ?? false)\n const preferences = useUiPreferences()\n const { t, dir } = useMessages()\n const open = props.open ?? uncontrolledOpen\n // The value prop is one more declaration, captured afresh at every opening.\n useDeclaration(state, value, open && value !== undefined)\n // Each opening starts clean (cleared on closing: the content records its values on mount).\n React.useEffect(() => {\n if (!open) changes.current = { initial: new Map(), changed: new Set() }\n }, [open])\n const commit = (next: boolean) => {\n setUncontrolledOpen(next)\n onOpenChange?.(next)\n }\n const request = (next: boolean) => {\n // Ask only when there are unsaved changes; an untouched dialog closes at once.\n const declarations = [...declared.current.values()]\n const { initial, changed } = changes.current\n const edited = [...changed].filter(\n (element) =>\n element.isConnected && isControl(element) && controlValue(element) !== initial.get(element)\n )\n const unsaved = declarations.length\n ? declarations.some((entry) => entry.current !== entry.opened)\n : edited.length > 0\n // A visible control changed but no declaration did: the dialog declared only part of its\n // state. (Hidden inputs mirror Radix switches, checkboxes and selects for form submission.)\n const undeclared = edited.filter((element) => !element.closest('[aria-hidden=\"true\"]'))\n if (declarations.length && !unsaved && undeclared.length)\n console.warn(\n '[Dialog] A control changed while every declared value is unchanged; declare the full form state with `value` or useDialogValue (ADR 016):',\n undeclared\n .map(\n (element) =>\n element.id ||\n element.getAttribute('name') ||\n element.getAttribute('aria-label') ||\n element.outerHTML.slice(0, 120)\n )\n .join(', ')\n )\n const editing = mode !== 'view' && mode !== 'confirm' && unsaved\n if (!next && editing && preferences.confirmDialogClose) setConfirming(true)\n else commit(next)\n }\n return (\n <DialogContentContext.Provider value={state}>\n <DialogPrimitive.Root data-slot=\"dialog\" {...props} open={open} onOpenChange={request}>\n {children}\n </DialogPrimitive.Root>\n {confirming && open && (\n <Dialog mode=\"confirm\" open onOpenChange={(next) => !next && setConfirming(false)}>\n <DialogContent showCloseButton={false} className=\"z-[70] sm:max-w-md\" dir={dir}>\n <DialogHeader>\n <DialogTitle>{t('إغلاق النموذج؟')}</DialogTitle>\n <DialogDescription>\n {t('قد تفقد التغييرات التي لم تحفظها. يمكنك متابعة التحرير أو إغلاق النموذج.')}\n </DialogDescription>\n </DialogHeader>\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" onClick={() => setConfirming(false)}>\n {t('متابعة التحرير')}\n </Button>\n <Button\n type=\"button\"\n variant=\"destructive\"\n onClick={() => {\n setConfirming(false)\n commit(false)\n }}\n >\n {t('إغلاق دون حفظ')}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )}\n </DialogContentContext.Provider>\n )\n}\n\nfunction DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {\n return <DialogPrimitive.Trigger data-slot=\"dialog-trigger\" {...props} />\n}\n\nfunction DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {\n return <DialogPrimitive.Portal data-slot=\"dialog-portal\" {...props} />\n}\n\nfunction DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {\n return <DialogPrimitive.Close data-slot=\"dialog-close\" {...props} />\n}\n\nfunction DialogOverlay({\n className,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {\n return (\n <DialogPrimitive.Overlay\n data-slot=\"dialog-overlay\"\n className={cn(\n 'fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0',\n className\n )}\n {...props}\n />\n )\n}\n\nfunction DialogContent({\n ref,\n className,\n children,\n showCloseButton = true,\n onInputCapture,\n onChangeCapture,\n onFocusCapture,\n onPointerDownCapture,\n onKeyDownCapture,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Content> & {\n showCloseButton?: boolean\n}) {\n const dialog = React.useContext(DialogContentContext)\n const content = dialog?.content\n const { t } = useMessages()\n // Controls: their values on mount, or when they take focus before a change, are the\n // baseline; a change marks them for comparison on closing.\n React.useEffect(() => {\n const node = content?.current\n if (!dialog || !node) return\n for (const element of node.querySelectorAll(CONTROLS)) remember(dialog.changes.current, element)\n }, [dialog, content])\n // The user's first interaction ends the opening: declared values are compared from here on.\n const settle = () => {\n for (const entry of dialog?.declared.current.values() ?? []) entry.settled = true\n }\n const touch = (target: EventTarget) => {\n settle()\n const element = target as Element\n if (dialog && isControl(element)) dialog.changes.current.changed.add(element)\n }\n return (\n <DialogPortal data-slot=\"dialog-portal\">\n <DialogOverlay />\n <DialogPrimitive.Content\n ref={(node) => {\n if (content) content.current = node\n if (typeof ref === 'function') return ref(node)\n if (ref) ref.current = node\n }}\n onFocusCapture={(event) => {\n if (dialog) remember(dialog.changes.current, event.target as Element, true)\n onFocusCapture?.(event)\n }}\n onInputCapture={(event) => {\n touch(event.target)\n onInputCapture?.(event)\n }}\n onChangeCapture={(event) => {\n touch(event.target)\n onChangeCapture?.(event)\n }}\n onPointerDownCapture={(event) => {\n settle()\n onPointerDownCapture?.(event)\n }}\n onKeyDownCapture={(event) => {\n settle()\n onKeyDownCapture?.(event)\n }}\n data-slot=\"dialog-content\"\n // Tools and tests tell a confirmation from an editor or a details view by this.\n data-dialog-mode={dialog?.mode.current ?? 'edit'}\n className={cn(\n 'fixed top-[50%] start-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] ltr:translate-x-[-50%] rtl:-translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg',\n className\n )}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close\n data-slot=\"dialog-close\"\n className=\"absolute top-4 end-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\"\n >\n <XIcon />\n <span className=\"sr-only\">{t('إغلاق')}</span>\n </DialogPrimitive.Close>\n )}\n </DialogPrimitive.Content>\n </DialogPortal>\n )\n}\n\nfunction DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"dialog-header\"\n className={cn('flex flex-col gap-2 text-center sm:text-start', className)}\n {...props}\n />\n )\n}\n\nfunction DialogFooter({\n className,\n showCloseButton = false,\n children,\n ...props\n}: React.ComponentProps<'div'> & {\n showCloseButton?: boolean\n}) {\n const { t } = useMessages()\n return (\n <div\n data-slot=\"dialog-footer\"\n className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close asChild>\n <Button variant=\"outline\">{t('إغلاق')}</Button>\n </DialogPrimitive.Close>\n )}\n </div>\n )\n}\n\nfunction DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {\n return (\n <DialogPrimitive.Title\n data-slot=\"dialog-title\"\n className={cn('text-lg leading-none font-semibold', className)}\n {...props}\n />\n )\n}\n\nfunction DialogDescription({\n className,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Description>) {\n return (\n <DialogPrimitive.Description\n data-slot=\"dialog-description\"\n className={cn('text-sm text-muted-foreground', className)}\n {...props}\n />\n )\n}\n\nexport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogOverlay,\n DialogPortal,\n DialogTitle,\n DialogTrigger,\n DialogValue,\n useDialogValue,\n}\n",
|
|
13
13
|
"target": "inertia/components/ui/dialog.tsx"
|
|
14
14
|
}
|
|
15
15
|
],
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "file-input",
|
|
3
|
+
"type": "registry:ui",
|
|
4
|
+
"registryDependencies": [
|
|
5
|
+
"button",
|
|
6
|
+
"messages"
|
|
7
|
+
],
|
|
8
|
+
"dependencies": [
|
|
9
|
+
"cn@0.3.0",
|
|
10
|
+
"lucide-react@1.47.0"
|
|
11
|
+
],
|
|
12
|
+
"files": [
|
|
13
|
+
{
|
|
14
|
+
"path": "registry/ui/file-input.tsx",
|
|
15
|
+
"type": "registry:ui",
|
|
16
|
+
"content": "import * as React from \"react\";\nimport { FileUp } from \"lucide-react\";\nimport { cn } from \"cn\";\nimport { Button } from \"~/components/ui/button\";\nimport { useMessages } from \"~/components/ui/messages\";\n\ntype FileInputProps = Omit<\n React.ComponentProps<\"input\">,\n \"type\" | \"value\" | \"onChange\"\n> & {\n id: string;\n /** The id of the field's label, read with the button so keyboard users hear the field name. */\n labelId?: string;\n /** Called with the chosen files; an empty list when the choice is cleared. */\n onFilesChange?: (files: File[]) => void;\n};\n\n/**\n * A file field in the interface language: a button that opens the file picker and the name of\n * the chosen file, instead of the browser's native control and its untranslated text. The native\n * input stays in the document, hidden, so a `<Label htmlFor={id}>` still names it and forms and\n * tests can set its files; keyboard users reach the button, which `labelId` describes.\n */\nfunction FileInput({\n id,\n labelId,\n className,\n disabled,\n multiple,\n onFilesChange,\n \"aria-describedby\": describedBy,\n ...props\n}: FileInputProps) {\n const { t } = useMessages();\n const input = React.useRef<HTMLInputElement>(null);\n const [names, setNames] = React.useState<string[]>([]);\n const chosen = names.length ? names.join(\"، \") : t(\"لم يُختر أي ملف\");\n return (\n <div\n data-slot=\"file-input\"\n className={cn(\n \"flex h-9 w-full min-w-0 items-center gap-2 rounded-md border border-input bg-transparent ps-1 pe-3 shadow-xs dark:bg-input/30\",\n disabled && \"cursor-not-allowed opacity-50\",\n className,\n )}\n >\n <input\n {...props}\n ref={input}\n id={id}\n type=\"file\"\n multiple={multiple}\n disabled={disabled}\n hidden\n onChange={(event) => {\n const files = [...(event.target.files ?? [])];\n setNames(files.map((file) => file.name));\n onFilesChange?.(files);\n }}\n />\n <Button\n type=\"button\"\n variant=\"secondary\"\n size=\"sm\"\n disabled={disabled}\n aria-describedby={[labelId, `${id}-chosen`, describedBy]\n .filter(Boolean)\n .join(\" \")}\n onClick={() => input.current?.click()}\n >\n <FileUp size={14} aria-hidden=\"true\" />\n {names.length ? t(\"تغيير الملف\") : t(\"اختيار ملف\")}\n </Button>\n <span\n id={`${id}-chosen`}\n data-slot=\"file-input-name\"\n aria-live=\"polite\"\n className={cn(\n \"min-w-0 truncate text-sm\",\n names.length ? \"text-foreground\" : \"text-muted-foreground\",\n )}\n title={names.join(\"، \") || undefined}\n >\n {chosen}\n </span>\n </div>\n );\n}\n\nexport { FileInput };\n",
|
|
17
|
+
"target": "inertia/components/ui/file-input.tsx"
|
|
18
|
+
}
|
|
19
|
+
],
|
|
20
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
21
|
+
}
|