-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathApp.tsx
More file actions
380 lines (343 loc) · 12.7 KB
/
Copy pathApp.tsx
File metadata and controls
380 lines (343 loc) · 12.7 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
import React, { useState, useEffect, useRef } from 'react';
import { useBlocker, useLocation, useNavigate } from 'react-router-dom';
import { parseAppPath, pathFor, type AppView } from './app/paths';
import { doneRouteProgress, startRouteProgress } from './app/routeProgress';
import { Layout } from './components/Layout';
import { RouteProgress } from './components/RouteProgress';
import { DbSetupError, Landing } from './components/Landing';
import { ChainList } from './components/ChainList';
import { ChainEditor } from './components/ChainEditor';
import { ArtistLibrary } from './components/ArtistLibrary';
import { ArtistAdmin } from './components/ArtistAdmin';
import { InspirationGallery } from './components/InspirationGallery';
import { GenHistory } from './components/GenHistory';
import { db } from './services/dbService';
import { DEFAULT_NAI_PARAMS } from './services/naiModels';
import { PromptChain, User, Artist, Inspiration, ChainType } from './types';
import { useFeedback } from './components/ui/Feedback';
type ViewState = AppView;
const CACHE_TTL = 60 * 60 * 1000; // 1 Hour Cache
const App = () => {
const location = useLocation();
const navigate = useNavigate();
const target = parseAppPath(location.pathname);
const [ready, setReady] = useState(target);
const view = ready.view;
const selectedId = ready.id;
const prefetchGen = useRef(0);
const [chains, setChains] = useState<PromptChain[]>([]);
const [loading, setLoading] = useState(true);
const [dbConfigError, setDbConfigError] = useState(false);
// Playground State
const [playgroundChain, setPlaygroundChain] = useState<PromptChain | null>(null);
// Data Cache State
const [artistsCache, setArtistsCache] = useState<Artist[] | null>(null);
const [inspirationsCache, setInspirationsCache] = useState<Inspiration[] | null>(null);
const [usersCache, setUsersCache] = useState<User[] | null>(null);
// Cache Timestamps
const [lastChainFetch, setLastChainFetch] = useState(0);
const [lastArtistFetch, setLastArtistFetch] = useState(0);
const [lastInspirationFetch, setLastInspirationFetch] = useState(0);
const [lastUserFetch, setLastUserFetch] = useState(0);
// Dirty State for Navigation Guard
const [isEditorDirty, setIsEditorDirty] = useState(false);
// Auth State
const [currentUser, setCurrentUser] = useState<User | null>(null);
const [loginUser, setLoginUser] = useState('');
const [loginPass, setLoginPass] = useState('');
const [loginError, setLoginError] = useState('');
const [discordEnabled, setDiscordEnabled] = useState(true);
const { toast, confirm } = useFeedback();
const notify = (message: string, type: 'success' | 'error' | 'warning' | 'info' = 'success') => {
toast(message, type);
};
// Check Session on Load
useEffect(() => {
const params = new URLSearchParams(location.search);
const discordError = params.get('discord_error');
if (discordError) {
setLoginError(discordError);
navigate(location.pathname, { replace: true });
}
fetch(`/api/meta?_t=${Date.now()}`)
.then((res) => res.ok ? res.json() : null)
.then((meta) => {
if (meta && typeof meta.discordEnabled === 'boolean') setDiscordEnabled(meta.discordEnabled);
})
.catch(() => {});
db.getMe().then(user => {
setCurrentUser(user);
refreshData();
}).catch(() => {
setLoading(false);
});
}, []);
const ensurePlayground = () => {
setPlaygroundChain((prev) => prev ?? {
id: 'playground',
name: '生图实验室',
description: '临时生图实验,点击保存为串可写入列表',
userId: currentUser?.id || 'guest',
basePrompt: '',
negativePrompt: '',
modules: [],
params: { ...DEFAULT_NAI_PARAMS },
variableValues: { subject: '' },
type: 'style',
tags: [],
createdAt: Date.now(),
updatedAt: Date.now(),
});
};
const refreshData = async (force = false) => {
// Chains (Always load all chains so we can filter client side and do mutual imports)
if (!force && chains.length > 0 && Date.now() - lastChainFetch < CACHE_TTL) return;
if (chains.length === 0) setLoading(true);
try {
const data = await db.getAllChains();
setChains(data);
setLastChainFetch(Date.now());
setDbConfigError(false);
} catch (e: any) {
if (e.message && e.message.includes('Database not configured')) {
setDbConfigError(true);
}
} finally {
setLoading(false);
}
};
const loadArtists = async (force = false) => {
if (!force && artistsCache && Date.now() - lastArtistFetch < CACHE_TTL) return;
const data = await db.getAllArtists();
setArtistsCache(data.sort((a, b) => a.name.localeCompare(b.name)));
setLastArtistFetch(Date.now());
};
const loadInspirations = async (force = false) => {
if (!force && inspirationsCache && Date.now() - lastInspirationFetch < CACHE_TTL) return;
const data = await db.getAllInspirations();
setInspirationsCache(data);
setLastInspirationFetch(Date.now());
};
const loadUsers = async (force = false) => {
if (!currentUser || currentUser.role !== 'admin') return;
if (!force && usersCache && Date.now() - lastUserFetch < CACHE_TTL) return;
const data = await db.getUsers();
setUsersCache(data);
setLastUserFetch(Date.now());
};
const prefetchView = async (next: ViewState) => {
if (next === 'list' || next === 'characters' || next === 'edit') await refreshData();
if (next === 'library' || next === 'admin') await loadArtists();
if (next === 'inspiration') await loadInspirations();
if (next === 'admin' && currentUser?.role === 'admin') await loadUsers();
if (next === 'playground') ensurePlayground();
};
const handleNavigate = (newView: ViewState, id?: string) => {
navigate(pathFor(newView, id));
};
const blocker = useBlocker(Boolean(currentUser && isEditorDirty && (view === 'edit' || view === 'playground')));
useEffect(() => {
if (blocker.state !== 'blocked') return;
let cancelled = false;
confirm({
title: '确定要离开吗?',
description: '您有未保存的更改。',
confirmLabel: '离开',
cancelLabel: '继续编辑',
tone: 'danger',
}).then((ok) => {
if (cancelled) return;
if (ok) {
setIsEditorDirty(false);
blocker.proceed();
} else {
blocker.reset();
}
});
return () => { cancelled = true; };
}, [blocker.state, confirm]);
useEffect(() => {
if (!currentUser) return;
const gen = ++prefetchGen.current;
const swap = target.view !== ready.view || target.id !== ready.id;
if (swap) startRouteProgress();
prefetchView(target.view).finally(() => {
if (gen !== prefetchGen.current) return;
setReady(target);
if (swap) doneRouteProgress();
});
}, [currentUser, target.view, target.id]);
const handleUpdatePlaygroundChain = async (id: string, updates: Partial<PromptChain>) => {
setPlaygroundChain(prev => prev ? { ...prev, ...updates } : null);
};
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
setLoginError('');
try {
const res = await db.login(loginUser, loginPass);
setCurrentUser(res.user);
// 切换角色后丢弃旧列表,避免前一个账号的私人串短暂残留
setChains([]);
setLastChainFetch(0);
// Force refresh chains to apply guest_hidden/private filters based on new role
await refreshData(true);
// Guest should not stay in admin/profile view
if (res.user.role === 'guest' && (target.view === 'admin' || target.view === 'edit')) {
navigate(pathFor('list'), { replace: true });
}
} catch (err: any) {
setLoginError(err.message || '登录失败');
}
};
const handleLogout = async () => {
await db.logout();
setCurrentUser(null);
setLoginUser(''); setLoginPass('');
// Clear all cache to prevent stale data after role switch
setChains([]);
setLastChainFetch(0);
setUsersCache(null);
setInspirationsCache(null);
// Reset view to list to prevent guest from staying in admin view
navigate(pathFor('list'), { replace: true });
};
const handleCreateChain = async (name: string, desc: string, type: ChainType) => {
setLoading(true);
const newId = await db.createChain(name, desc, undefined, type);
await refreshData(true);
setLoading(false);
handleNavigate('edit', newId);
};
const handleForkChain = async (chain: PromptChain, targetType?: ChainType) => {
const finalType = targetType || chain.type;
const fromPlayground = chain.id === 'playground';
const name = fromPlayground ? chain.name : `${chain.name} (Fork)`;
await db.createChain(name, chain.description, chain, finalType); // Persist type on fork
notify(fromPlayground ? '已保存为串' : 'Fork 成功!已保存到您的列表');
await refreshData(true);
// Return to appropriate list based on type
navigate(pathFor(finalType === 'character' ? 'characters' : 'list'));
};
const handleUpdateChain = async (id: string, updates: Partial<PromptChain>) => {
await db.updateChain(id, updates);
await refreshData(true);
};
const handleDelete = async (id: string) => {
setLoading(true);
await db.deleteChain(id);
await refreshData(true);
// Stay on current list view
setLoading(false);
};
const getSelectedChain = () => chains.find(c => c.id === selectedId);
if (!currentUser) {
return (
<>
<RouteProgress />
<Landing
loginUser={loginUser}
loginPass={loginPass}
loginError={loginError}
discordEnabled={discordEnabled}
onLoginUserChange={setLoginUser}
onLoginPassChange={setLoginPass}
onSubmit={handleLogin}
/>
</>
);
}
if (dbConfigError) {
return <DbSetupError />;
}
const openChainType = (next: ChainType) => {
handleNavigate(next === 'character' ? 'characters' : 'list');
};
const renderChainList = (type: ChainType, isGuest: boolean) => (
<ChainList
chains={chains}
type={type}
onTypeChange={openChainType}
onCreate={handleCreateChain}
onSelect={(id) => handleNavigate('edit', id)}
onDelete={handleDelete}
onRefresh={() => refreshData(true)}
isLoading={loading}
notify={notify}
isGuest={isGuest}
/>
);
const renderContent = () => {
switch (view) {
case 'list':
case 'characters':
return renderChainList(view === 'characters' ? 'character' : 'style', currentUser.role === 'guest');
case 'edit':
const editChain = getSelectedChain();
if (!editChain) return <div>Chain not found</div>;
return <ChainEditor
key={editChain.id}
chain={editChain}
allChains={chains}
currentUser={currentUser}
onUpdateChain={handleUpdateChain}
onBack={() => handleNavigate(editChain.type === 'character' ? 'characters' : 'list')}
onFork={handleForkChain}
setIsDirty={setIsEditorDirty}
notify={notify}
/>;
case 'library':
return <ArtistLibrary
artistsData={artistsCache}
onRefresh={() => loadArtists(true)}
notify={notify}
currentUser={currentUser}
/>;
case 'inspiration':
return <InspirationGallery
currentUser={currentUser}
inspirationsData={inspirationsCache}
onRefresh={() => loadInspirations(true)}
notify={notify}
onNavigateToPlayground={() => handleNavigate('playground')}
/>;
case 'admin':
return <ArtistAdmin
currentUser={currentUser}
artistsData={artistsCache}
usersData={usersCache}
onRefreshArtists={() => loadArtists(true)}
onRefreshUsers={() => loadUsers(true)}
/>;
case 'history':
return <GenHistory currentUser={currentUser} notify={notify} onNavigateToPlayground={() => handleNavigate('playground')} onRefreshInspiration={() => loadInspirations(true)} />;
case 'playground':
if (!playgroundChain) return <div>Loading...</div>;
return <ChainEditor
key={playgroundChain.id}
chain={playgroundChain}
allChains={chains}
currentUser={currentUser}
onUpdateChain={handleUpdatePlaygroundChain}
onBack={() => handleNavigate('list')}
onFork={handleForkChain}
setIsDirty={() => { }}
notify={notify}
/>;
default:
return <div>Unknown View</div>;
}
};
return (
<>
<RouteProgress />
<Layout
currentView={view}
currentUser={currentUser}
onLogout={handleLogout}
>
{renderContent()}
</Layout>
</>
);
};
export default App;