@svadmin/ui 0.17.0 → 0.19.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.
Files changed (30) hide show
  1. package/package.json +20 -2
  2. package/src/components/AboutSettings.svelte +106 -0
  3. package/src/components/AdminApp.svelte +5 -1
  4. package/src/components/AppearanceSettings.svelte +183 -0
  5. package/src/components/AuditLogViewer.svelte +226 -0
  6. package/src/components/AutoTable.svelte +12 -6
  7. package/src/components/CanAccess.svelte +1 -1
  8. package/src/components/DraggableGrid.svelte +90 -0
  9. package/src/components/FieldRenderer.svelte +4 -0
  10. package/src/components/MarkdownRenderer.svelte +0 -4
  11. package/src/components/PermissionMatrix.svelte +190 -0
  12. package/src/components/ProfilePage.svelte +139 -25
  13. package/src/components/RolesSettings.svelte +144 -0
  14. package/src/components/SettingsPage.svelte +113 -0
  15. package/src/components/Sidebar.svelte +3 -0
  16. package/src/components/TaskQueueDrawer.svelte +170 -0
  17. package/src/components/TenantSwitcher.svelte +90 -0
  18. package/src/components/buttons/CloneButton.svelte +3 -3
  19. package/src/components/buttons/CreateButton.svelte +3 -3
  20. package/src/components/buttons/DeleteButton.svelte +3 -3
  21. package/src/components/buttons/EditButton.svelte +3 -3
  22. package/src/components/buttons/ExportButton.svelte +3 -3
  23. package/src/components/buttons/ImportButton.svelte +3 -3
  24. package/src/components/buttons/ShowButton.svelte +3 -3
  25. package/src/components/fields/ArrayField.svelte +86 -0
  26. package/src/index.ts +14 -0
  27. package/src/markdown-deps.d.ts +21 -0
  28. package/src/components/stories/BarChart.stories.ts +0 -43
  29. package/src/components/stories/LineChart.stories.ts +0 -48
  30. package/src/components/stories/PieChart.stories.ts +0 -41
