@adula/ui 2.1.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -3
- package/build/attachment-preview.json +21 -0
- package/build/breadcrumb.json +18 -0
- package/build/calendar.json +1 -1
- package/build/checkbox.json +1 -1
- package/build/command.json +1 -1
- package/build/confirm-action.json +3 -2
- package/build/copy-button.json +21 -0
- package/build/data-table.json +8 -2
- package/build/dialog-param.json +17 -0
- package/build/dialog.json +3 -2
- package/build/dropdown-menu.json +1 -1
- package/build/file-input.json +21 -0
- package/build/form.json +1 -1
- package/build/hijri-calendar.json +1 -1
- package/build/label.json +1 -1
- package/build/list-filters.json +34 -0
- package/build/long-dialog.json +17 -0
- package/build/manifest.json +146 -76
- package/build/messages.json +21 -0
- package/build/pagination.json +3 -2
- package/build/popover.json +1 -1
- package/build/radio-group.json +1 -1
- package/build/record-assignments.json +3 -2
- package/build/record-collaboration.json +4 -2
- package/build/record-print.json +24 -0
- package/build/record-workflows.json +3 -2
- package/build/resource-actions.json +3 -2
- package/build/resource-bulk.json +27 -0
- package/build/resource-dashboard.json +27 -0
- package/build/resource-field.json +7 -2
- package/build/resource-form.json +4 -2
- package/build/resource-import.json +7 -3
- package/build/resource-page.json +4 -2
- package/build/resource-show.json +6 -2
- package/build/resource-surface.json +4 -2
- package/build/resource-value.json +11 -2
- package/build/select.json +1 -1
- package/build/separator.json +1 -1
- package/build/sheet.json +1 -1
- package/build/slider.json +17 -0
- package/build/sonner.json +1 -1
- package/build/sortable-list.json +20 -0
- package/build/switch.json +1 -1
- package/build/table.json +1 -1
- package/build/tabs.json +1 -1
- package/build/theme.css +48 -2
- package/build/tooltip.json +1 -1
- package/build/user-avatar.json +17 -0
- package/package.json +5 -2
package/build/resource-show.json
CHANGED
|
@@ -11,7 +11,11 @@
|
|
|
11
11
|
"ui-preferences",
|
|
12
12
|
"record-collaboration",
|
|
13
13
|
"record-assignments",
|
|
14
|
-
"record-workflows"
|
|
14
|
+
"record-workflows",
|
|
15
|
+
"record-print",
|
|
16
|
+
"resource-surface",
|
|
17
|
+
"messages",
|
|
18
|
+
"user-avatar"
|
|
15
19
|
],
|
|
16
20
|
"dependencies": [
|
|
17
21
|
"lucide-react@1.47.0"
|
|
@@ -20,7 +24,7 @@
|
|
|
20
24
|
{
|
|
21
25
|
"path": "registry/ui/resource-show.tsx",
|
|
22
26
|
"type": "registry:ui",
|
|
23
|
-
"content": "import { Deferred, router } from '@inertiajs/react'\nimport { Link } from '@adonisjs/inertia/react'\nimport { History, Pencil, Printer } 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 { 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'\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}\n\nexport function documentStatus(status: unknown) {\n return status === 1 ? 'معتمد' : status === 2 ? 'ملغي' : 'مسودة'\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 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 resource.fields.find((field) => field.key === key)?.label.ar ?? key\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 تعديل السجل\n </Button>\n ) : (\n <Button asChild>\n <Link href={`${base}/edit`}>\n <Pencil size={15} />\n تعديل السجل\n </Link>\n </Button>\n )}\n </Can>\n <Button variant=\"outline\" asChild>\n <a href={`${base}/print`} target=\"_blank\" rel=\"noopener\">\n <Printer size={15} />\n طباعة\n </a>\n </Button>\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)}\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\">{field.label.ar}</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\">الوحدة التنظيمية</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=\"البنود\" 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={field.label.ar}\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\">{field.label.ar}</h2>\n <span className=\"text-xs text-muted-foreground\">\n {group.rows.length} بند{group.hasMore ? ' · تظهر أول 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 {columns.find((entry) => entry.key === key)?.label.ar ?? 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\">لا توجد بنود متاحة.</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=\"سجل النشاط\" rows={4} />}>\n <section aria-label=\"سجل النشاط\" 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\">سجل النشاط</h2>\n <span className=\"ms-auto text-xs text-muted-foreground\">\n آخر {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] ?? entry.action}\n </span>\n <span className=\"text-xs text-muted-foreground\">\n {entry.actorName ?? `مستخدم #${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 الحقول: {entry.fields.map(fieldLabel).join('، ')}\n </span>\n )}\n </li>\n ))}\n </ol>\n ) : (\n <p className=\"px-7 py-6 text-xs text-muted-foreground\">لا يوجد نشاط مسجل بعد.</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 return (\n <section\n role=\"status\"\n aria-label={`جارٍ تحميل ${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",
|
|
24
28
|
"target": "inertia/components/ui/resource-show.tsx"
|
|
25
29
|
}
|
|
26
30
|
],
|
|
@@ -3,14 +3,16 @@
|
|
|
3
3
|
"type": "registry:ui",
|
|
4
4
|
"registryDependencies": [
|
|
5
5
|
"button",
|
|
6
|
-
"dialog"
|
|
6
|
+
"dialog",
|
|
7
|
+
"long-dialog",
|
|
8
|
+
"messages"
|
|
7
9
|
],
|
|
8
10
|
"dependencies": [],
|
|
9
11
|
"files": [
|
|
10
12
|
{
|
|
11
13
|
"path": "registry/ui/resource-surface.tsx",
|
|
12
14
|
"type": "registry:ui",
|
|
13
|
-
"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'\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 [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=\"rtl\" className=\"space-y-6\">\n <Button variant=\"outline\" asChild>\n <Link href={backHref}>العودة إلى القائمة</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=\"rtl\"\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",
|
|
14
16
|
"target": "inertia/components/ui/resource-surface.tsx"
|
|
15
17
|
}
|
|
16
18
|
],
|
|
@@ -3,8 +3,11 @@
|
|
|
3
3
|
"type": "registry:ui",
|
|
4
4
|
"registryDependencies": [
|
|
5
5
|
"badge",
|
|
6
|
+
"attachment-preview",
|
|
6
7
|
"calendar-date",
|
|
7
|
-
"ui-preferences"
|
|
8
|
+
"ui-preferences",
|
|
9
|
+
"messages",
|
|
10
|
+
"user-avatar"
|
|
8
11
|
],
|
|
9
12
|
"dependencies": [
|
|
10
13
|
"lucide-react@1.47.0"
|
|
@@ -13,8 +16,14 @@
|
|
|
13
16
|
{
|
|
14
17
|
"path": "registry/ui/resource-value.tsx",
|
|
15
18
|
"type": "registry:ui",
|
|
16
|
-
"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 { Badge } from '~/components/ui/badge'\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}\n\n/** Project-owned copy: change the label once here for another currency. */\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\nexport function toLatinDigits(raw: string) {\n return raw\n .replace(/[٠-٩]/g, (digit) => String('٠١٢٣٤٥٦٧٨٩'.indexOf(digit)))\n .replace(/[۰-۹]/g, (digit) => String('۰۱۲۳۴۵۶۷۸۹'.indexOf(digit)))\n .replaceAll('٫', '.')\n .replaceAll('٬', '')\n .replaceAll(',', '')\n .trim()\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\nexport function fileSize(bytes: number) {\n if (bytes < 1024) return `${integerFormat.format(bytes)} بايت`\n if (bytes < 1024 * 1024) return `${sizeFormat.format(bytes / 1024)} ك.ب`\n return `${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 === 'json') return JSON.stringify(value, null, 2)\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/** Converts a control's string state into the JSON the resource route validates. */\nexport function parseValue(field: ResourceField, raw: string): unknown {\n if (raw === '') return null\n switch (field.type) {\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) {\n const value = row[field.key]\n if (value === null || value === undefined || value === '') return '—'\n switch (field.type) {\n case 'money':\n return `${moneyDisplay(value)} ${CURRENCY_LABEL}`\n case 'boolean':\n return value ? 'نعم' : 'لا'\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 return isAttachment(value) ? value.name : 'مرفق'\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\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 value = row[field.key]\n if (value === null || value === undefined || value === '')\n return <span className=\"text-muted-foreground\">—</span>\n if (field.type === 'attachment' && isAttachment(value))\n return (\n <a\n href={value.url}\n download={value.name}\n className=\"inline-flex items-center gap-2 text-primary underline-offset-4 hover:underline\"\n >\n <Paperclip size={14} />\n {value.name}\n <span className=\"text-xs text-muted-foreground\">({fileSize(value.size)})</span>\n </a>\n )\n if (field.type === 'boolean')\n return <Badge variant={value ? 'default' : 'secondary'}>{value ? 'نعم' : 'لا'}</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\">{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)}\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)}</bdi>\n return <>{displayValue(field, row, related, lookups, calendar)}</>\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",
|
|
17
20
|
"target": "inertia/components/ui/resource-value.tsx"
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
"path": "registry/ui/field_values.ts",
|
|
24
|
+
"type": "registry:ui",
|
|
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",
|
|
26
|
+
"target": "inertia/components/ui/field_values.ts"
|
|
18
27
|
}
|
|
19
28
|
],
|
|
20
29
|
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
package/build/select.json
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
{
|
|
10
10
|
"path": "registry/ui/select.tsx",
|
|
11
11
|
"type": "registry:ui",
|
|
12
|
-
"content": "
|
|
12
|
+
"content": "import * as React from \"react\"\nimport { cn } from \"cn\"\nimport { CheckIcon, ChevronDownIcon, ChevronUpIcon } from \"lucide-react\"\nimport { Select as SelectPrimitive } from \"radix-ui\"\n\nfunction Select({\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Root>) {\n return <SelectPrimitive.Root dir=\"rtl\" data-slot=\"select\" {...props} />\n}\n\nfunction SelectGroup({\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Group>) {\n return <SelectPrimitive.Group data-slot=\"select-group\" {...props} />\n}\n\nfunction SelectValue({\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Value>) {\n return <SelectPrimitive.Value data-slot=\"select-value\" {...props} />\n}\n\nfunction SelectTrigger({\n className,\n size = \"default\",\n children,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {\n size?: \"sm\" | \"default\"\n}) {\n return (\n <SelectPrimitive.Trigger\n data-slot=\"select-trigger\"\n data-size={size}\n className={cn(\n \"flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground\",\n className\n )}\n {...props}\n >\n {children}\n <SelectPrimitive.Icon asChild>\n <ChevronDownIcon className=\"size-4 opacity-50\" />\n </SelectPrimitive.Icon>\n </SelectPrimitive.Trigger>\n )\n}\n\nfunction SelectContent({\n className,\n children,\n position = \"item-aligned\",\n align = \"center\",\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Content>) {\n return (\n <SelectPrimitive.Portal>\n <SelectPrimitive.Content\n data-slot=\"select-content\"\n className={cn(\n \"relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95\",\n position === \"popper\" &&\n \"data-[side=bottom]:translate-y-1 ltr:data-[side=left]:-translate-x-1 rtl:data-[side=left]:translate-x-1 ltr:data-[side=right]:translate-x-1 rtl:data-[side=right]:-translate-x-1 data-[side=top]:-translate-y-1\",\n className\n )}\n position={position}\n align={align}\n {...props}\n >\n <SelectScrollUpButton />\n <SelectPrimitive.Viewport\n className={cn(\n \"p-1\",\n position === \"popper\" &&\n \"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1\"\n )}\n >\n {children}\n </SelectPrimitive.Viewport>\n <SelectScrollDownButton />\n </SelectPrimitive.Content>\n </SelectPrimitive.Portal>\n )\n}\n\nfunction SelectLabel({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Label>) {\n return (\n <SelectPrimitive.Label\n data-slot=\"select-label\"\n className={cn(\"px-2 py-1.5 text-xs text-muted-foreground\", className)}\n {...props}\n />\n )\n}\n\nfunction SelectItem({\n className,\n children,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Item>) {\n return (\n <SelectPrimitive.Item\n data-slot=\"select-item\"\n className={cn(\n \"relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pe-8 ps-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2\",\n className\n )}\n {...props}\n >\n <span\n data-slot=\"select-item-indicator\"\n className=\"absolute end-2 flex size-3.5 items-center justify-center\"\n >\n <SelectPrimitive.ItemIndicator>\n <CheckIcon className=\"size-4\" />\n </SelectPrimitive.ItemIndicator>\n </span>\n <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>\n </SelectPrimitive.Item>\n )\n}\n\nfunction SelectSeparator({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Separator>) {\n return (\n <SelectPrimitive.Separator\n data-slot=\"select-separator\"\n className={cn(\"pointer-events-none -mx-1 my-1 h-px bg-border\", className)}\n {...props}\n />\n )\n}\n\nfunction SelectScrollUpButton({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {\n return (\n <SelectPrimitive.ScrollUpButton\n data-slot=\"select-scroll-up-button\"\n className={cn(\n \"flex cursor-default items-center justify-center py-1\",\n className\n )}\n {...props}\n >\n <ChevronUpIcon className=\"size-4\" />\n </SelectPrimitive.ScrollUpButton>\n )\n}\n\nfunction SelectScrollDownButton({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {\n return (\n <SelectPrimitive.ScrollDownButton\n data-slot=\"select-scroll-down-button\"\n className={cn(\n \"flex cursor-default items-center justify-center py-1\",\n className\n )}\n {...props}\n >\n <ChevronDownIcon className=\"size-4\" />\n </SelectPrimitive.ScrollDownButton>\n )\n}\n\nexport {\n Select,\n SelectContent,\n SelectGroup,\n SelectItem,\n SelectLabel,\n SelectScrollDownButton,\n SelectScrollUpButton,\n SelectSeparator,\n SelectTrigger,\n SelectValue,\n}\n",
|
|
13
13
|
"target": "inertia/components/ui/select.tsx"
|
|
14
14
|
}
|
|
15
15
|
],
|
package/build/separator.json
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
{
|
|
10
10
|
"path": "registry/ui/separator.tsx",
|
|
11
11
|
"type": "registry:ui",
|
|
12
|
-
"content": "
|
|
12
|
+
"content": "import * as React from \"react\"\nimport { cn } from \"cn\"\nimport { Separator as SeparatorPrimitive } from \"radix-ui\"\n\nfunction Separator({\n className,\n orientation = \"horizontal\",\n decorative = true,\n ...props\n}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {\n return (\n <SeparatorPrimitive.Root\n data-slot=\"separator\"\n decorative={decorative}\n orientation={orientation}\n className={cn(\n \"shrink-0 bg-border data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Separator }\n",
|
|
13
13
|
"target": "inertia/components/ui/separator.tsx"
|
|
14
14
|
}
|
|
15
15
|
],
|
package/build/sheet.json
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
{
|
|
10
10
|
"path": "registry/ui/sheet.tsx",
|
|
11
11
|
"type": "registry:ui",
|
|
12
|
-
"content": "
|
|
12
|
+
"content": "import * as React from \"react\"\nimport { cn } from \"cn\"\nimport { XIcon } from \"lucide-react\"\nimport { Dialog as SheetPrimitive } from \"radix-ui\"\n\nfunction Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {\n return <SheetPrimitive.Root data-slot=\"sheet\" {...props} />\n}\n\nfunction SheetTrigger({\n ...props\n}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {\n return <SheetPrimitive.Trigger data-slot=\"sheet-trigger\" {...props} />\n}\n\nfunction SheetClose({\n ...props\n}: React.ComponentProps<typeof SheetPrimitive.Close>) {\n return <SheetPrimitive.Close data-slot=\"sheet-close\" {...props} />\n}\n\nfunction SheetPortal({\n ...props\n}: React.ComponentProps<typeof SheetPrimitive.Portal>) {\n return <SheetPrimitive.Portal data-slot=\"sheet-portal\" {...props} />\n}\n\nfunction SheetOverlay({\n className,\n ...props\n}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {\n return (\n <SheetPrimitive.Overlay\n data-slot=\"sheet-overlay\"\n className={cn(\n \"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction SheetContent({\n className,\n children,\n side = \"right\",\n showCloseButton = true,\n ...props\n}: React.ComponentProps<typeof SheetPrimitive.Content> & {\n side?: \"top\" | \"right\" | \"bottom\" | \"left\"\n showCloseButton?: boolean\n}) {\n return (\n <SheetPortal>\n <SheetOverlay />\n <SheetPrimitive.Content\n data-slot=\"sheet-content\"\n className={cn(\n \"fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:animate-in data-[state=open]:duration-500\",\n side === \"right\" &&\n \"inset-y-0 end-0 h-full w-3/4 border-s data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm\",\n side === \"left\" &&\n \"inset-y-0 start-0 h-full w-3/4 border-e data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm\",\n side === \"top\" &&\n \"inset-x-0 top-0 h-auto border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top\",\n side === \"bottom\" &&\n \"inset-x-0 bottom-0 h-auto border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom\",\n className\n )}\n {...props}\n >\n {children}\n {showCloseButton && (\n <SheetPrimitive.Close className=\"absolute top-4 end-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-secondary\">\n <XIcon className=\"size-4\" />\n <span className=\"sr-only\">إغلاق</span>\n </SheetPrimitive.Close>\n )}\n </SheetPrimitive.Content>\n </SheetPortal>\n )\n}\n\nfunction SheetHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"sheet-header\"\n className={cn(\"flex flex-col gap-1.5 p-4\", className)}\n {...props}\n />\n )\n}\n\nfunction SheetFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"sheet-footer\"\n className={cn(\"mt-auto flex flex-col gap-2 p-4\", className)}\n {...props}\n />\n )\n}\n\nfunction SheetTitle({\n className,\n ...props\n}: React.ComponentProps<typeof SheetPrimitive.Title>) {\n return (\n <SheetPrimitive.Title\n data-slot=\"sheet-title\"\n className={cn(\"font-semibold text-foreground\", className)}\n {...props}\n />\n )\n}\n\nfunction SheetDescription({\n className,\n ...props\n}: React.ComponentProps<typeof SheetPrimitive.Description>) {\n return (\n <SheetPrimitive.Description\n data-slot=\"sheet-description\"\n className={cn(\"text-sm text-muted-foreground\", className)}\n {...props}\n />\n )\n}\n\nexport {\n Sheet,\n SheetTrigger,\n SheetClose,\n SheetContent,\n SheetHeader,\n SheetFooter,\n SheetTitle,\n SheetDescription,\n}\n",
|
|
13
13
|
"target": "inertia/components/ui/sheet.tsx"
|
|
14
14
|
}
|
|
15
15
|
],
|
|
@@ -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
|
+
}
|
package/build/sonner.json
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
{
|
|
9
9
|
"path": "registry/ui/sonner.tsx",
|
|
10
10
|
"type": "registry:ui",
|
|
11
|
-
"content": "
|
|
11
|
+
"content": "import {\n CircleCheckIcon,\n InfoIcon,\n Loader2Icon,\n OctagonXIcon,\n TriangleAlertIcon,\n} from \"lucide-react\"\nimport { Toaster as Sonner, type ToasterProps } from \"sonner\"\n\nconst Toaster = ({ ...props }: ToasterProps) => {\n\n return (\n <Sonner\n theme=\"light\"\n dir=\"rtl\"\n className=\"toaster group\"\n icons={{\n success: <CircleCheckIcon className=\"size-4\" />,\n info: <InfoIcon className=\"size-4\" />,\n warning: <TriangleAlertIcon className=\"size-4\" />,\n error: <OctagonXIcon className=\"size-4\" />,\n loading: <Loader2Icon className=\"size-4 animate-spin\" />,\n }}\n style={\n {\n \"--normal-bg\": \"var(--popover)\",\n \"--normal-text\": \"var(--popover-foreground)\",\n \"--normal-border\": \"var(--border)\",\n \"--border-radius\": \"var(--radius)\",\n } as React.CSSProperties\n }\n {...props}\n />\n )\n}\n\nexport { Toaster }\n",
|
|
12
12
|
"target": "inertia/components/ui/sonner.tsx"
|
|
13
13
|
}
|
|
14
14
|
],
|
|
@@ -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/switch.json
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
{
|
|
10
10
|
"path": "registry/ui/switch.tsx",
|
|
11
11
|
"type": "registry:ui",
|
|
12
|
-
"content": "
|
|
12
|
+
"content": "import * as React from \"react\"\nimport { cn } from \"cn\"\nimport { Switch as SwitchPrimitive } from \"radix-ui\"\n\nfunction Switch({\n className,\n size = \"default\",\n ...props\n}: React.ComponentProps<typeof SwitchPrimitive.Root> & {\n size?: \"sm\" | \"default\"\n}) {\n return (\n <SwitchPrimitive.Root\n data-slot=\"switch\"\n data-size={size}\n className={cn(\n \"peer group/switch inline-flex shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-[1.15rem] data-[size=default]:w-8 data-[size=sm]:h-3.5 data-[size=sm]:w-6 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input dark:data-[state=unchecked]:bg-input/80\",\n className\n )}\n {...props}\n >\n <SwitchPrimitive.Thumb\n data-slot=\"switch-thumb\"\n className={cn(\n \"pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 ltr:data-[state=checked]:translate-x-[calc(100%-2px)] rtl:data-[state=checked]:-translate-x-[calc(100%-2px)] ltr:data-[state=unchecked]:translate-x-0 rtl:data-[state=unchecked]:-translate-x-0 dark:data-[state=checked]:bg-primary-foreground dark:data-[state=unchecked]:bg-foreground\"\n )}\n />\n </SwitchPrimitive.Root>\n )\n}\n\nexport { Switch }\n",
|
|
13
13
|
"target": "inertia/components/ui/switch.tsx"
|
|
14
14
|
}
|
|
15
15
|
],
|
package/build/table.json
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
{
|
|
9
9
|
"path": "registry/ui/table.tsx",
|
|
10
10
|
"type": "registry:ui",
|
|
11
|
-
"content": "
|
|
11
|
+
"content": "import * as React from \"react\"\nimport { cn } from \"cn\"\n\nfunction Table({ className, ...props }: React.ComponentProps<\"table\">) {\n return (\n <div\n data-slot=\"table-container\"\n className=\"relative w-full overflow-x-auto\"\n >\n <table\n data-slot=\"table\"\n className={cn(\"w-full caption-bottom text-sm\", className)}\n {...props}\n />\n </div>\n )\n}\n\nfunction TableHeader({ className, ...props }: React.ComponentProps<\"thead\">) {\n return (\n <thead\n data-slot=\"table-header\"\n className={cn(\"[&_tr]:border-b\", className)}\n {...props}\n />\n )\n}\n\nfunction TableBody({ className, ...props }: React.ComponentProps<\"tbody\">) {\n return (\n <tbody\n data-slot=\"table-body\"\n className={cn(\"[&_tr:last-child]:border-0\", className)}\n {...props}\n />\n )\n}\n\nfunction TableFooter({ className, ...props }: React.ComponentProps<\"tfoot\">) {\n return (\n <tfoot\n data-slot=\"table-footer\"\n className={cn(\n \"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction TableRow({ className, ...props }: React.ComponentProps<\"tr\">) {\n return (\n <tr\n data-slot=\"table-row\"\n className={cn(\n \"border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction TableHead({ className, ...props }: React.ComponentProps<\"th\">) {\n return (\n <th\n data-slot=\"table-head\"\n className={cn(\n \"h-10 px-2 text-start align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pe-0 [&>[role=checkbox]]:translate-y-[2px]\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction TableCell({ className, ...props }: React.ComponentProps<\"td\">) {\n return (\n <td\n data-slot=\"table-cell\"\n className={cn(\n \"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pe-0 [&>[role=checkbox]]:translate-y-[2px]\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction TableCaption({\n className,\n ...props\n}: React.ComponentProps<\"caption\">) {\n return (\n <caption\n data-slot=\"table-caption\"\n className={cn(\"mt-4 text-sm text-muted-foreground\", className)}\n {...props}\n />\n )\n}\n\nexport {\n Table,\n TableHeader,\n TableBody,\n TableFooter,\n TableHead,\n TableRow,\n TableCell,\n TableCaption,\n}\n",
|
|
12
12
|
"target": "inertia/components/ui/table.tsx"
|
|
13
13
|
}
|
|
14
14
|
],
|
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": "
|
|
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
|
],
|