@adula/ui 1.2.0 → 2.0.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.
@@ -20,7 +20,7 @@
20
20
  {
21
21
  "path": "registry/ui/resource-show.tsx",
22
22
  "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/kit'\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",
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",
24
24
  "target": "inertia/components/ui/resource-show.tsx"
25
25
  }
26
26
  ],
@@ -13,7 +13,7 @@
13
13
  {
14
14
  "path": "registry/ui/resource-value.tsx",
15
15
  "type": "registry:ui",
16
- "content": "import type { ReactNode } from 'react'\nimport { Paperclip } from 'lucide-react'\nimport type { CalendarPreference, ResourceField, SerializedRecord } from '@adula/kit'\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",
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",
17
17
  "target": "inertia/components/ui/resource-value.tsx"
18
18
  }
19
19
  ],
@@ -7,7 +7,7 @@
7
7
  {
8
8
  "path": "registry/ui/ui-preferences.tsx",
9
9
  "type": "registry:ui",
10
- "content": "import { usePage } from '@inertiajs/react'\nimport type { UiPreferences } from '@adula/kit'\n\n/** A consumer without shared preferences keeps the documented defaults. */\nexport function useUiPreferences(): UiPreferences {\n const page = usePage<{ uiPreferences?: UiPreferences }>()\n return (\n page.props.uiPreferences ?? {\n calendar: 'gregory',\n confirmDialogClose: true,\n pageTransitions: true,\n }\n )\n}\n",
10
+ "content": "import { usePage } from '@inertiajs/react'\nimport type { UiPreferences } from 'adula'\n\n/** A consumer without shared preferences keeps the documented defaults. */\nexport function useUiPreferences(): UiPreferences {\n const page = usePage<{ uiPreferences?: UiPreferences }>()\n return (\n page.props.uiPreferences ?? {\n calendar: 'gregory',\n confirmDialogClose: true,\n pageTransitions: true,\n }\n )\n}\n",
11
11
  "target": "inertia/components/ui/ui-preferences.tsx"
12
12
  }
13
13
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adula/ui",
3
- "version": "1.2.0",
3
+ "version": "2.0.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "Arabic RTL shadcn registry copied into AdonisJS applications",
@@ -24,12 +24,12 @@
24
24
  },
25
25
  "repository": {
26
26
  "type": "git",
27
- "url": "git+https://github.com/adulash/adula-kit.git",
27
+ "url": "git+https://github.com/adulash/adulajs.git",
28
28
  "directory": "packages/ui"
29
29
  },
30
- "homepage": "https://github.com/adulash/adula-kit/tree/main/packages/ui#readme",
30
+ "homepage": "https://github.com/adulash/adulajs/tree/main/packages/ui#readme",
31
31
  "bugs": {
32
- "url": "https://github.com/adulash/adula-kit/issues"
32
+ "url": "https://github.com/adulash/adulajs/issues"
33
33
  },
34
34
  "author": "adula contributors",
35
35
  "keywords": [