初始化
This commit is contained in:
23
client/.gitignore
vendored
Normal file
23
client/.gitignore
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
46
client/README.md
Normal file
46
client/README.md
Normal file
@@ -0,0 +1,46 @@
|
||||
# Getting Started with Create React App
|
||||
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||
|
||||
## Available Scripts
|
||||
|
||||
In the project directory, you can run:
|
||||
|
||||
### `npm start`
|
||||
|
||||
Runs the app in the development mode.\
|
||||
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
|
||||
|
||||
The page will reload if you make edits.\
|
||||
You will also see any lint errors in the console.
|
||||
|
||||
### `npm test`
|
||||
|
||||
Launches the test runner in the interactive watch mode.\
|
||||
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
||||
|
||||
### `npm run build`
|
||||
|
||||
Builds the app for production to the `build` folder.\
|
||||
It correctly bundles React in production mode and optimizes the build for the best performance.
|
||||
|
||||
The build is minified and the filenames include the hashes.\
|
||||
Your app is ready to be deployed!
|
||||
|
||||
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
||||
|
||||
### `npm run eject`
|
||||
|
||||
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
|
||||
|
||||
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
|
||||
|
||||
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
|
||||
|
||||
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
|
||||
|
||||
## Learn More
|
||||
|
||||
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
||||
|
||||
To learn React, check out the [React documentation](https://reactjs.org/).
|
||||
56
client/package.json
Normal file
56
client/package.json
Normal file
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"name": "client",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@testing-library/dom": "^10.4.0",
|
||||
"@testing-library/jest-dom": "^6.6.3",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@testing-library/user-event": "^13.5.0",
|
||||
"@types/bcryptjs": "^3.0.0",
|
||||
"@types/jest": "^27.5.2",
|
||||
"@types/jsonwebtoken": "^9.0.9",
|
||||
"@types/node": "^16.18.126",
|
||||
"@types/react": "^19.1.8",
|
||||
"@types/react-dom": "^19.1.6",
|
||||
"@types/react-router-dom": "^5.3.3",
|
||||
"axios": "^1.9.0",
|
||||
"bcryptjs": "^3.0.2",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"react-router-dom": "^7.6.2",
|
||||
"react-scripts": "5.0.1",
|
||||
"typescript": "^4.9.5",
|
||||
"web-vitals": "^2.1.4"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"eject": "react-scripts eject"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
},
|
||||
"devDependencies": {
|
||||
"autoprefixer": "^10.4.19",
|
||||
"postcss": "^8.4.38",
|
||||
"tailwindcss": "^3.3.3"
|
||||
}
|
||||
}
|
||||
6
client/postcss.config.js
Normal file
6
client/postcss.config.js
Normal file
@@ -0,0 +1,6 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
BIN
client/public/favicon.ico
Normal file
BIN
client/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
43
client/public/index.html
Normal file
43
client/public/index.html
Normal file
@@ -0,0 +1,43 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta
|
||||
name="description"
|
||||
content="Web site created using create-react-app"
|
||||
/>
|
||||
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
-->
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||
<!--
|
||||
Notice the use of %PUBLIC_URL% in the tags above.
|
||||
It will be replaced with the URL of the `public` folder during the build.
|
||||
Only files inside the `public` folder can be referenced from the HTML.
|
||||
|
||||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<title>React App</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
||||
BIN
client/public/logo192.png
Normal file
BIN
client/public/logo192.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 5.2 KiB |
BIN
client/public/logo512.png
Normal file
BIN
client/public/logo512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 9.4 KiB |
25
client/public/manifest.json
Normal file
25
client/public/manifest.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"short_name": "React App",
|
||||
"name": "Create React App Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
},
|
||||
{
|
||||
"src": "logo192.png",
|
||||
"type": "image/png",
|
||||
"sizes": "192x192"
|
||||
},
|
||||
{
|
||||
"src": "logo512.png",
|
||||
"type": "image/png",
|
||||
"sizes": "512x512"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff"
|
||||
}
|
||||
3
client/public/robots.txt
Normal file
3
client/public/robots.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
# https://www.robotstxt.org/robotstxt.html
|
||||
User-agent: *
|
||||
Disallow:
|
||||
38
client/src/App.css
Normal file
38
client/src/App.css
Normal file
@@ -0,0 +1,38 @@
|
||||
.App {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.App-logo {
|
||||
height: 40vmin;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.App-logo {
|
||||
animation: App-logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.App-header {
|
||||
background-color: #282c34;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: calc(10px + 2vmin);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.App-link {
|
||||
color: #61dafb;
|
||||
}
|
||||
|
||||
@keyframes App-logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
287
client/src/App.tsx
Normal file
287
client/src/App.tsx
Normal file
@@ -0,0 +1,287 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { BrowserRouter as Router, Routes, Route, Navigate, useNavigate } from 'react-router-dom';
|
||||
import { Todo, Priority, priorityColors, priorityLabels } from './types/todo';
|
||||
import * as todoApi from './api/todo';
|
||||
import Login from './pages/Login';
|
||||
import Register from './pages/Register';
|
||||
|
||||
// 弹窗组件
|
||||
const Modal: React.FC<{ open: boolean; onClose: () => void; onConfirm?: () => void; title: string; content: string; confirmText?: string; cancelText?: string; }> = ({ open, onClose, onConfirm, title, content, confirmText = '确定', cancelText = '取消' }) => {
|
||||
if (!open) return null;
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-30 px-2">
|
||||
<div className="bg-white rounded-lg sm:rounded-xl shadow-lg p-4 sm:p-6 w-full max-w-xs sm:max-w-sm">
|
||||
<h3 className="text-base sm:text-lg font-bold mb-2 text-gray-800">{title}</h3>
|
||||
<div className="mb-4 text-gray-600 text-sm sm:text-base">{content}</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<button className="px-3 sm:px-4 py-1.5 sm:py-1 rounded bg-gray-200 text-gray-700 hover:bg-gray-300 text-xs sm:text-sm" onClick={onClose}>{cancelText}</button>
|
||||
{onConfirm && <button className="px-3 sm:px-4 py-1.5 sm:py-1 rounded bg-blue-500 text-white hover:bg-blue-600 text-xs sm:text-sm" onClick={onConfirm}>{confirmText}</button>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// 随机头像颜色生成
|
||||
function stringToColor(str: string) {
|
||||
let hash = 0;
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
hash = str.charCodeAt(i) + ((hash << 5) - hash);
|
||||
}
|
||||
const color = `hsl(${hash % 360}, 70%, 60%)`;
|
||||
return color;
|
||||
}
|
||||
|
||||
// 状态栏组件
|
||||
const StatusBar: React.FC<{ username: string; avatarColor: string; avatarText: string; onLogout: () => void }> = ({ username, avatarColor, avatarText, onLogout }) => (
|
||||
<div className="fixed top-0 left-0 w-full h-14 sm:h-16 bg-white shadow flex items-center justify-end pr-4 sm:pr-8 z-50">
|
||||
<div className="flex items-center gap-2 sm:gap-3">
|
||||
<span
|
||||
className="w-9 h-9 sm:w-10 sm:h-10 rounded-full flex items-center justify-center font-bold text-white text-lg sm:text-xl shadow"
|
||||
style={{ background: avatarColor }}
|
||||
>
|
||||
{avatarText}
|
||||
</span>
|
||||
<span className="text-sm sm:text-base font-medium text-gray-700 mr-1 sm:mr-2">{username}</span>
|
||||
<button
|
||||
className="text-xs sm:text-sm text-gray-500 bg-gray-200 px-3 sm:px-4 py-1.5 sm:py-2 rounded hover:bg-gray-300 transition font-semibold"
|
||||
onClick={onLogout}
|
||||
>
|
||||
退出登录
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const TodoApp: React.FC = () => {
|
||||
const [todos, setTodos] = useState<Todo[]>([]);
|
||||
const [title, setTitle] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [editTitle, setEditTitle] = useState('');
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [modalAction, setModalAction] = useState<null | (() => void)>(null);
|
||||
const [modalContent, setModalContent] = useState('');
|
||||
const [modalTitle, setModalTitle] = useState('');
|
||||
const [editModalOpen, setEditModalOpen] = useState(false);
|
||||
const [editTodoId, setEditTodoId] = useState<string | null>(null);
|
||||
const [newTodoTitle, setNewTodoTitle] = useState('');
|
||||
const [newTodoPriority, setNewTodoPriority] = useState<Priority>('medium');
|
||||
const [editingTodo, setEditingTodo] = useState<Todo | null>(null);
|
||||
const [isLogoutModalOpen, setIsLogoutModalOpen] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
|
||||
// 获取所有 Todo
|
||||
const fetchTodos = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await todoApi.getTodos();
|
||||
setTodos(data);
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch todos:', error);
|
||||
if ((error as any)?.response?.status === 401) {
|
||||
navigate('/login');
|
||||
}
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchTodos();
|
||||
}, []);
|
||||
|
||||
// 新增 Todo
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!newTodoTitle.trim()) return;
|
||||
|
||||
try {
|
||||
const todo = await todoApi.createTodo(newTodoTitle.trim(), newTodoPriority);
|
||||
setTodos([...todos, todo]);
|
||||
setNewTodoTitle('');
|
||||
setNewTodoPriority('medium');
|
||||
} catch (error) {
|
||||
console.error('Failed to create todo:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 删除 Todo
|
||||
const handleDelete = async (id: string) => {
|
||||
if (!window.confirm('确定要删除吗?')) return;
|
||||
try {
|
||||
await todoApi.deleteTodo(id);
|
||||
setTodos(todos.filter(todo => todo._id !== id));
|
||||
} catch {
|
||||
alert('删除失败');
|
||||
}
|
||||
};
|
||||
|
||||
// 标记完成/未完成
|
||||
const handleToggle = async (todo: Todo) => {
|
||||
try {
|
||||
const updatedTodo = await todoApi.updateTodo(todo._id!, { completed: !todo.completed });
|
||||
setTodos(todos.map(t => t._id === todo._id ? updatedTodo : t));
|
||||
} catch {
|
||||
alert('更新失败');
|
||||
}
|
||||
};
|
||||
|
||||
// 开始编辑
|
||||
const handleEdit = (todo: Todo) => {
|
||||
setEditingId(todo._id!);
|
||||
setEditTitle(todo.title);
|
||||
setEditTodoId(todo._id!);
|
||||
setEditingTodo(todo);
|
||||
setEditModalOpen(true);
|
||||
};
|
||||
|
||||
// 保存编辑
|
||||
const handleEditSave = async (id: string) => {
|
||||
try {
|
||||
const updatedTodo = await todoApi.updateTodo(id, {
|
||||
title: editingTodo?.title || '',
|
||||
priority: editingTodo?.priority || 'medium'
|
||||
});
|
||||
setTodos(todos.map(t => t._id === id ? updatedTodo : t));
|
||||
setEditingTodo(null);
|
||||
setEditModalOpen(false);
|
||||
} catch (error) {
|
||||
console.error('Failed to update todo:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 取消编辑
|
||||
const handleEditCancel = () => {
|
||||
setEditingId(null);
|
||||
setEditModalOpen(false);
|
||||
setEditTodoId(null);
|
||||
};
|
||||
|
||||
// 退出登录
|
||||
const handleLogout = () => {
|
||||
setModalTitle('退出登录');
|
||||
setModalContent('确定要退出登录吗?');
|
||||
setModalAction(() => () => {
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('username');
|
||||
window.dispatchEvent(new Event('tokenChange'));
|
||||
navigate('/login');
|
||||
});
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const username = localStorage.getItem('username') || '';
|
||||
const avatarColor = stringToColor(username);
|
||||
const avatarText = username ? username[0].toUpperCase() : '?';
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-100 flex flex-col items-center py-4 sm:py-10 px-1 sm:px-2">
|
||||
{/* 状态栏 */}
|
||||
<StatusBar username={username} avatarColor={avatarColor} avatarText={avatarText} onLogout={handleLogout} />
|
||||
<Modal
|
||||
open={modalOpen}
|
||||
onClose={() => setModalOpen(false)}
|
||||
onConfirm={modalAction ? () => { setModalOpen(false); modalAction(); } : undefined}
|
||||
title={modalTitle}
|
||||
content={modalContent}
|
||||
/>
|
||||
{/* 编辑弹窗 */}
|
||||
{editModalOpen && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-30 px-2">
|
||||
<div className="bg-white rounded-lg sm:rounded-xl shadow-lg p-4 sm:p-8 w-full max-w-xs sm:max-w-md">
|
||||
<h3 className="text-base sm:text-xl font-bold mb-4 text-gray-800">编辑待办事项</h3>
|
||||
<div className="flex flex-col gap-2 sm:gap-3 mb-4">
|
||||
<input
|
||||
value={editTitle}
|
||||
onChange={e => setEditTitle(e.target.value)}
|
||||
className="border rounded px-2 sm:px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400 text-sm sm:text-base"
|
||||
placeholder="标题"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<button className="bg-green-500 text-white px-4 sm:px-5 py-2 rounded hover:bg-green-600 text-xs sm:text-base" onClick={() => handleEditSave(editTodoId!)}>保存</button>
|
||||
<button className="bg-gray-300 text-gray-700 px-4 sm:px-5 py-2 rounded hover:bg-gray-400 text-xs sm:text-base" onClick={handleEditCancel}>取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* 主内容整体下移,宽度自适应 */}
|
||||
<div className="w-full max-w-xs sm:max-w-2xl bg-white rounded-lg sm:rounded-xl shadow-lg p-3 sm:p-6 relative mt-16 sm:mt-24">
|
||||
<h2 className="text-2xl sm:text-3xl font-bold text-center mb-4 sm:mb-6 text-blue-600 tracking-tight">Todo List</h2>
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-2 sm:gap-3 mb-6 sm:mb-8">
|
||||
<div className="flex space-x-4">
|
||||
<input
|
||||
className="border rounded px-2 sm:px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400 text-sm sm:text-base"
|
||||
type="text"
|
||||
placeholder="标题"
|
||||
value={newTodoTitle}
|
||||
onChange={e => setNewTodoTitle(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<select
|
||||
value={newTodoPriority}
|
||||
onChange={(e) => setNewTodoPriority(e.target.value as Priority)}
|
||||
className="p-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400 text-sm sm:text-base"
|
||||
>
|
||||
{Object.entries(priorityLabels).map(([value, label]) => (
|
||||
<option key={value} value={value}>{label}优先级</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<button className="bg-blue-500 text-white py-2 rounded hover:bg-blue-600 transition text-sm sm:text-base" type="submit">添加</button>
|
||||
</form>
|
||||
{loading ? (
|
||||
<div className="text-center text-gray-500 text-sm sm:text-base">加载中...</div>
|
||||
) : (
|
||||
<ul className="space-y-2 sm:space-y-3">
|
||||
{todos.map(todo => (
|
||||
<li key={todo._id} className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 bg-gray-50 rounded-lg shadow p-2 sm:p-3">
|
||||
<div className="flex items-center gap-2 sm:gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={todo.completed}
|
||||
onChange={() => handleToggle(todo)}
|
||||
className="accent-blue-500 w-5 h-5"
|
||||
/>
|
||||
<span className={`flex-1 ${todo.completed ? 'line-through text-gray-400' : 'text-gray-900'} font-medium text-sm sm:text-base`}>{todo.title}</span>
|
||||
</div>
|
||||
<div className="flex gap-2 mt-1 sm:mt-0">
|
||||
<button className="bg-yellow-400 text-white px-2 sm:px-3 py-1 rounded hover:bg-yellow-500 text-xs sm:text-base" onClick={() => handleEdit(todo)}>编辑</button>
|
||||
<button className="bg-red-500 text-white px-2 sm:px-3 py-1 rounded hover:bg-red-600 text-xs sm:text-base" onClick={() => handleDelete(todo._id!)}>删除</button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const App: React.FC = () => {
|
||||
const [isLogin, setIsLogin] = useState(!!localStorage.getItem('token'));
|
||||
|
||||
useEffect(() => {
|
||||
const onStorage = () => setIsLogin(!!localStorage.getItem('token'));
|
||||
window.addEventListener('storage', onStorage);
|
||||
// 兼容同窗口内的 token 变化
|
||||
const onTokenChange = () => setIsLogin(!!localStorage.getItem('token'));
|
||||
window.addEventListener('tokenChange', onTokenChange);
|
||||
return () => {
|
||||
window.removeEventListener('storage', onStorage);
|
||||
window.removeEventListener('tokenChange', onTokenChange);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Router>
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/" element={isLogin ? <TodoApp /> : <Navigate to="/login" />} />
|
||||
</Routes>
|
||||
</Router>
|
||||
);
|
||||
};
|
||||
|
||||
export default App;
|
||||
13
client/src/api/auth.ts
Normal file
13
client/src/api/auth.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import axios from 'axios';
|
||||
|
||||
const API_URL = process.env.REACT_APP_API_URL || 'http://localhost:5050/api/auth';
|
||||
|
||||
export const register = async (username: string, password: string) => {
|
||||
const res = await axios.post(`${API_URL}/register`, { username, password });
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const login = async (username: string, password: string) => {
|
||||
const res = await axios.post(`${API_URL}/login`, { username, password });
|
||||
return res.data;
|
||||
};
|
||||
37
client/src/api/todo.ts
Normal file
37
client/src/api/todo.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import axios from 'axios';
|
||||
import { Todo, Priority } from '../types/todo';
|
||||
|
||||
const API_URL = 'http://localhost:5050/api';
|
||||
|
||||
// 获取 token 辅助函数
|
||||
function getAuthHeader() {
|
||||
const token = localStorage.getItem('token');
|
||||
return token ? { Authorization: `Bearer ${token}` } : {};
|
||||
}
|
||||
|
||||
export const getTodos = async (): Promise<Todo[]> => {
|
||||
const res = await axios.get<Todo[]>(`${API_URL}/todos`, { headers: getAuthHeader() });
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const createTodo = async (title: string, priority: Priority): Promise<Todo> => {
|
||||
const res = await axios.post(
|
||||
`${API_URL}/todos`,
|
||||
{ title, priority },
|
||||
{ headers: getAuthHeader() }
|
||||
);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const updateTodo = async (id: string, updates: Partial<Todo>): Promise<Todo> => {
|
||||
const res = await axios.put(
|
||||
`${API_URL}/todos/${id}`,
|
||||
updates,
|
||||
{ headers: getAuthHeader() }
|
||||
);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const deleteTodo = async (id: string): Promise<void> => {
|
||||
await axios.delete(`${API_URL}/todos/${id}`, { headers: getAuthHeader() });
|
||||
};
|
||||
3
client/src/index.css
Normal file
3
client/src/index.css
Normal file
@@ -0,0 +1,3 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
13
client/src/index.tsx
Normal file
13
client/src/index.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import './index.css';
|
||||
import App from './App';
|
||||
|
||||
const root = ReactDOM.createRoot(
|
||||
document.getElementById('root') as HTMLElement
|
||||
);
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
);
|
||||
64
client/src/pages/Login.tsx
Normal file
64
client/src/pages/Login.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { login } from '../api/auth';
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
|
||||
const Login: React.FC = () => {
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const navigate = useNavigate();
|
||||
const [isLogin, setIsLogin] = useState(!!localStorage.getItem('token'));
|
||||
|
||||
useEffect(() => {
|
||||
const onStorage = () => setIsLogin(!!localStorage.getItem('token'));
|
||||
window.addEventListener('storage', onStorage);
|
||||
return () => window.removeEventListener('storage', onStorage);
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
try {
|
||||
const res = await login(username, password);
|
||||
localStorage.setItem('token', res.token);
|
||||
localStorage.setItem('username', res.username);
|
||||
window.dispatchEvent(new Event('tokenChange'));
|
||||
navigate('/');
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.message || '登录失败');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-100 flex flex-col items-center justify-center py-4 sm:py-10 px-1 sm:px-2">
|
||||
<div className="w-full max-w-xs sm:max-w-md bg-white rounded-lg sm:rounded-xl shadow-lg p-4 sm:p-8">
|
||||
<h2 className="text-2xl sm:text-3xl font-bold text-center mb-4 sm:mb-6 text-blue-600 tracking-tight">登录</h2>
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-2 sm:gap-4 mb-2">
|
||||
<input
|
||||
className="border rounded px-2 sm:px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400 text-sm sm:text-base"
|
||||
type="text"
|
||||
placeholder="用户名"
|
||||
value={username}
|
||||
onChange={e => setUsername(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<input
|
||||
className="border rounded px-2 sm:px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400 text-sm sm:text-base"
|
||||
type="password"
|
||||
placeholder="密码"
|
||||
value={password}
|
||||
onChange={e => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
{error && <div className="text-red-500 text-xs sm:text-sm text-center">{error}</div>}
|
||||
<button className="bg-blue-500 text-white py-2 rounded hover:bg-blue-600 transition text-sm sm:text-base" type="submit">登录</button>
|
||||
</form>
|
||||
<div className="text-xs sm:text-sm text-center mt-3 sm:mt-4">
|
||||
没有账号?<Link to="/register" className="text-blue-500 hover:underline">注册</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Login;
|
||||
58
client/src/pages/Register.tsx
Normal file
58
client/src/pages/Register.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
import React, { useState } from 'react';
|
||||
import { register } from '../api/auth';
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
|
||||
const Register: React.FC = () => {
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [success, setSuccess] = useState('');
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setSuccess('');
|
||||
try {
|
||||
await register(username, password);
|
||||
setSuccess('注册成功,请登录');
|
||||
setTimeout(() => navigate('/login'), 1000);
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.message || '注册失败');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-100 flex flex-col items-center justify-center py-4 sm:py-10 px-1 sm:px-2">
|
||||
<div className="w-full max-w-xs sm:max-w-md bg-white rounded-lg sm:rounded-xl shadow-lg p-4 sm:p-8">
|
||||
<h2 className="text-2xl sm:text-3xl font-bold text-center mb-4 sm:mb-6 text-blue-600 tracking-tight">注册</h2>
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-2 sm:gap-4 mb-2">
|
||||
<input
|
||||
className="border rounded px-2 sm:px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400 text-sm sm:text-base"
|
||||
type="text"
|
||||
placeholder="用户名"
|
||||
value={username}
|
||||
onChange={e => setUsername(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<input
|
||||
className="border rounded px-2 sm:px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400 text-sm sm:text-base"
|
||||
type="password"
|
||||
placeholder="密码"
|
||||
value={password}
|
||||
onChange={e => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
{error && <div className="text-red-500 text-xs sm:text-sm text-center">{error}</div>}
|
||||
{success && <div className="text-green-500 text-xs sm:text-sm text-center">{success}</div>}
|
||||
<button className="bg-blue-500 text-white py-2 rounded hover:bg-blue-600 transition text-sm sm:text-base" type="submit">注册</button>
|
||||
</form>
|
||||
<div className="text-xs sm:text-sm text-center mt-3 sm:mt-4">
|
||||
已有账号?<Link to="/login" className="text-blue-500 hover:underline">登录</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Register;
|
||||
1
client/src/react-app-env.d.ts
vendored
Normal file
1
client/src/react-app-env.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/// <reference types="react-scripts" />
|
||||
23
client/src/types/todo.ts
Normal file
23
client/src/types/todo.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
export type Priority = 'low' | 'medium' | 'high';
|
||||
|
||||
export interface Todo {
|
||||
_id: string;
|
||||
title: string;
|
||||
completed: boolean;
|
||||
priority: Priority;
|
||||
userId: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export const priorityColors = {
|
||||
low: 'bg-blue-100 text-blue-800',
|
||||
medium: 'bg-yellow-100 text-yellow-800',
|
||||
high: 'bg-red-100 text-red-800'
|
||||
} as const;
|
||||
|
||||
export const priorityLabels = {
|
||||
low: '低',
|
||||
medium: '中',
|
||||
high: '高'
|
||||
} as const;
|
||||
9
client/tailwind.config.js
Normal file
9
client/tailwind.config.js
Normal file
@@ -0,0 +1,9 @@
|
||||
module.exports = {
|
||||
content: [
|
||||
"./src/**/*.{js,jsx,ts,tsx}",
|
||||
],
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
||||
26
client/tsconfig.json
Normal file
26
client/tsconfig.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user