用户系统

This commit is contained in:
2026-04-15 00:21:43 +08:00
parent 97bbb3f306
commit 47c0863bab
23 changed files with 1640 additions and 56 deletions

View File

@@ -26,7 +26,9 @@ import {
deleteAsset as storeDeleteAsset,
toggleFavorite as storeToggleFavorite,
generateId,
setStoreUserId,
} from "./store";
import { useAuth } from "./auth-context";
interface AppContextValue {
// 会话
@@ -73,6 +75,8 @@ export function useApp(): AppContextValue {
}
export function AppProvider({ children }: { children: ReactNode }) {
const { user, isAuthenticated } = useAuth();
const [sessions, setSessions] = useState<Session[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string | null>(null);
const [tags, setTags] = useState<Tag[]>([]);
@@ -85,13 +89,20 @@ export function AppProvider({ children }: { children: ReactNode }) {
});
const [initialized, setInitialized] = useState(false);
// 初始化:从 localStorage 加载
// 当用户变化时,切换 store 的 userId 并重新加载数据
useEffect(() => {
if (!isAuthenticated || !user) {
setInitialized(false);
return;
}
setStoreUserId(user.id);
setSessions(loadSessions());
setTags(loadTags());
setAssets(loadAssets());
setActiveSessionId(null);
setDetailImage(null);
setInitialized(true);
}, []);
}, [user?.id, isAuthenticated]); // eslint-disable-line react-hooks/exhaustive-deps
// 初始化后,如果没有会话则自动创建一个
useEffect(() => {
@@ -181,7 +192,6 @@ export function AppProvider({ children }: { children: ReactNode }) {
messages: [...s.messages, message],
updatedAt: Date.now(),
};
// 用首条用户消息作为自动标题
if (message.role === "user" && s.messages.length === 0) {
updated.title = message.content.slice(0, 30) + (message.content.length > 30 ? "…" : "");
}
@@ -283,7 +293,8 @@ export function AppProvider({ children }: { children: ReactNode }) {
]
);
if (!initialized) return null;
// 未登录时(如 /login 页面)直接渲染 children不注入 AppContext
if (!initialized) return <>{children}</>;
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
}