@adula/ui 2.2.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/build/attachment-preview.json +1 -1
- package/build/breadcrumb.json +18 -0
- package/build/copy-button.json +21 -0
- package/build/data-table.json +3 -2
- package/build/dialog-param.json +17 -0
- package/build/dialog.json +1 -1
- package/build/file-input.json +21 -0
- package/build/list-filters.json +2 -2
- package/build/long-dialog.json +17 -0
- package/build/manifest.json +109 -69
- package/build/messages.json +2 -2
- package/build/record-assignments.json +3 -2
- package/build/record-collaboration.json +3 -2
- package/build/record-workflows.json +3 -2
- package/build/resource-actions.json +1 -1
- package/build/resource-bulk.json +1 -1
- package/build/resource-dashboard.json +1 -1
- package/build/resource-field.json +3 -2
- package/build/resource-form.json +2 -1
- package/build/resource-import.json +3 -2
- package/build/resource-page.json +2 -1
- package/build/resource-show.json +4 -2
- package/build/resource-surface.json +2 -1
- package/build/resource-value.json +4 -3
- package/build/slider.json +17 -0
- package/build/sortable-list.json +20 -0
- package/build/tabs.json +1 -1
- package/build/theme.css +48 -2
- package/build/user-avatar.json +17 -0
- package/package.json +1 -1
package/build/resource-page.json
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
"type": "registry:ui",
|
|
4
4
|
"registryDependencies": [
|
|
5
5
|
"button",
|
|
6
|
+
"card",
|
|
6
7
|
"data-table",
|
|
7
8
|
"resource-form",
|
|
8
9
|
"resource-show",
|
|
@@ -17,7 +18,7 @@
|
|
|
17
18
|
{
|
|
18
19
|
"path": "registry/ui/resource-page.tsx",
|
|
19
20
|
"type": "registry:ui",
|
|
20
|
-
"content": "import { Head, usePage } from '@inertiajs/react'\nimport { Link } from '@adonisjs/inertia/react'\nimport { Plus } from 'lucide-react'\nimport type {\n RecordPermissions,\n ResourceActivity,\n ResourceChildren,\n ResourceDescription,\n ResourceEditor,\n ResourceList,\n ResourceLookups,\n SavedView,\n ResourceShow as Show,\n} from 'adula'\nimport { Button } from '~/components/ui/button'\nimport { DataTable } from '~/components/ui/data-table'\nimport { ResourceForm } from '~/components/ui/resource-form'\nimport { ResourceShow } from '~/components/ui/resource-show'\nimport { ResourceImport } from '~/components/ui/resource-import'\nimport {\n ResourceSurface,\n closeRecord,\n openRecord,\n type RecordOverlay,\n type ResourcePresentation,\n} from '~/components/ui/resource-surface'\nimport { useMessages, type Translate } from '~/components/ui/messages'\n\n/** The discriminated view stays nested: Inertia's page typing flattens top-level unions. */\nexport type ResourceView =\n | {\n mode: 'index'\n resource: ResourceDescription\n lookups: ResourceLookups\n savedViews: SavedView[]\n /** `/resources/:name/trash`: the soft-deleted records, offered for restore (ADR 046). */\n trashed?: boolean\n }\n | { mode: 'form'; editor: ResourceEditor; permissions: RecordPermissions }\n | {\n mode: 'show'\n resource: ResourceDescription\n result: Show\n lookups: ResourceLookups\n childResources: Record<string, ResourceDescription>\n }\nexport type ResourcePageProps = {\n view: ResourceView\n /** Index pages receive the list as a top-level `inertia.scroll` prop so pages merge into `result.data`. */\n result?: ResourceList\n childrenData?: ResourceChildren\n activity?: ResourceActivity\n /** Set to page only when the user requests a non-modal form/detail override. */\n presentation?: ResourcePresentation\n}\ntype RecordView = Exclude<ResourceView, { mode: 'index' }>\n\n/** Title of a record dialog: «إضافة حساب», «تعديل · الحسابات» or «تفاصيل · الحسابات». */\nfunction recordTitle(view: RecordView, t: Translate) {\n if (view.mode === 'show') return t('تفاصيل · {resource}', { resource: view.resource.label })\n const create = view.editor.mode === 'create'\n // A singular record noun («حساب») reads better than the plural list label (#37).\n if (view.editor.recordLabel)\n return create\n ? t('إضافة {record}', { record: view.editor.recordLabel })\n : t('تعديل {record}', { record: view.editor.recordLabel })\n return create\n ? t('إضافة · {resource}', { resource: view.editor.label })\n : t('تعديل · {resource}', { resource: view.editor.label })\n}\n\nfunction RecordBody({\n view,\n childrenData,\n activity,\n onSaved,\n onCancel,\n onEdit,\n onAction,\n}: {\n view: RecordView\n childrenData?: ResourceChildren\n activity?: ResourceActivity\n onSaved?: (id: number) => void\n onCancel?: () => void\n onEdit?: () => void\n onAction?: (action: string) => void\n}) {\n return view.mode === 'form' ? (\n <ResourceForm\n key={`${view.editor.name}:${view.editor.record?.id ?? 'new'}`}\n editor={view.editor}\n permissions={view.permissions}\n onSaved={onSaved}\n onCancel={onCancel}\n onAction={onAction}\n />\n ) : (\n <ResourceShow\n key={`${view.resource.name}:${view.result.data.id}`}\n resource={view.resource}\n result={view.result}\n lookups={view.lookups}\n childResources={view.childResources}\n childrenData={childrenData}\n activity={activity}\n onEdit={onEdit}\n onAction={onAction}\n />\n )\n}\n\nexport function ResourcePage({\n view,\n result,\n childrenData,\n activity,\n presentation,\n}: ResourcePageProps) {\n // A record opened over this list by openRecord(); a client-only prop, never sent by the server.\n const overlay = usePage<{ overlay?: RecordOverlay }>().props.overlay\n const { t } = useMessages()\n const name = view.mode === 'form' ? view.editor.name : view.resource.name\n const label = view.mode === 'form' ? view.editor.label : view.resource.label\n const trashed = view.mode === 'index' && view.trashed === true\n const title =\n view.mode === 'index'\n ? trashed\n ? t('المحذوفات · {resource}', { resource: label })\n : label\n : recordTitle(view, t)\n const noun = view.mode === 'index' ? view.resource.recordLabel : null\n const createText =\n view.mode === 'index'\n ? (view.resource.createLabel ??\n (noun ? t('إضافة {record}', { record: noun }) : t('إضافة سجل')))\n : ''\n const overlayView = view.mode === 'index' ? (overlay?.view as RecordView | undefined) : undefined\n const overlayRecord =\n overlayView?.mode === 'form' ? overlayView.editor.record?.id : overlayView?.result.data.id\n const overlayId =\n overlayRecord === undefined || overlayRecord === null ? undefined : String(overlayRecord)\n return (\n <>\n <Head title={title} />\n {view.mode === 'index' && (\n <div className=\"mb-8 flex flex-wrap items-start justify-between gap-5\">\n <div>\n <h1 className=\"text-3xl font-semibold tracking-tight\">{title}</h1>\n <p className=\"mt-3 text-sm text-muted-foreground\">\n {trashed\n ? t('السجلات المحذوفة ضمن نطاقك؛ استعد ما تحتاجه منها إلى السجلات النشطة.')\n : t('سجلاتك ومتابعتك اليومية في مكان واحد.')}\n </p>\n </div>\n {view.mode === 'index' && view.resource.canCreate && !trashed && (\n <div className=\"flex flex-wrap gap-2\">\n <ResourceImport resource={name} label={label} />\n <Button asChild>\n <Link href={`/resources/${name}/create`}>\n <Plus size={16} />\n {createText}\n </Link>\n </Button>\n </div>\n )}\n </div>\n )}\n {view.mode === 'index' ? (\n <>\n {result ? (\n <DataTable\n key={`${name}:${trashed ? 'trash' : 'active'}`}\n resource={view.resource}\n result={result}\n lookups={view.lookups}\n savedViews={view.savedViews}\n trashed={trashed}\n />\n ) : null}\n {overlay && overlayView && overlayId !== undefined && (\n // Keyed by record, so saving an edit switches the same dialog to the details.\n <ResourceSurface\n key={`overlay:${name}:${overlayId}`}\n mode={overlayView.mode === 'form' ? 'edit' : 'view'}\n title={recordTitle(overlayView, t)}\n description={\n overlayView.mode === 'form'\n ? t('أكمل الحقول المطلوبة ثم احفظ السجل.')\n : t('راجع التفاصيل المتاحة لك وأكمل عملك.')\n }\n backHref={overlay.list}\n onClose={() => closeRecord(overlay)}\n >\n <RecordBody\n view={overlayView}\n childrenData={childrenData}\n activity={activity}\n onSaved={(id) =>\n void openRecord(name, id, 'show', {\n replace: true,\n changed: true,\n })\n }\n onCancel={() => void openRecord(name, overlayId, 'show', { replace: true })}\n onEdit={() => void openRecord(name, overlayId, 'edit', { replace: true })}\n onAction={(action) =>\n action === 'delete'\n ? closeRecord({ ...overlay, changed: true })\n : void openRecord(name, overlayId, 'show', {\n replace: true,\n changed: true,\n })\n }\n />\n </ResourceSurface>\n )}\n </>\n ) : (\n <ResourceSurface\n // Keyed by record, not mode: saving an edit shows the details in the same dialog.\n key={`${name}:${view.mode === 'form' ? (view.editor.record?.id ?? 'new') : view.result.data.id}`}\n mode={view.mode === 'form' ? 'edit' : 'view'}\n title={title}\n description={\n view.mode === 'form'\n ? t('أكمل الحقول المطلوبة ثم احفظ السجل.')\n : t('راجع التفاصيل المتاحة لك وأكمل عملك.')\n }\n backHref={`/resources/${name}`}\n presentation={presentation}\n >\n <RecordBody view={view} childrenData={childrenData} activity={activity} />\n </ResourceSurface>\n )}\n </>\n )\n}\n",
|
|
21
|
+
"content": "import { useEffect, useRef, useState, type ReactNode } from 'react'\nimport { Head, usePage } from '@inertiajs/react'\nimport { Link } from '@adonisjs/inertia/react'\nimport { Plus, Save } from 'lucide-react'\nimport type {\n RecordPermissions,\n ResourceActivity,\n ResourceChildren,\n ResourceDescription,\n ResourceEditor,\n ResourceList,\n ResourceLookups,\n SavedView,\n ResourceShow as Show,\n} from 'adula'\nimport { Button } from '~/components/ui/button'\nimport { DialogClose } from '~/components/ui/dialog'\nimport { Card, CardContent, CardHeader } from '~/components/ui/card'\nimport { Skeleton } from '~/components/ui/skeleton'\nimport { DataTable } from '~/components/ui/data-table'\nimport type { BulkAction } from '~/components/ui/resource-bulk'\nimport { ResourceForm } from '~/components/ui/resource-form'\nimport { ResourceShow } from '~/components/ui/resource-show'\nimport { ResourceImport } from '~/components/ui/resource-import'\nimport {\n RecordFooter,\n RecordFooterClose,\n ResourceSurface,\n closeCreated,\n closeRecord,\n fetchListRow,\n openCreate,\n openRecord,\n plainClick,\n prefetchCreate,\n useOverlayShell,\n useOverlayView,\n type RecordOverlay,\n type ResourcePresentation,\n} from '~/components/ui/resource-surface'\nimport { useMessages, type Translate } from '~/components/ui/messages'\n\n/** The discriminated view stays nested: Inertia's page typing flattens top-level unions. */\nexport type ResourceView =\n | {\n mode: 'index'\n resource: ResourceDescription\n lookups: ResourceLookups\n savedViews: SavedView[]\n /** The actor's bulk actions, sent with the list so its selection column renders at once (#108). */\n bulkActions?: BulkAction[]\n /** `/resources/:name/trash`: the soft-deleted records, offered for restore (ADR 046). */\n trashed?: boolean\n }\n | { mode: 'form'; editor: ResourceEditor; permissions: RecordPermissions }\n | {\n mode: 'show'\n resource: ResourceDescription\n result: Show\n lookups: ResourceLookups\n childResources: Record<string, ResourceDescription>\n }\nexport type ResourcePageProps = {\n view: ResourceView\n /** Index pages receive the list as a top-level `inertia.scroll` prop so pages merge into `result.data`. */\n result?: ResourceList\n childrenData?: ResourceChildren\n activity?: ResourceActivity\n /** Set to page only when the user requests a non-modal form/detail override. */\n presentation?: ResourcePresentation\n}\ntype RecordView = Exclude<ResourceView, { mode: 'index' }>\n\n/** Title of a record dialog: «إضافة حساب», «تعديل · الحسابات» or «تفاصيل · الحسابات». */\nfunction recordTitle(view: RecordView, t: Translate) {\n if (view.mode === 'show') return t('تفاصيل · {resource}', { resource: view.resource.label })\n const create = view.editor.mode === 'create'\n // A singular record noun («حساب») reads better than the plural list label (#37).\n if (view.editor.recordLabel)\n return create\n ? t('إضافة {record}', { record: view.editor.recordLabel })\n : t('تعديل {record}', { record: view.editor.recordLabel })\n return create\n ? t('إضافة · {resource}', { resource: view.editor.label })\n : t('تعديل · {resource}', { resource: view.editor.label })\n}\n\n/**\n * The title of a dialog whose view is still loading: from the list's own description, else\n * from the label the opener gave.\n */\nfunction openingTitle(\n opening: NonNullable<RecordOverlay['opening']>,\n resource: ResourceDescription | undefined,\n t: Translate\n) {\n const label = resource?.label ?? opening.label ?? ''\n if (opening.mode === 'show') return t('تفاصيل · {resource}', { resource: label })\n const noun = resource?.recordLabel\n if (opening.mode === 'create')\n return noun\n ? t('إضافة {record}', { record: noun })\n : t('إضافة · {resource}', { resource: label })\n return noun ? t('تعديل {record}', { record: noun }) : t('تعديل · {resource}', { resource: label })\n}\n\n/**\n * The body of a dialog whose view is still loading: the dialog is already open, with its fixed\n * footer and the close control it will keep, so nothing moves when the view arrives. Without\n * the skeleton, the first frame of a dialog whose view is at hand (AfterFirstPaint).\n */\nfunction RecordLoading({ form, skeleton = true }: { form: boolean; skeleton?: boolean }) {\n const { t } = useMessages()\n return (\n <>\n <RecordFooter>\n {/* Where the record's own actions will sit, as in the loaded footer. */}\n <div className=\"me-auto\" />\n {form ? (\n <>\n <DialogClose asChild>\n <Button type=\"button\" variant=\"outline\">\n {t('إلغاء')}\n </Button>\n </DialogClose>\n <Button type=\"button\" disabled>\n <Save size={16} />\n {t('حفظ السجل')}\n </Button>\n </>\n ) : (\n <RecordFooterClose />\n )}\n </RecordFooter>\n {/* While it shows, the dialog holds the focus itself (ResourceSurface). */}\n <span hidden data-record-pending=\"\" />\n {skeleton && <RecordSkeleton />}\n </>\n )\n}\n\n/** What Radix focuses when a dialog opens: the first tabbable control, links aside. */\nfunction firstTabbable(container: Element) {\n for (const element of container.querySelectorAll<HTMLElement>(\n 'button, input, select, textarea, [tabindex]'\n )) {\n const disabled = (element as HTMLButtonElement).disabled\n const hidden = element instanceof HTMLInputElement && element.type === 'hidden'\n if (element.tabIndex >= 0 && !disabled && !hidden && element.getClientRects().length)\n return element\n }\n return undefined\n}\n\n/**\n * A record body mounted after the dialog's first paint (decision 25). The click paints the\n * dialog at once, at its final size, with the footer it keeps; a long form's first render and\n * what follows it (style and layout forced by Radix's presence, size and focus handling) would\n * otherwise run inside the click and hold that first frame back (some 250 ms for the sample\n * form the first time it renders). One frame later the body takes its place, no skeleton in\n * between, and the focus goes to its first control as it would have at opening, unless the\n * user already moved it. Until then the dialog itself holds the focus (not «إلغاء», which a\n * screen reader would announce and Enter would press).\n */\nfunction AfterFirstPaint({ form, children }: { form: boolean; children: ReactNode }) {\n const [ready, setReady] = useState(false)\n const marker = useRef<HTMLSpanElement>(null)\n const opened = useRef<Element | null>(null)\n useEffect(() => {\n // A frame callback runs before that frame's paint; the timeout after it runs after.\n let timer: ReturnType<typeof setTimeout> | undefined\n const frame = requestAnimationFrame(() => {\n timer = setTimeout(() => {\n opened.current = document.activeElement\n setReady(true)\n }, 0)\n })\n return () => {\n cancelAnimationFrame(frame)\n clearTimeout(timer)\n }\n }, [])\n useEffect(() => {\n if (!ready || document.activeElement !== opened.current) return\n const dialog = marker.current?.closest('[role=dialog]')\n if (dialog) firstTabbable(dialog)?.focus()\n }, [ready])\n if (!ready) return <RecordLoading form={form} skeleton={false} />\n return (\n <>\n <span ref={marker} hidden />\n {children}\n </>\n )\n}\n\n/** The record's card as the form and the details draw it: a header, then two columns of fields. */\nfunction RecordSkeleton() {\n const { t } = useMessages()\n return (\n <Card\n role=\"status\"\n aria-label={t('جارٍ التحميل...')}\n data-slot=\"record-loading\"\n className=\"gap-0 py-0 shadow-none\"\n >\n <CardHeader className=\"border-b px-7 py-5 [.border-b]:pb-5\">\n <Skeleton className=\"h-4 w-28\" />\n <Skeleton className=\"h-3 w-48\" />\n </CardHeader>\n <CardContent className=\"grid gap-6 p-7 md:grid-cols-2\">\n {[0, 1, 2, 3].map((field) => (\n <div key={field} className=\"min-w-0 space-y-2\">\n <Skeleton className=\"h-4 w-32\" />\n <Skeleton className=\"h-9 w-full\" />\n </div>\n ))}\n </CardContent>\n </Card>\n )\n}\n\nfunction RecordBody({\n view,\n childrenData,\n activity,\n onSaved,\n onCancel,\n onEdit,\n onAction,\n}: {\n view: RecordView\n childrenData?: ResourceChildren\n activity?: ResourceActivity\n onSaved?: (id: number) => void\n onCancel?: () => void\n onEdit?: () => void\n onAction?: (action: string) => void\n}) {\n return view.mode === 'form' ? (\n <ResourceForm\n key={`${view.editor.name}:${view.editor.record?.id ?? 'new'}`}\n editor={view.editor}\n permissions={view.permissions}\n onSaved={onSaved}\n onCancel={onCancel}\n onAction={onAction}\n />\n ) : (\n <ResourceShow\n key={`${view.resource.name}:${view.result.data.id}`}\n resource={view.resource}\n result={view.result}\n lookups={view.lookups}\n childResources={view.childResources}\n childrenData={childrenData}\n activity={activity}\n onEdit={onEdit}\n onAction={onAction}\n />\n )\n}\n\n/**\n * A record or create form opened over the current page by openRecord() or openCreate(); the\n * page stays mounted behind it. ResourcePage renders it over the generic list; another page\n * that opens records with openRecord() (for example «مهامي») renders it too. `resource`, the\n * list's description, titles the dialog while its body loads.\n */\nexport function RecordOverlayDialog({ resource }: { resource?: ResourceDescription }) {\n const { t } = useMessages()\n // A client-only prop set by openRecord()/openCreate(), never sent by the server.\n const props = usePage<{\n overlay?: RecordOverlay\n childrenData?: ResourceChildren\n activity?: ResourceActivity\n }>().props\n // The click shows the dialog from the shell before the page carries it (useOverlayShell).\n const shell = useOverlayShell()\n const overlay = props.overlay ?? shell ?? undefined\n const { childrenData, activity } = props\n useOverlayView(props.overlay)\n // What closing does next: after a create, the list with the new row pinned first.\n const next = useRef<(() => void) | null>(null)\n const dismiss = useRef<(() => void) | null>(null)\n const name = overlay?.resource\n if (!overlay || !name || !(overlay.view || overlay.opening)) return null\n const view = overlay.view as RecordView | undefined\n const record = view?.mode === 'form' ? view.editor.record?.id : view?.result.data.id\n const id = record === undefined || record === null ? overlay.opening?.id : String(record)\n const mode = view\n ? view.mode === 'form'\n ? 'edit'\n : 'view'\n : overlay.opening?.mode === 'show'\n ? 'view'\n : 'edit'\n return (\n // Keyed by the opening, so the dialog that opened stays on screen while its body loads,\n // and saving switches the same dialog from the form to the details.\n <ResourceSurface\n key={`overlay:${name}:${overlay.record}`}\n mode={mode}\n title={view ? recordTitle(view, t) : openingTitle(overlay.opening!, resource, t)}\n description={\n mode === 'edit'\n ? t('أكمل الحقول المطلوبة ثم احفظ السجل.')\n : t('راجع التفاصيل المتاحة لك وأكمل عملك.')\n }\n backHref={overlay.list}\n onClose={() => (next.current ? next.current() : closeRecord(overlay))}\n dismissRef={dismiss}\n >\n {view ? (\n <AfterFirstPaint form={mode === 'edit'}>\n <RecordBody\n view={view}\n childrenData={childrenData}\n activity={activity}\n onSaved={(saved) => {\n if (view.mode === 'form' && view.editor.mode === 'create') {\n // A new record returns to the list, pinned first and highlighted there (owner,\n // 2.3.0); the toast's «عرض» opens it.\n const row = fetchListRow(name, saved)\n next.current = () => void closeCreated(overlay, saved, row)\n dismiss.current?.()\n return\n }\n // A saved edit shows the record's details in the same dialog.\n void openRecord(name, saved, 'show', { replace: true, changed: true })\n }}\n onCancel={() =>\n id === undefined\n ? closeRecord(overlay)\n : void openRecord(name, id, 'show', { replace: true })\n }\n onEdit={() => id !== undefined && void openRecord(name, id, 'edit', { replace: true })}\n onAction={(action) =>\n action === 'delete' || id === undefined\n ? closeRecord({ ...overlay, changed: true })\n : void openRecord(name, id, 'show', { replace: true, changed: true })\n }\n />\n </AfterFirstPaint>\n ) : (\n <RecordLoading form={mode === 'edit'} />\n )}\n </ResourceSurface>\n )\n}\n\nexport function ResourcePage({\n view,\n result,\n childrenData,\n activity,\n presentation,\n}: ResourcePageProps) {\n const { t } = useMessages()\n const name = view.mode === 'form' ? view.editor.name : view.resource.name\n const label = view.mode === 'form' ? view.editor.label : view.resource.label\n const trashed = view.mode === 'index' && view.trashed === true\n const title =\n view.mode === 'index'\n ? trashed\n ? t('المحذوفات · {resource}', { resource: label })\n : label\n : recordTitle(view, t)\n const noun = view.mode === 'index' ? view.resource.recordLabel : null\n const createText =\n view.mode === 'index'\n ? (view.resource.createLabel ??\n (noun ? t('إضافة {record}', { record: noun }) : t('إضافة سجل')))\n : ''\n const canCreate = view.mode === 'index' && view.resource.canCreate && !trashed\n // The create form is the same for every opening: fetched once the list is idle, so «إضافة»\n // opens it complete.\n useEffect(() => {\n if (!canCreate) return\n const idle = window.requestIdleCallback ?? ((run: () => void) => window.setTimeout(run, 200))\n const cancel = window.cancelIdleCallback ?? window.clearTimeout\n const handle = idle(() => prefetchCreate(name))\n return () => cancel(handle)\n }, [canCreate, name])\n return (\n <>\n <Head title={title} />\n {view.mode === 'index' && (\n <div className=\"mb-8 flex flex-wrap items-start justify-between gap-5\">\n <div>\n <h1 className=\"text-3xl font-semibold tracking-tight\">{title}</h1>\n <p className=\"mt-3 text-sm text-muted-foreground\">\n {trashed\n ? t('السجلات المحذوفة ضمن نطاقك؛ استعد ما تحتاجه منها إلى السجلات النشطة.')\n : t('سجلاتك ومتابعتك اليومية في مكان واحد.')}\n </p>\n </div>\n {canCreate && (\n <div className=\"flex flex-wrap gap-2\">\n <ResourceImport resource={name} label={label} />\n <Button asChild>\n <Link\n href={`/resources/${name}/create`}\n // The form opens in a dialog over this list, which stays mounted; modified\n // clicks (new tab, new window) keep the link's own behavior.\n onPointerEnter={() => prefetchCreate(name)}\n onFocus={() => prefetchCreate(name)}\n onClick={(event) => {\n if (!plainClick(event)) return\n event.preventDefault()\n void openCreate(name)\n }}\n >\n <Plus size={16} />\n {createText}\n </Link>\n </Button>\n </div>\n )}\n </div>\n )}\n {view.mode === 'index' ? (\n <>\n {result ? (\n <DataTable\n key={`${name}:${trashed ? 'trash' : 'active'}`}\n resource={view.resource}\n result={result}\n lookups={view.lookups}\n savedViews={view.savedViews}\n trashed={trashed}\n bulkActions={view.bulkActions}\n />\n ) : null}\n <RecordOverlayDialog resource={view.resource} />\n </>\n ) : (\n <ResourceSurface\n // Keyed by record, not mode: saving an edit shows the details in the same dialog.\n key={`${name}:${view.mode === 'form' ? (view.editor.record?.id ?? 'new') : view.result.data.id}`}\n mode={view.mode === 'form' ? 'edit' : 'view'}\n title={title}\n description={\n view.mode === 'form'\n ? t('أكمل الحقول المطلوبة ثم احفظ السجل.')\n : t('راجع التفاصيل المتاحة لك وأكمل عملك.')\n }\n backHref={`/resources/${name}`}\n presentation={presentation}\n >\n <RecordBody view={view} childrenData={childrenData} activity={activity} />\n </ResourceSurface>\n )}\n </>\n )\n}\n",
|
|
21
22
|
"target": "inertia/components/ui/resource-page.tsx"
|
|
22
23
|
}
|
|
23
24
|
],
|
package/build/resource-show.json
CHANGED
|
@@ -13,7 +13,9 @@
|
|
|
13
13
|
"record-assignments",
|
|
14
14
|
"record-workflows",
|
|
15
15
|
"record-print",
|
|
16
|
-
"
|
|
16
|
+
"resource-surface",
|
|
17
|
+
"messages",
|
|
18
|
+
"user-avatar"
|
|
17
19
|
],
|
|
18
20
|
"dependencies": [
|
|
19
21
|
"lucide-react@1.47.0"
|
|
@@ -22,7 +24,7 @@
|
|
|
22
24
|
{
|
|
23
25
|
"path": "registry/ui/resource-show.tsx",
|
|
24
26
|
"type": "registry:ui",
|
|
25
|
-
"content": "import { Deferred, router } from '@inertiajs/react'\nimport { Link } from '@adonisjs/inertia/react'\nimport { History, Pencil } from 'lucide-react'\nimport type {\n ResourceActivity,\n ResourceChildren as Children,\n ResourceDescription,\n ResourceShow as Show,\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 { arabicText, useMessages, type Translate } from '~/components/ui/messages'\nimport { Skeleton } from '~/components/ui/skeleton'\nimport { ResourceActions } from '~/components/ui/resource-actions'\nimport { ResourceValue, formatDatetime, type LookupOptions } from '~/components/ui/resource-value'\nimport { RecordCollaboration } from '~/components/ui/record-collaboration'\nimport { RecordAssignments } from '~/components/ui/record-assignments'\nimport { RecordWorkflows } from '~/components/ui/record-workflows'\nimport { RecordPrint } from '~/components/ui/record-print'\n\nexport type ResourceChildren = Children\nconst meta = new Set(['id', 'version', 'docStatus', 'orgUnitId'])\nconst activityLabels: Record<string, string> = {\n create: 'إنشاء السجل',\n update: 'تعديل السجل',\n delete: 'حذف السجل',\n submit: 'اعتماد المستند',\n cancel: 'إلغاء الاعتماد',\n amend: 'تعديل بعد الاعتماد',\n assignment_closed: 'إغلاق مهمة مع السجل',\n printed: 'طباعة السجل بقالب',\n}\n\nexport function documentStatus(status: unknown, t: Translate = arabicText) {\n return status === 1 ? t('معتمد') : status === 2 ? t('ملغي') : t('مسودة')\n}\n\nexport function ResourceShow({\n resource,\n result,\n lookups = {},\n childResources = {},\n childrenData,\n activity,\n onEdit,\n onAction,\n}: {\n resource: ResourceDescription\n result: Show\n lookups?: LookupOptions\n childResources?: Record<string, ResourceDescription>\n childrenData?: ResourceChildren\n activity?: ResourceActivity\n /** Replaces the edit link (record dialogs switch to the form in place). */\n onEdit?: () => void\n /** Called after a record action instead of reloading or leaving the page. */\n onAction?: (action: string) => void\n}) {\n const { calendar } = useUiPreferences()\n const { t, label } = useMessages()\n const base = `/resources/${resource.name}/${result.data.id}`\n const fields = resource.fields.filter(\n (field) =>\n resource.show.includes(field.key) && field.type !== 'hasMany' && field.key in result.data\n )\n const children = resource.fields.filter(\n (field) => field.type === 'hasMany' && resource.show.includes(field.key)\n )\n const fieldLabel = (key: string) => {\n const field = resource.fields.find((entry) => entry.key === key)\n return field ? label(field.label) : key\n }\n const columnLabel = (field: ResourceDescription['fields'][number] | undefined) =>\n field ? label(field.label) : undefined\n return (\n <div className=\"max-w-5xl space-y-6\">\n <div className=\"flex flex-wrap items-center gap-3\">\n <Can permissions={result.permissions} action=\"update\">\n {onEdit ? (\n <Button onClick={onEdit}>\n <Pencil size={15} />\n {t('تعديل السجل')}\n </Button>\n ) : (\n <Button asChild>\n <Link href={`${base}/edit`}>\n <Pencil size={15} />\n {t('تعديل السجل')}\n </Link>\n </Button>\n )}\n </Can>\n <RecordPrint resource={resource.name} id={result.data.id as number} />\n <ResourceActions\n resource={resource.name}\n id={result.data.id as number}\n version={result.data.version ?? undefined}\n permissions={result.permissions}\n onDone={(action) =>\n onAction\n ? onAction(action)\n : action === 'delete'\n ? router.visit(`/resources/${resource.name}`)\n : router.reload()\n }\n />\n {resource.submittable && (\n <Badge\n variant={result.data.docStatus === 1 ? 'default' : 'secondary'}\n className={result.data.docStatus === 2 ? 'bg-red-50 text-red-800' : ''}\n >\n {documentStatus(result.data.docStatus, t)}\n </Badge>\n )}\n </div>\n <dl className=\"grid gap-7 rounded-xl border bg-white p-7 md:grid-cols-2\">\n {fields.map((field) => (\n <div\n key={field.key}\n className={['text', 'json'].includes(field.type) ? 'md:col-span-2' : ''}\n >\n <dt className=\"mb-2 text-xs text-muted-foreground\">{label(field.label)}</dt>\n <dd className=\"break-words text-sm whitespace-pre-wrap\">\n <ResourceValue\n field={field}\n row={result.data}\n related={result.related}\n lookups={lookups}\n />\n </dd>\n </div>\n ))}\n {resource.scoped && result.data.orgUnitId !== undefined && (\n <div>\n <dt className=\"mb-2 text-xs text-muted-foreground\">{t('الوحدة التنظيمية')}</dt>\n <dd className=\"text-sm\">#{String(result.data.orgUnitId)}</dd>\n </div>\n )}\n </dl>\n {children.length > 0 && (\n <Deferred data=\"childrenData\" fallback={<SectionSkeleton title={t('البنود')} rows={3} />}>\n <div className=\"space-y-5\">\n {children.map((field) => {\n const group = childrenData?.[field.key]\n if (!group) return null\n const child = childResources[field.key]\n const columns = child\n ? child.fields.filter(\n (entry) => child.list.includes(entry.key) && entry.type !== 'hasMany'\n )\n : []\n const keys = columns.length\n ? columns.map((entry) => entry.key)\n : [...new Set(group.rows.flatMap((row) => Object.keys(row)))].filter(\n (key) => !meta.has(key)\n )\n return (\n <section\n key={field.key}\n aria-label={label(field.label)}\n className=\"rounded-xl border bg-white\"\n >\n <div className=\"flex items-center justify-between border-b px-7 py-4\">\n <h2 className=\"text-sm font-semibold\">{label(field.label)}</h2>\n <span className=\"text-xs text-muted-foreground\">\n {t('{count} بند', { count: group.rows.length })}\n {group.hasMore ? ` · ${t('تظهر أول 100 بند متاح')}` : ''}\n </span>\n </div>\n {group.rows.length ? (\n <div className=\"overflow-x-auto\">\n <table className=\"w-full min-w-[480px] text-sm\">\n <thead className=\"bg-muted text-xs text-muted-foreground\">\n <tr>\n {keys.map((key) => (\n <th\n key={key}\n scope=\"col\"\n className=\"px-5 py-3 text-start font-medium\"\n >\n {columnLabel(columns.find((entry) => entry.key === key)) ?? key}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {group.rows.map((row) => (\n <tr key={String(row.id)} className=\"border-b last:border-0\">\n {keys.map((key) => {\n const column = columns.find((entry) => entry.key === key)\n return (\n <td key={key} className=\"px-5 py-3\">\n {column ? (\n <ResourceValue field={column} row={row} lookups={lookups} />\n ) : (\n plain(row, key)\n )}\n </td>\n )\n })}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n ) : (\n <p className=\"px-7 py-6 text-xs text-muted-foreground\">\n {t('لا توجد بنود متاحة.')}\n </p>\n )}\n </section>\n )\n })}\n </div>\n </Deferred>\n )}\n {resource.submittable && (\n <RecordWorkflows resource={resource.name} id={result.data.id as number} />\n )}\n <RecordAssignments\n resource={resource.name}\n id={result.data.id as number}\n canAssign={Boolean(result.permissions.update)}\n />\n <RecordCollaboration resource={resource} id={result.data.id as number} />\n <Deferred data=\"activity\" fallback={<SectionSkeleton title={t('سجل النشاط')} rows={4} />}>\n <section aria-label={t('سجل النشاط')} className=\"rounded-xl border bg-white\">\n <div className=\"flex items-center gap-2 border-b px-7 py-4\">\n <History size={16} className=\"text-muted-foreground\" />\n <h2 className=\"text-sm font-semibold\">{t('سجل النشاط')}</h2>\n <span className=\"ms-auto text-xs text-muted-foreground\">\n {t('آخر {count} إجراء', { count: activity?.length ?? 0 })}\n </span>\n </div>\n {activity?.length ? (\n <ol className=\"divide-y\">\n {activity.map((entry) => (\n <li\n key={entry.id}\n className=\"flex flex-wrap items-baseline gap-x-4 gap-y-1 px-7 py-3 text-sm\"\n >\n <span className=\"font-medium\">\n {activityLabels[entry.action] ? t(activityLabels[entry.action]) : entry.action}\n </span>\n <span className=\"text-xs text-muted-foreground\">\n {entry.actorName ?? t('مستخدم #{id}', { id: String(entry.actorId) })}\n </span>\n <time\n dateTime={entry.createdAt}\n className=\"text-xs text-muted-foreground tabular-nums\"\n >\n {formatDatetime(entry.createdAt, calendar)}\n </time>\n {entry.fields.length > 0 && (\n <span className=\"basis-full text-xs text-muted-foreground\">\n {t('الحقول: {fields}', {\n fields: entry.fields.map(fieldLabel).join(t('، ')),\n })}\n </span>\n )}\n </li>\n ))}\n </ol>\n ) : (\n <p className=\"px-7 py-6 text-xs text-muted-foreground\">{t('لا يوجد نشاط مسجل بعد.')}</p>\n )}\n </section>\n </Deferred>\n </div>\n )\n}\n\nfunction plain(row: SerializedRecord, key: string) {\n const value = row[key]\n if (value === null || value === undefined) return '—'\n return typeof value === 'object' ? JSON.stringify(value) : String(value)\n}\n\nfunction SectionSkeleton({ title, rows }: { title: string; rows: number }) {\n const { t } = useMessages()\n return (\n <section\n role=\"status\"\n aria-label={t('جارٍ تحميل {section}', { section: title })}\n className=\"rounded-xl border bg-white\"\n >\n <div className=\"border-b px-7 py-4\">\n <Skeleton className=\"h-4 w-32\" />\n </div>\n <div className=\"space-y-3 px-7 py-5\">\n {Array.from({ length: rows }, (_, index) => (\n <Skeleton key={index} className=\"h-4 w-full\" />\n ))}\n </div>\n </section>\n )\n}\n",
|
|
27
|
+
"content": "import { Deferred, router } from '@inertiajs/react'\nimport { Link } from '@adonisjs/inertia/react'\nimport { History, Pencil } from 'lucide-react'\nimport type {\n ResourceActivity,\n ResourceChildren as Children,\n ResourceDescription,\n ResourceShow as Show,\n SerializedRecord,\n} from 'adula'\nimport { Badge } from '~/components/ui/badge'\nimport { UserAvatar } from '~/components/ui/user-avatar'\nimport { Button } from '~/components/ui/button'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\nimport { Can } from '~/components/ui/can'\nimport { arabicText, useMessages, type Translate } from '~/components/ui/messages'\nimport { Skeleton } from '~/components/ui/skeleton'\nimport { ResourceActions } from '~/components/ui/resource-actions'\nimport { ResourceValue, formatDatetime, type LookupOptions } from '~/components/ui/resource-value'\nimport { relationText } from '~/components/ui/field_values'\nimport { RecordCollaboration } from '~/components/ui/record-collaboration'\nimport { RecordAssignments } from '~/components/ui/record-assignments'\nimport { RecordWorkflows } from '~/components/ui/record-workflows'\nimport { RecordPrint } from '~/components/ui/record-print'\nimport { RecordFooter, RecordFooterClose } from '~/components/ui/resource-surface'\n\nexport type ResourceChildren = Children\nconst meta = new Set(['id', 'version', 'docStatus', 'orgUnitId'])\nconst activityLabels: Record<string, string> = {\n create: 'إنشاء السجل',\n update: 'تعديل السجل',\n delete: 'حذف السجل',\n submit: 'اعتماد المستند',\n cancel: 'إلغاء الاعتماد',\n amend: 'تعديل بعد الاعتماد',\n assignment_closed: 'إغلاق مهمة مع السجل',\n printed: 'طباعة السجل بقالب',\n}\n\nexport function documentStatus(status: unknown, t: Translate = arabicText) {\n return status === 1 ? t('معتمد') : status === 2 ? t('ملغي') : t('مسودة')\n}\n\nexport function ResourceShow({\n resource,\n result,\n lookups = {},\n childResources = {},\n childrenData,\n activity,\n onEdit,\n onAction,\n}: {\n resource: ResourceDescription\n result: Show\n lookups?: LookupOptions\n childResources?: Record<string, ResourceDescription>\n childrenData?: ResourceChildren\n activity?: ResourceActivity\n /** Replaces the edit link (record dialogs switch to the form in place). */\n onEdit?: () => void\n /** Called after a record action instead of reloading or leaving the page. */\n onAction?: (action: string) => void\n}) {\n const { calendar } = useUiPreferences()\n const { t, label } = useMessages()\n const base = `/resources/${resource.name}/${result.data.id}`\n const fields = resource.fields.filter(\n (field) =>\n resource.show.includes(field.key) && field.type !== 'hasMany' && field.key in result.data\n )\n const children = resource.fields.filter(\n (field) => field.type === 'hasMany' && resource.show.includes(field.key)\n )\n const fieldLabel = (key: string) => {\n const field = resource.fields.find((entry) => entry.key === key)\n return field ? label(field.label) : key\n }\n const columnLabel = (field: ResourceDescription['fields'][number] | undefined) =>\n field ? label(field.label) : undefined\n return (\n <div className=\"max-w-5xl space-y-6\">\n {resource.submittable && (\n <Badge\n variant={result.data.docStatus === 1 ? 'default' : 'secondary'}\n className={result.data.docStatus === 2 ? 'bg-destructive/10 text-destructive' : ''}\n >\n {documentStatus(result.data.docStatus, t)}\n </Badge>\n )}\n <RecordFooter>\n <div className=\"me-auto flex flex-wrap items-center gap-2\">\n <RecordPrint resource={resource.name} id={result.data.id as number} />\n <ResourceActions\n resource={resource.name}\n id={result.data.id as number}\n version={result.data.version ?? undefined}\n permissions={result.permissions}\n onDone={(action) =>\n onAction\n ? onAction(action)\n : action === 'delete'\n ? router.visit(`/resources/${resource.name}`)\n : router.reload()\n }\n />\n </div>\n <RecordFooterClose />\n <Can permissions={result.permissions} action=\"update\">\n {onEdit ? (\n <Button onClick={onEdit}>\n <Pencil size={15} />\n {t('تعديل السجل')}\n </Button>\n ) : (\n <Button asChild>\n {/* The same dialog switches to the form: the record page stays mounted. */}\n <Link href={`${base}/edit`} preserveState preserveScroll>\n <Pencil size={15} />\n {t('تعديل السجل')}\n </Link>\n </Button>\n )}\n </Can>\n </RecordFooter>\n <dl className=\"grid gap-7 rounded-xl border bg-card p-7 md:grid-cols-2\">\n {fields.map((field) => (\n <div\n key={field.key}\n className={['text', 'json'].includes(field.type) ? 'md:col-span-2' : ''}\n >\n <dt className=\"mb-2 text-xs text-muted-foreground\">{label(field.label)}</dt>\n <dd className=\"break-words text-sm whitespace-pre-wrap\">\n <ResourceValue\n field={field}\n row={result.data}\n related={result.related}\n lookups={lookups}\n />\n </dd>\n </div>\n ))}\n {resource.scoped && result.data.orgUnitId !== undefined && (\n <div>\n <dt className=\"mb-2 text-xs text-muted-foreground\">{t('الوحدة التنظيمية')}</dt>\n {/* The server sends the unit's name; without it the unit is labelled, never its id. */}\n <dd className=\"text-sm\">\n {relationText(\n result.related.orgUnitId?.find(\n (unit) => String(unit.id) === String(result.data.orgUnitId)\n ),\n result.data.orgUnitId,\n t('وحدة غير متاحة')\n )}\n </dd>\n </div>\n )}\n </dl>\n {children.length > 0 && (\n <Deferred data=\"childrenData\" fallback={<SectionSkeleton title={t('البنود')} rows={3} />}>\n <div className=\"space-y-5\">\n {children.map((field) => {\n const group = childrenData?.[field.key]\n if (!group) return null\n const child = childResources[field.key]\n const columns = child\n ? child.fields.filter(\n (entry) => child.list.includes(entry.key) && entry.type !== 'hasMany'\n )\n : []\n const keys = columns.length\n ? columns.map((entry) => entry.key)\n : [...new Set(group.rows.flatMap((row) => Object.keys(row)))].filter(\n (key) => !meta.has(key)\n )\n return (\n <section\n key={field.key}\n aria-label={label(field.label)}\n className=\"rounded-xl border bg-card\"\n >\n <div className=\"flex items-center justify-between border-b px-7 py-4\">\n <h2 className=\"text-sm font-semibold\">{label(field.label)}</h2>\n <span className=\"text-xs text-muted-foreground\">\n {t('{count} بند', { count: group.rows.length })}\n {group.hasMore ? ` · ${t('تظهر أول 100 بند متاح')}` : ''}\n </span>\n </div>\n {group.rows.length ? (\n <div className=\"overflow-x-auto\">\n <table className=\"w-full min-w-[480px] text-sm\">\n <thead className=\"bg-muted text-xs text-muted-foreground\">\n <tr>\n {keys.map((key) => (\n <th\n key={key}\n scope=\"col\"\n className=\"px-5 py-3 text-start font-medium\"\n >\n {columnLabel(columns.find((entry) => entry.key === key)) ?? key}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {group.rows.map((row) => (\n <tr key={String(row.id)} className=\"border-b last:border-0\">\n {keys.map((key) => {\n const column = columns.find((entry) => entry.key === key)\n return (\n <td key={key} className=\"px-5 py-3\">\n {column ? (\n <ResourceValue field={column} row={row} lookups={lookups} />\n ) : (\n plain(row, key)\n )}\n </td>\n )\n })}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n ) : (\n <p className=\"px-7 py-6 text-xs text-muted-foreground\">\n {t('لا توجد بنود متاحة.')}\n </p>\n )}\n </section>\n )\n })}\n </div>\n </Deferred>\n )}\n {resource.submittable && (\n <RecordWorkflows resource={resource.name} id={result.data.id as number} />\n )}\n <RecordAssignments\n resource={resource.name}\n id={result.data.id as number}\n canAssign={Boolean(result.permissions.update)}\n />\n <RecordCollaboration resource={resource} id={result.data.id as number} />\n <Deferred data=\"activity\" fallback={<SectionSkeleton title={t('سجل النشاط')} rows={4} />}>\n <section aria-label={t('سجل النشاط')} className=\"rounded-xl border bg-card\">\n <div className=\"flex items-center gap-2 border-b px-7 py-4\">\n <History size={16} className=\"text-muted-foreground\" />\n <h2 className=\"text-sm font-semibold\">{t('سجل النشاط')}</h2>\n <span className=\"ms-auto text-xs text-muted-foreground\">\n {t('آخر {count} إجراء', { count: activity?.length ?? 0 })}\n </span>\n </div>\n {activity?.length ? (\n <ol className=\"divide-y\">\n {activity.map((entry) => (\n <li\n key={entry.id}\n className=\"flex flex-wrap items-baseline gap-x-4 gap-y-1 px-7 py-3 text-sm\"\n >\n <span className=\"font-medium\">\n {activityLabels[entry.action] ? t(activityLabels[entry.action]) : entry.action}\n </span>\n <span className=\"inline-flex items-center gap-1.5 text-xs text-muted-foreground\">\n {entry.actorId ? (\n <UserAvatar\n user={{\n id: entry.actorId,\n name: entry.actorName,\n avatarUrl: entry.actorAvatarUrl,\n }}\n size=\"xs\"\n />\n ) : null}\n {entry.actorName ?? t('مستخدم #{id}', { id: String(entry.actorId) })}\n </span>\n <time\n dateTime={entry.createdAt}\n className=\"text-xs text-muted-foreground tabular-nums\"\n >\n {formatDatetime(entry.createdAt, calendar)}\n </time>\n {entry.fields.length > 0 && (\n <span className=\"basis-full text-xs text-muted-foreground\">\n {t('الحقول: {fields}', {\n fields: entry.fields.map(fieldLabel).join(t('، ')),\n })}\n </span>\n )}\n </li>\n ))}\n </ol>\n ) : (\n <p className=\"px-7 py-6 text-xs text-muted-foreground\">{t('لا يوجد نشاط مسجل بعد.')}</p>\n )}\n </section>\n </Deferred>\n </div>\n )\n}\n\nfunction plain(row: SerializedRecord, key: string) {\n const value = row[key]\n if (value === null || value === undefined) return '—'\n return typeof value === 'object' ? JSON.stringify(value) : String(value)\n}\n\nfunction SectionSkeleton({ title, rows }: { title: string; rows: number }) {\n const { t } = useMessages()\n return (\n <section\n role=\"status\"\n aria-label={t('جارٍ تحميل {section}', { section: title })}\n className=\"rounded-xl border bg-card\"\n >\n <div className=\"border-b px-7 py-4\">\n <Skeleton className=\"h-4 w-32\" />\n </div>\n <div className=\"space-y-3 px-7 py-5\">\n {Array.from({ length: rows }, (_, index) => (\n <Skeleton key={index} className=\"h-4 w-full\" />\n ))}\n </div>\n </section>\n )\n}\n",
|
|
26
28
|
"target": "inertia/components/ui/resource-show.tsx"
|
|
27
29
|
}
|
|
28
30
|
],
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
"registryDependencies": [
|
|
5
5
|
"button",
|
|
6
6
|
"dialog",
|
|
7
|
+
"long-dialog",
|
|
7
8
|
"messages"
|
|
8
9
|
],
|
|
9
10
|
"dependencies": [],
|
|
@@ -11,7 +12,7 @@
|
|
|
11
12
|
{
|
|
12
13
|
"path": "registry/ui/resource-surface.tsx",
|
|
13
14
|
"type": "registry:ui",
|
|
14
|
-
"content": "import { useEffect, useRef, useState, type ReactNode } from 'react'\nimport { router } from '@inertiajs/react'\nimport { Link } from '@adonisjs/inertia/react'\nimport axios from 'axios'\nimport { Button } from '~/components/ui/button'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n} from '~/components/ui/dialog'\nimport { useMessages } from '~/components/ui/messages'\n\nexport type ResourcePresentation = 'dialog' | 'page'\n\nconst LIST_RETURN = 'adula:list-return'\ntype ListReturn = { href: string; scroll: number; record: string }\n\n/**\n * Remembers the list view (query and scroll) before a record opens from it, so closing the\n * record dialog returns to that view. DataTable calls it; page overrides that link to records\n * from their own list can call it too.\n */\nexport function rememberListView(record: string) {\n try {\n sessionStorage.setItem(\n LIST_RETURN,\n JSON.stringify({\n href: window.location.pathname + window.location.search,\n scroll: window.scrollY,\n record,\n } satisfies ListReturn)\n )\n } catch {\n // Storage can be unavailable (private mode); closing then falls back to backHref.\n }\n}\n\nfunction listReturn(backHref: string): ListReturn | null {\n try {\n const saved = JSON.parse(sessionStorage.getItem(LIST_RETURN) ?? 'null') as ListReturn | null\n const path = (href: string) => new URL(href, window.location.origin).pathname\n if (saved && typeof saved.href === 'string' && path(saved.href) === path(backHref)) return saved\n } catch {\n // Ignore unreadable entries.\n }\n return null\n}\n\n/**\n * A record opened over the list it belongs to (#31): the list stays mounted, keeps its\n * query, loaded pages and scroll, and the URL names the record so it can be shared or\n * reloaded as a standalone page.\n */\nexport type RecordOverlay = {\n /** The record's view or edit form, as served by GET /resources/:resource/:id/view. */\n view: unknown\n /** The list URL to return to. */\n list: string\n /** The record that opened the dialog, for focus return. */\n record: string\n /** Set after a save or action, so closing refreshes the list rows. */\n changed?: boolean\n}\ntype OverlayPage = Record<string, unknown> & { overlay?: RecordOverlay }\n\n/**\n * Opens a record in a dialog over the current generic list without leaving it. Page\n * overrides can call it for their own rows. Resources with their own record pages, and\n * failures, fall back to a normal visit.\n */\nexport async function openRecord(\n resource: string,\n id: string | number,\n mode: 'show' | 'edit' = 'show',\n options: { replace?: boolean; changed?: boolean } = {}\n) {\n const href = `/resources/${resource}/${id}${mode === 'edit' ? '/edit' : ''}`\n let data: { view: unknown; childrenData?: unknown; activity?: unknown }\n try {\n const response = await axios.get(`/resources/${resource}/${id}/view`, {\n params: mode === 'edit' ? { mode } : {},\n headers: { Accept: 'application/json' },\n })\n data = response.data\n } catch {\n router.visit(href)\n return\n }\n const list = window.location.pathname + window.location.search\n const visit = options.replace ? router.replace.bind(router) : router.push.bind(router)\n visit({\n url: href,\n props: (current: OverlayPage) => ({\n ...current,\n childrenData: data.childrenData,\n activity: data.activity,\n overlay: {\n view: data.view,\n list: options.replace ? (current.overlay?.list ?? list) : list,\n record: options.replace ? (current.overlay?.record ?? href) : href,\n changed: Boolean(options.changed || (options.replace && current.overlay?.changed)),\n },\n }),\n preserveState: true,\n preserveScroll: true,\n })\n}\n\n/** Closes a record dialog opened by openRecord and returns to its list, refreshed if changed. */\nexport function closeRecord(overlay: RecordOverlay) {\n if (overlay.changed) {\n // Replace the record's history entry, so Back does not reopen a record that changed.\n router.visit(overlay.list, {\n replace: true,\n preserveScroll: true,\n onSuccess: () => restoreFocus(overlay.record),\n })\n return\n }\n router.replace({\n url: overlay.list,\n props: (current: OverlayPage) => {\n const { overlay: _closed, childrenData: _children, activity: _activity, ...rest } = current\n return rest\n },\n preserveState: true,\n preserveScroll: true,\n onSuccess: () => restoreFocus(overlay.record),\n })\n}\n\n/** Return focus to the control that opened the record, else to the page heading without a ring. */\nfunction restoreFocus(record: string | undefined) {\n const trigger = record\n ? document.querySelector<HTMLElement>(`main a[href=\"${CSS.escape(record)}\"]`)\n : null\n const target = trigger ?? document.querySelector<HTMLElement>('main h1')\n if (!trigger && target) {\n target.setAttribute('tabindex', '-1')\n target.classList.add('outline-none')\n }\n target?.focus({ preventScroll: true })\n}\n\n/** Forms and record details are modal unless the user requests a page override. */\nexport function ResourceSurface({\n title,\n description,\n backHref,\n presentation = 'dialog',\n mode,\n onClose,\n children,\n}: {\n title: string\n description: string\n backHref: string\n presentation?: ResourcePresentation\n mode?: 'view' | 'edit'\n /** Replaces the default return visit, for dialogs opened over a mounted list. */\n onClose?: () => void\n children: ReactNode\n}) {\n const { t, dir } = useMessages()\n const [open, setOpen] = useState(true)\n const closeTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n useEffect(() => () => clearTimeout(closeTimer.current), [])\n if (presentation === 'page')\n return (\n <section dir={dir} className=\"space-y-6\">\n <Button variant=\"outline\" asChild>\n <Link href={backHref}>{t('العودة إلى القائمة')}</Link>\n </Button>\n <header>\n <h1 className=\"text-3xl font-semibold\">{title}</h1>\n <p className=\"mt-3 text-sm text-muted-foreground\">{description}</p>\n </header>\n {children}\n </section>\n )\n\n return (\n <Dialog\n mode={mode}\n open={open}\n onOpenChange={(open) => {\n if (!open) {\n setOpen(false)\n closeTimer.current = setTimeout(\n () => {\n if (onClose) return onClose()\n // Return to the list view the record was opened from: same query and scroll.\n const saved = listReturn(backHref)\n router.visit(saved?.href ?? backHref, {\n onSuccess: () => {\n if (saved) window.scrollTo(0, saved.scroll)\n // A direct route has no mounted DialogTrigger to restore focus to.\n restoreFocus(saved?.record)\n },\n })\n },\n window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 160\n )\n }\n }}\n >\n <DialogContent\n dir={dir}\n className=\"flex max-h-[calc(100dvh-2rem)] w-[calc(100vw-2rem)] flex-col gap-0 overflow-hidden p-0 sm:max-w-5xl\"\n >\n <DialogHeader className=\"shrink-0 border-b px-6 py-5 pe-12 text-start\">\n <DialogTitle>{title}</DialogTitle>\n <DialogDescription>{description}</DialogDescription>\n </DialogHeader>\n <div className=\"min-h-0 overflow-y-auto overscroll-contain p-4 sm:p-6\">{children}</div>\n </DialogContent>\n </Dialog>\n )\n}\n",
|
|
15
|
+
"content": "import {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n type ReactNode,\n} from 'react'\nimport { createPortal } from 'react-dom'\nimport { router } from '@inertiajs/react'\nimport { Link } from '@adonisjs/inertia/react'\nimport axios from 'axios'\nimport { Button } from '~/components/ui/button'\nimport { Dialog, DialogClose } from '~/components/ui/dialog'\nimport { LongDialogContent } from '~/components/ui/long-dialog'\nimport { useMessages } from '~/components/ui/messages'\n\ntype FooterSlot = { slot: HTMLElement | null; register: () => () => void }\nconst RecordFooterContext = createContext<FooterSlot | null>(null)\n\n// Secondary actions sit at the start (me-auto on their group), then «إلغاء»/«إغلاق», then the\n// primary action: the shared dialog footer rule.\nconst footerClass = 'flex w-full flex-wrap items-center gap-2'\n\n/**\n * A record's actions. Inside a record dialog they move to its fixed footer (the long dialog\n * pattern, ADR 016), so they stay on screen while the body scrolls; on a record page they\n * render in place. Buttons that submit a form must name it with `form`, because the footer\n * is outside the form's markup.\n */\nexport function RecordFooter({ children }: { children: ReactNode }) {\n const surface = useContext(RecordFooterContext)\n const register = surface?.register\n // Registered before paint, so the dialog's fixed footer is there in the body's first frame.\n useLayoutEffect(() => register?.(), [register])\n if (!surface) return <div className={footerClass}>{children}</div>\n return surface.slot ? createPortal(children, surface.slot) : null\n}\n\n/** «إغلاق» for a record dialog's footer; nothing on a record page, which has its own way back. */\nexport function RecordFooterClose() {\n const { t } = useMessages()\n if (!useContext(RecordFooterContext)) return null\n return (\n <DialogClose asChild>\n <Button type=\"button\" variant=\"outline\">\n {t('إغلاق')}\n </Button>\n </DialogClose>\n )\n}\n\nexport type ResourcePresentation = 'dialog' | 'page'\n\nconst LIST_RETURN = 'adula:list-return'\ntype ListReturn = { href: string; scroll: number; record: string }\n\n/**\n * The page's scroll container: the workspace's scroll region (Inertia's `scroll-region`) when\n * it scrolls on its own, as on large screens; otherwise the window.\n */\nfunction pageScroller(): HTMLElement | null {\n const region = document.querySelector<HTMLElement>('[scroll-region]')\n if (!region) return null\n const { overflowY } = getComputedStyle(region)\n return overflowY === 'auto' || overflowY === 'scroll' ? region : null\n}\n\nfunction pageScrollTop() {\n return pageScroller()?.scrollTop ?? window.scrollY\n}\n\n/**\n * Scrolls the page back to a remembered position once Inertia has settled its own scroll\n * handling (a scroll region is set on the next frame) and the list is tall enough: it retries\n * for a few frames until the position holds.\n */\nfunction scrollPageTo(top: number) {\n let frames = 0\n const apply = () => {\n const region = pageScroller()\n if (region) region.scrollTo(0, top)\n else window.scrollTo(0, top)\n const current = region ? region.scrollTop : window.scrollY\n if (Math.abs(current - top) > 1 && ++frames < 30) requestAnimationFrame(apply)\n }\n requestAnimationFrame(apply)\n}\n\n/**\n * Remembers the list view (query and scroll) before a record opens from it, so closing the\n * record dialog returns to that view. DataTable calls it; page overrides that link to records\n * from their own list can call it too.\n */\nexport function rememberListView(record: string) {\n try {\n sessionStorage.setItem(\n LIST_RETURN,\n JSON.stringify({\n href: window.location.pathname + window.location.search,\n scroll: pageScrollTop(),\n record,\n } satisfies ListReturn)\n )\n } catch {\n // Storage can be unavailable (private mode); closing then falls back to backHref.\n }\n}\n\nfunction forgetListView() {\n try {\n sessionStorage.removeItem(LIST_RETURN)\n } catch {\n // Storage can be unavailable; nothing to forget.\n }\n}\n\n/** A path with its query on this origin, or null: never another origin or a scheme URL. */\nfunction localPath(href: unknown): string | null {\n if (typeof href !== 'string' || !href.startsWith('/')) return null\n if (href.startsWith('//') || href.includes('\\\\')) return null\n try {\n const url = new URL(href, window.location.origin)\n // Dot segments can still collapse to a protocol-relative path ('/.//host').\n if (url.origin !== window.location.origin || url.pathname.startsWith('//')) return null\n return url.pathname + url.search\n } catch {\n return null\n }\n}\n\nconst recordPath = (path: string) => path.split('?')[0].replace(/\\/edit$/, '')\n\n/**\n * The remembered view to return to when this record closes: the record's own list view, or\n * any page of this application that remembered itself for this record (for example «مهامي»).\n */\nfunction listReturn(backHref: string): ListReturn | null {\n try {\n const stored = sessionStorage.getItem(LIST_RETURN) ?? 'null'\n const saved = JSON.parse(stored) as Partial<ListReturn> | null\n const href = localPath(saved?.href)\n if (!saved || !href) return null\n const record = localPath(saved.record)\n const fromList = href.split('?')[0] === new URL(backHref, window.location.origin).pathname\n const forThisRecord =\n record !== null && recordPath(record) === recordPath(window.location.pathname)\n if (!fromList && !forThisRecord) return null\n const scroll = Number.isFinite(saved.scroll) ? Number(saved.scroll) : 0\n return { href, record: record ?? '', scroll: Math.max(0, scroll) }\n } catch {\n // Ignore unreadable entries.\n }\n return null\n}\n\n/**\n * A record opened over the list it belongs to (#31): the list stays mounted, keeps its\n * query, loaded pages and scroll, and the URL names the record so it can be shared or\n * reloaded as a standalone page.\n */\nexport type RecordOverlay = {\n /**\n * The record's view or edit form, as served by GET /resources/:resource/:id/view (or the\n * create form, by GET /resources/:resource/create/view). Absent while it loads: the dialog\n * is already on screen and its body shows a loading state.\n */\n view?: unknown\n /** The resource the dialog belongs to. */\n resource?: string\n /**\n * What the dialog shows, so its title and shell render before the view arrives; `label`\n * names the resource for a page that has no description of it.\n */\n opening?: { mode: 'create' | 'show' | 'edit'; id?: string; label?: string }\n /** The list URL to return to. */\n list: string\n /** The record that opened the dialog, for focus return. */\n record: string\n /** Set after a save or action, so closing refreshes the list rows. */\n changed?: boolean\n}\ntype OverlayPage = Record<string, unknown> & { overlay?: RecordOverlay }\n\n/** Deferred props being loaded for the page on screen (Inertia's async partial reloads). */\nlet deferredLoads = 0\n/** Inertia writes in flight (a form submit, a POST, PUT or DELETE): never cancelled. */\nlet pendingWrites = 0\nif (typeof window !== 'undefined') {\n router.on('start', (event) => {\n if (event.detail.visit.async) deferredLoads++\n if (event.detail.visit.method !== 'get') pendingWrites++\n })\n router.on('finish', (event) => {\n if (event.detail.visit.async) deferredLoads = Math.max(0, deferredLoads - 1)\n if (event.detail.visit.method !== 'get') pendingWrites = Math.max(0, pendingWrites - 1)\n })\n}\n\n/**\n * Cancels the page's reads still in flight (a GET visit, deferred props), so a late answer\n * cannot replace the page. A write in flight is never cancelled: its reply and message must\n * arrive, as the change may already be saved; while one is pending nothing is cancelled.\n */\nfunction cancelReads(options: { sync: boolean; async: boolean }) {\n if (pendingWrites > 0) return false\n router.cancelAll({ async: options.async, prefetch: false, sync: options.sync })\n return true\n}\n\n/**\n * Changes the address on the client (a dialog opening or closing over the page), with no\n * request of its own. `ownPage` marks an address the mounted page itself renders (the list\n * a dialog closes back to, or the same page with another query). Deferred props loading for\n * the old address (the «مهامي» badge) answer late: Inertia applies that answer when only the\n * query changed, restoring the old address and so the dialog, and drops it when the path\n * changed. On the page's own address they are cancelled if still loading, and those missing\n * are loaded again for it; a dialog's own address never reloads them, since it renders\n * another page.\n */\nexport function clientVisit<TProps = OverlayPage>(\n kind: 'push' | 'replace',\n options: Parameters<typeof router.push<TProps>>[0],\n ownPage = false\n) {\n const cancelled = ownPage && deferredLoads > 0 && cancelReads({ async: true, sync: false })\n const visit = kind === 'push' ? router.push.bind(router) : router.replace.bind(router)\n visit<TProps>({\n ...options,\n onSuccess: (page) => {\n options.onSuccess?.(page)\n if (!ownPage) return\n const props = page.props as Record<string, unknown>\n // Inertia keeps the page's deferred props under initialDeferredProps once they load.\n const groups =\n (page as { initialDeferredProps?: Record<string, string[]> }).initialDeferredProps ??\n page.deferredProps ??\n {}\n const keys = Object.values(groups)\n .flat()\n .filter((key) => cancelled || props[key] === undefined)\n if (keys.length) router.reload({ only: keys, async: true })\n },\n })\n}\n\n/**\n * A plain left click, which opens a dialog over the page; a modified click (new tab, new\n * window) keeps the link's own behavior.\n */\nexport function plainClick(event: {\n button: number\n metaKey: boolean\n ctrlKey: boolean\n shiftKey: boolean\n altKey: boolean\n}) {\n return event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey\n}\n\n/** The view being loaded for the open dialog; a newer opening or a close discards it. */\nlet loading: { href: string; abort: AbortController } | null = null\n\n/** The address whose loaded view is being put on the page (loadOverlay's replace). */\nlet delivering: string | null = null\n\nfunction cancelLoading() {\n loading?.abort.abort()\n loading = null\n}\n\n// Back and Forward leave the dialog that was loading; history brings its own page.\nif (typeof window !== 'undefined')\n window.addEventListener('popstate', () => {\n cancelLoading()\n // Back before the opening push applied: the page in history has no dialog.\n setShell(null)\n })\n\nconst here = () => window.location.pathname + window.location.search\n\ntype ViewData = {\n view: unknown\n childrenData?: unknown\n activity?: unknown\n presentation?: ResourcePresentation\n}\n\n/** `keep`: used for every opening while fresh (the create form), not only the next one. */\ntype Prefetch = { at: number; promise: Promise<ViewData>; data?: ViewData; keep: boolean }\n\n/**\n * Views fetched ahead of the click (a record on hover or focus, the create form when its list\n * mounts), so most dialogs open complete instead of with a loading body. A record's view is\n * used once, the create form for every opening, both only while fresh; a save clears them all,\n * since any view may show what it changed.\n */\nconst prefetched = new Map<string, Prefetch>()\nconst PREFETCH_FRESH_MS = 20_000\n\nconst viewKey = (endpoint: string, params: Record<string, unknown>) =>\n `${endpoint}?${new URLSearchParams(params as Record<string, string>).toString()}`\n\nfunction prefetchView(endpoint: string, params: Record<string, unknown>, keep = false) {\n const key = viewKey(endpoint, params)\n const entry = prefetched.get(key)\n if (entry && Date.now() - entry.at < PREFETCH_FRESH_MS) return\n const next: Prefetch = {\n at: Date.now(),\n keep,\n promise: axios\n .get<ViewData>(endpoint, { params, headers: { Accept: 'application/json' } })\n .then((response) => (next.data = response.data)),\n }\n // A failed prefetch is forgotten; the click loads the view itself and handles the failure.\n next.promise.catch(() => {\n if (prefetched.get(key) === next) prefetched.delete(key)\n })\n prefetched.set(key, next)\n}\n\n/** The fresh prefetched view for this request (taken out of the cache unless kept). */\nfunction takePrefetched(endpoint: string, params: Record<string, unknown>) {\n const key = viewKey(endpoint, params)\n const entry = prefetched.get(key)\n if (!entry) return undefined\n const fresh = Date.now() - entry.at < PREFETCH_FRESH_MS\n if (!fresh || !entry.keep) prefetched.delete(key)\n return fresh ? entry : undefined\n}\n\n/** Forgets every prefetched view: called after a save. */\nexport function clearPrefetched() {\n prefetched.clear()\n}\n\nconst recordView = (resource: string, id: string | number, mode: 'show' | 'edit') => ({\n endpoint: `/resources/${resource}/${id}/view`,\n params: (mode === 'edit' ? { mode } : {}) as Record<string, unknown>,\n})\nconst createView = (resource: string, search = '') => ({\n endpoint: `/resources/${resource}/create/view`,\n params: Object.fromEntries(new URLSearchParams(search)) as Record<string, unknown>,\n})\n\n/** Fetches a record's view ahead of the click (row hover or focus). */\nexport function prefetchRecord(\n resource: string,\n id: string | number,\n mode: 'show' | 'edit' = 'show'\n) {\n const { endpoint, params } = recordView(resource, id, mode)\n prefetchView(endpoint, params)\n}\n\n/** Fetches the create form ahead of the click (its list mounted, or «إضافة» hovered). */\nexport function prefetchCreate(resource: string, search = '') {\n const { endpoint, params } = createView(resource, search)\n prefetchView(endpoint, params, true)\n}\n\n/** Fetches a dialog's view and puts it in the dialog, if the dialog is still the one open. */\nasync function loadOverlay(\n href: string,\n endpoint: string,\n params: Record<string, unknown>,\n options: { changed?: boolean; fallback: () => void }\n) {\n cancelLoading()\n const abort = new AbortController()\n const current = (loading = { href, abort })\n let data: ViewData\n try {\n // A prefetch on its way answers this opening too: no second request.\n const ahead = takePrefetched(endpoint, params)\n if (ahead) data = await ahead.promise\n else {\n const response = await axios.get<ViewData>(endpoint, {\n params,\n headers: { Accept: 'application/json' },\n signal: abort.signal,\n })\n data = response.data\n }\n } catch (error) {\n if (loading !== current) return\n loading = null\n if (!axios.isCancel(error)) options.fallback()\n return\n }\n // Closed, gone Back, or another dialog opened meanwhile: this answer is not wanted.\n if (loading !== current) return\n loading = null\n // A page the user asked to see as a page, not a dialog: visit it.\n if (data.presentation === 'page') return options.fallback()\n // The view may arrive before the page shows the pushed opening (the shell made the click\n // faster than the page update); it is on its way, so the opening must not load it again.\n delivering = href\n clientVisit('replace', {\n url: href,\n props: (page: OverlayPage) => ({\n ...page,\n childrenData: data.childrenData,\n activity: data.activity,\n overlay: {\n view: data.view,\n resource: page.overlay?.resource,\n list: page.overlay?.list ?? href,\n record: page.overlay?.record ?? href,\n changed: Boolean(options.changed || page.overlay?.changed),\n },\n }),\n preserveState: true,\n preserveScroll: true,\n onFinish: () => {\n if (delivering === href) delivering = null\n },\n })\n}\n\n/**\n * Opens a record in a dialog over the current page without leaving it: the generic list, or\n * any page that renders RecordOverlayDialog (for example «مهامي»), stays mounted. The dialog\n * is on screen at once and its body loads inside it, so the opening animation never waits for\n * the server. `label` names the resource in the title while it loads, on a page that has no\n * description of it. Resources with their own record pages, and failures, fall back to a\n * normal visit.\n */\nexport async function openRecord(\n resource: string,\n id: string | number,\n mode: 'show' | 'edit' = 'show',\n options: { replace?: boolean; changed?: boolean; label?: string } = {}\n) {\n const href = `/resources/${resource}/${id}${mode === 'edit' ? '/edit' : ''}`\n const { endpoint, params } = recordView(resource, id, mode)\n const fallback = () => router.visit(href, { replace: true })\n if (options.changed) clearPrefetched()\n // Within the open dialog the current body and address stay until the next view arrives.\n if (!options.replace) {\n const opening = { mode, id: String(id), label: options.label }\n // Prefetched: the dialog opens complete, with nothing left to load.\n if (openPrefetched(href, resource, opening, endpoint, params, fallback)) return\n showOverlay(href, resource, opening)\n }\n await loadOverlay(href, endpoint, params, { changed: options.changed, fallback })\n}\n\n/**\n * Opens the create form in a dialog over the current generic list (the «إضافة» button), the\n * same way openRecord opens a record: `/resources/:resource/create` stays a page of its own\n * when it is visited or reloaded directly. `search` carries `?defaults[field]=` pre-fills.\n */\nexport async function openCreate(resource: string, search = '') {\n const href = `/resources/${resource}/create${search}`\n const { endpoint, params } = createView(resource, search)\n const fallback = () => router.visit(href, { replace: true })\n if (openPrefetched(href, resource, { mode: 'create' }, endpoint, params, fallback)) return\n showOverlay(href, resource, { mode: 'create' })\n await loadOverlay(href, endpoint, params, { fallback })\n}\n\n/**\n * Opens the dialog with a view that already arrived ahead of the click, so its first frame is\n * its final one. False when no such view is at hand (the caller shows the loading dialog).\n */\nfunction openPrefetched(\n href: string,\n resource: string,\n opening: NonNullable<RecordOverlay['opening']>,\n endpoint: string,\n params: Record<string, unknown>,\n fallback: () => void\n) {\n const entry = prefetched.get(viewKey(endpoint, params))\n if (!entry?.data || Date.now() - entry.at >= PREFETCH_FRESH_MS) return false\n const data = takePrefetched(endpoint, params)!.data!\n if (data.presentation === 'page') fallback()\n else showOverlay(href, resource, opening, data)\n return true\n}\n\n/** Pushes the dialog's address and its shell, with no request: the list stays as it is. */\n/**\n * The dialog being opened, shown before Inertia's page update: the click renders only the\n * dialog, at once, and the page update that follows (a re-render of the whole page) finds the\n * same dialog already on screen and keeps it.\n */\nlet shell: RecordOverlay | null = null\nconst shellListeners = new Set<() => void>()\nfunction setShell(next: RecordOverlay | null) {\n if (shell === next) return\n shell = next\n for (const listener of shellListeners) listener()\n}\n\n/** The dialog opening on this page before its address is pushed, or null. */\nexport function useOverlayShell() {\n return useSyncExternalStore(\n (listener) => {\n shellListeners.add(listener)\n return () => shellListeners.delete(listener)\n },\n () => shell,\n () => null\n )\n}\n\nfunction showOverlay(\n href: string,\n resource: string,\n opening: NonNullable<RecordOverlay['opening']>,\n // A view already at hand (prefetched): the dialog opens complete.\n data?: ViewData\n) {\n cancelLoading()\n // Opening a dialog is the user's latest navigation, as a link click is: a read or deferred\n // props still in flight for the page would otherwise answer later and replace its props,\n // dialog and all. Deferred props cancelled here load again when the dialog closes back to\n // the page (clientVisit with ownPage). A pending write is left to finish.\n cancelReads({ async: true, sync: true })\n const list = here()\n const overlay: RecordOverlay = { resource, opening, list, record: href, view: data?.view }\n setShell(overlay)\n clientVisit('push', {\n url: href,\n props: (page: OverlayPage) => {\n const { childrenData: _children, activity: _activity, ...rest } = page\n return data\n ? { ...rest, overlay, childrenData: data.childrenData, activity: data.activity }\n : { ...rest, overlay }\n },\n preserveState: true,\n preserveScroll: true,\n // The page now carries the dialog itself.\n onSuccess: () => {\n if (shell === overlay) setShell(null)\n },\n })\n}\n\n/**\n * Loads the view of a dialog whose address came back from history (Forward, or Back to it)\n * while its view had not arrived. RecordOverlayDialog calls it for the overlay it shows.\n */\nexport function useOverlayView(overlay: RecordOverlay | undefined) {\n const opening = overlay && !overlay.view ? overlay.opening : undefined\n const resource = overlay?.resource\n // The dialog's own address: an opening is pushed with it, before Inertia updates the\n // browser's address, so window.location may still name the page behind.\n const href = overlay?.record\n useEffect(() => {\n if (!opening || !resource || !href) return\n if (loading?.href === href || delivering === href) return\n if (opening.mode === 'create')\n void loadOverlay(\n href,\n `/resources/${resource}/create/view`,\n Object.fromEntries(new URL(href, window.location.origin).searchParams),\n { fallback: () => router.visit(href, { replace: true }) }\n )\n else\n void loadOverlay(\n href,\n `/resources/${resource}/${opening.id}/view`,\n opening.mode === 'edit' ? { mode: 'edit' } : {},\n { fallback: () => router.visit(href, { replace: true }) }\n )\n }, [opening, resource, href])\n}\n\ntype ListRows = {\n data: { id: unknown }[]\n permissions: Record<string, unknown>\n related: Record<string, { id: unknown }[]>\n meta: { estimatedTotal?: number } & Record<string, unknown>\n}\n\n/** Fetches a record as a row of its list (GET /resources/:resource/:id/row), or null. */\nexport async function fetchListRow(resource: string, id: string | number) {\n try {\n const response = await axios.get<ListRows>(`/resources/${resource}/${id}/row`, {\n headers: { Accept: 'application/json' },\n })\n return response.data\n } catch {\n return null\n }\n}\n\n/** The list's rows with this one first, whatever the sort; later pages never repeat it. */\nfunction pinRow(result: ListRows, row: ListRows, id: string): ListRows {\n const related = { ...result.related }\n for (const [key, rows] of Object.entries(row.related))\n related[key] = [\n ...new Map([...(related[key] ?? []), ...rows].map((entry) => [String(entry.id), entry])).values(),\n ]\n const known = result.data.some((entry) => String(entry.id) === id)\n return {\n ...result,\n data: [...row.data, ...result.data.filter((entry) => String(entry.id) !== id)],\n permissions: { ...result.permissions, ...row.permissions },\n related,\n meta:\n typeof result.meta.estimatedTotal === 'number' && !known\n ? { ...result.meta, estimatedTotal: result.meta.estimatedTotal + 1 }\n : result.meta,\n }\n}\n\n/**\n * Returns from a create dialog to the mounted list it was opened from, with the new record\n * pinned first and highlighted (the `created` page prop, read by DataTable): visible at once\n * whatever the list's sort and however many pages it has, without loading the list again. It\n * stays first until the list's query changes. Without its row (the list does not reach it),\n * the list refreshes instead.\n */\nexport async function closeCreated(\n overlay: RecordOverlay,\n id: string | number,\n row: Promise<ListRows | null>\n) {\n clearPrefetched()\n cancelLoading()\n forgetListView()\n const loaded = await row\n if (!loaded || loaded.data.length === 0) return closeRecord({ ...overlay, changed: true })\n const key = String(id)\n clientVisit('replace', {\n url: overlay.list,\n props: (page: OverlayPage) => {\n const { overlay: _closed, childrenData: _children, activity: _activity, ...rest } = page\n const result = rest.result as ListRows | undefined\n return result ? { ...rest, result: pinRow(result, loaded, key), created: key } : rest\n },\n preserveState: true,\n preserveScroll: true,\n onSuccess: () => restoreFocus(overlay.record),\n }, true)\n}\n\n/**\n * Pins a record just created at the top of the list on screen, highlighted, as closeCreated\n * does: for the standalone create page, which returns to its list after saving.\n */\nexport async function pinCreated(resource: string, id: string | number) {\n const loaded = await fetchListRow(resource, id)\n if (!loaded || loaded.data.length === 0) return\n const key = String(id)\n clientVisit('replace', {\n props: (page: OverlayPage) => {\n const result = page.result as ListRows | undefined\n return result ? { ...page, result: pinRow(result, loaded, key), created: key } : page\n },\n preserveState: true,\n preserveScroll: true,\n }, true)\n}\n\n/** Closes a record dialog opened by openRecord and returns to its list, refreshed if changed. */\nexport function closeRecord(overlay: RecordOverlay) {\n // A view still loading for this dialog is not wanted any more.\n cancelLoading()\n setShell(null)\n // The list is mounted; a later direct visit of a record must not return to this view.\n forgetListView()\n if (overlay.changed) {\n clearPrefetched()\n // Replace the record's history entry, so Back does not reopen a record that changed.\n // The list stays mounted and its rows refresh in place; the reset header restarts the\n // list's loaded pages from the first page, as the refreshed rows do.\n router.visit(overlay.list, {\n replace: true,\n preserveState: true,\n preserveScroll: true,\n // Closing a dialog never shows the top progress bar (owner decision 29).\n showProgress: false,\n headers: { 'X-Inertia-Reset': 'result' },\n onSuccess: () => restoreFocus(overlay.record),\n })\n return\n }\n clientVisit('replace', {\n url: overlay.list,\n props: (current: OverlayPage) => {\n const { overlay: _closed, childrenData: _children, activity: _activity, ...rest } = current\n return rest\n },\n preserveState: true,\n preserveScroll: true,\n onSuccess: () => restoreFocus(overlay.record),\n }, true)\n}\n\n/** Return focus to the control that opened the record, else to the page heading without a ring. */\nfunction restoreFocus(record: string | undefined) {\n const trigger = record\n ? document.querySelector<HTMLElement>(`main a[href=\"${CSS.escape(record)}\"]`)\n : null\n const target = trigger ?? document.querySelector<HTMLElement>('main h1')\n if (!trigger && target) {\n target.setAttribute('tabindex', '-1')\n target.classList.add('outline-none')\n }\n target?.focus({ preventScroll: true })\n}\n\n/** Forms and record details are modal unless the user requests a page override. */\nexport function ResourceSurface({\n title,\n description,\n backHref,\n presentation = 'dialog',\n mode,\n onClose,\n dismissRef,\n children,\n}: {\n title: string\n description: string\n backHref: string\n presentation?: ResourcePresentation\n mode?: 'view' | 'edit'\n /** Replaces the default return visit, for dialogs opened over a mounted list. */\n onClose?: () => void\n /**\n * Receives a function that closes the dialog with its closing animation and then calls\n * onClose, without asking about unsaved changes (for a form that was just saved).\n */\n dismissRef?: { current: (() => void) | null }\n children: ReactNode\n}) {\n const { t, dir } = useMessages()\n const [open, setOpen] = useState(true)\n const closeTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n useEffect(() => () => clearTimeout(closeTimer.current), [])\n // The footer appears once the record body registers actions for it; other bodies keep\n // their own buttons and the dialog shows no empty footer. Bodies register before paint, so\n // the bar stays in place while the loading body gives way to the loaded one.\n const [slot, setSlot] = useState<HTMLElement | null>(null)\n const [footers, setFooters] = useState(0)\n const register = useCallback(() => {\n setFooters((count) => count + 1)\n return () => setFooters((count) => count - 1)\n }, [])\n const footer = useMemo(() => ({ slot, register }), [slot, register])\n const close = () => {\n setOpen(false)\n closeTimer.current = setTimeout(\n () => {\n if (onClose) return onClose()\n // Return to the list view the record was opened from: same query and scroll.\n const saved = listReturn(backHref)\n forgetListView()\n router.visit(saved?.href ?? backHref, {\n // Closing a dialog never shows the top progress bar (owner decision 29).\n showProgress: false,\n onSuccess: () => {\n if (saved) scrollPageTo(saved.scroll)\n // A direct route has no mounted DialogTrigger to restore focus to.\n restoreFocus(saved?.record)\n },\n })\n },\n window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 160\n )\n }\n if (dismissRef) dismissRef.current = close\n if (presentation === 'page')\n return (\n <section dir={dir} className=\"space-y-6\">\n <Button variant=\"outline\" asChild>\n <Link href={backHref}>{t('العودة إلى القائمة')}</Link>\n </Button>\n <header>\n <h1 className=\"text-3xl font-semibold\">{title}</h1>\n <p className=\"mt-3 text-sm text-muted-foreground\">{description}</p>\n </header>\n {children}\n </section>\n )\n\n return (\n <Dialog\n mode={mode}\n open={open}\n onOpenChange={(open) => {\n if (!open) close()\n }}\n >\n {/* The long dialog pattern: fixed header and footer, only the body scrolls. */}\n <LongDialogContent\n dir={dir}\n width=\"5xl\"\n // Its body loads after opening (and its related lists after that): the full height\n // from the first frame keeps the dialog still while they arrive.\n height=\"fill\"\n // A record body still on its way (loading, or mounting after the first paint): the\n // dialog itself takes the focus instead of the footer's «إلغاء» or «إغلاق», and the\n // body moves it to its first control once there (AfterFirstPaint).\n onOpenAutoFocus={(event) => {\n const content = event.currentTarget as HTMLElement\n if (!content.querySelector('[data-record-pending]')) return\n event.preventDefault()\n content.focus({ preventScroll: true })\n }}\n title={title}\n description={description}\n footer={\n footers > 0 ? (\n <div ref={setSlot} data-slot=\"record-footer\" className={footerClass} />\n ) : undefined\n }\n >\n <RecordFooterContext.Provider value={footer}>{children}</RecordFooterContext.Provider>\n </LongDialogContent>\n </Dialog>\n )\n}\n",
|
|
15
16
|
"target": "inertia/components/ui/resource-surface.tsx"
|
|
16
17
|
}
|
|
17
18
|
],
|
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
"attachment-preview",
|
|
7
7
|
"calendar-date",
|
|
8
8
|
"ui-preferences",
|
|
9
|
-
"messages"
|
|
9
|
+
"messages",
|
|
10
|
+
"user-avatar"
|
|
10
11
|
],
|
|
11
12
|
"dependencies": [
|
|
12
13
|
"lucide-react@1.47.0"
|
|
@@ -15,13 +16,13 @@
|
|
|
15
16
|
{
|
|
16
17
|
"path": "registry/ui/resource-value.tsx",
|
|
17
18
|
"type": "registry:ui",
|
|
18
|
-
"content": "import type { ReactNode } from 'react'\nimport { Paperclip } from 'lucide-react'\nimport type { CalendarPreference, ResourceField, SerializedRecord } from 'adula'\nimport { calendarDisplay, calendarIso } from '~/components/ui/calendar_date'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\nimport { arabicText, useMessages, type Translate } from '~/components/ui/messages'\nimport { Badge } from '~/components/ui/badge'\nimport { AttachmentPreviewButton } from '~/components/ui/attachment-preview'\nimport {\n decimalDisplay,\n decimalInput,\n decimalScale,\n emailHref,\n listInput,\n listValue,\n orderedSelection,\n parseDecimal,\n phoneHref,\n safeUrl,\n toLatinDigits,\n} from '~/components/ui/field_values'\n\nexport { toLatinDigits } from '~/components/ui/field_values'\n\nexport type Option = { value: string; label: string }\nexport type LookupOptions = Record<string, Option[]>\nexport type AttachmentValue = {\n id: number\n name: string\n size: number\n mimeType: string\n url: string\n /** Inline preview kind for allow-listed images, PDF and text (ADR 047); others download. */\n preview?: 'image' | 'pdf' | 'text' | null\n}\n\n/**\n * Project-owned copy: change the label once here for another currency. It is shown through\n * `t()`, so a translated interface can map it (ui.value.currency).\n */\nexport const CURRENCY_LABEL = 'ر.س'\nconst locale = 'ar-u-nu-latn'\nconst integerFormat = new Intl.NumberFormat(locale)\nconst sizeFormat = new Intl.NumberFormat(locale, { maximumFractionDigits: 1 })\nconst meta = new Set(['id', 'version', 'docStatus', 'orgUnitId'])\n\n/** The percent sign after a percent value; translated interfaces map it (ui.value.percent). */\nexport const PERCENT_LABEL = '٪'\nconst multiValued = new Set(['multiSelect', 'manyToMany'])\n\n/** Option label of an enum or multiSelect value in the interface language. */\nexport function optionLabel(field: ResourceField, value: string, language = 'ar') {\n if (field.type !== 'enum' && field.type !== 'multiSelect') return value\n const option = field.options.find((entry) => entry.value === value)\n return option ? option.label[language] || option.label.ar : value\n}\n\n/** Localized options of an enum or multiSelect field, in definition order. */\nexport function fieldOptions(field: ResourceField, language = 'ar'): Option[] {\n if (field.type !== 'enum' && field.type !== 'multiSelect') return []\n return field.options.map((option) => ({\n value: option.value,\n label: option.label[language] || option.label.ar,\n }))\n}\n\n/** Linked records of a manyToMany value: id and title, #id when the reader cannot view it. */\nexport function linkedTitles(\n field: ResourceField,\n value: unknown,\n related: Record<string, SerializedRecord[]> = {}\n) {\n if (!Array.isArray(value)) return []\n return value.map((id) => ({\n id: String(id),\n title: relationLabel(\n related[field.key]?.find((item) => String(item.id) === String(id)),\n id\n ),\n }))\n}\n\nfunction minorUnits(value: unknown) {\n if (value === null || value === undefined || value === '') return null\n try {\n return BigInt(String(value))\n } catch {\n return null\n }\n}\n\nexport function moneyInput(value: unknown) {\n const minor = minorUnits(value)\n if (minor === null) return ''\n const abs = minor < 0n ? -minor : minor\n return `${minor < 0n ? '-' : ''}${abs / 100n}.${String(abs % 100n).padStart(2, '0')}`\n}\n\nexport function moneyDisplay(value: unknown) {\n const minor = minorUnits(value)\n if (minor === null) return ''\n const abs = minor < 0n ? -minor : minor\n return `${minor < 0n ? '-' : ''}${integerFormat.format(abs / 100n)}.${String(abs % 100n).padStart(2, '0')}`\n}\n\nexport function parseMoney(raw: string) {\n const value = toLatinDigits(raw)\n if (!/^-?\\d+(\\.\\d{1,2})?$/.test(value)) throw new Error('أدخل مبلغاً بخانتين عشريتين كحد أقصى')\n const [whole, cents = ''] = value.replace('-', '').split('.')\n return String(\n (BigInt(whole) * 100n + BigInt(cents.padEnd(2, '0'))) * (value.startsWith('-') ? -1n : 1n)\n )\n}\n\nexport function isAttachment(value: unknown): value is AttachmentValue {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'id' in value &&\n 'name' in value &&\n typeof (value as { url?: unknown }).url === 'string'\n )\n}\n\n/** Whether an attachment field holds several files (an ordered array of summaries). */\nexport function isMultipleAttachment(field: ResourceField) {\n return field.type === 'attachment' && field.multiple === true\n}\n\n/** The files of a multiple attachment value, in their stored order. */\nexport function attachmentList(value: unknown): AttachmentValue[] {\n return Array.isArray(value) ? value.filter(isAttachment) : []\n}\n\nexport function fileSize(bytes: number, t: Translate = arabicText) {\n if (bytes < 1024) return t('{size} بايت', { size: integerFormat.format(bytes) })\n if (bytes < 1024 * 1024) return t('{size} ك.ب', { size: sizeFormat.format(bytes / 1024) })\n return t('{size} م.ب', { size: sizeFormat.format(bytes / (1024 * 1024)) })\n}\n\nexport function formatDate(value: unknown, calendar: CalendarPreference = 'gregory') {\n return calendarDisplay(value, calendar)\n}\n\nexport function formatDatetime(value: unknown, calendar: CalendarPreference = 'gregory') {\n return calendarDisplay(value, calendar, true)\n}\n\n/**\n * A related record is labelled by the title the server computed from the resource's\n * `title` fields (`_title`, #47). Older servers send none; then the first readable string\n * of the record is used.\n */\nexport function relationLabel(row: SerializedRecord | undefined, fallback: unknown) {\n if (row && '_title' in row)\n return typeof row._title === 'string' && row._title\n ? row._title\n : fallback === null || fallback === undefined\n ? '—'\n : `#${fallback}`\n const label =\n row &&\n Object.entries(row).find(([key, entry]) => !meta.has(key) && typeof entry === 'string' && entry)\n return label\n ? String(label[1])\n : fallback === null || fallback === undefined\n ? '—'\n : `#${fallback}`\n}\n\nexport function inputValue(field: ResourceField, value: unknown) {\n if (value === null || value === undefined) return ''\n if (field.type === 'money') return moneyInput(value)\n if (field.type === 'decimal' || field.type === 'percent')\n return decimalInput(value, decimalScale(field))\n if (multiValued.has(field.type)) return listInput(value)\n if (field.type === 'json') return JSON.stringify(value, null, 2)\n // Several files are edited as the JSON array of their ids, in order.\n if (isMultipleAttachment(field))\n return Array.isArray(value)\n ? listInput(value.map((entry) => (isAttachment(entry) ? entry.id : entry)))\n : ''\n if (field.type === 'attachment') return isAttachment(value) ? String(value.id) : String(value)\n if (field.type === 'datetime') {\n const date = new Date(String(value))\n if (Number.isNaN(date.getTime())) return ''\n return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16)\n }\n if (field.type === 'date') return String(value).slice(0, 10)\n return String(value)\n}\n\n/**\n * Converts a control's string state into the JSON the resource route validates. Errors carry\n * the Arabic interface text; callers show them through `t(error.message)`.\n */\nexport function parseValue(field: ResourceField, raw: string): unknown {\n // Multi-value fields always submit an array, so clearing them is explicit.\n if (field.type === 'multiSelect') return orderedSelection(field.options, listValue(raw))\n if (field.type === 'manyToMany' || isMultipleAttachment(field)) return listValue(raw).map(Number)\n if (raw === '') return null\n switch (field.type) {\n case 'decimal':\n case 'percent':\n return parseDecimal(raw, decimalScale(field))\n case 'email':\n case 'url':\n case 'phone':\n return raw.trim()\n case 'money':\n return parseMoney(raw)\n case 'boolean':\n return raw === 'true'\n case 'integer': {\n const value = Number(toLatinDigits(raw))\n if (!Number.isInteger(value)) throw new Error('أدخل عدداً صحيحاً')\n return value\n }\n case 'belongsTo':\n case 'user':\n case 'attachment':\n return Number(raw)\n case 'json':\n try {\n return JSON.parse(raw)\n } catch {\n throw new Error('أدخل بيانات JSON صحيحة')\n }\n case 'date': {\n return raw.startsWith('hijri:')\n ? calendarIso(raw.slice(6), 'islamic-umalqura')\n : calendarIso(raw, 'gregory')\n }\n case 'datetime': {\n const [day, time] = raw.split('T')\n const isoDay = day.startsWith('hijri:')\n ? calendarIso(day.slice(6), 'islamic-umalqura')\n : calendarIso(day, 'gregory')\n const date = new Date(`${isoDay}T${time}`)\n if (Number.isNaN(date.getTime())) throw new Error('أدخل تاريخاً ووقتاً صحيحين')\n return date.toISOString()\n }\n default:\n return raw\n }\n}\n\nexport function displayValue(\n field: ResourceField,\n row: SerializedRecord,\n related: Record<string, SerializedRecord[]> = {},\n lookups: LookupOptions = {},\n calendar: CalendarPreference = 'gregory',\n t: Translate = arabicText,\n language = 'ar'\n) {\n const value = row[field.key]\n if (value === null || value === undefined || value === '') return '—'\n if (Array.isArray(value) && !value.length) return '—'\n switch (field.type) {\n case 'decimal':\n return decimalDisplay(value, decimalScale(field), language)\n case 'percent':\n return `${decimalDisplay(value, decimalScale(field), language)}${t(PERCENT_LABEL)}`\n case 'enum':\n return optionLabel(field, String(value), language)\n case 'multiSelect':\n return Array.isArray(value)\n ? value.map((entry) => optionLabel(field, String(entry), language)).join('، ')\n : String(value)\n case 'manyToMany':\n return linkedTitles(field, value, related)\n .map((entry) => entry.title)\n .join('، ')\n case 'money':\n return `${moneyDisplay(value)} ${t(CURRENCY_LABEL)}`\n case 'boolean':\n return value ? t('نعم') : t('لا')\n case 'integer':\n return typeof value === 'number' ? integerFormat.format(value) : String(value)\n case 'belongsTo':\n case 'user':\n return relationLabel(\n related[field.key]?.find((item) => String(item.id) === String(value)),\n value\n )\n case 'lookup':\n return (\n lookups[field.key]?.find((option) => option.value === String(value))?.label ?? String(value)\n )\n case 'json':\n return JSON.stringify(value)\n case 'attachment':\n if (Array.isArray(value))\n return attachmentList(value)\n .map((entry) => entry.name)\n .join('، ')\n return isAttachment(value) ? value.name : t('مرفق')\n case 'date':\n return formatDate(value, calendar)\n case 'datetime':\n return formatDatetime(value, calendar)\n default:\n return String(value)\n }\n}\n\n/** Prefix formula-like and leading-control values before quoting CSV cells. */\nexport function csvCell(value: string) {\n const safe = /^[\\s\u0000-\u001f]*[=+@-]|^[\\t\\r\\n]/.test(value) ? `'${value}` : value\n return `\"${safe.replaceAll('\"', '\"\"')}\"`\n}\n\n/** A downloadable file with its size and, for previewable types, a preview button. */\nfunction AttachmentLink({ file }: { file: AttachmentValue }) {\n const { t } = useMessages()\n return (\n <>\n <a\n href={file.url}\n download={file.name}\n className=\"inline-flex items-center gap-2 text-primary underline-offset-4 hover:underline\"\n >\n <Paperclip size={14} />\n {file.name}\n <span className=\"text-xs text-muted-foreground\">({fileSize(file.size, t)})</span>\n </a>\n <AttachmentPreviewButton file={file} />\n </>\n )\n}\n\nexport function ResourceValue({\n field,\n row,\n related,\n lookups,\n}: {\n field: ResourceField\n row: SerializedRecord\n related?: Record<string, SerializedRecord[]>\n lookups?: LookupOptions\n}): ReactNode {\n const { calendar } = useUiPreferences()\n const { t, locale } = useMessages()\n const value = row[field.key]\n if (value === null || value === undefined || value === '' || (Array.isArray(value) && !value.length))\n return <span className=\"text-muted-foreground\">—</span>\n if (field.type === 'decimal' || field.type === 'percent')\n return (\n <span className=\"tabular-nums\" dir=\"ltr\">\n {decimalDisplay(value, decimalScale(field), locale)}\n {field.type === 'percent' && (\n <span className=\"text-muted-foreground\">{t(PERCENT_LABEL)}</span>\n )}\n </span>\n )\n // A string with `format` renders like the dedicated type.\n const kind = field.type === 'string' ? field.format : field.type\n if (kind === 'email' || kind === 'phone' || kind === 'url') {\n const href =\n kind === 'email' ? emailHref(value) : kind === 'phone' ? phoneHref(value) : safeUrl(value)\n if (!href) return <bdi dir=\"ltr\">{String(value)}</bdi>\n return (\n <a\n href={href}\n dir=\"ltr\"\n className=\"break-all text-primary underline-offset-4 hover:underline\"\n {...(kind === 'url' ? { target: '_blank', rel: 'noopener noreferrer' } : {})}\n >\n {String(value)}\n </a>\n )\n }\n if (field.type === 'multiSelect' && Array.isArray(value))\n return (\n <span className=\"flex flex-wrap gap-1\">\n {value.map((entry) => (\n <Badge key={String(entry)} variant=\"secondary\" className=\"font-normal\">\n {optionLabel(field, String(entry), locale)}\n </Badge>\n ))}\n </span>\n )\n if (field.type === 'manyToMany')\n return (\n <span className=\"flex flex-wrap gap-1\">\n {linkedTitles(field, value, related).map((entry) => (\n <Badge key={entry.id} variant=\"outline\" className=\"font-normal\">\n {entry.title}\n </Badge>\n ))}\n </span>\n )\n if (field.type === 'attachment' && Array.isArray(value))\n return (\n <ul className=\"space-y-1\">\n {attachmentList(value).map((file) => (\n <li key={file.id} className=\"flex flex-wrap items-center gap-1\">\n <AttachmentLink file={file} />\n </li>\n ))}\n </ul>\n )\n if (field.type === 'attachment' && isAttachment(value))\n return (\n <span className=\"inline-flex flex-wrap items-center gap-1\">\n <AttachmentLink file={value} />\n </span>\n )\n if (field.type === 'boolean')\n return <Badge variant={value ? 'default' : 'secondary'}>{value ? t('نعم') : t('لا')}</Badge>\n if (field.type === 'money')\n return (\n <span className=\"tabular-nums\" dir=\"ltr\">\n {moneyDisplay(value)}{' '}\n <span className=\"text-xs text-muted-foreground\">{t(CURRENCY_LABEL)}</span>\n </span>\n )\n if (field.type === 'json')\n return (\n <pre dir=\"ltr\" className=\"max-h-64 overflow-auto rounded-md bg-muted p-3 text-xs\">\n {JSON.stringify(value, null, 2)}\n </pre>\n )\n if (field.type === 'integer')\n return (\n <span className=\"tabular-nums\" dir=\"ltr\">\n {displayValue(field, row, related, lookups, calendar, t, locale)}\n </span>\n )\n // Arabic dates carry Arabic month names and time markers; isolate them instead of forcing LTR.\n if (field.type === 'date' || field.type === 'datetime')\n return <bdi className=\"tabular-nums\">{displayValue(field, row, related, lookups, calendar, t, locale)}</bdi>\n return <>{displayValue(field, row, related, lookups, calendar, t, locale)}</>\n}\n",
|
|
19
|
+
"content": "import type { ReactNode } from 'react'\nimport { Paperclip } from 'lucide-react'\nimport type { CalendarPreference, ResourceField, SerializedRecord } from 'adula'\nimport { calendarDisplay, calendarIso } from '~/components/ui/calendar_date'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\nimport { arabicText, useMessages, type Translate } from '~/components/ui/messages'\nimport { Badge } from '~/components/ui/badge'\nimport { AttachmentPreviewButton } from '~/components/ui/attachment-preview'\nimport { UserAvatar, type UserAvatarUser } from '~/components/ui/user-avatar'\nimport {\n decimalDisplay,\n decimalInput,\n decimalScale,\n emailHref,\n listInput,\n listValue,\n orderedSelection,\n parseDecimal,\n phoneHref,\n relationText,\n safeUrl,\n toLatinDigits,\n} from '~/components/ui/field_values'\n\nexport { toLatinDigits } from '~/components/ui/field_values'\n\n/** A choice; a user choice also carries the person's picture (null without one, ADR 050). */\nexport type Option = { value: string; label: string; avatarUrl?: string | null }\nexport type LookupOptions = Record<string, Option[]>\nexport type AttachmentValue = {\n id: number\n name: string\n size: number\n mimeType: string\n url: string\n /** Inline preview kind for allow-listed images, PDF and text (ADR 047); others download. */\n preview?: 'image' | 'pdf' | 'text' | null\n}\n\n/**\n * Project-owned copy: change the label once here for another currency. It is shown through\n * `t()`, so a translated interface can map it (ui.value.currency).\n */\nexport const CURRENCY_LABEL = 'ر.س'\nconst locale = 'ar-u-nu-latn'\nconst integerFormat = new Intl.NumberFormat(locale)\nconst sizeFormat = new Intl.NumberFormat(locale, { maximumFractionDigits: 1 })\n\n/** The percent sign after a percent value; translated interfaces map it (ui.value.percent). */\nexport const PERCENT_LABEL = '٪'\nconst multiValued = new Set(['multiSelect', 'manyToMany'])\n\n/** Option label of an enum or multiSelect value in the interface language. */\nexport function optionLabel(field: ResourceField, value: string, language = 'ar') {\n if (field.type !== 'enum' && field.type !== 'multiSelect') return value\n const option = field.options.find((entry) => entry.value === value)\n return option ? option.label[language] || option.label.ar : value\n}\n\n/** Localized options of an enum or multiSelect field, in definition order. */\nexport function fieldOptions(field: ResourceField, language = 'ar'): Option[] {\n if (field.type !== 'enum' && field.type !== 'multiSelect') return []\n return field.options.map((option) => ({\n value: option.value,\n label: option.label[language] || option.label.ar,\n }))\n}\n\n/** Linked records of a manyToMany value: id and title, a neutral label when the reader cannot view it. */\nexport function linkedTitles(\n field: ResourceField,\n value: unknown,\n related: Record<string, SerializedRecord[]> = {},\n unavailable?: string\n) {\n if (!Array.isArray(value)) return []\n return value.map((id) => ({\n id: String(id),\n title: relationLabel(\n related[field.key]?.find((item) => String(item.id) === String(id)),\n id,\n unavailable\n ),\n }))\n}\n\nfunction minorUnits(value: unknown) {\n if (value === null || value === undefined || value === '') return null\n try {\n return BigInt(String(value))\n } catch {\n return null\n }\n}\n\nexport function moneyInput(value: unknown) {\n const minor = minorUnits(value)\n if (minor === null) return ''\n const abs = minor < 0n ? -minor : minor\n return `${minor < 0n ? '-' : ''}${abs / 100n}.${String(abs % 100n).padStart(2, '0')}`\n}\n\nexport function moneyDisplay(value: unknown) {\n const minor = minorUnits(value)\n if (minor === null) return ''\n const abs = minor < 0n ? -minor : minor\n return `${minor < 0n ? '-' : ''}${integerFormat.format(abs / 100n)}.${String(abs % 100n).padStart(2, '0')}`\n}\n\nexport function parseMoney(raw: string) {\n const value = toLatinDigits(raw)\n if (!/^-?\\d+(\\.\\d{1,2})?$/.test(value)) throw new Error('أدخل مبلغاً بخانتين عشريتين كحد أقصى')\n const [whole, cents = ''] = value.replace('-', '').split('.')\n return String(\n (BigInt(whole) * 100n + BigInt(cents.padEnd(2, '0'))) * (value.startsWith('-') ? -1n : 1n)\n )\n}\n\nexport function isAttachment(value: unknown): value is AttachmentValue {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'id' in value &&\n 'name' in value &&\n typeof (value as { url?: unknown }).url === 'string'\n )\n}\n\n/** Whether an attachment field holds several files (an ordered array of summaries). */\nexport function isMultipleAttachment(field: ResourceField) {\n return field.type === 'attachment' && field.multiple === true\n}\n\n/** The files of a multiple attachment value, in their stored order. */\nexport function attachmentList(value: unknown): AttachmentValue[] {\n return Array.isArray(value) ? value.filter(isAttachment) : []\n}\n\nexport function fileSize(bytes: number, t: Translate = arabicText) {\n if (bytes < 1024) return t('{size} بايت', { size: integerFormat.format(bytes) })\n if (bytes < 1024 * 1024) return t('{size} ك.ب', { size: sizeFormat.format(bytes / 1024) })\n return t('{size} م.ب', { size: sizeFormat.format(bytes / (1024 * 1024)) })\n}\n\nexport function formatDate(value: unknown, calendar: CalendarPreference = 'gregory') {\n return calendarDisplay(value, calendar)\n}\n\nexport function formatDatetime(value: unknown, calendar: CalendarPreference = 'gregory') {\n return calendarDisplay(value, calendar, true)\n}\n\n/**\n * A related record is labelled by the title the server computed from the resource's\n * `title` fields (`_title`, #47). Older servers send none; then the first readable string\n * of the record is used. Without a related row the reader may not view the record, so it\n * is labelled neutrally instead of by its id.\n */\nexport function relationLabel(\n row: SerializedRecord | undefined,\n fallback: unknown,\n unavailable?: string\n) {\n return relationText(row, fallback, unavailable)\n}\n\n/**\n * The person a `user` field points at, from the related row the server sent with its name and\n * picture (ADR 050). Null when the reader may not see that user or the field is another type.\n */\nexport function relatedUser(\n field: ResourceField,\n row: SerializedRecord,\n related: Record<string, SerializedRecord[]> | undefined\n): UserAvatarUser | null {\n if (field.type !== 'user') return null\n const value = row[field.key]\n if (value === null || value === undefined || value === '') return null\n const user = related?.[field.key]?.find((item) => String(item.id) === String(value))\n if (!user) return null\n return {\n id: Number(user.id),\n name: typeof user.fullName === 'string' ? user.fullName : null,\n avatarUrl:\n user.avatarUrl === null || typeof user.avatarUrl === 'string' ? user.avatarUrl : undefined,\n }\n}\n\nexport function inputValue(field: ResourceField, value: unknown) {\n if (value === null || value === undefined) return ''\n if (field.type === 'money') return moneyInput(value)\n if (field.type === 'decimal' || field.type === 'percent')\n return decimalInput(value, decimalScale(field))\n if (multiValued.has(field.type)) return listInput(value)\n if (field.type === 'json') return JSON.stringify(value, null, 2)\n // Several files are edited as the JSON array of their ids, in order.\n if (isMultipleAttachment(field))\n return Array.isArray(value)\n ? listInput(value.map((entry) => (isAttachment(entry) ? entry.id : entry)))\n : ''\n if (field.type === 'attachment') return isAttachment(value) ? String(value.id) : String(value)\n if (field.type === 'datetime') {\n const date = new Date(String(value))\n if (Number.isNaN(date.getTime())) return ''\n return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16)\n }\n if (field.type === 'date') return String(value).slice(0, 10)\n return String(value)\n}\n\n/**\n * Converts a control's string state into the JSON the resource route validates. Errors carry\n * the Arabic interface text; callers show them through `t(error.message)`.\n */\nexport function parseValue(field: ResourceField, raw: string): unknown {\n // Multi-value fields always submit an array, so clearing them is explicit.\n if (field.type === 'multiSelect') return orderedSelection(field.options, listValue(raw))\n if (field.type === 'manyToMany' || isMultipleAttachment(field)) return listValue(raw).map(Number)\n if (raw === '') return null\n switch (field.type) {\n case 'decimal':\n case 'percent':\n return parseDecimal(raw, decimalScale(field))\n case 'email':\n case 'url':\n case 'phone':\n return raw.trim()\n case 'money':\n return parseMoney(raw)\n case 'boolean':\n return raw === 'true'\n case 'integer': {\n const value = Number(toLatinDigits(raw))\n if (!Number.isInteger(value)) throw new Error('أدخل عدداً صحيحاً')\n return value\n }\n case 'belongsTo':\n case 'user':\n case 'attachment':\n return Number(raw)\n case 'json':\n try {\n return JSON.parse(raw)\n } catch {\n throw new Error('أدخل بيانات JSON صحيحة')\n }\n case 'date': {\n return raw.startsWith('hijri:')\n ? calendarIso(raw.slice(6), 'islamic-umalqura')\n : calendarIso(raw, 'gregory')\n }\n case 'datetime': {\n const [day, time] = raw.split('T')\n const isoDay = day.startsWith('hijri:')\n ? calendarIso(day.slice(6), 'islamic-umalqura')\n : calendarIso(day, 'gregory')\n const date = new Date(`${isoDay}T${time}`)\n if (Number.isNaN(date.getTime())) throw new Error('أدخل تاريخاً ووقتاً صحيحين')\n return date.toISOString()\n }\n default:\n return raw\n }\n}\n\nexport function displayValue(\n field: ResourceField,\n row: SerializedRecord,\n related: Record<string, SerializedRecord[]> = {},\n lookups: LookupOptions = {},\n calendar: CalendarPreference = 'gregory',\n t: Translate = arabicText,\n language = 'ar'\n) {\n const value = row[field.key]\n if (value === null || value === undefined || value === '') return '—'\n if (Array.isArray(value) && !value.length) return '—'\n switch (field.type) {\n case 'decimal':\n return decimalDisplay(value, decimalScale(field), language)\n case 'percent':\n return `${decimalDisplay(value, decimalScale(field), language)}${t(PERCENT_LABEL)}`\n case 'enum':\n return optionLabel(field, String(value), language)\n case 'multiSelect':\n return Array.isArray(value)\n ? value.map((entry) => optionLabel(field, String(entry), language)).join('، ')\n : String(value)\n case 'manyToMany':\n return linkedTitles(field, value, related, t('سجل غير متاح'))\n .map((entry) => entry.title)\n .join('، ')\n case 'money':\n return `${moneyDisplay(value)} ${t(CURRENCY_LABEL)}`\n case 'boolean':\n return value ? t('نعم') : t('لا')\n case 'integer':\n return typeof value === 'number' ? integerFormat.format(value) : String(value)\n case 'belongsTo':\n case 'user':\n return relationLabel(\n related[field.key]?.find((item) => String(item.id) === String(value)),\n value,\n t('سجل غير متاح')\n )\n case 'lookup':\n return (\n lookups[field.key]?.find((option) => option.value === String(value))?.label ?? String(value)\n )\n case 'json':\n return JSON.stringify(value)\n case 'attachment':\n if (Array.isArray(value))\n return attachmentList(value)\n .map((entry) => entry.name)\n .join('، ')\n return isAttachment(value) ? value.name : t('مرفق')\n case 'date':\n return formatDate(value, calendar)\n case 'datetime':\n return formatDatetime(value, calendar)\n default:\n return String(value)\n }\n}\n\n/** Prefix formula-like and leading-control values before quoting CSV cells. */\nexport function csvCell(value: string) {\n const safe = /^[\\s\u0000-\u001f]*[=+@-]|^[\\t\\r\\n]/.test(value) ? `'${value}` : value\n return `\"${safe.replaceAll('\"', '\"\"')}\"`\n}\n\n/** A downloadable file with its size and, for previewable types, a preview button. */\nfunction AttachmentLink({ file }: { file: AttachmentValue }) {\n const { t } = useMessages()\n return (\n <>\n <a\n href={file.url}\n download={file.name}\n className=\"inline-flex items-center gap-2 text-primary underline-offset-4 hover:underline\"\n >\n <Paperclip size={14} />\n {file.name}\n <span className=\"text-xs text-muted-foreground\">({fileSize(file.size, t)})</span>\n </a>\n <AttachmentPreviewButton file={file} />\n </>\n )\n}\n\nexport function ResourceValue({\n field,\n row,\n related,\n lookups,\n}: {\n field: ResourceField\n row: SerializedRecord\n related?: Record<string, SerializedRecord[]>\n lookups?: LookupOptions\n}): ReactNode {\n const { calendar } = useUiPreferences()\n const { t, locale } = useMessages()\n const value = row[field.key]\n if (value === null || value === undefined || value === '' || (Array.isArray(value) && !value.length))\n return <span className=\"text-muted-foreground\">—</span>\n if (field.type === 'decimal' || field.type === 'percent')\n return (\n <span className=\"tabular-nums\" dir=\"ltr\">\n {decimalDisplay(value, decimalScale(field), locale)}\n {field.type === 'percent' && (\n <span className=\"text-muted-foreground\">{t(PERCENT_LABEL)}</span>\n )}\n </span>\n )\n // A string with `format` renders like the dedicated type.\n const kind = field.type === 'string' ? field.format : field.type\n if (kind === 'email' || kind === 'phone' || kind === 'url') {\n const href =\n kind === 'email' ? emailHref(value) : kind === 'phone' ? phoneHref(value) : safeUrl(value)\n if (!href) return <bdi dir=\"ltr\">{String(value)}</bdi>\n return (\n <a\n href={href}\n dir=\"ltr\"\n className=\"break-all text-primary underline-offset-4 hover:underline\"\n {...(kind === 'url' ? { target: '_blank', rel: 'noopener noreferrer' } : {})}\n >\n {String(value)}\n </a>\n )\n }\n if (field.type === 'multiSelect' && Array.isArray(value))\n return (\n <span className=\"flex flex-wrap gap-1\">\n {value.map((entry) => (\n <Badge key={String(entry)} variant=\"secondary\" className=\"font-normal\">\n {optionLabel(field, String(entry), locale)}\n </Badge>\n ))}\n </span>\n )\n if (field.type === 'manyToMany')\n return (\n <span className=\"flex flex-wrap gap-1\">\n {linkedTitles(field, value, related, t('سجل غير متاح')).map((entry) => (\n <Badge key={entry.id} variant=\"outline\" className=\"font-normal\">\n {entry.title}\n </Badge>\n ))}\n </span>\n )\n if (field.type === 'attachment' && Array.isArray(value))\n return (\n <ul className=\"space-y-1\">\n {attachmentList(value).map((file) => (\n <li key={file.id} className=\"flex flex-wrap items-center gap-1\">\n <AttachmentLink file={file} />\n </li>\n ))}\n </ul>\n )\n if (field.type === 'attachment' && isAttachment(value))\n return (\n <span className=\"inline-flex flex-wrap items-center gap-1\">\n <AttachmentLink file={value} />\n </span>\n )\n if (field.type === 'boolean')\n return <Badge variant={value ? 'default' : 'secondary'}>{value ? t('نعم') : t('لا')}</Badge>\n const person = relatedUser(field, row, related)\n if (person)\n return (\n <span className=\"inline-flex items-center gap-1.5\">\n <UserAvatar user={person} size=\"xs\" />\n {/* Its own element: the name reads alone, apart from the initials behind the picture. */}\n <span>{displayValue(field, row, related, lookups, calendar, t, locale)}</span>\n </span>\n )\n if (field.type === 'money')\n return (\n <span className=\"tabular-nums\" dir=\"ltr\">\n {moneyDisplay(value)}{' '}\n <span className=\"text-xs text-muted-foreground\">{t(CURRENCY_LABEL)}</span>\n </span>\n )\n if (field.type === 'json')\n return (\n <pre dir=\"ltr\" className=\"max-h-64 overflow-auto rounded-md bg-muted p-3 text-xs\">\n {JSON.stringify(value, null, 2)}\n </pre>\n )\n if (field.type === 'integer')\n return (\n <span className=\"tabular-nums\" dir=\"ltr\">\n {displayValue(field, row, related, lookups, calendar, t, locale)}\n </span>\n )\n // Arabic dates carry Arabic month names and time markers; isolate them instead of forcing LTR.\n if (field.type === 'date' || field.type === 'datetime')\n return <bdi className=\"tabular-nums\">{displayValue(field, row, related, lookups, calendar, t, locale)}</bdi>\n return <>{displayValue(field, row, related, lookups, calendar, t, locale)}</>\n}\n",
|
|
19
20
|
"target": "inertia/components/ui/resource-value.tsx"
|
|
20
21
|
},
|
|
21
22
|
{
|
|
22
23
|
"path": "registry/ui/field_values.ts",
|
|
23
24
|
"type": "registry:ui",
|
|
24
|
-
"content": "import type { ResourceField } from 'adula'\n\n/**\n * Pure value helpers of the generated forms and values (decimal, percent, multi-value\n * fields, visibleWhen and safe links). They have no React or alias imports, so they are\n * shared by resource-field, resource-form and resource-value and tested directly.\n */\n\ntype Scalar = string | number | boolean | null\n\n/**\n * Arabic-Indic and Persian digits and the Arabic decimal separator to Latin. Commas (and the\n * Arabic thousands mark) are removed only when they group whole thousands, as in «1,234.5»;\n * any other comma, such as «1,5», stays and makes the number invalid instead of 15.\n */\nexport function toLatinDigits(raw: string) {\n const value = raw\n .replace(/[٠-٩]/g, (digit) => String('٠١٢٣٤٥٦٧٨٩'.indexOf(digit)))\n .replace(/[۰-۹]/g, (digit) => String('۰۱۲۳۴۵۶۷۸۹'.indexOf(digit)))\n .replaceAll('٫', '.')\n .replaceAll('٬', ',')\n .trim()\n return /^-?\\d{1,3}(,\\d{3})+(\\.\\d*)?$/.test(value) ? value.replaceAll(',', '') : value\n}\n\n/** Fractional digits of a decimal or percent field (the server default is 2). */\nexport function decimalScale(field: ResourceField) {\n return (field.type === 'decimal' || field.type === 'percent') && field.scale !== undefined\n ? field.scale\n : 2\n}\n\n/**\n * Typed decimal text to the canonical wire string with exactly `scale` digits, for example\n * «١٢٫٥» → \"12.50\". Errors carry the Arabic interface text.\n */\nexport function parseDecimal(raw: string, scale: number) {\n const value = toLatinDigits(raw)\n const match = /^(-?)(\\d*)(?:\\.(\\d*))?$/.exec(value)\n if (!match || (match[2] === '' && !match[3])) throw new Error('أدخل رقماً عشرياً صحيحاً')\n const [, sign, whole, fraction = ''] = match\n const significant = fraction.replace(/0+$/, '')\n if (significant.length > scale) throw new Error('عدد المنازل العشرية أكثر من المسموح')\n const integer = whole.replace(/^0+(?=\\d)/, '') || '0'\n const digits = scale ? `.${fraction.slice(0, scale).padEnd(scale, '0')}` : ''\n const canonical = `${integer}${digits}`\n return /^0(\\.0*)?$/.test(canonical) ? canonical : `${sign}${canonical}`\n}\n\n/** The input text of a stored decimal: the canonical string, or '' when empty. */\nexport function decimalInput(value: unknown, scale: number) {\n if (value === null || value === undefined || value === '') return ''\n try {\n return parseDecimal(String(value), scale)\n } catch {\n return String(value)\n }\n}\n\n/**\n * A decimal string formatted with the interface language and Latin digits. The string is\n * formatted exactly (no float rounding), so numeric(18, 2) values keep every digit.\n */\nexport function decimalDisplay(value: unknown, scale: number, language = 'ar') {\n if (value === null || value === undefined || value === '') return ''\n const format = new Intl.NumberFormat(`${language}-u-nu-latn`, {\n minimumFractionDigits: scale,\n maximumFractionDigits: scale,\n })\n // Intl formats numeric strings as exact decimals; the lib typing only names numbers.\n return format.format(String(value) as unknown as number)\n}\n\n/** Multi-value controls keep a JSON array of strings in the string form state. */\nexport function listValue(raw: string): string[] {\n if (!raw) return []\n try {\n const parsed: unknown = JSON.parse(raw)\n return Array.isArray(parsed) ? parsed.map(String) : []\n } catch {\n return []\n }\n}\n\nexport function listInput(values: unknown): string {\n if (!Array.isArray(values) || !values.length) return ''\n return JSON.stringify([...new Set(values.map(String))])\n}\n\n/** Selected option values in the definition's option order, as the server stores them. */\nexport function orderedSelection(options: readonly { value: string }[], selected: string[]) {\n const chosen = new Set(selected)\n return options.map((option) => option.value).filter((value) => chosen.has(value))\n}\n\n/**\n * Whether a field applies to the current form values (its `visibleWhen`). Every named\n * sibling must equal the value or one of the listed values; a multiSelect sibling must\n * contain it; `null` matches an empty sibling (no selection for a multiSelect). Both sides\n * compare canonically, as the server does (see canonicalValue). Use hiddenFields() for a\n * whole form: it also hides fields whose sibling is hidden.\n */\nexport function fieldApplies(\n field: Pick<ResourceField, 'visibleWhen'>,\n values: Record<string, string>,\n siblings: Readonly<Record<string, SiblingShape>> = {}\n) {\n if (!field.visibleWhen) return true\n return Object.entries(field.visibleWhen).every(([key, expected]) => {\n const sibling = siblings[key]\n const raw = values[key] ?? ''\n const accepted: Scalar[] = Array.isArray(expected) ? expected : [expected]\n if (sibling?.type === 'multiSelect' || sibling?.type === 'manyToMany') {\n const current = listValue(raw)\n return accepted.some((entry) =>\n entry === null ? current.length === 0 : current.includes(String(entry))\n )\n }\n const current = canonicalValue(raw, sibling)\n return accepted.some((entry) =>\n entry === null ? raw.trim() === '' : canonicalValue(String(entry), sibling) === current\n )\n })\n}\n\n/**\n * The fields that do not apply, resolved to a fixed point like the server's\n * applyVisibility: a hidden field counts as empty while its dependants are evaluated, so\n * in a chain C → B → A hiding A also hides B and then C.\n */\nexport function hiddenFields(\n fields: readonly (Pick<ResourceField, 'key' | 'visibleWhen'> & SiblingShape)[],\n values: Record<string, string>\n) {\n const siblings = siblingShapes(fields)\n const hidden = new Set<string>()\n // The same passes as the server: a field is cleared as soon as it is hidden.\n const current = { ...values }\n for (let pass = 0; pass <= fields.length; pass++) {\n let changed = false\n for (const field of fields) {\n if (hidden.has(field.key) || fieldApplies(field, current, siblings)) continue\n hidden.add(field.key)\n current[field.key] = ''\n changed = true\n }\n if (!changed) break\n }\n return hidden\n}\n\n/** What fieldApplies needs to know about a sibling field. */\nexport type SiblingShape = { type: string; scale?: number; format?: string }\n\n/** The comparison shape of every field, by key. */\nexport function siblingShapes(fields: readonly (SiblingShape & { key: string })[]) {\n return Object.fromEntries(\n fields.map((field) => [\n field.key,\n { type: field.type, scale: field.scale, format: field.format } satisfies SiblingShape,\n ])\n ) as Record<string, SiblingShape>\n}\n\n/**\n * The stored form of a sibling value, mirroring the server's normalization: e-mail trimmed\n * and lower-cased, phone with Latin digits and no separators (a leading + kept), URL\n * trimmed, decimal/percent at the sibling's scale («12.5» equals \"12.50\"), integers without\n * leading zeros, string fields trimmed (the server's validator trims them). Text is\n * compared as typed (the server does not trim it).\n */\nexport function canonicalValue(raw: string, sibling?: SiblingShape) {\n if (!sibling || raw.trim() === '') return raw\n const format = sibling.type === 'string' ? sibling.format : sibling.type\n if (format === 'email') return raw.trim().toLowerCase()\n if (format === 'phone') return toLatinDigits(raw.trim()).replace(/[\\s\\-().]/g, '')\n if (format === 'url' || sibling.type === 'string') return raw.trim()\n if (sibling.type === 'decimal' || sibling.type === 'percent') {\n try {\n return parseDecimal(raw, sibling.scale ?? 2)\n } catch {\n return raw.trim()\n }\n }\n if (sibling.type === 'integer') {\n const digits = toLatinDigits(raw)\n return /^-?\\d+$/.test(digits) ? String(BigInt(digits)) : raw.trim()\n }\n return raw\n}\n\n/** An absolute http(s) URL safe to link, or null (javascript:, data: and relative are refused). */\nexport function safeUrl(value: unknown) {\n if (typeof value !== 'string' || !/^https?:\\/\\//i.test(value.trim())) return null\n try {\n const url = new URL(value.trim())\n return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : null\n } catch {\n return null\n }\n}\n\n/** A tel: link for a stored `+?digits` phone; other text gets no link. */\nexport function phoneHref(value: unknown) {\n const text = toLatinDigits(String(value ?? '')).replace(/[\\s().-]/g, '')\n return /^\\+?\\d{3,15}$/.test(text) ? `tel:${text}` : null\n}\n\n/** A mailto: link for a plain address; anything with spaces or several @ gets no link. */\nexport function emailHref(value: unknown) {\n const text = String(value ?? '').trim()\n return /^[^\\s@?#]+@[^\\s@?#]+$/.test(text) ? `mailto:${text}` : null\n}\n",
|
|
25
|
+
"content": "import type { ResourceField } from 'adula'\n\n/**\n * Pure value helpers of the generated forms and values (decimal, percent, multi-value\n * fields, visibleWhen and safe links). They have no React or alias imports, so they are\n * shared by resource-field, resource-form and resource-value and tested directly.\n */\n\ntype Scalar = string | number | boolean | null\n\n/**\n * Arabic-Indic and Persian digits and the Arabic decimal separator to Latin. Commas (and the\n * Arabic thousands mark) are removed only when they group whole thousands, as in «1,234.5»;\n * any other comma, such as «1,5», stays and makes the number invalid instead of 15.\n */\nexport function toLatinDigits(raw: string) {\n const value = raw\n .replace(/[٠-٩]/g, (digit) => String('٠١٢٣٤٥٦٧٨٩'.indexOf(digit)))\n .replace(/[۰-۹]/g, (digit) => String('۰۱۲۳۴۵۶۷۸۹'.indexOf(digit)))\n .replaceAll('٫', '.')\n .replaceAll('٬', ',')\n .trim()\n return /^-?\\d{1,3}(,\\d{3})+(\\.\\d*)?$/.test(value) ? value.replaceAll(',', '') : value\n}\n\n/** Fractional digits of a decimal or percent field (the server default is 2). */\nexport function decimalScale(field: ResourceField) {\n return (field.type === 'decimal' || field.type === 'percent') && field.scale !== undefined\n ? field.scale\n : 2\n}\n\n/**\n * Typed decimal text to the canonical wire string with exactly `scale` digits, for example\n * «١٢٫٥» → \"12.50\". Errors carry the Arabic interface text.\n */\nexport function parseDecimal(raw: string, scale: number) {\n const value = toLatinDigits(raw)\n const match = /^(-?)(\\d*)(?:\\.(\\d*))?$/.exec(value)\n if (!match || (match[2] === '' && !match[3])) throw new Error('أدخل رقماً عشرياً صحيحاً')\n const [, sign, whole, fraction = ''] = match\n const significant = fraction.replace(/0+$/, '')\n if (significant.length > scale) throw new Error('عدد المنازل العشرية أكثر من المسموح')\n const integer = whole.replace(/^0+(?=\\d)/, '') || '0'\n const digits = scale ? `.${fraction.slice(0, scale).padEnd(scale, '0')}` : ''\n const canonical = `${integer}${digits}`\n return /^0(\\.0*)?$/.test(canonical) ? canonical : `${sign}${canonical}`\n}\n\n/** The input text of a stored decimal: the canonical string, or '' when empty. */\nexport function decimalInput(value: unknown, scale: number) {\n if (value === null || value === undefined || value === '') return ''\n try {\n return parseDecimal(String(value), scale)\n } catch {\n return String(value)\n }\n}\n\n/**\n * A decimal string formatted with the interface language and Latin digits. The string is\n * formatted exactly (no float rounding), so numeric(18, 2) values keep every digit.\n */\nexport function decimalDisplay(value: unknown, scale: number, language = 'ar') {\n if (value === null || value === undefined || value === '') return ''\n const format = new Intl.NumberFormat(`${language}-u-nu-latn`, {\n minimumFractionDigits: scale,\n maximumFractionDigits: scale,\n })\n // Intl formats numeric strings as exact decimals; the lib typing only names numbers.\n return format.format(String(value) as unknown as number)\n}\n\n/** Multi-value controls keep a JSON array of strings in the string form state. */\nexport function listValue(raw: string): string[] {\n if (!raw) return []\n try {\n const parsed: unknown = JSON.parse(raw)\n return Array.isArray(parsed) ? parsed.map(String) : []\n } catch {\n return []\n }\n}\n\nexport function listInput(values: unknown): string {\n if (!Array.isArray(values) || !values.length) return ''\n return JSON.stringify([...new Set(values.map(String))])\n}\n\n/** Selected option values in the definition's option order, as the server stores them. */\nexport function orderedSelection(options: readonly { value: string }[], selected: string[]) {\n const chosen = new Set(selected)\n return options.map((option) => option.value).filter((value) => chosen.has(value))\n}\n\n/**\n * Whether a field applies to the current form values (its `visibleWhen`). Every named\n * sibling must equal the value or one of the listed values; a multiSelect sibling must\n * contain it; `null` matches an empty sibling (no selection for a multiSelect). Both sides\n * compare canonically, as the server does (see canonicalValue). Use hiddenFields() for a\n * whole form: it also hides fields whose sibling is hidden.\n */\nexport function fieldApplies(\n field: Pick<ResourceField, 'visibleWhen'>,\n values: Record<string, string>,\n siblings: Readonly<Record<string, SiblingShape>> = {}\n) {\n if (!field.visibleWhen) return true\n return Object.entries(field.visibleWhen).every(([key, expected]) => {\n const sibling = siblings[key]\n const raw = values[key] ?? ''\n const accepted: Scalar[] = Array.isArray(expected) ? expected : [expected]\n if (sibling?.type === 'multiSelect' || sibling?.type === 'manyToMany') {\n const current = listValue(raw)\n return accepted.some((entry) =>\n entry === null ? current.length === 0 : current.includes(String(entry))\n )\n }\n const current = canonicalValue(raw, sibling)\n return accepted.some((entry) =>\n entry === null ? raw.trim() === '' : canonicalValue(String(entry), sibling) === current\n )\n })\n}\n\n/**\n * The fields that do not apply, resolved to a fixed point like the server's\n * applyVisibility: a hidden field counts as empty while its dependants are evaluated, so\n * in a chain C → B → A hiding A also hides B and then C.\n */\nexport function hiddenFields(\n fields: readonly (Pick<ResourceField, 'key' | 'visibleWhen'> & SiblingShape)[],\n values: Record<string, string>\n) {\n const siblings = siblingShapes(fields)\n const hidden = new Set<string>()\n // The same passes as the server: a field is cleared as soon as it is hidden.\n const current = { ...values }\n for (let pass = 0; pass <= fields.length; pass++) {\n let changed = false\n for (const field of fields) {\n if (hidden.has(field.key) || fieldApplies(field, current, siblings)) continue\n hidden.add(field.key)\n current[field.key] = ''\n changed = true\n }\n if (!changed) break\n }\n return hidden\n}\n\n/** What fieldApplies needs to know about a sibling field. */\nexport type SiblingShape = { type: string; scale?: number; format?: string }\n\n/** The comparison shape of every field, by key. */\nexport function siblingShapes(fields: readonly (SiblingShape & { key: string })[]) {\n return Object.fromEntries(\n fields.map((field) => [\n field.key,\n { type: field.type, scale: field.scale, format: field.format } satisfies SiblingShape,\n ])\n ) as Record<string, SiblingShape>\n}\n\n/**\n * The stored form of a sibling value, mirroring the server's normalization: e-mail trimmed\n * and lower-cased, phone with Latin digits and no separators (a leading + kept), URL\n * trimmed, decimal/percent at the sibling's scale («12.5» equals \"12.50\"), integers without\n * leading zeros, string fields trimmed (the server's validator trims them). Text is\n * compared as typed (the server does not trim it).\n */\nexport function canonicalValue(raw: string, sibling?: SiblingShape) {\n if (!sibling || raw.trim() === '') return raw\n const format = sibling.type === 'string' ? sibling.format : sibling.type\n if (format === 'email') return raw.trim().toLowerCase()\n if (format === 'phone') return toLatinDigits(raw.trim()).replace(/[\\s\\-().]/g, '')\n if (format === 'url' || sibling.type === 'string') return raw.trim()\n if (sibling.type === 'decimal' || sibling.type === 'percent') {\n try {\n return parseDecimal(raw, sibling.scale ?? 2)\n } catch {\n return raw.trim()\n }\n }\n if (sibling.type === 'integer') {\n const digits = toLatinDigits(raw)\n return /^-?\\d+$/.test(digits) ? String(BigInt(digits)) : raw.trim()\n }\n return raw\n}\n\n/** An absolute http(s) URL safe to link, or null (javascript:, data: and relative are refused). */\nexport function safeUrl(value: unknown) {\n if (typeof value !== 'string' || !/^https?:\\/\\//i.test(value.trim())) return null\n try {\n const url = new URL(value.trim())\n return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : null\n } catch {\n return null\n }\n}\n\n/** A tel: link for a stored `+?digits` phone; other text gets no link. */\nexport function phoneHref(value: unknown) {\n const text = toLatinDigits(String(value ?? '')).replace(/[\\s().-]/g, '')\n return /^\\+?\\d{3,15}$/.test(text) ? `tel:${text}` : null\n}\n\n/** A mailto: link for a plain address; anything with spaces or several @ gets no link. */\nexport function emailHref(value: unknown) {\n const text = String(value ?? '').trim()\n return /^[^\\s@?#]+@[^\\s@?#]+$/.test(text) ? `mailto:${text}` : null\n}\n\nconst RELATION_META = new Set(['id', 'version', 'docStatus', 'orgUnitId'])\n\n/**\n * The label of a related record: the title the server computed (`_title`, #47), else the\n * first readable text of the row (older servers), else `#id`. Without a row the reader may\n * not view the record (or it was deleted), so it is labelled `unavailable`, never by its id.\n */\nexport function relationText(\n row: Record<string, unknown> | undefined,\n fallback: unknown,\n unavailable = 'سجل غير متاح'\n): string {\n if (fallback === null || fallback === undefined) return row ? (relationTitleOf(row) ?? '—') : '—'\n if (!row) return unavailable\n return relationTitleOf(row) ?? `#${String(fallback)}`\n}\n\nfunction relationTitleOf(row: Record<string, unknown>) {\n if ('_title' in row) return typeof row._title === 'string' && row._title ? row._title : null\n const label = Object.entries(row).find(\n ([key, entry]) => !RELATION_META.has(key) && typeof entry === 'string' && entry\n )\n return label ? String(label[1]) : null\n}\n\n/**\n * Text folded for matching Arabic as people type it (#114): hamza forms of alef, taa marbuta,\n * alef maqsura, harakat and tatweel are ignored, Latin letters compare without case, and\n * Arabic-Indic digits match Latin ones. «اراده» finds «إرادة»، «اسكان» finds «إسكان».\n */\nexport function foldArabic(text: string) {\n return toLatinDigits(text.normalize('NFC'))\n .replace(/[\\u064B-\\u065F\\u0670\\u0640]/g, '')\n .replace(/[أإآٱ]/g, 'ا')\n .replace(/ة/g, 'ه')\n .replace(/ى/g, 'ي')\n .toLocaleLowerCase('en')\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\n/** A cmdk `filter`: 1 when the folded search occurs in the folded value or one of its keywords. */\nexport function foldedFilter(value: string, search: string, keywords: string[] = []) {\n const wanted = foldArabic(search)\n if (!wanted) return 1\n return [value, ...keywords].some((text) => foldArabic(text).includes(wanted)) ? 1 : 0\n}\n",
|
|
25
26
|
"target": "inertia/components/ui/field_values.ts"
|
|
26
27
|
}
|
|
27
28
|
],
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "slider",
|
|
3
|
+
"type": "registry:ui",
|
|
4
|
+
"dependencies": [
|
|
5
|
+
"cn@0.3.0",
|
|
6
|
+
"radix-ui@1.6.7"
|
|
7
|
+
],
|
|
8
|
+
"files": [
|
|
9
|
+
{
|
|
10
|
+
"path": "registry/ui/slider.tsx",
|
|
11
|
+
"type": "registry:ui",
|
|
12
|
+
"content": "import * as React from \"react\"\nimport { cn } from \"cn\"\nimport { Slider as SliderPrimitive } from \"radix-ui\"\n\n/**\n * A range slider on the Radix primitive (arrow keys, Home/End and Page keys move it). Right to\n * left by default like the other copied primitives; pass `dir=\"ltr\"` for a left-to-right scale.\n */\nfunction Slider({\n className,\n defaultValue,\n value,\n min = 0,\n max = 100,\n dir = \"rtl\",\n ...props\n}: React.ComponentProps<typeof SliderPrimitive.Root>) {\n const values = React.useMemo(\n () => (Array.isArray(value) ? value : Array.isArray(defaultValue) ? defaultValue : [min]),\n [value, defaultValue, min]\n )\n return (\n <SliderPrimitive.Root\n data-slot=\"slider\"\n defaultValue={defaultValue}\n value={value}\n min={min}\n max={max}\n dir={dir}\n className={cn(\n \"relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col\",\n className\n )}\n {...props}\n >\n <SliderPrimitive.Track\n data-slot=\"slider-track\"\n className=\"relative grow overflow-hidden rounded-full bg-muted data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5\"\n >\n <SliderPrimitive.Range\n data-slot=\"slider-range\"\n className=\"absolute bg-primary data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full\"\n />\n </SliderPrimitive.Track>\n {values.map((_, index) => (\n <SliderPrimitive.Thumb\n data-slot=\"slider-thumb\"\n key={index}\n className=\"block size-4 shrink-0 rounded-full border border-primary bg-background shadow-sm ring-ring/50 transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50\"\n />\n ))}\n </SliderPrimitive.Root>\n )\n}\n\nexport { Slider }\n",
|
|
13
|
+
"target": "inertia/components/ui/slider.tsx"
|
|
14
|
+
}
|
|
15
|
+
],
|
|
16
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
17
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "sortable-list",
|
|
3
|
+
"type": "registry:ui",
|
|
4
|
+
"registryDependencies": [
|
|
5
|
+
"button",
|
|
6
|
+
"messages"
|
|
7
|
+
],
|
|
8
|
+
"dependencies": [
|
|
9
|
+
"lucide-react@1.47.0"
|
|
10
|
+
],
|
|
11
|
+
"files": [
|
|
12
|
+
{
|
|
13
|
+
"path": "registry/ui/sortable-list.tsx",
|
|
14
|
+
"type": "registry:ui",
|
|
15
|
+
"content": "import { useRef, useState, type KeyboardEvent, type PointerEvent, type ReactNode } from 'react'\nimport { ArrowDown, ArrowUp, GripVertical } from 'lucide-react'\nimport { Button } from '~/components/ui/button'\nimport { useMessages } from '~/components/ui/messages'\n\nexport type SortableItem = { id: string; label: string }\n\n/**\n * A vertical list the user reorders by dragging a row's handle, with the keyboard (Space or\n * Enter picks a row up, the arrow keys, Home and End move it, Space or Enter drops it, Escape\n * puts it back) or with the move buttons. Every move is announced. While a row is picked up\n * its handle carries `data-sortable-picked`, so a surrounding Dialog can keep Escape for the\n * list (see `keepEscapeForSorting`).\n */\nexport function SortableList<T extends SortableItem>({\n items,\n onChange,\n renderItem,\n label,\n}: {\n items: T[]\n onChange: (items: T[]) => void\n renderItem?: (item: T) => ReactNode\n /** The list's accessible name. */\n label: string\n}) {\n const { t } = useMessages()\n const [picked, setPicked] = useState<{ id: string; from: number; original: T[] } | null>(null)\n const [dragging, setDragging] = useState<string | null>(null)\n const [announcement, setAnnouncement] = useState('')\n const rows = useRef(new Map<string, HTMLLIElement>())\n const handles = useRef(new Map<string, HTMLButtonElement>())\n\n const move = (list: T[], id: string, to: number) => {\n const from = list.findIndex((item) => item.id === id)\n if (from === -1) return list\n const target = Math.max(0, Math.min(list.length - 1, to))\n if (target === from) return list\n const next = [...list]\n const [item] = next.splice(from, 1)\n next.splice(target, 0, item)\n return next\n }\n const position = (list: T[], id: string) => list.findIndex((item) => item.id === id) + 1\n const commit = (next: T[], id: string, message: 'moved' | 'dropped') => {\n onChange(next)\n const item = next.find((entry) => entry.id === id)\n if (!item) return\n const values = {\n item: item.label,\n position: String(position(next, id)),\n total: String(next.length),\n }\n setAnnouncement(\n message === 'moved'\n ? t('نُقل {item} إلى الموضع {position} من {total}.', values)\n : t('وُضع {item} في الموضع {position} من {total}.', values)\n )\n // Keep focus on the moved row's handle after React re-renders the list.\n requestAnimationFrame(() => handles.current.get(id)?.focus())\n }\n\n const keyDown = (event: KeyboardEvent<HTMLButtonElement>, item: T) => {\n const index = items.findIndex((entry) => entry.id === item.id)\n if (!picked) {\n if (event.key === ' ' || event.key === 'Enter') {\n event.preventDefault()\n setPicked({ id: item.id, from: index, original: items })\n setAnnouncement(\n t('تم التقاط {item}، الموضع {position} من {total}. استخدم الأسهم للنقل ثم المسافة للإفلات.', {\n item: item.label,\n position: String(index + 1),\n total: String(items.length),\n })\n )\n }\n return\n }\n if (picked.id !== item.id) return\n const targets: Record<string, number> = {\n ArrowUp: index - 1,\n ArrowDown: index + 1,\n Home: 0,\n End: items.length - 1,\n }\n if (event.key in targets) {\n event.preventDefault()\n commit(move(items, item.id, targets[event.key]), item.id, 'moved')\n } else if (event.key === ' ' || event.key === 'Enter') {\n event.preventDefault()\n setPicked(null)\n commit(items, item.id, 'dropped')\n } else if (event.key === 'Escape') {\n event.preventDefault()\n event.stopPropagation()\n setPicked(null)\n onChange(picked.original)\n setAnnouncement(\n t('أُلغي النقل وعاد {item} إلى الموضع {position}.', {\n item: item.label,\n position: String(picked.from + 1),\n })\n )\n requestAnimationFrame(() => handles.current.get(item.id)?.focus())\n }\n }\n\n const pointerDown = (event: PointerEvent<HTMLButtonElement>, item: T) => {\n if (event.button !== 0) return\n event.preventDefault()\n event.currentTarget.setPointerCapture(event.pointerId)\n setPicked(null)\n setDragging(item.id)\n }\n const pointerMove = (event: PointerEvent<HTMLButtonElement>, item: T) => {\n if (dragging !== item.id) return\n // The new position is the number of other rows whose middle lies above the pointer.\n let to = 0\n for (const entry of items) {\n if (entry.id === item.id) continue\n const box = rows.current.get(entry.id)?.getBoundingClientRect()\n if (box && event.clientY > box.top + box.height / 2) to++\n }\n const from = items.findIndex((entry) => entry.id === item.id)\n if (to !== from) onChange(move(items, item.id, to))\n }\n const pointerUp = (item: T) => {\n if (dragging !== item.id) return\n setDragging(null)\n commit(items, item.id, 'dropped')\n }\n\n return (\n <>\n <ul aria-label={label} className=\"divide-y rounded-lg border\">\n {items.map((item, index) => {\n const active = picked?.id === item.id || dragging === item.id\n return (\n <li\n key={item.id}\n ref={(node) => {\n if (node) rows.current.set(item.id, node)\n else rows.current.delete(item.id)\n }}\n data-sortable-item={item.id}\n data-active={active || undefined}\n className=\"flex items-center gap-2 bg-background px-2 py-1.5 data-[active]:bg-accent\"\n >\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n ref={(node) => {\n if (node) handles.current.set(item.id, node)\n else handles.current.delete(item.id)\n }}\n aria-label={t('مقبض نقل {item}', { item: item.label })}\n aria-pressed={picked?.id === item.id}\n aria-describedby=\"sortable-list-hint\"\n data-sortable-picked={picked?.id === item.id || undefined}\n className=\"cursor-grab touch-none active:cursor-grabbing\"\n onKeyDown={(event) => keyDown(event, item)}\n onBlur={() => picked?.id === item.id && setPicked(null)}\n onPointerDown={(event) => pointerDown(event, item)}\n onPointerMove={(event) => pointerMove(event, item)}\n onPointerUp={() => pointerUp(item)}\n onPointerCancel={() => pointerUp(item)}\n >\n <GripVertical size={16} />\n </Button>\n <div className=\"min-w-0 flex-1\">{renderItem ? renderItem(item) : item.label}</div>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n disabled={index === 0}\n aria-label={t('نقل {item} للأعلى', { item: item.label })}\n onClick={() => commit(move(items, item.id, index - 1), item.id, 'moved')}\n >\n <ArrowUp size={15} />\n </Button>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n disabled={index === items.length - 1}\n aria-label={t('نقل {item} للأسفل', { item: item.label })}\n onClick={() => commit(move(items, item.id, index + 1), item.id, 'moved')}\n >\n <ArrowDown size={15} />\n </Button>\n </li>\n )\n })}\n </ul>\n <p id=\"sortable-list-hint\" className=\"sr-only\">\n {t('اضغط المسافة لالتقاط العنصر، ثم الأسهم لنقله، ثم المسافة لإفلاته، أو Escape للإلغاء.')}\n </p>\n <p aria-live=\"polite\" role=\"status\" className=\"sr-only\" data-testid=\"sortable-announcement\">\n {announcement}\n </p>\n </>\n )\n}\n\n/** For a Dialog's `onEscapeKeyDown`: Escape cancels a keyboard move instead of closing. */\nexport function keepEscapeForSorting(event: KeyboardEvent | globalThis.KeyboardEvent) {\n const target = event.target as Element | null\n if (target?.closest?.('[data-sortable-picked]')) event.preventDefault()\n}\n",
|
|
16
|
+
"target": "inertia/components/ui/sortable-list.tsx"
|
|
17
|
+
}
|
|
18
|
+
],
|
|
19
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
20
|
+
}
|
package/build/tabs.json
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
{
|
|
11
11
|
"path": "registry/ui/tabs.tsx",
|
|
12
12
|
"type": "registry:ui",
|
|
13
|
-
"content": "import * as React from \"react\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { cn } from \"cn\"\nimport { Tabs as TabsPrimitive } from \"radix-ui\"\n\nfunction Tabs({\n className,\n orientation = \"horizontal\",\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.Root>) {\n return (\n <TabsPrimitive.Root dir=\"rtl\"\n data-slot=\"tabs\"\n data-orientation={orientation}\n orientation={orientation}\n className={cn(\n \"group/tabs flex gap-2 data-[orientation=horizontal]:flex-col\",\n className\n )}\n {...props}\n />\n )\n}\n\nconst tabsListVariants = cva(\n \"group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-[orientation=horizontal]/tabs:h-9 group-data-[orientation=vertical]/tabs:h-fit group-data-[orientation=vertical]/tabs:flex-col data-[variant=line]:rounded-none\",\n {\n variants: {\n variant: {\n default: \"bg-muted\",\n line: \"gap-1 bg-transparent\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n },\n }\n)\n\nfunction TabsList({\n className,\n variant = \"default\",\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.List> &\n VariantProps<typeof tabsListVariants>) {\n return (\n <TabsPrimitive.List\n data-slot=\"tabs-list\"\n data-variant={variant}\n className={cn(tabsListVariants({ variant }), className)}\n {...props}\n />\n )\n}\n\nfunction TabsTrigger({\n className,\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {\n return (\n <TabsPrimitive.Trigger\n data-slot=\"tabs-trigger\"\n className={cn(\n \"relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-[orientation=vertical]/tabs:w-full group-data-[orientation=vertical]/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 group-data-[variant=default]/tabs-list:data-[state=active]:shadow-sm group-data-[variant=line]/tabs-list:data-[state=active]:shadow-none dark:text-muted-foreground dark:hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n \"group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent\",\n \"data-[state=active]:bg-background data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 dark:data-[state=active]:text-foreground\",\n \"after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-[orientation=horizontal]/tabs:after:inset-x-0 group-data-[orientation=horizontal]/tabs:after:bottom-[-5px] group-data-[orientation=horizontal]/tabs:after:h-0.5 group-data-[orientation=vertical]/tabs:after:inset-y-0 group-data-[orientation=vertical]/tabs:after:-end-1 group-data-[orientation=vertical]/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-[state=active]:after:opacity-100\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction TabsContent({\n className,\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.Content>) {\n return (\n <TabsPrimitive.Content\n data-slot=\"tabs-content\"\n className={cn(\"flex-1 outline-none\", className)}\n {...props}\n />\n )\n}\n\nexport { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }\n",
|
|
13
|
+
"content": "import * as React from \"react\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { cn } from \"cn\"\nimport { Tabs as TabsPrimitive } from \"radix-ui\"\n\nfunction Tabs({\n className,\n orientation = \"horizontal\",\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.Root>) {\n return (\n <TabsPrimitive.Root dir=\"rtl\"\n data-slot=\"tabs\"\n data-orientation={orientation}\n orientation={orientation}\n className={cn(\n \"group/tabs flex gap-2 data-[orientation=horizontal]:flex-col\",\n className\n )}\n {...props}\n />\n )\n}\n\nconst tabsListVariants = cva(\n \"group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-[orientation=horizontal]/tabs:h-9 group-data-[orientation=vertical]/tabs:h-fit group-data-[orientation=vertical]/tabs:flex-col data-[variant=line]:rounded-none\",\n {\n variants: {\n variant: {\n default: \"bg-muted\",\n line: \"gap-1 bg-transparent\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n },\n }\n)\n\n// AdulaJS: a list with more tabs than fit. From the medium breakpoint it wraps onto further\n// rows, so no tab is hidden; below it, one row that scrolls sideways, with a little more\n// inline padding so the focus ring of the first and last tab is not clipped at its ends.\nconst tabsListWrap =\n \"max-w-full justify-start overflow-x-auto px-1 [scrollbar-width:none] md:flex-wrap md:px-[3px] md:overflow-visible group-data-[orientation=horizontal]/tabs:data-[wrap=true]:md:h-auto\"\n\nfunction TabsList({\n className,\n variant = \"default\",\n wrap = false,\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.List> &\n VariantProps<typeof tabsListVariants> & {\n /** Wrap onto further rows from the medium breakpoint; scroll sideways below it. */\n wrap?: boolean\n }) {\n return (\n <TabsPrimitive.List\n data-slot=\"tabs-list\"\n data-variant={variant}\n data-wrap={wrap ? \"true\" : undefined}\n className={cn(tabsListVariants({ variant }), wrap && tabsListWrap, className)}\n {...props}\n />\n )\n}\n\nfunction TabsTrigger({\n className,\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {\n return (\n <TabsPrimitive.Trigger\n data-slot=\"tabs-trigger\"\n className={cn(\n \"relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-[orientation=vertical]/tabs:w-full group-data-[orientation=vertical]/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 group-data-[variant=default]/tabs-list:data-[state=active]:shadow-sm group-data-[variant=line]/tabs-list:data-[state=active]:shadow-none dark:text-muted-foreground dark:hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n \"group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent\",\n \"data-[state=active]:bg-background data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 dark:data-[state=active]:text-foreground\",\n \"group-data-[wrap=true]/tabs-list:flex-none group-data-[wrap=true]/tabs-list:md:h-8\",\n \"after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-[orientation=horizontal]/tabs:after:inset-x-0 group-data-[orientation=horizontal]/tabs:after:bottom-[-5px] group-data-[orientation=horizontal]/tabs:after:h-0.5 group-data-[orientation=vertical]/tabs:after:inset-y-0 group-data-[orientation=vertical]/tabs:after:-end-1 group-data-[orientation=vertical]/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-[state=active]:after:opacity-100\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction TabsContent({\n className,\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.Content>) {\n return (\n <TabsPrimitive.Content\n data-slot=\"tabs-content\"\n className={cn(\"flex-1 outline-none\", className)}\n {...props}\n />\n )\n}\n\nexport { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }\n",
|
|
14
14
|
"target": "inertia/components/ui/tabs.tsx"
|
|
15
15
|
}
|
|
16
16
|
],
|