add sign in page
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { afterEach, beforeEach, test } from 'node:test';
|
||||
|
||||
import { apiRequest } from './api';
|
||||
import { apiRequest, shouldRetryRequest, toNetworkApiError } from './api';
|
||||
import { clearStoredSession, saveStoredSession } from './session';
|
||||
|
||||
class MemoryStorage implements Storage {
|
||||
@@ -109,3 +109,33 @@ test('apiRequest throws backend message on business error', async () => {
|
||||
|
||||
await assert.rejects(() => apiRequest('/user/profile'), /login required/);
|
||||
});
|
||||
|
||||
test('network login failures are retried a limited number of times for auth login', () => {
|
||||
const error = new TypeError('Failed to fetch');
|
||||
|
||||
assert.equal(shouldRetryRequest('/auth/login', {method: 'POST'}, error, 0), true);
|
||||
assert.equal(shouldRetryRequest('/auth/login', {method: 'POST'}, error, 1), true);
|
||||
assert.equal(shouldRetryRequest('/auth/login', {method: 'POST'}, error, 2), false);
|
||||
});
|
||||
|
||||
test('network register failures are not retried automatically', () => {
|
||||
const error = new TypeError('Failed to fetch');
|
||||
|
||||
assert.equal(shouldRetryRequest('/auth/register', {method: 'POST'}, error, 0), false);
|
||||
});
|
||||
|
||||
test('network get failures are retried up to two times after the first attempt', () => {
|
||||
const error = new TypeError('Failed to fetch');
|
||||
|
||||
assert.equal(shouldRetryRequest('/files/list', {method: 'GET'}, error, 0), true);
|
||||
assert.equal(shouldRetryRequest('/files/list', {method: 'GET'}, error, 1), true);
|
||||
assert.equal(shouldRetryRequest('/files/list', {method: 'GET'}, error, 2), true);
|
||||
assert.equal(shouldRetryRequest('/files/list', {method: 'GET'}, error, 3), false);
|
||||
});
|
||||
|
||||
test('network fetch failures are converted to readable api errors', () => {
|
||||
const apiError = toNetworkApiError(new TypeError('Failed to fetch'));
|
||||
|
||||
assert.equal(apiError.status, 0);
|
||||
assert.match(apiError.message, /网络连接异常|Failed to fetch/);
|
||||
});
|
||||
|
||||
@@ -15,15 +15,57 @@ const API_BASE_URL = (import.meta.env?.VITE_API_BASE_URL || '/api').replace(/\/$
|
||||
export class ApiError extends Error {
|
||||
code?: number;
|
||||
status: number;
|
||||
isNetworkError: boolean;
|
||||
|
||||
constructor(message: string, status = 500, code?: number) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
this.isNetworkError = status === 0;
|
||||
}
|
||||
}
|
||||
|
||||
function isNetworkFailure(error: unknown) {
|
||||
return error instanceof TypeError || error instanceof DOMException;
|
||||
}
|
||||
|
||||
function sleep(ms: number) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms);
|
||||
});
|
||||
}
|
||||
|
||||
function getRetryDelayMs(attempt: number) {
|
||||
const schedule = [500, 1200, 2200];
|
||||
return schedule[Math.min(attempt, schedule.length - 1)];
|
||||
}
|
||||
|
||||
function getMaxRetryAttempts(path: string, init: ApiRequestInit = {}) {
|
||||
const method = (init.method || 'GET').toUpperCase();
|
||||
|
||||
if (method === 'POST' && path === '/auth/login') {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') {
|
||||
return 2;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
function getRetryDelayForRequest(path: string, init: ApiRequestInit = {}, attempt: number) {
|
||||
const method = (init.method || 'GET').toUpperCase();
|
||||
|
||||
if (method === 'POST' && path === '/auth/login') {
|
||||
const loginSchedule = [350, 800];
|
||||
return loginSchedule[Math.min(attempt, loginSchedule.length - 1)];
|
||||
}
|
||||
|
||||
return getRetryDelayMs(attempt);
|
||||
}
|
||||
|
||||
function resolveUrl(path: string) {
|
||||
if (/^https?:\/\//.test(path)) {
|
||||
return path;
|
||||
@@ -61,6 +103,25 @@ async function parseApiError(response: Response) {
|
||||
return new ApiError(payload.msg || `请求失败 (${response.status})`, response.status, payload.code);
|
||||
}
|
||||
|
||||
export function toNetworkApiError(error: unknown) {
|
||||
const fallbackMessage = '网络连接异常,请稍后重试';
|
||||
const message = error instanceof Error && error.message ? error.message : fallbackMessage;
|
||||
return new ApiError(message === 'Failed to fetch' ? fallbackMessage : message, 0);
|
||||
}
|
||||
|
||||
export function shouldRetryRequest(
|
||||
path: string,
|
||||
init: ApiRequestInit = {},
|
||||
error: unknown,
|
||||
attempt: number,
|
||||
) {
|
||||
if (!isNetworkFailure(error)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return attempt <= getMaxRetryAttempts(path, init);
|
||||
}
|
||||
|
||||
async function performRequest(path: string, init: ApiRequestInit = {}) {
|
||||
const session = readStoredSession();
|
||||
const headers = new Headers(init.headers);
|
||||
@@ -76,11 +137,30 @@ async function performRequest(path: string, init: ApiRequestInit = {}) {
|
||||
headers.set('Accept', 'application/json');
|
||||
}
|
||||
|
||||
const response = await fetch(resolveUrl(path), {
|
||||
...init,
|
||||
headers,
|
||||
body: requestBody,
|
||||
});
|
||||
let response: Response;
|
||||
let lastError: unknown;
|
||||
|
||||
for (let attempt = 0; attempt <= 3; attempt += 1) {
|
||||
try {
|
||||
response = await fetch(resolveUrl(path), {
|
||||
...init,
|
||||
headers,
|
||||
body: requestBody,
|
||||
});
|
||||
break;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (!shouldRetryRequest(path, init, error, attempt)) {
|
||||
throw toNetworkApiError(error);
|
||||
}
|
||||
|
||||
await sleep(getRetryDelayForRequest(path, init, attempt));
|
||||
}
|
||||
}
|
||||
|
||||
if (!response!) {
|
||||
throw toNetworkApiError(lastError);
|
||||
}
|
||||
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
clearStoredSession();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { AuthSession } from './types';
|
||||
|
||||
const SESSION_STORAGE_KEY = 'portal-session';
|
||||
const POST_LOGIN_PENDING_KEY = 'portal-post-login-pending';
|
||||
export const SESSION_EVENT_NAME = 'portal-session-change';
|
||||
|
||||
function notifySessionChanged() {
|
||||
@@ -44,3 +45,27 @@ export function clearStoredSession() {
|
||||
localStorage.removeItem(SESSION_STORAGE_KEY);
|
||||
notifySessionChanged();
|
||||
}
|
||||
|
||||
export function markPostLoginPending() {
|
||||
if (typeof sessionStorage === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
sessionStorage.setItem(POST_LOGIN_PENDING_KEY, String(Date.now()));
|
||||
}
|
||||
|
||||
export function hasPostLoginPending() {
|
||||
if (typeof sessionStorage === 'undefined') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return sessionStorage.getItem(POST_LOGIN_PENDING_KEY) != null;
|
||||
}
|
||||
|
||||
export function clearPostLoginPending() {
|
||||
if (typeof sessionStorage === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
sessionStorage.removeItem(POST_LOGIN_PENDING_KEY);
|
||||
}
|
||||
|
||||
@@ -1,25 +1,36 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { motion } from 'motion/react';
|
||||
import { LogIn, User, Lock } from 'lucide-react';
|
||||
import { motion, AnimatePresence } from 'motion/react';
|
||||
import { LogIn, User, Lock, UserPlus, Mail, ArrowLeft } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/src/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/src/components/ui/card';
|
||||
import { Button } from '@/src/components/ui/button';
|
||||
import { Input } from '@/src/components/ui/input';
|
||||
import { apiRequest, ApiError } from '@/src/lib/api';
|
||||
import { saveStoredSession } from '@/src/lib/session';
|
||||
import { cn } from '@/src/lib/utils';
|
||||
import { markPostLoginPending, saveStoredSession } from '@/src/lib/session';
|
||||
import type { AuthResponse } from '@/src/lib/types';
|
||||
|
||||
const DEV_LOGIN_ENABLED = import.meta.env.DEV || import.meta.env.VITE_ENABLE_DEV_LOGIN === 'true';
|
||||
|
||||
export default function Login() {
|
||||
const navigate = useNavigate();
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [isLogin, setIsLogin] = useState(true);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [registerUsername, setRegisterUsername] = useState('');
|
||||
const [registerEmail, setRegisterEmail] = useState('');
|
||||
const [registerPassword, setRegisterPassword] = useState('');
|
||||
|
||||
const handleLogin = async (e: React.FormEvent) => {
|
||||
function switchMode(nextIsLogin: boolean) {
|
||||
setIsLogin(nextIsLogin);
|
||||
setError('');
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
async function handleLoginSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError('');
|
||||
@@ -52,119 +63,287 @@ export default function Login() {
|
||||
token: auth.token,
|
||||
user: auth.user,
|
||||
});
|
||||
markPostLoginPending();
|
||||
setLoading(false);
|
||||
navigate('/overview');
|
||||
} catch (requestError) {
|
||||
setLoading(false);
|
||||
setError(requestError instanceof Error ? requestError.message : '登录失败,请稍后重试');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function handleRegisterSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError('');
|
||||
|
||||
try {
|
||||
const auth = await apiRequest<AuthResponse>('/auth/register', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
username: registerUsername.trim(),
|
||||
email: registerEmail.trim(),
|
||||
password: registerPassword,
|
||||
},
|
||||
});
|
||||
|
||||
saveStoredSession({
|
||||
token: auth.token,
|
||||
user: auth.user,
|
||||
});
|
||||
markPostLoginPending();
|
||||
setLoading(false);
|
||||
navigate('/overview');
|
||||
} catch (requestError) {
|
||||
setLoading(false);
|
||||
setError(requestError instanceof Error ? requestError.message : '注册失败,请稍后重试');
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-[#07101D] relative overflow-hidden">
|
||||
{/* Background Glow */}
|
||||
<div className="absolute top-1/4 left-1/4 w-96 h-96 bg-[#336EFF] rounded-full mix-blend-screen filter blur-[128px] opacity-20 animate-pulse" />
|
||||
<div className="absolute bottom-1/4 right-1/4 w-96 h-96 bg-purple-600 rounded-full mix-blend-screen filter blur-[128px] opacity-20" />
|
||||
|
||||
<div className="container mx-auto px-4 grid lg:grid-cols-2 gap-12 items-center relative z-10">
|
||||
{/* Left Side: Brand Info */}
|
||||
<div className="container mx-auto px-4 relative z-10 flex items-center w-full min-h-[600px]">
|
||||
<AnimatePresence>
|
||||
{isLogin && (
|
||||
<motion.div
|
||||
key="brand-info"
|
||||
initial={{ opacity: 0, x: -50 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: -50 }}
|
||||
transition={{ duration: 0.5, ease: 'easeOut' }}
|
||||
className="absolute left-4 lg:left-8 xl:left-12 w-1/2 max-w-lg hidden lg:flex flex-col space-y-6"
|
||||
>
|
||||
<div className="inline-flex items-center gap-2 px-4 py-2 rounded-full glass-panel border-white/10 w-fit">
|
||||
<span className="w-2 h-2 rounded-full bg-[#336EFF] animate-pulse" />
|
||||
<span className="text-sm text-slate-300 font-medium tracking-wide uppercase">Access Portal</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-xl text-[#336EFF] font-bold tracking-widest uppercase">YOYUZH.XYZ</h2>
|
||||
<h1 className="text-5xl md:text-6xl font-bold text-white leading-tight">
|
||||
个人网站
|
||||
<br />
|
||||
统一入口
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
<p className="text-lg text-slate-400 leading-relaxed">
|
||||
欢迎来到 YOYUZH 的个人门户。在这里,你可以集中管理个人网盘文件、查询教务成绩课表,以及体验轻量级小游戏。
|
||||
</p>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
<motion.div
|
||||
initial={{ opacity: 0, x: -50 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
transition={{ duration: 0.8, ease: 'easeOut' }}
|
||||
className="flex flex-col space-y-6 max-w-lg"
|
||||
layout
|
||||
transition={{ type: 'spring', stiffness: 200, damping: 25 }}
|
||||
className={cn(
|
||||
'w-full max-w-md z-10',
|
||||
isLogin ? 'ml-auto lg:mr-8 xl:mr-12' : 'mx-auto'
|
||||
)}
|
||||
>
|
||||
<div className="inline-flex items-center gap-2 px-4 py-2 rounded-full glass-panel border-white/10 w-fit">
|
||||
<span className="w-2 h-2 rounded-full bg-[#336EFF] animate-pulse" />
|
||||
<span className="text-sm text-slate-300 font-medium tracking-wide uppercase">Access Portal</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-xl text-[#336EFF] font-bold tracking-widest uppercase">YOYUZH.XYZ</h2>
|
||||
<h1 className="text-5xl md:text-6xl font-bold text-white leading-tight">
|
||||
个人网站
|
||||
<br />
|
||||
统一入口
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
<p className="text-lg text-slate-400 leading-relaxed">
|
||||
欢迎来到 YOYUZH 的个人门户。在这里,你可以集中管理个人网盘文件、查询教务成绩课表,以及体验轻量级小游戏。
|
||||
</p>
|
||||
</motion.div>
|
||||
|
||||
{/* Right Side: Login Form */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 50 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.8, delay: 0.2, ease: 'easeOut' }}
|
||||
className="w-full max-w-md mx-auto lg:mx-0 lg:ml-auto"
|
||||
>
|
||||
<Card className="border-white/10 backdrop-blur-2xl bg-white/5 shadow-2xl">
|
||||
<CardHeader className="space-y-1 pb-8">
|
||||
<CardTitle className="text-2xl font-bold text-white flex items-center gap-2">
|
||||
<LogIn className="w-6 h-6 text-[#336EFF]" />
|
||||
登录
|
||||
</CardTitle>
|
||||
<CardDescription className="text-slate-400">
|
||||
请输入您的账号和密码以继续
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleLogin} className="space-y-6">
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-slate-300 ml-1">用户名</label>
|
||||
<div className="relative">
|
||||
<User className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-500" />
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="账号 / 用户名 / 学号"
|
||||
className="pl-10 bg-black/20 border-white/10 focus-visible:ring-[#336EFF]"
|
||||
value={username}
|
||||
onChange={(event) => setUsername(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-slate-300 ml-1">密码</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-500" />
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="••••••••"
|
||||
className="pl-10 bg-black/20 border-white/10 focus-visible:ring-[#336EFF]"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-3 rounded-xl bg-red-500/10 border border-red-500/20 text-red-400 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full h-12 text-base font-semibold"
|
||||
disabled={loading}
|
||||
<Card className="border-white/10 backdrop-blur-2xl bg-white/5 shadow-2xl overflow-hidden">
|
||||
<AnimatePresence mode="wait">
|
||||
{isLogin ? (
|
||||
<motion.div
|
||||
key="login-form"
|
||||
initial={{ opacity: 0, x: 20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: -20 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
{loading ? (
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="w-4 h-4 border-2 border-white/20 border-t-white rounded-full animate-spin" />
|
||||
登录中...
|
||||
</span>
|
||||
) : (
|
||||
'进入系统'
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
<CardHeader className="space-y-1 pb-8">
|
||||
<CardTitle className="text-2xl font-bold text-white flex items-center gap-2">
|
||||
<LogIn className="w-6 h-6 text-[#336EFF]" />
|
||||
登录
|
||||
</CardTitle>
|
||||
<CardDescription className="text-slate-400">
|
||||
请输入您的账号和密码以继续
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleLoginSubmit} className="space-y-6">
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-slate-300 ml-1">用户名</label>
|
||||
<div className="relative">
|
||||
<User className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-500" />
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="账号 / 用户名 / 学号"
|
||||
className="pl-10 bg-black/20 border-white/10 focus-visible:ring-[#336EFF]"
|
||||
value={username}
|
||||
onChange={(event) => setUsername(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-slate-300 ml-1">密码</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-500" />
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="••••••••"
|
||||
className="pl-10 bg-black/20 border-white/10 focus-visible:ring-[#336EFF]"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-3 rounded-xl bg-red-500/10 border border-red-500/20 text-red-400 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full h-12 text-base font-semibold"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? (
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="w-4 h-4 border-2 border-white/20 border-t-white rounded-full animate-spin" />
|
||||
登录中...
|
||||
</span>
|
||||
) : (
|
||||
'进入系统'
|
||||
)}
|
||||
</Button>
|
||||
<div className="text-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => switchMode(false)}
|
||||
className="text-sm text-slate-400 hover:text-[#336EFF] transition-colors"
|
||||
>
|
||||
还没有账号?立即注册
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</motion.div>
|
||||
) : (
|
||||
<motion.div
|
||||
key="register-form"
|
||||
initial={{ opacity: 0, x: 20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: -20 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
<CardHeader className="space-y-1 pb-8">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-2xl font-bold text-white flex items-center gap-2">
|
||||
<UserPlus className="w-6 h-6 text-[#336EFF]" />
|
||||
注册账号
|
||||
</CardTitle>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => switchMode(true)}
|
||||
className="p-2 rounded-full hover:bg-white/5 text-slate-400 transition-colors"
|
||||
>
|
||||
<ArrowLeft className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
<CardDescription className="text-slate-400">
|
||||
创建一个新账号以开启您的门户体验
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleRegisterSubmit} className="space-y-6">
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-slate-300 ml-1">用户名</label>
|
||||
<div className="relative">
|
||||
<User className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-500" />
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="设置您的用户名"
|
||||
className="pl-10 bg-black/20 border-white/10 focus-visible:ring-[#336EFF]"
|
||||
value={registerUsername}
|
||||
onChange={(event) => setRegisterUsername(event.target.value)}
|
||||
required
|
||||
minLength={3}
|
||||
maxLength={64}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-slate-300 ml-1">邮箱</label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-500" />
|
||||
<Input
|
||||
type="email"
|
||||
placeholder="your@email.com"
|
||||
className="pl-10 bg-black/20 border-white/10 focus-visible:ring-[#336EFF]"
|
||||
value={registerEmail}
|
||||
onChange={(event) => setRegisterEmail(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-slate-300 ml-1">密码</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-500" />
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="设置您的密码"
|
||||
className="pl-10 bg-black/20 border-white/10 focus-visible:ring-[#336EFF]"
|
||||
value={registerPassword}
|
||||
onChange={(event) => setRegisterPassword(event.target.value)}
|
||||
required
|
||||
minLength={6}
|
||||
maxLength={64}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-3 rounded-xl bg-red-500/10 border border-red-500/20 text-red-400 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full h-12 text-base font-semibold"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? (
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="w-4 h-4 border-2 border-white/20 border-t-white rounded-full animate-spin" />
|
||||
注册中...
|
||||
</span>
|
||||
) : (
|
||||
'创建账号'
|
||||
)}
|
||||
</Button>
|
||||
<div className="text-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => switchMode(true)}
|
||||
className="text-sm text-slate-400 hover:text-[#336EFF] transition-colors"
|
||||
>
|
||||
已有账号?返回登录
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</Card>
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
@@ -20,8 +20,9 @@ import { apiRequest } from '@/src/lib/api';
|
||||
import { readCachedValue, writeCachedValue } from '@/src/lib/cache';
|
||||
import { getOverviewCacheKey, getSchoolResultsCacheKey, readStoredSchoolQuery, writeStoredSchoolQuery } from '@/src/lib/page-cache';
|
||||
import { cacheLatestSchoolData, fetchLatestSchoolData } from '@/src/lib/school';
|
||||
import { readStoredSession } from '@/src/lib/session';
|
||||
import { clearPostLoginPending, hasPostLoginPending, readStoredSession } from '@/src/lib/session';
|
||||
import type { CourseResponse, FileMetadata, GradeResponse, PageResponse, UserProfile } from '@/src/lib/types';
|
||||
import { getOverviewLoadErrorMessage } from './overview-state';
|
||||
|
||||
function formatFileSize(size: number) {
|
||||
if (size <= 0) {
|
||||
@@ -71,6 +72,8 @@ export default function Overview() {
|
||||
const [rootFiles, setRootFiles] = useState<FileMetadata[]>(cachedOverview?.rootFiles ?? []);
|
||||
const [schedule, setSchedule] = useState<CourseResponse[]>(cachedOverview?.schedule ?? cachedSchoolResults?.schedule ?? []);
|
||||
const [grades, setGrades] = useState<GradeResponse[]>(cachedOverview?.grades ?? cachedSchoolResults?.grades ?? []);
|
||||
const [loadingError, setLoadingError] = useState('');
|
||||
const [retryToken, setRetryToken] = useState(0);
|
||||
|
||||
const currentHour = new Date().getHours();
|
||||
let greeting = '晚上好';
|
||||
@@ -93,24 +96,38 @@ export default function Overview() {
|
||||
let cancelled = false;
|
||||
|
||||
async function loadOverview() {
|
||||
const pendingAfterLogin = hasPostLoginPending();
|
||||
setLoadingError('');
|
||||
|
||||
try {
|
||||
const [user, filesRecent, filesRoot] = await Promise.all([
|
||||
const [userResult, recentResult, rootResult] = await Promise.allSettled([
|
||||
apiRequest<UserProfile>('/user/profile'),
|
||||
apiRequest<FileMetadata[]>('/files/recent'),
|
||||
apiRequest<PageResponse<FileMetadata>>('/files/list?path=%2F&page=0&size=100'),
|
||||
]);
|
||||
|
||||
const primaryFailures = [userResult, recentResult, rootResult].filter(
|
||||
(result) => result.status === 'rejected'
|
||||
);
|
||||
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
setProfile(user);
|
||||
setRecentFiles(filesRecent);
|
||||
setRootFiles(filesRoot.items);
|
||||
if (userResult.status === 'fulfilled') {
|
||||
setProfile(userResult.value);
|
||||
}
|
||||
if (recentResult.status === 'fulfilled') {
|
||||
setRecentFiles(recentResult.value);
|
||||
}
|
||||
if (rootResult.status === 'fulfilled') {
|
||||
setRootFiles(rootResult.value.items);
|
||||
}
|
||||
|
||||
let scheduleData: CourseResponse[] = [];
|
||||
let gradesData: GradeResponse[] = [];
|
||||
const schoolQuery = readStoredSchoolQuery();
|
||||
let schoolFailed = false;
|
||||
|
||||
if (schoolQuery?.studentId && schoolQuery?.semester) {
|
||||
const queryString = new URLSearchParams({
|
||||
@@ -118,20 +135,35 @@ export default function Overview() {
|
||||
semester: schoolQuery.semester,
|
||||
}).toString();
|
||||
|
||||
[scheduleData, gradesData] = await Promise.all([
|
||||
const [scheduleResult, gradesResult] = await Promise.allSettled([
|
||||
apiRequest<CourseResponse[]>(`/cqu/schedule?${queryString}`),
|
||||
apiRequest<GradeResponse[]>(`/cqu/grades?${queryString}`),
|
||||
]);
|
||||
|
||||
if (scheduleResult.status === 'fulfilled') {
|
||||
scheduleData = scheduleResult.value;
|
||||
} else {
|
||||
schoolFailed = true;
|
||||
}
|
||||
if (gradesResult.status === 'fulfilled') {
|
||||
gradesData = gradesResult.value;
|
||||
} else {
|
||||
schoolFailed = true;
|
||||
}
|
||||
} else {
|
||||
const latest = await fetchLatestSchoolData();
|
||||
if (latest) {
|
||||
cacheLatestSchoolData(latest);
|
||||
writeStoredSchoolQuery({
|
||||
studentId: latest.studentId,
|
||||
semester: latest.semester,
|
||||
});
|
||||
scheduleData = latest.schedule;
|
||||
gradesData = latest.grades;
|
||||
try {
|
||||
const latest = await fetchLatestSchoolData();
|
||||
if (latest) {
|
||||
cacheLatestSchoolData(latest);
|
||||
writeStoredSchoolQuery({
|
||||
studentId: latest.studentId,
|
||||
semester: latest.semester,
|
||||
});
|
||||
scheduleData = latest.schedule;
|
||||
gradesData = latest.grades;
|
||||
}
|
||||
} catch {
|
||||
schoolFailed = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,12 +171,27 @@ export default function Overview() {
|
||||
setSchedule(scheduleData);
|
||||
setGrades(gradesData);
|
||||
writeCachedValue(getOverviewCacheKey(), {
|
||||
profile: user,
|
||||
recentFiles: filesRecent,
|
||||
rootFiles: filesRoot.items,
|
||||
profile:
|
||||
userResult.status === 'fulfilled'
|
||||
? userResult.value
|
||||
: profile,
|
||||
recentFiles:
|
||||
recentResult.status === 'fulfilled'
|
||||
? recentResult.value
|
||||
: recentFiles,
|
||||
rootFiles:
|
||||
rootResult.status === 'fulfilled'
|
||||
? rootResult.value.items
|
||||
: rootFiles,
|
||||
schedule: scheduleData,
|
||||
grades: gradesData,
|
||||
});
|
||||
|
||||
if (primaryFailures.length > 0 || schoolFailed) {
|
||||
setLoadingError(getOverviewLoadErrorMessage(pendingAfterLogin));
|
||||
} else {
|
||||
clearPostLoginPending();
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
const schoolQuery = readStoredSchoolQuery();
|
||||
@@ -159,6 +206,10 @@ export default function Overview() {
|
||||
setGrades(cachedSchoolResults.grades);
|
||||
}
|
||||
}
|
||||
|
||||
if (!cancelled) {
|
||||
setLoadingError(getOverviewLoadErrorMessage(pendingAfterLogin));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,7 +217,7 @@ export default function Overview() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
}, [retryToken]);
|
||||
|
||||
const latestSemester = grades[0]?.semester ?? '--';
|
||||
const previewCourses = schedule.slice(0, 3);
|
||||
@@ -191,6 +242,19 @@ export default function Overview() {
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{loadingError && (
|
||||
<motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }}>
|
||||
<Card className="border-amber-400/20 bg-amber-500/10">
|
||||
<CardContent className="flex flex-col gap-3 p-4 text-sm text-amber-100 md:flex-row md:items-center md:justify-between">
|
||||
<span>{loadingError}</span>
|
||||
<Button variant="secondary" size="sm" onClick={() => setRetryToken((value) => value + 1)}>
|
||||
重新加载总览
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* Metrics Cards */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
<MetricCard title="网盘文件总数" value={`${rootFiles.length}`} desc="当前根目录统计" icon={FileText} delay={0.1} />
|
||||
|
||||
18
front/src/pages/overview-state.test.ts
Normal file
18
front/src/pages/overview-state.test.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
|
||||
import { getOverviewLoadErrorMessage } from './overview-state';
|
||||
|
||||
test('post-login failures are presented as overview initialization issues', () => {
|
||||
assert.equal(
|
||||
getOverviewLoadErrorMessage(true),
|
||||
'登录已成功,但总览数据加载失败,请稍后重试。'
|
||||
);
|
||||
});
|
||||
|
||||
test('generic overview failures stay generic when not coming right after login', () => {
|
||||
assert.equal(
|
||||
getOverviewLoadErrorMessage(false),
|
||||
'总览数据加载失败,请稍后重试。'
|
||||
);
|
||||
});
|
||||
7
front/src/pages/overview-state.ts
Normal file
7
front/src/pages/overview-state.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export function getOverviewLoadErrorMessage(isPostLoginFailure: boolean) {
|
||||
if (isPostLoginFailure) {
|
||||
return '登录已成功,但总览数据加载失败,请稍后重试。';
|
||||
}
|
||||
|
||||
return '总览数据加载失败,请稍后重试。';
|
||||
}
|
||||
Reference in New Issue
Block a user