用户系统
This commit is contained in:
@@ -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>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user