@@ -0,0 +1,90 @@
1
+ <script lang="ts">
2
+ import type { Snippet } from 'svelte';
3
+
4
+ export interface GridModule {
5
+ id: string;
6
+ [key: string]: unknown;
7
+ }
8
+
9
+ let {
10
+ modules = $bindable<GridModule[]>([]),
11
+ onOrderSave,
12
+ renderItem,
13
+ class: className = '',
14
+ columns = 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
15
+ gap = 'gap-4',
16
+ }: {
17
+ modules?: GridModule[];
18
+ onOrderSave?: (orderedIds: string[]) => void;
19
+ renderItem: Snippet<[{ module: GridModule; index: number; dragging: boolean }]>;
20
+ class?: string;
21
+ columns?: string;
22
+ gap?: string;
23
+ } = $props();
24
+
25
+ let draggingId = $state<string | null>(null);
26
+ let dragOverId = $state<string | null>(null);
27
+
28
+ function handleDragStart(e: DragEvent, id: string) {
29
+ draggingId = id;
30
+ if (e.dataTransfer) {
31
+ e.dataTransfer.effectAllowed = 'move';
32
+ e.dataTransfer.setData('text/plain', id);
33
+ }
34
+ }
35
+
36
+ function handleDragOver(e: DragEvent, id: string) {
37
+ e.preventDefault();
38
+ if (draggingId && draggingId !== id) {
39
+ dragOverId = id;
40
+ }
41
+ }
42
+
43
+ function handleDrop(e: DragEvent, targetId: string) {
44
+ e.preventDefault();
45
+ if (!draggingId || draggingId === targetId) {
46
+ dragOverId = null;
47
+ return;
48
+ }
49
+
50
+ const sourceIdx = modules.findIndex(m => m.id === draggingId);
51
+ const targetIdx = modules.findIndex(m => m.id === targetId);
52
+
53
+ if (sourceIdx === -1 || targetIdx === -1) {
54
+ dragOverId = null;
55
+ return;
56
+ }
57
+
58
+ const newModules = [...modules];
59
+ const [dragged] = newModules.splice(sourceIdx, 1);
60
+ newModules.splice(targetIdx, 0, dragged);
61
+
62
+ modules = newModules;
63
+ dragOverId = null;
64
+ onOrderSave?.(modules.map(m => m.id));
65
+ }
66
+
67
+ function handleDragEnd() {
68
+ draggingId = null;
69
+ dragOverId = null;
70
+ }
71
+ </script>
72
+
73
+ <div class="grid {columns} {gap} {className}">
74
+ {#each modules as mod, i (mod.id)}
75
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
76
+ <div
77
+ draggable="true"
78
+ ondragstart={(e) => handleDragStart(e, mod.id)}
79
+ ondragover={(e) => handleDragOver(e, mod.id)}
80
+ ondrop={(e) => handleDrop(e, mod.id)}
81
+ ondragend={handleDragEnd}
82
+ ondragleave={() => { if (dragOverId === mod.id) dragOverId = null; }}
83
+ class="transition-all duration-200
84
+ {draggingId === mod.id ? 'opacity-40 scale-[0.97] cursor-grabbing' : 'cursor-grab'}
85
+ {dragOverId === mod.id ? 'ring-2 ring-primary/40 ring-offset-2 ring-offset-background rounded-lg scale-[1.02]' : ''}"
86
+ >
87
+ {@render renderItem({ module: mod, index: i, dragging: draggingId === mod.id })}
88
+ </div>
89
+ {/each}
90
+ </div>
@@ -15,6 +15,7 @@
15
15
  import { Button } from './ui/button/index.js';
16
16
  import TooltipButton from './TooltipButton.svelte';
17
17
  import ComboboxField from './ComboboxField.svelte';
18
+ import ArrayField from './fields/ArrayField.svelte';
18
19
  import { Plus, X } from 'lucide-svelte';
19
20
  import type { Snippet } from 'svelte';
20
21
 
@@ -86,6 +87,9 @@
86
87
  {#if children}
87
88
  {@render children()}
88
89
 
90
+ {:else if field.type === 'array'}
91
+ <ArrayField {field} {value} {onchange} />
92
+
89
93
  {:else if field.type === 'text' || field.type === 'image'}
90
94
  <Input
91
95
  id={field.key}
@@ -1,13 +1,9 @@
1
1
  <script lang="ts">
2
- // @ts-expect-error - missing types
3
2
  import { Marked } from "marked";
4
- // @ts-expect-error - missing types
5
3
  import { markedHighlight } from "marked-highlight";
6
- // @ts-expect-error - missing types
7
4
  import * as hljsModule from "highlight.js";
8
5
  const hljs = "default" in hljsModule ? hljsModule.default : hljsModule;
9
6
  import "highlight.js/styles/github-dark.css"; // or your preferred theme
10
- // @ts-expect-error - missing types
11
7
  import DOMPurify from "isomorphic-dompurify";
12
8
  import { Check, Copy } from "lucide-svelte";
13
9
  import { Button } from "./ui/button/index.js";
@@ -0,0 +1,190 @@
1
+ <script module context="module">
2
+ export type RoleInfo = { code: string; name: string; [key: string]: any };
3
+ export type ResourceInfo = { code: string; name: string; section?: string; [key: string]: any };
4
+ export type ActionInfo = { code: string; name: string; [key: string]: any };
5
+ </script>
6
+
7
+ <script lang="ts">
8
+ import { Shield, AlertCircle, Check } from 'lucide-svelte';
9
+ import type { Snippet } from 'svelte';
10
+
11
+ let {
12
+ // Basic metadata lists
13
+ roles = [],
14
+ resources = [],
15
+ actions = [],
16
+
17
+ // Authorization state resolver
18
+ // isGranted(roleCode, resourceCode, actionCode) => boolean
19
+ isGranted,
20
+
21
+ // Interactive states
22
+ selectedRole = $bindable(roles[0]?.code || ''),
23
+ loading = false,
24
+
25
+ // Feedback and alerts (passed down from upper business logic)
26
+ message = '',
27
+ messageType = 'success', // 'success' | 'error' | 'warning'
28
+ conflictCount = 0,
29
+
30
+ // Custom slots for injecting multi-tenant switchers or security filters
31
+ sidebarExtra,
32
+ headerExtra,
33
+
34
+ // Callback event
35
+ onToggle
36
+ }: {
37
+ roles: RoleInfo[];
38
+ resources: ResourceInfo[];
39
+ actions: ActionInfo[];
40
+ isGranted: (role: string, resource: string, action: string) => boolean;
41
+ selectedRole?: string;
42
+ loading?: boolean;
43
+ message?: string;
44
+ messageType?: 'success' | 'error' | 'warning';
45
+ conflictCount?: number;
46
+ sidebarExtra?: Snippet;
47
+ headerExtra?: Snippet;
48
+ onToggle: (role: string, resource: string, action: string, grant: boolean) => void;
49
+ } = $props();
50
+
51
+ </script>
52
+
53
+ <div class="h-full flex flex-col pt-2">
54
+ <!-- Header Title -->
55
+ <div class="mb-6 flex items-center justify-between">
56
+ <div>
57
+ <h1 class="text-2xl font-bold text-foreground flex items-center gap-2">
58
+ <Shield class="w-6 h-6 text-primary" />
59
+ 统一操作权限矩阵
60
+ </h1>
61
+ <p class="text-muted-foreground mt-1 text-sm">直观配置系统模块与角色的鉴权规则网络。</p>
62
+ </div>
63
+
64
+ <!-- Toast Feedback -->
65
+ {#if message}
66
+ <div class={`px-4 py-2 rounded-lg text-sm font-medium shadow-sm transition-all flex items-center gap-2 ${messageType === 'success' ? 'bg-green-500/10 text-green-600 dark:text-green-400 ring-1 ring-green-500/20' : 'bg-destructive/10 text-destructive ring-1 ring-destructive/20'}`}>
67
+ {#if messageType === 'success'}
68
+ <Check class="w-4 h-4" />
69
+ {:else}
70
+ <AlertCircle class="w-4 h-4" />
71
+ {/if}
72
+ {message}
73
+ </div>
74
+ {/if}
75
+ </div>
76
+
77
+ <div class="flex flex-col md:flex-row gap-6 flex-1 min-h-[500px]">
78
+ <!-- Left: Role Selector Sidebar -->
79
+ <div class="w-full md:w-64 flex-shrink-0 bg-card rounded-xl shadow-sm border border-border p-4 flex flex-col">
80
+ <h2 class="text-sm font-semibold text-muted-foreground uppercase tracking-wider mb-4 px-2">业务受众角色</h2>
81
+ <div class="space-y-1 flex-1 overflow-y-auto">
82
+ {#each roles as role}
83
+ <button
84
+ onclick={() => selectedRole = role.code}
85
+ class="w-full text-left px-3 py-2.5 rounded-lg text-sm transition-all duration-200 {selectedRole === role.code ? 'bg-primary/10 text-primary font-medium shadow-sm ring-1 ring-primary/20' : 'text-foreground hover:bg-muted'}"
86
+ >
87
+ {role.name}
88
+ <div class="text-[10px] mt-0.5 opacity-60 font-mono tracking-tighter">{role.code}</div>
89
+ </button>
90
+ {/each}
91
+ {#if roles.length === 0}
92
+ <p class="text-center text-muted-foreground text-sm p-4">暂无角色</p>
93
+ {/if}
94
+ </div>
95
+
96
+ <!-- Slot for Upper Logic inject (e.g. Org Switcher, Security Level Filter) -->
97
+ {#if sidebarExtra}
98
+ <div class="mt-4 pt-4 border-t border-border">
99
+ {@render sidebarExtra()}
100
+ </div>
101
+ {/if}
102
+ </div>
103
+
104
+ <!-- Right: Matrix Grid -->
105
+ <div class="flex-1 bg-card rounded-xl shadow-sm border border-border overflow-hidden flex flex-col">
106
+ <!-- Matrix Header -->
107
+ <div class="p-5 border-b border-border bg-muted/30 flex items-center justify-between">
108
+ <div class="flex items-center gap-4">
109
+ <div>
110
+ <h2 class="text-lg font-bold text-foreground">当前视角:
111
+ <span class="text-primary">{roles.find(r => r.code === selectedRole)?.name || '未选择'}</span>
112
+ </h2>
113
+ <p class="text-xs text-muted-foreground mt-1">勾选以即时挂载/收回操作权限</p>
114
+ </div>
115
+
116
+ <!-- Slot for header extra logic -->
117
+ {#if headerExtra}
118
+ {@render headerExtra()}
119
+ {/if}
120
+ </div>
121
+
122
+ {#if conflictCount > 0}
123
+ <div class="px-3 py-1.5 bg-destructive/10 text-destructive rounded-lg text-xs font-medium ring-1 ring-destructive/20 flex items-center gap-1.5">
124
+ <AlertCircle class="w-4 h-4" /> {conflictCount} 重叠/冲突规则
125
+ </div>
126
+ {/if}
127
+ </div>
128
+
129
+ <!-- Table Area -->
130
+ <div class="flex-1 overflow-auto p-4">
131
+ <table class="min-w-full divide-y divide-border border border-border rounded-lg overflow-hidden">
132
+ <thead class="bg-muted/50">
133
+ <tr>
134
+ <th scope="col" class="py-3 pr-3 pl-4 text-left text-sm font-semibold text-foreground border-r border-border w-48">模块域与资源点</th>
135
+ {#each actions as action}
136
+ <th scope="col" class="px-2 py-3 text-center text-sm font-semibold text-foreground border-r border-border">
137
+ <div class="flex flex-col items-center">
138
+ <span>{action.name}</span>
139
+ <span class="text-[10px] text-muted-foreground font-mono">{action.code}</span>
140
+ </div>
141
+ </th>
142
+ {/each}
143
+ </tr>
144
+ </thead>
145
+ <tbody class="divide-y divide-border bg-card">
146
+ {#if resources.length === 0}
147
+ <tr>
148
+ <td colspan={actions.length + 1} class="py-10 text-center text-muted-foreground">暂无可用资源</td>
149
+ </tr>
150
+ {/if}
151
+ {#each resources as resource, i}
152
+ <!-- Section Grouping Header -->
153
+ {#if resource.section && (i === 0 || resource.section !== resources[i-1].section)}
154
+ <tr class="bg-primary/5">
155
+ <td colspan="{actions.length + 1}" class="px-4 py-2 text-xs font-bold text-primary uppercase tracking-wider">{resource.section}</td>
156
+ </tr>
157
+ {/if}
158
+
159
+ <tr class="hover:bg-muted/50 transition-colors">
160
+ <td class="whitespace-nowrap py-3 pl-4 pr-3 text-sm border-r border-border">
161
+ <div class="font-medium text-foreground">{resource.name}</div>
162
+ <div class="text-xs text-muted-foreground font-mono">{resource.code}</div>
163
+ </td>
164
+
165
+ <!-- Action Checkboxes -->
166
+ {#each actions as action}
167
+ {@const granted = selectedRole ? isGranted(selectedRole, resource.code, action.code) : false}
168
+ <td class="whitespace-nowrap px-3 py-3 text-center border-r border-border">
169
+ <div class="flex items-center justify-center">
170
+ <button
171
+ disabled={loading || !selectedRole}
172
+ aria-label="Toggle {action.name}"
173
+ onclick={() => onToggle(selectedRole!, resource.code, action.code, !granted)}
174
+ class="w-6 h-6 rounded border flex items-center justify-center transition-all focus:outline-none focus:ring-2 focus:ring-primary/50 {granted ? 'bg-primary border-primary text-primary-foreground' : 'border-input bg-background hover:bg-accent'} {loading || !selectedRole ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}"
175
+ >
176
+ <svg class="w-3.5 h-3.5 {granted ? 'block' : 'hidden'}" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3">
177
+ <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
178
+ </svg>
179
+ </button>
180
+ </div>
181
+ </td>
182
+ {/each}
183
+ </tr>
184
+ {/each}
185
+ </tbody>
186
+ </table>
187
+ </div>
188
+ </div>
189
+ </div>
190
+ </div>
@@ -1,16 +1,72 @@
1
1
  <script lang="ts">
2
- import { useGetIdentity, useUpdatePassword } from '@svadmin/core';
2
+ import { useGetIdentity, useUpdatePassword, getAuthProvider } from '@svadmin/core';
3
3
  import { t } from '@svadmin/core/i18n';
4
4
  import { Button } from './ui/button/index.js';
5
5
  import { Label } from './ui/label/index.js';
6
+ import { Input } from './ui/input/index.js';
6
7
  import * as Card from './ui/card/index.js';
7
8
  import * as Alert from './ui/alert/index.js';
8
9
  import PasswordInput from './PasswordInput.svelte';
9
- import { User, Mail, Lock, Loader2, AlertCircle, CheckCircle } from 'lucide-svelte';
10
+ import { User, Mail, Lock, Loader2, AlertCircle, CheckCircle, Camera } from 'lucide-svelte';
10
11
 
11
12
  const identity = useGetIdentity();
12
13
  const updatePw = useUpdatePassword();
13
14
 
15
+ // Check if auth provider supports updateProfile
16
+ let authProvider: ReturnType<typeof getAuthProvider> | null = null;
17
+ try { authProvider = getAuthProvider(); } catch { /* no auth */ }
18
+ const canUpdateProfile = !!authProvider?.updateProfile;
19
+
20
+ // Profile edit state
21
+ let editingProfile = $state(false);
22
+ let editName = $state('');
23
+ let profileSaving = $state(false);
24
+ let profileSuccess = $state(false);
25
+ let profileError = $state('');
26
+
27
+ function startEditProfile() {
28
+ editName = identity.data?.name ?? '';
29
+ editingProfile = true;
30
+ profileSuccess = false;
31
+ profileError = '';
32
+ }
33
+
34
+ async function saveProfile() {
35
+ if (!authProvider?.updateProfile) return;
36
+ profileSaving = true;
37
+ profileError = '';
38
+ try {
39
+ const result = await authProvider.updateProfile({ name: editName });
40
+ if (result.success) {
41
+ profileSuccess = true;
42
+ editingProfile = false;
43
+ identity.refetch();
44
+ } else {
45
+ profileError = result.error?.message ?? t('common.operationFailed');
46
+ }
47
+ } catch (e) {
48
+ profileError = (e as Error).message;
49
+ } finally {
50
+ profileSaving = false;
51
+ }
52
+ }
53
+
54
+ // Avatar upload
55
+ let avatarUploading = $state(false);
56
+ let fileInput = $state<HTMLInputElement>(null!);
57
+
58
+ async function handleAvatarChange(e: Event) {
59
+ const file = (e.target as HTMLInputElement).files?.[0];
60
+ if (!file || !authProvider?.updateProfile) return;
61
+ avatarUploading = true;
62
+ try {
63
+ const result = await authProvider.updateProfile({ avatar: file });
64
+ if (result.success) identity.refetch();
65
+ } finally {
66
+ avatarUploading = false;
67
+ }
68
+ }
69
+
14
70
  // Password change form
15
71
  let currentPassword = $state('');
16
72
  let newPassword = $state('');
@@ -49,12 +105,16 @@
49
105
  );
50
106
  </script>
51
107
 
52
- <div class="max-w-2xl mx-auto space-y-6 p-4 sm:p-6">
108
+ <div class="space-y-6">
109
+ <div>
110
+ <h2 class="text-xl font-semibold text-foreground">{t('profile.title')}</h2>
111
+ </div>
112
+
53
113
  <!-- Profile Info -->
54
114
  <Card.Card>
55
115
  <Card.CardHeader>
56
- <Card.CardTitle class="flex items-center gap-2">
57
- <User class="h-5 w-5" />
116
+ <Card.CardTitle class="flex items-center gap-2 text-base">
117
+ <User class="h-4 w-4 text-muted-foreground" />
58
118
  {t('profile.title')}
59
119
  </Card.CardTitle>
60
120
  </Card.CardHeader>
@@ -65,9 +125,16 @@
65
125
  {t('common.loading')}
66
126
  </div>
67
127
  {:else if identity.data}
128
+ {#if profileSuccess}
129
+ <Alert.Root class="border-success/30 bg-success/5 text-success mb-4">
130
+ <CheckCircle class="h-4 w-4" />
131
+ <Alert.Description>{t('common.updateSuccess')}</Alert.Description>
132
+ </Alert.Root>
133
+ {/if}
134
+
68
135
  <div class="flex items-start gap-6">
69
136
  <!-- Avatar -->
70
- <div class="shrink-0">
137
+ <div class="shrink-0 relative group">
71
138
  {#if identity.data.avatar}
72
139
  <img
73
140
  src={identity.data.avatar}
@@ -79,30 +146,77 @@
79
146
  {initials}
80
147
  </div>
81
148
  {/if}
149
+ {#if canUpdateProfile}
150
+ <button
151
+ class="absolute inset-0 rounded-lg bg-black/50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer"
152
+ onclick={() => fileInput.click()}
153
+ disabled={avatarUploading}
154
+ >
155
+ {#if avatarUploading}
156
+ <Loader2 class="h-5 w-5 text-white animate-spin" />
157
+ {:else}
158
+ <Camera class="h-5 w-5 text-white" />
159
+ {/if}
160
+ </button>
161
+ <input
162
+ bind:this={fileInput}
163
+ type="file"
164
+ accept="image/*"
165
+ class="hidden"
166
+ onchange={handleAvatarChange}
167
+ />
168
+ {/if}
82
169
  </div>
83
170
 
84
171
  <!-- Info -->
85
172
  <div class="space-y-3 flex-1 min-w-0">
86
- <div>
87
- <Label class="text-xs text-muted-foreground">{t('profile.name')}</Label>
88
- <p class="text-lg font-semibold truncate">{identity.data.name ?? '—'}</p>
89
- </div>
90
-
91
- {#if identity.data.email || identity.data.username}
92
- <div class="flex items-center gap-2 text-sm text-muted-foreground">
93
- {#if identity.data.email}
94
- <Mail class="h-4 w-4 shrink-0" />
95
- {:else}
96
- <User class="h-4 w-4 shrink-0" />
173
+ {#if editingProfile}
174
+ <div class="space-y-3 max-w-sm">
175
+ <div>
176
+ <Label for="edit-name" class="text-xs text-muted-foreground">{t('profile.name')}</Label>
177
+ <Input id="edit-name" bind:value={editName} class="mt-1" />
178
+ </div>
179
+ {#if profileError}
180
+ <p class="text-xs text-destructive">{profileError}</p>
97
181
  {/if}
98
- <span class="truncate">{identity.data.email || identity.data.username}</span>
182
+ <div class="flex gap-2">
183
+ <Button size="sm" onclick={saveProfile} disabled={profileSaving}>
184
+ {#if profileSaving}<Loader2 class="h-3 w-3 animate-spin mr-1" />{/if}
185
+ {t('common.save')}
186
+ </Button>
187
+ <Button size="sm" variant="outline" onclick={() => { editingProfile = false; }}>
188
+ {t('common.cancel')}
189
+ </Button>
190
+ </div>
99
191
  </div>
100
- {/if}
101
-
102
- {#if identity.data.id}
103
- <div class="text-xs text-muted-foreground/60 font-mono">
104
- ID: {identity.data.id}
192
+ {:else}
193
+ <div>
194
+ <Label class="text-xs text-muted-foreground">{t('profile.name')}</Label>
195
+ <p class="text-lg font-semibold truncate">{identity.data.name ?? '—'}</p>
105
196
  </div>
197
+
198
+ {#if identity.data.email || identity.data.username}
199
+ <div class="flex items-center gap-2 text-sm text-muted-foreground">
200
+ {#if identity.data.email}
201
+ <Mail class="h-4 w-4 shrink-0" />
202
+ {:else}
203
+ <User class="h-4 w-4 shrink-0" />
204
+ {/if}
205
+ <span class="truncate">{identity.data.email || identity.data.username}</span>
206
+ </div>
207
+ {/if}
208
+
209
+ {#if identity.data.id}
210
+ <div class="text-xs text-muted-foreground/60 font-mono">
211
+ ID: {identity.data.id}
212
+ </div>
213
+ {/if}
214
+
215
+ {#if canUpdateProfile}
216
+ <Button size="sm" variant="outline" onclick={startEditProfile}>
217
+ {t('common.edit')}
218
+ </Button>
219
+ {/if}
106
220
  {/if}
107
221
  </div>
108
222
  </div>
@@ -115,8 +229,8 @@
115
229
  <!-- Change Password -->
116
230
  <Card.Card>
117
231
  <Card.CardHeader>
118
- <Card.CardTitle class="flex items-center gap-2">
119
- <Lock class="h-5 w-5" />
232
+ <Card.CardTitle class="flex items-center gap-2 text-base">
233
+ <Lock class="h-4 w-4 text-muted-foreground" />
120
234
  {t('profile.changePassword')}
121
235
  </Card.CardTitle>
122
236
  </Card.CardHeader>
@@ -0,0 +1,144 @@
1
+ <script lang="ts">
2
+ import { t } from '@svadmin/core/i18n';
3
+ import { getAuthProvider, getResources } from '@svadmin/core';
4
+ import type { Role } from '@svadmin/core';
5
+ import PermissionMatrix, { type RoleInfo, type ResourceInfo, type ActionInfo } from './PermissionMatrix.svelte';
6
+ import { toast } from '@svadmin/core/toast';
7
+
8
+ const authProvider = getAuthProvider();
9
+ const rawResources = getResources();
10
+
11
+ let roles = $state<RoleInfo[]>([]);
12
+ let selectedRoleCode = $state<string>('');
13
+
14
+ // Matrix format: { "roleId": { "resourceName": ["action1", "action2"] } }
15
+ let permissionsCache = $state<Record<string, Record<string, string[]>>>({});
16
+
17
+ let loadingRoles = $state(true);
18
+ let loadingPermissions = $state(false);
19
+ let saving = $state(false);
20
+ let error = $state<string | null>(null);
21
+
22
+ // Convert system resources to MatrixResource format
23
+ let matrixResources = $derived<ResourceInfo[]>(
24
+ rawResources.map(r => ({
25
+ code: r.name,
26
+ name: r.label || r.name,
27
+ }))
28
+ );
29
+
30
+ let matrixActions = $state<ActionInfo[]>([
31
+ { code: 'create', name: t('common.create') ?? 'Create' },
32
+ { code: 'read', name: t('common.detail') ?? 'Read' },
33
+ { code: 'update', name: t('common.edit') ?? 'Update' },
34
+ { code: 'delete', name: t('common.delete') ?? 'Delete' },
35
+ ]);
36
+
37
+ async function loadRoles() {
38
+ if (!authProvider?.getRoles) {
39
+ error = t('settings.rbacNotSupported') ?? 'RBAC not supported by AuthProvider';
40
+ loadingRoles = false;
41
+ return;
42
+ }
43
+ try {
44
+ const fetchedRoles = await authProvider.getRoles();
45
+ roles = fetchedRoles.map(r => ({ code: r.id, name: r.name, ...r }));
46
+ if (roles.length > 0 && !selectedRoleCode) {
47
+ selectedRoleCode = roles[0].code;
48
+ }
49
+ } catch (e) {
50
+ error = (e as Error).message;
51
+ } finally {
52
+ loadingRoles = false;
53
+ }
54
+ }
55
+
56
+ async function loadPermissionsForRole(roleId: string) {
57
+ if (!authProvider?.getRolePermissions || permissionsCache[roleId]) return;
58
+
59
+ loadingPermissions = true;
60
+ try {
61
+ const perms = await authProvider.getRolePermissions(roleId);
62
+ permissionsCache[roleId] = perms;
63
+ } catch (e) {
64
+ toast.error((e as Error).message);
65
+ } finally {
66
+ loadingPermissions = false;
67
+ }
68
+ }
69
+
70
+ // Load permissions whenever the selected role changes
71
+ $effect(() => {
72
+ if (selectedRoleCode && !permissionsCache[selectedRoleCode] && !loadingPermissions) {
73
+ loadPermissionsForRole(selectedRoleCode);
74
+ }
75
+ });
76
+
77
+ $effect(() => {
78
+ loadRoles();
79
+ });
80
+
81
+ // isGranted logic
82
+ function checkGrant(roleCode: string, resourceCode: string, actionCode: string) {
83
+ const rolePerms = permissionsCache[roleCode];
84
+ if (!rolePerms) return false;
85
+ return rolePerms[resourceCode]?.includes(actionCode) ?? false;
86
+ }
87
+
88
+ async function handleToggle(roleCode: string, resourceCode: string, actionCode: string, grant: boolean) {
89
+ if (!authProvider?.updateRolePermissions) return;
90
+
91
+ // Copy state
92
+ const currentRolePerms = { ...(permissionsCache[roleCode] || {}) };
93
+ const currentResPerms = [...(currentRolePerms[resourceCode] || [])];
94
+
95
+ // Optimistic update
96
+ if (grant) {
97
+ if (!currentResPerms.includes(actionCode)) currentResPerms.push(actionCode);
98
+ } else {
99
+ const idx = currentResPerms.indexOf(actionCode);
100
+ if (idx > -1) currentResPerms.splice(idx, 1);
101
+ }
102
+
103
+ currentRolePerms[resourceCode] = currentResPerms;
104
+ permissionsCache[roleCode] = currentRolePerms;
105
+
106
+ saving = true;
107
+ try {
108
+ // Send the entire role's permissions back (as defined by our AuthProvider interface)
109
+ const result = await authProvider.updateRolePermissions(roleCode, currentRolePerms);
110
+ if (result.success) {
111
+ // Success silently
112
+ } else {
113
+ throw new Error(result.error?.message ?? t('common.operationFailed'));
114
+ }
115
+ } catch (e) {
116
+ toast.error((e as Error).message);
117
+ // Rollback on fail
118
+ delete permissionsCache[roleCode];
119
+ loadPermissionsForRole(roleCode);
120
+ } finally {
121
+ saving = false;
122
+ }
123
+ }
124
+ </script>
125
+
126
+ {#if error}
127
+ <div class="h-full flex items-center justify-center">
128
+ <div class="max-w-md p-6 border border-destructive/20 bg-destructive/10 text-destructive rounded-lg flex flex-col items-center gap-3 text-center">
129
+ <AlertCircle class="h-8 w-8" />
130
+ <h3 class="font-bold text-lg">{t('common.error') ?? 'Error'}</h3>
131
+ <p>{error}</p>
132
+ </div>
133
+ </div>
134
+ {:else}
135
+ <PermissionMatrix
136
+ {roles}
137
+ resources={matrixResources}
138
+ actions={matrixActions}
139
+ isGranted={checkGrant}
140
+ bind:selectedRole={selectedRoleCode}
141
+ loading={loadingRoles || loadingPermissions || saving}
142
+ onToggle={handleToggle}
143
+ />
144
+ {/if}