完善
19
client-temp/.gitignore
vendored
@ -1,19 +0,0 @@
|
||||
# dependencies
|
||||
node_modules/
|
||||
|
||||
# production
|
||||
/dist
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env*
|
||||
|
||||
# logs
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# editor
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
@ -1,54 +0,0 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
|
||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||
|
||||
```js
|
||||
export default tseslint.config({
|
||||
extends: [
|
||||
// Remove ...tseslint.configs.recommended and replace with this
|
||||
...tseslint.configs.recommendedTypeChecked,
|
||||
// Alternatively, use this for stricter rules
|
||||
...tseslint.configs.strictTypeChecked,
|
||||
// Optionally, add this for stylistic rules
|
||||
...tseslint.configs.stylisticTypeChecked,
|
||||
],
|
||||
languageOptions: {
|
||||
// other options...
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import reactX from 'eslint-plugin-react-x'
|
||||
import reactDom from 'eslint-plugin-react-dom'
|
||||
|
||||
export default tseslint.config({
|
||||
plugins: {
|
||||
// Add the react-x and react-dom plugins
|
||||
'react-x': reactX,
|
||||
'react-dom': reactDom,
|
||||
},
|
||||
rules: {
|
||||
// other rules...
|
||||
// Enable its recommended typescript rules
|
||||
...reactX.configs['recommended-typescript'].rules,
|
||||
...reactDom.configs.recommended.rules,
|
||||
},
|
||||
})
|
||||
```
|
||||
@ -1,41 +0,0 @@
|
||||
{
|
||||
"name": "client-temp",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"build:dev": "tsc -b && vite build --mode development",
|
||||
"build:prod": "tsc -b && vite build --mode production",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/icons": "^6.0.0",
|
||||
"@types/react-router-dom": "^5.3.3",
|
||||
"antd": "^5.26.1",
|
||||
"axios": "^1.10.0",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"react-router-dom": "^7.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.25.0",
|
||||
"@types/react": "^19.1.2",
|
||||
"@types/react-dom": "^19.1.2",
|
||||
"@vitejs/plugin-react-swc": "^3.9.0",
|
||||
"autoprefixer": "^10.4.17",
|
||||
"eslint": "^9.25.0",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.19",
|
||||
"globals": "^16.0.0",
|
||||
"postcss": "^8.4.35",
|
||||
"tailwindcss": "^3.4.1",
|
||||
"typescript": "~5.8.3",
|
||||
"typescript-eslint": "^8.30.1",
|
||||
"unplugin-auto-import": "^19.3.0",
|
||||
"unplugin-auto-import-antd": "0.0.2",
|
||||
"vite": "^6.3.5"
|
||||
}
|
||||
}
|
||||
@ -1,6 +0,0 @@
|
||||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
@ -1,88 +0,0 @@
|
||||
import { Layout } from 'antd';
|
||||
import type { Priority, Todo } from './types/todo';
|
||||
import TodoModalForm from './components/TodoModalForm';
|
||||
import TodoHeader from './components/TodoHeader';
|
||||
import TodoListContent from './components/TodoListContent';
|
||||
import { getPriorityTagColor, getPriorityIcon, priorityLabels } from './utils/priorityUtils';
|
||||
import { useTodos } from './hooks/useTodos';
|
||||
import { Typography, Input, Button, Space } from 'antd';
|
||||
|
||||
const { Content } = Layout;
|
||||
const { Text } = Typography;
|
||||
const { Search } = Input;
|
||||
|
||||
function App() {
|
||||
const {
|
||||
todos,
|
||||
isModalOpen,
|
||||
currentTodo,
|
||||
modalTitle,
|
||||
isEditing,
|
||||
activeTab,
|
||||
searchTerm,
|
||||
setSearchTerm,
|
||||
openAddModal,
|
||||
closeModal,
|
||||
handleEditClick,
|
||||
handleModalSubmit,
|
||||
handleToggle,
|
||||
handleDelete,
|
||||
handleTabChange,
|
||||
filteredTodos,
|
||||
} = useTodos();
|
||||
|
||||
return (
|
||||
<Layout style={{ minHeight: '100vh' }}>
|
||||
<TodoHeader />
|
||||
<Content style={{ padding: '24px', margin: '0 auto',width: '90%', }}>
|
||||
{/* Title */}
|
||||
<div style={{ width: '100%', margin: '0 auto' }}>
|
||||
{/* Search and button */}
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0 0px 24px 0px' }}>
|
||||
<Search
|
||||
placeholder="搜索待办事项..."
|
||||
allowClear
|
||||
onSearch={setSearchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
style={{ width: 300 }}
|
||||
/>
|
||||
<Button type="primary" onClick={openAddModal}>
|
||||
新增待办事项
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TodoListContent
|
||||
todos={todos}
|
||||
handleEditClick={handleEditClick}
|
||||
handleToggle={handleToggle}
|
||||
handleDelete={handleDelete}
|
||||
getPriorityTagColor={getPriorityTagColor}
|
||||
getPriorityIcon={getPriorityIcon}
|
||||
priorityLabels={priorityLabels}
|
||||
activeTab={activeTab}
|
||||
handleTabChange={handleTabChange}
|
||||
filteredTodos={filteredTodos}
|
||||
/>
|
||||
|
||||
{isModalOpen && (
|
||||
<TodoModalForm
|
||||
isVisible={isModalOpen}
|
||||
title={modalTitle}
|
||||
initialValues={{
|
||||
title: currentTodo?.title || '',
|
||||
description: currentTodo?.description || '',
|
||||
priority: currentTodo?.priority || 'medium',
|
||||
completed: currentTodo?.completed || false,
|
||||
}}
|
||||
onCancel={closeModal}
|
||||
onSubmit={handleModalSubmit}
|
||||
isEditing={isEditing}
|
||||
/>
|
||||
)}
|
||||
</Content>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
@ -1,13 +0,0 @@
|
||||
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;
|
||||
};
|
||||
@ -1,26 +0,0 @@
|
||||
import type { Todo } from '../types/todo';
|
||||
import { api } from './axios';
|
||||
|
||||
export const getTodos = async (): Promise<Todo[]> => {
|
||||
const response = await api.get('/todos');
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const addTodo = async (title: string, description: string, priority: Todo['priority']): Promise<Todo> => {
|
||||
const response = await api.post('/todos', { title, description, priority });
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const updateTodo = async (_id: string, title: string, description: string, priority: Todo['priority'], completed: boolean): Promise<Todo> => {
|
||||
const response = await api.put(`/todos/${_id}`, { title, description, priority, completed });
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const toggleTodo = async (_id: string): Promise<Todo> => {
|
||||
const response = await api.patch(`/todos/${_id}/toggle`);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const deleteTodo = async (_id: string): Promise<void> => {
|
||||
await api.delete(`/todos/${_id}`);
|
||||
};
|
||||
@ -1,9 +0,0 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@layer base {
|
||||
body {
|
||||
@apply bg-gray-50;
|
||||
}
|
||||
}
|
||||
@ -1,117 +0,0 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Form, Input, Button, Card, Space, Typography, Alert, Checkbox, Divider } from 'antd';
|
||||
import { UserOutlined, LockOutlined, CheckSquareOutlined } from '@ant-design/icons';
|
||||
import { api } from '../api/axios';
|
||||
|
||||
const { Title, Text, Link } = Typography;
|
||||
|
||||
function Login() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const onFinish = async (values: any) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await api.post('/auth/login', {
|
||||
username: values.username,
|
||||
password: values.password,
|
||||
});
|
||||
localStorage.setItem('token', response.data.token);
|
||||
localStorage.setItem('username', values.username);
|
||||
navigate('/');
|
||||
} catch (err: any) {
|
||||
const errorMessage = err.response?.data?.message || '登录失败,请检查用户名或密码。';
|
||||
setError(errorMessage);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen bg-gray-100" style={{ background: '#f0f2f5',height: '100vh',display: 'flex',alignItems: 'center',justifyContent: 'center' }}>
|
||||
<Card
|
||||
className="w-full max-w-sm"
|
||||
variant="borderless"
|
||||
style={{
|
||||
boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
|
||||
padding: '40px 24px 24px',
|
||||
textAlign: 'center',
|
||||
width: '500px',
|
||||
margin: '0 auto 200px',
|
||||
}}
|
||||
>
|
||||
<Space direction="vertical" size="large" style={{ width: '100%' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: 24 }}>
|
||||
<CheckSquareOutlined style={{ fontSize: '48px', color: '#1890ff' }} />
|
||||
<Title level={2} style={{ margin: '8px 0 0' }}>Todo List</Title>
|
||||
<Text type="secondary">轻松管理您的任务</Text>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Alert
|
||||
message="账户或密码错误"
|
||||
description={error}
|
||||
type="error"
|
||||
showIcon
|
||||
closable
|
||||
onClose={() => setError(null)}
|
||||
style={{ marginBottom: 24 }}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Form
|
||||
name="login"
|
||||
initialValues={{ remember: true }}
|
||||
onFinish={onFinish}
|
||||
autoComplete="off"
|
||||
layout="vertical"
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
<Form.Item
|
||||
name="username"
|
||||
rules={[{ required: true, message: '请输入用户名!' }]}
|
||||
>
|
||||
<Input
|
||||
prefix={<UserOutlined className="site-form-item-icon" />}
|
||||
placeholder="账户"
|
||||
size="large"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="password"
|
||||
rules={[{ required: true, message: '请输入密码!' }]}
|
||||
>
|
||||
<Input.Password
|
||||
prefix={<LockOutlined className="site-form-item-icon" />}
|
||||
placeholder="密码"
|
||||
size="large"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<Checkbox>自动登录</Checkbox>
|
||||
<Space>
|
||||
<Link href="/forgot-password">忘记密码</Link>
|
||||
<Link href="/register">注册新账号</Link>
|
||||
</Space>
|
||||
</div>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item>
|
||||
<Button type="primary" htmlType="submit" className="w-full" size="large" loading={loading} style={{width: '100%',}}>
|
||||
登录
|
||||
</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Space>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Login;
|
||||
@ -1,131 +0,0 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Form, Input, Button, Card, Space, Typography, Alert } from 'antd';
|
||||
import { UserOutlined, LockOutlined, CheckSquareOutlined } from '@ant-design/icons';
|
||||
import { api } from '../api/axios';
|
||||
|
||||
const { Title, Text, Link } = Typography;
|
||||
|
||||
function Register() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const onFinish = async (values: any) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.post('/auth/register', {
|
||||
username: values.username,
|
||||
password: values.password,
|
||||
});
|
||||
navigate('/login');
|
||||
} catch (err: any) {
|
||||
const errorMessage = err.response?.data?.message || '注册失败,用户名可能已被占用或服务器错误。';
|
||||
setError(errorMessage);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen bg-gray-100" style={{ background: '#f0f2f5',height: '100vh',display: 'flex',alignItems: 'center',justifyContent: 'center' }}>
|
||||
<Card
|
||||
className="w-full max-w-sm"
|
||||
variant="borderless"
|
||||
style={{
|
||||
boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
|
||||
padding: '40px 24px 24px',
|
||||
textAlign: 'center',
|
||||
width: '500px',
|
||||
margin: '0 auto 200px',
|
||||
}}
|
||||
>
|
||||
<Space direction="vertical" size="large" style={{ width: '100%' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: 24 }}>
|
||||
<CheckSquareOutlined style={{ fontSize: '48px', color: '#1890ff' }} />
|
||||
<Title level={2} style={{ margin: '8px 0 0' }}>Todo List</Title>
|
||||
<Text type="secondary">轻松管理您的任务</Text>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Alert
|
||||
message="注册失败"
|
||||
description={error}
|
||||
type="error"
|
||||
showIcon
|
||||
closable
|
||||
onClose={() => setError(null)}
|
||||
style={{ marginBottom: 24 }}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Form
|
||||
name="register"
|
||||
initialValues={{ remember: true }}
|
||||
onFinish={onFinish}
|
||||
autoComplete="off"
|
||||
layout="vertical"
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
<Form.Item
|
||||
name="username"
|
||||
rules={[{ required: true, message: '请输入用户名!' }]}
|
||||
>
|
||||
<Input
|
||||
prefix={<UserOutlined className="site-form-item-icon" />}
|
||||
placeholder="用户名"
|
||||
size="large"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="password"
|
||||
rules={[{ required: true, message: '请输入密码!' }]}
|
||||
>
|
||||
<Input.Password
|
||||
prefix={<LockOutlined className="site-form-item-icon" />}
|
||||
placeholder="密码"
|
||||
size="large"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="confirm"
|
||||
dependencies={['password']}
|
||||
hasFeedback
|
||||
rules={[
|
||||
{ required: true, message: '请确认您的密码!' },
|
||||
({ getFieldValue }) => ({
|
||||
validator(_, value) {
|
||||
if (!value || getFieldValue('password') === value) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
return Promise.reject(new Error('两次输入的密码不一致!'));
|
||||
},
|
||||
}),
|
||||
]}
|
||||
>
|
||||
<Input.Password
|
||||
prefix={<LockOutlined className="site-form-item-icon" />}
|
||||
placeholder="确认密码"
|
||||
size="large"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item>
|
||||
<Button type="primary" htmlType="submit" className="w-full" size="large" style={{width: '100%',}} loading={loading}>
|
||||
注册
|
||||
</Button>
|
||||
</Form.Item>
|
||||
<div style={{ textAlign: 'right' }}>
|
||||
<Link href="/login">已有账号?去登录</Link>
|
||||
</div>
|
||||
</Form>
|
||||
</Space>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Register;
|
||||
@ -1,21 +0,0 @@
|
||||
export type Priority = 'low' | 'medium' | 'high';
|
||||
|
||||
export interface Todo {
|
||||
_id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
completed: boolean;
|
||||
priority: Priority;
|
||||
}
|
||||
|
||||
export const priorityColors: Record<Priority, string> = {
|
||||
low: 'green',
|
||||
medium: 'orange',
|
||||
high: 'red',
|
||||
};
|
||||
|
||||
export const priorityLabels = {
|
||||
low: '低',
|
||||
medium: '中',
|
||||
high: '高'
|
||||
} as const;
|
||||
@ -1,12 +0,0 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
export default {
|
||||
content: [
|
||||
"./index.html",
|
||||
"./src/**/*.{js,ts,jsx,tsx}",
|
||||
],
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
||||
|
||||
@ -1,7 +0,0 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
22
client/.gitignore
vendored
@ -1,23 +1,19 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
node_modules/
|
||||
|
||||
# production
|
||||
/build
|
||||
/dist
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env*
|
||||
|
||||
# logs
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# editor
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
|
||||
@ -1,46 +1,54 @@
|
||||
# Getting Started with Create React App
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
|
||||
## Available Scripts
|
||||
Currently, two official plugins are available:
|
||||
|
||||
In the project directory, you can run:
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||
|
||||
### `npm start`
|
||||
## Expanding the ESLint configuration
|
||||
|
||||
Runs the app in the development mode.\
|
||||
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
|
||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||
|
||||
The page will reload if you make edits.\
|
||||
You will also see any lint errors in the console.
|
||||
```js
|
||||
export default tseslint.config({
|
||||
extends: [
|
||||
// Remove ...tseslint.configs.recommended and replace with this
|
||||
...tseslint.configs.recommendedTypeChecked,
|
||||
// Alternatively, use this for stricter rules
|
||||
...tseslint.configs.strictTypeChecked,
|
||||
// Optionally, add this for stylistic rules
|
||||
...tseslint.configs.stylisticTypeChecked,
|
||||
],
|
||||
languageOptions: {
|
||||
// other options...
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### `npm test`
|
||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||
|
||||
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.
|
||||
```js
|
||||
// eslint.config.js
|
||||
import reactX from 'eslint-plugin-react-x'
|
||||
import reactDom from 'eslint-plugin-react-dom'
|
||||
|
||||
### `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/).
|
||||
export default tseslint.config({
|
||||
plugins: {
|
||||
// Add the react-x and react-dom plugins
|
||||
'react-x': reactX,
|
||||
'react-dom': reactDom,
|
||||
},
|
||||
rules: {
|
||||
// other rules...
|
||||
// Enable its recommended typescript rules
|
||||
...reactX.configs['recommended-typescript'].rules,
|
||||
...reactDom.configs.recommended.rules,
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
@ -1,56 +1,41 @@
|
||||
{
|
||||
"name": "client",
|
||||
"version": "0.1.0",
|
||||
"name": "client-temp",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"build:dev": "tsc -b && vite build --mode development",
|
||||
"build:prod": "tsc -b && vite build --mode production",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"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",
|
||||
"@ant-design/icons": "^6.0.0",
|
||||
"@types/react-router-dom": "^5.3.3",
|
||||
"axios": "^1.9.0",
|
||||
"bcryptjs": "^3.0.2",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"antd": "^5.26.1",
|
||||
"axios": "^1.10.0",
|
||||
"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"
|
||||
]
|
||||
"react-router-dom": "^7.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"autoprefixer": "^10.4.19",
|
||||
"postcss": "^8.4.38",
|
||||
"tailwindcss": "^3.3.3"
|
||||
"@eslint/js": "^9.25.0",
|
||||
"@types/react": "^19.1.2",
|
||||
"@types/react-dom": "^19.1.2",
|
||||
"@vitejs/plugin-react-swc": "^3.9.0",
|
||||
"autoprefixer": "^10.4.17",
|
||||
"eslint": "^9.25.0",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.19",
|
||||
"globals": "^16.0.0",
|
||||
"postcss": "^8.4.35",
|
||||
"tailwindcss": "^3.4.1",
|
||||
"typescript": "~5.8.3",
|
||||
"typescript-eslint": "^8.30.1",
|
||||
"unplugin-auto-import": "^19.3.0",
|
||||
"unplugin-auto-import-antd": "0.0.2",
|
||||
"vite": "^6.3.5"
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
module.exports = {
|
||||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
|
||||
|
Before Width: | Height: | Size: 3.8 KiB |
@ -1,43 +0,0 @@
|
||||
<!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>
|
||||
|
Before Width: | Height: | Size: 5.2 KiB |
|
Before Width: | Height: | Size: 9.4 KiB |
@ -1,25 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@ -1,3 +0,0 @@
|
||||
# https://www.robotstxt.org/robotstxt.html
|
||||
User-agent: *
|
||||
Disallow:
|
||||
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
@ -1,38 +0,0 @@
|
||||
.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);
|
||||
}
|
||||
}
|
||||
@ -1,287 +1,88 @@
|
||||
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';
|
||||
import { Layout } from 'antd';
|
||||
import type { Priority, Todo } from './types/todo';
|
||||
import TodoModalForm from './components/TodoModalForm';
|
||||
import TodoHeader from './components/TodoHeader';
|
||||
import TodoListContent from './components/TodoListContent';
|
||||
import { getPriorityTagColor, getPriorityIcon, priorityLabels } from './utils/priorityUtils';
|
||||
import { useTodos } from './hooks/useTodos';
|
||||
import { Typography, Input, Button, Space } from 'antd';
|
||||
|
||||
// 弹窗组件
|
||||
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>
|
||||
);
|
||||
};
|
||||
const { Content } = Layout;
|
||||
const { Text } = Typography;
|
||||
const { Search } = Input;
|
||||
|
||||
// 随机头像颜色生成
|
||||
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() : '?';
|
||||
function App() {
|
||||
const {
|
||||
todos,
|
||||
isModalOpen,
|
||||
currentTodo,
|
||||
modalTitle,
|
||||
isEditing,
|
||||
activeTab,
|
||||
searchTerm,
|
||||
setSearchTerm,
|
||||
openAddModal,
|
||||
closeModal,
|
||||
handleEditClick,
|
||||
handleModalSubmit,
|
||||
handleToggle,
|
||||
handleDelete,
|
||||
handleTabChange,
|
||||
filteredTodos,
|
||||
} = useTodos();
|
||||
|
||||
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}
|
||||
<Layout style={{ minHeight: '100vh' }}>
|
||||
<TodoHeader />
|
||||
<Content style={{ padding: '24px', margin: '0 auto',width: '90%', }}>
|
||||
{/* Title */}
|
||||
<div style={{ width: '100%', margin: '0 auto' }}>
|
||||
{/* Search and button */}
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0 0px 24px 0px' }}>
|
||||
<Search
|
||||
placeholder="搜索待办事项..."
|
||||
allowClear
|
||||
onSearch={setSearchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
style={{ width: 300 }}
|
||||
/>
|
||||
<Button type="primary" onClick={openAddModal}>
|
||||
新增待办事项
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TodoListContent
|
||||
todos={todos}
|
||||
handleEditClick={handleEditClick}
|
||||
handleToggle={handleToggle}
|
||||
handleDelete={handleDelete}
|
||||
getPriorityTagColor={getPriorityTagColor}
|
||||
getPriorityIcon={getPriorityIcon}
|
||||
priorityLabels={priorityLabels}
|
||||
activeTab={activeTab}
|
||||
handleTabChange={handleTabChange}
|
||||
filteredTodos={filteredTodos}
|
||||
/>
|
||||
|
||||
{isModalOpen && (
|
||||
<TodoModalForm
|
||||
isVisible={isModalOpen}
|
||||
title={modalTitle}
|
||||
content={modalContent}
|
||||
initialValues={{
|
||||
title: currentTodo?.title || '',
|
||||
description: currentTodo?.description || '',
|
||||
priority: currentTodo?.priority || 'medium',
|
||||
completed: currentTodo?.completed || false,
|
||||
}}
|
||||
onCancel={closeModal}
|
||||
onSubmit={handleModalSubmit}
|
||||
isEditing={isEditing}
|
||||
/>
|
||||
{/* 编辑弹窗 */}
|
||||
{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>
|
||||
</Content>
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
|
||||
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;
|
||||
@ -1,37 +1,26 @@
|
||||
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}` } : {};
|
||||
}
|
||||
import type { Todo } from '../types/todo';
|
||||
import { api } from './axios';
|
||||
|
||||
export const getTodos = async (): Promise<Todo[]> => {
|
||||
const res = await axios.get<Todo[]>(`${API_URL}/todos`, { headers: getAuthHeader() });
|
||||
return res.data;
|
||||
const response = await api.get('/todos');
|
||||
return response.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 addTodo = async (title: string, description: string, priority: Todo['priority']): Promise<Todo> => {
|
||||
const response = await api.post('/todos', { title, description, priority });
|
||||
return response.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 updateTodo = async (_id: string, title: string, description: string, priority: Todo['priority'], completed: boolean): Promise<Todo> => {
|
||||
const response = await api.put(`/todos/${_id}`, { title, description, priority, completed });
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const deleteTodo = async (id: string): Promise<void> => {
|
||||
await axios.delete(`${API_URL}/todos/${id}`, { headers: getAuthHeader() });
|
||||
export const toggleTodo = async (_id: string): Promise<Todo> => {
|
||||
const response = await api.patch(`/todos/${_id}/toggle`);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const deleteTodo = async (_id: string): Promise<void> => {
|
||||
await api.delete(`/todos/${_id}`);
|
||||
};
|
||||
|
Before Width: | Height: | Size: 4.0 KiB After Width: | Height: | Size: 4.0 KiB |
@ -1,3 +1,9 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@layer base {
|
||||
body {
|
||||
@apply bg-gray-50;
|
||||
}
|
||||
}
|
||||
@ -1,13 +0,0 @@
|
||||
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>
|
||||
);
|
||||
@ -1,64 +1,117 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { login } from '../api/auth';
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import React, { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Form, Input, Button, Card, Space, Typography, Alert, Checkbox, Divider } from 'antd';
|
||||
import { UserOutlined, LockOutlined, CheckSquareOutlined } from '@ant-design/icons';
|
||||
import { api } from '../api/axios';
|
||||
|
||||
const Login: React.FC = () => {
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const { Title, Text, Link } = Typography;
|
||||
|
||||
function Login() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
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('');
|
||||
const onFinish = async (values: any) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await login(username, password);
|
||||
localStorage.setItem('token', res.token);
|
||||
localStorage.setItem('username', res.username);
|
||||
window.dispatchEvent(new Event('tokenChange'));
|
||||
const response = await api.post('/auth/login', {
|
||||
username: values.username,
|
||||
password: values.password,
|
||||
});
|
||||
localStorage.setItem('token', response.data.token);
|
||||
localStorage.setItem('username', values.username);
|
||||
navigate('/');
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.message || '登录失败');
|
||||
const errorMessage = err.response?.data?.message || '登录失败,请检查用户名或密码。';
|
||||
setError(errorMessage);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
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
|
||||
<div className="flex items-center justify-center min-h-screen bg-gray-100" style={{ background: '#f0f2f5',height: '100vh',display: 'flex',alignItems: 'center',justifyContent: 'center' }}>
|
||||
<Card
|
||||
className="w-full max-w-sm"
|
||||
variant="borderless"
|
||||
style={{
|
||||
boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
|
||||
padding: '40px 24px 24px',
|
||||
textAlign: 'center',
|
||||
width: '500px',
|
||||
margin: '0 auto 200px',
|
||||
}}
|
||||
>
|
||||
<Space direction="vertical" size="large" style={{ width: '100%' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: 24 }}>
|
||||
<CheckSquareOutlined style={{ fontSize: '48px', color: '#1890ff' }} />
|
||||
<Title level={2} style={{ margin: '8px 0 0' }}>Todo List</Title>
|
||||
<Text type="secondary">轻松管理您的任务</Text>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Alert
|
||||
message="账户或密码错误"
|
||||
description={error}
|
||||
type="error"
|
||||
showIcon
|
||||
closable
|
||||
onClose={() => setError(null)}
|
||||
style={{ marginBottom: 24 }}
|
||||
/>
|
||||
<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"
|
||||
)}
|
||||
|
||||
<Form
|
||||
name="login"
|
||||
initialValues={{ remember: true }}
|
||||
onFinish={onFinish}
|
||||
autoComplete="off"
|
||||
layout="vertical"
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
<Form.Item
|
||||
name="username"
|
||||
rules={[{ required: true, message: '请输入用户名!' }]}
|
||||
>
|
||||
<Input
|
||||
prefix={<UserOutlined className="site-form-item-icon" />}
|
||||
placeholder="账户"
|
||||
size="large"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="password"
|
||||
rules={[{ required: true, message: '请输入密码!' }]}
|
||||
>
|
||||
<Input.Password
|
||||
prefix={<LockOutlined className="site-form-item-icon" />}
|
||||
placeholder="密码"
|
||||
value={password}
|
||||
onChange={e => setPassword(e.target.value)}
|
||||
required
|
||||
size="large"
|
||||
/>
|
||||
{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>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<Checkbox>自动登录</Checkbox>
|
||||
<Space>
|
||||
<Link href="/forgot-password">忘记密码</Link>
|
||||
<Link href="/register">注册新账号</Link>
|
||||
</Space>
|
||||
</div>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item>
|
||||
<Button type="primary" htmlType="submit" className="w-full" size="large" loading={loading} style={{width: '100%',}}>
|
||||
登录
|
||||
</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Space>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
export default Login;
|
||||
@ -1,58 +1,131 @@
|
||||
import React, { useState } from 'react';
|
||||
import { register } from '../api/auth';
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Form, Input, Button, Card, Space, Typography, Alert } from 'antd';
|
||||
import { UserOutlined, LockOutlined, CheckSquareOutlined } from '@ant-design/icons';
|
||||
import { api } from '../api/axios';
|
||||
|
||||
const Register: React.FC = () => {
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [success, setSuccess] = useState('');
|
||||
const { Title, Text, Link } = Typography;
|
||||
|
||||
function Register() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setSuccess('');
|
||||
const onFinish = async (values: any) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
await register(username, password);
|
||||
setSuccess('注册成功,请登录');
|
||||
setTimeout(() => navigate('/login'), 1000);
|
||||
await api.post('/auth/register', {
|
||||
username: values.username,
|
||||
password: values.password,
|
||||
});
|
||||
navigate('/login');
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.message || '注册失败');
|
||||
const errorMessage = err.response?.data?.message || '注册失败,用户名可能已被占用或服务器错误。';
|
||||
setError(errorMessage);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
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"
|
||||
<div className="flex items-center justify-center min-h-screen bg-gray-100" style={{ background: '#f0f2f5',height: '100vh',display: 'flex',alignItems: 'center',justifyContent: 'center' }}>
|
||||
<Card
|
||||
className="w-full max-w-sm"
|
||||
variant="borderless"
|
||||
style={{
|
||||
boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
|
||||
padding: '40px 24px 24px',
|
||||
textAlign: 'center',
|
||||
width: '500px',
|
||||
margin: '0 auto 200px',
|
||||
}}
|
||||
>
|
||||
<Space direction="vertical" size="large" style={{ width: '100%' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: 24 }}>
|
||||
<CheckSquareOutlined style={{ fontSize: '48px', color: '#1890ff' }} />
|
||||
<Title level={2} style={{ margin: '8px 0 0' }}>Todo List</Title>
|
||||
<Text type="secondary">轻松管理您的任务</Text>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Alert
|
||||
message="注册失败"
|
||||
description={error}
|
||||
type="error"
|
||||
showIcon
|
||||
closable
|
||||
onClose={() => setError(null)}
|
||||
style={{ marginBottom: 24 }}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Form
|
||||
name="register"
|
||||
initialValues={{ remember: true }}
|
||||
onFinish={onFinish}
|
||||
autoComplete="off"
|
||||
layout="vertical"
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
<Form.Item
|
||||
name="username"
|
||||
rules={[{ required: true, message: '请输入用户名!' }]}
|
||||
>
|
||||
<Input
|
||||
prefix={<UserOutlined className="site-form-item-icon" />}
|
||||
placeholder="用户名"
|
||||
value={username}
|
||||
onChange={e => setUsername(e.target.value)}
|
||||
required
|
||||
size="large"
|
||||
/>
|
||||
<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"
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="password"
|
||||
rules={[{ required: true, message: '请输入密码!' }]}
|
||||
>
|
||||
<Input.Password
|
||||
prefix={<LockOutlined className="site-form-item-icon" />}
|
||||
placeholder="密码"
|
||||
value={password}
|
||||
onChange={e => setPassword(e.target.value)}
|
||||
required
|
||||
size="large"
|
||||
/>
|
||||
{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>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="confirm"
|
||||
dependencies={['password']}
|
||||
hasFeedback
|
||||
rules={[
|
||||
{ required: true, message: '请确认您的密码!' },
|
||||
({ getFieldValue }) => ({
|
||||
validator(_, value) {
|
||||
if (!value || getFieldValue('password') === value) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
return Promise.reject(new Error('两次输入的密码不一致!'));
|
||||
},
|
||||
}),
|
||||
]}
|
||||
>
|
||||
<Input.Password
|
||||
prefix={<LockOutlined className="site-form-item-icon" />}
|
||||
placeholder="确认密码"
|
||||
size="large"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item>
|
||||
<Button type="primary" htmlType="submit" className="w-full" size="large" style={{width: '100%',}} loading={loading}>
|
||||
注册
|
||||
</Button>
|
||||
</Form.Item>
|
||||
<div style={{ textAlign: 'right' }}>
|
||||
<Link href="/login">已有账号?去登录</Link>
|
||||
</div>
|
||||
</Form>
|
||||
</Space>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
export default Register;
|
||||
1
client/src/react-app-env.d.ts
vendored
@ -1 +0,0 @@
|
||||
/// <reference types="react-scripts" />
|
||||
@ -3,18 +3,16 @@ export type Priority = 'low' | 'medium' | 'high';
|
||||
export interface Todo {
|
||||
_id: string;
|
||||
title: string;
|
||||
description: 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 priorityColors: Record<Priority, string> = {
|
||||
low: 'green',
|
||||
medium: 'orange',
|
||||
high: 'red',
|
||||
};
|
||||
|
||||
export const priorityLabels = {
|
||||
low: '低',
|
||||
|
||||
@ -1,9 +1,12 @@
|
||||
module.exports = {
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
export default {
|
||||
content: [
|
||||
"./src/**/*.{js,jsx,ts,tsx}",
|
||||
"./index.html",
|
||||
"./src/**/*.{js,ts,jsx,tsx}",
|
||||
],
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
||||
|
||||
|
||||
@ -1,26 +1,7 @@
|
||||
{
|
||||
"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"
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
|
||||