@adula/ui 2.0.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -3
- package/build/attachment-preview.json +21 -0
- package/build/calendar.json +1 -1
- package/build/checkbox.json +1 -1
- package/build/command.json +1 -1
- package/build/confirm-action.json +3 -2
- package/build/data-table.json +7 -2
- package/build/dialog.json +3 -2
- package/build/dropdown-menu.json +1 -1
- package/build/form.json +1 -1
- package/build/hijri-calendar.json +1 -1
- package/build/label.json +1 -1
- package/build/list-filters.json +34 -0
- package/build/manifest.json +106 -76
- package/build/messages.json +21 -0
- package/build/pagination.json +3 -2
- package/build/popover.json +1 -1
- package/build/radio-group.json +1 -1
- package/build/record-collaboration.json +3 -2
- package/build/record-print.json +24 -0
- package/build/record-workflows.json +1 -1
- package/build/resource-actions.json +3 -2
- package/build/resource-bulk.json +27 -0
- package/build/resource-dashboard.json +27 -0
- package/build/resource-field.json +6 -2
- package/build/resource-form.json +3 -2
- package/build/resource-import.json +5 -2
- package/build/resource-page.json +3 -2
- package/build/resource-show.json +4 -2
- package/build/resource-surface.json +3 -2
- package/build/resource-value.json +10 -2
- package/build/select.json +1 -1
- package/build/separator.json +1 -1
- package/build/sheet.json +1 -1
- package/build/sonner.json +1 -1
- package/build/switch.json +1 -1
- package/build/table.json +1 -1
- package/build/tabs.json +1 -1
- package/build/theme.css +16 -16
- package/build/tooltip.json +1 -1
- package/package.json +5 -2
package/README.md
CHANGED
|
@@ -1,12 +1,22 @@
|
|
|
1
1
|
# @adula/ui
|
|
2
2
|
|
|
3
|
-
Version 2.
|
|
3
|
+
Version 2.2.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 {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from '~/components/ui/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=\"max-h-[65vh] overflow-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 <DialogContent dir={dir} className=\"sm:max-w-4xl\">\n <DialogHeader>\n <DialogTitle className=\"truncate pe-6\">{file.name}</DialogTitle>\n <DialogDescription>{t('معاينة المرفق. يمكنك تنزيله من الزر أدناه.')}</DialogDescription>\n </DialogHeader>\n {open && file.preview === 'image' && (\n <img\n src={previewUrl(file)}\n alt={file.name}\n className=\"mx-auto max-h-[65vh] 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 <DialogFooter>\n <Button asChild variant=\"outline\">\n <a href={file.url} download={file.name}>\n <Download size={15} />\n {t('تنزيل')}\n </a>\n </Button>\n </DialogFooter>\n </DialogContent>\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
|
+
}
|
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
|
],
|
package/build/data-table.json
CHANGED
|
@@ -12,7 +12,12 @@
|
|
|
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"
|
|
16
21
|
],
|
|
17
22
|
"dependencies": [
|
|
18
23
|
"@tanstack/react-table@9.2.4",
|
|
@@ -24,7 +29,7 @@
|
|
|
24
29
|
{
|
|
25
30
|
"path": "registry/ui/data-table.tsx",
|
|
26
31
|
"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",
|
|
32
|
+
"content": "import { useEffect, useRef, useState, type ComponentRef, type MouseEvent } from 'react'\nimport { InfiniteScroll, router, usePage } from '@inertiajs/react'\nimport { Link } from '@adonisjs/inertia/react'\nimport { tableFeatures, useTable } from '@tanstack/react-table'\nimport { useVirtualizer } from '@tanstack/react-virtual'\nimport axios from 'axios'\nimport {\n ArrowDown,\n ArrowDownUp,\n ArrowUp,\n Download,\n Inbox,\n ListChecks,\n Loader2,\n Bookmark,\n BookmarkPlus,\n Search,\n SlidersHorizontal,\n Trash2,\n X,\n} from 'lucide-react'\nimport type {\n ResourceDescription,\n ResourceField,\n ResourceList,\n SavedView,\n SavedViewQuery,\n SerializedRecord,\n} from 'adula'\nimport { Alert, AlertDescription } from '~/components/ui/alert'\nimport { Badge } from '~/components/ui/badge'\nimport { Button } from '~/components/ui/button'\nimport { Checkbox } from '~/components/ui/checkbox'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\nimport { useMessages } from '~/components/ui/messages'\nimport { Can } from '~/components/ui/can'\nimport { Input } from '~/components/ui/input'\nimport { ResourceActions } from '~/components/ui/resource-actions'\nimport { openRecord, rememberListView } from '~/components/ui/resource-surface'\nimport { displayValue, type LookupOptions, type Option } from '~/components/ui/resource-value'\nimport {\n FilterControl,\n describeFilter,\n filterValueLabel,\n type FilterLabels,\n} from '~/components/ui/list-filters'\nimport { BulkBar, RestoreAction, actionScope, useBulkActions } from '~/components/ui/resource-bulk'\nimport {\n clearFilter,\n exportHref,\n fromSavedFilter,\n readFilters,\n selectionState,\n serverMessage,\n toSavedFilter,\n toggleSelection,\n writeFilter,\n type FieldFilter,\n} from '~/components/ui/list_query'\n\n/** Rows above this count render through the virtualizer (plan section 13). */\nexport const VIRTUAL_ROWS = 200\nconst ROW_HEIGHT = 52\nconst PAGE_SIZE = 100\nconst features = tableFeatures({})\n\n/**\n * List-layer keys of the description (ADR 046). Older servers omit them: no «المحذوفات»\n * toggle, and the server export stays available.\n */\ntype ListDescription = ResourceDescription & {\n trash?: boolean\n exportable?: boolean\n bulk?: boolean\n}\n\n/** The file name from `Content-Disposition`, or null. */\nfunction attachmentName(header: unknown) {\n if (typeof header !== 'string') return null\n const encoded = header.match(/filename\\*=UTF-8''([^;]+)/i)\n if (encoded) {\n try {\n return decodeURIComponent(encoded[1])\n } catch {\n // Fall through to the plain name.\n }\n }\n return header.match(/filename=\"?([^\";]+)\"?/i)?.[1] ?? null\n}\n\nexport function DataTable({\n resource,\n result,\n lookups = {},\n savedViews = [],\n trashed = false,\n}: {\n resource: ResourceDescription\n result: ResourceList\n lookups?: LookupOptions\n savedViews?: SavedView[]\n /** The «المحذوفات» list of `/resources/:name/trash`: rows offer restore only. */\n trashed?: boolean\n}) {\n const { calendar } = useUiPreferences()\n const { t, label, locale } = useMessages()\n const { url } = usePage()\n const description = resource as ListDescription\n const query = new URL(url, 'http://localhost').searchParams\n const listPath = `/resources/${resource.name}${trashed ? '/trash' : ''}`\n const [search, setSearch] = useState(query.get('search') ?? '')\n const [failure, setFailure] = useState('')\n const [queryFailure, setQueryFailure] = useState('')\n const [exporting, setExporting] = useState(false)\n const [exportFailure, setExportFailure] = useState('')\n const [selected, setSelected] = useState<Set<string>>(() => new Set())\n const labels = useRef<FilterLabels>({})\n const container = useRef<HTMLDivElement>(null)\n const scroller = useRef<ComponentRef<typeof InfiniteScroll>>(null)\n const offered = useBulkActions(resource.name, description.bulk !== false)\n // The «المحذوفات» list offers restore only; the active list everything else.\n const bulkActions = offered.filter(\n (action) => actionScope(action) === (trashed ? 'trash' : 'records')\n )\n // Opening one of this list's records remembers the view, so closing the dialog returns to it.\n useEffect(\n () =>\n router.on('before', (event) => {\n const { pathname } = event.detail.visit.url\n if (pathname.startsWith(`/resources/${resource.name}/`)) rememberListView(pathname)\n }),\n [resource.name]\n )\n // Inertia merges `result.data` page by page; permissions and labels of earlier pages accumulate here.\n const store = useRef<{\n source: ResourceList | null\n permissions: ResourceList['permissions']\n related: ResourceList['related']\n }>({ source: null, permissions: {}, related: {} })\n if (store.current.source !== result) {\n const related = { ...store.current.related }\n for (const [key, rows] of Object.entries(result.related))\n related[key] = [\n ...new Map([...(related[key] ?? []), ...rows].map((row) => [String(row.id), row])).values(),\n ]\n store.current = {\n source: result,\n permissions: { ...store.current.permissions, ...result.permissions },\n related,\n }\n }\n const { permissions, related } = store.current\n const fields = resource.fields.filter(\n (field) => resource.list.includes(field.key) && field.type !== 'hasMany'\n )\n const filterable = fields.filter((field) => field.filterable)\n const filters = readFilters(\n query,\n filterable.map((field) => field.key)\n )\n const activeFilters = filterable.filter((field) => filters[field.key])\n const table = useTable({\n features,\n data: result.data,\n columns: fields.map((field) => ({ accessorKey: field.key, id: field.key })),\n getRowId: (row) => String(row.id),\n })\n const rows = table.getRowModel().rows\n const loadedIds = rows.map((row) => row.id)\n const selectable = bulkActions.length > 0\n const columns = fields.length + 1 + (selectable ? 1 : 0)\n const virtualized = rows.length > VIRTUAL_ROWS\n const virtual = useVirtualizer({\n count: rows.length,\n getScrollElement: () => container.current,\n estimateSize: () => ROW_HEIGHT,\n overscan: 10,\n enabled: virtualized,\n getItemKey: (index) => rows[index].id,\n })\n const items = virtualized\n ? virtual.getVirtualItems()\n : rows.map((_, index) => ({ index, start: 0, end: 0 }))\n const go = (next: URLSearchParams) => {\n next.delete('cursor')\n setQueryFailure('')\n setSelected(new Set())\n const suffix = next.toString()\n router.get(\n `${listPath}${suffix ? `?${suffix}` : ''}`,\n {},\n {\n preserveScroll: true,\n // An invalid filter is 422 E_FILTER; show the server's message instead of the error page.\n onHttpException: (response) => {\n if (response.status !== 422) return\n setQueryFailure(\n serverMessage(response.data) ?? t('تعذر تطبيق التصفية. راجع القيم ثم أعد المحاولة.')\n )\n return false\n },\n }\n )\n }\n const navigate = (changes: Record<string, string | undefined>) => {\n const next = new URLSearchParams(query)\n for (const [key, value] of Object.entries(changes))\n value ? next.set(key, value) : next.delete(key)\n go(next)\n }\n const applyFilter = (key: string, filter: FieldFilter | null) => {\n const next = new URLSearchParams(query)\n writeFilter(next, key, filter)\n go(next)\n }\n const clearFilters = () => {\n const next = new URLSearchParams(query)\n for (const field of activeFilters) clearFilter(next, field.key)\n go(next)\n }\n const sort = query.get('sort')\n const direction = query.get('direction') === 'desc' ? 'desc' : 'asc'\n const valueLabel = (field: ResourceField) => (raw: string) =>\n filterValueLabel(field, raw, {\n options: lookups[field.key],\n related: related[field.key],\n labels: labels.current[field.key],\n calendar,\n t,\n language: locale,\n })\n const remember = (key: string) => (choices: Option[]) => {\n labels.current[key] = {\n ...labels.current[key],\n ...Object.fromEntries(choices.map((choice) => [choice.value, choice.label])),\n }\n }\n // The server export reads the same filtered set as this list, page by page, up to its limit.\n const exportResults = async () => {\n setExporting(true)\n setExportFailure('')\n try {\n const response = await axios.get<Blob>(exportHref(resource.name, query), {\n responseType: 'blob',\n headers: { Accept: 'text/csv, application/json' },\n })\n const href = URL.createObjectURL(response.data)\n const link = document.createElement('a')\n link.href = href\n link.download =\n attachmentName(response.headers['content-disposition']) ?? `${resource.label}.csv`\n link.click()\n // Revoking right after click can cancel the download in some browsers.\n setTimeout(() => URL.revokeObjectURL(href), 60_000)\n } catch (error) {\n const body = axios.isAxiosError(error) ? error.response?.data : null\n const message = body instanceof Blob ? serverMessage(await body.text().catch(() => '')) : null\n setExportFailure(message ?? t('تعذر تصدير النتائج. حاول مجدداً.'))\n } finally {\n setExporting(false)\n }\n }\n const refresh = () => router.visit(url, { preserveScroll: true })\n // Records open in a dialog over this list, which stays mounted (#31); modified clicks\n // (new tab, new window) keep the link's own behavior.\n const overlay = (event: MouseEvent, id: string, mode: 'show' | 'edit') => {\n if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)\n return\n event.preventDefault()\n void openRecord(resource.name, id, mode)\n }\n const currentQuery = (): SavedViewQuery => {\n const view: SavedViewQuery = {}\n const text = query.get('search')\n if (text) view.search = text\n if (sort) {\n view.sort = sort\n view.direction = direction\n }\n const saved: Record<string, unknown> = {}\n for (const field of activeFilters) saved[field.key] = toSavedFilter(filters[field.key])\n // Saved views store operator objects too (ADR 046); older type declarations list scalars.\n if (Object.keys(saved).length) view.filters = saved as SavedViewQuery['filters']\n return view\n }\n const applyView = (view: SavedView) => {\n const next = new URLSearchParams()\n if (view.query.search) next.set('search', view.query.search)\n if (view.query.sort) {\n next.set('sort', view.query.sort)\n next.set('direction', view.query.direction ?? 'asc')\n }\n for (const [key, value] of Object.entries(view.query.filters ?? {}))\n writeFilter(next, key, fromSavedFilter(value))\n setSearch(view.query.search ?? '')\n go(next)\n }\n const allState = selectionState(selected, loadedIds)\n const chosen = loadedIds.filter((id) => selected.has(id))\n return (\n <section\n aria-label={t('قائمة {resource}', { resource: resource.label })}\n className=\"min-w-0 overflow-hidden rounded-xl border border-border bg-white shadow-[0_2px_10px_#1c302804]\"\n >\n <div className=\"flex flex-wrap items-center justify-between gap-4 border-b px-5 py-4\">\n <div className=\"flex flex-wrap items-center gap-3\">\n <h2 className=\"text-sm font-semibold\">\n {trashed\n ? t('المحذوفات من {resource}', { resource: resource.label })\n : t('سجل {resource}', { resource: resource.label })}\n </h2>\n <Badge variant=\"secondary\" className=\"font-normal tabular-nums\">\n {t('{count} معروض', { count: rows.length })}\n </Badge>\n <span className=\"text-xs text-muted-foreground\">\n {result.meta.estimatedTotal !== undefined\n ? t('نحو {count} سجل ضمن نطاقك', {\n count: result.meta.estimatedTotal,\n })\n : t('حسب نطاق صلاحياتك')}\n </span>\n </div>\n <div className=\"flex flex-wrap items-center gap-2\">\n {description.trash && (\n <Button variant=\"outline\" size=\"sm\" asChild>\n <Link\n href={trashed ? `/resources/${resource.name}` : `/resources/${resource.name}/trash`}\n >\n {trashed ? <ListChecks size={15} /> : <Trash2 size={15} />}\n {trashed ? t('السجلات النشطة') : t('المحذوفات')}\n </Link>\n </Button>\n )}\n {!trashed && description.exportable !== false && (\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={() => void exportResults()}\n disabled={!rows.length || exporting}\n >\n {exporting ? <Loader2 size={15} className=\"animate-spin\" /> : <Download size={15} />}\n {exporting ? t('جارٍ التصدير...') : t('تصدير النتائج')}\n </Button>\n )}\n </div>\n </div>\n {exportFailure && (\n <div className=\"border-b px-5 py-3\">\n <Alert variant=\"destructive\">\n <AlertDescription className=\"flex flex-wrap items-center justify-between gap-2\">\n {exportFailure}\n <Button variant=\"ghost\" size=\"sm\" onClick={() => setExportFailure('')}>\n {t('إغلاق')}\n </Button>\n </AlertDescription>\n </Alert>\n </div>\n )}\n {/* Saved views belong to the active list; «المحذوفات» has none. */}\n {!trashed && (resource.searchable || filterable.length > 0) && (\n <SavedViewsBar\n resource={resource}\n views={savedViews}\n current={currentQuery}\n onApply={applyView}\n onChanged={refresh}\n onFailure={setFailure}\n />\n )}\n {(resource.searchable || filterable.length > 0) && (\n <div className=\"grid gap-3 border-b px-5 py-4\">\n <div className=\"flex flex-wrap items-center gap-3\">\n {resource.searchable && (\n <form\n role=\"search\"\n className=\"relative w-full max-w-sm\"\n onSubmit={(event) => {\n event.preventDefault()\n navigate({ search })\n }}\n >\n <Search\n className=\"pointer-events-none absolute start-3 top-2.5 text-muted-foreground\"\n size={16}\n />\n <Input\n aria-label={t('البحث في {field}', { field: resource.label })}\n value={search}\n onChange={(event) => setSearch(event.target.value)}\n placeholder={t('ابحث في السجلات...')}\n className=\"h-9 bg-background/60 ps-10 text-xs\"\n />\n </form>\n )}\n {filterable.length > 0 && (\n <span className=\"flex items-center gap-2 text-xs text-muted-foreground\">\n <SlidersHorizontal size={15} />\n {t('تصفية')}\n </span>\n )}\n {filterable.map((field) => (\n <FilterControl\n key={field.key}\n resource={resource.name}\n field={field}\n filter={filters[field.key]}\n options={lookups[field.key]}\n related={related[field.key]}\n labels={labels.current[field.key]}\n onRemember={remember(field.key)}\n onApply={(filter) => applyFilter(field.key, filter)}\n />\n ))}\n </div>\n {activeFilters.length > 0 && (\n <ul aria-label={t('التصفية المطبقة')} className=\"flex flex-wrap items-center gap-2\">\n {activeFilters.map((field) => (\n <li key={field.key}>\n <Badge\n variant=\"secondary\"\n className=\"h-7 gap-1.5 ps-3 pe-1.5 text-xs font-normal\"\n >\n <span className=\"font-medium\">{label(field.label)}:</span>\n <span className=\"max-w-[260px] truncate\">\n {describeFilter(filters[field.key], valueLabel(field), t)}\n </span>\n <button\n type=\"button\"\n aria-label={t('إزالة تصفية {field}', {\n field: label(field.label),\n })}\n className=\"rounded-full p-0.5 text-muted-foreground hover:bg-background hover:text-foreground\"\n onClick={() => applyFilter(field.key, null)}\n >\n <X size={13} />\n </button>\n </Badge>\n </li>\n ))}\n <li>\n <Button variant=\"ghost\" size=\"sm\" className=\"h-7 text-xs\" onClick={clearFilters}>\n <X size={14} />\n {t('مسح التصفية')}\n </Button>\n </li>\n </ul>\n )}\n {queryFailure && (\n <Alert variant=\"destructive\">\n <AlertDescription>{queryFailure}</AlertDescription>\n </Alert>\n )}\n </div>\n )}\n {selectable && (\n <BulkBar\n resource={resource.name}\n actions={bulkActions}\n selected={chosen}\n rows={result.data}\n onClear={() => setSelected(new Set())}\n onDone={(outcome) => {\n // Refused rows stay selected so they can be reviewed or retried.\n const failed = new Set(outcome.failed.map((entry) => String(entry.id)))\n setSelected((current) => new Set([...current].filter((id) => failed.has(id))))\n refresh()\n }}\n />\n )}\n <InfiniteScroll\n ref={(instance) => {\n scroller.current = instance\n }}\n data=\"result\"\n manual\n onlyNext\n preserveUrl\n params={{\n data: { limit: PAGE_SIZE },\n onBefore: () => {\n setFailure('')\n },\n onHttpException: () => {\n setFailure(t('تعذر تحميل السجلات التالية. أعد المحاولة.'))\n return false\n },\n onNetworkError: () => {\n setFailure(t('تعذر الاتصال بالخادم. تحقق من الاتصال ثم أعد المحاولة.'))\n return false\n },\n }}\n next={({ fetch, loading, hasMore }) => (\n <div className=\"flex flex-wrap items-center justify-center gap-4 border-t px-5 py-3 text-xs text-muted-foreground\">\n {failure && (\n <p role=\"alert\" className=\"text-destructive\">\n {failure}\n </p>\n )}\n {loading ? (\n <span role=\"status\" className=\"inline-flex items-center gap-2\">\n <Loader2 size={14} className=\"animate-spin\" />\n {t('جارٍ تحميل المزيد...')}\n </span>\n ) : hasMore ? (\n <Button variant=\"ghost\" size=\"sm\" onClick={fetch}>\n {t('تحميل المزيد')}\n </Button>\n ) : (\n <span>{rows.length ? t('نهاية السجلات') : ''}</span>\n )}\n </div>\n )}\n >\n <div\n ref={container}\n data-slot=\"table-scroll\"\n className=\"max-h-[600px] overflow-auto\"\n onScroll={(event) => {\n const element = event.currentTarget\n if (\n !failure &&\n element.scrollHeight - element.scrollTop - element.clientHeight < 200 &&\n scroller.current?.hasNext()\n )\n scroller.current.fetchNext()\n }}\n >\n <table\n className=\"w-full min-w-[720px] text-start text-sm\"\n aria-rowcount={rows.length + 1}\n aria-label={resource.label}\n >\n <thead className=\"sticky top-0 z-10 bg-muted text-xs text-muted-foreground\">\n <tr>\n {selectable && (\n <th scope=\"col\" className=\"h-11 w-10 ps-5 pe-1 text-start\">\n <Checkbox\n aria-label={t('تحديد كل السجلات المعروضة')}\n checked={allState}\n disabled={!rows.length}\n onCheckedChange={(value) =>\n setSelected(value === true ? new Set(loadedIds) : new Set())\n }\n />\n </th>\n )}\n {fields.map((field) => (\n <th\n key={field.key}\n scope=\"col\"\n className=\"h-11 whitespace-nowrap px-5 text-start font-medium\"\n aria-sort={\n sort === field.key\n ? direction === 'desc'\n ? 'descending'\n : 'ascending'\n : undefined\n }\n >\n {field.sortable ? (\n <button\n type=\"button\"\n className=\"inline-flex items-center gap-2 hover:text-foreground\"\n onClick={() =>\n navigate({\n sort: field.key,\n direction: sort === field.key && direction === 'asc' ? 'desc' : 'asc',\n })\n }\n >\n {label(field.label)}\n {sort === field.key ? (\n direction === 'desc' ? (\n <ArrowDown size={12} />\n ) : (\n <ArrowUp size={12} />\n )\n ) : (\n <ArrowDownUp size={12} className=\"opacity-60\" />\n )}\n </button>\n ) : (\n label(field.label)\n )}\n </th>\n ))}\n <th\n scope=\"col\"\n className=\"sticky end-0 border-s bg-muted px-5 text-start font-medium\"\n >\n {t('الإجراءات')}\n </th>\n </tr>\n </thead>\n <tbody>\n {virtualized && items[0] && items[0].start > 0 && (\n <tr aria-hidden=\"true\">\n <td colSpan={columns} style={{ height: items[0].start }} />\n </tr>\n )}\n {items.map(({ index }) => {\n const row = rows[index].original\n const id = String(row.id)\n const checked = selected.has(id)\n return (\n <tr\n key={id}\n aria-rowindex={index + 2}\n aria-selected={selectable ? checked : undefined}\n className={`group border-b last:border-0 hover:bg-background ${checked ? 'bg-accent/40' : ''}`}\n style={{ height: ROW_HEIGHT }}\n >\n {selectable && (\n <td className=\"w-10 ps-5 pe-1\">\n <Checkbox\n aria-label={t('تحديد السجل {id}', { id })}\n checked={checked}\n onCheckedChange={(value) =>\n setSelected((current) => toggleSelection(current, id, value === true))\n }\n />\n </td>\n )}\n {fields.map((field) => (\n <Cell\n key={field.key}\n field={field}\n row={row}\n related={related}\n lookups={lookups}\n />\n ))}\n {/* Pinned at the inline end so wide tables keep their row actions in view. */}\n <td className=\"sticky end-0 whitespace-nowrap border-s bg-card px-5 text-xs group-hover:bg-background\">\n <span className=\"inline-flex items-center gap-1\">\n {trashed ? (\n // Restore is authorized by the delete rule on the deleted record (ADR 046).\n (permissions[id] as Record<string, boolean | undefined> | undefined)\n ?.restore === true && (\n <RestoreAction\n resource={resource.name}\n id={id}\n version={row.version ?? undefined}\n label={t('السجل {id}', { id })}\n onDone={refresh}\n />\n )\n ) : (\n <>\n <Button variant=\"ghost\" size=\"sm\" asChild>\n <Link\n href={`/resources/${resource.name}/${id}`}\n aria-label={t('عرض السجل {id}', { id })}\n onClick={(event) => overlay(event, id, 'show')}\n >\n {t('عرض')}\n </Link>\n </Button>\n <Can permissions={permissions[id] ?? {}} action=\"update\">\n <Button variant=\"ghost\" size=\"sm\" asChild>\n <Link\n href={`/resources/${resource.name}/${id}/edit`}\n aria-label={t('تعديل السجل {id}', { id })}\n onClick={(event) => overlay(event, id, 'edit')}\n >\n {t('تعديل')}\n </Link>\n </Button>\n </Can>\n <ResourceActions\n resource={resource.name}\n id={id}\n version={row.version ?? undefined}\n permissions={permissions[id] ?? {}}\n label={t('السجل {id}', { id })}\n size=\"sm\"\n variant=\"ghost\"\n onDone={refresh}\n />\n </>\n )}\n </span>\n </td>\n </tr>\n )\n })}\n {virtualized && (\n <tr aria-hidden=\"true\">\n <td\n colSpan={columns}\n style={{\n height: Math.max(0, virtual.getTotalSize() - (items.at(-1)?.end ?? 0)),\n }}\n />\n </tr>\n )}\n {!rows.length && (\n <tr>\n <td colSpan={columns} className=\"py-16 text-center\">\n {trashed ? (\n <Trash2\n className=\"mx-auto mb-3 text-muted-foreground\"\n size={30}\n strokeWidth={1.3}\n />\n ) : (\n <Inbox\n className=\"mx-auto mb-3 text-muted-foreground\"\n size={30}\n strokeWidth={1.3}\n />\n )}\n <p className=\"text-sm font-medium\">\n {trashed && !query.get('search') && !activeFilters.length\n ? t('لا توجد سجلات محذوفة')\n : t('لا توجد سجلات مطابقة')}\n </p>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {query.get('search') || activeFilters.length\n ? t('غيّر البحث أو التصفية لعرض سجلات أخرى.')\n : trashed\n ? t('تظهر هنا السجلات المحذوفة ضمن نطاقك لتستعيدها.')\n : t('لم تُضف سجلات ضمن نطاقك بعد.')}\n </p>\n </td>\n </tr>\n )}\n </tbody>\n </table>\n </div>\n </InfiniteScroll>\n </section>\n )\n}\n\n/** Presets over the same query keys the list already accepts; AdulaJS validates every one. */\nfunction SavedViewsBar({\n resource,\n views,\n current,\n onApply,\n onChanged,\n onFailure,\n}: {\n resource: ResourceDescription\n views: SavedView[]\n current: () => SavedViewQuery\n onApply: (view: SavedView) => void\n onChanged: () => void\n onFailure: (message: string) => void\n}) {\n const { t } = useMessages()\n const [naming, setNaming] = useState(false)\n const [name, setName] = useState('')\n const [shared, setShared] = useState(false)\n const [busy, setBusy] = useState(false)\n const base = `/resources/${resource.name}/views`\n const save = async (event: React.FormEvent) => {\n event.preventDefault()\n setBusy(true)\n onFailure('')\n try {\n await axios.post(\n base,\n { name, query: current(), shared },\n { headers: { Accept: 'application/json' }, withXSRFToken: true }\n )\n setNaming(false)\n setName('')\n setShared(false)\n onChanged()\n } catch (error) {\n onFailure(\n axios.isAxiosError(error) && error.response?.data?.error?.message\n ? String(error.response.data.error.message)\n : t('تعذر حفظ العرض.')\n )\n } finally {\n setBusy(false)\n }\n }\n const remove = async (view: SavedView) => {\n setBusy(true)\n onFailure('')\n try {\n await axios.delete(`${base}/${view.id}`, {\n headers: { Accept: 'application/json' },\n withXSRFToken: true,\n })\n onChanged()\n } catch {\n onFailure(t('تعذر حذف العرض.'))\n } finally {\n setBusy(false)\n }\n }\n return (\n <div className=\"flex flex-wrap items-center gap-2 border-b px-5 py-3\">\n <span className=\"flex items-center gap-2 text-xs text-muted-foreground\">\n <Bookmark size={15} />\n {t('العروض المحفوظة')}\n </span>\n {views.length === 0 && (\n <span className=\"text-xs text-muted-foreground\">{t('لا عروض بعد')}</span>\n )}\n {views.map((view) => (\n <span\n key={view.id}\n className=\"flex items-center gap-1 rounded-full border border-border bg-background/60 ps-1 pe-3\"\n >\n <Button\n variant=\"ghost\"\n size=\"sm\"\n className=\"h-7 rounded-full px-2 text-xs\"\n onClick={() => onApply(view)}\n >\n {view.name}\n {!view.own && <span className=\"text-muted-foreground\"> · {t('مشترك')}</span>}\n </Button>\n {view.own && (\n <button\n type=\"button\"\n aria-label={t('حذف العرض {name}', { name: view.name })}\n disabled={busy}\n onClick={() => remove(view)}\n className=\"text-muted-foreground transition-colors hover:text-destructive\"\n >\n <X size={13} />\n </button>\n )}\n </span>\n ))}\n {naming ? (\n <form onSubmit={save} className=\"flex flex-wrap items-center gap-2\">\n <Input\n aria-label={t('اسم العرض')}\n value={name}\n autoFocus\n maxLength={60}\n onChange={(event) => setName(event.target.value)}\n placeholder={t('اسم العرض')}\n className=\"h-8 w-44 text-xs\"\n />\n <label className=\"flex items-center gap-1 text-xs text-muted-foreground\">\n <Checkbox checked={shared} onCheckedChange={(value) => setShared(value === true)} />\n {t('مشترك')}\n </label>\n <Button type=\"submit\" size=\"sm\" className=\"h-8\" disabled={busy || !name.trim()}>\n {t('حفظ')}\n </Button>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"h-8\"\n onClick={() => setNaming(false)}\n >\n {t('إلغاء')}\n </Button>\n </form>\n ) : (\n <Button variant=\"outline\" size=\"sm\" className=\"h-8 text-xs\" onClick={() => setNaming(true)}>\n <BookmarkPlus size={14} />\n {t('حفظ العرض الحالي')}\n </Button>\n )}\n </div>\n )\n}\n\nfunction Cell({\n field,\n row,\n related,\n lookups,\n}: {\n field: ResourceField\n row: SerializedRecord\n related: ResourceList['related']\n lookups: LookupOptions\n}) {\n const { calendar } = useUiPreferences()\n const { t, locale } = useMessages()\n const text = displayValue(field, row, related, lookups, calendar, t, locale)\n const numeric = ['money', 'integer', 'decimal', 'percent', 'date', 'datetime'].includes(\n field.type\n )\n return (\n <td\n className={`max-w-[280px] truncate px-5 ${numeric ? 'tabular-nums' : ''}`}\n dir={numeric ? 'ltr' : undefined}\n title={text}\n >\n {field.type === 'boolean' && row[field.key] !== null && row[field.key] !== undefined ? (\n <Badge variant={row[field.key] ? 'default' : 'secondary'}>{text}</Badge>\n ) : (\n text\n )}\n </td>\n )\n}\n",
|
|
28
33
|
"target": "inertia/components/ui/data-table.tsx"
|
|
29
34
|
}
|
|
30
35
|
],
|
package/build/dialog.json
CHANGED
|
@@ -9,13 +9,14 @@
|
|
|
9
9
|
{
|
|
10
10
|
"path": "registry/ui/dialog.tsx",
|
|
11
11
|
"type": "registry:ui",
|
|
12
|
-
"content": "
|
|
12
|
+
"content": "import * as React from 'react'\nimport { cn } from 'cn'\nimport { XIcon } from 'lucide-react'\nimport { Dialog as DialogPrimitive } from 'radix-ui'\n\nimport { Button } from '~/components/ui/button'\nimport { useMessages } from '~/components/ui/messages'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\n\nconst DialogContentContext = React.createContext<React.RefObject<HTMLDivElement | null> | null>(\n null\n)\n\nfunction Dialog({\n mode,\n onOpenChange,\n children,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Root> & { mode?: 'view' | 'edit' | 'confirm' }) {\n const content = React.useRef<HTMLDivElement>(null)\n const [confirming, setConfirming] = React.useState(false)\n const [uncontrolledOpen, setUncontrolledOpen] = React.useState(props.defaultOpen ?? false)\n const preferences = useUiPreferences()\n const { t, dir } = useMessages()\n const open = props.open ?? uncontrolledOpen\n const commit = (next: boolean) => {\n setUncontrolledOpen(next)\n onOpenChange?.(next)\n }\n const request = (next: boolean) => {\n const editing = mode === 'edit' || (!mode && Boolean(content.current?.querySelector('form')))\n if (!next && editing && preferences.confirmDialogClose) setConfirming(true)\n else commit(next)\n }\n return (\n <DialogContentContext.Provider value={content}>\n <DialogPrimitive.Root data-slot=\"dialog\" {...props} open={open} onOpenChange={request}>\n {children}\n </DialogPrimitive.Root>\n {confirming && open && (\n <Dialog mode=\"confirm\" open onOpenChange={(next) => !next && setConfirming(false)}>\n <DialogContent showCloseButton={false} className=\"z-[70] sm:max-w-md\" dir={dir}>\n <DialogHeader>\n <DialogTitle>{t('إغلاق النموذج؟')}</DialogTitle>\n <DialogDescription>\n {t('قد تفقد التغييرات التي لم تحفظها. يمكنك متابعة التحرير أو إغلاق النموذج.')}\n </DialogDescription>\n </DialogHeader>\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" onClick={() => setConfirming(false)}>\n {t('متابعة التحرير')}\n </Button>\n <Button\n type=\"button\"\n variant=\"destructive\"\n onClick={() => {\n setConfirming(false)\n commit(false)\n }}\n >\n {t('إغلاق دون حفظ')}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )}\n </DialogContentContext.Provider>\n )\n}\n\nfunction DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {\n return <DialogPrimitive.Trigger data-slot=\"dialog-trigger\" {...props} />\n}\n\nfunction DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {\n return <DialogPrimitive.Portal data-slot=\"dialog-portal\" {...props} />\n}\n\nfunction DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {\n return <DialogPrimitive.Close data-slot=\"dialog-close\" {...props} />\n}\n\nfunction DialogOverlay({\n className,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {\n return (\n <DialogPrimitive.Overlay\n data-slot=\"dialog-overlay\"\n className={cn(\n 'fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0',\n className\n )}\n {...props}\n />\n )\n}\n\nfunction DialogContent({\n ref,\n className,\n children,\n showCloseButton = true,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Content> & {\n showCloseButton?: boolean\n}) {\n const content = React.useContext(DialogContentContext)\n const { t } = useMessages()\n return (\n <DialogPortal data-slot=\"dialog-portal\">\n <DialogOverlay />\n <DialogPrimitive.Content\n ref={(node) => {\n if (content) content.current = node\n if (typeof ref === 'function') return ref(node)\n if (ref) ref.current = node\n }}\n data-slot=\"dialog-content\"\n className={cn(\n 'fixed top-[50%] start-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] ltr:translate-x-[-50%] rtl:-translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg',\n className\n )}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close\n data-slot=\"dialog-close\"\n className=\"absolute top-4 end-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\"\n >\n <XIcon />\n <span className=\"sr-only\">{t('إغلاق')}</span>\n </DialogPrimitive.Close>\n )}\n </DialogPrimitive.Content>\n </DialogPortal>\n )\n}\n\nfunction DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"dialog-header\"\n className={cn('flex flex-col gap-2 text-center sm:text-start', className)}\n {...props}\n />\n )\n}\n\nfunction DialogFooter({\n className,\n showCloseButton = false,\n children,\n ...props\n}: React.ComponentProps<'div'> & {\n showCloseButton?: boolean\n}) {\n const { t } = useMessages()\n return (\n <div\n data-slot=\"dialog-footer\"\n className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close asChild>\n <Button variant=\"outline\">{t('إغلاق')}</Button>\n </DialogPrimitive.Close>\n )}\n </div>\n )\n}\n\nfunction DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {\n return (\n <DialogPrimitive.Title\n data-slot=\"dialog-title\"\n className={cn('text-lg leading-none font-semibold', className)}\n {...props}\n />\n )\n}\n\nfunction DialogDescription({\n className,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Description>) {\n return (\n <DialogPrimitive.Description\n data-slot=\"dialog-description\"\n className={cn('text-sm text-muted-foreground', className)}\n {...props}\n />\n )\n}\n\nexport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogOverlay,\n DialogPortal,\n DialogTitle,\n DialogTrigger,\n}\n",
|
|
13
13
|
"target": "inertia/components/ui/dialog.tsx"
|
|
14
14
|
}
|
|
15
15
|
],
|
|
16
16
|
"type": "registry:ui",
|
|
17
17
|
"registryDependencies": [
|
|
18
|
-
"ui-preferences"
|
|
18
|
+
"ui-preferences",
|
|
19
|
+
"messages"
|
|
19
20
|
],
|
|
20
21
|
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
21
22
|
}
|
package/build/dropdown-menu.json
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
{
|
|
10
10
|
"path": "registry/ui/dropdown-menu.tsx",
|
|
11
11
|
"type": "registry:ui",
|
|
12
|
-
"content": "
|
|
12
|
+
"content": "import * as React from \"react\"\nimport { cn } from \"cn\"\nimport { CheckIcon, ChevronRightIcon, CircleIcon } from \"lucide-react\"\nimport { DropdownMenu as DropdownMenuPrimitive } from \"radix-ui\"\n\nfunction DropdownMenu({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {\n return <DropdownMenuPrimitive.Root dir=\"rtl\" data-slot=\"dropdown-menu\" {...props} />\n}\n\nfunction DropdownMenuPortal({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {\n return (\n <DropdownMenuPrimitive.Portal data-slot=\"dropdown-menu-portal\" {...props} />\n )\n}\n\nfunction DropdownMenuTrigger({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {\n return (\n <DropdownMenuPrimitive.Trigger\n data-slot=\"dropdown-menu-trigger\"\n {...props}\n />\n )\n}\n\nfunction DropdownMenuContent({\n className,\n sideOffset = 4,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {\n return (\n <DropdownMenuPrimitive.Portal>\n <DropdownMenuPrimitive.Content\n data-slot=\"dropdown-menu-content\"\n sideOffset={sideOffset}\n className={cn(\n \"z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95\",\n className\n )}\n {...props}\n />\n </DropdownMenuPrimitive.Portal>\n )\n}\n\nfunction DropdownMenuGroup({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {\n return (\n <DropdownMenuPrimitive.Group data-slot=\"dropdown-menu-group\" {...props} />\n )\n}\n\nfunction DropdownMenuItem({\n className,\n inset,\n variant = \"default\",\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {\n inset?: boolean\n variant?: \"default\" | \"destructive\"\n}) {\n return (\n <DropdownMenuPrimitive.Item\n data-slot=\"dropdown-menu-item\"\n data-inset={inset}\n data-variant={variant}\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 focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:ps-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction DropdownMenuCheckboxItem({\n className,\n children,\n checked,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {\n return (\n <DropdownMenuPrimitive.CheckboxItem\n data-slot=\"dropdown-menu-checkbox-item\"\n className={cn(\n \"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pe-2 ps-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n className\n )}\n checked={checked}\n {...props}\n >\n <span className=\"pointer-events-none absolute start-2 flex size-3.5 items-center justify-center\">\n <DropdownMenuPrimitive.ItemIndicator>\n <CheckIcon className=\"size-4\" />\n </DropdownMenuPrimitive.ItemIndicator>\n </span>\n {children}\n </DropdownMenuPrimitive.CheckboxItem>\n )\n}\n\nfunction DropdownMenuRadioGroup({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {\n return (\n <DropdownMenuPrimitive.RadioGroup\n data-slot=\"dropdown-menu-radio-group\"\n {...props}\n />\n )\n}\n\nfunction DropdownMenuRadioItem({\n className,\n children,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {\n return (\n <DropdownMenuPrimitive.RadioItem\n data-slot=\"dropdown-menu-radio-item\"\n className={cn(\n \"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pe-2 ps-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n className\n )}\n {...props}\n >\n <span className=\"pointer-events-none absolute start-2 flex size-3.5 items-center justify-center\">\n <DropdownMenuPrimitive.ItemIndicator>\n <CircleIcon className=\"size-2 fill-current\" />\n </DropdownMenuPrimitive.ItemIndicator>\n </span>\n {children}\n </DropdownMenuPrimitive.RadioItem>\n )\n}\n\nfunction DropdownMenuLabel({\n className,\n inset,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {\n inset?: boolean\n}) {\n return (\n <DropdownMenuPrimitive.Label\n data-slot=\"dropdown-menu-label\"\n data-inset={inset}\n className={cn(\n \"px-2 py-1.5 text-sm font-medium data-[inset]:ps-8\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction DropdownMenuSeparator({\n className,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {\n return (\n <DropdownMenuPrimitive.Separator\n data-slot=\"dropdown-menu-separator\"\n className={cn(\"-mx-1 my-1 h-px bg-border\", className)}\n {...props}\n />\n )\n}\n\nfunction DropdownMenuShortcut({\n className,\n ...props\n}: React.ComponentProps<\"span\">) {\n return (\n <span\n data-slot=\"dropdown-menu-shortcut\"\n className={cn(\n \"ms-auto text-xs tracking-widest text-muted-foreground\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction DropdownMenuSub({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {\n return <DropdownMenuPrimitive.Sub data-slot=\"dropdown-menu-sub\" {...props} />\n}\n\nfunction DropdownMenuSubTrigger({\n className,\n inset,\n children,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {\n inset?: boolean\n}) {\n return (\n <DropdownMenuPrimitive.SubTrigger\n data-slot=\"dropdown-menu-sub-trigger\"\n data-inset={inset}\n className={cn(\n \"flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:ps-8 data-[state=open]:bg-accent data-[state=open]: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 {children}\n <ChevronRightIcon className=\"ms-auto size-4 rtl:rotate-180\" />\n </DropdownMenuPrimitive.SubTrigger>\n )\n}\n\nfunction DropdownMenuSubContent({\n className,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {\n return (\n <DropdownMenuPrimitive.SubContent\n data-slot=\"dropdown-menu-sub-content\"\n className={cn(\n \"z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport {\n DropdownMenu,\n DropdownMenuPortal,\n DropdownMenuTrigger,\n DropdownMenuContent,\n DropdownMenuGroup,\n DropdownMenuLabel,\n DropdownMenuItem,\n DropdownMenuCheckboxItem,\n DropdownMenuRadioGroup,\n DropdownMenuRadioItem,\n DropdownMenuSeparator,\n DropdownMenuShortcut,\n DropdownMenuSub,\n DropdownMenuSubTrigger,\n DropdownMenuSubContent,\n}\n",
|
|
13
13
|
"target": "inertia/components/ui/dropdown-menu.tsx"
|
|
14
14
|
}
|
|
15
15
|
],
|
package/build/form.json
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
{
|
|
15
15
|
"path": "registry/ui/form.tsx",
|
|
16
16
|
"type": "registry:ui",
|
|
17
|
-
"content": "
|
|
17
|
+
"content": "import * as React from \"react\"\nimport { cn } from \"cn\"\nimport type { Label as LabelPrimitive } from \"radix-ui\"\nimport { Slot } from \"radix-ui\"\nimport {\n Controller,\n FormProvider,\n useFormContext,\n useFormState,\n type ControllerProps,\n type FieldPath,\n type FieldValues,\n} from \"react-hook-form\"\n\nimport { Label } from \"~/components/ui/label\"\n\nconst Form = FormProvider\n\ntype FormFieldContextValue<\n TFieldValues extends FieldValues = FieldValues,\n TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\n> = {\n name: TName\n}\n\nconst FormFieldContext = React.createContext<FormFieldContextValue>(\n {} as FormFieldContextValue\n)\n\nconst FormField = <\n TFieldValues extends FieldValues = FieldValues,\n TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\n>({\n ...props\n}: ControllerProps<TFieldValues, TName>) => {\n return (\n <FormFieldContext.Provider value={{ name: props.name }}>\n <Controller {...props} />\n </FormFieldContext.Provider>\n )\n}\n\nconst useFormField = () => {\n const fieldContext = React.useContext(FormFieldContext)\n const itemContext = React.useContext(FormItemContext)\n const { getFieldState } = useFormContext()\n const formState = useFormState({ name: fieldContext.name })\n const fieldState = getFieldState(fieldContext.name, formState)\n\n if (!fieldContext) {\n throw new Error(\"useFormField should be used within <FormField>\")\n }\n\n const { id } = itemContext\n\n return {\n id,\n name: fieldContext.name,\n formItemId: `${id}-form-item`,\n formDescriptionId: `${id}-form-item-description`,\n formMessageId: `${id}-form-item-message`,\n ...fieldState,\n }\n}\n\ntype FormItemContextValue = {\n id: string\n}\n\nconst FormItemContext = React.createContext<FormItemContextValue>(\n {} as FormItemContextValue\n)\n\nfunction FormItem({ className, ...props }: React.ComponentProps<\"div\">) {\n const id = React.useId()\n\n return (\n <FormItemContext.Provider value={{ id }}>\n <div\n data-slot=\"form-item\"\n className={cn(\"grid gap-2\", className)}\n {...props}\n />\n </FormItemContext.Provider>\n )\n}\n\nfunction FormLabel({\n className,\n ...props\n}: React.ComponentProps<typeof LabelPrimitive.Root>) {\n const { error, formItemId } = useFormField()\n\n return (\n <Label\n data-slot=\"form-label\"\n data-error={!!error}\n className={cn(\"data-[error=true]:text-destructive\", className)}\n htmlFor={formItemId}\n {...props}\n />\n )\n}\n\nfunction FormControl({ ...props }: React.ComponentProps<typeof Slot.Root>) {\n const { error, formItemId, formDescriptionId, formMessageId } = useFormField()\n\n return (\n <Slot.Root\n data-slot=\"form-control\"\n id={formItemId}\n aria-describedby={\n !error\n ? `${formDescriptionId}`\n : `${formDescriptionId} ${formMessageId}`\n }\n aria-invalid={!!error}\n {...props}\n />\n )\n}\n\nfunction FormDescription({ className, ...props }: React.ComponentProps<\"p\">) {\n const { formDescriptionId } = useFormField()\n\n return (\n <p\n data-slot=\"form-description\"\n id={formDescriptionId}\n className={cn(\"text-sm text-muted-foreground\", className)}\n {...props}\n />\n )\n}\n\nfunction FormMessage({ className, ...props }: React.ComponentProps<\"p\">) {\n const { error, formMessageId } = useFormField()\n const body = error ? String(error?.message ?? \"\") : props.children\n\n if (!body) {\n return null\n }\n\n return (\n <p\n data-slot=\"form-message\"\n id={formMessageId}\n className={cn(\"text-sm text-destructive\", className)}\n {...props}\n >\n {body}\n </p>\n )\n}\n\nexport {\n useFormField,\n Form,\n FormItem,\n FormLabel,\n FormControl,\n FormDescription,\n FormMessage,\n FormField,\n}\n",
|
|
18
18
|
"target": "inertia/components/ui/form.tsx"
|
|
19
19
|
}
|
|
20
20
|
],
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
{
|
|
12
12
|
"path": "registry/ui/hijri-calendar.tsx",
|
|
13
13
|
"type": "registry:ui",
|
|
14
|
-
"content": "import { useState } from 'react'\nimport { ChevronLeft, ChevronRight } from 'lucide-react'\nimport { Button } from '~/components/ui/button'\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from '~/components/ui/select'\nimport { calendarInput, calendarIso, calendarDisplay } from '~/components/ui/calendar_date'\n\nconst months = [\n 'محرم',\n 'صفر',\n 'ربيع الأول',\n 'ربيع الآخر',\n 'جمادى الأولى',\n 'جمادى الآخرة',\n 'رجب',\n 'شعبان',\n 'رمضان',\n 'شوال',\n 'ذو القعدة',\n 'ذو الحجة',\n]\nconst pad = (value: number) => String(value).padStart(2, '0')\n\nexport function HijriCalendar({\n value,\n onSelect,\n}: {\n value: string\n onSelect: (iso: string) => void\n}) {\n const
|
|
14
|
+
"content": "import { useState } from 'react'\nimport { ChevronLeft, ChevronRight } from 'lucide-react'\nimport { Button } from '~/components/ui/button'\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from '~/components/ui/select'\nimport { calendarInput, calendarIso, calendarDisplay } from '~/components/ui/calendar_date'\n\nconst months = [\n 'محرم',\n 'صفر',\n 'ربيع الأول',\n 'ربيع الآخر',\n 'جمادى الأولى',\n 'جمادى الآخرة',\n 'رجب',\n 'شعبان',\n 'رمضان',\n 'شوال',\n 'ذو القعدة',\n 'ذو الحجة',\n]\nconst pad = (value: number) => String(value).padStart(2, '0')\n\nexport function HijriCalendar({\n value,\n onSelect,\n}: {\n value: string\n onSelect: (iso: string) => void\n}) {\n // Today is the viewer's local day; its UTC date is yesterday shortly after midnight east of UTC.\n const now = new Date()\n const today = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`\n const initial = calendarInput(value || today, 'islamic-umalqura')\n const [year, setYear] = useState(Math.max(1300, Math.min(1600, Number(initial.slice(0, 4)))))\n const [month, setMonth] = useState(Number(initial.slice(5, 7)))\n const first = calendarIso(`${year}-${pad(month)}-01`, 'islamic-umalqura')\n const offset = new Date(`${first}T00:00:00Z`).getUTCDay()\n let days = 30\n try {\n calendarIso(`${year}-${pad(month)}-30`, 'islamic-umalqura')\n } catch {\n days = 29\n }\n const move = (delta: number) => {\n const next = year * 12 + month - 1 + delta\n setYear(Math.floor(next / 12))\n setMonth((next % 12) + 1)\n }\n return (\n <div dir=\"rtl\" className=\"w-80 space-y-3 p-3\" aria-label=\"تقويم أم القرى\">\n <div className=\"flex items-center gap-2\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"الشهر السابق\"\n disabled={year === 1300 && month === 1}\n onClick={() => move(-1)}\n >\n <ChevronRight />\n </Button>\n <Select value={String(month)} onValueChange={(value) => setMonth(Number(value))}>\n <SelectTrigger aria-label=\"الشهر الهجري\" className=\"flex-1\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {months.map((label, index) => (\n <SelectItem key={label} value={String(index + 1)}>\n {label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <Select value={String(year)} onValueChange={(value) => setYear(Number(value))}>\n <SelectTrigger aria-label=\"السنة الهجرية\" className=\"w-24\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {Array.from({ length: 301 }, (_, index) => (\n <SelectItem key={index} value={String(1300 + index)}>\n {1300 + index} هـ\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"الشهر التالي\"\n disabled={year === 1600 && month === 12}\n onClick={() => move(1)}\n >\n <ChevronLeft />\n </Button>\n </div>\n <div\n className=\"grid grid-cols-7 gap-1 text-center text-xs text-muted-foreground\"\n aria-hidden=\"true\"\n >\n {['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'].map((day) => (\n <span key={day}>{day}</span>\n ))}\n </div>\n <div\n className=\"grid grid-cols-7 gap-1\"\n role=\"group\"\n aria-label={`${months[month - 1]} ${year} هـ`}\n >\n {Array.from({ length: offset }, (_, index) => (\n <span key={`empty-${index}`} />\n ))}\n {Array.from({ length: days }, (_, index) => {\n const iso = new Date(Date.parse(`${first}T00:00:00Z`) + index * 86400000)\n .toISOString()\n .slice(0, 10)\n return (\n <Button\n key={iso}\n type=\"button\"\n size=\"icon-sm\"\n variant={iso === value ? 'default' : 'ghost'}\n aria-pressed={iso === value}\n aria-label={calendarDisplay(iso, 'islamic-umalqura')}\n onClick={() => onSelect(iso)}\n >\n {index + 1}\n </Button>\n )\n })}\n </div>\n <p className=\"text-center text-xs text-muted-foreground\">\n تقويم أم القرى · يُحفظ التاريخ موحدًا\n </p>\n </div>\n )\n}\n",
|
|
15
15
|
"target": "inertia/components/ui/hijri-calendar.tsx"
|
|
16
16
|
}
|
|
17
17
|
],
|
package/build/label.json
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
{
|
|
10
10
|
"path": "registry/ui/label.tsx",
|
|
11
11
|
"type": "registry:ui",
|
|
12
|
-
"content": "
|
|
12
|
+
"content": "import * as React from \"react\"\nimport { cn } from \"cn\"\nimport { Label as LabelPrimitive } from \"radix-ui\"\n\nfunction Label({\n className,\n ...props\n}: React.ComponentProps<typeof LabelPrimitive.Root>) {\n return (\n <LabelPrimitive.Root\n data-slot=\"label\"\n className={cn(\n \"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Label }\n",
|
|
13
13
|
"target": "inertia/components/ui/label.tsx"
|
|
14
14
|
}
|
|
15
15
|
],
|