@adula/ui 2.1.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -3
- package/build/attachment-preview.json +21 -0
- package/build/breadcrumb.json +18 -0
- package/build/calendar.json +1 -1
- package/build/checkbox.json +1 -1
- package/build/command.json +1 -1
- package/build/confirm-action.json +3 -2
- package/build/copy-button.json +21 -0
- package/build/data-table.json +8 -2
- package/build/dialog-param.json +17 -0
- package/build/dialog.json +3 -2
- package/build/dropdown-menu.json +1 -1
- package/build/file-input.json +21 -0
- package/build/form.json +1 -1
- package/build/hijri-calendar.json +1 -1
- package/build/label.json +1 -1
- package/build/list-filters.json +34 -0
- package/build/long-dialog.json +17 -0
- package/build/manifest.json +146 -76
- package/build/messages.json +21 -0
- package/build/pagination.json +3 -2
- package/build/popover.json +1 -1
- package/build/radio-group.json +1 -1
- package/build/record-assignments.json +3 -2
- package/build/record-collaboration.json +4 -2
- package/build/record-print.json +24 -0
- package/build/record-workflows.json +3 -2
- package/build/resource-actions.json +3 -2
- package/build/resource-bulk.json +27 -0
- package/build/resource-dashboard.json +27 -0
- package/build/resource-field.json +7 -2
- package/build/resource-form.json +4 -2
- package/build/resource-import.json +7 -3
- package/build/resource-page.json +4 -2
- package/build/resource-show.json +6 -2
- package/build/resource-surface.json +4 -2
- package/build/resource-value.json +11 -2
- package/build/select.json +1 -1
- package/build/separator.json +1 -1
- package/build/sheet.json +1 -1
- package/build/slider.json +17 -0
- package/build/sonner.json +1 -1
- package/build/sortable-list.json +20 -0
- package/build/switch.json +1 -1
- package/build/table.json +1 -1
- package/build/tabs.json +1 -1
- package/build/theme.css +48 -2
- package/build/tooltip.json +1 -1
- package/build/user-avatar.json +17 -0
- package/package.json +5 -2
package/README.md
CHANGED
|
@@ -1,12 +1,22 @@
|
|
|
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
|
|
|
7
7
|
The 25 primitives are based on the official shadcn new-york-v4 registry. See LICENSE.shadcn.md and UPSTREAM.json for attribution and source hashes. Adaptations include logical spacing, Arabic labels, RTL keyboard direction, Arabic calendar defaults, RTL notifications and switch movement. Visual acceptance of the application remains a separate check.
|
|
8
8
|
|
|
9
|
-
Build with `pnpm --filter @adula/ui build`.
|
|
9
|
+
Build with `pnpm --filter @adula/ui build`. `registry/ui` is the single source of copied UI in this repository: `scripts/ui-registry.mjs` maintains it with one subcommand per step.
|
|
10
|
+
|
|
11
|
+
| Command | Effect |
|
|
12
|
+
|---|---|
|
|
13
|
+
| `node scripts/ui-registry.mjs sync` | Fetches the upstream new-york-v4 primitives, `UPSTREAM.json` and the shadcn license (network; explicit maintenance). |
|
|
14
|
+
| `node scripts/ui-registry.mjs prepare` | Adapts sources for Arabic RTL and refreshes the pinned versions in `dependencies.json` and `registry.json` (npm). `--sources-only` skips npm. |
|
|
15
|
+
| `node scripts/ui-registry.mjs register` | Registers the AdulaJS resource components in `registry.json`. |
|
|
16
|
+
| `node scripts/ui-registry.mjs build` | Writes `build/` (what `pnpm --filter @adula/ui build` runs). |
|
|
17
|
+
| `node scripts/ui-registry.mjs reference` | Regenerates the reference application's `inertia/components/ui` and `ui.lock.json`. Both are untracked; the root `build`, `dev`, `typecheck` and `test` scripts run it first. Never edit the generated copy; change `registry/ui` instead. Because the directory is gitignored, `apps/reference/inertia/css/adula.css` registers it with `@source "../components/ui"`; Tailwind 4 skips ignored paths otherwise. |
|
|
18
|
+
|
|
19
|
+
Refreshing upstream sources: run `sync`, review the changes, run `prepare`, then build and visually test. `prepare` is idempotent. Its last step is the direction transform that `shadcn add` itself applies when `components.json` sets `"rtl": true`, so the stored file is what an application installs, byte for byte. Two rules keep it a fixed point of that transform. First, every horizontal translate is stored as an explicit `ltr:`/`rtl:` pair, because shadcn appends a second `rtl:` class to a plain one on every install. The pairing covers only the `translate-x-*` family, with any variants. Any other class the transform keeps appending to, such as `space-x-*` (it re-adds `rtl:space-x-reverse`), fails the drift gate and needs a reviewed source edit. Second, no file keeps a `"use client"` directive. Applications use `"rsc": false`, and Inertia does not use it. shadcn 4.21.0 strips the directive inconsistently: its global regular expression keeps `lastIndex` between files, so only every other file in a multi-file install loses it. `pnpm --filter @adula/ui test` fails when a registry file is not prepared, when installing it would change it, or when the generated reference copy differs from the registry.
|
|
10
20
|
|
|
11
21
|
Required host tooling: Node 24, React 19, shadcn 4.21.0, Tailwind CSS 4.3.3 and @tailwindcss/vite 4.3.3. AdulaJS installer supports the official AdonisJS React starter layout. The registry is unpublished until explicitly authorized.
|
|
12
22
|
|
|
@@ -16,7 +26,7 @@ Components merge `className` with `cn` (shadcn's clsx + tailwind-merge replaceme
|
|
|
16
26
|
|
|
17
27
|
## Resource components
|
|
18
28
|
|
|
19
|
-
Nine AdulaJS components sit on top of the primitives and are registered by `scripts/
|
|
29
|
+
Nine AdulaJS components sit on top of the primitives and are registered by `node scripts/ui-registry.mjs register`. They consume the `ResourceDescription`, `ResourceList`, `ResourceEditor`, `ResourceShow`, `ResourceChildren`, `ResourceLookups` and `ResourceActivity` contracts exported by `adula`; the copied files are project-owned like every other registry item.
|
|
20
30
|
|
|
21
31
|
| Component | Role |
|
|
22
32
|
|---|---|
|
|
@@ -29,6 +39,7 @@ Nine AdulaJS components sit on top of the primitives and are registered by `scri
|
|
|
29
39
|
| `resource-show` | Field cards, status badge, actions by permission, deferred `childrenData` tables described by `childResources`, and the deferred `activity` list, each behind a skeleton. |
|
|
30
40
|
| `resource-actions` | Confirmation dialog and versioned `DELETE`/`submit`/`cancel` requests shared by the table and the show page. |
|
|
31
41
|
| `can` | Renders children only when the server-computed record permission allows the action. |
|
|
42
|
+
| `messages` | `useMessages()` returns `{ t, label, locale, dir }` from the shared `locale`, `dir` and `messages` props. Arabic is the base language: `t('نص عربي', { name })` returns the translation of that exact Arabic text or the text itself, filling `{name}` placeholders; `label(field.label)` returns `label.<locale>` or `label.ar`. Without the shared props every component renders Arabic. Helpers outside components (`failureMessage`, `documentStatus`, `displayValue`, `fileSize`) take an optional `t`. |
|
|
32
43
|
|
|
33
44
|
Override rule: a page file at `inertia/pages/<resource>/{index,form,show}.tsx` replaces the generic page for that resource and mode; there is no setting or hook. See docs/decisions/015-generic-resource-ui.md.
|
|
34
45
|
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "attachment-preview",
|
|
3
|
+
"type": "registry:ui",
|
|
4
|
+
"registryDependencies": [
|
|
5
|
+
"button",
|
|
6
|
+
"dialog",
|
|
7
|
+
"messages"
|
|
8
|
+
],
|
|
9
|
+
"dependencies": [
|
|
10
|
+
"lucide-react@1.47.0"
|
|
11
|
+
],
|
|
12
|
+
"files": [
|
|
13
|
+
{
|
|
14
|
+
"path": "registry/ui/attachment-preview.tsx",
|
|
15
|
+
"type": "registry:ui",
|
|
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
|
+
"target": "inertia/components/ui/attachment-preview.tsx"
|
|
18
|
+
}
|
|
19
|
+
],
|
|
20
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
21
|
+
}
|
|
@@ -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
|
+
}
|
package/build/calendar.json
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
{
|
|
14
14
|
"path": "registry/ui/calendar.tsx",
|
|
15
15
|
"type": "registry:ui",
|
|
16
|
-
"content": "
|
|
16
|
+
"content": "import { ar } from 'react-day-picker/locale'\n\nimport * as React from \"react\"\nimport { cn } from \"cn\"\nimport {\n ChevronDownIcon,\n ChevronLeftIcon,\n ChevronRightIcon,\n} from \"lucide-react\"\nimport {\n DayPicker,\n getDefaultClassNames,\n type DayButton,\n} from \"react-day-picker\"\n\nimport { Button, buttonVariants } from \"~/components/ui/button\"\n\nfunction Calendar({\n className,\n classNames,\n showOutsideDays = true,\n captionLayout = \"label\",\n buttonVariant = \"ghost\",\n formatters,\n components,\n ...props\n}: React.ComponentProps<typeof DayPicker> & {\n buttonVariant?: React.ComponentProps<typeof Button>[\"variant\"]\n}) {\n const defaultClassNames = getDefaultClassNames()\n\n return (\n <DayPicker\n dir=\"rtl\"\n locale={ar}\n showOutsideDays={showOutsideDays}\n className={cn(\n \"group/calendar bg-background p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent\",\n String.raw`rtl:**:[.rdp-button\\_next>svg]:rotate-180`,\n String.raw`rtl:**:[.rdp-button\\_previous>svg]:rotate-180`,\n className\n )}\n captionLayout={captionLayout}\n formatters={{\n formatMonthDropdown: (date) =>\n date.toLocaleString(\"ar\", { month: \"short\" }),\n ...formatters,\n }}\n classNames={{\n root: cn(\"w-fit\", defaultClassNames.root),\n months: cn(\n \"relative flex flex-col gap-4 md:flex-row\",\n defaultClassNames.months\n ),\n month: cn(\"flex w-full flex-col gap-4\", defaultClassNames.month),\n nav: cn(\n \"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1\",\n defaultClassNames.nav\n ),\n button_previous: cn(\n buttonVariants({ variant: buttonVariant }),\n \"size-(--cell-size) p-0 select-none aria-disabled:opacity-50\",\n defaultClassNames.button_previous\n ),\n button_next: cn(\n buttonVariants({ variant: buttonVariant }),\n \"size-(--cell-size) p-0 select-none aria-disabled:opacity-50\",\n defaultClassNames.button_next\n ),\n month_caption: cn(\n \"flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)\",\n defaultClassNames.month_caption\n ),\n dropdowns: cn(\n \"flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium\",\n defaultClassNames.dropdowns\n ),\n dropdown_root: cn(\n \"relative rounded-md border border-input shadow-xs has-focus:border-ring has-focus:ring-[3px] has-focus:ring-ring/50\",\n defaultClassNames.dropdown_root\n ),\n dropdown: cn(\n \"absolute inset-0 bg-popover opacity-0\",\n defaultClassNames.dropdown\n ),\n caption_label: cn(\n \"font-medium select-none\",\n captionLayout === \"label\"\n ? \"text-sm\"\n : \"flex h-8 items-center gap-1 rounded-md pe-1 ps-2 text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground\",\n defaultClassNames.caption_label\n ),\n month_grid: cn(\"w-full border-collapse\", defaultClassNames.month_grid),\n weekdays: cn(\"flex\", defaultClassNames.weekdays),\n weekday: cn(\n \"flex-1 rounded-md text-[0.8rem] font-normal text-muted-foreground select-none\",\n defaultClassNames.weekday\n ),\n week: cn(\"mt-2 flex w-full\", defaultClassNames.week),\n week_number_header: cn(\n \"w-(--cell-size) select-none\",\n defaultClassNames.week_number_header\n ),\n week_number: cn(\n \"text-[0.8rem] text-muted-foreground select-none\",\n defaultClassNames.week_number\n ),\n day: cn(\n \"group/day relative aspect-square h-full w-full p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-e-md\",\n props.showWeekNumber\n ? \"[&:nth-child(2)[data-selected=true]_button]:rounded-s-md\"\n : \"[&:first-child[data-selected=true]_button]:rounded-s-md\",\n defaultClassNames.day\n ),\n range_start: cn(\n \"rounded-s-md bg-accent\",\n defaultClassNames.range_start\n ),\n range_middle: cn(\"rounded-none\", defaultClassNames.range_middle),\n range_end: cn(\"rounded-e-md bg-accent\", defaultClassNames.range_end),\n today: cn(\n \"rounded-md bg-accent text-accent-foreground data-[selected=true]:rounded-none\",\n defaultClassNames.today\n ),\n outside: cn(\n \"text-muted-foreground aria-selected:text-muted-foreground\",\n defaultClassNames.outside\n ),\n disabled: cn(\n \"text-muted-foreground opacity-50\",\n defaultClassNames.disabled\n ),\n hidden: cn(\"invisible\", defaultClassNames.hidden),\n ...classNames,\n }}\n components={{\n Root: ({ className, rootRef, ...props }) => {\n return (\n <div\n data-slot=\"calendar\"\n ref={rootRef}\n className={cn(className)}\n {...props}\n />\n )\n },\n Chevron: ({ className, orientation, ...props }) => {\n if (orientation === \"left\") {\n return (\n <ChevronLeftIcon className={cn(\"size-4\", className)} {...props} />\n )\n }\n\n if (orientation === \"right\") {\n return (\n <ChevronRightIcon\n className={cn(\"size-4\", className)}\n {...props}\n />\n )\n }\n\n return (\n <ChevronDownIcon className={cn(\"size-4\", className)} {...props} />\n )\n },\n DayButton: CalendarDayButton,\n WeekNumber: ({ children, ...props }) => {\n return (\n <td {...props}>\n <div className=\"flex size-(--cell-size) items-center justify-center text-center\">\n {children}\n </div>\n </td>\n )\n },\n ...components,\n }}\n {...props}\n />\n )\n}\n\nfunction CalendarDayButton({\n className,\n day,\n modifiers,\n ...props\n}: React.ComponentProps<typeof DayButton>) {\n const defaultClassNames = getDefaultClassNames()\n\n const ref = React.useRef<HTMLButtonElement>(null)\n React.useEffect(() => {\n if (modifiers.focused) ref.current?.focus()\n }, [modifiers.focused])\n\n return (\n <Button\n ref={ref}\n variant=\"ghost\"\n size=\"icon\"\n data-day={day.date.toLocaleDateString()}\n data-selected-single={\n modifiers.selected &&\n !modifiers.range_start &&\n !modifiers.range_end &&\n !modifiers.range_middle\n }\n data-range-start={modifiers.range_start}\n data-range-end={modifiers.range_end}\n data-range-middle={modifiers.range_middle}\n className={cn(\n \"flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-md data-[range-end=true]:rounded-e-md data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:rounded-md data-[range-start=true]:rounded-s-md data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-accent-foreground [&>span]:text-xs [&>span]:opacity-70\",\n defaultClassNames.day,\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Calendar, CalendarDayButton }\n",
|
|
17
17
|
"target": "inertia/components/ui/calendar.tsx"
|
|
18
18
|
}
|
|
19
19
|
],
|
package/build/checkbox.json
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
{
|
|
10
10
|
"path": "registry/ui/checkbox.tsx",
|
|
11
11
|
"type": "registry:ui",
|
|
12
|
-
"content": "
|
|
12
|
+
"content": "import * as React from \"react\"\nimport { cn } from \"cn\"\nimport { CheckIcon } from \"lucide-react\"\nimport { Checkbox as CheckboxPrimitive } from \"radix-ui\"\n\nfunction Checkbox({\n className,\n ...props\n}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {\n return (\n <CheckboxPrimitive.Root\n data-slot=\"checkbox\"\n className={cn(\n \"peer size-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:data-[state=checked]:bg-primary\",\n className\n )}\n {...props}\n >\n <CheckboxPrimitive.Indicator\n data-slot=\"checkbox-indicator\"\n className=\"grid place-content-center text-current transition-none\"\n >\n <CheckIcon className=\"size-3.5\" />\n </CheckboxPrimitive.Indicator>\n </CheckboxPrimitive.Root>\n )\n}\n\nexport { Checkbox }\n",
|
|
13
13
|
"target": "inertia/components/ui/checkbox.tsx"
|
|
14
14
|
}
|
|
15
15
|
],
|
package/build/command.json
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
{
|
|
13
13
|
"path": "registry/ui/command.tsx",
|
|
14
14
|
"type": "registry:ui",
|
|
15
|
-
"content": "
|
|
15
|
+
"content": "import * as React from \"react\"\nimport { Command as CommandPrimitive } from \"cmdk\"\nimport { cn } from \"cn\"\nimport { SearchIcon } from \"lucide-react\"\n\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n} from \"~/components/ui/dialog\"\n\nfunction Command({\n className,\n ...props\n}: React.ComponentProps<typeof CommandPrimitive>) {\n return (\n <CommandPrimitive\n data-slot=\"command\"\n className={cn(\n \"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CommandDialog({\n title = \"قائمة الأوامر\",\n description = \"ابحث عن أمر لتنفيذه\",\n children,\n className,\n showCloseButton = true,\n ...props\n}: React.ComponentProps<typeof Dialog> & {\n title?: string\n description?: string\n className?: string\n showCloseButton?: boolean\n}) {\n return (\n <Dialog {...props}>\n <DialogHeader className=\"sr-only\">\n <DialogTitle>{title}</DialogTitle>\n <DialogDescription>{description}</DialogDescription>\n </DialogHeader>\n <DialogContent\n className={cn(\"overflow-hidden p-0\", className)}\n showCloseButton={showCloseButton}\n >\n <Command className=\"**:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5\">\n {children}\n </Command>\n </DialogContent>\n </Dialog>\n )\n}\n\nfunction CommandInput({\n className,\n ...props\n}: React.ComponentProps<typeof CommandPrimitive.Input>) {\n return (\n <div\n data-slot=\"command-input-wrapper\"\n className=\"flex h-9 items-center gap-2 border-b px-3\"\n >\n <SearchIcon className=\"size-4 shrink-0 opacity-50\" />\n <CommandPrimitive.Input\n data-slot=\"command-input\"\n className={cn(\n \"flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50\",\n className\n )}\n {...props}\n />\n </div>\n )\n}\n\nfunction CommandList({\n className,\n ...props\n}: React.ComponentProps<typeof CommandPrimitive.List>) {\n return (\n <CommandPrimitive.List\n data-slot=\"command-list\"\n className={cn(\n \"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CommandEmpty({\n ...props\n}: React.ComponentProps<typeof CommandPrimitive.Empty>) {\n return (\n <CommandPrimitive.Empty\n data-slot=\"command-empty\"\n className=\"py-6 text-center text-sm\"\n {...props}\n />\n )\n}\n\nfunction CommandGroup({\n className,\n ...props\n}: React.ComponentProps<typeof CommandPrimitive.Group>) {\n return (\n <CommandPrimitive.Group\n data-slot=\"command-group\"\n className={cn(\n \"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CommandSeparator({\n className,\n ...props\n}: React.ComponentProps<typeof CommandPrimitive.Separator>) {\n return (\n <CommandPrimitive.Separator\n data-slot=\"command-separator\"\n className={cn(\"-mx-1 h-px bg-border\", className)}\n {...props}\n />\n )\n}\n\nfunction CommandItem({\n className,\n ...props\n}: React.ComponentProps<typeof CommandPrimitive.Item>) {\n return (\n <CommandPrimitive.Item\n data-slot=\"command-item\"\n className={cn(\n \"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CommandShortcut({\n className,\n ...props\n}: React.ComponentProps<\"span\">) {\n return (\n <span\n data-slot=\"command-shortcut\"\n className={cn(\n \"ms-auto text-xs tracking-widest text-muted-foreground\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport {\n Command,\n CommandDialog,\n CommandInput,\n CommandList,\n CommandEmpty,\n CommandGroup,\n CommandItem,\n CommandShortcut,\n CommandSeparator,\n}\n",
|
|
16
16
|
"target": "inertia/components/ui/command.tsx"
|
|
17
17
|
}
|
|
18
18
|
],
|
|
@@ -3,14 +3,15 @@
|
|
|
3
3
|
"type": "registry:ui",
|
|
4
4
|
"registryDependencies": [
|
|
5
5
|
"dialog",
|
|
6
|
-
"button"
|
|
6
|
+
"button",
|
|
7
|
+
"messages"
|
|
7
8
|
],
|
|
8
9
|
"dependencies": [],
|
|
9
10
|
"files": [
|
|
10
11
|
{
|
|
11
12
|
"path": "registry/ui/confirm-action.tsx",
|
|
12
13
|
"type": "registry:ui",
|
|
13
|
-
"content": "import { useState } from 'react'\nimport { Button } from '~/components/ui/button'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from '~/components/ui/dialog'\n\ntype Confirmation = {\n title: string\n description: string\n action: () => void\n destructive?: boolean\n label?: string\n}\n\n/** Keep confirmation separate from editor state; cancel never sends a mutation. */\nexport function useConfirmAction() {\n const [pending, confirm] = useState<Confirmation | null>(null)\n return {\n confirm,\n confirmation: (\n <Dialog\n mode=\"confirm\"\n open={Boolean(pending)}\n onOpenChange={(open) => !open && confirm(null)}\n >\n <DialogContent dir
|
|
14
|
+
"content": "import { useState } from 'react'\nimport { Button } from '~/components/ui/button'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from '~/components/ui/dialog'\nimport { useMessages } from '~/components/ui/messages'\n\ntype Confirmation = {\n title: string\n description: string\n action: () => void\n destructive?: boolean\n label?: string\n}\n\n/** Keep confirmation separate from editor state; cancel never sends a mutation. */\nexport function useConfirmAction() {\n const { t, dir } = useMessages()\n const [pending, confirm] = useState<Confirmation | null>(null)\n return {\n confirm,\n confirmation: (\n <Dialog\n mode=\"confirm\"\n open={Boolean(pending)}\n onOpenChange={(open) => !open && confirm(null)}\n >\n <DialogContent dir={dir} className=\"sm:max-w-md\">\n <DialogHeader>\n <DialogTitle>{pending?.title ?? t('تأكيد الإجراء')}</DialogTitle>\n <DialogDescription>{pending?.description}</DialogDescription>\n </DialogHeader>\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" onClick={() => confirm(null)}>\n {t('تراجع')}\n </Button>\n <Button\n type=\"button\"\n variant={pending?.destructive ? 'destructive' : 'default'}\n onClick={() => {\n const action = pending?.action\n confirm(null)\n action?.()\n }}\n >\n {pending?.label ?? t('تأكيد التغيير')}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n ),\n }\n}\n",
|
|
14
15
|
"target": "inertia/components/ui/confirm-action.tsx"
|
|
15
16
|
}
|
|
16
17
|
],
|
|
@@ -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
|
@@ -12,7 +12,13 @@
|
|
|
12
12
|
"ui-preferences",
|
|
13
13
|
"command",
|
|
14
14
|
"popover",
|
|
15
|
-
"resource-surface"
|
|
15
|
+
"resource-surface",
|
|
16
|
+
"messages",
|
|
17
|
+
"alert",
|
|
18
|
+
"checkbox",
|
|
19
|
+
"list-filters",
|
|
20
|
+
"resource-bulk",
|
|
21
|
+
"user-avatar"
|
|
16
22
|
],
|
|
17
23
|
"dependencies": [
|
|
18
24
|
"@tanstack/react-table@9.2.4",
|
|
@@ -24,7 +30,7 @@
|
|
|
24
30
|
{
|
|
25
31
|
"path": "registry/ui/data-table.tsx",
|
|
26
32
|
"type": "registry:ui",
|
|
27
|
-
"content": "import {\n useEffect,\n useId,\n useRef,\n useState,\n type ComponentRef,\n type MouseEvent,\n type ReactNode,\n} 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 Check,\n ChevronsUpDown,\n Download,\n Inbox,\n Loader2,\n Bookmark,\n BookmarkPlus,\n Search,\n SlidersHorizontal,\n X,\n} from 'lucide-react'\nimport type {\n ResourceDescription,\n ResourceField,\n ResourceList,\n SavedView,\n SavedViewQuery,\n SerializedRecord,\n} from 'adula'\nimport { Badge } from '~/components/ui/badge'\nimport { Button } from '~/components/ui/button'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\nimport { Can } from '~/components/ui/can'\nimport { Input } from '~/components/ui/input'\nimport { ResourceActions } from '~/components/ui/resource-actions'\nimport { openRecord, rememberListView } from '~/components/ui/resource-surface'\nimport { FieldControl, ResourceSelect } from '~/components/ui/resource-field'\nimport {\n Command,\n CommandEmpty,\n CommandGroup,\n CommandInput,\n CommandItem,\n CommandList,\n} from '~/components/ui/command'\nimport { Popover, PopoverContent, PopoverTrigger } from '~/components/ui/popover'\nimport {\n csvCell,\n displayValue,\n parseValue,\n relationLabel,\n type LookupOptions,\n type Option,\n} from '~/components/ui/resource-value'\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({})\ntype Query = Record<string, string | undefined>\n\nexport function DataTable({\n resource,\n result,\n lookups = {},\n savedViews = [],\n}: {\n resource: ResourceDescription\n result: ResourceList\n lookups?: LookupOptions\n savedViews?: SavedView[]\n}) {\n const { calendar } = useUiPreferences()\n const { url } = usePage()\n const query = new URL(url, 'http://localhost').searchParams\n const [search, setSearch] = useState(query.get('search') ?? '')\n const [failure, setFailure] = useState('')\n const container = useRef<HTMLDivElement>(null)\n const scroller = useRef<ComponentRef<typeof InfiniteScroll>>(null)\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 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 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 navigate = (changes: Query) => {\n const next = new URLSearchParams(query)\n next.delete('cursor')\n for (const [key, value] of Object.entries(changes))\n value ? next.set(key, value) : next.delete(key)\n const suffix = next.toString()\n router.get(\n `/resources/${resource.name}${suffix ? `?${suffix}` : ''}`,\n {},\n { preserveScroll: true }\n )\n }\n const sort = query.get('sort')\n const direction = query.get('direction') === 'desc' ? 'desc' : 'asc'\n const activeFilters = filterable.filter((field) => query.get(`filters[${field.key}]`))\n const csv = () => {\n const content = [\n fields.map((field) => field.label.ar),\n ...result.data.map((row) =>\n fields.map((field) => displayValue(field, row, related, lookups, calendar))\n ),\n ]\n const href = URL.createObjectURL(\n new Blob(['' + content.map((row) => row.map(csvCell).join(',')).join('\\r\\n')], {\n type: 'text/csv;charset=utf-8',\n })\n )\n const link = document.createElement('a')\n link.href = href\n link.download = `${resource.label}.csv`\n link.click()\n URL.revokeObjectURL(href)\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 filters: Record<string, string> = {}\n for (const field of filterable) {\n const value = query.get(`filters[${field.key}]`)\n if (value) filters[field.key] = value\n }\n if (Object.keys(filters).length) view.filters = 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 if (value !== null) next.set(`filters[${key}]`, String(value))\n setSearch(view.query.search ?? '')\n const suffix = next.toString()\n router.get(\n `/resources/${resource.name}${suffix ? `?${suffix}` : ''}`,\n {},\n { preserveScroll: true }\n )\n }\n return (\n <section\n aria-label={`قائمة ${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\">سجل {resource.label}</h2>\n <Badge variant=\"secondary\" className=\"font-normal tabular-nums\">\n {rows.length} معروض\n </Badge>\n <span className=\"text-xs text-muted-foreground\">\n {result.meta.estimatedTotal !== undefined\n ? `نحو ${result.meta.estimatedTotal} سجل ضمن نطاقك`\n : 'حسب نطاق صلاحياتك'}\n </span>\n </div>\n <Button variant=\"outline\" size=\"sm\" onClick={csv} disabled={!rows.length}>\n <Download size={15} />\n تصدير المعروض\n </Button>\n </div>\n {(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=\"flex flex-wrap items-end gap-3 border-b px-5 py-4\">\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={`البحث في ${resource.label}`}\n value={search}\n onChange={(event) => setSearch(event.target.value)}\n placeholder=\"ابحث في السجلات...\"\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 تصفية\n </span>\n )}\n {filterable.map((field) => (\n <Filter\n key={field.key}\n resource={resource.name}\n field={field}\n value={query.get(`filters[${field.key}]`) ?? ''}\n options={lookups[field.key]}\n related={related[field.key]}\n onApply={(value) => navigate({ [`filters[${field.key}]`]: value })}\n />\n ))}\n {activeFilters.length > 0 && (\n <Button\n variant=\"ghost\"\n size=\"sm\"\n onClick={() =>\n navigate(\n Object.fromEntries(\n activeFilters.map((field) => [`filters[${field.key}]`, undefined])\n )\n )\n }\n >\n <X size={14} />\n مسح التصفية\n </Button>\n )}\n </div>\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('تعذر تحميل السجلات التالية. أعد المحاولة.')\n return false\n },\n onNetworkError: () => {\n setFailure('تعذر الاتصال بالخادم. تحقق من الاتصال ثم أعد المحاولة.')\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 جارٍ تحميل المزيد...\n </span>\n ) : hasMore ? (\n <Button variant=\"ghost\" size=\"sm\" onClick={fetch}>\n تحميل المزيد\n </Button>\n ) : (\n <span>{rows.length ? 'نهاية السجلات' : ''}</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 {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 {field.label.ar}\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 field.label.ar\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 الإجراءات\n </th>\n </tr>\n </thead>\n <tbody>\n {virtualized && items[0] && items[0].start > 0 && (\n <tr aria-hidden=\"true\">\n <td colSpan={fields.length + 1} 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 return (\n <tr\n key={id}\n aria-rowindex={index + 2}\n className=\"group border-b last:border-0 hover:bg-background\"\n style={{ height: ROW_HEIGHT }}\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 <Button variant=\"ghost\" size=\"sm\" asChild>\n <Link\n href={`/resources/${resource.name}/${id}`}\n aria-label={`عرض السجل ${id}`}\n onClick={(event) => overlay(event, id, 'show')}\n >\n عرض\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={`تعديل السجل ${id}`}\n onClick={(event) => overlay(event, id, 'edit')}\n >\n تعديل\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={`السجل ${id}`}\n size=\"sm\"\n variant=\"ghost\"\n onDone={refresh}\n />\n </span>\n </td>\n </tr>\n )\n })}\n {virtualized && (\n <tr aria-hidden=\"true\">\n <td\n colSpan={fields.length + 1}\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={fields.length + 1} className=\"py-16 text-center\">\n <Inbox\n className=\"mx-auto mb-3 text-muted-foreground\"\n size={30}\n strokeWidth={1.3}\n />\n <p className=\"text-sm font-medium\">لا توجد سجلات مطابقة</p>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {query.get('search') || activeFilters.length\n ? 'غيّر البحث أو التصفية لعرض سجلات أخرى.'\n : 'لم تُضف سجلات ضمن نطاقك بعد.'}\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 [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 : 'تعذر حفظ العرض.'\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('تعذر حذف العرض.')\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 العروض المحفوظة\n </span>\n {views.length === 0 && <span className=\"text-xs text-muted-foreground\">لا عروض بعد</span>}\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\"> · مشترك</span>}\n </Button>\n {view.own && (\n <button\n type=\"button\"\n aria-label={`حذف العرض ${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=\"اسم العرض\"\n value={name}\n autoFocus\n maxLength={60}\n onChange={(event) => setName(event.target.value)}\n placeholder=\"اسم العرض\"\n className=\"h-8 w-44 text-xs\"\n />\n <label className=\"flex items-center gap-1 text-xs text-muted-foreground\">\n <input\n type=\"checkbox\"\n checked={shared}\n onChange={(event) => setShared(event.target.checked)}\n />\n مشترك\n </label>\n <Button type=\"submit\" size=\"sm\" className=\"h-8\" disabled={busy || !name.trim()}>\n حفظ\n </Button>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"h-8\"\n onClick={() => setNaming(false)}\n >\n إلغاء\n </Button>\n </form>\n ) : (\n <Button variant=\"outline\" size=\"sm\" className=\"h-8 text-xs\" onClick={() => setNaming(true)}>\n <BookmarkPlus size={14} />\n حفظ العرض الحالي\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 text = displayValue(field, row, related, lookups, calendar)\n const numeric = ['money', 'integer', 'date', 'datetime'].includes(field.type)\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\nfunction Filter({\n resource,\n field,\n value,\n options,\n related,\n onApply,\n}: {\n resource: string\n field: ResourceField\n value: string\n options?: Option[]\n related?: SerializedRecord[]\n onApply: (value: string | undefined) => void\n}): ReactNode {\n const [draft, setDraft] = useState(value)\n const id = `filter-${field.key}`\n const select = (choices: Option[]) => (\n <ResourceSelect\n id={id}\n className=\"h-9 w-44 text-xs\"\n value={value}\n placeholder=\"الكل\"\n options={choices}\n onChange={(next) => onApply(next || undefined)}\n />\n )\n return (\n <label htmlFor={id} className=\"flex flex-col gap-1 text-xs text-muted-foreground\">\n {field.label.ar}\n {field.type === 'lookup' ? (\n select(options ?? [])\n ) : field.type === 'boolean' ? (\n select([\n { value: 'true', label: 'نعم' },\n { value: 'false', label: 'لا' },\n ])\n ) : field.type === 'belongsTo' || field.type === 'user' ? (\n <RelationFilter\n resource={resource}\n field={field}\n value={value}\n related={related}\n onApply={onApply}\n />\n ) : field.type === 'date' ? (\n <div className=\"w-56\">\n <FieldControl\n field={field}\n id={id}\n value={draft}\n label={`تصفية ${field.label.ar}`}\n onChange={(next) => {\n setDraft(next)\n try {\n const parsed = parseValue(field, next)\n onApply(parsed ? String(parsed) : undefined)\n } catch {\n // Keep partial or invalid input without issuing an invalid date query.\n }\n }}\n />\n </div>\n ) : (\n <Input\n id={id}\n className=\"h-9 w-44 text-xs\"\n value={draft}\n placeholder=\"اضغط Enter للتطبيق\"\n onChange={(event) => setDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault()\n onApply(draft || undefined)\n }\n }}\n />\n )}\n </label>\n )\n}\n\n/**\n * Filters by a related record through the target list route, which enforces the target's\n * own rules. User fields list users through the field's options route instead.\n */\nfunction RelationFilter({\n resource,\n field,\n value,\n related = [],\n onApply,\n}: {\n resource: string\n field: ResourceField & { type: 'belongsTo' | 'user' }\n value: string\n /** Related rows already loaded with the list; they label the active filter after a reload. */\n related?: SerializedRecord[]\n onApply: (value: string | undefined) => void\n}) {\n const [open, setOpen] = useState(false)\n const [term, setTerm] = useState('')\n const [choices, setChoices] = useState<Option[]>([])\n const [selected, setSelected] = useState<Option | null>(null)\n const [busy, setBusy] = useState(false)\n const timer = useRef<ReturnType<typeof setTimeout>>(undefined)\n const listId = useId()\n const load = async (search: string) => {\n setBusy(true)\n try {\n if (field.type === 'user') {\n const users = await axios.get<{ data: Option[] }>(\n `/resources/${resource}/options/${field.key}`,\n {\n params: { purpose: 'filter', ...(search ? { search } : {}) },\n headers: { Accept: 'application/json' },\n }\n )\n setChoices(users.data.data)\n return\n }\n const response = await axios.get<ResourceList>(`/resources/${field.resource}`, {\n params: {\n limit: 50,\n estimate: 'false',\n ...(search ? { search } : {}),\n },\n headers: { Accept: 'application/json' },\n })\n setChoices(\n response.data.data.map((row) => ({\n value: String(row.id),\n label: relationLabel(row, row.id),\n }))\n )\n } catch {\n setChoices([])\n } finally {\n setBusy(false)\n }\n }\n const loaded = related.find((row) => String(row.id) === value)\n const current =\n choices.find((choice) => choice.value === value) ??\n (selected?.value === value ? selected : null) ??\n (loaded ? { value, label: relationLabel(loaded, value) } : null)\n const choose = (option: Option | null) => {\n setSelected(option)\n setOpen(false)\n onApply(option?.value)\n }\n return (\n <Popover\n open={open}\n onOpenChange={(next) => {\n setOpen(next)\n if (next && !choices.length) void load(term)\n }}\n >\n <PopoverTrigger asChild>\n <Button\n id={`filter-${field.key}`}\n type=\"button\"\n role=\"combobox\"\n variant=\"outline\"\n aria-expanded={open}\n aria-controls={listId}\n className={`h-9 w-44 justify-between bg-transparent text-xs font-normal ${value ? '' : 'text-muted-foreground'}`}\n >\n <span className=\"truncate\">{value ? (current?.label ?? `#${value}`) : 'الكل'}</span>\n <ChevronsUpDown className=\"opacity-50\" />\n </Button>\n </PopoverTrigger>\n <PopoverContent className=\"w-64 p-0\" align=\"start\">\n <Command shouldFilter={false}>\n <CommandInput\n placeholder=\"ابحث في السجلات المرتبطة\"\n aria-label={`البحث في ${field.label.ar}`}\n value={term}\n onValueChange={(next) => {\n setTerm(next)\n clearTimeout(timer.current)\n timer.current = setTimeout(() => void load(next), 300)\n }}\n />\n <CommandList id={listId}>\n <CommandEmpty>{busy ? 'جارٍ البحث...' : 'لا توجد سجلات مطابقة'}</CommandEmpty>\n <CommandGroup>\n <CommandItem value=\"__all__\" onSelect={() => choose(null)}>\n <Check className={value ? 'opacity-0' : 'opacity-100'} />\n الكل\n </CommandItem>\n {choices.map((choice) => (\n <CommandItem\n key={choice.value}\n value={choice.value}\n onSelect={() => choose(choice)}\n >\n <Check className={choice.value === value ? 'opacity-100' : 'opacity-0'} />\n {choice.label}\n </CommandItem>\n ))}\n </CommandGroup>\n </CommandList>\n </Command>\n </PopoverContent>\n </Popover>\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",
|
|
28
34
|
"target": "inertia/components/ui/data-table.tsx"
|
|
29
35
|
}
|
|
30
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
|
+
}
|