-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathApp.tsx
More file actions
560 lines (510 loc) · 23.6 KB
/
App.tsx
File metadata and controls
560 lines (510 loc) · 23.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
import { BrowserRouter, Routes, Route, Navigate, useNavigate, useLocation } from 'react-router-dom';
import { useState, useEffect, useCallback, lazy, Suspense, useMemo, type ReactNode } from 'react';
import { ModalForm } from '@object-ui/plugin-form';
import { Empty, EmptyTitle, EmptyDescription, Button } from '@object-ui/components';
import { toast } from 'sonner';
import { SchemaRendererProvider, useActionRunner, useGlobalUndo } from '@object-ui/react';
import { useObjectTranslation } from '@object-ui/i18n';
import type { ConnectionState } from './dataSource';
import { AuthGuard, useAuth, PreviewBanner } from '@object-ui/auth';
import { MetadataProvider, useMetadata } from './context/MetadataProvider';
import { AdapterProvider, useAdapter } from './context/AdapterProvider';
// Components (eagerly loaded — always needed)
import { ConsoleLayout } from './components/ConsoleLayout';
import { CommandPalette } from './components/CommandPalette';
import { ErrorBoundary } from './components/ErrorBoundary';
import { LoadingScreen } from './components/LoadingScreen';
import { ObjectView } from './components/ObjectView';
import { ExpressionProvider, evaluateVisibility } from './context/ExpressionProvider';
import { ExpressionEvaluator } from '@object-ui/core';
import { ConditionalAuthWrapper } from './components/ConditionalAuthWrapper';
import { KeyboardShortcutsDialog } from './components/KeyboardShortcutsDialog';
import { OnboardingWalkthrough } from './components/OnboardingWalkthrough';
import { useRecentItems } from './hooks/useRecentItems';
import { NavigationSyncEffect } from './hooks/useNavigationSync';
// Route-based code splitting — lazy-load less-frequently-used routes
const RecordDetailView = lazy(() => import('./components/RecordDetailView').then(m => ({ default: m.RecordDetailView })));
const DashboardView = lazy(() => import('./components/DashboardView').then(m => ({ default: m.DashboardView })));
const PageView = lazy(() => import('./components/PageView').then(m => ({ default: m.PageView })));
const ReportView = lazy(() => import('./components/ReportView').then(m => ({ default: m.ReportView })));
const SearchResultsPage = lazy(() => import('./components/SearchResultsPage').then(m => ({ default: m.SearchResultsPage })));
// App Creation / Edit Pages (lazy — only needed during app management)
const CreateAppPage = lazy(() => import('./pages/CreateAppPage').then(m => ({ default: m.CreateAppPage })));
const EditAppPage = lazy(() => import('./pages/EditAppPage').then(m => ({ default: m.EditAppPage })));
// Design Pages (lazy — only needed when editing pages/dashboards)
const PageDesignPage = lazy(() => import('./pages/PageDesignPage').then(m => ({ default: m.PageDesignPage })));
const DashboardDesignPage = lazy(() => import('./pages/DashboardDesignPage').then(m => ({ default: m.DashboardDesignPage })));
// Auth Pages (lazy — only needed before login)
const LoginPage = lazy(() => import('./pages/LoginPage').then(m => ({ default: m.LoginPage })));
const RegisterPage = lazy(() => import('./pages/RegisterPage').then(m => ({ default: m.RegisterPage })));
const ForgotPasswordPage = lazy(() => import('./pages/ForgotPasswordPage').then(m => ({ default: m.ForgotPasswordPage })));
// System Admin Pages (lazy — rarely accessed)
const SystemHubPage = lazy(() => import('./pages/system/SystemHubPage').then(m => ({ default: m.SystemHubPage })));
const AppManagementPage = lazy(() => import('./pages/system/AppManagementPage').then(m => ({ default: m.AppManagementPage })));
const ObjectManagerPage = lazy(() => import('./pages/system/ObjectManagerPage').then(m => ({ default: m.ObjectManagerPage })));
const MetadataManagerPage = lazy(() => import('./pages/system/MetadataManagerPage').then(m => ({ default: m.MetadataManagerPage })));
const UserManagementPage = lazy(() => import('./pages/system/UserManagementPage').then(m => ({ default: m.UserManagementPage })));
const OrgManagementPage = lazy(() => import('./pages/system/OrgManagementPage').then(m => ({ default: m.OrgManagementPage })));
const RoleManagementPage = lazy(() => import('./pages/system/RoleManagementPage').then(m => ({ default: m.RoleManagementPage })));
const PermissionManagementPage = lazy(() => import('./pages/system/PermissionManagementPage').then(m => ({ default: m.PermissionManagementPage })));
const AuditLogPage = lazy(() => import('./pages/system/AuditLogPage').then(m => ({ default: m.AuditLogPage })));
const ProfilePage = lazy(() => import('./pages/system/ProfilePage').then(m => ({ default: m.ProfilePage })));
// Home Page (lazy — landing page)
const HomePage = lazy(() => import('./pages/home/HomePage').then(m => ({ default: m.HomePage })));
const HomeLayout = lazy(() => import('./pages/home/HomeLayout').then(m => ({ default: m.HomeLayout })));
import { useParams } from 'react-router-dom';
import { ThemeProvider } from './components/theme-provider';
import { ConsoleToaster } from './components/ConsoleToaster';
/**
* ConnectedShell
*
* Creates the ObjectStackAdapter (via AdapterProvider), waits for connection,
* then wraps children in MetadataProvider for API-driven metadata.
*/
function ConnectedShell({ children }: { children: ReactNode }) {
return (
<AdapterProvider>
<ConnectedShellInner>{children}</ConnectedShellInner>
</AdapterProvider>
);
}
function ConnectedShellInner({ children }: { children: ReactNode }) {
const adapter = useAdapter();
if (!adapter) return <LoadingScreen />;
return (
<MetadataProvider adapter={adapter}>
{children}
</MetadataProvider>
);
}
export function AppContent() {
const [connectionState, setConnectionState] = useState<ConnectionState>('disconnected');
const { user } = useAuth();
const dataSource = useAdapter();
// App Selection
const navigate = useNavigate();
const location = useLocation();
const { appName } = useParams();
const { apps, objects: allObjects, loading: metadataLoading } = useMetadata();
const { t } = useObjectTranslation();
// Determine active app based on URL
const activeApps = apps.filter((a: any) => a.active !== false);
const activeApp = apps.find((a: any) => a.name === appName) || activeApps.find((a: any) => a.isDefault === true) || activeApps[0];
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [editingRecord, setEditingRecord] = useState<any>(null);
const [refreshKey, setRefreshKey] = useState(0);
const { addRecentItem } = useRecentItems();
// ActionRunner for CRUD dialog callbacks (Phase 2.9)
const { execute: executeAction, runner } = useActionRunner();
// Global Undo/Redo with toast notifications (Phase 16 L2)
useGlobalUndo({
dataSource: dataSource ?? undefined,
onUndo: (op: any) => {
toast.info(`Undo: ${op.description}`, {
duration: 4000,
});
setRefreshKey(k => k + 1);
},
onRedo: (op: any) => {
toast.info(`Redo: ${op.description}`, {
duration: 3000,
});
setRefreshKey(k => k + 1);
},
});
useEffect(() => {
runner.registerHandler('crud_success', async (action: any) => {
setIsDialogOpen(false);
setRefreshKey(k => k + 1);
toast.success(action.params?.message ?? 'Record saved successfully');
return { success: true, reload: true };
});
runner.registerHandler('dialog_cancel', async () => {
setIsDialogOpen(false);
return { success: true };
});
}, [runner]);
// Branding is now applied by AppShell via ConsoleLayout
useEffect(() => {
if (!dataSource) return;
const unsub = dataSource.onConnectionStateChange((event: any) => {
setConnectionState(event.state);
if (event.error) {
console.error('[Console] Connection error:', event.error);
}
});
// Sync current state
setConnectionState(dataSource.getConnectionState());
return unsub;
}, [dataSource]);
// allObjects already derived from useMetadata() above
// Find current object for Dialog
// Path is now relative to /apps/:appName/
// e.g. /apps/crm/contact -> contact is at index 3 (0=, 1=apps, 2=crm, 3=contact)
const pathParts = location.pathname.split('/');
// Filter out empty parts
const cleanParts = pathParts.filter(p => p);
// [apps, crm, contact]
let objectNameFromPath = cleanParts[2];
if (objectNameFromPath === 'view' || objectNameFromPath === 'record' || objectNameFromPath === 'page' || objectNameFromPath === 'dashboard' || objectNameFromPath === 'design') {
objectNameFromPath = ''; // Not an object root
}
const currentObjectDef = allObjects.find((o: any) => o.name === objectNameFromPath);
const handleCrudSuccess = useCallback(() => {
const label = currentObjectDef?.label || 'Record';
executeAction({
type: 'crud_success',
params: {
message: editingRecord
? `${label} updated successfully`
: `${label} created successfully`,
},
});
}, [executeAction, editingRecord, currentObjectDef?.label]);
const handleDialogCancel = useCallback(() => {
executeAction({ type: 'dialog_cancel' });
}, [executeAction]);
// Track recent items on route change
// Only depend on location.pathname — the sole external trigger.
// All other values (activeApp, allObjects, cleanParts) are derived from
// stable module-level config and the current pathname, so they don't need
// to be in the dependency array (and including array refs would loop).
useEffect(() => {
if (!activeApp) return;
const parts = location.pathname.split('/').filter(Boolean);
let objName = parts[2];
if (objName === 'view' || objName === 'record' || objName === 'page' || objName === 'dashboard' || objName === 'design') {
objName = '';
}
const basePath = `/apps/${activeApp.name}`;
const objects = allObjects;
if (objName) {
const obj = objects.find((o: any) => o.name === objName);
if (obj) {
addRecentItem({
id: `object:${obj.name}`,
label: obj.label || obj.name,
href: `${basePath}/${obj.name}`,
type: 'object',
});
}
} else if (parts[2] === 'dashboard' && parts[3]) {
addRecentItem({
id: `dashboard:${parts[3]}`,
label: parts[3].replace(/[-_]/g, ' ').replace(/\b\w/g, (c: string) => c.toUpperCase()),
href: `${basePath}/dashboard/${parts[3]}`,
type: 'dashboard',
});
} else if (parts[2] === 'report' && parts[3]) {
addRecentItem({
id: `report:${parts[3]}`,
label: parts[3].replace(/[-_]/g, ' ').replace(/\b\w/g, (c: string) => c.toUpperCase()),
href: `${basePath}/report/${parts[3]}`,
type: 'report',
});
}
}, [location.pathname, addRecentItem]); // eslint-disable-line react-hooks/exhaustive-deps
const handleEdit = (record: any) => {
setEditingRecord(record);
setIsDialogOpen(true);
};
const handleAppChange = (newAppName: string) => {
navigate(`/apps/${newAppName}`);
};
// Expression evaluator for CRUD dialog field visibility (includes editing record data)
const expressionEvaluator = useMemo(
() => new ExpressionEvaluator({
user: user ? { name: user.name, email: user.email, role: user.role ?? 'user' } : {},
app: activeApp || {},
data: editingRecord || {},
}),
[user, activeApp, editingRecord]
);
if (!dataSource || metadataLoading) return <LoadingScreen />;
// Allow create-app route even when no active app exists
const isCreateAppRoute = location.pathname.endsWith('/create-app');
// Check if we're on a system route (accessible without an active app)
const isSystemRoute = location.pathname.includes('/system');
if (!activeApp && !isCreateAppRoute && !isSystemRoute) return (
<div className="h-screen flex items-center justify-center">
<Empty>
<EmptyTitle>No Apps Configured</EmptyTitle>
<EmptyDescription>
No applications have been registered. Create your first app or visit System Settings to configure your environment.
</EmptyDescription>
<div className="mt-4 flex flex-col sm:flex-row items-center gap-3">
<Button
onClick={() => navigate('/create-app')}
data-testid="create-first-app-btn"
>
Create Your First App
</Button>
<Button
variant="outline"
onClick={() => navigate('/system')}
data-testid="go-to-settings-btn"
>
System Settings
</Button>
</div>
</Empty>
</div>
);
// When on create-app without an active app, render a minimal layout with just the wizard
if (!activeApp && (isCreateAppRoute || isSystemRoute)) {
return (
<Suspense fallback={<LoadingScreen />}>
<Routes>
<Route path="create-app" element={<CreateAppPage />} />
<Route path="system" element={<SystemHubPage />} />
<Route path="system/apps" element={<AppManagementPage />} />
<Route path="system/objects" element={<ObjectManagerPage />} />
<Route path="system/objects/:objectName" element={<ObjectManagerPage />} />
<Route path="system/users" element={<UserManagementPage />} />
<Route path="system/organizations" element={<OrgManagementPage />} />
<Route path="system/roles" element={<RoleManagementPage />} />
<Route path="system/permissions" element={<PermissionManagementPage />} />
<Route path="system/audit-log" element={<AuditLogPage />} />
<Route path="system/profile" element={<ProfilePage />} />
<Route path="system/metadata/:metadataType" element={<MetadataManagerPage />} />
</Routes>
</Suspense>
);
}
// Expression context for dynamic visibility/disabled/hidden expressions
const expressionUser = user
? { name: user.name, email: user.email, role: user.role ?? 'user' }
: { name: 'Anonymous', email: '', role: 'guest' };
return (
<ExpressionProvider user={expressionUser} app={activeApp} data={{}}>
<NavigationSyncEffect />
<ConsoleLayout
activeAppName={activeApp.name}
activeApp={activeApp}
onAppChange={handleAppChange}
objects={allObjects}
connectionState={connectionState}
>
<CommandPalette
apps={apps}
activeApp={activeApp}
objects={allObjects}
onAppChange={handleAppChange}
/>
<KeyboardShortcutsDialog />
<OnboardingWalkthrough />
<SchemaRendererProvider dataSource={dataSource || {}}>
<ErrorBoundary>
<Suspense fallback={<LoadingScreen />}>
<Routes>
<Route path="/" element={
// Redirect to first route within the app
<Navigate to={findFirstRoute(activeApp.navigation || [])} replace />
} />
{/* List View */}
<Route path=":objectName" element={
<ObjectView
dataSource={dataSource}
objects={allObjects}
onEdit={handleEdit}
/>
} />
{/* List View with specific view */}
<Route path=":objectName/view/:viewId" element={
<ObjectView
dataSource={dataSource}
objects={allObjects}
onEdit={handleEdit}
/>
} />
{/* Detail Page */}
<Route path=":objectName/record/:recordId" element={
<RecordDetailView key={refreshKey} dataSource={dataSource} objects={allObjects} onEdit={handleEdit} />
} />
<Route path="dashboard/:dashboardName" element={
<DashboardView dataSource={dataSource} />
} />
<Route path="report/:reportName" element={
<ReportView dataSource={dataSource} />
} />
<Route path="page/:pageName" element={
<PageView />
} />
<Route path="design/page/:pageName" element={
<PageDesignPage />
} />
<Route path="design/dashboard/:dashboardName" element={
<DashboardDesignPage />
} />
<Route path="search" element={
<SearchResultsPage />
} />
{/* App Creation & Editing */}
<Route path="create-app" element={<CreateAppPage />} />
<Route path="edit-app/:editAppName" element={<EditAppPage />} />
{/* System Administration Routes */}
<Route path="system" element={<SystemHubPage />} />
<Route path="system/apps" element={<AppManagementPage />} />
<Route path="system/objects" element={<ObjectManagerPage />} />
<Route path="system/objects/:objectName" element={<ObjectManagerPage />} />
<Route path="system/users" element={<UserManagementPage />} />
<Route path="system/organizations" element={<OrgManagementPage />} />
<Route path="system/roles" element={<RoleManagementPage />} />
<Route path="system/permissions" element={<PermissionManagementPage />} />
<Route path="system/audit-log" element={<AuditLogPage />} />
<Route path="system/profile" element={<ProfilePage />} />
<Route path="system/metadata/:metadataType" element={<MetadataManagerPage />} />
</Routes>
</Suspense>
</ErrorBoundary>
{currentObjectDef && (
<ModalForm
key={editingRecord?.id || 'new'}
schema={{
type: 'object-form',
formType: 'modal',
objectName: currentObjectDef.name,
mode: editingRecord ? 'edit' : 'create',
recordId: editingRecord?.id,
title: editingRecord
? t('form.editTitle', { object: currentObjectDef?.label })
: t('form.createTitle', { object: currentObjectDef?.label }),
description: editingRecord
? t('form.editDescription', { object: currentObjectDef?.label })
: t('form.createDescription', { object: currentObjectDef?.label }),
open: isDialogOpen,
onOpenChange: setIsDialogOpen,
layout: 'vertical',
fields: currentObjectDef.fields
? (Array.isArray(currentObjectDef.fields)
? currentObjectDef.fields
.filter((f: any) => {
if (typeof f === 'string') return true;
return evaluateVisibility(f.visible, expressionEvaluator);
})
.map((f: any) => typeof f === 'string' ? f : f.name)
: Object.entries(currentObjectDef.fields)
.filter(([_, f]: [string, any]) => evaluateVisibility(f.visible, expressionEvaluator))
.map(([key]: [string, any]) => key))
: [],
onSuccess: handleCrudSuccess,
onCancel: handleDialogCancel,
showSubmit: true,
showCancel: true,
submitText: t('form.saveRecord'),
cancelText: t('common.cancel'),
}}
dataSource={dataSource}
/>
)}
</SchemaRendererProvider>
</ConsoleLayout>
</ExpressionProvider>
);
}
// Helper to find first valid route in navigation tree
function findFirstRoute(items: any[]): string {
if (!items || items.length === 0) return '';
for (const item of items) {
if (item.type === 'object') return item.viewName ? `${item.objectName}/view/${item.viewName}` : `${item.objectName}`;
if (item.type === 'page') return item.pageName ? `page/${item.pageName}` : '';
if (item.type === 'dashboard') return item.dashboardName ? `dashboard/${item.dashboardName}` : '';
if (item.type === 'url') continue; // Skip external URLs
if (item.type === 'group' && item.children) {
const childRoute = findFirstRoute(item.children); // Recurse
if (childRoute !== '') return childRoute;
}
}
return '';
}
// Redirect root to home page
function RootRedirect() {
const { loading } = useMetadata();
if (loading) return <LoadingScreen />;
// Always redirect to home page
return <Navigate to="/home" replace />;
}
/**
* SystemRoutes — Top-level system admin routes accessible without any app context.
* Provides a minimal layout with system navigation sidebar.
*/
function SystemRoutes() {
return (
<Suspense fallback={<LoadingScreen />}>
<Routes>
<Route path="/" element={<SystemHubPage />} />
<Route path="apps" element={<AppManagementPage />} />
<Route path="objects" element={<ObjectManagerPage />} />
<Route path="objects/:objectName" element={<ObjectManagerPage />} />
<Route path="users" element={<UserManagementPage />} />
<Route path="organizations" element={<OrgManagementPage />} />
<Route path="roles" element={<RoleManagementPage />} />
<Route path="permissions" element={<PermissionManagementPage />} />
<Route path="audit-log" element={<AuditLogPage />} />
<Route path="profile" element={<ProfilePage />} />
<Route path="metadata/:metadataType" element={<MetadataManagerPage />} />
</Routes>
</Suspense>
);
}
export function App() {
return (
<ThemeProvider defaultTheme="system" storageKey="object-ui-theme">
<ConsoleToaster position="bottom-right" />
<ConditionalAuthWrapper authUrl="/api/v1/auth">
<PreviewBanner />
<BrowserRouter basename={import.meta.env.BASE_URL?.replace(/\/$/, '') || '/'}>
<Suspense fallback={<LoadingScreen />}>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/register" element={<RegisterPage />} />
<Route path="/forgot-password" element={<ForgotPasswordPage />} />
{/* Home Dashboard — unified workspace landing page */}
<Route path="/home" element={
<AuthGuard fallback={<Navigate to="/login" />} loadingFallback={<LoadingScreen />}>
<ConnectedShell>
<Suspense fallback={<LoadingScreen />}>
<HomeLayout>
<HomePage />
</HomeLayout>
</Suspense>
</ConnectedShell>
</AuthGuard>
} />
{/* Top-level system routes — accessible without any app */}
<Route path="/system/*" element={
<AuthGuard fallback={<Navigate to="/login" />} loadingFallback={<LoadingScreen />}>
<ConnectedShell>
<SystemRoutes />
</ConnectedShell>
</AuthGuard>
} />
{/* Top-level create-app — accessible without any app */}
<Route path="/create-app" element={
<AuthGuard fallback={<Navigate to="/login" />} loadingFallback={<LoadingScreen />}>
<ConnectedShell>
<Suspense fallback={<LoadingScreen />}>
<CreateAppPage />
</Suspense>
</ConnectedShell>
</AuthGuard>
} />
<Route path="/apps/:appName/*" element={
<AuthGuard fallback={<Navigate to="/login" />} loadingFallback={<LoadingScreen />}>
<ConnectedShell>
<AppContent />
</ConnectedShell>
</AuthGuard>
} />
<Route path="/" element={
<ConnectedShell>
<RootRedirect />
</ConnectedShell>
} />
</Routes>
</Suspense>
</BrowserRouter>
</ConditionalAuthWrapper>
</ThemeProvider>
);
}