@adula/ui 2.2.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/build/attachment-preview.json +1 -1
- package/build/breadcrumb.json +18 -0
- package/build/copy-button.json +21 -0
- package/build/data-table.json +3 -2
- package/build/dialog-param.json +17 -0
- package/build/dialog.json +1 -1
- package/build/file-input.json +21 -0
- package/build/list-filters.json +2 -2
- package/build/long-dialog.json +17 -0
- package/build/manifest.json +109 -69
- package/build/messages.json +2 -2
- package/build/record-assignments.json +3 -2
- package/build/record-collaboration.json +3 -2
- package/build/record-workflows.json +3 -2
- package/build/resource-actions.json +1 -1
- package/build/resource-bulk.json +1 -1
- package/build/resource-dashboard.json +1 -1
- package/build/resource-field.json +3 -2
- package/build/resource-form.json +2 -1
- package/build/resource-import.json +3 -2
- package/build/resource-page.json +2 -1
- package/build/resource-show.json +4 -2
- package/build/resource-surface.json +2 -1
- package/build/resource-value.json +4 -3
- package/build/slider.json +17 -0
- package/build/sortable-list.json +20 -0
- package/build/tabs.json +1 -1
- package/build/theme.css +48 -2
- package/build/user-avatar.json +17 -0
- package/package.json +1 -1
|
@@ -10,7 +10,8 @@
|
|
|
10
10
|
"dialog",
|
|
11
11
|
"select",
|
|
12
12
|
"ui-preferences",
|
|
13
|
-
"resource-value"
|
|
13
|
+
"resource-value",
|
|
14
|
+
"user-avatar"
|
|
14
15
|
],
|
|
15
16
|
"dependencies": [
|
|
16
17
|
"lucide-react@1.47.0",
|
|
@@ -20,7 +21,7 @@
|
|
|
20
21
|
{
|
|
21
22
|
"path": "registry/ui/record-assignments.tsx",
|
|
22
23
|
"type": "registry:ui",
|
|
23
|
-
"content": "import { useCallback, useEffect, useState } from 'react'\nimport axios from 'axios'\nimport { ListChecks, Plus } from 'lucide-react'\nimport type { Assignment, MentionCandidate } from 'adula'\nimport { Badge } from '~/components/ui/badge'\nimport { Button } from '~/components/ui/button'\nimport { Input } from '~/components/ui/input'\nimport { Label } from '~/components/ui/label'\nimport { Textarea } from '~/components/ui/textarea'\nimport {
|
|
24
|
+
"content": "import { useCallback, useEffect, useState } from 'react'\nimport axios from 'axios'\nimport { ListChecks, Plus } from 'lucide-react'\nimport type { Assignment, MentionCandidate } 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 { 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 {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from '~/components/ui/select'\nimport { formatDate } from '~/components/ui/resource-value'\nimport { useUiPreferences } from '~/components/ui/ui-preferences'\n\nconst json = { headers: { Accept: 'application/json' }, withXSRFToken: true }\nconst statusLabel: Record<Assignment['status'], string> = {\n open: 'مفتوحة',\n done: 'منجزة',\n cancelled: 'ملغاة',\n}\n\n/** Tasks assigned on one record, with an assignment dialog for users who may update it. */\nexport function RecordAssignments({\n resource,\n id,\n canAssign,\n}: {\n resource: string\n id: number | string\n canAssign: boolean\n}) {\n const { calendar } = useUiPreferences()\n const base = `/resources/${resource}/${id}`\n const [rows, setRows] = useState<Assignment[] | null>(null)\n const [open, setOpen] = useState(false)\n const [people, setPeople] = useState<MentionCandidate[]>([])\n const [assigneeId, setAssigneeId] = useState('')\n const [title, setTitle] = useState('')\n const [note, setNote] = useState('')\n const [dueOn, setDueOn] = useState('')\n const [error, setError] = useState('')\n const [busy, setBusy] = useState(false)\n\n const load = useCallback(async () => {\n try {\n const response = await axios.get<{ data: Assignment[] }>(`${base}/assignments`, json)\n setRows(response.data.data)\n } catch {\n setRows([])\n }\n }, [base])\n useEffect(() => {\n void load()\n }, [load])\n useEffect(() => {\n if (!open) return\n // Each opening starts from an empty draft, so «إغلاق دون حفظ» really discards it.\n setAssigneeId('')\n setTitle('')\n setNote('')\n setDueOn('')\n setError('')\n axios\n .get<{ data: MentionCandidate[] }>(`${base}/mentions`, json)\n .then((response) => setPeople(response.data.data))\n .catch(() => setPeople([]))\n }, [open, base])\n\n const submit = async (event: React.FormEvent) => {\n event.preventDefault()\n setBusy(true)\n setError('')\n try {\n await axios.post(\n `${base}/assignments`,\n { assigneeId: Number(assigneeId), title, note, dueOn },\n json\n )\n setOpen(false)\n await load()\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\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 <ListChecks size={16} className=\"text-muted-foreground\" />\n <h2 className=\"text-sm font-semibold\">المهام المسندة</h2>\n {canAssign && (\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"outline\"\n className=\"ms-auto\"\n onClick={() => setOpen(true)}\n >\n <Plus size={14} />\n إسناد مهمة\n </Button>\n )}\n </div>\n {rows === null ? (\n <p role=\"status\" className=\"px-7 py-5 text-xs text-muted-foreground\">\n جارٍ تحميل المهام…\n </p>\n ) : rows.length === 0 ? (\n <p className=\"px-7 py-5 text-xs text-muted-foreground\">لا مهام على هذا السجل.</p>\n ) : (\n <ul className=\"divide-y\">\n {rows.map((row) => (\n <li\n key={row.id}\n className=\"flex flex-wrap items-center gap-x-4 gap-y-1 px-7 py-3 text-sm\"\n >\n <span className=\"font-medium\">{row.title}</span>\n <Badge variant={row.status === 'open' ? 'default' : 'secondary'}>\n {statusLabel[row.status]}\n </Badge>\n <span className=\"inline-flex items-center gap-1.5 text-xs text-muted-foreground\">\n <UserAvatar\n user={{ id: row.assigneeId, name: row.assigneeName, avatarUrl: row.assigneeAvatarUrl }}\n size=\"xs\"\n />\n المكلف: {row.assigneeName ?? `#${row.assigneeId}`}\n </span>\n {row.dueOn && (\n <span className=\"text-xs text-muted-foreground\">\n الاستحقاق <bdi className=\"tabular-nums\">{formatDate(row.dueOn, calendar)}</bdi>\n </span>\n )}\n </li>\n ))}\n </ul>\n )}\n <Dialog\n mode=\"edit\"\n open={open}\n onOpenChange={setOpen}\n value={{ assigneeId, title, note, dueOn }}\n >\n <LongDialogContent\n dir=\"rtl\"\n width=\"lg\"\n title=\"إسناد مهمة\"\n description=\"تظهر المهمة في «مهامي» لدى المكلف، ويُشعَر بها فوراً.\"\n footer={\n <>\n <DialogClose asChild>\n <Button type=\"button\" variant=\"outline\">\n إلغاء\n </Button>\n </DialogClose>\n <Button\n type=\"submit\"\n form=\"assignment-form\"\n disabled={busy || !assigneeId || !title.trim()}\n >\n إسناد\n </Button>\n </>\n }\n >\n <form\n id=\"assignment-form\"\n className=\"space-y-4\"\n onSubmit={submit}\n // Closing asks first only when a value differs from the empty draft it opened with.\n >\n <div className=\"space-y-2\">\n <Label htmlFor=\"assignment-assignee\">المكلف</Label>\n <Select value={assigneeId} onValueChange={setAssigneeId}>\n <SelectTrigger id=\"assignment-assignee\" aria-label=\"المكلف\">\n <SelectValue placeholder=\"اختر زميلاً يملك صلاحية العرض\" />\n </SelectTrigger>\n <SelectContent>\n {people.map((person) => (\n <SelectItem key={person.id} value={String(person.id)}>\n {person.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <div className=\"space-y-2\">\n <Label htmlFor=\"assignment-title\">عنوان المهمة</Label>\n <Input\n id=\"assignment-title\"\n value={title}\n maxLength={200}\n required\n onChange={(event) => setTitle(event.target.value)}\n />\n </div>\n <div className=\"space-y-2\">\n <Label htmlFor=\"assignment-due\">تاريخ الاستحقاق</Label>\n <Input\n id=\"assignment-due\"\n type=\"date\"\n value={dueOn}\n onChange={(event) => setDueOn(event.target.value)}\n />\n </div>\n <div className=\"space-y-2\">\n <Label htmlFor=\"assignment-note\">ملاحظة</Label>\n <Textarea\n id=\"assignment-note\"\n value={note}\n maxLength={2000}\n onChange={(event) => setNote(event.target.value)}\n />\n </div>\n {error && (\n <p role=\"alert\" className=\"rounded-lg bg-destructive/10 px-3 py-2 text-xs text-destructive\">\n {error}\n </p>\n )}\n </form>\n </LongDialogContent>\n </Dialog>\n </section>\n )\n}\n",
|
|
24
25
|
"target": "inertia/components/ui/record-assignments.tsx"
|
|
25
26
|
}
|
|
26
27
|
],
|
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
"tabs",
|
|
12
12
|
"ui-preferences",
|
|
13
13
|
"resource-value",
|
|
14
|
-
"messages"
|
|
14
|
+
"messages",
|
|
15
|
+
"user-avatar"
|
|
15
16
|
],
|
|
16
17
|
"dependencies": [
|
|
17
18
|
"lucide-react@1.47.0",
|
|
@@ -21,7 +22,7 @@
|
|
|
21
22
|
{
|
|
22
23
|
"path": "registry/ui/record-collaboration.tsx",
|
|
23
24
|
"type": "registry:ui",
|
|
24
|
-
"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 { 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-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",
|
|
25
26
|
"target": "inertia/components/ui/record-collaboration.tsx"
|
|
26
27
|
}
|
|
27
28
|
],
|
|
@@ -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 { 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 {\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 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-amber-300 bg-amber-50 text-amber-900' : 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-sky-300 bg-sky-50 text-sky-900\">\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 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 {behalf && (\n <p className=\"rounded-lg bg-sky-50 px-3 py-2 text-xs text-sky-900\">\n تقرر نيابة عن {behalf.name ?? 'زميل'} بموجب تفويض، ويُسجَّل القرار باسمك نيابة عنه.\n </p>\n )}\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 {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-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 {entry.onBehalfOfName && (\n <span className=\"text-sky-800\">نيابة عن {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
|
+
"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
|
],
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
{
|
|
16
16
|
"path": "registry/ui/resource-actions.tsx",
|
|
17
17
|
"type": "registry:ui",
|
|
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}\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",
|
|
19
19
|
"target": "inertia/components/ui/resource-actions.tsx"
|
|
20
20
|
}
|
|
21
21
|
],
|
package/build/resource-bulk.json
CHANGED
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
{
|
|
20
20
|
"path": "registry/ui/resource-bulk.tsx",
|
|
21
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 DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from '~/components/ui/dialog'\nimport { failureMessage } from '~/components/ui/resource-actions'\nimport { 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}\nconst builtInDescriptions: Record<string, string> = {\n delete: 'سيُحذف {count} سجل محدد ويُخفى من القوائم.',\n restore: 'سيُستعاد {count} سجل محذوف إلى السجلات النشطة.',\n submit: 'سيُعتمد {count} مستند محدد ولن يمكن تعديله بعد الاعتماد.',\n cancel: 'سيُلغى اعتماد {count} مستند محدد ولن يُحتسب.',\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/** Loads the bulk actions the actor may offer; refusals and failures mean none. */\nexport function useBulkActions(resource: string, enabled = true) {\n const [actions, setActions] = useState<BulkAction[]>([])\n useEffect(() => {\n let live = true\n if (!enabled) {\n setActions([])\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])\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], { count })\n : t('سيُنفذ الإجراء «{action}» على {count} سجل محدد.', {\n action: name(action),\n count,\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('نُفذ على {count} سجل', { count: outcome.succeeded.length }))\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=\"sm\" className=\"h-7 text-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('يمكن تنفيذ الإجراء على {count} سجل كحد أقصى في كل مرة.', {\n count: BULK_LIMIT,\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 <DialogContent className=\"sm:max-w-lg\">\n <DialogHeader>\n <DialogTitle>{pending ? name(pending) : ''}</DialogTitle>\n <DialogDescription>\n {pending ? describe(pending, ids.length) : ''}{' '}\n {!result && t('يُتحقق من صلاحيتك لكل سجل على حدة.')}\n </DialogDescription>\n </DialogHeader>\n {result && (\n <div className=\"grid gap-3\">\n {result.succeeded.length > 0 && (\n <Alert>\n <CircleCheck />\n <AlertTitle>\n {t('نُفذ على {count} سجل', {\n count: result.succeeded.length,\n })}\n </AlertTitle>\n </Alert>\n )}\n {result.failed.length > 0 && (\n <Alert variant=\"destructive\">\n <CircleAlert />\n <AlertTitle>\n {t('تعذر تنفيذ الإجراء على {count} سجل', {\n count: result.failed.length,\n })}\n </AlertTitle>\n <AlertDescription>\n <ul className=\"max-h-48 w-full space-y-1 overflow-y-auto 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 <DialogFooter>\n {result ? (\n <Button type=\"button\" onClick={close}>\n {t('إغلاق')}\n </Button>\n ) : (\n <>\n <Button type=\"button\" variant=\"outline\" disabled={busy} onClick={close}>\n {t('تراجع')}\n </Button>\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 </DialogFooter>\n </DialogContent>\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",
|
|
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
23
|
"target": "inertia/components/ui/resource-bulk.tsx"
|
|
24
24
|
}
|
|
25
25
|
],
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
{
|
|
14
14
|
"path": "registry/ui/resource-dashboard.tsx",
|
|
15
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/** 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('فتح
|
|
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
17
|
"target": "inertia/components/ui/resource-dashboard.tsx"
|
|
18
18
|
},
|
|
19
19
|
{
|