@aventoapp/framework 0.1.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 (160) hide show
  1. package/dist/index.js +6 -0
  2. package/dist/index.js.map +7 -0
  3. package/dist/native/index.js +2522 -0
  4. package/dist/native/index.js.map +7 -0
  5. package/dist/server/index.js +2776 -0
  6. package/dist/server/index.js.map +7 -0
  7. package/dist/server/workflow/index.js +537 -0
  8. package/dist/server/workflow/index.js.map +7 -0
  9. package/dist/shared/index.js +62 -0
  10. package/dist/shared/index.js.map +7 -0
  11. package/dist/web/index.js +7323 -0
  12. package/dist/web/index.js.map +7 -0
  13. package/package.json +81 -0
  14. package/schemas/Workflow.json +14 -0
  15. package/schemas/WorkflowHistory.json +22 -0
  16. package/schemas/WorkflowInstance.json +16 -0
  17. package/schemas/WorkflowState.json +18 -0
  18. package/schemas/WorkflowTransition.json +27 -0
  19. package/src/index.js +8 -0
  20. package/src/native/components/NativeAuthProvider.jsx +249 -0
  21. package/src/native/components/NativeDetail.jsx +270 -0
  22. package/src/native/components/NativeForm.jsx +543 -0
  23. package/src/native/components/NativeGrid.jsx +90 -0
  24. package/src/native/components/NativeJsonGrid.jsx +213 -0
  25. package/src/native/components/NativeJsonView.jsx +454 -0
  26. package/src/native/components/NativeJsonViewContext.js +17 -0
  27. package/src/native/components/NativeShell.jsx +68 -0
  28. package/src/native/components/NativeViewComponent.jsx +351 -0
  29. package/src/native/extensions/NativeExtensionRegistry.js +81 -0
  30. package/src/native/hooks/useNativeStore.js +72 -0
  31. package/src/native/index.js +15 -0
  32. package/src/native/layouts/NativeStackLayout.jsx +30 -0
  33. package/src/native/layouts/NativeTabLayout.jsx +96 -0
  34. package/src/native/storage.js +13 -0
  35. package/src/native/stores/NativeBaseStore.js +348 -0
  36. package/src/native/stores/NativeStoreContext.jsx +53 -0
  37. package/src/server/ai/capabilities-routes.js +106 -0
  38. package/src/server/ai/index.js +1 -0
  39. package/src/server/cache/MemoryCache.js +153 -0
  40. package/src/server/cache/index.js +2 -0
  41. package/src/server/cache/middleware.js +12 -0
  42. package/src/server/db/index.js +14 -0
  43. package/src/server/db/mongo.js +137 -0
  44. package/src/server/db/postgres.js +144 -0
  45. package/src/server/index.js +38 -0
  46. package/src/server/middleware/auth.js +682 -0
  47. package/src/server/middleware/can-flags.js +132 -0
  48. package/src/server/middleware/entityRoles.js +105 -0
  49. package/src/server/middleware/index.js +58 -0
  50. package/src/server/middleware/permissions.js +240 -0
  51. package/src/server/middleware/tenant.js +203 -0
  52. package/src/server/realtime/EventBus.js +45 -0
  53. package/src/server/realtime/WebSocketServer.js +105 -0
  54. package/src/server/realtime/index.js +3 -0
  55. package/src/server/realtime/middleware.js +18 -0
  56. package/src/server/services/email-templates.js +157 -0
  57. package/src/server/services/email.js +78 -0
  58. package/src/server/services/index.js +15 -0
  59. package/src/server/services/storage.js +119 -0
  60. package/src/server/utils/index.js +16 -0
  61. package/src/server/utils/paginate.js +65 -0
  62. package/src/server/utils/query-builder.js +293 -0
  63. package/src/server/utils/route-loader.js +61 -0
  64. package/src/server/workflow/WorkflowEngine.js +494 -0
  65. package/src/server/workflow/index.js +2 -0
  66. package/src/server/workflow/workflow-routes.js +174 -0
  67. package/src/shared/index.js +10 -0
  68. package/src/shared/utils/field-accessor.js +108 -0
  69. package/src/shared/utils/index.js +7 -0
  70. package/src/shared/utils/validation-utils.js +83 -0
  71. package/src/web/components/AppRouter/AppRouter.jsx +130 -0
  72. package/src/web/components/AppRouter/index.js +1 -0
  73. package/src/web/components/AppShell/AppShell.jsx +101 -0
  74. package/src/web/components/AppShell/DefaultUserMenu.jsx +54 -0
  75. package/src/web/components/AppShell/ShellConfig.js +53 -0
  76. package/src/web/components/AppShell/index.js +3 -0
  77. package/src/web/components/AuthProvider.jsx +426 -0
  78. package/src/web/components/CardList/CardList.jsx +272 -0
  79. package/src/web/components/CardList/index.js +2 -0
  80. package/src/web/components/DetailView/DetailView.jsx +281 -0
  81. package/src/web/components/DetailView/index.js +2 -0
  82. package/src/web/components/Form/Form.jsx +300 -0
  83. package/src/web/components/Form/FormField.jsx +226 -0
  84. package/src/web/components/Form/index.js +3 -0
  85. package/src/web/components/Grid/Grid.jsx +304 -0
  86. package/src/web/components/Grid/index.js +2 -0
  87. package/src/web/components/IconRegistry/IconRegistry.jsx +127 -0
  88. package/src/web/components/IconRegistry/index.js +1 -0
  89. package/src/web/components/JsonView/JsonView.jsx +647 -0
  90. package/src/web/components/JsonView/ViewComponent.jsx +1045 -0
  91. package/src/web/components/JsonView/ViewToolbar.jsx +141 -0
  92. package/src/web/components/JsonView/index.js +14 -0
  93. package/src/web/components/JsonView/layouts/SingleLayout.jsx +41 -0
  94. package/src/web/components/JsonView/layouts/SplitLayout.jsx +122 -0
  95. package/src/web/components/JsonView/layouts/TabLayout.jsx +112 -0
  96. package/src/web/components/JsonView/layouts/index.js +8 -0
  97. package/src/web/components/Layout.jsx +265 -0
  98. package/src/web/components/MobileLayout/MobileLayout.jsx +385 -0
  99. package/src/web/components/MobileLayout/index.js +1 -0
  100. package/src/web/components/Navigation/Navigation.jsx +248 -0
  101. package/src/web/components/Navigation/index.js +1 -0
  102. package/src/web/components/NotificationProvider.jsx +55 -0
  103. package/src/web/components/Pagination/InfiniteScroll.jsx +82 -0
  104. package/src/web/components/Pagination/Pagination.jsx +73 -0
  105. package/src/web/components/Pagination/index.js +8 -0
  106. package/src/web/components/SimpleList/SimpleList.jsx +177 -0
  107. package/src/web/components/SimpleList/index.js +2 -0
  108. package/src/web/components/TenantProvider.jsx +121 -0
  109. package/src/web/components/WorkflowActions/WorkflowActions.jsx +71 -0
  110. package/src/web/components/WorkflowActions/index.js +1 -0
  111. package/src/web/components/WorkflowField/WorkflowField.jsx +176 -0
  112. package/src/web/components/WorkflowField/index.js +2 -0
  113. package/src/web/components/WorkflowField/workflowColors.js +32 -0
  114. package/src/web/components/auth/DevTenantSelector.jsx +90 -0
  115. package/src/web/components/auth/ForgotPasswordForm.jsx +94 -0
  116. package/src/web/components/auth/RegisterForm.jsx +168 -0
  117. package/src/web/components/auth/ResetPasswordForm.jsx +121 -0
  118. package/src/web/components/auth/VerifyEmailView.jsx +85 -0
  119. package/src/web/components/auth/index.js +5 -0
  120. package/src/web/components/index.js +39 -0
  121. package/src/web/components/layouts/CardListLayout.jsx +68 -0
  122. package/src/web/components/layouts/FullscreenLayout.jsx +30 -0
  123. package/src/web/components/layouts/MobileStackLayout.jsx +28 -0
  124. package/src/web/components/layouts/WizardLayout.jsx +86 -0
  125. package/src/web/components/layouts/index.js +4 -0
  126. package/src/web/components/mobile/Badge.jsx +105 -0
  127. package/src/web/components/mobile/BadgeThemeEditor.jsx +104 -0
  128. package/src/web/components/mobile/EmptyState.jsx +30 -0
  129. package/src/web/components/mobile/QuickActionButton.jsx +77 -0
  130. package/src/web/components/mobile/ServerAutocomplete.jsx +123 -0
  131. package/src/web/components/mobile/StarRating.jsx +42 -0
  132. package/src/web/components/mobile/StatCard.jsx +65 -0
  133. package/src/web/components/mobile/index.js +7 -0
  134. package/src/web/extensions/ExtensionRegistry.js +79 -0
  135. package/src/web/extensions/index.js +7 -0
  136. package/src/web/hooks/index.js +15 -0
  137. package/src/web/hooks/useApi.js +76 -0
  138. package/src/web/hooks/useAuth.js +37 -0
  139. package/src/web/hooks/useDebouncedSave.js +158 -0
  140. package/src/web/hooks/useIsMobile.js +14 -0
  141. package/src/web/hooks/useOfflineQueue.js +99 -0
  142. package/src/web/hooks/useSelectionModel.js +143 -0
  143. package/src/web/hooks/useServerAutocomplete.js +146 -0
  144. package/src/web/hooks/useStore.js +107 -0
  145. package/src/web/hooks/useSubscription.js +130 -0
  146. package/src/web/hooks/useTenant.js +39 -0
  147. package/src/web/hooks/useTenantResolver.js +65 -0
  148. package/src/web/hooks/useUndoRedo.js +77 -0
  149. package/src/web/hooks/useViews.js +113 -0
  150. package/src/web/hooks/useWorkflow.js +190 -0
  151. package/src/web/index.js +117 -0
  152. package/src/web/stores/BaseStore.js +439 -0
  153. package/src/web/stores/StoreContext.jsx +93 -0
  154. package/src/web/stores/index.js +3 -0
  155. package/src/web/theme/index.js +3 -0
  156. package/src/web/theme/mui-theme.js +228 -0
  157. package/src/web/utils/formatTimeAgo.js +22 -0
  158. package/src/web/utils/index.js +1 -0
  159. package/src/web/views/ViewRegistry.js +235 -0
  160. package/src/web/views/index.js +2 -0
