@adula/ui 2.1.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -3
- package/build/attachment-preview.json +21 -0
- package/build/breadcrumb.json +18 -0
- package/build/calendar.json +1 -1
- package/build/checkbox.json +1 -1
- package/build/command.json +1 -1
- package/build/confirm-action.json +3 -2
- package/build/copy-button.json +21 -0
- package/build/data-table.json +8 -2
- package/build/dialog-param.json +17 -0
- package/build/dialog.json +3 -2
- package/build/dropdown-menu.json +1 -1
- package/build/file-input.json +21 -0
- package/build/form.json +1 -1
- package/build/hijri-calendar.json +1 -1
- package/build/label.json +1 -1
- package/build/list-filters.json +34 -0
- package/build/long-dialog.json +17 -0
- package/build/manifest.json +146 -76
- package/build/messages.json +21 -0
- package/build/pagination.json +3 -2
- package/build/popover.json +1 -1
- package/build/radio-group.json +1 -1
- package/build/record-assignments.json +3 -2
- package/build/record-collaboration.json +4 -2
- package/build/record-print.json +24 -0
- package/build/record-workflows.json +3 -2
- package/build/resource-actions.json +3 -2
- package/build/resource-bulk.json +27 -0
- package/build/resource-dashboard.json +27 -0
- package/build/resource-field.json +7 -2
- package/build/resource-form.json +4 -2
- package/build/resource-import.json +7 -3
- package/build/resource-page.json +4 -2
- package/build/resource-show.json +6 -2
- package/build/resource-surface.json +4 -2
- package/build/resource-value.json +11 -2
- package/build/select.json +1 -1
- package/build/separator.json +1 -1
- package/build/sheet.json +1 -1
- package/build/slider.json +17 -0
- package/build/sonner.json +1 -1
- package/build/sortable-list.json +20 -0
- package/build/switch.json +1 -1
- package/build/table.json +1 -1
- package/build/tabs.json +1 -1
- package/build/theme.css +48 -2
- package/build/tooltip.json +1 -1
- package/build/user-avatar.json +17 -0
- package/package.json +5 -2
package/build/dialog.json
CHANGED
|
@@ -9,13 +9,14 @@
|
|
|
9
9
|
{
|
|
10
10
|
"path": "registry/ui/dialog.tsx",
|
|
11
11
|
"type": "registry:ui",
|
|
12
|
-
"content": "'use client'\n\nimport * 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 { 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 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=\"rtl\">\n <DialogHeader>\n <DialogTitle>إغلاق النموذج؟</DialogTitle>\n <DialogDescription>\n قد تفقد التغييرات التي لم تحفظها. يمكنك متابعة التحرير أو إغلاق النموذج.\n </DialogDescription>\n </DialogHeader>\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" onClick={() => setConfirming(false)}>\n متابعة التحرير\n </Button>\n <Button\n type=\"button\"\n variant=\"destructive\"\n onClick={() => {\n setConfirming(false)\n commit(false)\n }}\n >\n إغلاق دون حفظ\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 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%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] 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\">إغلاق</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 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\">إغلاق</Button>\n </DialogPrimitive.Close>\n )}\n </div>\n )\n}\n\nfunction DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {\n return (\n <DialogPrimitive.Title\n data-slot=\"dialog-title\"\n className={cn('text-lg leading-none font-semibold', className)}\n {...props}\n />\n )\n}\n\nfunction DialogDescription({\n className,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Description>) {\n return (\n <DialogPrimitive.Description\n data-slot=\"dialog-description\"\n className={cn('text-sm text-muted-foreground', className)}\n {...props}\n />\n )\n}\n\nexport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogOverlay,\n DialogPortal,\n DialogTitle,\n DialogTrigger,\n}\n",
|
|
12
|
+
"content": "import * as React from 'react'\nimport { cn } from 'cn'\nimport { XIcon } from 'lucide-react'\nimport { Dialog as DialogPrimitive } from 'radix-ui'\n\nimport { Button } from '~/components/ui/button'\nimport { useMessages } from '~/components/ui/messages'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\n\n/**\n * Clean close (ADR 016, decision 23 for 2.3.0): a dialog asks before closing only while\n * something differs from how it opened, and a value changed and restored is clean. The dialog\n * decides this itself; a dialog never computes its own dirty state.\n *\n * Two sources, one rule:\n * - Declared state. A dialog whose state is not plain controls (a draft object, a list order,\n * switches, an image) declares it with the `value` prop of `Dialog`, or with\n * `useDialogValue(value)` from a component inside the dialog. Each declaration is captured\n * as it renders until the user first interacts with the dialog (so values reset on opening\n * or loaded just after it are the starting point), then compared on closing.\n * - Plain controls. A dialog that declares nothing compares its inputs, text areas and\n * selects: the value each had before the user changed it against the value now.\n *\n * When a dialog declares state, the declarations are the whole truth for it and its controls\n * are not compared one by one, so a dialog that declares a value declares its full state. A\n * control that changed while no declaration did is reported once on the console.\n */\ntype Changes = { initial: Map<Element, string>; changed: Set<Element> }\ntype Declared = { opened: string; current: string; settled: boolean }\ntype DialogState = {\n content: React.RefObject<HTMLDivElement | null>\n changes: React.RefObject<Changes>\n declared: React.RefObject<Map<symbol, Declared>>\n mode: React.RefObject<'view' | 'edit' | 'confirm'>\n}\nconst DialogContentContext = React.createContext<DialogState | null>(null)\n\n/**\n * Which side the page's own scrollbar is on, as `data-root-scrollbar` on <html>. Locking page\n * scrolling hides that scrollbar and pads the body by its width (theme.css pads the measured\n * side). The direction does not decide it: Chromium keeps the page's scrollbar on the right in\n * a right-to-left page while an element's moves left, and Firefox moves both. Measured while\n * the scrollbar shows, again whenever the page's width changes (a scrollbar appearing).\n */\nfunction watchPageScrollbar() {\n if (typeof window === 'undefined' || typeof ResizeObserver === 'undefined') return\n const root = document.documentElement\n const measure = () => {\n const gap = window.innerWidth - root.clientWidth\n if (gap <= 0) return\n const side = root.getBoundingClientRect().left >= gap - 0.5 ? 'left' : 'right'\n if (root.dataset.rootScrollbar !== side) root.dataset.rootScrollbar = side\n }\n new ResizeObserver(measure).observe(root)\n measure()\n}\nwatchPageScrollbar()\n\nconst CONTROLS = 'input, textarea, select'\n\n/** A comparable value of a form control (checked state, selected options, files or text). */\nfunction controlValue(element: Element) {\n if (element instanceof HTMLInputElement) {\n if (element.type === 'checkbox' || element.type === 'radio') return String(element.checked)\n if (element.type === 'file')\n return [...(element.files ?? [])].map((file) => `${file.name}:${file.size}`).join('|')\n return element.value\n }\n if (element instanceof HTMLSelectElement)\n return [...element.selectedOptions].map((option) => option.value).join('|')\n if (element instanceof HTMLTextAreaElement) return element.value\n return ''\n}\n\n/** True for a form control the dialog compares when nothing is declared. */\nfunction isControl(element: Element) {\n return Boolean(element.matches?.(CONTROLS))\n}\n\n/**\n * Remembers a control's value before the user changes it. On mount every control is recorded;\n * taking focus records it again until it changes, so values loaded after opening count as the\n * starting point.\n */\nfunction remember(changes: Changes, element: Element, focus = false) {\n if (!isControl(element) || changes.changed.has(element)) return\n if (focus || !changes.initial.has(element)) changes.initial.set(element, controlValue(element))\n}\n\n/** A plain, ordered copy of a value: object keys sorted, files and dates as comparable data. */\nfunction normalize(value: unknown): unknown {\n if (typeof value === 'function' || typeof value === 'symbol') return undefined\n if (value === null || typeof value !== 'object') return value\n if (value instanceof Date) return value.toISOString()\n if (typeof File !== 'undefined' && value instanceof File)\n return { file: value.name, size: value.size, modified: value.lastModified }\n if (typeof Blob !== 'undefined' && value instanceof Blob)\n return { blob: value.type, size: value.size }\n if (value instanceof Map) return [...value.entries()].map(([key, item]) => [key, normalize(item)])\n if (value instanceof Set) return [...value].map((item) => normalize(item) ?? null)\n if (Array.isArray(value)) return value.map((item) => normalize(item) ?? null)\n const plain: Record<string, unknown> = {}\n for (const key of Object.keys(value).sort()) {\n const item = normalize((value as Record<string, unknown>)[key])\n if (item !== undefined) plain[key] = item\n }\n return plain\n}\n\n/** Stable text of a declared value: equal data gives equal text whatever the key order. */\nfunction serialize(value: unknown) {\n return JSON.stringify(normalize(value)) ?? ''\n}\n\nconst useIsomorphicLayoutEffect =\n typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect\n\n/** Records one declaration in a dialog while `active`; removes it when inactive or unmounted. */\nfunction useDeclaration(state: DialogState | null, value: unknown, active: boolean) {\n const [key] = React.useState(() => Symbol('dialog-value'))\n const text = active ? serialize(value) : ''\n useIsomorphicLayoutEffect(() => {\n const declared = state?.declared.current\n if (!declared) return\n if (!active) {\n declared.delete(key)\n return\n }\n const entry = declared.get(key)\n if (!entry) declared.set(key, { opened: text, current: text, settled: false })\n else {\n entry.current = text\n if (!entry.settled) entry.opened = text\n }\n })\n useIsomorphicLayoutEffect(() => () => void state?.declared.current.delete(key), [state, key])\n}\n\n/**\n * Declares state of the surrounding dialog that is not a plain control: the dialog compares it\n * on closing with how it was when the dialog opened. Outside a dialog it does nothing, so a\n * form shown both as a page and in a dialog can always call it.\n */\nfunction useDialogValue(value: unknown) {\n useDeclaration(React.useContext(DialogContentContext), value, true)\n}\n\n/**\n * `useDialogValue` as an element, for state that starts afresh within one opening: give it a\n * `key` that changes when a step is saved (an uploaded file becomes a mapping to review), and\n * the new step is compared with how it began. Place it inside the dialog's content.\n */\nfunction DialogValue({ value }: { value: unknown }) {\n useDialogValue(value)\n return null\n}\n\nfunction Dialog({\n mode,\n value,\n onOpenChange,\n children,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Root> & {\n mode?: 'view' | 'edit' | 'confirm'\n /** The dialog's editable state when it is not plain controls (see useDialogValue). */\n value?: unknown\n}) {\n const content = React.useRef<HTMLDivElement>(null)\n const changes = React.useRef<Changes>({ initial: new Map(), changed: new Set() })\n const declared = React.useRef(new Map<symbol, Declared>())\n const modeRef = React.useRef<'view' | 'edit' | 'confirm'>(mode ?? 'edit')\n modeRef.current = mode ?? 'edit'\n const state = React.useMemo(() => ({ content, changes, declared, mode: modeRef }), [])\n const [confirming, setConfirming] = React.useState(false)\n const [uncontrolledOpen, setUncontrolledOpen] = React.useState(props.defaultOpen ?? false)\n const preferences = useUiPreferences()\n const { t, dir } = useMessages()\n const open = props.open ?? uncontrolledOpen\n // The value prop is one more declaration, captured afresh at every opening.\n useDeclaration(state, value, open && value !== undefined)\n // Each opening starts clean (cleared on closing: the content records its values on mount).\n React.useEffect(() => {\n if (!open) changes.current = { initial: new Map(), changed: new Set() }\n }, [open])\n const commit = (next: boolean) => {\n setUncontrolledOpen(next)\n onOpenChange?.(next)\n }\n const request = (next: boolean) => {\n // Ask only when there are unsaved changes; an untouched dialog closes at once.\n const declarations = [...declared.current.values()]\n const { initial, changed } = changes.current\n const edited = [...changed].filter(\n (element) =>\n element.isConnected && isControl(element) && controlValue(element) !== initial.get(element)\n )\n const unsaved = declarations.length\n ? declarations.some((entry) => entry.current !== entry.opened)\n : edited.length > 0\n // A visible control changed but no declaration did: the dialog declared only part of its\n // state. (Hidden inputs mirror Radix switches, checkboxes and selects for form submission.)\n const undeclared = edited.filter((element) => !element.closest('[aria-hidden=\"true\"]'))\n if (declarations.length && !unsaved && undeclared.length)\n console.warn(\n '[Dialog] A control changed while every declared value is unchanged; declare the full form state with `value` or useDialogValue (ADR 016):',\n undeclared\n .map(\n (element) =>\n element.id ||\n element.getAttribute('name') ||\n element.getAttribute('aria-label') ||\n element.outerHTML.slice(0, 120)\n )\n .join(', ')\n )\n const editing = mode !== 'view' && mode !== 'confirm' && unsaved\n if (!next && editing && preferences.confirmDialogClose) setConfirming(true)\n else commit(next)\n }\n return (\n <DialogContentContext.Provider value={state}>\n <DialogPrimitive.Root data-slot=\"dialog\" {...props} open={open} onOpenChange={request}>\n {children}\n </DialogPrimitive.Root>\n {confirming && open && (\n <Dialog mode=\"confirm\" open onOpenChange={(next) => !next && setConfirming(false)}>\n <DialogContent showCloseButton={false} className=\"z-[70] sm:max-w-md\" dir={dir}>\n <DialogHeader>\n <DialogTitle>{t('إغلاق النموذج؟')}</DialogTitle>\n <DialogDescription>\n {t('قد تفقد التغييرات التي لم تحفظها. يمكنك متابعة التحرير أو إغلاق النموذج.')}\n </DialogDescription>\n </DialogHeader>\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" onClick={() => setConfirming(false)}>\n {t('متابعة التحرير')}\n </Button>\n <Button\n type=\"button\"\n variant=\"destructive\"\n onClick={() => {\n setConfirming(false)\n commit(false)\n }}\n >\n {t('إغلاق دون حفظ')}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )}\n </DialogContentContext.Provider>\n )\n}\n\nfunction DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {\n return <DialogPrimitive.Trigger data-slot=\"dialog-trigger\" {...props} />\n}\n\nfunction DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {\n return <DialogPrimitive.Portal data-slot=\"dialog-portal\" {...props} />\n}\n\nfunction DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {\n return <DialogPrimitive.Close data-slot=\"dialog-close\" {...props} />\n}\n\nfunction DialogOverlay({\n className,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {\n return (\n <DialogPrimitive.Overlay\n data-slot=\"dialog-overlay\"\n className={cn(\n 'fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0',\n className\n )}\n {...props}\n />\n )\n}\n\nfunction DialogContent({\n ref,\n className,\n children,\n showCloseButton = true,\n onInputCapture,\n onChangeCapture,\n onFocusCapture,\n onPointerDownCapture,\n onKeyDownCapture,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Content> & {\n showCloseButton?: boolean\n}) {\n const dialog = React.useContext(DialogContentContext)\n const content = dialog?.content\n const { t } = useMessages()\n // Controls: their values on mount, or when they take focus before a change, are the\n // baseline; a change marks them for comparison on closing.\n React.useEffect(() => {\n const node = content?.current\n if (!dialog || !node) return\n for (const element of node.querySelectorAll(CONTROLS)) remember(dialog.changes.current, element)\n }, [dialog, content])\n // The user's first interaction ends the opening: declared values are compared from here on.\n const settle = () => {\n for (const entry of dialog?.declared.current.values() ?? []) entry.settled = true\n }\n const touch = (target: EventTarget) => {\n settle()\n const element = target as Element\n if (dialog && isControl(element)) dialog.changes.current.changed.add(element)\n }\n return (\n <DialogPortal data-slot=\"dialog-portal\">\n <DialogOverlay />\n <DialogPrimitive.Content\n ref={(node) => {\n if (content) content.current = node\n if (typeof ref === 'function') return ref(node)\n if (ref) ref.current = node\n }}\n onFocusCapture={(event) => {\n if (dialog) remember(dialog.changes.current, event.target as Element, true)\n onFocusCapture?.(event)\n }}\n onInputCapture={(event) => {\n touch(event.target)\n onInputCapture?.(event)\n }}\n onChangeCapture={(event) => {\n touch(event.target)\n onChangeCapture?.(event)\n }}\n onPointerDownCapture={(event) => {\n settle()\n onPointerDownCapture?.(event)\n }}\n onKeyDownCapture={(event) => {\n settle()\n onKeyDownCapture?.(event)\n }}\n data-slot=\"dialog-content\"\n // Tools and tests tell a confirmation from an editor or a details view by this.\n data-dialog-mode={dialog?.mode.current ?? 'edit'}\n className={cn(\n 'fixed top-[50%] start-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] ltr:translate-x-[-50%] rtl:-translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg',\n className\n )}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close\n data-slot=\"dialog-close\"\n className=\"absolute top-4 end-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\"\n >\n <XIcon />\n <span className=\"sr-only\">{t('إغلاق')}</span>\n </DialogPrimitive.Close>\n )}\n </DialogPrimitive.Content>\n </DialogPortal>\n )\n}\n\nfunction DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot=\"dialog-header\"\n className={cn('flex flex-col gap-2 text-center sm:text-start', className)}\n {...props}\n />\n )\n}\n\nfunction DialogFooter({\n className,\n showCloseButton = false,\n children,\n ...props\n}: React.ComponentProps<'div'> & {\n showCloseButton?: boolean\n}) {\n const { t } = useMessages()\n return (\n <div\n data-slot=\"dialog-footer\"\n className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close asChild>\n <Button variant=\"outline\">{t('إغلاق')}</Button>\n </DialogPrimitive.Close>\n )}\n </div>\n )\n}\n\nfunction DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {\n return (\n <DialogPrimitive.Title\n data-slot=\"dialog-title\"\n className={cn('text-lg leading-none font-semibold', className)}\n {...props}\n />\n )\n}\n\nfunction DialogDescription({\n className,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Description>) {\n return (\n <DialogPrimitive.Description\n data-slot=\"dialog-description\"\n className={cn('text-sm text-muted-foreground', className)}\n {...props}\n />\n )\n}\n\nexport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogOverlay,\n DialogPortal,\n DialogTitle,\n DialogTrigger,\n DialogValue,\n useDialogValue,\n}\n",
|
|
13
13
|
"target": "inertia/components/ui/dialog.tsx"
|
|
14
14
|
}
|
|
15
15
|
],
|
|
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
|
],
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "file-input",
|
|
3
|
+
"type": "registry:ui",
|
|
4
|
+
"registryDependencies": [
|
|
5
|
+
"button",
|
|
6
|
+
"messages"
|
|
7
|
+
],
|
|
8
|
+
"dependencies": [
|
|
9
|
+
"cn@0.3.0",
|
|
10
|
+
"lucide-react@1.47.0"
|
|
11
|
+
],
|
|
12
|
+
"files": [
|
|
13
|
+
{
|
|
14
|
+
"path": "registry/ui/file-input.tsx",
|
|
15
|
+
"type": "registry:ui",
|
|
16
|
+
"content": "import * as React from \"react\";\nimport { FileUp } from \"lucide-react\";\nimport { cn } from \"cn\";\nimport { Button } from \"~/components/ui/button\";\nimport { useMessages } from \"~/components/ui/messages\";\n\ntype FileInputProps = Omit<\n React.ComponentProps<\"input\">,\n \"type\" | \"value\" | \"onChange\"\n> & {\n id: string;\n /** The id of the field's label, read with the button so keyboard users hear the field name. */\n labelId?: string;\n /** Called with the chosen files; an empty list when the choice is cleared. */\n onFilesChange?: (files: File[]) => void;\n};\n\n/**\n * A file field in the interface language: a button that opens the file picker and the name of\n * the chosen file, instead of the browser's native control and its untranslated text. The native\n * input stays in the document, hidden, so a `<Label htmlFor={id}>` still names it and forms and\n * tests can set its files; keyboard users reach the button, which `labelId` describes.\n */\nfunction FileInput({\n id,\n labelId,\n className,\n disabled,\n multiple,\n onFilesChange,\n \"aria-describedby\": describedBy,\n ...props\n}: FileInputProps) {\n const { t } = useMessages();\n const input = React.useRef<HTMLInputElement>(null);\n const [names, setNames] = React.useState<string[]>([]);\n const chosen = names.length ? names.join(\"، \") : t(\"لم يُختر أي ملف\");\n return (\n <div\n data-slot=\"file-input\"\n className={cn(\n \"flex h-9 w-full min-w-0 items-center gap-2 rounded-md border border-input bg-transparent ps-1 pe-3 shadow-xs dark:bg-input/30\",\n disabled && \"cursor-not-allowed opacity-50\",\n className,\n )}\n >\n <input\n {...props}\n ref={input}\n id={id}\n type=\"file\"\n multiple={multiple}\n disabled={disabled}\n hidden\n onChange={(event) => {\n const files = [...(event.target.files ?? [])];\n setNames(files.map((file) => file.name));\n onFilesChange?.(files);\n }}\n />\n <Button\n type=\"button\"\n variant=\"secondary\"\n size=\"sm\"\n disabled={disabled}\n aria-describedby={[labelId, `${id}-chosen`, describedBy]\n .filter(Boolean)\n .join(\" \")}\n onClick={() => input.current?.click()}\n >\n <FileUp size={14} aria-hidden=\"true\" />\n {names.length ? t(\"تغيير الملف\") : t(\"اختيار ملف\")}\n </Button>\n <span\n id={`${id}-chosen`}\n data-slot=\"file-input-name\"\n aria-live=\"polite\"\n className={cn(\n \"min-w-0 truncate text-sm\",\n names.length ? \"text-foreground\" : \"text-muted-foreground\",\n )}\n title={names.join(\"، \") || undefined}\n >\n {chosen}\n </span>\n </div>\n );\n}\n\nexport { FileInput };\n",
|
|
17
|
+
"target": "inertia/components/ui/file-input.tsx"
|
|
18
|
+
}
|
|
19
|
+
],
|
|
20
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
21
|
+
}
|
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
|
],
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "list-filters",
|
|
3
|
+
"type": "registry:ui",
|
|
4
|
+
"registryDependencies": [
|
|
5
|
+
"badge",
|
|
6
|
+
"button",
|
|
7
|
+
"checkbox",
|
|
8
|
+
"command",
|
|
9
|
+
"input",
|
|
10
|
+
"popover",
|
|
11
|
+
"resource-field",
|
|
12
|
+
"resource-value",
|
|
13
|
+
"messages"
|
|
14
|
+
],
|
|
15
|
+
"dependencies": [
|
|
16
|
+
"axios@1.19.0",
|
|
17
|
+
"lucide-react@1.47.0"
|
|
18
|
+
],
|
|
19
|
+
"files": [
|
|
20
|
+
{
|
|
21
|
+
"path": "registry/ui/list-filters.tsx",
|
|
22
|
+
"type": "registry:ui",
|
|
23
|
+
"content": "import { useEffect, useId, useRef, useState, type KeyboardEvent } from 'react'\nimport axios from 'axios'\nimport { ChevronDown, X } from 'lucide-react'\nimport type { CalendarPreference, ResourceField, ResourceList, SerializedRecord } from 'adula'\nimport { Badge } from '~/components/ui/badge'\nimport { Button } from '~/components/ui/button'\nimport { Checkbox } from '~/components/ui/checkbox'\nimport {\n Command,\n CommandEmpty,\n CommandGroup,\n CommandInput,\n CommandItem,\n CommandList,\n} from '~/components/ui/command'\nimport { Input } from '~/components/ui/input'\nimport { Popover, PopoverContent, PopoverTrigger } from '~/components/ui/popover'\nimport { FieldControl } from '~/components/ui/resource-field'\nimport { useMessages, type Translate } from '~/components/ui/messages'\nimport {\n CURRENCY_LABEL,\n PERCENT_LABEL,\n fieldOptions,\n formatDate,\n formatDatetime,\n inputValue,\n moneyDisplay,\n optionLabel,\n parseValue,\n relationLabel,\n type Option,\n} from '~/components/ui/resource-value'\nimport { decimalDisplay, decimalScale } from '~/components/ui/field_values'\nimport {\n FILTER_IN_LIMIT,\n choiceFilter,\n chosenValues,\n filterAllowed,\n filterMode,\n inclusiveDatetime,\n normalizeFilter,\n singleChoice,\n type FieldFilter,\n} from '~/components/ui/list_query'\n\n/** Labels of chosen related records, remembered so chips stay readable after a reload. */\nexport type FilterLabels = Record<string, Record<string, string>>\n\n/**\n * A bound or value as the user reads it: lookup or option label, record title, formatted\n * date, amount, decimal or percent.\n */\nexport function filterValueLabel(\n field: ResourceField,\n value: string,\n context: {\n options?: Option[]\n related?: SerializedRecord[]\n labels?: Record<string, string>\n calendar: CalendarPreference\n t: Translate\n /** The interface language of option labels and number formats; Arabic by default. */\n language?: string\n }\n) {\n const language = context.language ?? 'ar'\n switch (field.type) {\n case 'lookup':\n return context.options?.find((option) => option.value === value)?.label ?? value\n case 'enum':\n case 'multiSelect':\n return optionLabel(field, value, language)\n case 'boolean':\n return value === 'true' ? context.t('نعم') : context.t('لا')\n case 'belongsTo':\n case 'user':\n case 'manyToMany': {\n const row = context.related?.find((item) => String(item.id) === value)\n return context.labels?.[value] ?? (row ? relationLabel(row, value) : `#${value}`)\n }\n case 'money':\n return `${moneyDisplay(value)} ${context.t(CURRENCY_LABEL)}`\n case 'decimal':\n return decimalDisplay(value, decimalScale(field), language)\n case 'percent':\n return `${decimalDisplay(value, decimalScale(field), language)}${context.t(PERCENT_LABEL)}`\n case 'date':\n return formatDate(value, context.calendar)\n case 'datetime':\n return formatDatetime(value, context.calendar)\n default:\n return value\n }\n}\n\n/** The chip text of one active filter, without the field label. */\nexport function describeFilter(filter: FieldFilter, value: (raw: string) => string, t: Translate) {\n switch (filter.op) {\n case 'eq':\n return value(filter.value)\n case 'in':\n return filter.values.map(value).join(t('، '))\n case 'range':\n if (filter.gte && filter.lte)\n return t('من {from} إلى {to}', {\n from: value(filter.gte),\n to: value(filter.lte),\n })\n return filter.gte\n ? t('من {from}', { from: value(filter.gte) })\n : t('إلى {to}', { to: value(filter.lte ?? '') })\n case 'empty':\n return filter.empty ? t('فارغ') : t('غير فارغ')\n }\n}\n\n/**\n * One field's filter: «أيٌّ من» for lookups, options, text and related records, «يحتوي على»\n * one option or linked record for multiSelect and manyToMany, «من / إلى» for numbers,\n * amounts, decimals, percents and dates, نعم/لا for booleans and «فارغ / غير فارغ» for\n * every field. Changes stay a draft until «تطبيق».\n */\nexport function FilterControl({\n resource,\n field,\n filter,\n options,\n related,\n labels,\n onRemember,\n onApply,\n}: {\n resource: string\n field: ResourceField\n filter?: FieldFilter\n options?: Option[]\n related?: SerializedRecord[]\n labels?: Record<string, string>\n onRemember?: (choices: Option[]) => void\n onApply: (filter: FieldFilter | null) => void\n}) {\n const { t, label, locale } = useMessages()\n const [open, setOpen] = useState(false)\n const [draft, setDraft] = useState<FieldFilter | null>(filter ?? null)\n const [error, setError] = useState('')\n const mode = filterMode(field.type)\n const name = label(field.label)\n const id = `filter-${field.key}`\n const count = filter?.op === 'in' ? filter.values.length : filter ? 1 : 0\n const apply = (next: FieldFilter | null) => {\n setError('')\n if (next?.op === 'in' && next.values.length > FILTER_IN_LIMIT) {\n setError(t('يمكن اختيار {count} قيمة كحد أقصى.', { count: FILTER_IN_LIMIT }))\n return\n }\n if (next && !filterAllowed(field.type, next)) {\n setError(t('لا يدعم هذا الحقل هذا النوع من التصفية.'))\n return\n }\n setOpen(false)\n onApply(normalizeFilter(next))\n }\n const empty = draft?.op === 'empty' ? draft.empty : null\n return (\n <Popover\n open={open}\n onOpenChange={(next) => {\n setOpen(next)\n if (next) {\n setDraft(filter ?? null)\n setError('')\n }\n }}\n >\n <PopoverTrigger asChild>\n <Button\n id={id}\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n aria-label={t('تصفية {field}', { field: name })}\n className={`h-9 gap-2 text-xs font-normal ${filter ? 'border-primary/60' : ''}`}\n >\n {name}\n {count > 0 && (\n <Badge variant=\"secondary\" className=\"h-5 px-1.5 tabular-nums\">\n {count}\n </Badge>\n )}\n <ChevronDown className=\"opacity-50\" />\n </Button>\n </PopoverTrigger>\n <PopoverContent className=\"w-72 p-0\" align=\"start\">\n <div className=\"border-b px-3 py-2 text-xs font-medium\">\n {t('تصفية {field}', { field: name })}\n </div>\n <div className=\"p-3\">\n {mode === 'boolean' ? (\n <div role=\"group\" aria-label={name} className=\"flex gap-2\">\n {(['true', 'false'] as const).map((value) => {\n const on = draft?.op === 'eq' && draft.value === value\n return (\n <Button\n key={value}\n type=\"button\"\n size=\"sm\"\n variant={on ? 'default' : 'outline'}\n aria-pressed={on}\n className=\"flex-1\"\n onClick={() => setDraft(on ? null : { op: 'eq', value })}\n >\n {value === 'true' ? t('نعم') : t('لا')}\n </Button>\n )\n })}\n </div>\n ) : mode === 'range' ? (\n <RangeInputs\n field={field}\n filter={draft?.op === 'range' ? draft : undefined}\n onChange={(next) => setDraft(next)}\n onError={setError}\n />\n ) : mode === 'choice' && LISTED.has(field.type) ? (\n <ChoiceList\n resource={resource}\n field={field}\n values={chosenValues(draft ?? undefined)}\n options={\n field.type === 'enum' || field.type === 'multiSelect'\n ? fieldOptions(field, locale)\n : options\n }\n related={related}\n labels={labels}\n onRemember={onRemember}\n onChange={(values) => setDraft(choiceFilter(field.type, values))}\n />\n ) : mode === 'choice' ? (\n <TextValues\n name={name}\n values={chosenValues(draft ?? undefined)}\n onChange={(values) => setDraft({ op: 'in', values })}\n />\n ) : (\n <Input\n aria-label={t('قيمة {field}', { field: name })}\n className=\"h-9 text-xs\"\n value={draft?.op === 'eq' ? draft.value : ''}\n onChange={(event) => setDraft({ op: 'eq', value: event.target.value })}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault()\n apply(draft)\n }\n }}\n />\n )}\n <div\n role=\"group\"\n aria-label={t('القيم الفارغة')}\n className=\"mt-3 flex gap-2 border-t pt-3\"\n >\n {[true, false].map((value) => (\n <Button\n key={String(value)}\n type=\"button\"\n size=\"xs\"\n variant={empty === value ? 'secondary' : 'ghost'}\n aria-pressed={empty === value}\n className=\"flex-1\"\n onClick={() => setDraft(empty === value ? null : { op: 'empty', empty: value })}\n >\n {value ? t('فارغ') : t('غير فارغ')}\n </Button>\n ))}\n </div>\n {error && (\n <p role=\"alert\" className=\"mt-2 text-xs text-destructive\">\n {error}\n </p>\n )}\n </div>\n <div className=\"flex justify-between gap-2 border-t px-3 py-2\">\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" onClick={() => apply(null)}>\n {t('إزالة التصفية')}\n </Button>\n <Button type=\"button\" size=\"sm\" onClick={() => apply(draft)}>\n {t('تطبيق')}\n </Button>\n </div>\n </PopoverContent>\n </Popover>\n )\n}\n\n/** Choice fields whose values come from a list: lookups, options or related records. */\nconst LISTED = new Set(['lookup', 'enum', 'multiSelect', 'belongsTo', 'user', 'manyToMany'])\n/** Related records searched through the target resource's list route. */\nconst REMOTE = new Set(['belongsTo', 'user', 'manyToMany'])\n\n/**\n * Inclusive bounds; dates use the field's own control, so the calendar preference applies.\n * Numbers accept Arabic-Indic digits and the Arabic decimal separator (parseValue).\n */\nfunction RangeInputs({\n field,\n filter,\n onChange,\n onError,\n}: {\n field: ResourceField\n filter?: FieldFilter & { op: 'range' }\n onChange: (filter: FieldFilter | null) => void\n onError: (message: string) => void\n}) {\n const { t, label } = useMessages()\n const [text, setText] = useState({\n gte: filter?.gte ? inputValue(field, filter.gte) : '',\n lte: filter?.lte ? inputValue(field, filter.lte) : '',\n })\n const bound = (raw: string, side: 'gte' | 'lte') => {\n const parsed = parseValue(field, field.type === 'datetime' ? inclusiveDatetime(raw, side) : raw)\n return parsed === null || parsed === undefined ? undefined : String(parsed)\n }\n const change = (side: 'gte' | 'lte', raw: string) => {\n const next = { ...text, [side]: raw }\n setText(next)\n try {\n onError('')\n onChange({ op: 'range', gte: bound(next.gte, 'gte'), lte: bound(next.lte, 'lte') })\n } catch (error) {\n // Keep partial input; the previous valid bounds stay in the draft.\n onError(error instanceof Error ? t(error.message) : t('قيمة غير صالحة'))\n }\n }\n const name = label(field.label)\n const dated = field.type === 'date' || field.type === 'datetime'\n return (\n <div className=\"grid gap-3\">\n {(['gte', 'lte'] as const).map((side) => {\n const caption = side === 'gte' ? t('من') : t('إلى')\n const id = `filter-${field.key}-${side}`\n return (\n <label key={side} htmlFor={id} className=\"grid gap-1 text-xs text-muted-foreground\">\n {caption}\n {dated ? (\n <FieldControl\n field={field}\n id={id}\n value={text[side]}\n label={t('{bound} · {field}', { bound: caption, field: name })}\n onChange={(raw) => change(side, raw)}\n />\n ) : (\n <Input\n id={id}\n dir=\"ltr\"\n inputMode={field.type === 'integer' ? 'numeric' : 'decimal'}\n className=\"h-9 text-xs tabular-nums\"\n value={text[side]}\n onChange={(event) => change(side, event.target.value)}\n />\n )}\n </label>\n )\n })}\n </div>\n )\n}\n\n/**\n * «أيٌّ من»: lookup or field options, or related records searched through the server. A\n * multiSelect or manyToMany filter is «يحتوي على» one option or record.\n */\nfunction ChoiceList({\n resource,\n field,\n values,\n options,\n related = [],\n labels = {},\n onRemember,\n onChange,\n}: {\n resource: string\n field: ResourceField\n values: string[]\n options?: Option[]\n related?: SerializedRecord[]\n labels?: Record<string, string>\n onRemember?: (choices: Option[]) => void\n onChange: (values: string[]) => void\n}) {\n const { t, label } = useMessages()\n const remote = REMOTE.has(field.type)\n const single = singleChoice(field.type)\n const [term, setTerm] = useState('')\n const [found, setFound] = 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 let choices: Option[]\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 choices = users.data.data\n } else {\n const target = (field as ResourceField & { resource?: string }).resource\n const response = await axios.get<ResourceList>(`/resources/${target}`, {\n params: {\n limit: 50,\n estimate: 'false',\n ...(search ? { search } : {}),\n },\n headers: { Accept: 'application/json' },\n })\n choices = response.data.data.map((row) => ({\n value: String(row.id),\n label: relationLabel(row, row.id),\n }))\n }\n setFound(choices)\n onRemember?.(choices)\n } catch {\n setFound([])\n } finally {\n setBusy(false)\n }\n }\n // The list mounts when the popover opens; related records load once per opening.\n const first = useRef(load)\n useEffect(() => {\n if (remote) void first.current('')\n }, [remote])\n const known = new Map<string, string>()\n for (const row of related) known.set(String(row.id), relationLabel(row, row.id))\n for (const [value, text] of Object.entries(labels)) known.set(value, text)\n const base = remote ? (found ?? []) : (options ?? [])\n // Chosen values stay listed even when the current search does not return them.\n const listed = [\n ...values\n .filter((value) => !base.some((option) => option.value === value))\n .map((value) => ({ value, label: known.get(value) ?? `#${value}` })),\n ...base.filter((option) => String(option.value) !== ''),\n ]\n const toggle = (value: string) =>\n onChange(\n values.includes(value) ? values.filter((entry) => entry !== value) : [...values, value]\n )\n return (\n <div className=\"grid gap-2\">\n <span className=\"text-xs text-muted-foreground\">\n {single ? t('يحتوي على') : t('أيٌّ من')}\n </span>\n <Command shouldFilter={!remote} className=\"rounded-md border\">\n <CommandInput\n placeholder={remote ? t('ابحث في السجلات المرتبطة') : t('ابحث في الخيارات')}\n aria-label={t('البحث في {field}', { field: label(field.label) })}\n value={term}\n onValueChange={(next) => {\n setTerm(next)\n if (!remote) return\n clearTimeout(timer.current)\n timer.current = setTimeout(() => void load(next), 300)\n }}\n />\n <CommandList id={listId} className=\"max-h-56\">\n <CommandEmpty>{busy ? t('جارٍ البحث...') : t('لا توجد خيارات مطابقة')}</CommandEmpty>\n <CommandGroup>\n {listed.map((option) => {\n const on = values.includes(option.value)\n return (\n <CommandItem\n key={option.value}\n value={remote ? option.value : `${option.label} ${option.value}`}\n aria-checked={on}\n onSelect={() => toggle(option.value)}\n >\n <Checkbox\n checked={on}\n tabIndex={-1}\n aria-hidden\n className=\"pointer-events-none\"\n />\n <span className=\"truncate\">{option.label}</span>\n </CommandItem>\n )\n })}\n </CommandGroup>\n </CommandList>\n </Command>\n </div>\n )\n}\n\n/** «أيٌّ من» for free text: Enter adds a value; each value is removable. */\nfunction TextValues({\n name,\n values,\n onChange,\n}: {\n name: string\n values: string[]\n onChange: (values: string[]) => void\n}) {\n const { t } = useMessages()\n const [text, setText] = useState('')\n const add = (event: KeyboardEvent<HTMLInputElement>) => {\n if (event.key !== 'Enter') return\n event.preventDefault()\n const value = text.trim()\n if (value && !values.includes(value)) onChange([...values, value])\n setText('')\n }\n return (\n <div className=\"grid gap-2\">\n <span className=\"text-xs text-muted-foreground\">{t('أيٌّ من')}</span>\n <Input\n aria-label={t('قيمة {field}', { field: name })}\n className=\"h-9 text-xs\"\n value={text}\n placeholder={t('اكتب قيمة ثم اضغط Enter')}\n onChange={(event) => setText(event.target.value)}\n onKeyDown={add}\n />\n {values.length > 0 && (\n <ul className=\"flex flex-wrap gap-1\">\n {values.map((value) => (\n <li key={value}>\n <Badge variant=\"secondary\" className=\"gap-1 font-normal\">\n {value}\n <button\n type=\"button\"\n aria-label={t('إزالة {value}', { value })}\n className=\"text-muted-foreground hover:text-foreground\"\n onClick={() => onChange(values.filter((entry) => entry !== value))}\n >\n <X size={12} />\n </button>\n </Badge>\n </li>\n ))}\n </ul>\n )}\n </div>\n )\n}\n",
|
|
24
|
+
"target": "inertia/components/ui/list-filters.tsx"
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
"path": "registry/ui/list_query.ts",
|
|
28
|
+
"type": "registry:ui",
|
|
29
|
+
"content": "export const FILTER_IN_LIMIT = 50\nexport const BULK_LIMIT = 100\n/*\n * List query helpers shared by the data table (ADR 046): operator filters in the URL,\n * saved-view round trips, the server export link and server error messages. Pure and\n * import-free so the registry tests run it directly.\n */\n\n/** One active filter of a field; `eq` is the scalar equality the list always accepted. */\nexport type FieldFilter =\n | { op: 'eq'; value: string }\n | { op: 'in'; values: string[] }\n | { op: 'range'; gte?: string; lte?: string }\n | { op: 'empty'; empty: boolean }\n\n/** The shape a saved view stores for one field: a scalar or one operator object. */\nexport type SavedFilterValue =\n | string\n | number\n | boolean\n | null\n | { in: (string | number)[] }\n | { gte?: string | number; lte?: string | number }\n | { empty: boolean }\n\n/** How the filter control of a field type behaves. */\nexport type FilterMode = 'choice' | 'range' | 'boolean' | 'text'\n\nconst CHOICE = new Set([\n 'lookup',\n 'enum',\n 'belongsTo',\n 'user',\n 'string',\n 'text',\n 'email',\n 'phone',\n 'url',\n 'multiSelect',\n 'manyToMany',\n])\nconst RANGE = new Set(['integer', 'money', 'decimal', 'percent', 'date', 'datetime'])\n/** Several values per record: the server matches one member (equality) or emptiness only. */\nconst MEMBER = new Set(['multiSelect', 'manyToMany'])\n\nexport function filterMode(type: string): FilterMode {\n if (type === 'boolean') return 'boolean'\n if (RANGE.has(type)) return 'range'\n if (CHOICE.has(type)) return 'choice'\n return 'text'\n}\n\n/** Whether a choice filter picks one member (multiSelect, manyToMany) instead of «أيٌّ من». */\nexport function singleChoice(type: string) {\n return MEMBER.has(type)\n}\n\n/**\n * The draft of a choice control: «أيٌّ من» is `in`; a member filter keeps only the latest\n * choice as equality, since the server accepts no `in` for several-valued fields.\n */\nexport function choiceFilter(type: string, values: string[]): FieldFilter | null {\n const chosen = values.filter(Boolean)\n if (!singleChoice(type)) return { op: 'in', values: chosen }\n const last = chosen.at(-1)\n return last ? { op: 'eq', value: last } : null\n}\n\n/**\n * Whether the filter controls emit this operator for the field type, each one the server\n * accepts (ADR 046): `in` for choices except member fields, ranges for numbers and dates,\n * equality and emptiness for every type.\n */\nexport function filterAllowed(type: string, filter: FieldFilter) {\n switch (filter.op) {\n case 'eq':\n case 'empty':\n return true\n case 'in':\n return filterMode(type) === 'choice' && !singleChoice(type)\n case 'range':\n return filterMode(type) === 'range'\n }\n}\n\nconst prefix = (key: string) => `filters[${key}]`\n\n/** Reads the filters of the given field keys from the list URL. */\nexport function readFilters(params: URLSearchParams, keys: string[]) {\n const filters: Record<string, FieldFilter> = {}\n for (const key of keys) {\n const base = prefix(key)\n const empty = params.get(`${base}[empty]`)\n const list = params.getAll(`${base}[in][]`)\n const joined = params.get(`${base}[in]`)\n const gte = params.get(`${base}[gte]`)\n const lte = params.get(`${base}[lte]`)\n const value = params.get(base)\n if (empty === 'true' || empty === 'false')\n filters[key] = { op: 'empty', empty: empty === 'true' }\n else if (list.length || joined) {\n const values = (list.length ? list : joined!.split(','))\n .map((entry) => entry.trim())\n .filter(Boolean)\n if (values.length) filters[key] = { op: 'in', values }\n } else if (gte || lte)\n filters[key] = {\n op: 'range',\n ...(gte ? { gte } : {}),\n ...(lte ? { lte } : {}),\n }\n else if (value) filters[key] = { op: 'eq', value }\n }\n return filters\n}\n\n/** Removes every parameter of one field's filter, whatever its operator. */\nexport function clearFilter(params: URLSearchParams, key: string) {\n const base = prefix(key)\n for (const name of [...params.keys()])\n if (name === base || name.startsWith(`${base}[`)) params.delete(name)\n}\n\n/**\n * Writes one field's filter. A single choice stays plain equality; several are\n * `[in]=a,b`, or repeated `[in][]` when a value itself contains a comma.\n */\nexport function writeFilter(params: URLSearchParams, key: string, filter: FieldFilter | null) {\n clearFilter(params, key)\n if (!filter) return\n const base = prefix(key)\n switch (filter.op) {\n case 'eq':\n if (filter.value) params.set(base, filter.value)\n return\n case 'in': {\n const values = [...new Set(filter.values.filter(Boolean))]\n if (values.length === 1) params.set(base, values[0])\n else if (values.some((value) => value.includes(',')))\n for (const value of values) params.append(`${base}[in][]`, value)\n else if (values.length) params.set(`${base}[in]`, values.join(','))\n return\n }\n case 'range':\n if (filter.gte) params.set(`${base}[gte]`, filter.gte)\n if (filter.lte) params.set(`${base}[lte]`, filter.lte)\n return\n case 'empty':\n params.set(`${base}[empty]`, String(filter.empty))\n }\n}\n\n/** A filter with nothing to apply (no values, no bounds) is no filter. */\nexport function normalizeFilter(filter: FieldFilter | null): FieldFilter | null {\n if (!filter) return null\n if (filter.op === 'eq') return filter.value ? filter : null\n if (filter.op === 'in') {\n const values = [...new Set(filter.values.filter(Boolean))]\n if (!values.length) return null\n return values.length === 1 ? { op: 'eq', value: values[0] } : { op: 'in', values }\n }\n if (filter.op === 'range') {\n if (!filter.gte && !filter.lte) return null\n return {\n op: 'range',\n ...(filter.gte ? { gte: filter.gte } : {}),\n ...(filter.lte ? { lte: filter.lte } : {}),\n }\n }\n return filter\n}\n\n/** The values a choice control shows as selected. */\nexport function chosenValues(filter: FieldFilter | undefined) {\n if (!filter) return []\n if (filter.op === 'eq') return [filter.value]\n if (filter.op === 'in') return filter.values\n return []\n}\n\nexport function toSavedFilter(filter: FieldFilter): SavedFilterValue {\n switch (filter.op) {\n case 'eq':\n return filter.value\n case 'in':\n return { in: filter.values }\n case 'range':\n return {\n ...(filter.gte ? { gte: filter.gte } : {}),\n ...(filter.lte ? { lte: filter.lte } : {}),\n }\n case 'empty':\n return { empty: filter.empty }\n }\n}\n\n/** Reads a stored saved-view value; anything unrecognised is dropped (null). */\nexport function fromSavedFilter(value: unknown): FieldFilter | null {\n if (value === null || value === undefined || value === '') return null\n if (['string', 'number', 'boolean'].includes(typeof value))\n return { op: 'eq', value: String(value) }\n if (typeof value !== 'object' || Array.isArray(value)) return null\n const entry = value as Record<string, unknown>\n if ('empty' in entry) {\n const empty = entry.empty\n if (empty === true || empty === 'true') return { op: 'empty', empty: true }\n if (empty === false || empty === 'false') return { op: 'empty', empty: false }\n return null\n }\n if ('in' in entry) {\n const list = Array.isArray(entry.in)\n ? entry.in\n : typeof entry.in === 'string'\n ? entry.in.split(',')\n : []\n return normalizeFilter({\n op: 'in',\n values: list.map((item) => String(item).trim()),\n })\n }\n if ('gte' in entry || 'lte' in entry) {\n const bound = (operand: unknown) =>\n operand === null || operand === undefined || operand === '' ? undefined : String(operand)\n return normalizeFilter({\n op: 'range',\n gte: bound(entry.gte),\n lte: bound(entry.lte),\n })\n }\n return null\n}\n\n/**\n * `GET /resources/:name/export` with the list's query (search, filters, tag, sort) but no\n * cursor; `format` 'xlsx' asks for an Excel workbook instead of CSV.\n */\nexport function exportHref(\n resource: string,\n params: URLSearchParams,\n format: 'csv' | 'xlsx' = 'csv'\n) {\n const query = new URLSearchParams(params)\n query.delete('cursor')\n query.delete('limit')\n query.delete('format')\n if (format === 'xlsx') query.set('format', 'xlsx')\n const suffix = query.toString()\n return `/resources/${resource}/export${suffix ? `?${suffix}` : ''}`\n}\n\n/** The `error.message` of an AdulaJS JSON error body (object, JSON text or nothing). */\nexport function serverMessage(data: unknown): string | null {\n let body = data\n if (typeof body === 'string') {\n try {\n body = JSON.parse(body)\n } catch {\n return null\n }\n }\n const message = (body as { error?: { message?: unknown } } | null)?.error?.message\n return typeof message === 'string' && message ? message : null\n}\n\n/** Selection helpers for bulk actions; ids are the string keys the table uses. */\nexport function toggleSelection(selected: Set<string>, id: string, on: boolean) {\n const next = new Set(selected)\n if (on) next.add(id)\n else next.delete(id)\n return next\n}\n\nexport function selectionState(selected: Set<string>, ids: string[]): boolean | 'indeterminate' {\n const count = ids.filter((id) => selected.has(id)).length\n if (!count) return false\n return count === ids.length ? true : 'indeterminate'\n}\n\n/** The bulk request body: numeric ids and the loaded rows' versions keyed by id. */\nexport function bulkPayload(\n action: string,\n ids: string[],\n rows: { id?: unknown; version?: unknown }[]\n) {\n const versions: Record<string, unknown> = {}\n const wanted = new Set(ids)\n for (const row of rows)\n if (wanted.has(String(row.id)) && row.version !== undefined && row.version !== null)\n versions[String(row.id)] = row.version\n return { action, ids: ids.map(Number), versions }\n}\n\n/**\n * A datetime range bound as typed (`YYYY-MM-DD` or `YYYY-MM-DDTHH:mm`, optionally `hijri:`)\n * made inclusive: «من» starts at the beginning of the chosen day or minute, «إلى» ends at\n * its last millisecond, so filtering «إلى ١ أكتوبر» keeps records of 1 October.\n */\nexport function inclusiveDatetime(raw: string, side: 'gte' | 'lte') {\n const value = raw.trim()\n if (!value) return value\n const [day, time] = value.split('T')\n if (!time) return `${day}T${side === 'gte' ? '00:00:00.000' : '23:59:59.999'}`\n if (/^\\d{2}:\\d{2}$/.test(time)) return `${day}T${time}${side === 'gte' ? ':00.000' : ':59.999'}`\n return value\n}\n\n/**\n * The URL of the list itself. While a record dialog is open over the list, the page URL is the\n * record's, so filters, sort and refresh read the list URL the dialog returns to instead (#104).\n */\nexport function listUrl(pageUrl: string, overlay?: { list?: unknown } | null) {\n return typeof overlay?.list === 'string' && overlay.list ? overlay.list : pageUrl\n}\n",
|
|
30
|
+
"target": "inertia/components/ui/list_query.ts"
|
|
31
|
+
}
|
|
32
|
+
],
|
|
33
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
34
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "long-dialog",
|
|
3
|
+
"type": "registry:ui",
|
|
4
|
+
"registryDependencies": [
|
|
5
|
+
"dialog"
|
|
6
|
+
],
|
|
7
|
+
"dependencies": [],
|
|
8
|
+
"files": [
|
|
9
|
+
{
|
|
10
|
+
"path": "registry/ui/long-dialog.tsx",
|
|
11
|
+
"type": "registry:ui",
|
|
12
|
+
"content": "import * as React from 'react'\nimport { cn } from 'cn'\nimport {\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from '~/components/ui/dialog'\n\n// Named after the Tailwind max-width each one applies from the small screen breakpoint up.\nconst widths = {\n lg: 'sm:max-w-lg',\n xl: 'sm:max-w-xl',\n '2xl': 'sm:max-w-2xl',\n '3xl': 'sm:max-w-3xl',\n '4xl': 'sm:max-w-4xl',\n '5xl': 'sm:max-w-5xl',\n} as const\n\ntype LongDialogContentProps = {\n title: React.ReactNode\n description?: React.ReactNode\n /**\n * Actions shown in the fixed footer: secondary actions first (pushed to the start side with\n * `sm:me-auto`), then «إلغاء» or «إغلاق» as outline inside `DialogClose`, then the primary.\n * Closing asks first only while something differs from how the dialog opened (Dialog).\n */\n footer?: React.ReactNode\n /** Dialog width from the small screen breakpoint up; phones always use the full width. */\n width?: keyof typeof widths\n /**\n * `content` (default) grows with the body up to the maximum height. `fill` takes the maximum\n * height from the first frame, for a body that loads after opening: the dialog's size never\n * changes when its data arrives, so the opening animation is never disturbed.\n */\n height?: 'content' | 'fill'\n children: React.ReactNode\n} & Omit<React.ComponentProps<typeof DialogContent>, 'title' | 'className' | 'children'>\n\n/**\n * The long dialog pattern (ADR 016): the header and footer stay fixed and only the body scrolls,\n * with a scrollbar that stays visible in both themes so the reader sees there is more below.\n * Place it inside a shadcn `Dialog`; the layout matches the record surface (resource-surface).\n */\nexport function LongDialogContent({\n title,\n description,\n footer,\n width = 'xl',\n height = 'content',\n children,\n ...props\n}: LongDialogContentProps) {\n return (\n <DialogContent\n // Anchored to the top, so content that loads after opening extends the dialog downward.\n // Clipped, not hidden: focus cannot scroll the header away; the body is the only scroller.\n className={cn(\n 'top-4 flex max-h-[calc(100dvh-2rem)] w-[calc(100vw-2rem)] translate-y-0 flex-col gap-0 overflow-clip p-0 sm:top-[5dvh] sm:max-h-[90dvh]',\n height === 'fill' && 'h-[calc(100dvh-2rem)] sm:h-[90dvh]',\n widths[width]\n )}\n data-long-dialog=\"\"\n {...props}\n >\n <DialogHeader className=\"shrink-0 border-b px-6 py-5 pe-12 text-start\">\n <DialogTitle>{title}</DialogTitle>\n {description && <DialogDescription>{description}</DialogDescription>}\n </DialogHeader>\n <div\n data-slot=\"long-dialog-body\"\n // overflow-y: scroll keeps the scrollbar on screen while idle; the gutter keeps the\n // content from shifting, and the thumb uses theme tokens to read in light and dark.\n className=\"min-h-0 flex-1 scroll-py-6 overflow-y-scroll overscroll-contain p-4 [scrollbar-color:var(--muted-foreground)_transparent] [scrollbar-gutter:stable] [scrollbar-width:thin] sm:p-6\"\n >\n {children}\n </div>\n {footer && (\n <DialogFooter className=\"shrink-0 border-t px-6 py-4\" data-slot=\"long-dialog-footer\">\n {footer}\n </DialogFooter>\n )}\n </DialogContent>\n )\n}\n",
|
|
13
|
+
"target": "inertia/components/ui/long-dialog.tsx"
|
|
14
|
+
}
|
|
15
|
+
],
|
|
16
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
17
|
+
}
|