@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
|
@@ -10,7 +10,9 @@
|
|
|
10
10
|
"command",
|
|
11
11
|
"tabs",
|
|
12
12
|
"ui-preferences",
|
|
13
|
-
"resource-value"
|
|
13
|
+
"resource-value",
|
|
14
|
+
"messages",
|
|
15
|
+
"user-avatar"
|
|
14
16
|
],
|
|
15
17
|
"dependencies": [
|
|
16
18
|
"lucide-react@1.47.0",
|
|
@@ -20,7 +22,7 @@
|
|
|
20
22
|
{
|
|
21
23
|
"path": "registry/ui/record-collaboration.tsx",
|
|
22
24
|
"type": "registry:ui",
|
|
23
|
-
"content": "import { useCallback, useEffect, useState } from 'react'\nimport axios from 'axios'\nimport { AtSign, Bell, BellOff, MessageSquare, Pencil, Tag, Trash2, X } from 'lucide-react'\nimport type { MentionCandidate, RecordCollaborationState, ResourceDescription } from 'adula'\nimport { Badge } from '~/components/ui/badge'\nimport { Button } from '~/components/ui/button'\nimport { Input } from '~/components/ui/input'\nimport { Textarea } from '~/components/ui/textarea'\nimport { Popover, PopoverContent, PopoverTrigger } from '~/components/ui/popover'\nimport {\n Command,\n CommandEmpty,\n CommandInput,\n CommandItem,\n CommandList,\n} from '~/components/ui/command'\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from '~/components/ui/tabs'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\nimport { formatDatetime } from '~/components/ui/resource-value'\n\nconst json = { headers: { Accept: 'application/json' }, withXSRFToken: true }\n\nfunction failure(error: unknown, fallback: string) {\n return axios.isAxiosError(error) && error.response?.data?.error?.message\n ? String(error.response.data.error.message)\n : fallback\n}\n\nfunction shown(value: unknown) {\n if (value === null || value === undefined || value === '') return '—'\n if (typeof value === 'boolean') return value ? 'نعم' : 'لا'\n if (typeof value === 'object') return JSON.stringify(value)\n return String(value)\n}\n\n/**\n * Comments with mentions, following, tags and field history for one record.\n * The server re-authorizes the record on every request; this panel only renders\n * what the current user may read.\n */\nexport function RecordCollaboration({\n resource,\n id,\n}: {\n resource: ResourceDescription\n id: number | string\n}) {\n const { calendar } = useUiPreferences()\n const base = `/resources/${resource.name}/${id}`\n const [state, setState] = useState<RecordCollaborationState | null>(null)\n const [error, setError] = useState('')\n const [busy, setBusy] = useState(false)\n const [body, setBody] = useState('')\n const [mentions, setMentions] = useState<MentionCandidate[]>([])\n const [editing, setEditing] = useState<{ id: number; body: string } | null>(null)\n const [tagText, setTagText] = useState<string | null>(null)\n\n const load = useCallback(async () => {\n try {\n const response = await axios.get<RecordCollaborationState>(`${base}/collaboration`, json)\n setState(response.data)\n } catch (caught) {\n setError(failure(caught, 'تعذر تحميل التعليقات.'))\n }\n }, [base])\n useEffect(() => {\n void load()\n }, [load])\n\n const run = async (action: () => Promise<unknown>, fallback: string) => {\n setBusy(true)\n setError('')\n try {\n await action()\n await load()\n return true\n } catch (caught) {\n setError(failure(caught, fallback))\n return false\n } finally {\n setBusy(false)\n }\n }\n const fieldLabel = (key: string) =>\n resource.fields.find((field) => field.key === key)?.label.ar ?? key\n\n if (!state)\n return (\n <section aria-label=\"التعاون حول السجل\" className=\"rounded-xl border bg-white p-7\">\n <p className=\"text-xs text-muted-foreground\" role=\"status\">\n {error || 'جارٍ تحميل التعليقات…'}\n </p>\n </section>\n )\n\n return (\n <section aria-label=\"التعاون حول السجل\" className=\"rounded-xl border bg-white\">\n <div className=\"flex flex-wrap items-center gap-3 border-b px-7 py-4\">\n <MessageSquare size={16} className=\"text-muted-foreground\" />\n <h2 className=\"text-sm font-semibold\">التعاون حول السجل</h2>\n <span className=\"text-xs text-muted-foreground\">{state.followers} متابع</span>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n className=\"ms-auto\"\n disabled={busy}\n onClick={() =>\n run(\n () => axios.put(`${base}/follow`, { following: !state.following }, json),\n 'تعذر تحديث المتابعة.'\n )\n }\n >\n {state.following ? <BellOff size={14} /> : <Bell size={14} />}\n {state.following ? 'إلغاء المتابعة' : 'متابعة السجل'}\n </Button>\n </div>\n <div className=\"flex flex-wrap items-center gap-2 border-b px-7 py-3\">\n <Tag size={14} className=\"text-muted-foreground\" />\n {tagText === null ? (\n <>\n {state.tags.length ? (\n state.tags.map((tag) => (\n <Badge key={tag} variant=\"secondary\">\n {tag}\n </Badge>\n ))\n ) : (\n <span className=\"text-xs text-muted-foreground\">بلا وسوم</span>\n )}\n {state.canTag && (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n onClick={() => setTagText(state.tags.join('، '))}\n >\n تعديل الوسوم\n </Button>\n )}\n </>\n ) : (\n <form\n className=\"flex flex-1 flex-wrap items-center gap-2\"\n onSubmit={async (event) => {\n event.preventDefault()\n const tags = tagText\n .split(/[,،]/)\n .map((tag) => tag.trim())\n .filter(Boolean)\n if (await run(() => axios.put(`${base}/tags`, { tags }, json), 'تعذر حفظ الوسوم.'))\n setTagText(null)\n }}\n >\n <Input\n aria-label=\"الوسوم مفصولة بفواصل\"\n className=\"max-w-sm flex-1\"\n value={tagText}\n onChange={(event) => setTagText(event.target.value)}\n />\n <Button type=\"submit\" size=\"sm\" disabled={busy}>\n حفظ الوسوم\n </Button>\n <Button type=\"button\" size=\"sm\" variant=\"ghost\" onClick={() => setTagText(null)}>\n إلغاء\n </Button>\n </form>\n )}\n </div>\n {error && (\n <p role=\"alert\" className=\"border-b bg-red-50 px-7 py-3 text-xs text-red-800\">\n {error}\n </p>\n )}\n <Tabs defaultValue=\"comments\" className=\"px-7 py-5\">\n <TabsList>\n <TabsTrigger value=\"comments\">التعليقات ({state.comments.length})</TabsTrigger>\n <TabsTrigger value=\"changes\">سجل التغييرات ({state.changes.length})</TabsTrigger>\n </TabsList>\n <TabsContent value=\"comments\" className=\"space-y-4 pt-4\">\n {state.comments.length === 0 && (\n <p className=\"text-xs text-muted-foreground\">لا توجد تعليقات بعد.</p>\n )}\n <ol className=\"space-y-3\">\n {state.comments.map((comment) => (\n <li key={comment.id} className=\"rounded-lg border px-4 py-3\">\n <div className=\"mb-1 flex flex-wrap items-center gap-2 text-xs text-muted-foreground\">\n <span className=\"font-medium text-foreground\">\n {comment.authorName ?? `مستخدم #${comment.authorId}`}\n </span>\n <time dateTime={comment.createdAt} className=\"tabular-nums\">\n {formatDatetime(comment.createdAt, calendar)}\n </time>\n {comment.editedAt && <span>(معدّل)</span>}\n {comment.own && editing?.id !== comment.id && (\n <span className=\"ms-auto flex gap-1\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n aria-label=\"تعديل التعليق\"\n onClick={() => setEditing({ id: comment.id, body: comment.body })}\n >\n <Pencil size={13} />\n </Button>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n aria-label=\"حذف التعليق\"\n disabled={busy}\n onClick={() =>\n run(\n () => axios.delete(`${base}/comments/${comment.id}`, json),\n 'تعذر حذف التعليق.'\n )\n }\n >\n <Trash2 size={13} />\n </Button>\n </span>\n )}\n </div>\n {editing?.id === comment.id ? (\n <form\n className=\"space-y-2\"\n onSubmit={async (event) => {\n event.preventDefault()\n if (\n await run(\n () =>\n axios.patch(\n `${base}/comments/${comment.id}`,\n { body: editing.body },\n json\n ),\n 'تعذر تعديل التعليق.'\n )\n )\n setEditing(null)\n }}\n >\n <Textarea\n aria-label=\"نص التعليق المعدّل\"\n value={editing.body}\n onChange={(event) => setEditing({ ...editing, body: event.target.value })}\n />\n <div className=\"flex gap-2\">\n <Button type=\"submit\" size=\"sm\" disabled={busy}>\n حفظ\n </Button>\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"ghost\"\n onClick={() => setEditing(null)}\n >\n إلغاء\n </Button>\n </div>\n </form>\n ) : (\n <p className=\"text-sm whitespace-pre-wrap break-words\">{comment.body}</p>\n )}\n {comment.mentions.length > 0 && (\n <p className=\"mt-2 text-xs text-muted-foreground\">\n إشارة إلى: {comment.mentions.map((user) => user.name).join('، ')}\n </p>\n )}\n </li>\n ))}\n </ol>\n {state.canComment && (\n <form\n className=\"space-y-2\"\n onSubmit={async (event) => {\n event.preventDefault()\n if (\n await run(\n () =>\n axios.post(\n `${base}/comments`,\n { body, mentions: mentions.map((user) => user.id) },\n json\n ),\n 'تعذر إضافة التعليق.'\n )\n ) {\n setBody('')\n setMentions([])\n }\n }}\n >\n <Textarea\n aria-label=\"تعليق جديد\"\n placeholder=\"اكتب تعليقاً…\"\n value={body}\n maxLength={5000}\n onChange={(event) => setBody(event.target.value)}\n />\n <div className=\"flex flex-wrap items-center gap-2\">\n <MentionPicker\n base={base}\n onPick={(user) =>\n setMentions((current) =>\n current.some((entry) => entry.id === user.id) ? current : [...current, user]\n )\n }\n />\n {mentions.map((user) => (\n <Badge key={user.id} variant=\"outline\" className=\"gap-1\">\n @{user.name}\n <button\n type=\"button\"\n aria-label={`إزالة الإشارة إلى ${user.name}`}\n onClick={() =>\n setMentions((current) => current.filter((entry) => entry.id !== user.id))\n }\n >\n <X size={12} />\n </button>\n </Badge>\n ))}\n <Button type=\"submit\" size=\"sm\" className=\"ms-auto\" disabled={busy || !body.trim()}>\n إضافة تعليق\n </Button>\n </div>\n </form>\n )}\n </TabsContent>\n <TabsContent value=\"changes\" className=\"pt-4\">\n {state.changes.length === 0 ? (\n <p className=\"text-xs text-muted-foreground\">لا توجد تغييرات مسجلة على الحقول.</p>\n ) : (\n <div className=\"overflow-x-auto\">\n <table className=\"w-full min-w-[520px] text-sm\">\n <thead className=\"bg-muted text-xs text-muted-foreground\">\n <tr>\n <th scope=\"col\" className=\"px-4 py-2 text-start font-medium\">\n الحقل\n </th>\n <th scope=\"col\" className=\"px-4 py-2 text-start font-medium\">\n قبل\n </th>\n <th scope=\"col\" className=\"px-4 py-2 text-start font-medium\">\n بعد\n </th>\n <th scope=\"col\" className=\"px-4 py-2 text-start font-medium\">\n بواسطة\n </th>\n </tr>\n </thead>\n <tbody>\n {state.changes.map((change) => (\n <tr key={change.id} className=\"border-b last:border-0\">\n <td className=\"px-4 py-2 font-medium\">{fieldLabel(change.field)}</td>\n <td className=\"px-4 py-2 text-red-800 line-through\">\n {shown(change.before)}\n </td>\n <td className=\"px-4 py-2 text-emerald-800\">{shown(change.after)}</td>\n <td className=\"px-4 py-2 text-xs text-muted-foreground\">\n {change.actorName ?? '—'} ·{' '}\n <time dateTime={change.createdAt}>\n {formatDatetime(change.createdAt, calendar)}\n </time>\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n )}\n </TabsContent>\n </Tabs>\n </section>\n )\n}\n\nfunction MentionPicker({\n base,\n onPick,\n}: {\n base: string\n onPick: (user: MentionCandidate) => void\n}) {\n const [open, setOpen] = useState(false)\n const [search, setSearch] = useState('')\n const [users, setUsers] = useState<MentionCandidate[]>([])\n useEffect(() => {\n if (!open) return\n const timer = setTimeout(async () => {\n try {\n const response = await axios.get<{ data: MentionCandidate[] }>(`${base}/mentions`, {\n ...json,\n params: { search },\n })\n setUsers(response.data.data)\n } catch {\n setUsers([])\n }\n }, 200)\n return () => clearTimeout(timer)\n }, [open, search, base])\n return (\n <Popover open={open} onOpenChange={setOpen}>\n <PopoverTrigger asChild>\n <Button type=\"button\" variant=\"outline\" size=\"sm\">\n <AtSign size={14} />\n إشارة إلى زميل\n </Button>\n </PopoverTrigger>\n <PopoverContent className=\"w-72 p-0\" align=\"start\">\n <Command shouldFilter={false}>\n <CommandInput placeholder=\"ابحث بالاسم…\" value={search} onValueChange={setSearch} />\n <CommandList>\n <CommandEmpty>لا يوجد زملاء يملكون صلاحية عرض السجل.</CommandEmpty>\n {users.map((user) => (\n <CommandItem\n key={user.id}\n value={String(user.id)}\n onSelect={() => {\n onPick(user)\n setOpen(false)\n }}\n >\n {user.name}\n </CommandItem>\n ))}\n </CommandList>\n </Command>\n </PopoverContent>\n </Popover>\n )\n}\n",
|
|
25
|
+
"content": "import { useCallback, useEffect, useState } from 'react'\nimport axios from 'axios'\nimport { AtSign, Bell, BellOff, MessageSquare, Pencil, Tag, Trash2, X } from 'lucide-react'\nimport type { MentionCandidate, RecordCollaborationState, ResourceDescription } from 'adula'\nimport { Badge } from '~/components/ui/badge'\nimport { UserAvatar } from '~/components/ui/user-avatar'\nimport { Button } from '~/components/ui/button'\nimport { Input } from '~/components/ui/input'\nimport { Textarea } from '~/components/ui/textarea'\nimport { Popover, PopoverContent, PopoverTrigger } from '~/components/ui/popover'\nimport {\n Command,\n CommandEmpty,\n CommandInput,\n CommandItem,\n CommandList,\n} from '~/components/ui/command'\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from '~/components/ui/tabs'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\nimport { useMessages } from '~/components/ui/messages'\nimport { formatDatetime } from '~/components/ui/resource-value'\n\nconst json = { headers: { Accept: 'application/json' }, withXSRFToken: true }\n\nfunction failure(error: unknown, fallback: string) {\n return axios.isAxiosError(error) && error.response?.data?.error?.message\n ? String(error.response.data.error.message)\n : fallback\n}\n\nfunction shown(value: unknown) {\n if (value === null || value === undefined || value === '') return '—'\n if (typeof value === 'boolean') return value ? 'نعم' : 'لا'\n if (typeof value === 'object') return JSON.stringify(value)\n return String(value)\n}\n\n/**\n * Comments with mentions, following, tags and field history for one record.\n * The server re-authorizes the record on every request; this panel only renders\n * what the current user may read.\n */\nexport function RecordCollaboration({\n resource,\n id,\n}: {\n resource: ResourceDescription\n id: number | string\n}) {\n const { calendar } = useUiPreferences()\n const base = `/resources/${resource.name}/${id}`\n const [state, setState] = useState<RecordCollaborationState | null>(null)\n const [error, setError] = useState('')\n const [busy, setBusy] = useState(false)\n const [body, setBody] = useState('')\n const [mentions, setMentions] = useState<MentionCandidate[]>([])\n const [editing, setEditing] = useState<{ id: number; body: string } | null>(null)\n const [tagText, setTagText] = useState<string | null>(null)\n\n const load = useCallback(async () => {\n try {\n const response = await axios.get<RecordCollaborationState>(`${base}/collaboration`, json)\n setState(response.data)\n } catch (caught) {\n setError(failure(caught, 'تعذر تحميل التعليقات.'))\n }\n }, [base])\n useEffect(() => {\n void load()\n }, [load])\n\n const run = async (action: () => Promise<unknown>, fallback: string) => {\n setBusy(true)\n setError('')\n try {\n await action()\n await load()\n return true\n } catch (caught) {\n setError(failure(caught, fallback))\n return false\n } finally {\n setBusy(false)\n }\n }\n const { label } = useMessages()\n const fieldLabel = (key: string) => {\n const field = resource.fields.find((entry) => entry.key === key)\n return field ? label(field.label) : key\n }\n\n if (!state)\n return (\n <section aria-label=\"التعاون حول السجل\" className=\"rounded-xl border bg-card p-7\">\n <p className=\"text-xs text-muted-foreground\" role=\"status\">\n {error || 'جارٍ تحميل التعليقات…'}\n </p>\n </section>\n )\n\n return (\n <section aria-label=\"التعاون حول السجل\" className=\"rounded-xl border bg-card\">\n <div className=\"flex flex-wrap items-center gap-3 border-b px-7 py-4\">\n <MessageSquare size={16} className=\"text-muted-foreground\" />\n <h2 className=\"text-sm font-semibold\">التعاون حول السجل</h2>\n <span className=\"text-xs text-muted-foreground\">{state.followers} متابع</span>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n className=\"ms-auto\"\n disabled={busy}\n onClick={() =>\n run(\n () => axios.put(`${base}/follow`, { following: !state.following }, json),\n 'تعذر تحديث المتابعة.'\n )\n }\n >\n {state.following ? <BellOff size={14} /> : <Bell size={14} />}\n {state.following ? 'إلغاء المتابعة' : 'متابعة السجل'}\n </Button>\n </div>\n <div className=\"flex flex-wrap items-center gap-2 border-b px-7 py-3\">\n <Tag size={14} className=\"text-muted-foreground\" />\n {tagText === null ? (\n <>\n {state.tags.length ? (\n state.tags.map((tag) => (\n <Badge key={tag} variant=\"secondary\">\n {tag}\n </Badge>\n ))\n ) : (\n <span className=\"text-xs text-muted-foreground\">بلا وسوم</span>\n )}\n {state.canTag && (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n onClick={() => setTagText(state.tags.join('، '))}\n >\n تعديل الوسوم\n </Button>\n )}\n </>\n ) : (\n <form\n className=\"flex flex-1 flex-wrap items-center gap-2\"\n onSubmit={async (event) => {\n event.preventDefault()\n const tags = tagText\n .split(/[,،]/)\n .map((tag) => tag.trim())\n .filter(Boolean)\n if (await run(() => axios.put(`${base}/tags`, { tags }, json), 'تعذر حفظ الوسوم.'))\n setTagText(null)\n }}\n >\n <Input\n aria-label=\"الوسوم مفصولة بفواصل\"\n className=\"max-w-sm flex-1\"\n value={tagText}\n onChange={(event) => setTagText(event.target.value)}\n />\n <Button type=\"submit\" size=\"sm\" disabled={busy}>\n حفظ الوسوم\n </Button>\n <Button type=\"button\" size=\"sm\" variant=\"ghost\" onClick={() => setTagText(null)}>\n إلغاء\n </Button>\n </form>\n )}\n </div>\n {error && (\n <p role=\"alert\" className=\"border-b bg-destructive/10 px-7 py-3 text-xs text-destructive\">\n {error}\n </p>\n )}\n <Tabs defaultValue=\"comments\" className=\"px-7 py-5\">\n <TabsList>\n <TabsTrigger value=\"comments\">التعليقات ({state.comments.length})</TabsTrigger>\n <TabsTrigger value=\"changes\">سجل التغييرات ({state.changes.length})</TabsTrigger>\n </TabsList>\n <TabsContent value=\"comments\" className=\"space-y-4 pt-4\">\n {state.comments.length === 0 && (\n <p className=\"text-xs text-muted-foreground\">لا توجد تعليقات بعد.</p>\n )}\n <ol className=\"space-y-3\">\n {state.comments.map((comment) => (\n <li key={comment.id} className=\"rounded-lg border px-4 py-3\">\n <div className=\"mb-1 flex flex-wrap items-center gap-2 text-xs text-muted-foreground\">\n <UserAvatar\n user={{\n id: comment.authorId,\n name: comment.authorName,\n avatarUrl: comment.authorAvatarUrl,\n }}\n size=\"xs\"\n />\n <span className=\"font-medium text-foreground\">\n {comment.authorName ?? `مستخدم #${comment.authorId}`}\n </span>\n <time dateTime={comment.createdAt} className=\"tabular-nums\">\n {formatDatetime(comment.createdAt, calendar)}\n </time>\n {comment.editedAt && <span>(معدّل)</span>}\n {comment.own && editing?.id !== comment.id && (\n <span className=\"ms-auto flex gap-1\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n aria-label=\"تعديل التعليق\"\n onClick={() => setEditing({ id: comment.id, body: comment.body })}\n >\n <Pencil size={13} />\n </Button>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n aria-label=\"حذف التعليق\"\n disabled={busy}\n onClick={() =>\n run(\n () => axios.delete(`${base}/comments/${comment.id}`, json),\n 'تعذر حذف التعليق.'\n )\n }\n >\n <Trash2 size={13} />\n </Button>\n </span>\n )}\n </div>\n {editing?.id === comment.id ? (\n <form\n className=\"space-y-2\"\n onSubmit={async (event) => {\n event.preventDefault()\n if (\n await run(\n () =>\n axios.patch(\n `${base}/comments/${comment.id}`,\n { body: editing.body },\n json\n ),\n 'تعذر تعديل التعليق.'\n )\n )\n setEditing(null)\n }}\n >\n <Textarea\n aria-label=\"نص التعليق المعدّل\"\n value={editing.body}\n onChange={(event) => setEditing({ ...editing, body: event.target.value })}\n />\n <div className=\"flex gap-2\">\n <Button type=\"submit\" size=\"sm\" disabled={busy}>\n حفظ\n </Button>\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"ghost\"\n onClick={() => setEditing(null)}\n >\n إلغاء\n </Button>\n </div>\n </form>\n ) : (\n <p className=\"text-sm whitespace-pre-wrap break-words\">{comment.body}</p>\n )}\n {comment.mentions.length > 0 && (\n <p className=\"mt-2 text-xs text-muted-foreground\">\n إشارة إلى: {comment.mentions.map((user) => user.name).join('، ')}\n </p>\n )}\n </li>\n ))}\n </ol>\n {state.canComment && (\n <form\n className=\"space-y-2\"\n onSubmit={async (event) => {\n event.preventDefault()\n if (\n await run(\n () =>\n axios.post(\n `${base}/comments`,\n { body, mentions: mentions.map((user) => user.id) },\n json\n ),\n 'تعذر إضافة التعليق.'\n )\n ) {\n setBody('')\n setMentions([])\n }\n }}\n >\n <Textarea\n aria-label=\"تعليق جديد\"\n placeholder=\"اكتب تعليقاً…\"\n value={body}\n maxLength={5000}\n onChange={(event) => setBody(event.target.value)}\n />\n <div className=\"flex flex-wrap items-center gap-2\">\n <MentionPicker\n base={base}\n onPick={(user) =>\n setMentions((current) =>\n current.some((entry) => entry.id === user.id) ? current : [...current, user]\n )\n }\n />\n {mentions.map((user) => (\n <Badge key={user.id} variant=\"outline\" className=\"gap-1\">\n <UserAvatar user={user} size=\"xs\" />@{user.name}\n <button\n type=\"button\"\n aria-label={`إزالة الإشارة إلى ${user.name}`}\n onClick={() =>\n setMentions((current) => current.filter((entry) => entry.id !== user.id))\n }\n >\n <X size={12} />\n </button>\n </Badge>\n ))}\n <Button type=\"submit\" size=\"sm\" className=\"ms-auto\" disabled={busy || !body.trim()}>\n إضافة تعليق\n </Button>\n </div>\n </form>\n )}\n </TabsContent>\n <TabsContent value=\"changes\" className=\"pt-4\">\n {state.changes.length === 0 ? (\n <p className=\"text-xs text-muted-foreground\">لا توجد تغييرات مسجلة على الحقول.</p>\n ) : (\n <div className=\"overflow-x-auto\">\n <table className=\"w-full min-w-[520px] text-sm\">\n <thead className=\"bg-muted text-xs text-muted-foreground\">\n <tr>\n <th scope=\"col\" className=\"px-4 py-2 text-start font-medium\">\n الحقل\n </th>\n <th scope=\"col\" className=\"px-4 py-2 text-start font-medium\">\n قبل\n </th>\n <th scope=\"col\" className=\"px-4 py-2 text-start font-medium\">\n بعد\n </th>\n <th scope=\"col\" className=\"px-4 py-2 text-start font-medium\">\n بواسطة\n </th>\n </tr>\n </thead>\n <tbody>\n {state.changes.map((change) => (\n <tr key={change.id} className=\"border-b last:border-0\">\n <td className=\"px-4 py-2 font-medium\">{fieldLabel(change.field)}</td>\n <td className=\"px-4 py-2 text-destructive line-through\">\n {shown(change.before)}\n </td>\n <td className=\"px-4 py-2 text-success\">{shown(change.after)}</td>\n <td className=\"px-4 py-2 text-xs text-muted-foreground\">\n <span className=\"inline-flex items-center gap-1.5\">\n {change.actorId && change.actorName ? (\n <UserAvatar\n user={{\n id: change.actorId,\n name: change.actorName,\n avatarUrl: change.actorAvatarUrl,\n }}\n size=\"xs\"\n />\n ) : null}\n {change.actorName ?? '—'}\n </span>{' '}\n ·{' '}\n <time dateTime={change.createdAt}>\n {formatDatetime(change.createdAt, calendar)}\n </time>\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n )}\n </TabsContent>\n </Tabs>\n </section>\n )\n}\n\nfunction MentionPicker({\n base,\n onPick,\n}: {\n base: string\n onPick: (user: MentionCandidate) => void\n}) {\n const [open, setOpen] = useState(false)\n const [search, setSearch] = useState('')\n const [users, setUsers] = useState<MentionCandidate[]>([])\n useEffect(() => {\n if (!open) return\n const timer = setTimeout(async () => {\n try {\n const response = await axios.get<{ data: MentionCandidate[] }>(`${base}/mentions`, {\n ...json,\n params: { search },\n })\n setUsers(response.data.data)\n } catch {\n setUsers([])\n }\n }, 200)\n return () => clearTimeout(timer)\n }, [open, search, base])\n return (\n <Popover open={open} onOpenChange={setOpen}>\n <PopoverTrigger asChild>\n <Button type=\"button\" variant=\"outline\" size=\"sm\">\n <AtSign size={14} />\n إشارة إلى زميل\n </Button>\n </PopoverTrigger>\n <PopoverContent className=\"w-72 p-0\" align=\"start\">\n <Command shouldFilter={false}>\n <CommandInput placeholder=\"ابحث بالاسم…\" value={search} onValueChange={setSearch} />\n <CommandList>\n <CommandEmpty>لا يوجد زملاء يملكون صلاحية عرض السجل.</CommandEmpty>\n {users.map((user) => (\n <CommandItem\n key={user.id}\n value={String(user.id)}\n onSelect={() => {\n onPick(user)\n setOpen(false)\n }}\n >\n <UserAvatar user={user} size=\"xs\" />\n {user.name}\n </CommandItem>\n ))}\n </CommandList>\n </Command>\n </PopoverContent>\n </Popover>\n )\n}\n",
|
|
24
26
|
"target": "inertia/components/ui/record-collaboration.tsx"
|
|
25
27
|
}
|
|
26
28
|
],
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "record-print",
|
|
3
|
+
"type": "registry:ui",
|
|
4
|
+
"registryDependencies": [
|
|
5
|
+
"button",
|
|
6
|
+
"label",
|
|
7
|
+
"radio-group",
|
|
8
|
+
"dialog",
|
|
9
|
+
"messages"
|
|
10
|
+
],
|
|
11
|
+
"dependencies": [
|
|
12
|
+
"lucide-react@1.47.0",
|
|
13
|
+
"axios@1.19.0"
|
|
14
|
+
],
|
|
15
|
+
"files": [
|
|
16
|
+
{
|
|
17
|
+
"path": "registry/ui/record-print.tsx",
|
|
18
|
+
"type": "registry:ui",
|
|
19
|
+
"content": "import { useState } from 'react'\nimport axios from 'axios'\nimport { Printer } from 'lucide-react'\nimport type { PrintTemplateOption } from 'adula'\nimport { Button } from '~/components/ui/button'\nimport { Label } from '~/components/ui/label'\nimport { RadioGroup, RadioGroupItem } from '~/components/ui/radio-group'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from '~/components/ui/dialog'\nimport { useMessages } from '~/components/ui/messages'\n\ntype Options = { templates: PrintTemplateOption[]; pdf: boolean }\n\n/**\n * «طباعة» on the record page (ADR 048): a Dialog to pick the generic layout, a code\n * template or an administrator template, and HTML or PDF when PDF is configured. The\n * print page authorizes the record and every field again on the server.\n */\nexport function RecordPrint({ resource, id }: { resource: string; id: number | string }) {\n const { t, label } = useMessages()\n const [open, setOpen] = useState(false)\n const [options, setOptions] = useState<Options | null>(null)\n const [failed, setFailed] = useState(false)\n const [template, setTemplate] = useState('default')\n const [format, setFormat] = useState<'html' | 'pdf'>('html')\n const load = () => {\n setFailed(false)\n axios\n .get<{ data: Options }>(`/resources/${resource}/print-templates`, {\n headers: { Accept: 'application/json' },\n })\n .then((response) => setOptions(response.data.data))\n .catch(() => setFailed(true))\n }\n const query = new URLSearchParams()\n if (template !== 'default') query.set('template', template)\n if (format === 'pdf') query.set('format', 'pdf')\n const href = `/resources/${resource}/${id}/print${query.size ? `?${query}` : ''}`\n return (\n <>\n <Button\n variant=\"outline\"\n onClick={() => {\n setOpen(true)\n if (!options) load()\n }}\n >\n <Printer size={15} />\n {t('طباعة')}\n </Button>\n <Dialog open={open} onOpenChange={setOpen}>\n <DialogContent dir=\"rtl\" className=\"sm:max-w-md\">\n <DialogHeader>\n <DialogTitle>{t('طباعة السجل')}</DialogTitle>\n <DialogDescription>{t('اختر قالب الطباعة وصيغة المستند.')}</DialogDescription>\n </DialogHeader>\n {failed ? (\n <div className=\"space-y-3 text-sm\">\n <p className=\"text-destructive\">{t('تعذر تحميل قوالب الطباعة.')}</p>\n <Button variant=\"outline\" size=\"sm\" onClick={load}>\n {t('إعادة المحاولة')}\n </Button>\n </div>\n ) : !options ? (\n <p className=\"text-sm text-muted-foreground\">{t('جارٍ تحميل القوالب…')}</p>\n ) : (\n <div className=\"space-y-5\">\n <fieldset className=\"space-y-3\">\n <legend className=\"mb-2 text-sm font-medium\">{t('قالب الطباعة')}</legend>\n <RadioGroup value={template} onValueChange={setTemplate} className=\"gap-3\">\n {options.templates.map((option) => (\n <div key={option.key} className=\"flex items-center gap-2\">\n <RadioGroupItem id={`print-template-${option.key}`} value={option.key} />\n <Label htmlFor={`print-template-${option.key}`}>{label(option.label)}</Label>\n </div>\n ))}\n </RadioGroup>\n </fieldset>\n <fieldset className=\"space-y-3\">\n <legend className=\"mb-2 text-sm font-medium\">{t('صيغة المستند')}</legend>\n <RadioGroup\n value={format}\n onValueChange={(value) => setFormat(value as 'html' | 'pdf')}\n className=\"flex flex-wrap gap-6\"\n >\n <div className=\"flex items-center gap-2\">\n <RadioGroupItem id=\"print-format-html\" value=\"html\" />\n <Label htmlFor=\"print-format-html\">{t('صفحة للطباعة')}</Label>\n </div>\n <div className=\"flex items-center gap-2\">\n <RadioGroupItem id=\"print-format-pdf\" value=\"pdf\" disabled={!options.pdf} />\n <Label htmlFor=\"print-format-pdf\">PDF</Label>\n </div>\n </RadioGroup>\n {!options.pdf && (\n <p className=\"text-xs text-muted-foreground\">\n {t('تحويل PDF غير مفعّل؛ استخدم الطباعة من المتصفح.')}\n </p>\n )}\n </fieldset>\n </div>\n )}\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" onClick={() => setOpen(false)}>\n {t('إلغاء')}\n </Button>\n {options ? (\n <Button asChild>\n <a href={href} target=\"_blank\" rel=\"noopener\" onClick={() => setOpen(false)}>\n <Printer size={15} />\n {t('فتح للطباعة')}\n </a>\n </Button>\n ) : (\n // A link cannot be disabled; until the templates load the action is a button.\n <Button type=\"button\" disabled>\n <Printer size={15} />\n {t('فتح للطباعة')}\n </Button>\n )}\n </DialogFooter>\n </DialogContent>\n </Dialog>\n </>\n )\n}\n",
|
|
20
|
+
"target": "inertia/components/ui/record-print.tsx"
|
|
21
|
+
}
|
|
22
|
+
],
|
|
23
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
24
|
+
}
|
|
@@ -8,7 +8,8 @@
|
|
|
8
8
|
"textarea",
|
|
9
9
|
"dialog",
|
|
10
10
|
"ui-preferences",
|
|
11
|
-
"resource-value"
|
|
11
|
+
"resource-value",
|
|
12
|
+
"user-avatar"
|
|
12
13
|
],
|
|
13
14
|
"dependencies": [
|
|
14
15
|
"lucide-react@1.47.0",
|
|
@@ -18,7 +19,7 @@
|
|
|
18
19
|
{
|
|
19
20
|
"path": "registry/ui/record-workflows.tsx",
|
|
20
21
|
"type": "registry:ui",
|
|
21
|
-
"content": "import { useCallback, useEffect, useState } from 'react'\nimport axios from 'axios'\nimport { CheckCircle2, GitBranch, XCircle } from 'lucide-react'\nimport type { WorkflowRun } from 'adula'\nimport { Badge } from '~/components/ui/badge'\nimport { Button } from '~/components/ui/button'\nimport { Label } from '~/components/ui/label'\nimport { Textarea } from '~/components/ui/textarea'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from '~/components/ui/dialog'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\nimport { formatDatetime } from '~/components/ui/resource-value'\n\nconst json = { headers: { Accept: 'application/json' }, withXSRFToken: true }\nexport const runStatusLabel: Record<string, string> = {\n pending_definition: 'بانتظار التعريف',\n running: 'قيد التنفيذ',\n waiting: 'بانتظار موافقة',\n completed: 'مكتمل',\n failed: 'فشل',\n cancelled: 'أُلغي',\n}\nconst outcomeLabel: Record<string, string> = {\n approved: 'معتمد',\n rejected: 'مرفوض',\n completed: 'مكتمل',\n no_workflow: 'بلا تدفق',\n}\nconst eventLabel: Record<string, string> = {\n started: 'بدأ التدفق',\n evaluate: 'تقييم شرط',\n approval_requested: 'طُلبت الموافقة',\n approved: 'موافقة',\n rejected: 'رفض',\n decided: 'قرار',\n done: 'نُفذت الخطوة',\n delay_started: 'بدأ الانتظار',\n retry_scheduled: 'جدولة إعادة المحاولة',\n failed: 'فشل',\n retried: 'إعادة تشغيل',\n migrated: 'ترحيل إلى إصدار أحدث',\n completed: 'اكتمل',\n cancelled: 'أُلغي',\n}\n\ntype DecisionChoice = NonNullable<\n NonNullable<WorkflowRun['myApproval']>['decision']\n>['outcomes'][number]\n\n// A plain approval step offers exactly these two decisions.\nconst approvalChoices: DecisionChoice[] = [\n { key: 'approve', label: 'موافقة', comment: 'optional' },\n { key: 'reject', label: 'رفض', comment: 'optional' },\n]\nconst dialogTitle: Record<string, string> = { approve: 'تأكيد الموافقة', reject: 'تأكيد الرفض' }\n\n/**\n * The approver's decision in a confirmation dialog: approve or reject, or at a decision\n * step one of its named outcomes (#42). A decision never edits the submitted document.\n */\nexport function WorkflowDecision({\n run,\n onDecided,\n}: {\n run: WorkflowRun\n onDecided: (run: WorkflowRun) => void\n}) {\n const [choice, setChoice] = useState<DecisionChoice | null>(null)\n const [comment, setComment] = useState('')\n const [error, setError] = useState('')\n const [busy, setBusy] = useState(false)\n if (!run.myApproval) return null\n const form = run.myApproval.decision\n const choices = form?.outcomes ?? approvalChoices\n const open = (next: DecisionChoice) => {\n setChoice(next)\n setComment('')\n setError('')\n }\n const submit = async () => {\n if (!choice) return\n if (choice.comment === 'required' && !comment.trim()) {\n setError('اكتب ملاحظة القرار.')\n return\n }\n setBusy(true)\n setError('')\n try {\n const response = await axios.post<{ data: WorkflowRun }>(\n `/workflows/${run.id}/decide`,\n { decision: choice.key, comment },\n json\n )\n setChoice(null)\n setComment('')\n onDecided(response.data.data)\n } catch (caught) {\n setError(\n axios.isAxiosError(caught) && caught.response?.data?.error?.message\n ? String(caught.response.data.error.message)\n : 'تعذر تسجيل القرار.'\n )\n } finally {\n setBusy(false)\n }\n }\n const rejecting = choice?.key === 'reject'\n return (\n <>\n <div className=\"flex flex-wrap gap-2\">\n {choices.map((item, index) => (\n <Button\n key={item.key}\n size=\"sm\"\n variant={index === 0 ? 'default' : 'outline'}\n className={item.key === 'reject' ? 'text-destructive' : undefined}\n onClick={() => open(item)}\n >\n {item.key === 'approve' && <CheckCircle2 size={15} />}\n {item.key === 'reject' && <XCircle size={15} />}\n {item.label}\n </Button>\n ))}\n </div>\n <Dialog open={choice !== null} onOpenChange={(next) => !next && !busy && setChoice(null)}>\n <DialogContent dir=\"rtl\">\n <DialogHeader>\n <DialogTitle>\n {choice && (form ? `تأكيد القرار: ${choice.label}` : dialogTitle[choice.key])}\n </DialogTitle>\n <DialogDescription>\n {run.myApproval.title} — {run.resourceLabel}:{' '}\n {run.recordTitle ?? `#${run.recordId}`}\n </DialogDescription>\n </DialogHeader>\n <div className=\"space-y-2\">\n <Label htmlFor={`decision-comment-${run.id}`} className=\"flex items-center gap-1\">\n {choice?.comment === 'required' ? (\n <>\n ملاحظة\n <span className=\"text-destructive\" aria-hidden=\"true\">\n *\n </span>\n </>\n ) : (\n 'ملاحظة (اختيارية)'\n )}\n </Label>\n <Textarea\n id={`decision-comment-${run.id}`}\n value={comment}\n maxLength={1000}\n required={choice?.comment === 'required'}\n onChange={(event) => setComment(event.target.value)}\n />\n </div>\n {error && (\n <p role=\"alert\" className=\"rounded-lg bg-red-50 px-3 py-2 text-xs text-red-800\">\n {error}\n </p>\n )}\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" disabled={busy} onClick={() => setChoice(null)}>\n تراجع\n </Button>\n <Button\n type=\"button\"\n variant={rejecting ? 'destructive' : 'default'}\n disabled={busy}\n onClick={() => void submit()}\n >\n {choice?.label}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n </>\n )\n}\n\n/** Workflow runs of one submittable record with their step history. */\nexport function RecordWorkflows({ resource, id }: { resource: string; id: number | string }) {\n const { calendar } = useUiPreferences()\n const [runs, setRuns] = useState<WorkflowRun[] | null>(null)\n const load = useCallback(async () => {\n try {\n const response = await axios.get<{ data: WorkflowRun[] }>(\n `/resources/${resource}/${id}/workflows`,\n json\n )\n setRuns(response.data.data)\n } catch {\n setRuns([])\n }\n }, [resource, id])\n useEffect(() => {\n void load()\n }, [load])\n if (runs !== null && runs.length === 0) return null\n return (\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 <GitBranch size={16} className=\"text-muted-foreground\" />\n <h2 className=\"text-sm font-semibold\">سير العمل</h2>\n </div>\n {runs === null ? (\n <p role=\"status\" className=\"px-7 py-5 text-xs text-muted-foreground\">\n جارٍ تحميل سير العمل…\n </p>\n ) : (\n <ul className=\"divide-y\">\n {runs.map((run) => (\n <li key={run.id} className=\"space-y-3 px-7 py-4\">\n <div className=\"flex flex-wrap items-center gap-2 text-sm\">\n <span className=\"font-medium\">{run.label}</span>\n <Badge variant={run.status === 'failed' ? 'destructive' : 'secondary'}>\n {runStatusLabel[run.status] ?? run.status}\n </Badge>\n {run.outcome && <Badge>{outcomeLabel[run.outcome] ?? run.outcome}</Badge>}\n {run.status === 'waiting' && run.stepLabel && (\n <span className=\"text-xs text-muted-foreground\">الخطوة: {run.stepLabel}</span>\n )}\n <span className=\"ms-auto\">\n <WorkflowDecision\n run={run}\n onDecided={() => {\n void load()\n }}\n />\n </span>\n </div>\n {run.lastError && (\n <p className=\"rounded-lg bg-red-50 px-3 py-2 text-xs text-red-800\">\n {run.lastError}\n </p>\n )}\n <ol className=\"space-y-1 border-s ps-4 text-xs\">\n {run.history.map((entry, index) => (\n <li key={index} className=\"flex flex-wrap gap-x-3\">\n <span className=\"font-medium\">{eventLabel[entry.event] ?? entry.event}</span>\n {entry.actorName && <span>{entry.actorName}</span>}\n {typeof entry.detail.comment === 'string' && (\n <span className=\"text-muted-foreground\">«{entry.detail.comment}»</span>\n )}\n <time dateTime={entry.at} className=\"text-muted-foreground tabular-nums\">\n {formatDatetime(entry.at, calendar)}\n </time>\n </li>\n ))}\n </ol>\n </li>\n ))}\n </ul>\n )}\n </section>\n )\n}\n",
|
|
22
|
+
"content": "import { useCallback, useEffect, useState } from 'react'\nimport axios from 'axios'\nimport { AlarmClock, CheckCircle2, GitBranch, UserRoundCheck, XCircle } from 'lucide-react'\nimport type { SlaState, WorkflowRun } from 'adula'\nimport { Badge } from '~/components/ui/badge'\nimport { Button } from '~/components/ui/button'\nimport { Label } from '~/components/ui/label'\nimport { Textarea } from '~/components/ui/textarea'\nimport { Dialog, DialogClose } from '~/components/ui/dialog'\nimport { LongDialogContent } from '~/components/ui/long-dialog'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\nimport { UserAvatar } from '~/components/ui/user-avatar'\nimport { formatDatetime } from '~/components/ui/resource-value'\n\nconst json = { headers: { Accept: 'application/json' }, withXSRFToken: true }\nexport const runStatusLabel: Record<string, string> = {\n pending_definition: 'بانتظار التعريف',\n running: 'قيد التنفيذ',\n waiting: 'بانتظار موافقة',\n completed: 'مكتمل',\n failed: 'فشل',\n cancelled: 'أُلغي',\n}\nconst outcomeLabel: Record<string, string> = {\n approved: 'معتمد',\n rejected: 'مرفوض',\n completed: 'مكتمل',\n no_workflow: 'بلا تدفق',\n}\nconst eventLabel: Record<string, string> = {\n started: 'بدأ التدفق',\n evaluate: 'تقييم شرط',\n approval_requested: 'طُلبت الموافقة',\n approved: 'موافقة',\n rejected: 'رفض',\n decided: 'قرار',\n done: 'نُفذت الخطوة',\n delay_started: 'بدأ الانتظار',\n retry_scheduled: 'جدولة إعادة المحاولة',\n failed: 'فشل',\n retried: 'إعادة تشغيل',\n migrated: 'ترحيل إلى إصدار أحدث',\n completed: 'اكتمل',\n cancelled: 'أُلغي',\n sla_reminded: 'تذكير بقرب الموعد',\n sla_escalated: 'تصعيد بعد تجاوز المهلة',\n}\nconst escalationLabel: Record<string, string> = {\n overdue: 'وُسمت متأخرة',\n notify: 'أُبلغ المسؤول',\n reassign: 'أُعيد الإسناد',\n}\nexport const slaStateLabel: Record<SlaState, string> = {\n on_time: 'في الموعد',\n due_soon: 'يقترب الموعد',\n overdue: 'متأخر',\n}\n\n/**\n * Where an approval stands against its SLA deadline (ADR 044), with the deadline itself;\n * the state is in the text, never in the colour alone.\n */\nexport function SlaBadge({\n state,\n dueAt,\n escalated = false,\n}: {\n state: SlaState\n dueAt: string\n escalated?: boolean\n}) {\n const { calendar } = useUiPreferences()\n return (\n <span className=\"inline-flex flex-wrap items-center gap-1.5 text-xs\">\n <Badge\n variant={state === 'overdue' ? 'destructive' : 'outline'}\n className={state === 'due_soon' ? 'border-warning/30 bg-warning/10 text-warning' : undefined}\n >\n <AlarmClock aria-hidden=\"true\" />\n {slaStateLabel[state]}\n </Badge>\n <span className=\"text-muted-foreground\">\n الموعد{' '}\n <time dateTime={dueAt} className=\"tabular-nums\">\n <bdi>{formatDatetime(dueAt, calendar)}</bdi>\n </time>\n </span>\n {escalated && <Badge variant=\"secondary\">صُعّدت</Badge>}\n </span>\n )\n}\n\n/** «On behalf of <name>» for an approval decided through a delegation. */\nexport function OnBehalfOf({ name }: { name: string | null | undefined }) {\n return (\n <Badge variant=\"outline\" className=\"border-info/30 bg-info/10 text-info\">\n <UserRoundCheck aria-hidden=\"true\" />\n نيابة عن {name ?? 'زميل'}\n </Badge>\n )\n}\n\ntype DecisionChoice = NonNullable<\n NonNullable<WorkflowRun['myApproval']>['decision']\n>['outcomes'][number]\n\n// A plain approval step offers exactly these two decisions.\nconst approvalChoices: DecisionChoice[] = [\n { key: 'approve', label: 'موافقة', comment: 'optional' },\n { key: 'reject', label: 'رفض', comment: 'optional' },\n]\nconst dialogTitle: Record<string, string> = { approve: 'تأكيد الموافقة', reject: 'تأكيد الرفض' }\n\n/**\n * The approver's decision in a confirmation dialog: approve or reject, or at a decision\n * step one of its named outcomes (#42). A decision never edits the submitted document.\n */\nexport function WorkflowDecision({\n run,\n onDecided,\n}: {\n run: WorkflowRun\n onDecided: (run: WorkflowRun) => void\n}) {\n const [choice, setChoice] = useState<DecisionChoice | null>(null)\n const [comment, setComment] = useState('')\n const [error, setError] = useState('')\n const [busy, setBusy] = useState(false)\n if (!run.myApproval) return null\n const form = run.myApproval.decision\n const choices = form?.outcomes ?? approvalChoices\n const open = (next: DecisionChoice) => {\n setChoice(next)\n setComment('')\n setError('')\n }\n const submit = async () => {\n if (!choice) return\n if (choice.comment === 'required' && !comment.trim()) {\n setError('اكتب ملاحظة القرار.')\n return\n }\n setBusy(true)\n setError('')\n try {\n const response = await axios.post<{ data: WorkflowRun }>(\n `/workflows/${run.id}/decide`,\n { decision: choice.key, comment },\n json\n )\n setChoice(null)\n setComment('')\n onDecided(response.data.data)\n } catch (caught) {\n setError(\n axios.isAxiosError(caught) && caught.response?.data?.error?.message\n ? String(caught.response.data.error.message)\n : 'تعذر تسجيل القرار.'\n )\n } finally {\n setBusy(false)\n }\n }\n const rejecting = choice?.key === 'reject'\n const behalf = run.myApproval.onBehalfOf\n return (\n <>\n <div className=\"flex flex-wrap gap-2\">\n {choices.map((item, index) => (\n <Button\n key={item.key}\n size=\"sm\"\n variant={index === 0 ? 'default' : 'outline'}\n className={item.key === 'reject' ? 'text-destructive' : undefined}\n onClick={() => open(item)}\n >\n {item.key === 'approve' && <CheckCircle2 size={15} />}\n {item.key === 'reject' && <XCircle size={15} />}\n {item.label}\n </Button>\n ))}\n </div>\n <Dialog\n mode=\"edit\"\n open={choice !== null}\n onOpenChange={(next) => !next && !busy && setChoice(null)}\n // The note is the only value typed here, and it opens empty.\n value={comment}\n >\n <LongDialogContent\n dir=\"rtl\"\n width=\"lg\"\n title={choice && (form ? `تأكيد القرار: ${choice.label}` : dialogTitle[choice.key])}\n description={`${run.myApproval.title} — ${run.resourceLabel}: ${run.recordTitle ?? `#${run.recordId}`}`}\n footer={\n <>\n <DialogClose asChild>\n <Button type=\"button\" variant=\"outline\" disabled={busy}>\n إلغاء\n </Button>\n </DialogClose>\n <Button\n type=\"submit\"\n form={`decision-form-${run.id}`}\n variant={rejecting ? 'destructive' : 'default'}\n disabled={busy}\n >\n {choice?.label}\n </Button>\n </>\n }\n >\n {behalf && (\n <p className=\"mb-4 rounded-lg bg-info/10 px-3 py-2 text-xs text-info\">\n تقرر نيابة عن {behalf.name ?? 'زميل'} بموجب تفويض، ويُسجَّل القرار باسمك نيابة عنه.\n </p>\n )}\n <form\n id={`decision-form-${run.id}`}\n className=\"space-y-2\"\n // The required note is checked here, with an Arabic message, not by the browser.\n noValidate\n onSubmit={(event) => {\n event.preventDefault()\n void submit()\n }}\n >\n <Label htmlFor={`decision-comment-${run.id}`} className=\"flex items-center gap-1\">\n {choice?.comment === 'required' ? (\n <>\n ملاحظة\n <span className=\"text-destructive\" aria-hidden=\"true\">\n *\n </span>\n </>\n ) : (\n 'ملاحظة (اختيارية)'\n )}\n </Label>\n <Textarea\n id={`decision-comment-${run.id}`}\n value={comment}\n maxLength={1000}\n required={choice?.comment === 'required'}\n onChange={(event) => setComment(event.target.value)}\n />\n </form>\n {error && (\n <p\n role=\"alert\"\n className=\"mt-4 rounded-lg bg-destructive/10 px-3 py-2 text-xs text-destructive\"\n >\n {error}\n </p>\n )}\n </LongDialogContent>\n </Dialog>\n </>\n )\n}\n\n/** Workflow runs of one submittable record with their step history. */\nexport function RecordWorkflows({ resource, id }: { resource: string; id: number | string }) {\n const { calendar } = useUiPreferences()\n const [runs, setRuns] = useState<WorkflowRun[] | null>(null)\n const load = useCallback(async () => {\n try {\n const response = await axios.get<{ data: WorkflowRun[] }>(\n `/resources/${resource}/${id}/workflows`,\n json\n )\n setRuns(response.data.data)\n } catch {\n setRuns([])\n }\n }, [resource, id])\n useEffect(() => {\n void load()\n }, [load])\n if (runs !== null && runs.length === 0) return null\n return (\n <section aria-label=\"سير العمل\" className=\"rounded-xl border bg-card\">\n <div className=\"flex items-center gap-2 border-b px-7 py-4\">\n <GitBranch size={16} className=\"text-muted-foreground\" />\n <h2 className=\"text-sm font-semibold\">سير العمل</h2>\n </div>\n {runs === null ? (\n <p role=\"status\" className=\"px-7 py-5 text-xs text-muted-foreground\">\n جارٍ تحميل سير العمل…\n </p>\n ) : (\n <ul className=\"divide-y\">\n {runs.map((run) => (\n <li key={run.id} className=\"space-y-3 px-7 py-4\">\n <div className=\"flex flex-wrap items-center gap-2 text-sm\">\n <span className=\"font-medium\">{run.label}</span>\n <Badge variant={run.status === 'failed' ? 'destructive' : 'secondary'}>\n {runStatusLabel[run.status] ?? run.status}\n </Badge>\n {run.outcome && <Badge>{outcomeLabel[run.outcome] ?? run.outcome}</Badge>}\n {run.status === 'waiting' && run.stepLabel && (\n <span className=\"text-xs text-muted-foreground\">الخطوة: {run.stepLabel}</span>\n )}\n {run.status === 'waiting' && run.sla && (\n <SlaBadge\n state={run.sla.state}\n dueAt={run.sla.dueAt}\n escalated={run.sla.escalated}\n />\n )}\n <span className=\"ms-auto flex flex-wrap items-center gap-2\">\n {run.myApproval?.onBehalfOf && (\n <OnBehalfOf name={run.myApproval.onBehalfOf.name} />\n )}\n <WorkflowDecision\n run={run}\n onDecided={() => {\n void load()\n }}\n />\n </span>\n </div>\n {run.lastError && (\n <p className=\"rounded-lg bg-destructive/10 px-3 py-2 text-xs text-destructive\">\n {run.lastError}\n </p>\n )}\n <ol className=\"space-y-1 border-s ps-4 text-xs\">\n {run.history.map((entry, index) => (\n <li key={index} className=\"flex flex-wrap gap-x-3\">\n <span className=\"font-medium\">{eventLabel[entry.event] ?? entry.event}</span>\n {entry.actorName && (\n <span className=\"inline-flex items-center gap-1.5\">\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}\n </span>\n )}\n {entry.onBehalfOfName && (\n <span className=\"text-info\">نيابة عن {entry.onBehalfOfName}</span>\n )}\n {entry.event === 'sla_escalated' &&\n typeof entry.detail.action === 'string' && (\n <span className=\"text-muted-foreground\">\n {escalationLabel[entry.detail.action] ?? entry.detail.action}\n </span>\n )}\n {typeof entry.detail.comment === 'string' && (\n <span className=\"text-muted-foreground\">«{entry.detail.comment}»</span>\n )}\n <time dateTime={entry.at} className=\"text-muted-foreground tabular-nums\">\n {formatDatetime(entry.at, calendar)}\n </time>\n </li>\n ))}\n </ol>\n </li>\n ))}\n </ul>\n )}\n </section>\n )\n}\n",
|
|
22
23
|
"target": "inertia/components/ui/record-workflows.tsx"
|
|
23
24
|
}
|
|
24
25
|
],
|
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
"registryDependencies": [
|
|
5
5
|
"button",
|
|
6
6
|
"dialog",
|
|
7
|
-
"can"
|
|
7
|
+
"can",
|
|
8
|
+
"messages"
|
|
8
9
|
],
|
|
9
10
|
"dependencies": [
|
|
10
11
|
"axios@1.19.0",
|
|
@@ -14,7 +15,7 @@
|
|
|
14
15
|
{
|
|
15
16
|
"path": "registry/ui/resource-actions.tsx",
|
|
16
17
|
"type": "registry:ui",
|
|
17
|
-
"content": "import { useState } from 'react'\nimport { router } from '@inertiajs/react'\nimport axios from 'axios'\nimport { toast } from 'sonner'\nimport type { RecordPermissions } from 'adula'\nimport { Button } from '~/components/ui/button'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from '~/components/ui/dialog'\nimport { Can } from '~/components/ui/can'\n\nexport type TransitionAction = 'delete' | 'submit' | 'cancel' | 'amend'\nexport const transitionLabels: Record<TransitionAction, string> = {\n delete: 'حذف السجل',\n submit: 'اعتماد المستند',\n cancel: 'إلغاء الاعتماد',\n amend: 'تعديل بالنسخ',\n}\nconst
|
|
18
|
+
"content": "import { useState } from 'react'\nimport { router } from '@inertiajs/react'\nimport axios from 'axios'\nimport { toast } from 'sonner'\nimport type { RecordPermissions } from 'adula'\nimport { Button } from '~/components/ui/button'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from '~/components/ui/dialog'\nimport { Can } from '~/components/ui/can'\nimport { arabicText, useMessages, type Translate } from '~/components/ui/messages'\n\nexport type TransitionAction = 'delete' | 'submit' | 'cancel' | 'amend'\nexport const transitionLabels: Record<TransitionAction, string> = {\n delete: 'حذف السجل',\n submit: 'اعتماد المستند',\n cancel: 'إلغاء الاعتماد',\n amend: 'تعديل بالنسخ',\n}\n/** Accessible names that name the record: «حذف ORD-000012», never «حذف السجل السجل 12» (#110). */\nconst namedLabels: Record<TransitionAction, (record: string, t: Translate) => string> = {\n delete: (record, t) => t('حذف {record}', { record }),\n submit: (record, t) => t('اعتماد {record}', { record }),\n cancel: (record, t) => t('إلغاء اعتماد {record}', { record }),\n amend: (record, t) => t('تعديل {record} بالنسخ', { record }),\n}\nconst descriptions: Record<TransitionAction, string> = {\n // Deleting is soft: the record moves to «المحذوفات», where whoever deletes may restore it.\n delete: 'سيُنقل السجل إلى «المحذوفات»، ويمكن استعادته منها.',\n submit: 'بعد الاعتماد لا يمكن تعديل المستند أو بنوده.',\n cancel: 'سيُعاد المستند إلى حالة الإلغاء ولن يُحتسب.',\n amend: 'تُنشأ مسودة جديدة منسوخة من هذا المستند الملغي مع بنوده، ويبقى الأصل كما هو.',\n}\nconst successes: Record<TransitionAction, string> = {\n delete: 'تم حذف السجل',\n submit: 'تم اعتماد المستند',\n cancel: 'تم إلغاء الاعتماد',\n amend: 'تم تعديل بالنسخ',\n}\n\n/** Pass the component's `t` so the built-in messages follow the interface language. */\nexport function failureMessage(error: unknown, fallback: string, t: Translate = arabicText) {\n if (!axios.isAxiosError(error)) return t('تعذر الاتصال بالخادم. حاول مجدداً.')\n if (error.response?.status === 409 && error.response.data?.error?.code === 'E_VERSION_CONFLICT')\n return t('تغير السجل منذ فتحه. أعد تحميل الصفحة قبل المتابعة.')\n return error.response?.data?.error?.message ?? fallback\n}\n\nexport function isConflict(error: unknown) {\n return axios.isAxiosError(error) && error.response?.status === 409\n}\n\n/** Version travels with every transition so a stale page cannot delete or approve a changed record. */\nexport function ResourceActions({\n resource,\n id,\n version,\n permissions,\n label,\n size = 'default',\n variant = 'outline',\n onDone,\n}: {\n resource: string\n id: number | string\n version?: unknown\n permissions: RecordPermissions\n label?: string\n size?: 'default' | 'sm'\n variant?: 'outline' | 'ghost'\n onDone?: (action: TransitionAction) => void\n}) {\n const { t } = useMessages()\n const [pending, setPending] = useState<TransitionAction | null>(null)\n const [busy, setBusy] = useState(false)\n const [failure, setFailure] = useState('')\n const [conflict, setConflict] = useState(false)\n const base = `/resources/${resource}/${id}`\n // «تراجع» restores the record just deleted, then shows the page as it now is.\n const undoDelete = async () => {\n try {\n await axios.post(\n `${base}/restore`,\n {},\n { headers: { Accept: 'application/json' }, withXSRFToken: true }\n )\n toast.success(t('تمت استعادة السجل'))\n router.reload()\n } catch (error) {\n toast.error(failureMessage(error, t('تعذر التراجع عن الحذف. استعد السجل من «المحذوفات».'), t))\n }\n }\n const execute = async () => {\n if (!pending) return\n setBusy(true)\n setFailure('')\n try {\n const response = await axios.request({\n method: pending === 'delete' ? 'delete' : 'post',\n url: pending === 'delete' ? base : `${base}/${pending}`,\n data: version === undefined ? {} : { version },\n headers: { Accept: 'application/json' },\n withXSRFToken: true,\n })\n const done = pending\n if (done === 'delete')\n toast.success(t(successes.delete), {\n action: {\n label: t('تراجع'),\n onClick: () => void undoDelete(),\n },\n })\n else toast.success(t(successes[done]))\n setPending(null)\n // The amended copy is a new draft; continue editing it.\n if (done === 'amend') router.visit(`/resources/${resource}/${response.data.data.id}/edit`)\n else if (onDone) onDone(done)\n else if (done === 'delete') router.visit(`/resources/${resource}`)\n else router.reload()\n } catch (error) {\n setConflict(isConflict(error))\n setFailure(\n failureMessage(error, t('تعذر تنفيذ الإجراء. تحقق من صلاحياتك وحاول مجدداً.'), t)\n )\n } finally {\n setBusy(false)\n }\n }\n return (\n <>\n {(['submit', 'cancel', 'amend', 'delete'] as const).map((action) => (\n <Can key={action} permissions={permissions} action={action}>\n <Button\n type=\"button\"\n variant={variant}\n size={size}\n className={action === 'delete' ? 'text-destructive' : undefined}\n aria-label={label ? namedLabels[action](label, t) : undefined}\n onClick={() => {\n setPending(action)\n setFailure('')\n setConflict(false)\n }}\n >\n {t(transitionLabels[action])}\n </Button>\n </Can>\n ))}\n <Dialog open={pending !== null} onOpenChange={(open) => !open && !busy && setPending(null)}>\n <DialogContent>\n <DialogHeader>\n <DialogTitle>{pending ? t(transitionLabels[pending]) : ''}</DialogTitle>\n <DialogDescription>\n {pending ? t(descriptions[pending]) : ''}\n {label ? ` (${label})` : ''}\n </DialogDescription>\n </DialogHeader>\n {failure && (\n <div role=\"alert\" className=\"flex flex-wrap items-center gap-3 text-sm text-destructive\">\n {failure}\n {conflict && (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={() => router.reload()}>\n {t('إعادة التحميل')}\n </Button>\n )}\n </div>\n )}\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" disabled={busy} onClick={() => setPending(null)}>\n {t('تراجع')}\n </Button>\n <Button\n type=\"button\"\n variant={pending === 'delete' ? 'destructive' : 'default'}\n disabled={busy || conflict}\n onClick={() => void execute()}\n >\n {busy ? t('جارٍ التنفيذ...') : t('تأكيد')}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n </>\n )\n}\n",
|
|
18
19
|
"target": "inertia/components/ui/resource-actions.tsx"
|
|
19
20
|
}
|
|
20
21
|
],
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "resource-bulk",
|
|
3
|
+
"type": "registry:ui",
|
|
4
|
+
"registryDependencies": [
|
|
5
|
+
"alert",
|
|
6
|
+
"button",
|
|
7
|
+
"dialog",
|
|
8
|
+
"resource-actions",
|
|
9
|
+
"resource-value",
|
|
10
|
+
"list-filters",
|
|
11
|
+
"messages"
|
|
12
|
+
],
|
|
13
|
+
"dependencies": [
|
|
14
|
+
"axios@1.19.0",
|
|
15
|
+
"sonner@2.0.8",
|
|
16
|
+
"lucide-react@1.47.0"
|
|
17
|
+
],
|
|
18
|
+
"files": [
|
|
19
|
+
{
|
|
20
|
+
"path": "registry/ui/resource-bulk.tsx",
|
|
21
|
+
"type": "registry:ui",
|
|
22
|
+
"content": "import { useEffect, useState } from 'react'\nimport axios from 'axios'\nimport { toast } from 'sonner'\nimport { CircleAlert, CircleCheck, X } from 'lucide-react'\nimport type { SerializedRecord } from 'adula'\nimport { Alert, AlertDescription, AlertTitle } from '~/components/ui/alert'\nimport { Button } from '~/components/ui/button'\nimport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from '~/components/ui/dialog'\nimport { LongDialogContent } from '~/components/ui/long-dialog'\nimport { failureMessage } from '~/components/ui/resource-actions'\nimport { documentCount, recordCount, useMessages } from '~/components/ui/messages'\nimport { relationLabel } from '~/components/ui/resource-value'\nimport { BULK_LIMIT, bulkPayload } from '~/components/ui/list_query'\n\n/** An action offered by `GET /resources/:name/bulk` (the server's BulkActionOption). */\nexport type BulkAction = {\n key: string\n label?: string | null\n confirm?: string | null\n builtIn?: boolean\n /** `trash` actions (restore) belong to «المحذوفات»; `records` to the active list. */\n scope?: 'records' | 'trash'\n destructive?: boolean\n}\nexport type BulkFailure = {\n id: number | string\n code?: string\n message: string\n}\nexport type BulkResult = {\n succeeded: (number | string)[]\n failed: BulkFailure[]\n}\n\nconst builtInLabels: Record<string, string> = {\n delete: 'حذف',\n restore: 'استعادة',\n submit: 'اعتماد',\n cancel: 'إلغاء المستند',\n}\n// `{records}`/`{documents}` are counted phrases («سجلان»، «11 سجلًا»), never «{count} سجل» (#110).\nconst builtInDescriptions: Record<string, string> = {\n delete: 'سيُحذف {records} من القوائم، وتبقى الاستعادة ممكنة من «المحذوفات».',\n restore: 'سيُستعاد {records} من «المحذوفات» إلى السجلات النشطة.',\n submit: 'سيُعتمد {documents}، ولا يمكن التعديل بعد الاعتماد.',\n cancel: 'سيُلغى الاعتماد. المحدد: {documents}. لا يُحتسب المستند الملغى.',\n}\n\nconst asList = (data: unknown): BulkAction[] => {\n const list = Array.isArray(data) ? data : (data as { data?: unknown } | null)?.data\n return Array.isArray(list)\n ? list.filter(\n (entry): entry is BulkAction =>\n Boolean(entry) && typeof (entry as BulkAction).key === 'string'\n )\n : []\n}\n\n/** Whether an action belongs to the active list or to «المحذوفات». */\nexport function actionScope(action: BulkAction) {\n return action.scope ?? (action.key === 'restore' ? 'trash' : 'records')\n}\n\n/**\n * The bulk actions the actor may offer; refusals and failures mean none. `initial` comes with\n * the page props of the generic list (#108), so the selection column renders with the first rows;\n * pages that pass nothing load them from `GET /resources/:name/bulk`.\n */\nexport function useBulkActions(resource: string, enabled = true, initial?: BulkAction[]) {\n const given = initial === undefined ? undefined : asList(initial)\n // A new array holding the same actions (every page visit) is not a change.\n const seed = given === undefined ? null : JSON.stringify(given)\n const [actions, setActions] = useState<BulkAction[]>(() => (enabled ? (given ?? []) : []))\n useEffect(() => {\n let live = true\n if (!enabled) {\n setActions([])\n return\n }\n if (given) {\n setActions(given)\n return\n }\n axios\n .get(`/resources/${resource}/bulk`, {\n headers: { Accept: 'application/json' },\n })\n .then((response) => live && setActions(asList(response.data)))\n .catch(() => live && setActions([]))\n return () => {\n live = false\n }\n }, [resource, enabled, seed])\n return actions\n}\n\n/**\n * The sticky bar of a selection: one button per offered action, each confirmed in a Dialog\n * that then shows which rows succeeded and which were refused, with the server's message.\n */\nexport function BulkBar({\n resource,\n actions,\n selected,\n rows,\n onClear,\n onDone,\n}: {\n resource: string\n actions: BulkAction[]\n selected: string[]\n rows: SerializedRecord[]\n onClear: () => void\n onDone: (result: BulkResult) => void\n}) {\n const { t } = useMessages()\n const [pending, setPending] = useState<BulkAction | null>(null)\n const [busy, setBusy] = useState(false)\n const [failure, setFailure] = useState('')\n const [result, setResult] = useState<BulkResult | null>(null)\n const [ids, setIds] = useState<string[]>([])\n const over = selected.length > BULK_LIMIT\n const name = (action: BulkAction) =>\n action.label ? action.label : t(builtInLabels[action.key] ?? action.key)\n const describe = (action: BulkAction, count: number) =>\n action.confirm\n ? action.confirm\n : builtInDescriptions[action.key]\n ? t(builtInDescriptions[action.key], {\n records: recordCount(count, t),\n documents: documentCount(count, t),\n })\n : t('سيُنفذ الإجراء «{action}». المحدد: {records}.', {\n action: name(action),\n records: recordCount(count, t),\n })\n const destructive = (action: BulkAction) => action.destructive ?? action.key === 'delete'\n const titles = new Map(rows.map((row) => [String(row.id), relationLabel(row, row.id)]))\n const execute = async () => {\n if (!pending) return\n setBusy(true)\n setFailure('')\n try {\n const response = await axios.post<{ data: BulkResult }>(\n `/resources/${resource}/bulk`,\n bulkPayload(pending.key, ids, rows),\n { headers: { Accept: 'application/json' }, withXSRFToken: true }\n )\n const outcome = response.data.data\n setResult(outcome)\n if (!outcome.failed.length)\n toast.success(t('نُفذ الإجراء: {records}', { records: recordCount(outcome.succeeded.length, t) }))\n } catch (error) {\n setFailure(failureMessage(error, t('تعذر تنفيذ الإجراء. تحقق من صلاحياتك وحاول مجدداً.'), t))\n } finally {\n setBusy(false)\n }\n }\n // The list refreshes once the summary is closed: a refresh remounts the page, which would\n // otherwise dismiss the summary before it is read.\n const close = () => {\n if (busy) return\n if (result) onDone(result)\n setPending(null)\n setResult(null)\n setFailure('')\n }\n if (!selected.length && !pending) return null\n return (\n <>\n {selected.length > 0 && (\n <div\n role=\"region\"\n aria-label={t('الإجراءات الجماعية')}\n className=\"sticky top-0 z-20 flex flex-wrap items-center gap-2 border-b bg-accent px-5 py-2.5 text-sm\"\n >\n <span className=\"font-medium tabular-nums\">\n {t('تم تحديد {count}', { count: selected.length })}\n </span>\n <Button variant=\"ghost\" size=\"xs\" onClick={onClear}>\n <X size={13} />\n {t('إلغاء التحديد')}\n </Button>\n <span className=\"ms-auto flex flex-wrap items-center gap-2\">\n {over && (\n <span className=\"text-xs text-destructive\">\n {t('الحد الأقصى في كل مرة: {records}.', {\n records: recordCount(BULK_LIMIT, t),\n })}\n </span>\n )}\n {actions.map((action) => (\n <Button\n key={action.key}\n type=\"button\"\n size=\"sm\"\n variant=\"outline\"\n disabled={over}\n className={`h-8 bg-background ${destructive(action) ? 'text-destructive' : ''}`}\n onClick={() => {\n setIds(selected)\n setResult(null)\n setFailure('')\n setPending(action)\n }}\n >\n {name(action)}\n </Button>\n ))}\n </span>\n </div>\n )}\n <Dialog open={pending !== null} onOpenChange={(open) => !open && close()}>\n <LongDialogContent\n width=\"lg\"\n title={pending ? name(pending) : ''}\n description={\n <>\n {pending ? describe(pending, ids.length) : ''}{' '}\n {!result && t('يُتحقق من صلاحيتك لكل سجل على حدة.')}\n </>\n }\n footer={\n result ? (\n <Button type=\"button\" onClick={close}>\n {t('إغلاق')}\n </Button>\n ) : (\n <>\n <DialogClose asChild>\n <Button type=\"button\" variant=\"outline\" disabled={busy}>\n {t('إلغاء')}\n </Button>\n </DialogClose>\n <Button\n type=\"button\"\n variant={pending && destructive(pending) ? 'destructive' : 'default'}\n disabled={busy}\n onClick={() => void execute()}\n >\n {busy ? t('جارٍ التنفيذ...') : t('تأكيد')}\n </Button>\n </>\n )\n }\n >\n {result && (\n <div className=\"grid gap-3\">\n {result.succeeded.length > 0 && (\n <Alert>\n <CircleCheck />\n <AlertTitle>\n {t('نُفذ الإجراء: {records}', {\n records: recordCount(result.succeeded.length, t),\n })}\n </AlertTitle>\n </Alert>\n )}\n {result.failed.length > 0 && (\n <Alert variant=\"destructive\">\n <CircleAlert />\n <AlertTitle>\n {t('تعذر التنفيذ: {records}', {\n records: recordCount(result.failed.length, t),\n })}\n </AlertTitle>\n <AlertDescription>\n <ul className=\"w-full space-y-1 text-xs\">\n {result.failed.map((entry) => (\n <li key={String(entry.id)}>\n <span className=\"font-medium\">\n {titles.get(String(entry.id)) ?? `#${entry.id}`}\n </span>{' '}\n <span dir=\"ltr\" className=\"tabular-nums\">\n (#{entry.id})\n </span>\n {t('، ')}\n {entry.message}\n </li>\n ))}\n </ul>\n </AlertDescription>\n </Alert>\n )}\n </div>\n )}\n {failure && (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {failure}\n </p>\n )}\n </LongDialogContent>\n </Dialog>\n </>\n )\n}\n\n/** «استعادة» of one deleted record, confirmed in a Dialog; restore is authorized by delete. */\nexport function RestoreAction({\n resource,\n id,\n version,\n label,\n onDone,\n}: {\n resource: string\n id: string\n version?: unknown\n label: string\n onDone: () => void\n}) {\n const { t } = useMessages()\n const [open, setOpen] = useState(false)\n const [busy, setBusy] = useState(false)\n const [failure, setFailure] = useState('')\n const restore = async () => {\n setBusy(true)\n setFailure('')\n try {\n await axios.post(\n `/resources/${resource}/${id}/restore`,\n version === undefined || version === null ? {} : { version },\n { headers: { Accept: 'application/json' }, withXSRFToken: true }\n )\n toast.success(t('تمت استعادة السجل'))\n setOpen(false)\n onDone()\n } catch (error) {\n setFailure(failureMessage(error, t('تعذر استعادة السجل. تحقق من صلاحياتك وحاول مجدداً.'), t))\n } finally {\n setBusy(false)\n }\n }\n return (\n <>\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n aria-label={t('استعادة {record}', { record: label })}\n onClick={() => {\n setFailure('')\n setOpen(true)\n }}\n >\n {t('استعادة')}\n </Button>\n <Dialog open={open} onOpenChange={(next) => !next && !busy && setOpen(false)}>\n <DialogContent className=\"sm:max-w-md\">\n <DialogHeader>\n <DialogTitle>{t('استعادة السجل')}</DialogTitle>\n <DialogDescription>\n {t('سيعود {record} إلى السجلات النشطة ويظهر في القوائم.', {\n record: label,\n })}\n </DialogDescription>\n </DialogHeader>\n {failure && (\n <p role=\"alert\" className=\"text-sm text-destructive\">\n {failure}\n </p>\n )}\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" disabled={busy} onClick={() => setOpen(false)}>\n {t('تراجع')}\n </Button>\n <Button type=\"button\" disabled={busy} onClick={() => void restore()}>\n {busy ? t('جارٍ التنفيذ...') : t('استعادة')}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n </>\n )\n}\n",
|
|
23
|
+
"target": "inertia/components/ui/resource-bulk.tsx"
|
|
24
|
+
}
|
|
25
|
+
],
|
|
26
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
27
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "resource-dashboard",
|
|
3
|
+
"type": "registry:ui",
|
|
4
|
+
"registryDependencies": [
|
|
5
|
+
"card",
|
|
6
|
+
"resource-value",
|
|
7
|
+
"messages"
|
|
8
|
+
],
|
|
9
|
+
"dependencies": [
|
|
10
|
+
"lucide-react@1.47.0"
|
|
11
|
+
],
|
|
12
|
+
"files": [
|
|
13
|
+
{
|
|
14
|
+
"path": "registry/ui/resource-dashboard.tsx",
|
|
15
|
+
"type": "registry:ui",
|
|
16
|
+
"content": "import { Link } from '@adonisjs/inertia/react'\nimport { Inbox, ShieldCheck } from 'lucide-react'\nimport { Card, CardContent, CardDescription, CardHeader, CardTitle } from '~/components/ui/card'\nimport { useMessages, type Translate } from '~/components/ui/messages'\nimport { CURRENCY_LABEL, PERCENT_LABEL } from '~/components/ui/resource-value'\nimport {\n formatDecimal,\n normalizeDashboard,\n shares,\n type DashboardFormat,\n type DashboardTile,\n} from '~/components/ui/dashboard_data'\n\nexport type DashboardLink = { name: string; label: string }\n\n/**\n * A value as the indicator shows it: grouped digits, amounts with two decimals and currency,\n * percent totals with the percent sign.\n */\nexport function indicatorValue(value: string, format: DashboardFormat, t: Translate) {\n const digits = formatDecimal(value, format)\n if (format === 'money') return `${digits} ${t(CURRENCY_LABEL)}`\n return format === 'percent' ? `${digits}${t(PERCENT_LABEL)}` : digits\n}\n\n/**\n * An indicators page (ADR 046). Every number is computed by the server as the viewer, so it\n * covers only the records the viewer may see; widgets the viewer cannot read are absent.\n * Pass `dashboards` to switch between several pages, linked at `/dashboards/:name`.\n */\nexport function ResourceDashboard({\n dashboard,\n dashboards = [],\n hrefFor = (name) => `/dashboards/${name}`,\n}: {\n /** The server's DashboardResult; read structurally so older or newer shapes still render. */\n dashboard: unknown\n dashboards?: DashboardLink[]\n hrefFor?: (name: string) => string\n}) {\n const { t } = useMessages()\n const view = normalizeDashboard(dashboard)\n const totals = view.widgets.filter((widget) => widget.kind === 'total')\n const grouped = view.widgets.filter((widget) => widget.kind === 'grouped')\n return (\n <div className=\"grid gap-6\">\n <div className=\"flex flex-wrap items-start justify-between gap-5\">\n <div>\n <h1 className=\"text-3xl font-semibold tracking-tight\">{view.label}</h1>\n {view.description && (\n <p className=\"mt-3 text-sm text-muted-foreground\">{view.description}</p>\n )}\n <p className=\"mt-2 inline-flex items-center gap-1.5 text-xs text-muted-foreground\">\n <ShieldCheck size={14} />\n {t('تُحسب الأرقام ضمن نطاق صلاحياتك')}\n </p>\n </div>\n </div>\n {dashboards.length > 1 && (\n <nav\n aria-label={t('لوحات المؤشرات')}\n className=\"flex flex-wrap gap-1 rounded-lg border bg-muted p-1\"\n >\n {dashboards.map((entry) => {\n const current = entry.name === view.name\n return (\n <Link\n key={entry.name}\n href={hrefFor(entry.name)}\n aria-current={current ? 'page' : undefined}\n className={`rounded-md px-3 py-1.5 text-sm transition-colors ${\n current\n ? 'bg-background font-medium text-foreground shadow-sm'\n : 'text-muted-foreground hover:text-foreground'\n }`}\n >\n {entry.label}\n </Link>\n )\n })}\n </nav>\n )}\n {view.widgets.length === 0 ? (\n <Card>\n <CardContent className=\"py-12 text-center\">\n <Inbox className=\"mx-auto mb-3 text-muted-foreground\" size={30} strokeWidth={1.3} />\n <p className=\"text-sm font-medium\">{t('لا توجد مؤشرات متاحة لك في هذه اللوحة')}</p>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {t('تظهر المؤشرات التي تسمح صلاحياتك بقراءة سجلاتها.')}\n </p>\n </CardContent>\n </Card>\n ) : (\n <>\n {totals.length > 0 && (\n <section\n aria-label={t('المؤشرات الإجمالية')}\n className=\"grid gap-4 sm:grid-cols-2 lg:grid-cols-4\"\n >\n {totals.map((widget) => (\n <TotalTile key={widget.key} widget={widget} />\n ))}\n </section>\n )}\n {grouped.length > 0 && (\n <section aria-label={t('المؤشرات حسب الفئة')} className=\"grid gap-4 lg:grid-cols-2\">\n {grouped.map((widget) => (\n <GroupedCard key={widget.key} widget={widget} />\n ))}\n </section>\n )}\n </>\n )}\n </div>\n )\n}\n\n/** One widget of a DashboardResult on its own, as the personal overview shows it (ADR 050). */\nexport function DashboardWidgetCard({ widget }: { widget: unknown }) {\n const [tile] = normalizeDashboard({ widgets: [widget] }).widgets\n if (!tile) return null\n return tile.kind === 'total' ? <TotalTile widget={tile} /> : <GroupedCard widget={tile} />\n}\n\n/** The widget's label links to its resource list, where the same records can be reviewed. */\nfunction WidgetLabel({ label, href }: { label: string; href: string | null }) {\n const { t } = useMessages()\n if (!href) return <>{label}</>\n return (\n <Link\n href={href}\n className=\"hover:text-foreground hover:underline\"\n aria-label={t('فتح القائمة: {label}', { label })}\n >\n {label}\n </Link>\n )\n}\n\nfunction TotalTile({ widget }: { widget: DashboardTile & { kind: 'total' } }) {\n const { t } = useMessages()\n return (\n <Card className=\"gap-2 py-5\">\n <CardHeader className=\"px-5\">\n <CardDescription>\n <WidgetLabel label={widget.label} href={widget.href} />\n </CardDescription>\n </CardHeader>\n <CardContent className=\"px-5\">\n {widget.value === null ? (\n <p className=\"text-sm text-muted-foreground\">{t('لا توجد بيانات ضمن نطاقك')}</p>\n ) : (\n <p dir=\"ltr\" className=\"text-end text-3xl font-semibold tabular-nums tracking-tight\">\n {indicatorValue(widget.value, widget.format, t)}\n </p>\n )}\n </CardContent>\n </Card>\n )\n}\n\nfunction GroupedCard({ widget }: { widget: DashboardTile & { kind: 'grouped' } }) {\n const { t } = useMessages()\n const bars = shares(widget.groups.map((group) => group.value))\n return (\n <Card className=\"gap-4 py-5\">\n <CardHeader className=\"px-5\">\n <CardTitle className=\"text-sm\">\n <WidgetLabel label={widget.label} href={widget.href} />\n </CardTitle>\n </CardHeader>\n <CardContent className=\"px-5\">\n {widget.groups.length === 0 ? (\n <p className=\"py-6 text-center text-sm text-muted-foreground\">\n {t('لا توجد بيانات ضمن نطاقك')}\n </p>\n ) : (\n <ol className=\"grid gap-3\">\n {widget.groups.map((group, index) => {\n const value = indicatorValue(group.value, widget.format, t)\n const name = group.label || t('بلا قيمة')\n return (\n <li key={group.key} className=\"grid gap-1.5\">\n <div className=\"flex items-baseline justify-between gap-3 text-sm\">\n <span className=\"truncate\">{name}</span>\n <span dir=\"ltr\" className=\"shrink-0 font-medium tabular-nums\">\n {value}\n </span>\n </div>\n <div\n role=\"meter\"\n aria-label={t('{label}: {value}', { label: name, value })}\n aria-valuemin={0}\n aria-valuemax={100}\n aria-valuenow={bars[index]}\n className=\"h-1.5 overflow-hidden rounded-full bg-muted\"\n >\n <div\n className=\"h-full rounded-full bg-primary\"\n style={{ width: `${bars[index]}%` }}\n />\n </div>\n </li>\n )\n })}\n </ol>\n )}\n {widget.truncated && (\n <p className=\"mt-4 text-xs text-muted-foreground\">{t('تُعرض الفئات الأعلى قيمة فقط.')}</p>\n )}\n </CardContent>\n </Card>\n )\n}\n",
|
|
17
|
+
"target": "inertia/components/ui/resource-dashboard.tsx"
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
"path": "registry/ui/dashboard_data.ts",
|
|
21
|
+
"type": "registry:ui",
|
|
22
|
+
"content": "export type DashboardFormat = 'count' | 'integer' | 'money' | 'decimal' | 'percent'\n/*\n * The DashboardResult of ADR 046 as the indicators page reads it. Every number was computed\n * by the server as the viewer; this module only normalizes and ranks it, and drops what it\n * cannot read instead of showing an invented value. Pure and import-free so the registry\n * tests run it directly.\n */\n/** Values stay canonical decimal strings: money sums are minor units and may exceed 2^53. */\nexport type DashboardGroup = { key: string; label: string; value: string }\nexport type DashboardTile =\n | {\n kind: 'total'\n key: string\n label: string\n href: string | null\n format: DashboardFormat\n value: string | null\n }\n | {\n kind: 'grouped'\n key: string\n label: string\n href: string | null\n format: DashboardFormat\n groups: DashboardGroup[]\n truncated: boolean\n }\nexport type DashboardView = {\n name: string\n label: string\n description: string | null\n widgets: DashboardTile[]\n}\n\nconst DECIMAL = /^-?\\d+(\\.\\d+)?$/\n/**\n * count is an integer; integer, decimal and percent sums are decimal strings; money sums are\n * minor-unit strings.\n * Strings are kept as they are (never through Number), so large sums lose no digits.\n */\nexport function decimal(value: unknown): string | null {\n if (typeof value === 'number') return Number.isFinite(value) ? String(value) : null\n if (typeof value !== 'string') return null\n const trimmed = value.trim()\n return DECIMAL.test(trimmed) ? trimmed : null\n}\n\n/** Exact comparison of two canonical decimal strings. */\nexport function compareDecimal(a: string, b: string) {\n const parse = (value: string) => {\n const negative = value.startsWith('-')\n const [whole, fraction = ''] = value.replace('-', '').split('.')\n return { negative, whole: BigInt(whole), fraction }\n }\n const left = parse(a)\n const right = parse(b)\n const width = Math.max(left.fraction.length, right.fraction.length)\n const scaled = (part: ReturnType<typeof parse>) =>\n (part.whole * 10n ** BigInt(width) + BigInt(part.fraction.padEnd(width, '0') || '0')) *\n (part.negative ? -1n : 1n)\n const difference = scaled(left) - scaled(right)\n return difference === 0n ? 0 : difference > 0n ? 1 : -1\n}\n\nconst grouping = new Intl.NumberFormat('ar-u-nu-latn')\nconst groupDigits = (whole: string) => grouping.format(BigInt(whole))\n\n/**\n * The digits of an indicator: grouped thousands; money as major units with two decimals\n * (minor units in, string math only); decimal and percent sums keep the fraction the server\n * returned. The caller adds the currency or percent label.\n */\nexport function formatDecimal(value: string, format: DashboardFormat) {\n const negative = value.startsWith('-')\n const [whole, fraction] = value.replace('-', '').split('.')\n const sign = negative && /[1-9]/.test(value) ? '-' : ''\n if (format === 'money') {\n // Minor units are integers; a fractional part (not expected) is dropped, never rounded up.\n const minor = whole.padStart(3, '0')\n return `${sign}${groupDigits(minor.slice(0, -2))}.${minor.slice(-2)}`\n }\n return `${sign}${groupDigits(whole)}${fraction ? `.${fraction}` : ''}`\n}\nconst text = (value: unknown) => (typeof value === 'string' ? value : null)\nconst formats = new Set<unknown>(['count', 'integer', 'money', 'decimal', 'percent'])\n\n/** Reads one DashboardWidgetResult; a widget without a key is dropped. */\nexport function normalizeWidget(input: unknown): DashboardTile | null {\n if (!input || typeof input !== 'object') return null\n const widget = input as Record<string, unknown>\n const key = text(widget.key)\n if (!key) return null\n const base = {\n key,\n label: text(widget.label) ?? key,\n href: text(widget.href),\n format: (formats.has(widget.format) ? widget.format : 'count') as DashboardFormat,\n }\n if (widget.kind === 'grouped') {\n const groups: DashboardGroup[] = []\n const rows = Array.isArray(widget.rows) ? widget.rows : []\n for (const [index, row] of rows.entries()) {\n if (!row || typeof row !== 'object') continue\n const entry = row as Record<string, unknown>\n // `value` is the group's key; `measure` its count or sum (null when nothing to sum).\n const measure = decimal(entry.measure)\n if (measure === null) continue\n const group = entry.value\n groups.push({\n key:\n group === null || group === undefined ? `__none_${index}` : `${index}:${String(group)}`,\n label: text(entry.label) ?? (group === null || group === undefined ? '' : String(group)),\n value: measure,\n })\n }\n groups.sort((a, b) => compareDecimal(b.value, a.value))\n return { ...base, kind: 'grouped', groups, truncated: widget.truncated === true }\n }\n if (widget.kind !== undefined && widget.kind !== 'total') return null\n return { ...base, kind: 'total', value: decimal(widget.value) }\n}\n\nexport function normalizeDashboard(input: unknown): DashboardView {\n const dashboard = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>\n const widgets = Array.isArray(dashboard.widgets) ? dashboard.widgets : []\n return {\n name: text(dashboard.name) ?? '',\n label: text(dashboard.label) ?? '',\n description: text(dashboard.description),\n widgets: widgets\n .map(normalizeWidget)\n .filter((widget): widget is DashboardTile => widget !== null),\n }\n}\n\n/**\n * Share of the largest value, 0–100, for the proportional bars of grouped indicators. A bar\n * is a picture of proportion, so converting to Number here loses nothing visible.\n */\nexport function shares(input: (number | string)[]) {\n const values = input.map(Number)\n const max = Math.max(0, ...values)\n return values.map((value) =>\n max > 0 && value > 0 ? Math.max(2, Math.round((value / max) * 100)) : 0\n )\n}\n",
|
|
23
|
+
"target": "inertia/components/ui/dashboard_data.ts"
|
|
24
|
+
}
|
|
25
|
+
],
|
|
26
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
|
|
27
|
+
}
|