@@ -0,0 +1,426 @@
1
+ /**
2
+ * Auth Provider Component
3
+ *
4
+ * Provides authentication context to the application.
5
+ * Handles login, logout, token management, and auth state.
6
+ */
7
+ import React, { createContext, useState, useCallback, useEffect, useMemo } from 'react';
8
+
9
+ /**
10
+ * Auth context - use useAuth hook to access
11
+ */
12
+ export const AuthContext = createContext(null);
13
+
14
+ /**
15
+ * Parse the expiry time from a JWT token
16
+ * @param {string} token - JWT token string
17
+ * @returns {number|null} Expiry time in milliseconds, or null if parsing fails
18
+ */
19
+ function parseTokenExpiry(token) {
20
+ try {
21
+ const payload = token.split('.')[1];
22
+ const decoded = JSON.parse(atob(payload));
23
+ return decoded.exp ? decoded.exp * 1000 : null;
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Return a user-friendly message for network errors thrown by fetch.
31
+ */
32
+ function friendlyErrorMessage(err) {
33
+ if (err.name === 'AbortError') {
34
+ return 'Request timed out. Check your connection and try again.';
35
+ }
36
+ if (
37
+ err instanceof TypeError &&
38
+ /Failed to fetch|Load failed|Network request failed/i.test(err.message)
39
+ ) {
40
+ return 'Unable to connect to server. Check your connection and try again.';
41
+ }
42
+ return err.message;
43
+ }
44
+
45
+ /**
46
+ * Storage keys
47
+ */
48
+ const TOKEN_KEY = 'avento_token';
49
+ const REFRESH_TOKEN_KEY = 'avento_refresh_token';
50
+ const USER_KEY = 'avento_user';
51
+
52
+ /**
53
+ * Get stored auth data from localStorage
54
+ */
55
+ function getStoredAuth() {
56
+ try {
57
+ const token = localStorage.getItem(TOKEN_KEY);
58
+ const refreshToken = localStorage.getItem(REFRESH_TOKEN_KEY);
59
+ const userJson = localStorage.getItem(USER_KEY);
60
+ const user = userJson ? JSON.parse(userJson) : null;
61
+
62
+ return { token, refreshToken, user };
63
+ } catch {
64
+ return { token: null, refreshToken: null, user: null };
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Store auth data in localStorage
70
+ */
71
+ function storeAuth(token, refreshToken, user) {
72
+ if (token) {
73
+ localStorage.setItem(TOKEN_KEY, token);
74
+ } else {
75
+ localStorage.removeItem(TOKEN_KEY);
76
+ }
77
+
78
+ if (refreshToken) {
79
+ localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken);
80
+ } else {
81
+ localStorage.removeItem(REFRESH_TOKEN_KEY);
82
+ }
83
+
84
+ if (user) {
85
+ localStorage.setItem(USER_KEY, JSON.stringify(user));
86
+ } else {
87
+ localStorage.removeItem(USER_KEY);
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Clear all stored auth data
93
+ */
94
+ function clearStoredAuth() {
95
+ localStorage.removeItem(TOKEN_KEY);
96
+ localStorage.removeItem(REFRESH_TOKEN_KEY);
97
+ localStorage.removeItem(USER_KEY);
98
+ }
99
+
100
+ /**
101
+ * Auth Provider Component
102
+ *
103
+ * @param {Object} props
104
+ * @param {React.ReactNode} props.children - Child components
105
+ * @param {string} props.apiUrl - Base API URL for auth endpoints
106
+ * @param {Function} props.onAuthChange - Callback when auth state changes
107
+ */
108
+ export function AuthProvider({ children, apiUrl = '/api', onAuthChange, refreshBeforeMs = 5 * 60 * 1000 }) {
109
+ const [user, setUser] = useState(null);
110
+ const [token, setToken] = useState(null);
111
+ const [refreshToken, setRefreshToken] = useState(null);
112
+ const [loading, setLoading] = useState(true);
113
+ const [error, setError] = useState(null);
114
+ const [sessionExpired, setSessionExpired] = useState(false);
115
+
116
+ // Initialize from localStorage on mount
117
+ useEffect(() => {
118
+ const stored = getStoredAuth();
119
+ if (stored.token && stored.user) {
120
+ setToken(stored.token);
121
+ setRefreshToken(stored.refreshToken);
122
+ setUser(stored.user);
123
+ }
124
+ setLoading(false);
125
+ }, []);
126
+
127
+ // Notify on auth changes
128
+ useEffect(() => {
129
+ if (onAuthChange && !loading) {
130
+ onAuthChange({ user, isAuthenticated: !!user });
131
+ }
132
+ }, [user, loading, onAuthChange]);
133
+
134
+ /**
135
+ * Login with email and password
136
+ */
137
+ const login = useCallback(async (email, password, tenantId) => {
138
+ setLoading(true);
139
+ setError(null);
140
+
141
+ try {
142
+ const response = await fetch(`${apiUrl}/auth/login`, {
143
+ method: 'POST',
144
+ headers: { 'Content-Type': 'application/json' },
145
+ body: JSON.stringify({ email, password, tenant_id: tenantId })
146
+ });
147
+
148
+ const data = await response.json();
149
+
150
+ if (!response.ok) {
151
+ throw new Error(data.message || 'Login failed');
152
+ }
153
+
154
+ setToken(data.token);
155
+ setRefreshToken(data.refreshToken);
156
+ setUser(data.user);
157
+ storeAuth(data.token, data.refreshToken, data.user);
158
+
159
+ return { success: true, user: data.user, tenant: data.tenant };
160
+ } catch (err) {
161
+ const msg = friendlyErrorMessage(err);
162
+ setError(msg);
163
+ return { success: false, error: msg };
164
+ } finally {
165
+ setLoading(false);
166
+ }
167
+ }, [apiUrl]);
168
+
169
+ /**
170
+ * Set auth state directly from token data (e.g. after guest-join API call)
171
+ */
172
+ const loginWithToken = useCallback((tokenData) => {
173
+ setToken(tokenData.token);
174
+ setRefreshToken(tokenData.refreshToken);
175
+ setUser(tokenData.user);
176
+ storeAuth(tokenData.token, tokenData.refreshToken, tokenData.user);
177
+ return { success: true };
178
+ }, []);
179
+
180
+ /**
181
+ * Logout - clear all auth state
182
+ */
183
+ const logout = useCallback(() => {
184
+ setToken(null);
185
+ setRefreshToken(null);
186
+ setUser(null);
187
+ setError(null);
188
+ setSessionExpired(false);
189
+ clearStoredAuth();
190
+ }, []);
191
+
192
+ /**
193
+ * Refresh the access token
194
+ */
195
+ const refresh = useCallback(async () => {
196
+ if (!refreshToken) {
197
+ return { success: false, error: 'No refresh token' };
198
+ }
199
+
200
+ try {
201
+ const response = await fetch(`${apiUrl}/auth/refresh`, {
202
+ method: 'POST',
203
+ headers: { 'Content-Type': 'application/json' },
204
+ body: JSON.stringify({ refreshToken })
205
+ });
206
+
207
+ const data = await response.json();
208
+
209
+ if (!response.ok) {
210
+ throw new Error(data.message || 'Token refresh failed');
211
+ }
212
+
213
+ setToken(data.token);
214
+ const updatedUser = data.user || user;
215
+ if (data.user) setUser(data.user);
216
+ setSessionExpired(false);
217
+ storeAuth(data.token, refreshToken, updatedUser);
218
+
219
+ return { success: true };
220
+ } catch (err) {
221
+ // If refresh fails, signal session expiry (dialog will prompt re-login)
222
+ setSessionExpired(true);
223
+ return { success: false, error: err.message };
224
+ }
225
+ }, [apiUrl, refreshToken, user, logout]);
226
+
227
+ // Auto-refresh timer: refresh the token before it expires
228
+ useEffect(() => {
229
+ if (!token) return;
230
+
231
+ const expiresAt = parseTokenExpiry(token);
232
+ if (!expiresAt) return;
233
+
234
+ const now = Date.now();
235
+ const msUntilRefresh = expiresAt - now - refreshBeforeMs;
236
+
237
+ if (msUntilRefresh <= 0) {
238
+ // Token is already expired or within the refresh window — refresh immediately
239
+ refresh();
240
+ return;
241
+ }
242
+
243
+ const timerId = setTimeout(() => {
244
+ refresh();
245
+ }, msUntilRefresh);
246
+
247
+ return () => clearTimeout(timerId);
248
+ }, [token, refreshBeforeMs, refresh]);
249
+
250
+ /**
251
+ * Register a new user
252
+ */
253
+ const register = useCallback(async (userData, tenantId) => {
254
+ setError(null);
255
+
256
+ try {
257
+ const response = await fetch(`${apiUrl}/auth/register`, {
258
+ method: 'POST',
259
+ headers: {
260
+ 'Content-Type': 'application/json',
261
+ ...(tenantId ? { 'X-Tenant-ID': tenantId } : {})
262
+ },
263
+ body: JSON.stringify(userData)
264
+ });
265
+
266
+ const data = await response.json();
267
+
268
+ if (!response.ok) {
269
+ throw new Error(data.message || 'Registration failed');
270
+ }
271
+
272
+ // If auto-login (no email verification required)
273
+ if (data.token) {
274
+ setToken(data.token);
275
+ setRefreshToken(data.refreshToken);
276
+ setUser(data.user);
277
+ storeAuth(data.token, data.refreshToken, data.user);
278
+ }
279
+
280
+ return { success: true, ...data };
281
+ } catch (err) {
282
+ const msg = friendlyErrorMessage(err);
283
+ setError(msg);
284
+ return { success: false, error: msg };
285
+ }
286
+ }, [apiUrl]);
287
+
288
+ /**
289
+ * Request a password reset email
290
+ */
291
+ const forgotPassword = useCallback(async (email, tenantId) => {
292
+ setError(null);
293
+
294
+ try {
295
+ const response = await fetch(`${apiUrl}/auth/forgot-password`, {
296
+ method: 'POST',
297
+ headers: {
298
+ 'Content-Type': 'application/json',
299
+ ...(tenantId ? { 'X-Tenant-ID': tenantId } : {})
300
+ },
301
+ body: JSON.stringify({ email })
302
+ });
303
+
304
+ const data = await response.json();
305
+
306
+ if (!response.ok) {
307
+ throw new Error(data.message || 'Request failed');
308
+ }
309
+
310
+ return { success: true, message: data.message };
311
+ } catch (err) {
312
+ const msg = friendlyErrorMessage(err);
313
+ setError(msg);
314
+ return { success: false, error: msg };
315
+ }
316
+ }, [apiUrl]);
317
+
318
+ /**
319
+ * Reset password with token
320
+ */
321
+ const resetPassword = useCallback(async (token, password) => {
322
+ setError(null);
323
+
324
+ try {
325
+ const response = await fetch(`${apiUrl}/auth/reset-password`, {
326
+ method: 'POST',
327
+ headers: { 'Content-Type': 'application/json' },
328
+ body: JSON.stringify({ token, password })
329
+ });
330
+
331
+ const data = await response.json();
332
+
333
+ if (!response.ok) {
334
+ throw new Error(data.message || 'Reset failed');
335
+ }
336
+
337
+ return { success: true, message: data.message };
338
+ } catch (err) {
339
+ const msg = friendlyErrorMessage(err);
340
+ setError(msg);
341
+ return { success: false, error: msg };
342
+ }
343
+ }, [apiUrl]);
344
+
345
+ /**
346
+ * Verify email with token
347
+ */
348
+ const verifyEmail = useCallback(async (tokenValue) => {
349
+ setError(null);
350
+
351
+ try {
352
+ const response = await fetch(`${apiUrl}/auth/verify-email`, {
353
+ method: 'POST',
354
+ headers: { 'Content-Type': 'application/json' },
355
+ body: JSON.stringify({ token: tokenValue })
356
+ });
357
+
358
+ const data = await response.json();
359
+
360
+ if (!response.ok) {
361
+ throw new Error(data.message || 'Verification failed');
362
+ }
363
+
364
+ return { success: true, message: data.message };
365
+ } catch (err) {
366
+ const msg = friendlyErrorMessage(err);
367
+ setError(msg);
368
+ return { success: false, error: msg };
369
+ }
370
+ }, [apiUrl]);
371
+
372
+ /**
373
+ * Check if user has a specific role
374
+ */
375
+ const hasRole = useCallback((role) => {
376
+ return user?.roles?.includes(role) || false;
377
+ }, [user]);
378
+
379
+ /**
380
+ * Check if user has any of the specified roles
381
+ */
382
+ const hasAnyRole = useCallback((roles) => {
383
+ if (!user?.roles) return false;
384
+ return roles.some(role => user.roles.includes(role));
385
+ }, [user]);
386
+
387
+ /**
388
+ * Get authorization header for API requests
389
+ */
390
+ const getAuthHeader = useCallback(() => {
391
+ return token ? { Authorization: `Bearer ${token}` } : {};
392
+ }, [token]);
393
+
394
+ const value = useMemo(() => ({
395
+ // State
396
+ user,
397
+ token,
398
+ isAuthenticated: !!user,
399
+ loading,
400
+ error,
401
+ sessionExpired,
402
+
403
+ // Actions
404
+ login,
405
+ loginWithToken,
406
+ logout,
407
+ refresh,
408
+ register,
409
+ forgotPassword,
410
+ resetPassword,
411
+ verifyEmail,
412
+
413
+ // Helpers
414
+ hasRole,
415
+ hasAnyRole,
416
+ getAuthHeader
417
+ }), [user, token, loading, error, sessionExpired, login, loginWithToken, logout, refresh, register, forgotPassword, resetPassword, verifyEmail, hasRole, hasAnyRole, getAuthHeader]);
418
+
419
+ return (
420
+ <AuthContext.Provider value={value}>
421
+ {children}
422
+ </AuthContext.Provider>
423
+ );
424
+ }
425
+
426
+ export default AuthProvider;
@@ -0,0 +1,272 @@
1
+ /**
2
+ * CardList Component
3
+ *
4
+ * Config-driven card-based list renderer. An alternative to Grid that presents
5
+ * rows as scannable cards — ideal for mobile and medium breakpoints.
6
+ *
7
+ * Card anatomy:
8
+ * ┌─────────────────────────────────┐
9
+ * │ [title] [badges...] │
10
+ * │ [subtitle] │
11
+ * │ [body] │
12
+ * │ [meta fields...] [actions...] │
13
+ * └─────────────────────────────────┘
14
+ *
15
+ * Config:
16
+ * entityName, entityNamePlural, rowKey
17
+ * fields: [{ field, label, placement, type, weight, color, size }]
18
+ * placement: 'title' | 'subtitle' | 'badge' | 'body' | 'meta' | 'hidden'
19
+ * actions: [{ id, label, icon, color }]
20
+ * maxWidth: card max-width (default: 700)
21
+ */
22
+ import React from 'react';
23
+ import {
24
+ Box,
25
+ Card,
26
+ CardActionArea,
27
+ CardContent,
28
+ Typography,
29
+ Chip,
30
+ IconButton,
31
+ CircularProgress,
32
+ Stack,
33
+ } from '@mui/material';
34
+ import EditIcon from '@mui/icons-material/Edit';
35
+ import DeleteIcon from '@mui/icons-material/Delete';
36
+ import VisibilityIcon from '@mui/icons-material/Visibility';
37
+ import ChevronRightIcon from '@mui/icons-material/ChevronRight';
38
+ import { getFieldValue } from '../../../shared/utils/field-accessor.js';
39
+
40
+ const ACTION_ICONS = {
41
+ edit: EditIcon,
42
+ delete: DeleteIcon,
43
+ view: VisibilityIcon,
44
+ };
45
+
46
+ /**
47
+ * Format a field value for display based on type.
48
+ */
49
+ function formatValue(value, type) {
50
+ if (value === null || value === undefined || value === '') return null;
51
+
52
+ switch (type) {
53
+ case 'date':
54
+ try { return new Date(value).toLocaleDateString(); } catch { return String(value); }
55
+ case 'datetime':
56
+ try { return new Date(value).toLocaleString(); } catch { return String(value); }
57
+ case 'boolean':
58
+ return value ? 'Yes' : 'No';
59
+ case 'decimal':
60
+ case 'number':
61
+ return typeof value === 'number' ? value.toLocaleString() : String(value);
62
+ default:
63
+ return String(value);
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Single card for one data row.
69
+ */
70
+ function DataCard({ row, config, onRowClick, onAction }) {
71
+ const {
72
+ rowKey = 'id',
73
+ fields = [],
74
+ actions = [],
75
+ maxWidth = 700,
76
+ } = config;
77
+
78
+ const rowId = row[rowKey];
79
+
80
+ // Partition fields by placement
81
+ const titleField = fields.find(f => f.placement === 'title');
82
+ const subtitleField = fields.find(f => f.placement === 'subtitle');
83
+ const bodyField = fields.find(f => f.placement === 'body');
84
+ const badgeFields = fields.filter(f => f.placement === 'badge');
85
+ const metaFields = fields.filter(f => f.placement === 'meta' || (!f.placement && f !== titleField && f !== subtitleField && f !== bodyField));
86
+
87
+ const titleValue = titleField ? formatValue(getFieldValue(row, titleField.field), titleField.type) : null;
88
+ const subtitleValue = subtitleField ? formatValue(getFieldValue(row, subtitleField.field), subtitleField.type) : null;
89
+ const bodyValue = bodyField ? formatValue(getFieldValue(row, bodyField.field), bodyField.type) : null;
90
+
91
+ const cardContent = (
92
+ <CardContent sx={{ pb: '12px !important' }}>
93
+ {/* Title row + badges */}
94
+ <Box sx={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 1 }}>
95
+ <Box sx={{ flex: 1, minWidth: 0 }}>
96
+ {titleValue && (
97
+ <Typography
98
+ variant="body1"
99
+ fontWeight={titleField?.weight || 600}
100
+ noWrap
101
+ sx={{ color: titleField?.color || 'text.primary' }}
102
+ >
103
+ {titleValue}
104
+ </Typography>
105
+ )}
106
+ {subtitleValue && (
107
+ <Typography variant="body2" color="text.secondary" noWrap>
108
+ {subtitleValue}
109
+ </Typography>
110
+ )}
111
+ </Box>
112
+
113
+ {/* Badge chips */}
114
+ {badgeFields.length > 0 && (
115
+ <Stack direction="row" spacing={0.5} sx={{ flexShrink: 0, flexWrap: 'wrap', justifyContent: 'flex-end', gap: 0.5 }}>
116
+ {badgeFields.map(f => {
117
+ const val = getFieldValue(row, f.field);
118
+ if (!val) return null;
119
+ const colorMap = f.enumConfig?.colors || f.colors || {};
120
+ const chipColor = colorMap[val] || f.color || 'default';
121
+ return (
122
+ <Chip
123
+ key={f.field}
124
+ label={formatValue(val, f.type)}
125
+ size="small"
126
+ color={chipColor}
127
+ sx={{ fontSize: '0.7rem', height: 20 }}
128
+ />
129
+ );
130
+ })}
131
+ </Stack>
132
+ )}
133
+ </Box>
134
+
135
+ {/* Body text */}
136
+ {bodyValue && (
137
+ <Typography variant="body2" color="text.secondary" sx={{ mt: 0.5, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
138
+ {bodyValue}
139
+ </Typography>
140
+ )}
141
+
142
+ {/* Meta fields row + actions */}
143
+ {(metaFields.length > 0 || actions.length > 0) && (
144
+ <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mt: 1, gap: 1 }}>
145
+ {/* Meta: label: value pairs */}
146
+ <Stack direction="row" spacing={1.5} sx={{ flexWrap: 'wrap', gap: '4px 12px' }}>
147
+ {metaFields.map(f => {
148
+ const val = getFieldValue(row, f.field);
149
+ const display = formatValue(val, f.type);
150
+ if (!display) return null;
151
+ return (
152
+ <Box key={f.field} sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
153
+ {f.label && (
154
+ <Typography variant="caption" color="text.secondary" sx={{ fontSize: '0.7rem' }}>
155
+ {f.label}:
156
+ </Typography>
157
+ )}
158
+ <Typography variant="caption" sx={{ fontSize: '0.75rem', fontWeight: f.weight || 400, color: f.color || 'text.primary' }}>
159
+ {display}
160
+ </Typography>
161
+ </Box>
162
+ );
163
+ })}
164
+ </Stack>
165
+
166
+ {/* Action buttons */}
167
+ {actions.length > 0 && (
168
+ <Stack direction="row" spacing={0.5} sx={{ flexShrink: 0 }}>
169
+ {actions.map(action => {
170
+ const Icon = ACTION_ICONS[action.id] || ChevronRightIcon;
171
+ return (
172
+ <IconButton
173
+ key={action.id}
174
+ size="small"
175
+ color={action.color || 'default'}
176
+ title={action.label}
177
+ onClick={(e) => {
178
+ e.stopPropagation();
179
+ onAction?.(action.id, row);
180
+ }}
181
+ >
182
+ <Icon fontSize="small" />
183
+ </IconButton>
184
+ );
185
+ })}
186
+ </Stack>
187
+ )}
188
+ </Box>
189
+ )}
190
+ </CardContent>
191
+ );
192
+
193
+ return (
194
+ <Card
195
+ variant="outlined"
196
+ sx={{
197
+ maxWidth,
198
+ width: '100%',
199
+ '&:hover': onRowClick ? { boxShadow: 2 } : undefined,
200
+ }}
201
+ >
202
+ {onRowClick ? (
203
+ <CardActionArea onClick={() => onRowClick(rowId, row)}>
204
+ {cardContent}
205
+ </CardActionArea>
206
+ ) : cardContent}
207
+ </Card>
208
+ );
209
+ }
210
+
211
+ /**
212
+ * CardList Component
213
+ *
214
+ * @param {Object} config - CardList configuration object
215
+ * @param {Array} data - Array of row data
216
+ * @param {boolean} loading - Whether data is loading
217
+ * @param {string} selectedId - Currently selected row ID
218
+ * @param {Function} onRowClick - Called when card is clicked (id, row)
219
+ * @param {Function} onAction - Called when action button clicked (actionId, row)
220
+ */
221
+ export function CardList({
222
+ config,
223
+ data = [],
224
+ loading = false,
225
+ selectedId,
226
+ onRowClick,
227
+ onAction,
228
+ }) {
229
+ const {
230
+ entityNamePlural = 'Items',
231
+ maxWidth = 700,
232
+ } = config || {};
233
+
234
+ if (loading && data.length === 0) {
235
+ return (
236
+ <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
237
+ <CircularProgress />
238
+ </Box>
239
+ );
240
+ }
241
+
242
+ if (!loading && data.length === 0) {
243
+ return (
244
+ <Box sx={{ textAlign: 'center', py: 4 }}>
245
+ <Typography color="text.secondary">
246
+ No {entityNamePlural.toLowerCase()} yet.
247
+ </Typography>
248
+ </Box>
249
+ );
250
+ }
251
+
252
+ return (
253
+ <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1, maxWidth, mx: 'auto', width: '100%' }}>
254
+ {data.map((row, idx) => (
255
+ <DataCard
256
+ key={row[config?.rowKey || 'id'] ?? idx}
257
+ row={row}
258
+ config={config}
259
+ onRowClick={onRowClick}
260
+ onAction={onAction}
261
+ />
262
+ ))}
263
+ {loading && data.length > 0 && (
264
+ <Box sx={{ display: 'flex', justifyContent: 'center', py: 2 }}>
265
+ <CircularProgress size={24} />
266
+ </Box>
267
+ )}
268
+ </Box>
269
+ );
270
+ }
271
+
272
+ export default CardList;
@@ -0,0 +1,2 @@
1
+ export { CardList } from './CardList.jsx';
2
+ export { default } from './CardList.jsx';