feat: integrate learning module
This commit is contained in:
173
src/components/layout/LearningSidebar.tsx
Normal file
173
src/components/layout/LearningSidebar.tsx
Normal file
@@ -0,0 +1,173 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { BookOpen, Download, Loader2, Plus, Sparkles } from 'lucide-react';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
downloadLearningCourse,
|
||||
fetchMyLearningCourses,
|
||||
LEARNING_LIBRARY_CHANGED_EVENT,
|
||||
listInstalledLearningCourses,
|
||||
} from '@/lib/learning';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { InstalledLearningCourse, LearningCourse } from '../../../shared/learning';
|
||||
|
||||
type LearningSidebarProps = {
|
||||
sidebarCollapsed: boolean;
|
||||
};
|
||||
|
||||
export function LearningSidebar({ sidebarCollapsed }: LearningSidebarProps) {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const [installed, setInstalled] = useState<Record<string, InstalledLearningCourse>>({});
|
||||
const [ownedCourses, setOwnedCourses] = useState<LearningCourse[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [downloading, setDownloading] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const loadCourses = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const [localCourses, personalCourses] = await Promise.all([
|
||||
listInstalledLearningCourses(),
|
||||
fetchMyLearningCourses().catch(() => []),
|
||||
]);
|
||||
setInstalled(Object.fromEntries(localCourses.map((record) => [record.course.id, record])));
|
||||
setOwnedCourses(personalCourses);
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '个人课程暂时无法读取');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void loadCourses();
|
||||
const refresh = () => void loadCourses();
|
||||
window.addEventListener(LEARNING_LIBRARY_CHANGED_EVENT, refresh);
|
||||
return () => window.removeEventListener(LEARNING_LIBRARY_CHANGED_EVENT, refresh);
|
||||
}, [loadCourses]);
|
||||
|
||||
const personalCourses = (() => {
|
||||
const courses = new Map<string, LearningCourse>();
|
||||
for (const record of Object.values(installed)) courses.set(record.course.id, record.course);
|
||||
for (const course of ownedCourses) courses.set(course.id, course);
|
||||
return [...courses.values()];
|
||||
})();
|
||||
|
||||
const openCourse = useCallback(async (course: LearningCourse) => {
|
||||
if (installed[course.id]) {
|
||||
navigate(`/learning/course/${encodeURIComponent(course.id)}`);
|
||||
return;
|
||||
}
|
||||
setDownloading(course.id);
|
||||
setError(null);
|
||||
try {
|
||||
const record = await downloadLearningCourse(course.id);
|
||||
setInstalled((current) => ({ ...current, [course.id]: record }));
|
||||
navigate(`/learning/course/${encodeURIComponent(course.id)}`);
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '课程下载失败');
|
||||
} finally {
|
||||
setDownloading(null);
|
||||
}
|
||||
}, [installed, navigate]);
|
||||
|
||||
const catalogActive = location.pathname === '/learning';
|
||||
|
||||
return (
|
||||
<div data-testid="sidebar-learning-navigation" className="px-1 py-1">
|
||||
<button
|
||||
type="button"
|
||||
aria-label="课程广场"
|
||||
aria-current={catalogActive ? 'page' : undefined}
|
||||
onClick={() => navigate('/learning')}
|
||||
className={cn(
|
||||
'motion-press flex min-h-9 w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm font-semibold transition-colors active:scale-[0.985]',
|
||||
catalogActive ? 'bg-brand-soft text-foreground' : 'text-foreground hover:bg-surface-subtle',
|
||||
sidebarCollapsed && 'justify-center px-0',
|
||||
)}
|
||||
>
|
||||
<BookOpen className="h-4 w-4 shrink-0 text-brand" />
|
||||
{!sidebarCollapsed ? <span>课程广场</span> : null}
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
aria-label="生成课程"
|
||||
onClick={() => navigate('/learning?generate=1')}
|
||||
className={cn(
|
||||
'motion-press mt-1 flex min-h-9 w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm font-medium text-foreground transition-colors hover:bg-surface-subtle active:scale-[0.985]',
|
||||
sidebarCollapsed && 'justify-center px-0',
|
||||
)}
|
||||
>
|
||||
<Plus className="h-4 w-4 shrink-0 text-brand" />
|
||||
{!sidebarCollapsed ? <span>生成课程</span> : null}
|
||||
</button>
|
||||
|
||||
{!sidebarCollapsed ? (
|
||||
<div className="mt-4">
|
||||
<div className="flex min-h-8 items-center gap-2 px-2 text-xs font-semibold text-muted-foreground">
|
||||
<Sparkles className="h-4 w-4 shrink-0" />
|
||||
<span className="min-w-0 flex-1 truncate">我的课程</span>
|
||||
{!loading ? <span className="tabular-nums">{personalCourses.length}</span> : null}
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div role="status" className="flex items-center px-2 py-3 text-xs font-medium text-muted-foreground">
|
||||
<Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />正在读取课程
|
||||
</div>
|
||||
) : error ? (
|
||||
<button
|
||||
type="button"
|
||||
className="w-full rounded-lg px-2 py-3 text-left text-xs font-medium leading-5 text-destructive hover:bg-destructive/5"
|
||||
onClick={() => void loadCourses()}
|
||||
>
|
||||
{error},点击重试
|
||||
</button>
|
||||
) : personalCourses.length === 0 ? (
|
||||
<p className="px-2 py-3 text-xs font-medium leading-5 text-muted-foreground">
|
||||
下载或生成课程后,会显示在这里。
|
||||
</p>
|
||||
) : (
|
||||
<div className="mt-1 space-y-1">
|
||||
{personalCourses.map((course) => {
|
||||
const isInstalled = Boolean(installed[course.id]);
|
||||
const isActive = location.pathname === `/learning/course/${encodeURIComponent(course.id)}`;
|
||||
const courseMeta = course.origin === 'user_single'
|
||||
? isInstalled ? '我生成的,已下载' : '我生成的,待下载'
|
||||
: '已下载到本机';
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={course.id}
|
||||
aria-label={`${isInstalled ? '打开' : '下载'}课程 ${course.title}`}
|
||||
aria-current={isActive ? 'page' : undefined}
|
||||
disabled={downloading === course.id}
|
||||
onClick={() => void openCourse(course)}
|
||||
className={cn(
|
||||
'motion-press group/course flex w-full items-center gap-2 rounded-xl px-2.5 py-2 text-left transition-[background-color,color,transform] active:scale-[0.985]',
|
||||
isActive ? 'bg-brand-selected text-foreground ring-1 ring-brand/20' : 'hover:bg-surface-tertiary',
|
||||
)}
|
||||
>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm font-semibold text-foreground">{course.title}</span>
|
||||
<span className="mt-0.5 block truncate text-[11px] font-medium text-muted-foreground">{courseMeta}</span>
|
||||
</span>
|
||||
{downloading === course.id ? (
|
||||
<Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin text-brand" />
|
||||
) : isInstalled ? (
|
||||
<BookOpen className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
|
||||
) : (
|
||||
<Download className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -35,6 +35,7 @@ export function MainLayout() {
|
||||
const activeModule = getAiModuleForPath(location.pathname);
|
||||
const isProgrammingModule = activeModule === 'programming';
|
||||
const isPaintingModule = activeModule === 'painting';
|
||||
const isLearningPlayer = location.pathname.startsWith('/learning/course/');
|
||||
const isPromptMuseum = location.pathname === '/image-prompts' || location.pathname.startsWith('/image-prompts/');
|
||||
const isChatWorkspace = location.pathname === '/opencode-chat';
|
||||
const isInitializationSafeRoute = location.pathname === '/project-config' || !isProgrammingModule;
|
||||
@@ -91,7 +92,7 @@ export function MainLayout() {
|
||||
<div data-testid="main-layout" className="relative flex h-[100dvh] flex-col overflow-hidden bg-transparent font-sans">
|
||||
{/* Title bar: drag region on macOS, icon + controls on Windows */}
|
||||
<TitleBar
|
||||
integrated
|
||||
integrated={!isLearningPlayer}
|
||||
workspaceLayout={isChatWorkspace}
|
||||
overlay={isPaintingModule && !isPromptMuseum}
|
||||
pageTitle={isPromptMuseum ? '获取灵感' : undefined}
|
||||
@@ -101,16 +102,18 @@ export function MainLayout() {
|
||||
|
||||
{/* Below the title bar: sidebar + content */}
|
||||
<div className="relative flex min-h-0 flex-1 overflow-hidden">
|
||||
<Sidebar
|
||||
workspaceLayout={isChatWorkspace}
|
||||
sidebarPeekOpen={sidebarPeekOpen}
|
||||
onSidebarPeekChange={handleSidebarPeekChange}
|
||||
/>
|
||||
{!isLearningPlayer ? (
|
||||
<Sidebar
|
||||
workspaceLayout={isChatWorkspace}
|
||||
sidebarPeekOpen={sidebarPeekOpen}
|
||||
onSidebarPeekChange={handleSidebarPeekChange}
|
||||
/>
|
||||
) : null}
|
||||
<main
|
||||
data-testid="main-content"
|
||||
className={cn(
|
||||
'relative min-h-0 min-w-0 flex-1 overflow-auto bg-background',
|
||||
isPaintingModule ? 'basis-0 h-full overflow-hidden p-0' : 'p-5 sm:p-6',
|
||||
isPaintingModule || isLearningPlayer ? 'basis-0 h-full overflow-hidden p-0' : 'p-5 sm:p-6',
|
||||
isChatWorkspace && !isPaintingModule && 'basis-0 overflow-hidden p-0',
|
||||
)}
|
||||
>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
@@ -12,39 +12,36 @@ import {
|
||||
LogOut,
|
||||
Plus,
|
||||
Settings as SettingsIcon,
|
||||
Trash2,
|
||||
Upload,
|
||||
UserCircle2,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { DisclosureContent } from '@/components/ui/disclosure';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { getAgentAvatarSrc } from '@/lib/agent-avatars';
|
||||
import { AgentProfileApiError, deleteAgentAvatar, getAgentProfileApiErrorMessage, uploadAgentAvatar } from '@/lib/agent-profile';
|
||||
import { getAiModuleForPath } from '@/lib/ai-modules';
|
||||
import { invokeIpc } from '@/lib/api-client';
|
||||
import { getAuthUserDisplayName } from '@/lib/auth-user-display';
|
||||
import { prepareUserAvatar, type PreparedUserAvatar } from '@/lib/user-avatar';
|
||||
import { WORKS_SQUARE_TOKEN_USAGE_STALE_EVENT } from '@/lib/works-square-usage-events';
|
||||
import { fetchWorksTokenUsage, type WorksTokenUsage } from '@/lib/works-square';
|
||||
import { isWorksTokenUsageExhausted } from '@/lib/works-square-token-usage';
|
||||
import { openWorksSquareSubscriptionUpgrade } from '@/lib/subscription-upgrade';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useCurrentUserProfile } from '@/hooks/use-current-user-profile';
|
||||
import type { SidebarPeekSource } from './sidebar-peek';
|
||||
import { ModuleSwitcher } from './ModuleSwitcher';
|
||||
import { ImageWorkspaceSidebar } from './ImageWorkspaceSidebar';
|
||||
import { LearningSidebar } from './LearningSidebar';
|
||||
import { SidebarUpdateButton } from './SidebarUpdateButton';
|
||||
import { UserAvatar } from '@/components/profile/UserAvatar';
|
||||
import { getAccountInitial } from '@/components/profile/user-avatar-utils';
|
||||
import { UserProfileDialog } from '@/components/profile/UserProfileDialog';
|
||||
import { useSettingsStore } from '@/stores/settings';
|
||||
import { useAuthStore, type AuthUser } from '@/stores/auth';
|
||||
import { useOpencodeStore, type ProjectDirectoryMode } from '@/stores/opencode';
|
||||
import { useProviderStore } from '@/stores/providers';
|
||||
import type { OpencodeProject } from '@/types/opencode';
|
||||
import { useProjectConfigStore } from '@/stores/project-config';
|
||||
import { EMPTY_AGENT_USER_PROFILE, getProfileAccountKey, isUserProfileComplete, useUserProfileStore, type UserGender } from '@/stores/user-profile';
|
||||
import type { ProjectType } from '../../../shared/project-config';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
@@ -64,40 +61,6 @@ type ProjectEntryError = {
|
||||
message: string;
|
||||
};
|
||||
|
||||
type ProfileAvatarDraft =
|
||||
| { kind: 'unchanged' }
|
||||
| { kind: 'upload'; value: PreparedUserAvatar }
|
||||
| { kind: 'remove' };
|
||||
|
||||
type UserAvatarProps = {
|
||||
src: string | null | undefined;
|
||||
initial: string;
|
||||
className: string;
|
||||
alt?: string;
|
||||
testId?: string;
|
||||
};
|
||||
|
||||
function UserAvatar({ src, initial, className, alt = '', testId }: UserAvatarProps) {
|
||||
const [failedSrc, setFailedSrc] = useState<string | null>(null);
|
||||
const imageAvailable = Boolean(src && failedSrc !== src);
|
||||
|
||||
return (
|
||||
<span data-testid={testId} className={cn('flex items-center justify-center overflow-hidden rounded-full bg-accent-soft text-xs font-semibold text-foreground', className)}>
|
||||
{imageAvailable ? (
|
||||
<img src={src ?? undefined} alt={alt} className="h-full w-full object-cover" onError={() => setFailedSrc(src ?? null)} />
|
||||
) : (
|
||||
initial
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
function getAccountInitial(name: string): string {
|
||||
const first = name.trim().charAt(0);
|
||||
return first ? first.toUpperCase() : 'M';
|
||||
}
|
||||
|
||||
function getFolderName(pathValue: string): string {
|
||||
const trimmed = pathValue.trim();
|
||||
const withoutTrailingSeparators = trimmed.replace(/[\\/]+$/u, '');
|
||||
@@ -175,23 +138,16 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
|
||||
const authUser = useAuthStore((state) => state.user);
|
||||
const getValidAccessToken = useAuthStore((state) => state.getValidAccessToken);
|
||||
const logout = useAuthStore((state) => state.logout);
|
||||
const profilesByUserId = useUserProfileStore((state) => state.profilesByUserId);
|
||||
const syncStatesByUserId = useUserProfileStore((state) => state.syncStatesByUserId);
|
||||
const saveUserProfile = useUserProfileStore((state) => state.saveProfile);
|
||||
const setUserAvatarUrl = useUserProfileStore((state) => state.setAvatarUrl);
|
||||
const syncUserProfile = useUserProfileStore((state) => state.syncProfile);
|
||||
const saveUserProfileToServer = useUserProfileStore((state) => state.saveProfileToServer);
|
||||
const {
|
||||
userProfile,
|
||||
profileRequired,
|
||||
profileSyncError,
|
||||
syncProfileNow,
|
||||
} = useCurrentUserProfile();
|
||||
const refreshProviderSnapshot = useProviderStore((state) => state.refreshProviderSnapshot);
|
||||
const [projectsOpen, setProjectsOpen] = useState(true);
|
||||
const [accountMenuOpen, setAccountMenuOpen] = useState(false);
|
||||
const [profileDialogOpen, setProfileDialogOpen] = useState(false);
|
||||
const [profileName, setProfileName] = useState('');
|
||||
const [profileAge, setProfileAge] = useState('');
|
||||
const [profileGender, setProfileGender] = useState<UserGender>('undisclosed');
|
||||
const [profileAvatarDraft, setProfileAvatarDraft] = useState<ProfileAvatarDraft>({ kind: 'unchanged' });
|
||||
const [profileAvatarProcessing, setProfileAvatarProcessing] = useState(false);
|
||||
const [profileError, setProfileError] = useState<string | null>(null);
|
||||
const [profileSaving, setProfileSaving] = useState(false);
|
||||
const [usageDrawerOpen, setUsageDrawerOpen] = useState(false);
|
||||
const [tokenUsageState, setTokenUsageState] = useState<TokenUsageState>({ status: 'idle', usage: null });
|
||||
const [createDialogOpen, setCreateDialogOpen] = useState(false);
|
||||
@@ -205,34 +161,21 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
|
||||
const [removeProjectCandidate, setRemoveProjectCandidate] = useState<OpencodeProject | null>(null);
|
||||
const accountButtonRef = useRef<HTMLButtonElement | null>(null);
|
||||
const accountMenuRef = useRef<HTMLDivElement | null>(null);
|
||||
const profileDialogDirtyRef = useRef(false);
|
||||
const tokenUsageRequestIdRef = useRef(0);
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const activeModule = getAiModuleForPath(location.pathname);
|
||||
const isProgrammingModule = activeModule === 'programming';
|
||||
const isPaintingModule = activeModule === 'painting';
|
||||
const isLearningModule = activeModule === 'learning';
|
||||
const isPromptMuseum = location.pathname === '/image-prompts' || location.pathname.startsWith('/image-prompts/');
|
||||
const projectConfigPath = '/project-config';
|
||||
const visibleProjects = opencodeProjects;
|
||||
const selectedProjectFolderName = getFolderName(newProjectSelectedPath);
|
||||
const accountName = getAuthUserDisplayName(authUser) || '未登录用户';
|
||||
const profileAccountKey = getProfileAccountKey(authUser?.userId ?? authUser?.username);
|
||||
const userProfile = profileAccountKey ? profilesByUserId[profileAccountKey] : undefined;
|
||||
const profileSyncState = profileAccountKey ? syncStatesByUserId[profileAccountKey] : undefined;
|
||||
const profileRequired = Boolean(
|
||||
authUser
|
||||
&& profileSyncState?.status === 'ready'
|
||||
&& !isUserProfileComplete(userProfile),
|
||||
);
|
||||
const accountFullName = authUser?.username?.trim() || accountName;
|
||||
const accountName = userProfile?.displayName?.trim() || getAuthUserDisplayName(authUser) || '未登录用户';
|
||||
const accountFullName = accountName;
|
||||
const accountInitial = getAccountInitial(accountName);
|
||||
const accountAvatarUrl = userProfile?.avatarUrl ?? null;
|
||||
const profileAvatarPreviewUrl = profileAvatarDraft.kind === 'upload'
|
||||
? profileAvatarDraft.value.previewUrl
|
||||
: profileAvatarDraft.kind === 'remove'
|
||||
? null
|
||||
: accountAvatarUrl;
|
||||
const settingsLabel = t('sidebar.settings', '设置');
|
||||
const memberLabel = getSubscriptionPlanLabel(authUser, tokenUsageState);
|
||||
const membershipLabel = getSubscriptionMembershipLabel(authUser, tokenUsageState);
|
||||
@@ -258,109 +201,8 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
|
||||
}, [isProgrammingModule, refreshProviderSnapshot]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!authUser || !profileAccountKey) return;
|
||||
let cancelled = false;
|
||||
void getValidAccessToken()
|
||||
.then((accessToken) => {
|
||||
if (!accessToken) throw new Error('登录已过期,请重新登录后再同步个人资料。');
|
||||
return syncUserProfile(profileAccountKey, accessToken);
|
||||
})
|
||||
.catch((error) => {
|
||||
if (cancelled) return;
|
||||
setProfileError(error instanceof Error ? error.message : String(error));
|
||||
setProfileDialogOpen(true);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [authUser, getValidAccessToken, profileAccountKey, syncUserProfile]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!profileRequired) return;
|
||||
profileDialogDirtyRef.current = false;
|
||||
setProfileError(null);
|
||||
setProfileDialogOpen(true);
|
||||
}, [profileRequired]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!profileDialogOpen) {
|
||||
profileDialogDirtyRef.current = false;
|
||||
return;
|
||||
}
|
||||
if (profileDialogDirtyRef.current) return;
|
||||
const profile = userProfile ?? EMPTY_AGENT_USER_PROFILE;
|
||||
setProfileName(profile.displayName);
|
||||
setProfileAge(profile.age === null ? '' : String(profile.age));
|
||||
setProfileGender(profile.gender);
|
||||
setProfileAvatarDraft({ kind: 'unchanged' });
|
||||
}, [profileDialogOpen, userProfile]);
|
||||
|
||||
const handleAvatarFileChange = async (event: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
event.target.value = '';
|
||||
if (!file) return;
|
||||
|
||||
profileDialogDirtyRef.current = true;
|
||||
setProfileAvatarProcessing(true);
|
||||
setProfileError(null);
|
||||
try {
|
||||
const prepared = await prepareUserAvatar(file);
|
||||
setProfileAvatarDraft({ kind: 'upload', value: prepared });
|
||||
} catch (error) {
|
||||
setProfileError(error instanceof Error ? error.message : '头像图片处理失败');
|
||||
} finally {
|
||||
setProfileAvatarProcessing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveAvatar = () => {
|
||||
profileDialogDirtyRef.current = true;
|
||||
setProfileAvatarDraft({ kind: 'remove' });
|
||||
setProfileError(null);
|
||||
};
|
||||
|
||||
const handleSaveProfile = async () => {
|
||||
if (!profileAccountKey) return;
|
||||
const displayName = profileName.trim();
|
||||
if (!displayName) { setProfileError('请填写名字'); return; }
|
||||
const age = profileAge.trim() ? Number(profileAge) : null;
|
||||
if (age !== null && (!Number.isInteger(age) || age < 1 || age > 150)) { setProfileError('年龄请输入 1 至 150 的整数'); return; }
|
||||
setProfileError(null);
|
||||
setProfileSaving(true);
|
||||
try {
|
||||
const accessToken = await getValidAccessToken();
|
||||
if (!accessToken) throw new Error('登录已过期,请重新登录后再同步个人资料。');
|
||||
|
||||
if (profileAvatarDraft.kind === 'upload') {
|
||||
const avatarUrl = await uploadAgentAvatar(accessToken, {
|
||||
fileName: profileAvatarDraft.value.fileName,
|
||||
mimeType: profileAvatarDraft.value.mimeType,
|
||||
dataBase64: profileAvatarDraft.value.dataBase64,
|
||||
});
|
||||
if (!avatarUrl) throw new Error('头像上传成功但未返回头像地址');
|
||||
setUserAvatarUrl(profileAccountKey, avatarUrl);
|
||||
} else if (profileAvatarDraft.kind === 'remove') {
|
||||
const avatarUrl = await deleteAgentAvatar(accessToken);
|
||||
setUserAvatarUrl(profileAccountKey, avatarUrl);
|
||||
}
|
||||
|
||||
setProfileAvatarDraft({ kind: 'unchanged' });
|
||||
saveUserProfile(profileAccountKey, { displayName, age, gender: profileGender });
|
||||
await saveUserProfileToServer(profileAccountKey, accessToken);
|
||||
setProfileDialogOpen(false);
|
||||
} catch (error) {
|
||||
if (error instanceof AgentProfileApiError && error.status === 409) {
|
||||
setProfileError('个人资料已在其他设备更新,请确认最新内容后再次保存。');
|
||||
} else if (error instanceof AgentProfileApiError) {
|
||||
setProfileError(getAgentProfileApiErrorMessage(error));
|
||||
} else {
|
||||
setProfileError(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
} finally {
|
||||
setProfileSaving(false);
|
||||
}
|
||||
};
|
||||
if (profileRequired || profileSyncError) setProfileDialogOpen(true);
|
||||
}, [profileRequired, profileSyncError]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!accountMenuOpen) return undefined;
|
||||
@@ -589,19 +431,8 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
|
||||
const openProfileDialog = () => {
|
||||
setAccountMenuOpen(false);
|
||||
setUsageDrawerOpen(false);
|
||||
profileDialogDirtyRef.current = false;
|
||||
setProfileError(null);
|
||||
setProfileDialogOpen(true);
|
||||
if (profileAccountKey) {
|
||||
void getValidAccessToken()
|
||||
.then((accessToken) => {
|
||||
if (!accessToken) throw new Error('登录已过期,请重新登录后再同步个人资料。');
|
||||
return syncUserProfile(profileAccountKey, accessToken);
|
||||
})
|
||||
.catch((error) => {
|
||||
setProfileError(error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
}
|
||||
void syncProfileNow().catch(() => undefined);
|
||||
};
|
||||
|
||||
const openSubscriptionUpgrade = () => {
|
||||
@@ -736,6 +567,8 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
|
||||
) : null}
|
||||
</div>
|
||||
</>
|
||||
) : isLearningModule ? (
|
||||
<LearningSidebar sidebarCollapsed={sidebarCollapsed} />
|
||||
) : (
|
||||
<div data-testid="sidebar-robot-navigation" className="px-2 py-3">
|
||||
<button
|
||||
@@ -1015,99 +848,12 @@ export function Sidebar({ workspaceLayout = false, sidebarPeekOpen = false, onSi
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{profileDialogOpen ? (
|
||||
<Dialog
|
||||
open={profileDialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open && !profileRequired && !profileSaving && !profileAvatarProcessing) setProfileDialogOpen(false);
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
className="max-w-sm p-5"
|
||||
onInteractOutside={(event) => {
|
||||
if (profileRequired || profileSaving || profileAvatarProcessing) event.preventDefault();
|
||||
}}
|
||||
>
|
||||
<DialogHeader className="flex-row items-start justify-between gap-3 space-y-0">
|
||||
<div>
|
||||
<DialogTitle className="text-xl">个人资料</DialogTitle>
|
||||
<DialogDescription className="mt-1 text-xs">帮助所有 Agent 更自然地了解和协作</DialogDescription>
|
||||
</div>
|
||||
{!profileRequired ? <button
|
||||
type="button"
|
||||
aria-label="关闭个人资料"
|
||||
className="flex h-9 w-9 items-center justify-center rounded-md border border-foreground/15 bg-white text-foreground transition-transform active:scale-[0.985]"
|
||||
onClick={() => setProfileDialogOpen(false)}
|
||||
disabled={profileAvatarProcessing || profileSaving}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button> : null}
|
||||
</DialogHeader>
|
||||
|
||||
{profileRequired ? <div className="mt-4 rounded-lg border border-foreground/15 bg-surface-tertiary p-3 text-sm font-semibold">首次使用前请先填写名字。个人资料与登录账号信息相互独立。</div> : null}
|
||||
|
||||
<div className="mt-4 grid gap-4 text-sm font-medium">
|
||||
<div>
|
||||
<Label>个人头像</Label>
|
||||
<div className="mt-2 flex items-center gap-3 rounded-lg border border-foreground/10 bg-surface-tertiary p-3">
|
||||
<UserAvatar
|
||||
src={profileAvatarPreviewUrl}
|
||||
initial={getAccountInitial(profileName || accountName)}
|
||||
alt="个人头像预览"
|
||||
testId="profile-avatar-preview"
|
||||
className="h-16 w-16 shrink-0 border border-foreground/15 text-lg shadow-soft"
|
||||
/>
|
||||
<div className="min-w-0 flex-1 space-y-2">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<label
|
||||
htmlFor="profile-avatar-upload"
|
||||
className={cn(
|
||||
'inline-flex min-h-8 cursor-pointer items-center justify-center gap-1.5 rounded-md border border-foreground/15 bg-white px-2.5 py-1.5 text-xs font-semibold text-foreground shadow-soft transition-transform active:scale-[0.985]',
|
||||
(profileAvatarProcessing || profileSaving) && 'pointer-events-none opacity-60',
|
||||
)}
|
||||
>
|
||||
<Upload className="h-3.5 w-3.5" />
|
||||
{profileAvatarProcessing ? '处理中…' : '更换头像'}
|
||||
</label>
|
||||
<input
|
||||
id="profile-avatar-upload"
|
||||
data-testid="profile-avatar-upload"
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/webp"
|
||||
className="sr-only"
|
||||
onChange={(event) => void handleAvatarFileChange(event)}
|
||||
disabled={profileAvatarProcessing || profileSaving}
|
||||
/>
|
||||
{profileAvatarDraft.kind !== 'remove' && (profileAvatarPreviewUrl || accountAvatarUrl) ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
data-testid="profile-avatar-remove"
|
||||
className="min-h-8 border border-foreground/15 bg-white px-2.5 py-1.5 text-xs font-semibold text-foreground"
|
||||
onClick={handleRemoveAvatar}
|
||||
disabled={profileAvatarProcessing || profileSaving}
|
||||
>
|
||||
<Trash2 className="mr-1.5 h-3.5 w-3.5" />
|
||||
移除
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="text-[11px] font-medium leading-4 text-muted-foreground">
|
||||
支持 PNG、JPEG、WebP 格式。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div><Label htmlFor="profile-display-name">名字 <span className="text-red-700">*</span></Label><Input id="profile-display-name" value={profileName} maxLength={100} onChange={(event) => { profileDialogDirtyRef.current = true; setProfileName(event.target.value); }} placeholder="希望 Agent 如何称呼你" className="mt-2 border border-foreground/15 bg-white" /></div>
|
||||
<div><Label htmlFor="profile-age">年龄(选填)</Label><Input id="profile-age" type="number" min={1} max={150} value={profileAge} onChange={(event) => { profileDialogDirtyRef.current = true; setProfileAge(event.target.value); }} className="mt-2 border border-foreground/15 bg-white" /></div>
|
||||
<div><Label htmlFor="profile-gender">性别(选填)</Label><select id="profile-gender" value={profileGender} onChange={(event) => { profileDialogDirtyRef.current = true; setProfileGender(event.target.value as UserGender); }} className="mt-2 h-10 w-full rounded-md border border-foreground/15 bg-white px-3"><option value="undisclosed">不透露</option><option value="male">男</option><option value="female">女</option><option value="other">其他</option></select></div>
|
||||
{profileError ? <p role="alert" className="text-sm font-semibold text-red-700">{profileError}</p> : null}
|
||||
{profileSyncState?.status === 'loading' ? <p className="text-xs font-medium text-muted-foreground">正在同步云端个人资料…</p> : null}
|
||||
<Button type="button" onClick={() => void handleSaveProfile()} disabled={profileSaving || profileAvatarProcessing || profileSyncState?.status === 'loading'} className="border border-foreground/15 bg-brand-soft font-semibold text-foreground shadow-soft">{profileSaving ? '正在同步…' : '保存个人资料'}</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
) : null}
|
||||
<UserProfileDialog
|
||||
open={profileDialogOpen}
|
||||
required={profileRequired}
|
||||
syncError={profileSyncError}
|
||||
onOpenChange={setProfileDialogOpen}
|
||||
/>
|
||||
|
||||
<div className="mt-auto px-2 pb-2 pt-1">
|
||||
<div className="relative">
|
||||
|
||||
25
src/components/profile/UserAvatar.tsx
Normal file
25
src/components/profile/UserAvatar.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import { useState } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export type UserAvatarProps = {
|
||||
src: string | null | undefined;
|
||||
initial: string;
|
||||
className: string;
|
||||
alt?: string;
|
||||
testId?: string;
|
||||
};
|
||||
|
||||
export function UserAvatar({ src, initial, className, alt = '', testId }: UserAvatarProps) {
|
||||
const [failedSrc, setFailedSrc] = useState<string | null>(null);
|
||||
const imageAvailable = Boolean(src && failedSrc !== src);
|
||||
|
||||
return (
|
||||
<span data-testid={testId} className={cn('flex items-center justify-center overflow-hidden rounded-full bg-accent-soft text-xs font-semibold text-foreground', className)}>
|
||||
{imageAvailable ? (
|
||||
<img src={src ?? undefined} alt={alt} className="h-full w-full object-cover" onError={() => setFailedSrc(src ?? null)} />
|
||||
) : (
|
||||
initial
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
322
src/components/profile/UserProfileDialog.tsx
Normal file
322
src/components/profile/UserProfileDialog.tsx
Normal file
@@ -0,0 +1,322 @@
|
||||
import { useEffect, useRef, useState, type ChangeEvent } from 'react';
|
||||
import { Trash2, Upload, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { AgentProfileApiError, deleteAgentAvatar, getAgentProfileApiErrorMessage, uploadAgentAvatar } from '@/lib/agent-profile';
|
||||
import { getAuthUserDisplayName } from '@/lib/auth-user-display';
|
||||
import { prepareUserAvatar, type PreparedUserAvatar } from '@/lib/user-avatar';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
import {
|
||||
EMPTY_AGENT_USER_PROFILE,
|
||||
getProfileAccountKey,
|
||||
useUserProfileStore,
|
||||
type UserGender,
|
||||
} from '@/stores/user-profile';
|
||||
import { UserAvatar } from './UserAvatar';
|
||||
import { getAccountInitial } from './user-avatar-utils';
|
||||
|
||||
type ProfileAvatarDraft =
|
||||
| { kind: 'unchanged' }
|
||||
| { kind: 'upload'; value: PreparedUserAvatar }
|
||||
| { kind: 'remove' };
|
||||
|
||||
export type UserProfileDialogProps = {
|
||||
open: boolean;
|
||||
required?: boolean;
|
||||
syncError?: string | null;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
};
|
||||
|
||||
export function UserProfileDialog({
|
||||
open,
|
||||
required = false,
|
||||
syncError = null,
|
||||
onOpenChange,
|
||||
}: UserProfileDialogProps) {
|
||||
const authUser = useAuthStore((state) => state.user);
|
||||
const getValidAccessToken = useAuthStore((state) => state.getValidAccessToken);
|
||||
const profilesByUserId = useUserProfileStore((state) => state.profilesByUserId);
|
||||
const syncStatesByUserId = useUserProfileStore((state) => state.syncStatesByUserId);
|
||||
const saveUserProfile = useUserProfileStore((state) => state.saveProfile);
|
||||
const setUserAvatarUrl = useUserProfileStore((state) => state.setAvatarUrl);
|
||||
const saveUserProfileToServer = useUserProfileStore((state) => state.saveProfileToServer);
|
||||
const profileAccountKey = getProfileAccountKey(authUser?.userId ?? authUser?.username);
|
||||
const userProfile = profileAccountKey ? profilesByUserId[profileAccountKey] : undefined;
|
||||
const profileSyncState = profileAccountKey ? syncStatesByUserId[profileAccountKey] : undefined;
|
||||
const accountName = getAuthUserDisplayName(authUser) || '未登录用户';
|
||||
const accountAvatarUrl = userProfile?.avatarUrl ?? null;
|
||||
const [profileName, setProfileName] = useState('');
|
||||
const [profileAge, setProfileAge] = useState('');
|
||||
const [profileGender, setProfileGender] = useState<UserGender>('undisclosed');
|
||||
const [profileAvatarDraft, setProfileAvatarDraft] = useState<ProfileAvatarDraft>({ kind: 'unchanged' });
|
||||
const [profileAvatarProcessing, setProfileAvatarProcessing] = useState(false);
|
||||
const [profileError, setProfileError] = useState<string | null>(null);
|
||||
const [profileSaving, setProfileSaving] = useState(false);
|
||||
const profileDialogDirtyRef = useRef(false);
|
||||
const forceRequiredRef = useRef(false);
|
||||
const dismissAfterSaveRef = useRef(false);
|
||||
|
||||
const mustCompleteProfile = required || forceRequiredRef.current;
|
||||
const profileAvatarPreviewUrl = profileAvatarDraft.kind === 'upload'
|
||||
? profileAvatarDraft.value.previewUrl
|
||||
: profileAvatarDraft.kind === 'remove'
|
||||
? null
|
||||
: accountAvatarUrl;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
profileDialogDirtyRef.current = false;
|
||||
forceRequiredRef.current = false;
|
||||
dismissAfterSaveRef.current = false;
|
||||
return;
|
||||
}
|
||||
if (required) forceRequiredRef.current = true;
|
||||
}, [open, required]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || profileDialogDirtyRef.current) return;
|
||||
const profile = userProfile ?? EMPTY_AGENT_USER_PROFILE;
|
||||
setProfileName(profile.displayName);
|
||||
setProfileAge(profile.age === null ? '' : String(profile.age));
|
||||
setProfileGender(profile.gender);
|
||||
setProfileAvatarDraft({ kind: 'unchanged' });
|
||||
}, [open, userProfile]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open && syncError) setProfileError(syncError);
|
||||
}, [open, syncError]);
|
||||
|
||||
const handleAvatarFileChange = async (event: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
event.target.value = '';
|
||||
if (!file) return;
|
||||
|
||||
profileDialogDirtyRef.current = true;
|
||||
setProfileAvatarProcessing(true);
|
||||
setProfileError(null);
|
||||
try {
|
||||
const prepared = await prepareUserAvatar(file);
|
||||
setProfileAvatarDraft({ kind: 'upload', value: prepared });
|
||||
} catch (error) {
|
||||
setProfileError(error instanceof Error ? error.message : '头像图片处理失败');
|
||||
} finally {
|
||||
setProfileAvatarProcessing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveAvatar = () => {
|
||||
profileDialogDirtyRef.current = true;
|
||||
setProfileAvatarDraft({ kind: 'remove' });
|
||||
setProfileError(null);
|
||||
};
|
||||
|
||||
const handleSaveProfile = async () => {
|
||||
if (!profileAccountKey) {
|
||||
setProfileError('请先登录后再维护个人资料。');
|
||||
return;
|
||||
}
|
||||
|
||||
const displayName = profileName.trim();
|
||||
if (!displayName) {
|
||||
setProfileError('请填写名字');
|
||||
return;
|
||||
}
|
||||
const age = profileAge.trim() ? Number(profileAge) : null;
|
||||
if (age !== null && (!Number.isInteger(age) || age < 1 || age > 150)) {
|
||||
setProfileError('年龄请输入 1 至 150 的整数');
|
||||
return;
|
||||
}
|
||||
|
||||
setProfileError(null);
|
||||
setProfileSaving(true);
|
||||
try {
|
||||
const accessToken = await getValidAccessToken();
|
||||
if (!accessToken) throw new Error('登录已过期,请重新登录后再同步个人资料。');
|
||||
|
||||
if (profileAvatarDraft.kind === 'upload') {
|
||||
const avatarUrl = await uploadAgentAvatar(accessToken, {
|
||||
fileName: profileAvatarDraft.value.fileName,
|
||||
mimeType: profileAvatarDraft.value.mimeType,
|
||||
dataBase64: profileAvatarDraft.value.dataBase64,
|
||||
});
|
||||
if (!avatarUrl) throw new Error('头像上传成功但未返回头像地址');
|
||||
setUserAvatarUrl(profileAccountKey, avatarUrl);
|
||||
} else if (profileAvatarDraft.kind === 'remove') {
|
||||
const avatarUrl = await deleteAgentAvatar(accessToken);
|
||||
setUserAvatarUrl(profileAccountKey, avatarUrl);
|
||||
}
|
||||
|
||||
setProfileAvatarDraft({ kind: 'unchanged' });
|
||||
saveUserProfile(profileAccountKey, { displayName, age, gender: profileGender });
|
||||
await saveUserProfileToServer(profileAccountKey, accessToken);
|
||||
forceRequiredRef.current = false;
|
||||
dismissAfterSaveRef.current = true;
|
||||
onOpenChange(false);
|
||||
} catch (error) {
|
||||
if (error instanceof AgentProfileApiError && error.status === 409) {
|
||||
setProfileError('个人资料已在其他设备更新,请确认最新内容后再次保存。');
|
||||
} else if (error instanceof AgentProfileApiError) {
|
||||
setProfileError(getAgentProfileApiErrorMessage(error));
|
||||
} else {
|
||||
setProfileError(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
} finally {
|
||||
setProfileSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!nextOpen && (mustCompleteProfile || profileSaving || profileAvatarProcessing) && !dismissAfterSaveRef.current) return;
|
||||
if (nextOpen) dismissAfterSaveRef.current = false;
|
||||
onOpenChange(nextOpen);
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
className="max-w-sm p-5"
|
||||
onInteractOutside={(event) => {
|
||||
if (mustCompleteProfile || profileSaving || profileAvatarProcessing) event.preventDefault();
|
||||
}}
|
||||
>
|
||||
<DialogHeader className="flex-row items-start justify-between gap-3 space-y-0">
|
||||
<div>
|
||||
<DialogTitle className="text-xl">个人资料</DialogTitle>
|
||||
<DialogDescription className="mt-1 text-xs">帮助所有 Agent 更自然地了解和协作</DialogDescription>
|
||||
</div>
|
||||
{!mustCompleteProfile ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label="关闭个人资料"
|
||||
className="flex h-9 w-9 items-center justify-center rounded-md border border-foreground/15 bg-white text-foreground transition-transform active:scale-[0.985]"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={profileAvatarProcessing || profileSaving}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
) : null}
|
||||
</DialogHeader>
|
||||
|
||||
{mustCompleteProfile ? (
|
||||
<div className="mt-4 rounded-lg border border-foreground/15 bg-surface-tertiary p-3 text-sm font-semibold">
|
||||
首次使用前请先填写名字。个人资料与登录账号信息相互独立。
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="mt-4 grid gap-4 text-sm font-medium">
|
||||
<div>
|
||||
<Label>个人头像</Label>
|
||||
<div className="mt-2 flex items-center gap-3 rounded-lg border border-foreground/10 bg-surface-tertiary p-3">
|
||||
<UserAvatar
|
||||
src={profileAvatarPreviewUrl}
|
||||
initial={getAccountInitial(profileName || accountName)}
|
||||
alt="个人头像预览"
|
||||
testId="profile-avatar-preview"
|
||||
className="h-16 w-16 shrink-0 border border-foreground/15 text-lg shadow-soft"
|
||||
/>
|
||||
<div className="min-w-0 flex-1 space-y-2">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<label
|
||||
htmlFor="profile-avatar-upload"
|
||||
className={cn(
|
||||
'inline-flex min-h-8 cursor-pointer items-center justify-center gap-1.5 rounded-md border border-foreground/15 bg-white px-2.5 py-1.5 text-xs font-semibold text-foreground shadow-soft transition-transform active:scale-[0.985]',
|
||||
(profileAvatarProcessing || profileSaving) && 'pointer-events-none opacity-60',
|
||||
)}
|
||||
>
|
||||
<Upload className="h-3.5 w-3.5" />
|
||||
{profileAvatarProcessing ? '处理中…' : '更换头像'}
|
||||
</label>
|
||||
<input
|
||||
id="profile-avatar-upload"
|
||||
data-testid="profile-avatar-upload"
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/webp"
|
||||
className="sr-only"
|
||||
onChange={(event) => void handleAvatarFileChange(event)}
|
||||
disabled={profileAvatarProcessing || profileSaving}
|
||||
/>
|
||||
{profileAvatarDraft.kind !== 'remove' && (profileAvatarPreviewUrl || accountAvatarUrl) ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
data-testid="profile-avatar-remove"
|
||||
className="min-h-8 border border-foreground/15 bg-white px-2.5 py-1.5 text-xs font-semibold text-foreground"
|
||||
onClick={handleRemoveAvatar}
|
||||
disabled={profileAvatarProcessing || profileSaving}
|
||||
>
|
||||
<Trash2 className="mr-1.5 h-3.5 w-3.5" />
|
||||
移除
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="text-[11px] font-medium leading-4 text-muted-foreground">
|
||||
支持 PNG、JPEG、WebP 格式。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="profile-display-name">名字 <span className="text-red-700">*</span></Label>
|
||||
<Input
|
||||
id="profile-display-name"
|
||||
value={profileName}
|
||||
maxLength={100}
|
||||
onChange={(event) => {
|
||||
profileDialogDirtyRef.current = true;
|
||||
setProfileName(event.target.value);
|
||||
}}
|
||||
placeholder="希望 Agent 如何称呼你"
|
||||
className="mt-2 border border-foreground/15 bg-white"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="profile-age">年龄(选填)</Label>
|
||||
<Input
|
||||
id="profile-age"
|
||||
type="number"
|
||||
min={1}
|
||||
max={150}
|
||||
value={profileAge}
|
||||
onChange={(event) => {
|
||||
profileDialogDirtyRef.current = true;
|
||||
setProfileAge(event.target.value);
|
||||
}}
|
||||
className="mt-2 border border-foreground/15 bg-white"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="profile-gender">性别(选填)</Label>
|
||||
<select
|
||||
id="profile-gender"
|
||||
value={profileGender}
|
||||
onChange={(event) => {
|
||||
profileDialogDirtyRef.current = true;
|
||||
setProfileGender(event.target.value as UserGender);
|
||||
}}
|
||||
className="mt-2 h-10 w-full rounded-md border border-foreground/15 bg-white px-3"
|
||||
>
|
||||
<option value="undisclosed">不透露</option>
|
||||
<option value="male">男</option>
|
||||
<option value="female">女</option>
|
||||
<option value="other">其他</option>
|
||||
</select>
|
||||
</div>
|
||||
{profileError ? <p role="alert" className="text-sm font-semibold text-red-700">{profileError}</p> : null}
|
||||
{profileSyncState?.status === 'loading' ? <p className="text-xs font-medium text-muted-foreground">正在同步云端个人资料…</p> : null}
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => void handleSaveProfile()}
|
||||
disabled={profileSaving || profileAvatarProcessing || profileSyncState?.status === 'loading'}
|
||||
className="border border-foreground/15 bg-brand-soft font-semibold text-foreground shadow-soft"
|
||||
>
|
||||
{profileSaving ? '正在同步…' : '保存个人资料'}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
4
src/components/profile/user-avatar-utils.ts
Normal file
4
src/components/profile/user-avatar-utils.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export function getAccountInitial(name: string): string {
|
||||
const first = name.trim().charAt(0);
|
||||
return first ? first.toUpperCase() : 'M';
|
||||
}
|
||||
@@ -1,7 +1,20 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { type FormEvent, useEffect, useRef, useState } from 'react';
|
||||
import { CheckCircle2, Loader2, UploadCloud, XCircle } from 'lucide-react';
|
||||
import { Button, type ButtonProps } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
import { getProfileAccountKey, useUserProfileStore } from '@/stores/user-profile';
|
||||
import {
|
||||
createDefaultWorksAppId,
|
||||
describeWorksPublishFailure,
|
||||
@@ -10,6 +23,7 @@ import {
|
||||
import {
|
||||
fetchCurrentWorksProjectStatus,
|
||||
publishWorksProjectSource,
|
||||
type WorksProjectCoverUpload,
|
||||
type WorksProjectMetadataInput,
|
||||
} from '@/lib/works-square';
|
||||
import type { OpencodeProject } from '@/types/opencode';
|
||||
@@ -32,6 +46,8 @@ type ProjectPublishActionProps = {
|
||||
|
||||
const BUILD_POLL_INTERVAL_MS = 2_000;
|
||||
const BUILD_POLL_ATTEMPTS = 300;
|
||||
const MAX_PROJECT_COVER_BYTES = 10 * 1024 * 1024;
|
||||
const PROJECT_COVER_MIME_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);
|
||||
|
||||
function delay(milliseconds: number): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
@@ -59,6 +75,17 @@ function failureFromVersion(version: BuildVersion): WorksPublishFailure {
|
||||
return describeWorksPublishFailure(code);
|
||||
}
|
||||
|
||||
function readFileAsBase64(file: File): Promise<string> {
|
||||
return file.arrayBuffer().then((buffer) => {
|
||||
const bytes = new Uint8Array(buffer);
|
||||
let binary = '';
|
||||
for (let offset = 0; offset < bytes.length; offset += 0x8000) {
|
||||
binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
|
||||
}
|
||||
return window.btoa(binary);
|
||||
});
|
||||
}
|
||||
|
||||
function buttonLabel(phase: PublishPhase): string {
|
||||
if (phase === 'submitting') return '正在生成本次构建结果…';
|
||||
if (phase === 'polling') return '正在等待云端检查…';
|
||||
@@ -72,23 +99,43 @@ export function ProjectPublishAction({ project, projectType, buttonVariant = 'de
|
||||
const [phase, setPhase] = useState<PublishPhase>('idle');
|
||||
const [failure, setFailure] = useState<WorksPublishFailure | null>(null);
|
||||
const [bindingWarning, setBindingWarning] = useState<string | null>(null);
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [title, setTitle] = useState(() => project.name.trim().slice(0, 160) || 'Makelore 作品');
|
||||
const [summary, setSummary] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [creatorName, setCreatorName] = useState<string | undefined>();
|
||||
const [creatorAge, setCreatorAge] = useState<string | undefined>();
|
||||
const [ageBand, setAgeBand] = useState('');
|
||||
const [difficulty, setDifficulty] = useState('');
|
||||
const [coverFile, setCoverFile] = useState<File | null>(null);
|
||||
const [coverPreviewUrl, setCoverPreviewUrl] = useState<string | null>(null);
|
||||
const coverPreviewUrlRef = useRef<string | null>(null);
|
||||
const pollGeneration = useRef(0);
|
||||
|
||||
const authUser = useAuthStore((state) => state.user);
|
||||
const profileAccountKey = getProfileAccountKey(authUser?.userId ?? authUser?.username);
|
||||
const profile = useUserProfileStore((state) => (
|
||||
profileAccountKey ? state.profilesByUserId[profileAccountKey] : undefined
|
||||
));
|
||||
const profileName = profile?.displayName.trim() || authUser?.username?.trim() || '';
|
||||
|
||||
const creatorNameValue = creatorName ?? profileName;
|
||||
const creatorAgeValue = creatorAge ?? (profile?.age != null ? String(profile.age) : '');
|
||||
|
||||
function releaseCoverPreview(): void {
|
||||
if (coverPreviewUrlRef.current && typeof URL.revokeObjectURL === 'function') {
|
||||
URL.revokeObjectURL(coverPreviewUrlRef.current);
|
||||
}
|
||||
coverPreviewUrlRef.current = null;
|
||||
}
|
||||
|
||||
useEffect(() => () => {
|
||||
pollGeneration.current += 1;
|
||||
releaseCoverPreview();
|
||||
}, []);
|
||||
|
||||
const appId = createDefaultWorksAppId(project);
|
||||
const title = project.name.trim().slice(0, 160) || 'Makelore 作品';
|
||||
const metadata: WorksProjectMetadataInput = {
|
||||
app_id: appId,
|
||||
title,
|
||||
summary: `${title},由 Makelore 创建的作品。`,
|
||||
cover_url: null,
|
||||
category: projectType,
|
||||
age_band: null,
|
||||
difficulty: null,
|
||||
};
|
||||
|
||||
async function pollBuildStatus(versionId: string, generation: number): Promise<void> {
|
||||
for (let attempt = 0; attempt < BUILD_POLL_ATTEMPTS; attempt += 1) {
|
||||
@@ -130,7 +177,7 @@ export function ProjectPublishAction({ project, projectType, buttonVariant = 'de
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSubmit(): Promise<void> {
|
||||
async function submitProject(metadata: WorksProjectMetadataInput, cover: WorksProjectCoverUpload): Promise<void> {
|
||||
pollGeneration.current += 1;
|
||||
const generation = pollGeneration.current;
|
||||
setFailure(null);
|
||||
@@ -141,6 +188,7 @@ export function ProjectPublishAction({ project, projectType, buttonVariant = 'de
|
||||
const result = await publishWorksProjectSource({
|
||||
projectId: project.id,
|
||||
project: metadata,
|
||||
cover,
|
||||
});
|
||||
if (pollGeneration.current !== generation) return;
|
||||
setBindingWarning(result.bindingWarning?.message ?? null);
|
||||
@@ -153,6 +201,90 @@ export function ProjectPublishAction({ project, projectType, buttonVariant = 'de
|
||||
}
|
||||
}
|
||||
|
||||
function handleCoverChange(file: File | undefined): void {
|
||||
setFormError(null);
|
||||
if (!file) {
|
||||
releaseCoverPreview();
|
||||
setCoverFile(null);
|
||||
setCoverPreviewUrl(null);
|
||||
return;
|
||||
}
|
||||
if (!PROJECT_COVER_MIME_TYPES.has(file.type)) {
|
||||
releaseCoverPreview();
|
||||
setCoverFile(null);
|
||||
setCoverPreviewUrl(null);
|
||||
setFormError('封面只支持 PNG、JPEG 或 WebP 图片。');
|
||||
return;
|
||||
}
|
||||
if (file.size > MAX_PROJECT_COVER_BYTES) {
|
||||
releaseCoverPreview();
|
||||
setCoverFile(null);
|
||||
setCoverPreviewUrl(null);
|
||||
setFormError('封面图片不能超过 10MB。');
|
||||
return;
|
||||
}
|
||||
releaseCoverPreview();
|
||||
const nextPreviewUrl = typeof URL.createObjectURL === 'function'
|
||||
? URL.createObjectURL(file)
|
||||
: null;
|
||||
coverPreviewUrlRef.current = nextPreviewUrl;
|
||||
setCoverFile(file);
|
||||
setCoverPreviewUrl(nextPreviewUrl);
|
||||
}
|
||||
|
||||
async function handleFormSubmit(event: FormEvent<HTMLFormElement>): Promise<void> {
|
||||
event.preventDefault();
|
||||
const trimmedTitle = title.trim();
|
||||
const trimmedSummary = summary.trim();
|
||||
const trimmedCreatorName = creatorNameValue.trim();
|
||||
const parsedCreatorAge = Number(creatorAgeValue);
|
||||
if (!trimmedTitle) {
|
||||
setFormError('请填写项目名称。');
|
||||
return;
|
||||
}
|
||||
if (!trimmedSummary) {
|
||||
setFormError('请填写项目简介。');
|
||||
return;
|
||||
}
|
||||
if (!trimmedCreatorName) {
|
||||
setFormError('请填写发布者姓名。');
|
||||
return;
|
||||
}
|
||||
if (!Number.isInteger(parsedCreatorAge) || parsedCreatorAge < 1 || parsedCreatorAge > 150) {
|
||||
setFormError('请填写 1 到 150 之间的发布者年龄。');
|
||||
return;
|
||||
}
|
||||
if (!coverFile) {
|
||||
setFormError('请上传项目封面。');
|
||||
return;
|
||||
}
|
||||
|
||||
setFormError(null);
|
||||
try {
|
||||
const cover = {
|
||||
fileName: coverFile.name || 'project-cover',
|
||||
mimeType: coverFile.type,
|
||||
dataBase64: await readFileAsBase64(coverFile),
|
||||
} satisfies WorksProjectCoverUpload;
|
||||
const metadata: WorksProjectMetadataInput = {
|
||||
app_id: appId,
|
||||
title: trimmedTitle.slice(0, 160),
|
||||
summary: trimmedSummary,
|
||||
description: description.trim() || null,
|
||||
cover_url: null,
|
||||
creator_name: trimmedCreatorName.slice(0, 160),
|
||||
creator_age: parsedCreatorAge,
|
||||
category: projectType,
|
||||
age_band: ageBand.trim() || null,
|
||||
difficulty: difficulty.trim() || null,
|
||||
};
|
||||
setDialogOpen(false);
|
||||
await submitProject(metadata, cover);
|
||||
} catch {
|
||||
setFormError('封面读取失败,请重新选择图片后再试。');
|
||||
}
|
||||
}
|
||||
|
||||
const locked = phase === 'submitting'
|
||||
|| phase === 'polling'
|
||||
|| phase === 'succeeded'
|
||||
@@ -166,7 +298,10 @@ export function ProjectPublishAction({ project, projectType, buttonVariant = 'de
|
||||
variant={buttonVariant}
|
||||
size={buttonSize}
|
||||
disabled={locked}
|
||||
onClick={() => void handleSubmit()}
|
||||
onClick={() => {
|
||||
setFormError(null);
|
||||
setDialogOpen(true);
|
||||
}}
|
||||
className={cn(
|
||||
buttonSize === 'sm' ? 'h-9 w-full px-3 font-semibold sm:w-auto' : 'h-12 w-full px-6 font-semibold sm:w-auto',
|
||||
buttonVariant === 'outline'
|
||||
@@ -184,6 +319,145 @@ export function ProjectPublishAction({ project, projectType, buttonVariant = 'de
|
||||
{buttonLabel(phase)}
|
||||
</Button>
|
||||
|
||||
<Dialog
|
||||
open={dialogOpen}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!busy) setDialogOpen(nextOpen);
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-h-[min(820px,calc(100vh-2rem))] overflow-y-auto sm:max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>完善作品信息后提交</DialogTitle>
|
||||
<DialogDescription>
|
||||
这些信息会和项目构建结果一起提交给运营审核。发布者年龄指作者本人年龄。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form className="grid gap-4" onSubmit={(event) => void handleFormSubmit(event)}>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="project-publish-title">项目名称 <span className="text-destructive">*</span></Label>
|
||||
<Input
|
||||
id="project-publish-title"
|
||||
value={title}
|
||||
maxLength={160}
|
||||
onChange={(event) => setTitle(event.target.value)}
|
||||
placeholder="例如:太空清洁员"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2 sm:grid-cols-[1fr_160px]">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="project-publish-creator-name">发布者姓名 <span className="text-destructive">*</span></Label>
|
||||
<Input
|
||||
id="project-publish-creator-name"
|
||||
value={creatorNameValue}
|
||||
maxLength={160}
|
||||
onChange={(event) => setCreatorName(event.target.value)}
|
||||
placeholder="作品作者或孩子的名字"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="project-publish-creator-age">发布者年龄 <span className="text-destructive">*</span></Label>
|
||||
<Input
|
||||
id="project-publish-creator-age"
|
||||
type="number"
|
||||
min={1}
|
||||
max={150}
|
||||
value={creatorAgeValue}
|
||||
onChange={(event) => setCreatorAge(event.target.value)}
|
||||
placeholder="作者年龄"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="project-publish-summary">项目简介 <span className="text-destructive">*</span></Label>
|
||||
<Textarea
|
||||
id="project-publish-summary"
|
||||
value={summary}
|
||||
maxLength={2000}
|
||||
onChange={(event) => setSummary(event.target.value)}
|
||||
placeholder="用一两句话介绍这个项目,网页列表会展示这段文字。"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="project-publish-description">详细介绍(选填)</Label>
|
||||
<Textarea
|
||||
id="project-publish-description"
|
||||
value={description}
|
||||
maxLength={10000}
|
||||
onChange={(event) => setDescription(event.target.value)}
|
||||
placeholder="可以补充玩法、创作过程或想让访客了解的内容。"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="project-publish-cover">项目封面 <span className="text-destructive">*</span></Label>
|
||||
<Input
|
||||
id="project-publish-cover"
|
||||
data-testid="project-publish-cover"
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/webp"
|
||||
onChange={(event) => handleCoverChange(event.target.files?.[0])}
|
||||
required={!coverFile}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">支持 PNG、JPEG、WebP,最大 10MB。封面会随本次提交上传。</p>
|
||||
{coverPreviewUrl ? (
|
||||
<img
|
||||
src={coverPreviewUrl}
|
||||
alt="项目封面预览"
|
||||
className="h-32 w-full rounded-xl border border-border/80 object-cover"
|
||||
/>
|
||||
) : null}
|
||||
{coverFile ? <p className="truncate text-xs text-muted-foreground">已选择:{coverFile.name}</p> : null}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="project-publish-age-band">适龄范围(选填)</Label>
|
||||
<Input
|
||||
id="project-publish-age-band"
|
||||
value={ageBand}
|
||||
maxLength={40}
|
||||
onChange={(event) => setAgeBand(event.target.value)}
|
||||
placeholder="例如:6-12岁"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="project-publish-difficulty">难度(选填)</Label>
|
||||
<Input
|
||||
id="project-publish-difficulty"
|
||||
value={difficulty}
|
||||
maxLength={40}
|
||||
onChange={(event) => setDifficulty(event.target.value)}
|
||||
placeholder="例如:入门"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="rounded-xl bg-muted/50 px-3 py-2 text-xs text-muted-foreground">
|
||||
作品类型:{projectType}。名称、简介、作者信息和封面都会交给运营端统一审核。
|
||||
</p>
|
||||
|
||||
{formError ? (
|
||||
<p className="rounded-xl border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive" role="alert">
|
||||
{formError}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setDialogOpen(false)}>取消</Button>
|
||||
<Button type="submit">提交审核</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{phase === 'submitting' || phase === 'polling' || phase === 'succeeded' ? (
|
||||
<p
|
||||
data-testid="project-publish-status"
|
||||
|
||||
Reference in New Issue
Block a user